@ermis-network/ermis-chat-sdk 1.0.6 → 1.0.7

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.
@@ -17,8 +17,8 @@
17
17
  `,Mf=Ln.encode(At),jf=2,oa=class{constructor(e,t){let{escapeName:s}=this.constructor,i=d.isString(t),a=`Content-Disposition: form-data; name="${s(e)}"${!i&&t.name?`; filename="${s(t.name)}"`:""}${At}`;i?t=Ln.encode(String(t).replace(/\r?\n|\r\n?/g,At)):a+=`Content-Type: ${t.type||"application/octet-stream"}${At}`,this.headers=Ln.encode(a+At),this.contentLength=i?t.byteLength:t.size,this.size=this.headers.byteLength+this.contentLength+jf,this.name=e,this.value=t}async*encode(){yield this.headers;let{value:e}=this;d.isTypedArray(e)?yield e:yield*As(e),yield Mf}static escapeName(e){return String(e).replace(/[\r\n"]/g,t=>({"\r":"%0D","\n":"%0A",'"':"%22"})[t])}},Nf=(n,e,t)=>{let{tag:s="form-data-boundary",size:i=25,boundary:a=s+"-"+$.generateString(i,Pf)}=t||{};if(!d.isFormData(n))throw TypeError("FormData instance required");if(a.length<1||a.length>70)throw Error("boundary must be 10-70 characters long");let r=Ln.encode("--"+a+At),o=Ln.encode("--"+a+"--"+At),l=o.byteLength,c=Array.from(n.entries()).map(([u,m])=>{let f=new oa(u,m);return l+=f.size,f});l+=r.byteLength*c.length,l=d.toFiniteNumber(l);let p={"Content-Type":`multipart/form-data; boundary=${a}`};return Number.isFinite(l)&&(p["Content-Length"]=l),e&&e(p),sl.Readable.from((async function*(){for(let u of c)yield r,yield*u.encode();yield o})())},il=Nf;var al=Re(I("stream"),1),ca=class extends al.default.Transform{__transform(e,t,s){this.push(e),s()}_transform(e,t,s){if(e.length!==0&&(this._transform=this.__transform,e[0]!==120)){let i=Buffer.alloc(2);i[0]=120,i[1]=156,this.push(i,t)}this.__transform(e,t,s)}},rl=ca;var qf=(n,e)=>d.isAsyncFn(n)?function(...t){let s=t.pop();n.apply(this,t).then(i=>{try{e?s(null,...e(i)):s(null,i)}catch(a){s(a)}},s)}:n,ol=qf;function Gf(n,e){n=n||10;let t=new Array(n),s=new Array(n),i=0,a=0,r;return e=e!==void 0?e:1e3,function(l){let c=Date.now(),p=s[a];r||(r=c),t[i]=l,s[i]=c;let u=a,m=0;for(;u!==i;)m+=t[u++],u=u%n;if(i=(i+1)%n,i===a&&(a=(a+1)%n),c-r<e)return;let f=p&&c-p;return f?Math.round(m*1e3/f):void 0}}var cl=Gf;function Bf(n,e){let t=0,s=1e3/e,i,a,r=(c,p=Date.now())=>{t=p,i=null,a&&(clearTimeout(a),a=null),n.apply(null,c)};return[(...c)=>{let p=Date.now(),u=p-t;u>=s?r(c,p):(i=c,a||(a=setTimeout(()=>{a=null,r(i)},s-u)))},()=>i&&r(i)]}var ll=Bf;var it=(n,e,t=3)=>{let s=0,i=cl(50,250);return ll(a=>{let r=a.loaded,o=a.lengthComputable?a.total:void 0,l=r-s,c=i(l),p=r<=o;s=r;let u={loaded:r,total:o,progress:o?r/o:void 0,bytes:l,rate:c||void 0,estimated:c&&o&&p?(o-r)/c:void 0,event:a,lengthComputable:o!=null,[e?"download":"upload"]:!0};n(u)},t)},nn=(n,e)=>{let t=n!=null;return[s=>e[0]({lengthComputable:t,total:n,loaded:s}),e[1]]},sn=n=>(...e)=>d.asap(()=>n(...e));var pl={flush:at.default.constants.Z_SYNC_FLUSH,finishFlush:at.default.constants.Z_SYNC_FLUSH},$f={flush:at.default.constants.BROTLI_OPERATION_FLUSH,finishFlush:at.default.constants.BROTLI_OPERATION_FLUSH},ul=d.isFunction(at.default.createBrotliDecompress),{http:zf,https:Wf}=xl.default,Vf=/https:?/,dl=$.protocols.map(n=>n+":"),ml=(n,[e,t])=>(n.on("end",t).on("error",t),e);function Hf(n,e){n.beforeRedirects.proxy&&n.beforeRedirects.proxy(n),n.beforeRedirects.config&&n.beforeRedirects.config(n,e)}function _l(n,e,t){let s=e;if(!s&&s!==!1){let i=hl.default.getProxyForUrl(t);i&&(s=new URL(i))}if(s){if(s.username&&(s.auth=(s.username||"")+":"+(s.password||"")),s.auth){(s.auth.username||s.auth.password)&&(s.auth=(s.auth.username||"")+":"+(s.auth.password||""));let a=Buffer.from(s.auth,"utf8").toString("base64");n.headers["Proxy-Authorization"]="Basic "+a}n.headers.host=n.hostname+(n.port?":"+n.port:"");let i=s.hostname||s.host;n.hostname=i,n.host=i,n.port=s.port,n.path=t,s.protocol&&(n.protocol=s.protocol.includes(":")?s.protocol:`${s.protocol}:`)}n.beforeRedirects.proxy=function(a){_l(a,e,a.href)}}var Kf=typeof process<"u"&&d.kindOf(process)==="process",Jf=n=>new Promise((e,t)=>{let s,i,a=(l,c)=>{i||(i=!0,s&&s(l,c))},r=l=>{a(l),e(l)},o=l=>{a(l,!0),t(l)};n(r,o,l=>s=l).catch(o)}),Xf=({address:n,family:e})=>{if(!d.isString(n))throw TypeError("address must be a string");return{address:n,family:e||(n.indexOf(".")<0?6:4)}},fl=(n,e)=>Xf(d.isObject(n)?n:{address:n,family:e}),yl=Kf&&function(e){return Jf(async function(s,i,a){let{data:r,lookup:o,family:l}=e,{responseType:c,responseEncoding:p}=e,u=e.method.toUpperCase(),m,f=!1,g;if(o){let T=ol(o,A=>d.isArray(A)?A:[A]);o=(A,X,Te)=>{T(A,X,(ee,Ge,bt)=>{if(ee)return Te(ee);let Be=d.isArray(Ge)?Ge.map(ke=>fl(ke)):[fl(Ge,bt)];X.all?Te(ee,Be):Te(ee,Be[0].address,Be[0].family)})}}let v=new vl.EventEmitter,_=()=>{e.cancelToken&&e.cancelToken.unsubscribe(R),e.signal&&e.signal.removeEventListener("abort",R),v.removeAllListeners()};a((T,A)=>{m=!0,A&&(f=!0,_())});function R(T){v.emit("abort",!T||T.type?new je(null,e,g):T)}v.once("abort",i),(e.cancelToken||e.signal)&&(e.cancelToken&&e.cancelToken.subscribe(R),e.signal&&(e.signal.aborted?R():e.signal.addEventListener("abort",R)));let D=Et(e.baseURL,e.url,e.allowAbsoluteUrls),L=new URL(D,$.hasBrowserEnv?$.origin:void 0),q=L.protocol||dl[0];if(q==="data:"){let T;if(u!=="GET")return Xe(s,i,{status:405,statusText:"method not allowed",headers:{},config:e});try{T=sa(e.url,c==="blob",{Blob:e.env&&e.env.Blob})}catch(A){throw C.from(A,C.ERR_BAD_REQUEST,e)}return c==="text"?(T=T.toString(p),(!p||p==="utf8")&&(T=d.stripBOM(T))):c==="stream"&&(T=It.default.Readable.from(T)),Xe(s,i,{data:T,status:200,statusText:"OK",headers:new se,config:e})}if(dl.indexOf(q)===-1)return i(new C("Unsupported protocol "+q,C.ERR_BAD_REQUEST,e));let M=se.from(e.headers).normalize();M.set("User-Agent","axios/"+kt,!1);let{onUploadProgress:Y,onDownloadProgress:ae}=e,Z=e.maxRate,ye,Le;if(d.isSpecCompliantForm(r)){let T=M.getContentType(/boundary=([-_\w\d]{10,70})/i);r=il(r,A=>{M.set(A)},{tag:`axios-${kt}-boundary`,boundary:T&&T[1]||void 0})}else if(d.isFormData(r)&&d.isFunction(r.getHeaders)){if(M.set(r.getHeaders()),!M.hasContentLength())try{let T=await bl.default.promisify(r.getLength).call(r);Number.isFinite(T)&&T>=0&&M.setContentLength(T)}catch{}}else if(d.isBlob(r)||d.isFile(r))r.size&&M.setContentType(r.type||"application/octet-stream"),M.setContentLength(r.size||0),r=It.default.Readable.from(As(r));else if(r&&!d.isStream(r)){if(!Buffer.isBuffer(r))if(d.isArrayBuffer(r))r=Buffer.from(new Uint8Array(r));else if(d.isString(r))r=Buffer.from(r,"utf-8");else return i(new C("Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream",C.ERR_BAD_REQUEST,e));if(M.setContentLength(r.length,!1),e.maxBodyLength>-1&&r.length>e.maxBodyLength)return i(new C("Request body larger than maxBodyLength limit",C.ERR_BAD_REQUEST,e))}let Nt=d.toFiniteNumber(M.getContentLength());d.isArray(Z)?(ye=Z[0],Le=Z[1]):ye=Le=Z,r&&(Y||ye)&&(d.isStream(r)||(r=It.default.Readable.from(r,{objectMode:!1})),r=It.default.pipeline([r,new ra({maxRate:d.toFiniteNumber(ye)})],d.noop),Y&&r.on("progress",ml(r,nn(Nt,it(sn(Y),!1,3)))));let qe;if(e.auth){let T=e.auth.username||"",A=e.auth.password||"";qe=T+":"+A}if(!qe&&L.username){let T=L.username,A=L.password;qe=T+":"+A}qe&&M.delete("authorization");let gt;try{gt=Ct(L.pathname+L.search,e.params,e.paramsSerializer).replace(/^\?/,"")}catch(T){let A=new Error(T.message);return A.config=e,A.url=e.url,A.exists=!0,i(A)}M.set("Accept-Encoding","gzip, compress, deflate"+(ul?", br":""),!1);let ce={path:gt,method:u,headers:M.toJSON(),agents:{http:e.httpAgent,https:e.httpsAgent},auth:qe,protocol:q,family:l,beforeRedirect:Hf,beforeRedirects:{}};!d.isUndefined(o)&&(ce.lookup=o),e.socketPath?ce.socketPath=e.socketPath:(ce.hostname=L.hostname.startsWith("[")?L.hostname.slice(1,-1):L.hostname,ce.port=L.port,_l(ce,e.proxy,q+"//"+L.hostname+(L.port?":"+L.port:"")+ce.path));let z,pe=Vf.test(ce.protocol);if(ce.agent=pe?e.httpsAgent:e.httpAgent,e.transport?z=e.transport:e.maxRedirects===0?z=pe?yt:gl.default:(e.maxRedirects&&(ce.maxRedirects=e.maxRedirects),e.beforeRedirect&&(ce.beforeRedirects.config=e.beforeRedirect),z=pe?Wf:zf),e.maxBodyLength>-1?ce.maxBodyLength=e.maxBodyLength:ce.maxBodyLength=1/0,e.insecureHTTPParser&&(ce.insecureHTTPParser=e.insecureHTTPParser),g=z.request(ce,function(A){if(g.destroyed)return;let X=[A],Te=+A.headers["content-length"];if(ae||Le){let ke=new ra({maxRate:d.toFiniteNumber(Le)});ae&&ke.on("progress",ml(ke,nn(Te,it(sn(ae),!0,3)))),X.push(ke)}let ee=A,Ge=A.req||g;if(e.decompress!==!1&&A.headers["content-encoding"])switch((u==="HEAD"||A.statusCode===204)&&delete A.headers["content-encoding"],(A.headers["content-encoding"]||"").toLowerCase()){case"gzip":case"x-gzip":case"compress":case"x-compress":X.push(at.default.createUnzip(pl)),delete A.headers["content-encoding"];break;case"deflate":X.push(new rl),X.push(at.default.createUnzip(pl)),delete A.headers["content-encoding"];break;case"br":ul&&(X.push(at.default.createBrotliDecompress($f)),delete A.headers["content-encoding"])}ee=X.length>1?It.default.pipeline(X,d.noop):X[0];let bt=It.default.finished(ee,()=>{bt(),_()}),Be={status:A.statusCode,statusText:A.statusMessage,headers:new se(A.headers),config:e,request:Ge};if(c==="stream")Be.data=ee,Xe(s,i,Be);else{let ke=[],qt=0;ee.on("data",function(re){ke.push(re),qt+=re.length,e.maxContentLength>-1&&qt>e.maxContentLength&&(f=!0,ee.destroy(),i(new C("maxContentLength size of "+e.maxContentLength+" exceeded",C.ERR_BAD_RESPONSE,e,Ge)))}),ee.on("aborted",function(){if(f)return;let re=new C("stream has been aborted",C.ERR_BAD_RESPONSE,e,Ge);ee.destroy(re),i(re)}),ee.on("error",function(re){g.destroyed||i(C.from(re,null,e,Ge))}),ee.on("end",function(){try{let re=ke.length===1?ke[0]:Buffer.concat(ke);c!=="arraybuffer"&&(re=re.toString(p),(!p||p==="utf8")&&(re=d.stripBOM(re))),Be.data=re}catch(re){return i(C.from(re,null,e,Be.request,Be))}Xe(s,i,Be)})}v.once("abort",ke=>{ee.destroyed||(ee.emit("error",ke),ee.destroy())})}),v.once("abort",T=>{i(T),g.destroy(T)}),g.on("error",function(A){i(C.from(A,null,e,g))}),g.on("socket",function(A){A.setKeepAlive(!0,1e3*60)}),e.timeout){let T=parseInt(e.timeout,10);if(Number.isNaN(T)){i(new C("error trying to parse `config.timeout` to int",C.ERR_BAD_OPTION_VALUE,e,g));return}g.setTimeout(T,function(){if(m)return;let X=e.timeout?"timeout of "+e.timeout+"ms exceeded":"timeout exceeded",Te=e.transitional||Jt;e.timeoutErrorMessage&&(X=e.timeoutErrorMessage),i(new C(X,Te.clarifyTimeoutError?C.ETIMEDOUT:C.ECONNABORTED,e,g)),R()})}if(d.isStream(r)){let T=!1,A=!1;r.on("end",()=>{T=!0}),r.once("error",X=>{A=!0,g.destroy(X)}),r.on("close",()=>{!T&&!A&&R(new je("Request stream has been aborted",e,g))}),r.pipe(g)}else g.end(r)})};var wl=$.hasStandardBrowserEnv?((n,e)=>t=>(t=new URL(t,$.origin),n.protocol===t.protocol&&n.host===t.host&&(e||n.port===t.port)))(new URL($.origin),$.navigator&&/(msie|trident)/i.test($.navigator.userAgent)):()=>!0;var Cl=$.hasStandardBrowserEnv?{write(n,e,t,s,i,a){let r=[n+"="+encodeURIComponent(e)];d.isNumber(t)&&r.push("expires="+new Date(t).toGMTString()),d.isString(s)&&r.push("path="+s),d.isString(i)&&r.push("domain="+i),a===!0&&r.push("secure"),document.cookie=r.join("; ")},read(n){let e=document.cookie.match(new RegExp("(^|;\\s*)("+n+")=([^;]*)"));return e?decodeURIComponent(e[3]):null},remove(n){this.write(n,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};var El=n=>n instanceof se?{...n}:n;function Je(n,e){e=e||{};let t={};function s(c,p,u,m){return d.isPlainObject(c)&&d.isPlainObject(p)?d.merge.call({caseless:m},c,p):d.isPlainObject(p)?d.merge({},p):d.isArray(p)?p.slice():p}function i(c,p,u,m){if(d.isUndefined(p)){if(!d.isUndefined(c))return s(void 0,c,u,m)}else return s(c,p,u,m)}function a(c,p){if(!d.isUndefined(p))return s(void 0,p)}function r(c,p){if(d.isUndefined(p)){if(!d.isUndefined(c))return s(void 0,c)}else return s(void 0,p)}function o(c,p,u){if(u in e)return s(c,p);if(u in n)return s(void 0,c)}let l={url:a,method:a,data:a,baseURL:r,transformRequest:r,transformResponse:r,paramsSerializer:r,timeout:r,timeoutMessage:r,withCredentials:r,withXSRFToken:r,adapter:r,responseType:r,xsrfCookieName:r,xsrfHeaderName:r,onUploadProgress:r,onDownloadProgress:r,decompress:r,maxContentLength:r,maxBodyLength:r,beforeRedirect:r,transport:r,httpAgent:r,httpsAgent:r,cancelToken:r,socketPath:r,responseEncoding:r,validateStatus:o,headers:(c,p,u)=>i(El(c),El(p),u,!0)};return d.forEach(Object.keys(Object.assign({},n,e)),function(p){let u=l[p]||i,m=u(n[p],e[p],p);d.isUndefined(m)&&u!==o||(t[p]=m)}),t}var Is=n=>{let e=Je({},n),{data:t,withXSRFToken:s,xsrfHeaderName:i,xsrfCookieName:a,headers:r,auth:o}=e;e.headers=r=se.from(r),e.url=Ct(Et(e.baseURL,e.url,e.allowAbsoluteUrls),n.params,n.paramsSerializer),o&&r.set("Authorization","Basic "+btoa((o.username||"")+":"+(o.password?unescape(encodeURIComponent(o.password)):"")));let l;if(d.isFormData(t)){if($.hasStandardBrowserEnv||$.hasStandardBrowserWebWorkerEnv)r.setContentType(void 0);else if((l=r.getContentType())!==!1){let[c,...p]=l?l.split(";").map(u=>u.trim()).filter(Boolean):[];r.setContentType([c||"multipart/form-data",...p].join("; "))}}if($.hasStandardBrowserEnv&&(s&&d.isFunction(s)&&(s=s(e)),s||s!==!1&&wl(e.url))){let c=i&&a&&Cl.read(a);c&&r.set(i,c)}return e};var Qf=typeof XMLHttpRequest<"u",Sl=Qf&&function(n){return new Promise(function(t,s){let i=Is(n),a=i.data,r=se.from(i.headers).normalize(),{responseType:o,onUploadProgress:l,onDownloadProgress:c}=i,p,u,m,f,g;function v(){f&&f(),g&&g(),i.cancelToken&&i.cancelToken.unsubscribe(p),i.signal&&i.signal.removeEventListener("abort",p)}let _=new XMLHttpRequest;_.open(i.method.toUpperCase(),i.url,!0),_.timeout=i.timeout;function R(){if(!_)return;let L=se.from("getAllResponseHeaders"in _&&_.getAllResponseHeaders()),M={data:!o||o==="text"||o==="json"?_.responseText:_.response,status:_.status,statusText:_.statusText,headers:L,config:n,request:_};Xe(function(ae){t(ae),v()},function(ae){s(ae),v()},M),_=null}"onloadend"in _?_.onloadend=R:_.onreadystatechange=function(){!_||_.readyState!==4||_.status===0&&!(_.responseURL&&_.responseURL.indexOf("file:")===0)||setTimeout(R)},_.onabort=function(){_&&(s(new C("Request aborted",C.ECONNABORTED,n,_)),_=null)},_.onerror=function(){s(new C("Network Error",C.ERR_NETWORK,n,_)),_=null},_.ontimeout=function(){let q=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded",M=i.transitional||Jt;i.timeoutErrorMessage&&(q=i.timeoutErrorMessage),s(new C(q,M.clarifyTimeoutError?C.ETIMEDOUT:C.ECONNABORTED,n,_)),_=null},a===void 0&&r.setContentType(null),"setRequestHeader"in _&&d.forEach(r.toJSON(),function(q,M){_.setRequestHeader(M,q)}),d.isUndefined(i.withCredentials)||(_.withCredentials=!!i.withCredentials),o&&o!=="json"&&(_.responseType=i.responseType),c&&([m,g]=it(c,!0),_.addEventListener("progress",m)),l&&_.upload&&([u,f]=it(l),_.upload.addEventListener("progress",u),_.upload.addEventListener("loadend",f)),(i.cancelToken||i.signal)&&(p=L=>{_&&(s(!L||L.type?new je(null,n,_):L),_.abort(),_=null)},i.cancelToken&&i.cancelToken.subscribe(p),i.signal&&(i.signal.aborted?p():i.signal.addEventListener("abort",p)));let D=Un(i.url);if(D&&$.protocols.indexOf(D)===-1){s(new C("Unsupported protocol "+D+":",C.ERR_BAD_REQUEST,n));return}_.send(a||null)})};var Yf=(n,e)=>{let{length:t}=n=n?n.filter(Boolean):[];if(e||t){let s=new AbortController,i,a=function(c){if(!i){i=!0,o();let p=c instanceof Error?c:this.reason;s.abort(p instanceof C?p:new je(p instanceof Error?p.message:p))}},r=e&&setTimeout(()=>{r=null,a(new C(`timeout ${e} of ms exceeded`,C.ETIMEDOUT))},e),o=()=>{n&&(r&&clearTimeout(r),r=null,n.forEach(c=>{c.unsubscribe?c.unsubscribe(a):c.removeEventListener("abort",a)}),n=null)};n.forEach(c=>c.addEventListener("abort",a));let{signal:l}=s;return l.unsubscribe=()=>d.asap(o),l}},Rl=Yf;var Zf=function*(n,e){let t=n.byteLength;if(!e||t<e){yield n;return}let s=0,i;for(;s<t;)i=s+e,yield n.slice(s,i),s=i},eh=async function*(n,e){for await(let t of th(n))yield*Zf(t,e)},th=async function*(n){if(n[Symbol.asyncIterator]){yield*n;return}let e=n.getReader();try{for(;;){let{done:t,value:s}=await e.read();if(t)break;yield s}}finally{await e.cancel()}},la=(n,e,t,s)=>{let i=eh(n,e),a=0,r,o=l=>{r||(r=!0,s&&s(l))};return new ReadableStream({async pull(l){try{let{done:c,value:p}=await i.next();if(c){o(),l.close();return}let u=p.byteLength;if(t){let m=a+=u;t(m)}l.enqueue(new Uint8Array(p))}catch(c){throw o(c),c}},cancel(l){return o(l),i.return()}},{highWaterMark:2})};var Os=typeof fetch=="function"&&typeof Request=="function"&&typeof Response=="function",kl=Os&&typeof ReadableStream=="function",nh=Os&&(typeof TextEncoder=="function"?(n=>e=>n.encode(e))(new TextEncoder):async n=>new Uint8Array(await new Response(n).arrayBuffer())),Al=(n,...e)=>{try{return!!n(...e)}catch{return!1}},sh=kl&&Al(()=>{let n=!1,e=new Request($.origin,{body:new ReadableStream,method:"POST",get duplex(){return n=!0,"half"}}).headers.has("Content-Type");return n&&!e}),Tl=64*1024,pa=kl&&Al(()=>d.isReadableStream(new Response("").body)),Ds={stream:pa&&(n=>n.body)};Os&&(n=>{["text","arrayBuffer","blob","formData","stream"].forEach(e=>{!Ds[e]&&(Ds[e]=d.isFunction(n[e])?t=>t[e]():(t,s)=>{throw new C(`Response type '${e}' is not supported`,C.ERR_NOT_SUPPORT,s)})})})(new Response);var ih=async n=>{if(n==null)return 0;if(d.isBlob(n))return n.size;if(d.isSpecCompliantForm(n))return(await new Request($.origin,{method:"POST",body:n}).arrayBuffer()).byteLength;if(d.isArrayBufferView(n)||d.isArrayBuffer(n))return n.byteLength;if(d.isURLSearchParams(n)&&(n=n+""),d.isString(n))return(await nh(n)).byteLength},ah=async(n,e)=>{let t=d.toFiniteNumber(n.getContentLength());return t??ih(e)},Il=Os&&(async n=>{let{url:e,method:t,data:s,signal:i,cancelToken:a,timeout:r,onDownloadProgress:o,onUploadProgress:l,responseType:c,headers:p,withCredentials:u="same-origin",fetchOptions:m}=Is(n);c=c?(c+"").toLowerCase():"text";let f=Rl([i,a&&a.toAbortSignal()],r),g,v=f&&f.unsubscribe&&(()=>{f.unsubscribe()}),_;try{if(l&&sh&&t!=="get"&&t!=="head"&&(_=await ah(p,s))!==0){let M=new Request(e,{method:"POST",body:s,duplex:"half"}),Y;if(d.isFormData(s)&&(Y=M.headers.get("content-type"))&&p.setContentType(Y),M.body){let[ae,Z]=nn(_,it(sn(l)));s=la(M.body,Tl,ae,Z)}}d.isString(u)||(u=u?"include":"omit");let R="credentials"in Request.prototype;g=new Request(e,{...m,signal:f,method:t.toUpperCase(),headers:p.normalize().toJSON(),body:s,duplex:"half",credentials:R?u:void 0});let D=await fetch(g,m),L=pa&&(c==="stream"||c==="response");if(pa&&(o||L&&v)){let M={};["status","statusText","headers"].forEach(ye=>{M[ye]=D[ye]});let Y=d.toFiniteNumber(D.headers.get("content-length")),[ae,Z]=o&&nn(Y,it(sn(o),!0))||[];D=new Response(la(D.body,Tl,ae,()=>{Z&&Z(),v&&v()}),M)}c=c||"text";let q=await Ds[d.findKey(Ds,c)||"text"](D,n);return!L&&v&&v(),await new Promise((M,Y)=>{Xe(M,Y,{data:q,headers:se.from(D.headers),status:D.status,statusText:D.statusText,config:n,request:g})})}catch(R){throw v&&v(),R&&R.name==="TypeError"&&/Load failed|fetch/i.test(R.message)?Object.assign(new C("Network Error",C.ERR_NETWORK,n,g),{cause:R.cause||R}):C.from(R,R&&R.code,n,g)}});var ua={http:yl,xhr:Sl,fetch:Il};d.forEach(ua,(n,e)=>{if(n){try{Object.defineProperty(n,"name",{value:e})}catch{}Object.defineProperty(n,"adapterName",{value:e})}});var Dl=n=>`- ${n}`,rh=n=>d.isFunction(n)||n===null||n===!1,Us={getAdapter:n=>{n=d.isArray(n)?n:[n];let{length:e}=n,t,s,i={};for(let a=0;a<e;a++){t=n[a];let r;if(s=t,!rh(t)&&(s=ua[(r=String(t)).toLowerCase()],s===void 0))throw new C(`Unknown adapter '${r}'`);if(s)break;i[r||"#"+a]=s}if(!s){let a=Object.entries(i).map(([o,l])=>`adapter ${o} `+(l===!1?"is not supported by the environment":"is not available in the build")),r=e?a.length>1?`since :
18
18
  `+a.map(Dl).join(`
19
19
  `):" "+Dl(a[0]):"as no adapter specified";throw new C("There is no suitable adapter to dispatch the request "+r,"ERR_NOT_SUPPORT")}return s},adapters:ua};function da(n){if(n.cancelToken&&n.cancelToken.throwIfRequested(),n.signal&&n.signal.aborted)throw new je(null,n)}function Ls(n){return da(n),n.headers=se.from(n.headers),n.data=Tn.call(n,n.transformRequest),["post","put","patch"].indexOf(n.method)!==-1&&n.headers.setContentType("application/x-www-form-urlencoded",!1),Us.getAdapter(n.adapter||Xt.adapter)(n).then(function(s){return da(n),s.data=Tn.call(n,n.transformResponse,s),s.headers=se.from(s.headers),s},function(s){return kn(s)||(da(n),s&&s.response&&(s.response.data=Tn.call(n,n.transformResponse,s.response),s.response.headers=se.from(s.response.headers))),Promise.reject(s)})}var Fs={};["object","boolean","number","function","string","symbol"].forEach((n,e)=>{Fs[n]=function(s){return typeof s===n||"a"+(e<1?"n ":" ")+n}});var Ol={};Fs.transitional=function(e,t,s){function i(a,r){return"[Axios v"+kt+"] Transitional option '"+a+"'"+r+(s?". "+s:"")}return(a,r,o)=>{if(e===!1)throw new C(i(r," has been removed"+(t?" in "+t:"")),C.ERR_DEPRECATED);return t&&!Ol[r]&&(Ol[r]=!0,console.warn(i(r," has been deprecated since v"+t+" and will be removed in the near future"))),e?e(a,r,o):!0}};Fs.spelling=function(e){return(t,s)=>(console.warn(`${s} is likely a misspelling of ${e}`),!0)};function oh(n,e,t){if(typeof n!="object")throw new C("options must be an object",C.ERR_BAD_OPTION_VALUE);let s=Object.keys(n),i=s.length;for(;i-- >0;){let a=s[i],r=e[a];if(r){let o=n[a],l=o===void 0||r(o,a,n);if(l!==!0)throw new C("option "+a+" must be "+l,C.ERR_BAD_OPTION_VALUE);continue}if(t!==!0)throw new C("Unknown option "+a,C.ERR_BAD_OPTION)}}var Fn={assertOptions:oh,validators:Fs};var Qe=Fn.validators,an=class{constructor(e){this.defaults=e||{},this.interceptors={request:new Oi,response:new Oi}}async request(e,t){try{return await this._request(e,t)}catch(s){if(s instanceof Error){let i={};Error.captureStackTrace?Error.captureStackTrace(i):i=new Error;let a=i.stack?i.stack.replace(/^.+\n/,""):"";try{s.stack?a&&!String(s.stack).endsWith(a.replace(/^.+\n.+\n/,""))&&(s.stack+=`
20
- `+a):s.stack=a}catch{}}throw s}}_request(e,t){typeof e=="string"?(t=t||{},t.url=e):t=e||{},t=Je(this.defaults,t);let{transitional:s,paramsSerializer:i,headers:a}=t;s!==void 0&&Fn.assertOptions(s,{silentJSONParsing:Qe.transitional(Qe.boolean),forcedJSONParsing:Qe.transitional(Qe.boolean),clarifyTimeoutError:Qe.transitional(Qe.boolean)},!1),i!=null&&(d.isFunction(i)?t.paramsSerializer={serialize:i}:Fn.assertOptions(i,{encode:Qe.function,serialize:Qe.function},!0)),t.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),Fn.assertOptions(t,{baseUrl:Qe.spelling("baseURL"),withXsrfToken:Qe.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let r=a&&d.merge(a.common,a[t.method]);a&&d.forEach(["delete","get","head","post","put","patch","common"],g=>{delete a[g]}),t.headers=se.concat(r,a);let o=[],l=!0;this.interceptors.request.forEach(function(v){typeof v.runWhen=="function"&&v.runWhen(t)===!1||(l=l&&v.synchronous,o.unshift(v.fulfilled,v.rejected))});let c=[];this.interceptors.response.forEach(function(v){c.push(v.fulfilled,v.rejected)});let p,u=0,m;if(!l){let g=[Ls.bind(this),void 0];for(g.unshift.apply(g,o),g.push.apply(g,c),m=g.length,p=Promise.resolve(t);u<m;)p=p.then(g[u++],g[u++]);return p}m=o.length;let f=t;for(u=0;u<m;){let g=o[u++],v=o[u++];try{f=g(f)}catch(_){v.call(this,_);break}}try{p=Ls.call(this,f)}catch(g){return Promise.reject(g)}for(u=0,m=c.length;u<m;)p=p.then(c[u++],c[u++]);return p}getUri(e){e=Je(this.defaults,e);let t=Et(e.baseURL,e.url,e.allowAbsoluteUrls);return Ct(t,e.params,e.paramsSerializer)}};d.forEach(["delete","get","head","options"],function(e){an.prototype[e]=function(t,s){return this.request(Je(s||{},{method:e,url:t,data:(s||{}).data}))}});d.forEach(["post","put","patch"],function(e){function t(s){return function(a,r,o){return this.request(Je(o||{},{method:e,headers:s?{"Content-Type":"multipart/form-data"}:{},url:a,data:r}))}}an.prototype[e]=t(),an.prototype[e+"Form"]=t(!0)});var Pn=an;var ma=class n{constructor(e){if(typeof e!="function")throw new TypeError("executor must be a function.");let t;this.promise=new Promise(function(a){t=a});let s=this;this.promise.then(i=>{if(!s._listeners)return;let a=s._listeners.length;for(;a-- >0;)s._listeners[a](i);s._listeners=null}),this.promise.then=i=>{let a,r=new Promise(o=>{s.subscribe(o),a=o}).then(i);return r.cancel=function(){s.unsubscribe(a)},r},e(function(a,r,o){s.reason||(s.reason=new je(a,r,o),t(s.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;let t=this._listeners.indexOf(e);t!==-1&&this._listeners.splice(t,1)}toAbortSignal(){let e=new AbortController,t=s=>{e.abort(s)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let e;return{token:new n(function(i){e=i}),cancel:e}}},Ul=ma;function fa(n){return function(t){return n.apply(null,t)}}function ha(n){return d.isObject(n)&&n.isAxiosError===!0}var ga={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(ga).forEach(([n,e])=>{ga[e]=n});var Ll=ga;function Fl(n){let e=new Pn(n),t=xn(Pn.prototype.request,e);return d.extend(t,Pn.prototype,e,{allOwnKeys:!0}),d.extend(t,e,null,{allOwnKeys:!0}),t.create=function(i){return Fl(Je(n,i))},t}var ue=Fl(Xt);ue.Axios=Pn;ue.CanceledError=je;ue.CancelToken=Ul;ue.isCancel=kn;ue.VERSION=kt;ue.toFormData=dt;ue.AxiosError=C;ue.Cancel=ue.CanceledError;ue.all=function(e){return Promise.all(e)};ue.spread=fa;ue.isAxiosError=ha;ue.mergeConfig=Je;ue.AxiosHeaders=se;ue.formToJSON=n=>ws(d.isHTMLForm(n)?new FormData(n):n);ue.getAdapter=Us.getAdapter;ue.HttpStatusCode=Ll;ue.default=ue;var rn=ue;var{Axios:Fy,AxiosError:Py,CanceledError:My,isCancel:jy,CancelToken:Ny,VERSION:qy,all:Gy,Cancel:By,isAxiosError:$y,spread:zy,toFormData:Wy,AxiosHeaders:Vy,HttpStatusCode:Hy,formToJSON:Ky,getAdapter:Jy,mergeConfig:Xy}=rn;pt();var Pl=Re(Ai());function Ps(n,e){n.then().catch(t=>{console.warn(`failed to do ${e}, ran into error: `,t)})}var on=n=>new Promise(e=>setTimeout(e,n));function Ms(n){return n&&(Object.prototype.toString.call(n)==="[object Function]"||typeof n=="function"||n instanceof Function)}var mt={TOKEN_EXPIRED:40,WS_CLOSED_SUCCESS:1e3};function ch(n){return n!==null&&typeof n=="object"&&(n.readable||typeof n._read=="function")}function lh(n){return n!=null&&n.constructor!=null&&typeof n.constructor.isBuffer=="function"&&n.constructor.isBuffer(n)}function ph(n){return typeof window<"u"&&"File"in window&&n instanceof File}function uh(n){return typeof window<"u"&&"Blob"in window&&n instanceof Blob}function Ml(n,e,t){let s=new Pl.default;return ch(n)||lh(n)||ph(n)||uh(n)?e?s.append("file",n,e):s.append("file",n):s.append("file",{uri:n,name:e||n.split("/").reverse()[0],contentType:t||void 0,type:t||void 0}),s}function js(n){let e=Math.min(500+n*2e3,25e3),t=Math.min(Math.max(250,(n-1)*2e3),25e3);return Math.floor(Math.random()*(e-t)+t)}function Ue(){return dh()}function Mn(n){let e="";for(let t=0;t<n.length;t++)e+=n[t].toString(16).padStart(2,"0");return e}function dh(){let n=hh(16);return n[6]=n[6]&15|64,n[8]=n[8]&191|128,Mn(n.subarray(0,4))+"-"+Mn(n.subarray(4,6))+"-"+Mn(n.subarray(6,8))+"-"+Mn(n.subarray(8,10))+"-"+Mn(n.subarray(10,16))}function mh(n){let e=Math.pow(2,8*n.byteLength/n.length);for(let t=0;t<n.length;t++)n[t]=Math.random()*e}var fh=typeof crypto<"u"&&typeof crypto?.getRandomValues<"u"?crypto.getRandomValues.bind(crypto):typeof msCrypto<"u"?msCrypto.getRandomValues.bind(msCrypto):mh;function hh(n){let e=new Uint8Array(n);return fh(e),e}function jl(n){typeof window<"u"&&window.addEventListener&&(window.addEventListener("offline",n),window.addEventListener("online",n))}function Nl(n){typeof window<"u"&&window.removeEventListener&&(window.removeEventListener("offline",n),window.removeEventListener("online",n))}var ql=n=>{let e=[];for(let t in n)n[t]!==void 0&&(Array.isArray(n[t])||typeof n[t]=="object"?e.push(`${t}=${encodeURIComponent(JSON.stringify(n[t]))}`):e.push(`${t}=${encodeURIComponent(n[t])}`));return e.join("&")};function Gl(n){return{...n,__html:n.html,pinned_at:n.pinned_at?new Date(n.pinned_at):null,created_at:n.created_at?new Date(n.created_at):new Date,updated_at:n.updated_at?new Date(n.updated_at):new Date,status:n.status||"received"}}function Bl(n,e,t=!1,s="created_at",i=!0){let a=i||t,r=n;t&&(r=r.filter(v=>!(v.id&&e.id===v.id)));let o=r.length;if(o===0&&a)return r.concat(e);if(o===0)return[...r];if(s==="pinned_at")return r.concat(e);let l=e[s].getTime(),c=r[o-1][s].getTime()<l;if(c&&a)return r.concat(e);if(c)return[...r];let p=0,u=0,m=o-1;for(;p<=m;)u=Math.floor((m+p)/2),r[u][s].getTime()<=l?p=u+1:m=u-1;if(!t&&e.id){if(r[p]&&e.id===r[p].id)return r[p]=e,[...r];if(r[p-1]&&e.id===r[p-1].id)return r[p-1]=e,[...r]}a&&r.splice(p,0,e);let f=new Map,g=[];for(let v of r)f.has(v.id)||(f.set(v.id,!0),g.push(v));return g}var H=(n,e)=>n.length===0?[]:e.length===0?n.map(t=>(t.user={id:t.user?.id,name:t.user?.id,avatar:""},t)):n.map(t=>{let s=t.user?.id,i=t?.latest_reactions,a=t?.quoted_message,r=e.find(o=>o.id===s);if(r&&(t.user={id:r.id,name:r.name||r.id,avatar:r.avatar||""}),i&&(t.latest_reactions=i.map(o=>{let l=e.find(c=>c.id===o.user_id);return{...o,user:{id:l?.id||o.user_id,name:l?.name||o.user_id,avatar:l?.avatar||""}}})),a){let o=e.find(l=>l.id===a.user?.id);t.quoted_message.user={id:o?.id||a.user?.id,name:o?.name||a.user?.id,avatar:o?.avatar||""}}return t}),W=(n,e)=>{if(e.length===0)return{id:n,name:n,avatar:""};let t=e.find(s=>s.id===n);return{id:n,name:t?.name||n,avatar:t?.avatar||""}},Dt=(n,e)=>{if(n.length===0)return"Empty channel";let t=n.find(s=>s.user.id!==e);return t?t.user.name||t.user.id:"Empty channel"},jn=(n,e)=>{if(n.length===0)return"";let t=n.find(s=>s.user.id!==e);return t&&t.user.avatar||""};async function Nn(n,e){let t=(e||[]).map(a=>a.user?.id).filter(a=>!!a),s=n.state.users,i=t.filter(a=>!s[a]);i.length>0&&await n.getBatchUsers(i)}var Ot=(n=[])=>n.length>0?Math.max(...n.map(e=>new Date(e.created_at).getTime())):0,Ut=(n,e,t,s)=>{let i,a;if(["videoConfig","audioConfig","transciverState"].includes(t)&&s){i=1;let l=JSON.stringify(s);a=new TextEncoder().encode(l)}else t==="connected"?(i=1,a=new Uint8Array(0)):(i=9,a=new Uint8Array(n));let r=new Uint8Array(i+a.byteLength),o=0;switch(t){case"videoConfig":o=0;break;case"audioConfig":o=1;break;case"video-key":o=2;break;case"video-delta":o=3;break;case"audio":o=4;break;case"connected":o=6;break;case"transciverState":o=7;break}return r[0]=o,e!==null&&new DataView(r.buffer).setBigUint64(1,BigInt(e),!1),r.set(a,i),r},ba=n=>{let e="",t=new Uint8Array(n),s=t.byteLength;for(let i=0;i<s;i++)e+=String.fromCharCode(t[i]);return btoa(e)},$l=n=>{let e={2048:"123",4096:"153",8192:"156",16384:"183",32768:"186"},t=/2048|4096|8192|16384|32768/g;return n.match(t)?n.replace(t,s=>e[s]):"hev1.1.6.L123.B0"},zl=(n,e,t)=>{let s={cid:e,forward_cid:t,forward_message_id:n.id};return n.sticker_url&&(!n.text||n.text==="")&&(!n.attachments||Array.isArray(n.attachments)&&n.attachments.length===0)?(s.sticker_url=n.sticker_url,s.text=n.text):(s.text=n.text||"",n.attachments&&n.attachments.length>0&&(s.attachments=n.attachments.filter(i=>i.type!=="linkPreview"))),s};var qn=class{_channel;watcher_count;typing;read;pinnedMessages;watchers;members;unreadCount;membership;last_message_at;isUpToDate;messageSets=[];topics=[];constructor(e){this._channel=e,this.watcher_count=0,this.typing={},this.read={},this.initMessages(),this.pinnedMessages=[],this.watchers={},this.members={},this.membership={},this.unreadCount=0,this.isUpToDate=!0,this.last_message_at=e?.state?.last_message_at!=null?new Date(e.state.last_message_at):null}get messages(){return this.messageSets.find(e=>e.isCurrent)?.messages||[]}set messages(e){let t=this.messageSets.findIndex(s=>s.isCurrent);this.messageSets[t].messages=e}get latestMessages(){return this.messageSets.find(e=>e.isLatest)?.messages||[]}set latestMessages(e){let t=this.messageSets.findIndex(s=>s.isLatest);this.messageSets[t].messages=e}addMessageSorted(e,t=!1,s=!0,i="latest"){return this.addMessagesSorted([e],t,!1,s,i)}formatMessage(e){return{...e,__html:e.html,pinned_at:e.pinned_at?new Date(e.pinned_at):null,created_at:e.created_at?new Date(e.created_at):new Date,updated_at:e.updated_at?new Date(e.updated_at):null,status:e.status||"received"}}addMessagesSorted(e,t=!1,s=!1,i=!0,a="current"){let{messagesToAdd:r,targetMessageSetIndex:o}=this.findTargetMessageSet(e,i,a);for(let l=0;l<r.length;l+=1){let c=r[l].created_at instanceof Date,p;if(c?p=r[l]:(p=this.formatMessage(r[l]),p.user&&this._channel?.cid&&this._channel.getClient().state.updateUserReference(p.user,this._channel.cid),this.last_message_at||(this.last_message_at=new Date(p.created_at.getTime())),p.created_at.getTime()>this.last_message_at.getTime()&&(this.last_message_at=new Date(p.created_at.getTime()))),!p.pinned){let m=this.pinnedMessages.find(f=>f.id===p.id);m&&(p.pinned=!0,p.pinned_at=m.pinned_at||new Date)}!p.parent_id&&o!==-1&&(this.messageSets[o].messages=this._addToMessageList(this.messageSets[o].messages,p,t,"created_at",i))}return{messageSet:this.messageSets[o]}}addPinnedMessages(e){for(let t=0;t<e.length;t+=1)this.addPinnedMessage(e[t]);this.pinnedMessages.sort((t,s)=>{let i=t.pinned_at?new Date(t.pinned_at).getTime():0;return(s.pinned_at?new Date(s.pinned_at).getTime():0)-i})}addPinnedMessage(e){let t=this.formatMessage(e);this.pinnedMessages=this.pinnedMessages.filter(s=>s.id!==t.id),this.pinnedMessages=[t,...this.pinnedMessages]}removePinnedMessage(e){let{result:t}=this.removeMessageFromArray(this.pinnedMessages,e);this.pinnedMessages=t}addReaction(e,t,s){if(!t)return;let i=t;return this._updateMessage(t,a=>(i.own_reactions=this._addOwnReactionToMessage(a.own_reactions,e,s),this.formatMessage(i))),i}_addOwnReactionToMessage(e,t,s){return s?e=[]:e=this._removeOwnReactionFromMessage(e,t),e=e||[],this._channel.getClient().userID===t.user_id&&e.push(t),e}_removeOwnReactionFromMessage(e,t){return e&&e.filter(s=>s.user_id!==t.user_id||s.type!==t.type)}removeReaction(e,t){if(!t)return;let s=t;return this._updateMessage(t,i=>(s.own_reactions=this._removeOwnReactionFromMessage(i.own_reactions,e),this.formatMessage(s))),s}removeQuotedMessageReferences(e){let t=s=>({...s,created_at:s.created_at.toISOString(),pinned_at:s.pinned_at?.toISOString(),updated_at:s.updated_at?.toISOString()});this.messageSets.forEach(s=>{let i=s.messages.filter(a=>a.quoted_message_id===e.id).map(t).map(a=>({...a,quoted_message:{...e,attachments:[]}}));this.addMessagesSorted(i,!0)})}_updateMessage(e,t){let{parent_id:s,pinned:i}=e;if(!s){let a=this.findMessageSetIndex(e);if(a!==-1){let r=this.messageSets[a].messages.findIndex(o=>o.id===e.id);r!==-1&&(this.messageSets[a].messages[r]=t(this.messageSets[a].messages[r]))}}if(i){let a=this.pinnedMessages.findIndex(r=>r.id===e.id);a!==-1&&(this.pinnedMessages[a]=t(this.pinnedMessages[a]))}}setIsUpToDate=e=>{this.isUpToDate=e};updateMessageStatus(e,t){this._updateMessage({id:e},s=>({...s,status:t}))}_addToMessageList(e,t,s=!1,i="created_at",a=!0){return Bl(e,t,s,i,a)}removeMessage(e){let t=!1,s=e.messageSetIndex??this.findMessageSetIndex(e);if(s!==-1){let{removed:i,result:a}=this.removeMessageFromArray(this.messageSets[s].messages,e);this.messageSets[s].messages=a,t=i}return t}removeMessageFromArray=(e,t)=>{let s=e.filter(i=>!(i.id&&t.id&&i.id===t.id));return{removed:s.length<e.length,result:s}};updateUserMessages=e=>{let t=(s,i)=>{for(let a=0;a<s.length;a++){let r=s[a],o=r?.latest_reactions||[];r.user?.id===i.id&&(s[a]={...r,user:r.user?.id===i.id?i:r.user}),o&&o.some(l=>l.user?.id===i.id)&&(s[a]={...r,latest_reactions:o.map(l=>l.user?.id===i.id?{...l,user:i}:l)})}};this.messageSets.forEach(s=>t(s.messages,e)),t(this.pinnedMessages,e)};deleteUserMessages=(e,t=!1)=>{let s=(i,a,r=!1)=>{for(let o=0;o<i.length;o++){let l=i[o];l.user?.id===a.id&&(r?i[o]={cid:l.cid,created_at:l.created_at,deleted_at:new Date().toISOString(),id:l.id,latest_reactions:[],mentioned_users:[],own_reactions:[],parent_id:l.parent_id,reply_count:l.reply_count,status:l.status,type:"deleted",updated_at:l.updated_at,user:l.user}:i[o]={...l,type:"deleted",deleted_at:new Date().toISOString()})}};this.messageSets.forEach(i=>s(i.messages,e,t)),s(this.pinnedMessages,e,t)};filterErrorMessages(){let e=this.latestMessages.filter(t=>t.type!=="error");this.latestMessages=e}clean(){let e=new Date;for(let[t,s]of Object.entries(this.typing)){let i=typeof s.received_at=="string"?new Date(s.received_at):s.received_at||new Date;e.getTime()-i.getTime()>7e3&&(delete this.typing[t],this._channel.getClient().dispatchEvent({cid:this._channel.cid,type:"typing.stop",user:{id:t}}))}}clearMessages(){this.initMessages(),this.pinnedMessages=[]}initMessages(){this.messageSets=[{messages:[],isLatest:!0,isCurrent:!0}]}async loadMessageIntoState(e,t,s=25){let i,a=!1,r=t||e;if(e==="latest"){if(this.messages===this.latestMessages)return;i=this.messageSets.findIndex(o=>o.isLatest)}else i=this.findMessageSetIndex({id:r});i!==-1&&(this.switchToMessageSet(i),a=!0),a||await this._channel.query({messages:{id_around:r,limit:s}},"new"),i=this.findMessageSetIndex({id:r}),i!==-1&&this.switchToMessageSet(i)}findMessage(e,t){let s=this.findMessageSetIndex({id:e});if(s!==-1)return this.messageSets[s].messages.find(i=>i.id===e)}switchToMessageSet(e){let t=this.messageSets.find(s=>s.isCurrent);t&&(t.isCurrent=!1,this.messageSets[e].isCurrent=!0)}areMessageSetsOverlap(e,t){return e.some(s=>t.find(i=>s.id===i.id))}findMessageSetIndex(e){return this.messageSets.findIndex(t=>!!t.messages.find(s=>s.id===e.id))}findTargetMessageSet(e,t=!0,s="current"){let i=e,a;if(t){let r=this.messageSets.map((c,p)=>p).filter(c=>this.areMessageSetsOverlap(this.messageSets[c].messages,e));switch(s){case"new":r.length>0?a=r[0]:e.some(c=>!c.parent_id)&&(this.messageSets.push({messages:[],isCurrent:!1,isLatest:!1}),a=this.messageSets.length-1);break;case"current":a=this.messageSets.findIndex(c=>c.isCurrent);break;case"latest":a=this.messageSets.findIndex(c=>c.isLatest);break;default:a=-1}let o=r.splice(0,1)[0],l=[...r];if(o!==void 0&&o!==a&&l.push(a),l.length>0){let c=this.messageSets[o],p=this.messageSets.filter((m,f)=>l.indexOf(f)!==-1);p.forEach(m=>{c.isLatest=c.isLatest||m.isLatest,c.isCurrent=c.isCurrent||m.isCurrent,i=[...i,...m.messages]}),p.forEach(m=>this.messageSets.splice(this.messageSets.indexOf(m),1)),a=this.messageSets.findIndex(m=>this.areMessageSetsOverlap(m.messages,e))}}else a=this.findMessageSetIndex(e[0]);return{targetMessageSetIndex:a,messagesToAdd:i}}};function Gn(n){let e=n.lastIndexOf("."),t=e>0?n.slice(0,e):n,s=e>0?n.slice(e):"";return t.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/đ/g,"d").replace(/Đ/g,"D").replace(/\s+/g,"_")+s}function Wl(n){let e=n.type.toLowerCase(),t=n.name.toLowerCase().split(".").pop()||"";return e==="image/heic"||e==="image/heif"||t==="heic"||t==="heif"}function xa(n,e){let t=n.toLowerCase(),s=(e||"").toLowerCase().split(".").pop()||"";return t==="image/heic"||t==="image/heif"||s==="heic"||s==="heif"?"file":t.startsWith("image/")?"image":t.startsWith("video/")?"video":t.startsWith("audio/")?"audio":"file"}function Ns(n){return n.type==="video/mp4"||n.type==="video/webm"||n.type==="video/quicktime"}function qs(n,e,t,s){let i=Gn(n.name),a=n.type||"",r=xa(a,n.name);if(s)return{type:"voiceRecording",asset_url:e,title:i,file_size:n.size,mime_type:a,waveform_data:s.waveform_data,duration:s.duration};switch(r){case"image":return{type:"image",image_url:e,title:i,file_size:n.size,mime_type:a};case"video":return{type:"video",asset_url:e,title:i,file_size:n.size,mime_type:a,thumb_url:t||""};case"audio":return{type:"file",asset_url:e,title:i,file_size:n.size,mime_type:a};default:return{type:"file",asset_url:e,title:i,file_size:n.size,mime_type:a||""}}}var cn=class{_client;type;id;data;_data;cid;listeners;state;initialized;offlineMode;lastKeyStroke;lastTypingEvent;isTyping;disconnected;constructor(e,t,s,i){let a=/^[\w_-]+$/,r=/^[\w!:_-]+$/;if(!a.test(t))throw new Error(`Invalid chat type ${t}, letters, numbers and "_-" are allowed`);if(typeof s=="string"&&!r.test(s))throw new Error(`Invalid chat id ${s}, letters, numbers and "!-_" are allowed`);this._client=e,this.type=t,this.id=s,this.data=i,this._data={...i},this.cid=`${t}:${s}`,this.listeners={},this.state=new qn(this),this.initialized=!1,this.offlineMode=!1,this.lastTypingEvent=null,this.isTyping=!1,this.disconnected=!1}getClient(){return this._client}async sendMessage(e){e.id||(e={...e,id:Ue()});let t=e.id,s={...e,id:t,status:"sending",created_at:new Date().toISOString(),updated_at:new Date().toISOString(),user:this.getClient().user,user_id:this.getClient().userID,type:"regular"};this.state.addMessageSorted(s);try{return await this.getClient().post(this._channelURL()+"/message",{message:{...e}})}catch(i){let r=!i.response||i.code==="ERR_NETWORK"||i.isWSFailure||!this.getClient().wsConnection?.isHealthy?"failed_offline":"error";throw this.state.updateMessageStatus(t,r),i}}async retryMessage(e){let t=this.state.messages.find(i=>i.id===e);if(!t)throw new Error(`Message ${e} not found in state`);this.state.updateMessageStatus(e,"sending");let s={id:t.id,text:t.text,attachments:t.attachments,mentioned_users:t.mentioned_users,parent_id:t.parent_id,quoted_message_id:t.quoted_message_id,sticker_url:t.sticker_url};t.show_in_channel!==void 0&&(s.show_in_channel=t.show_in_channel);try{return await this.getClient().post(this._channelURL()+"/message",{message:s})}catch(i){let a=!i.response||i.code==="ERR_NETWORK"||i.isWSFailure||!this.getClient().wsConnection?.isHealthy;throw this.state.updateMessageStatus(e,a?"failed_offline":"error"),i}}async createPoll(e){let t=Ue();return e={...e,id:t},await this.getClient().post(this._channelURL()+"/message",{message:{...e}})}async votePoll(e,t){if(!e)throw Error("Message id is missing");return await this.getClient().post(this.getClient().baseURL+`/messages/${this.type}/${this.id}/${e}/poll/${t}`)}async forwardMessage(e,t){return e.id||(e={...e,id:Ue()}),await this.getClient().post(`${this.getClient().baseURL}/channels/${t.type}/${t.channelID}/message`,{message:{...e}})}async pinMessage(e){return await this.getClient().post(this.getClient().baseURL+`/messages/${this.type}/${this.id}/${e}/pin`)}async unpinMessage(e){return await this.getClient().post(this.getClient().baseURL+`/messages/${this.type}/${this.id}/${e}/unpin`)}async editMessage(e,t){return await this.getClient().post(this.getClient().baseURL+`/messages/${this.type}/${this.id}/${e}`,{message:t})}sendFile(e,t,s,i){return this.getClient().sendFile(`${this._channelURL()}/file`,e,t,s,i)}async uploadAndPrepareAttachments(e,t){let s=[],i=e.map(c=>{let p=Gn(c.name);return p!==c.name?new File([c],p,{type:c.type,lastModified:c.lastModified}):c}),a=await Promise.allSettled(i.map(c=>this.sendFile(c,c.name,c.type))),r=new Map,o=[];for(let c=0;c<i.length;c++)a[c].status==="fulfilled"&&Ns(i[c])&&o.push((async()=>{try{let u=await this.getThumbBlobVideo(e[c]);if(u){let m=new File([u],`thumb_${i[c].name}.jpg`,{type:"image/jpeg"}),f=await this.sendFile(m,m.name,"image/jpeg");r.set(c,f.file)}}catch{}})());await Promise.allSettled(o);let l=[];for(let c=0;c<i.length;c++){let p=a[c];if(p.status==="fulfilled"){let u=p.value.file,m=r.get(c),f=t?.voiceMetadata?.get(c);l.push(qs(i[c],u,m,f))}else s.push({file:e[c],error:p.reason instanceof Error?p.reason:new Error(String(p.reason))})}return{attachments:l,failedFiles:s}}async sendEvent(e){return await this.getClient().post(this._channelURL()+"/event",{event:e})}async sendReaction(e,t){if(!e)throw Error("Message id is missing");return await this.getClient().post(this.getClient().baseURL+`/messages/${this.type}/${this.id}/${e}/reaction/${t}`)}deleteReaction(e,t){if(!t||!e)throw Error("Deleting a reaction requires specifying both the message and reaction type");let s=this.getClient().baseURL+`/messages/${this.type}/${this.id}/${e}/reaction/${t}`;return this.getClient().delete(s,{})}async update(e={},t){return["config","cid","created_by","id","member_count","type","created_at","updated_at","last_message_at","own_capabilities"].forEach(i=>{delete e[i]}),await this._update({message:t,data:e})}async delete(){return await this.getClient().delete(this._channelURL())}async truncate(){return await this.getClient().delete(this._channelURL()+"/truncate")}async blockUser(){return await this.getClient().post(this._channelURL(),{action:"block"})}async unblockUser(){return await this.getClient().post(this._channelURL(),{action:"unblock"})}async acceptInvite(e){let t=this.id,s=this.getClient().userBaseURL+`/token_gate/join_channel/${this.type}`;return this.getClient().post(s,{},{channel_id:t,action:e})}async rejectInvite(){let e=this.getClient().baseURL+`/invites/${this.type}/${this.id}/reject`;return this.getClient().post(e)}async skipInvite(){let e=this.getClient().baseURL+`/invites/${this.type}/${this.id}/skip`;return this.getClient().post(e)}async addMembers(e){return await this._update({add_members:e})}async addModerators(e){return await this._update({promote_members:e})}async banMembers(e){return await this._update({ban_members:e})}async unbanMembers(e){return await this._update({unban_members:e})}async updateCapabilities(e){return await this._update({capabilities:e})}async setSlowMode(e){let t=[0,1e4,3e4,6e4,3e5,9e5,36e5];if(!t.includes(e))throw new Error(`Invalid cooldown value: ${e}. Allowed values are: ${t.join(", ")} (milliseconds).`);return await this.update({member_message_cooldown:e})}async queryAttachmentMessages(){let e=await this.getClient().post(this.getClient().baseURL+`/channels/${this.type}/${this.id}/attachment`,{attachment_types:["image","video","file","voiceRecording","linkPreview"]});return e.attachments&&e.attachments.sort((t,s)=>new Date(s.created_at).getTime()-new Date(t.created_at).getTime()),e}async searchMessage(e,t){let s=await this.getClient().post(this.getClient().baseURL+"/channels/search",{cid:this.cid,search_term:e,offset:t,limit:25});return!s||s?.search_result?.messages.length===0?null:{...s?.search_result,messages:s?.search_result?.messages.map(i=>{let a=W(i.user_id,Object.values(this.getClient().state.users))||i.user;return{...i,user:a}})}}async removeMembers(e){return await this._update({remove_members:e})}async demoteModerators(e){return await this._update({demote_members:e})}async _update(e){let t=await this.getClient().post(this._channelURL(),e);return this.data={...this.data,...t.channel},t}_processTopics(e,t){let s=e.map(a=>(a.channel&&a.channel.members&&(a.channel.members=H(a.channel.members,t)),a.messages&&(a.messages=H(a.messages,t)),a.pinned_messages&&(a.pinned_messages=H(a.pinned_messages,t)),a.read&&(a.read=H(a.read,t)),a)),{channels:i}=this.getClient().hydrateChannels(s,{});this.state.topics=i}async muteNotification(e){return await this.getClient().post(this.getClient().baseURL+`/channels/${this.type}/${this.id}/muted`,{mute:!0,duration:e})}async unMuteNotification(){return await this.getClient().post(this.getClient().baseURL+`/channels/${this.type}/${this.id}/muted`,{mute:!1})}async keystroke(e,t){let s=new Date,i=this.lastTypingEvent&&s.getTime()-this.lastTypingEvent.getTime();this.lastKeyStroke=s,this.isTyping=!0,(i===null||i>2e3)&&(this.lastTypingEvent=new Date,await this.sendEvent({type:"typing.start",parent_id:e,...t||{}}))}async stopTyping(e,t){this.isTyping&&(this.lastTypingEvent=null,this.isTyping=!1,await this.sendEvent({type:"typing.stop",parent_id:e,...t||{}}))}_isTypingIndicatorsEnabled(){return!0}lastMessage(){let e=this.state.latestMessages.length-5;e<0&&(e=0);let t=this.state.latestMessages.length+1,s=this.state.latestMessages.slice(e,t);return s.sort((i,a)=>a.created_at.getTime()-i.created_at.getTime()),s[0]}async markRead(){return await this.getClient().post(this._channelURL()+"/read")}clean(){this.lastKeyStroke&&new Date().getTime()-this.lastKeyStroke.getTime()>1e3&&this.isTyping&&Ps(this.stopTyping(),"stop typing event"),this.state.clean()}async watch(e){await this.getClient().wsPromise;let t={...e},s=await this.query(t,"latest");this.initialized=!0,await Nn(this.getClient(),s.channel.members);let i=Object.values(this.getClient().state.users);if(s.channel.members=H(s.channel.members,i),s.channel.name=s.channel.type==="messaging"?Dt(s.channel.members,this.getClient().userID||""):s.channel.name,s.channel.image=s.channel.type==="messaging"?jn(s.channel.members,this.getClient().userID||""):s.channel.image,s.messages=H(s.messages,i),s.pinned_messages=s.pinned_messages?H(s.pinned_messages,i):[],s.read=H(s.read||[],i),this.type==="team"&&s.channel.topics_enabled){let a={filter_conditions:{type:["topic"],parent_cid:this.cid,project_id:this.getClient().projectId},sort:[],message_limit:25},r=await this.getClient().post(this.getClient().baseURL+"/channels",a);this._processTopics(r.channels||[],i)}return this.data=s.channel,this._client.logger("info",`channel:watch() - started watching channel ${this.cid}`,{tags:["channel"],channel:this}),s}lastRead(){let{userID:e}=this.getClient();if(e)return this.state.read[e]?this.state.read[e].last_read:null}_countMessageAsUnread(e){return!(e.parent_id&&!e.show_in_channel||e.user?.id===this.getClient().userID||e.type==="system"||Array.isArray(this.data?.own_capabilities)&&!this.data?.own_capabilities.includes("read-events"))}countUnread(e){if(!e)return this.state.unreadCount;let t=0;for(let s=0;s<this.state.latestMessages.length;s+=1){let i=this.state.latestMessages[s];i.created_at>e&&this._countMessageAsUnread(i)&&t++}return t}getUnreadMemberCount(){return this.state.read?Object.values(this.state.read):[]}getCapabilitiesMember(){return this.data?this.data.member_capabilities:[]}create=async()=>this.type==="messaging"?await this.createDirectChannel("latest"):await this.query({},"latest");async createTopic(e){let t=this._client.projectId,s=Ue(),i=`${t}:${s}`,a=`${this.getClient().baseURL}/channels/topic/${i}`,r={project_id:t,parent_cid:this.cid,data:{...e}};return await this.getClient().post(a+"/query",r)}async query(e,t="current"){await this.getClient().wsPromise;let s=this._client.projectId,i={...e,project_id:s},a=`${this.getClient().baseURL}/channels/${this.type}`;if(this.id)a+=`/${this.id}`;else if(this.type==="team"||this.type==="meeting"){let u=Ue();this.id=`${s}:${u}`,a+=`/${this.id}`}let r={state:!0,...i};this._data&&Object.keys(this._data).length>0&&(r.data=this._data);let o=await this.getClient().post(a+"/query",r);await Nn(this.getClient(),o.channel.members);let l=Object.values(this.getClient().state.users);if(o.channel.members=H(o.channel.members,l),o.channel.name=o.channel.type==="messaging"?Dt(o.channel.members,this.getClient().userID||""):o.channel.name,o.channel.image=o.channel.type==="messaging"?jn(o.channel.members,this.getClient().userID||""):o.channel.image,o.messages=H(o.messages,l),o.pinned_messages=o.pinned_messages?H(o.pinned_messages,l):[],o.read=H(o.read||[],l),o.channel.is_pinned=o.is_pinned||!1,!this.id){this.id=o.channel.id,this.cid=o.channel.cid;let u=o.channel.members.map(f=>f.user_id||f.user?.id).sort().join(","),m=`${this.type}:!members-${u}`;m in this.getClient().activeChannels&&delete this.getClient().activeChannels[m],this.cid in this.getClient().activeChannels||(this.getClient().activeChannels[this.cid]=this)}let{messageSet:c}=this._initializeState(o,t),p=[...o.channel.own_capabilities||[]].sort().join()!==[...Array.isArray(this.data?.own_capabilities)?this.data?.own_capabilities:[]].sort().join();return this.data=o.channel,this.offlineMode=!1,p&&this.getClient().dispatchEvent({type:"capabilities.changed",cid:this.cid,own_capabilities:o.channel.own_capabilities}),o}async createDirectChannel(e="current"){await this.getClient().wsPromise;let t=this._client.projectId,s=`${this.getClient().baseURL}/channels/${this.type}`,i={project_id:t};this._data&&Object.keys(this._data).length>0&&(i.data=this._data);let a=await this.getClient().post(s+"/query",i),r=Object.values(this.getClient().state.users);a.channel.members=H(a.channel.members,r),a.channel.name=a.channel.type==="messaging"?Dt(a.channel.members,this.getClient().userID||""):a.channel.name,a.messages=H(a.messages,r),a.pinned_messages=a.pinned_messages?H(a.pinned_messages,r):[],a.read=H(a.read||[],r);let{messageSet:o}=this._initializeState(a,e),l=[...a.channel.own_capabilities||[]].sort().join()!==[...Array.isArray(this.data?.own_capabilities)?this.data?.own_capabilities:[]].sort().join();return this.data=a.channel,this.offlineMode=!1,l&&this.getClient().dispatchEvent({type:"capabilities.changed",cid:a.channel.cid,own_capabilities:a.channel.own_capabilities}),a}async queryMessagesLessThanId(e,t=25){await this.getClient().wsPromise;let s=this._client.projectId,i=`${this.getClient().baseURL}/channels/${this.type}/${this.id}`,a=await this.getClient().post(i+"/query",{state:!0,project_id:s,messages:{limit:t,id_lt:e}}),r=Object.values(this.getClient().state.users);if(a.messages=H(a.messages,r),a.messages&&a.messages.length>0){for(let o of a.messages)if(!o.pinned){let l=this.state.pinnedMessages?.find(c=>c.id===o.id);if(l){o.pinned=!0;let c=l.pinned_at||new Date;o.pinned_at=typeof c=="string"?c:c.toISOString()}}this.state.addMessagesSorted(a.messages,!1,!0,!0,"current")}return a.messages}async queryMessagesGreaterThanId(e,t=25){await this.getClient().wsPromise;let s=this._client.projectId,i=`${this.getClient().baseURL}/channels/${this.type}/${this.id}`,a=await this.getClient().post(i+"/query",{state:!0,project_id:s,messages:{limit:t,id_gt:e}}),r=Object.values(this.getClient().state.users);if(a.messages=H(a.messages,r),a.messages&&a.messages.length>0){for(let o of a.messages)if(!o.pinned){let l=this.state.pinnedMessages?.find(c=>c.id===o.id);if(l){o.pinned=!0;let c=l.pinned_at||new Date;o.pinned_at=typeof c=="string"?c:c.toISOString()}}this.state.addMessagesSorted(a.messages,!1,!0,!0,"current")}return a.messages}async queryMessagesAroundId(e,t=25){await this.getClient().wsPromise;let s=this._client.projectId,i=`${this.getClient().baseURL}/channels/${this.type}/${this.id}`,a=await this.getClient().post(i+"/query",{state:!0,project_id:s,messages:{limit:t,id_around:e}}),r=Object.values(this.getClient().state.users);if(a.messages=H(a.messages,r),a.messages&&a.messages.length>0){for(let o of a.messages)if(!o.pinned){let l=this.state.pinnedMessages?.find(c=>c.id===o.id);if(l){o.pinned=!0;let c=l.pinned_at||new Date;o.pinned_at=typeof c=="string"?c:c.toISOString()}}this.state.addMessagesSorted(a.messages,!1,!0,!0,"current")}return a.messages}async deleteMessage(e){return await this.getClient().delete(this.getClient().baseURL+`/messages/${this.type}/${this.id}/${e}`)}async deleteMessageForMe(e){return await this.getClient().delete(this.getClient().baseURL+`/messages/${this.type}/${this.id}/${e}`,{for_me:!0})}async getThumbBlobVideo(e){return new Promise(t=>{let i=document.createElement("video");i.src=URL.createObjectURL(e),i.crossOrigin="anonymous",i.load(),i.addEventListener("error",()=>{console.error("Error when loading video file."),t(null)}),i.addEventListener("loadedmetadata",()=>{if(i.duration<.1){console.error("Video is too short."),t(null);return}setTimeout(()=>{i.currentTime=.1},200)}),i.addEventListener("seeked",()=>{try{let a=document.createElement("canvas");a.width=i.videoWidth,a.height=i.videoHeight;let r=a.getContext("2d");if(!r){console.error("Failed to create canvas context."),t(null);return}r.drawImage(i,0,0,a.width,a.height),r.canvas.toBlob(o=>{if(!o){console.error("Failed to generate thumbnail."),t(null);return}t(o),URL.revokeObjectURL(i.src)},"image/jpeg",.75)}catch(a){console.error("Error while extracting thumbnail:",a),t(null)}})})}async enableTopics(){return await this.getClient().post(this.getClient().baseURL+`/channels/${this.type}/${this.id}/topics/enable`,{project_id:this.getClient().projectId,messages:{limit:25}})}async disableTopics(){return await this.getClient().post(this.getClient().baseURL+`/channels/${this.type}/${this.id}/topics/disable`,{project_id:this.getClient().projectId})}async closeTopic(e){return await this.getClient().post(this.getClient().baseURL+`/channels/${this.type}/${this.id}/topics/close`,{project_id:this.getClient().projectId,topic_cid:e})}async reopenTopic(e){return await this.getClient().post(this.getClient().baseURL+`/channels/${this.type}/${this.id}/topics/reopen`,{project_id:this.getClient().projectId,topic_cid:e})}async editTopic(e,t){let s=await this.getClient().post(this.getClient().baseURL+`/channels/${this.type}/${this.id}/topics`,{project_id:this.getClient().projectId,topic_cid:e,data:t});if(s){let i=this.getClient().activeChannels[e];return i?(i.data=s.channel,i.data):s.channel}}on(e,t){let s=t?e:"all",i=t||e;return s in this.listeners||(this.listeners[s]=[]),this._client.logger("info",`Attaching listener for ${s} event on channel ${this.cid}`,{tags:["event","channel"],channel:this}),this.listeners[s].push(i),{unsubscribe:()=>{this._client.logger("info",`Removing listener for ${s} event from channel ${this.cid}`,{tags:["event","channel"],channel:this}),this.listeners[s]=this.listeners[s].filter(a=>a!==i)}}}off(e,t){let s=t?e:"all",i=t||e;s in this.listeners||(this.listeners[s]=[]),this._client.logger("info",`Removing listener for ${s} event from channel ${this.cid}`,{tags:["event","channel"],channel:this}),this.listeners[s]=this.listeners[s].filter(a=>a!==i)}async _handleChannelEvent(e){let t=this;this._client.logger("info",`channel:_handleChannelEvent - Received event of type { ${e.type} } on ${this.cid}`,{tags:["event","channel"],channel:this});let s=t.state,i=Object.values(this.getClient().state.users);switch(e.type){case"typing.start":if(e.user?.id){let c=W(e.user.id||"",i);e.user=c,s.typing[e.user.id]=e}break;case"typing.stop":e.user?.id&&delete s.typing[e.user.id];break;case"message.read":if(e.user?.id&&e.created_at){let c=W(e.user.id||"",i);e.user=c,s.read[e.user.id]={last_read:new Date(e.created_at),last_read_message_id:e.last_read_message_id,user:c,unread_messages:0},e.user?.id===this.getClient().user?.id&&(s.unreadCount=0)}break;case"user.watching.start":e.user?.id&&(s.watchers[e.user.id]=e.user);break;case"user.watching.stop":e.user?.id&&delete s.watchers[e.user.id];break;case"message.deleted":if(e.message){this._extendEventWithOwnReactions(e);s.removeMessage(e.message),s.addMessageSorted(e.message,!1,!1),s.removeQuotedMessageReferences(e.message),[...s.pinnedMessages].some(c=>c.id===e.message?.id)&&s.removePinnedMessage(e.message);for(let c in s.read)c!==e.user?.id&&e.message.id===s.read[c].last_read_message_id&&(s.read[c]={...s.read[c],last_read_message_id:void 0})}break;case"message.deleted_for_me":e.message&&(s.removeMessage(e.message),s.removeQuotedMessageReferences(e.message),[...s.pinnedMessages].some(c=>c.id===e.message?.id)&&s.removePinnedMessage(e.message));break;case"message.new":if(e.message){let c=e.user?.id===this.getClient().user?.id,p=!!e.message.parent_id;if(!i.find(g=>g.id===e.user?.id)&&e.user?.id){let g=await this.getClient().queryUser(e.user.id);i.push(g)}let m=W(e.user?.id||"",i);if(e.message.user=m,e.message?.quoted_message){let g=W(e.message.quoted_message.user?.id||"",i);e.message.quoted_message.user=g}if(e.user=m,(this.state.isUpToDate||p)&&s.addMessageSorted(e.message,c),c||p)break;if(e.user?.id)for(let g in s.read)g===e.user.id?s.read[e.user.id]={last_read:new Date(e.created_at),user:e.user,unread_messages:0}:s.read[g].unread_messages+=1;this._countMessageAsUnread(e.message)&&(s.unreadCount=s.unreadCount+1)}break;case"message.updated":if(e.message){let c=W(e.user?.id||"",i),p=W(e.message.user?.id||"",i);if(e.user=c,e.message.user=p,e.message?.quoted_message){let u=W(e.message.quoted_message.user?.id||"",i);e.message.quoted_message.user=u}e.message?.latest_reactions&&(e.message.latest_reactions=H(e.message.latest_reactions||[],i)),this._extendEventWithOwnReactions(e),s.addMessageSorted(e.message,!1,!1),e.message.pinned?s.addPinnedMessage(e.message):s.removePinnedMessage(e.message)}break;case"message.pinned":if(e.message){let c=W(e.message.user?.id||"",i);e.message.user=c,s.addPinnedMessage(e.message),s.addMessageSorted(e.message,!1,!1)}break;case"message.unpinned":if(e.message){let c=W(e.message.user?.id||"",i);e.message.user=c,s.removePinnedMessage(e.message),s.addMessageSorted(e.message,!1,!1)}break;case"channel.truncate":if(e.channel?.created_at){let c=+new Date(e.channel.created_at);s.messageSets.forEach((p,u)=>{p.messages.forEach(({created_at:m,id:f})=>{c>+m&&s.removeMessage({id:f,messageSetIndex:u})})}),s.pinnedMessages.forEach(({id:p,created_at:u})=>{c>+u&&s.removePinnedMessage({id:p})})}else s.clearMessages();s.unreadCount=0,e.message&&(s.addMessageSorted(e.message),e.message.pinned&&s.addPinnedMessage(e.message));break;case"member.added":if(e.member?.user_id){let c=W(e.member.user_id,i);e.member.user=c,s.members[e.member.user_id]=e.member,e.member.user?.id===this.getClient().user?.id&&(s.membership=e.member)}break;case"member.updated":if(e.member?.user_id){let c=W(e.member.user_id,i);e.member.user=c,s.members[e.member.user_id]=e.member,s.membership=e.member}break;case"member.removed":e.member?.user_id?delete s.members[e.member.user_id]:e.user?.id&&delete s.members[e.user.id];break;case"channel.updated":e.channel&&(t.data={...t.data,...e.channel,own_capabilities:e.channel?.own_capabilities??t.data?.own_capabilities});break;case"pollchoice.new":if(e.message){let c=W(e.message.user?.id||"",i);e.message.user=c,s.addMessageSorted(e.message,!1,!1)}break;case"reaction.new":if(e.message&&e.reaction){let c=W(e.message.user?.id||"",i),p=W(e.reaction.user?.id||"",i);if(e.message.user=c,e.message.latest_reactions=H(e.message.latest_reactions||[],i),e.reaction.user=p,e.message?.quoted_message){let u=W(e.message.quoted_message.user?.id||"",i);e.message.quoted_message.user=u}e.message=s.addReaction(e.reaction,e.message)}break;case"reaction.deleted":if(e.user=W(e.user?.id||"",i),e.message){if(e.message?.quoted_message){let c=W(e.message.quoted_message.user?.id||"",i);e.message.quoted_message.user=c}e.message.user=W(e.message.user?.id||"",i),e.message.latest_reactions?.map(c=>(c.user=W(c.user?.id||"",i),c))}e.reaction&&(e.reaction.user=W(e.reaction.user?.id||"",i),e.message=s.removeReaction(e.reaction,e.message));break;case"member.joined":case"notification.invite_accepted":if(e.member?.user_id){if(!i.find(u=>u.id===e.member?.user_id)){let u=await this.getClient().queryUser(e.member?.user_id);i.push(u)}let p=W(e.member.user_id,i);e.member.user=p,e.member.user_id===this.getClient().user?.id&&(s.membership=e.member,this.state.membership=e.member),s.members[e.member.user_id]=e.member,t.data={...t.data,member_count:Number(t.data?.member_count)+1,members:t.data?.members?[...t.data.members,e.member]:[e.member]},this.offlineMode=!0,this.initialized=!0}break;case"notification.invite_rejected":e.member?.user_id&&delete s.members[e.member.user_id];break;case"notification.invite_messaging_skipped":if(e.member?.user_id){let c=W(e.member.user_id,i);e.member.user=c,e.member.user_id===this.getClient().user?.id&&(s.membership=e.member,this.state.membership=e.member),s.members[e.member.user_id]=e.member}break;case"member.promoted":case"member.demoted":case"member.banned":case"member.unbanned":case"member.blocked":case"member.unblocked":if(e.member?.user_id){let c=W(e.member.user_id,i);e.member.user=c,s.members[e.member.user_id]=e.member,e.member.user_id===this.getClient().user?.id&&(s.membership=e.member,this.state.membership=e.member)}break;case"channel.pinned":t.data&&(t.data.is_pinned=!0);break;case"channel.unpinned":t.data&&(t.data.is_pinned=!1);break;case"channel.topic.disabled":t.data&&(t.data.topics_enabled=!1),e.user=W(e.user?.id||"",i);break;case"channel.topic.enabled":t.data&&(t.data.topics_enabled=!0),e.user=W(e.user?.id||"",i);break;case"channel.topic.created":let a=e.channel?.members||[],r=H(a,i),o={channel:e.channel,members:r,messages:[],pinned_messages:[]},l=this.getClient().channel(e.channel_type||"",e.channel_id||"");l.data=e.channel,l._initializeState(o,"latest"),s.topics?.unshift(l);break;case"channel.topic.closed":t.data&&(t.data.is_closed_topic=!0),e.user=W(e.user?.id||"",i);break;case"channel.topic.reopen":t.data&&(t.data.is_closed_topic=!1),e.user=W(e.user?.id||"",i);break;case"channel.topic.updated":t.data&&(t.data.name=e.channel?.name,t.data.image=e.channel?.image,t.data.description=e.channel?.description),e.user=W(e.user?.id||"",i);break;default:}e.watcher_count!==void 0&&(t.state.watcher_count=e.watcher_count)}_callChannelListeners=e=>{let t=this,s=[];t.listeners.all&&s.push(...t.listeners.all),t.listeners[e.type]&&s.push(...t.listeners[e.type]);for(let i of s)typeof i!="string"&&i(e)};_channelURL=()=>{if(!this.id)throw new Error("channel id is not defined");return`${this.getClient().baseURL}/channels/${this.type}/${this.id}`};_checkInitialized(){if(!this.initialized&&!this.offlineMode)throw Error(`Channel ${this.cid} hasn't been initialized yet. Make sure to call .watch() and wait for it to resolve`)}_initializeState(e,t="latest",s){let{state:i,user:a,userID:r}=this.getClient();if(e.channel.members)for(let u of e.channel.members)u.user&&(s&&s(u.user.id),i.updateUserReference(u.user,this.cid));this.state.membership=e.membership||{};let o=new Map,l=[];e.messages||(e.messages=[]);for(let u of e.messages)o.has(u.id)||(o.set(u.id,!0),l.push(u));this.state.pinnedMessages&&(this.state.pinnedMessages=[]),this.state.addPinnedMessages(e.pinned_messages||[]);let c=l||[];this.state.messages||this.state.initMessages();let{messageSet:p}=this.state.addMessagesSorted(c,!1,!0,!0,t);if(e.watcher_count!==void 0&&(this.state.watcher_count=e.watcher_count),e.watchers)for(let u of e.watchers)u&&(i.updateUserReference(u,this.cid),this.state.watchers[u.id]=u);if(r!=null){let u=this.state.last_message_at||new Date;a&&(this.state.read[a.id]={user:a,last_read:u,unread_messages:0})}if(e.read)for(let u of e.read)this.state.read[u.user.id]={last_read:new Date(u.last_read),last_read_message_id:u.last_read_message_id,unread_messages:u.unread_messages??0,user:u.user,last_send:u.last_send},u.user.id===a?.id&&(this.state.unreadCount=this.state.read[u.user.id].unread_messages);if(e.channel.members&&(this.state.members=e.channel.members.reduce((u,m)=>(m.user&&(u[m.user.id]=m),u),{})),e.channel.type==="team"&&e.channel.topics_enabled&&e.topics){let u=Object.values(this.getClient().state.users);this._processTopics(e.topics,u)}return{messageSet:p}}_extendEventWithOwnReactions(e){if(!e.message)return;let t=this.state.findMessage(e.message.id,e.message.parent_id);t&&(e.message.own_reactions=t.own_reactions)}_disconnect(){this._client.logger("info",`channel:disconnect() - Disconnecting the channel ${this.cid}`,{tags:["connection","channel"],channel:this}),this.disconnected=!0,this.state.setIsUpToDate(!1)}};var ln=class{users;userChannelReferences;constructor(){this.users={},this.userChannelReferences={}}updateUsers(e){for(let t of e)this.updateUser(t)}updateUser(e){if(e!=null)if(this.users[e.id]){let t={...this.users[e.id],...e};this.users[e.id]=t}else this.users[e.id]=e}updateUserReference(e,t){e!=null&&(this.userChannelReferences[e.id]||(this.userChannelReferences[e.id]={}),this.userChannelReferences[e.id][t]=!0)}deleteAllChannelReference(e){for(let t in this.userChannelReferences)delete this.userChannelReferences[t][e]}};var Gp=Re(qp());var _g=n=>n.code!==void 0,yg=n=>n.error!==void 0,Xn=class{client;connectionOpen;consecutiveFailures;pingInterval;healthCheckTimeoutRef;isConnecting;isDisconnected;isHealthy;isResolved;lastEvent;connectionCheckTimeout;connectionCheckTimeoutRef;rejectPromise;requestID;resolvePromise;totalFailures;ws;wsID;constructor({client:e}){this.client=e,this.consecutiveFailures=0,this.totalFailures=0,this.isConnecting=!1,this.isDisconnected=!1,this.isResolved=!1,this.isHealthy=!1,this.wsID=1,this.lastEvent=null,this.pingInterval=25*1e3,this.connectionCheckTimeout=this.pingInterval+10*1e3,jl(this.onlineStatusChanged)}_log(e,t={},s="info"){this.client.logger(s,"connection:"+e,{tags:["connection"],...t})}setClient(e){this.client=e}async connect(e=15e3){if(this.isConnecting)throw Error("You've called connect twice, can only attempt 1 connection at the time");this.isDisconnected=!1;try{let t=await this._connect();this.consecutiveFailures=0,this._log(`connect() - Established ws connection with healthcheck: ${t}`)}catch(t){if(this.isHealthy=!1,this.consecutiveFailures+=1,t.code===mt.TOKEN_EXPIRED)this._log("connect() - WS failure due to expired token");else if(!t.isWSFailure)throw new Error(JSON.stringify({code:t.code,StatusCode:t.StatusCode,message:t.message,isWSFailure:t.isWSFailure}))}return await this._waitForHealthy(e)}async _waitForHealthy(e=15e3){return Promise.race([(async()=>{for(let s=0;s<=e;s+=50)try{return await this.connectionOpen}catch(i){if(s===e)throw new Error(JSON.stringify({code:i.code,StatusCode:i.StatusCode,message:i.message,isWSFailure:i.isWSFailure}));await on(50)}})(),(async()=>{throw await on(e),this.isConnecting=!1,new Error(JSON.stringify({code:"",StatusCode:"",message:"initial WS connection could not be established",isWSFailure:!0}))})()])}_buildUrl=()=>{let e=encodeURIComponent(this.client._buildWSPayload(this.requestID)),t=this.client.tokenManager.getToken(),s=`${this.client.wsBaseURL}/connect?json=${e}&api_key=${this.client.apiKey}&authorization=${t}&stream-auth-type=${this.client.getAuthType()}&X-Stream-Client=${this.client.getUserAgent()}`;return s=encodeURI(s),s};disconnect(e){this._log(`disconnect() - Closing the websocket connection for wsID ${this.wsID}`),this.wsID+=1,this.isConnecting=!1,this.isDisconnected=!0,this.healthCheckTimeoutRef&&clearInterval(this.healthCheckTimeoutRef),this.connectionCheckTimeoutRef&&clearInterval(this.connectionCheckTimeoutRef),Nl(this.onlineStatusChanged),this.isHealthy=!1,this.ws&&this.ws.removeAllListeners&&this.ws.removeAllListeners();let t,{ws:s}=this;return s&&s.close&&s.readyState===s.OPEN?(t=new Promise(i=>{let a=r=>{this._log(`disconnect() - resolving isClosedPromise ${r?"with":"without"} close frame`,{event:r}),i()};s.onclose=a,setTimeout(a,e??1e3)}),this._log("disconnect() - Manually closed connection by calling client.disconnect()"),s.close(mt.WS_CLOSED_SUCCESS,"Manually closed connection by calling client.disconnect()")):(this._log("disconnect() - ws connection doesn't exist or it is already closed."),t=Promise.resolve()),delete this.ws,t}async _connect(){if(this.isConnecting)return;this.isConnecting=!0,this.requestID=Ue();let e=!1;try{this._log("_connect() - waiting for token"),await this.client.tokenManager.tokenReady(),e=!0}catch{}try{this._setupConnectionPromise();let t=this._buildUrl();this._log(`_connect() - Connecting to ${t}`,{wsURL:t,requestID:this.requestID}),this.ws=new Gp.default(t),this.ws.onopen=this.onopen.bind(this,this.wsID),this.ws.onclose=this.onclose.bind(this,this.wsID),this.ws.onerror=this.onerror.bind(this,this.wsID),this.ws.onmessage=this.onmessage.bind(this,this.wsID);let s=await this.connectionOpen;if(this.isConnecting=!1,s)return s}catch(t){throw this.isConnecting=!1,this._log("_connect() - Error - ",t),t}}async _reconnect(e={}){if(this._log("_reconnect() - Initiating the reconnect"),this.isConnecting||this.isHealthy){this._log("_reconnect() - Abort (1) since already connecting or healthy");return}let t=e.interval;if(t||(t=js(this.consecutiveFailures)),await on(t),this.isConnecting||this.isHealthy){this._log("_reconnect() - Abort (2) since already connecting or healthy");return}if(this.isDisconnected){this._log("_reconnect() - Abort (3) since disconnect() is called");return}this._log("_reconnect() - Destroying current WS connection"),this._destroyCurrentWSConnection();try{await this._connect(),this._log("_reconnect() - Waiting for recoverCallBack"),await this.client.recoverState(),this._log("_reconnect() - Finished recoverCallBack"),this.consecutiveFailures=0}catch(s){this.isHealthy=!1,this.consecutiveFailures+=1,s.isWSFailure&&(this._log("_reconnect() - WS failure, so going to try to reconnect"),this._reconnect())}this._log("_reconnect() - == END ==")}onlineStatusChanged=e=>{e.type==="offline"?(this._log("onlineStatusChanged() - Status changing to offline"),this._setHealth(!1)):e.type==="online"&&(this._log(`onlineStatusChanged() - Status changing to online. isHealthy: ${this.isHealthy}`),this.isHealthy||this._reconnect({interval:10}))};onopen=e=>{this.wsID===e&&this._log("onopen() - onopen callback",{wsID:e})};onmessage=(e,t)=>{if(this.wsID!==e)return;this._log("onmessage() - onmessage callback",{event:t,wsID:e});let s=typeof t.data=="string"?JSON.parse(t.data):null;if(!this.isResolved&&s){if(this.isResolved=!0,s.error){this.rejectPromise?.(this._errorFromWSEvent(s,!1));return}this.resolvePromise?.(s),this._setHealth(!0)}this.lastEvent=new Date,s&&s.type==="health.check"&&this.scheduleNextPing(),this.client.handleEvent(t),this.scheduleConnectionCheck()};onclose=(e,t)=>{if(this.wsID===e)if(this._log("onclose() - onclose callback - "+t.code,{event:t,wsID:e}),t.code===mt.WS_CLOSED_SUCCESS){let s=new Error(`WS connection reject with error ${t.reason}`);s.reason=t.reason,s.code=t.code,s.wasClean=t.wasClean,s.target=t.target,this.rejectPromise?.(s),this._log(`onclose() - WS connection reject with error ${t.reason}`,{event:t})}else this.consecutiveFailures+=1,this.totalFailures+=1,this._setHealth(!1),this.isConnecting=!1,this.rejectPromise?.(this._errorFromWSEvent(t)),this._log("onclose() - WS connection closed. Calling reconnect ...",{event:t}),this._reconnect()};onerror=(e,t)=>{this.wsID===e&&(this.consecutiveFailures+=1,this.totalFailures+=1,this._setHealth(!1),this.isConnecting=!1,this.rejectPromise?.(this._errorFromWSEvent(t)),this._log("onerror() - WS connection resulted into error",{event:t}),this._reconnect())};_setHealth=e=>{if(e!==this.isHealthy){if(this.isHealthy=e,this.isHealthy){this.client.dispatchEvent({type:"connection.changed",online:this.isHealthy});return}setTimeout(()=>{this.isHealthy||this.client.dispatchEvent({type:"connection.changed",online:this.isHealthy})},1e3)}};_errorFromWSEvent=(e,t=!0)=>{let s,i,a;_g(e)&&(s=e.code,i="unknown",a=e.reason),yg(e)&&(s=e.error.code,i=e.error.StatusCode,a=e.error.message),this._log(`_errorFromWSEvent() - WS failed with code ${s}`,{event:e},"warn");let r=new Error(`WS failed with code ${s} and reason - ${a}`);return r.code=s,r.StatusCode=i,r.isWSFailure=t,r};_destroyCurrentWSConnection(){this.wsID+=1;try{this?.ws?.removeAllListeners(),this?.ws?.close()}catch{}}_setupConnectionPromise=()=>{this.isResolved=!1,this.connectionOpen=new Promise((e,t)=>{this.resolvePromise=e,this.rejectPromise=t})};scheduleNextPing=()=>{this.healthCheckTimeoutRef&&clearTimeout(this.healthCheckTimeoutRef),this.healthCheckTimeoutRef=setTimeout(()=>{let e=[{type:"health.check",client_id:this.client.clientID}];try{this.ws?.send(JSON.stringify(e))}catch{}},this.pingInterval)};scheduleConnectionCheck=()=>{this.connectionCheckTimeoutRef&&clearTimeout(this.connectionCheckTimeoutRef),this.connectionCheckTimeoutRef=setTimeout(()=>{let e=new Date;this.lastEvent&&e.getTime()-this.lastEvent.getTime()>this.connectionCheckTimeout&&(this._log("scheduleConnectionCheck - going to reconnect"),this._setHealth(!1),this._reconnect())},this.connectionCheckTimeout)}};var Qn=class{loadTokenPromise;token;user;constructor(){this.loadTokenPromise=null}setTokenOrProvider=async(e,t)=>{this.user=t,typeof e=="string"&&(this.token=e),this.loadTokenPromise=Promise.resolve(this.token)};reset=()=>{this.token=void 0,this.user=void 0,this.loadTokenPromise=null};tokenReady=()=>this.loadTokenPromise;getToken=()=>this.token};function Hs(n){return!n.status||n.status<200||300<=n.status}var Js=Re(Bp());var Mt=class extends Error{code;response;status},Va=(c=>(c.CREATE_CALL="create-call",c.ACCEPT_CALL="accept-call",c.SIGNAL_CALL="signal-call",c.CONNECT_CALL="connect-call",c.HEALTH_CALL="health-call",c.END_CALL="end-call",c.REJECT_CALL="reject-call",c.MISS_CALL="miss-call",c.UPGRADE_CALL="upgrade-call",c))(Va||{}),Ha=(i=>(i.RINGING="ringing",i.ENDED="ended",i.CONNECTED="connected",i.ERROR="error",i))(Ha||{}),Ka=(u=>(u[u.VIDEO_CONFIG=0]="VIDEO_CONFIG",u[u.AUDIO_CONFIG=1]="AUDIO_CONFIG",u[u.VIDEO_KEY=2]="VIDEO_KEY",u[u.VIDEO_DELTA=3]="VIDEO_DELTA",u[u.AUDIO=4]="AUDIO",u[u.ORIENTATION=5]="ORIENTATION",u[u.CONNECTED=6]="CONNECTED",u[u.TRANSCEIVER_STATE=7]="TRANSCEIVER_STATE",u[u.REQUEST_CONFIG=8]="REQUEST_CONFIG",u[u.REQUEST_KEY_FRAME=9]="REQUEST_KEY_FRAME",u[u.END_CALL=10]="END_CALL",u))(Ka||{});function wg(n){return typeof n=="string"||n instanceof String}var Ja=class n{static _instance;activeChannels;axiosInstance;baseURL;userBaseURL;browser;cleaningIntervalRef;clientID;apiKey;projectId;listeners;logger;recoverStateOnReconnect;node;options;setUserPromise;state;tokenManager;user;userAgent;userID;wsBaseURL;wsConnection;wsPromise;consecutiveFailures;defaultWSTimeout;eventSource=null;constructor(e,t,s,i){this.apiKey=e,this.projectId=t,this.listeners={},this.state=new ln;let a=i||{};this.browser=typeof a.browser<"u"?a.browser:typeof window<"u",this.node=!this.browser,this.options={withCredentials:!1,warmUp:!1,recoverStateOnReconnect:!0,...a},this.node&&!this.options.httpsAgent&&(this.options.httpsAgent=new yt.Agent({keepAlive:!0,keepAliveMsecs:3e3})),this.axiosInstance=rn.create(this.options),this.setBaseURL(s),this.wsConnection=null,this.wsPromise=null,this.setUserPromise=null,this.activeChannels={},this.tokenManager=new Qn,this.consecutiveFailures=0,this.defaultWSTimeout=15e3,this.axiosInstance.defaults.paramsSerializer=ql,this.logger=Ms(a.logger)?a.logger:()=>null,this.recoverStateOnReconnect=this.options.recoverStateOnReconnect}static getInstance(e,t,s,i){return n._instance||(n._instance=new n(e,t,s,i)),n._instance}async refreshNewToken(e){return await this.post(this.userBaseURL+"/refresh_token",{refresh_token:e})}getAuthType(){return"jwt"}setBaseURL(e){this.baseURL=e,this.userBaseURL=this.options.userBaseURL||e+"/uss/v1",this.wsBaseURL=this.baseURL.replace("http","ws").replace(":3030",":8800")}async getExternalAuthToken(e,t){let s={apikey:this.apiKey,name:e.name};e.avatar&&(s.avatar=e.avatar);let i=this.userBaseURL+"/get_token/external_auth",a=new URLSearchParams(s).toString(),r={"Content-Type":"application/json"};if(t){let l=typeof t=="string"&&t.startsWith("Bearer ")?t:`Bearer ${t}`;r.Authorization=l}let o=await fetch(`${i}?${a}`,{method:"GET",headers:r});if(!o.ok){let l="";try{let c=await o.json();l=c.message||JSON.stringify(c)}catch{l=await o.text()}throw new Error(l)}return await o.json()}connectUser=async(e,t,s)=>{if(this.logger("info","client:connectUser() - started",{tags:["connection","client"]}),!e.id)throw new Error('The "id" field on the user is missing');if(s){let r=await this.getExternalAuthToken(e,t);t=r.token,e.id=r.user_id}if(this.userID===e.id&&this.setUserPromise)return console.warn("Consecutive calls to connectUser is detected, ideally you should only call this function once in your app."),this.setUserPromise;if(this.userID)throw new Error("Use client.disconnect() before trying to connect as a different user. connectUser was called twice.");this.node&&!this.options.allowServerSideConnect&&console.warn('Please do not use connectUser server side. connectUser impacts MAU and concurrent connection usage and thus your bill. If you have a valid use-case, add "allowServerSideConnect: true" to the client options to disable this warning.'),this.userID=e.id;let i=this._setToken(e,t);this._setUser(e),this.state.updateUser({id:e.id,name:e?.name||e.id,avatar:e?.avatar||""});let a=this.openConnection();this.setUserPromise=Promise.all([i,a]).then(r=>r[1]);try{let r=await this.setUserPromise;return await this.connectToSSE(),r}catch(r){throw this.disconnectUser(),r}};setUser=this.connectUser;_setToken=(e,t)=>this.tokenManager.setTokenOrProvider(t,e);_setUser(e){this.user={...e},this.userID=e.id}closeConnection=async e=>(this.cleaningIntervalRef!=null&&(clearInterval(this.cleaningIntervalRef),this.cleaningIntervalRef=void 0),await this.wsConnection?.disconnect(e),Promise.resolve());openConnection=async()=>{if(!this.userID)throw Error("User is not set on client, use client.connectUser instead");return this.wsConnection?.isConnecting&&this.wsPromise?(this.logger("info","client:openConnection() - connection already in progress",{tags:["connection","client"]}),this.wsPromise):this.wsConnection?.isHealthy?(this.logger("info","client:openConnection() - openConnection called twice, healthy connection already exists",{tags:["connection","client"]}),Promise.resolve()):(this.clientID=`${this.userID}--${Ue()}`,this.wsPromise=this.connect(),this._startCleaning(),this.wsPromise)};_setupConnection=this.openConnection;disconnectUser=async e=>{this.logger("info","client:disconnect() - Disconnecting the client",{tags:["connection","client"]}),delete this.user,delete this.userID;let t=this.closeConnection(e);for(let s of Object.values(this.activeChannels))s._disconnect();return this.activeChannels={},this.state=new ln,setTimeout(this.tokenManager.reset),t};disconnect=this.disconnectUser;on(e,t){let s=t?e:"all",i=t||e;return s in this.listeners||(this.listeners[s]=[]),this.logger("info",`Attaching listener for ${s} event`,{tags:["event","client"]}),this.listeners[s].push(i),{unsubscribe:()=>{this.logger("info",`Removing listener for ${s} event`,{tags:["event","client"]}),this.listeners[s]=this.listeners[s].filter(a=>a!==i)}}}off(e,t){let s=t?e:"all",i=t||e;s in this.listeners||(this.listeners[s]=[]),this.logger("info",`Removing listener for ${s} event`,{tags:["event","client"]}),this.listeners[s]=this.listeners[s].filter(a=>a!==i)}_logApiRequest(e,t,s,i){this.logger("info",`client: ${e} - Request - ${t}- ${JSON.stringify(s)} - ${JSON.stringify(i.params)}`,{tags:["api","api_request","client"],url:t,payload:s,config:i})}_logApiResponse(e,t,s){this.logger("info",`client:${e} - Response - url: ${t} > status ${s.status}`,{tags:["api","api_response","client"],url:t,response:s})}_logApiError(e,t,s,i){this.logger("error",`client:${e} - Error: ${JSON.stringify(s)} - url: ${t} - options: ${JSON.stringify(i)}`,{tags:["api","api_response","client"],url:t,error:s})}doAxiosRequest=async(e,t,s,i={})=>{await this.tokenManager.tokenReady();let a=this._enrichAxiosOptions(i);try{let r;switch(this._logApiRequest(e,t,s,a),e){case"get":r=await this.axiosInstance.get(t,a);break;case"delete":r=await this.axiosInstance.delete(t,a);break;case"post":r=await this.axiosInstance.post(t,s,a);break;case"postForm":r=await this.axiosInstance.postForm(t,s,a);break;case"put":r=await this.axiosInstance.put(t,s,a);break;case"patch":r=await this.axiosInstance.patch(t,s,a);break;case"options":r=await this.axiosInstance.options(t,a);break;default:throw new Error("Invalid request type")}return this._logApiResponse(e,t,r),this.consecutiveFailures=0,this.handleResponse(r)}catch(r){if(r.client_request_id=a.headers?.["x-client-request-id"],this._logApiError(e,t,r,i),this.consecutiveFailures+=1,r.response)return this.handleResponse(r.response);throw r}};get(e,t){return this.doAxiosRequest("get",e,null,{params:t})}put(e,t){return this.doAxiosRequest("put",e,t)}post(e,t,s){return this.doAxiosRequest("post",e,t,{params:s})}patch(e,t){return this.doAxiosRequest("patch",e,t)}delete(e,t){return this.doAxiosRequest("delete",e,null,{params:t})}sendFile(e,t,s,i,a){let r=Ml(t,s,i||"multipart/form-data");return a!=null&&r.append("user",JSON.stringify(a)),this.doAxiosRequest("postForm",e,r,{headers:r.getHeaders?r.getHeaders():{},config:{timeout:0,maxContentLength:1/0,maxBodyLength:1/0}})}errorFromResponse(e){let t;return t=new Mt(`ErmisChat error HTTP code: ${e.status}`),e.data&&e.data.code&&(t=new Error(`ErmisChat error code ${e.data.code}: ${e.data.message}`),t.code=e.data.code),t.response=e,t.status=e.status,t}handleResponse(e){let t=e.data;if(Hs(e))throw this.errorFromResponse(e);return t}dispatchEvent=e=>{if(e.received_at||(e.received_at=new Date),e.type==="channel.created")this._handleChannelCreatedEvent(e).then(()=>{this._afterDispatchEvent(e)});else{let t=this._handleClientEvent(e),s=e.cid,i=s?this.activeChannels[s]:void 0;i&&i._handleChannelEvent(e),this._callClientListeners(e),i&&i._callChannelListeners(e),t.forEach(a=>a())}};_afterDispatchEvent(e){let t=this._handleClientEvent(e),s=e.cid,i=s?this.activeChannels[s]:void 0;i&&i._handleChannelEvent(e),this._callClientListeners(e),i&&i._callChannelListeners(e),t.forEach(a=>a())}async _handleChannelCreatedEvent(e){let t=e.channel?.members||[];await Nn(this,t);let s=Object.values(this.state.users),i=H(t,s),a=e.channel_type==="messaging"?Dt(i,this.userID||""):e.channel?.name,r={...e.channel,members:i,name:a},o={channel:r,members:i,messages:[],pinned_messages:[]},l=this.channel(e.channel_type||"",e.channel_id||"");l.data=r,l._initializeState(o,"latest")}handleEvent=e=>{let t=e.data,s=JSON.parse(t);this.dispatchEvent(s)};_updateMemberWatcherReferences=e=>{let t=this.state.userChannelReferences[e.id]||{};for(let s in t){let i=this.activeChannels[s];i?.state&&(i.state.members[e.id]&&(i.state.members[e.id].user=e),i.state.watchers[e.id]&&(i.state.watchers[e.id]=e),i.state.read[e.id]&&(i.state.read[e.id].user=e))}};_updateUserReferences=this._updateMemberWatcherReferences;_updateUserMessageReferences=e=>{let t=this.state.userChannelReferences[e.id]||{};for(let s in t){let i=this.activeChannels[s];if(!i)continue;i.state?.updateUserMessages(e)}};_deleteUserMessageReference=(e,t=!1)=>{let s=this.state.userChannelReferences[e.id]||{};for(let i in s)this.activeChannels[i].state?.deleteUserMessages(e,t)};_handleClientEvent(e){let t=this,s=[];if(this.logger("info",`client:_handleClientEvent - Received event of type { ${e.type} }`,{tags:["event","client"],event:e}),e.type==="health.check"&&e.me,(e.type==="channel.deleted"||e.type==="notification.channel_deleted")&&e.cid){t.state.deleteAllChannelReference(e.cid),this.activeChannels[e.cid]?._disconnect(),s.push(()=>{e.cid&&delete this.activeChannels[e.cid]});for(let i of Object.values(this.activeChannels))i.type==="team"&&i.state.topics?.some(a=>a.cid===e.cid)&&(i.state.topics=i.state.topics.filter(a=>a.cid!==e.cid))}return e.type==="notification.invite_rejected"&&e.member?.user_id===this.userID&&e.cid&&(t.state.deleteAllChannelReference(e.cid),this.activeChannels[e.cid]?._disconnect(),s.push(()=>{e.cid&&delete this.activeChannels[e.cid]})),e.type,e.type==="member.added"&&e.member?.user_id===this.userID&&this.channel(e.channel_type||"",e.channel_id||"").watch().catch(a=>{this.logger("error","Failed to watch channel after member.added",{err:a,event:e})}),e.type==="connection.recovered"&&s.push(()=>{Object.values(this.activeChannels).forEach(i=>{if(!i.state?.messages)return;i.state.messages.filter(r=>r.status==="failed_offline"&&r.user?.id===this.userID&&(!r.attachments||r.attachments.length===0)).forEach(r=>{r.id&&i.retryMessage(r.id).catch(o=>{this.logger("error",`Failed to auto-resend offline message ${r.id}`,{tags:["offline","retry"],err:o})})})})}),s}_callClientListeners=e=>{let t=this,s=[];t.listeners.all&&s.push(...t.listeners.all),t.listeners[e.type]&&s.push(...t.listeners[e.type]);for(let i of s)i(e)};recoverState=async()=>{this.logger("info","client:recoverState() - Start of recoverState",{tags:["connection"]});let e=Object.keys(this.activeChannels);if(e.length&&this.recoverStateOnReconnect){this.logger("info",`client:recoverState() - Start the querying of ${e.length} channels`,{tags:["connection","client"]});let t={type:["messaging","team"]},s=[],i={message_limit:25};await this.queryChannels(t,s,i),this.logger("info","client:recoverState() - Querying channels finished",{tags:["connection","client"]}),this.dispatchEvent({type:"connection.recovered"})}else this.dispatchEvent({type:"connection.recovered"});this.wsPromise=Promise.resolve(),this.setUserPromise=Promise.resolve()};async connect(){if(!this.userID||!this.user)throw Error("Call connectUser before starting the connection");if(!this.wsBaseURL)throw Error("Websocket base url not set");if(!this.clientID)throw Error("clientID is not set");this.options.wsConnection&&this.node?(this.options.wsConnection.setClient(this),this.wsConnection=this.options.wsConnection):this.wsConnection=new Xn({client:this});try{return await this.wsConnection.connect(this.defaultWSTimeout)}catch(e){throw e}}async connectToSSE(e){if(this.eventSource){this.logger("info","client:connectToSSE() - SSE connection already established",{});return}let t=this._getToken();t?.startsWith("Bearer ")||(t=`Bearer ${t}`);let s={method:"GET",Authorization:t};this.eventSource=new Js.EventSourcePolyfill(this.userBaseURL+"/sse/subscribe",{headers:s,heartbeatTimeout:6e4}),this.eventSource.onopen=()=>{this.logger("info","client:connectToSSE() - SSE connection established",{})},this.eventSource.onmessage=i=>{let a=JSON.parse(i.data);if(this.logger("info",`client:connectToSSE() - SSE message received event : ${JSON.stringify(a)}`,{event:i}),a.type==="AccountUserChainProjects"){let r={name:a.name,id:a.id,avatar:a.avatar,about_me:a.about_me,project_id:a.project_id};this.user?.id===r.id&&(this.user={...this.user,...r}),this.state.updateUser(r);let o={id:r.id,name:r.name?r.name:r.id,avatar:r?.avatar||""};this._updateMemberWatcherReferences(o),this._updateUserMessageReferences(o),Object.values(this.activeChannels).forEach(l=>{if(l.data?.type==="messaging"&&Object.keys(l.state.members).length===2){let c=Object.values(l.state.members).find(p=>p.user?.id!==this.userID);c&&c.user?.id===r.id&&(l.data.name=r.name||r.id,l.data.image=r.avatar||"")}}),e&&e(a)}},this.eventSource.onerror=i=>{this.logger("error",`client:connectToSSE() - SSE connection error : ${JSON.stringify(i.data)} `,{event:i}),i.status===401?(this.logger("error","client:connectToSSE() - Unauthorized (401). Aborting the connection.",{}),this.disconnectFromSSE()):(this.eventSource?.readyState===Js.EventSourcePolyfill.CLOSED||this.eventSource?.readyState===Js.EventSourcePolyfill.CONNECTING)&&(this.eventSource.close(),setTimeout(()=>{this.logger("info","client:connectToSSE() - Reconnecting to SSE",{}),this.connectToSSE(e)},3e3))}}async disconnectFromSSE(){this.eventSource?(this.eventSource.close(),this.eventSource=null,this.logger("info","client:disconnectFromSSE() - SSE connection closed",{})):this.logger("info","client:disconnectFromSSE() - SSE connection already closed",{})}async queryUsers(e,t){let s={presence:!1};await this.wsPromise;let i=this.projectId,a=await this.get(this.userBaseURL+"/users",{project_id:i,page:t,page_size:e});return this.state.updateUsers(a.data),a}async queryUser(e){let t=this.projectId,s=await this.get(this.userBaseURL+"/users/"+e,{project_id:t});return this.state.updateUser(s),s}async getBatchUsers(e,t,s){let i=this.projectId,a=await this.post(this.userBaseURL+"/users/batch?page=1&page_size=10000",{users:e,project_id:i},{page:t,page_size:s});return this.state.updateUsers(a.data),a.data||[]}async searchUsers(e,t,s){let i=this.projectId;return await this.post(this.userBaseURL+"/users/search",void 0,{page:e,page_size:t,name:s,project_id:i})}async queryContacts(){let e=this.projectId,s=(await this.post(this.baseURL+"/contacts/list",{project_id:e})).project_id_user_ids[e],i=[],a=[];return s.forEach(r=>{let o=r.other_id,l=this.state.users[o],c=l||{id:o};switch(r.relation_status){case"blocked":a.push(c);break;case"normal":i.push(c);break;default:}}),{contact_users:i,block_users:a}}_updateProjectID(e){this.projectId=e}async uploadFile(e){let t=new FormData;t.append("avatar",e);let s=await this.post(this.userBaseURL+"/users/upload",t,{headers:{"Content-Type":"multipart/form-data"}});if(this.user){this.user.avatar=s.avatar;let i={...this.user,avatar:s.avatar};this.state.updateUser(i)}return s}async updateProfile(e,t){let s={name:e,about_me:t},i=await this.patch(this.userBaseURL+"/users/update",s);return this.user=i,this.state.updateUser(i),i}async queryChannels(e,t=[],s={},i={}){await this.wsPromise;let a=this.projectId,r={filter_conditions:{...e,project_id:a},sort:t,...s},o=await this.post(this.baseURL+"/channels",r);o.channels.sort((m,f)=>{let g=Ot(m.messages);if(m.channel.type==="team"&&Array.isArray(m.topics))for(let _ of m.topics)g=Math.max(g,Ot(_.messages));let v=Ot(f.messages);if(f.channel.type==="team"&&Array.isArray(f.topics))for(let _ of f.topics)v=Math.max(v,Ot(_.messages));return v-g});let l=Array.from(new Set(o.channels.flatMap(m=>(m.channel.members||[]).map(f=>f.user.id))))||[],c=e.parent_cid?Object.values(this.state.users):await this.getBatchUsers(l);o.channels.forEach(m=>{m.channel.members=H(m.channel.members,c),m.messages=H(m.messages,c),m.read=H(m.read||[],c),m.channel.name=m.channel.type==="messaging"?Dt(m.channel.members,this.userID||""):m.channel.name,m.channel.image=m.channel.type==="messaging"?jn(m.channel.members,this.userID||""):m.channel.image,m.channel.type==="team"&&Array.isArray(m.topics)&&m.topics.sort((f,g)=>{let v=Ot(f.messages);return Ot(g.messages)-v}),m.pinned_messages&&(m.pinned_messages=H(m.pinned_messages||[],c))});let{channels:p,userIds:u}=this.hydrateChannels(o.channels,i);return console.log("---channels---",p),p}hydrateChannels(e=[],t={}){let{skipInitialization:s,offlineMode:i=!1}=t,a=[],r=[];for(let o of e){let l=this.channel(o.channel.type,o.channel.id);l.data={...o.channel,is_pinned:o.is_pinned||!1},l.offlineMode=i,l.initialized=!i,s===void 0?l._initializeState(o,"latest",c=>{r.includes(c)||r.push(c)}):s.includes(o.channel.id)||(l.state.clearMessages(),l._initializeState(o,"latest",c=>{r.includes(c)||r.push(c)})),a.push(l)}return{channels:a,userIds:r}}async searchPublicChannel(e,t=0,s=25){let i=this.projectId;return await this.post(this.baseURL+"/channels/public/search",{project_id:i,search_term:e,limit:s,offset:t})}async pinChannel(e,t){return await this.post(this.baseURL+`/channels/${e}/${t}/pin`)}async unpinChannel(e,t){return await this.post(this.baseURL+`/channels/${e}/${t}/unpin`)}channel(e,t,s){if(!this.userID)throw Error("Call connectUser before creating a channel");if(~e.indexOf(":"))throw Error(`Invalid channel group ${e}, can't contain the : character`);let i,a=s||{};return typeof t=="string"?i=t:typeof t=="object"&&t!==null&&(a=t),this.getChannelById(e,i,a)}getChannelById=(e,t,s)=>{let i=`${e}:${t||""}`;if(i in this.activeChannels&&!this.activeChannels[i].disconnected){let r=this.activeChannels[i];return Object.keys(s).length>0&&(r.data=s,r._data=s),r}let a=new cn(this,e,t,s);return this.activeChannels[a.cid]=a,a};getChannel=(e,t)=>{let s=Ue(),i=`${this.projectId}:${s}`,a=`${e}:${i}`;if(a in this.activeChannels&&!this.activeChannels[a].disconnected){let o=this.activeChannels[a];return Object.keys(t).length>0&&(o.data=t,o._data=t),o}let r=new cn(this,e,i,t);return this.activeChannels[r.cid]=r,r};async createMeetingChannel(e){if(!this.userID)throw Error("Call connectUser before creating a channel");let t={name:e||`Meeting Public - ${new Date().toISOString()}`,members:[this.userID],public:!0},s=this.channel("meeting",t);return await s.create(),s}async joinMeetingChannel(e){if(!this.userID)throw Error("Call connectUser before joining a channel");let t=this.channel("meeting",e);return await t.watch(),t.state.members&&t.state.members[this.userID]||(await t.acceptInvite("join"),await t.watch()),t}_normalizeExpiration(e){let t=null;if(typeof e=="number"){let s=new Date;s.setSeconds(s.getSeconds()+e),t=s.toISOString()}else wg(e)?t=e:e instanceof Date&&(t=e.toISOString());return t}getUserAgent(){return this.userAgent||`ermis-chat-sdk-javascript-client-${this.node?"node":"browser"}-1.0.6`}setUserAgent(e){this.userAgent=e}_enrichAxiosOptions(e={params:{},headers:{},config:{}}){let t=this._getToken();t?.startsWith("Bearer ")||(t=`Bearer ${t}`);let s=t?{Authorization:t}:void 0;e.headers?.["x-client-request-id"]||(e.headers={...e.headers,"x-client-request-id":Ue()});let{params:i,headers:a,...r}=this.options.axiosRequestConfig||{};return{params:{...e.params,...i||{}},headers:{...s,"stream-auth-type":this.getAuthType(),"X-Stream-Client":this.getUserAgent(),...e.headers,...a||{}},...e.config,...r||{}}}_getToken(){return this.tokenManager?this.tokenManager.getToken():null}_startCleaning(){let e=this;this.cleaningIntervalRef==null&&(this.cleaningIntervalRef=setInterval(()=>{for(let t of Object.values(e.activeChannels))t.clean()},500))}_buildWSPayload=e=>JSON.stringify({user_id:this.userID,user_details:this.user,client_request_id:e})};var Cg={"channel.created":!0,"channel.deleted":!0,"channel.truncate":!0,"channel.updated":!0,"channel.pinned":!0,"channel.unpinned":!0,"health.check":!0,"member.added":!0,"member.removed":!0,"member.updated":!0,"member.joined":!0,"member.promoted":!0,"member.demoted":!0,"member.banned":!0,"member.unbanned":!0,"member.blocked":!0,"member.unblocked":!0,"message.deleted":!0,"message.deleted_for_me":!0,"message.new":!0,"message.read":!0,"message.updated":!0,"message.pinned":!0,"message.unpinned":!0,"notification.channel_deleted":!0,"notification.invite_accepted":!0,"notification.invite_rejected":!0,"notification.invite_messaging_skipped":!0,"pollchoice.new":!0,"reaction.deleted":!0,"reaction.new":!0,"typing.start":!0,"typing.stop":!0,"user.watching.start":!0,"user.watching.stop":!0,"connection.changed":!0,"connection.recovered":!0,"capabilities.changed":!0,"channel.topic.disabled":!0,"channel.topic.enabled":!0,"channel.topic.created":!0,"channel.topic.closed":!0,"channel.topic.reopen":!0,"channel.topic.updated":!0};var b,es=null;function dn(){return(es===null||es.byteLength===0)&&(es=new Uint8Array(b.memory.buffer)),es}var Xs=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});Xs.decode();var Eg=2146435072,Xa=0;function Sg(n,e){return Xa+=e,Xa>=Eg&&(Xs=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}),Xs.decode(),Xa=e),Xs.decode(dn().subarray(n,n+e))}function _e(n,e){return n=n>>>0,Sg(n,e)}var lt=new Array(128).fill(void 0);lt.push(void 0,null,!0,!1);var ts=lt.length;function y(n){ts===lt.length&&lt.push(lt.length+1);let e=ts;return ts=lt[e],lt[e]=n,e}function h(n){return lt[n]}var xe=0,ns=new TextEncoder;"encodeInto"in ns||(ns.encodeInto=function(n,e){let t=ns.encode(n);return e.set(t),{read:n.length,written:t.length}});function Ze(n,e,t){if(t===void 0){let o=ns.encode(n),l=e(o.length,1)>>>0;return dn().subarray(l,l+o.length).set(o),xe=o.length,l}let s=n.length,i=e(s,1)>>>0,a=dn(),r=0;for(;r<s;r++){let o=n.charCodeAt(r);if(o>127)break;a[i+r]=o}if(r!==s){r!==0&&(n=n.slice(r)),i=t(i,s,s=r+n.length*3,1)>>>0;let o=dn().subarray(i+r,i+s),l=ns.encodeInto(n,o);r+=l.written,i=t(i,s,r,1)>>>0}return xe=r,i}var jt=null;function U(){return(jt===null||jt.buffer.detached===!0||jt.buffer.detached===void 0&&jt.buffer!==b.memory.buffer)&&(jt=new DataView(b.memory.buffer)),jt}function ie(n){return n==null}function Qa(n){let e=typeof n;if(e=="number"||e=="boolean"||n==null)return`${n}`;if(e=="string")return`"${n}"`;if(e=="symbol"){let i=n.description;return i==null?"Symbol":`Symbol(${i})`}if(e=="function"){let i=n.name;return typeof i=="string"&&i.length>0?`Function(${i})`:"Function"}if(Array.isArray(n)){let i=n.length,a="[";i>0&&(a+=Qa(n[0]));for(let r=1;r<i;r++)a+=", "+Qa(n[r]);return a+="]",a}let t=/\[object ([^\]]+)\]/.exec(toString.call(n)),s;if(t&&t.length>1)s=t[1];else return toString.call(n);if(s=="Object")try{return"Object("+JSON.stringify(n)+")"}catch{return"Object"}return n instanceof Error?`${n.name}: ${n.message}
21
- ${n.stack}`:s}function K(n,e){try{return n.apply(this,e)}catch(t){b.__wbindgen_export3(y(t))}}function Rg(n){n<132||(lt[n]=ts,ts=n)}function J(n){let e=h(n);return Rg(n),e}function un(n,e){return n=n>>>0,dn().subarray(n/1,n/1+e)}var Qs=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>n.dtor(n.a,n.b));function Yn(n,e,t,s){let i={a:n,b:e,cnt:1,dtor:t},a=(...r)=>{i.cnt++;let o=i.a;i.a=0;try{return s(o,i.b,...r)}finally{i.a=o,a._wbg_cb_unref()}};return a._wbg_cb_unref=()=>{--i.cnt===0&&(i.dtor(i.a,i.b),i.a=0,Qs.unregister(i))},Qs.register(a,i,i),a}function Tg(n,e,t,s){let i={a:n,b:e,cnt:1,dtor:t},a=(...r)=>{i.cnt++;try{return s(i.a,i.b,...r)}finally{a._wbg_cb_unref()}};return a._wbg_cb_unref=()=>{--i.cnt===0&&(i.dtor(i.a,i.b),i.a=0,Qs.unregister(i))},Qs.register(a,i,i),a}function Zn(n,e){let t=e(n.length*1,1)>>>0;return dn().set(n,t/1),xe=n.length,t}function kg(n,e){b.__wasm_bindgen_func_elem_12858(n,e)}function Ag(n,e,t){b.__wasm_bindgen_func_elem_11688(n,e,y(t))}function Ig(n,e){b.__wasm_bindgen_func_elem_6230(n,e)}function Dg(n,e,t){b.__wasm_bindgen_func_elem_2287(n,e,y(t))}function Og(n,e,t){b.__wasm_bindgen_func_elem_12912(n,e,y(t))}function Ug(n,e){b.__wasm_bindgen_func_elem_5748(n,e)}function Lg(n,e,t,s){b.__wasm_bindgen_func_elem_14376(n,e,y(t),y(s))}var Fg=["blob","arraybuffer"],Pg=["bytes"],Mg=["default","no-store","reload","no-cache","force-cache","only-if-cached"],jg=["omit","same-origin","include"],Ng=["same-origin","no-cors","cors","navigate"],$p=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>b.__wbg_connectionstats_free(n>>>0,1)),Ys=class{__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,$p.unregister(this),e}free(){let e=this.__destroy_into_raw();b.__wbg_connectionstats_free(e,0)}get rtt_ms(){try{let s=b.__wbindgen_add_to_stack_pointer(-16);b.__wbg_get_connectionstats_rtt_ms(s,this.__wbg_ptr);var e=U().getInt32(s+0,!0),t=U().getFloat64(s+8,!0);return e===0?void 0:t}finally{b.__wbindgen_add_to_stack_pointer(16)}}set rtt_ms(e){b.__wbg_set_connectionstats_rtt_ms(this.__wbg_ptr,!ie(e),ie(e)?0:e)}get packet_loss(){try{let s=b.__wbindgen_add_to_stack_pointer(-16);b.__wbg_get_connectionstats_packet_loss(s,this.__wbg_ptr);var e=U().getInt32(s+0,!0),t=U().getFloat64(s+8,!0);return e===0?void 0:t}finally{b.__wbindgen_add_to_stack_pointer(16)}}set packet_loss(e){b.__wbg_set_connectionstats_packet_loss(this.__wbg_ptr,!ie(e),ie(e)?0:e)}constructor(e,t,s){var i=ie(e)?0:Ze(e,b.__wbindgen_export,b.__wbindgen_export2),a=xe;let r=b.connectionstats_new(i,a,!ie(t),ie(t)?0:t,!ie(s),ie(s)?0:s);return this.__wbg_ptr=r>>>0,$p.register(this,this.__wbg_ptr,this),this}get connection_type(){try{let s=b.__wbindgen_add_to_stack_pointer(-16);b.connectionstats_connection_type(s,this.__wbg_ptr);var e=U().getInt32(s+0,!0),t=U().getInt32(s+4,!0);let i;return e!==0&&(i=_e(e,t).slice(),b.__wbindgen_export4(e,t*1,1)),i}finally{b.__wbindgen_add_to_stack_pointer(16)}}set connection_type(e){var t=ie(e)?0:Ze(e,b.__wbindgen_export,b.__wbindgen_export2),s=xe;b.connectionstats_set_connection_type(this.__wbg_ptr,t,s)}};Symbol.dispose&&(Ys.prototype[Symbol.dispose]=Ys.prototype.free);var zp=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>b.__wbg_ermiscall_free(n>>>0,1)),mn=class{__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,zp.unregister(this),e}free(){let e=this.__destroy_into_raw();b.__wbg_ermiscall_free(e,0)}constructor(){let e=b.ermiscall_new();return this.__wbg_ptr=e>>>0,zp.register(this,this.__wbg_ptr,this),this}spawn(e,t){var s=ie(t)?0:Zn(t,b.__wbindgen_export),i=xe;let a=b.ermiscall_spawn(this.__wbg_ptr,y(e),s,i);return J(a)}getLocalEndpointAddr(){let e=b.ermiscall_getLocalEndpointAddr(this.__wbg_ptr);return J(e)}connect(e){let t=Ze(e,b.__wbindgen_export,b.__wbindgen_export2),s=xe,i=b.ermiscall_connect(this.__wbg_ptr,t,s);return J(i)}closeEndpoint(){let e=b.ermiscall_closeEndpoint(this.__wbg_ptr);return J(e)}closeConnection(){try{let s=b.__wbindgen_add_to_stack_pointer(-16);b.ermiscall_closeConnection(s,this.__wbg_ptr);var e=U().getInt32(s+0,!0),t=U().getInt32(s+4,!0);if(t)throw J(e)}finally{b.__wbindgen_add_to_stack_pointer(16)}}acceptConnection(){let e=b.ermiscall_acceptConnection(this.__wbg_ptr);return J(e)}sendControlFrame(e){try{let i=b.__wbindgen_add_to_stack_pointer(-16),a=Zn(e,b.__wbindgen_export),r=xe;b.ermiscall_sendControlFrame(i,this.__wbg_ptr,a,r);var t=U().getInt32(i+0,!0),s=U().getInt32(i+4,!0);if(s)throw J(t)}finally{b.__wbindgen_add_to_stack_pointer(16)}}sendAudioFrame(e){try{let i=b.__wbindgen_add_to_stack_pointer(-16),a=Zn(e,b.__wbindgen_export),r=xe;b.ermiscall_sendAudioFrame(i,this.__wbg_ptr,a,r);var t=U().getInt32(i+0,!0),s=U().getInt32(i+4,!0);if(s)throw J(t)}finally{b.__wbindgen_add_to_stack_pointer(16)}}sendFrame(e){try{let i=b.__wbindgen_add_to_stack_pointer(-16),a=Zn(e,b.__wbindgen_export),r=xe;b.ermiscall_sendFrame(i,this.__wbg_ptr,a,r);var t=U().getInt32(i+0,!0),s=U().getInt32(i+4,!0);if(s)throw J(t)}finally{b.__wbindgen_add_to_stack_pointer(16)}}notifyNewGop(){try{let s=b.__wbindgen_add_to_stack_pointer(-16);b.ermiscall_notifyNewGop(s,this.__wbg_ptr);var e=U().getInt32(s+0,!0),t=U().getInt32(s+4,!0);if(t)throw J(e)}finally{b.__wbindgen_add_to_stack_pointer(16)}}recv(){try{let i=b.__wbindgen_add_to_stack_pointer(-16);b.ermiscall_recv(i,this.__wbg_ptr);var e=U().getInt32(i+0,!0),t=U().getInt32(i+4,!0),s=U().getInt32(i+8,!0);if(s)throw J(t);return J(e)}finally{b.__wbindgen_add_to_stack_pointer(16)}}asyncRecv(){let e=b.ermiscall_asyncRecv(this.__wbg_ptr);return J(e)}beginWithGop(e){try{let i=b.__wbindgen_add_to_stack_pointer(-16),a=Zn(e,b.__wbindgen_export),r=xe;b.ermiscall_beginWithGop(i,this.__wbg_ptr,a,r);var t=U().getInt32(i+0,!0),s=U().getInt32(i+4,!0);if(s)throw J(t)}finally{b.__wbindgen_add_to_stack_pointer(16)}}connectionType(){try{let s=b.__wbindgen_add_to_stack_pointer(-16);b.ermiscall_connectionType(s,this.__wbg_ptr);var e=U().getInt32(s+0,!0),t=U().getInt32(s+4,!0);let i;return e!==0&&(i=_e(e,t).slice(),b.__wbindgen_export4(e,t*1,1)),i}finally{b.__wbindgen_add_to_stack_pointer(16)}}roundTripTime(){try{let s=b.__wbindgen_add_to_stack_pointer(-16);b.ermiscall_roundTripTime(s,this.__wbg_ptr);var e=U().getInt32(s+0,!0),t=U().getFloat64(s+8,!0);return e===0?void 0:t}finally{b.__wbindgen_add_to_stack_pointer(16)}}currentPacketLoss(){try{let s=b.__wbindgen_add_to_stack_pointer(-16);b.ermiscall_currentPacketLoss(s,this.__wbg_ptr);var e=U().getInt32(s+0,!0),t=U().getFloat64(s+8,!0);return e===0?void 0:t}finally{b.__wbindgen_add_to_stack_pointer(16)}}networkChange(){b.ermiscall_networkChange(this.__wbg_ptr)}getStats(){try{let i=b.__wbindgen_add_to_stack_pointer(-16);b.ermiscall_getStats(i,this.__wbg_ptr);var e=U().getInt32(i+0,!0),t=U().getInt32(i+4,!0),s=U().getInt32(i+8,!0);if(s)throw J(t);return J(e)}finally{b.__wbindgen_add_to_stack_pointer(16)}}};Symbol.dispose&&(mn.prototype[Symbol.dispose]=mn.prototype.free);var qg=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>b.__wbg_intounderlyingbytesource_free(n>>>0,1)),Zs=class{__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,qg.unregister(this),e}free(){let e=this.__destroy_into_raw();b.__wbg_intounderlyingbytesource_free(e,0)}get type(){let e=b.intounderlyingbytesource_type(this.__wbg_ptr);return Pg[e]}get autoAllocateChunkSize(){return b.intounderlyingbytesource_autoAllocateChunkSize(this.__wbg_ptr)>>>0}start(e){b.intounderlyingbytesource_start(this.__wbg_ptr,y(e))}pull(e){let t=b.intounderlyingbytesource_pull(this.__wbg_ptr,y(e));return J(t)}cancel(){let e=this.__destroy_into_raw();b.intounderlyingbytesource_cancel(e)}};Symbol.dispose&&(Zs.prototype[Symbol.dispose]=Zs.prototype.free);var Gg=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>b.__wbg_intounderlyingsink_free(n>>>0,1)),ei=class{__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,Gg.unregister(this),e}free(){let e=this.__destroy_into_raw();b.__wbg_intounderlyingsink_free(e,0)}write(e){let t=b.intounderlyingsink_write(this.__wbg_ptr,y(e));return J(t)}close(){let e=this.__destroy_into_raw(),t=b.intounderlyingsink_close(e);return J(t)}abort(e){let t=this.__destroy_into_raw(),s=b.intounderlyingsink_abort(t,y(e));return J(s)}};Symbol.dispose&&(ei.prototype[Symbol.dispose]=ei.prototype.free);var Bg=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>b.__wbg_intounderlyingsource_free(n>>>0,1)),ti=class{__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,Bg.unregister(this),e}free(){let e=this.__destroy_into_raw();b.__wbg_intounderlyingsource_free(e,0)}pull(e){let t=b.intounderlyingsource_pull(this.__wbg_ptr,y(e));return J(t)}cancel(){let e=this.__destroy_into_raw();b.intounderlyingsource_cancel(e)}};Symbol.dispose&&(ti.prototype[Symbol.dispose]=ti.prototype.free);var $g=new Set(["basic","cors","default"]);async function zg(n,e){if(typeof Response=="function"&&n instanceof Response){if(typeof WebAssembly.instantiateStreaming=="function")try{return await WebAssembly.instantiateStreaming(n,e)}catch(s){if(n.ok&&$g.has(n.type)&&n.headers.get("Content-Type")!=="application/wasm")console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",s);else throw s}let t=await n.arrayBuffer();return await WebAssembly.instantiate(t,e)}else{let t=await WebAssembly.instantiate(n,e);return t instanceof WebAssembly.Instance?{instance:t,module:n}:t}}function Wg(){let n={};return n.wbg={},n.wbg.__wbg_Error_e83987f665cf5504=function(e,t){let s=Error(_e(e,t));return y(s)},n.wbg.__wbg_String_8f0eb39a4a4c2f66=function(e,t){let s=String(h(t)),i=Ze(s,b.__wbindgen_export,b.__wbindgen_export2),a=xe;U().setInt32(e+4,a,!0),U().setInt32(e+0,i,!0)},n.wbg.__wbg___wbindgen_boolean_get_6d5a1ee65bab5f68=function(e){let t=h(e),s=typeof t=="boolean"?t:void 0;return ie(s)?16777215:s?1:0},n.wbg.__wbg___wbindgen_debug_string_df47ffb5e35e6763=function(e,t){let s=Qa(h(t)),i=Ze(s,b.__wbindgen_export,b.__wbindgen_export2),a=xe;U().setInt32(e+4,a,!0),U().setInt32(e+0,i,!0)},n.wbg.__wbg___wbindgen_is_function_ee8a6c5833c90377=function(e){return typeof h(e)=="function"},n.wbg.__wbg___wbindgen_is_object_c818261d21f283a4=function(e){let t=h(e);return typeof t=="object"&&t!==null},n.wbg.__wbg___wbindgen_is_string_fbb76cb2940daafd=function(e){return typeof h(e)=="string"},n.wbg.__wbg___wbindgen_is_undefined_2d472862bd29a478=function(e){return h(e)===void 0},n.wbg.__wbg___wbindgen_jsval_loose_eq_b664b38a2f582147=function(e,t){return h(e)==h(t)},n.wbg.__wbg___wbindgen_number_get_a20bf9b85341449d=function(e,t){let s=h(t),i=typeof s=="number"?s:void 0;U().setFloat64(e+8,ie(i)?0:i,!0),U().setInt32(e+0,!ie(i),!0)},n.wbg.__wbg___wbindgen_string_get_e4f06c90489ad01b=function(e,t){let s=h(t),i=typeof s=="string"?s:void 0;var a=ie(i)?0:Ze(i,b.__wbindgen_export,b.__wbindgen_export2),r=xe;U().setInt32(e+4,r,!0),U().setInt32(e+0,a,!0)},n.wbg.__wbg___wbindgen_throw_b855445ff6a94295=function(e,t){throw new Error(_e(e,t))},n.wbg.__wbg__wbg_cb_unref_2454a539ea5790d9=function(e){h(e)._wbg_cb_unref()},n.wbg.__wbg_abort_28ad55c5825b004d=function(e,t){h(e).abort(h(t))},n.wbg.__wbg_abort_e7eb059f72f9ed0c=function(e){h(e).abort()},n.wbg.__wbg_addEventListener_40dc0fc428fc49e1=function(){return K(function(e,t,s,i){h(e).addEventListener(_e(t,s),h(i))},arguments)},n.wbg.__wbg_append_b577eb3a177bc0fa=function(){return K(function(e,t,s,i,a){h(e).append(_e(t,s),_e(i,a))},arguments)},n.wbg.__wbg_body_587542b2fd8e06c0=function(e){let t=h(e).body;return ie(t)?0:y(t)},n.wbg.__wbg_buffer_ccc4520b36d3ccf4=function(e){let t=h(e).buffer;return y(t)},n.wbg.__wbg_byobRequest_2344e6975f27456e=function(e){let t=h(e).byobRequest;return ie(t)?0:y(t)},n.wbg.__wbg_byteLength_bcd42e4025299788=function(e){return h(e).byteLength},n.wbg.__wbg_byteOffset_ca3a6cf7944b364b=function(e){return h(e).byteOffset},n.wbg.__wbg_call_525440f72fbfc0ea=function(){return K(function(e,t,s){let i=h(e).call(h(t),h(s));return y(i)},arguments)},n.wbg.__wbg_call_e762c39fa8ea36bf=function(){return K(function(e,t){let s=h(e).call(h(t));return y(s)},arguments)},n.wbg.__wbg_cancel_48ab6f9dc366e369=function(e){let t=h(e).cancel();return y(t)},n.wbg.__wbg_catch_943836faa5d29bfb=function(e,t){let s=h(e).catch(h(t));return y(s)},n.wbg.__wbg_clearTimeout_15dfc3d1dcb635c6=function(){return K(function(e,t){h(e).clearTimeout(J(t))},arguments)},n.wbg.__wbg_clearTimeout_7a42b49784aea641=function(e){let t=clearTimeout(J(e));return y(t)},n.wbg.__wbg_close_5a6caed3231b68cd=function(){return K(function(e){h(e).close()},arguments)},n.wbg.__wbg_close_6956df845478561a=function(){return K(function(e){h(e).close()},arguments)},n.wbg.__wbg_close_885e277edf06b3fa=function(){return K(function(e){h(e).close()},arguments)},n.wbg.__wbg_code_20d453b11b200026=function(e){return h(e).code},n.wbg.__wbg_code_218f5fdf8c7fcabd=function(e){return h(e).code},n.wbg.__wbg_crypto_574e78ad8b13b65f=function(e){let t=h(e).crypto;return y(t)},n.wbg.__wbg_data_ee4306d069f24f2d=function(e){let t=h(e).data;return y(t)},n.wbg.__wbg_done_2042aa2670fb1db1=function(e){return h(e).done},n.wbg.__wbg_enqueue_7b18a650aec77898=function(){return K(function(e,t){h(e).enqueue(h(t))},arguments)},n.wbg.__wbg_fetch_74a3e84ebd2c9a0e=function(e){let t=fetch(h(e));return y(t)},n.wbg.__wbg_fetch_f8ba0e29a9d6de0d=function(e,t){let s=h(e).fetch(h(t));return y(s)},n.wbg.__wbg_getRandomValues_1c61fac11405ffdc=function(){return K(function(e,t){globalThis.crypto.getRandomValues(un(e,t))},arguments)},n.wbg.__wbg_getRandomValues_b8f5dbd5f3995a9e=function(){return K(function(e,t){h(e).getRandomValues(h(t))},arguments)},n.wbg.__wbg_getReader_48e00749fe3f6089=function(){return K(function(e){let t=h(e).getReader();return y(t)},arguments)},n.wbg.__wbg_getTime_14776bfb48a1bff9=function(e){return h(e).getTime()},n.wbg.__wbg_get_7bed016f185add81=function(e,t){let s=h(e)[t>>>0];return y(s)},n.wbg.__wbg_get_done_a0463af43a1fc764=function(e){let t=h(e).done;return ie(t)?16777215:t?1:0},n.wbg.__wbg_get_efcb449f58ec27c2=function(){return K(function(e,t){let s=Reflect.get(h(e),h(t));return y(s)},arguments)},n.wbg.__wbg_get_value_5ce96c9f81ce7398=function(e){let t=h(e).value;return y(t)},n.wbg.__wbg_has_787fafc980c3ccdb=function(){return K(function(e,t){return Reflect.has(h(e),h(t))},arguments)},n.wbg.__wbg_headers_b87d7eaba61c3278=function(e){let t=h(e).headers;return y(t)},n.wbg.__wbg_instanceof_ArrayBuffer_70beb1189ca63b38=function(e){let t;try{t=h(e)instanceof ArrayBuffer}catch{t=!1}return t},n.wbg.__wbg_instanceof_Blob_23b3322f66e5a83b=function(e){let t;try{t=h(e)instanceof Blob}catch{t=!1}return t},n.wbg.__wbg_instanceof_Response_f4f3e87e07f3135c=function(e){let t;try{t=h(e)instanceof Response}catch{t=!1}return t},n.wbg.__wbg_instanceof_Uint8Array_20c8e73002f7af98=function(e){let t;try{t=h(e)instanceof Uint8Array}catch{t=!1}return t},n.wbg.__wbg_isArray_96e0af9891d0945d=function(e){return Array.isArray(h(e))},n.wbg.__wbg_iterator_e5822695327a3c39=function(){return y(Symbol.iterator)},n.wbg.__wbg_length_69bca3cb64fc8748=function(e){return h(e).length},n.wbg.__wbg_length_cdd215e10d9dd507=function(e){return h(e).length},n.wbg.__wbg_log_ee0138cca4957740=function(e,t){console.log(_e(e,t))},n.wbg.__wbg_message_bd42dbe3f2f3ed8e=function(e,t){let s=h(t).message,i=Ze(s,b.__wbindgen_export,b.__wbindgen_export2),a=xe;U().setInt32(e+4,a,!0),U().setInt32(e+0,i,!0)},n.wbg.__wbg_msCrypto_a61aeb35a24c1329=function(e){let t=h(e).msCrypto;return y(t)},n.wbg.__wbg_new_0_f9740686d739025c=function(){return y(new Date)},n.wbg.__wbg_new_1acc0b6eea89d040=function(){let e=new Object;return y(e)},n.wbg.__wbg_new_2531773dac38ebb3=function(){return K(function(){let e=new AbortController;return y(e)},arguments)},n.wbg.__wbg_new_3c3d849046688a66=function(e,t){try{var s={a:e,b:t},i=(r,o)=>{let l=s.a;s.a=0;try{return Lg(l,s.b,r,o)}finally{s.a=l}};let a=new Promise(i);return y(a)}finally{s.a=s.b=0}},n.wbg.__wbg_new_5a79be3ab53b8aa5=function(e){let t=new Uint8Array(h(e));return y(t)},n.wbg.__wbg_new_881c4fe631eee9ad=function(){return K(function(e,t){let s=new WebSocket(_e(e,t));return y(s)},arguments)},n.wbg.__wbg_new_9edf9838a2def39c=function(){return K(function(){let e=new Headers;return y(e)},arguments)},n.wbg.__wbg_new_a7442b4b19c1a356=function(e,t){let s=new Error(_e(e,t));return y(s)},n.wbg.__wbg_new_e17d9f43105b08be=function(){let e=new Array;return y(e)},n.wbg.__wbg_new_from_slice_92f4d78ca282a2d2=function(e,t){let s=new Uint8Array(un(e,t));return y(s)},n.wbg.__wbg_new_no_args_ee98eee5275000a4=function(e,t){let s=new Function(_e(e,t));return y(s)},n.wbg.__wbg_new_with_byte_offset_and_length_46e3e6a5e9f9e89b=function(e,t,s){let i=new Uint8Array(h(e),t>>>0,s>>>0);return y(i)},n.wbg.__wbg_new_with_length_01aa0dc35aa13543=function(e){let t=new Uint8Array(e>>>0);return y(t)},n.wbg.__wbg_new_with_str_and_init_0ae7728b6ec367b1=function(){return K(function(e,t,s){let i=new Request(_e(e,t),h(s));return y(i)},arguments)},n.wbg.__wbg_new_with_str_sequence_57a88eb77393f23f=function(){return K(function(e,t,s){let i=new WebSocket(_e(e,t),h(s));return y(i)},arguments)},n.wbg.__wbg_next_020810e0ae8ebcb0=function(){return K(function(e){let t=h(e).next();return y(t)},arguments)},n.wbg.__wbg_next_2c826fe5dfec6b6a=function(e){let t=h(e).next;return y(t)},n.wbg.__wbg_node_905d3e251edff8a2=function(e){let t=h(e).node;return y(t)},n.wbg.__wbg_now_2c95c9de01293173=function(e){return h(e).now()},n.wbg.__wbg_now_793306c526e2e3b6=function(){return Date.now()},n.wbg.__wbg_performance_7a3ffd0b17f663ad=function(e){let t=h(e).performance;return y(t)},n.wbg.__wbg_process_dc0fbacc7c1c06f7=function(e){let t=h(e).process;return y(t)},n.wbg.__wbg_prototypesetcall_2a6620b6922694b2=function(e,t,s){Uint8Array.prototype.set.call(un(e,t),h(s))},n.wbg.__wbg_push_df81a39d04db858c=function(e,t){return h(e).push(h(t))},n.wbg.__wbg_queueMicrotask_34d692c25c47d05b=function(e){let t=h(e).queueMicrotask;return y(t)},n.wbg.__wbg_queueMicrotask_9d76cacb20c84d58=function(e){queueMicrotask(h(e))},n.wbg.__wbg_randomFillSync_ac0988aba3254290=function(){return K(function(e,t){h(e).randomFillSync(J(t))},arguments)},n.wbg.__wbg_read_48f1593df542f968=function(e){let t=h(e).read();return y(t)},n.wbg.__wbg_readyState_97984f126080aeda=function(e){return h(e).readyState},n.wbg.__wbg_reason_1cced37e3a93763e=function(e,t){let s=h(t).reason,i=Ze(s,b.__wbindgen_export,b.__wbindgen_export2),a=xe;U().setInt32(e+4,a,!0),U().setInt32(e+0,i,!0)},n.wbg.__wbg_releaseLock_5d0b5a68887b891d=function(e){h(e).releaseLock()},n.wbg.__wbg_removeEventListener_924d9db66a4f775d=function(){return K(function(e,t,s,i){h(e).removeEventListener(_e(t,s),h(i))},arguments)},n.wbg.__wbg_require_60cc747a6bc5215a=function(){return K(function(){let e=module.require;return y(e)},arguments)},n.wbg.__wbg_resolve_caf97c30b83f7053=function(e){let t=Promise.resolve(h(e));return y(t)},n.wbg.__wbg_respond_0f4dbf5386f5c73e=function(){return K(function(e,t){h(e).respond(t>>>0)},arguments)},n.wbg.__wbg_send_171576d2f7487517=function(){return K(function(e,t,s){h(e).send(_e(t,s))},arguments)},n.wbg.__wbg_send_3d2cf376613294f0=function(){return K(function(e,t,s){h(e).send(un(t,s))},arguments)},n.wbg.__wbg_setTimeout_4eb823e8b72fbe79=function(){return K(function(e,t,s){let i=h(e).setTimeout(J(t),s);return y(i)},arguments)},n.wbg.__wbg_setTimeout_7bb3429662ab1e70=function(e,t){let s=setTimeout(h(e),t);return y(s)},n.wbg.__wbg_set_3f1d0b984ed272ed=function(e,t,s){h(e)[J(t)]=J(s)},n.wbg.__wbg_set_9e6516df7b7d0f19=function(e,t,s){h(e).set(un(t,s))},n.wbg.__wbg_set_binaryType_9d839cea8fcdc5c3=function(e,t){h(e).binaryType=Fg[t]},n.wbg.__wbg_set_body_3c365989753d61f4=function(e,t){h(e).body=h(t)},n.wbg.__wbg_set_cache_2f9deb19b92b81e3=function(e,t){h(e).cache=Mg[t]},n.wbg.__wbg_set_credentials_f621cd2d85c0c228=function(e,t){h(e).credentials=jg[t]},n.wbg.__wbg_set_handle_event_b2de49ad6c81e3c8=function(e,t){h(e).handleEvent=h(t)},n.wbg.__wbg_set_headers_6926da238cd32ee4=function(e,t){h(e).headers=h(t)},n.wbg.__wbg_set_method_c02d8cbbe204ac2d=function(e,t,s){h(e).method=_e(t,s)},n.wbg.__wbg_set_mode_52ef73cfa79639cb=function(e,t){h(e).mode=Ng[t]},n.wbg.__wbg_set_onclose_c09e4f7422de8dae=function(e,t){h(e).onclose=h(t)},n.wbg.__wbg_set_onerror_337a3a2db9517378=function(e,t){h(e).onerror=h(t)},n.wbg.__wbg_set_onmessage_8661558551a89792=function(e,t){h(e).onmessage=h(t)},n.wbg.__wbg_set_onopen_efccb9305427b907=function(e,t){h(e).onopen=h(t)},n.wbg.__wbg_set_signal_dda2cf7ccb6bee0f=function(e,t){h(e).signal=h(t)},n.wbg.__wbg_signal_4db5aa055bf9eb9a=function(e){let t=h(e).signal;return y(t)},n.wbg.__wbg_static_accessor_GLOBAL_89e1d9ac6a1b250e=function(){let e=typeof global>"u"?null:global;return ie(e)?0:y(e)},n.wbg.__wbg_static_accessor_GLOBAL_THIS_8b530f326a9e48ac=function(){let e=typeof globalThis>"u"?null:globalThis;return ie(e)?0:y(e)},n.wbg.__wbg_static_accessor_SELF_6fdf4b64710cc91b=function(){let e=typeof self>"u"?null:self;return ie(e)?0:y(e)},n.wbg.__wbg_static_accessor_WINDOW_b45bfc5a37f6cfa2=function(){let e=typeof window>"u"?null:window;return ie(e)?0:y(e)},n.wbg.__wbg_status_de7eed5a7a5bfd5d=function(e){return h(e).status},n.wbg.__wbg_stringify_b5fb28f6465d9c3e=function(){return K(function(e){let t=JSON.stringify(h(e));return y(t)},arguments)},n.wbg.__wbg_subarray_480600f3d6a9f26c=function(e,t,s){let i=h(e).subarray(t>>>0,s>>>0);return y(i)},n.wbg.__wbg_then_4f46f6544e6b4a28=function(e,t){let s=h(e).then(h(t));return y(s)},n.wbg.__wbg_then_70d05cf780a18d77=function(e,t,s){let i=h(e).then(h(t),h(s));return y(i)},n.wbg.__wbg_url_9bd0af1cd8643de7=function(e,t){let s=h(t).url,i=Ze(s,b.__wbindgen_export,b.__wbindgen_export2),a=xe;U().setInt32(e+4,a,!0),U().setInt32(e+0,i,!0)},n.wbg.__wbg_url_b36d2a5008eb056f=function(e,t){let s=h(t).url,i=Ze(s,b.__wbindgen_export,b.__wbindgen_export2),a=xe;U().setInt32(e+4,a,!0),U().setInt32(e+0,i,!0)},n.wbg.__wbg_value_692627309814bb8c=function(e){let t=h(e).value;return y(t)},n.wbg.__wbg_versions_c01dfd4722a88165=function(e){let t=h(e).versions;return y(t)},n.wbg.__wbg_view_f6c15ac9fed63bbd=function(e){let t=h(e).view;return ie(t)?0:y(t)},n.wbg.__wbg_wasClean_3d7c0cf05bd0a123=function(e){return h(e).wasClean},n.wbg.__wbindgen_cast_0b4723bb5ff7475b=function(e,t){let s=Yn(e,t,b.__wasm_bindgen_func_elem_11664,Ag);return y(s)},n.wbg.__wbindgen_cast_2241b6af4c4b2941=function(e,t){let s=_e(e,t);return y(s)},n.wbg.__wbindgen_cast_253c73f2760a05aa=function(e,t){let s=Yn(e,t,b.__wasm_bindgen_func_elem_6219,Ig);return y(s)},n.wbg.__wbindgen_cast_343835dd8f264af2=function(e,t){let s=Tg(e,t,b.__wasm_bindgen_func_elem_5735,Ug);return y(s)},n.wbg.__wbindgen_cast_7bacc9fa7d2c65f4=function(e,t){let s=Yn(e,t,b.__wasm_bindgen_func_elem_12841,kg);return y(s)},n.wbg.__wbindgen_cast_88fdcfb6b716b7f8=function(e,t){let s=Yn(e,t,b.__wasm_bindgen_func_elem_12896,Og);return y(s)},n.wbg.__wbindgen_cast_c43a1cf1b94f2e7c=function(e,t){let s=Yn(e,t,b.__wasm_bindgen_func_elem_2083,Dg);return y(s)},n.wbg.__wbindgen_cast_cb9088102bce6b30=function(e,t){let s=un(e,t);return y(s)},n.wbg.__wbindgen_cast_d6cd19b81560fd6e=function(e){return y(e)},n.wbg.__wbindgen_object_clone_ref=function(e){let t=h(e);return y(t)},n.wbg.__wbindgen_object_drop_ref=function(e){J(e)},n}function Vg(n,e){return b=n.exports,Wp.__wbindgen_wasm_module=e,jt=null,es=null,b}async function Wp(n){if(b!==void 0)return b;typeof n<"u"&&(Object.getPrototypeOf(n)===Object.prototype?{module_or_path:n}=n:console.warn("using deprecated parameters for the initialization function; pass a single object instead")),typeof n>"u"&&(n="/ermis_call_node_wasm_bg.wasm");let e=Wg();(typeof n=="string"||typeof Request=="function"&&n instanceof Request||typeof URL=="function"&&n instanceof URL)&&(n=fetch(n));let{instance:t,module:s}=await zg(await n,e);return Vg(t,s)}var Vp=Wp;var ni=class{videoEncoder=null;audioEncoder=null;videoReader=null;localStream=null;videoConfig=null;audioConfig=null;videoConfigSent=!1;audioConfigSent=!1;hasVideo=!1;hasAudio=!1;forceKeyFrame=!1;nodeCall;constructor(e){this.nodeCall=e}async connect(e){try{await this.nodeCall.connect(e),await this.sendConnected(),await this.sendConfigs()}catch(t){console.error("Error starting MediaStreamSender:",t)}}async sendConfigs(){try{await this.sendTransceiverState(this.hasAudio,this.hasVideo),await this.sendAudioConfig(),this.localStream?.getVideoTracks()[0]&&await this.sendVideoConfig()}catch(e){console.error("Error sending configs:",e)}}stop=()=>{if(this.videoReader){try{this.videoReader.cancel("Stream stopped").catch(()=>{})}catch{}this.videoReader=null}if(this.videoEncoder){try{this.videoEncoder.state!=="closed"&&(this.videoEncoder.reset(),this.videoEncoder.close())}catch{}this.videoEncoder=null}if(this.audioEncoder){try{this.audioEncoder.state!=="closed"&&(this.audioEncoder.reset(),this.audioEncoder.close())}catch{}this.audioEncoder=null}this.videoConfig=null,this.audioConfig=null,this.videoConfigSent=!1,this.audioConfigSent=!1,this.hasVideo=!1,this.hasAudio=!1,this.localStream&&(this.localStream.getTracks().forEach(e=>e.stop()),this.localStream=null)};initAudioEncoder=e=>{this.localStream=new MediaStream([e]),this.audioConfigSent=!1,this.hasAudio=!!e;let t=new AudioEncoder({output:(s,i)=>{if(i?.decoderConfig&&!this.audioConfigSent){let a;i.decoderConfig.description&&(a=ba(i.decoderConfig.description)),this.audioConfig={codec:i.decoderConfig.codec??"opus",sampleRate:i.decoderConfig.sampleRate??48e3,numberOfChannels:i.decoderConfig.numberOfChannels??1,...a&&{description:a}}}if(s&&this.isReadyToSendData("audio")){let a=new ArrayBuffer(s.byteLength);s.copyTo(a);let r=s.timestamp,o=Ut(a,r,"audio",null);this.sendPacketOrQueue(o,"audio",null)}},error:s=>console.error("AudioEncoder error:",s)});t.configure({codec:"mp4a.40.2",sampleRate:48e3,numberOfChannels:1,bitrate:128e3}),this.audioEncoder=t,this.processAudioFrames(e)};initVideoEncoder(e){this.localStream&&this.localStream.addTrack(e),this.videoConfigSent=!1,this.hasVideo=!!e;let t=e.getSettings(),s=t.width||1280,i=t.height||720,a=new VideoEncoder({output:async(r,o)=>{if(o?.decoderConfig&&!this.videoConfigSent){let l;o.decoderConfig.description&&(l=ba(o.decoderConfig.description)),this.videoConfig={codec:o.decoderConfig.codec??"hev1.1.6.L93.B0",codedWidth:o.decoderConfig.codedWidth??s,codedHeight:o.decoderConfig.codedHeight??i,frameRate:30,orientation:0,...l&&{description:l}},await this.sendVideoConfig()}if(r&&this.isReadyToSendData("video")){let l=new ArrayBuffer(r.byteLength);r.copyTo(l);let c=r.type==="key"?"video-key":"video-delta",p=r.timestamp,u=Ut(l,p,c,null);this.sendPacketOrQueue(u,"video",c)}},error:r=>console.error("VideoEncoder error:",r)});a.configure({codec:"hev1.1.6.L93.B0",width:s,height:i,bitrate:5e5,framerate:30,latencyMode:"realtime",hardwareAcceleration:"prefer-hardware"}),this.videoEncoder=a,this.processVideoFrames(e)}initEncoders=e=>{let t=e.getVideoTracks()[0],s=e.getAudioTracks()[0];s&&this.initAudioEncoder(s),t&&this.initVideoEncoder(t)};sendTransceiverState=async(e,t)=>{let i=Ut(null,null,"transciverState",{audio_enable:!!e,video_enable:!!t});await this.nodeCall.sendControlFrame(i)};async replaceVideoTrack(e){if(this.videoReader){try{await this.videoReader.cancel("Replacing track")}catch{}this.videoReader=null}e&&this.processVideoFrames(e)}async replaceAudioTrack(e){e&&this.processAudioFrames(e)}requestKeyFrame=()=>{console.log("\u{1F4E5} KeyFrame requested"),this.forceKeyFrame=!0};processVideoFrames=async e=>{try{let t=new MediaStreamTrackProcessor({track:e});this.videoReader=t.readable.getReader();let s=0;for(;this.videoReader;){let{done:i,value:a}=await this.videoReader.read();if(i)break;if(!this.videoEncoder){a?.close();break}if(a){s+=1;let r=s%60===0||this.forceKeyFrame;this.forceKeyFrame&&(console.log("\u{1F4E4} Sending forced KeyFrame"),this.forceKeyFrame=!1);try{this.videoEncoder.encode(a,{keyFrame:r})}catch(o){console.error("Encode error:",o)}finally{a.close()}}}}catch(t){console.error(`Error processing video frames: ${t.message}`)}finally{if(this.videoReader)try{this.videoReader.releaseLock()}catch{}}};processAudioFrames=async e=>{let s=new MediaStreamTrackProcessor({track:e}).readable.getReader();try{for(;;){let{done:i,value:a}=await s.read();if(i)break;if(!this.audioEncoder){a?.close();break}if(a)try{this.audioEncoder.encode(a)}catch(r){console.error("Audio Encoding error:",r)}finally{a.close()}}}catch(i){console.error(`Error processing audio frames: ${i.message}`)}};isReadyToSendData=e=>{let t=!this.hasVideo||this.videoConfigSent,s=!this.hasAudio||this.audioConfigSent,i=t&&s;return e==="video"?i&&this.videoConfigSent:e==="audio"?i&&this.audioConfigSent:!1};sendVideoConfig=async()=>{if(this.videoConfig&&!this.videoConfigSent)try{let e=Ut(null,null,"videoConfig",this.videoConfig);await this.nodeCall.sendControlFrame(e),this.videoConfigSent=!0}catch(e){console.error("Error sending video config:",e)}};sendAudioConfig=async()=>{if(this.audioConfig&&!this.audioConfigSent)try{let e=Ut(null,null,"audioConfig",this.audioConfig);await this.nodeCall.sendControlFrame(e),this.audioConfigSent=!0}catch(e){console.error("Error sending audio config:",e)}};sendConnected=async()=>{let e=Ut(null,null,"connected",null);await this.nodeCall.sendControlFrame(e)};sendPacketOrQueue=async(e,t,s)=>{this.isReadyToSendData(t)&&(t==="audio"?await this.nodeCall.sendAudioFrame(e):t==="video"&&(s==="video-key"?await this.nodeCall.beginWithGop(e):s==="video-delta"&&await this.nodeCall.sendFrame(e)))}};var fn={VPS_NUT:32,SPS_NUT:33,PPS_NUT:34,PREFIX_SEI_NUT:39,SUFFIX_SEI_NUT:40,fromValue(n){return{32:"VPS_NUT",33:"SPS_NUT",34:"PPS_NUT",39:"PREFIX_SEI_NUT",40:"SUFFIX_SEI_NUT"}[n]||n}},si=class n{generalProfileSpace=0;generalTierFlag=!1;generalProfileIdc=0;generalProfileCompatibilityFlags=0;generalConstraintIndicatorFlags=0;generalLevelIdc=0;minSpatialSegmentationIdc=0;parallelismType=0;chromaFormatIdc=0;bitDepthLumaMinus8=0;bitDepthChromaMinus8=0;avgFrameRate=0;constantFrameRate=0;numTemporalLayers=0;temporalIdNested=!1;lengthSizeMinusOne=0;arrays=[];constructor(e){Object.assign(this,e)}static demux(e){let t=e instanceof Uint8Array?e:new Uint8Array(e),s=new DataView(t.buffer,t.byteOffset,t.byteLength),i=0,a=0,r=z=>{let pe=0;for(let T=0;T<z;T++){if(i>=t.length)throw new Error("End of buffer");let A=t[i]>>7-a&1;pe=pe<<1|A,a++,a===8&&(a=0,i++)}return pe},o=()=>{if(a!==0)return r(8);if(i>=t.length)throw new Error("End of buffer");return t[i++]},l=()=>{if(a!==0)return r(16);let z=s.getUint16(i,!1);return i+=2,z},c=()=>{if(a!==0)return r(32);let z=s.getUint32(i,!1);return i+=4,z},p=()=>{let z=l(),pe=c();return z*4294967296+pe},u=z=>{if(a!==0){let T=new Uint8Array(z);for(let A=0;A<z;A++)T[A]=r(8);return T}if(i+z>t.length)throw new Error("End of buffer");let pe=t.slice(i,i+z);return i+=z,pe};if(o()!==1)throw new Error("Invalid configuration version");let f=r(2),g=r(1)===1,v=r(5),_=c(),R=p(),D=o();r(4);let L=r(12);r(6);let q=r(2);r(6);let M=r(2);r(5);let Y=r(3);r(5);let ae=r(3),Z=l(),ye=r(2),Le=r(3),Nt=r(1)===1,qe=r(2);if(qe===2)throw new Error("length_size_minus_one must be 0, 1, or 3");let gt=o(),ce=[];for(let z=0;z<gt;z++){let pe=r(1)===1;r(1);let T=r(6),A=fn.fromValue(T);T!==fn.VPS_NUT&&T!==fn.SPS_NUT&&T!==fn.PPS_NUT&&T!==fn.PREFIX_SEI_NUT&&fn.SUFFIX_SEI_NUT;let X=l(),Te=[];for(let ee=0;ee<X;ee++){let Ge=l(),bt=u(Ge);Te.push(bt)}ce.push({arrayCompleteness:pe,nalUnitType:A,nalus:Te})}return new n({generalProfileSpace:f,generalTierFlag:g,generalProfileIdc:v,generalProfileCompatibilityFlags:_,generalConstraintIndicatorFlags:R,generalLevelIdc:D,minSpatialSegmentationIdc:L,parallelismType:q,chromaFormatIdc:M,bitDepthLumaMinus8:Y,bitDepthChromaMinus8:ae,avgFrameRate:Z,constantFrameRate:ye,numTemporalLayers:Le,temporalIdNested:Nt,lengthSizeMinusOne:qe,arrays:ce})}toCodecString(){let t={0:"",1:"A",2:"B",3:"C"}[this.generalProfileSpace];if(t===void 0)throw new Error("Unknown profile space");let s=`${t}${this.generalProfileIdc}`,i=this.generalProfileCompatibilityFlags.toString(16).padStart(8,"0").split("").reverse().join(""),a="";for(let u=0;u<i.length;u++){let m=i[u];(m!=="0"||u===0)&&(a+=m)}let o=`${this.generalTierFlag?"H":"L"}${this.generalLevelIdc}`,l="",c=this.generalConstraintIndicatorFlags,p=[Math.floor(c/1099511627776)&255,Math.floor(c/4294967296)&255,Math.floor(c/16777216)&255,Math.floor(c/65536)&255,Math.floor(c/256)&255,c&255];for(let u=2;u<6;u++)p[u]!==0&&(l+=`.${p[u].toString(16).padStart(2,"0")}`);return`hev1.${s}.${a}.${o}${l}`}};var Hg=.1,Hp=.02,ii=class{videoDecoder=null;audioDecoder=null;videoWriter=null;audioContext=null;mediaDestination=null;isWaitingForKeyFrame=!0;nextStartTime=0;lastVideoConfig=null;nodeCall;events;generatedStream=null;constructor(e,t={}){this.nodeCall=e,this.events=t}async acceptConnection(){try{await this.nodeCall.acceptConnection()}catch(e){console.error("\u274C Error starting MediaStreamReceiver:",e)}}getRemoteStream=()=>this.generatedStream;stop=()=>{this.resetDecoders()};initAudioContext=async()=>{if(!this.audioContext||this.audioContext.state==="closed"){let e=window.AudioContext||window.webkitAudioContext;this.audioContext=new e({sampleRate:48e3,latencyHint:"interactive"}),this.mediaDestination=this.audioContext.createMediaStreamDestination(),this.audioContext.state==="suspended"&&await this.audioContext.resume(),this.nextStartTime=this.audioContext.currentTime+Hp}};initDecoders=e=>{if(this.audioDecoder&&this.audioDecoder.close(),this.initAudioContext(),this.mediaDestination){let t=this.mediaDestination.stream.getAudioTracks()[0];this.generatedStream=new MediaStream([t])}this.isWaitingForKeyFrame=!0,this.audioDecoder=new AudioDecoder({output:t=>this.playDecodedAudio(t),error:t=>console.error("AudioDecoder error:",t)}),e==="video"&&this.setupVideoDecoder(),this.receiveLoop()};setupVideoDecoder=()=>{if(!this.videoWriter)return;if(this.videoDecoder)try{this.videoDecoder.state!=="closed"&&this.videoDecoder.close()}catch{}let e=new VideoDecoder({output:async t=>{try{if(!this.videoWriter){t.close();return}if(this.videoWriter.desiredSize<=0){t.close();return}await this.videoWriter.write(t)}catch{t.close()}finally{t.close()}},error:t=>{if(console.error("\u274C VideoDecoder CRASHED:",t),this.isWaitingForKeyFrame=!0,this.videoWriter&&(console.log("\u267B\uFE0F Attempting to respawn VideoDecoder..."),this.setupVideoDecoder(),this.lastVideoConfig&&this.videoDecoder))try{this.videoDecoder.configure(this.lastVideoConfig)}catch{}}});this.videoDecoder=e};playDecodedAudio=e=>{try{if(!this.audioContext||!this.mediaDestination){e.close();return}let{numberOfChannels:t,numberOfFrames:s,sampleRate:i}=e,a=s/i,r=this.audioContext.currentTime;this.nextStartTime<r?this.nextStartTime=r:this.nextStartTime>r+Hg&&(this.nextStartTime=r+Hp);let o=this.audioContext.createBuffer(t,s,i),l=t*s,c=new Float32Array(l);e.copyTo(c,{planeIndex:0,format:"f32-planar"});for(let u=0;u<t;u++){let m=c.subarray(u*s,(u+1)*s);o.copyToChannel(m,u)}let p=this.audioContext.createBufferSource();p.buffer=o,p.connect(this.mediaDestination),p.start(this.nextStartTime),this.nextStartTime+=a,e.close()}catch(t){console.error("Error in playDecodedAudio:",t),e?.close()}};newCodecFromDescription=(e,t)=>{if(!t.toLowerCase().includes("hvc")&&!t.toLowerCase().includes("hev"))return"";try{return si.demux(e).toCodecString()}catch{return""}};receiveLoop=async()=>{let e=new TextDecoder;for(;;)try{if(!this.nodeCall)break;let t=await this.nodeCall.asyncRecv(),s=new DataView(t.buffer,t.byteOffset,t.byteLength),i=s.getUint8(0),a=[0,1,6,7,5,8,9,10].includes(i)?1:9,r=new Uint8Array(t.buffer,t.byteOffset+a,t.byteLength-a);switch(i){case 0:{try{let l=e.decode(r),c=JSON.parse(l);if(console.log("--videoConfig--",c),!this.videoWriter){let f=new MediaStreamTrackGenerator({kind:"video"});this.videoWriter=f.writable.getWriter(),this.generatedStream&&this.generatedStream.addTrack(f)}this.videoDecoder||this.setupVideoDecoder(),this.isWaitingForKeyFrame=!0;let p;if(c.description)try{let f=atob(c.description),g=new Uint8Array(f.length);for(let v=0;v<f.length;v++)g[v]=f.charCodeAt(v);p=g.buffer}catch{}let u="";p&&(u=this.newCodecFromDescription(p,c.codec)||$l(c.codec));let m={codec:u,frameRate:c.frameRate,codedWidth:c.codedWidth,codedHeight:c.codedHeight,...c.orientation&&{rotation:c.orientation},...p&&{description:p}};this.lastVideoConfig=m,this.videoDecoder&&this.videoDecoder.state!=="closed"&&((await VideoDecoder.isConfigSupported(m)).supported?(this.videoDecoder.configure(m),this.isWaitingForKeyFrame=!0):console.error("\u274C Browser does not support this video config:",m))}catch(l){console.error("\u274C Error processing VIDEO_CONFIG:",l)}break}case 1:{let l=JSON.parse(e.decode(r));console.log("--audioConfig--",l),this.audioDecoder?.state!=="closed"&&this.audioDecoder?.configure({codec:l.codec,sampleRate:l.sampleRate,numberOfChannels:l.numberOfChannels});break}case 2:case 3:{if(!this.videoDecoder||this.videoDecoder.state!=="configured")break;let l=i===2;if(this.isWaitingForKeyFrame){if(!l)break;console.log("\u2705 Resumed decoding at KeyFrame"),this.isWaitingForKeyFrame=!1}if(!l&&this.videoDecoder.decodeQueueSize>15){console.warn("\u26A0\uFE0F Queue > 15. Dropping & Waiting for KeyFrame..."),this.isWaitingForKeyFrame=!0;break}let c=s.getBigUint64(1,!1),p=Number(c);try{this.videoDecoder.decode(new EncodedVideoChunk({type:l?"key":"delta",timestamp:p,data:r}))}catch(u){console.error("Video decode failed:",u),this.videoDecoder.state==="closed"&&(this.isWaitingForKeyFrame=!0)}break}case 4:{if(this.audioDecoder?.state==="configured"){let l=s.getBigUint64(1,!1),c=Number(l);this.audioDecoder.decode(new EncodedAudioChunk({type:"key",timestamp:c,data:r}))}break}case 6:this.events.onConnected&&this.events.onConnected();break;case 7:let o=JSON.parse(e.decode(r));this.events.onTransceiverState&&this.events.onTransceiverState(o);break;case 5:{let l=s.getInt32(1,!1);if(this.videoDecoder&&this.lastVideoConfig&&this.lastVideoConfig.rotation!==l){this.lastVideoConfig.rotation=l;try{this.videoDecoder.configure(this.lastVideoConfig),this.isWaitingForKeyFrame=!0,console.log("\u{1F504} Reconfigured rotation to",l,"- Waiting for next KeyFrame")}catch(c){console.error("Error reconfiguring VideoDecoder with new orientation:",c)}}break}case 8:console.log("\u{1F4E5} Received REQUEST_CONFIG"),this.events.onRequestConfig&&this.events.onRequestConfig();break;case 9:console.log("\u{1F4E5} Received REQUEST_KEY_FRAME"),this.events.onRequestKeyFrame&&this.events.onRequestKeyFrame();break;case 10:console.log("\u{1F4E5} Received END_CALL"),this.events.onEndCall&&this.events.onEndCall();break;default:console.warn("\u2753 Unknown frame type received:",i);break}}catch(t){console.error("Stream loop error",t),await new Promise(s=>setTimeout(s,200))}};resetDecoders=()=>{if(this.videoWriter){try{this.videoWriter.abort("Stream stopped").catch(()=>{}),this.videoWriter.releaseLock()}catch(e){console.warn("Error closing video writer:",e)}this.videoWriter=null}if(this.videoDecoder){try{this.videoDecoder.state!=="closed"&&(this.videoDecoder.reset(),this.videoDecoder.close())}catch{}this.videoDecoder=null}if(this.audioDecoder){try{this.audioDecoder.state!=="closed"&&(this.audioDecoder.reset(),this.audioDecoder.close())}catch{}this.audioDecoder=null}if(this.audioContext){try{this.audioContext.close()}catch(e){console.warn("Error closing audio context:",e)}this.audioContext=null}this.isWaitingForKeyFrame=!0,this.mediaDestination=null,this.nextStartTime=0,this.lastVideoConfig=null,this.generatedStream&&(this.generatedStream.getTracks().forEach(e=>e.stop()),this.generatedStream=null)}};var Ya=class{wasmPath;relayUrl="https://test-iroh.ermis.network.:8443";_client;sessionID;cid;callType;userID;callStatus="";metadata;callNode=null;localStream=null;remoteStream=null;callerInfo;receiverInfo;onCallEvent;onLocalStream;onRemoteStream;onConnectionMessageChange;onCallStatus;onDataChannelMessage;onUpgradeCall;onScreenShareChange;onError;onDeviceChange;availableAudioDevices=[];availableVideoDevices=[];selectedAudioDeviceId;selectedVideoDeviceId;missCallTimeout=null;healthCallInterval=null;healthCallServerInterval=null;healthCallTimeout=null;healthCallWarningTimeout=null;signalHandler;connectionChangedHandler;messageUpdatedHandler;isOffline=!1;isDestroyed=!1;mediaSender=null;mediaReceiver=null;constructor(e,t,s,i){this._client=e,this.cid="",this.callType="",this.sessionID=t,this.userID=e.userID,this.metadata={},this.wasmPath=s,this.relayUrl=i,this.listenSocketEvents(),this.setupDeviceChangeListener(),this.loadWasm()}async loadWasm(){try{await Vp(this.wasmPath)}catch(e){throw console.error("Failed to load ErmisCall WASM module:",e),e}}async initialize(){try{let e=new mn;return await e.spawn([this.relayUrl]),this.callNode=e,this.mediaSender=new ni(e),this.mediaReceiver=new ii(e,{onConnected:()=>{this.setCallStatus("connected"),this.connectCall(),this.missCallTimeout&&(clearTimeout(this.missCallTimeout),this.missCallTimeout=null),this.healthCallServerInterval&&clearInterval(this.healthCallServerInterval),this.healthCallServerInterval=setInterval(()=>{this.healthCall()},1e4);let t=this.mediaReceiver?.getRemoteStream();t&&this.onRemoteStream&&this.onRemoteStream(t)},onTransceiverState:t=>{typeof this.onDataChannelMessage=="function"&&this.onDataChannelMessage(t)},onRequestConfig:()=>{console.log("\u{1F4E4} Responding to REQUEST_CONFIG by sending configs"),this.mediaSender?.sendConfigs()},onRequestKeyFrame:()=>{console.log("\u{1F4E4} Responding to REQUEST_KEY_FRAME by forcing key frame"),this.mediaSender?.requestKeyFrame()},onEndCall:()=>{console.log("\u{1F4E5} Received END_CALL from remote peer"),this.destroy()}}),e}catch(e){throw console.error("Failed to initialize Ermis SDK:",e),e}}async getLocalEndpointAddr(){try{if(await this.initialize(),!this.callNode)return console.error("ErmisCall is not initialized."),null;let e=await this.callNode.getLocalEndpointAddr();return this.metadata&&(this.metadata.address=e),e}catch(e){return console.error("Failed to get address from ErmisCall:",e),null}}getClient(){return this._client}async _sendSignal(e){try{return await this.getClient().post(this.getClient().baseURL+"/signal",{...e,cid:this.cid||e.cid,is_video:this.callType==="video"||e.is_video,ios:!1,session_id:this.sessionID})}catch(t){let s=e.action;if(s==="health-call")return;if(typeof this.onError=="function")if(t.code==="ERR_NETWORK")s==="create-call"&&this.onError("Unable to make the call. Please check your network connection");else if(t.response.data.ermis_code===20)this.onError("Recipient was busy");else{let i=t.response.data?.message?t.response.data?.message:"Call failed";this.onError(i)}}}async getAvailableDevices(){try{let e=await navigator.mediaDevices.enumerateDevices(),t=e.filter(i=>i.kind==="audioinput"),s=e.filter(i=>i.kind==="videoinput");return this.availableAudioDevices=t,this.availableVideoDevices=s,{audioDevices:t,videoDevices:s}}catch(e){return console.error("Error enumerating devices:",e),{audioDevices:[],videoDevices:[]}}}async getMediaConstraints(){let{audioDevices:e,videoDevices:t}=await this.getAvailableDevices();this.onDeviceChange&&this.onDeviceChange(e,t),!this.selectedAudioDeviceId&&e.length>0&&(this.selectedAudioDeviceId=e[0].deviceId),!this.selectedVideoDeviceId&&t.length>0&&(this.selectedVideoDeviceId=t[0].deviceId);let s={deviceId:this.selectedAudioDeviceId?{exact:this.selectedAudioDeviceId}:void 0,echoCancellation:!0,noiseSuppression:!0,sampleRate:48e3},i=this.callType==="video"?{deviceId:this.selectedVideoDeviceId?{exact:this.selectedVideoDeviceId}:void 0,width:640,height:360}:!1;return{audio:s,video:i}}async startLocalStream(){let e=await this.getMediaConstraints();try{let t=await navigator.mediaDevices.getUserMedia(e);return this.applyLocalStream(t)}catch(t){if(console.warn("Error getting user media:",t?.message),this.callType==="video"&&e.video)try{let s=await navigator.mediaDevices.getUserMedia({audio:e.audio,video:!1});return this.setConnectionMessage("Camera not available, using audio only"),this.applyLocalStream(s)}catch{}return typeof this.onError=="function"&&this.onError("No microphone or camera found. Please check your device."),null}}applyLocalStream(e){if(this.callStatus==="ended"){e.getTracks().forEach(t=>t.stop()),this.destroy();return}return this.onLocalStream&&this.onLocalStream(e),this.localStream=e,e}setConnectionMessage(e){typeof this.onConnectionMessageChange=="function"&&this.onConnectionMessageChange(e)}setCallStatus(e){this.callStatus=e,typeof this.onCallStatus=="function"&&this.onCallStatus(e)}setUserInfo(e,t){if(!e||!t)return;let i=(e?this.getClient().activeChannels[e]:void 0)?.state?.members||{},a=Object.keys(i),r=t||"",o=a.find(p=>p!==r)||"",l=this.getClient().state.users[r],c=this.getClient().state.users[o];this.callerInfo={id:r,name:l?.name,avatar:l?.avatar||""},this.receiverInfo={id:o,name:c?.name,avatar:c?.avatar||""}}listenSocketEvents(){this.signalHandler=async e=>{let{action:t,user_id:s,session_id:i,cid:a,is_video:r,signal:o,metadata:l}=e;switch(t){case"create-call":if(s===this.userID&&i!==this.sessionID){this.isDestroyed=!0,this.destroy();return}if(this.isDestroyed=!1,this.callStatus="",this.callType=r?"video":"audio",this.setUserInfo(a,s),this.setCallStatus("ringing"),this.cid=a||"",this.metadata=l||{},typeof this.onCallEvent=="function"&&this.onCallEvent({type:s!==this.userID?"incoming":"outgoing",callType:r?"video":"audio",cid:a||"",callerInfo:this.callerInfo,receiverInfo:this.receiverInfo,metadata:this.metadata}),await this.startLocalStream(),this.callStatus==="ended")return;s!==this.userID&&await this.initialize(),this.localStream&&this.mediaSender&&this.mediaReceiver&&(this.mediaSender?.initEncoders(this.localStream),this.mediaReceiver?.initDecoders(this.callType)),s===this.userID&&(this.missCallTimeout&&clearTimeout(this.missCallTimeout),this.missCallTimeout=setTimeout(async()=>{await this.missCall()},6e4));break;case"accept-call":if(s===this.userID&&i!==this.sessionID){this.isDestroyed=!0,this.destroy();return}s!==this.userID&&!this.isDestroyed&&this.mediaReceiver&&this.mediaSender&&(await this.mediaReceiver.acceptConnection(),await this.mediaSender.sendConnected(),await this.mediaSender.sendConfigs());break;case"end-call":case"reject-call":case"miss-call":this.destroy();break}},this.connectionChangedHandler=e=>{let t=e.online;this.isOffline=!t,t?(this.setConnectionMessage(null),this.callStatus==="connected"&&(this.healthCallServerInterval||(this.healthCallServerInterval=setInterval(()=>{this.healthCall()},1e4)))):(this.setConnectionMessage("Your network connection is unstable"),this.healthCallInterval&&(clearInterval(this.healthCallInterval),this.healthCallInterval=null),this.healthCallServerInterval&&(clearInterval(this.healthCallServerInterval),this.healthCallServerInterval=null))},this.messageUpdatedHandler=e=>{if(this.callStatus==="connected"&&e.cid===this.cid){let t=e.user?.id,s;t===this.callerInfo?.id?s=this.callerInfo:t===this.receiverInfo?.id&&(s=this.receiverInfo),s&&typeof this.onUpgradeCall=="function"&&this.onUpgradeCall(s)}},this._client.on("signal",this.signalHandler),this._client.on("connection.changed",this.connectionChangedHandler),this._client.on("message.updated",this.messageUpdatedHandler)}cleanupCall(){this.mediaSender&&(this.mediaSender?.stop(),this.mediaSender=null),this.mediaReceiver&&(this.mediaReceiver.stop(),this.mediaReceiver=null),this.callNode&&(this.callNode?.closeEndpoint(),this.callStatus==="connected"&&this.callNode?.closeConnection(),this.callNode=null),this.missCallTimeout&&(clearTimeout(this.missCallTimeout),this.missCallTimeout=null),this.healthCallInterval&&(clearInterval(this.healthCallInterval),this.healthCallInterval=null),this.healthCallServerInterval&&(clearInterval(this.healthCallServerInterval),this.healthCallServerInterval=null),this.healthCallTimeout&&(clearTimeout(this.healthCallTimeout),this.healthCallTimeout=null),this.healthCallWarningTimeout&&(clearTimeout(this.healthCallWarningTimeout),this.healthCallWarningTimeout=null),this.setConnectionMessage(null),this.cid="",this.callType="",this.metadata={},this.localStream&&(this.localStream.getTracks().forEach(e=>e.stop()),this.localStream=null),this.remoteStream&&(this.remoteStream.getTracks().forEach(e=>e.stop()),this.remoteStream=null),this.setCallStatus("ended")}destroy(){this.cleanupCall()}async getDevices(){return this.availableAudioDevices.length>0||this.availableVideoDevices.length>0?{audioDevices:this.availableAudioDevices,videoDevices:this.availableVideoDevices}:await this.getAvailableDevices()}getSelectedDevices(){let e=this.selectedAudioDeviceId?this.availableAudioDevices.find(s=>s.deviceId===this.selectedAudioDeviceId):void 0,t=this.selectedVideoDeviceId?this.availableVideoDevices.find(s=>s.deviceId===this.selectedVideoDeviceId):void 0;return{audioDevice:e,videoDevice:t}}getDefaultDevices(){return{audioDevice:this.availableAudioDevices[0],videoDevice:this.availableVideoDevices[0]}}async createCall(e,t){try{this.cid=t;let s=await this.getLocalEndpointAddr();await this._sendSignal({action:"create-call",cid:t,is_video:e==="video",metadata:{address:s}})}catch(s){throw console.error("Failed to create call:",s),s}}async acceptCall(){try{if(await this._sendSignal({action:"accept-call"}),this.mediaSender){let e=this.metadata?.address||"";await this.mediaSender.connect(e)}}catch(e){throw console.error("Failed to accept call:",e),e}}async endCall(){await this._sendSignal({action:"end-call"}),this.destroy()}async rejectCall(){await this._sendSignal({action:"reject-call"}),this.destroy()}async missCall(){await this._sendSignal({action:"miss-call"}),this.destroy()}async connectCall(){return await this._sendSignal({action:"connect-call"})}async healthCall(){return await this._sendSignal({action:"health-call"})}async addVideoTrackToLocalStream(){let e=await this.getMediaConstraints(),t=await navigator.mediaDevices.getUserMedia(e),s=t.getVideoTracks()[0];this.localStream?(this.localStream.addTrack(s),this.onLocalStream&&this.onLocalStream(this.localStream)):(this.localStream=t,this.onLocalStream&&this.onLocalStream(this.localStream))}async upgradeCall(){try{if(this.callType="video",await this.addVideoTrackToLocalStream(),await this._sendSignal({action:"upgrade-call"}),this.localStream){this.mediaSender?.initVideoEncoder(this.localStream?.getVideoTracks()[0]);let e=!!this.localStream?.getAudioTracks().some(s=>s.enabled),t=!!this.localStream?.getVideoTracks().some(s=>s.enabled);await this.mediaSender?.sendTransceiverState(e,t)}}catch(e){throw console.error("Failed to upgrade call:",e),e}}async requestUpgradeCall(e){if(e&&(this.callType="video",await this.addVideoTrackToLocalStream(),this.localStream)){this.mediaSender?.initVideoEncoder(this.localStream?.getVideoTracks()[0]);let t=!!this.localStream?.getAudioTracks().some(i=>i.enabled),s=!!this.localStream?.getVideoTracks().some(i=>i.enabled);await this.mediaSender?.sendTransceiverState(t,s)}}async startScreenShare(){if(!navigator.mediaDevices.getDisplayMedia)throw new Error("Screen sharing is not supported in this browser.");let e=await navigator.mediaDevices.getDisplayMedia({video:!0}),t=e.getVideoTracks()[0];this.localStream?(this.localStream.getVideoTracks().forEach(s=>s.stop()),this.localStream.removeTrack(this.localStream.getVideoTracks()[0]),this.localStream.addTrack(t)):this.localStream=e,t.onended=()=>{this.stopScreenShare()},this.onLocalStream&&(this.onLocalStream(this.localStream),this.mediaSender?.replaceVideoTrack(this.localStream.getVideoTracks()[0])),typeof this.onScreenShareChange=="function"&&this.onScreenShareChange(!0)}async stopScreenShare(){let e=await this.getMediaConstraints();try{let t=await navigator.mediaDevices.getUserMedia({video:e.video,audio:!1}),s=t.getVideoTracks()[0];this.localStream?(this.localStream.getVideoTracks().forEach(i=>{i.stop(),this.localStream?.removeTrack(i)}),this.localStream.addTrack(s)):this.localStream=t,this.onLocalStream&&(this.onLocalStream(this.localStream),this.mediaSender?.replaceVideoTrack(this.localStream.getVideoTracks()[0])),typeof this.onScreenShareChange=="function"&&this.onScreenShareChange(!1)}catch(t){console.error("Error stopping screen share and reverting to camera:",t)}}async toggleMic(e){if(this.localStream){this.localStream.getAudioTracks().forEach(i=>{i.enabled=e});let t=e,s=this.localStream.getVideoTracks().some(i=>i.enabled);await this.mediaSender?.sendTransceiverState(t,s)}}async toggleCamera(e){if(this.localStream){this.localStream.getVideoTracks().forEach(i=>{i.enabled=e});let t=this.localStream.getAudioTracks().some(i=>i.enabled),s=e;await this.mediaSender?.sendTransceiverState(t,s)}}async switchAudioDevice(e){try{if(!this.availableAudioDevices.find(r=>r.deviceId===e))return console.error("Audio device not found:",e),this.onError&&this.onError("Selected microphone not found"),!1;if(this.selectedAudioDeviceId=e,!this.localStream)return!1;let i=(await navigator.mediaDevices.getUserMedia({audio:{deviceId:{exact:e}},video:!1})).getAudioTracks()[0],a=this.localStream.getAudioTracks()[0];return a&&(this.localStream.removeTrack(a),a.stop()),this.localStream.addTrack(i),this.onLocalStream&&this.onLocalStream(this.localStream),!0}catch(t){return console.error("Error switching audio device:",t),this.onError&&this.onError("Failed to switch microphone"),!1}}async switchVideoDevice(e){try{if(!this.availableVideoDevices.find(r=>r.deviceId===e))return console.error("Video device not found:",e),this.onError&&this.onError("Selected camera not found"),!1;if(this.selectedVideoDeviceId=e,!this.localStream)return!1;let i=(await navigator.mediaDevices.getUserMedia({audio:!1,video:{deviceId:{exact:e}}})).getVideoTracks()[0],a=this.localStream.getVideoTracks()[0];return a&&(this.localStream.removeTrack(a),a.stop()),this.localStream.addTrack(i),this.onLocalStream&&this.onLocalStream(this.localStream),!0}catch(t){return console.error("Error switching video device:",t),this.onError&&this.onError("Failed to switch camera"),!1}}setupDeviceChangeListener(){navigator.mediaDevices.addEventListener("devicechange",async()=>{let{audioDevices:e,videoDevices:t}=await this.getAvailableDevices();this.onDeviceChange&&this.onDeviceChange(e,t)})}};pt();var Za=class{apiKey;baseURL;options;axiosInstance;disconnected;browser;node;logger;consecutiveFailures;userAgent;lastIdentifier;lastMethod;address;constructor(e,t,s){let i=s||{};this.apiKey=e,this.baseURL=s?.userBaseURL||t+"/uss/v1",this.browser=typeof i.browser<"u"?i.browser:typeof window<"u",this.node=!this.browser,this.options={withCredentials:!1,warmUp:!1,recoverStateOnReconnect:!0,...i},this.node&&!this.options.httpsAgent&&(this.options.httpsAgent=new yt.Agent({keepAlive:!0,keepAliveMsecs:3e3})),this.axiosInstance=rn.create(this.options),this.logger=Ms(i.logger)?i.logger:()=>null,this.consecutiveFailures=0,this.disconnected=!1}_logApiRequest(e,t,s,i){this.logger("info",`client: ${e} - Request - ${t}- ${JSON.stringify(s)} - ${JSON.stringify(i.params)}`,{tags:["api","api_request","client"],url:t,payload:s,config:i})}_logApiResponse(e,t,s){this.logger("info",`client:${e} - Response - url: ${t} > status ${s.status}`,{tags:["api","api_response","client"],url:t,response:s})}_logApiError(e,t,s,i){this.logger("error",`client:${e} - Error: ${JSON.stringify(s)} - url: ${t} - options: ${JSON.stringify(i)}`,{tags:["api","api_response","client"],url:t,error:s})}doAxiosRequest=async(e,t,s,i={})=>{let a=this._enrichAxiosOptions(i);try{let r;switch(this._logApiRequest(e,t,s,a),e){case"get":r=await this.axiosInstance.get(t,a);break;case"delete":r=await this.axiosInstance.delete(t,a);break;case"post":r=await this.axiosInstance.post(t,s,a);break;case"postForm":r=await this.axiosInstance.postForm(t,s,a);break;case"put":r=await this.axiosInstance.put(t,s,a);break;case"patch":r=await this.axiosInstance.patch(t,s,a);break;case"options":r=await this.axiosInstance.options(t,a);break;default:throw new Error("Invalid request type")}return this._logApiResponse(e,t,r),this.consecutiveFailures=0,this.handleResponse(r)}catch(r){if(r.client_request_id=a.headers?.["x-client-request-id"],this._logApiError(e,t,r,i),this.consecutiveFailures+=1,r.response)return r.response.data.code===mt.TOKEN_EXPIRED?(this.consecutiveFailures>1&&await on(js(this.consecutiveFailures)),await this.doAxiosRequest(e,t,s,a)):this.handleResponse(r.response);throw r}};get(e,t){return this.doAxiosRequest("get",e,null,{params:t})}put(e,t){return this.doAxiosRequest("put",e,t)}post(e,t,s){return this.doAxiosRequest("post",e,t,{params:s})}patch(e,t){return this.doAxiosRequest("patch",e,t)}delete(e,t){return this.doAxiosRequest("delete",e,null,{params:t})}errorFromResponse(e){let t;return t=new Mt(`ErmisChat error HTTP code: ${e.status}`),e.data&&e.data.code&&(t=new Error(`ErmisChat error code ${e.data.code}: ${e.data.message}`),t.code=e.data.code),t.response=e,t.status=e.status,t}handleResponse(e){let t=e.data;if(Hs(e))throw this.errorFromResponse(e);return t}getUserAgent(){return this.userAgent||`ermis-chat-sdk-javascript-client-${this.node?"node":"browser"}-1.0.6`}setUserAgent(e){this.userAgent=e}_enrichAxiosOptions(e={params:{},headers:{},config:{}}){let t=null;e.headers?.["x-client-request-id"]||(e.headers={...e.headers,"x-client-request-id":Ue()});let{params:s,headers:i,...a}=this.options?.axiosRequestConfig||{};return{params:{...e.params,...s||{}},headers:{"X-Stream-Client":this.getUserAgent(),...e.headers,...i||{}},...t?{signal:t}:{},...e.config,...a||{}}}async sendOtpToPhone(e,t){this.lastIdentifier=e,this.lastMethod=t;let s={apikey:this.apiKey,identifier:e,language:"Vi",method:t,otp_type:"Login"};return this.post(this.baseURL+"/auth/get_otp_new",s)}async sendOtpToEmail(e){this.lastIdentifier=e,this.lastMethod="Email";let t={apikey:this.apiKey,identifier:e,language:"Vi",method:"Email",otp_type:"Login"};return this.post(this.baseURL+"/auth/get_otp_new",t)}async verifyOtp(e){let t={identifier:this.lastIdentifier,method:this.lastMethod,apikey:this.apiKey,otp:e};return this.post(this.baseURL+"/auth/otp_login",t)}async loginWithGoogle(e){let t={token:e,apikey:this.apiKey};return this.post(this.baseURL+"/auth/google_login",t)}async getWalletChallenge(e){this.address=e;let t=await this.post(this.baseURL+"/auth/get_challenge",{address:e,apikey:this.apiKey});return JSON.parse(t.challenge)}createNonce(e){let t="",s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",i=s.length;for(let a=0;a<e;a++)t+=s.charAt(Math.floor(Math.random()*i));return t}async verifyWalletSignature(e){let t={address:this.address,signature:e,nonce:this.createNonce(20),apikey:this.apiKey};return this.post(this.baseURL+"/auth/verify_signature",t)}};var Kg={1e4:"10 seconds",3e4:"30 seconds",6e4:"1 minute",3e5:"5 minutes",9e5:"15 minutes",36e5:"60 minutes"};function er(n,e){return e[n]??n}function Kp(n,e){if(!n||typeof n!="string")return n??"";let t=n.trim();if(!t)return"";let s=t.split(" "),i=s[0],a=s[1]??"",r=a?er(a,e):"User";switch(i){case"1":{let o=s.slice(2).join(" ");return`${r} changed the channel name to ${o}.`}case"2":return`${r} changed the channel avatar.`;case"3":return`${r} changed the channel description.`;case"4":return`${r} was removed from the channel.`;case"5":return`${r} was banned.`;case"6":return`${r} was unbanned.`;case"7":return`${r} was promoted to moderator.`;case"8":return`${r} was demoted from moderator.`;case"9":return`${r}'s permissions were updated.`;case"10":return`${r} joined the channel.`;case"11":return`${r} declined the channel invitation.`;case"12":return`${r} left the channel.`;case"13":return`${r} cleared the chat history.`;case"14":{let l=(s[2]??"")==="true"?"public":"private";return`${r} changed the channel to ${l}.`}case"15":{let o=s[2]??"0";if(o==="0")return`${r} disabled cooldown.`;let l=Kg[o]??`${o}ms`;return`${r} enabled cooldown for ${l}.`}case"16":return`${r} updated the banned words.`;case"17":return`${r} was added to the channel.`;case"18":{let o=s[1]??"",l=s[2]??"",c=o?er(o,e):"User",p=l?er(l,e):"User";return`Admin ${c} left and assigned ${p} as the new admin.`}case"19":return`${r} pinned a message.`;case"20":return`${r} unpinned a message.`;default:return t}}var ze={AUDIO:"audio",VIDEO:"video"};function Jg(n){if(!n)return"";let e=parseInt(n,10);if(isNaN(e)||e<=0)return"";let t=Math.floor(e/1e3),s=Math.floor(t/60),i=t%60;return`${s} min, ${i} sec`}function Jp(n,e){if(!n||typeof n!="string")return null;let t=n.trim();if(!t)return null;let s=t.split(" "),i=parseInt(s[0],10),a=s[1]??"",r=e===a,o="",l="",c="",p="";(i===3||i===6)&&(o=s[2]??"",l=s[3]==="0"?"":s[3]??"");let u;switch(i){case 1:u=r?"Calling...":"Incoming audio call...",c=ze.AUDIO,p="#54D62C";break;case 2:u=r?"Outgoing audio call":"You missed audio call",c=ze.AUDIO,p="#FF4842";break;case 3:l?(u=r?"Outgoing audio call":"Incoming audio call",p="#54D62C"):(o===e?u="You cancel audio call":u="You missed audio call",p="#FF4842"),c=ze.AUDIO;break;case 4:u=r?"Calling...":"Incoming video call...",c=ze.VIDEO,p="#54D62C";break;case 5:u=r?"Outgoing video call":"You missed video call",c=ze.VIDEO,p="#FF4842";break;case 6:l?(u=r?"Outgoing video call":"Incoming video call",p="#54D62C"):(o===e?u="You cancel video call":u="You missed video call",p="#FF4842"),c=ze.VIDEO;break;case 7:u=r?"Recipient rejected audio call":"You rejected audio call",c=ze.AUDIO,p="#FF4842";break;case 8:u=r?"Recipient rejected video call":"You rejected video call",c=ze.VIDEO,p="#FF4842";break;case 9:u=r?"Recipient was busy":"You missed audio call",c=ze.AUDIO,p="#FF4842";break;case 10:u=r?"Recipient was busy":"You missed video call",c=ze.VIDEO,p="#FF4842";break;default:u=t,c="",p=""}return{text:u,duration:Jg(l),callType:c,color:p}}return bn(Xg);})();
20
+ `+a):s.stack=a}catch{}}throw s}}_request(e,t){typeof e=="string"?(t=t||{},t.url=e):t=e||{},t=Je(this.defaults,t);let{transitional:s,paramsSerializer:i,headers:a}=t;s!==void 0&&Fn.assertOptions(s,{silentJSONParsing:Qe.transitional(Qe.boolean),forcedJSONParsing:Qe.transitional(Qe.boolean),clarifyTimeoutError:Qe.transitional(Qe.boolean)},!1),i!=null&&(d.isFunction(i)?t.paramsSerializer={serialize:i}:Fn.assertOptions(i,{encode:Qe.function,serialize:Qe.function},!0)),t.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),Fn.assertOptions(t,{baseUrl:Qe.spelling("baseURL"),withXsrfToken:Qe.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let r=a&&d.merge(a.common,a[t.method]);a&&d.forEach(["delete","get","head","post","put","patch","common"],g=>{delete a[g]}),t.headers=se.concat(r,a);let o=[],l=!0;this.interceptors.request.forEach(function(v){typeof v.runWhen=="function"&&v.runWhen(t)===!1||(l=l&&v.synchronous,o.unshift(v.fulfilled,v.rejected))});let c=[];this.interceptors.response.forEach(function(v){c.push(v.fulfilled,v.rejected)});let p,u=0,m;if(!l){let g=[Ls.bind(this),void 0];for(g.unshift.apply(g,o),g.push.apply(g,c),m=g.length,p=Promise.resolve(t);u<m;)p=p.then(g[u++],g[u++]);return p}m=o.length;let f=t;for(u=0;u<m;){let g=o[u++],v=o[u++];try{f=g(f)}catch(_){v.call(this,_);break}}try{p=Ls.call(this,f)}catch(g){return Promise.reject(g)}for(u=0,m=c.length;u<m;)p=p.then(c[u++],c[u++]);return p}getUri(e){e=Je(this.defaults,e);let t=Et(e.baseURL,e.url,e.allowAbsoluteUrls);return Ct(t,e.params,e.paramsSerializer)}};d.forEach(["delete","get","head","options"],function(e){an.prototype[e]=function(t,s){return this.request(Je(s||{},{method:e,url:t,data:(s||{}).data}))}});d.forEach(["post","put","patch"],function(e){function t(s){return function(a,r,o){return this.request(Je(o||{},{method:e,headers:s?{"Content-Type":"multipart/form-data"}:{},url:a,data:r}))}}an.prototype[e]=t(),an.prototype[e+"Form"]=t(!0)});var Pn=an;var ma=class n{constructor(e){if(typeof e!="function")throw new TypeError("executor must be a function.");let t;this.promise=new Promise(function(a){t=a});let s=this;this.promise.then(i=>{if(!s._listeners)return;let a=s._listeners.length;for(;a-- >0;)s._listeners[a](i);s._listeners=null}),this.promise.then=i=>{let a,r=new Promise(o=>{s.subscribe(o),a=o}).then(i);return r.cancel=function(){s.unsubscribe(a)},r},e(function(a,r,o){s.reason||(s.reason=new je(a,r,o),t(s.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;let t=this._listeners.indexOf(e);t!==-1&&this._listeners.splice(t,1)}toAbortSignal(){let e=new AbortController,t=s=>{e.abort(s)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let e;return{token:new n(function(i){e=i}),cancel:e}}},Ul=ma;function fa(n){return function(t){return n.apply(null,t)}}function ha(n){return d.isObject(n)&&n.isAxiosError===!0}var ga={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(ga).forEach(([n,e])=>{ga[e]=n});var Ll=ga;function Fl(n){let e=new Pn(n),t=xn(Pn.prototype.request,e);return d.extend(t,Pn.prototype,e,{allOwnKeys:!0}),d.extend(t,e,null,{allOwnKeys:!0}),t.create=function(i){return Fl(Je(n,i))},t}var ue=Fl(Xt);ue.Axios=Pn;ue.CanceledError=je;ue.CancelToken=Ul;ue.isCancel=kn;ue.VERSION=kt;ue.toFormData=dt;ue.AxiosError=C;ue.Cancel=ue.CanceledError;ue.all=function(e){return Promise.all(e)};ue.spread=fa;ue.isAxiosError=ha;ue.mergeConfig=Je;ue.AxiosHeaders=se;ue.formToJSON=n=>ws(d.isHTMLForm(n)?new FormData(n):n);ue.getAdapter=Us.getAdapter;ue.HttpStatusCode=Ll;ue.default=ue;var rn=ue;var{Axios:Fy,AxiosError:Py,CanceledError:My,isCancel:jy,CancelToken:Ny,VERSION:qy,all:Gy,Cancel:By,isAxiosError:$y,spread:zy,toFormData:Wy,AxiosHeaders:Vy,HttpStatusCode:Hy,formToJSON:Ky,getAdapter:Jy,mergeConfig:Xy}=rn;pt();var Pl=Re(Ai());function Ps(n,e){n.then().catch(t=>{console.warn(`failed to do ${e}, ran into error: `,t)})}var on=n=>new Promise(e=>setTimeout(e,n));function Ms(n){return n&&(Object.prototype.toString.call(n)==="[object Function]"||typeof n=="function"||n instanceof Function)}var mt={TOKEN_EXPIRED:40,WS_CLOSED_SUCCESS:1e3};function ch(n){return n!==null&&typeof n=="object"&&(n.readable||typeof n._read=="function")}function lh(n){return n!=null&&n.constructor!=null&&typeof n.constructor.isBuffer=="function"&&n.constructor.isBuffer(n)}function ph(n){return typeof window<"u"&&"File"in window&&n instanceof File}function uh(n){return typeof window<"u"&&"Blob"in window&&n instanceof Blob}function Ml(n,e,t){let s=new Pl.default;return ch(n)||lh(n)||ph(n)||uh(n)?e?s.append("file",n,e):s.append("file",n):s.append("file",{uri:n,name:e||n.split("/").reverse()[0],contentType:t||void 0,type:t||void 0}),s}function js(n){let e=Math.min(500+n*2e3,25e3),t=Math.min(Math.max(250,(n-1)*2e3),25e3);return Math.floor(Math.random()*(e-t)+t)}function Ue(){return dh()}function Mn(n){let e="";for(let t=0;t<n.length;t++)e+=n[t].toString(16).padStart(2,"0");return e}function dh(){let n=hh(16);return n[6]=n[6]&15|64,n[8]=n[8]&191|128,Mn(n.subarray(0,4))+"-"+Mn(n.subarray(4,6))+"-"+Mn(n.subarray(6,8))+"-"+Mn(n.subarray(8,10))+"-"+Mn(n.subarray(10,16))}function mh(n){let e=Math.pow(2,8*n.byteLength/n.length);for(let t=0;t<n.length;t++)n[t]=Math.random()*e}var fh=typeof crypto<"u"&&typeof crypto?.getRandomValues<"u"?crypto.getRandomValues.bind(crypto):typeof msCrypto<"u"?msCrypto.getRandomValues.bind(msCrypto):mh;function hh(n){let e=new Uint8Array(n);return fh(e),e}function jl(n){typeof window<"u"&&window.addEventListener&&(window.addEventListener("offline",n),window.addEventListener("online",n))}function Nl(n){typeof window<"u"&&window.removeEventListener&&(window.removeEventListener("offline",n),window.removeEventListener("online",n))}var ql=n=>{let e=[];for(let t in n)n[t]!==void 0&&(Array.isArray(n[t])||typeof n[t]=="object"?e.push(`${t}=${encodeURIComponent(JSON.stringify(n[t]))}`):e.push(`${t}=${encodeURIComponent(n[t])}`));return e.join("&")};function Gl(n){return{...n,__html:n.html,pinned_at:n.pinned_at?new Date(n.pinned_at):null,created_at:n.created_at?new Date(n.created_at):new Date,updated_at:n.updated_at?new Date(n.updated_at):new Date,status:n.status||"received"}}function Bl(n,e,t=!1,s="created_at",i=!0){let a=i||t,r=n;t&&(r=r.filter(v=>!(v.id&&e.id===v.id)));let o=r.length;if(o===0&&a)return r.concat(e);if(o===0)return[...r];if(s==="pinned_at")return r.concat(e);let l=e[s].getTime(),c=r[o-1][s].getTime()<l;if(c&&a)return r.concat(e);if(c)return[...r];let p=0,u=0,m=o-1;for(;p<=m;)u=Math.floor((m+p)/2),r[u][s].getTime()<=l?p=u+1:m=u-1;if(!t&&e.id){if(r[p]&&e.id===r[p].id)return r[p]=e,[...r];if(r[p-1]&&e.id===r[p-1].id)return r[p-1]=e,[...r]}a&&r.splice(p,0,e);let f=new Map,g=[];for(let v of r)f.has(v.id)||(f.set(v.id,!0),g.push(v));return g}var H=(n,e)=>n.length===0?[]:e.length===0?n.map(t=>(t.user={id:t.user?.id,name:t.user?.id,avatar:""},t)):n.map(t=>{let s=t.user?.id,i=t?.latest_reactions,a=t?.quoted_message,r=e.find(o=>o.id===s);if(r&&(t.user={id:r.id,name:r.name||r.id,avatar:r.avatar||""}),i&&(t.latest_reactions=i.map(o=>{let l=e.find(c=>c.id===o.user_id);return{...o,user:{id:l?.id||o.user_id,name:l?.name||o.user_id,avatar:l?.avatar||""}}})),a){let o=e.find(l=>l.id===a.user?.id);t.quoted_message.user={id:o?.id||a.user?.id,name:o?.name||a.user?.id,avatar:o?.avatar||""}}return t}),W=(n,e)=>{if(e.length===0)return{id:n,name:n,avatar:""};let t=e.find(s=>s.id===n);return{id:n,name:t?.name||n,avatar:t?.avatar||""}},Dt=(n,e)=>{if(n.length===0)return"Empty channel";let t=n.find(s=>s.user.id!==e);return t?t.user.name||t.user.id:"Empty channel"},jn=(n,e)=>{if(n.length===0)return"";let t=n.find(s=>s.user.id!==e);return t&&t.user.avatar||""};async function Nn(n,e){let t=(e||[]).map(a=>a.user?.id).filter(a=>!!a),s=n.state.users,i=t.filter(a=>!s[a]);i.length>0&&await n.getBatchUsers(i)}var Ot=(n=[])=>n.length>0?Math.max(...n.map(e=>new Date(e.created_at).getTime())):0,Ut=(n,e,t,s)=>{let i,a;if(["videoConfig","audioConfig","transciverState"].includes(t)&&s){i=1;let l=JSON.stringify(s);a=new TextEncoder().encode(l)}else t==="connected"?(i=1,a=new Uint8Array(0)):(i=9,a=new Uint8Array(n));let r=new Uint8Array(i+a.byteLength),o=0;switch(t){case"videoConfig":o=0;break;case"audioConfig":o=1;break;case"video-key":o=2;break;case"video-delta":o=3;break;case"audio":o=4;break;case"connected":o=6;break;case"transciverState":o=7;break}return r[0]=o,e!==null&&new DataView(r.buffer).setBigUint64(1,BigInt(e),!1),r.set(a,i),r},ba=n=>{let e="",t=new Uint8Array(n),s=t.byteLength;for(let i=0;i<s;i++)e+=String.fromCharCode(t[i]);return btoa(e)},$l=n=>{let e={2048:"123",4096:"153",8192:"156",16384:"183",32768:"186"},t=/2048|4096|8192|16384|32768/g;return n.match(t)?n.replace(t,s=>e[s]):"hev1.1.6.L123.B0"},zl=(n,e,t)=>{let s={cid:e,forward_cid:t,forward_message_id:n.id};return n.sticker_url&&(!n.text||n.text==="")&&(!n.attachments||Array.isArray(n.attachments)&&n.attachments.length===0)?(s.sticker_url=n.sticker_url,s.text=n.text):(s.text=n.text||"",n.attachments&&n.attachments.length>0&&(s.attachments=n.attachments.filter(i=>i.type!=="linkPreview"))),s};var qn=class{_channel;watcher_count;typing;read;pinnedMessages;watchers;members;unreadCount;membership;last_message_at;isUpToDate;messageSets=[];topics=[];constructor(e){this._channel=e,this.watcher_count=0,this.typing={},this.read={},this.initMessages(),this.pinnedMessages=[],this.watchers={},this.members={},this.membership={},this.unreadCount=0,this.isUpToDate=!0,this.last_message_at=e?.state?.last_message_at!=null?new Date(e.state.last_message_at):null}get messages(){return this.messageSets.find(e=>e.isCurrent)?.messages||[]}set messages(e){let t=this.messageSets.findIndex(s=>s.isCurrent);this.messageSets[t].messages=e}get latestMessages(){return this.messageSets.find(e=>e.isLatest)?.messages||[]}set latestMessages(e){let t=this.messageSets.findIndex(s=>s.isLatest);this.messageSets[t].messages=e}addMessageSorted(e,t=!1,s=!0,i="latest"){return this.addMessagesSorted([e],t,!1,s,i)}formatMessage(e){return{...e,__html:e.html,pinned_at:e.pinned_at?new Date(e.pinned_at):null,created_at:e.created_at?new Date(e.created_at):new Date,updated_at:e.updated_at?new Date(e.updated_at):null,status:e.status||"received"}}addMessagesSorted(e,t=!1,s=!1,i=!0,a="current"){let{messagesToAdd:r,targetMessageSetIndex:o}=this.findTargetMessageSet(e,i,a);for(let l=0;l<r.length;l+=1){let c=r[l].created_at instanceof Date,p;if(c?p=r[l]:(p=this.formatMessage(r[l]),p.user&&this._channel?.cid&&this._channel.getClient().state.updateUserReference(p.user,this._channel.cid),this.last_message_at||(this.last_message_at=new Date(p.created_at.getTime())),p.created_at.getTime()>this.last_message_at.getTime()&&(this.last_message_at=new Date(p.created_at.getTime()))),!p.pinned){let m=this.pinnedMessages.find(f=>f.id===p.id);m&&(p.pinned=!0,p.pinned_at=m.pinned_at||new Date)}!p.parent_id&&o!==-1&&(this.messageSets[o].messages=this._addToMessageList(this.messageSets[o].messages,p,t,"created_at",i))}return{messageSet:this.messageSets[o]}}addPinnedMessages(e){for(let t=0;t<e.length;t+=1)this.addPinnedMessage(e[t]);this.pinnedMessages.sort((t,s)=>{let i=t.pinned_at?new Date(t.pinned_at).getTime():0;return(s.pinned_at?new Date(s.pinned_at).getTime():0)-i})}addPinnedMessage(e){let t=this.formatMessage(e);this.pinnedMessages=this.pinnedMessages.filter(s=>s.id!==t.id),this.pinnedMessages=[t,...this.pinnedMessages]}removePinnedMessage(e){let{result:t}=this.removeMessageFromArray(this.pinnedMessages,e);this.pinnedMessages=t}addReaction(e,t,s){if(!t)return;let i=t;return this._updateMessage(t,a=>(i.own_reactions=this._addOwnReactionToMessage(a.own_reactions,e,s),this.formatMessage(i))),i}_addOwnReactionToMessage(e,t,s){return s?e=[]:e=this._removeOwnReactionFromMessage(e,t),e=e||[],this._channel.getClient().userID===t.user_id&&e.push(t),e}_removeOwnReactionFromMessage(e,t){return e&&e.filter(s=>s.user_id!==t.user_id||s.type!==t.type)}removeReaction(e,t){if(!t)return;let s=t;return this._updateMessage(t,i=>(s.own_reactions=this._removeOwnReactionFromMessage(i.own_reactions,e),this.formatMessage(s))),s}removeQuotedMessageReferences(e){let t=s=>({...s,created_at:s.created_at.toISOString(),pinned_at:s.pinned_at?.toISOString(),updated_at:s.updated_at?.toISOString()});this.messageSets.forEach(s=>{let i=s.messages.filter(a=>a.quoted_message_id===e.id).map(t).map(a=>({...a,quoted_message:{...e,attachments:[]}}));this.addMessagesSorted(i,!0)})}_updateMessage(e,t){let{parent_id:s,pinned:i}=e;if(!s){let a=this.findMessageSetIndex(e);if(a!==-1){let r=this.messageSets[a].messages.findIndex(o=>o.id===e.id);r!==-1&&(this.messageSets[a].messages[r]=t(this.messageSets[a].messages[r]))}}if(i){let a=this.pinnedMessages.findIndex(r=>r.id===e.id);a!==-1&&(this.pinnedMessages[a]=t(this.pinnedMessages[a]))}}setIsUpToDate=e=>{this.isUpToDate=e};updateMessageStatus(e,t){this._updateMessage({id:e},s=>({...s,status:t}))}_addToMessageList(e,t,s=!1,i="created_at",a=!0){return Bl(e,t,s,i,a)}removeMessage(e){let t=!1,s=e.messageSetIndex??this.findMessageSetIndex(e);if(s!==-1){let{removed:i,result:a}=this.removeMessageFromArray(this.messageSets[s].messages,e);this.messageSets[s].messages=a,t=i}return t}removeMessageFromArray=(e,t)=>{let s=e.filter(i=>!(i.id&&t.id&&i.id===t.id));return{removed:s.length<e.length,result:s}};updateUserMessages=e=>{let t=(s,i)=>{for(let a=0;a<s.length;a++){let r=s[a],o=r?.latest_reactions||[];r.user?.id===i.id&&(s[a]={...r,user:r.user?.id===i.id?i:r.user}),o&&o.some(l=>l.user?.id===i.id)&&(s[a]={...r,latest_reactions:o.map(l=>l.user?.id===i.id?{...l,user:i}:l)})}};this.messageSets.forEach(s=>t(s.messages,e)),t(this.pinnedMessages,e)};deleteUserMessages=(e,t=!1)=>{let s=(i,a,r=!1)=>{for(let o=0;o<i.length;o++){let l=i[o];l.user?.id===a.id&&(r?i[o]={cid:l.cid,created_at:l.created_at,deleted_at:new Date().toISOString(),id:l.id,latest_reactions:[],mentioned_users:[],own_reactions:[],parent_id:l.parent_id,reply_count:l.reply_count,status:l.status,type:"deleted",updated_at:l.updated_at,user:l.user}:i[o]={...l,type:"deleted",deleted_at:new Date().toISOString()})}};this.messageSets.forEach(i=>s(i.messages,e,t)),s(this.pinnedMessages,e,t)};filterErrorMessages(){let e=this.latestMessages.filter(t=>t.type!=="error");this.latestMessages=e}clean(){let e=new Date;for(let[t,s]of Object.entries(this.typing)){let i=typeof s.received_at=="string"?new Date(s.received_at):s.received_at||new Date;e.getTime()-i.getTime()>7e3&&(delete this.typing[t],this._channel.getClient().dispatchEvent({cid:this._channel.cid,type:"typing.stop",user:{id:t}}))}}clearMessages(){this.initMessages(),this.pinnedMessages=[]}initMessages(){this.messageSets=[{messages:[],isLatest:!0,isCurrent:!0}]}async loadMessageIntoState(e,t,s=25){let i,a=!1,r=t||e;if(e==="latest"){if(this.messages===this.latestMessages)return;i=this.messageSets.findIndex(o=>o.isLatest)}else i=this.findMessageSetIndex({id:r});i!==-1&&(this.switchToMessageSet(i),a=!0),a||await this._channel.query({messages:{id_around:r,limit:s}},"new"),i=this.findMessageSetIndex({id:r}),i!==-1&&this.switchToMessageSet(i)}findMessage(e,t){let s=this.findMessageSetIndex({id:e});if(s!==-1)return this.messageSets[s].messages.find(i=>i.id===e)}switchToMessageSet(e){let t=this.messageSets.find(s=>s.isCurrent);t&&(t.isCurrent=!1,this.messageSets[e].isCurrent=!0)}areMessageSetsOverlap(e,t){return e.some(s=>t.find(i=>s.id===i.id))}findMessageSetIndex(e){return this.messageSets.findIndex(t=>!!t.messages.find(s=>s.id===e.id))}findTargetMessageSet(e,t=!0,s="current"){let i=e,a;if(t){let r=this.messageSets.map((c,p)=>p).filter(c=>this.areMessageSetsOverlap(this.messageSets[c].messages,e));switch(s){case"new":r.length>0?a=r[0]:e.some(c=>!c.parent_id)&&(this.messageSets.push({messages:[],isCurrent:!1,isLatest:!1}),a=this.messageSets.length-1);break;case"current":a=this.messageSets.findIndex(c=>c.isCurrent);break;case"latest":a=this.messageSets.findIndex(c=>c.isLatest);break;default:a=-1}let o=r.splice(0,1)[0],l=[...r];if(o!==void 0&&o!==a&&l.push(a),l.length>0){let c=this.messageSets[o],p=this.messageSets.filter((m,f)=>l.indexOf(f)!==-1);p.forEach(m=>{c.isLatest=c.isLatest||m.isLatest,c.isCurrent=c.isCurrent||m.isCurrent,i=[...i,...m.messages]}),p.forEach(m=>this.messageSets.splice(this.messageSets.indexOf(m),1)),a=this.messageSets.findIndex(m=>this.areMessageSetsOverlap(m.messages,e))}}else a=this.findMessageSetIndex(e[0]);return{targetMessageSetIndex:a,messagesToAdd:i}}};function Gn(n){let e=n.lastIndexOf("."),t=e>0?n.slice(0,e):n,s=e>0?n.slice(e):"";return t.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/đ/g,"d").replace(/Đ/g,"D").replace(/\s+/g,"_")+s}function Wl(n){let e=n.type.toLowerCase(),t=n.name.toLowerCase().split(".").pop()||"";return e==="image/heic"||e==="image/heif"||t==="heic"||t==="heif"}function xa(n,e){let t=n.toLowerCase(),s=(e||"").toLowerCase().split(".").pop()||"";return t==="image/heic"||t==="image/heif"||s==="heic"||s==="heif"?"file":t.startsWith("image/")?"image":t.startsWith("video/")?"video":t.startsWith("audio/")?"audio":"file"}function Ns(n){return n.type==="video/mp4"||n.type==="video/webm"||n.type==="video/quicktime"}function qs(n,e,t,s){let i=Gn(n.name),a=n.type||"",r=xa(a,n.name);if(s)return{type:"voiceRecording",asset_url:e,title:i,file_size:n.size,mime_type:a,waveform_data:s.waveform_data,duration:s.duration};switch(r){case"image":return{type:"image",image_url:e,title:i,file_size:n.size,mime_type:a};case"video":return{type:"video",asset_url:e,title:i,file_size:n.size,mime_type:a,thumb_url:t||""};case"audio":return{type:"file",asset_url:e,title:i,file_size:n.size,mime_type:a};default:return{type:"file",asset_url:e,title:i,file_size:n.size,mime_type:a||""}}}var cn=class{_client;type;id;data;_data;cid;listeners;state;initialized;offlineMode;lastKeyStroke;lastTypingEvent;isTyping;disconnected;constructor(e,t,s,i){let a=/^[\w_-]+$/,r=/^[\w!:_-]+$/;if(!a.test(t))throw new Error(`Invalid chat type ${t}, letters, numbers and "_-" are allowed`);if(typeof s=="string"&&!r.test(s))throw new Error(`Invalid chat id ${s}, letters, numbers and "!-_" are allowed`);this._client=e,this.type=t,this.id=s,this.data=i,this._data={...i},this.cid=`${t}:${s}`,this.listeners={},this.state=new qn(this),this.initialized=!1,this.offlineMode=!1,this.lastTypingEvent=null,this.isTyping=!1,this.disconnected=!1}getClient(){return this._client}async sendMessage(e){e.id||(e={...e,id:Ue()});let t=e.id,s={...e,id:t,status:"sending",created_at:new Date().toISOString(),updated_at:new Date().toISOString(),user:this.getClient().user,user_id:this.getClient().userID,type:"regular"};this.state.addMessageSorted(s);try{return await this.getClient().post(this._channelURL()+"/message",{message:{...e}})}catch(i){let r=!i.response||i.code==="ERR_NETWORK"||i.isWSFailure||!this.getClient().wsConnection?.isHealthy?"failed_offline":"error";throw this.state.updateMessageStatus(t,r),i}}async retryMessage(e){let t=this.state.messages.find(i=>i.id===e);if(!t)throw new Error(`Message ${e} not found in state`);this.state.updateMessageStatus(e,"sending");let s={id:t.id,text:t.text,attachments:t.attachments,mentioned_users:t.mentioned_users,parent_id:t.parent_id,quoted_message_id:t.quoted_message_id,sticker_url:t.sticker_url};t.show_in_channel!==void 0&&(s.show_in_channel=t.show_in_channel);try{return await this.getClient().post(this._channelURL()+"/message",{message:s})}catch(i){let a=!i.response||i.code==="ERR_NETWORK"||i.isWSFailure||!this.getClient().wsConnection?.isHealthy;throw this.state.updateMessageStatus(e,a?"failed_offline":"error"),i}}async createPoll(e){let t=Ue();return e={...e,id:t},await this.getClient().post(this._channelURL()+"/message",{message:{...e}})}async votePoll(e,t){if(!e)throw Error("Message id is missing");return await this.getClient().post(this.getClient().baseURL+`/messages/${this.type}/${this.id}/${e}/poll/${t}`)}async forwardMessage(e,t){return e.id||(e={...e,id:Ue()}),await this.getClient().post(`${this.getClient().baseURL}/channels/${t.type}/${t.channelID}/message`,{message:{...e}})}async pinMessage(e){return await this.getClient().post(this.getClient().baseURL+`/messages/${this.type}/${this.id}/${e}/pin`)}async unpinMessage(e){return await this.getClient().post(this.getClient().baseURL+`/messages/${this.type}/${this.id}/${e}/unpin`)}async pin(){this.data&&(this.data.is_pinned=!0),this.getClient().dispatchEvent({type:"channel.pinned",cid:this.cid,channel:this.data});try{return await this.getClient().pinChannel(this.type,this.id)}catch(e){throw this.data&&(this.data.is_pinned=!1),this.getClient().dispatchEvent({type:"channel.unpinned",cid:this.cid,channel:this.data}),e}}async unpin(){this.data&&(this.data.is_pinned=!1),this.getClient().dispatchEvent({type:"channel.unpinned",cid:this.cid,channel:this.data});try{return await this.getClient().unpinChannel(this.type,this.id)}catch(e){throw this.data&&(this.data.is_pinned=!0),this.getClient().dispatchEvent({type:"channel.pinned",cid:this.cid,channel:this.data}),e}}async editMessage(e,t){return await this.getClient().post(this.getClient().baseURL+`/messages/${this.type}/${this.id}/${e}`,{message:t})}sendFile(e,t,s,i){return this.getClient().sendFile(`${this._channelURL()}/file`,e,t,s,i)}async uploadAndPrepareAttachments(e,t){let s=[],i=e.map(c=>{let p=Gn(c.name);return p!==c.name?new File([c],p,{type:c.type,lastModified:c.lastModified}):c}),a=await Promise.allSettled(i.map(c=>this.sendFile(c,c.name,c.type))),r=new Map,o=[];for(let c=0;c<i.length;c++)a[c].status==="fulfilled"&&Ns(i[c])&&o.push((async()=>{try{let u=await this.getThumbBlobVideo(e[c]);if(u){let m=new File([u],`thumb_${i[c].name}.jpg`,{type:"image/jpeg"}),f=await this.sendFile(m,m.name,"image/jpeg");r.set(c,f.file)}}catch{}})());await Promise.allSettled(o);let l=[];for(let c=0;c<i.length;c++){let p=a[c];if(p.status==="fulfilled"){let u=p.value.file,m=r.get(c),f=t?.voiceMetadata?.get(c);l.push(qs(i[c],u,m,f))}else s.push({file:e[c],error:p.reason instanceof Error?p.reason:new Error(String(p.reason))})}return{attachments:l,failedFiles:s}}async sendEvent(e){return await this.getClient().post(this._channelURL()+"/event",{event:e})}async sendReaction(e,t){if(!e)throw Error("Message id is missing");return await this.getClient().post(this.getClient().baseURL+`/messages/${this.type}/${this.id}/${e}/reaction/${t}`)}deleteReaction(e,t){if(!t||!e)throw Error("Deleting a reaction requires specifying both the message and reaction type");let s=this.getClient().baseURL+`/messages/${this.type}/${this.id}/${e}/reaction/${t}`;return this.getClient().delete(s,{})}async update(e={},t){return["config","cid","created_by","id","member_count","type","created_at","updated_at","last_message_at","own_capabilities"].forEach(i=>{delete e[i]}),await this._update({message:t,data:e})}async delete(){return await this.getClient().delete(this._channelURL())}async truncate(){return await this.getClient().delete(this._channelURL()+"/truncate")}async blockUser(){return await this.getClient().post(this._channelURL(),{action:"block"})}async unblockUser(){return await this.getClient().post(this._channelURL(),{action:"unblock"})}async acceptInvite(e){let t=this.id,s=this.getClient().userBaseURL+`/token_gate/join_channel/${this.type}`;return this.getClient().post(s,{},{channel_id:t,action:e})}async rejectInvite(){let e=this.getClient().baseURL+`/invites/${this.type}/${this.id}/reject`;return this.getClient().post(e)}async skipInvite(){let e=this.getClient().baseURL+`/invites/${this.type}/${this.id}/skip`;return this.getClient().post(e)}async addMembers(e){return await this._update({add_members:e})}async addModerators(e){return await this._update({promote_members:e})}async banMembers(e){return await this._update({ban_members:e})}async unbanMembers(e){return await this._update({unban_members:e})}async updateCapabilities(e){return await this._update({capabilities:e})}async setSlowMode(e){let t=[0,1e4,3e4,6e4,3e5,9e5,36e5];if(!t.includes(e))throw new Error(`Invalid cooldown value: ${e}. Allowed values are: ${t.join(", ")} (milliseconds).`);return await this.update({member_message_cooldown:e})}async queryAttachmentMessages(){let e=await this.getClient().post(this.getClient().baseURL+`/channels/${this.type}/${this.id}/attachment`,{attachment_types:["image","video","file","voiceRecording","linkPreview"]});return e.attachments&&e.attachments.sort((t,s)=>new Date(s.created_at).getTime()-new Date(t.created_at).getTime()),e}async searchMessage(e,t){let s=await this.getClient().post(this.getClient().baseURL+"/channels/search",{cid:this.cid,search_term:e,offset:t,limit:25});return!s||s?.search_result?.messages.length===0?null:{...s?.search_result,messages:s?.search_result?.messages.map(i=>{let a=W(i.user_id,Object.values(this.getClient().state.users))||i.user;return{...i,user:a}})}}async removeMembers(e){return await this._update({remove_members:e})}async demoteModerators(e){return await this._update({demote_members:e})}async _update(e){let t=await this.getClient().post(this._channelURL(),e);return this.data={...this.data,...t.channel},t}_processTopics(e,t){let s=e.map(a=>(a.channel&&a.channel.members&&(a.channel.members=H(a.channel.members,t)),a.messages&&(a.messages=H(a.messages,t)),a.pinned_messages&&(a.pinned_messages=H(a.pinned_messages,t)),a.read&&(a.read=H(a.read,t)),a)),{channels:i}=this.getClient().hydrateChannels(s,{});this.state.topics=i}async muteNotification(e){return await this.getClient().post(this.getClient().baseURL+`/channels/${this.type}/${this.id}/muted`,{mute:!0,duration:e})}async unMuteNotification(){return await this.getClient().post(this.getClient().baseURL+`/channels/${this.type}/${this.id}/muted`,{mute:!1})}async keystroke(e,t){let s=new Date,i=this.lastTypingEvent&&s.getTime()-this.lastTypingEvent.getTime();this.lastKeyStroke=s,this.isTyping=!0,(i===null||i>2e3)&&(this.lastTypingEvent=new Date,await this.sendEvent({type:"typing.start",parent_id:e,...t||{}}))}async stopTyping(e,t){this.isTyping&&(this.lastTypingEvent=null,this.isTyping=!1,await this.sendEvent({type:"typing.stop",parent_id:e,...t||{}}))}_isTypingIndicatorsEnabled(){return!0}lastMessage(){let e=this.state.latestMessages.length-5;e<0&&(e=0);let t=this.state.latestMessages.length+1,s=this.state.latestMessages.slice(e,t);return s.sort((i,a)=>a.created_at.getTime()-i.created_at.getTime()),s[0]}async markRead(){return await this.getClient().post(this._channelURL()+"/read")}clean(){this.lastKeyStroke&&new Date().getTime()-this.lastKeyStroke.getTime()>1e3&&this.isTyping&&Ps(this.stopTyping(),"stop typing event"),this.state.clean()}async watch(e){await this.getClient().wsPromise;let t={...e},s=await this.query(t,"latest");this.initialized=!0,await Nn(this.getClient(),s.channel.members);let i=Object.values(this.getClient().state.users);if(s.channel.members=H(s.channel.members,i),s.channel.name=s.channel.type==="messaging"?Dt(s.channel.members,this.getClient().userID||""):s.channel.name,s.channel.image=s.channel.type==="messaging"?jn(s.channel.members,this.getClient().userID||""):s.channel.image,s.messages=H(s.messages,i),s.pinned_messages=s.pinned_messages?H(s.pinned_messages,i):[],s.read=H(s.read||[],i),this.type==="team"&&s.channel.topics_enabled){let a={filter_conditions:{type:["topic"],parent_cid:this.cid,project_id:this.getClient().projectId},sort:[],message_limit:25},r=await this.getClient().post(this.getClient().baseURL+"/channels",a);this._processTopics(r.channels||[],i)}return this.data=s.channel,this._client.logger("info",`channel:watch() - started watching channel ${this.cid}`,{tags:["channel"],channel:this}),s}lastRead(){let{userID:e}=this.getClient();if(e)return this.state.read[e]?this.state.read[e].last_read:null}_countMessageAsUnread(e){return!(e.parent_id&&!e.show_in_channel||e.user?.id===this.getClient().userID||e.type==="system"||Array.isArray(this.data?.own_capabilities)&&!this.data?.own_capabilities.includes("read-events"))}countUnread(e){if(!e)return this.state.unreadCount;let t=0;for(let s=0;s<this.state.latestMessages.length;s+=1){let i=this.state.latestMessages[s];i.created_at>e&&this._countMessageAsUnread(i)&&t++}return t}getUnreadMemberCount(){return this.state.read?Object.values(this.state.read):[]}getCapabilitiesMember(){return this.data?this.data.member_capabilities:[]}create=async()=>this.type==="messaging"?await this.createDirectChannel("latest"):await this.query({},"latest");async createTopic(e){let t=this._client.projectId,s=Ue(),i=`${t}:${s}`,a=`${this.getClient().baseURL}/channels/topic/${i}`,r={project_id:t,parent_cid:this.cid,data:{...e}};return await this.getClient().post(a+"/query",r)}async query(e,t="current"){await this.getClient().wsPromise;let s=this._client.projectId,i={...e,project_id:s},a=`${this.getClient().baseURL}/channels/${this.type}`;if(this.id)a+=`/${this.id}`;else if(this.type==="team"||this.type==="meeting"){let u=Ue();this.id=`${s}:${u}`,a+=`/${this.id}`}let r={state:!0,...i};this._data&&Object.keys(this._data).length>0&&(r.data=this._data);let o=await this.getClient().post(a+"/query",r);await Nn(this.getClient(),o.channel.members);let l=Object.values(this.getClient().state.users);if(o.channel.members=H(o.channel.members,l),o.channel.name=o.channel.type==="messaging"?Dt(o.channel.members,this.getClient().userID||""):o.channel.name,o.channel.image=o.channel.type==="messaging"?jn(o.channel.members,this.getClient().userID||""):o.channel.image,o.messages=H(o.messages,l),o.pinned_messages=o.pinned_messages?H(o.pinned_messages,l):[],o.read=H(o.read||[],l),o.channel.is_pinned=o.is_pinned||!1,!this.id){this.id=o.channel.id,this.cid=o.channel.cid;let u=o.channel.members.map(f=>f.user_id||f.user?.id).sort().join(","),m=`${this.type}:!members-${u}`;m in this.getClient().activeChannels&&delete this.getClient().activeChannels[m],this.cid in this.getClient().activeChannels||(this.getClient().activeChannels[this.cid]=this)}let{messageSet:c}=this._initializeState(o,t),p=[...o.channel.own_capabilities||[]].sort().join()!==[...Array.isArray(this.data?.own_capabilities)?this.data?.own_capabilities:[]].sort().join();return this.data=o.channel,this.offlineMode=!1,p&&this.getClient().dispatchEvent({type:"capabilities.changed",cid:this.cid,own_capabilities:o.channel.own_capabilities}),o}async createDirectChannel(e="current"){await this.getClient().wsPromise;let t=this._client.projectId,s=`${this.getClient().baseURL}/channels/${this.type}`,i={project_id:t};this._data&&Object.keys(this._data).length>0&&(i.data=this._data);let a=await this.getClient().post(s+"/query",i),r=Object.values(this.getClient().state.users);a.channel.members=H(a.channel.members,r),a.channel.name=a.channel.type==="messaging"?Dt(a.channel.members,this.getClient().userID||""):a.channel.name,a.messages=H(a.messages,r),a.pinned_messages=a.pinned_messages?H(a.pinned_messages,r):[],a.read=H(a.read||[],r);let{messageSet:o}=this._initializeState(a,e),l=[...a.channel.own_capabilities||[]].sort().join()!==[...Array.isArray(this.data?.own_capabilities)?this.data?.own_capabilities:[]].sort().join();return this.data=a.channel,this.offlineMode=!1,l&&this.getClient().dispatchEvent({type:"capabilities.changed",cid:a.channel.cid,own_capabilities:a.channel.own_capabilities}),a}async queryMessagesLessThanId(e,t=25){await this.getClient().wsPromise;let s=this._client.projectId,i=`${this.getClient().baseURL}/channels/${this.type}/${this.id}`,a=await this.getClient().post(i+"/query",{state:!0,project_id:s,messages:{limit:t,id_lt:e}}),r=Object.values(this.getClient().state.users);if(a.messages=H(a.messages,r),a.messages&&a.messages.length>0){for(let o of a.messages)if(!o.pinned){let l=this.state.pinnedMessages?.find(c=>c.id===o.id);if(l){o.pinned=!0;let c=l.pinned_at||new Date;o.pinned_at=typeof c=="string"?c:c.toISOString()}}this.state.addMessagesSorted(a.messages,!1,!0,!0,"current")}return a.messages}async queryMessagesGreaterThanId(e,t=25){await this.getClient().wsPromise;let s=this._client.projectId,i=`${this.getClient().baseURL}/channels/${this.type}/${this.id}`,a=await this.getClient().post(i+"/query",{state:!0,project_id:s,messages:{limit:t,id_gt:e}}),r=Object.values(this.getClient().state.users);if(a.messages=H(a.messages,r),a.messages&&a.messages.length>0){for(let o of a.messages)if(!o.pinned){let l=this.state.pinnedMessages?.find(c=>c.id===o.id);if(l){o.pinned=!0;let c=l.pinned_at||new Date;o.pinned_at=typeof c=="string"?c:c.toISOString()}}this.state.addMessagesSorted(a.messages,!1,!0,!0,"current")}return a.messages}async queryMessagesAroundId(e,t=25){await this.getClient().wsPromise;let s=this._client.projectId,i=`${this.getClient().baseURL}/channels/${this.type}/${this.id}`,a=await this.getClient().post(i+"/query",{state:!0,project_id:s,messages:{limit:t,id_around:e}}),r=Object.values(this.getClient().state.users);if(a.messages=H(a.messages,r),a.messages&&a.messages.length>0){for(let o of a.messages)if(!o.pinned){let l=this.state.pinnedMessages?.find(c=>c.id===o.id);if(l){o.pinned=!0;let c=l.pinned_at||new Date;o.pinned_at=typeof c=="string"?c:c.toISOString()}}this.state.addMessagesSorted(a.messages,!1,!0,!0,"current")}return a.messages}async deleteMessage(e){return await this.getClient().delete(this.getClient().baseURL+`/messages/${this.type}/${this.id}/${e}`)}async deleteMessageForMe(e){return await this.getClient().delete(this.getClient().baseURL+`/messages/${this.type}/${this.id}/${e}`,{for_me:!0})}async getThumbBlobVideo(e){return new Promise(t=>{let i=document.createElement("video");i.src=URL.createObjectURL(e),i.crossOrigin="anonymous",i.load(),i.addEventListener("error",()=>{console.error("Error when loading video file."),t(null)}),i.addEventListener("loadedmetadata",()=>{if(i.duration<.1){console.error("Video is too short."),t(null);return}setTimeout(()=>{i.currentTime=.1},200)}),i.addEventListener("seeked",()=>{try{let a=document.createElement("canvas");a.width=i.videoWidth,a.height=i.videoHeight;let r=a.getContext("2d");if(!r){console.error("Failed to create canvas context."),t(null);return}r.drawImage(i,0,0,a.width,a.height),r.canvas.toBlob(o=>{if(!o){console.error("Failed to generate thumbnail."),t(null);return}t(o),URL.revokeObjectURL(i.src)},"image/jpeg",.75)}catch(a){console.error("Error while extracting thumbnail:",a),t(null)}})})}async enableTopics(){return await this.getClient().post(this.getClient().baseURL+`/channels/${this.type}/${this.id}/topics/enable`,{project_id:this.getClient().projectId,messages:{limit:25}})}async disableTopics(){return await this.getClient().post(this.getClient().baseURL+`/channels/${this.type}/${this.id}/topics/disable`,{project_id:this.getClient().projectId})}async closeTopic(e){return await this.getClient().post(this.getClient().baseURL+`/channels/${this.type}/${this.id}/topics/close`,{project_id:this.getClient().projectId,topic_cid:e})}async reopenTopic(e){return await this.getClient().post(this.getClient().baseURL+`/channels/${this.type}/${this.id}/topics/reopen`,{project_id:this.getClient().projectId,topic_cid:e})}async editTopic(e,t){let s=await this.getClient().post(this.getClient().baseURL+`/channels/${this.type}/${this.id}/topics`,{project_id:this.getClient().projectId,topic_cid:e,data:t});if(s){let i=this.getClient().activeChannels[e];return i?(i.data=s.channel,i.data):s.channel}}on(e,t){let s=t?e:"all",i=t||e;return s in this.listeners||(this.listeners[s]=[]),this._client.logger("info",`Attaching listener for ${s} event on channel ${this.cid}`,{tags:["event","channel"],channel:this}),this.listeners[s].push(i),{unsubscribe:()=>{this._client.logger("info",`Removing listener for ${s} event from channel ${this.cid}`,{tags:["event","channel"],channel:this}),this.listeners[s]=this.listeners[s].filter(a=>a!==i)}}}off(e,t){let s=t?e:"all",i=t||e;s in this.listeners||(this.listeners[s]=[]),this._client.logger("info",`Removing listener for ${s} event from channel ${this.cid}`,{tags:["event","channel"],channel:this}),this.listeners[s]=this.listeners[s].filter(a=>a!==i)}async _handleChannelEvent(e){let t=this;this._client.logger("info",`channel:_handleChannelEvent - Received event of type { ${e.type} } on ${this.cid}`,{tags:["event","channel"],channel:this});let s=t.state,i=Object.values(this.getClient().state.users);switch(e.type){case"typing.start":if(e.user?.id){let c=W(e.user.id||"",i);e.user=c,s.typing[e.user.id]=e}break;case"typing.stop":e.user?.id&&delete s.typing[e.user.id];break;case"message.read":if(e.user?.id&&e.created_at){let c=W(e.user.id||"",i);e.user=c,s.read[e.user.id]={last_read:new Date(e.created_at),last_read_message_id:e.last_read_message_id,user:c,unread_messages:0},e.user?.id===this.getClient().user?.id&&(s.unreadCount=0)}break;case"user.watching.start":e.user?.id&&(s.watchers[e.user.id]=e.user);break;case"user.watching.stop":e.user?.id&&delete s.watchers[e.user.id];break;case"message.deleted":if(e.message){this._extendEventWithOwnReactions(e);s.removeMessage(e.message),s.addMessageSorted(e.message,!1,!1),s.removeQuotedMessageReferences(e.message),[...s.pinnedMessages].some(c=>c.id===e.message?.id)&&s.removePinnedMessage(e.message);for(let c in s.read)c!==e.user?.id&&e.message.id===s.read[c].last_read_message_id&&(s.read[c]={...s.read[c],last_read_message_id:void 0})}break;case"message.deleted_for_me":e.message&&(s.removeMessage(e.message),s.removeQuotedMessageReferences(e.message),[...s.pinnedMessages].some(c=>c.id===e.message?.id)&&s.removePinnedMessage(e.message));break;case"message.new":if(e.message){let c=e.user?.id===this.getClient().user?.id,p=!!e.message.parent_id;if(!i.find(g=>g.id===e.user?.id)&&e.user?.id){let g=await this.getClient().queryUser(e.user.id);i.push(g)}let m=W(e.user?.id||"",i);if(e.message.user=m,e.message?.quoted_message){let g=W(e.message.quoted_message.user?.id||"",i);e.message.quoted_message.user=g}if(e.user=m,(this.state.isUpToDate||p)&&s.addMessageSorted(e.message,c),c||p)break;if(e.user?.id)for(let g in s.read)g===e.user.id?s.read[e.user.id]={last_read:new Date(e.created_at),user:e.user,unread_messages:0}:s.read[g].unread_messages+=1;this._countMessageAsUnread(e.message)&&(s.unreadCount=s.unreadCount+1)}break;case"message.updated":if(e.message){let c=W(e.user?.id||"",i),p=W(e.message.user?.id||"",i);if(e.user=c,e.message.user=p,e.message?.quoted_message){let u=W(e.message.quoted_message.user?.id||"",i);e.message.quoted_message.user=u}e.message?.latest_reactions&&(e.message.latest_reactions=H(e.message.latest_reactions||[],i)),this._extendEventWithOwnReactions(e),s.addMessageSorted(e.message,!1,!1),e.message.pinned?s.addPinnedMessage(e.message):s.removePinnedMessage(e.message)}break;case"message.pinned":if(e.message){let c=W(e.message.user?.id||"",i);e.message.user=c,s.addPinnedMessage(e.message),s.addMessageSorted(e.message,!1,!1)}break;case"message.unpinned":if(e.message){let c=W(e.message.user?.id||"",i);e.message.user=c,s.removePinnedMessage(e.message),s.addMessageSorted(e.message,!1,!1)}break;case"channel.truncate":if(e.channel?.created_at){let c=+new Date(e.channel.created_at);s.messageSets.forEach((p,u)=>{p.messages.forEach(({created_at:m,id:f})=>{c>+m&&s.removeMessage({id:f,messageSetIndex:u})})}),s.pinnedMessages.forEach(({id:p,created_at:u})=>{c>+u&&s.removePinnedMessage({id:p})})}else s.clearMessages();s.unreadCount=0,e.message&&(s.addMessageSorted(e.message),e.message.pinned&&s.addPinnedMessage(e.message));break;case"member.added":if(e.member?.user_id){let c=W(e.member.user_id,i);e.member.user=c,s.members[e.member.user_id]=e.member,e.member.user?.id===this.getClient().user?.id&&(s.membership=e.member)}break;case"member.updated":if(e.member?.user_id){let c=W(e.member.user_id,i);e.member.user=c,s.members[e.member.user_id]=e.member,s.membership=e.member}break;case"member.removed":e.member?.user_id?delete s.members[e.member.user_id]:e.user?.id&&delete s.members[e.user.id];break;case"channel.topic.enabled":t.data&&(t.data.topics_enabled=!0),s.topics=s.topics||[];break;case"channel.topic.disabled":t.data&&(t.data.topics_enabled=!1),s.topics=[];break;case"channel.updated":e.channel&&(t.data={...t.data,...e.channel,own_capabilities:e.channel?.own_capabilities??t.data?.own_capabilities});break;case"pollchoice.new":if(e.message){let c=W(e.message.user?.id||"",i);e.message.user=c,s.addMessageSorted(e.message,!1,!1)}break;case"reaction.new":if(e.message&&e.reaction){let c=W(e.message.user?.id||"",i),p=W(e.reaction.user?.id||"",i);if(e.message.user=c,e.message.latest_reactions=H(e.message.latest_reactions||[],i),e.reaction.user=p,e.message?.quoted_message){let u=W(e.message.quoted_message.user?.id||"",i);e.message.quoted_message.user=u}e.message=s.addReaction(e.reaction,e.message)}break;case"reaction.deleted":if(e.user=W(e.user?.id||"",i),e.message){if(e.message?.quoted_message){let c=W(e.message.quoted_message.user?.id||"",i);e.message.quoted_message.user=c}e.message.user=W(e.message.user?.id||"",i),e.message.latest_reactions?.map(c=>(c.user=W(c.user?.id||"",i),c))}e.reaction&&(e.reaction.user=W(e.reaction.user?.id||"",i),e.message=s.removeReaction(e.reaction,e.message));break;case"member.joined":case"notification.invite_accepted":if(e.member?.user_id){if(!i.find(u=>u.id===e.member?.user_id)){let u=await this.getClient().queryUser(e.member?.user_id);i.push(u)}let p=W(e.member.user_id,i);e.member.user=p,e.member.user_id===this.getClient().user?.id&&(s.membership=e.member,this.state.membership=e.member),s.members[e.member.user_id]=e.member,t.data={...t.data,member_count:Number(t.data?.member_count)+1,members:t.data?.members?[...t.data.members,e.member]:[e.member]},this.offlineMode=!0,this.initialized=!0}break;case"notification.invite_rejected":e.member?.user_id&&delete s.members[e.member.user_id];break;case"notification.invite_messaging_skipped":if(e.member?.user_id){let c=W(e.member.user_id,i);e.member.user=c,e.member.user_id===this.getClient().user?.id&&(s.membership=e.member,this.state.membership=e.member),s.members[e.member.user_id]=e.member}break;case"member.promoted":case"member.demoted":case"member.banned":case"member.unbanned":case"member.blocked":case"member.unblocked":if(e.member?.user_id){let c=W(e.member.user_id,i);e.member.user=c,s.members[e.member.user_id]=e.member,e.member.user_id===this.getClient().user?.id&&(s.membership=e.member,this.state.membership=e.member)}break;case"channel.pinned":t.data&&(t.data.is_pinned=!0);break;case"channel.unpinned":t.data&&(t.data.is_pinned=!1);break;case"channel.topic.disabled":t.data&&(t.data.topics_enabled=!1),e.user=W(e.user?.id||"",i);break;case"channel.topic.enabled":t.data&&(t.data.topics_enabled=!0),e.user=W(e.user?.id||"",i);break;case"channel.topic.created":let a=e.channel?.members||[],r=H(a,i),o={channel:e.channel,members:r,messages:[],pinned_messages:[]},l=this.getClient().channel(e.channel_type||"",e.channel_id||"");l.data=e.channel,l._initializeState(o,"latest"),s.topics||(s.topics=[]),s.topics.some(c=>c.cid===l.cid)||s.topics.push(l);break;case"channel.topic.closed":t.data&&(t.data.is_closed_topic=!0),e.user=W(e.user?.id||"",i);break;case"channel.topic.reopen":t.data&&(t.data.is_closed_topic=!1),e.user=W(e.user?.id||"",i);break;case"channel.topic.updated":t.data&&(t.data.name=e.channel?.name,t.data.image=e.channel?.image,t.data.description=e.channel?.description),e.user=W(e.user?.id||"",i);break;default:}e.watcher_count!==void 0&&(t.state.watcher_count=e.watcher_count)}_callChannelListeners=e=>{let t=this,s=[];t.listeners.all&&s.push(...t.listeners.all),t.listeners[e.type]&&s.push(...t.listeners[e.type]);for(let i of s)typeof i!="string"&&i(e)};_channelURL=()=>{if(!this.id)throw new Error("channel id is not defined");return`${this.getClient().baseURL}/channels/${this.type}/${this.id}`};_checkInitialized(){if(!this.initialized&&!this.offlineMode)throw Error(`Channel ${this.cid} hasn't been initialized yet. Make sure to call .watch() and wait for it to resolve`)}_initializeState(e,t="latest",s){let{state:i,user:a,userID:r}=this.getClient();if(e.channel.members)for(let u of e.channel.members)u.user&&(s&&s(u.user.id),i.updateUserReference(u.user,this.cid));this.state.membership=e.membership||{};let o=new Map,l=[];e.messages||(e.messages=[]);for(let u of e.messages)o.has(u.id)||(o.set(u.id,!0),l.push(u));this.state.pinnedMessages&&(this.state.pinnedMessages=[]),this.state.addPinnedMessages(e.pinned_messages||[]);let c=l||[];this.state.messages||this.state.initMessages();let{messageSet:p}=this.state.addMessagesSorted(c,!1,!0,!0,t);if(e.watcher_count!==void 0&&(this.state.watcher_count=e.watcher_count),e.watchers)for(let u of e.watchers)u&&(i.updateUserReference(u,this.cid),this.state.watchers[u.id]=u);if(r!=null){let u=this.state.last_message_at||new Date;a&&(this.state.read[a.id]={user:a,last_read:u,unread_messages:0})}if(e.read)for(let u of e.read)this.state.read[u.user.id]={last_read:new Date(u.last_read),last_read_message_id:u.last_read_message_id,unread_messages:u.unread_messages??0,user:u.user,last_send:u.last_send},u.user.id===a?.id&&(this.state.unreadCount=this.state.read[u.user.id].unread_messages);if(e.channel.members&&(this.state.members=e.channel.members.reduce((u,m)=>(m.user&&(u[m.user.id]=m),u),{})),e.channel.type==="team"&&e.channel.topics_enabled&&e.topics){let u=Object.values(this.getClient().state.users);this._processTopics(e.topics,u)}return{messageSet:p}}_extendEventWithOwnReactions(e){if(!e.message)return;let t=this.state.findMessage(e.message.id,e.message.parent_id);t&&(e.message.own_reactions=t.own_reactions)}_disconnect(){this._client.logger("info",`channel:disconnect() - Disconnecting the channel ${this.cid}`,{tags:["connection","channel"],channel:this}),this.disconnected=!0,this.state.setIsUpToDate(!1)}};var ln=class{users;userChannelReferences;constructor(){this.users={},this.userChannelReferences={}}updateUsers(e){for(let t of e)this.updateUser(t)}updateUser(e){if(e!=null)if(this.users[e.id]){let t={...this.users[e.id],...e};this.users[e.id]=t}else this.users[e.id]=e}updateUserReference(e,t){e!=null&&(this.userChannelReferences[e.id]||(this.userChannelReferences[e.id]={}),this.userChannelReferences[e.id][t]=!0)}deleteAllChannelReference(e){for(let t in this.userChannelReferences)delete this.userChannelReferences[t][e]}};var Gp=Re(qp());var _g=n=>n.code!==void 0,yg=n=>n.error!==void 0,Xn=class{client;connectionOpen;consecutiveFailures;pingInterval;healthCheckTimeoutRef;isConnecting;isDisconnected;isHealthy;isResolved;lastEvent;connectionCheckTimeout;connectionCheckTimeoutRef;rejectPromise;requestID;resolvePromise;totalFailures;ws;wsID;constructor({client:e}){this.client=e,this.consecutiveFailures=0,this.totalFailures=0,this.isConnecting=!1,this.isDisconnected=!1,this.isResolved=!1,this.isHealthy=!1,this.wsID=1,this.lastEvent=null,this.pingInterval=25*1e3,this.connectionCheckTimeout=this.pingInterval+10*1e3,jl(this.onlineStatusChanged)}_log(e,t={},s="info"){this.client.logger(s,"connection:"+e,{tags:["connection"],...t})}setClient(e){this.client=e}async connect(e=15e3){if(this.isConnecting)throw Error("You've called connect twice, can only attempt 1 connection at the time");this.isDisconnected=!1;try{let t=await this._connect();this.consecutiveFailures=0,this._log(`connect() - Established ws connection with healthcheck: ${t}`)}catch(t){if(this.isHealthy=!1,this.consecutiveFailures+=1,t.code===mt.TOKEN_EXPIRED)this._log("connect() - WS failure due to expired token");else if(!t.isWSFailure)throw new Error(JSON.stringify({code:t.code,StatusCode:t.StatusCode,message:t.message,isWSFailure:t.isWSFailure}))}return await this._waitForHealthy(e)}async _waitForHealthy(e=15e3){return Promise.race([(async()=>{for(let s=0;s<=e;s+=50)try{return await this.connectionOpen}catch(i){if(s===e)throw new Error(JSON.stringify({code:i.code,StatusCode:i.StatusCode,message:i.message,isWSFailure:i.isWSFailure}));await on(50)}})(),(async()=>{throw await on(e),this.isConnecting=!1,new Error(JSON.stringify({code:"",StatusCode:"",message:"initial WS connection could not be established",isWSFailure:!0}))})()])}_buildUrl=()=>{let e=encodeURIComponent(this.client._buildWSPayload(this.requestID)),t=this.client.tokenManager.getToken(),s=`${this.client.wsBaseURL}/connect?json=${e}&api_key=${this.client.apiKey}&authorization=${t}&stream-auth-type=${this.client.getAuthType()}&X-Stream-Client=${this.client.getUserAgent()}`;return s=encodeURI(s),s};disconnect(e){this._log(`disconnect() - Closing the websocket connection for wsID ${this.wsID}`),this.wsID+=1,this.isConnecting=!1,this.isDisconnected=!0,this.healthCheckTimeoutRef&&clearInterval(this.healthCheckTimeoutRef),this.connectionCheckTimeoutRef&&clearInterval(this.connectionCheckTimeoutRef),Nl(this.onlineStatusChanged),this.isHealthy=!1,this.ws&&this.ws.removeAllListeners&&this.ws.removeAllListeners();let t,{ws:s}=this;return s&&s.close&&s.readyState===s.OPEN?(t=new Promise(i=>{let a=r=>{this._log(`disconnect() - resolving isClosedPromise ${r?"with":"without"} close frame`,{event:r}),i()};s.onclose=a,setTimeout(a,e??1e3)}),this._log("disconnect() - Manually closed connection by calling client.disconnect()"),s.close(mt.WS_CLOSED_SUCCESS,"Manually closed connection by calling client.disconnect()")):(this._log("disconnect() - ws connection doesn't exist or it is already closed."),t=Promise.resolve()),delete this.ws,t}async _connect(){if(this.isConnecting)return;this.isConnecting=!0,this.requestID=Ue();let e=!1;try{this._log("_connect() - waiting for token"),await this.client.tokenManager.tokenReady(),e=!0}catch{}try{this._setupConnectionPromise();let t=this._buildUrl();this._log(`_connect() - Connecting to ${t}`,{wsURL:t,requestID:this.requestID}),this.ws=new Gp.default(t),this.ws.onopen=this.onopen.bind(this,this.wsID),this.ws.onclose=this.onclose.bind(this,this.wsID),this.ws.onerror=this.onerror.bind(this,this.wsID),this.ws.onmessage=this.onmessage.bind(this,this.wsID);let s=await this.connectionOpen;if(this.isConnecting=!1,s)return s}catch(t){throw this.isConnecting=!1,this._log("_connect() - Error - ",t),t}}async _reconnect(e={}){if(this._log("_reconnect() - Initiating the reconnect"),this.isConnecting||this.isHealthy){this._log("_reconnect() - Abort (1) since already connecting or healthy");return}let t=e.interval;if(t||(t=js(this.consecutiveFailures)),await on(t),this.isConnecting||this.isHealthy){this._log("_reconnect() - Abort (2) since already connecting or healthy");return}if(this.isDisconnected){this._log("_reconnect() - Abort (3) since disconnect() is called");return}this._log("_reconnect() - Destroying current WS connection"),this._destroyCurrentWSConnection();try{await this._connect(),this._log("_reconnect() - Waiting for recoverCallBack"),await this.client.recoverState(),this._log("_reconnect() - Finished recoverCallBack"),this.consecutiveFailures=0}catch(s){this.isHealthy=!1,this.consecutiveFailures+=1,s.isWSFailure&&(this._log("_reconnect() - WS failure, so going to try to reconnect"),this._reconnect())}this._log("_reconnect() - == END ==")}onlineStatusChanged=e=>{e.type==="offline"?(this._log("onlineStatusChanged() - Status changing to offline"),this._setHealth(!1)):e.type==="online"&&(this._log(`onlineStatusChanged() - Status changing to online. isHealthy: ${this.isHealthy}`),this.isHealthy||this._reconnect({interval:10}))};onopen=e=>{this.wsID===e&&this._log("onopen() - onopen callback",{wsID:e})};onmessage=(e,t)=>{if(this.wsID!==e)return;this._log("onmessage() - onmessage callback",{event:t,wsID:e});let s=typeof t.data=="string"?JSON.parse(t.data):null;if(!this.isResolved&&s){if(this.isResolved=!0,s.error){this.rejectPromise?.(this._errorFromWSEvent(s,!1));return}this.resolvePromise?.(s),this._setHealth(!0)}this.lastEvent=new Date,s&&s.type==="health.check"&&this.scheduleNextPing(),this.client.handleEvent(t),this.scheduleConnectionCheck()};onclose=(e,t)=>{if(this.wsID===e)if(this._log("onclose() - onclose callback - "+t.code,{event:t,wsID:e}),t.code===mt.WS_CLOSED_SUCCESS){let s=new Error(`WS connection reject with error ${t.reason}`);s.reason=t.reason,s.code=t.code,s.wasClean=t.wasClean,s.target=t.target,this.rejectPromise?.(s),this._log(`onclose() - WS connection reject with error ${t.reason}`,{event:t})}else this.consecutiveFailures+=1,this.totalFailures+=1,this._setHealth(!1),this.isConnecting=!1,this.rejectPromise?.(this._errorFromWSEvent(t)),this._log("onclose() - WS connection closed. Calling reconnect ...",{event:t}),this._reconnect()};onerror=(e,t)=>{this.wsID===e&&(this.consecutiveFailures+=1,this.totalFailures+=1,this._setHealth(!1),this.isConnecting=!1,this.rejectPromise?.(this._errorFromWSEvent(t)),this._log("onerror() - WS connection resulted into error",{event:t}),this._reconnect())};_setHealth=e=>{if(e!==this.isHealthy){if(this.isHealthy=e,this.isHealthy){this.client.dispatchEvent({type:"connection.changed",online:this.isHealthy});return}setTimeout(()=>{this.isHealthy||this.client.dispatchEvent({type:"connection.changed",online:this.isHealthy})},1e3)}};_errorFromWSEvent=(e,t=!0)=>{let s,i,a;_g(e)&&(s=e.code,i="unknown",a=e.reason),yg(e)&&(s=e.error.code,i=e.error.StatusCode,a=e.error.message),this._log(`_errorFromWSEvent() - WS failed with code ${s}`,{event:e},"warn");let r=new Error(`WS failed with code ${s} and reason - ${a}`);return r.code=s,r.StatusCode=i,r.isWSFailure=t,r};_destroyCurrentWSConnection(){this.wsID+=1;try{this?.ws?.removeAllListeners(),this?.ws?.close()}catch{}}_setupConnectionPromise=()=>{this.isResolved=!1,this.connectionOpen=new Promise((e,t)=>{this.resolvePromise=e,this.rejectPromise=t})};scheduleNextPing=()=>{this.healthCheckTimeoutRef&&clearTimeout(this.healthCheckTimeoutRef),this.healthCheckTimeoutRef=setTimeout(()=>{let e=[{type:"health.check",client_id:this.client.clientID}];try{this.ws?.send(JSON.stringify(e))}catch{}},this.pingInterval)};scheduleConnectionCheck=()=>{this.connectionCheckTimeoutRef&&clearTimeout(this.connectionCheckTimeoutRef),this.connectionCheckTimeoutRef=setTimeout(()=>{let e=new Date;this.lastEvent&&e.getTime()-this.lastEvent.getTime()>this.connectionCheckTimeout&&(this._log("scheduleConnectionCheck - going to reconnect"),this._setHealth(!1),this._reconnect())},this.connectionCheckTimeout)}};var Qn=class{loadTokenPromise;token;user;constructor(){this.loadTokenPromise=null}setTokenOrProvider=async(e,t)=>{this.user=t,typeof e=="string"&&(this.token=e),this.loadTokenPromise=Promise.resolve(this.token)};reset=()=>{this.token=void 0,this.user=void 0,this.loadTokenPromise=null};tokenReady=()=>this.loadTokenPromise;getToken=()=>this.token};function Hs(n){return!n.status||n.status<200||300<=n.status}var Js=Re(Bp());var Mt=class extends Error{code;response;status},Va=(c=>(c.CREATE_CALL="create-call",c.ACCEPT_CALL="accept-call",c.SIGNAL_CALL="signal-call",c.CONNECT_CALL="connect-call",c.HEALTH_CALL="health-call",c.END_CALL="end-call",c.REJECT_CALL="reject-call",c.MISS_CALL="miss-call",c.UPGRADE_CALL="upgrade-call",c))(Va||{}),Ha=(i=>(i.RINGING="ringing",i.ENDED="ended",i.CONNECTED="connected",i.ERROR="error",i))(Ha||{}),Ka=(u=>(u[u.VIDEO_CONFIG=0]="VIDEO_CONFIG",u[u.AUDIO_CONFIG=1]="AUDIO_CONFIG",u[u.VIDEO_KEY=2]="VIDEO_KEY",u[u.VIDEO_DELTA=3]="VIDEO_DELTA",u[u.AUDIO=4]="AUDIO",u[u.ORIENTATION=5]="ORIENTATION",u[u.CONNECTED=6]="CONNECTED",u[u.TRANSCEIVER_STATE=7]="TRANSCEIVER_STATE",u[u.REQUEST_CONFIG=8]="REQUEST_CONFIG",u[u.REQUEST_KEY_FRAME=9]="REQUEST_KEY_FRAME",u[u.END_CALL=10]="END_CALL",u))(Ka||{});function wg(n){return typeof n=="string"||n instanceof String}var Ja=class n{static _instance;activeChannels;axiosInstance;baseURL;userBaseURL;browser;cleaningIntervalRef;clientID;apiKey;projectId;listeners;logger;recoverStateOnReconnect;node;options;setUserPromise;state;tokenManager;user;userAgent;userID;wsBaseURL;wsConnection;wsPromise;consecutiveFailures;defaultWSTimeout;eventSource=null;constructor(e,t,s,i){this.apiKey=e,this.projectId=t,this.listeners={},this.state=new ln;let a=i||{};this.browser=typeof a.browser<"u"?a.browser:typeof window<"u",this.node=!this.browser,this.options={withCredentials:!1,warmUp:!1,recoverStateOnReconnect:!0,...a},this.node&&!this.options.httpsAgent&&(this.options.httpsAgent=new yt.Agent({keepAlive:!0,keepAliveMsecs:3e3})),this.axiosInstance=rn.create(this.options),this.setBaseURL(s),this.wsConnection=null,this.wsPromise=null,this.setUserPromise=null,this.activeChannels={},this.tokenManager=new Qn,this.consecutiveFailures=0,this.defaultWSTimeout=15e3,this.axiosInstance.defaults.paramsSerializer=ql,this.logger=Ms(a.logger)?a.logger:()=>null,this.recoverStateOnReconnect=this.options.recoverStateOnReconnect}static getInstance(e,t,s,i){return n._instance||(n._instance=new n(e,t,s,i)),n._instance}async refreshNewToken(e){return await this.post(this.userBaseURL+"/refresh_token",{refresh_token:e})}getAuthType(){return"jwt"}setBaseURL(e){this.baseURL=e,this.userBaseURL=this.options.userBaseURL||e+"/uss/v1",this.wsBaseURL=this.baseURL.replace("http","ws").replace(":3030",":8800")}async getExternalAuthToken(e,t){let s={apikey:this.apiKey,name:e.name};e.avatar&&(s.avatar=e.avatar);let i=this.userBaseURL+"/get_token/external_auth",a={"Content-Type":"application/json"};if(t){let r=typeof t=="string"&&t.startsWith("Bearer ")?t:`Bearer ${t}`;a.Authorization=r}try{return(await this.axiosInstance.get(i,{params:s,headers:a})).data}catch(r){let o="Failed to fetch external auth token";throw r.response&&r.response.data?o=r.response.data.message||JSON.stringify(r.response.data):r.message&&(o=r.message),new Error(o)}}connectUser=async(e,t,s)=>{if(this.logger("info","client:connectUser() - started",{tags:["connection","client"]}),!e.id)throw new Error('The "id" field on the user is missing');let i=e,a=t;if(s){let l=await this.getExternalAuthToken(e,t);a=l.token,i={...e,id:l.user_id}}if(this.userID===i.id&&this.setUserPromise)return console.warn("Consecutive calls to connectUser is detected, ideally you should only call this function once in your app."),this.setUserPromise;if(this.userID)throw new Error("Use client.disconnect() before trying to connect as a different user. connectUser was called twice.");this.node&&!this.options.allowServerSideConnect&&console.warn('Please do not use connectUser server side. connectUser impacts MAU and concurrent connection usage and thus your bill. If you have a valid use-case, add "allowServerSideConnect: true" to the client options to disable this warning.'),this.userID=i.id;let r=this._setToken(i,a);this._setUser(i),this.state.updateUser({id:i.id,name:i?.name||i.id,avatar:i?.avatar||""});let o=this.openConnection();this.setUserPromise=Promise.all([r,o]).then(l=>l[1]);try{let l=await this.setUserPromise;return await this.connectToSSE(),l}catch(l){throw this.disconnectUser(),l}};setUser=this.connectUser;_setToken=(e,t)=>this.tokenManager.setTokenOrProvider(t,e);_setUser(e){this.user={...e},this.userID=e.id}closeConnection=async e=>(this.cleaningIntervalRef!=null&&(clearInterval(this.cleaningIntervalRef),this.cleaningIntervalRef=void 0),await this.wsConnection?.disconnect(e),Promise.resolve());openConnection=async()=>{if(!this.userID)throw Error("User is not set on client, use client.connectUser instead");return this.wsConnection?.isConnecting&&this.wsPromise?(this.logger("info","client:openConnection() - connection already in progress",{tags:["connection","client"]}),this.wsPromise):this.wsConnection?.isHealthy?(this.logger("info","client:openConnection() - openConnection called twice, healthy connection already exists",{tags:["connection","client"]}),Promise.resolve()):(this.clientID=`${this.userID}--${Ue()}`,this.wsPromise=this.connect(),this._startCleaning(),this.wsPromise)};_setupConnection=this.openConnection;disconnectUser=async e=>{this.logger("info","client:disconnect() - Disconnecting the client",{tags:["connection","client"]}),delete this.user,delete this.userID;let t=this.closeConnection(e);for(let s of Object.values(this.activeChannels))s._disconnect();return this.activeChannels={},this.state=new ln,setTimeout(this.tokenManager.reset),t};disconnect=this.disconnectUser;on(e,t){let s=t?e:"all",i=t||e;return s in this.listeners||(this.listeners[s]=[]),this.logger("info",`Attaching listener for ${s} event`,{tags:["event","client"]}),this.listeners[s].push(i),{unsubscribe:()=>{this.logger("info",`Removing listener for ${s} event`,{tags:["event","client"]}),this.listeners[s]=this.listeners[s].filter(a=>a!==i)}}}off(e,t){let s=t?e:"all",i=t||e;s in this.listeners||(this.listeners[s]=[]),this.logger("info",`Removing listener for ${s} event`,{tags:["event","client"]}),this.listeners[s]=this.listeners[s].filter(a=>a!==i)}_logApiRequest(e,t,s,i){this.logger("info",`client: ${e} - Request - ${t}- ${JSON.stringify(s)} - ${JSON.stringify(i.params)}`,{tags:["api","api_request","client"],url:t,payload:s,config:i})}_logApiResponse(e,t,s){this.logger("info",`client:${e} - Response - url: ${t} > status ${s.status}`,{tags:["api","api_response","client"],url:t,response:s})}_logApiError(e,t,s,i){this.logger("error",`client:${e} - Error: ${JSON.stringify(s)} - url: ${t} - options: ${JSON.stringify(i)}`,{tags:["api","api_response","client"],url:t,error:s})}doAxiosRequest=async(e,t,s,i={})=>{await this.tokenManager.tokenReady();let a=this._enrichAxiosOptions(i);try{let r;switch(this._logApiRequest(e,t,s,a),e){case"get":r=await this.axiosInstance.get(t,a);break;case"delete":r=await this.axiosInstance.delete(t,a);break;case"post":r=await this.axiosInstance.post(t,s,a);break;case"postForm":r=await this.axiosInstance.postForm(t,s,a);break;case"put":r=await this.axiosInstance.put(t,s,a);break;case"patch":r=await this.axiosInstance.patch(t,s,a);break;case"options":r=await this.axiosInstance.options(t,a);break;default:throw new Error("Invalid request type")}return this._logApiResponse(e,t,r),this.consecutiveFailures=0,this.handleResponse(r)}catch(r){if(r.client_request_id=a.headers?.["x-client-request-id"],this._logApiError(e,t,r,i),this.consecutiveFailures+=1,r.response)return this.handleResponse(r.response);throw r}};get(e,t){return this.doAxiosRequest("get",e,null,{params:t})}put(e,t){return this.doAxiosRequest("put",e,t)}post(e,t,s){return this.doAxiosRequest("post",e,t,{params:s})}patch(e,t){return this.doAxiosRequest("patch",e,t)}delete(e,t){return this.doAxiosRequest("delete",e,null,{params:t})}sendFile(e,t,s,i,a){let r=Ml(t,s,i||"multipart/form-data");return a!=null&&r.append("user",JSON.stringify(a)),this.doAxiosRequest("postForm",e,r,{headers:r.getHeaders?r.getHeaders():{},config:{timeout:0,maxContentLength:1/0,maxBodyLength:1/0}})}errorFromResponse(e){let t;return t=new Mt(`ErmisChat error HTTP code: ${e.status}`),e.data&&e.data.code&&(t=new Error(`ErmisChat error code ${e.data.code}: ${e.data.message}`),t.code=e.data.code),t.response=e,t.status=e.status,t}handleResponse(e){let t=e.data;if(Hs(e))throw this.errorFromResponse(e);return t}dispatchEvent=e=>{if(e.received_at||(e.received_at=new Date),e.type==="channel.created"||e.type==="channel.topic.created")this._handleChannelCreatedEvent(e).then(()=>{this._afterDispatchEvent(e)});else{let t=this._handleClientEvent(e),s=e.cid,i=s?this.activeChannels[s]:void 0;i&&i._handleChannelEvent(e),this._callClientListeners(e),i&&i._callChannelListeners(e),t.forEach(a=>a())}};_afterDispatchEvent(e){let t=this._handleClientEvent(e),s=e.cid,i=s?this.activeChannels[s]:void 0;i&&i._handleChannelEvent(e),this._callClientListeners(e),i&&i._callChannelListeners(e),t.forEach(a=>a())}async _handleChannelCreatedEvent(e){let t=e.channel?.members||[];await Nn(this,t);let s=Object.values(this.state.users),i=H(t,s),a=e.channel_type==="messaging"?Dt(i,this.userID||""):e.channel?.name,r={...e.channel,members:i,name:a},o={channel:r,members:i,messages:[],pinned_messages:[]},l=this.channel(e.channel_type||"",e.channel_id||"");l.data=r,l._initializeState(o,"latest")}handleEvent=e=>{let t=e.data,s=JSON.parse(t);this.dispatchEvent(s)};_updateMemberWatcherReferences=e=>{let t=this.state.userChannelReferences[e.id]||{};for(let s in t){let i=this.activeChannels[s];i?.state&&(i.state.members[e.id]&&(i.state.members[e.id].user=e),i.state.watchers[e.id]&&(i.state.watchers[e.id]=e),i.state.read[e.id]&&(i.state.read[e.id].user=e))}};_updateUserReferences=this._updateMemberWatcherReferences;_updateUserMessageReferences=e=>{let t=this.state.userChannelReferences[e.id]||{};for(let s in t){let i=this.activeChannels[s];if(!i)continue;i.state?.updateUserMessages(e)}};_deleteUserMessageReference=(e,t=!1)=>{let s=this.state.userChannelReferences[e.id]||{};for(let i in s)this.activeChannels[i].state?.deleteUserMessages(e,t)};_handleClientEvent(e){let t=this,s=[];if(this.logger("info",`client:_handleClientEvent - Received event of type { ${e.type} }`,{tags:["event","client"],event:e}),e.type==="health.check"&&e.me,(e.type==="channel.deleted"||e.type==="notification.channel_deleted")&&e.cid){t.state.deleteAllChannelReference(e.cid),this.activeChannels[e.cid]?._disconnect(),s.push(()=>{e.cid&&delete this.activeChannels[e.cid]});for(let i of Object.values(this.activeChannels))i.type==="team"&&i.state.topics?.some(a=>a.cid===e.cid)&&(i.state.topics=i.state.topics.filter(a=>a.cid!==e.cid))}return e.type==="notification.invite_rejected"&&e.member?.user_id===this.userID&&e.cid&&(t.state.deleteAllChannelReference(e.cid),this.activeChannels[e.cid]?._disconnect(),s.push(()=>{e.cid&&delete this.activeChannels[e.cid]})),e.type,e.type==="member.added"&&e.member?.user_id===this.userID&&this.channel(e.channel_type||"",e.channel_id||"").watch().catch(a=>{this.logger("error","Failed to watch channel after member.added",{err:a,event:e})}),e.type==="message.new"&&e.channel_type==="topic"&&s.push(()=>{let i=e.parent_cid||e.channel?.parent_cid;if(i&&this.activeChannels[i]){let a=this.activeChannels[i];a.state.topics&&(a.state.topics.sort((r,o)=>{let l=r.state?.latestMessages?.[r.state.latestMessages.length-1]?.created_at,c=o.state?.latestMessages?.[o.state.latestMessages.length-1]?.created_at,p=l?new Date(l).getTime():0;return(c?new Date(c).getTime():0)-p}),a._callChannelListeners({...e,type:"channel.updated",channel:a.data}))}}),e.type==="channel.topic.updated"&&s.push(()=>{let i=e.parent_cid||e.channel?.parent_cid;if(i&&this.activeChannels[i]){let a=this.activeChannels[i];if(a.state?.topics&&e.channel){let r=a.state.topics.findIndex(o=>o.cid===e.cid||o.channel?.cid===e.cid);if(r!==-1){let o=a.state.topics[r];o.data?o.data={...o.data,...e.channel}:o.channel?o.channel={...o.channel,...e.channel}:Object.assign(o,e.channel)}a._callChannelListeners({...e,type:"channel.updated",channel:a.data})}}if(e.cid&&this.activeChannels[e.cid]){let a=this.activeChannels[e.cid];e.channel&&(a.data={...a.data,...e.channel},a._callChannelListeners({...e,type:"channel.updated",channel:a.data}))}}),(e.type==="channel.topic.closed"||e.type==="channel.topic.reopen")&&s.push(()=>{let i=e.type==="channel.topic.closed",a=e.parent_cid;if(a&&this.activeChannels[a]){let r=this.activeChannels[a];if(r.state?.topics){let o=r.state.topics.findIndex(l=>l.cid===e.cid||l.channel?.cid===e.cid);if(o!==-1){let l=r.state.topics[o];l.data?l.data.is_closed_topic=i:l.channel?l.channel.is_closed_topic=i:l.is_closed_topic=i}r._callChannelListeners({...e,type:"channel.updated",channel:r.data})}}if(e.cid&&this.activeChannels[e.cid]){let r=this.activeChannels[e.cid];r.data&&(r.data.is_closed_topic=i),r._callChannelListeners({...e,type:"channel.updated",channel:r.data})}}),e.type==="connection.recovered"&&s.push(()=>{Object.values(this.activeChannels).forEach(i=>{if(!i.state?.messages)return;i.state.messages.filter(r=>r.status==="failed_offline"&&r.user?.id===this.userID&&(!r.attachments||r.attachments.length===0)).forEach(r=>{r.id&&i.retryMessage(r.id).catch(o=>{this.logger("error",`Failed to auto-resend offline message ${r.id}`,{tags:["offline","retry"],err:o})})})})}),s}_callClientListeners=e=>{let t=this,s=[];t.listeners.all&&s.push(...t.listeners.all),t.listeners[e.type]&&s.push(...t.listeners[e.type]);for(let i of s)i(e)};recoverState=async()=>{this.logger("info","client:recoverState() - Start of recoverState",{tags:["connection"]});let e=Object.keys(this.activeChannels);if(e.length&&this.recoverStateOnReconnect){this.logger("info",`client:recoverState() - Start the querying of ${e.length} channels`,{tags:["connection","client"]});let t={type:["messaging","team"]},s=[],i={message_limit:25};await this.queryChannels(t,s,i),this.logger("info","client:recoverState() - Querying channels finished",{tags:["connection","client"]}),this.dispatchEvent({type:"connection.recovered"})}else this.dispatchEvent({type:"connection.recovered"});this.wsPromise=Promise.resolve(),this.setUserPromise=Promise.resolve()};async connect(){if(!this.userID||!this.user)throw Error("Call connectUser before starting the connection");if(!this.wsBaseURL)throw Error("Websocket base url not set");if(!this.clientID)throw Error("clientID is not set");this.options.wsConnection&&this.node?(this.options.wsConnection.setClient(this),this.wsConnection=this.options.wsConnection):this.wsConnection=new Xn({client:this});try{return await this.wsConnection.connect(this.defaultWSTimeout)}catch(e){throw e}}async connectToSSE(e){if(this.eventSource){this.logger("info","client:connectToSSE() - SSE connection already established",{});return}let t=this._getToken();t?.startsWith("Bearer ")||(t=`Bearer ${t}`);let s={method:"GET",Authorization:t};this.eventSource=new Js.EventSourcePolyfill(this.userBaseURL+"/sse/subscribe",{headers:s,heartbeatTimeout:6e4}),this.eventSource.onopen=()=>{this.logger("info","client:connectToSSE() - SSE connection established",{})},this.eventSource.onmessage=i=>{let a=JSON.parse(i.data);if(this.logger("info",`client:connectToSSE() - SSE message received event : ${JSON.stringify(a)}`,{event:i}),a.type==="AccountUserChainProjects"){let r={name:a.name,id:a.id,avatar:a.avatar,about_me:a.about_me,project_id:a.project_id};this.user?.id===r.id&&(this.user={...this.user,...r}),this.state.updateUser(r);let o={id:r.id,name:r.name?r.name:r.id,avatar:r?.avatar||""};this._updateMemberWatcherReferences(o),this._updateUserMessageReferences(o),Object.values(this.activeChannels).forEach(l=>{if(l.data?.type==="messaging"&&Object.keys(l.state.members).length===2){let c=Object.values(l.state.members).find(p=>p.user?.id!==this.userID);c&&c.user?.id===r.id&&(l.data.name=r.name||r.id,l.data.image=r.avatar||"")}}),e&&e(a)}},this.eventSource.onerror=i=>{this.logger("error",`client:connectToSSE() - SSE connection error : ${JSON.stringify(i.data)} `,{event:i}),i.status===401?(this.logger("error","client:connectToSSE() - Unauthorized (401). Aborting the connection.",{}),this.disconnectFromSSE()):(this.eventSource?.readyState===Js.EventSourcePolyfill.CLOSED||this.eventSource?.readyState===Js.EventSourcePolyfill.CONNECTING)&&(this.eventSource.close(),setTimeout(()=>{this.logger("info","client:connectToSSE() - Reconnecting to SSE",{}),this.connectToSSE(e)},3e3))}}async disconnectFromSSE(){this.eventSource?(this.eventSource.close(),this.eventSource=null,this.logger("info","client:disconnectFromSSE() - SSE connection closed",{})):this.logger("info","client:disconnectFromSSE() - SSE connection already closed",{})}async queryUsers(e,t){let s={presence:!1};await this.wsPromise;let i=this.projectId,a=await this.get(this.userBaseURL+"/users",{project_id:i,page:t,page_size:e});return this.state.updateUsers(a.data),a}async queryUser(e){let t=this.projectId,s=await this.get(this.userBaseURL+"/users/"+e,{project_id:t});return this.state.updateUser(s),s}async getBatchUsers(e,t,s){let i=this.projectId,a=await this.post(this.userBaseURL+"/users/batch?page=1&page_size=10000",{users:e,project_id:i},{page:t,page_size:s});return this.state.updateUsers(a.data),a.data||[]}async searchUsers(e,t,s){let i=this.projectId;return await this.post(this.userBaseURL+"/users/search",void 0,{page:e,page_size:t,name:s,project_id:i})}async queryContacts(){let e=this.projectId,s=(await this.post(this.baseURL+"/contacts/list",{project_id:e})).project_id_user_ids[e],i=[],a=[];return s.forEach(r=>{let o=r.other_id,l=this.state.users[o],c=l||{id:o};switch(r.relation_status){case"blocked":a.push(c);break;case"normal":i.push(c);break;default:}}),{contact_users:i,block_users:a}}_updateProjectID(e){this.projectId=e}async uploadAvatar(e){let t=new FormData;t.append("avatar",e);let s=await this.post(this.userBaseURL+"/users/upload",t,{headers:{"Content-Type":"multipart/form-data"}});if(this.user){this.user.avatar=s.avatar;let i={...this.user,avatar:s.avatar};this.state.updateUser(i)}return s}async updateProfile(e){let t=await this.patch(this.userBaseURL+"/users/update",e);return this.user=t,this.state.updateUser(t),t}async queryChannels(e,t=[],s={},i={}){await this.wsPromise;let a=this.projectId,r={filter_conditions:{...e,project_id:a},sort:t,...s},o=await this.post(this.baseURL+"/channels",r);o.channels.sort((m,f)=>{let g=Ot(m.messages);if(m.channel.type==="team"&&Array.isArray(m.topics))for(let _ of m.topics)g=Math.max(g,Ot(_.messages));let v=Ot(f.messages);if(f.channel.type==="team"&&Array.isArray(f.topics))for(let _ of f.topics)v=Math.max(v,Ot(_.messages));return v-g});let l=Array.from(new Set(o.channels.flatMap(m=>(m.channel.members||[]).map(f=>f.user.id))))||[],c=e.parent_cid?Object.values(this.state.users):await this.getBatchUsers(l);o.channels.forEach(m=>{m.channel.members=H(m.channel.members,c),m.messages=H(m.messages,c),m.read=H(m.read||[],c),m.channel.name=m.channel.type==="messaging"?Dt(m.channel.members,this.userID||""):m.channel.name,m.channel.image=m.channel.type==="messaging"?jn(m.channel.members,this.userID||""):m.channel.image,m.channel.type==="team"&&Array.isArray(m.topics)&&m.topics.sort((f,g)=>{let v=Ot(f.messages);return Ot(g.messages)-v}),m.pinned_messages&&(m.pinned_messages=H(m.pinned_messages||[],c))});let{channels:p,userIds:u}=this.hydrateChannels(o.channels,i);return console.log("---channels---",p),p}hydrateChannels(e=[],t={}){let{skipInitialization:s,offlineMode:i=!1}=t,a=[],r=[];for(let o of e){let l=this.channel(o.channel.type,o.channel.id);l.data={...o.channel,is_pinned:o.is_pinned||!1},l.offlineMode=i,l.initialized=!i,s===void 0?l._initializeState(o,"latest",c=>{r.includes(c)||r.push(c)}):s.includes(o.channel.id)||(l.state.clearMessages(),l._initializeState(o,"latest",c=>{r.includes(c)||r.push(c)})),a.push(l)}return{channels:a,userIds:r}}async searchPublicChannel(e,t=0,s=25){let i=this.projectId;return await this.post(this.baseURL+"/channels/public/search",{project_id:i,search_term:e,limit:s,offset:t})}async pinChannel(e,t){return await this.post(this.baseURL+`/channels/${e}/${t}/pin`)}async unpinChannel(e,t){return await this.post(this.baseURL+`/channels/${e}/${t}/unpin`)}channel(e,t,s){if(!this.userID)throw Error("Call connectUser before creating a channel");if(~e.indexOf(":"))throw Error(`Invalid channel group ${e}, can't contain the : character`);let i,a=s||{};return typeof t=="string"?i=t:typeof t=="object"&&t!==null&&(a=t),this.getChannelById(e,i,a)}getChannelById=(e,t,s)=>{let i=`${e}:${t||""}`;if(i in this.activeChannels&&!this.activeChannels[i].disconnected){let r=this.activeChannels[i];return Object.keys(s).length>0&&(r.data=s,r._data=s),r}let a=new cn(this,e,t,s);return this.activeChannels[a.cid]=a,a};getChannel=(e,t)=>{let s=Ue(),i=`${this.projectId}:${s}`,a=`${e}:${i}`;if(a in this.activeChannels&&!this.activeChannels[a].disconnected){let o=this.activeChannels[a];return Object.keys(t).length>0&&(o.data=t,o._data=t),o}let r=new cn(this,e,i,t);return this.activeChannels[r.cid]=r,r};async createQuickChannel(e){if(!this.userID)throw Error("Call connectUser before creating a channel");let t=new Date,s=new Intl.DateTimeFormat("en-US",{month:"short",day:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).format(t),i={name:e||`Quick Channel - ${s}`,members:[this.userID],public:!0},a=this.channel("meeting",i);return await a.create(),a}async joinQuickChannel(e){if(!this.userID)throw Error("Call connectUser before joining a channel");let t=this.channel("meeting",e);return await t.watch(),t.state.members&&t.state.members[this.userID]||(await t.acceptInvite("join"),await t.watch()),t}_normalizeExpiration(e){let t=null;if(typeof e=="number"){let s=new Date;s.setSeconds(s.getSeconds()+e),t=s.toISOString()}else wg(e)?t=e:e instanceof Date&&(t=e.toISOString());return t}getUserAgent(){return this.userAgent||`ermis-chat-sdk-javascript-client-${this.node?"node":"browser"}-1.0.7`}setUserAgent(e){this.userAgent=e}_enrichAxiosOptions(e={params:{},headers:{},config:{}}){let t=this._getToken();t?.startsWith("Bearer ")||(t=`Bearer ${t}`);let s=t?{Authorization:t}:void 0;e.headers?.["x-client-request-id"]||(e.headers={...e.headers,"x-client-request-id":Ue()});let{params:i,headers:a,...r}=this.options.axiosRequestConfig||{};return{params:{...e.params,...i||{}},headers:{...s,"stream-auth-type":this.getAuthType(),"X-Stream-Client":this.getUserAgent(),...e.headers,...a||{}},...e.config,...r||{}}}_getToken(){return this.tokenManager?this.tokenManager.getToken():null}_startCleaning(){let e=this;this.cleaningIntervalRef==null&&(this.cleaningIntervalRef=setInterval(()=>{for(let t of Object.values(e.activeChannels))t.clean()},500))}_buildWSPayload=e=>JSON.stringify({user_id:this.userID,user_details:this.user,client_request_id:e})};var Cg={"channel.created":!0,"channel.deleted":!0,"channel.truncate":!0,"channel.updated":!0,"channel.pinned":!0,"channel.unpinned":!0,"health.check":!0,"member.added":!0,"member.removed":!0,"member.updated":!0,"member.joined":!0,"member.promoted":!0,"member.demoted":!0,"member.banned":!0,"member.unbanned":!0,"member.blocked":!0,"member.unblocked":!0,"message.deleted":!0,"message.deleted_for_me":!0,"message.new":!0,"message.read":!0,"message.updated":!0,"message.pinned":!0,"message.unpinned":!0,"notification.channel_deleted":!0,"notification.invite_accepted":!0,"notification.invite_rejected":!0,"notification.invite_messaging_skipped":!0,"pollchoice.new":!0,"reaction.deleted":!0,"reaction.new":!0,"typing.start":!0,"typing.stop":!0,"user.watching.start":!0,"user.watching.stop":!0,"connection.changed":!0,"connection.recovered":!0,"capabilities.changed":!0,"channel.topic.disabled":!0,"channel.topic.enabled":!0,"channel.topic.created":!0,"channel.topic.closed":!0,"channel.topic.reopen":!0,"channel.topic.updated":!0};var b,es=null;function dn(){return(es===null||es.byteLength===0)&&(es=new Uint8Array(b.memory.buffer)),es}var Xs=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});Xs.decode();var Eg=2146435072,Xa=0;function Sg(n,e){return Xa+=e,Xa>=Eg&&(Xs=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}),Xs.decode(),Xa=e),Xs.decode(dn().subarray(n,n+e))}function _e(n,e){return n=n>>>0,Sg(n,e)}var lt=new Array(128).fill(void 0);lt.push(void 0,null,!0,!1);var ts=lt.length;function y(n){ts===lt.length&&lt.push(lt.length+1);let e=ts;return ts=lt[e],lt[e]=n,e}function h(n){return lt[n]}var xe=0,ns=new TextEncoder;"encodeInto"in ns||(ns.encodeInto=function(n,e){let t=ns.encode(n);return e.set(t),{read:n.length,written:t.length}});function Ze(n,e,t){if(t===void 0){let o=ns.encode(n),l=e(o.length,1)>>>0;return dn().subarray(l,l+o.length).set(o),xe=o.length,l}let s=n.length,i=e(s,1)>>>0,a=dn(),r=0;for(;r<s;r++){let o=n.charCodeAt(r);if(o>127)break;a[i+r]=o}if(r!==s){r!==0&&(n=n.slice(r)),i=t(i,s,s=r+n.length*3,1)>>>0;let o=dn().subarray(i+r,i+s),l=ns.encodeInto(n,o);r+=l.written,i=t(i,s,r,1)>>>0}return xe=r,i}var jt=null;function U(){return(jt===null||jt.buffer.detached===!0||jt.buffer.detached===void 0&&jt.buffer!==b.memory.buffer)&&(jt=new DataView(b.memory.buffer)),jt}function ie(n){return n==null}function Qa(n){let e=typeof n;if(e=="number"||e=="boolean"||n==null)return`${n}`;if(e=="string")return`"${n}"`;if(e=="symbol"){let i=n.description;return i==null?"Symbol":`Symbol(${i})`}if(e=="function"){let i=n.name;return typeof i=="string"&&i.length>0?`Function(${i})`:"Function"}if(Array.isArray(n)){let i=n.length,a="[";i>0&&(a+=Qa(n[0]));for(let r=1;r<i;r++)a+=", "+Qa(n[r]);return a+="]",a}let t=/\[object ([^\]]+)\]/.exec(toString.call(n)),s;if(t&&t.length>1)s=t[1];else return toString.call(n);if(s=="Object")try{return"Object("+JSON.stringify(n)+")"}catch{return"Object"}return n instanceof Error?`${n.name}: ${n.message}
21
+ ${n.stack}`:s}function K(n,e){try{return n.apply(this,e)}catch(t){b.__wbindgen_export3(y(t))}}function Rg(n){n<132||(lt[n]=ts,ts=n)}function J(n){let e=h(n);return Rg(n),e}function un(n,e){return n=n>>>0,dn().subarray(n/1,n/1+e)}var Qs=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>n.dtor(n.a,n.b));function Yn(n,e,t,s){let i={a:n,b:e,cnt:1,dtor:t},a=(...r)=>{i.cnt++;let o=i.a;i.a=0;try{return s(o,i.b,...r)}finally{i.a=o,a._wbg_cb_unref()}};return a._wbg_cb_unref=()=>{--i.cnt===0&&(i.dtor(i.a,i.b),i.a=0,Qs.unregister(i))},Qs.register(a,i,i),a}function Tg(n,e,t,s){let i={a:n,b:e,cnt:1,dtor:t},a=(...r)=>{i.cnt++;try{return s(i.a,i.b,...r)}finally{a._wbg_cb_unref()}};return a._wbg_cb_unref=()=>{--i.cnt===0&&(i.dtor(i.a,i.b),i.a=0,Qs.unregister(i))},Qs.register(a,i,i),a}function Zn(n,e){let t=e(n.length*1,1)>>>0;return dn().set(n,t/1),xe=n.length,t}function kg(n,e){b.__wasm_bindgen_func_elem_12858(n,e)}function Ag(n,e,t){b.__wasm_bindgen_func_elem_11688(n,e,y(t))}function Ig(n,e){b.__wasm_bindgen_func_elem_6230(n,e)}function Dg(n,e,t){b.__wasm_bindgen_func_elem_2287(n,e,y(t))}function Og(n,e,t){b.__wasm_bindgen_func_elem_12912(n,e,y(t))}function Ug(n,e){b.__wasm_bindgen_func_elem_5748(n,e)}function Lg(n,e,t,s){b.__wasm_bindgen_func_elem_14376(n,e,y(t),y(s))}var Fg=["blob","arraybuffer"],Pg=["bytes"],Mg=["default","no-store","reload","no-cache","force-cache","only-if-cached"],jg=["omit","same-origin","include"],Ng=["same-origin","no-cors","cors","navigate"],$p=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>b.__wbg_connectionstats_free(n>>>0,1)),Ys=class{__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,$p.unregister(this),e}free(){let e=this.__destroy_into_raw();b.__wbg_connectionstats_free(e,0)}get rtt_ms(){try{let s=b.__wbindgen_add_to_stack_pointer(-16);b.__wbg_get_connectionstats_rtt_ms(s,this.__wbg_ptr);var e=U().getInt32(s+0,!0),t=U().getFloat64(s+8,!0);return e===0?void 0:t}finally{b.__wbindgen_add_to_stack_pointer(16)}}set rtt_ms(e){b.__wbg_set_connectionstats_rtt_ms(this.__wbg_ptr,!ie(e),ie(e)?0:e)}get packet_loss(){try{let s=b.__wbindgen_add_to_stack_pointer(-16);b.__wbg_get_connectionstats_packet_loss(s,this.__wbg_ptr);var e=U().getInt32(s+0,!0),t=U().getFloat64(s+8,!0);return e===0?void 0:t}finally{b.__wbindgen_add_to_stack_pointer(16)}}set packet_loss(e){b.__wbg_set_connectionstats_packet_loss(this.__wbg_ptr,!ie(e),ie(e)?0:e)}constructor(e,t,s){var i=ie(e)?0:Ze(e,b.__wbindgen_export,b.__wbindgen_export2),a=xe;let r=b.connectionstats_new(i,a,!ie(t),ie(t)?0:t,!ie(s),ie(s)?0:s);return this.__wbg_ptr=r>>>0,$p.register(this,this.__wbg_ptr,this),this}get connection_type(){try{let s=b.__wbindgen_add_to_stack_pointer(-16);b.connectionstats_connection_type(s,this.__wbg_ptr);var e=U().getInt32(s+0,!0),t=U().getInt32(s+4,!0);let i;return e!==0&&(i=_e(e,t).slice(),b.__wbindgen_export4(e,t*1,1)),i}finally{b.__wbindgen_add_to_stack_pointer(16)}}set connection_type(e){var t=ie(e)?0:Ze(e,b.__wbindgen_export,b.__wbindgen_export2),s=xe;b.connectionstats_set_connection_type(this.__wbg_ptr,t,s)}};Symbol.dispose&&(Ys.prototype[Symbol.dispose]=Ys.prototype.free);var zp=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>b.__wbg_ermiscall_free(n>>>0,1)),mn=class{__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,zp.unregister(this),e}free(){let e=this.__destroy_into_raw();b.__wbg_ermiscall_free(e,0)}constructor(){let e=b.ermiscall_new();return this.__wbg_ptr=e>>>0,zp.register(this,this.__wbg_ptr,this),this}spawn(e,t){var s=ie(t)?0:Zn(t,b.__wbindgen_export),i=xe;let a=b.ermiscall_spawn(this.__wbg_ptr,y(e),s,i);return J(a)}getLocalEndpointAddr(){let e=b.ermiscall_getLocalEndpointAddr(this.__wbg_ptr);return J(e)}connect(e){let t=Ze(e,b.__wbindgen_export,b.__wbindgen_export2),s=xe,i=b.ermiscall_connect(this.__wbg_ptr,t,s);return J(i)}closeEndpoint(){let e=b.ermiscall_closeEndpoint(this.__wbg_ptr);return J(e)}closeConnection(){try{let s=b.__wbindgen_add_to_stack_pointer(-16);b.ermiscall_closeConnection(s,this.__wbg_ptr);var e=U().getInt32(s+0,!0),t=U().getInt32(s+4,!0);if(t)throw J(e)}finally{b.__wbindgen_add_to_stack_pointer(16)}}acceptConnection(){let e=b.ermiscall_acceptConnection(this.__wbg_ptr);return J(e)}sendControlFrame(e){try{let i=b.__wbindgen_add_to_stack_pointer(-16),a=Zn(e,b.__wbindgen_export),r=xe;b.ermiscall_sendControlFrame(i,this.__wbg_ptr,a,r);var t=U().getInt32(i+0,!0),s=U().getInt32(i+4,!0);if(s)throw J(t)}finally{b.__wbindgen_add_to_stack_pointer(16)}}sendAudioFrame(e){try{let i=b.__wbindgen_add_to_stack_pointer(-16),a=Zn(e,b.__wbindgen_export),r=xe;b.ermiscall_sendAudioFrame(i,this.__wbg_ptr,a,r);var t=U().getInt32(i+0,!0),s=U().getInt32(i+4,!0);if(s)throw J(t)}finally{b.__wbindgen_add_to_stack_pointer(16)}}sendFrame(e){try{let i=b.__wbindgen_add_to_stack_pointer(-16),a=Zn(e,b.__wbindgen_export),r=xe;b.ermiscall_sendFrame(i,this.__wbg_ptr,a,r);var t=U().getInt32(i+0,!0),s=U().getInt32(i+4,!0);if(s)throw J(t)}finally{b.__wbindgen_add_to_stack_pointer(16)}}notifyNewGop(){try{let s=b.__wbindgen_add_to_stack_pointer(-16);b.ermiscall_notifyNewGop(s,this.__wbg_ptr);var e=U().getInt32(s+0,!0),t=U().getInt32(s+4,!0);if(t)throw J(e)}finally{b.__wbindgen_add_to_stack_pointer(16)}}recv(){try{let i=b.__wbindgen_add_to_stack_pointer(-16);b.ermiscall_recv(i,this.__wbg_ptr);var e=U().getInt32(i+0,!0),t=U().getInt32(i+4,!0),s=U().getInt32(i+8,!0);if(s)throw J(t);return J(e)}finally{b.__wbindgen_add_to_stack_pointer(16)}}asyncRecv(){let e=b.ermiscall_asyncRecv(this.__wbg_ptr);return J(e)}beginWithGop(e){try{let i=b.__wbindgen_add_to_stack_pointer(-16),a=Zn(e,b.__wbindgen_export),r=xe;b.ermiscall_beginWithGop(i,this.__wbg_ptr,a,r);var t=U().getInt32(i+0,!0),s=U().getInt32(i+4,!0);if(s)throw J(t)}finally{b.__wbindgen_add_to_stack_pointer(16)}}connectionType(){try{let s=b.__wbindgen_add_to_stack_pointer(-16);b.ermiscall_connectionType(s,this.__wbg_ptr);var e=U().getInt32(s+0,!0),t=U().getInt32(s+4,!0);let i;return e!==0&&(i=_e(e,t).slice(),b.__wbindgen_export4(e,t*1,1)),i}finally{b.__wbindgen_add_to_stack_pointer(16)}}roundTripTime(){try{let s=b.__wbindgen_add_to_stack_pointer(-16);b.ermiscall_roundTripTime(s,this.__wbg_ptr);var e=U().getInt32(s+0,!0),t=U().getFloat64(s+8,!0);return e===0?void 0:t}finally{b.__wbindgen_add_to_stack_pointer(16)}}currentPacketLoss(){try{let s=b.__wbindgen_add_to_stack_pointer(-16);b.ermiscall_currentPacketLoss(s,this.__wbg_ptr);var e=U().getInt32(s+0,!0),t=U().getFloat64(s+8,!0);return e===0?void 0:t}finally{b.__wbindgen_add_to_stack_pointer(16)}}networkChange(){b.ermiscall_networkChange(this.__wbg_ptr)}getStats(){try{let i=b.__wbindgen_add_to_stack_pointer(-16);b.ermiscall_getStats(i,this.__wbg_ptr);var e=U().getInt32(i+0,!0),t=U().getInt32(i+4,!0),s=U().getInt32(i+8,!0);if(s)throw J(t);return J(e)}finally{b.__wbindgen_add_to_stack_pointer(16)}}};Symbol.dispose&&(mn.prototype[Symbol.dispose]=mn.prototype.free);var qg=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>b.__wbg_intounderlyingbytesource_free(n>>>0,1)),Zs=class{__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,qg.unregister(this),e}free(){let e=this.__destroy_into_raw();b.__wbg_intounderlyingbytesource_free(e,0)}get type(){let e=b.intounderlyingbytesource_type(this.__wbg_ptr);return Pg[e]}get autoAllocateChunkSize(){return b.intounderlyingbytesource_autoAllocateChunkSize(this.__wbg_ptr)>>>0}start(e){b.intounderlyingbytesource_start(this.__wbg_ptr,y(e))}pull(e){let t=b.intounderlyingbytesource_pull(this.__wbg_ptr,y(e));return J(t)}cancel(){let e=this.__destroy_into_raw();b.intounderlyingbytesource_cancel(e)}};Symbol.dispose&&(Zs.prototype[Symbol.dispose]=Zs.prototype.free);var Gg=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>b.__wbg_intounderlyingsink_free(n>>>0,1)),ei=class{__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,Gg.unregister(this),e}free(){let e=this.__destroy_into_raw();b.__wbg_intounderlyingsink_free(e,0)}write(e){let t=b.intounderlyingsink_write(this.__wbg_ptr,y(e));return J(t)}close(){let e=this.__destroy_into_raw(),t=b.intounderlyingsink_close(e);return J(t)}abort(e){let t=this.__destroy_into_raw(),s=b.intounderlyingsink_abort(t,y(e));return J(s)}};Symbol.dispose&&(ei.prototype[Symbol.dispose]=ei.prototype.free);var Bg=typeof FinalizationRegistry>"u"?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(n=>b.__wbg_intounderlyingsource_free(n>>>0,1)),ti=class{__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,Bg.unregister(this),e}free(){let e=this.__destroy_into_raw();b.__wbg_intounderlyingsource_free(e,0)}pull(e){let t=b.intounderlyingsource_pull(this.__wbg_ptr,y(e));return J(t)}cancel(){let e=this.__destroy_into_raw();b.intounderlyingsource_cancel(e)}};Symbol.dispose&&(ti.prototype[Symbol.dispose]=ti.prototype.free);var $g=new Set(["basic","cors","default"]);async function zg(n,e){if(typeof Response=="function"&&n instanceof Response){if(typeof WebAssembly.instantiateStreaming=="function")try{return await WebAssembly.instantiateStreaming(n,e)}catch(s){if(n.ok&&$g.has(n.type)&&n.headers.get("Content-Type")!=="application/wasm")console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",s);else throw s}let t=await n.arrayBuffer();return await WebAssembly.instantiate(t,e)}else{let t=await WebAssembly.instantiate(n,e);return t instanceof WebAssembly.Instance?{instance:t,module:n}:t}}function Wg(){let n={};return n.wbg={},n.wbg.__wbg_Error_e83987f665cf5504=function(e,t){let s=Error(_e(e,t));return y(s)},n.wbg.__wbg_String_8f0eb39a4a4c2f66=function(e,t){let s=String(h(t)),i=Ze(s,b.__wbindgen_export,b.__wbindgen_export2),a=xe;U().setInt32(e+4,a,!0),U().setInt32(e+0,i,!0)},n.wbg.__wbg___wbindgen_boolean_get_6d5a1ee65bab5f68=function(e){let t=h(e),s=typeof t=="boolean"?t:void 0;return ie(s)?16777215:s?1:0},n.wbg.__wbg___wbindgen_debug_string_df47ffb5e35e6763=function(e,t){let s=Qa(h(t)),i=Ze(s,b.__wbindgen_export,b.__wbindgen_export2),a=xe;U().setInt32(e+4,a,!0),U().setInt32(e+0,i,!0)},n.wbg.__wbg___wbindgen_is_function_ee8a6c5833c90377=function(e){return typeof h(e)=="function"},n.wbg.__wbg___wbindgen_is_object_c818261d21f283a4=function(e){let t=h(e);return typeof t=="object"&&t!==null},n.wbg.__wbg___wbindgen_is_string_fbb76cb2940daafd=function(e){return typeof h(e)=="string"},n.wbg.__wbg___wbindgen_is_undefined_2d472862bd29a478=function(e){return h(e)===void 0},n.wbg.__wbg___wbindgen_jsval_loose_eq_b664b38a2f582147=function(e,t){return h(e)==h(t)},n.wbg.__wbg___wbindgen_number_get_a20bf9b85341449d=function(e,t){let s=h(t),i=typeof s=="number"?s:void 0;U().setFloat64(e+8,ie(i)?0:i,!0),U().setInt32(e+0,!ie(i),!0)},n.wbg.__wbg___wbindgen_string_get_e4f06c90489ad01b=function(e,t){let s=h(t),i=typeof s=="string"?s:void 0;var a=ie(i)?0:Ze(i,b.__wbindgen_export,b.__wbindgen_export2),r=xe;U().setInt32(e+4,r,!0),U().setInt32(e+0,a,!0)},n.wbg.__wbg___wbindgen_throw_b855445ff6a94295=function(e,t){throw new Error(_e(e,t))},n.wbg.__wbg__wbg_cb_unref_2454a539ea5790d9=function(e){h(e)._wbg_cb_unref()},n.wbg.__wbg_abort_28ad55c5825b004d=function(e,t){h(e).abort(h(t))},n.wbg.__wbg_abort_e7eb059f72f9ed0c=function(e){h(e).abort()},n.wbg.__wbg_addEventListener_40dc0fc428fc49e1=function(){return K(function(e,t,s,i){h(e).addEventListener(_e(t,s),h(i))},arguments)},n.wbg.__wbg_append_b577eb3a177bc0fa=function(){return K(function(e,t,s,i,a){h(e).append(_e(t,s),_e(i,a))},arguments)},n.wbg.__wbg_body_587542b2fd8e06c0=function(e){let t=h(e).body;return ie(t)?0:y(t)},n.wbg.__wbg_buffer_ccc4520b36d3ccf4=function(e){let t=h(e).buffer;return y(t)},n.wbg.__wbg_byobRequest_2344e6975f27456e=function(e){let t=h(e).byobRequest;return ie(t)?0:y(t)},n.wbg.__wbg_byteLength_bcd42e4025299788=function(e){return h(e).byteLength},n.wbg.__wbg_byteOffset_ca3a6cf7944b364b=function(e){return h(e).byteOffset},n.wbg.__wbg_call_525440f72fbfc0ea=function(){return K(function(e,t,s){let i=h(e).call(h(t),h(s));return y(i)},arguments)},n.wbg.__wbg_call_e762c39fa8ea36bf=function(){return K(function(e,t){let s=h(e).call(h(t));return y(s)},arguments)},n.wbg.__wbg_cancel_48ab6f9dc366e369=function(e){let t=h(e).cancel();return y(t)},n.wbg.__wbg_catch_943836faa5d29bfb=function(e,t){let s=h(e).catch(h(t));return y(s)},n.wbg.__wbg_clearTimeout_15dfc3d1dcb635c6=function(){return K(function(e,t){h(e).clearTimeout(J(t))},arguments)},n.wbg.__wbg_clearTimeout_7a42b49784aea641=function(e){let t=clearTimeout(J(e));return y(t)},n.wbg.__wbg_close_5a6caed3231b68cd=function(){return K(function(e){h(e).close()},arguments)},n.wbg.__wbg_close_6956df845478561a=function(){return K(function(e){h(e).close()},arguments)},n.wbg.__wbg_close_885e277edf06b3fa=function(){return K(function(e){h(e).close()},arguments)},n.wbg.__wbg_code_20d453b11b200026=function(e){return h(e).code},n.wbg.__wbg_code_218f5fdf8c7fcabd=function(e){return h(e).code},n.wbg.__wbg_crypto_574e78ad8b13b65f=function(e){let t=h(e).crypto;return y(t)},n.wbg.__wbg_data_ee4306d069f24f2d=function(e){let t=h(e).data;return y(t)},n.wbg.__wbg_done_2042aa2670fb1db1=function(e){return h(e).done},n.wbg.__wbg_enqueue_7b18a650aec77898=function(){return K(function(e,t){h(e).enqueue(h(t))},arguments)},n.wbg.__wbg_fetch_74a3e84ebd2c9a0e=function(e){let t=fetch(h(e));return y(t)},n.wbg.__wbg_fetch_f8ba0e29a9d6de0d=function(e,t){let s=h(e).fetch(h(t));return y(s)},n.wbg.__wbg_getRandomValues_1c61fac11405ffdc=function(){return K(function(e,t){globalThis.crypto.getRandomValues(un(e,t))},arguments)},n.wbg.__wbg_getRandomValues_b8f5dbd5f3995a9e=function(){return K(function(e,t){h(e).getRandomValues(h(t))},arguments)},n.wbg.__wbg_getReader_48e00749fe3f6089=function(){return K(function(e){let t=h(e).getReader();return y(t)},arguments)},n.wbg.__wbg_getTime_14776bfb48a1bff9=function(e){return h(e).getTime()},n.wbg.__wbg_get_7bed016f185add81=function(e,t){let s=h(e)[t>>>0];return y(s)},n.wbg.__wbg_get_done_a0463af43a1fc764=function(e){let t=h(e).done;return ie(t)?16777215:t?1:0},n.wbg.__wbg_get_efcb449f58ec27c2=function(){return K(function(e,t){let s=Reflect.get(h(e),h(t));return y(s)},arguments)},n.wbg.__wbg_get_value_5ce96c9f81ce7398=function(e){let t=h(e).value;return y(t)},n.wbg.__wbg_has_787fafc980c3ccdb=function(){return K(function(e,t){return Reflect.has(h(e),h(t))},arguments)},n.wbg.__wbg_headers_b87d7eaba61c3278=function(e){let t=h(e).headers;return y(t)},n.wbg.__wbg_instanceof_ArrayBuffer_70beb1189ca63b38=function(e){let t;try{t=h(e)instanceof ArrayBuffer}catch{t=!1}return t},n.wbg.__wbg_instanceof_Blob_23b3322f66e5a83b=function(e){let t;try{t=h(e)instanceof Blob}catch{t=!1}return t},n.wbg.__wbg_instanceof_Response_f4f3e87e07f3135c=function(e){let t;try{t=h(e)instanceof Response}catch{t=!1}return t},n.wbg.__wbg_instanceof_Uint8Array_20c8e73002f7af98=function(e){let t;try{t=h(e)instanceof Uint8Array}catch{t=!1}return t},n.wbg.__wbg_isArray_96e0af9891d0945d=function(e){return Array.isArray(h(e))},n.wbg.__wbg_iterator_e5822695327a3c39=function(){return y(Symbol.iterator)},n.wbg.__wbg_length_69bca3cb64fc8748=function(e){return h(e).length},n.wbg.__wbg_length_cdd215e10d9dd507=function(e){return h(e).length},n.wbg.__wbg_log_ee0138cca4957740=function(e,t){console.log(_e(e,t))},n.wbg.__wbg_message_bd42dbe3f2f3ed8e=function(e,t){let s=h(t).message,i=Ze(s,b.__wbindgen_export,b.__wbindgen_export2),a=xe;U().setInt32(e+4,a,!0),U().setInt32(e+0,i,!0)},n.wbg.__wbg_msCrypto_a61aeb35a24c1329=function(e){let t=h(e).msCrypto;return y(t)},n.wbg.__wbg_new_0_f9740686d739025c=function(){return y(new Date)},n.wbg.__wbg_new_1acc0b6eea89d040=function(){let e=new Object;return y(e)},n.wbg.__wbg_new_2531773dac38ebb3=function(){return K(function(){let e=new AbortController;return y(e)},arguments)},n.wbg.__wbg_new_3c3d849046688a66=function(e,t){try{var s={a:e,b:t},i=(r,o)=>{let l=s.a;s.a=0;try{return Lg(l,s.b,r,o)}finally{s.a=l}};let a=new Promise(i);return y(a)}finally{s.a=s.b=0}},n.wbg.__wbg_new_5a79be3ab53b8aa5=function(e){let t=new Uint8Array(h(e));return y(t)},n.wbg.__wbg_new_881c4fe631eee9ad=function(){return K(function(e,t){let s=new WebSocket(_e(e,t));return y(s)},arguments)},n.wbg.__wbg_new_9edf9838a2def39c=function(){return K(function(){let e=new Headers;return y(e)},arguments)},n.wbg.__wbg_new_a7442b4b19c1a356=function(e,t){let s=new Error(_e(e,t));return y(s)},n.wbg.__wbg_new_e17d9f43105b08be=function(){let e=new Array;return y(e)},n.wbg.__wbg_new_from_slice_92f4d78ca282a2d2=function(e,t){let s=new Uint8Array(un(e,t));return y(s)},n.wbg.__wbg_new_no_args_ee98eee5275000a4=function(e,t){let s=new Function(_e(e,t));return y(s)},n.wbg.__wbg_new_with_byte_offset_and_length_46e3e6a5e9f9e89b=function(e,t,s){let i=new Uint8Array(h(e),t>>>0,s>>>0);return y(i)},n.wbg.__wbg_new_with_length_01aa0dc35aa13543=function(e){let t=new Uint8Array(e>>>0);return y(t)},n.wbg.__wbg_new_with_str_and_init_0ae7728b6ec367b1=function(){return K(function(e,t,s){let i=new Request(_e(e,t),h(s));return y(i)},arguments)},n.wbg.__wbg_new_with_str_sequence_57a88eb77393f23f=function(){return K(function(e,t,s){let i=new WebSocket(_e(e,t),h(s));return y(i)},arguments)},n.wbg.__wbg_next_020810e0ae8ebcb0=function(){return K(function(e){let t=h(e).next();return y(t)},arguments)},n.wbg.__wbg_next_2c826fe5dfec6b6a=function(e){let t=h(e).next;return y(t)},n.wbg.__wbg_node_905d3e251edff8a2=function(e){let t=h(e).node;return y(t)},n.wbg.__wbg_now_2c95c9de01293173=function(e){return h(e).now()},n.wbg.__wbg_now_793306c526e2e3b6=function(){return Date.now()},n.wbg.__wbg_performance_7a3ffd0b17f663ad=function(e){let t=h(e).performance;return y(t)},n.wbg.__wbg_process_dc0fbacc7c1c06f7=function(e){let t=h(e).process;return y(t)},n.wbg.__wbg_prototypesetcall_2a6620b6922694b2=function(e,t,s){Uint8Array.prototype.set.call(un(e,t),h(s))},n.wbg.__wbg_push_df81a39d04db858c=function(e,t){return h(e).push(h(t))},n.wbg.__wbg_queueMicrotask_34d692c25c47d05b=function(e){let t=h(e).queueMicrotask;return y(t)},n.wbg.__wbg_queueMicrotask_9d76cacb20c84d58=function(e){queueMicrotask(h(e))},n.wbg.__wbg_randomFillSync_ac0988aba3254290=function(){return K(function(e,t){h(e).randomFillSync(J(t))},arguments)},n.wbg.__wbg_read_48f1593df542f968=function(e){let t=h(e).read();return y(t)},n.wbg.__wbg_readyState_97984f126080aeda=function(e){return h(e).readyState},n.wbg.__wbg_reason_1cced37e3a93763e=function(e,t){let s=h(t).reason,i=Ze(s,b.__wbindgen_export,b.__wbindgen_export2),a=xe;U().setInt32(e+4,a,!0),U().setInt32(e+0,i,!0)},n.wbg.__wbg_releaseLock_5d0b5a68887b891d=function(e){h(e).releaseLock()},n.wbg.__wbg_removeEventListener_924d9db66a4f775d=function(){return K(function(e,t,s,i){h(e).removeEventListener(_e(t,s),h(i))},arguments)},n.wbg.__wbg_require_60cc747a6bc5215a=function(){return K(function(){let e=module.require;return y(e)},arguments)},n.wbg.__wbg_resolve_caf97c30b83f7053=function(e){let t=Promise.resolve(h(e));return y(t)},n.wbg.__wbg_respond_0f4dbf5386f5c73e=function(){return K(function(e,t){h(e).respond(t>>>0)},arguments)},n.wbg.__wbg_send_171576d2f7487517=function(){return K(function(e,t,s){h(e).send(_e(t,s))},arguments)},n.wbg.__wbg_send_3d2cf376613294f0=function(){return K(function(e,t,s){h(e).send(un(t,s))},arguments)},n.wbg.__wbg_setTimeout_4eb823e8b72fbe79=function(){return K(function(e,t,s){let i=h(e).setTimeout(J(t),s);return y(i)},arguments)},n.wbg.__wbg_setTimeout_7bb3429662ab1e70=function(e,t){let s=setTimeout(h(e),t);return y(s)},n.wbg.__wbg_set_3f1d0b984ed272ed=function(e,t,s){h(e)[J(t)]=J(s)},n.wbg.__wbg_set_9e6516df7b7d0f19=function(e,t,s){h(e).set(un(t,s))},n.wbg.__wbg_set_binaryType_9d839cea8fcdc5c3=function(e,t){h(e).binaryType=Fg[t]},n.wbg.__wbg_set_body_3c365989753d61f4=function(e,t){h(e).body=h(t)},n.wbg.__wbg_set_cache_2f9deb19b92b81e3=function(e,t){h(e).cache=Mg[t]},n.wbg.__wbg_set_credentials_f621cd2d85c0c228=function(e,t){h(e).credentials=jg[t]},n.wbg.__wbg_set_handle_event_b2de49ad6c81e3c8=function(e,t){h(e).handleEvent=h(t)},n.wbg.__wbg_set_headers_6926da238cd32ee4=function(e,t){h(e).headers=h(t)},n.wbg.__wbg_set_method_c02d8cbbe204ac2d=function(e,t,s){h(e).method=_e(t,s)},n.wbg.__wbg_set_mode_52ef73cfa79639cb=function(e,t){h(e).mode=Ng[t]},n.wbg.__wbg_set_onclose_c09e4f7422de8dae=function(e,t){h(e).onclose=h(t)},n.wbg.__wbg_set_onerror_337a3a2db9517378=function(e,t){h(e).onerror=h(t)},n.wbg.__wbg_set_onmessage_8661558551a89792=function(e,t){h(e).onmessage=h(t)},n.wbg.__wbg_set_onopen_efccb9305427b907=function(e,t){h(e).onopen=h(t)},n.wbg.__wbg_set_signal_dda2cf7ccb6bee0f=function(e,t){h(e).signal=h(t)},n.wbg.__wbg_signal_4db5aa055bf9eb9a=function(e){let t=h(e).signal;return y(t)},n.wbg.__wbg_static_accessor_GLOBAL_89e1d9ac6a1b250e=function(){let e=typeof global>"u"?null:global;return ie(e)?0:y(e)},n.wbg.__wbg_static_accessor_GLOBAL_THIS_8b530f326a9e48ac=function(){let e=typeof globalThis>"u"?null:globalThis;return ie(e)?0:y(e)},n.wbg.__wbg_static_accessor_SELF_6fdf4b64710cc91b=function(){let e=typeof self>"u"?null:self;return ie(e)?0:y(e)},n.wbg.__wbg_static_accessor_WINDOW_b45bfc5a37f6cfa2=function(){let e=typeof window>"u"?null:window;return ie(e)?0:y(e)},n.wbg.__wbg_status_de7eed5a7a5bfd5d=function(e){return h(e).status},n.wbg.__wbg_stringify_b5fb28f6465d9c3e=function(){return K(function(e){let t=JSON.stringify(h(e));return y(t)},arguments)},n.wbg.__wbg_subarray_480600f3d6a9f26c=function(e,t,s){let i=h(e).subarray(t>>>0,s>>>0);return y(i)},n.wbg.__wbg_then_4f46f6544e6b4a28=function(e,t){let s=h(e).then(h(t));return y(s)},n.wbg.__wbg_then_70d05cf780a18d77=function(e,t,s){let i=h(e).then(h(t),h(s));return y(i)},n.wbg.__wbg_url_9bd0af1cd8643de7=function(e,t){let s=h(t).url,i=Ze(s,b.__wbindgen_export,b.__wbindgen_export2),a=xe;U().setInt32(e+4,a,!0),U().setInt32(e+0,i,!0)},n.wbg.__wbg_url_b36d2a5008eb056f=function(e,t){let s=h(t).url,i=Ze(s,b.__wbindgen_export,b.__wbindgen_export2),a=xe;U().setInt32(e+4,a,!0),U().setInt32(e+0,i,!0)},n.wbg.__wbg_value_692627309814bb8c=function(e){let t=h(e).value;return y(t)},n.wbg.__wbg_versions_c01dfd4722a88165=function(e){let t=h(e).versions;return y(t)},n.wbg.__wbg_view_f6c15ac9fed63bbd=function(e){let t=h(e).view;return ie(t)?0:y(t)},n.wbg.__wbg_wasClean_3d7c0cf05bd0a123=function(e){return h(e).wasClean},n.wbg.__wbindgen_cast_0b4723bb5ff7475b=function(e,t){let s=Yn(e,t,b.__wasm_bindgen_func_elem_11664,Ag);return y(s)},n.wbg.__wbindgen_cast_2241b6af4c4b2941=function(e,t){let s=_e(e,t);return y(s)},n.wbg.__wbindgen_cast_253c73f2760a05aa=function(e,t){let s=Yn(e,t,b.__wasm_bindgen_func_elem_6219,Ig);return y(s)},n.wbg.__wbindgen_cast_343835dd8f264af2=function(e,t){let s=Tg(e,t,b.__wasm_bindgen_func_elem_5735,Ug);return y(s)},n.wbg.__wbindgen_cast_7bacc9fa7d2c65f4=function(e,t){let s=Yn(e,t,b.__wasm_bindgen_func_elem_12841,kg);return y(s)},n.wbg.__wbindgen_cast_88fdcfb6b716b7f8=function(e,t){let s=Yn(e,t,b.__wasm_bindgen_func_elem_12896,Og);return y(s)},n.wbg.__wbindgen_cast_c43a1cf1b94f2e7c=function(e,t){let s=Yn(e,t,b.__wasm_bindgen_func_elem_2083,Dg);return y(s)},n.wbg.__wbindgen_cast_cb9088102bce6b30=function(e,t){let s=un(e,t);return y(s)},n.wbg.__wbindgen_cast_d6cd19b81560fd6e=function(e){return y(e)},n.wbg.__wbindgen_object_clone_ref=function(e){let t=h(e);return y(t)},n.wbg.__wbindgen_object_drop_ref=function(e){J(e)},n}function Vg(n,e){return b=n.exports,Wp.__wbindgen_wasm_module=e,jt=null,es=null,b}async function Wp(n){if(b!==void 0)return b;typeof n<"u"&&(Object.getPrototypeOf(n)===Object.prototype?{module_or_path:n}=n:console.warn("using deprecated parameters for the initialization function; pass a single object instead")),typeof n>"u"&&(n="/ermis_call_node_wasm_bg.wasm");let e=Wg();(typeof n=="string"||typeof Request=="function"&&n instanceof Request||typeof URL=="function"&&n instanceof URL)&&(n=fetch(n));let{instance:t,module:s}=await zg(await n,e);return Vg(t,s)}var Vp=Wp;var ni=class{videoEncoder=null;audioEncoder=null;videoReader=null;localStream=null;videoConfig=null;audioConfig=null;videoConfigSent=!1;audioConfigSent=!1;hasVideo=!1;hasAudio=!1;forceKeyFrame=!1;nodeCall;constructor(e){this.nodeCall=e}async connect(e){try{await this.nodeCall.connect(e),await this.sendConnected(),await this.sendConfigs()}catch(t){console.error("Error starting MediaStreamSender:",t)}}async sendConfigs(){try{await this.sendTransceiverState(this.hasAudio,this.hasVideo),await this.sendAudioConfig(),this.localStream?.getVideoTracks()[0]&&await this.sendVideoConfig()}catch(e){console.error("Error sending configs:",e)}}stop=()=>{if(this.videoReader){try{this.videoReader.cancel("Stream stopped").catch(()=>{})}catch{}this.videoReader=null}if(this.videoEncoder){try{this.videoEncoder.state!=="closed"&&(this.videoEncoder.reset(),this.videoEncoder.close())}catch{}this.videoEncoder=null}if(this.audioEncoder){try{this.audioEncoder.state!=="closed"&&(this.audioEncoder.reset(),this.audioEncoder.close())}catch{}this.audioEncoder=null}this.videoConfig=null,this.audioConfig=null,this.videoConfigSent=!1,this.audioConfigSent=!1,this.hasVideo=!1,this.hasAudio=!1,this.localStream&&(this.localStream.getTracks().forEach(e=>e.stop()),this.localStream=null)};initAudioEncoder=e=>{this.localStream=new MediaStream([e]),this.audioConfigSent=!1,this.hasAudio=!!e;let t=new AudioEncoder({output:(s,i)=>{if(i?.decoderConfig&&!this.audioConfigSent){let a;i.decoderConfig.description&&(a=ba(i.decoderConfig.description)),this.audioConfig={codec:i.decoderConfig.codec??"opus",sampleRate:i.decoderConfig.sampleRate??48e3,numberOfChannels:i.decoderConfig.numberOfChannels??1,...a&&{description:a}}}if(s&&this.isReadyToSendData("audio")){let a=new ArrayBuffer(s.byteLength);s.copyTo(a);let r=s.timestamp,o=Ut(a,r,"audio",null);this.sendPacketOrQueue(o,"audio",null)}},error:s=>console.error("AudioEncoder error:",s)});t.configure({codec:"mp4a.40.2",sampleRate:48e3,numberOfChannels:1,bitrate:128e3}),this.audioEncoder=t,this.processAudioFrames(e)};initVideoEncoder(e){this.localStream&&this.localStream.addTrack(e),this.videoConfigSent=!1,this.hasVideo=!!e;let t=e.getSettings(),s=t.width||1280,i=t.height||720,a=new VideoEncoder({output:async(r,o)=>{if(o?.decoderConfig&&!this.videoConfigSent){let l;o.decoderConfig.description&&(l=ba(o.decoderConfig.description)),this.videoConfig={codec:o.decoderConfig.codec??"hev1.1.6.L93.B0",codedWidth:o.decoderConfig.codedWidth??s,codedHeight:o.decoderConfig.codedHeight??i,frameRate:30,orientation:0,...l&&{description:l}},await this.sendVideoConfig()}if(r&&this.isReadyToSendData("video")){let l=new ArrayBuffer(r.byteLength);r.copyTo(l);let c=r.type==="key"?"video-key":"video-delta",p=r.timestamp,u=Ut(l,p,c,null);this.sendPacketOrQueue(u,"video",c)}},error:r=>console.error("VideoEncoder error:",r)});a.configure({codec:"hev1.1.6.L93.B0",width:s,height:i,bitrate:5e5,framerate:30,latencyMode:"realtime",hardwareAcceleration:"prefer-hardware"}),this.videoEncoder=a,this.processVideoFrames(e)}initEncoders=e=>{let t=e.getVideoTracks()[0],s=e.getAudioTracks()[0];s&&this.initAudioEncoder(s),t&&this.initVideoEncoder(t)};sendTransceiverState=async(e,t)=>{let i=Ut(null,null,"transciverState",{audio_enable:!!e,video_enable:!!t});await this.nodeCall.sendControlFrame(i)};async replaceVideoTrack(e){if(this.videoReader){try{await this.videoReader.cancel("Replacing track")}catch{}this.videoReader=null}e&&this.processVideoFrames(e)}async replaceAudioTrack(e){e&&this.processAudioFrames(e)}requestKeyFrame=()=>{console.log("\u{1F4E5} KeyFrame requested"),this.forceKeyFrame=!0};processVideoFrames=async e=>{try{let t=new MediaStreamTrackProcessor({track:e});this.videoReader=t.readable.getReader();let s=0;for(;this.videoReader;){let{done:i,value:a}=await this.videoReader.read();if(i)break;if(!this.videoEncoder){a?.close();break}if(a){s+=1;let r=s%60===0||this.forceKeyFrame;this.forceKeyFrame&&(console.log("\u{1F4E4} Sending forced KeyFrame"),this.forceKeyFrame=!1);try{this.videoEncoder.encode(a,{keyFrame:r})}catch(o){console.error("Encode error:",o)}finally{a.close()}}}}catch(t){console.error(`Error processing video frames: ${t.message}`)}finally{if(this.videoReader)try{this.videoReader.releaseLock()}catch{}}};processAudioFrames=async e=>{let s=new MediaStreamTrackProcessor({track:e}).readable.getReader();try{for(;;){let{done:i,value:a}=await s.read();if(i)break;if(!this.audioEncoder){a?.close();break}if(a)try{this.audioEncoder.encode(a)}catch(r){console.error("Audio Encoding error:",r)}finally{a.close()}}}catch(i){console.error(`Error processing audio frames: ${i.message}`)}};isReadyToSendData=e=>{let t=!this.hasVideo||this.videoConfigSent,s=!this.hasAudio||this.audioConfigSent,i=t&&s;return e==="video"?i&&this.videoConfigSent:e==="audio"?i&&this.audioConfigSent:!1};sendVideoConfig=async()=>{if(this.videoConfig&&!this.videoConfigSent)try{let e=Ut(null,null,"videoConfig",this.videoConfig);await this.nodeCall.sendControlFrame(e),this.videoConfigSent=!0}catch(e){console.error("Error sending video config:",e)}};sendAudioConfig=async()=>{if(this.audioConfig&&!this.audioConfigSent)try{let e=Ut(null,null,"audioConfig",this.audioConfig);await this.nodeCall.sendControlFrame(e),this.audioConfigSent=!0}catch(e){console.error("Error sending audio config:",e)}};sendConnected=async()=>{let e=Ut(null,null,"connected",null);await this.nodeCall.sendControlFrame(e)};sendPacketOrQueue=async(e,t,s)=>{this.isReadyToSendData(t)&&(t==="audio"?await this.nodeCall.sendAudioFrame(e):t==="video"&&(s==="video-key"?await this.nodeCall.beginWithGop(e):s==="video-delta"&&await this.nodeCall.sendFrame(e)))}};var fn={VPS_NUT:32,SPS_NUT:33,PPS_NUT:34,PREFIX_SEI_NUT:39,SUFFIX_SEI_NUT:40,fromValue(n){return{32:"VPS_NUT",33:"SPS_NUT",34:"PPS_NUT",39:"PREFIX_SEI_NUT",40:"SUFFIX_SEI_NUT"}[n]||n}},si=class n{generalProfileSpace=0;generalTierFlag=!1;generalProfileIdc=0;generalProfileCompatibilityFlags=0;generalConstraintIndicatorFlags=0;generalLevelIdc=0;minSpatialSegmentationIdc=0;parallelismType=0;chromaFormatIdc=0;bitDepthLumaMinus8=0;bitDepthChromaMinus8=0;avgFrameRate=0;constantFrameRate=0;numTemporalLayers=0;temporalIdNested=!1;lengthSizeMinusOne=0;arrays=[];constructor(e){Object.assign(this,e)}static demux(e){let t=e instanceof Uint8Array?e:new Uint8Array(e),s=new DataView(t.buffer,t.byteOffset,t.byteLength),i=0,a=0,r=z=>{let pe=0;for(let T=0;T<z;T++){if(i>=t.length)throw new Error("End of buffer");let A=t[i]>>7-a&1;pe=pe<<1|A,a++,a===8&&(a=0,i++)}return pe},o=()=>{if(a!==0)return r(8);if(i>=t.length)throw new Error("End of buffer");return t[i++]},l=()=>{if(a!==0)return r(16);let z=s.getUint16(i,!1);return i+=2,z},c=()=>{if(a!==0)return r(32);let z=s.getUint32(i,!1);return i+=4,z},p=()=>{let z=l(),pe=c();return z*4294967296+pe},u=z=>{if(a!==0){let T=new Uint8Array(z);for(let A=0;A<z;A++)T[A]=r(8);return T}if(i+z>t.length)throw new Error("End of buffer");let pe=t.slice(i,i+z);return i+=z,pe};if(o()!==1)throw new Error("Invalid configuration version");let f=r(2),g=r(1)===1,v=r(5),_=c(),R=p(),D=o();r(4);let L=r(12);r(6);let q=r(2);r(6);let M=r(2);r(5);let Y=r(3);r(5);let ae=r(3),Z=l(),ye=r(2),Le=r(3),Nt=r(1)===1,qe=r(2);if(qe===2)throw new Error("length_size_minus_one must be 0, 1, or 3");let gt=o(),ce=[];for(let z=0;z<gt;z++){let pe=r(1)===1;r(1);let T=r(6),A=fn.fromValue(T);T!==fn.VPS_NUT&&T!==fn.SPS_NUT&&T!==fn.PPS_NUT&&T!==fn.PREFIX_SEI_NUT&&fn.SUFFIX_SEI_NUT;let X=l(),Te=[];for(let ee=0;ee<X;ee++){let Ge=l(),bt=u(Ge);Te.push(bt)}ce.push({arrayCompleteness:pe,nalUnitType:A,nalus:Te})}return new n({generalProfileSpace:f,generalTierFlag:g,generalProfileIdc:v,generalProfileCompatibilityFlags:_,generalConstraintIndicatorFlags:R,generalLevelIdc:D,minSpatialSegmentationIdc:L,parallelismType:q,chromaFormatIdc:M,bitDepthLumaMinus8:Y,bitDepthChromaMinus8:ae,avgFrameRate:Z,constantFrameRate:ye,numTemporalLayers:Le,temporalIdNested:Nt,lengthSizeMinusOne:qe,arrays:ce})}toCodecString(){let t={0:"",1:"A",2:"B",3:"C"}[this.generalProfileSpace];if(t===void 0)throw new Error("Unknown profile space");let s=`${t}${this.generalProfileIdc}`,i=this.generalProfileCompatibilityFlags.toString(16).padStart(8,"0").split("").reverse().join(""),a="";for(let u=0;u<i.length;u++){let m=i[u];(m!=="0"||u===0)&&(a+=m)}let o=`${this.generalTierFlag?"H":"L"}${this.generalLevelIdc}`,l="",c=this.generalConstraintIndicatorFlags,p=[Math.floor(c/1099511627776)&255,Math.floor(c/4294967296)&255,Math.floor(c/16777216)&255,Math.floor(c/65536)&255,Math.floor(c/256)&255,c&255];for(let u=2;u<6;u++)p[u]!==0&&(l+=`.${p[u].toString(16).padStart(2,"0")}`);return`hev1.${s}.${a}.${o}${l}`}};var Hg=.1,Hp=.02,ii=class{videoDecoder=null;audioDecoder=null;videoWriter=null;audioContext=null;mediaDestination=null;isWaitingForKeyFrame=!0;nextStartTime=0;lastVideoConfig=null;nodeCall;events;generatedStream=null;constructor(e,t={}){this.nodeCall=e,this.events=t}async acceptConnection(){try{await this.nodeCall.acceptConnection()}catch(e){console.error("\u274C Error starting MediaStreamReceiver:",e)}}getRemoteStream=()=>this.generatedStream;stop=()=>{this.resetDecoders()};initAudioContext=async()=>{if(!this.audioContext||this.audioContext.state==="closed"){let e=window.AudioContext||window.webkitAudioContext;this.audioContext=new e({sampleRate:48e3,latencyHint:"interactive"}),this.mediaDestination=this.audioContext.createMediaStreamDestination(),this.audioContext.state==="suspended"&&await this.audioContext.resume(),this.nextStartTime=this.audioContext.currentTime+Hp}};initDecoders=e=>{if(this.audioDecoder&&this.audioDecoder.close(),this.initAudioContext(),this.mediaDestination){let t=this.mediaDestination.stream.getAudioTracks()[0];this.generatedStream=new MediaStream([t])}this.isWaitingForKeyFrame=!0,this.audioDecoder=new AudioDecoder({output:t=>this.playDecodedAudio(t),error:t=>console.error("AudioDecoder error:",t)}),e==="video"&&this.setupVideoDecoder(),this.receiveLoop()};setupVideoDecoder=()=>{if(!this.videoWriter)return;if(this.videoDecoder)try{this.videoDecoder.state!=="closed"&&this.videoDecoder.close()}catch{}let e=new VideoDecoder({output:async t=>{try{if(!this.videoWriter){t.close();return}if(this.videoWriter.desiredSize<=0){t.close();return}await this.videoWriter.write(t)}catch{t.close()}finally{t.close()}},error:t=>{if(console.error("\u274C VideoDecoder CRASHED:",t),this.isWaitingForKeyFrame=!0,this.videoWriter&&(console.log("\u267B\uFE0F Attempting to respawn VideoDecoder..."),this.setupVideoDecoder(),this.lastVideoConfig&&this.videoDecoder))try{this.videoDecoder.configure(this.lastVideoConfig)}catch{}}});this.videoDecoder=e};playDecodedAudio=e=>{try{if(!this.audioContext||!this.mediaDestination){e.close();return}let{numberOfChannels:t,numberOfFrames:s,sampleRate:i}=e,a=s/i,r=this.audioContext.currentTime;this.nextStartTime<r?this.nextStartTime=r:this.nextStartTime>r+Hg&&(this.nextStartTime=r+Hp);let o=this.audioContext.createBuffer(t,s,i),l=t*s,c=new Float32Array(l);e.copyTo(c,{planeIndex:0,format:"f32-planar"});for(let u=0;u<t;u++){let m=c.subarray(u*s,(u+1)*s);o.copyToChannel(m,u)}let p=this.audioContext.createBufferSource();p.buffer=o,p.connect(this.mediaDestination),p.start(this.nextStartTime),this.nextStartTime+=a,e.close()}catch(t){console.error("Error in playDecodedAudio:",t),e?.close()}};newCodecFromDescription=(e,t)=>{if(!t.toLowerCase().includes("hvc")&&!t.toLowerCase().includes("hev"))return"";try{return si.demux(e).toCodecString()}catch{return""}};receiveLoop=async()=>{let e=new TextDecoder;for(;;)try{if(!this.nodeCall)break;let t=await this.nodeCall.asyncRecv(),s=new DataView(t.buffer,t.byteOffset,t.byteLength),i=s.getUint8(0),a=[0,1,6,7,5,8,9,10].includes(i)?1:9,r=new Uint8Array(t.buffer,t.byteOffset+a,t.byteLength-a);switch(i){case 0:{try{let l=e.decode(r),c=JSON.parse(l);if(console.log("--videoConfig--",c),!this.videoWriter){let f=new MediaStreamTrackGenerator({kind:"video"});this.videoWriter=f.writable.getWriter(),this.generatedStream&&this.generatedStream.addTrack(f)}this.videoDecoder||this.setupVideoDecoder(),this.isWaitingForKeyFrame=!0;let p;if(c.description)try{let f=atob(c.description),g=new Uint8Array(f.length);for(let v=0;v<f.length;v++)g[v]=f.charCodeAt(v);p=g.buffer}catch{}let u="";p&&(u=this.newCodecFromDescription(p,c.codec)||$l(c.codec));let m={codec:u,frameRate:c.frameRate,codedWidth:c.codedWidth,codedHeight:c.codedHeight,...c.orientation&&{rotation:c.orientation},...p&&{description:p}};this.lastVideoConfig=m,this.videoDecoder&&this.videoDecoder.state!=="closed"&&((await VideoDecoder.isConfigSupported(m)).supported?(this.videoDecoder.configure(m),this.isWaitingForKeyFrame=!0):console.error("\u274C Browser does not support this video config:",m))}catch(l){console.error("\u274C Error processing VIDEO_CONFIG:",l)}break}case 1:{let l=JSON.parse(e.decode(r));console.log("--audioConfig--",l),this.audioDecoder?.state!=="closed"&&this.audioDecoder?.configure({codec:l.codec,sampleRate:l.sampleRate,numberOfChannels:l.numberOfChannels});break}case 2:case 3:{if(!this.videoDecoder||this.videoDecoder.state!=="configured")break;let l=i===2;if(this.isWaitingForKeyFrame){if(!l)break;console.log("\u2705 Resumed decoding at KeyFrame"),this.isWaitingForKeyFrame=!1}if(!l&&this.videoDecoder.decodeQueueSize>15){console.warn("\u26A0\uFE0F Queue > 15. Dropping & Waiting for KeyFrame..."),this.isWaitingForKeyFrame=!0;break}let c=s.getBigUint64(1,!1),p=Number(c);try{this.videoDecoder.decode(new EncodedVideoChunk({type:l?"key":"delta",timestamp:p,data:r}))}catch(u){console.error("Video decode failed:",u),this.videoDecoder.state==="closed"&&(this.isWaitingForKeyFrame=!0)}break}case 4:{if(this.audioDecoder?.state==="configured"){let l=s.getBigUint64(1,!1),c=Number(l);this.audioDecoder.decode(new EncodedAudioChunk({type:"key",timestamp:c,data:r}))}break}case 6:this.events.onConnected&&this.events.onConnected();break;case 7:let o=JSON.parse(e.decode(r));this.events.onTransceiverState&&this.events.onTransceiverState(o);break;case 5:{let l=s.getInt32(1,!1);if(this.videoDecoder&&this.lastVideoConfig&&this.lastVideoConfig.rotation!==l){this.lastVideoConfig.rotation=l;try{this.videoDecoder.configure(this.lastVideoConfig),this.isWaitingForKeyFrame=!0,console.log("\u{1F504} Reconfigured rotation to",l,"- Waiting for next KeyFrame")}catch(c){console.error("Error reconfiguring VideoDecoder with new orientation:",c)}}break}case 8:console.log("\u{1F4E5} Received REQUEST_CONFIG"),this.events.onRequestConfig&&this.events.onRequestConfig();break;case 9:console.log("\u{1F4E5} Received REQUEST_KEY_FRAME"),this.events.onRequestKeyFrame&&this.events.onRequestKeyFrame();break;case 10:console.log("\u{1F4E5} Received END_CALL"),this.events.onEndCall&&this.events.onEndCall();break;default:console.warn("\u2753 Unknown frame type received:",i);break}}catch(t){console.error("Stream loop error",t),await new Promise(s=>setTimeout(s,200))}};resetDecoders=()=>{if(this.videoWriter){try{this.videoWriter.abort("Stream stopped").catch(()=>{}),this.videoWriter.releaseLock()}catch(e){console.warn("Error closing video writer:",e)}this.videoWriter=null}if(this.videoDecoder){try{this.videoDecoder.state!=="closed"&&(this.videoDecoder.reset(),this.videoDecoder.close())}catch{}this.videoDecoder=null}if(this.audioDecoder){try{this.audioDecoder.state!=="closed"&&(this.audioDecoder.reset(),this.audioDecoder.close())}catch{}this.audioDecoder=null}if(this.audioContext){try{this.audioContext.close()}catch(e){console.warn("Error closing audio context:",e)}this.audioContext=null}this.isWaitingForKeyFrame=!0,this.mediaDestination=null,this.nextStartTime=0,this.lastVideoConfig=null,this.generatedStream&&(this.generatedStream.getTracks().forEach(e=>e.stop()),this.generatedStream=null)}};var Ya=class{wasmPath;relayUrl="https://test-iroh.ermis.network.:8443";_client;sessionID;cid;callType;userID;callStatus="";metadata;callNode=null;localStream=null;remoteStream=null;callerInfo;receiverInfo;onCallEvent;onLocalStream;onRemoteStream;onConnectionMessageChange;onCallStatus;onDataChannelMessage;onUpgradeCall;onScreenShareChange;onError;onDeviceChange;availableAudioDevices=[];availableVideoDevices=[];selectedAudioDeviceId;selectedVideoDeviceId;missCallTimeout=null;healthCallInterval=null;healthCallServerInterval=null;healthCallTimeout=null;healthCallWarningTimeout=null;signalHandler;connectionChangedHandler;messageUpdatedHandler;isOffline=!1;isDestroyed=!1;mediaSender=null;mediaReceiver=null;constructor(e,t,s,i){this._client=e,this.cid="",this.callType="",this.sessionID=t,this.userID=e.userID,this.metadata={},this.wasmPath=s,this.relayUrl=i,this.listenSocketEvents(),this.setupDeviceChangeListener(),this.loadWasm()}async loadWasm(){try{await Vp(this.wasmPath)}catch(e){throw console.error("Failed to load ErmisCall WASM module:",e),e}}async initialize(){try{let e=new mn;return await e.spawn([this.relayUrl]),this.callNode=e,this.mediaSender=new ni(e),this.mediaReceiver=new ii(e,{onConnected:()=>{this.setCallStatus("connected"),this.connectCall(),this.missCallTimeout&&(clearTimeout(this.missCallTimeout),this.missCallTimeout=null),this.healthCallServerInterval&&clearInterval(this.healthCallServerInterval),this.healthCallServerInterval=setInterval(()=>{this.healthCall()},1e4);let t=this.mediaReceiver?.getRemoteStream();t&&this.onRemoteStream&&this.onRemoteStream(t)},onTransceiverState:t=>{typeof this.onDataChannelMessage=="function"&&this.onDataChannelMessage(t)},onRequestConfig:()=>{console.log("\u{1F4E4} Responding to REQUEST_CONFIG by sending configs"),this.mediaSender?.sendConfigs()},onRequestKeyFrame:()=>{console.log("\u{1F4E4} Responding to REQUEST_KEY_FRAME by forcing key frame"),this.mediaSender?.requestKeyFrame()},onEndCall:()=>{console.log("\u{1F4E5} Received END_CALL from remote peer"),this.destroy()}}),e}catch(e){throw console.error("Failed to initialize Ermis SDK:",e),e}}async getLocalEndpointAddr(){try{if(await this.initialize(),!this.callNode)return console.error("ErmisCall is not initialized."),null;let e=await this.callNode.getLocalEndpointAddr();return this.metadata&&(this.metadata.address=e),e}catch(e){return console.error("Failed to get address from ErmisCall:",e),null}}getClient(){return this._client}async _sendSignal(e){try{return await this.getClient().post(this.getClient().baseURL+"/signal",{...e,cid:this.cid||e.cid,is_video:this.callType==="video"||e.is_video,ios:!1,session_id:this.sessionID})}catch(t){let s=e.action;if(s==="health-call")return;if(typeof this.onError=="function")if(t.code==="ERR_NETWORK")s==="create-call"&&this.onError("Unable to make the call. Please check your network connection");else if(t.response.data.ermis_code===20)this.onError("Recipient was busy");else{let i=t.response.data?.message?t.response.data?.message:"Call failed";this.onError(i)}}}async getAvailableDevices(){try{let e=await navigator.mediaDevices.enumerateDevices(),t=e.filter(i=>i.kind==="audioinput"),s=e.filter(i=>i.kind==="videoinput");return this.availableAudioDevices=t,this.availableVideoDevices=s,{audioDevices:t,videoDevices:s}}catch(e){return console.error("Error enumerating devices:",e),{audioDevices:[],videoDevices:[]}}}async getMediaConstraints(){let{audioDevices:e,videoDevices:t}=await this.getAvailableDevices();this.onDeviceChange&&this.onDeviceChange(e,t),!this.selectedAudioDeviceId&&e.length>0&&(this.selectedAudioDeviceId=e[0].deviceId),!this.selectedVideoDeviceId&&t.length>0&&(this.selectedVideoDeviceId=t[0].deviceId);let s={deviceId:this.selectedAudioDeviceId?{exact:this.selectedAudioDeviceId}:void 0,echoCancellation:!0,noiseSuppression:!0,sampleRate:48e3},i=this.callType==="video"?{deviceId:this.selectedVideoDeviceId?{exact:this.selectedVideoDeviceId}:void 0,width:640,height:360}:!1;return{audio:s,video:i}}async startLocalStream(){let e=await this.getMediaConstraints();try{let t=await navigator.mediaDevices.getUserMedia(e);return this.applyLocalStream(t)}catch(t){if(console.warn("Error getting user media:",t?.message),this.callType==="video"&&e.video)try{let s=await navigator.mediaDevices.getUserMedia({audio:e.audio,video:!1});return this.setConnectionMessage("Camera not available, using audio only"),this.applyLocalStream(s)}catch{}return typeof this.onError=="function"&&this.onError("No microphone or camera found. Please check your device."),null}}applyLocalStream(e){if(this.callStatus==="ended"){e.getTracks().forEach(t=>t.stop()),this.destroy();return}return this.onLocalStream&&this.onLocalStream(e),this.localStream=e,e}setConnectionMessage(e){typeof this.onConnectionMessageChange=="function"&&this.onConnectionMessageChange(e)}setCallStatus(e){this.callStatus=e,typeof this.onCallStatus=="function"&&this.onCallStatus(e)}setUserInfo(e,t){if(!e||!t)return;let i=(e?this.getClient().activeChannels[e]:void 0)?.state?.members||{},a=Object.keys(i),r=t||"",o=a.find(p=>p!==r)||"",l=this.getClient().state.users[r],c=this.getClient().state.users[o];this.callerInfo={id:r,name:l?.name,avatar:l?.avatar||""},this.receiverInfo={id:o,name:c?.name,avatar:c?.avatar||""}}listenSocketEvents(){this.signalHandler=async e=>{let{action:t,user_id:s,session_id:i,cid:a,is_video:r,signal:o,metadata:l}=e;switch(t){case"create-call":if(s===this.userID&&i!==this.sessionID){this.isDestroyed=!0,this.destroy();return}if(this.isDestroyed=!1,this.callStatus="",this.callType=r?"video":"audio",this.setUserInfo(a,s),this.setCallStatus("ringing"),this.cid=a||"",this.metadata=l||{},typeof this.onCallEvent=="function"&&this.onCallEvent({type:s!==this.userID?"incoming":"outgoing",callType:r?"video":"audio",cid:a||"",callerInfo:this.callerInfo,receiverInfo:this.receiverInfo,metadata:this.metadata}),await this.startLocalStream(),this.callStatus==="ended")return;s!==this.userID&&await this.initialize(),this.localStream&&this.mediaSender&&this.mediaReceiver&&(this.mediaSender?.initEncoders(this.localStream),this.mediaReceiver?.initDecoders(this.callType)),s===this.userID&&(this.missCallTimeout&&clearTimeout(this.missCallTimeout),this.missCallTimeout=setTimeout(async()=>{await this.missCall()},6e4));break;case"accept-call":if(s===this.userID&&i!==this.sessionID){this.isDestroyed=!0,this.destroy();return}s!==this.userID&&!this.isDestroyed&&this.mediaReceiver&&this.mediaSender&&(await this.mediaReceiver.acceptConnection(),await this.mediaSender.sendConnected(),await this.mediaSender.sendConfigs());break;case"end-call":case"reject-call":case"miss-call":this.destroy();break}},this.connectionChangedHandler=e=>{let t=e.online;this.isOffline=!t,t?(this.setConnectionMessage(null),this.callStatus==="connected"&&(this.healthCallServerInterval||(this.healthCallServerInterval=setInterval(()=>{this.healthCall()},1e4)))):(this.setConnectionMessage("Your network connection is unstable"),this.healthCallInterval&&(clearInterval(this.healthCallInterval),this.healthCallInterval=null),this.healthCallServerInterval&&(clearInterval(this.healthCallServerInterval),this.healthCallServerInterval=null))},this.messageUpdatedHandler=e=>{if(this.callStatus==="connected"&&e.cid===this.cid){let t=e.user?.id,s;t===this.callerInfo?.id?s=this.callerInfo:t===this.receiverInfo?.id&&(s=this.receiverInfo),s&&typeof this.onUpgradeCall=="function"&&this.onUpgradeCall(s)}},this._client.on("signal",this.signalHandler),this._client.on("connection.changed",this.connectionChangedHandler),this._client.on("message.updated",this.messageUpdatedHandler)}cleanupCall(){this.mediaSender&&(this.mediaSender?.stop(),this.mediaSender=null),this.mediaReceiver&&(this.mediaReceiver.stop(),this.mediaReceiver=null),this.callNode&&(this.callNode?.closeEndpoint(),this.callStatus==="connected"&&this.callNode?.closeConnection(),this.callNode=null),this.missCallTimeout&&(clearTimeout(this.missCallTimeout),this.missCallTimeout=null),this.healthCallInterval&&(clearInterval(this.healthCallInterval),this.healthCallInterval=null),this.healthCallServerInterval&&(clearInterval(this.healthCallServerInterval),this.healthCallServerInterval=null),this.healthCallTimeout&&(clearTimeout(this.healthCallTimeout),this.healthCallTimeout=null),this.healthCallWarningTimeout&&(clearTimeout(this.healthCallWarningTimeout),this.healthCallWarningTimeout=null),this.setConnectionMessage(null),this.cid="",this.callType="",this.metadata={},this.localStream&&(this.localStream.getTracks().forEach(e=>e.stop()),this.localStream=null),this.remoteStream&&(this.remoteStream.getTracks().forEach(e=>e.stop()),this.remoteStream=null),this.setCallStatus("ended")}destroy(){this.cleanupCall()}async getDevices(){return this.availableAudioDevices.length>0||this.availableVideoDevices.length>0?{audioDevices:this.availableAudioDevices,videoDevices:this.availableVideoDevices}:await this.getAvailableDevices()}getSelectedDevices(){let e=this.selectedAudioDeviceId?this.availableAudioDevices.find(s=>s.deviceId===this.selectedAudioDeviceId):void 0,t=this.selectedVideoDeviceId?this.availableVideoDevices.find(s=>s.deviceId===this.selectedVideoDeviceId):void 0;return{audioDevice:e,videoDevice:t}}getDefaultDevices(){return{audioDevice:this.availableAudioDevices[0],videoDevice:this.availableVideoDevices[0]}}async createCall(e,t){try{this.cid=t;let s=await this.getLocalEndpointAddr();await this._sendSignal({action:"create-call",cid:t,is_video:e==="video",metadata:{address:s}})}catch(s){throw console.error("Failed to create call:",s),s}}async acceptCall(){try{if(await this._sendSignal({action:"accept-call"}),this.mediaSender){let e=this.metadata?.address||"";await this.mediaSender.connect(e)}}catch(e){throw console.error("Failed to accept call:",e),e}}async endCall(){await this._sendSignal({action:"end-call"}),this.destroy()}async rejectCall(){await this._sendSignal({action:"reject-call"}),this.destroy()}async missCall(){await this._sendSignal({action:"miss-call"}),this.destroy()}async connectCall(){return await this._sendSignal({action:"connect-call"})}async healthCall(){return await this._sendSignal({action:"health-call"})}async addVideoTrackToLocalStream(){let e=await this.getMediaConstraints(),t=await navigator.mediaDevices.getUserMedia(e),s=t.getVideoTracks()[0];this.localStream?(this.localStream.addTrack(s),this.onLocalStream&&this.onLocalStream(this.localStream)):(this.localStream=t,this.onLocalStream&&this.onLocalStream(this.localStream))}async upgradeCall(){try{if(this.callType="video",await this.addVideoTrackToLocalStream(),await this._sendSignal({action:"upgrade-call"}),this.localStream){this.mediaSender?.initVideoEncoder(this.localStream?.getVideoTracks()[0]);let e=!!this.localStream?.getAudioTracks().some(s=>s.enabled),t=!!this.localStream?.getVideoTracks().some(s=>s.enabled);await this.mediaSender?.sendTransceiverState(e,t)}}catch(e){throw console.error("Failed to upgrade call:",e),e}}async requestUpgradeCall(e){if(e&&(this.callType="video",await this.addVideoTrackToLocalStream(),this.localStream)){this.mediaSender?.initVideoEncoder(this.localStream?.getVideoTracks()[0]);let t=!!this.localStream?.getAudioTracks().some(i=>i.enabled),s=!!this.localStream?.getVideoTracks().some(i=>i.enabled);await this.mediaSender?.sendTransceiverState(t,s)}}async startScreenShare(){if(!navigator.mediaDevices.getDisplayMedia)throw new Error("Screen sharing is not supported in this browser.");let e=await navigator.mediaDevices.getDisplayMedia({video:!0}),t=e.getVideoTracks()[0];this.localStream?(this.localStream.getVideoTracks().forEach(s=>s.stop()),this.localStream.removeTrack(this.localStream.getVideoTracks()[0]),this.localStream.addTrack(t)):this.localStream=e,t.onended=()=>{this.stopScreenShare()},this.onLocalStream&&(this.onLocalStream(this.localStream),this.mediaSender?.replaceVideoTrack(this.localStream.getVideoTracks()[0])),typeof this.onScreenShareChange=="function"&&this.onScreenShareChange(!0)}async stopScreenShare(){let e=await this.getMediaConstraints();try{let t=await navigator.mediaDevices.getUserMedia({video:e.video,audio:!1}),s=t.getVideoTracks()[0];this.localStream?(this.localStream.getVideoTracks().forEach(i=>{i.stop(),this.localStream?.removeTrack(i)}),this.localStream.addTrack(s)):this.localStream=t,this.onLocalStream&&(this.onLocalStream(this.localStream),this.mediaSender?.replaceVideoTrack(this.localStream.getVideoTracks()[0])),typeof this.onScreenShareChange=="function"&&this.onScreenShareChange(!1)}catch(t){console.error("Error stopping screen share and reverting to camera:",t)}}async toggleMic(e){if(this.localStream){this.localStream.getAudioTracks().forEach(i=>{i.enabled=e});let t=e,s=this.localStream.getVideoTracks().some(i=>i.enabled);await this.mediaSender?.sendTransceiverState(t,s)}}async toggleCamera(e){if(this.localStream){this.localStream.getVideoTracks().forEach(i=>{i.enabled=e});let t=this.localStream.getAudioTracks().some(i=>i.enabled),s=e;await this.mediaSender?.sendTransceiverState(t,s)}}async switchAudioDevice(e){try{if(!this.availableAudioDevices.find(r=>r.deviceId===e))return console.error("Audio device not found:",e),this.onError&&this.onError("Selected microphone not found"),!1;if(this.selectedAudioDeviceId=e,!this.localStream)return!1;let i=(await navigator.mediaDevices.getUserMedia({audio:{deviceId:{exact:e}},video:!1})).getAudioTracks()[0],a=this.localStream.getAudioTracks()[0];return a&&(this.localStream.removeTrack(a),a.stop()),this.localStream.addTrack(i),this.onLocalStream&&this.onLocalStream(this.localStream),!0}catch(t){return console.error("Error switching audio device:",t),this.onError&&this.onError("Failed to switch microphone"),!1}}async switchVideoDevice(e){try{if(!this.availableVideoDevices.find(r=>r.deviceId===e))return console.error("Video device not found:",e),this.onError&&this.onError("Selected camera not found"),!1;if(this.selectedVideoDeviceId=e,!this.localStream)return!1;let i=(await navigator.mediaDevices.getUserMedia({audio:!1,video:{deviceId:{exact:e}}})).getVideoTracks()[0],a=this.localStream.getVideoTracks()[0];return a&&(this.localStream.removeTrack(a),a.stop()),this.localStream.addTrack(i),this.onLocalStream&&this.onLocalStream(this.localStream),!0}catch(t){return console.error("Error switching video device:",t),this.onError&&this.onError("Failed to switch camera"),!1}}setupDeviceChangeListener(){navigator.mediaDevices.addEventListener("devicechange",async()=>{let{audioDevices:e,videoDevices:t}=await this.getAvailableDevices();this.onDeviceChange&&this.onDeviceChange(e,t)})}};pt();var Za=class{apiKey;baseURL;options;axiosInstance;disconnected;browser;node;logger;consecutiveFailures;userAgent;lastIdentifier;lastMethod;address;constructor(e,t,s){let i=s||{};this.apiKey=e,this.baseURL=s?.userBaseURL||t+"/uss/v1",this.browser=typeof i.browser<"u"?i.browser:typeof window<"u",this.node=!this.browser,this.options={withCredentials:!1,warmUp:!1,recoverStateOnReconnect:!0,...i},this.node&&!this.options.httpsAgent&&(this.options.httpsAgent=new yt.Agent({keepAlive:!0,keepAliveMsecs:3e3})),this.axiosInstance=rn.create(this.options),this.logger=Ms(i.logger)?i.logger:()=>null,this.consecutiveFailures=0,this.disconnected=!1}_logApiRequest(e,t,s,i){this.logger("info",`client: ${e} - Request - ${t}- ${JSON.stringify(s)} - ${JSON.stringify(i.params)}`,{tags:["api","api_request","client"],url:t,payload:s,config:i})}_logApiResponse(e,t,s){this.logger("info",`client:${e} - Response - url: ${t} > status ${s.status}`,{tags:["api","api_response","client"],url:t,response:s})}_logApiError(e,t,s,i){this.logger("error",`client:${e} - Error: ${JSON.stringify(s)} - url: ${t} - options: ${JSON.stringify(i)}`,{tags:["api","api_response","client"],url:t,error:s})}doAxiosRequest=async(e,t,s,i={})=>{let a=this._enrichAxiosOptions(i);try{let r;switch(this._logApiRequest(e,t,s,a),e){case"get":r=await this.axiosInstance.get(t,a);break;case"delete":r=await this.axiosInstance.delete(t,a);break;case"post":r=await this.axiosInstance.post(t,s,a);break;case"postForm":r=await this.axiosInstance.postForm(t,s,a);break;case"put":r=await this.axiosInstance.put(t,s,a);break;case"patch":r=await this.axiosInstance.patch(t,s,a);break;case"options":r=await this.axiosInstance.options(t,a);break;default:throw new Error("Invalid request type")}return this._logApiResponse(e,t,r),this.consecutiveFailures=0,this.handleResponse(r)}catch(r){if(r.client_request_id=a.headers?.["x-client-request-id"],this._logApiError(e,t,r,i),this.consecutiveFailures+=1,r.response)return r.response.data.code===mt.TOKEN_EXPIRED?(this.consecutiveFailures>1&&await on(js(this.consecutiveFailures)),await this.doAxiosRequest(e,t,s,a)):this.handleResponse(r.response);throw r}};get(e,t){return this.doAxiosRequest("get",e,null,{params:t})}put(e,t){return this.doAxiosRequest("put",e,t)}post(e,t,s){return this.doAxiosRequest("post",e,t,{params:s})}patch(e,t){return this.doAxiosRequest("patch",e,t)}delete(e,t){return this.doAxiosRequest("delete",e,null,{params:t})}errorFromResponse(e){let t;return t=new Mt(`ErmisChat error HTTP code: ${e.status}`),e.data&&e.data.code&&(t=new Error(`ErmisChat error code ${e.data.code}: ${e.data.message}`),t.code=e.data.code),t.response=e,t.status=e.status,t}handleResponse(e){let t=e.data;if(Hs(e))throw this.errorFromResponse(e);return t}getUserAgent(){return this.userAgent||`ermis-chat-sdk-javascript-client-${this.node?"node":"browser"}-1.0.7`}setUserAgent(e){this.userAgent=e}_enrichAxiosOptions(e={params:{},headers:{},config:{}}){let t=null;e.headers?.["x-client-request-id"]||(e.headers={...e.headers,"x-client-request-id":Ue()});let{params:s,headers:i,...a}=this.options?.axiosRequestConfig||{};return{params:{...e.params,...s||{}},headers:{"X-Stream-Client":this.getUserAgent(),...e.headers,...i||{}},...t?{signal:t}:{},...e.config,...a||{}}}async sendOtpToPhone(e,t){this.lastIdentifier=e,this.lastMethod=t;let s={apikey:this.apiKey,identifier:e,language:"Vi",method:t,otp_type:"Login"};return this.post(this.baseURL+"/auth/get_otp_new",s)}async sendOtpToEmail(e){this.lastIdentifier=e,this.lastMethod="Email";let t={apikey:this.apiKey,identifier:e,language:"Vi",method:"Email",otp_type:"Login"};return this.post(this.baseURL+"/auth/get_otp_new",t)}async verifyOtp(e){let t={identifier:this.lastIdentifier,method:this.lastMethod,apikey:this.apiKey,otp:e};return this.post(this.baseURL+"/auth/otp_login",t)}async loginWithGoogle(e){let t={token:e,apikey:this.apiKey};return this.post(this.baseURL+"/auth/google_login",t)}async getWalletChallenge(e){this.address=e;let t=await this.post(this.baseURL+"/auth/get_challenge",{address:e,apikey:this.apiKey});return JSON.parse(t.challenge)}createNonce(e){let t="",s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",i=s.length;for(let a=0;a<e;a++)t+=s.charAt(Math.floor(Math.random()*i));return t}async verifyWalletSignature(e){let t={address:this.address,signature:e,nonce:this.createNonce(20),apikey:this.apiKey};return this.post(this.baseURL+"/auth/verify_signature",t)}};var Kg={1e4:"10 seconds",3e4:"30 seconds",6e4:"1 minute",3e5:"5 minutes",9e5:"15 minutes",36e5:"60 minutes"};function er(n,e){return e[n]??n}function Kp(n,e){if(!n||typeof n!="string")return n??"";let t=n.trim();if(!t)return"";let s=t.split(" "),i=s[0],a=s[1]??"",r=a?er(a,e):"User";switch(i){case"1":{let o=s.slice(2).join(" ");return`${r} changed the channel name to ${o}.`}case"2":return`${r} changed the channel avatar.`;case"3":return`${r} changed the channel description.`;case"4":return`${r} was removed from the channel.`;case"5":return`${r} was banned.`;case"6":return`${r} was unbanned.`;case"7":return`${r} was promoted to moderator.`;case"8":return`${r} was demoted from moderator.`;case"9":return`${r}'s permissions were updated.`;case"10":return`${r} joined the channel.`;case"11":return`${r} declined the channel invitation.`;case"12":return`${r} left the channel.`;case"13":return`${r} cleared the chat history.`;case"14":{let l=(s[2]??"")==="true"?"public":"private";return`${r} changed the channel to ${l}.`}case"15":{let o=s[2]??"0";if(o==="0")return`${r} disabled cooldown.`;let l=Kg[o]??`${o}ms`;return`${r} enabled cooldown for ${l}.`}case"16":return`${r} updated the banned words.`;case"17":return`${r} was added to the channel.`;case"18":{let o=s[1]??"",l=s[2]??"",c=o?er(o,e):"User",p=l?er(l,e):"User";return`Admin ${c} left and assigned ${p} as the new admin.`}case"19":return`${r} pinned a message.`;case"20":return`${r} unpinned a message.`;default:return t}}var ze={AUDIO:"audio",VIDEO:"video"};function Jg(n){if(!n)return"";let e=parseInt(n,10);if(isNaN(e)||e<=0)return"";let t=Math.floor(e/1e3),s=Math.floor(t/60),i=t%60;return`${s} min, ${i} sec`}function Jp(n,e){if(!n||typeof n!="string")return null;let t=n.trim();if(!t)return null;let s=t.split(" "),i=parseInt(s[0],10),a=s[1]??"",r=e===a,o="",l="",c="",p="";(i===3||i===6)&&(o=s[2]??"",l=s[3]==="0"?"":s[3]??"");let u;switch(i){case 1:u=r?"Calling...":"Incoming audio call...",c=ze.AUDIO,p="#54D62C";break;case 2:u=r?"Outgoing audio call":"You missed audio call",c=ze.AUDIO,p="#FF4842";break;case 3:l?(u=r?"Outgoing audio call":"Incoming audio call",p="#54D62C"):(o===e?u="You cancel audio call":u="You missed audio call",p="#FF4842"),c=ze.AUDIO;break;case 4:u=r?"Calling...":"Incoming video call...",c=ze.VIDEO,p="#54D62C";break;case 5:u=r?"Outgoing video call":"You missed video call",c=ze.VIDEO,p="#FF4842";break;case 6:l?(u=r?"Outgoing video call":"Incoming video call",p="#54D62C"):(o===e?u="You cancel video call":u="You missed video call",p="#FF4842"),c=ze.VIDEO;break;case 7:u=r?"Recipient rejected audio call":"You rejected audio call",c=ze.AUDIO,p="#FF4842";break;case 8:u=r?"Recipient rejected video call":"You rejected video call",c=ze.VIDEO,p="#FF4842";break;case 9:u=r?"Recipient was busy":"You missed audio call",c=ze.AUDIO,p="#FF4842";break;case 10:u=r?"Recipient was busy":"You missed video call",c=ze.VIDEO,p="#FF4842";break;default:u=t,c="",p=""}return{text:u,duration:Jg(l),callType:c,color:p}}return bn(Xg);})();
22
22
  //! NOTE: check lai o day
23
23
  /*! Bundled license information:
24
24