UNPKG

pope-test-lite-chat-api

Version:

Tencent Cloud Chat SDK for Web/Mini Program/uni-app/React Native/Donut

1 lines 94.7 kB
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).liteChat={})}(this,(function(e){"use strict";class t{constructor(){this.listeners={}}on(e,t,s){this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push({fn:t,context:s})}off(e,t,s){var n;t&&(this.listeners[e]=null===(n=this.listeners[e])||void 0===n?void 0:n.filter((e=>{const n=e.fn===t,o=!s||e.context===s;return!(n&&o)})))}emit(e,...t){const s=this.listeners[e];s&&s.forEach((e=>{const{fn:s,context:n}=e;s.apply(n,t)}))}once(e,t,s){const n=(...o)=>{t.apply(s,o),this.off(e,n)};this.on(e,n)}}var s;!function(e){e.BUSINESS_COMMAND="business_command",e.C2C_REALTIME_MESSAGE="C2cMsgArray",e.C2C_MODIFIED_MESSAGE="C2cMsgModNotifys",e.PROFILE_MODIFIED="ProfileDataMod"}(s||(s={}));const n=[{type:"event",value:100,subType:s.BUSINESS_COMMAND},{type:"hasKey",value:"C2cMsgArray",subType:s.C2C_REALTIME_MESSAGE},{type:"hasKey",value:"C2cMsgModNotifys",subType:s.C2C_MODIFIED_MESSAGE},{type:"hasKey",value:"ProfileDataMod",subType:s.PROFILE_MODIFIED}];var o;!function(e){e.SERVER_PUSH_MESSAGE="im_open_push.msg_push",e.ERROR="error"}(o||(o={}));const i={[o.SERVER_PUSH_MESSAGE]:function(e){const{EventArray:t}=(null==e?void 0:e.body)||{};return t.map((e=>{const{Event:t}=e,s=n.find((e=>"event"===e.type&&e.value===t));if(s)return{type:`${o.SERVER_PUSH_MESSAGE}:${s.subType}`,data:e};const i=n.find((t=>"hasKey"===t.type&&Object.prototype.hasOwnProperty.call(e,t.value)));return i?{type:`${o.SERVER_PUSH_MESSAGE}:${i.subType}`,data:e}:void 0}))},[o.ERROR]:function(e){const{errorCode:t}=e;return[{type:`error:${t}`,data:e}]}};const r=new class{constructor(){this._outerEventEmitter=null,this._innerEventEmitter=null,this._outerEventEmitter=new t,this._innerEventEmitter=new t,this.InnerEventSubType=s}subscribeInnerEvent(e,t,s,n){var o,i;if(["string","number"].includes(typeof t)){const i=t,r=s;null===(o=this._innerEventEmitter)||void 0===o||o.on(`${e}:${i}`,r,n)}else{const n=t;null===(i=this._innerEventEmitter)||void 0===i||i.on(e,n,s)}}emitInnerEvent(e,t){var s,n;if(null===(s=this._innerEventEmitter)||void 0===s||s.emit(e,t),Object.keys(i).includes(e)){const s=null===(n=i[e])||void 0===n?void 0:n.call(i,t);null==s||s.forEach((e=>{var t;e&&(null===(t=this._innerEventEmitter)||void 0===t||t.emit(e.type,e.data))}))}}unSubscribeInnerEvent(e,t,s,n){var o,i;if(["string","number"].includes(typeof t)){const i=t,r=s;null===(o=this._innerEventEmitter)||void 0===o||o.off(`${e}:${i}`,r,n)}else{const n=t;null===(i=this._innerEventEmitter)||void 0===i||i.off(e,n,s)}}subscribeOuterEvent(e,t,s){var n;null===(n=this._outerEventEmitter)||void 0===n||n.on(e,t,s)}unSubscribeOuterEvent(e,t,s){var n;null===(n=this._outerEventEmitter)||void 0===n||n.off(e,t,s)}emitOuterEvent(e,t){var s;null===(s=this._outerEventEmitter)||void 0===s||s.emit(e,t)}getOuterEventEmitter(){return this._outerEventEmitter}rest(){this._outerEventEmitter=null,this._innerEventEmitter=null}};function a(e,t,s,n){var o,i=arguments.length,r=i<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,s):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)r=Reflect.decorate(e,t,s,n);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(r=(i<3?o(r):i>3?o(t,s,r):o(t,s))||r);return i>3&&r&&Object.defineProperty(t,s,r),r}function c(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}function d(e,t,s,n){return new(s||(s=Promise))((function(o,i){function r(e){try{c(n.next(e))}catch(e){i(e)}}function a(e){try{c(n.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(r,a)}c((n=n.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const l=e=>{if("string"!=typeof e)return!1;const t=e[0];return!/[^a-zA-Z0-9]/.test(t)},u=e=>{if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);if(null===t)return!0;let s=t;for(;null!==Object.getPrototypeOf(s);)s=Object.getPrototypeOf(s);return t===s};function _(e=99999999){return Math.round(Math.random()*e)}function h(e){let t,s,n=e;e.length%8!=0&&(n="0".repeat(8-e.length%8)+e);let o="";for(let e=0,{length:i}=n;e<i;e+=8)t=parseInt(n.slice(e,e+4),2),s=parseInt(n.slice(e+4,e+8),2),o+=base16Map.get(t)+base16Map.get(s);return o}const g={ANDROID:2,IOS:3,MAC:4,WEB:7,WX_MP:8,QQ_MP:9,TT_MP:10,BAIDU_MP:11,ALI_MP:12,IPAD:13,UNI_NATIVE_APP:15,DONUT_NATIVE_APP:19,NS_NATIVE_APP:20,RN_NATIVE_APP:21},m="undefined"!=typeof wx&&"function"==typeof wx.getSystemInfoSync&&Boolean(wx.getSystemInfoSync().fontSizeSetting),p=m&&"function"==typeof wx.createGamePortal,f="undefined"!=typeof qq&&"function"==typeof qq.getSystemInfoSync&&Boolean(qq.getSystemInfoSync().fontSizeSetting),I="undefined"!=typeof tt&&"function"==typeof tt.getSystemInfoSync&&Boolean(tt.getSystemInfoSync().fontSizeSetting),E="undefined"!=typeof swan&&"function"==typeof swan.getSystemInfoSync&&Boolean(swan.getSystemInfoSync().fontSizeSetting),S="undefined"!=typeof my&&"function"==typeof my.getSystemInfoSync&&Boolean(my.getSystemInfoSync().fontSizeSetting),v="undefined"!=typeof jd&&"function"==typeof jd.getSystemInfoSync,T="undefined"!=typeof uni&&"undefined"==typeof window&&"function"==typeof uni.requireNativePlugin,y=m&&"object"==typeof wx.miniapp,M="undefined"!=typeof uni,O=m||f||I||E||S||T||v,A="undefined"==typeof window&&!O&&"undefined"!=typeof global&&void 0!==global.NativeScriptGlobals,C="undefined"!=typeof global&&(void 0!==global.nativeModuleProxy||void 0!==global.ReactNative),D="undefined"!=typeof uni?!O:"undefined"!=typeof window&&!O&&!C,L=f?qq:I?tt:E?swan:S?my:m?wx:T?uni:v?jd:{},N=D&&window&&window.navigator&&window.navigator.userAgent||"",R=/(micromessenger|webbrowser)/i.test(N),P=function(){let e="WEB";return R?e="WEB":f?e="QQ_MP":I?e="TT_MP":E?e="BAIDU_MP":S?e="ALI_MP":m?e=y?"DONUT_NATIVE_APP":"WX_MP":T?e="UNI_NATIVE_APP":A?e="NS_NATIVE_APP":C&&(e="RN_NATIVE_APP"),g[e]}(),w=/iPad/i.test(N),k=/iPhone/i.test(N)&&!w,U=/iPod/i.test(N),b=k||w||U,F=function(){const e=N.match(/OS (\d+)_/i);return e&&e[1]?e[1]:null}(),G=/Android/i.test(N),$=function(){const e=N.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(!e)return null;const t=e[1]&&parseFloat(e[1]),s=e[2]&&parseFloat(e[2]);return t&&s?parseFloat(`${e[1]}.${e[2]}`):t||null}(),q=/Firefox/i.test(N),x=/Edge/i.test(N),B=!x&&/Chrome/i.test(N),K=/MSIE/.test(N)||N.indexOf("Trident")>-1&&N.indexOf("rv:11.0")>-1,V=function(){const e=/MSIE\s(\d+)\.\d/.exec(N);let t=e&&parseFloat(e[1]);return!t&&/Trident\/7.0/i.test(N)&&/rv:11.0/.test(N)&&(t=11),t}(),j=/Safari/i.test(N)&&!B&&!G&&!x,Y=/Windows/i.test(N),H=/MAC OS X/i.test(N),W=D&&"undefined"!=typeof Worker&&!K,z=G||b,J=D&&void 0!==window.tencent_cloud_im_csig_flutter_for_web_25F_cy,X=function(){if("undefined"==typeof window||void 0===window.navigator)return!1;const{standalone:e}=window.navigator;return!(!b||e||j)}();function Q(){let e="unknown";if(H&&(e="mac"),Y&&(e="windows"),b&&(e="ios"),G&&(e="android"),O)try{const{platform:t}=wx.getSystemInfoSync();void 0!==t&&(e=t)}catch(e){console.error(e)}return e}const Z=2800,ee=2801,te=60002,se=3e3,ne="application/x-www-form-urlencoded;charset=UTF-8";function oe(e){return d(this,arguments,void 0,(function*({method:e,url:t,data:s,timeout:n=se}){return new Promise(O?(o,i)=>{L.request({url:t,data:s,method:e,timeout:n,header:{"content-type":ne},success:e=>o(e.data),fail:()=>i(new Error(`{"message":"Network error","code":${Z}}`))})}:(o,i)=>{const r=new XMLHttpRequest,a=setTimeout((()=>{r.abort(),i(new Error(`{"message":"Request timeout","code":${ee}}`))}),n);r.onreadystatechange=function(){if(4===r.readyState)if(clearTimeout(a),200===r.status||304===r.status)try{o(r.responseText?JSON.parse(r.responseText):null)}catch(e){o(r.responseText)}else i(new Error(`{"message":"Network error","code":${Z}}`))},r.open(e,t,!0),r.setRequestHeader("Content-type",ne),r.send(s||null)})}))}function ie(e){if(null==e)return!0;if("boolean"==typeof e)return!1;if("number"==typeof e)return 0===e;if("string"==typeof e)return 0===e.length;if("function"==typeof e)return 0===e.length;if(Array.isArray(e))return 0===e.length;if(e instanceof Error)return""===e.message;if(u(e)){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}return("[object Map]"===Object.prototype.toString.call(e)||"[object Set]"===Object.prototype.toString.call(e)||"[object File]"===Object.prototype.toString.call(e))&&0===e.size}function re(){let e,t;return{promise:new Promise(((s,n)=>{e=s,t=n})),resolve:e,reject:t}}var ae,ce=Object.freeze({__proto__:null,ANDROID_VERSION:$,IE_VERSION:V,IN_ALIPAY_MINI_APP:S,IN_BAIDU_MINI_APP:E,IN_BROWSER:D,IN_DONUT_NATIVE_APP:y,IN_JD_MINI_APP:v,IN_MINI_APP:O,IN_NS_NATIVE_APP:A,IN_QQ_MINI_APP:f,IN_RN_APP:C,IN_TT_MINI_APP:I,IN_UNI_APP:M,IN_UNI_NATIVE_APP:T,IN_WX_MINI_APP:m,IN_WX_MINI_GAME:p,IOS_VERSION:F,IS_ANDROID:G,IS_CHROME:B,IS_EDGE:x,IS_FIREFOX:q,IS_IE:K,IS_IOS:b,IS_IPAD:w,IS_IPHONE:k,IS_IPOD:U,IS_MAC:H,IS_SAFARI:j,IS_WECHAT:R,IS_WIN:Y,IS_WORKER_AVAILABLE:W,MINI_APP_NAMESPACE:L,USER_AGENT:N,base16EncodeBinaryString:h,generatePromise:re,getPlatformType:Q,httpRequest:oe,isEmpty:ie,isFlutterWeb:J,isH5:z,isIOSWebView:X,isPlainObject:u,isValidRequestKey:l,platform:P,randomInt:_});class de{constructor(){this._socket=null}connectSocket(e){return this._socket=new WebSocket(e),this._socket}send(e){var t,s;try{null===(t=this._socket)||void 0===t||t.send(e)}catch(e){null===(s=this._onSendFail)||void 0===s||s.call(this,e)}}bindSocketHandlers(e){const{onOpen:t,onMessage:s,onClose:n,onError:o,onSendFail:i}=e;this._socket&&(this._socket.binaryType="arraybuffer",this._socket.onopen=t,this._socket.onmessage=s,this._socket.onclose=n,this._socket.onerror=o,this._onSendFail=i)}unbindSocketHandlers(){this._socket&&(this._socket.onopen=null,this._socket.onmessage=null,this._socket.onclose=null,this._socket.onerror=null)}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}class le{connectSocket(e){return this._socket=wx.connectSocket({url:e,header:{"content-type":"application/json"},complete:()=>{}}),this._socket}send(e){var t;null===(t=this._socket)||void 0===t||t.send({data:e,fail:this._onSendFail})}bindSocketHandlers(e){const{onOpen:t,onMessage:s,onClose:n,onError:o,onSendFail:i}=e;this._socket.onClose(n),this._socket.onOpen(t),this._socket.onMessage(s),this._socket.onError(o),this._onSendFail=i}unbindSocketHandlers(){this._socket&&(this._socket.onClose((()=>{})),this._socket.onOpen((()=>{})),this._socket.onMessage((()=>{})),this._socket.onError((()=>{})))}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}!function(e){e[e.CONNECTED=0]="CONNECTED",e[e.CONNECTING=1]="CONNECTING",e[e.DISCONNECTED=2]="DISCONNECTED"}(ae||(ae={}));class ue{constructor(e){this._url="",this._readyState=ae.DISCONNECTED,this._url=e,this._id=_(),this._emitter=new t,this._socket=m?new le:new de,this.connect()}connect(){this.doOpen(),this._bindSocketHandlers()}doOpen(){[ae.CONNECTED,ae.CONNECTING].includes(this._readyState)||(this._readyState=ae.CONNECTING,this._ws=this._socket.connectSocket(this._url))}send(e){this._readyState!==ae.CONNECTED?this.reconnect():this._socket.send(e)}reconnect(){[ae.CONNECTED,ae.CONNECTING].includes(this._readyState)||(this.disconnect(),this.doOpen())}getId(){return this._id}on(e,t,s){this._emitter.on(e,t,s)}off(e,t,s){this._emitter.off(e,t,s)}isConnected(){return this._readyState===ae.CONNECTED}disconnect(){this._readyState=ae.DISCONNECTED,this._unbindSocketHandlers(),this._socket.disconnect()}_onOpen(e){this._readyState===ae.CONNECTING&&(this._readyState=ae.CONNECTED,this._emitter.emit("connect",{socketId:this._id,event:e}))}_onMessage(e){this._emitter.emit("message",e)}_onClose(e){this._readyState=ae.DISCONNECTED,this._emitter.emit("close",{socketId:this._id,event:e})}_onError(e){this._readyState=ae.DISCONNECTED,this._emitter.emit("error",e)}_onSendFail(e){this._emitter.emit("sendFail",e)}_bindSocketHandlers(){this._socket.bindSocketHandlers({onOpen:this._onOpen.bind(this),onMessage:this._onMessage.bind(this),onClose:this._onClose.bind(this),onError:this._onError.bind(this),onSendFail:this._onSendFail.bind(this)})}_unbindSocketHandlers(){this._socket.unbindSocketHandlers()}}const _e="CHINA",he="SINGAPORE",ge="KOREA",me="GERMANY",pe="IND",fe="JPN",Ie="USA",Ee="INDONESIA",Se={TEST:{CHINA:{DEFAULT:"wss://wss-dev.tim.qq.com"},OVERSEA:{DEFAULT:"wss://wss-dev.tim.qq.com"},SINGAPORE:{DEFAULT:"wss://wsssgp-dev.im.qcloud.com"},KOREA:{DEFAULT:"wss://wsskr-dev.im.qcloud.com"},GERMANY:{DEFAULT:"wss://wssger-dev.im.qcloud.com"},IND:{DEFAULT:"wss://wssind-dev.im.qcloud.com"},JPN:{DEFAULT:"wss://wssjpn-dev.im.qcloud.com"},USA:{DEFAULT:"wss://wssusa-dev.im.qcloud.com"},INDONESIA:{DEFAULT:"wss://wssidn-dev.im.qcloud.com"}},PRODUCTION:{CHINA:{INITIAL:"wss://*w4c.my-imcloud.com",DEFAULT:"wss://wss.im.qcloud.com",BACKUP:"wss://wss.tim.qq.com",STAT:"https://events.im.qcloud.com",ANYCAST:"wss://162.14.13.203"},OVERSEA:{INITIAL:"wss://*w4c.my-imcloud.com",DEFAULT:"wss://wss.im.qcloud.com",BACKUP:"wss://wss.my-imcloud.com",STAT:"https://api.my-imcloud.com"},SINGAPORE:{INITIAL:"wss://*w4s.my-imcloud.com",DEFAULT:"wss://wsssgp.im.qcloud.com",BACKUP:"wss://wsssgp.my-imcloud.com",STAT:"https://apisgp.my-imcloud.com",ANYCAST:"wss://162.14.19.159"},KOREA:{INITIAL:"wss://*w4k.my-imcloud.com",DEFAULT:"wss://wsskr.im.qcloud.com",BACKUP:"wss://wsskr.my-imcloud.com",STAT:"https://apikr.my-imcloud.com",ANYCAST:"wss://162.14.13.104"},GERMANY:{INITIAL:"wss://*w4g.my-imcloud.com",DEFAULT:"wss://wssger.im.qcloud.com",BACKUP:"wss://wssger.my-imcloud.com",STAT:"https://apiger.my-imcloud.com",ANYCAST:"wss://162.14.3.17"},IND:{INITIAL:"wss://*w4i.my-imcloud.com",DEFAULT:"wss://wssind.my-imcloud.com",BACKUP:"wss://wssind.im.qcloud.com",STAT:"https://apiind.my-imcloud.com",ANYCAST:"wss://162.14.18.188"},JPN:{INITIAL:"wss://*w4j.my-imcloud.com",DEFAULT:"wss://wssjpn.im.qcloud.com",BACKUP:"wss://wssjpn.my-imcloud.com",STAT:"https://apijpn.my-imcloud.com"},USA:{INITIAL:"wss://*w4u.my-imcloud.com",DEFAULT:"wss://wssusa.im.qcloud.com",BACKUP:"wss://wssusa.my-imcloud.com",STAT:"https://apiusa.my-imcloud.com",ANYCAST:"wss://162.14.10.42"},INDONESIA:{INITIAL:"wss://*w4y.my-imcloud.com",DEFAULT:"wss://wssidn.im.qcloud.com",BACKUP:"wss://wssidn.my-imcloud.com",STAT:"https://apiidn.my-imcloud.com",ANYCAST:"wss://43.129.34.169"}}},ve={[he]:[[2e7,3e7],[172e7,173e7]],[ge]:[[3e7,4e7],[173e7,174e7]],[me]:[[4e7,5e7],[174e7,175e7]],[pe]:[[5e7,6e7],[175e7,176e7]],[fe]:[[6e7,7e7],[176e7,177e7]],[Ie]:[[7e7,8e7],[177e7,178e7]],[Ee]:[[8e7,9e7],[178e7,179e7]]};function Te(e){for(const t of Object.keys(ve))for(const[s,n]of ve[t])if(e>=s&&e<n)return t;return _e}var ye,Me=new class{constructor(){this._store=new Map}get(e){return this._store.get(e)}getStorage(e){if(O){if(S){return my.getStorageSync({key:e}).data}return L.getStorageSync(e)}return this._canUseLocalStorage()?localStorage.getItem(e):{}}set(e,t){const s=this._store.get(e)||{};t instanceof Map?this._store.set(e,t):this._store.set(e,Object.assign(Object.assign({},s),t))}setStorage(e,t){O?S?my.setStorageSync({key:e,data:JSON.stringify(t)}):L.setStorageSync(e,JSON.stringify(t)):this._canUseLocalStorage()&&localStorage.setItem(e,JSON.stringify(t))}clear(e){"string"==typeof e?this._store.set(e,{}):this._store.clear()}clearLocalStorage(e){this._canUseLocalStorage()&&("string"==typeof e?localStorage.setItem(e,""):localStorage.clear())}reset(){this.clear()}_canUseLocalStorage(){return"undefined"!=typeof window&&(navigator&&navigator.cookieEnabled&&localStorage)}},Oe="1.0.0";!function(e){e.INITIAL="INITIAL",e.DEFAULT="DEFAULT",e.BACKUP="BACKUP",e.ANYCAST="ANYCAST"}(ye||(ye={}));let Ae=ye.INITIAL;function Ce(){const e=Math.random();return 0===e?Ce():e}function De(e,t){const{isBinary:s=!1}=t||{},n=Me.get("instance"),{sdkAppId:o,instanceId:i}=n,r=Ce(),a=Q(),c=function(){const e=Q();let t=-1;"ios"===e?t=F||-1:"android"===e&&(t=$||-1);return t}();var d;return`${e}/${s?"binfo":"info"}?${d={sdkappid:o,instanceid:i,random:r,platform:P,host:a,version:c,sdkversion:Oe},Object.keys(d).map((e=>`${e}=${d[e]}`)).join("&")}`}var Le=new class{constructor(){this._timeOffsetWithServer=0}getServerTimeMs(){return Date.now()+this._timeOffsetWithServer}getServerTimeSeconds(){return Math.floor(this.getServerTimeMs()/1e3)}getTimeOffsetWithServer(){return this._timeOffsetWithServer}calculateTimeOffsetWithServer(e,t){const s=Date.now(),n=s-e;this._timeOffsetWithServer=t+n-s}};const Ne=16;var Re=new class{constructor(){this._tasks=[],this._timer=null,this._taskMap=new Map}_addTaskToScheduler(e){const{id:t}=e;this.removeTask(t),this._tasks.push(e),this._taskMap.set(t,e),this._sort(),this._scheduleNextTask()}_createTask(e){const{id:t,callback:s,context:n,isOnce:o=!1,intervalMs:i=Ne}=e,r=Math.max(i,Ne);return{id:t,nextExecuteTime:Date.now()+r,intervalMs:i,callback:s,context:n,isOnce:o}}addTask(e){const t=this._createTask(e);this._addTaskToScheduler(t)}addOnceTask(e){const t=this._createTask(Object.assign(Object.assign({},e),{isOnce:!0}));this._addTaskToScheduler(t)}removeTask(e){const t=this._tasks.findIndex((t=>t.id===e));t>-1&&(this._tasks.splice(t,1),this._taskMap.delete(e),this._scheduleNextTask())}updateTaskInterval(e,t){const s=this._taskMap.get(e);s&&(s.intervalMs=t,s.nextExecuteTime=Date.now()+t,this._sort(),this._scheduleNextTask())}clearAllTasks(){this._tasks=[],this._taskMap.clear(),this._timer&&(clearTimeout(this._timer),this._timer=null)}dispose(){this.clearAllTasks()}_sort(){this._tasks.sort(((e,t)=>e.nextExecuteTime-t.nextExecuteTime))}_scheduleNextTask(){this._timer&&(clearTimeout(this._timer),this._timer=null);const e=this._tasks[0];if(e){const t=Math.max(0,e.nextExecuteTime-Date.now());this._timer=setTimeout((()=>this._execute()),t)}}_execute(){const e=Date.now();for(;this._tasks.length&&this._tasks[0].nextExecuteTime<=e;){const t=this._tasks[0];try{t.context?t.callback.call(t.context):t.callback(),t.isOnce?this.removeTask(t.id):(t.nextExecuteTime=e+t.intervalMs,this._sort())}catch(e){console.warn(`Task ${t.id} execution failed:`,e),t.isOnce&&this.removeTask(t.id)}}this._scheduleNextTask()}};function Pe(e){return Object.assign(Object.assign({},function(){const e=Me.get("login")||{},t=Me.get("instance")||{};return{ver:"v4",platform:P,websdkappid:537048168,websdkversion:"1.7.3",a2:e.a2Key||void 0,tinyid:e.tinyID||void 0,status_instid:e.statusInstanceId||0,sdkappid:t.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:e.a2Key?void 0:e.userId,usersig:e.a2Key?void 0:e.userSig,sdkability:4386675,sdkability_ext:h(""),cappid:e.cappid||0,tjgID:"",seq:Fe()}}()),{servcmd:e})}function we(e){const t=Array.isArray(e)?[]:Object.create(null);for(const s in e)Object.prototype.hasOwnProperty.call(e,s)&&l(s)&&null!=e[s]&&(null===e[s]||"object"!=typeof e[s]?t[s]=e[s]:t[s]=we(e[s]));return t}function ke(e){const{servcmd:t,data:s}=e;return we({head:Pe(t),body:s})}function Ue(e){const{servcmd:t,data:s}=e,n=function(e){const t=Me.get("login")||{},s=Me.get("instance")||{};return{servcmd:e,ver:"v4",platform:P,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:s.sdkAppId,contenttype:"",reqtime:Math.floor(Date.now()/1e3),identifier:"",usersig:"",status_instid:t.statusInstanceId||0,sdkability:12775283,sdkability_ext:h(""),cappid:t.cappid||0,seq:Fe()}}(t);return we({head:n,body:s})}let be=_();function Fe(){return be=be<2415919103?be+1:_(),be}var Ge,$e=Object.freeze({__proto__:null,generateProtocolData:ke,generateSSOLogProtocolData:Ue,generateSequence:Fe,taskScheduler:Re,timeManager:Le});!function(e){e[e.info=4]="info",e[e.warning=5]="warning",e[e.error=6]="error"}(Ge||(Ge={}));const qe={method:"extension",networkType:"network_type",eventType:"event_type",code:"error_code",message:"error_message",moreMessage:"more_message",duplicate:"duplicate",costTime:"cost_time",level:"level",uiPlatform:"ui_platform",timestamp:"timestamp"};class xe{constructor(e){this.level=Ge.info,this._canSendLog=!0,this._logCreatedAt=Le.getServerTimeMs(),this.timestamp=0,this.networkType=8,this.code=0,this.moreMessage="",this.method="",this.message="",this.costTime=0,this.duplicate=!1,this.eventType=0,this.uiPlatform=void 0;const{method:t,eventType:s=0}=e||{};this.eventType=s,this.method=t}setMoreMessage(e){this.moreMessage=`${this.moreMessage} ${e}`}updateLogCreatedAtByTimeOffset(){this._logCreatedAt+=Le.getTimeOffsetWithServer()}end(e=!1){if(!this._canSendLog)return;const t=Le.getServerTimeMs();0===this.costTime&&(this.costTime=t-this._logCreatedAt),this.setMoreMessage(`startts:${this._logCreatedAt} endts:${t}`),e?(this._canSendLog=!1,this.timestamp=Le.getServerTimeMs(),this._ssoLogModule.pushToLogQueue(this._convertSSOLogDataKeyToServe())):setTimeout((()=>{this._canSendLog=!1,this.timestamp=Le.getServerTimeMs(),this._ssoLogModule.pushToLogQueue(this._convertSSOLogDataKeyToServe())}),0)}setError(e){var t;if(!(e instanceof Error))return console.warn("SSOLogData.setError value not instanceof Error, please check!"),this;if(!this._canSendLog)return this;return(null===(t=Me.get("netWorkMonitor"))||void 0===t?void 0:t.isNetworkOnline)&&(e.errorCode&&(this.code=e.errorCode),e.errorMessage&&this.setMoreMessage(e.errorMessage)),this.level=Ge.error,this}setLogInfo(e){return Object.keys(e).forEach((t=>{Object.keys(qe).includes(t)&&(this[t]=e[t])})),this}setSSOLogModule(e){this._ssoLogModule=e}_convertSSOLogDataKeyToServe(){const e={};return Object.keys(this).forEach((t=>{const s=t;qe[s]&&(e[qe[s]]=this[s])})),e}}function Be(){const e=Me.get("login")||{},t=Me.get("instance")||{};return{sdk_type:30,sdk_app_id:t.sdkAppId,sdk_version:Oe,tiny_id:Number(e.tinyID),user_id:e.userId,platform:P,instance_id:t.instanceId,trace_id:(new Date).getTime()}}var Ke;!function(e){e.RECONNECTED="reconnected",e.CLOUD_CONFIG_UPDATE="cloud_config_update"}(Ke||(Ke={}));var Ve=Ke;const je=20,Ye=6e4,He=[4,5,6],We=[],ze=[],Je="report-logger";var Xe=new class{constructor(){this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._reportLevel=[4,5,6],this._minThreshold=je,this._maxThreshold=100,this._waitingTime=Ye,this._lastReportAt=Date.now(),this._ssoLogMap=new Map,r.subscribeInnerEvent(Ve.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),Re.addTask({id:Je,intervalMs:1e3,callback:this._checkAndReportIfDue,context:this}),this._logQueue=[],this._savePlatFormInfo()}_handleCloudConfigUpdate(e){const{evt_rpt_threshold:t=je,evt_rpt_waiting:s=Ye,evt_rpt_level:n=He,evt_rpt_sdkappid_bl:o=We,evt_rpt_tinyid_wl:i=ze}=e||{};this._sdkAppIdBlackList=o,this._waitingTime=s,this._minThreshold=t,this._reportLevel=n,this._tinyIdWhiteList=i}createSSOLogData(e){const t=new xe(e);return t.setSSOLogModule(this),this._ssoLogMap.set(e.method,t),t}getSSOLogData(e){return this._ssoLogMap.get(e)||{}}pushToLogQueue(e){e&&(this._logQueue.push(e),this._shouldUploadImmediately()&&this._uploadSSOLogData())}_shouldUploadImmediately(){return this._logQueue.length>=this._minThreshold}_isReportDue(){return Date.now()>=this._lastReportAt+this._waitingTime}_checkAndReportIfDue(){this._isReportDue()&&this._logQueue.length>0&&this._uploadSSOLogData()}_uploadSSOLogData(){return d(this,void 0,void 0,(function*(){if(0===this._logQueue.length)return;const e=this._logQueue.slice(),t=this._filterLogs(e);if(this._logQueue=[],0===t.length)return void(this._lastReportAt=Date.now());const s={Header:Be(),Event:t};yield function(e){const t="imopenstat.tim_web_report_v2",s=Ue({servcmd:t,data:e}),n=`${s.head.seq}${t}`;rt.sendPacket(s,{requestId:n})}(s),this._lastReportAt=Date.now()}))}_savePlatFormInfo(){var e,t;if(m){const s=null===(t=null===(e=wx.getAccountInfoSync)||void 0===e?void 0:e.call(wx))||void 0===t?void 0:t.miniProgram;if(s){const{appId:e,envVersion:t}=s;Me.set("instance",{appId:e,envVersion:t})}}else D&&Me.set("instance",{href:window.location.href})}_filterLogs(e){const{tinyID:t}=Me.get("login")||{},{sdkAppId:s}=Me.get("instance")||{};return this._sdkAppIdBlackList.includes(s)&&!this._tinyIdWhiteList.includes(t)?[]:e.filter((e=>this._reportLevel.includes(e.level)))}reset(){console.log("SSO_LOG_MODULE.reset"),Re.removeTask(Je),r.unSubscribeInnerEvent(Ve.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),this._lastReportAt=0,this._uploadSSOLogData(),this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._minThreshold=je,this._maxThreshold=100,this._waitingTime=Ye,this._logQueue=[]}};const Qe=15e3,Ze="Channel",et="channel_schedule_task",st="connected",nt="connecting",ot="disconnected";function it(e){const t=[];for(let s=0;s<e.length;s+=1){const n=e.charCodeAt(s);if(n>=55296&&n<=56319){const o=e.charCodeAt(++s)-56320+(n-55296<<10)+65536;t.push(240|o>>18,128|o>>12&63,128|o>>6&63,128|63&o)}else n<=127?t.push(n):n<=2047?t.push(192|n>>6,128|63&n):t.push(224|n>>12,128|n>>6&63,128|63&n)}return new Uint8Array(t)}var rt=new class{constructor(){this._socketAdapter=null,this._url="",this._isReconnecting=!1,this._reconnectAttempts=0,this._pendingRequests=new Map,this._nextHeartbeatAt=0,this._lastDiagnoseAt=0,this._isHeartbeatInProgress=!1,this._connectionEstablishedTime=0,this._connectionStartTime=0,this._hasFatalError=!1,this._connectionId=-1,this._isBinarySupported=!0,this._currentConnectState=st}init(){Re.addTask({id:et,intervalMs:1e3,callback:this._executeScheduledTaskIfReady,context:this}),this._updateIsBinarySupported(),this._url=function(e){const t=Me.get("instance"),{sdkAppId:s,testEnv:n}=t,o=Te(s);return De(n?Se.TEST[o].DEFAULT:Se.PRODUCTION[o].INITIAL.replace("*",`${s}`),{isBinary:e})}(this._isBinarySupported),r.subscribeInnerEvent("networkStatusChange",this._handleNetworkStatusChange,this),this.connect()}sendPacket(e,t){var s;const{requestId:n,timeout:o=Qe,canResend:i=!0}=t||{};if(ie(e))return console.warn(`${Ze}.sendPacket: packet is empty `,e),null;const r=JSON.stringify(e);let a=null;if(n){const{resolve:e,reject:t,promise:s}=re();a=s,this._pendingRequests.set(n,{resolve:e,reject:t,timestamp:Date.now(),uplinkData:r,timeout:o,canResend:i})}const c=this._isBinarySupported?it(r).buffer:r;return null===(s=this._socketAdapter)||void 0===s||s.send(c),a}connect(){var e;this._socketAdapter=new ue(this._url),this._connectionEstablishedTime=0,this._addEventListeners(),this._connectionStartTime=Date.now();const t=null===(e=this._socketAdapter)||void 0===e?void 0:e.getId();console.log(`${Ze}._connect isWorkerEnabled: false socketID:${t} url:${this._url}`);Xe.createSSOLogData({method:"wsConnect"}).setLogInfo({message:`socketID:${t} url:${this._url}`}).end()}disconnect(){var e,t;const s=null===(e=this._socketAdapter)||void 0===e?void 0:e.getId();console.log(`${Ze}.disconnect socketID:${s}`),this._removeEventListeners(),null===(t=this._socketAdapter)||void 0===t||t.disconnect()}getSocketAdapter(){return this._socketAdapter}dispose(){console.log(`${Ze}.dispose`),Re.removeTask(et),r.unSubscribeInnerEvent("networkStatusChange",this._handleNetworkStatusChange,this),this.disconnect(),this._socketAdapter=null,this._isReconnecting=!1,this._reconnectAttempts=0,this._isHeartbeatInProgress=!1,this._pendingRequests.clear(),this._nextHeartbeatAt=0,this._lastDiagnoseAt=0,this._hasFatalError=!1,this._url=""}_shouldSkipReconnect(e){if(e)return!1;const t=this._currentConnectState===nt&&this._isReconnecting;return this._hasFatalError||!this._socketAdapter||t}reconnect(){return d(this,arguments,void 0,(function*(e=!1){var t;const s=`forcedFlag:${e}_reconnectAttempts:${this._reconnectAttempts}hasFatalError:${this._hasFatalError}isReconnecting:${this._isReconnecting}_currentConnectState:${this._currentConnectState}`;if(console.log(`Channel.reconnect ${s}`),!this._shouldSkipReconnect(e)){this._url=function(e){const t=Me.get("instance"),{sdkAppId:s,testEnv:n}=t,o=Te(s);if(n)return De(Se.TEST[o].DEFAULT,{isBinary:e});const i=Se.PRODUCTION[o],r=D&&i.ANYCAST;return De({[ye.INITIAL]:()=>(Ae=ye.DEFAULT,i.DEFAULT),[ye.DEFAULT]:()=>(Ae=ye.BACKUP,i.BACKUP),[ye.BACKUP]:()=>(Ae=r?ye.ANYCAST:ye.DEFAULT,r?i.ANYCAST:i.DEFAULT),[ye.ANYCAST]:()=>(Ae=ye.DEFAULT,i.ANYCAST="",i.DEFAULT)}[Ae](),{isBinary:e})}(this._isBinarySupported);try{if(this._isReconnecting=!0,this._handleConnectStateChange(nt),this._reconnectAttempts>=3)return this._reconnectAttempts=0,void((null===(t=Me.get("netWorkMonitor"))||void 0===t?void 0:t.isNetworkOnline)?(console.log("Network is available but connection failed, retrying..."),this.disconnect(),this.connect()):(this._isReconnecting=!1,this._handleConnectStateChange(ot)));this._reconnectAttempts+=1,this.disconnect(),this.connect()}catch(e){this._isReconnecting=!1,this._handleConnectStateChange(ot),console.warn("Reconnection failed:",e)}}}))}_addEventListeners(){var e,t,s,n,o;null===(e=this._socketAdapter)||void 0===e||e.on("connect",this._onConnect,this),null===(t=this._socketAdapter)||void 0===t||t.on("message",this._onMessage,this),null===(s=this._socketAdapter)||void 0===s||s.on("close",this._onClose,this),null===(n=this._socketAdapter)||void 0===n||n.on("error",this._onError,this),null===(o=this._socketAdapter)||void 0===o||o.on("sendFail",this._onSendFail,this)}_removeEventListeners(){var e,t,s,n,o;null===(e=this._socketAdapter)||void 0===e||e.off("connect",this._onConnect,this),null===(t=this._socketAdapter)||void 0===t||t.off("message",this._onMessage,this),null===(s=this._socketAdapter)||void 0===s||s.off("close",this._onClose,this),null===(n=this._socketAdapter)||void 0===n||n.off("error",this._onError,this),null===(o=this._socketAdapter)||void 0===o||o.off("sendFail",this._onSendFail,this)}_onClose(e){const{socketId:t,event:s}=e||{},n=Xe.createSSOLogData({method:"wsOnClose"}),o=`sourceSocketID:${t} currentSocketID:${this._connectionId} code:${null==s?void 0:s.code} reason:${null==s?void 0:s.reason}`,i=0!==this._connectionEstablishedTime?Date.now()-this._connectionEstablishedTime:0;n.setLogInfo({message:i,moreMessage:o,code:null==s?void 0:s.code,costTime:i}).end(!0),console.log(`${Ze}._onClose ${o} connectionDuration: ${i}`),this._isReconnecting&&(this._handleConnectStateChange(ot),this._isReconnecting=!1),t===this._connectionId&&this.reconnect()}_onError(e){console.warn(`${Ze}._onError ${JSON.stringify(e)}`),this._handleConnectStateChange(ot)}_onSendFail(){this._handleConnectStateChange(ot)}_onMessage(e){let t;this._updateHeartbeatTime();try{const s=this._isBinarySupported?function(e){const t=new Uint8Array(e);let s="",n=0;const{length:o}=t;for(;n<o;){let e=t[n],i=0,r=0;if(e<=127?(i=0,r=255&e):e<=223?(i=1,r=31&e):e<=239?(i=2,r=15&e):e<=244&&(i=3,r=7&e),o-n-i>0)for(let s=0;s<i;s+=1)e=t[n+s+1],r=r<<6|63&e;else r=65533,i=o-n;s+=String.fromCodePoint(r),n+=i+1}return s}(e.data):e.data;t=JSON.parse(s)}catch(t){console.error(t);return void Xe.createSSOLogData({method:"jsonParseError"}).setLogInfo({message:e.data}).end()}if(!t||!t.head)return;const{seq:s,servcmd:n}=t.head,o=`${s}${n}`;this._pendingRequests.has(o)?this._handleRequestResponse(t):this._handlePushMessage(t)}_handleRequestResponse(e){const{seq:t,servcmd:s}=e.head,{int32_error_code:n,str_error_message:o,ErrorCode:i=n,ErrorInfo:a=o}=(null==e?void 0:e.body)||{},c=`${t}${s}`,{resolve:d,reject:l,timestamp:u,headSeq:_}=this._pendingRequests.get(c);if(this._pendingRequests.delete(c),i&&0!==i)return r.emitInnerEvent("error",{errorCode:i,errorInfo:a}),void l({errorCode:i,errorInfo:a});d(e.body)}_handlePushMessage(e){const{servcmd:t}=e.head,{NeedAck:s,SessionData:n}=e.body;1===s&&this._sendAck(n),r.emitInnerEvent(t,e)}_checkPendingRequestsAndResend(){var e;console.log(`${Ze}._checkPendingRequestsAndResend reConnectFlag:${this._isReconnecting} promiseMap.size:${this._pendingRequests.size}`),null===(e=this._pendingRequests)||void 0===e||e.forEach(((e,t)=>{var s;const{uplinkData:n,canResend:o,resolve:i,reject:r,timeout:a}=e;if(o){this._pendingRequests.set(t,{resolve:i,reject:r,timestamp:Date.now(),uplinkData:n,timeout:a,canResend:o});const e=this._isBinarySupported?it(n).buffer:n;null===(s=this._socketAdapter)||void 0===s||s.send(e)}else this._pendingRequests.delete(t)}))}_onConnect(e){const{socketId:t,event:s={}}=e||{};this._connectionId=t,this._connectionEstablishedTime=Date.now();const n=Date.now()-this._connectionStartTime,o=`${Ze}._onOpen cost:${n} ms. socketID:${t} res:${JSON.stringify(s)}`;console.log(o);Xe.createSSOLogData({method:"wsOnOpen"}).setLogInfo({message:o,costTime:n}).end(),this._checkPendingRequestsAndResend(),this._sendHeartbeatIfReady(),this._reconnectAttempts=0,this._isReconnecting&&(r.emitInnerEvent(Ve.RECONNECTED),this._isReconnecting=!1),this._handleConnectStateChange(st)}_sendAck(e){const t=ke({servcmd:"openim.ws_msg_push_ack",data:{SessionData:e}});this.sendPacket(t)}_executeScheduledTaskIfReady(){return d(this,void 0,void 0,(function*(){this._clearTimeoutRequest(),this._sendHeartbeatIfReady()}))}_canSendHeartbeat(){var e;return(null===(e=this._socketAdapter)||void 0===e?void 0:e.isConnected())&&Date.now()>=this._nextHeartbeatAt&&!this._isHeartbeatInProgress}_sendHeartbeat(){return d(this,void 0,void 0,(function*(){var e;const t=ke({servcmd:"heartbeat.alive",data:{}});try{const e=`${t.head.seq}${t.head.servcmd}`;yield this.sendPacket(t,{requestId:e,timeout:3e3})}catch(t){const s=null===(e=Me.get("netWorkMonitor"))||void 0===e?void 0:e.isNetWorkOnline;if(console.debug(`${Ze}._sendHeartbeat failed. isNetWorkOnline:${s} error:`,t),(null==t?void 0:t.code)===te){this._hasFatalError=!0;return Xe.createSSOLogData({method:"error"}).setLogInfo({message:`code:${null==t?void 0:t.code} message:${null==t?void 0:t.message}`}).end(),void this._handleConnectStateChange(ot)}s?this.reconnect():this._handleConnectStateChange(ot)}}))}_sendHeartbeatIfReady(){return d(this,void 0,void 0,(function*(){this._canSendHeartbeat()&&(this._isHeartbeatInProgress=!0,yield this._sendHeartbeat(),this._isHeartbeatInProgress=!1)}))}_updateHeartbeatTime(){this._nextHeartbeatAt=T?Date.now()+5e3:Date.now()+1e4}_handleNetworkStatusChange(e){console.warn(`${Ze}._handleNetworkStatusChange ${JSON.stringify(e)}`);const{isNetworkOnline:t,networkType:s}=e;t&&"none"!==s&&this._reconnectAttempts<3&&this._socketAdapter?(this._reconnectAttempts+=1,this.reconnect()):(this._handleConnectStateChange(ot),this._reconnectAttempts=0)}isPrivateNetWork(){const e=Me.get("instance")||{};return e.proxyServer&&!e.fileDownloadProxy}_handleConnectStateChange(e){this._currentConnectState!==e&&(console.log(`${Ze}._handleConnectStateChange from ${this._currentConnectState} to ${e}`),this._currentConnectState=e,r.emitOuterEvent("netStateChange",{name:"netStateChange",data:{state:e}}))}_diagnose(){this.isPrivateNetWork()||(this._lastDiagnoseAt=Date.now(),function(e){d(this,void 0,void 0,(function*(){const t=e.split("/")[2];if(!t.startsWith("ws"))return;const s=`https://${t}/v3/netcheck/getconninfo?${e.slice(e.indexOf("info?")+5)}&reqtime=${Date.now()}`;try{yield oe({method:"GET",url:s,data:{}})}catch(e){console.warn("diagnoseBySSO failed. error:",e)}}))}(this._url),function(e){d(this,void 0,void 0,(function*(){const t=`https://boce-cdn.my-imcloud.com/v3/netcheck/getconninfo?${e.slice(e.indexOf("info?")+5)}&reqtime=${Date.now()}`;try{yield oe({method:"GET",url:t,data:{}})}catch(e){console.warn("diagnoseByCDN failed. error:",e)}}))}(this._url))}_clearTimeoutRequest(){for(const[e,t]of this._pendingRequests.entries()){const{reject:s,timestamp:n,timeout:o}=t;Date.now()-n>=o&&(this._pendingRequests.delete(e),Date.now()-this._lastDiagnoseAt>=3e4&&this._diagnose(),s({errorCode:ee,errorInfo:"NETWORK_TIMEOUT",data:{requestId:e}}))}}_updateIsBinarySupported(){var e;if(null===(e=Me.get("instance"))||void 0===e?void 0:e.devMode)return void(this._isBinarySupported=!1);const t=Q();(S||m&&"windows"===t||T)&&(this._isBinarySupported=!1)}};const at={init:function(e){Me.set("instance",e),rt.init()},destroy:function(){rt.dispose(),Me.clear(),Re.dispose()},notificationCenter:r,channel:rt,store:Me,ssoLog:Xe,utils:ce,common:$e};var ct;!function(e){e.SDK_READY="sdkStateReady",e.SDK_NOT_READY="sdkStateNotReady",e.SDK_DESTROY="sdkDestroy",e.MESSAGE_RECEIVED="onMessageReceived",e.ROOM_CUSTOM_DATA_RECEIVED="onRoomCustomDataReceived",e.MESSAGE_MODIFIED="onMessageModified",e.MESSAGE_REVOKED="onMessageRevoked",e.MESSAGE_READ_BY_PEER="onMessageReadByPeer",e.MESSAGE_READ_RECEIPT_RECEIVED="onMessageReadReceiptReceived",e.MESSAGE_EXTENSIONS_UPDATED="onMessageExtensionsUpdated",e.MESSAGE_EXTENSIONS_DELETED="onMessageExtensionsDeleted",e.MESSAGE_REACTIONS_UPDATED="onMessageReactionsUpdated",e.CONVERSATION_LIST_UPDATED="onConversationListUpdated",e.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED="onTotalUnreadMessageCountUpdated",e.CONVERSATION_GROUP_LIST_UPDATED="onConversationGroupListUpdated",e.CONVERSATION_IN_GROUP_UPDATED="onConversationInGroupUpdated",e.GROUP_LIST_UPDATED="onGroupListUpdated",e.GROUP_ATTRIBUTES_UPDATED="groupAttributesUpdated",e.GROUP_COUNTER_UPDATED="onGroupCounterUpdated",e.TOPIC_CREATED="onTopicCreated",e.TOPIC_DELETED="onTopicDeleted",e.TOPIC_UPDATED="onTopicUpdated",e.PROFILE_UPDATED="onProfileUpdated",e.USER_STATUS_UPDATED="onUserStatusUpdated",e.BLACKLIST_UPDATED="blacklistUpdated",e.FRIEND_LIST_UPDATED="onFriendListUpdated",e.FRIEND_GROUP_LIST_UPDATED="onFriendGroupListUpdated",e.FRIEND_APPLICATION_LIST_UPDATED="onFriendApplicationListUpdated",e.MY_FOLLOWERS_LIST_UPDATED="onMyFollowersListUpdated",e.MY_FOLLOWING_LIST_UPDATED="onMyFollowingListUpdated",e.MUTUAL_FOLLOWERS_LIST_UPDATED="onMutualFollowersListUpdated",e.KICKED_OUT="kickedOut",e.ERROR="error",e.NET_STATE_CHANGE="netStateChange",e.ALL_RECEIVE_MESSAGE_OPT_UPDATED="onAllReceiveMessageOptUpdated"}(ct||(ct={}));var dt,lt=ct;!function(e){e.LOGIN="login",e.RE_LOGIN="re_login",e.BEFORE_LOGIN="before_login",e.LOGOUT="logout",e.DESTROY="destroy",e.CLOUD_CONFIG_UPDATE="cloud_config_update",e.PROFILE_UPDATE="profile_updated",e.UNREAD_MESSAGES_SYNC_COMPLETED="unread_messages_sync_completed",e.ERROR="error",e.RECONNECTED="reconnected",e.FORCE_OFFLINE="im_open_status.stat_forceoffline",e.COMMERCIAL_CONFIG_PUSH="im_sdk_config_mgr.push_imsdk_purchase_bitsv2",e.OVERLOAD_PUSH="OverLoadPush.notify2"}(dt||(dt={}));var ut,_t=dt;!function(e){e.NEW_INVITATION_RECEIVED="newInvitationReceived",e.INVITEE_ACCEPTED="ts_invitee_accepted",e.INVITEE_REJECTED="ts_invitee_rejected",e.INVITATION_CANCELLED="ts_invitation_cancelled",e.INVITATION_TIMEOUT="ts_invitation_timeout",e.INVITATION_MODIFIED="ts_invitation_modified"}(ut||(ut={}));var ht,gt=ut;!function(e){e.KICKED_OUT_REST_API="REST_API_Kick",e.KICKED_OUT_MULT_ACCOUNT="multipleAccount",e.KICKED_OUT_MULT_DEVICE="multipleDevice",e.KICKED_OUT_USERSIG_EXPIRED="userSigExpired",e.MSG_CUSTOM="TIMCustomElem",e.CONV_C2C="C2C"}(ht||(ht={}));var mt=ht;const pt={NO_SDKAPPID:2e3,NO_ACCOUNT_TYPE:2001,NO_IDENTIFIER:2002,NO_USERSIG:2003,NO_TINYID:2022,NO_A2KEY:2023,USER_NOT_LOGGED_IN:2024,REPEAT_LOGIN:2025,COS_UNDETECTED:2040,COS_GET_SIG_FAIL:2041,MSG_SEND_FAIL:2100,MSG_SEND_FAIL_NOT_IN_AV:2101,MSG_INSTANCE_REQUIRED:2105,MSG_INVALID_CONV_TYPE:2106,MSG_F_IS_EMPTY:2108,MSG_ONPROGRESS_ERR:2109,MSG_REVOKE_FAIL:2110,MSG_DELETE_FAIL:2111,MSG_UNREAD_ALL_FAIL:2112,READ_RECEIPT_MSG_LIST_EMPTY:2114,MSG_SEND_GRP_WITH_TOPIC_FAIL:2115,CANNOT_DELETE_GRP_SYSTEM_NOTICE:2116,TRANSLATE_TEXT_FAIL:2117,VOICE_TO_TEXT_FAIL:2118,UNSUPPORTED_VOICE_FORMAT:2119,MSG_I_SELECT_F_FIRST:2251,MSG_I_TYPES_LIMIT:2252,MSG_I_SIZE_LIMIT:2253,MSG_A_UPLOAD_FAIL:2300,MSG_A_SIZE_LIMIT:2301,MSG_V_UPLOAD_FAIL:2350,MSG_V_SIZE_LIMIT:2351,MSG_V_TYPES_LIMIT:2352,MSG_F_UPLOAD_FAIL:2400,MSG_F_SELECT_F_FIRST:2401,MSG_F_SIZE_LIMIT:2402,MSG_F_URL_IS_EMPTY:2403,MSG_MERGER_TYPE_INVALID:2450,MSG_MERGER_KEY_INVALID:2451,MSG_MERGER_DOWNLOAD_FAIL:2452,MSG_FORWARD_TYPE_INVALID:2453,MSG_FORWARD_INVALID_ELEMENTS:2454,MSG_MODIFY_CONFLICT:2480,MSG_MODIFY_DISABLED_IN_AV:2481,CONV_NOT_FOUND:2500,USER_OR_GRP_NOT_FOUND:2501,CONV_UN_RECORDED_TYPE:2502,INVALID_CONV_ID:2503,ILLEGAL_GRP_TYPE:2600,ILLEGAL_GRP_ID:2602,CANNOT_FIND_GRP:2603,CANNOT_CHANGE_OWNER_IN_AV:2620,CANNOT_CHANGE_OWNER_TO_SELF:2621,MEMBER_NOT_IN_GRP:2623,JOIN_GRP_FAIL:2660,CANNOT_ADD_MEMBER_IN_AV:2661,CANNOT_JOIN_NON_AV_WITHOUT_LOGIN:2662,NOT_OWNER:2681,INVALID_MEMBER_ROLE:2683,CANNOT_SET_SELF_MEMBER_ROLE:2684,CANNOT_MUTE_SELF:2685,BAN_DURATION_INVALID:2686,OPERATION_NOT_SUPPORTED_IN_AV:2687,NOT_MY_FRIEND:2700,ALREADY_MY_FRIEND:2701,FRIEND_GRP_EXISTED:2710,FRIEND_GRP_NOT_EXIST:2711,FRIEND_APPLICATION_NOT_EXIST:2716,UPDATE_PROFILE_INVALID_PARAM:2721,UPDATE_PROFILE_NO_KEY:2722,CANNOT_ADD_SELF_TO_BLACKLIST:2742,NETWORK_ERROR:2800,NETWORK_TIMEOUT:2801,NO_NETWORK:2805,UNCAUGHT_ERROR:2903,INVALID_OPERATION:2905,INVALID_TRTC_CMD:2995,OVER_FREQUENCY_LIMIT:2996,NO_PROTOCOL:2997,NO_MODULE:2998,SDK_IS_NOT_READY:2999,LOGGING_IN:3e3,LOGIN_FAILED:3001,KICKED_OUT_MULT_DEVICE:3002,KICKED_OUT_MULT_ACCOUNT:3003,KICKED_OUT_USERSIG_EXPIRED:3004,LOGGED_OUT:3005,KICKED_OUT_REST_API:3006,ILLEGAL_TOPIC_ID:3021,NO_USE:3122,PROFANITY_FOUND:3123,OPTIONS_IS_EMPTY:3153,MSG_A2KEY_EXPIRED:20002,ACCOUNT_A2KEY_EXPIRED:70001,HELLO_ANSWER_KICKED_OUT:1002,OPEN_SERVICE_OVERLOAD_ERROR:60022,SIGNALING_INVALID_INVITE_ID:8010,SIGNALING_NO_PERMISSION:8011,SIGNALING_ALREADY_EXISTS:8012,INVALID_CANCEL_MESSAGE:8020,MSG_SEARCH_CURSOR_INVALID:27002,MSG_SEARCH_CURSOR_EXPIRED:27003};function ft(e){var t;if(!e)return"";try{const s=(null===(t=JSON.parse(Me.getStorage("errorMessage")))||void 0===t?void 0:t.errorMessage)||{},{isIntl:n=!1,code:o,replacement1:i="",replacement2:r=""}=e;if(!o)return"";const a=n?`${o}_en`:`${o}_cn`;let c=s[s[a]?a:o]||"";return c&&(i&&(c=c.replace("$replacement1",i)),r&&(c=c.replace("$replacement2",r))),c}catch(e){return console.error("Error parsing stored error messages:",e),""}}class It extends Error{constructor(e){const{functionName:t="Unknown",code:s,message:n=""}=e;let o=n;s&&!n&&(o=ft(e));super(s?`${t} failed. error: {"message": ${o}, "code": ${s}}`:`${t} failed. error: {"message": ${o}}`),this.errorCode=s,this.errorMessage=o}}const Et=e=>"function"==typeof e;function St(e,t,s){const n=s||[];if(!e||!t)return!1;const o=Object.keys(e).filter((e=>!n.includes(e))),i=Object.keys(t).filter((e=>!n.includes(e)));return o.length===i.length&&o.every((n=>!!t.hasOwnProperty(n)&&("object"==typeof e[n]&&null!==e[n]?St(e[n],t[n],s):e[n]===t[n])))}function vt({required:e,rules:t,range:s,value:n,allowEmpty:o,name:i,key:r}){if(void 0===n){if(e){throw new It({functionName:i,message:`[${i}]Missing required params: "${r}"`})}return}let a="";if(!t.some((e=>{return e===(t=n,Object.prototype.toString.call(t).match(/^\[object (.*)\]$/)[1].toLowerCase());var t}))){for(let e=0;e<t.length;e++){let s=t[e];s=s.replace(s[0],s[0].toUpperCase()),a+=`${s}/`}a=a.substring(0,a.length-1);const e=`[${r}] must be type of ${a}, received type: ${function(e){return Reflect.apply(Object.prototype.toString,e,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}(n)}.`;throw new It({functionName:i,message:e})}if(!1===o){if(Array.isArray(n)&&(0===n.length||"string"==typeof n[0]&&""===n[0].trim())){throw new It({functionName:i,message:`cannot be empty: "${r}"`})}if("string"==typeof n&&""===n.trim()){throw new It({functionName:i,message:`cannot be empty: "${r}"`})}}}const Tt=[],yt={},Mt={on:at.notificationCenter.subscribeOuterEvent.bind(at.notificationCenter),off:at.notificationCenter.unSubscribeOuterEvent.bind(at.notificationCenter),destroy:function(){return d(this,void 0,void 0,(function*(){var e,t;try{(null===(e=at.store.get("login"))||void 0===e?void 0:e.isLogin)&&(yield Mt.logout()),at.notificationCenter.emitInnerEvent(_t.DESTROY)}catch(e){console.debug("destroy error: ",e)}finally{at.notificationCenter.emitOuterEvent(lt.SDK_DESTROY,{SDKAppID:null===(t=at.store.get("instance"))||void 0===t?void 0:t.sdkAppId}),Ys.clear(),Js(),at.destroy()}}))},callExperimentalAPI:function(e,t){if(Ot[e])return Ot[e](t);return Promise.reject(new Error(`API ${e} is not found`))}},Ot={};function At(e,t,s){const n=s||e;Mt[e]=(...e)=>(function(e,t,s){if(Array.isArray(e))for(let n=0;n<e.length;n++)vt.call(this,Object.assign(Object.assign({},e[n]),{value:t[n],name:s}));else for(const n in e)vt.call(this,Object.assign(Object.assign({},e[n]),{value:t[0][n],name:s,key:n}))}(yt[n],e,n),function(e){Tt.forEach((t=>{const{interceptor:s,context:n}=t;s.apply(n,[e])}))}(n),t[n].bind(t)(...e))}function Ct(e,t,s){const n=s||e;Ot[e]=t[n].bind(t)}function Dt(e,t){Tt.push({interceptor:e,context:t})}function Lt(e){e&&"object"==typeof e&&Object.assign(yt,e)}function Nt(){return Object.assign(Object.assign({InnerEvent:_t,InnerEventSubType:at.notificationCenter.InnerEventSubType,OuterEvent:lt,SignalingEvent:gt,helper:Object.assign(Object.assign(Object.assign({},at.utils),at.common),{registerApi:At,registerExperimentalAPI:Ct,registerInterceptor:Dt,registerParamsConfig:Lt,ChatError:It})},Mt),at)}var Rt,Pt,wt;!function(e){e[e.USER_INITIATED=0]="USER_INITIATED",e[e.KICKED_OUT=1]="KICKED_OUT"}(Rt||(Rt={})),function(e){e[e.multipleAccount=1]="multipleAccount",e[e.multipleDevice=2]="multipleDevice",e[e.restApi=3]="restApi"}(Pt||(Pt={})),function(e){e[e.multipleDevice=3002]="multipleDevice",e[e.multipleAccount=3003]="multipleAccount",e[e.usersigExpired=3004]="usersigExpired",e[e.restApi=3006]="restApi"}(wt||(wt={}));const kt={[Pt.multipleAccount]:"multipleAccount",[Pt.multipleDevice]:"multipleDevice",[Pt.restApi]:"REST_API_Kick",[wt.multipleAccount]:"multipleAccount",[wt.multipleDevice]:"multipleDevice",[wt.restApi]:"REST_API_Kick",[wt.usersigExpired]:"userSigExpired"},Ut="login_online_presence_task",{ERROR:bt,DESTROY:Ft,FORCE_OFFLINE:Gt}=_t,{KICKED_OUT_MULT_ACCOUNT:$t,KICKED_OUT_MULT_DEVICE:qt,KICKED_OUT_REST_API:xt,ACCOUNT_A2KEY_EXPIRED:Bt,MSG_A2KEY_EXPIRED:Kt}=pt;class Vt{init(){const{notificationCenter:e}=at;e.subscribeInnerEvent(Gt,this._handleForceOfflineFromServerPush,this),e.subscribeInnerEvent(bt,Kt,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(bt,Bt,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(bt,$t,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(bt,qt,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(bt,xt,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(Ft,this._dispose,this)}_handleForceOfflineFromServerPush(e){const{EventArray:t=[]}=(null==e?void 0:e.body)||{};this._extractKickedOutMessages(t).forEach((e=>{const{KickoutMsgNotify:{KickType:t,NewInstInfo:s}}=e;this._processKickedOutReasonInfo({kickedOutReasonCode:t,newInstanceInfo:s})}))}_extractKickedOutMessages(e){return e.reduce(((e,t)=>[...e,...t.C2cNotifyMsgArray||[]]),[]).filter((e=>{var t;return this._isKickedOut(null===(t=null==e?void 0:e.KickoutMsgNotify)||void 0===t?void 0:t.KickType)}))}_handleForceOfflineFromResponse(e){const{errorCode:t}=e;this._processKickedOutReasonInfo({kickedOutReasonCode:t})}_processKickedOutReasonInfo(e){return d(this,void 0,void 0,(function*(){const{kickedOutReasonCode:t}=e;try{yield at.login.loginAction.logout(Rt.KICKED_OUT)}catch(e){console.debug(e)}finally{this._logKickedOutEvent(e),at.notificationCenter.emitOuterEvent(lt.KICKED_OUT,{data:{type:kt[t]},name:lt.KICKED_OUT}),[Pt.restApi,Bt,Kt].includes(t)&&at.channel.reconnect()}}))}_logKickedOutEvent(e){const{kickedOutReasonCode:t,newInstanceInfo:s={}}=e,n=at.ssoLog.createSSOLogData({method:"kickedOut"}),o=`type:${kt[t]} newInstanceInfo: ${JSON.stringify(s)}`;n.setLogInfo({message:o}).end(!0),console.warn(`loginModule.${o}`)}_isKickedOut(e){return[Pt.multipleAccount,Pt.multipleDevice,Pt.restApi].includes(e)}_dispose(){const{notificationCenter:e}=at;e.unSubscribeInnerEvent(Gt,this._handleForceOfflineFromServerPush,this),e.unSubscribeInnerEvent(bt,Bt,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(bt,Kt,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(bt,$t,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(bt,qt,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(bt,xt,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(Ft,this._dispose,this)}}function jt(){return d(this,void 0,void 0,(function*(){const e="im_open_status.wslogin",t=at.common.generateProtocolData({servcmd:e,data:{state:"Online",isWebUniapp:0,InstType:0,customInfo:""}}),s=`${t.head.seq}${e}`;try{const e=yield at.channel.sendPacket(t,{timeout:9e4,requestId:s});if(e){const{HelloInterval:t,InstId:s,TinyId:n,TimeStamp:o,CustomStatus:i,PurchaseBits:r,A2Key:a,RichMsgAuthKey:c,ErrorCode:d,ErrorInfo:l,ActionStatus:u}=e;return{helloInterval:t,instanceID:s,tinyID:n,timeStamp:o,customStatus:i,purchaseBits:r,a2Key:a,authKey:c,errorCode:d,errorInfo:l,actionStatus:u}}}catch(e){throw console.warn(e),e}}))}function Yt(){return function(e,t,s){const n=s.value;return s.value=function(...e){var s;if(!(!0===(null===(s=at.store.get("login"))||void 0===s?void 0:s.isLoggedIn)))throw new It({code:pt.USER_NOT_LOGGED_IN,functionName:t});return n.apply(this,e)},s}}class Ht{constructor(){this._latestLoginAt=0,this._latestSendOnlinePresenceRequestTime=0,this._helloInterval=120}init(){const{notificationCenter:e,store:t}=at;t.set("login",{isReady:!1}),At("login",this),At("logout",this),At("getLoginUser",this),At("isReady",this),e.subscribeInnerEvent(_t.RECONNECTED,this._reLogin,this),at.notificationCenter.subscribeInnerEvent(_t.DESTROY,this._dispose,this)}login(e){return d(this,void 0,void 0,(function*(){at.notificationCenter.emitInnerEvent("BEFORE_LOGIN");const t=at.ssoLog.createSSOLogData({method:"login",eventType:4});try{if(this._validateBeforeLogin(),this._isLoginIn())return this._createRepeatLoginResponse();const t=yield this._performLogin(e);return this._validateAfterLogin(t),this._handleLoginSuccess(t),yield this._ensureAsyncComplete(),this._updateAndEmitSDKReady(),{code:0,data:t}}catch(e){const{errorCode:s}=e,n=new It({functionName:"login",code:s});throw t.setError(n).end(!0),n}finally{this._latestLoginAt=0}}))}_reLogin(){return d(this,void 0,void 0,(function*(){var e;try{if(!this._isLoginIn())return;const t=at.ssoLog.createSSOLogData({method:"reLogin"}),s=yield jt();if(s){const{instanceID:n,customStatus:o}=s;at.store.set("login",{statusInstanceId:n}),at.user.userStatus.setCustomStatus(o),at.notific