1import{getDefaultExportFromCjs as ll}from"./react-core-chunk-B2r03cU8.js";try{(function(){var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c0df115a-dee1-4782-8715-0ece44a81a7f",e._sentryDebugIdIdentifier="sentry-dbid-c0df115a-dee1-4782-8715-0ece44a81a7f")})()}catch{}var et={},Tn;function cl(){if(Tn)return et;Tn=1,et.byteLength=o,et.toByteArray=c,et.fromByteArray=f;for(var e=[],t=[],s=typeof Uint8Array<"u"?Uint8Array:Array,i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",n=0,r=i.length;n<r;++n)e[n]=i[n],t[i.charCodeAt(n)]=n;t[45]=62,t[95]=63;function a(p){var y=p.length;if(y%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var w=p.indexOf("=");w===-1&&(w=y);var m=w===y?0:4-w%4;return[w,m]}function o(p){var y=a(p),w=y[0],m=y[1];return(w+m)*3/4-m}function l(p,y,w){return(y+w)*3/4-w}function c(p){var y,w=a(p),m=w[0],g=w[1],_=new s(l(p,m,g)),b=0,R=g>0?m-4:m,v;for(v=0;v<R;v+=4)y=t[p.charCodeAt(v)]<<18|t[p.charCodeAt(v+1)]<<12|t[p.charCodeAt(v+2)]<<6|t[p.charCodeAt(v+3)],_[b++]=y>>16&255,_[b++]=y>>8&255,_[b++]=y&255;return g===2&&(y=t[p.charCodeAt(v)]<<2|t[p.charCodeAt(v+1)]>>4,_[b++]=y&255),g===1&&(y=t[p.charCodeAt(v)]<<10|t[p.charCodeAt(v+1)]<<4|t[p.charCodeAt(v+2)]>>2,_[b++]=y>>8&255,_[b++]=y&255),_}function d(p){return e[p>>18&63]+e[p>>12&63]+e[p>>6&63]+e[p&63]}function h(p,y,w){for(var m,g=[],_=y;_<w;_+=3)m=(p[_]<<16&16711680)+(p[_+1]<<8&65280)+(p[_+2]&255),g.push(d(m));return g.join("")}function f(p){for(var y,w=p.length,m=w%3,g=[],_=16383,b=0,R=w-m;b<R;b+=_)g.push(h(p,b,b+_>R?R:b+_));return m===1?(y=p[w-1],g.push(e[y>>2]+e[y<<4&63]+"==")):m===2&&(y=(p[w-2]<<8)+p[w-1],g.push(e[y>>10]+e[y>>4&63]+e[y<<2&63]+"=")),g.join("")}return et}var dl=cl();function br(e,t){return function(){return e.apply(t,arguments)}}const{toString:hl}=Object.prototype,{getPrototypeOf:We}=Object,{iterator:Rt,toStringTag:Cr}=Symbol,Zt=(({hasOwnProperty:e})=>(t,s)=>e.call(t,s))(Object.prototype),mt=(e,t)=>{let s=e;const i=[];for(;s!=null&&s!==Object.prototype;){if(i.indexOf(s)!==-1)return!1;if(i.push(s),Zt(s,t))return!0;s=We(s)}return!1},ul=(e,t)=>
vendor: 8,403 bytes, lines 1-2
1e!=null&&mt(e,t)?e[t]:void 0,Bi=(e=>t=>{const s=hl.call(t);return e[s]||(e[s]=s.slice(8,-1).toLowerCase())})(Object.create(null)),Y=e=>(e=e.toLowerCase(),t=>Bi(t)===e),Os=e=>t=>typeof t===e,{isArray:Le}=Array,ze=Os("undefined");function Qe(e){return e!==null&&!ze(e)&&e.constructor!==null&&!ze(e.constructor)&&$(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const Sr=Y("ArrayBuffer");function fl(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&Sr(e.buffer),t}const pl=Os("string"),$=Os("function"),vr=Os("number"),Ge=e=>e!==null&&typeof e=="object",gl=e=>e===!0||e===!1,$t=e=>{if(!Ge(e))return!1;const t=We(e);return(t===null||t===Object.prototype||We(t)===null)&&!mt(e,Cr)&&!mt(e,Rt)},ml=e=>{if(!Ge(e)||Qe(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},yl=Y("Date"),_l=Y("File"),wl=e=>!!(e&&typeof e.uri<"u"),bl=e=>e&&typeof e.getParts<"u",Cl=Y("Blob"),Sl=Y("FileList"),vl=e=>Ge(e)&&$(e.pipe);function Rl(){return typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof globalThis<"u"?globalThis:{}}const Ln=Rl(),In=typeof Ln.FormData<"u"?Ln.FormData:void 0,El=e=>{if(!e)return!1;if(In&&e instanceof In)return!0;const t=We(e);if(!t||t===Object.prototype||!$(e.append))return!1;const s=Bi(e);return s==="formdata"||s==="object"&&$(e.toString)&&e.toString()==="[object FormData]"},xl=Y("URLSearchParams"),[Ml,Al,Ul,Tl]=["ReadableStream","Request","Response","Headers"].map(Y),Ll=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function Et(e,t,{allOwnKeys:s=!1}={}){if(e===null||typeof e>"u")return;let i,n;if(typeof e!="object"&&(e=[e]),Le(e))for(i=0,n=e.length;i<n;i++)t.call(null,e[i],i,e);else{if(Qe(e))return;const r=s?Object.getOwnPropertyNames(e):Object.keys(e),a=r.length;let o;for(i=0;i<a;i++)o=r[i],t.call(null,e[o],o,e)}}function Rr(e,t){if(Qe(e))return null;t=t.toLowerCase();const s=Object.keys(e);let i=s.length,n;for(;i-- >0;)if(n=s[i],t===n.toLowerCase())return n;return null}const xe=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:globalThis,Er=e=>!ze(e)&&e!==xe;function ri(...e){const{caseless:t,skipUndefined:s}=Er(this)&&this||{},i={},n=(r,a)=>{if(a==="__proto__"||a==="constructor"||a==="prototype")return;const o=t&&typeof a=="string"&&Rr(i,a)||a,l=Zt(i,o)?i[o]:void 0;$t(l)&&$t(r)?i[o]=ri(l,r):$t(r)?i[o]=ri({},r):Le(r)?i[o]=r.slice():(!s||!ze(r))&&(i[o]=r)};for(let r=0,a=e.length;r<a;r++){const o=e[r];if(!o||Qe(o)||(Et(o,n),typeof o!="object"||Le(o)))continue;const l=Object.getOwnPropertySymbols(o);for(let c=0;c<l.length;c++){const d=l[c];Vl.call(o,d)&&n(o[d],d)}}return i}const Il=(e,t,s,{allOwnKeys:i}={})=>(Et(t,(n,r)=>{s&&$(n)?Object.defineProperty(e,r,{__proto__:null,value:br(n,s),writable:!0,enumerable:!0,configurable:!0}):Object.defineProperty(e,r,{__proto__:null,value:n,writable:!0,enumerable:!0,configurable:!0})},{allOwnKeys:i}),e),Dl=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),Ol=(e,t,s,i)=>{e.prototype=Object.create(t.prototype,i),Object.defineProperty(e.prototype,"constructor",{__proto__:null,value:e,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(e,"super",{__proto__:null,value:t.prototype}),s&&Object.assign(e.prototype,s)},Pl=(e,t,s,i)=>{let n,r,a;const o={};if(t=t||{},e==null)return t;do{for(n=Object.getOwnPropertyNames(e),r=n.length;r-- >0;)a=n[r],(!i||i(a,e,t))&&!o[a]&&(t[a]=e[a],o[a]=!0);e=s!==!1&&We(e)}while(e&&(!s||s(e,t))&&e!==Object.prototype);return t},kl=(e,t,s)=>{e=String(e),(s===void 0||s>e.length)&&(s=e.length),s-=t.length;const i=e.indexOf(t,s);return i!==-1&&i===s},Nl=e=>{if(!e)return null;if(Le(e))return e;let t=e.length;if(!vr(t))return null;const s=new Array(t);for(;t-- >0;)s[t]=e[t];return s},Fl=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&We(Uint8Array)),Bl=(e,t)=>{const i=(e&&e[Rt]).call(e);let n;for(;(n=i.next())&&!n.done;){const r=n.value;t.call(e,r[0],r[1])}},ql=(e,t)=>{let s;const i=[];for(;(s=e.exec(t))!==null;)i.push(s);return i},$l=Y("HTMLFormElement"),Hl=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(s,i,n){return i.toUpperCase()+n}),{propertyIsEnumerable:Vl}=Object.prototype,jl=Y("RegExp"),xr=(e,t)=>{const s=Object.getOwnPropertyDescriptors(e),i={};Et(s,(n,r)=>{let a;(a=t(n,r,e))!==!1&&(i[r]=a||n)}),Object.defineProperties(e,i)},Wl=e=>{xr(e,(t,s)=>{if($(e)&&["arguments","caller","callee"].includes(s))return!1;const i=e[s];if($(i)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+s+"'")})}})},zl=(e,t)=>{const s={},i=n=>{n.forEach(r=>{s[r]=!0})};return Le(e)?i(e):i(String(e).split(t)),s},Ql=()=>{},Gl=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function Kl(e){return!!(e&&$(e.append)&&e[Cr]==="FormData"&&e[Rt])}const Jl=e=>{const t=new WeakSet,s=i=>{if(Ge(i)){if(t.has(i))return;if(Qe(i))return i;if(!("toJSON"in i)){t.add(i);const n=Le(i)?[]:{};return Et(i,(r,a)=>{const o=s(r);!ze(o)&&(n[a]=o)}),t.delete(i),n}}return i};return s(e)},Xl=Y("AsyncFunction"),Yl=e=>e&&(Ge(e)||$(e))&&$(e.then)&&$(e.catch),Mr=((e,t)=>e?setImmediate:t?((s,i)=>(xe.addEventListener("message",({source:n,data:r})=>{n===xe&&r===s&&i.length&&i.shift()()},!1),n=>{i.push(n),xe.postMessage(s,"*")}))(`axios@${Math.random()}`,[]):s=>setTimeout(s))(typeof setImmediate=="function",$(xe.postMessage)),Zl=typeof queueMicrotask<"u"?queueMicrotask.bind(xe):typeof process<"u"&&process.nextTick||Mr,Ar=e=>e!=null&&$(e[Rt]),ec=e=>e!=null&&mt(e,Rt)&&Ar(e),u={isArray:Le,isArrayBuffer:Sr,isBuffer:Qe,isFormData:El,isArrayBufferView:fl,isString:pl,isNumber:vr,isBoolean:gl,isObject:Ge,isPlainObject:$t,isEmptyObject:ml,isReadableStream:Ml,isRequest:Al,isResponse:Ul,isHeaders:Tl,isUndefined:ze,isDate:yl,isFile:_l,isReactNativeBlob:wl,isReactNative:bl,isBlob:Cl,isRegExp:jl,isFunction:$,isStream:vl,isURLSearchParams:xl,isTypedArray:Fl,isFileList:Sl,forEach:Et,merge:ri,extend:Il,trim:Ll,stripBOM:Dl,inherits:Ol,toFlatObject:Pl,kindOf:Bi,kindOfTest:Y,endsWith:kl,toArray:Nl,forEachEntry:Bl,matchAll:ql,isHTMLForm:$l,hasOwnProperty:Zt,hasOwnProp:Zt,hasOwnInPrototypeChain:mt,getSafeProp:ul,reduceDescriptors:xr,freezeMethods:Wl,toObjectSet:zl,toCamelCase:Hl,noop:Ql,toFiniteNumber:Gl,findKey:Rr,global:xe,isContextDefined:Er,isSpecCompliantForm:Kl,toJSONObject:Jl,isAsyncFn:Xl,isThenable:Yl,setImmediate:Mr,asap:Zl,isIterable:Ar,isSafeIterable:ec},tc=u.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),sc=e=>{const t={};let s,i,n;return e&&e.split(` 2`).forEach(function(a){n=a.indexOf(":"),s=a.substring(0,n).trim().toLowerCase(),i=a.substring(n+1).trim(),!(!s||t[s]&&tc[s])&&(s==="set-cookie"?t[s]?t[s].push(i):t[s]=[i]:t[s]=t[s]?t[s]+", "+i:i)}),t};function ic(e){let t=0,s=e.length;for(;t<s;){const i=e.charCodeAt(t);if(i!==9&&i!==32)break;t+=1}for(;s>t;){const i=e.charCodeAt(s-1);if(i!==9&&i!==32)break;s-=1}return t===0&&s===e.length?e:e.slice(t,s)}const nc=new RegExp("[\\u0000-\\u0008\\u000a-\\u001f\\u007f]+","g"),rc=new RegExp("[^\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+","g");function qi(e,t){return u.isArray(e)?e.map(s=>qi(s,t)):ic(String(e).replace(t,""))}const ac=e=>qi(e,nc),oc=e=>qi(e,rc);function Ur(e){const t=Object.create(null);return u.forEach(e.toJSON(),(s,i)=>{t[i]=oc(s)}),t}const Dn=Symbol("internals");function tt(e){return e&&String(e).trim().toLowerCase()}function Ht(e){return e===!1||e==null?e:u.isArray(e)?e.map(Ht):ac(String(e))}function lc(e){const t=Object.create(null),s=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let i;for(;i=s.exec(e);)t[i[1]]=i[2];return t}const cc=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function Hs(e,t,s,i,n){if(u.isFunction(i))return i.call(this,t,s);if(n&&(t=s),!!u.isString(t)){if(u.isString(i))return t.indexOf(i)!==-1;if(u.isRegExp(i))return i.test(t)}}function dc(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,s,i)=>s.toUpperCase()+i)}function hc(e,t){const s=u.toCamelCase(" "+t);["get","set","has"].forEach(i=>{Object.defineProperty(e,i+s,{__proto__:null,value:function(n,r,a){return this[i].call(this,t,n,r,a)},configurable:!0})})}let F=class{constructor(t){t&&this.set(t)}set(t,s,i){const n=this;function r(o,l,c){const d=tt(l);if(!d)return;
vendor: 7,009 bytes, lines 2-3
2const h=u.findKey(n,d);(!h||n[h]===void 0||c===!0||c===void 0&&n[h]!==!1)&&(n[h||l]=Ht(o))}const a=(o,l)=>u.forEach(o,(c,d)=>r(c,d,l));if(u.isPlainObject(t)||t instanceof this.constructor)a(t,s);else if(u.isString(t)&&(t=t.trim())&&!cc(t))a(sc(t),s);else if(u.isObject(t)&&u.isSafeIterable(t)){let o=Object.create(null),l,c;for(const d of t){if(!u.isArray(d))throw new TypeError("Object iterator must return a key-value pair");c=d[0],u.hasOwnProp(o,c)?(l=o[c],o[c]=u.isArray(l)?[...l,d[1]]:[l,d[1]]):o[c]=d[1]}a(o,s)}else t!=null&&r(s,t,i);return this}get(t,s){if(t=tt(t),t){const i=u.findKey(this,t);if(i){const n=this[i];if(!s)return n;if(s===!0)return lc(n);if(u.isFunction(s))return s.call(this,n,i);if(u.isRegExp(s))return s.exec(n);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,s){if(t=tt(t),t){const i=u.findKey(this,t);return!!(i&&this[i]!==void 0&&(!s||Hs(this,this[i],i,s)))}return!1}delete(t,s){const i=this;let n=!1;function r(a){if(a=tt(a),a){const o=u.findKey(i,a);o&&(!s||Hs(i,i[o],o,s))&&(delete i[o],n=!0)}}return u.isArray(t)?t.forEach(r):r(t),n}clear(t){const s=Object.keys(this);let i=s.length,n=!1;for(;i--;){const r=s[i];(!t||Hs(this,this[r],r,t,!0))&&(delete this[r],n=!0)}return n}normalize(t){const s=this,i={};return u.forEach(this,(n,r)=>{const a=u.findKey(i,r);if(a){s[a]=Ht(n),delete s[r];return}const o=t?dc(r):String(r).trim();o!==r&&delete s[r],s[o]=Ht(n),i[o]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){const s=Object.create(null);return u.forEach(this,(i,n)=>{i!=null&&i!==!1&&(s[n]=t&&u.isArray(i)?i.join(", "):i)}),s}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,s])=>t+": "+s).join(` 3`)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...s){const i=new this(t);return s.forEach(n=>i.set(n)),i}static accessor(t){const i=(this[Dn]=this[Dn]={accessors:{}}).accessors,n=this.prototype;function r(a){const o=tt(a);i[o]||(hc(n,a),i[o]=!0)}return u.isArray(t)?t.forEach(r):r(t),this}};F.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);u.reduceDescriptors(F.prototype,({value:e},t)=>{let s=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(i){this[s]=i}}});u.freezeMethods(F);const uc="[REDACTED ****]";function fc(e){if(u.hasOwnProp(e,"toJSON"))return!0;let t=Object.getPrototypeOf(e);for(;t&&t!==Object.prototype;){if(u.hasOwnProp(t,"toJSON"))return!0;t=Object.getPrototypeOf(t)}return!1}function pc(e,t){const s=new Set(t.map(r=>String(r).toLowerCase())),i=[],n=r=>{if(r===null||typeof r!="object"||u.isBuffer(r))return r;if(i.indexOf(r)!==-1)return;r instanceof F&&(r=r.toJSON()),i.push(r);let a;if(u.isArray(r))a=[],r.forEach((o,l)=>{const c=n(o);u.isUndefined(c)||(a[l]=c)});else{if(!u.isPlainObject(r)&&fc(r))return i.pop(),r;a=Object.create(null);for(const[o,l]of Object.entries(r)){const c=s.has(o.toLowerCase())?uc:n(l);u.isUndefined(c)||(a[o]=c)}}return i.pop(),a};return n(e)}let S=class Tr extends Error{static from(t,s,i,n,r,a){const o=new Tr(t.message,s||t.code,i,n,r);return Object.defineProperty(o,"cause",{__proto__:null,value:t,writable:!0,enumerable:!1,configurable:!0}),o.name=t.name,t.status!=null&&o.status==null&&(o.status=t.status),a&&Object.assign(o,a),o}constructor(t,s,i,n,r){super(t),Object.defineProperty(this,"message",{__proto__:null,value:t,enumerable:!0,writable:!0,configurable:!0}),this.name="AxiosError",this.isAxiosError=!0,s&&(this.code=s),i&&(this.config=i),n&&(this.request=n),r&&(this.response=r,this.status=r.status)}toJSON(){const t=this.config,s=t&&u.hasOwnProp(t,"redact")?t.redact:void 0,i=u.isArray(s)&&s.length>0?pc(t,s):u.toJSONObject(t);return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:i,code:this.code,status:this.status}}};S.ERR_BAD_OPTION_VALUE="ERR_BAD_OPTION_VALUE";S.ERR_BAD_OPTION="ERR_BAD_OPTION";S.ECONNABORTED="ECONNABORTED";S.ETIMEDOUT="ETIMEDOUT";S.ECONNREFUSED="ECONNREFUSED";S.ERR_NETWORK="ERR_NETWORK";S.ERR_FR_TOO_MANY_REDIRECTS="ERR_FR_TOO_MANY_REDIRECTS";S.ERR_DEPRECATED="ERR_DEPRECATED";S.ERR_BAD_RESPONSE="ERR_BAD_RESPONSE";S.ERR_BAD_REQUEST="ERR_BAD_REQUEST";S.ERR_CANCELED="ERR_CANCELED";S.ERR_NOT_SUPPORT="ERR_NOT_SUPPORT";S.ERR_INVALID_URL="ERR_INVALID_URL";S.ERR_FORM_DATA_DEPTH_EXCEEDED="ERR_FORM_DATA_DEPTH_EXCEEDED";const gc=null,Lr=100;function ai(e){return u.isPlainObject(e)||u.isArray(e)}function Ir(e){return u.endsWith(e,"[]")?e.slice(0,-2):e}function Vs(e,t,s){return e?e.concat(t).map(function(n,r){return n=Ir(n),!s&&r?"["+n+"]":n}).join(s?".":""):t}function mc(e){return u.isArray(e)&&!e.some(ai)}const yc=u.toFlatObject(u,{},null,function(t){return/^is[A-Z]/.test(t)});function Ps(e,t,s){if(!u.isObject(e))throw new TypeError("target must be an object");t=t||new FormData,s=u.toFlatObject(s,{metaTokens:!0,dots:!1,indexes:!1},!1,function(_,b){return!u.isUndefined(b[_])});const i=s.metaTokens,n=s.visitor||y,r=s.dots,a=s.indexes,o=s.Blob||typeof Blob<"u"&&Blob,l=s.maxDepth===void 0?Lr:s.maxDepth,c=o&&u.isSpecCompliantForm(t),d=[];if(!u.isFunction(n))throw new TypeError("visitor must be a function");function h(g){if(g===null)return"";if(u.isDate(g))return g.toISOString();if(u.isBoolean(g))return g.toString();if(!c&&u.isBlob(g))throw new S("Blob is not supported. Use a Buffer instead.");if(u.isArrayBuffer(g)||u.isTypedArray(g)){if(c&&typeof o=="function")return new o([g]);if(typeof Buffer<"u")return Buffer.from(g);throw new S("Blob is not supported. Use a Buffer instead.",S.ERR_NOT_SUPPORT)}return g}function f(g){if(g>l)throw new S("Object is too deeply nested ("+g+" levels). Max depth: "+l,S.ERR_FORM_DATA_DEPTH_EXCEEDED)}function p(g,_){if(l===1/0)return JSON.stringify(g);const b=[];return JSON.stringify(g,function(v,M){if(!u.isObject(M))return M;for(;b.length&&b[b.length-1]!==this;)b.pop();return b.push(M),f(_+b.length-1),M})}function y(g,_,b){let R=g;if(u.isReactNative(t)&&u.isReactNativeBlob(g))return t.append(Vs(b,_,r),h(g)),!1;if(g&&!b&&typeof g=="object"){if(u.endsWith(_,"{}"))_=i?_:_.slice(0,-2),g=p(g,1);else if(u.isArray(g)&&mc(g)||(u.isFileList(g)||u.endsWith(_,"[]"))&&(R=u.toArray(g)))return _=Ir(_),R.forEach(function(M,P){!(u.isUndefined(M)||M===null)&&t.append(a===!0?Vs([_],P,r):a===null?_:_+"[]",h(M))}),!1}return ai(g)?!0:(t.append(Vs(b,_,r),h(g)),!1)}const w=Object.assign(yc,{defaultVisitor:y,convertValue:h,isVisitable:ai});function m(g,_,b=0){if(!u.isUndefined(g)){if(f(b),d.indexOf(g)!==-1)throw new Error("Circular reference detected in "+_.join("."));d.push(g),u.forEach(g,function(v,M){(!(u.isUndefined(v)||v===null)&&n.call(t,v,u.isString(M)?M.trim():M,_,w))===!0&&m(v,_?_.concat(M):[M],b+1)}),d.pop()}}if(!u.isObject(e))throw new TypeError("data must be an object");return m(e),t}
vendor: 3,579 bytes, line 3
3function On(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"};return encodeURIComponent(e).replace(/[!'()~]|%20/g,function(i){return t[i]})}function $i(e,t){this._pairs=[],e&&Ps(e,this,t)}const Dr=$i.prototype;Dr.append=function(t,s){this._pairs.push([t,s])};Dr.toString=function(t){const s=t?i=>t.call(this,i,On):On;return this._pairs.map(function(n){return s(n[0])+"="+s(n[1])},"").join("&")};function _c(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function Or(e,t,s){if(!t)return e;e=e||"";const i=u.isFunction(s)?{serialize:s}:s,n=u.getSafeProp(i,"encode")||_c,r=u.getSafeProp(i,"serialize");let a;if(r?a=r(t,i):a=u.isURLSearchParams(t)?t.toString():new $i(t,i).toString(n),a){const o=e.indexOf("#");o!==-1&&(e=e.slice(0,o)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}class Pn{constructor(){this.handlers=[]}use(t,s,i){return this.handlers.push({fulfilled:t,rejected:s,synchronous:i?i.synchronous:!1,runWhen:i?i.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){u.forEach(this.handlers,function(i){i!==null&&t(i)})}}const Hi={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1,legacyInterceptorReqResOrdering:!0,advertiseZstdAcceptEncoding:!1,validateStatusUndefinedResolves:!0},wc=typeof URLSearchParams<"u"?URLSearchParams:$i,bc=typeof FormData<"u"?FormData:null,Cc=typeof Blob<"u"?Blob:null,Sc={isBrowser:!0,classes:{URLSearchParams:wc,FormData:bc,Blob:Cc},protocols:["http","https","file","blob","url","data"]},Vi=typeof window<"u"&&typeof document<"u",oi=typeof navigator=="object"&&navigator||void 0,vc=Vi&&(!oi||["ReactNative","NativeScript","NS"].indexOf(oi.product)<0),Rc=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",Ec=Vi&&window.location.href||"http://localhost",xc=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:Vi,hasStandardBrowserEnv:vc,hasStandardBrowserWebWorkerEnv:Rc,navigator:oi,origin:Ec},Symbol.toStringTag,{value:"Module"})),O={...xc,...Sc};function Mc(e,t){return Ps(e,new O.classes.URLSearchParams,{visitor:function(s,i,n,r){return O.isNode&&u.isBuffer(s)?(this.append(i,s.toString("base64")),!1):r.defaultVisitor.apply(this,arguments)},...t})}const kn=Lr;function Pr(e){if(e>kn)throw new S("FormData field is too deeply nested ("+e+" levels). Max depth: "+kn,S.ERR_FORM_DATA_DEPTH_EXCEEDED)}function Ac(e){const t=[],s=/\w+|\[(\w*)]/g;let i;for(;(i=s.exec(e))!==null;)Pr(t.length),t.push(i[0]==="[]"?"":i[1]||i[0]);return t}function Uc(e){const t={},s=Object.keys(e);let i;const n=s.length;let r;for(i=0;i<n;i++)r=s[i],t[r]=e[r];return t}function kr(e){function t(s,i,n,r){Pr(r);let a=s[r++];if(a==="__proto__")return!0;const o=Number.isFinite(+a),l=r>=s.length;return a=!a&&u.isArray(n)?n.length:a,l?(u.hasOwnProp(n,a)?n[a]=u.isArray(n[a])?n[a].concat(i):[n[a],i]:n[a]=i,!o):((!u.hasOwnProp(n,a)||!u.isObject(n[a]))&&(n[a]=[]),t(s,i,n[a],r)&&u.isArray(n[a])&&(n[a]=Uc(n[a])),!o)}if(u.isFormData(e)&&u.isFunction(e.entries)){const s={};return u.forEachEntry(e,(i,n)=>{t(Ac(i),n,s,0)}),s}return null}const Ne=(e,t)=>e!=null&&u.hasOwnProp(e,t)?e[t]:void 0;function Tc(e,t,s){if(u.isString(e))try{return(t||JSON.parse)(e),u.trim(e)}catch(i){if(i.name!=="SyntaxError")throw i}return(s||JSON.stringify)(e)}const xt={transitional:Hi,adapter:["xhr","http","fetch"],transformRequest:[function(t,s){const i=s.getContentType()||"",n=i.indexOf("application/json")>-1,r=u.isObject(t);
vendor: 19,856 bytes, lines 3-5
3if(r&&u.isHTMLForm(t)&&(t=new FormData(t)),u.isFormData(t))return n?JSON.stringify(kr(t)):t;if(u.isArrayBuffer(t)||u.isBuffer(t)||u.isStream(t)||u.isFile(t)||u.isBlob(t)||u.isReadableStream(t))return t;if(u.isArrayBufferView(t))return t.buffer;if(u.isURLSearchParams(t))return s.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let o;if(r){const l=Ne(this,"formSerializer");if(i.indexOf("application/x-www-form-urlencoded")>-1)return Mc(t,l).toString();if((o=u.isFileList(t))||i.indexOf("multipart/form-data")>-1){const c=Ne(this,"env"),d=c&&c.FormData;return Ps(o?{"files[]":t}:t,d&&new d,l)}}return r||n?(s.setContentType("application/json",!1),Tc(t)):t}],transformResponse:[function(t){const s=Ne(this,"transitional")||xt.transitional,i=s&&s.forcedJSONParsing,n=Ne(this,"responseType"),r=n==="json";if(u.isResponse(t)||u.isReadableStream(t))return t;if(t&&u.isString(t)&&(i&&!n||r)){const o=!(s&&s.silentJSONParsing)&&r;try{return JSON.parse(t,Ne(this,"parseReviver"))}catch(l){if(o)throw l.name==="SyntaxError"?S.from(l,S.ERR_BAD_RESPONSE,this,null,Ne(this,"response")):l}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:O.classes.FormData,Blob:O.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};u.forEach(["delete","get","head","post","put","patch","query"],e=>{xt.headers[e]={}});function js(e,t){const s=this||xt,i=t||s,n=F.from(i.headers);let r=i.data;return u.forEach(e,function(o){r=o.call(s,r,n.normalize(),t?t.status:void 0)}),n.normalize(),r}function Nr(e){return!!(e&&e.__CANCEL__)}let Mt=class extends S{constructor(t,s,i){super(t??"canceled",S.ERR_CANCELED,s,i),this.name="CanceledError",this.__CANCEL__=!0}};function Fr(e,t,s){const i=s.config.validateStatus;!s.status||!i||i(s.status)?e(s):t(new S("Request failed with status code "+s.status,s.status>=400&&s.status<500?S.ERR_BAD_REQUEST:S.ERR_BAD_RESPONSE,s.config,s.request,s))}function Lc(e){const t=/^([-+\w]{1,25}):(?:\/\/)?/.exec(e);return t&&t[1]||""}function Ic(e,t){e=e||10;const s=new Array(e),i=new Array(e);let n=0,r=0,a;return t=t!==void 0?t:1e3,function(l){const c=Date.now(),d=i[r];a||(a=c),s[n]=l,i[n]=c;let h=r,f=0;for(;h!==n;)f+=s[h++],h=h%e;if(n=(n+1)%e,n===r&&(r=(r+1)%e),c-a<t)return;const p=d&&c-d;return p?Math.round(f*1e3/p):void 0}}function Dc(e,t){let s=0,i=1e3/t,n,r;const a=(c,d=Date.now())=>{s=d,n=null,r&&(clearTimeout(r),r=null),e(...c)};return[(...c)=>{const d=Date.now(),h=d-s;h>=i?a(c,d):(n=c,r||(r=setTimeout(()=>{r=null,a(n)},i-h)))},()=>n&&a(n)]}const es=(e,t,s=3)=>{let i=0;const n=Ic(50,250);return Dc(r=>{if(!r||typeof r.loaded!="number")return;const a=r.loaded,o=r.lengthComputable?r.total:void 0,l=o!=null?Math.min(a,o):a,c=Math.max(0,l-i),d=n(c);i=Math.max(i,l);const h={loaded:l,total:o,progress:o?l/o:void 0,bytes:c,rate:d||void 0,estimated:d&&o?(o-l)/d:void 0,event:r,lengthComputable:o!=null,[t?"download":"upload"]:!0};e(h)},s)},Nn=(e,t)=>{const s=e!=null;return[i=>t[0]({lengthComputable:s,total:e,loaded:i}),t[1]]},Fn=e=>(...t)=>u.asap(()=>e(...t)),Oc=O.hasStandardBrowserEnv?((e,t)=>s=>(s=new URL(s,O.origin),e.protocol===s.protocol&&e.host===s.host&&(t||e.port===s.port)))(new URL(O.origin),O.navigator&&/(msie|trident)/i.test(O.navigator.userAgent)):()=>!0,Pc=O.hasStandardBrowserEnv?{write(e,t,s,i,n,r,a){if(typeof document>"u")return;const o=[`${e}=${encodeURIComponent(t)}`];u.isNumber(s)&&o.push(`expires=${new Date(s).toUTCString()}`),u.isString(i)&&o.push(`path=${i}`),u.isString(n)&&o.push(`domain=${n}`),r===!0&&o.push("secure"),u.isString(a)&&o.push(`SameSite=${a}`),document.cookie=o.join("; ")},read(e){if(typeof document>"u")return null;const t=document.cookie.split(";");for(let s=0;s<t.length;s++){const i=t[s].replace(/^\s+/,""),n=i.indexOf("=");if(n!==-1&&i.slice(0,n)===e)try{return decodeURIComponent(i.slice(n+1))}catch{return i.slice(n+1)}}return null},remove(e){this.write(e,"",Date.now()-864e5,"/")}}:{write(){},read(){return null},remove(){}};function kc(e){return typeof e!="string"?!1:/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function Nc(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}const Fc=/^https?:(?!\/\/)/i,Bc=/[\t\n\r]/g;function qc(e){let t=0;for(;t<e.length&&e.charCodeAt(t)<=32;)t++;return e.slice(t)}function $c(e){return qc(e).replace(Bc,"")}function Bn(e,t){if(typeof e=="string"&&Fc.test($c(e)))throw new S('Invalid URL: missing "//" after protocol',S.ERR_INVALID_URL,t)}function Br(e,t,s,i){Bn(t,i);let n=!kc(t);return e&&(n||s===!1)?(Bn(e,i),Nc(e,t)):t}const qn=e=>e instanceof F?{...e}:e;function Ie(e,t){e=e||{},t=t||{};const s=Object.create(null);Object.defineProperty(s,"hasOwnProperty",{__proto__:null,value:Object.prototype.hasOwnProperty,enumerable:!1,writable:!0,configurable:!0});function i(d,h,f,p){return u.isPlainObject(d)&&u.isPlainObject(h)?u.merge.call({caseless:p},d,h):u.isPlainObject(h)?u.merge({},h):u.isArray(h)?h.slice():h}function n(d,h,f,p){if(u.isUndefined(h)){if(!u.isUndefined(d))return i(void 0,d,f,p)}else return i(d,h,f,p)}function r(d,h){if(!u.isUndefined(h))return i(void 0,h)}function a(d,h){if(u.isUndefined(h)){if(!u.isUndefined(d))return i(void 0,d)}else return i(void 0,h)}function o(d){const h=u.hasOwnProp(t,"transitional")?t.transitional:void 0;if(!u.isUndefined(h))if(u.isPlainObject(h)){if(u.hasOwnProp(h,d))return h[d]}else return;const f=u.hasOwnProp(e,"transitional")?e.transitional:void 0;if(u.isPlainObject(f)&&u.hasOwnProp(f,d))return f[d]}function l(d,h,f){if(u.hasOwnProp(t,f))return i(d,h);if(u.hasOwnProp(e,f))return i(void 0,d)}const c={url:r,method:r,data:r,baseURL:a,transformRequest:a,transformResponse:a,paramsSerializer:a,timeout:a,timeoutMessage:a,withCredentials:a,withXSRFToken:a,adapter:a,responseType:a,xsrfCookieName:a,xsrfHeaderName:a,onUploadProgress:a,onDownloadProgress:a,decompress:a,maxContentLength:a,maxBodyLength:a,beforeRedirect:a,transport:a,httpAgent:a,httpsAgent:a,cancelToken:a,socketPath:a,allowedSocketPaths:a,responseEncoding:a,validateStatus:l,headers:(d,h,f)=>n(qn(d),qn(h),f,!0)};return u.forEach(Object.keys({...e,...t}),function(h){if(h==="__proto__"||h==="constructor"||h==="prototype")return;const f=u.hasOwnProp(c,h)?c[h]:n,p=u.hasOwnProp(e,h)?e[h]:void 0,y=u.hasOwnProp(t,h)?t[h]:void 0,w=f(p,y,h);u.isUndefined(w)&&f!==l||(s[h]=w)}),u.hasOwnProp(t,"validateStatus")&&u.isUndefined(t.validateStatus)&&o("validateStatusUndefinedResolves")===!1&&(u.hasOwnProp(e,"validateStatus")?s.validateStatus=i(void 0,e.validateStatus):delete s.validateStatus),s}const Hc=["content-type","content-length"];function Vc(e,t,s){if(s!=="content-only"){e.set(t);return}Object.entries(t||{}).forEach(([i,n])=>{Hc.includes(i.toLowerCase())&&e.set(i,n)})}const jc=e=>encodeURIComponent(e).replace(/%([0-9A-F]{2})/gi,(t,s)=>String.fromCharCode(parseInt(s,16)));function qr(e){const t=Ie({},e),s=f=>u.hasOwnProp(t,f)?t[f]:void 0,i=s("data");let n=s("withXSRFToken");const r=s("xsrfHeaderName"),a=s("xsrfCookieName");let o=s("headers");const l=s("auth"),c=s("baseURL"),d=s("allowAbsoluteUrls"),h=s("url");if(t.headers=o=F.from(o),t.url=Or(Br(c,h,d,t),s("params"),s("paramsSerializer")),l){const f=u.getSafeProp(l,"username")||"",p=u.getSafeProp(l,"password")||"";try{o.set("Authorization","Basic "+btoa(f+":"+(p?jc(p):"")))}catch(y){throw S.from(y,S.ERR_BAD_OPTION_VALUE,e)}}if(u.isFormData(i)&&(O.hasStandardBrowserEnv||O.hasStandardBrowserWebWorkerEnv||u.isReactNative(i)?o.setContentType(void 0):u.isFunction(i.getHeaders)&&Vc(o,i.getHeaders(),s("formDataHeaderPolicy"))),O.hasStandardBrowserEnv&&(u.isFunction(n)&&(n=n(t)),n===!0||n==null&&Oc(t.url))){const p=r&&a&&Pc.read(a);p&&o.set(r,p)}return t}const Wc=typeof XMLHttpRequest<"u",zc=Wc&&function(e){return new Promise(function(s,i){const n=qr(e);let r=n.data;const a=F.from(n.headers).normalize();let{responseType:o,onUploadProgress:l,onDownloadProgress:c}=n,d,h,f,p,y;function w(){p&&p(),y&&y(),n.cancelToken&&n.cancelToken.unsubscribe(d),n.signal&&n.signal.removeEventListener("abort",d)}let m=new XMLHttpRequest;m.open(n.method.toUpperCase(),n.url,!0),m.timeout=n.timeout;function g(){if(!m)return;const b=F.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders()),v={data:!o||o==="text"||o==="json"?m.responseText:m.response,status:m.status,statusText:m.statusText,headers:b,config:e,request:m};Fr(function(P){s(P),w()},function(P){i(P),w()},v),m=null}"onloadend"in m?m.onloadend=g:m.onreadystatechange=function(){!m||m.readyState!==4||m.status===0&&!(m.responseURL&&m.responseURL.startsWith("file:"))||setTimeout(g)},m.onabort=function(){m&&(i(new S("Request aborted",S.ECONNABORTED,e,m)),w(),m=null)},m.onerror=function(R){const v=R&&R.message?R.message:"Network Error",M=new S(v,S.ERR_NETWORK,e,m);M.event=R||null,i(M),w(),m=null},m.ontimeout=function(){let R=n.timeout?"timeout of "+n.timeout+"ms exceeded":"timeout exceeded";const v=n.transitional||Hi;n.timeoutErrorMessage&&(R=n.timeoutErrorMessage),i(new S(R,v.clarifyTimeoutError?S.ETIMEDOUT:S.ECONNABORTED,e,m)),w(),m=null},r===void 0&&a.setContentType(null),"setRequestHeader"in m&&u.forEach(Ur(a),function(R,v){m.setRequestHeader(v,R)}),u.isUndefined(n.withCredentials)||(m.withCredentials=!!n.withCredentials),o&&o!=="json"&&(m.responseType=n.responseType),c&&([f,y]=es(c,!0),m.addEventListener("progress",f)),l&&m.upload&&([h,p]=es(l),m.upload.addEventListener("progress",h),m.upload.addEventListener("loadend",p)),(n.cancelToken||n.signal)&&(d=b=>{m&&(i(!b||b.type?new Mt(null,e,m):b),m.abort(),w(),m=null)},n.cancelToken&&n.cancelToken.subscribe(d),n.signal&&(n.signal.aborted?d():n.signal.addEventListener("abort",d)));const _=Lc(n.url);if(_&&!O.protocols.includes(_)){i(new S("Unsupported protocol "+_+":",S.ERR_BAD_REQUEST,e)),w();return}m.send(r||null)})},Qc=(e,t)=>{if(e=e?e.filter(Boolean):[],!t&&!e.length)return;const s=new AbortController;let i=!1;const n=function(l){if(!i){i=!0,a();const c=l instanceof Error?l:this.reason;s.abort(c instanceof S?c:new Mt(c instanceof Error?c.message:c))}};let r=t&&setTimeout(()=>{r=null,n(new S(`timeout of ${t}ms exceeded`,S.ETIMEDOUT))},t);const a=()=>{e&&(r&&clearTimeout(r),r=null,e.forEach(l=>{l.unsubscribe?l.unsubscribe(n):l.removeEventListener("abort",n)}),e=null)};e.forEach(l=>l.addEventListener("abort",n,{once:!0}));const{signal:o}=s;return o.unsubscribe=()=>u.asap(a),o},Gc=function*(e,t){let s=e.byteLength;if(s<t){yield e;return}let i=0,n;for(;i<s;)n=i+t,yield e.slice(i,n),i=n},Kc=async function*(e,t){for await(const s of Jc(e))yield*Gc(s,t)},Jc=async function*(e){if(e[Symbol.asyncIterator]){yield*e;return}const t=e.getReader();try{for(;;){const{done:s,value:i}=await t.read();if(s)break;yield i}}finally{await t.cancel()}},$n=(e,t,s,i)=>{const n=Kc(e,t);let r=0,a,o=l=>{a||(a=!0,i&&i(l))};return new ReadableStream({async pull(l){try{const{done:c,value:d}=await n.next();if(c){o(),l.close();return}let h=d.byteLength;if(s){let f=r+=h;s(f)}l.enqueue(new Uint8Array(d))}catch(c){throw o(c),c}},cancel(l){return o(l),n.return()}},{highWaterMark:2})},ts=e=>e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102,Xc=(e,t,s)=>t+2<s&&ts(e.charCodeAt(t+1))&&ts(e.charCodeAt(t+2));function Yc(e){if(!e||typeof e!="string"||!e.startsWith("data:"))return 0;const t=e.indexOf(",");if(t<0)return 0;const s=e.slice(5,t),i=e.slice(t+1);if(/;base64/i.test(s)){let a=i.length;const o=i.length;for(let p=0;p<o;p++)if(i.charCodeAt(p)===37&&p+2<o){const y=i.charCodeAt(p+1),w=i.charCodeAt(p+2);ts(y)&&ts(w)&&(a-=2,p+=2)}let l=0,c=o-1;const d=p=>p>=2&&i.charCodeAt(p-2)===37&&i.charCodeAt(p-1)===51&&(i.charCodeAt(p)===68||i.charCodeAt(p)===100);c>=0&&(i.charCodeAt(c)===61?(l++,c--):d(c)&&(l++,c-=3)),l===1&&c>=0&&(i.charCodeAt(c)===61||d(c))&&l++;const f=Math.floor(a/4)*3-(l||0);return f>0?f:0}let r=0;for(let a=0,o=i.length;a<o;a++){const l=i.charCodeAt(a);if(l===37&&Xc(i,a,o))r+=1,a+=2;else if(l<128)r+=1;else if(l<2048)r+=2;else if(l>=55296&&l<=56319&&a+1<o){const c=i.charCodeAt(a+1);c>=56320&&c<=57343?(r+=4,a++):r+=3}else r+=3}return r}const ji="1.18.1",Hn=64*1024,{isFunction:Tt}=u,Zc=e=>encodeURIComponent(e).replace(/%([0-9A-F]{2})/gi,(t,s)=>String.fromCharCode(parseInt(s,16))),Vn=e=>{if(!u.isString(e))return e;try{return decodeURIComponent(e)}catch{return e}},jn=(e,...t)=>{try{return!!e(...t)}catch{return!1}},ed=e=>{const t=e.indexOf("://");let s=e;return t!==-1&&(s=s.slice(t+3)),s.includes("@")||s.includes(":")},td=e=>{const t=u.global!==void 0&&u.global!==null?u.global:globalThis,{ReadableStream:s,TextEncoder:i}=t;e=u.merge.call({skipUndefined:!0},{Request:t.Request,Response:t.Response},e);const{fetch:n,Request:r,Response:a}=e,o=n?Tt(n):typeof fetch=="function",l=Tt(r),c=Tt(a);if(!o)return!1;const d=o&&Tt(s),h=o&&(typeof i=="function"?(g=>_=>g.encode(_))(new i):async g=>new Uint8Array(await new r(g).arrayBuffer())),f=l&&d&&jn(()=>{let g=!1;const _=new r(O.origin,{body:new s,method:"POST",get duplex(){return g=!0,"half"}}),b=_.headers.has("Content-Type");return _.body!=null&&_.body.cancel(),g&&!b}),p=c&&d&&jn(()=>u.isReadableStream(new a("").body)),y={stream:p&&(g=>g.body)};o&&["text","arrayBuffer","blob","formData","stream"].forEach(g=>{!y[g]&&(y[g]=(_,b)=>{let R=_&&_[g];if(R)return R.call(_);throw new S(`Response type '${g}' is not supported`,S.ERR_NOT_SUPPORT,b)})});const w=async g=>{if(g==null)return 0;if(u.isBlob(g))return g.size;if(u.isSpecCompliantForm(g))return(await new r(O.origin,{method:"POST",body:g}).arrayBuffer()).byteLength;if(u.isArrayBufferView(g)||u.isArrayBuffer(g))return g.byteLength;if(u.isURLSearchParams(g)&&(g=g+""),u.isString(g))return(await h(g)).byteLength},m=async(g,_)=>{const b=u.toFiniteNumber(g.getContentLength());return b??w(_)};return async g=>{let{url:_,method:b,data:R,signal:v,cancelToken:M,timeout:P,onDownloadProgress:Ke,onUploadProgress:Je,responseType:z,headers:X,withCredentials:le="same-origin",fetchOptions:Xe,maxContentLength:q,maxBodyLength:te}=qr(g);const Q=u.isNumber(q)&&q>-1,se=u.isNumber(te)&&te>-1,rl=A=>u.hasOwnProp(g,A)?g[A]:void 0;let Rn=n||fetch;z=z?(z+"").toLowerCase():"text";let ce=Qc([v,M&&M.toAbortSignal()],P),I=null;const be=ce&&ce.unsubscribe&&(()=>{ce.unsubscribe()});let ke,Ye=null;const En=()=>new S("Request body larger than maxBodyLength limit",S.ERR_BAD_REQUEST,g,I);try{let A;const G=rl("auth");if(G){const E=u.getSafeProp(G,"username")||"",H=u.getSafeProp(G,"password")||"";A={username:E,password:H}}if(ed(_)){const E=new URL(_,O.origin);if(!A&&(E.username||E.password)){const H=Vn(E.username),de=Vn(E.password);A={username:H,password:de}}(E.username||E.password)&&(E.username="",E.password="",_=E.href)}if(A&&(X.delete("authorization"),X.set("Authorization","Basic "+btoa(Zc((A.username||"")+":"+(A.password||""))))),Q&&typeof _=="string"&&_.startsWith("data:")&&Yc(_)>q)throw new S("maxContentLength size of "+q+" exceeded",S.ERR_BAD_RESPONSE,g,I);if(se&&b!=="get"&&b!=="head"){const E=await w(R);if(typeof E=="number"&&isFinite(E)&&(ke=E,E>te))throw En()}const Ut=se&&(u.isReadableStream(R)||u.isStream(R)),xn=(E,H,de)=>$n(E,Hn,Ce=>{if(se&&Ce>te)throw Ye=En();H&&H(Ce)},de);if(f&&b!=="get"&&b!=="head"&&(Je||Ut)){if(ke=ke??await m(X,R),ke!==0||Ut){let E=new r(_,{method:"POST",body:R,duplex:"half"}),H;if(u.isFormData(R)&&(H=E.headers.get("content-type"))&&X.setContentType(H),E.body){const[de,Ce]=Je&&Nn(ke,es(Fn(Je)))||[];R=xn(E.body,de,Ce)}}}else if(Ut&&!l&&d&&b!=="get"&&b!=="head")R=xn(R);else if(Ut&&l&&!f&&b!=="get"&&b!=="head")throw new S("Stream request bodies are not supported by the current fetch implementation",S.ERR_NOT_SUPPORT,g,I);u.isString(le)||(le=le?"include":"omit");const al=l&&"credentials"in r.prototype;if(u.isFormData(R)){const E=X.getContentType();E&&/^multipart\/form-data/i.test(E)&&!/boundary=/i.test(E)&&X.delete("content-type")}X.set("User-Agent","axios/"+ji,!1);const Mn={...Xe,signal:ce,method:b.toUpperCase(),headers:Ur(X.normalize()),body:R,duplex:"half",credentials:al?le:void 0};I=l&&new r(_,Mn);let ie=await(l?Rn(I,Xe):Rn(_,Mn));const An=F.from(ie.headers);if(Q){const E=u.toFiniteNumber(An.getContentLength());if(E!=null&&E>q)throw new S("maxContentLength size of "+q+" exceeded",S.ERR_BAD_RESPONSE,g,I)}const $s=p&&(z==="stream"||z==="response");if(p&&ie.body&&(Ke||Q||$s&&be)){const E={};["status","statusText","headers"].forEach(Ze=>{E[Ze]=ie[Ze]});const H=u.toFiniteNumber(An.getContentLength()),[de,Ce]=Ke&&Nn(H,es(Fn(Ke),!0))||[];let Un=0;const ol=Ze=>{if(Q&&(Un=Ze,Un>q))throw new S("maxContentLength size of "+q+" exceeded",S.ERR_BAD_RESPONSE,g,I);de&&de(Ze)};ie=new a($n(ie.body,Hn,ol,()=>{Ce&&Ce(),be&&be()}),E)}z=z||"text";let ne=await y[u.findKey(y,z)||"text"](ie,g);if(Q&&!p&&!$s){let E;if(ne!=null&&(typeof ne.byteLength=="number"?E=ne.byteLength:typeof ne.size=="number"?E=ne.size:typeof ne=="string"&&(E=typeof i=="function"?new i().encode(ne).byteLength:ne.length)),typeof E=="number"&&E>q)throw new S("maxContentLength size of "+q+" exceeded",S.ERR_BAD_RESPONSE,g,I)}return!$s&&be&&be(),await new Promise((E,H)=>{Fr(E,H,{data:ne,headers:F.from(ie.headers),status:ie.status,statusText:ie.statusText,config:g,request:I})})}catch(A){if(be&&be(),ce&&ce.aborted&&ce.reason instanceof S){const G=ce.reason;throw G.config=g,I&&(G.request=I),A!==G&&Object.defineProperty(G,"cause",{__proto__:null,value:A,writable:!0,enumerable:!1,configurable:!0}),G}if(Ye)throw I&&!Ye.request&&(Ye.request=I),Ye;if(A instanceof S)throw I&&!A.request&&(A.request=I),A;if(A&&A.name==="TypeError"&&/Load failed|fetch/i.test(A.message)){const G=new S("Network Error",S.ERR_NETWORK,g,I,A&&A.response);throw Object.defineProperty(G,"cause",{__proto__:null,value:A.cause||A,writable:!0,enumerable:!1,configurable:!0}),G}throw S.from(A,A&&A.code,g,I,A&&A.response)}}},sd=new Map,$r=e=>{let t=e&&e.env||{};const{fetch:s,Request:i,Response:n}=t,r=[i,n,s];let a=r.length,o=a,l,c,d=sd;for(;o--;)l=r[o],c=d.get(l),c===void 0&&d.set(l,c=o?new Map:td(t)),d=c;return c};$r();const Wi={http:gc,xhr:zc,fetch:{get:$r}};u.forEach(Wi,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{__proto__:null,value:t})}catch{}Object.defineProperty(e,"adapterName",{__proto__:null,value:t})}});const Wn=e=>`- ${e}`,id=e=>u.isFunction(e)||e===null||e===!1;function nd(e,t){e=u.isArray(e)?e:[e];const{length:s}=e;let i,n;const r={};for(let a=0;a<s;a++){i=e[a];let o;if(n=i,!id(i)&&(n=Wi[(o=String(i)).toLowerCase()],n===void 0))throw new S(`Unknown adapter '${o}'`);if(n&&(u.isFunction(n)||(n=n.get(t))))break;r[o||"#"+a]=n}if(!n){const a=Object.entries(r).map(([l,c])=>`adapter ${l} `+(c===!1?"is not supported by the environment":"is not available in the build"));let o=s?a.length>1?`since : 4`+a.map(Wn).join(` 5`):" "+Wn(a[0]):"as no adapter specified";throw new S("There is no suitable adapter to dispatch the request "+o,S.ERR_NOT_SUPPORT)}return n}const Hr={getAdapter:nd,adapters:Wi};function Ws(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Mt(null,e)}function zn(e){return Ws(e),e.headers=F.from(e.headers),e.data=js.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),Hr.getAdapter(e.adapter||xt.adapter,e)(e).then(function(i){Ws(e),e.response=i;try{i.data=js.call(e,e.transformResponse,i)}finally{delete e.response}return i.headers=F.from(i.headers),i},function(i){if(!Nr(i)&&(Ws(e),i&&i.response)){e.response=i.response;try{i.response.data=js.call(e,e.transformResponse,i.response)}finally{delete e.response}i.response.headers=F.from(i.response.headers)}return Promise.reject(i)})}const ks={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{ks[e]=function(i){return typeof i===e||"a"+(t<1?"n ":" ")+e}});const Qn={};ks.transitional=function(t,s,i){function n(r,a){return"[Axios v"+ji+"] Transitional option '"+r+"'"+a+(i?". "+i:"")}return(r,a,o)=>
vendor: 10,379 bytes, lines 5-9
5{if(t===!1)throw new S(n(a," has been removed"+(s?" in "+s:"")),S.ERR_DEPRECATED);return s&&!Qn[a]&&(Qn[a]=!0,console.warn(n(a," has been deprecated since v"+s+" and will be removed in the near future"))),t?t(r,a,o):!0}};ks.spelling=function(t){return(s,i)=>(console.warn(`${i} is likely a misspelling of ${t}`),!0)};function rd(e,t,s){if(typeof e!="object"||e===null)throw new S("options must be an object",S.ERR_BAD_OPTION_VALUE);const i=Object.keys(e);let n=i.length;for(;n-- >0;){const r=i[n],a=Object.prototype.hasOwnProperty.call(t,r)?t[r]:void 0;if(a){const o=e[r],l=o===void 0||a(o,r,e);if(l!==!0)throw new S("option "+r+" must be "+l,S.ERR_BAD_OPTION_VALUE);continue}if(s!==!0)throw new S("Unknown option "+r,S.ERR_BAD_OPTION)}}const Vt={assertOptions:rd,validators:ks},k=Vt.validators;let Ae=class{constructor(t){this.defaults=t||{},this.interceptors={request:new Pn,response:new Pn}}async request(t,s){try{return await this._request(t,s)}catch(i){if(i instanceof Error){let n={};Error.captureStackTrace?Error.captureStackTrace(n):n=new Error;const r=(()=>{if(!n.stack)return"";const a=n.stack.indexOf(` 6`);return a===-1?"":n.stack.slice(a+1)})();try{if(!i.stack)i.stack=r;else if(r){const a=r.indexOf(` 7`),o=a===-1?-1:r.indexOf(` 8`,a+1),l=o===-1?"":r.slice(o+1);String(i.stack).endsWith(l)||(i.stack+=` 9`+r)}}catch{}}throw i}}_request(t,s){typeof t=="string"?(s=s||{},s.url=t):s=t||{},s=Ie(this.defaults,s);const{transitional:i,paramsSerializer:n,headers:r}=s;i!==void 0&&Vt.assertOptions(i,{silentJSONParsing:k.transitional(k.boolean),forcedJSONParsing:k.transitional(k.boolean),clarifyTimeoutError:k.transitional(k.boolean),legacyInterceptorReqResOrdering:k.transitional(k.boolean),advertiseZstdAcceptEncoding:k.transitional(k.boolean),validateStatusUndefinedResolves:k.transitional(k.boolean)},!1),n!=null&&(u.isFunction(n)?s.paramsSerializer={serialize:n}:Vt.assertOptions(n,{encode:k.function,serialize:k.function},!0)),s.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?s.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:s.allowAbsoluteUrls=!0),Vt.assertOptions(s,{baseUrl:k.spelling("baseURL"),withXsrfToken:k.spelling("withXSRFToken")},!0),s.method=(s.method||this.defaults.method||"get").toLowerCase();let a=r&&u.merge(r.common,r[s.method]);r&&u.forEach(["delete","get","head","post","put","patch","query","common"],y=>{delete r[y]}),s.headers=F.concat(a,r);const o=[];let l=!0;this.interceptors.request.forEach(function(w){if(typeof w.runWhen=="function"&&w.runWhen(s)===!1)return;l=l&&w.synchronous;const m=s.transitional||Hi;m&&m.legacyInterceptorReqResOrdering?o.unshift(w.fulfilled,w.rejected):o.push(w.fulfilled,w.rejected)});const c=[];this.interceptors.response.forEach(function(w){c.push(w.fulfilled,w.rejected)});let d,h=0,f;if(!l){const y=[zn.bind(this),void 0];for(y.unshift(...o),y.push(...c),f=y.length,d=Promise.resolve(s);h<f;)d=d.then(y[h++],y[h++]);return d}f=o.length;let p=s;for(;h<f;){const y=o[h++],w=o[h++];try{p=y(p)}catch(m){w.call(this,m);break}}try{d=zn.call(this,p)}catch(y){return Promise.reject(y)}for(h=0,f=c.length;h<f;)d=d.then(c[h++],c[h++]);return d}getUri(t){t=Ie(this.defaults,t);const s=Br(t.baseURL,t.url,t.allowAbsoluteUrls,t);return Or(s,t.params,t.paramsSerializer)}};u.forEach(["delete","get","head","options"],function(t){Ae.prototype[t]=function(s,i){return this.request(Ie(i||{},{method:t,url:s,data:i&&u.hasOwnProp(i,"data")?i.data:void 0}))}});u.forEach(["post","put","patch","query"],function(t){function s(i){return function(r,a,o){return this.request(Ie(o||{},{method:t,headers:i?{"Content-Type":"multipart/form-data"}:{},url:r,data:a}))}}Ae.prototype[t]=s(),t!=="query"&&(Ae.prototype[t+"Form"]=s(!0))});let ad=class Vr{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let s;this.promise=new Promise(function(r){s=r});const i=this;this.promise.then(n=>{if(!i._listeners)return;let r=i._listeners.length;for(;r-- >0;)i._listeners[r](n);i._listeners=null}),this.promise.then=n=>{let r;const a=new Promise(o=>{i.subscribe(o),r=o}).then(n);return a.cancel=function(){i.unsubscribe(r)},a},t(function(r,a,o){i.reason||(i.reason=new Mt(r,a,o),s(i.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const s=this._listeners.indexOf(t);s!==-1&&this._listeners.splice(s,1)}toAbortSignal(){const t=new AbortController,s=i=>{t.abort(i)};return this.subscribe(s),t.signal.unsubscribe=()=>this.unsubscribe(s),t.signal}static source(){let t;return{token:new Vr(function(n){t=n}),cancel:t}}};function od(e){return function(s){return e.apply(null,s)}}function ld(e){return u.isObject(e)&&e.isAxiosError===!0}const li={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,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(li).forEach(([e,t])=>{li[t]=e});function jr(e){const t=new Ae(e),s=br(Ae.prototype.request,t);return u.extend(s,Ae.prototype,t,{allOwnKeys:!0}),u.extend(s,t,null,{allOwnKeys:!0}),s.create=function(n){return jr(Ie(e,n))},s}const T=jr(xt);T.Axios=Ae;T.CanceledError=Mt;T.CancelToken=ad;T.isCancel=Nr;T.VERSION=ji;T.toFormData=Ps;T.AxiosError=S;T.Cancel=T.CanceledError;T.all=function(t){return Promise.all(t)};T.spread=od;T.isAxiosError=ld;T.mergeConfig=Ie;T.AxiosHeaders=F;T.formToJSON=e=>kr(u.isHTMLForm(e)?new FormData(e):e);T.getAdapter=Hr.getAdapter;T.HttpStatusCode=li;T.default=T;const{Axios:wu,AxiosError:bu,CanceledError:Cu,isCancel:Su,CancelToken:vu,VERSION:Ru,all:Eu,Cancel:xu,isAxiosError:Mu,spread:Au,toFormData:Uu,AxiosHeaders:Tu,HttpStatusCode:Lu,formToJSON:Iu,getAdapter:Du,mergeConfig:Ou,create:Pu}=T;var zs,Gn;function cd(){return Gn||(Gn=1,zs=typeof self=="object"?self.FormData:window.FormData),zs}var dd=cd();const hd=ll(dd),ud="aaa1rp3bb0ott3vie4c1le2ogado5udhabi7c0ademy5centure6ountant0s9o1tor4d0s1ult4e0g1ro2tna4f0l1rica5g0akhan5ency5i0g1rbus3force5tel5kdn3l0ibaba4pay4lfinanz6state5y2sace3tom5m0azon4ericanexpress7family11x2fam3ica3sterdam8nalytics7droid5quan4z2o0l2partments8p0le4q0uarelle8r0ab1mco4chi3my2pa2t0e3s0da2ia2sociates9t0hleta5torney7u0ction5di0ble3o3spost5thor3o0s4w0s2x0a2z0ure5ba0by2idu3namex4d1k2r0celona5laycard4s5efoot5gains6seball5ketball8uhaus5yern5b0c1t1va3cg1n2d1e0ats2uty4er2rlin4st0buy5t2f1g1h0arti5i0ble3d1ke2ng0o3o1z2j1lack0friday9ockbuster8g1omberg7ue3m0s1w2n0pparibas9o0ats3ehringer8fa2m1nd2o0k0ing5sch2tik2on4t1utique6x2r0adesco6idgestone9oadway5ker3ther5ussels7s1t1uild0ers6siness6y1zz3v1w1y1z0h3ca0b1fe2l0l1vinklein9m0era3p2non3petown5ital0one8r0avan4ds2e0er0s4s2sa1e1h1ino4t0ering5holic7ba1n1re3c1d1enter4o1rn3f0a1d2g1h0anel2nel4rity4se2t2eap3intai5ristmas6ome4urch5i0priani6rcle4sco3tadel4i0c2y3k1l0aims4eaning6ick2nic1que6othing5ud3ub0med6m1n1o0ach3des3ffee4llege4ogne5m0mbank4unity6pany2re3uter5sec4ndos3struction8ulting7tact3ractors9oking4l1p2rsica5untry4pon0s4rses6pa2r0edit0card4union9icket5own3s1uise0s6u0isinella9v1w1x1y0mru3ou3z2dad1nce3ta1e1ing3sun4y2clk3ds2e0al0er2s3gree4livery5l1oitte5ta3mocrat6ntal2ist5si0gn4v2hl2iamonds6et2gital5rect0ory7scount3ver5h2y2j1k1m1np2o0cs1tor4g1mains5t1wnload7rive4tv2ubai3nlop4pont4rban5vag2r2z2earth3t2c0o2deka3u0cation8e1g1mail3erck5nergy4gineer0ing9terprises10pson4quipment8r0icsson6ni3s0q1tate5t1u0rovision8s2vents5xchange6pert3osed4ress5traspace10fage2il1rwinds6th3mily4n0s2rm0ers5shion4t3edex3edback6rrari3ero6i0delity5o2lm2nal1nce1ial7re0stone6mdale6sh0ing5t0ness6j1k1lickr3ghts4r2orist4wers5y2m1o0o0d1tball6rd1ex2sale4um3undation8x2r0ee1senius7l1ogans4ntier7tr2ujitsu5n0d2rniture7tbol5yi3ga0l0lery3o1up4me0s3p1rden4y2b0iz3d0n2e0a1nt0ing5orge5f1g0ee3h1i0ft0s3ves2ing5l0ass3e1obal2o4m0ail3bh2o1x2n1odaddy5ld0point6f2o0dyear5g0le4p1t1v2p1q1r0ainger5phics5tis4een3ipe3ocery4up4s1t1u0cci3ge2ide2tars5ru3w1y2hair2mburg5ngout5us3bo2dfc0bank7ealth0care8lp1sinki6re1mes5iphop4samitsu7tachi5v2k0t2m1n1ockey4ldings5iday5medepot5goods5s0ense7nda3rse3spital5t0ing5t0els3mail5use3w2r1sbc3t1u0ghes5yatt3undai7ibm2cbc2e1u2d1e0ee3fm2kano4l1m0amat4db2mo0bilien9n0c1dustries8finiti5o2g1k1stitute6urance4e4t0ernational10uit4vestments10o1piranga7q1r0ish4s0maili5t0anbul7t0au2v3jaguar4va3cb2e0ep2tzt3welry6io2ll2m0p2nj2o0bs1urg4t1y2p0morgan6rs3uegos4niper7kaufen5ddi3e0rryhotels6properties14fh2g1h1i0a1ds2m1ndle4tchen5wi3m1n1oeln3matsu5sher5p0mg2n2r0d1ed3uokgroup8w1y0oto4z2la0caixa5mborghini8er3nd0rover6xess5salle5t0ino3robe5w0yer5b1c1ds2ease3clerc5frak4gal2o2xus4gbt3i0dl2fe0insurance9style7ghting6ke2lly3mited4o2ncoln4k2ve1ing5k1lc1p2oan0s3cker3us3l1ndon4tte1o3ve3pl0financial11r1s1t0d0a3u0ndbeck6xe1ury5v1y2ma0drid4if1son4keup4n0agement7go3p1rket0ing3s4riott5shalls7ttel5ba2c0kinsey7d1e0d0ia3et2lbourne7me1orial6n0u2rckmsd7g1h1iami3crosoft7l1ni1t2t0subishi9k1l0b1s2m0a2n1o0bi0le4da2e1i1m1nash3ey2ster5rmon3tgage6scow4to0rcycles9v0ie4p1q1r1s0d2t0n1r2u0seum3ic4v1w1x1y1z2na0b1goya4me2vy3ba2c1e0c1t0bank4flix4work5ustar5w0s2xt0direct7us4f0l2g0o2hk2i0co2ke1on3nja3ssan1y5l1o0kia3rton4w0ruz3tv4p1r0a1w2tt2u1yc2z2obi1server7ffice5kinawa6layan0group9lo3m0ega4ne1g1l0ine5oo2pen3racle3nge4g0anic5igins6saka4tsuka4t2vh3pa0ge2nasonic7ris2s1tners4s1y3y2
9ccw3e0t2f0izer5g1h0armacy6d1ilips5one2to0graphy6s4ysio5ics1tet2ures6d1n0g1k2oneer5zza4k1l0ace2y0station9umbing5s3m1n0c2ohl2ker3litie5rn2st3r0axi3ess3ime3o0d0uctions8f1gressive8mo2perties3y5tection8u0dential9s1t1ub2w0c2y2qa1pon3uebec3st5racing4dio4e0ad1lestate6tor2y4cipes5d0stone5umbrella9hab3ise0n3t2liance6n0t0als5pair3ort3ublican8st0aurant8view0s5xroth6ich0ardli6oh3l1o1p2o0cks3deo3gers4om3s0vp3u0gby3hr2n2w0e2yukyu6sa0arland6fe0ty4kura4le1on3msclub4ung5ndvik0coromant12ofi4p1rl2s1ve2xo3b0i1s2c0b1haeffler7midt4olarships8ol3ule3warz5ience5ot3d1e0arch3t2cure1ity6ek2lect4ner3rvices6ven3w1x0y3fr2g1h0angrila6rp3ell3ia1ksha5oes2p0ping5uji3w3i0lk2na1gles5te3j1k0i0n2y0pe4l0ing4m0art3ile4n0cf3o0ccer3ial4ftbank4ware6hu2lar2utions7ng1y2y2pa0ce3ort2t3r0l2s1t0ada2ples4r1tebank4farm7c0group6ockholm6rage3e3ream4udio2y3yle4u0cks3pplies3y2ort5rf1gery5zuki5v1watch4iss4x1y0dney4stems6z2tab1ipei4lk2obao4rget4tamotors6r2too4x0i3c0i2d0k2eam2ch0nology8l1masek5nnis4va3f1g1h0d1eater2re6iaa2ckets5enda4ps2res2ol4j0maxx4x2k0maxx5l1m0all4n1o0day3kyo3ols3p1ray3shiba5tal3urs3wn2yota3s3r0ade1ing4ining5vel0ers0insurance16ust3v2t1ube2i1nes3shu4v0s2w1z2ua1bank3s2g1k1nicom3versity8o2ol2ps2s1y1z2va0cations7na1guard7c1e0gas3ntures6risign5mögensberater2ung14sicherung10t2g1i0ajes4deo3g1king4llas4n1p1rgin4sa1ion4va1o3laanderen9n1odka3lvo3te1ing3o2yage5u2wales2mart4ter4ng0gou5tch0es6eather0channel12bcam3er2site5d0ding5ibo2r3f1hoswho6ien2ki2lliamhill9n0dows4e1ners6me2olterskluwer11odside6rk0s2ld3w2s1tc1f3xbox3erox4ihuan4n2xx2yz3yachts4hoo3maxun5ndex5e1odobashi7ga2kohama6u0tube6t1un3za0ppos4ra3ero3ip2m1one3uerich6w2",fd="ελ1Ï
2бг1ел3деÑи4еÑ2каÑолик6ом3мÐ
9ºÐ´2он1Ñква6онлайн5Ñг3ÑÑÑ2Ñ2ÑайÑ3Ñб3ÑкÑ3Òаз3Õ°Õ¡Õµ3×שר××5×§××3Ø§Ø¨ÙØ¸Ø¨Ù5را٠ÙÙ5ÙØ§Ø±Ø¯Ù4Ø¨ØØ±ÙÙ5جزائر5Ø³Ø¹ÙØ¯ÙØ©6عÙÙØ§Ù5٠غرب5٠ارات5ÛØ±Ø§Ù5بارت2زار4ÙØªÙ3ھارت5تÙÙØ³4Ø³ÙØ¯Ø§Ù3Ø±ÙØ©5Ø´Ø¨ÙØ©4عراÙ2ب2٠اÙ4ÙÙØ³Ø·ÙÙ6ÙØ·Ø±3ÙØ§Ø«ÙÙÙÙ6ÙÙ 3٠صر2ÙÙØ³Ùا5ÙØ±ÙتاÙÙØ§7ÙØ¹4Ù٠راÙ5پاکستاÙ7ÚØ§Ø±Øª4à¤à¥à¤®3नà¥à¤3à¤à¤¾à¤°à¤¤0मà¥3à¥à¤¤5सà¤à¤à¤ न5বাà¦à¦²à¦¾5à¦à¦¾à¦°à¦¤2ৰত4à¨à¨¾à¨°à¨¤4àªàª¾àª°àª¤4à¬à¬¾à¬°à¬¤4à®à®¨à¯à®¤à®¿à®¯à®¾6லà®à¯à®à¯6à®à®¿à®à¯à®à®ªà¯à®ªà¯à®°à¯11à°à°¾à°°à°¤à±5à²à²¾à²°à²¤4à´à´¾à´°à´¤à´5à¶½à¶à¶à·4à¸à¸à¸¡3à¹à¸à¸¢3ລາວ3áá2ã¿ããª3ã¢ãã¾ã³4ã¯ã©ã¦ã4ã°ã¼ã°ã«4ã³ã 2ã¹ãã¢3ã»ã¼ã«3ãã¡ãã·ã§ã³6ãã¤ã³ã4ä¸ç2ä¸ä¿¡1å½1å1æç½3äºé©¬é3ä¼ä¸2ä½å±±2ä¿¡æ¯2å¥åº·2å «å¦2å ¬å¸1ç2å°æ¹¾1ç£2åå1åº1æ 2åé0大é åº5å¨çº¿2大æ¿2天主æ3娱ä¹2å®¶é»2广ä¸2å¾®å2æ å2æç±ä½ 3ææº2æè2æ¿å¡1åº2æ°å å¡2é»2æ¶å°2æ¸ç±2æºæ2淡马é¡3游æ2æ¾³é2ç¹ç2ç§»å¨2ç»ç»æºæ4ç½å1åº1ç«1ç»2èé2è°·æ2è´ç©2é販2éå¢2é»è¨çç§4é£å©æµ¦3é£å2é¤å 2馿 ¼éæ3港2ë·ë·1ì»´2ì¼ì±2íêµ2",ci="numeric",di="ascii",hi="alpha",ct="asciinumeric",at="alphanumeric",ui="domain",Wr="emoji",pd="scheme",gd="slashscheme",Qs="whitespace";function md(e,t){return e in t||(t[e]=[]),t[e]}function Me(e,t,s){t[ci]&&(t[ct]=!0,t[at]=!0),t[di]&&(t[ct]=!0,t[hi]=!0),t[ct]&&(t[at]=!0),t[hi]&&(t[at]=!0),t[at]&&(t[ui]=!0),t[Wr]&&(t[ui]=!0);for(const i in t){const n=md(i,s);n.indexOf(e)<0&&n.push(e)}}function yd(e,t){const s={};for(const i in t)t[i].indexOf(e)>=0&&(s[i]=!0);return s}function j(e=null){this.j={},this.jr=[],this.jd=null,this.t=e}j.groups={};j.prototype={accepts(){return!!this.t},go(e){const t=this,s=t.j[e];if(s)return s;for(let i=0;i<t.jr.length;i++){const n=t.jr[i][0],r=t.jr[i][1];if(r&&n.test(e))return r}return t.jd},has(e,t=!1){return t?e in this.j:!!this.go(e)},ta(e,t,s,i){for(let n=0;n<e.length;n++)this.tt(e[n],t,s,i)},tr(e,t,s,i){i=i||j.groups;let n;return t&&t.j?n=t:(n=new j(t),s&&i&&Me(t,s,i)),this.jr.push([e,n]),n},ts(e,t,s,i){let n=this;const r=e.length;if(!r)return n;for(let a=0;a<r-1;a++)n=n.tt(e[a]);return n.tt(e[r-1],t,s,i)},tt(e,t,s,i){i=i||j.groups;const n=this;if(t&&t.j)return n.j[e]=t,t;const r=t;let a,o=n.go(e);if(o?(a=new j,Object.assign(a.j,o.j),a.jr.push.apply(a.jr,o.jr),a.jd=o.jd,a.t=o.t):a=new j,r){if(i)if(a.t&&typeof a.t=="string"){const l=Object.assign(yd(a.t,i),s);Me(r,l,i)}else s&&Me(r,s,i);a.t=r}return n.j[e]=a,a}};const x=(e,t,s,i,n)=>e.ta(t,s,i,n),L=(e,t,s,i,n)=>e.tr(t,s,i,n),Kn=(e,t,s,i,n)=>e.ts(t,s,i,n),C=(e,t,s,i,n)=>e.tt(t,s,i,n),oe="WORD",fi="UWORD",zr="ASCIINUMERICAL",Qr="ALPHANUMERICAL",yt="LOCALHOST",pi="TLD",gi="UTLD",jt="SCHEME",Fe="SLASH_SCHEME",zi="NUM",mi="WS",Qi="NL",dt="OPENBRACE",ht="CLOSEBRACE",ss="OPENBRACKET",is="CLOSEBRACKET",ns="OPENPAREN",rs="CLOSEPAREN",as="OPENANGLEBRACKET",os="CLOSEANGLEBRACKET",ls="FULLWIDTHLEFTPAREN",cs="FULLWIDTHRIGHTPAREN",ds="LEFTCORNERBRACKET",hs="RIGHTCORNERBRACKET",us="LEFTWHITECORNERBRACKET",fs="RIGHTWHITECORNERBRACKET",ps="FULLWIDTHLESSTHAN",gs="FULLWIDTHGREATERTHAN",ms="AMPERSAND",ys="APOSTROPHE",_s="ASTERISK",fe="AT",ws="BACKSLASH",bs="BACKTICK",Cs="CARET",ge="COLON",Gi="COMMA",Ss="DOLLAR",Z="DOT",vs="EQUALS",Ki="EXCLAMATION",J="HYPHEN",ut="PERCENT",Rs="PIPE",Es="PLUS",xs="POUND",ft="QUERY",Ji="QUOTE",Gr="FULLWIDTHMIDDLEDOT",Xi="SEMI",ee="SLASH",pt="TILDE",Ms="UNDERSCORE",Kr="EMOJI",As="SYM";var Jr=Object.freeze({__proto__:null,ALPHANUMERICAL:Qr,AMPERSAND:ms,APOSTROPHE:ys,ASCIINUMERICAL:zr,ASTERISK:_s,AT:fe,BACKSLASH:ws,BACKTICK:bs,CARET:Cs,CLOSEANGLEBRACKET:os,CLOSEBRACE:ht,CLOSEBRACKET:is,CLOSEPAREN:rs,COLON:ge,COMMA:Gi,DOLLAR:Ss,DOT:Z,EMOJI:Kr,EQUALS:vs,EXCLAMATION:Ki,FULLWIDTHGREATERTHAN:gs,FULLWIDTHLEFTPAREN:ls,FULLWIDTHLESSTHAN:ps,FULLWIDTHMIDDLEDOT:Gr,FULLWIDTHRIGHTPAREN:cs,HYPHEN:J,LEFTCORNERBRACKET:ds,LEFTWHITECORNERBRACKET:us,LOCALHOST:yt,NL:Qi,NUM:zi,OPENANGLEBRACKET:as,OPENBRACE:dt,OPENBRACKET:ss,OPENPAREN:ns,PERCENT:ut,PIPE:Rs,PLUS:Es,POUND:xs,QUERY:ft,QUOTE:Ji,RIGHTCORNERBRACKET:hs,RIGHTWHITECORNERBRACKET:fs,SCHEME:jt,SEMI:Xi,SLASH:ee,SLASH_SCHEME:Fe,SYM:As,TILDE:pt,TLD:pi,UNDERSCORE:Ms,UTLD:gi,UWORD:fi,WORD:oe,WS:mi});const re=/[a-z]/,st=new RegExp("\\p{L}","u"),Gs=new RegExp("\\p{Emoji}","u"),ae=/\d/,Ks=/\s/,Jn="\r",Js=` 10`,_d="ï¸",wd="â",Xs="";let Lt=null,It=null;function bd(e=[]){const t={};j.groups=t;const s=new j;Lt==null&&(Lt=Xn(ud)),It==null&&(It=Xn(fd)),C(s,"'",ys),C(s,"{",dt),C(s,"}",ht),C(s,"[",ss),C(s,"]",is),C(s,"(",ns),C(s,")",rs),C(s,"<",as),C(s,">",os),C(s,"ï¼",ls),C(s,"ï¼",cs),C(s,"ã",ds),C(s,"ã",hs),C(s,"ã",us),C(s,"ã",f
vendor: 5,634 bytes, line 10
10s),C(s,"ï¼",ps),C(s,"ï¼",gs),C(s,"&",ms),C(s,"*",_s),C(s,"@",fe),C(s,"`",bs),C(s,"^",Cs),C(s,":",ge),C(s,",",Gi),C(s,"$",Ss),C(s,".",Z),C(s,"=",vs),C(s,"!",Ki),C(s,"-",J),C(s,"%",ut),C(s,"|",Rs),C(s,"+",Es),C(s,"#",xs),C(s,"?",ft),C(s,'"',Ji),C(s,"/",ee),C(s,";",Xi),C(s,"~",pt),C(s,"_",Ms),C(s,"\\",ws),C(s,"ã»",Gr);const i=L(s,ae,zi,{[ci]:!0});L(i,ae,i);const n=L(i,re,zr,{[ct]:!0}),r=L(i,st,Qr,{[at]:!0}),a=L(s,re,oe,{[di]:!0});L(a,ae,n),L(a,re,a),L(n,ae,n),L(n,re,n);const o=L(s,st,fi,{[hi]:!0});L(o,re),L(o,ae,r),L(o,st,o),L(r,ae,r),L(r,re),L(r,st,r);const l=C(s,Js,Qi,{[Qs]:!0}),c=C(s,Jn,mi,{[Qs]:!0}),d=L(s,Ks,mi,{[Qs]:!0});C(s,Xs,d),C(c,Js,l),C(c,Xs,d),L(c,Ks,d),C(d,Jn),C(d,Js),L(d,Ks,d),C(d,Xs,d);const h=L(s,Gs,Kr,{[Wr]:!0});C(h,"#"),L(h,Gs,h),C(h,_d,h);const f=C(h,wd);C(f,"#"),L(f,Gs,h);const p=[[re,a],[ae,n]],y=[[re,null],[st,o],[ae,r]];for(let w=0;w<Lt.length;w++)he(s,Lt[w],pi,oe,p);for(let w=0;w<It.length;w++)he(s,It[w],gi,fi,y);Me(pi,{tld:!0,ascii:!0},t),Me(gi,{utld:!0,alpha:!0},t),he(s,"file",jt,oe,p),he(s,"mailto",jt,oe,p),he(s,"http",Fe,oe,p),he(s,"https",Fe,oe,p),he(s,"ftp",Fe,oe,p),he(s,"ftps",Fe,oe,p),Me(jt,{scheme:!0,ascii:!0},t),Me(Fe,{slashscheme:!0,ascii:!0},t),e=e.sort((w,m)=>w[0]>m[0]?1:-1);for(let w=0;w<e.length;w++){const m=e[w][0],_=e[w][1]?{[pd]:!0}:{[gd]:!0};m.indexOf("-")>=0?_[ui]=!0:re.test(m)?ae.test(m)?_[ct]=!0:_[di]=!0:_[ci]=!0,Kn(s,m,m,_)}return Kn(s,"localhost",yt,{ascii:!0}),s.jd=new j(As),{start:s,tokens:Object.assign({groups:t},Jr)}}function Xr(e,t){const s=Cd(t.replace(/[A-Z]/g,o=>o.toLowerCase())),i=s.length,n=[];let r=0,a=0;for(;a<i;){let o=e,l=null,c=0,d=null,h=-1,f=-1;for(;a<i&&(l=o.go(s[a]));)o=l,o.accepts()?(h=0,f=0,d=o):h>=0&&(h+=s[a].length,f++),c+=s[a].length,r+=s[a].length,a++;r-=h,a-=f,c-=h,n.push({t:d.t,v:t.slice(r-c,r),s:r-c,e:r})}return n}function Cd(e){const t=[],s=e.length;let i=0;for(;i<s;){let n=e.charCodeAt(i),r,a=n<55296||n>56319||i+1===s||(r=e.charCodeAt(i+1))<56320||r>57343?e[i]:e.slice(i,i+2);t.push(a),i+=a.length}return t}function he(e,t,s,i,n){let r;const a=t.length;for(let o=0;o<a-1;o++){const l=t[o];e.j[l]?r=e.j[l]:(r=new j(i),r.jr=n.slice(),e.j[l]=r),e=r}return r=new j(s),r.jr=n.slice(),e.j[t[a-1]]=r,r}function Xn(e){const t=[],s=[];let i=0,n="0123456789";for(;i<e.length;){let r=0;for(;n.indexOf(e[i+r])>=0;)r++;if(r>0){t.push(s.join(""));for(let a=parseInt(e.substring(i,i+r),10);a>0;a--)s.pop();i+=r}else s.push(e[i]),i++}return t}const _t={defaultProtocol:"http",events:null,format:Yn,formatHref:Yn,nl2br:!1,tagName:"a",target:null,rel:null,validate:!0,truncate:1/0,className:null,attributes:null,ignoreTags:[],render:null};function Yi(e,t=null){let s=Object.assign({},_t);e&&(s=Object.assign(s,e instanceof Yi?e.o:e));const i=s.ignoreTags,n=[];for(let r=0;r<i.length;r++)n.push(i[r].toUpperCase());this.o=s,t&&(this.defaultRender=t),this.ignoreTags=n}Yi.prototype={o:_t,ignoreTags:[],defaultRender(e){return e},check(e){return this.get("validate",e.toString(),e)},get(e,t,s){const i=t!=null;let n=this.o[e];return n&&(typeof n=="object"?(n=s.t in n?n[s.t]:_t[e],typeof n=="function"&&i&&(n=n(t,s))):typeof n=="function"&&i&&(n=n(t,s.t,s)),n)},getObj(e,t,s){let i=this.o[e];return typeof i=="function"&&t!=null&&(i=i(t,s.t,s)),i},render(e){const t=e.render(this);return(this.get("render",null,e)||this.defaultRender)(t,e.t,e)}};function Yn(e){return e}function Yr(e,t){this.t="token",this.v=e,this.tk=t}Yr.prototype={isLink:!1,toString(){return this.v},toHref(e){return this.toString()},toFormattedString(e){const t=this.toString(),s=e.get("truncate",t,this),i=e.get("format",t,this);return s&&i.length>s?i.substring(0,s)+"â¦":i},toFormattedHref(e){return e.get("formatHref",this.toHref(e.get("defaultProtocol")),this)},startIndex(){return this.tk[0].s},endIndex(){return this.tk[this.tk.length-1].e},toObject(e=_t.defaultProtocol){return{type:this.t,value:this.toString(),isLink:this.isLink,href:this.toHref(e),start:this.startIndex(),end:this.endIndex()}},toFormattedObject(e){return{type:this.t,value:this.toFormattedString(e),isLink:this.isLink,href:this.toFormattedHref(e),start:this.startIndex(),end:this.endIndex()}},validate(e){return e.get("validate",this.toString(),this)},render(e){const t=this,s=this.toHref(e.get("defaultProtocol")),i=e.get("formatHref",s,this),n=e.get("tagName",s,t),r=this.toFormattedString(e),a={},o=e.get("className",s,t),l=e.get("target",s,t),c=e.get("rel",s,t),d=e.getObj("attributes",s,t),h=e.getObj("events",s,t);return a.href=i,o&&(a.class=o),l&&(a.target=l),c&&(a.rel=c),d&&Object.assign(a,d),{tagName:n,attributes:a,content:r,eventListeners:h}}};function Ns(e,t){class s extends Yr{constructor(n,r){super(n,r),this.t=e}}for(const i in t)s.prototype[i]=t[i];return s.t=e,s}const Zn=Ns("email",{isLink:!0,toHref(){return"mailto:"+this.toString()}}),er=Ns("text"),Sd=Ns("nl"),Dt=Ns("url",{isLink:!0,toHref(e=_t.defaultProtocol){return this.hasProtocol()?this.v:`${e}://${this.v}`},hasProtocol(){const e=this.tk;return e.length>=2&&e[0].t!==yt&&e[1].t===ge}}),K=e=>new j(e);function vd({groups:e}){const t=e.domain.concat([ms,_s,fe,ws,bs,Cs,Ss,vs,J,zi,ut,Rs,Es,xs,ee,As,pt,Ms]),s=[ys,ge,Gi,Z,Ki,ut,ft,Ji,Xi,as,os,dt,ht,is,ss,ns,rs,ls,cs,ds,hs,us,fs,ps,gs],i=[ms,ys,_s,ws,bs,Cs,Ss,vs,J,dt,ht,ut,Rs,Es,xs,ft,ee,As,pt,Ms],n=K(),r=C(n,pt);x(r,i,r),x(r,e.domain,r);const a=K(),o=K(),l=K();x(n,e.domain,a),x(n,e.scheme,o),x(n,e.slashscheme,l),x(a,i,r),x(a,e.domain,a);const c=C(a,fe);C(r,fe,c),C(o,fe,c),C(l,fe,c);const d=C(r,Z);x(d,i,r),x(d,e.domain,r);const h=K();x(c,e.domain,h),x(h,e.domain,h);const f=C(h,Z);x(f,e.domain,h);const p=K(Zn);x(f,e.tld,p),x(f,e.utld,p),C(c,yt,p);const y=C(h,J);
10C(y,J,y),x(y,e.domain,h),x(p,e.domain,h),C(p,Z,f),C(p,J,y);const w=C(p,ge);x(w,e.numeric,Zn);const m=C(a,J),g=C(a,Z);C(m,J,m),x(m,e.domain,a),x(g,i,r),x(g,e.domain,a);const _=K(Dt);x(g,e.tld,_),x(g,e.utld,_),x(_,e.domain,a),x(_,i,r),C(_,Z,g),C(_,J,m),C(_,fe,c);const b=C(_,ge),R=K(Dt);x(b,e.numeric,R);const v=K(Dt),M=K();x(v,t,v),x(v,s,M),x(M,t,v),x(M,s,M),C(_,ee,v),C(R,ee,v);const P=C(o,ge),Ke=C(l,ge),Je=C(Ke,ee),z=C(Je,ee);x(o,e.domain,a),C(o,Z,g),C(o,J,m),x(l,e.domain,a),C(l,Z,g),C(l,J,m),x(P,e.domain,v),C(P,ee,v),C(P,ft,v),x(z,e.domain,v),x(z,t,v),C(z,ee,v);const X=[[dt,ht],[ss,is],[ns,rs],[as,os],[ls,cs],[ds,hs],[us,fs],[ps,gs]];for(let le=0;le<X.length;le++){const[Xe,q]=X[le],te=C(v,Xe);C(M,Xe,te),C(te,q,v);const Q=K(Dt);x(te,t,Q);const se=K();x(te,s),x(Q,t,Q),x(Q,s,se),x(se,t,Q),x(se,s,se),C(Q,q,v),C(se,q,v)}return C(n,yt,_),C(n,Qi,Sd),{start:n,tokens:Jr}}function Rd(e,t,s){let i=s.length,n=0,r=[],a=[];for(;n<i;){let o=e,l=null,c=null,d=0,h=null,f=-1;for(;n<i&&!(l=o.go(s[n].t));)a.push(s[n++]);for(;n<i&&(c=l||o.go(s[n].t));)l=null,o=c,o.accepts()?(f=0,h=o):f>=0&&f++,n++,d++;if(f<0)n-=d,n<i&&(a.push(s[n]),n++);else{a.length>0&&(r.push(Ys(er,t,a)),a=[]),n-=f,d-=f;const p=h.t,y=s.slice(n-d,n);r.push(Ys(p,t,y))}}return a.length>0&&r.push(Ys(er,t,a)),r}function Ys(e,t,s){const i=s[0].s,n=s[s.length-1].e,r=t.slice(i,n);return new e(r,s)}const N={scanner:null,parser:null,tokenQueue:[],pluginQueue:[],customSchemes:[],initialized:!1};function Ed(){N.scanner=bd(N.customSchemes);for(let e=0;e<N.tokenQueue.length;e++)N.tokenQueue[e][1]({scanner:N.scanner});N.parser=vd(N.scanner.tokens);for(let e=0;e<N.pluginQueue.length;e++)N.pluginQueue[e][1]({scanner:N.scanner,parser:N.parser});return N.initialized=!0,N}function Zi(e){return N.initialized||Ed(),Rd(N.parser.start,e,Xr(N.scanner.start,e))}Zi.scan=Xr;function xd(e,t=null,s=null){if(t&&typeof t=="object"){if(s)throw Error(`linkifyjs: Invalid link type ${t}; must be a string`);s=t,t=null}const i=new Yi(s),n=Zi(e),r=[];for(let a=0;a<n.length;a++){const o=n[a];o.isLink&&(!t||o.t===t)&&i.check(o)&&r.push(o.toFormattedObject(i))}return r}function ku(e,t=null){const s=Zi(e);return s.length===1&&s[0].isLink&&(!t||s[0].t===t)}var Be=null;typeof WebSocket<"u"?Be=WebSocket:typeof MozWebSocket<"u"?Be=MozWebSocket:typeof globalThis<"u"?Be=globalThis.WebSocket||globalThis.MozWebSocket:typeof window<"u"?Be=window.WebSocket||window.MozWebSocket:typeof self<"u"&&(Be=self.WebSocket||self.MozWebSocket);var Zs={},Md=Object.create,Zr=Object.defineProperty,Ad=Object.getOwnPropertyDescriptor,ea=Object.getOwnPropertyNames,Ud=Object.getPrototypeOf,Td=Object.prototype.hasOwnProperty,en=(e,t)=>function(){return t||(0,e[ea(e)[0]])((t={exports:{}}).exports,t),t.exports},Ld=(e,t,s,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of ea(t))!Td.call(e,n)&&n!==s&&Zr(e,n,{get:()=>t[n],enumerable:!(i=Ad(t,n))||i.enumerable});return e},tn=(e,t,s)=>(s=e!=null?Md(Ud(e)):{},Ld(!e||!e.__esModule?Zr(s,"default",{value:e,enumerable:!0}):s,e)),Id=en({"(disabled):https"(){}}),Dd=en({"(disabled):node_modules/jsonwebtoken/index.js"(){}}),Od=en({"(disabled):crypto"(){}});function yi(e){return typeof e=="string"}function tr(e,t){return!!t&&yi(e)}function Pd(e,t){const s=[];if(yi(e)&&tr(e,t)){for(let i=0,n=e.length;i<n;i++)if(e.charAt(i)){const r=e.charAt(i),a=t(r,i,e);s[i]=a}}else if(!yi(e)&&!tr(e,t)){for(let i=0,n=e.length;i<n;i++)if(i in e){const r=e[i],a=t(r,i,e);s[i]=a}}return s}var ta=e=>dl.fromByteArray(new Uint8Array(Pd(e,t=>t.charCodeAt(0)))),sa=e=>{const t={},s=String.fromCharCode,i=e.length;let n,r=0,a,o,l=0,c,d="";const h="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(n=0;n<64;n++)t[h.charAt(n)]=n;for(o=0;o<i;o++)for(a=t[e.charAt(o)],r=(r<<6)+a,l+=6;l>=8;)((c=r>>>(l-=8)&255)||o<i-2)&&(d+=s(c));return d},_i=class{constructor(e,t,s){this.client=e,this.id=t,this.data=s}async create(){const e={id:this.id,message_template:this.data?.message_template,segment_ids:this.data?.segment_ids,sender_id:this.data?.sender_id,sender_mode:this.data?.sender_mode,sender_visibility:this.data?.sender_visibility,channel_template:this.data?.channel_template,create_channels:this.data?.create_channels,show_channels:this.data?.show_channels,description:this.data?.description,name:this.data?.name,skip_push:this.data?.ski
10p_push,skip_webhook:this.data?.skip_webhook,user_ids:this.data?.user_ids},t=await this.client.createCampaign(e);return this.id=t.campaign.id,this.data=t.campaign,t}verifyCampaignId(){if(!this.id)throw new Error("Campaign id is missing. Either create the campaign using campaign.create() or set the id during instantiation - const campaign = client.campaign(id)")}async start(e){return this.verifyCampaignId(),await this.client.startCampaign(this.id,e)}update(e){return this.verifyCampaignId(),this.client.updateCampaign(this.id,e)}async delete(){return this.verifyCampaignId(),await this.client.deleteCampaign(this.id)}stop(){return this.verifyCampaignId(),this.client.stopCampaign(this.id)}get(e){return this.verifyCampaignId(),this.client.getCampaign(this.id,e)}},kd=tn(Id()),Nd=25,Fd=100,Ot=Object.freeze({hasNext:!1,hasPrev:!1}),Bd=100*1024*1024,qd=10,$d=100,Hd=Object.freeze({created_at:!0,deleted_at:!0,pinned_at:!0,updated_at:!0,command:!0,mentioned_users:!0,quoted_message:!0,latest_reactions:!0,own_reactions:!0,reaction_counts:!0,reply_count:!0,i18n:!0,t
10ype:!0,html:!0,__html:!0,user:!0}),Vd=Object.freeze({error:!0}),jd=3,Wd=1e3;function sn(e,t){e.then().catch(s=>{console.warn(`failed to do ${t}, ran into error: `,s)})}var ye=e=>new Promise(t=>setTimeout(t,e));function wi(e){return typeof e=="function"||e instanceof Function||Object.prototype.toString.call(e)==="[object Function]"}var qe={TOKEN_EXPIRED:40,WS_CLOSED_SUCCESS:1e3};function zd(e){return e!==null&&typeof e=="object"&&(e.readable||typeof e._read=="function")}function Qd(e){return e!=null&&e.constructor!=null&&typeof e.constructor.isBuffer=="function"&&e.constructor.isBuffer(e)}function Gd(e){return typeof window<"u"&&"File"in window&&e instanceof File}function Kd(e){return typeof window<"u"&&"Blob"in window&&e instanceof Blob}function Jd(e){return{channel_mutes:!0,devices:!0,mutes:!0,total_unread_count:!0,unread_channels:!0,unread_count:!0,unread_threads:!0,invisible:!0,privacy_settings:!0,roles:!0,push_preferences:!0,total_unread_count_by_team:!0}[e]}function Xd(e,t,s){const i=new hd;return zd(e)||Qd(e)||Gd(e)||Kd(e)?t?i.append("file",e,t):i.append("file",e):i.append("file",{uri:e,name:t||e.split("/").reverse()[0],contentType:s,type:s}),i}function D(e){const t=[],s=Array.isArray(e)?e:[e];for(const i of s){const n=Object.entries(i);n.length>1&&console.warn("client._buildSort() - multiple fields in a single sort object detected. Object's field order is not guaranteed");for(const[r,a]of n)t.push({field:r,direction:a})}return t}function Us(e){const t=Math.min(500+e*2e3,25e3),s=Math.min(Math.max(250,(e-1)*2e3),25e3);return Math.floor(Math.random()*(t-s)+s)}function $e(){return W()}function it(e){let t="";for(let s=0;s<e.length;s++)t+=e[s].toString(16).padStart(2,"0");return t}function W(){const e=eh(16);return e[6]=e[6]&15|64,e[8]=e[8]&191|128,it(e.subarray(0,4))+"-"+it(e.subarray(4,6))+"-"+it(e.subarray(6,8))+"-"+it(e.subarray(8,10))+"-"+it(e.subarray(10,16))}function Yd(e){const t=Math.pow(2,8*e.byteLength/e.length);for(let s=0;s<e.length;s++)e[s]=Math.random()*t}var Zd=typeof crypto<"u"&&typeof crypto?.getRandomValues<"u"?crypto.getRandomValues.bind(crypto):typeof msCrypto<"u"?msCrypto.getRandomValues.bind(msCrypto):Yd;function eh(e){const t=new Uint8Array(e);return Zd(t),t}function th(e){const t={};if(!e)return t;try{Object.getOwnPropertyNames(e).forEach(s=>{t[s]=Object.getOwnPropertyDescriptor(e,s)})}catch{return{error:"failed to serialize the error"}}return t}function sh(){const e=typeof navigator<"u"?navigator:typeof window<"u"&&window.navigator?window.navigator:void 0;return e?typeof e.onLine!="boolean"?!0:e.onLine:(console.warn("isOnline failed to access window.navigator and assume browser is online"),!0)}function ia(e){typeof window<"u"&&window.addEventListener&&(window.addEventListener("offline",e),window.addEventListener("online",e))}function na(e){typeof window<"u"&&window.removeEventListener&&(window.removeEventListener("offline",e),window.removeEventListener("online",e))}var ih=e=>{const t=[];for(const s in e)e[s]!==void 0&&(Array.isArray(e[s])||typeof e[s]=="object"?t.push(`${s}=${encodeURIComponent(JSON.stringify(e[s]))}`):t.push(`${s}=${encodeURIComponent(e[s])}`));return t.join("&")};function B(e){const t=s=>s?{...s,created_at:s.created_at?new Date(s.created_at):new Date,deleted_at:s.deleted_at?new Date(s.deleted_at):null,pinned_at:s.pinned_at?new Date(s.pinned_at):null,reaction_groups:ah(s.reaction_groups,s.reaction_counts,s.reaction_scores),status:s.status||"received",updated_at:s.updated_at?new Date(s.updated_at):new Date}:null;return{...t(e),error:e.error??null,quoted_message:t(e.quoted_message)}}function nh(e){const t=s=>{if(!s)return null;const i=new Date().toISOString();return{...s,created_at:e.created_at?e.created_at.toISOString():i,deleted_at:e.deleted_at?e.deleted_at.toISOString():void 0,pinned_at:e.pinned_at?e.pinned_at.toISOString():void 0,updated_at:e.updated_at?e.updated_at.toISOString():i}};return{...t(e),quoted_message:t(e.quoted_message)}}var rh=e=>{const{created_at:t,updated_at:s,deleted_at:i,error:n,status:r,latest_reactions:a,own_reactions:o,reaction_counts:l,reaction_scores:c,reply_count:d,command:h,html:f,i18n:p,quoted_message:y,mentioned_users:w,...m}=e;return{...m,pinned_at:m.pinned_at?.toISOString(),mentioned_users:w?.map(g=>g.id)}},ra=e=>{const t={...Hd,...Vd};return{...Object.fromEntries(Object.entries(e).filter(([i])=>!t[i])),pinned:!!e.pinned_at,mentioned_users:e.mentioned_users?.map(i=>typeof i=="string"?i:i.id)}},sr=({message:e,deletedAt:t,hardDelete:s=!1})=>s?{attachments:[],cid:e.cid,created_at:e.created_at,deleted_at:t,
10id:e.id,latest_reactions:[],mentioned_users:[],own_reactions:[],parent_id:e.parent_id,reply_count:e.reply_count,status:e.status,thread_participants:e.thread_participants,type:"deleted",updated_at:e.updated_at,user:e.user}:{...e,attachments:[],type:"deleted",deleted_at:t},ei=({messages:e,user:t,hardDelete:s=!1,deletedAt:i})=>{for(let n=0;n<e.length;n++){const r=e[n];r.user?.id===t.id&&(e[n]=r.type==="deleted"?r:sr({message:r,hardDelete:s,deletedAt:i})),r.quoted_message?.user?.id===t.id&&(e[n].quoted_message=r.quoted_message.type==="deleted"?r.quoted_message:sr({message:e[n].quoted_message,hardDelete:s,deletedAt:i}))}},aa=({needle:e,sortedArray:t,selectKey:s,selectValueToCompare:i=r=>r,sortDirection:n="ascending"})=>{if(!t.length)return 0;let r=0,a=t.length-1,o=0;const l=()=>{o=Math.round((r+a)/2)},c=i(e);for(;r<=a;){l();const d=i(t[o]);n==="ascending"&&c<d||n==="descending"&&c>=d?a=o-1:r=o+1}if(s){const d=s(e),h=n==="ascending"?-1:1;for(let f=r+h;0<=f&&f<t.length&&i(t[f])===c;f+=h)if(s(t[f])===d)return f}return r};function oa(e,t,s=!1,i="created_at",n=!0){const r=n||s;let a=[...e];if(s&&(a=a.filter(d=>!(d.id&&t.id===d.id))),a.length===0&&r)return a.concat(t);if(a.length===0)return a;const o=t[i].getTime(),l=a.at(-1)[i].getTime()<o;if(l&&r)return a.concat(t);if(l)return a;const c=aa({needle:t,sortedArray:a,sortDirection:"ascending",selectValueToCompare:d=>d[i].getTime(),selectKey:d=>d.id});return!s&&t.id&&a[c]&&t.id===a[c].id?(a[c]=t,a):(r&&a.splice(c,0,t),a)}function ah(e,t,s){if(e)return e;if(t&&s){const i={};for(const n of Object.keys(t))i[n]={count:t[n],sum_scores:s[n]};return i}return null}var wt=(e,t=0,{leading:s=!1,trailing:i=!0}={})=>{let n=null,r=null,a;const o=(...l)=>(n?clearTimeout(n):s&&(a=e(...l)),i&&(r=l),n=setTimeout(()=>{r&&(a=e(...r),r=null),n=null},t),a);return o.cancel=()=>{n&&clearTimeout(n)},o.flush=()=>(n&&(clearTimeout(n),n=null,r&&(a=e(...r))),a),o},nn=(e,t=200,{leading:s=!0,trailing:i=!1}={})=>{let n=null,r=null;return(...a)=>{if(n){i&&(r=a);return}s&&e(...a);const o=()=>{if(r){e(...r),r=null,n=setTimeout(o,t);return}n=null};n=setTimeout(o,t)}},oh=(e,t)=>t.split(".").reduce((s,i)=>{if(s&&typeof s=="object"&&i in s)return s[i]},e),lh=(e,t)=>{if(!Array.isArray(e))return[];const s=new Set;return e.filter(i=>{const n=oh(i,t);return s.has(n)?!1:(s.add(n),!0)})};function ch(e,t){let s=0,i=e.length-1;for(;s<=i;){const n=Math.floor((s+i)/2),r=e[n].created_at;if(!r){s+=1;continue}const a=new Date(r);if(a.getTime()===t.getTime())return n;a.getTime()<t.getTime()?s=n+1:i=n-1}return s}var dh=({parentSet:e,requestedPageSize:t,returnedPage:s,messagePaginationOptions:i})=>{const n={...e.pagination};if(!i?.created_at_around)return n;let r,a,o,l;const c=new Date(i.created_at_around),[d,h]=[s[0],s.slice(-1)[0]],f=!!d?.created_at&&new Date(d.created_at)>c,p=!!h?.created_at&&new Date(h.created_at)<c,y=t>e.messages.length&&t>s.length,w=(t>e.messages.length||e.messages.length>=s.length)&&t>s.length;if(f)r=!1,o=!0,y&&(a=!1,l=!0);else if(p)a=!1,l=!0,y&&(r=!1,o=!0);else if(w)a=r=!1,o=l=!0;else{const[m,g]=[d?.id&&d.id===e.messages[0]?.id,h?.id&&h.id===e.messages.slice(-1)[0]?.id];o=m,l=g;const _=Math.floor(s.length/2),b=ch(s,c);b!==-1&&(r=_<=b,a=_>=b)}return o&&typeof r<"u"&&(n.hasPrev=r),l&&typeof a<"u"&&(n.hasNext=a),n},hh=({parentSet:e,requestedPageSize:t,returnedPage:s,messagePaginationOptions:i})=>{const n={...e.pagination},{id_around:r}=i||{};if(!r)return n;let a,o;const[l,c]=[s[0],s.slice(-1)[0]],[d,h]=[l?.id===e.messages[0]?.id,c?.id===e.messages.slice(-1)[0]?.id];let f=d,p=h;const y=Math.floor(s.length/2);if((t>e.messages.length||e.messages.length>=s.length)&&t>s.length)o=a=!1,f=p=!0;else if(s[y])if(s[y].id===r)a=o=!0;else{let m;const g=[s.slice(0,y),s.slice(y)];a=o=!0;for(let _=0;_<g.length;_++)m=g[_].find(b=>b.id===r),m&&_===0&&(a=!1),m&&_===1&&(o=!1)}else return n;return f&&typeof a<"u"&&(n.hasPrev=a),p&&typeof o<"u"&&(n.hasNext=o),n},uh=({parentSet:e,requestedPageSize:t,returnedPage:s,messagePaginationOptions:i})=>{const n={...e.pagination};let r,a;const[o,l]=[s[0],s.slice(-1)[0]],[c,d]=[o?.id&&o.id===e.messages[0]?.id,l?.id&&l.id===e.messages.slice(-1)[0]?.id],h=i&&(i.created_at_after_or_equal||i.created_at_after||i.id_gt||i.id_gte),f=typeof i>"u"?!0:i.created_at_before_or_equal||i.created_at_before||i.id_lt||i.id_lte||i.offset,p=!h&&!f&&!i?.id_around&&!i?.created_at_around,y=s.length>=t;(typeof f<"u"||p)&&(r=y),typeof h<"u"&&(a=y);const w=s.length===0;return(c||w)&&typeof r<"u"&&(n.hasPrev=r),(d||w)&&typeof a<"u"&&(n.hasNext=a),n},la=e=>{const t=e.returnedPage.filter(({shadowed:s})=>s);return e.parentSet.messages.length+t.length<e.returnedPage.length?(e.logger?.("error","Corrupted message set state: parent set size < returned page size"),e.parentSet.pagination):e.messagePaginationOptions?.created_at_around?dh(e):e.messagePaginationOptions?.id_around?hh(e):uh(e)},Pt={},ti=async({channel:e,client:t,id:s,members:i,options:n,type:r})=>{if(!e&&!r)throw new Error("Channel or channel type have to be provided to query a channel.");const a=e||t.channel(r,s,{members:i}),o=a.id?a.cid:i&&i.length?rn(a.type,i):void 0;if(!o)throw new Error("Channel ID or channel members array have to be provided to query a channel.");const l=Pt[o];if(l)await l;else try{Pt[o]=a.watch(n),await Pt[o]}finally{delete Pt[o]}return a},rn=(e,t)=>{if(!t)return;const s=[...t].sort().join(",");if(s)return`${e}:!members-${s}`},Ts=e=>e?!!e.state.membership?.pinned_at:!1,kt=e=>e?!!e.state.membership?.archived_at:!1,Nt=e=>e?typeof e.archived=="boolean":!1,ca=({atIndex:e,sort:t,targetKey:s})=>{if(!t)return null;let i=null;if(Array.isArray(t))i=t[e]??null;else for(const n in t){if(n!==s)return null;i=t;break}return i?.[s]??null},bi=e=>{const t=fh({sort:e});return typeof t!="number"?!1:Math.abs(t)===1},fh=({sort:e})=>ca({atIndex:0,sort:e,targetKey:"pinned_at"}),da=({channels:e})=>{let t=null;for(const s of e){if(!Ts(s))break;typeof t=="number"?t++:t=0}return t},ot=({channels:e,channelToMove:t,channelToMoveIndexWithinChannels:s,sort:i})=>{const n=s??e.findIndex(h=>h.cid===t.cid),r=n>=0,a=n===0,o=bi(i),l=Ts(t);if(a||o&&l)return e;const c=[...e];r&&c.splice(n,1);let d=null;return o&&(d=da({channels:c})),c.splice(typeof d=="number"?d+1:0,0,t),c}
10,ph=e=>!!e.getTime,ha=e=>ph(e.created_at),gh=e=>e.type==="error"&&(e.moderation_details?.action==="MESSAGE_RESPONSE_ACTION_REMOVE"||e.moderation?.action==="remove"),ua=(e,t)=>({newestMessageA:new Date(e[0]?.created_at??0),oldestMessageA:new Date(e.slice(-1)[0]?.created_at??0),newestMessageB:new Date(t[0]?.created_at??0),oldestMessageB:new Date(t.slice(-1)[0]?.created_at??0)}),ir=(e,t)=>{const{newestMessageA:s,newestMessageB:i,oldestMessageA:n,oldestMessageB:r}=ua(e,t);return s>=i&&r>=n},nr=(e,t)=>{const{newestMessageA:s,newestMessageB:i,oldestMessageA:n,oldestMessageB:r}=ua(e,t);return n<r&&r<s&&s<i},mh=(e,t)=>ir(e,t)||ir(t,e)||nr(e,t)||nr(t,e),fa=class{constructor(e){this.messageSets=[],this.formatMessage=t=>B(t),this.setIsUpToDate=t=>{this.isUpToDate=t},this.removeMessageFromArray=(t,s)=>{const i=t.filter(n=>!(n.id&&s.id&&n.id===s.id));return{removed:i.length<t.length,result:i}},this.updateUserMessages=t=>{const s=(i,n)=>{for(let r=0;r<i.length;r++){const a=i[r];a.user?.id===n.id&&(i[r]={...a,user:n})}};this.messageSets.forEach(i=>s(i.messages,t));for(const i in this.threads)s(this.threads[i],t);s(this.pinnedMessages,t)},this.deleteUserMessages=(t,s=!1,i)=>{this.messageSets.forEach(({messages:n})=>ei({messages:n,user:t,hardDelete:s,deletedAt:i??null}));for(const n in this.threads)ei({messages:this.threads[n],user:t,hardDelete:s,deletedAt:i??null});ei({messages:this.pinnedMessages,user:t,hardDelete:s,deletedAt:i??null})},this.findMessageSetByOldestTimestamp=t=>{let s=0,i=this.messageSets.length;for(;s<i;){const n=s+i>>>1,r=this.messageSets[n];if(r.messages.length===0)return-1;r.messages[0].created_at.getTime()<=t?i=n:s=n+1}return s},this._channel=e,this.watcher_count=0,this.typing={},this.read={},this.initMessages(),this.pinnedMessages=[],this.pending_messages=[],this.threads={},this.mutedUsers=[],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){const 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){const t=this.messageSets.findIndex(s=>s.isLatest);this.messageSets[t].messages=e}get messagePagination(){return this.messageSets.find(e=>e.isCurrent)?.pagination||Ot}pruneOldest(e){const t=this.messageSets.findIndex(s=>s.isCurrent);if(this.messageSets[t].isLatest){const s=this.messageSets[t].messages;this.messageSets[t].messages=s.slice(-e),this.messageSets[t].pagination.hasPrev=!0}}addMessageSorted(e,t=!1,s=!0,i="latest"){return this.addMessagesSorted([e],t,!1,s,i)}addMessagesSorted(e,t=!1,s=!1,i=!0,n="current"){const{messagesToAdd:r,targetMessageSetIndex:a}=this.findTargetMessageSet(e,i,n);for(let o=0;o<r.length;o+=1){if(r[o].shadowed)continue;const c=r[o].created_at instanceof Date;let d;c?d=r[o]:(d=this.formatMessage(r[o]),d.user&&this._channel?.cid&&this._channel.getClient().state.updateUserReference(d.user,this._channel.cid),s&&d.id&&this.threads[d.id]&&delete this.threads[d.id],!(this._channel.getConfig()?.skip_last_msg_update_for_system_msgs&&d.type==="system")&&(!this.last_message_at||d.created_at.getTime()>this.last_message_at.getTime())&&(this.last_message_at=new Date(d.created_at.getTime())));const h=d.parent_id;if((!h||d.show_in_channel)&&a!==-1&&(this.messageSets[a].messages=this._addToMessageList(this.messageSets[a].messages,d,t,"created_at",i)),h&&!s){const f=this.threads[h]||[];this.threads[h]=this._addToMessageList(f,d,t,"created_at",i)}}return{messageSet:this.messageSets[a]}}addPinnedMessages(e){for(let t=0;t<e.length;t+=1)this.addPinnedMessage(e[t])}addPinnedMessage(e){this.pinnedMessages=this._addToMessageList(this.pinnedMessages,this.formatMessage(e),!1,"pinned_at")}removePinnedMessage(e){const{result:t}=this.removeMessageFromArray(this.pinnedMessages,e);this.pinnedMessages=t}addReaction(e,t,s){const i=t;let n;if(i||(n=this.findMessage(e.message_id)),!i&&!n)return;const r=i??n,a={id:r?.id,parent_id:r?.parent_id,pinned:r?.pinned,show_in_channel:r?.show_in_channel};
10return this._updateMessage(a,o=>{if(i){const l={...i};return i.own_reactions=this._addOwnReactionToMessage(o.own_reactions,e,s),l.own_reactions=this._channel.getClient().userID===e.user_id?i.own_reactions:o.own_reactions,this.formatMessage(l)}return n?this._addReactionToState(n,e,s):o}),i??n}_addReactionToState(e,t,s){if(e.reaction_groups||(e.reaction_groups={}),s)for(const o of e.own_reactions??[]){const l=e.reaction_groups[o.type];e.reaction_groups[o.type]={...l,count:l.count-1,sum_scores:l.sum_scores-(o.score??1)},e.reaction_groups[o.type].count<1&&delete e.reaction_groups[o.type]}const n=e.reaction_groups[t.type],r=t.score??1;e.reaction_groups[t.type]=n?{...n,count:n.count+1,sum_scores:n.sum_scores+r,last_reaction_at:t.created_at}:{count:1,first_reaction_at:t.created_at,last_reaction_at:t.created_at,sum_scores:r},e.own_reactions=this._addOwnReactionToMessage(e.own_reactions,t,s);const a=this._channel.getClient().userID;return e.latest_reactions=s?[...(e.latest_reactions||[]).filter(o=>o.user_id!==a),t]:[...e.latest_reactions||[],t],e}_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){const s=t;let i;if(s||(i=this.findMessage(e.message_id)),!s&&!i)return;const n=s??i,r={id:n?.id,parent_id:n?.parent_id,pinned:n?.pinned,show_in_channel:n?.show_in_channel};return this._updateMessage(r,a=>s?(s.own_reactions=this._removeOwnReactionFromMessage(a.own_reactions,e),this.formatMessage(s)):i?this._removeReactionFromState(i,e):a),s}_removeReactionFromState(e,t){const s=e.own_reactions?.find(n=>n.type===t.type);if(s&&e.reaction_groups?.[s.type]){const n=e.reaction_groups[s.type];e.reaction_groups[s.type]={...n,count:n.count-1,sum_scores:n.sum_scores-(s.score??1)},e.reaction_groups[s.type].count<1&&delete e.reaction_groups[s.type]}e.own_reactions=e.own_reactions?.filter(n=>n.type!==t.type);const i=this._channel.getClient().userID;return e.latest_reactions=e.latest_reactions?.filter(n=>!(n.user_id===i&&n.type===t.type)),e}_updateQuotedMessageReferences({message:e,remove:t}){const s=n=>({...n,created_at:n.created_at.toISOString(),pinned_at:n.pinned_at?.toISOString(),updated_at:n.updated_at?.toISOString()}),i=n=>{const r=n.reduce((a,o)=>(o.quoted_message_id===e.id&&a.push({...s(o),quoted_message:t?{...e,attachments:[]}:e}),a),[]);this.addMessagesSorted(r,!0)};e.parent_id?e.parent_id&&this.threads[e.parent_id]&&i(this.threads[e.parent_id]):this.messageSets.forEach(n=>i(n.messages))}removeQuotedMessageReferences(e){this._updateQuotedMessageReferences({message:e,remove:!0})}_updateMessage(e,t){const{parent_id:s,show_in_channel:i,pinned:n}=e;if(s&&this.threads[s]){const r=this.threads[s],a=r.findIndex(o=>o.id===e.id);a!==-1&&(r[a]=t(r[a]),this.threads[s]=r)}if(!i&&!s||i){const r=this.findMessageSetIndex(e);if(r!==-1){const a=this.messageSets[r].messages.findIndex(o=>o.id===e.id);if(a!==-1){const o=t(this.messageSets[r].messages[a]);this.messageSets[r].messages[a]=o}}}if(n){const r=this.pinnedMessages.findIndex(a=>a.id===e.id);r!==-1&&(this.pinnedMessages[r]=t(this.pinnedMessages[r]))}}_addToMessageList(e,t,s=!1,i="created_at",n=!0){return oa(e,t,s,i,n)}removeMessage(e){let t=!1;if(e.parent_id&&this.threads[e.parent_id]){const{removed:s,result:i}=this.removeMessageFromArray(this.threads[e.parent_id],e);this.threads[e.parent_id]=i,t=s}else{const s=e.messageSetIndex??this.findMessageSetIndex(e);if(s!==-1){const{removed:i,result:n}=this.removeMessageFromArray(this.messageSets[s].messages,e);this.messageSets[s].messages=n,t=i}}return t}filterErrorMessages(){const e=this.latestMessages.filter(s=>s.type!=="error"),t=this.latestMessages.filter(gh);for(const s of t)this._channel.getClient().offlineDb?.hardDeleteMessage({id:s.id});this.latestMessages=e}clean(){const e=new Date;for(const[t,s]of Object.entries(this.typing)){const 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,pagination:{...Ot}}]}async loadMessageIntoState(e,t,s=25){let i,n=!1,r=!1;const a=t||e;if(e==="latest"){if(this.messages===this.latestMessages)return;i=this.messageSets.findIndex(o=>o.isLatest)}else i=this.findMessageSetIndex({id:a});i!==-1&&(this.switchToMessageSet(i),n=!0),r=!t||!!this.threads[t]?.find(o=>
10o.id===e),!(n&&r)&&(n||await this._channel.query({messages:{id_around:a,limit:s}},"new"),!r&&t&&await this._channel.getReplies(t,{id_around:e,limit:s}),i=this.findMessageSetIndex({id:a}),i!==-1&&this.switchToMessageSet(i))}findMessage(e,t){if(t){const i=this.threads[t];return i?i.find(n=>n.id===e):void 0}const s=this.findMessageSetIndex({id:e});if(s!==-1)return this.messageSets[s].messages.find(i=>i.id===e)}findMessageByTimestamp(e,t,s=!1){if(t&&!this.threads[t]||this.messageSets.length===0)return null;const i=this.findMessageSetByOldestTimestamp(e),n=this.messageSets[i]?.messages;if(!n?.length)return null;const r=n[0].created_at.getTime(),a=n.slice(-1)[0].created_at.getTime();if((e<r||a<e)&&s)return null;let l=0,c=n.length-1;for(;l<c;){const h=l+c>>>1;e<=n[h].created_at.getTime()?c=h:l=h+1}const d=n[l];return s?d.created_at.getTime()===e?d:null:d}switchToMessageSet(e){const 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,n;if(e.length===0)return{targetMessageSetIndex:0,messagesToAdd:e};if(t){const r=this.messageSets.map((c,d)=>d).filter(c=>this.areMessageSetsOverlap(this.messageSets[c].messages,e)),a=this.messageSets.map((c,d)=>d).filter(c=>mh(this.messageSets[c].messages,e.map(B)));switch(s){case"new":if(r.length>0)n=r[0];else if(a.length>0)n=a[0];else if(e.some(c=>!c.parent_id)){const c=this.findMessageSetByOldestTimestamp(new Date(e[0].created_at).getTime());if(c===-1)this.messageSets.push({messages:[],isCurrent:!1,isLatest:!1,pagination:{...Ot}}),n=this.messageSets.length-1;else{const d=c===0;this.messageSets.splice(c,0,{messages:[],isCurrent:!1,isLatest:d,pagination:{...Ot}}),d&&this.messageSets.slice(1).forEach(h=>{h.isLatest=!1}),n=c}}break;case"current":a.length>0?n=a[0]:n=this.messageSets.findIndex(c=>c.isCurrent);break;case"latest":a.length>0?n=a[0]:n=this.messageSets.findIndex(c=>c.isLatest);break;default:n=-1}const o=r.splice(0,1)[0],l=[...r];if(o!==void 0&&o!==n&&l.push(n),l.length>0){const c=this.messageSets[o],d=this.messageSets.filter((f,p)=>l.indexOf(p)!==-1);d.forEach(f=>{c.isLatest=c.isLatest||f.isLatest,c.isCurrent=c.isCurrent||f.isCurrent,c.pagination.hasPrev=f.messages[0].created_at<c.messages[0].created_at?f.pagination.hasPrev:c.pagination.hasPrev,c.pagination.hasNext=c.messages.slice(-1)[0].created_at<f.messages.slice(-1)[0].created_at?f.pagination.hasNext:c.pagination.hasNext,i=[...i,...f.messages]}),d.forEach(f=>this.messageSets.splice(this.messageSets.indexOf(f),1)),n=this.messageSets.findIndex(f=>this.areMessageSetsOverlap(f.messages,e))}}else n=this.findMessageSetIndex(e[0]);return{targetMessageSetIndex:n,messagesToAdd:i}}},pa=e=>!!e?.og_scrape_url||!!e?.title_link,De=e=>!!e?.localMetadata?.id,yh=e=>!!e?.localMetadata?.uploadState,an=(e,t=[])=>e.type==="file"||!!(e.mime_type&&t.indexOf(e.mime_type)===-1&&e.type!=="video"),_h=e=>an(e)&&De(e),on=e=>e.type==="image"&&!pa(e),ln=e=>on(e)&&De(e),cn=e=>e.type==="audio",wh=e=>cn(e)&&De(e),dn=e=>e.type==="voiceRecording",bh=e=>dn(e)&&De(e),hn=(e,t=[])=>e.type==="video"||!!(e.mime_type&&t.indexOf(e.mime_type)!==-1),Ch=e=>hn(e)&&De(e),ga=e=>cn(e)||an(e)||on(e)||hn(e)||dn(e),Sh=e=>!!e.latitude&&!!e.longitude&&!!e.channel_cid,bt=e=>!!e.lastModified&&!("uri"in e),ma=e=>e==null||typeof e!="object"?!1:typeof FileList<"u"&&e instanceof FileList||"item"in e&&"length"in e&&!Array.isArray(e),ya=e=>e instanceof Blob&&!(e instanceof File),me=e=>e!==null&&typeof e=="object"&&!bt(e)&&!ya(e)&&typeof e.name=="string"&&typeof e.uri=="string"&&typeof e.size=="number"&&typeof e.type=="string",un=({blobsArray:e,fileName:t,mimeType:s})=>{const i=new Blob(e,{type:s});return new File([i],t,{type:i.type})},_a=e=>e.match(/\/([^/;]+)/)?.[1],fn=e=>{const t=_a(e);return`file_${new Date().toISOString()}${t?"."+t:""}`},He=e=>{const t=e.type;return t.startsWith("image/")&&!t.endsWith(".photoshop")},wa=e=>e.startsWith("image/")&&!e.endsWith(".photoshop")?"image":e.includes("video/")?"video":e.includes("audio/")?"audio":"file",Ci=e=>{if(!e)return null;if(De(e))return e;const{localMetadata:t,...s}=e;return{localMetadata:{...t??{},id:t?.id||W()},...s}},ba=()=>({id:"stream-io/attachment-manager-middleware/post-upload-enrichment",handlers:{postProcess:({state:e,discard:t,forward:s,next:i})=>{const{attachment:n,error:r,response:a}=e;if(r)return s();if(!n||!a)return t();const o={...n};return ln(n)?(n.localMetadata.previewUri&&(URL.revokeObjectURL(n.localMetadata.previewUri),delete o.localMetadata.previewUri),o.image_url=a.file):o.asset_url=a.file,a.thumb_url&&(o.thumb_url=a.thumb_url),i({...e,attachment:o})}}}),Ca=vh(Rh),Si=new Map;function vh(e){return function(s,i){const{cb:n,onContinued:r}=e(s,i),a=Si.get(s);a?.onContinued();const o=a?a.promise.then(n,n):n();return Si.set(s,{promise:o,onContinued:r}),o}}function Rh(e,t){const s=new AbortController;return{cb:()=>s.signal.aborted?Promise.resolve("canceled"):t(s.signal).finally(()=>{s.signal.aborted||Si.delete(e)}),onContinued:()=>s.abort()}}var we=class{constructor(){this.middleware=[],this.id=W()}use(e){return this.middleware=this.middleware.concat(e),this}replace(e){const t=[...this.middleware];return e.forEach(s=>{const i=this.middleware.findIndex(n=>n.id===s.id);i>=0?t.splice(i,1,s):t.push(s)}),this.middleware=t,this}insert({middleware:e,position:t,unique:s}){s&&e.forEach(a=>{const o=this.middleware.findIndex(l=>l.id===a.id);o>=0&&this.middleware.splice(o,1)});const i=t.after||t.before,n=this.middleware.findIndex(a=>a.id===i),r=t.after?n+1:n;return this.middleware.splice(r,0,...e),this}setOrder(e){this.middleware=e.map(t=>this.middleware.find(s=>
10s.id===t)).filter(Boolean)}remove(e){!e&&!e.length||(this.middleware=this.middleware.filter(t=>typeof e=="string"?e!==t.id:!e.includes(t.id)))}async executeMiddlewareChain({eventName:e,initialValue:t,mode:s="cancelable"}){let i=-1;const n=async(a,o,l)=>{if(a<=i)throw new Error("next() called multiple times");if(i=a,a===this.middleware.length||l&&["complete","discard"].includes(l))return{state:o,status:l};const h=this.middleware[a].handlers[e];return h?await h({state:o,next:m=>n(a+1,m),complete:m=>n(a+1,m,"complete"),discard:()=>n(a+1,o,"discard"),forward:()=>n(a+1,o)}):n(a+1,o,l)},r=s==="cancelable"?await Ca(`middleware-execution-${this.id}-${e}`,async a=>{const o=await n(0,t);return a.aborted?"canceled":o}):await n(0,t);return r==="canceled"?{state:t,status:"discard"}:r}async execute({eventName:e,initialValue:t,mode:s}){return await this.executeMiddlewareChain({eventName:e,initialValue:t,mode:s})}},Sa=e=>({id:"stream-io/attachment-manager-middleware/upload-error",handlers:{postProcess:({state:t,discard:s,forward:i})=>{const{attachment:n,error:r}=t;if(!r)return i();if(!n)return s();const a=r instanceof Error?r.message:"unknown error";return e.client.notifications.addError({message:"Error uploading attachment",origin:{emitter:"AttachmentManager",context:{attachment:n}},options:{type:"api:attachment:upload:failed",metadata:{reason:a},originalError:r}}),i()}}}),va=class extends we{constructor({composer:e}){super(),this.use([Sa(e),ba()])}},Ra=e=>({id:"stream-io/attachment-manager-middleware/file-upload-config-check",handlers:{prepare:async({state:t,next:s,discard:i})=>{const{attachmentManager:n}=e;if(!n||!t.attachment)return i();const r=await n.getUploadConfigCheck(t.attachment.localMetadata.file),a={...t.attachment,localMetadata:{...t.attachment.localMetadata,uploadPermissionCheck:r,uploadState:r.uploadBlocked?"blocked":"pending"}};return s({...t,attachment:a})}}}),Ea=e=>({id:"stream-io/attachment-manager-middleware/blocked-upload-notification",handlers:{prepare:({state:{attachment:t},forward:s})=>(t&&t.localMetadata.uploadPermissionCheck?.uploadBlocked&&e.client.notifications.addError({message:"The attachment upload was blocked",origin:{emitter:"AttachmentManager",context:{blockedAttachment:t}},options:{type:"validation:attachment:upload:blocked",metadata:{reason:t.localMetadata.uploadPermissionCheck?.reason}}}),s())}}),xa=class extends we{constructor({composer:e}){super(),this.use([Ra(e),Ea(e)])}},pn=e=>typeof e=="function",Eh=()=>{},U=class{constructor(e){this.value=e,this.handlers=new Set,this.preprocessors=new Set,this.partialNext=t=>this.next(s=>({...s,...t})),this.subscribeWithSelector=(t,s)=>{let i;const n=r=>{const a=t(r);let o=typeof i>"u";for(const c in i)if(i[c]!==a[c]){o=!0;break}if(!o)return;const l=i;i=a,s(a,l)};return this.subscribe(n)}}merge(e){return new Ma({original:this,merged:e})}next(e){const t=pn(e)?e(this.value):e;if(t===this.value)return;this.preprocessors.forEach(i=>i(t,this.value));const s=this.value;this.value=t,this.handlers.forEach(i=>i(this.value,s))}getLatestValue(){return this.value}subscribe(e){return e(this.value,void 0),this.handlers.add(e),()=>{this.handlers.delete(e)}}addPreprocessor(e){return this.preprocessors.add(e),()=>{this.preprocessors.delete(e)}}},Ma=class Wt extends U{constructor({original:t,merged:s}){const i=t.getLatestValue(),n=s.getLatestValue();super({...i,...n}),this.next=()=>{console.warn(`${Wt.name}.next is disabled, call original.next or merged.next instead`)},this.partialNext=()=>{console.warn(`${Wt.name}.partialNext is disabled, call original.partialNext or merged.partialNext instead`)},this.cachedOriginalValue=i,this.cachedMergedValue=n,this.original=t,this.merged=s}subscribe(t){const s=[];if(!this.handlers.size){const i=n=>{super.next(r=>({...r,...n}))};s.push(this.original.subscribe(n=>{n!==this.cachedOriginalValue&&(this.cachedOriginalValue=n,i(n))}),this.merged.subscribe(n=>{n!==this.cachedMergedValue&&(this.cachedMergedValue=n,i(n))}))}return s.push(super.subscribe(t)),()=>{s.forEach(i=>i())}}getLatestValue(){if(!this.handlers.size){const t=this.original.getLatestValue(),s=this.merged.getLatestValue();(t!==this.cachedOriginalValue||s!==this.cachedMergedValue)&&(this.value={...t,...s},this.cachedMergedValue=s,this.cachedOriginalValue=t)}return super.getLatestValue()}addPreprocessor(){return console.warn(`${Wt.name}.addPreprocessor is disabled, call original.addPreprocessor or merged.addPreprocessor instead`),Eh}},Ue=e=>{if(!e||typeof e!="object"||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===null||t===Object.prototype?!1:e.constructor&&e.constructor!==Object},vi=(e,t,s=new Set,i=new WeakSet,n=new WeakSet)=>{if(e===t)return!0;
10if(e==null||t==null)return!1;const r=typeof e;if(r!==typeof t)return!1;if(r!=="object")return e!==e&&t!==t?!0:e===t;const o=e,l=t;if(i.has(o)||n.has(l))return i.has(o)&&n.has(l);if(i.add(o),n.add(l),e instanceof Date&&t instanceof Date)return i.delete(o),n.delete(l),e.getTime()===t.getTime();if(e instanceof RegExp&&t instanceof RegExp)return i.delete(o),n.delete(l),e.toString()===t.toString();if(Ue(e)||Ue(t))return i.delete(o),n.delete(l),!1;const c=Array.isArray(e),d=Array.isArray(t);if(c!==d)return i.delete(o),n.delete(l),!1;if(c&&d){const m=e,g=t;if(m.length!==g.length)return i.delete(o),n.delete(l),!1;const _=[e,t];if(s.has(_))return i.delete(o),n.delete(l),!0;s.add(_);for(let b=0;b<m.length;b++)if(!vi(m[b],g[b],s,i,n))return s.delete(_),i.delete(o),n.delete(l),!1;return s.delete(_),i.delete(o),n.delete(l),!0}const h=e,f=t,p=Object.keys(h),y=Object.keys(f);if(p.length!==y.length)return i.delete(o),n.delete(l),!1;for(const m of y)if(!Object.prototype.hasOwnProperty.call(h,m))return i.delete(o),n.delete(l),!1;const w=[e,t];if(s.has(w))return i.delete(o),n.delete(l),!0;s.add(w);for(const m of p)if(!vi(h[m],f[m],s,i,n))return s.delete(w),i.delete(o),n.delete(l),!1;return s.delete(w),i.delete(o),n.delete(l),!0};function xh(e,t){const s={children:{}};return Aa(e,t,s),gn(s)}function Aa(e,t,s,i,n=new Set,r=new Set){if(vi(e,t,new Set(n)))return;if(e==null){i!==void 0&&(s.children[String(i)]={type:"added",value:t,children:{}});return}if(typeof e=="object"&&e!==null){if(r.has(e)){i!==void 0&&(s.children[String(i)]={type:"circular",value:t,oldValue:e,children:{}});return}r.add(e)}if(typeof e!="object"||typeof t!="object"||e===null||t===null||Array.isArray(e)!==Array.isArray(t)||Ue(e)||Ue(t)){i!==void 0&&(s.children[String(i)]={type:"updated",value:t,oldValue:e,children:{}}),typeof e=="object"&&e!==null&&r.delete(e);return}const o=e,l=t,c=i!==void 0?{type:"updated",children:{},oldValue:e,value:t}:s;i!==void 0&&(s.children[String(i)]=c);const d=[e,t];if(n.has(d)){typeof e=="object"&&e!==null&&r.delete(e);return}n.add(d);const h=new Set([...Object.keys(o),...Object.getOwnPropertySymbols(o),...Object.keys(l),...Object.getOwnPropertySymbols(l)]);for(const f of h){const p=o[f],y=l[f];if(f in l){if(!(f in o)){c.children[String(f)]={type:"added",value:y,children:{}};continue}Aa(p,y,c,f,n,r)}}n.delete(d),typeof e=="object"&&e!==null&&r.delete(e)}function Ua(e={}){const{trackDiff:t=!1}=e;return function({target:i,source:n,customizer:r}){const a=Array.isArray(n)?n:[n],o=t?structuredClone(i):void 0;function l(m,g,_,b,R,v){const M=r?.(m,g,_,b,R,v);return M!==void 0?(Object.defineProperty(b,_,{value:M,enumerable:!0,writable:!0,configurable:!0}),!0):!1}function c(m,g){if(m===null||typeof m>"u"||!Array.isArray(m)&&typeof m!="object")return g;if(m&&typeof m=="object"){const _=Ue(m),b=Ue(g);return _||b?b?g:m:Array.isArray(m)?[...m]:{...m}}return Array.isArray(g)?[]:{}}function d(m,g,_,b,R){const v=g[_],M=m[_];if(!l(M,v,_,m,g,b))if(v&&typeof v=="object"){if(!b.has(v)){const P=c(M,v);if(Object.defineProperty(m,_,{value:P,enumerable:!0,writable:!0,configurable:!0}),Ue(P))return;R.push({target:P,source:v,sourceKey:_,parentTarget:m})}}else v!==void 0&&(m[_]=v)}function h(m,g,_,b){const R=[...Object.keys(g),...Object.getOwnPropertySymbols(g)];for(const v of R)d(m,g,v,_,b)}function f({target:m,source:g,sourceKey:_,parentTarget:b},R,v){if(R.has(g)){t&&_&&b&&Object.defineProperty(b,_,{value:m,enumerable:!0,writable:!0,configurable:!0});return}!R.has(m)&&!R.has(g)&&(R.add(m),R.add(g),h(m,g,R,v),R.delete(g),R.delete(m))}function p(m,g,_=new Set){if(_.has(m)||_.has(g))return{...m};const b={...m},R=[];for(_.add(b),_.add(g),h(b,g,_,R);R.length;)f(R.pop(),_,R);return _.delete(g),_.delete(b),b}const y=a.reduce((m,g)=>p(m,g),{...i}),w=t&&o?xh(o,y):null;return{result:y,diff:w}}}function gn(e){const t={};let s=!1;for(const i in e.children){const n=gn(e.children[i]);n&&(t[i]=n,s=!0)}return e.type||s?{...e,children:t}:null}function Ve(e,t,s){return Ua()({target:e,source:t,customizer:s}).result}function Ta(e,t,s){const i=Ua({trackDiff:!0}),{result:n,diff:r}=i({target:e,source:t,customizer:s});return{result:n,diff:gn(r??{children:{}})||{children:{}}}}var rr=({message:e})=>({attachments:(e?.attachments??[])?.filter(({og_scrape_url:t})=>!t).map(t=>{const s=ga(t)?{id:W(),uploadState:"finished"}:{id:W()};return{...t,localMetadata:s}})}),La=class Ri{constructor({composer:t,message:s}){this.setCustomUploadFn=i=>{this.composer.updateConfig({attachments:{doUploadRequest:i}})},this.initState=({message:i}={})=>{this.state.next(rr({message:i}))},this.getAttachmentIndex=i=>
10{const n=this.attachmentsById;return this.attachments.indexOf(n[i])},this.prepareAttachmentUpdate=i=>{const n=this.attachments,r=[...this.attachments],a=this.getAttachmentIndex(i.localMetadata.id);if(a===-1)return null;const o=Ta(n[a],i);if(o.diff&&Object.keys(o.diff.children).length){const c=Ci(o.result);if(c)return r.splice(a,1,c),r}return null},this.updateAttachment=i=>{const n=this.prepareAttachmentUpdate(i);n&&this.state.partialNext({attachments:n})},this.upsertAttachments=i=>{if(!i.length)return;let n=[...this.attachments],r=!1;i.forEach(a=>{const o=this.prepareAttachmentUpdate(a);if(o)n=o,r=!0;else{const l=Ci(a);l&&(n.push(l),r=!0)}}),r&&this.state.partialNext({attachments:n})},this.removeAttachments=i=>{this.state.partialNext({attachments:this.attachments.filter(n=>!i.includes(n.localMetadata?.id))})},this.getUploadConfigCheck=async i=>{const n=this.channel.getClient();let r;n.appSettingsPromise?r=await n.appSettingsPromise:r=await n.getAppSettings();const a=He(i)?r?.app?.image_upload_config:r?.app?.file_upload_config;if(!a)return{uploadBlocked:!1};const{allowed_file_extensions:o,allowed_mime_types:l,blocked_file_extensions:c,blocked_mime_types:d,size_limit:h}=a,f=h||Bd,p=i.type;if(bt(i)||me(i)){if(o?.length&&!o.some(y=>i.name.toLowerCase().endsWith(y.toLowerCase())))return{uploadBlocked:!0,reason:"allowed_file_extensions"};if(c?.length&&c.some(y=>i.name.toLowerCase().endsWith(y.toLowerCase())))return{uploadBlocked:!0,reason:"blocked_file_extensions"}}return l?.length&&!l.some(y=>y.toLowerCase()===p?.toLowerCase())?{uploadBlocked:!0,reason:"allowed_mime_types"}:d?.length&&d.some(y=>y.toLowerCase()===p?.toLowerCase())?{uploadBlocked:!0,reason:"blocked_mime_types"}:i.size&&i.size>f?{uploadBlocked:!0,reason:"size_limit"}:{uploadBlocked:!1}},this.fileToLocalUploadAttachment=async i=>{const n=Ri.toLocalUploadAttachment(i),r=await this.getUploadConfigCheck(n.localMetadata.file);return n.localMetadata.uploadPermissionCheck=r,n.localMetadata.uploadState=r.uploadBlocked?"blocked":"pending",n},this.ensureLocalUploadAttachment=async i=>{if(!i.localMetadata?.file){this.client.notifications.addError({message:"File is required for upload attachment",origin:{emitter:"AttachmentManager",context:{attachment:i}},options:{type:"validation:attachment:file:missing"}});return}if(!i.localMetadata.id){this.client.notifications.addError({message:"Local upload attachment missing local id",origin:{emitter:"AttachmentManager",context:{attachment:i}},options:{type:"validation:attachment:id:missing"}});return}if(!this.fileUploadFilter(i))return;const n=await this.fileToLocalUploadAttachment(i.localMetadata.file);return i.localMetadata.id&&(n.localMetadata.id=i.localMetadata.id),n},this.doDefaultUploadRequest=async i=>{if(me(i))return this.channel[He(i)?"sendImage":"sendFile"](i.uri,i.name,i.type);const n=bt(i)?i:un({blobsArray:[i],fileName:fn(i.type),mimeType:i.type}),{duration:r,...a}=await this.channel[He(i)?"sendImage":"sendFile"](n);return a},this.doUploadRequest=async i=>{const n=this.config.doUploadRequest;return n?await n(i):this.doDefaultUploadRequest(i)},this.uploadAttachment=async i=>{if(!this.isUploadEnabled)return;const n=await this.ensureLocalUploadAttachment(i);if(typeof n>"u")return;if(n.localMetadata.uploadState==="blocked")return this.upsertAttachments([n]),this.client.notifications.addError({message:"The attachment upload was blocked",origin:{emitter:"AttachmentManager",context:{attachment:i,blockedAttachment:n}},options:{type:"validation:attachment:upload:blocked",metadata:{reason:n.localMetadata.uploadPermissionCheck?.reason}}}),n;this.upsertAttachments([{...i,localMetadata:{...i.localMetadata,uploadState:"uploading"}}]);let r;try{r=await this.doUploadRequest(n.localMetadata.file)}catch(o){const l=o instanceof Error?o.message:"unknown error",c={...i,localMetadata:{...i.localMetadata,uploadState:"failed"}};return this.client.notifications.addError({message:"Error uploading attachment",origin:{emitter:"AttachmentManager",context:{attachment:i,failedAttachment:c}},options:{type:"api:attachment:upload:failed",metadata:{reason:l},originalError:o instanceof Error?o:void 0}}),this.updateAttachment(c),c}if(!r){this.removeAttachments([i.localMetadata.id]);return}const a={...i,localMetadata:{...i.localMetadata,uploadState:"finished"}};return ln(a)?(a.localMetadata.previewUri&&(URL.revokeObjectURL(a.localMetadata.previewUri),delete a.localMetadata.previewUri),a.image_url=r.file):a.asset_url=r.file,r.thumb_url&&(a.thumb_url=r.thumb_url),this.updateAttachment(a),a},this.uploadFile=async i=>{const n=await this.preUploadMiddlewareExecutor.execute({eventName:"prepare",initialValue:{attachment:Ri.toLocalUploadAttachment(i)},mode:"concurrent"});let r=n.state.attachment;if(n.status==="discard"||!this.fileUploadFilter(r))return r;if(r.localMetadata.uploadState==="blocked")return this.upsertAttachments([r]),n.state.attachment;r={...r,localMetadata:{...r.localMetadata,uploadState:"uploading"}},this.upsertAttachments([r]);let a,o;try{a=await this.doUploadRequest(i)}catch(c){o=c instanceof Error?c:void 0}const l=await this.postUploadMiddlewareExecutor.execute({eventName:"postProcess",initialValue:{attachment:{...r,localMetadata:{...r.localMetadata,uploadState:o?"failed":"finished"}},error:o,response:a},mode:"concurrent"});return r=l.state.attachment,l.status==="discard"?(this.removeAttachments([r.localMetadata.id]),r):(this.updateAttachment(r),r)},this.uploadFiles=async i=>{if(!this.isUploadEnabled)return;const n=ma(i)?Array.from(i):i;return await Promise.all(n.slice(0,this.availableUploadSlots).map(this.uploadFile))},this.composer=t,this.state=new U(rr({message:s})),this.attachmentsByIdGetterCache={attachmentsById:{},attachments:[]},this.preUploadMiddlewareExecutor=new xa({composer:t}),this.postUploadMiddlewareExecutor=new va({composer:t})}get attachmentsById(){const{attachments:t}=this.state.getLatestValue();return t!==this.attachmentsByIdGetterCache.attachments&&(this.attachmentsByIdGetterCache.attachments=t,this.attachmentsByIdGetterCache.attachmentsById=t.reduce((s,i)=>{var n;return i.localMetadata.id&&(s[n=i.localMetadata.id]??(s[n]=i)),s},{})),this.attachmentsByIdGetterCache.attachmentsById}get client(){return this.composer.client}get channel(){return this.composer.channel}
10get config(){return this.composer.config.attachments}get acceptedFiles(){return this.config.acceptedFiles}set acceptedFiles(t){this.composer.updateConfig({attachments:{acceptedFiles:t}})}get fileUploadFilter(){return this.config.fileUploadFilter}set fileUploadFilter(t){this.composer.updateConfig({attachments:{fileUploadFilter:t}})}get maxNumberOfFilesPerMessage(){return this.config.maxNumberOfFilesPerMessage}set maxNumberOfFilesPerMessage(t){t!==this.maxNumberOfFilesPerMessage&&this.composer.updateConfig({attachments:{maxNumberOfFilesPerMessage:t}})}get attachments(){return this.state.getLatestValue().attachments}get hasUploadPermission(){return!!this.channel.data?.own_capabilities?.includes("upload-file")}get isUploadEnabled(){return this.hasUploadPermission&&this.availableUploadSlots>0}get successfulUploads(){return this.getUploadsByState("finished")}get successfulUploadsCount(){return this.successfulUploads.length}get uploadsInProgressCount(){return this.getUploadsByState("uploading").length}get failedUploadsCount(){return this.getUploadsByState("failed").length}get blockedUploadsCount(){return this.getUploadsByState("blocked").length}get pendingUploadsCount(){return this.getUploadsByState("pending").length}get availableUploadSlots(){return this.config.maxNumberOfFilesPerMessage-this.successfulUploadsCount-this.uploadsInProgressCount}getUploadsByState(t){return Object.values(this.attachments).filter(({localMetadata:s})=>s.uploadState===t)}};La.toLocalUploadAttachment=e=>{const t=me(e)||bt(e)?e:un({blobsArray:[e],fileName:fn(e.type),mimeType:e.type}),s={file_size:t.size,mime_type:t.type,localMetadata:{file:t,id:W(),uploadState:"pending"},type:wa(t.type)};return s[He(t)?"fallback":"title"]=t.name,He(t)&&(s.localMetadata.previewUri=me(e)?e.uri:URL.createObjectURL?.(e),me(e)&&e.height&&e.width&&(s.original_height=e.height,s.original_width=e.width)),me(e)&&e.thumb_url&&(s.thumb_url=e.thumb_url),me(e)&&e.duration&&(s.duration=e.duration),s};var Ia=La,Da={debounceURLEnrichmentMs:1500,enabled:!1,findURLFn:e=>xd(e,"url",{defaultProtocol:"https"}).reduce((t,s)=>{try{const i=new URL(s.href);s.isLink&&/^[a-zA-Z0-9-.]+\.[a-zA-Z]{2,}$/.test(i.hostname)&&t.push(s.href)}catch{}return t},[])},Oa={acceptedFiles:[],fileUploadFilter:()=>!0,maxNumberOfFilesPerMessage:qd},Pa={enabled:!0,publishTypingEvents:!0},ka={enabled:!0,getDeviceId:()=>W()},Na={attachments:Oa,drafts:{enabled:!1},linkPreviews:Da,location:ka,text:Pa},ar=e=>e?{message:{},custom:{}}:{message:{},custom:{}},Fa=class{constructor({composer:e,message:t}){this.isMessageDataEqual=(s,i)=>JSON.stringify(s.message)===JSON.stringify(i?.message),this.initState=({message:s}={})=>{this.state.next(ar({composer:this.composer}))},this.composer=e,this.state=new U(ar({}))}get customMessageData(){return this.state.getLatestValue().message}get customComposerData(){return this.state.getLatestValue().custom}setMessageData(e){this.state.partialNext({message:{...this.state.getLatestValue().message,...e}})}setCustomData(e){this.state.partialNext({custom:{...this.state.getLatestValue().custom,...e}})}},Mh=e=>new Map(e.map(t=>[t.og_scrape_url,t])),or=({message:e})=>e?{previews:e.attachments?.reduce((t,s)=>(s.og_scrape_url&&t.set(s.og_scrape_url,{...s,status:"loaded"}),t),new Map)??new Map}:{previews:new Map},Oe=class Re{constructor({composer:t,message:s}){this.shouldDiscardEnrichQueries=!1,this.initState=({message:i}={})=>{this.state.next(or({message:this.enabled?i:void 0}))},this._findAndEnrichUrls=async i=>{if(!this.enabled)return;const n=this.config.findURLFn(i);if(this.shouldDiscardEnrichQueries=!n.length,this.shouldDiscardEnrichQueries){this.state.next({previews:new Map});return}const r=new Map(Array.from(this.previews).filter(([o])=>n.includes(o)||n.includes(o+"/"))),a=n.filter(o=>{const l=this.previews;return!(l.get(o)||l.get(o+"/"))}).map(o=>({og_scrape_url:o.trim(),status:"loading"}));a.length&&(this.state.partialNext({previews:new Map([...r,...Mh(a)])}),await Promise.all(a.map(async o=>{try{const{duration:l,...c}=await this.client.enrichURL(o.og_scrape_url);if(this.shouldDiscardEnrichQueries)return;this.previews.has(o.og_scrape_url)&&this.updatePreview(o.og_scrape_url,{status:"loaded",...c})}catch{this.previews.has(o.og_scrape_url)&&this.updatePreview(o.og_scrape_url,{status:"failed"})}return o}
10)))},this.cancelURLEnrichment=()=>{this.findAndEnrichUrls.cancel(),this.findAndEnrichUrls.flush()},this.clearPreviews=()=>{const i=this.previews,n=new Map;i.forEach((r,a)=>{Re.previewIsDismissed(r)&&n.set(a,r)}),this.state.partialNext({previews:n})},this.updatePreview=(i,n)=>{if(!i)return;const r=this.previews.get(i),a=n.status??this.previews.get(i)?.status??"pending";let o=n;if(r){const l=Ta(r,n);if(!l.diff||Object.keys(l.diff).length===0)return;o=l.result}this.state.partialNext({previews:new Map(this.previews).set(i,{...o,og_scrape_url:i,status:a})})},this.dismissPreview=i=>{const n=this.previews.get(i);n&&(this.onLinkPreviewDismissed?.(n),this.updatePreview(i,{status:"dismissed"}))},this.composer=t,this.state=new U(or({message:this.enabled?s:void 0})),this.findAndEnrichUrls=wt(this._findAndEnrichUrls.bind(this),this.config.debounceURLEnrichmentMs)}get client(){return this.composer.client}get channel(){return this.composer.channel}get previews(){return this.state.getLatestValue().previews}get loadingPreviews(){return Array.from(this.previews.values()).filter(t=>Re.previewIsLoading(t))}get loadedPreviews(){return Array.from(this.previews.values()).filter(t=>Re.previewIsLoaded(t))}get dismissedPreviews(){return Array.from(this.previews.values()).filter(t=>Re.previewIsDismissed(t))}get failedPreviews(){return Array.from(this.previews.values()).filter(t=>Re.previewIsFailed(t))}get pendingPreviews(){return Array.from(this.previews.values()).filter(t=>Re.previewIsPending(t))}get config(){return this.composer.config.linkPreviews}get debounceURLEnrichmentMs(){return this.config.debounceURLEnrichmentMs}set debounceURLEnrichmentMs(t){this.cancelURLEnrichment(),this.findAndEnrichUrls=wt(this._findAndEnrichUrls.bind(this),this.config.debounceURLEnrichmentMs),this.composer.updateConfig({linkPreviews:{debounceURLEnrichmentMs:t}})}get enabled(){return!!this.channel.getConfig()?.url_enrichment&&this.composer.config.linkPreviews.enabled}set enabled(t){t!==this.enabled&&this.composer.updateConfig({linkPreviews:{enabled:t}})}get findURLFn(){return this.config.findURLFn}set findURLFn(t){this.composer.updateConfig({linkPreviews:{findURLFn:t}})}get onLinkPreviewDismissed(){return this.config.onLinkPreviewDismissed}set onLinkPreviewDismissed(t){this.composer.updateConfig({linkPreviews:{onLinkPreviewDismissed:t}})}};Oe.previewIsLoading=e=>e.status==="loading";Oe.previewIsLoaded=e=>e.status==="loaded";Oe.previewIsDismissed=e=>e.status==="dismissed";Oe.previewIsFailed=e=>e.status==="failed";Oe.previewIsPending=e=>e.status==="pending";Oe.getPreviewData=e=>{const{status:t,...s}=e;return s};var Fs=Oe,Ah=60*1e3,lr=({message:e})=>({location:e?.shared_location??null}),Ba=class{constructor({composer:e,message:t}){this.initState=({message:s}={})=>{this.state.next(lr({message:s}))},this.setData=s=>{this.config.enabled&&(!s.latitude||!s.longitude||this.state.partialNext({location:{...s,message_id:this.composer.id,created_by_device_id:this.deviceId}}))},this.composer=e,this.state=new U(lr({message:t})),this._deviceId=this.config.getDeviceId()}get config(){return this.composer.config.location}get deviceId(){return this._deviceId}get location(){return this.state.getLatestValue().location}get validLocation(){const{durationMs:e,...t}=this.location??{};return t?.created_by_device_id&&t.message_id&&t.latitude&&t.longitude&&(typeof e>"u"||e>=Ah)?{...t,end_at:e&&new Date(Date.now()+e).toISOString()}:null}},Bs=/^([2-9]|10)$/,qa=100,cr=e=>!e.trim(),Ls={enforce_unique_vote:()=>({max_votes_allowed:void 0}),max_votes_allowed:({data:e,value:t})=>e.enforce_unique_vote&&t?{max_votes_allowed:"Enforce unique vote is enabled"}:!t.match(/^[0-9]+$/)&&t?{max_votes_allowed:"Only numbers are allowed"}:t?.length>1&&!t.match(Bs)?{max_votes_allowed:"Type a number from 2 to 10"}:{max_votes_allowed:void 0},options:({value:e})=>{const t={},s=new Set;return e.forEach(i=>{s.has(i.text)&&i.text.length?t[i.id]="Option already exists":s.add(i.text)}),Object.keys(t).length>0?{options:t}:{options:void 0}}},$a={name:({currentError:e,value:t})=>t&&e?{name:void 0}:{name:typeof e=="string"?e:void 0}},Ha={max_votes_allowed:({value:e})=>e&&!e.match(Bs)?{max_votes_allowed:"Type a number from 2 to 10"}:{max_votes_allowed:void 0},name:({value:e})=>cr(e)?{name:"Question is required"}:{name:void 0},options:e=>{const s=Ls.options?.(e)?.options??{};return e.value.forEach((i,n)=>{const r=n===e.value.length-1;cr(i.text)&&!r&&(s[i.id]="Option is empty")}),Object.keys(s).length>0?{options:s}:{options:void 0}}},Va=e=>!Array.isArray(e)&&typeof e?.index=="number"&&typeof e?.text=="string",ja={enforce_unique_vote:({value:e})=>({enforce_unique_vote:e,max_votes_allowed:""}),options:({value:e,data:t})=>{if(Array.isArray(e))return{options:e.map(d=>({id:d.id,text:d.text.trim()}))};const{index:s,text:i}=e,n=t.options||[],r=n&&n.slice(s+1).length>0&&!i,a=n.slice(0,s),o=n.slice(s+1),l=[...a,...r?[]:[{...n[s],text:i}],...o];return n.length<qa&&!l.some(d=>!d.text.trim())&&l.push({id:W(),text:""}),{options:l}}},Wa=({processors:e,validators:t}={})=>{const s=({state:i,validators:n,processors:r})=>{const{previousState:a,targetFields:o}=i;let l;if(!r&&Va(o.options)){const d=[...a.data.options],h=a.data.options[o.options.index];h&&(h.text=o.options.text,d.splice(o.options.index,1,h)),l={...o,options:d}}else r?l=Object.entries(o).reduce((d,[h,f])=>{const p=r[h];return d={...d,...p?p({data:a.data,value:f}):{[h]:f}},d},{}):l=o;const c=Object.keys(o).reduce((d,h)=>{const f=n[h];if(f){const p=f({currentError:a.errors[h],data:a.data,value:l[h]});d={...d,...p}}return d},{});return{newData:l,newErrors:c}};return{id:"stream-io/poll-composer-state-processing",handlers:{handleFieldChange:({state:i,next:n,forward:r})=>{if(!i.targetFields)return r();const{previousState:a,injectedFieldErrors:o}
10=i,{newData:l,newErrors:c}=s({processors:{...ja,...e?.handleFieldChange},state:i,validators:{...Ls,...$a,...t?.handleFieldChange}});return n({...i,nextState:{...a,data:{...a.data,...l},errors:{...a.errors,...c,...o}}})},handleFieldBlur:({state:i,next:n,forward:r})=>{if(!i.targetFields)return r();const{previousState:a}=i,{newData:o,newErrors:l}=s({processors:e?.handleFieldBlur,state:i,validators:{...Ls,...Ha,...t?.handleFieldBlur}});return n({...i,nextState:{...a,data:{...a.data,...o},errors:{...a.errors,...l,...i.injectedFieldErrors}}})}}}},Uh=e=>({id:"stream-io/poll-composer-composition",handlers:{compose:({discard:t,forward:s})=>e.pollComposer.canCreatePoll?s():t()}}),za=class extends we{constructor({composer:e}){super(),this.use([Uh(e)])}},Qa=class extends we{constructor(){super(),this.use([Wa()])}},Ga=class extends Error{constructor(e,{code:t,status:s,response:i}){super(e),this.name="ErrorFromResponse",this.code=t,this.response=i,this.status=s}toJSON(){const e=[["status",this.status],["code",this.code]],t=[];for(const[s,i]of e)typeof i<"u"&&i!==null&&t.push(`${s}: ${i}`);return{message:`(${t.join(", ")}) - ${this.message}`,stack:this.stack,name:this.name,code:this.code,status:this.status}}},Ka=(e=>(e.anonymous="anonymous",e.public="public",e))(Ka||{}),Ja=class{constructor({composer:e}){this.initState=()=>{this.state.next(this.initialState)},this.updateFields=async(t,s)=>{const{state:i,status:n}=await this.stateMiddlewareExecutor.execute({eventName:"handleFieldChange",initialValue:{nextState:{...this.state.getLatestValue()},previousState:{...this.state.getLatestValue()},targetFields:t,injectedFieldErrors:s}});n!=="discard"&&this.state.next(i.nextState)},this.handleFieldBlur=async t=>{const s=await this.stateMiddlewareExecutor.execute({eventName:"handleFieldBlur",initialValue:{nextState:{...this.state.getLatestValue()},previousState:{...this.state.getLatestValue()},targetFields:{[t]:this.state.getLatestValue().data[t]}}});s.status!=="discard"&&this.state.next(s.state.nextState)},this.compose=async()=>{const{data:t,errors:s}=this.state.getLatestValue(),i=await this.compositionMiddlewareExecutor.execute({eventName:"compose",initialValue:{data:{...t,max_votes_allowed:t.max_votes_allowed?parseInt(t.max_votes_allowed):void 0,options:t.options?.filter(n=>n.text.trim()).map(n=>({text:n.text}))},errors:s}});if(i.status!=="discard")return i.state},this.composer=e,this.state=new U(this.initialState),this.compositionMiddlewareExecutor=new za({composer:e}),this.stateMiddlewareExecutor=new Qa}get initialState(){return{data:{allow_answers:!1,allow_user_suggested_options:!1,description:"",enforce_unique_vote:!0,id:W(),max_votes_allowed:"",name:"",options:[{id:W(),text:""}],user_id:this.composer.client.user?.id,voting_visibility:"public"},errors:{}}}get allow_answers(){return this.state.getLatestValue().data.allow_answers}get allow_user_suggested_options(){return this.state.getLatestValue().data.allow_user_suggested_options}get description(){return this.state.getLatestValue().data.description}get enforce_unique_vote(){return this.state.getLatestValue().data.enforce_unique_vote}get id(){return this.state.getLatestValue().data.id}get max_votes_allowed(){return this.state.getLatestValue().data.max_votes_allowed}get name(){return this.state.getLatestValue().data.name}get options(){return this.state.getLatestValue().data.options}get user_id(){return this.state.getLatestValue().data.user_id}get voting_visibility(){return this.state.getLatestValue().data.voting_visibility}get canCreatePoll(){const{data:e,errors:t}=this.state.getLatestValue(),s=e.options.filter(a=>!!a.text.trim()).length>0,i=!!e.name,n=parseInt(e.max_votes_allowed?.match(Bs)?.[0]||""),r=e.max_votes_allowed===""||!!n&&(2<=n||n<=10);return s&&i&&r&&Object.values(t).filter(a=>!!a).length===0}},Xa=e=>{const{localMetadata:t,...s}=e;return s},Ya=e=>({id:"stream-io/message-composer-middleware/attachments",handlers:{compose:({state:t,next:s,discard:i,forward:n})=>{const{attachmentManager:r}=e;if(!r)return n();if(r.uploadsInProgressCount>0)return e.client.notifications.addWarning({message:"Wait until all attachments have uploaded",origin:{emitter:"MessageComposer",context:{composer:e}},options:{type:"validation:attachment:upload:in-progress"}}),i();const a=(t.message.attachments??[]).concat(r.successfulUploads.map(Xa));
10return a.length?s({...t,localMessage:{...t.localMessage,attachments:a},message:{...t.message,attachments:a}}):n()}}}),Za=e=>({id:"stream-io/message-composer-middleware/draft-attachments",handlers:{compose:({state:t,next:s,forward:i})=>{const{attachmentManager:n}=e;if(!n)return i();const r=n.successfulUploads,a=r.length?(t.draft.attachments??[]).concat(r.map(Xa)):void 0;return s({...t,draft:{...t.draft,attachments:a}})}}}),eo=e=>({id:"stream-io/message-composer-middleware/data-cleanup",handlers:{compose:({state:t,next:s})=>{const n={type:!e.editedMessage?.type||e.editedMessage.type==="error"?"regular":e.editedMessage.type},r=e.editedMessage?ra(e.editedMessage):void 0;return s({...t,localMessage:B({...e.editedMessage,...t.localMessage,...n}),message:{...r,...t.message,...n},sendOptions:e.editedMessage&&t.sendOptions?.skip_enrich_url?{skip_enrich_url:t.sendOptions?.skip_enrich_url}:t.sendOptions})}}}),to=e=>({id:"stream-io/message-composer-middleware/custom-data",handlers:{compose:({state:t,next:s,forward:i})=>{const n=e.customDataManager.customMessageData;return n?s({...t,localMessage:{...t.localMessage,...n},message:{...t.message,...n}}):i()}}}),so=e=>({id:"stream-io/message-composer-middleware/draft-custom-data",handlers:{compose:({state:t,next:s,forward:i})=>{const n=e.customDataManager.customMessageData;return n?s({...t,draft:{...t.draft,...n}}):i()}}}),io=e=>({id:"stream-io/message-composer-middleware/data-validation",handlers:{compose:async({state:t,discard:s,forward:i})=>{const{maxLengthOnSend:n}=e.config.text??{},r=t.message.text??"",a=typeof n=="number"&&r.length>n;return e.compositionIsEmpty||a?await s():await i()}}}),no=e=>({id:"stream-io/message-composer-middleware/draft-data-validation",handlers:{compose:async({state:t,discard:s,forward:i})=>{const n=!wn(t.draft.text??"")||t.draft.attachments?.length||t.draft.poll_id||t.draft.quoted_message_id;return e.lastChangeOriginIsLocal&&n?await i():await s()}}}),ro=e=>({id:"stream-io/message-composer-middleware/link-previews",handlers:{compose:({state:t,next:s,forward:i})=>{const{linkPreviewsManager:n}=e;if(!n)return i();n.cancelURLEnrichment();const r=n.loadingPreviews.length>0,a=n.dismissedPreviews.length>0,o=n.loadingPreviews.length>0?[]:n.loadedPreviews.map(h=>Fs.getPreviewData(h)),l=(t.message.attachments??[]).concat(o);if(!l.length)return i();const c={...t.sendOptions};return(!r&&o.length>0||a)&&(c.skip_enrich_url=!0),s({...t,message:{...t.message,attachments:l},localMessage:{...t.localMessage,attachments:l},sendOptions:c})}}}),ao=e=>({id:"stream-io/message-composer-middleware/draft-link-previews",handlers:{compose:({state:t,next:s,forward:i})=>{const{linkPreviewsManager:n}=e;if(!n)return i();n.cancelURLEnrichment();const r=n.loadedPreviews.map(a=>Fs.getPreviewData(a));return r.length?s({...t,draft:{...t.draft,attachments:(t.draft.attachments??[]).concat(r)}}):i()}}}),oo=e=>({id:"stream-io/message-composer-middleware/text-composition",handlers:{compose:({state:t,next:s,forward:i})=>{if(!e.textComposer)return i();const{mentionedUsers:n,text:r}=e.textComposer,a=Array.from(new Set(n.filter(({id:o,name:l})=>r.includes(`@${o}`)||r.includes(`@${l}`))));return!r&&a.length===0?i():s({...t,localMessage:{...t.localMessage,mentioned_users:a,text:r},message:{...t.message,mentioned_users:a.map(o=>o.id),text:r}})}}}),lo=e=>({id:"stream-io/message-composer-middleware/draft-text-composition",handlers:{compose:({state:t,next:s,forward:i})=>{if(!e.textComposer)return i();const{maxLengthOnSend:n}=e.config.text??{},{mentionedUsers:r,text:a}=e.textComposer,o=r.length?Array.from(new Set(r.filter(({id:c,name:d})=>a.includes(`@${c}`)||a.includes(`@${d}`)))):void 0,l=typeof n=="number"&&a.length>n?a.slice(0,n):a;return s({...t,draft:{...t.draft,mentioned_users:o?.map(c=>c.id),text:l}})}}}),co=e=>({id:"stream-io/message-composer-middleware/own-state",handlers:{compose:({state:t,next:s})=>{const i={};return e.quotedMessage&&(i.quoted_message_id=e.quotedMessage.id),e.pollId&&(i.poll_id=e.pollId),e.showReplyInChannel&&(i.show_in_channel=!0),s({...t,localMessage:{...t.localMessage,...i,quoted_message:e.quotedMessage??void 0},message:{...t.message,...i}})}}}),ho=e=>({id:"stream-io/message-composer-middleware/draft-own-state",handlers:{compose:({state:t,next:s})=>{const i={};return e.quotedMessage&&(i.quoted_message_id=e.quotedMessage.id),e.pollId&&(i.poll_id=e.pollId),e.showReplyInChannel&&(i.show_in_channel=!0),s({...t,draft:{...t.draft,...i}})}}}),Th=e=>({id:"stream-io/message-composer-middleware/user-data-injection",handlers:{compose:({state:t,next:s,forward:i})=>{if(!e.client.user)return i();const{channel_mutes:n,devices:r,mutes:a,...o}=e.client.user;
10return s({...t,localMessage:{...t.localMessage,user:o,user_id:o.id}})}}}),Lh={attachments:[],mentioned_users:[],parent_id:void 0,quoted_message:void 0,text:""},Ih=e=>({id:"stream-io/message-composer-middleware/poll-only",handlers:{compose:({state:t,complete:s,forward:i})=>{const n=e.pollId,r=!!e.editedMessage,a=!!e.threadId;return!n||a||r?i():s({...t,localMessage:{...t.localMessage,...Lh,poll_id:n},message:{id:t.localMessage.id,poll_id:n}})}}}),uo=e=>({id:"stream-io/message-composer-middleware/shared-location",handlers:{compose:({state:t,next:s,forward:i})=>{const{locationComposer:n}=e,r=n.validLocation;if(!n||!r||!e.client.user)return i();const a=new Date().toISOString();return s({...t,localMessage:{...t.localMessage,shared_location:{...r,channel_cid:e.channel.cid,created_at:a,updated_at:a,user_id:e.client.user.id}},message:{...t.message,shared_location:r}})}}}),fo=class extends we{constructor({composer:e}){super(),this.use([Th(e),Ih(e),oo(e),Ya(e),ro(e),uo(e),co(e),to(e),io(e),eo(e)])}},po=class extends we{constructor({composer:e}){super(),this.use([lo(e),Za(e),ao(e),ho(e),so(e),no(e)])}},Dh={"-1":{name:"InternalSystemError",retryable:!0},2:{name:"AccessKeyError",retryable:!1},3:{name:"AuthenticationFailedError",retryable:!0},4:{name:"InputError",retryable:!1},6:{name:"DuplicateUsernameError",retryable:!1},9:{name:"RateLimitError",retryable:!0},16:{name:"DoesNotExistError",retryable:!1},17:{name:"NotAllowedError",retryable:!1},18:{name:"EventNotSupportedError",retryable:!1},19:{name:"ChannelFeatureNotSupportedError",retryable:!1},20:{name:"MessageTooLongError",retryable:!1},21:{name:"MultipleNestingLevelError",retryable:!1},22:{name:"PayloadTooBigError",retryable:!1},23:{name:"RequestTimeoutError",retryable:!0},24:{name:"MaxHeaderSizeExceededError",retryable:!1},40:{name:"AuthErrorTokenExpired",retryable:!1},41:{name:"AuthErrorTokenNotValidYet",retryable:!1},42:{name:"AuthErrorTokenUsedBeforeIssuedAt",retryable:!1},43:{name:"AuthErrorTokenSignatureInvalid",retryable:!1},44:{name:"CustomCommandEndpointMissingError",retryable:!1},45:{name:"CustomCommandEndpointCallError",retryable:!0},46:{name:"ConnectionIDNotFoundError",retryable:!1},60:{name:"CoolDownError",retryable:!0},69:{name:"ErrWrongRegion",retryable:!1},70:{name:"ErrQueryChannelPermissions",retryable:!1},71:{name:"ErrTooManyConnections",retryable:!0},99:{name:"AppSuspendedError",retryable:!1}};function qs(e){return e.code!==void 0}function Ct(e){if(!e.code)return!1;const t=Dh[`${e.code}`];return t?t.retryable:!1}function Oh(e){return e.code===46}function Ph(e){if(typeof e.isWSFailure=="boolean")return e.isWSFailure;try{return JSON.parse(e.message).isWSFailure}catch{return!1}}function kh(e){return!e.status||e.status<200||300<=e.status}var mn={debounceMs:300,pageSize:10},go=class{constructor(e){this.activate=()=>{this.isActive||this.state.partialNext({isActive:!0})},this.deactivate=()=>{this.isActive&&this.state.partialNext({isActive:!1})},this.canExecuteQuery=s=>{const i=typeof s<"u",n=s??this.searchQuery;return!!(this.isActive&&!this.isLoading&&(this.hasNext||i)&&n)};const{pageSize:t}={...mn,...e};this.pageSize=t,this.state=new U(this.initialState)}get lastQueryError(){return this.state.getLatestValue().lastQueryError}get hasNext(){return this.state.getLatestValue().hasNext}get hasResults(){return Array.isArray(this.state.getLatestValue().items)}get isActive(){return this.state.getLatestValue().isActive}get isLoading(){return this.state.getLatestValue().isLoading}get initialState(){return{hasNext:!0,isActive:!1,isLoading:!1,items:void 0,lastQueryError:void 0,next:void 0,offset:0,searchQuery:""}}get items(){return this.state.getLatestValue().items}get next(){return this.state.getLatestValue().next}get offset(){return this.state.getLatestValue().offset}get searchQuery(){return this.state.getLatestValue().searchQuery}getStateBeforeFirstQuery(e){return{...this.initialState,isActive:this.isActive,isLoading:!0,searchQuery:e}}getStateAfterQuery(e,t){return{...this.state.getLatestValue(),lastQueryError:void 0,...e,isLoading:!1,items:t?e.items:[...this.items??[],...e.items||[]]}}prepareStateForQuery(e){const t=typeof e<"u",s=e??this.searchQuery;return t?this.state.next(this.getStateBeforeFirstQuery(e??"")):this.state.partialNext({isLoading:!0}),{searchString:s,hasNewSearchQuery:t}}updatePaginationStateFromQuery(e){const{items:t,next:s}=e,i={};return Object.prototype.hasOwnProperty.call(e,"next")?(i.next=s,i.hasNext=!!s):(i.offset=(this.offset??0)+t.length,i.hasNext=t.length===this.pageSize),i}resetState(){this.state.next(this.initialState)}resetStateAndActivate(){this.resetState(),this.activate()}},At=class extends go{constructor(e){const{debounceMs:t}={...mn,...e};super(e),this.setDebounceOptions=({debounceMs:s})=>{this.searchDebounced=wt(this.executeQuery.bind(this),s)},this.search=s=>this.searchDebounced(s),this.setDebounceOptions({debounceMs:t})}async executeQuery(e){if(!this.canExecuteQuery(e))return;const{hasNewSearchQuery:t,searchString:s}=this.prepareStateForQuery(e);let i={};try{const n=await this.query(s);if(!n)return;const{items:r}=n;i=this.updatePaginationStateFromQuery(n),i.items=await this.filterQueryResults(r)}catch(n){i.lastQueryError=n,qs(n)&&!Ct(n)&&(i.hasNext=!1)}finally{this.state.next(this.getStateAfterQuery(i,t))}}cancelScheduledQuery(){this.searchDebounced.cancel()}},mo=class extends go{constructor(e){const{debounceMs:t}={...mn,...e};super(e),this.setDebounceOptions=({debounceMs:s})=>{this.searchDebounced=wt(this.executeQuery.bind(this),s)},this.search=s=>this.searchDebounced(s),this.setDebounceOptions({debounceMs:t})}executeQuery(e){if(!this.canExecuteQuery(e))return;const{hasNewSearchQuery:t,searchString:s}=this.prepareStateForQuery(e);let i={};try{const n=this.query(s);if(!n)return;const{items:r}=n;i=this.updatePaginationStateFromQuery(n),i.items=this.filterQueryResults(r)}catch(n){i.lastQueryError=n,qs(n)&&!Ct(n)&&(i.hasNext=!1)}finally{this.state.next(this.getStateAfterQuery(i,t))}}cancelScheduledQuery(){this.searchDebounced.cancel()}},Nh=class{constructor({config:e,sources:t}={}){this.addSource=s=>{this.state.partialNext({sources:[...this.sources,s]})}
10,this.getSource=s=>this.sources.find(i=>i.type===s),this.removeSource=s=>{const i=this.sources.filter(n=>n.type!==s);i.length!==this.sources.length&&this.state.partialNext({sources:i})},this.activateSource=s=>{const i=this.getSource(s);!i||i.isActive||(this.config.keepSingleActiveSource&&this.sources.forEach(n=>{n.type!==s&&n.deactivate()}),i.activate(),this.state.partialNext({sources:[...this.sources]}))},this.deactivateSource=s=>{const i=this.getSource(s);i?.isActive&&this.activeSources.length!==1&&(i.deactivate(),this.state.partialNext({sources:[...this.sources]}))},this.activate=()=>{this.activeSources.length||(this.config.keepSingleActiveSource?this.sources.slice(0,1):this.sources).forEach(i=>i.activate()),!this.isActive&&this.state.partialNext({isActive:!0})},this.search=async s=>{const i=this.activeSources;this.state.partialNext({searchQuery:s}),await Promise.all(i.map(n=>n.search(s)))},this.cancelSearchQueries=()=>{this.activeSources.forEach(s=>s.cancelScheduledQuery())},this.clear=()=>{this.cancelSearchQueries(),this.sources.forEach(s=>s.state.next({...s.initialState,isActive:s.isActive})),this.state.next(s=>({...s,isActive:!0,queriesInProgress:[],searchQuery:""}))},this.exit=()=>{this.cancelSearchQueries(),this.sources.forEach(s=>s.state.next({...s.initialState,isActive:s.isActive})),this.state.next(s=>({...s,isActive:!1,queriesInProgress:[],searchQuery:""}))},this.state=new U({isActive:!1,searchQuery:"",sources:t??[]}),this._internalState=new U({}),this.config={keepSingleActiveSource:!0,...e}}get hasNext(){return this.sources.some(e=>e.hasNext)}get sources(){return this.state.getLatestValue().sources}get activeSources(){return this.state.getLatestValue().sources.filter(e=>e.isActive)}get isActive(){return this.state.getLatestValue().isActive}get searchQuery(){return this.state.getLatestValue().searchQuery}get searchSourceTypes(){return this.sources.map(e=>e.type)}},yo={debounceMs:300,pageSize:10},_o=class{constructor(e){this._isCursorPagination=!1,this.setDebounceOptions=({debounceMs:i})=>{this._executeQueryDebounced=wt(this.executeQuery.bind(this),i)},this.canExecuteQuery=i=>!this.isLoading&&i==="next"&&this.hasNext||i==="prev"&&this.hasPrev,this.next=()=>this.executeQuery({direction:"next"}),this.prev=()=>this.executeQuery({direction:"prev"}),this.nextDebounced=()=>{this._executeQueryDebounced({direction:"next"})},this.prevDebounced=()=>{this._executeQueryDebounced({direction:"prev"})};const{debounceMs:t,pageSize:s}={...yo,...e};this.pageSize=s,this.state=new U(this.initialState),this.setDebounceOptions({debounceMs:t})}get lastQueryError(){return this.state.getLatestValue().lastQueryError}get hasNext(){return this.state.getLatestValue().hasNext}get hasPrev(){return this.state.getLatestValue().hasPrev}get hasResults(){return Array.isArray(this.state.getLatestValue().items)}get isLoading(){return this.state.getLatestValue().isLoading}get initialState(){return{hasNext:!0,hasPrev:!0,isLoading:!1,items:void 0,lastQueryError:void 0,cursor:void 0,offset:0}}get items(){return this.state.getLatestValue().items}get cursor(){return this.state.getLatestValue().cursor}get offset(){return this.state.getLatestValue().offset}getStateBeforeFirstQuery(){return{...this.initialState,isLoading:!0}}getStateAfterQuery(e,t){return{...this.state.getLatestValue(),lastQueryError:void 0,...e,isLoading:!1,items:t?e.items:[...this.items??[],...e.items||[]]}}async executeQuery({direction:e}){if(!this.canExecuteQuery(e))return;const t=typeof this.items>"u";t?this.state.next(this.getStateBeforeFirstQuery()):this.state.partialNext({isLoading:!0});const s={};try{const i=await this.query({direction:e});if(!i)return;const{items:n,next:r,prev:a}=i;t&&(r||a)&&(this._isCursorPagination=!0),this._isCursorPagination?(s.cursor={next:r||null,prev:a||null},s.hasNext=!!r,s.hasPrev=!!a):(s.offset=(this.offset??0)+n.length,s.hasNext=n.length===this.pageSize),s.items=await this.filterQueryResults(n)}catch(i){s.lastQueryError=i}finally{this.state.next(this.getStateAfterQuery(s,t))}}cancelScheduledQuery(){this._executeQueryDebounced.cancel()}resetState(){this.state.next(this.initialState)}},je=class{constructor(e){this.context=new U(e?.initialContext??{}),this.filterConfig=new U(e?.initialFilterConfig??{})}updateFilterConfig(e){this.filterConfig.partialNext(e)}enableFilter(e){const t=this.filterConfig.getLatestValue();t[e]&&this.filterConfig.partialNext({[e]:{...t[e],enabled:!0}})}disableFilter(e){const t=this.filterConfig.getLatestValue();t[e]&&this.filterConfig.partialNext({[e]:{...t[e],enabled:!1}})}updateContext(e){this.context.partialNext(e)}buildFilters(e){const t={...e?.baseFilters??{}},s=this.filterConfig.getLatestValue();for(const i in s){const n=s[i];if(!n?.enabled)continue;const r=n.generate({...this.context.getLatestValue(),...e?.context??{}});r&&Object.assign(t,r)}return t}},wo=class extends _o{constructor(e,t){super(t),this.query=async({direction:s})=>{const i=this.cursor?.[s],{reminders:n,next:r,prev:a}=await this.client.queryReminders({filter:this.filters,sort:this.sort,limit:this.pageSize,[s]:i});return{items:n,next:r,prev:a}},this.filterQueryResults=s=>s,this.client=e}get filters(){return this._filters}get sort(){return this._sort}set filters(e){this._filters=e,this.resetState()}set sort(e){this._sort=e,this.resetState()}},Fh=class extends At{constructor(e,t,s={}){super(t),this.type="users",this.client=e,this.filterBuilder=new je({initialFilterConfig:{$or:{enabled:!0,generate:({searchQuery:i})=>i?{$or:[{id:{$autocomplete:i}},{name:{$autocomplete:i}}]}:null}},...s})}async query(e){const t=this.filterBuilder.buildFilters({baseFilters:this.filters,context:{searchQuery:e}}),s={id:1,...this.sort},i={...this.searchOptions,limit:this.pageSize,offset:this.offset},{users:n}=await this.client.queryUsers(t,s,i);return{items:n}}filterQueryResults(e){return e.filter(t=>t.id!==this.client.user?.id)}},Bh=class extends At{constructor(e,t,s={}){super(t),this.type="channels",this.client=e,this.filterBuilder=new je({...s,initialFilterConfig:{name:{enabled:!0,generate:({searchQuery:i})=>i?{name:{$autocomplete:i}}:null},...s.initialFilterConfig}})}async query(e){const t=this.filterBuilder.buildFilters({baseFilters:{...this.client.userID?{members:{$in:[this.client.userID]}}:{},...this.filters},context:{searchQuery:e}}),s=this.sort??{},i={...this.searchOptions,limit:this.pageSize,offset:this.offset};return{items:await this.client.queryChannels(t,s,i)}}filterQueryResults(e){return e}},qh=class extends At{constructor(e,t,s){super(t),this.type="messages",this.client=e,this.messageSearchChannelFilterBuilder=new je(s?.messageSearchChannel),this.messageSearchFilterBuilder=new je({...s?.messageSearch,initialFilterConfig:{text:{enabled:!0,generate:({searchQuery:i})=>i?{text:i}:null},...s?.messageSearch?.initialFilterConfig}}),this.channelQueryFilterBuilder=new je({...s?.channelQuery,initialFilterConfig:{cid:{enabled:!0,generate:({cids:i})=>i?{cid:{$in:i}}:null},...s?.channelQuery?.initialFilterConfig}})}async query(e){if(!this.client.userID||!e||this.next===null)return{items:[]};const t=this.messageSearchChannelFilterBuilder.buildFilters({baseFilters:{...this.client.userID?{members:{$in:[this.client.userID]}}:{},...this.messageSearchChannelFilters},context:{searchQuery:e}}),s=this.messageSearchFilterBuilder.buildFilters({baseFilters:{type:"regular",...this.messageSearchFilters},context:{searchQuery:e}}),i={created_at:-1,...this.messageSearchSort},n={limit:this.pageSize,next:this.next,sort:i},{next:r,results:a}=await this.client.search(t,s,n),o=a.map(({message:c})=>c),l=Array.from(o.reduce((c,d)=>(d.cid&&!this.client.activeChannels[d.cid]&&c.add(d.cid),c),new Set));if(l.length>0){const c=this.channelQueryFilterBuilder.buildFilters({baseFilters:this.channelQueryFilters,context:{cids:l}});await this.client.queryChannels(c,{last_message_at:-1,...this.channelQuerySort},this.channelQueryOptions)}return{items:o,next:r}}filterQueryResults(e){return e}},yn=({trigger:e,text:t,isCommand:s=!1,acceptTrailingSpaces:i=!0})=>{const n=`[^\\s${e}]*`,r=t.match(new RegExp(s?`^[${e}]${n}$`:i?`(?!^|\\W)?[${e}]${n}\\s?${n}$`:`(?!^|\\W)?[${e}]${n}$`,"g"));return r&&r[r.length-1].trim()},bo=e=>{const t=e.match(/^\/(\S+)\s+.*/);return t&&t[1]},_n=({insertText:e,selection:t,text:s,trigger:i})=>
10{const n=s.slice(0,t.end),r=s.slice(t.end),a=n.lastIndexOf(i);return{text:n.slice(0,a)+e+r,selection:{start:a+e.length,end:a+e.length}}};function Co(e){return e.replace(/[-[\]{}()*+?.,/\\^$|#]/g,"\\$&")}var So=({displayName:e,searchToken:t})=>({tokenizedDisplayName:{token:t,parts:t?e.split(new RegExp(`(${Co(t)})`,"gi")).filter(Boolean):[e]}}),vo=class extends mo{constructor(e,t){super(t),this.type="commands",this.canExecuteQuery=s=>{const i=typeof s<"u";return this.isActive&&!this.isLoading&&(this.hasNext||i)},this.channel=e}getStateBeforeFirstQuery(e){const t=super.getStateBeforeFirstQuery(e),{items:s}=this.state.getLatestValue();return{...t,items:s}}query(e){const i=(this.channel.getConfig()?.commands||[]).filter(n=>!!(n.name&&n.name.toLowerCase().indexOf(e.toLowerCase())!==-1));return i.sort((n,r)=>{let a=n.name?.toLowerCase(),o=r.name?.toLowerCase();if(a?.indexOf(e)===0&&(a=`0${a}`),o?.indexOf(e)===0&&(o=`0${o}`),a!=null&&o!=null){if(a<o)return-1;if(a>o)return 1}return 0}),{items:i.map(n=>({...n,id:n.name})),next:null}}filterQueryResults(e){return e}},$h={minChars:1,trigger:"/"},Ro=(e,t)=>{const s=Ve($h,{});let i=new vo(e);return i.activate(),{id:"stream-io/text-composer/commands-middleware",handlers:{onChange:({state:n,next:r,complete:a,forward:o})=>{if(!n.selection)return o();const l=n.text.slice(0,n.selection.end),c=bo(l);if(c){const p=i?.query(c).items[0];if(p)return r({...n,command:p,suggestions:void 0})}const d=yn({trigger:s.trigger,text:l,acceptTrailingSpaces:!1,isCommand:!0});if(d&&d.length===s.minChars&&i.resetStateAndActivate(),!d||d.length<s.minChars){const p=n.suggestions?.trigger===s.trigger,y={...n};return p&&delete y.suggestions,r(y)}return a({...n,command:null,suggestions:{query:d.slice(1),searchSource:i,trigger:s.trigger}})},onSuggestionItemSelect:({state:n,next:r,forward:a})=>{const{selectedSuggestion:o}=n.change??{};return!o||n.suggestions?.trigger!==s.trigger?a():(i.resetStateAndActivate(),r({...n,..._n({insertText:`/${o.name} `,selection:n.selection,text:n.text,trigger:s.trigger}),command:o,suggestions:void 0}))}}}},Ei={a:"á|à |ã|â|Ã|Ã|Ã|Ã",c:"ç|Ã",e:"é|è|ê|Ã|Ã|Ã",i:"Ã|ì|î|Ã|Ã|Ã",n:"ñ|Ã",o:"ó|ò|ô|Å|õ|Ã|Ã|Ã|Ã",u:"ú|ù|û|ü|Ã|Ã|Ã|Ã"},zt=e=>e?Object.keys(Ei).reduce((t,s)=>t.replace(new RegExp(Ei[s],"g"),s),e):"",xi=(e,t)=>{if(e.length===0)return t.length;if(t.length===0)return e.length;const s=[];let i;for(i=0;i<=t.length;i++)s[i]=[i];let n;for(n=0;n<=e.length;n++)s[0][n]=n;for(i=1;i<=t.length;i++)for(n=1;n<=e.length;n++)t.charAt(i-1)===e.charAt(n-1)?s[i][n]=s[i-1][n-1]:s[i][n]=Math.min(s[i-1][n-1]+1,Math.min(s[i][n-1]+1,s[i-1][n]+1));return s[t.length][e.length]},Eo=class extends At{constructor(e,t){const{mentionAllAppUsers:s,textComposerText:i,transliterate:n,...r}=t||{};super(r),this.type="mentions",this.toUserSuggestion=a=>({...a,...So({displayName:a.name||a.id,searchToken:this.searchQuery})}),this.canExecuteQuery=a=>{const o=typeof a<"u";return this.isActive&&!this.isLoading&&(o||this.hasNext)},this.transliterate=a=>a,this.getMembersAndWatchers=()=>{const a=Object.values(this.channel.state.members??{}).map(({user:d})=>d),o=Object.values(this.channel.state.watchers??{}),l=[...a,...o],c={};return l.forEach(d=>{d&&!c[d.id]&&(c[d.id]=d)}),Object.values(c)},this.searchMembersLocally=a=>{const{textComposerText:o}=this.config;return o?this.getMembersAndWatchers().filter(l=>{if(l.id===this.client.userID)return!1;if(!a)return!0;const c=this.transliterate(zt(l.id)).toLowerCase(),d=this.transliterate(zt(l.name)).toLowerCase(),h=this.transliterate(zt(a)).toLowerCase(),f=3,p=o.slice(-4).includes("@");if(d){const w=xi(h,d);if(d.includes(h)||w<=f&&p)return!0}const y=xi(h,c);return c.includes(h)||y<=f&&p}).sort((l,c)=>{if(!this.memberSort)return(l.name||"").localeCompare(c.name||"");for(const[d,h]of Object.entries(this.memberSort)){const f=l[d],p=c[d];if(f!==p)return h===1?String(f||"").localeCompare(String(p||"")):String(p||"").localeCompare(String(f||""))}return 0}):[]},this.prepareQueryUsersParams=a=>({filters:{$or:[{id:{$autocomplete:a}},{name:{$autocomplete:a}}],...this.userFilters},sort:this.userSort??[{name:1},{id:1}],options:{...this.searchOptions,limit:this.pageSize,offset:this.offset}}),this.prepareQueryMembersParams=a=>{let l=[{user_id:1}];return this.memberSort?Array.isArray(this.memberSort)?l=this.memberSort[0]:Object.keys(this.memberSort).length===1&&(l=this.memberSort):l=[{user_id:1}],{filters:this.memberFilters??{name:{$autocomplete:a}},sort:l,options:{...this.searchOptions,limit:this.pageSize,offset:this.offset}}},this.queryUsers=async a=>{const{filters:o,sort:l,options:c}=this.prepareQueryUsersParams(a),{users:d}=await this.client.queryUsers(o,l,c);return d},this.queryMembers=async a=>{const{filters:o,sort:l,options:c}=this.prepareQueryMembersParams(a);return(await this.channel.queryMembers(o,l,c)).members.map(h=>h.user)},this.filterMutes=a=>{const{textComposerText:o}=this.config;if(!o)return[];const{mutedUsers:l}=this.client;return o.includes("/unmute")&&!l.length?[]:l.length?o.includes("/unmute")?a.filter(c=>l.some(d=>d.target.id===c.id)):a.filter(c=>l.every(d=>d.target.id!==c.id)):a},this.client=e.getClient(),this.channel=e,this.config={mentionAllAppUsers:s,textComposerText:i},n&&(this.transliterate=n)}get allMembersLoadedWithInitialChannelQuery(){return Object.keys(this.channel.state.members||{}).length<$d}getStateBeforeFirstQuery(e){const t=super.getStateBeforeFirstQuery(e),{items:s}=this.state.getLatestValue();return{...t,items:s}}async query(e){let t;const s=this.allMembersLoadedWithInitialChannelQuery||!e;return this.config.mentionAllAppUsers?t=await this.queryUsers(e):s?t=this.searchMembersLocally(e):t=await this.queryMembers(e),{items:t.map(this.toUserSuggestion)}}filterQueryResults(e){return this.filterMutes(e)}},Hh={minChars:1,trigger:"@"},Vh=e=>{const{tokenizedDisplayName:t,...s}=e;return s},xo=(e,t)=>{const s=Ve(Hh,{});let i;return i=new Eo(e),i.activate(),{id:"stream-io/text-composer/mentions-middleware",handlers:{onChange:({state:n,next:r,complete:a,forward:o})=>{if(!n.selection)return o();const l=yn({trigger:s.trigger,text:n.text.slice(0,n.selection.end)});if(l&&l.length===s.minChars&&i.resetStateAndActivate(),!l||l.length<s.minChars){const h=n.suggestions?.trigger===s.trigger,f={...n};return h&&delete f.suggestions,r(f)}return i.config.textComposerText=n.text,a({...n,suggestions:{query:l.slice(1),searchSource:i,trigger:s.trigger}})},onSuggestionItemSelect:({state:n,complete:r,forward:a})=>{const{selectedSuggestion:o}=n.change??{};return!o||n.suggestions?.trigger!==s.trigger?a():(i.resetStateAndActivate(),r({...n,..._n({insertText:`@${o.name||o.id} `,selection:n.selection,text:n.text,trigger:s.trigger}),mentionedUsers:n.mentionedUsers.concat(Vh(o)),suggestions:void 0}))}}}},Mo=e=>({id:"stream-io/text-composer/pre-validation-middleware",handlers:{onChange:({state:t,next:s,forward:i})=>{const{maxLengthOnEdit:n}=e.config.text??{};return typeof n=="number"&&t.text.length>n?(t.text=t.text.slice(0,n),s({...t,text:t.text})):i()},onSuggestionItemSelect:({forward:t})=>t()}}),Ao=class extends we{constructor({composer:e}){super(),this.use([Mo(e),xo(e.channel),Ro(e.channel)])}async execute({eventName:e,initialValue:t}){const s=await this.executeMiddlewareChain({eventName:e,initialValue:t}),{query:i,searchSource:n}=s.state.suggestions??{};return n?.search(i)?.catch(console.error),s}},wn=e=>{const t=e.trim();return t===""||t===">"||t==="``````"||t==="``"||t==="**"||t==="____"||t==="__"||t==="****"},dr=({composer:e,message:t})=>{if(!t){const i=e.config.text.defaultValue??"";return{command:null,mentionedUsers:[],text:i,selection:{start:i.length,end:i.length}}}const s=t.text??"";return{mentionedUsers:(t.mentioned_users??[]).map(i=>typeof i=="string"?{id:i}:i),text:s,selection:{start:s.length,end:s.length}}},Uo=class{constructor({composer:e,message:t}){this.initState=({message:s}={})=>{this.state.next(dr({composer:this.composer,message:s}))},this.upsertMentionedUser=s=>{const i=[...this.mentionedUsers],n=i.findIndex(r=>
10r.id===s.id);n>=0?(i.splice(n,1,s),this.state.partialNext({mentionedUsers:i})):(i.push(s),this.state.partialNext({mentionedUsers:i}))},this.getMentionedUser=s=>this.state.getLatestValue().mentionedUsers.find(i=>i.id===s),this.removeMentionedUser=s=>{const i=this.mentionedUsers.findIndex(r=>r.id===s);if(i===-1)return;const n=[...this.mentionedUsers];n.splice(i,1),this.state.partialNext({mentionedUsers:n})},this.setCommand=s=>{s?.name!==this.command?.name&&this.state.partialNext({command:s})},this.setText=s=>{!this.enabled||s===this.text||this.state.partialNext({text:s})},this.setSelection=s=>{const i=s.start!==this.selection.start||s.end!==this.selection.end;!this.enabled||!i||this.state.partialNext({selection:s})},this.insertText=async({text:s,selection:i})=>{if(!this.enabled)return;const n=s.replace(/\r\n/g,` 11`),r=i??this.selection,{maxLengthOnEdit:a}=this.composer.config.text??{},o=this.text,l=[o.slice(0,r.start),n,o.slice(r.end)].join(""),c=l.slice(0,typeof a=="number"?a:l.length),d=r.start+n.length,h=Math.min(d,c.length);await this.handleChange({text:c,selection:{start:h,end:h}})},this.wrapSelection=({head:s="",selection:i,tail:n=""})=>
11{if(!this.enabled)return;const r=i??this.selection,a=this.text.slice(0,r.start),o=this.text.slice(r.start,r.end),l=this.text.slice(r.end),c={start:a.length+s.length,end:a.length+s.length+o.length};this.state.partialNext({text:[a,s,o,n,l].join(""),selection:c})},this.setSuggestions=s=>{this.state.partialNext({suggestions:s})},this.closeSuggestions=()=>{const{suggestions:s}=this.state.getLatestValue();s&&this.state.partialNext({suggestions:void 0})},this.handleChange=async({text:s,selection:i})=>{if(!this.enabled)return;const n=await this.middlewareExecutor.execute({eventName:"onChange",initialValue:{...this.state.getLatestValue(),text:s,selection:i}});n.status!=="discard"&&(this.state.next(n.state),this.config.publishTypingEvents&&s&&sn(this.channel.keystroke(this.composer.threadId??void 0),"start typing event"))},this.handleSelect=async s=>{if(!this.enabled)return;const i=await this.middlewareExecutor.execute({eventName:"onSuggestionItemSelect",initialValue:{...this.state.getLatestValue(),change:{selectedSuggestion:s}}});i?.status!=="discard"&&this.state.next(i.state)},this.composer=e,this.state=new U(dr({composer:e,message:t})),this.middlewareExecutor=new Ao({composer:e})}get channel(){return this.composer.channel}get config(){return this.composer.config.text}get enabled(){return this.composer.config.text.enabled}set enabled(e){e!==this.enabled&&this.composer.updateConfig({text:{enabled:e}})}get defaultValue(){return this.composer.config.text.defaultValue}set defaultValue(e){e!==this.defaultValue&&this.composer.updateConfig({text:{defaultValue:e}})}get maxLengthOnEdit(){return this.composer.config.text.maxLengthOnEdit}set maxLengthOnEdit(e){e!==this.maxLengthOnEdit&&this.composer.updateConfig({text:{maxLengthOnEdit:e}})}get maxLengthOnSend(){return this.composer.config.text.maxLengthOnSend}set maxLengthOnSend(e){e!==this.maxLengthOnSend&&this.composer.updateConfig({text:{maxLengthOnSend:e}})}get publishTypingEvents(){return this.composer.config.text.publishTypingEvents}set publishTypingEvents(e){e!==this.publishTypingEvents&&this.composer.updateConfig({text:{publishTypingEvents:e}})}get command(){return this.state.getLatestValue().command}get mentionedUsers(){return this.state.getLatestValue().mentionedUsers}get selection(){return this.state.getLatestValue().selection}get suggestions(){return this.state.getLatestValue().suggestions}get text(){return this.state.getLatestValue().text}get textIsEmpty(){return wn(this.text)}setMentionedUsers(e){this.state.partialNext({mentionedUsers:e})}clearCommand(){this.state.partialNext({command:null})}},Mi=class Ai{constructor(){this.unsubscribeFunctions=new Set,this.refCount=0}get hasSubscriptions(){return this.unsubscribeFunctions.size>0}addUnsubscribeFunction(t){this.unsubscribeFunctions.add(t)}incrementRefCount(){return++this.refCount}unregisterSubscriptions(){return this.refCount>1?(this.refCount--,Ai.symbol):(this.unsubscribeFunctions.forEach(t=>t()),this.unsubscribeFunctions.clear(),this.refCount=0,Ai.symbol)}};Mi.symbol=Symbol(Mi.name);var Pe=Mi,si=50,jh=[{created_at:-1}],Wh=1e3,zh={active_participant_count:!0,channel:!0,channel_cid:!0,created_at:!0,created_by:!0,created_by_user_id:!0,deleted_at:!0,draft:!0,last_message_at:!0,latest_replies:!0,parent_message:!0,parent_message_id:!0,participant_count:!0,read:!0,reply_count:!0,thread_participants:!0,title:!0,updated_at:!0},hr=e=>{const t={};for(const s in e){if(zh[s])continue;const i=s;t[i]=e[i]}return t},Te=class extends Pe{constructor({client:e,threadData:t}){super(),this.failedRepliesMap=new Map,this.activate=()=>{this.state.partialNext({active:!0})},this.deactivate=()=>{this.state.partialNext({active:!1})},this.reload=async()=>{if(!this.state.getLatestValue().isLoading){this.state.partialNext({isLoading:!0});try{const n=await this.client.getThread(this.id,{watch:!0});this.hydrateState(n)}finally{this.state.partialNext({isLoading:!1})}}},this.hydrateState=n=>{if(n===this)return;if(n.id!==this.id)throw new Error("Cannot hydrate thread's state using thread with different threadId");const{createdAt:r,custom:a,title:o,deletedAt:l,parentMessage:c,participants:d,read:h,replyCount:f,replies:p,updatedAt:y}=n.state.getLatestValue(),w=Array.from(this.failedRepliesMap.values());this.state.partialNext({title:o,createdAt:r,custom:a,deletedAt:l,parentMessage:c,participants:d,read:h,replyCount:f,replies:w.length?p.concat(w):p,updatedAt:y,isStateStale:!1})},this.registerSubscriptions=()=>{this.hasSubscriptions||(this.addUnsubscribeFunction(this.subscribeThreadUpdated()),this.addUnsubscribeFunction(this.subscribeMarkActiveThreadRead()),this.addUnsubscribeFunction(this.subscribeReloadActiveStaleThread()),this.addUnsubscribeFunction(this.subscribeMarkThreadStale()),this.addUnsubscribeFunction(this.subscribeNewReplies()),this.addUnsubscribeFunction(this.subscribeRepliesRead()),this.addUnsubscribeFunction(this.subscribeMessageDeleted()),this.addUnsubscribeFunction(this.subscribeMessageUpdated()))},this.subscribeThreadUpdated=()=>this.client.on("thread.updated",n=>{if(!n.thread||n.thread.parent_message_id!==this.id)return;const r=n.thread;this.state.partialNext({title:r.title,updatedAt:new Date(r.updated_at),deletedAt:r.deleted_at?new Date(r.deleted_at):null,custom:hr(r)})}).unsubscribe,this.subscribeMarkActiveThreadRead=()=>this.state.subscribeWithSelector(n=>({active:n.active,unreadMessageCount:ur(this.client.userID)(n)}),({active:n,unreadMessageCount:r})=>{!n||!r||this.throttledMarkAsRead()}),this.subscribeReloadActiveStaleThread=()=>this.state.subscribeWithSelector(n=>({active:n.active,isStateStale:n.isStateStale}),({active:n,isStateStale:r})=>{n&&r&&this.reload()}),this.subscribeMarkThreadStale=()=>this.client.on("user.watching.stop",n=>{const{channel:r}=this.state.getLatestValue();!this.client.userID||this.client.userID!==n.user?.id||n.channel?.cid!==r.cid||this.state.partialNext({isStateStale:!0})}).unsubscribe,this.subscribeNewReplies=()=>this.client.on("message.new",n=>{if(!this.client.userID||n.message?.parent_id!==this.id)return;const r=n.message.user?.id===this.client.userID,{active:a,read:o}=this.state.getLatestValue();this.upsertReplyLocally({message:n.message,timestampChanged:r}),a&&this.throttledMarkAsRead();const l={};for(const c of Object.keys(o)){const d=o[c];if(d){let h=d;c===n.user?.id?h={...h,lastReadAt:n.created_at?new Date(n.created_at):new Date,user:n.user,unreadMessageCount:0}:a&&c===this.client.userID||(h={...h,unreadMessageCount:d.unreadMessageCount+1}),l[c]=h}}this.state.partialNext({read:l})}).unsubscribe,this.subscribeRepliesRead=()=>this.client.on("message.read",n=>{if(!n.user||!n.created_at||!n.thread||n.thread.parent_message_id!==this.id)return;const r=n.user.id,a=n.created_at,o=n.user;this.state.next(l=>({...l,read:{...l.read,[r]:{lastReadAt:new Date(a),user:o,lastReadMessageId:n.last_read_message_id,unreadMessageCount:0}}}))}).unsubscribe,this.subscribeMessageDeleted=()=>this.client.on("message.deleted",n=>{n.message&&(n.message.parent_id===this.id&&(n.hard_delete?this.deleteReplyLocally({message:n.message}):this.upsertReplyLocally({message:n.message})),n.message.id===this.id&&this.updateParentMessageLocally({message:n.message}))}).unsubscribe,this.subscribeMessageUpdated=()=>{const r=["message.updated","reaction.new","reaction.deleted","reaction.updated"].map(a=>this.client.on(a,o=>{o.message&&this.updateParentMessageOrReplyLocally(o.message)}).unsubscribe);return()=>r.forEach(a=>a())},this.unregisterSubscriptions=()=>{const n=super.unregisterSubscriptions();return this.state.partialNext({isStateStale:!0}),n},this.deleteReplyLocally=({message:n})=>{const{replies:r}=this.state.getLatestValue(),a=aa({needle:B(n),sortedArray:r,sortDirection:"ascending",selectValueToCompare:l=>l.created_at.getTime(),selectKey:l=>l.id});
11if(r[a]?.id!==n.id)return;const o=[...r];o.splice(a,1),this.state.partialNext({replies:o})},this.upsertReplyLocally=({message:n,timestampChanged:r=!1})=>{if(n.parent_id!==this.id)throw new Error("Reply does not belong to this thread");const a=B(n);n.status==="failed"?this.failedRepliesMap.set(a.id,a):this.failedRepliesMap.has(n.id)&&this.failedRepliesMap.delete(n.id),this.state.next(o=>({...o,replies:oa(o.replies,a,r)}))},this.updateParentMessageLocally=({message:n})=>{if(n.id!==this.id)throw new Error("Message does not belong to this thread");this.state.next(r=>{const a=B(n);return{...r,deletedAt:a.deleted_at,parentMessage:a,replyCount:n.reply_count??r.replyCount}})},this.updateParentMessageOrReplyLocally=n=>{n.parent_id===this.id&&this.upsertReplyLocally({message:n}),!n.parent_id&&n.id===this.id&&this.updateParentMessageLocally({message:n})},this.markAsRead=async({force:n=!1}={})=>this.ownUnreadCount===0&&!n?null:await this.client.messageDeliveryReporter.markRead(this),this.throttledMarkAsRead=nn(()=>this.markAsRead(),Wh,{trailing:!0}),this.queryReplies=({limit:n=si,sort:r=jh,...a}={})=>this.channel.getReplies(this.id,{limit:n,...a},r),this.loadNextPage=({limit:n=si}={})=>this.loadPage(n),this.loadPrevPage=({limit:n=si}={})=>this.loadPage(-n),this.loadPage=async n=>{const{pagination:r}=this.state.getLatestValue(),[a,o,l]=n>0?["isLoadingNext","nextCursor","push"]:["isLoadingPrev","prevCursor","unshift"];if(r[a]||r[o]===null)return;const c={[n>0?"id_gt":"id_lt"]:r[o]},d=Math.abs(n);this.state.partialNext({pagination:{...r,[a]:!0}});try{const h=await this.queryReplies({...c,limit:d}),f=h.messages.map(B),p=f.at(n>0?-1:0)?.id??null;this.state.next(y=>{let w=y.replies;return f.length>0&&(w=[...y.replies],w[l](...f)),{...y,replies:w,pagination:{...y.pagination,[o]:h.messages.length<d?null:p,[a]:!1}}})}catch(h){this.client.logger("error",h.message),this.state.next(f=>({...f,pagination:{...f.pagination,[a]:!1}}))}};
11const s=e.channel(t.channel.type,t.channel.id,{name:t.channel.name});s._hydrateMembers({members:t.channel.members??[],overrideCurrentState:!1});const i=e.userID?[{user:{id:e.userID},unread_messages:0,last_read:new Date().toISOString()}]:[];this.state=new U({active:!1,isLoading:!1,isStateStale:!1,channel:s,createdAt:new Date(t.created_at),deletedAt:t.deleted_at?new Date(t.deleted_at):null,pagination:Gh(t),parentMessage:B(t.parent_message),participants:t.thread_participants,read:Qh(!t.read||t.read.length===0?i:t.read),replies:t.latest_replies.map(B),replyCount:t.reply_count??0,updatedAt:t.updated_at?new Date(t.updated_at):null,title:t.title,custom:hr(t)}),this.id=t.parent_message_id,this.client=e,this.messageComposer=new St({client:e,composition:t.draft,compositionContext:this})}get channel(){return this.state.getLatestValue().channel}get hasStaleState(){return this.state.getLatestValue().isStateStale}get ownUnreadCount(){return ur(this.client.userID)(this.state.getLatestValue())}},Qh=e=>e.reduce((t,s)=>(t[s.user.id]={user:s.user,lastReadMessageId:s.last_read_message_id,unreadMessageCount:s.unread_messages??0,lastReadAt:new Date(s.last_read)},t),{}),Gh=e=>({nextCursor:null,prevCursor:e.latest_replies.length===e.reply_count?null:e.latest_replies.at(0)?.id??null,isLoadingNext:!1,isLoadingPrev:!1}),ur=e=>t=>e&&t.read[e]?.unreadMessageCount||0,gt=e=>!!e?.message,Kh=e=>{let t=null,s=new Date().getTime();return gt(e)?s=t=new Date(e.created_at).getTime():e&&ha(e)&&(s=new Date(e.updated_at).getTime()),{lastChange:{draftUpdate:t,stateUpdate:s}}},fr=e=>{if(!e)return{draftId:null,id:St.generateId(),pollId:null,quotedMessage:null,showReplyInChannel:!1};const t=e.quoted_message;let s,i=null,n=St.generateId();return gt(e)?(s=e.message,i=e.message.id):(s=e,n=e.id),{draftId:i,id:n,pollId:s.poll_id??null,quotedMessage:t?B(t):null,showReplyInChannel:!1}},To=class Qt extends Pe{constructor({composition:t,config:s,compositionContext:i,client:n}){if(super(),this.refreshId=()=>{this.state.partialNext({id:Qt.generateId()})},this.initState=({composition:o}={})=>{this.editingAuditState.partialNext(this.initEditingAuditState(o));const l=typeof o>"u"?o:gt(o)?o.message:B(o);this.attachmentManager.initState({message:l}),this.linkPreviewsManager.initState({message:l}),this.locationComposer.initState({message:l}),this.textComposer.initState({message:l}),this.pollComposer.initState(),this.customDataManager.initState({message:l}),this.state.next(fr(o)),o&&!gt(o)&&l&&ha(l)&&(this.editedMessage=l)},this.initStateFromChannelResponse=o=>{this.channel.cid===o.channel.cid&&(o.draft?this.initState({composition:o.draft}):this.state.getLatestValue().draftId&&(this.clear(),this.client.offlineDb?.executeQuerySafely(l=>l.deleteDraft({cid:this.channel.cid,parent_id:void 0}),{method:"deleteDraft"})))},this.initEditingAuditState=o=>Kh(o),this.registerDraftEventSubscriptions=()=>{const o=this.subscribeDraftUpdated(),l=this.subscribeDraftDeleted();return()=>{o(),l()}},this.registerSubscriptions=()=>(this.hasSubscriptions||(this.addUnsubscribeFunction(this.subscribeMessageComposerSetupStateChange()),this.addUnsubscribeFunction(this.subscribeMessageUpdated()),this.addUnsubscribeFunction(this.subscribeMessageDeleted()),this.addUnsubscribeFunction(this.subscribeTextComposerStateChanged()),this.addUnsubscribeFunction(this.subscribeAttachmentManagerStateChanged()),this.addUnsubscribeFunction(this.subscribeLinkPreviewsManagerStateChanged()),this.addUnsubscribeFunction(this.subscribeLocationComposerStateChanged()),this.addUnsubscribeFunction(this.subscribePollComposerStateChanged()),this.addUnsubscribeFunction(this.subscribeCustomDataManagerStateChanged()),this.addUnsubscribeFunction(this.subscribeMessageComposerStateChanged()),this.addUnsubscribeFunction(this.subscribeMessageComposerConfigStateChanged())),this.incrementRefCount(),()=>this.unregisterSubscriptions()),this.subscribeMessageUpdated=()=>{const l=["message.updated","reaction.new","reaction.deleted","reaction.updated"].map(c=>this.client.on(c,d=>{d.message&&(d.message.id===this.id&&this.initState({composition:d.message}),this.quotedMessage?.id&&d.message.id===this.quotedMessage.id&&this.setQuotedMessage(B(d.message)))}).unsubscribe);return()=>l.forEach(c=>c())},this.subscribeMessageComposerSetupStateChange=()=>{let o=null;const l=this.client._messageComposerSetupState.subscribeWithSelector(({setupFunction:c})=>({setup:c}),({setup:c})=>{o?.(),o=c?.({composer:this})??null});return()=>{o?.(),l()}},this.subscribeMessageDeleted=()=>this.client.on("message.deleted",o=>{o.message&&(o.message.id===this.id?this.clear():this.quotedMessage&&o.message.id===this.quotedMessage.id&&this.setQuotedMessage(null))}).unsubscribe,this.subscribeDraftUpdated=()=>this.client.on("draft.updated",o=>{const l=o.draft;!l||(l.parent_id??null)!==(this.threadId??null)||l.channel_cid!==this.channel.cid||this.initState({composition:l})}).unsubscribe,this.subscribeDraftDeleted=()=>this.client.on("draft.deleted",o=>{const l=o.draft;!l||(l.parent_id??null)!==(this.threadId??null)||l.channel_cid!==this.channel.cid||(this.logDraftUpdateTimestamp(),!this.compositionIsEmpty&&this.clear())}).unsubscribe,this.subscribeTextComposerStateChanged=()=>this.textComposer.state.subscribeWithSelector(({text:o})=>[o],([o],l)=>{if(!(typeof l>"u")){if(this.logStateUpdateTimestamp(),this.compositionIsEmpty){this.deleteDraft();return}this.linkPreviewsManager.enabled&&(o?this.linkPreviewsManager.findAndEnrichUrls(o):this.linkPreviewsManager.clearPreviews())}}),this.subscribeAttachmentManagerStateChanged=()=>this.attachmentManager.state.subscribe((o,l)=>{if(!(typeof l>"u")&&(this.logStateUpdateTimestamp(),this.compositionIsEmpty)){this.deleteDraft();return}}),this.subscribeLocationComposerStateChanged=()=>this.locationComposer.state.subscribe((o,l)=>{if(!(typeof l>"u")&&(this.logStateUpdateTimestamp(),this.compositionIsEmpty)){this.deleteDraft();return}}),this.subscribeLinkPreviewsManagerStateChanged=()=>this.linkPreviewsManager.state.subscribe((o,l)=>{if(!(typeof l>"u")&&(this.logStateUpdateTimestamp(),this.compositionIsEmpty)){this.deleteDraft();return}}),this.subscribePollComposerStateChanged=()=>this.pollComposer.state.subscribe((o,l)=>{if(!(typeof l>"u")&&(this.logStateUpdateTimestamp(),this.compositionIsEmpty)){this.deleteDraft();return}}),this.subscribeCustomDataManagerStateChanged=()=>this.customDataManager.state.subscribe((o,l)=>{typeof l<"u"&&!this.customDataManager.isMessageDataEqual(o,l)&&this.logStateUpdateTimestamp()}),this.subscribeMessageComposerStateChanged=()=>this.state.subscribe((o,l)=>{typeof l>"u"||(this.logStateUpdateTimestamp(),this.compositionIsEmpty&&this.deleteDraft())}),this.subscribeMessageComposerConfigStateChanged=()=>{let o;const l=this.configState.subscribeWithSelector(c=>
11({textDefaultValue:c.text.defaultValue,draftsEnabled:c.drafts.enabled}),({textDefaultValue:c,draftsEnabled:d})=>{this.textComposer.text===""&&c&&this.textComposer.insertText({text:c,selection:{start:0,end:0}}),d&&!o?o=this.registerDraftEventSubscriptions():!d&&o&&(o(),o=null)});return()=>{o?.(),l()}},this.setQuotedMessage=o=>{this.state.partialNext({quotedMessage:o})},this.toggleShowReplyInChannel=()=>{this.state.partialNext({showReplyInChannel:!this.showReplyInChannel})},this.clear=()=>{this.setQuotedMessage(null),this.initState()},this.restore=()=>{const{editedMessage:o}=this;if(o){this.initState({composition:o});return}this.clear()},this.compose=async()=>{const o=this.editedMessage?.created_at??new Date,c=await this.compositionMiddlewareExecutor.execute({eventName:"compose",initialValue:{message:{id:this.id,parent_id:this.threadId??void 0,type:"regular"},localMessage:{attachments:[],created_at:o,deleted_at:null,error:void 0,id:this.id,mentioned_users:[],parent_id:this.threadId??void 0,pinned_at:this.editedMessage?.pinned_at||null,reaction_groups:null,status:this.editedMessage?this.editedMessage.status:"sending",text:"",type:"regular",updated_at:o},sendOptions:{}}});if(c.status!=="discard")return c.state},this.composeDraft=async()=>{const{state:o,status:l}=await this.draftCompositionMiddlewareExecutor.execute({eventName:"compose",initialValue:{draft:{id:this.id,parent_id:this.threadId??void 0,text:""}}});if(l!=="discard")return o},this.createDraft=async()=>{if(this.editedMessage||!this.config.drafts.enabled)return;const o=await this.composeDraft();if(!o)return;const{draft:l}=o;if(this.state.partialNext({draftId:l.id}),this.client.offlineDb)try{const c={channel_cid:this.channel.cid,created_at:new Date().toISOString(),message:l,parent_id:l.parent_id,quoted_message:this.quotedMessage?nh(this.quotedMessage):void 0};await this.client.offlineDb.upsertDraft({draft:c})}catch(c){this.client.logger("error","offlineDb:upsertDraft",{tags:["channel","offlineDb"],error:c})}this.logDraftUpdateTimestamp(),await this.channel.createDraft(l)},this.deleteDraft=async()=>{if(this.editedMessage||!this.config.drafts.enabled||!this.draftId)return;this.state.partialNext({draftId:null});const o=this.threadId??void 0;if(this.client.offlineDb)try{await this.client.offlineDb.deleteDraft({cid:this.channel.cid,parent_id:o})}catch(l){this.client.logger("error","offlineDb:deleteDraft",{tags:["channel","offlineDb"],error:l})}this.logDraftUpdateTimestamp(),await this.channel.deleteDraft({parent_id:o})},this.getDraft=async()=>{if(this.editedMessage||!this.config.drafts.enabled||!this.client.userID)return;const o=await this.client.offlineDb?.getDraft({cid:this.channel.cid,userId:this.client.userID,parent_id:this.threadId??void 0});o&&this.initState({composition:o});try{const l=await this.channel.getDraft({parent_id:this.threadId??void 0}),{draft:c}=l;if(!c)return;this.client.offlineDb?.executeQuerySafely(d=>d.upsertDraft({draft:c}),{method:"upsertDraft"}),this.initState({composition:c})}catch(l){this.client.logger("error","messageComposer:getDraft",{tags:["channel","messageComposer"],error:l})}},this.createPoll=async()=>{const o=await this.pollComposer.compose();if(!(!o||!o.data.id))try{const l=await this.client.polls.createPoll(o.data);this.state.partialNext({pollId:l?.id})}catch(l){throw this.client.notifications.addError({message:"Failed to create the poll",origin:{emitter:"MessageComposer",context:{composer:this}},options:{type:"api:poll:create:failed",metadata:{reason:l.message},originalError:l instanceof Error?l:void 0}}),l}},this.sendLocation=async()=>{const o=this.locationComposer.validLocation;if(!(this.threadId||!o))try{await this.channel.sendSharedLocation(o),this.refreshId(),this.locationComposer.initState()}catch(l){throw this.client.notifications.addError({message:"Failed to share the location",origin:{emitter:"MessageComposer",context:{composer:this}},options:{type:"api:location:create:failed",metadata:{reason:l.message},originalError:l instanceof Error?l:void 0}}),l}},this.compositionContext=i,i instanceof _e)this.channel=i;else if(i instanceof Te)this.channel=i.channel;else if(i.cid){const[o,l]=i.cid.split(":");this.channel=n.channel(o,l)}else throw new Error("MessageComposer requires composition context pointing to channel (channel or context.cid)");const r=(o,l,c)=>typeof o=="object"?void 0:o===!1&&c==="enabled"?!1:["string","number","bigint","boolean","symbol"].includes(typeof l)?l:o;this.configState=new U(Ve(Ve(Na,s??{}),{location:{enabled:this.channel.getConfig()?.shared_locations}},r));let a;gt(t)?a=t.message:t&&(a=B(t),this.editedMessage=a),this.attachmentManager=new Ia({composer:this,message:a}),this.linkPreviewsManager=new Fs({composer:this,message:a}),this.locationComposer=new Ba({composer:this,message:a}),this.textComposer=new Uo({composer:this,message:a}),this.pollComposer=new Ja({composer:this}),this.customDataManager=new Fa({composer:this,message:a}),this.editingAuditState=new U(this.initEditingAuditState(t)),this.state=new U(fr(t)),this.compositionMiddlewareExecutor=new fo({composer:this}),this.draftCompositionMiddlewareExecutor=new po({composer:this})}static evaluateContextType(t){return t instanceof _e?"channel":t instanceof Te?"thread":typeof t.legacyThreadId=="string"?"legacy_thread":"message"}static constructTag(t){return`${this.evaluateContextType(t)}_${t.id}`}get config(){return this.configState.getLatestValue()}get contextType(){return Qt.evaluateContextType(this.compositionContext)}get tag(){return Qt.constructTag(this.compositionContext)}get threadId(){return this.compositionContext instanceof _e?null:this.compositionContext instanceof Te?this.compositionContext.id:typeof this.compositionContext.legacyThreadId=="string"?this.compositionContext.legacyThreadId:typeof this.compositionContext.parent_id=="string"?this.compositionContext.parent_id:null}get client(){return this.channel.getClient()}get id(){return this.state.getLatestValue().id}get draftId(){return this.state.getLatestValue().draftId}get lastChange(){return this.editingAuditState.getLatestValue().lastChange}get quotedMessage(){return this.state.getLatestValue().quotedMessage}get pollId(){return this.state.getLatestValue().pollId}
11get showReplyInChannel(){return this.state.getLatestValue().showReplyInChannel}get hasSendableData(){return this.client.offlineDb?!this.compositionIsEmpty:!!(!this.attachmentManager.uploadsInProgressCount&&(!this.textComposer.textIsEmpty||this.attachmentManager.successfulUploadsCount>0)||this.pollId||this.locationComposer.validLocation)}get compositionIsEmpty(){return!this.quotedMessage&&this.textComposer.textIsEmpty&&!this.attachmentManager.attachments.length&&!this.pollId&&!this.locationComposer.validLocation}get lastChangeOriginIsLocal(){const s=this.lastChange.draftUpdate===null&&!this.editedMessage,i=!!this.editedMessage?.updated_at&&new Date(this.editedMessage.updated_at).getTime()<this.lastChange.stateUpdate,n=!!this.lastChange.draftUpdate&&this.lastChange.draftUpdate<this.lastChange.stateUpdate;return i||n||s}updateConfig(t){this.configState.partialNext(Ve(this.config,t))}logStateUpdateTimestamp(){this.editingAuditState.partialNext({lastChange:{...this.lastChange,stateUpdate:new Date().getTime()}})}logDraftUpdateTimestamp(){if(!this.config.drafts.enabled)return;const t=new Date().getTime();this.editingAuditState.partialNext({lastChange:{draftUpdate:t,stateUpdate:t}})}};To.generateId=W;var St=To,pr=100,gr=1e3,Jh=1e3,Xh=3,Ft=e=>e instanceof _e,Bt=e=>e instanceof Te,Lo=class Io{constructor({client:t}){this.deliveryReportCandidates=new Map,this.nextDeliveryReportCandidates=new Map,this.markDeliveredRequestPromise=null,this.markDeliveredTimeout=null,this.requestTimeoutMs=gr,this.requestRetryCount=0,this.getNextDeliveryReportCandidate=s=>{const i=this.client.user?.id;if(!i)return;let n=[],r,a,o;if(Ft(s)){n=s.state.latestMessages;const h=s.state.read[i]??{};a=h?.last_read,r=h?.last_delivered_at,o=s.cid}else if(Bt(s)){n=s.state.getLatestValue().replies;const h=s.state.getLatestValue().read[i]??{};a=h?.lastReadAt,r=h?.lastDeliveredAt,o=`${s.channel.cid}:${s.id}`;return}else return;if(!o)return;const[l]=n.slice(-1);return!l||a>=l.created_at?{key:o,id:null}:!l||(r??0)>=l.created_at?{key:o,id:null}:{key:o,id:l.id||null}},this.announceDelivery=s=>{if(!this.canExecuteRequest)return;const{latest_delivered_messages:i,sendBuffer:n}=this.confirmationsFromDeliveryReportCandidates();if(!i.length)return;const r={...s,latest_delivered_messages:i},a=({preventSchedulingRetry:c}={})=>{this.markDeliveredRequestPromise=null;for(const[d,h]of this.nextDeliveryReportCandidates.entries())this.deliveryReportCandidates.set(d,h);this.nextDeliveryReportCandidates=new Map,!c&&this.announceDeliveryBuffered(s)},o=()=>{this.resetBackOff(),a()},l=c=>{const d=new Map(n);for(const[h,f]of this.deliveryReportCandidates.entries())d.set(h,f);this.deliveryReportCandidates=d,qs(c)&&Ct(c)||c.status>=500?(this.increaseBackOff(),a()):a({preventSchedulingRetry:!0})};this.markDeliveredRequestPromise=this.client.markChannelsDelivered(r).then(o,l)},this.announceDeliveryBuffered=s=>{this.hasTimer||!this.canExecuteRequest||(this.markDeliveredTimeout=setTimeout(()=>{this.markDeliveredTimeout=null,this.announceDelivery(s)},this.requestTimeoutMs))},this.markRead=async(s,i)=>{let n=null;return Ft(s)?n=await s.markAsReadRequest(i):Bt(s)&&(n=await s.channel.markAsReadRequest({...i,thread_id:s.id})),this.removeCandidateFor(s),n},this.throttledMarkRead=nn(this.markRead,Jh,{leading:!1,trailing:!0}),this.client=t}get markDeliveredRequestInFlight(){return this.markDeliveredRequestPromise!==null}get hasTimer(){return this.markDeliveredTimeout!==null}get hasDeliveryCandidates(){return this.deliveryReportCandidates.size>0}get canExecuteRequest(){return!this.markDeliveredRequestInFlight&&this.hasDeliveryCandidates}static hasPermissionToReportDeliveryFor(t){if(Ft(t))return!!t.getConfig()?.delivery_events;if(Bt(t))return!!t.channel.getConfig()?.delivery_events}increaseBackOff(){this.requestRetryCount>=Xh||(this.requestRetryCount=this.requestRetryCount+1,this.requestTimeoutMs=this.requestTimeoutMs*2)}resetBackOff(){this.requestTimeoutMs=gr,this.requestRetryCount=0}confirmationsFrom(t){return Array.from(t.entries()).map(([s,i])=>{const[n,r,a]=s.split(":");return a?{cid:`${n}:${r}`,id:i,parent_id:a}:{cid:s,id:i}})}confirmationsFromDeliveryReportCandidates(){const t=Array.from(this.deliveryReportCandidates),s=new Map(t.slice(0,pr));return this.deliveryReportCandidates=new Map(t.slice(pr)),{latest_delivered_messages:this.confirmationsFrom(s),sendBuffer:s}}candidateKeyFor(t){if(Ft(t))return t.cid;if(Bt(t))return`${t.channel.cid}:${t.id}`}trackDeliveredCandidate(t){if(!Io.hasPermissionToReportDeliveryFor(t))return;const s=this.getNextDeliveryReportCandidate(t);
11if(!s?.key)return;const i=this.markDeliveredRequestInFlight?this.nextDeliveryReportCandidates:this.deliveryReportCandidates;s.id===null?i.delete(s.key):i.set(s.key,s.id)}removeCandidateFor(t){const s=this.candidateKeyFor(t);s&&(this.deliveryReportCandidates.delete(s),this.nextDeliveryReportCandidates.delete(s))}syncDeliveredCandidates(t){if(this.client.user?.privacy_settings?.delivery_receipts?.enabled!==!1){for(const s of t)this.trackDeliveredCandidate(s);this.announceDeliveryBuffered()}}},Se={timestampMs:Number.NEGATIVE_INFINITY,msgId:""},V=(e,t)=>e.timestampMs!==t.timestampMs?e.timestampMs-t.timestampMs:0,ue=(e,t,s)=>{let i=0,n=e.length;for(;i<n;){const r=i+n>>>1;V(s(e[r]),t)>=0?n=r:i=r+1}return i},Ui=(e,t,s)=>{let i=0,n=e.length;for(;i<n;){const r=i+n>>>1;V(s(e[r]),t)>0?n=r:i=r+1}return i},ve=(e,t,s)=>e.splice(Ui(e,s(t),s),0,t),nt=(e,t,s,i)=>{let n=ue(e,s,i);for(;n<e.length&&V(i(e[n]),s)===0;){if(e[n].user.id===t.user.id){e.splice(n,1);return}n++}},Do=class{constructor({locateMessage:e}){this.byUser=new Map,this.readSorted=[],this.deliveredSorted=[],this.locateMessage=e}ingestInitial(e){this.byUser.clear(),this.readSorted=[],this.deliveredSorted=[];for(const t of e){const s=t.last_read?new Date(t.last_read).getTime():null,i=t.last_delivered_at?new Date(t.last_delivered_at).getTime():null,n=s?this.locateMessage(s)??Se:Se;let r=i?this.locateMessage(i)??Se:Se;V(r,n)<0&&(r=n);const o={user:t.user,lastReadRef:n,lastDeliveredRef:r};this.byUser.set(t.user.id,o),this.readSorted.splice(ue(this.readSorted,n,l=>l.lastReadRef),0,o),this.deliveredSorted.splice(ue(this.deliveredSorted,r,l=>l.lastDeliveredRef),0,o)}}onMessageDelivered({user:e,deliveredAt:t,lastDeliveredMessageId:s}){const i=new Date(t).getTime(),n=s?{timestampMs:i,msgId:s}:this.locateMessage(new Date(t).getTime());if(!n)return;const r=this.ensureUser(e),a=V(n,r.lastReadRef)<0?r.lastReadRef:n;V(a,r.lastDeliveredRef)<=0||(nt(this.deliveredSorted,r,r.lastDeliveredRef,o=>o.lastDeliveredRef),r.lastDeliveredRef=a,ve(this.deliveredSorted,r,o=>o.lastDeliveredRef))}onMessageRead({user:e,readAt:t,lastReadMessageId:s}){const i=new Date(t).getTime(),n=s?{timestampMs:i,msgId:s}:this.locateMessage(i);if(!n)return;const r=this.ensureUser(e);V(n,r.lastReadRef)<=0||(nt(this.readSorted,r,r.lastReadRef,a=>a.lastReadRef),r.lastReadRef=n,ve(this.readSorted,r,a=>a.lastReadRef),V(r.lastDeliveredRef,r.lastReadRef)<0&&(nt(this.deliveredSorted,r,r.lastDeliveredRef,a=>a.lastDeliveredRef),r.lastDeliveredRef=r.lastReadRef,ve(this.deliveredSorted,r,a=>a.lastDeliveredRef)))}onNotificationMarkUnread({user:e,lastReadAt:t,lastReadMessageId:s}){const i=this.ensureUser(e),n=t?{timestampMs:new Date(t).getTime(),msgId:s??""}:{...Se};V(n,i.lastReadRef)===0&&n.msgId===i.lastReadRef.msgId||(nt(this.readSorted,i,i.lastReadRef,r=>r.lastReadRef),i.lastReadRef=n,ve(this.readSorted,i,r=>r.lastReadRef),V(i.lastDeliveredRef,i.lastReadRef)<0&&(nt(this.deliveredSorted,i,i.lastDeliveredRef,r=>r.lastDeliveredRef),i.lastDeliveredRef=i.lastReadRef,ve(this.deliveredSorted,i,r=>r.lastDeliveredRef)))}readersForMessage(e){const t=ue(this.readSorted,e,({lastReadRef:s})=>s);return this.readSorted.slice(t).map(s=>s.user)}deliveredForMessage(e){const t=ue(this.deliveredSorted,e,({lastDeliveredRef:s})=>s);return this.deliveredSorted.slice(t).map(s=>s.user)}deliveredNotReadForMessage(e){const t=ue(this.deliveredSorted,e,({lastDeliveredRef:i})=>i),s=[];for(let i=t;i<this.deliveredSorted.length;i++){const n=this.deliveredSorted[i];V(n.lastReadRef,e)<0&&s.push(n.user)}return s}usersWhoseLastReadIs(e){if(!e.msgId)return[];const t=ue(this.readSorted,e,n=>n.lastReadRef),s=Ui(this.readSorted,e,n=>n.lastReadRef),i=[];for(let n=t;n<s;n++){const r=this.readSorted[n];r.lastReadRef.msgId===e.msgId&&i.push(r.user)}return i}usersWhoseLastDeliveredIs(e){if(!e.msgId)return[];const t=ue(this.deliveredSorted,e,n=>n.lastDeliveredRef),s=Ui(this.deliveredSorted,e,n=>n.lastDeliveredRef),i=[];for(let n=t;n<s;n++){const r=this.deliveredSorted[n];r.lastDeliveredRef.msgId===e.msgId&&i.push(r.user)}return i}hasUserRead(e,t){const s=this.byUser.get(t);return!!s&&V(s.lastReadRef,e)>=0}hasUserDelivered(e,t){const s=this.byUser.get(t);return!!s&&V(s.lastDeliveredRef,e)>=0}getUserProgress(e){const t=this.byUser.get(e);return t||null}groupUsersByLastReadMessage(){return Array.from(this.byUser.values()).reduce((e,t)=>
11{const s=t.lastReadRef.msgId;return s&&(e[s]||(e[s]=[]),e[s].push(t.user)),e},{})}groupUsersByLastDeliveredMessage(){return Array.from(this.byUser.values()).reduce((e,t)=>{const s=t.lastDeliveredRef.msgId;return s&&(e[s]||(e[s]=[]),e[s].push(t.user)),e},{})}ensureUser(e){let t=this.byUser.get(e.id);return t||(t={user:e,lastReadRef:Se,lastDeliveredRef:Se},this.byUser.set(e.id,t),ve(this.readSorted,t,s=>s.lastReadRef),ve(this.deliveredSorted,t,s=>s.lastDeliveredRef)),t}},_e=class{constructor(e,t,s,i){this.create=async a=>{const o={...a,watch:!1,state:!1,presence:!1};return await this.query(o,"latest")},this._callChannelListeners=a=>{const o=this,l=[];o.listeners.all&&l.push(...o.listeners.all),o.listeners[a.type]&&l.push(...o.listeners[a.type]);for(const c of l)typeof c!="string"&&c(a)},this._channelURL=()=>{if(!this.id)throw new Error("channel id is not defined");return`${this.getClient().baseURL}/channels/${encodeURIComponent(this.type)}/${encodeURIComponent(this.id)}`};const n=/^[\w_-]+$/,r=/^[\w!_-]+$/;if(!n.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 fa(this),this.initialized=!1,this.offlineMode=!1,this.lastTypingEvent=null,this.isTyping=!1,this.disconnected=!1,this.messageComposer=new St({client:this._client,compositionContext:this}),this.messageReceiptsTracker=new Do({locateMessage:a=>{const o=this.state.findMessageByTimestamp(a);return o&&{timestampMs:a,msgId:o.id}}})}getClient(){if(this.disconnected===!0)throw Error("You can't use a channel after client.disconnect() was called");return this._client}getConfig(){return this.getClient().configs[this.cid]}async _sendMessage(e,t){return await this.getClient().post(this._channelURL()+"/message",{message:e,...t})}async sendMessage(e,t){try{const s=this.getClient().offlineDb;if(s){const i=e.id;if(i)return await s.queueTask({task:{channelId:this.id,channelType:this.type,messageId:i,payload:[e,t],type:"send-message"}})}}catch(s){this._client.logger("error","offlineDb:send-message",{tags:["channel","offlineDb"],error:s})}return await this._sendMessage(e,t)}sendFile(e,t,s,i){return this.getClient().sendFile(`${this._channelURL()}/file`,e,t,s,i)}sendImage(e,t,s,i){return this.getClient().sendFile(`${this._channelURL()}/image`,e,t,s,i)}deleteFile(e){return this.getClient().delete(`${this._channelURL()}/file`,{url:e})}deleteImage(e){return this.getClient().delete(`${this._channelURL()}/image`,{url:e})}async sendEvent(e){return this._checkInitialized(),await this.getClient().post(this._channelURL()+"/event",{event:e})}async search(e,t={}){if(t.offset&&t.next)throw Error("Cannot specify offset with next");const s={filter_conditions:{cid:this.cid},...t,sort:t.sort?D(t.sort):void 0};if(typeof e=="string")s.query=e;else if(typeof e=="object")s.message_filter_conditions=e;else throw Error(`Invalid type ${typeof e} for query parameter`);return await this.getClient().wsPromise,await this.getClient().get(this.getClient().baseURL+"/search",{payload:s})}async queryMembers(e,t=[],s={}){let i;const n=this.type;let r;return this.id?i=this.id:this.data?.members&&Array.isArray(this.data.members)&&(r=this.data.members),await this.getClient().get(this.getClient().baseURL+"/members",{payload:{type:n,id:i,members:r,sort:D(t),filter_conditions:e,...s}})}async updateMemberPartial(e,t){const s=new URL(`${this._channelURL()}/member`);return t?.userId&&s.searchParams.append("user_id",t.userId),await this.getClient().patch(s.toString(),e)}async partialUpdateMember(e,t){if(!e)throw Error("Please specify the user id");return await this.getClient().patch(this._channelURL()+`/member/${encodeURIComponent(e)}`,t)}async sendReaction(e,t,s){if(!e)throw Error("Message id is missing");if(!t||Object.keys(t).length===0)throw Error("Reaction object is missing");try{const i=this.getClient().offlineDb;if(i)return await i.queueTask({task:{channelId:this.id,channelType:this.t
11ype,messageId:e,payload:[e,t,s],type:"send-reaction"}})}catch(i){this._client.logger("error","offlineDb:send-reaction",{tags:["channel","offlineDb"],error:i})}return this._sendReaction(e,t,s)}async _sendReaction(e,t,s){if(!e)throw Error("Message id is missing");if(!t||Object.keys(t).length===0)throw Error("Reaction object is missing");return await this.getClient().post(this.getClient().baseURL+`/messages/${encodeURIComponent(e)}/reaction`,{reaction:t,...s})}async deleteReaction(e,t,s){if(this._checkInitialized(),!t||!e)throw Error("Deleting a reaction requires specifying both the message and reaction type");try{const i=this.getClient().offlineDb;if(i){const n=this.state.messages.find(({id:a})=>a===e),r={created_at:"",updated_at:"",message_id:e,type:t,user_id:this.getClient().userID??s};return n&&await i.deleteReaction({message:n,reaction:r}),await i.queueTask({task:{channelId:this.id,channelType:this.type,messageId:e,payload:[e,t],type:"delete-reaction"}})}}catch(i){this._client.logger("error","offlineDb:delete-reaction",{tags:["channel","offlineDb"],error:i})}return await this._deleteReaction(e,t,s)}async _deleteReaction(e,t,s){if(this._checkInitialized(),!t||!e)throw Error("Deleting a reaction requires specifying both the message and reaction type");const i=this.getClient().baseURL+`/messages/${encodeURIComponent(e)}/reaction/${encodeURIComponent(t)}`;return s?await this.getClient().delete(i,{user_id:s}):await this.getClient().delete(i,{})}async update(e={},t,s){return["config","cid","created_by","id","member_count","type","created_at","updated_at","last_message_at","own_capabilities"].forEach(n=>{delete e[n]}),await this._update({message:t,data:e,...s})}async updatePartial(e){const t=await this.getClient().patch(this._channelURL(),e),s=[...t.channel.own_capabilities||[]].sort().join()!==[...Array.isArray(this.data?.own_capabilities)?this.data?.own_capabilities:[]].sort().join();return this.data=t.channel,s&&this.getClient().dispatchEvent({type:"capabilities.changed",cid:this.cid,own_capabilities:t.channel.own_capabilities}),t}async enableSlowMode(e){const t=await this.getClient().post(this._channelURL(),{cooldown:e});return this.data=t.channel,t}async disableSlowMode(){const e=await this.getClient().post(this._channelURL(),{cooldown:0});return this.data=e.channel,e}async sendSharedLocation(e,t){const s=await this.sendMessage({id:e.message_id,shared_location:e,user:t?{id:t}:void 0});return e.end_at&&this.getClient().dispatchEvent({message:s.message,type:"live_location_sharing.started"}),s}async stopLiveLocationSharing(e){const t=await this.getClient().updateLocation({...e,end_at:new Date().toISOString()});this.getClient().dispatchEvent({live_location:t,type:"live_location_sharing.stopped"})}async delete(e={}){return await this.getClient().delete(this._channelURL(),{...e})}async truncate(e={}){return await this.getClient().post(this._channelURL()+"/truncate",e)}async acceptInvite(e={}){return await this._update({accept_invite:!0,...e})}async rejectInvite(e={}){return await this._update({reject_invite:!0,...e})}async addMembers(e,t,s={}){return await this._update({add_members:e,message:t,...s})}async addFilterTags(e,t,s={}){return await this._update({add_filter_tags:e,message:t,...s})}async removeFilterTags(e,t,s={}){return await this._update({remove_filter_tags:e,message:t,...s})}async addModerators(e,t,s={}){return await this._update({add_moderators:e,message:t,...s})}async assignRoles(e,t,s={}){return await this._update({assign_roles:e,message:t,...s})}async inviteMembers(e,t,s={}){return await this._update({invites:e,message:t,...s})}async removeMembers(e,t,s={}){return await this._update({remove_members:e,message:t,...s})}async demoteModerators(e,t,s={}){return await this._update({demote_moderators:e,message:t,...s})}async _update(e){const t=await this.getClient().post(this._channelURL(),e);return this.data=t.channel,t}async mute(e={}){return await this.getClient().post(this.getClient().baseURL+"/moderation/mute/channel",{channel_cid:this.cid,...e})}async unmute(e={}){return await this.getClient().post(this.getClient().baseURL+"/moderation/unmute/channel",{channel_cid:this.cid,...e})}async archive(e={}){const t=this.getClient(),s=e.user_id||t.userID;if(!s)throw Error("A user_id is required for archiving a channel");return(await this.partialUpdateMember(s,{set:{archived:!0}})).channel_member}async unarchive(e={}){const t=this.getClient(),s=e.user_id||t.userID;if(!s)throw Error("A user_id is required for unarchiving a channel");return(await this.partialUpdateMember(s,{set:{archived:!1}})).channel_member}async pin(e={}){const t=this.getClient(),s=e.user_id||t.userID;if(!s)throw new Error("A user_id is required for pinning a channel");return(await this.partialUpdateMember(s,{set:{pinned:!0}})).channel_member}async unpin(e={}){const t=this.getClient(),s=e.user_id||t.userID;if(!s)throw new Error("A user_id is required for unpinning a channel");return(await this.partialUpdateMember(s,{set:{pinned:!1}
11})).channel_member}muteStatus(){return this._checkInitialized(),this.getClient()._muteStatus(this.cid)}sendAction(e,t){if(this._checkInitialized(),!e)throw Error("Message id is missing");return this.getClient().post(this.getClient().baseURL+`/messages/${encodeURIComponent(e)}/action`,{message_id:e,form_data:t,id:this.id,type:this.type})}async keystroke(e,t){if(!this._isTypingIndicatorsEnabled())return;const 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 updateAIState(e,t,s={}){await this.sendEvent({...s,type:"ai_indicator.update",message_id:e,ai_state:t})}async clearAIIndicator(){await this.sendEvent({type:"ai_indicator.clear"})}async stopAIResponse(){await this.sendEvent({type:"ai_indicator.stop"})}async stopTyping(e,t){this._isTypingIndicatorsEnabled()&&(this.lastTypingEvent=null,this.isTyping=!1,await this.sendEvent({type:"typing.stop",parent_id:e,...t||{}}))}_isTypingIndicatorsEnabled(){return!this.getConfig()?.typing_events||!this.getClient().wsConnection?.isHealthy?!1:this.getClient().user?.privacy_settings?.typing_indicators?.enabled??!0}lastMessage(){let e=this.state.latestMessages.length-5;e<0&&(e=0);const t=this.state.latestMessages.length+1,s=this.state.latestMessages.slice(e,t);return s.sort((i,n)=>n.created_at.getTime()-i.created_at.getTime()),s[0]}async markRead(e={}){return await this.getClient().messageDeliveryReporter.markRead(this,e)}async markAsReadRequest(e={}){return this._checkInitialized(),!this.getConfig()?.read_events&&!this.getClient()._isUsingServerAuth()?null:await this.getClient().post(this._channelURL()+"/read",{...e})}async markUnread(e){return this._checkInitialized(),!this.getConfig()?.read_events&&!this.getClient()._isUsingServerAuth()?Promise.resolve(null):await this.getClient().post(this._channelURL()+"/unread",{...e})}clean(){this.lastKeyStroke&&new Date().getTime()-this.lastKeyStroke.getTime()>1e3&&this.isTyping&&sn(this.stopTyping(),"stop typing event"),this.state.clean()}async watch(e){const t={state:!0,watch:!0,presence:!1};await this.getClient().wsPromise,this.getClient()._hasConnectionID()||(t.watch=!1);const s={...t,...e},i=await this.query(s,"latest");return this.initialized=!0,this.data=i.channel,this._client.logger("info",`channel:watch() - started watching channel ${this.cid}`,{tags:["channel"],channel:this}),i}async stopWatching(){const e=await this.getClient().post(this._channelURL()+"/stop-watching",{});return this._client.logger("info",`channel:watch() - stopped watching channel ${this.cid}`,{tags:["channel"],channel:this}),e}async getReplies(e,t,s){const i=s?D(s):void 0,n=await this.getClient().get(this.getClient().baseURL+`/messages/${encodeURIComponent(e)}/replies`,{sort:i,...t});return n.messages&&this.state.addMessagesSorted(n.messages),n}async getPinnedMessages(e,t=[]){return await this.getClient().get(this._channelURL()+"/pinned_messages",{payload:{...e,sort:D(t)}})}getReactions(e,t){return this.getClient().get(this.getClient().baseURL+`/messages/${encodeURIComponent(e)}/reactions`,{...t})}getMessagesById(e){return this.getClient().get(this._channelURL()+"/messages",{ids:e.join(",")})}lastRead(){const{userID:e}=this.getClient();if(e)return this.state.read[e]?this.state.read[e].last_read:null}_countMessageAsUnread(e){return!(e.shadowed||e.silent||e.parent_id&&!e.show_in_channel||e.user?.id===this.getClient().userID||e.user?.id&&this.getClient().userMuteStatus(e.user.id)||Array.isArray(this.data?.own_capabilities)&&!this.data?.own_capabilities.includes("read-events")||this.muteStatus().muted)}countUnread(e){if(!e)return this.state.unreadCount;let t=0;for(let s=0;s<this.state.latestMessages.length;s+=1){const i=this.state.latestMessages[s];i.created_at>e&&this._countMessageAsUnread(i)&&t++}return t}countUnreadMentions(){const e=this.lastRead(),t=this.getClient().userID;let s=0;for(let i=0;i<this.state.latestMessages.length;i+=1){const n=this.state.latestMessages[i];this._countMessageAsUnread(n)&&(!e||n.created_at>e)&&n.mentioned_users?.some(r=>r.id===t)&&s++}return s}async query(e={},t="current"){await this.getClient().wsPromise;const s=e.created_by?.id??e.created_by_id??this._data?.created_by?.id??this._data?.created_by_id;
11this.getClient()._isUsingServerAuth()&&typeof s!="string"&&this.getClient().logger("warn","Either `created_by` (with `id` property) or `created_by_id` are missing from both `Channel._data` and `options` parameter");let i=`${this.getClient().baseURL}/channels/${encodeURIComponent(this.type)}`;this.id&&(i+=`/${encodeURIComponent(this.id)}`);const n=await this.getClient().post(i+"/query",{data:this._data,state:!0,...e});if(!this.id){this.id=n.channel.id,this.cid=n.channel.cid;const o=rn(this.type,n.members.map(l=>l.user_id||l.user?.id||""));o&&o in this.getClient().activeChannels&&delete this.getClient().activeChannels[o],!(this.cid in this.getClient().activeChannels)&&this.getClient()._cacheEnabled()&&(this.getClient().activeChannels[this.cid]=this)}this.getClient()._addChannelConfig(n.channel),typeof n.channel.config?.shared_locations<"u"&&this.messageComposer.updateConfig({location:{enabled:n.channel.config.shared_locations}});const{messageSet:r}=this._initializeState(n,t);r.pagination={...r.pagination,...la({parentSet:r,messagePaginationOptions:e?.messages,requestedPageSize:e?.messages?.limit??Fd,returnedPage:n.messages,logger:this.getClient().logger})},this.getClient().polls.hydratePollCache(n.messages,!0),this.getClient().reminders.hydrateState(n.messages),this.messageComposer.initStateFromChannelResponse(n);const a=[...n.channel.own_capabilities||[]].sort().join()!==[...this.data&&Array.isArray(this.data?.own_capabilities)?this.data.own_capabilities:[]].sort().join();return this.data=n.channel,this.offlineMode=!1,a&&this.getClient().dispatchEvent({type:"capabilities.changed",cid:this.cid,own_capabilities:n.channel.own_capabilities}),this.getClient().dispatchEvent({type:"channels.queried",queriedChannels:{channels:[n],isLatestMessageSet:r.isLatest}}),this.getClient().offlineDb?.executeQuerySafely(o=>o.upsertChannels?.({channels:[n],isLatestMessagesSet:r.isLatest}),{method:"upsertChannels"}),this.getClient().syncDeliveredCandidates([this]),n}async banUser(e,t){return this._checkInitialized(),await this.getClient().banUser(e,{...t,type:this.type,id:this.id})}async hide(e=null,t=!1){return this._checkInitialized(),await this.getClient().post(`${this._channelURL()}/hide`,{user_id:e,clear_history:t})}async show(e=null){return this._checkInitialized(),await this.getClient().post(`${this._channelURL()}/show`,{user_id:e})}async unbanUser(e){return this._checkInitialized(),await this.getClient().unbanUser(e,{type:this.t
11ype,id:this.id})}async shadowBan(e,t){return this._checkInitialized(),await this.getClient().shadowBan(e,{...t,type:this.type,id:this.id})}async removeShadowBan(e){return this._checkInitialized(),await this.getClient().removeShadowBan(e,{type:this.type,id:this.id})}async vote(e,t,s){return await this.getClient().castPollVote(e,t,s)}async removeVote(e,t,s){return await this.getClient().removePollVote(e,t,s)}async _createDraft(e){return await this.getClient().post(this._channelURL()+"/draft",{message:e})}async createDraft(e){try{const t=this.getClient().offlineDb;if(t)return await t.queueTask({task:{channelId:this.id,channelType:this.type,threadId:e.parent_id,payload:[e],type:"create-draft"}})}catch(t){this._client.logger("error","offlineDb:create-draft",{tags:["channel","offlineDb"],error:t})}return this._createDraft(e)}async _deleteDraft({parent_id:e}={}){return await this.getClient().delete(this._channelURL()+"/draft",{parent_id:e})}async deleteDraft(e={}){const{parent_id:t}=e;try{const s=this.getClient().offlineDb;if(s)return await s.queueTask({task:{channelId:this.id,channelType:this.type,threadId:t,payload:[e],type:"delete-draft"}})}catch(s){this._client.logger("error","offlineDb:delete-draft",{tags:["channel","offlineDb"],error:s})}return this._deleteDraft(e)}async getDraft({parent_id:e}={}){return await this.getClient().get(this._channelURL()+"/draft",{parent_id:e})}on(e,t){const 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(n=>n!==i)}}}off(e,t){const 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(n=>n!==i)}_handleChannelEvent(e){const t=this;this._client.logger("info",`channel:_handleChannelEvent - Received event of type { ${e.type} } on ${this.cid}`,{tags:["event","channel"],channel:this});const s=t.state;switch(e.type){case"typing.start":e.user?.id&&(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){const i=s.read[e.user.id];s.read[e.user.id]={...i,last_read:new Date(e.created_at),last_read_message_id:e.last_read_message_id,user:e.user,unread_messages:0},this.messageReceiptsTracker.onMessageRead({user:e.user,readAt:e.created_at,lastReadMessageId:e.last_read_message_id});const n=this.getClient();e.user?.id===n.user?.id&&(s.unreadCount=0,n.syncDeliveredCandidates([this]))}break;case"message.delivered":if(e.user?.id&&e.created_at){const i=s.read[e.user.id];s.read[e.user.id]={...i,last_delivered_at:e.last_delivered_at?new Date(e.last_delivered_at):void 0,last_delivered_message_id:e.last_delivered_message_id,user:e.user},this.messageReceiptsTracker.onMessageDelivered({user:e.user,deliveredAt:e.created_at,lastDeliveredMessageId:e.last_delivered_message_id});const n=this.getClient();e.user?.id===n.user?.id&&n.syncDeliveredCandidates([this])}break;case"user.watching.start":case"user.updated":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":e.message&&(this._extendEventWithOwnReactions(e),e.hard_delete?s.removeMessage(e.message):s.addMessageSorted(e.message,!1,!1),s.removeQuotedMessageReferences(e.message),e.message.pinned&&s.removePinnedMessage(e.message));break;case"user.messages.deleted":e.user&&this.state.deleteUserMessages(e.user,!!e.hard_delete,new Date(e.created_at??Date.now()));break;case"message.new":if(e.message){const i=this.getClient(),n=e.user?.id===i.user?.id,r=e.message.parent_id&&!e.message.show_in_channel;if((this.state.isUpToDate||r)&&s.addMessageSorted(e.message,n),e.message.pinned&&s.addPinnedMessage(e.message),n||r)break;if(e.user?.id)for(const o in s.read)o===e.user.id?s.read[e.user.id]={last_read:new Date(e.created_at),user:e.user,unread_messages:0,last_delivered_at:new Date(e.created_at),last_delivered_message_id:e.message.id}:s.read[o].unread_messages+=1;this._countMessageAsUnread(e.message)&&(s.unreadCount=s.unreadCount+1),i.syncDeliveredCandidates([this])}break;case"message.updated":case"message.undeleted":e.message&&(this._extendEventWithOwnReactions(e),s.addMessageSorted(e.message,!1,!1),s._updateQuotedMessageReferences({message:e.message}
11),e.message.pinned?s.addPinnedMessage(e.message):s.removePinnedMessage(e.message));break;case"channel.truncated":if(e.channel?.truncated_at){const i=+new Date(e.channel.truncated_at);s.messageSets.forEach((n,r)=>{n.messages.forEach(({created_at:a,id:o})=>{i>+a&&s.removeMessage({id:o,messageSetIndex:r})})}),s.pinnedMessages.forEach(({id:n,created_at:r})=>{i>+r&&s.removePinnedMessage({id:n})}),s.unreadCount=this.countUnread(new Date(e.channel.truncated_at))}else s.clearMessages(),s.unreadCount=0;e.message&&(s.addMessageSorted(e.message),e.message.pinned&&s.addPinnedMessage(e.message));break;case"member.added":case"member.updated":{const i={...e.member};i.pinned_at===null&&delete i.pinned_at,i.archived_at===null&&delete i.archived_at,i?.user&&(s.members={...s.members,[i.user.id]:i},t.data?.member_count&&e.type==="member.added"&&(t.data.member_count+=1));const n=this.getClient().userID;typeof n=="string"&&typeof i?.user?.id=="string"&&i.user.id===n&&(s.membership=i);break}case"member.removed":if(e.user?.id){const i={...s.members};delete i[e.user.id],s.members=i,t.data?.member_count&&(t.data.member_count=Math.max(t.data.member_count-1,0))}break;case"notification.mark_unread":{if(!(e.user?.id===this.getClient().user?.id)||!e.user)break;const n=e.unread_messages??0,r=s.read[e.user.id];s.read[e.user.id]={...r,first_unread_message_id:e.first_unread_message_id,last_read:new Date(e.last_read_at),last_read_message_id:e.last_read_message_id,user:e.user,unread_messages:n},s.unreadCount=n,this.messageReceiptsTracker.onNotificationMarkUnread({user:e.user,lastReadAt:e.last_read_at,lastReadMessageId:e.last_read_message_id});break}case"channel.updated":if(e.channel){e.channel?.frozen!==void 0&&e.channel.frozen!==t.data?.frozen&&this.query({state:!1,messages:{limit:0},watchers:{limit:0}});const n={...e.channel,hidden:e.channel?.hidden??t.data?.hidden,own_capabilities:e.channel?.own_capabilities??t.data?.own_capabilities};t.data=n}break;case"reaction.new":if(e.message&&e.reaction){const{message:i,reaction:n}=e;e.message=s.addReaction(n,i)}break;case"reaction.deleted":if(e.message&&e.reaction){const{message:i,reaction:n}=e;e.message=s.removeReaction(n,i)}break;case"reaction.updated":if(e.message&&e.reaction){const{message:i,reaction:n}=e;e.message=s.addReaction(n,i,!0)}break;case"channel.hidden":t.data={...t.data,blocked:!!e.channel?.blocked,hidden:!0},e.clear_history&&s.clearMessages();break;case"channel.visible":t.data={...t.data,blocked:!!e.channel?.blocked,hidden:!1},this.getClient().offlineDb?.handleChannelVisibilityEvent({event:e});break;case"user.banned":if(!e.user?.id)break;s.members[e.user.id]={...s.members[e.user.id]||{},shadow_banned:!!e.shadow,banned:!e.shadow,user:{...s.members[e.user.id]?.user||{},...e.user}};break;case"user.unbanned":if(!e.user?.id)break;s.members[e.user.id]={...s.members[e.user.id]||{},shadow_banned:!1,banned:!1,user:{...s.members[e.user.id]?.user||{},...e.user}};break}e.watcher_count!==void 0&&(t.state.watcher_count=e.watcher_count)}_checkInitialized(){if(!this.initialized&&!this.offlineMode&&!this.getClient()._isUsingServerAuth())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"){const{state:s,user:i,userID:n}=this.getClient();if(e.members){this._hydrateMembers({members:e.members});for(const o of e.members)o.user&&s.updateUserReference(o.user,this.cid)}this.state.membership=e.membership||{};const r=e.messages||[];this.state.messages||this.state.initMessages();const{messageSet:a}=this.state.addMessagesSorted(r,!1,!0,!0,t);if(this.state.pinnedMessages||(this.state.pinnedMessages=[]),this.state.addPinnedMessages(e.pinned_messages||[]),e.pending_messages&&(this.state.pending_messages=e.pending_messages),e.watcher_count!==void 0&&(this.state.watcher_count=e.watcher_count),e.watchers)for(const o of e.watchers)o&&(s.updateUserReference(o,this.cid),this.state.watchers[o.id]=o);if(n!=null){const o=this.state.last_message_at||new Date;i&&(this.state.read[i.id]={user:i,last_read:o,unread_messages:0})}if(e.read){for(const o of e.read)this.state.read[o.user.id]={last_delivered_at:o.last_delivered_at?new Date(o.last_delivered_at):void 0,last_delivered_message_id:o.last_delivered_message_id,last_read:new Date(o.last_read),last_read_message_id:o.last_read_message_id,unread_messages:o.unread_messages??0,user:o.user},o.user.id===i?.id&&(this.state.unreadCount=this.state.read[o.user.id].unread_messages);this.messageReceiptsTracker.ingestInitial(e.read)}return{messageSet:a}}_extendEventWithOwnReactions(e){if(!e.message)return;const t=this.state.findMessage(e.message.id,e.message.parent_id);t&&(e.message.own_reactions=t.own_reactions)}_hydrateMembers({members:e,overrideCurrentState:t=!0}){const s=e.reduce((i,n)=>(n.user&&(i[n.user.id]=n),i),{});t?this.state.members=s:!t&&e.length&&(this.state.members={...this.state.members,...s})}_disconnect(){this._client.logger("info",`channel:disconnect() - Disconnecting the channel ${this.cid}
11`,{tags:["connection","channel"],channel:this}),this.disconnected=!0,this.state.setIsUpToDate(!1)}},Ti=class{constructor({client:e}){this.client=e,this.users={},this.userChannelReferences={}}updateUsers(e){for(const t of e)this.updateUser(t)}updateUser(e){e!=null&&this.client._cacheEnabled()&&(this.users[e.id]=e)}updateUserReference(e,t){e==null||!this.client._cacheEnabled()||(this.updateUser(e),this.userChannelReferences[e.id]||(this.userChannelReferences[e.id]={}),this.userChannelReferences[e.id][t]=!0)}deleteAllChannelReference(e){for(const t in this.userChannelReferences)delete this.userChannelReferences[t][e]}},Oo=class{constructor(){this.connectionStartTimestamp=null,this.wsTotalFailures=0,this.wsConsecutiveFailures=0,this.instanceClientId=$e()}},Is=async(e,t)=>{for(let i=0;i<3;i++){try{await T.post(`https://chat-insights.getstream.io/insights/${e}`,t)}catch{await ye((i+1)*3e3);continue}break}};function Po(e,t){return{...t,...ko(e)}}function ko(e){const{client:t}=e;return{ready_state:e.ws?.readyState,url:e._buildUrl(),api_key:t.key,start_ts:t.insightMetrics.connectionStartTimestamp,end_ts:new Date().getTime(),auth_type:t.getAuthType(),token:t.tokenManager.token,user_id:t.userID,user_details:t._user,device:t.options.device,client_id:e.connectionID,ws_details:e.ws,ws_consecutive_failures:t.insightMetrics.wsConsecutiveFailures,ws_total_failures:t.insightMetrics.wsTotalFailures,request_id:e.requestID,online:typeof navigator<"u"?navigator?.onLine:null,user_agent:typeof navigator<"u"?navigator?.userAgent:null,instance_client_id:t.insightMetrics.instanceClientId}}function No(e){return ko(e)}var Yh=e=>e.code!==void 0,Zh=e=>e.error!==void 0,Fo=class{constructor({client:e}){this._buildUrl=()=>{const t=this.client._buildWSPayload(this.requestID),s=this.client.tokenManager.getToken(),i=this.client.options.wsUrlParams,n=new URLSearchParams(i);return n.set("json",t),n.set("api_key",this.client.key),n.set("authorization",`${s}`),n.set("stream-auth-type",this.client.getAuthType()),n.set("X-Stream-Client",this.client.getUserAgent()),`${this.client.wsBaseURL}/connect?${n.toString()}`},this.onlineStatusChanged=t=>{t.type==="offline"?(this._log("onlineStatusChanged() - Status changing to offline"),this._setHealth(!1)):t.type==="online"&&(this._log(`onlineStatusChanged() - Status changing to online. isHealthy: ${this.isHealthy}`),this.isHealthy||this._reconnect({interval:10}))},this.onopen=t=>{this.wsID===t&&this._log("onopen() - onopen callback",{wsID:t})},this.onmessage=(t,s)=>{if(this.wsID!==t)return;this._log("onmessage() - onmessage callback",{event:s,wsID:t});
11const i=typeof s.data=="string"?JSON.parse(s.data):null;if(!this.isResolved&&i){if(this.isResolved=!0,i.error){this.rejectPromise?.(this._errorFromWSEvent(i,!1));return}this.resolvePromise?.(i),this._setHealth(!0)}this.lastEvent=new Date,i&&i.type==="health.check"&&this.scheduleNextPing(),this.client.handleEvent(s),this.scheduleConnectionCheck()},this.onclose=(t,s)=>{if(this.wsID===t)if(this._log("onclose() - onclose callback - "+s.code,{event:s,wsID:t}),s.code===qe.WS_CLOSED_SUCCESS){const i=new Error(`WS connection reject with error ${s.reason}`);i.reason=s.reason,i.code=s.code,i.wasClean=s.wasClean,i.target=s.target,this.rejectPromise?.(i),this._log(`onclose() - WS connection reject with error ${s.reason}`,{event:s})}else this.consecutiveFailures+=1,this.totalFailures+=1,this._setHealth(!1),this.isConnecting=!1,this.rejectPromise?.(this._errorFromWSEvent(s)),this._log("onclose() - WS connection closed. Calling reconnect ...",{event:s}),this._reconnect()},this.onerror=(t,s)=>{this.wsID===t&&(this.consecutiveFailures+=1,this.totalFailures+=1,this._setHealth(!1),this.isConnecting=!1,this.rejectPromise?.(this._errorFromWSEvent(s)),this._log("onerror() - WS connection resulted into error",{event:s}),this._reconnect())},this._setHealth=t=>{if(t!==this.isHealthy){if(this.isHealthy=t,this.isHealthy){this.client.dispatchEvent({type:"connection.changed",online:this.isHealthy});return}setTimeout(()=>{this.isHealthy||this.client.dispatchEvent({type:"connection.changed",online:this.isHealthy})},5e3)}},this._errorFromWSEvent=(t,s=!0)=>{let i,n,r;Yh(t)&&(i=t.code,n="unknown",r=t.reason),Zh(t)&&(i=t.error.code,n=t.error.StatusCode,r=t.error.message),this._log(`_errorFromWSEvent() - WS failed with code ${i}`,{event:t},"warn");const a=new Error(`WS failed with code ${i} and reason - ${r}`);return a.code=i,a.StatusCode=n,a.isWSFailure=s,a},this._setupConnectionPromise=()=>{this.isResolved=!1,this.connectionOpen=new Promise((t,s)=>{this.resolvePromise=t,this.rejectPromise=s})},this.scheduleNextPing=()=>{this.healthCheckTimeoutRef&&clearTimeout(this.healthCheckTimeoutRef),this.healthCheckTimeoutRef=setTimeout(()=>{const t=[{type:"health.check",client_id:this.client.clientID}];try{this.ws?.send(JSON.stringify(t))}catch{}},this.pingInterval)},this.scheduleConnectionCheck=()=>{this.connectionCheckTimeoutRef&&clearTimeout(this.connectionCheckTimeoutRef),this.connectionCheckTimeoutRef=setTimeout(()=>{const t=new Date;this.lastEvent&&t.getTime()-this.lastEvent.getTime()>this.connectionCheckTimeout&&(this._log("scheduleConnectionCheck - going to reconnect"),this._setHealth(!1),this._reconnect())},this.connectionCheckTimeout)},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,ia(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{const t=await this._connect();this.consecutiveFailures=0,this._log(`connect() - Established ws connection with healthcheck: ${t}`)}catch(t){this.isHealthy=!1,this.consecutiveFailures+=1;const s=t;if(s.code===qe.TOKEN_EXPIRED&&!this.client.tokenManager.isStatic())this._log("connect() - WS failure due to expired token, so going to try to reload token and reconnect"),this._reconnect({refreshToken:!0});else if(!s.isWSFailure)throw new Error(JSON.stringify({code:s.code,StatusCode:s.StatusCode,message:s.message,isWSFailure:s.isWSFailure}))}return await this._waitForHealthy(e)}_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 ye(50)}})(),(async()=>{throw await ye(e),this.isConnecting=!1,new Error(JSON.stringify({code:"",StatusCode:"",message:"initial WS connection could not be established",isWSFailure:!0}))})()])}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),na(this.onlineStatusChanged),this.isHealthy=!1,this.ws&&this.ws.removeAllListeners&&this.ws.removeAllListeners();let t;const{ws:s}=this;return s&&s.close&&s.readyState===s.OPEN?(t=new Promise(i=>{const n=r=>{this._log(`disconnect() - resolving isClosedPromise ${r?"with":"without"} close frame`,{event:r}),i()};
11s.onclose=n,setTimeout(n,e??1e3)}),this._log("disconnect() - Manually closed connection by calling client.disconnect()"),s.close(qe.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||this.isDisconnected&&this.client.options.enableWSFallback)return;this.isConnecting=!0,this.requestID=$e(),this.client.insightMetrics.connectionStartTimestamp=new Date().getTime();let e=!1;try{this._log("_connect() - waiting for token"),await this.client.tokenManager.tokenReady(),e=!0}catch{}try{e||(this._log("_connect() - tokenProvider failed before, so going to retry"),await this.client.tokenManager.loadToken()),this._setupConnectionPromise();const t=this._buildUrl();this._log(`_connect() - Connecting to ${t}`,{wsURL:t,requestID:this.requestID}),this.ws=new Be(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);const s=await this.connectionOpen;if(this.isConnecting=!1,s)return this.connectionID=s.connection_id,this.client.insightMetrics.wsConsecutiveFailures>0&&this.client.options.enableInsights&&(Is("ws_success_after_failure",No(this)),this.client.insightMetrics.wsConsecutiveFailures=0),s}catch(t){if(this.isConnecting=!1,this._log("_connect() - Error - ",t),this.client.options.enableInsights){this.client.insightMetrics.wsConsecutiveFailures++,this.client.insightMetrics.wsTotalFailures++;const s=Po(this,th(t));Is?.("ws_fatal",s)}throw 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=Us(this.consecutiveFailures)),await ye(t),this.isConnecting||this.isHealthy){this._log("_reconnect() - Abort (2) since already connecting or healthy");return}if(this.isDisconnected&&this.client.options.enableWSFallback){this._log("_reconnect() - Abort (3) since disconnect() is called");return}this._log("_reconnect() - Destroying current WS connection"),this._destroyCurrentWSConnection(),e.refreshToken&&await this.client.tokenManager.loadToken();try{await this._connect(),this._log("_reconnect() - Waiting for recoverCallBack"),await this.client.recoverState(),this._log("_reconnect() - Finished recoverCallBack"),this.consecutiveFailures=0}catch(s){if(this.isHealthy=!1,this.consecutiveFailures+=1,s.code===qe.TOKEN_EXPIRED&&!this.client.tokenManager.isStatic())return this._log("_reconnect() - WS failure due to expired token, so going to try to reload token and reconnect"),this._reconnect({refreshToken:!0});s.isWSFailure&&(this._log("_reconnect() - WS failure, so going to try to reconnect"),this._reconnect())}this._log("_reconnect() - == END ==")}_destroyCurrentWSConnection(){this.wsID+=1;try{this?.ws?.removeAllListeners(),this?.ws?.close()}catch{}}},Gt=tn(Dd()),mr=tn(Od());function bn(e,t,s={},i={}){if(typeof t!="string")throw new TypeError("userId should be a string");const n={user_id:t,...s};if(Gt.default==null||Gt.default.sign==null)throw Error("Unable to find jwt crypto, if you are getting this error is probably because you are trying to generate tokens on browser or React Native (or other environment where crypto functions are not available). Please Note: token should only be generated server-side.");const r=Object.assign({algorithm:"HS256",noTimestamp:!0},i);return n.iat&&(r.noTimestamp=!1),Gt.default.sign(n,e,r)}function Li(e,t={}){const s={server:!0},i=Object.assign({algorithm:"HS256",noTimestamp:!0},t);return Gt.default.sign(s,e,i)}function Bo(e){const t=e.split(".");if(t.length!==3)return"";const s=t[1],i=sa(s);return JSON.parse(i).user_id}function qo(e){return["eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9",ta(JSON.stringify({user_id:e})),"devtoken"].join(".")}function $o(e,t,s){const i=Buffer.from(t,"utf8"),n=mr.default.createHmac("sha256",i).update(e).digest("hex");try{return mr.default.timingSafeEqual(Buffer.from(n),Buffer.from(s))}catch{return!1}}var Ho=class{constructor(e){this.setTokenOrProvider=async(t,s)=>{this.validateToken(t,s),this.user=s,wi(t)&&(this.tokenProvider=t,this.type="provider"),typeof t=="string"&&(this.token=t,this.type="static"),!t&&this.user&&this.secret&&(this.token=bn(this.secret,s.id,{},{}),this.type="static"),await this.loadToken()},this.reset=()=>{this.token=void 0,this.tokenProvider=void 0,this.type="static",this.user=void 0,this.loadTokenPromise=null},this.validateToken=(t,s)=>{if(!(s&&s.anon&&!t)){if(!this.secret&&!t)throw new Error("User token can not be empty");if(t&&typeof t!="string"&&!wi(t))throw new Error("user token should either be a string or a function");if(typeof t=="string"){if(s.anon&&t==="")return;const i=Bo(t);
11if(t!=null&&(i==null||i===""||i!==s.id))throw new Error("userToken does not have a user_id or is not matching with user.id")}}},this.tokenReady=()=>this.loadTokenPromise,this.loadToken=()=>(this.loadTokenPromise=new Promise(async(t,s)=>{if(this.type==="static")return t(this.token);if(this.tokenProvider&&typeof this.tokenProvider!="string"){try{this.token=await this.tokenProvider()}catch(i){return s(new Error(`Call to tokenProvider failed with message: ${i}`,{cause:i}))}t(this.token)}}),this.loadTokenPromise),this.getToken=()=>{if(this.token)return this.token;if(this.user&&this.user.anon&&!this.token)return this.token;if(this.secret)return Li(this.secret);throw new Error("Both secret and user tokens are not set. Either client.connectUser wasn't called or client.disconnect was called")},this.isStatic=()=>this.type==="static",this.loadTokenPromise=null,e&&(this.secret=e),this.type="static",this.secret&&(this.token=Li(this.secret))}},eu=class{constructor({client:e}){this._onlineStatusChanged=t=>{if(this._log(`_onlineStatusChanged() - ${t.type}`),t.type==="offline"){this._setState("CLOSED"),this.cancelToken?.cancel("disconnect() is called"),this.cancelToken=void 0;return}t.type==="online"&&this.state==="CLOSED"&&this.connect(!0)},this._req=async(t,s,i)=>{!this.cancelToken&&!t.close&&(this.cancelToken=T.CancelToken.source());try{const n=await this.client.doAxiosRequest("get",this.client.baseURL.replace(":3030",":8900")+"/longpoll",void 0,{config:{...s,cancelToken:this.cancelToken?.token},params:t});return this.consecutiveFailures=0,n}catch(n){if(this.consecutiveFailures+=1,i&&Ct(n))return this._log("_req() - Retryable error, retrying request"),await ye(Us(this.consecutiveFailures)),this._req(t,s,i);throw n}},this._poll=async()=>{for(;this.state==="CONNECTED";)try{const t=await this._req({},{timeout:3e4},!0);if(t.events?.length)for(let s=0;s<t.events.length;s++)this.client.dispatchEvent(t.events[s])}catch(t){if(T.isCancel(t)){this._log("_poll() - axios canceled request");return}if(Oh(t)){this._log("_poll() - ConnectionID error, connecting without ID..."),this._setState("DISCONNECTED"),this.connect(!0);return}if(qs(t)&&!Ct(t)){this._setState("CLOSED");return}await ye(Us(this.consecutiveFailures))}},this.connect=async(t=!1)=>{if(this.state==="CONNECTING"){this._log("connect() - connecting already in progress",{reconnect:t},"warn");return}if(this.state==="CONNECTED"){this._log("connect() - already connected and polling",{reconnect:t},"warn");return}this._setState("CONNECTING"),this.connectionID=void 0;try{const{event:s}=await this._req({json:this.client._buildWSPayload()},{timeout:8e3},t);return this._setState("CONNECTED"),this.connectionID=s.connection_id,this.client.dispatchEvent(s),this._poll(),t&&this.client.recoverState(),s}catch(s){throw this._setState("CLOSED"),s}},this.isHealthy=()=>!!this.connectionID&&this.state==="CONNECTED",this.disconnect=async(t=2e3)=>{na(this._onlineStatusChanged),this._setState("DISCONNECTED"),this.cancelToken?.cancel("disconnect() is called"),this.cancelToken=void 0;const s=this.connectionID;this.connectionID=void 0;try{await this._req({close:!0,connection_id:s},{timeout:t},!1),this._log("disconnect() - Closed connectionID")}catch(i){this._log("disconnect() - Failed",{err:i},"error")}},this.client=e,this.state="INIT",this.consecutiveFailures=0,ia(this._onlineStatusChanged)}_log(e,t={},s="info"){this.client.logger(s,"WSConnectionFallback:"+e,{tags:["connection_fallback","connection"],...t})}_setState(e){this._log(`_setState() - ${e}`),this.state==="CONNECTING"&&e==="CONNECTED"&&this.client.dispatchEvent({type:"connection.changed",online:!0}),(e==="CLOSED"||e==="DISCONNECTED")&&this.client.dispatchEvent({type:"connection.changed",online:!1}),this.state=e}},Ii=class{constructor(e,t,s,i){this.client=e,this.type=t,this.id=s,this.data=i}create(){const e={name:this.data?.name,filter:this.data?.filter,description:this.data?.description,all_sender_channels:this.data?.all_sender_channels,all_users:this.data?.all_users};return this.client.createSegment(this.type,this.id,e)}verifySegmentId(){if(!this.id)throw new Error("Segment id is missing. Either create the segment using segment.create() or set the id during instantiation - const segment = client.segment(id)")}get(){return this.verifySegmentId(),this.client.getSegment(this.id
11)}update(e){return this.verifySegmentId(),this.client.updateSegment(this.id,e)}addTargets(e){return this.verifySegmentId(),this.client.addSegmentTargets(this.id,e)}removeTargets(e){return this.verifySegmentId(),this.client.removeSegmentTargets(this.id,e)}delete(){return this.verifySegmentId(),this.client.deleteSegment(this.id)}targetExists(e){return this.verifySegmentId(),this.client.segmentTargetExists(this.id,e)}queryTargets(e={},t=[],s={}){return this.verifySegmentId(),this.client.querySegmentTargets(this.id,e,t,s)}},lt={user:"stream:user",message:"stream:chat:v1:message",userprofile:"stream:v1:user_profile"},Vo=class{constructor(e){this.client=e}flagUser(e,t,s={}){return this.flag(lt.user,e,"",t,s)}flagMessage(e,t,s={}){return this.flag(lt.message,e,"",t,s)}async flag(e,t,s,i,n={}){return await this.client.post(this.client.baseURL+"/api/v2/moderation/flag",{entity_type:e,entity_id:t,entity_creator_id:s,reason:i,...n})}async muteUser(e,t={}){return await this.client.post(this.client.baseURL+"/api/v2/moderation/mute",{target_ids:[e],...t})}async unmuteUser(e,t){return await this.client.post(this.client.baseURL+"/api/v2/moderation/unmute",{target_ids:[e],...t})}async getUserModerationReport(e,t={}){return await this.client.get(this.client.baseURL+"/api/v2/moderation/user_report",{user_id:e,...t})}async queryReviewQueue(e={},t=[],s={}){return await this.client.post(this.client.baseURL+"/api/v2/moderation/review_queue",{filter:e,sort:D(t),...s})}async upsertConfig(e){return await this.client.post(this.client.baseURL+"/api/v2/moderation/config",e)}async getConfig(e,t){return await this.client.get(this.client.baseURL+"/api/v2/moderation/config/"+e,t)}async deleteConfig(e,t){return await this.client.delete(this.client.baseURL+"/api/v2/moderation/config/"+e,t)}async queryConfigs(e,t,s={}){return await this.client.post(this.client.baseURL+"/api/v2/moderation/configs",{filter:e,sort:t,...s})}async submitAction(e,t,s={}){return await this.client.post(this.client.baseURL+"/api/v2/moderation/submit_action",{action_type:e,item_id:t,...s})}async check(e,t,s,i,n,r){return await this.client.post(this.client.baseURL+"/api/v2/moderation/check",{entity_type:e,entity_id:t,entity_creator_id:s,moderation_payload:i,config_key:n,options:r})}async checkUserProfile(e,t){if(!t.username&&!t.image)throw new Error("Either username or image must be provided");const s={};return t.username&&(s.texts=[t.username]),t.image&&(s.images=[t.image]),await this.check(lt.userprofile,e,e,s,"user_profile:default",{force_sync:!0,test_mode:!0})}async addCustomFlags(e,t,s,i,n){return await this.client.post(this.client.baseURL+"/api/v2/moderation/custom_check",{entity_type:e,entity_id:t,entity_creator_id:s,moderation_payload:i,flags:n})}async addCustomMessageFlags(e,t){return await this.addCustomFlags(lt.message,e,"",{},t)}async upsertModerationRule(e){return await this.client.post(this.client.baseURL+"/api/v2/moderation/moderation_rule",e)}async queryModerationRules(e={},t=[],s={}){return await this.client.post(this.client.baseURL+"/api/v2/moderation/moderation_rules",{filter:e,sort:t,...s})}async getModerationRule(e){return await this.client.get(this.client.baseURL+"/api/v2/moderation/moderation_rule/"+e)}async deleteModerationRule(e){return await this.client.delete(this.client.baseURL+"/api/v2/moderation/moderation_rule/"+e)}},tu=1e3,yr=25,Di={active:!1,isThreadOrderStale:!1,threads:[],unreadThreadCount:0,unseenThreadIds:[],lastConnectionDropAt:null,pagination:{isLoading:!1,isLoadingNext:!1,nextCursor:null},ready:!1},jo=class extends Pe{constructor({client:e}){super(),this.resetState=()=>{this.state.next(Di)},this.activate=()=>{this.state.partialNext({active:!0})},this.deactivate=()=>{this.state.partialNext({active:!1})},this.registerSubscriptions=()=>{this.hasSubscriptions||(this.addUnsubscribeFunction(this.subscribeUnreadThreadsCountChange()),this.addUnsubscribeFunction(this.subscribeManageThreadSubscriptions()),this.addUnsubscribeFunction(this.subscribeReloadOnActivation()),this.addUnsubscribeFunction(this.subscribeNewReplies()),this.addUnsubscribeFunction(this.subscribeRecoverAfterConnectionDrop()),this.addUnsubscribeFunction(this.subscribeChannelDeleted()))},this.subscribeUnreadThreadsCountChange=()=>{const{unread_threads:t=0}=this.client.user??{};this.state.partialNext({unreadThreadCount:t});const s=["health.check","notification.mark_read","notification.thread_message_new","notification.channel_deleted"].map(i=>this.client.on(i,n=>{const{unread_threads:r}=n.me??n;typeof r=="number"&&this.state.partialNext({unreadThreadCount:r})}).unsubscribe);return()=>s.forEach(i=>
11i())},this.subscribeChannelDeleted=()=>this.client.on("notification.channel_deleted",t=>{const{cid:s}=t,{threads:i}=this.state.getLatestValue(),n=i.filter(r=>r.channel.cid!==s);this.state.partialNext({threads:n})}).unsubscribe,this.subscribeManageThreadSubscriptions=()=>this.state.subscribeWithSelector(t=>({threads:t.threads}),({threads:t},s)=>{const{threads:i=[]}=s??{},n=i.filter(r=>r!==this.threadsById[r.id]);t.forEach(r=>r.registerSubscriptions()),n.forEach(r=>r.unregisterSubscriptions())}),this.subscribeReloadOnActivation=()=>this.state.subscribeWithSelector(t=>({active:t.active}),({active:t})=>{t&&this.reload()}),this.subscribeNewReplies=()=>this.client.on("notification.thread_message_new",t=>{const s=t.message?.parent_id;if(!s)return;const{unseenThreadIds:i,ready:n}=this.state.getLatestValue();n&&(this.threadsById[s]?this.state.partialNext({isThreadOrderStale:!0}):i.includes(s)||this.state.partialNext({unseenThreadIds:i.concat(s)}))}).unsubscribe,this.subscribeRecoverAfterConnectionDrop=()=>{const t=this.client.on("connection.changed",n=>{n.online===!1&&this.state.next(r=>r.lastConnectionDropAt?r:{...r,lastConnectionDropAt:new Date})}).unsubscribe,s=nn(()=>{const{lastConnectionDropAt:n}=this.state.getLatestValue();n&&this.reload({force:!0})},tu,{trailing:!0}),i=this.client.on("connection.recovered",s).unsubscribe;return()=>{t(),i()}},this.unregisterSubscriptions=()=>(this.state.getLatestValue().threads.forEach(t=>t.unregisterSubscriptions()),super.unregisterSubscriptions()),this.reload=async({force:t=!1}={})=>{const{threads:s,unseenThreadIds:i,isThreadOrderStale:n,pagination:r,ready:a}=this.state.getLatestValue();if(r.isLoading||!t&&a&&!i.length&&!n)return;const o=s.length+i.length;try{this.state.next(d=>({...d,pagination:{...d.pagination,isLoading:!0}}));const l=await this.queryThreads({limit:Math.min(o,yr)||yr}),c=[];for(const d of l.threads){const h=this.threadsById[d.id];h?(c.push(h),h.hasStaleState&&h.hydrateState(d)):c.push(d)}this.state.next(d=>({...d,threads:c,unseenThreadIds:[],isThreadOrderStale:!1,pagination:{...d.pagination,isLoading:!1,nextCursor:l.next??null},ready:!0}))}catch(l){this.client.logger("error",l.message),this.state.next(c=>({...c,pagination:{...c.pagination,isLoading:!1}}))}},this.queryThreads=(t={})=>this.client.queryThreads({limit:25,participant_limit:10,reply_limit:10,watch:!0,...t}),this.loadNextPage=async(t={})=>{const{pagination:s}=this.state.getLatestValue();if(!(s.isLoadingNext||!s.nextCursor))try{this.state.partialNext({pagination:{...s,isLoadingNext:!0}});const i=await this.queryThreads({...t,next:s.nextCursor});this.state.next(n=>({...n,threads:i.threads.length?n.threads.concat(i.threads):n.threads,pagination:{...n.pagination,nextCursor:i.next??null,isLoadingNext:!1}}))}catch(i){this.client.logger("error",i.message),this.state.next(n=>({...n,pagination:{...n.pagination,isLoadingNext:!1}}))}},this.client=e,this.state=new U(Di),this.threadsByIdGetterCache={threads:[],threadsById:{}}}get threadsById(){const{threads:e}=this.state.getLatestValue();if(e===this.threadsByIdGetterCache.threads)return this.threadsByIdGetterCache.threadsById;const t=e.reduce((s,i)=>(s[i.id]=i,s),{});return this.threadsByIdGetterCache.threads=e,this.threadsByIdGetterCache.threadsById=t,t}},su=e=>e.type==="poll.updated",iu=e=>e.type==="poll.closed",nu=e=>e.type==="poll.vote_casted",ru=e=>e.type==="poll.vote_changed",au=e=>e.type==="poll.vote_removed",pe=e=>!!e?.answer_text,Wo=class{constructor({client:e,poll:t}){this.getInitialStateFromPollResponse=s=>{const{own_votes:i,id:n,...r}=s,{ownAnswer:a,ownVotes:o}=i?.reduce((l,c)=>(pe(c)?l.ownAnswer=c:l.ownVotes.push(c),l),{ownVotes:[]})??{ownVotes:[]};return{...r,lastActivityAt:new Date,maxVotedOptionIds:rt(r.vote_counts_by_option),ownAnswer:a,ownVotesByOptionId:ou(o)}},this.upsertOfflineDb=()=>{this.client.offlineDb?.executeQuerySafely(s=>s.upsertPoll({poll:Qo(this)}),{method:"upsertPoll"})},this.reinitializeState=s=>{this.state.partialNext(this.getInitialStateFromPollResponse(s))},this.handlePollUpdated=s=>{if(s.poll?.id&&s.poll.id!==this.id||!su(s))return;const{id:i,...n}=zo(s.poll);this.state.partialNext({...n,lastActivityAt:new Date(s.created_at)}),this.upsertOfflineDb()},this.handlePollClosed=s=>{s.poll?.id&&s.poll.id!==this.id||iu(s)&&(this.state.partialNext({is_closed:!0,lastActivityAt:new Date(s.created_at)}),this.upsertOfflineDb())},this.handleVoteCasted=s=>{if(s.poll?.id&&s.poll.id!==this.id||!nu(s))return;const i=this.data,n=s.poll_vote.user_id===this.client.userID;let r=[...i.latest_answers],a=i.ownAnswer;const o=i.ownVotesByOptionId;let l=i.maxVotedOptionIds;n&&(pe(s.poll_vote)?a=s.poll_vote:s.poll_vote.option_id&&(o[s.poll_vote.option_id]=s.poll_vote)),pe(s.poll_vote)?r=[s.poll_vote,...r]:l=rt(s.poll.vote_counts_by_option);const c=Kt(s.poll);this.state.partialNext({...c,latest_answers:r,lastActivityAt:new Date(s.created_at),ownAnswer:a,ownVotesByOptionId:o,maxVotedOptionIds:l}),this.upsertOfflineDb()},this.handleVoteChanged=s=>{if(s.poll?.id&&s.poll.id!==this.id||!ru(s))return;const i=this.data,n=s.poll_vote.user_id===this.client.userID;let r=[...i.latest_answers],a=i.ownAnswer,o=i.ownVotesByOptionId,l=i.maxVotedOptionIds;n?pe(s.poll_vote)?(r=[s.poll_vote,...r.filter(d=>d.id!==s.poll_vote.id)],a=s.poll_vote):s.poll_vote.option_id&&(s.poll.enforce_unique_vote?o={[s.poll_vote.option_id]:s.poll_vote}:(o=Object.entries(o).reduce((d,[h,f])=>(h!==s.poll_vote.option_id&&f.id===s.poll_vote.id||(d[h]=f),d),{}),o[s.poll_vote.option_id]=s.poll_vote),a?.id===s.poll_vote.id&&(a=void 0),l=rt(s.poll.vote_counts_by_option)):pe(s.poll_vote)?r=[s.poll_vote,...r]:l=rt(s.poll.vote_counts_by_option);const c=Kt(s.poll);this.state.partialNext({...c,latest_answers:r,lastActivityAt:new Date(s.created_at),ownAnswer:a,ownVotesByOptionId:o,maxVotedOptionIds:l}),this.upsertOfflineDb()},this.handleVoteRemoved=s=>{if(s.poll?.id&&s.poll.id!==this.id||!au(s))return;const i=this.data,n=s.poll_vote.user_id===this.client.userID;let r=[...i.latest_answers],a=i.ownAnswer;const o={...i.ownVotesByOptionId};let l=i.maxVotedOptionIds;pe(s.poll_vote)?(r=r.filter(d=>d.id!==s.poll_vote.id),n&&(a=void 0)):(l=rt(s.poll.vote_counts_by_option),n&&s.poll_vote.option_id&&delete o[s.poll_vote.option_id]);const c=Kt(s.poll);this.state.partialNext({...c,latest_answers:r,lastActivityAt:new Date(s.created_at),ownAnswer:a,ownVotesByOptionId:o,maxVotedOptionIds:l}),this.upsertOfflineDb()},this.query=async s=>{const{poll:i}=await this.client.getPoll(s);return this.state.partialNext({...i,lastActivityAt:new Date}),i},this.update=async s=>await this.client.updatePoll({...s,id:this.id}),this.partialUpdate=async s=>await this.client.partialUpdatePoll(this.id,s),this.close=async()=>
11await this.client.closePoll(this.id),this.delete=async()=>await this.client.deletePoll(this.id),this.createOption=async s=>await this.client.createPollOption(this.id,s),this.updateOption=async s=>await this.client.updatePollOption(this.id,s),this.deleteOption=async s=>await this.client.deletePollOption(this.id,s),this.castVote=async(s,i)=>{const{max_votes_allowed:n,ownVotesByOptionId:r}=this.data;if(n&&n===Object.keys(r).length){this.client.notifications.addInfo({message:"Reached the vote limit. Remove an existing vote first.",origin:{emitter:"Poll",context:{messageId:i,optionId:s}},options:{type:"validation:poll:castVote:limit"}});return}return await this.client.castPollVote(i,this.id,{option_id:s})},this.removeVote=async(s,i)=>await this.client.removePollVote(i,this.id,s),this.addAnswer=async(s,i)=>await this.client.addPollAnswer(i,this.id,s),this.removeAnswer=async(s,i)=>await this.client.removePollVote(i,this.id,s),this.queryAnswers=async s=>await this.client.queryPollAnswers(this.id,s.filter,s.sort,s.options),this.queryOptionVotes=async s=>await this.client.queryPollVotes(this.id,s.filter,s.sort,s.options),this.client=e,this.id=t.id,this.state=new U(this.getInitialStateFromPollResponse(t))}get data(){return this.state.getLatestValue()}};function rt(e){let t=0,s=[];for(const[i,n]of Object.entries(e??{}))n>t?(s=[i],t=n):n===t&&s.push(i);return s}function ou(e){return e?e.reduce((t,s)=>(pe(s)||!s.option_id||(t[s.option_id]=s),t),{}):{}}function zo(e){return{allow_answers:e.allow_answers,allow_user_suggested_options:e.allow_user_suggested_options,description:e.description,enforce_unique_vote:e.enforce_unique_vote,id:e.id,is_closed:e.is_closed,max_votes_allowed:e.max_votes_allowed,name:e.name,options:e.options,voting_visibility:e.voting_visibility}}function Qo(e){const{lastActivityAt:t,maxVotedOptionIds:s,ownVotesByOptionId:i,ownAnswer:n,...r}=e.data,a=[...Object.values(i),...n?[n]:[]].sort((o,l)=>Date.parse(o.created_at)-Date.parse(l.created_at));return{...r,own_votes:a,id:e.id}}function Kt(e){return{answers_count:e.answers_count,latest_votes_by_option:e.latest_votes_by_option,vote_count:e.vote_count,vote_counts_by_option:e.vote_counts_by_option}}var Go=class extends Pe{constructor({client:e}){super(),this.pollCache=new Map,this.fromState=t=>this.pollCache.get(t),this.registerSubscriptions=()=>{this.hasSubscriptions||(this.addUnsubscribeFunction(this.subscribeMessageNew()),this.addUnsubscribeFunction(this.subscribePollUpdated()),this.addUnsubscribeFunction(this.subscribePollClosed()),this.addUnsubscribeFunction(this.subscribeVoteCasted()),this.addUnsubscribeFunction(this.subscribeVoteChanged()),this.addUnsubscribeFunction(this.subscribeVoteRemoved()))},this.createPoll=async t=>{const{poll:s}=await this.client.createPoll(t);return s.vote_counts_by_option||(s.vote_counts_by_option={}),this.setOrOverwriteInCache(s),this.fromState(s.id)},this.getPoll=async t=>{const s=this.fromState(t);if(s)return this.client.getPoll(t).then(({poll:n})=>this.setOrOverwriteInCache(n,!0)),s;const{poll:i}=await this.client.getPoll(t);return this.setOrOverwriteInCache(i),this.fromState(t)},this.queryPolls=async(t,s=[],i={})=>{const{polls:n,next:r}=await this.client.queryPolls(t,s,i);return{polls:n.map(o=>(this.setOrOverwriteInCache(o,!0),this.fromState(o.id))),next:r}},this.hydratePollCache=(t,s)=>{for(const i of t){if(!i.poll)continue;const n=i.poll;this.setOrOverwriteInCache(n,s)}},this.setOrOverwriteInCache=(t,s)=>{if(!this.client._cacheEnabled())return;const i=this.fromState(t.id);if(i)s&&i.reinitializeState(t);else{const n=new Wo({client:this.client,poll:t});this.pollCache.set(n.id,n)}},this.subscribePollUpdated=()=>this.client.on("poll.updated",t=>{t.poll?.id&&this.fromState(t.poll.id)?.handlePollUpdated(t)}).unsubscribe,this.subscribePollClosed=()=>this.client.on("poll.closed",t=>{t.poll?.id&&this.fromState(t.poll.id)?.handlePollClosed(t)}).unsubscribe,this.subscribeVoteCasted=()=>this.client.on("poll.vote_casted",t=>{t.poll?.id&&this.fromState(t.poll.id)?.handleVoteCasted(t)}).unsubscribe,this.subscribeVoteChanged=()=>this.client.on("poll.vote_changed",t=>{t.poll?.id&&this.fromState(t.poll.id)?.handleVoteChanged(t)}).unsubscribe,this.subscribeVoteRemoved=()=>this.client.on("poll.vote_removed",t=>{t.poll?.id&&this.fromState(t.poll.id)?.handleVoteRemoved(t)}).unsubscribe,this.subscribeMessageNew=()=>this.client.on("message.new",t=>{const{message:s}=t;if(s){const i=B(s);this.hydratePollCache([i])}}).unsubscribe,this.client=e}get data(){return this.pollCache}},Oi={"channel.deleted":"channelDeletedHandler","channel.hidden":"channelHiddenHandler","channel.truncated":"channelTruncatedHandler","channel.updated":"channelUpdatedHandler","channel.visible":"channelVisibleHandler","message.new":"newMessageHandler","member.updated":"memberUpdatedHandler","notification.added_to_channel":"notificationAddedToChannelHandler","notification.message_new":"notificationNewMessageHandler","notification.removed_from_channel":"notificationRemovedFromChannelHandler"},Ko={abortInFlightQuery:!1,allowNotLoadedChannelPromotionForEvent:{"channel.visible":!0,"message.new":!0,"notification.added_to_channel":!0,"notification.message_new":!0},lockChannelOrder:!1},Jt={limit:10,offset:0},Jo=class extends Pe{constructor({client:e,eventHandlerOverrides:t={},options:s={},queryChannelsOverride:i}){super(),this.eventHandlers=new Map,this.eventHandlerOverrides=new Map,this.options={},this.stateOptions={},this.setChannels=n=>{this.state.next(l=>{const{channels:c}=l,d=pn(n)?n(c):n;return c===d?l:{...l,channels:d}});const{channels:r,pagination:{filters:a,sort:o}}=this.state.getLatestValue();this.client.offlineDb?.executeQuerySafely(l=>l.upsertCidsForQuery({cids:r.map(c=>c.cid),filters:a,sort:o}),{method:"upsertCidsForQuery"})},this.setEventHandlerOverrides=(n={})=>{const r=Object.entries(n).reduce((a,[o,l])=>(l&&(a[o]=l),a),{});this.eventHandlerOverrides=new Map(Object.entries(r))},this.setQueryChannelsRequest=n=>{this.queryChannelsRequest=n},this.setOptions=(n={})=>{this.options={...Ko,...n}},this.executeChannelsQuery=async(n,r=0)=>{const{filters:a,sort:o,options:l,stateOptions:c}=n,{offset:d,limit:h}={...Jt,...l};try{const f=await this.queryChannelsRequest(a,o,l,c),p=d+(f?.length??0),y={...l,offset:p},{pagination:w}=this.state.getLatestValue();this.state.partialNext({channels:f,pagination:{...w,hasNext:(f?.length??0)>=h,isLoading:!1,options:y},initialized:!0,error:void 0}),this.client.offlineDb?.executeQuerySafely(m=>m.upsertCidsForQuery({cids:f.map(g=>g.cid),filters:w.filters,sort:w.sort}),{method:"upsertCidsForQuery"})}catch(f){if(r>=jd){console.warn(f);const p=new Error(`Maximum number of retries reached in queryChannels. Last error message is: ${f}`),y=this.state.getLatestValue(),w=this.client.offlineDb&&y.channels.length>0;this.state.partialNext({error:w?void 0:p,pagination:{...y.pagination,isLoading:!1,isLoadingNext:!1}});return}return await ye(Wd),this.executeChannelsQuery(n,r+1)}},this.queryChannels=async(n,r=[],a={},o={})=>{const{pagination:{isLoading:l,filters:c},initialized:d}=this.state.getLatestValue();if(l&&!this.options.abortInFlightQuery&&JSON.stringify(c)===JSON.stringify(n))return;const h={filters:n,sort:r,options:a,stateOptions:o};try{if(this.stateOptions=o,this.state.next(f=>({...f,pagination:{...f.pagination,isLoading:!0,isLoadingNext:!1,filters:n,sort:r,options:a},error:void 0})),this.client.offlineDb?.getChannelsForQuery&&this.client.user?.id){if(!d){const f=await this.client.offlineDb.getChannelsForQuery({userId:this.client.user.id,filters:n,sort:r});if(f){const p=this.client.hydrateActiveChannels(f,{offlineMode:!0,skipInitialization:[]});this.state.partialNext({channels:p})}}if(!this.client.offlineDb.syncManager.syncStatus){this.client.offlineDb.syncManager.scheduleSyncStatusChangeCallback(this.id,async()=>{await this.executeChannelsQuery(h)});return}}await this.executeChannelsQuery(h)}catch(f){throw this.client.logger("error",f.message),this.state.next(p=>({...p,pagination:{...p.pagination,isLoading:!1}})),f}},this.loadNext=async()=>{const{pagination:n,initialized:r}=this.state.getLatestValue(),{filters:a,sort:o,options:l,isLoadingNext:c,hasNext:d}=n;
11if(!(!r||c||!d))try{const{offset:h,limit:f}={...Jt,...l};this.state.partialNext({pagination:{...n,isLoading:!1,isLoadingNext:!0}});const p=await this.queryChannelsRequest(a,o,l,this.stateOptions),{channels:y}=this.state.getLatestValue(),w=h+(p?.length??0),m={...l,offset:w};this.state.partialNext({channels:lh([...y||[],...p],"cid"),pagination:{...n,hasNext:(p?.length??0)>=f,isLoading:!1,isLoadingNext:!1,options:m}})}catch(h){throw this.client.logger("error",h.message),this.state.next(f=>({...f,pagination:{...f.pagination,isLoadingNext:!1,isLoading:!1}})),h}},this.notificationAddedToChannelHandler=async n=>{const{id:r,type:a,members:o}=n?.channel??{};if(!a||!this.options.allowNotLoadedChannelPromotionForEvent?.["notification.added_to_channel"])return;const l=await ti({client:this.client,id:r,members:o?.reduce((f,{user:p,user_id:y})=>{const w=y||p?.id;return w&&f.push(w),f},[]),type:a}),{pagination:c,channels:d}=this.state.getLatestValue();if(!d)return;const{sort:h}=c??{};this.setChannels(ot({channels:d,channelToMove:l,sort:h}))},this.channelDeletedHandler=n=>{const{channels:r}=this.state.getLatestValue();if(!r)return;const a=[...r],o=a.findIndex(l=>l.cid===(n.cid||n.channel?.cid));o<0||(a.splice(o,1),this.setChannels(a))},this.channelHiddenHandler=this.channelDeletedHandler,this.newMessageHandler=n=>{const{pagination:r,channels:a}=this.state.getLatestValue();if(!a)return;const{filters:o,sort:l}=r??{},c=n.channel_type,d=n.channel_id;if(!c||!d)return;const h=this.client.channel(c,d),f=a.indexOf(h),p=f>=0,y=Ts(h),w=kt(h),m=Nt(o),g=bi(l);m&&w&&!o.archived||m&&!w&&o.archived||g&&y||this.options.lockChannelOrder||!p&&!this.options.allowNotLoadedChannelPromotionForEvent?.["message.new"]||this.setChannels(ot
11({channels:a,channelToMove:h,channelToMoveIndexWithinChannels:f,sort:l}))},this.notificationNewMessageHandler=async n=>{const{id:r,type:a}=n?.channel??{};if(!r||!a)return;const o=await ti({client:this.client,id:r,type:a}),{channels:l,pagination:c}=this.state.getLatestValue(),{filters:d,sort:h}=c??{},f=Nt(d),p=kt(o);!l||f&&p&&!d.archived||f&&!p&&d.archived||!this.options.allowNotLoadedChannelPromotionForEvent?.["notification.message_new"]||this.setChannels(ot({channels:l,channelToMove:o,sort:h}))},this.channelVisibleHandler=async n=>{const{channel_type:r,channel_id:a}=n;if(!r||!a)return;const o=await ti({client:this.client,id:n.channel_id,type:n.channel_type}),{channels:l,pagination:c}=this.state.getLatestValue(),{sort:d,filters:h}=c??{},f=Nt(h),p=kt(o);!l||f&&p&&!h.archived||f&&!p&&h.archived||!this.options.allowNotLoadedChannelPromotionForEvent?.["channel.visible"]||this.setChannels(ot({channels:l,channelToMove:o,sort:d}))},this.notificationRemovedFromChannelHandler=this.channelDeletedHandler,this.memberUpdatedHandler=n=>{const{pagination:r,channels:a}=this.state.getLatestValue(),{filters:o,sort:l}=r;if(!n.member?.user||n.member.user.id!==this.client.userID||!n.channel_type||!n.channel_id)return;const c=n.channel_type,d=n.channel_id,h=bi(l),f=Nt(o),p=ca({atIndex:0,sort:l,targetKey:"pinned_at"});if(!a||!h&&!f||this.options.lockChannelOrder)return;const y=this.client.channel(c,d),w=a.indexOf(y),m=w>=0,g=Ts(y),_=kt(y),b=[...a];if(m&&b.splice(w,1),f&&!_&&o?.archived||f&&_&&!o?.archived){this.setChannels(b);return}let R=null;(p===1||p===-1&&!g)&&(R=da({channels:b}));const v=typeof R=="number"?R+1:0;a[v]!==y&&(b.splice(v,0,y),this.setChannels(b))},this.subscriptionOrOverride=n=>{const r=Oi[n.type],a=this.eventHandlers.get(r),o=this.eventHandlerOverrides.get(r);if(o&&typeof o=="function"){o(this.setChannels,n);return}a&&typeof a=="function"&&a(n)},this.registerSubscriptions=()=>{if(!this.hasSubscriptions)for(const n of Object.keys(Oi))this.addUnsubscribeFunction(this.client.on(n,this.subscriptionOrOverride).unsubscribe)},this.id=`channel-manager-${W()}`,this.client=e,this.state=new U({channels:[],pagination:{isLoading:!1,isLoadingNext:!1,hasNext:!1,filters:{},sort:{},options:Jt},initialized:!1,error:void 0}),this.setEventHandlerOverrides(t),this.setOptions(s),this.queryChannelsRequest=i??((...n)=>this.client.queryChannels(...n)),this.eventHandlers=new Map(Object.entries({channelDeletedHandler:this.channelDeletedHandler,channelHiddenHandler:this.channelHiddenHandler,channelVisibleHandler:this.channelVisibleHandler,memberUpdatedHandler:this.memberUpdatedHandler,newMessageHandler:this.newMessageHandler,notificationAddedToChannelHandler:this.notificationAddedToChannelHandler,notificationNewMessageHandler:this.notificationNewMessageHandler,notificationRemovedFromChannelHandler:this.notificationRemovedFromChannelHandler}))}},qt=3e3,lu={durations:{error:qt,info:qt,success:qt,warning:qt}},Xo=class{constructor(e={}){this.timeouts=new Map,this.store=new U({notifications:[]}),this.config=Ve(lu,e)}get notifications(){return this.store.getLatestValue().notifications}get warning(){return this.notifications.filter(e=>e.severity==="warning")}get error(){return this.notifications.filter(e=>e.severity==="error")}get info(){return this.notifications.filter(e=>e.severity==="info")}get success(){return this.notifications.filter(e=>e.severity==="success")}add({message:e,origin:t,options:s={}}){const i=W(),n=Date.now(),r=s.severity||"info",a=s.duration??this.config.durations[r],o={id:i,message:e,origin:t,type:s?.type,severity:r,createdAt:n,expiresAt:n+a,actions:s.actions,metadata:s.metadata,originalError:s.originalError};if(this.store.partialNext({notifications:[...this.store.getLatestValue().notifications,o]}),o.expiresAt){const l=setTimeout(()=>{this.remove(i)},s.duration||this.config.durations[o.severity]);this.timeouts.set(i,l)}return i}addError({message:e,origin:t,options:s}){return this.add({message:e,origin:t,options:{...s,severity:"error"}})}addWarning({message:e,origin:t,options:s}){return this.add({message:e,origin:t,options:{...s,severity:"warning"}})}addInfo({message:e,origin:t,options:s}){return this.add({message:e,origin:t,options:{...s,severity:"info"}})}addSuccess({message:e,origin:t,options:s}){return this.add({message:e,origin:t,options:{...s,severity:"success"}})}remove(e){const t=this.timeouts.get(e);t&&(clearTimeout(t),this.timeouts.delete(e)),this.store.partialNext({notifications:this.store.getLatestValue().notifications.filter(s=>s.id!==e)})}
11clear(){this.timeouts.forEach(e=>clearTimeout(e)),this.timeouts.clear(),this.store.partialNext({notifications:[]})}},Ds=60*1e3,Cn=60*Ds,Sn=24*Cn,cu=7*Sn,ii={minute:{lower:Ds,upper:Cn},hour:{upper:Sn}},vn=2*cu,Yo=class{constructor({reminder:e,config:t}){this.timeout=null,this.stopRefreshBoundaryMs=vn,this.getRefreshIntervalLength=()=>{if(!this.reminder.remindAt)return null;const s=Math.abs(vt(this.reminder.remindAt.getTime()));let i;return s===0?i=Ds:s<ii.minute.lower?i=s:s<=ii.minute.upper?i=Ds:s<=ii.hour.upper?i=Cn:i=Sn,i},this.init=()=>{if(!this.reminder.remindAt)return null;const s=this.getRefreshIntervalLength();if(s===null)return null;if(this.reminder.remindAt?.getTime()+this.stopRefreshBoundaryMs-Date.now()<=0){this.timeout=null;return}this.timeout&&clearTimeout(this.timeout),this.timeout=setTimeout(()=>{this.reminder.refreshTimeLeft(),this.init()},s)},this.clear=()=>{this.timeout&&(clearInterval(this.timeout),this.timeout=null)},this.reminder=e,typeof t?.stopRefreshBoundaryMs=="number"&&(this.stopRefreshBoundaryMs=t.stopRefreshBoundaryMs)}},vt=e=>e-new Date().getTime(),Zo=class Pi{constructor({data:t,config:s}){this.setState=i=>{this.state.next(n=>{const r={...n,...Pi.toStateValue(i)};return r.remind_at&&(r.timeLeftMs=vt(r.remind_at.getTime())),r}),i.remind_at?this.initTimer():i.remind_at||this.clearTimer()},this.refreshTimeLeft=()=>{this.remindAt&&this.state.partialNext({timeLeftMs:vt(this.remindAt.getTime())})},this.initTimer=()=>{this.timer.init()},this.clearTimer=()=>{this.timer.clear()},this.state=new U(Pi.toStateValue(t)),this.timer=new Yo({reminder:this,config:s}),this.initTimer()}get id(){return this.state.getLatestValue().message_id}get remindAt(){return this.state.getLatestValue().remind_at}get timeLeftMs(){return this.state.getLatestValue().timeLeftMs}};Zo.toStateValue=e=>({...e,created_at:new Date(e.created_at),message:e.message||null,remind_at:e.remind_at?new Date(e.remind_at):null,timeLeftMs:e.remind_at?vt(new Date(e.remind_at).getTime()):null,updated_at:new Date(e.updated_at),user:e.user||null});var el=Zo,ki=60*1e3,Xt=60*ki,du=24*Xt,Ni={scheduledOffsetsMs:[2*ki,30*ki,Xt,2*Xt,8*Xt,du],stopTimerRefreshBoundaryMs:vn},hu=e=>e.message.match("already has reminder created for this message_id"),uu=e=>e.message.match("reminder does not exist"),tl=class Yt extends Pe{constructor({client:t,config:s}){super(),this.upsertToState=({data:i,overwrite:n=!0})=>{if(!this.client._cacheEnabled())return;const r=this.getFromState(i.message_id);if(r)n&&r.setState(i);else{const a=new el({data:i,config:{stopRefreshBoundaryMs:this.stopTimerRefreshBoundaryMs}});this.state.partialNext({reminders:new Map(this.reminders.set(i.message_id,a))})}return r},this.removeFromState=i=>{const n=this.getFromState(i);if(!n)return;n.clearTimer();const r=this.reminders;r.delete(i),this.state.partialNext({reminders:new Map(r)})},this.hydrateState=i=>{i.forEach(({reminder:n})=>{n&&this.upsertToState({data:n})})},this.initTimers=()=>{this.reminders.forEach(i=>i.initTimer())},this.clearTimers=()=>{this.reminders.forEach(i=>i.clearTimer())},this.registerSubscriptions=()=>{this.hasSubscriptions||(this.addUnsubscribeFunction(this.subscribeReminderCreated()),this.addUnsubscribeFunction(this.subscribeReminderUpdated()),this.addUnsubscribeFunction(this.subscribeReminderDeleted()),this.addUnsubscribeFunction(this.subscribeNotificationReminderDue()),this.addUnsubscribeFunction(this.subscribeMessageDeleted()),this.addUnsubscribeFunction(this.subscribeMessageUndeleted()),this.addUnsubscribeFunction(this.subscribePaginatorStateUpdated()),this.addUnsubscribeFunction(this.subscribeConfigStateUpdated()))},this.subscribeReminderCreated=()=>this.client.on("reminder.created",i=>{if(!Yt.isReminderWsEventPayload(i))return;const{reminder:n}=i;this.upsertToState({data:n})}).unsubscribe,this.subscribeReminderUpdated=()=>this.client.on("reminder.updated",i=>{if(!Yt.isReminderWsEventPayload(i))return;const{reminder:n}=i;this.upsertToState({data:n})}).unsubscribe,this.subscribeReminderDeleted=()=>this.client.on("reminder.deleted",i=>{Yt.isReminderWsEventPayload(i)&&this.removeFromState(i.message_id)}).unsubscribe,this.subscribeMessageDeleted=()=>this.client.on("message.deleted",i=>{i.message?.id&&this.removeFromState(i.message.id)}).unsubscribe,this.subscribeMessageUndeleted=()=>this.client.on("message.undeleted",i=>{i.message?.reminder&&this.upsertToState({data:i.message.reminder})}).unsubscribe,this.subscribeNotificationReminderDue=()=>this.client.on("notification.reminder_due",()=>null).unsubscribe,this.subscribePaginatorStateUpdated=()=>this.paginator.state.subscribeWithSelector(({items:i})=>[i],([i])=>{if(i)for(const n of i)this.upsertToState({data:n})}),this.subscribeConfigStateUpdated=()=>this.configState.subscribeWithSelector(({stopTimerRefreshBoundaryMs:i})=>({stopTimerRefreshBoundaryMs:i}),({stopTimerRefreshBoundaryMs:i},n)=>{typeof i=="number"&&i!==n?.stopTimerRefreshBoundaryMs&&this.reminders.forEac
11h(r=>{r.timer&&(r.timer.stopRefreshBoundaryMs=i)})}),this.upsertReminder=async i=>{const{messageId:n}=i;if(this.getFromState(n))try{return await this.updateReminder(i)}catch(r){if(uu(r))return await this.createReminder(i);throw r}else try{return await this.createReminder(i)}catch(r){if(hu(r))return await this.updateReminder(i);throw r}},this.createReminder=async i=>{const{reminder:n}=await this.client.createReminder(i);return this.upsertToState({data:n,overwrite:!1})},this.updateReminder=async i=>{const{reminder:n}=await this.client.updateReminder(i);return this.upsertToState({data:n})},this.deleteReminder=async i=>{await this.client.deleteReminder(i),this.removeFromState(i)},this.queryNextReminders=async()=>{await this.paginator.next()},this.queryPreviousReminders=async()=>{await this.paginator.prev()},this.client=t,this.configState=new U({scheduledOffsetsMs:s?.scheduledOffsetsMs??Ni.scheduledOffsetsMs,stopTimerRefreshBoundaryMs:s?.stopTimerRefreshBoundaryMs??Ni.stopTimerRefreshBoundaryMs}),this.state=new U({reminders:new Map}),this.paginator=new wo(t)}updateConfig(t){typeof t.stopTimerRefreshBoundaryMs=="number"&&t.stopTimerRefreshBoundaryMs!==this.stopTimerRefreshBoundaryMs&&this.reminders.forEach(s=>{s.timer.stopRefreshBoundaryMs=t?.stopTimerRefreshBoundaryMs}),this.configState.partialNext(t)}get stopTimerRefreshBoundaryMs(){return this.configState.getLatestValue().stopTimerRefreshBoundaryMs}get scheduledOffsetsMs(){return this.configState.getLatestValue().scheduledOffsetsMs}get reminders(){return this.state.getLatestValue().reminders}getFromState(t){return this.reminders.get(t)}};tl.isReminderWsEventPayload=e=>!!e.reminder&&(e.type.startsWith("reminder.")||e.type==="notification.reminder_due");var sl=tl;function ni(e){return typeof e=="string"||e instanceof String}var fu=class Ee{constructor(t,s,i){this.nextRequestAbortController=null,this._messageComposerSetupState=new U({setupFunction:null}),this._getConnectionID=()=>this.wsConnection?.connectionID||this.wsFallback?.connectionID,this._hasConnectionID=()=>!!this._getConnectionID(),this.setMessageComposerSetupFunction=r=>{this._messageComposerSetupState.partialNext({setupFunction:r})},this.connectUser=async(r,a)=>{if(!r.id)throw new Error('The "id" field on the user is missing');if(this.userID===r.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._isUsingServerAuth()||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=r.id,this.anonymous=!1;const o=this._setToken(r,a);this._setUser(r);const l=this.openConnection();this.setUserPromise=Promise.all([o,l]).then(c=>c[1]);try{return await this.setUserPromise}catch(c){throw this.persistUserOnConnectionFailure?this.closeConnection():this.disconnectUser(),c}},this.setUser=this.connectUser,this._setToken=(r,a)=>this.tokenManager.setTokenOrProvider(a,r),this.closeConnection=async r=>(this.cleaningIntervalRef!=null&&(clearInterval(this.cleaningIntervalRef),this.cleaningIntervalRef=void 0),await Promise.all([this.wsConnection?.disconnect(r),this.wsFallback?.disconnect(r)]),this.offlineDb?.executeQuerySafely(async a=>{this.userID&&await a.upsertUserSyncStatus({userId:this.userID,lastSyncedAt:new Date().toString()})},{method:"upsertUserSyncStatus"}),Promise.resolve()),this.createChannelManager=({eventHandlerOverrides:r={},options:a={},queryChannelsOverride:o})=>new Jo({client:this,eventHandlerOverrides:r,options:a,queryChannelsOverride:o}),this.openConnection=()=>{if(!this.userID)throw Error("User is not set on client, use client.connectUser or client.connectAnonymousUser instead");if(this.wsConnection?.isConnecting&&this.wsPromise)return this.logger("info","client:openConnection() - connection already in progress",{tags:["connection","client"]}),this.wsPromise;if((this.wsConnection?.isHealthy||this.wsFallback?.isHealthy())&&this._hasConnectionID()){this.logger("info","client:openConnection() - openConnection called twice, healthy connection already exists",{tags:["connection","client"]});return}return this.clientID=`${this.userID}--${$e()}`,this.wsPromise=this.connect(),this._startCleaning(),this.wsPromise},this._setupConnection=this.openConnection,this._normalizeDate=r=>{if(r instanceof Date&&(r=r.toISOString()),r==="")throw new Error("Don't pass blank string for since, use null instead if resetting the token revoke");return r},this.disconnectUser=r=>{this.logger("info","client:disconnect() - Disconnecting the client",{tags:["connection","client"]}),delete this.user,delete this._user,delete this.userID,this.anonymous=!1;const a=this.closeConnection(r);for(const o of Object.values(this.activeChannels))o._disconnect();return this.activeChannels={},this.state=new Ti({client:this}),this.threads.resetState(),a.finally(()=>{this.tokenManager.reset()}).catch(o=>console.error(o)),a},this.disconnect=this.disconnectUser,this.connectAnonymousUser=()=>{(this._isUsingServerAuth()||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.anonymous=!0,this.userID=$e();const r={id:this.userID,anon:!0};return this._setToken(r,""),this._setUser(r),this._setupConnection()},this.setAnonymousUser=this.connectAnonymousUser,this.doAxiosRequest=async(r,a,o,l={})=>{await this.tokenManager.tokenReady();const c=this._enrichAxiosOptions(l);try{let d;switch(this._logApiRequest(r,a,o,c),r){case"get":d=await this.axiosInstance.get(a,c);break;case"delete":d=await this.axiosInstance.delete(a,c);break;case"post":d=await this.axiosInstance.post(a,o,c);break;case"postForm":d=await this.axiosInstance.postForm(a,o,c);break;
11case"put":d=await this.axiosInstance.put(a,o,c);break;case"patch":d=await this.axiosInstance.patch(a,o,c);break;case"options":d=await this.axiosInstance.options(a,c);break;default:throw new Error("Invalid request type")}return this._logApiResponse(r,a,d),this.consecutiveFailures=0,this.handleResponse(d)}catch(d){if(d.client_request_id=c.headers?.["x-client-request-id"],this._logApiError(r,a,d),this.consecutiveFailures+=1,d.response)return d.response.data.code===qe.TOKEN_EXPIRED&&!this.tokenManager.isStatic()?(this.consecutiveFailures>1&&await ye(Us(this.consecutiveFailures)),this.tokenManager.loadToken(),await this.doAxiosRequest(r,a,o,l)):this.handleResponse(d.response);throw d}},this.dispatchEvent=r=>{r.received_at||(r.received_at=new Date);const a=this._handleClientEvent(r),o=r.cid,l=o?this.activeChannels[o]:void 0;l&&l._handleChannelEvent(r),this._callClientListeners(r),l&&l._callChannelListeners(r),a.forEach(c=>c()),this.offlineDb?.executeQuerySafely(c=>c.handleEvent({event:r}),{method:`handleEvent;${r.type}`})},this.handleEvent=r=>{const a=r.data,o=JSON.parse(a);this.dispatchEvent(o)},this._updateMemberWatcherReferences=r=>{const a=this.state.userChannelReferences[r.id]||{};for(const o in a){const l=this.activeChannels[o];l?.state&&(l.state.members[r.id]&&(l.state.members[r.id].user=r),l.state.watchers[r.id]&&(l.state.watchers[r.id]=r),l.state.read[r.id]&&(l.state.read[r.id].user=r))}},this._updateUserReferences=this._updateMemberWatcherReferences,this._updateUserMessageReferences=r=>{const a=this.state.userChannelReferences[r.id]||{};for(const o in a){const l=this.activeChannels[o];if(!l)continue;l.state?.updateUserMessages(r)}},this._deleteUserMessageReference=(r,a=!1,o)=>{const l=this.state.userChannelReferences[r.id]||{};for(const c in l){const d=this.activeChannels[c];d&&d.state?.deleteUserMessages(r,a,o)}},this._handleUserEvent=r=>{if(r.user){if(r.type==="user.presence.changed"||r.type==="user.updated"){if(r.user.id===this.userID){const a={...this.user},o={...this._user};for(const l in this.user){if(l in r.user||Jd(l))continue;const c=l;delete a[c],delete o[c]}for(const l in o){const c=l;c in r.user&&(o[c]=r.user[c])}this._user=o,this.user={...a,...r.user}}this.state.updateUser(r.user),this._updateMemberWatcherReferences(r.user)}r.type==="user.updated"&&this._updateUserMessageReferences(r.user),r.type==="user.deleted"&&r.user.deleted_at&&(r.mark_messages_deleted||r.hard_delete)&&this._deleteUserMessageReference(r.user,r.hard_delete,r.user.deleted_at?new Date(r.user.deleted_at):null)}},this._callClientListeners=r=>{const a=this,o=[];a.listeners.all&&o.push(...a.listeners.all),a.listeners[r.type]&&o.push(...a.listeners[r.type]);for(const l of o)l(r)},this.recoverState=async()=>{this.logger("info",`client:recoverState() - Start of recoverState with connectionID ${this._getConnectionID()}`,{tags:["connection"]});const r=Object.keys(this.activeChannels);r.length&&this.recoverStateOnReconnect?(this.logger("info",`client:recoverState() - Start the querying of ${r.length} channels`,{tags:["connection","client"]}),await this.queryChannels({cid:{$in:r}},{last_message_at:-1},{limit:30}),this.logger("info","client:recoverState() - Querying channels finished",{tags:["connection","client"]}),this.dispatchEvent({type:"connection.recovered"})):this.dispatchEvent({type:"connection.recovered"}),this.wsPromise=Promise.resolve(),this.setUserPromise=Promise.resolve()},this.getChannelByMembers=(r,a)=>{const o=(a.members??[]).map(h=>typeof h=="string"?h:h.user_id??""),l=o.sort().join(","),c=rn(r,o);if(!c)throw Error("Please specify atleast one member when creating unique conversation");for(const h in this.activeChannels){const f=this.activeChannels[h];if(!f.disconnected&&(h===c||h.indexOf(`${r}:!members-`)===0&&Object.keys(f.state.members).sort().join(",")===l))return f}const d=new _e(this,r,void 0,a);return this._cacheEnabled()&&(this.activeChannels[c]=d),d},this.getChannelById=(r,a,o)=>
11{if(typeof a=="string"&&~a.indexOf(":"))throw Error(`Invalid channel id ${a}, can't contain the : character`);const l=`${r}:${a}`;if(l in this.activeChannels&&this.activeChannels[l]&&!this.activeChannels[l].disconnected){const d=this.activeChannels[l];return Object.keys(o).length>0&&(d.data={...d.data,...o},d._data={...d._data,...o}),d}const c=new _e(this,r,a,o);return this._cacheEnabled()&&(this.activeChannels[c.cid]=c),c},this.updateUsers=this.upsertUsers,this.updateUser=this.upsertUser,this._unblockMessage=this.unblockMessage,this.markAllRead=this.markChannelsRead,this._isUsingServerAuth=()=>!!this.secret,this._cacheEnabled=()=>!this._isUsingServerAuth()||!this.options.disableCache,this._buildWSPayload=r=>JSON.stringify({user_id:this.userID,user_details:this._user,device:this.options.device,client_request_id:r}),this.key=t,this.listeners={},this.state=new Ti({client:this}),this.mutedChannels=[],this.mutedUsers=[],this.moderation=new Vo(this),this.notifications=i?.notifications??new Xo,s&&ni(s)&&(this.secret=s);const n=i||(s&&!ni(s)?s:{});this.browser=typeof n.browser<"u"?n.browser:typeof window<"u",this.node=!this.browser,this.options={timeout:3e3,withCredentials:!1,warmUp:!1,recoverStateOnReconnect:!0,disableCache:!1,wsUrlParams:new URLSearchParams({}),...n},this.node&&!this.options.httpsAgent&&(this.options.httpsAgent=new kd.default.Agent({keepAlive:!0,keepAliveMsecs:3e3})),this.axiosInstance=T.create(this.options),this.setBaseURL(this.options.baseURL||"https://chat.stream-io-api.com"),typeof process<"u"&&"env"in process&&Zs.STREAM_LOCAL_TEST_RUN&&this.setBaseURL("http://localhost:3030"),typeof process<"u"&&"env"in process&&Zs.STREAM_LOCAL_TEST_HOST&&this.setBaseURL("http://"+Zs.STREAM_LOCAL_TEST_HOST),this.wsConnection=null,this.wsPromise=null,this.setUserPromise=null,this.activeChannels={},this.configs={},this.anonymous=!1,this.persistUserOnConnectionFailure=this.options?.persistUserOnConnectionFailure,this.tokenManager=new Ho(this.secret),this.consecutiveFailures=0,this.insightMetrics=new Oo,this.defaultWSTimeoutWithFallback=6*1e3,this.defaultWSTimeout=15*1e3,this.axiosInstance.defaults.paramsSerializer=ih,this.logger=wi(n.logger)?n.logger:()=>null,this.recoverStateOnReconnect=this.options.recoverStateOnReconnect,this.threads=new jo({client:this}),this.polls=new Go({client:this}),this.reminders=new sl({client:this}),this.messageDeliveryReporter=new Lo({client:this})}static getInstance(t,s,i){return Ee._instance||(typeof s=="string"?Ee._instance=new Ee(t,s,i):Ee._instance=new Ee(t,s)),Ee._instance}setOfflineDBApi(t){this.offlineDb||(this.offlineDb=t)}devToken(t){return qo(t)}getAuthType(){return this.anonymous?"anonymous":"jwt"}setBaseURL(t){this.baseURL=t,this.wsBaseURL=this.baseURL.replace("http","ws").replace(":3030",":8800")}_setUser(t){this.user=t,this.userID=t.id,this._user={...t}}async updateAppSettings(t){const s=t.apn_config;return s?.p12_cert&&(t={...t,apn_config:{...s,p12_cert:Buffer.from(s.p12_cert).toString("base64")}}),await this.patch(this.baseURL+"/app",t)}async revokeTokens(t){return await this.updateAppSettings({revoke_tokens_issued_before:this._normalizeDate(t)})}async revokeUserToken(t,s){return await this.revokeUsersToken([t],s)}async revokeUsersToken(t,s){s===void 0?s=new Date().toISOString():s=this._normalizeDate(s);const i=[];for(const n of t)i.push({id:n,set:{revoke_tokens_issued_before:s}});return await this.partialUpdateUsers(i)}async getAppSettings(){return this.appSettingsPromise=this.get(this.baseURL+"/app"),await this.appSettingsPromise}async testPushSettings(t,s={}){return await this.post(this.baseURL+"/check_push",{user_id:t,...s.messageID?{message_id:s.messageID}:{},...s.apnTemplate?{apn_template:s.apnTemplate}:{},...s.firebaseTemplate?{firebase_template:s.firebaseTemplate}:{},...s.firebaseDataTemplate?{firebase_data_template:s.firebaseDataTemplate}:{},...s.skipDevices?{skip_devices:!0}:{},...s.pushProviderName?{push_provider_name:s.pushProviderName}:{},...s.pushProviderType?{push_provider_type:s.pushProviderType}:{}})}async testSQSSettings(t={}){return await this.post(this.baseURL+"/check_sqs",t)}async testSNSSettings(t={}){return await this.post(this.baseURL+"/check_sns",t)}async setGuestUser(t){let s;this.anonymous=!0;
11try{s=await this.post(this.baseURL+"/guest",{user:t})}catch(l){throw this.anonymous=!1,l}this.anonymous=!1;const{created_at:i,updated_at:n,last_active:r,online:a,...o}=s.user;return await this.connectUser(o,s.access_token)}createToken(t,s,i){if(this.secret==null)throw Error("tokens can only be created server-side using the API Secret");const n={};return s&&(n.exp=s),i&&(n.iat=i),bn(this.secret,t,n,{})}on(t,s){const i=s?t:"all",n=s||t;return i in this.listeners||(this.listeners[i]=[]),this.logger("info",`Attaching listener for ${i} event`,{tags:["event","client"]}),this.listeners[i].push(n),{unsubscribe:()=>{this.logger("info",`Removing listener for ${i} event`,{tags:["event","client"]}),this.listeners[i]=this.listeners[i].filter(r=>r!==n)}}}off(t,s){const i=s?t:"all",n=s||t;i in this.listeners||(this.listeners[i]=[]),this.logger("info",`Removing listener for ${i} event`,{tags:["event","client"]}),this.listeners[i]=this.listeners[i].filter(r=>r!==n)}_logApiRequest(t,s,i,n){this.logger("info",`client: ${t} - Request - ${s}`,{tags:["api","api_request","client"],url:s,payload:i,config:n})}_logApiResponse(t,s,i){this.logger("info",`client:${t} - Response - url: ${s} > status ${i.status}`,{tags:["api","api_response","client"],url:s,response:i})}_logApiError(t,s,i){this.logger("error",`client:${t} - Error - url: ${s}`,{tags:["api","api_response","client"],url:s,error:i})}get(t,s){return this.doAxiosRequest("get",t,null,{params:s})}put(t,s){return this.doAxiosRequest("put",t,s)}post(t,s){return this.doAxiosRequest("post",t,s)}patch(t,s){return this.doAxiosRequest("patch",t,s)}delete(t,s){return this.doAxiosRequest("delete",t,null,{params:s})}sendFile(t,s,i,n,r){const a=Xd(s,i,n||"multipart/form-data");return r!=null&&a.append("user",JSON.stringify(r)),this.doAxiosRequest("postForm",t,a,{headers:a.getHeaders?a.getHeaders():{},config:{timeout:0,maxContentLength:1/0,maxBodyLength:1/0}})}errorFromResponse(t){const s=typeof t.data.code<"u"?`StreamChat error code ${t.data.code}: ${t.data.message}`:`StreamChat error HTTP code: ${t.status}`;return new Ga(s,{code:t.data.code??null,response:t,status:t.status})}handleResponse(t){const s=t.data;if(kh(t))throw this.errorFromResponse(t);return s}_handleClientEvent(t){const s=this,i=[];if(this.logger("info",`client:_handleClientEvent - Received event of type { ${t.type} }`,{tags:["event","client"],event:t}),(t.type==="user.presence.changed"||t.type==="user.updated"||t.type==="user.deleted")&&this._handleUserEvent(t),t.type==="user.messages.deleted"&&!t.cid&&t.user&&this._deleteUserMessageReference(t.user,t.hard_delete,t.created_at?new Date(t.created_at):null),t.type==="health.check"&&t.me&&(s.user=t.me,s.state.updateUser(t.me),s.mutedChannels=t.me.channel_mutes,s.mutedUsers=t.me.mutes),t.channel&&t.type==="notification.message_new"){const{channel:n}=t;this._addChannelConfig(n)}if(t.type==="notification.channel_mutes_updated"&&t.me?.channel_mutes&&(this.mutedChannels=t.me.channel_mutes),t.type==="notification.mutes_updated"&&t.me?.mutes&&(this.mutedUsers=t.me.mutes),t.type==="notification.mark_read"&&t.unread_channels===0&&Object.keys(this.activeChannels).forEach(r=>this.activeChannels[r].state.unreadCount=0),(t.type==="channel.deleted"||t.type==="notification.channel_deleted")&&t.cid){const{cid:n}=t;s.state.deleteAllChannelReference(n),this.activeChannels[t.cid]?._disconnect(),i.push(()=>{n&&delete this.activeChannels[n]})}return i}_muteStatus(t){let s;for(let i=0;i<this.mutedChannels.length;i++){const n=this.mutedChannels[i];if(n.channel?.cid===t){s={muted:n.expires?new Date(n.expires).getTime()>new Date().getTime():!0,createdAt:n.created_at?new Date(n.created_at):new Date,expiresAt:n.expires?new Date(n.expires):null};break}}return s||{muted:!1,createdAt:null,expiresAt:null}}async connect(){if(!this.userID||!this._user)throw Error("Call connectUser or connectAnonymousUser before starting the connection");if(!this.wsBaseURL)throw Error("Websocket base url not set");if(!this.clientID)throw Error("clientID is not set");!this.wsConnection&&(this.options.warmUp||this.options.enableInsights)&&this._sayHi(),this.options.wsConnection&&this.node?(this.options.wsConnection.setClient(this),this.wsConnection=this.options.wsConnection):this.wsConnection=new Fo({client:this});try{return this.wsFallback?await this.wsFallback.connect():await this.wsConnection.connect(this.options.enableWSFallback?this.defaultWSTimeoutWithFallback:this.defaultWSTimeout)}catch(t){if(this.options.enableWSFallback&&Ph(t)&&sh())return this.logger("info","client:connect() - WS failed, fallback to longpoll",{tags:["connection","client"]}),this.dispatchEvent({type:"transport.changed",mode:"longpoll"}),this.wsConnection._destroyCurrentWSConnection(),this.wsConnection.disconnect().then(),this.wsFallback=new eu({client:this}),await this.wsFallback.connect();throw t}}
11_sayHi(){const t=$e(),s={headers:{"x-client-request-id":t}};this.doAxiosRequest("get",this.baseURL+"/hi",null,s).catch(i=>{this.options.enableInsights&&Is("http_hi_failed",{api_key:this.key,err:i,client_request_id:t})})}async queryUsers(t,s=[],i={}){const n={presence:!1};await this.wsPromise,this._hasConnectionID()||(n.presence=!1);const r=await this.get(this.baseURL+"/users",{payload:{filter_conditions:t,sort:D(s),...n,...i}});return this.state.updateUsers(r.users),r}async queryBannedUsers(t={},s=[],i={}){return await this.get(this.baseURL+"/query_banned_users",{payload:{filter_conditions:t,sort:D(s),...i}})}async queryMessageFlags(t={},s={}){return await this.get(this.baseURL+"/moderation/flags/message",{payload:{filter_conditions:t,...s}})}async queryChannelsRequest(t,s=[],i={}){const n={state:!0,watch:!0,presence:!1};await this.wsPromise,this._hasConnectionID()||(n.watch=!1);const r={filter_conditions:t,sort:D(s),...n,...i};return(await this.post(this.baseURL+"/channels",r)).channels}async queryChannels(t,s=[],i={},n={}){const r=await this.queryChannelsRequest(t,s,i);return this.dispatchEvent({type:"channels.queried",queriedChannels:{channels:r,isLatestMessageSet:!0}}),r?.length&&this.offlineDb?.upsertChannels&&await this.offlineDb.upsertChannels({channels:r,isLatestMessagesSet:!0}),this.hydrateActiveChannels(r,n,i)}async queryReactions(t,s,i=[],n={}){const r={filter:s,sort:D(i),...n};if(this.offlineDb?.getReactions&&!n.next)try{const a=await this.offlineDb.getReactions({messageId:t,filters:s,sort:i,limit:n.limit});a&&this.dispatchEvent({type:"offline_reactions.queried",offlineReactions:a})}catch(a){this.logger("warn","An error has occurred while querying offline reactions",{error:a})}return await this.wsPromise,await this.post(this.baseURL+"/messages/"+encodeURIComponent(t)+"/reactions",r)}hydrateActiveChannels(t=[],s={},i){const{skipInitialization:n,offlineMode:r=!1}=s,a=[];for(const o of t){this._addChannelConfig(o.channel);const l=this.channel(o.channel.type,o.channel.id);l.data=o.channel,l.offlineMode=r,l.initialized=!r,l.push_preferences=o.push_preferences;let c;if(n===void 0){const{messageSet:d}=l._initializeState(o,"latest");c=d}else if(!n.includes(o.channel.id)){l.state.clearMessages();const{messageSet:d}=l._initializeState(o,"latest");c=d}c&&(c.pagination={...c.pagination,...la({parentSet:c,requestedPageSize:i?.message_limit||Nd,returnedPage:o.messages,logger:this.logger})},this.polls.hydratePollCache(o.messages,!0),this.reminders.hydrateState(o.messages)),l.messageComposer.initStateFromChannelResponse(o),a.push(l)}return this.syncDeliveredCandidates(a),a}async search(t,s,i={}){if(i.offset&&i.next)throw Error("Cannot specify offset with next");const n={filter_conditions:t,...i,sort:i.sort?D(i.sort):void 0};if(typeof s=="string")n.query=s;else if(typeof s=="object")n.message_filter_conditions=s;else throw Error(`Invalid type ${typeof s} for query parameter`);return await this.wsPromise,await this.get(this.baseURL+"/search",{payload:n})}setLocalDevice(t){if(this.wsConnection?.isConnecting&&this.wsPromise||(this.wsConnection?.isHealthy||this.wsFallback?.isHealthy())&&this._hasConnectionID())throw new Error("you can only set device before opening a websocket connection");this.options.device=t}async addDevice(t,s,i,n){return await this.post(this.baseURL+"/devices",{id:t,push_provider:s,...i!=null?{user_id:i}:{},...n!=null?{push_provider_name:n}:{}})}async getDevices(t){return await this.get(this.baseURL+"/devices",t?{user_id:t}:{})}async getUnreadCount(t){return await this.get(this.baseURL+"/unread",t?{user_id:t}:{})}async getUnreadCountBatch(t){return await this.post(this.baseURL+"/unread_batch",{user_ids:t})}async setPushPreferences(t){return await this.post(this.baseURL+"/push_preferences",{preferences:t})}async removeDevice(t,s){return await this.delete(this.baseURL+"/devices",{id:t,...s?{user_id:s}:{}})}getRateLimits(t){const{serverSide:s,web:i,android:n,ios:r,endpoints:a}=t||{};return this.get(this.baseURL+"/rate_limits",{server_side:s,web:i,android:n,ios:r,endpoints:a?a.join(","):void 0})}async getHookEvents(t){const s=t&&t.length>0?{product:t.join(",")}:{};return await this.get(this.baseURL+"/hook/events",s)}_addChannelConfig({cid:t,config:s}){this._cacheEnabled()&&(this.configs[t]=s)}channel(t,s,i={}){if(!this.userID&&!this._isUsingServerAuth())throw Error("Call connectUser or connectAnonymousUser before creating a channel");
11if(~t.indexOf(":"))throw new Error(`Invalid channel group ${t}, can't contain the : character`);return s&&typeof s=="object"?this.getChannelByMembers(t,s):!s&&typeof i=="object"&&i.members?.length?this.getChannelByMembers(t,i):s?this.getChannelById(t,s,i):new _e(this,t,void 0,i)}async partialUpdateUser(t){return await this.partialUpdateUsers([t])}async upsertUsers(t){const s={};for(const i of t){if(!i.id)throw Error("User ID is required when updating a user");s[i.id]=i}return await this.post(this.baseURL+"/users",{users:s})}upsertUser(t){return this.upsertUsers([t])}async partialUpdateUsers(t){for(const s of t)if(!s.id)throw Error("User ID is required when updating a user");return await this.patch(this.baseURL+"/users",{users:t})}async deleteUser(t,s){return await this.delete(this.baseURL+`/users/${encodeURIComponent(t)}`,s)}async restoreUsers(t){return await this.post(this.baseURL+"/users/restore",{user_ids:t})}async reactivateUser(t,s){return await this.post(this.baseURL+`/users/${encodeURIComponent(t)}/reactivate`,{...s})}async reactivateUsers(t,s){return await this.post(this.baseURL+"/users/reactivate",{user_ids:t,...s})}async deactivateUser(t,s){return await this.post(this.baseURL+`/users/${encodeURIComponent(t)}/deactivate`,{...s})}async deactivateUsers(t,s){return await this.post(this.baseURL+"/users/deactivate",{user_ids:t,...s})}async exportUser(t,s){return await this.get(this.baseURL+`/users/${encodeURIComponent(t)}/export`,{...s})}async banUser(t,s){return await this.post(this.baseURL+"/moderation/ban",{target_user_id:t,...s})}async unbanUser(t,s){return await this.delete(this.baseURL+"/moderation/ban",{target_user_id:t,...s})}async shadowBan(t,s){return await this.banUser(t,{shadow:!0,...s})}async removeShadowBan(t,s){return await this.unbanUser(t,{shadow:!0,...s})}async blockUser(t,s){return await this.post(this.baseURL+"/users/block",{blocked_user_id:t,...s?{user_id:s}:{}})}async getBlockedUsers(t){return await this.get(this.baseURL+"/users/block",{...t?{user_id:t}:{}})}async unBlockUser(t,s){return await this.post(this.baseURL+"/users/unblock",{blocked_user_id:t,...s?{user_id:s}:{}})}async getSharedLocations(){return await this.get(this.baseURL+"/users/live_locations")}async muteUser(t,s,i={}){return await this.post(this.baseURL+"/moderation/mute",{target_id:t,...s?{user_id:s}:{},...i})}async unmuteUser(t,s){return await this.post(this.baseURL+"/moderation/unmute",{target_id:t,...s?{user_id:s}:{}})}userMuteStatus(t){if(!this.user||!this.wsPromise)throw new Error("Make sure to await connectUser() first.");for(let s=0;s<this.mutedUsers.length;s+=1)if(this.mutedUsers[s].target.id===t)return!0;return!1}async flagMessage(t,s={}){return await this.post(this.baseURL+"/moderation/flag",{target_message_id:t,...s})}async flagUser(t,s={}){return await this.post(this.baseURL+"/moderation/flag",{target_user_id:t,...s})}async unflagMessage(t,s={}){return await this.post(this.baseURL+"/moderation/unflag",{target_message_id:t,...s})}async unflagUser(t,s={}){return await this.post(this.baseURL+"/moderation/unflag",{target_user_id:t,...s})}async _queryFlags(t={},s={}){return await this.post(this.baseURL+"/moderation/flags",{filter_conditions:t,...s})}async _queryFlagReports(t={},s={}){return await this.post(this.baseURL+"/moderation/reports",{filter_conditions:t,...s})}async _reviewFlagReport(t,s,i={}){return await this.patch(this.baseURL+`/moderation/reports/${encodeURIComponent(t)}`,{review_result:s,...i})}async unblockMessage(t,s={}){return await this.post(this.baseURL+"/moderation/unblock_message",{target_message_id:t,...s})}async markChannelsRead(t={}){await this.post(this.baseURL+"/channels/read",{...t})}createCommand(t){return this.post(this.baseURL+"/commands",t)}getCommand(t){return this.get(this.baseURL+`/commands/${encodeURIComponent(t)}`)}updateCommand(t,s){return this.put(this.baseURL+`/commands/${encodeURIComponent(t)}`,s)}deleteCommand(t){return this.delete(this.baseURL+`/commands/${encodeURIComponent(t)}`)}listCommands(){return this.get(this.baseURL+"/commands")}createChannelType(t){const s=Object.assign({},{commands:["all"]},t);return this.post(this.baseURL+"/channeltypes",s)}getChannelType(t){return this.get(this.baseURL+`/channeltypes/${encodeURIComponent(t)}`)}updateChannelType(t,s){return this.put(this.baseURL+`/channeltypes/${encodeURIComponent(t)}`,s)}deleteChannelType(t){return this.delete(this.baseURL+`/channeltypes/${encodeURIComponent(t)}`)}listChannelTypes(){return this.get(this.baseURL+"/channeltypes")}async translateMessage(t,s){return await this.post(this.baseURL+`/messages/${encodeURIComponent(t)}/translate`,{language:s})}async translate(t,s,i){return await this.post(this.baseURL+"/translate",{text:t,source_language:i,destination_language:s})}
11_normalizeExpiration(t){let s=null;if(typeof t=="number"){const i=new Date;i.setSeconds(i.getSeconds()+t),s=i.toISOString()}else ni(t)?s=t:t instanceof Date&&(s=t.toISOString());return s}_validateAndGetMessageId(t,s){let i;if(typeof t=="string")i=t;else{if(!t.id)throw Error(s);i=t.id}return i}pinMessage(t,s,i,n){const r=this._validateAndGetMessageId(t,"Please specify the message id when calling unpinMessage");return this.partialUpdateMessage(r,{set:{pinned:!0,pin_expires:this._normalizeExpiration(s),pinned_at:this._normalizeExpiration(n)}},i)}unpinMessage(t,s){const i=this._validateAndGetMessageId(t,"Please specify the message id when calling unpinMessage");return this.partialUpdateMessage(i,{set:{pinned:!1}},s)}async updateMessage(t,s,i){if(!t.id)throw Error("Please specify the message.id when calling updateMessage");const n=ra(t);return typeof s=="string"?n.user_id=s:typeof s?.id=="string"&&(n.user_id=s.id),await this.post(this.baseURL+`/messages/${encodeURIComponent(t.id)}`,{message:n,...i})}async partialUpdateMessage(t,s,i,n){if(!t)throw Error("Please specify the message.id when calling partialUpdateMessage");let r;return typeof i=="string"?r={id:i}:typeof i?.id=="string"&&(r={id:i.id}),await this.put(this.baseURL+`/messages/${encodeURIComponent(t)}`,{...s,...n,user:r})}async ephemeralUpdateMessage(t,s,i,n){if(!t)throw Error("messageId is required");let r;return typeof i=="string"?r={id:i}:typeof i?.id=="string"&&(r={id:i.id}),await this.patch(`${this.baseURL}/messages/${encodeURIComponent(t)}/ephemeral`,{...s,...n,user:r})}async deleteMessage(t,s){let i={};typeof s=="boolean"?i=s?{hardDelete:!0}:{}:s?.deleteForMe?i={deleteForMe:!0}:s?.hardDelete&&(i={hardDelete:!0});try{if(this.offlineDb)return i.hardDelete?await this.offlineDb.hardDeleteMessage({id:t}):await this.offlineDb.softDeleteMessage({id:t,deleteForMe:i.deleteForMe}),await this.offlineDb.queueTask({task:{messageId:t,payload:[t,i],type:"delete-message"}})}catch(n){this.logger("error","offlineDb:deleteMessage",{tags:["channel","offlineDb"],error:n})}return this._deleteMessage(t,i)}async _deleteMessage(t,s){const{deleteForMe:i,hardDelete:n}=typeof s=="boolean"?{hardDelete:s}:s??{};let r={};n&&(r={hard:!0}),i&&(r={...r,delete_for_me:!0});const a=await this.delete(this.baseURL+`/messages/${encodeURIComponent(t)}`,r);return i&&(a.message.deleted_for_me=!0,a.message.type="deleted"),a}async undeleteMessage(t,s){return await this.post(this.baseURL+`/messages/${encodeURIComponent(t)}/undelete`,{undeleted_by:s})}async getMessage(t,s){return await this.get(this.baseURL+`/messages/${encodeURIComponent(t)}`,{...s})}async queryThreads(t={}){const s={limit:10,participant_limit:10,reply_limit:3,watch:!0,...t},i={...s};s.filter&&Object.keys(s.filter).length>0&&(i.filter=s.filter),s.sort&&(Array.isArray(s.sort)?s.sort.length>0:Object.keys(s.sort).length>0)&&(i.sort=D(s.sort));const n=await this.post(`${this.baseURL}/threads`,i);return{threads:n.threads.map(r=>new Te({client:this,threadData:r})),next:n.next}}async getThread(t,s={}){if(!t)throw new Error("Please specify the messageId when calling getThread");const i={participant_limit:100,reply_limit:3,watch:!0,...s},n=await this.get(`${this.baseURL}/threads/${encodeURIComponent(t)}`,i);return new Te({client:this,threadData:n.thread})}async partialUpdateThread(t,s){if(!t)throw Error("Please specify the message id when calling partialUpdateThread");const i=["created_at","id","last_message_at","type","updated_at","user","reply_count","participants","channel","custom"];for(const n in{...s.set,...s.unset})if(i.includes(n))throw Error(`You cannot set ${n} field on Thread object. ${n} is reserved for server-side use. Please omit ${n} from your set object.`);return await this.patch(`${this.baseURL}/threads/${encodeURIComponent(t)}`,s)}getUserAgent(){if(this.userAgent)return this.userAgent;const t="9.27.2",s="browser-esm";let i="";this.sdkIdentifier?i=`stream-chat-${this.sdkIdentifier.name}-v${this.sdkIdentifier.version}-llc-v${t}`:i=`stream-chat-js-v${t}-${this.node?"node":"browser"}`;const{os:n,model:r}=this.deviceIdentifier??{};return[["os",n],["device_model",r],["client_bundle",s]].reduce((a,[o,l])=>l&&l.length>0?a.concat(`|${o}=${l}`):a,i)}setUserAgent(t){this.userAgent=t}_enrichAxiosOptions(t={params:{},headers:{},config:{}}){const s=this._getToken(),i=s?{Authorization:s}:void 0;let n=null;this.nextRequestAbortController!==null&&(n=this.nextRequestAbortController.signal,this.nextRequestAbortController=null),t.headers?.["x-client-request-id"]||(t.headers={...t.headers,"x-client-request-id":$e()});const{params:r,headers:a,...o}=this.options.axiosRequestConfig||{};return{params:{user_id:this.userID,connection_id:this._getConnectionID(),api_key:this.key,...t.params,...r||{}},headers:{...i,"stream-auth-type":this.getAuthType(),"X-Stream-Client":this.getUserAgent(),...t.headers,...a||{}},...n?{signal:n}:{},...t.config,...o||{}}}_getToken(){return!this.tokenManager||this.anonymous?null:this.tokenManager.getToken()}_startCleaning(){const t=this;this.cleaningIntervalRef==null&&(this.cleaningIntervalRef=setInterval(()=>{for(const s of Object.values(t.activeChannels))s.clean()},500))}verifyWebhook(t,s){return!!this.secret&&$o(t,this.secret,s)}getPermission(t){return this.get(`${this.baseURL}
11/permissions/${encodeURIComponent(t)}`)}createPermission(t){return this.post(`${this.baseURL}/permissions`,{...t})}updatePermission(t,s){return this.put(`${this.baseURL}/permissions/${encodeURIComponent(t)}`,{...s})}deletePermission(t){return this.delete(`${this.baseURL}/permissions/${encodeURIComponent(t)}`)}listPermissions(){return this.get(`${this.baseURL}/permissions`)}createRole(t){return this.post(`${this.baseURL}/roles`,{name:t})}listRoles(){return this.get(`${this.baseURL}/roles`)}deleteRole(t){return this.delete(`${this.baseURL}/roles/${encodeURIComponent(t)}`)}sync(t,s,i={}){return this.post(`${this.baseURL}/sync`,{channel_cids:t,last_sync_at:s,...i})}async sendUserCustomEvent(t,s){return await this.post(`${this.baseURL}/users/${encodeURIComponent(t)}/event`,{event:s})}createBlockList(t){return this.post(`${this.baseURL}/blocklists`,t)}listBlockLists(t){return this.get(`${this.baseURL}/blocklists`,t)}getBlockList(t,s){return this.get(`${this.baseURL}/blocklists/${encodeURIComponent(t)}`,s)}updateBlockList(t,s){return this.put(`${this.baseURL}/blocklists/${encodeURIComponent(t)}`,s)}deleteBlockList(t,s){return this.delete(`${this.baseURL}/blocklists/${encodeURIComponent(t)}`,s)}exportChannels(t,s={}){const i={channels:t,...s};return this.post(`${this.baseURL}/export_channels`,i)}exportUsers(t){return this.post(`${this.baseURL}/export/users`,t)}exportChannel(t,s){return this.exportChannels([t],s)}getExportChannelStatus(t){return this.get(`${this.baseURL}/export_channels/${encodeURIComponent(t)}`)}campaign(t,s){return t&&typeof t=="object"?new _i(this,null,t):new _i(this,t,s)}segment(t,s,i){return typeof s=="string"?new Ii(this,t,s,i):new Ii(this,t,null,s)}validateServerSideAuth(){if(!this.secret)throw new Error("Campaigns is a server-side only feature. Please initialize the client with a secret to use this feature.")}createSegment(t,s,i){this.validateServerSideAuth();const n={id:s,type:t,...i};return this.post(this.baseURL+"/segments",n)}createUserSegment(t,s){return this.validateServerSideAuth(),this.createSegment("user",t,s)}createChannelSegment(t,s){return this.validateServerSideAuth(),this.createSegment("channel",t,s)}getSegment(t){return this.validateServerSideAuth(),this.get(this.baseURL+`/segments/${encodeURIComponent(t)}`)}updateSegment(t,s){return this.validateServerSideAuth(),this.put(this.baseURL+`/segments/${encodeURIComponent(t)}`,s)}addSegmentTargets(t,s){this.validateServerSideAuth();const i={target_ids:s};return this.post(this.baseURL+`/segments/${encodeURIComponent(t)}/addtargets`,i)}querySegmentTargets(t,s={},i=[],n={}){return this.validateServerSideAuth(),this.post(this.baseURL+`/segments/${encodeURIComponent(t)}/targets/query`,{filter:s||{},sort:i||[],...n})}removeSegmentTargets(t,s){this.validateServerSideAuth();const i={target_ids:s};return this.post(this.baseURL+`/segments/${encodeURIComponent(t)}/deletetargets`,i)}querySegments(t,s,i={}){return this.validateServerSideAuth(),this.post(this.baseURL+"/segments/query",{filter:t,sort:s,...i})}deleteSegment(t){return this.validateServerSideAuth(),this.delete(this.baseURL+`/segments/${encodeURIComponent(t)}`)}segmentTargetExists(t,s){return this.validateServerSideAuth(),this.get(this.baseURL+`/segments/${encodeURIComponent(t)}/target/${encodeURIComponent(s)}`)}createCampaign(t){return this.validateServerSideAuth(),this.post(this.baseURL+"/campaigns",{...t})}getCampaign(t,s){return this.validateServerSideAuth(),this.get(this.baseURL+`/campaigns/${encodeURIComponent(t)}`,{...s?.users})}startCampaign(t,s){return this.validateServerSideAuth(),this.post(this.baseURL+`/campaigns/${encodeURIComponent(t)}/start`,{scheduled_for:s?.scheduledFor,stop_at:s?.stopAt})}async queryCampaigns(t,s,i){return this.validateServerSideAuth(),await this.post(this.baseURL+"/campaigns/query",{filter:t,sort:s,...i||{}})}updateCampaign(t,s){return this.validateServerSideAuth(),this.put(this.baseURL+`/campaigns/${encodeURIComponent(t)}`,s)}deleteCampaign(t){return this.validateServerSideAuth(),this.delete(this.baseURL+`/campaigns/${encodeURIComponent(t)}`)}stopCampaign(t){return this.validateServerSideAuth(),this.post(this.baseURL+`/campaigns/${encodeURIComponent(t)}/stop`)}enrichURL(t){return this.get(this.baseURL+"/og",{url:t})}getTask(t){return this.get(`${this.baseURL}
11/tasks/${encodeURIComponent(t)}`)}async deleteChannels(t,s={}){return await this.post(this.baseURL+"/channels/delete",{cids:t,...s})}async deleteUsers(t,s={}){if(typeof s.user<"u"&&!["soft","hard","pruning"].includes(s.user))throw new Error("Invalid delete user options. user must be one of [soft hard pruning]");if(typeof s.conversations<"u"&&!["soft","hard"].includes(s.conversations))throw new Error("Invalid delete user options. conversations must be one of [soft hard]");if(typeof s.messages<"u"&&!["soft","hard","pruning"].includes(s.messages))throw new Error("Invalid delete user options. messages must be one of [soft hard pruning]");return await this.post(this.baseURL+"/users/delete",{user_ids:t,...s})}async _createImportURL(t){return await this.post(this.baseURL+"/import_urls",{filename:t})}async _createImport(t,s={mode:"upsert"}){return await this.post(this.baseURL+"/imports",{path:t,...s})}async _getImport(t){return await this.get(this.baseURL+`/imports/${encodeURIComponent(t)}`)}async _listImports(t){return await this.get(this.baseURL+"/imports",t)}async upsertPushProvider(t){return await this.post(this.baseURL+"/push_providers",{push_provider:t})}async deletePushProvider({type:t,name:s}){return await this.delete(this.baseURL+`/push_providers/${encodeURIComponent(t)}/${encodeURIComponent(s)}`)}async listPushProviders(){return await this.get(this.baseURL+"/push_providers")}createAbortControllerForNextRequest(){return this.nextRequestAbortController=new AbortController}async commitMessage(t){return await this.post(this.baseURL+`/messages/${encodeURIComponent(t)}/commit`)}async createPoll(t,s){return await this.post(this.baseURL+"/polls",{...t,...s?{user_id:s}:{}})}async getPoll(t,s){return await this.get(this.baseURL+`/polls/${encodeURIComponent(t)}`,s?{user_id:s}:{})}async updatePoll(t,s){return await this.put(this.baseURL+"/polls",{...t,...s?{user_id:s}:{}})}async partialUpdatePoll(t,s,i){return await this.patch(this.baseURL+`/polls/${encodeURIComponent(t)}`,{...s,...i?{user_id:i}:{}})}async deletePoll(t,s){return await this.delete(this.baseURL+`/polls/${encodeURIComponent(t)}`,{...s?{user_id:s}:{}})}closePoll(t,s){return this.partialUpdatePoll(t,{set:{is_closed:!0}},s)}async createPollOption(t,s,i){return await this.post(this.baseURL+`/polls/${encodeURIComponent(t)}/options`,{...s,...i?{user_id:i}:{}})}async getPollOption(t,s,i){return await this.get(this.baseURL+`/polls/${encodeURIComponent(t)}/options/${encodeURIComponent(s)}`,i?{user_id:i}:{})}async updatePollOption(t,s,i){return await this.put(this.baseURL+`/polls/${encodeURIComponent(t)}/options`,{...s,...i?{user_id:i}:{}})}async deletePollOption(t,s,i){return await this.delete(this.baseURL+`/polls/${encodeURIComponent(t)}/options/${encodeURIComponent(s)}`,i?{user_id:i}:{})}async castPollVote(t,s,i,n){return await this.post(this.baseURL+`/messages/${encodeURIComponent(t)}/polls/${encodeURIComponent(s)}/vote`,{vote:i,...n?{user_id:n}:{}})}addPollAnswer(t,s,i,n){return this.castPollVote(t,s,{answer_text:i},n)}async removePollVote(t,s,i,n){return await this.delete(this.baseURL+`/messages/${encodeURIComponent(t)}/polls/${encodeURIComponent(s)}/vote/${encodeURIComponent(i)}`,{...n?{user_id:n}:{}})}async queryPolls(t={},s=[],i={},n){const r=n?`?user_id=${n}`:"";return await this.post(this.baseURL+`/polls/query${r}`,{filter:t,sort:D(s),...i})}async queryPollVotes(t,s={},i=[],n={},r){const a=r?`?user_id=${r}`:"";return await this.post(this.baseURL+`/polls/${encodeURIComponent(t)}/votes${a}`,{filter:s,sort:D(i),...n})}async queryPollAnswers(t,s={},i=[],n={},r){const a=r?`?user_id=${r}`:"";return await this.post(this.baseURL+`/polls/${encodeURIComponent(t)}/votes${a}`,{filter:{...s,is_answer:!0},sort:D(i),...n})}async queryMessageHistory(t={},s=[],i={}){return await this.post(this.baseURL+"/messages/history",{filter:t,sort:D(s),...i})}async updateFlags(t,s,i={}){return await this.post(this.baseURL+"/automod/v1/moderation/update_flags",{message_ids:t,reviewed_by:s,...i})}async queryDrafts(t={}){const s={...t,sort:t.sort?D(t.sort):void 0};return await this.post(this.baseURL+"/drafts/query",s)}async createReminder({messageId:t,...s}){return await this.post(`${this.baseURL}
11/messages/${t}/reminders`,s)}async updateReminder({messageId:t,...s}){return await this.patch(`${this.baseURL}/messages/${t}/reminders`,s)}async deleteReminder(t,s){return await this.delete(`${this.baseURL}/messages/${t}/reminders`,s?{user_id:s}:{})}async queryReminders({filter:t,sort:s,...i}={}){return await this.post(`${this.baseURL}/reminders/query`,{filter:t,sort:s&&D(s),...i})}async updateLocation(t){return await this.put(this.baseURL+"/users/live_locations",t)}uploadFile(t,s,i,n){return this.sendFile(`${this.baseURL}/uploads/file`,t,s,i,n)}uploadImage(t,s,i,n){return this.sendFile(`${this.baseURL}/uploads/image`,t,s,i,n)}deleteFile(t){return this.delete(`${this.baseURL}/uploads/file`,{url:t})}deleteImage(t){return this.delete(`${this.baseURL}/uploads/image`,{url:t})}async markChannelsDelivered(t){if(t?.latest_delivered_messages?.length)return await this.post(this.baseURL+"/channels/delivered",t)}syncDeliveredCandidates(t){this.messageDeliveryReporter.syncDeliveredCandidates(t)}},Fi=e=>new Date(e.end_at).getTime()<Date.now();function _r(e){return!e||e.type==="deleted"||!e.shared_location?.end_at?!1:!Fi(e.shared_location)}var il=3e3,wr=class nl extends Pe{constructor({client:t,getDeviceId:s,watchLocation:i}){if(!t.userID)throw new Error("Live-location sharing is reserved for client-side use only");super(),this.registerSubscriptions=()=>{this.incrementRefCount(),!this.hasSubscriptions&&(this.addUnsubscribeFunction(this.subscribeLiveLocationSharingUpdates()),this.addUnsubscribeFunction(this.subscribeTargetMessagesChange()))},this.unregisterSubscriptions=()=>super.unregisterSubscriptions(),this.client=t,this.state=new U({messages:new Map,ready:!1}),this._deviceId=s(),this.getDeviceId=s,this.watchLocation=i}
11async init(){await this.assureStateInit(),this.registerSubscriptions()}get messages(){return this.state.getLatestValue().messages}get stateIsReady(){return this.state.getLatestValue().ready}get deviceId(){return this._deviceId||(this._deviceId=this.getDeviceId()),this._deviceId}async assureStateInit(){if(this.stateIsReady)return;const{active_live_locations:t}=await this.client.getSharedLocations();this.state.next({messages:new Map(t.filter(s=>!Fi(s)).map(s=>[s.message_id,{...s,stopSharingTimeout:setTimeout(()=>{this.unregisterMessages([s.message_id])},new Date(s.end_at).getTime()-Date.now())}])),ready:!0})}subscribeTargetMessagesChange(){let t=null;const s=this.state.subscribeWithSelector(({messages:i})=>({messages:i}),({messages:i})=>{i.size?i.size&&!t&&(t=this.subscribeWatchLocation()):(t?.(),t=null)});return()=>{s(),t?.()}}subscribeWatchLocation(){let t=Date.now();return this.watchLocation(({latitude:i,longitude:n})=>{Date.now()<t||(t=Date.now()+il,Ca(nl.symbol,async()=>{const r=[];await this.assureStateInit();const a=[];for(const[o,l]of this.messages){if(Fi(l)){a.push(l.message_id);continue}if(l.latitude===i&&l.longitude===n)continue;const c=this.client.updateLocation({created_by_device_id:l.created_by_device_id,message_id:o,latitude:i,longitude:n});r.push(c)}this.unregisterMessages(a),r.length>0&&await Promise.allSettled(r)}))})}subscribeLiveLocationSharingUpdates(){const t=[...["live_location_sharing.started","message.updated","message.deleted"].map(s=>this.client.on(s,i=>{i.message&&(i.type==="live_location_sharing.started"?this.registerMessage(i.message):i.type==="message.updated"?(this.messages.has(i.message.id)&&!_r(i.message)&&this.unregisterMessages([i.message.id]),this.registerMessage(i.message)):this.unregisterMessages([i.message.id]))})),this.client.on("live_location_sharing.stopped",s=>{s.live_location&&this.unregisterMessages([s.live_location?.message_id])})];return()=>t.forEach(s=>s.unsubscribe())}registerMessage(t){!this.client.userID||t?.user?.id!==this.client.userID||!_r(t)||this.state.next(s=>{const i=new Map(s.messages);return i.set(t.id,{...t.shared_location,stopSharingTimeout:setTimeout(()=>{this.unregisterMessages([t.id])},new Date(t.shared_location.end_at).getTime()-Date.now())}),{...s,messages:i}})}unregisterMessages(t){const s=this.messages,i=new Set(t),n=new Map(Array.from(s).filter(([r,a])=>(i.has(r)&&a.stopSharingTimeout&&(clearTimeout(a.stopSharingTimeout),a.stopSharingTimeout=null),!i.has(r))));n.size!==s.size&&this.state.partialNext({messages:n})}};wr.symbol=Symbol(wr.name);var pu=class{constructor(e,t){if(!e)throw new Error("Size must be greater than 0");this.keys=[],this.size=e,this.map=new Map,this.dispose=t?.dispose??null}add(e,t){if(this.keys.indexOf(e)>-1)this.keys.splice(this.keys.indexOf(e),1);else if(this.keys.length>=this.size){const i=this.keys.shift();if(i){const n=this.peek(i);n&&this.dispose?.(i,n),this.map.delete(i)}}this.keys.push(e),this.map.set(e,t)}peek(e){return this.map.get(e)}get(e){const t=this.peek(e);return t&&this.keys.indexOf(e)!==this.size-1&&(this.keys.splice(this.keys.indexOf(e),1),this.keys.push(e)),t}};const Nu=Object.freeze(Object.defineProperty({__proto__:null,AttachmentManager:Ia,AttachmentPostUploadMiddlewareExecutor:va,AttachmentPreUploadMiddlewareExecutor:xa,BasePaginator:_o,BaseSearchSource:At,BaseSearchSourceSync:mo,Campaign:_i,Channel:_e,ChannelManager:Jo,ChannelSearchSource:Bh,ChannelState:fa,CheckSignature:$o,ClientState:Ti,CommandSearchSource:vo,CustomDataManager:Fa,DEFAULT_ATTACHMENT_MANAGER_CONFIG:Oa,DEFAULT_CHANNEL_MANAGER_OPTIONS:Ko,DEFAULT_CHANNEL_MANAGER_PAGINATION_OPTIONS:Jt,DEFAULT_COMPOSER_CONFIG:Na,DEFAULT_LINK_PREVIEW_MANAGER_CONFIG:Da,DEFAULT_LOCATION_COMPOSER_CONFIG:ka,DEFAULT_PAGINATION_OPTIONS:yo,DEFAULT_REMINDER_MANAGER_CONFIG:Ni,DEFAULT_STOP_REFRESH_BOUNDARY_MS:vn,DEFAULT_TEXT_COMPOSER_CONFIG:Pa,DevToken:qo,ErrorFromResponse:Ga,FilterBuilder:je,FixedSizeQueueCache:pu,InsightMetrics:Oo,JWTServerToken:Li,JWTUserToken:bn,LinkPreviewsManager:Fs,LocationComposer:Ba,MAX_POLL_OPTIONS:qa,MODERATION_ENTITY_TYPES:lt,MentionsSearchSource:Eo,MergedStateStore:Ma,MessageComposer:St,MessageComposerMiddlewareExecutor:fo,MessageDeliveryReporter:Lo,MessageDraftComposerMiddlewareExecutor:po,MessageReceiptsTracker:Do,MessageSearchSource:qh,MiddlewareExecutor:we,Moderation:Vo,NotificationManager:Xo,Poll:Wo,PollComposer:Ja,PollComposerCompositionMiddlewareExecutor:za,PollComposerStateMiddlewareExecutor:Qa,PollManager:Go,Reminder:el,ReminderManager:sl,ReminderPaginator:wo,ReminderTimer:Yo,SearchController:Nh,Segment:Ii,StableWSConnection:Fo,StateStore:U,StreamChat:fu,THREAD_MANAGER_INITIAL_STATE:Di,TextComposer:Uo,TextComposerMiddlewareExecutor:Ao,Thread:Te,ThreadManager:jo,TokenManager:Ho,UPDATE_LIVE_LOCATION_REQUEST_MIN_THROTTLE_TIMEOUT:il,UserFromToken:Bo,UserSearchSource:Fh,VALID_MAX_VOTES_VALUE_REGEX:Bs,VotingVisibility:Ka,accentsMap:Ei,buildWsFatalInsight:Po,buildWsSuccessAfterFailureInsight:No,calculateLevenshtein:xi,channelManagerEventToHandlerMapping:Oi,chatCodes:qe,createAttachmentsCompositionMiddleware:Ya,createBlockedAttachmentUploadNotificationMiddleware:Ea,createCommandsMiddleware:Ro,createCompositionDataCleanupMiddleware:eo,createCompositionValidationMiddleware:io,createCustomDataCompositionMiddleware:to,createDraftAttachmentsCompositionMiddleware:Za,createDraftCompositionValidationMiddleware:no,createDraftCustomDataCompositionMiddleware:so,createDraftLinkPreviewsCompositionMiddleware:ao,createDraftMessageComposerStateCompositionMiddleware:ho,createDraftTextComposerCompositionMiddleware:lo,createFileFromBlobs:un,createLinkPreviewsCompositionMiddleware:ro,createMentionsMiddleware:xo,createMessageComposerStateCompositionMiddleware:co,createPollComposerStateMiddleware:Wa,createPostUploadAttachmentEnrichmentMiddleware:ba,createSharedLocationCompositionMiddleware:uo,createTextComposerCompositionMiddleware:oo,createTextComposerPreValidationMiddleware:Mo,createUploadConfigCheckMiddleware:Ra,createUploadErrorHandlerMiddleware:Sa,decodeBase64:sa,defaultPollFieldBlurEventValidators:Ha,defaultPollFieldChangeEventValidators:$a,encodeBase64:ta,ensureIsLocalAttachment:Ci,escapeRegExp:Co,extractPollData:zo,extractPollEnrichedData:Kt,formatMessage:B,generateFileName:fn,getAttachmentTypeFromMimeType:wa,getCompleteCommandInString:bo,getExtensionFromMimeType:_a,getTokenizedSuggestionDisplayName:So,getTriggerCharWithToken:yn,insertItemWithTrigger:_n,isAudioAttachment:cn,isBlobButNotFile:ya,isFile:bt,isFileAttachment:an,isFileList:ma,isFileReference:me,isImageAttachment:on,isImageFile:He,isLocalAttachment:De,isLocalAudioAttachment:wh,isLocalFileAttachment:_h,isLocalImageAttachment:ln,isLocalUploadAttachment:yh,isLocalVideoAttachment:Ch,isLocalVoiceRecordingAttachment:bh,isPatch:pn,isScrapedContent:pa,isSharedLocationResponse:Sh,isTargetedOptionTextUpdate:Va,isUploadedAttachment:ga,isVideoAttachment:hn,isVoiceRecordingAttachment:dn,isVoteAnswer:pe,localMe
11ssageToNewMessagePayload:rh,logChatPromiseExecution:sn,mapPollStateToResponse:Qo,pollCompositionStateProcessors:ja,pollStateChangeValidators:Ls,postInsights:Is,promoteChannel:ot,removeDiacritics:zt,textIsEmpty:wn,timeLeftMs:vt},Symbol.toStringTag,{value:"Module"}));export{Bh as ChannelSearchSource,pu as FixedSizeQueueCache,Fs as LinkPreviewsManager,St as MessageComposer,qh as MessageSearchSource,Nh as SearchController,U as StateStore,Fh as UserSearchSource,Ka as VotingVisibility,xd as find,B as formatMessage,Nu as index,cn as isAudioAttachment,an as isFileAttachment,on as isImageAttachment,De as isLocalAttachment,wh as isLocalAudioAttachment,_h as isLocalFileAttachment,ln as isLocalImageAttachment,yh as isLocalUploadAttachment,Ch as isLocalVideoAttachment,bh as isLocalVoiceRecordingAttachment,pa as isScrapedContent,Sh as isSharedLocationResponse,hn as isVideoAttachment,dn as isVoiceRecordingAttachment,pe as isVoteAnswer,rh as localMessageToNewMessagePayload,ku as test}; 12//# sourceMappingURL=index-chunk-_po-jwAP.js.map
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.