@tencentcloud/lite-chat 1.2.0 → 1.2.1

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/basic.es.js ADDED
@@ -0,0 +1 @@
1
+ class e{constructor(){this.listeners={}}on(e,t,s){this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push({fn:t,context:s})}off(e,t,s){var n;t&&(this.listeners[e]=null===(n=this.listeners[e])||void 0===n?void 0:n.filter((e=>{const n=e.fn===t,o=!s||e.context===s;return!(n&&o)})))}emit(e,...t){const s=this.listeners[e];s&&s.forEach((e=>{const{fn:s,context:n}=e;s.apply(n,t)}))}once(e,t,s){const n=(...o)=>{t.apply(s,o),this.off(e,n)};this.on(e,n)}}var t;!function(e){e.BUSINESS_COMMAND="business_command",e.C2C_REALTIME_MESSAGE="c2c_realtime_message",e.C2C_MESSAGE_MODIFIED="c2c_message_modified",e.C2C_REVOKED_MESSAGE="c2c_message_revoked",e.GROUP_REALTIME_MESSAGE="group_realtime_message",e.GROUP_MESSAGE_MODIFIED="group_message_modified",e.GROUP_MESSAGE_REVOKED="group_message_revoked",e.C2C_MESSAGE_READ_RECEIPT="c2c_message_read_receipt",e.MESSAGE_REACTION_UPDATED="message_reaction_updated",e.MESSAGE_REACTION_UPDATED_SYNC="message_reaction_updated_sync",e.GROUP_AT_TIPS="group_at_tips",e.USER_STATUS_UPDATE="user_status_update",e.FRIEND_LIST_MODIFIED="friend_list_modified",e.PROFILE_MODIFIED="profile_modified",e.CONV_MODIFIED="conversation_modified",e.GROUP_TIPS_NOTIFICATION="group_tips_notification",e.GROUP_MESSAGE_READ_RECEIPT="group_message_read_receipt",e.GROUP_MESSAGE_READ_SYNC="group_message_read_sync",e.GROUP_SYSTEM_NOTIFICATION="group_system_notification",e.C2C_MESSAGE_PEER_READ="c2c_message_peer_read",e.C2C_MESSAGE_READ_SYNC="c2c_message_read_sync",e.C2C_REMIND_TYPE_SYNC="c2c_remind_type_sync",e.FOLLOW_LIST_UPDATED="follow_list_updated"}(t||(t={}));const s=[{conditions:[{type:"event",value:100}],subType:t.BUSINESS_COMMAND},{conditions:[{type:"hasKey",value:"C2cMsgArray"}],subType:t.C2C_REALTIME_MESSAGE},{conditions:[{type:"hasKey",value:"C2cMsgModNotifys"}],subType:t.C2C_MESSAGE_MODIFIED},{conditions:[{type:"hasKey",value:"ProfileDataMod"}],subType:t.PROFILE_MODIFIED},{conditions:[{type:"hasKey",value:"UserStatusList"}],subType:t.USER_STATUS_UPDATE},{conditions:[{type:"hasKey",value:"FriendListMod"}],subType:t.FRIEND_LIST_MODIFIED},{conditions:[{type:"hasKey",value:"GroupMsgArray"}],subType:t.GROUP_REALTIME_MESSAGE},{conditions:[{type:"hasKey",value:"GroupMsgModNotifys"}],subType:t.GROUP_MESSAGE_MODIFIED},{conditions:[{type:"hasKey",value:"C2cNotifyMsgArray"}],subTypeParser:function(e){var s;const n=[];return null===(s=null==e?void 0:e.C2cNotifyMsgArray)||void 0===s||s.forEach((e=>{e.WithdrawC2cMsgNotify&&n.push(t.C2C_REVOKED_MESSAGE),e.C2cReadedReceipt&&n.push(t.C2C_MESSAGE_PEER_READ),e.ReadC2cMsgNotify&&n.push(t.C2C_MESSAGE_READ_SYNC),e.MuteNotificationsSync&&n.push(t.C2C_REMIND_TYPE_SYNC)})),n}},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:4}],subType:t.GROUP_TIPS_NOTIFICATION},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:5}],subTypeParser:function(e){var s;const n=[];return null===(s=null==e?void 0:e.GroupTips)||void 0===s||s.forEach((e=>{Array.isArray(e.MsgBody.GroupWithdrawInfoArray)&&n.push(t.GROUP_MESSAGE_REVOKED),Array.isArray(e.MsgBody.GroupMsgReceiptList)&&n.push(t.GROUP_MESSAGE_READ_RECEIPT),Array.isArray(e.MsgBody.GroupReadInfoArray)?n.push(t.GROUP_MESSAGE_READ_SYNC):n.push(t.GROUP_SYSTEM_NOTIFICATION)})),n}},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:6}],subType:t.GROUP_TIPS_NOTIFICATION},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:12}],subType:t.GROUP_AT_TIPS},{conditions:[{type:"hasKey",value:"RecentContactMod"}],subType:t.CONV_MODIFIED},{conditions:[{type:"hasKey",value:"MsgReactionNotifyList"}],subType:t.MESSAGE_REACTION_UPDATED},{conditions:[{type:"hasKey",value:"MsgReactionNotify"}],subType:t.MESSAGE_REACTION_UPDATED_SYNC},{conditions:[{type:"hasKey",value:"C2cMsgInfo"}],subType:t.C2C_MESSAGE_READ_RECEIPT},{conditions:[{type:"hasKey",value:"FollowChangeList"}],subType:t.FOLLOW_LIST_UPDATED}];var n;!function(e){e.SERVER_PUSH_MESSAGE="im_open_push.msg_push",e.ERROR="error"}(n||(n={}));const o={[n.SERVER_PUSH_MESSAGE]:function(e){var t;const o=Array.isArray(null===(t=null==e?void 0:e.body)||void 0===t?void 0:t.EventArray)?e.body.EventArray:[],i=[];return o.forEach((t=>{t.Flag=e.body.Flag;const o=s.find((e=>e.conditions.every((e=>{switch(e.type){case"event":return t.Event===e.value;case"hasKey":return Object.prototype.hasOwnProperty.call(t,e.value);default:return!1}}))));if(!o)return null;let r=[];"function"==typeof o.subTypeParser?r=o.subTypeParser(t):o.subType&&(r=o.subType),Array.isArray(r)?r.forEach((e=>{i.push({type:`${n.SERVER_PUSH_MESSAGE}:${e}`,data:t})})):i.push({type:`${n.SERVER_PUSH_MESSAGE}:${r}`,data:t})})),i},[n.ERROR]:function(e){const{errorCode:t}=e;return[{type:`error:${t}`,data:e}]}};const i=new class{constructor(){this._outerEventEmitter=null,this._innerEventEmitter=null,this._outerEventEmitter=new e,this._innerEventEmitter=new e,this.InnerEventSubType=t}subscribeInnerEvent(e,t,s,n){var o,i;if(["string","number"].includes(typeof t)){const i=t,r=s;null===(o=this._innerEventEmitter)||void 0===o||o.on(`${e}:${i}`,r,n)}else{const n=t;null===(i=this._innerEventEmitter)||void 0===i||i.on(e,n,s)}}emitInnerEvent(e,t){var s,n;if(null===(s=this._innerEventEmitter)||void 0===s||s.emit(e,t),Object.keys(o).includes(e)){const s=null===(n=o[e])||void 0===n?void 0:n.call(o,t);null==s||s.forEach((e=>{var t;e&&(null===(t=this._innerEventEmitter)||void 0===t||t.emit(e.type,e.data))}))}}unSubscribeInnerEvent(e,t,s,n){var o,i;if(["string","number"].includes(typeof t)){const i=t,r=s;null===(o=this._innerEventEmitter)||void 0===o||o.off(`${e}:${i}`,r,n)}else{const n=t;null===(i=this._innerEventEmitter)||void 0===i||i.off(e,n,s)}}subscribeOuterEvent(e,t,s){var n;null===(n=this._outerEventEmitter)||void 0===n||n.on(e,t,s)}unSubscribeOuterEvent(e,t,s){var n;null===(n=this._outerEventEmitter)||void 0===n||n.off(e,t,s)}emitOuterEvent(e,t){var s;null===(s=this._outerEventEmitter)||void 0===s||s.emit(e,t)}getOuterEventEmitter(){return this._outerEventEmitter}rest(){this._outerEventEmitter=null,this._innerEventEmitter=null}};function r(e,t,s,n){return new(s||(s=Promise))((function(o,i){function r(e){try{c(n.next(e))}catch(e){i(e)}}function a(e){try{c(n.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(r,a)}c((n=n.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const a=e=>void 0===e,c=e=>"string"==typeof e,l=e=>{var t;return null===(t=Object.prototype.toString.call(e).match(/^\[object (.*)\]$/))||void 0===t?void 0:t[1].toLowerCase()},d=e=>"function"==typeof Array.isArray?Array.isArray(e):"array"===l(e),u=e=>null!==e&&"object"==typeof e,_=e=>d(e)||u(e),h=e=>{if("string"!=typeof e)return!1;const t=e[0];return!/[^a-zA-Z0-9]/.test(t)},g=e=>{if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);if(null===t)return!0;let s=t;for(;null!==Object.getPrototypeOf(s);)s=Object.getPrototypeOf(s);return t===s};function f(e=99999999){return Math.round(Math.random()*e)}const E=(e,t,s,n)=>{if(!_(e)||!_(t))return 0;let o=0;const i=Object.keys(t);let r;for(let c=0,l=i.length;c<l;c++)if(r=i[c],!(a(t[r])||s&&s.includes(r)))if(_(e[r])&&_(t[r]))o+=E(e[r],t[r],s,n);else{if(n&&n.includes(t[r]))continue;e[r]!==t[r]&&(e[r]=t[r],o+=1)}return o};function p(e){let t,s,n=e;e.length%8!=0&&(n="0".repeat(8-e.length%8)+e);let o="";for(let e=0,{length:i}=n;e<i;e+=8)t=parseInt(n.slice(e,e+4),2),s=parseInt(n.slice(e+4,e+8),2),o+=base16Map.get(t)+base16Map.get(s);return o}const m={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},S=["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 v=Object.freeze({__proto__:null,ENUM_PLATFORM:m,NOT_NEED_CRC_SERVCMD:S});const I="undefined"!=typeof wx&&"function"==typeof wx.getSystemInfoSync&&Boolean(wx.getSystemInfoSync().fontSizeSetting),C=I&&"function"==typeof wx.createGamePortal,y="undefined"!=typeof qq&&"function"==typeof qq.getSystemInfoSync&&Boolean(qq.getSystemInfoSync().fontSizeSetting),M="undefined"!=typeof tt&&"function"==typeof tt.getSystemInfoSync&&Boolean(tt.getSystemInfoSync().fontSizeSetting),O="undefined"!=typeof swan&&"function"==typeof swan.getSystemInfoSync&&Boolean(swan.getSystemInfoSync().fontSizeSetting),T="undefined"!=typeof my&&"function"==typeof my.getSystemInfoSync&&Boolean(my.getSystemInfoSync().fontSizeSetting),A="undefined"!=typeof jd&&"function"==typeof jd.getSystemInfoSync,N="undefined"!=typeof uni&&"undefined"==typeof window&&"function"==typeof uni.requireNativePlugin,R=I&&"object"==typeof wx.miniapp,D="undefined"!=typeof uni,w=I||y||M||O||T||N||A,b="undefined"==typeof window&&!w&&"undefined"!=typeof global&&void 0!==global.NativeScriptGlobals,k="undefined"!=typeof global&&(void 0!==global.nativeModuleProxy||void 0!==global.ReactNative),P="undefined"!=typeof wx&&"function"==typeof wx.getAccountInfoSync&&Boolean(wx.getAccountInfoSync().plugin),L="undefined"!=typeof uni?!w:"undefined"!=typeof window&&!w&&!k,U=y?qq:M?tt:O?swan:T?my:I?wx:N?uni:A?jd:{},G=L&&window&&window.navigator&&window.navigator.userAgent||"",F=/(micromessenger|webbrowser)/i.test(G),x=function(){let e="WEB";return F?e="WEB":y?e="QQ_MP":M?e="TT_MP":O?e="BAIDU_MP":T?e="ALI_MP":I?e=R?"DONUT_NATIVE_APP":"WX_MP":N?e="UNI_NATIVE_APP":b?e="NS_NATIVE_APP":k&&(e="RN_NATIVE_APP"),m[e]}(),B=/iPad/i.test(G),$=/iPhone/i.test(G)&&!B,V=/iPod/i.test(G),q=$||B||V,W=function(){const e=G.match(/OS (\d+)_/i);return e&&e[1]?e[1]:null}(),Y=/Android/i.test(G),K=function(){const e=G.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(!e)return null;const t=e[1]&&parseFloat(e[1]),s=e[2]&&parseFloat(e[2]);return t&&s?parseFloat(`${e[1]}.${e[2]}`):t||null}(),j=/Firefox/i.test(G),H=/Edge/i.test(G),z=!H&&/Chrome/i.test(G),Z=/MSIE/.test(G)||G.indexOf("Trident")>-1&&G.indexOf("rv:11.0")>-1,J=function(){const e=/MSIE\s(\d+)\.\d/.exec(G);let t=e&&parseFloat(e[1]);return!t&&/Trident\/7.0/i.test(G)&&/rv:11.0/.test(G)&&(t=11),t}(),X=/Safari/i.test(G)&&!z&&!Y&&!H,Q=/Windows/i.test(G),ee=/MAC OS X/i.test(G),te=L&&"undefined"!=typeof Worker&&!Z,se=Y||q,ne=L&&void 0!==window.tencent_cloud_im_csig_flutter_for_web_25F_cy,oe=function(){if("undefined"==typeof window||void 0===window.navigator)return!1;const{standalone:e}=window.navigator;return!(!q||e||X)}();function ie(){let e="unknown";if(ee&&(e="mac"),Q&&(e="windows"),q&&(e="ios"),Y&&(e="android"),w)try{const{platform:t}=wx.getSystemInfoSync();void 0!==t&&(e=t)}catch(e){console.error(e)}return e}const re=2800,ae=2801,ce=3e3,le="application/x-www-form-urlencoded;charset=UTF-8";function de(e){return r(this,arguments,void 0,(function*({method:e,url:t,data:s,timeout:n=ce}){return new Promise(w?(o,i)=>{U.request({url:t,data:s,method:e,timeout:n,header:{"content-type":le},success:e=>o(e.data),fail:()=>i(new Error(`{"message":"Network error","code":${re}}`))})}:(o,i)=>{const r=new XMLHttpRequest,a=setTimeout((()=>{r.abort(),i(new Error(`{"message":"Request timeout","code":${ae}}`))}),n);r.onreadystatechange=function(){if(4===r.readyState)if(clearTimeout(a),200===r.status||304===r.status)try{o(r.responseText?JSON.parse(r.responseText):null)}catch(e){o(r.responseText)}else i(new Error(`{"message":"Network error","code":${re}}`))},r.open(e,t,!0),r.setRequestHeader("Content-type",le),r.send(s||null)})}))}function ue(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(g(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 _e(e){if(null===e||"object"!=typeof e)return e;if(e instanceof Date)return new Date(e.getTime());if(e instanceof RegExp)return new RegExp(e.source,e.flags);if(e instanceof Map){const t=new Map;return e.forEach(((e,s)=>{t.set(_e(s),_e(e))})),t}if(e instanceof Set){const t=new Set;return e.forEach((e=>{t.add(_e(e))})),t}if(Array.isArray(e))return e.map((e=>_e(e)));const t=Object.getPrototypeOf(e),s=Object.create(t);return[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)].forEach((t=>{const n=Object.getOwnPropertyDescriptor(e,t);n&&(n.get||n.set?Object.defineProperty(s,t,n):s[t]=_e(e[t]))})),s}function he(){let e,t;return{promise:new Promise(((s,n)=>{e=s,t=n})),resolve:e,reject:t}}var ge=Object.freeze({__proto__:null,ANDROID_VERSION:K,IE_VERSION:J,IN_ALIPAY_MINI_APP:T,IN_BAIDU_MINI_APP:O,IN_BROWSER:L,IN_DONUT_NATIVE_APP:R,IN_JD_MINI_APP:A,IN_MINI_APP:w,IN_NS_NATIVE_APP:b,IN_QQ_MINI_APP:y,IN_RN_APP:k,IN_TT_MINI_APP:M,IN_UNI_APP:D,IN_UNI_NATIVE_APP:N,IN_WX_MINI_APP:I,IN_WX_MINI_GAME:C,IN_WX_MINI_PLUGIN:P,IOS_VERSION:W,IS_ANDROID:Y,IS_CHROME:z,IS_EDGE:H,IS_FIREFOX:j,IS_IE:Z,IS_IOS:q,IS_IPAD:B,IS_IPHONE:$,IS_IPOD:V,IS_MAC:ee,IS_SAFARI:X,IS_WECHAT:F,IS_WIN:Q,IS_WORKER_AVAILABLE:te,MINI_APP_NAMESPACE:U,USER_AGENT:G,base16EncodeBinaryString:p,deepCopyWithMethods:_e,deepMerge:E,generatePromise:he,getPlatformType:ie,getType:l,httpRequest:de,isArray:d,isArrayOrObject:_,isEmpty:ue,isFlutterWeb:ne,isH5:se,isIOSWebView:oe,isNumber:e=>null!==e&&("number"==typeof e&&!Number.isNaN(e-0)||"object"==typeof e&&e.constructor===Number),isObject:u,isPlainObject:g,isString:c,isUndefined:a,isValidRequestKey:h,platform:x,randomInt:f,randomString:function(){const e="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";let t="";for(let s=32;s>0;--s)t+=e[Math.floor(62*Math.random())];return t}});class fe{constructor(){this._socket=null}connectSocket(e){return this._socket=new WebSocket(e),this._socket}send(e){var t,s;try{null===(t=this._socket)||void 0===t||t.send(e)}catch(e){null===(s=this._onSendFail)||void 0===s||s.call(this,e)}}bindSocketHandlers(e){const{onOpen:t,onMessage:s,onClose:n,onError:o,onSendFail:i}=e;this._socket&&(this._socket.binaryType="arraybuffer",this._socket.onopen=t,this._socket.onmessage=s,this._socket.onclose=n,this._socket.onerror=o,this._onSendFail=i)}unbindSocketHandlers(){this._socket&&(this._socket.onopen=null,this._socket.onmessage=null,this._socket.onclose=null,this._socket.onerror=null)}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}class Ee{connectSocket(e){return this._socket=wx.connectSocket({url:e,header:{"content-type":"application/json"},complete:()=>{}}),this._socket}send(e){var t;null===(t=this._socket)||void 0===t||t.send({data:e,fail:this._onSendFail})}bindSocketHandlers(e){const{onOpen:t,onMessage:s,onClose:n,onError:o,onSendFail:i}=e;this._socket.onClose(n),this._socket.onOpen(t),this._socket.onMessage(s),this._socket.onError(o),this._onSendFail=i}unbindSocketHandlers(){this._socket&&(this._socket.onClose((()=>{})),this._socket.onOpen((()=>{})),this._socket.onMessage((()=>{})),this._socket.onError((()=>{})))}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}const pe="CONNECT",me="SEND",Se="DISCONNECT",ve="OPEN",Ie="MESSAGE",Ce="CLOSE",ye="ERROR",Me="SEND_FAIL";class Oe{constructor(){this._worker=null,this._blobUrl=null}connectSocket(e){const t=new Blob(["\n let _socket = null;\n\n self.onmessage = (event) => {\n const { type, url, data } = event.data;\n\n switch (type) {\n case 'CONNECT':\n connectSocket(url);\n break;\n case 'SEND':\n send(data);\n break;\n case 'DISCONNECT':\n disconnect();\n break;\n }\n };\n\n function connectSocket(url) {\n _socket = new WebSocket(url);\n _socket.binaryType = 'arraybuffer';\n bindSocketHandlers();\n return _socket;\n }\n\n function send(packet) {\n try {\n _socket?.send(packet);\n } catch (error) {\n self.postMessage({\n type: 'SEND_FAIL', \n error: {\n message: error.message,\n name: error.name,\n },\n });\n }\n }\n\n function bindSocketHandlers() {\n if (_socket) {\n _socket.onopen = (event) => {\n self.postMessage({\n type: 'OPEN',\n data: {\n type: event.type,\n timeStamp: event.timeStamp,\n },\n });\n };\n\n _socket.onmessage = (event) => {\n self.postMessage({ \n type: 'MESSAGE',\n data: event.data,\n });\n };\n\n _socket.onclose = (event) => {\n self.postMessage({ \n type: 'CLOSE', \n data: { \n code: event.code,\n reason: event.reason,\n timeStamp: event.timeStamp,\n },\n });\n };\n\n _socket.onerror = (error) => {\n self.postMessage({\n type: 'ERROR',\n data: {\n message: error.message,\n name: error.name\n },\n });\n };\n }\n }\n\n function unbindSocketHandlers() {\n if (_socket) {\n _socket.onopen = null;\n _socket.onmessage = null;\n _socket.onclose = null;\n _socket.onerror = null;\n }\n }\n\n function disconnect() {\n if (_socket) {\n _socket.close();\n _socket = null;\n }\n }\n"],{type:"application/javascript"});this._worker=new Worker(URL.createObjectURL(t)),this._worker.postMessage({type:pe,url:e})}send(e){var t,s;try{null===(t=this._worker)||void 0===t||t.postMessage({type:me,data:e})}catch(e){null===(s=this._onSendFail)||void 0===s||s.call(this,e)}}bindSocketHandlers(e){const{onOpen:t,onMessage:s,onClose:n,onError:o,onSendFail:i}=e;if(this._worker){const e={[ve]:t,[Ie]:s,[Ce]:n,[ye]:o,[Me]:i};this._onSendFail=i,this._worker.onmessage=t=>{var s;const{type:n}=(null==t?void 0:t.data)||{};"function"==typeof e[n]&&(null===(s=e[n])||void 0===s||s.call(e,null==t?void 0:t.data))}}}unbindSocketHandlers(){this._worker&&(this._worker.onmessage=null)}disconnect(){this._worker&&(this._worker.postMessage({type:Se}),this._worker.terminate(),this._worker=null),this._blobUrl&&(URL.revokeObjectURL(this._blobUrl),this._blobUrl=null)}}var Te,Ae=new class{constructor(){this._store=new Map}get(e){return this._store.get(e)}getStorage(e){if(w){if(T){return my.getStorageSync({key:e}).data}return U.getStorageSync(e)}return this._canUseLocalStorage()?localStorage.getItem(e):{}}set(e,t){const s=this._store.get(e)||{};t instanceof Map?this._store.set(e,t):this._store.set(e,Object.assign(Object.assign({},s),t))}setStorage(e,t){w?T?my.setStorageSync({key:e,data:JSON.stringify(t)}):U.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)}};!function(e){e[e.CONNECTED=0]="CONNECTED",e[e.CONNECTING=1]="CONNECTING",e[e.DISCONNECTED=2]="DISCONNECTED"}(Te||(Te={}));class Ne{constructor(t){this._url="",this._readyState=Te.DISCONNECTED,this._url=t,this._id=f(),this._emitter=new e,I?this._socket=new Ee:this._canUseWebWorker()?this._socket=new Oe:this._socket=new fe,this.connect()}connect(){this.doOpen(),this._bindSocketHandlers()}doOpen(){[Te.CONNECTED,Te.CONNECTING].includes(this._readyState)||(this._readyState=Te.CONNECTING,this._ws=this._socket.connectSocket(this._url))}send(e){this._readyState!==Te.CONNECTED?this.reconnect():this._socket.send(e)}reconnect(){[Te.CONNECTED,Te.CONNECTING].includes(this._readyState)||(this.disconnect(),this.doOpen())}getId(){return this._id}on(e,t,s){this._emitter.on(e,t,s)}off(e,t,s){this._emitter.off(e,t,s)}isConnected(){return this._readyState===Te.CONNECTED}disconnect(){this._readyState=Te.DISCONNECTED,this._unbindSocketHandlers(),this._socket.disconnect()}_onOpen(e){this._readyState===Te.CONNECTING&&(this._readyState=Te.CONNECTED,this._emitter.emit("connect",{socketId:this._id,event:e}))}_onMessage(e){this._emitter.emit("message",e)}_onClose(e){this._readyState=Te.DISCONNECTED,this._emitter.emit("close",{socketId:this._id,event:e})}_onError(e){this._readyState=Te.DISCONNECTED,this._emitter.emit("error",{socketId:this._id,error:e})}_onSendFail(e){this._readyState=Te.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()}_canUseWebWorker(){const e=Ae.get("cloudConfig")||{};return(a(e.isWorkerEnabled)||"1"===e.isWorkerEnabled)&&te}}const Re="CHINA",De="SINGAPORE",we="KOREA",be="GERMANY",ke="IND",Pe="JPN",Le="USA",Ue="INDONESIA",Ge={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"}}},Fe={[De]:[[2e7,3e7],[172e7,173e7]],[we]:[[3e7,4e7],[173e7,174e7]],[be]:[[4e7,5e7],[174e7,175e7]],[ke]:[[5e7,6e7],[175e7,176e7]],[Pe]:[[6e7,7e7],[176e7,177e7]],[Le]:[[7e7,8e7],[177e7,178e7]],[Ue]:[[8e7,9e7],[178e7,179e7]]};function xe(e){for(const t of Object.keys(Fe))for(const[s,n]of Fe[t])if(e>=s&&e<n)return t;return Re}var Be,$e="1.2.1";!function(e){e.INITIAL="INITIAL",e.DEFAULT="DEFAULT",e.BACKUP="BACKUP",e.ANYCAST="ANYCAST"}(Be||(Be={}));let Ve=Be.INITIAL;function qe(){const e=Math.random();return 0===e?qe():e}function We(e,t){const{isBinary:s=!1}=t||{},n=Ae.get("instance"),{sdkAppId:o,instanceId:i}=n,r=qe(),a=ie(),c=function(){const e=ie();let t=-1;"ios"===e?t=W||-1:"android"===e&&(t=K||-1);return t}(),l=(d={sdkappid:o,instanceid:i,random:r,platform:x,host:a,version:c,sdkversion:$e},Object.keys(d).map((e=>`${e}=${d[e]}`)).join("&"));var d;return s?`${e}/binfo?${l}&compress=gzip`:`${e}/info?${l}`}var Ye=new class{constructor(){this._timeOffsetWithServer=0}getServerTimeMs(){return Date.now()+this._timeOffsetWithServer}getServerTimeSeconds(){return Math.floor(this.getServerTimeMs()/1e3)}getTimeOffsetWithServer(){return this._timeOffsetWithServer}calculateTimeOffsetWithServer(e,t){const s=Date.now(),n=s-e;this._timeOffsetWithServer=t+n-s}};const Ke=16;var je=new class{constructor(){this._tasks=[],this._timer=null,this._taskMap=new Map}_addTaskToScheduler(e){const{id:t}=e;this.removeTask(t),this._tasks.push(e),this._taskMap.set(t,e),this._sort(),this._scheduleNextTask()}_createTask(e){const{id:t,callback:s,context:n,isOnce:o=!1,intervalMs:i=Ke}=e,r=Math.max(i,Ke);return{id:t,nextExecuteTime:Date.now()+r,intervalMs:i,callback:s,context:n,isOnce:o}}addTask(e){const t=this._createTask(e);this._addTaskToScheduler(t)}addOnceTask(e){const t=this._createTask(Object.assign(Object.assign({},e),{isOnce:!0}));this._addTaskToScheduler(t)}removeTask(e){const t=this._tasks.findIndex((t=>t.id===e));t>-1&&(this._tasks.splice(t,1),this._taskMap.delete(e),this._scheduleNextTask())}updateTaskInterval(e,t){const s=this._taskMap.get(e);s&&(s.intervalMs=t,s.nextExecuteTime=Date.now()+t,this._sort(),this._scheduleNextTask())}clearAllTasks(){this._tasks=[],this._taskMap.clear(),this._timer&&(clearTimeout(this._timer),this._timer=null)}dispose(){this.clearAllTasks()}_sort(){this._tasks.sort(((e,t)=>e.nextExecuteTime-t.nextExecuteTime))}_scheduleNextTask(){this._timer&&(clearTimeout(this._timer),this._timer=null);const e=this._tasks[0];if(e){const t=Math.max(0,e.nextExecuteTime-Date.now());this._timer=setTimeout((()=>this._execute()),t)}}_execute(){const e=Date.now();for(;this._tasks.length&&this._tasks[0].nextExecuteTime<=e;){const t=this._tasks[0];try{t.context?t.callback.call(t.context):t.callback(),t.isOnce?this.removeTask(t.id):(t.nextExecuteTime=e+t.intervalMs,this._sort())}catch(e){console.warn(`Task ${t.id} execution failed:`,e),t.isOnce&&this.removeTask(t.id)}}this._scheduleNextTask()}};function He(e){const t=[];for(let s=0;s<e.length;s+=1){const n=e.charCodeAt(s);if(n>=55296&&n<=56319){const o=e.charCodeAt(++s)-56320+(n-55296<<10)+65536;t.push(240|o>>18,128|o>>12&63,128|o>>6&63,128|63&o)}else n<=127?t.push(n):n<=2047?t.push(192|n>>6,128|63&n):t.push(224|n>>12,128|n>>6&63,128|63&n)}return new Uint8Array(t)}function ze(e){const t=Array.isArray(e)?[]:Object.create(null);for(const s in e)Object.prototype.hasOwnProperty.call(e,s)&&h(s)&&null!=e[s]&&(null===e[s]||"object"!=typeof e[s]?t[s]=e[s]:t[s]=ze(e[s]));return t}function Ze(e,t){if(S.includes(e))return 0;const s=He(JSON.stringify(t));let n=4294967295;const{length:o}=s;for(let e=0;e<o;e++){n^=s[e];for(let e=0;e<8;e++)1&~n?n>>>=1:n=n>>>1^3988292384}return(4294967295^n)>>>0}function Je(e){const{servcmd:t,data:s}=e,n=function(e){const t=Ae.get("login")||{},s=Ae.get("instance")||{};return{servcmd:e,ver:"v4",platform:x,websdkappid:537048168,websdkversion:"1.7.3",a2:t.a2Key||void 0,tinyid:t.tinyID||void 0,status_instid:t.statusInstanceId||0,sdkappid:s.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:p(""),cappid:t.cappid||0,tjgID:"",seq:et(),cs:0}}(t),o=ze(s);return n.cs=Ze(t,o),{head:n,body:o}}function Xe(e){const{servcmd:t,data:s}=e,n=function(e){const t=Ae.get("login")||{},s=Ae.get("instance")||{};return{servcmd:e,ver:"v4",platform:x,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:s.sdkAppId,contenttype:"",reqtime:Math.floor(Date.now()/1e3),identifier:"",usersig:"",status_instid:t.statusInstanceId||0,sdkability:75689843,sdkability_ext:p(""),cappid:t.cappid||0,seq:et(),cs:0}}(t),o=ze(s);return n.cs=Ze(t,o),{head:n,body:o}}let Qe=f();function et(){return Qe=Qe<2415919103?Qe+1:f(),Qe}var st,nt=Object.freeze({__proto__:null,generateCosSpecifiedData:function(e){const{servcmd:t,data:s}=e,n=function(e){const t=Ae.get("login")||{},s=Ae.get("instance")||{};return{servcmd:e,ver:"v4",platform:x,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:s.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:t.userId,usersig:t.userSig,status_instid:t.statusInstanceId||0,sdkability:75689843,sdkability_ext:p(""),cappid:t.cappid||0,seq:et(),cs:0}}(t),o=ze(s);return n.cs=Ze(t,o),{head:n,body:o}},generateProtocolData:Je,generateSSOLogProtocolData:Xe,generateSequence:et,taskScheduler:je,timeManager:Ye});!function(e){e[e.info=4]="info",e[e.warning=5]="warning",e[e.error=6]="error"}(st||(st={}));const ot={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 it{constructor(e){this.level=st.info,this._canSendLog=!0,this._logCreatedAt=Ye.getServerTimeMs(),this.timestamp=0,this.networkType=8,this.code=0,this.moreMessage="",this.method="",this.message="",this.costTime=0,this.duplicate=!1,this.eventType=0,this.uiPlatform=void 0;const{method:t,eventType:s=0}=e||{};this.eventType=s,this.method=t}setMoreMessage(e){this.moreMessage=`${this.moreMessage} ${e}`}updateLogCreatedAtByTimeOffset(){this._logCreatedAt+=Ye.getTimeOffsetWithServer()}end(e=!1){if(!this._canSendLog)return;const t=Ye.getServerTimeMs();0===this.costTime&&(this.costTime=t-this._logCreatedAt),this.setMoreMessage(`startts:${this._logCreatedAt} endts:${t}`),e?(this._canSendLog=!1,this.timestamp=Ye.getServerTimeMs(),this._ssoLogModule.pushToLogQueue(this._convertSSOLogDataKeyToServe())):setTimeout((()=>{this._canSendLog=!1,this.timestamp=Ye.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=Ae.get("netWorkMonitor"))||void 0===t?void 0:t.isNetworkOnline)&&(e.errorCode&&(this.code=e.errorCode),e.errorMessage&&this.setMoreMessage(e.errorMessage)),this.level=st.error,this}setLogInfo(e){return Object.keys(e).forEach((t=>{Object.keys(ot).includes(t)&&(this[t]=e[t])})),this}setSSOLogModule(e){this._ssoLogModule=e}_convertSSOLogDataKeyToServe(){const e={};return Object.keys(this).forEach((t=>{const s=t;ot[s]&&(e[ot[s]]=this[s])})),e}}var rt;function at(){const e=Ae.get("login")||{},t=Ae.get("instance")||{};return{sdk_type:30,sdk_app_id:t.sdkAppId,sdk_version:"1.2.1",tiny_id:Number(e.tinyID),user_id:e.userId,platform:x,instance_id:t.instanceId,trace_id:(new Date).getTime()}}!function(e){e.RECONNECTED="reconnected",e.CLOUD_CONFIG_UPDATE="cloud_config_update",e.SOCKET_DISCONNECTED="socket_disconnected"}(rt||(rt={}));var ct=rt;const lt=20,dt=6e4,ut=[4,5,6],_t=[],ht=[],gt="report-logger";var ft=new class{constructor(){this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._reportLevel=[4,5,6],this._minThreshold=lt,this._maxThreshold=100,this._waitingTime=dt,this._lastReportAt=Date.now(),this._ssoLogMap=new Map,i.subscribeInnerEvent(ct.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),je.addTask({id:gt,intervalMs:1e3,callback:this._checkAndReportIfDue,context:this}),this._logQueue=[],this._savePlatFormInfo()}_handleCloudConfigUpdate(e){const{evt_rpt_threshold:t=lt,evt_rpt_waiting:s=dt,evt_rpt_level:n=ut,evt_rpt_sdkappid_bl:o=_t,evt_rpt_tinyid_wl:i=ht}=e||{};this._sdkAppIdBlackList=o,this._waitingTime=s,this._minThreshold=t,this._reportLevel=n,this._tinyIdWhiteList=i}createSSOLogData(e){const t=new it(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 r(this,void 0,void 0,(function*(){if(0===this._logQueue.length)return;const e=this._logQueue.slice(),t=this._filterLogs(e);if(this._logQueue=[],0===t.length)return void(this._lastReportAt=Date.now());const s={Header:at(),Event:t};yield function(e){const t="imopenstat.tim_web_report_v2",s=Xe({servcmd:t,data:e}),n=`${s.head.seq}${t}`;Lt.sendPacket(s,{requestId:n})}(s),this._lastReportAt=Date.now()}))}_savePlatFormInfo(){var e,t;if(I){const s=null===(t=null===(e=wx.getAccountInfoSync)||void 0===e?void 0:e.call(wx))||void 0===t?void 0:t.miniProgram;if(s){const{appId:e,envVersion:t}=s;Ae.set("instance",{appId:e,envVersion:t})}}else L&&Ae.set("instance",{href:window.location.href})}_filterLogs(e){const{tinyID:t}=Ae.get("login")||{},{sdkAppId:s}=Ae.get("instance")||{};return this._sdkAppIdBlackList.includes(s)&&!this._tinyIdWhiteList.includes(t)?[]:e.filter((e=>this._reportLevel.includes(e.level)))}reset(){console.log("SSO_LOG_MODULE.reset"),je.removeTask(gt),i.unSubscribeInnerEvent(ct.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),this._lastReportAt=0,this._uploadSSOLogData(),this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._minThreshold=lt,this._maxThreshold=100,this._waitingTime=dt,this._logQueue=[]}};const Et=15e3,pt="Channel",mt="channel_schedule_task",St="channel_reconnect_task",vt="connected",It="connecting",Ct="disconnected",yt=500,Mt="network_status_change",Ot="activity_status_change",Tt="send_fail",At="reconnect_failed",Nt="socket_error",Rt="socket_close";function Dt(e){return Dt="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},Dt(e)}function wt(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 bt,kt={exports:{}};var Pt=(bt||(bt=1,kt.exports=function e(t,s,n){function o(r,a){if(!s[r]){if(!t[r]){if(!a&&wt)return wt(r);if(i)return i(r,!0);var c=new Error("Cannot find module '"+r+"'");throw c.code="MODULE_NOT_FOUND",c}var l=s[r]={exports:{}};t[r][0].call(l.exports,(function(e){return o(t[r][1][e]||e)}),l,l.exports,e,t,s,n)}return s[r].exports}for(var i=wt,r=0;r<n.length;r++)o(n[r]);return o}({1:[function(e,t,s){var n="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;s.assign=function(e){for(var t,s,n=Array.prototype.slice.call(arguments,1);n.length;){var o=n.shift();if(o){if("object"!=Dt(o))throw new TypeError(o+"must be non-object");for(var i in o)t=o,s=i,Object.prototype.hasOwnProperty.call(t,s)&&(e[i]=o[i])}}return e},s.shrinkBuf=function(e,t){return e.length===t?e:e.subarray?e.subarray(0,t):(e.length=t,e)};var o={arraySet:function(e,t,s,n,o){if(t.subarray&&e.subarray)e.set(t.subarray(s,s+n),o);else for(var i=0;i<n;i++)e[o+i]=t[s+i]},flattenChunks:function(e){var t,s,n,o,i,r;for(t=n=0,s=e.length;t<s;t++)n+=e[t].length;for(r=new Uint8Array(n),t=o=0,s=e.length;t<s;t++)i=e[t],r.set(i,o),o+=i.length;return r}},i={arraySet:function(e,t,s,n,o){for(var i=0;i<n;i++)e[o+i]=t[s+i]},flattenChunks:function(e){return[].concat.apply([],e)}};s.setTyped=function(e){e?(s.Buf8=Uint8Array,s.Buf16=Uint16Array,s.Buf32=Int32Array,s.assign(s,o)):(s.Buf8=Array,s.Buf16=Array,s.Buf32=Array,s.assign(s,i))},s.setTyped(n)},{}],2:[function(e,t,s){var n=e("./common"),o=!0,i=!0;try{String.fromCharCode.apply(null,[0])}catch(e){o=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(e){i=!1}for(var r=new n.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&&i||!e.subarray&&o))return String.fromCharCode.apply(null,n.shrinkBuf(e,t));for(var s="",r=0;r<t;r++)s+=String.fromCharCode(e[r]);return s}r[254]=r[254]=1,s.string2buf=function(e){var t,s,o,i,r,a=e.length,c=0;for(i=0;i<a;i++)55296==(64512&(s=e.charCodeAt(i)))&&i+1<a&&56320==(64512&(o=e.charCodeAt(i+1)))&&(s=65536+(s-55296<<10)+(o-56320),i++),c+=s<128?1:s<2048?2:s<65536?3:4;for(t=new n.Buf8(c),i=r=0;r<c;i++)55296==(64512&(s=e.charCodeAt(i)))&&i+1<a&&56320==(64512&(o=e.charCodeAt(i+1)))&&(s=65536+(s-55296<<10)+(o-56320),i++),s<128?t[r++]=s:(s<2048?t[r++]=192|s>>>6:(s<65536?t[r++]=224|s>>>12:(t[r++]=240|s>>>18,t[r++]=128|s>>>12&63),t[r++]=128|s>>>6&63),t[r++]=128|63&s);return t},s.buf2binstring=function(e){return c(e,e.length)},s.binstring2buf=function(e){for(var t=new n.Buf8(e.length),s=0,o=t.length;s<o;s++)t[s]=e.charCodeAt(s);return t},s.buf2string=function(e,t){var s,n,o,i,a=t||e.length,l=new Array(2*a);for(s=n=0;s<a;)if((o=e[s++])<128)l[n++]=o;else if(4<(i=r[o]))l[n++]=65533,s+=i-1;else{for(o&=2===i?31:3===i?15:7;1<i&&s<a;)o=o<<6|63&e[s++],i--;1<i?l[n++]=65533:o<65536?l[n++]=o:(o-=65536,l[n++]=55296|o>>10&1023,l[n++]=56320|1023&o)}return c(l,n)},s.utf8border=function(e,t){var s;for((t=t||e.length)>e.length&&(t=e.length),s=t-1;0<=s&&128==(192&e[s]);)s--;return s<0||0===s?t:s+r[e[s]]>t?s:t}},{"./common":1}],3:[function(e,t,s){t.exports=function(e,t,s,n){for(var o=65535&e,i=e>>>16&65535,r=0;0!==s;){for(s-=r=2e3<s?2e3:s;i=i+(o=o+t[n++]|0)|0,--r;);o%=65521,i%=65521}return o|i<<16}},{}],4:[function(e,t,s){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,s){var n=function(){for(var e,t=[],s=0;s<256;s++){e=s;for(var n=0;n<8;n++)e=1&e?3988292384^e>>>1:e>>>1;t[s]=e}return t}();t.exports=function(e,t,s,o){var i=n,r=o+s;e^=-1;for(var a=o;a<r;a++)e=e>>>8^i[255&(e^t[a])];return~e}},{}],6:[function(e,t,s){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,s){t.exports=function(e,t){var s,n,o,i,r,a,c,l,d,u,_,h,g,f,E,p,m,S,v,I,C,y,M,O,T;s=e.state,n=e.next_in,O=e.input,o=n+(e.avail_in-5),i=e.next_out,T=e.output,r=i-(t-e.avail_out),a=i+(e.avail_out-257),c=s.dmax,l=s.wsize,d=s.whave,u=s.wnext,_=s.window,h=s.hold,g=s.bits,f=s.lencode,E=s.distcode,p=(1<<s.lenbits)-1,m=(1<<s.distbits)-1;e:do{g<15&&(h+=O[n++]<<g,g+=8,h+=O[n++]<<g,g+=8),S=f[h&p];t:for(;;){if(h>>>=v=S>>>24,g-=v,0==(v=S>>>16&255))T[i++]=65535&S;else{if(!(16&v)){if(!(64&v)){S=f[(65535&S)+(h&(1<<v)-1)];continue t}if(32&v){s.mode=12;break e}e.msg="invalid literal/length code",s.mode=30;break e}I=65535&S,(v&=15)&&(g<v&&(h+=O[n++]<<g,g+=8),I+=h&(1<<v)-1,h>>>=v,g-=v),g<15&&(h+=O[n++]<<g,g+=8,h+=O[n++]<<g,g+=8),S=E[h&m];s:for(;;){if(h>>>=v=S>>>24,g-=v,!(16&(v=S>>>16&255))){if(!(64&v)){S=E[(65535&S)+(h&(1<<v)-1)];continue s}e.msg="invalid distance code",s.mode=30;break e}if(C=65535&S,g<(v&=15)&&(h+=O[n++]<<g,(g+=8)<v&&(h+=O[n++]<<g,g+=8)),c<(C+=h&(1<<v)-1)){e.msg="invalid distance too far back",s.mode=30;break e}if(h>>>=v,g-=v,(v=i-r)<C){if(d<(v=C-v)&&s.sane){e.msg="invalid distance too far back",s.mode=30;break e}if(M=_,(y=0)===u){if(y+=l-v,v<I){for(I-=v;T[i++]=_[y++],--v;);y=i-C,M=T}}else if(u<v){if(y+=l+u-v,(v-=u)<I){for(I-=v;T[i++]=_[y++],--v;);if(y=0,u<I){for(I-=v=u;T[i++]=_[y++],--v;);y=i-C,M=T}}}else if(y+=u-v,v<I){for(I-=v;T[i++]=_[y++],--v;);y=i-C,M=T}for(;2<I;)T[i++]=M[y++],T[i++]=M[y++],T[i++]=M[y++],I-=3;I&&(T[i++]=M[y++],1<I&&(T[i++]=M[y++]))}else{for(y=i-C;T[i++]=T[y++],T[i++]=T[y++],T[i++]=T[y++],2<(I-=3););I&&(T[i++]=T[y++],1<I&&(T[i++]=T[y++]))}break}}break}}while(n<o&&i<a);n-=I=g>>3,h&=(1<<(g-=I<<3))-1,e.next_in=n,e.next_out=i,e.avail_in=n<o?o-n+5:5-(n-o),e.avail_out=i<a?a-i+257:257-(i-a),s.hold=h,s.bits=g}},{}],8:[function(e,t,s){var n=e("../utils/common"),o=e("./adler32"),i=e("./crc32"),r=e("./inffast"),a=e("./inftrees"),c=1,l=2,d=0,u=-2,_=1,h=852,g=592;function f(e){return(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)}function E(){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 n.Buf16(320),this.work=new n.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function p(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=_,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new n.Buf32(h),t.distcode=t.distdyn=new n.Buf32(g),t.sane=1,t.back=-1,d):u}function m(e){var t;return e&&e.state?((t=e.state).wsize=0,t.whave=0,t.wnext=0,p(e)):u}function S(e,t){var s,n;return e&&e.state?(n=e.state,t<0?(s=0,t=-t):(s=1+(t>>4),t<48&&(t&=15)),t&&(t<8||15<t)?u:(null!==n.window&&n.wbits!==t&&(n.window=null),n.wrap=s,n.wbits=t,m(e))):u}function v(e,t){var s,n;return e?(n=new E,(e.state=n).window=null,(s=S(e,t))!==d&&(e.state=null),s):u}var I,C,y=!0;function M(e){if(y){var t;for(I=new n.Buf32(512),C=new n.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,C,0,e.work,{bits:5}),y=!1}e.lencode=I,e.lenbits=9,e.distcode=C,e.distbits=5}function O(e,t,s,o){var i,r=e.state;return null===r.window&&(r.wsize=1<<r.wbits,r.wnext=0,r.whave=0,r.window=new n.Buf8(r.wsize)),o>=r.wsize?(n.arraySet(r.window,t,s-r.wsize,r.wsize,0),r.wnext=0,r.whave=r.wsize):(o<(i=r.wsize-r.wnext)&&(i=o),n.arraySet(r.window,t,s-o,i,r.wnext),(o-=i)?(n.arraySet(r.window,t,s-o,o,0),r.wnext=o,r.whave=r.wsize):(r.wnext+=i,r.wnext===r.wsize&&(r.wnext=0),r.whave<r.wsize&&(r.whave+=i))),0}s.inflateReset=m,s.inflateReset2=S,s.inflateResetKeep=p,s.inflateInit=function(e){return v(e,15)},s.inflateInit2=v,s.inflate=function(e,t){var s,h,g,E,p,m,S,v,I,C,y,T,A,N,R,D,w,b,k,P,L,U,G,F,x=0,B=new n.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===(s=e.state).mode&&(s.mode=13),p=e.next_out,g=e.output,S=e.avail_out,E=e.next_in,h=e.input,m=e.avail_in,v=s.hold,I=s.bits,C=m,y=S,U=d;e:for(;;)switch(s.mode){case _:if(0===s.wrap){s.mode=13;break}for(;I<16;){if(0===m)break e;m--,v+=h[E++]<<I,I+=8}if(2&s.wrap&&35615===v){B[s.check=0]=255&v,B[1]=v>>>8&255,s.check=i(s.check,B,2,0),I=v=0,s.mode=2;break}if(s.flags=0,s.head&&(s.head.done=!1),!(1&s.wrap)||(((255&v)<<8)+(v>>8))%31){e.msg="incorrect header check",s.mode=30;break}if(8!=(15&v)){e.msg="unknown compression method",s.mode=30;break}if(I-=4,L=8+(15&(v>>>=4)),0===s.wbits)s.wbits=L;else if(L>s.wbits){e.msg="invalid window size",s.mode=30;break}s.dmax=1<<L,e.adler=s.check=1,s.mode=512&v?10:12,I=v=0;break;case 2:for(;I<16;){if(0===m)break e;m--,v+=h[E++]<<I,I+=8}if(s.flags=v,8!=(255&s.flags)){e.msg="unknown compression method",s.mode=30;break}if(57344&s.flags){e.msg="unknown header flags set",s.mode=30;break}s.head&&(s.head.text=v>>8&1),512&s.flags&&(B[0]=255&v,B[1]=v>>>8&255,s.check=i(s.check,B,2,0)),I=v=0,s.mode=3;case 3:for(;I<32;){if(0===m)break e;m--,v+=h[E++]<<I,I+=8}s.head&&(s.head.time=v),512&s.flags&&(B[0]=255&v,B[1]=v>>>8&255,B[2]=v>>>16&255,B[3]=v>>>24&255,s.check=i(s.check,B,4,0)),I=v=0,s.mode=4;case 4:for(;I<16;){if(0===m)break e;m--,v+=h[E++]<<I,I+=8}s.head&&(s.head.xflags=255&v,s.head.os=v>>8),512&s.flags&&(B[0]=255&v,B[1]=v>>>8&255,s.check=i(s.check,B,2,0)),I=v=0,s.mode=5;case 5:if(1024&s.flags){for(;I<16;){if(0===m)break e;m--,v+=h[E++]<<I,I+=8}s.length=v,s.head&&(s.head.extra_len=v),512&s.flags&&(B[0]=255&v,B[1]=v>>>8&255,s.check=i(s.check,B,2,0)),I=v=0}else s.head&&(s.head.extra=null);s.mode=6;case 6:if(1024&s.flags&&(m<(T=s.length)&&(T=m),T&&(s.head&&(L=s.head.extra_len-s.length,s.head.extra||(s.head.extra=new Array(s.head.extra_len)),n.arraySet(s.head.extra,h,E,T,L)),512&s.flags&&(s.check=i(s.check,h,T,E)),m-=T,E+=T,s.length-=T),s.length))break e;s.length=0,s.mode=7;case 7:if(2048&s.flags){if(0===m)break e;for(T=0;L=h[E+T++],s.head&&L&&s.length<65536&&(s.head.name+=String.fromCharCode(L)),L&&T<m;);if(512&s.flags&&(s.check=i(s.check,h,T,E)),m-=T,E+=T,L)break e}else s.head&&(s.head.name=null);s.length=0,s.mode=8;case 8:if(4096&s.flags){if(0===m)break e;for(T=0;L=h[E+T++],s.head&&L&&s.length<65536&&(s.head.comment+=String.fromCharCode(L)),L&&T<m;);if(512&s.flags&&(s.check=i(s.check,h,T,E)),m-=T,E+=T,L)break e}else s.head&&(s.head.comment=null);s.mode=9;case 9:if(512&s.flags){for(;I<16;){if(0===m)break e;m--,v+=h[E++]<<I,I+=8}if(v!==(65535&s.check)){e.msg="header crc mismatch",s.mode=30;break}I=v=0}s.head&&(s.head.hcrc=s.flags>>9&1,s.head.done=!0),e.adler=s.check=0,s.mode=12;break;case 10:for(;I<32;){if(0===m)break e;m--,v+=h[E++]<<I,I+=8}e.adler=s.check=f(v),I=v=0,s.mode=11;case 11:if(0===s.havedict)return e.next_out=p,e.avail_out=S,e.next_in=E,e.avail_in=m,s.hold=v,s.bits=I,2;e.adler=s.check=1,s.mode=12;case 12:if(5===t||6===t)break e;case 13:if(s.last){v>>>=7&I,I-=7&I,s.mode=27;break}for(;I<3;){if(0===m)break e;m--,v+=h[E++]<<I,I+=8}switch(s.last=1&v,I-=1,3&(v>>>=1)){case 0:s.mode=14;break;case 1:if(M(s),s.mode=20,6!==t)break;v>>>=2,I-=2;break e;case 2:s.mode=17;break;case 3:e.msg="invalid block type",s.mode=30}v>>>=2,I-=2;break;case 14:for(v>>>=7&I,I-=7&I;I<32;){if(0===m)break e;m--,v+=h[E++]<<I,I+=8}if((65535&v)!=(v>>>16^65535)){e.msg="invalid stored block lengths",s.mode=30;break}if(s.length=65535&v,I=v=0,s.mode=15,6===t)break e;case 15:s.mode=16;case 16:if(T=s.length){if(m<T&&(T=m),S<T&&(T=S),0===T)break e;n.arraySet(g,h,E,T,p),m-=T,E+=T,S-=T,p+=T,s.length-=T;break}s.mode=12;break;case 17:for(;I<14;){if(0===m)break e;m--,v+=h[E++]<<I,I+=8}if(s.nlen=257+(31&v),v>>>=5,I-=5,s.ndist=1+(31&v),v>>>=5,I-=5,s.ncode=4+(15&v),v>>>=4,I-=4,286<s.nlen||30<s.ndist){e.msg="too many length or distance symbols",s.mode=30;break}s.have=0,s.mode=18;case 18:for(;s.have<s.ncode;){for(;I<3;){if(0===m)break e;m--,v+=h[E++]<<I,I+=8}s.lens[$[s.have++]]=7&v,v>>>=3,I-=3}for(;s.have<19;)s.lens[$[s.have++]]=0;if(s.lencode=s.lendyn,s.lenbits=7,G={bits:s.lenbits},U=a(0,s.lens,0,19,s.lencode,0,s.work,G),s.lenbits=G.bits,U){e.msg="invalid code lengths set",s.mode=30;break}s.have=0,s.mode=19;case 19:for(;s.have<s.nlen+s.ndist;){for(;D=(x=s.lencode[v&(1<<s.lenbits)-1])>>>16&255,w=65535&x,!((R=x>>>24)<=I);){if(0===m)break e;m--,v+=h[E++]<<I,I+=8}if(w<16)v>>>=R,I-=R,s.lens[s.have++]=w;else{if(16===w){for(F=R+2;I<F;){if(0===m)break e;m--,v+=h[E++]<<I,I+=8}if(v>>>=R,I-=R,0===s.have){e.msg="invalid bit length repeat",s.mode=30;break}L=s.lens[s.have-1],T=3+(3&v),v>>>=2,I-=2}else if(17===w){for(F=R+3;I<F;){if(0===m)break e;m--,v+=h[E++]<<I,I+=8}I-=R,L=0,T=3+(7&(v>>>=R)),v>>>=3,I-=3}else{for(F=R+7;I<F;){if(0===m)break e;m--,v+=h[E++]<<I,I+=8}I-=R,L=0,T=11+(127&(v>>>=R)),v>>>=7,I-=7}if(s.have+T>s.nlen+s.ndist){e.msg="invalid bit length repeat",s.mode=30;break}for(;T--;)s.lens[s.have++]=L}}if(30===s.mode)break;if(0===s.lens[256]){e.msg="invalid code -- missing end-of-block",s.mode=30;break}if(s.lenbits=9,G={bits:s.lenbits},U=a(c,s.lens,0,s.nlen,s.lencode,0,s.work,G),s.lenbits=G.bits,U){e.msg="invalid literal/lengths set",s.mode=30;break}if(s.distbits=6,s.distcode=s.distdyn,G={bits:s.distbits},U=a(l,s.lens,s.nlen,s.ndist,s.distcode,0,s.work,G),s.distbits=G.bits,U){e.msg="invalid distances set",s.mode=30;break}if(s.mode=20,6===t)break e;case 20:s.mode=21;case 21:if(6<=m&&258<=S){e.next_out=p,e.avail_out=S,e.next_in=E,e.avail_in=m,s.hold=v,s.bits=I,r(e,y),p=e.next_out,g=e.output,S=e.avail_out,E=e.next_in,h=e.input,m=e.avail_in,v=s.hold,I=s.bits,12===s.mode&&(s.back=-1);break}for(s.back=0;D=(x=s.lencode[v&(1<<s.lenbits)-1])>>>16&255,w=65535&x,!((R=x>>>24)<=I);){if(0===m)break e;m--,v+=h[E++]<<I,I+=8}if(D&&!(240&D)){for(b=R,k=D,P=w;D=(x=s.lencode[P+((v&(1<<b+k)-1)>>b)])>>>16&255,w=65535&x,!(b+(R=x>>>24)<=I);){if(0===m)break e;m--,v+=h[E++]<<I,I+=8}v>>>=b,I-=b,s.back+=b}if(v>>>=R,I-=R,s.back+=R,s.length=w,0===D){s.mode=26;break}if(32&D){s.back=-1,s.mode=12;break}if(64&D){e.msg="invalid literal/length code",s.mode=30;break}s.extra=15&D,s.mode=22;case 22:if(s.extra){for(F=s.extra;I<F;){if(0===m)break e;m--,v+=h[E++]<<I,I+=8}s.length+=v&(1<<s.extra)-1,v>>>=s.extra,I-=s.extra,s.back+=s.extra}s.was=s.length,s.mode=23;case 23:for(;D=(x=s.distcode[v&(1<<s.distbits)-1])>>>16&255,w=65535&x,!((R=x>>>24)<=I);){if(0===m)break e;m--,v+=h[E++]<<I,I+=8}if(!(240&D)){for(b=R,k=D,P=w;D=(x=s.distcode[P+((v&(1<<b+k)-1)>>b)])>>>16&255,w=65535&x,!(b+(R=x>>>24)<=I);){if(0===m)break e;m--,v+=h[E++]<<I,I+=8}v>>>=b,I-=b,s.back+=b}if(v>>>=R,I-=R,s.back+=R,64&D){e.msg="invalid distance code",s.mode=30;break}s.offset=w,s.extra=15&D,s.mode=24;case 24:if(s.extra){for(F=s.extra;I<F;){if(0===m)break e;m--,v+=h[E++]<<I,I+=8}s.offset+=v&(1<<s.extra)-1,v>>>=s.extra,I-=s.extra,s.back+=s.extra}if(s.offset>s.dmax){e.msg="invalid distance too far back",s.mode=30;break}s.mode=25;case 25:if(0===S)break e;if(T=y-S,s.offset>T){if((T=s.offset-T)>s.whave&&s.sane){e.msg="invalid distance too far back",s.mode=30;break}T>s.wnext?(T-=s.wnext,A=s.wsize-T):A=s.wnext-T,T>s.length&&(T=s.length),N=s.window}else N=g,A=p-s.offset,T=s.length;for(S<T&&(T=S),S-=T,s.length-=T;g[p++]=N[A++],--T;);0===s.length&&(s.mode=21);break;case 26:if(0===S)break e;g[p++]=s.length,S--,s.mode=21;break;case 27:if(s.wrap){for(;I<32;){if(0===m)break e;m--,v|=h[E++]<<I,I+=8}if(y-=S,e.total_out+=y,s.total+=y,y&&(e.adler=s.check=s.flags?i(s.check,g,y,p-y):o(s.check,g,y,p-y)),y=S,(s.flags?v:f(v))!==s.check){e.msg="incorrect data check",s.mode=30;break}I=v=0}s.mode=28;case 28:if(s.wrap&&s.flags){for(;I<32;){if(0===m)break e;m--,v+=h[E++]<<I,I+=8}if(v!==(4294967295&s.total)){e.msg="incorrect length check",s.mode=30;break}I=v=0}s.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=p,e.avail_out=S,e.next_in=E,e.avail_in=m,s.hold=v,s.bits=I,(s.wsize||y!==e.avail_out&&s.mode<30&&(s.mode<27||4!==t))&&O(e,e.output,e.next_out,y-e.avail_out)?(s.mode=31,-4):(C-=e.avail_in,y-=e.avail_out,e.total_in+=C,e.total_out+=y,s.total+=y,s.wrap&&y&&(e.adler=s.check=s.flags?i(s.check,g,y,e.next_out-y):o(s.check,g,y,e.next_out-y)),e.data_type=s.bits+(s.last?64:0)+(12===s.mode?128:0)+(20===s.mode||15===s.mode?256:0),(0===C&&0===y||4===t)&&U===d&&(U=-5),U)},s.inflateEnd=function(e){if(!e||!e.state)return u;var t=e.state;return t.window&&(t.window=null),e.state=null,d},s.inflateGetHeader=function(e,t){var s;return e&&e.state&&2&(s=e.state).wrap?((s.head=t).done=!1,d):u},s.inflateSetDictionary=function(e,t){var s,n=t.length;return e&&e.state?0!==(s=e.state).wrap&&11!==s.mode?u:11===s.mode&&o(1,t,n,0)!==s.check?-3:O(e,t,n,n)?(s.mode=31,-4):(s.havedict=1,d):u},s.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":1,"./adler32":3,"./crc32":5,"./inffast":7,"./inftrees":9}],9:[function(e,t,s){var n=e("../utils/common"),o=[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],i=[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,s,c,l,d,u,_){var h,g,f,E,p,m,S,v,I,C=_.bits,y=0,M=0,O=0,T=0,A=0,N=0,R=0,D=0,w=0,b=0,k=null,P=0,L=new n.Buf16(16),U=new n.Buf16(16),G=null,F=0;for(y=0;y<=15;y++)L[y]=0;for(M=0;M<c;M++)L[t[s+M]]++;for(A=C,T=15;1<=T&&0===L[T];T--);if(T<A&&(A=T),0===T)return l[d++]=20971520,l[d++]=20971520,_.bits=1,0;for(O=1;O<T&&0===L[O];O++);for(A<O&&(A=O),y=D=1;y<=15;y++)if(D<<=1,(D-=L[y])<0)return-1;if(0<D&&(0===e||1!==T))return-1;for(U[1]=0,y=1;y<15;y++)U[y+1]=U[y]+L[y];for(M=0;M<c;M++)0!==t[s+M]&&(u[U[t[s+M]]++]=M);if(0===e?(k=G=u,m=19):1===e?(k=o,P-=257,G=i,F-=257,m=256):(k=r,G=a,m=-1),y=O,p=d,R=M=b=0,f=-1,E=(w=1<<(N=A))-1,1===e&&852<w||2===e&&592<w)return 1;for(;;){for(S=y-R,u[M]<m?(v=0,I=u[M]):u[M]>m?(v=G[F+u[M]],I=k[P+u[M]]):(v=96,I=0),h=1<<y-R,O=g=1<<N;l[p+(b>>R)+(g-=h)]=S<<24|v<<16|I,0!==g;);for(h=1<<y-1;b&h;)h>>=1;if(0!==h?(b&=h-1,b+=h):b=0,M++,0==--L[y]){if(y===T)break;y=t[s+u[M]]}if(A<y&&(b&E)!==f){for(0===R&&(R=A),p+=O,D=1<<(N=y-R);N+R<T&&!((D-=L[N+R])<=0);)N++,D<<=1;if(w+=1<<N,1===e&&852<w||2===e&&592<w)return 1;l[f=b&E]=A<<24|N<<16|p-d}}return 0!==b&&(l[p+b]=y-R<<24|64<<16),_.bits=A,0}},{"../utils/common":1}],10:[function(e,t,s){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,s){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,s){var n=e("./zlib/inflate"),o=e("./utils/common"),i=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=o.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 s=n.inflateInit2(this.strm,t.windowBits);if(s!==r.Z_OK)throw new Error(a[s]);if(this.header=new l,n.inflateGetHeader(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=i.string2buf(t.dictionary):"[object ArrayBuffer]"===d.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(s=n.inflateSetDictionary(this.strm,t.dictionary))!==r.Z_OK))throw new Error(a[s])}function _(e,t){var s=new u(t);if(s.push(e,!0),s.err)throw s.msg||a[s.err];return s.result}u.prototype.push=function(e,t){var s,a,c,l,u,_=this.strm,h=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?_.input=i.binstring2buf(e):"[object ArrayBuffer]"===d.call(e)?_.input=new Uint8Array(e):_.input=e,_.next_in=0,_.avail_in=_.input.length;do{if(0===_.avail_out&&(_.output=new o.Buf8(h),_.next_out=0,_.avail_out=h),(s=n.inflate(_,r.Z_NO_FLUSH))===r.Z_NEED_DICT&&g&&(s=n.inflateSetDictionary(this.strm,g)),s===r.Z_BUF_ERROR&&!0===f&&(s=r.Z_OK,f=!1),s!==r.Z_STREAM_END&&s!==r.Z_OK)return this.onEnd(s),!(this.ended=!0);_.next_out&&(0!==_.avail_out&&s!==r.Z_STREAM_END&&(0!==_.avail_in||a!==r.Z_FINISH&&a!==r.Z_SYNC_FLUSH)||("string"===this.options.to?(c=i.utf8border(_.output,_.next_out),l=_.next_out-c,u=i.buf2string(_.output,c),_.next_out=l,_.avail_out=h-l,l&&o.arraySet(_.output,_.output,c,l,0),this.onData(u)):this.onData(o.shrinkBuf(_.output,_.next_out)))),0===_.avail_in&&0===_.avail_out&&(f=!0)}while((0<_.avail_in||0===_.avail_out)&&s!==r.Z_STREAM_END);return s===r.Z_STREAM_END&&(a=r.Z_FINISH),a===r.Z_FINISH?(s=n.inflateEnd(this.strm),this.onEnd(s),this.ended=!0,s===r.Z_OK):a!==r.Z_SYNC_FLUSH||(this.onEnd(r.Z_OK),!(_.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=o.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg},s.Inflate=u,s.inflate=_,s.inflateRaw=function(e,t){return(t=t||{}).raw=!0,_(e,t)},s.ungzip=_},{"./utils/common":1,"./utils/strings":2,"./zlib/constants":4,"./zlib/gzheader":6,"./zlib/inflate":8,"./zlib/messages":10,"./zlib/zstream":11}]},{},[])("/lib/inflate.js")),kt.exports);var Lt=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=yt,this._currentConnectState=vt,this._beforeSendInterceptors=[]}init(){je.addTask({id:mt,intervalMs:1e3,callback:this._executeScheduledTaskIfReady,context:this}),this._updateIsBinarySupported(),this._url=function(e){const t=Ae.get("instance"),{sdkAppId:s,testEnv:n}=t,o=xe(s);return We(n?Ge.TEST[o].DEFAULT:Ge.PRODUCTION[o].INITIAL.replace("*",`${s}`),{isBinary:e})}(this._isBinarySupported),i.subscribeInnerEvent("networkStatusChange",this._handleNetworkStatusChange,this),i.subscribeInnerEvent("activityStatusChange",this._handleActivityStatusChange,this),this.connect()}sendPacket(e,t){var s;const{requestId:n,timeout:o=Et,canResend:i=!0}=t||{};if(ue(e))return console.warn(`${pt}.sendPacket: packet is empty `,e),null;this._executeBeforeSendInterceptors(e);const r=JSON.stringify(e);let a=null;if(n){const{resolve:e,reject:t,promise:s}=he();a=s,this._pendingRequests.set(n,{resolve:e,reject:t,timestamp:Date.now(),uplinkData:r,timeout:o,canResend:i})}const c=this._isBinarySupported?He(r).buffer:r;return null===(s=this._socketAdapter)||void 0===s||s.send(c),a}connect(){var e;this._socketAdapter=new Ne(this._url),this._connectionEstablishedTime=0,this._addEventListeners(),this._connectionStartTime=Date.now();const t=null===(e=this._socketAdapter)||void 0===e?void 0:e.getId(),s=`${pt}.connect isWorkerEnabled: false socketID:${t} url:${this._url}`;this._ssoLog({method:"connect",message:s}),console.log(s)}disconnect(){var e,t;const s=null===(e=this._socketAdapter)||void 0===e?void 0:e.getId(),n=`${pt}.disconnect socketID:${s}`;this._ssoLog({method:"disconnect",message:n}),console.log(n),this._removeEventListeners(),null===(t=this._socketAdapter)||void 0===t||t.disconnect()}getSocketAdapter(){return this._socketAdapter}dispose(){console.log(`${pt}.dispose`),je.removeTask(mt),je.removeTask(St),i.unSubscribeInnerEvent("networkStatusChange",this._handleNetworkStatusChange,this),i.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=yt,this._url=""}registerBeforeSendInterceptor(e,t){this._beforeSendInterceptors.push(e.bind(t))}_executeBeforeSendInterceptors(e){for(const t of this._beforeSendInterceptors){const{servcmd:s=""}=null==e?void 0:e.head;t(s.includes(".")?s.split(".").pop():"")}}_shouldSkipReconnect(){const e=this._currentConnectState===It&&this._isReconnecting;return!this._socketAdapter||e}reconnect(){return r(this,void 0,void 0,(function*(){const e=`${pt} 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=Ae.get("instance"),{sdkAppId:s,testEnv:n}=t,o=xe(s);if(n)return We(Ge.TEST[o].DEFAULT,{isBinary:e});const i=Ge.PRODUCTION[o],r=L&&i.ANYCAST;return We({[Be.INITIAL]:()=>(Ve=Be.DEFAULT,i.DEFAULT),[Be.DEFAULT]:()=>(Ve=Be.BACKUP,i.BACKUP),[Be.BACKUP]:()=>(Ve=r?Be.ANYCAST:Be.DEFAULT,r?i.ANYCAST:i.DEFAULT),[Be.ANYCAST]:()=>(Ve=Be.DEFAULT,i.ANYCAST="",i.DEFAULT)}[Ve](),{isBinary:e})}(this._isBinarySupported);try{this._isReconnecting=!0,this.disconnect(),this.connect()}catch(e){this._isReconnecting=!1,this._handleConnectStateChange({state:Ct,reason:At}),console.warn(`${pt} reconnect failed: `,e)}}}))}_addEventListeners(){var e,t,s,n,o;null===(e=this._socketAdapter)||void 0===e||e.on("connect",this._onConnect,this),null===(t=this._socketAdapter)||void 0===t||t.on("message",this._onMessage,this),null===(s=this._socketAdapter)||void 0===s||s.on("close",this._onClose,this),null===(n=this._socketAdapter)||void 0===n||n.on("error",this._onError,this),null===(o=this._socketAdapter)||void 0===o||o.on("sendFail",this._onSendFail,this)}_removeEventListeners(){var e,t,s,n,o;null===(e=this._socketAdapter)||void 0===e||e.off("connect",this._onConnect,this),null===(t=this._socketAdapter)||void 0===t||t.off("message",this._onMessage,this),null===(s=this._socketAdapter)||void 0===s||s.off("close",this._onClose,this),null===(n=this._socketAdapter)||void 0===n||n.off("error",this._onError,this),null===(o=this._socketAdapter)||void 0===o||o.off("sendFail",this._onSendFail,this)}_onClose(e){const{socketId:t,event:s}=e||{},n=0!==this._connectionEstablishedTime?Date.now()-this._connectionEstablishedTime:0,o=`${pt} onClose closeSocketID: ${t} currentSocketID: ${this._connectionId} connectionDuration: ${n} code:${null==s?void 0:s.code} reason:${null==s?void 0:s.reason}`;this._ssoLog({method:"onClose",message:o}),console.warn(o),t===this._connectionId&&this._handleConnectStateChange({state:Ct,reason:Rt}),this._isReconnecting&&(this._isReconnecting=!1)}_onError(e){const{socketId:t,error:s}=e||{},n=`${pt} onError sourceSocketID: ${t} currentSocketID:${this._connectionId} isReconnecting: ${this._isReconnecting} error: ${JSON.stringify(s)}`;this._ssoLog({method:"onError",message:n}),console.warn(n),t===this._connectionId&&this._handleConnectStateChange({state:Ct,reason:Nt}),this._isReconnecting&&(this._isReconnecting=!1)}_onSendFail(e){const{socketId:t,error:s}=e||{},n=`${pt} onSendFail sendFailSocketId: ${t} currentSocketID:${this._connectionId} isReconnecting: ${this._isReconnecting} error: ${s}`;this._ssoLog({method:"onSendFail",message:n}),console.warn(n),t===this._connectionId&&this._handleConnectStateChange({state:Ct,reason:Tt}),this._isReconnecting&&(this._isReconnecting=!1)}_onMessage(e){let t,s;this._updateHeartbeatTime();try{t=this._isBinarySupported?this._isCompressedData(e.data)?(e=>{const t=new Uint8Array(e).slice(4);let s;try{s=Pt.inflate(t,{to:"string"})}catch(e){console.error("inflate error",e)}return s})(e.data):function(e){const t=new Uint8Array(e);let s="",n=0;const{length:o}=t;for(;n<o;){let e=t[n],i=0,r=0;if(e<=127?(i=0,r=255&e):e<=223?(i=1,r=31&e):e<=239?(i=2,r=15&e):e<=244&&(i=3,r=7&e),o-n-i>0)for(let s=0;s<i;s+=1)e=t[n+s+1],r=r<<6|63&e;else r=65533,i=o-n;s+=String.fromCodePoint(r),n+=i+1}return s}(e.data):e.data,s=JSON.parse(t)}catch(t){const s=e.data;return this._ssoLog({method:"jsonParseError",message:s}),void console.error(t)}if(!s||!s.head)return;const{seq:n,servcmd:o}=s.head,i=`${n}${o}`;this._pendingRequests.has(i)?this._handleRequestResponse(s):this._handlePushMessage(s)}_handleRequestResponse(e){const{seq:t,servcmd:s}=e.head,{int32_error_code:n,str_error_message:o,ErrorCode:r=n,ErrorInfo:a=o}=(null==e?void 0:e.body)||{},c=`${t}${s}`,{resolve:l,reject:d,timestamp:u,headSeq:_}=this._pendingRequests.get(c);if(this._pendingRequests.delete(c),r&&0!==r)return i.emitInnerEvent("error",{errorCode:r,errorInfo:a}),void d({errorCode:r,errorInfo:a});l(e.body)}_handlePushMessage(e){const{servcmd:t}=e.head,{NeedAck:s,SessionData:n}=e.body;1===s&&this._sendAck(n),i.emitInnerEvent(t,e)}_checkPendingRequestsAndResend(){var e;console.log(`${pt}._checkPendingRequestsAndResend reConnectFlag:${this._isReconnecting} promiseMap.size:${this._pendingRequests.size}`),null===(e=this._pendingRequests)||void 0===e||e.forEach(((e,t)=>{var s;const{uplinkData:n,canResend:o,resolve:i,reject:r,timeout:a}=e;if(o){this._pendingRequests.set(t,{resolve:i,reject:r,timestamp:Date.now(),uplinkData:n,timeout:a,canResend:o});const e=this._isBinarySupported?He(n).buffer:n;null===(s=this._socketAdapter)||void 0===s||s.send(e)}else this._pendingRequests.delete(t)}))}_onConnect(e){const{socketId:t,event:s={}}=e||{};this._connectionId=t,this._connectionEstablishedTime=Date.now();const n=Date.now()-this._connectionStartTime,o=`${pt} onConnect cost:${n} ms. socketID:${t} res:${JSON.stringify(s)}`;if(this._ssoLog({method:"onConnect",message:o}),console.log(o),this._checkPendingRequestsAndResend(),this._sendHeartbeatIfReady(),this._isReconnecting){const e=`${pt} reconnect success`;this._ssoLog({method:"reconnectSuccess",message:e}),console.log(e),i.emitInnerEvent(ct.RECONNECTED),this._isReconnecting=!1}this._resetReconnectDelay(),this._handleConnectStateChange({state:vt})}_sendAck(e){const t=Je({servcmd:"openim.ws_msg_push_ack",data:{SessionData:e}});this.sendPacket(t)}_executeScheduledTaskIfReady(){return r(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 r(this,void 0,void 0,(function*(){var e;const t=Je({servcmd:"heartbeat.alive",data:{}});try{const e=`${t.head.seq}${t.head.servcmd}`;yield this.sendPacket(t,{requestId:e,timeout:3e3})}catch(t){const s=null===(e=Ae.get("netWorkMonitor"))||void 0===e?void 0:e.isNetWorkOnline,n=`${pt} sendHeartbeat failed. isNetWorkOnline:${s} error: ${t}`;this._ssoLog({method:"sendHeartbeatError",message:n}),console.debug(n),this._handleConnectStateChange({state:Ct,reason:Tt})}}))}_sendHeartbeatIfReady(){return r(this,void 0,void 0,(function*(){this._canSendHeartbeat()&&(this._isHeartbeatInProgress=!0,yield this._sendHeartbeat(),this._isHeartbeatInProgress=!1)}))}_updateHeartbeatTime(){this._nextHeartbeatAt=N?Date.now()+5e3:Date.now()+1e4}_handleNetworkStatusChange(e){const t=`${pt} networkStatusChange ${JSON.stringify(e)}`;this._ssoLog({method:"networkStatusChange",message:t}),console.warn(t);const{isNetworkOnline:s,networkType:n}=e;s&&"none"!==n?this._handleConnectStateChange({state:vt,reason:Mt}):this._handleConnectStateChange({state:Ct,reason:Mt})}isPrivateNetWork(){const e=Ae.get("instance")||{};return e.proxyServer&&!e.fileDownloadProxy}_handleConnectStateChange(e){const{state:t,reason:s}=e;if(this._currentConnectState!==t){const e=`${pt}._handleConnectStateChange from ${this._currentConnectState} to ${t} reason: ${s}`;this._ssoLog({method:"handleConnectStateChange",message:e}),console.log(e),this._currentConnectState=t,i.emitOuterEvent("netStateChange",{name:"netStateChange",data:{state:t}}),t===Ct&&i.emitInnerEvent(ct.SOCKET_DISCONNECTED),t!==Ct&&t!==vt||(this._resetReconnectDelay(),je.addTask({id:St,intervalMs:this._intendedDelay,callback:this._scheduleReconnectWithBackoff,context:this}))}}_handleActivityStatusChange(e){var t,s;const n=null===(s=null===(t=this._socketAdapter)||void 0===t?void 0:t._ws)||void 0===s?void 0:s.readyState,o=`${pt} activityStatusChange ${JSON.stringify(e)} readyState: ${n}`;this._ssoLog({method:"activityStatusChange",message:o}),console.warn(o),3===n&&this._handleConnectStateChange({state:Ct,reason:Ot})}_resetReconnectDelay(){var e;je.removeTask(St);const t=null===(e=Ae.get("activityMonitor"))||void 0===e?void 0:e.isActive;this._intendedDelay=t?yt:1e3}_scheduleReconnectWithBackoff(){var e;const t=null===(e=Ae.get("activityMonitor"))||void 0===e?void 0:e.isActive;this._intendedDelay=t?Math.min(5e3,Math.max(yt,1.5*this._intendedDelay)):Math.min(3e5,Math.max(1e3,1.5*this._intendedDelay));const s=(new Date).toTimeString().slice(0,8),n=`${pt}.scheduleReconnectWithBackoff timeStr: ${s} intendedDelay: ${this._intendedDelay}`;this._ssoLog({method:"scheduleReconnectWithBackoff",message:n}),console.log(n),this.reconnect(),je.updateTaskInterval(St,this._intendedDelay)}_ssoLog(e){const{method:t,message:s}=e;ft.createSSOLogData({method:t}).setLogInfo({message:s}).end()}_diagnose(){this.isPrivateNetWork()||(this._lastDiagnoseAt=Date.now(),function(e){r(this,void 0,void 0,(function*(){const t=e.split("/")[2];if(!t.startsWith("ws"))return;const s=`https://${t}/v3/netcheck/getconninfo?${e.slice(e.indexOf("info?")+5)}&reqtime=${Date.now()}`;try{yield de({method:"GET",url:s,data:{}})}catch(e){console.warn("diagnoseBySSO failed. error:",e)}}))}(this._url),function(e){r(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 de({method:"GET",url:t,data:{}})}catch(e){console.warn("diagnoseByCDN failed. error:",e)}}))}(this._url),this._beforeSendInterceptors=[])}_clearTimeoutRequest(){for(const[e,t]of this._pendingRequests.entries()){const{reject:s,timestamp:n,timeout:o}=t;Date.now()-n>=o&&(this._pendingRequests.delete(e),Date.now()-this._lastDiagnoseAt>=3e4&&this._diagnose(),s({errorCode:ae,errorInfo:"NETWORK_TIMEOUT",data:{requestId:e}}))}}_updateIsBinarySupported(){var e;if(null===(e=Ae.get("instance"))||void 0===e?void 0:e.devMode)return void(this._isBinarySupported=!1);const t=ie();(T||I&&"windows"===t||N)&&(this._isBinarySupported=!1)}_isCompressedData(e){const t=new Uint8Array(e);return 67===t[0]&&79===t[1]&&77===t[2]&&80===t[3]}};const Ut={init:function(e){Ae.set("instance",e),Lt.init()},destroy:function(){Lt.dispose(),Ae.clear(),je.dispose()},notificationCenter:i,channel:Lt,store:Ae,ssoLog:ft,utils:ge,common:nt,constants:v};var Gt;!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"}(Gt||(Gt={}));var Ft,xt=Gt;!function(e){e.LOGOUT="logout",e.DESTROY="destroy",e.CLOUD_CONFIG_UPDATE="cloud_config_update",e.PROFILE_UPDATE="profile_updated",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.SOCKET_DISCONNECTED="socket_disconnected",e.CONVERSATION_UPDATED="conversation_updated"}(Ft||(Ft={}));var Bt,$t=Ft;!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"}(Bt||(Bt={}));var Vt=Bt;const qt=Object.assign({},{KICKED_OUT_MULT_ACCOUNT:"multipleAccount",KICKED_OUT_MULT_DEVICE:"multipleDevice",KICKED_OUT_USERSIG_EXPIRED:"userSigExpired",KICKED_OUT_REST_API:"REST_API_Kick"}),Wt={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 Yt;!function(e){e.UNSENT="unSend",e.SUCCESS="success",e.FAIL="fail"}(Yt||(Yt={}));const Kt={modify:$t.MESSAGE_MODIFIED,delete:$t.MESSAGE_DELETED,revoke:$t.MESSAGE_REVOKED},jt=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},Wt),{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:Yt}),Ht={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,USER_NOT_FOUND:"@TLS#NOT_FOUND"},zt=Object.assign({},Ht),Zt=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"}),Jt=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"}),Xt={COMMUNITY:"@TGS#_",TOPIC:"@TOPIC#_"},Qt=Object.assign(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"}),{GROUP_ID_PREFIX:Xt}),es=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},qt),jt),zt),Zt),Jt),Qt),{IOS_OFFLINE_PUSH_NO_SOUND:"push.no_sound",IOS_OFFLINE_PUSH_DEFAULT_SOUND:"default"}),{NET_STATE_CONNECTING:"connecting",NET_STATE_DISCONNECTED:"disconnected"}),ts={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},ss={SYNC_SERVER_INFO_AFTER_RE_ONLINE:"sync-server-info-after-re-online",SYNC_SERVER_INFO_AFTER_LOGIN:"sync-server-info-after-login",RECEIVE_C2C_NEW_MESSAGE:"receive-c2c-new-message",RECEIVE_GROUP_NEW_MESSAGE:"receive-group-new-message"},ns={USER_STATUS_UPDATE:"user-status-update",CONVERSATION_RECOVER:"conversation-recover",HISTORY_MESSAGE_RECOVER:"history-message-recover",BLACKLIST_RECOVER:"blacklist-recover",FRIEND_RECOVER:"friend-recover",GROUP_ATTRIBUTE_CACHE_CLEAR:"group-attribute-cache-clear",UNREAD_MESSAGE_RECOVER:"unread-message-recover",HANDLE_NEW_MESSAGE:"handle-new-message",HANDLE_CONVERSATION_PROFILE_UPDATED:"handle-conversation-profile-updated",COMMERCIAL_CONFIG_UPDATE:"commercial-config-update",UNREAD_MESSAGE_SYNC:"unread-message-sync",FRIEND_AND_BLACKLIST_SYNC:"friend-and-blacklist-sync",SIGNALING_MESSAGE_RECOVER:"signaling-message-recover",GROUP_LIST_SYNC:"group-list-sync",CONVERSATION_LIST_SYNC:"conversation-list-sync",USER_PROFILE_SYNC:"user-profile-sync",CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED:"conversation-update-after-unread-sync-finished",CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED:"conversation-update-after-group-list-sync-finished",HANDLE_C2C_NEW_MESSAGE:"handle-c2c-new-message",HANDLE_GROUP_NEW_MESSAGE:"handle-group-new-message",CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE:"create-or-update-conversation-by-receive-new-message",HANDLE_GROUP_TIPS_FROM_SYNC_UNREAD:"handle-group-tips-from-sync-unread",HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD:"handle-c2c-revoked-message-from-sync-unread",GROUP_REVOKED_NOTICE_RECOVER:"group-revoked-notice-recover",CLOUD_CONFIG_SYNC:"cloud-config-sync",UPDATE_GROUP_NEXT_SEQUENCE:"update-group-next-sequence",EMIT_C2C_MESSAGE_EVENT:"emit-c2c-message-event",EMIT_GROUP_MESSAGE_EVENT:"emit-group-message-event"},os={[ss.SYNC_SERVER_INFO_AFTER_RE_ONLINE]:[{stepId:ns.USER_STATUS_UPDATE},{stepId:ns.GROUP_ATTRIBUTE_CACHE_CLEAR},{stepId:ns.UNREAD_MESSAGE_SYNC},{stepId:ns.CONVERSATION_RECOVER},{stepId:ns.HISTORY_MESSAGE_RECOVER,dependency:ns.CONVERSATION_RECOVER},{stepId:ns.BLACKLIST_RECOVER},{stepId:ns.FRIEND_RECOVER},{stepId:ns.GROUP_REVOKED_NOTICE_RECOVER},{stepId:ns.HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD,dependency:ns.UNREAD_MESSAGE_SYNC},{stepId:ns.HANDLE_GROUP_TIPS_FROM_SYNC_UNREAD,dependency:ns.UNREAD_MESSAGE_SYNC},{stepId:ns.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[ns.UNREAD_MESSAGE_SYNC,ns.CONVERSATION_RECOVER]},{stepId:ns.EMIT_C2C_MESSAGE_EVENT,dependency:[ns.UNREAD_MESSAGE_SYNC,ns.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED],skipIfDependencyMissing:!1}],[ss.SYNC_SERVER_INFO_AFTER_LOGIN]:[{stepId:ns.COMMERCIAL_CONFIG_UPDATE},{stepId:ns.CLOUD_CONFIG_SYNC},{stepId:ns.USER_PROFILE_SYNC},{stepId:ns.UNREAD_MESSAGE_SYNC},{stepId:ns.FRIEND_AND_BLACKLIST_SYNC},{stepId:ns.GROUP_LIST_SYNC},{stepId:ns.CONVERSATION_LIST_SYNC},{stepId:ns.SIGNALING_MESSAGE_RECOVER,dependency:ns.UNREAD_MESSAGE_SYNC},{stepId:ns.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[ns.UNREAD_MESSAGE_SYNC,ns.CONVERSATION_LIST_SYNC]},{stepId:ns.CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED,dependency:[ns.GROUP_LIST_SYNC,ns.CONVERSATION_LIST_SYNC]}],[ss.RECEIVE_C2C_NEW_MESSAGE]:[{stepId:ns.HANDLE_C2C_NEW_MESSAGE},{stepId:ns.UNREAD_MESSAGE_SYNC},{stepId:ns.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:ns.HANDLE_C2C_NEW_MESSAGE},{stepId:ns.EMIT_C2C_MESSAGE_EVENT,dependency:[ns.HANDLE_C2C_NEW_MESSAGE,ns.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1},{stepId:ns.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[ns.UNREAD_MESSAGE_SYNC]}],[ss.RECEIVE_GROUP_NEW_MESSAGE]:[{stepId:ns.HANDLE_GROUP_NEW_MESSAGE},{stepId:ns.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:ns.HANDLE_GROUP_NEW_MESSAGE},{stepId:ns.UPDATE_GROUP_NEXT_SEQUENCE,dependency:ns.HANDLE_GROUP_NEW_MESSAGE},{stepId:ns.EMIT_GROUP_MESSAGE_EVENT,dependency:[ns.HANDLE_GROUP_NEW_MESSAGE,ns.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1}]};var is=Object.freeze({__proto__:null,ERROR_CODE:ts,InnerEvent:$t,OuterConstant:es,OuterEvent:xt,SDK_INFO:{VERSION:"1.7.3",APPID:537048168},SignalingEvent:Vt,WORKFLOW_DEFINITIONS:os,WORKFLOW_NAME:ss,WORKFLOW_STEP:ns});function rs(e){var t;try{const s=Ae.getStorage("errorMessage");if(!e||!s)return"";const n=(null===(t=JSON.parse(s))||void 0===t?void 0:t.errorMessage)||{},{isIntl:o=!1,code:i,replacement1:r="",replacement2:a=""}=e;if(!i)return"";const c=o?`${i}_en`:`${i}_cn`;let l=n[n[c]?c:i]||"";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 as extends Error{constructor(e){const{functionName:t="Unknown",code:s,message:n="",data:o=""}=e;let i=n;s&&!n&&(i=rs(e));const r=s?`${t} failed. error: {"message": ${i}, "code": ${s}}`:`${t} failed. error: {"message": ${i}}`;super(),this.code=s,this.errorCode=s,this.errorMessage=r,this.message=r,this.data=o}}function cs(e,t){var s;if(!e)return;if(!(!0===(null===(s=Ut.store.get("login"))||void 0===s?void 0:s.isLoggedIn)))throw new as({code:ts.USER_NOT_LOGGED_IN,functionName:t})}const ls=e=>"function"==typeof e;function ds(e,t,s){const n=s||[];if(!e||!t)return!1;const o=Object.keys(e).filter((e=>!n.includes(e))),i=Object.keys(t).filter((e=>!n.includes(e)));return o.length===i.length&&o.every((n=>!!t.hasOwnProperty(n)&&("object"==typeof e[n]&&null!==e[n]?ds(e[n],t[n],s):e[n]===t[n])))}function us(e,t,s){if(Array.isArray(e))for(let n=0;n<e.length;n++)_s.call(this,Object.assign(Object.assign({},e[n]),{value:t[n],name:s}));else for(const n in e)_s.call(this,Object.assign(Object.assign({},e[n]),{value:t[0][n],name:s,key:n}))}function _s({required:e,rules:t,range:s,value:n,allowEmpty:o,name:i,key:r,customValidator:a}){if(void 0===n){if(e){throw new as({functionName:i,message:`[${i}] Missing required params: "${r}"`})}return}let c="";if(!t.some((e=>{return e===(t=n,Object.prototype.toString.call(t).match(/^\[object (.*)\]$/)[1].toLowerCase());var t}))){for(let e=0;e<t.length;e++){let s=t[e];s=s.replace(s[0],s[0].toUpperCase()),c+=`${s}/`}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()}(n)}.`;throw new as({functionName:i,message:e})}if(!1===o){if(Array.isArray(n)&&(0===n.length||"string"==typeof n[0]&&""===n[0].trim())){throw new as({functionName:i,message:`${r} can not be empty.`})}if("string"==typeof n&&""===n.trim()){throw new as({functionName:i,message:`${r} can not be empty.`})}}if(a&&"function"==typeof a){const e=a(n);if(!0!==e){throw new as({functionName:i,message:`[${r}] custom validation failed: ${e||"Invalid value"}`})}}}const hs=[],gs={},fs={};function Es(e,t){cs(gs[e],e),us(fs[e],t,e),function(e){hs.forEach((t=>{const{interceptor:s,context:n}=t;s.apply(n,[e])}))}(e)}function ps(e,t){hs.push({interceptor:e,context:t})}function ms(e){const{params:t,auth:s}=e;t&&"object"==typeof t&&Object.assign(fs,t),s&&"object"==typeof s&&Object.assign(gs,s)}var Ss=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,s){let n=[];n=Array.isArray(e)?e:[e],n.forEach((e=>{t.has(e)||(e&&ls(e.install)?(t.add(e),e.install(Cn(),s),ls(e.handleLoginSuccess)&&this._isLoggedIn()&&e.handleLoginSuccess()):ls(e)?(t.add(e),e(Cn(),s),ls(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=Ut.store.get("login"))||void 0===e?void 0:e.isLoggedIn)}};function vs(e){return Ut.store.get("commercialConfig").get(e)}const Is=new Map;var Cs=new class{constructor(){this._handlers=new Map,this._activeWorkflows=new Map,this._stepStartTimes=new Map,this._logHandlers={start:(e,t)=>{const s=Date.now();t?(this._stepStartTimes.set(`${e}-${t}`,s),console.log(`[Workflow ${e}] Step ${t} started at ${new Date(s).toISOString()}`)):(this._workflowStartTimes.set(e,s),console.log(`[Workflow ${e}] started at ${new Date(s).toISOString()}`))},success:(e,t)=>{const s=Date.now();if(t){const n=this._stepStartTimes.get(`${e}-${t}`),o=n?s-n:0;this._stepStartTimes.delete(`${e}-${t}`),console.log(`[Workflow ${e}] Step ${t} completed successfully at ${new Date(s).toISOString()} (${o}ms)`)}else{const t=this._workflowStartTimes.get(e),n=t?s-t:0;this._workflowStartTimes.delete(e),console.log(`[Workflow ${e}] completed successfully at ${new Date(s).toISOString()} (${n}ms)`)}},error:(e,t,s)=>{const n=Date.now();if(t){const o=this._stepStartTimes.get(`${e}-${t}`),i=o?n-o:0;this._stepStartTimes.delete(`${e}-${t}`),console.error(`[Workflow ${e}] Step ${t} failed at ${new Date(n).toISOString()} (${i}ms)`,s)}else{const t=this._workflowStartTimes.get(e),o=t?n-t:0;this._workflowStartTimes.delete(e),console.error(`[Workflow ${e}] failed at ${new Date(n).toISOString()} (${o}ms)`,s)}}}}init(){this._initializeWorkflows()}registerWorkflowStep(e,t,s,n){if(!this._handlers.has(e))return void console.debug(`Workflow '${e}' not defined in core`);if(!os[e].find((e=>e.stepId===t)))return void console.debug(`Step '${t}' not defined in workflow '${e}'`);this._handlers.get(e).set(t,n?s.bind(n):s)}executeWorkflow(e,t){return r(this,void 0,void 0,(function*(){if(!this._validateWorkflow(e))return;console.log(`[Workflow ${e}] Started execution at ${(new Date).toISOString()}`);const s=os[e],n={},o={cancelled:!1};this._activeWorkflows.set(e,{cancelToken:o});try{const i=new Map;s.forEach((e=>{i.set(e.stepId,e)}));const r={workflowName:e,pendingSteps:new Set(s.map((e=>e.stepId))),completedSteps:new Set,runningSteps:new Set,stepMap:i,stepResults:n,data:t,cancelToken:o};yield new Promise(((t,s)=>{const n=()=>{if(o.cancelled)return void t();this._getExecutableSteps({pendingSteps:r.pendingSteps,completedSteps:r.completedSteps,stepMap:r.stepMap,workflowName:e}).filter((e=>!r.runningSteps.has(e))).forEach((o=>{r.completedSteps.has(o)||r.runningSteps.has(o)||this._executeWorkflowStep(o,r,{onComplete:()=>{if(0===r.pendingSteps.size)return void t();0===this._getExecutableSteps({pendingSteps:r.pendingSteps,completedSteps:r.completedSteps,stepMap:r.stepMap,workflowName:e}).filter((e=>!r.runningSteps.has(e))).length&&0===r.runningSteps.size&&(console.log(`Workflow ${e} completed with some steps skipped due to dependency failures`),t())},onError:s,onStepComplete:n})}))};n()})),console.log(`[Workflow ${e}] Completed execution at ${(new Date).toISOString()}`)}catch(t){console.error(`[Workflow ${e}] Failed execution at ${(new Date).toISOString()}`,t)}finally{this._activeWorkflows.delete(e)}}))}_executeWorkflowStep(e,t,s){return r(this,void 0,void 0,(function*(){const{workflowName:n,runningSteps:o,stepMap:i,stepResults:r,data:a}=t;o.add(e),this._logWorkflowExecution(n,e,"start");try{const s=i.get(e);let o=null;(null==s?void 0:s.dependency)&&(c(s.dependency)?o=r[s.dependency]:Array.isArray(s.dependency)&&(o={},s.dependency.forEach((e=>{o[e]=r[e]}))));const l=this._handlers.get(n).get(e);if(l){const t=yield Promise.resolve(l({data:a,result:o}));r[e]=t,this._logWorkflowExecution(n,e,"success")}t.completedSteps.add(e)}catch(t){const o=`[Workflow].${n}.${e}`,{errorCode:i,errorInfo:r=`${o} failed`}=t||{},a=new as({functionName:o,code:i,message:r});Ut.ssoLog.createSSOLogData({method:"Workflow"}).setLogInfo({message:`workflowName: ${n}, stepId: ${e}`}).setError(a).end(),this._logWorkflowExecution(n,e,"error",t),s.onError(t)}finally{o.delete(e),t.pendingSteps.delete(e),s.onStepComplete(),s.onComplete()}}))}reset(){this._cancelAllWorkflows()}destroy(){this.reset(),this._handlers.clear()}_initializeWorkflows(){Object.keys(os).forEach((e=>{this._handlers.set(e,new Map)}))}_cancelWorkFlow(e){const t=this._activeWorkflows.get(e);if(!t)return;const{cancelToken:s}=t;s.cancelled=!0,this._activeWorkflows.delete(e)}_cancelAllWorkflows(){Object.keys(os).forEach((e=>{this._cancelWorkFlow(e)}))}_validateWorkflow(e){if(!os[e])return console.debug(`Workflow '${e}' not defined`),!1;return!!this._handlers.get(e)||(console.debug(`No handlers registered for workflow '${e}'`),!1)}_getExecutableSteps(e){const{pendingSteps:t,completedSteps:s,stepMap:n,workflowName:o}=e;return Array.from(t).filter((e=>{const t=n.get(e)||{},{dependency:i,skipIfDependencyMissing:r=!0}=t;if(!i)return!0;if(c(i))return this._isStepRegistered({workflowName:o,stepId:i})?s.has(i):!r;if(d(i)){if(i.filter((e=>!this._isStepRegistered({workflowName:o,stepId:e}))).length>0&&r)return!1;for(const e of i)if(!s.has(e))return!1;return!0}return!1}))}_isStepRegistered(e){var t;const{workflowName:s,stepId:n}=e;return null===(t=this._handlers.get(s))||void 0===t?void 0:t.has(n)}_logWorkflowExecution(e,t,s,n){this._logHandlers[s](e,t)}};function ys(){var e;return null===(e=Ut.store.get("login"))||void 0===e?void 0:e.userId}const Ms=e=>d(e)||u(e),Os=(e,t,s,n)=>{if(!Ms(e)||!Ms(t))return 0;let o=0;const i=Object.keys(t);let r;for(let c=0,l=i.length;c<l;c++)if(r=i[c],!(a(t[r])||s&&s.includes(r)))if(Ms(e[r])&&Ms(t[r]))o+=Os(e[r],t[r],s,n);else{if(n&&n.includes(t[r]))continue;e[r]!==t[r]&&(e[r]=t[r],o+=1)}return o},Ts=e=>`${e}`.startsWith(Xt.COMMUNITY)&&`${e}`.includes(Xt.TOPIC),As=(e,t)=>{if(a(t))return"";switch(e){case es.MSG_TEXT:return t.text||"";case es.MSG_IMAGE:return"[Image]";case es.MSG_LOCATION:return"[Location]";case es.MSG_AUDIO:return"[Voice]";case es.MSG_VIDEO:return"[Video]";case es.MSG_FILE:return"[File]";case es.MSG_CUSTOM:return"[Custom Messages]";case es.MSG_GRP_TIP:return"[Group Notification]";case es.MSG_GRP_SYS_NOTICE:return"[Group System Message]";case es.MSG_FACE:return"[Animated Sticker]";case es.MSG_MERGER:return"[Chat Record]";default:return""}},Ns=[{cmd:"ws_get_user_status",interval:5,count:20},{cmd:"ws_status_subscribe",interval:5,count:20},{cmd:"ws_status_unsubscribe",interval:5,count:20},{cmd:"get_group_self_member_info",interval:5,count:20},{cmd:"modify_group_base_info",interval:1,count:8},{cmd:"get_members",interval:3,count:1},{cmd:"get_pendency",interval:1,count:15},{cmd:"set_group_attr",interval:5,count:10},{cmd:"modify_group_attr",interval:5,count:10},{cmd:"delete_group_attr",interval:5,count:10},{cmd:"clear_group_attr",interval:5,count:10},{cmd:"get_group_attr",interval:5,count:20},{cmd:"update_group_counter",interval:5,count:20},{cmd:"get_group_counter",interval:5,count:20},{cmd:"get_topic",interval:1,count:10},{cmd:"read_all_unread_msg",interval:1,count:1},{cmd:"query",interval:5,count:20}],Rs="im_sdk_config_mgr.fetch_config",Ds="im_sdk_config_mgr.push_configv2",ws="cloud-config",bs=2996;var ks=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:s,helper:n,constants:{WORKFLOW_NAME:o,WORKFLOW_STEP:i},channel:r}=e;t.subscribeInnerEvent(Ds,this._handlePushedConfig,this),n.registerWorkflowStep(o.SYNC_SERVER_INFO_AFTER_LOGIN,i.CLOUD_CONFIG_SYNC,this._handleLoginSuccess,this),t.subscribeInnerEvent(s.LOGOUT,this._reset,this),t.subscribeInnerEvent(s.DESTROY,this._dispose,this),n.registerExperimentalAPI("getServerConfig",this),this._updateCmdFreqLimitMap(Ns),r.registerBeforeSendInterceptor(this.checkMethodCallOverLimit,this)}getServerConfig(e){var t;const s={code:0,data:""};return e?(s.data=(null===(t=this._core.store.get("cloudConfig"))||void 0===t?void 0:t[e])||"",s):s}checkMethodCallOverLimit(e){if(!this._cmdFrequencyLimitMap.has(e))return;if(!this._methodCallFrequencyMap.has(e))return void this._methodCallFrequencyMap.set(e,{startTime:Date.now(),methodCallCounter:1});const{count:t,interval:s}=this._cmdFrequencyLimitMap.get(e);let{startTime:n,methodCallCounter:o}=this._methodCallFrequencyMap.get(e);if(Date.now()-n>1e3*s)this._methodCallFrequencyMap.set(e,{startTime:Date.now(),methodCallCounter:1});else if(o+=1,this._methodCallFrequencyMap.set(e,{startTime:n,methodCallCounter:o}),o>t)throw new this._core.helper.ChatError({code:bs,replacement1:e})}_fetchCloudConfig(){return r(this,void 0,void 0,(function*(){try{const{sdkAppId:e}=this._core.store.get("instance")||{},t=this._core.helper.generateProtocolData({servcmd:Rs,data:{uint32_sdkappid:e,uint64_version:this._version}}),s=`${t.head.seq}${Rs}`;return yield this._core.channel.sendPacket(t,{requestId:s})}catch(e){throw console.warn("fetch cloudControl fail: ",e),e}}))}_handlePushedConfig(e){this._updateCloudConfig(e)}_handleLoginSuccess(){return r(this,void 0,void 0,(function*(){try{if(this._canFetch()){const e=yield this._fetchCloudConfig();this._updateCloudConfig(e)}this._core.helper.taskScheduler.addTask({id:ws,intervalMs:1e3,callback:this._fetchCloudConfigIfReady,context:this})}catch(e){console.warn(e)}}))}_fetchCloudConfigIfReady(){return r(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:s,str_json_config:n,uint32_expired_time:o,uint32_sdkappid:i,uint64_version:r}=e;let a=null;if(0===t){if(this._version!==r)try{a=JSON.parse(n),this._version=r}catch(e){}this._expirationTime=Date.now()+1e3*o}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;const{isEmpty:s}=this._core.utils;if(!s(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,count:e.count})}))}_reset(){this._core.helper.taskScheduler.removeTask(ws),this._core.store.clear("cloudConfig"),this._updateCmdFreqLimitMap(Ns),this._methodCallFrequencyMap.clear(),this._expirationTime=0,this._version=0,this._isFetching=!1}_dispose(){const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(Ds,this._handlePushedConfig,this),e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this),this._reset()}};class Ps{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 Ls={SEARCH_GRP_SNS:new Ps(0,Math.pow(2,1)).toString(),AV_HISTORY_MSG:new Ps(0,Math.pow(2,2)).toString(),GRP_COMMUNITY:new Ps(0,Math.pow(2,3)).toString(),MSG_TO_SPECIFIED_GRP_MBR:new Ps(0,Math.pow(2,4)).toString(),AV_MBR_LIST:new Ps(0,Math.pow(2,6)).toString(),USER_STATUS:new Ps(0,Math.pow(2,7)).toString(),CONV_MARK:new Ps(0,Math.pow(2,9)).toString(),CONV_GROUP:new Ps(0,Math.pow(2,10)).toString(),AV_BAN_MBR:new Ps(0,Math.pow(2,11)).toString(),MSG_EXT:new Ps(0,Math.pow(2,13)).toString(),GRP_COUNTER:new Ps(0,Math.pow(2,15)).toString(),PLUGIN_TRANSLATE:new Ps(Math.pow(2,6)).toString(),PLUGIN_VOICE_TO_TEXT:new Ps(Math.pow(2,7)).toString(),PLUGIN_CS:new Ps(Math.pow(2,8)).toString(),PLUGIN_PUSH:new Ps(Math.pow(2,9)).toString(),PLUGIN_BOT:new Ps(Math.pow(2,10)).toString(),MSG_REACTION:new Ps(Math.pow(2,16)).toString(),FOLLOW:new Ps(Math.pow(2,20)).toString()},Us="CommercialConfig",Gs="commercial-config";var Fs=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;const{helper:t,notificationCenter:s,constants:{WORKFLOW_NAME:n,WORKFLOW_STEP:o,InnerEvent:i}}=e;s.subscribeInnerEvent(i.COMMERCIAL_CONFIG_PUSH,this._handlePushedConfig,this),s.subscribeInnerEvent(i.LOGOUT,this._handleLogout,this),s.subscribeInnerEvent(i.DESTROY,this._dispose,this),t.registerWorkflowStep(n.SYNC_SERVER_INFO_AFTER_LOGIN,o.COMMERCIAL_CONFIG_UPDATE,this._syncCommercialConfig,this),e.helper.registerExperimentalAPI("isCommercialAbilityEnabled",this)}isCommercialAbilityEnabled(e){return r(this,void 0,void 0,(function*(){const t=parseInt(e,10).toString(2),{length:s}=t;let n,o=!0;for(let e=s-1,i=0;e>=0;e--,i++)if("1"===t.charAt(e)&&(n=i<32?new Ps(0,2**i).toString():new Ps(2**(i-32),0).toString(),!this._featureMap.get(n))){o=!1;break}return console.log(`${Us}.isFeatureEnabled decimalNumber:${e} key:${n} ret:${o}`),{code:0,data:{enabled:o}}}))}_fetchAndParseCommercialConfig(){return r(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}}),s=yield this._core.channel.sendPacket(t);(null==s?void 0:s.body)&&(this._parseCommercialConfig(s.body),this._core.store.set("commercialConfig",this._methodKeyMap))}catch(e){console.warn("fetch commercial fail: ",e)}finally{this._isFetching=!1}}))}_syncCommercialConfig(e){return r(this,void 0,void 0,(function*(){const{purchaseBits:t}=(null==e?void 0:e.data)||{};t&&(this._parsePurchaseBits(t),this._core.store.set("commercialConfig",this._methodKeyMap)),this._canFetch()&&(yield this._fetchAndParseCommercialConfig()),this._core.helper.taskScheduler.addTask({id:Gs,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,s=Date.now()>=this._expirationTime;return t&&!this._isFetching&&s}_handlePushedConfig(e){(null==e?void 0:e.body)&&(this._parseCommercialConfig(e.body),this._core.store.set("commercialConfig",this._methodKeyMap))}_fetchCommercialConfigIfReady(){return r(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:s,str_purchase_bits:n,uint32_expired_time:o}=e;0===t?(this._parsePurchaseBits(n),this._expirationTime=Date.now()+1e3*o):void 0===t?(console.log(`${Us}._parseCommercialConfig failed. Invalid message format:`,e),this._expirationTime=Date.now()+36e5):(console.error(`${Us}._parseCommercialConfig errorCode:${t} errorMessage:${s}`),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 s=e.length-1,n=0;s>=0;s--,n++)if(t=n<32?new Ps(0,2**n).toString():new Ps(2**(n-32),0).toString(),"1"===e[s]){this._featureMap.set(t,!0);const e=this._getKeyByValue(Ls,t);e&&this._methodKeyMap.set(e,!0)}else{this._featureMap.set(t,!1);const e=this._getKeyByValue(Ls,t);e&&this._methodKeyMap.set(e,!1)}}else console.warn(`${Us}.parsePurchaseBits invalid purchases:${e}`)}_getKeyByValue(e,t){const s=Object.entries(e).find((([e,s])=>s===t));return s?s[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.LOGOUT,this._reset,this),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}_reset(){this._core.helper.taskScheduler.removeTask(Gs),this._core.store.set("commercialConfig",{}),this._expirationTime=0,this._isFetching=!1,this._featureMap.clear()}};var xs=new class{constructor(){this._core=null,this._serverOverloadInfoMap=new Map}install(e){this._core=e;const{notificationCenter:t,InnerEvent:s,channel:n}=this._core;t.subscribeInnerEvent(s.OVERLOAD_PUSH,this._handleOverLoadPush,this),t.subscribeInnerEvent(s.LOGOUT,this._reset,this),t.subscribeInnerEvent(s.DESTROY,this._dispose,this),n.registerBeforeSendInterceptor(this.checkServerOverload,this)}checkServerOverload(e){if(!this._serverOverloadInfoMap.has(e))return;const{overloadStartTimestamp:t,delaySeconds:s}=this._serverOverloadInfoMap.get(e);if(Date.now()-t<=1e3*s)throw new this._core.helper.ChatError({functionName:e,message:"service is busy, please try again later"});this._serverOverloadInfoMap.delete(e)}_handleOverLoadPush(e){const{OverLoadServCmd:t,DelaySecs:s}=e;this._serverOverloadInfoMap.set(t,{overloadStartTimestamp:Date.now(),delaySeconds:s})}_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 Bs=new class{constructor(){this._core=null}install(e){return r(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 r(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"),s={},n=new RegExp(/'/g);for(let e=0;e<t.length;e++){const o=t[e].indexOf(":"),i=t[e].slice(0,o);let r=t[e].slice(o+1);if(!i.startsWith("//")){if(""===r)continue;r=r.replace(n,""),s[i]=r}}return s}}};function $s(e,t){return r(this,void 0,void 0,(function*(){const{cookie:s,syncFlag:n,syncTriggerEvent:o}=e,i="openim.getmsg",r=t.helper.generateProtocolData({servcmd:i,data:{Cookie:s,SyncFlag:n,IsOnlineSync:o,NeedAbstract:1,NeedSignaling:1,NeedCachedMsg:1}}),a=`${r.head.seq}${i}`;try{const e=yield t.channel.sendPacket(r,{requestId:a});if(!e)return null;const{C2CPairUnreadCount:s,C2CRemainingUnreadCount:n,EventArray:o}=e,{unreadMessageList:i,revokedMessageList:c}=function(e,t){const s=[],n=[];return null==e||e.forEach((e=>{var o,i,r;const a=function(e,t){const{From_Account:s,From_AccountHeadurl:n,From_AccountNick:o,IsNeedReadReceipt:i,MsgBody:r,MsgClientTime:a,MsgRandom:c,MsgSeq:l,MsgTimeStamp:d,SendMsgControl:u,SupportMessageExtension:_,To_Account:h,TinyId:g,MsgCheckResult:f,CloudCustomData:E,IsPeerRead:p,MsgFlagBits:m,MsgVersion:S,EventArray:v}=e;return{from:s,avatar:n,nick:o,needReadReceipt:1===i,readReceiptSentByPeer:p,clientTime:a,messageFlagBits:m,random:c,sequence:l,time:d,messageControlInfo:u,isSupportExtension:_,to:h,tinyID:g,checkResult:f,cloudCustomData:E,messageVersion:S,eventArray:v,elements:t.message.messageHelper.parseServerPushMessageElement(r)}}(e,t);if(null===(r=null===(i=null===(o=null==e?void 0:e.EventArray)||void 0===o?void 0:o[0])||void 0===i?void 0:i.hasOwnProperty)||void 0===r?void 0:r.call(i,"C2cNotifyMsgArray"))n.push(...function(e){var t;const s=[];return null===(t=e.EventArray)||void 0===t||t.forEach((e=>{var t,n;const{C2cNotifyMsgArray:o}=e,i=null===(n=null===(t=null==o?void 0:o[0])||void 0===t?void 0:t.WithdrawC2cMsgNotify)||void 0===n?void 0:n.C2cWithdrawInfoArray;Array.isArray(i)&&s.push(...i)})),s}(e));else{const e=t.message.messageFactory.createMessage(Object.assign(Object.assign({},a),{conversationType:"C2C",flow:"in"})),{elements:n}=a;e.setElement(n),s.push(e)}})),{unreadMessageList:s,revokedMessageList:n}}(e.MsgList,t);return{syncFlag:null==e?void 0:e.SyncFlag,unreadMessageList:i,revokedMessageList:c,unreadCountList:s,overflowUnreadCountList:n,cookie:null==e?void 0:e.Cookie,groupTipList:o}}catch(e){console.warn(e)}}))}var Vs,qs;!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.NEW_MESSAGE_RECEIVED=1]="NEW_MESSAGE_RECEIVED"}(qs||(qs={}));var Ws=new class{constructor(){this._unreadDBMessageMap=new Map,this._cookie=""}install(e){this._core=e;const{constants:t}=e;e.helper.registerWorkflowStep(t.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,t.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterReOnline,this),e.helper.registerWorkflowStep(t.WORKFLOW_NAME.RECEIVE_C2C_NEW_MESSAGE,t.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterNewMessageReceived,this),e.helper.registerWorkflowStep(t.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_LOGIN,t.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterLogin,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.LOGOUT,this._reset,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this)}_syncUnreadMessage(e){return r(this,void 0,void 0,(function*(){const{isAfterReOnline:t=!1,isAfterNewMessageReceived:s=!1,isAfterLogin:n=!1}=e||{};let o=Vs.START_SYNC;const i=[],r=[],a=[],c=[];for(;this._canContinueSync({cookie:this._cookie,syncFlag:o});){const e=yield this._fetchUnreadDBMessage({cookie:this._cookie,syncFlag:o,syncTriggerEvent:s?qs.NEW_MESSAGE_RECEIVED:qs.LOGIN_SUCCESS});if(!e)break;const{unreadMessageList:n=[],revokedMessageList:l=[],overflowUnreadCountList:d,unreadCountList:u,groupTipList:_}=e;if(this._cookie=(null==e?void 0:e.cookie)||"",o=null==e?void 0:e.syncFlag,this._parseAndSaveUnreadMessageList(n),a.push(...l),this._updateConversationUnreadOptions({unreadCountList:u,overflowUnreadCountList:d,conversationUpdateFieldList:i}),Array.isArray(_)&&r.push(..._),t){const{messages:e}=this._handleNewMessageList(n);c.push(...e)}}return t?{conversationUpdateFieldList:i,revokedMessageList:a,unreadMessageMap:this._unreadDBMessageMap,groupTipList:r,messages:c}:{conversationUpdateFieldList:i,isInstantMessage:!n,isUnreadC2CMessage:!0,revokedMessageList:a,unreadMessageMap:this._unreadDBMessageMap,groupTipList:r}}))}_syncUnreadDBMessageAfterLogin(){return r(this,void 0,void 0,(function*(){return this._syncUnreadMessage({isAfterLogin:!0})}))}_syncUnreadDBMessageAfterNewMessageReceived(e){return r(this,void 0,void 0,(function*(){if(1===e.data.Flag)return this._syncUnreadMessage({isAfterNewMessageReceived:!0})}))}_updateConversationUnreadOptions(e){const{unreadCountList:t,overflowUnreadCountList:s,conversationUpdateFieldList:n}=e,{constants:{OuterConstant:{CONV_C2C:o,CONV_SYSTEM:i}}}=this._core;null==t||t.forEach((e=>{const{From_Account:t,UnreadCount:s}=e;if(t!==i){const e=n.find((({conversationID:e})=>e===`${o}${t}`));e?e.unreadCount=s:n.push({conversationID:`${o}${t}`,unreadCount:s,type:o})}})),null==s||s.forEach((e=>{const{From_Account:t,LastMsgTime:s}=e;if(t!==i){n.find((({conversationID:e})=>e===`${o}${t}`))||n.push({conversationID:`${o}${t}`,type:o,lastMsgTime:s})}}))}_syncUnreadDBMessageAfterReOnline(){return r(this,void 0,void 0,(function*(){return this._syncUnreadMessage({isAfterReOnline:!0})}))}_updateMessageProfile(e){var t;const{messageDataHandler:s}=this._core.message||{},n=null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userId,{from:o,nick:i,avatar:r,conversationID:a=""}=e;if(o!==n){const t=s.getLatestMsgSentByPeer(a);if(t){const{nick:n,avatar:o}=t;i&&r?i===n&&r===o||s.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:i,latestAvatar:r,isSentByMe:!1}):(e.nick=n,e.avatar=o)}}else{const e=s.getLatestMsgSentByMe(a);!e||i===e.nick&&r===e.avatar||s.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:i,latestAvatar:r,isSentByMe:!0})}}_handleNewMessageList(e){const{messageDataHandler:t}=this._core.message||{},s=new Map,n=[];return e.forEach((e=>{this._updateMessageProfile(e);let o=1===e.isModified;if(t.isMessageSentByCurrentInstance(e)?e.isModified=o:o=!1,e.isOnlineMessage())e._onlineOnlyFlag=!0,t.isMessageSentByCurrentInstance(e)||n.push(e);else if(!t.isInMessageList(e)){if(t.storeConversationMessage(e)){const{conversationID:t,conversationType:n,conversationSubType:o,flow:i,_isExcludedFromUnreadCount:r,_isExcludedFromLastMessage:a}=e,c=a?"":e;s.has(t)?(s.get(t).lastMessage=c,"in"===i&&(r||s.get(t).unreadCount++)):s.set(t,{conversationID:t,type:n,subType:o,unreadCount:r||"in"!==i?0:1,lastMessage:c})}t.isMessageSentByCurrentInstance(e)&&!o||n.push(e)}})),{messages:n,conversationOptions:s}}_fetchUnreadDBMessage(e){return r(this,void 0,void 0,(function*(){try{const t="unread-message-synchronizer._fetchUnreadDBMessage";console.log(`${t} options:`,e);const s=yield $s(e,this._core);if(!s)return null;const{syncFlag:n,unreadMessageList:o,revokedMessageList:i,cookie:r,unreadCountList:a,overflowUnreadCountList:c,groupTipList:l}=s;return this._parseAndSaveUnreadMessageList(o),{syncFlag:n,cookie:r,unreadMessageList:o,revokedMessageList:i,unreadCountList:a,overflowUnreadCountList:c,groupTipList:l}}catch(e){console.log(e)}}))}_canContinueSync({cookie:e,syncFlag:t}){var s;return t===Vs.START_SYNC||t===Vs.SYNCING&&!(null===(s=this._core)||void 0===s?void 0:s.helper.isEmpty(e))}_parseAndSaveUnreadMessageList(e){e.forEach((e=>{const{ID:t}=e;this._unreadDBMessageMap.set(t,e)}))}_reset(){this._cookie="",this._unreadDBMessageMap.clear()}_dispose(){var e,t;null===(e=this._core)||void 0===e||e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),null===(t=this._core)||void 0===t||t.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),this._reset()}};var Ys=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 s="visible"===document.visibilityState;null===(e=this._core)||void 0===e||e.store.set("activityMonitor",{isActive:s}),null===(t=this._core)||void 0===t||t.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:s})}_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 Ks=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 js=new class{init(e){const{IN_WX_MINI_APP:t,IN_WX_MINI_PLUGIN:s}=e.helper;s||(t?Ks.init(e):Ys.init(e))}};const Hs="none",zs="online";var Zs=new class{init(e){this._core=e,this._activateNetworkMonitoring(),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return r(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,s;const{isConnected:n,networkType:o}=e;null===(t=this._core)||void 0===t||t.store.set("netWorkMonitor",{isNetworkOnline:n,networkType:o}),null===(s=this._core)||void 0===s||s.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:n,networkType:o})}_onOnline(){this._onNetworkStatusChange({isConnected:!0,networkType:zs})}_onOffline(){this._onNetworkStatusChange({isConnected:!1,networkType:Hs})}_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 Js=new class{init(e){this._core=e,this._activateNetworkMonitoring(),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return r(this,void 0,void 0,(function*(){try{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,s;const{isConnected:n,networkType:o}=e;null===(t=this._core)||void 0===t||t.store.set("netWorkMonitor",{isNetworkOnline:n,networkType:o}),null===(s=this._core)||void 0===s||s.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:n,networkType:o})}_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 Xs=new class{init(e){const{IN_WX_MINI_APP:t}=e.helper;t?Js.init(e):Zs.init(e)}};var Qs=new class{install(e){js.init(e),Xs.init(e)}};const en=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.*"]),tn="tui_room_svr.*";var sn=new class{constructor(){this._transferredCommands=en}install(e){this._core=e;const{notificationCenter:t,InnerEvent:s,helper:n}=e;t.subscribeInnerEvent(s.CLOUD_CONFIG_UPDATE,this._onCloudConfigUpdate,this),t.subscribeInnerEvent(s.LOGOUT,this._reset,this),t.subscribeInnerEvent(s.DESTROY,this._dispose,this),t.subscribeInnerEvent("im_open_push.msg_push",t.InnerEventSubType.BUSINESS_COMMAND,this._onServerPushBusinessCommand,this),n.registerExperimentalAPI("sendTRTCCustomData",this,"transferBusinessCommand"),n.registerExperimentalAPI("sendRoomCustomData",this,"transferBusinessCommand")}transferBusinessCommand(e){return r(this,void 0,void 0,(function*(){const t="transferBusinessCommand";try{const{serviceCommand:s=tn}=e||{};if(!this._isValidTransferredCommand(s))throw new this._core.helper.ChatError({code:2995,functionName:t});const n=yield function(e,t){return r(this,void 0,void 0,(function*(){const{helper:s,channel:n}=t,{serviceCommand:o=tn,data:i}=e||{};let r={};try{r="string"==typeof i?JSON.parse(i):i}catch(e){console.warn(e)}const a=s.generateProtocolData({servcmd:o,data:r}),c=`${a.head.seq}${o}`;return n.sendPacket(a,{requestId:c})}))}(e,this._core);return{code:0,data:n||{}}}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:s}=this._core,{MsgContent:n}=e||{},{ROOM_CUSTOM_DATA_RECEIVED:o}=t;s.emitOuterEvent(o,{name:o,data:n})}_reset(){this._transferredCommands=en}_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)}};let nn=[];const on=[Bs,function(e){ks.install(e),Fs.install(e),xs.install(e)},Ws,Qs,sn];nn=on;var rn=Object.freeze({__proto__:null,ChatError:as,buildAndSendPacket:function(e){return r(this,void 0,void 0,(function*(){const{servcmd:t,data:s}=e,n=Ut.common.generateProtocolData({servcmd:t,data:s}),o=`${n.head.seq}${t}`;return Ut.channel.sendPacket(n,{requestId:o})}))},get builtInPlugins(){return nn},checkBusinessCapabilityBits:vs,deepMerge:Os,destroy:vn,exposeApiForClient:In,exposeApiForPlugin:Cn,getCurrentUserID:ys,getErrorMessage:rs,getMessagePreviewText:As,isCommunity:({type:e,groupID:t})=>e===es.GRP_COMMUNITY||`${t}`.startsWith(Xt.COMMUNITY)&&!`${t}`.includes(Xt.TOPIC),isTopic:Ts,isUnlimitedAVChatRoom:function(){var e;return!!(null===(e=Ut.store.get("instance"))||void 0===e?void 0:e.unlimitedAVChatRoom)},liteChatInstanceMap:Is,registerApi:mn,registerExperimentalAPI:Sn,registerInterceptor:ps,registerPlugin:fn,registerValidateConfig:ms,requireAuth:cs,setLogLevel:pn,statKeyFeatureUsage:En,validateAndExecute:Es,validateParameters:us,workflowManager:Cs});var an=new class{constructor(){this._conversationMap=new Map}getConversationMap(){return this._conversationMap}getConversation(e){return this._conversationMap.get(e)}updateConversation(e,t){const s=this._conversationMap.get(e);s&&!ue(t)&&(Object.keys(t).forEach((e=>{s[e]=t[e]})),Ut.notificationCenter.emitInnerEvent($t.CONVERSATION_UPDATED))}deleteConversation(e){this._conversationMap.has(e)&&(this._conversationMap.delete(e),Ut.notificationCenter.emitInnerEvent($t.CONVERSATION_UPDATED))}};var cn=new class{constructor(){this._groupMap=new Map}getGroupMap(){return this._groupMap}getGroup(e){return this._groupMap.get(e)}updateGroup(e,t){const s=this._groupMap.get(e);s&&!ue(t)&&Object.keys(t).forEach((e=>{s[e]=t[e]}))}};var ln=new class{constructor(){this._messagesByConversation=new Map}updateMessage(e,t,s){var n;const{operation:o,updateUnreadCount:i=!0}=s,r=function(e,t){var s={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(s[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(n=Object.getOwnPropertySymbols(e);o<n.length;o++)t.indexOf(n[o])<0&&Object.prototype.propertyIsEnumerable.call(e,n[o])&&(s[n[o]]=e[n[o]])}return s}(s,["operation","updateUnreadCount"]),a=[];for(const s of t){const t=null===(n=this._messagesByConversation.get(e))||void 0===n?void 0:n.get(s);if(!t)return!1;Object.keys(r).forEach((e=>{t[e]=r[e]})),a.push(t)}return this._emitMessageStoreOperationEvent(o,{conversationID:e,messageList:a,updateUnreadCount:i}),a}getMessagesByConversation(e){var t;return[...(null===(t=this._messagesByConversation.get(e))||void 0===t?void 0:t.values())||[]]}getMessages(){return this._messagesByConversation}_emitMessageStoreOperationEvent(e,t){Ut.notificationCenter.emitInnerEvent(e,t)}};var dn=new class{constructor(){this.userProfileMap=new Map,this.friendMap=new Map}getUserProfileMap(){return this.userProfileMap}getFriendMap(){return this.friendMap}getUserProfile(e){return this.userProfileMap.get(e)}getFriend(e){return this.friendMap.get(e)}},un=Object.freeze({__proto__:null,conversationStore:an,groupStore:cn,messageStore:ln,userStore:dn});const _n={on:Ut.notificationCenter.subscribeOuterEvent.bind(Ut.notificationCenter),off:Ut.notificationCenter.unSubscribeOuterEvent.bind(Ut.notificationCenter),destroy:vn,callExperimentalAPI:function(e,t){if(hn[e])return hn[e](t);return Promise.reject(new Error(`API ${e} is not found`))},use:Ss.installExternalPlugin.bind(Ss),registerPlugin:fn,setLogLevel:pn},hn={},gn={};function fn(e){console.log("registerPlugin",e)}function En(e){console.log("statTUIKeyFeatures",e)}function pn(e){console.log("setLogLevel",e),Ut&&"function"==typeof Ut.setLogLevel&&(null==Ut||Ut.setLogLevel(e))}function mn(e){const{apiName:t,context:s,methodName:n=t,matcher:o}=e;gn[t]||(gn[t]=[]),gn[t].push({context:s,methodName:n,matcher:o}),_n[t]&&1!==gn[t].length||(_n[t]=(...e)=>{Es(n,e);const s=gn[t];for(const t of s)if(!t.matcher||t.matcher(e))return t.context[t.methodName].bind(t.context)(...e)})}function Sn(e,t,s){const n=s||e;hn[e]=t[n].bind(t)}function vn(){return r(this,void 0,void 0,(function*(){var e,t;try{(null===(e=Ut.store.get("login"))||void 0===e?void 0:e.isLogin)&&(yield _n.logout()),Ut.notificationCenter.emitInnerEvent($t.DESTROY)}catch(e){console.debug("destroy error: ",e)}finally{Ut.notificationCenter.emitOuterEvent(xt.SDK_DESTROY,{SDKAppID:null===(t=Ut.store.get("instance"))||void 0===t?void 0:t.sdkAppId}),Is.clear(),Ss.clear(),Cs.destroy(),Ut.destroy()}}))}function In(){return _n}function Cn(){return Object.assign(Object.assign({InnerEvent:$t,InnerEventSubType:Ut.notificationCenter.InnerEventSubType,OuterEvent:xt,OuterConstant:es,SignalingEvent:Vt,helper:Object.assign(Object.assign(Object.assign({},Ut.utils),Ut.common),{registerApi:mn,registerExperimentalAPI:Sn,registerInterceptor:ps,registerValidateConfig:ms,checkBusinessCapabilityBits:vs,registerWorkflowStep:Cs.registerWorkflowStep.bind(Cs),ChatError:as}),apiMap:_n},Ut),{constants:Object.assign(Object.assign({},is),Ut.constants),common:Object.assign(Object.assign({},rn),Ut.common),utils:Ut.utils,appStore:un})}hn.statTUIKeyFeatures=En;var yn,Mn,On;!function(e){e[e.USER_INITIATED=0]="USER_INITIATED",e[e.KICKED_OUT=1]="KICKED_OUT"}(yn||(yn={})),function(e){e[e.multipleAccount=1]="multipleAccount",e[e.multipleDevice=2]="multipleDevice",e[e.restApi=3]="restApi"}(Mn||(Mn={})),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 Tn={[Mn.multipleAccount]:"multipleAccount",[Mn.multipleDevice]:"multipleDevice",[Mn.restApi]:"REST_API_Kick",[On.multipleAccount]:"multipleAccount",[On.multipleDevice]:"multipleDevice",[On.restApi]:"REST_API_Kick",[On.usersigExpired]:"userSigExpired"},An="login_online_presence_task",{ERROR:Nn,DESTROY:Rn,FORCE_OFFLINE:Dn}=$t,{KICKED_OUT_MULT_ACCOUNT:wn,KICKED_OUT_MULT_DEVICE:bn,KICKED_OUT_REST_API:kn,ACCOUNT_A2KEY_EXPIRED:Pn,MSG_A2KEY_EXPIRED:Ln}=ts;class Un{init(){const{notificationCenter:e}=Ut;e.subscribeInnerEvent(Dn,this._handleForceOfflineFromServerPush,this),e.subscribeInnerEvent(Nn,Ln,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(Nn,Pn,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(Nn,wn,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(Nn,bn,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(Nn,kn,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(Rn,this._dispose,this)}_handleForceOfflineFromServerPush(e){const{EventArray:t=[]}=(null==e?void 0:e.body)||{};this._extractKickedOutMessages(t).forEach((e=>{const{KickoutMsgNotify:{KickType:t,NewInstInfo:s}}=e;this._processKickedOutReasonInfo({kickedOutReasonCode:t,newInstanceInfo:s})}))}_extractKickedOutMessages(e){return e.reduce(((e,t)=>[...e,...t.C2cNotifyMsgArray||[]]),[]).filter((e=>{var t;return this._isKickedOut(null===(t=null==e?void 0:e.KickoutMsgNotify)||void 0===t?void 0:t.KickType)}))}_handleForceOfflineFromResponse(e){const{errorCode:t}=e;this._processKickedOutReasonInfo({kickedOutReasonCode:t})}_processKickedOutReasonInfo(e){return r(this,void 0,void 0,(function*(){const{kickedOutReasonCode:t}=e;try{yield Ut.login.loginAction.logout(yn.KICKED_OUT)}catch(e){console.debug(e)}finally{this._logKickedOutEvent(e),Ut.notificationCenter.emitOuterEvent(xt.KICKED_OUT,{data:{type:Tn[t]},name:xt.KICKED_OUT}),[Mn.restApi,Pn,Ln].includes(t)&&Ut.channel.reconnect()}}))}_logKickedOutEvent(e){const{kickedOutReasonCode:t,newInstanceInfo:s={}}=e,n=Ut.ssoLog.createSSOLogData({method:"kickedOut"}),o=`type:${Tn[t]} newInstanceInfo: ${JSON.stringify(s)}`;n.setLogInfo({message:o}).end(!0),console.warn(`loginModule.${o}`)}_isKickedOut(e){return[Mn.multipleAccount,Mn.multipleDevice,Mn.restApi].includes(e)}_dispose(){const{notificationCenter:e}=Ut;e.unSubscribeInnerEvent(Dn,this._handleForceOfflineFromServerPush,this),e.unSubscribeInnerEvent(Nn,Pn,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(Nn,Ln,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(Nn,wn,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(Nn,bn,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(Nn,kn,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(Rn,this._dispose,this)}}function Gn(){return r(this,void 0,void 0,(function*(){const e="im_open_status.wslogin",t=Ut.common.generateProtocolData({servcmd:e,data:{state:"Online",isWebUniapp:0,InstType:0,customInfo:""}}),s=`${t.head.seq}${e}`;try{const e=yield Ut.channel.sendPacket(t,{timeout:9e4,requestId:s});if(e){const{HelloInterval:t,InstId:s,TinyId:n,TimeStamp:o,CustomStatus:i,PurchaseBits:r,A2Key:a,RichMsgAuthKey:c,ErrorCode:l,ErrorInfo:d,ActionStatus:u}=e;return{helloInterval:t,instanceID:s,tinyID:n,timeStamp:o,customStatus:i,purchaseBits:r,a2Key:a,authKey:c,errorCode:l,errorInfo:d,actionStatus:u}}}catch(e){throw console.warn(e),e}}))}class Fn{constructor(){this._latestLoginAt=0,this._latestSendOnlinePresenceRequestTime=0,this._helloInterval=120}init(){const{notificationCenter:e,store:t}=Ut;t.set("login",{isReady:!1}),mn({apiName:"login",context:this}),mn({apiName:"logout",context:this}),mn({apiName:"getLoginUser",context:this}),mn({apiName:"isReady",context:this}),e.subscribeInnerEvent($t.RECONNECTED,this._reLogin,this),Ut.notificationCenter.subscribeInnerEvent($t.DESTROY,this._dispose,this)}login(e){return r(this,void 0,void 0,(function*(){const t=Ut.ssoLog.createSSOLogData({method:"login",eventType:4});try{if(this._isLoginIn())return this._createRepeatLoginResponse();if(this._isLoginFrequencyExceeded())throw new as({functionName:"login",code:ts.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:s}=e,n=new as({functionName:"login",code:s});throw t.setError(n).end(!0),n}finally{this._latestLoginAt=0}}))}_reLogin(){return r(this,void 0,void 0,(function*(){var e;try{if(!this._isLoginIn())return;const t=Ut.ssoLog.createSSOLogData({method:"reLogin"}),s=yield Gn();if(s){const{instanceID:n,customStatus:o}=s;Ut.store.set("login",{statusInstanceId:n}),Cs.executeWorkflow(ss.SYNC_SERVER_INFO_AFTER_RE_ONLINE,{customStatus:o,statusType:Ht.USER_STATUS_ONLINE});const i=`socketId:${null===(e=Ut.channel.getSocketAdapter())||void 0===e?void 0:e.getId()} instanceId:${n}`;t.setLogInfo({message:i}).end(!0)}}catch(e){console.warn(e)}}))}logout(){return r(this,arguments,void 0,(function*(e=yn.USER_INITIATED){Ut.ssoLog.createSSOLogData({method:"logout"}).setLogInfo({moreMessage:`identifier:${ys()}`}).end(!0);try{yield this._performLogout(e)}catch(e){const{errorCode:t}=e,s=new as({functionName:"logout",code:t});this._handleLogoutError(s)}finally{this._handleLogoutCompleted()}return{code:0,data:{}}}))}getLoginUser(){return this._isLoginIn()?ys():""}isReady(){var e;return null===(e=Ut.store.get("login"))||void 0===e?void 0:e.isReady}_updateAndEmitSDKReady(){Ut.store.set("login",{isReady:!0}),setTimeout((()=>{Ut.notificationCenter.emitOuterEvent(xt.SDK_READY,{name:xt.SDK_READY})}),1)}_updateAndEmitSDKNotReady(){Ut.store.set("login",{isReady:!1}),Ut.notificationCenter.emitOuterEvent(xt.SDK_NOT_READY,{name:xt.SDK_NOT_READY})}_validateAfterLogin(e){var t,s;const n="login";if(!e)throw new as({functionName:n,message:"login response is empty"});const{tinyID:o,a2Key:i}=e||{},r=Ut.ssoLog.getSSOLogData(n);if(!o){const e=new as({functionName:n,code:ts.NO_TINYID});throw null===(t=null==r?void 0:r.setError)||void 0===t||t.call(r,e).end(),e}if(!i){const e=new as({functionName:n,code:ts.NO_A2KEY});throw null===(s=null==r?void 0:r.setError)||void 0===s||s.call(r,e).end(),e}}_createRepeatLoginResponse(){var e;return{code:0,data:{actionStatus:"OK",errorCode:0,errorInfo:rs({code:"RepeatLogin",replacement1:null===(e=Ut.store.get("login"))||void 0===e?void 0:e.userId}),repeatLogin:!0}}}_performLogin(e){return r(this,void 0,void 0,(function*(){const{userID:t,userSig:s}=e;return Ut.store.set("login",{userId:t,userSig:s}),this._latestLoginAt=Date.now(),Gn()}))}_ensureAsyncComplete(){return r(this,void 0,void 0,(function*(){yield new Promise((e=>{setTimeout((()=>e(null)),1)}))}))}_handleLoginSuccess(e){const{timeManager:t}=Ut.common,{helloInterval:s,timeStamp:n,customStatus:o,purchaseBits:i}=e,r=1e3*n;t.calculateTimeOffsetWithServer(this._latestLoginAt,r),this._helloInterval=s||120,this._updateLoginStore(e),Ut.user.userStatus.setCustomStatus(o),Cs.executeWorkflow(ss.SYNC_SERVER_INFO_AFTER_LOGIN,{purchaseBits:i}),Ut.common.taskScheduler.addTask({id:An,intervalMs:1e3*this._helloInterval,callback:this._sendOnlinePresenceRequest,context:this}),this._logLoginSuccess(e)}_performLogout(e){return function(e){return r(this,void 0,void 0,(function*(){const{logoutReason:t}=e,s="im_open_status.wslogout",n=Ut.common.generateProtocolData({servcmd:s,data:{wslogout_type:t,isWebUniapp:0}}),o=`${n.head.seq}${s}`;return yield Ut.channel.sendPacket(n,{requestId:o})}))}({logoutReason:e})}_handleLogoutError(e){Ut.ssoLog.getSSOLogData("logout").setError(e).end(),console.error(`logout ${e}`)}_handleLogoutCompleted(){this._updateAndEmitSDKNotReady(),this._reset(),Cs.reset(),Ut.notificationCenter.emitInnerEvent("logout")}_updateLoginStore(e){const{a2Key:t,tinyID:s,instanceID:n,authKey:o}=e;Ut.store.set("login",{a2Key:t,tinyID:s,statusInstanceId:n,authKey:o,isLoggedIn:!0})}_logLoginSuccess(e){var t;const s=Ut.ssoLog.getSSOLogData("login"),{helloInterval:n,instanceID:o,timeStamp:i,customStatus:r}=e,a=null===(t=Ut.channel.getSocketAdapter())||void 0===t?void 0:t.getId(),c=Ut.common.timeManager.getTimeOffsetWithServer(),{appId:l,href:d}=Ut.store.get("instance")||{},u=`login._logLoginSuccess socketID:${a} scene: helloInterval:${n} instanceID:${o}\n timeStamp:${i} offset:${c} customStatus:${r} href: ${d} appId: ${l}`;console.log(`login ok. ${u}`),s.updateLogCreatedAtByTimeOffset(),s.setLogInfo({moreMessage:u}).end()}_sendOnlinePresenceRequest(){return r(this,void 0,void 0,(function*(){this._latestSendOnlinePresenceRequestTime=Date.now();try{yield function(){const e="im_open_status.wshello",t=Ut.common.generateProtocolData({servcmd:e,data:{isWebUniapp:0}}),s=`${t.head.seq}${e}`;return Ut.channel.sendPacket(t,{requestId:s})}()}catch(e){console.warn("Login._sendOnlinePresenceRequest error:",e)}}))}_isLoginIn(){var e;return!0===(null===(e=Ut.store.get("login"))||void 0===e?void 0:e.isLoggedIn)}_isLoginFrequencyExceeded(){return Date.now()-this._latestLoginAt<=15e3}_reset(){console.log("Login reset"),Ut.common.taskScheduler.removeTask(An),this._helloInterval=120,this._latestSendOnlinePresenceRequestTime=0,this._latestLoginAt=0,Ut.store.clear("login"),Ut.store.set("login",{isReady:!1})}_dispose(){console.log("Login dispose"),this._reset();const{notificationCenter:e}=Ut;e.unSubscribeInnerEvent($t.RECONNECTED,this._reLogin,this),e.unSubscribeInnerEvent($t.DESTROY,this._dispose,this)}}const xn={login:{userID:{required:!0,rules:["string"],allowEmpty:!1},userSig:{required:!0,rules:["string"],allowEmpty:!1}}},Bn={logout:!0};class $n{constructor(){this.loginAction=new Fn,this.kickedOutHandler=new Un,this.loginAction.init(),this.kickedOutHandler.init(),ms({auth:Bn,params:xn})}}var Vn,qn,Wn;!function(e){e.CONV_C2C="C2C",e.CONV_GROUP="GROUP",e.CONV_TOPIC="TOPIC",e.CONV_SYSTEM="@TIM#SYSTEM"}(Vn||(Vn={})),function(e){e.MSG_PRIORITY_HIGH="High",e.MSG_PRIORITY_NORMAL="Normal",e.MSG_PRIORITY_LOW="Low",e.MSG_PRIORITY_LOWEST="Lowest"}(qn||(qn={})),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"}(Wn||(Wn={}));const Yn={1:qn.MSG_PRIORITY_HIGH,2:qn.MSG_PRIORITY_NORMAL,3:qn.MSG_PRIORITY_LOW,4:qn.MSG_PRIORITY_LOWEST},Kn=0,jn=1;var Hn;!function(e){e.IN="in",e.OUT="out"}(Hn||(Hn={}));const zn={};function Zn(e){if(!e)return 0;if(void 0===zn[e]){const t=new Date,s=`3${t.getHours()}`.slice(-2),n=`0${t.getMinutes()}`.slice(-2),o=`0${t.getSeconds()}`.slice(-2);zn[e]=parseInt([s,n,o,"0001"].join(""),10),console.log(`autoIncrementIndex start index:${zn[e]}`)}else zn[e]+=1;return zn[e]}class Jn{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=qn.MSG_PRIORITY_NORMAL,this._relayFlag=!1;const{clientTime:t=Ut.common.timeManager.getServerTimeSeconds()||0,senderTinyID:s,currentUser:n,needReadReceipt:o,isSupportExtension:i,customModerationConfigurationId:r,to:a,from:c,nick:l="",avatar:d="",time:u,messageControlInfo:_,tinyID:h,cloudCustomData:g="",messageLifeTime:f,messageVersion:E=0,conversationType:p,sequence:m,checkResult:S=0,isPlaceMessage:v=0,messageFlagBits:I,receiverList:C,isSystemMessage:y=!1,status:M=Yt.SUCCESS,revokeReason:O="",conversationSubType:T,clientSequence:A,protocol:N="JSON",revokerInfo:R={userID:"",nick:"",avatar:""},readReceiptInfo:D={readCount:void 0,unreadCount:void 0,isPeerRead:void 0,timestamp:0},random:w,groupProfile:b,atUserList:k,flow:P,isRead:L=!1}=e;var U;this.clientTime=t,this.senderTinyID=s||h,this.needReadReceipt=!0===o||1===o,this.isSupportExtension=!0===i||1===i,this._cmConfigID=r,this.to=a,this.nick=l,this.avatar=d,this.protocol=N,this.random=void 0===w?(U=U||99999999,Math.round(Math.random()*U)):w,this.time=u||Math.ceil(Date.now()/1e3),this._isExcludedFromLastMessage=!!(null==_?void 0:_.excludedFromLastMessage),this._isExcludedFromUnreadCount=!!(null==_?void 0:_.excludedFromUnreadCount),this.isModified=!!E,this.cloudCustomData=g,this.messageLifeTime=f,this.from=c||null,this.sequence=m||0,this.conversationType=p||Vn.CONV_C2C,this.hasRiskContent=S>1,this.version=E,this.isPlaceMessage=v,this.isRevoked=2===v||8===I,this.isSystemMessage=y,this.readReceiptInfo=D,this.revokeReason=O,this.revokerInfo=R,this._receiverList=C,this.conversationSubType=T,this.revoker=(null==R?void 0:R.revoker)||"",this.clientSequence=A||m||0,this.status=M,this.atUserList=k||[],this.flow=P,this.isRead=L,this.reInitialize(n),this._initC2CReadReceiptInfo(e),this._extractGroupInfo(b)}getElements(){return this._elements}isOnlineMessage(){return 0===this.messageLifeTime}setElement(e){Array.isArray(e)?this._elements=e:this._elements=[e],this._updatePayloadAndType()}transformElementsToServerFormat(){return this._elements?Array.isArray(this._elements)?this._elements.map((e=>e.transformToServerFormat())):this._elements.transformToServerFormat():null}setRelayFlag(e){this._relayFlag=e}validateBeforeSend(){var e,t,s;return this._relayFlag?{isValid:!0}:(null===(e=this._elements)||void 0===e?void 0:e.length)>0?null===(s=null===(t=this._elements[0])||void 0===t?void 0:t.validateBeforeSend)||void 0===s?void 0:s.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:s=0}=e;this.conversationType===Vn.CONV_C2C&&!0===this.needReadReceipt&&(this.readReceiptInfo.isPeerRead=1===t,this.readReceiptInfo.timestamp=s)}_extractGroupInfo(e){if(!e)return;const{From_AccountNick:t,From_AccountHeadurl:s,MsgFrom_AccountExtraInfo:n}=e,{NameCard:o}=n||{};"string"==typeof t&&(this.nick=t),"string"==typeof s&&(this.avatar=s),"string"==typeof o&&(this.nameCard=o)}reInitialize(e){e===this.from&&(this.isRead=!0),this._initSequence(e),this._concatConversationID(e),this.generateMessageID()}_concatConversationID(e){let t="";const s=this.conversationType;s!==Vn.CONV_SYSTEM?(t=s===Vn.CONV_C2C?e===this.from?this.to:this.from:this.to,this.conversationID=t?`${s}${t}`:null):this.conversationID=Vn.CONV_SYSTEM}_initSequence(e){0===this.clientSequence&&e&&(this.clientSequence=Zn(e)),0===this.sequence&&this.conversationType===Vn.CONV_C2C&&(this.sequence=this.clientSequence)}generateMessageID(){this.from===Vn.CONV_SYSTEM&&(this.senderTinyID="144115198244471703"),this.ID=`${this.senderTinyID}-${this.clientTime}-${this.random}`}setIsRead(e){this.isRead=e}}class Xn{static parseServerPushElement(e){const{MsgContent:t={}}=e,{Data:s,Ext:n,Desc:o}=t;return new Xn({data:s,description:o,extension:n})}constructor(e){this.type=Wn.MSG_CUSTOM;const{data:t="",description:s="",extension:n=""}=e;this.content={data:t,description:s,extension:n}}transformToServerFormat(e){const{isMergerMessage:t=!1}=e||{},s=t?this.payload:this.content,{data:n,description:o,extension:i}=s;return{MsgType:this.type,MsgContent:{Data:n,Ext:i,Desc:o}}}validateBeforeSend(){const{isEmpty:e}=Ut.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 Qn{static parseServerPushElement(e){const{MsgContent:t={Text:""}}=e,{Text:s}=t;return new Qn({text:s})}constructor(e){this.type=Wt.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"}}}transformToServerFormat(e){const{isMergerMessage:t=!1}=e||{},s=t?this.payload:this.content,{text:n}=s;return{MsgType:this.type,MsgContent:{Text:n}}}}class eo{constructor(){this._elementClassMap={[Wn.MSG_CUSTOM]:Xn,[Wn.MSG_TEXT]:Qn}}init(){mn({apiName:"createCustomMessage",context:this}),mn({apiName:"createTextMessage",context:this})}registerElementClass(e,t){var s;void 0!==(s=t).prototype&&"constructor"in s.prototype&&(this._elementClassMap[e]=t)}getElementClass(e){return this._elementClassMap[e]}createMessage(e){const{from:t,flow:s=Hn.OUT}=e,{userId:n}=Ut.store.get("login")||{};this._isSendByCurrentInstance({from:t,flow:s,currentUser:n})?this._updateWithSenderInfo(e):this._isMultiEndpointSyncMessage({from:t,flow:s,currentUser:n})&&(e.flow=Hn.OUT);const o=Object.assign(Object.assign({},e),{currentUser:n});return new Jn(o)}createCustomMessage(e){const t=ys(),s=this.createMessage(Object.assign(Object.assign({},e),{from:t})),n=this._elementClassMap[Wn.MSG_CUSTOM];if(!s)return null;if(n){const t=new n(e.payload);s.setElement(t)}return s}createTextMessage(e){var t;if(!e)return null;const s="string"==typeof e.payload?e.payload:(null===(t=null==e?void 0:e.payload)||void 0===t?void 0:t.text)||"",n=new Qn({text:s}),o=ys(),i=Ut.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{from:o}));return i.setElement(n),i}_updateWithSenderInfo(e){const{nick:t,avatar:s}=e,{userId:n,tinyID:o}=Ut.store.get("login")||{},i=dn.getUserProfile(n);return e.nick=t||(null==i?void 0:i.nick)||"",e.avatar=s||(null==i?void 0:i.avatar)||"",e.tinyID=e.tinyID||o||"",e.from=n,e.status=Yt.UNSENT,e.flow=Hn.OUT,e}_isMultiEndpointSyncMessage(e){const{from:t,flow:s,currentUser:n}=e;return t===n&&s===Hn.IN}_isSendByCurrentInstance(e){const{from:t,flow:s,currentUser:n}=e;return t===n&&s===Hn.OUT}}function to(e){const t=e.lastIndexOf(".");return-1===t?e:e.slice(0,t)}function so(e){const{androidInfo:t={},androidOPPOChannelID:s=""}=e,n=t.OPPOChannelID||s;return Object.assign(Object.assign({},t),{Sound:to(t.sound||""),OPPOChannelID:n,GoogleChannelID:t.FCMChannelID||""})}function no(e){const{apnsInfo:t={},ignoreIOSBadge:s=!1,disableVoipPush:n}=e,o=!0===t.ignoreIOSBadge||!0===s?1:0;let i;return void 0!==n&&(i=!1===n?1:0),void 0!==t.disableVoipPush&&(i=!1===t.disableVoipPush?1:0),Object.assign(Object.assign({},t),{badgeMode:o,isVoipPush:i})}function oo(e){return Ut.utils.isPlainObject(e)?{PushFlag:!0===e.disablePush?1:0,Title:e.title||"",Desc:e.description||"",Ext:e.extension||"",ApnsInfo:no(e),AndroidInfo:so(e)}:null}function io(e){const{From_AccountHeadurl:t,From_AccountNick:s,IsNeedReadReceipt:n,IsPeerRead:o,IsSyncMsg:i,MsgBody:r,MsgClientTime:a,MsgLifeTime:c,MsgRandom:l,MsgSeq:d,MsgTimeStamp:u,SendMsgControl:_,SupportMessageExtension:h,TinyId:g,MsgCheckResult:f,CloudCustomData:E,MsgVersion:p,MsgFlagBits:m,RevokerInfo:S}=e;let v,{From_Account:I,To_Account:C}=e;if(1===i){const e=C;C=I,I=e}if(S){const{Reason:e,Revoker_Account:t,Revoker_FromUin:s}=S;v={reason:e,revoker:t,revokerFromUin:s,userID:t}}return{from:I,avatar:t,nick:s,needReadReceipt:1===n,isSyncMessage:i,clientTime:a,messageLifeTime:c,random:l,sequence:d,time:u,messageControlInfo:{excludedFromLastMessage:1===(null==_?void 0:_.NoLastMsg),excludedFromUnreadCount:1===(null==_?void 0:_.NoUnread)},isSupportExtension:h,to:C,tinyID:g,checkResult:f,cloudCustomData:E,revokerInfo:v,messageVersion:p,messageFlagBits:m,readReceiptSentByPeer:o,elements:co(r)}}function ro(e){const{From_Account:t,MsgBody:s,MsgClientTime:n,MsgRandom:o,MsgSeq:i,MsgTimeStamp:r,To_Account:a,MsgVersion:c,CloudCustomData:l}=e;return{from:t,clientTime:n,random:o,sequence:i,time:r,to:a,elements:co(s),messageVersion:c,cloudCustomData:l}}function ao(e){const{ClientSeq:t,From_Account:s,GroupInfo:n,MsgBody:o,MsgClientTime:i,MsgRandom:r,MsgSeq:a,MsgTimeStamp:c,SendMsgControl:l,SupportMessageExtension:d,TinyId:u,ToGroupId:_,CloudCustomData:h,MsgVersion:g,MsgCheckResult:f,NeedReadReceipt:E,IsPlaceMsg:p,RevokerInfo:m,GroupAtInfo:S}=e;let v,I=qn.MSG_PRIORITY_NORMAL;if(Object.keys(Yn).includes(String(e.MsgPriority))&&(I=Yn[e.MsgPriority]),m){const{Reason:e,Revoker_Account:t,Revoker_FromUin:s}=m;v={reason:e,revoker:t,revokerFromUin:s,userID:t}}const C=function(e){const t=[];Array.isArray(e)&&e.forEach((e=>{e.GroupAtAllFlag===Kn?t.push(e.GroupAt_Account):e.GroupAtAllFlag===jn&&t.push(es.MSG_AT_ALL)}));return t}(S);return{clientSequence:t,from:s,groupProfile:n,clientTime:i,priority:I,random:r,sequence:a,time:c,messageControlInfo:{excludedFromLastMessage:1===(null==l?void 0:l.NoLastMsg),excludedFromUnreadCount:1===(null==l?void 0:l.NoUnread)},isSupportExtension:d,to:_,tinyID:u,cloudCustomData:h,messageVersion:g,messageCheckResult:f,needReadReceipt:E,isPlaceMessage:p,revokerInfo:v,atUserList:C,elements:co(o)}}function co(e){if(!e)return null;if(Array.isArray(e))return e.map((e=>{const t=Ut.message.messageFactory.getElementClass(e.MsgType);return null==t?void 0:t.parseServerPushElement(e)}));const t=Ut.message.messageFactory.getElementClass(e.MsgType);return null==t?void 0:t.parseServerPushElement(e)}function lo(e){const{From_Account:t,MsgBody:s,MsgClientTime:n,MsgRandom:o,MsgSeq:i,MsgTimeStamp:r,GroupId:a,TopicId:c,MsgVersion:l,CloudCustomData:d}=e;return{from:t,clientTime:n,random:o,sequence:i,time:r,groupID:a,topicID:c,elements:co(s),messageVersion:l,cloudCustomData:d}}function uo({conversationUpdateFields:e,message:t}){const{conversationID:s,conversationType:n,conversationSubType:o,flow:i,_isExcludedFromUnreadCount:r,_isExcludedFromLastMessage:a}=t,c=a?"":t,l=!r&&i===Hn.IN;e.has(s)?(e.get(s).lastMessage=c,l&&e.get(s).unreadCount++):e.set(s,{conversationID:s,type:n,subType:o,unreadCount:l?1:0,lastMessage:c})}var _o=Object.freeze({__proto__:null,autoIncrementIndex:Zn,parseServerGroupMessage:ao,parseServerPushC2CModifyMessage:ro,parseServerPushGroupModifyMessage:lo,parseServerPushMessage:io,parseServerPushMessageElement:co,updateConversationFields:uo});const{isPlainObject:ho}=Ut.utils;function go(e,t={}){const{onlineUserOnly:s,messageControlInfo:n}=t;let{offlinePushInfo:o}=t;e.conversationType===Vn.CONV_C2C&&!0===s&&(o?o.disablePush=!0:o={disablePush:!0});let i="";"string"==typeof e.cloudCustomData&&e.cloudCustomData.length>0&&(i=e.cloudCustomData);const r=[];if(n&&ho(n)){const{excludedFromUnreadCount:e,excludedFromLastMessage:t,excludedFromContentModeration:s}=n;!0===e&&r.push("NoUnread"),!0===t&&r.push("NoLastMsg"),!0===s&&r.push("NoMsgCheck")}return{onlineUserOnly:s,cloudCustomData:i,messageControlInfo:r,offlinePushInfo:o}}function fo(e){const{webhookInfo:{disableCloudMessagePreHook:t=!1,disableCloudMessagePostHook:s=!1}={}}=e||{};if(!t&&!s)return;const n=[];return t&&n.push("ForbidBeforeSendMsgCallback"),s&&n.push("ForbidAfterSendMsgCallback"),n}function Eo(e,t){return r(this,void 0,void 0,(function*(){const s=e.conversationType===Vn.CONV_GROUP?function(e,t){var s;const n=go(e,t),{onlineUserOnly:o,cloudCustomData:i,messageControlInfo:r,offlinePushInfo:a}=n,c=JSON.parse(JSON.stringify(e.transformElementsToServerFormat()));return{servcmd:"group_open_http_svc.send_group_msg",data:{From_Account:null===(s=Ut.store.get("login"))||void 0===s?void 0:s.userId,GroupId:e.to,MsgBody:c,CloudCustomData:i,Random:e.random,MsgPriority:e.priority,ClientSeq:e.clientSequence,GroupAtInfo:e._groupAtInfoList,OnlineOnlyFlag:o?1:0,MsgClientTime:e.clientTime,OfflinePushInfo:oo(a),SendMsgControl:o?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:fo(t)}}}(e,t):function(e,t){var s;const n=go(e,t),{onlineUserOnly:o,cloudCustomData:i,messageControlInfo:r,offlinePushInfo:a}=n,c=!0===o?0:void 0,l=JSON.parse(JSON.stringify(e.transformElementsToServerFormat()));return{servcmd:"openim.sendmsg",data:{From_Account:null===(s=Ut.store.get("login"))||void 0===s?void 0:s.userId,To_Account:e.to,MsgBody:l,CloudCustomData:i,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:oo(a),forbidCallbackControl:fo(t)}}}(e,t),n=Ut.common.generateProtocolData(s),o=`${n.head.seq}${n.head.servcmd}`,i=yield Ut.channel.sendPacket(n,{requestId:o});return i?{time:i.MsgTime,messageDropReason:i.MsgDropReason,sequence:i.MsgSeq}:null}))}const{isPlainObject:po}=Ut.utils,{MSG_AUDIO:mo,MSG_FILE:So,MSG_IMAGE:vo,MSG_VIDEO:Io,MSG_MERGER:Co}=es;class yo{init(){mn({apiName:"sendMessage",context:this,matcher:e=>![mo,So,vo,Io,Co].includes(e[0].type)})}sendMessage(e,t){return r(this,void 0,void 0,(function*(){const s=Ut.ssoLog.createSSOLogData({method:"sendMessage"});if(!(e instanceof Jn)){const e=new as({code:ts.MSG_INSTANCE_REQUIRED});throw s.setError(e).end(),e}const n=e.validateBeforeSend();if(!n.isValid){const{code:e,message:t=""}=n.error||{},o=new as({code:e,message:t});throw s.setError(o).end(),o}let o=!1;const{messageDataHandler:i}=Ut.message||{};try{const{messageControlInfo:n}=t||{};let r=null;if(i.addRandomOfSentMessage(e.random),e.conversationType===Vn.CONV_C2C?(o=!0===(null==t?void 0:t.onlineUserOnly),r=yield Eo(e,t)):e.conversationType===Vn.CONV_GROUP&&(r=yield Eo(e,t)),r){const{messageDropReason:a,sequence:c,time:l}=r;if(this._updateNickAndAvatarOfSentMessageByMe(e),a&&this._logRateLimitInfo(e,c),!0===e.isResend){const t=i.findMessage(e.ID);t&&(console.log(`sendMessage resend ok. ID:${t.ID}`),i.deleteConversationMessage(t))}return e.status=Yt.SUCCESS,e.time=l,e.conversationType===Vn.CONV_GROUP&&(e.sequence=c),o?e._onlineOnlyFlag=!0:(i.storeConversationMessage(e),this._applySentMessageControlInfo(e,n),this._emitOnlineMessageSent(e)),s.setLogInfo({message:`options: ${JSON.stringify(t)}`}).end(),{code:0,data:{message:e}}}}catch(t){e.status=Yt.FAIL,i.removeRandomOfSentMessage(e.random);const{errorCode:s,errorInfo:n=""}=t||{};this._hasRiskContent(s)&&(e.hasRiskContent=!0),o||this._isRejectedByRestApi(s)||i.storeConversationMessage(e);const r=new as({code:s,message:n,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 s=Ut.ssoLog.createSSOLogData({method:"sendMessage"});let n=`head.seq: type:${e.type} from:${e.from} to:${e.to}`;if(Ut.utils.IN_BROWSER){if("connection"in navigator){const e=navigator.connection;n+=` downlink:${e.downlink} effectiveType:${e.effectiveType} rtt:${e.rtt}`}if("memory"in window.performance){const e=window.performance.memory;n+=` usedJSHeapSize:${e.usedJSHeapSize} totalJSHeapSize:${e.totalJSHeapSize} jsHeapSizeLimit:${e.jsHeapSizeLimit}`}}s.setLogInfo({message:n}).setError(t).end()}_emitOnlineMessageSent(e){const t=e._isExcludedFromLastMessage?"":e,{conversationID:s,conversationType:n}=e;Ut.notificationCenter.emitInnerEvent($t.NEW_MESSAGE,{result:{conversationUpdateFieldList:[{conversationID:s,type:n,message:e,lastMessage:t,unreadCount:0}]}})}_applySentMessageControlInfo(e,t){t&&po(t)&&(!0===t.excludedFromLastMessage&&(e._isExcludedFromLastMessage=!0),!0===t.excludedFromUnreadCount&&(e._isExcludedFromUnreadCount=!0))}_logRateLimitInfo(e,t){const s=Ut.ssoLog.createSSOLogData({method:"messageDropReason"}),n=`from:${e.from} to:${e.to} sequence:${t} messageDropReason:${messageDropReason}`;s.setLogInfo({message:n}).end(),console.warn(`sendMessage ${n}`)}_updateNickAndAvatarOfSentMessageByMe(e){const{messageDataHandler:t}=Ut.message||{};let s=!1;const{conversationID:n}=e,o=t.getLatestMsgSentByMe(n);if(o){const{nick:i,avatar:r}=o;i===e.nick&&r===e.avatar||(s=!0),s&&t.updateNickAndAvatarOfSentMessage({conversationID:n,latestNick:e.nick,latestAvatar:e.avatar,isSentByMe:!0})}}}class Mo{constructor(e){this.value=e,this.next=null}}class Oo{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 Mo(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,s=!1;for(;t;)t.value===e&&(s=!0),t=t.next;return s}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 To{constructor(){this._sparseMessagesByConversation=new Map,this._latestMessageSentByPeerMap=new Map,this._latestMessageSentByMeMap=new Map,this._randomOfSentMessageList=new Oo(100),Ut.notificationCenter.subscribeInnerEvent($t.LOGOUT,this._reset,this),Ut.notificationCenter.subscribeInnerEvent($t.DESTROY,this._dispose,this)}get _messagesByConversation(){return ln.getMessages()}storeConversationMessage(e,t=!1){const{conversationID:s}=e;if(!s)return!1;if(this._messagesByConversation.has(s)||this._messagesByConversation.set(s,new Map),this._shouldSkipStoreMessage(e,t))return!1;const n=this._getUniqueIdOfMessage(e);return this._messagesByConversation.get(s).set(n,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 s=this._getUniqueIdOfMessage(e),n=this._messagesByConversation.get(e.conversationID);if(null==n?void 0:n.has(s)){const e=null==n?void 0:n.get(s);if(!t||!0===(null==e?void 0:e.isModified))return!0}return!1}deleteConversationMessage(e){var t;const{conversationID:s=""}=e,n=this._getUniqueIdOfMessage(e);this._messagesByConversation.has(s)&&(null===(t=this._messagesByConversation.get(s))||void 0===t||t.delete(n))}modifyConversationMessage(e,t){var s;if(!this._messagesByConversation.has(e)&&!this._sparseMessagesByConversation.has(e))return{isUpdated:!1,message:null};const n=this._getUniqueIdOfMessage(t),o=this._getMessageFromLocalMessage(e,n);if(o){const{messageVersion:n,elements:i,cloudCustomData:r,checkResult:a=0}=t,c=a>1;if(console.log(`conversationToMessageMap modifyConversationMessage localVersion:${o.version} remoteVersion:${n}`),o.version<n){const t=this._getUniqueIdOfMessage(o),a=_e(i);return(null===(s=this._messagesByConversation.get(e))||void 0===s?void 0:s.has(t))?ln.updateMessage(e,[t],{isModified:!0,version:n,_elements:a,payload:a[0].content,type:a[0].type,cloudCustomData:r,hasRiskContent:c,operation:Kt.modify}):(o.version=n,o._elements=a,o.payload=o._elements[0].content,o.type=o._elements[0].type,o.cloudCustomData=r,o.isModified=!0,o.hasRiskContent=c),{isUpdated:!0,message:o}}return{isUpdated:!1,message:o}}return{isUpdated:!1,message:null}}_getMessageFromLocalMessage(e,t){var s;if(this._messagesByConversation.has(e))return null===(s=this._messagesByConversation.get(e))||void 0===s?void 0:s.get(t);if(this._sparseMessagesByConversation.has(e)){const s=[...this._sparseMessagesByConversation.get(e).values()];for(let e=0;e<s.length;e++)if(this._getUniqueIdOfMessage(s[e])===t)return s[e]}return null}findMessage(e){let t=null;const s=Array.from(this._messagesByConversation.values());for(const n of s){if(t=Array.from(n.values()).find((t=>t.ID===e))||null,t)break}if(!t){const s=Array.from(this._sparseMessagesByConversation.values());for(const n of s)if(t=n.get(e)||null,t)break}return t}deleteConversationMessageList(e){this._messagesByConversation.has(e)&&(this._messagesByConversation.delete(e),this._latestMessageSentByMeMap.delete(e),this._latestMessageSentByPeerMap.delete(e)),this._sparseMessagesByConversation.has(e)&&this._sparseMessagesByConversation.delete(e)}revokeMessage({conversationID:e,sequence:t,random:s,revoker:n}){const o=this._messagesByConversation.get(e);let i=null;if(o){const r=Array.from(o.values());if(i=this._findMessageBySequenceAndRandom({messageList:r,random:s,sequence:t}),i){const t=this._getUniqueIdOfMessage(i);return ln.updateMessage(e,[t],{isRevoked:!0,revoker:n,operation:Kt.revoke}),i}}if(this._sparseMessagesByConversation.has(e)){const o=Array.from(this._sparseMessagesByConversation.get(e).values());if(i=this._findMessageBySequenceAndRandom({messageList:o,random:s,sequence:t}),i)return i.isRevoked=!0,i.revoker=n,i}}_findMessageBySequenceAndRandom({messageList:e,sequence:t,random:s}){for(let n=0;n<e.length;n+=1){const o=e[n];if(o.sequence===t&&(a(s)||o.random===s))return o}return null}prependLocalMessageList(e){const{messageList:t,conversationID:s}=e;if(0===t.length)return[];const n=[],o=[],i=this._messagesByConversation.get(s)||new Map;for(const e of t){const t=this._getUniqueIdOfMessage(e);i.has(t)||(n.push(e),o.push([t,e]))}if(o.length>0){const e=new Map([...o,...i.entries()]);this._messagesByConversation.set(s,e),this._updateLatestMessageSentByMe(s),this._updateLatestMessageSentByPeer(s)}return n}storeSparseMessageList(e){if(0===e.length)return;const{conversationID:t}=e[0],s=e.length;this._sparseMessagesByConversation.has(t)||this._sparseMessagesByConversation.set(t,new Map);const n=this._sparseMessagesByConversation.get(t);for(let t=0;t<s;t++){const s=e[t];n.has(s.ID)||n.set(s.ID,s)}}_updateLatestMessageSentByMe(e){var t;const s=Array.from((null===(t=this._messagesByConversation.get(e))||void 0===t?void 0:t.values())||[]);if(0!==s.length)for(let t=s.length-1;t>=0;t--)if("out"===s[t].flow){this._setLatestMsgSentByMe(e,s[t]);break}}_updateLatestMessageSentByPeer(e){var t;const s=Array.from((null===(t=this._messagesByConversation.get(e))||void 0===t?void 0:t.values())||[]);if(0!==s.length&&e.startsWith("C2C"))for(let t=s.length-1;t>=0;t--)if("in"===s[t].flow){this._setLatestMsgSentByPeer(e,s[t]);break}}_getUniqueIdOfMessage(e){const{from:t,to:s,random:n,sequence:o,time:i}=e;return`${t}-${s}-${n}-${o}-${i}`}_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:s,latestNick:n,isSentByMe:o=!0}=e,i=this._messagesByConversation.get(t);if(!i)return;const r=Array.from(i.values()),a=o?"out":"in";r.forEach((e=>{const{nick:t,avatar:o,flow:i}=e;i===a&&(t!==n&&(e.nick=n),o!==s&&(e.avatar=s))}))}isInMessageList(e){var t;const{conversationID:s}=e;if(!s)return!1;if(!this._messagesByConversation.has(s))return!1;const n=this._getUniqueIdOfMessage(e);return null===(t=this._messagesByConversation.get(s))||void 0===t?void 0:t.has(n)}isMessageSentByCurrentInstance(e){const{random:t}=e;return this._randomOfSentMessageList.has(t)}getContinuousMessagesByConversation(){return this._messagesByConversation}getLocalMessageList(e){const t=this._messagesByConversation.get(e);return t?[...t.values()]:[]}getSparseMessageList(e){const t=this._sparseMessagesByConversation.get(e);return t?[...t.values()]:[]}_reset(){this._messagesByConversation.clear(),this._latestMessageSentByPeerMap.clear(),this._latestMessageSentByMeMap.clear(),this._randomOfSentMessageList.clear()}_dispose(){this._reset(),Ut.notificationCenter.unSubscribeInnerEvent($t.LOGOUT,this._reset,this),Ut.notificationCenter.unSubscribeInnerEvent($t.DESTROY,this._dispose,this)}}function Ao(e,t){const s=an.getConversation(e);if(null==s?void 0:s.lastMessage){const{lastMessage:n}=s,{lastTime:o,lastSequence:i,version:r}=n,{time:a,sequence:c,messageVersion:l,elements:d,cloudCustomData:u}=t;o===a&&i===c&&r!==l&&(n.type=d[0].type,n.payload=d[0].content,n.messageForShow=As(n.type,n.payload),n.cloudCustomData=u,n.version=l,an.updateConversation(e,{lastMessage:n}))}}class No{init(){mn({apiName:"modifyMessage",context:this})}modifyMessage(e){return r(this,void 0,void 0,(function*(){const t=Ut.ssoLog.createSSOLogData({method:"modifyMessage"}),{to:s,payload:n,sequence:o,conversationType:i,random:a,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=n);try{let n=null,d=null;if(t.setLogInfo({message:`to:${s}`}),i===Vn.CONV_C2C?n=yield function(e){return r(this,void 0,void 0,(function*(){const t="openim.modify_c2c_msg",{from:s,to:n,version:o=0,sequence:i,random:r,time:a,type:c,cloudCustomData:l}=e,d=Ut.common.generateProtocolData({servcmd:t,data:{From_Account:s,To_Account:n,MsgVersion:o,MsgSeq:i,MsgRandom:r,MsgTime:a,MsgType:c,MsgBody:e.transformElementsToServerFormat(),CloudCustomData:l}}),u=`${d.head.seq}${t}`,_=yield Ut.channel.sendPacket(d,{requestId:u});if(_){const{MsgBody:e,MsgVersion:t,CloudCustomData:s}=_;return{elements:co(e),messageVersion:t,cloudCustomData:s}}}))}(e):i===Vn.CONV_GROUP&&(n=yield function(e){return r(this,void 0,void 0,(function*(){const t="openim.modify_group_msg",{to:s,version:n=0,sequence:o,cloudCustomData:i}=e;let r,a=s;Ts(s)&&(a=s.split(Xt.TOPIC)[0],r=s);const c=Ut.common.generateProtocolData({servcmd:t,data:{GroupId:a,TopicId:r,MsgVersion:n,MsgSeq:o,MsgBody:e.transformElementsToServerFormat(),CloudCustomData:i}}),l=`${c.head.seq}${t}`,d=yield Ut.channel.sendPacket(c,{requestId:l});if(d){const{MsgBody:e,MsgVersion:t,CloudCustomData:s}=d;return{elements:co(e),messageVersion:t,cloudCustomData:s}}}))}(e)),n){t.end();let r=`${i}${s}`;return s===ys()&&i===Vn.CONV_C2C&&(r=`${i}${l}`),d={conversationType:i,from:l,to:s,time:c,random:a,sequence:o,elements:null==n?void 0:n.elements,cloudCustomData:null==n?void 0:n.cloudCustomData,messageVersion:null==n?void 0:n.messageVersion,conversationID:r},this._handleModifyMessageSuccess(d),{code:0,data:{message:e}}}}catch(e){const{errorCode:t}=e||{},s=new as({functionName:"modifyMessage",code:t});throw this._logModifyMessageError(s),s}}))}_logModifyMessageError(e){Ut.ssoLog.getSSOLogData("modifyMessage").setError(e).end()}_handleModifyMessageSuccess(e){const{conversationID:t}=e,{isUpdated:s,message:n}=Ut.message.messageDataHandler.modifyConversationMessage(t,e);!0===s&&Ut.notificationCenter.emitOuterEvent(xt.MESSAGE_MODIFIED,{name:xt.MESSAGE_MODIFIED,data:[n]}),Ut.notificationCenter.emitInnerEvent($t.MESSAGE_MODIFIED,{conversationID:t,message:n}),Ao(t,e)}_canModifyMessageElement(e){return[Wn.MSG_TEXT,Wn.MSG_CUSTOM,Wn.MSG_LOCATION,Wn.MSG_FACE].includes(e)}}class Ro{init(){const{notificationCenter:e}=Ut,{InnerEventSubType:t}=e;Cs.registerWorkflowStep(ss.RECEIVE_C2C_NEW_MESSAGE,ns.HANDLE_C2C_NEW_MESSAGE,this._handleC2CMessagePush,this),Cs.registerWorkflowStep(ss.RECEIVE_C2C_NEW_MESSAGE,ns.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterReceiveNewMessage,this),Cs.registerWorkflowStep(ss.SYNC_SERVER_INFO_AFTER_RE_ONLINE,ns.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterSyncUnreadMessage,this),e.subscribeInnerEvent($t.MESSAGE_PUSH,t.C2C_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),e.subscribeInnerEvent($t.MESSAGE_PUSH,t.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),e.subscribeInnerEvent($t.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(e){Cs.executeWorkflow(ss.RECEIVE_C2C_NEW_MESSAGE,e)}_handleC2CMessagePush(e){const t=e.data||{},{messageDataHandler:s}=Ut.message||{},n=[],o=new Map;return t.C2cMsgArray.forEach((e=>{const t=this._generateC2CMessage(e);this._updateMessageProfile(t);let i=1===t.isModified;if(s.isMessageSentByCurrentInstance(t)?t.isModified=i:i=!1,t.isOnlineMessage())t._onlineOnlyFlag=!0,s.isMessageSentByCurrentInstance(t)||n.push(t);else if(!s.isInMessageList(t)){s.storeConversationMessage(t)&&uo({conversationUpdateFields:o,message:t}),s.isMessageSentByCurrentInstance(t)&&!i||n.push(t)}})),{conversationUpdateFieldList:[...o.values()],messages:n}}_emitMessageEventsAfterReceiveNewMessage(e){var t;const{messages:s=[]}=(null===(t=e.result)||void 0===t?void 0:t[ns.HANDLE_C2C_NEW_MESSAGE])||{};this._emitMessageEvents(s)}_emitMessageEventsAfterSyncUnreadMessage(e){var t;const{messages:s=[]}=(null===(t=e.result)||void 0===t?void 0:t[ns.UNREAD_MESSAGE_SYNC])||{};this._emitMessageEvents(s)}_emitMessageEvents(e){const t=(null==e?void 0:e.filter((e=>!0===(null==e?void 0:e.isModified))))||[];t.length>0&&Ut.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:t});const s=null==e?void 0:e.filter((e=>!(null==e?void 0:e.isModified)));s.length>0&&Ut.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:s})}_generateC2CMessage(e){const t=Vn.CONV_C2C,s=io(e),n=Ut.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{conversationType:t,flow:Hn.IN})),{elements:o}=s;return n.setElement(o),n}_updateMessageProfile(e){var t;const{messageDataHandler:s}=Ut.message||{},n=null===(t=Ut.store.get("login"))||void 0===t?void 0:t.userId,{from:o,nick:i,avatar:r,conversationID:l=""}=e;if(o!==n){const t=s.getLatestMsgSentByPeer(l);if(t){const{nick:n,avatar:o}=t;a(i)||a(r)?(e.nick=c(n)?n:e.nick,e.avatar=c(o)?o:e.avatar):i===n&&r===o||(s.updateNickAndAvatarOfSentMessage({conversationID:l,latestNick:i,latestAvatar:r,isSentByMe:!1}),this._updateConversationUserProfile({conversationID:l,nick:i,avatar:r}))}}else{const e=s.getLatestMsgSentByMe(l);!e||i===e.nick&&r===e.avatar||s.updateNickAndAvatarOfSentMessage({conversationID:l,latestNick:i,latestAvatar:r,isSentByMe:!0})}}_updateConversationUserProfile(e){const{conversationID:t,nick:s,avatar:n}=e,o=an.getConversation(t),{userProfile:i={}}=o||{};i.avatar===n&&i.nick===s||an.updateConversation(t,{userProfile:Object.assign(Object.assign({},i),{nick:s,avatar:n})})}_updateMessageListDueToModify(e){const{conversationID:t}=e,{isUpdated:s,message:n}=Ut.message.messageDataHandler.modifyConversationMessage(t,e);!0===s&&Ut.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[n]}),Ut.notificationCenter.emitInnerEvent("ModifyMessageSuccess",e),Ao(t,e)}_handleC2CMessageModify(e){e.C2cMsgModNotifys.forEach((e=>{var t;const s=Vn.CONV_C2C;let n=ro(e);const{to:o,from:i}=n;let r=`${s}${o}`;o===(null===(t=Ut.store.get("login"))||void 0===t?void 0:t.userId)&&(r=`${s}${i}`),n=Object.assign({conversationType:s,conversationID:r},n),this._updateMessageListDueToModify(n)}))}_dispose(){const{notificationCenter:e}=Ut,{InnerEventSubType:t}=e;Ut.notificationCenter.unSubscribeInnerEvent($t.MESSAGE_PUSH,t.C2C_REALTIME_MESSAGE,this._handleC2CMessagePush,this),Ut.notificationCenter.unSubscribeInnerEvent($t.MESSAGE_PUSH,t.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),Ut.notificationCenter.unSubscribeInnerEvent($t.DESTROY,this._dispose,this)}}class Do{init(){const{notificationCenter:e}=Ut,{InnerEventSubType:t}=e;Cs.registerWorkflowStep(ss.RECEIVE_GROUP_NEW_MESSAGE,ns.HANDLE_GROUP_NEW_MESSAGE,this._handleGroupMessagePush,this),Cs.registerWorkflowStep(ss.RECEIVE_GROUP_NEW_MESSAGE,ns.EMIT_GROUP_MESSAGE_EVENT,this._emitMessageEvents,this),e.subscribeInnerEvent($t.MESSAGE_PUSH,t.GROUP_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),e.subscribeInnerEvent($t.MESSAGE_PUSH,t.GROUP_MESSAGE_MODIFIED,this._handleGroupMessageModify,this),e.subscribeInnerEvent($t.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(e){Cs.executeWorkflow(ss.RECEIVE_GROUP_NEW_MESSAGE,e)}_handleGroupMessagePush(e){const t=e.data||{},{messageDataHandler:s}=Ut.message,n=[],o=new Map,i=null==t?void 0:t.GroupMsgArray;return null==i||i.forEach((e=>{const t=this._generateGroupMessage(e);this.updateMessageProfile(t);let i=1===t.isModified;if(s.isMessageSentByCurrentInstance(t)?t.isModified=i:i=!1,t.isOnlineMessage())t._onlineOnlyFlag=!0,s.isMessageSentByCurrentInstance(t)||n.push(t);else if(!s.isInMessageList(t)){s.storeConversationMessage(t)&&(n.push(t),uo({conversationUpdateFields:o,message:t}))}})),{conversationUpdateFieldList:[...o.values()],messages:n}}_emitMessageEvents(e){var t;const{messages:s}=(null===(t=e.result)||void 0===t?void 0:t[ns.HANDLE_GROUP_NEW_MESSAGE])||{},n=(null==s?void 0:s.filter((e=>!0===(null==e?void 0:e.isModified))))||[];n.length>0&&Ut.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:n});const o=(null==s?void 0:s.filter((e=>!(null==e?void 0:e.isModified))))||[];o.length>0&&Ut.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:o})}_generateGroupMessage(e){const t=Vn.CONV_GROUP,s=ao(e),n=Ut.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{conversationType:t,flow:Hn.IN})),{elements:o}=s;return n.setElement(o),n}updateMessageProfile(e){var t;const{messageDataHandler:s}=Ut.message||{},n=null===(t=Ut.store.get("login"))||void 0===t?void 0:t.userId,{from:o,nick:i,avatar:r,conversationID:a=""}=e;if(o===n){const e=s.getLatestMsgSentByMe(a);!e||i===e.nick&&r===e.avatar||s.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:i,latestAvatar:r,isSentByMe:!0})}}_updateMessageListDueToModify(e){const{conversationID:t}=e,{isUpdated:s,message:n}=Ut.message.messageDataHandler.modifyConversationMessage(t,e);!0===s&&Ut.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[n]}),Ao(t,e)}_handleGroupMessageModify(e){e.GroupMsgModNotifys.forEach((e=>{const t=Vn.CONV_GROUP;let s=lo(e);const{topicID:n,groupID:o}=s,i=n||o,r=`${t}${i}`;s=Object.assign({conversationType:t,conversationID:r,to:i},s),this._updateMessageListDueToModify(s)}))}_dispose(){const{notificationCenter:e}=Ut,{InnerEventSubType:{GROUP_REALTIME_MESSAGE:t,GROUP_MESSAGE_MODIFIED:s}}=e;e.unSubscribeInnerEvent($t.MESSAGE_PUSH,t,this._handleGroupMessagePush,this),e.unSubscribeInnerEvent($t.MESSAGE_PUSH,s,this._handleGroupMessageModify,this),e.unSubscribeInnerEvent($t.DESTROY,this._dispose,this)}}class wo{constructor(){this.c2cMessageReceiver=new Ro,this.groupMessageReceiver=new Do}init(){this.c2cMessageReceiver.init(),this.groupMessageReceiver.init()}}const bo={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 ko={createCustomMessage:!0,sendMessage:!0,modifyMessage:!0};class Po{constructor(){this.messageHelper=_o,this.messageFactory=new eo,this.messageSender=new yo,this.messageAction=new No,this.messageReceiver=new wo,this.messageDataHandler=new To,this.messageSender.init(),this.messageFactory.init(),this.messageAction.init(),this.messageReceiver.init(),ms({auth:ko,params:bo})}}const Lo="User",Uo="Tag_Profile_IM_",Go=100,Fo={NICK:`${Uo}Nick`,GENDER:`${Uo}Gender`,BIRTHDAY:`${Uo}BirthDay`,LOCATION:`${Uo}Location`,SELFSIGNATURE:`${Uo}SelfSignature`,ALLOWTYPE:`${Uo}AllowType`,LANGUAGE:`${Uo}Language`,AVATAR:`${Uo}Image`,MESSAGESETTINGS:`${Uo}MsgSettings`,ADMINFORBIDTYPE:`${Uo}AdminForbidType`,LEVEL:`${Uo}Level`,ROLE:`${Uo}Role`},xo="USER_STATUS",Bo=1,$o={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:[]},Vo=new Map([[Fo.NICK,"nick"],[Fo.GENDER,"gender"],[Fo.BIRTHDAY,"birthday"],[Fo.LOCATION,"location"],[Fo.SELFSIGNATURE,"selfSignature"],[Fo.ALLOWTYPE,"allowType"],[Fo.LANGUAGE,"language"],[Fo.AVATAR,"avatar"],[Fo.MESSAGESETTINGS,"messageSettings"],[Fo.ADMINFORBIDTYPE,"adminForbidType"],[Fo.LEVEL,"level"],[Fo.ROLE,"role"]]);var qo=new class{createProfile(e,t){const s={userID:e,profileCustomField:[]};return t.forEach((e=>{const{tag:t,value:n}=e;t&&t.indexOf("Tag_Profile_Custom")>-1?s.profileCustomField.push({key:t,value:n}):Vo.has(t)&&(s[Vo.get(t)]=n)})),Object.assign(Object.assign({},$o),s)}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((s=>{t.push({tag:Fo[s.toUpperCase()],value:e[s]})})),t}normalizeProfileFields(e){const t={};return e.forEach((e=>{const{tag:s,value:n}=e;if(Vo.has(s)){const e=Vo.get(s);t[e]=n}})),t}};const{generateProtocolData:Wo}=Ut.common;function Yo(e){return r(this,void 0,void 0,(function*(){const t="profile.portrait_get_all",s={From_Account:ys(),UserItem:[]};e.forEach((e=>{s.UserItem.push({CustomSequence:0,StandardSequence:0,To_Account:e})}));const n=Wo({servcmd:t,data:s}),o=`${n.head.seq}${t}`,i=yield Ut.channel.sendPacket(n,{requestId:o});if(i)return function(e){const{ActionStatus:t,ErrorCode:s,ErrorDisplay:n,ErrorInfo:o,UserProfileItem:i}=e,r=[];return i.map((e=>{const{To_Account:t,CustomSequence:s,ResultCode:n,ResultInfo:o,StandardSequence:i,ProfileItem:a}=e,c=qo.parseProfileItem(a);r.push({userId:t,customSequence:s,resultCode:n,resultInfo:o,standardSequence:i,profileItem:c})})),{actionStatus:t,errorCode:s,errorDisplay:n,errorInfo:o,userProfile:r}}(i)}))}function Ko(e){return dn.getFriendMap().has(e)}const{isEmpty:jo}=Ut.utils;class Ho{init(){mn({apiName:"getMyProfile",context:this}),mn({apiName:"getUserProfile",context:this}),mn({apiName:"updateMyProfile",context:this}),this.createProfile=qo.createProfile.bind(qo);const{notificationCenter:e}=Ut;Cs.registerWorkflowStep(ss.SYNC_SERVER_INFO_AFTER_LOGIN,ns.USER_PROFILE_SYNC,this.getMyProfileCacheThenServer,this),e.subscribeInnerEvent($t.MESSAGE_PUSH,e.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),e.subscribeInnerEvent($t.LOGOUT,this._reset,this),e.subscribeInnerEvent($t.DESTROY,this._dispose,this)}getMyProfile(){return r(this,void 0,void 0,(function*(){const e=Ut.ssoLog.createSSOLogData({method:"getMyProfile"});try{const t=ys(),s=yield Yo([t]);if(s){const e=this._handleProfileFormResponse(s)[0];return dn.getUserProfileMap().set(t,e),{code:0,data:e}}e.end()}catch(t){const{errorCode:s,errorInfo:n}=t,o=new as({functionName:"getMyProfile",code:s,message:n});throw e.setError(o).end(),t}}))}getUserProfile(e){return r(this,void 0,void 0,(function*(){const t=Ut.ssoLog.createSSOLogData({method:"getUserProfile"});try{let{userIDList:s}=e;s.length>Go&&(s=s.slice(0,Go));const{userIdListToRequest:n,userIdListToCache:o}=this._filterRequestAndCacheUsers(s),i=[];o.forEach((e=>{const t=dn.getUserProfile(e);i.push(t)}));const r=`userIDList.length:${s.length}`;if(0===n.length)return t.setLogInfo({message:r}).end(),{code:0,data:i};const a=yield Yo(n);if(a){const e=this._handleProfileFormResponse(a);e.forEach((e=>{Ko(e.userID)&&dn.getUserProfileMap().set(e.userID,e)}));const s=e.concat(i);return t.setLogInfo({message:r}).end(),{code:0,data:s}}}catch(e){const{errorCode:s}=e,n=new as({functionName:"getUserProfile",code:s});throw t.setError(n).end(),n}}))}getMyProfileCacheThenServer(){return r(this,void 0,void 0,(function*(){const e=ys(),t=dn.getUserProfileMap().has(e);return t?{code:0,data:t}:this.getMyProfile()}))}updateMyProfile(e){return r(this,void 0,void 0,(function*(){const t=Ut.ssoLog.createSSOLogData({method:"updateMyProfile"}),s=ys(),n={};for(const t in e)void 0!==e[t]&&(n[t]=e[t]);const o=qo.convertParamsToProfile(n);try{const e={From_Account:s,ProfileItem:o};t.setLogInfo({message:JSON.stringify(o)}),yield function(e){return r(this,void 0,void 0,(function*(){const t="profile.portrait_set",s=Wo({servcmd:t,data:e}),n=`${s.head.seq}${t}`,o=yield Ut.channel.sendPacket(s,{requestId:n});if(o){const{ActionStatus:e,ErrorCode:t,ErrorDisplay:s,ErrorInfo:n}=o;return{actionStatus:e,errorCode:t,errorDisplay:s,errorInfo:n}}}))}(e);const i=dn.getUserProfile(s);let a;a=i?Object.assign(Object.assign({},i),n):qo.createProfile(s,o);return!ds(i,a,["lastUpdatedTime","profileCustomField"])&&Ut.notificationCenter.emitOuterEvent(xt.PROFILE_UPDATED,{name:xt.PROFILE_UPDATED,data:[a]}),a.lastUpdatedTime=Date.now(),dn.getUserProfileMap().set(s,a),t.end(),{code:0,data:a}}catch(e){const{errorCode:s,errorInfo:n}=e,o=new as({functionName:"updateMyProfile",code:s,message:n});throw t.setError(o).end(),o}}))}updateMyNickAndAvatar(e){return r(this,void 0,void 0,(function*(){const t=ys(),s=Date.now(),n=dn.getUserProfile(t);let o={};o=n?Object.assign(n,e):qo.createProfile(t,e),o.lastUpdatedTime=s,dn.getUserProfileMap().set(t,o)}))}_onProfileDataModify(e){const t=function(e){const{Profile_Account:t,PushType:s,ProfileList:n}=e;return{userId:t,pushType:s,profileList:qo.parseProfileList(n)}}(e.ProfileDataMod[0]);if(jo(t))return;const{isProfileUpdated:s,profile:n}=this._handleProfileModified(t);s&&(Ut.notificationCenter.emitInnerEvent($t.PROFILE_UPDATE,{name:$t.PROFILE_UPDATE,data:[n]}),Ut.notificationCenter.emitOuterEvent(xt.PROFILE_UPDATED,{name:xt.PROFILE_UPDATED,data:[n]}))}_dispose(){const{notificationCenter:e}=Ut;e.unSubscribeInnerEvent($t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent($t.MESSAGE_PUSH,e.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),e.unSubscribeInnerEvent($t.DESTROY,this._dispose,this),this._reset()}_handleProfileModified(e){const{userId:t,profileList:s}=e,n=dn.getUserProfile(t);if(!n||!Ko(t))return{isProfileUpdated:!1,profile:null};const o=qo.normalizeProfileFields(s),i=Object.keys(o).some((e=>n[e]!==o[e]));if(!i)return{isProfileUpdated:!1,profile:n};const r=Date.now(),a=Object.assign(Object.assign(Object.assign({},n),o),{lastUpdatedTime:r});return dn.getUserProfileMap().set(t,a),an.updateConversation(`C2C${t}`,{userProfile:a}),{isProfileUpdated:i,profile:a}}_filterRequestAndCacheUsers(e){const t=[],s=[];return e.forEach((e=>{const n=dn.getUserProfileMap().has(e);Ko(e)&&n?s.push(e):t.push(e)})),{userIdListToRequest:t,userIdListToCache:s}}_handleProfileFormResponse(e){const{userProfile:t}=e;if(!Array.isArray(t))return[];const s=t.filter((e=>"@TLS#NOT_FOUND"!==e.userId&&""!==e.userId&&!jo(e.profileItem))),n=Date.now();return s.map((e=>{const t=qo.createProfile(e.userId,e.profileItem);return t.lastUpdatedTime=n,t}))}_reset(){dn.getUserProfileMap().clear()}}const zo=new Map,Zo=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];for(let e=0,t=Zo.length;e<t;e++)zo.set(e,Zo[e]);function Jo(e){if(!e)return"";const t=String(e).replace(/[=]+$/,"");let s="";if(t.length%4==1)return"";for(let e,n,o=0,i=0;n=t.charAt(i++);~n&&(e=o%4?64*e+n:n,o++%4)?s+=String.fromCharCode(255&e>>(-2*o&6)):0)n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(n);try{return decodeURIComponent(escape(s))}catch(e){return console.warn(e),""}}const{isEmpty:Xo}=Ut.utils,{generateProtocolData:Qo}=Ut.common;function ei(e){return r(this,void 0,void 0,(function*(){const t="im_open_status.ws_get_user_status",s=Qo({servcmd:t,data:{To_Account:e}}),n=`${s.head.seq}${t}`,o=yield Ut.channel.sendPacket(s,{requestId:n});if(o)return function(e){const{ErrorCode:t,ErrorInfo:s,ErrorList:n=[],UserStatusList:o=[]}=e,i=o.map((e=>{const{To_Account:t,Status:s,CustomStatus:n}=e;return{userID:t,statusType:s,customStatus:Jo(n)}})),r=n.map((e=>{const{To_Account:t,Invalid_Account:s,ErrorCode:n,ErrorInfo:o}=e;return{userID:Xo(s)?t:s,code:n,message:o}}));return{errorCode:t,errorInfo:s,successUserList:i,failureUserList:r}}(o)}))}class ti{constructor(){this._customStatus=""}init(){const{notificationCenter:e}=Ut;mn({apiName:"getUserStatus",context:this}),mn({apiName:"setSelfStatus",context:this}),mn({apiName:"subscribeUserStatus",context:this}),mn({apiName:"unsubscribeUserStatus",context:this}),Cs.registerWorkflowStep(ss.SYNC_SERVER_INFO_AFTER_RE_ONLINE,ns.USER_STATUS_UPDATE,this._onReOnline,this),e.subscribeInnerEvent($t.MESSAGE_PUSH,e.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),e.subscribeInnerEvent($t.LOGOUT,this._reset,this),e.subscribeInnerEvent($t.DESTROY,this._dispose,this)}setSelfStatus(e){return r(this,void 0,void 0,(function*(){const t=Ut.ssoLog.createSSOLogData({method:"setSelfStatus"}),s=ys(),{customStatus:n}=e;try{return yield function(e){return r(this,void 0,void 0,(function*(){const t="im_open_status.ws_set_custom_status",s=Qo({servcmd:t,data:{CustomStatus:e}}),n=`${s.head.seq}${t}`,o=yield Ut.channel.sendPacket(s,{requestId:n});if(o){const{ErrorCode:e,ErrorInfo:t}=o;return{errorCode:e,errorInfo:t}}}))}(n),this._customStatus=n,t.setLogInfo({message:`customStatus: ${n}`}).end(),{code:0,data:{userID:s,statusType:Bo,customStatus:n}}}catch(e){const{errorCode:s,errorInfo:n}=e,o=new as({functionName:"setSelfStatus",code:s,message:n});throw t.setError(o).end(),o}}))}getUserStatus(e){return r(this,void 0,void 0,(function*(){const t=Ut.ssoLog.createSSOLogData({method:"getUserStatus"}),{userIDList:s=[]}=e;return t.setLogInfo({moreMessage:`userIDList length: ${s.length}`}),this._isOnlyMeInArray(s)?this._getMyStatus():this._getUserStatus(s)}))}setCustomStatus(e){const t=Jo(e);this._customStatus=t}subscribeUserStatus(e){return r(this,void 0,void 0,(function*(){try{console.log(`${Lo} subscribeUserStatus options: `,e);const{userIDList:t=[]}=e;this._checkBusinessCapabilityBits("subscribeUserStatus");const s=this._getMaxUserCount("subscribe"),n=this._sliceUserIDList(t,s),o=yield function(e){return r(this,void 0,void 0,(function*(){const{channel:t}=Ut,s="im_open_status.ws_status_subscribe",n=Qo({servcmd:s,data:{To_Account:e}}),o=`${n.head.seq}${s}`;return yield t.sendPacket(n,{requestId:o})}))}(n);return{code:0,data:{failureUserList:this._parseResponse(o)}}}catch(e){throw console.error(`${Lo} subscribeUserStatus error:`,e),e}}))}unsubscribeUserStatus(e){return r(this,void 0,void 0,(function*(){try{console.log(`${Lo} unsubscribeUserStatus options: `,e),this._checkBusinessCapabilityBits("unsubscribeUserStatus");const{userIDList:t=[]}=e,s=this._getMaxUserCount("unsubscribe"),n=this._sliceUserIDList(t,s),o=yield function(e){return r(this,void 0,void 0,(function*(){const{channel:t}=Ut,s="im_open_status.ws_status_unsubscribe";let n={};n=0===e.length?{UnsubscribeAll:1}:{To_Account:e};const o=Qo({servcmd:s,data:n}),i=`${o.head.seq}${s}`;return yield t.sendPacket(o,{requestId:i})}))}(n);return{code:0,data:{failureUserList:this._parseResponse(o)}}}catch(e){throw console.error(`${Lo} unsubscribeUserStatus error:`,e),e}}))}_onUserStatusUpdate(e){const{UserStatusList:t=[]}=e||{},s=t.map((e=>{const{To_Account:t,Status:s,CustomStatus:n}=e;return{userID:t,statusType:s,customStatus:Jo(n)}}));this._emitUserStatusUpdatedEvent(s)}_onReOnline(e){const t=Jo(e.data.customStatus);if(this._customStatus===t)return;this._customStatus=t;const s={userID:ys(),statusType:Bo,customStatus:t};this._emitUserStatusUpdatedEvent(s)}_emitUserStatusUpdatedEvent(e){Ut.notificationCenter.emitOuterEvent(xt.USER_STATUS_UPDATED,{name:xt.USER_STATUS_UPDATED,data:e})}_sliceUserIDList(e,t){return e.slice(0,t)}_parseResponse(e){const{ErrorList:t=[]}=e;return t.map((e=>{const{To_Account:t,Invalid_Account:s,ErrorCode:n,ErrorInfo:o}=e;return{userID:Ut.utils.isEmpty(s)?t:s,code:n,message:o}}))}_checkBusinessCapabilityBits(e){if(!Ut.store.get("commercialConfig").get(xo))throw new as({functionName:e,code:ts.NO_USE,replacement1:e})}_getMaxUserCount(e){const t=Ut.store.get("cloudConfig")||{},s={query:{key:"status_query_count",default:500},subscribe:{key:"status_sub_count",default:Go},unsubscribe:{key:"status_unsub_count",default:Go}},{key:n,default:o}=s[e],i=t[n]||o;return parseInt(i,10)}_getMyStatus(){const e=Ut.ssoLog.getSSOLogData("getUserStatus");e.setLogInfo({moreMessage:"getUserStatus._getMyStatus"});const t={userID:ys(),statusType:Bo,customStatus:this._customStatus};return e.end(),{code:0,data:{successUserList:[t],failureUserList:[]}}}_getUserStatus(e){return r(this,void 0,void 0,(function*(){const t=Ut.ssoLog.getSSOLogData("getUserStatus");t.setLogInfo({moreMessage:"getUserStatus._getUserStatus"});try{this._checkBusinessCapabilityBits("getUserStatus");const s=this._getMaxUserCount("query"),n=this._sliceUserIDList(e,s),o=yield ei(n),{successUserList:i,failureUserList:r}=o||{};return t.end(),{code:0,data:{successUserList:i,failureUserList:r}}}catch(e){const{errorCode:s}=e,n=new as({functionName:"getUserStatus",code:s});throw t.setError(n).end(),n}}))}_isOnlyMeInArray(e){const t=ys();return 1===e.length&&e.indexOf(t)>-1}_dispose(){const{notificationCenter:e}=Ut;e.unSubscribeInnerEvent($t.MESSAGE_PUSH,e.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),e.unSubscribeInnerEvent($t.DESTROY,this._dispose,this),e.unSubscribeInnerEvent($t.LOGOUT,this._reset,this),this._reset()}_reset(){this._customStatus=""}}const si={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}}},ni={getMyProfile:!0,getUserProfile:!0,updateMyProfile:!0,setSelfStatus:!0,getUserStatus:!0,subscribeUserStatus:!0,unsubscribeUserStatus:!0};class oi{constructor(){this.userProfile=new Ho,this.userStatus=new ti,this.userProfile.init(),this.userStatus.init(),ms({auth:ni,params:si})}}console.log(`TencentCloudLiteChat.VERSION:${$e}`);var ii={create:function(e){const{SDKAppID:t,testEnv:s=!1,devMode:n=!1,unlimitedAVChatRoom:o=!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),Is.has(i))return Is.get(i);const r=function(){function e(){return(65536*(1+Math.random())|0).toString(16).substring(1)}return`${e()+e()}${e()}${e()}${e()}${e()}${e()}${e()}`}();Ut.init({sdkAppId:i,instanceId:r,testEnv:s,devMode:n,unlimitedAVChatRoom:o}),Cs.init(),Ut.message=new Po,Ut.user=new oi,Ut.login=new $n,Ss.installBuiltInPlugin(nn);const a=In();return Is.set(i,a),a},TSignaling:Vt,EVENT:xt,VERSION:$e,TYPES:es};export{ii as default};