@tencentcloud/lite-chat 1.1.0 → 1.1.1-beta.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.js CHANGED
@@ -1 +1 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).LiteChat={})}(this,(function(e){"use strict";class t{constructor(){this.listeners={}}on(e,t,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 n;!function(e){e.BUSINESS_COMMAND="business_command",e.C2C_REALTIME_MESSAGE="C2cMsgArray",e.C2C_MODIFIED_MESSAGE="C2cMsgModNotifys",e.PROFILE_MODIFIED="ProfileDataMod",e.GROUP_REALTIME_MESSAGE="GroupMsgArray",e.GROUP_MODIFIED_MESSAGE="GroupMsgModNotifys",e.C2C_NOTIFY_MESSAGE="C2cNotifyMsgArray",e.GROUP_NOTIFY_MESSAGE="GroupTips"}(n||(n={}));const s=[{type:"event",value:100,subType:n.BUSINESS_COMMAND},{type:"hasKey",value:"C2cMsgArray",subType:n.C2C_REALTIME_MESSAGE},{type:"hasKey",value:"C2cMsgModNotifys",subType:n.C2C_MODIFIED_MESSAGE},{type:"hasKey",value:"ProfileDataMod",subType:n.PROFILE_MODIFIED},{type:"hasKey",value:"GroupMsgArray",subType:n.GROUP_REALTIME_MESSAGE},{type:"hasKey",value:"GroupMsgModNotifys",subType:n.GROUP_MODIFIED_MESSAGE},{type:"hasKey",value:"C2cNotifyMsgArray",subType:n.C2C_NOTIFY_MESSAGE},{type:"hasKey",value:"GroupTips",subType:n.GROUP_NOTIFY_MESSAGE}];var i;!function(e){e.SERVER_PUSH_MESSAGE="im_open_push.msg_push",e.ERROR="error"}(i||(i={}));const o={[i.SERVER_PUSH_MESSAGE]:function(e){const{EventArray:t}=(null==e?void 0:e.body)||{};return t.map((e=>{const{Event:t}=e,n=s.find((e=>"event"===e.type&&e.value===t));if(n)return{type:`${i.SERVER_PUSH_MESSAGE}:${n.subType}`,data:e};const o=s.find((t=>"hasKey"===t.type&&Object.prototype.hasOwnProperty.call(e,t.value)));return o?{type:`${i.SERVER_PUSH_MESSAGE}:${o.subType}`,data:e}:void 0}))},[i.ERROR]:function(e){const{errorCode:t}=e;return[{type:`error:${t}`,data:e}]}};const r=new class{constructor(){this._outerEventEmitter=null,this._innerEventEmitter=null,this._outerEventEmitter=new t,this._innerEventEmitter=new t,this.InnerEventSubType=n}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(o).includes(e)){const n=null===(s=o[e])||void 0===s?void 0:s.call(o,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 a(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 c=e=>{if("string"!=typeof e)return!1;const t=e[0];return!/[^a-zA-Z0-9]/.test(t)},l=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 d(e=99999999){return Math.round(Math.random()*e)}function u(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 h={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},_=["heartbeat.alive","im_open_status.wslogin","im_open_status.wslogout","group_open_long_polling_http_svc.get_msg","group_open_long_polling_http_noauth_svc.get_msg"],g="undefined"!=typeof wx&&"function"==typeof wx.getSystemInfoSync&&Boolean(wx.getSystemInfoSync().fontSizeSetting),f=g&&"function"==typeof wx.createGamePortal,m="undefined"!=typeof qq&&"function"==typeof qq.getSystemInfoSync&&Boolean(qq.getSystemInfoSync().fontSizeSetting),v="undefined"!=typeof tt&&"function"==typeof tt.getSystemInfoSync&&Boolean(tt.getSystemInfoSync().fontSizeSetting),p="undefined"!=typeof swan&&"function"==typeof swan.getSystemInfoSync&&Boolean(swan.getSystemInfoSync().fontSizeSetting),S="undefined"!=typeof my&&"function"==typeof my.getSystemInfoSync&&Boolean(my.getSystemInfoSync().fontSizeSetting),I="undefined"!=typeof jd&&"function"==typeof jd.getSystemInfoSync,E="undefined"!=typeof uni&&"undefined"==typeof window&&"function"==typeof uni.requireNativePlugin,y=g&&"object"==typeof wx.miniapp,C="undefined"!=typeof uni,M=g||m||v||p||S||E||I,O="undefined"==typeof window&&!M&&"undefined"!=typeof global&&void 0!==global.NativeScriptGlobals,T="undefined"!=typeof global&&(void 0!==global.nativeModuleProxy||void 0!==global.ReactNative),D="undefined"!=typeof uni?!M:"undefined"!=typeof window&&!M&&!T,A=m?qq:v?tt:p?swan:S?my:g?wx:E?uni:I?jd:{},b=D&&window&&window.navigator&&window.navigator.userAgent||"",w=/(micromessenger|webbrowser)/i.test(b),N=function(){let e="WEB";return w?e="WEB":m?e="QQ_MP":v?e="TT_MP":p?e="BAIDU_MP":S?e="ALI_MP":g?e=y?"DONUT_NATIVE_APP":"WX_MP":E?e="UNI_NATIVE_APP":O?e="NS_NATIVE_APP":T&&(e="RN_NATIVE_APP"),h[e]}(),R=/iPad/i.test(b),L=/iPhone/i.test(b)&&!R,k=/iPod/i.test(b),P=L||R||k,U=function(){const e=b.match(/OS (\d+)_/i);return e&&e[1]?e[1]:null}(),F=/Android/i.test(b),G=function(){const e=b.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}(),B=/Firefox/i.test(b),$=/Edge/i.test(b),x=!$&&/Chrome/i.test(b),q=/MSIE/.test(b)||b.indexOf("Trident")>-1&&b.indexOf("rv:11.0")>-1,j=function(){const e=/MSIE\s(\d+)\.\d/.exec(b);let t=e&&parseFloat(e[1]);return!t&&/Trident\/7.0/i.test(b)&&/rv:11.0/.test(b)&&(t=11),t}(),V=/Safari/i.test(b)&&!x&&!F&&!$,Y=/Windows/i.test(b),K=/MAC OS X/i.test(b),H=D&&"undefined"!=typeof Worker&&!q,W=F||P,z=D&&void 0!==window.tencent_cloud_im_csig_flutter_for_web_25F_cy,J=function(){if("undefined"==typeof window||void 0===window.navigator)return!1;const{standalone:e}=window.navigator;return!(!P||e||V)}();function Z(){let e="unknown";if(K&&(e="mac"),Y&&(e="windows"),P&&(e="ios"),F&&(e="android"),M)try{const{platform:t}=wx.getSystemInfoSync();void 0!==t&&(e=t)}catch(e){console.error(e)}return e}const X=2800,Q=2801,ee=3e3,te="application/x-www-form-urlencoded;charset=UTF-8";function ne(e){return a(this,arguments,void 0,(function*({method:e,url:t,data:n,timeout:s=ee}){return new Promise(M?(i,o)=>{A.request({url:t,data:n,method:e,timeout:s,header:{"content-type":te},success:e=>i(e.data),fail:()=>o(new Error(`{"message":"Network error","code":${X}}`))})}:(i,o)=>{const r=new XMLHttpRequest,a=setTimeout((()=>{r.abort(),o(new Error(`{"message":"Request timeout","code":${Q}}`))}),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":${X}}`))},r.open(e,t,!0),r.setRequestHeader("Content-type",te),r.send(n||null)})}))}function se(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(l(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 ie(){let e,t;return{promise:new Promise(((n,s)=>{e=n,t=s})),resolve:e,reject:t}}var oe,re=Object.freeze({__proto__:null,ANDROID_VERSION:G,IE_VERSION:j,IN_ALIPAY_MINI_APP:S,IN_BAIDU_MINI_APP:p,IN_BROWSER:D,IN_DONUT_NATIVE_APP:y,IN_JD_MINI_APP:I,IN_MINI_APP:M,IN_NS_NATIVE_APP:O,IN_QQ_MINI_APP:m,IN_RN_APP:T,IN_TT_MINI_APP:v,IN_UNI_APP:C,IN_UNI_NATIVE_APP:E,IN_WX_MINI_APP:g,IN_WX_MINI_GAME:f,IOS_VERSION:U,IS_ANDROID:F,IS_CHROME:x,IS_EDGE:$,IS_FIREFOX:B,IS_IE:q,IS_IOS:P,IS_IPAD:R,IS_IPHONE:L,IS_IPOD:k,IS_MAC:K,IS_SAFARI:V,IS_WECHAT:w,IS_WIN:Y,IS_WORKER_AVAILABLE:H,MINI_APP_NAMESPACE:A,USER_AGENT:b,base16EncodeBinaryString:u,generatePromise:ie,getPlatformType:Z,httpRequest:ne,isEmpty:se,isFlutterWeb:z,isH5:W,isIOSWebView:J,isPlainObject:l,isValidRequestKey:c,platform:N,randomInt:d});class ae{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 ce{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"}(oe||(oe={}));class le{constructor(e){this._url="",this._readyState=oe.DISCONNECTED,this._url=e,this._id=d(),this._emitter=new t,this._socket=g?new ce:new ae,this.connect()}connect(){this.doOpen(),this._bindSocketHandlers()}doOpen(){[oe.CONNECTED,oe.CONNECTING].includes(this._readyState)||(this._readyState=oe.CONNECTING,this._ws=this._socket.connectSocket(this._url))}send(e){this._readyState!==oe.CONNECTED?this.reconnect():this._socket.send(e)}reconnect(){[oe.CONNECTED,oe.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===oe.CONNECTED}disconnect(){this._readyState=oe.DISCONNECTED,this._unbindSocketHandlers(),this._socket.disconnect()}_onOpen(e){this._readyState===oe.CONNECTING&&(this._readyState=oe.CONNECTED,this._emitter.emit("connect",{socketId:this._id,event:e}))}_onMessage(e){this._emitter.emit("message",e)}_onClose(e){this._readyState=oe.DISCONNECTED,this._emitter.emit("close",{socketId:this._id,event:e})}_onError(e){this._readyState=oe.DISCONNECTED,this._emitter.emit("error",{socketId:this._id,error:e})}_onSendFail(e){this._readyState=oe.DISCONNECTED,this._emitter.emit("sendFail",{socketId:this._id,error: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 de="CHINA",ue="SINGAPORE",he="KOREA",_e="GERMANY",ge="IND",fe="JPN",me="USA",ve="INDONESIA",pe={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={[ue]:[[2e7,3e7],[172e7,173e7]],[he]:[[3e7,4e7],[173e7,174e7]],[_e]:[[4e7,5e7],[174e7,175e7]],[ge]:[[5e7,6e7],[175e7,176e7]],[fe]:[[6e7,7e7],[176e7,177e7]],[me]:[[7e7,8e7],[177e7,178e7]],[ve]:[[8e7,9e7],[178e7,179e7]]};function Ie(e){for(const t of Object.keys(Se))for(const[n,s]of Se[t])if(e>=n&&e<s)return t;return de}var Ee,ye=new class{constructor(){this._store=new Map}get(e){return this._store.get(e)}getStorage(e){if(M){if(S){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){M?S?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)}},Ce="1.0.0";!function(e){e.INITIAL="INITIAL",e.DEFAULT="DEFAULT",e.BACKUP="BACKUP",e.ANYCAST="ANYCAST"}(Ee||(Ee={}));let Me=Ee.INITIAL;function Oe(){const e=Math.random();return 0===e?Oe():e}function Te(e,t){const{isBinary:n=!1}=t||{},s=ye.get("instance"),{sdkAppId:i,instanceId:o}=s,r=Oe(),a=Z(),c=function(){const e=Z();let t=-1;"ios"===e?t=U||-1:"android"===e&&(t=G||-1);return t}(),l=(d={sdkappid:i,instanceid:o,random:r,platform:N,host:a,version:c,sdkversion:Ce},Object.keys(d).map((e=>`${e}=${d[e]}`)).join("&"));var d;return n?`${e}/binfo?${l}&compress=gzip`:`${e}/info?${l}`}var De=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 Ae=16;var be=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=Ae}=e,r=Math.max(o,Ae);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){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)}function Ne(e){const t=Array.isArray(e)?[]:Object.create(null);for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&c(n)&&null!=e[n]&&(null===e[n]||"object"!=typeof e[n]?t[n]=e[n]:t[n]=Ne(e[n]));return t}function Re(e,t){if(_.includes(e))return 0;const n=we(JSON.stringify(t));let s=4294967295;const{length:i}=n;for(let e=0;e<i;e++){s^=n[e];for(let e=0;e<8;e++)1&~s?s>>>=1:s=s>>>1^3988292384}return(4294967295^s)>>>0}function Le(e){const{servcmd:t,data:n}=e,s=function(e){const t=ye.get("login")||{},n=ye.get("instance")||{};return{servcmd:e,ver:"v4",platform:N,websdkappid:537048168,websdkversion:"1.7.3",a2:t.a2Key||void 0,tinyid:t.tinyID||void 0,status_instid:t.statusInstanceId||0,sdkappid:n.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:t.a2Key?void 0:t.userId,usersig:t.a2Key?void 0:t.userSig,sdkability:75689843,sdkability_ext:u(""),cappid:t.cappid||0,tjgID:"",seq:Ue(),cs:0}}(t),i=Ne(n);return s.cs=Re(t,i),{head:s,body:i}}function ke(e){const{servcmd:t,data:n}=e,s=function(e){const t=ye.get("login")||{},n=ye.get("instance")||{};return{servcmd:e,ver:"v4",platform:N,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:n.sdkAppId,contenttype:"",reqtime:Math.floor(Date.now()/1e3),identifier:"",usersig:"",status_instid:t.statusInstanceId||0,sdkability:75689843,sdkability_ext:u(""),cappid:t.cappid||0,seq:Ue(),cs:0}}(t),i=Ne(n);return s.cs=Re(t,i),{head:s,body:i}}let Pe=d();function Ue(){return Pe=Pe<2415919103?Pe+1:d(),Pe}var Fe,Ge=Object.freeze({__proto__:null,generateCosSpecifiedData:function(e){const{servcmd:t,data:n}=e,s=function(e){const t=ye.get("login")||{},n=ye.get("instance")||{};return{servcmd:e,ver:"v4",platform:N,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:n.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:t.userId,usersig:t.userSig,status_instid:t.statusInstanceId||0,sdkability:75689843,sdkability_ext:u(""),cappid:t.cappid||0,seq:Ue(),cs:0}}(t),i=Ne(n);return s.cs=Re(t,i),{head:s,body:i}},generateProtocolData:Le,generateSSOLogProtocolData:ke,generateSequence:Ue,taskScheduler:be,timeManager:De});!function(e){e[e.info=4]="info",e[e.warning=5]="warning",e[e.error=6]="error"}(Fe||(Fe={}));const Be={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 $e{constructor(e){this.level=Fe.info,this._canSendLog=!0,this._logCreatedAt=De.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+=De.getTimeOffsetWithServer()}end(e=!1){if(!this._canSendLog)return;const t=De.getServerTimeMs();0===this.costTime&&(this.costTime=t-this._logCreatedAt),this.setMoreMessage(`startts:${this._logCreatedAt} endts:${t}`),e?(this._canSendLog=!1,this.timestamp=De.getServerTimeMs(),this._ssoLogModule.pushToLogQueue(this._convertSSOLogDataKeyToServe())):setTimeout((()=>{this._canSendLog=!1,this.timestamp=De.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=ye.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(Be).includes(t)&&(this[t]=e[t])})),this}setSSOLogModule(e){this._ssoLogModule=e}_convertSSOLogDataKeyToServe(){const e={};return Object.keys(this).forEach((t=>{const n=t;Be[n]&&(e[Be[n]]=this[n])})),e}}function xe(){const e=ye.get("login")||{},t=ye.get("instance")||{};return{sdk_type:30,sdk_app_id:t.sdkAppId,sdk_version:Ce,tiny_id:Number(e.tinyID),user_id:e.userId,platform:N,instance_id:t.instanceId,trace_id:(new Date).getTime()}}var qe;!function(e){e.RECONNECTED="reconnected",e.CLOUD_CONFIG_UPDATE="cloud_config_update",e.SOCKET_DISCONNECTED="socket_disconnected"}(qe||(qe={}));var je=qe;const Ve=20,Ye=6e4,Ke=[4,5,6],He=[],We=[],ze="report-logger";var Je=new class{constructor(){this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._reportLevel=[4,5,6],this._minThreshold=Ve,this._maxThreshold=100,this._waitingTime=Ye,this._lastReportAt=Date.now(),this._ssoLogMap=new Map,r.subscribeInnerEvent(je.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),be.addTask({id:ze,intervalMs:1e3,callback:this._checkAndReportIfDue,context:this}),this._logQueue=[],this._savePlatFormInfo()}_handleCloudConfigUpdate(e){const{evt_rpt_threshold:t=Ve,evt_rpt_waiting:n=Ye,evt_rpt_level:s=Ke,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 $e(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 a(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:xe(),Event:t};yield function(e){const t="imopenstat.tim_web_report_v2",n=ke({servcmd:t,data:e}),s=`${n.head.seq}${t}`;vt.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;ye.set("instance",{appId:e,envVersion:t})}}else D&&ye.set("instance",{href:window.location.href})}_filterLogs(e){const{tinyID:t}=ye.get("login")||{},{sdkAppId:n}=ye.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"),be.removeTask(ze),r.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=Ye,this._logQueue=[]}};const Ze=15e3,Xe="Channel",Qe="channel_schedule_task",et="channel_reconnect_task",nt="connected",st="connecting",it="disconnected",ot=500,rt="network_status_change",at="activity_status_change",ct="send_fail",lt="reconnect_failed",dt="socket_error",ut="socket_close";function ht(e){return ht="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},ht(e)}function _t(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var gt,ft={exports:{}};var mt=(gt||(gt=1,function(e){e.exports=function e(t,n,s){function i(r,a){if(!n[r]){if(!t[r]){if(!a&&_t)return _t(r);if(o)return o(r,!0);var c=new Error("Cannot find module '"+r+"'");throw c.code="MODULE_NOT_FOUND",c}var l=n[r]={exports:{}};t[r][0].call(l.exports,(function(e){return i(t[r][1][e]||e)}),l,l.exports,e,t,n,s)}return n[r].exports}for(var o=_t,r=0;r<s.length;r++)i(s[r]);return i}({1:[function(e,t,n){var s="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;n.assign=function(e){for(var t,n,s=Array.prototype.slice.call(arguments,1);s.length;){var i=s.shift();if(i){if("object"!=ht(i))throw new TypeError(i+"must be non-object");for(var o in i)t=i,n=o,Object.prototype.hasOwnProperty.call(t,n)&&(e[o]=i[o])}}return e},n.shrinkBuf=function(e,t){return e.length===t?e:e.subarray?e.subarray(0,t):(e.length=t,e)};var i={arraySet:function(e,t,n,s,i){if(t.subarray&&e.subarray)e.set(t.subarray(n,n+s),i);else for(var o=0;o<s;o++)e[i+o]=t[n+o]},flattenChunks:function(e){var t,n,s,i,o,r;for(t=s=0,n=e.length;t<n;t++)s+=e[t].length;for(r=new Uint8Array(s),t=i=0,n=e.length;t<n;t++)o=e[t],r.set(o,i),i+=o.length;return r}},o={arraySet:function(e,t,n,s,i){for(var o=0;o<s;o++)e[i+o]=t[n+o]},flattenChunks:function(e){return[].concat.apply([],e)}};n.setTyped=function(e){e?(n.Buf8=Uint8Array,n.Buf16=Uint16Array,n.Buf32=Int32Array,n.assign(n,i)):(n.Buf8=Array,n.Buf16=Array,n.Buf32=Array,n.assign(n,o))},n.setTyped(s)},{}],2:[function(e,t,n){var s=e("./common"),i=!0,o=!0;try{String.fromCharCode.apply(null,[0])}catch(e){i=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(e){o=!1}for(var r=new s.Buf8(256),a=0;a<256;a++)r[a]=252<=a?6:248<=a?5:240<=a?4:224<=a?3:192<=a?2:1;function c(e,t){if(t<65534&&(e.subarray&&o||!e.subarray&&i))return String.fromCharCode.apply(null,s.shrinkBuf(e,t));for(var n="",r=0;r<t;r++)n+=String.fromCharCode(e[r]);return n}r[254]=r[254]=1,n.string2buf=function(e){var t,n,i,o,r,a=e.length,c=0;for(o=0;o<a;o++)55296==(64512&(n=e.charCodeAt(o)))&&o+1<a&&56320==(64512&(i=e.charCodeAt(o+1)))&&(n=65536+(n-55296<<10)+(i-56320),o++),c+=n<128?1:n<2048?2:n<65536?3:4;for(t=new s.Buf8(c),o=r=0;r<c;o++)55296==(64512&(n=e.charCodeAt(o)))&&o+1<a&&56320==(64512&(i=e.charCodeAt(o+1)))&&(n=65536+(n-55296<<10)+(i-56320),o++),n<128?t[r++]=n:(n<2048?t[r++]=192|n>>>6:(n<65536?t[r++]=224|n>>>12:(t[r++]=240|n>>>18,t[r++]=128|n>>>12&63),t[r++]=128|n>>>6&63),t[r++]=128|63&n);return t},n.buf2binstring=function(e){return c(e,e.length)},n.binstring2buf=function(e){for(var t=new s.Buf8(e.length),n=0,i=t.length;n<i;n++)t[n]=e.charCodeAt(n);return t},n.buf2string=function(e,t){var n,s,i,o,a=t||e.length,l=new Array(2*a);for(n=s=0;n<a;)if((i=e[n++])<128)l[s++]=i;else if(4<(o=r[i]))l[s++]=65533,n+=o-1;else{for(i&=2===o?31:3===o?15:7;1<o&&n<a;)i=i<<6|63&e[n++],o--;1<o?l[s++]=65533:i<65536?l[s++]=i:(i-=65536,l[s++]=55296|i>>10&1023,l[s++]=56320|1023&i)}return c(l,s)},n.utf8border=function(e,t){var n;for((t=t||e.length)>e.length&&(t=e.length),n=t-1;0<=n&&128==(192&e[n]);)n--;return n<0||0===n?t:n+r[e[n]]>t?n:t}},{"./common":1}],3:[function(e,t,n){t.exports=function(e,t,n,s){for(var i=65535&e,o=e>>>16&65535,r=0;0!==n;){for(n-=r=2e3<n?2e3:n;o=o+(i=i+t[s++]|0)|0,--r;);i%=65521,o%=65521}return i|o<<16}},{}],4:[function(e,t,n){t.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],5:[function(e,t,n){var s=function(){for(var e,t=[],n=0;n<256;n++){e=n;for(var s=0;s<8;s++)e=1&e?3988292384^e>>>1:e>>>1;t[n]=e}return t}();t.exports=function(e,t,n,i){var o=s,r=i+n;e^=-1;for(var a=i;a<r;a++)e=e>>>8^o[255&(e^t[a])];return~e}},{}],6:[function(e,t,n){t.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],7:[function(e,t,n){t.exports=function(e,t){var n,s,i,o,r,a,c,l,d,u,h,_,g,f,m,v,p,S,I,E,y,C,M,O,T;n=e.state,s=e.next_in,O=e.input,i=s+(e.avail_in-5),o=e.next_out,T=e.output,r=o-(t-e.avail_out),a=o+(e.avail_out-257),c=n.dmax,l=n.wsize,d=n.whave,u=n.wnext,h=n.window,_=n.hold,g=n.bits,f=n.lencode,m=n.distcode,v=(1<<n.lenbits)-1,p=(1<<n.distbits)-1;e:do{g<15&&(_+=O[s++]<<g,g+=8,_+=O[s++]<<g,g+=8),S=f[_&v];t:for(;;){if(_>>>=I=S>>>24,g-=I,0==(I=S>>>16&255))T[o++]=65535&S;else{if(!(16&I)){if(!(64&I)){S=f[(65535&S)+(_&(1<<I)-1)];continue t}if(32&I){n.mode=12;break e}e.msg="invalid literal/length code",n.mode=30;break e}E=65535&S,(I&=15)&&(g<I&&(_+=O[s++]<<g,g+=8),E+=_&(1<<I)-1,_>>>=I,g-=I),g<15&&(_+=O[s++]<<g,g+=8,_+=O[s++]<<g,g+=8),S=m[_&p];n:for(;;){if(_>>>=I=S>>>24,g-=I,!(16&(I=S>>>16&255))){if(!(64&I)){S=m[(65535&S)+(_&(1<<I)-1)];continue n}e.msg="invalid distance code",n.mode=30;break e}if(y=65535&S,g<(I&=15)&&(_+=O[s++]<<g,(g+=8)<I&&(_+=O[s++]<<g,g+=8)),c<(y+=_&(1<<I)-1)){e.msg="invalid distance too far back",n.mode=30;break e}if(_>>>=I,g-=I,(I=o-r)<y){if(d<(I=y-I)&&n.sane){e.msg="invalid distance too far back",n.mode=30;break e}if(M=h,(C=0)===u){if(C+=l-I,I<E){for(E-=I;T[o++]=h[C++],--I;);C=o-y,M=T}}else if(u<I){if(C+=l+u-I,(I-=u)<E){for(E-=I;T[o++]=h[C++],--I;);if(C=0,u<E){for(E-=I=u;T[o++]=h[C++],--I;);C=o-y,M=T}}}else if(C+=u-I,I<E){for(E-=I;T[o++]=h[C++],--I;);C=o-y,M=T}for(;2<E;)T[o++]=M[C++],T[o++]=M[C++],T[o++]=M[C++],E-=3;E&&(T[o++]=M[C++],1<E&&(T[o++]=M[C++]))}else{for(C=o-y;T[o++]=T[C++],T[o++]=T[C++],T[o++]=T[C++],2<(E-=3););E&&(T[o++]=T[C++],1<E&&(T[o++]=T[C++]))}break}}break}}while(s<i&&o<a);s-=E=g>>3,_&=(1<<(g-=E<<3))-1,e.next_in=s,e.next_out=o,e.avail_in=s<i?i-s+5:5-(s-i),e.avail_out=o<a?a-o+257:257-(o-a),n.hold=_,n.bits=g}},{}],8:[function(e,t,n){var s=e("../utils/common"),i=e("./adler32"),o=e("./crc32"),r=e("./inffast"),a=e("./inftrees"),c=1,l=2,d=0,u=-2,h=1,_=852,g=592;function f(e){return(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)}function m(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new s.Buf16(320),this.work=new s.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function v(e){var t;return e&&e.state?(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=h,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new s.Buf32(_),t.distcode=t.distdyn=new s.Buf32(g),t.sane=1,t.back=-1,d):u}function p(e){var t;return e&&e.state?((t=e.state).wsize=0,t.whave=0,t.wnext=0,v(e)):u}function S(e,t){var n,s;return e&&e.state?(s=e.state,t<0?(n=0,t=-t):(n=1+(t>>4),t<48&&(t&=15)),t&&(t<8||15<t)?u:(null!==s.window&&s.wbits!==t&&(s.window=null),s.wrap=n,s.wbits=t,p(e))):u}function I(e,t){var n,s;return e?(s=new m,(e.state=s).window=null,(n=S(e,t))!==d&&(e.state=null),n):u}var E,y,C=!0;function M(e){if(C){var t;for(E=new s.Buf32(512),y=new s.Buf32(32),t=0;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(a(c,e.lens,0,288,E,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;a(l,e.lens,0,32,y,0,e.work,{bits:5}),C=!1}e.lencode=E,e.lenbits=9,e.distcode=y,e.distbits=5}function O(e,t,n,i){var o,r=e.state;return null===r.window&&(r.wsize=1<<r.wbits,r.wnext=0,r.whave=0,r.window=new s.Buf8(r.wsize)),i>=r.wsize?(s.arraySet(r.window,t,n-r.wsize,r.wsize,0),r.wnext=0,r.whave=r.wsize):(i<(o=r.wsize-r.wnext)&&(o=i),s.arraySet(r.window,t,n-i,o,r.wnext),(i-=o)?(s.arraySet(r.window,t,n-i,i,0),r.wnext=i,r.whave=r.wsize):(r.wnext+=o,r.wnext===r.wsize&&(r.wnext=0),r.whave<r.wsize&&(r.whave+=o))),0}n.inflateReset=p,n.inflateReset2=S,n.inflateResetKeep=v,n.inflateInit=function(e){return I(e,15)},n.inflateInit2=I,n.inflate=function(e,t){var n,_,g,m,v,p,S,I,E,y,C,T,D,A,b,w,N,R,L,k,P,U,F,G,B=0,$=new s.Buf8(4),x=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!e||!e.state||!e.output||!e.input&&0!==e.avail_in)return u;12===(n=e.state).mode&&(n.mode=13),v=e.next_out,g=e.output,S=e.avail_out,m=e.next_in,_=e.input,p=e.avail_in,I=n.hold,E=n.bits,y=p,C=S,U=d;e:for(;;)switch(n.mode){case h:if(0===n.wrap){n.mode=13;break}for(;E<16;){if(0===p)break e;p--,I+=_[m++]<<E,E+=8}if(2&n.wrap&&35615===I){$[n.check=0]=255&I,$[1]=I>>>8&255,n.check=o(n.check,$,2,0),E=I=0,n.mode=2;break}if(n.flags=0,n.head&&(n.head.done=!1),!(1&n.wrap)||(((255&I)<<8)+(I>>8))%31){e.msg="incorrect header check",n.mode=30;break}if(8!=(15&I)){e.msg="unknown compression method",n.mode=30;break}if(E-=4,P=8+(15&(I>>>=4)),0===n.wbits)n.wbits=P;else if(P>n.wbits){e.msg="invalid window size",n.mode=30;break}n.dmax=1<<P,e.adler=n.check=1,n.mode=512&I?10:12,E=I=0;break;case 2:for(;E<16;){if(0===p)break e;p--,I+=_[m++]<<E,E+=8}if(n.flags=I,8!=(255&n.flags)){e.msg="unknown compression method",n.mode=30;break}if(57344&n.flags){e.msg="unknown header flags set",n.mode=30;break}n.head&&(n.head.text=I>>8&1),512&n.flags&&($[0]=255&I,$[1]=I>>>8&255,n.check=o(n.check,$,2,0)),E=I=0,n.mode=3;case 3:for(;E<32;){if(0===p)break e;p--,I+=_[m++]<<E,E+=8}n.head&&(n.head.time=I),512&n.flags&&($[0]=255&I,$[1]=I>>>8&255,$[2]=I>>>16&255,$[3]=I>>>24&255,n.check=o(n.check,$,4,0)),E=I=0,n.mode=4;case 4:for(;E<16;){if(0===p)break e;p--,I+=_[m++]<<E,E+=8}n.head&&(n.head.xflags=255&I,n.head.os=I>>8),512&n.flags&&($[0]=255&I,$[1]=I>>>8&255,n.check=o(n.check,$,2,0)),E=I=0,n.mode=5;case 5:if(1024&n.flags){for(;E<16;){if(0===p)break e;p--,I+=_[m++]<<E,E+=8}n.length=I,n.head&&(n.head.extra_len=I),512&n.flags&&($[0]=255&I,$[1]=I>>>8&255,n.check=o(n.check,$,2,0)),E=I=0}else n.head&&(n.head.extra=null);n.mode=6;case 6:if(1024&n.flags&&(p<(T=n.length)&&(T=p),T&&(n.head&&(P=n.head.extra_len-n.length,n.head.extra||(n.head.extra=new Array(n.head.extra_len)),s.arraySet(n.head.extra,_,m,T,P)),512&n.flags&&(n.check=o(n.check,_,T,m)),p-=T,m+=T,n.length-=T),n.length))break e;n.length=0,n.mode=7;case 7:if(2048&n.flags){if(0===p)break e;for(T=0;P=_[m+T++],n.head&&P&&n.length<65536&&(n.head.name+=String.fromCharCode(P)),P&&T<p;);if(512&n.flags&&(n.check=o(n.check,_,T,m)),p-=T,m+=T,P)break e}else n.head&&(n.head.name=null);n.length=0,n.mode=8;case 8:if(4096&n.flags){if(0===p)break e;for(T=0;P=_[m+T++],n.head&&P&&n.length<65536&&(n.head.comment+=String.fromCharCode(P)),P&&T<p;);if(512&n.flags&&(n.check=o(n.check,_,T,m)),p-=T,m+=T,P)break e}else n.head&&(n.head.comment=null);n.mode=9;case 9:if(512&n.flags){for(;E<16;){if(0===p)break e;p--,I+=_[m++]<<E,E+=8}if(I!==(65535&n.check)){e.msg="header crc mismatch",n.mode=30;break}E=I=0}n.head&&(n.head.hcrc=n.flags>>9&1,n.head.done=!0),e.adler=n.check=0,n.mode=12;break;case 10:for(;E<32;){if(0===p)break e;p--,I+=_[m++]<<E,E+=8}e.adler=n.check=f(I),E=I=0,n.mode=11;case 11:if(0===n.havedict)return e.next_out=v,e.avail_out=S,e.next_in=m,e.avail_in=p,n.hold=I,n.bits=E,2;e.adler=n.check=1,n.mode=12;case 12:if(5===t||6===t)break e;case 13:if(n.last){I>>>=7&E,E-=7&E,n.mode=27;break}for(;E<3;){if(0===p)break e;p--,I+=_[m++]<<E,E+=8}switch(n.last=1&I,E-=1,3&(I>>>=1)){case 0:n.mode=14;break;case 1:if(M(n),n.mode=20,6!==t)break;I>>>=2,E-=2;break e;case 2:n.mode=17;break;case 3:e.msg="invalid block type",n.mode=30}I>>>=2,E-=2;break;case 14:for(I>>>=7&E,E-=7&E;E<32;){if(0===p)break e;p--,I+=_[m++]<<E,E+=8}if((65535&I)!=(I>>>16^65535)){e.msg="invalid stored block lengths",n.mode=30;break}if(n.length=65535&I,E=I=0,n.mode=15,6===t)break e;case 15:n.mode=16;case 16:if(T=n.length){if(p<T&&(T=p),S<T&&(T=S),0===T)break e;s.arraySet(g,_,m,T,v),p-=T,m+=T,S-=T,v+=T,n.length-=T;break}n.mode=12;break;case 17:for(;E<14;){if(0===p)break e;p--,I+=_[m++]<<E,E+=8}if(n.nlen=257+(31&I),I>>>=5,E-=5,n.ndist=1+(31&I),I>>>=5,E-=5,n.ncode=4+(15&I),I>>>=4,E-=4,286<n.nlen||30<n.ndist){e.msg="too many length or distance symbols",n.mode=30;break}n.have=0,n.mode=18;case 18:for(;n.have<n.ncode;){for(;E<3;){if(0===p)break e;p--,I+=_[m++]<<E,E+=8}n.lens[x[n.have++]]=7&I,I>>>=3,E-=3}for(;n.have<19;)n.lens[x[n.have++]]=0;if(n.lencode=n.lendyn,n.lenbits=7,F={bits:n.lenbits},U=a(0,n.lens,0,19,n.lencode,0,n.work,F),n.lenbits=F.bits,U){e.msg="invalid code lengths set",n.mode=30;break}n.have=0,n.mode=19;case 19:for(;n.have<n.nlen+n.ndist;){for(;w=(B=n.lencode[I&(1<<n.lenbits)-1])>>>16&255,N=65535&B,!((b=B>>>24)<=E);){if(0===p)break e;p--,I+=_[m++]<<E,E+=8}if(N<16)I>>>=b,E-=b,n.lens[n.have++]=N;else{if(16===N){for(G=b+2;E<G;){if(0===p)break e;p--,I+=_[m++]<<E,E+=8}if(I>>>=b,E-=b,0===n.have){e.msg="invalid bit length repeat",n.mode=30;break}P=n.lens[n.have-1],T=3+(3&I),I>>>=2,E-=2}else if(17===N){for(G=b+3;E<G;){if(0===p)break e;p--,I+=_[m++]<<E,E+=8}E-=b,P=0,T=3+(7&(I>>>=b)),I>>>=3,E-=3}else{for(G=b+7;E<G;){if(0===p)break e;p--,I+=_[m++]<<E,E+=8}E-=b,P=0,T=11+(127&(I>>>=b)),I>>>=7,E-=7}if(n.have+T>n.nlen+n.ndist){e.msg="invalid bit length repeat",n.mode=30;break}for(;T--;)n.lens[n.have++]=P}}if(30===n.mode)break;if(0===n.lens[256]){e.msg="invalid code -- missing end-of-block",n.mode=30;break}if(n.lenbits=9,F={bits:n.lenbits},U=a(c,n.lens,0,n.nlen,n.lencode,0,n.work,F),n.lenbits=F.bits,U){e.msg="invalid literal/lengths set",n.mode=30;break}if(n.distbits=6,n.distcode=n.distdyn,F={bits:n.distbits},U=a(l,n.lens,n.nlen,n.ndist,n.distcode,0,n.work,F),n.distbits=F.bits,U){e.msg="invalid distances set",n.mode=30;break}if(n.mode=20,6===t)break e;case 20:n.mode=21;case 21:if(6<=p&&258<=S){e.next_out=v,e.avail_out=S,e.next_in=m,e.avail_in=p,n.hold=I,n.bits=E,r(e,C),v=e.next_out,g=e.output,S=e.avail_out,m=e.next_in,_=e.input,p=e.avail_in,I=n.hold,E=n.bits,12===n.mode&&(n.back=-1);break}for(n.back=0;w=(B=n.lencode[I&(1<<n.lenbits)-1])>>>16&255,N=65535&B,!((b=B>>>24)<=E);){if(0===p)break e;p--,I+=_[m++]<<E,E+=8}if(w&&!(240&w)){for(R=b,L=w,k=N;w=(B=n.lencode[k+((I&(1<<R+L)-1)>>R)])>>>16&255,N=65535&B,!(R+(b=B>>>24)<=E);){if(0===p)break e;p--,I+=_[m++]<<E,E+=8}I>>>=R,E-=R,n.back+=R}if(I>>>=b,E-=b,n.back+=b,n.length=N,0===w){n.mode=26;break}if(32&w){n.back=-1,n.mode=12;break}if(64&w){e.msg="invalid literal/length code",n.mode=30;break}n.extra=15&w,n.mode=22;case 22:if(n.extra){for(G=n.extra;E<G;){if(0===p)break e;p--,I+=_[m++]<<E,E+=8}n.length+=I&(1<<n.extra)-1,I>>>=n.extra,E-=n.extra,n.back+=n.extra}n.was=n.length,n.mode=23;case 23:for(;w=(B=n.distcode[I&(1<<n.distbits)-1])>>>16&255,N=65535&B,!((b=B>>>24)<=E);){if(0===p)break e;p--,I+=_[m++]<<E,E+=8}if(!(240&w)){for(R=b,L=w,k=N;w=(B=n.distcode[k+((I&(1<<R+L)-1)>>R)])>>>16&255,N=65535&B,!(R+(b=B>>>24)<=E);){if(0===p)break e;p--,I+=_[m++]<<E,E+=8}I>>>=R,E-=R,n.back+=R}if(I>>>=b,E-=b,n.back+=b,64&w){e.msg="invalid distance code",n.mode=30;break}n.offset=N,n.extra=15&w,n.mode=24;case 24:if(n.extra){for(G=n.extra;E<G;){if(0===p)break e;p--,I+=_[m++]<<E,E+=8}n.offset+=I&(1<<n.extra)-1,I>>>=n.extra,E-=n.extra,n.back+=n.extra}if(n.offset>n.dmax){e.msg="invalid distance too far back",n.mode=30;break}n.mode=25;case 25:if(0===S)break e;if(T=C-S,n.offset>T){if((T=n.offset-T)>n.whave&&n.sane){e.msg="invalid distance too far back",n.mode=30;break}T>n.wnext?(T-=n.wnext,D=n.wsize-T):D=n.wnext-T,T>n.length&&(T=n.length),A=n.window}else A=g,D=v-n.offset,T=n.length;for(S<T&&(T=S),S-=T,n.length-=T;g[v++]=A[D++],--T;);0===n.length&&(n.mode=21);break;case 26:if(0===S)break e;g[v++]=n.length,S--,n.mode=21;break;case 27:if(n.wrap){for(;E<32;){if(0===p)break e;p--,I|=_[m++]<<E,E+=8}if(C-=S,e.total_out+=C,n.total+=C,C&&(e.adler=n.check=n.flags?o(n.check,g,C,v-C):i(n.check,g,C,v-C)),C=S,(n.flags?I:f(I))!==n.check){e.msg="incorrect data check",n.mode=30;break}E=I=0}n.mode=28;case 28:if(n.wrap&&n.flags){for(;E<32;){if(0===p)break e;p--,I+=_[m++]<<E,E+=8}if(I!==(4294967295&n.total)){e.msg="incorrect length check",n.mode=30;break}E=I=0}n.mode=29;case 29:U=1;break e;case 30:U=-3;break e;case 31:return-4;default:return u}return e.next_out=v,e.avail_out=S,e.next_in=m,e.avail_in=p,n.hold=I,n.bits=E,(n.wsize||C!==e.avail_out&&n.mode<30&&(n.mode<27||4!==t))&&O(e,e.output,e.next_out,C-e.avail_out)?(n.mode=31,-4):(y-=e.avail_in,C-=e.avail_out,e.total_in+=y,e.total_out+=C,n.total+=C,n.wrap&&C&&(e.adler=n.check=n.flags?o(n.check,g,C,e.next_out-C):i(n.check,g,C,e.next_out-C)),e.data_type=n.bits+(n.last?64:0)+(12===n.mode?128:0)+(20===n.mode||15===n.mode?256:0),(0===y&&0===C||4===t)&&U===d&&(U=-5),U)},n.inflateEnd=function(e){if(!e||!e.state)return u;var t=e.state;return t.window&&(t.window=null),e.state=null,d},n.inflateGetHeader=function(e,t){var n;return e&&e.state&&2&(n=e.state).wrap?((n.head=t).done=!1,d):u},n.inflateSetDictionary=function(e,t){var n,s=t.length;return e&&e.state?0!==(n=e.state).wrap&&11!==n.mode?u:11===n.mode&&i(1,t,s,0)!==n.check?-3:O(e,t,s,s)?(n.mode=31,-4):(n.havedict=1,d):u},n.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":1,"./adler32":3,"./crc32":5,"./inffast":7,"./inftrees":9}],9:[function(e,t,n){var s=e("../utils/common"),i=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],o=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],r=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],a=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];t.exports=function(e,t,n,c,l,d,u,h){var _,g,f,m,v,p,S,I,E,y=h.bits,C=0,M=0,O=0,T=0,D=0,A=0,b=0,w=0,N=0,R=0,L=null,k=0,P=new s.Buf16(16),U=new s.Buf16(16),F=null,G=0;for(C=0;C<=15;C++)P[C]=0;for(M=0;M<c;M++)P[t[n+M]]++;for(D=y,T=15;1<=T&&0===P[T];T--);if(T<D&&(D=T),0===T)return l[d++]=20971520,l[d++]=20971520,h.bits=1,0;for(O=1;O<T&&0===P[O];O++);for(D<O&&(D=O),C=w=1;C<=15;C++)if(w<<=1,(w-=P[C])<0)return-1;if(0<w&&(0===e||1!==T))return-1;for(U[1]=0,C=1;C<15;C++)U[C+1]=U[C]+P[C];for(M=0;M<c;M++)0!==t[n+M]&&(u[U[t[n+M]]++]=M);if(0===e?(L=F=u,p=19):1===e?(L=i,k-=257,F=o,G-=257,p=256):(L=r,F=a,p=-1),C=O,v=d,b=M=R=0,f=-1,m=(N=1<<(A=D))-1,1===e&&852<N||2===e&&592<N)return 1;for(;;){for(S=C-b,u[M]<p?(I=0,E=u[M]):u[M]>p?(I=F[G+u[M]],E=L[k+u[M]]):(I=96,E=0),_=1<<C-b,O=g=1<<A;l[v+(R>>b)+(g-=_)]=S<<24|I<<16|E,0!==g;);for(_=1<<C-1;R&_;)_>>=1;if(0!==_?(R&=_-1,R+=_):R=0,M++,0==--P[C]){if(C===T)break;C=t[n+u[M]]}if(D<C&&(R&m)!==f){for(0===b&&(b=D),v+=O,w=1<<(A=C-b);A+b<T&&!((w-=P[A+b])<=0);)A++,w<<=1;if(N+=1<<A,1===e&&852<N||2===e&&592<N)return 1;l[f=R&m]=D<<24|A<<16|v-d}}return 0!==R&&(l[v+R]=C-b<<24|64<<16),h.bits=D,0}},{"../utils/common":1}],10:[function(e,t,n){t.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],11:[function(e,t,n){t.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],"/lib/inflate.js":[function(e,t,n){var s=e("./zlib/inflate"),i=e("./utils/common"),o=e("./utils/strings"),r=e("./zlib/constants"),a=e("./zlib/messages"),c=e("./zlib/zstream"),l=e("./zlib/gzheader"),d=Object.prototype.toString;function u(e){if(!(this instanceof u))return new u(e);this.options=i.assign({chunkSize:16384,windowBits:0,to:""},e||{});var t=this.options;t.raw&&0<=t.windowBits&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(0<=t.windowBits&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),15<t.windowBits&&t.windowBits<48&&!(15&t.windowBits)&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new c,this.strm.avail_out=0;var n=s.inflateInit2(this.strm,t.windowBits);if(n!==r.Z_OK)throw new Error(a[n]);if(this.header=new l,s.inflateGetHeader(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=o.string2buf(t.dictionary):"[object ArrayBuffer]"===d.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(n=s.inflateSetDictionary(this.strm,t.dictionary))!==r.Z_OK))throw new Error(a[n])}function h(e,t){var n=new u(t);if(n.push(e,!0),n.err)throw n.msg||a[n.err];return n.result}u.prototype.push=function(e,t){var n,a,c,l,u,h=this.strm,_=this.options.chunkSize,g=this.options.dictionary,f=!1;if(this.ended)return!1;a=t===~~t?t:!0===t?r.Z_FINISH:r.Z_NO_FLUSH,"string"==typeof e?h.input=o.binstring2buf(e):"[object ArrayBuffer]"===d.call(e)?h.input=new Uint8Array(e):h.input=e,h.next_in=0,h.avail_in=h.input.length;do{if(0===h.avail_out&&(h.output=new i.Buf8(_),h.next_out=0,h.avail_out=_),(n=s.inflate(h,r.Z_NO_FLUSH))===r.Z_NEED_DICT&&g&&(n=s.inflateSetDictionary(this.strm,g)),n===r.Z_BUF_ERROR&&!0===f&&(n=r.Z_OK,f=!1),n!==r.Z_STREAM_END&&n!==r.Z_OK)return this.onEnd(n),!(this.ended=!0);h.next_out&&(0!==h.avail_out&&n!==r.Z_STREAM_END&&(0!==h.avail_in||a!==r.Z_FINISH&&a!==r.Z_SYNC_FLUSH)||("string"===this.options.to?(c=o.utf8border(h.output,h.next_out),l=h.next_out-c,u=o.buf2string(h.output,c),h.next_out=l,h.avail_out=_-l,l&&i.arraySet(h.output,h.output,c,l,0),this.onData(u)):this.onData(i.shrinkBuf(h.output,h.next_out)))),0===h.avail_in&&0===h.avail_out&&(f=!0)}while((0<h.avail_in||0===h.avail_out)&&n!==r.Z_STREAM_END);return n===r.Z_STREAM_END&&(a=r.Z_FINISH),a===r.Z_FINISH?(n=s.inflateEnd(this.strm),this.onEnd(n),this.ended=!0,n===r.Z_OK):a!==r.Z_SYNC_FLUSH||(this.onEnd(r.Z_OK),!(h.avail_out=0))},u.prototype.onData=function(e){this.chunks.push(e)},u.prototype.onEnd=function(e){e===r.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=i.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg},n.Inflate=u,n.inflate=h,n.inflateRaw=function(e,t){return(t=t||{}).raw=!0,h(e,t)},n.ungzip=h},{"./utils/common":1,"./utils/strings":2,"./zlib/constants":4,"./zlib/gzheader":6,"./zlib/inflate":8,"./zlib/messages":10,"./zlib/zstream":11}]},{},[])("/lib/inflate.js")}(ft)),ft.exports);var vt=new class{constructor(){this._socketAdapter=null,this._url="",this._isReconnecting=!1,this._pendingRequests=new Map,this._nextHeartbeatAt=0,this._lastDiagnoseAt=0,this._isHeartbeatInProgress=!1,this._connectionEstablishedTime=0,this._connectionStartTime=0,this._connectionId=-1,this._isBinarySupported=!0,this._intendedDelay=ot,this._currentConnectState=nt}init(){be.addTask({id:Qe,intervalMs:1e3,callback:this._executeScheduledTaskIfReady,context:this}),this._updateIsBinarySupported(),this._url=function(e){const t=ye.get("instance"),{sdkAppId:n,testEnv:s}=t,i=Ie(n);return Te(s?pe.TEST[i].DEFAULT:pe.PRODUCTION[i].INITIAL.replace("*",`${n}`),{isBinary:e})}(this._isBinarySupported),r.subscribeInnerEvent("networkStatusChange",this._handleNetworkStatusChange,this),r.subscribeInnerEvent("activityStatusChange",this._handleActivityStatusChange,this),this.connect()}sendPacket(e,t){var n;const{requestId:s,timeout:i=Ze,canResend:o=!0}=t||{};if(se(e))return console.warn(`${Xe}.sendPacket: packet is empty `,e),null;const r=JSON.stringify(e);let a=null;if(s){const{resolve:e,reject:t,promise:n}=ie();a=n,this._pendingRequests.set(s,{resolve:e,reject:t,timestamp:Date.now(),uplinkData:r,timeout:i,canResend:o})}const c=this._isBinarySupported?we(r).buffer:r;return null===(n=this._socketAdapter)||void 0===n||n.send(c),a}connect(){var e;this._socketAdapter=new le(this._url),this._connectionEstablishedTime=0,this._addEventListeners(),this._connectionStartTime=Date.now();const t=null===(e=this._socketAdapter)||void 0===e?void 0:e.getId(),n=`${Xe}.connect isWorkerEnabled: false socketID:${t} url:${this._url}`;this._ssoLog({method:"connect",message:n}),console.log(n)}disconnect(){var e,t;const n=null===(e=this._socketAdapter)||void 0===e?void 0:e.getId(),s=`${Xe}.disconnect socketID:${n}`;this._ssoLog({method:"disconnect",message:s}),console.log(s),this._removeEventListeners(),null===(t=this._socketAdapter)||void 0===t||t.disconnect()}getSocketAdapter(){return this._socketAdapter}dispose(){console.log(`${Xe}.dispose`),be.removeTask(Qe),be.removeTask(et),r.unSubscribeInnerEvent("networkStatusChange",this._handleNetworkStatusChange,this),r.unSubscribeInnerEvent("activityStatusChange",this._handleActivityStatusChange,this),this.disconnect(),this._socketAdapter=null,this._isReconnecting=!1,this._isHeartbeatInProgress=!1,this._pendingRequests.clear(),this._nextHeartbeatAt=0,this._lastDiagnoseAt=0,this._intendedDelay=ot,this._url=""}_shouldSkipReconnect(){const e=this._currentConnectState===st&&this._isReconnecting;return!this._socketAdapter||e}reconnect(){return a(this,void 0,void 0,(function*(){const e=`${Xe} reconnect isReconnecting: ${this._isReconnecting} currentConnectState: ${this._currentConnectState}`;if(this._ssoLog({method:"reconnect",message:e}),console.log(e),!this._shouldSkipReconnect()){this._url=function(e){const t=ye.get("instance"),{sdkAppId:n,testEnv:s}=t,i=Ie(n);if(s)return Te(pe.TEST[i].DEFAULT,{isBinary:e});const o=pe.PRODUCTION[i],r=D&&o.ANYCAST;return Te({[Ee.INITIAL]:()=>(Me=Ee.DEFAULT,o.DEFAULT),[Ee.DEFAULT]:()=>(Me=Ee.BACKUP,o.BACKUP),[Ee.BACKUP]:()=>(Me=r?Ee.ANYCAST:Ee.DEFAULT,r?o.ANYCAST:o.DEFAULT),[Ee.ANYCAST]:()=>(Me=Ee.DEFAULT,o.ANYCAST="",o.DEFAULT)}[Me](),{isBinary:e})}(this._isBinarySupported);try{this._isReconnecting=!0,this.disconnect(),this.connect()}catch(e){this._isReconnecting=!1,this._handleConnectStateChange({state:it,reason:lt}),console.warn(`${Xe} reconnect 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=0!==this._connectionEstablishedTime?Date.now()-this._connectionEstablishedTime:0,i=`${Xe} onClose closeSocketID: ${t} currentSocketID: ${this._connectionId} connectionDuration: ${s} code:${null==n?void 0:n.code} reason:${null==n?void 0:n.reason}`;this._ssoLog({method:"onClose",message:i}),console.warn(i),t===this._connectionId&&this._handleConnectStateChange({state:it,reason:ut}),this._isReconnecting&&(this._isReconnecting=!1)}_onError(e){const{socketId:t,error:n}=e||{},s=`${Xe} onError sourceSocketID: ${t} currentSocketID:${this._connectionId} isReconnecting: ${this._isReconnecting} error: ${JSON.stringify(n)}`;this._ssoLog({method:"onError",message:s}),console.warn(s),t===this._connectionId&&this._handleConnectStateChange({state:it,reason:dt}),this._isReconnecting&&(this._isReconnecting=!1)}_onSendFail(e){const{socketId:t,error:n}=e||{},s=`${Xe} onSendFail sendFailSocketId: ${t} currentSocketID:${this._connectionId} isReconnecting: ${this._isReconnecting} error: ${n}`;this._ssoLog({method:"onSendFail",message:s}),console.warn(s),t===this._connectionId&&this._handleConnectStateChange({state:it,reason:ct}),this._isReconnecting&&(this._isReconnecting=!1)}_onMessage(e){let t,n;this._updateHeartbeatTime();try{t=this._isBinarySupported?this._isCompressedData(e.data)?(e=>{const t=new Uint8Array(e).slice(4);let n;try{n=mt.inflate(t,{to:"string"})}catch(e){console.error("inflate error",e)}return n})(e.data):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,n=JSON.parse(t)}catch(t){const n=e.data;return this._ssoLog({method:"jsonParseError",message:n}),void console.error(t)}if(!n||!n.head)return;const{seq:s,servcmd:i}=n.head,o=`${s}${i}`;this._pendingRequests.has(o)?this._handleRequestResponse(n):this._handlePushMessage(n)}_handleRequestResponse(e){const{seq:t,servcmd:n}=e.head,{int32_error_code:s,str_error_message:i,ErrorCode:o=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),o&&0!==o)return r.emitInnerEvent("error",{errorCode:o,errorInfo:a}),void d({errorCode:o,errorInfo:a});l(e.body)}_handlePushMessage(e){const{servcmd:t}=e.head,{NeedAck:n,SessionData:s}=e.body;1===n&&this._sendAck(s),r.emitInnerEvent(t,e)}_checkPendingRequestsAndResend(){var e;console.log(`${Xe}._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?we(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=`${Xe} onConnect cost:${s} ms. socketID:${t} res:${JSON.stringify(n)}`;if(this._ssoLog({method:"onConnect",message:i}),console.log(i),this._checkPendingRequestsAndResend(),this._sendHeartbeatIfReady(),this._isReconnecting){const e=`${Xe} reconnect success`;this._ssoLog({method:"reconnectSuccess",message:e}),console.log(e),r.emitInnerEvent(je.RECONNECTED),this._isReconnecting=!1}this._resetReconnectDelay(),this._handleConnectStateChange({state:nt})}_sendAck(e){const t=Le({servcmd:"openim.ws_msg_push_ack",data:{SessionData:e}});this.sendPacket(t)}_executeScheduledTaskIfReady(){return a(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 a(this,void 0,void 0,(function*(){var e;const t=Le({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=ye.get("netWorkMonitor"))||void 0===e?void 0:e.isNetWorkOnline,s=`${Xe} sendHeartbeat failed. isNetWorkOnline:${n} error: ${t}`;this._ssoLog({method:"sendHeartbeatError",message:s}),console.debug(s),this._handleConnectStateChange({state:it,reason:ct})}}))}_sendHeartbeatIfReady(){return a(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){const t=`${Xe} networkStatusChange ${JSON.stringify(e)}`;this._ssoLog({method:"networkStatusChange",message:t}),console.warn(t);const{isNetworkOnline:n,networkType:s}=e;n&&"none"!==s?this._handleConnectStateChange({state:nt,reason:rt}):this._handleConnectStateChange({state:it,reason:rt})}isPrivateNetWork(){const e=ye.get("instance")||{};return e.proxyServer&&!e.fileDownloadProxy}_handleConnectStateChange(e){const{state:t,reason:n}=e;if(this._currentConnectState!==t){const e=`${Xe}._handleConnectStateChange from ${this._currentConnectState} to ${t} reason: ${n}`;this._ssoLog({method:"handleConnectStateChange",message:e}),console.log(e),this._currentConnectState=t,r.emitOuterEvent("netStateChange",{name:"netStateChange",data:{state:t}}),t===it&&r.emitInnerEvent(je.SOCKET_DISCONNECTED),t!==it&&t!==nt||(this._resetReconnectDelay(),be.addTask({id:et,intervalMs:this._intendedDelay,callback:this._scheduleReconnectWithBackoff,context:this}))}}_handleActivityStatusChange(e){var t,n;const s=null===(n=null===(t=this._socketAdapter)||void 0===t?void 0:t._ws)||void 0===n?void 0:n.readyState,i=`${Xe} activityStatusChange ${JSON.stringify(e)} readyState: ${s}`;this._ssoLog({method:"activityStatusChange",message:i}),console.warn(i),3===s&&this._handleConnectStateChange({state:it,reason:at})}_resetReconnectDelay(){var e;be.removeTask(et);const t=null===(e=ye.get("activityMonitor"))||void 0===e?void 0:e.isActive;this._intendedDelay=t?ot:1e3}_scheduleReconnectWithBackoff(){var e;const t=null===(e=ye.get("activityMonitor"))||void 0===e?void 0:e.isActive;this._intendedDelay=t?Math.min(5e3,Math.max(ot,1.5*this._intendedDelay)):Math.min(3e5,Math.max(1e3,1.5*this._intendedDelay));const n=(new Date).toTimeString().slice(0,8),s=`${Xe}.scheduleReconnectWithBackoff timeStr: ${n} intendedDelay: ${this._intendedDelay}`;this._ssoLog({method:"scheduleReconnectWithBackoff",message:s}),console.log(s),this.reconnect(),be.updateTaskInterval(et,this._intendedDelay)}_ssoLog(e){const{method:t,message:n}=e;Je.createSSOLogData({method:t}).setLogInfo({message:n}).end()}_diagnose(){this.isPrivateNetWork()||(this._lastDiagnoseAt=Date.now(),function(e){a(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 ne({method:"GET",url:n,data:{}})}catch(e){console.warn("diagnoseBySSO failed. error:",e)}}))}(this._url),function(e){a(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 ne({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:Q,errorInfo:"NETWORK_TIMEOUT",data:{requestId:e}}))}}_updateIsBinarySupported(){var e;if(null===(e=ye.get("instance"))||void 0===e?void 0:e.devMode)return void(this._isBinarySupported=!1);const t=Z();(S||g&&"windows"===t||E)&&(this._isBinarySupported=!1)}_isCompressedData(e){const t=new Uint8Array(e);return 67===t[0]&&79===t[1]&&77===t[2]&&80===t[3]}};const pt={init:function(e){ye.set("instance",e),vt.init()},destroy:function(){vt.dispose(),ye.clear(),be.dispose()},notificationCenter:r,channel:vt,store:ye,ssoLog:Je,utils:re,common:Ge};var St,It="1.1.0";!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"}(St||(St={}));var Et,yt=St;!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",e.NEW_MESSAGE="new_message",e.MESSAGE_PUSH="im_open_push.msg_push",e.MESSAGE_DELETED="message_deleted",e.MESSAGE_REVOKED="message_revoked",e.MESSAGE_MODIFIED="message_modified",e.RECOVER_CONVERSATIONS_COMPLETED="recover_conversations_completed",e.SOCKET_DISCONNECTED="socket_disconnected"}(Et||(Et={}));var Ct,Mt=Et;!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"}(Ct||(Ct={}));var Ot=Ct;const Tt=Object.assign({},{KICKED_OUT_MULT_ACCOUNT:"multipleAccount",KICKED_OUT_MULT_DEVICE:"multipleDevice",KICKED_OUT_USERSIG_EXPIRED:"userSigExpired",KICKED_OUT_REST_API:"REST_API_Kick"});var Dt;!function(e){e.UNSENT="unSend",e.SUCCESS="success",e.FAIL="fail"}(Dt||(Dt={}));const At=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},{MSG_TEXT:"TIMTextElem",MSG_IMAGE:"TIMImageElem",MSG_AUDIO:"TIMSoundElem",MSG_FILE:"TIMFileElem",MSG_FACE:"TIMFaceElem",MSG_VIDEO:"TIMVideoFileElem",MSG_LOCATION:"TIMLocationElem",MSG_GRP_TIP:"TIMGroupTipElem",MSG_GRP_SYS_NOTICE:"TIMGroupSystemNoticeElem",MSG_CUSTOM:"TIMCustomElem",MSG_MERGER:"TIMRelayElem"}),{MSG_PRIORITY_HIGH:"High",MSG_PRIORITY_NORMAL:"Normal",MSG_PRIORITY_LOW:"Low",MSG_PRIORITY_LOWEST:"Lowest"}),{RECEIVE_WITH_OFFLINE_PUSH_EXCEPT_AT:"AcceptNotNotifyExceptAt",NOT_RECEIVE_OFFLINE_PUSH_EXCEPT_AT:"AcceptNotNotifyExceptAt",NOT_RECEIVE_MSG_EXCEPT_AT:"NotReceiveMsgExceptAt",MSG_AT_ALL:"__kImSDK_MesssageAtALL__"}),{MSG_REMIND_ACPT_AND_NOTE:"AcceptAndNotify",MSG_REMIND_ACPT_NOT_NOTE:"AcceptNotNotify",MSG_REMIND_DISCARD:"Discard"}),{MessageStatus:Dt}),bt=Object.assign({},{GENDER_UNKNOWN:"Gender_Type_Unknown",GENDER_FEMALE:"Gender_Type_Female",GENDER_MALE:"Gender_Type_Male",USER_STATUS_UNKNOWN:0,USER_STATUS_ONLINE:1,USER_STATUS_OFFLINE:2,USER_STATUS_UNLOGINED:3}),wt=Object.assign(Object.assign(Object.assign(Object.assign({},{CONV_C2C:"C2C",CONV_GROUP:"GROUP",CONV_TOPIC:"TOPIC",CONV_SYSTEM:"@TIM#SYSTEM"}),{CONV_AT_ME:1,CONV_AT_ALL:2,CONV_AT_ALL_AT_ME:3}),{CONV_MARK_TYPE_STAR:1,CONV_MARK_TYPE_UNREAD:2,CONV_MARK_TYPE_FOLD:4,CONV_MARK_TYPE_HIDE:8}),{READ_ALL_C2C_MSG:"readAllC2CMessage",READ_ALL_GROUP_MSG:"readAllGroupMessage",READ_ALL_MSG:"readAllMessage"}),Nt=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},{SNS_TYPE_NO_RELATION:"CheckResult_Type_NoRelation",SNS_TYPE_A_WITH_B:"CheckResult_Type_AWithB",SNS_TYPE_B_WITH_A:"CheckResult_Type_BWithA",SNS_TYPE_BOTH_WAY:"CheckResult_Type_BothWay"}),{ALLOW_TYPE_ALLOW_ANY:"AllowType_Type_AllowAny",ALLOW_TYPE_NEED_CONFIRM:"AllowType_Type_NeedConfirm",ALLOW_TYPE_DENY_ANY:"AllowType_Type_DenyAny"}),{SNS_ADD_TYPE_SINGLE:"Add_Type_Single",SNS_ADD_TYPE_BOTH:"Add_Type_Both"}),{SNS_DELETE_TYPE_SINGLE:"Delete_Type_Single",SNS_DELETE_TYPE_BOTH:"Delete_Type_Both"}),{SNS_APPLICATION_TYPE_BOTH:"Pendency_Type_Both",SNS_APPLICATION_SENT_TO_ME:"Pendency_Type_ComeIn",SNS_APPLICATION_SENT_BY_ME:"Pendency_Type_SendOut",SNS_APPLICATION_AGREE:"Response_Action_Agree",SNS_APPLICATION_AGREE_AND_ADD:"Response_Action_AgreeAndAdd"}),{SNS_CHECK_TYPE_BOTH:"CheckResult_Type_Both",SNS_CHECK_TYPE_SINGLE:"CheckResult_Type_Single"}),{FORBID_TYPE_NONE:"AdminForbid_Type_None",FORBID_TYPE_SEND_OUT:"AdminForbid_Type_SendOut"}),Rt=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},{GRP_WORK:"Private",GRP_PUBLIC:"Public",GRP_MEETING:"ChatRoom",GRP_AVCHATROOM:"AVChatRoom",GRP_COMMUNITY:"Community",GRP_ROOM:"Room",GRP_LIVE:"Live"}),{GRP_MBR_ROLE_OWNER:"Owner",GRP_MBR_ROLE_ADMIN:"Admin",GRP_MBR_ROLE_MEMBER:"Member",GRP_MBR_ROLE_CUSTOM:"Custom"}),{GRP_TIP_MBR_JOIN:1,GRP_TIP_MBR_QUIT:2,GRP_TIP_MBR_KICKED_OUT:3,GRP_TIP_MBR_SET_ADMIN:4,GRP_TIP_MBR_CANCELED_ADMIN:5,GRP_TIP_GRP_PROFILE_UPDATED:6,GRP_TIP_MBR_PROFILE_UPDATED:7,GRP_TIP_BAN_AVCHATROOM_MEMBER:10,GRP_TIP_UNBAN_AVCHATROOM_MEMBER:11}),{JOIN_OPTIONS_FREE_ACCESS:"FreeAccess",JOIN_OPTIONS_NEED_PERMISSION:"NeedPermission",JOIN_OPTIONS_DISABLE_APPLY:"DisableApply",JOIN_STATUS_SUCCESS:"JoinedSuccess",JOIN_STATUS_ALREADY_IN_GROUP:"AlreadyInGroup",JOIN_STATUS_WAIT_APPROVAL:"WaitAdminApproval"}),{INVITE_OPTIONS_DISABLE_INVITE:"DisableInvite",INVITE_OPTIONS_NEED_PERMISSION:"NeedPermission",INVITE_OPTIONS_FREE_ACCESS:"FreeAccess"}),{GRP_PROFILE_OWNER_ID:"ownerID",GRP_PROFILE_CREATE_TIME:"createTime",GRP_PROFILE_LAST_INFO_TIME:"lastInfoTime",GRP_PROFILE_MEMBER_NUM:"memberNum",GRP_PROFILE_MAX_MEMBER_NUM:"maxMemberNum",GRP_PROFILE_JOIN_OPTION:"joinOption",GRP_PROFILE_INVITE_OPTION:"inviteOption",GRP_PROFILE_INTRODUCTION:"introduction",GRP_PROFILE_NOTIFICATION:"notification",GRP_PROFILE_MUTE_ALL_MBRS:"muteAllMembers"}),Lt=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},Tt),At),bt),wt),Nt),Rt),{IOS_OFFLINE_PUSH_NO_SOUND:"push.no_sound",IOS_OFFLINE_PUSH_DEFAULT_SOUND:"default"}),{NET_STATE_CONNECTING:"connecting",NET_STATE_DISCONNECTED:"disconnected"}),kt={NO_SDKAPPID:2e3,NO_TINYID:2022,NO_A2KEY:2023,USER_NOT_LOGGED_IN:2024,REPEAT_LOGIN:2025,MSG_SEND_FAIL:2100,MSG_INSTANCE_REQUIRED:2105,MSG_INVALID_CONV_TYPE:2106,MSG_REVOKE_FAIL:2110,MSG_DELETE_FAIL:2111,MSG_UNREAD_ALL_FAIL:2112,READ_RECEIPT_MSG_LIST_EMPTY:2114,CANNOT_DELETE_GRP_SYSTEM_NOTICE:2116,NOT_MY_FRIEND:2700,NETWORK_ERROR:2800,NETWORK_TIMEOUT:2801,NO_NETWORK:2805,UNCAUGHT_ERROR:2903,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,NO_USE:3122,OPTIONS_IS_EMPTY:3153,MSG_A2KEY_EXPIRED:20002,ACCOUNT_A2KEY_EXPIRED:70001,HELLO_ANSWER_KICKED_OUT:1002,OPEN_SERVICE_OVERLOAD_ERROR:60022};function Pt(e){var t;try{const n=ye.getStorage("errorMessage");if(!e||!n)return"";const s=(null===(t=JSON.parse(n))||void 0===t?void 0:t.errorMessage)||{},{isIntl:i=!1,code:o,replacement1:r="",replacement2:a=""}=e;if(!o)return"";const c=i?`${o}_en`:`${o}_cn`;let l=s[s[c]?c:o]||"";return l&&(r&&(l=l.replace("$replacement1",r)),a&&(l=l.replace("$replacement2",a))),l}catch(e){return console.warn("Error parsing stored error messages:",e),""}}class Ut extends Error{constructor(e){const{functionName:t="Unknown",code:n,message:s="",data:i=""}=e;let o=s;n&&!s&&(o=Pt(e));const r=n?`${t} failed. error: {"message": ${o}, "code": ${n}}`:`${t} failed. error: {"message": ${o}}`;super(),this.code=n,this.errorCode=n,this.errorMessage=r,this.message=r,this.data=i}}const Ft=e=>"function"==typeof e;function Gt(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]?Gt(e[s],t[s],n):e[s]===t[s])))}function Bt({required:e,rules:t,range:n,value:s,allowEmpty:i,name:o,key:r,customValidator:a}){if(void 0===s){if(e){throw new Ut({functionName:o,message:`[${o}] Missing required params: "${r}"`})}return}let c="";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()),c+=`${n}/`}c=c.substring(0,c.length-1);const e=`[${r}] must be type of ${c}, received type: ${function(e){return Reflect.apply(Object.prototype.toString,e,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}(s)}.`;throw new Ut({functionName:o,message:e})}if(!1===i){if(Array.isArray(s)&&(0===s.length||"string"==typeof s[0]&&""===s[0].trim())){throw new Ut({functionName:o,message:`cannot be empty: "${r}"`})}if("string"==typeof s&&""===s.trim()){throw new Ut({functionName:o,message:`cannot be empty: "${r}"`})}}if(a&&"function"==typeof a){const e=a(s);if(!0!==e){throw new Ut({functionName:o,message:`[${r}] custom validation failed: ${e||"Invalid value"}`})}}}const $t=[],xt={},qt={};function jt(e,t){!function(e,t){var n;if(!e)return;if(!0!==(null===(n=pt.store.get("login"))||void 0===n?void 0:n.isLoggedIn))throw new Ut({code:kt.USER_NOT_LOGGED_IN,functionName:t})}(xt[e],e),function(e,t,n){if(Array.isArray(e))for(let s=0;s<e.length;s++)Bt.call(this,Object.assign(Object.assign({},e[s]),{value:t[s],name:n}));else for(const s in e)Bt.call(this,Object.assign(Object.assign({},e[s]),{value:t[0][s],name:n,key:s}))}(qt[e],t,e),function(e){$t.forEach((t=>{const{interceptor:n,context:s}=t;n.apply(s,[e])}))}(e)}function Vt(e,t){$t.push({interceptor:e,context:t})}function Yt(e){const{params:t,auth:n}=e;t&&"object"==typeof t&&Object.assign(qt,t),n&&"object"==typeof n&&Object.assign(xt,n)}var Kt=new class{constructor(){this._builtInPlugins=new WeakSet,this._externalPlugins=new WeakSet}installBuiltInPlugin(e){e&&this._installPlugin(e,this._builtInPlugins)}installExternalPlugin(e,...t){e&&this._installPlugin(e,this._externalPlugins,...t)}clear(){this._builtInPlugins=new WeakSet,this._externalPlugins=new WeakSet}_installPlugin(e,t,...n){let s=[];s=Array.isArray(e)?e:[e],s.forEach((e=>{t.has(e)||(e&&Ft(e.install)?(t.add(e),e.install(Zt(),...n),Ft(e.handleLoginSuccess)&&this._isLoggedIn()&&e.handleLoginSuccess()):Ft(e)?(t.add(e),e(Zt(),...n),Ft(e.handleLoginSuccess)&&this._isLoggedIn()&&e.handleLoginSuccess()):console.warn('A plugin must either be a function or an object with an "install" function.'))}))}_isLoggedIn(){var e;return!0===(null===(e=pt.store.get("login"))||void 0===e?void 0:e.isLoggedIn)}};const Ht={on:pt.notificationCenter.subscribeOuterEvent.bind(pt.notificationCenter),off:pt.notificationCenter.unSubscribeOuterEvent.bind(pt.notificationCenter),destroy:function(){return a(this,void 0,void 0,(function*(){var e,t;try{(null===(e=pt.store.get("login"))||void 0===e?void 0:e.isLogin)&&(yield Ht.logout()),pt.notificationCenter.emitInnerEvent(Mt.DESTROY)}catch(e){console.debug("destroy error: ",e)}finally{pt.notificationCenter.emitOuterEvent(yt.SDK_DESTROY,{SDKAppID:null===(t=pt.store.get("instance"))||void 0===t?void 0:t.sdkAppId}),Oi.clear(),Kt.clear(),pt.destroy()}}))},callExperimentalAPI:function(e,t){if(Wt[e])return Wt[e](t);return Promise.reject(new Error(`API ${e} is not found`))},use:Kt.installExternalPlugin.bind(Kt),registerPlugin:function(e){console.log("registerPlugin",e)}},Wt={};function zt(e,t,n){const s=n||e;Ht[e]=(...e)=>(jt(s,e),t[s].bind(t)(...e))}function Jt(e,t,n){const s=n||e;Wt[e]=t[s].bind(t)}function Zt(){return Object.assign({InnerEvent:Mt,InnerEventSubType:pt.notificationCenter.InnerEventSubType,OuterEvent:yt,OuterConstant:Lt,SignalingEvent:Ot,helper:Object.assign(Object.assign(Object.assign({},pt.utils),pt.common),{registerApi:zt,registerExperimentalAPI:Jt,registerInterceptor:Vt,registerValidateConfig:Yt,ChatError:Ut}),apiMap:Ht},pt)}var Xt,Qt,en;!function(e){e[e.USER_INITIATED=0]="USER_INITIATED",e[e.KICKED_OUT=1]="KICKED_OUT"}(Xt||(Xt={})),function(e){e[e.multipleAccount=1]="multipleAccount",e[e.multipleDevice=2]="multipleDevice",e[e.restApi=3]="restApi"}(Qt||(Qt={})),function(e){e[e.multipleDevice=3002]="multipleDevice",e[e.multipleAccount=3003]="multipleAccount",e[e.usersigExpired=70001]="usersigExpired",e[e.restApi=20002]="restApi"}(en||(en={}));const tn={[Qt.multipleAccount]:"multipleAccount",[Qt.multipleDevice]:"multipleDevice",[Qt.restApi]:"REST_API_Kick",[en.multipleAccount]:"multipleAccount",[en.multipleDevice]:"multipleDevice",[en.restApi]:"REST_API_Kick",[en.usersigExpired]:"userSigExpired"},nn="login_online_presence_task",{ERROR:sn,DESTROY:on,FORCE_OFFLINE:rn}=Mt,{KICKED_OUT_MULT_ACCOUNT:an,KICKED_OUT_MULT_DEVICE:cn,KICKED_OUT_REST_API:ln,ACCOUNT_A2KEY_EXPIRED:dn,MSG_A2KEY_EXPIRED:un}=kt;class hn{init(){const{notificationCenter:e}=pt;e.subscribeInnerEvent(rn,this._handleForceOfflineFromServerPush,this),e.subscribeInnerEvent(sn,un,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(sn,dn,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(sn,an,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(sn,cn,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(sn,ln,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(on,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 a(this,void 0,void 0,(function*(){const{kickedOutReasonCode:t}=e;try{yield pt.login.loginAction.logout(Xt.KICKED_OUT)}catch(e){console.debug(e)}finally{this._logKickedOutEvent(e),pt.notificationCenter.emitOuterEvent(yt.KICKED_OUT,{data:{type:tn[t]},name:yt.KICKED_OUT}),[Qt.restApi,dn,un].includes(t)&&pt.channel.reconnect()}}))}_logKickedOutEvent(e){const{kickedOutReasonCode:t,newInstanceInfo:n={}}=e,s=pt.ssoLog.createSSOLogData({method:"kickedOut"}),i=`type:${tn[t]} newInstanceInfo: ${JSON.stringify(n)}`;s.setLogInfo({message:i}).end(!0),console.warn(`loginModule.${i}`)}_isKickedOut(e){return[Qt.multipleAccount,Qt.multipleDevice,Qt.restApi].includes(e)}_dispose(){const{notificationCenter:e}=pt;e.unSubscribeInnerEvent(rn,this._handleForceOfflineFromServerPush,this),e.unSubscribeInnerEvent(sn,dn,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(sn,un,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(sn,an,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(sn,cn,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(sn,ln,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(on,this._dispose,this)}}function _n(){return a(this,void 0,void 0,(function*(){const e="im_open_status.wslogin",t=pt.common.generateProtocolData({servcmd:e,data:{state:"Online",isWebUniapp:0,InstType:0,customInfo:""}}),n=`${t.head.seq}${e}`;try{const e=yield pt.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}}))}class gn{constructor(){this._latestLoginAt=0,this._latestSendOnlinePresenceRequestTime=0,this._helloInterval=120}init(){const{notificationCenter:e,store:t}=pt;t.set("login",{isReady:!1}),zt("login",this),zt("logout",this),zt("getLoginUser",this),zt("isReady",this),e.subscribeInnerEvent(Mt.RECONNECTED,this._reLogin,this),pt.notificationCenter.subscribeInnerEvent(Mt.DESTROY,this._dispose,this)}login(e){return a(this,void 0,void 0,(function*(){pt.notificationCenter.emitInnerEvent("BEFORE_LOGIN");const t=pt.ssoLog.createSSOLogData({method:"login",eventType:4});try{if(this._isLoginIn())return this._createRepeatLoginResponse();if(this._isLoginFrequencyExceeded())throw new Ut({functionName:"login",code:kt.REPEAT_LOGIN});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 Ut({functionName:"login",code:n});throw t.setError(s).end(!0),s}finally{this._latestLoginAt=0}}))}_reLogin(){return a(this,void 0,void 0,(function*(){var e;try{if(!this._isLoginIn())return;const t=pt.ssoLog.createSSOLogData({method:"reLogin"}),n=yield _n();if(n){const{instanceID:s,customStatus:i}=n;pt.store.set("login",{statusInstanceId:s}),pt.user.userStatus.setCustomStatus(i),pt.notificationCenter.emitInnerEvent(Mt.RE_LOGIN);const o=`socketId:${null===(e=pt.channel.getSocketAdapter())||void 0===e?void 0:e.getId()} instanceId:${s}`;t.setLogInfo({message:o}).end(!0)}}catch(e){console.warn(e)}}))}logout(){return a(this,arguments,void 0,(function*(e=Xt.USER_INITIATED){pt.ssoLog.createSSOLogData({method:"logout"}).setLogInfo({moreMessage:`identifier:${this._getCurrentUserId()}`}).end(!0);try{yield this._performLogout(e)}catch(e){const{errorCode:t}=e,n=new Ut({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=pt.store.get("login"))||void 0===e?void 0:e.isReady}_updateAndEmitSDKReady(){pt.store.set("login",{isReady:!0}),setTimeout((()=>{pt.notificationCenter.emitOuterEvent(yt.SDK_READY,{name:yt.SDK_READY})}),1)}_updateAndEmitSDKNotReady(){pt.store.set("login",{isReady:!1}),pt.notificationCenter.emitOuterEvent(yt.SDK_NOT_READY,{name:yt.SDK_NOT_READY})}_validateAfterLogin(e){var t,n;const s="login";if(!e)throw new Ut({functionName:s,message:"login response is empty"});const{tinyID:i,a2Key:o}=e||{},r=pt.ssoLog.getSSOLogData(s);if(!i){const e=new Ut({functionName:s,code:kt.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 Ut({functionName:s,code:kt.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=pt.store.get("login"))||void 0===e?void 0:e.userId}),repeatLogin:!0}}}_performLogin(e){return a(this,void 0,void 0,(function*(){const{userID:t,userSig:n}=e;return pt.store.set("login",{userId:t,userSig:n}),this._latestLoginAt=Date.now(),_n()}))}_ensureAsyncComplete(){return a(this,void 0,void 0,(function*(){yield new Promise((e=>{setTimeout((()=>e(null)),1)}))}))}_handleLoginSuccess(e){const{timeManager:t}=pt.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),pt.user.userStatus.setCustomStatus(i),pt.notificationCenter.emitInnerEvent(Mt.LOGIN,{purchaseBits:o}),pt.common.taskScheduler.addTask({id:nn,intervalMs:1e3*this._helloInterval,callback:this._sendOnlinePresenceRequest,context:this}),this._logLoginSuccess(e)}_performLogout(e){return function(e){return a(this,void 0,void 0,(function*(){const{logoutReason:t}=e,n="im_open_status.wslogout",s=pt.common.generateProtocolData({servcmd:n,data:{wslogout_type:t,isWebUniapp:0}}),i=`${s.head.seq}${n}`;return yield pt.channel.sendPacket(s,{requestId:i})}))}({logoutReason:e})}_handleLogoutError(e){pt.ssoLog.getSSOLogData("logout").setError(e).end(),console.error(`logout ${e}`)}_handleLogoutCompleted(){this._updateAndEmitSDKNotReady(),this._reset(),pt.notificationCenter.emitInnerEvent("logout")}_updateLoginStore(e){const{a2Key:t,tinyID:n,instanceID:s,authKey:i}=e;pt.store.set("login",{a2Key:t,tinyID:n,statusInstanceId:s,authKey:i,isLoggedIn:!0})}_logLoginSuccess(e){var t;const n=pt.ssoLog.getSSOLogData("login"),{helloInterval:s,instanceID:i,timeStamp:o,customStatus:r}=e,a=null===(t=pt.channel.getSocketAdapter())||void 0===t?void 0:t.getId(),c=pt.common.timeManager.getTimeOffsetWithServer(),{appId:l,href:d}=pt.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 a(this,void 0,void 0,(function*(){this._latestSendOnlinePresenceRequestTime=Date.now();try{yield function(){const e="im_open_status.wshello",t=pt.common.generateProtocolData({servcmd:e,data:{isWebUniapp:0}}),n=`${t.head.seq}${e}`;return pt.channel.sendPacket(t,{requestId:n})}()}catch(e){console.warn("Login._sendOnlinePresenceRequest error:",e)}}))}_getCurrentUserId(){var e;return null===(e=pt.store.get("login"))||void 0===e?void 0:e.userId}_isLoginIn(){var e;return!0===(null===(e=pt.store.get("login"))||void 0===e?void 0:e.isLoggedIn)}_isLoginFrequencyExceeded(){return Date.now()-this._latestLoginAt<=15e3}_reset(){console.log("Login reset"),pt.common.taskScheduler.removeTask(nn),this._helloInterval=120,this._latestSendOnlinePresenceRequestTime=0,this._latestLoginAt=0,pt.store.clear("login"),pt.store.set("login",{isReady:!1})}_dispose(){console.log("Login dispose"),this._reset();const{notificationCenter:e}=pt;e.unSubscribeInnerEvent(Mt.RECONNECTED,this._reLogin,this),e.unSubscribeInnerEvent(Mt.DESTROY,this._dispose,this)}}const fn={login:{userID:{required:!0,rules:["string"],allowEmpty:!1},userSig:{required:!0,rules:["string"],allowEmpty:!1}}},mn={logout:!0};class vn{constructor(){this.loginAction=new gn,this.kickedOutHandler=new hn,this.loginAction.init(),this.kickedOutHandler.init(),Yt({auth:mn,params:fn})}}var pn,Sn,In;!function(e){e.CONV_C2C="C2C",e.CONV_GROUP="GROUP",e.CONV_TOPIC="TOPIC",e.CONV_SYSTEM="@TIM#SYSTEM"}(pn||(pn={})),function(e){e.MSG_PRIORITY_HIGH="High",e.MSG_PRIORITY_NORMAL="Normal",e.MSG_PRIORITY_LOW="Low",e.MSG_PRIORITY_LOWEST="Lowest"}(Sn||(Sn={})),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"}(In||(In={}));const En={1:Sn.MSG_PRIORITY_HIGH,2:Sn.MSG_PRIORITY_NORMAL,3:Sn.MSG_PRIORITY_LOW,4:Sn.MSG_PRIORITY_LOWEST};var yn;!function(e){e.IN="in",e.OUT="out"}(yn||(yn={}));const Cn={};function Mn(e){if(!e)return 0;if(void 0===Cn[e]){const t=new Date,n=`3${t.getHours()}`.slice(-2),s=`0${t.getMinutes()}`.slice(-2),i=`0${t.getSeconds()}`.slice(-2);Cn[e]=parseInt([n,s,i,"0001"].join(""),10),console.log(`autoIncrementIndex start index:${Cn[e]}`)}else Cn[e]+=1;return Cn[e]}class On{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=Sn.MSG_PRIORITY_NORMAL,this._relayFlag=!1;const{clientTime:t=pt.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:f,messageVersion:m=0,conversationType:v,sequence:p,checkResult:S=0,isPlaceMessage:I=0,messageFlagBits:E,receiverList:y,isSystemMessage:C=!1,status:M=Dt.SUCCESS,revokeReason:O="",conversationSubType:T,clientSequence:D,protocol:A="JSON",revokerInfo:b={userID:"",nick:"",avatar:""},readReceiptInfo:w={readCount:void 0,unreadCount:void 0,isPeerRead:void 0,timestamp:0},random:N,groupProfile:R,flow:L}=e;var k;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===N?(k=k||99999999,Math.round(Math.random()*k)):N,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=!!m,this.cloudCustomData=g,this.messageLifeTime=f,this.from=c||null,this.sequence=p||0,this.conversationType=v||pn.CONV_C2C,this.hasRiskContent=S>1,this.version=m,this.isPlaceMessage=I,this.isRevoked=2===I||8===E,this.isSystemMessage=C,this.readReceiptInfo=w,this.revokeReason=O,this.revokerInfo=b,this._receiverList=y,this.conversationSubType=T,this.revoker=(null==b?void 0:b.revoker)||"",this.clientSequence=D||p||0,this.status=M,this.flow=L,this.reInitialize(s),this._initC2CReadReceiptInfo(e),this._extractGroupInfo(R)}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}setRelayFlag(e){this._relayFlag=e}validateBeforeSend(){var e,t,n;return this._relayFlag?{isValid:!0}:(null===(e=this._elements)||void 0===e?void 0:e.length)>0?null===(n=null===(t=this._elements[0])||void 0===t?void 0:t.validateBeforeSend)||void 0===n?void 0:n.call(t):{isValid:!1}}_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===pn.CONV_C2C&&!0===this.needReadReceipt&&(this.readReceiptInfo.isPeerRead=1===t,this.readReceiptInfo.timestamp=n)}_extractGroupInfo(e){if(!e)return;const{From_AccountNick:t,From_AccountHeadurl:n,MsgFrom_AccountExtraInfo:s}=e,{NameCard:i}=s||{};"string"==typeof t&&(this.nick=t),"string"==typeof n&&(this.avatar=n),"string"==typeof i&&(this.nameCard=i)}reInitialize(e){e===this.from&&(this.isRead=!0),this._initSequence(e),this._concatConversationID(e),this._generateMessageID()}_concatConversationID(e){let t="";const n=this.conversationType;n!==pn.CONV_SYSTEM?(t=n===pn.CONV_C2C?e===this.from?this.to:this.from:this.to,this.conversationID=t?`${n}${t}`:null):this.conversationID=pn.CONV_SYSTEM}_initSequence(e){0===this.clientSequence&&e&&(this.clientSequence=Mn(e)),0===this.sequence&&this.conversationType===pn.CONV_C2C&&(this.sequence=this.clientSequence)}_generateMessageID(){this.from===pn.CONV_SYSTEM&&(this.senderTinyID="144115198244471703"),this.ID=`${this.senderTinyID}-${this.clientTime}-${this.random}`}}class Tn{static parseServerPushElement(e){const{MsgContent:t={}}=e,{Data:n,Ext:s,Desc:i}=t;return new Tn({data:n,description:i,extension:s})}constructor(e){this.type=In.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}}}validateBeforeSend(){const{isEmpty:e}=pt.utils,t=[this.content.data,this.content.description,this.content.extension].some((t=>!e(t)));return{isValid:t,error:t?null:{message:"content can not be empty"}}}}class Dn{constructor(){this._elementClassMap={[In.MSG_CUSTOM]:Tn}}init(){zt("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){const{from:t,flow:n=yn.OUT}=e,{userId:s}=pt.store.get("login")||{};this._isSendByCurrentInstance({from:t,flow:n,currentUser:s})?this._updateWithSenderInfo(e):this._isMultiEndpointSyncMessage({from:t,flow:n,currentUser:s})&&(e.flow=yn.OUT);const i=Object.assign(Object.assign({},e),{currentUser:s});return new On(i)}createCustomMessage(e){var t;const n=null===(t=pt.store.get("login"))||void 0===t?void 0:t.userId,s=this.createMessage(Object.assign(Object.assign({},e),{from:n})),i=this._elementClassMap[In.MSG_CUSTOM];if(!s)return null;if(i){const t=new i(e.payload);s.setElement(t)}return s}_updateWithSenderInfo(e){const{nick:t,avatar:n}=e,{userId:s,tinyID:i}=pt.store.get("login")||{},o=pt.user.userProfile.getUserProfileFromCache(s);return e.nick=t||(null==o?void 0:o.nick)||"",e.avatar=n||(null==o?void 0:o.avatar)||"",e.tinyID=e.tinyID||i||"",e.from=s,e.status=Dt.UNSENT,e.flow=yn.OUT,e}_isMultiEndpointSyncMessage(e){const{from:t,flow:n,currentUser:s}=e;return t===s&&n===yn.IN}_isSendByCurrentInstance(e){const{from:t,flow:n,currentUser:s}=e;return t===s&&n===yn.OUT}}function An(e){const t=e.lastIndexOf(".");return-1===t?e:e.slice(0,t)}function bn(e){const{androidInfo:t={},androidOPPOChannelID:n=""}=e,s=t.OPPOChannelID||n;return Object.assign(Object.assign({},t),{Sound:An(t.sound||""),OPPOChannelID:s,GoogleChannelID:t.FCMChannelID||""})}function wn(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 Nn(e){return pt.utils.isPlainObject(e)?{PushFlag:!0===e.disablePush?1:0,Title:e.title||"",Desc:e.description||"",Ext:e.extension||"",ApnsInfo:wn(e),AndroidInfo:bn(e)}:null}const{isPlainObject:Rn}=pt.utils;function Ln(e,t={}){const{onlineUserOnly:n,messageControlInfo:s}=t;let{offlinePushInfo:i}=t;e.conversationType===pn.CONV_C2C&&!0===n&&(i?i.disablePush=!0:i={disablePush:!0});let o="";"string"==typeof e.cloudCustomData&&e.cloudCustomData.length>0&&(o=e.cloudCustomData);const r=[];if(s&&Rn(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}}function kn(e){const{webhookInfo:{disableCloudMessagePreHook:t=!1,disableCloudMessagePostHook:n=!1}={}}=e||{};if(!t&&!n)return;const s=[];return t&&s.push("ForbidBeforeSendMsgCallback"),n&&s.push("ForbidAfterSendMsgCallback"),s}function Pn(e,t){return a(this,void 0,void 0,(function*(){const n=e.conversationType===pn.CONV_GROUP?function(e,t){var n;const s=Ln(e,t),{onlineUserOnly:i,cloudCustomData:o,messageControlInfo:r,offlinePushInfo:a}=s,c=JSON.parse(JSON.stringify(e.convertElementsToBackendFormat()));return{servcmd:"group_open_http_svc.send_group_msg",data:{From_Account:null===(n=pt.store.get("login"))||void 0===n?void 0:n.userId,GroupId:e.to,MsgBody:c,CloudCustomData:o,Random:e.random,MsgPriority:e.priority,ClientSeq:e.clientSequence,GroupAtInfo:[],OnlineOnlyFlag:i?1:0,MsgClientTime:e.clientTime,OfflinePushInfo:Nn(a),SendMsgControl:i?void 0:r,NeedReadReceipt:!0===e.needReadReceipt?1:0,receiverList:null,SupportMessageExtension:!0===e.isSupportExtension?1:0,IsRelayMsg:!0===e._relayFlag?1:0,CustomModerationConfigID:e._cmConfigID,ForbidCallbackControl:kn(t)}}}(e,t):function(e,t){var n;const s=Ln(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=pt.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,CustomModerationConfigID:e._cmConfigID,OfflinePushInfo:Nn(a),forbidCallbackControl:kn(t)}}}(e,t),s=pt.common.generateProtocolData(n),i=`${s.head.seq}${s.head.servcmd}`,o=yield pt.channel.sendPacket(s,{requestId:i});return o?{time:o.MsgTime,messageDropReason:o.MsgDropReason,sequence:o.MsgSeq}:null}))}const{isPlainObject:Un}=pt.utils;class Fn{init(){zt("sendMessage",this)}sendMessage(e,t){return a(this,void 0,void 0,(function*(){const n=pt.ssoLog.createSSOLogData({method:"sendMessage"});if(!(e instanceof On)){const e=new Ut({code:kt.MSG_INSTANCE_REQUIRED});throw n.setError(e).end(),e}const s=e.validateBeforeSend();if(!s.isValid){const{code:e,message:t=""}=s.error||{},i=new Ut({code:e,message:t});throw n.setError(i).end(),i}let i=!1;const{messageStore:o}=pt.message||{};try{const{messageControlInfo:s}=t||{};let r=null;if(o.addRandomOfSentMessage(e.random),e.conversationType===pn.CONV_C2C?(i=!0===(null==t?void 0:t.onlineUserOnly),r=yield this._sendC2cMessage(e,t)):e.conversationType===pn.CONV_GROUP&&(r=yield this._sendGroupMessage(e,t)),r){const{messageDropReason:a,sequence:c,time:l}=r;if(a&&this._logRateLimitInfo(e,c),!0===e.isResend){const t=o.findMessage(e.ID);t&&(console.log(`sendMessage resend ok. ID:${t.ID}`),o.deleteConversationMessage(t))}return e.status=Dt.SUCCESS,e.time=l,e.conversationType===pn.CONV_GROUP&&(e.sequence=c),i?e._onlineOnlyFlag=!0:(o.storeConversationMessage(e),this._applySentMessageControlInfo(e,s),this._emitOnlineMessageSent(e)),n.setLogInfo({message:`options: ${JSON.stringify(t)}`}).end(),{code:0,data:{message:e}}}}catch(t){e.status=Dt.FAIL,o.removeRandomOfSentMessage(e.random);const{errorCode:n,errorInfo:s=""}=t||{};this._hasRiskContent(n)&&(e.hasRiskContent=!0),i||this._isRejectedByRestApi(n)||o.storeConversationMessage(e);const r=new Ut({code:n,message:s,data:{message:e}});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=pt.ssoLog.createSSOLogData({method:"sendMessage"});let s=`head.seq: type:${e.type} from:${e.from} to:${e.to}`;if(pt.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,{conversationID:n,conversationType:s}=e;pt.notificationCenter.emitInnerEvent(Mt.NEW_MESSAGE,{conversationOptionsList:[{conversationID:n,type:s,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=pt.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 a(this,void 0,void 0,(function*(){const n=yield Pn(e,t),{messageStore:s}=pt.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}))}_sendGroupMessage(e,t){return a(this,void 0,void 0,(function*(){return Pn(e,t)}))}}function Gn(e){const{From_AccountHeadurl:t,From_AccountNick:n,IsNeedReadReceipt:s,IsSyncMsg:i,MsgBody:o,MsgClientTime:r,MsgLifeTime:a,MsgRandom:c,MsgSeq:l,MsgTimeStamp:d,SendMsgControl:u,SupportMessageExtension:h,TinyId:_,MsgCheckResult:g,CloudCustomData:f,RevokerInfo:m}=e;let v,{From_Account:p,To_Account:S}=e;if(1===i){const e=S;S=p,p=e}if(m){const{Reason:e,Revoker_Account:t,Revoker_FromUin:n}=m;v={reason:e,revoker:t,revokerFromUin:n,userID:t}}return{from:p,avatar:t,nick:n,needReadReceipt:1===s,isSyncMessage:i,clientTime:r,messageLifeTime:a,random:c,sequence:l,time:d,messageControlInfo:u,isSupportExtension:h,to:S,tinyID:_,checkResult:g,cloudCustomData:f,revokerInfo:v,elements:xn(o)}}function Bn(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:xn(n),messageVersion:c,cloudCustomData:l}}function $n(e){const{ClientSeq:t,From_Account:n,GroupInfo:s,MsgBody:i,MsgClientTime:o,MsgRandom:r,MsgSeq:a,MsgTimeStamp:c,SendMsgControl:l,SupportMessageExtension:d,TinyId:u,ToGroupId:h,CloudCustomData:_,MsgVersion:g,MsgCheckResult:f,NeedReadReceipt:m,IsPlaceMsg:v,RevokerInfo:p}=e;let S,I=Sn.MSG_PRIORITY_NORMAL;if(Object.keys(En).includes(String(e.MsgPriority))&&(I=En[e.MsgPriority]),p){const{Reason:e,Revoker_Account:t,Revoker_FromUin:n}=p;S={reason:e,revoker:t,revokerFromUin:n,userID:t}}return{clientSequence:t,from:n,groupProfile:s,clientTime:o,priority:I,random:r,sequence:a,time:c,messageControlInfo:l,isSupportExtension:d,to:h,tinyID:u,cloudCustomData:_,messageVersion:g,messageCheckResult:f,needReadReceipt:m,isPlaceMessage:v,revokerInfo:S,elements:xn(i)}}function xn(e){if(!e)return null;if(Array.isArray(e))return e.map((e=>{const t=pt.message.messageFactory.getElementClass(e.MsgType);return null==t?void 0:t.parseServerPushElement(e)}));const t=pt.message.messageFactory.getElementClass(e.MsgType);return null==t?void 0:t.parseServerPushElement(e)}var qn=Object.freeze({__proto__:null,autoIncrementIndex:Mn,parseServerGroupMessage:$n,parseServerPushC2CModifyMessage:Bn,parseServerPushMessage:Gn,parseServerPushMessageElement:xn});class jn{constructor(e){this.value=e,this.next=null}}class Vn{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 jn(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 Yn{constructor(){this._continuousMessagesByConversation=new Map,this._sparseMessagesByConversation=new Map,this._latestMessageSentByPeerMap=new Map,this._latestMessageSentByMeMap=new Map,this._randomOfSentMessageList=new Vn(100),pt.notificationCenter.subscribeInnerEvent(Mt.LOGOUT,this._reset,this),pt.notificationCenter.subscribeInnerEvent(Mt.DESTROY,this._dispose,this)}storeConversationMessage(e,t=!1){const{conversationID:n}=e;if(!n)return!1;if(this._continuousMessagesByConversation.has(n)||this._continuousMessagesByConversation.set(n,new Map),this._shouldSkipStoreMessage(e,t))return!1;const s=this._getUniqueIdOfMessage(e);return this._continuousMessagesByConversation.get(n).set(s,e),this._updateLatestMessageMap(e),!0}_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._continuousMessagesByConversation.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!0}return!1}deleteConversationMessage(e){var t;const{conversationID:n=""}=e,s=this._getUniqueIdOfMessage(e);this._continuousMessagesByConversation.has(n)&&(null===(t=this._continuousMessagesByConversation.get(n))||void 0===t||t.delete(s))}modifyConversationMessage(e,t){if(!this._continuousMessagesByConversation.has(e))return{isUpdated:!1,message:null};const n=this._getUniqueIdOfMessage(t),s=this._getMessageFromLocalMessage(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}}_getMessageFromLocalMessage(e,t){var n;return this._continuousMessagesByConversation.has(e)?null===(n=this._continuousMessagesByConversation.get(e))||void 0===n?void 0:n.get(t):null}findMessage(e){let t=null;const n=Array.from(this._continuousMessagesByConversation.values());for(const s of n){if(t=Array.from(s.values()).find((t=>t.ID===e))||null,t)break}if(!t){const n=Array.from(this._sparseMessagesByConversation.values());for(const s of n)if(t=s.get(e)||null,t)break}return t}deleteConversationMessageList(e){this._continuousMessagesByConversation.has(e)&&(this._continuousMessagesByConversation.delete(e),this._latestMessageSentByMeMap.delete(e),this._latestMessageSentByPeerMap.delete(e))}revokeMessage({conversationID:e,sequence:t,random:n}){const s=this._continuousMessagesByConversation.get(e);let i=null;if(s){const e=Array.from(s.values());for(let s=0;s<e.length;s+=1){const o=e[s];if(o.sequence===t&&(void 0===n||o.random===n)){o.isRevoked=!0,i=o;break}}}return i}prependLocalMessageList(e){const{messageList:t,conversationID:n}=e;if(0===t.length)return[];const s=[],i=[],o=this._continuousMessagesByConversation.get(n)||new Map;for(const e of t){const t=this._getUniqueIdOfMessage(e);o.has(t)||(s.push(e),i.push([t,e]))}if(i.length>0){const e=new Map([...i,...o.entries()]);this._continuousMessagesByConversation.set(n,e),this._updateLatestMessageSentByMe(n),this._updateLatestMessageSentByPeer(n)}return s}storeSparseMessageList(e){if(0===e.length)return;const{conversationID:t}=e[0],n=e.length;this._sparseMessagesByConversation.has(t)||this._sparseMessagesByConversation.set(t,new Map);const s=this._sparseMessagesByConversation.get(t);for(let t=0;t<n;t++){const n=e[t];s.has(n.ID)||s.set(n.ID,n)}}_updateLatestMessageSentByMe(e){var t;const n=Array.from((null===(t=this._continuousMessagesByConversation.get(e))||void 0===t?void 0:t.values())||[]);if(0!==n.length)for(let t=n.length-1;t>=0;t--)if("out"===n[t].flow){this._setLatestMsgSentByMe(e,n[t]);break}}_updateLatestMessageSentByPeer(e){var t;const n=Array.from((null===(t=this._continuousMessagesByConversation.get(e))||void 0===t?void 0:t.values())||[]);if(0!==n.length&&e.startsWith("C2C"))for(let t=n.length-1;t>=0;t--)if("in"===n[t].flow){this._setLatestMsgSentByPeer(e,n[t]);break}}_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._continuousMessagesByConversation.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._continuousMessagesByConversation.has(n))return!1;const s=this._getUniqueIdOfMessage(e);return null===(t=this._continuousMessagesByConversation.get(n))||void 0===t?void 0:t.has(s)}isMessageSentByCurrentInstance(e){const{random:t}=e;return this._randomOfSentMessageList.has(t)}getContinuousMessagesByConversation(){return this._continuousMessagesByConversation}getLocalMessageList(e){const t=this._continuousMessagesByConversation.get(e);return t?[...t.values()]:[]}_reset(){this._continuousMessagesByConversation.clear(),this._latestMessageSentByPeerMap.clear(),this._latestMessageSentByMeMap.clear(),this._randomOfSentMessageList.clear()}_dispose(){this._reset(),pt.notificationCenter.unSubscribeInnerEvent(Mt.LOGOUT,this._reset,this),pt.notificationCenter.unSubscribeInnerEvent(Mt.DESTROY,this._dispose,this)}}class Kn{init(){zt("modifyMessage",this)}modifyMessage(e){return a(this,void 0,void 0,(function*(){const t=pt.ssoLog.createSSOLogData({method:"modifyMessage"}),{to:n,payload:s,sequence:i,conversationType:o,random:r,time:c,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===pn.CONV_C2C)return s=yield function(e){return a(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=pt.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 pt.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:c,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 Ut({functionName:"modifyMessage",code:t});throw this._logModifyMessageError(n),n}}))}_logModifyMessageError(e){pt.ssoLog.getSSOLogData("modifyMessage").setError(e).end()}_handleC2CModifyMessageSuccess(e){const{conversationID:t}=e,{isUpdated:n,message:s}=pt.message.messageStore.modifyConversationMessage(t,e);!0===n&&pt.notificationCenter.emitOuterEvent(yt.MESSAGE_MODIFIED,[s]),pt.notificationCenter.emitInnerEvent(Mt.MESSAGE_MODIFIED,{conversationID:t,message:s})}_canModifyMessageElement(e){return[In.MSG_TEXT,In.MSG_CUSTOM,In.MSG_LOCATION,In.MSG_FACE].includes(e)}}class Hn{init(){const{notificationCenter:e}=pt,{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(Mt.DESTROY,this._dispose,this)}_handleC2CMessagePush(e){const{messageStore:t}=pt.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&&pt.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&&pt.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:n})}_generateC2CMessage(e){const t=pn.CONV_C2C,n=Gn(e),s=pt.message.messageFactory.createMessage(Object.assign(Object.assign({},n),{conversationType:t,flow:yn.IN})),{elements:i}=n;return s.setElement(i),s}_updateMessageProfile(e){var t;const{messageStore:n}=pt.message||{},s=null===(t=pt.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}=pt.message.messageStore.modifyConversationMessage(t,e);!0===n&&pt.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[s]}),pt.notificationCenter.emitInnerEvent("ModifyMessageSuccess",e)}_handleC2CMessageModify(e){e.C2cMsgModNotifys.forEach((e=>{var t;const n=pn.CONV_C2C;let s=Bn(e);const{to:i,from:o}=s;let r=`${n}${i}`;i===(null===(t=pt.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}=pt,{InnerEventSubType:t}=e;pt.notificationCenter.unSubscribeInnerEvent("im_open_push.msg_push",t.C2C_REALTIME_MESSAGE,this._handleC2CMessagePush,this),pt.notificationCenter.unSubscribeInnerEvent("im_open_push.msg_push",t.C2C_MODIFIED_MESSAGE,this._handleC2CMessageModify,this),pt.notificationCenter.unSubscribeInnerEvent(Mt.DESTROY,this._dispose,this)}}class Wn{init(){const{notificationCenter:e}=pt,{InnerEventSubType:t}=e;e.subscribeInnerEvent("im_open_push.msg_push",t.GROUP_REALTIME_MESSAGE,this._handleGroupMessagePush,this),e.subscribeInnerEvent(Mt.DESTROY,this._dispose,this)}_handleGroupMessagePush(e){const{messageStore:t}=pt.message,n=[];e.GroupMsgArray.forEach((e=>{const s=this._generateGroupMessage(e);this.updateMessageProfile(s);let i=1===s.isModified;if(t.isMessageSentByCurrentInstance(s)?s.isModified=i:i=!1,s.isOnlineMessage())s._onlineOnlyFlag=!0,t.isMessageSentByCurrentInstance(s)||n.push(s);else if(!t.isInMessageList(s)){t.storeConversationMessage(s)&&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&&pt.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&&pt.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:n})}_generateGroupMessage(e){const t=pn.CONV_GROUP,n=$n(e),s=pt.message.messageFactory.createMessage(Object.assign(Object.assign({},n),{conversationType:t,flow:yn.IN})),{elements:i}=n;return s.setElement(i),s}updateMessageProfile(e){var t;const{messageStore:n}=pt.message||{},s=null===(t=pt.store.get("login"))||void 0===t?void 0:t.userId,{from:i,nick:o,avatar:r,conversationID:a=""}=e;if(i===s){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}=pt.message.messageStore.modifyConversationMessage(t,e);!0===n&&pt.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[s]}),pt.notificationCenter.emitInnerEvent(Mt.MESSAGE_MODIFIED,e)}_dispose(){const{notificationCenter:e}=pt,{InnerEventSubType:t}=e;pt.notificationCenter.unSubscribeInnerEvent("im_open_push.msg_push",t.GROUP_REALTIME_MESSAGE,this._handleGroupMessagePush,this),pt.notificationCenter.unSubscribeInnerEvent(Mt.DESTROY,this._dispose,this)}}class zn{constructor(){this.c2cMessageReceiver=new Hn,this.groupMessageReceiver=new Wn}init(){this.c2cMessageReceiver.init(),this.groupMessageReceiver.init()}}const Jn={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}]},Zn={createCustomMessage:!0,sendMessage:!0,modifyMessage:!0};class Xn{constructor(){this.messageHelper=qn,this.messageFactory=new Dn,this.messageSender=new Fn,this.messageAction=new Kn,this.messageReceiver=new zn,this.messageStore=new Yn,this.messageSender.init(),this.messageFactory.init(),this.messageAction.init(),this.messageReceiver.init(),Yt({auth:Zn,params:Jn})}}function Qn(){return pt.store.get("login").userId}const es="Tag_Profile_IM_",ts=100,ns=500,ss={NICK:`${es}Nick`,GENDER:`${es}Gender`,BIRTHDAY:`${es}BirthDay`,LOCATION:`${es}Location`,SELFSIGNATURE:`${es}SelfSignature`,ALLOWTYPE:`${es}AllowType`,LANGUAGE:`${es}Language`,AVATAR:`${es}Image`,MESSAGESETTINGS:`${es}MsgSettings`,ADMINFORBIDTYPE:`${es}AdminForbidType`,LEVEL:`${es}Level`,ROLE:`${es}Role`},is="USER_STATUS",os=1,rs={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:[]},as=new Map([[ss.NICK,"nick"],[ss.GENDER,"gender"],[ss.BIRTHDAY,"birthday"],[ss.LOCATION,"location"],[ss.SELFSIGNATURE,"selfSignature"],[ss.ALLOWTYPE,"allowType"],[ss.LANGUAGE,"language"],[ss.AVATAR,"avatar"],[ss.MESSAGESETTINGS,"messageSettings"],[ss.ADMINFORBIDTYPE,"adminForbidType"],[ss.LEVEL,"level"],[ss.ROLE,"role"]]);var cs=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}):as.has(t)&&(n[as.get(t)]=s)})),Object.assign(Object.assign({},rs),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:ss[n.toUpperCase()],value:e[n]})})),t}normalizeProfileFields(e){const t={};return e.forEach((e=>{const{tag:n,value:s}=e;if(as.has(n)){const e=as.get(n);t[e]=s}})),t}};const ls=new Map,ds=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];for(let e=0,t=ds.length;e<t;e++)ls.set(e,ds[e]);function us(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:hs}=pt.utils,{generateProtocolData:_s}=pt.common;function gs(e){return a(this,void 0,void 0,(function*(){try{const t="profile.portrait_get_all",n={From_Account:Qn(),UserItem:[]};e.forEach((e=>{n.UserItem.push({CustomSequence:0,StandardSequence:0,To_Account:e})}));const s=_s({servcmd:t,data:n}),i=`${s.head.seq}${t}`,o=yield pt.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=cs.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 fs(e){return a(this,void 0,void 0,(function*(){try{const t="im_open_status.ws_get_user_status",n=_s({servcmd:t,data:{To_Account:e}}),s=`${n.head.seq}${t}`,i=yield pt.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:us(s)}})),r=s.map((e=>{const{To_Account:t,Invalid_Account:n,ErrorCode:s,ErrorInfo:i}=e;return{userID:hs(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:ms}=pt.utils;class vs{constructor(){this._userProfileMap=new Map}init(){zt("getMyProfile",this),zt("getUserProfile",this),zt("updateMyProfile",this),zt("getFriendProfile",this),this.createProfile=cs.createProfile.bind(cs);const{notificationCenter:e}=pt;e.subscribeInnerEvent(Mt.LOGIN,this._handleLoginSuccess,this),e.subscribeInnerEvent("im_open_push.msg_push",e.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),e.subscribeInnerEvent(Mt.LOGOUT,this._reset,this),e.subscribeInnerEvent(Mt.DESTROY,this._dispose,this)}getMyProfile(){return a(this,void 0,void 0,(function*(){const e=pt.ssoLog.createSSOLogData({method:"getMyProfile"});try{const t=Qn(),n=yield gs([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 Ut({functionName:"getMyProfile",code:n,message:s});throw e.setError(i).end(),t}}))}getFriendProfile(e){return a(this,void 0,void 0,(function*(){const t=pt.ssoLog.createSSOLogData({method:"getFriendProfile"});let{userIDList:n}=e;const s=[];n.length>ts&&(n=n.slice(0,ts));try{const{friendUserIdList:e,unFriendUserIdList:i}=this._partitionByIsFriend(n);if(i.forEach((e=>{s.push({userID:e,code:kt.NOT_MY_FRIEND,message:Pt({code:kt.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 a(this,void 0,void 0,(function*(){try{const t="sns.friend_get_specified",n=Qn(),s=_s({servcmd:t,data:{From_Account:n,To_Account:e}}),i=`${s.head.seq}${t}`;return yield pt.channel.sendPacket(s,{requestId:i})}catch(e){throw console.warn(e),e}}))}(e))||{},{successDueToResponseList:r,failureDueToResponseList:c}=this._handleFriendProfileResponse(o);return t.end(),{code:0,data:{friendList:r,failureUserIDList:[...c,...s]}}}catch(e){const{errorCode:n,errorInfo:s}=e,i=new Ut({functionName:"getFriendProfile",code:n,message:s});throw t.setError(i).end(),i}}))}getUserProfile(e){return a(this,void 0,void 0,(function*(){const t=pt.ssoLog.createSSOLogData({method:"getUserProfile"});try{let{userIDList:n}=e;n.length>ts&&(n=n.slice(0,ts));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 gs(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 Ut({functionName:"getUserProfile",code:n});throw t.setError(s).end(),s}}))}getMyProfileCacheThenServer(){return a(this,void 0,void 0,(function*(){const e=Qn(),t=this._userProfileMap.has(e);return t?{code:0,data:t}:this.getMyProfile()}))}updateMyProfile(e){return a(this,void 0,void 0,(function*(){const t=pt.ssoLog.createSSOLogData({method:"updateMyProfile"}),n=Qn(),s={};for(const t in e)void 0!==e[t]&&(s[t]=e[t]);const i=cs.convertParamsToProfile(s);try{const e={From_Account:n,ProfileItem:i};t.setLogInfo({message:JSON.stringify(i)}),yield function(e){return a(this,void 0,void 0,(function*(){try{const t="profile.portrait_set",n=_s({servcmd:t,data:e}),s=`${n.head.seq}${t}`,i=yield pt.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}}))}(e);const o=this._userProfileMap.get(n);let r;r=o?Object.assign(Object.assign({},o),s):cs.createProfile(n,i);return!Gt(o,r,["lastUpdatedTime","profileCustomField"])&&pt.notificationCenter.emitOuterEvent(yt.PROFILE_UPDATED,{name:yt.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 Ut({functionName:"updateMyProfile",code:n,message:s});throw t.setError(i).end(),i}}))}updateMyNickAndAvatar(e){return a(this,void 0,void 0,(function*(){const t=Qn(),n=Date.now(),s=this._userProfileMap.get(t);let i={};i=s?Object.assign(s,e):cs.createProfile(t,e),i.lastUpdatedTime=n,this._userProfileMap.set(t,i)}))}getUserProfileFromCache(e){return this._userProfileMap.get(e)}_handleLoginSuccess(){return a(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:cs.parseProfileList(s)}}(e.ProfileDataMod[0]);if(ms(t))return;const{isProfileUpdated:n,profile:s}=this._handleProfileModified(t);n&&(pt.notificationCenter.emitInnerEvent(Mt.PROFILE_UPDATE,{name:Mt.PROFILE_UPDATE,data:[s]}),pt.notificationCenter.emitOuterEvent(yt.PROFILE_UPDATED,{name:yt.PROFILE_UPDATED,data:[s]}))}_dispose(){const{notificationCenter:e}=pt;e.unSubscribeInnerEvent(Mt.LOGIN,this._handleLoginSuccess,this),e.unSubscribeInnerEvent(Mt.LOGOUT,this._reset,this),e.unSubscribeInnerEvent("im_open_push.msg_push",e.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),e.unSubscribeInnerEvent(Mt.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=cs.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=pt.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&&!ms(e.profileItem))),s=Date.now();return n.map((e=>{const t=cs.createProfile(e.userId,e.profileItem);return t.lastUpdatedTime=s,t}))}_reset(){this._userProfileMap.clear()}}class ps{constructor(){this._customStatus=""}init(){zt("getUserStatus",this),zt("setSelfStatus",this),pt.notificationCenter.subscribeInnerEvent(Mt.LOGOUT,this._reset,this),pt.notificationCenter.subscribeInnerEvent(Mt.DESTROY,this._dispose,this)}setSelfStatus(e){return a(this,void 0,void 0,(function*(){const t=pt.ssoLog.createSSOLogData({method:"setSelfStatus"}),n=Qn(),{customStatus:s}=e;try{return yield function(e){return a(this,void 0,void 0,(function*(){try{const t="im_open_status.ws_set_custom_status",n=_s({servcmd:t,data:{CustomStatus:e}}),s=`${n.head.seq}${t}`,i=yield pt.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:os,customStatus:s}}}catch(e){const{errorCode:n,errorInfo:s}=e,i=new Ut({functionName:"setSelfStatus",code:n,message:s});throw t.setError(i).end(),i}}))}getUserStatus(e){return a(this,void 0,void 0,(function*(){const t=pt.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=us(e);this._customStatus=t}_getMaxQueryUserCount(){const e=pt.store.get("cloudConfig")||{},{status_query_count:t=ns}=e;return parseInt(t,10)}_getMyStatus(){const e=pt.ssoLog.getSSOLogData("getUserStatus");e.setLogInfo({moreMessage:"getUserStatus._getMyStatus"});const t={userID:Qn(),statusType:os,customStatus:this._customStatus};return e.end(),{code:0,data:{successUserList:[t],failureUserList:[]}}}_getUserStatus(e){return a(this,void 0,void 0,(function*(){const t=pt.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 fs(s),{successUserList:o,failureUserList:r}=i||{};return t.end(),{code:0,data:{successUserList:o,failureUserList:r}}}catch(e){const{errorCode:n}=e,s=new Ut({functionName:"getUserStatus",code:n});throw t.setError(s).end(),s}}))}_validateBeforeGetUserStatus(){var e;const t="getUserStatus";if(!(e=is,pt.store.get("commercialConfig").get(e)))throw new Ut({functionName:t,code:kt.NO_USE,replacement1:t})}_isOnlyMeInArray(e){const t=Qn();return 1===e.length&&e.indexOf(t)>-1}_dispose(){pt.notificationCenter.unSubscribeInnerEvent(Mt.DESTROY,this._dispose,this),pt.notificationCenter.unSubscribeInnerEvent(Mt.LOGOUT,this._reset,this),this._reset()}_reset(){this._customStatus=""}}const Ss={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}}},Is={getMyProfile:!0,getUserProfile:!0,getFriendProfile:!0,updateMyProfile:!0,setSelfStatus:!0,getUserStatus:!0};class Es{constructor(){this.userProfile=new vs,this.userStatus=new ps,this.userProfile.init(),this.userStatus.init(),Yt({auth:Is,params:Ss})}}const ys=[{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}],Cs={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"},Ms="im_sdk_config_mgr.fetch_config",Os="im_sdk_config_mgr.push_configv2",Ts="cloud-config";var Ds=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(Os,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(ys)}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=Cs[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 a(this,void 0,void 0,(function*(){try{const{sdkAppId:e}=this._core.store.get("instance")||{},t=this._core.helper.generateProtocolData({servcmd:Ms,data:{uint32_sdkappid:e,uint64_version:this._version}}),n=`${t.head.seq}${Ms}`;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 a(this,void 0,void 0,(function*(){try{if(this._canFetch()){const e=yield this._fetchCloudConfig();this._updateCloudConfig(e)}this._core.helper.taskScheduler.addTask({id:Ts,intervalMs:1e3,callback:this._fetchCloudConfigIfReady,context:this})}catch(e){console.warn(e)}}))}_fetchCloudConfigIfReady(){return a(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(Ts),this._core.store.clear("cloudConfig"),this._updateCmdFreqLimitMap(ys),this._methodCallFrequencyMap.clear(),this._expirationTime=0,this._version=0,this._isFetching=!1}_dispose(){const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(Os,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 As{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 bs={SEARCH_GRP_SNS:new As(0,Math.pow(2,1)).toString(),AV_HISTORY_MSG:new As(0,Math.pow(2,2)).toString(),GRP_COMMUNITY:new As(0,Math.pow(2,3)).toString(),MSG_TO_SPECIFIED_GRP_MBR:new As(0,Math.pow(2,4)).toString(),AV_MBR_LIST:new As(0,Math.pow(2,6)).toString(),USER_STATUS:new As(0,Math.pow(2,7)).toString(),CONV_MARK:new As(0,Math.pow(2,9)).toString(),CONV_GROUP:new As(0,Math.pow(2,10)).toString(),AV_BAN_MBR:new As(0,Math.pow(2,11)).toString(),MSG_EXT:new As(0,Math.pow(2,13)).toString(),GRP_COUNTER:new As(0,Math.pow(2,15)).toString(),PLUGIN_TRANSLATE:new As(Math.pow(2,6)).toString(),PLUGIN_VOICE_TO_TEXT:new As(Math.pow(2,7)).toString(),PLUGIN_CS:new As(Math.pow(2,8)).toString(),PLUGIN_PUSH:new As(Math.pow(2,9)).toString(),PLUGIN_BOT:new As(Math.pow(2,10)).toString(),MSG_REACTION:new As(Math.pow(2,16)).toString(),FOLLOW:new As(Math.pow(2,20)).toString()},ws="CommercialConfig",Ns="commercial-config";var Rs=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){return a(this,void 0,void 0,(function*(){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 As(0,2**o).toString():new As(2**(o-32),0).toString(),!this._featureMap.get(s))){i=!1;break}return console.log(`${ws}.isFeatureEnabled decimalNumber:${e} key:${s} ret:${i}`),{code:0,data:{enabled:i}}}))}_fetchAndParseCommercialConfig(){return a(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 a(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:Ns,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 a(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(`${ws}._parseCommercialConfig failed. Invalid message format:`,e),this._expirationTime=Date.now()+36e5):(console.error(`${ws}._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 As(0,2**s).toString():new As(2**(s-32),0).toString(),"1"===e[n]){this._featureMap.set(t,!0);const e=this._getKeyByValue(bs,t);e&&this._methodKeyMap.set(e,!0)}else{this._featureMap.set(t,!1);const e=this._getKeyByValue(bs,t);e&&this._methodKeyMap.set(e,!1)}}else console.warn(`${ws}.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(Ns),this._core.store.set("commercialConfig",{}),this._expirationTime=0,this._isFetching=!1,this._featureMap.clear()}};var Ls=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=Cs[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 ks=new class{constructor(){this._core=null}install(e){return a(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 a(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}}};function Ps(e,t){return a(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,revokedMessageList:s}=function(e,t){const n=[],s=[];return null==e||e.forEach((e=>{var i,o,r;const a=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:f,CloudCustomData:m,IsPeerRead:v,MsgFlagBits:p,MsgVersion:S,EventArray:I}=e;return{from:n,avatar:s,nick:i,needReadReceipt:1===o,readReceiptSentByPeer:v,clientTime:a,messageFlagBits:p,random:c,sequence:l,time:d,messageControlInfo:u,isSupportExtension:h,to:_,tinyID:g,checkResult:f,cloudCustomData:m,messageVersion:S,eventArray:I,elements:t.message.messageHelper.parseServerPushMessageElement(r)}}(e,t);if(null===(r=null===(o=null===(i=null==a?void 0:a.eventArray)||void 0===i?void 0:i[0])||void 0===o?void 0:o.hasOwnProperty)||void 0===r?void 0:r.call(o,"c2cMessageRevokedNotify"))s.push(a);else{const e=t.message.messageFactory.createMessage(Object.assign(Object.assign({},a),{conversationType:"C2C",flow:"in"})),{elements:s}=a;e.setElement(s),n.push(e)}})),{unreadMessageList:n,revokedMessageList:s}}(e.MsgList,t);return{syncFlag:null==e?void 0:e.SyncFlag,unreadMessageList:n,revokedMessageList:s,cookie:null==e?void 0:e.Cookie}}catch(e){console.warn(e)}}))}var Us,Fs;!function(e){e[e.START_SYNC=0]="START_SYNC",e[e.SYNCING=1]="SYNCING",e[e.SYNC_COMPLETE=2]="SYNC_COMPLETE"}(Us||(Us={})),function(e){e[e.LOGIN_SUCCESS=0]="LOGIN_SUCCESS",e[e.SEND_MESSAGE=1]="SEND_MESSAGE"}(Fs||(Fs={}));var Gs=new class{constructor(){this._unreadDBMessageMap=new Map,this._revokedMessageList=[]}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 a(this,void 0,void 0,(function*(){let e=Us.START_SYNC,t="";for(;this._canContinueSync({cookie:t,syncFlag:e});){const n=yield this._fetchUnreadDBMessage({cookie:t,syncFlag:e,syncTriggerEvent:Fs.LOGIN_SUCCESS});if(!n)break;const{unreadMessageList:s=[],revokedMessageList:i=[]}=n;t=(null==n?void 0:n.cookie)||"",e=null==n?void 0:n.syncFlag,this._parseAndSaveUnreadMessageList(s),this._saveRevokedMessageList(i)}this._emitUnreadMessageSyncComplete()}))}_emitUnreadMessageSyncComplete(){var e;null===(e=this._core)||void 0===e||e.notificationCenter.emitInnerEvent(this._core.InnerEvent.UNREAD_MESSAGES_SYNC_COMPLETED,{revokedMessageList:this._revokedMessageList,unreadMessageMap:this._unreadDBMessageMap})}_saveRevokedMessageList(e){this._revokedMessageList=[...this._revokedMessageList,...e]}_fetchUnreadDBMessage(e){return a(this,void 0,void 0,(function*(){try{const t="unread-message-synchronizer._fetchUnreadDBMessage";console.log(`${t} options:`,e);const n=yield Ps(e,this._core);if(!n)return null;const{syncFlag:s,unreadMessageList:i,revokedMessageList:o,cookie:r}=n;return this._parseAndSaveUnreadMessageList(i),{syncFlag:s,cookie:r,unreadMessageList:i,revokedMessageList:o}}catch(e){console.log(e)}}))}_canContinueSync({cookie:e,syncFlag:t}){var n;return t===Us.START_SYNC||t===Us.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._revokedMessageList=[]}_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()}};var Bs=new class{init(e){var t;this._core=e,this._visibilityChangeHandler=this._handleVisibilityChange.bind(this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this),document.addEventListener("visibilitychange",this._visibilityChangeHandler),null===(t=this._core)||void 0===t||t.store.set("activityMonitor",{isActive:!0})}_handleVisibilityChange(){var e,t;const n="visible"===document.visibilityState;null===(e=this._core)||void 0===e||e.store.set("activityMonitor",{isActive:n}),null===(t=this._core)||void 0===t||t.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:n})}_reset(){var e;null===(e=this._core)||void 0===e||e.store.clear("activityMonitor")}_dispose(){document.removeEventListener("visibilitychange",this._visibilityChangeHandler);const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this),this._reset()}};var $s=new class{init(e){var t;this._core=e,this._bindAppActivityEvent(),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this),null===(t=this._core)||void 0===t||t.store.set("activityMonitor",{isActive:!0})}_bindAppActivityEvent(){var e;const{MINI_APP_NAMESPACE:t}=(null===(e=this._core)||void 0===e?void 0:e.utils)||{};t.onAppShow((()=>{var e,t;null===(e=this._core)||void 0===e||e.store.set("activityMonitor",{isActive:!0}),null===(t=this._core)||void 0===t||t.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!0})})),t.onAppHide((()=>{var e,t;null===(e=this._core)||void 0===e||e.store.set("activityMonitor",{isActive:!1}),null===(t=this._core)||void 0===t||t.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!1})}))}_reset(){var e;null===(e=this._core)||void 0===e||e.store.clear("activityMonitor")}_dispose(){const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this),this._reset()}};var xs=new class{init(e){const{IN_WX_MINI_APP:t}=e.helper;t?$s.init(e):Bs.init(e)}};const qs="none",js="online";var Vs=new class{init(e){this._core=e,this._activateNetworkMonitoring(),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return a(this,void 0,void 0,(function*(){navigator.onLine?this._onOnline():this._onOffline(),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:js})}_onOffline(){this._onNetworkStatusChange({isConnected:!1,networkType:qs})}_reset(){var e;this._deactivateNetworkMonitoring(),null===(e=this._core)||void 0===e||e.store.clear("netWorkMonitor")}_dispose(){var e,t;null===(e=this._core)||void 0===e||e.notificationCenter.unSubscribeInnerEvent(null===(t=this._core)||void 0===t?void 0:t.InnerEvent.DESTROY,this._dispose,this),this._reset()}};var Ys=new class{init(e){this._core=e,this._activateNetworkMonitoring(),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return a(this,void 0,void 0,(function*(){try{wx.getNetworkType().then((e=>{const{isConnected:t,networkType:n}=e;this._onNetworkStatusChange({isConnected:t,networkType:n})})),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;null===(e=this._core)||void 0===e||e.notificationCenter.unSubscribeInnerEvent(null===(t=this._core)||void 0===t?void 0:t.InnerEvent.DESTROY,this._dispose,this),this._reset()}};var Ks=new class{init(e){const{IN_WX_MINI_APP:t}=e.helper;t?Ys.init(e):Vs.init(e)}};var Hs=new class{install(e){xs.init(e),Ks.init(e)}};const Ws=1,zs=2,Js=3,Zs=4,Xs=5,Qs="TIMCustomElem",ei="C2C",ti="GROUP",ni="invite",si="accept",ii="cancel",oi="reject",ri="modifyInvitation",ai="signaling",ci=8010,li="signaling-timeout";function di(e){return e.filter((e=>{if(e.type===Qs){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 ui(e){const{data:t}=e.payload;try{return JSON.parse(t)}catch(e){return console.error(e),null}}function hi(e,t){return e.toString(16).padStart(t,"0")}function _i(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 gi=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=`${ai}.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=`${ai}.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 fi=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=gi.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===Xs&&!!e.match(/excludeTimeoutSignalingFromHistoryMessage/),s=!!e.match(/excludeFromHistoryMessage/)||!!e.match(/excludeOriginalSignalingFromHistoryMessage/);return{excludedFromContentModeration:!0,excludedFromUnreadCount:n||s,excludedFromLastMessage:n||s}}_createInviteSignalingData(e){const t=`${ai}._createInviteSignalingData`,{userID:n,timeout:s=0,groupID:i="",inviteeList:o=[]}=e,r=this._getCurrentUserId(),a=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:Ws,inviter:r,inviteeList:i?o:[n],timeout:s});return console.log(`${t} signalingData:`,a),a}_createAcceptSignalingData(e){const t=`${ai}._createAcceptSignalingData`,{inviteID:n}=e,s=this._getCurrentUserId(),{inviter:i,groupID:o}=gi.getSignaling(n),r=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:Js,groupID:o,inviter:i,inviteeList:[s]});return console.log(`${t} signalingData:`,r),r}_createCancelSignalingData(e){const t=`${ai}._createCancelSignalingData`,{inviteID:n}=e,s=this._getCurrentUserId(),{inviteeList:i,groupID:o}=gi.getSignaling(n),r=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:zs,groupID:o,inviter:s,inviteeList:i});return console.log(`${t} signalingData:`,r),r}_createRejectSignalingData(e){const t=`${ai}._createRejectSignalingData`,{inviteID:n}=e,s=this._getCurrentUserId(),{inviter:i,groupID:o}=gi.getSignaling(n),r=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:Zs,groupID:o,inviter:i,inviteeList:[s]});return console.log(`${t} signalingData:`,r),r}_createTimeoutSignalingData(e){const t=`${ai}._createTimeoutSignalingData`,{isInviter:n=!1,inviteID:s}=e,{inviteeList:i,inviter:o}=gi.getSignaling(s),r=this._getCurrentUserId(),a=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:Xs,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?ti:ei,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[hi(_i(32),8),hi(_i(16),4),hi(16384|_i(12),4),hi(32768|_i(14),4),hi(_i(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 mi=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 a(this,void 0,void 0,(function*(){var t;console.log(`${ai}.invite params:${JSON.stringify(e)}`);try{this._validateBeforeInvite(e);const{signaling:n,signalingData:s,signalingExtensionOptions:i}=fi.createInviteSignaling(e),o=yield this._sendSignaling(n,i);if(0===(null==o?void 0:o.code)){const{inviteID:e,timeout:i}=s;return gi.saveSignaling(e,Object.assign(Object.assign({},s),{signaling:n})),i>0&&(null===(t=this._core)||void 0===t||t.helper.taskScheduler.addOnceTask({id:`${li}-${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(`${ai}.invite error:${e}`),e}}))}accept(e){return a(this,void 0,void 0,(function*(){console.log(`${ai}.accept params:${JSON.stringify(e)}`);try{const{inviteID:t}=e;this._validateBeforeAccept(t),this._isProcessingSignaling=!0;const{signaling:n,signalingData:s,signalingExtensionOptions:i}=fi.createAcceptSignaling(e),o=yield this._sendSignaling(n,i);return 0===(null==o?void 0:o.code)?(gi.updateSignaling(s),Object.assign(Object.assign({},o),{inviteID:t})):o}catch(e){throw console.error(`${ai}.accept error:${e}`),e}finally{this._isProcessingSignaling=!1}}))}cancel(e){return a(this,void 0,void 0,(function*(){console.log(`${ai}.cancel params:${JSON.stringify(e)}`);try{const{inviteID:t}=e;this._validateBeforeCancel(t),this._isProcessingSignaling=!0;const{signaling:n,signalingExtensionOptions:s}=fi.createCancelSignaling(e),i=yield this._sendSignaling(n,s);return 0===(null==i?void 0:i.code)?(gi.removeSignaling(t),Object.assign(Object.assign({},i),{inviteID:t})):i}catch(e){throw console.error(`${ai}.cancel error:${e}`),e}finally{this._isProcessingSignaling=!1}}))}reject(e){return a(this,void 0,void 0,(function*(){console.log(`${ai}.reject params:${JSON.stringify(e)}`);try{const{inviteID:t}=e;this._validateBeforeReject(t),this._isProcessingSignaling=!0;const{signaling:n,signalingExtensionOptions:s}=fi.createRejectSignaling(e),i=yield this._sendSignaling(n,s);return 0===(null==i?void 0:i.code)?(gi.removeSignaling(t),Object.assign(Object.assign({},i),{inviteID:t})):i}catch(e){throw console.error(`${ai}.reject error:${e}`),e}finally{this._isProcessingSignaling=!1}}))}modifyInvitation(e){return a(this,void 0,void 0,(function*(){var t,n;console.log(`${ai}.modifyInvitation params:${JSON.stringify(e)}`);const{inviteID:s,data:i}=e;let o="";try{this._validateBeforeModifyInvitation(s);const e=gi.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 gi.hasSignaling(s)&&gi.saveSignaling(s,Object.assign(Object.assign({},a),{signaling:r})),c}catch(e){if(o){const{signaling:e}=gi.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)&&gi.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)&&gi.setSignalingListenStatus(!1),null===(i=this._core)||void 0===i||i.notificationCenter.unSubscribeOuterEvent(e,t,n)}handleInvitationExpiryTimer(e){const t=gi.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 a(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 a(this,void 0,void 0,(function*(){var t,n,s;console.log(`${ai}._sendTimeoutNotice params:${JSON.stringify(e)}`);const{isInviter:i,inviteID:o}=e,{signaling:r,signalingData:a,signalingExtensionOptions:c}=fi.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?gi.removeSignaling(o):gi.updateSignaling(a)}}))}_validateInviteId(e,t){if(!gi.hasSignaling(t))throw new this._core.helper.ChatError({functionName:e,code:ci})}_validateProcessStatus(e){if(this._isProcessingSignaling)throw new this._core.helper.ChatError({functionName:e,message:"processing other signaling operations"})}_validateBeforeInvite(e){const t=ni,{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=si;this._validateInviteId(t,e),this._validateProcessStatus(t);const n=this._getCurrentUserId(),{inviteeList:s}=gi.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=ii;this._validateInviteId(t,e),this._validateProcessStatus(t);const n=this._getCurrentUserId(),{inviter:s}=gi.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=oi;this._validateInviteId(t,e),this._validateProcessStatus(t);const n=this._getCurrentUserId(),{inviteeList:s}=gi.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=ri;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 vi=new class{constructor(){this._actionProcessor=new Map([[Ws,this._onNewInvitationReceived.bind(this)],[Zs,this._onInviteeRejected.bind(this)],[Js,this._onInviteeAccepted.bind(this)],[zs,this._onInvitationCancelled.bind(this)],[Xs,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=ui(e);if(t){const n=this._actionProcessor.get(t.actionType);null==n||n(t,e)}}))}_handleMessageReceived(e){if(!gi.getSignalingListenStatus())return;const t=di(e.data);0!==t.length&&this.handleActionSignaling(t)}_handleMessageModified(e){if(!gi.getSignalingListenStatus())return;const t=di(e.data);t.length>0&&t.forEach((e=>{const t=ui(e);t&&this._onInvitationModified(t,e)}))}_onNewInvitationReceived(e,t){var n,s;const i=`${ai}._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=gi.getSignaling(o);u!==e&&(u||gi.saveSignaling(o,Object.assign(Object.assign({},e),{signaling:t})),l>0&&(null===(n=this._core)||void 0===n||n.helper.taskScheduler.addOnceTask({id:`${li}-${o}`,intervalMs:1e3*l,callback:mi.handleInvitationExpiryTimer.bind(mi,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=`${ai}._onInviteeRejected`,{inviteID:s,inviter:i,groupID:o,inviteeList:r}=e,a=gi.hasSignaling(s);console.log(`${n} inviteID:${s} hasInviteID:${a} inviter:${i} groupID:${o}`),a&&(gi.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=`${ai}._onInviteeAccepted`,{inviteID:s,inviter:i,groupID:o,inviteeList:r}=e,a=gi.hasSignaling(s);console.log(`${n} inviteID:${s} hasInviteID:${a} inviter:${i} groupID:${o}`),a&&(gi.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=`${ai}._onInvitationCancelled`,{inviteID:s,inviter:i,groupID:o}=e,r=gi.hasSignaling(s);console.log(`${n} inviteID:${s} hasInviteID:${r} inviter:${i} groupID:${o}`),r&&(gi.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=`${ai}._onInvitationTimeout`,{inviteID:s,inviteeList:i}=e,o=gi.hasSignaling(s);console.log(`${n} inviteID:${s} hasInviteID:${o} data:${e.data}`),o&&(gi.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=`${ai}._onInvitationModified`,{inviteID:i,data:o}=e,r=gi.hasSignaling(i);console.log(`${s} inviteID:${i} data:${o}`),r&&(gi.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 pi=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)&&gi.getSignalingListenStatus()))return;const t=di([...e.unreadMessageMap.values()]);if(0!==t.length&&(t.forEach((e=>{this._handleC2CActionType(e)})),this._offlineSignalingMap.size>0)){const e=this._sortOfflineSignalingByTime();vi.handleActionSignaling(e)}}_handleC2CActionType(e){const t=ui(e);if(!t)return;const{actionType:n}=t;n===Ws?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 Si={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}}},Ii={invite:!0,cancel:!0,accept:!0,reject:!0,modifyInvitation:!0};var Ei=new class{install(e){mi.init(e),vi.init(e),fi.init(e),gi.init(e),pi.init(e),e.helper.registerValidateConfig({auth:Ii,params:Si})}};const yi=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.*"]),Ci="tui_room_svr.*";var Mi=new class{constructor(){this._transferredCommands=yi}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 a(this,void 0,void 0,(function*(){const t="transferBusinessCommand";try{const{serviceCommand:n=Ci}=e||{};if(!this._isValidTransferredCommand(n))throw new this._core.helper.ChatError({code:2995,functionName:t});const s=yield function(e,t){return a(this,void 0,void 0,(function*(){const{helper:n,channel:s}=t,{serviceCommand:i=Ci,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,message:null==e?void 0:e.errorInfo,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=yi}_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 Oi=new Map,Ti=[ks,function(e){Ds.install(e),Rs.install(e),Ls.install(e)},Gs,Hs,Mi,Ei];console.log(`TencentCloudLiteChat.VERSION:${It}`);var Di={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),Oi.has(i))return Oi.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()}`}();pt.init({sdkAppId:i,instanceId:o,testEnv:n,devMode:s}),pt.message=new Xn,pt.user=new Es,pt.login=new vn,Kt.installBuiltInPlugin(Ti);const r=Ht;return Oi.set(i,r),r},TSignaling:Ot,EVENT:yt,VERSION:It,TYPES:Lt};e.default=Di,e.liteChatInstanceMap=Oi,Object.defineProperty(e,"__esModule",{value:!0})}));
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).LiteChat={})}(this,(function(e){"use strict";class t{constructor(){this.listeners={}}on(e,t,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 n;!function(e){e.BUSINESS_COMMAND="business_command",e.C2C_REALTIME_MESSAGE="C2cMsgArray",e.C2C_MODIFIED_MESSAGE="C2cMsgModNotifys",e.USER_STATUS_UPDATE="UserStatusList",e.FRIEND_LIST_MODIFIED="FriendListMod",e.PROFILE_MODIFIED="ProfileDataMod",e.GROUP_REALTIME_MESSAGE="GroupMsgArray",e.GROUP_MODIFIED_MESSAGE="GroupMsgModNotifys",e.C2C_NOTIFY_MESSAGE="C2cNotifyMsgArray",e.GROUP_NOTIFY_MESSAGE="GroupTips",e.CONV_MODIFIED="RecentContactMod"}(n||(n={}));const s=[{type:"event",value:100,subType:n.BUSINESS_COMMAND},{type:"hasKey",value:"C2cMsgArray",subType:n.C2C_REALTIME_MESSAGE},{type:"hasKey",value:"C2cMsgModNotifys",subType:n.C2C_MODIFIED_MESSAGE},{type:"hasKey",value:"ProfileDataMod",subType:n.PROFILE_MODIFIED},{type:"hasKey",value:"UserStatusList",subType:n.USER_STATUS_UPDATE},{type:"hasKey",value:"FriendListMod",subType:n.FRIEND_LIST_MODIFIED},{type:"hasKey",value:"GroupMsgArray",subType:n.GROUP_REALTIME_MESSAGE},{type:"hasKey",value:"GroupMsgModNotifys",subType:n.GROUP_MODIFIED_MESSAGE},{type:"hasKey",value:"C2cNotifyMsgArray",subType:n.C2C_NOTIFY_MESSAGE},{type:"hasKey",value:"GroupTips",subType:n.GROUP_NOTIFY_MESSAGE},{type:"hasKey",value:"RecentContactMod",subType:n.CONV_MODIFIED}];var i;!function(e){e.SERVER_PUSH_MESSAGE="im_open_push.msg_push",e.ERROR="error"}(i||(i={}));const o={[i.SERVER_PUSH_MESSAGE]:function(e){const{EventArray:t}=(null==e?void 0:e.body)||{};return t.map((e=>{const{Event:t}=e,n=s.find((e=>"event"===e.type&&e.value===t));if(n)return{type:`${i.SERVER_PUSH_MESSAGE}:${n.subType}`,data:e};const o=s.find((t=>"hasKey"===t.type&&Object.prototype.hasOwnProperty.call(e,t.value)));return o?{type:`${i.SERVER_PUSH_MESSAGE}:${o.subType}`,data:e}:void 0}))},[i.ERROR]:function(e){const{errorCode:t}=e;return[{type:`error:${t}`,data:e}]}};const r=new class{constructor(){this._outerEventEmitter=null,this._innerEventEmitter=null,this._outerEventEmitter=new t,this._innerEventEmitter=new t,this.InnerEventSubType=n}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(o).includes(e)){const n=null===(s=o[e])||void 0===s?void 0:s.call(o,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 a(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 c=e=>{if("string"!=typeof e)return!1;const t=e[0];return!/[^a-zA-Z0-9]/.test(t)},l=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 d(e=99999999){return Math.round(Math.random()*e)}function u(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 h={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},_=["heartbeat.alive","im_open_status.wslogin","im_open_status.wslogout","group_open_long_polling_http_svc.get_msg","group_open_long_polling_http_noauth_svc.get_msg"];var g=Object.freeze({__proto__:null,ENUM_PLATFORM:h,NOT_NEED_CRC_SERVCMD:_});const f="undefined"!=typeof wx&&"function"==typeof wx.getSystemInfoSync&&Boolean(wx.getSystemInfoSync().fontSizeSetting),m=f&&"function"==typeof wx.createGamePortal,v="undefined"!=typeof qq&&"function"==typeof qq.getSystemInfoSync&&Boolean(qq.getSystemInfoSync().fontSizeSetting),p="undefined"!=typeof tt&&"function"==typeof tt.getSystemInfoSync&&Boolean(tt.getSystemInfoSync().fontSizeSetting),S="undefined"!=typeof swan&&"function"==typeof swan.getSystemInfoSync&&Boolean(swan.getSystemInfoSync().fontSizeSetting),E="undefined"!=typeof my&&"function"==typeof my.getSystemInfoSync&&Boolean(my.getSystemInfoSync().fontSizeSetting),I="undefined"!=typeof jd&&"function"==typeof jd.getSystemInfoSync,y="undefined"!=typeof uni&&"undefined"==typeof window&&"function"==typeof uni.requireNativePlugin,C=f&&"object"==typeof wx.miniapp,M="undefined"!=typeof uni,O=f||v||p||S||E||y||I,T="undefined"==typeof window&&!O&&"undefined"!=typeof global&&void 0!==global.NativeScriptGlobals,b="undefined"!=typeof global&&(void 0!==global.nativeModuleProxy||void 0!==global.ReactNative),D="undefined"!=typeof uni?!O:"undefined"!=typeof window&&!O&&!b,A=v?qq:p?tt:S?swan:E?my:f?wx:y?uni:I?jd:{},w=D&&window&&window.navigator&&window.navigator.userAgent||"",R=/(micromessenger|webbrowser)/i.test(w),N=function(){let e="WEB";return R?e="WEB":v?e="QQ_MP":p?e="TT_MP":S?e="BAIDU_MP":E?e="ALI_MP":f?e=C?"DONUT_NATIVE_APP":"WX_MP":y?e="UNI_NATIVE_APP":T?e="NS_NATIVE_APP":b&&(e="RN_NATIVE_APP"),h[e]}(),L=/iPad/i.test(w),k=/iPhone/i.test(w)&&!L,P=/iPod/i.test(w),U=k||L||P,F=function(){const e=w.match(/OS (\d+)_/i);return e&&e[1]?e[1]:null}(),G=/Android/i.test(w),B=function(){const e=w.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}(),x=/Firefox/i.test(w),$=/Edge/i.test(w),q=!$&&/Chrome/i.test(w),j=/MSIE/.test(w)||w.indexOf("Trident")>-1&&w.indexOf("rv:11.0")>-1,V=function(){const e=/MSIE\s(\d+)\.\d/.exec(w);let t=e&&parseFloat(e[1]);return!t&&/Trident\/7.0/i.test(w)&&/rv:11.0/.test(w)&&(t=11),t}(),K=/Safari/i.test(w)&&!q&&!G&&!$,Y=/Windows/i.test(w),H=/MAC OS X/i.test(w),W=D&&"undefined"!=typeof Worker&&!j,z=G||U,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!(!U||e||K)}();function X(){let e="unknown";if(H&&(e="mac"),Y&&(e="windows"),U&&(e="ios"),G&&(e="android"),O)try{const{platform:t}=wx.getSystemInfoSync();void 0!==t&&(e=t)}catch(e){console.error(e)}return e}const Q=2800,ee=2801,te=3e3,ne="application/x-www-form-urlencoded;charset=UTF-8";function se(e){return a(this,arguments,void 0,(function*({method:e,url:t,data:n,timeout:s=te}){return new Promise(O?(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":${ee}}`))}),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(l(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:B,IE_VERSION:V,IN_ALIPAY_MINI_APP:E,IN_BAIDU_MINI_APP:S,IN_BROWSER:D,IN_DONUT_NATIVE_APP:C,IN_JD_MINI_APP:I,IN_MINI_APP:O,IN_NS_NATIVE_APP:T,IN_QQ_MINI_APP:v,IN_RN_APP:b,IN_TT_MINI_APP:p,IN_UNI_APP:M,IN_UNI_NATIVE_APP:y,IN_WX_MINI_APP:f,IN_WX_MINI_GAME:m,IOS_VERSION:F,IS_ANDROID:G,IS_CHROME:q,IS_EDGE:$,IS_FIREFOX:x,IS_IE:j,IS_IOS:U,IS_IPAD:L,IS_IPHONE:k,IS_IPOD:P,IS_MAC:H,IS_SAFARI:K,IS_WECHAT:R,IS_WIN:Y,IS_WORKER_AVAILABLE:W,MINI_APP_NAMESPACE:A,USER_AGENT:w,base16EncodeBinaryString:u,generatePromise:oe,getPlatformType:X,httpRequest:se,isEmpty:ie,isFlutterWeb:J,isH5:z,isIOSWebView:Z,isPlainObject:l,isValidRequestKey:c,platform:N,randomInt:d});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(e){this._url="",this._readyState=re.DISCONNECTED,this._url=e,this._id=d(),this._emitter=new t,this._socket=f?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",{socketId:this._id,error:e})}_onSendFail(e){this._readyState=re.DISCONNECTED,this._emitter.emit("sendFail",{socketId:this._id,error: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",fe="IND",me="JPN",ve="USA",pe="INDONESIA",Se={TEST:{CHINA:{DEFAULT:"wss://wss-dev.tim.qq.com"},OVERSEA:{DEFAULT:"wss://wss-dev.tim.qq.com"},SINGAPORE:{DEFAULT:"wss://wsssgp-dev.im.qcloud.com"},KOREA:{DEFAULT:"wss://wsskr-dev.im.qcloud.com"},GERMANY:{DEFAULT:"wss://wssger-dev.im.qcloud.com"},IND:{DEFAULT:"wss://wssind-dev.im.qcloud.com"},JPN:{DEFAULT:"wss://wssjpn-dev.im.qcloud.com"},USA:{DEFAULT:"wss://wssusa-dev.im.qcloud.com"},INDONESIA:{DEFAULT:"wss://wssidn-dev.im.qcloud.com"}},PRODUCTION:{CHINA:{INITIAL:"wss://*w4c.my-imcloud.com",DEFAULT:"wss://wss.im.qcloud.com",BACKUP:"wss://wss.tim.qq.com",STAT:"https://events.im.qcloud.com",ANYCAST:"wss://162.14.13.203"},OVERSEA:{INITIAL:"wss://*w4c.my-imcloud.com",DEFAULT:"wss://wss.im.qcloud.com",BACKUP:"wss://wss.my-imcloud.com",STAT:"https://api.my-imcloud.com"},SINGAPORE:{INITIAL:"wss://*w4s.my-imcloud.com",DEFAULT:"wss://wsssgp.im.qcloud.com",BACKUP:"wss://wsssgp.my-imcloud.com",STAT:"https://apisgp.my-imcloud.com",ANYCAST:"wss://162.14.19.159"},KOREA:{INITIAL:"wss://*w4k.my-imcloud.com",DEFAULT:"wss://wsskr.im.qcloud.com",BACKUP:"wss://wsskr.my-imcloud.com",STAT:"https://apikr.my-imcloud.com",ANYCAST:"wss://162.14.13.104"},GERMANY:{INITIAL:"wss://*w4g.my-imcloud.com",DEFAULT:"wss://wssger.im.qcloud.com",BACKUP:"wss://wssger.my-imcloud.com",STAT:"https://apiger.my-imcloud.com",ANYCAST:"wss://162.14.3.17"},IND:{INITIAL:"wss://*w4i.my-imcloud.com",DEFAULT:"wss://wssind.my-imcloud.com",BACKUP:"wss://wssind.im.qcloud.com",STAT:"https://apiind.my-imcloud.com",ANYCAST:"wss://162.14.18.188"},JPN:{INITIAL:"wss://*w4j.my-imcloud.com",DEFAULT:"wss://wssjpn.im.qcloud.com",BACKUP:"wss://wssjpn.my-imcloud.com",STAT:"https://apijpn.my-imcloud.com"},USA:{INITIAL:"wss://*w4u.my-imcloud.com",DEFAULT:"wss://wssusa.im.qcloud.com",BACKUP:"wss://wssusa.my-imcloud.com",STAT:"https://apiusa.my-imcloud.com",ANYCAST:"wss://162.14.10.42"},INDONESIA:{INITIAL:"wss://*w4y.my-imcloud.com",DEFAULT:"wss://wssidn.im.qcloud.com",BACKUP:"wss://wssidn.my-imcloud.com",STAT:"https://apiidn.my-imcloud.com",ANYCAST:"wss://43.129.34.169"}}},Ee={[he]:[[2e7,3e7],[172e7,173e7]],[_e]:[[3e7,4e7],[173e7,174e7]],[ge]:[[4e7,5e7],[174e7,175e7]],[fe]:[[5e7,6e7],[175e7,176e7]],[me]:[[6e7,7e7],[176e7,177e7]],[ve]:[[7e7,8e7],[177e7,178e7]],[pe]:[[8e7,9e7],[178e7,179e7]]};function Ie(e){for(const t of Object.keys(Ee))for(const[n,s]of Ee[t])if(e>=n&&e<s)return t;return ue}var ye,Ce=new class{constructor(){this._store=new Map}get(e){return this._store.get(e)}getStorage(e){if(O){if(E){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){O?E?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)}},Me="1.0.0";!function(e){e.INITIAL="INITIAL",e.DEFAULT="DEFAULT",e.BACKUP="BACKUP",e.ANYCAST="ANYCAST"}(ye||(ye={}));let Oe=ye.INITIAL;function Te(){const e=Math.random();return 0===e?Te():e}function be(e,t){const{isBinary:n=!1}=t||{},s=Ce.get("instance"),{sdkAppId:i,instanceId:o}=s,r=Te(),a=X(),c=function(){const e=X();let t=-1;"ios"===e?t=F||-1:"android"===e&&(t=B||-1);return t}(),l=(d={sdkappid:i,instanceid:o,random:r,platform:N,host:a,version:c,sdkversion:Me},Object.keys(d).map((e=>`${e}=${d[e]}`)).join("&"));var d;return n?`${e}/binfo?${l}&compress=gzip`:`${e}/info?${l}`}var De=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 Ae=16;var we=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=Ae}=e,r=Math.max(o,Ae);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 Re(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)}function Ne(e){const t=Array.isArray(e)?[]:Object.create(null);for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&c(n)&&null!=e[n]&&(null===e[n]||"object"!=typeof e[n]?t[n]=e[n]:t[n]=Ne(e[n]));return t}function Le(e,t){if(_.includes(e))return 0;const n=Re(JSON.stringify(t));let s=4294967295;const{length:i}=n;for(let e=0;e<i;e++){s^=n[e];for(let e=0;e<8;e++)1&~s?s>>>=1:s=s>>>1^3988292384}return(4294967295^s)>>>0}function ke(e){const{servcmd:t,data:n}=e,s=function(e){const t=Ce.get("login")||{},n=Ce.get("instance")||{};return{servcmd:e,ver:"v4",platform:N,websdkappid:537048168,websdkversion:"1.7.3",a2:t.a2Key||void 0,tinyid:t.tinyID||void 0,status_instid:t.statusInstanceId||0,sdkappid:n.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:t.a2Key?void 0:t.userId,usersig:t.a2Key?void 0:t.userSig,sdkability:75689843,sdkability_ext:u(""),cappid:t.cappid||0,tjgID:"",seq:Fe(),cs:0}}(t),i=Ne(n);return s.cs=Le(t,i),{head:s,body:i}}function Pe(e){const{servcmd:t,data:n}=e,s=function(e){const t=Ce.get("login")||{},n=Ce.get("instance")||{};return{servcmd:e,ver:"v4",platform:N,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:n.sdkAppId,contenttype:"",reqtime:Math.floor(Date.now()/1e3),identifier:"",usersig:"",status_instid:t.statusInstanceId||0,sdkability:75689843,sdkability_ext:u(""),cappid:t.cappid||0,seq:Fe(),cs:0}}(t),i=Ne(n);return s.cs=Le(t,i),{head:s,body:i}}let Ue=d();function Fe(){return Ue=Ue<2415919103?Ue+1:d(),Ue}var Ge,Be=Object.freeze({__proto__:null,generateCosSpecifiedData:function(e){const{servcmd:t,data:n}=e,s=function(e){const t=Ce.get("login")||{},n=Ce.get("instance")||{};return{servcmd:e,ver:"v4",platform:N,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:n.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:t.userId,usersig:t.userSig,status_instid:t.statusInstanceId||0,sdkability:75689843,sdkability_ext:u(""),cappid:t.cappid||0,seq:Fe(),cs:0}}(t),i=Ne(n);return s.cs=Le(t,i),{head:s,body:i}},generateProtocolData:ke,generateSSOLogProtocolData:Pe,generateSequence:Fe,taskScheduler:we,timeManager:De});!function(e){e[e.info=4]="info",e[e.warning=5]="warning",e[e.error=6]="error"}(Ge||(Ge={}));const xe={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 $e{constructor(e){this.level=Ge.info,this._canSendLog=!0,this._logCreatedAt=De.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+=De.getTimeOffsetWithServer()}end(e=!1){if(!this._canSendLog)return;const t=De.getServerTimeMs();0===this.costTime&&(this.costTime=t-this._logCreatedAt),this.setMoreMessage(`startts:${this._logCreatedAt} endts:${t}`),e?(this._canSendLog=!1,this.timestamp=De.getServerTimeMs(),this._ssoLogModule.pushToLogQueue(this._convertSSOLogDataKeyToServe())):setTimeout((()=>{this._canSendLog=!1,this.timestamp=De.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=Ce.get("netWorkMonitor"))||void 0===t?void 0:t.isNetworkOnline)&&(e.errorCode&&(this.code=e.errorCode),e.errorMessage&&this.setMoreMessage(e.errorMessage)),this.level=Ge.error,this}setLogInfo(e){return Object.keys(e).forEach((t=>{Object.keys(xe).includes(t)&&(this[t]=e[t])})),this}setSSOLogModule(e){this._ssoLogModule=e}_convertSSOLogDataKeyToServe(){const e={};return Object.keys(this).forEach((t=>{const n=t;xe[n]&&(e[xe[n]]=this[n])})),e}}function qe(){const e=Ce.get("login")||{},t=Ce.get("instance")||{};return{sdk_type:30,sdk_app_id:t.sdkAppId,sdk_version:Me,tiny_id:Number(e.tinyID),user_id:e.userId,platform:N,instance_id:t.instanceId,trace_id:(new Date).getTime()}}var je;!function(e){e.RECONNECTED="reconnected",e.CLOUD_CONFIG_UPDATE="cloud_config_update",e.SOCKET_DISCONNECTED="socket_disconnected"}(je||(je={}));var Ve=je;const Ke=20,Ye=6e4,He=[4,5,6],We=[],ze=[],Je="report-logger";var Ze=new class{constructor(){this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._reportLevel=[4,5,6],this._minThreshold=Ke,this._maxThreshold=100,this._waitingTime=Ye,this._lastReportAt=Date.now(),this._ssoLogMap=new Map,r.subscribeInnerEvent(Ve.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),we.addTask({id:Je,intervalMs:1e3,callback:this._checkAndReportIfDue,context:this}),this._logQueue=[],this._savePlatFormInfo()}_handleCloudConfigUpdate(e){const{evt_rpt_threshold:t=Ke,evt_rpt_waiting:n=Ye,evt_rpt_level:s=He,evt_rpt_sdkappid_bl:i=We,evt_rpt_tinyid_wl:o=ze}=e||{};this._sdkAppIdBlackList=i,this._waitingTime=n,this._minThreshold=t,this._reportLevel=s,this._tinyIdWhiteList=o}createSSOLogData(e){const t=new $e(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 a(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:qe(),Event:t};yield function(e){const t="imopenstat.tim_web_report_v2",n=Pe({servcmd:t,data:e}),s=`${n.head.seq}${t}`;pt.sendPacket(n,{requestId:s})}(n),this._lastReportAt=Date.now()}))}_savePlatFormInfo(){var e,t;if(f){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;Ce.set("instance",{appId:e,envVersion:t})}}else D&&Ce.set("instance",{href:window.location.href})}_filterLogs(e){const{tinyID:t}=Ce.get("login")||{},{sdkAppId:n}=Ce.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"),we.removeTask(Je),r.unSubscribeInnerEvent(Ve.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),this._lastReportAt=0,this._uploadSSOLogData(),this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._minThreshold=Ke,this._maxThreshold=100,this._waitingTime=Ye,this._logQueue=[]}};const Xe=15e3,Qe="Channel",et="channel_schedule_task",nt="channel_reconnect_task",st="connected",it="connecting",ot="disconnected",rt=500,at="network_status_change",ct="activity_status_change",lt="send_fail",dt="reconnect_failed",ut="socket_error",ht="socket_close";function _t(e){return _t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_t(e)}function gt(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var ft,mt={exports:{}};var vt=(ft||(ft=1,function(e){e.exports=function e(t,n,s){function i(r,a){if(!n[r]){if(!t[r]){if(!a&&gt)return gt(r);if(o)return o(r,!0);var c=new Error("Cannot find module '"+r+"'");throw c.code="MODULE_NOT_FOUND",c}var l=n[r]={exports:{}};t[r][0].call(l.exports,(function(e){return i(t[r][1][e]||e)}),l,l.exports,e,t,n,s)}return n[r].exports}for(var o=gt,r=0;r<s.length;r++)i(s[r]);return i}({1:[function(e,t,n){var s="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;n.assign=function(e){for(var t,n,s=Array.prototype.slice.call(arguments,1);s.length;){var i=s.shift();if(i){if("object"!=_t(i))throw new TypeError(i+"must be non-object");for(var o in i)t=i,n=o,Object.prototype.hasOwnProperty.call(t,n)&&(e[o]=i[o])}}return e},n.shrinkBuf=function(e,t){return e.length===t?e:e.subarray?e.subarray(0,t):(e.length=t,e)};var i={arraySet:function(e,t,n,s,i){if(t.subarray&&e.subarray)e.set(t.subarray(n,n+s),i);else for(var o=0;o<s;o++)e[i+o]=t[n+o]},flattenChunks:function(e){var t,n,s,i,o,r;for(t=s=0,n=e.length;t<n;t++)s+=e[t].length;for(r=new Uint8Array(s),t=i=0,n=e.length;t<n;t++)o=e[t],r.set(o,i),i+=o.length;return r}},o={arraySet:function(e,t,n,s,i){for(var o=0;o<s;o++)e[i+o]=t[n+o]},flattenChunks:function(e){return[].concat.apply([],e)}};n.setTyped=function(e){e?(n.Buf8=Uint8Array,n.Buf16=Uint16Array,n.Buf32=Int32Array,n.assign(n,i)):(n.Buf8=Array,n.Buf16=Array,n.Buf32=Array,n.assign(n,o))},n.setTyped(s)},{}],2:[function(e,t,n){var s=e("./common"),i=!0,o=!0;try{String.fromCharCode.apply(null,[0])}catch(e){i=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(e){o=!1}for(var r=new s.Buf8(256),a=0;a<256;a++)r[a]=252<=a?6:248<=a?5:240<=a?4:224<=a?3:192<=a?2:1;function c(e,t){if(t<65534&&(e.subarray&&o||!e.subarray&&i))return String.fromCharCode.apply(null,s.shrinkBuf(e,t));for(var n="",r=0;r<t;r++)n+=String.fromCharCode(e[r]);return n}r[254]=r[254]=1,n.string2buf=function(e){var t,n,i,o,r,a=e.length,c=0;for(o=0;o<a;o++)55296==(64512&(n=e.charCodeAt(o)))&&o+1<a&&56320==(64512&(i=e.charCodeAt(o+1)))&&(n=65536+(n-55296<<10)+(i-56320),o++),c+=n<128?1:n<2048?2:n<65536?3:4;for(t=new s.Buf8(c),o=r=0;r<c;o++)55296==(64512&(n=e.charCodeAt(o)))&&o+1<a&&56320==(64512&(i=e.charCodeAt(o+1)))&&(n=65536+(n-55296<<10)+(i-56320),o++),n<128?t[r++]=n:(n<2048?t[r++]=192|n>>>6:(n<65536?t[r++]=224|n>>>12:(t[r++]=240|n>>>18,t[r++]=128|n>>>12&63),t[r++]=128|n>>>6&63),t[r++]=128|63&n);return t},n.buf2binstring=function(e){return c(e,e.length)},n.binstring2buf=function(e){for(var t=new s.Buf8(e.length),n=0,i=t.length;n<i;n++)t[n]=e.charCodeAt(n);return t},n.buf2string=function(e,t){var n,s,i,o,a=t||e.length,l=new Array(2*a);for(n=s=0;n<a;)if((i=e[n++])<128)l[s++]=i;else if(4<(o=r[i]))l[s++]=65533,n+=o-1;else{for(i&=2===o?31:3===o?15:7;1<o&&n<a;)i=i<<6|63&e[n++],o--;1<o?l[s++]=65533:i<65536?l[s++]=i:(i-=65536,l[s++]=55296|i>>10&1023,l[s++]=56320|1023&i)}return c(l,s)},n.utf8border=function(e,t){var n;for((t=t||e.length)>e.length&&(t=e.length),n=t-1;0<=n&&128==(192&e[n]);)n--;return n<0||0===n?t:n+r[e[n]]>t?n:t}},{"./common":1}],3:[function(e,t,n){t.exports=function(e,t,n,s){for(var i=65535&e,o=e>>>16&65535,r=0;0!==n;){for(n-=r=2e3<n?2e3:n;o=o+(i=i+t[s++]|0)|0,--r;);i%=65521,o%=65521}return i|o<<16}},{}],4:[function(e,t,n){t.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],5:[function(e,t,n){var s=function(){for(var e,t=[],n=0;n<256;n++){e=n;for(var s=0;s<8;s++)e=1&e?3988292384^e>>>1:e>>>1;t[n]=e}return t}();t.exports=function(e,t,n,i){var o=s,r=i+n;e^=-1;for(var a=i;a<r;a++)e=e>>>8^o[255&(e^t[a])];return~e}},{}],6:[function(e,t,n){t.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],7:[function(e,t,n){t.exports=function(e,t){var n,s,i,o,r,a,c,l,d,u,h,_,g,f,m,v,p,S,E,I,y,C,M,O,T;n=e.state,s=e.next_in,O=e.input,i=s+(e.avail_in-5),o=e.next_out,T=e.output,r=o-(t-e.avail_out),a=o+(e.avail_out-257),c=n.dmax,l=n.wsize,d=n.whave,u=n.wnext,h=n.window,_=n.hold,g=n.bits,f=n.lencode,m=n.distcode,v=(1<<n.lenbits)-1,p=(1<<n.distbits)-1;e:do{g<15&&(_+=O[s++]<<g,g+=8,_+=O[s++]<<g,g+=8),S=f[_&v];t:for(;;){if(_>>>=E=S>>>24,g-=E,0==(E=S>>>16&255))T[o++]=65535&S;else{if(!(16&E)){if(!(64&E)){S=f[(65535&S)+(_&(1<<E)-1)];continue t}if(32&E){n.mode=12;break e}e.msg="invalid literal/length code",n.mode=30;break e}I=65535&S,(E&=15)&&(g<E&&(_+=O[s++]<<g,g+=8),I+=_&(1<<E)-1,_>>>=E,g-=E),g<15&&(_+=O[s++]<<g,g+=8,_+=O[s++]<<g,g+=8),S=m[_&p];n:for(;;){if(_>>>=E=S>>>24,g-=E,!(16&(E=S>>>16&255))){if(!(64&E)){S=m[(65535&S)+(_&(1<<E)-1)];continue n}e.msg="invalid distance code",n.mode=30;break e}if(y=65535&S,g<(E&=15)&&(_+=O[s++]<<g,(g+=8)<E&&(_+=O[s++]<<g,g+=8)),c<(y+=_&(1<<E)-1)){e.msg="invalid distance too far back",n.mode=30;break e}if(_>>>=E,g-=E,(E=o-r)<y){if(d<(E=y-E)&&n.sane){e.msg="invalid distance too far back",n.mode=30;break e}if(M=h,(C=0)===u){if(C+=l-E,E<I){for(I-=E;T[o++]=h[C++],--E;);C=o-y,M=T}}else if(u<E){if(C+=l+u-E,(E-=u)<I){for(I-=E;T[o++]=h[C++],--E;);if(C=0,u<I){for(I-=E=u;T[o++]=h[C++],--E;);C=o-y,M=T}}}else if(C+=u-E,E<I){for(I-=E;T[o++]=h[C++],--E;);C=o-y,M=T}for(;2<I;)T[o++]=M[C++],T[o++]=M[C++],T[o++]=M[C++],I-=3;I&&(T[o++]=M[C++],1<I&&(T[o++]=M[C++]))}else{for(C=o-y;T[o++]=T[C++],T[o++]=T[C++],T[o++]=T[C++],2<(I-=3););I&&(T[o++]=T[C++],1<I&&(T[o++]=T[C++]))}break}}break}}while(s<i&&o<a);s-=I=g>>3,_&=(1<<(g-=I<<3))-1,e.next_in=s,e.next_out=o,e.avail_in=s<i?i-s+5:5-(s-i),e.avail_out=o<a?a-o+257:257-(o-a),n.hold=_,n.bits=g}},{}],8:[function(e,t,n){var s=e("../utils/common"),i=e("./adler32"),o=e("./crc32"),r=e("./inffast"),a=e("./inftrees"),c=1,l=2,d=0,u=-2,h=1,_=852,g=592;function f(e){return(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)}function m(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new s.Buf16(320),this.work=new s.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function v(e){var t;return e&&e.state?(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=h,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new s.Buf32(_),t.distcode=t.distdyn=new s.Buf32(g),t.sane=1,t.back=-1,d):u}function p(e){var t;return e&&e.state?((t=e.state).wsize=0,t.whave=0,t.wnext=0,v(e)):u}function S(e,t){var n,s;return e&&e.state?(s=e.state,t<0?(n=0,t=-t):(n=1+(t>>4),t<48&&(t&=15)),t&&(t<8||15<t)?u:(null!==s.window&&s.wbits!==t&&(s.window=null),s.wrap=n,s.wbits=t,p(e))):u}function E(e,t){var n,s;return e?(s=new m,(e.state=s).window=null,(n=S(e,t))!==d&&(e.state=null),n):u}var I,y,C=!0;function M(e){if(C){var t;for(I=new s.Buf32(512),y=new s.Buf32(32),t=0;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(a(c,e.lens,0,288,I,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;a(l,e.lens,0,32,y,0,e.work,{bits:5}),C=!1}e.lencode=I,e.lenbits=9,e.distcode=y,e.distbits=5}function O(e,t,n,i){var o,r=e.state;return null===r.window&&(r.wsize=1<<r.wbits,r.wnext=0,r.whave=0,r.window=new s.Buf8(r.wsize)),i>=r.wsize?(s.arraySet(r.window,t,n-r.wsize,r.wsize,0),r.wnext=0,r.whave=r.wsize):(i<(o=r.wsize-r.wnext)&&(o=i),s.arraySet(r.window,t,n-i,o,r.wnext),(i-=o)?(s.arraySet(r.window,t,n-i,i,0),r.wnext=i,r.whave=r.wsize):(r.wnext+=o,r.wnext===r.wsize&&(r.wnext=0),r.whave<r.wsize&&(r.whave+=o))),0}n.inflateReset=p,n.inflateReset2=S,n.inflateResetKeep=v,n.inflateInit=function(e){return E(e,15)},n.inflateInit2=E,n.inflate=function(e,t){var n,_,g,m,v,p,S,E,I,y,C,T,b,D,A,w,R,N,L,k,P,U,F,G,B=0,x=new s.Buf8(4),$=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!e||!e.state||!e.output||!e.input&&0!==e.avail_in)return u;12===(n=e.state).mode&&(n.mode=13),v=e.next_out,g=e.output,S=e.avail_out,m=e.next_in,_=e.input,p=e.avail_in,E=n.hold,I=n.bits,y=p,C=S,U=d;e:for(;;)switch(n.mode){case h:if(0===n.wrap){n.mode=13;break}for(;I<16;){if(0===p)break e;p--,E+=_[m++]<<I,I+=8}if(2&n.wrap&&35615===E){x[n.check=0]=255&E,x[1]=E>>>8&255,n.check=o(n.check,x,2,0),I=E=0,n.mode=2;break}if(n.flags=0,n.head&&(n.head.done=!1),!(1&n.wrap)||(((255&E)<<8)+(E>>8))%31){e.msg="incorrect header check",n.mode=30;break}if(8!=(15&E)){e.msg="unknown compression method",n.mode=30;break}if(I-=4,P=8+(15&(E>>>=4)),0===n.wbits)n.wbits=P;else if(P>n.wbits){e.msg="invalid window size",n.mode=30;break}n.dmax=1<<P,e.adler=n.check=1,n.mode=512&E?10:12,I=E=0;break;case 2:for(;I<16;){if(0===p)break e;p--,E+=_[m++]<<I,I+=8}if(n.flags=E,8!=(255&n.flags)){e.msg="unknown compression method",n.mode=30;break}if(57344&n.flags){e.msg="unknown header flags set",n.mode=30;break}n.head&&(n.head.text=E>>8&1),512&n.flags&&(x[0]=255&E,x[1]=E>>>8&255,n.check=o(n.check,x,2,0)),I=E=0,n.mode=3;case 3:for(;I<32;){if(0===p)break e;p--,E+=_[m++]<<I,I+=8}n.head&&(n.head.time=E),512&n.flags&&(x[0]=255&E,x[1]=E>>>8&255,x[2]=E>>>16&255,x[3]=E>>>24&255,n.check=o(n.check,x,4,0)),I=E=0,n.mode=4;case 4:for(;I<16;){if(0===p)break e;p--,E+=_[m++]<<I,I+=8}n.head&&(n.head.xflags=255&E,n.head.os=E>>8),512&n.flags&&(x[0]=255&E,x[1]=E>>>8&255,n.check=o(n.check,x,2,0)),I=E=0,n.mode=5;case 5:if(1024&n.flags){for(;I<16;){if(0===p)break e;p--,E+=_[m++]<<I,I+=8}n.length=E,n.head&&(n.head.extra_len=E),512&n.flags&&(x[0]=255&E,x[1]=E>>>8&255,n.check=o(n.check,x,2,0)),I=E=0}else n.head&&(n.head.extra=null);n.mode=6;case 6:if(1024&n.flags&&(p<(T=n.length)&&(T=p),T&&(n.head&&(P=n.head.extra_len-n.length,n.head.extra||(n.head.extra=new Array(n.head.extra_len)),s.arraySet(n.head.extra,_,m,T,P)),512&n.flags&&(n.check=o(n.check,_,T,m)),p-=T,m+=T,n.length-=T),n.length))break e;n.length=0,n.mode=7;case 7:if(2048&n.flags){if(0===p)break e;for(T=0;P=_[m+T++],n.head&&P&&n.length<65536&&(n.head.name+=String.fromCharCode(P)),P&&T<p;);if(512&n.flags&&(n.check=o(n.check,_,T,m)),p-=T,m+=T,P)break e}else n.head&&(n.head.name=null);n.length=0,n.mode=8;case 8:if(4096&n.flags){if(0===p)break e;for(T=0;P=_[m+T++],n.head&&P&&n.length<65536&&(n.head.comment+=String.fromCharCode(P)),P&&T<p;);if(512&n.flags&&(n.check=o(n.check,_,T,m)),p-=T,m+=T,P)break e}else n.head&&(n.head.comment=null);n.mode=9;case 9:if(512&n.flags){for(;I<16;){if(0===p)break e;p--,E+=_[m++]<<I,I+=8}if(E!==(65535&n.check)){e.msg="header crc mismatch",n.mode=30;break}I=E=0}n.head&&(n.head.hcrc=n.flags>>9&1,n.head.done=!0),e.adler=n.check=0,n.mode=12;break;case 10:for(;I<32;){if(0===p)break e;p--,E+=_[m++]<<I,I+=8}e.adler=n.check=f(E),I=E=0,n.mode=11;case 11:if(0===n.havedict)return e.next_out=v,e.avail_out=S,e.next_in=m,e.avail_in=p,n.hold=E,n.bits=I,2;e.adler=n.check=1,n.mode=12;case 12:if(5===t||6===t)break e;case 13:if(n.last){E>>>=7&I,I-=7&I,n.mode=27;break}for(;I<3;){if(0===p)break e;p--,E+=_[m++]<<I,I+=8}switch(n.last=1&E,I-=1,3&(E>>>=1)){case 0:n.mode=14;break;case 1:if(M(n),n.mode=20,6!==t)break;E>>>=2,I-=2;break e;case 2:n.mode=17;break;case 3:e.msg="invalid block type",n.mode=30}E>>>=2,I-=2;break;case 14:for(E>>>=7&I,I-=7&I;I<32;){if(0===p)break e;p--,E+=_[m++]<<I,I+=8}if((65535&E)!=(E>>>16^65535)){e.msg="invalid stored block lengths",n.mode=30;break}if(n.length=65535&E,I=E=0,n.mode=15,6===t)break e;case 15:n.mode=16;case 16:if(T=n.length){if(p<T&&(T=p),S<T&&(T=S),0===T)break e;s.arraySet(g,_,m,T,v),p-=T,m+=T,S-=T,v+=T,n.length-=T;break}n.mode=12;break;case 17:for(;I<14;){if(0===p)break e;p--,E+=_[m++]<<I,I+=8}if(n.nlen=257+(31&E),E>>>=5,I-=5,n.ndist=1+(31&E),E>>>=5,I-=5,n.ncode=4+(15&E),E>>>=4,I-=4,286<n.nlen||30<n.ndist){e.msg="too many length or distance symbols",n.mode=30;break}n.have=0,n.mode=18;case 18:for(;n.have<n.ncode;){for(;I<3;){if(0===p)break e;p--,E+=_[m++]<<I,I+=8}n.lens[$[n.have++]]=7&E,E>>>=3,I-=3}for(;n.have<19;)n.lens[$[n.have++]]=0;if(n.lencode=n.lendyn,n.lenbits=7,F={bits:n.lenbits},U=a(0,n.lens,0,19,n.lencode,0,n.work,F),n.lenbits=F.bits,U){e.msg="invalid code lengths set",n.mode=30;break}n.have=0,n.mode=19;case 19:for(;n.have<n.nlen+n.ndist;){for(;w=(B=n.lencode[E&(1<<n.lenbits)-1])>>>16&255,R=65535&B,!((A=B>>>24)<=I);){if(0===p)break e;p--,E+=_[m++]<<I,I+=8}if(R<16)E>>>=A,I-=A,n.lens[n.have++]=R;else{if(16===R){for(G=A+2;I<G;){if(0===p)break e;p--,E+=_[m++]<<I,I+=8}if(E>>>=A,I-=A,0===n.have){e.msg="invalid bit length repeat",n.mode=30;break}P=n.lens[n.have-1],T=3+(3&E),E>>>=2,I-=2}else if(17===R){for(G=A+3;I<G;){if(0===p)break e;p--,E+=_[m++]<<I,I+=8}I-=A,P=0,T=3+(7&(E>>>=A)),E>>>=3,I-=3}else{for(G=A+7;I<G;){if(0===p)break e;p--,E+=_[m++]<<I,I+=8}I-=A,P=0,T=11+(127&(E>>>=A)),E>>>=7,I-=7}if(n.have+T>n.nlen+n.ndist){e.msg="invalid bit length repeat",n.mode=30;break}for(;T--;)n.lens[n.have++]=P}}if(30===n.mode)break;if(0===n.lens[256]){e.msg="invalid code -- missing end-of-block",n.mode=30;break}if(n.lenbits=9,F={bits:n.lenbits},U=a(c,n.lens,0,n.nlen,n.lencode,0,n.work,F),n.lenbits=F.bits,U){e.msg="invalid literal/lengths set",n.mode=30;break}if(n.distbits=6,n.distcode=n.distdyn,F={bits:n.distbits},U=a(l,n.lens,n.nlen,n.ndist,n.distcode,0,n.work,F),n.distbits=F.bits,U){e.msg="invalid distances set",n.mode=30;break}if(n.mode=20,6===t)break e;case 20:n.mode=21;case 21:if(6<=p&&258<=S){e.next_out=v,e.avail_out=S,e.next_in=m,e.avail_in=p,n.hold=E,n.bits=I,r(e,C),v=e.next_out,g=e.output,S=e.avail_out,m=e.next_in,_=e.input,p=e.avail_in,E=n.hold,I=n.bits,12===n.mode&&(n.back=-1);break}for(n.back=0;w=(B=n.lencode[E&(1<<n.lenbits)-1])>>>16&255,R=65535&B,!((A=B>>>24)<=I);){if(0===p)break e;p--,E+=_[m++]<<I,I+=8}if(w&&!(240&w)){for(N=A,L=w,k=R;w=(B=n.lencode[k+((E&(1<<N+L)-1)>>N)])>>>16&255,R=65535&B,!(N+(A=B>>>24)<=I);){if(0===p)break e;p--,E+=_[m++]<<I,I+=8}E>>>=N,I-=N,n.back+=N}if(E>>>=A,I-=A,n.back+=A,n.length=R,0===w){n.mode=26;break}if(32&w){n.back=-1,n.mode=12;break}if(64&w){e.msg="invalid literal/length code",n.mode=30;break}n.extra=15&w,n.mode=22;case 22:if(n.extra){for(G=n.extra;I<G;){if(0===p)break e;p--,E+=_[m++]<<I,I+=8}n.length+=E&(1<<n.extra)-1,E>>>=n.extra,I-=n.extra,n.back+=n.extra}n.was=n.length,n.mode=23;case 23:for(;w=(B=n.distcode[E&(1<<n.distbits)-1])>>>16&255,R=65535&B,!((A=B>>>24)<=I);){if(0===p)break e;p--,E+=_[m++]<<I,I+=8}if(!(240&w)){for(N=A,L=w,k=R;w=(B=n.distcode[k+((E&(1<<N+L)-1)>>N)])>>>16&255,R=65535&B,!(N+(A=B>>>24)<=I);){if(0===p)break e;p--,E+=_[m++]<<I,I+=8}E>>>=N,I-=N,n.back+=N}if(E>>>=A,I-=A,n.back+=A,64&w){e.msg="invalid distance code",n.mode=30;break}n.offset=R,n.extra=15&w,n.mode=24;case 24:if(n.extra){for(G=n.extra;I<G;){if(0===p)break e;p--,E+=_[m++]<<I,I+=8}n.offset+=E&(1<<n.extra)-1,E>>>=n.extra,I-=n.extra,n.back+=n.extra}if(n.offset>n.dmax){e.msg="invalid distance too far back",n.mode=30;break}n.mode=25;case 25:if(0===S)break e;if(T=C-S,n.offset>T){if((T=n.offset-T)>n.whave&&n.sane){e.msg="invalid distance too far back",n.mode=30;break}T>n.wnext?(T-=n.wnext,b=n.wsize-T):b=n.wnext-T,T>n.length&&(T=n.length),D=n.window}else D=g,b=v-n.offset,T=n.length;for(S<T&&(T=S),S-=T,n.length-=T;g[v++]=D[b++],--T;);0===n.length&&(n.mode=21);break;case 26:if(0===S)break e;g[v++]=n.length,S--,n.mode=21;break;case 27:if(n.wrap){for(;I<32;){if(0===p)break e;p--,E|=_[m++]<<I,I+=8}if(C-=S,e.total_out+=C,n.total+=C,C&&(e.adler=n.check=n.flags?o(n.check,g,C,v-C):i(n.check,g,C,v-C)),C=S,(n.flags?E:f(E))!==n.check){e.msg="incorrect data check",n.mode=30;break}I=E=0}n.mode=28;case 28:if(n.wrap&&n.flags){for(;I<32;){if(0===p)break e;p--,E+=_[m++]<<I,I+=8}if(E!==(4294967295&n.total)){e.msg="incorrect length check",n.mode=30;break}I=E=0}n.mode=29;case 29:U=1;break e;case 30:U=-3;break e;case 31:return-4;default:return u}return e.next_out=v,e.avail_out=S,e.next_in=m,e.avail_in=p,n.hold=E,n.bits=I,(n.wsize||C!==e.avail_out&&n.mode<30&&(n.mode<27||4!==t))&&O(e,e.output,e.next_out,C-e.avail_out)?(n.mode=31,-4):(y-=e.avail_in,C-=e.avail_out,e.total_in+=y,e.total_out+=C,n.total+=C,n.wrap&&C&&(e.adler=n.check=n.flags?o(n.check,g,C,e.next_out-C):i(n.check,g,C,e.next_out-C)),e.data_type=n.bits+(n.last?64:0)+(12===n.mode?128:0)+(20===n.mode||15===n.mode?256:0),(0===y&&0===C||4===t)&&U===d&&(U=-5),U)},n.inflateEnd=function(e){if(!e||!e.state)return u;var t=e.state;return t.window&&(t.window=null),e.state=null,d},n.inflateGetHeader=function(e,t){var n;return e&&e.state&&2&(n=e.state).wrap?((n.head=t).done=!1,d):u},n.inflateSetDictionary=function(e,t){var n,s=t.length;return e&&e.state?0!==(n=e.state).wrap&&11!==n.mode?u:11===n.mode&&i(1,t,s,0)!==n.check?-3:O(e,t,s,s)?(n.mode=31,-4):(n.havedict=1,d):u},n.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":1,"./adler32":3,"./crc32":5,"./inffast":7,"./inftrees":9}],9:[function(e,t,n){var s=e("../utils/common"),i=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],o=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],r=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],a=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];t.exports=function(e,t,n,c,l,d,u,h){var _,g,f,m,v,p,S,E,I,y=h.bits,C=0,M=0,O=0,T=0,b=0,D=0,A=0,w=0,R=0,N=0,L=null,k=0,P=new s.Buf16(16),U=new s.Buf16(16),F=null,G=0;for(C=0;C<=15;C++)P[C]=0;for(M=0;M<c;M++)P[t[n+M]]++;for(b=y,T=15;1<=T&&0===P[T];T--);if(T<b&&(b=T),0===T)return l[d++]=20971520,l[d++]=20971520,h.bits=1,0;for(O=1;O<T&&0===P[O];O++);for(b<O&&(b=O),C=w=1;C<=15;C++)if(w<<=1,(w-=P[C])<0)return-1;if(0<w&&(0===e||1!==T))return-1;for(U[1]=0,C=1;C<15;C++)U[C+1]=U[C]+P[C];for(M=0;M<c;M++)0!==t[n+M]&&(u[U[t[n+M]]++]=M);if(0===e?(L=F=u,p=19):1===e?(L=i,k-=257,F=o,G-=257,p=256):(L=r,F=a,p=-1),C=O,v=d,A=M=N=0,f=-1,m=(R=1<<(D=b))-1,1===e&&852<R||2===e&&592<R)return 1;for(;;){for(S=C-A,u[M]<p?(E=0,I=u[M]):u[M]>p?(E=F[G+u[M]],I=L[k+u[M]]):(E=96,I=0),_=1<<C-A,O=g=1<<D;l[v+(N>>A)+(g-=_)]=S<<24|E<<16|I,0!==g;);for(_=1<<C-1;N&_;)_>>=1;if(0!==_?(N&=_-1,N+=_):N=0,M++,0==--P[C]){if(C===T)break;C=t[n+u[M]]}if(b<C&&(N&m)!==f){for(0===A&&(A=b),v+=O,w=1<<(D=C-A);D+A<T&&!((w-=P[D+A])<=0);)D++,w<<=1;if(R+=1<<D,1===e&&852<R||2===e&&592<R)return 1;l[f=N&m]=b<<24|D<<16|v-d}}return 0!==N&&(l[v+N]=C-A<<24|64<<16),h.bits=b,0}},{"../utils/common":1}],10:[function(e,t,n){t.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],11:[function(e,t,n){t.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],"/lib/inflate.js":[function(e,t,n){var s=e("./zlib/inflate"),i=e("./utils/common"),o=e("./utils/strings"),r=e("./zlib/constants"),a=e("./zlib/messages"),c=e("./zlib/zstream"),l=e("./zlib/gzheader"),d=Object.prototype.toString;function u(e){if(!(this instanceof u))return new u(e);this.options=i.assign({chunkSize:16384,windowBits:0,to:""},e||{});var t=this.options;t.raw&&0<=t.windowBits&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(0<=t.windowBits&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),15<t.windowBits&&t.windowBits<48&&!(15&t.windowBits)&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new c,this.strm.avail_out=0;var n=s.inflateInit2(this.strm,t.windowBits);if(n!==r.Z_OK)throw new Error(a[n]);if(this.header=new l,s.inflateGetHeader(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=o.string2buf(t.dictionary):"[object ArrayBuffer]"===d.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(n=s.inflateSetDictionary(this.strm,t.dictionary))!==r.Z_OK))throw new Error(a[n])}function h(e,t){var n=new u(t);if(n.push(e,!0),n.err)throw n.msg||a[n.err];return n.result}u.prototype.push=function(e,t){var n,a,c,l,u,h=this.strm,_=this.options.chunkSize,g=this.options.dictionary,f=!1;if(this.ended)return!1;a=t===~~t?t:!0===t?r.Z_FINISH:r.Z_NO_FLUSH,"string"==typeof e?h.input=o.binstring2buf(e):"[object ArrayBuffer]"===d.call(e)?h.input=new Uint8Array(e):h.input=e,h.next_in=0,h.avail_in=h.input.length;do{if(0===h.avail_out&&(h.output=new i.Buf8(_),h.next_out=0,h.avail_out=_),(n=s.inflate(h,r.Z_NO_FLUSH))===r.Z_NEED_DICT&&g&&(n=s.inflateSetDictionary(this.strm,g)),n===r.Z_BUF_ERROR&&!0===f&&(n=r.Z_OK,f=!1),n!==r.Z_STREAM_END&&n!==r.Z_OK)return this.onEnd(n),!(this.ended=!0);h.next_out&&(0!==h.avail_out&&n!==r.Z_STREAM_END&&(0!==h.avail_in||a!==r.Z_FINISH&&a!==r.Z_SYNC_FLUSH)||("string"===this.options.to?(c=o.utf8border(h.output,h.next_out),l=h.next_out-c,u=o.buf2string(h.output,c),h.next_out=l,h.avail_out=_-l,l&&i.arraySet(h.output,h.output,c,l,0),this.onData(u)):this.onData(i.shrinkBuf(h.output,h.next_out)))),0===h.avail_in&&0===h.avail_out&&(f=!0)}while((0<h.avail_in||0===h.avail_out)&&n!==r.Z_STREAM_END);return n===r.Z_STREAM_END&&(a=r.Z_FINISH),a===r.Z_FINISH?(n=s.inflateEnd(this.strm),this.onEnd(n),this.ended=!0,n===r.Z_OK):a!==r.Z_SYNC_FLUSH||(this.onEnd(r.Z_OK),!(h.avail_out=0))},u.prototype.onData=function(e){this.chunks.push(e)},u.prototype.onEnd=function(e){e===r.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=i.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg},n.Inflate=u,n.inflate=h,n.inflateRaw=function(e,t){return(t=t||{}).raw=!0,h(e,t)},n.ungzip=h},{"./utils/common":1,"./utils/strings":2,"./zlib/constants":4,"./zlib/gzheader":6,"./zlib/inflate":8,"./zlib/messages":10,"./zlib/zstream":11}]},{},[])("/lib/inflate.js")}(mt)),mt.exports);var pt=new class{constructor(){this._socketAdapter=null,this._url="",this._isReconnecting=!1,this._pendingRequests=new Map,this._nextHeartbeatAt=0,this._lastDiagnoseAt=0,this._isHeartbeatInProgress=!1,this._connectionEstablishedTime=0,this._connectionStartTime=0,this._connectionId=-1,this._isBinarySupported=!0,this._intendedDelay=rt,this._currentConnectState=st}init(){we.addTask({id:et,intervalMs:1e3,callback:this._executeScheduledTaskIfReady,context:this}),this._updateIsBinarySupported(),this._url=function(e){const t=Ce.get("instance"),{sdkAppId:n,testEnv:s}=t,i=Ie(n);return be(s?Se.TEST[i].DEFAULT:Se.PRODUCTION[i].INITIAL.replace("*",`${n}`),{isBinary:e})}(this._isBinarySupported),r.subscribeInnerEvent("networkStatusChange",this._handleNetworkStatusChange,this),r.subscribeInnerEvent("activityStatusChange",this._handleActivityStatusChange,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?Re(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(),n=`${Qe}.connect isWorkerEnabled: false socketID:${t} url:${this._url}`;this._ssoLog({method:"connect",message:n}),console.log(n)}disconnect(){var e,t;const n=null===(e=this._socketAdapter)||void 0===e?void 0:e.getId(),s=`${Qe}.disconnect socketID:${n}`;this._ssoLog({method:"disconnect",message:s}),console.log(s),this._removeEventListeners(),null===(t=this._socketAdapter)||void 0===t||t.disconnect()}getSocketAdapter(){return this._socketAdapter}dispose(){console.log(`${Qe}.dispose`),we.removeTask(et),we.removeTask(nt),r.unSubscribeInnerEvent("networkStatusChange",this._handleNetworkStatusChange,this),r.unSubscribeInnerEvent("activityStatusChange",this._handleActivityStatusChange,this),this.disconnect(),this._socketAdapter=null,this._isReconnecting=!1,this._isHeartbeatInProgress=!1,this._pendingRequests.clear(),this._nextHeartbeatAt=0,this._lastDiagnoseAt=0,this._intendedDelay=rt,this._url=""}_shouldSkipReconnect(){const e=this._currentConnectState===it&&this._isReconnecting;return!this._socketAdapter||e}reconnect(){return a(this,void 0,void 0,(function*(){const e=`${Qe} reconnect isReconnecting: ${this._isReconnecting} currentConnectState: ${this._currentConnectState}`;if(this._ssoLog({method:"reconnect",message:e}),console.log(e),!this._shouldSkipReconnect()){this._url=function(e){const t=Ce.get("instance"),{sdkAppId:n,testEnv:s}=t,i=Ie(n);if(s)return be(Se.TEST[i].DEFAULT,{isBinary:e});const o=Se.PRODUCTION[i],r=D&&o.ANYCAST;return be({[ye.INITIAL]:()=>(Oe=ye.DEFAULT,o.DEFAULT),[ye.DEFAULT]:()=>(Oe=ye.BACKUP,o.BACKUP),[ye.BACKUP]:()=>(Oe=r?ye.ANYCAST:ye.DEFAULT,r?o.ANYCAST:o.DEFAULT),[ye.ANYCAST]:()=>(Oe=ye.DEFAULT,o.ANYCAST="",o.DEFAULT)}[Oe](),{isBinary:e})}(this._isBinarySupported);try{this._isReconnecting=!0,this.disconnect(),this.connect()}catch(e){this._isReconnecting=!1,this._handleConnectStateChange({state:ot,reason:dt}),console.warn(`${Qe} reconnect 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=0!==this._connectionEstablishedTime?Date.now()-this._connectionEstablishedTime:0,i=`${Qe} onClose closeSocketID: ${t} currentSocketID: ${this._connectionId} connectionDuration: ${s} code:${null==n?void 0:n.code} reason:${null==n?void 0:n.reason}`;this._ssoLog({method:"onClose",message:i}),console.warn(i),t===this._connectionId&&this._handleConnectStateChange({state:ot,reason:ht}),this._isReconnecting&&(this._isReconnecting=!1)}_onError(e){const{socketId:t,error:n}=e||{},s=`${Qe} onError sourceSocketID: ${t} currentSocketID:${this._connectionId} isReconnecting: ${this._isReconnecting} error: ${JSON.stringify(n)}`;this._ssoLog({method:"onError",message:s}),console.warn(s),t===this._connectionId&&this._handleConnectStateChange({state:ot,reason:ut}),this._isReconnecting&&(this._isReconnecting=!1)}_onSendFail(e){const{socketId:t,error:n}=e||{},s=`${Qe} onSendFail sendFailSocketId: ${t} currentSocketID:${this._connectionId} isReconnecting: ${this._isReconnecting} error: ${n}`;this._ssoLog({method:"onSendFail",message:s}),console.warn(s),t===this._connectionId&&this._handleConnectStateChange({state:ot,reason:lt}),this._isReconnecting&&(this._isReconnecting=!1)}_onMessage(e){let t,n;this._updateHeartbeatTime();try{t=this._isBinarySupported?this._isCompressedData(e.data)?(e=>{const t=new Uint8Array(e).slice(4);let n;try{n=vt.inflate(t,{to:"string"})}catch(e){console.error("inflate error",e)}return n})(e.data):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,n=JSON.parse(t)}catch(t){const n=e.data;return this._ssoLog({method:"jsonParseError",message:n}),void console.error(t)}if(!n||!n.head)return;const{seq:s,servcmd:i}=n.head,o=`${s}${i}`;this._pendingRequests.has(o)?this._handleRequestResponse(n):this._handlePushMessage(n)}_handleRequestResponse(e){const{seq:t,servcmd:n}=e.head,{int32_error_code:s,str_error_message:i,ErrorCode:o=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),o&&0!==o)return r.emitInnerEvent("error",{errorCode:o,errorInfo:a}),void d({errorCode:o,errorInfo:a});l(e.body)}_handlePushMessage(e){const{servcmd:t}=e.head,{NeedAck:n,SessionData:s}=e.body;1===n&&this._sendAck(s),r.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?Re(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} onConnect cost:${s} ms. socketID:${t} res:${JSON.stringify(n)}`;if(this._ssoLog({method:"onConnect",message:i}),console.log(i),this._checkPendingRequestsAndResend(),this._sendHeartbeatIfReady(),this._isReconnecting){const e=`${Qe} reconnect success`;this._ssoLog({method:"reconnectSuccess",message:e}),console.log(e),r.emitInnerEvent(Ve.RECONNECTED),this._isReconnecting=!1}this._resetReconnectDelay(),this._handleConnectStateChange({state:st})}_sendAck(e){const t=ke({servcmd:"openim.ws_msg_push_ack",data:{SessionData:e}});this.sendPacket(t)}_executeScheduledTaskIfReady(){return a(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 a(this,void 0,void 0,(function*(){var e;const t=ke({servcmd:"heartbeat.alive",data:{}});try{const e=`${t.head.seq}${t.head.servcmd}`;yield this.sendPacket(t,{requestId:e,timeout:3e3})}catch(t){const n=null===(e=Ce.get("netWorkMonitor"))||void 0===e?void 0:e.isNetWorkOnline,s=`${Qe} sendHeartbeat failed. isNetWorkOnline:${n} error: ${t}`;this._ssoLog({method:"sendHeartbeatError",message:s}),console.debug(s),this._handleConnectStateChange({state:ot,reason:lt})}}))}_sendHeartbeatIfReady(){return a(this,void 0,void 0,(function*(){this._canSendHeartbeat()&&(this._isHeartbeatInProgress=!0,yield this._sendHeartbeat(),this._isHeartbeatInProgress=!1)}))}_updateHeartbeatTime(){this._nextHeartbeatAt=y?Date.now()+5e3:Date.now()+1e4}_handleNetworkStatusChange(e){const t=`${Qe} networkStatusChange ${JSON.stringify(e)}`;this._ssoLog({method:"networkStatusChange",message:t}),console.warn(t);const{isNetworkOnline:n,networkType:s}=e;n&&"none"!==s?this._handleConnectStateChange({state:st,reason:at}):this._handleConnectStateChange({state:ot,reason:at})}isPrivateNetWork(){const e=Ce.get("instance")||{};return e.proxyServer&&!e.fileDownloadProxy}_handleConnectStateChange(e){const{state:t,reason:n}=e;if(this._currentConnectState!==t){const e=`${Qe}._handleConnectStateChange from ${this._currentConnectState} to ${t} reason: ${n}`;this._ssoLog({method:"handleConnectStateChange",message:e}),console.log(e),this._currentConnectState=t,r.emitOuterEvent("netStateChange",{name:"netStateChange",data:{state:t}}),t===ot&&r.emitInnerEvent(Ve.SOCKET_DISCONNECTED),t!==ot&&t!==st||(this._resetReconnectDelay(),we.addTask({id:nt,intervalMs:this._intendedDelay,callback:this._scheduleReconnectWithBackoff,context:this}))}}_handleActivityStatusChange(e){var t,n;const s=null===(n=null===(t=this._socketAdapter)||void 0===t?void 0:t._ws)||void 0===n?void 0:n.readyState,i=`${Qe} activityStatusChange ${JSON.stringify(e)} readyState: ${s}`;this._ssoLog({method:"activityStatusChange",message:i}),console.warn(i),3===s&&this._handleConnectStateChange({state:ot,reason:ct})}_resetReconnectDelay(){var e;we.removeTask(nt);const t=null===(e=Ce.get("activityMonitor"))||void 0===e?void 0:e.isActive;this._intendedDelay=t?rt:1e3}_scheduleReconnectWithBackoff(){var e;const t=null===(e=Ce.get("activityMonitor"))||void 0===e?void 0:e.isActive;this._intendedDelay=t?Math.min(5e3,Math.max(rt,1.5*this._intendedDelay)):Math.min(3e5,Math.max(1e3,1.5*this._intendedDelay));const n=(new Date).toTimeString().slice(0,8),s=`${Qe}.scheduleReconnectWithBackoff timeStr: ${n} intendedDelay: ${this._intendedDelay}`;this._ssoLog({method:"scheduleReconnectWithBackoff",message:s}),console.log(s),this.reconnect(),we.updateTaskInterval(nt,this._intendedDelay)}_ssoLog(e){const{method:t,message:n}=e;Ze.createSSOLogData({method:t}).setLogInfo({message:n}).end()}_diagnose(){this.isPrivateNetWork()||(this._lastDiagnoseAt=Date.now(),function(e){a(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){a(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:ee,errorInfo:"NETWORK_TIMEOUT",data:{requestId:e}}))}}_updateIsBinarySupported(){var e;if(null===(e=Ce.get("instance"))||void 0===e?void 0:e.devMode)return void(this._isBinarySupported=!1);const t=X();(E||f&&"windows"===t||y)&&(this._isBinarySupported=!1)}_isCompressedData(e){const t=new Uint8Array(e);return 67===t[0]&&79===t[1]&&77===t[2]&&80===t[3]}};const St={init:function(e){Ce.set("instance",e),pt.init()},destroy:function(){pt.dispose(),Ce.clear(),we.dispose()},notificationCenter:r,channel:pt,store:Ce,ssoLog:Ze,utils:ae,common:Be,constants:g};var Et,It="1.1.0";!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"}(Et||(Et={}));var yt,Ct=Et;!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",e.NEW_MESSAGE="new_message",e.MESSAGE_PUSH="im_open_push.msg_push",e.MESSAGE_DELETED="message_deleted",e.MESSAGE_REVOKED="message_revoked",e.MESSAGE_MODIFIED="message_modified",e.RECOVER_CONVERSATIONS_COMPLETED="recover_conversations_completed",e.SOCKET_DISCONNECTED="socket_disconnected"}(yt||(yt={}));var Mt,Ot=yt;!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"}(Mt||(Mt={}));var Tt=Mt;const bt=Object.assign({},{KICKED_OUT_MULT_ACCOUNT:"multipleAccount",KICKED_OUT_MULT_DEVICE:"multipleDevice",KICKED_OUT_USERSIG_EXPIRED:"userSigExpired",KICKED_OUT_REST_API:"REST_API_Kick"}),Dt={MSG_TEXT:"TIMTextElem",MSG_IMAGE:"TIMImageElem",MSG_AUDIO:"TIMSoundElem",MSG_FILE:"TIMFileElem",MSG_FACE:"TIMFaceElem",MSG_VIDEO:"TIMVideoFileElem",MSG_LOCATION:"TIMLocationElem",MSG_GRP_TIP:"TIMGroupTipElem",MSG_GRP_SYS_NOTICE:"TIMGroupSystemNoticeElem",MSG_CUSTOM:"TIMCustomElem",MSG_MERGER:"TIMRelayElem"};var At;!function(e){e.UNSENT="unSend",e.SUCCESS="success",e.FAIL="fail"}(At||(At={}));const wt=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},Dt),{MSG_PRIORITY_HIGH:"High",MSG_PRIORITY_NORMAL:"Normal",MSG_PRIORITY_LOW:"Low",MSG_PRIORITY_LOWEST:"Lowest"}),{RECEIVE_WITH_OFFLINE_PUSH_EXCEPT_AT:"AcceptNotNotifyExceptAt",NOT_RECEIVE_OFFLINE_PUSH_EXCEPT_AT:"AcceptNotNotifyExceptAt",NOT_RECEIVE_MSG_EXCEPT_AT:"NotReceiveMsgExceptAt",MSG_AT_ALL:"__kImSDK_MesssageAtALL__"}),{MSG_REMIND_ACPT_AND_NOTE:"AcceptAndNotify",MSG_REMIND_ACPT_NOT_NOTE:"AcceptNotNotify",MSG_REMIND_DISCARD:"Discard"}),{MessageStatus:At}),Rt=Object.assign({},{GENDER_UNKNOWN:"Gender_Type_Unknown",GENDER_FEMALE:"Gender_Type_Female",GENDER_MALE:"Gender_Type_Male",USER_STATUS_UNKNOWN:0,USER_STATUS_ONLINE:1,USER_STATUS_OFFLINE:2,USER_STATUS_UNLOGINED:3}),Nt=Object.assign(Object.assign(Object.assign(Object.assign({},{CONV_C2C:"C2C",CONV_GROUP:"GROUP",CONV_TOPIC:"TOPIC",CONV_SYSTEM:"@TIM#SYSTEM"}),{CONV_AT_ME:1,CONV_AT_ALL:2,CONV_AT_ALL_AT_ME:3}),{CONV_MARK_TYPE_STAR:1,CONV_MARK_TYPE_UNREAD:2,CONV_MARK_TYPE_FOLD:4,CONV_MARK_TYPE_HIDE:8}),{READ_ALL_C2C_MSG:"readAllC2CMessage",READ_ALL_GROUP_MSG:"readAllGroupMessage",READ_ALL_MSG:"readAllMessage"}),Lt=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},{SNS_TYPE_NO_RELATION:"CheckResult_Type_NoRelation",SNS_TYPE_A_WITH_B:"CheckResult_Type_AWithB",SNS_TYPE_B_WITH_A:"CheckResult_Type_BWithA",SNS_TYPE_BOTH_WAY:"CheckResult_Type_BothWay"}),{ALLOW_TYPE_ALLOW_ANY:"AllowType_Type_AllowAny",ALLOW_TYPE_NEED_CONFIRM:"AllowType_Type_NeedConfirm",ALLOW_TYPE_DENY_ANY:"AllowType_Type_DenyAny"}),{SNS_ADD_TYPE_SINGLE:"Add_Type_Single",SNS_ADD_TYPE_BOTH:"Add_Type_Both"}),{SNS_DELETE_TYPE_SINGLE:"Delete_Type_Single",SNS_DELETE_TYPE_BOTH:"Delete_Type_Both"}),{SNS_APPLICATION_TYPE_BOTH:"Pendency_Type_Both",SNS_APPLICATION_SENT_TO_ME:"Pendency_Type_ComeIn",SNS_APPLICATION_SENT_BY_ME:"Pendency_Type_SendOut",SNS_APPLICATION_AGREE:"Response_Action_Agree",SNS_APPLICATION_AGREE_AND_ADD:"Response_Action_AgreeAndAdd"}),{SNS_CHECK_TYPE_BOTH:"CheckResult_Type_Both",SNS_CHECK_TYPE_SINGLE:"CheckResult_Type_Single"}),{FORBID_TYPE_NONE:"AdminForbid_Type_None",FORBID_TYPE_SEND_OUT:"AdminForbid_Type_SendOut"}),kt=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},{GRP_WORK:"Private",GRP_PUBLIC:"Public",GRP_MEETING:"ChatRoom",GRP_AVCHATROOM:"AVChatRoom",GRP_COMMUNITY:"Community",GRP_ROOM:"Room",GRP_LIVE:"Live"}),{GRP_MBR_ROLE_OWNER:"Owner",GRP_MBR_ROLE_ADMIN:"Admin",GRP_MBR_ROLE_MEMBER:"Member",GRP_MBR_ROLE_CUSTOM:"Custom"}),{GRP_TIP_MBR_JOIN:1,GRP_TIP_MBR_QUIT:2,GRP_TIP_MBR_KICKED_OUT:3,GRP_TIP_MBR_SET_ADMIN:4,GRP_TIP_MBR_CANCELED_ADMIN:5,GRP_TIP_GRP_PROFILE_UPDATED:6,GRP_TIP_MBR_PROFILE_UPDATED:7,GRP_TIP_BAN_AVCHATROOM_MEMBER:10,GRP_TIP_UNBAN_AVCHATROOM_MEMBER:11}),{JOIN_OPTIONS_FREE_ACCESS:"FreeAccess",JOIN_OPTIONS_NEED_PERMISSION:"NeedPermission",JOIN_OPTIONS_DISABLE_APPLY:"DisableApply",JOIN_STATUS_SUCCESS:"JoinedSuccess",JOIN_STATUS_ALREADY_IN_GROUP:"AlreadyInGroup",JOIN_STATUS_WAIT_APPROVAL:"WaitAdminApproval"}),{INVITE_OPTIONS_DISABLE_INVITE:"DisableInvite",INVITE_OPTIONS_NEED_PERMISSION:"NeedPermission",INVITE_OPTIONS_FREE_ACCESS:"FreeAccess"}),{GRP_PROFILE_OWNER_ID:"ownerID",GRP_PROFILE_CREATE_TIME:"createTime",GRP_PROFILE_LAST_INFO_TIME:"lastInfoTime",GRP_PROFILE_MEMBER_NUM:"memberNum",GRP_PROFILE_MAX_MEMBER_NUM:"maxMemberNum",GRP_PROFILE_JOIN_OPTION:"joinOption",GRP_PROFILE_INVITE_OPTION:"inviteOption",GRP_PROFILE_INTRODUCTION:"introduction",GRP_PROFILE_NOTIFICATION:"notification",GRP_PROFILE_MUTE_ALL_MBRS:"muteAllMembers"}),Pt=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},bt),wt),Rt),Nt),Lt),kt),{IOS_OFFLINE_PUSH_NO_SOUND:"push.no_sound",IOS_OFFLINE_PUSH_DEFAULT_SOUND:"default"}),{NET_STATE_CONNECTING:"connecting",NET_STATE_DISCONNECTED:"disconnected"}),Ut={NO_SDKAPPID:2e3,NO_TINYID:2022,NO_A2KEY:2023,USER_NOT_LOGGED_IN:2024,REPEAT_LOGIN:2025,MSG_SEND_FAIL:2100,MSG_INSTANCE_REQUIRED:2105,MSG_INVALID_CONV_TYPE:2106,MSG_REVOKE_FAIL:2110,MSG_DELETE_FAIL:2111,MSG_UNREAD_ALL_FAIL:2112,READ_RECEIPT_MSG_LIST_EMPTY:2114,CANNOT_DELETE_GRP_SYSTEM_NOTICE:2116,NOT_MY_FRIEND:2700,NETWORK_ERROR:2800,NETWORK_TIMEOUT:2801,NO_NETWORK:2805,UNCAUGHT_ERROR:2903,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,NO_USE:3122,OPTIONS_IS_EMPTY:3153,MSG_A2KEY_EXPIRED:20002,ACCOUNT_A2KEY_EXPIRED:70001,HELLO_ANSWER_KICKED_OUT:1002,OPEN_SERVICE_OVERLOAD_ERROR:60022};var Ft=Object.freeze({__proto__:null,ERROR_CODE:Ut,InnerEvent:Ot,OuterConstant:Pt,OuterEvent:Ct,SDK_INFO:{VERSION:"1.7.3",APPID:537048168},SignalingEvent:Tt});function Gt(e){var t;try{const n=Ce.getStorage("errorMessage");if(!e||!n)return"";const s=(null===(t=JSON.parse(n))||void 0===t?void 0:t.errorMessage)||{},{isIntl:i=!1,code:o,replacement1:r="",replacement2:a=""}=e;if(!o)return"";const c=i?`${o}_en`:`${o}_cn`;let l=s[s[c]?c:o]||"";return l&&(r&&(l=l.replace("$replacement1",r)),a&&(l=l.replace("$replacement2",a))),l}catch(e){return console.warn("Error parsing stored error messages:",e),""}}class Bt extends Error{constructor(e){const{functionName:t="Unknown",code:n,message:s="",data:i=""}=e;let o=s;n&&!s&&(o=Gt(e));const r=n?`${t} failed. error: {"message": ${o}, "code": ${n}}`:`${t} failed. error: {"message": ${o}}`;super(),this.code=n,this.errorCode=n,this.errorMessage=r,this.message=r,this.data=i}}const xt=e=>"function"==typeof e;function $t(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]?$t(e[s],t[s],n):e[s]===t[s])))}function qt({required:e,rules:t,range:n,value:s,allowEmpty:i,name:o,key:r,customValidator:a}){if(void 0===s){if(e){throw new Bt({functionName:o,message:`[${o}] Missing required params: "${r}"`})}return}let c="";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()),c+=`${n}/`}c=c.substring(0,c.length-1);const e=`[${r}] must be type of ${c}, received type: ${function(e){return Reflect.apply(Object.prototype.toString,e,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}(s)}.`;throw new Bt({functionName:o,message:e})}if(!1===i){if(Array.isArray(s)&&(0===s.length||"string"==typeof s[0]&&""===s[0].trim())){throw new Bt({functionName:o,message:`${r} can not be empty.`})}if("string"==typeof s&&""===s.trim()){throw new Bt({functionName:o,message:`${r} can not be empty.`})}}if(a&&"function"==typeof a){const e=a(s);if(!0!==e){throw new Bt({functionName:o,message:`[${r}] custom validation failed: ${e||"Invalid value"}`})}}}const jt=[],Vt={},Kt={};function Yt(e,t){!function(e,t){var n;if(!e)return;if(!0!==(null===(n=St.store.get("login"))||void 0===n?void 0:n.isLoggedIn))throw new Bt({code:Ut.USER_NOT_LOGGED_IN,functionName:t})}(Vt[e],e),function(e,t,n){if(Array.isArray(e))for(let s=0;s<e.length;s++)qt.call(this,Object.assign(Object.assign({},e[s]),{value:t[s],name:n}));else for(const s in e)qt.call(this,Object.assign(Object.assign({},e[s]),{value:t[0][s],name:n,key:s}))}(Kt[e],t,e),function(e){jt.forEach((t=>{const{interceptor:n,context:s}=t;n.apply(s,[e])}))}(e)}function Ht(e,t){jt.push({interceptor:e,context:t})}function Wt(e){const{params:t,auth:n}=e;t&&"object"==typeof t&&Object.assign(Kt,t),n&&"object"==typeof n&&Object.assign(Vt,n)}var zt=new class{constructor(){this._builtInPlugins=new WeakSet,this._externalPlugins=new WeakSet}installBuiltInPlugin(e){e&&this._installPlugin(e,this._builtInPlugins)}installExternalPlugin(e,...t){e&&this._installPlugin(e,this._externalPlugins,...t)}clear(){this._builtInPlugins=new WeakSet,this._externalPlugins=new WeakSet}_installPlugin(e,t,...n){let s=[];s=Array.isArray(e)?e:[e],s.forEach((e=>{t.has(e)||(e&&xt(e.install)?(t.add(e),e.install(tn(),...n),xt(e.handleLoginSuccess)&&this._isLoggedIn()&&e.handleLoginSuccess()):xt(e)?(t.add(e),e(tn(),...n),xt(e.handleLoginSuccess)&&this._isLoggedIn()&&e.handleLoginSuccess()):console.warn('A plugin must either be a function or an object with an "install" function.'))}))}_isLoggedIn(){var e;return!0===(null===(e=St.store.get("login"))||void 0===e?void 0:e.isLoggedIn)}};function Jt(e){return St.store.get("commercialConfig").get(e)}const Zt={on:St.notificationCenter.subscribeOuterEvent.bind(St.notificationCenter),off:St.notificationCenter.unSubscribeOuterEvent.bind(St.notificationCenter),destroy:function(){return a(this,void 0,void 0,(function*(){var e,t;try{(null===(e=St.store.get("login"))||void 0===e?void 0:e.isLogin)&&(yield Zt.logout()),St.notificationCenter.emitInnerEvent(Ot.DESTROY)}catch(e){console.debug("destroy error: ",e)}finally{St.notificationCenter.emitOuterEvent(Ct.SDK_DESTROY,{SDKAppID:null===(t=St.store.get("instance"))||void 0===t?void 0:t.sdkAppId}),Li.clear(),zt.clear(),St.destroy()}}))},callExperimentalAPI:function(e,t){if(Xt[e])return Xt[e](t);return Promise.reject(new Error(`API ${e} is not found`))},use:zt.installExternalPlugin.bind(zt),registerPlugin:function(e){console.log("registerPlugin",e)}},Xt={};function Qt(e,t,n){const s=n||e;Zt[e]=(...e)=>(Yt(s,e),t[s].bind(t)(...e))}function en(e,t,n){const s=n||e;Xt[e]=t[s].bind(t)}function tn(){return Object.assign(Object.assign({InnerEvent:Ot,InnerEventSubType:St.notificationCenter.InnerEventSubType,OuterEvent:Ct,OuterConstant:Pt,SignalingEvent:Tt,helper:Object.assign(Object.assign(Object.assign({},St.utils),St.common),{registerApi:Qt,registerExperimentalAPI:en,registerInterceptor:Ht,registerValidateConfig:Wt,checkBusinessCapabilityBits:Jt,ChatError:Bt}),apiMap:Zt},St),{constants:Object.assign(Object.assign({},Ft),St.constants)})}var nn,sn,on;!function(e){e[e.USER_INITIATED=0]="USER_INITIATED",e[e.KICKED_OUT=1]="KICKED_OUT"}(nn||(nn={})),function(e){e[e.multipleAccount=1]="multipleAccount",e[e.multipleDevice=2]="multipleDevice",e[e.restApi=3]="restApi"}(sn||(sn={})),function(e){e[e.multipleDevice=3002]="multipleDevice",e[e.multipleAccount=3003]="multipleAccount",e[e.usersigExpired=70001]="usersigExpired",e[e.restApi=20002]="restApi"}(on||(on={}));const rn={[sn.multipleAccount]:"multipleAccount",[sn.multipleDevice]:"multipleDevice",[sn.restApi]:"REST_API_Kick",[on.multipleAccount]:"multipleAccount",[on.multipleDevice]:"multipleDevice",[on.restApi]:"REST_API_Kick",[on.usersigExpired]:"userSigExpired"},an="login_online_presence_task",{ERROR:cn,DESTROY:ln,FORCE_OFFLINE:dn}=Ot,{KICKED_OUT_MULT_ACCOUNT:un,KICKED_OUT_MULT_DEVICE:hn,KICKED_OUT_REST_API:_n,ACCOUNT_A2KEY_EXPIRED:gn,MSG_A2KEY_EXPIRED:fn}=Ut;class mn{init(){const{notificationCenter:e}=St;e.subscribeInnerEvent(dn,this._handleForceOfflineFromServerPush,this),e.subscribeInnerEvent(cn,fn,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(cn,gn,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(cn,un,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(cn,hn,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(cn,_n,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(ln,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 a(this,void 0,void 0,(function*(){const{kickedOutReasonCode:t}=e;try{yield St.login.loginAction.logout(nn.KICKED_OUT)}catch(e){console.debug(e)}finally{this._logKickedOutEvent(e),St.notificationCenter.emitOuterEvent(Ct.KICKED_OUT,{data:{type:rn[t]},name:Ct.KICKED_OUT}),[sn.restApi,gn,fn].includes(t)&&St.channel.reconnect()}}))}_logKickedOutEvent(e){const{kickedOutReasonCode:t,newInstanceInfo:n={}}=e,s=St.ssoLog.createSSOLogData({method:"kickedOut"}),i=`type:${rn[t]} newInstanceInfo: ${JSON.stringify(n)}`;s.setLogInfo({message:i}).end(!0),console.warn(`loginModule.${i}`)}_isKickedOut(e){return[sn.multipleAccount,sn.multipleDevice,sn.restApi].includes(e)}_dispose(){const{notificationCenter:e}=St;e.unSubscribeInnerEvent(dn,this._handleForceOfflineFromServerPush,this),e.unSubscribeInnerEvent(cn,gn,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(cn,fn,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(cn,un,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(cn,hn,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(cn,_n,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(ln,this._dispose,this)}}function vn(){return a(this,void 0,void 0,(function*(){const e="im_open_status.wslogin",t=St.common.generateProtocolData({servcmd:e,data:{state:"Online",isWebUniapp:0,InstType:0,customInfo:""}}),n=`${t.head.seq}${e}`;try{const e=yield St.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}}))}class pn{constructor(){this._latestLoginAt=0,this._latestSendOnlinePresenceRequestTime=0,this._helloInterval=120}init(){const{notificationCenter:e,store:t}=St;t.set("login",{isReady:!1}),Qt("login",this),Qt("logout",this),Qt("getLoginUser",this),Qt("isReady",this),e.subscribeInnerEvent(Ot.RECONNECTED,this._reLogin,this),St.notificationCenter.subscribeInnerEvent(Ot.DESTROY,this._dispose,this)}login(e){return a(this,void 0,void 0,(function*(){St.notificationCenter.emitInnerEvent("BEFORE_LOGIN");const t=St.ssoLog.createSSOLogData({method:"login",eventType:4});try{if(this._isLoginIn())return this._createRepeatLoginResponse();if(this._isLoginFrequencyExceeded())throw new Bt({functionName:"login",code:Ut.REPEAT_LOGIN});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 Bt({functionName:"login",code:n});throw t.setError(s).end(!0),s}finally{this._latestLoginAt=0}}))}_reLogin(){return a(this,void 0,void 0,(function*(){var e;try{if(!this._isLoginIn())return;const t=St.ssoLog.createSSOLogData({method:"reLogin"}),n=yield vn();if(n){const{instanceID:s,customStatus:i}=n;St.store.set("login",{statusInstanceId:s}),St.notificationCenter.emitInnerEvent(Ot.RE_LOGIN,{customStatus:i});const o=`socketId:${null===(e=St.channel.getSocketAdapter())||void 0===e?void 0:e.getId()} instanceId:${s}`;t.setLogInfo({message:o}).end(!0)}}catch(e){console.warn(e)}}))}logout(){return a(this,arguments,void 0,(function*(e=nn.USER_INITIATED){St.ssoLog.createSSOLogData({method:"logout"}).setLogInfo({moreMessage:`identifier:${this._getCurrentUserId()}`}).end(!0);try{yield this._performLogout(e)}catch(e){const{errorCode:t}=e,n=new Bt({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=St.store.get("login"))||void 0===e?void 0:e.isReady}_updateAndEmitSDKReady(){St.store.set("login",{isReady:!0}),setTimeout((()=>{St.notificationCenter.emitOuterEvent(Ct.SDK_READY,{name:Ct.SDK_READY})}),1)}_updateAndEmitSDKNotReady(){St.store.set("login",{isReady:!1}),St.notificationCenter.emitOuterEvent(Ct.SDK_NOT_READY,{name:Ct.SDK_NOT_READY})}_validateAfterLogin(e){var t,n;const s="login";if(!e)throw new Bt({functionName:s,message:"login response is empty"});const{tinyID:i,a2Key:o}=e||{},r=St.ssoLog.getSSOLogData(s);if(!i){const e=new Bt({functionName:s,code:Ut.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 Bt({functionName:s,code:Ut.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:Gt({code:"RepeatLogin",replacement1:null===(e=St.store.get("login"))||void 0===e?void 0:e.userId}),repeatLogin:!0}}}_performLogin(e){return a(this,void 0,void 0,(function*(){const{userID:t,userSig:n}=e;return St.store.set("login",{userId:t,userSig:n}),this._latestLoginAt=Date.now(),vn()}))}_ensureAsyncComplete(){return a(this,void 0,void 0,(function*(){yield new Promise((e=>{setTimeout((()=>e(null)),1)}))}))}_handleLoginSuccess(e){const{timeManager:t}=St.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),St.user.userStatus.setCustomStatus(i),St.notificationCenter.emitInnerEvent(Ot.LOGIN,{purchaseBits:o}),St.common.taskScheduler.addTask({id:an,intervalMs:1e3*this._helloInterval,callback:this._sendOnlinePresenceRequest,context:this}),this._logLoginSuccess(e)}_performLogout(e){return function(e){return a(this,void 0,void 0,(function*(){const{logoutReason:t}=e,n="im_open_status.wslogout",s=St.common.generateProtocolData({servcmd:n,data:{wslogout_type:t,isWebUniapp:0}}),i=`${s.head.seq}${n}`;return yield St.channel.sendPacket(s,{requestId:i})}))}({logoutReason:e})}_handleLogoutError(e){St.ssoLog.getSSOLogData("logout").setError(e).end(),console.error(`logout ${e}`)}_handleLogoutCompleted(){this._updateAndEmitSDKNotReady(),this._reset(),St.notificationCenter.emitInnerEvent("logout")}_updateLoginStore(e){const{a2Key:t,tinyID:n,instanceID:s,authKey:i}=e;St.store.set("login",{a2Key:t,tinyID:n,statusInstanceId:s,authKey:i,isLoggedIn:!0})}_logLoginSuccess(e){var t;const n=St.ssoLog.getSSOLogData("login"),{helloInterval:s,instanceID:i,timeStamp:o,customStatus:r}=e,a=null===(t=St.channel.getSocketAdapter())||void 0===t?void 0:t.getId(),c=St.common.timeManager.getTimeOffsetWithServer(),{appId:l,href:d}=St.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 a(this,void 0,void 0,(function*(){this._latestSendOnlinePresenceRequestTime=Date.now();try{yield function(){const e="im_open_status.wshello",t=St.common.generateProtocolData({servcmd:e,data:{isWebUniapp:0}}),n=`${t.head.seq}${e}`;return St.channel.sendPacket(t,{requestId:n})}()}catch(e){console.warn("Login._sendOnlinePresenceRequest error:",e)}}))}_getCurrentUserId(){var e;return null===(e=St.store.get("login"))||void 0===e?void 0:e.userId}_isLoginIn(){var e;return!0===(null===(e=St.store.get("login"))||void 0===e?void 0:e.isLoggedIn)}_isLoginFrequencyExceeded(){return Date.now()-this._latestLoginAt<=15e3}_reset(){console.log("Login reset"),St.common.taskScheduler.removeTask(an),this._helloInterval=120,this._latestSendOnlinePresenceRequestTime=0,this._latestLoginAt=0,St.store.clear("login"),St.store.set("login",{isReady:!1})}_dispose(){console.log("Login dispose"),this._reset();const{notificationCenter:e}=St;e.unSubscribeInnerEvent(Ot.RECONNECTED,this._reLogin,this),e.unSubscribeInnerEvent(Ot.DESTROY,this._dispose,this)}}const Sn={login:{userID:{required:!0,rules:["string"],allowEmpty:!1},userSig:{required:!0,rules:["string"],allowEmpty:!1}}},En={logout:!0};class In{constructor(){this.loginAction=new pn,this.kickedOutHandler=new mn,this.loginAction.init(),this.kickedOutHandler.init(),Wt({auth:En,params:Sn})}}var yn,Cn,Mn;!function(e){e.CONV_C2C="C2C",e.CONV_GROUP="GROUP",e.CONV_TOPIC="TOPIC",e.CONV_SYSTEM="@TIM#SYSTEM"}(yn||(yn={})),function(e){e.MSG_PRIORITY_HIGH="High",e.MSG_PRIORITY_NORMAL="Normal",e.MSG_PRIORITY_LOW="Low",e.MSG_PRIORITY_LOWEST="Lowest"}(Cn||(Cn={})),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"}(Mn||(Mn={}));const On={1:Cn.MSG_PRIORITY_HIGH,2:Cn.MSG_PRIORITY_NORMAL,3:Cn.MSG_PRIORITY_LOW,4:Cn.MSG_PRIORITY_LOWEST},Tn=0,bn=1;var Dn;!function(e){e.IN="in",e.OUT="out"}(Dn||(Dn={}));const An={};function wn(e){if(!e)return 0;if(void 0===An[e]){const t=new Date,n=`3${t.getHours()}`.slice(-2),s=`0${t.getMinutes()}`.slice(-2),i=`0${t.getSeconds()}`.slice(-2);An[e]=parseInt([n,s,i,"0001"].join(""),10),console.log(`autoIncrementIndex start index:${An[e]}`)}else An[e]+=1;return An[e]}class Rn{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=Cn.MSG_PRIORITY_NORMAL,this._relayFlag=!1;const{clientTime:t=St.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:f,messageVersion:m=0,conversationType:v,sequence:p,checkResult:S=0,isPlaceMessage:E=0,messageFlagBits:I,receiverList:y,isSystemMessage:C=!1,status:M=At.SUCCESS,revokeReason:O="",conversationSubType:T,clientSequence:b,protocol:D="JSON",revokerInfo:A={userID:"",nick:"",avatar:""},readReceiptInfo:w={readCount:void 0,unreadCount:void 0,isPeerRead:void 0,timestamp:0},random:R,groupProfile:N,atUserList:L,flow:k}=e;var P;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=D,this.random=void 0===R?(P=P||99999999,Math.round(Math.random()*P)):R,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=!!m,this.cloudCustomData=g,this.messageLifeTime=f,this.from=c||null,this.sequence=p||0,this.conversationType=v||yn.CONV_C2C,this.hasRiskContent=S>1,this.version=m,this.isPlaceMessage=E,this.isRevoked=2===E||8===I,this.isSystemMessage=C,this.readReceiptInfo=w,this.revokeReason=O,this.revokerInfo=A,this._receiverList=y,this.conversationSubType=T,this.revoker=(null==A?void 0:A.revoker)||"",this.clientSequence=b||p||0,this.status=M,this.atUserList=L||[],this.flow=k,this.reInitialize(s),this._initC2CReadReceiptInfo(e),this._extractGroupInfo(N)}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}setRelayFlag(e){this._relayFlag=e}validateBeforeSend(){var e,t,n;return this._relayFlag?{isValid:!0}:(null===(e=this._elements)||void 0===e?void 0:e.length)>0?null===(n=null===(t=this._elements[0])||void 0===t?void 0:t.validateBeforeSend)||void 0===n?void 0:n.call(t):{isValid:!1}}_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===yn.CONV_C2C&&!0===this.needReadReceipt&&(this.readReceiptInfo.isPeerRead=1===t,this.readReceiptInfo.timestamp=n)}_extractGroupInfo(e){if(!e)return;const{From_AccountNick:t,From_AccountHeadurl:n,MsgFrom_AccountExtraInfo:s}=e,{NameCard:i}=s||{};"string"==typeof t&&(this.nick=t),"string"==typeof n&&(this.avatar=n),"string"==typeof i&&(this.nameCard=i)}reInitialize(e){e===this.from&&(this.isRead=!0),this._initSequence(e),this._concatConversationID(e),this._generateMessageID()}_concatConversationID(e){let t="";const n=this.conversationType;n!==yn.CONV_SYSTEM?(t=n===yn.CONV_C2C?e===this.from?this.to:this.from:this.to,this.conversationID=t?`${n}${t}`:null):this.conversationID=yn.CONV_SYSTEM}_initSequence(e){0===this.clientSequence&&e&&(this.clientSequence=wn(e)),0===this.sequence&&this.conversationType===yn.CONV_C2C&&(this.sequence=this.clientSequence)}_generateMessageID(){this.from===yn.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=Mn.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}}}validateBeforeSend(){const{isEmpty:e}=St.utils,t=[this.content.data,this.content.description,this.content.extension].some((t=>!e(t)));return{isValid:t,error:t?null:{message:"content can not be empty"}}}}class Ln{static parseServerPushElement(e){const{MsgContent:t={Text:""}}=e,{Text:n}=t;return new Ln({text:n})}constructor(e){this.type=Dt.MSG_TEXT,this.content={text:e.text||""}}validateBeforeSend(){var e,t;return(null===(t=null===(e=this.content)||void 0===e?void 0:e.text)||void 0===t?void 0:t.length)>0?{isValid:!0}:{isValid:!1,error:{message:"content can not be empty"}}}convertToBackendFormat(){const{text:e}=this.content;return{MsgType:this.type,MsgContent:{Text:e}}}}class kn{constructor(){this._elementClassMap={[Mn.MSG_CUSTOM]:Nn,[Mn.MSG_TEXT]:Ln}}init(){Qt("createCustomMessage",this),Qt("createTextMessage",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){const{from:t,flow:n=Dn.OUT}=e,{userId:s}=St.store.get("login")||{};this._isSendByCurrentInstance({from:t,flow:n,currentUser:s})?this._updateWithSenderInfo(e):this._isMultiEndpointSyncMessage({from:t,flow:n,currentUser:s})&&(e.flow=Dn.OUT);const i=Object.assign(Object.assign({},e),{currentUser:s});return new Rn(i)}createCustomMessage(e){const t=this._getCurrentUserId(),n=this.createMessage(Object.assign(Object.assign({},e),{from:t})),s=this._elementClassMap[Mn.MSG_CUSTOM];if(!n)return null;if(s){const t=new s(e.payload);n.setElement(t)}return n}createTextMessage(e){var t;if(!e)return null;const n="string"==typeof e.payload?e.payload:(null===(t=null==e?void 0:e.payload)||void 0===t?void 0:t.text)||"",s=new Ln({text:n}),i=this._getCurrentUserId(),o=St.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{from:i}));return o.setElement(s),o}_updateWithSenderInfo(e){const{nick:t,avatar:n}=e,{userId:s,tinyID:i}=St.store.get("login")||{},o=St.user.userProfile.getUserProfileFromCache(s);return e.nick=t||(null==o?void 0:o.nick)||"",e.avatar=n||(null==o?void 0:o.avatar)||"",e.tinyID=e.tinyID||i||"",e.from=s,e.status=At.UNSENT,e.flow=Dn.OUT,e}_isMultiEndpointSyncMessage(e){const{from:t,flow:n,currentUser:s}=e;return t===s&&n===Dn.IN}_isSendByCurrentInstance(e){const{from:t,flow:n,currentUser:s}=e;return t===s&&n===Dn.OUT}_getCurrentUserId(){var e;return null===(e=St.store.get("login"))||void 0===e?void 0:e.userId}}function Pn(e){const t=e.lastIndexOf(".");return-1===t?e:e.slice(0,t)}function Un(e){const{androidInfo:t={},androidOPPOChannelID:n=""}=e,s=t.OPPOChannelID||n;return Object.assign(Object.assign({},t),{Sound:Pn(t.sound||""),OPPOChannelID:s,GoogleChannelID:t.FCMChannelID||""})}function Fn(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 Gn(e){return St.utils.isPlainObject(e)?{PushFlag:!0===e.disablePush?1:0,Title:e.title||"",Desc:e.description||"",Ext:e.extension||"",ApnsInfo:Fn(e),AndroidInfo:Un(e)}:null}const{isPlainObject:Bn}=St.utils;function xn(e,t={}){const{onlineUserOnly:n,messageControlInfo:s}=t;let{offlinePushInfo:i}=t;e.conversationType===yn.CONV_C2C&&!0===n&&(i?i.disablePush=!0:i={disablePush:!0});let o="";"string"==typeof e.cloudCustomData&&e.cloudCustomData.length>0&&(o=e.cloudCustomData);const r=[];if(s&&Bn(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}}function $n(e){const{webhookInfo:{disableCloudMessagePreHook:t=!1,disableCloudMessagePostHook:n=!1}={}}=e||{};if(!t&&!n)return;const s=[];return t&&s.push("ForbidBeforeSendMsgCallback"),n&&s.push("ForbidAfterSendMsgCallback"),s}function qn(e,t){return a(this,void 0,void 0,(function*(){const n=e.conversationType===yn.CONV_GROUP?function(e,t){var n;const s=xn(e,t),{onlineUserOnly:i,cloudCustomData:o,messageControlInfo:r,offlinePushInfo:a}=s,c=JSON.parse(JSON.stringify(e.convertElementsToBackendFormat()));return{servcmd:"group_open_http_svc.send_group_msg",data:{From_Account:null===(n=St.store.get("login"))||void 0===n?void 0:n.userId,GroupId:e.to,MsgBody:c,CloudCustomData:o,Random:e.random,MsgPriority:e.priority,ClientSeq:e.clientSequence,GroupAtInfo:e._groupAtInfoList,OnlineOnlyFlag:i?1:0,MsgClientTime:e.clientTime,OfflinePushInfo:Gn(a),SendMsgControl:i?void 0:r,NeedReadReceipt:!0===e.needReadReceipt?1:0,receiverList:null,SupportMessageExtension:!0===e.isSupportExtension?1:0,IsRelayMsg:!0===e._relayFlag?1:0,CustomModerationConfigID:e._cmConfigID,ForbidCallbackControl:$n(t)}}}(e,t):function(e,t){var n;const s=xn(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=St.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,CustomModerationConfigID:e._cmConfigID,OfflinePushInfo:Gn(a),forbidCallbackControl:$n(t)}}}(e,t),s=St.common.generateProtocolData(n),i=`${s.head.seq}${s.head.servcmd}`,o=yield St.channel.sendPacket(s,{requestId:i});return o?{time:o.MsgTime,messageDropReason:o.MsgDropReason,sequence:o.MsgSeq}:null}))}const{isPlainObject:jn}=St.utils;class Vn{init(){Qt("sendMessage",this)}sendMessage(e,t){return a(this,void 0,void 0,(function*(){const n=St.ssoLog.createSSOLogData({method:"sendMessage"});if(!(e instanceof Rn)){const e=new Bt({code:Ut.MSG_INSTANCE_REQUIRED});throw n.setError(e).end(),e}const s=e.validateBeforeSend();if(!s.isValid){const{code:e,message:t=""}=s.error||{},i=new Bt({code:e,message:t});throw n.setError(i).end(),i}let i=!1;const{messageStore:o}=St.message||{};try{const{messageControlInfo:s}=t||{};let r=null;if(o.addRandomOfSentMessage(e.random),e.conversationType===yn.CONV_C2C?(i=!0===(null==t?void 0:t.onlineUserOnly),r=yield this._sendC2cMessage(e,t)):e.conversationType===yn.CONV_GROUP&&(r=yield this._sendGroupMessage(e,t)),r){const{messageDropReason:a,sequence:c,time:l}=r;if(a&&this._logRateLimitInfo(e,c),!0===e.isResend){const t=o.findMessage(e.ID);t&&(console.log(`sendMessage resend ok. ID:${t.ID}`),o.deleteConversationMessage(t))}return e.status=At.SUCCESS,e.time=l,e.conversationType===yn.CONV_GROUP&&(e.sequence=c),i?e._onlineOnlyFlag=!0:(o.storeConversationMessage(e),this._applySentMessageControlInfo(e,s),this._emitOnlineMessageSent(e)),n.setLogInfo({message:`options: ${JSON.stringify(t)}`}).end(),{code:0,data:{message:e}}}}catch(t){e.status=At.FAIL,o.removeRandomOfSentMessage(e.random);const{errorCode:n,errorInfo:s=""}=t||{};this._hasRiskContent(n)&&(e.hasRiskContent=!0),i||this._isRejectedByRestApi(n)||o.storeConversationMessage(e);const r=new Bt({code:n,message:s,data:{message:e}});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=St.ssoLog.createSSOLogData({method:"sendMessage"});let s=`head.seq: type:${e.type} from:${e.from} to:${e.to}`;if(St.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,{conversationID:n,conversationType:s}=e;St.notificationCenter.emitInnerEvent(Ot.NEW_MESSAGE,{conversationOptionsList:[{conversationID:n,type:s,message:e,lastMessage:t,unreadCount:0}]})}_applySentMessageControlInfo(e,t){t&&jn(t)&&(!0===t.excludedFromLastMessage&&(e._isExcludedFromLastMessage=!0),!0===t.excludedFromUnreadCount&&(e._isExcludedFromUnreadCount=!0))}_logRateLimitInfo(e,t){const n=St.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 a(this,void 0,void 0,(function*(){const n=yield qn(e,t),{messageStore:s}=St.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}))}_sendGroupMessage(e,t){return a(this,void 0,void 0,(function*(){return qn(e,t)}))}}function Kn(e){const{From_AccountHeadurl:t,From_AccountNick:n,IsNeedReadReceipt:s,IsSyncMsg:i,MsgBody:o,MsgClientTime:r,MsgLifeTime:a,MsgRandom:c,MsgSeq:l,MsgTimeStamp:d,SendMsgControl:u,SupportMessageExtension:h,TinyId:_,MsgCheckResult:g,CloudCustomData:f,RevokerInfo:m}=e;let v,{From_Account:p,To_Account:S}=e;if(1===i){const e=S;S=p,p=e}if(m){const{Reason:e,Revoker_Account:t,Revoker_FromUin:n}=m;v={reason:e,revoker:t,revokerFromUin:n,userID:t}}return{from:p,avatar:t,nick:n,needReadReceipt:1===s,isSyncMessage:i,clientTime:r,messageLifeTime:a,random:c,sequence:l,time:d,messageControlInfo:u,isSupportExtension:h,to:S,tinyID:_,checkResult:g,cloudCustomData:f,revokerInfo:v,elements:Wn(o)}}function Yn(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:Wn(n),messageVersion:c,cloudCustomData:l}}function Hn(e){const{ClientSeq:t,From_Account:n,GroupInfo:s,MsgBody:i,MsgClientTime:o,MsgRandom:r,MsgSeq:a,MsgTimeStamp:c,SendMsgControl:l,SupportMessageExtension:d,TinyId:u,ToGroupId:h,CloudCustomData:_,MsgVersion:g,MsgCheckResult:f,NeedReadReceipt:m,IsPlaceMsg:v,RevokerInfo:p,GroupAtInfo:S}=e;let E,I=Cn.MSG_PRIORITY_NORMAL;if(Object.keys(On).includes(String(e.MsgPriority))&&(I=On[e.MsgPriority]),p){const{Reason:e,Revoker_Account:t,Revoker_FromUin:n}=p;E={reason:e,revoker:t,revokerFromUin:n,userID:t}}const y=function(e){const t=[];Array.isArray(e)&&e.forEach((e=>{e.GroupAtAllFlag===Tn?t.push(e.GroupAt_Account):e.GroupAtAllFlag===bn&&t.push(Pt.MSG_AT_ALL)}));return t}(S);return{clientSequence:t,from:n,groupProfile:s,clientTime:o,priority:I,random:r,sequence:a,time:c,messageControlInfo:l,isSupportExtension:d,to:h,tinyID:u,cloudCustomData:_,messageVersion:g,messageCheckResult:f,needReadReceipt:m,isPlaceMessage:v,revokerInfo:E,atUserList:y,elements:Wn(i)}}function Wn(e){if(!e)return null;if(Array.isArray(e))return e.map((e=>{const t=St.message.messageFactory.getElementClass(e.MsgType);return null==t?void 0:t.parseServerPushElement(e)}));const t=St.message.messageFactory.getElementClass(e.MsgType);return null==t?void 0:t.parseServerPushElement(e)}var zn=Object.freeze({__proto__:null,autoIncrementIndex:wn,parseServerGroupMessage:Hn,parseServerPushC2CModifyMessage:Yn,parseServerPushMessage:Kn,parseServerPushMessageElement:Wn});class Jn{constructor(e){this.value=e,this.next=null}}class Zn{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 Jn(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 Xn{constructor(){this._continuousMessagesByConversation=new Map,this._sparseMessagesByConversation=new Map,this._latestMessageSentByPeerMap=new Map,this._latestMessageSentByMeMap=new Map,this._randomOfSentMessageList=new Zn(100),St.notificationCenter.subscribeInnerEvent(Ot.LOGOUT,this._reset,this),St.notificationCenter.subscribeInnerEvent(Ot.DESTROY,this._dispose,this)}storeConversationMessage(e,t=!1){const{conversationID:n}=e;if(!n)return!1;if(this._continuousMessagesByConversation.has(n)||this._continuousMessagesByConversation.set(n,new Map),this._shouldSkipStoreMessage(e,t))return!1;const s=this._getUniqueIdOfMessage(e);return this._continuousMessagesByConversation.get(n).set(s,e),this._updateLatestMessageMap(e),!0}_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._continuousMessagesByConversation.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!0}return!1}deleteConversationMessage(e){var t;const{conversationID:n=""}=e,s=this._getUniqueIdOfMessage(e);this._continuousMessagesByConversation.has(n)&&(null===(t=this._continuousMessagesByConversation.get(n))||void 0===t||t.delete(s))}modifyConversationMessage(e,t){if(!this._continuousMessagesByConversation.has(e))return{isUpdated:!1,message:null};const n=this._getUniqueIdOfMessage(t),s=this._getMessageFromLocalMessage(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}}_getMessageFromLocalMessage(e,t){var n;return this._continuousMessagesByConversation.has(e)?null===(n=this._continuousMessagesByConversation.get(e))||void 0===n?void 0:n.get(t):null}findMessage(e){let t=null;const n=Array.from(this._continuousMessagesByConversation.values());for(const s of n){if(t=Array.from(s.values()).find((t=>t.ID===e))||null,t)break}if(!t){const n=Array.from(this._sparseMessagesByConversation.values());for(const s of n)if(t=s.get(e)||null,t)break}return t}deleteConversationMessageList(e){this._continuousMessagesByConversation.has(e)&&(this._continuousMessagesByConversation.delete(e),this._latestMessageSentByMeMap.delete(e),this._latestMessageSentByPeerMap.delete(e)),this._sparseMessagesByConversation.has(e)&&this._sparseMessagesByConversation.delete(e)}revokeMessage({conversationID:e,sequence:t,random:n}){const s=this._continuousMessagesByConversation.get(e);let i=null;if(s){const e=Array.from(s.values());for(let s=0;s<e.length;s+=1){const o=e[s];if(o.sequence===t&&(void 0===n||o.random===n)){o.isRevoked=!0,i=o;break}}}return i}prependLocalMessageList(e){const{messageList:t,conversationID:n}=e;if(0===t.length)return[];const s=[],i=[],o=this._continuousMessagesByConversation.get(n)||new Map;for(const e of t){const t=this._getUniqueIdOfMessage(e);o.has(t)||(s.push(e),i.push([t,e]))}if(i.length>0){const e=new Map([...i,...o.entries()]);this._continuousMessagesByConversation.set(n,e),this._updateLatestMessageSentByMe(n),this._updateLatestMessageSentByPeer(n)}return s}storeSparseMessageList(e){if(0===e.length)return;const{conversationID:t}=e[0],n=e.length;this._sparseMessagesByConversation.has(t)||this._sparseMessagesByConversation.set(t,new Map);const s=this._sparseMessagesByConversation.get(t);for(let t=0;t<n;t++){const n=e[t];s.has(n.ID)||s.set(n.ID,n)}}_updateLatestMessageSentByMe(e){var t;const n=Array.from((null===(t=this._continuousMessagesByConversation.get(e))||void 0===t?void 0:t.values())||[]);if(0!==n.length)for(let t=n.length-1;t>=0;t--)if("out"===n[t].flow){this._setLatestMsgSentByMe(e,n[t]);break}}_updateLatestMessageSentByPeer(e){var t;const n=Array.from((null===(t=this._continuousMessagesByConversation.get(e))||void 0===t?void 0:t.values())||[]);if(0!==n.length&&e.startsWith("C2C"))for(let t=n.length-1;t>=0;t--)if("in"===n[t].flow){this._setLatestMsgSentByPeer(e,n[t]);break}}_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._continuousMessagesByConversation.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._continuousMessagesByConversation.has(n))return!1;const s=this._getUniqueIdOfMessage(e);return null===(t=this._continuousMessagesByConversation.get(n))||void 0===t?void 0:t.has(s)}isMessageSentByCurrentInstance(e){const{random:t}=e;return this._randomOfSentMessageList.has(t)}getContinuousMessagesByConversation(){return this._continuousMessagesByConversation}getLocalMessageList(e){const t=this._continuousMessagesByConversation.get(e);return t?[...t.values()]:[]}_reset(){this._continuousMessagesByConversation.clear(),this._latestMessageSentByPeerMap.clear(),this._latestMessageSentByMeMap.clear(),this._randomOfSentMessageList.clear()}_dispose(){this._reset(),St.notificationCenter.unSubscribeInnerEvent(Ot.LOGOUT,this._reset,this),St.notificationCenter.unSubscribeInnerEvent(Ot.DESTROY,this._dispose,this)}}class Qn{init(){Qt("modifyMessage",this)}modifyMessage(e){return a(this,void 0,void 0,(function*(){const t=St.ssoLog.createSSOLogData({method:"modifyMessage"}),{to:n,payload:s,sequence:i,conversationType:o,random:r,time:c,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===yn.CONV_C2C)return s=yield function(e){return a(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=St.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 St.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:c,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 Bt({functionName:"modifyMessage",code:t});throw this._logModifyMessageError(n),n}}))}_logModifyMessageError(e){St.ssoLog.getSSOLogData("modifyMessage").setError(e).end()}_handleC2CModifyMessageSuccess(e){const{conversationID:t}=e,{isUpdated:n,message:s}=St.message.messageStore.modifyConversationMessage(t,e);!0===n&&St.notificationCenter.emitOuterEvent(Ct.MESSAGE_MODIFIED,[s]),St.notificationCenter.emitInnerEvent(Ot.MESSAGE_MODIFIED,{conversationID:t,message:s})}_canModifyMessageElement(e){return[Mn.MSG_TEXT,Mn.MSG_CUSTOM,Mn.MSG_LOCATION,Mn.MSG_FACE].includes(e)}}class es{init(){const{notificationCenter:e}=St,{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(Ot.DESTROY,this._dispose,this)}_handleC2CMessagePush(e){const{messageStore:t}=St.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&&St.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&&St.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:n})}_generateC2CMessage(e){const t=yn.CONV_C2C,n=Kn(e),s=St.message.messageFactory.createMessage(Object.assign(Object.assign({},n),{conversationType:t,flow:Dn.IN})),{elements:i}=n;return s.setElement(i),s}_updateMessageProfile(e){var t;const{messageStore:n}=St.message||{},s=null===(t=St.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}=St.message.messageStore.modifyConversationMessage(t,e);!0===n&&St.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[s]}),St.notificationCenter.emitInnerEvent("ModifyMessageSuccess",e)}_handleC2CMessageModify(e){e.C2cMsgModNotifys.forEach((e=>{var t;const n=yn.CONV_C2C;let s=Yn(e);const{to:i,from:o}=s;let r=`${n}${i}`;i===(null===(t=St.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}=St,{InnerEventSubType:t}=e;St.notificationCenter.unSubscribeInnerEvent("im_open_push.msg_push",t.C2C_REALTIME_MESSAGE,this._handleC2CMessagePush,this),St.notificationCenter.unSubscribeInnerEvent("im_open_push.msg_push",t.C2C_MODIFIED_MESSAGE,this._handleC2CMessageModify,this),St.notificationCenter.unSubscribeInnerEvent(Ot.DESTROY,this._dispose,this)}}class ts{init(){const{notificationCenter:e}=St,{InnerEventSubType:t}=e;e.subscribeInnerEvent("im_open_push.msg_push",t.GROUP_REALTIME_MESSAGE,this._handleGroupMessagePush,this),e.subscribeInnerEvent(Ot.DESTROY,this._dispose,this)}_handleGroupMessagePush(e){const{messageStore:t}=St.message,n=[];e.GroupMsgArray.forEach((e=>{const s=this._generateGroupMessage(e);this.updateMessageProfile(s);let i=1===s.isModified;if(t.isMessageSentByCurrentInstance(s)?s.isModified=i:i=!1,s.isOnlineMessage())s._onlineOnlyFlag=!0,t.isMessageSentByCurrentInstance(s)||n.push(s);else if(!t.isInMessageList(s)){t.storeConversationMessage(s)&&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&&St.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&&St.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:n})}_generateGroupMessage(e){const t=yn.CONV_GROUP,n=Hn(e),s=St.message.messageFactory.createMessage(Object.assign(Object.assign({},n),{conversationType:t,flow:Dn.IN})),{elements:i}=n;return s.setElement(i),s}updateMessageProfile(e){var t;const{messageStore:n}=St.message||{},s=null===(t=St.store.get("login"))||void 0===t?void 0:t.userId,{from:i,nick:o,avatar:r,conversationID:a=""}=e;if(i===s){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}=St.message.messageStore.modifyConversationMessage(t,e);!0===n&&St.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[s]}),St.notificationCenter.emitInnerEvent(Ot.MESSAGE_MODIFIED,e)}_dispose(){const{notificationCenter:e}=St,{InnerEventSubType:t}=e;St.notificationCenter.unSubscribeInnerEvent("im_open_push.msg_push",t.GROUP_REALTIME_MESSAGE,this._handleGroupMessagePush,this),St.notificationCenter.unSubscribeInnerEvent(Ot.DESTROY,this._dispose,this)}}class ns{constructor(){this.c2cMessageReceiver=new es,this.groupMessageReceiver=new ts}init(){this.c2cMessageReceiver.init(),this.groupMessageReceiver.init()}}const ss={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}],createTextMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!(!e.startsWith("C2C")&&!e.startsWith("GROUP"))||"conversationType is invalid."},payload:{required:!0,rules:["object"],allowEmpty:!1,customValidator:e=>function(e){var t;if("string"!=typeof(null==e?void 0:e.text)||"string"==typeof e.text&&0===(null===(t=null==e?void 0:e.text)||void 0===t?void 0:t.length))return"payload.text is invalid.";return!0}(e)}}};const is={createCustomMessage:!0,sendMessage:!0,modifyMessage:!0};class os{constructor(){this.messageHelper=zn,this.messageFactory=new kn,this.messageSender=new Vn,this.messageAction=new Qn,this.messageReceiver=new ns,this.messageStore=new Xn,this.messageSender.init(),this.messageFactory.init(),this.messageAction.init(),this.messageReceiver.init(),Wt({auth:is,params:ss})}}function rs(){return St.store.get("login").userId}const as="User",cs="Tag_Profile_IM_",ls=100,ds={NICK:`${cs}Nick`,GENDER:`${cs}Gender`,BIRTHDAY:`${cs}BirthDay`,LOCATION:`${cs}Location`,SELFSIGNATURE:`${cs}SelfSignature`,ALLOWTYPE:`${cs}AllowType`,LANGUAGE:`${cs}Language`,AVATAR:`${cs}Image`,MESSAGESETTINGS:`${cs}MsgSettings`,ADMINFORBIDTYPE:`${cs}AdminForbidType`,LEVEL:`${cs}Level`,ROLE:`${cs}Role`},us="USER_STATUS",hs=1,_s={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:[]},gs=new Map([[ds.NICK,"nick"],[ds.GENDER,"gender"],[ds.BIRTHDAY,"birthday"],[ds.LOCATION,"location"],[ds.SELFSIGNATURE,"selfSignature"],[ds.ALLOWTYPE,"allowType"],[ds.LANGUAGE,"language"],[ds.AVATAR,"avatar"],[ds.MESSAGESETTINGS,"messageSettings"],[ds.ADMINFORBIDTYPE,"adminForbidType"],[ds.LEVEL,"level"],[ds.ROLE,"role"]]);var fs=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}):gs.has(t)&&(n[gs.get(t)]=s)})),Object.assign(Object.assign({},_s),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:ds[n.toUpperCase()],value:e[n]})})),t}normalizeProfileFields(e){const t={};return e.forEach((e=>{const{tag:n,value:s}=e;if(gs.has(n)){const e=gs.get(n);t[e]=s}})),t}};const{generateProtocolData:ms}=St.common;function vs(e){return a(this,void 0,void 0,(function*(){const t="profile.portrait_get_all",n={From_Account:rs(),UserItem:[]};e.forEach((e=>{n.UserItem.push({CustomSequence:0,StandardSequence:0,To_Account:e})}));const s=ms({servcmd:t,data:n}),i=`${s.head.seq}${t}`,o=yield St.channel.sendPacket(s,{requestId:i});if(o)return 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=fs.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)}))}const{isEmpty:ps}=St.utils;class Ss{constructor(){this._userProfileMap=new Map}init(){Qt("getMyProfile",this),Qt("getUserProfile",this),Qt("updateMyProfile",this),Qt("getFriendProfile",this),this.createProfile=fs.createProfile.bind(fs);const{notificationCenter:e}=St;e.subscribeInnerEvent(Ot.LOGIN,this._handleLoginSuccess,this),e.subscribeInnerEvent("im_open_push.msg_push",e.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),e.subscribeInnerEvent(Ot.LOGOUT,this._reset,this),e.subscribeInnerEvent(Ot.DESTROY,this._dispose,this)}getMyProfile(){return a(this,void 0,void 0,(function*(){const e=St.ssoLog.createSSOLogData({method:"getMyProfile"});try{const t=rs(),n=yield vs([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 Bt({functionName:"getMyProfile",code:n,message:s});throw e.setError(i).end(),t}}))}getUserProfile(e){return a(this,void 0,void 0,(function*(){const t=St.ssoLog.createSSOLogData({method:"getUserProfile"});try{let{userIDList:n}=e;n.length>ls&&(n=n.slice(0,ls));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 vs(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 Bt({functionName:"getUserProfile",code:n});throw t.setError(s).end(),s}}))}getMyProfileCacheThenServer(){return a(this,void 0,void 0,(function*(){const e=rs(),t=this._userProfileMap.has(e);return t?{code:0,data:t}:this.getMyProfile()}))}updateMyProfile(e){return a(this,void 0,void 0,(function*(){const t=St.ssoLog.createSSOLogData({method:"updateMyProfile"}),n=rs(),s={};for(const t in e)void 0!==e[t]&&(s[t]=e[t]);const i=fs.convertParamsToProfile(s);try{const e={From_Account:n,ProfileItem:i};t.setLogInfo({message:JSON.stringify(i)}),yield function(e){return a(this,void 0,void 0,(function*(){const t="profile.portrait_set",n=ms({servcmd:t,data:e}),s=`${n.head.seq}${t}`,i=yield St.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}}}))}(e);const o=this._userProfileMap.get(n);let r;r=o?Object.assign(Object.assign({},o),s):fs.createProfile(n,i);return!$t(o,r,["lastUpdatedTime","profileCustomField"])&&St.notificationCenter.emitOuterEvent(Ct.PROFILE_UPDATED,{name:Ct.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 Bt({functionName:"updateMyProfile",code:n,message:s});throw t.setError(i).end(),i}}))}updateMyNickAndAvatar(e){return a(this,void 0,void 0,(function*(){const t=rs(),n=Date.now(),s=this._userProfileMap.get(t);let i={};i=s?Object.assign(s,e):fs.createProfile(t,e),i.lastUpdatedTime=n,this._userProfileMap.set(t,i)}))}getUserProfileFromCache(e){return this._userProfileMap.get(e)}_handleLoginSuccess(){return a(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:fs.parseProfileList(s)}}(e.ProfileDataMod[0]);if(ps(t))return;const{isProfileUpdated:n,profile:s}=this._handleProfileModified(t);n&&(St.notificationCenter.emitInnerEvent(Ot.PROFILE_UPDATE,{name:Ot.PROFILE_UPDATE,data:[s]}),St.notificationCenter.emitOuterEvent(Ct.PROFILE_UPDATED,{name:Ct.PROFILE_UPDATED,data:[s]}))}_dispose(){const{notificationCenter:e}=St;e.unSubscribeInnerEvent(Ot.LOGIN,this._handleLoginSuccess,this),e.unSubscribeInnerEvent(Ot.LOGOUT,this._reset,this),e.unSubscribeInnerEvent("im_open_push.msg_push",e.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),e.unSubscribeInnerEvent(Ot.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=fs.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}}_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&&!ps(e.profileItem))),s=Date.now();return n.map((e=>{const t=fs.createProfile(e.userId,e.profileItem);return t.lastUpdatedTime=s,t}))}_reset(){this._userProfileMap.clear()}}const Es=new Map,Is=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];for(let e=0,t=Is.length;e<t;e++)Es.set(e,Is[e]);function ys(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:Cs}=St.utils,{generateProtocolData:Ms}=St.common;function Os(e){return a(this,void 0,void 0,(function*(){const t="im_open_status.ws_get_user_status",n=Ms({servcmd:t,data:{To_Account:e}}),s=`${n.head.seq}${t}`,i=yield St.channel.sendPacket(n,{requestId:s});if(i)return 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:ys(s)}})),r=s.map((e=>{const{To_Account:t,Invalid_Account:n,ErrorCode:s,ErrorInfo:i}=e;return{userID:Cs(n)?t:n,code:s,message:i}}));return{errorCode:t,errorInfo:n,successUserList:o,failureUserList:r}}(i)}))}class Ts{constructor(){this._customStatus=""}init(){const{notificationCenter:e}=St;Qt("getUserStatus",this),Qt("setSelfStatus",this),Qt("subscribeUserStatus",this),Qt("unsubscribeUserStatus",this),e.subscribeInnerEvent(Ot.MESSAGE_PUSH,e.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),e.subscribeInnerEvent(Ot.RE_LOGIN,this._onReLogin,this),e.subscribeInnerEvent(Ot.LOGOUT,this._reset,this),e.subscribeInnerEvent(Ot.DESTROY,this._dispose,this)}setSelfStatus(e){return a(this,void 0,void 0,(function*(){const t=St.ssoLog.createSSOLogData({method:"setSelfStatus"}),n=rs(),{customStatus:s}=e;try{return yield function(e){return a(this,void 0,void 0,(function*(){const t="im_open_status.ws_set_custom_status",n=Ms({servcmd:t,data:{CustomStatus:e}}),s=`${n.head.seq}${t}`,i=yield St.channel.sendPacket(n,{requestId:s});if(i){const{ErrorCode:e,ErrorInfo:t}=i;return{errorCode:e,errorInfo:t}}}))}(s),this._customStatus=s,t.setLogInfo({message:`customStatus: ${s}`}).end(),{code:0,data:{userID:n,statusType:hs,customStatus:s}}}catch(e){const{errorCode:n,errorInfo:s}=e,i=new Bt({functionName:"setSelfStatus",code:n,message:s});throw t.setError(i).end(),i}}))}getUserStatus(e){return a(this,void 0,void 0,(function*(){const t=St.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=ys(e);this._customStatus=t}subscribeUserStatus(e){return a(this,void 0,void 0,(function*(){try{console.log(`${as} subscribeUserStatus options: `,e);const{userIDList:t=[]}=e;this._checkBusinessCapabilityBits("subscribeUserStatus");const n=this._getMaxUserCount("subscribe"),s=this._truncateUserIDList(t,n),i=yield function(e){return a(this,void 0,void 0,(function*(){const{channel:t}=St,n="im_open_status.ws_status_subscribe",s=Ms({servcmd:n,data:{To_Account:e}}),i=`${s.head.seq}${n}`;return yield t.sendPacket(s,{requestId:i})}))}(s);return{code:0,data:{failureUserList:this._parseResponse(i)}}}catch(e){throw console.error(`${as} subscribeUserStatus error:`,e),e}}))}unsubscribeUserStatus(e){return a(this,void 0,void 0,(function*(){try{console.log(`${as} unsubscribeUserStatus options: `,e),this._checkBusinessCapabilityBits("unsubscribeUserStatus");const{userIDList:t=[]}=e,n=this._getMaxUserCount("unsubscribe"),s=this._truncateUserIDList(t,n),i=yield function(e){return a(this,void 0,void 0,(function*(){const{channel:t}=St,n="im_open_status.ws_status_unsubscribe";let s={};s=0===e.length?{UnsubscribeAll:1}:{To_Account:e};const i=Ms({servcmd:n,data:s}),o=`${i.head.seq}${n}`;return yield t.sendPacket(i,{requestId:o})}))}(s);return{code:0,data:{failureUserList:this._parseResponse(i)}}}catch(e){throw console.error(`${as} unsubscribeUserStatus error:`,e),e}}))}_onUserStatusUpdate(e){const{UserStatusList:t=[]}=e||{},n=t.map((e=>{const{To_Account:t,Status:n,CustomStatus:s}=e;return{userID:t,statusType:n,customStatus:ys(s)}}));this._emitUserStatusUpdatedEvent(n)}_onReLogin(e){const t=ys(e.customStatus);if(this._customStatus===t)return;this._customStatus=t;const n={userID:rs(),statusType:hs,customStatus:t};this._emitUserStatusUpdatedEvent(n)}_emitUserStatusUpdatedEvent(e){St.notificationCenter.emitOuterEvent(Ct.USER_STATUS_UPDATED,{name:Ct.USER_STATUS_UPDATED,data:e})}_truncateUserIDList(e,t){return e.length>t?e.slice(0,t):[...e]}_parseResponse(e){const{ErrorList:t=[]}=e;return t.map((e=>{const{To_Account:t,Invalid_Account:n,ErrorCode:s,ErrorInfo:i}=e;return{userID:St.utils.isEmpty(n)?t:n,code:s,message:i}}))}_checkBusinessCapabilityBits(e){if(!St.store.get("commercialConfig").get(us))throw new Bt({functionName:e,code:Ut.NO_USE,replacement1:e})}_getMaxUserCount(e){const t=St.store.get("cloudConfig")||{},n={query:{key:"status_query_count",default:500},subscribe:{key:"status_sub_count",default:ls},unsubscribe:{key:"status_unsub_count",default:ls}},{key:s,default:i}=n[e],o=t[s]||i;return parseInt(o,10)}_getMyStatus(){const e=St.ssoLog.getSSOLogData("getUserStatus");e.setLogInfo({moreMessage:"getUserStatus._getMyStatus"});const t={userID:rs(),statusType:hs,customStatus:this._customStatus};return e.end(),{code:0,data:{successUserList:[t],failureUserList:[]}}}_getUserStatus(e){return a(this,void 0,void 0,(function*(){const t=St.ssoLog.getSSOLogData("getUserStatus");t.setLogInfo({moreMessage:"getUserStatus._getUserStatus"});try{this._checkBusinessCapabilityBits("getUserStatus");const n=this._getMaxUserCount("query"),s=this._truncateUserIDList(e,n),i=yield Os(s),{successUserList:o,failureUserList:r}=i||{};return t.end(),{code:0,data:{successUserList:o,failureUserList:r}}}catch(e){const{errorCode:n}=e,s=new Bt({functionName:"getUserStatus",code:n});throw t.setError(s).end(),s}}))}_isOnlyMeInArray(e){const t=rs();return 1===e.length&&e.indexOf(t)>-1}_dispose(){const{notificationCenter:e}=St;e.unSubscribeInnerEvent(Ot.MESSAGE_PUSH,e.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),e.unSubscribeInnerEvent(Ot.RE_LOGIN,this._onReLogin,this),e.unSubscribeInnerEvent(Ot.DESTROY,this._dispose,this),e.unSubscribeInnerEvent(Ot.LOGOUT,this._reset,this),this._reset()}_reset(){this._customStatus=""}}const bs={getUserProfile:{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}},subscribeUserStatus:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}},unsubscribeUserStatus:{userIDList:{required:!1,rules:["array"],allowEmpty:!0}}},Ds={getMyProfile:!0,getUserProfile:!0,updateMyProfile:!0,setSelfStatus:!0,getUserStatus:!0,subscribeUserStatus:!0,unsubscribeUserStatus:!0};class As{constructor(){this.userProfile=new Ss,this.userStatus=new Ts,this.userProfile.init(),this.userStatus.init(),Wt({auth:Ds,params:bs})}}const ws=[{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}],Rs={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"},Ns="im_sdk_config_mgr.fetch_config",Ls="im_sdk_config_mgr.push_configv2",ks="cloud-config";var Ps=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(Ls,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(ws)}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=Rs[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 a(this,void 0,void 0,(function*(){try{const{sdkAppId:e}=this._core.store.get("instance")||{},t=this._core.helper.generateProtocolData({servcmd:Ns,data:{uint32_sdkappid:e,uint64_version:this._version}}),n=`${t.head.seq}${Ns}`;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 a(this,void 0,void 0,(function*(){try{if(this._canFetch()){const e=yield this._fetchCloudConfig();this._updateCloudConfig(e)}this._core.helper.taskScheduler.addTask({id:ks,intervalMs:1e3,callback:this._fetchCloudConfigIfReady,context:this})}catch(e){console.warn(e)}}))}_fetchCloudConfigIfReady(){return a(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(ks),this._core.store.clear("cloudConfig"),this._updateCmdFreqLimitMap(ws),this._methodCallFrequencyMap.clear(),this._expirationTime=0,this._version=0,this._isFetching=!1}_dispose(){const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(Ls,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 Us{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 Fs={SEARCH_GRP_SNS:new Us(0,Math.pow(2,1)).toString(),AV_HISTORY_MSG:new Us(0,Math.pow(2,2)).toString(),GRP_COMMUNITY:new Us(0,Math.pow(2,3)).toString(),MSG_TO_SPECIFIED_GRP_MBR:new Us(0,Math.pow(2,4)).toString(),AV_MBR_LIST:new Us(0,Math.pow(2,6)).toString(),USER_STATUS:new Us(0,Math.pow(2,7)).toString(),CONV_MARK:new Us(0,Math.pow(2,9)).toString(),CONV_GROUP:new Us(0,Math.pow(2,10)).toString(),AV_BAN_MBR:new Us(0,Math.pow(2,11)).toString(),MSG_EXT:new Us(0,Math.pow(2,13)).toString(),GRP_COUNTER:new Us(0,Math.pow(2,15)).toString(),PLUGIN_TRANSLATE:new Us(Math.pow(2,6)).toString(),PLUGIN_VOICE_TO_TEXT:new Us(Math.pow(2,7)).toString(),PLUGIN_CS:new Us(Math.pow(2,8)).toString(),PLUGIN_PUSH:new Us(Math.pow(2,9)).toString(),PLUGIN_BOT:new Us(Math.pow(2,10)).toString(),MSG_REACTION:new Us(Math.pow(2,16)).toString(),FOLLOW:new Us(Math.pow(2,20)).toString()},Gs="CommercialConfig",Bs="commercial-config";var xs=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){return a(this,void 0,void 0,(function*(){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 Us(0,2**o).toString():new Us(2**(o-32),0).toString(),!this._featureMap.get(s))){i=!1;break}return console.log(`${Gs}.isFeatureEnabled decimalNumber:${e} key:${s} ret:${i}`),{code:0,data:{enabled:i}}}))}_fetchAndParseCommercialConfig(){return a(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 a(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:Bs,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 a(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(`${Gs}._parseCommercialConfig failed. Invalid message format:`,e),this._expirationTime=Date.now()+36e5):(console.error(`${Gs}._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 Us(0,2**s).toString():new Us(2**(s-32),0).toString(),"1"===e[n]){this._featureMap.set(t,!0);const e=this._getKeyByValue(Fs,t);e&&this._methodKeyMap.set(e,!0)}else{this._featureMap.set(t,!1);const e=this._getKeyByValue(Fs,t);e&&this._methodKeyMap.set(e,!1)}}else console.warn(`${Gs}.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(Bs),this._core.store.set("commercialConfig",{}),this._expirationTime=0,this._isFetching=!1,this._featureMap.clear()}};var $s=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=Rs[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 qs=new class{constructor(){this._core=null}install(e){return a(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 a(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}}};function js(e,t){return a(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,revokedMessageList:s}=function(e,t){const n=[],s=[];return null==e||e.forEach((e=>{var i,o,r;const a=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:f,CloudCustomData:m,IsPeerRead:v,MsgFlagBits:p,MsgVersion:S,EventArray:E}=e;return{from:n,avatar:s,nick:i,needReadReceipt:1===o,readReceiptSentByPeer:v,clientTime:a,messageFlagBits:p,random:c,sequence:l,time:d,messageControlInfo:u,isSupportExtension:h,to:_,tinyID:g,checkResult:f,cloudCustomData:m,messageVersion:S,eventArray:E,elements:t.message.messageHelper.parseServerPushMessageElement(r)}}(e,t);if(null===(r=null===(o=null===(i=null==a?void 0:a.eventArray)||void 0===i?void 0:i[0])||void 0===o?void 0:o.hasOwnProperty)||void 0===r?void 0:r.call(o,"c2cMessageRevokedNotify"))s.push(a);else{const e=t.message.messageFactory.createMessage(Object.assign(Object.assign({},a),{conversationType:"C2C",flow:"in"})),{elements:s}=a;e.setElement(s),n.push(e)}})),{unreadMessageList:n,revokedMessageList:s}}(e.MsgList,t);return{syncFlag:null==e?void 0:e.SyncFlag,unreadMessageList:n,revokedMessageList:s,cookie:null==e?void 0:e.Cookie}}catch(e){console.warn(e)}}))}var Vs,Ks;!function(e){e[e.START_SYNC=0]="START_SYNC",e[e.SYNCING=1]="SYNCING",e[e.SYNC_COMPLETE=2]="SYNC_COMPLETE"}(Vs||(Vs={})),function(e){e[e.LOGIN_SUCCESS=0]="LOGIN_SUCCESS",e[e.SEND_MESSAGE=1]="SEND_MESSAGE"}(Ks||(Ks={}));var Ys=new class{constructor(){this._unreadDBMessageMap=new Map,this._revokedMessageList=[]}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 a(this,void 0,void 0,(function*(){let e=Vs.START_SYNC,t="";for(;this._canContinueSync({cookie:t,syncFlag:e});){const n=yield this._fetchUnreadDBMessage({cookie:t,syncFlag:e,syncTriggerEvent:Ks.LOGIN_SUCCESS});if(!n)break;const{unreadMessageList:s=[],revokedMessageList:i=[]}=n;t=(null==n?void 0:n.cookie)||"",e=null==n?void 0:n.syncFlag,this._parseAndSaveUnreadMessageList(s),this._saveRevokedMessageList(i)}this._emitUnreadMessageSyncComplete()}))}_emitUnreadMessageSyncComplete(){var e;null===(e=this._core)||void 0===e||e.notificationCenter.emitInnerEvent(this._core.InnerEvent.UNREAD_MESSAGES_SYNC_COMPLETED,{revokedMessageList:this._revokedMessageList,unreadMessageMap:this._unreadDBMessageMap})}_saveRevokedMessageList(e){this._revokedMessageList=[...this._revokedMessageList,...e]}_fetchUnreadDBMessage(e){return a(this,void 0,void 0,(function*(){try{const t="unread-message-synchronizer._fetchUnreadDBMessage";console.log(`${t} options:`,e);const n=yield js(e,this._core);if(!n)return null;const{syncFlag:s,unreadMessageList:i,revokedMessageList:o,cookie:r}=n;return this._parseAndSaveUnreadMessageList(i),{syncFlag:s,cookie:r,unreadMessageList:i,revokedMessageList:o}}catch(e){console.log(e)}}))}_canContinueSync({cookie:e,syncFlag:t}){var n;return t===Vs.START_SYNC||t===Vs.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._revokedMessageList=[]}_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()}};var Hs=new class{init(e){var t;this._core=e,this._visibilityChangeHandler=this._handleVisibilityChange.bind(this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this),document.addEventListener("visibilitychange",this._visibilityChangeHandler),null===(t=this._core)||void 0===t||t.store.set("activityMonitor",{isActive:!0})}_handleVisibilityChange(){var e,t;const n="visible"===document.visibilityState;null===(e=this._core)||void 0===e||e.store.set("activityMonitor",{isActive:n}),null===(t=this._core)||void 0===t||t.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:n})}_reset(){var e;null===(e=this._core)||void 0===e||e.store.clear("activityMonitor")}_dispose(){document.removeEventListener("visibilitychange",this._visibilityChangeHandler);const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this),this._reset()}};var Ws=new class{init(e){var t;this._core=e,this._bindAppActivityEvent(),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this),null===(t=this._core)||void 0===t||t.store.set("activityMonitor",{isActive:!0})}_bindAppActivityEvent(){var e;const{MINI_APP_NAMESPACE:t}=(null===(e=this._core)||void 0===e?void 0:e.utils)||{};t.onAppShow((()=>{var e,t;null===(e=this._core)||void 0===e||e.store.set("activityMonitor",{isActive:!0}),null===(t=this._core)||void 0===t||t.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!0})})),t.onAppHide((()=>{var e,t;null===(e=this._core)||void 0===e||e.store.set("activityMonitor",{isActive:!1}),null===(t=this._core)||void 0===t||t.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!1})}))}_reset(){var e;null===(e=this._core)||void 0===e||e.store.clear("activityMonitor")}_dispose(){const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this),this._reset()}};var zs=new class{init(e){const{IN_WX_MINI_APP:t}=e.helper;t?Ws.init(e):Hs.init(e)}};const Js="none",Zs="online";var Xs=new class{init(e){this._core=e,this._activateNetworkMonitoring(),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return a(this,void 0,void 0,(function*(){navigator.onLine?this._onOnline():this._onOffline(),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:Zs})}_onOffline(){this._onNetworkStatusChange({isConnected:!1,networkType:Js})}_reset(){var e;this._deactivateNetworkMonitoring(),null===(e=this._core)||void 0===e||e.store.clear("netWorkMonitor")}_dispose(){var e,t;null===(e=this._core)||void 0===e||e.notificationCenter.unSubscribeInnerEvent(null===(t=this._core)||void 0===t?void 0:t.InnerEvent.DESTROY,this._dispose,this),this._reset()}};var Qs=new class{init(e){this._core=e,this._activateNetworkMonitoring(),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return a(this,void 0,void 0,(function*(){try{wx.getNetworkType().then((e=>{const{isConnected:t,networkType:n}=e;this._onNetworkStatusChange({isConnected:t,networkType:n})})),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;null===(e=this._core)||void 0===e||e.notificationCenter.unSubscribeInnerEvent(null===(t=this._core)||void 0===t?void 0:t.InnerEvent.DESTROY,this._dispose,this),this._reset()}};var ei=new class{init(e){const{IN_WX_MINI_APP:t}=e.helper;t?Qs.init(e):Xs.init(e)}};var ti=new class{install(e){zs.init(e),ei.init(e)}};const ni=1,si=2,ii=3,oi=4,ri=5,ai="TIMCustomElem",ci="C2C",li="GROUP",di="invite",ui="accept",hi="cancel",_i="reject",gi="modifyInvitation",fi="signaling",mi=8010,vi="signaling-timeout";function pi(e){return e.filter((e=>{if(e.type===ai){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 Si(e){const{data:t}=e.payload;try{return JSON.parse(t)}catch(e){return console.error(e),null}}function Ei(e,t){return e.toString(16).padStart(t,"0")}function Ii(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 yi=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=`${fi}.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=`${fi}.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 Ci=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=yi.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===ri&&!!e.match(/excludeTimeoutSignalingFromHistoryMessage/),s=!!e.match(/excludeFromHistoryMessage/)||!!e.match(/excludeOriginalSignalingFromHistoryMessage/);return{excludedFromContentModeration:!0,excludedFromUnreadCount:n||s,excludedFromLastMessage:n||s}}_createInviteSignalingData(e){const t=`${fi}._createInviteSignalingData`,{userID:n,timeout:s=0,groupID:i="",inviteeList:o=[]}=e,r=this._getCurrentUserId(),a=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:ni,inviter:r,inviteeList:i?o:[n],timeout:s});return console.log(`${t} signalingData:`,a),a}_createAcceptSignalingData(e){const t=`${fi}._createAcceptSignalingData`,{inviteID:n}=e,s=this._getCurrentUserId(),{inviter:i,groupID:o}=yi.getSignaling(n),r=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:ii,groupID:o,inviter:i,inviteeList:[s]});return console.log(`${t} signalingData:`,r),r}_createCancelSignalingData(e){const t=`${fi}._createCancelSignalingData`,{inviteID:n}=e,s=this._getCurrentUserId(),{inviteeList:i,groupID:o}=yi.getSignaling(n),r=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:si,groupID:o,inviter:s,inviteeList:i});return console.log(`${t} signalingData:`,r),r}_createRejectSignalingData(e){const t=`${fi}._createRejectSignalingData`,{inviteID:n}=e,s=this._getCurrentUserId(),{inviter:i,groupID:o}=yi.getSignaling(n),r=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:oi,groupID:o,inviter:i,inviteeList:[s]});return console.log(`${t} signalingData:`,r),r}_createTimeoutSignalingData(e){const t=`${fi}._createTimeoutSignalingData`,{isInviter:n=!1,inviteID:s}=e,{inviteeList:i,inviter:o}=yi.getSignaling(s),r=this._getCurrentUserId(),a=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:ri,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?li:ci,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[Ei(Ii(32),8),Ei(Ii(16),4),Ei(16384|Ii(12),4),Ei(32768|Ii(14),4),Ei(Ii(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 Mi=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 a(this,void 0,void 0,(function*(){var t;console.log(`${fi}.invite params:${JSON.stringify(e)}`);try{this._validateBeforeInvite(e);const{signaling:n,signalingData:s,signalingExtensionOptions:i}=Ci.createInviteSignaling(e),o=yield this._sendSignaling(n,i);if(0===(null==o?void 0:o.code)){const{inviteID:e,timeout:i}=s;return yi.saveSignaling(e,Object.assign(Object.assign({},s),{signaling:n})),i>0&&(null===(t=this._core)||void 0===t||t.helper.taskScheduler.addOnceTask({id:`${vi}-${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(`${fi}.invite error:${e}`),e}}))}accept(e){return a(this,void 0,void 0,(function*(){console.log(`${fi}.accept params:${JSON.stringify(e)}`);try{const{inviteID:t}=e;this._validateBeforeAccept(t),this._isProcessingSignaling=!0;const{signaling:n,signalingData:s,signalingExtensionOptions:i}=Ci.createAcceptSignaling(e),o=yield this._sendSignaling(n,i);return 0===(null==o?void 0:o.code)?(yi.updateSignaling(s),Object.assign(Object.assign({},o),{inviteID:t})):o}catch(e){throw console.error(`${fi}.accept error:${e}`),e}finally{this._isProcessingSignaling=!1}}))}cancel(e){return a(this,void 0,void 0,(function*(){console.log(`${fi}.cancel params:${JSON.stringify(e)}`);try{const{inviteID:t}=e;this._validateBeforeCancel(t),this._isProcessingSignaling=!0;const{signaling:n,signalingExtensionOptions:s}=Ci.createCancelSignaling(e),i=yield this._sendSignaling(n,s);return 0===(null==i?void 0:i.code)?(yi.removeSignaling(t),Object.assign(Object.assign({},i),{inviteID:t})):i}catch(e){throw console.error(`${fi}.cancel error:${e}`),e}finally{this._isProcessingSignaling=!1}}))}reject(e){return a(this,void 0,void 0,(function*(){console.log(`${fi}.reject params:${JSON.stringify(e)}`);try{const{inviteID:t}=e;this._validateBeforeReject(t),this._isProcessingSignaling=!0;const{signaling:n,signalingExtensionOptions:s}=Ci.createRejectSignaling(e),i=yield this._sendSignaling(n,s);return 0===(null==i?void 0:i.code)?(yi.removeSignaling(t),Object.assign(Object.assign({},i),{inviteID:t})):i}catch(e){throw console.error(`${fi}.reject error:${e}`),e}finally{this._isProcessingSignaling=!1}}))}modifyInvitation(e){return a(this,void 0,void 0,(function*(){var t,n;console.log(`${fi}.modifyInvitation params:${JSON.stringify(e)}`);const{inviteID:s,data:i}=e;let o="";try{this._validateBeforeModifyInvitation(s);const e=yi.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 yi.hasSignaling(s)&&yi.saveSignaling(s,Object.assign(Object.assign({},a),{signaling:r})),c}catch(e){if(o){const{signaling:e}=yi.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)&&yi.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)&&yi.setSignalingListenStatus(!1),null===(i=this._core)||void 0===i||i.notificationCenter.unSubscribeOuterEvent(e,t,n)}handleInvitationExpiryTimer(e){const t=yi.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 a(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 a(this,void 0,void 0,(function*(){var t,n,s;console.log(`${fi}._sendTimeoutNotice params:${JSON.stringify(e)}`);const{isInviter:i,inviteID:o}=e,{signaling:r,signalingData:a,signalingExtensionOptions:c}=Ci.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?yi.removeSignaling(o):yi.updateSignaling(a)}}))}_validateInviteId(e,t){if(!yi.hasSignaling(t))throw new this._core.helper.ChatError({functionName:e,code:mi})}_validateProcessStatus(e){if(this._isProcessingSignaling)throw new this._core.helper.ChatError({functionName:e,message:"processing other signaling operations"})}_validateBeforeInvite(e){const t=di,{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=ui;this._validateInviteId(t,e),this._validateProcessStatus(t);const n=this._getCurrentUserId(),{inviteeList:s}=yi.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=hi;this._validateInviteId(t,e),this._validateProcessStatus(t);const n=this._getCurrentUserId(),{inviter:s}=yi.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=_i;this._validateInviteId(t,e),this._validateProcessStatus(t);const n=this._getCurrentUserId(),{inviteeList:s}=yi.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=gi;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 Oi=new class{constructor(){this._actionProcessor=new Map([[ni,this._onNewInvitationReceived.bind(this)],[oi,this._onInviteeRejected.bind(this)],[ii,this._onInviteeAccepted.bind(this)],[si,this._onInvitationCancelled.bind(this)],[ri,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=Si(e);if(t){const n=this._actionProcessor.get(t.actionType);null==n||n(t,e)}}))}_handleMessageReceived(e){if(!yi.getSignalingListenStatus())return;const t=pi(e.data);0!==t.length&&this.handleActionSignaling(t)}_handleMessageModified(e){if(!yi.getSignalingListenStatus())return;const t=pi(e.data);t.length>0&&t.forEach((e=>{const t=Si(e);t&&this._onInvitationModified(t,e)}))}_onNewInvitationReceived(e,t){var n,s;const i=`${fi}._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=yi.getSignaling(o);u!==e&&(u||yi.saveSignaling(o,Object.assign(Object.assign({},e),{signaling:t})),l>0&&(null===(n=this._core)||void 0===n||n.helper.taskScheduler.addOnceTask({id:`${vi}-${o}`,intervalMs:1e3*l,callback:Mi.handleInvitationExpiryTimer.bind(Mi,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=`${fi}._onInviteeRejected`,{inviteID:s,inviter:i,groupID:o,inviteeList:r}=e,a=yi.hasSignaling(s);console.log(`${n} inviteID:${s} hasInviteID:${a} inviter:${i} groupID:${o}`),a&&(yi.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=`${fi}._onInviteeAccepted`,{inviteID:s,inviter:i,groupID:o,inviteeList:r}=e,a=yi.hasSignaling(s);console.log(`${n} inviteID:${s} hasInviteID:${a} inviter:${i} groupID:${o}`),a&&(yi.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=`${fi}._onInvitationCancelled`,{inviteID:s,inviter:i,groupID:o}=e,r=yi.hasSignaling(s);console.log(`${n} inviteID:${s} hasInviteID:${r} inviter:${i} groupID:${o}`),r&&(yi.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=`${fi}._onInvitationTimeout`,{inviteID:s,inviteeList:i}=e,o=yi.hasSignaling(s);console.log(`${n} inviteID:${s} hasInviteID:${o} data:${e.data}`),o&&(yi.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=`${fi}._onInvitationModified`,{inviteID:i,data:o}=e,r=yi.hasSignaling(i);console.log(`${s} inviteID:${i} data:${o}`),r&&(yi.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 Ti=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)&&yi.getSignalingListenStatus()))return;const t=pi([...e.unreadMessageMap.values()]);if(0!==t.length&&(t.forEach((e=>{this._handleC2CActionType(e)})),this._offlineSignalingMap.size>0)){const e=this._sortOfflineSignalingByTime();Oi.handleActionSignaling(e)}}_handleC2CActionType(e){const t=Si(e);if(!t)return;const{actionType:n}=t;n===ni?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 bi={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}}},Di={invite:!0,cancel:!0,accept:!0,reject:!0,modifyInvitation:!0};var Ai=new class{install(e){Mi.init(e),Oi.init(e),Ci.init(e),yi.init(e),Ti.init(e),e.helper.registerValidateConfig({auth:Di,params:bi})}};const wi=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.*"]),Ri="tui_room_svr.*";var Ni=new class{constructor(){this._transferredCommands=wi}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 a(this,void 0,void 0,(function*(){const t="transferBusinessCommand";try{const{serviceCommand:n=Ri}=e||{};if(!this._isValidTransferredCommand(n))throw new this._core.helper.ChatError({code:2995,functionName:t});const s=yield function(e,t){return a(this,void 0,void 0,(function*(){const{helper:n,channel:s}=t,{serviceCommand:i=Ri,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,message:null==e?void 0:e.errorInfo,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=wi}_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 Li=new Map,ki=[qs,function(e){Ps.install(e),xs.install(e),$s.install(e)},Ys,ti,Ni,Ai];console.log(`TencentCloudLiteChat.VERSION:${It}`);var Pi={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),Li.has(i))return Li.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()}`}();St.init({sdkAppId:i,instanceId:o,testEnv:n,devMode:s}),St.message=new os,St.user=new As,St.login=new In,zt.installBuiltInPlugin(ki);const r=Zt;return Li.set(i,r),r},TSignaling:Tt,EVENT:Ct,VERSION:It,TYPES:Pt};e.default=Pi,e.liteChatInstanceMap=Li,Object.defineProperty(e,"__esModule",{value:!0})}));