qiscus-sdk-core 2.16.2 → 2.16.3

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,4 +1,4 @@
1
- (function(Le,Me){typeof exports=="object"&&typeof module!="undefined"?module.exports=Me():typeof define=="function"&&define.amd?define("QiscusSDKCore",Me):(Le=typeof globalThis!="undefined"?globalThis:Le||self,Le.QiscusSDKCore=Me())})(this,(function(){"use strict";var uv=Object.defineProperty,fv=Object.defineProperties;var lv=Object.getOwnPropertyDescriptors;var Vp=Object.getOwnPropertySymbols;var cv=Object.prototype.hasOwnProperty,hv=Object.prototype.propertyIsEnumerable;var Za=(Le,Me)=>(Me=Symbol[Le])?Me:Symbol.for("Symbol."+Le);var Oe=Math.pow,eu=(Le,Me,xe)=>Me in Le?uv(Le,Me,{enumerable:!0,configurable:!0,writable:!0,value:xe}):Le[Me]=xe,br=(Le,Me)=>{for(var xe in Me||(Me={}))cv.call(Me,xe)&&eu(Le,xe,Me[xe]);if(Vp)for(var xe of Vp(Me))hv.call(Me,xe)&&eu(Le,xe,Me[xe]);return Le},wr=(Le,Me)=>fv(Le,lv(Me));var He=(Le,Me,xe)=>eu(Le,typeof Me!="symbol"?Me+"":Me,xe);var ke=(Le,Me,xe)=>new Promise((rt,ut)=>{var et=Xe=>{try{tt(xe.next(Xe))}catch(nt){ut(nt)}},it=Xe=>{try{tt(xe.throw(Xe))}catch(nt){ut(nt)}},tt=Xe=>Xe.done?rt(Xe.value):Promise.resolve(Xe.value).then(et,it);tt((xe=xe.apply(Le,Me)).next())}),Sr=function(Le,Me){this[0]=Le,this[1]=Me},tu=(Le,Me,xe)=>{var rt=(it,tt,Xe,nt)=>{try{var Lt=xe[it](tt),Ft=(tt=Lt.value)instanceof Sr,Ut=Lt.done;Promise.resolve(Ft?tt[0]:tt).then(ft=>Ft?rt(it==="return"?it:"next",tt[1]?{done:ft.done,value:ft.value}:ft,Xe,nt):Xe({value:ft,done:Ut})).catch(ft=>rt("throw",ft,Xe,nt))}catch(ft){nt(ft)}},ut=it=>et[it]=tt=>new Promise((Xe,nt)=>rt(it,tt,Xe,nt)),et={};return xe=xe.apply(Le,Me),et[Za("asyncIterator")]=()=>et,ut("next"),ut("throw"),ut("return"),et};var ru=(Le,Me,xe)=>(Me=Le[Za("asyncIterator")])?Me.call(Le):(Le=Le[Za("iterator")](),Me={},xe=(rt,ut)=>(ut=Le[rt])&&(Me[rt]=et=>new Promise((it,tt,Xe)=>(et=ut.call(Le,et),Xe=et.done,Promise.resolve(et.value).then(nt=>it({value:nt,done:Xe}),tt)))),xe("next"),xe("return"),Me);let Le="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",Me=(i=21)=>{let e="",t=crypto.getRandomValues(new Uint8Array(i|=0));for(;i--;)e+=Le[t[i]&63];return e};var xe=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function rt(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}function ut(i){if(Object.prototype.hasOwnProperty.call(i,"__esModule"))return i;var e=i.default;if(typeof e=="function"){var t=function r(){return this instanceof r?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};t.prototype=e.prototype}else t={};return Object.defineProperty(t,"__esModule",{value:!0}),Object.keys(i).forEach(function(r){var n=Object.getOwnPropertyDescriptor(i,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:function(){return i[r]}})}),t}var et={exports:{}},it={exports:{}},tt;function Xe(){return tt||(tt=1,(function(i){i.exports=e;function e(r){if(r)return t(r)}function t(r){for(var n in e.prototype)r[n]=e.prototype[n];return r}e.prototype.on=e.prototype.addEventListener=function(r,n){return this._callbacks=this._callbacks||{},(this._callbacks["$"+r]=this._callbacks["$"+r]||[]).push(n),this},e.prototype.once=function(r,n){function o(){this.off(r,o),n.apply(this,arguments)}return o.fn=n,this.on(r,o),this},e.prototype.off=e.prototype.removeListener=e.prototype.removeAllListeners=e.prototype.removeEventListener=function(r,n){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var o=this._callbacks["$"+r];if(!o)return this;if(arguments.length==1)return delete this._callbacks["$"+r],this;for(var u,a=0;a<o.length;a++)if(u=o[a],u===n||u.fn===n){o.splice(a,1);break}return o.length===0&&delete this._callbacks["$"+r],this},e.prototype.emit=function(r){this._callbacks=this._callbacks||{};for(var n=new Array(arguments.length-1),o=this._callbacks["$"+r],u=1;u<arguments.length;u++)n[u-1]=arguments[u];if(o){o=o.slice(0);for(var u=0,a=o.length;u<a;++u)o[u].apply(this,n)}return this},e.prototype.listeners=function(r){return this._callbacks=this._callbacks||{},this._callbacks["$"+r]||[]},e.prototype.hasListeners=function(r){return!!this.listeners(r).length}})(it)),it.exports}var nt,Lt;function Ft(){if(Lt)return nt;Lt=1;function i(e){return e!==null&&typeof e=="object"}return nt=i,nt}var Ut,ft;function Kp(){if(ft)return Ut;ft=1;var i=Ft();Ut=e;function e(n){if(n)return t(n)}function t(n){for(var o in e.prototype)n[o]=e.prototype[o];return n}e.prototype.clearTimeout=function(){return clearTimeout(this._timer),clearTimeout(this._responseTimeoutTimer),delete this._timer,delete this._responseTimeoutTimer,this},e.prototype.parse=function(o){return this._parser=o,this},e.prototype.responseType=function(n){return this._responseType=n,this},e.prototype.serialize=function(o){return this._serializer=o,this},e.prototype.timeout=function(o){if(!o||typeof o!="object")return this._timeout=o,this._responseTimeout=0,this;for(var u in o)switch(u){case"deadline":this._timeout=o.deadline;break;case"response":this._responseTimeout=o.response;break;default:console.warn("Unknown timeout option",u)}return this},e.prototype.retry=function(o,u){return(arguments.length===0||o===!0)&&(o=1),o<=0&&(o=0),this._maxRetries=o,this._retries=0,this._retryCallback=u,this};var r=["ECONNRESET","ETIMEDOUT","EADDRINFO","ESOCKETTIMEDOUT"];return e.prototype._shouldRetry=function(n,o){if(!this._maxRetries||this._retries++>=this._maxRetries)return!1;if(this._retryCallback)try{var u=this._retryCallback(n,o);if(u===!0)return!0;if(u===!1)return!1}catch(a){console.error(a)}return!!(o&&o.status&&o.status>=500&&o.status!=501||n&&(n.code&&~r.indexOf(n.code)||n.timeout&&n.code=="ECONNABORTED"||n.crossDomain))},e.prototype._retry=function(){return this.clearTimeout(),this.req&&(this.req=null,this.req=this.request()),this._aborted=!1,this.timedout=!1,this._end()},e.prototype.then=function(o,u){if(!this._fullfilledPromise){var a=this;this._endCalled&&console.warn("Warning: superagent request was sent twice, because both .end() and .then() were called. Never call .end() if you use promises"),this._fullfilledPromise=new Promise(function(s,l){a.end(function(d,_){d?l(d):s(_)})})}return this._fullfilledPromise.then(o,u)},e.prototype.catch=function(n){return this.then(void 0,n)},e.prototype.use=function(o){return o(this),this},e.prototype.ok=function(n){if(typeof n!="function")throw Error("Callback required");return this._okCallback=n,this},e.prototype._isResponseOK=function(n){return n?this._okCallback?this._okCallback(n):n.status>=200&&n.status<300:!1},e.prototype.get=function(n){return this._header[n.toLowerCase()]},e.prototype.getHeader=e.prototype.get,e.prototype.set=function(n,o){if(i(n)){for(var u in n)this.set(u,n[u]);return this}return this._header[n.toLowerCase()]=o,this.header[n]=o,this},e.prototype.unset=function(n){return delete this._header[n.toLowerCase()],delete this.header[n],this},e.prototype.field=function(n,o){if(n==null)throw new Error(".field(name, val) name can not be empty");if(this._data&&console.error(".field() can't be used if .send() is used. Please use only .send() or only .field() & .attach()"),i(n)){for(var u in n)this.field(u,n[u]);return this}if(Array.isArray(o)){for(var a in o)this.field(n,o[a]);return this}if(o==null)throw new Error(".field(name, val) val can not be empty");return typeof o=="boolean"&&(o=""+o),this._getFormData().append(n,o),this},e.prototype.abort=function(){return this._aborted?this:(this._aborted=!0,this.xhr&&this.xhr.abort(),this.req&&this.req.abort(),this.clearTimeout(),this.emit("abort"),this)},e.prototype._auth=function(n,o,u,a){switch(u.type){case"basic":this.set("Authorization","Basic "+a(n+":"+o));break;case"auto":this.username=n,this.password=o;break;case"bearer":this.set("Authorization","Bearer "+n);break}return this},e.prototype.withCredentials=function(n){return n==null&&(n=!0),this._withCredentials=n,this},e.prototype.redirects=function(n){return this._maxRedirects=n,this},e.prototype.maxResponseSize=function(n){if(typeof n!="number")throw TypeError("Invalid argument");return this._maxResponseSize=n,this},e.prototype.toJSON=function(){return{method:this.method,url:this.url,data:this._data,headers:this._header}},e.prototype.send=function(n){var o=i(n),u=this._header["content-type"];if(this._formData&&console.error(".send() can't be used if .attach() or .field() is used. Please use only .send() or only .field() & .attach()"),o&&!this._data)Array.isArray(n)?this._data=[]:this._isHost(n)||(this._data={});else if(n&&this._data&&this._isHost(this._data))throw Error("Can't merge these send calls");if(o&&i(this._data))for(var a in n)this._data[a]=n[a];else typeof n=="string"?(u||this.type("form"),u=this._header["content-type"],u=="application/x-www-form-urlencoded"?this._data=this._data?this._data+"&"+n:n:this._data=(this._data||"")+n):this._data=n;return!o||this._isHost(n)?this:(u||this.type("json"),this)},e.prototype.sortQuery=function(n){return this._sort=typeof n=="undefined"?!0:n,this},e.prototype._finalizeQueryString=function(){var n=this._query.join("&");if(n&&(this.url+=(this.url.indexOf("?")>=0?"&":"?")+n),this._query.length=0,this._sort){var o=this.url.indexOf("?");if(o>=0){var u=this.url.substring(o+1).split("&");typeof this._sort=="function"?u.sort(this._sort):u.sort(),this.url=this.url.substring(0,o)+"?"+u.join("&")}}},e.prototype._appendQueryString=function(){console.trace("Unsupported")},e.prototype._timeoutError=function(n,o,u){if(!this._aborted){var a=new Error(n+o+"ms exceeded");a.timeout=o,a.code="ECONNABORTED",a.errno=u,this.timedout=!0,this.abort(),this.callback(a)}},e.prototype._setTimeouts=function(){var n=this;this._timeout&&!this._timer&&(this._timer=setTimeout(function(){n._timeoutError("Timeout of ",n._timeout,"ETIME")},this._timeout)),this._responseTimeout&&!this._responseTimeoutTimer&&(this._responseTimeoutTimer=setTimeout(function(){n._timeoutError("Response timeout of ",n._responseTimeout,"ETIMEDOUT")},this._responseTimeout))},Ut}var At={},nu;function Qp(){return nu||(nu=1,At.type=function(i){return i.split(/ *; */).shift()},At.params=function(i){return i.split(/ *; */).reduce(function(e,t){var r=t.split(/ *= */),n=r.shift(),o=r.shift();return n&&o&&(e[n]=o),e},{})},At.parseLinks=function(i){return i.split(/ *, */).reduce(function(e,t){var r=t.split(/ *; */),n=r[0].slice(1,-1),o=r[1].split(/ *= */)[1].slice(1,-1);return e[o]=n,e},{})},At.cleanHeader=function(i,e){return delete i["content-type"],delete i["content-length"],delete i["transfer-encoding"],delete i.host,e&&(delete i.authorization,delete i.cookie),i}),At}var Er,iu;function Jp(){if(iu)return Er;iu=1;var i=Qp();Er=e;function e(r){if(r)return t(r)}function t(r){for(var n in e.prototype)r[n]=e.prototype[n];return r}return e.prototype.get=function(r){return this.header[r.toLowerCase()]},e.prototype._setHeaderProperties=function(r){var n=r["content-type"]||"";this.type=i.type(n);var o=i.params(n);for(var u in o)this[u]=o[u];this.links={};try{r.link&&(this.links=i.parseLinks(r.link))}catch(a){}},e.prototype._setStatusProperties=function(r){var n=r/100|0;this.status=this.statusCode=r,this.statusType=n,this.info=n==1,this.ok=n==2,this.redirect=n==3,this.clientError=n==4,this.serverError=n==5,this.error=n==4||n==5?this.toError():!1,this.created=r==201,this.accepted=r==202,this.noContent=r==204,this.badRequest=r==400,this.unauthorized=r==401,this.notAcceptable=r==406,this.forbidden=r==403,this.notFound=r==404,this.unprocessableEntity=r==422},Er}var Ir,ou;function Xp(){if(ou)return Ir;ou=1;function i(){this._defaults=[]}return["use","on","once","set","query","type","accept","auth","withCredentials","sortQuery","retry","ok","redirects","timeout","buffer","serialize","parse","ca","key","pfx","cert"].forEach(function(e){i.prototype[e]=function(){return this._defaults.push({fn:e,arguments}),this}}),i.prototype._setDefaults=function(e){this._defaults.forEach(function(t){e[t.fn].apply(e,t.arguments)})},Ir=i,Ir}var Zp=et.exports,su;function em(){return su||(su=1,(function(i,e){var t;typeof window!="undefined"?t=window:typeof self!="undefined"?t=self:(console.warn("Using browser-only version of superagent in non-browser environment"),t=Zp);var r=Xe(),n=Kp(),o=Ft(),u=Jp(),a=Xp();function s(){}var l=e=i.exports=function(S,b){return typeof b=="function"?new e.Request("GET",S).end(b):arguments.length==1?new e.Request("GET",S):new e.Request(S,b)};e.Request=A,l.getXHR=function(){if(t.XMLHttpRequest&&(!t.location||t.location.protocol!="file:"||!t.ActiveXObject))return new XMLHttpRequest;try{return new ActiveXObject("Microsoft.XMLHTTP")}catch(S){}try{return new ActiveXObject("Msxml2.XMLHTTP.6.0")}catch(S){}try{return new ActiveXObject("Msxml2.XMLHTTP.3.0")}catch(S){}try{return new ActiveXObject("Msxml2.XMLHTTP")}catch(S){}throw Error("Browser-only version of superagent could not find XHR")};var d="".trim?function(S){return S.trim()}:function(S){return S.replace(/(^\s*|\s*$)/g,"")};function _(S){if(!o(S))return S;var b=[];for(var h in S)g(b,h,S[h]);return b.join("&")}function g(S,b,h){if(h!=null)if(Array.isArray(h))h.forEach(function(v){g(S,b,v)});else if(o(h))for(var p in h)g(S,b+"["+p+"]",h[p]);else S.push(encodeURIComponent(b)+"="+encodeURIComponent(h));else h===null&&S.push(encodeURIComponent(b))}l.serializeObject=_;function E(S){for(var b={},h=S.split("&"),p,v,I=0,B=h.length;I<B;++I)p=h[I],v=p.indexOf("="),v==-1?b[decodeURIComponent(p)]="":b[decodeURIComponent(p.slice(0,v))]=decodeURIComponent(p.slice(v+1));return b}l.parseString=E,l.types={html:"text/html",json:"application/json",xml:"text/xml",urlencoded:"application/x-www-form-urlencoded",form:"application/x-www-form-urlencoded","form-data":"application/x-www-form-urlencoded"},l.serialize={"application/x-www-form-urlencoded":_,"application/json":JSON.stringify},l.parse={"application/x-www-form-urlencoded":E,"application/json":JSON.parse};function w(S){for(var b=S.split(/\r?\n/),h={},p,v,I,B,H=0,V=b.length;H<V;++H)v=b[H],p=v.indexOf(":"),p!==-1&&(I=v.slice(0,p).toLowerCase(),B=d(v.slice(p+1)),h[I]=B);return h}function q(S){return/[\/+]json($|[^-\w])/.test(S)}function k(S){this.req=S,this.xhr=this.req.xhr,this.text=this.req.method!="HEAD"&&(this.xhr.responseType===""||this.xhr.responseType==="text")||typeof this.xhr.responseType=="undefined"?this.xhr.responseText:null,this.statusText=this.req.xhr.statusText;var b=this.xhr.status;b===1223&&(b=204),this._setStatusProperties(b),this.header=this.headers=w(this.xhr.getAllResponseHeaders()),this.header["content-type"]=this.xhr.getResponseHeader("content-type"),this._setHeaderProperties(this.header),this.text===null&&S._responseType?this.body=this.xhr.response:this.body=this.req.method!="HEAD"?this._parseBody(this.text?this.text:this.xhr.response):null}u(k.prototype),k.prototype._parseBody=function(S){var b=l.parse[this.type];return this.req._parser?this.req._parser(this,S):(!b&&q(this.type)&&(b=l.parse["application/json"]),b&&S&&(S.length||S instanceof Object)?b(S):null)},k.prototype.toError=function(){var S=this.req,b=S.method,h=S.url,p="cannot "+b+" "+h+" ("+this.status+")",v=new Error(p);return v.status=this.status,v.method=b,v.url=h,v},l.Response=k;function A(S,b){var h=this;this._query=this._query||[],this.method=S,this.url=b,this.header={},this._header={},this.on("end",function(){var p=null,v=null;try{v=new k(h)}catch(B){return p=new Error("Parser is unable to parse the response"),p.parse=!0,p.original=B,h.xhr?(p.rawResponse=typeof h.xhr.responseType=="undefined"?h.xhr.responseText:h.xhr.response,p.status=h.xhr.status?h.xhr.status:null,p.statusCode=p.status):(p.rawResponse=null,p.status=null),h.callback(p)}h.emit("response",v);var I;try{h._isResponseOK(v)||(I=new Error(v.statusText||"Unsuccessful HTTP response"))}catch(B){I=B}I?(I.original=p,I.response=v,I.status=v.status,h.callback(I,v)):h.callback(null,v)})}r(A.prototype),n(A.prototype),A.prototype.type=function(S){return this.set("Content-Type",l.types[S]||S),this},A.prototype.accept=function(S){return this.set("Accept",l.types[S]||S),this},A.prototype.auth=function(S,b,h){arguments.length===1&&(b=""),typeof b=="object"&&b!==null&&(h=b,b=""),h||(h={type:typeof btoa=="function"?"basic":"auto"});var p=function(v){if(typeof btoa=="function")return btoa(v);throw new Error("Cannot use basic auth, btoa is not a function")};return this._auth(S,b,h,p)},A.prototype.query=function(S){return typeof S!="string"&&(S=_(S)),S&&this._query.push(S),this},A.prototype.attach=function(S,b,h){if(b){if(this._data)throw Error("superagent can't mix .send() and .attach()");this._getFormData().append(S,b,h||b.name)}return this},A.prototype._getFormData=function(){return this._formData||(this._formData=new t.FormData),this._formData},A.prototype.callback=function(S,b){if(this._shouldRetry(S,b))return this._retry();var h=this._callback;this.clearTimeout(),S&&(this._maxRetries&&(S.retries=this._retries-1),this.emit("error",S)),h(S,b)},A.prototype.crossDomainError=function(){var S=new Error(`Request has been terminated
1
+ (function(Le,Me){typeof exports=="object"&&typeof module!="undefined"?module.exports=Me():typeof define=="function"&&define.amd?define("QiscusSDKCore",Me):(Le=typeof globalThis!="undefined"?globalThis:Le||self,Le.QiscusSDKCore=Me())})(this,(function(){"use strict";var uv=Object.defineProperty,fv=Object.defineProperties;var lv=Object.getOwnPropertyDescriptors;var Vp=Object.getOwnPropertySymbols;var cv=Object.prototype.hasOwnProperty,hv=Object.prototype.propertyIsEnumerable;var Za=(Le,Me)=>(Me=Symbol[Le])?Me:Symbol.for("Symbol."+Le);var Oe=Math.pow,eu=(Le,Me,xe)=>Me in Le?uv(Le,Me,{enumerable:!0,configurable:!0,writable:!0,value:xe}):Le[Me]=xe,br=(Le,Me)=>{for(var xe in Me||(Me={}))cv.call(Me,xe)&&eu(Le,xe,Me[xe]);if(Vp)for(var xe of Vp(Me))hv.call(Me,xe)&&eu(Le,xe,Me[xe]);return Le},wr=(Le,Me)=>fv(Le,lv(Me));var He=(Le,Me,xe)=>eu(Le,typeof Me!="symbol"?Me+"":Me,xe);var ke=(Le,Me,xe)=>new Promise((rt,ut)=>{var et=Xe=>{try{tt(xe.next(Xe))}catch(nt){ut(nt)}},it=Xe=>{try{tt(xe.throw(Xe))}catch(nt){ut(nt)}},tt=Xe=>Xe.done?rt(Xe.value):Promise.resolve(Xe.value).then(et,it);tt((xe=xe.apply(Le,Me)).next())}),Sr=function(Le,Me){this[0]=Le,this[1]=Me},tu=(Le,Me,xe)=>{var rt=(it,tt,Xe,nt)=>{try{var Lt=xe[it](tt),Ft=(tt=Lt.value)instanceof Sr,Ut=Lt.done;Promise.resolve(Ft?tt[0]:tt).then(ft=>Ft?rt(it==="return"?it:"next",tt[1]?{done:ft.done,value:ft.value}:ft,Xe,nt):Xe({value:ft,done:Ut})).catch(ft=>rt("throw",ft,Xe,nt))}catch(ft){nt(ft)}},ut=it=>et[it]=tt=>new Promise((Xe,nt)=>rt(it,tt,Xe,nt)),et={};return xe=xe.apply(Le,Me),et[Za("asyncIterator")]=()=>et,ut("next"),ut("throw"),ut("return"),et};var ru=(Le,Me,xe)=>(Me=Le[Za("asyncIterator")])?Me.call(Le):(Le=Le[Za("iterator")](),Me={},xe=(rt,ut)=>(ut=Le[rt])&&(Me[rt]=et=>new Promise((it,tt,Xe)=>(et=ut.call(Le,et),Xe=et.done,Promise.resolve(et.value).then(nt=>it({value:nt,done:Xe}),tt)))),xe("next"),xe("return"),Me);let Le="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",Me=(i=21)=>{let e="",t=i|0;for(;t-- >0;)e+=Le[Math.random()*64|0];return e};var xe=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function rt(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}function ut(i){if(Object.prototype.hasOwnProperty.call(i,"__esModule"))return i;var e=i.default;if(typeof e=="function"){var t=function r(){return this instanceof r?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};t.prototype=e.prototype}else t={};return Object.defineProperty(t,"__esModule",{value:!0}),Object.keys(i).forEach(function(r){var n=Object.getOwnPropertyDescriptor(i,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:function(){return i[r]}})}),t}var et={exports:{}},it={exports:{}},tt;function Xe(){return tt||(tt=1,(function(i){i.exports=e;function e(r){if(r)return t(r)}function t(r){for(var n in e.prototype)r[n]=e.prototype[n];return r}e.prototype.on=e.prototype.addEventListener=function(r,n){return this._callbacks=this._callbacks||{},(this._callbacks["$"+r]=this._callbacks["$"+r]||[]).push(n),this},e.prototype.once=function(r,n){function o(){this.off(r,o),n.apply(this,arguments)}return o.fn=n,this.on(r,o),this},e.prototype.off=e.prototype.removeListener=e.prototype.removeAllListeners=e.prototype.removeEventListener=function(r,n){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var o=this._callbacks["$"+r];if(!o)return this;if(arguments.length==1)return delete this._callbacks["$"+r],this;for(var u,a=0;a<o.length;a++)if(u=o[a],u===n||u.fn===n){o.splice(a,1);break}return o.length===0&&delete this._callbacks["$"+r],this},e.prototype.emit=function(r){this._callbacks=this._callbacks||{};for(var n=new Array(arguments.length-1),o=this._callbacks["$"+r],u=1;u<arguments.length;u++)n[u-1]=arguments[u];if(o){o=o.slice(0);for(var u=0,a=o.length;u<a;++u)o[u].apply(this,n)}return this},e.prototype.listeners=function(r){return this._callbacks=this._callbacks||{},this._callbacks["$"+r]||[]},e.prototype.hasListeners=function(r){return!!this.listeners(r).length}})(it)),it.exports}var nt,Lt;function Ft(){if(Lt)return nt;Lt=1;function i(e){return e!==null&&typeof e=="object"}return nt=i,nt}var Ut,ft;function Kp(){if(ft)return Ut;ft=1;var i=Ft();Ut=e;function e(n){if(n)return t(n)}function t(n){for(var o in e.prototype)n[o]=e.prototype[o];return n}e.prototype.clearTimeout=function(){return clearTimeout(this._timer),clearTimeout(this._responseTimeoutTimer),delete this._timer,delete this._responseTimeoutTimer,this},e.prototype.parse=function(o){return this._parser=o,this},e.prototype.responseType=function(n){return this._responseType=n,this},e.prototype.serialize=function(o){return this._serializer=o,this},e.prototype.timeout=function(o){if(!o||typeof o!="object")return this._timeout=o,this._responseTimeout=0,this;for(var u in o)switch(u){case"deadline":this._timeout=o.deadline;break;case"response":this._responseTimeout=o.response;break;default:console.warn("Unknown timeout option",u)}return this},e.prototype.retry=function(o,u){return(arguments.length===0||o===!0)&&(o=1),o<=0&&(o=0),this._maxRetries=o,this._retries=0,this._retryCallback=u,this};var r=["ECONNRESET","ETIMEDOUT","EADDRINFO","ESOCKETTIMEDOUT"];return e.prototype._shouldRetry=function(n,o){if(!this._maxRetries||this._retries++>=this._maxRetries)return!1;if(this._retryCallback)try{var u=this._retryCallback(n,o);if(u===!0)return!0;if(u===!1)return!1}catch(a){console.error(a)}return!!(o&&o.status&&o.status>=500&&o.status!=501||n&&(n.code&&~r.indexOf(n.code)||n.timeout&&n.code=="ECONNABORTED"||n.crossDomain))},e.prototype._retry=function(){return this.clearTimeout(),this.req&&(this.req=null,this.req=this.request()),this._aborted=!1,this.timedout=!1,this._end()},e.prototype.then=function(o,u){if(!this._fullfilledPromise){var a=this;this._endCalled&&console.warn("Warning: superagent request was sent twice, because both .end() and .then() were called. Never call .end() if you use promises"),this._fullfilledPromise=new Promise(function(s,l){a.end(function(d,_){d?l(d):s(_)})})}return this._fullfilledPromise.then(o,u)},e.prototype.catch=function(n){return this.then(void 0,n)},e.prototype.use=function(o){return o(this),this},e.prototype.ok=function(n){if(typeof n!="function")throw Error("Callback required");return this._okCallback=n,this},e.prototype._isResponseOK=function(n){return n?this._okCallback?this._okCallback(n):n.status>=200&&n.status<300:!1},e.prototype.get=function(n){return this._header[n.toLowerCase()]},e.prototype.getHeader=e.prototype.get,e.prototype.set=function(n,o){if(i(n)){for(var u in n)this.set(u,n[u]);return this}return this._header[n.toLowerCase()]=o,this.header[n]=o,this},e.prototype.unset=function(n){return delete this._header[n.toLowerCase()],delete this.header[n],this},e.prototype.field=function(n,o){if(n==null)throw new Error(".field(name, val) name can not be empty");if(this._data&&console.error(".field() can't be used if .send() is used. Please use only .send() or only .field() & .attach()"),i(n)){for(var u in n)this.field(u,n[u]);return this}if(Array.isArray(o)){for(var a in o)this.field(n,o[a]);return this}if(o==null)throw new Error(".field(name, val) val can not be empty");return typeof o=="boolean"&&(o=""+o),this._getFormData().append(n,o),this},e.prototype.abort=function(){return this._aborted?this:(this._aborted=!0,this.xhr&&this.xhr.abort(),this.req&&this.req.abort(),this.clearTimeout(),this.emit("abort"),this)},e.prototype._auth=function(n,o,u,a){switch(u.type){case"basic":this.set("Authorization","Basic "+a(n+":"+o));break;case"auto":this.username=n,this.password=o;break;case"bearer":this.set("Authorization","Bearer "+n);break}return this},e.prototype.withCredentials=function(n){return n==null&&(n=!0),this._withCredentials=n,this},e.prototype.redirects=function(n){return this._maxRedirects=n,this},e.prototype.maxResponseSize=function(n){if(typeof n!="number")throw TypeError("Invalid argument");return this._maxResponseSize=n,this},e.prototype.toJSON=function(){return{method:this.method,url:this.url,data:this._data,headers:this._header}},e.prototype.send=function(n){var o=i(n),u=this._header["content-type"];if(this._formData&&console.error(".send() can't be used if .attach() or .field() is used. Please use only .send() or only .field() & .attach()"),o&&!this._data)Array.isArray(n)?this._data=[]:this._isHost(n)||(this._data={});else if(n&&this._data&&this._isHost(this._data))throw Error("Can't merge these send calls");if(o&&i(this._data))for(var a in n)this._data[a]=n[a];else typeof n=="string"?(u||this.type("form"),u=this._header["content-type"],u=="application/x-www-form-urlencoded"?this._data=this._data?this._data+"&"+n:n:this._data=(this._data||"")+n):this._data=n;return!o||this._isHost(n)?this:(u||this.type("json"),this)},e.prototype.sortQuery=function(n){return this._sort=typeof n=="undefined"?!0:n,this},e.prototype._finalizeQueryString=function(){var n=this._query.join("&");if(n&&(this.url+=(this.url.indexOf("?")>=0?"&":"?")+n),this._query.length=0,this._sort){var o=this.url.indexOf("?");if(o>=0){var u=this.url.substring(o+1).split("&");typeof this._sort=="function"?u.sort(this._sort):u.sort(),this.url=this.url.substring(0,o)+"?"+u.join("&")}}},e.prototype._appendQueryString=function(){console.trace("Unsupported")},e.prototype._timeoutError=function(n,o,u){if(!this._aborted){var a=new Error(n+o+"ms exceeded");a.timeout=o,a.code="ECONNABORTED",a.errno=u,this.timedout=!0,this.abort(),this.callback(a)}},e.prototype._setTimeouts=function(){var n=this;this._timeout&&!this._timer&&(this._timer=setTimeout(function(){n._timeoutError("Timeout of ",n._timeout,"ETIME")},this._timeout)),this._responseTimeout&&!this._responseTimeoutTimer&&(this._responseTimeoutTimer=setTimeout(function(){n._timeoutError("Response timeout of ",n._responseTimeout,"ETIMEDOUT")},this._responseTimeout))},Ut}var At={},nu;function Qp(){return nu||(nu=1,At.type=function(i){return i.split(/ *; */).shift()},At.params=function(i){return i.split(/ *; */).reduce(function(e,t){var r=t.split(/ *= */),n=r.shift(),o=r.shift();return n&&o&&(e[n]=o),e},{})},At.parseLinks=function(i){return i.split(/ *, */).reduce(function(e,t){var r=t.split(/ *; */),n=r[0].slice(1,-1),o=r[1].split(/ *= */)[1].slice(1,-1);return e[o]=n,e},{})},At.cleanHeader=function(i,e){return delete i["content-type"],delete i["content-length"],delete i["transfer-encoding"],delete i.host,e&&(delete i.authorization,delete i.cookie),i}),At}var Er,iu;function Jp(){if(iu)return Er;iu=1;var i=Qp();Er=e;function e(r){if(r)return t(r)}function t(r){for(var n in e.prototype)r[n]=e.prototype[n];return r}return e.prototype.get=function(r){return this.header[r.toLowerCase()]},e.prototype._setHeaderProperties=function(r){var n=r["content-type"]||"";this.type=i.type(n);var o=i.params(n);for(var u in o)this[u]=o[u];this.links={};try{r.link&&(this.links=i.parseLinks(r.link))}catch(a){}},e.prototype._setStatusProperties=function(r){var n=r/100|0;this.status=this.statusCode=r,this.statusType=n,this.info=n==1,this.ok=n==2,this.redirect=n==3,this.clientError=n==4,this.serverError=n==5,this.error=n==4||n==5?this.toError():!1,this.created=r==201,this.accepted=r==202,this.noContent=r==204,this.badRequest=r==400,this.unauthorized=r==401,this.notAcceptable=r==406,this.forbidden=r==403,this.notFound=r==404,this.unprocessableEntity=r==422},Er}var Ir,ou;function Xp(){if(ou)return Ir;ou=1;function i(){this._defaults=[]}return["use","on","once","set","query","type","accept","auth","withCredentials","sortQuery","retry","ok","redirects","timeout","buffer","serialize","parse","ca","key","pfx","cert"].forEach(function(e){i.prototype[e]=function(){return this._defaults.push({fn:e,arguments}),this}}),i.prototype._setDefaults=function(e){this._defaults.forEach(function(t){e[t.fn].apply(e,t.arguments)})},Ir=i,Ir}var Zp=et.exports,su;function em(){return su||(su=1,(function(i,e){var t;typeof window!="undefined"?t=window:typeof self!="undefined"?t=self:(console.warn("Using browser-only version of superagent in non-browser environment"),t=Zp);var r=Xe(),n=Kp(),o=Ft(),u=Jp(),a=Xp();function s(){}var l=e=i.exports=function(S,b){return typeof b=="function"?new e.Request("GET",S).end(b):arguments.length==1?new e.Request("GET",S):new e.Request(S,b)};e.Request=A,l.getXHR=function(){if(t.XMLHttpRequest&&(!t.location||t.location.protocol!="file:"||!t.ActiveXObject))return new XMLHttpRequest;try{return new ActiveXObject("Microsoft.XMLHTTP")}catch(S){}try{return new ActiveXObject("Msxml2.XMLHTTP.6.0")}catch(S){}try{return new ActiveXObject("Msxml2.XMLHTTP.3.0")}catch(S){}try{return new ActiveXObject("Msxml2.XMLHTTP")}catch(S){}throw Error("Browser-only version of superagent could not find XHR")};var d="".trim?function(S){return S.trim()}:function(S){return S.replace(/(^\s*|\s*$)/g,"")};function _(S){if(!o(S))return S;var b=[];for(var h in S)g(b,h,S[h]);return b.join("&")}function g(S,b,h){if(h!=null)if(Array.isArray(h))h.forEach(function(v){g(S,b,v)});else if(o(h))for(var p in h)g(S,b+"["+p+"]",h[p]);else S.push(encodeURIComponent(b)+"="+encodeURIComponent(h));else h===null&&S.push(encodeURIComponent(b))}l.serializeObject=_;function E(S){for(var b={},h=S.split("&"),p,v,I=0,B=h.length;I<B;++I)p=h[I],v=p.indexOf("="),v==-1?b[decodeURIComponent(p)]="":b[decodeURIComponent(p.slice(0,v))]=decodeURIComponent(p.slice(v+1));return b}l.parseString=E,l.types={html:"text/html",json:"application/json",xml:"text/xml",urlencoded:"application/x-www-form-urlencoded",form:"application/x-www-form-urlencoded","form-data":"application/x-www-form-urlencoded"},l.serialize={"application/x-www-form-urlencoded":_,"application/json":JSON.stringify},l.parse={"application/x-www-form-urlencoded":E,"application/json":JSON.parse};function w(S){for(var b=S.split(/\r?\n/),h={},p,v,I,B,H=0,V=b.length;H<V;++H)v=b[H],p=v.indexOf(":"),p!==-1&&(I=v.slice(0,p).toLowerCase(),B=d(v.slice(p+1)),h[I]=B);return h}function q(S){return/[\/+]json($|[^-\w])/.test(S)}function k(S){this.req=S,this.xhr=this.req.xhr,this.text=this.req.method!="HEAD"&&(this.xhr.responseType===""||this.xhr.responseType==="text")||typeof this.xhr.responseType=="undefined"?this.xhr.responseText:null,this.statusText=this.req.xhr.statusText;var b=this.xhr.status;b===1223&&(b=204),this._setStatusProperties(b),this.header=this.headers=w(this.xhr.getAllResponseHeaders()),this.header["content-type"]=this.xhr.getResponseHeader("content-type"),this._setHeaderProperties(this.header),this.text===null&&S._responseType?this.body=this.xhr.response:this.body=this.req.method!="HEAD"?this._parseBody(this.text?this.text:this.xhr.response):null}u(k.prototype),k.prototype._parseBody=function(S){var b=l.parse[this.type];return this.req._parser?this.req._parser(this,S):(!b&&q(this.type)&&(b=l.parse["application/json"]),b&&S&&(S.length||S instanceof Object)?b(S):null)},k.prototype.toError=function(){var S=this.req,b=S.method,h=S.url,p="cannot "+b+" "+h+" ("+this.status+")",v=new Error(p);return v.status=this.status,v.method=b,v.url=h,v},l.Response=k;function A(S,b){var h=this;this._query=this._query||[],this.method=S,this.url=b,this.header={},this._header={},this.on("end",function(){var p=null,v=null;try{v=new k(h)}catch(B){return p=new Error("Parser is unable to parse the response"),p.parse=!0,p.original=B,h.xhr?(p.rawResponse=typeof h.xhr.responseType=="undefined"?h.xhr.responseText:h.xhr.response,p.status=h.xhr.status?h.xhr.status:null,p.statusCode=p.status):(p.rawResponse=null,p.status=null),h.callback(p)}h.emit("response",v);var I;try{h._isResponseOK(v)||(I=new Error(v.statusText||"Unsuccessful HTTP response"))}catch(B){I=B}I?(I.original=p,I.response=v,I.status=v.status,h.callback(I,v)):h.callback(null,v)})}r(A.prototype),n(A.prototype),A.prototype.type=function(S){return this.set("Content-Type",l.types[S]||S),this},A.prototype.accept=function(S){return this.set("Accept",l.types[S]||S),this},A.prototype.auth=function(S,b,h){arguments.length===1&&(b=""),typeof b=="object"&&b!==null&&(h=b,b=""),h||(h={type:typeof btoa=="function"?"basic":"auto"});var p=function(v){if(typeof btoa=="function")return btoa(v);throw new Error("Cannot use basic auth, btoa is not a function")};return this._auth(S,b,h,p)},A.prototype.query=function(S){return typeof S!="string"&&(S=_(S)),S&&this._query.push(S),this},A.prototype.attach=function(S,b,h){if(b){if(this._data)throw Error("superagent can't mix .send() and .attach()");this._getFormData().append(S,b,h||b.name)}return this},A.prototype._getFormData=function(){return this._formData||(this._formData=new t.FormData),this._formData},A.prototype.callback=function(S,b){if(this._shouldRetry(S,b))return this._retry();var h=this._callback;this.clearTimeout(),S&&(this._maxRetries&&(S.retries=this._retries-1),this.emit("error",S)),h(S,b)},A.prototype.crossDomainError=function(){var S=new Error(`Request has been terminated
2
2
  Possible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.`);S.crossDomain=!0,S.status=this.status,S.method=this.method,S.url=this.url,this.callback(S)},A.prototype.buffer=A.prototype.ca=A.prototype.agent=function(){return console.warn("This is not supported in browser version of superagent"),this},A.prototype.pipe=A.prototype.write=function(){throw Error("Streaming is not supported in browser version of superagent")},A.prototype._isHost=function(b){return b&&typeof b=="object"&&!Array.isArray(b)&&Object.prototype.toString.call(b)!=="[object Object]"},A.prototype.end=function(S){return this._endCalled&&console.warn("Warning: .end() was called twice. This is not supported in superagent"),this._endCalled=!0,this._callback=S||s,this._finalizeQueryString(),this._end()},A.prototype._end=function(){var S=this,b=this.xhr=l.getXHR(),h=this._formData||this._data;this._setTimeouts(),b.onreadystatechange=function(){var H=b.readyState;if(H>=2&&S._responseTimeoutTimer&&clearTimeout(S._responseTimeoutTimer),H==4){var V;try{V=b.status}catch(P){V=0}if(!V)return S.timedout||S._aborted?void 0:S.crossDomainError();S.emit("end")}};var p=function(H,V){V.total>0&&(V.percent=V.loaded/V.total*100),V.direction=H,S.emit("progress",V)};if(this.hasListeners("progress"))try{b.onprogress=p.bind(null,"download"),b.upload&&(b.upload.onprogress=p.bind(null,"upload"))}catch(H){}try{this.username&&this.password?b.open(this.method,this.url,!0,this.username,this.password):b.open(this.method,this.url,!0)}catch(H){return this.callback(H)}if(this._withCredentials&&(b.withCredentials=!0),!this._formData&&this.method!="GET"&&this.method!="HEAD"&&typeof h!="string"&&!this._isHost(h)){var v=this._header["content-type"],I=this._serializer||l.serialize[v?v.split(";")[0]:""];!I&&q(v)&&(I=l.serialize["application/json"]),I&&(h=I(h))}for(var B in this.header)this.header[B]!=null&&this.header.hasOwnProperty(B)&&b.setRequestHeader(B,this.header[B]);return this._responseType&&(b.responseType=this._responseType),this.emit("request",this),b.send(typeof h!="undefined"?h:null),this},l.agent=function(){return new a},["GET","POST","OPTIONS","PATCH","PUT","DELETE"].forEach(function(S){a.prototype[S.toLowerCase()]=function(b,h){var p=new l.Request(S,b);return this._setDefaults(p),h&&p.end(h),p}}),a.prototype.del=a.prototype.delete,l.get=function(S,b,h){var p=l("GET",S);return typeof b=="function"&&(h=b,b=null),b&&p.query(b),h&&p.end(h),p},l.head=function(S,b,h){var p=l("HEAD",S);return typeof b=="function"&&(h=b,b=null),b&&p.query(b),h&&p.end(h),p},l.options=function(S,b,h){var p=l("OPTIONS",S);return typeof b=="function"&&(h=b,b=null),b&&p.send(b),h&&p.end(h),p};function R(S,b,h){var p=l("DELETE",S);return typeof b=="function"&&(h=b,b=null),b&&p.send(b),h&&p.end(h),p}l.del=R,l.delete=R,l.patch=function(S,b,h){var p=l("PATCH",S);return typeof b=="function"&&(h=b,b=null),b&&p.send(b),h&&p.end(h),p},l.post=function(S,b,h){var p=l("POST",S);return typeof b=="function"&&(h=b,b=null),b&&p.send(b),h&&p.end(h),p},l.put=function(S,b,h){var p=l("PUT",S);return typeof b=="function"&&(h=b,b=null),b&&p.send(b),h&&p.end(h),p}})(et,et.exports)),et.exports}var tm=em();const st=rt(tm);function Ot(i){return i=i||Object.create(null),{on:function(t,r){(i[t]||(i[t]=[])).push(r)},off:function(t,r){i[t]&&i[t].splice(i[t].indexOf(r)>>>0,1)},emit:function(t,r){(i[t]||[]).slice().map(function(n){n(r)}),(i["*"]||[]).slice().map(function(n){n(t,r)})}}}const Tr=Object.prototype.toString,Ye={};Ye.array=Array.isArray,Ye.undefined=i=>i===void 0,Ye.string=i=>Tr.call(i)==="[object String]",Ye.object=i=>Object(i)===i,Ye.function=i=>Tr.call(i)==="[object Function]"||typeof i=="function",Ye.json=i=>Tr.call(i)==="[object Object]",Ye.not={array:i=>!Ye.array(i),string:i=>!Ye.string(i),object:i=>!Ye.object(i),function:i=>!Ye.function(i),json:i=>!Ye.json(i)};var Rr,au;function rm(){if(au)return Rr;au=1;var i=6e4;return Rr=function(t){var r=new Date(t.getTime()),n=r.getTimezoneOffset();r.setSeconds(0,0);var o=r.getTime()%i;return n*i+o},Rr}var Ar,uu;function Or(){if(uu)return Ar;uu=1;function i(e){return e instanceof Date}return Ar=i,Ar}var xr,fu;function ge(){if(fu)return xr;fu=1;var i=rm(),e=Or(),t=36e5,r=6e4,n=2,o=/[T ]/,u=/:/,a=/^(\d{2})$/,s=[/^([+-]\d{2})$/,/^([+-]\d{3})$/,/^([+-]\d{4})$/],l=/^(\d{4})/,d=[/^([+-]\d{4})/,/^([+-]\d{5})/,/^([+-]\d{6})/],_=/^-(\d{2})$/,g=/^-?(\d{3})$/,E=/^-?(\d{2})-?(\d{2})$/,w=/^-?W(\d{2})$/,q=/^-?W(\d{2})-?(\d{1})$/,k=/^(\d{2}([.,]\d*)?)$/,A=/^(\d{2}):?(\d{2}([.,]\d*)?)$/,R=/^(\d{2}):?(\d{2}):?(\d{2}([.,]\d*)?)$/,S=/([Z+-].*)$/,b=/^(Z)$/,h=/^([+-])(\d{2})$/,p=/^([+-])(\d{2}):?(\d{2})$/;function v(oe,ne){if(e(oe))return new Date(oe.getTime());if(typeof oe!="string")return new Date(oe);var se=ne||{},he=se.additionalDigits;he==null?he=n:he=Number(he);var J=I(oe),me=B(J.date,he),de=me.year,be=me.restDateString,G=H(be,de);if(G){var re=G.getTime(),j=0,L;if(J.time&&(j=V(J.time)),J.timezone)L=P(J.timezone)*r;else{var M=re+j,D=new Date(M);L=i(D);var $=new Date(M);$.setDate(D.getDate()+1);var z=i($)-i(D);z>0&&(L+=z)}return new Date(re+j+L)}else return new Date(oe)}function I(oe){var ne={},se=oe.split(o),he;if(u.test(se[0])?(ne.date=null,he=se[0]):(ne.date=se[0],he=se[1]),he){var J=S.exec(he);J?(ne.time=he.replace(J[1],""),ne.timezone=J[1]):ne.time=he}return ne}function B(oe,ne){var se=s[ne],he=d[ne],J;if(J=l.exec(oe)||he.exec(oe),J){var me=J[1];return{year:parseInt(me,10),restDateString:oe.slice(me.length)}}if(J=a.exec(oe)||se.exec(oe),J){var de=J[1];return{year:parseInt(de,10)*100,restDateString:oe.slice(de.length)}}return{year:null}}function H(oe,ne){if(ne===null)return null;var se,he,J,me;if(oe.length===0)return he=new Date(0),he.setUTCFullYear(ne),he;if(se=_.exec(oe),se)return he=new Date(0),J=parseInt(se[1],10)-1,he.setUTCFullYear(ne,J),he;if(se=g.exec(oe),se){he=new Date(0);var de=parseInt(se[1],10);return he.setUTCFullYear(ne,0,de),he}if(se=E.exec(oe),se){he=new Date(0),J=parseInt(se[1],10)-1;var be=parseInt(se[2],10);return he.setUTCFullYear(ne,J,be),he}if(se=w.exec(oe),se)return me=parseInt(se[1],10)-1,ce(ne,me);if(se=q.exec(oe),se){me=parseInt(se[1],10)-1;var G=parseInt(se[2],10)-1;return ce(ne,me,G)}return null}function V(oe){var ne,se,he;if(ne=k.exec(oe),ne)return se=parseFloat(ne[1].replace(",",".")),se%24*t;if(ne=A.exec(oe),ne)return se=parseInt(ne[1],10),he=parseFloat(ne[2].replace(",",".")),se%24*t+he*r;if(ne=R.exec(oe),ne){se=parseInt(ne[1],10),he=parseInt(ne[2],10);var J=parseFloat(ne[3].replace(",","."));return se%24*t+he*r+J*1e3}return null}function P(oe){var ne,se;return ne=b.exec(oe),ne?0:(ne=h.exec(oe),ne?(se=parseInt(ne[2],10)*60,ne[1]==="+"?-se:se):(ne=p.exec(oe),ne?(se=parseInt(ne[2],10)*60+parseInt(ne[3],10),ne[1]==="+"?-se:se):0))}function ce(oe,ne,se){ne=ne||0,se=se||0;var he=new Date(0);he.setUTCFullYear(oe,0,4);var J=he.getUTCDay()||7,me=ne*7+se+1-J;return he.setUTCDate(he.getUTCDate()+me),he}return xr=v,xr}var Cr,lu;function cu(){if(lu)return Cr;lu=1;var i=ge();function e(t){var r=i(t),n=new Date(0);return n.setFullYear(r.getFullYear(),0,1),n.setHours(0,0,0,0),n}return Cr=e,Cr}var kr,hu;function bt(){if(hu)return kr;hu=1;var i=ge();function e(t){var r=i(t);return r.setHours(0,0,0,0),r}return kr=e,kr}var qr,du;function Xt(){if(du)return qr;du=1;var i=bt(),e=6e4,t=864e5;function r(n,o){var u=i(n),a=i(o),s=u.getTime()-u.getTimezoneOffset()*e,l=a.getTime()-a.getTimezoneOffset()*e;return Math.round((s-l)/t)}return qr=r,qr}var Mr,pu;function mu(){if(pu)return Mr;pu=1;var i=ge(),e=cu(),t=Xt();function r(n){var o=i(n),u=t(o,e(o)),a=u+1;return a}return Mr=r,Mr}var Pr,yu;function Zt(){if(yu)return Pr;yu=1;var i=ge();function e(t,r){var n=r&&Number(r.weekStartsOn)||0,o=i(t),u=o.getDay(),a=(u<n?7:0)+u-n;return o.setDate(o.getDate()-a),o.setHours(0,0,0,0),o}return Pr=e,Pr}var Br,gu;function wt(){if(gu)return Br;gu=1;var i=Zt();function e(t){return i(t,{weekStartsOn:1})}return Br=e,Br}var Dr,_u;function St(){if(_u)return Dr;_u=1;var i=ge(),e=wt();function t(r){var n=i(r),o=n.getFullYear(),u=new Date(0);u.setFullYear(o+1,0,4),u.setHours(0,0,0,0);var a=e(u),s=new Date(0);s.setFullYear(o,0,4),s.setHours(0,0,0,0);var l=e(s);return n.getTime()>=a.getTime()?o+1:n.getTime()>=l.getTime()?o:o-1}return Dr=t,Dr}var Lr,vu;function Nt(){if(vu)return Lr;vu=1;var i=St(),e=wt();function t(r){var n=i(r),o=new Date(0);o.setFullYear(n,0,4),o.setHours(0,0,0,0);var u=e(o);return u}return Lr=t,Lr}var Fr,bu;function Ur(){if(bu)return Fr;bu=1;var i=ge(),e=wt(),t=Nt(),r=6048e5;function n(o){var u=i(o),a=e(u).getTime()-t(u).getTime();return Math.round(a/r)+1}return Fr=n,Fr}var Nr,wu;function Su(){if(wu)return Nr;wu=1;var i=Or();function e(t){if(i(t))return!isNaN(t);throw new TypeError(toString.call(t)+" is not an instance of Date")}return Nr=e,Nr}var jr,Eu;function nm(){if(Eu)return jr;Eu=1;function i(){var e={lessThanXSeconds:{one:"less than a second",other:"less than {{count}} seconds"},xSeconds:{one:"1 second",other:"{{count}} seconds"},halfAMinute:"half a minute",lessThanXMinutes:{one:"less than a minute",other:"less than {{count}} minutes"},xMinutes:{one:"1 minute",other:"{{count}} minutes"},aboutXHours:{one:"about 1 hour",other:"about {{count}} hours"},xHours:{one:"1 hour",other:"{{count}} hours"},xDays:{one:"1 day",other:"{{count}} days"},aboutXMonths:{one:"about 1 month",other:"about {{count}} months"},xMonths:{one:"1 month",other:"{{count}} months"},aboutXYears:{one:"about 1 year",other:"about {{count}} years"},xYears:{one:"1 year",other:"{{count}} years"},overXYears:{one:"over 1 year",other:"over {{count}} years"},almostXYears:{one:"almost 1 year",other:"almost {{count}} years"}};function t(r,n,o){o=o||{};var u;return typeof e[r]=="string"?u=e[r]:n===1?u=e[r].one:u=e[r].other.replace("{{count}}",n),o.addSuffix?o.comparison>0?"in "+u:u+" ago":u}return{localize:t}}return jr=i,jr}var $r,Iu;function im(){if(Iu)return $r;Iu=1;var i=["M","MM","Q","D","DD","DDD","DDDD","d","E","W","WW","YY","YYYY","GG","GGGG","H","HH","h","hh","m","mm","s","ss","S","SS","SSS","Z","ZZ","X","x"];function e(t){var r=[];for(var n in t)t.hasOwnProperty(n)&&r.push(n);var o=i.concat(r).sort().reverse(),u=new RegExp("(\\[[^\\[]*\\])|(\\\\)?("+o.join("|")+"|.)","g");return u}return $r=e,$r}var Hr,Tu;function om(){if(Tu)return Hr;Tu=1;var i=im();function e(){var r=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],n=["January","February","March","April","May","June","July","August","September","October","November","December"],o=["Su","Mo","Tu","We","Th","Fr","Sa"],u=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],a=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],s=["AM","PM"],l=["am","pm"],d=["a.m.","p.m."],_={MMM:function(E){return r[E.getMonth()]},MMMM:function(E){return n[E.getMonth()]},dd:function(E){return o[E.getDay()]},ddd:function(E){return u[E.getDay()]},dddd:function(E){return a[E.getDay()]},A:function(E){return E.getHours()/12>=1?s[1]:s[0]},a:function(E){return E.getHours()/12>=1?l[1]:l[0]},aa:function(E){return E.getHours()/12>=1?d[1]:d[0]}},g=["M","D","DDD","d","Q","W"];return g.forEach(function(E){_[E+"o"]=function(w,q){return t(q[E](w))}}),{formatters:_,formattingTokensRegExp:i(_)}}function t(r){var n=r%100;if(n>20||n<10)switch(n%10){case 1:return r+"st";case 2:return r+"nd";case 3:return r+"rd"}return r+"th"}return Hr=e,Hr}var Wr,Ru;function Yr(){if(Ru)return Wr;Ru=1;var i=nm(),e=om();return Wr={distanceInWords:i(),format:e()},Wr}var Gr,Au;function Ou(){if(Au)return Gr;Au=1;var i=mu(),e=Ur(),t=St(),r=ge(),n=Su(),o=Yr();function u(g,E,w){var q=E?String(E):"YYYY-MM-DDTHH:mm:ss.SSSZ",k=w||{},A=k.locale,R=o.format.formatters,S=o.format.formattingTokensRegExp;A&&A.format&&A.format.formatters&&(R=A.format.formatters,A.format.formattingTokensRegExp&&(S=A.format.formattingTokensRegExp));var b=r(g);if(!n(b))return"Invalid Date";var h=s(q,R,S);return h(b)}var a={M:function(g){return g.getMonth()+1},MM:function(g){return _(g.getMonth()+1,2)},Q:function(g){return Math.ceil((g.getMonth()+1)/3)},D:function(g){return g.getDate()},DD:function(g){return _(g.getDate(),2)},DDD:function(g){return i(g)},DDDD:function(g){return _(i(g),3)},d:function(g){return g.getDay()},E:function(g){return g.getDay()||7},W:function(g){return e(g)},WW:function(g){return _(e(g),2)},YY:function(g){return _(g.getFullYear(),4).substr(2)},YYYY:function(g){return _(g.getFullYear(),4)},GG:function(g){return String(t(g)).substr(2)},GGGG:function(g){return t(g)},H:function(g){return g.getHours()},HH:function(g){return _(g.getHours(),2)},h:function(g){var E=g.getHours();return E===0?12:E>12?E%12:E},hh:function(g){return _(a.h(g),2)},m:function(g){return g.getMinutes()},mm:function(g){return _(g.getMinutes(),2)},s:function(g){return g.getSeconds()},ss:function(g){return _(g.getSeconds(),2)},S:function(g){return Math.floor(g.getMilliseconds()/100)},SS:function(g){return _(Math.floor(g.getMilliseconds()/10),2)},SSS:function(g){return _(g.getMilliseconds(),3)},Z:function(g){return d(g.getTimezoneOffset(),":")},ZZ:function(g){return d(g.getTimezoneOffset())},X:function(g){return Math.floor(g.getTime()/1e3)},x:function(g){return g.getTime()}};function s(g,E,w){var q=g.match(w),k=q.length,A,R;for(A=0;A<k;A++)R=E[q[A]]||a[q[A]],R?q[A]=R:q[A]=l(q[A]);return function(S){for(var b="",h=0;h<k;h++)q[h]instanceof Function?b+=q[h](S,a):b+=q[h];return b}}function l(g){return g.match(/\[[\s\S]/)?g.replace(/^\[|]$/g,""):g.replace(/\\/g,"")}function d(g,E){E=E||"";var w=g>0?"-":"+",q=Math.abs(g),k=Math.floor(q/60),A=q%60;return w+_(k,2)+E+_(A,2)}function _(g,E){for(var w=Math.abs(g).toString();w.length<E;)w="0"+w;return w}return Gr=u,Gr}var sm=Ou();const am=rt(sm);var zr,xu;function Vr(){if(xu)return zr;xu=1;var i=ge();function e(t,r){var n=i(t),o=n.getTime(),u=i(r),a=u.getTime();return o>a?-1:o<a?1:0}return zr=e,zr}var Kr,Cu;function er(){if(Cu)return Kr;Cu=1;var i=ge();function e(t,r){var n=i(t),o=i(r);return n.getTime()-o.getTime()}return Kr=e,Kr}var Qr,ku;function Jr(){if(ku)return Qr;ku=1;var i=er();function e(t,r){var n=i(t,r)/1e3;return n>0?Math.floor(n):Math.ceil(n)}return Qr=e,Qr}var Xr,qu;function Mu(){if(qu)return Xr;qu=1;var i=ge();function e(t,r){var n=i(t),o=i(r),u=n.getFullYear()-o.getFullYear(),a=n.getMonth()-o.getMonth();return u*12+a}return Xr=e,Xr}var Zr,Pu;function jt(){if(Pu)return Zr;Pu=1;var i=ge();function e(t,r){var n=i(t),o=n.getTime(),u=i(r),a=u.getTime();return o<a?-1:o>a?1:0}return Zr=e,Zr}var en,Bu;function tn(){if(Bu)return en;Bu=1;var i=ge(),e=Mu(),t=jt();function r(n,o){var u=i(n),a=i(o),s=t(u,a),l=Math.abs(e(u,a));u.setMonth(u.getMonth()-s*l);var d=t(u,a)===-s;return s*(l-d)}return en=r,en}var rn,Du;function Lu(){if(Du)return rn;Du=1;var i=Vr(),e=ge(),t=Jr(),r=tn(),n=Yr(),o=1440,u=2520,a=43200,s=86400;function l(d,_,g){var E=g||{},w=i(d,_),q=E.locale,k=n.distanceInWords.localize;q&&q.distanceInWords&&q.distanceInWords.localize&&(k=q.distanceInWords.localize);var A={addSuffix:!!E.addSuffix,comparison:w},R,S;w>0?(R=e(d),S=e(_)):(R=e(_),S=e(d));var b=t(S,R),h=S.getTimezoneOffset()-R.getTimezoneOffset(),p=Math.round(b/60)-h,v;if(p<2)return E.includeSeconds?b<5?k("lessThanXSeconds",5,A):b<10?k("lessThanXSeconds",10,A):b<20?k("lessThanXSeconds",20,A):b<40?k("halfAMinute",null,A):b<60?k("lessThanXMinutes",1,A):k("xMinutes",1,A):p===0?k("lessThanXMinutes",1,A):k("xMinutes",p,A);if(p<45)return k("xMinutes",p,A);if(p<90)return k("aboutXHours",1,A);if(p<o){var I=Math.round(p/60);return k("aboutXHours",I,A)}else{if(p<u)return k("xDays",1,A);if(p<a){var B=Math.round(p/o);return k("xDays",B,A)}else if(p<s)return v=Math.round(p/a),k("aboutXMonths",v,A)}if(v=r(S,R),v<12){var H=Math.round(p/a);return k("xMonths",H,A)}else{var V=v%12,P=Math.floor(v/12);return V<3?k("aboutXYears",P,A):V<9?k("overXYears",P,A):k("almostXYears",P+1,A)}}return rn=l,rn}var nn,Fu;function Uu(){if(Fu)return nn;Fu=1;var i=Lu();function e(t,r){return i(Date.now(),t,r)}return nn=e,nn}var um=Uu();const fm=rt(um);var on,Nu;function $t(){if(Nu)return on;Nu=1;var i=ge();function e(t,r){var n=i(t),o=Number(r);return n.setDate(n.getDate()+o),n}return on=e,on}var sn,ju;function Ht(){if(ju)return sn;ju=1;var i=ge();function e(t,r){var n=i(t).getTime(),o=Number(r);return new Date(n+o)}return sn=e,sn}var an,$u;function Hu(){if($u)return an;$u=1;var i=Ht(),e=36e5;function t(r,n){var o=Number(n);return i(r,o*e)}return an=t,an}var un,Wu;function Yu(){if(Wu)return un;Wu=1;var i=ge(),e=Nt(),t=Xt();function r(n,o){var u=i(n),a=Number(o),s=t(u,e(u)),l=new Date(0);return l.setFullYear(a,0,4),l.setHours(0,0,0,0),u=e(l),u.setDate(u.getDate()+s),u}return un=r,un}var fn,Gu;function zu(){if(Gu)return fn;Gu=1;var i=St(),e=Yu();function t(r,n){var o=Number(n);return e(r,i(r)+o)}return fn=t,fn}var ln,Vu;function Ku(){if(Vu)return ln;Vu=1;var i=Ht(),e=6e4;function t(r,n){var o=Number(n);return i(r,o*e)}return ln=t,ln}var cn,Qu;function hn(){if(Qu)return cn;Qu=1;var i=ge();function e(t){var r=i(t),n=r.getFullYear(),o=r.getMonth(),u=new Date(0);return u.setFullYear(n,o+1,0),u.setHours(0,0,0,0),u.getDate()}return cn=e,cn}var dn,Ju;function tr(){if(Ju)return dn;Ju=1;var i=ge(),e=hn();function t(r,n){var o=i(r),u=Number(n),a=o.getMonth()+u,s=new Date(0);s.setFullYear(o.getFullYear(),a,1),s.setHours(0,0,0,0);var l=e(s);return o.setMonth(a,Math.min(l,o.getDate())),o}return dn=t,dn}var pn,Xu;function Zu(){if(Xu)return pn;Xu=1;var i=tr();function e(t,r){var n=Number(r),o=n*3;return i(t,o)}return pn=e,pn}var mn,ef;function tf(){if(ef)return mn;ef=1;var i=Ht();function e(t,r){var n=Number(r);return i(t,n*1e3)}return mn=e,mn}var yn,rf;function gn(){if(rf)return yn;rf=1;var i=$t();function e(t,r){var n=Number(r),o=n*7;return i(t,o)}return yn=e,yn}var _n,nf;function of(){if(nf)return _n;nf=1;var i=tr();function e(t,r){var n=Number(r);return i(t,n*12)}return _n=e,_n}var vn,sf;function lm(){if(sf)return vn;sf=1;var i=ge();function e(t,r,n,o){var u=i(t).getTime(),a=i(r).getTime(),s=i(n).getTime(),l=i(o).getTime();if(u>a||s>l)throw new Error("The start of the range cannot be after the end of the range");return u<l&&s<a}return vn=e,vn}var bn,af;function cm(){if(af)return bn;af=1;var i=ge();function e(t,r){if(!(r instanceof Array))throw new TypeError(toString.call(r)+" is not an instance of Array");var n=i(t),o=n.getTime(),u,a;return r.forEach(function(s,l){var d=i(s),_=Math.abs(o-d.getTime());(u===void 0||_<a)&&(u=l,a=_)}),u}return bn=e,bn}var wn,uf;function hm(){if(uf)return wn;uf=1;var i=ge();function e(t,r){if(!(r instanceof Array))throw new TypeError(toString.call(r)+" is not an instance of Array");var n=i(t),o=n.getTime(),u,a;return r.forEach(function(s){var l=i(s),d=Math.abs(o-l.getTime());(u===void 0||d<a)&&(u=l,a=d)}),u}return wn=e,wn}var Sn,ff;function dm(){if(ff)return Sn;ff=1;var i=wt(),e=6e4,t=6048e5;function r(n,o){var u=i(n),a=i(o),s=u.getTime()-u.getTimezoneOffset()*e,l=a.getTime()-a.getTimezoneOffset()*e;return Math.round((s-l)/t)}return Sn=r,Sn}var En,lf;function cf(){if(lf)return En;lf=1;var i=St();function e(t,r){return i(t)-i(r)}return En=e,En}var In,hf;function df(){if(hf)return In;hf=1;var i=ge();function e(t){var r=i(t),n=Math.floor(r.getMonth()/3)+1;return n}return In=e,In}var Tn,pf;function pm(){if(pf)return Tn;pf=1;var i=df(),e=ge();function t(r,n){var o=e(r),u=e(n),a=o.getFullYear()-u.getFullYear(),s=i(o)-i(u);return a*4+s}return Tn=t,Tn}var Rn,mf;function mm(){if(mf)return Rn;mf=1;var i=Zt(),e=6e4,t=6048e5;function r(n,o,u){var a=i(n,u),s=i(o,u),l=a.getTime()-a.getTimezoneOffset()*e,d=s.getTime()-s.getTimezoneOffset()*e;return Math.round((l-d)/t)}return Rn=r,Rn}var An,yf;function gf(){if(yf)return An;yf=1;var i=ge();function e(t,r){var n=i(t),o=i(r);return n.getFullYear()-o.getFullYear()}return An=e,An}var On,_f;function vf(){if(_f)return On;_f=1;var i=ge(),e=Xt(),t=jt();function r(n,o){var u=i(n),a=i(o),s=t(u,a),l=Math.abs(e(u,a));u.setDate(u.getDate()-s*l);var d=t(u,a)===-s;return s*(l-d)}return On=r,On}var xn,bf;function ym(){if(bf)return xn;bf=1;var i=er(),e=36e5;function t(r,n){var o=i(r,n)/e;return o>0?Math.floor(o):Math.ceil(o)}return xn=t,xn}var Cn,wf;function Sf(){if(wf)return Cn;wf=1;var i=zu();function e(t,r){var n=Number(r);return i(t,-n)}return Cn=e,Cn}var kn,Ef;function gm(){if(Ef)return kn;Ef=1;var i=ge(),e=cf(),t=jt(),r=Sf();function n(o,u){var a=i(o),s=i(u),l=t(a,s),d=Math.abs(e(a,s));a=r(a,l*d);var _=t(a,s)===-l;return l*(d-_)}return kn=n,kn}var qn,If;function _m(){if(If)return qn;If=1;var i=er(),e=6e4;function t(r,n){var o=i(r,n)/e;return o>0?Math.floor(o):Math.ceil(o)}return qn=t,qn}var Mn,Tf;function vm(){if(Tf)return Mn;Tf=1;var i=tn();function e(t,r){var n=i(t,r)/3;return n>0?Math.floor(n):Math.ceil(n)}return Mn=e,Mn}var Pn,Rf;function bm(){if(Rf)return Pn;Rf=1;var i=vf();function e(t,r){var n=i(t,r)/7;return n>0?Math.floor(n):Math.ceil(n)}return Pn=e,Pn}var Bn,Af;function wm(){if(Af)return Bn;Af=1;var i=ge(),e=gf(),t=jt();function r(n,o){var u=i(n),a=i(o),s=t(u,a),l=Math.abs(e(u,a));u.setFullYear(u.getFullYear()-s*l);var d=t(u,a)===-s;return s*(l-d)}return Bn=r,Bn}var Dn,Of;function Sm(){if(Of)return Dn;Of=1;var i=Vr(),e=ge(),t=Jr(),r=Yr(),n=1440,o=43200,u=525600;function a(s,l,d){var _=d||{},g=i(s,l),E=_.locale,w=r.distanceInWords.localize;E&&E.distanceInWords&&E.distanceInWords.localize&&(w=E.distanceInWords.localize);var q={addSuffix:!!_.addSuffix,comparison:g},k,A;g>0?(k=e(s),A=e(l)):(k=e(l),A=e(s));var R,S=Math[_.partialMethod?String(_.partialMethod):"floor"],b=t(A,k),h=A.getTimezoneOffset()-k.getTimezoneOffset(),p=S(b/60)-h,v,I,B,H;if(_.unit?R=String(_.unit):p<1?R="s":p<60?R="m":p<n?R="h":p<o?R="d":p<u?R="M":R="Y",R==="s")return w("xSeconds",b,q);if(R==="m")return w("xMinutes",p,q);if(R==="h")return v=S(p/60),w("xHours",v,q);if(R==="d")return I=S(p/n),w("xDays",I,q);if(R==="M")return B=S(p/o),w("xMonths",B,q);if(R==="Y")return H=S(p/u),w("xYears",H,q);throw new Error("Unknown unit: "+R)}return Dn=a,Dn}var Ln,xf;function Em(){if(xf)return Ln;xf=1;var i=ge();function e(t,r,n){var o=i(t),u=i(r),a=n!==void 0?n:1,s=u.getTime();if(o.getTime()>s)throw new Error("The first date cannot be after the second date");var l=[],d=o;for(d.setHours(0,0,0,0);d.getTime()<=s;)l.push(i(d)),d.setDate(d.getDate()+a);return l}return Ln=e,Ln}var Fn,Cf;function Un(){if(Cf)return Fn;Cf=1;var i=ge();function e(t){var r=i(t);return r.setHours(23,59,59,999),r}return Fn=e,Fn}var Nn,kf;function Im(){if(kf)return Nn;kf=1;var i=ge();function e(t){var r=i(t);return r.setMinutes(59,59,999),r}return Nn=e,Nn}var jn,qf;function Mf(){if(qf)return jn;qf=1;var i=ge();function e(t,r){var n=r&&Number(r.weekStartsOn)||0,o=i(t),u=o.getDay(),a=(u<n?-7:0)+6-(u-n);return o.setDate(o.getDate()+a),o.setHours(23,59,59,999),o}return jn=e,jn}var $n,Pf;function Tm(){if(Pf)return $n;Pf=1;var i=Mf();function e(t){return i(t,{weekStartsOn:1})}return $n=e,$n}var Hn,Bf;function Rm(){if(Bf)return Hn;Bf=1;var i=St(),e=wt();function t(r){var n=i(r),o=new Date(0);o.setFullYear(n+1,0,4),o.setHours(0,0,0,0);var u=e(o);return u.setMilliseconds(u.getMilliseconds()-1),u}return Hn=t,Hn}var Wn,Df;function Am(){if(Df)return Wn;Df=1;var i=ge();function e(t){var r=i(t);return r.setSeconds(59,999),r}return Wn=e,Wn}var Yn,Lf;function Ff(){if(Lf)return Yn;Lf=1;var i=ge();function e(t){var r=i(t),n=r.getMonth();return r.setFullYear(r.getFullYear(),n+1,0),r.setHours(23,59,59,999),r}return Yn=e,Yn}var Gn,Uf;function Om(){if(Uf)return Gn;Uf=1;var i=ge();function e(t){var r=i(t),n=r.getMonth(),o=n-n%3+3;return r.setMonth(o,0),r.setHours(23,59,59,999),r}return Gn=e,Gn}var zn,Nf;function xm(){if(Nf)return zn;Nf=1;var i=ge();function e(t){var r=i(t);return r.setMilliseconds(999),r}return zn=e,zn}var Vn,jf;function Cm(){if(jf)return Vn;jf=1;var i=Un();function e(){return i(new Date)}return Vn=e,Vn}var Kn,$f;function km(){if($f)return Kn;$f=1;function i(){var e=new Date,t=e.getFullYear(),r=e.getMonth(),n=e.getDate(),o=new Date(0);return o.setFullYear(t,r,n+1),o.setHours(23,59,59,999),o}return Kn=i,Kn}var Qn,Hf;function qm(){if(Hf)return Qn;Hf=1;var i=ge();function e(t){var r=i(t),n=r.getFullYear();return r.setFullYear(n+1,0,0),r.setHours(23,59,59,999),r}return Qn=e,Qn}var Jn,Wf;function Mm(){if(Wf)return Jn;Wf=1;function i(){var e=new Date,t=e.getFullYear(),r=e.getMonth(),n=e.getDate(),o=new Date(0);return o.setFullYear(t,r,n-1),o.setHours(23,59,59,999),o}return Jn=i,Jn}var Xn,Yf;function Pm(){if(Yf)return Xn;Yf=1;var i=ge();function e(t){var r=i(t),n=r.getDate();return n}return Xn=e,Xn}var Zn,Gf;function Bm(){if(Gf)return Zn;Gf=1;var i=ge();function e(t){var r=i(t),n=r.getDay();return n}return Zn=e,Zn}var ei,zf;function Vf(){if(zf)return ei;zf=1;var i=ge();function e(t){var r=i(t),n=r.getFullYear();return n%400===0||n%4===0&&n%100!==0}return ei=e,ei}var ti,Kf;function Dm(){if(Kf)return ti;Kf=1;var i=Vf();function e(t){return i(t)?366:365}return ti=e,ti}var ri,Qf;function Lm(){if(Qf)return ri;Qf=1;var i=ge();function e(t){var r=i(t),n=r.getHours();return n}return ri=e,ri}var ni,Jf;function Xf(){if(Jf)return ni;Jf=1;var i=ge();function e(t){var r=i(t),n=r.getDay();return n===0&&(n=7),n}return ni=e,ni}var ii,Zf;function Fm(){if(Zf)return ii;Zf=1;var i=Nt(),e=gn(),t=6048e5;function r(n){var o=i(n),u=i(e(o,60)),a=u.valueOf()-o.valueOf();return Math.round(a/t)}return ii=r,ii}var oi,el;function Um(){if(el)return oi;el=1;var i=ge();function e(t){var r=i(t),n=r.getMilliseconds();return n}return oi=e,oi}var si,tl;function Nm(){if(tl)return si;tl=1;var i=ge();function e(t){var r=i(t),n=r.getMinutes();return n}return si=e,si}var ai,rl;function jm(){if(rl)return ai;rl=1;var i=ge();function e(t){var r=i(t),n=r.getMonth();return n}return ai=e,ai}var ui,nl;function $m(){if(nl)return ui;nl=1;var i=ge(),e=1440*60*1e3;function t(r,n,o,u){var a=i(r).getTime(),s=i(n).getTime(),l=i(o).getTime(),d=i(u).getTime();if(a>s||l>d)throw new Error("The start of the range cannot be after the end of the range");var _=a<d&&l<s;if(!_)return 0;var g=l<a?a:l,E=d>s?s:d,w=E-g;return Math.ceil(w/e)}return ui=t,ui}var fi,il;function Hm(){if(il)return fi;il=1;var i=ge();function e(t){var r=i(t),n=r.getSeconds();return n}return fi=e,fi}var li,ol;function Wm(){if(ol)return li;ol=1;var i=ge();function e(t){var r=i(t),n=r.getTime();return n}return li=e,li}var ci,sl;function Ym(){if(sl)return ci;sl=1;var i=ge();function e(t){var r=i(t),n=r.getFullYear();return n}return ci=e,ci}var hi,al;function Gm(){if(al)return hi;al=1;var i=ge();function e(t,r){var n=i(t),o=i(r);return n.getTime()>o.getTime()}return hi=e,hi}var di,ul;function zm(){if(ul)return di;ul=1;var i=ge();function e(t,r){var n=i(t),o=i(r);return n.getTime()<o.getTime()}return di=e,di}var pi,fl;function Vm(){if(fl)return pi;fl=1;var i=ge();function e(t,r){var n=i(t),o=i(r);return n.getTime()===o.getTime()}return pi=e,pi}var mi,ll;function Km(){if(ll)return mi;ll=1;var i=ge();function e(t){return i(t).getDate()===1}return mi=e,mi}var yi,cl;function Qm(){if(cl)return yi;cl=1;var i=ge();function e(t){return i(t).getDay()===5}return yi=e,yi}var gi,hl;function Jm(){if(hl)return gi;hl=1;var i=ge();function e(t){return i(t).getTime()>new Date().getTime()}return gi=e,gi}var _i,dl;function Xm(){if(dl)return _i;dl=1;var i=ge(),e=Un(),t=Ff();function r(n){var o=i(n);return e(o).getTime()===t(o).getTime()}return _i=r,_i}var vi,pl;function Zm(){if(pl)return vi;pl=1;var i=ge();function e(t){return i(t).getDay()===1}return vi=e,vi}var bi,ml;function ey(){if(ml)return bi;ml=1;var i=ge();function e(t){return i(t).getTime()<new Date().getTime()}return bi=e,bi}var wi,yl;function ty(){if(yl)return wi;yl=1;var i=bt();function e(t,r){var n=i(t),o=i(r);return n.getTime()===o.getTime()}return wi=e,wi}var Si,gl;function _l(){if(gl)return Si;gl=1;var i=ge();function e(t){var r=i(t);return r.setMinutes(0,0,0),r}return Si=e,Si}var Ei,vl;function bl(){if(vl)return Ei;vl=1;var i=_l();function e(t,r){var n=i(t),o=i(r);return n.getTime()===o.getTime()}return Ei=e,Ei}var Ii,wl;function Ti(){if(wl)return Ii;wl=1;var i=Zt();function e(t,r,n){var o=i(t,n),u=i(r,n);return o.getTime()===u.getTime()}return Ii=e,Ii}var Ri,Sl;function El(){if(Sl)return Ri;Sl=1;var i=Ti();function e(t,r){return i(t,r,{weekStartsOn:1})}return Ri=e,Ri}var Ai,Il;function Tl(){if(Il)return Ai;Il=1;var i=Nt();function e(t,r){var n=i(t),o=i(r);return n.getTime()===o.getTime()}return Ai=e,Ai}var Oi,Rl;function Al(){if(Rl)return Oi;Rl=1;var i=ge();function e(t){var r=i(t);return r.setSeconds(0,0),r}return Oi=e,Oi}var xi,Ol;function xl(){if(Ol)return xi;Ol=1;var i=Al();function e(t,r){var n=i(t),o=i(r);return n.getTime()===o.getTime()}return xi=e,xi}var Ci,Cl;function kl(){if(Cl)return Ci;Cl=1;var i=ge();function e(t,r){var n=i(t),o=i(r);return n.getFullYear()===o.getFullYear()&&n.getMonth()===o.getMonth()}return Ci=e,Ci}var ki,ql;function Ml(){if(ql)return ki;ql=1;var i=ge();function e(t){var r=i(t),n=r.getMonth(),o=n-n%3;return r.setMonth(o,1),r.setHours(0,0,0,0),r}return ki=e,ki}var qi,Pl;function Bl(){if(Pl)return qi;Pl=1;var i=Ml();function e(t,r){var n=i(t),o=i(r);return n.getTime()===o.getTime()}return qi=e,qi}var Mi,Dl;function Ll(){if(Dl)return Mi;Dl=1;var i=ge();function e(t){var r=i(t);return r.setMilliseconds(0),r}return Mi=e,Mi}var Pi,Fl;function Ul(){if(Fl)return Pi;Fl=1;var i=Ll();function e(t,r){var n=i(t),o=i(r);return n.getTime()===o.getTime()}return Pi=e,Pi}var Bi,Nl;function jl(){if(Nl)return Bi;Nl=1;var i=ge();function e(t,r){var n=i(t),o=i(r);return n.getFullYear()===o.getFullYear()}return Bi=e,Bi}var Di,$l;function ry(){if($l)return Di;$l=1;var i=ge();function e(t){return i(t).getDay()===6}return Di=e,Di}var Li,Hl;function ny(){if(Hl)return Li;Hl=1;var i=ge();function e(t){return i(t).getDay()===0}return Li=e,Li}var Fi,Wl;function iy(){if(Wl)return Fi;Wl=1;var i=bl();function e(t){return i(new Date,t)}return Fi=e,Fi}var Ui,Yl;function oy(){if(Yl)return Ui;Yl=1;var i=El();function e(t){return i(new Date,t)}return Ui=e,Ui}var Ni,Gl;function sy(){if(Gl)return Ni;Gl=1;var i=Tl();function e(t){return i(new Date,t)}return Ni=e,Ni}var ji,zl;function ay(){if(zl)return ji;zl=1;var i=xl();function e(t){return i(new Date,t)}return ji=e,ji}var $i,Vl;function uy(){if(Vl)return $i;Vl=1;var i=kl();function e(t){return i(new Date,t)}return $i=e,$i}var Hi,Kl;function fy(){if(Kl)return Hi;Kl=1;var i=Bl();function e(t){return i(new Date,t)}return Hi=e,Hi}var Wi,Ql;function ly(){if(Ql)return Wi;Ql=1;var i=Ul();function e(t){return i(new Date,t)}return Wi=e,Wi}var Yi,Jl;function cy(){if(Jl)return Yi;Jl=1;var i=Ti();function e(t,r){return i(new Date,t,r)}return Yi=e,Yi}var Gi,Xl;function hy(){if(Xl)return Gi;Xl=1;var i=jl();function e(t){return i(new Date,t)}return Gi=e,Gi}var zi,Zl;function dy(){if(Zl)return zi;Zl=1;var i=ge();function e(t){return i(t).getDay()===4}return zi=e,zi}var Vi,ec;function py(){if(ec)return Vi;ec=1;var i=bt();function e(t){return i(t).getTime()===i(new Date).getTime()}return Vi=e,Vi}var Ki,tc;function my(){if(tc)return Ki;tc=1;var i=bt();function e(t){var r=new Date;return r.setDate(r.getDate()+1),i(t).getTime()===i(r).getTime()}return Ki=e,Ki}var Qi,rc;function yy(){if(rc)return Qi;rc=1;var i=ge();function e(t){return i(t).getDay()===2}return Qi=e,Qi}var Ji,nc;function gy(){if(nc)return Ji;nc=1;var i=ge();function e(t){return i(t).getDay()===3}return Ji=e,Ji}var Xi,ic;function _y(){if(ic)return Xi;ic=1;var i=ge();function e(t){var r=i(t),n=r.getDay();return n===0||n===6}return Xi=e,Xi}var Zi,oc;function vy(){if(oc)return Zi;oc=1;var i=ge();function e(t,r,n){var o=i(t).getTime(),u=i(r).getTime(),a=i(n).getTime();if(u>a)throw new Error("The start of the range cannot be after the end of the range");return o>=u&&o<=a}return Zi=e,Zi}var eo,sc;function by(){if(sc)return eo;sc=1;var i=bt();function e(t){var r=new Date;return r.setDate(r.getDate()-1),i(t).getTime()===i(r).getTime()}return eo=e,eo}var to,ac;function uc(){if(ac)return to;ac=1;var i=ge();function e(t,r){var n=r&&Number(r.weekStartsOn)||0,o=i(t),u=o.getDay(),a=(u<n?-7:0)+6-(u-n);return o.setHours(0,0,0,0),o.setDate(o.getDate()+a),o}return to=e,to}var ro,fc;function wy(){if(fc)return ro;fc=1;var i=uc();function e(t){return i(t,{weekStartsOn:1})}return ro=e,ro}var no,lc;function Sy(){if(lc)return no;lc=1;var i=St(),e=wt();function t(r){var n=i(r),o=new Date(0);o.setFullYear(n+1,0,4),o.setHours(0,0,0,0);var u=e(o);return u.setDate(u.getDate()-1),u}return no=t,no}var io,cc;function Ey(){if(cc)return io;cc=1;var i=ge();function e(t){var r=i(t),n=r.getMonth();return r.setFullYear(r.getFullYear(),n+1,0),r.setHours(0,0,0,0),r}return io=e,io}var oo,hc;function Iy(){if(hc)return oo;hc=1;var i=ge();function e(t){var r=i(t),n=r.getMonth(),o=n-n%3+3;return r.setMonth(o,0),r.setHours(0,0,0,0),r}return oo=e,oo}var so,dc;function Ty(){if(dc)return so;dc=1;var i=ge();function e(t){var r=i(t),n=r.getFullYear();return r.setFullYear(n+1,0,0),r.setHours(0,0,0,0),r}return so=e,so}var ao,pc;function Ry(){if(pc)return ao;pc=1;var i=ge();function e(){var t=Array.prototype.slice.call(arguments),r=t.map(function(o){return i(o)}),n=Math.max.apply(null,r);return new Date(n)}return ao=e,ao}var uo,mc;function Ay(){if(mc)return uo;mc=1;var i=ge();function e(){var t=Array.prototype.slice.call(arguments),r=t.map(function(o){return i(o)}),n=Math.min.apply(null,r);return new Date(n)}return uo=e,uo}var fo,yc;function Oy(){if(yc)return fo;yc=1;var i=ge();function e(t,r){var n=i(t),o=Number(r);return n.setDate(o),n}return fo=e,fo}var lo,gc;function xy(){if(gc)return lo;gc=1;var i=ge(),e=$t();function t(r,n,o){var u=o&&Number(o.weekStartsOn)||0,a=i(r),s=Number(n),l=a.getDay(),d=s%7,_=(d+7)%7,g=(_<u?7:0)+s-l;return e(a,g)}return lo=t,lo}var co,_c;function Cy(){if(_c)return co;_c=1;var i=ge();function e(t,r){var n=i(t),o=Number(r);return n.setMonth(0),n.setDate(o),n}return co=e,co}var ho,vc;function ky(){if(vc)return ho;vc=1;var i=ge();function e(t,r){var n=i(t),o=Number(r);return n.setHours(o),n}return ho=e,ho}var po,bc;function qy(){if(bc)return po;bc=1;var i=ge(),e=$t(),t=Xf();function r(n,o){var u=i(n),a=Number(o),s=t(u),l=a-s;return e(u,l)}return po=r,po}var mo,wc;function My(){if(wc)return mo;wc=1;var i=ge(),e=Ur();function t(r,n){var o=i(r),u=Number(n),a=e(o)-u;return o.setDate(o.getDate()-a*7),o}return mo=t,mo}var yo,Sc;function Py(){if(Sc)return yo;Sc=1;var i=ge();function e(t,r){var n=i(t),o=Number(r);return n.setMilliseconds(o),n}return yo=e,yo}var go,Ec;function By(){if(Ec)return go;Ec=1;var i=ge();function e(t,r){var n=i(t),o=Number(r);return n.setMinutes(o),n}return go=e,go}var _o,Ic;function Tc(){if(Ic)return _o;Ic=1;var i=ge(),e=hn();function t(r,n){var o=i(r),u=Number(n),a=o.getFullYear(),s=o.getDate(),l=new Date(0);l.setFullYear(a,u,15),l.setHours(0,0,0,0);var d=e(l);return o.setMonth(u,Math.min(s,d)),o}return _o=t,_o}var vo,Rc;function Dy(){if(Rc)return vo;Rc=1;var i=ge(),e=Tc();function t(r,n){var o=i(r),u=Number(n),a=Math.floor(o.getMonth()/3)+1,s=u-a;return e(o,o.getMonth()+s*3)}return vo=t,vo}var bo,Ac;function Ly(){if(Ac)return bo;Ac=1;var i=ge();function e(t,r){var n=i(t),o=Number(r);return n.setSeconds(o),n}return bo=e,bo}var wo,Oc;function Fy(){if(Oc)return wo;Oc=1;var i=ge();function e(t,r){var n=i(t),o=Number(r);return n.setFullYear(o),n}return wo=e,wo}var So,xc;function Uy(){if(xc)return So;xc=1;var i=ge();function e(t){var r=i(t);return r.setDate(1),r.setHours(0,0,0,0),r}return So=e,So}var Eo,Cc;function Ny(){if(Cc)return Eo;Cc=1;var i=bt();function e(){return i(new Date)}return Eo=e,Eo}var Io,kc;function jy(){if(kc)return Io;kc=1;function i(){var e=new Date,t=e.getFullYear(),r=e.getMonth(),n=e.getDate(),o=new Date(0);return o.setFullYear(t,r,n+1),o.setHours(0,0,0,0),o}return Io=i,Io}var To,qc;function $y(){if(qc)return To;qc=1;function i(){var e=new Date,t=e.getFullYear(),r=e.getMonth(),n=e.getDate(),o=new Date(0);return o.setFullYear(t,r,n-1),o.setHours(0,0,0,0),o}return To=i,To}var Ro,Mc;function Hy(){if(Mc)return Ro;Mc=1;var i=$t();function e(t,r){var n=Number(r);return i(t,-n)}return Ro=e,Ro}var Ao,Pc;function Wy(){if(Pc)return Ao;Pc=1;var i=Hu();function e(t,r){var n=Number(r);return i(t,-n)}return Ao=e,Ao}var Oo,Bc;function Yy(){if(Bc)return Oo;Bc=1;var i=Ht();function e(t,r){var n=Number(r);return i(t,-n)}return Oo=e,Oo}var xo,Dc;function Gy(){if(Dc)return xo;Dc=1;var i=Ku();function e(t,r){var n=Number(r);return i(t,-n)}return xo=e,xo}var Co,Lc;function zy(){if(Lc)return Co;Lc=1;var i=tr();function e(t,r){var n=Number(r);return i(t,-n)}return Co=e,Co}var ko,Fc;function Vy(){if(Fc)return ko;Fc=1;var i=Zu();function e(t,r){var n=Number(r);return i(t,-n)}return ko=e,ko}var qo,Uc;function Ky(){if(Uc)return qo;Uc=1;var i=tf();function e(t,r){var n=Number(r);return i(t,-n)}return qo=e,qo}var Mo,Nc;function Qy(){if(Nc)return Mo;Nc=1;var i=gn();function e(t,r){var n=Number(r);return i(t,-n)}return Mo=e,Mo}var Po,jc;function Jy(){if(jc)return Po;jc=1;var i=of();function e(t,r){var n=Number(r);return i(t,-n)}return Po=e,Po}var Bo,$c;function Xy(){return $c||($c=1,Bo={addDays:$t(),addHours:Hu(),addISOYears:zu(),addMilliseconds:Ht(),addMinutes:Ku(),addMonths:tr(),addQuarters:Zu(),addSeconds:tf(),addWeeks:gn(),addYears:of(),areRangesOverlapping:lm(),closestIndexTo:cm(),closestTo:hm(),compareAsc:jt(),compareDesc:Vr(),differenceInCalendarDays:Xt(),differenceInCalendarISOWeeks:dm(),differenceInCalendarISOYears:cf(),differenceInCalendarMonths:Mu(),differenceInCalendarQuarters:pm(),differenceInCalendarWeeks:mm(),differenceInCalendarYears:gf(),differenceInDays:vf(),differenceInHours:ym(),differenceInISOYears:gm(),differenceInMilliseconds:er(),differenceInMinutes:_m(),differenceInMonths:tn(),differenceInQuarters:vm(),differenceInSeconds:Jr(),differenceInWeeks:bm(),differenceInYears:wm(),distanceInWords:Lu(),distanceInWordsStrict:Sm(),distanceInWordsToNow:Uu(),eachDay:Em(),endOfDay:Un(),endOfHour:Im(),endOfISOWeek:Tm(),endOfISOYear:Rm(),endOfMinute:Am(),endOfMonth:Ff(),endOfQuarter:Om(),endOfSecond:xm(),endOfToday:Cm(),endOfTomorrow:km(),endOfWeek:Mf(),endOfYear:qm(),endOfYesterday:Mm(),format:Ou(),getDate:Pm(),getDay:Bm(),getDayOfYear:mu(),getDaysInMonth:hn(),getDaysInYear:Dm(),getHours:Lm(),getISODay:Xf(),getISOWeek:Ur(),getISOWeeksInYear:Fm(),getISOYear:St(),getMilliseconds:Um(),getMinutes:Nm(),getMonth:jm(),getOverlappingDaysInRanges:$m(),getQuarter:df(),getSeconds:Hm(),getTime:Wm(),getYear:Ym(),isAfter:Gm(),isBefore:zm(),isDate:Or(),isEqual:Vm(),isFirstDayOfMonth:Km(),isFriday:Qm(),isFuture:Jm(),isLastDayOfMonth:Xm(),isLeapYear:Vf(),isMonday:Zm(),isPast:ey(),isSameDay:ty(),isSameHour:bl(),isSameISOWeek:El(),isSameISOYear:Tl(),isSameMinute:xl(),isSameMonth:kl(),isSameQuarter:Bl(),isSameSecond:Ul(),isSameWeek:Ti(),isSameYear:jl(),isSaturday:ry(),isSunday:ny(),isThisHour:iy(),isThisISOWeek:oy(),isThisISOYear:sy(),isThisMinute:ay(),isThisMonth:uy(),isThisQuarter:fy(),isThisSecond:ly(),isThisWeek:cy(),isThisYear:hy(),isThursday:dy(),isToday:py(),isTomorrow:my(),isTuesday:yy(),isValid:Su(),isWednesday:gy(),isWeekend:_y(),isWithinRange:vy(),isYesterday:by(),lastDayOfISOWeek:wy(),lastDayOfISOYear:Sy(),lastDayOfMonth:Ey(),lastDayOfQuarter:Iy(),lastDayOfWeek:uc(),lastDayOfYear:Ty(),max:Ry(),min:Ay(),parse:ge(),setDate:Oy(),setDay:xy(),setDayOfYear:Cy(),setHours:ky(),setISODay:qy(),setISOWeek:My(),setISOYear:Yu(),setMilliseconds:Py(),setMinutes:By(),setMonth:Tc(),setQuarter:Dy(),setSeconds:Ly(),setYear:Fy(),startOfDay:bt(),startOfHour:_l(),startOfISOWeek:wt(),startOfISOYear:Nt(),startOfMinute:Al(),startOfMonth:Uy(),startOfQuarter:Ml(),startOfSecond:Ll(),startOfToday:Ny(),startOfTomorrow:jy(),startOfWeek:Zt(),startOfYear:cu(),startOfYesterday:$y(),subDays:Hy(),subHours:Wy(),subISOYears:Sf(),subMilliseconds:Yy(),subMinutes:Gy(),subMonths:zy(),subQuarters:Vy(),subSeconds:Ky(),subWeeks:Qy(),subYears:Jy()}),Bo}var Hc=Xy();function xt(i){return i.replace(/<[^>]*\/?>([\s\S]*)?<\/.*?>/gi,function(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")})}class Zy{constructor(e){this.roomAdapter=e,this.name=null,this.emails=[],this.options={}}withName(e){return this.name=e,this}withOptions(e){return this.options=e,this}addParticipants(...e){return this.emails=this.emails.filter(t=>e.indexOf(t)===-1).concat(...e),this}create(){const e=this.name,t=this.emails,r=this.options;return this.roomAdapter.createRoom(e,t,{avatarURL:r.avatarURL},r)}}function eg(i,e){let t=null;return function(...r){t!=null&&clearTimeout(t),t=setTimeout(()=>{i(...r),t=null},e)}}class pt{constructor(e){this.id=e.id,this.before_id=e.comment_before_id,this.message=xt(e.message),this.username_as=e.username_as||e.username,this.username_real=e.username_real||e.email,this.email=this.username_real,this.user_extras=e.user_extras,this.date=Hc.format(e.timestamp,"YYYY-MM-DD"),this.time=Hc.format(e.timestamp,"HH:mm"),this.timestamp=e.timestamp,this.unique_id=e.unique_temp_id||e.unique_id,this.unique_temp_id=e.unique_temp_id||e.unique_id,this.avatar=e.user_avatar_url,this.room_id=e.room_id,this.isChannel=e.is_public_channel,this.unix_timestamp=e.unix_timestamp,this.unix_nano_timestamp=e.unix_nano_timestamp,this.extras=e.extras,this.is_deleted=e.is_deleted,this.isPending=!1,this.isFailed=!1,this.isDelivered=!1,this.isRead=!1,this.isSent=!1,this.attachment=null,this.payload=e.payload,this.status=e.status,e.type==="reply"&&(e.payload.replied_comment_message=xt(e.payload.replied_comment_message),e.payload.text=xt(e.payload.text)),this.type=e.type,this.subtype=e.type==="custom"?e.payload.type:null,e.status==="sent"?this.markAsSent():e.status==="delivered"?this.markAsDelivered():e.status==="read"&&this.markAsRead()}isAttachment(e){return e.substring(0,6)==="[file]"}isImageAttachment(e){return this.isAttachment(e)&&e.match(/\.(jpg|jpeg|gif|png)/i)!=null}attachUniqueId(e){this.unique_id=e}getAttachmentURI(e){if(!this.isAttachment(e))return;const t=e.length,r=6,n=t-7;return e.substring(r,n).trim()}setAttachment(e){this.attachment=e}markAsPending(){this.isPending=!0,this.isDelivered=!1,this.status="pending"}markAsSent(){this.isSent=!0,this.isPending=!1,this.isFailed=!1,this.status="sent"}markAsDelivered({actor:e,activeActorId:t}={}){e!==t&&(this.isRead||this.status==="read"||(this.isSent=!0,this.isRead=!1,this.isDelivered=!0,this.status="delivered"))}markAsRead({actor:e,activeActorId:t}={}){e!==t&&(this.isPending=!1,this.isSent=!0,this.isDelivered=!0,this.isRead=!0,this.status="read")}markAsFailed(){this.isFailed=!0,this.isPending=!1,this.isStatus="failed"}update(e){this.id=e.id,this.before_id=e.comment_before_id,this.message=xt(e.message),e.payload&&(this.payload=e.payload),e.status&&(this.status=e.status),e.type==="reply"&&(this.payload.replied_comment_message=xt(e.payload.replied_comment_message),this.payload.text=xt(e.payload.text)),e.status==="sent"?this.markAsSent():e.status==="delivered"?this.markAsDelivered():e.status==="read"&&this.markAsRead()}}class rr{constructor(e){this.id=e.id,this.last_comment_id=e.last_comment_id,this.last_comment_message=e.last_comment_message,this.last_comment_message_created_at=e.last_comment_message_created_at,this.last_comment_topic_title=e.last_comment_topic_title,this.avatar=e.room_avatar||e.avatarURL||e.avatar_url,this.name=e.room_name,this.room_type=e.room_type||e.chat_type,this.secret_code=e.secret_code,this.participants=e.participants,this.options=e.options,this.topics=[],this.last_comment=e.last_comment,this.comments=[],this.count_notif=e.unread_count,this.isLoaded=!1,this.custom_title=null,this.custom_subtitle=null,this.options=e.options,this.unique_id=e.unique_id,this.isChannel=e.is_public_channel,this.participantNumber=e.room_total_participants,e.comments&&this.receiveComments(e.comments)}isCurrentlySelected(e){return this.id===e.id}getParticipantCount(){return this.participants==null?this.participantNumber:this.participants.length}setTitle(e){this.custom_title=e}setSubTitle(e){this.custom_subtitle=e}receiveComment(e){if(e.room_id!==this.id)return;const t=this.comments.find(r=>r.unique_id===e.unique_id);t?(t.id=e.id,t.message=e.message,t.date=e.date,t.time=e.time,t.unix_timestamp=e.unix_timestamp):this.comments=[...this.comments,e]}receiveComments(e){e.forEach(t=>{this.receiveComment(new pt(t))})}getParticipant(e){return this.participants.find(t=>t.email===e)||null}addParticipant(e){this.getParticipant(e.email)||this.participants.push(e)}}class Do{constructor({baseURL:e,AppId:t,userId:r,version:n,getCustomHeader:o,expiredTokenAdapterGetter:u}){this.baseURL=e,this.token=null,this.userId=r,this.AppId=t,this.version=n,this.getCustomHeader=o,this._expiredTokenAdapterGetter=u}setToken(e){this.token=e}get(e,t={},r){return this._retryHelper(()=>ke(this,null,function*(){var n=st.get(`${this.baseURL}/${e}`);return r&&r.baseURL&&(n=st.get(`${r.baseURL}/${e}`)),n=this.setupHeaders(n,t),n}))}get_request(e){return this._retryHelper(()=>ke(this,null,function*(){let t=st.get(`${this.baseURL}/${e}`);return t=this.setupHeaders(t,{}),t}))}post(e,t={},r={}){return this._retryHelper(()=>ke(this,null,function*(){let n=st.post(`${this.baseURL}/${e}`);return n=this.setupHeaders(n,r),n.send(t).set("Content-Type","application/x-www-form-urlencoded")}))}post_json(e,t={},r={}){return this._retryHelper(()=>ke(this,null,function*(){let n=st.post(`${this.baseURL}/${e}`);return n=this.setupHeaders(n,r),n.send(t),n}))}put(e,t={},r={}){return this._retryHelper(()=>ke(this,null,function*(){let n=st.put(`${this.baseURL}/${e}`);return n=this.setupHeaders(n,r),n.send(t).set("Content-Type","application/x-www-form-urlencoded")}))}patch(e,t={},r={}){return this._retryHelper(()=>ke(this,null,function*(){let n=st.patch(`${this.baseURL}/${e}`);return n=this.setupHeaders(n,r),n.send(t).set("Content-Type","application/x-www-form-urlencoded")}))}del(e,t={},r={}){return this._retryHelper(()=>ke(this,null,function*(){let n=st.del(`${this.baseURL}/${e}`);return n=this.setupHeaders(n,r),n.send(t).set("Content-Type","application/json")}))}setupHeaders(e,t={}){if(e.set("QISCUS-SDK-PLATFORM","javascript"),this.AppId!=null&&e.set("QISCUS-SDK-APP-ID",`${this.AppId}`),this.userId!=null&&e.set("QISCUS-SDK-USER-ID",`${this.userId}`),this.token!=null&&e.set("QISCUS-SDK-TOKEN",`${this.token}`),this.version!=null&&e.set("QISCUS-SDK-VERSION",`${this.version}`),this.getCustomHeader!=null){const r=this.getCustomHeader();Object.keys(r).filter(n=>r[n]!=null).forEach(n=>{e.set(n,r[n])})}if(Object.keys(t).length<1)return e;for(let r in t)t.hasOwnProperty(r)&&e.set(r,t[r]);return e}_retryHelper(e){return ke(this,null,function*(){var t,r,n,o;try{return yield e()}catch(u){const a=(t=u==null?void 0:u.response)==null?void 0:t.status,s=(r=u==null?void 0:u.response)==null?void 0:r.body;if(a===403&&((o=(n=s.error)==null?void 0:n.message)==null?void 0:o.toLowerCase())==="unauthorized. token is expired")return yield this._expiredTokenAdapterGetter().refreshAuthToken(),yield e();throw u}})}}class tg{constructor(e){this.HTTPAdapter=e,this.refreshToken=null,this.userId=null,this.autoRefreshToken=!1}getNonce(){return this.HTTPAdapter.post("api/v2/sdk/auth/nonce").then(e=>e.body.results)}loginOrRegister(e){return this.HTTPAdapter.post("api/v2/sdk/login_or_register",e).then(t=>{if(t.body.status!==200)return Promise.reject(t);let r=t.body.results;return this.userId=r.user.email,this.refreshToken=r.user.refresh_token,r})}verifyIdentityToken(e){return this.HTTPAdapter.post("api/v2/sdk/auth/verify_identity_token",{identity_token:e}).then(t=>{let r=t.body.results;return this.userId=r.user.email,this.refreshToken=r.user.refresh_token,r})}refreshAuthToken(){return this.HTTPAdapter.post("api/v2/sdk/refresh_user_token",{user_id:this.userId,refresh_token:this.refreshToken}).then(e=>{let t=e.body.results;return this.refreshToken=t.refresh_token,this.HTTPAdapter.token=t.token,t})}expiredAuthToken(){return this.HTTPAdapter.post("api/v2/sdk/expire_user_token",{user_id:this.userId}).then(e=>e.body.results)}}var Lo,Wc;function rg(){if(Wc)return Lo;Wc=1;var i="Expected a function",e=NaN,t="[object Symbol]",r=/^\s+|\s+$/g,n=/^[-+]0x[0-9a-f]+$/i,o=/^0b[01]+$/i,u=/^0o[0-7]+$/i,a=parseInt,s=typeof xe=="object"&&xe&&xe.Object===Object&&xe,l=typeof self=="object"&&self&&self.Object===Object&&self,d=s||l||Function("return this")(),_=Object.prototype,g=_.toString,E=Math.max,w=Math.min,q=function(){return d.Date.now()};function k(p,v,I){var B,H,V,P,ce,oe,ne=0,se=!1,he=!1,J=!0;if(typeof p!="function")throw new TypeError(i);v=h(v)||0,R(I)&&(se=!!I.leading,he="maxWait"in I,V=he?E(h(I.maxWait)||0,v):V,J="trailing"in I?!!I.trailing:J);function me($){var z=B,Y=H;return B=H=void 0,ne=$,P=p.apply(Y,z),P}function de($){return ne=$,ce=setTimeout(re,v),se?me($):P}function be($){var z=$-oe,Y=$-ne,T=v-z;return he?w(T,V-Y):T}function G($){var z=$-oe,Y=$-ne;return oe===void 0||z>=v||z<0||he&&Y>=V}function re(){var $=q();if(G($))return j($);ce=setTimeout(re,be($))}function j($){return ce=void 0,J&&B?me($):(B=H=void 0,P)}function L(){ce!==void 0&&clearTimeout(ce),ne=0,B=oe=H=ce=void 0}function M(){return ce===void 0?P:j(q())}function D(){var $=q(),z=G($);if(B=arguments,H=this,oe=$,z){if(ce===void 0)return de(oe);if(he)return ce=setTimeout(re,v),me(oe)}return ce===void 0&&(ce=setTimeout(re,v)),P}return D.cancel=L,D.flush=M,D}function A(p,v,I){var B=!0,H=!0;if(typeof p!="function")throw new TypeError(i);return R(I)&&(B="leading"in I?!!I.leading:B,H="trailing"in I?!!I.trailing:H),k(p,v,{leading:B,maxWait:v,trailing:H})}function R(p){var v=typeof p;return!!p&&(v=="object"||v=="function")}function S(p){return!!p&&typeof p=="object"}function b(p){return typeof p=="symbol"||S(p)&&g.call(p)==t}function h(p){if(typeof p=="number")return p;if(b(p))return e;if(R(p)){var v=typeof p.valueOf=="function"?p.valueOf():p;p=R(v)?v+"":v}if(typeof p!="string")return p===0?p:+p;p=p.replace(r,"");var I=o.test(p);return I||u.test(p)?a(p.slice(2),I?2:8):n.test(p)?e:+p}return Lo=A,Lo}var ng=rg();const ig=rt(ng);function nr(i){const e={},t=(r,n)=>`${r}=${n}`;return{param(r,n){return e[r]=n,this},build(){const r=Object.keys(e).filter(n=>e[n]!=null).map(n=>Array.isArray(e[n])?e[n].map(o=>t(`${n}[]`,o)).join("&"):t(n,e[n])).join("&");return[i].concat(r).join("?")}}}class og{constructor(e){He(this,"updateCommentStatus",ig((e,t,r)=>{const n={room_id:e};return t&&(n.last_comment_read_id=t),r&&(n.last_comment_received_id=r),this.HTTPAdapter.post("api/v2/sdk/update_comment_status",n)},500));this.HTTPAdapter=e,this.token=e.token}postComment(e,t,r,n,o,u){return this.HTTPAdapter.post_json("api/v2/sdk/post_comment",{comment:t,topic_id:e,unique_temp_id:r,type:n,payload:o,extras:u}).then(a=>a.body.status!==200?Promise.reject(a):Promise.resolve(a.body.results.comment))}loadRoomList(e={}){var r;const t=nr("api/v2/sdk/user_rooms").param("page",e.page).param("show_participants",e.show_participants||!0).param("limit",e.limit).param("show_empty",e.show_empty).param("room_type",(r=e.room_type)!=null?r:"default").build();return this.HTTPAdapter.get(t).then(n=>n.body.status!==200?Promise.reject(n):Promise.resolve(n.body.results.rooms_info))}searchMessages(e){const t={query:e.query||null,room_id:e.room_id||null,last_comment_id:e.last_comment_id||null};return this.HTTPAdapter.post("api/v2/sdk/search_messages",t).then(r=>r.body.results.comments)}updateProfile(e){const t={name:e.name||null,avatar_url:e.avatar_url||null,extras:e.extras?JSON.stringify(e.extras):null};return this.HTTPAdapter.patch("api/v2/sdk/my_profile",t).then(r=>r.body.results.user)}uploadFile(e){const t={file:e};return this.HTTPAdapter.post("api/v2/sdk/upload",t).then(r=>r.body)}getRoomsInfo(e){const t={show_participants:!0,show_removed:!1};return e.room_ids&&(t.room_id=e.room_ids),e.room_unique_ids&&(t.room_unique_id=e.room_unique_ids),e.show_participants&&(t.show_participants=e.show_participants),e.show_removed&&(t.show_removed=e.show_removed),this.HTTPAdapter.post_json("api/v2/sdk/rooms_info",t).then(r=>r.body)}loadComments(e,t){const r=nr("api/v2/sdk/load_comments").param("topic_id",e).param("last_comment_id",t.last_comment_id).param("timestamp",t.timestamp).param("after",t.after).param("limit",t.limit).build();return this.HTTPAdapter.get(r).then(n=>n.status!==200?Promise.reject(n):Promise.resolve(n.body.results.comments))}deleteComment(e,t,r=!0,n=!0){r===!1&&console.warn("Deprecated: delete comment for me will be removed on next release"),n===!1&&console.warn("Deprecated: soft delete will be removed on next release");const o={unique_ids:t,is_delete_for_everyone:r,is_hard_delete:n};return this.HTTPAdapter.del("api/v2/sdk/delete_messages",o).then(u=>u.body)}clearRoomMessages(e){const t={room_channel_ids:e};return this.HTTPAdapter.del("api/v2/sdk/clear_room_messages",t).then(r=>r.body)}getCommentReceiptStatus(e){return this.HTTPAdapter.get(`api/v2/sdk/comment_receipt?comment_id=${e}`).then(t=>t.body)}getBlockedUser(e=1,t=20){const r=`api/v2/sdk/get_blocked_users?page=${e}&limit=${t}`;return this.HTTPAdapter.get(r).then(n=>n.body.status!==200?Promise.reject(n):Promise.resolve(n.body.results.blocked_users))}blockUser(e){if(!e)throw new Error("email is required");let t={user_email:e};return this.HTTPAdapter.post("api/v2/sdk/block_user",t).then(r=>r.body.status!==200?Promise.reject(r):Promise.resolve(r.body.results.user))}unblockUser(e){if(!e)throw new Error("email is required");const t={user_email:e};return this.HTTPAdapter.post("api/v2/sdk/unblock_user",t).then(r=>r.body.status!==200?Promise.reject(r):Promise.resolve(r.body.results.user))}getProfile(){return this.HTTPAdapter.get("api/v2/sdk/my_profile").then(e=>e.body.results.user)}getUserPresences(e){let t={user_ids:e};return this.HTTPAdapter.post_json("api/v2/sdk/users/status",t).then(r=>r.body.status!==200?Promise.reject(r):Promise.resolve(r.body.results.user_status))}updateMessage(e){const t={token:this.token,comment:e.message,unique_id:e.unique_id||e.unique_temp_id};return e.extras!=null&&(t.extras=e.extras),e.payload!=null&&(t.payload=e.payload),this.HTTPAdapter.post_json("api/v2/sdk/update_message",t).then(r=>r.body.results.comment)}}class sg{constructor(e){this.HTTPAdapter=e,this.token=e.token}getOrCreateRoom(e,t,r){let n={emails:e};return r&&(n[r]=r),t&&(n.options=JSON.stringify(t)),this.HTTPAdapter.post("api/v2/sdk/get_or_create_room_with_target",n).then(o=>{if(o.body.status!==200)return Promise.reject(o);const u=o.body.results.room;u.avatar=u.avatar_url,u.comments=o.body.results.comments.reverse();const a=u.participants.find(s=>s.email===e);return u.name=a?a.username:"Room name",Promise.resolve(u)})}getRoomById(e){return this.HTTPAdapter.get(`api/v2/sdk/get_room_by_id?id=${e}`).then(t=>t.body)}getOrCreateRoomByUniqueId(e,t,r){let n={unique_id:e,name:t,avatar_url:r};return this.HTTPAdapter.post("api/v2/sdk/get_or_create_room_with_unique_id",n).then(o=>{if(o.body.status!==200)return Promise.reject(o);const u=o.body.results.room;return u.avatar=u.avatar_url,u.comments=o.body.results.comments.reverse(),u.name=u.room_name,Promise.resolve(u)})}createRoom(e,t,r={},n={}){const o=Object.keys(n).length<=0?null:JSON.stringify(n),u={name:e,"participants[]":t,avatar_url:r.avatarURL,options:o};return this.HTTPAdapter.post("api/v2/sdk/create_room",u).then(a=>{if(a.body.status!==200)return Promise.reject(a);const s=a.body.results.room;return s.comments=a.body.results.comments,Promise.resolve({id:s.id,name:s.room_name,lastCommentId:s.last_comment_id,lastCommentMessage:s.last_comment_message,lastTopicId:s.last_topic_id,avatarURL:s.avatar_url,options:s.options,participants:s.participants.map(l=>({id:l.id,email:l.email,username:l.username,avatarURL:l.avatar_url}))})})}updateRoom(e){if(!e.id)throw new Error("id is required");let t={id:e.id};return e.room_name&&(t.room_name=e.room_name),e.avatar_url&&(t.avatar_url=e.avatar_url),e.options&&(t.options=JSON.stringify(e.options)),this.HTTPAdapter.post("api/v2/sdk/update_room",t).then(r=>r.body.status!==200?Promise.reject(r):Promise.resolve(r.body.results.room))}getTotalUnreadCount(){return this.HTTPAdapter.get("api/v2/sdk/total_unread_count").then(e=>e.body.results.total_unread_count)}getRoomUnreadCount(){return this.HTTPAdapter.get("api/v2/sdk/get_room_unread_count").then(e=>e.body.results.total_unread_count)}addParticipantsToGroup(e,t=[]){if(!e||!t)throw new Error("room_id and emails is required");let r={room_id:e,"emails[]":t};return this.HTTPAdapter.post("api/v2/sdk/add_room_participants",r).then(n=>n.body.status!==200?Promise.reject(n):Promise.resolve(n.body.results.participants_added))}removeParticipantsFromGroup(e,t=[]){if(!e||!t)throw new Error("room_id and emails is required");let r={room_id:e,"emails[]":t};return this.HTTPAdapter.post("api/v2/sdk/remove_room_participants",r).then(n=>n.body.status!==200?Promise.reject(n):Promise.resolve(n.body.results.participants_removed))}}const Wt="match.pattern.catchAll",Yc="match.pattern.OR",ag=Yc.toString(),Gc="match.pattern.AND",ug=Gc.toString(),zc="match.pattern.RANGE",fg=zc.toString(),Vc="match.pattern.REGEXP",lg=Vc.toString(),cg=/\/(.*)\/(.*)/;function Kc(){Error.call(this,"Missing when() catch-all pattern as last match argument, add [when()]: void 0"),"stack"in this||(this.stack=new Error().stack)}Kc.prototype=Object.create(Error.prototype);function hg(...i){const e=i[i.length-1];let t=[];for(let n in e)t.push(Ze.unserialize(n,e[n]));t.sort(function(n,o){return n.position<o.position?-1:1}),Object.getOwnPropertySymbols(e).indexOf(Wt)!==-1&&t.push(Ze.unserialize(Wt,e[Wt]));const r=function(n){const o=t.find(u=>u.match(n));if(!o)throw new Kc;return typeof o.result=="function"?o.result(n):o.result};return i.length===2?r(i[0]):r}function Ze(i){return i===void 0?Wt:i instanceof RegExp?Yt([Vc.toString(),i.toString()]):Yt(i)}Ze.__uid=0;function Yt(i){return JSON.stringify([Ze.__uid++,i])}function dg(i){return JSON.parse(i)}function pg(){return!0}function mg(i){if(Array.isArray(i)){if(i[0]===ag)return i.shift(),function(t){return i[0].some(r=>e(r,t))};if(i[0]===ug)return i.shift(),function(t){return i[0].every(r=>e(r,t))};if(i[0]===fg)return i.shift(),function(t){return i[0]<=t&&t<=i[1]};if(i[0]===lg){const t=cg.exec(i[1]);return e.bind(null,new RegExp(t[1],t[2]))}}function e(t,r){if(Array.isArray(r))return JSON.stringify(t)===JSON.stringify(r);if(t instanceof RegExp)return t.test(r);if(typeof r=="object"){for(let n in t)if(r[n]!==t[n])return!1;return!0}return t===r}return t=>e(i,t)}Ze.or=function(...i){return Yt([Yc.toString(),i])},Ze.and=function(...i){return Yt([Gc.toString(),i])},Ze.range=function(i,e){return Yt([zc.toString(),i,e])},Ze.unserialize=function(i,e){if(i===Wt)return{match:pg,result:e,position:1/0};const t=dg(i),r=t[1],n=t[0];return{match:mg(r),result:e,position:n}};function yg(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var Qc={exports:{}},Ke=Qc.exports={},lt,ct;function Fo(){throw new Error("setTimeout has not been defined")}function Uo(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?lt=setTimeout:lt=Fo}catch(i){lt=Fo}try{typeof clearTimeout=="function"?ct=clearTimeout:ct=Uo}catch(i){ct=Uo}})();function Jc(i){if(lt===setTimeout)return setTimeout(i,0);if((lt===Fo||!lt)&&setTimeout)return lt=setTimeout,setTimeout(i,0);try{return lt(i,0)}catch(e){try{return lt.call(null,i,0)}catch(t){return lt.call(this,i,0)}}}function gg(i){if(ct===clearTimeout)return clearTimeout(i);if((ct===Uo||!ct)&&clearTimeout)return ct=clearTimeout,clearTimeout(i);try{return ct(i)}catch(e){try{return ct.call(null,i)}catch(t){return ct.call(this,i)}}}var mt=[],Ct=!1,Et,ir=-1;function _g(){!Ct||!Et||(Ct=!1,Et.length?mt=Et.concat(mt):ir=-1,mt.length&&Xc())}function Xc(){if(!Ct){var i=Jc(_g);Ct=!0;for(var e=mt.length;e;){for(Et=mt,mt=[];++ir<e;)Et&&Et[ir].run();ir=-1,e=mt.length}Et=null,Ct=!1,gg(i)}}Ke.nextTick=function(i){var e=new Array(arguments.length-1);if(arguments.length>1)for(var t=1;t<arguments.length;t++)e[t-1]=arguments[t];mt.push(new Zc(i,e)),mt.length===1&&!Ct&&Jc(Xc)};function Zc(i,e){this.fun=i,this.array=e}Zc.prototype.run=function(){this.fun.apply(null,this.array)},Ke.title="browser",Ke.browser=!0,Ke.env={},Ke.argv=[],Ke.version="",Ke.versions={};function yt(){}Ke.on=yt,Ke.addListener=yt,Ke.once=yt,Ke.off=yt,Ke.removeListener=yt,Ke.removeAllListeners=yt,Ke.emit=yt,Ke.prependListener=yt,Ke.prependOnceListener=yt,Ke.listeners=function(i){return[]},Ke.binding=function(i){throw new Error("process.binding is not supported")},Ke.cwd=function(){return"/"},Ke.chdir=function(i){throw new Error("process.chdir is not supported")},Ke.umask=function(){return 0};var vg=Qc.exports;const Re=yg(vg);var kt={exports:{}},or={exports:{}},eh;function Gt(){if(eh)return or.exports;eh=1;var i=typeof Reflect=="object"?Reflect:null,e=i&&typeof i.apply=="function"?i.apply:function(h,p,v){return Function.prototype.apply.call(h,p,v)},t;i&&typeof i.ownKeys=="function"?t=i.ownKeys:Object.getOwnPropertySymbols?t=function(h){return Object.getOwnPropertyNames(h).concat(Object.getOwnPropertySymbols(h))}:t=function(h){return Object.getOwnPropertyNames(h)};function r(b){console&&console.warn&&console.warn(b)}var n=Number.isNaN||function(h){return h!==h};function o(){o.init.call(this)}or.exports=o,or.exports.once=A,o.EventEmitter=o,o.prototype._events=void 0,o.prototype._eventsCount=0,o.prototype._maxListeners=void 0;var u=10;function a(b){if(typeof b!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof b)}Object.defineProperty(o,"defaultMaxListeners",{enumerable:!0,get:function(){return u},set:function(b){if(typeof b!="number"||b<0||n(b))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+b+".");u=b}}),o.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},o.prototype.setMaxListeners=function(h){if(typeof h!="number"||h<0||n(h))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+h+".");return this._maxListeners=h,this};function s(b){return b._maxListeners===void 0?o.defaultMaxListeners:b._maxListeners}o.prototype.getMaxListeners=function(){return s(this)},o.prototype.emit=function(h){for(var p=[],v=1;v<arguments.length;v++)p.push(arguments[v]);var I=h==="error",B=this._events;if(B!==void 0)I=I&&B.error===void 0;else if(!I)return!1;if(I){var H;if(p.length>0&&(H=p[0]),H instanceof Error)throw H;var V=new Error("Unhandled error."+(H?" ("+H.message+")":""));throw V.context=H,V}var P=B[h];if(P===void 0)return!1;if(typeof P=="function")e(P,this,p);else for(var ce=P.length,oe=w(P,ce),v=0;v<ce;++v)e(oe[v],this,p);return!0};function l(b,h,p,v){var I,B,H;if(a(p),B=b._events,B===void 0?(B=b._events=Object.create(null),b._eventsCount=0):(B.newListener!==void 0&&(b.emit("newListener",h,p.listener?p.listener:p),B=b._events),H=B[h]),H===void 0)H=B[h]=p,++b._eventsCount;else if(typeof H=="function"?H=B[h]=v?[p,H]:[H,p]:v?H.unshift(p):H.push(p),I=s(b),I>0&&H.length>I&&!H.warned){H.warned=!0;var V=new Error("Possible EventEmitter memory leak detected. "+H.length+" "+String(h)+" listeners added. Use emitter.setMaxListeners() to increase limit");V.name="MaxListenersExceededWarning",V.emitter=b,V.type=h,V.count=H.length,r(V)}return b}o.prototype.addListener=function(h,p){return l(this,h,p,!1)},o.prototype.on=o.prototype.addListener,o.prototype.prependListener=function(h,p){return l(this,h,p,!0)};function d(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function _(b,h,p){var v={fired:!1,wrapFn:void 0,target:b,type:h,listener:p},I=d.bind(v);return I.listener=p,v.wrapFn=I,I}o.prototype.once=function(h,p){return a(p),this.on(h,_(this,h,p)),this},o.prototype.prependOnceListener=function(h,p){return a(p),this.prependListener(h,_(this,h,p)),this},o.prototype.removeListener=function(h,p){var v,I,B,H,V;if(a(p),I=this._events,I===void 0)return this;if(v=I[h],v===void 0)return this;if(v===p||v.listener===p)--this._eventsCount===0?this._events=Object.create(null):(delete I[h],I.removeListener&&this.emit("removeListener",h,v.listener||p));else if(typeof v!="function"){for(B=-1,H=v.length-1;H>=0;H--)if(v[H]===p||v[H].listener===p){V=v[H].listener,B=H;break}if(B<0)return this;B===0?v.shift():q(v,B),v.length===1&&(I[h]=v[0]),I.removeListener!==void 0&&this.emit("removeListener",h,V||p)}return this},o.prototype.off=o.prototype.removeListener,o.prototype.removeAllListeners=function(h){var p,v,I;if(v=this._events,v===void 0)return this;if(v.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):v[h]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete v[h]),this;if(arguments.length===0){var B=Object.keys(v),H;for(I=0;I<B.length;++I)H=B[I],H!=="removeListener"&&this.removeAllListeners(H);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(p=v[h],typeof p=="function")this.removeListener(h,p);else if(p!==void 0)for(I=p.length-1;I>=0;I--)this.removeListener(h,p[I]);return this};function g(b,h,p){var v=b._events;if(v===void 0)return[];var I=v[h];return I===void 0?[]:typeof I=="function"?p?[I.listener||I]:[I]:p?k(I):w(I,I.length)}o.prototype.listeners=function(h){return g(this,h,!0)},o.prototype.rawListeners=function(h){return g(this,h,!1)},o.listenerCount=function(b,h){return typeof b.listenerCount=="function"?b.listenerCount(h):E.call(b,h)},o.prototype.listenerCount=E;function E(b){var h=this._events;if(h!==void 0){var p=h[b];if(typeof p=="function")return 1;if(p!==void 0)return p.length}return 0}o.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]};function w(b,h){for(var p=new Array(h),v=0;v<h;++v)p[v]=b[v];return p}function q(b,h){for(;h+1<b.length;h++)b[h]=b[h+1];b.pop()}function k(b){for(var h=new Array(b.length),p=0;p<h.length;++p)h[p]=b[p].listener||b[p];return h}function A(b,h){return new Promise(function(p,v){function I(H){b.removeListener(h,B),v(H)}function B(){typeof b.removeListener=="function"&&b.removeListener("error",I),p([].slice.call(arguments))}S(b,h,B,{once:!0}),h!=="error"&&R(b,I,{once:!0})})}function R(b,h,p){typeof b.on=="function"&&S(b,"error",h,p)}function S(b,h,p,v){if(typeof b.on=="function")v.once?b.once(h,p):b.on(h,p);else if(typeof b.addEventListener=="function")b.addEventListener(h,function I(B){v.once&&b.removeEventListener(h,I),p(B)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof b)}return or.exports}var No,th;function jo(){if(th)return No;th=1,No=e;var i=Object.prototype.hasOwnProperty;function e(){for(var t={},r=0;r<arguments.length;r++){var n=arguments[r];for(var o in n)i.call(n,o)&&(t[o]=n[o])}return t}return No}var sr={exports:{}},$o,rh;function nh(){return rh||(rh=1,$o=Gt().EventEmitter),$o}var Ho={},ih;function zt(){return ih||(ih=1,(function(i){Object.defineProperties(i,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});var e={},t={};t.byteLength=d,t.toByteArray=g,t.fromByteArray=q;for(var r=[],n=[],o=typeof Uint8Array!="undefined"?Uint8Array:Array,u="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0,s=u.length;a<s;++a)r[a]=u[a],n[u.charCodeAt(a)]=a;n[45]=62,n[95]=63;function l(R){var S=R.length;if(S%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var b=R.indexOf("=");b===-1&&(b=S);var h=b===S?0:4-b%4;return[b,h]}function d(R){var S=l(R),b=S[0],h=S[1];return(b+h)*3/4-h}function _(R,S,b){return(S+b)*3/4-b}function g(R){var S,b=l(R),h=b[0],p=b[1],v=new o(_(R,h,p)),I=0,B=p>0?h-4:h,H;for(H=0;H<B;H+=4)S=n[R.charCodeAt(H)]<<18|n[R.charCodeAt(H+1)]<<12|n[R.charCodeAt(H+2)]<<6|n[R.charCodeAt(H+3)],v[I++]=S>>16&255,v[I++]=S>>8&255,v[I++]=S&255;return p===2&&(S=n[R.charCodeAt(H)]<<2|n[R.charCodeAt(H+1)]>>4,v[I++]=S&255),p===1&&(S=n[R.charCodeAt(H)]<<10|n[R.charCodeAt(H+1)]<<4|n[R.charCodeAt(H+2)]>>2,v[I++]=S>>8&255,v[I++]=S&255),v}function E(R){return r[R>>18&63]+r[R>>12&63]+r[R>>6&63]+r[R&63]}function w(R,S,b){for(var h,p=[],v=S;v<b;v+=3)h=(R[v]<<16&16711680)+(R[v+1]<<8&65280)+(R[v+2]&255),p.push(E(h));return p.join("")}function q(R){for(var S,b=R.length,h=b%3,p=[],v=16383,I=0,B=b-h;I<B;I+=v)p.push(w(R,I,I+v>B?B:I+v));return h===1?(S=R[b-1],p.push(r[S>>2]+r[S<<4&63]+"==")):h===2&&(S=(R[b-2]<<8)+R[b-1],p.push(r[S>>10]+r[S>>4&63]+r[S<<2&63]+"=")),p.join("")}var k={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */k.read=function(R,S,b,h,p){var v,I,B=p*8-h-1,H=(1<<B)-1,V=H>>1,P=-7,ce=b?p-1:0,oe=b?-1:1,ne=R[S+ce];for(ce+=oe,v=ne&(1<<-P)-1,ne>>=-P,P+=B;P>0;v=v*256+R[S+ce],ce+=oe,P-=8);for(I=v&(1<<-P)-1,v>>=-P,P+=h;P>0;I=I*256+R[S+ce],ce+=oe,P-=8);if(v===0)v=1-V;else{if(v===H)return I?NaN:(ne?-1:1)*(1/0);I=I+Math.pow(2,h),v=v-V}return(ne?-1:1)*I*Math.pow(2,v-h)},k.write=function(R,S,b,h,p,v){var I,B,H,V=v*8-p-1,P=(1<<V)-1,ce=P>>1,oe=p===23?Math.pow(2,-24)-Math.pow(2,-77):0,ne=h?0:v-1,se=h?1:-1,he=S<0||S===0&&1/S<0?1:0;for(S=Math.abs(S),isNaN(S)||S===1/0?(B=isNaN(S)?1:0,I=P):(I=Math.floor(Math.log(S)/Math.LN2),S*(H=Math.pow(2,-I))<1&&(I--,H*=2),I+ce>=1?S+=oe/H:S+=oe*Math.pow(2,1-ce),S*H>=2&&(I++,H/=2),I+ce>=P?(B=0,I=P):I+ce>=1?(B=(S*H-1)*Math.pow(2,p),I=I+ce):(B=S*Math.pow(2,ce-1)*Math.pow(2,p),I=0));p>=8;R[b+ne]=B&255,ne+=se,B/=256,p-=8);for(I=I<<p|B,V+=p;V>0;R[b+ne]=I&255,ne+=se,I/=256,V-=8);R[b+ne-se]|=he*128};/*!
3
3
  * The buffer module from node.js, for the browser.
4
4
  *
@@ -23,5 +23,5 @@ Possible causes: the network is offline, Origin is not allowed by Access-Control
23
23
  `+Z.prev+Z.base;return Ee+I.call(N,","+Ee)+`
24
24
  `+Z.prev}function te(N,Z){var Ee=D(N),Ae=[];if(Ee){Ae.length=N.length;for(var _e=0;_e<N.length;_e++)Ae[_e]=Se(N,_e)?Z(N[_e],N):""}var ve=typeof P=="function"?P(N):[],Ve;if(oe){Ve={};for(var Ue=0;Ue<ve.length;Ue++)Ve["$"+ve[Ue]]=ve[Ue]}for(var Ne in N)Se(N,Ne)&&(Ee&&String(Number(Ne))===Ne&&Ne<N.length||oe&&Ve["$"+Ne]instanceof Symbol||(p.call(/[^\w$]/,Ne)?Ae.push(Z(Ne,N)+": "+Z(N[Ne],N)):Ae.push(Ne+": "+Z(N[Ne],N))));if(typeof P=="function")for(var ot=0;ot<ve.length;ot++)se.call(N,ve[ot])&&Ae.push("["+Z(ve[ot])+"]: "+Z(N[ve[ot]],N));return Ae}return Ra}var Aa,fp;function q_(){if(fp)return Aa;fp=1;var i=yr(),e=gt(),t=function(a,s,l){for(var d=a,_;(_=d.next)!=null;d=_)if(_.key===s)return d.next=_.next,l||(_.next=a.next,a.next=_),_},r=function(a,s){if(a){var l=t(a,s);return l&&l.value}},n=function(a,s,l){var d=t(a,s);d?d.value=l:a.next={key:s,next:a.next,value:l}},o=function(a,s){return a?!!t(a,s):!1},u=function(a,s){if(a)return t(a,s,!0)};return Aa=function(){var s,l={assert:function(d){if(!l.has(d))throw new e("Side channel does not contain "+i(d))},delete:function(d){var _=u(s,d);return _&&s&&!s.next&&(s=void 0),!!_},get:function(d){return r(s,d)},has:function(d){return o(s,d)},set:function(d,_){s||(s={next:void 0}),n(s,d,_)}};return l},Aa}var Oa,lp;function cp(){if(lp)return Oa;lp=1;var i=fr(),e=It(),t=yr(),r=gt(),n=i("%Map%",!0),o=e("Map.prototype.get",!0),u=e("Map.prototype.set",!0),a=e("Map.prototype.has",!0),s=e("Map.prototype.delete",!0),l=e("Map.prototype.size",!0);return Oa=!!n&&function(){var _,g={assert:function(E){if(!g.has(E))throw new r("Side channel does not contain "+t(E))},delete:function(E){if(_){var w=s(_,E);return l(_)===0&&(_=void 0),w}return!1},get:function(E){if(_)return o(_,E)},has:function(E){return _?a(_,E):!1},set:function(E,w){_||(_=new n),u(_,E,w)}};return g},Oa}var xa,hp;function M_(){if(hp)return xa;hp=1;var i=fr(),e=It(),t=yr(),r=cp(),n=gt(),o=i("%WeakMap%",!0),u=e("WeakMap.prototype.get",!0),a=e("WeakMap.prototype.set",!0),s=e("WeakMap.prototype.has",!0),l=e("WeakMap.prototype.delete",!0);return xa=o?function(){var _,g,E={assert:function(w){if(!E.has(w))throw new n("Side channel does not contain "+t(w))},delete:function(w){if(o&&w&&(typeof w=="object"||typeof w=="function")){if(_)return l(_,w)}else if(r&&g)return g.delete(w);return!1},get:function(w){return o&&w&&(typeof w=="object"||typeof w=="function")&&_?u(_,w):g&&g.get(w)},has:function(w){return o&&w&&(typeof w=="object"||typeof w=="function")&&_?s(_,w):!!g&&g.has(w)},set:function(w,q){o&&w&&(typeof w=="object"||typeof w=="function")?(_||(_=new o),a(_,w,q)):r&&(g||(g=r()),g.set(w,q))}};return E}:r,xa}var Ca,dp;function pp(){if(dp)return Ca;dp=1;var i=gt(),e=yr(),t=q_(),r=cp(),n=M_(),o=n||r||t;return Ca=function(){var a,s={assert:function(l){if(!s.has(l)){var d=l&&Object(l)===l?"the given object key":e(l);throw new i("Side channel does not contain "+d)}},delete:function(l){return!!a&&a.delete(l)},get:function(l){return a&&a.get(l)},has:function(l){return!!a&&a.has(l)},set:function(l,d){a||(a=o()),a.set(l,d)}};return s},Ca}var ka,mp;function qa(){if(mp)return ka;mp=1;var i=String.prototype.replace,e=/%20/g,t={RFC1738:"RFC1738",RFC3986:"RFC3986"};return ka={default:t.RFC3986,formatters:{RFC1738:function(r){return i.call(r,e,"+")},RFC3986:function(r){return String(r)}},RFC1738:t.RFC1738,RFC3986:t.RFC3986},ka}var Ma,yp;function gp(){if(yp)return Ma;yp=1;var i=qa(),e=pp(),t=Object.prototype.hasOwnProperty,r=Array.isArray,n=e(),o=function(v,I){return n.set(v,I),v},u=function(v){return n.has(v)},a=function(v){return n.get(v)},s=function(v,I){n.set(v,I)},l=(function(){for(var p=[],v=0;v<256;++v)p[p.length]="%"+((v<16?"0":"")+v.toString(16)).toUpperCase();return p})(),d=function(v){for(;v.length>1;){var I=v.pop(),B=I.obj[I.prop];if(r(B)){for(var H=[],V=0;V<B.length;++V)typeof B[V]!="undefined"&&(H[H.length]=B[V]);I.obj[I.prop]=H}}},_=function(v,I){for(var B=I&&I.plainObjects?{__proto__:null}:{},H=0;H<v.length;++H)typeof v[H]!="undefined"&&(B[H]=v[H]);return B},g=function p(v,I,B){if(!I)return v;if(typeof I!="object"&&typeof I!="function"){if(r(v)){var H=v.length;if(B&&typeof B.arrayLimit=="number"&&H>B.arrayLimit)return o(_(v.concat(I),B),H);v[H]=I}else if(v&&typeof v=="object")if(u(v)){var V=a(v)+1;v[V]=I,s(v,V)}else{if(B&&B.strictMerge)return[v,I];(B&&(B.plainObjects||B.allowPrototypes)||!t.call(Object.prototype,I))&&(v[I]=!0)}else return[v,I];return v}if(!v||typeof v!="object"){if(u(I)){for(var P=Object.keys(I),ce=B&&B.plainObjects?{__proto__:null,0:v}:{0:v},oe=0;oe<P.length;oe++){var ne=parseInt(P[oe],10);ce[ne+1]=I[P[oe]]}return o(ce,a(I)+1)}var se=[v].concat(I);return B&&typeof B.arrayLimit=="number"&&se.length>B.arrayLimit?o(_(se,B),se.length-1):se}var he=v;return r(v)&&!r(I)&&(he=_(v,B)),r(v)&&r(I)?(I.forEach(function(J,me){if(t.call(v,me)){var de=v[me];de&&typeof de=="object"&&J&&typeof J=="object"?v[me]=p(de,J,B):v[v.length]=J}else v[me]=J}),v):Object.keys(I).reduce(function(J,me){var de=I[me];if(t.call(J,me)?J[me]=p(J[me],de,B):J[me]=de,u(I)&&!u(J)&&o(J,a(I)),u(J)){var be=parseInt(me,10);String(be)===me&&be>=0&&be>a(J)&&s(J,be)}return J},he)},E=function(v,I){return Object.keys(I).reduce(function(B,H){return B[H]=I[H],B},v)},w=function(p,v,I){var B=p.replace(/\+/g," ");if(I==="iso-8859-1")return B.replace(/%[0-9a-f]{2}/gi,unescape);try{return decodeURIComponent(B)}catch(H){return B}},q=1024,k=function(v,I,B,H,V){if(v.length===0)return v;var P=v;if(typeof v=="symbol"?P=Symbol.prototype.toString.call(v):typeof v!="string"&&(P=String(v)),B==="iso-8859-1")return escape(P).replace(/%u[0-9a-f]{4}/gi,function(me){return"%26%23"+parseInt(me.slice(2),16)+"%3B"});for(var ce="",oe=0;oe<P.length;oe+=q){for(var ne=P.length>=q?P.slice(oe,oe+q):P,se=[],he=0;he<ne.length;++he){var J=ne.charCodeAt(he);if(J===45||J===46||J===95||J===126||J>=48&&J<=57||J>=65&&J<=90||J>=97&&J<=122||V===i.RFC1738&&(J===40||J===41)){se[se.length]=ne.charAt(he);continue}if(J<128){se[se.length]=l[J];continue}if(J<2048){se[se.length]=l[192|J>>6]+l[128|J&63];continue}if(J<55296||J>=57344){se[se.length]=l[224|J>>12]+l[128|J>>6&63]+l[128|J&63];continue}he+=1,J=65536+((J&1023)<<10|ne.charCodeAt(he)&1023),se[se.length]=l[240|J>>18]+l[128|J>>12&63]+l[128|J>>6&63]+l[128|J&63]}ce+=se.join("")}return ce},A=function(v){for(var I=[{obj:{o:v},prop:"o"}],B=[],H=0;H<I.length;++H)for(var V=I[H],P=V.obj[V.prop],ce=Object.keys(P),oe=0;oe<ce.length;++oe){var ne=ce[oe],se=P[ne];typeof se=="object"&&se!==null&&B.indexOf(se)===-1&&(I[I.length]={obj:P,prop:ne},B[B.length]=se)}return d(I),v},R=function(v){return Object.prototype.toString.call(v)==="[object RegExp]"},S=function(v){return!v||typeof v!="object"?!1:!!(v.constructor&&v.constructor.isBuffer&&v.constructor.isBuffer(v))},b=function(v,I,B,H){if(u(v)){var V=a(v)+1;return v[V]=I,s(v,V),v}var P=[].concat(v,I);return P.length>B?o(_(P,{plainObjects:H}),P.length-1):P},h=function(v,I){if(r(v)){for(var B=[],H=0;H<v.length;H+=1)B[B.length]=I(v[H]);return B}return I(v)};return Ma={arrayToObject:_,assign:E,combine:b,compact:A,decode:w,encode:k,isBuffer:S,isOverflow:u,isRegExp:R,markOverflow:o,maybeMap:h,merge:g},Ma}var Pa,_p;function P_(){if(_p)return Pa;_p=1;var i=pp(),e=gp(),t=qa(),r=Object.prototype.hasOwnProperty,n={brackets:function(k){return k+"[]"},comma:"comma",indices:function(k,A){return k+"["+A+"]"},repeat:function(k){return k}},o=Array.isArray,u=Array.prototype.push,a=function(q,k){u.apply(q,o(k)?k:[k])},s=Date.prototype.toISOString,l=t.default,d={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,commaRoundTrip:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:e.encode,encodeValuesOnly:!1,filter:void 0,format:l,formatter:t.formatters[l],indices:!1,serializeDate:function(k){return s.call(k)},skipNulls:!1,strictNullHandling:!1},_=function(k){return typeof k=="string"||typeof k=="number"||typeof k=="boolean"||typeof k=="symbol"||typeof k=="bigint"},g={},E=function q(k,A,R,S,b,h,p,v,I,B,H,V,P,ce,oe,ne,se,he){for(var J=k,me=he,de=0,be=!1;(me=me.get(g))!==void 0&&!be;){var G=me.get(k);if(de+=1,typeof G!="undefined"){if(G===de)throw new RangeError("Cyclic object value");be=!0}typeof me.get(g)=="undefined"&&(de=0)}if(typeof B=="function"?J=B(A,J):J instanceof Date?J=P(J):R==="comma"&&o(J)&&(J=e.maybeMap(J,function(ye){return ye instanceof Date?P(ye):ye})),J===null){if(h)return oe(I&&!ne?I(A,d.encoder,se,"key",ce):A);J=""}if(_(J)||e.isBuffer(J)){if(I){var re=ne?A:I(A,d.encoder,se,"key",ce);return[oe(re)+"="+oe(I(J,d.encoder,se,"value",ce))]}return[oe(A)+"="+oe(String(J))]}var j=[];if(typeof J=="undefined")return j;var L;if(R==="comma"&&o(J))ne&&I&&(J=e.maybeMap(J,function(ye){return ye==null?ye:I(ye)})),L=[{value:J.length>0?J.join(",")||null:void 0}];else if(o(B))L=B;else{var M=Object.keys(J);L=H?M.sort(H):M}var D=v?String(A).replace(/\./g,"%2E"):String(A),$=S&&o(J)&&J.length===1?D+"[]":D;if(b&&o(J)&&J.length===0)return $+"[]";for(var z=0;z<L.length;++z){var Y=L[z],T=typeof Y=="object"&&Y&&typeof Y.value!="undefined"?Y.value:J[Y];if(!(p&&T===null)){var O=V&&v?String(Y).replace(/\./g,"%2E"):String(Y),ee=o(J)?typeof R=="function"?R($,O):$:$+(V?"."+O:"["+O+"]");he.set(k,de);var ae=i();ae.set(g,he),a(j,q(T,ee,R,S,b,h,p,v,R==="comma"&&ne&&o(J)?null:I,B,H,V,P,ce,oe,ne,se,ae))}}return j},w=function(k){if(!k)return d;if(typeof k.allowEmptyArrays!="undefined"&&typeof k.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof k.encodeDotInKeys!="undefined"&&typeof k.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(k.encoder!==null&&typeof k.encoder!="undefined"&&typeof k.encoder!="function")throw new TypeError("Encoder has to be a function.");var A=k.charset||d.charset;if(typeof k.charset!="undefined"&&k.charset!=="utf-8"&&k.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var R=t.default;if(typeof k.format!="undefined"){if(!r.call(t.formatters,k.format))throw new TypeError("Unknown format option provided.");R=k.format}var S=t.formatters[R],b=d.filter;(typeof k.filter=="function"||o(k.filter))&&(b=k.filter);var h;if(k.arrayFormat in n?h=k.arrayFormat:"indices"in k?h=k.indices?"indices":"repeat":h=d.arrayFormat,"commaRoundTrip"in k&&typeof k.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");var p=typeof k.allowDots=="undefined"?k.encodeDotInKeys===!0?!0:d.allowDots:!!k.allowDots;return{addQueryPrefix:typeof k.addQueryPrefix=="boolean"?k.addQueryPrefix:d.addQueryPrefix,allowDots:p,allowEmptyArrays:typeof k.allowEmptyArrays=="boolean"?!!k.allowEmptyArrays:d.allowEmptyArrays,arrayFormat:h,charset:A,charsetSentinel:typeof k.charsetSentinel=="boolean"?k.charsetSentinel:d.charsetSentinel,commaRoundTrip:!!k.commaRoundTrip,delimiter:typeof k.delimiter=="undefined"?d.delimiter:k.delimiter,encode:typeof k.encode=="boolean"?k.encode:d.encode,encodeDotInKeys:typeof k.encodeDotInKeys=="boolean"?k.encodeDotInKeys:d.encodeDotInKeys,encoder:typeof k.encoder=="function"?k.encoder:d.encoder,encodeValuesOnly:typeof k.encodeValuesOnly=="boolean"?k.encodeValuesOnly:d.encodeValuesOnly,filter:b,format:R,formatter:S,serializeDate:typeof k.serializeDate=="function"?k.serializeDate:d.serializeDate,skipNulls:typeof k.skipNulls=="boolean"?k.skipNulls:d.skipNulls,sort:typeof k.sort=="function"?k.sort:null,strictNullHandling:typeof k.strictNullHandling=="boolean"?k.strictNullHandling:d.strictNullHandling}};return Pa=function(q,k){var A=q,R=w(k),S,b;typeof R.filter=="function"?(b=R.filter,A=b("",A)):o(R.filter)&&(b=R.filter,S=b);var h=[];if(typeof A!="object"||A===null)return"";var p=n[R.arrayFormat],v=p==="comma"&&R.commaRoundTrip;S||(S=Object.keys(A)),R.sort&&S.sort(R.sort);for(var I=i(),B=0;B<S.length;++B){var H=S[B];if(!(typeof H=="undefined"||H===null)){var V=A[H];R.skipNulls&&V===null||a(h,E(V,H,p,v,R.allowEmptyArrays,R.strictNullHandling,R.skipNulls,R.encodeDotInKeys,R.encode?R.encoder:null,R.filter,R.sort,R.allowDots,R.serializeDate,R.format,R.formatter,R.encodeValuesOnly,R.charset,I))}}var P=h.join(R.delimiter),ce=R.addQueryPrefix===!0?"?":"";return R.charsetSentinel&&(R.charset==="iso-8859-1"?ce+="utf8=%26%2310003%3B"+R.delimiter:ce+="utf8=%E2%9C%93"+R.delimiter),P.length>0?ce+P:""},Pa}var Ba,vp;function B_(){if(vp)return Ba;vp=1;var i=gp(),e=Object.prototype.hasOwnProperty,t=Array.isArray,r={allowDots:!1,allowEmptyArrays:!1,allowPrototypes:!1,allowSparse:!1,arrayLimit:20,charset:"utf-8",charsetSentinel:!1,comma:!1,decodeDotInKeys:!1,decoder:i.decode,delimiter:"&",depth:5,duplicates:"combine",ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictDepth:!1,strictMerge:!0,strictNullHandling:!1,throwOnLimitExceeded:!1},n=function(E){return E.replace(/&#(\d+);/g,function(w,q){return String.fromCharCode(parseInt(q,10))})},o=function(E,w,q){if(E&&typeof E=="string"&&w.comma&&E.indexOf(",")>-1)return E.split(",");if(w.throwOnLimitExceeded&&q>=w.arrayLimit)throw new RangeError("Array limit exceeded. Only "+w.arrayLimit+" element"+(w.arrayLimit===1?"":"s")+" allowed in an array.");return E},u="utf8=%26%2310003%3B",a="utf8=%E2%9C%93",s=function(w,q){var k={__proto__:null},A=q.ignoreQueryPrefix?w.replace(/^\?/,""):w;A=A.replace(/%5B/gi,"[").replace(/%5D/gi,"]");var R=q.parameterLimit===1/0?void 0:q.parameterLimit,S=A.split(q.delimiter,q.throwOnLimitExceeded&&typeof R!="undefined"?R+1:R);if(q.throwOnLimitExceeded&&typeof R!="undefined"&&S.length>R)throw new RangeError("Parameter limit exceeded. Only "+R+" parameter"+(R===1?"":"s")+" allowed.");var b=-1,h,p=q.charset;if(q.charsetSentinel)for(h=0;h<S.length;++h)S[h].indexOf("utf8=")===0&&(S[h]===a?p="utf-8":S[h]===u&&(p="iso-8859-1"),b=h,h=S.length);for(h=0;h<S.length;++h)if(h!==b){var v=S[h],I=v.indexOf("]="),B=I===-1?v.indexOf("="):I+1,H,V;if(B===-1?(H=q.decoder(v,r.decoder,p,"key"),V=q.strictNullHandling?null:""):(H=q.decoder(v.slice(0,B),r.decoder,p,"key"),H!==null&&(V=i.maybeMap(o(v.slice(B+1),q,t(k[H])?k[H].length:0),function(ce){return q.decoder(ce,r.decoder,p,"value")}))),V&&q.interpretNumericEntities&&p==="iso-8859-1"&&(V=n(String(V))),v.indexOf("[]=")>-1&&(V=t(V)?[V]:V),q.comma&&t(V)&&V.length>q.arrayLimit){if(q.throwOnLimitExceeded)throw new RangeError("Array limit exceeded. Only "+q.arrayLimit+" element"+(q.arrayLimit===1?"":"s")+" allowed in an array.");V=i.combine([],V,q.arrayLimit,q.plainObjects)}if(H!==null){var P=e.call(k,H);P&&(q.duplicates==="combine"||v.indexOf("[]=")>-1)?k[H]=i.combine(k[H],V,q.arrayLimit,q.plainObjects):(!P||q.duplicates==="last")&&(k[H]=V)}}return k},l=function(E,w,q,k){var A=0;if(E.length>0&&E[E.length-1]==="[]"){var R=E.slice(0,-1).join("");A=Array.isArray(w)&&w[R]?w[R].length:0}for(var S=k?w:o(w,q,A),b=E.length-1;b>=0;--b){var h,p=E[b];if(p==="[]"&&q.parseArrays)i.isOverflow(S)?h=S:h=q.allowEmptyArrays&&(S===""||q.strictNullHandling&&S===null)?[]:i.combine([],S,q.arrayLimit,q.plainObjects);else{h=q.plainObjects?{__proto__:null}:{};var v=p.charAt(0)==="["&&p.charAt(p.length-1)==="]"?p.slice(1,-1):p,I=q.decodeDotInKeys?v.replace(/%2E/g,"."):v,B=parseInt(I,10),H=!isNaN(B)&&p!==I&&String(B)===I&&B>=0&&q.parseArrays;if(!q.parseArrays&&I==="")h={0:S};else if(H&&B<q.arrayLimit)h=[],h[B]=S;else{if(H&&q.throwOnLimitExceeded)throw new RangeError("Array limit exceeded. Only "+q.arrayLimit+" element"+(q.arrayLimit===1?"":"s")+" allowed in an array.");H?(h[B]=S,i.markOverflow(h,B)):I!=="__proto__"&&(h[I]=S)}}S=h}return S},d=function(w,q){var k=q.allowDots?w.replace(/\.([^.[]+)/g,"[$1]"):w;if(q.depth<=0)return!q.plainObjects&&e.call(Object.prototype,k)&&!q.allowPrototypes?void 0:[k];var A=[],R=k.indexOf("["),S=R>=0?k.slice(0,R):k;if(S){if(!q.plainObjects&&e.call(Object.prototype,S)&&!q.allowPrototypes)return;A[A.length]=S}for(var b=k.length,h=R,p=0;h>=0&&p<q.depth;){for(var v=1,I=h+1,B=-1;I<b&&B<0;){var H=k.charCodeAt(I);H===91?v+=1:H===93&&(v-=1,v===0&&(B=I)),I+=1}if(B<0)return A[A.length]="["+k.slice(h)+"]",A;var V=k.slice(h,B+1),P=V.slice(1,-1);if(!q.plainObjects&&e.call(Object.prototype,P)&&!q.allowPrototypes)return;A[A.length]=V,p+=1,h=k.indexOf("[",B+1)}if(h>=0){if(q.strictDepth===!0)throw new RangeError("Input depth exceeded depth option of "+q.depth+" and strictDepth is true");A[A.length]="["+k.slice(h)+"]"}return A},_=function(w,q,k,A){if(w){var R=d(w,k);if(R)return l(R,q,k,A)}},g=function(w){if(!w)return r;if(typeof w.allowEmptyArrays!="undefined"&&typeof w.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof w.decodeDotInKeys!="undefined"&&typeof w.decodeDotInKeys!="boolean")throw new TypeError("`decodeDotInKeys` option can only be `true` or `false`, when provided");if(w.decoder!==null&&typeof w.decoder!="undefined"&&typeof w.decoder!="function")throw new TypeError("Decoder has to be a function.");if(typeof w.charset!="undefined"&&w.charset!=="utf-8"&&w.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");if(typeof w.throwOnLimitExceeded!="undefined"&&typeof w.throwOnLimitExceeded!="boolean")throw new TypeError("`throwOnLimitExceeded` option must be a boolean");var q=typeof w.charset=="undefined"?r.charset:w.charset,k=typeof w.duplicates=="undefined"?r.duplicates:w.duplicates;if(k!=="combine"&&k!=="first"&&k!=="last")throw new TypeError("The duplicates option must be either combine, first, or last");var A=typeof w.allowDots=="undefined"?w.decodeDotInKeys===!0?!0:r.allowDots:!!w.allowDots;return{allowDots:A,allowEmptyArrays:typeof w.allowEmptyArrays=="boolean"?!!w.allowEmptyArrays:r.allowEmptyArrays,allowPrototypes:typeof w.allowPrototypes=="boolean"?w.allowPrototypes:r.allowPrototypes,allowSparse:typeof w.allowSparse=="boolean"?w.allowSparse:r.allowSparse,arrayLimit:typeof w.arrayLimit=="number"?w.arrayLimit:r.arrayLimit,charset:q,charsetSentinel:typeof w.charsetSentinel=="boolean"?w.charsetSentinel:r.charsetSentinel,comma:typeof w.comma=="boolean"?w.comma:r.comma,decodeDotInKeys:typeof w.decodeDotInKeys=="boolean"?w.decodeDotInKeys:r.decodeDotInKeys,decoder:typeof w.decoder=="function"?w.decoder:r.decoder,delimiter:typeof w.delimiter=="string"||i.isRegExp(w.delimiter)?w.delimiter:r.delimiter,depth:typeof w.depth=="number"||w.depth===!1?+w.depth:r.depth,duplicates:k,ignoreQueryPrefix:w.ignoreQueryPrefix===!0,interpretNumericEntities:typeof w.interpretNumericEntities=="boolean"?w.interpretNumericEntities:r.interpretNumericEntities,parameterLimit:typeof w.parameterLimit=="number"?w.parameterLimit:r.parameterLimit,parseArrays:w.parseArrays!==!1,plainObjects:typeof w.plainObjects=="boolean"?w.plainObjects:r.plainObjects,strictDepth:typeof w.strictDepth=="boolean"?!!w.strictDepth:r.strictDepth,strictMerge:typeof w.strictMerge=="boolean"?!!w.strictMerge:r.strictMerge,strictNullHandling:typeof w.strictNullHandling=="boolean"?w.strictNullHandling:r.strictNullHandling,throwOnLimitExceeded:typeof w.throwOnLimitExceeded=="boolean"?w.throwOnLimitExceeded:!1}};return Ba=function(E,w){var q=g(w);if(E===""||E===null||typeof E=="undefined")return q.plainObjects?{__proto__:null}:{};for(var k=typeof E=="string"?s(E,q):E,A=q.plainObjects?{__proto__:null}:{},R=Object.keys(k),S=0;S<R.length;++S){var b=R[S],h=_(b,k[b],q,typeof E=="string");A=i.merge(A,h,q)}return q.allowSparse===!0?A:i.compact(A)},Ba}var Da,bp;function D_(){if(bp)return Da;bp=1;var i=P_(),e=B_(),t=qa();return Da={formats:t,parse:e,stringify:i},Da}var wp;function L_(){return wp||(wp=1,(function(i,e){Object.defineProperty(e,"__esModule",{value:!0});var t=C_(),r=D_();function n(K){return K&&typeof K=="object"&&"default"in K?K:{default:K}}var o=n(t),u=n(r),a=o.default;function s(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}var l=/^([a-z0-9.+-]+:)/i,d=/:[0-9]*$/,_=/^(\/\/?(?!\/)[^?\s]*)(\?[^\s]*)?$/,g=["<",">",'"',"`"," ","\r",`
25
25
  `," "],E=["{","}","|","\\","^","`"].concat(g),w=["'"].concat(E),q=["%","/","?",";","#"].concat(w),k=["/","?","#"],A=255,R=/^[+a-z0-9A-Z_-]{0,63}$/,S=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,b={javascript:!0,"javascript:":!0},h={javascript:!0,"javascript:":!0},p={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},v=u.default;function I(K,pe,X){if(K&&typeof K=="object"&&K instanceof s)return K;var Te=new s;return Te.parse(K,pe,X),Te}s.prototype.parse=function(K,pe,X){if(typeof K!="string")throw new TypeError("Parameter 'url' must be a string, not "+typeof K);var Te=K.indexOf("?"),qe=Te!==-1&&Te<K.indexOf("#")?"?":"#",$e=K.split(qe),Be=/\\/g;$e[0]=$e[0].replace(Be,"/"),K=$e.join(qe);var Ie=K;if(Ie=Ie.trim(),!X&&K.split("#").length===1){var x=_.exec(Ie);if(x)return this.path=Ie,this.href=Ie,this.pathname=x[1],x[2]?(this.search=x[2],pe?this.query=v.parse(this.search.substr(1)):this.query=this.search.substr(1)):pe&&(this.search="",this.query={}),this}var f=l.exec(Ie);if(f){f=f[0];var m=f.toLowerCase();this.protocol=m,Ie=Ie.substr(f.length)}if(X||f||Ie.match(/^\/\/[^@/]+@[^@/]+/)){var F=Ie.substr(0,2)==="//";F&&!(f&&h[f])&&(Ie=Ie.substr(2),this.slashes=!0)}if(!h[f]&&(F||f&&!p[f])){for(var W=-1,te=0;te<k.length;te++){var N=Ie.indexOf(k[te]);N!==-1&&(W===-1||N<W)&&(W=N)}var Z,Ee;W===-1?Ee=Ie.lastIndexOf("@"):Ee=Ie.lastIndexOf("@",W),Ee!==-1&&(Z=Ie.slice(0,Ee),Ie=Ie.slice(Ee+1),this.auth=decodeURIComponent(Z)),W=-1;for(var te=0;te<q.length;te++){var N=Ie.indexOf(q[te]);N!==-1&&(W===-1||N<W)&&(W=N)}W===-1&&(W=Ie.length),this.host=Ie.slice(0,W),Ie=Ie.slice(W),this.parseHost(),this.hostname=this.hostname||"";var Ae=this.hostname[0]==="["&&this.hostname[this.hostname.length-1]==="]";if(!Ae)for(var _e=this.hostname.split(/\./),te=0,ve=_e.length;te<ve;te++){var Ve=_e[te];if(Ve&&!Ve.match(R)){for(var Ue="",Ne=0,ot=Ve.length;Ne<ot;Ne++)Ve.charCodeAt(Ne)>127?Ue+="x":Ue+=Ve[Ne];if(!Ue.match(R)){var Qe=_e.slice(0,te),Je=_e.slice(te+1),C=Ve.match(S);C&&(Qe.push(C[1]),Je.unshift(C[2])),Je.length&&(Ie="/"+Je.join(".")+Ie),this.hostname=Qe.join(".");break}}}this.hostname.length>A?this.hostname="":this.hostname=this.hostname.toLowerCase(),Ae||(this.hostname=a.toASCII(this.hostname));var c=this.port?":"+this.port:"",y=this.hostname||"";this.host=y+c,this.href+=this.host,Ae&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),Ie[0]!=="/"&&(Ie="/"+Ie))}if(!b[m])for(var te=0,ve=w.length;te<ve;te++){var U=w[te];if(Ie.indexOf(U)!==-1){var Q=encodeURIComponent(U);Q===U&&(Q=escape(U)),Ie=Ie.split(U).join(Q)}}var ie=Ie.indexOf("#");ie!==-1&&(this.hash=Ie.substr(ie),Ie=Ie.slice(0,ie));var fe=Ie.indexOf("?");if(fe!==-1?(this.search=Ie.substr(fe),this.query=Ie.substr(fe+1),pe&&(this.query=v.parse(this.query)),Ie=Ie.slice(0,fe)):pe&&(this.search="",this.query={}),Ie&&(this.pathname=Ie),p[m]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){var c=this.pathname||"",Ce=this.search||"";this.path=c+Ce}return this.href=this.format(),this};function B(K){return typeof K=="string"&&(K=I(K)),K instanceof s?K.format():s.prototype.format.call(K)}s.prototype.format=function(){var K=this.auth||"";K&&(K=encodeURIComponent(K),K=K.replace(/%3A/i,":"),K+="@");var pe=this.protocol||"",X=this.pathname||"",Te=this.hash||"",qe=!1,$e="";this.host?qe=K+this.host:this.hostname&&(qe=K+(this.hostname.indexOf(":")===-1?this.hostname:"["+this.hostname+"]"),this.port&&(qe+=":"+this.port)),this.query&&typeof this.query=="object"&&Object.keys(this.query).length&&($e=v.stringify(this.query,{arrayFormat:"repeat",addQueryPrefix:!1}));var Be=this.search||$e&&"?"+$e||"";return pe&&pe.substr(-1)!==":"&&(pe+=":"),this.slashes||(!pe||p[pe])&&qe!==!1?(qe="//"+(qe||""),X&&X.charAt(0)!=="/"&&(X="/"+X)):qe||(qe=""),Te&&Te.charAt(0)!=="#"&&(Te="#"+Te),Be&&Be.charAt(0)!=="?"&&(Be="?"+Be),X=X.replace(/[?#]/g,function(Ie){return encodeURIComponent(Ie)}),Be=Be.replace("#","%23"),pe+qe+X+Be+Te};function H(K,pe){return I(K,!1,!0).resolve(pe)}s.prototype.resolve=function(K){return this.resolveObject(I(K,!1,!0)).format()};function V(K,pe){return K?I(K,!1,!0).resolveObject(pe):pe}s.prototype.resolveObject=function(K){if(typeof K=="string"){var pe=new s;pe.parse(K,!1,!0),K=pe}for(var X=new s,Te=Object.keys(this),qe=0;qe<Te.length;qe++){var $e=Te[qe];X[$e]=this[$e]}if(X.hash=K.hash,K.href==="")return X.href=X.format(),X;if(K.slashes&&!K.protocol){for(var Be=Object.keys(K),Ie=0;Ie<Be.length;Ie++){var x=Be[Ie];x!=="protocol"&&(X[x]=K[x])}return p[X.protocol]&&X.hostname&&!X.pathname&&(X.pathname="/",X.path=X.pathname),X.href=X.format(),X}if(K.protocol&&K.protocol!==X.protocol){if(!p[K.protocol]){for(var f=Object.keys(K),m=0;m<f.length;m++){var F=f[m];X[F]=K[F]}return X.href=X.format(),X}if(X.protocol=K.protocol,!K.host&&!h[K.protocol]){for(var ve=(K.pathname||"").split("/");ve.length&&!(K.host=ve.shift()););K.host||(K.host=""),K.hostname||(K.hostname=""),ve[0]!==""&&ve.unshift(""),ve.length<2&&ve.unshift(""),X.pathname=ve.join("/")}else X.pathname=K.pathname;if(X.search=K.search,X.query=K.query,X.host=K.host||"",X.auth=K.auth,X.hostname=K.hostname||K.host,X.port=K.port,X.pathname||X.search){var W=X.pathname||"",te=X.search||"";X.path=W+te}return X.slashes=X.slashes||K.slashes,X.href=X.format(),X}var N=X.pathname&&X.pathname.charAt(0)==="/",Z=K.host||K.pathname&&K.pathname.charAt(0)==="/",Ee=Z||N||X.host&&K.pathname,Ae=Ee,_e=X.pathname&&X.pathname.split("/")||[],ve=K.pathname&&K.pathname.split("/")||[],Ve=X.protocol&&!p[X.protocol];if(Ve&&(X.hostname="",X.port=null,X.host&&(_e[0]===""?_e[0]=X.host:_e.unshift(X.host)),X.host="",K.protocol&&(K.hostname=null,K.port=null,K.host&&(ve[0]===""?ve[0]=K.host:ve.unshift(K.host)),K.host=null),Ee=Ee&&(ve[0]===""||_e[0]==="")),Z)X.host=K.host||K.host===""?K.host:X.host,X.hostname=K.hostname||K.hostname===""?K.hostname:X.hostname,X.search=K.search,X.query=K.query,_e=ve;else if(ve.length)_e||(_e=[]),_e.pop(),_e=_e.concat(ve),X.search=K.search,X.query=K.query;else if(K.search!=null){if(Ve){X.host=_e.shift(),X.hostname=X.host;var Ue=X.host&&X.host.indexOf("@")>0?X.host.split("@"):!1;Ue&&(X.auth=Ue.shift(),X.hostname=Ue.shift(),X.host=X.hostname)}return X.search=K.search,X.query=K.query,(X.pathname!==null||X.search!==null)&&(X.path=(X.pathname?X.pathname:"")+(X.search?X.search:"")),X.href=X.format(),X}if(!_e.length)return X.pathname=null,X.search?X.path="/"+X.search:X.path=null,X.href=X.format(),X;for(var Ne=_e.slice(-1)[0],ot=(X.host||K.host||_e.length>1)&&(Ne==="."||Ne==="..")||Ne==="",Qe=0,Je=_e.length;Je>=0;Je--)Ne=_e[Je],Ne==="."?_e.splice(Je,1):Ne===".."?(_e.splice(Je,1),Qe++):Qe&&(_e.splice(Je,1),Qe--);if(!Ee&&!Ae)for(;Qe--;Qe)_e.unshift("..");Ee&&_e[0]!==""&&(!_e[0]||_e[0].charAt(0)!=="/")&&_e.unshift(""),ot&&_e.join("/").substr(-1)!=="/"&&_e.push("");var C=_e[0]===""||_e[0]&&_e[0].charAt(0)==="/";if(Ve){X.hostname=C?"":_e.length?_e.shift():"",X.host=X.hostname;var Ue=X.host&&X.host.indexOf("@")>0?X.host.split("@"):!1;Ue&&(X.auth=Ue.shift(),X.hostname=Ue.shift(),X.host=X.hostname)}return Ee=Ee||X.host&&_e.length,Ee&&!C&&_e.unshift(""),_e.length>0?X.pathname=_e.join("/"):(X.pathname=null,X.path=null),(X.pathname!==null||X.search!==null)&&(X.path=(X.pathname?X.pathname:"")+(X.search?X.search:"")),X.auth=K.auth||X.auth,X.slashes=X.slashes||K.slashes,X.href=X.format(),X},s.prototype.parseHost=function(){var K=this.host,pe=d.exec(K);pe&&(pe=pe[0],pe!==":"&&(this.port=pe.substr(1)),K=K.substr(0,K.length-pe.length)),K&&(this.hostname=K)};var P=I,ce=H,oe=V,ne=B,se=s;function he(K,pe){for(var X=0,Te=K.length-1;Te>=0;Te--){var qe=K[Te];qe==="."?K.splice(Te,1):qe===".."?(K.splice(Te,1),X++):X&&(K.splice(Te,1),X--)}if(pe)for(;X--;X)K.unshift("..");return K}function J(){for(var K="",pe=!1,X=arguments.length-1;X>=-1&&!pe;X--){var Te=X>=0?arguments[X]:"/";if(typeof Te!="string")throw new TypeError("Arguments to path.resolve must be strings");if(!Te)continue;K=Te+"/"+K,pe=Te.charAt(0)==="/"}return K=he(me(K.split("/"),function(qe){return!!qe}),!pe).join("/"),(pe?"/":"")+K||"."}function me(K,pe){if(K.filter)return K.filter(pe);for(var X=[],Te=0;Te<K.length;Te++)pe(K[Te],Te,K)&&X.push(K[Te]);return X}var de=(function(K){function pe(){var Te=this||self;return delete K.prototype.__magic__,Te}if(typeof globalThis=="object")return globalThis;if(this)return pe();K.defineProperty(K.prototype,"__magic__",{configurable:!0,get:pe});var X=__magic__;return X})(Object),be=ne,G=P,re=ce,j=se,L=de.URL,M=de.URLSearchParams,D=/%/g,$=/\\/g,z=/\n/g,Y=/\r/g,T=/\t/g,O=47;function ee(K){var pe=K!=null?K:null;return!!(pe!==null&&(pe!=null&&pe.href)&&(pe!=null&&pe.origin))}function ae(K){if(K.hostname!=="")throw new TypeError('File URL host must be "localhost" or empty on browser');for(var pe=K.pathname,X=0;X<pe.length;X++)if(pe[X]==="%"){var Te=pe.codePointAt(X+2)|32;if(pe[X+1]==="2"&&Te===102)throw new TypeError("File URL path must not include encoded / characters")}return decodeURIComponent(pe)}function ye(K){return K.includes("%")&&(K=K.replace(D,"%25")),K.includes("\\")&&(K=K.replace($,"%5C")),K.includes(`
26
- `)&&(K=K.replace(z,"%0A")),K.includes("\r")&&(K=K.replace(Y,"%0D")),K.includes(" ")&&(K=K.replace(T,"%09")),K}var le=function(pe){if(typeof pe=="undefined")throw new TypeError('The "domain" argument must be specified');return new L("http://"+pe).hostname},Se=function(pe){if(typeof pe=="undefined")throw new TypeError('The "domain" argument must be specified');return new L("http://"+pe).hostname},Pe=function(pe){var X=new L("file://"),Te=J(pe),qe=pe.charCodeAt(pe.length-1);return qe===O&&Te[Te.length-1]!=="/"&&(Te+="/"),X.pathname=ye(Te),X},ue=function(pe){if(!ee(pe)&&typeof pe!="string")throw new TypeError('The "path" argument must be of type string or an instance of URL. Received type '+typeof pe+" ("+pe+")");var X=new L(pe);if(X.protocol!=="file:")throw new TypeError("The URL must be of scheme file");return ae(X)},je=function(pe,X){var Te,qe,$e,Be;if(X===void 0&&(X={}),!(pe instanceof L))return be(pe);if(typeof X!="object"||X===null)throw new TypeError('The "options" argument must be of type object.');var Ie=(Te=X.auth)!=null?Te:!0,x=(qe=X.fragment)!=null?qe:!0,f=($e=X.search)!=null?$e:!0;(Be=X.unicode)!=null;var m=new L(pe.toString());return Ie||(m.username="",m.password=""),x||(m.hash=""),f||(m.search=""),m.toString()},De={format:je,parse:G,resolve:re,resolveObject:oe,Url:j,URL:L,URLSearchParams:M,domainToASCII:le,domainToUnicode:Se,pathToFileURL:Pe,fileURLToPath:ue};e.URL=L,e.URLSearchParams=M,e.Url=j,e.default=De,e.domainToASCII=le,e.domainToUnicode=Se,e.fileURLToPath=ue,e.format=je,e.parse=G,e.pathToFileURL=Pe,e.resolve=re,e.resolveObject=oe,e=i.exports=De})(mr,mr.exports)),mr.exports}var La,Sp;function Ep(){if(Sp)return La;Sp=1;var i=null;return La=i,La}var Fa,Ip;function Tp(){if(Ip)return Fa;Ip=1;var i=Ep(),e=Rt()("mqttjs:tcp");function t(r,n){var o,u;return n.port=n.port||1883,n.hostname=n.hostname||n.host||"localhost",o=n.port,u=n.hostname,e("port %d and host %s",o,u),i.createConnection(o,u)}return Fa=t,Fa}var Ua,Rp;function Na(){if(Rp)return Ua;Rp=1;var i=Ep(),e=Rt()("mqttjs:tls");function t(r,n){var o;n.port=n.port||8883,n.host=n.hostname||n.host||"localhost",n.servername=n.host,n.rejectUnauthorized=n.rejectUnauthorized!==!1,delete n.path,e("port %d host %s rejectUnauthorized %b",n.port,n.host,n.rejectUnauthorized),o=i.connect(n),o.on("secureConnect",function(){n.rejectUnauthorized&&!o.authorized?o.emit("error",new Error("TLS not authorized")):o.removeListener("error",u)});function u(a){n.rejectUnauthorized&&r.emit("error",a),o.end()}return o.on("error",u),o}return Ua=t,Ua}var gr={exports:{}},ja,Ap;function F_(){if(Ap)return ja;Ap=1,ja=i;function i(e,t){if(e&&t)return i(e)(t);if(typeof e!="function")throw new TypeError("need wrapper function");return Object.keys(e).forEach(function(n){r[n]=e[n]}),r;function r(){for(var n=new Array(arguments.length),o=0;o<n.length;o++)n[o]=arguments[o];var u=e.apply(this,n),a=n[n.length-1];return typeof u=="function"&&u!==a&&Object.keys(a).forEach(function(s){u[s]=a[s]}),u}}return ja}var Op;function U_(){if(Op)return gr.exports;Op=1;var i=F_();gr.exports=i(e),gr.exports.strict=i(t),e.proto=e(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return e(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return t(this)},configurable:!0})});function e(r){var n=function(){return n.called?n.value:(n.called=!0,n.value=r.apply(this,arguments))};return n.called=!1,n}function t(r){var n=function(){if(n.called)throw new Error(n.onceError);return n.called=!0,n.value=r.apply(this,arguments)},o=r.name||"Function wrapped with `once`";return n.onceError=o+" shouldn't be called more than once",n.called=!1,n}return gr.exports}var $a,xp;function N_(){if(xp)return $a;xp=1;var i=U_(),e=function(){},t=xe.Bare?queueMicrotask:Re.nextTick.bind(Re),r=function(u){return u.setHeader&&typeof u.abort=="function"},n=function(u){return u.stdio&&Array.isArray(u.stdio)&&u.stdio.length===3},o=function(u,a,s){if(typeof a=="function")return o(u,null,a);a||(a={}),s=i(s||e);var l=u._writableState,d=u._readableState,_=a.readable||a.readable!==!1&&u.readable,g=a.writable||a.writable!==!1&&u.writable,E=!1,w=function(){u.writable||q()},q=function(){g=!1,_||s.call(u)},k=function(){_=!1,g||s.call(u)},A=function(p){s.call(u,p?new Error("exited with error code: "+p):null)},R=function(p){s.call(u,p)},S=function(){t(b)},b=function(){if(!E){if(_&&!(d&&d.ended&&!d.destroyed))return s.call(u,new Error("premature close"));if(g&&!(l&&l.ended&&!l.destroyed))return s.call(u,new Error("premature close"))}},h=function(){u.req.on("finish",q)};return r(u)?(u.on("complete",q),u.on("abort",S),u.req?h():u.on("request",h)):g&&!l&&(u.on("end",w),u.on("close",w)),n(u)&&u.on("exit",A),u.on("end",k),u.on("finish",q),a.error!==!1&&u.on("error",R),u.on("close",S),function(){E=!0,u.removeListener("complete",q),u.removeListener("abort",S),u.removeListener("request",h),u.req&&u.req.removeListener("finish",q),u.removeListener("end",w),u.removeListener("close",w),u.removeListener("finish",q),u.removeListener("exit",A),u.removeListener("end",k),u.removeListener("error",R),u.removeListener("close",S)}};return $a=o,$a}var Ha,Cp;function j_(){if(Cp)return Ha;Cp=1,Ha=i;function i(t){var r=t._readableState;return r?r.objectMode||typeof t._duplexState=="number"?t.read():t.read(e(r)):null}function e(t){if(t.buffer.length){var r=t.bufferIndex||0;if(t.buffer.head)return t.buffer.head.data.length;if(t.buffer.length-r>0&&t.buffer[r])return t.buffer[r].length}return t.length}return Ha}var Wa,kp;function Ya(){if(kp)return Wa;kp=1;var i=Tt(),e=N_(),t=_t(),r=j_(),n=we.from&&we.from!==Uint8Array.from?we.from([0]):new we([0]),o=function(g,E){g._corked?g.once("uncork",E):E()},u=function(g,E){g._autoDestroy&&g.destroy(E)},a=function(g,E){return function(w){w?u(g,w.message==="premature close"?null:w):E&&!g._ended&&g.end()}},s=function(g,E){if(!g||g._writableState&&g._writableState.finished)return E();if(g._writableState)return g.end(E);g.end(),E()},l=function(){},d=function(g){return new i.Readable({objectMode:!0,highWaterMark:16}).wrap(g)},_=function(g,E,w){if(!(this instanceof _))return new _(g,E,w);i.Duplex.call(this,w),this._writable=null,this._readable=null,this._readable2=null,this._autoDestroy=!w||w.autoDestroy!==!1,this._forwardDestroy=!w||w.destroy!==!1,this._forwardEnd=!w||w.end!==!1,this._corked=1,this._ondrain=null,this._drained=!1,this._forwarding=!1,this._unwrite=null,this._unread=null,this._ended=!1,this.destroyed=!1,g&&this.setWritable(g),E&&this.setReadable(E)};return t(_,i.Duplex),_.obj=function(g,E,w){return w||(w={}),w.objectMode=!0,w.highWaterMark=16,new _(g,E,w)},_.prototype.cork=function(){++this._corked===1&&this.emit("cork")},_.prototype.uncork=function(){this._corked&&--this._corked===0&&this.emit("uncork")},_.prototype.setWritable=function(g){if(this._unwrite&&this._unwrite(),this.destroyed){g&&g.destroy&&g.destroy();return}if(g===null||g===!1){this.end();return}var E=this,w=e(g,{writable:!0,readable:!1},a(this,this._forwardEnd)),q=function(){var A=E._ondrain;E._ondrain=null,A&&A()},k=function(){E._writable.removeListener("drain",q),w()};this._unwrite&&Re.nextTick(q),this._writable=g,this._writable.on("drain",q),this._unwrite=k,this.uncork()},_.prototype.setReadable=function(g){if(this._unread&&this._unread(),this.destroyed){g&&g.destroy&&g.destroy();return}if(g===null||g===!1){this.push(null),this.resume();return}var E=this,w=e(g,{writable:!1,readable:!0},a(this)),q=function(){E._forward()},k=function(){E.push(null)},A=function(){E._readable2.removeListener("readable",q),E._readable2.removeListener("end",k),w()};this._drained=!0,this._readable=g,this._readable2=g._readableState?g:d(g),this._readable2.on("readable",q),this._readable2.on("end",k),this._unread=A,this._forward()},_.prototype._read=function(){this._drained=!0,this._forward()},_.prototype._forward=function(){if(!(this._forwarding||!this._readable2||!this._drained)){this._forwarding=!0;for(var g;this._drained&&(g=r(this._readable2))!==null;)this.destroyed||(this._drained=this.push(g));this._forwarding=!1}},_.prototype.destroy=function(g,E){if(E||(E=l),this.destroyed)return E(null);this.destroyed=!0;var w=this;Re.nextTick(function(){w._destroy(g),E(null)})},_.prototype._destroy=function(g){if(g){var E=this._ondrain;this._ondrain=null,E?E(g):this.emit("error",g)}this._forwardDestroy&&(this._readable&&this._readable.destroy&&this._readable.destroy(),this._writable&&this._writable.destroy&&this._writable.destroy()),this.emit("close")},_.prototype._write=function(g,E,w){if(!this.destroyed){if(this._corked)return o(this,this._write.bind(this,g,E,w));if(g===n)return this._finish(w);if(!this._writable)return w();this._writable.write(g)===!1?this._ondrain=w:this.destroyed||w()}},_.prototype._finish=function(g){var E=this;this.emit("preend"),o(this,function(){s(E._forwardEnd&&E._writable,function(){E._writableState.prefinished===!1&&(E._writableState.prefinished=!0),E.emit("prefinish"),o(E,g)})})},_.prototype.end=function(g,E,w){return typeof g=="function"?this.end(null,null,g):typeof E=="function"?this.end(g,null,E):(this._ended=!0,g&&this.write(g),!this._writableState.ending&&!this._writableState.destroyed&&this.write(n),i.Writable.prototype.end.call(this,w))},Wa=_,Wa}var Ga,qp;function Mp(){if(qp)return Ga;qp=1;var i=Tt().Transform,e=Ya(),t,r,n;function o(){var d=new i;return d._write=function(_,g,E){t.send({data:_.buffer,success:function(){E()},fail:function(w){E(new Error(w))}})},d._flush=function(g){t.close({success:function(){g()}})},d}function u(d){d.hostname||(d.hostname="localhost"),d.path||(d.path="/"),d.wsOptions||(d.wsOptions={})}function a(d,_){var g=d.protocol==="wxs"?"wss":"ws",E=g+"://"+d.hostname+d.path;return d.port&&d.port!==80&&d.port!==443&&(E=g+"://"+d.hostname+":"+d.port+d.path),typeof d.transformWsUrl=="function"&&(E=d.transformWsUrl(E,d,_)),E}function s(){t.onOpen(function(){n.setReadable(r),n.setWritable(r),n.emit("connect")}),t.onMessage(function(d){var _=d.data;_ instanceof ArrayBuffer?_=we.from(_):_=we.from(_,"utf8"),r.push(_)}),t.onClose(function(){n.end(),n.destroy()}),t.onError(function(d){n.destroy(new Error(d.errMsg))})}function l(d,_){if(_.hostname=_.hostname||_.host,!_.hostname)throw new Error("Could not determine host. Specify host manually.");var g=_.protocolId==="MQIsdp"&&_.protocolVersion===3?"mqttv3.1":"mqtt";u(_);var E=a(_,d);t=wx.connectSocket({url:E,protocols:[g]}),r=o(),n=e.obj(),n._destroy=function(q,k){t.close({success:function(){k&&k(q)}})};var w=n.destroy;return n.destroy=function(){n.destroy=w;var q=this;setTimeout(function(){t.close({fail:function(){q._destroy(new Error)}})},0)}.bind(n),s(),n}return Ga=l,Ga}var za,Pp;function Bp(){if(Pp)return za;Pp=1;var i=Tt().Transform,e=Ya(),t,r,n,o=!1;function u(){var _=new i;return _._write=function(g,E,w){t.sendSocketMessage({data:g.buffer,success:function(){w()},fail:function(){w(new Error)}})},_._flush=function(E){t.closeSocket({success:function(){E()}})},_}function a(_){_.hostname||(_.hostname="localhost"),_.path||(_.path="/"),_.wsOptions||(_.wsOptions={})}function s(_,g){var E=_.protocol==="alis"?"wss":"ws",w=E+"://"+_.hostname+_.path;return _.port&&_.port!==80&&_.port!==443&&(w=E+"://"+_.hostname+":"+_.port+_.path),typeof _.transformWsUrl=="function"&&(w=_.transformWsUrl(w,_,g)),w}function l(){o||(o=!0,t.onSocketOpen(function(){n.setReadable(r),n.setWritable(r),n.emit("connect")}),t.onSocketMessage(function(_){if(typeof _.data=="string"){var g=we.from(_.data,"base64");r.push(g)}else{var E=new FileReader;E.addEventListener("load",function(){var w=E.result;w instanceof ArrayBuffer?w=we.from(w):w=we.from(w,"utf8"),r.push(w)}),E.readAsArrayBuffer(_.data)}}),t.onSocketClose(function(){n.end(),n.destroy()}),t.onSocketError(function(_){n.destroy(_)}))}function d(_,g){if(g.hostname=g.hostname||g.host,!g.hostname)throw new Error("Could not determine host. Specify host manually.");var E=g.protocolId==="MQIsdp"&&g.protocolVersion===3?"mqttv3.1":"mqtt";a(g);var w=s(g,_);return t=g.my,t.connectSocket({url:w,protocols:E}),r=u(),n=e.obj(),l(),n}return za=d,za}var _r={exports:{}},Va,Dp;function $_(){return Dp||(Dp=1,Va=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}),Va}var Lp;function Fp(){if(Lp)return _r.exports;Lp=1;const i=$_(),e=Rt()("mqttjs:ws"),t=Ya(),r=Tt().Transform;let n=["rejectUnauthorized","ca","cert","key","pfx","passphrase"];const o=typeof Re!="undefined"&&Re.title==="browser"||typeof __webpack_require__=="function";function u(E,w){let q=E.protocol+"://"+E.hostname+":"+E.port+E.path;return typeof E.transformWsUrl=="function"&&(q=E.transformWsUrl(q,E,w)),q}function a(E){let w=E;return E.hostname||(w.hostname="localhost"),E.port||(E.protocol==="wss"?w.port=443:w.port=80),E.path||(w.path="/"),E.wsOptions||(w.wsOptions={}),!o&&E.protocol==="wss"&&n.forEach(function(q){E.hasOwnProperty(q)&&!E.wsOptions.hasOwnProperty(q)&&(w.wsOptions[q]=E[q])}),w}function s(E){let w=a(E);if(w.hostname||(w.hostname=w.host),!w.hostname){if(typeof document=="undefined")throw new Error("Could not determine host. Specify host manually.");const q=new URL(document.URL);w.hostname=q.hostname,w.port||(w.port=q.port)}return w.objectMode===void 0&&(w.objectMode=!(w.binary===!0||w.binary===void 0)),w}function l(E,w,q){e("createWebSocket"),e("protocol: "+q.protocolId+" "+q.protocolVersion);const k=q.protocolId==="MQIsdp"&&q.protocolVersion===3?"mqttv3.1":"mqtt";return e("creating new Websocket for url: "+w+" and protocol: "+k),new i(w,[k],q.wsOptions)}function d(E,w){const q=w.protocolId==="MQIsdp"&&w.protocolVersion===3?"mqttv3.1":"mqtt";let k=u(w,E),A=new WebSocket(k,[q]);return A.binaryType="arraybuffer",A}function _(E,w){e("streamBuilder");let q=a(w);const k=u(q,E);let A=l(E,k,q),R=i.createWebSocketStream(A,q.wsOptions);return R.url=k,A.on("close",()=>{R.destroy()}),R}function g(E,w){e("browserStreamBuilder");let q;const A=s(w).browserBufferSize||1024*512,R=w.browserBufferTimeout||1e3,S=!w.objectMode;let b=d(E,w),h=v(w,ce,oe);w.objectMode||(h._writev=P),h.on("close",()=>{b.close()});const p=typeof b.addEventListener!="undefined";b.readyState===b.OPEN?q=h:(q=q=t(void 0,void 0,w),w.objectMode||(q._writev=P),p?b.addEventListener("open",I):b.onopen=I),q.socket=b,p?(b.addEventListener("close",B),b.addEventListener("error",H),b.addEventListener("message",V)):(b.onclose=B,b.onerror=H,b.onmessage=V);function v(ne,se,he){let J=new r({objectModeMode:ne.objectMode});return J._write=se,J._flush=he,J}function I(){q.setReadable(h),q.setWritable(h),q.emit("connect")}function B(){q.end(),q.destroy()}function H(ne){q.destroy(ne)}function V(ne){let se=ne.data;se instanceof ArrayBuffer?se=we.from(se):se=we.from(se,"utf8"),h.push(se)}function P(ne,se){const he=new Array(ne.length);for(let J=0;J<ne.length;J++)typeof ne[J].chunk=="string"?he[J]=we.from(ne[J],"utf8"):he[J]=ne[J].chunk;this._write(we.concat(he),"binary",se)}function ce(ne,se,he){b.bufferedAmount>A&&setTimeout(ce,R,ne,se,he),S&&typeof ne=="string"&&(ne=we.from(ne,"utf8"));try{b.send(ne)}catch(J){return he(J)}he()}function oe(ne){b.close(),ne()}return q}return o?_r.exports=g:_r.exports=_,_r.exports}var Up;function H_(){if(Up)return kt.exports;Up=1;var i=O_(),e=Nd(),t=L_(),r=jo(),n=Rt()("mqttjs"),o={};typeof Re!="undefined"&&Re.title!=="browser"||typeof __webpack_require__!="function"?(o.mqtt=Tp(),o.tcp=Tp(),o.ssl=Na(),o.tls=Na(),o.mqtts=Na()):(o.wx=Mp(),o.wxs=Mp(),o.ali=Bp(),o.alis=Bp()),o.ws=Fp(),o.wss=Fp();function u(s){var l;s.auth&&(l=s.auth.match(/^(.+):(.+)$/),l?(s.username=l[1],s.password=l[2]):s.username=s.auth)}function a(s,l){if(n("connecting to an MQTT broker..."),typeof s=="object"&&!l&&(l=s,s=null),l=l||{},s){var d=t.parse(s,!0);if(d.port!=null&&(d.port=Number(d.port)),l=r(d,l),l.protocol===null)throw new Error("Missing protocol");l.protocol=l.protocol.replace(/:$/,"")}if(u(l),l.query&&typeof l.query.clientId=="string"&&(l.clientId=l.query.clientId),l.cert&&l.key)if(l.protocol){if(["mqtts","wss","wxs","alis"].indexOf(l.protocol)===-1)switch(l.protocol){case"mqtt":l.protocol="mqtts";break;case"ws":l.protocol="wss";break;case"wx":l.protocol="wxs";break;case"ali":l.protocol="alis";break;default:throw new Error('Unknown protocol for secure connection: "'+l.protocol+'"!')}}else throw new Error("Missing secure protocol key");if(!o[l.protocol]){var _=["mqtts","wss"].indexOf(l.protocol)!==-1;l.protocol=["mqtt","mqtts","ws","wss","wx","wxs","ali","alis"].filter(function(w,q){return _&&q%2===0?!1:typeof o[w]=="function"})[0]}if(l.clean===!1&&!l.clientId)throw new Error("Missing clientId for unclean clients");l.protocol&&(l.defaultProtocol=l.protocol);function g(w){return l.servers&&((!w._reconnectCount||w._reconnectCount===l.servers.length)&&(w._reconnectCount=0),l.host=l.servers[w._reconnectCount].host,l.port=l.servers[w._reconnectCount].port,l.protocol=l.servers[w._reconnectCount].protocol?l.servers[w._reconnectCount].protocol:l.defaultProtocol,l.hostname=l.host,w._reconnectCount++),n("calling streambuilder for",l.protocol),o[l.protocol](w,l)}var E=new i(g,l);return E.on("error",function(){}),E}return kt.exports=a,kt.exports.connect=a,kt.exports.MqttClient=i,kt.exports.Store=e,kt.exports}var W_=H_();const Y_=rt(W_);var Ka,Np;function G_(){if(Np)return Ka;Np=1;var i="Expected a function",e=NaN,t="[object Symbol]",r=/^\s+|\s+$/g,n=/^[-+]0x[0-9a-f]+$/i,o=/^0b[01]+$/i,u=/^0o[0-7]+$/i,a=parseInt,s=typeof xe=="object"&&xe&&xe.Object===Object&&xe,l=typeof self=="object"&&self&&self.Object===Object&&self,d=s||l||Function("return this")(),_=Object.prototype,g=_.toString,E=Math.max,w=Math.min,q=function(){return d.Date.now()};function k(h,p,v){var I,B,H,V,P,ce,oe=0,ne=!1,se=!1,he=!0;if(typeof h!="function")throw new TypeError(i);p=b(p)||0,A(v)&&(ne=!!v.leading,se="maxWait"in v,H=se?E(b(v.maxWait)||0,p):H,he="trailing"in v?!!v.trailing:he);function J(D){var $=I,z=B;return I=B=void 0,oe=D,V=h.apply(z,$),V}function me(D){return oe=D,P=setTimeout(G,p),ne?J(D):V}function de(D){var $=D-ce,z=D-oe,Y=p-$;return se?w(Y,H-z):Y}function be(D){var $=D-ce,z=D-oe;return ce===void 0||$>=p||$<0||se&&z>=H}function G(){var D=q();if(be(D))return re(D);P=setTimeout(G,de(D))}function re(D){return P=void 0,he&&I?J(D):(I=B=void 0,V)}function j(){P!==void 0&&clearTimeout(P),oe=0,I=ce=B=P=void 0}function L(){return P===void 0?V:re(q())}function M(){var D=q(),$=be(D);if(I=arguments,B=this,ce=D,$){if(P===void 0)return me(ce);if(se)return P=setTimeout(G,p),J(ce)}return P===void 0&&(P=setTimeout(G,p)),V}return M.cancel=j,M.flush=L,M}function A(h){var p=typeof h;return!!h&&(p=="object"||p=="function")}function R(h){return!!h&&typeof h=="object"}function S(h){return typeof h=="symbol"||R(h)&&g.call(h)==t}function b(h){if(typeof h=="number")return h;if(S(h))return e;if(A(h)){var p=typeof h.valueOf=="function"?h.valueOf():h;h=A(p)?p+"":p}if(typeof h!="string")return h===0?h:+h;h=h.replace(r,"");var v=o.test(h);return v||u.test(h)?a(h.slice(2),v?2:8):n.test(h)?e:+h}return Ka=k,Ka}var z_=G_();const V_=rt(z_),jp=(i,e,t,r)=>{try{const n=i();return r!=null&&r(n),n}catch(n){return t!=null&&t(n),e}},K_=i=>i.then(e=>[e,null]).catch(e=>[null,e]);class Q_{constructor(e,t,r,{shouldConnect:n=!0,brokerLbUrl:o,enableLb:u,getClientId:a}){He(this,"_getClientId",()=>this.getClientId==null?`${this.core.AppId}_${this.core.user_id}_${Date.now()}`:this.getClientId());He(this,"__mqtt_connected_handler",()=>{this.emitter.emit("connected")});He(this,"__mqtt_reconnect_handler",()=>{this.emitter.emit("reconnect")});He(this,"__mqtt_closed_handler",(...e)=>{this.emitter.emit("close",e)});He(this,"__mqtt_message_handler",(e,t)=>{const r=t.toString(),n=this.matcher(e);this.logger("message",e,t),n!=null&&n(r)});He(this,"__mqtt_error_handler",e=>{e&&e.message==="client disconnecting"||(this.emitter.emit("error",e.message),this.logger("error",e.message))});He(this,"__mqtt_conneck",e=>{const t=[],r={will:{topic:`u/${this.core.user_id}/s`,payload:0,retain:!0},clientId:this._getClientId()};if(e==null&&(e=this.cacheRealtimeURL),this.mqtt!=null){const o=Object.keys(this.mqtt._resubscribeTopics);t.push(...o),this.mqtt.removeAllListeners(),this.mqtt.end(!0),delete this.mqtt,this.mqtt=null}const n=Y_(e,r);return n.addListener("connect",this.__mqtt_connected_handler),n.addListener("reconnect",this.__mqtt_reconnect_handler),n.addListener("close",this.__mqtt_closed_handler),n.addListener("error",this.__mqtt_error_handler),n.addListener("message",this.__mqtt_message_handler),this.logger(`resubscribe to old topics ${t}`),t.forEach(o=>n.subscribe(o)),n});He(this,"_on_close_handler",V_(()=>ke(this,null,function*(){const e=this.enableLb===!0&&this.core.isLogin===!0&&this.shouldConnect===!0&&!this.willConnectToRealtime;if(this.logEnabled&&(console.group("@mqtt.closed"),console.log(`this.enableLb(${this.enableLb})`),console.log(`this.core.isLogin(${this.core.isLogin})`),console.log(`this.shouldConnect(${this.shouldConnect})`),console.log(`this.willConnectToRealtime(${this.willConnectToRealtime})`),console.log(`shouldReconnect(${e})`),console.groupEnd()),!e)return;this.willConnectToRealtime=!0;const[t,r]=yield K_(this.getMqttNode());r?(this.logger(`cannot get new brokerURL, using old url instead (${this.cacheRealtimeURL})`),this.mqtt=this.__mqtt_conneck(this.cacheRealtimeURL)):(this.cacheRealtimeURL=t,this.logger("trying to reconnect to",t),this.mqtt=this.__mqtt_conneck(t)),this.willConnectToRealtime=!1}),1e3));He(this,"subscribtionBuffer",[]);He(this,"unsubscribtionBuffer",[]);He(this,"publishBuffer",[]);this.emitter=Ot(),this.core=t,this.mqtt=null,this.brokerLbUrl=o,this.getClientId=a,this.enableLb=u,this.shouldConnect=n,this.matcher=hg({[Ze(this.reNewMessage)]:l=>this.newMessageHandler.bind(this,l),[Ze(this.reNotification)]:l=>this.notificationHandler.bind(this,l),[Ze(this.reTyping)]:l=>this.typingHandler.bind(this,l),[Ze(this.reRoomTyping)]:l=>this.roomTypingHandler.bind(this,l),[Ze(this.reDelivery)]:l=>this.deliveryReceiptHandler.bind(this,l),[Ze(this.reRead)]:l=>this.readReceiptHandler.bind(this,l),[Ze(this.reOnlineStatus)]:l=>this.onlinePresenceHandler.bind(this,l),[Ze(this.reChannelMessage)]:l=>this.channelMessageHandler.bind(this,l),[Ze(this.reMessageUpdated)]:l=>this.messageUpdatedHandler.bind(this,l),[Ze()]:l=>this.logger("topic not handled",l)});let s=this.__mqtt_conneck(e);this.mqtt=s,n||s.end(!0),this.willConnectToRealtime=!1,this.emitter.on("close",this._on_close_handler)}get cacheRealtimeURL(){return this.core.mqttURL}set cacheRealtimeURL(e){this.core.mqttURL=e}connect(){this.mqtt=this.__mqtt_conneck()}openConnection(){return ke(this,null,function*(){this.shouldConnect=!0,this.mqtt=this.__mqtt_conneck()})}closeConnection(){return ke(this,null,function*(){this.shouldConnect=!1,this.mqtt.end(!0,e=>{e&&this.logger("error when close connection",e.message)}),this.mqtt=null})}getMqttNode(){return ke(this,null,function*(){const e=yield st.get(this.brokerLbUrl),t=e.body.data.url,r=e.body.data.wss_port;return`wss://${t}:${r}/mqtt`})}get connected(){return this.mqtt==null?!1:this.mqtt.connected}subscribe(...e){for(this.subscribtionBuffer.push(e);this.mqtt!=null&&this.subscribtionBuffer.length>0;){const t=this.subscribtionBuffer.shift();t!=null&&(this.logger("subscribe topic",t),this.mqtt.subscribe(...t))}}unsubscribe(...e){for(this.unsubscribtionBuffer.push(e);this.mqtt!=null&&this.unsubscribtionBuffer.length>0;){const t=this.unsubscribtionBuffer.shift();t!=null&&(this.logger("unsubscribe topic",t),this.mqtt.unsubscribe(...t))}}publish(e,t,r={}){for(this.publishBuffer.push({topic:e,payload:t,options:r});this.mqtt!=null&&this.publishBuffer.length>0;){const n=this.publishBuffer.shift();n!=null&&(this.logger("publish to",n.topic,n.payload,n.options),this.mqtt.publish(n.topic,n.payload.toString(),n.options))}}emit(...e){this.emitter.emit(...e)}on(...e){this.emitter.on(...e)}off(...e){this.emitter.off(...e)}get logEnabled(){return this.core.debugMQTTMode}get logger(){return this.core.debugMQTTMode?console.log.bind(console,"QRealtime ->"):this.noop}get reNewMessage(){return/^(.+)\/c$/i}get reNotification(){return/^(.+)\/n$/i}get reTyping(){return/^r\/([\d]+)\/([\d]+)\/(.+)\/t$/i}get reRoomTyping(){return/^r\/(.+)\/typing$/i}get reDelivery(){return/^r\/([\d]+)\/([\d]+)\/(.+)\/d$/i}get reRead(){return/^r\/([\d]+)\/([\d]+)\/(.+)\/r$/i}get reOnlineStatus(){return/^u\/(.+)\/s$/i}get reChannelMessage(){return/^(.+)\/(.+)\/c$/i}get reMessageUpdated(){return/^(.+)\/update$/i}noop(){}newMessageHandler(e,t){t=JSON.parse(t),this.logger("on:new-message",t),this.emit("new-message",t)}notificationHandler(e,t){this.logger("on:notification",t),t=JSON.parse(t);const r=t.payload.data;"deleted_messages"in r&&r.deleted_messages.forEach(n=>{this.emit("comment-deleted",{roomId:n.room_id,commentUniqueIds:n.message_unique_ids,isForEveryone:!0,isHard:!0})}),"deleted_rooms"in r&&r.deleted_rooms.forEach(n=>{this.emit("room-cleared",n)})}roomTypingHandler(e,t){var o;this.logger("on:room-typing",e);let r=(o=e.match(this.reRoomTyping))==null?void 0:o[1],n=JSON.parse(t);this.emit("room-typing",wr(br({},n),{room_id:r}))}typingHandler(e,t){this.logger("on:typing",e);const r=e.match(this.reTyping);if(r[3]===this.core.user_id)return;const n=r[3],o=r[1];if(this.emit("typing",{message:t,userId:n,roomId:o}),this.core.selected!=null)if(t==="1"&&o===this.core.selected.id){const u=this.core.selected.participants.find(s=>s.email===n);if(u==null)return;const a=u.username;this.core.isTypingStatus=`${a} is typing ...`}else this.core.isTypingStatus=null}deliveryReceiptHandler(e,t){this.logger("on:delivered",e,t);const r=e.match(this.reDelivery),n=t.split(":"),o=Number(n[0]),u=n[1],a=r[3];this.emit("message-delivered",{commentId:o,commentUniqueId:u,userId:a})}readReceiptHandler(e,t){this.logger("on:read",e,t);const r=e.match(this.reRead),n=t.split(":"),o=Number(n[0]),u=n[1],a=r[3];this.emit("message-read",{commentId:o,commentUniqueId:u,userId:a})}onlinePresenceHandler(e,t){this.logger("on:online-presence",e,t);const n=this.reOnlineStatus.exec(e)[1];this.emit("presence",{message:t,userId:n})}channelMessageHandler(e,t){this.logger("on:channel-message",e,t),this.emit("new-message",JSON.parse(t))}messageUpdatedHandler(e,t){t=JSON.parse(t),this.logger("on:message-updated",e,t),this.emit("message:updated",t)}subscribeChannel(e,t){this.subscribe(`${e}/${t}/c`)}subscribeRoom(e){this.core.selected!=null&&(e=e||this.core.selected.id,this.subscribe(`r/${e}/typing`),this.subscribe(`r/${e}/${e}/+/t`),this.subscribe(`r/${e}/${e}/+/d`),this.subscribe(`r/${e}/${e}/+/r`))}unsubscribeRoom(e){this.core.selected!=null&&(e=e||this.core.selected.id,this.unsubscribe(`r/${e}/typing`),this.unsubscribe(`r/${e}/${e}/+/t`),this.unsubscribe(`r/${e}/${e}/+/d`),this.unsubscribe(`r/${e}/${e}/+/r`))}get subscribeTyping(){return this.subscribeRoom.bind(this)}get unsubscribeTyping(){return this.unsubscribeRoom.bind(this)}subscribeUserChannel(){this.subscribe(`${this.core.userData.token}/c`),this.subscribe(`${this.core.userData.token}/n`),this.subscribe(`${this.core.userData.token}/update`)}subscribeUserChannelByToken(e){this.subscribe(`${e}/c`),this.subscribe(`${e}/n`),this.subscribe(`${e}/update`)}unsubscribeUserChannel(){this.unsubscribe(`${this.core.userData.token}/c`),this.unsubscribe(`${this.core.userData.token}/n`),this.unsubscribe(`${this.core.userData.token}/update`)}unsusbcribeUserChannelByToken(e){this.unsubscribe(`${e}/c`),this.unsubscribe(`${e}/n`),this.unsubscribe(`${e}/update`)}publishPresence(e,t=!0){t?this.publish(`u/${e}/s`,1,{retain:!0}):this.publish(`u/${e}/s`,0,{retain:!0})}disconnect(){this.publishPresence(this.core.userData.email,!1),this.unsubscribe(Object.keys(this.mqtt._resubscribeTopics))}subscribeUserPresence(e){this.subscribe(`u/${e}/s`)}unsubscribeUserPresence(e){this.unsubscribe(`u/${e}/s`)}get subscribeRoomPresence(){return this.subscribeUserPresence.bind(this)}get unsubscribeRoomPresence(){return this.unsubscribeUserPresence.bind(this)}publishTyping(e){if(this.core.selected==null)return;const t=this.core.selected.id,r=this.core.user_id;this.publish(`r/${t}/${t}/${r}/t`,e)}}function J_(i,e){const t=Ot(),r={},n=/^r\/[\w]+\/[\w]+\/e$/i;i.mqtt.on("message",(u,a)=>{n.test(u)&&t.emit(u,a)});const o=u=>`r/${u}/${u}/e`;return{publishEvent(u,a){if(Ye.undefined(u))throw new Error("`roomId` required");if(Ye.not.string(u))throw new TypeError("`roomId` must have type of string");if(Ye.undefined(a))throw new Error("`payload` required");if(Ye.not.object(a))throw new TypeError("`payload` must have type of object");const s=JSON.stringify({sender:e,data:a});i.publish(o(u),s)},subscribeEvent(u,a){if(Ye.undefined(u))throw new Error("`roomId` required");if(Ye.not.string(u))throw new TypeError("`roomId` must have type of string");if(Ye.undefined(a))throw new Error("`callback` required");if(Ye.not.function(a))throw new TypeError("`callback` must have type of function");const s=o(u);if(r[s])return;i.subscribe(s);const l=d=>{const _=JSON.parse(d);a(_)};t.on(s,l),r[s]=l},unsubscribeEvent(u){if(Ye.undefined(u))throw new Error("`roomId` required");if(Ye.not.string(u))throw new TypeError("`roomId` must have type of string");const a=o(u);r[a]&&(i.unsubscribe(a),t.off(a,r[a]),r[a]=null,delete r[a])}}}const $p=()=>{},Hp=i=>new Promise(e=>setTimeout(e,i));function X_(i,e,t,r,n){const o=Ot(),u=l=>{const d=nr("api/v2/sdk/sync").param("last_received_comment_id",l).build();return i().get(d).then(_=>{const g=_.body.results,E=g.comments,w=g.meta.last_received_comment_id;return E.sort((q,k)=>q.id-k.id),Promise.resolve({lastMessageId:w,messages:E,interval:e()})}).catch($p)};function a(){return tu(this,null,function*(){let l=0;const d=100,_=()=>i()!=null&&t();for(;;)l+=d,l>=e()&&_()&&(l=0,yield u(r())),yield new Sr(Hp(d))})}return{get synchronize(){return u},get on(){return o.on},get off(){return o.off},run(){return ke(this,null,function*(){try{for(var l=ru(a()),d,_,g;d=!(_=yield l.next()).done;d=!1){let E=_.value;try{if(o.emit("synchronize",Date.now()),(E==null?void 0:E.lastMessageId)!=null&&(E==null?void 0:E.messages)!=null){const w=E.lastMessageId,q=E.messages;w>r()&&(q.forEach(k=>o.emit("message.new",k)),o.emit("last-message-id.new",w))}}catch(w){n("error when sync",w.message),console.log("error when sync",w)}}}catch(_){g=[_]}finally{try{d&&(_=l.return)&&(yield _.call(l))}finally{if(g)throw g[0]}}})}}}function Z_(i,e,t,r,n){const o=Ot(),u=l=>{const d=nr("api/v2/sdk/sync_event").param("start_event_id",l).build();return i().get(d).then(_=>{const g=_.body.events,E=g.map(R=>R.id).sort((R,S)=>R-S).pop(),w=g.filter(R=>R.action_topic==="delivered").map(R=>R.payload.data),q=g.filter(R=>R.action_topic==="read").map(R=>R.payload.data),k=g.filter(R=>R.action_topic==="delete_message").map(R=>R.payload.data),A=g.filter(R=>R.action_topic==="clear_room").map(R=>R.payload.data);return Promise.resolve({lastId:E,messageDelivered:w,messageRead:q,messageDeleted:k,roomCleared:A,interval:e()})}).catch($p)};function a(){return tu(this,null,function*(){let l=0;const d=100,_=()=>i()!=null&&t();for(;;)l+=d,l>=e()&&_()&&(l=0,yield u(r())),yield new Sr(Hp(d))})}return{get synchronize(){return u},get on(){return o.on},get off(){return o.off},run(){return ke(this,null,function*(){try{for(var l=ru(a()),d,_,g;d=!(_=yield l.next()).done;d=!1){let E=_.value;try{const w=E.lastId;w>r()&&(o.emit("last-event-id.new",w),E.messageDelivered.forEach(q=>o.emit("message.delivered",q)),E.messageDeleted.forEach(q=>o.emit("message.deleted",q)),E.messageRead.forEach(q=>o.emit("message.read",q)),E.roomCleared.forEach(q=>o.emit("room.cleared",q)))}catch(w){n("error when sync event",w.message)}}}catch(_){g=[_]}finally{try{d&&(_=l.return)&&(yield _.call(l))}finally{if(g)throw g[0]}}})}}}function ev(i,{isDebug:e=!1,syncInterval:t,getShouldSync:r,syncOnConnect:n,lastCommentId:o,statusLogin:u,enableSync:a,enableSyncEvent:s}){const l=Ot(),d=(...R)=>e?console.log("QSync:",...R):{};let _=0;const g=()=>u()?r()?t():n():0,w=X_(i,g,()=>r()&&a(),o,d);w.on("last-message-id.new",R=>R),w.on("message.new",R=>l.emit("message.new",R)),w.on("synchronize",R=>l.emit("synchronize",R)),w.run().catch(R=>d("got error when sync",R));const k=Z_(i,g,()=>r()&&s(),()=>_,d);return k.on("last-event-id.new",R=>{_=R}),k.on("message.read",R=>{l.emit("message.read",R)}),k.on("message.delivered",R=>l.emit("message.delivered",R)),k.on("message.deleted",R=>l.emit("message.deleted",R)),k.on("room.cleared",R=>l.emit("room.cleared",R)),k.run().catch(R=>d("got error when sync event",R)),{get on(){return l.on},get off(){return l.off},get interval(){return g()},get enabled(){return a()},synchronize(){return ke(this,null,function*(){var p,v;let R=o(),S=yield w.synchronize(R),b=(p=S==null?void 0:S.messages)!=null?p:[],h=(v=S==null?void 0:S.lastMessageId)!=null?v:-1;for(let I of b)l.emit("message.new",I);h>0&&l.emit("last-message-id.new",h)})},synchronizeEvent(){return ke(this,null,function*(){let R=yield k.synchronize(_);try{const S=R.lastId;S>getId()&&(l.emit("last-event-id.new",S),R.messageDelivered.forEach(b=>l.emit("message.delivered",b)),R.messageDeleted.forEach(b=>l.emit("message.deleted",b)),R.messageRead.forEach(b=>l.emit("message.read",b)),R.roomCleared.forEach(b=>l.emit("room.cleared",b)))}catch(S){d("error when sync event",S.message)}})}}}const tv={version:"2.16.2"},dt={MESSAGE_BEFORE_SENT:"message::before-sent",MESSAGE_BEFORE_RECEIVED:"message::before-received"};function rv(){const i={},e=n=>(Array.isArray(i[n])||(i[n]=[]),i[n]);function t(n,o){e(n).push(o);const u=e(n).length;return()=>e(n).splice(u,1)}function r(n,o){return e(n).reduce((u,a)=>Promise.resolve(u).then(a),Promise.resolve(o))}return{trigger:r,intercept:t}}class nv{constructor({httpAdapter:e,refreshToken:t,expiredAt:r,userId:n,onTokenRefreshed:o,getAuthenticationStatus:u}){He(this,"_isExpiredTokenEnabled",!1);He(this,"_refreshToken",null);He(this,"_expiredAt",null);He(this,"_http");He(this,"_onTokenRefreshed");He(this,"_timerId");He(this,"_getAuthenticationStatus");this._http=e,this._refreshToken=t,this._userId=n,this._onTokenRefreshed=o,this._getAuthenticationStatus=u,this._refreshToken!=null&&this._refreshToken===""&&(this._refreshToken=null),r!=null&&r!==""&&(this._expiredAt=new Date(r)),this._isExpiredTokenEnabled=this._refreshToken!=null&&this._expiredAt!=null,this._setTimer(this._expiredAt)}_setTimer(e){var r;this._timerId!=null&&(clearTimeout(this._timerId),this._timerId=null);const t=Math.floor(((r=e==null?void 0:e.getTime())!=null?r:NaN)-Date.now());!isNaN(t)&&t>0&&(this._timerId=setTimeout(()=>{this.refreshAuthToken()},t))}refreshAuthToken(){return ke(this,null,function*(){if(!(this._getAuthenticationStatus()==!1||this._refreshToken==null))return this._http.post("api/v2/sdk/refresh_user_token",{user_id:this._userId,refresh_token:this._refreshToken}).then(e=>{var n;let t=e.body.results,r=t.token;return this._refreshToken=t.refresh_token,(n=this._onTokenRefreshed)==null||n.call(this,r,this._refreshToken,this._expiredAt,this._http.token),this._http.setToken(t.token),t.token_expires_at!=null&&(this._expiredAt=new Date(t.token_expires_at)),this._setTimer(this._expiredAt),t})})}logout(){return ke(this,null,function*(){return this._http.post("api/v2/sdk/logout",{user_id:this._userId,token:this._http.token})})}}let Wp;const iv=Object.freeze({disabled:"UpdateCommentStatusMode.disabled",throttled:"UpdateCommentStatusMode.throttled",enabled:"UpdateCommentStatusMode.enabled"}),vt=class vt{constructor(){He(this,"_pendingComments",[]);He(this,"_pendingCommentsCount",{});He(this,"_readComment",(e,t)=>this._updateStatus(e,t));He(this,"_readCommentT",this._throttle((e,t)=>{this._updateStatus(e,t)},()=>this._throttleDelay));He(this,"_deliverComment",(e,t)=>this._updateStatus(e,void 0,t));He(this,"_deliverCommentT",this._throttle((e,t)=>{this._updateStatus(e,void 0,t)},()=>this._throttleDelay));this.events=Ot(),this.rooms=[],this.selected=null,this.room_name_id_map={},this.pendingCommentId=0,this.uploadedFiles=[],this.chatmateStatus=null,this.version=`WEB_${tv.version}`,this.userData={},this.AppId=null,this.baseURL="https://api.qiscus.com",this.mqttURL="wss://realtime-jogja.qiscus.com:1886/mqtt",this.brokerLbUrl="https://realtime-lb.qiscus.com",this.syncOnConnect=1e4,this.enableEventReport=!1,this.enableRealtime=!0,this.enableRealtimeCheck=!0,this.enableSync=!0,this.enableSyncEvent=!1,this.HTTPAdapter=null,this.expiredTokenAdapter=null,this.realtimeAdapter=null,this.customEventAdapter=null,this.isInit=!1,this.isSynced=!1,this.syncInterval=5e3,this.sync="socket",this.enableLb=!0,this.httpsync=null,this.eventsync=null,this.extras=null,this.last_received_comment_id=0,this.googleMapKey="",this.options={avatar:!0},this.isConfigLoaded=!1,this.updateCommentStatusMode=vt.UpdateCommentStatusMode.enabled,this.updateCommentStatusThrottleDelay=300,this.UI={},this.mode="widget",this.avatar=!0,this.plugins=[],this.isLogin=!1,this.isLoading=!1,this.isInit=!1,this.emoji=!1,this.isTypingStatus="",this.customTemplate=!1,this.templateFunction=null,this.debugMode=!1,this.debugMQTTMode=!1,this._customHeader={},this._forceEnableSync=!0,this.lastReceiveMessages=[],this._hookAdapter=rv(),this._uploadURL=null,this._autoRefreshToken=!1}get uploadURL(){return this._uploadURL||`${this.baseURL}/api/v2/sdk/upload`}set uploadURL(e){this._uploadURL=e}init(e){return ke(this,null,function*(){var a;if(!e.AppId)throw new Error("Please provide valid AppId");this.AppId=e.AppId;const t=e.baseURL!=null&&this.baseURL!==e.baseURL,r=e.mqttURL!=null&&this.mqttURL!==e.mqttURL,n=e.brokerLbURL!=null&&this.brokerLbUrl!==e.brokerLbURL;(t||r)&&!n?(this.logger("force disable load balancing for realtime server, because `baseURL` or `mqttURL` get changed but did not provide `brokerLbURL`"),this.enableLb=!1):e.enableRealtimeLB!=null&&(this.enableLb=e.enableRealtimeLB),e.updateCommentStatusMode!=null&&(this.updateCommentStatusMode=e.updateCommentStatusMode),e.updateCommentStatusThrottleDelay!=null&&(this.updateCommentStatusThrottleDelay=e.updateCommentStatusThrottleDelay),e.baseURL&&(this.baseURL=e.baseURL),e.mqttURL&&(this.mqttURL=e.brokerUrl||e.mqttURL),e.mqttURL&&(this.brokerUrl=e.brokerUrl||e.mqttURL),e.brokerLbURL&&(this.brokerLbUrl=e.brokerLbURL),e.uploadURL&&(this.uploadURL=e.uploadURL),e.sync&&(this.sync=e.sync),e.mode&&(this.mode=e.mode),e.syncInterval&&(this.syncInterval=e.syncInterval||5e3),e.googleMapKey&&(this.googleMapKey=e.googleMapKey),e.allowedFileTypes&&(this.allowedFileTypes=e.allowedFileTypes),e.options&&(this.options=Object.assign({},this.options,e.options)),e.customTemplate&&(this.customTemplate=e.customTemplate),e.templateFunction&&(this.templateFunction=e.templateFunction),e.syncInterval!=null&&(this.syncInterval=e.syncInterval),this.HTTPAdapter=new Do({baseURL:this.baseURL,AppId:this.AppId,userId:this.user_id,version:this.version,getCustomHeader:()=>this._customHeader});const o=(s,l,d)=>l===""&&s!=null&&(typeof s!="string"||s.length>0)?s:l!=null&&(l.length>0||typeof l!="string")?l:d,u=s=>s.includes("wss://")?s:`wss://${s}:1886/mqtt`;this.withConfig=(a=e.withConfig)!=null?a:!0,this.withConfig===!0?yield this.HTTPAdapter.get_request("api/v2/sdk/config").then(s=>(s.status==200?this.isConfigLoaded=!0:this.isConfigLoaded=!1,s.body.results)).then(s=>{const l=this.baseURL,d=this.brokerLbUrl,_=this.mqttURL,g=this.enableRealtime,E=this.enableRealtimeCheck,w=this.syncInterval,q=this.syncOnConnect,k=this.enableEventReport,A={};this.baseURL=o(e.baseURL,s.base_url,l),this.brokerLbUrl=o(e.brokerLbURL,s.broker_lb_url,d),this.mqttURL=u(o(e.mqttURL,s.broker_url,_)),this.enableRealtime=o(e.enableRealtime,s.enable_realtime,g),this.syncInterval=o(e.syncInterval,s.sync_interval,w),this.syncOnConnect=o(e.syncOnConnect,s.sync_on_connect,q),this.enableRealtimeCheck=o(null,s.enable_realtime_check,E),this.enableEventReport=o(null,s.enable_event_report,k),this.extras=o(null,s.extras,A),this.enableSync=o(null,s.enable_sync,this.enableSync),this.enableSyncEvent=o(null,s.enable_sync_event,this.enableSyncEvent),this._autoRefreshToken=o(null,s.auto_refresh_token,!1)}).catch(s=>{this.logger("got error when trying to get app config",s),this.isConfigLoaded=!0}):this.isConfigLoaded=!0,this._getMqttClientId=()=>`${this.AppId}_${this.user_id}_${Date.now()}`,this.realtimeAdapter=new Q_(this.mqttURL,this,this.isLogin,{brokerLbUrl:this.brokerLbUrl,enableLb:this.enableLb,shouldConnect:this.enableRealtime,getClientId:this._getMqttClientId}),this.realtimeAdapter.on("connected",()=>{(this.isLogin||!this.realtimeAdapter.connected)&&(this.last_received_comment_id=this.userData.last_comment_id,this.updateLastReceivedComment(this.last_received_comment_id))}),this.realtimeAdapter.on("close",()=>{}),this.realtimeAdapter.on("reconnect",()=>{var s,l;(l=(s=this.options).onReconnectCallback)==null||l.call(s)}),this.realtimeAdapter.on("message-delivered",({commentId:s,commentUniqueId:l,userId:d})=>this._setDelivered(s,l,d)),this.realtimeAdapter.on("message-read",({commentId:s,commentUniqueId:l,userId:d})=>this._setRead(s,l,d)),this.realtimeAdapter.on("new-message",s=>ke(this,null,function*(){s=yield this._hookAdapter.trigger(dt.MESSAGE_BEFORE_RECEIVED,s),this.events.emit("newmessages",[s])})),this.realtimeAdapter.on("presence",s=>this.events.emit("presence",s)),this.realtimeAdapter.on("comment-deleted",s=>this.events.emit("comment-deleted",s)),this.realtimeAdapter.on("room-cleared",s=>this.events.emit("room-cleared",s)),this.realtimeAdapter.on("typing",s=>this.events.emit("typing",{message:s.message,username:s.userId,room_id:s.roomId})),this.realtimeAdapter.on("message:updated",s=>{this.options.messageUpdatedCallback!=null&&this.options.messageUpdatedCallback(s)}),this.realtimeAdapter.on("room-typing",s=>{this.events.emit("typing",{message:s.text,username:s.sender_name,email:s.sender_id,room_id:s.room_id}),this.options.onRoomTypingCallback!=null&&(this.events.emit("room-typing",s),this.options.onRoomTypingCallback(s))}),this.syncAdapter=ev(()=>this.HTTPAdapter,{syncInterval:()=>this.syncInterval,getShouldSync:()=>this._forceEnableSync&&this.isLogin&&!this.realtimeAdapter.connected,syncOnConnect:()=>this.syncOnConnect,lastCommentId:()=>this.last_received_comment_id,statusLogin:()=>this.isLogin,enableSync:()=>this.enableSync,enableSyncEvent:()=>this.enableSyncEvent}),this.syncAdapter.on("message.new",s=>ke(this,null,function*(){if(s=yield this._hookAdapter.trigger(dt.MESSAGE_BEFORE_RECEIVED,s),this.selected!=null){if(this.selected.comments.findIndex(d=>d.id===s.id||d.unique_id===s.unique_temp_id)===-1){const d=new pt(s);d.room_id===this.selected.id&&(this.selected.comments.push(d),this.sortComments()),this.events.emit("newmessages",[s])}}else this.events.emit("newmessages",[s])})),this.syncAdapter.on("message.delivered",s=>{this._setDelivered(s.comment_id,s.comment_unique_id,s.email)}),this.syncAdapter.on("message.read",s=>{this._setRead(s.comment_id,s.comment_unique_id,s.email)}),this.syncAdapter.on("message.deleted",s=>{s.deleted_messages.forEach(l=>{this.events.emit("comment-deleted",{roomId:l.room_id,commentUniqueIds:l.message_unique_ids,isForEveryone:!0,isHard:!0})})}),this.syncAdapter.on("room.cleared",s=>{s.deleted_rooms.forEach(l=>{this.events.emit("room-cleared",l)})}),this.syncAdapter.on("synchronize",()=>{this._pendingComments.forEach(s=>this._retrySendComment(s))}),this.syncAdapter.on("last-message-id.new",s=>{this.last_received_comment_id=s}),this.customEventAdapter=J_(this.realtimeAdapter,this.user_id),this.setEventListeners()})}_setRead(e,t,r){if(this.selected==null)return;const n=this.selected,o=n.comments.find(a=>a.id===e||a.unique_id===t);if(o==null||o.status==="read")return;const u={participants:n.participants,actor:r,comment_id:e,activeActorId:this.user_id};n.comments.forEach(a=>{a.id<=o.id&&a.markAsRead(u)}),o.isRead&&this.events.emit("comment-read",{comment:o,userId:r})}_setDelivered(e,t,r){if(this.selected==null)return;const n=this.selected,o=n.comments.find(a=>a.id===e||a.unique_id===t);if(o==null||o.status==="read")return;const u={participants:n.participants,actor:r,comment_id:e,activeActorId:this.user_id};n.comments.forEach(a=>{a.id<=o.id&&a.markAsDelivered(u)}),o.isDelivered&&this.events.emit("comment-delivered",{comment:o,userId:r})}setEventListeners(){const e=this;this.authAdapter=new tg(e.HTTPAdapter),this.userData.email!=null&&(this.authAdapter.userId=this.userData.email),e.events.on("start-init",()=>{e.HTTPAdapter=new Do({baseURL:e.baseURL,AppId:e.AppId,userId:e.user_id,version:e.version,getCustomHeader:()=>this._customHeader}),e.HTTPAdapter.setToken(e.userData.token)}),e.events.on("room-changed",t=>{this.logging("room changed",t),e.options.roomChangedCallback&&e.options.roomChangedCallback(t)}),e.events.on("file-uploaded",t=>{e.options.fileUploadedCallback&&e.options.fileUploadedCallback(t)}),e.events.on("profile-updated",t=>{e.username=t.name,e.avatar_url=t.avatar_url,e.options.updateProfileCallback&&e.options.updateProfileCallback(t)}),e.events.on("newmessages",t=>{if(this.logging("newmessages",t),this.lastReceiveMessages.length>0&&this.lastReceiveMessages[0].unique_temp_id===t[0].unique_temp_id){this.logging("lastReceiveMessages double",t);return}this.lastReceiveMessages=t,e._callNewMessagesCallback(t),t.forEach(n=>{e.receiveComment(n.room_id,n.id);const o=e.selected?n.room_id===e.selected.id:!1,u=n.id<=e.last_received_comment_id;if(o){const a=e.selected,s=e.selected.comments[e.selected.comments.length-1];!s.isPending&&!u&&e.user_id!==n.email&&e.readComment(n.room_id,n.id);const l=s.id,d=e.selected.comments.find(g=>g.id===s.comment_before_id);!s.isPending&&!d&&(this.logging("comment before id not found! ",n.comment_before_id),e.synchronize(l));const _=new pt(n);a.receiveComment(_),a.last_comment_id=_.id,a.last_comment_message=_.message}e.updateLastReceivedComment(n.id),this.sortComments()})}),this.events.on("login-success",t=>{this.isLogin=!0,this.userData=t.user,this.last_received_comment_id=this.userData.last_comment_id,this.realtimeAdapter.connected||this.updateLastReceivedComment(this.last_received_comment_id),this.HTTPAdapter=new Do({baseURL:this.baseURL,AppId:this.AppId,userId:this.user_id,version:this.version,getCustomHeader:()=>this._customHeader,expiredTokenAdapterGetter:()=>this.expiredTokenAdapter}),this.HTTPAdapter.setToken(this.userData.token);let r=t.user;this._delayedSync=eg(()=>{this.synchronize(),this.synchronizeEvent()},500),this.expiredTokenAdapter=new nv({httpAdapter:this.HTTPAdapter,refreshToken:r.refresh_token,expiredAt:r.token_expires_at,userId:this.user_id,onTokenRefreshed:(n,o,u,a)=>{this.userData.token=n,this.userData.refresh_token=o,this.userData.token_expires_at=u==null?void 0:u.toJSON(),this.events.emit("token-refreshed",{token:n,refreshToken:o,expiredAt:u,oldToken:a}),this.realtimeAdapter.unsusbcribeUserChannelByToken(a),this.realtimeAdapter.subscribeUserChannelByToken(n),this._delayedSync()},getAuthenticationStatus:()=>this.user_id!=null&&this.isLogin}),this.userAdapter=new og(this.HTTPAdapter),this.roomAdapter=new sg(this.HTTPAdapter),this.realtimeAdapter.subscribeUserChannel(),this.presensePublisherId!=null&&this.presensePublisherId!==-1&&clearInterval(this.presensePublisherId),this.presensePublisherId=setInterval(()=>{this.realtimeAdapter.publishPresence(this.user_id,!0)},3500),this.options.loginSuccessCallback&&this.options.loginSuccessCallback(t),this.authAdapter.userId=this.userData.email,this.authAdapter.refreshToken=this.userData.refresh_token,this.authAdapter.autoRefreshToken=this._autoRefreshToken}),e.events.on("login-error",function(t){e.options.loginErrorCallback&&e.options.loginErrorCallback(t)}),e.events.on("token-refreshed",t=>{var r,n;(n=(r=this.options).authTokenRefreshedCallback)==null||n.call(r,t)}),e.events.on("room-cleared",function(t){if(e.selected){const r=e.selected;e.selected.unique_id===t.unique_id&&(e.selected=null,e.selected=r)}e.options.roomClearedCallback&&e.options.roomClearedCallback(t)}),e.events.on("comment-deleted",function(t){const{roomId:r,commentUniqueIds:n,isForEveryone:o,isHard:u}=t;e.selected&&e.selected.id==r&&n.map(a=>{const s=e.selected.comments.findIndex(d=>d.unique_id===a);s>-1&&(u?e.selected.comments.splice(s,1):e.selected.comments[s].message="this message has been deleted");const l=e.selected.comments[e.selected.comments.length-1];e.selected.last_comment_id=l.id,e.selected.last_comment_message=l.message}),e.options.commentDeletedCallback&&e.options.commentDeletedCallback(t)}),e.events.on("comment-delivered",function(t){if(e.logging("comment-delivered",t),!t)return!1;if(e.options.commentDeliveredCallback)return e.options.commentDeliveredCallback(t)}),e.events.on("chat-room-created",function(t){e.isLoading=!1,e.options.chatRoomCreatedCallback&&e.options.chatRoomCreatedCallback(t)}),e.events.on("group-room-created",function(t){e.isLoading=!1,e.options.groupRoomCreatedCallback&&e.options.groupRoomCreatedCallback(t)}),e.events.on("header-clicked",function(t){e.options.headerClickedCallback&&e.options.headerClickedCallback(t)}),e.events.on("comment-read",function(t){e.logging("comment-read",t),e.options.commentReadCallback&&e.options.commentReadCallback(t)}),e.events.on("presence",({message:t,userId:r})=>{const n=t.split(":");this.chatmateStatus!==n[0]&&(this.chatmateStatus=n[0]===1?"Online":`Last seen ${fm(Number(n[1].substring(0,13)))}`),e.options.presenceCallback&&e.options.presenceCallback(t,r)}),e.events.on("typing",function(t){e.options.typingCallback&&e.options.typingCallback(t)}),e.events.on("message-info",function(t){e.options.messageInfoCallback&&e.options.messageInfoCallback(t)}),e.events.on("participants-added",t=>{t==null||this.selected==null||this.selected.participants.push(...t)}),e.events.on("participants-removed",t=>{if(t==null||this.selected==null)return;const r=this.selected.participants.filter(n=>t.indexOf(n.email)<=-1);this.selected.participants=r}),e.events.on("block-user",function(t){e.options.blockUserCallback&&e.options.blockUserCallback(t)}),e.events.on("unblock-user",function(t){e.options.unblockUserCallback&&e.options.unblockUserCallback(t)})}onReconnectMqtt(){this.options.onReconnectCallback&&this.options.onReconnectedCallback(),this.selected&&this.loadComments(this.selected.id)}_callNewMessagesCallback(e){this.options.newMessagesCallback&&this.options.newMessagesCallback(e)}updateLastReceivedComment(e){this.last_received_comment_id<e&&(this.last_received_comment_id=e)}setUser(e,t,r,n,o){const u=this;u.user_id=e,u.key=t,u.username=r,u.avatar_url=n;let a={email:this.user_id,password:this.key,username:this.username,extras:o?JSON.stringify(o):null};return this.avatar_url&&(a.avatar_url=this.avatar_url),new Promise((s,l)=>{let d=setInterval(()=>{if(!this.isConfigLoaded)this.debugMode&&this.logger("Waiting for init config...");else return clearInterval(d),this.logger("Config Success!"),u.events.emit("start-init"),u.authAdapter.loginOrRegister(a).then(g=>{u.isInit=!0,u.refresh_token=g.user.refresh_token,u.events.emit("login-success",g),this.realtimeAdapter.connect(),s(g)},g=>{u.events.emit("login-error",g),l(g)})},300)})}setUserWithIdentityToken(e){if(!e||!("user"in e))return this.events.emit("login-error",e);this.email=e.user.email,this.user_id=e.user.email,this.key=e.identity_token,this.username=e.user.username,this.avatar_url=e.user.avatar_url,this.isInit=!0;let t=setInterval(()=>{this.isConfigLoaded?(clearInterval(t),this.logger("Config Success!"),this.events.emit("login-success",e)):this.debugMode&&this.logger("Waiting for init config...")},300)}refreshAuthToken(){return this.expiredTokenAdapter.refreshAuthToken()}publishOnlinePresence(e){e===!0?Wp=setInterval(()=>{this.realtimeAdapter.publishPresence(this.user_id,!0)},3500):(clearInterval(this.presensePublisherId),clearInterval(Wp),setTimeout(()=>{this.realtimeAdapter.publishPresence(this.user_id,!1)},3500))}subscribeUserPresence(e){this.realtimeAdapter.subscribeUserPresence(e)}unsubscribeUserPresence(e){this.realtimeAdapter.unsubscribeUserPresence(e)}logout(){return ke(this,null,function*(){yield this.expiredTokenAdapter.logout(),clearInterval(this.presensePublisherId),this.publishOnlinePresence(!1),this.selected=null,this.isInit=!1,this.isLogin=!1,this.realtimeAdapter.disconnect(),this.userData={}})}get synchronize(){return this.syncAdapter.synchronize}get synchronizeEvent(){return this.syncAdapter.synchronizeEvent}disconnect(){this.logout()}setActiveRoom(e){if(this.selected&&(this.realtimeAdapter.unsubscribeTyping(),this.selected.room_type==="single")){const n=this.selected.participants.filter(o=>o.email!==this.user_id);n.length>0&&this.realtimeAdapter.unsubscribeRoomPresence(n[0].email)}e.participants==null&&(e.participants=[]);const t=e.participants.find(n=>n.email!==this.user_id);this.chatmateStatus=null,this.isTypingStatus=null,this.selected=e;const r=setInterval(()=>{this.debugMode&&this.logger("Trying Initial Subscribe"),this.realtimeAdapter!=null?(this.debugMode&&this.logger("MQTT Connected"),clearInterval(r),e.room_type==="single"&&t!=null&&this.realtimeAdapter.subscribeRoomPresence(t.email),this.selected!=null&&!this.selected.isChannel&&(this.realtimeAdapter.subscribeTyping(e.id),this.events.emit("room-changed",this.selected)),this.debugMode&&this.realtimeAdapter==null&&this.logger("Retry")):this.debugMode&&this.logger("MQTT Not Connected, yet")},3e3)}chatTarget(e,t={}){if(this.userData.length!=null)return!1;const r=t?t.message:null,n=t.distinctId;return this.isLoading=!0,this.isTypingStatus="",this.roomAdapter.getOrCreateRoom(e,t,n).then(o=>ke(this,null,function*(){const u=new rr(o);this.updateLastReceivedComment(u.last_comment_id),this.isLoading=!1;const a=d=>ke(this,null,function*(){return yield this._hookAdapter.trigger(dt.MESSAGE_BEFORE_RECEIVED,d)});u.comments=yield Promise.all(u.comments.map(d=>a(d))),this.setActiveRoom(u);const s=u.comments[u.comments.length-1];if(s&&this.readComment(u.id,s.id),this.events.emit("chat-room-created",{room:u}),!r)return u;const l=u.id;return this.sendComment(l,r).then(()=>Promise.resolve(u)).catch(d=>{console.error("Error when submit comment",d)})})).catch(o=>(console.error("Error when creating room",o),this.isLoading=!1,Promise.reject(o)))}chatGroup(e){const t=this;if(t.isInit)return t.getRoomById(e).then(r=>Promise.resolve(r),r=>Promise.reject(r))}getRoomById(e){if(!this.isInit)return;const t=this;return t.isLoading=!0,t.isTypingStatus="",t.roomAdapter.getRoomById(e).then(r=>ke(this,null,function*(){const n=r.results.room,o=[];for(const s of r.results.comments.reverse()){const l=yield this._hookAdapter.trigger(dt.MESSAGE_BEFORE_RECEIVED,s);o.push(l)}const u=new rr(wr(br({},n),{comments:o,name:n.room_name}));t.updateLastReceivedComment(u.last_comment_id),t.setActiveRoom(u),t.isLoading=!1;const a=u.comments[u.comments.length-1];return a&&t.readComment(u.id,a.id),u.isChannel&&this.realtimeAdapter.subscribeChannel(this.AppId,u.unique_id),u})).catch(r=>(console.error("Error getting room by id",r),Promise.reject(r)))}getOrCreateRoomByUniqueId(e,t,r){const n=this;return n.isLoading=!0,n.isTypingStatus="",n.roomAdapter.getOrCreateRoomByUniqueId(e,t,r).then(o=>ke(this,null,function*(){let u=new rr(o);n.updateLastReceivedComment(u.last_comment_id);const a=l=>ke(this,null,function*(){return yield this._hookAdapter.trigger(dt.MESSAGE_BEFORE_RECEIVED,l)});u.comments=yield Promise.all(u.comments.map(l=>a(l))),n.setActiveRoom(u),n.isLoading=!1;const s=u.comments[u.comments.length-1];return s&&n.readComment(u.id,s.id),this.realtimeAdapter.subscribeChannel(this.AppId,u.unique_id),Promise.resolve(u)})).catch(o=>Promise.reject(o))}getOrCreateRoomByChannel(e,t,r){return this.getOrCreateRoomByUniqueId(e,t,r)}sortComments(){this.selected&&this.selected.comments.sort(function(e,t){return e.unix_timestamp-t.unix_timestamp})}loadRoomList(){return ke(this,arguments,function*(e={}){return(yield this.userAdapter.loadRoomList(e)).map(r=>(r.last_comment_id=r.last_comment.id,r.last_comment_message=r.last_comment.message,r.last_comment_message_created_at=r.last_comment.timestamp,r.room_type=r.chat_type,r.comments=[],new rr(r)))})}loadComments(e,t={}){return this.userAdapter.loadComments(e,t).then(r=>ke(this,null,function*(){const n=[];for(const o of r)n.push(yield this._hookAdapter.trigger(dt.MESSAGE_BEFORE_RECEIVED,o));return this.selected!=null&&(this.selected.receiveComments(n.reverse()),this.sortComments()),n}))}loadMore(e,t={}){if(this.selected!=null)return t.last_comment_id=e,t.after=!1,this.loadComments(this.selected.id,t)}registerDeviceToken(e,t=!1){return ke(this,null,function*(){return(yield this.HTTPAdapter.post("api/v2/sdk/set_user_device_token",{device_token:e,device_platform:"rn",is_development:t})).body.results})}removeDeviceToken(e,t=!1){return ke(this,null,function*(){return(yield this.HTTPAdapter.post("api/v2/sdk/remove_user_device_token",{device_token:e,device_platform:"rn",is_development:t})).body.results})}searchMessages(){return ke(this,arguments,function*(e={}){return console.warn("Deprecated: search message will be removed on next release"),(yield this.userAdapter.searchMessages(e)).map(r=>new pt(r))})}updateProfile(e){return this.userAdapter.updateProfile(e).then(t=>(this.events.emit("profile-updated",e),this.userData=t,Promise.resolve(t)),t=>this.logger(t))}getNonce(){return st.post(`${this.baseURL}/api/v2/sdk/auth/nonce`).send().set("qiscus_sdk_app_id",`${this.AppId}`).set("qiscus_sdk_version",`${this.version}`).then(e=>Promise.resolve(e.body.results),e=>Promise.reject(e))}verifyIdentityToken(e){return st.post(`${this.baseURL}/api/v2/sdk/auth/verify_identity_token`).send({identity_token:e}).set("qiscus_sdk_app_id",`${this.AppId}`).set("qiscus_sdk_version",`${this.version}`).then(t=>Promise.resolve(t.body.results),t=>Promise.reject(t))}sendComment(e,t,r,n="text",o,u){return ke(this,null,function*(){var q,k,A,R;const a=this;a.options.prePostCommentCallback&&a.options.prePostCommentCallback(t),a.options.commentFormaterCallback&&(t=a.options.commentFormaterCallback(t)),a.pendingCommentId--;const s={room_id:e,message:t,username_as:this.username,username_real:this.user_id,user_avatar_url:this.userData.avatar_url,user_extras:this.userData.user_extras,id:Math.round(Date.now()*1e6+Date.now()),type:n||"text",timestamp:am(new Date),unique_id:r?String(r):null,payload:jp(()=>JSON.parse(o),o,S=>this.logger("Error when parsing payload",S.message))},l=a.prepareCommentToBeSubmitted(s);if(n==="reply"){var d=JSON.parse(o),_=a.selected.comments.find(S=>S.id===d.replied_comment_id);d.replied_comment_message=_.type==="reply"?_.payload.text:_.message,d.replied_comment_sender_username=_.username_as,l.payload=d}const g=u||a.extras;let E=yield this._hookAdapter.trigger(dt.MESSAGE_BEFORE_SENT,wr(br({},l),{extras:g}));E=a.prepareCommentToBeSubmitted(E),a.selected&&a.selected.comments.push(E);const w=()=>this.userAdapter.postComment(""+e,E.message,E.unique_id,E.type,E.payload,E.extras);try{let S=yield w();if(S=yield this._hookAdapter.trigger(dt.MESSAGE_BEFORE_RECEIVED,S),Object.assign(E,S),!a.selected)return Promise.resolve(E);E.markAsSent(),E.id=S.id,E.before_id=S.comment_before_id,E.unix_timestamp=S.unix_timestamp,(k=(q=this.options).commentSentCallback)==null||k.call(q,{comment:E}),a.events.emit("comment-sent",E),a.sortComments();const b=a._pendingComments.findIndex(h=>h.unique_id===E.unique_id);return b>-1&&a._pendingComments.splice(b,1),E}catch(S){E.markAsFailed();const b=[void 0,408,413,429,500,502,503,504,521,522,524],p=((R=(A=S.message)==null?void 0:A.toLowerCase())!=null?R:"").includes("offline");return(b.includes(S.status)||p)&&(this._pendingComments.push(E),this.logger("Failed sending comment",S)),Promise.reject(S)}})}_retrySendComment(e){return ke(this,null,function*(){var t,r,n;if(this.logger("Retrying send comment",e),this._pendingCommentsCount[e.unique_id]=((t=this._pendingCommentsCount[e.unique_id])!=null?t:0)+1,this._pendingCommentsCount[e.unique_id]>10){this.logger(`Exceeding maximum retry count for comment ${e.unique_id}, not retrying anymore`),(n=(r=this.options).commentRetryExceedCallback)==null||n.call(r,e);const o=this._pendingComments.findIndex(u=>u.unique_id===e.unique_id);return o>-1&&this._pendingComments.splice(o,1),e.markAsFailed(),this.events.emit("comment-retry-exceed",e),Promise.reject(new Error("Exceeding maximum retry count"))}return this.userAdapter.postComment(""+e.room_id,e.message,e.unique_id,e.type,e.payload,e.extras).then(o=>ke(this,null,function*(){var s,l,d,_;if(((s=this.selected)==null?void 0:s.id)!==e.room_id)return o;Object.assign(e,o),e.markAsSent(),e.id=o.id,e.before_id=o.comment_before_id,e.unix_timestamp=o.unix_timestamp;const u=(l=this.selected)==null?void 0:l.comments.findIndex(g=>g.unique_id===e.unique_id);u>-1&&(this.selected.comments[u]=e),this.sortComments(),(_=(d=this.options).commentSentCallback)==null||_.call(d,{comment:e}),this.events.emit("comment-sent",e);const a=this._pendingComments.findIndex(g=>g.unique_id===e.unique_id);return a>-1&&this._pendingComments.splice(a,1),e})).catch(o=>(e.markAsFailed(),Promise.reject(o)))})}getUsers(e="",t=1,r=20){return this.HTTPAdapter.get_request("api/v2/sdk/get_user_list").query({query:e,page:t,limit:r}).then(n=>Promise.resolve(n.body.results))}getParticipants(e,t=1,r=20){return this.HTTPAdapter.get_request("api/v2/sdk/room_participants").query({room_unique_id:e,page:t,limit:r}).then(n=>n.body.results)}getRoomParticipants(e,t=0){return console.warn("`getRoomParticipants` are deprecated, use `getParticipants` instead."),this.HTTPAdapter.get_request("api/v2/sdk/room_participants").query({room_unique_id:e,offset:t}).then(r=>Promise.resolve(r.body.results))}resendComment(e){if(this.selected==null)return;var t=this,r=t.selected,n=r.comments.find(u=>u.id===e.id);const o=t.extras;return this.userAdapter.postComment(""+r.id,n.message,n.unique_id,e.type,e.payload,o).then(u=>(n.markAsSent(),n.id=u.id,n.before_id=u.comment_before_id,new Promise((a,s)=>a(t.selected))),u=>(n.markAsFailed(),new Promise((a,s)=>s(u))))}prepareCommentToBeSubmitted(e){let t=new pt(e),r=`javascript-${Me()}`;return e.unique_id&&(r=e.unique_id),t.attachUniqueId(r),t.markAsPending(),t.isDelivered=!1,t.isSent=!1,t.isRead=!1,t.unix_timestamp=Math.round(new Date().getTime()/1e3),t}updateRoom(e){return this.roomAdapter.updateRoom(e)}removeSelectedRoomParticipants(e=[],t="id"){if(Ye.not.array(e))return Promise.reject(new Error("`values` must have type of array"));const r=this.selected.participants;if(!r)return Promise.reject(new Error("Nothing selected room chat."));let n=r;return t==="id"&&(n=r.filter(o=>e.indexOf(o.id)<=-1)),t==="email"&&(n=r.filter(o=>e.indexOf(o.email)<=-1)),t==="username"&&(n=r.filter(o=>e.indexOf(o.username)<=-1)),this.selected.participants=n,Promise.resolve(r)}createGroupRoom(e,t,r){const n=this;if(!this.isLogin)throw new Error("Please initiate qiscus SDK first");return new Zy(this.roomAdapter).withName(e).withOptions(r).addParticipants(t).create().then(o=>(n.events.emit("group-room-created",o),Promise.resolve(o)))}addParticipantsToGroup(e,t){const r=this;if(!Array.isArray(t))throw new Error("emails' must be type of Array");return r.roomAdapter.addParticipantsToGroup(e,t).then(n=>(r.events.emit("participants-added",n),Promise.resolve(n)),n=>Promise.reject(n))}removeParticipantsFromGroup(e,t){return Ye.not.array(t)?Promise.reject(new Error("`emails` must have type of array")):this.roomAdapter.removeParticipantsFromGroup(e,t).then(r=>(this.events.emit("participants-removed",t),Promise.resolve(r)))}getBlockedUser(e=1,t=20){return this.userAdapter.getBlockedUser(e,t).then(n=>Promise.resolve(n),n=>Promise.reject(n))}blockUser(e){const t=this;return t.userAdapter.blockUser(e).then(r=>(t.events.emit("block-user",r),Promise.resolve(r)),r=>Promise.reject(r))}unblockUser(e){const t=this;return t.userAdapter.unblockUser(e).then(r=>(t.events.emit("unblock-user",r),Promise.resolve(r)),r=>Promise.reject(r))}getUserPresences(e=[]){if(Ye.not.array(e))return Promise.reject(new Error("`email` must have type of array"));const t=this;return t.userAdapter.getUserPresences(e).then(r=>(t.events.emit("user-status",r),Promise.resolve(r)),r=>Promise.reject(r))}upload(e,t){let r=st.post(this.uploadURL);return r=this.HTTPAdapter.setupHeaders(r),r.attach("file",e).on("progress",n=>{n.direction==="upload"&&t(null,n)}).then(n=>{const o=n.body.results.file.url;return t(null,null,n.body.results.file.url),Promise.resolve(o)}).catch(n=>(t(n),Promise.reject(n)))}uploadFile(e,t){const r=this;var n=new FormData;n.append("file",t);var o=new XMLHttpRequest;o.open("POST",`${r.baseURL}/api/v2/sdk/upload`,!0),o.setRequestHeader("qiscus_sdk_app_id",`${r.AppId}`),o.setRequestHeader("qiscus_sdk_user_id",`${r.user_id}`),o.setRequestHeader("qiscus_sdk_token",`${r.userData.token}`),o.onload=function(){if(o.status===200){var u=JSON.parse(o.response).results.file.url;return r.events.emit("fileupload",u),r.sendComment(e,`[file] ${u} [/file]`)}else return Promise.reject(o)},o.send(n)}addUploadedFile(e,t){this.uploadedFiles.push(new ov(e,t))}removeUploadedFile(e,t){const r=this.uploadedFiles.findIndex(n=>n.name===e&&n.roomId===t);this.uploadedFiles.splice(r,1)}publishTyping(e){this.realtimeAdapter.publishTyping(e)}getRoomsInfo(e){return this.userAdapter.getRoomsInfo(e)}deleteComment(e,t,r,n){if(!Array.isArray(t))throw new Error("unique ids' must be type of Array");return this.userAdapter.deleteComment(e,t,r,n).then(o=>(this.events.emit("comment-deleted",{roomId:e,commentUniqueIds:t,isForEveryone:r,isHard:n}),Promise.resolve(o)),o=>Promise.reject(o))}clearRoomsCache(){if(this.selected){this.room_name_id_map={[this.selected.name]:this.selected.id};const e=this.rooms.length;let t=this.rooms.findIndex(r=>r.id===this.selected.id);t+1!==e&&this.rooms.splice(t+1,e-(t+1)),t=this.rooms.findIndex(r=>r.id===this.selected.id),t>0&&this.rooms.length>1&&this.rooms.splice(1,this.rooms.length-1)}}exitChatRoom(){this.realtimeAdapter.unsubscribeTyping(),jp(()=>this.selected.participants.filter(e=>e.email!==this.user_id).map(e=>e.email),null,this.noop,e=>e.forEach(t=>this.realtimeAdapter.unsubscribeRoomPresence(t))),this.selected=null}clearRoomMessages(e){if(!Array.isArray(e))throw new Error("room_ids must be type of array");return this.userAdapter.clearRoomMessages(e)}logging(e,t={}){this.debugMode&&console.log(e,t)}getTotalUnreadCount(){return this.roomAdapter.getTotalUnreadCount().then(e=>Promise.resolve(e),e=>Promise.reject(e))}getRoomUnreadCount(){return this.roomAdapter.getRoomUnreadCount()}publishEvent(...e){this.customEventAdapter.publishEvent(...e)}subscribeEvent(...e){this.customEventAdapter.subscribeEvent(...e)}unsubscribeEvent(...e){this.customEventAdapter.unsubscribeEvent(...e)}setCustomHeader(e){if(Ye.not.json(e))throw new TypeError("`headers` must have type of object");this._customHeader=e}getUserProfile(){return this.userAdapter.getProfile()}get Interceptor(){return dt}intercept(e,t){return this._hookAdapter.intercept(e,t)}getThumbnailURL(e){const t=/^https?:\/\/\S+(\/upload\/)\S+(\.\w+)$/i;return e.replace(t,(r,n,o)=>r.replace(n,"/upload/w_320,h_320,c_limit/").replace(o,".png"))}getBlurryThumbnailURL(e){const t=/^https?:\/\/\S+(\/upload\/)\S+(\.\w+)$/i;return e.replace(t,(r,n,o)=>r.replace(n,"/upload/w_320,h_320,c_limit,e_blur:300/").replace(o,".png"))}get logger(){return this.debugMode?console.log.bind(console,"Qiscus ->"):this.noop}noop(){}get _throttleDelay(){return this.updateCommentStatusMode===vt.UpdateCommentStatusMode.enabled?0:this.updateCommentStatusThrottleDelay||300}get _updateStatusEnabled(){return this.updateCommentStatusMode!==vt.UpdateCommentStatusMode.disabled}_updateStatus(e,t=null,r=null){const n=r!=null,o=t!=null;this.selected!=null&&this.selected.id;const u=this.selected!=null&&this.selected.isChannel||!1,a=!this._updateStatusEnabled,s=(()=>{if(o)return"read";if(n)return"receive"})(),l=!(u||n&&a);if(this.debugMode&&(console.group("update-command-status"),console.log("run:",s,`on: roomId(${e}) commentId(${t||r})`),console.log("is able to run command?",l),console.groupEnd()),!l)return!1;this.userAdapter.updateCommentStatus(e,t,r).catch(d=>{})}readComment(e,t){return this.updateCommentStatusMode===vt.UpdateCommentStatusMode.enabled?this._readComment(e,t):this._readCommentT(e,t)}receiveComment(e,t){return this.updateCommentStatusMode===vt.UpdateCommentStatusMode.enabled?this._deliverComment(e,t):this._deliverCommentT(e,t)}_throttle(e,t){let r=!1;return(...n)=>{let o=t();r||(e(...n),r=!0,setTimeout(()=>r=!1,o))}}searchMessage(){return ke(this,arguments,function*({query:e,roomIds:t=[],userId:r,type:n,roomType:o,page:u,limit:a}={}){const s="api/v2/sdk/search",l=["group","single","channel"].some(_=>_===o);if(o!=null&&!l)return Promise.reject("Invalid room type, valid room type are: `group`, `single`, and `channel`");const d=(_=>{const g=_==null?void 0:_==="single"?"single":"group",E=_==null?void 0:_==="channel";return{type:g,isPublic:E}})(o);return this.HTTPAdapter.post_json(s,{token:this.token,query:e,sender:r,type:n,room_ids:t.map(_=>String(_)),room_type:d.type||void 0,is_public:d.isPublic||void 0,page:u,limit:a}).then(_=>_.body)})}getFileList(){return ke(this,arguments,function*({roomIds:e=[],fileType:t,page:r,limit:n,sender:o,userId:u,includeExtensions:a,excludeExtensions:s}={}){const l="api/v2/sdk/file_list";if(!this.isLogin)return Promise.reject("You need to login to use this method");o===void 0&&(o=this.user_id),u===void 0&&(o=u=this.user_id);let d={room_ids:e.map(_=>String(_)),file_type:t,page:r,limit:n,include_extensions:a,exclude_extensions:s};return o!=null&&(d.sender=o),this.HTTPAdapter.post_json(l,d).then(_=>_.body)})}_generateUniqueId(){return`javascript-${Me()}`}generateMessage({roomId:e,text:t,extras:r}){const n=Date.now();return new pt({id:n,message:t,room_id:e,extras:r,timestamp:new Date,unique_id:this._generateUniqueId(),before_id:0,username:this.userData.username,email:this.userData.email,status:"pending",type:"text"})}generateFileAttachmentMessage({roomId:e,caption:t,url:r,text:n="File attachment",extras:o,filename:u,size:a}){const s=Date.now();return new pt({id:s,message:n,room_id:e,extras:o,timestamp:new Date,unique_id:this._generateUniqueId(),before_id:0,username:this.userData.username,email:this.userData.email,status:"pending",type:"file_attachment",payload:{url:r,file_name:u,size:a,caption:t}})}generateCustomMessage({roomId:e,text:t,type:r,payload:n,extras:o}){const u=Date.now();return new pt({id:u,message:t,room_id:e,extras:o,timestamp:new Date,unique_id:this._generateUniqueId(),before_id:0,username:this.userData.username,email:this.userData.email,status:"pending",type:"custom",payload:{type:r,content:n}})}generateReplyMessage({roomId:e,text:t,repliedMessage:r,extras:n}){const o=Date.now();return new pt({id:o,message:t,room_id:e,extras:n,timestamp:new Date,unique_id:this._generateUniqueId(),before_id:0,username:this.userData.username,email:this.userData.email,status:"pending",type:"reply",payload:{text:t,replied_comment_id:r.id,replied_comment_message:r.message,replied_comment_type:r.type,replied_comment_payload:r.payload,replied_comment_sender_username:r.username_as,replied_comment_sender_email:r.username_real}})}updateMessage(e){return ke(this,null,function*(){return this.userAdapter.updateMessage(e)})}onMessageUpdated(e){return this.realtimeAdapter.on("message:updated",e),()=>this.realtimeAdapter.off("message:updated",e)}closeRealtimeConnection(){return ke(this,null,function*(){return this.realtimeAdapter.closeConnection()})}openRealtimeConnection(){return ke(this,null,function*(){return this.realtimeAdapter.openConnection()})}startSync(){return ke(this,null,function*(){this._forceEnableSync=!0})}stopSync(){return ke(this,null,function*(){this._forceEnableSync=!1})}};He(vt,"UpdateCommentStatusMode",iv),He(vt,"Interceptor",dt);let Qa=vt;class ov{constructor(e,t){this.name=e,this.roomId=t,this.progress=0}}return Qa}));
26
+ `)&&(K=K.replace(z,"%0A")),K.includes("\r")&&(K=K.replace(Y,"%0D")),K.includes(" ")&&(K=K.replace(T,"%09")),K}var le=function(pe){if(typeof pe=="undefined")throw new TypeError('The "domain" argument must be specified');return new L("http://"+pe).hostname},Se=function(pe){if(typeof pe=="undefined")throw new TypeError('The "domain" argument must be specified');return new L("http://"+pe).hostname},Pe=function(pe){var X=new L("file://"),Te=J(pe),qe=pe.charCodeAt(pe.length-1);return qe===O&&Te[Te.length-1]!=="/"&&(Te+="/"),X.pathname=ye(Te),X},ue=function(pe){if(!ee(pe)&&typeof pe!="string")throw new TypeError('The "path" argument must be of type string or an instance of URL. Received type '+typeof pe+" ("+pe+")");var X=new L(pe);if(X.protocol!=="file:")throw new TypeError("The URL must be of scheme file");return ae(X)},je=function(pe,X){var Te,qe,$e,Be;if(X===void 0&&(X={}),!(pe instanceof L))return be(pe);if(typeof X!="object"||X===null)throw new TypeError('The "options" argument must be of type object.');var Ie=(Te=X.auth)!=null?Te:!0,x=(qe=X.fragment)!=null?qe:!0,f=($e=X.search)!=null?$e:!0;(Be=X.unicode)!=null;var m=new L(pe.toString());return Ie||(m.username="",m.password=""),x||(m.hash=""),f||(m.search=""),m.toString()},De={format:je,parse:G,resolve:re,resolveObject:oe,Url:j,URL:L,URLSearchParams:M,domainToASCII:le,domainToUnicode:Se,pathToFileURL:Pe,fileURLToPath:ue};e.URL=L,e.URLSearchParams=M,e.Url=j,e.default=De,e.domainToASCII=le,e.domainToUnicode=Se,e.fileURLToPath=ue,e.format=je,e.parse=G,e.pathToFileURL=Pe,e.resolve=re,e.resolveObject=oe,e=i.exports=De})(mr,mr.exports)),mr.exports}var La,Sp;function Ep(){if(Sp)return La;Sp=1;var i=null;return La=i,La}var Fa,Ip;function Tp(){if(Ip)return Fa;Ip=1;var i=Ep(),e=Rt()("mqttjs:tcp");function t(r,n){var o,u;return n.port=n.port||1883,n.hostname=n.hostname||n.host||"localhost",o=n.port,u=n.hostname,e("port %d and host %s",o,u),i.createConnection(o,u)}return Fa=t,Fa}var Ua,Rp;function Na(){if(Rp)return Ua;Rp=1;var i=Ep(),e=Rt()("mqttjs:tls");function t(r,n){var o;n.port=n.port||8883,n.host=n.hostname||n.host||"localhost",n.servername=n.host,n.rejectUnauthorized=n.rejectUnauthorized!==!1,delete n.path,e("port %d host %s rejectUnauthorized %b",n.port,n.host,n.rejectUnauthorized),o=i.connect(n),o.on("secureConnect",function(){n.rejectUnauthorized&&!o.authorized?o.emit("error",new Error("TLS not authorized")):o.removeListener("error",u)});function u(a){n.rejectUnauthorized&&r.emit("error",a),o.end()}return o.on("error",u),o}return Ua=t,Ua}var gr={exports:{}},ja,Ap;function F_(){if(Ap)return ja;Ap=1,ja=i;function i(e,t){if(e&&t)return i(e)(t);if(typeof e!="function")throw new TypeError("need wrapper function");return Object.keys(e).forEach(function(n){r[n]=e[n]}),r;function r(){for(var n=new Array(arguments.length),o=0;o<n.length;o++)n[o]=arguments[o];var u=e.apply(this,n),a=n[n.length-1];return typeof u=="function"&&u!==a&&Object.keys(a).forEach(function(s){u[s]=a[s]}),u}}return ja}var Op;function U_(){if(Op)return gr.exports;Op=1;var i=F_();gr.exports=i(e),gr.exports.strict=i(t),e.proto=e(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return e(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return t(this)},configurable:!0})});function e(r){var n=function(){return n.called?n.value:(n.called=!0,n.value=r.apply(this,arguments))};return n.called=!1,n}function t(r){var n=function(){if(n.called)throw new Error(n.onceError);return n.called=!0,n.value=r.apply(this,arguments)},o=r.name||"Function wrapped with `once`";return n.onceError=o+" shouldn't be called more than once",n.called=!1,n}return gr.exports}var $a,xp;function N_(){if(xp)return $a;xp=1;var i=U_(),e=function(){},t=xe.Bare?queueMicrotask:Re.nextTick.bind(Re),r=function(u){return u.setHeader&&typeof u.abort=="function"},n=function(u){return u.stdio&&Array.isArray(u.stdio)&&u.stdio.length===3},o=function(u,a,s){if(typeof a=="function")return o(u,null,a);a||(a={}),s=i(s||e);var l=u._writableState,d=u._readableState,_=a.readable||a.readable!==!1&&u.readable,g=a.writable||a.writable!==!1&&u.writable,E=!1,w=function(){u.writable||q()},q=function(){g=!1,_||s.call(u)},k=function(){_=!1,g||s.call(u)},A=function(p){s.call(u,p?new Error("exited with error code: "+p):null)},R=function(p){s.call(u,p)},S=function(){t(b)},b=function(){if(!E){if(_&&!(d&&d.ended&&!d.destroyed))return s.call(u,new Error("premature close"));if(g&&!(l&&l.ended&&!l.destroyed))return s.call(u,new Error("premature close"))}},h=function(){u.req.on("finish",q)};return r(u)?(u.on("complete",q),u.on("abort",S),u.req?h():u.on("request",h)):g&&!l&&(u.on("end",w),u.on("close",w)),n(u)&&u.on("exit",A),u.on("end",k),u.on("finish",q),a.error!==!1&&u.on("error",R),u.on("close",S),function(){E=!0,u.removeListener("complete",q),u.removeListener("abort",S),u.removeListener("request",h),u.req&&u.req.removeListener("finish",q),u.removeListener("end",w),u.removeListener("close",w),u.removeListener("finish",q),u.removeListener("exit",A),u.removeListener("end",k),u.removeListener("error",R),u.removeListener("close",S)}};return $a=o,$a}var Ha,Cp;function j_(){if(Cp)return Ha;Cp=1,Ha=i;function i(t){var r=t._readableState;return r?r.objectMode||typeof t._duplexState=="number"?t.read():t.read(e(r)):null}function e(t){if(t.buffer.length){var r=t.bufferIndex||0;if(t.buffer.head)return t.buffer.head.data.length;if(t.buffer.length-r>0&&t.buffer[r])return t.buffer[r].length}return t.length}return Ha}var Wa,kp;function Ya(){if(kp)return Wa;kp=1;var i=Tt(),e=N_(),t=_t(),r=j_(),n=we.from&&we.from!==Uint8Array.from?we.from([0]):new we([0]),o=function(g,E){g._corked?g.once("uncork",E):E()},u=function(g,E){g._autoDestroy&&g.destroy(E)},a=function(g,E){return function(w){w?u(g,w.message==="premature close"?null:w):E&&!g._ended&&g.end()}},s=function(g,E){if(!g||g._writableState&&g._writableState.finished)return E();if(g._writableState)return g.end(E);g.end(),E()},l=function(){},d=function(g){return new i.Readable({objectMode:!0,highWaterMark:16}).wrap(g)},_=function(g,E,w){if(!(this instanceof _))return new _(g,E,w);i.Duplex.call(this,w),this._writable=null,this._readable=null,this._readable2=null,this._autoDestroy=!w||w.autoDestroy!==!1,this._forwardDestroy=!w||w.destroy!==!1,this._forwardEnd=!w||w.end!==!1,this._corked=1,this._ondrain=null,this._drained=!1,this._forwarding=!1,this._unwrite=null,this._unread=null,this._ended=!1,this.destroyed=!1,g&&this.setWritable(g),E&&this.setReadable(E)};return t(_,i.Duplex),_.obj=function(g,E,w){return w||(w={}),w.objectMode=!0,w.highWaterMark=16,new _(g,E,w)},_.prototype.cork=function(){++this._corked===1&&this.emit("cork")},_.prototype.uncork=function(){this._corked&&--this._corked===0&&this.emit("uncork")},_.prototype.setWritable=function(g){if(this._unwrite&&this._unwrite(),this.destroyed){g&&g.destroy&&g.destroy();return}if(g===null||g===!1){this.end();return}var E=this,w=e(g,{writable:!0,readable:!1},a(this,this._forwardEnd)),q=function(){var A=E._ondrain;E._ondrain=null,A&&A()},k=function(){E._writable.removeListener("drain",q),w()};this._unwrite&&Re.nextTick(q),this._writable=g,this._writable.on("drain",q),this._unwrite=k,this.uncork()},_.prototype.setReadable=function(g){if(this._unread&&this._unread(),this.destroyed){g&&g.destroy&&g.destroy();return}if(g===null||g===!1){this.push(null),this.resume();return}var E=this,w=e(g,{writable:!1,readable:!0},a(this)),q=function(){E._forward()},k=function(){E.push(null)},A=function(){E._readable2.removeListener("readable",q),E._readable2.removeListener("end",k),w()};this._drained=!0,this._readable=g,this._readable2=g._readableState?g:d(g),this._readable2.on("readable",q),this._readable2.on("end",k),this._unread=A,this._forward()},_.prototype._read=function(){this._drained=!0,this._forward()},_.prototype._forward=function(){if(!(this._forwarding||!this._readable2||!this._drained)){this._forwarding=!0;for(var g;this._drained&&(g=r(this._readable2))!==null;)this.destroyed||(this._drained=this.push(g));this._forwarding=!1}},_.prototype.destroy=function(g,E){if(E||(E=l),this.destroyed)return E(null);this.destroyed=!0;var w=this;Re.nextTick(function(){w._destroy(g),E(null)})},_.prototype._destroy=function(g){if(g){var E=this._ondrain;this._ondrain=null,E?E(g):this.emit("error",g)}this._forwardDestroy&&(this._readable&&this._readable.destroy&&this._readable.destroy(),this._writable&&this._writable.destroy&&this._writable.destroy()),this.emit("close")},_.prototype._write=function(g,E,w){if(!this.destroyed){if(this._corked)return o(this,this._write.bind(this,g,E,w));if(g===n)return this._finish(w);if(!this._writable)return w();this._writable.write(g)===!1?this._ondrain=w:this.destroyed||w()}},_.prototype._finish=function(g){var E=this;this.emit("preend"),o(this,function(){s(E._forwardEnd&&E._writable,function(){E._writableState.prefinished===!1&&(E._writableState.prefinished=!0),E.emit("prefinish"),o(E,g)})})},_.prototype.end=function(g,E,w){return typeof g=="function"?this.end(null,null,g):typeof E=="function"?this.end(g,null,E):(this._ended=!0,g&&this.write(g),!this._writableState.ending&&!this._writableState.destroyed&&this.write(n),i.Writable.prototype.end.call(this,w))},Wa=_,Wa}var Ga,qp;function Mp(){if(qp)return Ga;qp=1;var i=Tt().Transform,e=Ya(),t,r,n;function o(){var d=new i;return d._write=function(_,g,E){t.send({data:_.buffer,success:function(){E()},fail:function(w){E(new Error(w))}})},d._flush=function(g){t.close({success:function(){g()}})},d}function u(d){d.hostname||(d.hostname="localhost"),d.path||(d.path="/"),d.wsOptions||(d.wsOptions={})}function a(d,_){var g=d.protocol==="wxs"?"wss":"ws",E=g+"://"+d.hostname+d.path;return d.port&&d.port!==80&&d.port!==443&&(E=g+"://"+d.hostname+":"+d.port+d.path),typeof d.transformWsUrl=="function"&&(E=d.transformWsUrl(E,d,_)),E}function s(){t.onOpen(function(){n.setReadable(r),n.setWritable(r),n.emit("connect")}),t.onMessage(function(d){var _=d.data;_ instanceof ArrayBuffer?_=we.from(_):_=we.from(_,"utf8"),r.push(_)}),t.onClose(function(){n.end(),n.destroy()}),t.onError(function(d){n.destroy(new Error(d.errMsg))})}function l(d,_){if(_.hostname=_.hostname||_.host,!_.hostname)throw new Error("Could not determine host. Specify host manually.");var g=_.protocolId==="MQIsdp"&&_.protocolVersion===3?"mqttv3.1":"mqtt";u(_);var E=a(_,d);t=wx.connectSocket({url:E,protocols:[g]}),r=o(),n=e.obj(),n._destroy=function(q,k){t.close({success:function(){k&&k(q)}})};var w=n.destroy;return n.destroy=function(){n.destroy=w;var q=this;setTimeout(function(){t.close({fail:function(){q._destroy(new Error)}})},0)}.bind(n),s(),n}return Ga=l,Ga}var za,Pp;function Bp(){if(Pp)return za;Pp=1;var i=Tt().Transform,e=Ya(),t,r,n,o=!1;function u(){var _=new i;return _._write=function(g,E,w){t.sendSocketMessage({data:g.buffer,success:function(){w()},fail:function(){w(new Error)}})},_._flush=function(E){t.closeSocket({success:function(){E()}})},_}function a(_){_.hostname||(_.hostname="localhost"),_.path||(_.path="/"),_.wsOptions||(_.wsOptions={})}function s(_,g){var E=_.protocol==="alis"?"wss":"ws",w=E+"://"+_.hostname+_.path;return _.port&&_.port!==80&&_.port!==443&&(w=E+"://"+_.hostname+":"+_.port+_.path),typeof _.transformWsUrl=="function"&&(w=_.transformWsUrl(w,_,g)),w}function l(){o||(o=!0,t.onSocketOpen(function(){n.setReadable(r),n.setWritable(r),n.emit("connect")}),t.onSocketMessage(function(_){if(typeof _.data=="string"){var g=we.from(_.data,"base64");r.push(g)}else{var E=new FileReader;E.addEventListener("load",function(){var w=E.result;w instanceof ArrayBuffer?w=we.from(w):w=we.from(w,"utf8"),r.push(w)}),E.readAsArrayBuffer(_.data)}}),t.onSocketClose(function(){n.end(),n.destroy()}),t.onSocketError(function(_){n.destroy(_)}))}function d(_,g){if(g.hostname=g.hostname||g.host,!g.hostname)throw new Error("Could not determine host. Specify host manually.");var E=g.protocolId==="MQIsdp"&&g.protocolVersion===3?"mqttv3.1":"mqtt";a(g);var w=s(g,_);return t=g.my,t.connectSocket({url:w,protocols:E}),r=u(),n=e.obj(),l(),n}return za=d,za}var _r={exports:{}},Va,Dp;function $_(){return Dp||(Dp=1,Va=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}),Va}var Lp;function Fp(){if(Lp)return _r.exports;Lp=1;const i=$_(),e=Rt()("mqttjs:ws"),t=Ya(),r=Tt().Transform;let n=["rejectUnauthorized","ca","cert","key","pfx","passphrase"];const o=typeof Re!="undefined"&&Re.title==="browser"||typeof __webpack_require__=="function";function u(E,w){let q=E.protocol+"://"+E.hostname+":"+E.port+E.path;return typeof E.transformWsUrl=="function"&&(q=E.transformWsUrl(q,E,w)),q}function a(E){let w=E;return E.hostname||(w.hostname="localhost"),E.port||(E.protocol==="wss"?w.port=443:w.port=80),E.path||(w.path="/"),E.wsOptions||(w.wsOptions={}),!o&&E.protocol==="wss"&&n.forEach(function(q){E.hasOwnProperty(q)&&!E.wsOptions.hasOwnProperty(q)&&(w.wsOptions[q]=E[q])}),w}function s(E){let w=a(E);if(w.hostname||(w.hostname=w.host),!w.hostname){if(typeof document=="undefined")throw new Error("Could not determine host. Specify host manually.");const q=new URL(document.URL);w.hostname=q.hostname,w.port||(w.port=q.port)}return w.objectMode===void 0&&(w.objectMode=!(w.binary===!0||w.binary===void 0)),w}function l(E,w,q){e("createWebSocket"),e("protocol: "+q.protocolId+" "+q.protocolVersion);const k=q.protocolId==="MQIsdp"&&q.protocolVersion===3?"mqttv3.1":"mqtt";return e("creating new Websocket for url: "+w+" and protocol: "+k),new i(w,[k],q.wsOptions)}function d(E,w){const q=w.protocolId==="MQIsdp"&&w.protocolVersion===3?"mqttv3.1":"mqtt";let k=u(w,E),A=new WebSocket(k,[q]);return A.binaryType="arraybuffer",A}function _(E,w){e("streamBuilder");let q=a(w);const k=u(q,E);let A=l(E,k,q),R=i.createWebSocketStream(A,q.wsOptions);return R.url=k,A.on("close",()=>{R.destroy()}),R}function g(E,w){e("browserStreamBuilder");let q;const A=s(w).browserBufferSize||1024*512,R=w.browserBufferTimeout||1e3,S=!w.objectMode;let b=d(E,w),h=v(w,ce,oe);w.objectMode||(h._writev=P),h.on("close",()=>{b.close()});const p=typeof b.addEventListener!="undefined";b.readyState===b.OPEN?q=h:(q=q=t(void 0,void 0,w),w.objectMode||(q._writev=P),p?b.addEventListener("open",I):b.onopen=I),q.socket=b,p?(b.addEventListener("close",B),b.addEventListener("error",H),b.addEventListener("message",V)):(b.onclose=B,b.onerror=H,b.onmessage=V);function v(ne,se,he){let J=new r({objectModeMode:ne.objectMode});return J._write=se,J._flush=he,J}function I(){q.setReadable(h),q.setWritable(h),q.emit("connect")}function B(){q.end(),q.destroy()}function H(ne){q.destroy(ne)}function V(ne){let se=ne.data;se instanceof ArrayBuffer?se=we.from(se):se=we.from(se,"utf8"),h.push(se)}function P(ne,se){const he=new Array(ne.length);for(let J=0;J<ne.length;J++)typeof ne[J].chunk=="string"?he[J]=we.from(ne[J],"utf8"):he[J]=ne[J].chunk;this._write(we.concat(he),"binary",se)}function ce(ne,se,he){b.bufferedAmount>A&&setTimeout(ce,R,ne,se,he),S&&typeof ne=="string"&&(ne=we.from(ne,"utf8"));try{b.send(ne)}catch(J){return he(J)}he()}function oe(ne){b.close(),ne()}return q}return o?_r.exports=g:_r.exports=_,_r.exports}var Up;function H_(){if(Up)return kt.exports;Up=1;var i=O_(),e=Nd(),t=L_(),r=jo(),n=Rt()("mqttjs"),o={};typeof Re!="undefined"&&Re.title!=="browser"||typeof __webpack_require__!="function"?(o.mqtt=Tp(),o.tcp=Tp(),o.ssl=Na(),o.tls=Na(),o.mqtts=Na()):(o.wx=Mp(),o.wxs=Mp(),o.ali=Bp(),o.alis=Bp()),o.ws=Fp(),o.wss=Fp();function u(s){var l;s.auth&&(l=s.auth.match(/^(.+):(.+)$/),l?(s.username=l[1],s.password=l[2]):s.username=s.auth)}function a(s,l){if(n("connecting to an MQTT broker..."),typeof s=="object"&&!l&&(l=s,s=null),l=l||{},s){var d=t.parse(s,!0);if(d.port!=null&&(d.port=Number(d.port)),l=r(d,l),l.protocol===null)throw new Error("Missing protocol");l.protocol=l.protocol.replace(/:$/,"")}if(u(l),l.query&&typeof l.query.clientId=="string"&&(l.clientId=l.query.clientId),l.cert&&l.key)if(l.protocol){if(["mqtts","wss","wxs","alis"].indexOf(l.protocol)===-1)switch(l.protocol){case"mqtt":l.protocol="mqtts";break;case"ws":l.protocol="wss";break;case"wx":l.protocol="wxs";break;case"ali":l.protocol="alis";break;default:throw new Error('Unknown protocol for secure connection: "'+l.protocol+'"!')}}else throw new Error("Missing secure protocol key");if(!o[l.protocol]){var _=["mqtts","wss"].indexOf(l.protocol)!==-1;l.protocol=["mqtt","mqtts","ws","wss","wx","wxs","ali","alis"].filter(function(w,q){return _&&q%2===0?!1:typeof o[w]=="function"})[0]}if(l.clean===!1&&!l.clientId)throw new Error("Missing clientId for unclean clients");l.protocol&&(l.defaultProtocol=l.protocol);function g(w){return l.servers&&((!w._reconnectCount||w._reconnectCount===l.servers.length)&&(w._reconnectCount=0),l.host=l.servers[w._reconnectCount].host,l.port=l.servers[w._reconnectCount].port,l.protocol=l.servers[w._reconnectCount].protocol?l.servers[w._reconnectCount].protocol:l.defaultProtocol,l.hostname=l.host,w._reconnectCount++),n("calling streambuilder for",l.protocol),o[l.protocol](w,l)}var E=new i(g,l);return E.on("error",function(){}),E}return kt.exports=a,kt.exports.connect=a,kt.exports.MqttClient=i,kt.exports.Store=e,kt.exports}var W_=H_();const Y_=rt(W_);var Ka,Np;function G_(){if(Np)return Ka;Np=1;var i="Expected a function",e=NaN,t="[object Symbol]",r=/^\s+|\s+$/g,n=/^[-+]0x[0-9a-f]+$/i,o=/^0b[01]+$/i,u=/^0o[0-7]+$/i,a=parseInt,s=typeof xe=="object"&&xe&&xe.Object===Object&&xe,l=typeof self=="object"&&self&&self.Object===Object&&self,d=s||l||Function("return this")(),_=Object.prototype,g=_.toString,E=Math.max,w=Math.min,q=function(){return d.Date.now()};function k(h,p,v){var I,B,H,V,P,ce,oe=0,ne=!1,se=!1,he=!0;if(typeof h!="function")throw new TypeError(i);p=b(p)||0,A(v)&&(ne=!!v.leading,se="maxWait"in v,H=se?E(b(v.maxWait)||0,p):H,he="trailing"in v?!!v.trailing:he);function J(D){var $=I,z=B;return I=B=void 0,oe=D,V=h.apply(z,$),V}function me(D){return oe=D,P=setTimeout(G,p),ne?J(D):V}function de(D){var $=D-ce,z=D-oe,Y=p-$;return se?w(Y,H-z):Y}function be(D){var $=D-ce,z=D-oe;return ce===void 0||$>=p||$<0||se&&z>=H}function G(){var D=q();if(be(D))return re(D);P=setTimeout(G,de(D))}function re(D){return P=void 0,he&&I?J(D):(I=B=void 0,V)}function j(){P!==void 0&&clearTimeout(P),oe=0,I=ce=B=P=void 0}function L(){return P===void 0?V:re(q())}function M(){var D=q(),$=be(D);if(I=arguments,B=this,ce=D,$){if(P===void 0)return me(ce);if(se)return P=setTimeout(G,p),J(ce)}return P===void 0&&(P=setTimeout(G,p)),V}return M.cancel=j,M.flush=L,M}function A(h){var p=typeof h;return!!h&&(p=="object"||p=="function")}function R(h){return!!h&&typeof h=="object"}function S(h){return typeof h=="symbol"||R(h)&&g.call(h)==t}function b(h){if(typeof h=="number")return h;if(S(h))return e;if(A(h)){var p=typeof h.valueOf=="function"?h.valueOf():h;h=A(p)?p+"":p}if(typeof h!="string")return h===0?h:+h;h=h.replace(r,"");var v=o.test(h);return v||u.test(h)?a(h.slice(2),v?2:8):n.test(h)?e:+h}return Ka=k,Ka}var z_=G_();const V_=rt(z_),jp=(i,e,t,r)=>{try{const n=i();return r!=null&&r(n),n}catch(n){return t!=null&&t(n),e}},K_=i=>i.then(e=>[e,null]).catch(e=>[null,e]);class Q_{constructor(e,t,r,{shouldConnect:n=!0,brokerLbUrl:o,enableLb:u,getClientId:a}){He(this,"_getClientId",()=>this.getClientId==null?`${this.core.AppId}_${this.core.user_id}_${Date.now()}`:this.getClientId());He(this,"__mqtt_connected_handler",()=>{this.emitter.emit("connected")});He(this,"__mqtt_reconnect_handler",()=>{this.emitter.emit("reconnect")});He(this,"__mqtt_closed_handler",(...e)=>{this.emitter.emit("close",e)});He(this,"__mqtt_message_handler",(e,t)=>{const r=t.toString(),n=this.matcher(e);this.logger("message",e,t),n!=null&&n(r)});He(this,"__mqtt_error_handler",e=>{e&&e.message==="client disconnecting"||(this.emitter.emit("error",e.message),this.logger("error",e.message))});He(this,"__mqtt_conneck",e=>{const t=[],r={will:{topic:`u/${this.core.user_id}/s`,payload:0,retain:!0},clientId:this._getClientId()};if(e==null&&(e=this.cacheRealtimeURL),this.mqtt!=null){const o=Object.keys(this.mqtt._resubscribeTopics);t.push(...o),this.mqtt.removeAllListeners(),this.mqtt.end(!0),delete this.mqtt,this.mqtt=null}const n=Y_(e,r);return n.addListener("connect",this.__mqtt_connected_handler),n.addListener("reconnect",this.__mqtt_reconnect_handler),n.addListener("close",this.__mqtt_closed_handler),n.addListener("error",this.__mqtt_error_handler),n.addListener("message",this.__mqtt_message_handler),this.logger(`resubscribe to old topics ${t}`),t.forEach(o=>n.subscribe(o)),n});He(this,"_on_close_handler",V_(()=>ke(this,null,function*(){const e=this.enableLb===!0&&this.core.isLogin===!0&&this.shouldConnect===!0&&!this.willConnectToRealtime;if(this.logEnabled&&(console.group("@mqtt.closed"),console.log(`this.enableLb(${this.enableLb})`),console.log(`this.core.isLogin(${this.core.isLogin})`),console.log(`this.shouldConnect(${this.shouldConnect})`),console.log(`this.willConnectToRealtime(${this.willConnectToRealtime})`),console.log(`shouldReconnect(${e})`),console.groupEnd()),!e)return;this.willConnectToRealtime=!0;const[t,r]=yield K_(this.getMqttNode());r?(this.logger(`cannot get new brokerURL, using old url instead (${this.cacheRealtimeURL})`),this.mqtt=this.__mqtt_conneck(this.cacheRealtimeURL)):(this.cacheRealtimeURL=t,this.logger("trying to reconnect to",t),this.mqtt=this.__mqtt_conneck(t)),this.willConnectToRealtime=!1}),1e3));He(this,"subscribtionBuffer",[]);He(this,"unsubscribtionBuffer",[]);He(this,"publishBuffer",[]);this.emitter=Ot(),this.core=t,this.mqtt=null,this.brokerLbUrl=o,this.getClientId=a,this.enableLb=u,this.shouldConnect=n,this.matcher=hg({[Ze(this.reNewMessage)]:l=>this.newMessageHandler.bind(this,l),[Ze(this.reNotification)]:l=>this.notificationHandler.bind(this,l),[Ze(this.reTyping)]:l=>this.typingHandler.bind(this,l),[Ze(this.reRoomTyping)]:l=>this.roomTypingHandler.bind(this,l),[Ze(this.reDelivery)]:l=>this.deliveryReceiptHandler.bind(this,l),[Ze(this.reRead)]:l=>this.readReceiptHandler.bind(this,l),[Ze(this.reOnlineStatus)]:l=>this.onlinePresenceHandler.bind(this,l),[Ze(this.reChannelMessage)]:l=>this.channelMessageHandler.bind(this,l),[Ze(this.reMessageUpdated)]:l=>this.messageUpdatedHandler.bind(this,l),[Ze()]:l=>this.logger("topic not handled",l)});let s=this.__mqtt_conneck(e);this.mqtt=s,n||s.end(!0),this.willConnectToRealtime=!1,this.emitter.on("close",this._on_close_handler)}get cacheRealtimeURL(){return this.core.mqttURL}set cacheRealtimeURL(e){this.core.mqttURL=e}connect(){this.mqtt=this.__mqtt_conneck()}openConnection(){return ke(this,null,function*(){this.shouldConnect=!0,this.mqtt=this.__mqtt_conneck()})}closeConnection(){return ke(this,null,function*(){this.shouldConnect=!1,this.mqtt.end(!0,e=>{e&&this.logger("error when close connection",e.message)}),this.mqtt=null})}getMqttNode(){return ke(this,null,function*(){const e=yield st.get(this.brokerLbUrl),t=e.body.data.url,r=e.body.data.wss_port;return`wss://${t}:${r}/mqtt`})}get connected(){return this.mqtt==null?!1:this.mqtt.connected}subscribe(...e){for(this.subscribtionBuffer.push(e);this.mqtt!=null&&this.subscribtionBuffer.length>0;){const t=this.subscribtionBuffer.shift();t!=null&&(this.logger("subscribe topic",t),this.mqtt.subscribe(...t))}}unsubscribe(...e){for(this.unsubscribtionBuffer.push(e);this.mqtt!=null&&this.unsubscribtionBuffer.length>0;){const t=this.unsubscribtionBuffer.shift();t!=null&&(this.logger("unsubscribe topic",t),this.mqtt.unsubscribe(...t))}}publish(e,t,r={}){for(this.publishBuffer.push({topic:e,payload:t,options:r});this.mqtt!=null&&this.publishBuffer.length>0;){const n=this.publishBuffer.shift();n!=null&&(this.logger("publish to",n.topic,n.payload,n.options),this.mqtt.publish(n.topic,n.payload.toString(),n.options))}}emit(...e){this.emitter.emit(...e)}on(...e){this.emitter.on(...e)}off(...e){this.emitter.off(...e)}get logEnabled(){return this.core.debugMQTTMode}get logger(){return this.core.debugMQTTMode?console.log.bind(console,"QRealtime ->"):this.noop}get reNewMessage(){return/^(.+)\/c$/i}get reNotification(){return/^(.+)\/n$/i}get reTyping(){return/^r\/([\d]+)\/([\d]+)\/(.+)\/t$/i}get reRoomTyping(){return/^r\/(.+)\/typing$/i}get reDelivery(){return/^r\/([\d]+)\/([\d]+)\/(.+)\/d$/i}get reRead(){return/^r\/([\d]+)\/([\d]+)\/(.+)\/r$/i}get reOnlineStatus(){return/^u\/(.+)\/s$/i}get reChannelMessage(){return/^(.+)\/(.+)\/c$/i}get reMessageUpdated(){return/^(.+)\/update$/i}noop(){}newMessageHandler(e,t){t=JSON.parse(t),this.logger("on:new-message",t),this.emit("new-message",t)}notificationHandler(e,t){this.logger("on:notification",t),t=JSON.parse(t);const r=t.payload.data;"deleted_messages"in r&&r.deleted_messages.forEach(n=>{this.emit("comment-deleted",{roomId:n.room_id,commentUniqueIds:n.message_unique_ids,isForEveryone:!0,isHard:!0})}),"deleted_rooms"in r&&r.deleted_rooms.forEach(n=>{this.emit("room-cleared",n)})}roomTypingHandler(e,t){var o;this.logger("on:room-typing",e);let r=(o=e.match(this.reRoomTyping))==null?void 0:o[1],n=JSON.parse(t);this.emit("room-typing",wr(br({},n),{room_id:r}))}typingHandler(e,t){this.logger("on:typing",e);const r=e.match(this.reTyping);if(r[3]===this.core.user_id)return;const n=r[3],o=r[1];if(this.emit("typing",{message:t,userId:n,roomId:o}),this.core.selected!=null)if(t==="1"&&o===this.core.selected.id){const u=this.core.selected.participants.find(s=>s.email===n);if(u==null)return;const a=u.username;this.core.isTypingStatus=`${a} is typing ...`}else this.core.isTypingStatus=null}deliveryReceiptHandler(e,t){this.logger("on:delivered",e,t);const r=e.match(this.reDelivery),n=t.split(":"),o=Number(n[0]),u=n[1],a=r[3];this.emit("message-delivered",{commentId:o,commentUniqueId:u,userId:a})}readReceiptHandler(e,t){this.logger("on:read",e,t);const r=e.match(this.reRead),n=t.split(":"),o=Number(n[0]),u=n[1],a=r[3];this.emit("message-read",{commentId:o,commentUniqueId:u,userId:a})}onlinePresenceHandler(e,t){this.logger("on:online-presence",e,t);const n=this.reOnlineStatus.exec(e)[1];this.emit("presence",{message:t,userId:n})}channelMessageHandler(e,t){this.logger("on:channel-message",e,t),this.emit("new-message",JSON.parse(t))}messageUpdatedHandler(e,t){t=JSON.parse(t),this.logger("on:message-updated",e,t),this.emit("message:updated",t)}subscribeChannel(e,t){this.subscribe(`${e}/${t}/c`)}subscribeRoom(e){this.core.selected!=null&&(e=e||this.core.selected.id,this.subscribe(`r/${e}/typing`),this.subscribe(`r/${e}/${e}/+/t`),this.subscribe(`r/${e}/${e}/+/d`),this.subscribe(`r/${e}/${e}/+/r`))}unsubscribeRoom(e){this.core.selected!=null&&(e=e||this.core.selected.id,this.unsubscribe(`r/${e}/typing`),this.unsubscribe(`r/${e}/${e}/+/t`),this.unsubscribe(`r/${e}/${e}/+/d`),this.unsubscribe(`r/${e}/${e}/+/r`))}get subscribeTyping(){return this.subscribeRoom.bind(this)}get unsubscribeTyping(){return this.unsubscribeRoom.bind(this)}subscribeUserChannel(){this.subscribe(`${this.core.userData.token}/c`),this.subscribe(`${this.core.userData.token}/n`),this.subscribe(`${this.core.userData.token}/update`)}subscribeUserChannelByToken(e){this.subscribe(`${e}/c`),this.subscribe(`${e}/n`),this.subscribe(`${e}/update`)}unsubscribeUserChannel(){this.unsubscribe(`${this.core.userData.token}/c`),this.unsubscribe(`${this.core.userData.token}/n`),this.unsubscribe(`${this.core.userData.token}/update`)}unsusbcribeUserChannelByToken(e){this.unsubscribe(`${e}/c`),this.unsubscribe(`${e}/n`),this.unsubscribe(`${e}/update`)}publishPresence(e,t=!0){t?this.publish(`u/${e}/s`,1,{retain:!0}):this.publish(`u/${e}/s`,0,{retain:!0})}disconnect(){this.publishPresence(this.core.userData.email,!1),this.unsubscribe(Object.keys(this.mqtt._resubscribeTopics))}subscribeUserPresence(e){this.subscribe(`u/${e}/s`)}unsubscribeUserPresence(e){this.unsubscribe(`u/${e}/s`)}get subscribeRoomPresence(){return this.subscribeUserPresence.bind(this)}get unsubscribeRoomPresence(){return this.unsubscribeUserPresence.bind(this)}publishTyping(e){if(this.core.selected==null)return;const t=this.core.selected.id,r=this.core.user_id;this.publish(`r/${t}/${t}/${r}/t`,e)}}function J_(i,e){const t=Ot(),r={},n=/^r\/[\w]+\/[\w]+\/e$/i;i.mqtt.on("message",(u,a)=>{n.test(u)&&t.emit(u,a)});const o=u=>`r/${u}/${u}/e`;return{publishEvent(u,a){if(Ye.undefined(u))throw new Error("`roomId` required");if(Ye.not.string(u))throw new TypeError("`roomId` must have type of string");if(Ye.undefined(a))throw new Error("`payload` required");if(Ye.not.object(a))throw new TypeError("`payload` must have type of object");const s=JSON.stringify({sender:e,data:a});i.publish(o(u),s)},subscribeEvent(u,a){if(Ye.undefined(u))throw new Error("`roomId` required");if(Ye.not.string(u))throw new TypeError("`roomId` must have type of string");if(Ye.undefined(a))throw new Error("`callback` required");if(Ye.not.function(a))throw new TypeError("`callback` must have type of function");const s=o(u);if(r[s])return;i.subscribe(s);const l=d=>{const _=JSON.parse(d);a(_)};t.on(s,l),r[s]=l},unsubscribeEvent(u){if(Ye.undefined(u))throw new Error("`roomId` required");if(Ye.not.string(u))throw new TypeError("`roomId` must have type of string");const a=o(u);r[a]&&(i.unsubscribe(a),t.off(a,r[a]),r[a]=null,delete r[a])}}}const $p=()=>{},Hp=i=>new Promise(e=>setTimeout(e,i));function X_(i,e,t,r,n){const o=Ot(),u=l=>{const d=nr("api/v2/sdk/sync").param("last_received_comment_id",l).build();return i().get(d).then(_=>{const g=_.body.results,E=g.comments,w=g.meta.last_received_comment_id;return E.sort((q,k)=>q.id-k.id),Promise.resolve({lastMessageId:w,messages:E,interval:e()})}).catch($p)};function a(){return tu(this,null,function*(){let l=0;const d=100,_=()=>i()!=null&&t();for(;;)l+=d,l>=e()&&_()&&(l=0,yield u(r())),yield new Sr(Hp(d))})}return{get synchronize(){return u},get on(){return o.on},get off(){return o.off},run(){return ke(this,null,function*(){try{for(var l=ru(a()),d,_,g;d=!(_=yield l.next()).done;d=!1){let E=_.value;try{if(o.emit("synchronize",Date.now()),(E==null?void 0:E.lastMessageId)!=null&&(E==null?void 0:E.messages)!=null){const w=E.lastMessageId,q=E.messages;w>r()&&(q.forEach(k=>o.emit("message.new",k)),o.emit("last-message-id.new",w))}}catch(w){n("error when sync",w.message),console.log("error when sync",w)}}}catch(_){g=[_]}finally{try{d&&(_=l.return)&&(yield _.call(l))}finally{if(g)throw g[0]}}})}}}function Z_(i,e,t,r,n){const o=Ot(),u=l=>{const d=nr("api/v2/sdk/sync_event").param("start_event_id",l).build();return i().get(d).then(_=>{const g=_.body.events,E=g.map(R=>R.id).sort((R,S)=>R-S).pop(),w=g.filter(R=>R.action_topic==="delivered").map(R=>R.payload.data),q=g.filter(R=>R.action_topic==="read").map(R=>R.payload.data),k=g.filter(R=>R.action_topic==="delete_message").map(R=>R.payload.data),A=g.filter(R=>R.action_topic==="clear_room").map(R=>R.payload.data);return Promise.resolve({lastId:E,messageDelivered:w,messageRead:q,messageDeleted:k,roomCleared:A,interval:e()})}).catch($p)};function a(){return tu(this,null,function*(){let l=0;const d=100,_=()=>i()!=null&&t();for(;;)l+=d,l>=e()&&_()&&(l=0,yield u(r())),yield new Sr(Hp(d))})}return{get synchronize(){return u},get on(){return o.on},get off(){return o.off},run(){return ke(this,null,function*(){try{for(var l=ru(a()),d,_,g;d=!(_=yield l.next()).done;d=!1){let E=_.value;try{const w=E.lastId;w>r()&&(o.emit("last-event-id.new",w),E.messageDelivered.forEach(q=>o.emit("message.delivered",q)),E.messageDeleted.forEach(q=>o.emit("message.deleted",q)),E.messageRead.forEach(q=>o.emit("message.read",q)),E.roomCleared.forEach(q=>o.emit("room.cleared",q)))}catch(w){n("error when sync event",w.message)}}}catch(_){g=[_]}finally{try{d&&(_=l.return)&&(yield _.call(l))}finally{if(g)throw g[0]}}})}}}function ev(i,{isDebug:e=!1,syncInterval:t,getShouldSync:r,syncOnConnect:n,lastCommentId:o,statusLogin:u,enableSync:a,enableSyncEvent:s}){const l=Ot(),d=(...R)=>e?console.log("QSync:",...R):{};let _=0;const g=()=>u()?r()?t():n():0,w=X_(i,g,()=>r()&&a(),o,d);w.on("last-message-id.new",R=>R),w.on("message.new",R=>l.emit("message.new",R)),w.on("synchronize",R=>l.emit("synchronize",R)),w.run().catch(R=>d("got error when sync",R));const k=Z_(i,g,()=>r()&&s(),()=>_,d);return k.on("last-event-id.new",R=>{_=R}),k.on("message.read",R=>{l.emit("message.read",R)}),k.on("message.delivered",R=>l.emit("message.delivered",R)),k.on("message.deleted",R=>l.emit("message.deleted",R)),k.on("room.cleared",R=>l.emit("room.cleared",R)),k.run().catch(R=>d("got error when sync event",R)),{get on(){return l.on},get off(){return l.off},get interval(){return g()},get enabled(){return a()},synchronize(){return ke(this,null,function*(){var p,v;let R=o(),S=yield w.synchronize(R),b=(p=S==null?void 0:S.messages)!=null?p:[],h=(v=S==null?void 0:S.lastMessageId)!=null?v:-1;for(let I of b)l.emit("message.new",I);h>0&&l.emit("last-message-id.new",h)})},synchronizeEvent(){return ke(this,null,function*(){let R=yield k.synchronize(_);try{const S=R.lastId;S>getId()&&(l.emit("last-event-id.new",S),R.messageDelivered.forEach(b=>l.emit("message.delivered",b)),R.messageDeleted.forEach(b=>l.emit("message.deleted",b)),R.messageRead.forEach(b=>l.emit("message.read",b)),R.roomCleared.forEach(b=>l.emit("room.cleared",b)))}catch(S){d("error when sync event",S.message)}})}}}const tv={version:"2.16.3"},dt={MESSAGE_BEFORE_SENT:"message::before-sent",MESSAGE_BEFORE_RECEIVED:"message::before-received"};function rv(){const i={},e=n=>(Array.isArray(i[n])||(i[n]=[]),i[n]);function t(n,o){e(n).push(o);const u=e(n).length;return()=>e(n).splice(u,1)}function r(n,o){return e(n).reduce((u,a)=>Promise.resolve(u).then(a),Promise.resolve(o))}return{trigger:r,intercept:t}}class nv{constructor({httpAdapter:e,refreshToken:t,expiredAt:r,userId:n,onTokenRefreshed:o,getAuthenticationStatus:u}){He(this,"_isExpiredTokenEnabled",!1);He(this,"_refreshToken",null);He(this,"_expiredAt",null);He(this,"_http");He(this,"_onTokenRefreshed");He(this,"_timerId");He(this,"_getAuthenticationStatus");this._http=e,this._refreshToken=t,this._userId=n,this._onTokenRefreshed=o,this._getAuthenticationStatus=u,this._refreshToken!=null&&this._refreshToken===""&&(this._refreshToken=null),r!=null&&r!==""&&(this._expiredAt=new Date(r)),this._isExpiredTokenEnabled=this._refreshToken!=null&&this._expiredAt!=null,this._setTimer(this._expiredAt)}_setTimer(e){var r;this._timerId!=null&&(clearTimeout(this._timerId),this._timerId=null);const t=Math.floor(((r=e==null?void 0:e.getTime())!=null?r:NaN)-Date.now());!isNaN(t)&&t>0&&(this._timerId=setTimeout(()=>{this.refreshAuthToken()},t))}refreshAuthToken(){return ke(this,null,function*(){if(!(this._getAuthenticationStatus()==!1||this._refreshToken==null))return this._http.post("api/v2/sdk/refresh_user_token",{user_id:this._userId,refresh_token:this._refreshToken}).then(e=>{var n;let t=e.body.results,r=t.token;return this._refreshToken=t.refresh_token,(n=this._onTokenRefreshed)==null||n.call(this,r,this._refreshToken,this._expiredAt,this._http.token),this._http.setToken(t.token),t.token_expires_at!=null&&(this._expiredAt=new Date(t.token_expires_at)),this._setTimer(this._expiredAt),t})})}logout(){return ke(this,null,function*(){return this._http.post("api/v2/sdk/logout",{user_id:this._userId,token:this._http.token})})}}let Wp;const iv=Object.freeze({disabled:"UpdateCommentStatusMode.disabled",throttled:"UpdateCommentStatusMode.throttled",enabled:"UpdateCommentStatusMode.enabled"}),vt=class vt{constructor(){He(this,"_pendingComments",[]);He(this,"_pendingCommentsCount",{});He(this,"_readComment",(e,t)=>this._updateStatus(e,t));He(this,"_readCommentT",this._throttle((e,t)=>{this._updateStatus(e,t)},()=>this._throttleDelay));He(this,"_deliverComment",(e,t)=>this._updateStatus(e,void 0,t));He(this,"_deliverCommentT",this._throttle((e,t)=>{this._updateStatus(e,void 0,t)},()=>this._throttleDelay));this.events=Ot(),this.rooms=[],this.selected=null,this.room_name_id_map={},this.pendingCommentId=0,this.uploadedFiles=[],this.chatmateStatus=null,this.version=`WEB_${tv.version}`,this.userData={},this.AppId=null,this.baseURL="https://api.qiscus.com",this.mqttURL="wss://realtime-jogja.qiscus.com:1886/mqtt",this.brokerLbUrl="https://realtime-lb.qiscus.com",this.syncOnConnect=1e4,this.enableEventReport=!1,this.enableRealtime=!0,this.enableRealtimeCheck=!0,this.enableSync=!0,this.enableSyncEvent=!1,this.HTTPAdapter=null,this.expiredTokenAdapter=null,this.realtimeAdapter=null,this.customEventAdapter=null,this.isInit=!1,this.isSynced=!1,this.syncInterval=5e3,this.sync="socket",this.enableLb=!0,this.httpsync=null,this.eventsync=null,this.extras=null,this.last_received_comment_id=0,this.googleMapKey="",this.options={avatar:!0},this.isConfigLoaded=!1,this.updateCommentStatusMode=vt.UpdateCommentStatusMode.enabled,this.updateCommentStatusThrottleDelay=300,this.UI={},this.mode="widget",this.avatar=!0,this.plugins=[],this.isLogin=!1,this.isLoading=!1,this.isInit=!1,this.emoji=!1,this.isTypingStatus="",this.customTemplate=!1,this.templateFunction=null,this.debugMode=!1,this.debugMQTTMode=!1,this._customHeader={},this._forceEnableSync=!0,this.lastReceiveMessages=[],this._hookAdapter=rv(),this._uploadURL=null,this._autoRefreshToken=!1}get uploadURL(){return this._uploadURL||`${this.baseURL}/api/v2/sdk/upload`}set uploadURL(e){this._uploadURL=e}init(e){return ke(this,null,function*(){var a;if(!e.AppId)throw new Error("Please provide valid AppId");this.AppId=e.AppId;const t=e.baseURL!=null&&this.baseURL!==e.baseURL,r=e.mqttURL!=null&&this.mqttURL!==e.mqttURL,n=e.brokerLbURL!=null&&this.brokerLbUrl!==e.brokerLbURL;(t||r)&&!n?(this.logger("force disable load balancing for realtime server, because `baseURL` or `mqttURL` get changed but did not provide `brokerLbURL`"),this.enableLb=!1):e.enableRealtimeLB!=null&&(this.enableLb=e.enableRealtimeLB),e.updateCommentStatusMode!=null&&(this.updateCommentStatusMode=e.updateCommentStatusMode),e.updateCommentStatusThrottleDelay!=null&&(this.updateCommentStatusThrottleDelay=e.updateCommentStatusThrottleDelay),e.baseURL&&(this.baseURL=e.baseURL),e.mqttURL&&(this.mqttURL=e.brokerUrl||e.mqttURL),e.mqttURL&&(this.brokerUrl=e.brokerUrl||e.mqttURL),e.brokerLbURL&&(this.brokerLbUrl=e.brokerLbURL),e.uploadURL&&(this.uploadURL=e.uploadURL),e.sync&&(this.sync=e.sync),e.mode&&(this.mode=e.mode),e.syncInterval&&(this.syncInterval=e.syncInterval||5e3),e.googleMapKey&&(this.googleMapKey=e.googleMapKey),e.allowedFileTypes&&(this.allowedFileTypes=e.allowedFileTypes),e.options&&(this.options=Object.assign({},this.options,e.options)),e.customTemplate&&(this.customTemplate=e.customTemplate),e.templateFunction&&(this.templateFunction=e.templateFunction),e.syncInterval!=null&&(this.syncInterval=e.syncInterval),this.HTTPAdapter=new Do({baseURL:this.baseURL,AppId:this.AppId,userId:this.user_id,version:this.version,getCustomHeader:()=>this._customHeader});const o=(s,l,d)=>l===""&&s!=null&&(typeof s!="string"||s.length>0)?s:l!=null&&(l.length>0||typeof l!="string")?l:d,u=s=>s.includes("wss://")?s:`wss://${s}:1886/mqtt`;this.withConfig=(a=e.withConfig)!=null?a:!0,this.withConfig===!0?yield this.HTTPAdapter.get_request("api/v2/sdk/config").then(s=>(s.status==200?this.isConfigLoaded=!0:this.isConfigLoaded=!1,s.body.results)).then(s=>{const l=this.baseURL,d=this.brokerLbUrl,_=this.mqttURL,g=this.enableRealtime,E=this.enableRealtimeCheck,w=this.syncInterval,q=this.syncOnConnect,k=this.enableEventReport,A={};this.baseURL=o(e.baseURL,s.base_url,l),this.brokerLbUrl=o(e.brokerLbURL,s.broker_lb_url,d),this.mqttURL=u(o(e.mqttURL,s.broker_url,_)),this.enableRealtime=o(e.enableRealtime,s.enable_realtime,g),this.syncInterval=o(e.syncInterval,s.sync_interval,w),this.syncOnConnect=o(e.syncOnConnect,s.sync_on_connect,q),this.enableRealtimeCheck=o(null,s.enable_realtime_check,E),this.enableEventReport=o(null,s.enable_event_report,k),this.extras=o(null,s.extras,A),this.enableSync=o(null,s.enable_sync,this.enableSync),this.enableSyncEvent=o(null,s.enable_sync_event,this.enableSyncEvent),this._autoRefreshToken=o(null,s.auto_refresh_token,!1)}).catch(s=>{this.logger("got error when trying to get app config",s),this.isConfigLoaded=!0}):this.isConfigLoaded=!0,this._getMqttClientId=()=>`${this.AppId}_${this.user_id}_${Date.now()}`,this.realtimeAdapter=new Q_(this.mqttURL,this,this.isLogin,{brokerLbUrl:this.brokerLbUrl,enableLb:this.enableLb,shouldConnect:this.enableRealtime,getClientId:this._getMqttClientId}),this.realtimeAdapter.on("connected",()=>{(this.isLogin||!this.realtimeAdapter.connected)&&(this.last_received_comment_id=this.userData.last_comment_id,this.updateLastReceivedComment(this.last_received_comment_id))}),this.realtimeAdapter.on("close",()=>{}),this.realtimeAdapter.on("reconnect",()=>{var s,l;(l=(s=this.options).onReconnectCallback)==null||l.call(s)}),this.realtimeAdapter.on("message-delivered",({commentId:s,commentUniqueId:l,userId:d})=>this._setDelivered(s,l,d)),this.realtimeAdapter.on("message-read",({commentId:s,commentUniqueId:l,userId:d})=>this._setRead(s,l,d)),this.realtimeAdapter.on("new-message",s=>ke(this,null,function*(){s=yield this._hookAdapter.trigger(dt.MESSAGE_BEFORE_RECEIVED,s),this.events.emit("newmessages",[s])})),this.realtimeAdapter.on("presence",s=>this.events.emit("presence",s)),this.realtimeAdapter.on("comment-deleted",s=>this.events.emit("comment-deleted",s)),this.realtimeAdapter.on("room-cleared",s=>this.events.emit("room-cleared",s)),this.realtimeAdapter.on("typing",s=>this.events.emit("typing",{message:s.message,username:s.userId,room_id:s.roomId})),this.realtimeAdapter.on("message:updated",s=>{this.options.messageUpdatedCallback!=null&&this.options.messageUpdatedCallback(s)}),this.realtimeAdapter.on("room-typing",s=>{this.events.emit("typing",{message:s.text,username:s.sender_name,email:s.sender_id,room_id:s.room_id}),this.options.onRoomTypingCallback!=null&&(this.events.emit("room-typing",s),this.options.onRoomTypingCallback(s))}),this.syncAdapter=ev(()=>this.HTTPAdapter,{syncInterval:()=>this.syncInterval,getShouldSync:()=>this._forceEnableSync&&this.isLogin&&!this.realtimeAdapter.connected,syncOnConnect:()=>this.syncOnConnect,lastCommentId:()=>this.last_received_comment_id,statusLogin:()=>this.isLogin,enableSync:()=>this.enableSync,enableSyncEvent:()=>this.enableSyncEvent}),this.syncAdapter.on("message.new",s=>ke(this,null,function*(){if(s=yield this._hookAdapter.trigger(dt.MESSAGE_BEFORE_RECEIVED,s),this.selected!=null){if(this.selected.comments.findIndex(d=>d.id===s.id||d.unique_id===s.unique_temp_id)===-1){const d=new pt(s);d.room_id===this.selected.id&&(this.selected.comments.push(d),this.sortComments()),this.events.emit("newmessages",[s])}}else this.events.emit("newmessages",[s])})),this.syncAdapter.on("message.delivered",s=>{this._setDelivered(s.comment_id,s.comment_unique_id,s.email)}),this.syncAdapter.on("message.read",s=>{this._setRead(s.comment_id,s.comment_unique_id,s.email)}),this.syncAdapter.on("message.deleted",s=>{s.deleted_messages.forEach(l=>{this.events.emit("comment-deleted",{roomId:l.room_id,commentUniqueIds:l.message_unique_ids,isForEveryone:!0,isHard:!0})})}),this.syncAdapter.on("room.cleared",s=>{s.deleted_rooms.forEach(l=>{this.events.emit("room-cleared",l)})}),this.syncAdapter.on("synchronize",()=>{this._pendingComments.forEach(s=>this._retrySendComment(s))}),this.syncAdapter.on("last-message-id.new",s=>{this.last_received_comment_id=s}),this.customEventAdapter=J_(this.realtimeAdapter,this.user_id),this.setEventListeners()})}_setRead(e,t,r){if(this.selected==null)return;const n=this.selected,o=n.comments.find(a=>a.id===e||a.unique_id===t);if(o==null||o.status==="read")return;const u={participants:n.participants,actor:r,comment_id:e,activeActorId:this.user_id};n.comments.forEach(a=>{a.id<=o.id&&a.markAsRead(u)}),o.isRead&&this.events.emit("comment-read",{comment:o,userId:r})}_setDelivered(e,t,r){if(this.selected==null)return;const n=this.selected,o=n.comments.find(a=>a.id===e||a.unique_id===t);if(o==null||o.status==="read")return;const u={participants:n.participants,actor:r,comment_id:e,activeActorId:this.user_id};n.comments.forEach(a=>{a.id<=o.id&&a.markAsDelivered(u)}),o.isDelivered&&this.events.emit("comment-delivered",{comment:o,userId:r})}setEventListeners(){const e=this;this.authAdapter=new tg(e.HTTPAdapter),this.userData.email!=null&&(this.authAdapter.userId=this.userData.email),e.events.on("start-init",()=>{e.HTTPAdapter=new Do({baseURL:e.baseURL,AppId:e.AppId,userId:e.user_id,version:e.version,getCustomHeader:()=>this._customHeader}),e.HTTPAdapter.setToken(e.userData.token)}),e.events.on("room-changed",t=>{this.logging("room changed",t),e.options.roomChangedCallback&&e.options.roomChangedCallback(t)}),e.events.on("file-uploaded",t=>{e.options.fileUploadedCallback&&e.options.fileUploadedCallback(t)}),e.events.on("profile-updated",t=>{e.username=t.name,e.avatar_url=t.avatar_url,e.options.updateProfileCallback&&e.options.updateProfileCallback(t)}),e.events.on("newmessages",t=>{if(this.logging("newmessages",t),this.lastReceiveMessages.length>0&&this.lastReceiveMessages[0].unique_temp_id===t[0].unique_temp_id){this.logging("lastReceiveMessages double",t);return}this.lastReceiveMessages=t,e._callNewMessagesCallback(t),t.forEach(n=>{e.receiveComment(n.room_id,n.id);const o=e.selected?n.room_id===e.selected.id:!1,u=n.id<=e.last_received_comment_id;if(o){const a=e.selected,s=e.selected.comments[e.selected.comments.length-1];!s.isPending&&!u&&e.user_id!==n.email&&e.readComment(n.room_id,n.id);const l=s.id,d=e.selected.comments.find(g=>g.id===s.comment_before_id);!s.isPending&&!d&&(this.logging("comment before id not found! ",n.comment_before_id),e.synchronize(l));const _=new pt(n);a.receiveComment(_),a.last_comment_id=_.id,a.last_comment_message=_.message}e.updateLastReceivedComment(n.id),this.sortComments()})}),this.events.on("login-success",t=>{this.isLogin=!0,this.userData=t.user,this.last_received_comment_id=this.userData.last_comment_id,this.realtimeAdapter.connected||this.updateLastReceivedComment(this.last_received_comment_id),this.HTTPAdapter=new Do({baseURL:this.baseURL,AppId:this.AppId,userId:this.user_id,version:this.version,getCustomHeader:()=>this._customHeader,expiredTokenAdapterGetter:()=>this.expiredTokenAdapter}),this.HTTPAdapter.setToken(this.userData.token);let r=t.user;this._delayedSync=eg(()=>{this.synchronize(),this.synchronizeEvent()},500),this.expiredTokenAdapter=new nv({httpAdapter:this.HTTPAdapter,refreshToken:r.refresh_token,expiredAt:r.token_expires_at,userId:this.user_id,onTokenRefreshed:(n,o,u,a)=>{this.userData.token=n,this.userData.refresh_token=o,this.userData.token_expires_at=u==null?void 0:u.toJSON(),this.events.emit("token-refreshed",{token:n,refreshToken:o,expiredAt:u,oldToken:a}),this.realtimeAdapter.unsusbcribeUserChannelByToken(a),this.realtimeAdapter.subscribeUserChannelByToken(n),this._delayedSync()},getAuthenticationStatus:()=>this.user_id!=null&&this.isLogin}),this.userAdapter=new og(this.HTTPAdapter),this.roomAdapter=new sg(this.HTTPAdapter),this.realtimeAdapter.subscribeUserChannel(),this.presensePublisherId!=null&&this.presensePublisherId!==-1&&clearInterval(this.presensePublisherId),this.presensePublisherId=setInterval(()=>{this.realtimeAdapter.publishPresence(this.user_id,!0)},3500),this.options.loginSuccessCallback&&this.options.loginSuccessCallback(t),this.authAdapter.userId=this.userData.email,this.authAdapter.refreshToken=this.userData.refresh_token,this.authAdapter.autoRefreshToken=this._autoRefreshToken}),e.events.on("login-error",function(t){e.options.loginErrorCallback&&e.options.loginErrorCallback(t)}),e.events.on("token-refreshed",t=>{var r,n;(n=(r=this.options).authTokenRefreshedCallback)==null||n.call(r,t)}),e.events.on("room-cleared",function(t){if(e.selected){const r=e.selected;e.selected.unique_id===t.unique_id&&(e.selected=null,e.selected=r)}e.options.roomClearedCallback&&e.options.roomClearedCallback(t)}),e.events.on("comment-deleted",function(t){const{roomId:r,commentUniqueIds:n,isForEveryone:o,isHard:u}=t;e.selected&&e.selected.id==r&&n.map(a=>{const s=e.selected.comments.findIndex(d=>d.unique_id===a);s>-1&&(u?e.selected.comments.splice(s,1):e.selected.comments[s].message="this message has been deleted");const l=e.selected.comments[e.selected.comments.length-1];e.selected.last_comment_id=l.id,e.selected.last_comment_message=l.message}),e.options.commentDeletedCallback&&e.options.commentDeletedCallback(t)}),e.events.on("comment-delivered",function(t){if(e.logging("comment-delivered",t),!t)return!1;if(e.options.commentDeliveredCallback)return e.options.commentDeliveredCallback(t)}),e.events.on("chat-room-created",function(t){e.isLoading=!1,e.options.chatRoomCreatedCallback&&e.options.chatRoomCreatedCallback(t)}),e.events.on("group-room-created",function(t){e.isLoading=!1,e.options.groupRoomCreatedCallback&&e.options.groupRoomCreatedCallback(t)}),e.events.on("header-clicked",function(t){e.options.headerClickedCallback&&e.options.headerClickedCallback(t)}),e.events.on("comment-read",function(t){e.logging("comment-read",t),e.options.commentReadCallback&&e.options.commentReadCallback(t)}),e.events.on("presence",({message:t,userId:r})=>{const n=t.split(":");this.chatmateStatus!==n[0]&&(this.chatmateStatus=n[0]===1?"Online":`Last seen ${fm(Number(n[1].substring(0,13)))}`),e.options.presenceCallback&&e.options.presenceCallback(t,r)}),e.events.on("typing",function(t){e.options.typingCallback&&e.options.typingCallback(t)}),e.events.on("message-info",function(t){e.options.messageInfoCallback&&e.options.messageInfoCallback(t)}),e.events.on("participants-added",t=>{t==null||this.selected==null||this.selected.participants.push(...t)}),e.events.on("participants-removed",t=>{if(t==null||this.selected==null)return;const r=this.selected.participants.filter(n=>t.indexOf(n.email)<=-1);this.selected.participants=r}),e.events.on("block-user",function(t){e.options.blockUserCallback&&e.options.blockUserCallback(t)}),e.events.on("unblock-user",function(t){e.options.unblockUserCallback&&e.options.unblockUserCallback(t)})}onReconnectMqtt(){this.options.onReconnectCallback&&this.options.onReconnectedCallback(),this.selected&&this.loadComments(this.selected.id)}_callNewMessagesCallback(e){this.options.newMessagesCallback&&this.options.newMessagesCallback(e)}updateLastReceivedComment(e){this.last_received_comment_id<e&&(this.last_received_comment_id=e)}setUser(e,t,r,n,o){const u=this;u.user_id=e,u.key=t,u.username=r,u.avatar_url=n;let a={email:this.user_id,password:this.key,username:this.username,extras:o?JSON.stringify(o):null};return this.avatar_url&&(a.avatar_url=this.avatar_url),new Promise((s,l)=>{let d=setInterval(()=>{if(!this.isConfigLoaded)this.debugMode&&this.logger("Waiting for init config...");else return clearInterval(d),this.logger("Config Success!"),u.events.emit("start-init"),u.authAdapter.loginOrRegister(a).then(g=>{u.isInit=!0,u.refresh_token=g.user.refresh_token,u.events.emit("login-success",g),this.realtimeAdapter.connect(),s(g)},g=>{u.events.emit("login-error",g),l(g)})},300)})}setUserWithIdentityToken(e){if(!e||!("user"in e))return this.events.emit("login-error",e);this.email=e.user.email,this.user_id=e.user.email,this.key=e.identity_token,this.username=e.user.username,this.avatar_url=e.user.avatar_url,this.isInit=!0;let t=setInterval(()=>{this.isConfigLoaded?(clearInterval(t),this.logger("Config Success!"),this.events.emit("login-success",e)):this.debugMode&&this.logger("Waiting for init config...")},300)}refreshAuthToken(){return this.expiredTokenAdapter.refreshAuthToken()}publishOnlinePresence(e){e===!0?Wp=setInterval(()=>{this.realtimeAdapter.publishPresence(this.user_id,!0)},3500):(clearInterval(this.presensePublisherId),clearInterval(Wp),setTimeout(()=>{this.realtimeAdapter.publishPresence(this.user_id,!1)},3500))}subscribeUserPresence(e){this.realtimeAdapter.subscribeUserPresence(e)}unsubscribeUserPresence(e){this.realtimeAdapter.unsubscribeUserPresence(e)}logout(){return ke(this,null,function*(){yield this.expiredTokenAdapter.logout(),clearInterval(this.presensePublisherId),this.publishOnlinePresence(!1),this.selected=null,this.isInit=!1,this.isLogin=!1,this.realtimeAdapter.disconnect(),this.userData={}})}get synchronize(){return this.syncAdapter.synchronize}get synchronizeEvent(){return this.syncAdapter.synchronizeEvent}disconnect(){this.logout()}setActiveRoom(e){if(this.selected&&(this.realtimeAdapter.unsubscribeTyping(),this.selected.room_type==="single")){const n=this.selected.participants.filter(o=>o.email!==this.user_id);n.length>0&&this.realtimeAdapter.unsubscribeRoomPresence(n[0].email)}e.participants==null&&(e.participants=[]);const t=e.participants.find(n=>n.email!==this.user_id);this.chatmateStatus=null,this.isTypingStatus=null,this.selected=e;const r=setInterval(()=>{this.debugMode&&this.logger("Trying Initial Subscribe"),this.realtimeAdapter!=null?(this.debugMode&&this.logger("MQTT Connected"),clearInterval(r),e.room_type==="single"&&t!=null&&this.realtimeAdapter.subscribeRoomPresence(t.email),this.selected!=null&&!this.selected.isChannel&&(this.realtimeAdapter.subscribeTyping(e.id),this.events.emit("room-changed",this.selected)),this.debugMode&&this.realtimeAdapter==null&&this.logger("Retry")):this.debugMode&&this.logger("MQTT Not Connected, yet")},3e3)}chatTarget(e,t={}){if(this.userData.length!=null)return!1;const r=t?t.message:null,n=t.distinctId;return this.isLoading=!0,this.isTypingStatus="",this.roomAdapter.getOrCreateRoom(e,t,n).then(o=>ke(this,null,function*(){const u=new rr(o);this.updateLastReceivedComment(u.last_comment_id),this.isLoading=!1;const a=d=>ke(this,null,function*(){return yield this._hookAdapter.trigger(dt.MESSAGE_BEFORE_RECEIVED,d)});u.comments=yield Promise.all(u.comments.map(d=>a(d))),this.setActiveRoom(u);const s=u.comments[u.comments.length-1];if(s&&this.readComment(u.id,s.id),this.events.emit("chat-room-created",{room:u}),!r)return u;const l=u.id;return this.sendComment(l,r).then(()=>Promise.resolve(u)).catch(d=>{console.error("Error when submit comment",d)})})).catch(o=>(console.error("Error when creating room",o),this.isLoading=!1,Promise.reject(o)))}chatGroup(e){const t=this;if(t.isInit)return t.getRoomById(e).then(r=>Promise.resolve(r),r=>Promise.reject(r))}getRoomById(e){if(!this.isInit)return;const t=this;return t.isLoading=!0,t.isTypingStatus="",t.roomAdapter.getRoomById(e).then(r=>ke(this,null,function*(){const n=r.results.room,o=[];for(const s of r.results.comments.reverse()){const l=yield this._hookAdapter.trigger(dt.MESSAGE_BEFORE_RECEIVED,s);o.push(l)}const u=new rr(wr(br({},n),{comments:o,name:n.room_name}));t.updateLastReceivedComment(u.last_comment_id),t.setActiveRoom(u),t.isLoading=!1;const a=u.comments[u.comments.length-1];return a&&t.readComment(u.id,a.id),u.isChannel&&this.realtimeAdapter.subscribeChannel(this.AppId,u.unique_id),u})).catch(r=>(console.error("Error getting room by id",r),Promise.reject(r)))}getOrCreateRoomByUniqueId(e,t,r){const n=this;return n.isLoading=!0,n.isTypingStatus="",n.roomAdapter.getOrCreateRoomByUniqueId(e,t,r).then(o=>ke(this,null,function*(){let u=new rr(o);n.updateLastReceivedComment(u.last_comment_id);const a=l=>ke(this,null,function*(){return yield this._hookAdapter.trigger(dt.MESSAGE_BEFORE_RECEIVED,l)});u.comments=yield Promise.all(u.comments.map(l=>a(l))),n.setActiveRoom(u),n.isLoading=!1;const s=u.comments[u.comments.length-1];return s&&n.readComment(u.id,s.id),this.realtimeAdapter.subscribeChannel(this.AppId,u.unique_id),Promise.resolve(u)})).catch(o=>Promise.reject(o))}getOrCreateRoomByChannel(e,t,r){return this.getOrCreateRoomByUniqueId(e,t,r)}sortComments(){this.selected&&this.selected.comments.sort(function(e,t){return e.unix_timestamp-t.unix_timestamp})}loadRoomList(){return ke(this,arguments,function*(e={}){return(yield this.userAdapter.loadRoomList(e)).map(r=>(r.last_comment_id=r.last_comment.id,r.last_comment_message=r.last_comment.message,r.last_comment_message_created_at=r.last_comment.timestamp,r.room_type=r.chat_type,r.comments=[],new rr(r)))})}loadComments(e,t={}){return this.userAdapter.loadComments(e,t).then(r=>ke(this,null,function*(){const n=[];for(const o of r)n.push(yield this._hookAdapter.trigger(dt.MESSAGE_BEFORE_RECEIVED,o));return this.selected!=null&&(this.selected.receiveComments(n.reverse()),this.sortComments()),n}))}loadMore(e,t={}){if(this.selected!=null)return t.last_comment_id=e,t.after=!1,this.loadComments(this.selected.id,t)}registerDeviceToken(e,t=!1){return ke(this,null,function*(){return(yield this.HTTPAdapter.post("api/v2/sdk/set_user_device_token",{device_token:e,device_platform:"rn",is_development:t})).body.results})}removeDeviceToken(e,t=!1){return ke(this,null,function*(){return(yield this.HTTPAdapter.post("api/v2/sdk/remove_user_device_token",{device_token:e,device_platform:"rn",is_development:t})).body.results})}searchMessages(){return ke(this,arguments,function*(e={}){return console.warn("Deprecated: search message will be removed on next release"),(yield this.userAdapter.searchMessages(e)).map(r=>new pt(r))})}updateProfile(e){return this.userAdapter.updateProfile(e).then(t=>(this.events.emit("profile-updated",e),this.userData=t,Promise.resolve(t)),t=>this.logger(t))}getNonce(){return st.post(`${this.baseURL}/api/v2/sdk/auth/nonce`).send().set("qiscus_sdk_app_id",`${this.AppId}`).set("qiscus_sdk_version",`${this.version}`).then(e=>Promise.resolve(e.body.results),e=>Promise.reject(e))}verifyIdentityToken(e){return st.post(`${this.baseURL}/api/v2/sdk/auth/verify_identity_token`).send({identity_token:e}).set("qiscus_sdk_app_id",`${this.AppId}`).set("qiscus_sdk_version",`${this.version}`).then(t=>Promise.resolve(t.body.results),t=>Promise.reject(t))}sendComment(e,t,r,n="text",o,u){return ke(this,null,function*(){var q,k,A,R;const a=this;a.options.prePostCommentCallback&&a.options.prePostCommentCallback(t),a.options.commentFormaterCallback&&(t=a.options.commentFormaterCallback(t)),a.pendingCommentId--;const s={room_id:e,message:t,username_as:this.username,username_real:this.user_id,user_avatar_url:this.userData.avatar_url,user_extras:this.userData.user_extras,id:Math.round(Date.now()*1e6+Date.now()),type:n||"text",timestamp:am(new Date),unique_id:r?String(r):null,payload:jp(()=>JSON.parse(o),o,S=>this.logger("Error when parsing payload",S.message))},l=a.prepareCommentToBeSubmitted(s);if(n==="reply"){var d=JSON.parse(o),_=a.selected.comments.find(S=>S.id===d.replied_comment_id);d.replied_comment_message=_.type==="reply"?_.payload.text:_.message,d.replied_comment_sender_username=_.username_as,l.payload=d}const g=u||a.extras;let E=yield this._hookAdapter.trigger(dt.MESSAGE_BEFORE_SENT,wr(br({},l),{extras:g}));E=a.prepareCommentToBeSubmitted(E),a.selected&&a.selected.comments.push(E);const w=()=>this.userAdapter.postComment(""+e,E.message,E.unique_id,E.type,E.payload,E.extras);try{let S=yield w();if(S=yield this._hookAdapter.trigger(dt.MESSAGE_BEFORE_RECEIVED,S),Object.assign(E,S),!a.selected)return Promise.resolve(E);E.markAsSent(),E.id=S.id,E.before_id=S.comment_before_id,E.unix_timestamp=S.unix_timestamp,(k=(q=this.options).commentSentCallback)==null||k.call(q,{comment:E}),a.events.emit("comment-sent",E),a.sortComments();const b=a._pendingComments.findIndex(h=>h.unique_id===E.unique_id);return b>-1&&a._pendingComments.splice(b,1),E}catch(S){E.markAsFailed();const b=[void 0,408,413,429,500,502,503,504,521,522,524],p=((R=(A=S.message)==null?void 0:A.toLowerCase())!=null?R:"").includes("offline");return(b.includes(S.status)||p)&&(this._pendingComments.push(E),this.logger("Failed sending comment",S)),Promise.reject(S)}})}_retrySendComment(e){return ke(this,null,function*(){var t,r,n;if(this.logger("Retrying send comment",e),this._pendingCommentsCount[e.unique_id]=((t=this._pendingCommentsCount[e.unique_id])!=null?t:0)+1,this._pendingCommentsCount[e.unique_id]>10){this.logger(`Exceeding maximum retry count for comment ${e.unique_id}, not retrying anymore`),(n=(r=this.options).commentRetryExceedCallback)==null||n.call(r,e);const o=this._pendingComments.findIndex(u=>u.unique_id===e.unique_id);return o>-1&&this._pendingComments.splice(o,1),e.markAsFailed(),this.events.emit("comment-retry-exceed",e),Promise.reject(new Error("Exceeding maximum retry count"))}return this.userAdapter.postComment(""+e.room_id,e.message,e.unique_id,e.type,e.payload,e.extras).then(o=>ke(this,null,function*(){var s,l,d,_;if(((s=this.selected)==null?void 0:s.id)!==e.room_id)return o;Object.assign(e,o),e.markAsSent(),e.id=o.id,e.before_id=o.comment_before_id,e.unix_timestamp=o.unix_timestamp;const u=(l=this.selected)==null?void 0:l.comments.findIndex(g=>g.unique_id===e.unique_id);u>-1&&(this.selected.comments[u]=e),this.sortComments(),(_=(d=this.options).commentSentCallback)==null||_.call(d,{comment:e}),this.events.emit("comment-sent",e);const a=this._pendingComments.findIndex(g=>g.unique_id===e.unique_id);return a>-1&&this._pendingComments.splice(a,1),e})).catch(o=>(e.markAsFailed(),Promise.reject(o)))})}getUsers(e="",t=1,r=20){return this.HTTPAdapter.get_request("api/v2/sdk/get_user_list").query({query:e,page:t,limit:r}).then(n=>Promise.resolve(n.body.results))}getParticipants(e,t=1,r=20){return this.HTTPAdapter.get_request("api/v2/sdk/room_participants").query({room_unique_id:e,page:t,limit:r}).then(n=>n.body.results)}getRoomParticipants(e,t=0){return console.warn("`getRoomParticipants` are deprecated, use `getParticipants` instead."),this.HTTPAdapter.get_request("api/v2/sdk/room_participants").query({room_unique_id:e,offset:t}).then(r=>Promise.resolve(r.body.results))}resendComment(e){if(this.selected==null)return;var t=this,r=t.selected,n=r.comments.find(u=>u.id===e.id);const o=t.extras;return this.userAdapter.postComment(""+r.id,n.message,n.unique_id,e.type,e.payload,o).then(u=>(n.markAsSent(),n.id=u.id,n.before_id=u.comment_before_id,new Promise((a,s)=>a(t.selected))),u=>(n.markAsFailed(),new Promise((a,s)=>s(u))))}prepareCommentToBeSubmitted(e){let t=new pt(e),r=`javascript-${Me()}`;return e.unique_id&&(r=e.unique_id),t.attachUniqueId(r),t.markAsPending(),t.isDelivered=!1,t.isSent=!1,t.isRead=!1,t.unix_timestamp=Math.round(new Date().getTime()/1e3),t}updateRoom(e){return this.roomAdapter.updateRoom(e)}removeSelectedRoomParticipants(e=[],t="id"){if(Ye.not.array(e))return Promise.reject(new Error("`values` must have type of array"));const r=this.selected.participants;if(!r)return Promise.reject(new Error("Nothing selected room chat."));let n=r;return t==="id"&&(n=r.filter(o=>e.indexOf(o.id)<=-1)),t==="email"&&(n=r.filter(o=>e.indexOf(o.email)<=-1)),t==="username"&&(n=r.filter(o=>e.indexOf(o.username)<=-1)),this.selected.participants=n,Promise.resolve(r)}createGroupRoom(e,t,r){const n=this;if(!this.isLogin)throw new Error("Please initiate qiscus SDK first");return new Zy(this.roomAdapter).withName(e).withOptions(r).addParticipants(t).create().then(o=>(n.events.emit("group-room-created",o),Promise.resolve(o)))}addParticipantsToGroup(e,t){const r=this;if(!Array.isArray(t))throw new Error("emails' must be type of Array");return r.roomAdapter.addParticipantsToGroup(e,t).then(n=>(r.events.emit("participants-added",n),Promise.resolve(n)),n=>Promise.reject(n))}removeParticipantsFromGroup(e,t){return Ye.not.array(t)?Promise.reject(new Error("`emails` must have type of array")):this.roomAdapter.removeParticipantsFromGroup(e,t).then(r=>(this.events.emit("participants-removed",t),Promise.resolve(r)))}getBlockedUser(e=1,t=20){return this.userAdapter.getBlockedUser(e,t).then(n=>Promise.resolve(n),n=>Promise.reject(n))}blockUser(e){const t=this;return t.userAdapter.blockUser(e).then(r=>(t.events.emit("block-user",r),Promise.resolve(r)),r=>Promise.reject(r))}unblockUser(e){const t=this;return t.userAdapter.unblockUser(e).then(r=>(t.events.emit("unblock-user",r),Promise.resolve(r)),r=>Promise.reject(r))}getUserPresences(e=[]){if(Ye.not.array(e))return Promise.reject(new Error("`email` must have type of array"));const t=this;return t.userAdapter.getUserPresences(e).then(r=>(t.events.emit("user-status",r),Promise.resolve(r)),r=>Promise.reject(r))}upload(e,t){let r=st.post(this.uploadURL);return r=this.HTTPAdapter.setupHeaders(r),r.attach("file",e).on("progress",n=>{n.direction==="upload"&&t(null,n)}).then(n=>{const o=n.body.results.file.url;return t(null,null,n.body.results.file.url),Promise.resolve(o)}).catch(n=>(t(n),Promise.reject(n)))}uploadFile(e,t){const r=this;var n=new FormData;n.append("file",t);var o=new XMLHttpRequest;o.open("POST",`${r.baseURL}/api/v2/sdk/upload`,!0),o.setRequestHeader("qiscus_sdk_app_id",`${r.AppId}`),o.setRequestHeader("qiscus_sdk_user_id",`${r.user_id}`),o.setRequestHeader("qiscus_sdk_token",`${r.userData.token}`),o.onload=function(){if(o.status===200){var u=JSON.parse(o.response).results.file.url;return r.events.emit("fileupload",u),r.sendComment(e,`[file] ${u} [/file]`)}else return Promise.reject(o)},o.send(n)}addUploadedFile(e,t){this.uploadedFiles.push(new ov(e,t))}removeUploadedFile(e,t){const r=this.uploadedFiles.findIndex(n=>n.name===e&&n.roomId===t);this.uploadedFiles.splice(r,1)}publishTyping(e){this.realtimeAdapter.publishTyping(e)}getRoomsInfo(e){return this.userAdapter.getRoomsInfo(e)}deleteComment(e,t,r,n){if(!Array.isArray(t))throw new Error("unique ids' must be type of Array");return this.userAdapter.deleteComment(e,t,r,n).then(o=>(this.events.emit("comment-deleted",{roomId:e,commentUniqueIds:t,isForEveryone:r,isHard:n}),Promise.resolve(o)),o=>Promise.reject(o))}clearRoomsCache(){if(this.selected){this.room_name_id_map={[this.selected.name]:this.selected.id};const e=this.rooms.length;let t=this.rooms.findIndex(r=>r.id===this.selected.id);t+1!==e&&this.rooms.splice(t+1,e-(t+1)),t=this.rooms.findIndex(r=>r.id===this.selected.id),t>0&&this.rooms.length>1&&this.rooms.splice(1,this.rooms.length-1)}}exitChatRoom(){this.realtimeAdapter.unsubscribeTyping(),jp(()=>this.selected.participants.filter(e=>e.email!==this.user_id).map(e=>e.email),null,this.noop,e=>e.forEach(t=>this.realtimeAdapter.unsubscribeRoomPresence(t))),this.selected=null}clearRoomMessages(e){if(!Array.isArray(e))throw new Error("room_ids must be type of array");return this.userAdapter.clearRoomMessages(e)}logging(e,t={}){this.debugMode&&console.log(e,t)}getTotalUnreadCount(){return this.roomAdapter.getTotalUnreadCount().then(e=>Promise.resolve(e),e=>Promise.reject(e))}getRoomUnreadCount(){return this.roomAdapter.getRoomUnreadCount()}publishEvent(...e){this.customEventAdapter.publishEvent(...e)}subscribeEvent(...e){this.customEventAdapter.subscribeEvent(...e)}unsubscribeEvent(...e){this.customEventAdapter.unsubscribeEvent(...e)}setCustomHeader(e){if(Ye.not.json(e))throw new TypeError("`headers` must have type of object");this._customHeader=e}getUserProfile(){return this.userAdapter.getProfile()}get Interceptor(){return dt}intercept(e,t){return this._hookAdapter.intercept(e,t)}getThumbnailURL(e){const t=/^https?:\/\/\S+(\/upload\/)\S+(\.\w+)$/i;return e.replace(t,(r,n,o)=>r.replace(n,"/upload/w_320,h_320,c_limit/").replace(o,".png"))}getBlurryThumbnailURL(e){const t=/^https?:\/\/\S+(\/upload\/)\S+(\.\w+)$/i;return e.replace(t,(r,n,o)=>r.replace(n,"/upload/w_320,h_320,c_limit,e_blur:300/").replace(o,".png"))}get logger(){return this.debugMode?console.log.bind(console,"Qiscus ->"):this.noop}noop(){}get _throttleDelay(){return this.updateCommentStatusMode===vt.UpdateCommentStatusMode.enabled?0:this.updateCommentStatusThrottleDelay||300}get _updateStatusEnabled(){return this.updateCommentStatusMode!==vt.UpdateCommentStatusMode.disabled}_updateStatus(e,t=null,r=null){const n=r!=null,o=t!=null;this.selected!=null&&this.selected.id;const u=this.selected!=null&&this.selected.isChannel||!1,a=!this._updateStatusEnabled,s=(()=>{if(o)return"read";if(n)return"receive"})(),l=!(u||n&&a);if(this.debugMode&&(console.group("update-command-status"),console.log("run:",s,`on: roomId(${e}) commentId(${t||r})`),console.log("is able to run command?",l),console.groupEnd()),!l)return!1;this.userAdapter.updateCommentStatus(e,t,r).catch(d=>{})}readComment(e,t){return this.updateCommentStatusMode===vt.UpdateCommentStatusMode.enabled?this._readComment(e,t):this._readCommentT(e,t)}receiveComment(e,t){return this.updateCommentStatusMode===vt.UpdateCommentStatusMode.enabled?this._deliverComment(e,t):this._deliverCommentT(e,t)}_throttle(e,t){let r=!1;return(...n)=>{let o=t();r||(e(...n),r=!0,setTimeout(()=>r=!1,o))}}searchMessage(){return ke(this,arguments,function*({query:e,roomIds:t=[],userId:r,type:n,roomType:o,page:u,limit:a}={}){const s="api/v2/sdk/search",l=["group","single","channel"].some(_=>_===o);if(o!=null&&!l)return Promise.reject("Invalid room type, valid room type are: `group`, `single`, and `channel`");const d=(_=>{const g=_==null?void 0:_==="single"?"single":"group",E=_==null?void 0:_==="channel";return{type:g,isPublic:E}})(o);return this.HTTPAdapter.post_json(s,{token:this.token,query:e,sender:r,type:n,room_ids:t.map(_=>String(_)),room_type:d.type||void 0,is_public:d.isPublic||void 0,page:u,limit:a}).then(_=>_.body)})}getFileList(){return ke(this,arguments,function*({roomIds:e=[],fileType:t,page:r,limit:n,sender:o,userId:u,includeExtensions:a,excludeExtensions:s}={}){const l="api/v2/sdk/file_list";if(!this.isLogin)return Promise.reject("You need to login to use this method");o===void 0&&(o=this.user_id),u===void 0&&(o=u=this.user_id);let d={room_ids:e.map(_=>String(_)),file_type:t,page:r,limit:n,include_extensions:a,exclude_extensions:s};return o!=null&&(d.sender=o),this.HTTPAdapter.post_json(l,d).then(_=>_.body)})}_generateUniqueId(){return`javascript-${Me()}`}generateMessage({roomId:e,text:t,extras:r}){const n=Date.now();return new pt({id:n,message:t,room_id:e,extras:r,timestamp:new Date,unique_id:this._generateUniqueId(),before_id:0,username:this.userData.username,email:this.userData.email,status:"pending",type:"text"})}generateFileAttachmentMessage({roomId:e,caption:t,url:r,text:n="File attachment",extras:o,filename:u,size:a}){const s=Date.now();return new pt({id:s,message:n,room_id:e,extras:o,timestamp:new Date,unique_id:this._generateUniqueId(),before_id:0,username:this.userData.username,email:this.userData.email,status:"pending",type:"file_attachment",payload:{url:r,file_name:u,size:a,caption:t}})}generateCustomMessage({roomId:e,text:t,type:r,payload:n,extras:o}){const u=Date.now();return new pt({id:u,message:t,room_id:e,extras:o,timestamp:new Date,unique_id:this._generateUniqueId(),before_id:0,username:this.userData.username,email:this.userData.email,status:"pending",type:"custom",payload:{type:r,content:n}})}generateReplyMessage({roomId:e,text:t,repliedMessage:r,extras:n}){const o=Date.now();return new pt({id:o,message:t,room_id:e,extras:n,timestamp:new Date,unique_id:this._generateUniqueId(),before_id:0,username:this.userData.username,email:this.userData.email,status:"pending",type:"reply",payload:{text:t,replied_comment_id:r.id,replied_comment_message:r.message,replied_comment_type:r.type,replied_comment_payload:r.payload,replied_comment_sender_username:r.username_as,replied_comment_sender_email:r.username_real}})}updateMessage(e){return ke(this,null,function*(){return this.userAdapter.updateMessage(e)})}onMessageUpdated(e){return this.realtimeAdapter.on("message:updated",e),()=>this.realtimeAdapter.off("message:updated",e)}closeRealtimeConnection(){return ke(this,null,function*(){return this.realtimeAdapter.closeConnection()})}openRealtimeConnection(){return ke(this,null,function*(){return this.realtimeAdapter.openConnection()})}startSync(){return ke(this,null,function*(){this._forceEnableSync=!0})}stopSync(){return ke(this,null,function*(){this._forceEnableSync=!1})}};He(vt,"UpdateCommentStatusMode",iv),He(vt,"Interceptor",dt);let Qa=vt;class ov{constructor(e,t){this.name=e,this.roomId=t,this.progress=0}}return Qa}));
27
27
  //# sourceMappingURL=qiscus-sdk-core.min.js.map