nervoscan-js-sdk 1.0.1 → 1.0.2-0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,1599 @@
1
- "use strict";var st=Object.defineProperty;var ot=(t,e,r)=>e in t?st(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var I=(t,e,r)=>ot(t,typeof e!="symbol"?e+"":e,r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function De(t,e){return function(){return t.apply(e,arguments)}}const{toString:it}=Object.prototype,{getPrototypeOf:ye}=Object,te=(t=>e=>{const r=it.call(e);return t[r]||(t[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),P=t=>(t=t.toLowerCase(),e=>te(e)===t),re=t=>e=>typeof e===t,{isArray:H}=Array,K=re("undefined");function at(t){return t!==null&&!K(t)&&t.constructor!==null&&!K(t.constructor)&&x(t.constructor.isBuffer)&&t.constructor.isBuffer(t)}const Le=P("ArrayBuffer");function ct(t){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(t):e=t&&t.buffer&&Le(t.buffer),e}const lt=re("string"),x=re("function"),Be=re("number"),ne=t=>t!==null&&typeof t=="object",ut=t=>t===!0||t===!1,G=t=>{if(te(t)!=="object")return!1;const e=ye(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in t)&&!(Symbol.iterator in t)},ft=P("Date"),dt=P("File"),pt=P("Blob"),ht=P("FileList"),mt=t=>ne(t)&&x(t.pipe),wt=t=>{let e;return t&&(typeof FormData=="function"&&t instanceof FormData||x(t.append)&&((e=te(t))==="formdata"||e==="object"&&x(t.toString)&&t.toString()==="[object FormData]"))},yt=P("URLSearchParams"),[Et,bt,St,gt]=["ReadableStream","Request","Response","Headers"].map(P),Rt=t=>t.trim?t.trim():t.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function J(t,e,{allOwnKeys:r=!1}={}){if(t===null||typeof t>"u")return;let n,s;if(typeof t!="object"&&(t=[t]),H(t))for(n=0,s=t.length;n<s;n++)e.call(null,t[n],n,t);else{const o=r?Object.getOwnPropertyNames(t):Object.keys(t),i=o.length;let c;for(n=0;n<i;n++)c=o[n],e.call(null,t[c],c,t)}}function Ie(t,e){e=e.toLowerCase();const r=Object.keys(t);let n=r.length,s;for(;n-- >0;)if(s=r[n],e===s.toLowerCase())return s;return null}const q=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,je=t=>!K(t)&&t!==q;function ue(){const{caseless:t}=je(this)&&this||{},e={},r=(n,s)=>{const o=t&&Ie(e,s)||s;G(e[o])&&G(n)?e[o]=ue(e[o],n):G(n)?e[o]=ue({},n):H(n)?e[o]=n.slice():e[o]=n};for(let n=0,s=arguments.length;n<s;n++)arguments[n]&&J(arguments[n],r);return e}const Tt=(t,e,r,{allOwnKeys:n}={})=>(J(e,(s,o)=>{r&&x(s)?t[o]=De(s,r):t[o]=s},{allOwnKeys:n}),t),At=t=>(t.charCodeAt(0)===65279&&(t=t.slice(1)),t),Ot=(t,e,r,n)=>{t.prototype=Object.create(e.prototype,n),t.prototype.constructor=t,Object.defineProperty(t,"super",{value:e.prototype}),r&&Object.assign(t.prototype,r)},Nt=(t,e,r,n)=>{let s,o,i;const c={};if(e=e||{},t==null)return e;do{for(s=Object.getOwnPropertyNames(t),o=s.length;o-- >0;)i=s[o],(!n||n(i,t,e))&&!c[i]&&(e[i]=t[i],c[i]=!0);t=r!==!1&&ye(t)}while(t&&(!r||r(t,e))&&t!==Object.prototype);return e},xt=(t,e,r)=>{t=String(t),(r===void 0||r>t.length)&&(r=t.length),r-=e.length;const n=t.indexOf(e,r);return n!==-1&&n===r},Ct=t=>{if(!t)return null;if(H(t))return t;let e=t.length;if(!Be(e))return null;const r=new Array(e);for(;e-- >0;)r[e]=t[e];return r},Pt=(t=>e=>t&&e instanceof t)(typeof Uint8Array<"u"&&ye(Uint8Array)),kt=(t,e)=>{const n=(t&&t[Symbol.iterator]).call(t);let s;for(;(s=n.next())&&!s.done;){const o=s.value;e.call(t,o[0],o[1])}},Ft=(t,e)=>{let r;const n=[];for(;(r=t.exec(e))!==null;)n.push(r);return n},Ut=P("HTMLFormElement"),_t=t=>t.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,n,s){return n.toUpperCase()+s}),ge=(({hasOwnProperty:t})=>(e,r)=>t.call(e,r))(Object.prototype),Dt=P("RegExp"),qe=(t,e)=>{const r=Object.getOwnPropertyDescriptors(t),n={};J(r,(s,o)=>{let i;(i=e(s,o,t))!==!1&&(n[o]=i||s)}),Object.defineProperties(t,n)},Lt=t=>{qe(t,(e,r)=>{if(x(t)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;const n=t[r];if(x(n)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")})}})},Bt=(t,e)=>{const r={},n=s=>{s.forEach(o=>{r[o]=!0})};return H(t)?n(t):n(String(t).split(e)),r},It=()=>{},jt=(t,e)=>t!=null&&Number.isFinite(t=+t)?t:e;function qt(t){return!!(t&&x(t.append)&&t[Symbol.toStringTag]==="FormData"&&t[Symbol.iterator])}const zt=t=>{const e=new Array(10),r=(n,s)=>{if(ne(n)){if(e.indexOf(n)>=0)return;if(!("toJSON"in n)){e[s]=n;const o=H(n)?[]:{};return J(n,(i,c)=>{const f=r(i,s+1);!K(f)&&(o[c]=f)}),e[s]=void 0,o}}return n};return r(t,0)},Mt=P("AsyncFunction"),Ht=t=>t&&(ne(t)||x(t))&&x(t.then)&&x(t.catch),ze=((t,e)=>t?setImmediate:e?((r,n)=>(q.addEventListener("message",({source:s,data:o})=>{s===q&&o===r&&n.length&&n.shift()()},!1),s=>{n.push(s),q.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",x(q.postMessage)),vt=typeof queueMicrotask<"u"?queueMicrotask.bind(q):typeof process<"u"&&process.nextTick||ze,a={isArray:H,isArrayBuffer:Le,isBuffer:at,isFormData:wt,isArrayBufferView:ct,isString:lt,isNumber:Be,isBoolean:ut,isObject:ne,isPlainObject:G,isReadableStream:Et,isRequest:bt,isResponse:St,isHeaders:gt,isUndefined:K,isDate:ft,isFile:dt,isBlob:pt,isRegExp:Dt,isFunction:x,isStream:mt,isURLSearchParams:yt,isTypedArray:Pt,isFileList:ht,forEach:J,merge:ue,extend:Tt,trim:Rt,stripBOM:At,inherits:Ot,toFlatObject:Nt,kindOf:te,kindOfTest:P,endsWith:xt,toArray:Ct,forEachEntry:kt,matchAll:Ft,isHTMLForm:Ut,hasOwnProperty:ge,hasOwnProp:ge,reduceDescriptors:qe,freezeMethods:Lt,toObjectSet:Bt,toCamelCase:_t,noop:It,toFiniteNumber:jt,findKey:Ie,global:q,isContextDefined:je,isSpecCompliantForm:qt,toJSONObject:zt,isAsyncFn:Mt,isThenable:Ht,setImmediate:ze,asap:vt};function m(t,e,r,n,s){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=t,this.name="AxiosError",e&&(this.code=e),r&&(this.config=r),n&&(this.request=n),s&&(this.response=s,this.status=s.status?s.status:null)}a.inherits(m,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:a.toJSONObject(this.config),code:this.code,status:this.status}}});const Me=m.prototype,He={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(t=>{He[t]={value:t}});Object.defineProperties(m,He);Object.defineProperty(Me,"isAxiosError",{value:!0});m.from=(t,e,r,n,s,o)=>{const i=Object.create(Me);return a.toFlatObject(t,i,function(f){return f!==Error.prototype},c=>c!=="isAxiosError"),m.call(i,t.message,e,r,n,s),i.cause=t,i.name=t.name,o&&Object.assign(i,o),i};const Vt=null;function fe(t){return a.isPlainObject(t)||a.isArray(t)}function ve(t){return a.endsWith(t,"[]")?t.slice(0,-2):t}function Re(t,e,r){return t?t.concat(e).map(function(s,o){return s=ve(s),!r&&o?"["+s+"]":s}).join(r?".":""):e}function $t(t){return a.isArray(t)&&!t.some(fe)}const Kt=a.toFlatObject(a,{},null,function(e){return/^is[A-Z]/.test(e)});function se(t,e,r){if(!a.isObject(t))throw new TypeError("target must be an object");e=e||new FormData,r=a.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(w,h){return!a.isUndefined(h[w])});const n=r.metaTokens,s=r.visitor||u,o=r.dots,i=r.indexes,f=(r.Blob||typeof Blob<"u"&&Blob)&&a.isSpecCompliantForm(e);if(!a.isFunction(s))throw new TypeError("visitor must be a function");function l(p){if(p===null)return"";if(a.isDate(p))return p.toISOString();if(!f&&a.isBlob(p))throw new m("Blob is not supported. Use a Buffer instead.");return a.isArrayBuffer(p)||a.isTypedArray(p)?f&&typeof Blob=="function"?new Blob([p]):Buffer.from(p):p}function u(p,w,h){let b=p;if(p&&!h&&typeof p=="object"){if(a.endsWith(w,"{}"))w=n?w:w.slice(0,-2),p=JSON.stringify(p);else if(a.isArray(p)&&$t(p)||(a.isFileList(p)||a.endsWith(w,"[]"))&&(b=a.toArray(p)))return w=ve(w),b.forEach(function(R,U){!(a.isUndefined(R)||R===null)&&e.append(i===!0?Re([w],U,o):i===null?w:w+"[]",l(R))}),!1}return fe(p)?!0:(e.append(Re(h,w,o),l(p)),!1)}const d=[],y=Object.assign(Kt,{defaultVisitor:u,convertValue:l,isVisitable:fe});function S(p,w){if(!a.isUndefined(p)){if(d.indexOf(p)!==-1)throw Error("Circular reference detected in "+w.join("."));d.push(p),a.forEach(p,function(b,g){(!(a.isUndefined(b)||b===null)&&s.call(e,b,a.isString(g)?g.trim():g,w,y))===!0&&S(b,w?w.concat(g):[g])}),d.pop()}}if(!a.isObject(t))throw new TypeError("data must be an object");return S(t),e}function Te(t){const e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(t).replace(/[!'()~]|%20|%00/g,function(n){return e[n]})}function Ee(t,e){this._pairs=[],t&&se(t,this,e)}const Ve=Ee.prototype;Ve.append=function(e,r){this._pairs.push([e,r])};Ve.toString=function(e){const r=e?function(n){return e.call(this,n,Te)}:Te;return this._pairs.map(function(s){return r(s[0])+"="+r(s[1])},"").join("&")};function Jt(t){return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function $e(t,e,r){if(!e)return t;const n=r&&r.encode||Jt;a.isFunction(r)&&(r={serialize:r});const s=r&&r.serialize;let o;if(s?o=s(e,r):o=a.isURLSearchParams(e)?e.toString():new Ee(e,r).toString(n),o){const i=t.indexOf("#");i!==-1&&(t=t.slice(0,i)),t+=(t.indexOf("?")===-1?"?":"&")+o}return t}class Ae{constructor(){this.handlers=[]}use(e,r,n){return this.handlers.push({fulfilled:e,rejected:r,synchronous:n?n.synchronous:!1,runWhen:n?n.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){a.forEach(this.handlers,function(n){n!==null&&e(n)})}}const Ke={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Wt=typeof URLSearchParams<"u"?URLSearchParams:Ee,Xt=typeof FormData<"u"?FormData:null,Gt=typeof Blob<"u"?Blob:null,Qt={isBrowser:!0,classes:{URLSearchParams:Wt,FormData:Xt,Blob:Gt},protocols:["http","https","file","blob","url","data"]},be=typeof window<"u"&&typeof document<"u",de=typeof navigator=="object"&&navigator||void 0,Zt=be&&(!de||["ReactNative","NativeScript","NS"].indexOf(de.product)<0),Yt=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",er=be&&window.location.href||"http://localhost",tr=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:be,hasStandardBrowserEnv:Zt,hasStandardBrowserWebWorkerEnv:Yt,navigator:de,origin:er},Symbol.toStringTag,{value:"Module"})),T={...tr,...Qt};function rr(t,e){return se(t,new T.classes.URLSearchParams,Object.assign({visitor:function(r,n,s,o){return T.isNode&&a.isBuffer(r)?(this.append(n,r.toString("base64")),!1):o.defaultVisitor.apply(this,arguments)}},e))}function nr(t){return a.matchAll(/\w+|\[(\w*)]/g,t).map(e=>e[0]==="[]"?"":e[1]||e[0])}function sr(t){const e={},r=Object.keys(t);let n;const s=r.length;let o;for(n=0;n<s;n++)o=r[n],e[o]=t[o];return e}function Je(t){function e(r,n,s,o){let i=r[o++];if(i==="__proto__")return!0;const c=Number.isFinite(+i),f=o>=r.length;return i=!i&&a.isArray(s)?s.length:i,f?(a.hasOwnProp(s,i)?s[i]=[s[i],n]:s[i]=n,!c):((!s[i]||!a.isObject(s[i]))&&(s[i]=[]),e(r,n,s[i],o)&&a.isArray(s[i])&&(s[i]=sr(s[i])),!c)}if(a.isFormData(t)&&a.isFunction(t.entries)){const r={};return a.forEachEntry(t,(n,s)=>{e(nr(n),s,r,0)}),r}return null}function or(t,e,r){if(a.isString(t))try{return(e||JSON.parse)(t),a.trim(t)}catch(n){if(n.name!=="SyntaxError")throw n}return(r||JSON.stringify)(t)}const W={transitional:Ke,adapter:["xhr","http","fetch"],transformRequest:[function(e,r){const n=r.getContentType()||"",s=n.indexOf("application/json")>-1,o=a.isObject(e);if(o&&a.isHTMLForm(e)&&(e=new FormData(e)),a.isFormData(e))return s?JSON.stringify(Je(e)):e;if(a.isArrayBuffer(e)||a.isBuffer(e)||a.isStream(e)||a.isFile(e)||a.isBlob(e)||a.isReadableStream(e))return e;if(a.isArrayBufferView(e))return e.buffer;if(a.isURLSearchParams(e))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let c;if(o){if(n.indexOf("application/x-www-form-urlencoded")>-1)return rr(e,this.formSerializer).toString();if((c=a.isFileList(e))||n.indexOf("multipart/form-data")>-1){const f=this.env&&this.env.FormData;return se(c?{"files[]":e}:e,f&&new f,this.formSerializer)}}return o||s?(r.setContentType("application/json",!1),or(e)):e}],transformResponse:[function(e){const r=this.transitional||W.transitional,n=r&&r.forcedJSONParsing,s=this.responseType==="json";if(a.isResponse(e)||a.isReadableStream(e))return e;if(e&&a.isString(e)&&(n&&!this.responseType||s)){const i=!(r&&r.silentJSONParsing)&&s;try{return JSON.parse(e)}catch(c){if(i)throw c.name==="SyntaxError"?m.from(c,m.ERR_BAD_RESPONSE,this,null,this.response):c}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:T.classes.FormData,Blob:T.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};a.forEach(["delete","get","head","post","put","patch"],t=>{W.headers[t]={}});const ir=a.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),ar=t=>{const e={};let r,n,s;return t&&t.split(`
2
- `).forEach(function(i){s=i.indexOf(":"),r=i.substring(0,s).trim().toLowerCase(),n=i.substring(s+1).trim(),!(!r||e[r]&&ir[r])&&(r==="set-cookie"?e[r]?e[r].push(n):e[r]=[n]:e[r]=e[r]?e[r]+", "+n:n)}),e},Oe=Symbol("internals");function V(t){return t&&String(t).trim().toLowerCase()}function Q(t){return t===!1||t==null?t:a.isArray(t)?t.map(Q):String(t)}function cr(t){const e=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let n;for(;n=r.exec(t);)e[n[1]]=n[2];return e}const lr=t=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(t.trim());function ae(t,e,r,n,s){if(a.isFunction(n))return n.call(this,e,r);if(s&&(e=r),!!a.isString(e)){if(a.isString(n))return e.indexOf(n)!==-1;if(a.isRegExp(n))return n.test(e)}}function ur(t){return t.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,r,n)=>r.toUpperCase()+n)}function fr(t,e){const r=a.toCamelCase(" "+e);["get","set","has"].forEach(n=>{Object.defineProperty(t,n+r,{value:function(s,o,i){return this[n].call(this,e,s,o,i)},configurable:!0})})}let N=class{constructor(e){e&&this.set(e)}set(e,r,n){const s=this;function o(c,f,l){const u=V(f);if(!u)throw new Error("header name must be a non-empty string");const d=a.findKey(s,u);(!d||s[d]===void 0||l===!0||l===void 0&&s[d]!==!1)&&(s[d||f]=Q(c))}const i=(c,f)=>a.forEach(c,(l,u)=>o(l,u,f));if(a.isPlainObject(e)||e instanceof this.constructor)i(e,r);else if(a.isString(e)&&(e=e.trim())&&!lr(e))i(ar(e),r);else if(a.isHeaders(e))for(const[c,f]of e.entries())o(f,c,n);else e!=null&&o(r,e,n);return this}get(e,r){if(e=V(e),e){const n=a.findKey(this,e);if(n){const s=this[n];if(!r)return s;if(r===!0)return cr(s);if(a.isFunction(r))return r.call(this,s,n);if(a.isRegExp(r))return r.exec(s);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,r){if(e=V(e),e){const n=a.findKey(this,e);return!!(n&&this[n]!==void 0&&(!r||ae(this,this[n],n,r)))}return!1}delete(e,r){const n=this;let s=!1;function o(i){if(i=V(i),i){const c=a.findKey(n,i);c&&(!r||ae(n,n[c],c,r))&&(delete n[c],s=!0)}}return a.isArray(e)?e.forEach(o):o(e),s}clear(e){const r=Object.keys(this);let n=r.length,s=!1;for(;n--;){const o=r[n];(!e||ae(this,this[o],o,e,!0))&&(delete this[o],s=!0)}return s}normalize(e){const r=this,n={};return a.forEach(this,(s,o)=>{const i=a.findKey(n,o);if(i){r[i]=Q(s),delete r[o];return}const c=e?ur(o):String(o).trim();c!==o&&delete r[o],r[c]=Q(s),n[c]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const r=Object.create(null);return a.forEach(this,(n,s)=>{n!=null&&n!==!1&&(r[s]=e&&a.isArray(n)?n.join(", "):n)}),r}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,r])=>e+": "+r).join(`
3
- `)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...r){const n=new this(e);return r.forEach(s=>n.set(s)),n}static accessor(e){const n=(this[Oe]=this[Oe]={accessors:{}}).accessors,s=this.prototype;function o(i){const c=V(i);n[c]||(fr(s,i),n[c]=!0)}return a.isArray(e)?e.forEach(o):o(e),this}};N.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);a.reduceDescriptors(N.prototype,({value:t},e)=>{let r=e[0].toUpperCase()+e.slice(1);return{get:()=>t,set(n){this[r]=n}}});a.freezeMethods(N);function ce(t,e){const r=this||W,n=e||r,s=N.from(n.headers);let o=n.data;return a.forEach(t,function(c){o=c.call(r,o,s.normalize(),e?e.status:void 0)}),s.normalize(),o}function We(t){return!!(t&&t.__CANCEL__)}function v(t,e,r){m.call(this,t??"canceled",m.ERR_CANCELED,e,r),this.name="CanceledError"}a.inherits(v,m,{__CANCEL__:!0});function Xe(t,e,r){const n=r.config.validateStatus;!r.status||!n||n(r.status)?t(r):e(new m("Request failed with status code "+r.status,[m.ERR_BAD_REQUEST,m.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}function dr(t){const e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(t);return e&&e[1]||""}function pr(t,e){t=t||10;const r=new Array(t),n=new Array(t);let s=0,o=0,i;return e=e!==void 0?e:1e3,function(f){const l=Date.now(),u=n[o];i||(i=l),r[s]=f,n[s]=l;let d=o,y=0;for(;d!==s;)y+=r[d++],d=d%t;if(s=(s+1)%t,s===o&&(o=(o+1)%t),l-i<e)return;const S=u&&l-u;return S?Math.round(y*1e3/S):void 0}}function hr(t,e){let r=0,n=1e3/e,s,o;const i=(l,u=Date.now())=>{r=u,s=null,o&&(clearTimeout(o),o=null),t.apply(null,l)};return[(...l)=>{const u=Date.now(),d=u-r;d>=n?i(l,u):(s=l,o||(o=setTimeout(()=>{o=null,i(s)},n-d)))},()=>s&&i(s)]}const Y=(t,e,r=3)=>{let n=0;const s=pr(50,250);return hr(o=>{const i=o.loaded,c=o.lengthComputable?o.total:void 0,f=i-n,l=s(f),u=i<=c;n=i;const d={loaded:i,total:c,progress:c?i/c:void 0,bytes:f,rate:l||void 0,estimated:l&&c&&u?(c-i)/l:void 0,event:o,lengthComputable:c!=null,[e?"download":"upload"]:!0};t(d)},r)},Ne=(t,e)=>{const r=t!=null;return[n=>e[0]({lengthComputable:r,total:t,loaded:n}),e[1]]},xe=t=>(...e)=>a.asap(()=>t(...e)),mr=T.hasStandardBrowserEnv?((t,e)=>r=>(r=new URL(r,T.origin),t.protocol===r.protocol&&t.host===r.host&&(e||t.port===r.port)))(new URL(T.origin),T.navigator&&/(msie|trident)/i.test(T.navigator.userAgent)):()=>!0,wr=T.hasStandardBrowserEnv?{write(t,e,r,n,s,o){const i=[t+"="+encodeURIComponent(e)];a.isNumber(r)&&i.push("expires="+new Date(r).toGMTString()),a.isString(n)&&i.push("path="+n),a.isString(s)&&i.push("domain="+s),o===!0&&i.push("secure"),document.cookie=i.join("; ")},read(t){const e=document.cookie.match(new RegExp("(^|;\\s*)("+t+")=([^;]*)"));return e?decodeURIComponent(e[3]):null},remove(t){this.write(t,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function yr(t){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)}function Er(t,e){return e?t.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):t}function Ge(t,e,r){let n=!yr(e);return t&&(n||r==!1)?Er(t,e):e}const Ce=t=>t instanceof N?{...t}:t;function M(t,e){e=e||{};const r={};function n(l,u,d,y){return a.isPlainObject(l)&&a.isPlainObject(u)?a.merge.call({caseless:y},l,u):a.isPlainObject(u)?a.merge({},u):a.isArray(u)?u.slice():u}function s(l,u,d,y){if(a.isUndefined(u)){if(!a.isUndefined(l))return n(void 0,l,d,y)}else return n(l,u,d,y)}function o(l,u){if(!a.isUndefined(u))return n(void 0,u)}function i(l,u){if(a.isUndefined(u)){if(!a.isUndefined(l))return n(void 0,l)}else return n(void 0,u)}function c(l,u,d){if(d in e)return n(l,u);if(d in t)return n(void 0,l)}const f={url:o,method:o,data:o,baseURL:i,transformRequest:i,transformResponse:i,paramsSerializer:i,timeout:i,timeoutMessage:i,withCredentials:i,withXSRFToken:i,adapter:i,responseType:i,xsrfCookieName:i,xsrfHeaderName:i,onUploadProgress:i,onDownloadProgress:i,decompress:i,maxContentLength:i,maxBodyLength:i,beforeRedirect:i,transport:i,httpAgent:i,httpsAgent:i,cancelToken:i,socketPath:i,responseEncoding:i,validateStatus:c,headers:(l,u,d)=>s(Ce(l),Ce(u),d,!0)};return a.forEach(Object.keys(Object.assign({},t,e)),function(u){const d=f[u]||s,y=d(t[u],e[u],u);a.isUndefined(y)&&d!==c||(r[u]=y)}),r}const Qe=t=>{const e=M({},t);let{data:r,withXSRFToken:n,xsrfHeaderName:s,xsrfCookieName:o,headers:i,auth:c}=e;e.headers=i=N.from(i),e.url=$e(Ge(e.baseURL,e.url,e.allowAbsoluteUrls),t.params,t.paramsSerializer),c&&i.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):"")));let f;if(a.isFormData(r)){if(T.hasStandardBrowserEnv||T.hasStandardBrowserWebWorkerEnv)i.setContentType(void 0);else if((f=i.getContentType())!==!1){const[l,...u]=f?f.split(";").map(d=>d.trim()).filter(Boolean):[];i.setContentType([l||"multipart/form-data",...u].join("; "))}}if(T.hasStandardBrowserEnv&&(n&&a.isFunction(n)&&(n=n(e)),n||n!==!1&&mr(e.url))){const l=s&&o&&wr.read(o);l&&i.set(s,l)}return e},br=typeof XMLHttpRequest<"u",Sr=br&&function(t){return new Promise(function(r,n){const s=Qe(t);let o=s.data;const i=N.from(s.headers).normalize();let{responseType:c,onUploadProgress:f,onDownloadProgress:l}=s,u,d,y,S,p;function w(){S&&S(),p&&p(),s.cancelToken&&s.cancelToken.unsubscribe(u),s.signal&&s.signal.removeEventListener("abort",u)}let h=new XMLHttpRequest;h.open(s.method.toUpperCase(),s.url,!0),h.timeout=s.timeout;function b(){if(!h)return;const R=N.from("getAllResponseHeaders"in h&&h.getAllResponseHeaders()),A={data:!c||c==="text"||c==="json"?h.responseText:h.response,status:h.status,statusText:h.statusText,headers:R,config:t,request:h};Xe(function(B){r(B),w()},function(B){n(B),w()},A),h=null}"onloadend"in h?h.onloadend=b:h.onreadystatechange=function(){!h||h.readyState!==4||h.status===0&&!(h.responseURL&&h.responseURL.indexOf("file:")===0)||setTimeout(b)},h.onabort=function(){h&&(n(new m("Request aborted",m.ECONNABORTED,t,h)),h=null)},h.onerror=function(){n(new m("Network Error",m.ERR_NETWORK,t,h)),h=null},h.ontimeout=function(){let U=s.timeout?"timeout of "+s.timeout+"ms exceeded":"timeout exceeded";const A=s.transitional||Ke;s.timeoutErrorMessage&&(U=s.timeoutErrorMessage),n(new m(U,A.clarifyTimeoutError?m.ETIMEDOUT:m.ECONNABORTED,t,h)),h=null},o===void 0&&i.setContentType(null),"setRequestHeader"in h&&a.forEach(i.toJSON(),function(U,A){h.setRequestHeader(A,U)}),a.isUndefined(s.withCredentials)||(h.withCredentials=!!s.withCredentials),c&&c!=="json"&&(h.responseType=s.responseType),l&&([y,p]=Y(l,!0),h.addEventListener("progress",y)),f&&h.upload&&([d,S]=Y(f),h.upload.addEventListener("progress",d),h.upload.addEventListener("loadend",S)),(s.cancelToken||s.signal)&&(u=R=>{h&&(n(!R||R.type?new v(null,t,h):R),h.abort(),h=null)},s.cancelToken&&s.cancelToken.subscribe(u),s.signal&&(s.signal.aborted?u():s.signal.addEventListener("abort",u)));const g=dr(s.url);if(g&&T.protocols.indexOf(g)===-1){n(new m("Unsupported protocol "+g+":",m.ERR_BAD_REQUEST,t));return}h.send(o||null)})},gr=(t,e)=>{const{length:r}=t=t?t.filter(Boolean):[];if(e||r){let n=new AbortController,s;const o=function(l){if(!s){s=!0,c();const u=l instanceof Error?l:this.reason;n.abort(u instanceof m?u:new v(u instanceof Error?u.message:u))}};let i=e&&setTimeout(()=>{i=null,o(new m(`timeout ${e} of ms exceeded`,m.ETIMEDOUT))},e);const c=()=>{t&&(i&&clearTimeout(i),i=null,t.forEach(l=>{l.unsubscribe?l.unsubscribe(o):l.removeEventListener("abort",o)}),t=null)};t.forEach(l=>l.addEventListener("abort",o));const{signal:f}=n;return f.unsubscribe=()=>a.asap(c),f}},Rr=function*(t,e){let r=t.byteLength;if(r<e){yield t;return}let n=0,s;for(;n<r;)s=n+e,yield t.slice(n,s),n=s},Tr=async function*(t,e){for await(const r of Ar(t))yield*Rr(r,e)},Ar=async function*(t){if(t[Symbol.asyncIterator]){yield*t;return}const e=t.getReader();try{for(;;){const{done:r,value:n}=await e.read();if(r)break;yield n}}finally{await e.cancel()}},Pe=(t,e,r,n)=>{const s=Tr(t,e);let o=0,i,c=f=>{i||(i=!0,n&&n(f))};return new ReadableStream({async pull(f){try{const{done:l,value:u}=await s.next();if(l){c(),f.close();return}let d=u.byteLength;if(r){let y=o+=d;r(y)}f.enqueue(new Uint8Array(u))}catch(l){throw c(l),l}},cancel(f){return c(f),s.return()}},{highWaterMark:2})},oe=typeof fetch=="function"&&typeof Request=="function"&&typeof Response=="function",Ze=oe&&typeof ReadableStream=="function",Or=oe&&(typeof TextEncoder=="function"?(t=>e=>t.encode(e))(new TextEncoder):async t=>new Uint8Array(await new Response(t).arrayBuffer())),Ye=(t,...e)=>{try{return!!t(...e)}catch{return!1}},Nr=Ze&&Ye(()=>{let t=!1;const e=new Request(T.origin,{body:new ReadableStream,method:"POST",get duplex(){return t=!0,"half"}}).headers.has("Content-Type");return t&&!e}),ke=64*1024,pe=Ze&&Ye(()=>a.isReadableStream(new Response("").body)),ee={stream:pe&&(t=>t.body)};oe&&(t=>{["text","arrayBuffer","blob","formData","stream"].forEach(e=>{!ee[e]&&(ee[e]=a.isFunction(t[e])?r=>r[e]():(r,n)=>{throw new m(`Response type '${e}' is not supported`,m.ERR_NOT_SUPPORT,n)})})})(new Response);const xr=async t=>{if(t==null)return 0;if(a.isBlob(t))return t.size;if(a.isSpecCompliantForm(t))return(await new Request(T.origin,{method:"POST",body:t}).arrayBuffer()).byteLength;if(a.isArrayBufferView(t)||a.isArrayBuffer(t))return t.byteLength;if(a.isURLSearchParams(t)&&(t=t+""),a.isString(t))return(await Or(t)).byteLength},Cr=async(t,e)=>{const r=a.toFiniteNumber(t.getContentLength());return r??xr(e)},Pr=oe&&(async t=>{let{url:e,method:r,data:n,signal:s,cancelToken:o,timeout:i,onDownloadProgress:c,onUploadProgress:f,responseType:l,headers:u,withCredentials:d="same-origin",fetchOptions:y}=Qe(t);l=l?(l+"").toLowerCase():"text";let S=gr([s,o&&o.toAbortSignal()],i),p;const w=S&&S.unsubscribe&&(()=>{S.unsubscribe()});let h;try{if(f&&Nr&&r!=="get"&&r!=="head"&&(h=await Cr(u,n))!==0){let A=new Request(e,{method:"POST",body:n,duplex:"half"}),L;if(a.isFormData(n)&&(L=A.headers.get("content-type"))&&u.setContentType(L),A.body){const[B,X]=Ne(h,Y(xe(f)));n=Pe(A.body,ke,B,X)}}a.isString(d)||(d=d?"include":"omit");const b="credentials"in Request.prototype;p=new Request(e,{...y,signal:S,method:r.toUpperCase(),headers:u.normalize().toJSON(),body:n,duplex:"half",credentials:b?d:void 0});let g=await fetch(p);const R=pe&&(l==="stream"||l==="response");if(pe&&(c||R&&w)){const A={};["status","statusText","headers"].forEach(Se=>{A[Se]=g[Se]});const L=a.toFiniteNumber(g.headers.get("content-length")),[B,X]=c&&Ne(L,Y(xe(c),!0))||[];g=new Response(Pe(g.body,ke,B,()=>{X&&X(),w&&w()}),A)}l=l||"text";let U=await ee[a.findKey(ee,l)||"text"](g,t);return!R&&w&&w(),await new Promise((A,L)=>{Xe(A,L,{data:U,headers:N.from(g.headers),status:g.status,statusText:g.statusText,config:t,request:p})})}catch(b){throw w&&w(),b&&b.name==="TypeError"&&/fetch/i.test(b.message)?Object.assign(new m("Network Error",m.ERR_NETWORK,t,p),{cause:b.cause||b}):m.from(b,b&&b.code,t,p)}}),he={http:Vt,xhr:Sr,fetch:Pr};a.forEach(he,(t,e)=>{if(t){try{Object.defineProperty(t,"name",{value:e})}catch{}Object.defineProperty(t,"adapterName",{value:e})}});const Fe=t=>`- ${t}`,kr=t=>a.isFunction(t)||t===null||t===!1,et={getAdapter:t=>{t=a.isArray(t)?t:[t];const{length:e}=t;let r,n;const s={};for(let o=0;o<e;o++){r=t[o];let i;if(n=r,!kr(r)&&(n=he[(i=String(r)).toLowerCase()],n===void 0))throw new m(`Unknown adapter '${i}'`);if(n)break;s[i||"#"+o]=n}if(!n){const o=Object.entries(s).map(([c,f])=>`adapter ${c} `+(f===!1?"is not supported by the environment":"is not available in the build"));let i=e?o.length>1?`since :
4
- `+o.map(Fe).join(`
5
- `):" "+Fe(o[0]):"as no adapter specified";throw new m("There is no suitable adapter to dispatch the request "+i,"ERR_NOT_SUPPORT")}return n},adapters:he};function le(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new v(null,t)}function Ue(t){return le(t),t.headers=N.from(t.headers),t.data=ce.call(t,t.transformRequest),["post","put","patch"].indexOf(t.method)!==-1&&t.headers.setContentType("application/x-www-form-urlencoded",!1),et.getAdapter(t.adapter||W.adapter)(t).then(function(n){return le(t),n.data=ce.call(t,t.transformResponse,n),n.headers=N.from(n.headers),n},function(n){return We(n)||(le(t),n&&n.response&&(n.response.data=ce.call(t,t.transformResponse,n.response),n.response.headers=N.from(n.response.headers))),Promise.reject(n)})}const tt="1.8.4",ie={};["object","boolean","number","function","string","symbol"].forEach((t,e)=>{ie[t]=function(n){return typeof n===t||"a"+(e<1?"n ":" ")+t}});const _e={};ie.transitional=function(e,r,n){function s(o,i){return"[Axios v"+tt+"] Transitional option '"+o+"'"+i+(n?". "+n:"")}return(o,i,c)=>{if(e===!1)throw new m(s(i," has been removed"+(r?" in "+r:"")),m.ERR_DEPRECATED);return r&&!_e[i]&&(_e[i]=!0,console.warn(s(i," has been deprecated since v"+r+" and will be removed in the near future"))),e?e(o,i,c):!0}};ie.spelling=function(e){return(r,n)=>(console.warn(`${n} is likely a misspelling of ${e}`),!0)};function Fr(t,e,r){if(typeof t!="object")throw new m("options must be an object",m.ERR_BAD_OPTION_VALUE);const n=Object.keys(t);let s=n.length;for(;s-- >0;){const o=n[s],i=e[o];if(i){const c=t[o],f=c===void 0||i(c,o,t);if(f!==!0)throw new m("option "+o+" must be "+f,m.ERR_BAD_OPTION_VALUE);continue}if(r!==!0)throw new m("Unknown option "+o,m.ERR_BAD_OPTION)}}const Z={assertOptions:Fr,validators:ie},k=Z.validators;let z=class{constructor(e){this.defaults=e,this.interceptors={request:new Ae,response:new Ae}}async request(e,r){try{return await this._request(e,r)}catch(n){if(n instanceof Error){let s={};Error.captureStackTrace?Error.captureStackTrace(s):s=new Error;const o=s.stack?s.stack.replace(/^.+\n/,""):"";try{n.stack?o&&!String(n.stack).endsWith(o.replace(/^.+\n.+\n/,""))&&(n.stack+=`
6
- `+o):n.stack=o}catch{}}throw n}}_request(e,r){typeof e=="string"?(r=r||{},r.url=e):r=e||{},r=M(this.defaults,r);const{transitional:n,paramsSerializer:s,headers:o}=r;n!==void 0&&Z.assertOptions(n,{silentJSONParsing:k.transitional(k.boolean),forcedJSONParsing:k.transitional(k.boolean),clarifyTimeoutError:k.transitional(k.boolean)},!1),s!=null&&(a.isFunction(s)?r.paramsSerializer={serialize:s}:Z.assertOptions(s,{encode:k.function,serialize:k.function},!0)),r.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?r.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:r.allowAbsoluteUrls=!0),Z.assertOptions(r,{baseUrl:k.spelling("baseURL"),withXsrfToken:k.spelling("withXSRFToken")},!0),r.method=(r.method||this.defaults.method||"get").toLowerCase();let i=o&&a.merge(o.common,o[r.method]);o&&a.forEach(["delete","get","head","post","put","patch","common"],p=>{delete o[p]}),r.headers=N.concat(i,o);const c=[];let f=!0;this.interceptors.request.forEach(function(w){typeof w.runWhen=="function"&&w.runWhen(r)===!1||(f=f&&w.synchronous,c.unshift(w.fulfilled,w.rejected))});const l=[];this.interceptors.response.forEach(function(w){l.push(w.fulfilled,w.rejected)});let u,d=0,y;if(!f){const p=[Ue.bind(this),void 0];for(p.unshift.apply(p,c),p.push.apply(p,l),y=p.length,u=Promise.resolve(r);d<y;)u=u.then(p[d++],p[d++]);return u}y=c.length;let S=r;for(d=0;d<y;){const p=c[d++],w=c[d++];try{S=p(S)}catch(h){w.call(this,h);break}}try{u=Ue.call(this,S)}catch(p){return Promise.reject(p)}for(d=0,y=l.length;d<y;)u=u.then(l[d++],l[d++]);return u}getUri(e){e=M(this.defaults,e);const r=Ge(e.baseURL,e.url,e.allowAbsoluteUrls);return $e(r,e.params,e.paramsSerializer)}};a.forEach(["delete","get","head","options"],function(e){z.prototype[e]=function(r,n){return this.request(M(n||{},{method:e,url:r,data:(n||{}).data}))}});a.forEach(["post","put","patch"],function(e){function r(n){return function(o,i,c){return this.request(M(c||{},{method:e,headers:n?{"Content-Type":"multipart/form-data"}:{},url:o,data:i}))}}z.prototype[e]=r(),z.prototype[e+"Form"]=r(!0)});let Ur=class rt{constructor(e){if(typeof e!="function")throw new TypeError("executor must be a function.");let r;this.promise=new Promise(function(o){r=o});const n=this;this.promise.then(s=>{if(!n._listeners)return;let o=n._listeners.length;for(;o-- >0;)n._listeners[o](s);n._listeners=null}),this.promise.then=s=>{let o;const i=new Promise(c=>{n.subscribe(c),o=c}).then(s);return i.cancel=function(){n.unsubscribe(o)},i},e(function(o,i,c){n.reason||(n.reason=new v(o,i,c),r(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const r=this._listeners.indexOf(e);r!==-1&&this._listeners.splice(r,1)}toAbortSignal(){const e=new AbortController,r=n=>{e.abort(n)};return this.subscribe(r),e.signal.unsubscribe=()=>this.unsubscribe(r),e.signal}static source(){let e;return{token:new rt(function(s){e=s}),cancel:e}}};function _r(t){return function(r){return t.apply(null,r)}}function Dr(t){return a.isObject(t)&&t.isAxiosError===!0}const me={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(me).forEach(([t,e])=>{me[e]=t});function nt(t){const e=new z(t),r=De(z.prototype.request,e);return a.extend(r,z.prototype,e,{allOwnKeys:!0}),a.extend(r,e,null,{allOwnKeys:!0}),r.create=function(s){return nt(M(t,s))},r}const E=nt(W);E.Axios=z;E.CanceledError=v;E.CancelToken=Ur;E.isCancel=We;E.VERSION=tt;E.toFormData=se;E.AxiosError=m;E.Cancel=E.CanceledError;E.all=function(e){return Promise.all(e)};E.spread=_r;E.isAxiosError=Dr;E.mergeConfig=M;E.AxiosHeaders=N;E.formToJSON=t=>Je(a.isHTMLForm(t)?new FormData(t):t);E.getAdapter=et.getAdapter;E.HttpStatusCode=me;E.default=E;const{Axios:Kr,AxiosError:Jr,CanceledError:Wr,isCancel:Xr,CancelToken:Gr,VERSION:Qr,all:Zr,Cancel:Yr,isAxiosError:en,spread:tn,toFormData:rn,AxiosHeaders:nn,HttpStatusCode:sn,formToJSON:on,getAdapter:an,mergeConfig:cn}=E;class D extends Error{constructor(e){super(e)}}class Lr extends D{constructor(e){super(e)}}class Br extends D{constructor(e){super(e)}}class Ir extends D{constructor(e){super(e)}}class jr extends D{constructor(e){super(e)}}class qr extends D{constructor(e){super(e)}}class zr extends D{constructor(e){super(e)}}class Mr extends D{constructor(e){super(e)}}class Hr extends D{constructor(e){super(e)}}const _={NotInitializedError:Lr,EmptyVideoError:Br,VideoTypeError:Ir,InvalidUsernameError:jr,InvalidPasswordError:qr,NoScansAvailableError:zr,InvalidAccessTokenError:Mr,NoScanDataError:Hr},C={NotInitializedError:new _.NotInitializedError("Nervoscan Client not initialized!"),EmptyVideoError:new _.EmptyVideoError("Video is empty!"),VideoTypeError:new _.VideoTypeError("Video is not a Blob!"),InvalidUsernameError:new _.InvalidUsernameError("Invalid username!"),InvalidPasswordError:new _.InvalidPasswordError("Invalid password!"),NoScansAvailableError:new _.NoScansAvailableError("No scans available, Please purchase a plan!"),InvalidAccessTokenError:new _.InvalidAccessTokenError("Invalid access token!"),NoScanDataError:new _.NoScanDataError("No scan data found!")},F=class F{constructor(){}static getInstance(){return F.instance||(F.instance=new F),F.instance}static throwKnownError(e){throw e}static throwUnknownError(e){throw e}static handleErrorResponse(e){var r,n,s,o,i,c,f,l,u;((s=(n=(r=e.response)==null?void 0:r.data)==null?void 0:n.error)==null?void 0:s.code)==="INVALID_USERNAME"?F.throwKnownError(C.InvalidUsernameError):((c=(i=(o=e.response)==null?void 0:o.data)==null?void 0:i.error)==null?void 0:c.code)==="INVALID_PASSWORD"?F.throwKnownError(C.InvalidPasswordError):((u=(l=(f=e.response)==null?void 0:f.data)==null?void 0:l.error)==null?void 0:u.code)==="NO_SCANS_AVAILABLE"&&F.throwKnownError(C.NoScansAvailableError)}};I(F,"instance");let O=F;const $="http://localhost:5001",j=class j{constructor(){I(this,"username");I(this,"password");I(this,"initialized",!1);I(this,"accessToken")}static getInstance(){return j.instance||(j.instance=new j),j.instance}initialize(e,r){this.initialized=!0,this.username=e,this.password=r}async getToken(){try{const r=(await E.post($.concat("/clientlogin"),{username:this.username,password:this.password})).data.access_token;return localStorage.setItem("accessToken",r),r}catch(e){O.handleErrorResponse(e)}}async getAPIKey(e){e||O.throwKnownError(C.InvalidAccessTokenError);try{return(await E.post($.concat("/clientgeturl"),{host_name:"www.nervoscan.com"},{headers:{Authorization:`Bearer ${e}`}})).data.url.split("?api_key=")[1]}catch(r){O.handleErrorResponse(r)}}async uploadVideoToServer(e,r,n){(!r||!n)&&O.throwKnownError(C.InvalidAccessTokenError);try{const s=new FormData;return s.append("file",e,"recording.webm"),s.append("data",JSON.stringify({uuid:n,meta_data:{}})),(await E.post($.concat("/submitscan"),s,{headers:{"Content-Type":"multipart/form-data",Authorization:`Bearer ${r}`}})).data}catch(s){throw console.error("Error uploading video:",s),s.response?(console.error("Error response:",s.response.data),console.error("Error status:",s.response.status),console.error("Error headers:",s.response.headers)):s.request?console.error("Error request:",s.request):console.error("Error message:",s.message),s}}async uploadVideo(e){this.initialized||O.throwKnownError(C.NotInitializedError),e instanceof Blob||O.throwKnownError(C.VideoTypeError),(e===null||e.size===0)&&O.throwKnownError(C.EmptyVideoError);const r=await this.getToken(),n=await this.getAPIKey(r);return this.uploadVideoToServer(e,r,n),n}async checkResults(e){this.initialized||O.throwKnownError(C.NotInitializedError);try{this.accessToken||(this.accessToken=await this.getToken());const s=(await E.post($.concat("/check"),{api_key:e},{headers:{Authorization:`Bearer ${this.accessToken}`}})).data.job_status;return s==="Completed"||s==="Failed"?s:"Pending"}catch(r){O.handleErrorResponse(r)}}async getResults(e){var r;this.initialized||O.throwKnownError(C.NotInitializedError),this.accessToken||(this.accessToken=await this.getToken());try{const n=await E.post($.concat("/getcustomerinfo"),{mode:"selection",api_keys:[e]},{headers:{Authorization:`Bearer ${this.accessToken}`}});return((r=n.data)==null?void 0:r.success)===!1&&O.throwKnownError(C.NoScanDataError),n.data}catch(n){console.error("Error getting results:",n),O.handleErrorResponse(n)}}};I(j,"instance");let we=j;exports.Client=we;exports.Errors=_;exports.NervoscanError=D;
1
+ "use strict";var zo=Object.defineProperty;var Go=(n,e,t)=>e in n?zo(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var Q=(n,e,t)=>Go(n,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});class ie extends Error{constructor(e){super(e)}}class Ko extends ie{constructor(e){super(e)}}class Yo extends ie{constructor(e){super(e)}}class Qo extends ie{constructor(e){super(e)}}class Jo extends ie{constructor(e){super(e)}}class Xo extends ie{constructor(e){super(e)}}class Zo extends ie{constructor(e){super(e)}}class ea extends ie{constructor(e){super(e)}}class ta extends ie{constructor(e){super(e)}}class na extends ie{constructor(e){super(e)}}class sa extends ie{constructor(e){super(e)}}const Z={NotInitializedError:Ko,EmptyVideoError:Yo,VideoTypeError:Qo,InvalidUsernameError:Jo,InvalidPasswordError:Xo,NoScansAvailableError:Zo,InvalidAccessTokenError:ea,NoScanDataError:ta,InvalidServerTypeError:na,NotImplementedError:sa},M={NotInitializedError:new Z.NotInitializedError("Nervoscan Client not initialized!"),EmptyVideoError:new Z.EmptyVideoError("Video is empty!"),VideoTypeError:new Z.VideoTypeError("Video is not a Blob!"),InvalidUsernameError:new Z.InvalidUsernameError("Invalid username!"),InvalidPasswordError:new Z.InvalidPasswordError("Invalid password!"),NoScansAvailableError:new Z.NoScansAvailableError("No scans available, Please purchase a plan!"),InvalidAccessTokenError:new Z.InvalidAccessTokenError("Invalid access token!"),NoScanDataError:new Z.NoScanDataError("No scan data found!"),InvalidServerTypeError:new Z.InvalidServerTypeError("Invalid server type!"),NotImplementedError:new Z.NotImplementedError("Not implemented!")},J=class J{constructor(){}static getInstance(){return J.instance||(J.instance=new J),J.instance}static throwKnownError(e){throw e}static throwUnknownError(e){throw e}static handleErrorResponse(e){var t,s,i,r,o,a,c,l,u,h,d,_,p;((i=(s=(t=e.response)==null?void 0:t.data)==null?void 0:s.error)==null?void 0:i.code)==="INVALID_USERNAME"?J.throwKnownError(M.InvalidUsernameError):((a=(o=(r=e.response)==null?void 0:r.data)==null?void 0:o.error)==null?void 0:a.code)==="INVALID_PASSWORD"?J.throwKnownError(M.InvalidPasswordError):(((u=(l=(c=e.response)==null?void 0:c.data)==null?void 0:l.error)==null?void 0:u.code)==="NO_SCANS_AVAILABLE"||((d=(h=e.response)==null?void 0:h.data)==null?void 0:d.message)==="No packages available!"||((p=(_=e.response)==null?void 0:_.data)==null?void 0:p.message)==="No scans available!")&&J.throwKnownError(M.NoScansAvailableError)}};Q(J,"instance");let R=J;function Hi(n,e){return function(){return n.apply(e,arguments)}}const{toString:ia}=Object.prototype,{getPrototypeOf:Zn}=Object,Xt=(n=>e=>{const t=ia.call(e);return n[t]||(n[t]=t.slice(8,-1).toLowerCase())})(Object.create(null)),re=n=>(n=n.toLowerCase(),e=>Xt(e)===n),Zt=n=>e=>typeof e===n,{isArray:$e}=Array,rt=Zt("undefined");function ra(n){return n!==null&&!rt(n)&&n.constructor!==null&&!rt(n.constructor)&&K(n.constructor.isBuffer)&&n.constructor.isBuffer(n)}const Vi=re("ArrayBuffer");function oa(n){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(n):e=n&&n.buffer&&Vi(n.buffer),e}const aa=Zt("string"),K=Zt("function"),qi=Zt("number"),en=n=>n!==null&&typeof n=="object",la=n=>n===!0||n===!1,Nt=n=>{if(Xt(n)!=="object")return!1;const e=Zn(n);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in n)&&!(Symbol.iterator in n)},ca=re("Date"),ua=re("File"),ha=re("Blob"),da=re("FileList"),fa=n=>en(n)&&K(n.pipe),pa=n=>{let e;return n&&(typeof FormData=="function"&&n instanceof FormData||K(n.append)&&((e=Xt(n))==="formdata"||e==="object"&&K(n.toString)&&n.toString()==="[object FormData]"))},_a=re("URLSearchParams"),[ma,ga,ya,Ea]=["ReadableStream","Request","Response","Headers"].map(re),wa=n=>n.trim?n.trim():n.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function mt(n,e,{allOwnKeys:t=!1}={}){if(n===null||typeof n>"u")return;let s,i;if(typeof n!="object"&&(n=[n]),$e(n))for(s=0,i=n.length;s<i;s++)e.call(null,n[s],s,n);else{const r=t?Object.getOwnPropertyNames(n):Object.keys(n),o=r.length;let a;for(s=0;s<o;s++)a=r[s],e.call(null,n[a],a,n)}}function $i(n,e){e=e.toLowerCase();const t=Object.keys(n);let s=t.length,i;for(;s-- >0;)if(i=t[s],e===i.toLowerCase())return i;return null}const be=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,ji=n=>!rt(n)&&n!==be;function Nn(){const{caseless:n}=ji(this)&&this||{},e={},t=(s,i)=>{const r=n&&$i(e,i)||i;Nt(e[r])&&Nt(s)?e[r]=Nn(e[r],s):Nt(s)?e[r]=Nn({},s):$e(s)?e[r]=s.slice():e[r]=s};for(let s=0,i=arguments.length;s<i;s++)arguments[s]&&mt(arguments[s],t);return e}const va=(n,e,t,{allOwnKeys:s}={})=>(mt(e,(i,r)=>{t&&K(i)?n[r]=Hi(i,t):n[r]=i},{allOwnKeys:s}),n),Ca=n=>(n.charCodeAt(0)===65279&&(n=n.slice(1)),n),ba=(n,e,t,s)=>{n.prototype=Object.create(e.prototype,s),n.prototype.constructor=n,Object.defineProperty(n,"super",{value:e.prototype}),t&&Object.assign(n.prototype,t)},Sa=(n,e,t,s)=>{let i,r,o;const a={};if(e=e||{},n==null)return e;do{for(i=Object.getOwnPropertyNames(n),r=i.length;r-- >0;)o=i[r],(!s||s(o,n,e))&&!a[o]&&(e[o]=n[o],a[o]=!0);n=t!==!1&&Zn(n)}while(n&&(!t||t(n,e))&&n!==Object.prototype);return e},Ta=(n,e,t)=>{n=String(n),(t===void 0||t>n.length)&&(t=n.length),t-=e.length;const s=n.indexOf(e,t);return s!==-1&&s===t},Ia=n=>{if(!n)return null;if($e(n))return n;let e=n.length;if(!qi(e))return null;const t=new Array(e);for(;e-- >0;)t[e]=n[e];return t},Ra=(n=>e=>n&&e instanceof n)(typeof Uint8Array<"u"&&Zn(Uint8Array)),Na=(n,e)=>{const s=(n&&n[Symbol.iterator]).call(n);let i;for(;(i=s.next())&&!i.done;){const r=i.value;e.call(n,r[0],r[1])}},Aa=(n,e)=>{let t;const s=[];for(;(t=n.exec(e))!==null;)s.push(t);return s},ka=re("HTMLFormElement"),xa=n=>n.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(t,s,i){return s.toUpperCase()+i}),Ls=(({hasOwnProperty:n})=>(e,t)=>n.call(e,t))(Object.prototype),Oa=re("RegExp"),zi=(n,e)=>{const t=Object.getOwnPropertyDescriptors(n),s={};mt(t,(i,r)=>{let o;(o=e(i,r,n))!==!1&&(s[r]=o||i)}),Object.defineProperties(n,s)},Da=n=>{zi(n,(e,t)=>{if(K(n)&&["arguments","caller","callee"].indexOf(t)!==-1)return!1;const s=n[t];if(K(s)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+t+"'")})}})},Pa=(n,e)=>{const t={},s=i=>{i.forEach(r=>{t[r]=!0})};return $e(n)?s(n):s(String(n).split(e)),t},Ma=()=>{},La=(n,e)=>n!=null&&Number.isFinite(n=+n)?n:e;function Fa(n){return!!(n&&K(n.append)&&n[Symbol.toStringTag]==="FormData"&&n[Symbol.iterator])}const Ua=n=>{const e=new Array(10),t=(s,i)=>{if(en(s)){if(e.indexOf(s)>=0)return;if(!("toJSON"in s)){e[i]=s;const r=$e(s)?[]:{};return mt(s,(o,a)=>{const c=t(o,i+1);!rt(c)&&(r[a]=c)}),e[i]=void 0,r}}return s};return t(n,0)},Ba=re("AsyncFunction"),Wa=n=>n&&(en(n)||K(n))&&K(n.then)&&K(n.catch),Gi=((n,e)=>n?setImmediate:e?((t,s)=>(be.addEventListener("message",({source:i,data:r})=>{i===be&&r===t&&s.length&&s.shift()()},!1),i=>{s.push(i),be.postMessage(t,"*")}))(`axios@${Math.random()}`,[]):t=>setTimeout(t))(typeof setImmediate=="function",K(be.postMessage)),Ha=typeof queueMicrotask<"u"?queueMicrotask.bind(be):typeof process<"u"&&process.nextTick||Gi,f={isArray:$e,isArrayBuffer:Vi,isBuffer:ra,isFormData:pa,isArrayBufferView:oa,isString:aa,isNumber:qi,isBoolean:la,isObject:en,isPlainObject:Nt,isReadableStream:ma,isRequest:ga,isResponse:ya,isHeaders:Ea,isUndefined:rt,isDate:ca,isFile:ua,isBlob:ha,isRegExp:Oa,isFunction:K,isStream:fa,isURLSearchParams:_a,isTypedArray:Ra,isFileList:da,forEach:mt,merge:Nn,extend:va,trim:wa,stripBOM:Ca,inherits:ba,toFlatObject:Sa,kindOf:Xt,kindOfTest:re,endsWith:Ta,toArray:Ia,forEachEntry:Na,matchAll:Aa,isHTMLForm:ka,hasOwnProperty:Ls,hasOwnProp:Ls,reduceDescriptors:zi,freezeMethods:Da,toObjectSet:Pa,toCamelCase:xa,noop:Ma,toFiniteNumber:La,findKey:$i,global:be,isContextDefined:ji,isSpecCompliantForm:Fa,toJSONObject:Ua,isAsyncFn:Ba,isThenable:Wa,setImmediate:Gi,asap:Ha};function w(n,e,t,s,i){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=n,this.name="AxiosError",e&&(this.code=e),t&&(this.config=t),s&&(this.request=s),i&&(this.response=i,this.status=i.status?i.status:null)}f.inherits(w,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:f.toJSONObject(this.config),code:this.code,status:this.status}}});const Ki=w.prototype,Yi={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(n=>{Yi[n]={value:n}});Object.defineProperties(w,Yi);Object.defineProperty(Ki,"isAxiosError",{value:!0});w.from=(n,e,t,s,i,r)=>{const o=Object.create(Ki);return f.toFlatObject(n,o,function(c){return c!==Error.prototype},a=>a!=="isAxiosError"),w.call(o,n.message,e,t,s,i),o.cause=n,o.name=n.name,r&&Object.assign(o,r),o};const Va=null;function An(n){return f.isPlainObject(n)||f.isArray(n)}function Qi(n){return f.endsWith(n,"[]")?n.slice(0,-2):n}function Fs(n,e,t){return n?n.concat(e).map(function(i,r){return i=Qi(i),!t&&r?"["+i+"]":i}).join(t?".":""):e}function qa(n){return f.isArray(n)&&!n.some(An)}const $a=f.toFlatObject(f,{},null,function(e){return/^is[A-Z]/.test(e)});function tn(n,e,t){if(!f.isObject(n))throw new TypeError("target must be an object");e=e||new FormData,t=f.toFlatObject(t,{metaTokens:!0,dots:!1,indexes:!1},!1,function(y,g){return!f.isUndefined(g[y])});const s=t.metaTokens,i=t.visitor||u,r=t.dots,o=t.indexes,c=(t.Blob||typeof Blob<"u"&&Blob)&&f.isSpecCompliantForm(e);if(!f.isFunction(i))throw new TypeError("visitor must be a function");function l(p){if(p===null)return"";if(f.isDate(p))return p.toISOString();if(!c&&f.isBlob(p))throw new w("Blob is not supported. Use a Buffer instead.");return f.isArrayBuffer(p)||f.isTypedArray(p)?c&&typeof Blob=="function"?new Blob([p]):Buffer.from(p):p}function u(p,y,g){let I=p;if(p&&!g&&typeof p=="object"){if(f.endsWith(y,"{}"))y=s?y:y.slice(0,-2),p=JSON.stringify(p);else if(f.isArray(p)&&qa(p)||(f.isFileList(p)||f.endsWith(y,"[]"))&&(I=f.toArray(p)))return y=Qi(y),I.forEach(function(D,X){!(f.isUndefined(D)||D===null)&&e.append(o===!0?Fs([y],X,r):o===null?y:y+"[]",l(D))}),!1}return An(p)?!0:(e.append(Fs(g,y,r),l(p)),!1)}const h=[],d=Object.assign($a,{defaultVisitor:u,convertValue:l,isVisitable:An});function _(p,y){if(!f.isUndefined(p)){if(h.indexOf(p)!==-1)throw Error("Circular reference detected in "+y.join("."));h.push(p),f.forEach(p,function(I,O){(!(f.isUndefined(I)||I===null)&&i.call(e,I,f.isString(O)?O.trim():O,y,d))===!0&&_(I,y?y.concat(O):[O])}),h.pop()}}if(!f.isObject(n))throw new TypeError("data must be an object");return _(n),e}function Us(n){const e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(n).replace(/[!'()~]|%20|%00/g,function(s){return e[s]})}function es(n,e){this._pairs=[],n&&tn(n,this,e)}const Ji=es.prototype;Ji.append=function(e,t){this._pairs.push([e,t])};Ji.toString=function(e){const t=e?function(s){return e.call(this,s,Us)}:Us;return this._pairs.map(function(i){return t(i[0])+"="+t(i[1])},"").join("&")};function ja(n){return encodeURIComponent(n).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function Xi(n,e,t){if(!e)return n;const s=t&&t.encode||ja;f.isFunction(t)&&(t={serialize:t});const i=t&&t.serialize;let r;if(i?r=i(e,t):r=f.isURLSearchParams(e)?e.toString():new es(e,t).toString(s),r){const o=n.indexOf("#");o!==-1&&(n=n.slice(0,o)),n+=(n.indexOf("?")===-1?"?":"&")+r}return n}class Bs{constructor(){this.handlers=[]}use(e,t,s){return this.handlers.push({fulfilled:e,rejected:t,synchronous:s?s.synchronous:!1,runWhen:s?s.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){f.forEach(this.handlers,function(s){s!==null&&e(s)})}}const Zi={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},za=typeof URLSearchParams<"u"?URLSearchParams:es,Ga=typeof FormData<"u"?FormData:null,Ka=typeof Blob<"u"?Blob:null,Ya={isBrowser:!0,classes:{URLSearchParams:za,FormData:Ga,Blob:Ka},protocols:["http","https","file","blob","url","data"]},ts=typeof window<"u"&&typeof document<"u",kn=typeof navigator=="object"&&navigator||void 0,Qa=ts&&(!kn||["ReactNative","NativeScript","NS"].indexOf(kn.product)<0),Ja=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",Xa=ts&&window.location.href||"http://localhost",Za=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:ts,hasStandardBrowserEnv:Qa,hasStandardBrowserWebWorkerEnv:Ja,navigator:kn,origin:Xa},Symbol.toStringTag,{value:"Module"})),V={...Za,...Ya};function el(n,e){return tn(n,new V.classes.URLSearchParams,Object.assign({visitor:function(t,s,i,r){return V.isNode&&f.isBuffer(t)?(this.append(s,t.toString("base64")),!1):r.defaultVisitor.apply(this,arguments)}},e))}function tl(n){return f.matchAll(/\w+|\[(\w*)]/g,n).map(e=>e[0]==="[]"?"":e[1]||e[0])}function nl(n){const e={},t=Object.keys(n);let s;const i=t.length;let r;for(s=0;s<i;s++)r=t[s],e[r]=n[r];return e}function er(n){function e(t,s,i,r){let o=t[r++];if(o==="__proto__")return!0;const a=Number.isFinite(+o),c=r>=t.length;return o=!o&&f.isArray(i)?i.length:o,c?(f.hasOwnProp(i,o)?i[o]=[i[o],s]:i[o]=s,!a):((!i[o]||!f.isObject(i[o]))&&(i[o]=[]),e(t,s,i[o],r)&&f.isArray(i[o])&&(i[o]=nl(i[o])),!a)}if(f.isFormData(n)&&f.isFunction(n.entries)){const t={};return f.forEachEntry(n,(s,i)=>{e(tl(s),i,t,0)}),t}return null}function sl(n,e,t){if(f.isString(n))try{return(e||JSON.parse)(n),f.trim(n)}catch(s){if(s.name!=="SyntaxError")throw s}return(t||JSON.stringify)(n)}const gt={transitional:Zi,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const s=t.getContentType()||"",i=s.indexOf("application/json")>-1,r=f.isObject(e);if(r&&f.isHTMLForm(e)&&(e=new FormData(e)),f.isFormData(e))return i?JSON.stringify(er(e)):e;if(f.isArrayBuffer(e)||f.isBuffer(e)||f.isStream(e)||f.isFile(e)||f.isBlob(e)||f.isReadableStream(e))return e;if(f.isArrayBufferView(e))return e.buffer;if(f.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let a;if(r){if(s.indexOf("application/x-www-form-urlencoded")>-1)return el(e,this.formSerializer).toString();if((a=f.isFileList(e))||s.indexOf("multipart/form-data")>-1){const c=this.env&&this.env.FormData;return tn(a?{"files[]":e}:e,c&&new c,this.formSerializer)}}return r||i?(t.setContentType("application/json",!1),sl(e)):e}],transformResponse:[function(e){const t=this.transitional||gt.transitional,s=t&&t.forcedJSONParsing,i=this.responseType==="json";if(f.isResponse(e)||f.isReadableStream(e))return e;if(e&&f.isString(e)&&(s&&!this.responseType||i)){const o=!(t&&t.silentJSONParsing)&&i;try{return JSON.parse(e)}catch(a){if(o)throw a.name==="SyntaxError"?w.from(a,w.ERR_BAD_RESPONSE,this,null,this.response):a}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:V.classes.FormData,Blob:V.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};f.forEach(["delete","get","head","post","put","patch"],n=>{gt.headers[n]={}});const il=f.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),rl=n=>{const e={};let t,s,i;return n&&n.split(`
2
+ `).forEach(function(o){i=o.indexOf(":"),t=o.substring(0,i).trim().toLowerCase(),s=o.substring(i+1).trim(),!(!t||e[t]&&il[t])&&(t==="set-cookie"?e[t]?e[t].push(s):e[t]=[s]:e[t]=e[t]?e[t]+", "+s:s)}),e},Ws=Symbol("internals");function Ye(n){return n&&String(n).trim().toLowerCase()}function At(n){return n===!1||n==null?n:f.isArray(n)?n.map(At):String(n)}function ol(n){const e=Object.create(null),t=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let s;for(;s=t.exec(n);)e[s[1]]=s[2];return e}const al=n=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(n.trim());function pn(n,e,t,s,i){if(f.isFunction(s))return s.call(this,e,t);if(i&&(e=t),!!f.isString(e)){if(f.isString(s))return e.indexOf(s)!==-1;if(f.isRegExp(s))return s.test(e)}}function ll(n){return n.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,t,s)=>t.toUpperCase()+s)}function cl(n,e){const t=f.toCamelCase(" "+e);["get","set","has"].forEach(s=>{Object.defineProperty(n,s+t,{value:function(i,r,o){return this[s].call(this,e,i,r,o)},configurable:!0})})}let z=class{constructor(e){e&&this.set(e)}set(e,t,s){const i=this;function r(a,c,l){const u=Ye(c);if(!u)throw new Error("header name must be a non-empty string");const h=f.findKey(i,u);(!h||i[h]===void 0||l===!0||l===void 0&&i[h]!==!1)&&(i[h||c]=At(a))}const o=(a,c)=>f.forEach(a,(l,u)=>r(l,u,c));if(f.isPlainObject(e)||e instanceof this.constructor)o(e,t);else if(f.isString(e)&&(e=e.trim())&&!al(e))o(rl(e),t);else if(f.isHeaders(e))for(const[a,c]of e.entries())r(c,a,s);else e!=null&&r(t,e,s);return this}get(e,t){if(e=Ye(e),e){const s=f.findKey(this,e);if(s){const i=this[s];if(!t)return i;if(t===!0)return ol(i);if(f.isFunction(t))return t.call(this,i,s);if(f.isRegExp(t))return t.exec(i);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=Ye(e),e){const s=f.findKey(this,e);return!!(s&&this[s]!==void 0&&(!t||pn(this,this[s],s,t)))}return!1}delete(e,t){const s=this;let i=!1;function r(o){if(o=Ye(o),o){const a=f.findKey(s,o);a&&(!t||pn(s,s[a],a,t))&&(delete s[a],i=!0)}}return f.isArray(e)?e.forEach(r):r(e),i}clear(e){const t=Object.keys(this);let s=t.length,i=!1;for(;s--;){const r=t[s];(!e||pn(this,this[r],r,e,!0))&&(delete this[r],i=!0)}return i}normalize(e){const t=this,s={};return f.forEach(this,(i,r)=>{const o=f.findKey(s,r);if(o){t[o]=At(i),delete t[r];return}const a=e?ll(r):String(r).trim();a!==r&&delete t[r],t[a]=At(i),s[a]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return f.forEach(this,(s,i)=>{s!=null&&s!==!1&&(t[i]=e&&f.isArray(s)?s.join(", "):s)}),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,t])=>e+": "+t).join(`
3
+ `)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...t){const s=new this(e);return t.forEach(i=>s.set(i)),s}static accessor(e){const s=(this[Ws]=this[Ws]={accessors:{}}).accessors,i=this.prototype;function r(o){const a=Ye(o);s[a]||(cl(i,o),s[a]=!0)}return f.isArray(e)?e.forEach(r):r(e),this}};z.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);f.reduceDescriptors(z.prototype,({value:n},e)=>{let t=e[0].toUpperCase()+e.slice(1);return{get:()=>n,set(s){this[t]=s}}});f.freezeMethods(z);function _n(n,e){const t=this||gt,s=e||t,i=z.from(s.headers);let r=s.data;return f.forEach(n,function(a){r=a.call(t,r,i.normalize(),e?e.status:void 0)}),i.normalize(),r}function tr(n){return!!(n&&n.__CANCEL__)}function je(n,e,t){w.call(this,n??"canceled",w.ERR_CANCELED,e,t),this.name="CanceledError"}f.inherits(je,w,{__CANCEL__:!0});function nr(n,e,t){const s=t.config.validateStatus;!t.status||!s||s(t.status)?n(t):e(new w("Request failed with status code "+t.status,[w.ERR_BAD_REQUEST,w.ERR_BAD_RESPONSE][Math.floor(t.status/100)-4],t.config,t.request,t))}function ul(n){const e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(n);return e&&e[1]||""}function hl(n,e){n=n||10;const t=new Array(n),s=new Array(n);let i=0,r=0,o;return e=e!==void 0?e:1e3,function(c){const l=Date.now(),u=s[r];o||(o=l),t[i]=c,s[i]=l;let h=r,d=0;for(;h!==i;)d+=t[h++],h=h%n;if(i=(i+1)%n,i===r&&(r=(r+1)%n),l-o<e)return;const _=u&&l-u;return _?Math.round(d*1e3/_):void 0}}function dl(n,e){let t=0,s=1e3/e,i,r;const o=(l,u=Date.now())=>{t=u,i=null,r&&(clearTimeout(r),r=null),n.apply(null,l)};return[(...l)=>{const u=Date.now(),h=u-t;h>=s?o(l,u):(i=l,r||(r=setTimeout(()=>{r=null,o(i)},s-h)))},()=>i&&o(i)]}const Ot=(n,e,t=3)=>{let s=0;const i=hl(50,250);return dl(r=>{const o=r.loaded,a=r.lengthComputable?r.total:void 0,c=o-s,l=i(c),u=o<=a;s=o;const h={loaded:o,total:a,progress:a?o/a:void 0,bytes:c,rate:l||void 0,estimated:l&&a&&u?(a-o)/l:void 0,event:r,lengthComputable:a!=null,[e?"download":"upload"]:!0};n(h)},t)},Hs=(n,e)=>{const t=n!=null;return[s=>e[0]({lengthComputable:t,total:n,loaded:s}),e[1]]},Vs=n=>(...e)=>f.asap(()=>n(...e)),fl=V.hasStandardBrowserEnv?((n,e)=>t=>(t=new URL(t,V.origin),n.protocol===t.protocol&&n.host===t.host&&(e||n.port===t.port)))(new URL(V.origin),V.navigator&&/(msie|trident)/i.test(V.navigator.userAgent)):()=>!0,pl=V.hasStandardBrowserEnv?{write(n,e,t,s,i,r){const o=[n+"="+encodeURIComponent(e)];f.isNumber(t)&&o.push("expires="+new Date(t).toGMTString()),f.isString(s)&&o.push("path="+s),f.isString(i)&&o.push("domain="+i),r===!0&&o.push("secure"),document.cookie=o.join("; ")},read(n){const e=document.cookie.match(new RegExp("(^|;\\s*)("+n+")=([^;]*)"));return e?decodeURIComponent(e[3]):null},remove(n){this.write(n,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function _l(n){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(n)}function ml(n,e){return e?n.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):n}function sr(n,e,t){let s=!_l(e);return n&&(s||t==!1)?ml(n,e):e}const qs=n=>n instanceof z?{...n}:n;function Ie(n,e){e=e||{};const t={};function s(l,u,h,d){return f.isPlainObject(l)&&f.isPlainObject(u)?f.merge.call({caseless:d},l,u):f.isPlainObject(u)?f.merge({},u):f.isArray(u)?u.slice():u}function i(l,u,h,d){if(f.isUndefined(u)){if(!f.isUndefined(l))return s(void 0,l,h,d)}else return s(l,u,h,d)}function r(l,u){if(!f.isUndefined(u))return s(void 0,u)}function o(l,u){if(f.isUndefined(u)){if(!f.isUndefined(l))return s(void 0,l)}else return s(void 0,u)}function a(l,u,h){if(h in e)return s(l,u);if(h in n)return s(void 0,l)}const c={url:r,method:r,data:r,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,withXSRFToken:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:a,headers:(l,u,h)=>i(qs(l),qs(u),h,!0)};return f.forEach(Object.keys(Object.assign({},n,e)),function(u){const h=c[u]||i,d=h(n[u],e[u],u);f.isUndefined(d)&&h!==a||(t[u]=d)}),t}const ir=n=>{const e=Ie({},n);let{data:t,withXSRFToken:s,xsrfHeaderName:i,xsrfCookieName:r,headers:o,auth:a}=e;e.headers=o=z.from(o),e.url=Xi(sr(e.baseURL,e.url,e.allowAbsoluteUrls),n.params,n.paramsSerializer),a&&o.set("Authorization","Basic "+btoa((a.username||"")+":"+(a.password?unescape(encodeURIComponent(a.password)):"")));let c;if(f.isFormData(t)){if(V.hasStandardBrowserEnv||V.hasStandardBrowserWebWorkerEnv)o.setContentType(void 0);else if((c=o.getContentType())!==!1){const[l,...u]=c?c.split(";").map(h=>h.trim()).filter(Boolean):[];o.setContentType([l||"multipart/form-data",...u].join("; "))}}if(V.hasStandardBrowserEnv&&(s&&f.isFunction(s)&&(s=s(e)),s||s!==!1&&fl(e.url))){const l=i&&r&&pl.read(r);l&&o.set(i,l)}return e},gl=typeof XMLHttpRequest<"u",yl=gl&&function(n){return new Promise(function(t,s){const i=ir(n);let r=i.data;const o=z.from(i.headers).normalize();let{responseType:a,onUploadProgress:c,onDownloadProgress:l}=i,u,h,d,_,p;function y(){_&&_(),p&&p(),i.cancelToken&&i.cancelToken.unsubscribe(u),i.signal&&i.signal.removeEventListener("abort",u)}let g=new XMLHttpRequest;g.open(i.method.toUpperCase(),i.url,!0),g.timeout=i.timeout;function I(){if(!g)return;const D=z.from("getAllResponseHeaders"in g&&g.getAllResponseHeaders()),q={data:!a||a==="text"||a==="json"?g.responseText:g.response,status:g.status,statusText:g.statusText,headers:D,config:n,request:g};nr(function(Ee){t(Ee),y()},function(Ee){s(Ee),y()},q),g=null}"onloadend"in g?g.onloadend=I:g.onreadystatechange=function(){!g||g.readyState!==4||g.status===0&&!(g.responseURL&&g.responseURL.indexOf("file:")===0)||setTimeout(I)},g.onabort=function(){g&&(s(new w("Request aborted",w.ECONNABORTED,n,g)),g=null)},g.onerror=function(){s(new w("Network Error",w.ERR_NETWORK,n,g)),g=null},g.ontimeout=function(){let X=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded";const q=i.transitional||Zi;i.timeoutErrorMessage&&(X=i.timeoutErrorMessage),s(new w(X,q.clarifyTimeoutError?w.ETIMEDOUT:w.ECONNABORTED,n,g)),g=null},r===void 0&&o.setContentType(null),"setRequestHeader"in g&&f.forEach(o.toJSON(),function(X,q){g.setRequestHeader(q,X)}),f.isUndefined(i.withCredentials)||(g.withCredentials=!!i.withCredentials),a&&a!=="json"&&(g.responseType=i.responseType),l&&([d,p]=Ot(l,!0),g.addEventListener("progress",d)),c&&g.upload&&([h,_]=Ot(c),g.upload.addEventListener("progress",h),g.upload.addEventListener("loadend",_)),(i.cancelToken||i.signal)&&(u=D=>{g&&(s(!D||D.type?new je(null,n,g):D),g.abort(),g=null)},i.cancelToken&&i.cancelToken.subscribe(u),i.signal&&(i.signal.aborted?u():i.signal.addEventListener("abort",u)));const O=ul(i.url);if(O&&V.protocols.indexOf(O)===-1){s(new w("Unsupported protocol "+O+":",w.ERR_BAD_REQUEST,n));return}g.send(r||null)})},El=(n,e)=>{const{length:t}=n=n?n.filter(Boolean):[];if(e||t){let s=new AbortController,i;const r=function(l){if(!i){i=!0,a();const u=l instanceof Error?l:this.reason;s.abort(u instanceof w?u:new je(u instanceof Error?u.message:u))}};let o=e&&setTimeout(()=>{o=null,r(new w(`timeout ${e} of ms exceeded`,w.ETIMEDOUT))},e);const a=()=>{n&&(o&&clearTimeout(o),o=null,n.forEach(l=>{l.unsubscribe?l.unsubscribe(r):l.removeEventListener("abort",r)}),n=null)};n.forEach(l=>l.addEventListener("abort",r));const{signal:c}=s;return c.unsubscribe=()=>f.asap(a),c}},wl=function*(n,e){let t=n.byteLength;if(t<e){yield n;return}let s=0,i;for(;s<t;)i=s+e,yield n.slice(s,i),s=i},vl=async function*(n,e){for await(const t of Cl(n))yield*wl(t,e)},Cl=async function*(n){if(n[Symbol.asyncIterator]){yield*n;return}const e=n.getReader();try{for(;;){const{done:t,value:s}=await e.read();if(t)break;yield s}}finally{await e.cancel()}},$s=(n,e,t,s)=>{const i=vl(n,e);let r=0,o,a=c=>{o||(o=!0,s&&s(c))};return new ReadableStream({async pull(c){try{const{done:l,value:u}=await i.next();if(l){a(),c.close();return}let h=u.byteLength;if(t){let d=r+=h;t(d)}c.enqueue(new Uint8Array(u))}catch(l){throw a(l),l}},cancel(c){return a(c),i.return()}},{highWaterMark:2})},nn=typeof fetch=="function"&&typeof Request=="function"&&typeof Response=="function",rr=nn&&typeof ReadableStream=="function",bl=nn&&(typeof TextEncoder=="function"?(n=>e=>n.encode(e))(new TextEncoder):async n=>new Uint8Array(await new Response(n).arrayBuffer())),or=(n,...e)=>{try{return!!n(...e)}catch{return!1}},Sl=rr&&or(()=>{let n=!1;const e=new Request(V.origin,{body:new ReadableStream,method:"POST",get duplex(){return n=!0,"half"}}).headers.has("Content-Type");return n&&!e}),js=64*1024,xn=rr&&or(()=>f.isReadableStream(new Response("").body)),Dt={stream:xn&&(n=>n.body)};nn&&(n=>{["text","arrayBuffer","blob","formData","stream"].forEach(e=>{!Dt[e]&&(Dt[e]=f.isFunction(n[e])?t=>t[e]():(t,s)=>{throw new w(`Response type '${e}' is not supported`,w.ERR_NOT_SUPPORT,s)})})})(new Response);const Tl=async n=>{if(n==null)return 0;if(f.isBlob(n))return n.size;if(f.isSpecCompliantForm(n))return(await new Request(V.origin,{method:"POST",body:n}).arrayBuffer()).byteLength;if(f.isArrayBufferView(n)||f.isArrayBuffer(n))return n.byteLength;if(f.isURLSearchParams(n)&&(n=n+""),f.isString(n))return(await bl(n)).byteLength},Il=async(n,e)=>{const t=f.toFiniteNumber(n.getContentLength());return t??Tl(e)},Rl=nn&&(async n=>{let{url:e,method:t,data:s,signal:i,cancelToken:r,timeout:o,onDownloadProgress:a,onUploadProgress:c,responseType:l,headers:u,withCredentials:h="same-origin",fetchOptions:d}=ir(n);l=l?(l+"").toLowerCase():"text";let _=El([i,r&&r.toAbortSignal()],o),p;const y=_&&_.unsubscribe&&(()=>{_.unsubscribe()});let g;try{if(c&&Sl&&t!=="get"&&t!=="head"&&(g=await Il(u,s))!==0){let q=new Request(e,{method:"POST",body:s,duplex:"half"}),fe;if(f.isFormData(s)&&(fe=q.headers.get("content-type"))&&u.setContentType(fe),q.body){const[Ee,Tt]=Hs(g,Ot(Vs(c)));s=$s(q.body,js,Ee,Tt)}}f.isString(h)||(h=h?"include":"omit");const I="credentials"in Request.prototype;p=new Request(e,{...d,signal:_,method:t.toUpperCase(),headers:u.normalize().toJSON(),body:s,duplex:"half",credentials:I?h:void 0});let O=await fetch(p);const D=xn&&(l==="stream"||l==="response");if(xn&&(a||D&&y)){const q={};["status","statusText","headers"].forEach(Ms=>{q[Ms]=O[Ms]});const fe=f.toFiniteNumber(O.headers.get("content-length")),[Ee,Tt]=a&&Hs(fe,Ot(Vs(a),!0))||[];O=new Response($s(O.body,js,Ee,()=>{Tt&&Tt(),y&&y()}),q)}l=l||"text";let X=await Dt[f.findKey(Dt,l)||"text"](O,n);return!D&&y&&y(),await new Promise((q,fe)=>{nr(q,fe,{data:X,headers:z.from(O.headers),status:O.status,statusText:O.statusText,config:n,request:p})})}catch(I){throw y&&y(),I&&I.name==="TypeError"&&/fetch/i.test(I.message)?Object.assign(new w("Network Error",w.ERR_NETWORK,n,p),{cause:I.cause||I}):w.from(I,I&&I.code,n,p)}}),On={http:Va,xhr:yl,fetch:Rl};f.forEach(On,(n,e)=>{if(n){try{Object.defineProperty(n,"name",{value:e})}catch{}Object.defineProperty(n,"adapterName",{value:e})}});const zs=n=>`- ${n}`,Nl=n=>f.isFunction(n)||n===null||n===!1,ar={getAdapter:n=>{n=f.isArray(n)?n:[n];const{length:e}=n;let t,s;const i={};for(let r=0;r<e;r++){t=n[r];let o;if(s=t,!Nl(t)&&(s=On[(o=String(t)).toLowerCase()],s===void 0))throw new w(`Unknown adapter '${o}'`);if(s)break;i[o||"#"+r]=s}if(!s){const r=Object.entries(i).map(([a,c])=>`adapter ${a} `+(c===!1?"is not supported by the environment":"is not available in the build"));let o=e?r.length>1?`since :
4
+ `+r.map(zs).join(`
5
+ `):" "+zs(r[0]):"as no adapter specified";throw new w("There is no suitable adapter to dispatch the request "+o,"ERR_NOT_SUPPORT")}return s},adapters:On};function mn(n){if(n.cancelToken&&n.cancelToken.throwIfRequested(),n.signal&&n.signal.aborted)throw new je(null,n)}function Gs(n){return mn(n),n.headers=z.from(n.headers),n.data=_n.call(n,n.transformRequest),["post","put","patch"].indexOf(n.method)!==-1&&n.headers.setContentType("application/x-www-form-urlencoded",!1),ar.getAdapter(n.adapter||gt.adapter)(n).then(function(s){return mn(n),s.data=_n.call(n,n.transformResponse,s),s.headers=z.from(s.headers),s},function(s){return tr(s)||(mn(n),s&&s.response&&(s.response.data=_n.call(n,n.transformResponse,s.response),s.response.headers=z.from(s.response.headers))),Promise.reject(s)})}const lr="1.8.4",sn={};["object","boolean","number","function","string","symbol"].forEach((n,e)=>{sn[n]=function(s){return typeof s===n||"a"+(e<1?"n ":" ")+n}});const Ks={};sn.transitional=function(e,t,s){function i(r,o){return"[Axios v"+lr+"] Transitional option '"+r+"'"+o+(s?". "+s:"")}return(r,o,a)=>{if(e===!1)throw new w(i(o," has been removed"+(t?" in "+t:"")),w.ERR_DEPRECATED);return t&&!Ks[o]&&(Ks[o]=!0,console.warn(i(o," has been deprecated since v"+t+" and will be removed in the near future"))),e?e(r,o,a):!0}};sn.spelling=function(e){return(t,s)=>(console.warn(`${s} is likely a misspelling of ${e}`),!0)};function Al(n,e,t){if(typeof n!="object")throw new w("options must be an object",w.ERR_BAD_OPTION_VALUE);const s=Object.keys(n);let i=s.length;for(;i-- >0;){const r=s[i],o=e[r];if(o){const a=n[r],c=a===void 0||o(a,r,n);if(c!==!0)throw new w("option "+r+" must be "+c,w.ERR_BAD_OPTION_VALUE);continue}if(t!==!0)throw new w("Unknown option "+r,w.ERR_BAD_OPTION)}}const kt={assertOptions:Al,validators:sn},oe=kt.validators;let Te=class{constructor(e){this.defaults=e,this.interceptors={request:new Bs,response:new Bs}}async request(e,t){try{return await this._request(e,t)}catch(s){if(s instanceof Error){let i={};Error.captureStackTrace?Error.captureStackTrace(i):i=new Error;const r=i.stack?i.stack.replace(/^.+\n/,""):"";try{s.stack?r&&!String(s.stack).endsWith(r.replace(/^.+\n.+\n/,""))&&(s.stack+=`
6
+ `+r):s.stack=r}catch{}}throw s}}_request(e,t){typeof e=="string"?(t=t||{},t.url=e):t=e||{},t=Ie(this.defaults,t);const{transitional:s,paramsSerializer:i,headers:r}=t;s!==void 0&&kt.assertOptions(s,{silentJSONParsing:oe.transitional(oe.boolean),forcedJSONParsing:oe.transitional(oe.boolean),clarifyTimeoutError:oe.transitional(oe.boolean)},!1),i!=null&&(f.isFunction(i)?t.paramsSerializer={serialize:i}:kt.assertOptions(i,{encode:oe.function,serialize:oe.function},!0)),t.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),kt.assertOptions(t,{baseUrl:oe.spelling("baseURL"),withXsrfToken:oe.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let o=r&&f.merge(r.common,r[t.method]);r&&f.forEach(["delete","get","head","post","put","patch","common"],p=>{delete r[p]}),t.headers=z.concat(o,r);const a=[];let c=!0;this.interceptors.request.forEach(function(y){typeof y.runWhen=="function"&&y.runWhen(t)===!1||(c=c&&y.synchronous,a.unshift(y.fulfilled,y.rejected))});const l=[];this.interceptors.response.forEach(function(y){l.push(y.fulfilled,y.rejected)});let u,h=0,d;if(!c){const p=[Gs.bind(this),void 0];for(p.unshift.apply(p,a),p.push.apply(p,l),d=p.length,u=Promise.resolve(t);h<d;)u=u.then(p[h++],p[h++]);return u}d=a.length;let _=t;for(h=0;h<d;){const p=a[h++],y=a[h++];try{_=p(_)}catch(g){y.call(this,g);break}}try{u=Gs.call(this,_)}catch(p){return Promise.reject(p)}for(h=0,d=l.length;h<d;)u=u.then(l[h++],l[h++]);return u}getUri(e){e=Ie(this.defaults,e);const t=sr(e.baseURL,e.url,e.allowAbsoluteUrls);return Xi(t,e.params,e.paramsSerializer)}};f.forEach(["delete","get","head","options"],function(e){Te.prototype[e]=function(t,s){return this.request(Ie(s||{},{method:e,url:t,data:(s||{}).data}))}});f.forEach(["post","put","patch"],function(e){function t(s){return function(r,o,a){return this.request(Ie(a||{},{method:e,headers:s?{"Content-Type":"multipart/form-data"}:{},url:r,data:o}))}}Te.prototype[e]=t(),Te.prototype[e+"Form"]=t(!0)});let kl=class cr{constructor(e){if(typeof e!="function")throw new TypeError("executor must be a function.");let t;this.promise=new Promise(function(r){t=r});const s=this;this.promise.then(i=>{if(!s._listeners)return;let r=s._listeners.length;for(;r-- >0;)s._listeners[r](i);s._listeners=null}),this.promise.then=i=>{let r;const o=new Promise(a=>{s.subscribe(a),r=a}).then(i);return o.cancel=function(){s.unsubscribe(r)},o},e(function(r,o,a){s.reason||(s.reason=new je(r,o,a),t(s.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);t!==-1&&this._listeners.splice(t,1)}toAbortSignal(){const e=new AbortController,t=s=>{e.abort(s)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let e;return{token:new cr(function(i){e=i}),cancel:e}}};function xl(n){return function(t){return n.apply(null,t)}}function Ol(n){return f.isObject(n)&&n.isAxiosError===!0}const Dn={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(Dn).forEach(([n,e])=>{Dn[e]=n});function ur(n){const e=new Te(n),t=Hi(Te.prototype.request,e);return f.extend(t,Te.prototype,e,{allOwnKeys:!0}),f.extend(t,e,null,{allOwnKeys:!0}),t.create=function(i){return ur(Ie(n,i))},t}const T=ur(gt);T.Axios=Te;T.CanceledError=je;T.CancelToken=kl;T.isCancel=tr;T.VERSION=lr;T.toFormData=tn;T.AxiosError=w;T.Cancel=T.CanceledError;T.all=function(e){return Promise.all(e)};T.spread=xl;T.isAxiosError=Ol;T.mergeConfig=Ie;T.AxiosHeaders=z;T.formToJSON=n=>er(f.isHTMLForm(n)?new FormData(n):n);T.getAdapter=ar.getAdapter;T.HttpStatusCode=Dn;T.default=T;const{Axios:Of,AxiosError:Df,CanceledError:Pf,isCancel:Mf,CancelToken:Lf,VERSION:Ff,all:Uf,Cancel:Bf,isAxiosError:Wf,spread:Hf,toFormData:Vf,AxiosHeaders:qf,HttpStatusCode:$f,formToJSON:jf,getAdapter:zf,mergeConfig:Gf}=T;class hr{constructor(e,t){Q(this,"backendUrl","http://localhost:5001");Q(this,"username");Q(this,"password");this.username=e,this.password=t}}class Dl extends hr{constructor(e,t){super(e,t),this.backendUrl="http://localhost:5001"}async getToken(){try{return(await T.post(this.backendUrl.concat("/clientlogin"),{username:this.username,password:this.password})).data.access_token}catch(e){R.handleErrorResponse(e)}}async getAPIKey(e){e||R.throwKnownError(M.InvalidAccessTokenError);try{return(await T.post(this.backendUrl.concat("/clientgeturl"),{host_name:"www.nervoscan.com"},{headers:{Authorization:`Bearer ${e}`}})).data.url.split("?api_key=")[1]}catch(t){R.handleErrorResponse(t)}}async uploadVideoToServer(e,t,s){(!t||!s)&&R.throwKnownError(M.InvalidAccessTokenError);try{const i=new FormData;return i.append("file",e,"recording.webm"),i.append("data",JSON.stringify({uuid:s,meta_data:{}})),(await T.post(this.backendUrl.concat("/submitscan"),i,{headers:{"Content-Type":"multipart/form-data",Authorization:`Bearer ${t}`}})).data}catch(i){throw console.error("Error uploading video:",i),i.response?(console.error("Error response:",i.response.data),console.error("Error status:",i.response.status),console.error("Error headers:",i.response.headers)):i.request?console.error("Error request:",i.request):console.error("Error message:",i.message),i}}async getResults(e,t){var s;t||R.throwKnownError(M.InvalidAccessTokenError);try{const i=await T.post(this.backendUrl.concat("/getcustomerinfo"),{mode:"selection",api_keys:[e]},{headers:{Authorization:`Bearer ${t}`}});return((s=i.data)==null?void 0:s.success)===!1&&R.throwKnownError(M.NoScanDataError),i.data}catch(i){console.error("Error getting results:",i),R.handleErrorResponse(i)}}async checkResults(e,t){try{t||R.throwKnownError(M.InvalidAccessTokenError);const r=(await T.post(this.backendUrl.concat("/check"),{api_key:e},{headers:{Authorization:`Bearer ${t}`}})).data.job_status;return r==="Completed"||r==="Failed"?r:"Pending"}catch(s){R.handleErrorResponse(s)}}}class Pl extends hr{constructor(e,t){super(e,t),this.backendUrl="https://backendv2-dev.nervoscan.com"}async getToken(){try{const e=await T.post(this.backendUrl.concat("/user/login"),{username:this.username,password:this.password});if(e.data.success===!1)R.throwKnownError(M.InvalidUsernameError);else return JSON.parse(e.data.body).idToken}catch(e){console.error("error printed in serverless repository",e),R.handleErrorResponse(e)}}async getAPIKey(e){e||R.throwKnownError(M.InvalidAccessTokenError);try{return(await T.post(this.backendUrl.concat("/get-redirection-url"),{host_name:"www.nervoscan.com",username:this.username},{headers:{Authorization:`Bearer ${e}`}})).data.url.split("?api_key=")[1]}catch(t){R.handleErrorResponse(t)}}async uploadVideoToServer(e,t,s){(!t||!s)&&R.throwKnownError(M.InvalidAccessTokenError);try{const i=await this.generatePreSignedUrl(s);return i||R.throwKnownError(M.InvalidAccessTokenError),await this.uploadVideoToS3(e,i)}catch(i){throw console.error("Error uploading video:",i),i.response?(console.error("Error response:",i.response.data),console.error("Error status:",i.response.status),console.error("Error headers:",i.response.headers)):i.request?console.error("Error request:",i.request):console.error("Error message:",i.message),i}}getResults(e,t){return console.log("not implemented"),Promise.resolve(void 0)}async checkResults(e,t){try{t||R.throwKnownError(M.InvalidAccessTokenError);const r=(await T.post(this.backendUrl.concat("/check"),{api_key:e},{headers:{Authorization:`Bearer ${t}`}})).data.job_status;return r==="Completed"||r==="Failed"?r:"Pending"}catch(s){R.handleErrorResponse(s)}}async generatePreSignedUrl(e){try{return(await T.get(this.backendUrl.concat("/generate-presigned-url?job_id="+e))).data.upload_url}catch(t){R.handleErrorResponse(t)}}async uploadVideoToS3(e,t){try{return(await T.put(t,e,{headers:{"Content-Type":"video/mp4"}})).data}catch(s){R.handleErrorResponse(s)}}}const Ml=()=>{};/**
7
+ * @license
8
+ * Copyright 2017 Google LLC
9
+ *
10
+ * Licensed under the Apache License, Version 2.0 (the "License");
11
+ * you may not use this file except in compliance with the License.
12
+ * You may obtain a copy of the License at
13
+ *
14
+ * http://www.apache.org/licenses/LICENSE-2.0
15
+ *
16
+ * Unless required by applicable law or agreed to in writing, software
17
+ * distributed under the License is distributed on an "AS IS" BASIS,
18
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
+ * See the License for the specific language governing permissions and
20
+ * limitations under the License.
21
+ */const dr={NODE_ADMIN:!1,SDK_VERSION:"${JSCORE_VERSION}"};/**
22
+ * @license
23
+ * Copyright 2017 Google LLC
24
+ *
25
+ * Licensed under the Apache License, Version 2.0 (the "License");
26
+ * you may not use this file except in compliance with the License.
27
+ * You may obtain a copy of the License at
28
+ *
29
+ * http://www.apache.org/licenses/LICENSE-2.0
30
+ *
31
+ * Unless required by applicable law or agreed to in writing, software
32
+ * distributed under the License is distributed on an "AS IS" BASIS,
33
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
34
+ * See the License for the specific language governing permissions and
35
+ * limitations under the License.
36
+ */const m=function(n,e){if(!n)throw ze(e)},ze=function(n){return new Error("Firebase Database ("+dr.SDK_VERSION+") INTERNAL ASSERT FAILED: "+n)};/**
37
+ * @license
38
+ * Copyright 2017 Google LLC
39
+ *
40
+ * Licensed under the Apache License, Version 2.0 (the "License");
41
+ * you may not use this file except in compliance with the License.
42
+ * You may obtain a copy of the License at
43
+ *
44
+ * http://www.apache.org/licenses/LICENSE-2.0
45
+ *
46
+ * Unless required by applicable law or agreed to in writing, software
47
+ * distributed under the License is distributed on an "AS IS" BASIS,
48
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
49
+ * See the License for the specific language governing permissions and
50
+ * limitations under the License.
51
+ */const fr=function(n){const e=[];let t=0;for(let s=0;s<n.length;s++){let i=n.charCodeAt(s);i<128?e[t++]=i:i<2048?(e[t++]=i>>6|192,e[t++]=i&63|128):(i&64512)===55296&&s+1<n.length&&(n.charCodeAt(s+1)&64512)===56320?(i=65536+((i&1023)<<10)+(n.charCodeAt(++s)&1023),e[t++]=i>>18|240,e[t++]=i>>12&63|128,e[t++]=i>>6&63|128,e[t++]=i&63|128):(e[t++]=i>>12|224,e[t++]=i>>6&63|128,e[t++]=i&63|128)}return e},Ll=function(n){const e=[];let t=0,s=0;for(;t<n.length;){const i=n[t++];if(i<128)e[s++]=String.fromCharCode(i);else if(i>191&&i<224){const r=n[t++];e[s++]=String.fromCharCode((i&31)<<6|r&63)}else if(i>239&&i<365){const r=n[t++],o=n[t++],a=n[t++],c=((i&7)<<18|(r&63)<<12|(o&63)<<6|a&63)-65536;e[s++]=String.fromCharCode(55296+(c>>10)),e[s++]=String.fromCharCode(56320+(c&1023))}else{const r=n[t++],o=n[t++];e[s++]=String.fromCharCode((i&15)<<12|(r&63)<<6|o&63)}}return e.join("")},ns={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:typeof atob=="function",encodeByteArray(n,e){if(!Array.isArray(n))throw Error("encodeByteArray takes an array as a parameter");this.init_();const t=e?this.byteToCharMapWebSafe_:this.byteToCharMap_,s=[];for(let i=0;i<n.length;i+=3){const r=n[i],o=i+1<n.length,a=o?n[i+1]:0,c=i+2<n.length,l=c?n[i+2]:0,u=r>>2,h=(r&3)<<4|a>>4;let d=(a&15)<<2|l>>6,_=l&63;c||(_=64,o||(d=64)),s.push(t[u],t[h],t[d],t[_])}return s.join("")},encodeString(n,e){return this.HAS_NATIVE_SUPPORT&&!e?btoa(n):this.encodeByteArray(fr(n),e)},decodeString(n,e){return this.HAS_NATIVE_SUPPORT&&!e?atob(n):Ll(this.decodeStringToByteArray(n,e))},decodeStringToByteArray(n,e){this.init_();const t=e?this.charToByteMapWebSafe_:this.charToByteMap_,s=[];for(let i=0;i<n.length;){const r=t[n.charAt(i++)],a=i<n.length?t[n.charAt(i)]:0;++i;const l=i<n.length?t[n.charAt(i)]:64;++i;const h=i<n.length?t[n.charAt(i)]:64;if(++i,r==null||a==null||l==null||h==null)throw new Fl;const d=r<<2|a>>4;if(s.push(d),l!==64){const _=a<<4&240|l>>2;if(s.push(_),h!==64){const p=l<<6&192|h;s.push(p)}}}return s},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let n=0;n<this.ENCODED_VALS.length;n++)this.byteToCharMap_[n]=this.ENCODED_VALS.charAt(n),this.charToByteMap_[this.byteToCharMap_[n]]=n,this.byteToCharMapWebSafe_[n]=this.ENCODED_VALS_WEBSAFE.charAt(n),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[n]]=n,n>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(n)]=n,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(n)]=n)}}};class Fl extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}const pr=function(n){const e=fr(n);return ns.encodeByteArray(e,!0)},Pt=function(n){return pr(n).replace(/\./g,"")},Pn=function(n){try{return ns.decodeString(n,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};/**
52
+ * @license
53
+ * Copyright 2017 Google LLC
54
+ *
55
+ * Licensed under the Apache License, Version 2.0 (the "License");
56
+ * you may not use this file except in compliance with the License.
57
+ * You may obtain a copy of the License at
58
+ *
59
+ * http://www.apache.org/licenses/LICENSE-2.0
60
+ *
61
+ * Unless required by applicable law or agreed to in writing, software
62
+ * distributed under the License is distributed on an "AS IS" BASIS,
63
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
64
+ * See the License for the specific language governing permissions and
65
+ * limitations under the License.
66
+ */function Ul(n){return _r(void 0,n)}function _r(n,e){if(!(e instanceof Object))return e;switch(e.constructor){case Date:const t=e;return new Date(t.getTime());case Object:n===void 0&&(n={});break;case Array:n=[];break;default:return e}for(const t in e)!e.hasOwnProperty(t)||!Bl(t)||(n[t]=_r(n[t],e[t]));return n}function Bl(n){return n!=="__proto__"}/**
67
+ * @license
68
+ * Copyright 2022 Google LLC
69
+ *
70
+ * Licensed under the Apache License, Version 2.0 (the "License");
71
+ * you may not use this file except in compliance with the License.
72
+ * You may obtain a copy of the License at
73
+ *
74
+ * http://www.apache.org/licenses/LICENSE-2.0
75
+ *
76
+ * Unless required by applicable law or agreed to in writing, software
77
+ * distributed under the License is distributed on an "AS IS" BASIS,
78
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
79
+ * See the License for the specific language governing permissions and
80
+ * limitations under the License.
81
+ */function Wl(){if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global;throw new Error("Unable to locate global object.")}/**
82
+ * @license
83
+ * Copyright 2022 Google LLC
84
+ *
85
+ * Licensed under the Apache License, Version 2.0 (the "License");
86
+ * you may not use this file except in compliance with the License.
87
+ * You may obtain a copy of the License at
88
+ *
89
+ * http://www.apache.org/licenses/LICENSE-2.0
90
+ *
91
+ * Unless required by applicable law or agreed to in writing, software
92
+ * distributed under the License is distributed on an "AS IS" BASIS,
93
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
94
+ * See the License for the specific language governing permissions and
95
+ * limitations under the License.
96
+ */const Hl=()=>Wl().__FIREBASE_DEFAULTS__,Vl=()=>{if(typeof process>"u"||typeof process.env>"u")return;const n=process.env.__FIREBASE_DEFAULTS__;if(n)return JSON.parse(n)},ql=()=>{if(typeof document>"u")return;let n;try{n=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch{return}const e=n&&Pn(n[1]);return e&&JSON.parse(e)},mr=()=>{try{return Ml()||Hl()||Vl()||ql()}catch(n){console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${n}`);return}},$l=n=>{var e,t;return(t=(e=mr())===null||e===void 0?void 0:e.emulatorHosts)===null||t===void 0?void 0:t[n]},jl=n=>{const e=$l(n);if(!e)return;const t=e.lastIndexOf(":");if(t<=0||t+1===e.length)throw new Error(`Invalid host ${e} with no separate hostname and port!`);const s=parseInt(e.substring(t+1),10);return e[0]==="["?[e.substring(1,t-1),s]:[e.substring(0,t),s]},gr=()=>{var n;return(n=mr())===null||n===void 0?void 0:n.config};/**
97
+ * @license
98
+ * Copyright 2017 Google LLC
99
+ *
100
+ * Licensed under the Apache License, Version 2.0 (the "License");
101
+ * you may not use this file except in compliance with the License.
102
+ * You may obtain a copy of the License at
103
+ *
104
+ * http://www.apache.org/licenses/LICENSE-2.0
105
+ *
106
+ * Unless required by applicable law or agreed to in writing, software
107
+ * distributed under the License is distributed on an "AS IS" BASIS,
108
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
109
+ * See the License for the specific language governing permissions and
110
+ * limitations under the License.
111
+ */class ss{constructor(){this.reject=()=>{},this.resolve=()=>{},this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}wrapCallback(e){return(t,s)=>{t?this.reject(t):this.resolve(s),typeof e=="function"&&(this.promise.catch(()=>{}),e.length===1?e(t):e(t,s))}}}/**
112
+ * @license
113
+ * Copyright 2021 Google LLC
114
+ *
115
+ * Licensed under the Apache License, Version 2.0 (the "License");
116
+ * you may not use this file except in compliance with the License.
117
+ * You may obtain a copy of the License at
118
+ *
119
+ * http://www.apache.org/licenses/LICENSE-2.0
120
+ *
121
+ * Unless required by applicable law or agreed to in writing, software
122
+ * distributed under the License is distributed on an "AS IS" BASIS,
123
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
124
+ * See the License for the specific language governing permissions and
125
+ * limitations under the License.
126
+ */function zl(n,e){if(n.uid)throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.');const t={alg:"none",type:"JWT"},s=e||"demo-project",i=n.iat||0,r=n.sub||n.user_id;if(!r)throw new Error("mockUserToken must contain 'sub' or 'user_id' field!");const o=Object.assign({iss:`https://securetoken.google.com/${s}`,aud:s,iat:i,exp:i+3600,auth_time:i,sub:r,user_id:r,firebase:{sign_in_provider:"custom",identities:{}}},n);return[Pt(JSON.stringify(t)),Pt(JSON.stringify(o)),""].join(".")}/**
127
+ * @license
128
+ * Copyright 2017 Google LLC
129
+ *
130
+ * Licensed under the Apache License, Version 2.0 (the "License");
131
+ * you may not use this file except in compliance with the License.
132
+ * You may obtain a copy of the License at
133
+ *
134
+ * http://www.apache.org/licenses/LICENSE-2.0
135
+ *
136
+ * Unless required by applicable law or agreed to in writing, software
137
+ * distributed under the License is distributed on an "AS IS" BASIS,
138
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
139
+ * See the License for the specific language governing permissions and
140
+ * limitations under the License.
141
+ */function Gl(){return typeof navigator<"u"&&typeof navigator.userAgent=="string"?navigator.userAgent:""}function yr(){return typeof window<"u"&&!!(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(Gl())}function Kl(){return typeof navigator=="object"&&navigator.product==="ReactNative"}function Yl(){return dr.NODE_ADMIN===!0}function Ql(){try{return typeof indexedDB=="object"}catch{return!1}}function Jl(){return new Promise((n,e)=>{try{let t=!0;const s="validate-browser-context-for-indexeddb-analytics-module",i=self.indexedDB.open(s);i.onsuccess=()=>{i.result.close(),t||self.indexedDB.deleteDatabase(s),n(!0)},i.onupgradeneeded=()=>{t=!1},i.onerror=()=>{var r;e(((r=i.error)===null||r===void 0?void 0:r.message)||"")}}catch(t){e(t)}})}/**
142
+ * @license
143
+ * Copyright 2017 Google LLC
144
+ *
145
+ * Licensed under the Apache License, Version 2.0 (the "License");
146
+ * you may not use this file except in compliance with the License.
147
+ * You may obtain a copy of the License at
148
+ *
149
+ * http://www.apache.org/licenses/LICENSE-2.0
150
+ *
151
+ * Unless required by applicable law or agreed to in writing, software
152
+ * distributed under the License is distributed on an "AS IS" BASIS,
153
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
154
+ * See the License for the specific language governing permissions and
155
+ * limitations under the License.
156
+ */const Xl="FirebaseError";class yt extends Error{constructor(e,t,s){super(t),this.code=e,this.customData=s,this.name=Xl,Object.setPrototypeOf(this,yt.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,Er.prototype.create)}}class Er{constructor(e,t,s){this.service=e,this.serviceName=t,this.errors=s}create(e,...t){const s=t[0]||{},i=`${this.service}/${e}`,r=this.errors[e],o=r?Zl(r,s):"Error",a=`${this.serviceName}: ${o} (${i}).`;return new yt(i,a,s)}}function Zl(n,e){return n.replace(ec,(t,s)=>{const i=e[s];return i!=null?String(i):`<${s}?>`})}const ec=/\{\$([^}]+)}/g;/**
157
+ * @license
158
+ * Copyright 2017 Google LLC
159
+ *
160
+ * Licensed under the Apache License, Version 2.0 (the "License");
161
+ * you may not use this file except in compliance with the License.
162
+ * You may obtain a copy of the License at
163
+ *
164
+ * http://www.apache.org/licenses/LICENSE-2.0
165
+ *
166
+ * Unless required by applicable law or agreed to in writing, software
167
+ * distributed under the License is distributed on an "AS IS" BASIS,
168
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
169
+ * See the License for the specific language governing permissions and
170
+ * limitations under the License.
171
+ */function ot(n){return JSON.parse(n)}function B(n){return JSON.stringify(n)}/**
172
+ * @license
173
+ * Copyright 2017 Google LLC
174
+ *
175
+ * Licensed under the Apache License, Version 2.0 (the "License");
176
+ * you may not use this file except in compliance with the License.
177
+ * You may obtain a copy of the License at
178
+ *
179
+ * http://www.apache.org/licenses/LICENSE-2.0
180
+ *
181
+ * Unless required by applicable law or agreed to in writing, software
182
+ * distributed under the License is distributed on an "AS IS" BASIS,
183
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
184
+ * See the License for the specific language governing permissions and
185
+ * limitations under the License.
186
+ */const wr=function(n){let e={},t={},s={},i="";try{const r=n.split(".");e=ot(Pn(r[0])||""),t=ot(Pn(r[1])||""),i=r[2],s=t.d||{},delete t.d}catch{}return{header:e,claims:t,data:s,signature:i}},tc=function(n){const e=wr(n),t=e.claims;return!!t&&typeof t=="object"&&t.hasOwnProperty("iat")},nc=function(n){const e=wr(n).claims;return typeof e=="object"&&e.admin===!0};/**
187
+ * @license
188
+ * Copyright 2017 Google LLC
189
+ *
190
+ * Licensed under the Apache License, Version 2.0 (the "License");
191
+ * you may not use this file except in compliance with the License.
192
+ * You may obtain a copy of the License at
193
+ *
194
+ * http://www.apache.org/licenses/LICENSE-2.0
195
+ *
196
+ * Unless required by applicable law or agreed to in writing, software
197
+ * distributed under the License is distributed on an "AS IS" BASIS,
198
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
199
+ * See the License for the specific language governing permissions and
200
+ * limitations under the License.
201
+ */function he(n,e){return Object.prototype.hasOwnProperty.call(n,e)}function We(n,e){if(Object.prototype.hasOwnProperty.call(n,e))return n[e]}function Ys(n){for(const e in n)if(Object.prototype.hasOwnProperty.call(n,e))return!1;return!0}function Mt(n,e,t){const s={};for(const i in n)Object.prototype.hasOwnProperty.call(n,i)&&(s[i]=e.call(t,n[i],i,n));return s}function Lt(n,e){if(n===e)return!0;const t=Object.keys(n),s=Object.keys(e);for(const i of t){if(!s.includes(i))return!1;const r=n[i],o=e[i];if(Qs(r)&&Qs(o)){if(!Lt(r,o))return!1}else if(r!==o)return!1}for(const i of s)if(!t.includes(i))return!1;return!0}function Qs(n){return n!==null&&typeof n=="object"}/**
202
+ * @license
203
+ * Copyright 2017 Google LLC
204
+ *
205
+ * Licensed under the Apache License, Version 2.0 (the "License");
206
+ * you may not use this file except in compliance with the License.
207
+ * You may obtain a copy of the License at
208
+ *
209
+ * http://www.apache.org/licenses/LICENSE-2.0
210
+ *
211
+ * Unless required by applicable law or agreed to in writing, software
212
+ * distributed under the License is distributed on an "AS IS" BASIS,
213
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
214
+ * See the License for the specific language governing permissions and
215
+ * limitations under the License.
216
+ */function sc(n){const e=[];for(const[t,s]of Object.entries(n))Array.isArray(s)?s.forEach(i=>{e.push(encodeURIComponent(t)+"="+encodeURIComponent(i))}):e.push(encodeURIComponent(t)+"="+encodeURIComponent(s));return e.length?"&"+e.join("&"):""}/**
217
+ * @license
218
+ * Copyright 2017 Google LLC
219
+ *
220
+ * Licensed under the Apache License, Version 2.0 (the "License");
221
+ * you may not use this file except in compliance with the License.
222
+ * You may obtain a copy of the License at
223
+ *
224
+ * http://www.apache.org/licenses/LICENSE-2.0
225
+ *
226
+ * Unless required by applicable law or agreed to in writing, software
227
+ * distributed under the License is distributed on an "AS IS" BASIS,
228
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
229
+ * See the License for the specific language governing permissions and
230
+ * limitations under the License.
231
+ */class ic{constructor(){this.chain_=[],this.buf_=[],this.W_=[],this.pad_=[],this.inbuf_=0,this.total_=0,this.blockSize=512/8,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 s=this.W_;if(typeof e=="string")for(let h=0;h<16;h++)s[h]=e.charCodeAt(t)<<24|e.charCodeAt(t+1)<<16|e.charCodeAt(t+2)<<8|e.charCodeAt(t+3),t+=4;else for(let h=0;h<16;h++)s[h]=e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3],t+=4;for(let h=16;h<80;h++){const d=s[h-3]^s[h-8]^s[h-14]^s[h-16];s[h]=(d<<1|d>>>31)&4294967295}let i=this.chain_[0],r=this.chain_[1],o=this.chain_[2],a=this.chain_[3],c=this.chain_[4],l,u;for(let h=0;h<80;h++){h<40?h<20?(l=a^r&(o^a),u=1518500249):(l=r^o^a,u=1859775393):h<60?(l=r&o|a&(r|o),u=2400959708):(l=r^o^a,u=3395469782);const d=(i<<5|i>>>27)+l+c+u+s[h]&4294967295;c=a,a=o,o=(r<<30|r>>>2)&4294967295,r=i,i=d}this.chain_[0]=this.chain_[0]+i&4294967295,this.chain_[1]=this.chain_[1]+r&4294967295,this.chain_[2]=this.chain_[2]+o&4294967295,this.chain_[3]=this.chain_[3]+a&4294967295,this.chain_[4]=this.chain_[4]+c&4294967295}update(e,t){if(e==null)return;t===void 0&&(t=e.length);const s=t-this.blockSize;let i=0;const r=this.buf_;let o=this.inbuf_;for(;i<t;){if(o===0)for(;i<=s;)this.compress_(e,i),i+=this.blockSize;if(typeof e=="string"){for(;i<t;)if(r[o]=e.charCodeAt(i),++o,++i,o===this.blockSize){this.compress_(r),o=0;break}}else for(;i<t;)if(r[o]=e[i],++o,++i,o===this.blockSize){this.compress_(r),o=0;break}}this.inbuf_=o,this.total_+=t}digest(){const e=[];let t=this.total_*8;this.inbuf_<56?this.update(this.pad_,56-this.inbuf_):this.update(this.pad_,this.blockSize-(this.inbuf_-56));for(let i=this.blockSize-1;i>=56;i--)this.buf_[i]=t&255,t/=256;this.compress_(this.buf_);let s=0;for(let i=0;i<5;i++)for(let r=24;r>=0;r-=8)e[s]=this.chain_[i]>>r&255,++s;return e}}function vr(n,e){return`${n} failed: ${e} argument `}/**
232
+ * @license
233
+ * Copyright 2017 Google LLC
234
+ *
235
+ * Licensed under the Apache License, Version 2.0 (the "License");
236
+ * you may not use this file except in compliance with the License.
237
+ * You may obtain a copy of the License at
238
+ *
239
+ * http://www.apache.org/licenses/LICENSE-2.0
240
+ *
241
+ * Unless required by applicable law or agreed to in writing, software
242
+ * distributed under the License is distributed on an "AS IS" BASIS,
243
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
244
+ * See the License for the specific language governing permissions and
245
+ * limitations under the License.
246
+ */const rc=function(n){const e=[];let t=0;for(let s=0;s<n.length;s++){let i=n.charCodeAt(s);if(i>=55296&&i<=56319){const r=i-55296;s++,m(s<n.length,"Surrogate pair missing trail surrogate.");const o=n.charCodeAt(s)-56320;i=65536+(r<<10)+o}i<128?e[t++]=i:i<2048?(e[t++]=i>>6|192,e[t++]=i&63|128):i<65536?(e[t++]=i>>12|224,e[t++]=i>>6&63|128,e[t++]=i&63|128):(e[t++]=i>>18|240,e[t++]=i>>12&63|128,e[t++]=i>>6&63|128,e[t++]=i&63|128)}return e},rn=function(n){let e=0;for(let t=0;t<n.length;t++){const s=n.charCodeAt(t);s<128?e++:s<2048?e+=2:s>=55296&&s<=56319?(e+=4,t++):e+=3}return e};/**
247
+ * @license
248
+ * Copyright 2021 Google LLC
249
+ *
250
+ * Licensed under the Apache License, Version 2.0 (the "License");
251
+ * you may not use this file except in compliance with the License.
252
+ * You may obtain a copy of the License at
253
+ *
254
+ * http://www.apache.org/licenses/LICENSE-2.0
255
+ *
256
+ * Unless required by applicable law or agreed to in writing, software
257
+ * distributed under the License is distributed on an "AS IS" BASIS,
258
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
259
+ * See the License for the specific language governing permissions and
260
+ * limitations under the License.
261
+ */function on(n){return n&&n._delegate?n._delegate:n}class at{constructor(e,t,s){this.name=e,this.instanceFactory=t,this.type=s,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}}/**
262
+ * @license
263
+ * Copyright 2019 Google LLC
264
+ *
265
+ * Licensed under the Apache License, Version 2.0 (the "License");
266
+ * you may not use this file except in compliance with the License.
267
+ * You may obtain a copy of the License at
268
+ *
269
+ * http://www.apache.org/licenses/LICENSE-2.0
270
+ *
271
+ * Unless required by applicable law or agreed to in writing, software
272
+ * distributed under the License is distributed on an "AS IS" BASIS,
273
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
274
+ * See the License for the specific language governing permissions and
275
+ * limitations under the License.
276
+ */const we="[DEFAULT]";/**
277
+ * @license
278
+ * Copyright 2019 Google LLC
279
+ *
280
+ * Licensed under the Apache License, Version 2.0 (the "License");
281
+ * you may not use this file except in compliance with the License.
282
+ * You may obtain a copy of the License at
283
+ *
284
+ * http://www.apache.org/licenses/LICENSE-2.0
285
+ *
286
+ * Unless required by applicable law or agreed to in writing, software
287
+ * distributed under the License is distributed on an "AS IS" BASIS,
288
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
289
+ * See the License for the specific language governing permissions and
290
+ * limitations under the License.
291
+ */class oc{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 s=new ss;if(this.instancesDeferred.set(t,s),this.isInitialized(t)||this.shouldAutoInitialize())try{const i=this.getOrInitializeService({instanceIdentifier:t});i&&s.resolve(i)}catch{}}return this.instancesDeferred.get(t).promise}getImmediate(e){var t;const s=this.normalizeInstanceIdentifier(e==null?void 0:e.identifier),i=(t=e==null?void 0:e.optional)!==null&&t!==void 0?t:!1;if(this.isInitialized(s)||this.shouldAutoInitialize())try{return this.getOrInitializeService({instanceIdentifier:s})}catch(r){if(i)return null;throw r}else{if(i)return null;throw Error(`Service ${this.name} is not available`)}}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(lc(e))try{this.getOrInitializeService({instanceIdentifier:we})}catch{}for(const[t,s]of this.instancesDeferred.entries()){const i=this.normalizeInstanceIdentifier(t);try{const r=this.getOrInitializeService({instanceIdentifier:i});s.resolve(r)}catch{}}}}clearInstance(e=we){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(t=>"INTERNAL"in t).map(t=>t.INTERNAL.delete()),...e.filter(t=>"_delete"in t).map(t=>t._delete())])}isComponentSet(){return this.component!=null}isInitialized(e=we){return this.instances.has(e)}getOptions(e=we){return this.instancesOptions.get(e)||{}}initialize(e={}){const{options:t={}}=e,s=this.normalizeInstanceIdentifier(e.instanceIdentifier);if(this.isInitialized(s))throw Error(`${this.name}(${s}) has already been initialized`);if(!this.isComponentSet())throw Error(`Component ${this.name} has not been registered yet`);const i=this.getOrInitializeService({instanceIdentifier:s,options:t});for(const[r,o]of this.instancesDeferred.entries()){const a=this.normalizeInstanceIdentifier(r);s===a&&o.resolve(i)}return i}onInit(e,t){var s;const i=this.normalizeInstanceIdentifier(t),r=(s=this.onInitCallbacks.get(i))!==null&&s!==void 0?s:new Set;r.add(e),this.onInitCallbacks.set(i,r);const o=this.instances.get(i);return o&&e(o,i),()=>{r.delete(e)}}invokeOnInitCallbacks(e,t){const s=this.onInitCallbacks.get(t);if(s)for(const i of s)try{i(e,t)}catch{}}getOrInitializeService({instanceIdentifier:e,options:t={}}){let s=this.instances.get(e);if(!s&&this.component&&(s=this.component.instanceFactory(this.container,{instanceIdentifier:ac(e),options:t}),this.instances.set(e,s),this.instancesOptions.set(e,t),this.invokeOnInitCallbacks(s,e),this.component.onInstanceCreated))try{this.component.onInstanceCreated(this.container,e,s)}catch{}return s||null}normalizeInstanceIdentifier(e=we){return this.component?this.component.multipleInstances?e:we:e}shouldAutoInitialize(){return!!this.component&&this.component.instantiationMode!=="EXPLICIT"}}function ac(n){return n===we?void 0:n}function lc(n){return n.instantiationMode==="EAGER"}/**
292
+ * @license
293
+ * Copyright 2019 Google LLC
294
+ *
295
+ * Licensed under the Apache License, Version 2.0 (the "License");
296
+ * you may not use this file except in compliance with the License.
297
+ * You may obtain a copy of the License at
298
+ *
299
+ * http://www.apache.org/licenses/LICENSE-2.0
300
+ *
301
+ * Unless required by applicable law or agreed to in writing, software
302
+ * distributed under the License is distributed on an "AS IS" BASIS,
303
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
304
+ * See the License for the specific language governing permissions and
305
+ * limitations under the License.
306
+ */class cc{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 oc(e,this);return this.providers.set(e,t),t}getProviders(){return Array.from(this.providers.values())}}/**
307
+ * @license
308
+ * Copyright 2017 Google LLC
309
+ *
310
+ * Licensed under the Apache License, Version 2.0 (the "License");
311
+ * you may not use this file except in compliance with the License.
312
+ * You may obtain a copy of the License at
313
+ *
314
+ * http://www.apache.org/licenses/LICENSE-2.0
315
+ *
316
+ * Unless required by applicable law or agreed to in writing, software
317
+ * distributed under the License is distributed on an "AS IS" BASIS,
318
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
319
+ * See the License for the specific language governing permissions and
320
+ * limitations under the License.
321
+ */var A;(function(n){n[n.DEBUG=0]="DEBUG",n[n.VERBOSE=1]="VERBOSE",n[n.INFO=2]="INFO",n[n.WARN=3]="WARN",n[n.ERROR=4]="ERROR",n[n.SILENT=5]="SILENT"})(A||(A={}));const uc={debug:A.DEBUG,verbose:A.VERBOSE,info:A.INFO,warn:A.WARN,error:A.ERROR,silent:A.SILENT},hc=A.INFO,dc={[A.DEBUG]:"log",[A.VERBOSE]:"log",[A.INFO]:"info",[A.WARN]:"warn",[A.ERROR]:"error"},fc=(n,e,...t)=>{if(e<n.logLevel)return;const s=new Date().toISOString(),i=dc[e];if(i)console[i](`[${s}] ${n.name}:`,...t);else throw new Error(`Attempted to log a message with an invalid logType (value: ${e})`)};class Cr{constructor(e){this.name=e,this._logLevel=hc,this._logHandler=fc,this._userLogHandler=null}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in A))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel=typeof e=="string"?uc[e]:e}get logHandler(){return this._logHandler}set logHandler(e){if(typeof e!="function")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,A.DEBUG,...e),this._logHandler(this,A.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,A.VERBOSE,...e),this._logHandler(this,A.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,A.INFO,...e),this._logHandler(this,A.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,A.WARN,...e),this._logHandler(this,A.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,A.ERROR,...e),this._logHandler(this,A.ERROR,...e)}}const pc=(n,e)=>e.some(t=>n instanceof t);let Js,Xs;function _c(){return Js||(Js=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function mc(){return Xs||(Xs=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}const br=new WeakMap,Mn=new WeakMap,Sr=new WeakMap,gn=new WeakMap,is=new WeakMap;function gc(n){const e=new Promise((t,s)=>{const i=()=>{n.removeEventListener("success",r),n.removeEventListener("error",o)},r=()=>{t(pe(n.result)),i()},o=()=>{s(n.error),i()};n.addEventListener("success",r),n.addEventListener("error",o)});return e.then(t=>{t instanceof IDBCursor&&br.set(t,n)}).catch(()=>{}),is.set(e,n),e}function yc(n){if(Mn.has(n))return;const e=new Promise((t,s)=>{const i=()=>{n.removeEventListener("complete",r),n.removeEventListener("error",o),n.removeEventListener("abort",o)},r=()=>{t(),i()},o=()=>{s(n.error||new DOMException("AbortError","AbortError")),i()};n.addEventListener("complete",r),n.addEventListener("error",o),n.addEventListener("abort",o)});Mn.set(n,e)}let Ln={get(n,e,t){if(n instanceof IDBTransaction){if(e==="done")return Mn.get(n);if(e==="objectStoreNames")return n.objectStoreNames||Sr.get(n);if(e==="store")return t.objectStoreNames[1]?void 0:t.objectStore(t.objectStoreNames[0])}return pe(n[e])},set(n,e,t){return n[e]=t,!0},has(n,e){return n instanceof IDBTransaction&&(e==="done"||e==="store")?!0:e in n}};function Ec(n){Ln=n(Ln)}function wc(n){return n===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(e,...t){const s=n.call(yn(this),e,...t);return Sr.set(s,e.sort?e.sort():[e]),pe(s)}:mc().includes(n)?function(...e){return n.apply(yn(this),e),pe(br.get(this))}:function(...e){return pe(n.apply(yn(this),e))}}function vc(n){return typeof n=="function"?wc(n):(n instanceof IDBTransaction&&yc(n),pc(n,_c())?new Proxy(n,Ln):n)}function pe(n){if(n instanceof IDBRequest)return gc(n);if(gn.has(n))return gn.get(n);const e=vc(n);return e!==n&&(gn.set(n,e),is.set(e,n)),e}const yn=n=>is.get(n);function Cc(n,e,{blocked:t,upgrade:s,blocking:i,terminated:r}={}){const o=indexedDB.open(n,e),a=pe(o);return s&&o.addEventListener("upgradeneeded",c=>{s(pe(o.result),c.oldVersion,c.newVersion,pe(o.transaction),c)}),t&&o.addEventListener("blocked",c=>t(c.oldVersion,c.newVersion,c)),a.then(c=>{r&&c.addEventListener("close",()=>r()),i&&c.addEventListener("versionchange",l=>i(l.oldVersion,l.newVersion,l))}).catch(()=>{}),a}const bc=["get","getKey","getAll","getAllKeys","count"],Sc=["put","add","delete","clear"],En=new Map;function Zs(n,e){if(!(n instanceof IDBDatabase&&!(e in n)&&typeof e=="string"))return;if(En.get(e))return En.get(e);const t=e.replace(/FromIndex$/,""),s=e!==t,i=Sc.includes(t);if(!(t in(s?IDBIndex:IDBObjectStore).prototype)||!(i||bc.includes(t)))return;const r=async function(o,...a){const c=this.transaction(o,i?"readwrite":"readonly");let l=c.store;return s&&(l=l.index(a.shift())),(await Promise.all([l[t](...a),i&&c.done]))[0]};return En.set(e,r),r}Ec(n=>({...n,get:(e,t,s)=>Zs(e,t)||n.get(e,t,s),has:(e,t)=>!!Zs(e,t)||n.has(e,t)}));/**
322
+ * @license
323
+ * Copyright 2019 Google LLC
324
+ *
325
+ * Licensed under the Apache License, Version 2.0 (the "License");
326
+ * you may not use this file except in compliance with the License.
327
+ * You may obtain a copy of the License at
328
+ *
329
+ * http://www.apache.org/licenses/LICENSE-2.0
330
+ *
331
+ * Unless required by applicable law or agreed to in writing, software
332
+ * distributed under the License is distributed on an "AS IS" BASIS,
333
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
334
+ * See the License for the specific language governing permissions and
335
+ * limitations under the License.
336
+ */class Tc{constructor(e){this.container=e}getPlatformInfoString(){return this.container.getProviders().map(t=>{if(Ic(t)){const s=t.getImmediate();return`${s.library}/${s.version}`}else return null}).filter(t=>t).join(" ")}}function Ic(n){const e=n.getComponent();return(e==null?void 0:e.type)==="VERSION"}const Fn="@firebase/app",ei="0.11.5";/**
337
+ * @license
338
+ * Copyright 2019 Google LLC
339
+ *
340
+ * Licensed under the Apache License, Version 2.0 (the "License");
341
+ * you may not use this file except in compliance with the License.
342
+ * You may obtain a copy of the License at
343
+ *
344
+ * http://www.apache.org/licenses/LICENSE-2.0
345
+ *
346
+ * Unless required by applicable law or agreed to in writing, software
347
+ * distributed under the License is distributed on an "AS IS" BASIS,
348
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
349
+ * See the License for the specific language governing permissions and
350
+ * limitations under the License.
351
+ */const ce=new Cr("@firebase/app"),Rc="@firebase/app-compat",Nc="@firebase/analytics-compat",Ac="@firebase/analytics",kc="@firebase/app-check-compat",xc="@firebase/app-check",Oc="@firebase/auth",Dc="@firebase/auth-compat",Pc="@firebase/database",Mc="@firebase/data-connect",Lc="@firebase/database-compat",Fc="@firebase/functions",Uc="@firebase/functions-compat",Bc="@firebase/installations",Wc="@firebase/installations-compat",Hc="@firebase/messaging",Vc="@firebase/messaging-compat",qc="@firebase/performance",$c="@firebase/performance-compat",jc="@firebase/remote-config",zc="@firebase/remote-config-compat",Gc="@firebase/storage",Kc="@firebase/storage-compat",Yc="@firebase/firestore",Qc="@firebase/vertexai",Jc="@firebase/firestore-compat",Xc="firebase",Zc="11.6.1";/**
352
+ * @license
353
+ * Copyright 2019 Google LLC
354
+ *
355
+ * Licensed under the Apache License, Version 2.0 (the "License");
356
+ * you may not use this file except in compliance with the License.
357
+ * You may obtain a copy of the License at
358
+ *
359
+ * http://www.apache.org/licenses/LICENSE-2.0
360
+ *
361
+ * Unless required by applicable law or agreed to in writing, software
362
+ * distributed under the License is distributed on an "AS IS" BASIS,
363
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
364
+ * See the License for the specific language governing permissions and
365
+ * limitations under the License.
366
+ */const Un="[DEFAULT]",eu={[Fn]:"fire-core",[Rc]:"fire-core-compat",[Ac]:"fire-analytics",[Nc]:"fire-analytics-compat",[xc]:"fire-app-check",[kc]:"fire-app-check-compat",[Oc]:"fire-auth",[Dc]:"fire-auth-compat",[Pc]:"fire-rtdb",[Mc]:"fire-data-connect",[Lc]:"fire-rtdb-compat",[Fc]:"fire-fn",[Uc]:"fire-fn-compat",[Bc]:"fire-iid",[Wc]:"fire-iid-compat",[Hc]:"fire-fcm",[Vc]:"fire-fcm-compat",[qc]:"fire-perf",[$c]:"fire-perf-compat",[jc]:"fire-rc",[zc]:"fire-rc-compat",[Gc]:"fire-gcs",[Kc]:"fire-gcs-compat",[Yc]:"fire-fst",[Jc]:"fire-fst-compat",[Qc]:"fire-vertex","fire-js":"fire-js",[Xc]:"fire-js-all"};/**
367
+ * @license
368
+ * Copyright 2019 Google LLC
369
+ *
370
+ * Licensed under the Apache License, Version 2.0 (the "License");
371
+ * you may not use this file except in compliance with the License.
372
+ * You may obtain a copy of the License at
373
+ *
374
+ * http://www.apache.org/licenses/LICENSE-2.0
375
+ *
376
+ * Unless required by applicable law or agreed to in writing, software
377
+ * distributed under the License is distributed on an "AS IS" BASIS,
378
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
379
+ * See the License for the specific language governing permissions and
380
+ * limitations under the License.
381
+ */const Ft=new Map,tu=new Map,Bn=new Map;function ti(n,e){try{n.container.addComponent(e)}catch(t){ce.debug(`Component ${e.name} failed to register with FirebaseApp ${n.name}`,t)}}function Ut(n){const e=n.name;if(Bn.has(e))return ce.debug(`There were multiple attempts to register component ${e}.`),!1;Bn.set(e,n);for(const t of Ft.values())ti(t,n);for(const t of tu.values())ti(t,n);return!0}function nu(n,e){const t=n.container.getProvider("heartbeat").getImmediate({optional:!0});return t&&t.triggerHeartbeat(),n.container.getProvider(e)}function su(n){return n==null?!1:n.settings!==void 0}/**
382
+ * @license
383
+ * Copyright 2019 Google LLC
384
+ *
385
+ * Licensed under the Apache License, Version 2.0 (the "License");
386
+ * you may not use this file except in compliance with the License.
387
+ * You may obtain a copy of the License at
388
+ *
389
+ * http://www.apache.org/licenses/LICENSE-2.0
390
+ *
391
+ * Unless required by applicable law or agreed to in writing, software
392
+ * distributed under the License is distributed on an "AS IS" BASIS,
393
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
394
+ * See the License for the specific language governing permissions and
395
+ * limitations under the License.
396
+ */const iu={"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","server-app-deleted":"Firebase Server App has been 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}.","finalization-registry-not-supported":"FirebaseServerApp deleteOnDeref field defined but the JS runtime does not support FinalizationRegistry.","invalid-server-app-environment":"FirebaseServerApp is not for use in browser environments."},_e=new Er("app","Firebase",iu);/**
397
+ * @license
398
+ * Copyright 2019 Google LLC
399
+ *
400
+ * Licensed under the Apache License, Version 2.0 (the "License");
401
+ * you may not use this file except in compliance with the License.
402
+ * You may obtain a copy of the License at
403
+ *
404
+ * http://www.apache.org/licenses/LICENSE-2.0
405
+ *
406
+ * Unless required by applicable law or agreed to in writing, software
407
+ * distributed under the License is distributed on an "AS IS" BASIS,
408
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
409
+ * See the License for the specific language governing permissions and
410
+ * limitations under the License.
411
+ */class ru{constructor(e,t,s){this._isDeleted=!1,this._options=Object.assign({},e),this._config=Object.assign({},t),this._name=t.name,this._automaticDataCollectionEnabled=t.automaticDataCollectionEnabled,this._container=s,this.container.addComponent(new at("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 _e.create("app-deleted",{appName:this._name})}}/**
412
+ * @license
413
+ * Copyright 2019 Google LLC
414
+ *
415
+ * Licensed under the Apache License, Version 2.0 (the "License");
416
+ * you may not use this file except in compliance with the License.
417
+ * You may obtain a copy of the License at
418
+ *
419
+ * http://www.apache.org/licenses/LICENSE-2.0
420
+ *
421
+ * Unless required by applicable law or agreed to in writing, software
422
+ * distributed under the License is distributed on an "AS IS" BASIS,
423
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
424
+ * See the License for the specific language governing permissions and
425
+ * limitations under the License.
426
+ */const ou=Zc;function Tr(n,e={}){let t=n;typeof e!="object"&&(e={name:e});const s=Object.assign({name:Un,automaticDataCollectionEnabled:!1},e),i=s.name;if(typeof i!="string"||!i)throw _e.create("bad-app-name",{appName:String(i)});if(t||(t=gr()),!t)throw _e.create("no-options");const r=Ft.get(i);if(r){if(Lt(t,r.options)&&Lt(s,r.config))return r;throw _e.create("duplicate-app",{appName:i})}const o=new cc(i);for(const c of Bn.values())o.addComponent(c);const a=new ru(t,s,o);return Ft.set(i,a),a}function au(n=Un){const e=Ft.get(n);if(!e&&n===Un&&gr())return Tr();if(!e)throw _e.create("no-app",{appName:n});return e}function Le(n,e,t){var s;let i=(s=eu[n])!==null&&s!==void 0?s:n;t&&(i+=`-${t}`);const r=i.match(/\s|\//),o=e.match(/\s|\//);if(r||o){const a=[`Unable to register library "${i}" with version "${e}":`];r&&a.push(`library name "${i}" contains illegal characters (whitespace or "/")`),r&&o&&a.push("and"),o&&a.push(`version name "${e}" contains illegal characters (whitespace or "/")`),ce.warn(a.join(" "));return}Ut(new at(`${i}-version`,()=>({library:i,version:e}),"VERSION"))}/**
427
+ * @license
428
+ * Copyright 2021 Google LLC
429
+ *
430
+ * Licensed under the Apache License, Version 2.0 (the "License");
431
+ * you may not use this file except in compliance with the License.
432
+ * You may obtain a copy of the License at
433
+ *
434
+ * http://www.apache.org/licenses/LICENSE-2.0
435
+ *
436
+ * Unless required by applicable law or agreed to in writing, software
437
+ * distributed under the License is distributed on an "AS IS" BASIS,
438
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
439
+ * See the License for the specific language governing permissions and
440
+ * limitations under the License.
441
+ */const lu="firebase-heartbeat-database",cu=1,lt="firebase-heartbeat-store";let wn=null;function Ir(){return wn||(wn=Cc(lu,cu,{upgrade:(n,e)=>{switch(e){case 0:try{n.createObjectStore(lt)}catch(t){console.warn(t)}}}}).catch(n=>{throw _e.create("idb-open",{originalErrorMessage:n.message})})),wn}async function uu(n){try{const t=(await Ir()).transaction(lt),s=await t.objectStore(lt).get(Rr(n));return await t.done,s}catch(e){if(e instanceof yt)ce.warn(e.message);else{const t=_e.create("idb-get",{originalErrorMessage:e==null?void 0:e.message});ce.warn(t.message)}}}async function ni(n,e){try{const s=(await Ir()).transaction(lt,"readwrite");await s.objectStore(lt).put(e,Rr(n)),await s.done}catch(t){if(t instanceof yt)ce.warn(t.message);else{const s=_e.create("idb-set",{originalErrorMessage:t==null?void 0:t.message});ce.warn(s.message)}}}function Rr(n){return`${n.name}!${n.options.appId}`}/**
442
+ * @license
443
+ * Copyright 2021 Google LLC
444
+ *
445
+ * Licensed under the Apache License, Version 2.0 (the "License");
446
+ * you may not use this file except in compliance with the License.
447
+ * You may obtain a copy of the License at
448
+ *
449
+ * http://www.apache.org/licenses/LICENSE-2.0
450
+ *
451
+ * Unless required by applicable law or agreed to in writing, software
452
+ * distributed under the License is distributed on an "AS IS" BASIS,
453
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
454
+ * See the License for the specific language governing permissions and
455
+ * limitations under the License.
456
+ */const hu=1024,du=30;class fu{constructor(e){this.container=e,this._heartbeatsCache=null;const t=this.container.getProvider("app").getImmediate();this._storage=new _u(t),this._heartbeatsCachePromise=this._storage.read().then(s=>(this._heartbeatsCache=s,s))}async triggerHeartbeat(){var e,t;try{const i=this.container.getProvider("platform-logger").getImmediate().getPlatformInfoString(),r=si();if(((e=this._heartbeatsCache)===null||e===void 0?void 0:e.heartbeats)==null&&(this._heartbeatsCache=await this._heartbeatsCachePromise,((t=this._heartbeatsCache)===null||t===void 0?void 0:t.heartbeats)==null)||this._heartbeatsCache.lastSentHeartbeatDate===r||this._heartbeatsCache.heartbeats.some(o=>o.date===r))return;if(this._heartbeatsCache.heartbeats.push({date:r,agent:i}),this._heartbeatsCache.heartbeats.length>du){const o=mu(this._heartbeatsCache.heartbeats);this._heartbeatsCache.heartbeats.splice(o,1)}return this._storage.overwrite(this._heartbeatsCache)}catch(s){ce.warn(s)}}async getHeartbeatsHeader(){var e;try{if(this._heartbeatsCache===null&&await this._heartbeatsCachePromise,((e=this._heartbeatsCache)===null||e===void 0?void 0:e.heartbeats)==null||this._heartbeatsCache.heartbeats.length===0)return"";const t=si(),{heartbeatsToSend:s,unsentEntries:i}=pu(this._heartbeatsCache.heartbeats),r=Pt(JSON.stringify({version:2,heartbeats:s}));return this._heartbeatsCache.lastSentHeartbeatDate=t,i.length>0?(this._heartbeatsCache.heartbeats=i,await this._storage.overwrite(this._heartbeatsCache)):(this._heartbeatsCache.heartbeats=[],this._storage.overwrite(this._heartbeatsCache)),r}catch(t){return ce.warn(t),""}}}function si(){return new Date().toISOString().substring(0,10)}function pu(n,e=hu){const t=[];let s=n.slice();for(const i of n){const r=t.find(o=>o.agent===i.agent);if(r){if(r.dates.push(i.date),ii(t)>e){r.dates.pop();break}}else if(t.push({agent:i.agent,dates:[i.date]}),ii(t)>e){t.pop();break}s=s.slice(1)}return{heartbeatsToSend:t,unsentEntries:s}}class _u{constructor(e){this.app=e,this._canUseIndexedDBPromise=this.runIndexedDBEnvironmentCheck()}async runIndexedDBEnvironmentCheck(){return Ql()?Jl().then(()=>!0).catch(()=>!1):!1}async read(){if(await this._canUseIndexedDBPromise){const t=await uu(this.app);return t!=null&&t.heartbeats?t:{heartbeats:[]}}else return{heartbeats:[]}}async overwrite(e){var t;if(await this._canUseIndexedDBPromise){const i=await this.read();return ni(this.app,{lastSentHeartbeatDate:(t=e.lastSentHeartbeatDate)!==null&&t!==void 0?t:i.lastSentHeartbeatDate,heartbeats:e.heartbeats})}else return}async add(e){var t;if(await this._canUseIndexedDBPromise){const i=await this.read();return ni(this.app,{lastSentHeartbeatDate:(t=e.lastSentHeartbeatDate)!==null&&t!==void 0?t:i.lastSentHeartbeatDate,heartbeats:[...i.heartbeats,...e.heartbeats]})}else return}}function ii(n){return Pt(JSON.stringify({version:2,heartbeats:n})).length}function mu(n){if(n.length===0)return-1;let e=0,t=n[0].date;for(let s=1;s<n.length;s++)n[s].date<t&&(t=n[s].date,e=s);return e}/**
457
+ * @license
458
+ * Copyright 2019 Google LLC
459
+ *
460
+ * Licensed under the Apache License, Version 2.0 (the "License");
461
+ * you may not use this file except in compliance with the License.
462
+ * You may obtain a copy of the License at
463
+ *
464
+ * http://www.apache.org/licenses/LICENSE-2.0
465
+ *
466
+ * Unless required by applicable law or agreed to in writing, software
467
+ * distributed under the License is distributed on an "AS IS" BASIS,
468
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
469
+ * See the License for the specific language governing permissions and
470
+ * limitations under the License.
471
+ */function gu(n){Ut(new at("platform-logger",e=>new Tc(e),"PRIVATE")),Ut(new at("heartbeat",e=>new fu(e),"PRIVATE")),Le(Fn,ei,n),Le(Fn,ei,"esm2017"),Le("fire-js","")}gu("");const ri="@firebase/database",oi="1.0.14";/**
472
+ * @license
473
+ * Copyright 2019 Google LLC
474
+ *
475
+ * Licensed under the Apache License, Version 2.0 (the "License");
476
+ * you may not use this file except in compliance with the License.
477
+ * You may obtain a copy of the License at
478
+ *
479
+ * http://www.apache.org/licenses/LICENSE-2.0
480
+ *
481
+ * Unless required by applicable law or agreed to in writing, software
482
+ * distributed under the License is distributed on an "AS IS" BASIS,
483
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
484
+ * See the License for the specific language governing permissions and
485
+ * limitations under the License.
486
+ */let Nr="";function yu(n){Nr=n}/**
487
+ * @license
488
+ * Copyright 2017 Google LLC
489
+ *
490
+ * Licensed under the Apache License, Version 2.0 (the "License");
491
+ * you may not use this file except in compliance with the License.
492
+ * You may obtain a copy of the License at
493
+ *
494
+ * http://www.apache.org/licenses/LICENSE-2.0
495
+ *
496
+ * Unless required by applicable law or agreed to in writing, software
497
+ * distributed under the License is distributed on an "AS IS" BASIS,
498
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
499
+ * See the License for the specific language governing permissions and
500
+ * limitations under the License.
501
+ */class Eu{constructor(e){this.domStorage_=e,this.prefix_="firebase:"}set(e,t){t==null?this.domStorage_.removeItem(this.prefixedName_(e)):this.domStorage_.setItem(this.prefixedName_(e),B(t))}get(e){const t=this.domStorage_.getItem(this.prefixedName_(e));return t==null?null:ot(t)}remove(e){this.domStorage_.removeItem(this.prefixedName_(e))}prefixedName_(e){return this.prefix_+e}toString(){return this.domStorage_.toString()}}/**
502
+ * @license
503
+ * Copyright 2017 Google LLC
504
+ *
505
+ * Licensed under the Apache License, Version 2.0 (the "License");
506
+ * you may not use this file except in compliance with the License.
507
+ * You may obtain a copy of the License at
508
+ *
509
+ * http://www.apache.org/licenses/LICENSE-2.0
510
+ *
511
+ * Unless required by applicable law or agreed to in writing, software
512
+ * distributed under the License is distributed on an "AS IS" BASIS,
513
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
514
+ * See the License for the specific language governing permissions and
515
+ * limitations under the License.
516
+ */class wu{constructor(){this.cache_={},this.isInMemoryStorage=!0}set(e,t){t==null?delete this.cache_[e]:this.cache_[e]=t}get(e){return he(this.cache_,e)?this.cache_[e]:null}remove(e){delete this.cache_[e]}}/**
517
+ * @license
518
+ * Copyright 2017 Google LLC
519
+ *
520
+ * Licensed under the Apache License, Version 2.0 (the "License");
521
+ * you may not use this file except in compliance with the License.
522
+ * You may obtain a copy of the License at
523
+ *
524
+ * http://www.apache.org/licenses/LICENSE-2.0
525
+ *
526
+ * Unless required by applicable law or agreed to in writing, software
527
+ * distributed under the License is distributed on an "AS IS" BASIS,
528
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
529
+ * See the License for the specific language governing permissions and
530
+ * limitations under the License.
531
+ */const Ar=function(n){try{if(typeof window<"u"&&typeof window[n]<"u"){const e=window[n];return e.setItem("firebase:sentinel","cache"),e.removeItem("firebase:sentinel"),new Eu(e)}}catch{}return new wu},Se=Ar("localStorage"),vu=Ar("sessionStorage");/**
532
+ * @license
533
+ * Copyright 2017 Google LLC
534
+ *
535
+ * Licensed under the Apache License, Version 2.0 (the "License");
536
+ * you may not use this file except in compliance with the License.
537
+ * You may obtain a copy of the License at
538
+ *
539
+ * http://www.apache.org/licenses/LICENSE-2.0
540
+ *
541
+ * Unless required by applicable law or agreed to in writing, software
542
+ * distributed under the License is distributed on an "AS IS" BASIS,
543
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
544
+ * See the License for the specific language governing permissions and
545
+ * limitations under the License.
546
+ */const Fe=new Cr("@firebase/database"),Cu=function(){let n=1;return function(){return n++}}(),kr=function(n){const e=rc(n),t=new ic;t.update(e);const s=t.digest();return ns.encodeByteArray(s)},Et=function(...n){let e="";for(let t=0;t<n.length;t++){const s=n[t];Array.isArray(s)||s&&typeof s=="object"&&typeof s.length=="number"?e+=Et.apply(null,s):typeof s=="object"?e+=B(s):e+=s,e+=" "}return e};let et=null,ai=!0;const bu=function(n,e){m(!0,"Can't turn on custom loggers persistently."),Fe.logLevel=A.VERBOSE,et=Fe.log.bind(Fe)},W=function(...n){if(ai===!0&&(ai=!1,et===null&&vu.get("logging_enabled")===!0&&bu()),et){const e=Et.apply(null,n);et(e)}},wt=function(n){return function(...e){W(n,...e)}},Wn=function(...n){const e="FIREBASE INTERNAL ERROR: "+Et(...n);Fe.error(e)},ue=function(...n){const e=`FIREBASE FATAL ERROR: ${Et(...n)}`;throw Fe.error(e),new Error(e)},Y=function(...n){const e="FIREBASE WARNING: "+Et(...n);Fe.warn(e)},Su=function(){typeof window<"u"&&window.location&&window.location.protocol&&window.location.protocol.indexOf("https:")!==-1&&Y("Insecure Firebase access from a secure page. Please use https in calls to new Firebase().")},xr=function(n){return typeof n=="number"&&(n!==n||n===Number.POSITIVE_INFINITY||n===Number.NEGATIVE_INFINITY)},Tu=function(n){if(document.readyState==="complete")n();else{let e=!1;const t=function(){if(!document.body){setTimeout(t,Math.floor(10));return}e||(e=!0,n())};document.addEventListener?(document.addEventListener("DOMContentLoaded",t,!1),window.addEventListener("load",t,!1)):document.attachEvent&&(document.attachEvent("onreadystatechange",()=>{document.readyState==="complete"&&t()}),window.attachEvent("onload",t))}},He="[MIN_NAME]",Re="[MAX_NAME]",Ge=function(n,e){if(n===e)return 0;if(n===He||e===Re)return-1;if(e===He||n===Re)return 1;{const t=li(n),s=li(e);return t!==null?s!==null?t-s===0?n.length-e.length:t-s:-1:s!==null?1:n<e?-1:1}},Iu=function(n,e){return n===e?0:n<e?-1:1},Qe=function(n,e){if(e&&n in e)return e[n];throw new Error("Missing required key ("+n+") in object: "+B(e))},rs=function(n){if(typeof n!="object"||n===null)return B(n);const e=[];for(const s in n)e.push(s);e.sort();let t="{";for(let s=0;s<e.length;s++)s!==0&&(t+=","),t+=B(e[s]),t+=":",t+=rs(n[e[s]]);return t+="}",t},Or=function(n,e){const t=n.length;if(t<=e)return[n];const s=[];for(let i=0;i<t;i+=e)i+e>t?s.push(n.substring(i,t)):s.push(n.substring(i,i+e));return s};function G(n,e){for(const t in n)n.hasOwnProperty(t)&&e(t,n[t])}const Dr=function(n){m(!xr(n),"Invalid JSON number");const e=11,t=52,s=(1<<e-1)-1;let i,r,o,a,c;n===0?(r=0,o=0,i=1/n===-1/0?1:0):(i=n<0,n=Math.abs(n),n>=Math.pow(2,1-s)?(a=Math.min(Math.floor(Math.log(n)/Math.LN2),s),r=a+s,o=Math.round(n*Math.pow(2,t-a)-Math.pow(2,t))):(r=0,o=Math.round(n/Math.pow(2,1-s-t))));const l=[];for(c=t;c;c-=1)l.push(o%2?1:0),o=Math.floor(o/2);for(c=e;c;c-=1)l.push(r%2?1:0),r=Math.floor(r/2);l.push(i?1:0),l.reverse();const u=l.join("");let h="";for(c=0;c<64;c+=8){let d=parseInt(u.substr(c,8),2).toString(16);d.length===1&&(d="0"+d),h=h+d}return h.toLowerCase()},Ru=function(){return!!(typeof window=="object"&&window.chrome&&window.chrome.extension&&!/^chrome/.test(window.location.href))},Nu=function(){return typeof Windows=="object"&&typeof Windows.UI=="object"};function Au(n,e){let t="Unknown Error";n==="too_big"?t="The data requested exceeds the maximum size that can be accessed with a single request.":n==="permission_denied"?t="Client doesn't have permission to access the desired data.":n==="unavailable"&&(t="The service is unavailable");const s=new Error(n+" at "+e._path.toString()+": "+t);return s.code=n.toUpperCase(),s}const ku=new RegExp("^-?(0*)\\d{1,10}$"),xu=-2147483648,Ou=2147483647,li=function(n){if(ku.test(n)){const e=Number(n);if(e>=xu&&e<=Ou)return e}return null},vt=function(n){try{n()}catch(e){setTimeout(()=>{const t=e.stack||"";throw Y("Exception was thrown by user callback.",t),e},Math.floor(0))}},Du=function(){return(typeof window=="object"&&window.navigator&&window.navigator.userAgent||"").search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i)>=0},tt=function(n,e){const t=setTimeout(n,e);return typeof t=="number"&&typeof Deno<"u"&&Deno.unrefTimer?Deno.unrefTimer(t):typeof t=="object"&&t.unref&&t.unref(),t};/**
547
+ * @license
548
+ * Copyright 2021 Google LLC
549
+ *
550
+ * Licensed under the Apache License, Version 2.0 (the "License");
551
+ * you may not use this file except in compliance with the License.
552
+ * You may obtain a copy of the License at
553
+ *
554
+ * http://www.apache.org/licenses/LICENSE-2.0
555
+ *
556
+ * Unless required by applicable law or agreed to in writing, software
557
+ * distributed under the License is distributed on an "AS IS" BASIS,
558
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
559
+ * See the License for the specific language governing permissions and
560
+ * limitations under the License.
561
+ */class Pu{constructor(e,t){this.appCheckProvider=t,this.appName=e.name,su(e)&&e.settings.appCheckToken&&(this.serverAppAppCheckToken=e.settings.appCheckToken),this.appCheck=t==null?void 0:t.getImmediate({optional:!0}),this.appCheck||t==null||t.get().then(s=>this.appCheck=s)}getToken(e){if(this.serverAppAppCheckToken){if(e)throw new Error("Attempted reuse of `FirebaseServerApp.appCheckToken` after previous usage failed.");return Promise.resolve({token:this.serverAppAppCheckToken})}return this.appCheck?this.appCheck.getToken(e):new Promise((t,s)=>{setTimeout(()=>{this.appCheck?this.getToken(e).then(t,s):t(null)},0)})}addTokenChangeListener(e){var t;(t=this.appCheckProvider)===null||t===void 0||t.get().then(s=>s.addTokenListener(e))}notifyForInvalidToken(){Y(`Provided AppCheck credentials for the app named "${this.appName}" are invalid. This usually indicates your app was not initialized correctly.`)}}/**
562
+ * @license
563
+ * Copyright 2017 Google LLC
564
+ *
565
+ * Licensed under the Apache License, Version 2.0 (the "License");
566
+ * you may not use this file except in compliance with the License.
567
+ * You may obtain a copy of the License at
568
+ *
569
+ * http://www.apache.org/licenses/LICENSE-2.0
570
+ *
571
+ * Unless required by applicable law or agreed to in writing, software
572
+ * distributed under the License is distributed on an "AS IS" BASIS,
573
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
574
+ * See the License for the specific language governing permissions and
575
+ * limitations under the License.
576
+ */class Mu{constructor(e,t,s){this.appName_=e,this.firebaseOptions_=t,this.authProvider_=s,this.auth_=null,this.auth_=s.getImmediate({optional:!0}),this.auth_||s.onInit(i=>this.auth_=i)}getToken(e){return this.auth_?this.auth_.getToken(e).catch(t=>t&&t.code==="auth/token-not-initialized"?(W("Got auth/token-not-initialized error. Treating as null token."),null):Promise.reject(t)):new Promise((t,s)=>{setTimeout(()=>{this.auth_?this.getToken(e).then(t,s):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/.',Y(e)}}class xt{constructor(e){this.accessToken=e}getToken(e){return Promise.resolve({accessToken:this.accessToken})}addTokenChangeListener(e){e(this.accessToken)}removeTokenChangeListener(e){}notifyForInvalidToken(){}}xt.OWNER="owner";/**
577
+ * @license
578
+ * Copyright 2017 Google LLC
579
+ *
580
+ * Licensed under the Apache License, Version 2.0 (the "License");
581
+ * you may not use this file except in compliance with the License.
582
+ * You may obtain a copy of the License at
583
+ *
584
+ * http://www.apache.org/licenses/LICENSE-2.0
585
+ *
586
+ * Unless required by applicable law or agreed to in writing, software
587
+ * distributed under the License is distributed on an "AS IS" BASIS,
588
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
589
+ * See the License for the specific language governing permissions and
590
+ * limitations under the License.
591
+ */const os="5",Pr="v",Mr="s",Lr="r",Fr="f",Ur=/(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/,Br="ls",Wr="p",Hn="ac",Hr="websocket",Vr="long_polling";/**
592
+ * @license
593
+ * Copyright 2017 Google LLC
594
+ *
595
+ * Licensed under the Apache License, Version 2.0 (the "License");
596
+ * you may not use this file except in compliance with the License.
597
+ * You may obtain a copy of the License at
598
+ *
599
+ * http://www.apache.org/licenses/LICENSE-2.0
600
+ *
601
+ * Unless required by applicable law or agreed to in writing, software
602
+ * distributed under the License is distributed on an "AS IS" BASIS,
603
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
604
+ * See the License for the specific language governing permissions and
605
+ * limitations under the License.
606
+ */class qr{constructor(e,t,s,i,r=!1,o="",a=!1,c=!1,l=null){this.secure=t,this.namespace=s,this.webSocketOnly=i,this.nodeAdmin=r,this.persistenceKey=o,this.includeNamespaceInQueryParams=a,this.isUsingEmulator=c,this.emulatorOptions=l,this._host=e.toLowerCase(),this._domain=this._host.substr(this._host.indexOf(".")+1),this.internalHost=Se.get("host:"+e)||this._host}isCacheableHost(){return this.internalHost.substr(0,2)==="s-"}isCustomHost(){return this._domain!=="firebaseio.com"&&this._domain!=="firebaseio-demo.com"}get host(){return this._host}set host(e){e!==this.internalHost&&(this.internalHost=e,this.isCacheableHost()&&Se.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 Lu(n){return n.host!==n.internalHost||n.isCustomHost()||n.includeNamespaceInQueryParams}function $r(n,e,t){m(typeof e=="string","typeof type must == string"),m(typeof t=="object","typeof params must == object");let s;if(e===Hr)s=(n.secure?"wss://":"ws://")+n.internalHost+"/.ws?";else if(e===Vr)s=(n.secure?"https://":"http://")+n.internalHost+"/.lp?";else throw new Error("Unknown connection type: "+e);Lu(n)&&(t.ns=n.namespace);const i=[];return G(t,(r,o)=>{i.push(r+"="+o)}),s+i.join("&")}/**
607
+ * @license
608
+ * Copyright 2017 Google LLC
609
+ *
610
+ * Licensed under the Apache License, Version 2.0 (the "License");
611
+ * you may not use this file except in compliance with the License.
612
+ * You may obtain a copy of the License at
613
+ *
614
+ * http://www.apache.org/licenses/LICENSE-2.0
615
+ *
616
+ * Unless required by applicable law or agreed to in writing, software
617
+ * distributed under the License is distributed on an "AS IS" BASIS,
618
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
619
+ * See the License for the specific language governing permissions and
620
+ * limitations under the License.
621
+ */class Fu{constructor(){this.counters_={}}incrementCounter(e,t=1){he(this.counters_,e)||(this.counters_[e]=0),this.counters_[e]+=t}get(){return Ul(this.counters_)}}/**
622
+ * @license
623
+ * Copyright 2017 Google LLC
624
+ *
625
+ * Licensed under the Apache License, Version 2.0 (the "License");
626
+ * you may not use this file except in compliance with the License.
627
+ * You may obtain a copy of the License at
628
+ *
629
+ * http://www.apache.org/licenses/LICENSE-2.0
630
+ *
631
+ * Unless required by applicable law or agreed to in writing, software
632
+ * distributed under the License is distributed on an "AS IS" BASIS,
633
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
634
+ * See the License for the specific language governing permissions and
635
+ * limitations under the License.
636
+ */const vn={},Cn={};function as(n){const e=n.toString();return vn[e]||(vn[e]=new Fu),vn[e]}function Uu(n,e){const t=n.toString();return Cn[t]||(Cn[t]=e()),Cn[t]}/**
637
+ * @license
638
+ * Copyright 2017 Google LLC
639
+ *
640
+ * Licensed under the Apache License, Version 2.0 (the "License");
641
+ * you may not use this file except in compliance with the License.
642
+ * You may obtain a copy of the License at
643
+ *
644
+ * http://www.apache.org/licenses/LICENSE-2.0
645
+ *
646
+ * Unless required by applicable law or agreed to in writing, software
647
+ * distributed under the License is distributed on an "AS IS" BASIS,
648
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
649
+ * See the License for the specific language governing permissions and
650
+ * limitations under the License.
651
+ */class Bu{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 s=this.pendingResponses[this.currentResponseNum];delete this.pendingResponses[this.currentResponseNum];for(let i=0;i<s.length;++i)s[i]&&vt(()=>{this.onMessage_(s[i])});if(this.currentResponseNum===this.closeAfterResponse){this.onClose&&(this.onClose(),this.onClose=null);break}this.currentResponseNum++}}}/**
652
+ * @license
653
+ * Copyright 2017 Google LLC
654
+ *
655
+ * Licensed under the Apache License, Version 2.0 (the "License");
656
+ * you may not use this file except in compliance with the License.
657
+ * You may obtain a copy of the License at
658
+ *
659
+ * http://www.apache.org/licenses/LICENSE-2.0
660
+ *
661
+ * Unless required by applicable law or agreed to in writing, software
662
+ * distributed under the License is distributed on an "AS IS" BASIS,
663
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
664
+ * See the License for the specific language governing permissions and
665
+ * limitations under the License.
666
+ */const ci="start",Wu="close",Hu="pLPCommand",Vu="pRTLPCB",jr="id",zr="pw",Gr="ser",qu="cb",$u="seg",ju="ts",zu="d",Gu="dframe",Kr=1870,Yr=30,Ku=Kr-Yr,Yu=25e3,Qu=3e4;class Pe{constructor(e,t,s,i,r,o,a){this.connId=e,this.repoInfo=t,this.applicationId=s,this.appCheckToken=i,this.authToken=r,this.transportSessionId=o,this.lastSessionId=a,this.bytesSent=0,this.bytesReceived=0,this.everConnected_=!1,this.log_=wt(e),this.stats_=as(t),this.urlFn=c=>(this.appCheckToken&&(c[Hn]=this.appCheckToken),$r(t,Vr,c))}open(e,t){this.curSegmentNum=0,this.onDisconnect_=t,this.myPacketOrderer=new Bu(e),this.isClosed_=!1,this.connectTimeoutTimer_=setTimeout(()=>{this.log_("Timed out trying to connect."),this.onClosed_(),this.connectTimeoutTimer_=null},Math.floor(Qu)),Tu(()=>{if(this.isClosed_)return;this.scriptTagHolder=new ls((...r)=>{const[o,a,c,l,u]=r;if(this.incrementIncomingBytes_(r),!!this.scriptTagHolder)if(this.connectTimeoutTimer_&&(clearTimeout(this.connectTimeoutTimer_),this.connectTimeoutTimer_=null),this.everConnected_=!0,o===ci)this.id=a,this.password=c;else if(o===Wu)a?(this.scriptTagHolder.sendNewPolls=!1,this.myPacketOrderer.closeAfter(a,()=>{this.onClosed_()})):this.onClosed_();else throw new Error("Unrecognized command received: "+o)},(...r)=>{const[o,a]=r;this.incrementIncomingBytes_(r),this.myPacketOrderer.handleResponse(o,a)},()=>{this.onClosed_()},this.urlFn);const s={};s[ci]="t",s[Gr]=Math.floor(Math.random()*1e8),this.scriptTagHolder.uniqueCallbackIdentifier&&(s[qu]=this.scriptTagHolder.uniqueCallbackIdentifier),s[Pr]=os,this.transportSessionId&&(s[Mr]=this.transportSessionId),this.lastSessionId&&(s[Br]=this.lastSessionId),this.applicationId&&(s[Wr]=this.applicationId),this.appCheckToken&&(s[Hn]=this.appCheckToken),typeof location<"u"&&location.hostname&&Ur.test(location.hostname)&&(s[Lr]=Fr);const i=this.urlFn(s);this.log_("Connecting via long-poll to "+i),this.scriptTagHolder.addTag(i,()=>{})})}start(){this.scriptTagHolder.startLongPoll(this.id,this.password),this.addDisconnectPingFrame(this.id,this.password)}static forceAllow(){Pe.forceAllow_=!0}static forceDisallow(){Pe.forceDisallow_=!0}static isAvailable(){return Pe.forceAllow_?!0:!Pe.forceDisallow_&&typeof document<"u"&&document.createElement!=null&&!Ru()&&!Nu()}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=B(e);this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length);const s=pr(t),i=Or(s,Ku);for(let r=0;r<i.length;r++)this.scriptTagHolder.enqueueSegment(this.curSegmentNum,i.length,i[r]),this.curSegmentNum++}addDisconnectPingFrame(e,t){this.myDisconnFrame=document.createElement("iframe");const s={};s[Gu]="t",s[jr]=e,s[zr]=t,this.myDisconnFrame.src=this.urlFn(s),this.myDisconnFrame.style.display="none",document.body.appendChild(this.myDisconnFrame)}incrementIncomingBytes_(e){const t=B(e).length;this.bytesReceived+=t,this.stats_.incrementCounter("bytes_received",t)}}class ls{constructor(e,t,s,i){this.onDisconnect=s,this.urlFn=i,this.outstandingRequests=new Set,this.pendingSegs=[],this.currentSerial=Math.floor(Math.random()*1e8),this.sendNewPolls=!0;{this.uniqueCallbackIdentifier=Cu(),window[Hu+this.uniqueCallbackIdentifier]=e,window[Vu+this.uniqueCallbackIdentifier]=t,this.myIFrame=ls.createIFrame_();let r="";this.myIFrame.src&&this.myIFrame.src.substr(0,11)==="javascript:"&&(r='<script>document.domain="'+document.domain+'";<\/script>');const o="<html><body>"+r+"</body></html>";try{this.myIFrame.doc.open(),this.myIFrame.doc.write(o),this.myIFrame.doc.close()}catch(a){W("frame writing exception"),a.stack&&W(a.stack),W(a)}}}static createIFrame_(){const e=document.createElement("iframe");if(e.style.display="none",document.body){document.body.appendChild(e);try{e.contentWindow.document||W("No IE domain setting required")}catch{const s=document.domain;e.src="javascript:void((function(){document.open();document.domain='"+s+"';document.close();})())"}}else throw"Document body has not initialized. Wait to initialize Firebase until after the document is ready.";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(()=>{this.myIFrame!==null&&(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[jr]=this.myID,e[zr]=this.myPW,e[Gr]=this.currentSerial;let t=this.urlFn(e),s="",i=0;for(;this.pendingSegs.length>0&&this.pendingSegs[0].d.length+Yr+s.length<=Kr;){const o=this.pendingSegs.shift();s=s+"&"+$u+i+"="+o.seg+"&"+ju+i+"="+o.ts+"&"+zu+i+"="+o.d,i++}return t=t+s,this.addLongPollTag_(t,this.currentSerial),!0}else return!1}enqueueSegment(e,t,s){this.pendingSegs.push({seg:e,ts:t,d:s}),this.alive&&this.newRequest_()}addLongPollTag_(e,t){this.outstandingRequests.add(t);const s=()=>{this.outstandingRequests.delete(t),this.newRequest_()},i=setTimeout(s,Math.floor(Yu)),r=()=>{clearTimeout(i),s()};this.addTag(e,r)}addTag(e,t){setTimeout(()=>{try{if(!this.sendNewPolls)return;const s=this.myIFrame.doc.createElement("script");s.type="text/javascript",s.async=!0,s.src=e,s.onload=s.onreadystatechange=function(){const i=s.readyState;(!i||i==="loaded"||i==="complete")&&(s.onload=s.onreadystatechange=null,s.parentNode&&s.parentNode.removeChild(s),t())},s.onerror=()=>{W("Long-poll script failed to load: "+e),this.sendNewPolls=!1,this.close()},this.myIFrame.doc.body.appendChild(s)}catch{}},Math.floor(1))}}/**
667
+ * @license
668
+ * Copyright 2017 Google LLC
669
+ *
670
+ * Licensed under the Apache License, Version 2.0 (the "License");
671
+ * you may not use this file except in compliance with the License.
672
+ * You may obtain a copy of the License at
673
+ *
674
+ * http://www.apache.org/licenses/LICENSE-2.0
675
+ *
676
+ * Unless required by applicable law or agreed to in writing, software
677
+ * distributed under the License is distributed on an "AS IS" BASIS,
678
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
679
+ * See the License for the specific language governing permissions and
680
+ * limitations under the License.
681
+ */const Ju=16384,Xu=45e3;let Bt=null;typeof MozWebSocket<"u"?Bt=MozWebSocket:typeof WebSocket<"u"&&(Bt=WebSocket);class ee{constructor(e,t,s,i,r,o,a){this.connId=e,this.applicationId=s,this.appCheckToken=i,this.authToken=r,this.keepaliveTimer=null,this.frames=null,this.totalFrames=0,this.bytesSent=0,this.bytesReceived=0,this.log_=wt(this.connId),this.stats_=as(t),this.connURL=ee.connectionURL_(t,o,a,i,s),this.nodeAdmin=t.nodeAdmin}static connectionURL_(e,t,s,i,r){const o={};return o[Pr]=os,typeof location<"u"&&location.hostname&&Ur.test(location.hostname)&&(o[Lr]=Fr),t&&(o[Mr]=t),s&&(o[Br]=s),i&&(o[Hn]=i),r&&(o[Wr]=r),$r(e,Hr,o)}open(e,t){this.onDisconnect=t,this.onMessage=e,this.log_("Websocket connecting to "+this.connURL),this.everConnected_=!1,Se.set("previous_websocket_failure",!0);try{let s;Yl(),this.mySock=new Bt(this.connURL,[],s)}catch(s){this.log_("Error instantiating WebSocket.");const i=s.message||s.data;i&&this.log_(i),this.onClosed_();return}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=s=>{this.handleIncomingFrame(s)},this.mySock.onerror=s=>{this.log_("WebSocket error. Closing connection.");const i=s.message||s.data;i&&this.log_(i),this.onClosed_()}}start(){}static forceDisallow(){ee.forceDisallow_=!0}static isAvailable(){let e=!1;if(typeof navigator<"u"&&navigator.userAgent){const t=/Android ([0-9]{0,}\.[0-9]{0,})/,s=navigator.userAgent.match(t);s&&s.length>1&&parseFloat(s[1])<4.4&&(e=!0)}return!e&&Bt!==null&&!ee.forceDisallow_}static previouslyFailed(){return Se.isInMemoryStorage||Se.get("previous_websocket_failure")===!0}markConnectionHealthy(){Se.remove("previous_websocket_failure")}appendFrame_(e){if(this.frames.push(e),this.frames.length===this.totalFrames){const t=this.frames.join("");this.frames=null;const s=ot(t);this.onMessage(s)}}handleNewFrameCount_(e){this.totalFrames=e,this.frames=[]}extractFrameCount_(e){if(m(this.frames===null,"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(this.mySock===null)return;const t=e.data;if(this.bytesReceived+=t.length,this.stats_.incrementCounter("bytes_received",t.length),this.resetKeepAlive(),this.frames!==null)this.appendFrame_(t);else{const s=this.extractFrameCount_(t);s!==null&&this.appendFrame_(s)}}send(e){this.resetKeepAlive();const t=B(e);this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length);const s=Or(t,Ju);s.length>1&&this.sendString_(String(s.length));for(let i=0;i<s.length;i++)this.sendString_(s[i])}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(Xu))}sendString_(e){try{this.mySock.send(e)}catch(t){this.log_("Exception thrown from WebSocket.send():",t.message||t.data,"Closing connection."),setTimeout(this.onClosed_.bind(this),0)}}}ee.responsesRequiredToBeHealthy=2;ee.healthyTimeout=3e4;/**
682
+ * @license
683
+ * Copyright 2017 Google LLC
684
+ *
685
+ * Licensed under the Apache License, Version 2.0 (the "License");
686
+ * you may not use this file except in compliance with the License.
687
+ * You may obtain a copy of the License at
688
+ *
689
+ * http://www.apache.org/licenses/LICENSE-2.0
690
+ *
691
+ * Unless required by applicable law or agreed to in writing, software
692
+ * distributed under the License is distributed on an "AS IS" BASIS,
693
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
694
+ * See the License for the specific language governing permissions and
695
+ * limitations under the License.
696
+ */class ct{static get ALL_TRANSPORTS(){return[Pe,ee]}static get IS_TRANSPORT_INITIALIZED(){return this.globalTransportInitialized_}constructor(e){this.initTransports_(e)}initTransports_(e){const t=ee&&ee.isAvailable();let s=t&&!ee.previouslyFailed();if(e.webSocketOnly&&(t||Y("wss:// URL used, but browser isn't known to support websockets. Trying anyway."),s=!0),s)this.transports_=[ee];else{const i=this.transports_=[];for(const r of ct.ALL_TRANSPORTS)r&&r.isAvailable()&&i.push(r);ct.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}}ct.globalTransportInitialized_=!1;/**
697
+ * @license
698
+ * Copyright 2017 Google LLC
699
+ *
700
+ * Licensed under the Apache License, Version 2.0 (the "License");
701
+ * you may not use this file except in compliance with the License.
702
+ * You may obtain a copy of the License at
703
+ *
704
+ * http://www.apache.org/licenses/LICENSE-2.0
705
+ *
706
+ * Unless required by applicable law or agreed to in writing, software
707
+ * distributed under the License is distributed on an "AS IS" BASIS,
708
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
709
+ * See the License for the specific language governing permissions and
710
+ * limitations under the License.
711
+ */const Zu=6e4,eh=5e3,th=10*1024,nh=100*1024,bn="t",ui="d",sh="s",hi="r",ih="e",di="o",fi="a",pi="n",_i="p",rh="h";class oh{constructor(e,t,s,i,r,o,a,c,l,u){this.id=e,this.repoInfo_=t,this.applicationId_=s,this.appCheckToken_=i,this.authToken_=r,this.onMessage_=o,this.onReady_=a,this.onDisconnect_=c,this.onKill_=l,this.lastSessionId=u,this.connectionCount=0,this.pendingDataMessages=[],this.state_=0,this.log_=wt("c:"+this.id+":"),this.transportManager_=new ct(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_),s=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,s)},Math.floor(0));const i=e.healthyTimeout||0;i>0&&(this.healthyTimeout_=tt(()=>{this.healthyTimeout_=null,this.isHealthy_||(this.conn_&&this.conn_.bytesReceived>nh?(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>th?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(i)))}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=>{this.state_!==2&&(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(bn in e){const t=e[bn];t===fi?this.upgradeIfSecondaryHealthy_():t===hi?(this.log_("Got a reset on secondary, closing it"),this.secondaryConn_.close(),(this.tx_===this.secondaryConn_||this.rx_===this.secondaryConn_)&&this.close()):t===di&&(this.log_("got pong on secondary."),this.secondaryResponsesRequired_--,this.upgradeIfSecondaryHealthy_())}}onSecondaryMessageReceived_(e){const t=Qe("t",e),s=Qe("d",e);if(t==="c")this.onSecondaryControl_(s);else if(t==="d")this.pendingDataMessages.push(s);else throw new Error("Unknown protocol layer: "+t)}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:_i,d:{}}}))}proceedWithUpgrade_(){this.secondaryConn_.start(),this.log_("sending client ack on secondary"),this.secondaryConn_.send({t:"c",d:{t:fi,d:{}}}),this.log_("Ending transmission on primary"),this.conn_.send({t:"c",d:{t:pi,d:{}}}),this.tx_=this.secondaryConn_,this.tryCleanupConnection()}onPrimaryMessageReceived_(e){const t=Qe("t",e),s=Qe("d",e);t==="c"?this.onControl_(s):t==="d"&&this.onDataMessage_(s)}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=Qe(bn,e);if(ui in e){const s=e[ui];if(t===rh){const i=Object.assign({},s);this.repoInfo_.isUsingEmulator&&(i.h=this.repoInfo_.host),this.onHandshake_(i)}else if(t===pi){this.log_("recvd end transmission on primary"),this.rx_=this.secondaryConn_;for(let i=0;i<this.pendingDataMessages.length;++i)this.onDataMessage_(this.pendingDataMessages[i]);this.pendingDataMessages=[],this.tryCleanupConnection()}else t===sh?this.onConnectionShutdown_(s):t===hi?this.onReset_(s):t===ih?Wn("Server Error: "+s):t===di?(this.log_("got pong on primary."),this.onPrimaryResponse_(),this.sendPingOnPrimaryIfNecessary_()):Wn("Unknown control packet command: "+t)}}onHandshake_(e){const t=e.ts,s=e.v,i=e.h;this.sessionId=e.s,this.repoInfo_.host=i,this.state_===0&&(this.conn_.start(),this.onConnectionEstablished_(this.conn_,t),os!==s&&Y("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_),s=this.disconnReceiver_(this.secondaryConn_);this.secondaryConn_.open(t,s),tt(()=>{this.secondaryConn_&&(this.log_("Timed out trying to upgrade."),this.secondaryConn_.close())},Math.floor(Zu))}onReset_(e){this.log_("Reset packet received. New host: "+e),this.repoInfo_.host=e,this.state_===1?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),this.primaryResponsesRequired_===0?(this.log_("Primary connection is healthy."),this.isHealthy_=!0):tt(()=>{this.sendPingOnPrimaryIfNecessary_()},Math.floor(eh))}sendPingOnPrimaryIfNecessary_(){!this.isHealthy_&&this.state_===1&&(this.log_("sending ping on primary."),this.sendData_({t:"c",d:{t:_i,d:{}}}))}onSecondaryConnectionLost_(){const e=this.secondaryConn_;this.secondaryConn_=null,(this.tx_===e||this.rx_===e)&&this.close()}onConnectionLost_(e){this.conn_=null,!e&&this.state_===0?(this.log_("Realtime connection failed."),this.repoInfo_.isCacheableHost()&&(Se.remove("host:"+this.repoInfo_.host),this.repoInfo_.internalHost=this.repoInfo_.host)):this.state_===1&&this.log_("Realtime connection lost."),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(this.state_!==1)throw"Connection is not connected";this.tx_.send(e)}close(){this.state_!==2&&(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)}}/**
712
+ * @license
713
+ * Copyright 2017 Google LLC
714
+ *
715
+ * Licensed under the Apache License, Version 2.0 (the "License");
716
+ * you may not use this file except in compliance with the License.
717
+ * You may obtain a copy of the License at
718
+ *
719
+ * http://www.apache.org/licenses/LICENSE-2.0
720
+ *
721
+ * Unless required by applicable law or agreed to in writing, software
722
+ * distributed under the License is distributed on an "AS IS" BASIS,
723
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
724
+ * See the License for the specific language governing permissions and
725
+ * limitations under the License.
726
+ */class Qr{put(e,t,s,i){}merge(e,t,s,i){}refreshAuthToken(e){}refreshAppCheckToken(e){}onDisconnectPut(e,t,s){}onDisconnectMerge(e,t,s){}onDisconnectCancel(e,t){}reportStats(e){}}/**
727
+ * @license
728
+ * Copyright 2017 Google LLC
729
+ *
730
+ * Licensed under the Apache License, Version 2.0 (the "License");
731
+ * you may not use this file except in compliance with the License.
732
+ * You may obtain a copy of the License at
733
+ *
734
+ * http://www.apache.org/licenses/LICENSE-2.0
735
+ *
736
+ * Unless required by applicable law or agreed to in writing, software
737
+ * distributed under the License is distributed on an "AS IS" BASIS,
738
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
739
+ * See the License for the specific language governing permissions and
740
+ * limitations under the License.
741
+ */class Jr{constructor(e){this.allowedEvents_=e,this.listeners_={},m(Array.isArray(e)&&e.length>0,"Requires a non-empty array")}trigger(e,...t){if(Array.isArray(this.listeners_[e])){const s=[...this.listeners_[e]];for(let i=0;i<s.length;i++)s[i].callback.apply(s[i].context,t)}}on(e,t,s){this.validateEventType_(e),this.listeners_[e]=this.listeners_[e]||[],this.listeners_[e].push({callback:t,context:s});const i=this.getInitialEvent(e);i&&t.apply(s,i)}off(e,t,s){this.validateEventType_(e);const i=this.listeners_[e]||[];for(let r=0;r<i.length;r++)if(i[r].callback===t&&(!s||s===i[r].context)){i.splice(r,1);return}}validateEventType_(e){m(this.allowedEvents_.find(t=>t===e),"Unknown event: "+e)}}/**
742
+ * @license
743
+ * Copyright 2017 Google LLC
744
+ *
745
+ * Licensed under the Apache License, Version 2.0 (the "License");
746
+ * you may not use this file except in compliance with the License.
747
+ * You may obtain a copy of the License at
748
+ *
749
+ * http://www.apache.org/licenses/LICENSE-2.0
750
+ *
751
+ * Unless required by applicable law or agreed to in writing, software
752
+ * distributed under the License is distributed on an "AS IS" BASIS,
753
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
754
+ * See the License for the specific language governing permissions and
755
+ * limitations under the License.
756
+ */class Wt extends Jr{static getInstance(){return new Wt}constructor(){super(["online"]),this.online_=!0,typeof window<"u"&&typeof window.addEventListener<"u"&&!yr()&&(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))}getInitialEvent(e){return m(e==="online","Unknown event type: "+e),[this.online_]}currentlyOnline(){return this.online_}}/**
757
+ * @license
758
+ * Copyright 2017 Google LLC
759
+ *
760
+ * Licensed under the Apache License, Version 2.0 (the "License");
761
+ * you may not use this file except in compliance with the License.
762
+ * You may obtain a copy of the License at
763
+ *
764
+ * http://www.apache.org/licenses/LICENSE-2.0
765
+ *
766
+ * Unless required by applicable law or agreed to in writing, software
767
+ * distributed under the License is distributed on an "AS IS" BASIS,
768
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
769
+ * See the License for the specific language governing permissions and
770
+ * limitations under the License.
771
+ */const mi=32,gi=768;class N{constructor(e,t){if(t===void 0){this.pieces_=e.split("/");let s=0;for(let i=0;i<this.pieces_.length;i++)this.pieces_[i].length>0&&(this.pieces_[s]=this.pieces_[i],s++);this.pieces_.length=s,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 S(){return new N("")}function C(n){return n.pieceNum_>=n.pieces_.length?null:n.pieces_[n.pieceNum_]}function ge(n){return n.pieces_.length-n.pieceNum_}function k(n){let e=n.pieceNum_;return e<n.pieces_.length&&e++,new N(n.pieces_,e)}function Xr(n){return n.pieceNum_<n.pieces_.length?n.pieces_[n.pieces_.length-1]:null}function ah(n){let e="";for(let t=n.pieceNum_;t<n.pieces_.length;t++)n.pieces_[t]!==""&&(e+="/"+encodeURIComponent(String(n.pieces_[t])));return e||"/"}function Zr(n,e=0){return n.pieces_.slice(n.pieceNum_+e)}function eo(n){if(n.pieceNum_>=n.pieces_.length)return null;const e=[];for(let t=n.pieceNum_;t<n.pieces_.length-1;t++)e.push(n.pieces_[t]);return new N(e,0)}function L(n,e){const t=[];for(let s=n.pieceNum_;s<n.pieces_.length;s++)t.push(n.pieces_[s]);if(e instanceof N)for(let s=e.pieceNum_;s<e.pieces_.length;s++)t.push(e.pieces_[s]);else{const s=e.split("/");for(let i=0;i<s.length;i++)s[i].length>0&&t.push(s[i])}return new N(t,0)}function b(n){return n.pieceNum_>=n.pieces_.length}function $(n,e){const t=C(n),s=C(e);if(t===null)return e;if(t===s)return $(k(n),k(e));throw new Error("INTERNAL ERROR: innerPath ("+e+") is not within outerPath ("+n+")")}function cs(n,e){if(ge(n)!==ge(e))return!1;for(let t=n.pieceNum_,s=e.pieceNum_;t<=n.pieces_.length;t++,s++)if(n.pieces_[t]!==e.pieces_[s])return!1;return!0}function te(n,e){let t=n.pieceNum_,s=e.pieceNum_;if(ge(n)>ge(e))return!1;for(;t<n.pieces_.length;){if(n.pieces_[t]!==e.pieces_[s])return!1;++t,++s}return!0}class lh{constructor(e,t){this.errorPrefix_=t,this.parts_=Zr(e,0),this.byteLength_=Math.max(1,this.parts_.length);for(let s=0;s<this.parts_.length;s++)this.byteLength_+=rn(this.parts_[s]);to(this)}}function ch(n,e){n.parts_.length>0&&(n.byteLength_+=1),n.parts_.push(e),n.byteLength_+=rn(e),to(n)}function uh(n){const e=n.parts_.pop();n.byteLength_-=rn(e),n.parts_.length>0&&(n.byteLength_-=1)}function to(n){if(n.byteLength_>gi)throw new Error(n.errorPrefix_+"has a key path longer than "+gi+" bytes ("+n.byteLength_+").");if(n.parts_.length>mi)throw new Error(n.errorPrefix_+"path specified exceeds the maximum depth that can be written ("+mi+") or object contains a cycle "+ve(n))}function ve(n){return n.parts_.length===0?"":"in property '"+n.parts_.join(".")+"'"}/**
772
+ * @license
773
+ * Copyright 2017 Google LLC
774
+ *
775
+ * Licensed under the Apache License, Version 2.0 (the "License");
776
+ * you may not use this file except in compliance with the License.
777
+ * You may obtain a copy of the License at
778
+ *
779
+ * http://www.apache.org/licenses/LICENSE-2.0
780
+ *
781
+ * Unless required by applicable law or agreed to in writing, software
782
+ * distributed under the License is distributed on an "AS IS" BASIS,
783
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
784
+ * See the License for the specific language governing permissions and
785
+ * limitations under the License.
786
+ */class us extends Jr{static getInstance(){return new us}constructor(){super(["visible"]);let e,t;typeof document<"u"&&typeof document.addEventListener<"u"&&(typeof document.hidden<"u"?(t="visibilitychange",e="hidden"):typeof document.mozHidden<"u"?(t="mozvisibilitychange",e="mozHidden"):typeof document.msHidden<"u"?(t="msvisibilitychange",e="msHidden"):typeof document.webkitHidden<"u"&&(t="webkitvisibilitychange",e="webkitHidden")),this.visible_=!0,t&&document.addEventListener(t,()=>{const s=!document[e];s!==this.visible_&&(this.visible_=s,this.trigger("visible",s))},!1)}getInitialEvent(e){return m(e==="visible","Unknown event type: "+e),[this.visible_]}}/**
787
+ * @license
788
+ * Copyright 2017 Google LLC
789
+ *
790
+ * Licensed under the Apache License, Version 2.0 (the "License");
791
+ * you may not use this file except in compliance with the License.
792
+ * You may obtain a copy of the License at
793
+ *
794
+ * http://www.apache.org/licenses/LICENSE-2.0
795
+ *
796
+ * Unless required by applicable law or agreed to in writing, software
797
+ * distributed under the License is distributed on an "AS IS" BASIS,
798
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
799
+ * See the License for the specific language governing permissions and
800
+ * limitations under the License.
801
+ */const Je=1e3,hh=60*5*1e3,yi=30*1e3,dh=1.3,fh=3e4,ph="server_kill",Ei=3;class le extends Qr{constructor(e,t,s,i,r,o,a,c){if(super(),this.repoInfo_=e,this.applicationId_=t,this.onDataUpdate_=s,this.onConnectStatus_=i,this.onServerInfoUpdate_=r,this.authTokenProvider_=o,this.appCheckTokenProvider_=a,this.authOverride_=c,this.id=le.nextPersistentConnectionId_++,this.log_=wt("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_=Je,this.maxReconnectDelay_=hh,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,c)throw new Error("Auth override specified in options, but not supported on non Node.js platforms");us.getInstance().on("visible",this.onVisible_,this),e.host.indexOf("fblocal")===-1&&Wt.getInstance().on("online",this.onOnline_,this)}sendRequest(e,t,s){const i=++this.requestNumber_,r={r:i,a:e,b:t};this.log_(B(r)),m(this.connected_,"sendRequest call when we're not connected not allowed."),this.realtime_.sendRequest(r),s&&(this.requestCBHash_[i]=s)}get(e){this.initConnection_();const t=new ss,i={action:"g",request:{p:e._path.toString(),q:e._queryObject},onComplete:o=>{const a=o.d;o.s==="ok"?t.resolve(a):t.reject(a)}};this.outstandingGets_.push(i),this.outstandingGetCount_++;const r=this.outstandingGets_.length-1;return this.connected_&&this.sendGet_(r),t.promise}listen(e,t,s,i){this.initConnection_();const r=e._queryIdentifier,o=e._path.toString();this.log_("Listen called for "+o+" "+r),this.listens.has(o)||this.listens.set(o,new Map),m(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"listen() called for non-default but complete query"),m(!this.listens.get(o).has(r),"listen() called twice for same path/queryId.");const a={onComplete:i,hashFn:t,query:e,tag:s};this.listens.get(o).set(r,a),this.connected_&&this.sendListen_(a)}sendGet_(e){const t=this.outstandingGets_[e];this.sendRequest("g",t.request,s=>{delete this.outstandingGets_[e],this.outstandingGetCount_--,this.outstandingGetCount_===0&&(this.outstandingGets_=[]),t.onComplete&&t.onComplete(s)})}sendListen_(e){const t=e.query,s=t._path.toString(),i=t._queryIdentifier;this.log_("Listen on "+s+" for "+i);const r={p:s},o="q";e.tag&&(r.q=t._queryObject,r.t=e.tag),r.h=e.hashFn(),this.sendRequest(o,r,a=>{const c=a.d,l=a.s;le.warnOnListenWarnings_(c,t),(this.listens.get(s)&&this.listens.get(s).get(i))===e&&(this.log_("listen response",a),l!=="ok"&&this.removeListen_(s,i),e.onComplete&&e.onComplete(l,c))})}static warnOnListenWarnings_(e,t){if(e&&typeof e=="object"&&he(e,"w")){const s=We(e,"w");if(Array.isArray(s)&&~s.indexOf("no_index")){const i='".indexOn": "'+t._queryParams.getIndex().toString()+'"',r=t._path.toString();Y(`Using an unspecified index. Your data will be downloaded and filtered on the client. Consider adding ${i} at ${r} to your security rules for better performance.`)}}}refreshAuthToken(e){this.authToken_=e,this.log_("Auth token refreshed"),this.authToken_?this.tryAuth():this.connected_&&this.sendRequest("unauth",{},()=>{}),this.reduceReconnectDelayIfAdminCredential_(e)}reduceReconnectDelayIfAdminCredential_(e){(e&&e.length===40||nc(e))&&(this.log_("Admin auth credential detected. Reducing max reconnect time."),this.maxReconnectDelay_=yi)}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=tc(e)?"auth":"gauth",s={cred:e};this.authOverride_===null?s.noauth=!0:typeof this.authOverride_=="object"&&(s.authvar=this.authOverride_),this.sendRequest(t,s,i=>{const r=i.s,o=i.d||"error";this.authToken_===e&&(r==="ok"?this.invalidAuthTokenCount_=0:this.onAuthRevoked_(r,o))})}}tryAppCheck(){this.connected_&&this.appCheckToken_&&this.sendRequest("appcheck",{token:this.appCheckToken_},e=>{const t=e.s,s=e.d||"error";t==="ok"?this.invalidAppCheckTokenCount_=0:this.onAppCheckRevoked_(t,s)})}unlisten(e,t){const s=e._path.toString(),i=e._queryIdentifier;this.log_("Unlisten called for "+s+" "+i),m(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"unlisten() called for non-default but complete query"),this.removeListen_(s,i)&&this.connected_&&this.sendUnlisten_(s,i,e._queryObject,t)}sendUnlisten_(e,t,s,i){this.log_("Unlisten on "+e+" for "+t);const r={p:e},o="n";i&&(r.q=s,r.t=i),this.sendRequest(o,r)}onDisconnectPut(e,t,s){this.initConnection_(),this.connected_?this.sendOnDisconnect_("o",e,t,s):this.onDisconnectRequestQueue_.push({pathString:e,action:"o",data:t,onComplete:s})}onDisconnectMerge(e,t,s){this.initConnection_(),this.connected_?this.sendOnDisconnect_("om",e,t,s):this.onDisconnectRequestQueue_.push({pathString:e,action:"om",data:t,onComplete:s})}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,s,i){const r={p:t,d:s};this.log_("onDisconnect "+e,r),this.sendRequest(e,r,o=>{i&&setTimeout(()=>{i(o.s,o.d)},Math.floor(0))})}put(e,t,s,i){this.putInternal("p",e,t,s,i)}merge(e,t,s,i){this.putInternal("m",e,t,s,i)}putInternal(e,t,s,i,r){this.initConnection_();const o={p:t,d:s};r!==void 0&&(o.h=r),this.outstandingPuts_.push({action:e,request:o,onComplete:i}),this.outstandingPutCount_++;const a=this.outstandingPuts_.length-1;this.connected_?this.sendPut_(a):this.log_("Buffering put: "+t)}sendPut_(e){const t=this.outstandingPuts_[e].action,s=this.outstandingPuts_[e].request,i=this.outstandingPuts_[e].onComplete;this.outstandingPuts_[e].queued=this.connected_,this.sendRequest(t,s,r=>{this.log_(t+" response",r),delete this.outstandingPuts_[e],this.outstandingPutCount_--,this.outstandingPutCount_===0&&(this.outstandingPuts_=[]),i&&i(r.s,r.d)})}reportStats(e){if(this.connected_){const t={c:e};this.log_("reportStats",t),this.sendRequest("s",t,s=>{if(s.s!=="ok"){const r=s.d;this.log_("reportStats","Error sending stats: "+r)}})}}onDataMessage_(e){if("r"in e){this.log_("from server: "+B(e));const t=e.r,s=this.requestCBHash_[t];s&&(delete this.requestCBHash_[t],s(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),e==="d"?this.onDataUpdate_(t.p,t.d,!1,t.t):e==="m"?this.onDataUpdate_(t.p,t.d,!0,t.t):e==="c"?this.onListenRevoked_(t.p,t.q):e==="ac"?this.onAuthRevoked_(t.s,t.d):e==="apc"?this.onAppCheckRevoked_(t.s,t.d):e==="sd"?this.onSecurityDebugPacket_(t):Wn("Unrecognized action received from server: "+B(e)+`
802
+ Are 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){m(!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_=Je,this.realtime_||this.scheduleConnect_(0)),this.visible_=e}onOnline_(e){e?(this.log_("Browser went online."),this.reconnectDelay_=Je,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_>fh&&(this.reconnectDelay_=Je),this.lastConnectionEstablishedTime_=null):(this.log_("Window isn't visible. Delaying reconnect."),this.reconnectDelay_=this.maxReconnectDelay_,this.lastConnectionAttemptTime_=new Date().getTime());const e=Math.max(0,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_,this.reconnectDelay_*dh)}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),t=this.onReady_.bind(this),s=this.onRealtimeDisconnect_.bind(this),i=this.id+":"+le.nextConnectionId_++,r=this.lastSessionId;let o=!1,a=null;const c=function(){a?a.close():(o=!0,s())},l=function(h){m(a,"sendRequest call when we're not connected not allowed."),a.sendRequest(h)};this.realtime_={close:c,sendRequest:l};const u=this.forceTokenRefresh_;this.forceTokenRefresh_=!1;try{const[h,d]=await Promise.all([this.authTokenProvider_.getToken(u),this.appCheckTokenProvider_.getToken(u)]);o?W("getToken() completed but was canceled"):(W("getToken() completed. Creating connection."),this.authToken_=h&&h.accessToken,this.appCheckToken_=d&&d.token,a=new oh(i,this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,e,t,s,_=>{Y(_+" ("+this.repoInfo_.toString()+")"),this.interrupt(ph)},r))}catch(h){this.log_("Failed to get token: "+h),o||(this.repoInfo_.nodeAdmin&&Y(h),c())}}}interrupt(e){W("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){W("Resuming connection for reason: "+e),delete this.interruptReasons_[e],Ys(this.interruptReasons_)&&(this.reconnectDelay_=Je,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_--)}this.outstandingPutCount_===0&&(this.outstandingPuts_=[])}onListenRevoked_(e,t){let s;t?s=t.map(r=>rs(r)).join("$"):s="default";const i=this.removeListen_(e,s);i&&i.onComplete&&i.onComplete("permission_denied")}removeListen_(e,t){const s=new N(e).toString();let i;if(this.listens.has(s)){const r=this.listens.get(s);i=r.get(t),r.delete(t),r.size===0&&this.listens.delete(s)}else i=void 0;return i}onAuthRevoked_(e,t){W("Auth token revoked: "+e+"/"+t),this.authToken_=null,this.forceTokenRefresh_=!0,this.realtime_.close(),(e==="invalid_token"||e==="permission_denied")&&(this.invalidAuthTokenCount_++,this.invalidAuthTokenCount_>=Ei&&(this.reconnectDelay_=yi,this.authTokenProvider_.notifyForInvalidToken()))}onAppCheckRevoked_(e,t){W("App check token revoked: "+e+"/"+t),this.appCheckToken_=null,this.forceTokenRefresh_=!0,(e==="invalid_token"||e==="permission_denied")&&(this.invalidAppCheckTokenCount_++,this.invalidAppCheckTokenCount_>=Ei&&this.appCheckTokenProvider_.notifyForInvalidToken())}onSecurityDebugPacket_(e){this.securityDebugCallback_?this.securityDebugCallback_(e):"msg"in e&&console.log("FIREBASE: "+e.msg.replace(`
803
+ `,`
804
+ FIREBASE: `))}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+"."+Nr.replace(/\./g,"-")]=1,yr()?e["framework.cordova"]=1:Kl()&&(e["framework.reactnative"]=1),this.reportStats(e)}shouldReconnect_(){const e=Wt.getInstance().currentlyOnline();return Ys(this.interruptReasons_)&&e}}le.nextPersistentConnectionId_=0;le.nextConnectionId_=0;/**
805
+ * @license
806
+ * Copyright 2017 Google LLC
807
+ *
808
+ * Licensed under the Apache License, Version 2.0 (the "License");
809
+ * you may not use this file except in compliance with the License.
810
+ * You may obtain a copy of the License at
811
+ *
812
+ * http://www.apache.org/licenses/LICENSE-2.0
813
+ *
814
+ * Unless required by applicable law or agreed to in writing, software
815
+ * distributed under the License is distributed on an "AS IS" BASIS,
816
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
817
+ * See the License for the specific language governing permissions and
818
+ * limitations under the License.
819
+ */class v{constructor(e,t){this.name=e,this.node=t}static Wrap(e,t){return new v(e,t)}}/**
820
+ * @license
821
+ * Copyright 2017 Google LLC
822
+ *
823
+ * Licensed under the Apache License, Version 2.0 (the "License");
824
+ * you may not use this file except in compliance with the License.
825
+ * You may obtain a copy of the License at
826
+ *
827
+ * http://www.apache.org/licenses/LICENSE-2.0
828
+ *
829
+ * Unless required by applicable law or agreed to in writing, software
830
+ * distributed under the License is distributed on an "AS IS" BASIS,
831
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
832
+ * See the License for the specific language governing permissions and
833
+ * limitations under the License.
834
+ */class an{getCompare(){return this.compare.bind(this)}indexedValueChanged(e,t){const s=new v(He,e),i=new v(He,t);return this.compare(s,i)!==0}minPost(){return v.MIN}}/**
835
+ * @license
836
+ * Copyright 2017 Google LLC
837
+ *
838
+ * Licensed under the Apache License, Version 2.0 (the "License");
839
+ * you may not use this file except in compliance with the License.
840
+ * You may obtain a copy of the License at
841
+ *
842
+ * http://www.apache.org/licenses/LICENSE-2.0
843
+ *
844
+ * Unless required by applicable law or agreed to in writing, software
845
+ * distributed under the License is distributed on an "AS IS" BASIS,
846
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
847
+ * See the License for the specific language governing permissions and
848
+ * limitations under the License.
849
+ */let It;class no extends an{static get __EMPTY_NODE(){return It}static set __EMPTY_NODE(e){It=e}compare(e,t){return Ge(e.name,t.name)}isDefinedOn(e){throw ze("KeyIndex.isDefinedOn not expected to be called.")}indexedValueChanged(e,t){return!1}minPost(){return v.MIN}maxPost(){return new v(Re,It)}makePost(e,t){return m(typeof e=="string","KeyIndex indexValue must always be a string."),new v(e,It)}toString(){return".key"}}const Ue=new no;/**
850
+ * @license
851
+ * Copyright 2017 Google LLC
852
+ *
853
+ * Licensed under the Apache License, Version 2.0 (the "License");
854
+ * you may not use this file except in compliance with the License.
855
+ * You may obtain a copy of the License at
856
+ *
857
+ * http://www.apache.org/licenses/LICENSE-2.0
858
+ *
859
+ * Unless required by applicable law or agreed to in writing, software
860
+ * distributed under the License is distributed on an "AS IS" BASIS,
861
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
862
+ * See the License for the specific language governing permissions and
863
+ * limitations under the License.
864
+ */class Rt{constructor(e,t,s,i,r=null){this.isReverse_=i,this.resultGenerator_=r,this.nodeStack_=[];let o=1;for(;!e.isEmpty();)if(e=e,o=t?s(e.key,t):1,i&&(o*=-1),o<0)this.isReverse_?e=e.left:e=e.right;else if(o===0){this.nodeStack_.push(e);break}else this.nodeStack_.push(e),this.isReverse_?e=e.right:e=e.left}getNext(){if(this.nodeStack_.length===0)return null;let e=this.nodeStack_.pop(),t;if(this.resultGenerator_?t=this.resultGenerator_(e.key,e.value):t={key:e.key,value:e.value},this.isReverse_)for(e=e.left;!e.isEmpty();)this.nodeStack_.push(e),e=e.right;else for(e=e.right;!e.isEmpty();)this.nodeStack_.push(e),e=e.left;return t}hasNext(){return this.nodeStack_.length>0}peek(){if(this.nodeStack_.length===0)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 U{constructor(e,t,s,i,r){this.key=e,this.value=t,this.color=s??U.RED,this.left=i??j.EMPTY_NODE,this.right=r??j.EMPTY_NODE}copy(e,t,s,i,r){return new U(e??this.key,t??this.value,s??this.color,i??this.left,r??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,s){let i=this;const r=s(e,i.key);return r<0?i=i.copy(null,null,null,i.left.insert(e,t,s),null):r===0?i=i.copy(null,t,null,null,null):i=i.copy(null,null,null,null,i.right.insert(e,t,s)),i.fixUp_()}removeMin_(){if(this.left.isEmpty())return j.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 s,i;if(s=this,t(e,s.key)<0)!s.left.isEmpty()&&!s.left.isRed_()&&!s.left.left.isRed_()&&(s=s.moveRedLeft_()),s=s.copy(null,null,null,s.left.remove(e,t),null);else{if(s.left.isRed_()&&(s=s.rotateRight_()),!s.right.isEmpty()&&!s.right.isRed_()&&!s.right.left.isRed_()&&(s=s.moveRedRight_()),t(e,s.key)===0){if(s.right.isEmpty())return j.EMPTY_NODE;i=s.right.min_(),s=s.copy(i.key,i.value,null,null,s.right.removeMin_())}s=s.copy(null,null,null,null,s.right.remove(e,t))}return s.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,U.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight_(){const e=this.copy(null,null,U.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)}}U.RED=!0;U.BLACK=!1;class _h{copy(e,t,s,i,r){return this}insert(e,t,s){return new U(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}}class j{constructor(e,t=j.EMPTY_NODE){this.comparator_=e,this.root_=t}insert(e,t){return new j(this.comparator_,this.root_.insert(e,t,this.comparator_).copy(null,null,U.BLACK,null,null))}remove(e){return new j(this.comparator_,this.root_.remove(e,this.comparator_).copy(null,null,U.BLACK,null,null))}get(e){let t,s=this.root_;for(;!s.isEmpty();){if(t=this.comparator_(e,s.key),t===0)return s.value;t<0?s=s.left:t>0&&(s=s.right)}return null}getPredecessorKey(e){let t,s=this.root_,i=null;for(;!s.isEmpty();)if(t=this.comparator_(e,s.key),t===0){if(s.left.isEmpty())return i?i.key:null;for(s=s.left;!s.right.isEmpty();)s=s.right;return s.key}else t<0?s=s.left:t>0&&(i=s,s=s.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 Rt(this.root_,null,this.comparator_,!1,e)}getIteratorFrom(e,t){return new Rt(this.root_,e,this.comparator_,!1,t)}getReverseIteratorFrom(e,t){return new Rt(this.root_,e,this.comparator_,!0,t)}getReverseIterator(e){return new Rt(this.root_,null,this.comparator_,!0,e)}}j.EMPTY_NODE=new _h;/**
865
+ * @license
866
+ * Copyright 2017 Google LLC
867
+ *
868
+ * Licensed under the Apache License, Version 2.0 (the "License");
869
+ * you may not use this file except in compliance with the License.
870
+ * You may obtain a copy of the License at
871
+ *
872
+ * http://www.apache.org/licenses/LICENSE-2.0
873
+ *
874
+ * Unless required by applicable law or agreed to in writing, software
875
+ * distributed under the License is distributed on an "AS IS" BASIS,
876
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
877
+ * See the License for the specific language governing permissions and
878
+ * limitations under the License.
879
+ */function mh(n,e){return Ge(n.name,e.name)}function hs(n,e){return Ge(n,e)}/**
880
+ * @license
881
+ * Copyright 2017 Google LLC
882
+ *
883
+ * Licensed under the Apache License, Version 2.0 (the "License");
884
+ * you may not use this file except in compliance with the License.
885
+ * You may obtain a copy of the License at
886
+ *
887
+ * http://www.apache.org/licenses/LICENSE-2.0
888
+ *
889
+ * Unless required by applicable law or agreed to in writing, software
890
+ * distributed under the License is distributed on an "AS IS" BASIS,
891
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
892
+ * See the License for the specific language governing permissions and
893
+ * limitations under the License.
894
+ */let Vn;function gh(n){Vn=n}const so=function(n){return typeof n=="number"?"number:"+Dr(n):"string:"+n},io=function(n){if(n.isLeafNode()){const e=n.val();m(typeof e=="string"||typeof e=="number"||typeof e=="object"&&he(e,".sv"),"Priority must be a string or number.")}else m(n===Vn||n.isEmpty(),"priority of unexpected type.");m(n===Vn||n.getPriority().isEmpty(),"Priority nodes can't have a priority of their own.")};/**
895
+ * @license
896
+ * Copyright 2017 Google LLC
897
+ *
898
+ * Licensed under the Apache License, Version 2.0 (the "License");
899
+ * you may not use this file except in compliance with the License.
900
+ * You may obtain a copy of the License at
901
+ *
902
+ * http://www.apache.org/licenses/LICENSE-2.0
903
+ *
904
+ * Unless required by applicable law or agreed to in writing, software
905
+ * distributed under the License is distributed on an "AS IS" BASIS,
906
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
907
+ * See the License for the specific language governing permissions and
908
+ * limitations under the License.
909
+ */let wi;class F{static set __childrenNodeConstructor(e){wi=e}static get __childrenNodeConstructor(){return wi}constructor(e,t=F.__childrenNodeConstructor.EMPTY_NODE){this.value_=e,this.priorityNode_=t,this.lazyHash_=null,m(this.value_!==void 0&&this.value_!==null,"LeafNode shouldn't be created with null/undefined value."),io(this.priorityNode_)}isLeafNode(){return!0}getPriority(){return this.priorityNode_}updatePriority(e){return new F(this.value_,e)}getImmediateChild(e){return e===".priority"?this.priorityNode_:F.__childrenNodeConstructor.EMPTY_NODE}getChild(e){return b(e)?this:C(e)===".priority"?this.priorityNode_:F.__childrenNodeConstructor.EMPTY_NODE}hasChild(){return!1}getPredecessorChildName(e,t){return null}updateImmediateChild(e,t){return e===".priority"?this.updatePriority(t):t.isEmpty()&&e!==".priority"?this:F.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(e,t).updatePriority(this.priorityNode_)}updateChild(e,t){const s=C(e);return s===null?t:t.isEmpty()&&s!==".priority"?this:(m(s!==".priority"||ge(e)===1,".priority must be the last token in a path"),this.updateImmediateChild(s,F.__childrenNodeConstructor.EMPTY_NODE.updateChild(k(e),t)))}isEmpty(){return!1}numChildren(){return 0}forEachChild(e,t){return!1}val(e){return e&&!this.getPriority().isEmpty()?{".value":this.getValue(),".priority":this.getPriority().val()}:this.getValue()}hash(){if(this.lazyHash_===null){let e="";this.priorityNode_.isEmpty()||(e+="priority:"+so(this.priorityNode_.val())+":");const t=typeof this.value_;e+=t+":",t==="number"?e+=Dr(this.value_):e+=this.value_,this.lazyHash_=kr(e)}return this.lazyHash_}getValue(){return this.value_}compareTo(e){return e===F.__childrenNodeConstructor.EMPTY_NODE?1:e instanceof F.__childrenNodeConstructor?-1:(m(e.isLeafNode(),"Unknown node type"),this.compareToLeafNode_(e))}compareToLeafNode_(e){const t=typeof e.value_,s=typeof this.value_,i=F.VALUE_TYPE_ORDER.indexOf(t),r=F.VALUE_TYPE_ORDER.indexOf(s);return m(i>=0,"Unknown leaf type: "+t),m(r>=0,"Unknown leaf type: "+s),i===r?s==="object"?0:this.value_<e.value_?-1:this.value_===e.value_?0:1:r-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_)}else return!1}}F.VALUE_TYPE_ORDER=["object","boolean","number","string"];/**
910
+ * @license
911
+ * Copyright 2017 Google LLC
912
+ *
913
+ * Licensed under the Apache License, Version 2.0 (the "License");
914
+ * you may not use this file except in compliance with the License.
915
+ * You may obtain a copy of the License at
916
+ *
917
+ * http://www.apache.org/licenses/LICENSE-2.0
918
+ *
919
+ * Unless required by applicable law or agreed to in writing, software
920
+ * distributed under the License is distributed on an "AS IS" BASIS,
921
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
922
+ * See the License for the specific language governing permissions and
923
+ * limitations under the License.
924
+ */let ro,oo;function yh(n){ro=n}function Eh(n){oo=n}class wh extends an{compare(e,t){const s=e.node.getPriority(),i=t.node.getPriority(),r=s.compareTo(i);return r===0?Ge(e.name,t.name):r}isDefinedOn(e){return!e.getPriority().isEmpty()}indexedValueChanged(e,t){return!e.getPriority().equals(t.getPriority())}minPost(){return v.MIN}maxPost(){return new v(Re,new F("[PRIORITY-POST]",oo))}makePost(e,t){const s=ro(e);return new v(t,new F("[PRIORITY-POST]",s))}toString(){return".priority"}}const P=new wh;/**
925
+ * @license
926
+ * Copyright 2017 Google LLC
927
+ *
928
+ * Licensed under the Apache License, Version 2.0 (the "License");
929
+ * you may not use this file except in compliance with the License.
930
+ * You may obtain a copy of the License at
931
+ *
932
+ * http://www.apache.org/licenses/LICENSE-2.0
933
+ *
934
+ * Unless required by applicable law or agreed to in writing, software
935
+ * distributed under the License is distributed on an "AS IS" BASIS,
936
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
937
+ * See the License for the specific language governing permissions and
938
+ * limitations under the License.
939
+ */const vh=Math.log(2);class Ch{constructor(e){const t=r=>parseInt(Math.log(r)/vh,10),s=r=>parseInt(Array(r+1).join("1"),2);this.count=t(e+1),this.current_=this.count-1;const i=s(this.count);this.bits_=e+1&i}nextBitIsOne(){const e=!(this.bits_&1<<this.current_);return this.current_--,e}}const Ht=function(n,e,t,s){n.sort(e);const i=function(c,l){const u=l-c;let h,d;if(u===0)return null;if(u===1)return h=n[c],d=t?t(h):h,new U(d,h.node,U.BLACK,null,null);{const _=parseInt(u/2,10)+c,p=i(c,_),y=i(_+1,l);return h=n[_],d=t?t(h):h,new U(d,h.node,U.BLACK,p,y)}},r=function(c){let l=null,u=null,h=n.length;const d=function(p,y){const g=h-p,I=h;h-=p;const O=i(g+1,I),D=n[g],X=t?t(D):D;_(new U(X,D.node,y,null,O))},_=function(p){l?(l.left=p,l=p):(u=p,l=p)};for(let p=0;p<c.count;++p){const y=c.nextBitIsOne(),g=Math.pow(2,c.count-(p+1));y?d(g,U.BLACK):(d(g,U.BLACK),d(g,U.RED))}return u},o=new Ch(n.length),a=r(o);return new j(s||e,a)};/**
940
+ * @license
941
+ * Copyright 2017 Google LLC
942
+ *
943
+ * Licensed under the Apache License, Version 2.0 (the "License");
944
+ * you may not use this file except in compliance with the License.
945
+ * You may obtain a copy of the License at
946
+ *
947
+ * http://www.apache.org/licenses/LICENSE-2.0
948
+ *
949
+ * Unless required by applicable law or agreed to in writing, software
950
+ * distributed under the License is distributed on an "AS IS" BASIS,
951
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
952
+ * See the License for the specific language governing permissions and
953
+ * limitations under the License.
954
+ */let Sn;const De={};class ae{static get Default(){return m(De&&P,"ChildrenNode.ts has not been loaded"),Sn=Sn||new ae({".priority":De},{".priority":P}),Sn}constructor(e,t){this.indexes_=e,this.indexSet_=t}get(e){const t=We(this.indexes_,e);if(!t)throw new Error("No index defined for "+e);return t instanceof j?t:null}hasIndex(e){return he(this.indexSet_,e.toString())}addIndex(e,t){m(e!==Ue,"KeyIndex always exists and isn't meant to be added to the IndexMap.");const s=[];let i=!1;const r=t.getIterator(v.Wrap);let o=r.getNext();for(;o;)i=i||e.isDefinedOn(o.node),s.push(o),o=r.getNext();let a;i?a=Ht(s,e.getCompare()):a=De;const c=e.toString(),l=Object.assign({},this.indexSet_);l[c]=e;const u=Object.assign({},this.indexes_);return u[c]=a,new ae(u,l)}addToIndexes(e,t){const s=Mt(this.indexes_,(i,r)=>{const o=We(this.indexSet_,r);if(m(o,"Missing index implementation for "+r),i===De)if(o.isDefinedOn(e.node)){const a=[],c=t.getIterator(v.Wrap);let l=c.getNext();for(;l;)l.name!==e.name&&a.push(l),l=c.getNext();return a.push(e),Ht(a,o.getCompare())}else return De;else{const a=t.get(e.name);let c=i;return a&&(c=c.remove(new v(e.name,a))),c.insert(e,e.node)}});return new ae(s,this.indexSet_)}removeFromIndexes(e,t){const s=Mt(this.indexes_,i=>{if(i===De)return i;{const r=t.get(e.name);return r?i.remove(new v(e.name,r)):i}});return new ae(s,this.indexSet_)}}/**
955
+ * @license
956
+ * Copyright 2017 Google LLC
957
+ *
958
+ * Licensed under the Apache License, Version 2.0 (the "License");
959
+ * you may not use this file except in compliance with the License.
960
+ * You may obtain a copy of the License at
961
+ *
962
+ * http://www.apache.org/licenses/LICENSE-2.0
963
+ *
964
+ * Unless required by applicable law or agreed to in writing, software
965
+ * distributed under the License is distributed on an "AS IS" BASIS,
966
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
967
+ * See the License for the specific language governing permissions and
968
+ * limitations under the License.
969
+ */let Xe;class E{static get EMPTY_NODE(){return Xe||(Xe=new E(new j(hs),null,ae.Default))}constructor(e,t,s){this.children_=e,this.priorityNode_=t,this.indexMap_=s,this.lazyHash_=null,this.priorityNode_&&io(this.priorityNode_),this.children_.isEmpty()&&m(!this.priorityNode_||this.priorityNode_.isEmpty(),"An empty node cannot have a priority")}isLeafNode(){return!1}getPriority(){return this.priorityNode_||Xe}updatePriority(e){return this.children_.isEmpty()?this:new E(this.children_,e,this.indexMap_)}getImmediateChild(e){if(e===".priority")return this.getPriority();{const t=this.children_.get(e);return t===null?Xe:t}}getChild(e){const t=C(e);return t===null?this:this.getImmediateChild(t).getChild(k(e))}hasChild(e){return this.children_.get(e)!==null}updateImmediateChild(e,t){if(m(t,"We should always be passing snapshot nodes"),e===".priority")return this.updatePriority(t);{const s=new v(e,t);let i,r;t.isEmpty()?(i=this.children_.remove(e),r=this.indexMap_.removeFromIndexes(s,this.children_)):(i=this.children_.insert(e,t),r=this.indexMap_.addToIndexes(s,this.children_));const o=i.isEmpty()?Xe:this.priorityNode_;return new E(i,o,r)}}updateChild(e,t){const s=C(e);if(s===null)return t;{m(C(e)!==".priority"||ge(e)===1,".priority must be the last token in a path");const i=this.getImmediateChild(s).updateChild(k(e),t);return this.updateImmediateChild(s,i)}}isEmpty(){return this.children_.isEmpty()}numChildren(){return this.children_.count()}val(e){if(this.isEmpty())return null;const t={};let s=0,i=0,r=!0;if(this.forEachChild(P,(o,a)=>{t[o]=a.val(e),s++,r&&E.INTEGER_REGEXP_.test(o)?i=Math.max(i,Number(o)):r=!1}),!e&&r&&i<2*s){const o=[];for(const a in t)o[a]=t[a];return o}else return e&&!this.getPriority().isEmpty()&&(t[".priority"]=this.getPriority().val()),t}hash(){if(this.lazyHash_===null){let e="";this.getPriority().isEmpty()||(e+="priority:"+so(this.getPriority().val())+":"),this.forEachChild(P,(t,s)=>{const i=s.hash();i!==""&&(e+=":"+t+":"+i)}),this.lazyHash_=e===""?"":kr(e)}return this.lazyHash_}getPredecessorChildName(e,t,s){const i=this.resolveIndex_(s);if(i){const r=i.getPredecessorKey(new v(e,t));return r?r.name:null}else return this.children_.getPredecessorKey(e)}getFirstChildName(e){const t=this.resolveIndex_(e);if(t){const s=t.minKey();return s&&s.name}else 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 s=t.maxKey();return s&&s.name}else 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 s=this.resolveIndex_(e);return s?s.inorderTraversal(i=>t(i.name,i.node)):this.children_.inorderTraversal(t)}getIterator(e){return this.getIteratorFrom(e.minPost(),e)}getIteratorFrom(e,t){const s=this.resolveIndex_(t);if(s)return s.getIteratorFrom(e,i=>i);{const i=this.children_.getIteratorFrom(e.name,v.Wrap);let r=i.peek();for(;r!=null&&t.compare(r,e)<0;)i.getNext(),r=i.peek();return i}}getReverseIterator(e){return this.getReverseIteratorFrom(e.maxPost(),e)}getReverseIteratorFrom(e,t){const s=this.resolveIndex_(t);if(s)return s.getReverseIteratorFrom(e,i=>i);{const i=this.children_.getReverseIteratorFrom(e.name,v.Wrap);let r=i.peek();for(;r!=null&&t.compare(r,e)>0;)i.getNext(),r=i.peek();return i}}compareTo(e){return this.isEmpty()?e.isEmpty()?0:-1:e.isLeafNode()||e.isEmpty()?1:e===Ct?-1:0}withIndex(e){if(e===Ue||this.indexMap_.hasIndex(e))return this;{const t=this.indexMap_.addIndex(e,this.children_);return new E(this.children_,this.priorityNode_,t)}}isIndexed(e){return e===Ue||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 s=this.getIterator(P),i=t.getIterator(P);let r=s.getNext(),o=i.getNext();for(;r&&o;){if(r.name!==o.name||!r.node.equals(o.node))return!1;r=s.getNext(),o=i.getNext()}return r===null&&o===null}else return!1;else return!1}}resolveIndex_(e){return e===Ue?null:this.indexMap_.get(e.toString())}}E.INTEGER_REGEXP_=/^(0|[1-9]\d*)$/;class bh extends E{constructor(){super(new j(hs),E.EMPTY_NODE,ae.Default)}compareTo(e){return e===this?0:1}equals(e){return e===this}getPriority(){return this}getImmediateChild(e){return E.EMPTY_NODE}isEmpty(){return!1}}const Ct=new bh;Object.defineProperties(v,{MIN:{value:new v(He,E.EMPTY_NODE)},MAX:{value:new v(Re,Ct)}});no.__EMPTY_NODE=E.EMPTY_NODE;F.__childrenNodeConstructor=E;gh(Ct);Eh(Ct);/**
970
+ * @license
971
+ * Copyright 2017 Google LLC
972
+ *
973
+ * Licensed under the Apache License, Version 2.0 (the "License");
974
+ * you may not use this file except in compliance with the License.
975
+ * You may obtain a copy of the License at
976
+ *
977
+ * http://www.apache.org/licenses/LICENSE-2.0
978
+ *
979
+ * Unless required by applicable law or agreed to in writing, software
980
+ * distributed under the License is distributed on an "AS IS" BASIS,
981
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
982
+ * See the License for the specific language governing permissions and
983
+ * limitations under the License.
984
+ */const Sh=!0;function H(n,e=null){if(n===null)return E.EMPTY_NODE;if(typeof n=="object"&&".priority"in n&&(e=n[".priority"]),m(e===null||typeof e=="string"||typeof e=="number"||typeof e=="object"&&".sv"in e,"Invalid priority type found: "+typeof e),typeof n=="object"&&".value"in n&&n[".value"]!==null&&(n=n[".value"]),typeof n!="object"||".sv"in n){const t=n;return new F(t,H(e))}if(!(n instanceof Array)&&Sh){const t=[];let s=!1;if(G(n,(o,a)=>{if(o.substring(0,1)!=="."){const c=H(a);c.isEmpty()||(s=s||!c.getPriority().isEmpty(),t.push(new v(o,c)))}}),t.length===0)return E.EMPTY_NODE;const r=Ht(t,mh,o=>o.name,hs);if(s){const o=Ht(t,P.getCompare());return new E(r,H(e),new ae({".priority":o},{".priority":P}))}else return new E(r,H(e),ae.Default)}else{let t=E.EMPTY_NODE;return G(n,(s,i)=>{if(he(n,s)&&s.substring(0,1)!=="."){const r=H(i);(r.isLeafNode()||!r.isEmpty())&&(t=t.updateImmediateChild(s,r))}}),t.updatePriority(H(e))}}yh(H);/**
985
+ * @license
986
+ * Copyright 2017 Google LLC
987
+ *
988
+ * Licensed under the Apache License, Version 2.0 (the "License");
989
+ * you may not use this file except in compliance with the License.
990
+ * You may obtain a copy of the License at
991
+ *
992
+ * http://www.apache.org/licenses/LICENSE-2.0
993
+ *
994
+ * Unless required by applicable law or agreed to in writing, software
995
+ * distributed under the License is distributed on an "AS IS" BASIS,
996
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
997
+ * See the License for the specific language governing permissions and
998
+ * limitations under the License.
999
+ */class Th extends an{constructor(e){super(),this.indexPath_=e,m(!b(e)&&C(e)!==".priority","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 s=this.extractChild(e.node),i=this.extractChild(t.node),r=s.compareTo(i);return r===0?Ge(e.name,t.name):r}makePost(e,t){const s=H(e),i=E.EMPTY_NODE.updateChild(this.indexPath_,s);return new v(t,i)}maxPost(){const e=E.EMPTY_NODE.updateChild(this.indexPath_,Ct);return new v(Re,e)}toString(){return Zr(this.indexPath_,0).join("/")}}/**
1000
+ * @license
1001
+ * Copyright 2017 Google LLC
1002
+ *
1003
+ * Licensed under the Apache License, Version 2.0 (the "License");
1004
+ * you may not use this file except in compliance with the License.
1005
+ * You may obtain a copy of the License at
1006
+ *
1007
+ * http://www.apache.org/licenses/LICENSE-2.0
1008
+ *
1009
+ * Unless required by applicable law or agreed to in writing, software
1010
+ * distributed under the License is distributed on an "AS IS" BASIS,
1011
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1012
+ * See the License for the specific language governing permissions and
1013
+ * limitations under the License.
1014
+ */class Ih extends an{compare(e,t){const s=e.node.compareTo(t.node);return s===0?Ge(e.name,t.name):s}isDefinedOn(e){return!0}indexedValueChanged(e,t){return!e.equals(t)}minPost(){return v.MIN}maxPost(){return v.MAX}makePost(e,t){const s=H(e);return new v(t,s)}toString(){return".value"}}const Rh=new Ih;/**
1015
+ * @license
1016
+ * Copyright 2017 Google LLC
1017
+ *
1018
+ * Licensed under the Apache License, Version 2.0 (the "License");
1019
+ * you may not use this file except in compliance with the License.
1020
+ * You may obtain a copy of the License at
1021
+ *
1022
+ * http://www.apache.org/licenses/LICENSE-2.0
1023
+ *
1024
+ * Unless required by applicable law or agreed to in writing, software
1025
+ * distributed under the License is distributed on an "AS IS" BASIS,
1026
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1027
+ * See the License for the specific language governing permissions and
1028
+ * limitations under the License.
1029
+ */function ao(n){return{type:"value",snapshotNode:n}}function Ve(n,e){return{type:"child_added",snapshotNode:e,childName:n}}function ut(n,e){return{type:"child_removed",snapshotNode:e,childName:n}}function ht(n,e,t){return{type:"child_changed",snapshotNode:e,childName:n,oldSnap:t}}function Nh(n,e){return{type:"child_moved",snapshotNode:e,childName:n}}/**
1030
+ * @license
1031
+ * Copyright 2017 Google LLC
1032
+ *
1033
+ * Licensed under the Apache License, Version 2.0 (the "License");
1034
+ * you may not use this file except in compliance with the License.
1035
+ * You may obtain a copy of the License at
1036
+ *
1037
+ * http://www.apache.org/licenses/LICENSE-2.0
1038
+ *
1039
+ * Unless required by applicable law or agreed to in writing, software
1040
+ * distributed under the License is distributed on an "AS IS" BASIS,
1041
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1042
+ * See the License for the specific language governing permissions and
1043
+ * limitations under the License.
1044
+ */class ds{constructor(e){this.index_=e}updateChild(e,t,s,i,r,o){m(e.isIndexed(this.index_),"A node must be indexed if only a child is updated");const a=e.getImmediateChild(t);return a.getChild(i).equals(s.getChild(i))&&a.isEmpty()===s.isEmpty()||(o!=null&&(s.isEmpty()?e.hasChild(t)?o.trackChildChange(ut(t,a)):m(e.isLeafNode(),"A child remove without an old child only makes sense on a leaf node"):a.isEmpty()?o.trackChildChange(Ve(t,s)):o.trackChildChange(ht(t,s,a))),e.isLeafNode()&&s.isEmpty())?e:e.updateImmediateChild(t,s).withIndex(this.index_)}updateFullNode(e,t,s){return s!=null&&(e.isLeafNode()||e.forEachChild(P,(i,r)=>{t.hasChild(i)||s.trackChildChange(ut(i,r))}),t.isLeafNode()||t.forEachChild(P,(i,r)=>{if(e.hasChild(i)){const o=e.getImmediateChild(i);o.equals(r)||s.trackChildChange(ht(i,r,o))}else s.trackChildChange(Ve(i,r))})),t.withIndex(this.index_)}updatePriority(e,t){return e.isEmpty()?E.EMPTY_NODE:e.updatePriority(t)}filtersNodes(){return!1}getIndexedFilter(){return this}getIndex(){return this.index_}}/**
1045
+ * @license
1046
+ * Copyright 2017 Google LLC
1047
+ *
1048
+ * Licensed under the Apache License, Version 2.0 (the "License");
1049
+ * you may not use this file except in compliance with the License.
1050
+ * You may obtain a copy of the License at
1051
+ *
1052
+ * http://www.apache.org/licenses/LICENSE-2.0
1053
+ *
1054
+ * Unless required by applicable law or agreed to in writing, software
1055
+ * distributed under the License is distributed on an "AS IS" BASIS,
1056
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1057
+ * See the License for the specific language governing permissions and
1058
+ * limitations under the License.
1059
+ */class dt{constructor(e){this.indexedFilter_=new ds(e.getIndex()),this.index_=e.getIndex(),this.startPost_=dt.getStartPost_(e),this.endPost_=dt.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,s=this.endIsInclusive_?this.index_.compare(e,this.getEndPost())<=0:this.index_.compare(e,this.getEndPost())<0;return t&&s}updateChild(e,t,s,i,r,o){return this.matches(new v(t,s))||(s=E.EMPTY_NODE),this.indexedFilter_.updateChild(e,t,s,i,r,o)}updateFullNode(e,t,s){t.isLeafNode()&&(t=E.EMPTY_NODE);let i=t.withIndex(this.index_);i=i.updatePriority(E.EMPTY_NODE);const r=this;return t.forEachChild(P,(o,a)=>{r.matches(new v(o,a))||(i=i.updateImmediateChild(o,E.EMPTY_NODE))}),this.indexedFilter_.updateFullNode(e,i,s)}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)}else return e.getIndex().minPost()}static getEndPost_(e){if(e.hasEnd()){const t=e.getIndexEndName();return e.getIndex().makePost(e.getIndexEndValue(),t)}else return e.getIndex().maxPost()}}/**
1060
+ * @license
1061
+ * Copyright 2017 Google LLC
1062
+ *
1063
+ * Licensed under the Apache License, Version 2.0 (the "License");
1064
+ * you may not use this file except in compliance with the License.
1065
+ * You may obtain a copy of the License at
1066
+ *
1067
+ * http://www.apache.org/licenses/LICENSE-2.0
1068
+ *
1069
+ * Unless required by applicable law or agreed to in writing, software
1070
+ * distributed under the License is distributed on an "AS IS" BASIS,
1071
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1072
+ * See the License for the specific language governing permissions and
1073
+ * limitations under the License.
1074
+ */class Ah{constructor(e){this.withinDirectionalStart=t=>this.reverse_?this.withinEndPost(t):this.withinStartPost(t),this.withinDirectionalEnd=t=>this.reverse_?this.withinStartPost(t):this.withinEndPost(t),this.withinStartPost=t=>{const s=this.index_.compare(this.rangedFilter_.getStartPost(),t);return this.startIsInclusive_?s<=0:s<0},this.withinEndPost=t=>{const s=this.index_.compare(t,this.rangedFilter_.getEndPost());return this.endIsInclusive_?s<=0:s<0},this.rangedFilter_=new dt(e),this.index_=e.getIndex(),this.limit_=e.getLimit(),this.reverse_=!e.isViewFromLeft(),this.startIsInclusive_=!e.startAfterSet_,this.endIsInclusive_=!e.endBeforeSet_}updateChild(e,t,s,i,r,o){return this.rangedFilter_.matches(new v(t,s))||(s=E.EMPTY_NODE),e.getImmediateChild(t).equals(s)?e:e.numChildren()<this.limit_?this.rangedFilter_.getIndexedFilter().updateChild(e,t,s,i,r,o):this.fullLimitUpdateChild_(e,t,s,r,o)}updateFullNode(e,t,s){let i;if(t.isLeafNode()||t.isEmpty())i=E.EMPTY_NODE.withIndex(this.index_);else if(this.limit_*2<t.numChildren()&&t.isIndexed(this.index_)){i=E.EMPTY_NODE.withIndex(this.index_);let r;this.reverse_?r=t.getReverseIteratorFrom(this.rangedFilter_.getEndPost(),this.index_):r=t.getIteratorFrom(this.rangedFilter_.getStartPost(),this.index_);let o=0;for(;r.hasNext()&&o<this.limit_;){const a=r.getNext();if(this.withinDirectionalStart(a))if(this.withinDirectionalEnd(a))i=i.updateImmediateChild(a.name,a.node),o++;else break;else continue}}else{i=t.withIndex(this.index_),i=i.updatePriority(E.EMPTY_NODE);let r;this.reverse_?r=i.getReverseIterator(this.index_):r=i.getIterator(this.index_);let o=0;for(;r.hasNext();){const a=r.getNext();o<this.limit_&&this.withinDirectionalStart(a)&&this.withinDirectionalEnd(a)?o++:i=i.updateImmediateChild(a.name,E.EMPTY_NODE)}}return this.rangedFilter_.getIndexedFilter().updateFullNode(e,i,s)}updatePriority(e,t){return e}filtersNodes(){return!0}getIndexedFilter(){return this.rangedFilter_.getIndexedFilter()}getIndex(){return this.index_}fullLimitUpdateChild_(e,t,s,i,r){let o;if(this.reverse_){const h=this.index_.getCompare();o=(d,_)=>h(_,d)}else o=this.index_.getCompare();const a=e;m(a.numChildren()===this.limit_,"");const c=new v(t,s),l=this.reverse_?a.getFirstChild(this.index_):a.getLastChild(this.index_),u=this.rangedFilter_.matches(c);if(a.hasChild(t)){const h=a.getImmediateChild(t);let d=i.getChildAfterChild(this.index_,l,this.reverse_);for(;d!=null&&(d.name===t||a.hasChild(d.name));)d=i.getChildAfterChild(this.index_,d,this.reverse_);const _=d==null?1:o(d,c);if(u&&!s.isEmpty()&&_>=0)return r!=null&&r.trackChildChange(ht(t,s,h)),a.updateImmediateChild(t,s);{r!=null&&r.trackChildChange(ut(t,h));const y=a.updateImmediateChild(t,E.EMPTY_NODE);return d!=null&&this.rangedFilter_.matches(d)?(r!=null&&r.trackChildChange(Ve(d.name,d.node)),y.updateImmediateChild(d.name,d.node)):y}}else return s.isEmpty()?e:u&&o(l,c)>=0?(r!=null&&(r.trackChildChange(ut(l.name,l.node)),r.trackChildChange(Ve(t,s))),a.updateImmediateChild(t,s).updateImmediateChild(l.name,E.EMPTY_NODE)):e}}/**
1075
+ * @license
1076
+ * Copyright 2017 Google LLC
1077
+ *
1078
+ * Licensed under the Apache License, Version 2.0 (the "License");
1079
+ * you may not use this file except in compliance with the License.
1080
+ * You may obtain a copy of the License at
1081
+ *
1082
+ * http://www.apache.org/licenses/LICENSE-2.0
1083
+ *
1084
+ * Unless required by applicable law or agreed to in writing, software
1085
+ * distributed under the License is distributed on an "AS IS" BASIS,
1086
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1087
+ * See the License for the specific language governing permissions and
1088
+ * limitations under the License.
1089
+ */class fs{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_=P}hasStart(){return this.startSet_}isViewFromLeft(){return this.viewFrom_===""?this.startSet_:this.viewFrom_==="l"}getIndexStartValue(){return m(this.startSet_,"Only valid if start has been set"),this.indexStartValue_}getIndexStartName(){return m(this.startSet_,"Only valid if start has been set"),this.startNameSet_?this.indexStartName_:He}hasEnd(){return this.endSet_}getIndexEndValue(){return m(this.endSet_,"Only valid if end has been set"),this.indexEndValue_}getIndexEndName(){return m(this.endSet_,"Only valid if end has been set"),this.endNameSet_?this.indexEndName_:Re}hasLimit(){return this.limitSet_}hasAnchoredLimit(){return this.limitSet_&&this.viewFrom_!==""}getLimit(){return m(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_===P}copy(){const e=new fs;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 kh(n){return n.loadsAllData()?new ds(n.getIndex()):n.hasLimit()?new Ah(n):new dt(n)}function vi(n){const e={};if(n.isDefault())return e;let t;if(n.index_===P?t="$priority":n.index_===Rh?t="$value":n.index_===Ue?t="$key":(m(n.index_ instanceof Th,"Unrecognized index type!"),t=n.index_.toString()),e.orderBy=B(t),n.startSet_){const s=n.startAfterSet_?"startAfter":"startAt";e[s]=B(n.indexStartValue_),n.startNameSet_&&(e[s]+=","+B(n.indexStartName_))}if(n.endSet_){const s=n.endBeforeSet_?"endBefore":"endAt";e[s]=B(n.indexEndValue_),n.endNameSet_&&(e[s]+=","+B(n.indexEndName_))}return n.limitSet_&&(n.isViewFromLeft()?e.limitToFirst=n.limit_:e.limitToLast=n.limit_),e}function Ci(n){const e={};if(n.startSet_&&(e.sp=n.indexStartValue_,n.startNameSet_&&(e.sn=n.indexStartName_),e.sin=!n.startAfterSet_),n.endSet_&&(e.ep=n.indexEndValue_,n.endNameSet_&&(e.en=n.indexEndName_),e.ein=!n.endBeforeSet_),n.limitSet_){e.l=n.limit_;let t=n.viewFrom_;t===""&&(n.isViewFromLeft()?t="l":t="r"),e.vf=t}return n.index_!==P&&(e.i=n.index_.toString()),e}/**
1090
+ * @license
1091
+ * Copyright 2017 Google LLC
1092
+ *
1093
+ * Licensed under the Apache License, Version 2.0 (the "License");
1094
+ * you may not use this file except in compliance with the License.
1095
+ * You may obtain a copy of the License at
1096
+ *
1097
+ * http://www.apache.org/licenses/LICENSE-2.0
1098
+ *
1099
+ * Unless required by applicable law or agreed to in writing, software
1100
+ * distributed under the License is distributed on an "AS IS" BASIS,
1101
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1102
+ * See the License for the specific language governing permissions and
1103
+ * limitations under the License.
1104
+ */class Vt extends Qr{reportStats(e){throw new Error("Method not implemented.")}static getListenId_(e,t){return t!==void 0?"tag$"+t:(m(e._queryParams.isDefault(),"should have a tag if it's not a default query."),e._path.toString())}constructor(e,t,s,i){super(),this.repoInfo_=e,this.onDataUpdate_=t,this.authTokenProvider_=s,this.appCheckTokenProvider_=i,this.log_=wt("p:rest:"),this.listens_={}}listen(e,t,s,i){const r=e._path.toString();this.log_("Listen called for "+r+" "+e._queryIdentifier);const o=Vt.getListenId_(e,s),a={};this.listens_[o]=a;const c=vi(e._queryParams);this.restRequest_(r+".json",c,(l,u)=>{let h=u;if(l===404&&(h=null,l=null),l===null&&this.onDataUpdate_(r,h,!1,s),We(this.listens_,o)===a){let d;l?l===401?d="permission_denied":d="rest_error:"+l:d="ok",i(d,null)}})}unlisten(e,t){const s=Vt.getListenId_(e,t);delete this.listens_[s]}get(e){const t=vi(e._queryParams),s=e._path.toString(),i=new ss;return this.restRequest_(s+".json",t,(r,o)=>{let a=o;r===404&&(a=null,r=null),r===null?(this.onDataUpdate_(s,a,!1,null),i.resolve(a)):i.reject(new Error(a))}),i.promise}refreshAuthToken(e){}restRequest_(e,t={},s){return t.format="export",Promise.all([this.authTokenProvider_.getToken(!1),this.appCheckTokenProvider_.getToken(!1)]).then(([i,r])=>{i&&i.accessToken&&(t.auth=i.accessToken),r&&r.token&&(t.ac=r.token);const o=(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host+e+"?ns="+this.repoInfo_.namespace+sc(t);this.log_("Sending REST request for "+o);const a=new XMLHttpRequest;a.onreadystatechange=()=>{if(s&&a.readyState===4){this.log_("REST Response for "+o+" received. status:",a.status,"response:",a.responseText);let c=null;if(a.status>=200&&a.status<300){try{c=ot(a.responseText)}catch{Y("Failed to parse JSON response for "+o+": "+a.responseText)}s(null,c)}else a.status!==401&&a.status!==404&&Y("Got unsuccessful REST response for "+o+" Status: "+a.status),s(a.status);s=null}},a.open("GET",o,!0),a.send()})}}/**
1105
+ * @license
1106
+ * Copyright 2017 Google LLC
1107
+ *
1108
+ * Licensed under the Apache License, Version 2.0 (the "License");
1109
+ * you may not use this file except in compliance with the License.
1110
+ * You may obtain a copy of the License at
1111
+ *
1112
+ * http://www.apache.org/licenses/LICENSE-2.0
1113
+ *
1114
+ * Unless required by applicable law or agreed to in writing, software
1115
+ * distributed under the License is distributed on an "AS IS" BASIS,
1116
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1117
+ * See the License for the specific language governing permissions and
1118
+ * limitations under the License.
1119
+ */class xh{constructor(){this.rootNode_=E.EMPTY_NODE}getNode(e){return this.rootNode_.getChild(e)}updateSnapshot(e,t){this.rootNode_=this.rootNode_.updateChild(e,t)}}/**
1120
+ * @license
1121
+ * Copyright 2017 Google LLC
1122
+ *
1123
+ * Licensed under the Apache License, Version 2.0 (the "License");
1124
+ * you may not use this file except in compliance with the License.
1125
+ * You may obtain a copy of the License at
1126
+ *
1127
+ * http://www.apache.org/licenses/LICENSE-2.0
1128
+ *
1129
+ * Unless required by applicable law or agreed to in writing, software
1130
+ * distributed under the License is distributed on an "AS IS" BASIS,
1131
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1132
+ * See the License for the specific language governing permissions and
1133
+ * limitations under the License.
1134
+ */function qt(){return{value:null,children:new Map}}function lo(n,e,t){if(b(e))n.value=t,n.children.clear();else if(n.value!==null)n.value=n.value.updateChild(e,t);else{const s=C(e);n.children.has(s)||n.children.set(s,qt());const i=n.children.get(s);e=k(e),lo(i,e,t)}}function qn(n,e,t){n.value!==null?t(e,n.value):Oh(n,(s,i)=>{const r=new N(e.toString()+"/"+s);qn(i,r,t)})}function Oh(n,e){n.children.forEach((t,s)=>{e(s,t)})}/**
1135
+ * @license
1136
+ * Copyright 2017 Google LLC
1137
+ *
1138
+ * Licensed under the Apache License, Version 2.0 (the "License");
1139
+ * you may not use this file except in compliance with the License.
1140
+ * You may obtain a copy of the License at
1141
+ *
1142
+ * http://www.apache.org/licenses/LICENSE-2.0
1143
+ *
1144
+ * Unless required by applicable law or agreed to in writing, software
1145
+ * distributed under the License is distributed on an "AS IS" BASIS,
1146
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1147
+ * See the License for the specific language governing permissions and
1148
+ * limitations under the License.
1149
+ */class Dh{constructor(e){this.collection_=e,this.last_=null}get(){const e=this.collection_.get(),t=Object.assign({},e);return this.last_&&G(this.last_,(s,i)=>{t[s]=t[s]-i}),this.last_=e,t}}/**
1150
+ * @license
1151
+ * Copyright 2017 Google LLC
1152
+ *
1153
+ * Licensed under the Apache License, Version 2.0 (the "License");
1154
+ * you may not use this file except in compliance with the License.
1155
+ * You may obtain a copy of the License at
1156
+ *
1157
+ * http://www.apache.org/licenses/LICENSE-2.0
1158
+ *
1159
+ * Unless required by applicable law or agreed to in writing, software
1160
+ * distributed under the License is distributed on an "AS IS" BASIS,
1161
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1162
+ * See the License for the specific language governing permissions and
1163
+ * limitations under the License.
1164
+ */const bi=10*1e3,Ph=30*1e3,Mh=5*60*1e3;class Lh{constructor(e,t){this.server_=t,this.statsToReport_={},this.statsListener_=new Dh(e);const s=bi+(Ph-bi)*Math.random();tt(this.reportStats_.bind(this),Math.floor(s))}reportStats_(){const e=this.statsListener_.get(),t={};let s=!1;G(e,(i,r)=>{r>0&&he(this.statsToReport_,i)&&(t[i]=r,s=!0)}),s&&this.server_.reportStats(t),tt(this.reportStats_.bind(this),Math.floor(Math.random()*2*Mh))}}/**
1165
+ * @license
1166
+ * Copyright 2017 Google LLC
1167
+ *
1168
+ * Licensed under the Apache License, Version 2.0 (the "License");
1169
+ * you may not use this file except in compliance with the License.
1170
+ * You may obtain a copy of the License at
1171
+ *
1172
+ * http://www.apache.org/licenses/LICENSE-2.0
1173
+ *
1174
+ * Unless required by applicable law or agreed to in writing, software
1175
+ * distributed under the License is distributed on an "AS IS" BASIS,
1176
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1177
+ * See the License for the specific language governing permissions and
1178
+ * limitations under the License.
1179
+ */var ne;(function(n){n[n.OVERWRITE=0]="OVERWRITE",n[n.MERGE=1]="MERGE",n[n.ACK_USER_WRITE=2]="ACK_USER_WRITE",n[n.LISTEN_COMPLETE=3]="LISTEN_COMPLETE"})(ne||(ne={}));function co(){return{fromUser:!0,fromServer:!1,queryId:null,tagged:!1}}function ps(){return{fromUser:!1,fromServer:!0,queryId:null,tagged:!1}}function _s(n){return{fromUser:!1,fromServer:!0,queryId:n,tagged:!0}}/**
1180
+ * @license
1181
+ * Copyright 2017 Google LLC
1182
+ *
1183
+ * Licensed under the Apache License, Version 2.0 (the "License");
1184
+ * you may not use this file except in compliance with the License.
1185
+ * You may obtain a copy of the License at
1186
+ *
1187
+ * http://www.apache.org/licenses/LICENSE-2.0
1188
+ *
1189
+ * Unless required by applicable law or agreed to in writing, software
1190
+ * distributed under the License is distributed on an "AS IS" BASIS,
1191
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1192
+ * See the License for the specific language governing permissions and
1193
+ * limitations under the License.
1194
+ */class $t{constructor(e,t,s){this.path=e,this.affectedTree=t,this.revert=s,this.type=ne.ACK_USER_WRITE,this.source=co()}operationForChild(e){if(b(this.path)){if(this.affectedTree.value!=null)return m(this.affectedTree.children.isEmpty(),"affectedTree should not have overlapping affected paths."),this;{const t=this.affectedTree.subtree(new N(e));return new $t(S(),t,this.revert)}}else return m(C(this.path)===e,"operationForChild called for unrelated child."),new $t(k(this.path),this.affectedTree,this.revert)}}/**
1195
+ * @license
1196
+ * Copyright 2017 Google LLC
1197
+ *
1198
+ * Licensed under the Apache License, Version 2.0 (the "License");
1199
+ * you may not use this file except in compliance with the License.
1200
+ * You may obtain a copy of the License at
1201
+ *
1202
+ * http://www.apache.org/licenses/LICENSE-2.0
1203
+ *
1204
+ * Unless required by applicable law or agreed to in writing, software
1205
+ * distributed under the License is distributed on an "AS IS" BASIS,
1206
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1207
+ * See the License for the specific language governing permissions and
1208
+ * limitations under the License.
1209
+ */class ft{constructor(e,t){this.source=e,this.path=t,this.type=ne.LISTEN_COMPLETE}operationForChild(e){return b(this.path)?new ft(this.source,S()):new ft(this.source,k(this.path))}}/**
1210
+ * @license
1211
+ * Copyright 2017 Google LLC
1212
+ *
1213
+ * Licensed under the Apache License, Version 2.0 (the "License");
1214
+ * you may not use this file except in compliance with the License.
1215
+ * You may obtain a copy of the License at
1216
+ *
1217
+ * http://www.apache.org/licenses/LICENSE-2.0
1218
+ *
1219
+ * Unless required by applicable law or agreed to in writing, software
1220
+ * distributed under the License is distributed on an "AS IS" BASIS,
1221
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1222
+ * See the License for the specific language governing permissions and
1223
+ * limitations under the License.
1224
+ */class Ne{constructor(e,t,s){this.source=e,this.path=t,this.snap=s,this.type=ne.OVERWRITE}operationForChild(e){return b(this.path)?new Ne(this.source,S(),this.snap.getImmediateChild(e)):new Ne(this.source,k(this.path),this.snap)}}/**
1225
+ * @license
1226
+ * Copyright 2017 Google LLC
1227
+ *
1228
+ * Licensed under the Apache License, Version 2.0 (the "License");
1229
+ * you may not use this file except in compliance with the License.
1230
+ * You may obtain a copy of the License at
1231
+ *
1232
+ * http://www.apache.org/licenses/LICENSE-2.0
1233
+ *
1234
+ * Unless required by applicable law or agreed to in writing, software
1235
+ * distributed under the License is distributed on an "AS IS" BASIS,
1236
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1237
+ * See the License for the specific language governing permissions and
1238
+ * limitations under the License.
1239
+ */class pt{constructor(e,t,s){this.source=e,this.path=t,this.children=s,this.type=ne.MERGE}operationForChild(e){if(b(this.path)){const t=this.children.subtree(new N(e));return t.isEmpty()?null:t.value?new Ne(this.source,S(),t.value):new pt(this.source,S(),t)}else return m(C(this.path)===e,"Can't get a merge for a child not on the path of the operation"),new pt(this.source,k(this.path),this.children)}toString(){return"Operation("+this.path+": "+this.source.toString()+" merge: "+this.children.toString()+")"}}/**
1240
+ * @license
1241
+ * Copyright 2017 Google LLC
1242
+ *
1243
+ * Licensed under the Apache License, Version 2.0 (the "License");
1244
+ * you may not use this file except in compliance with the License.
1245
+ * You may obtain a copy of the License at
1246
+ *
1247
+ * http://www.apache.org/licenses/LICENSE-2.0
1248
+ *
1249
+ * Unless required by applicable law or agreed to in writing, software
1250
+ * distributed under the License is distributed on an "AS IS" BASIS,
1251
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1252
+ * See the License for the specific language governing permissions and
1253
+ * limitations under the License.
1254
+ */class Ae{constructor(e,t,s){this.node_=e,this.fullyInitialized_=t,this.filtered_=s}isFullyInitialized(){return this.fullyInitialized_}isFiltered(){return this.filtered_}isCompleteForPath(e){if(b(e))return this.isFullyInitialized()&&!this.filtered_;const t=C(e);return this.isCompleteForChild(t)}isCompleteForChild(e){return this.isFullyInitialized()&&!this.filtered_||this.node_.hasChild(e)}getNode(){return this.node_}}/**
1255
+ * @license
1256
+ * Copyright 2017 Google LLC
1257
+ *
1258
+ * Licensed under the Apache License, Version 2.0 (the "License");
1259
+ * you may not use this file except in compliance with the License.
1260
+ * You may obtain a copy of the License at
1261
+ *
1262
+ * http://www.apache.org/licenses/LICENSE-2.0
1263
+ *
1264
+ * Unless required by applicable law or agreed to in writing, software
1265
+ * distributed under the License is distributed on an "AS IS" BASIS,
1266
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1267
+ * See the License for the specific language governing permissions and
1268
+ * limitations under the License.
1269
+ */class Fh{constructor(e){this.query_=e,this.index_=this.query_._queryParams.getIndex()}}function Uh(n,e,t,s){const i=[],r=[];return e.forEach(o=>{o.type==="child_changed"&&n.index_.indexedValueChanged(o.oldSnap,o.snapshotNode)&&r.push(Nh(o.childName,o.snapshotNode))}),Ze(n,i,"child_removed",e,s,t),Ze(n,i,"child_added",e,s,t),Ze(n,i,"child_moved",r,s,t),Ze(n,i,"child_changed",e,s,t),Ze(n,i,"value",e,s,t),i}function Ze(n,e,t,s,i,r){const o=s.filter(a=>a.type===t);o.sort((a,c)=>Wh(n,a,c)),o.forEach(a=>{const c=Bh(n,a,r);i.forEach(l=>{l.respondsTo(a.type)&&e.push(l.createEvent(c,n.query_))})})}function Bh(n,e,t){return e.type==="value"||e.type==="child_removed"||(e.prevName=t.getPredecessorChildName(e.childName,e.snapshotNode,n.index_)),e}function Wh(n,e,t){if(e.childName==null||t.childName==null)throw ze("Should only compare child_ events.");const s=new v(e.childName,e.snapshotNode),i=new v(t.childName,t.snapshotNode);return n.index_.compare(s,i)}/**
1270
+ * @license
1271
+ * Copyright 2017 Google LLC
1272
+ *
1273
+ * Licensed under the Apache License, Version 2.0 (the "License");
1274
+ * you may not use this file except in compliance with the License.
1275
+ * You may obtain a copy of the License at
1276
+ *
1277
+ * http://www.apache.org/licenses/LICENSE-2.0
1278
+ *
1279
+ * Unless required by applicable law or agreed to in writing, software
1280
+ * distributed under the License is distributed on an "AS IS" BASIS,
1281
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1282
+ * See the License for the specific language governing permissions and
1283
+ * limitations under the License.
1284
+ */function ln(n,e){return{eventCache:n,serverCache:e}}function nt(n,e,t,s){return ln(new Ae(e,t,s),n.serverCache)}function uo(n,e,t,s){return ln(n.eventCache,new Ae(e,t,s))}function $n(n){return n.eventCache.isFullyInitialized()?n.eventCache.getNode():null}function ke(n){return n.serverCache.isFullyInitialized()?n.serverCache.getNode():null}/**
1285
+ * @license
1286
+ * Copyright 2017 Google LLC
1287
+ *
1288
+ * Licensed under the Apache License, Version 2.0 (the "License");
1289
+ * you may not use this file except in compliance with the License.
1290
+ * You may obtain a copy of the License at
1291
+ *
1292
+ * http://www.apache.org/licenses/LICENSE-2.0
1293
+ *
1294
+ * Unless required by applicable law or agreed to in writing, software
1295
+ * distributed under the License is distributed on an "AS IS" BASIS,
1296
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1297
+ * See the License for the specific language governing permissions and
1298
+ * limitations under the License.
1299
+ */let Tn;const Hh=()=>(Tn||(Tn=new j(Iu)),Tn);class x{static fromObject(e){let t=new x(null);return G(e,(s,i)=>{t=t.set(new N(s),i)}),t}constructor(e,t=Hh()){this.value=e,this.children=t}isEmpty(){return this.value===null&&this.children.isEmpty()}findRootMostMatchingPathAndValue(e,t){if(this.value!=null&&t(this.value))return{path:S(),value:this.value};if(b(e))return null;{const s=C(e),i=this.children.get(s);if(i!==null){const r=i.findRootMostMatchingPathAndValue(k(e),t);return r!=null?{path:L(new N(s),r.path),value:r.value}:null}else return null}}findRootMostValueAndPath(e){return this.findRootMostMatchingPathAndValue(e,()=>!0)}subtree(e){if(b(e))return this;{const t=C(e),s=this.children.get(t);return s!==null?s.subtree(k(e)):new x(null)}}set(e,t){if(b(e))return new x(t,this.children);{const s=C(e),r=(this.children.get(s)||new x(null)).set(k(e),t),o=this.children.insert(s,r);return new x(this.value,o)}}remove(e){if(b(e))return this.children.isEmpty()?new x(null):new x(null,this.children);{const t=C(e),s=this.children.get(t);if(s){const i=s.remove(k(e));let r;return i.isEmpty()?r=this.children.remove(t):r=this.children.insert(t,i),this.value===null&&r.isEmpty()?new x(null):new x(this.value,r)}else return this}}get(e){if(b(e))return this.value;{const t=C(e),s=this.children.get(t);return s?s.get(k(e)):null}}setTree(e,t){if(b(e))return t;{const s=C(e),r=(this.children.get(s)||new x(null)).setTree(k(e),t);let o;return r.isEmpty()?o=this.children.remove(s):o=this.children.insert(s,r),new x(this.value,o)}}fold(e){return this.fold_(S(),e)}fold_(e,t){const s={};return this.children.inorderTraversal((i,r)=>{s[i]=r.fold_(L(e,i),t)}),t(e,this.value,s)}findOnPath(e,t){return this.findOnPath_(e,S(),t)}findOnPath_(e,t,s){const i=this.value?s(t,this.value):!1;if(i)return i;if(b(e))return null;{const r=C(e),o=this.children.get(r);return o?o.findOnPath_(k(e),L(t,r),s):null}}foreachOnPath(e,t){return this.foreachOnPath_(e,S(),t)}foreachOnPath_(e,t,s){if(b(e))return this;{this.value&&s(t,this.value);const i=C(e),r=this.children.get(i);return r?r.foreachOnPath_(k(e),L(t,i),s):new x(null)}}foreach(e){this.foreach_(S(),e)}foreach_(e,t){this.children.inorderTraversal((s,i)=>{i.foreach_(L(e,s),t)}),this.value&&t(e,this.value)}foreachChild(e){this.children.inorderTraversal((t,s)=>{s.value&&e(t,s.value)})}}/**
1300
+ * @license
1301
+ * Copyright 2017 Google LLC
1302
+ *
1303
+ * Licensed under the Apache License, Version 2.0 (the "License");
1304
+ * you may not use this file except in compliance with the License.
1305
+ * You may obtain a copy of the License at
1306
+ *
1307
+ * http://www.apache.org/licenses/LICENSE-2.0
1308
+ *
1309
+ * Unless required by applicable law or agreed to in writing, software
1310
+ * distributed under the License is distributed on an "AS IS" BASIS,
1311
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1312
+ * See the License for the specific language governing permissions and
1313
+ * limitations under the License.
1314
+ */class se{constructor(e){this.writeTree_=e}static empty(){return new se(new x(null))}}function st(n,e,t){if(b(e))return new se(new x(t));{const s=n.writeTree_.findRootMostValueAndPath(e);if(s!=null){const i=s.path;let r=s.value;const o=$(i,e);return r=r.updateChild(o,t),new se(n.writeTree_.set(i,r))}else{const i=new x(t),r=n.writeTree_.setTree(e,i);return new se(r)}}}function Si(n,e,t){let s=n;return G(t,(i,r)=>{s=st(s,L(e,i),r)}),s}function Ti(n,e){if(b(e))return se.empty();{const t=n.writeTree_.setTree(e,new x(null));return new se(t)}}function jn(n,e){return xe(n,e)!=null}function xe(n,e){const t=n.writeTree_.findRootMostValueAndPath(e);return t!=null?n.writeTree_.get(t.path).getChild($(t.path,e)):null}function Ii(n){const e=[],t=n.writeTree_.value;return t!=null?t.isLeafNode()||t.forEachChild(P,(s,i)=>{e.push(new v(s,i))}):n.writeTree_.children.inorderTraversal((s,i)=>{i.value!=null&&e.push(new v(s,i.value))}),e}function me(n,e){if(b(e))return n;{const t=xe(n,e);return t!=null?new se(new x(t)):new se(n.writeTree_.subtree(e))}}function zn(n){return n.writeTree_.isEmpty()}function qe(n,e){return ho(S(),n.writeTree_,e)}function ho(n,e,t){if(e.value!=null)return t.updateChild(n,e.value);{let s=null;return e.children.inorderTraversal((i,r)=>{i===".priority"?(m(r.value!==null,"Priority writes must always be leaf nodes"),s=r.value):t=ho(L(n,i),r,t)}),!t.getChild(n).isEmpty()&&s!==null&&(t=t.updateChild(L(n,".priority"),s)),t}}/**
1315
+ * @license
1316
+ * Copyright 2017 Google LLC
1317
+ *
1318
+ * Licensed under the Apache License, Version 2.0 (the "License");
1319
+ * you may not use this file except in compliance with the License.
1320
+ * You may obtain a copy of the License at
1321
+ *
1322
+ * http://www.apache.org/licenses/LICENSE-2.0
1323
+ *
1324
+ * Unless required by applicable law or agreed to in writing, software
1325
+ * distributed under the License is distributed on an "AS IS" BASIS,
1326
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1327
+ * See the License for the specific language governing permissions and
1328
+ * limitations under the License.
1329
+ */function ms(n,e){return mo(e,n)}function Vh(n,e,t,s,i){m(s>n.lastWriteId,"Stacking an older write on top of newer ones"),i===void 0&&(i=!0),n.allWrites.push({path:e,snap:t,writeId:s,visible:i}),i&&(n.visibleWrites=st(n.visibleWrites,e,t)),n.lastWriteId=s}function qh(n,e){for(let t=0;t<n.allWrites.length;t++){const s=n.allWrites[t];if(s.writeId===e)return s}return null}function $h(n,e){const t=n.allWrites.findIndex(a=>a.writeId===e);m(t>=0,"removeWrite called with nonexistent writeId.");const s=n.allWrites[t];n.allWrites.splice(t,1);let i=s.visible,r=!1,o=n.allWrites.length-1;for(;i&&o>=0;){const a=n.allWrites[o];a.visible&&(o>=t&&jh(a,s.path)?i=!1:te(s.path,a.path)&&(r=!0)),o--}if(i){if(r)return zh(n),!0;if(s.snap)n.visibleWrites=Ti(n.visibleWrites,s.path);else{const a=s.children;G(a,c=>{n.visibleWrites=Ti(n.visibleWrites,L(s.path,c))})}return!0}else return!1}function jh(n,e){if(n.snap)return te(n.path,e);for(const t in n.children)if(n.children.hasOwnProperty(t)&&te(L(n.path,t),e))return!0;return!1}function zh(n){n.visibleWrites=fo(n.allWrites,Gh,S()),n.allWrites.length>0?n.lastWriteId=n.allWrites[n.allWrites.length-1].writeId:n.lastWriteId=-1}function Gh(n){return n.visible}function fo(n,e,t){let s=se.empty();for(let i=0;i<n.length;++i){const r=n[i];if(e(r)){const o=r.path;let a;if(r.snap)te(t,o)?(a=$(t,o),s=st(s,a,r.snap)):te(o,t)&&(a=$(o,t),s=st(s,S(),r.snap.getChild(a)));else if(r.children){if(te(t,o))a=$(t,o),s=Si(s,a,r.children);else if(te(o,t))if(a=$(o,t),b(a))s=Si(s,S(),r.children);else{const c=We(r.children,C(a));if(c){const l=c.getChild(k(a));s=st(s,S(),l)}}}else throw ze("WriteRecord should have .snap or .children")}}return s}function po(n,e,t,s,i){if(!s&&!i){const r=xe(n.visibleWrites,e);if(r!=null)return r;{const o=me(n.visibleWrites,e);if(zn(o))return t;if(t==null&&!jn(o,S()))return null;{const a=t||E.EMPTY_NODE;return qe(o,a)}}}else{const r=me(n.visibleWrites,e);if(!i&&zn(r))return t;if(!i&&t==null&&!jn(r,S()))return null;{const o=function(l){return(l.visible||i)&&(!s||!~s.indexOf(l.writeId))&&(te(l.path,e)||te(e,l.path))},a=fo(n.allWrites,o,e),c=t||E.EMPTY_NODE;return qe(a,c)}}}function Kh(n,e,t){let s=E.EMPTY_NODE;const i=xe(n.visibleWrites,e);if(i)return i.isLeafNode()||i.forEachChild(P,(r,o)=>{s=s.updateImmediateChild(r,o)}),s;if(t){const r=me(n.visibleWrites,e);return t.forEachChild(P,(o,a)=>{const c=qe(me(r,new N(o)),a);s=s.updateImmediateChild(o,c)}),Ii(r).forEach(o=>{s=s.updateImmediateChild(o.name,o.node)}),s}else{const r=me(n.visibleWrites,e);return Ii(r).forEach(o=>{s=s.updateImmediateChild(o.name,o.node)}),s}}function Yh(n,e,t,s,i){m(s||i,"Either existingEventSnap or existingServerSnap must exist");const r=L(e,t);if(jn(n.visibleWrites,r))return null;{const o=me(n.visibleWrites,r);return zn(o)?i.getChild(t):qe(o,i.getChild(t))}}function Qh(n,e,t,s){const i=L(e,t),r=xe(n.visibleWrites,i);if(r!=null)return r;if(s.isCompleteForChild(t)){const o=me(n.visibleWrites,i);return qe(o,s.getNode().getImmediateChild(t))}else return null}function Jh(n,e){return xe(n.visibleWrites,e)}function Xh(n,e,t,s,i,r,o){let a;const c=me(n.visibleWrites,e),l=xe(c,S());if(l!=null)a=l;else if(t!=null)a=qe(c,t);else return[];if(a=a.withIndex(o),!a.isEmpty()&&!a.isLeafNode()){const u=[],h=o.getCompare(),d=r?a.getReverseIteratorFrom(s,o):a.getIteratorFrom(s,o);let _=d.getNext();for(;_&&u.length<i;)h(_,s)!==0&&u.push(_),_=d.getNext();return u}else return[]}function Zh(){return{visibleWrites:se.empty(),allWrites:[],lastWriteId:-1}}function jt(n,e,t,s){return po(n.writeTree,n.treePath,e,t,s)}function gs(n,e){return Kh(n.writeTree,n.treePath,e)}function Ri(n,e,t,s){return Yh(n.writeTree,n.treePath,e,t,s)}function zt(n,e){return Jh(n.writeTree,L(n.treePath,e))}function ed(n,e,t,s,i,r){return Xh(n.writeTree,n.treePath,e,t,s,i,r)}function ys(n,e,t){return Qh(n.writeTree,n.treePath,e,t)}function _o(n,e){return mo(L(n.treePath,e),n.writeTree)}function mo(n,e){return{treePath:n,writeTree:e}}/**
1330
+ * @license
1331
+ * Copyright 2017 Google LLC
1332
+ *
1333
+ * Licensed under the Apache License, Version 2.0 (the "License");
1334
+ * you may not use this file except in compliance with the License.
1335
+ * You may obtain a copy of the License at
1336
+ *
1337
+ * http://www.apache.org/licenses/LICENSE-2.0
1338
+ *
1339
+ * Unless required by applicable law or agreed to in writing, software
1340
+ * distributed under the License is distributed on an "AS IS" BASIS,
1341
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1342
+ * See the License for the specific language governing permissions and
1343
+ * limitations under the License.
1344
+ */class td{constructor(){this.changeMap=new Map}trackChildChange(e){const t=e.type,s=e.childName;m(t==="child_added"||t==="child_changed"||t==="child_removed","Only child changes supported for tracking"),m(s!==".priority","Only non-priority child changes can be tracked.");const i=this.changeMap.get(s);if(i){const r=i.type;if(t==="child_added"&&r==="child_removed")this.changeMap.set(s,ht(s,e.snapshotNode,i.snapshotNode));else if(t==="child_removed"&&r==="child_added")this.changeMap.delete(s);else if(t==="child_removed"&&r==="child_changed")this.changeMap.set(s,ut(s,i.oldSnap));else if(t==="child_changed"&&r==="child_added")this.changeMap.set(s,Ve(s,e.snapshotNode));else if(t==="child_changed"&&r==="child_changed")this.changeMap.set(s,ht(s,e.snapshotNode,i.oldSnap));else throw ze("Illegal combination of changes: "+e+" occurred after "+i)}else this.changeMap.set(s,e)}getChanges(){return Array.from(this.changeMap.values())}}/**
1345
+ * @license
1346
+ * Copyright 2017 Google LLC
1347
+ *
1348
+ * Licensed under the Apache License, Version 2.0 (the "License");
1349
+ * you may not use this file except in compliance with the License.
1350
+ * You may obtain a copy of the License at
1351
+ *
1352
+ * http://www.apache.org/licenses/LICENSE-2.0
1353
+ *
1354
+ * Unless required by applicable law or agreed to in writing, software
1355
+ * distributed under the License is distributed on an "AS IS" BASIS,
1356
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1357
+ * See the License for the specific language governing permissions and
1358
+ * limitations under the License.
1359
+ */class nd{getCompleteChild(e){return null}getChildAfterChild(e,t,s){return null}}const go=new nd;class Es{constructor(e,t,s=null){this.writes_=e,this.viewCache_=t,this.optCompleteServerCache_=s}getCompleteChild(e){const t=this.viewCache_.eventCache;if(t.isCompleteForChild(e))return t.getNode().getImmediateChild(e);{const s=this.optCompleteServerCache_!=null?new Ae(this.optCompleteServerCache_,!0,!1):this.viewCache_.serverCache;return ys(this.writes_,e,s)}}getChildAfterChild(e,t,s){const i=this.optCompleteServerCache_!=null?this.optCompleteServerCache_:ke(this.viewCache_),r=ed(this.writes_,i,t,1,s,e);return r.length===0?null:r[0]}}/**
1360
+ * @license
1361
+ * Copyright 2017 Google LLC
1362
+ *
1363
+ * Licensed under the Apache License, Version 2.0 (the "License");
1364
+ * you may not use this file except in compliance with the License.
1365
+ * You may obtain a copy of the License at
1366
+ *
1367
+ * http://www.apache.org/licenses/LICENSE-2.0
1368
+ *
1369
+ * Unless required by applicable law or agreed to in writing, software
1370
+ * distributed under the License is distributed on an "AS IS" BASIS,
1371
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1372
+ * See the License for the specific language governing permissions and
1373
+ * limitations under the License.
1374
+ */function sd(n){return{filter:n}}function id(n,e){m(e.eventCache.getNode().isIndexed(n.filter.getIndex()),"Event snap not indexed"),m(e.serverCache.getNode().isIndexed(n.filter.getIndex()),"Server snap not indexed")}function rd(n,e,t,s,i){const r=new td;let o,a;if(t.type===ne.OVERWRITE){const l=t;l.source.fromUser?o=Gn(n,e,l.path,l.snap,s,i,r):(m(l.source.fromServer,"Unknown source."),a=l.source.tagged||e.serverCache.isFiltered()&&!b(l.path),o=Gt(n,e,l.path,l.snap,s,i,a,r))}else if(t.type===ne.MERGE){const l=t;l.source.fromUser?o=ad(n,e,l.path,l.children,s,i,r):(m(l.source.fromServer,"Unknown source."),a=l.source.tagged||e.serverCache.isFiltered(),o=Kn(n,e,l.path,l.children,s,i,a,r))}else if(t.type===ne.ACK_USER_WRITE){const l=t;l.revert?o=ud(n,e,l.path,s,i,r):o=ld(n,e,l.path,l.affectedTree,s,i,r)}else if(t.type===ne.LISTEN_COMPLETE)o=cd(n,e,t.path,s,r);else throw ze("Unknown operation type: "+t.type);const c=r.getChanges();return od(e,o,c),{viewCache:o,changes:c}}function od(n,e,t){const s=e.eventCache;if(s.isFullyInitialized()){const i=s.getNode().isLeafNode()||s.getNode().isEmpty(),r=$n(n);(t.length>0||!n.eventCache.isFullyInitialized()||i&&!s.getNode().equals(r)||!s.getNode().getPriority().equals(r.getPriority()))&&t.push(ao($n(e)))}}function yo(n,e,t,s,i,r){const o=e.eventCache;if(zt(s,t)!=null)return e;{let a,c;if(b(t))if(m(e.serverCache.isFullyInitialized(),"If change path is empty, we must have complete server data"),e.serverCache.isFiltered()){const l=ke(e),u=l instanceof E?l:E.EMPTY_NODE,h=gs(s,u);a=n.filter.updateFullNode(e.eventCache.getNode(),h,r)}else{const l=jt(s,ke(e));a=n.filter.updateFullNode(e.eventCache.getNode(),l,r)}else{const l=C(t);if(l===".priority"){m(ge(t)===1,"Can't have a priority with additional path components");const u=o.getNode();c=e.serverCache.getNode();const h=Ri(s,t,u,c);h!=null?a=n.filter.updatePriority(u,h):a=o.getNode()}else{const u=k(t);let h;if(o.isCompleteForChild(l)){c=e.serverCache.getNode();const d=Ri(s,t,o.getNode(),c);d!=null?h=o.getNode().getImmediateChild(l).updateChild(u,d):h=o.getNode().getImmediateChild(l)}else h=ys(s,l,e.serverCache);h!=null?a=n.filter.updateChild(o.getNode(),l,h,u,i,r):a=o.getNode()}}return nt(e,a,o.isFullyInitialized()||b(t),n.filter.filtersNodes())}}function Gt(n,e,t,s,i,r,o,a){const c=e.serverCache;let l;const u=o?n.filter:n.filter.getIndexedFilter();if(b(t))l=u.updateFullNode(c.getNode(),s,null);else if(u.filtersNodes()&&!c.isFiltered()){const _=c.getNode().updateChild(t,s);l=u.updateFullNode(c.getNode(),_,null)}else{const _=C(t);if(!c.isCompleteForPath(t)&&ge(t)>1)return e;const p=k(t),g=c.getNode().getImmediateChild(_).updateChild(p,s);_===".priority"?l=u.updatePriority(c.getNode(),g):l=u.updateChild(c.getNode(),_,g,p,go,null)}const h=uo(e,l,c.isFullyInitialized()||b(t),u.filtersNodes()),d=new Es(i,h,r);return yo(n,h,t,i,d,a)}function Gn(n,e,t,s,i,r,o){const a=e.eventCache;let c,l;const u=new Es(i,e,r);if(b(t))l=n.filter.updateFullNode(e.eventCache.getNode(),s,o),c=nt(e,l,!0,n.filter.filtersNodes());else{const h=C(t);if(h===".priority")l=n.filter.updatePriority(e.eventCache.getNode(),s),c=nt(e,l,a.isFullyInitialized(),a.isFiltered());else{const d=k(t),_=a.getNode().getImmediateChild(h);let p;if(b(d))p=s;else{const y=u.getCompleteChild(h);y!=null?Xr(d)===".priority"&&y.getChild(eo(d)).isEmpty()?p=y:p=y.updateChild(d,s):p=E.EMPTY_NODE}if(_.equals(p))c=e;else{const y=n.filter.updateChild(a.getNode(),h,p,d,u,o);c=nt(e,y,a.isFullyInitialized(),n.filter.filtersNodes())}}}return c}function Ni(n,e){return n.eventCache.isCompleteForChild(e)}function ad(n,e,t,s,i,r,o){let a=e;return s.foreach((c,l)=>{const u=L(t,c);Ni(e,C(u))&&(a=Gn(n,a,u,l,i,r,o))}),s.foreach((c,l)=>{const u=L(t,c);Ni(e,C(u))||(a=Gn(n,a,u,l,i,r,o))}),a}function Ai(n,e,t){return t.foreach((s,i)=>{e=e.updateChild(s,i)}),e}function Kn(n,e,t,s,i,r,o,a){if(e.serverCache.getNode().isEmpty()&&!e.serverCache.isFullyInitialized())return e;let c=e,l;b(t)?l=s:l=new x(null).setTree(t,s);const u=e.serverCache.getNode();return l.children.inorderTraversal((h,d)=>{if(u.hasChild(h)){const _=e.serverCache.getNode().getImmediateChild(h),p=Ai(n,_,d);c=Gt(n,c,new N(h),p,i,r,o,a)}}),l.children.inorderTraversal((h,d)=>{const _=!e.serverCache.isCompleteForChild(h)&&d.value===null;if(!u.hasChild(h)&&!_){const p=e.serverCache.getNode().getImmediateChild(h),y=Ai(n,p,d);c=Gt(n,c,new N(h),y,i,r,o,a)}}),c}function ld(n,e,t,s,i,r,o){if(zt(i,t)!=null)return e;const a=e.serverCache.isFiltered(),c=e.serverCache;if(s.value!=null){if(b(t)&&c.isFullyInitialized()||c.isCompleteForPath(t))return Gt(n,e,t,c.getNode().getChild(t),i,r,a,o);if(b(t)){let l=new x(null);return c.getNode().forEachChild(Ue,(u,h)=>{l=l.set(new N(u),h)}),Kn(n,e,t,l,i,r,a,o)}else return e}else{let l=new x(null);return s.foreach((u,h)=>{const d=L(t,u);c.isCompleteForPath(d)&&(l=l.set(u,c.getNode().getChild(d)))}),Kn(n,e,t,l,i,r,a,o)}}function cd(n,e,t,s,i){const r=e.serverCache,o=uo(e,r.getNode(),r.isFullyInitialized()||b(t),r.isFiltered());return yo(n,o,t,s,go,i)}function ud(n,e,t,s,i,r){let o;if(zt(s,t)!=null)return e;{const a=new Es(s,e,i),c=e.eventCache.getNode();let l;if(b(t)||C(t)===".priority"){let u;if(e.serverCache.isFullyInitialized())u=jt(s,ke(e));else{const h=e.serverCache.getNode();m(h instanceof E,"serverChildren would be complete if leaf node"),u=gs(s,h)}u=u,l=n.filter.updateFullNode(c,u,r)}else{const u=C(t);let h=ys(s,u,e.serverCache);h==null&&e.serverCache.isCompleteForChild(u)&&(h=c.getImmediateChild(u)),h!=null?l=n.filter.updateChild(c,u,h,k(t),a,r):e.eventCache.getNode().hasChild(u)?l=n.filter.updateChild(c,u,E.EMPTY_NODE,k(t),a,r):l=c,l.isEmpty()&&e.serverCache.isFullyInitialized()&&(o=jt(s,ke(e)),o.isLeafNode()&&(l=n.filter.updateFullNode(l,o,r)))}return o=e.serverCache.isFullyInitialized()||zt(s,S())!=null,nt(e,l,o,n.filter.filtersNodes())}}/**
1375
+ * @license
1376
+ * Copyright 2017 Google LLC
1377
+ *
1378
+ * Licensed under the Apache License, Version 2.0 (the "License");
1379
+ * you may not use this file except in compliance with the License.
1380
+ * You may obtain a copy of the License at
1381
+ *
1382
+ * http://www.apache.org/licenses/LICENSE-2.0
1383
+ *
1384
+ * Unless required by applicable law or agreed to in writing, software
1385
+ * distributed under the License is distributed on an "AS IS" BASIS,
1386
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1387
+ * See the License for the specific language governing permissions and
1388
+ * limitations under the License.
1389
+ */class hd{constructor(e,t){this.query_=e,this.eventRegistrations_=[];const s=this.query_._queryParams,i=new ds(s.getIndex()),r=kh(s);this.processor_=sd(r);const o=t.serverCache,a=t.eventCache,c=i.updateFullNode(E.EMPTY_NODE,o.getNode(),null),l=r.updateFullNode(E.EMPTY_NODE,a.getNode(),null),u=new Ae(c,o.isFullyInitialized(),i.filtersNodes()),h=new Ae(l,a.isFullyInitialized(),r.filtersNodes());this.viewCache_=ln(h,u),this.eventGenerator_=new Fh(this.query_)}get query(){return this.query_}}function dd(n){return n.viewCache_.serverCache.getNode()}function fd(n,e){const t=ke(n.viewCache_);return t&&(n.query._queryParams.loadsAllData()||!b(e)&&!t.getImmediateChild(C(e)).isEmpty())?t.getChild(e):null}function ki(n){return n.eventRegistrations_.length===0}function pd(n,e){n.eventRegistrations_.push(e)}function xi(n,e,t){const s=[];if(t){m(e==null,"A cancel should cancel all event registrations.");const i=n.query._path;n.eventRegistrations_.forEach(r=>{const o=r.createCancelEvent(t,i);o&&s.push(o)})}if(e){let i=[];for(let r=0;r<n.eventRegistrations_.length;++r){const o=n.eventRegistrations_[r];if(!o.matches(e))i.push(o);else if(e.hasAnyCallback()){i=i.concat(n.eventRegistrations_.slice(r+1));break}}n.eventRegistrations_=i}else n.eventRegistrations_=[];return s}function Oi(n,e,t,s){e.type===ne.MERGE&&e.source.queryId!==null&&(m(ke(n.viewCache_),"We should always have a full cache before handling merges"),m($n(n.viewCache_),"Missing event cache, even though we have a server cache"));const i=n.viewCache_,r=rd(n.processor_,i,e,t,s);return id(n.processor_,r.viewCache),m(r.viewCache.serverCache.isFullyInitialized()||!i.serverCache.isFullyInitialized(),"Once a server snap is complete, it should never go back"),n.viewCache_=r.viewCache,Eo(n,r.changes,r.viewCache.eventCache.getNode(),null)}function _d(n,e){const t=n.viewCache_.eventCache,s=[];return t.getNode().isLeafNode()||t.getNode().forEachChild(P,(r,o)=>{s.push(Ve(r,o))}),t.isFullyInitialized()&&s.push(ao(t.getNode())),Eo(n,s,t.getNode(),e)}function Eo(n,e,t,s){const i=s?[s]:n.eventRegistrations_;return Uh(n.eventGenerator_,e,t,i)}/**
1390
+ * @license
1391
+ * Copyright 2017 Google LLC
1392
+ *
1393
+ * Licensed under the Apache License, Version 2.0 (the "License");
1394
+ * you may not use this file except in compliance with the License.
1395
+ * You may obtain a copy of the License at
1396
+ *
1397
+ * http://www.apache.org/licenses/LICENSE-2.0
1398
+ *
1399
+ * Unless required by applicable law or agreed to in writing, software
1400
+ * distributed under the License is distributed on an "AS IS" BASIS,
1401
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1402
+ * See the License for the specific language governing permissions and
1403
+ * limitations under the License.
1404
+ */let Kt;class md{constructor(){this.views=new Map}}function gd(n){m(!Kt,"__referenceConstructor has already been defined"),Kt=n}function yd(){return m(Kt,"Reference.ts has not been loaded"),Kt}function Ed(n){return n.views.size===0}function ws(n,e,t,s){const i=e.source.queryId;if(i!==null){const r=n.views.get(i);return m(r!=null,"SyncTree gave us an op for an invalid query."),Oi(r,e,t,s)}else{let r=[];for(const o of n.views.values())r=r.concat(Oi(o,e,t,s));return r}}function wd(n,e,t,s,i){const r=e._queryIdentifier,o=n.views.get(r);if(!o){let a=jt(t,i?s:null),c=!1;a?c=!0:s instanceof E?(a=gs(t,s),c=!1):(a=E.EMPTY_NODE,c=!1);const l=ln(new Ae(a,c,!1),new Ae(s,i,!1));return new hd(e,l)}return o}function vd(n,e,t,s,i,r){const o=wd(n,e,s,i,r);return n.views.has(e._queryIdentifier)||n.views.set(e._queryIdentifier,o),pd(o,t),_d(o,t)}function Cd(n,e,t,s){const i=e._queryIdentifier,r=[];let o=[];const a=ye(n);if(i==="default")for(const[c,l]of n.views.entries())o=o.concat(xi(l,t,s)),ki(l)&&(n.views.delete(c),l.query._queryParams.loadsAllData()||r.push(l.query));else{const c=n.views.get(i);c&&(o=o.concat(xi(c,t,s)),ki(c)&&(n.views.delete(i),c.query._queryParams.loadsAllData()||r.push(c.query)))}return a&&!ye(n)&&r.push(new(yd())(e._repo,e._path)),{removed:r,events:o}}function wo(n){const e=[];for(const t of n.views.values())t.query._queryParams.loadsAllData()||e.push(t);return e}function Be(n,e){let t=null;for(const s of n.views.values())t=t||fd(s,e);return t}function vo(n,e){if(e._queryParams.loadsAllData())return cn(n);{const s=e._queryIdentifier;return n.views.get(s)}}function Co(n,e){return vo(n,e)!=null}function ye(n){return cn(n)!=null}function cn(n){for(const e of n.views.values())if(e.query._queryParams.loadsAllData())return e;return null}/**
1405
+ * @license
1406
+ * Copyright 2017 Google LLC
1407
+ *
1408
+ * Licensed under the Apache License, Version 2.0 (the "License");
1409
+ * you may not use this file except in compliance with the License.
1410
+ * You may obtain a copy of the License at
1411
+ *
1412
+ * http://www.apache.org/licenses/LICENSE-2.0
1413
+ *
1414
+ * Unless required by applicable law or agreed to in writing, software
1415
+ * distributed under the License is distributed on an "AS IS" BASIS,
1416
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1417
+ * See the License for the specific language governing permissions and
1418
+ * limitations under the License.
1419
+ */let Yt;function bd(n){m(!Yt,"__referenceConstructor has already been defined"),Yt=n}function Sd(){return m(Yt,"Reference.ts has not been loaded"),Yt}let Td=1;class Di{constructor(e){this.listenProvider_=e,this.syncPointTree_=new x(null),this.pendingWriteTree_=Zh(),this.tagToQueryMap=new Map,this.queryToTagMap=new Map}}function Id(n,e,t,s,i){return Vh(n.pendingWriteTree_,e,t,s,i),i?bt(n,new Ne(co(),e,t)):[]}function Me(n,e,t=!1){const s=qh(n.pendingWriteTree_,e);if($h(n.pendingWriteTree_,e)){let r=new x(null);return s.snap!=null?r=r.set(S(),!0):G(s.children,o=>{r=r.set(new N(o),!0)}),bt(n,new $t(s.path,r,t))}else return[]}function un(n,e,t){return bt(n,new Ne(ps(),e,t))}function Rd(n,e,t){const s=x.fromObject(t);return bt(n,new pt(ps(),e,s))}function Nd(n,e){return bt(n,new ft(ps(),e))}function Ad(n,e,t){const s=vs(n,t);if(s){const i=Cs(s),r=i.path,o=i.queryId,a=$(r,e),c=new ft(_s(o),a);return bs(n,r,c)}else return[]}function Yn(n,e,t,s,i=!1){const r=e._path,o=n.syncPointTree_.get(r);let a=[];if(o&&(e._queryIdentifier==="default"||Co(o,e))){const c=Cd(o,e,t,s);Ed(o)&&(n.syncPointTree_=n.syncPointTree_.remove(r));const l=c.removed;if(a=c.events,!i){const u=l.findIndex(d=>d._queryParams.loadsAllData())!==-1,h=n.syncPointTree_.findOnPath(r,(d,_)=>ye(_));if(u&&!h){const d=n.syncPointTree_.subtree(r);if(!d.isEmpty()){const _=Od(d);for(let p=0;p<_.length;++p){const y=_[p],g=y.query,I=Io(n,y);n.listenProvider_.startListening(it(g),Qt(n,g),I.hashFn,I.onComplete)}}}!h&&l.length>0&&!s&&(u?n.listenProvider_.stopListening(it(e),null):l.forEach(d=>{const _=n.queryToTagMap.get(hn(d));n.listenProvider_.stopListening(it(d),_)}))}Dd(n,l)}return a}function kd(n,e,t,s){const i=vs(n,s);if(i!=null){const r=Cs(i),o=r.path,a=r.queryId,c=$(o,e),l=new Ne(_s(a),c,t);return bs(n,o,l)}else return[]}function xd(n,e,t,s){const i=vs(n,s);if(i){const r=Cs(i),o=r.path,a=r.queryId,c=$(o,e),l=x.fromObject(t),u=new pt(_s(a),c,l);return bs(n,o,u)}else return[]}function Pi(n,e,t,s=!1){const i=e._path;let r=null,o=!1;n.syncPointTree_.foreachOnPath(i,(d,_)=>{const p=$(d,i);r=r||Be(_,p),o=o||ye(_)});let a=n.syncPointTree_.get(i);a?(o=o||ye(a),r=r||Be(a,S())):(a=new md,n.syncPointTree_=n.syncPointTree_.set(i,a));let c;r!=null?c=!0:(c=!1,r=E.EMPTY_NODE,n.syncPointTree_.subtree(i).foreachChild((_,p)=>{const y=Be(p,S());y&&(r=r.updateImmediateChild(_,y))}));const l=Co(a,e);if(!l&&!e._queryParams.loadsAllData()){const d=hn(e);m(!n.queryToTagMap.has(d),"View does not exist, but we have a tag");const _=Pd();n.queryToTagMap.set(d,_),n.tagToQueryMap.set(_,d)}const u=ms(n.pendingWriteTree_,i);let h=vd(a,e,t,u,r,c);if(!l&&!o&&!s){const d=vo(a,e);h=h.concat(Md(n,e,d))}return h}function bo(n,e,t){const i=n.pendingWriteTree_,r=n.syncPointTree_.findOnPath(e,(o,a)=>{const c=$(o,e),l=Be(a,c);if(l)return l});return po(i,e,r,t,!0)}function bt(n,e){return So(e,n.syncPointTree_,null,ms(n.pendingWriteTree_,S()))}function So(n,e,t,s){if(b(n.path))return To(n,e,t,s);{const i=e.get(S());t==null&&i!=null&&(t=Be(i,S()));let r=[];const o=C(n.path),a=n.operationForChild(o),c=e.children.get(o);if(c&&a){const l=t?t.getImmediateChild(o):null,u=_o(s,o);r=r.concat(So(a,c,l,u))}return i&&(r=r.concat(ws(i,n,s,t))),r}}function To(n,e,t,s){const i=e.get(S());t==null&&i!=null&&(t=Be(i,S()));let r=[];return e.children.inorderTraversal((o,a)=>{const c=t?t.getImmediateChild(o):null,l=_o(s,o),u=n.operationForChild(o);u&&(r=r.concat(To(u,a,c,l)))}),i&&(r=r.concat(ws(i,n,s,t))),r}function Io(n,e){const t=e.query,s=Qt(n,t);return{hashFn:()=>(dd(e)||E.EMPTY_NODE).hash(),onComplete:i=>{if(i==="ok")return s?Ad(n,t._path,s):Nd(n,t._path);{const r=Au(i,t);return Yn(n,t,null,r)}}}}function Qt(n,e){const t=hn(e);return n.queryToTagMap.get(t)}function hn(n){return n._path.toString()+"$"+n._queryIdentifier}function vs(n,e){return n.tagToQueryMap.get(e)}function Cs(n){const e=n.indexOf("$");return m(e!==-1&&e<n.length-1,"Bad queryKey."),{queryId:n.substr(e+1),path:new N(n.substr(0,e))}}function bs(n,e,t){const s=n.syncPointTree_.get(e);m(s,"Missing sync point for query tag that we're tracking");const i=ms(n.pendingWriteTree_,e);return ws(s,t,i,null)}function Od(n){return n.fold((e,t,s)=>{if(t&&ye(t))return[cn(t)];{let i=[];return t&&(i=wo(t)),G(s,(r,o)=>{i=i.concat(o)}),i}})}function it(n){return n._queryParams.loadsAllData()&&!n._queryParams.isDefault()?new(Sd())(n._repo,n._path):n}function Dd(n,e){for(let t=0;t<e.length;++t){const s=e[t];if(!s._queryParams.loadsAllData()){const i=hn(s),r=n.queryToTagMap.get(i);n.queryToTagMap.delete(i),n.tagToQueryMap.delete(r)}}}function Pd(){return Td++}function Md(n,e,t){const s=e._path,i=Qt(n,e),r=Io(n,t),o=n.listenProvider_.startListening(it(e),i,r.hashFn,r.onComplete),a=n.syncPointTree_.subtree(s);if(i)m(!ye(a.value),"If we're adding a query, it shouldn't be shadowed");else{const c=a.fold((l,u,h)=>{if(!b(l)&&u&&ye(u))return[cn(u).query];{let d=[];return u&&(d=d.concat(wo(u).map(_=>_.query))),G(h,(_,p)=>{d=d.concat(p)}),d}});for(let l=0;l<c.length;++l){const u=c[l];n.listenProvider_.stopListening(it(u),Qt(n,u))}}return o}/**
1420
+ * @license
1421
+ * Copyright 2017 Google LLC
1422
+ *
1423
+ * Licensed under the Apache License, Version 2.0 (the "License");
1424
+ * you may not use this file except in compliance with the License.
1425
+ * You may obtain a copy of the License at
1426
+ *
1427
+ * http://www.apache.org/licenses/LICENSE-2.0
1428
+ *
1429
+ * Unless required by applicable law or agreed to in writing, software
1430
+ * distributed under the License is distributed on an "AS IS" BASIS,
1431
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1432
+ * See the License for the specific language governing permissions and
1433
+ * limitations under the License.
1434
+ */class Ss{constructor(e){this.node_=e}getImmediateChild(e){const t=this.node_.getImmediateChild(e);return new Ss(t)}node(){return this.node_}}class Ts{constructor(e,t){this.syncTree_=e,this.path_=t}getImmediateChild(e){const t=L(this.path_,e);return new Ts(this.syncTree_,t)}node(){return bo(this.syncTree_,this.path_)}}const Ld=function(n){return n=n||{},n.timestamp=n.timestamp||new Date().getTime(),n},Mi=function(n,e,t){if(!n||typeof n!="object")return n;if(m(".sv"in n,"Unexpected leaf node or priority contents"),typeof n[".sv"]=="string")return Fd(n[".sv"],e,t);if(typeof n[".sv"]=="object")return Ud(n[".sv"],e);m(!1,"Unexpected server value: "+JSON.stringify(n,null,2))},Fd=function(n,e,t){switch(n){case"timestamp":return t.timestamp;default:m(!1,"Unexpected server value: "+n)}},Ud=function(n,e,t){n.hasOwnProperty("increment")||m(!1,"Unexpected server value: "+JSON.stringify(n,null,2));const s=n.increment;typeof s!="number"&&m(!1,"Unexpected increment value: "+s);const i=e.node();if(m(i!==null&&typeof i<"u","Expected ChildrenNode.EMPTY_NODE for nulls"),!i.isLeafNode())return s;const o=i.getValue();return typeof o!="number"?s:o+s},Bd=function(n,e,t,s){return Is(e,new Ts(t,n),s)},Wd=function(n,e,t){return Is(n,new Ss(e),t)};function Is(n,e,t){const s=n.getPriority().val(),i=Mi(s,e.getImmediateChild(".priority"),t);let r;if(n.isLeafNode()){const o=n,a=Mi(o.getValue(),e,t);return a!==o.getValue()||i!==o.getPriority().val()?new F(a,H(i)):n}else{const o=n;return r=o,i!==o.getPriority().val()&&(r=r.updatePriority(new F(i))),o.forEachChild(P,(a,c)=>{const l=Is(c,e.getImmediateChild(a),t);l!==c&&(r=r.updateImmediateChild(a,l))}),r}}/**
1435
+ * @license
1436
+ * Copyright 2017 Google LLC
1437
+ *
1438
+ * Licensed under the Apache License, Version 2.0 (the "License");
1439
+ * you may not use this file except in compliance with the License.
1440
+ * You may obtain a copy of the License at
1441
+ *
1442
+ * http://www.apache.org/licenses/LICENSE-2.0
1443
+ *
1444
+ * Unless required by applicable law or agreed to in writing, software
1445
+ * distributed under the License is distributed on an "AS IS" BASIS,
1446
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1447
+ * See the License for the specific language governing permissions and
1448
+ * limitations under the License.
1449
+ */class Rs{constructor(e="",t=null,s={children:{},childCount:0}){this.name=e,this.parent=t,this.node=s}}function Ns(n,e){let t=e instanceof N?e:new N(e),s=n,i=C(t);for(;i!==null;){const r=We(s.node.children,i)||{children:{},childCount:0};s=new Rs(i,s,r),t=k(t),i=C(t)}return s}function Ke(n){return n.node.value}function Ro(n,e){n.node.value=e,Qn(n)}function No(n){return n.node.childCount>0}function Hd(n){return Ke(n)===void 0&&!No(n)}function dn(n,e){G(n.node.children,(t,s)=>{e(new Rs(t,n,s))})}function Ao(n,e,t,s){t&&e(n),dn(n,i=>{Ao(i,e,!0)})}function Vd(n,e,t){let s=n.parent;for(;s!==null;){if(e(s))return!0;s=s.parent}return!1}function St(n){return new N(n.parent===null?n.name:St(n.parent)+"/"+n.name)}function Qn(n){n.parent!==null&&qd(n.parent,n.name,n)}function qd(n,e,t){const s=Hd(t),i=he(n.node.children,e);s&&i?(delete n.node.children[e],n.node.childCount--,Qn(n)):!s&&!i&&(n.node.children[e]=t.node,n.node.childCount++,Qn(n))}/**
1450
+ * @license
1451
+ * Copyright 2017 Google LLC
1452
+ *
1453
+ * Licensed under the Apache License, Version 2.0 (the "License");
1454
+ * you may not use this file except in compliance with the License.
1455
+ * You may obtain a copy of the License at
1456
+ *
1457
+ * http://www.apache.org/licenses/LICENSE-2.0
1458
+ *
1459
+ * Unless required by applicable law or agreed to in writing, software
1460
+ * distributed under the License is distributed on an "AS IS" BASIS,
1461
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1462
+ * See the License for the specific language governing permissions and
1463
+ * limitations under the License.
1464
+ */const $d=/[\[\].#$\/\u0000-\u001F\u007F]/,jd=/[\[\].#$\u0000-\u001F\u007F]/,In=10*1024*1024,ko=function(n){return typeof n=="string"&&n.length!==0&&!$d.test(n)},xo=function(n){return typeof n=="string"&&n.length!==0&&!jd.test(n)},zd=function(n){return n&&(n=n.replace(/^\/*\.info(\/|$)/,"/")),xo(n)},Oo=function(n,e,t){const s=t instanceof N?new lh(t,n):t;if(e===void 0)throw new Error(n+"contains undefined "+ve(s));if(typeof e=="function")throw new Error(n+"contains a function "+ve(s)+" with contents = "+e.toString());if(xr(e))throw new Error(n+"contains "+e.toString()+" "+ve(s));if(typeof e=="string"&&e.length>In/3&&rn(e)>In)throw new Error(n+"contains a string greater than "+In+" utf8 bytes "+ve(s)+" ('"+e.substring(0,50)+"...')");if(e&&typeof e=="object"){let i=!1,r=!1;if(G(e,(o,a)=>{if(o===".value")i=!0;else if(o!==".priority"&&o!==".sv"&&(r=!0,!ko(o)))throw new Error(n+" contains an invalid key ("+o+") "+ve(s)+`. Keys must be non-empty strings and can't contain ".", "#", "$", "/", "[", or "]"`);ch(s,o),Oo(n,a,s),uh(s)}),i&&r)throw new Error(n+' contains ".value" child '+ve(s)+" in addition to actual children.")}},Do=function(n,e,t,s){if(!xo(t))throw new Error(vr(n,e)+'was an invalid path = "'+t+`". Paths must be non-empty strings and can't contain ".", "#", "$", "[", or "]"`)},Gd=function(n,e,t,s){t&&(t=t.replace(/^\/*\.info(\/|$)/,"/")),Do(n,e,t)},Kd=function(n,e){const t=e.path.toString();if(typeof e.repoInfo.host!="string"||e.repoInfo.host.length===0||!ko(e.repoInfo.namespace)&&e.repoInfo.host.split(":")[0]!=="localhost"||t.length!==0&&!zd(t))throw new Error(vr(n,"url")+`must be a valid firebase URL and the path can't contain ".", "#", "$", "[", or "]".`)};/**
1465
+ * @license
1466
+ * Copyright 2017 Google LLC
1467
+ *
1468
+ * Licensed under the Apache License, Version 2.0 (the "License");
1469
+ * you may not use this file except in compliance with the License.
1470
+ * You may obtain a copy of the License at
1471
+ *
1472
+ * http://www.apache.org/licenses/LICENSE-2.0
1473
+ *
1474
+ * Unless required by applicable law or agreed to in writing, software
1475
+ * distributed under the License is distributed on an "AS IS" BASIS,
1476
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1477
+ * See the License for the specific language governing permissions and
1478
+ * limitations under the License.
1479
+ */class Yd{constructor(){this.eventLists_=[],this.recursionDepth_=0}}function Po(n,e){let t=null;for(let s=0;s<e.length;s++){const i=e[s],r=i.getPath();t!==null&&!cs(r,t.path)&&(n.eventLists_.push(t),t=null),t===null&&(t={events:[],path:r}),t.events.push(i)}t&&n.eventLists_.push(t)}function Mo(n,e,t){Po(n,t),Lo(n,s=>cs(s,e))}function Oe(n,e,t){Po(n,t),Lo(n,s=>te(s,e)||te(e,s))}function Lo(n,e){n.recursionDepth_++;let t=!0;for(let s=0;s<n.eventLists_.length;s++){const i=n.eventLists_[s];if(i){const r=i.path;e(r)?(Qd(n.eventLists_[s]),n.eventLists_[s]=null):t=!1}}t&&(n.eventLists_=[]),n.recursionDepth_--}function Qd(n){for(let e=0;e<n.events.length;e++){const t=n.events[e];if(t!==null){n.events[e]=null;const s=t.getEventRunner();et&&W("event: "+t.toString()),vt(s)}}}/**
1480
+ * @license
1481
+ * Copyright 2017 Google LLC
1482
+ *
1483
+ * Licensed under the Apache License, Version 2.0 (the "License");
1484
+ * you may not use this file except in compliance with the License.
1485
+ * You may obtain a copy of the License at
1486
+ *
1487
+ * http://www.apache.org/licenses/LICENSE-2.0
1488
+ *
1489
+ * Unless required by applicable law or agreed to in writing, software
1490
+ * distributed under the License is distributed on an "AS IS" BASIS,
1491
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1492
+ * See the License for the specific language governing permissions and
1493
+ * limitations under the License.
1494
+ */const Jd="repo_interrupt",Xd=25;class Zd{constructor(e,t,s,i){this.repoInfo_=e,this.forceRestClient_=t,this.authTokenProvider_=s,this.appCheckProvider_=i,this.dataUpdateCount=0,this.statsListener_=null,this.eventQueue_=new Yd,this.nextWriteId_=1,this.interceptServerDataCallback_=null,this.onDisconnect_=qt(),this.transactionQueueTree_=new Rs,this.persistentConnection_=null,this.key=this.repoInfo_.toURLString()}toString(){return(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host}}function ef(n,e,t){if(n.stats_=as(n.repoInfo_),n.forceRestClient_||Du())n.server_=new Vt(n.repoInfo_,(s,i,r,o)=>{Li(n,s,i,r,o)},n.authTokenProvider_,n.appCheckProvider_),setTimeout(()=>Fi(n,!0),0);else{if(typeof t<"u"&&t!==null){if(typeof t!="object")throw new Error("Only objects are supported for option databaseAuthVariableOverride");try{B(t)}catch(s){throw new Error("Invalid authOverride provided: "+s)}}n.persistentConnection_=new le(n.repoInfo_,e,(s,i,r,o)=>{Li(n,s,i,r,o)},s=>{Fi(n,s)},s=>{nf(n,s)},n.authTokenProvider_,n.appCheckProvider_,t),n.server_=n.persistentConnection_}n.authTokenProvider_.addTokenChangeListener(s=>{n.server_.refreshAuthToken(s)}),n.appCheckProvider_.addTokenChangeListener(s=>{n.server_.refreshAppCheckToken(s.token)}),n.statsReporter_=Uu(n.repoInfo_,()=>new Lh(n.stats_,n.server_)),n.infoData_=new xh,n.infoSyncTree_=new Di({startListening:(s,i,r,o)=>{let a=[];const c=n.infoData_.getNode(s._path);return c.isEmpty()||(a=un(n.infoSyncTree_,s._path,c),setTimeout(()=>{o("ok")},0)),a},stopListening:()=>{}}),As(n,"connected",!1),n.serverSyncTree_=new Di({startListening:(s,i,r,o)=>(n.server_.listen(s,r,i,(a,c)=>{const l=o(a,c);Oe(n.eventQueue_,s._path,l)}),[]),stopListening:(s,i)=>{n.server_.unlisten(s,i)}})}function tf(n){const t=n.infoData_.getNode(new N(".info/serverTimeOffset")).val()||0;return new Date().getTime()+t}function Fo(n){return Ld({timestamp:tf(n)})}function Li(n,e,t,s,i){n.dataUpdateCount++;const r=new N(e);t=n.interceptServerDataCallback_?n.interceptServerDataCallback_(e,t):t;let o=[];if(i)if(s){const c=Mt(t,l=>H(l));o=xd(n.serverSyncTree_,r,c,i)}else{const c=H(t);o=kd(n.serverSyncTree_,r,c,i)}else if(s){const c=Mt(t,l=>H(l));o=Rd(n.serverSyncTree_,r,c)}else{const c=H(t);o=un(n.serverSyncTree_,r,c)}let a=r;o.length>0&&(a=xs(n,r)),Oe(n.eventQueue_,a,o)}function Fi(n,e){As(n,"connected",e),e===!1&&rf(n)}function nf(n,e){G(e,(t,s)=>{As(n,t,s)})}function As(n,e,t){const s=new N("/.info/"+e),i=H(t);n.infoData_.updateSnapshot(s,i);const r=un(n.infoSyncTree_,s,i);Oe(n.eventQueue_,s,r)}function sf(n){return n.nextWriteId_++}function rf(n){Uo(n,"onDisconnectEvents");const e=Fo(n),t=qt();qn(n.onDisconnect_,S(),(i,r)=>{const o=Bd(i,r,n.serverSyncTree_,e);lo(t,i,o)});let s=[];qn(t,S(),(i,r)=>{s=s.concat(un(n.serverSyncTree_,i,r));const o=hf(n,i);xs(n,o)}),n.onDisconnect_=qt(),Oe(n.eventQueue_,S(),s)}function of(n,e,t){let s;C(e._path)===".info"?s=Pi(n.infoSyncTree_,e,t):s=Pi(n.serverSyncTree_,e,t),Mo(n.eventQueue_,e._path,s)}function af(n,e,t){let s;C(e._path)===".info"?s=Yn(n.infoSyncTree_,e,t):s=Yn(n.serverSyncTree_,e,t),Mo(n.eventQueue_,e._path,s)}function lf(n){n.persistentConnection_&&n.persistentConnection_.interrupt(Jd)}function Uo(n,...e){let t="";n.persistentConnection_&&(t=n.persistentConnection_.id+":"),W(t,...e)}function Bo(n,e,t){return bo(n.serverSyncTree_,e,t)||E.EMPTY_NODE}function ks(n,e=n.transactionQueueTree_){if(e||fn(n,e),Ke(e)){const t=Ho(n,e);m(t.length>0,"Sending zero length transaction queue"),t.every(i=>i.status===0)&&cf(n,St(e),t)}else No(e)&&dn(e,t=>{ks(n,t)})}function cf(n,e,t){const s=t.map(l=>l.currentWriteId),i=Bo(n,e,s);let r=i;const o=i.hash();for(let l=0;l<t.length;l++){const u=t[l];m(u.status===0,"tryToSendTransactionQueue_: items in queue should all be run."),u.status=1,u.retryCount++;const h=$(e,u.path);r=r.updateChild(h,u.currentOutputSnapshotRaw)}const a=r.val(!0),c=e;n.server_.put(c.toString(),a,l=>{Uo(n,"transaction put response",{path:c.toString(),status:l});let u=[];if(l==="ok"){const h=[];for(let d=0;d<t.length;d++)t[d].status=2,u=u.concat(Me(n.serverSyncTree_,t[d].currentWriteId)),t[d].onComplete&&h.push(()=>t[d].onComplete(null,!0,t[d].currentOutputSnapshotResolved)),t[d].unwatcher();fn(n,Ns(n.transactionQueueTree_,e)),ks(n,n.transactionQueueTree_),Oe(n.eventQueue_,e,u);for(let d=0;d<h.length;d++)vt(h[d])}else{if(l==="datastale")for(let h=0;h<t.length;h++)t[h].status===3?t[h].status=4:t[h].status=0;else{Y("transaction at "+c.toString()+" failed: "+l);for(let h=0;h<t.length;h++)t[h].status=4,t[h].abortReason=l}xs(n,e)}},o)}function xs(n,e){const t=Wo(n,e),s=St(t),i=Ho(n,t);return uf(n,i,s),s}function uf(n,e,t){if(e.length===0)return;const s=[];let i=[];const o=e.filter(a=>a.status===0).map(a=>a.currentWriteId);for(let a=0;a<e.length;a++){const c=e[a],l=$(t,c.path);let u=!1,h;if(m(l!==null,"rerunTransactionsUnderNode_: relativePath should not be null."),c.status===4)u=!0,h=c.abortReason,i=i.concat(Me(n.serverSyncTree_,c.currentWriteId,!0));else if(c.status===0)if(c.retryCount>=Xd)u=!0,h="maxretry",i=i.concat(Me(n.serverSyncTree_,c.currentWriteId,!0));else{const d=Bo(n,c.path,o);c.currentInputSnapshot=d;const _=e[a].update(d.val());if(_!==void 0){Oo("transaction failed: Data returned ",_,c.path);let p=H(_);typeof _=="object"&&_!=null&&he(_,".priority")||(p=p.updatePriority(d.getPriority()));const g=c.currentWriteId,I=Fo(n),O=Wd(p,d,I);c.currentOutputSnapshotRaw=p,c.currentOutputSnapshotResolved=O,c.currentWriteId=sf(n),o.splice(o.indexOf(g),1),i=i.concat(Id(n.serverSyncTree_,c.path,O,c.currentWriteId,c.applyLocally)),i=i.concat(Me(n.serverSyncTree_,g,!0))}else u=!0,h="nodata",i=i.concat(Me(n.serverSyncTree_,c.currentWriteId,!0))}Oe(n.eventQueue_,t,i),i=[],u&&(e[a].status=2,function(d){setTimeout(d,Math.floor(0))}(e[a].unwatcher),e[a].onComplete&&(h==="nodata"?s.push(()=>e[a].onComplete(null,!1,e[a].currentInputSnapshot)):s.push(()=>e[a].onComplete(new Error(h),!1,null))))}fn(n,n.transactionQueueTree_);for(let a=0;a<s.length;a++)vt(s[a]);ks(n,n.transactionQueueTree_)}function Wo(n,e){let t,s=n.transactionQueueTree_;for(t=C(e);t!==null&&Ke(s)===void 0;)s=Ns(s,t),e=k(e),t=C(e);return s}function Ho(n,e){const t=[];return Vo(n,e,t),t.sort((s,i)=>s.order-i.order),t}function Vo(n,e,t){const s=Ke(e);if(s)for(let i=0;i<s.length;i++)t.push(s[i]);dn(e,i=>{Vo(n,i,t)})}function fn(n,e){const t=Ke(e);if(t){let s=0;for(let i=0;i<t.length;i++)t[i].status!==2&&(t[s]=t[i],s++);t.length=s,Ro(e,t.length>0?t:void 0)}dn(e,s=>{fn(n,s)})}function hf(n,e){const t=St(Wo(n,e)),s=Ns(n.transactionQueueTree_,e);return Vd(s,i=>{Rn(n,i)}),Rn(n,s),Ao(s,i=>{Rn(n,i)}),t}function Rn(n,e){const t=Ke(e);if(t){const s=[];let i=[],r=-1;for(let o=0;o<t.length;o++)t[o].status===3||(t[o].status===1?(m(r===o-1,"All SENT items should be at beginning of queue."),r=o,t[o].status=3,t[o].abortReason="set"):(m(t[o].status===0,"Unexpected transaction status in abort"),t[o].unwatcher(),i=i.concat(Me(n.serverSyncTree_,t[o].currentWriteId,!0)),t[o].onComplete&&s.push(t[o].onComplete.bind(null,new Error("set"),!1,null))));r===-1?Ro(e,void 0):t.length=r+1,Oe(n.eventQueue_,St(e),i);for(let o=0;o<s.length;o++)vt(s[o])}}/**
1495
+ * @license
1496
+ * Copyright 2017 Google LLC
1497
+ *
1498
+ * Licensed under the Apache License, Version 2.0 (the "License");
1499
+ * you may not use this file except in compliance with the License.
1500
+ * You may obtain a copy of the License at
1501
+ *
1502
+ * http://www.apache.org/licenses/LICENSE-2.0
1503
+ *
1504
+ * Unless required by applicable law or agreed to in writing, software
1505
+ * distributed under the License is distributed on an "AS IS" BASIS,
1506
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1507
+ * See the License for the specific language governing permissions and
1508
+ * limitations under the License.
1509
+ */function df(n){let e="";const t=n.split("/");for(let s=0;s<t.length;s++)if(t[s].length>0){let i=t[s];try{i=decodeURIComponent(i.replace(/\+/g," "))}catch{}e+="/"+i}return e}function ff(n){const e={};n.charAt(0)==="?"&&(n=n.substring(1));for(const t of n.split("&")){if(t.length===0)continue;const s=t.split("=");s.length===2?e[decodeURIComponent(s[0])]=decodeURIComponent(s[1]):Y(`Invalid query segment '${t}' in query '${n}'`)}return e}const Ui=function(n,e){const t=pf(n),s=t.namespace;t.domain==="firebase.com"&&ue(t.host+" is no longer supported. Please use <YOUR FIREBASE>.firebaseio.com instead"),(!s||s==="undefined")&&t.domain!=="localhost"&&ue("Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com"),t.secure||Su();const i=t.scheme==="ws"||t.scheme==="wss";return{repoInfo:new qr(t.host,t.secure,s,i,e,"",s!==t.subdomain),path:new N(t.pathString)}},pf=function(n){let e="",t="",s="",i="",r="",o=!0,a="https",c=443;if(typeof n=="string"){let l=n.indexOf("//");l>=0&&(a=n.substring(0,l-1),n=n.substring(l+2));let u=n.indexOf("/");u===-1&&(u=n.length);let h=n.indexOf("?");h===-1&&(h=n.length),e=n.substring(0,Math.min(u,h)),u<h&&(i=df(n.substring(u,h)));const d=ff(n.substring(Math.min(n.length,h)));l=e.indexOf(":"),l>=0?(o=a==="https"||a==="wss",c=parseInt(e.substring(l+1),10)):l=e.length;const _=e.slice(0,l);if(_.toLowerCase()==="localhost")t="localhost";else if(_.split(".").length<=2)t=_;else{const p=e.indexOf(".");s=e.substring(0,p).toLowerCase(),t=e.substring(p+1),r=s}"ns"in d&&(r=d.ns)}return{host:e,port:c,domain:t,subdomain:s,secure:o,scheme:a,pathString:i,namespace:r}};/**
1510
+ * @license
1511
+ * Copyright 2017 Google LLC
1512
+ *
1513
+ * Licensed under the Apache License, Version 2.0 (the "License");
1514
+ * you may not use this file except in compliance with the License.
1515
+ * You may obtain a copy of the License at
1516
+ *
1517
+ * http://www.apache.org/licenses/LICENSE-2.0
1518
+ *
1519
+ * Unless required by applicable law or agreed to in writing, software
1520
+ * distributed under the License is distributed on an "AS IS" BASIS,
1521
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1522
+ * See the License for the specific language governing permissions and
1523
+ * limitations under the License.
1524
+ */class qo{constructor(e,t,s,i){this.eventType=e,this.eventRegistration=t,this.snapshot=s,this.prevName=i}getPath(){const e=this.snapshot.ref;return this.eventType==="value"?e._path:e.parent._path}getEventType(){return this.eventType}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.getPath().toString()+":"+this.eventType+":"+B(this.snapshot.exportVal())}}class $o{constructor(e,t,s){this.eventRegistration=e,this.error=t,this.path=s}getPath(){return this.path}getEventType(){return"cancel"}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.path.toString()+":cancel"}}/**
1525
+ * @license
1526
+ * Copyright 2017 Google LLC
1527
+ *
1528
+ * Licensed under the Apache License, Version 2.0 (the "License");
1529
+ * you may not use this file except in compliance with the License.
1530
+ * You may obtain a copy of the License at
1531
+ *
1532
+ * http://www.apache.org/licenses/LICENSE-2.0
1533
+ *
1534
+ * Unless required by applicable law or agreed to in writing, software
1535
+ * distributed under the License is distributed on an "AS IS" BASIS,
1536
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1537
+ * See the License for the specific language governing permissions and
1538
+ * limitations under the License.
1539
+ */class _f{constructor(e,t){this.snapshotCallback=e,this.cancelCallback=t}onValue(e,t){this.snapshotCallback.call(null,e,t)}onCancel(e){return m(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||this.snapshotCallback.userCallback!==void 0&&this.snapshotCallback.userCallback===e.snapshotCallback.userCallback&&this.snapshotCallback.context===e.snapshotCallback.context}}/**
1540
+ * @license
1541
+ * Copyright 2020 Google LLC
1542
+ *
1543
+ * Licensed under the Apache License, Version 2.0 (the "License");
1544
+ * you may not use this file except in compliance with the License.
1545
+ * You may obtain a copy of the License at
1546
+ *
1547
+ * http://www.apache.org/licenses/LICENSE-2.0
1548
+ *
1549
+ * Unless required by applicable law or agreed to in writing, software
1550
+ * distributed under the License is distributed on an "AS IS" BASIS,
1551
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1552
+ * See the License for the specific language governing permissions and
1553
+ * limitations under the License.
1554
+ */class Os{constructor(e,t,s,i){this._repo=e,this._path=t,this._queryParams=s,this._orderByCalled=i}get key(){return b(this._path)?null:Xr(this._path)}get ref(){return new de(this._repo,this._path)}get _queryIdentifier(){const e=Ci(this._queryParams),t=rs(e);return t==="{}"?"default":t}get _queryObject(){return Ci(this._queryParams)}isEqual(e){if(e=on(e),!(e instanceof Os))return!1;const t=this._repo===e._repo,s=cs(this._path,e._path),i=this._queryIdentifier===e._queryIdentifier;return t&&s&&i}toJSON(){return this.toString()}toString(){return this._repo.toString()+ah(this._path)}}class de extends Os{constructor(e,t){super(e,t,new fs,!1)}get parent(){const e=eo(this._path);return e===null?null:new de(this._repo,e)}get root(){let e=this;for(;e.parent!==null;)e=e.parent;return e}}class _t{constructor(e,t,s){this._node=e,this.ref=t,this._index=s}get priority(){return this._node.getPriority().val()}get key(){return this.ref.key}get size(){return this._node.numChildren()}child(e){const t=new N(e),s=Jt(this.ref,e);return new _t(this._node.getChild(t),s,P)}exists(){return!this._node.isEmpty()}exportVal(){return this._node.val(!0)}forEach(e){return this._node.isLeafNode()?!1:!!this._node.forEachChild(this._index,(s,i)=>e(new _t(i,Jt(this.ref,s),P)))}hasChild(e){const t=new N(e);return!this._node.getChild(t).isEmpty()}hasChildren(){return this._node.isLeafNode()?!1:!this._node.isEmpty()}toJSON(){return this.exportVal()}val(){return this._node.val()}}function Bi(n,e){return n=on(n),n._checkNotDeleted("ref"),e!==void 0?Jt(n._root,e):n._root}function Jt(n,e){return n=on(n),C(n._path)===null?Gd("child","path",e):Do("child","path",e),new de(n._repo,L(n._path,e))}class Ds{constructor(e){this.callbackContext=e}respondsTo(e){return e==="value"}createEvent(e,t){const s=t._queryParams.getIndex();return new qo("value",this,new _t(e.snapshotNode,new de(t._repo,t._path),s))}getEventRunner(e){return e.getEventType()==="cancel"?()=>this.callbackContext.onCancel(e.error):()=>this.callbackContext.onValue(e.snapshot,null)}createCancelEvent(e,t){return this.callbackContext.hasCancelCallback?new $o(this,e,t):null}matches(e){return e instanceof Ds?!e.callbackContext||!this.callbackContext?!0:e.callbackContext.matches(this.callbackContext):!1}hasAnyCallback(){return this.callbackContext!==null}}class Ps{constructor(e,t){this.eventType=e,this.callbackContext=t}respondsTo(e){let t=e==="children_added"?"child_added":e;return t=t==="children_removed"?"child_removed":t,this.eventType===t}createCancelEvent(e,t){return this.callbackContext.hasCancelCallback?new $o(this,e,t):null}createEvent(e,t){m(e.childName!=null,"Child events should have a childName.");const s=Jt(new de(t._repo,t._path),e.childName),i=t._queryParams.getIndex();return new qo(e.type,this,new _t(e.snapshotNode,s,i),e.prevName)}getEventRunner(e){return e.getEventType()==="cancel"?()=>this.callbackContext.onCancel(e.error):()=>this.callbackContext.onValue(e.snapshot,e.prevName)}matches(e){return e instanceof Ps?this.eventType===e.eventType&&(!this.callbackContext||!e.callbackContext||this.callbackContext.matches(e.callbackContext)):!1}hasAnyCallback(){return!!this.callbackContext}}function jo(n,e,t,s,i){const r=new _f(t,void 0),o=e==="value"?new Ds(r):new Ps(e,r);return of(n._repo,n,o),()=>af(n._repo,n,o)}function mf(n,e,t,s){return jo(n,"value",e)}function gf(n,e,t,s){return jo(n,"child_added",e)}gd(de);bd(de);/**
1555
+ * @license
1556
+ * Copyright 2020 Google LLC
1557
+ *
1558
+ * Licensed under the Apache License, Version 2.0 (the "License");
1559
+ * you may not use this file except in compliance with the License.
1560
+ * You may obtain a copy of the License at
1561
+ *
1562
+ * http://www.apache.org/licenses/LICENSE-2.0
1563
+ *
1564
+ * Unless required by applicable law or agreed to in writing, software
1565
+ * distributed under the License is distributed on an "AS IS" BASIS,
1566
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1567
+ * See the License for the specific language governing permissions and
1568
+ * limitations under the License.
1569
+ */const yf="FIREBASE_DATABASE_EMULATOR_HOST",Jn={};let Ef=!1;function wf(n,e,t,s){n.repoInfo_=new qr(e,!1,n.repoInfo_.namespace,n.repoInfo_.webSocketOnly,n.repoInfo_.nodeAdmin,n.repoInfo_.persistenceKey,n.repoInfo_.includeNamespaceInQueryParams,!0,t),s&&(n.authTokenProvider_=s)}function vf(n,e,t,s,i){let r=s||n.options.databaseURL;r===void 0&&(n.options.projectId||ue("Can't determine Firebase Database URL. Be sure to include a Project ID when calling firebase.initializeApp()."),W("Using default host for project ",n.options.projectId),r=`${n.options.projectId}-default-rtdb.firebaseio.com`);let o=Ui(r,i),a=o.repoInfo,c;typeof process<"u"&&process.env&&(c=process.env[yf]),c?(r=`http://${c}?ns=${a.namespace}`,o=Ui(r,i),a=o.repoInfo):o.repoInfo.secure;const l=new Mu(n.name,n.options,e);Kd("Invalid Firebase Database URL",o),b(o.path)||ue("Database URL must point to the root of a Firebase Database (not including a child path).");const u=bf(a,n,l,new Pu(n,t));return new Sf(u,n)}function Cf(n,e){const t=Jn[e];(!t||t[n.key]!==n)&&ue(`Database ${e}(${n.repoInfo_}) has already been deleted.`),lf(n),delete t[n.key]}function bf(n,e,t,s){let i=Jn[e.name];i||(i={},Jn[e.name]=i);let r=i[n.toURLString()];return r&&ue("Database initialized multiple times. Please make sure the format of the database URL matches with each database() call."),r=new Zd(n,Ef,t,s),i[n.toURLString()]=r,r}class Sf{constructor(e,t){this._repoInternal=e,this.app=t,this.type="database",this._instanceStarted=!1}get _repo(){return this._instanceStarted||(ef(this._repoInternal,this.app.options.appId,this.app.options.databaseAuthVariableOverride),this._instanceStarted=!0),this._repoInternal}get _root(){return this._rootInternal||(this._rootInternal=new de(this._repo,S())),this._rootInternal}_delete(){return this._rootInternal!==null&&(Cf(this._repo,this.app.name),this._repoInternal=null,this._rootInternal=null),Promise.resolve()}_checkNotDeleted(e){this._rootInternal===null&&ue("Cannot call "+e+" on a deleted database.")}}function Wi(n=au(),e){const t=nu(n,"database").getImmediate({identifier:e});if(!t._instanceStarted){const s=jl("database");s&&Tf(t,...s)}return t}function Tf(n,e,t,s={}){n=on(n),n._checkNotDeleted("useEmulator");const i=`${e}:${t}`,r=n._repoInternal;if(n._instanceStarted){if(i===n._repoInternal.repoInfo_.host&&Lt(s,r.repoInfo_.emulatorOptions))return;ue("connectDatabaseEmulator() cannot initialize or alter the emulator configuration after the database instance has started.")}let o;if(r.repoInfo_.nodeAdmin)s.mockUserToken&&ue('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".'),o=new xt(xt.OWNER);else if(s.mockUserToken){const a=typeof s.mockUserToken=="string"?s.mockUserToken:zl(s.mockUserToken,n.app.options.projectId);o=new xt(a)}wf(r,i,s,o)}/**
1570
+ * @license
1571
+ * Copyright 2021 Google LLC
1572
+ *
1573
+ * Licensed under the Apache License, Version 2.0 (the "License");
1574
+ * you may not use this file except in compliance with the License.
1575
+ * You may obtain a copy of the License at
1576
+ *
1577
+ * http://www.apache.org/licenses/LICENSE-2.0
1578
+ *
1579
+ * Unless required by applicable law or agreed to in writing, software
1580
+ * distributed under the License is distributed on an "AS IS" BASIS,
1581
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1582
+ * See the License for the specific language governing permissions and
1583
+ * limitations under the License.
1584
+ */function If(n){yu(ou),Ut(new at("database",(e,{instanceIdentifier:t})=>{const s=e.getProvider("app").getImmediate(),i=e.getProvider("auth-internal"),r=e.getProvider("app-check-internal");return vf(s,i,r,t)},"PUBLIC").setMultipleInstances(!0)),Le(ri,oi,n),Le(ri,oi,"esm2017")}le.prototype.simpleListen=function(n,e){this.sendRequest("q",{p:n},e)};le.prototype.echo=function(n,e){this.sendRequest("echo",{d:n},e)};If();var Rf="firebase",Nf="11.6.1";/**
1585
+ * @license
1586
+ * Copyright 2020 Google LLC
1587
+ *
1588
+ * Licensed under the Apache License, Version 2.0 (the "License");
1589
+ * you may not use this file except in compliance with the License.
1590
+ * You may obtain a copy of the License at
1591
+ *
1592
+ * http://www.apache.org/licenses/LICENSE-2.0
1593
+ *
1594
+ * Unless required by applicable law or agreed to in writing, software
1595
+ * distributed under the License is distributed on an "AS IS" BASIS,
1596
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1597
+ * See the License for the specific language governing permissions and
1598
+ * limitations under the License.
1599
+ */Le(Rf,Nf,"app");const Ce=class Ce{constructor(){Q(this,"initialized",!1);Q(this,"accessToken");Q(this,"backendRepository");Q(this,"onWindowResults");Q(this,"onFinalResults");Q(this,"firebaseHandlers",[]);Tr({apiKey:"AIzaSyAoOpQqLrc6wQLJI5KRE2Vt7QV1cplsZv8",authDomain:"nervowebreact.firebaseapp.com",databaseURL:"https://nervowebreact-default-rtdb.asia-southeast1.firebasedatabase.app",projectId:"nervowebreact",storageBucket:"nervowebreact.firebasestorage.app",messagingSenderId:"1025695568936",appId:"1:1025695568936:web:36f269a1eb74e1fdda511d",measurementId:"G-L3105FG92S"})}static getInstance(){return Ce.instance||(Ce.instance=new Ce),Ce.instance}initialize(e,t,s="server"){this.initialized=!0,s==="server"?this.backendRepository=new Dl(e,t):s==="serverless"?this.backendRepository=new Pl(e,t):R.throwKnownError(M.InvalidServerTypeError)}async uploadVideo(e){var i,r,o;this.initialized||R.throwKnownError(M.NotInitializedError),e instanceof Blob||R.throwKnownError(M.VideoTypeError),(e===null||e.size===0)&&R.throwKnownError(M.EmptyVideoError);const t=await((i=this.backendRepository)==null?void 0:i.getToken()),s=await((r=this.backendRepository)==null?void 0:r.getAPIKey(t));return(o=this.backendRepository)==null||o.uploadVideoToServer(e,t,s),s&&this.addfirebaseListeners(s),s}async checkResults(e){var t,s;console.warn("Warning: checkResults() is deprecated and will be removed in a future version. Use setOnWindowResults() and setOnFinalResults() instead!"),this.initialized||R.throwKnownError(M.NotInitializedError);try{return this.accessToken||(this.accessToken=await((t=this.backendRepository)==null?void 0:t.getToken())),await((s=this.backendRepository)==null?void 0:s.checkResults(e,this.accessToken))}catch(i){R.handleErrorResponse(i)}}async getResults(e){var s,i;return console.warn("Warning: getResults() is deprecated and will be removed in a future version. Use setOnWindowResults() and setOnFinalResults() instead!"),this.initialized||R.throwKnownError(M.NotInitializedError),this.accessToken||(this.accessToken=await((s=this.backendRepository)==null?void 0:s.getToken())),await((i=this.backendRepository)==null?void 0:i.getResults(e,this.accessToken))}setOnWindowResults(e){this.onWindowResults=e}setOnFinalResults(e){this.onFinalResults=e}async addfirebaseListeners(e){this.addWindowListener(e),this.addFinalListener(e)}async addWindowListener(e){const t=Wi(),s=Bi(t,`${e}`),i=gf(s,r=>{r.val()!==null&&r.key&&/^\d+$/.test(r.key)&&this.onWindowResults&&this.onWindowResults(r.val())});this.firebaseHandlers.push(i)}async removefirebaseListener(){this.firebaseHandlers.forEach(e=>{e()}),this.firebaseHandlers=[]}async addFinalListener(e){const t=Wi(),s=Bi(t,`/${e}/averaged_results/`),i=mf(s,r=>{r.val()!==null&&(this.onFinalResults&&this.onFinalResults(r.val()),this.removefirebaseListener())});this.firebaseHandlers.push(i)}};Q(Ce,"instance");let Xn=Ce;exports.Client=Xn;exports.Errors=Z;exports.NervoscanError=ie;