@tencentcloud/lite-chat 0.0.1-beta.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.esm.js DELETED
@@ -1,2 +0,0 @@
1
- class e{constructor(){this.listeners={}}on(e,t,n){this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push({fn:t,context:n})}off(e,t,n){var s;t&&(this.listeners[e]=null===(s=this.listeners[e])||void 0===s?void 0:s.filter((e=>{const s=e.fn===t,i=!n||e.context===n;return!(s&&i)})))}emit(e,...t){const n=this.listeners[e];n&&n.forEach((e=>{const{fn:n,context:s}=e;n.apply(s,t)}))}once(e,t,n){const s=(...i)=>{t.apply(n,i),this.off(e,s)};this.on(e,s)}}var t;!function(e){e.BUSINESS_COMMAND="business_command",e.C2C_REALTIME_MESSAGE="C2cMsgArray",e.C2C_MODIFIED_MESSAGE="C2cMsgModNotifys",e.PROFILE_MODIFIED="ProfileDataMod"}(t||(t={}));const n=[{type:"event",value:100,subType:t.BUSINESS_COMMAND},{type:"hasKey",value:"C2cMsgArray",subType:t.C2C_REALTIME_MESSAGE},{type:"hasKey",value:"C2cMsgModNotifys",subType:t.C2C_MODIFIED_MESSAGE},{type:"hasKey",value:"ProfileDataMod",subType:t.PROFILE_MODIFIED}];var s;!function(e){e.SERVER_PUSH_MESSAGE="im_open_push.msg_push",e.ERROR="error"}(s||(s={}));const i={[s.SERVER_PUSH_MESSAGE]:function(e){const{EventArray:t}=(null==e?void 0:e.body)||{};return t.map((e=>{const{Event:t}=e,i=n.find((e=>"event"===e.type&&e.value===t));if(i)return{type:`${s.SERVER_PUSH_MESSAGE}:${i.subType}`,data:e};const o=n.find((t=>"hasKey"===t.type&&Object.prototype.hasOwnProperty.call(e,t.value)));return o?{type:`${s.SERVER_PUSH_MESSAGE}:${o.subType}`,data:e}:void 0}))},[s.ERROR]:function(e){const{errorCode:t}=e;return[{type:`error:${t}`,data:e}]}};const o=new class{constructor(){this._outerEventEmitter=null,this._innerEventEmitter=null,this._outerEventEmitter=new e,this._innerEventEmitter=new e,this.InnerEventSubType=t}subscribeInnerEvent(e,t,n,s){var i,o;if(["string","number"].includes(typeof t)){const o=t,r=n;null===(i=this._innerEventEmitter)||void 0===i||i.on(`${e}:${o}`,r,s)}else{const s=t;null===(o=this._innerEventEmitter)||void 0===o||o.on(e,s,n)}}emitInnerEvent(e,t){var n,s;if(null===(n=this._innerEventEmitter)||void 0===n||n.emit(e,t),Object.keys(i).includes(e)){const n=null===(s=i[e])||void 0===s?void 0:s.call(i,t);null==n||n.forEach((e=>{var t;e&&(null===(t=this._innerEventEmitter)||void 0===t||t.emit(e.type,e.data))}))}}unSubscribeInnerEvent(e,t,n,s){var i,o;if(["string","number"].includes(typeof t)){const o=t,r=n;null===(i=this._innerEventEmitter)||void 0===i||i.off(`${e}:${o}`,r,s)}else{const s=t;null===(o=this._innerEventEmitter)||void 0===o||o.off(e,s,n)}}subscribeOuterEvent(e,t,n){var s;null===(s=this._outerEventEmitter)||void 0===s||s.on(e,t,n)}unSubscribeOuterEvent(e,t,n){var s;null===(s=this._outerEventEmitter)||void 0===s||s.off(e,t,n)}emitOuterEvent(e,t){var n;null===(n=this._outerEventEmitter)||void 0===n||n.emit(e,t)}getOuterEventEmitter(){return this._outerEventEmitter}rest(){this._outerEventEmitter=null,this._innerEventEmitter=null}};function r(e,t,n,s){var i,o=arguments.length,r=o<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,n):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)r=Reflect.decorate(e,t,n,s);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(r=(o<3?i(r):o>3?i(t,n,r):i(t,n))||r);return o>3&&r&&Object.defineProperty(t,n,r),r}function a(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}function c(e,t,n,s){return new(n||(n=Promise))((function(i,o){function r(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(r,a)}c((s=s.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)},d=e=>{if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);if(null===t)return!0;let n=t;for(;null!==Object.getPrototypeOf(n);)n=Object.getPrototypeOf(n);return t===n};function u(e=99999999){return Math.round(Math.random()*e)}function h(e){let t,n,s=e;e.length%8!=0&&(s="0".repeat(8-e.length%8)+e);let i="";for(let e=0,{length:o}=s;e<o;e+=8)t=parseInt(s.slice(e,e+4),2),n=parseInt(s.slice(e+4,e+8),2),i+=base16Map.get(t)+base16Map.get(n);return i}const _={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},g="undefined"!=typeof wx&&"function"==typeof wx.getSystemInfoSync&&Boolean(wx.getSystemInfoSync().fontSizeSetting),m=g&&"function"==typeof wx.createGamePortal,p="undefined"!=typeof qq&&"function"==typeof qq.getSystemInfoSync&&Boolean(qq.getSystemInfoSync().fontSizeSetting),v="undefined"!=typeof tt&&"function"==typeof tt.getSystemInfoSync&&Boolean(tt.getSystemInfoSync().fontSizeSetting),f="undefined"!=typeof swan&&"function"==typeof swan.getSystemInfoSync&&Boolean(swan.getSystemInfoSync().fontSizeSetting),I="undefined"!=typeof my&&"function"==typeof my.getSystemInfoSync&&Boolean(my.getSystemInfoSync().fontSizeSetting),S="undefined"!=typeof jd&&"function"==typeof jd.getSystemInfoSync,E="undefined"!=typeof uni&&"undefined"==typeof window&&"function"==typeof uni.requireNativePlugin,C=g&&"object"==typeof wx.miniapp,O="undefined"!=typeof uni,y=g||p||v||f||I||E||S,M="undefined"==typeof window&&!y&&"undefined"!=typeof global&&void 0!==global.NativeScriptGlobals,T="undefined"!=typeof global&&(void 0!==global.nativeModuleProxy||void 0!==global.ReactNative),D="undefined"!=typeof uni?!y:"undefined"!=typeof window&&!y&&!T,A=p?qq:v?tt:f?swan:I?my:g?wx:E?uni:S?jd:{},L=D&&window&&window.navigator&&window.navigator.userAgent||"",N=/(micromessenger|webbrowser)/i.test(L),w=function(){let e="WEB";return N?e="WEB":p?e="QQ_MP":v?e="TT_MP":f?e="BAIDU_MP":I?e="ALI_MP":g?e=C?"DONUT_NATIVE_APP":"WX_MP":E?e="UNI_NATIVE_APP":M?e="NS_NATIVE_APP":T&&(e="RN_NATIVE_APP"),_[e]}(),R=/iPad/i.test(L),b=/iPhone/i.test(L)&&!R,P=/iPod/i.test(L),k=b||R||P,U=function(){const e=L.match(/OS (\d+)_/i);return e&&e[1]?e[1]:null}(),F=/Android/i.test(L),$=function(){const e=L.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(!e)return null;const t=e[1]&&parseFloat(e[1]),n=e[2]&&parseFloat(e[2]);return t&&n?parseFloat(`${e[1]}.${e[2]}`):t||null}(),G=/Firefox/i.test(L),q=/Edge/i.test(L),B=!q&&/Chrome/i.test(L),x=/MSIE/.test(L)||L.indexOf("Trident")>-1&&L.indexOf("rv:11.0")>-1,j=function(){const e=/MSIE\s(\d+)\.\d/.exec(L);let t=e&&parseFloat(e[1]);return!t&&/Trident\/7.0/i.test(L)&&/rv:11.0/.test(L)&&(t=11),t}(),V=/Safari/i.test(L)&&!B&&!F&&!q,K=/Windows/i.test(L),Y=/MAC OS X/i.test(L),H=D&&"undefined"!=typeof Worker&&!x,W=F||k,J=D&&void 0!==window.tencent_cloud_im_csig_flutter_for_web_25F_cy,z=function(){if("undefined"==typeof window||void 0===window.navigator)return!1;const{standalone:e}=window.navigator;return!(!k||e||V)}();function X(){let e="unknown";if(Y&&(e="mac"),K&&(e="windows"),k&&(e="ios"),F&&(e="android"),y)try{const{platform:t}=wx.getSystemInfoSync();void 0!==t&&(e=t)}catch(e){console.error(e)}return e}const Q=2800,Z=2801,ee=60002,te=3e3,ne="application/x-www-form-urlencoded;charset=UTF-8";function se(e){return c(this,arguments,void 0,(function*({method:e,url:t,data:n,timeout:s=te}){return new Promise(y?(i,o)=>{A.request({url:t,data:n,method:e,timeout:s,header:{"content-type":ne},success:e=>i(e.data),fail:()=>o(new Error(`{"message":"Network error","code":${Q}}`))})}:(i,o)=>{const r=new XMLHttpRequest,a=setTimeout((()=>{r.abort(),o(new Error(`{"message":"Request timeout","code":${Z}}`))}),s);r.onreadystatechange=function(){if(4===r.readyState)if(clearTimeout(a),200===r.status||304===r.status)try{i(r.responseText?JSON.parse(r.responseText):null)}catch(e){i(r.responseText)}else o(new Error(`{"message":"Network error","code":${Q}}`))},r.open(e,t,!0),r.setRequestHeader("Content-type",ne),r.send(n||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(d(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 oe(){let e,t;return{promise:new Promise(((n,s)=>{e=n,t=s})),resolve:e,reject:t}}var re,ae=Object.freeze({__proto__:null,ANDROID_VERSION:$,IE_VERSION:j,IN_ALIPAY_MINI_APP:I,IN_BAIDU_MINI_APP:f,IN_BROWSER:D,IN_DONUT_NATIVE_APP:C,IN_JD_MINI_APP:S,IN_MINI_APP:y,IN_NS_NATIVE_APP:M,IN_QQ_MINI_APP:p,IN_RN_APP:T,IN_TT_MINI_APP:v,IN_UNI_APP:O,IN_UNI_NATIVE_APP:E,IN_WX_MINI_APP:g,IN_WX_MINI_GAME:m,IOS_VERSION:U,IS_ANDROID:F,IS_CHROME:B,IS_EDGE:q,IS_FIREFOX:G,IS_IE:x,IS_IOS:k,IS_IPAD:R,IS_IPHONE:b,IS_IPOD:P,IS_MAC:Y,IS_SAFARI:V,IS_WECHAT:N,IS_WIN:K,IS_WORKER_AVAILABLE:H,MINI_APP_NAMESPACE:A,USER_AGENT:L,base16EncodeBinaryString:h,generatePromise:oe,getPlatformType:X,httpRequest:se,isEmpty:ie,isFlutterWeb:J,isH5:W,isIOSWebView:z,isPlainObject:d,isValidRequestKey:l,platform:w,randomInt:u});class ce{constructor(){this._socket=null}connectSocket(e){return this._socket=new WebSocket(e),this._socket}send(e){var t,n;try{null===(t=this._socket)||void 0===t||t.send(e)}catch(e){null===(n=this._onSendFail)||void 0===n||n.call(this,e)}}bindSocketHandlers(e){const{onOpen:t,onMessage:n,onClose:s,onError:i,onSendFail:o}=e;this._socket&&(this._socket.binaryType="arraybuffer",this._socket.onopen=t,this._socket.onmessage=n,this._socket.onclose=s,this._socket.onerror=i,this._onSendFail=o)}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:n,onClose:s,onError:i,onSendFail:o}=e;this._socket.onClose(s),this._socket.onOpen(t),this._socket.onMessage(n),this._socket.onError(i),this._onSendFail=o}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"}(re||(re={}));class de{constructor(t){this._url="",this._readyState=re.DISCONNECTED,this._url=t,this._id=u(),this._emitter=new e,this._socket=g?new le:new ce,this.connect()}connect(){this.doOpen(),this._bindSocketHandlers()}doOpen(){[re.CONNECTED,re.CONNECTING].includes(this._readyState)||(this._readyState=re.CONNECTING,this._ws=this._socket.connectSocket(this._url))}send(e){this._readyState!==re.CONNECTED?this.reconnect():this._socket.send(e)}reconnect(){[re.CONNECTED,re.CONNECTING].includes(this._readyState)||(this.disconnect(),this.doOpen())}getId(){return this._id}on(e,t,n){this._emitter.on(e,t,n)}off(e,t,n){this._emitter.off(e,t,n)}isConnected(){return this._readyState===re.CONNECTED}disconnect(){this._readyState=re.DISCONNECTED,this._unbindSocketHandlers(),this._socket.disconnect()}_onOpen(e){this._readyState===re.CONNECTING&&(this._readyState=re.CONNECTED,this._emitter.emit("connect",{socketId:this._id,event:e}))}_onMessage(e){this._emitter.emit("message",e)}_onClose(e){this._readyState=re.DISCONNECTED,this._emitter.emit("close",{socketId:this._id,event:e})}_onError(e){this._readyState=re.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 ue="CHINA",he="SINGAPORE",_e="KOREA",ge="GERMANY",me="IND",pe="JPN",ve="USA",fe="INDONESIA",Ie={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"}}},Se={[he]:[[2e7,3e7],[172e7,173e7]],[_e]:[[3e7,4e7],[173e7,174e7]],[ge]:[[4e7,5e7],[174e7,175e7]],[me]:[[5e7,6e7],[175e7,176e7]],[pe]:[[6e7,7e7],[176e7,177e7]],[ve]:[[7e7,8e7],[177e7,178e7]],[fe]:[[8e7,9e7],[178e7,179e7]]};function Ee(e){for(const t of Object.keys(Se))for(const[n,s]of Se[t])if(e>=n&&e<s)return t;return ue}var Ce,Oe=new class{constructor(){this._store=new Map}get(e){return this._store.get(e)}getStorage(e){if(y){if(I){return my.getStorageSync({key:e}).data}return A.getStorageSync(e)}return this._canUseLocalStorage()?localStorage.getItem(e):{}}set(e,t){const n=this._store.get(e)||{};t instanceof Map?this._store.set(e,t):this._store.set(e,Object.assign(Object.assign({},n),t))}setStorage(e,t){y?I?my.setStorageSync({key:e,data:JSON.stringify(t)}):A.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)}},ye="1.0.0";!function(e){e.INITIAL="INITIAL",e.DEFAULT="DEFAULT",e.BACKUP="BACKUP",e.ANYCAST="ANYCAST"}(Ce||(Ce={}));let Me=Ce.INITIAL;function Te(){const e=Math.random();return 0===e?Te():e}function De(e,t){const{isBinary:n=!1}=t||{},s=Oe.get("instance"),{sdkAppId:i,instanceId:o}=s,r=Te(),a=X(),c=function(){const e=X();let t=-1;"ios"===e?t=U||-1:"android"===e&&(t=$||-1);return t}();var l;return`${e}/${n?"binfo":"info"}?${l={sdkappid:i,instanceid:o,random:r,platform:w,host:a,version:c,sdkversion:ye},Object.keys(l).map((e=>`${e}=${l[e]}`)).join("&")}`}var Ae=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 n=Date.now(),s=n-e;this._timeOffsetWithServer=t+s-n}};const Le=16;var Ne=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:n,context:s,isOnce:i=!1,intervalMs:o=Le}=e,r=Math.max(o,Le);return{id:t,nextExecuteTime:Date.now()+r,intervalMs:o,callback:n,context:s,isOnce:i}}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 n=this._taskMap.get(e);n&&(n.intervalMs=t,n.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 we(e){return Object.assign(Object.assign({},function(){const e=Oe.get("login")||{},t=Oe.get("instance")||{};return{ver:"v4",platform:w,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:Ue()}}()),{servcmd:e})}function Re(e){const t=Array.isArray(e)?[]:Object.create(null);for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&l(n)&&null!=e[n]&&(null===e[n]||"object"!=typeof e[n]?t[n]=e[n]:t[n]=Re(e[n]));return t}function be(e){const{servcmd:t,data:n}=e;return Re({head:we(t),body:n})}function Pe(e){const{servcmd:t,data:n}=e,s=function(e){const t=Oe.get("login")||{},n=Oe.get("instance")||{};return{servcmd:e,ver:"v4",platform:w,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:n.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:Ue()}}(t);return Re({head:s,body:n})}let ke=u();function Ue(){return ke=ke<2415919103?ke+1:u(),ke}var Fe,$e=Object.freeze({__proto__:null,generateProtocolData:be,generateSSOLogProtocolData:Pe,generateSequence:Ue,taskScheduler:Ne,timeManager:Ae});!function(e){e[e.info=4]="info",e[e.warning=5]="warning",e[e.error=6]="error"}(Fe||(Fe={}));const Ge={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 qe{constructor(e){this.level=Fe.info,this._canSendLog=!0,this._logCreatedAt=Ae.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:n=0}=e||{};this.eventType=n,this.method=t}setMoreMessage(e){this.moreMessage=`${this.moreMessage} ${e}`}updateLogCreatedAtByTimeOffset(){this._logCreatedAt+=Ae.getTimeOffsetWithServer()}end(e=!1){if(!this._canSendLog)return;const t=Ae.getServerTimeMs();0===this.costTime&&(this.costTime=t-this._logCreatedAt),this.setMoreMessage(`startts:${this._logCreatedAt} endts:${t}`),e?(this._canSendLog=!1,this.timestamp=Ae.getServerTimeMs(),this._ssoLogModule.pushToLogQueue(this._convertSSOLogDataKeyToServe())):setTimeout((()=>{this._canSendLog=!1,this.timestamp=Ae.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=Oe.get("netWorkMonitor"))||void 0===t?void 0:t.isNetworkOnline)&&(e.errorCode&&(this.code=e.errorCode),e.errorMessage&&this.setMoreMessage(e.errorMessage)),this.level=Fe.error,this}setLogInfo(e){return Object.keys(e).forEach((t=>{Object.keys(Ge).includes(t)&&(this[t]=e[t])})),this}setSSOLogModule(e){this._ssoLogModule=e}_convertSSOLogDataKeyToServe(){const e={};return Object.keys(this).forEach((t=>{const n=t;Ge[n]&&(e[Ge[n]]=this[n])})),e}}function Be(){const e=Oe.get("login")||{},t=Oe.get("instance")||{};return{sdk_type:30,sdk_app_id:t.sdkAppId,sdk_version:ye,tiny_id:Number(e.tinyID),user_id:e.userId,platform:w,instance_id:t.instanceId,trace_id:(new Date).getTime()}}var xe;!function(e){e.RECONNECTED="reconnected",e.CLOUD_CONFIG_UPDATE="cloud_config_update"}(xe||(xe={}));var je=xe;const Ve=20,Ke=6e4,Ye=[4,5,6],He=[],We=[],Je="report-logger";var ze=new class{constructor(){this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._reportLevel=[4,5,6],this._minThreshold=Ve,this._maxThreshold=100,this._waitingTime=Ke,this._lastReportAt=Date.now(),this._ssoLogMap=new Map,o.subscribeInnerEvent(je.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),Ne.addTask({id:Je,intervalMs:1e3,callback:this._checkAndReportIfDue,context:this}),this._logQueue=[],this._savePlatFormInfo()}_handleCloudConfigUpdate(e){const{evt_rpt_threshold:t=Ve,evt_rpt_waiting:n=Ke,evt_rpt_level:s=Ye,evt_rpt_sdkappid_bl:i=He,evt_rpt_tinyid_wl:o=We}=e||{};this._sdkAppIdBlackList=i,this._waitingTime=n,this._minThreshold=t,this._reportLevel=s,this._tinyIdWhiteList=o}createSSOLogData(e){const t=new qe(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 c(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 n={Header:Be(),Event:t};yield function(e){const t="imopenstat.tim_web_report_v2",n=Pe({servcmd:t,data:e}),s=`${n.head.seq}${t}`;ot.sendPacket(n,{requestId:s})}(n),this._lastReportAt=Date.now()}))}_savePlatFormInfo(){var e,t;if(g){const n=null===(t=null===(e=wx.getAccountInfoSync)||void 0===e?void 0:e.call(wx))||void 0===t?void 0:t.miniProgram;if(n){const{appId:e,envVersion:t}=n;Oe.set("instance",{appId:e,envVersion:t})}}else D&&Oe.set("instance",{href:window.location.href})}_filterLogs(e){const{tinyID:t}=Oe.get("login")||{},{sdkAppId:n}=Oe.get("instance")||{};return this._sdkAppIdBlackList.includes(n)&&!this._tinyIdWhiteList.includes(t)?[]:e.filter((e=>this._reportLevel.includes(e.level)))}reset(){console.log("SSO_LOG_MODULE.reset"),Ne.removeTask(Je),o.unSubscribeInnerEvent(je.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),this._lastReportAt=0,this._uploadSSOLogData(),this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._minThreshold=Ve,this._maxThreshold=100,this._waitingTime=Ke,this._logQueue=[]}};const Xe=15e3,Qe="Channel",Ze="channel_schedule_task",et="connected",nt="connecting",st="disconnected";function it(e){const t=[];for(let n=0;n<e.length;n+=1){const s=e.charCodeAt(n);if(s>=55296&&s<=56319){const i=e.charCodeAt(++n)-56320+(s-55296<<10)+65536;t.push(240|i>>18,128|i>>12&63,128|i>>6&63,128|63&i)}else s<=127?t.push(s):s<=2047?t.push(192|s>>6,128|63&s):t.push(224|s>>12,128|s>>6&63,128|63&s)}return new Uint8Array(t)}var ot=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=et}init(){Ne.addTask({id:Ze,intervalMs:1e3,callback:this._executeScheduledTaskIfReady,context:this}),this._updateIsBinarySupported(),this._url=function(e){const t=Oe.get("instance"),{sdkAppId:n,testEnv:s}=t,i=Ee(n);return De(s?Ie.TEST[i].DEFAULT:Ie.PRODUCTION[i].INITIAL.replace("*",`${n}`),{isBinary:e})}(this._isBinarySupported),o.subscribeInnerEvent("networkStatusChange",this._handleNetworkStatusChange,this),this.connect()}sendPacket(e,t){var n;const{requestId:s,timeout:i=Xe,canResend:o=!0}=t||{};if(ie(e))return console.warn(`${Qe}.sendPacket: packet is empty `,e),null;const r=JSON.stringify(e);let a=null;if(s){const{resolve:e,reject:t,promise:n}=oe();a=n,this._pendingRequests.set(s,{resolve:e,reject:t,timestamp:Date.now(),uplinkData:r,timeout:i,canResend:o})}const c=this._isBinarySupported?it(r).buffer:r;return null===(n=this._socketAdapter)||void 0===n||n.send(c),a}connect(){var e;this._socketAdapter=new de(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(`${Qe}._connect isWorkerEnabled: false socketID:${t} url:${this._url}`);ze.createSSOLogData({method:"wsConnect"}).setLogInfo({message:`socketID:${t} url:${this._url}`}).end()}disconnect(){var e,t;const n=null===(e=this._socketAdapter)||void 0===e?void 0:e.getId();console.log(`${Qe}.disconnect socketID:${n}`),this._removeEventListeners(),null===(t=this._socketAdapter)||void 0===t||t.disconnect()}getSocketAdapter(){return this._socketAdapter}dispose(){console.log(`${Qe}.dispose`),Ne.removeTask(Ze),o.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 c(this,arguments,void 0,(function*(e=!1){var t;const n=`forcedFlag:${e}_reconnectAttempts:${this._reconnectAttempts}hasFatalError:${this._hasFatalError}isReconnecting:${this._isReconnecting}_currentConnectState:${this._currentConnectState}`;if(console.log(`Channel.reconnect ${n}`),!this._shouldSkipReconnect(e)){this._url=function(e){const t=Oe.get("instance"),{sdkAppId:n,testEnv:s}=t,i=Ee(n);if(s)return De(Ie.TEST[i].DEFAULT,{isBinary:e});const o=Ie.PRODUCTION[i],r=D&&o.ANYCAST;return De({[Ce.INITIAL]:()=>(Me=Ce.DEFAULT,o.DEFAULT),[Ce.DEFAULT]:()=>(Me=Ce.BACKUP,o.BACKUP),[Ce.BACKUP]:()=>(Me=r?Ce.ANYCAST:Ce.DEFAULT,r?o.ANYCAST:o.DEFAULT),[Ce.ANYCAST]:()=>(Me=Ce.DEFAULT,o.ANYCAST="",o.DEFAULT)}[Me](),{isBinary:e})}(this._isBinarySupported);try{if(this._isReconnecting=!0,this._handleConnectStateChange(nt),this._reconnectAttempts>=3)return this._reconnectAttempts=0,void((null===(t=Oe.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(st)));this._reconnectAttempts+=1,this.disconnect(),this.connect()}catch(e){this._isReconnecting=!1,this._handleConnectStateChange(st),console.warn("Reconnection failed:",e)}}}))}_addEventListeners(){var e,t,n,s,i;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===(n=this._socketAdapter)||void 0===n||n.on("close",this._onClose,this),null===(s=this._socketAdapter)||void 0===s||s.on("error",this._onError,this),null===(i=this._socketAdapter)||void 0===i||i.on("sendFail",this._onSendFail,this)}_removeEventListeners(){var e,t,n,s,i;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===(n=this._socketAdapter)||void 0===n||n.off("close",this._onClose,this),null===(s=this._socketAdapter)||void 0===s||s.off("error",this._onError,this),null===(i=this._socketAdapter)||void 0===i||i.off("sendFail",this._onSendFail,this)}_onClose(e){const{socketId:t,event:n}=e||{},s=ze.createSSOLogData({method:"wsOnClose"}),i=`sourceSocketID:${t} currentSocketID:${this._connectionId} code:${null==n?void 0:n.code} reason:${null==n?void 0:n.reason}`,o=0!==this._connectionEstablishedTime?Date.now()-this._connectionEstablishedTime:0;s.setLogInfo({message:o,moreMessage:i,code:null==n?void 0:n.code,costTime:o}).end(!0),console.log(`${Qe}._onClose ${i} connectionDuration: ${o}`),this._isReconnecting&&(this._handleConnectStateChange(st),this._isReconnecting=!1),t===this._connectionId&&this.reconnect()}_onError(e){console.warn(`${Qe}._onError ${JSON.stringify(e)}`),this._handleConnectStateChange(st)}_onSendFail(){this._handleConnectStateChange(st)}_onMessage(e){let t;this._updateHeartbeatTime();try{const n=this._isBinarySupported?function(e){const t=new Uint8Array(e);let n="",s=0;const{length:i}=t;for(;s<i;){let e=t[s],o=0,r=0;if(e<=127?(o=0,r=255&e):e<=223?(o=1,r=31&e):e<=239?(o=2,r=15&e):e<=244&&(o=3,r=7&e),i-s-o>0)for(let n=0;n<o;n+=1)e=t[s+n+1],r=r<<6|63&e;else r=65533,o=i-s;n+=String.fromCodePoint(r),s+=o+1}return n}(e.data):e.data;t=JSON.parse(n)}catch(t){console.error(t);return void ze.createSSOLogData({method:"jsonParseError"}).setLogInfo({message:e.data}).end()}if(!t||!t.head)return;const{seq:n,servcmd:s}=t.head,i=`${n}${s}`;this._pendingRequests.has(i)?this._handleRequestResponse(t):this._handlePushMessage(t)}_handleRequestResponse(e){const{seq:t,servcmd:n}=e.head,{int32_error_code:s,str_error_message:i,ErrorCode:r=s,ErrorInfo:a=i}=(null==e?void 0:e.body)||{},c=`${t}${n}`,{resolve:l,reject:d,timestamp:u,headSeq:h}=this._pendingRequests.get(c);if(this._pendingRequests.delete(c),r&&0!==r)return o.emitInnerEvent("error",{errorCode:r,errorInfo:a}),void d({errorCode:r,errorInfo:a});l(e.body)}_handlePushMessage(e){const{servcmd:t}=e.head,{NeedAck:n,SessionData:s}=e.body;1===n&&this._sendAck(s),o.emitInnerEvent(t,e)}_checkPendingRequestsAndResend(){var e;console.log(`${Qe}._checkPendingRequestsAndResend reConnectFlag:${this._isReconnecting} promiseMap.size:${this._pendingRequests.size}`),null===(e=this._pendingRequests)||void 0===e||e.forEach(((e,t)=>{var n;const{uplinkData:s,canResend:i,resolve:o,reject:r,timeout:a}=e;if(i){this._pendingRequests.set(t,{resolve:o,reject:r,timestamp:Date.now(),uplinkData:s,timeout:a,canResend:i});const e=this._isBinarySupported?it(s).buffer:s;null===(n=this._socketAdapter)||void 0===n||n.send(e)}else this._pendingRequests.delete(t)}))}_onConnect(e){const{socketId:t,event:n={}}=e||{};this._connectionId=t,this._connectionEstablishedTime=Date.now();const s=Date.now()-this._connectionStartTime,i=`${Qe}._onOpen cost:${s} ms. socketID:${t} res:${JSON.stringify(n)}`;console.log(i);ze.createSSOLogData({method:"wsOnOpen"}).setLogInfo({message:i,costTime:s}).end(),this._checkPendingRequestsAndResend(),this._sendHeartbeatIfReady(),this._reconnectAttempts=0,this._isReconnecting&&(o.emitInnerEvent(je.RECONNECTED),this._isReconnecting=!1),this._handleConnectStateChange(et)}_sendAck(e){const t=be({servcmd:"openim.ws_msg_push_ack",data:{SessionData:e}});this.sendPacket(t)}_executeScheduledTaskIfReady(){return c(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 c(this,void 0,void 0,(function*(){var e;const t=be({servcmd:"heartbeat.alive",data:{}});try{const e=`${t.head.seq}${t.head.servcmd}`;yield this.sendPacket(t,{requestId:e,timeout:3e3})}catch(t){const n=null===(e=Oe.get("netWorkMonitor"))||void 0===e?void 0:e.isNetWorkOnline;if(console.debug(`${Qe}._sendHeartbeat failed. isNetWorkOnline:${n} error:`,t),(null==t?void 0:t.code)===ee){this._hasFatalError=!0;return ze.createSSOLogData({method:"error"}).setLogInfo({message:`code:${null==t?void 0:t.code} message:${null==t?void 0:t.message}`}).end(),void this._handleConnectStateChange(st)}n?this.reconnect():this._handleConnectStateChange(st)}}))}_sendHeartbeatIfReady(){return c(this,void 0,void 0,(function*(){this._canSendHeartbeat()&&(this._isHeartbeatInProgress=!0,yield this._sendHeartbeat(),this._isHeartbeatInProgress=!1)}))}_updateHeartbeatTime(){this._nextHeartbeatAt=E?Date.now()+5e3:Date.now()+1e4}_handleNetworkStatusChange(e){console.warn(`${Qe}._handleNetworkStatusChange ${JSON.stringify(e)}`);const{isNetworkOnline:t,networkType:n}=e;t&&"none"!==n&&this._reconnectAttempts<3&&this._socketAdapter?(this._reconnectAttempts+=1,this.reconnect()):(this._handleConnectStateChange(st),this._reconnectAttempts=0)}isPrivateNetWork(){const e=Oe.get("instance")||{};return e.proxyServer&&!e.fileDownloadProxy}_handleConnectStateChange(e){this._currentConnectState!==e&&(console.log(`${Qe}._handleConnectStateChange from ${this._currentConnectState} to ${e}`),this._currentConnectState=e,o.emitOuterEvent("netStateChange",{name:"netStateChange",data:{state:e}}))}_diagnose(){this.isPrivateNetWork()||(this._lastDiagnoseAt=Date.now(),function(e){c(this,void 0,void 0,(function*(){const t=e.split("/")[2];if(!t.startsWith("ws"))return;const n=`https://${t}/v3/netcheck/getconninfo?${e.slice(e.indexOf("info?")+5)}&reqtime=${Date.now()}`;try{yield se({method:"GET",url:n,data:{}})}catch(e){console.warn("diagnoseBySSO failed. error:",e)}}))}(this._url),function(e){c(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 se({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:n,timestamp:s,timeout:i}=t;Date.now()-s>=i&&(this._pendingRequests.delete(e),Date.now()-this._lastDiagnoseAt>=3e4&&this._diagnose(),n({errorCode:Z,errorInfo:"NETWORK_TIMEOUT",data:{requestId:e}}))}}_updateIsBinarySupported(){var e;if(null===(e=Oe.get("instance"))||void 0===e?void 0:e.devMode)return void(this._isBinarySupported=!1);const t=X();(I||g&&"windows"===t||E)&&(this._isBinarySupported=!1)}};const rt={init:function(e){Oe.set("instance",e),ot.init()},destroy:function(){ot.dispose(),Oe.clear(),Ne.dispose()},notificationCenter:o,channel:ot,store:Oe,ssoLog:ze,utils:ae,common:$e};var at;!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"}(at||(at={}));var ct,lt=at;!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"}(ct||(ct={}));var dt,ut=ct;!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"}(dt||(dt={}));var ht,_t=dt;!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 gt=ht;const mt={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 pt(e){var t;if(!e)return"";try{const n=(null===(t=JSON.parse(Oe.getStorage("errorMessage")))||void 0===t?void 0:t.errorMessage)||{},{isIntl:s=!1,code:i,replacement1:o="",replacement2:r=""}=e;if(!i)return"";const a=s?`${i}_en`:`${i}_cn`;let c=n[n[a]?a:i]||"";return c&&(o&&(c=c.replace("$replacement1",o)),r&&(c=c.replace("$replacement2",r))),c}catch(e){return console.error("Error parsing stored error messages:",e),""}}class vt extends Error{constructor(e){const{functionName:t="Unknown",code:n,message:s=""}=e;let i=s;n&&!s&&(i=pt(e));super(n?`${t} failed. error: {"message": ${i}, "code": ${n}}`:`${t} failed. error: {"message": ${i}}`),this.errorCode=n,this.errorMessage=i}}const ft=e=>"function"==typeof e;function It(e,t,n){const s=n||[];if(!e||!t)return!1;const i=Object.keys(e).filter((e=>!s.includes(e))),o=Object.keys(t).filter((e=>!s.includes(e)));return i.length===o.length&&i.every((s=>!!t.hasOwnProperty(s)&&("object"==typeof e[s]&&null!==e[s]?It(e[s],t[s],n):e[s]===t[s])))}function St({required:e,rules:t,range:n,value:s,allowEmpty:i,name:o,key:r}){if(void 0===s){if(e){throw new vt({functionName:o,message:`[${o}]Missing required params: "${r}"`})}return}let a="";if(!t.some((e=>{return e===(t=s,Object.prototype.toString.call(t).match(/^\[object (.*)\]$/)[1].toLowerCase());var t}))){for(let e=0;e<t.length;e++){let n=t[e];n=n.replace(n[0],n[0].toUpperCase()),a+=`${n}/`}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()}(s)}.`;throw new vt({functionName:o,message:e})}if(!1===i){if(Array.isArray(s)&&(0===s.length||"string"==typeof s[0]&&""===s[0].trim())){throw new vt({functionName:o,message:`cannot be empty: "${r}"`})}if("string"==typeof s&&""===s.trim()){throw new vt({functionName:o,message:`cannot be empty: "${r}"`})}}}const Et=[],Ct={},Ot={on:rt.notificationCenter.subscribeOuterEvent.bind(rt.notificationCenter),off:rt.notificationCenter.unSubscribeOuterEvent.bind(rt.notificationCenter),destroy:function(){return c(this,void 0,void 0,(function*(){var e,t;try{(null===(e=rt.store.get("login"))||void 0===e?void 0:e.isLogin)&&(yield Ot.logout()),rt.notificationCenter.emitInnerEvent(ut.DESTROY)}catch(e){console.debug("destroy error: ",e)}finally{rt.notificationCenter.emitOuterEvent(lt.SDK_DESTROY,{SDKAppID:null===(t=rt.store.get("instance"))||void 0===t?void 0:t.sdkAppId}),Ks.clear(),Js(),rt.destroy()}}))},callExperimentalAPI:function(e,t){if(yt[e])return yt[e](t);return Promise.reject(new Error(`API ${e} is not found`))}},yt={};function Mt(e,t,n){const s=n||e;Ot[e]=(...e)=>(function(e,t,n){if(Array.isArray(e))for(let s=0;s<e.length;s++)St.call(this,Object.assign(Object.assign({},e[s]),{value:t[s],name:n}));else for(const s in e)St.call(this,Object.assign(Object.assign({},e[s]),{value:t[0][s],name:n,key:s}))}(Ct[s],e,s),function(e){Et.forEach((t=>{const{interceptor:n,context:s}=t;n.apply(s,[e])}))}(s),t[s].bind(t)(...e))}function Tt(e,t,n){const s=n||e;yt[e]=t[s].bind(t)}function Dt(e,t){Et.push({interceptor:e,context:t})}function At(e){e&&"object"==typeof e&&Object.assign(Ct,e)}function Lt(){return Object.assign(Object.assign({InnerEvent:ut,InnerEventSubType:rt.notificationCenter.InnerEventSubType,OuterEvent:lt,SignalingEvent:_t,helper:Object.assign(Object.assign(Object.assign({},rt.utils),rt.common),{registerApi:Mt,registerExperimentalAPI:Tt,registerInterceptor:Dt,registerParamsConfig:At,ChatError:vt})},Ot),rt)}var Nt,wt,Rt;!function(e){e[e.USER_INITIATED=0]="USER_INITIATED",e[e.KICKED_OUT=1]="KICKED_OUT"}(Nt||(Nt={})),function(e){e[e.multipleAccount=1]="multipleAccount",e[e.multipleDevice=2]="multipleDevice",e[e.restApi=3]="restApi"}(wt||(wt={})),function(e){e[e.multipleDevice=3002]="multipleDevice",e[e.multipleAccount=3003]="multipleAccount",e[e.usersigExpired=3004]="usersigExpired",e[e.restApi=3006]="restApi"}(Rt||(Rt={}));const bt={[wt.multipleAccount]:"multipleAccount",[wt.multipleDevice]:"multipleDevice",[wt.restApi]:"REST_API_Kick",[Rt.multipleAccount]:"multipleAccount",[Rt.multipleDevice]:"multipleDevice",[Rt.restApi]:"REST_API_Kick",[Rt.usersigExpired]:"userSigExpired"},Pt="login_online_presence_task",{ERROR:kt,DESTROY:Ut,FORCE_OFFLINE:Ft}=ut,{KICKED_OUT_MULT_ACCOUNT:$t,KICKED_OUT_MULT_DEVICE:Gt,KICKED_OUT_REST_API:qt,ACCOUNT_A2KEY_EXPIRED:Bt,MSG_A2KEY_EXPIRED:xt}=mt;class jt{init(){const{notificationCenter:e}=rt;e.subscribeInnerEvent(Ft,this._handleForceOfflineFromServerPush,this),e.subscribeInnerEvent(kt,xt,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(kt,Bt,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(kt,$t,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(kt,Gt,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(kt,qt,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(Ut,this._dispose,this)}_handleForceOfflineFromServerPush(e){const{EventArray:t=[]}=(null==e?void 0:e.body)||{};this._extractKickedOutMessages(t).forEach((e=>{const{KickoutMsgNotify:{KickType:t,NewInstInfo:n}}=e;this._processKickedOutReasonInfo({kickedOutReasonCode:t,newInstanceInfo:n})}))}_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 c(this,void 0,void 0,(function*(){const{kickedOutReasonCode:t}=e;try{yield rt.login.loginAction.logout(Nt.KICKED_OUT)}catch(e){console.debug(e)}finally{this._logKickedOutEvent(e),rt.notificationCenter.emitOuterEvent(lt.KICKED_OUT,{data:{type:bt[t]},name:lt.KICKED_OUT}),[wt.restApi,Bt,xt].includes(t)&&rt.channel.reconnect()}}))}_logKickedOutEvent(e){const{kickedOutReasonCode:t,newInstanceInfo:n={}}=e,s=rt.ssoLog.createSSOLogData({method:"kickedOut"}),i=`type:${bt[t]} newInstanceInfo: ${JSON.stringify(n)}`;s.setLogInfo({message:i}).end(!0),console.warn(`loginModule.${i}`)}_isKickedOut(e){return[wt.multipleAccount,wt.multipleDevice,wt.restApi].includes(e)}_dispose(){const{notificationCenter:e}=rt;e.unSubscribeInnerEvent(Ft,this._handleForceOfflineFromServerPush,this),e.unSubscribeInnerEvent(kt,Bt,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(kt,xt,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(kt,$t,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(kt,Gt,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(kt,qt,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(Ut,this._dispose,this)}}function Vt(){return c(this,void 0,void 0,(function*(){const e="im_open_status.wslogin",t=rt.common.generateProtocolData({servcmd:e,data:{state:"Online",isWebUniapp:0,InstType:0,customInfo:""}}),n=`${t.head.seq}${e}`;try{const e=yield rt.channel.sendPacket(t,{timeout:9e4,requestId:n});if(e){const{HelloInterval:t,InstId:n,TinyId:s,TimeStamp:i,CustomStatus:o,PurchaseBits:r,A2Key:a,RichMsgAuthKey:c,ErrorCode:l,ErrorInfo:d,ActionStatus:u}=e;return{helloInterval:t,instanceID:n,tinyID:s,timeStamp:i,customStatus:o,purchaseBits:r,a2Key:a,authKey:c,errorCode:l,errorInfo:d,actionStatus:u}}}catch(e){throw console.warn(e),e}}))}function Kt(){return function(e,t,n){const s=n.value;return n.value=function(...e){var n;if(!(!0===(null===(n=rt.store.get("login"))||void 0===n?void 0:n.isLoggedIn)))throw new vt({code:mt.USER_NOT_LOGGED_IN,functionName:t});return s.apply(this,e)},n}}class Yt{constructor(){this._latestLoginAt=0,this._latestSendOnlinePresenceRequestTime=0,this._helloInterval=120}init(){const{notificationCenter:e,store:t}=rt;t.set("login",{isReady:!1}),Mt("login",this),Mt("logout",this),Mt("getLoginUser",this),Mt("isReady",this),e.subscribeInnerEvent(ut.RECONNECTED,this._reLogin,this),rt.notificationCenter.subscribeInnerEvent(ut.DESTROY,this._dispose,this)}login(e){return c(this,void 0,void 0,(function*(){rt.notificationCenter.emitInnerEvent("BEFORE_LOGIN");const t=rt.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:n}=e,s=new vt({functionName:"login",code:n});throw t.setError(s).end(!0),s}finally{this._latestLoginAt=0}}))}_reLogin(){return c(this,void 0,void 0,(function*(){var e;try{if(!this._isLoginIn())return;const t=rt.ssoLog.createSSOLogData({method:"reLogin"}),n=yield Vt();if(n){const{instanceID:s,customStatus:i}=n;rt.store.set("login",{statusInstanceId:s}),rt.user.userStatus.setCustomStatus(i),rt.notificationCenter.emitInnerEvent(ut.RE_LOGIN);const o=`socketId:${null===(e=rt.channel.getSocketAdapter())||void 0===e?void 0:e.getId()} instanceId:${s}`;t.setLogInfo({message:o}).end(!0)}}catch(e){console.warn(e)}}))}logout(){return c(this,arguments,void 0,(function*(e=Nt.USER_INITIATED){rt.ssoLog.createSSOLogData({method:"logout"}).setLogInfo({moreMessage:`identifier:${this._getCurrentUserId()}`}).end(!0);try{yield this._performLogout(e)}catch(e){const{errorCode:t}=e,n=new vt({functionName:"logout",code:t});this._handleLogoutError(n)}finally{this._handleLogoutCompleted()}return{code:0,data:{}}}))}getLoginUser(){return this._isLoginIn()?this._getCurrentUserId():""}isReady(){var e;return null===(e=rt.store.get("login"))||void 0===e?void 0:e.isReady}_updateAndEmitSDKReady(){rt.store.set("login",{isReady:!0}),setTimeout((()=>{rt.notificationCenter.emitOuterEvent(lt.SDK_READY,{name:lt.SDK_READY})}),1)}_updateAndEmitSDKNotReady(){rt.store.set("login",{isReady:!1}),rt.notificationCenter.emitOuterEvent(lt.SDK_NOT_READY,{name:lt.SDK_NOT_READY})}_validateBeforeLogin(){if(this._isLoginFrequencyExceeded())throw new vt({functionName:"login",code:mt.REPEAT_LOGIN})}_validateAfterLogin(e){var t,n;const s="login";if(!e)throw new vt({functionName:s,message:"login response is empty"});const{tinyID:i,a2Key:o}=e||{},r=rt.ssoLog.getSSOLogData(s);if(!i){const e=new vt({functionName:s,code:mt.NO_TINYID});throw null===(t=null==r?void 0:r.setError)||void 0===t||t.call(r,e).end(),e}if(!o){const e=new vt({functionName:s,code:mt.NO_A2KEY});throw null===(n=null==r?void 0:r.setError)||void 0===n||n.call(r,e).end(),e}}_createRepeatLoginResponse(){var e;return{code:0,data:{actionStatus:"OK",errorCode:0,errorInfo:pt({code:"RepeatLogin",replacement1:null===(e=rt.store.get("login"))||void 0===e?void 0:e.userId}),repeatLogin:!0}}}_performLogin(e){return c(this,void 0,void 0,(function*(){const{userID:t,userSig:n}=e;return rt.store.set("login",{userId:t,userSig:n}),this._latestLoginAt=Date.now(),Vt()}))}_ensureAsyncComplete(){return c(this,void 0,void 0,(function*(){yield new Promise((e=>{setTimeout((()=>e(null)),1)}))}))}_handleLoginSuccess(e){const{timeManager:t}=rt.common,{helloInterval:n,timeStamp:s,customStatus:i,purchaseBits:o}=e,r=1e3*s;t.calculateTimeOffsetWithServer(this._latestLoginAt,r),this._helloInterval=n||120,this._updateLoginStore(e),rt.user.userStatus.setCustomStatus(i),rt.notificationCenter.emitInnerEvent(ut.LOGIN,{purchaseBits:o}),rt.common.taskScheduler.addTask({id:Pt,intervalMs:1e3*this._helloInterval,callback:this._sendOnlinePresenceRequest,context:this}),this._logLoginSuccess(e)}_performLogout(e){return function(e){return c(this,void 0,void 0,(function*(){const{logoutReason:t}=e,n="im_open_status.wslogout",s=rt.common.generateProtocolData({servcmd:n,data:{wslogout_type:t,isWebUniapp:0}}),i=`${s.head.seq}${n}`;return yield rt.channel.sendPacket(s,{requestId:i})}))}({logoutReason:e})}_handleLogoutError(e){rt.ssoLog.getSSOLogData("logout").setError(e).end(),console.error(`logout ${e}`)}_handleLogoutCompleted(){this._updateAndEmitSDKNotReady(),this._reset(),rt.notificationCenter.emitInnerEvent("logout")}_updateLoginStore(e){const{a2Key:t,tinyID:n,instanceID:s,authKey:i}=e;rt.store.set("login",{a2Key:t,tinyID:n,statusInstanceId:s,authKey:i,isLoggedIn:!0})}_logLoginSuccess(e){var t;const n=rt.ssoLog.getSSOLogData("login"),{helloInterval:s,instanceID:i,timeStamp:o,customStatus:r}=e,a=null===(t=rt.channel.getSocketAdapter())||void 0===t?void 0:t.getId(),c=rt.common.timeManager.getTimeOffsetWithServer(),{appId:l,href:d}=rt.store.get("instance")||{},u=`login._logLoginSuccess socketID:${a} scene: helloInterval:${s} instanceID:${i}\n timeStamp:${o} offset:${c} customStatus:${r} href: ${d} appId: ${l}`;console.log(`login ok. ${u}`),n.updateLogCreatedAtByTimeOffset(),n.setLogInfo({moreMessage:u}).end()}_sendOnlinePresenceRequest(){return c(this,void 0,void 0,(function*(){this._latestSendOnlinePresenceRequestTime=Date.now();try{yield function(){const e="im_open_status.wshello",t=rt.common.generateProtocolData({servcmd:e,data:{isWebUniapp:0}}),n=`${t.head.seq}${e}`;return rt.channel.sendPacket(t,{requestId:n})}()}catch(e){console.warn("Login._sendOnlinePresenceRequest error:",e)}}))}_getCurrentUserId(){var e;return null===(e=rt.store.get("login"))||void 0===e?void 0:e.userId}_isLoginIn(){var e;return!0===(null===(e=rt.store.get("login"))||void 0===e?void 0:e.isLoggedIn)}_isLoginFrequencyExceeded(){return Date.now()-this._latestLoginAt<=15e3}_reset(){console.log("Login reset"),rt.common.taskScheduler.removeTask(Pt),this._helloInterval=120,this._latestSendOnlinePresenceRequestTime=0,this._latestLoginAt=0,rt.store.clear("login"),rt.store.set("login",{isReady:!1})}_dispose(){console.log("Login dispose"),this._reset();const{notificationCenter:e}=rt;e.unSubscribeInnerEvent(ut.RECONNECTED,this._reLogin,this),e.unSubscribeInnerEvent(ut.DESTROY,this._dispose,this)}}r([Kt(),a("design:type",Function),a("design:paramtypes",[Number]),a("design:returntype",Promise)],Yt.prototype,"logout",null);const Ht={login:{userID:{required:!0,rules:["string"],allowEmpty:!1},userSig:{required:!0,rules:["string"],allowEmpty:!1}}};class Wt{constructor(){this.loginAction=new Yt,this.kickedOutHandler=new jt,this.loginAction.init(),this.kickedOutHandler.init(),At(Ht)}}var Jt,zt,Xt,Qt;!function(e){e.CONV_C2C="C2C",e.CONV_GROUP="GROUP",e.CONV_TOPIC="TOPIC",e.CONV_SYSTEM="@TIM#SYSTEM"}(Jt||(Jt={})),function(e){e.MSG_PRIORITY_HIGH="High",e.MSG_PRIORITY_NORMAL="Normal",e.MSG_PRIORITY_LOW="Low",e.MSG_PRIORITY_LOWEST="Lowest"}(zt||(zt={})),function(e){e.MSG_TEXT="TIMTextElem",e.MSG_CUSTOM="TIMCustomElem",e.MSG_LOCATION="TIMLocationElem",e.MSG_FACE="TIMFaceElem",e.MSG_IMAGE="TIMImageElem",e.MSG_AUDIO="TIMSoundElem",e.MSG_FILE="TIMFileElem",e.MSG_VIDEO="TIMVideoFileElem",e.MSG_GRP_TIP="TIMGroupTipElem",e.MSG_GRP_SYS_NOTICE="TIMGroupSystemNoticeElem",e.MSG_MERGER="TIMRelayElem"}(Xt||(Xt={})),function(e){e.UNSENT="unSend",e.SUCCESS="success",e.FAIL="fail"}(Qt||(Qt={}));const Zt={};function en(e){if(!e)return 0;if(void 0===Zt[e]){const t=new Date,n=`3${t.getHours()}`.slice(-2),s=`0${t.getMinutes()}`.slice(-2),i=`0${t.getSeconds()}`.slice(-2);Zt[e]=parseInt([n,s,i,"0001"].join(""),10),console.log(`autoIncrementIndex start index:${Zt[e]}`)}else Zt[e]+=1;return Zt[e]}class tn{constructor(e){this.ID="",this.random=0,this.sequence=0,this.nameCard="",this.isRead=!1,this.isPeerRead=!1,this.isDeleted=!1,this.isResend=!1,this.hasRiskContent=!1,this._onlineOnlyFlag=!1,this.atUserList=[],this._groupAtInfoList=[],this.isBroadcastMessage=!1,this.priority=zt.MSG_PRIORITY_NORMAL,this._relayFlag=!1;const{clientTime:t=rt.common.timeManager.getServerTimeSeconds()||0,senderTinyID:n,currentUser:s,needReadReceipt:i,isSupportExtension:o,customModerationConfigurationId:r,to:a,from:c,nick:l="",avatar:d="",time:u,messageControlInfo:h,tinyID:_,cloudCustomData:g="",messageLifeTime:m,messageVersion:p=0,conversationType:v,sequence:f,checkResult:I=0,isPlaceMessage:S=0,messageFlagBits:E,receiverList:C,isSystemMessage:O=!1,status:y=Qt.SUCCESS,revokeReason:M="",conversationSubType:T,clientSequence:D,protocol:A="JSON",revokerInfo:L={userID:"",nick:"",avatar:""},readReceiptInfo:N={readCount:void 0,unreadCount:void 0,isPeerRead:void 0,timestamp:0},random:w}=e;var R;this.clientTime=t,this.senderTinyID=n||_,this.needReadReceipt=!0===i||1===i,this.isSupportExtension=!0===o||1===o,this._cmConfigID=r,this.to=a,this.nick=l,this.avatar=d,this.protocol=A,this.random=void 0===w?(R=R||99999999,Math.round(Math.random()*R)):w,this.time=u||Math.ceil(Date.now()/1e3),this._isExcludedFromLastMessage=1===(null==h?void 0:h.excludedFromLastMessage),this._isExcludedFromUnreadCount=1===(null==h?void 0:h.excludedFromUnreadCount),this.isModified=!!p,this.cloudCustomData=g,this.messageLifeTime=m,this.from=c||null,this.sequence=f||0,this.conversationType=v||Jt.CONV_C2C,this.hasRiskContent=I>1,this.version=p,this.isPlaceMessage=S,this.isRevoked=2===S||8===E,this.isSystemMessage=O,this.readReceiptInfo=N,this.revokeReason=M,this.revokerInfo=L,this._receiverList=C,this.conversationSubType=T,this.revoker=(null==L?void 0:L.revoker)||"",this.clientSequence=D||f||0,this.status=y,this.reInitialize(s),this._initC2CReadReceiptInfo(e)}getElements(){return this._elements}isOnlineMessage(){return 0===this.messageLifeTime}setElement(e){Array.isArray(e)?this._elements=e:this._elements=[e],this._updatePayloadAndType()}convertElementsToBackendFormat(){return this._elements?Array.isArray(this._elements)?this._elements.map((e=>e.convertToBackendFormat())):this._elements.convertToBackendFormat():null}_updatePayloadAndType(){this._elements[0]&&(this.payload=this._elements[0].content,this.type=this._elements[0].type)}_initC2CReadReceiptInfo(e){const{readReceiptSentByPeer:t,timestamp:n=0}=e;this.conversationType===Jt.CONV_C2C&&!0===this.needReadReceipt&&(this.readReceiptInfo.isPeerRead=1===t,this.readReceiptInfo.timestamp=n)}reInitialize(e){e&&(this.status=this.from?Qt.SUCCESS:Qt.UNSENT,!this.from&&(this.from=e)),this._initFlow(e),this._initSequence(e),this._concatConversationID(e),this._generateMessageID()}_concatConversationID(e){let t="";const n=this.conversationType;n!==Jt.CONV_SYSTEM?(t=n===Jt.CONV_C2C?e===this.from?this.to:this.from:this.to,this.conversationID=t?`${n}${t}`:null):this.conversationID=Jt.CONV_SYSTEM}_initFlow(e){e&&(e===this.from?(this.flow="out",this.isRead=!0):this.flow="in")}_initSequence(e){0===this.clientSequence&&e&&(this.clientSequence=en(e)),0===this.sequence&&this.conversationType===Jt.CONV_C2C&&(this.sequence=this.clientSequence)}_generateMessageID(){this.from===Jt.CONV_SYSTEM&&(this.senderTinyID="144115198244471703"),this.ID=`${this.senderTinyID}-${this.clientTime}-${this.random}`}}class nn{static parseServerPushElement(e){const{MsgContent:t={}}=e,{Data:n,Ext:s,Desc:i}=t;return new nn({data:n,description:i,extension:s})}constructor(e){this.type=Xt.MSG_CUSTOM;const{data:t="",description:n="",extension:s=""}=e;this.content={data:t,description:n,extension:s}}convertToBackendFormat(){const{data:e,description:t,extension:n}=this.content;return{MsgType:this.type,MsgContent:{Data:e,Ext:n,Desc:t}}}}class sn{constructor(){this._elementClassMap={[Xt.MSG_CUSTOM]:nn}}init(){Mt("createCustomMessage",this)}registerElementClass(e,t){var n;void 0!==(n=t).prototype&&"constructor"in n.prototype&&(this._elementClassMap[e]=t)}getElementClass(e){return this._elementClassMap[e]}createMessage(e){var t,n;const{userId:s,tinyID:i}=rt.store.get("login")||{},{nick:o="",avatar:r=""}=(null===(n=null===(t=null==rt?void 0:rt.user)||void 0===t?void 0:t.userProfile)||void 0===n?void 0:n.getMyProfileCacheThenServer())||{},a=Object.assign(Object.assign({},e),{currentUser:s,senderTinyID:i,avatar:r,nick:o});return new tn(a)}createCustomMessage(e){const t=this.createMessage(e),n=this._elementClassMap[Xt.MSG_CUSTOM];if(!t)return null;if(n){const s=new n(e.payload);t.setElement(s)}return t}}function on(e){const t=e.lastIndexOf(".");return-1===t?e:e.slice(0,t)}function rn(e){const{androidInfo:t={},androidOPPOChannelID:n=""}=e,s=t.OPPOChannelID||n;return Object.assign(Object.assign({},t),{Sound:on(t.sound||""),OPPOChannelID:s,GoogleChannelID:t.FCMChannelID||""})}function an(e){const{apnsInfo:t={},ignoreIOSBadge:n=!1,disableVoipPush:s}=e,i=!0===t.ignoreIOSBadge||!0===n?1:0;let o;return void 0!==s&&(o=!1===s?1:0),void 0!==t.disableVoipPush&&(o=!1===t.disableVoipPush?1:0),Object.assign(Object.assign({},t),{badgeMode:i,isVoipPush:o})}function cn(e){return rt.utils.isPlainObject(e)?{PushFlag:!0===e.disablePush?1:0,Title:e.title||"",Desc:e.description||"",Ext:e.extension||"",ApnsInfo:an(e),AndroidInfo:rn(e)}:null}r([Kt(),a("design:type",Function),a("design:paramtypes",[Object]),a("design:returntype",void 0)],sn.prototype,"createCustomMessage",null);const{isPlainObject:ln}=rt.utils;function dn(e,t){var n;const s=function(e,t={}){const{onlineUserOnly:n,messageControlInfo:s,offlinePushInfo:i={}}=t;!0===n&&(i.disablePush=!0);let o="";"string"==typeof e.cloudCustomData&&e.cloudCustomData.length>0&&(o=e.cloudCustomData);const r=[];if(s&&ln(s)){const{excludedFromUnreadCount:e,excludedFromLastMessage:t,excludedFromContentModeration:n}=s;!0===e&&r.push("NoUnread"),!0===t&&r.push("NoLastMsg"),!0===n&&r.push("NoMsgCheck")}return{onlineUserOnly:n,cloudCustomData:o,messageControlInfo:r,offlinePushInfo:i}}(e,t),{onlineUserOnly:i,cloudCustomData:o,messageControlInfo:r,offlinePushInfo:a}=s,c=!0===i?0:void 0,l=JSON.parse(JSON.stringify(e.convertElementsToBackendFormat()));return{servcmd:"openim.sendmsg",data:{From_Account:null===(n=rt.store.get("login"))||void 0===n?void 0:n.userId,To_Account:e.to,MsgBody:l,CloudCustomData:o,MsgSeq:e.sequence,MsgRandom:e.random,MsgLifeTime:c,From_AccountNick:e.nick,From_AccountHeadurl:e.avatar,SendMsgControl:0!==c?r:void 0,MsgClientTime:e.clientTime,IsNeedReadReceipt:!0===e.needReadReceipt?1:0,SupportMessageExtension:!0===e.isSupportExtension?1:0,IsRelayMsg:!0===e._relayFlag?1:0,cmConfigID:e._cmConfigID,OfflinePushInfo:cn(a)}}}const{isPlainObject:un}=rt.utils;class hn{init(){Mt("sendMessage",this)}sendMessage(e,t){return c(this,void 0,void 0,(function*(){const n=rt.ssoLog.createSSOLogData({method:"sendMessage"});let s=!1;const{messageStore:i}=rt.message||{};try{const{messageControlInfo:o}=t||{};let r=null;if(i.addRandomOfSentMessage(e.random),e.conversationType===Jt.CONV_C2C?(s=!0===(null==t?void 0:t.onlineUserOnly),r=yield this._sendC2cMessage(e,t)):(e.conversationType,Jt.CONV_GROUP),r){const{messageDropReason:a,sequence:c,isResend:l,time:d}=r;if(e.status=Qt.SUCCESS,e.time=d,a&&this._logRateLimitInfo(e,c),!0===l){const t=i.findMessage(e.ID);t&&(console.log(`sendMessage resend ok. ID:${t.ID}`),i.deleteConversationMessage(t))}return s?e._onlineOnlyFlag=!0:(i.storeConversationMessage(e),this._applySentMessageControlInfo(e,o),this._emitOnlineMessageSent(e)),n.setLogInfo({message:`options: ${JSON.stringify(t)}`}).end(),{code:0,data:{message:e}}}}catch(t){e.status=Qt.FAIL,i.removeRandomOfSentMessage(e.random);const{errorCode:n,errorInfo:o=""}=t||{};this._hasRiskContent(n)&&(e.hasRiskContent=!0),s||this._isRejectedByRestApi(n)||i.storeConversationMessage(e);const r=new vt({code:n});throw this._logSendMessageError({message:e,error:r}),r}}))}_hasRiskContent(e){return 80001===e||80004===e}_isRejectedByRestApi(e){return e>=10100&&e<=10200||e>=120001&&e<=13e4}_logSendMessageError({message:e,error:t}){const n=rt.ssoLog.createSSOLogData({method:"sendMessage"});let s=`head.seq: type:${e.type} from:${e.from} to:${e.to}`;if(rt.utils.IN_BROWSER){if("connection"in navigator){const e=navigator.connection;s+=` downlink:${e.downlink} effectiveType:${e.effectiveType} rtt:${e.rtt}`}if("memory"in window.performance){const e=window.performance.memory;s+=` usedJSHeapSize:${e.usedJSHeapSize} totalJSHeapSize:${e.totalJSHeapSize} jsHeapSizeLimit:${e.jsHeapSizeLimit}`}}n.setLogInfo({message:s}).setError(t).end()}_emitOnlineMessageSent(e){const t=e._isExcludedFromLastMessage?"":e;rt.notificationCenter.emitInnerEvent("OnlineMessageSent",{message:e,lastMessage:t,unreadCount:0})}_applySentMessageControlInfo(e,t){t&&un(t)&&(!0===t.excludedFromLastMessage&&(e._isExcludedFromLastMessage=!0),!0===t.excludedFromUnreadCount&&(e._isExcludedFromUnreadCount=!0))}_logRateLimitInfo(e,t){const n=rt.ssoLog.createSSOLogData({method:"messageDropReason"}),s=`from:${e.from} to:${e.to} sequence:${t} messageDropReason:${messageDropReason}`;n.setLogInfo({message:s}).end(),console.warn(`sendMessage ${s}`)}_sendC2cMessage(e,t){return c(this,void 0,void 0,(function*(){const n=yield function(e,t){return c(this,void 0,void 0,(function*(){const n=dn(e,t),s=rt.common.generateProtocolData(n),i=`${s.head.seq}${s.head.servcmd}`,o=yield rt.channel.sendPacket(s,{requestId:i});return o?{time:o.MsgTime,messageDropReason:o.MsgDropReason}:null}))}(e,t),{messageStore:s}=rt.message||{};let i=!1;const{conversationID:o}=e,r=s.getLatestMsgSentByMe(o);if(r){const{nick:t,avatar:n}=r;t===e.nick&&n===e.avatar||(i=!0),i&&s.updateNickAndAvatarOfSentMessage({conversationID:o,latestNick:e.nick,latestAvatar:e.avatar,isSentByMe:!0})}return n}))}}function _n(e){const{From_Account:t,From_AccountHeadurl:n,From_AccountNick:s,IsNeedReadReceipt:i,IsSyncMsg:o,MsgBody:r,MsgClientTime:a,MsgLifeTime:c,MsgRandom:l,MsgSeq:d,MsgTimeStamp:u,SendMsgControl:h,SupportMessageExtension:_,To_Account:g,TinyId:m,MsgCheckResult:p,CloudCustomData:v}=e;return{from:t,avatar:n,nick:s,needReadReceipt:1===i,isSyncMessage:o,clientTime:a,messageLifeTime:c,random:l,sequence:d,time:u,messageControlInfo:h,isSupportExtension:_,to:g,tinyID:m,checkResult:p,cloudCustomData:v,elements:mn(r)}}function gn(e){const{From_Account:t,MsgBody:n,MsgClientTime:s,MsgRandom:i,MsgSeq:o,MsgTimeStamp:r,To_Account:a,MsgVersion:c,CloudCustomData:l}=e;return{from:t,clientTime:s,random:i,sequence:o,time:r,to:a,elements:mn(n),messageVersion:c,cloudCustomData:l}}function mn(e){if(!e)return null;if(Array.isArray(e))return e.map((e=>{const t=rt.message.messageFactory.getElementClass(e.MsgType);return null==t?void 0:t.parseServerPushElement(e)}));const t=rt.message.messageFactory.getElementClass(e.MsgType);return null==t?void 0:t.parseServerPushElement(e)}r([Kt(),a("design:type",Function),a("design:paramtypes",[Function,Object]),a("design:returntype",Promise)],hn.prototype,"sendMessage",null);var pn=Object.freeze({__proto__:null,autoIncrementIndex:en,parseServerPushC2CModifyMessage:gn,parseServerPushMessage:_n,parseServerPushMessageElement:mn});class vn{constructor(e){this.value=e,this.next=null}}class fn{constructor(e){this.head=null,this.tail=null,this.size=0,this.capacity=e}append(e){this.size>=this.capacity&&this.removeHead();const t=new vn(e);this.head?(this.tail.next=t,this.tail=t):(this.head=t,this.tail=t),this.size+=1}delete(e){if(!this.head)return;if(this.head.value===e)return void(this.head=this.head.next);let t=this.head;for(;t.next;){if(t.next.value===e)return void(t.next=t.next.next);t=t.next}}has(e){if(!this.head)return!1;let t=this.head,n=!1;for(;t;)t.value===e&&(n=!0),t=t.next;return n}removeHead(){this.head&&(this.head===this.tail?(this.head=null,this.tail=null):this.head=this.head.next,this.size-=1)}peek(){var e;return null===(e=this.head)||void 0===e?void 0:e.value}length(){return this.size}isEmpty(){return 0===this.size}isFull(){return this.size===this.capacity}clear(){this.head=null,this.tail=null,this.size=0}}class In{constructor(){this._conversationToMessageMap=new Map,this._latestMessageSentByPeerMap=new Map,this._latestMessageSentByMeMap=new Map,this._randomOfSentMessageList=new fn(100),this._hoppingMsgMap=new Map,rt.notificationCenter.subscribeInnerEvent(ut.LOGOUT,this._reset,this),rt.notificationCenter.subscribeInnerEvent(ut.DESTROY,this._dispose,this)}storeConversationMessage(e,t=!1){const{conversationID:n}=e;if(!n)return;if(this._conversationToMessageMap.has(n)||this._conversationToMessageMap.set(n,new Map),this._shouldSkipStoreMessage(e,t))return;const s=this._getUniqueIdOfMessage(e);this._conversationToMessageMap.get(n).set(s,e),this._updateLatestMessageMap(e)}_updateLatestMessageMap(e){const{conversationID:t}=e;"out"===e.flow?this._setLatestMsgSentByMe(t,e):t.startsWith("C2C")&&this._setLatestMsgSentByPeer(t,e)}_shouldSkipStoreMessage(e,t){const n=this._getUniqueIdOfMessage(e),s=this._conversationToMessageMap.get(e.conversationID);if(null==s?void 0:s.has(n)){const e=null==s?void 0:s.get(n);if(!t||!0===(null==e?void 0:e.isModified))return!1}return!0}deleteConversationMessage(e){var t;const{conversationID:n=""}=e,s=this._getUniqueIdOfMessage(e);this._conversationToMessageMap.has(n)&&(null===(t=this._conversationToMessageMap.get(n))||void 0===t||t.delete(s))}modifyConversationMessage(e,t){if(!this._conversationToMessageMap.has(e))return{isUpdated:!1,message:null};const n=this._getUniqueIdOfMessage(t),s=this._getMessageFromLocalMessageAndHoppingMessage(e,n);if(s){const{messageVersion:e,elements:n,cloudCustomData:i,checkResult:o=0}=t,r=o>1;return console.log(`conversationToMessageMap modifyConversationMessage localVersion:${s.version} remoteVersion:${e}`),s.version<e?(s.version=e,s._elements=JSON.parse(JSON.stringify(n)),s.payload=s._elements[0].content,s.type=s._elements[0].type,s.cloudCustomData=i,s.isModified=!0,s.hasRiskContent=r,{isUpdated:!0,message:s}):{isUpdated:!1,message:s}}return{isUpdated:!1,message:null}}_getMessageFromLocalMessageAndHoppingMessage(e,t){var n;if(this._conversationToMessageMap.has(e))return null===(n=this._conversationToMessageMap.get(e))||void 0===n?void 0:n.get(t);let s;if(this._hoppingMsgMap.has(e)){const n=[...this._hoppingMsgMap.get(e).values()];for(let e=0;e<n.length;e+=1)if(this._getUniqueIdOfMessage(n[e])===t){s=n[e];break}}return s}findMessage(e){let t=null;return Array.from(this._conversationToMessageMap.values()).forEach((n=>{const s=Array.from(n.values());for(let n=0;n<s.length;n+=1)if(s[n].ID===e){t=s[n];break}})),t}deleteConversationMessageList(e){this._conversationToMessageMap.has(e)&&(this._conversationToMessageMap.delete(e),this._latestMessageSentByMeMap.delete(e),this._latestMessageSentByPeerMap.delete(e))}_getUniqueIdOfMessage(e){const{from:t,to:n,random:s,sequence:i,time:o}=e;return`${t}-${n}-${s}-${i}-${o}`}_setLatestMsgSentByPeer(e,t){this._latestMessageSentByPeerMap.set(e,t)}_setLatestMsgSentByMe(e,t){this._latestMessageSentByMeMap.set(e,t)}getLatestMsgSentByPeer(e){return this._latestMessageSentByPeerMap.get(e)}getLatestMsgSentByMe(e){return this._latestMessageSentByMeMap.get(e)}addRandomOfSentMessage(e){this._randomOfSentMessageList.append(e)}removeRandomOfSentMessage(e){this._randomOfSentMessageList.delete(e)}updateNickAndAvatarOfSentMessage(e){const{conversationID:t="",latestAvatar:n,latestNick:s,isSentByMe:i=!0}=e,o=this._conversationToMessageMap.get(t);if(!o)return;const r=Array.from(o.values()),a=i?"out":"in";r.forEach((e=>{const{nick:t,avatar:i,flow:o}=e;o===a&&(t!==s&&(e.nick=s),i!==n&&(e.avatar=n))}))}isInMessageList(e){var t;const{conversationID:n}=e;if(!n)return!1;if(!this._conversationToMessageMap.has(n))return!1;const s=this._getUniqueIdOfMessage(e);return null===(t=this._conversationToMessageMap.get(n))||void 0===t?void 0:t.has(s)}isMessageSentByCurrentInstance(e){const{random:t}=e;return this._randomOfSentMessageList.has(t)}_reset(){this._conversationToMessageMap.clear(),this._latestMessageSentByPeerMap.clear(),this._latestMessageSentByMeMap.clear(),this._hoppingMsgMap.clear(),this._randomOfSentMessageList.clear()}_dispose(){this._reset(),rt.notificationCenter.unSubscribeInnerEvent(ut.LOGOUT,this._reset,this),rt.notificationCenter.unSubscribeInnerEvent(ut.DESTROY,this._dispose,this)}}class Sn{init(){Mt("modifyMessage",this)}modifyMessage(e){return c(this,void 0,void 0,(function*(){const t=rt.ssoLog.createSSOLogData({method:"modifyMessage"}),{to:n,payload:s,sequence:i,conversationType:o,random:r,time:a,from:l,type:d}=e;if(!this._canModifyMessageElement(d))return void t.setLogInfo({message:`can not modify message element. message type: ${d}`}).end();const u=e.getElements();u.length>1&&(u[0].type=d,u[0].content=s);try{let s=null,d=null;if(t.setLogInfo({message:`to:${n}`}),o===Jt.CONV_C2C)return s=yield function(e){return c(this,void 0,void 0,(function*(){const t="openim.modify_c2c_msg",{from:n,to:s,version:i=0,sequence:o,random:r,time:a,type:c,cloudCustomData:l}=e,d=rt.common.generateProtocolData({servcmd:t,data:{From_Account:n,To_Account:s,MsgVersion:i,MsgSeq:o,MsgRandom:r,MsgTime:a,MsgType:c,MsgBody:e.convertElementsToBackendFormat(),CloudCustomData:l}}),u=`${d.head.seq}${t}`;try{const e=yield rt.channel.sendPacket(d,{requestId:u});if(e){const{MsgBody:t,MsgVersion:n,CloudCustomData:s}=e;return{elements:t,messageVersion:n,cloudCustomData:s}}}catch(e){console.warn(e)}}))}(e),t.end(),d={conversationType:o,from:l,to:n,time:a,random:r,sequence:i,elements:null==s?void 0:s.elements,cloudCustomData:null==s?void 0:s.cloudCustomData,messageVersion:null==s?void 0:s.messageVersion,conversationID:`${o}${n}`},this._handleC2CModifyMessageSuccess(d),{code:0,data:{message:e}}}catch(e){const{errorCode:t}=e||{},n=new vt({functionName:"modifyMessage",code:t});throw this._logModifyMessageError(n),n}}))}_logModifyMessageError(e){rt.ssoLog.getSSOLogData("modifyMessage").setError(e).end()}_handleC2CModifyMessageSuccess(e){const{conversationID:t}=e,{isUpdated:n,message:s}=rt.message.messageStore.modifyConversationMessage(t,e);!0===n&&rt.notificationCenter.emitOuterEvent(lt.MESSAGE_MODIFIED,[s]),rt.notificationCenter.emitInnerEvent("ModifyMessageSuccess",e)}_canModifyMessageElement(e){return[Xt.MSG_TEXT,Xt.MSG_CUSTOM,Xt.MSG_LOCATION,Xt.MSG_FACE].includes(e)}}r([Kt(),a("design:type",Function),a("design:paramtypes",[Function]),a("design:returntype",Promise)],Sn.prototype,"modifyMessage",null);class En{init(){const{notificationCenter:e}=rt,{InnerEventSubType:t}=e;e.subscribeInnerEvent("im_open_push.msg_push",t.C2C_REALTIME_MESSAGE,this._handleC2CMessagePush,this),e.subscribeInnerEvent("im_open_push.msg_push",t.C2C_MODIFIED_MESSAGE,this._handleC2CMessageModify,this),e.subscribeInnerEvent(ut.DESTROY,this._dispose,this)}_handleC2CMessagePush(e){const{messageStore:t}=rt.message||{},n=[];e.C2cMsgArray.forEach((e=>{const s=this._generateC2CMessage(e);this._updateMessageProfile(s);let i=1===s.isModified;t.isMessageSentByCurrentInstance(s)?s.isModified=i:i=!1,s.isOnlineMessage()?(s._onlineOnlyFlag=!0,t.isMessageSentByCurrentInstance(s)||n.push(s)):t.isInMessageList(s)||(t.storeConversationMessage(s),t.isMessageSentByCurrentInstance(s)&&!i||n.push(s))})),this._emitMessageEvents(n)}_emitMessageEvents(e){const t=null==e?void 0:e.filter((e=>!0===(null==e?void 0:e.isModified)));t.length>0&&rt.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:t});const n=null==e?void 0:e.filter((e=>!(null==e?void 0:e.isModified)));n.length>0&&rt.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:n})}_generateC2CMessage(e){const t=Jt.CONV_C2C,n=_n(e),s=rt.message.messageFactory.createMessage(Object.assign(Object.assign({},n),{conversationType:t})),{elements:i}=n;return s.setElement(i),s}_updateMessageProfile(e){var t;const{messageStore:n}=rt.message||{},s=null===(t=rt.store.get("login"))||void 0===t?void 0:t.userId,{from:i,nick:o,avatar:r,conversationID:a=""}=e;if(i!==s){const t=n.getLatestMsgSentByPeer(a);if(t){const{nick:s,avatar:i}=t;o&&r?o===s&&r===i||n.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:o,latestAvatar:r,isSentByMe:!1}):(e.nick=s,e.avatar=i)}}else{const e=n.getLatestMsgSentByMe(a);!e||o===e.nick&&r===e.avatar||n.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:o,latestAvatar:r,isSentByMe:!0})}}_updateMessageListDueToModify(e){const{conversationID:t}=e,{isUpdated:n,message:s}=rt.message.messageStore.modifyConversationMessage(t,e);!0===n&&rt.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[s]}),rt.notificationCenter.emitInnerEvent("ModifyMessageSuccess",e)}_handleC2CMessageModify(e){e.C2cMsgModNotifys.forEach((e=>{var t;const n=Jt.CONV_C2C;let s=gn(e);const{to:i,from:o}=s;let r=`${n}${i}`;i===(null===(t=rt.store.get("login"))||void 0===t?void 0:t.userId)&&(r=`${n}${o}`),s=Object.assign({conversationType:n,conversationID:r},s),this._updateMessageListDueToModify(s)}))}_dispose(){const{notificationCenter:e}=rt,{InnerEventSubType:t}=e;rt.notificationCenter.unSubscribeInnerEvent("im_open_push.msg_push",t.C2C_REALTIME_MESSAGE,this._handleC2CMessagePush,this),rt.notificationCenter.unSubscribeInnerEvent("im_open_push.msg_push",t.C2C_MODIFIED_MESSAGE,this._handleC2CMessageModify,this),rt.notificationCenter.unSubscribeInnerEvent(ut.DESTROY,this._dispose,this)}}const Cn={createCustomMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1},payload:{required:!0,rules:["object"],allowEmpty:!1},cloudCustomData:{required:!1,rules:["string"],allowEmpty:!1},priority:{required:!1,rules:["string"],allowEmpty:!1},customModerationConfigurationID:{required:!1,rules:["string"],allowEmpty:!1}},sendMessage:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"options",required:!1,rules:["object"],allowEmpty:!1}]};class On{constructor(){this.messageHelper=pn,this.messageFactory=new sn,this.messageSender=new hn,this.messageAction=new Sn,this.c2cMessageReceiver=new En,this.messageStore=new In,this.messageSender.init(),this.messageFactory.init(),this.messageAction.init(),this.c2cMessageReceiver.init(),At(Cn)}}function yn(){return rt.store.get("login").userId}const Mn="Tag_Profile_IM_",Tn=100,Dn=500,An={NICK:`${Mn}Nick`,GENDER:`${Mn}Gender`,BIRTHDAY:`${Mn}BirthDay`,LOCATION:`${Mn}Location`,SELFSIGNATURE:`${Mn}SelfSignature`,ALLOWTYPE:`${Mn}AllowType`,LANGUAGE:`${Mn}Language`,AVATAR:`${Mn}Image`,MESSAGESETTINGS:`${Mn}MsgSettings`,ADMINFORBIDTYPE:`${Mn}AdminForbidType`,LEVEL:`${Mn}Level`,ROLE:`${Mn}Role`},Ln="USER_STATUS",Nn=1,wn={userID:"",nick:"",gender:"Gender_Type_Unknown",birthday:0,location:"",selfSignature:"",allowType:"AllowType_Type_AllowAny",language:0,avatar:"",messageSettings:0,adminForbidType:"AdminForbid_Type_None",level:0,role:0,lastUpdatedTime:0,profileCustomField:[]},Rn=new Map([[An.NICK,"nick"],[An.GENDER,"gender"],[An.BIRTHDAY,"birthday"],[An.LOCATION,"location"],[An.SELFSIGNATURE,"selfSignature"],[An.ALLOWTYPE,"allowType"],[An.LANGUAGE,"language"],[An.AVATAR,"avatar"],[An.MESSAGESETTINGS,"messageSettings"],[An.ADMINFORBIDTYPE,"adminForbidType"],[An.LEVEL,"level"],[An.ROLE,"role"]]);var bn=new class{createProfile(e,t){const n={userID:e,profileCustomField:[]};return t.forEach((e=>{const{tag:t,value:s}=e;t&&t.indexOf("Tag_Profile_Custom")>-1?n.profileCustomField.push({key:t,value:s}):Rn.has(t)&&(n[Rn.get(t)]=s)})),Object.assign(Object.assign({},wn),n)}parseProfileItem(e=[]){const t=[];return e.forEach((e=>{t.push({tag:e.Tag,value:e.Value})})),t}parseProfileList(e=[]){const t=[];return e.forEach((e=>{t.push({tag:e.Tag,value:e.ValueBytes})})),t}convertParamsToProfile(e){const t=[];return Object.keys(e).forEach((n=>{t.push({tag:An[n.toUpperCase()],value:e[n]})})),t}normalizeProfileFields(e){const t={};return e.forEach((e=>{const{tag:n,value:s}=e;if(Rn.has(n)){const e=Rn.get(n);t[e]=s}})),t}};const Pn=new Map,kn=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];for(let e=0,t=kn.length;e<t;e++)Pn.set(e,kn[e]);function Un(e){if(!e)return"";const t=String(e).replace(/[=]+$/,"");let n="";if(t.length%4==1)return"";for(let e,s,i=0,o=0;s=t.charAt(o++);~s&&(e=i%4?64*e+s:s,i++%4)?n+=String.fromCharCode(255&e>>(-2*i&6)):0)s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(s);try{return decodeURIComponent(escape(n))}catch(e){return console.warn(e),""}}const{isEmpty:Fn}=rt.utils,{generateProtocolData:$n}=rt.common;function Gn(e){return c(this,void 0,void 0,(function*(){try{const t="profile.portrait_get_all",n={From_Account:yn(),UserItem:[]};e.forEach((e=>{n.UserItem.push({CustomSequence:0,StandardSequence:0,To_Account:e})}));const s=$n({servcmd:t,data:n}),i=`${s.head.seq}${t}`,o=yield rt.channel.sendPacket(s,{requestId:i});return o?function(e){const{ActionStatus:t,ErrorCode:n,ErrorDisplay:s,ErrorInfo:i,UserProfileItem:o}=e,r=[];return o.map((e=>{const{To_Account:t,CustomSequence:n,ResultCode:s,ResultInfo:i,StandardSequence:o,ProfileItem:a}=e,c=bn.parseProfileItem(a);r.push({userId:t,customSequence:n,resultCode:s,resultInfo:i,standardSequence:o,profileItem:c})})),{actionStatus:t,errorCode:n,errorDisplay:s,errorInfo:i,userProfile:r}}(o):void 0}catch(e){throw console.warn(e),e}}))}function qn(e){return c(this,void 0,void 0,(function*(){try{const t="im_open_status.ws_get_user_status",n=$n({servcmd:t,data:{To_Account:e}}),s=`${n.head.seq}${t}`,i=yield rt.channel.sendPacket(n,{requestId:s});return i?function(e){const{ErrorCode:t,ErrorInfo:n,ErrorList:s=[],UserStatusList:i=[]}=e,o=i.map((e=>{const{To_Account:t,Status:n,CustomStatus:s}=e;return{userID:t,statusType:n,customStatus:Un(s)}})),r=s.map((e=>{const{To_Account:t,Invalid_Account:n,ErrorCode:s,ErrorInfo:i}=e;return{userID:Fn(n)?t:n,code:s,message:i}}));return{errorCode:t,errorInfo:n,successUserList:o,failureUserList:r}}(i):void 0}catch(e){throw console.warn(e),e}}))}const{isEmpty:Bn}=rt.utils;class xn{constructor(){this._userProfileMap=new Map}init(){Mt("getMyProfile",this),Mt("getUserProfile",this),Mt("updateMyProfile",this),Mt("getFriendProfile",this);const{notificationCenter:e}=rt;e.subscribeInnerEvent(ut.LOGIN,this._handleLoginSuccess,this),e.subscribeInnerEvent("im_open_push.msg_push",e.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),e.subscribeInnerEvent(ut.LOGOUT,this._reset,this),e.subscribeInnerEvent(ut.DESTROY,this._dispose,this)}getMyProfile(){return c(this,void 0,void 0,(function*(){const e=rt.ssoLog.createSSOLogData({method:"getMyProfile"});try{const t=yn(),n=yield Gn([t]);if(n){const e=this._handleProfileFormResponse(n)[0];return this._userProfileMap.set(t,e),{code:0,data:e}}e.end()}catch(t){const{errorCode:n,errorInfo:s}=t,i=new vt({functionName:"getMyProfile",code:n,message:s});throw e.setError(i).end(),t}}))}getFriendProfile(e){return c(this,void 0,void 0,(function*(){const t=rt.ssoLog.createSSOLogData({method:"getFriendProfile"});let{userIDList:n}=e;const s=[];n.length>Tn&&(n=n.slice(0,Tn));try{const{friendUserIdList:e,unFriendUserIdList:i}=this._partitionByIsFriend(n);if(i.forEach((e=>{s.push({userID:e,code:mt.NOT_MY_FRIEND,message:pt({code:mt.NOT_MY_FRIEND})})})),0===e.length)return t.setLogInfo({message:"friendUserIdList is empty"}).end(),{code:0,data:{friendList:e,failureUserIDList:s}};t.setLogInfo({message:`friendUserIdList length: ${e.length}, unFriendUserIdList length: ${i.length}`});const o=(yield function(e){return c(this,void 0,void 0,(function*(){try{const t="sns.friend_get_specified",n=yn(),s=$n({servcmd:t,data:{From_Account:n,To_Account:e}}),i=`${s.head.seq}${t}`;return yield rt.channel.sendPacket(s,{requestId:i})}catch(e){throw console.warn(e),e}}))}(e))||{},{successDueToResponseList:r,failureDueToResponseList:a}=this._handleFriendProfileResponse(o);return t.end(),{code:0,data:{friendList:r,failureUserIDList:[...a,...s]}}}catch(e){const{errorCode:n,errorInfo:s}=e,i=new vt({functionName:"getFriendProfile",code:n,message:s});throw t.setError(i).end(),i}}))}getUserProfile(e){return c(this,void 0,void 0,(function*(){const t=rt.ssoLog.createSSOLogData({method:"getUserProfile"});try{let{userIDList:n}=e;n.length>Tn&&(n=n.slice(0,Tn));const{userIdListToRequest:s,userIdListToCache:i}=this._filterRequestAndCacheUsers(n),o=[];i.forEach((e=>{const t=this._userProfileMap.get(e);o.push(t)}));const r=`userIDList.length:${n.length}`;if(0===s.length)return t.setLogInfo({message:r}).end(),{code:0,data:o};const a=yield Gn(s);if(a){const e=this._handleProfileFormResponse(a);e.forEach((e=>{e.userID,0}));const n=e.concat(o);return t.setLogInfo({message:r}).end(),{code:0,data:n}}}catch(e){const{errorCode:n}=e,s=new vt({functionName:"getUserProfile",code:n});throw t.setError(s).end(),s}}))}getMyProfileCacheThenServer(){return c(this,void 0,void 0,(function*(){const e=yn(),t=this._userProfileMap.has(e);return t?{code:0,data:t}:this.getMyProfile()}))}updateMyProfile(e){return c(this,void 0,void 0,(function*(){const t=rt.ssoLog.createSSOLogData({method:"updateMyProfile"}),n=yn(),s=bn.convertParamsToProfile(e);try{const i={From_Account:n,ProfileItem:s};t.setLogInfo({message:JSON.stringify(s)}),yield function(e){return c(this,void 0,void 0,(function*(){try{const t="profile.portrait_set",n=$n({servcmd:t,data:e}),s=`${n.head.seq}${t}`,i=yield rt.channel.sendPacket(n,{requestId:s});if(i){const{ActionStatus:e,ErrorCode:t,ErrorDisplay:n,ErrorInfo:s}=i;return{actionStatus:e,errorCode:t,errorDisplay:n,errorInfo:s}}return}catch(e){throw console.warn(e),e}}))}(i);const o=this._userProfileMap.get(n);let r;r=o?Object.assign(Object.assign({},o),e):bn.createProfile(n,s);return!It(o,r,["lastUpdatedTime","profileCustomField"])&&rt.notificationCenter.emitOuterEvent(lt.PROFILE_UPDATED,{name:lt.PROFILE_UPDATED,data:[r]}),r.lastUpdatedTime=Date.now(),this._userProfileMap.set(n,r),t.end(),{code:0,data:r}}catch(e){const{errorCode:n,errorInfo:s}=e,i=new vt({functionName:"updateMyProfile",code:n,message:s});throw t.setError(i).end(),i}}))}updateMyNickAndAvatar(e){return c(this,void 0,void 0,(function*(){const t=yn(),n=Date.now(),s=this._userProfileMap.get(t);let i={};i=s?Object.assign(s,e):bn.createProfile(t,e),i.lastUpdatedTime=n,this._userProfileMap.set(t,i)}))}_handleLoginSuccess(){return c(this,void 0,void 0,(function*(){yield this.getMyProfileCacheThenServer()}))}_onProfileDataModify(e){const t=function(e){const{Profile_Account:t,PushType:n,ProfileList:s}=e;return{userId:t,pushType:n,profileList:bn.parseProfileList(s)}}(e.ProfileDataMod[0]);if(Bn(t))return;const{isProfileUpdated:n,profile:s}=this._handleProfileModified(t);n&&(rt.notificationCenter.emitInnerEvent(ut.PROFILE_UPDATE,{name:ut.PROFILE_UPDATE,data:[s]}),rt.notificationCenter.emitOuterEvent(lt.PROFILE_UPDATED,{name:lt.PROFILE_UPDATED,data:[s]}))}_dispose(){const{notificationCenter:e}=rt;e.unSubscribeInnerEvent(ut.LOGIN,this._handleLoginSuccess,this),e.unSubscribeInnerEvent(ut.LOGOUT,this._reset,this),e.unSubscribeInnerEvent("im_open_push.msg_push",e.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),e.unSubscribeInnerEvent(ut.DESTROY,this._dispose,this),this._reset()}_handleProfileModified(e){const{userId:t,profileList:n}=e,s=this._userProfileMap.get(t);if(!s)return{isProfileUpdated:!1,profile:null};const i=bn.normalizeProfileFields(n),o=Object.keys(i).some((e=>s[e]!==i[e]));if(!o)return{isProfileUpdated:!1,profile:s};const r=Date.now(),a=Object.assign(Object.assign(Object.assign({},s),i),{lastUpdatedTime:r});return this._userProfileMap.set(t,a),{isProfileUpdated:o,profile:a}}_partitionByIsFriend(e){const t=[],n=[],s=rt.store.get("friendUserIdMap")||new Map;return e.forEach((e=>{s.has(e)?t.push(e):n.push(e)})),console.log(`User _partitionByIsFriend, friendUserIdList: ${t}, unFriendUserIdList:${n}`),{friendUserIdList:t,unFriendUserIdList:n}}_handleFriendProfileResponse(e){const{InfoItem:t=[]}=e,n=[],s=[];return t.forEach((e=>{const{To_Account:t,ResultCode:i,ResultInfo:o,SnsProfileItem:r}=e;0===i?n.push(r):s.push({userID:t,code:i,message:o})})),{successDueToResponseList:n,failureDueToResponseList:s}}_filterRequestAndCacheUsers(e){const t=[];return e.forEach((e=>{this._userProfileMap.has(e),t.push(e)})),{userIdListToRequest:t,userIdListToCache:[]}}_handleProfileFormResponse(e){const{userProfile:t}=e;if(!Array.isArray(t))return[];const n=t.filter((e=>"@TLS#NOT_FOUND"!==e.userId&&""!==e.userId&&!Bn(e.profileItem))),s=Date.now();return n.map((e=>{const t=bn.createProfile(e.userId,e.profileItem);return t.lastUpdatedTime=s,t}))}_reset(){this._userProfileMap.clear()}}r([Kt(),a("design:type",Function),a("design:paramtypes",[]),a("design:returntype",Promise)],xn.prototype,"getMyProfile",null),r([Kt(),a("design:type",Function),a("design:paramtypes",[Object]),a("design:returntype",Promise)],xn.prototype,"getFriendProfile",null),r([Kt(),a("design:type",Function),a("design:paramtypes",[Object]),a("design:returntype",Promise)],xn.prototype,"getUserProfile",null),r([Kt(),a("design:type",Function),a("design:paramtypes",[Object]),a("design:returntype",Promise)],xn.prototype,"updateMyProfile",null);class jn{constructor(){this._customStatus=""}init(){Mt("getUserStatus",this),Mt("setSelfStatus",this),rt.notificationCenter.subscribeInnerEvent(ut.LOGOUT,this._reset,this),rt.notificationCenter.subscribeInnerEvent(ut.DESTROY,this._dispose,this)}setSelfStatus(e){return c(this,void 0,void 0,(function*(){const t=rt.ssoLog.createSSOLogData({method:"setSelfStatus"}),n=yn(),{customStatus:s}=e;try{return yield function(e){return c(this,void 0,void 0,(function*(){try{const t="im_open_status.ws_set_custom_status",n=$n({servcmd:t,data:{CustomStatus:e}}),s=`${n.head.seq}${t}`,i=yield rt.channel.sendPacket(n,{requestId:s});if(i){const{ErrorCode:e,ErrorInfo:t}=i;return{errorCode:e,errorInfo:t}}return}catch(e){throw console.warn(e),e}}))}(s),this._customStatus=s,t.setLogInfo({message:`customStatus: ${s}`}).end(),{code:0,data:{userID:n,statusType:Nn,customStatus:s}}}catch(e){const{errorCode:n,errorInfo:s}=e,i=new vt({functionName:"setSelfStatus",code:n,message:s});throw t.setError(i).end(),i}}))}getUserStatus(e){return c(this,void 0,void 0,(function*(){const t=rt.ssoLog.createSSOLogData({method:"getUserStatus"}),{userIDList:n=[]}=e;return t.setLogInfo({moreMessage:`userIDList length: ${n.length}`}),this._isOnlyMeInArray(n)?this._getMyStatus():this._getUserStatus(n)}))}setCustomStatus(e){const t=Un(e);this._customStatus=t}_getMaxQueryUserCount(){const e=rt.store.get("cloudConfig")||{},{status_query_count:t=Dn}=e;return parseInt(t,10)}_getMyStatus(){const e=rt.ssoLog.getSSOLogData("getUserStatus");e.setLogInfo({moreMessage:"getUserStatus._getMyStatus"});const t={userID:yn(),statusType:Nn,customStatus:this._customStatus};return e.end(),{code:0,data:{successUserList:[t],failureUserList:[]}}}_getUserStatus(e){return c(this,void 0,void 0,(function*(){const t=rt.ssoLog.getSSOLogData("getUserStatus");t.setLogInfo({moreMessage:"getUserStatus._getUserStatus"});try{this._validateBeforeGetUserStatus();const n=this._getMaxQueryUserCount();let s=[...e];e.length>n&&(s=e.slice(0,n));const i=yield qn(s),{successUserList:o,failureUserList:r}=i||{};return t.end(),{code:0,data:{successUserList:o,failureUserList:r}}}catch(e){const{errorCode:n}=e,s=new vt({functionName:"getUserStatus",code:n});throw t.setError(s).end(),s}}))}_validateBeforeGetUserStatus(){var e;const t="getUserStatus";if(!(e=Ln,rt.store.get("commercialConfig").get(e)))throw new vt({functionName:t,code:mt.NO_USE,replacement1:t})}_isOnlyMeInArray(e){const t=yn();return 1===e.length&&e.indexOf(t)>-1}_dispose(){rt.notificationCenter.unSubscribeInnerEvent(ut.DESTROY,this._dispose,this),rt.notificationCenter.unSubscribeInnerEvent(ut.LOGOUT,this._reset,this),this._reset()}_reset(){this._customStatus=""}}r([Kt(),a("design:type",Function),a("design:paramtypes",[Object]),a("design:returntype",Promise)],jn.prototype,"setSelfStatus",null),r([Kt(),a("design:type",Function),a("design:paramtypes",[Object]),a("design:returntype",Promise)],jn.prototype,"getUserStatus",null);const Vn={getUserProfile:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}},getFriendProfile:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}},updateMyProfile:{nick:{required:!1,rules:["string"],allowEmpty:!0},avatar:{required:!1,rules:["string"],allowEmpty:!0},gender:{required:!1,rules:["string"],allowEmpty:!0},selfSignature:{required:!1,rules:["string"],allowEmpty:!0},allowType:{required:!1,rules:["string"],allowEmpty:!0},birthday:{required:!1,rules:["number"],allowEmpty:!1},language:{required:!1,rules:["string"],allowEmpty:!0},messageSettings:{required:!1,rules:["string"],allowEmpty:!0},adminForbidType:{required:!1,rules:["string"],allowEmpty:!0},level:{required:!1,rules:["number"],allowEmpty:!1},role:{required:!1,rules:["number"],allowEmpty:!0},profileCustomField:{required:!1,rules:["array"],allowEmpty:!0}},setSelfStatus:{customStatus:{required:!0,rules:["string"],allowEmpty:!0}},getUserStatus:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}}};class Kn{constructor(){this.userProfile=new xn,this.userStatus=new jn,this.userProfile.init(),this.userStatus.init(),At(Vn)}}const Yn=[{cmd:"im_open_status.ws_get_user_status",interval:5,limit:20},{cmd:"im_open_status.ws_status_subscribe",interval:5,limit:20},{cmd:"im_open_status.ws_status_unsubscribe",interval:5,limit:20},{cmd:"group_open_http_svc.get_group_self_member_info",interval:5,limit:20},{cmd:"group_open_http_svc.modify_group_base_info",interval:1,limit:8},{cmd:"group_open_http_svc.get_members",interval:3,limit:1},{cmd:"group_open_http_svc.get_pendency",interval:1,limit:15},{cmd:"group_open_http_svc.set_group_attr",interval:5,limit:10},{cmd:"group_open_http_svc.modify_group_attr",interval:5,limit:10},{cmd:"group_open_http_svc.delete_group_attr",interval:5,limit:10},{cmd:"group_open_http_svc.clear_group_attr",interval:5,limit:10},{cmd:"group_open_http_svc.get_group_attr",interval:5,limit:20},{cmd:"group_open_http_svc.update_group_counter",interval:5,limit:20},{cmd:"group_open_http_svc.get_group_counter",interval:5,limit:20},{cmd:"million_group_open_http_svc.get_topic",interval:1,limit:10},{cmd:"openim.read_all_unread_msg",interval:1,limit:1},{cmd:"message_search.query",interval:5,limit:20},{cmd:"message_search.query_grp",interval:5,limit:20},{cmd:"message_search.query_grp_member",interval:5,limit:20},{cmd:"message_search.query_user",interval:5,limit:20}],Hn={login:"im_open_status.wslogin",logout:"im_open_status.wslogout",sendMessage:"openim.sendmsg",modifyMessage:"openim.modify_c2c_msg",getMyProfile:"profile.portrait_get_all",getUserProfile:"profile.portrait_get_all",updateMyProfile:"profile.portrait_set",setSelfStatus:"im_open_status.ws_set_custom_status",getUserStatus:"im_open_status.ws_get_user_status",getFriendProfile:"sns.friend_get_specified"},Wn="im_sdk_config_mgr.fetch_config",Jn="im_sdk_config_mgr.push_configv2",zn="cloud-config";var Xn=new class{constructor(){this._core=null,this._expirationTime=0,this._version=0,this._isFetching=!1,this._cmdFrequencyLimitMap=new Map,this._methodCallFrequencyMap=new Map}install(e){this._core=e;const{notificationCenter:t,InnerEvent:n,helper:s}=e;t.subscribeInnerEvent(Jn,this._handlePushedConfig,this),t.subscribeInnerEvent(n.LOGIN,this._handleLoginSuccess,this),t.subscribeInnerEvent(n.LOGOUT,this._reset,this),t.subscribeInnerEvent(n.DESTROY,this._dispose,this),s.registerExperimentalAPI("getServerConfig",this),s.registerInterceptor(this.checkMethodCallOverLimit,this),this._updateCmdFreqLimitMap(Yn)}getServerConfig(e){var t;const n={code:0,data:""};return e?(n.data=(null===(t=this._core.store.get("cloudConfig"))||void 0===t?void 0:t[e])||"",n):n}checkMethodCallOverLimit(e){const t=Hn[e];if(!this._cmdFrequencyLimitMap.has(t))return;if(!this._methodCallFrequencyMap.has(t))return void this._methodCallFrequencyMap.set(t,{startTime:Date.now(),methodCallCounter:1});const{limit:n,interval:s}=this._cmdFrequencyLimitMap.get(t);let{startTime:i,methodCallCounter:o}=this._methodCallFrequencyMap.get(t);if(Date.now()-i>1e3*s)this._methodCallFrequencyMap.set(t,{startTime:Date.now(),methodCallCounter:1});else if(o+=1,this._methodCallFrequencyMap.set(t,{startTime:i,methodCallCounter:o}),o>n)throw new this._core.helper.ChatError({functionName:e,message:"frequency control limit exceeded,"})}_fetchCloudConfig(){return c(this,void 0,void 0,(function*(){try{const{sdkAppId:e}=this._core.store.get("instance")||{},t=this._core.helper.generateProtocolData({servcmd:Wn,data:{uint32_sdkappid:e,uint64_version:this._version}}),n=`${t.head.seq}${Wn}`;return yield this._core.channel.sendPacket(t,{requestId:n})}catch(e){throw console.warn("fetch cloudControl fail: ",e),e}}))}_handlePushedConfig(e){this._updateCloudConfig(e)}_handleLoginSuccess(){return c(this,void 0,void 0,(function*(){try{if(this._canFetch()){const e=yield this._fetchCloudConfig();this._updateCloudConfig(e)}this._core.helper.taskScheduler.addTask({id:zn,intervalMs:1e3,callback:this._fetchCloudConfigIfReady,context:this})}catch(e){console.warn(e)}}))}_fetchCloudConfigIfReady(){return c(this,void 0,void 0,(function*(){if(this._canFetch())try{const e=yield this._fetchCloudConfig();this._updateCloudConfig(e)}catch(e){console.warn(e)}}))}_updateCloudConfig(e){const t=this._parseCloudConfig(e);t&&(this._core.store.set("cloudConfig",t),this._parseCmdFreqLimit(),this._core.notificationCenter.emitInnerEvent(this._core.InnerEvent.CLOUD_CONFIG_UPDATE,t))}_canFetch(){const{isLoggedIn:e}=this._core.store.get("login")||{};return e&&!this._isFetching&&Date.now()>=this._expirationTime}_parseCloudConfig(e){const{int32_error_code:t,str_error_message:n,str_json_config:s,uint32_expired_time:i,uint32_sdkappid:o,uint64_version:r}=e;let a=null;if(0===t){if(this._version!==r)try{a=JSON.parse(s),this._version=r}catch(e){}this._expirationTime=Date.now()+1e3*i}else this._expirationTime=void 0===t?Date.now()+36e5:Date.now()+12e4;return a}_parseCmdFreqLimit(){var e;let t=null===(e=this.getServerConfig("cmd_frequency_limit"))||void 0===e?void 0:e.data;if(void 0!==typeof t&&this._core.helper.isEmpty(t))try{t=JSON.parse(t),this._updateCmdFreqLimitMap(t)}catch(e){console.warn(e)}}_updateCmdFreqLimitMap(e){e.forEach((e=>{this._cmdFrequencyLimitMap.set(e.cmd,{interval:e.interval,limit:e.limit})}))}_reset(){this._core.helper.taskScheduler.removeTask(zn),this._core.store.clear("cloudConfig"),this._updateCmdFreqLimitMap(Yn),this._methodCallFrequencyMap.clear(),this._expirationTime=0,this._version=0,this._isFetching=!1}_dispose(){const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(Jn,this._handlePushedConfig,this),e.unSubscribeInnerEvent(t.LOGIN,this._handleLoginSuccess,this),e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this),this._reset()}};class Qn{constructor(e=0,t=0){this.high=e,this.low=t}equal(e){return null!==e&&(this.low===e.low&&this.high===e.high)}toString(){const e=Number(this.high).toString(16);let t=Number(this.low).toString(16);if(t.length<8){let e=8-t.length;for(;e;)t=`0${t}`,e--}return e+t}}const Zn={SEARCH_GRP_SNS:new Qn(0,Math.pow(2,1)).toString(),AV_HISTORY_MSG:new Qn(0,Math.pow(2,2)).toString(),GRP_COMMUNITY:new Qn(0,Math.pow(2,3)).toString(),MSG_TO_SPECIFIED_GRP_MBR:new Qn(0,Math.pow(2,4)).toString(),AV_MBR_LIST:new Qn(0,Math.pow(2,6)).toString(),USER_STATUS:new Qn(0,Math.pow(2,7)).toString(),CONV_MARK:new Qn(0,Math.pow(2,9)).toString(),CONV_GROUP:new Qn(0,Math.pow(2,10)).toString(),AV_BAN_MBR:new Qn(0,Math.pow(2,11)).toString(),MSG_EXT:new Qn(0,Math.pow(2,13)).toString(),GRP_COUNTER:new Qn(0,Math.pow(2,15)).toString(),PLUGIN_TRANSLATE:new Qn(Math.pow(2,6)).toString(),PLUGIN_VOICE_TO_TEXT:new Qn(Math.pow(2,7)).toString(),PLUGIN_CS:new Qn(Math.pow(2,8)).toString(),PLUGIN_PUSH:new Qn(Math.pow(2,9)).toString(),PLUGIN_BOT:new Qn(Math.pow(2,10)).toString(),MSG_REACTION:new Qn(Math.pow(2,16)).toString(),FOLLOW:new Qn(Math.pow(2,20)).toString()},es="CommercialConfig",ts="commercial-config";var ns=new class{constructor(){this._core=null,this._expirationTime=0,this._isFetching=!1,this._featureMap=new Map,this._methodKeyMap=new Map}install(e){this._core=e,this._core.notificationCenter.subscribeInnerEvent(e.InnerEvent.COMMERCIAL_CONFIG_PUSH,this._handlePushedConfig,this),this._core.notificationCenter.subscribeInnerEvent(e.InnerEvent.LOGIN,this._handleLoginSuccess,this),this._core.notificationCenter.subscribeInnerEvent(e.InnerEvent.LOGOUT,this._handleLogout,this),this._core.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this),e.helper.registerExperimentalAPI("isCommercialAbilityEnabled",this)}isCommercialAbilityEnabled(e){const t=parseInt(e,10).toString(2),{length:n}=t;let s,i=!0;for(let e=n-1,o=0;e>=0;e--,o++)if("1"===t.charAt(e)&&(s=o<32?new Qn(0,2**o).toString():new Qn(2**(o-32),0).toString(),!this._featureMap.get(s))){i=!1;break}return console.log(`${es}.isFeatureEnabled decimalNumber:${e} key:${s} ret:${i}`),{code:0,data:{enabled:i}}}_fetchAndParseCommercialConfig(){return c(this,void 0,void 0,(function*(){var e;try{this._isFetching=!0;const t=this._core.helper.generateProtocolData({servcmd:"im_sdk_config_mgr.fetch_imsdk_purchase_bitsv2",data:{uint32_sdkappid:null===(e=this._core.store.get("instance"))||void 0===e?void 0:e.sdkAppId}}),n=yield this._core.channel.sendPacket(t);(null==n?void 0:n.body)&&(this._parseCommercialConfig(n.body),this._core.store.set("commercialConfig",this._methodKeyMap))}catch(e){console.warn("fetch commercial fail: ",e)}finally{this._isFetching=!1}}))}_handleLoginSuccess(e){return c(this,void 0,void 0,(function*(){const{purchaseBits:t}=e||{};t&&(this._parsePurchaseBits(t),this._core.store.set("commercialConfig",this._methodKeyMap)),this._canFetch()&&(yield this._fetchAndParseCommercialConfig()),this._core.helper.taskScheduler.addTask({id:ts,intervalMs:1e3,callback:this._fetchCommercialConfigIfReady,context:this})}))}_canFetch(){var e;const t=null===(e=this._core.store.get("login"))||void 0===e?void 0:e.isLoggedIn,n=Date.now()>=this._expirationTime;return t&&!this._isFetching&&n}_handlePushedConfig(e){(null==e?void 0:e.body)&&(this._parseCommercialConfig(e.body),this._core.store.set("commercialConfig",this._methodKeyMap))}_fetchCommercialConfigIfReady(){return c(this,void 0,void 0,(function*(){this._canFetch()&&(yield this._fetchAndParseCommercialConfig())}))}_parseCommercialConfig(e){if("object"!=typeof e)return;const{int32_error_code:t,str_error_message:n,str_purchase_bits:s,uint32_expired_time:i}=e;0===t?(this._parsePurchaseBits(s),this._expirationTime=Date.now()+1e3*i):void 0===t?(console.log(`${es}._parseCommercialConfig failed. Invalid message format:`,e),this._expirationTime=Date.now()+36e5):(console.error(`${es}._parseCommercialConfig errorCode:${t} errorMessage:${n}`),this._expirationTime=Date.now()+12e4)}_isValidPurchaseBits(e){return e&&"string"==typeof e&&e.length>=1&&e.length<=64&&/[01]{1,64}/.test(e)}_parsePurchaseBits(e){if(this._isValidPurchaseBits(e)){this._featureMap.clear(),this._methodKeyMap.clear();let t=null;for(let n=e.length-1,s=0;n>=0;n--,s++)if(t=s<32?new Qn(0,2**s).toString():new Qn(2**(s-32),0).toString(),"1"===e[n]){this._featureMap.set(t,!0);const e=this._getKeyByValue(Zn,t);e&&this._methodKeyMap.set(e,!0)}else{this._featureMap.set(t,!1);const e=this._getKeyByValue(Zn,t);e&&this._methodKeyMap.set(e,!1)}}else console.warn(`${es}.parsePurchaseBits invalid purchases:${e}`)}_getKeyByValue(e,t){const n=Object.entries(e).find((([e,n])=>n===t));return n?n[0]:void 0}_handleLogout(){this._reset()}_dispose(){this._reset(),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.COMMERCIAL_CONFIG_PUSH,this._handlePushedConfig,this),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGIN,this._handleLoginSuccess,this),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}_reset(){this._core.helper.taskScheduler.removeTask(ts),this._core.store.set("commercialConfig",{}),this._expirationTime=0,this._isFetching=!1,this._featureMap.clear()}};var ss=new class{constructor(){this._core=null,this._serverOverloadInfoMap=new Map}install(e){this._core=e;const{notificationCenter:t,InnerEvent:n,helper:s}=this._core;t.subscribeInnerEvent(n.OVERLOAD_PUSH,this._handleOverLoadPush,this),t.subscribeInnerEvent(n.LOGOUT,this._reset,this),t.subscribeInnerEvent(n.DESTROY,this._dispose,this),s.registerInterceptor(this.checkServerOverload,this)}checkServerOverload(e){const t=Hn[e];if(!this._serverOverloadInfoMap.has(t))return;const{overloadStartTimestamp:n,delaySeconds:s}=this._serverOverloadInfoMap.get(t);if(Date.now()-n<=1e3*s)throw new this._core.helper.ChatError({functionName:e,message:"service is busy, please try again later"});this._serverOverloadInfoMap.delete(t)}_handleOverLoadPush(e){const{OverLoadServCmd:t,DelaySecs:n}=e;this._serverOverloadInfoMap.set(t,{overloadStartTimestamp:Date.now(),delaySeconds:n})}_reset(){this._serverOverloadInfoMap.clear()}_dispose(){this._reset();const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.OVERLOAD_PUSH,this._handleOverLoadPush,this),e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};var is=new class{constructor(){this._core=null}install(e){return c(this,void 0,void 0,(function*(){if(this._core=e,this._canFetch()){const e=yield this._fetchErrorMessage();if(!e)return;const t=this._parseResponse(e);this._saveErrorMessage(t)}}))}_canFetch(){const e=this._core.store.getStorage("errorMessage");return!e||this._isExpired(e)}_saveErrorMessage(e){this._core.store.setStorage("errorMessage",{errorMessage:e,errorMessageSavedTime:(new Date).getTime()})}_fetchErrorMessage(){return c(this,void 0,void 0,(function*(){try{return yield this._core.helper.httpRequest({method:"GET",url:"https://web.sdk.qcloud.com/im/download/error-message/v3/0.0.6/tim-error-message.txt"})}catch(e){console.error(e)}}))}_isExpired(e){if(!e)return!0;const{errorMessageSavedTime:t}=e;return t&&(new Date).getTime()-t>=6048e5}_parseResponse(e){if("string"==typeof e){const t=e.split(";\n"),n={},s=new RegExp(/'/g);for(let e=0;e<t.length;e++){const i=t[e].indexOf(":"),o=t[e].slice(0,i);let r=t[e].slice(i+1);if(!o.startsWith("//")){if(""===r)continue;r=r.replace(s,""),n[o]=r}}return n}}};var os,rs;!function(e){e[e.START_SYNC=0]="START_SYNC",e[e.SYNCING=1]="SYNCING",e[e.SYNC_COMPLETE=2]="SYNC_COMPLETE"}(os||(os={})),function(e){e[e.LOGIN_SUCCESS=0]="LOGIN_SUCCESS",e[e.SEND_MESSAGE=1]="SEND_MESSAGE"}(rs||(rs={}));function as(e,t){return c(this,void 0,void 0,(function*(){const{cookie:n,syncFlag:s,syncTriggerEvent:i}=e,o="openim.getmsg",r=t.helper.generateProtocolData({servcmd:o,data:{Cookie:n,SyncFlag:s,IsOnlineSync:i,NeedAbstract:1,NeedSignaling:1,NeedCachedMsg:1}}),a=`${r.head.seq}${o}`;try{const e=yield t.channel.sendPacket(r,{requestId:a});if(!e)return null;const{unreadMessageList:n,unreadNoticeList:s}=function(e,t){const n=[],s=[];return null==e||e.forEach((e=>{var i,o;const r=function(e,t){const{From_Account:n,From_AccountHeadurl:s,From_AccountNick:i,IsNeedReadReceipt:o,MsgBody:r,MsgClientTime:a,MsgRandom:c,MsgSeq:l,MsgTimeStamp:d,SendMsgControl:u,SupportMessageExtension:h,To_Account:_,TinyId:g,MsgCheckResult:m,CloudCustomData:p,IsPeerRead:v,MsgFlagBits:f,MsgVersion:I,EventArray:S}=e;return{from:n,avatar:s,nick:i,needReadReceipt:1===o,readReceiptSentByPeer:v,clientTime:a,messageFlagBits:f,random:c,sequence:l,time:d,messageControlInfo:u,isSupportExtension:h,to:_,tinyID:g,checkResult:m,cloudCustomData:p,messageVersion:I,eventArray:S,elements:t.message.messageHelper.parseServerPushMessageElement(r)}}(e,t);if(10===(null===(o=null===(i=null==r?void 0:r.eventArray)||void 0===i?void 0:i[0])||void 0===o?void 0:o.Event))s.push(r);else{const e=t.message.messageFactory.createMessage(Object.assign(Object.assign({},r),{conversationType:"C2C"})),{elements:s}=r;e.setElement(s),n.push(e)}})),{unreadMessageList:n,unreadNoticeList:s}}(e.MsgList,t);return{syncFlag:null==e?void 0:e.SyncFlag,unreadMessageList:n,unreadNoticeList:s,cookie:null==e?void 0:e.Cookie}}catch(e){console.warn(e)}}))}var cs=new class{constructor(){this._unreadDBMessageMap=new Map,this._unreadDBNoticeList=[]}install(e){this._core=e,e.notificationCenter.subscribeInnerEvent(e.InnerEvent.LOGIN,this._syncUnreadDBMessageAfterLogin,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.RE_LOGIN,this._syncUnreadDBMessageAfterLogin,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.LOGOUT,this._reset,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this)}_syncUnreadDBMessageAfterLogin(){return c(this,void 0,void 0,(function*(){let e=os.START_SYNC,t="";for(;this._canContinueSync({cookie:t,syncFlag:e});){const n=yield this._fetchUnreadDBMessage({cookie:t,syncFlag:e,syncTriggerEvent:rs.LOGIN_SUCCESS});if(!n)break;const{unreadMessageList:s=[],unreadNoticeList:i=[]}=n;t=(null==n?void 0:n.cookie)||"",e=null==n?void 0:n.syncFlag,this._parseAndSaveUnreadMessageList(s),this._saveUnreadNoticeList(i)}this._emitUnreadMessageSyncComplete()}))}_emitUnreadMessageSyncComplete(){var e;null===(e=this._core)||void 0===e||e.notificationCenter.emitInnerEvent(this._core.InnerEvent.UNREAD_MESSAGES_SYNC_COMPLETED,{unreadNoticeList:this._unreadDBNoticeList,unreadMessageMap:this._unreadDBMessageMap})}_saveUnreadNoticeList(e){this._unreadDBNoticeList=[...this._unreadDBNoticeList,...e]}_fetchUnreadDBMessage(e){return c(this,void 0,void 0,(function*(){try{const t="unread-message._fetchUnreadDBMessage";console.log(`${t} options:`,e);const n=yield as(e,this._core);if(!n)return null;const{syncFlag:s,unreadMessageList:i,unreadNoticeList:o,cookie:r}=n;return this._parseAndSaveUnreadMessageList(i),{syncFlag:s,cookie:r,unreadMessageList:i,unreadNoticeList:o}}catch(e){console.log(e)}}))}_canContinueSync({cookie:e,syncFlag:t}){var n;return t===os.START_SYNC||t===os.SYNCING&&!(null===(n=this._core)||void 0===n?void 0:n.helper.isEmpty(e))}_parseAndSaveUnreadMessageList(e){e.forEach((e=>{const{ID:t}=e;this._unreadDBMessageMap.set(t,e)}))}_reset(){this._unreadDBMessageMap.clear(),this._unreadDBNoticeList=[]}_dispose(){var e,t,n;null===(e=this._core)||void 0===e||e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGIN,this._syncUnreadDBMessageAfterLogin,this),null===(t=this._core)||void 0===t||t.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),null===(n=this._core)||void 0===n||n.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),this._reset()}};const ls="none",ds="online";class us{install(e){this._core=e,this._activateNetworkMonitoring(),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return c(this,void 0,void 0,(function*(){var e;null===(e=this._core)||void 0===e||e.store.set("netWorkMonitor",{isNetworkOnline:navigator.onLine,networkType:ds}),this._onOnlineCallback=this._onOnline.bind(this),this._onOfflineCallback=this._onOffline.bind(this),window.addEventListener("online",this._onOnlineCallback),window.addEventListener("offline",this._onOfflineCallback)}))}_deactivateNetworkMonitoring(){null!==this._onOnlineCallback&&(window.removeEventListener("online",this._onOnlineCallback),this._onOnlineCallback=null),null!==this._onOfflineCallback&&(window.removeEventListener("offline",this._onOfflineCallback),this._onOfflineCallback=null)}_onNetworkStatusChange(e){var t,n;const{isConnected:s,networkType:i}=e;null===(t=this._core)||void 0===t||t.store.set("netWorkMonitor",{isNetworkOnline:s,networkType:i}),null===(n=this._core)||void 0===n||n.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:s,networkType:i})}_onOnline(){this._onNetworkStatusChange({isConnected:!0,networkType:ds})}_onOffline(){this._onNetworkStatusChange({isConnected:!1,networkType:ls})}_reset(){var e;this._deactivateNetworkMonitoring(),null===(e=this._core)||void 0===e||e.store.clear("netWorkMonitor")}_dispose(){var e,t,n,s;null===(e=this._core)||void 0===e||e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGIN,this._activateNetworkMonitoring,this),null===(t=this._core)||void 0===t||t.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),null===(n=this._core)||void 0===n||n.notificationCenter.unSubscribeInnerEvent(null===(s=this._core)||void 0===s?void 0:s.InnerEvent.DESTROY,this._dispose,this),this._reset()}}class hs{install(e){this._core=e,this._activateNetworkMonitoring(),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return c(this,void 0,void 0,(function*(){try{wx.getNetworkType().then((e=>{var t;const{isConnected:n,networkType:s}=e;null===(t=this._core)||void 0===t||t.store.set("netWorkMonitor",{isNetworkOnline:n,networkType:s})})),this._mpNetworkStatusCallback=this._onNetworkStatusChange.bind(this),wx.onNetworkStatusChange(this._onNetworkStatusChange.bind(this))}catch(e){console.error(e)}}))}_deactivateNetworkMonitoring(){null!==this._mpNetworkStatusCallback&&(wx.offNetworkStatusChange&&wx.offNetworkStatusChange(this._mpNetworkStatusCallback),this._mpNetworkStatusCallback=null)}_onNetworkStatusChange(e){var t,n;const{isConnected:s,networkType:i}=e;null===(t=this._core)||void 0===t||t.store.set("netWorkMonitor",{isNetworkOnline:s,networkType:i}),null===(n=this._core)||void 0===n||n.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:s,networkType:i})}_reset(){var e;this._deactivateNetworkMonitoring(),null===(e=this._core)||void 0===e||e.store.clear("netWorkMonitor")}_dispose(){var e,t,n,s;null===(e=this._core)||void 0===e||e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGIN,this._activateNetworkMonitoring,this),null===(t=this._core)||void 0===t||t.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),null===(n=this._core)||void 0===n||n.notificationCenter.unSubscribeInnerEvent(null===(s=this._core)||void 0===s?void 0:s.InnerEvent.DESTROY,this._dispose,this),this._reset()}}const _s="undefined"!=typeof wx&&"function"==typeof wx.getSystemInfoSync&&Boolean(wx.getSystemInfoSync().fontSizeSetting);var gs={install:function(e){_s?(new hs).install(e):(new us).install(e)}};const ms=1,ps=2,vs=3,fs=4,Is=5,Ss="TIMCustomElem",Es="C2C",Cs="GROUP",Os="invite",ys="accept",Ms="cancel",Ts="reject",Ds="modifyInvitation",As="signaling",Ls=8010,Ns="signaling-timeout";function ws(e){return e.filter((e=>{if(e.type===Ss){const{cloudCustomData:t="",payload:{data:n=""}={}}=e,s=t.match(/"type":"tsignaling"/),i=n.match(/inviteID/),o=n.match(/actionType/);return s||i&&o}return!1}))}function Rs(e){const{data:t}=e.payload;try{return JSON.parse(t)}catch(e){return console.error(e),null}}function bs(e,t){return e.toString(16).padStart(t,"0")}function Ps(e){if(e<0||e>53)throw new Error("Number of digits must be between 0 and 53");if(e<=30)return Math.floor(Math.random()*(1<<e));const t=e-30;return Math.floor(Math.random()*(1<<t))*(1<<30)+Math.floor(Math.random()*(1<<30))}var ks=new class{constructor(){this._onlineSignalingMap=new Map,this._isSignalingListening=!1}init(e){this._core=e,e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.LOGOUT,this._reset,this)}getOnlineSignalingMap(){return this._onlineSignalingMap}hasSignaling(e){return this._onlineSignalingMap.has(e)}getSignaling(e){return this._onlineSignalingMap.get(e)}saveSignaling(e,t){return this._onlineSignalingMap.set(e,t)}removeSignaling(e){return this._onlineSignalingMap.delete(e)}isInvitationValid(e){const t=`${As}.isInvitationValid`,{inviteID:n,groupID:s,inviter:i}=e,o=i===this._getCurrentUserId();if(!this._onlineSignalingMap.has(n))return!1;const{inviteeList:r}=this._onlineSignalingMap.get(n);if(console.log(`${t} inviteID:${n} inviteeList:${r} groupID:${s}`),s){if(o)return r.length>0;const e=this._getCurrentUserId();return r.includes(e)}return!0}updateSignaling(e){const t=`${As}.updateSignaling`,{inviteID:n,inviter:s,inviteeList:i,groupID:o}=e;if(console.log(`${t} inviteID:${n} inviter:${s} groupID:${o}`),o&&this.hasSignaling(n)){const e=i[0],{inviteeList:s}=this._onlineSignalingMap.get(n);s.includes(e)&&(s.splice(s.indexOf(e),1),console.log(`${t} remove ${e}. localInviteeList.length:${s.length}`)),0===s.length&&this.removeSignaling(n)}else this.removeSignaling(n)}setSignalingListenStatus(e){this._isSignalingListening=e}getSignalingListenStatus(){return this._isSignalingListening}_getCurrentUserId(){var e,t;return null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("login"))||void 0===t?void 0:t.userId}_dispose(){var e,t;this._reset(),null===(e=this._core)||void 0===e||e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),null===(t=this._core)||void 0===t||t.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),this._isSignalingListening=!1}_reset(){this._onlineSignalingMap.clear()}};var Us=new class{init(e){this._core=e}createInviteSignaling(e){const t=this._generateInviteID(),n=this._createInviteSignalingData(Object.assign(Object.assign({},e),{inviteID:t})),{groupID:s,inviteeList:i}=n,o=s||i[0];return{signaling:this._createSignaling(n,o),signalingData:n,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createAcceptSignaling(e){const t=this._createAcceptSignalingData(e),{groupID:n,inviter:s}=t,i=n||s;return{signaling:this._createSignaling(t,i),signalingData:t,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createCancelSignaling(e){const t=this._createCancelSignalingData(e),{groupID:n,inviteeList:s}=t,i=n||s[0];return{signaling:this._createSignaling(t,i),signalingData:t,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createRejectSignaling(e){const t=this._createRejectSignalingData(e),{groupID:n,inviter:s}=t,i=n||s;return{signaling:this._createSignaling(t,i),signalingData:t,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createTimeoutSignaling(e){const{isInviter:t=!1}=e,n=this._createTimeoutSignalingData(e),{groupID:s,inviteeList:i,inviter:o}=n,r=s||(t?i[0]:o);return{signaling:this._createSignaling(n,r),signalingData:n,signalingExtensionOptions:this._createSignalingExtensionOptions(n)}}_createSignalingExtensionOptions(e){var t,n;const{data:s="",onlineUserOnly:i,inviteID:o="",offlinePushInfo:r,actionType:a}=e,c=(null===(n=null===(t=ks.getSignaling(o))||void 0===t?void 0:t.signaling)||void 0===n?void 0:n._onlineOnlyFlag)||!1;return{onlineUserOnly:i||c,offlinePushInfo:r,messageControlInfo:this._createMessageControlInfo(s,a)}}_createMessageControlInfo(e,t){const n=t===Is&&!!e.match(/excludeTimeoutSignalingFromHistoryMessage/),s=!!e.match(/excludeFromHistoryMessage/)||!!e.match(/excludeOriginalSignalingFromHistoryMessage/);return{excludedFromContentModeration:!0,excludedFromUnreadCount:n||s,excludedFromLastMessage:n||s}}_createInviteSignalingData(e){const t=`${As}._createInviteSignalingData`,{userID:n,timeout:s=0,groupID:i="",inviteeList:o=[]}=e,r=this._getCurrentUserId(),a=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:ms,inviter:r,inviteeList:i?o:[n],timeout:s});return console.log(`${t} signalingData:`,a),a}_createAcceptSignalingData(e){const t=`${As}._createAcceptSignalingData`,{inviteID:n}=e,s=this._getCurrentUserId(),{inviter:i,groupID:o}=ks.getSignaling(n),r=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:vs,groupID:o,inviter:i,inviteeList:[s]});return console.log(`${t} signalingData:`,r),r}_createCancelSignalingData(e){const t=`${As}._createCancelSignalingData`,{inviteID:n}=e,s=this._getCurrentUserId(),{inviteeList:i,groupID:o}=ks.getSignaling(n),r=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:ps,groupID:o,inviter:s,inviteeList:i});return console.log(`${t} signalingData:`,r),r}_createRejectSignalingData(e){const t=`${As}._createRejectSignalingData`,{inviteID:n}=e,s=this._getCurrentUserId(),{inviter:i,groupID:o}=ks.getSignaling(n),r=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:fs,groupID:o,inviter:i,inviteeList:[s]});return console.log(`${t} signalingData:`,r),r}_createTimeoutSignalingData(e){const t=`${As}._createTimeoutSignalingData`,{isInviter:n=!1,inviteID:s}=e,{inviteeList:i,inviter:o}=ks.getSignaling(s),r=this._getCurrentUserId(),a=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:Is,inviter:o,inviteeList:n?i:[r]});return console.log(`${t} signalingData:`,a),a}_createSignaling(e,t){var n,s,i;const{groupID:o=""}=e,r={to:t,conversationType:o?Cs:Es,priority:"High",payload:{data:JSON.stringify(e)}};return null===(i=null===(s=null===(n=this._core)||void 0===n?void 0:n.message)||void 0===s?void 0:s.messageFactory)||void 0===i?void 0:i.createCustomMessage(r)}_generateInviteID(){return[bs(Ps(32),8),bs(Ps(16),4),bs(16384|Ps(12),4),bs(32768|Ps(14),4),bs(Ps(48),12)].join("-")}_generateBaseSignalData(e){const{data:t="",inviteID:n="",groupID:s=""}=e;return{businessID:1,timeout:0,data:t,inviteID:n,groupID:s}}_getCurrentUserId(){var e,t;return null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("login"))||void 0===t?void 0:t.userId}};var Fs=new class{constructor(){this._isProcessingSignaling=!1}init(e){this._core=e,e.helper.registerApi("invite",this),e.helper.registerApi("accept",this),e.helper.registerApi("cancel",this),e.helper.registerApi("reject",this),e.helper.registerApi("modifyInvitation",this),e.helper.registerApi("addSignalingListener",this),e.helper.registerApi("removeSignalingListener",this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.LOGOUT,this._reset,this)}invite(e){return c(this,void 0,void 0,(function*(){var t;console.log(`${As}.invite params:${JSON.stringify(e)}`);try{this._validateBeforeInvite(e);const{signaling:n,signalingData:s,signalingExtensionOptions:i}=Us.createInviteSignaling(e),o=yield this._sendSignaling(n,i);if(0===(null==o?void 0:o.code)){const{inviteID:e,timeout:i}=s;return ks.saveSignaling(e,Object.assign(Object.assign({},s),{signaling:n})),i>0&&(null===(t=this._core)||void 0===t||t.helper.taskScheduler.addOnceTask({id:`${Ns}-${e}`,intervalMs:1e3*(i+5),callback:this.handleInvitationExpiryTimer.bind(this,e)})),Object.assign(Object.assign({},o),{inviteID:e})}return o}catch(e){throw console.error(`${As}.invite error:${e}`),e}}))}accept(e){return c(this,void 0,void 0,(function*(){console.log(`${As}.accept params:${JSON.stringify(e)}`);try{const{inviteID:t}=e;this._validateBeforeAccept(t),this._isProcessingSignaling=!0;const{signaling:n,signalingData:s,signalingExtensionOptions:i}=Us.createAcceptSignaling(e),o=yield this._sendSignaling(n,i);return 0===(null==o?void 0:o.code)?(ks.updateSignaling(s),Object.assign(Object.assign({},o),{inviteID:t})):o}catch(e){throw console.error(`${As}.accept error:${e}`),e}finally{this._isProcessingSignaling=!1}}))}cancel(e){return c(this,void 0,void 0,(function*(){console.log(`${As}.cancel params:${JSON.stringify(e)}`);try{const{inviteID:t}=e;this._validateBeforeCancel(t),this._isProcessingSignaling=!0;const{signaling:n,signalingExtensionOptions:s}=Us.createCancelSignaling(e),i=yield this._sendSignaling(n,s);return 0===(null==i?void 0:i.code)?(ks.removeSignaling(t),Object.assign(Object.assign({},i),{inviteID:t})):i}catch(e){throw console.error(`${As}.cancel error:${e}`),e}finally{this._isProcessingSignaling=!1}}))}reject(e){return c(this,void 0,void 0,(function*(){console.log(`${As}.reject params:${JSON.stringify(e)}`);try{const{inviteID:t}=e;this._validateBeforeReject(t),this._isProcessingSignaling=!0;const{signaling:n,signalingExtensionOptions:s}=Us.createRejectSignaling(e),i=yield this._sendSignaling(n,s);return 0===(null==i?void 0:i.code)?(ks.removeSignaling(t),Object.assign(Object.assign({},i),{inviteID:t})):i}catch(e){throw console.error(`${As}.reject error:${e}`),e}finally{this._isProcessingSignaling=!1}}))}modifyInvitation(e){return c(this,void 0,void 0,(function*(){var t,n;console.log(`${As}.modifyInvitation params:${JSON.stringify(e)}`);const{inviteID:s,data:i}=e;let o="";try{this._validateBeforeModifyInvitation(s);const e=ks.getSignaling(s),{signaling:r}=e,a=function(e,t){var n={};for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.indexOf(s)<0&&(n[s]=e[s]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(s=Object.getOwnPropertySymbols(e);i<s.length;i++)t.indexOf(s[i])<0&&Object.prototype.propertyIsEnumerable.call(e,s[i])&&(n[s[i]]=e[s[i]])}return n}(e,["signaling"]);o=r.payload.data,a.data=i,r.payload.data=JSON.stringify(a);const c=yield null===(n=null===(t=this._core)||void 0===t?void 0:t.message.messageAction)||void 0===n?void 0:n.modifyMessage(r);return ks.hasSignaling(s)&&ks.saveSignaling(s,Object.assign(Object.assign({},a),{signaling:r})),c}catch(e){if(o){const{signaling:e}=ks.getSignaling(s);e.payload.data=o}throw e}}))}addSignalingListener(e,t,n){var s,i;e===(null===(s=this._core)||void 0===s?void 0:s.SignalingEvent.NEW_INVITATION_RECEIVED)&&ks.setSignalingListenStatus(!0),null===(i=this._core)||void 0===i||i.notificationCenter.subscribeOuterEvent(e,t,n)}removeSignalingListener(e,t,n){var s,i;e===(null===(s=this._core)||void 0===s?void 0:s.SignalingEvent.NEW_INVITATION_RECEIVED)&&ks.setSignalingListenStatus(!1),null===(i=this._core)||void 0===i||i.notificationCenter.unSubscribeOuterEvent(e,t,n)}handleInvitationExpiryTimer(e){const t=ks.getOnlineSignalingMap(),n=this._getCurrentUserId();if(!t.has(e))return;const s=t.get(e).inviter===n;this._sendTimeoutNotice({inviteID:e,isInviter:s})}_sendSignaling(e,t){return c(this,void 0,void 0,(function*(){var n,s,i;return null===(i=null===(s=null===(n=this._core)||void 0===n?void 0:n.message)||void 0===s?void 0:s.messageSender)||void 0===i?void 0:i.sendMessage(e,t)}))}_sendTimeoutNotice(e){return c(this,void 0,void 0,(function*(){var t,n,s;console.log(`${As}._sendTimeoutNotice params:${JSON.stringify(e)}`);const{isInviter:i,inviteID:o}=e,{signaling:r,signalingData:a,signalingExtensionOptions:c}=Us.createTimeoutSignaling(e),l=yield this._sendSignaling(r,c);if(0===(null==l?void 0:l.code)){const{data:e,groupID:c,inviteeList:l,inviter:d}=a;null===(t=this._core)||void 0===t||t.notificationCenter.emitOuterEvent(null===(n=this._core)||void 0===n?void 0:n.SignalingEvent.INVITATION_TIMEOUT,{name:null===(s=this._core)||void 0===s?void 0:s.SignalingEvent.INVITATION_TIMEOUT,data:{data:e,groupID:c,inviteID:o,inviteeList:l,inviter:d,isSelfTimeout:!0,message:r}}),i?ks.removeSignaling(o):ks.updateSignaling(a)}}))}_validateInviteId(e,t){if(!ks.hasSignaling(t))throw new this._core.helper.ChatError({functionName:e,code:Ls})}_validateProcessStatus(e){if(this._isProcessingSignaling)throw new this._core.helper.ChatError({functionName:e,message:"processing other signaling operations"})}_validateBeforeInvite(e){const t=Os,{userID:n}=e,s=this._getCurrentUserId();if(n===s)throw new this._core.helper.ChatError({functionName:t,message:`cannot invite yourself, currentUserId:${s}, inviteeId:${n}`})}_validateBeforeAccept(e){const t=ys;this._validateInviteId(t,e),this._validateProcessStatus(t);const n=this._getCurrentUserId(),{inviteeList:s}=ks.getSignaling(e);if(!s.includes(n)){const s=`userID:${n} not in inviteeList. inviteID:${e}`;throw new this._core.helper.ChatError({functionName:t,message:s})}}_validateBeforeCancel(e){const t=Ms;this._validateInviteId(t,e),this._validateProcessStatus(t);const n=this._getCurrentUserId(),{inviter:s}=ks.getSignaling(e);if(s!==n){const e=`unmatched inviter:${s} and my userID:${n}`;throw new this._core.helper.ChatError({functionName:t,message:e})}}_validateBeforeReject(e){const t=Ts;this._validateInviteId(t,e),this._validateProcessStatus(t);const n=this._getCurrentUserId(),{inviteeList:s}=ks.getSignaling(e);if(!s.includes(n)){const s=`userID:${n} not in inviteeList. inviteID:${e}`;throw new this._core.helper.ChatError({functionName:t,message:s})}}_validateBeforeModifyInvitation(e){const t=Ds;this._validateInviteId(t,e)}_dispose(){var e,t;this._reset(),null===(e=this._core)||void 0===e||e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),null===(t=this._core)||void 0===t||t.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this)}_reset(){this._isProcessingSignaling=!1}_getCurrentUserId(){var e,t;return null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("login"))||void 0===t?void 0:t.userId}};var $s=new class{constructor(){this._actionProcessor=new Map([[ms,this._onNewInvitationReceived.bind(this)],[fs,this._onInviteeRejected.bind(this)],[vs,this._onInviteeAccepted.bind(this)],[ps,this._onInvitationCancelled.bind(this)],[Is,this._onInvitationTimeout.bind(this)]])}init(e){this._core=e,e.notificationCenter.subscribeOuterEvent(e.OuterEvent.MESSAGE_RECEIVED,this._handleMessageReceived,this),e.notificationCenter.subscribeOuterEvent(e.OuterEvent.MESSAGE_MODIFIED,this._handleMessageModified,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this)}handleActionSignaling(e){e.forEach((e=>{const t=Rs(e);if(t){const n=this._actionProcessor.get(t.actionType);null==n||n(t,e)}}))}_handleMessageReceived(e){if(!ks.getSignalingListenStatus())return;const t=ws(e.data);0!==t.length&&this.handleActionSignaling(t)}_handleMessageModified(e){if(!ks.getSignalingListenStatus())return;const t=ws(e.data);t.length>0&&t.forEach((e=>{const t=Rs(e);t&&this._onInvitationModified(t,e)}))}_onNewInvitationReceived(e,t){var n,s;const i=`${As}._onNewInvitationReceived`,{inviteID:o,inviteeList:r,groupID:a}=e,c=this._getCurrentUserId();console.log(`${i} signalingData:${JSON.stringify(e)}}`);if(a&&!r.includes(c))return;let{timeout:l}=e;const d=Date.now()/1e3-t.time;l>0&&d>0&&l>d&&(l-=d);const u=ks.getSignaling(o);u!==e&&(u||ks.saveSignaling(o,Object.assign(Object.assign({},e),{signaling:t})),l>0&&(null===(n=this._core)||void 0===n||n.helper.taskScheduler.addOnceTask({id:`${Ns}-${o}`,intervalMs:1e3*l,callback:Fs.handleInvitationExpiryTimer.bind(Fs,o)})),this._emitEvent({name:null===(s=this._core)||void 0===s?void 0:s.SignalingEvent.NEW_INVITATION_RECEIVED,data:Object.assign(Object.assign({},this._generateBaseEmitData(e)),{inviteeList:r})}))}_onInviteeRejected(e){var t;const n=`${As}._onInviteeRejected`,{inviteID:s,inviter:i,groupID:o,inviteeList:r}=e,a=ks.hasSignaling(s);console.log(`${n} inviteID:${s} hasInviteID:${a} inviter:${i} groupID:${o}`),a&&(ks.updateSignaling(e),this._emitEvent({name:null===(t=this._core)||void 0===t?void 0:t.SignalingEvent.INVITEE_REJECTED,data:Object.assign(Object.assign({},this._generateBaseEmitData(e)),{invitee:r[0]})}))}_onInviteeAccepted(e){var t;const n=`${As}._onInviteeAccepted`,{inviteID:s,inviter:i,groupID:o,inviteeList:r}=e,a=ks.hasSignaling(s);console.log(`${n} inviteID:${s} hasInviteID:${a} inviter:${i} groupID:${o}`),a&&(ks.updateSignaling(e),this._emitEvent({name:null===(t=this._core)||void 0===t?void 0:t.SignalingEvent.INVITEE_ACCEPTED,data:Object.assign(Object.assign({},this._generateBaseEmitData(e)),{invitee:r[0]})}))}_onInvitationCancelled(e){var t;const n=`${As}._onInvitationCancelled`,{inviteID:s,inviter:i,groupID:o}=e,r=ks.hasSignaling(s);console.log(`${n} inviteID:${s} hasInviteID:${r} inviter:${i} groupID:${o}`),r&&(ks.removeSignaling(s),this._emitEvent({name:null===(t=this._core)||void 0===t?void 0:t.SignalingEvent.INVITATION_CANCELLED,data:this._generateBaseEmitData(e)}))}_onInvitationTimeout(e){var t;const n=`${As}._onInvitationTimeout`,{inviteID:s,inviteeList:i}=e,o=ks.hasSignaling(s);console.log(`${n} inviteID:${s} hasInviteID:${o} data:${e.data}`),o&&(ks.updateSignaling(e),this._emitEvent({name:null===(t=this._core)||void 0===t?void 0:t.SignalingEvent.INVITATION_TIMEOUT,data:Object.assign(Object.assign({},this._generateBaseEmitData(e)),{inviteeList:i,isSelfTimeout:!1})}))}_onInvitationModified(e,t){var n;const s=`${As}._onInvitationModified`,{inviteID:i,data:o}=e,r=ks.hasSignaling(i);console.log(`${s} inviteID:${i} data:${o}`),r&&(ks.saveSignaling(i,Object.assign(Object.assign({},e),{signaling:t})),this._emitEvent({name:null===(n=this._core)||void 0===n?void 0:n.SignalingEvent.INVITATION_MODIFIED,data:{inviteID:i,data:o}}))}_emitEvent(e){var t;null===(t=this._core)||void 0===t||t.notificationCenter.emitOuterEvent(e.name,e)}_generateBaseEmitData(e){const{inviteID:t,inviter:n,groupID:s,data:i}=e;return{inviteID:t,inviter:n,groupID:s,data:i||""}}_getCurrentUserId(){var e,t;return null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("login"))||void 0===t?void 0:t.userId}_dispose(){var e,t,n;null===(e=this._core)||void 0===e||e.notificationCenter.unSubscribeOuterEvent(this._core.OuterEvent.MESSAGE_RECEIVED,this._handleMessageReceived,this),null===(t=this._core)||void 0===t||t.notificationCenter.unSubscribeOuterEvent(this._core.OuterEvent.MESSAGE_MODIFIED,this._handleMessageModified,this),null===(n=this._core)||void 0===n||n.notificationCenter.unSubscribeOuterEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}};var Gs=new class{constructor(){this._offlineSignalingMap=new Map}init(e){this._core=e,e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.LOGOUT,this._reset,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.UNREAD_MESSAGES_SYNC_COMPLETED,this._handleC2COfflineMessage,this)}_handleC2COfflineMessage(e){if(!(0!==(null==e?void 0:e.unreadMessageMap.size)&&ks.getSignalingListenStatus()))return;const t=ws([...e.unreadMessageMap.values()]);if(0!==t.length&&(t.forEach((e=>{this._handleC2CActionType(e)})),this._offlineSignalingMap.size>0)){const e=this._sortOfflineSignalingByTime();$s.handleActionSignaling(e)}}_handleC2CActionType(e){const t=Rs(e);if(!t)return;const{actionType:n}=t;n===ms?this._saveValidOfflineInvite(t,e):this._removeOfflineInvite(t)}_saveValidOfflineInvite(e,t){const{inviteID:n,inviteeList:s=[],timeout:i=0}=e,o=this._getCurrentUserId();if(!s.includes(o))return;const r=Date.now()/1e3-t.time;i>0&&r>i&&0!==i||this._offlineSignalingMap.set(n,Object.assign(Object.assign({},e),{signalingList:[t]}))}_removeOfflineInvite(e){const{inviteID:t=""}=e;this._offlineSignalingMap.has(t)&&this._offlineSignalingMap.delete(t)}_sortOfflineSignalingByTime(){let e=[];return this._offlineSignalingMap.forEach((t=>{e=[...e,...t.signalingList]})),e.sort(((e,t)=>e.time-t.time))}_getCurrentUserId(){var e,t;return null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("login"))||void 0===t?void 0:t.userId}_dispose(){var e,t,n;this._reset(),null===(e=this._core)||void 0===e||e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.UNREAD_MESSAGES_SYNC_COMPLETED,this._handleC2COfflineMessage,this),null===(t=this._core)||void 0===t||t.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),null===(n=this._core)||void 0===n||n.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}_reset(){this._offlineSignalingMap.clear()}};const qs={invite:{userID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0},timeout:{required:!1,rules:["number"],allowEmpty:!1},onlineUserOnly:{required:!1,rules:["boolean"],allowEmpty:!1},offlinePushInfo:{required:!1,rules:["object"],allowEmpty:!1}},cancel:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}},accept:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}},reject:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}},modifyInvitation:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}}};var Bs=new class{install(e){Fs.init(e),$s.init(e),Us.init(e),ks.init(e),Gs.init(e),e.helper.registerParamsConfig(qs)}};const xs=new Set(["tui_room_svr.*","callkit_records_svr.*","room_engine_srv.*","room_engine_http_srv.*","room_engine_mic.*","live_engine_srv.*","live_engine_http_srv.*","live_engine_pk.*","trtc_ai_service.*","call_engine_srv.*"]),js="tui_room_svr.*";var Vs=new class{constructor(){this._transferredCommands=xs}install(e){this._core=e;const{notificationCenter:t,InnerEvent:n,helper:s}=e;t.subscribeInnerEvent(n.CLOUD_CONFIG_UPDATE,this._onCloudConfigUpdate,this),t.subscribeInnerEvent(n.LOGOUT,this._reset,this),t.subscribeInnerEvent(n.DESTROY,this._dispose,this),t.subscribeInnerEvent("im_open_push.msg_push",t.InnerEventSubType.BUSINESS_COMMAND,this._onServerPushBusinessCommand,this),s.registerExperimentalAPI("sendTRTCCustomData",this,"transferBusinessCommand"),s.registerExperimentalAPI("sendRoomCustomData",this,"transferBusinessCommand")}transferBusinessCommand(e){return c(this,void 0,void 0,(function*(){const t="transferBusinessCommand";try{const{serviceCommand:n=js}=e||{};if(!this._isValidTransferredCommand(n))throw new this._core.helper.ChatError({code:2995,functionName:t});const s=yield function(e,t){return c(this,void 0,void 0,(function*(){const{helper:n,channel:s}=t,{serviceCommand:i=js,data:o}=e||{};let r={};try{r="string"==typeof o?JSON.parse(o):o}catch(e){console.warn(e)}const a=n.generateProtocolData({servcmd:i,data:r}),c=`${a.head.seq}${i}`;return s.sendPacket(a,{requestId:c})}))}(e,this._core);return{code:0,data:s||{}}}catch(e){throw console.warn(e),new this._core.helper.ChatError({code:null==e?void 0:e.errorCode,data:{},functionName:t})}}))}_onCloudConfigUpdate(e={}){try{if("string"!=typeof e.rtc_cmd)return;const t=JSON.parse(e.rtc_cmd);Array.isArray(t)&&(this._transferredCommands=new Set([...this._transferredCommands,...t]))}catch(e){console.log(e)}}_isValidTransferredCommand(e=""){const t=`${null==e?void 0:e.split(".")[0]}.*`;return this._transferredCommands.has(t)}_onServerPushBusinessCommand(e){const{OuterEvent:t,notificationCenter:n}=this._core,{MsgContent:s}=e||{},{ROOM_CUSTOM_DATA_RECEIVED:i}=t;n.emitOuterEvent(i,{name:i,data:s})}_reset(){this._transferredCommands=xs}_dispose(){const{notificationCenter:e,InnerEvent:t}=this._core;this._reset(),e.unSubscribeInnerEvent(t.CLOUD_CONFIG_UPDATE,this._onCloudConfigUpdate,this),e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this),e.unSubscribeInnerEvent("im_open_push.msg_push",e.InnerEventSubType.BUSINESS_COMMAND,this._onServerPushBusinessCommand,this)}};const Ks=new Map;let Ys=new WeakSet;const Hs=[is,function(e){Xn.install(e),ns.install(e),ss.install(e)},function(e){cs.install(e)},gs,Vs,Bs];function Ws(e,...t){Ys.has(e)?console.warn("Plugin has already been applied to target app."):e&&ft(e.install)?(Ys.add(e),e.install(Lt(),...t)):ft(e)?(Ys.add(e),e(Lt(),...t)):console.warn('A plugin must either be a function or an object with an "install" function.')}function Js(){Ys=new WeakSet}var zs={create:function(e){const{SDKAppID:t,testEnv:n=!1,devMode:s=!1}=e;let i=t;if(!function(e){if("number"==typeof e)return!0;const t=Number(e);return!Number.isNaN(t)}(i))return console.error("Create SDK instance failed. Failed to parse the SDKAppID, please check the arguments"),null;if(i=Number(i),Ks.has(i))return Ks.get(i);const o=function(){function e(){return(65536*(1+Math.random())|0).toString(16).substring(1)}return`${e()+e()}${e()}${e()}${e()}${e()}${e()}${e()}`}();rt.init({sdkAppId:i,instanceId:o,testEnv:n,devMode:s}),rt.message=new On,rt.user=new Kn,rt.login=new Wt,Hs.forEach((e=>Ws(e)));const r=Ot;return Ks.set(i,r),r},TSignaling:_t,EVENT:lt,VERSION:"1.0.0",TYPES:gt};export{Js as clearInstalledPlugins,zs as default,Ks as liteChatInstanceMap,Ws as use};
2
- //# sourceMappingURL=index.esm.js.map
package/index.esm.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.esm.js","sources":[],"sourcesContent":[],"names":[],"mappings":""}
package/index.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":""}