@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/index.es.js CHANGED
@@ -1 +1 @@
1
- class e{constructor(){this.listeners={}}on(e,t,n){this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push({fn:t,context:n})}off(e,t,n){var s;t&&(this.listeners[e]=null===(s=this.listeners[e])||void 0===s?void 0:s.filter((e=>{const s=e.fn===t,i=!n||e.context===n;return!(s&&i)})))}emit(e,...t){const n=this.listeners[e];n&&n.forEach((e=>{const{fn:n,context:s}=e;n.apply(s,t)}))}once(e,t,n){const s=(...i)=>{t.apply(n,i),this.off(e,s)};this.on(e,s)}}var t;!function(e){e.BUSINESS_COMMAND="business_command",e.C2C_REALTIME_MESSAGE="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"}(t||(t={}));const n=[{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 n;const s=[];return null===(n=null==e?void 0:e.C2cNotifyMsgArray)||void 0===n||n.forEach((e=>{e.WithdrawC2cMsgNotify&&s.push(t.C2C_REVOKED_MESSAGE),e.C2cReadedReceipt&&s.push(t.C2C_MESSAGE_PEER_READ),e.ReadC2cMsgNotify&&s.push(t.C2C_MESSAGE_READ_SYNC),e.MuteNotificationsSync&&s.push(t.C2C_REMIND_TYPE_SYNC)})),s}},{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 n;const s=[];return null===(n=null==e?void 0:e.GroupTips)||void 0===n||n.forEach((e=>{Array.isArray(e.MsgBody.GroupWithdrawInfoArray)&&s.push(t.GROUP_MESSAGE_REVOKED),Array.isArray(e.MsgBody.GroupMsgReceiptList)&&s.push(t.GROUP_MESSAGE_READ_RECEIPT),Array.isArray(e.MsgBody.GroupReadInfoArray)?s.push(t.GROUP_MESSAGE_READ_SYNC):s.push(t.GROUP_SYSTEM_NOTIFICATION)})),s}},{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}];var s;!function(e){e.SERVER_PUSH_MESSAGE="im_open_push.msg_push",e.ERROR="error"}(s||(s={}));const i={[s.SERVER_PUSH_MESSAGE]:function(e){var t;const i=Array.isArray(null===(t=null==e?void 0:e.body)||void 0===t?void 0:t.EventArray)?e.body.EventArray:[],o=[];return i.forEach((t=>{t.Flag=e.body.Flag;const i=n.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(!i)return null;let r=[];"function"==typeof i.subTypeParser?r=i.subTypeParser(t):i.subType&&(r=i.subType),Array.isArray(r)?r.forEach((e=>{o.push({type:`${s.SERVER_PUSH_MESSAGE}:${e}`,data:t})})):o.push({type:`${s.SERVER_PUSH_MESSAGE}:${r}`,data:t})})),o},[s.ERROR]:function(e){const{errorCode:t}=e;return[{type:`error:${t}`,data:e}]}};const o=new class{constructor(){this._outerEventEmitter=null,this._innerEventEmitter=null,this._outerEventEmitter=new e,this._innerEventEmitter=new e,this.InnerEventSubType=t}subscribeInnerEvent(e,t,n,s){var i,o;if(["string","number"].includes(typeof t)){const o=t,r=n;null===(i=this._innerEventEmitter)||void 0===i||i.on(`${e}:${o}`,r,s)}else{const s=t;null===(o=this._innerEventEmitter)||void 0===o||o.on(e,s,n)}}emitInnerEvent(e,t){var n,s;if(null===(n=this._innerEventEmitter)||void 0===n||n.emit(e,t),Object.keys(i).includes(e)){const n=null===(s=i[e])||void 0===s?void 0:s.call(i,t);null==n||n.forEach((e=>{var t;e&&(null===(t=this._innerEventEmitter)||void 0===t||t.emit(e.type,e.data))}))}}unSubscribeInnerEvent(e,t,n,s){var i,o;if(["string","number"].includes(typeof t)){const o=t,r=n;null===(i=this._innerEventEmitter)||void 0===i||i.off(`${e}:${o}`,r,s)}else{const s=t;null===(o=this._innerEventEmitter)||void 0===o||o.off(e,s,n)}}subscribeOuterEvent(e,t,n){var s;null===(s=this._outerEventEmitter)||void 0===s||s.on(e,t,n)}unSubscribeOuterEvent(e,t,n){var s;null===(s=this._outerEventEmitter)||void 0===s||s.off(e,t,n)}emitOuterEvent(e,t){var n;null===(n=this._outerEventEmitter)||void 0===n||n.emit(e,t)}getOuterEventEmitter(){return this._outerEventEmitter}rest(){this._outerEventEmitter=null,this._innerEventEmitter=null}};function r(e,t){var n={};for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.indexOf(s)<0&&(n[s]=e[s]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(s=Object.getOwnPropertySymbols(e);i<s.length;i++)t.indexOf(s[i])<0&&Object.prototype.propertyIsEnumerable.call(e,s[i])&&(n[s[i]]=e[s[i]])}return n}function a(e,t,n,s){return new(n||(n=Promise))((function(i,o){function r(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(r,a)}c((s=s.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const c=e=>void 0===e,l=e=>"string"==typeof e,d=e=>{var t;return null===(t=Object.prototype.toString.call(e).match(/^\[object (.*)\]$/))||void 0===t?void 0:t[1].toLowerCase()},u=e=>"function"==typeof Array.isArray?Array.isArray(e):"array"===d(e),_=e=>null!==e&&"object"==typeof e,h=e=>u(e)||_(e),g=e=>{if("string"!=typeof e)return!1;const t=e[0];return!/[^a-zA-Z0-9]/.test(t)},f=e=>{if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);if(null===t)return!0;let n=t;for(;null!==Object.getPrototypeOf(n);)n=Object.getPrototypeOf(n);return t===n};function E(e=99999999){return Math.round(Math.random()*e)}const p=(e,t,n,s)=>{if(!h(e)||!h(t))return 0;let i=0;const o=Object.keys(t);let r;for(let a=0,l=o.length;a<l;a++)if(r=o[a],!(c(t[r])||n&&n.includes(r)))if(h(e[r])&&h(t[r]))i+=p(e[r],t[r],n,s);else{if(s&&s.includes(t[r]))continue;e[r]!==t[r]&&(e[r]=t[r],i+=1)}return i};function S(e){let t,n,s=e;e.length%8!=0&&(s="0".repeat(8-e.length%8)+e);let i="";for(let e=0,{length:o}=s;e<o;e+=8)t=parseInt(s.slice(e,e+4),2),n=parseInt(s.slice(e+4,e+8),2),i+=base16Map.get(t)+base16Map.get(n);return i}const 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},v=["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 I=Object.freeze({__proto__:null,ENUM_PLATFORM:m,NOT_NEED_CRC_SERVCMD:v});const C="undefined"!=typeof wx&&"function"==typeof wx.getSystemInfoSync&&Boolean(wx.getSystemInfoSync().fontSizeSetting),y=C&&"function"==typeof wx.createGamePortal,O="undefined"!=typeof qq&&"function"==typeof qq.getSystemInfoSync&&Boolean(qq.getSystemInfoSync().fontSizeSetting),M="undefined"!=typeof tt&&"function"==typeof tt.getSystemInfoSync&&Boolean(tt.getSystemInfoSync().fontSizeSetting),T="undefined"!=typeof swan&&"function"==typeof swan.getSystemInfoSync&&Boolean(swan.getSystemInfoSync().fontSizeSetting),A="undefined"!=typeof my&&"function"==typeof my.getSystemInfoSync&&Boolean(my.getSystemInfoSync().fontSizeSetting),N="undefined"!=typeof jd&&"function"==typeof jd.getSystemInfoSync,D="undefined"!=typeof uni&&"undefined"==typeof window&&"function"==typeof uni.requireNativePlugin,R=C&&"object"==typeof wx.miniapp,b="undefined"!=typeof uni,w=C||O||M||T||A||D||N,L="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 uni?!w:"undefined"!=typeof window&&!w&&!k,U=O?qq:M?tt:T?swan:A?my:C?wx:D?uni:N?jd:{},F=P&&window&&window.navigator&&window.navigator.userAgent||"",G=/(micromessenger|webbrowser)/i.test(F),x=function(){let e="WEB";return G?e="WEB":O?e="QQ_MP":M?e="TT_MP":T?e="BAIDU_MP":A?e="ALI_MP":C?e=R?"DONUT_NATIVE_APP":"WX_MP":D?e="UNI_NATIVE_APP":L?e="NS_NATIVE_APP":k&&(e="RN_NATIVE_APP"),m[e]}(),B=/iPad/i.test(F),$=/iPhone/i.test(F)&&!B,V=/iPod/i.test(F),q=$||B||V,j=function(){const e=F.match(/OS (\d+)_/i);return e&&e[1]?e[1]:null}(),Y=/Android/i.test(F),W=function(){const e=F.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(!e)return null;const t=e[1]&&parseFloat(e[1]),n=e[2]&&parseFloat(e[2]);return t&&n?parseFloat(`${e[1]}.${e[2]}`):t||null}(),K=/Firefox/i.test(F),H=/Edge/i.test(F),z=!H&&/Chrome/i.test(F),J=/MSIE/.test(F)||F.indexOf("Trident")>-1&&F.indexOf("rv:11.0")>-1,Z=function(){const e=/MSIE\s(\d+)\.\d/.exec(F);let t=e&&parseFloat(e[1]);return!t&&/Trident\/7.0/i.test(F)&&/rv:11.0/.test(F)&&(t=11),t}(),X=/Safari/i.test(F)&&!z&&!Y&&!H,Q=/Windows/i.test(F),ee=/MAC OS X/i.test(F),te=P&&"undefined"!=typeof Worker&&!J,ne=Y||q,se=P&&void 0!==window.tencent_cloud_im_csig_flutter_for_web_25F_cy,ie=function(){if("undefined"==typeof window||void 0===window.navigator)return!1;const{standalone:e}=window.navigator;return!(!q||e||X)}();function oe(){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 a(this,arguments,void 0,(function*({method:e,url:t,data:n,timeout:s=ce}){return new Promise(w?(i,o)=>{U.request({url:t,data:n,method:e,timeout:s,header:{"content-type":le},success:e=>i(e.data),fail:()=>o(new Error(`{"message":"Network error","code":${re}}`))})}:(i,o)=>{const r=new XMLHttpRequest,a=setTimeout((()=>{r.abort(),o(new Error(`{"message":"Request timeout","code":${ae}}`))}),s);r.onreadystatechange=function(){if(4===r.readyState)if(clearTimeout(a),200===r.status||304===r.status)try{i(r.responseText?JSON.parse(r.responseText):null)}catch(e){i(r.responseText)}else o(new Error(`{"message":"Network error","code":${re}}`))},r.open(e,t,!0),r.setRequestHeader("Content-type",le),r.send(n||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(f(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(){let e,t;return{promise:new Promise(((n,s)=>{e=n,t=s})),resolve:e,reject:t}}var he,ge=Object.freeze({__proto__:null,ANDROID_VERSION:W,IE_VERSION:Z,IN_ALIPAY_MINI_APP:A,IN_BAIDU_MINI_APP:T,IN_BROWSER:P,IN_DONUT_NATIVE_APP:R,IN_JD_MINI_APP:N,IN_MINI_APP:w,IN_NS_NATIVE_APP:L,IN_QQ_MINI_APP:O,IN_RN_APP:k,IN_TT_MINI_APP:M,IN_UNI_APP:b,IN_UNI_NATIVE_APP:D,IN_WX_MINI_APP:C,IN_WX_MINI_GAME:y,IOS_VERSION:j,IS_ANDROID:Y,IS_CHROME:z,IS_EDGE:H,IS_FIREFOX:K,IS_IE:J,IS_IOS:q,IS_IPAD:B,IS_IPHONE:$,IS_IPOD:V,IS_MAC:ee,IS_SAFARI:X,IS_WECHAT:G,IS_WIN:Q,IS_WORKER_AVAILABLE:te,MINI_APP_NAMESPACE:U,USER_AGENT:F,base16EncodeBinaryString:S,deepCopyWithMethods:function e(t){if(null===t||"object"!=typeof t)return t;if(t instanceof Date)return new Date(t.getTime());if(t instanceof RegExp)return new RegExp(t.source,t.flags);if(t instanceof Map){const n=new Map;return t.forEach(((t,s)=>{n.set(e(s),e(t))})),n}if(t instanceof Set){const n=new Set;return t.forEach((t=>{n.add(e(t))})),n}if(Array.isArray(t))return t.map((t=>e(t)));const n=Object.getPrototypeOf(t),s=Object.create(n);return[...Object.getOwnPropertyNames(t),...Object.getOwnPropertySymbols(t)].forEach((n=>{const i=Object.getOwnPropertyDescriptor(t,n);i&&(i.get||i.set?Object.defineProperty(s,n,i):s[n]=e(t[n]))})),s},deepMerge:p,generatePromise:_e,getPlatformType:oe,getType:d,httpRequest:de,isArray:u,isArrayOrObject:h,isEmpty:ue,isFlutterWeb:se,isH5:ne,isIOSWebView:ie,isNumber:e=>null!==e&&("number"==typeof e&&!Number.isNaN(e-0)||"object"==typeof e&&e.constructor===Number),isObject:_,isPlainObject:f,isString:l,isUndefined:c,isValidRequestKey:g,platform:x,randomInt:E});class fe{constructor(){this._socket=null}connectSocket(e){return this._socket=new WebSocket(e),this._socket}send(e){var t,n;try{null===(t=this._socket)||void 0===t||t.send(e)}catch(e){null===(n=this._onSendFail)||void 0===n||n.call(this,e)}}bindSocketHandlers(e){const{onOpen:t,onMessage:n,onClose:s,onError:i,onSendFail:o}=e;this._socket&&(this._socket.binaryType="arraybuffer",this._socket.onopen=t,this._socket.onmessage=n,this._socket.onclose=s,this._socket.onerror=i,this._onSendFail=o)}unbindSocketHandlers(){this._socket&&(this._socket.onopen=null,this._socket.onmessage=null,this._socket.onclose=null,this._socket.onerror=null)}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}class 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:n,onClose:s,onError:i,onSendFail:o}=e;this._socket.onClose(s),this._socket.onOpen(t),this._socket.onMessage(n),this._socket.onError(i),this._onSendFail=o}unbindSocketHandlers(){this._socket&&(this._socket.onClose((()=>{})),this._socket.onOpen((()=>{})),this._socket.onMessage((()=>{})),this._socket.onError((()=>{})))}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}!function(e){e[e.CONNECTED=0]="CONNECTED",e[e.CONNECTING=1]="CONNECTING",e[e.DISCONNECTED=2]="DISCONNECTED"}(he||(he={}));class pe{constructor(t){this._url="",this._readyState=he.DISCONNECTED,this._url=t,this._id=E(),this._emitter=new e,this._socket=C?new Ee:new fe,this.connect()}connect(){this.doOpen(),this._bindSocketHandlers()}doOpen(){[he.CONNECTED,he.CONNECTING].includes(this._readyState)||(this._readyState=he.CONNECTING,this._ws=this._socket.connectSocket(this._url))}send(e){this._readyState!==he.CONNECTED?this.reconnect():this._socket.send(e)}reconnect(){[he.CONNECTED,he.CONNECTING].includes(this._readyState)||(this.disconnect(),this.doOpen())}getId(){return this._id}on(e,t,n){this._emitter.on(e,t,n)}off(e,t,n){this._emitter.off(e,t,n)}isConnected(){return this._readyState===he.CONNECTED}disconnect(){this._readyState=he.DISCONNECTED,this._unbindSocketHandlers(),this._socket.disconnect()}_onOpen(e){this._readyState===he.CONNECTING&&(this._readyState=he.CONNECTED,this._emitter.emit("connect",{socketId:this._id,event:e}))}_onMessage(e){this._emitter.emit("message",e)}_onClose(e){this._readyState=he.DISCONNECTED,this._emitter.emit("close",{socketId:this._id,event:e})}_onError(e){this._readyState=he.DISCONNECTED,this._emitter.emit("error",{socketId:this._id,error:e})}_onSendFail(e){this._readyState=he.DISCONNECTED,this._emitter.emit("sendFail",{socketId:this._id,error:e})}_bindSocketHandlers(){this._socket.bindSocketHandlers({onOpen:this._onOpen.bind(this),onMessage:this._onMessage.bind(this),onClose:this._onClose.bind(this),onError:this._onError.bind(this),onSendFail:this._onSendFail.bind(this)})}_unbindSocketHandlers(){this._socket.unbindSocketHandlers()}}const Se="CHINA",me="SINGAPORE",ve="KOREA",Ie="GERMANY",Ce="IND",ye="JPN",Oe="USA",Me="INDONESIA",Te={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"}}},Ae={[me]:[[2e7,3e7],[172e7,173e7]],[ve]:[[3e7,4e7],[173e7,174e7]],[Ie]:[[4e7,5e7],[174e7,175e7]],[Ce]:[[5e7,6e7],[175e7,176e7]],[ye]:[[6e7,7e7],[176e7,177e7]],[Oe]:[[7e7,8e7],[177e7,178e7]],[Me]:[[8e7,9e7],[178e7,179e7]]};function Ne(e){for(const t of Object.keys(Ae))for(const[n,s]of Ae[t])if(e>=n&&e<s)return t;return Se}var De,Re=new class{constructor(){this._store=new Map}get(e){return this._store.get(e)}getStorage(e){if(w){if(A){return my.getStorageSync({key:e}).data}return U.getStorageSync(e)}return this._canUseLocalStorage()?localStorage.getItem(e):{}}set(e,t){const n=this._store.get(e)||{};t instanceof Map?this._store.set(e,t):this._store.set(e,Object.assign(Object.assign({},n),t))}setStorage(e,t){w?A?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)}},be="1.2.0";!function(e){e.INITIAL="INITIAL",e.DEFAULT="DEFAULT",e.BACKUP="BACKUP",e.ANYCAST="ANYCAST"}(De||(De={}));let we=De.INITIAL;function Le(){const e=Math.random();return 0===e?Le():e}function ke(e,t){const{isBinary:n=!1}=t||{},s=Re.get("instance"),{sdkAppId:i,instanceId:o}=s,r=Le(),a=oe(),c=function(){const e=oe();let t=-1;"ios"===e?t=j||-1:"android"===e&&(t=W||-1);return t}(),l=(d={sdkappid:i,instanceid:o,random:r,platform:x,host:a,version:c,sdkversion:be},Object.keys(d).map((e=>`${e}=${d[e]}`)).join("&"));var d;return n?`${e}/binfo?${l}&compress=gzip`:`${e}/info?${l}`}var Pe=new class{constructor(){this._timeOffsetWithServer=0}getServerTimeMs(){return Date.now()+this._timeOffsetWithServer}getServerTimeSeconds(){return Math.floor(this.getServerTimeMs()/1e3)}getTimeOffsetWithServer(){return this._timeOffsetWithServer}calculateTimeOffsetWithServer(e,t){const n=Date.now(),s=n-e;this._timeOffsetWithServer=t+s-n}};const Ue=16;var Fe=new class{constructor(){this._tasks=[],this._timer=null,this._taskMap=new Map}_addTaskToScheduler(e){const{id:t}=e;this.removeTask(t),this._tasks.push(e),this._taskMap.set(t,e),this._sort(),this._scheduleNextTask()}_createTask(e){const{id:t,callback:n,context:s,isOnce:i=!1,intervalMs:o=Ue}=e,r=Math.max(o,Ue);return{id:t,nextExecuteTime:Date.now()+r,intervalMs:o,callback:n,context:s,isOnce:i}}addTask(e){const t=this._createTask(e);this._addTaskToScheduler(t)}addOnceTask(e){const t=this._createTask(Object.assign(Object.assign({},e),{isOnce:!0}));this._addTaskToScheduler(t)}removeTask(e){const t=this._tasks.findIndex((t=>t.id===e));t>-1&&(this._tasks.splice(t,1),this._taskMap.delete(e),this._scheduleNextTask())}updateTaskInterval(e,t){const n=this._taskMap.get(e);n&&(n.intervalMs=t,n.nextExecuteTime=Date.now()+t,this._sort(),this._scheduleNextTask())}clearAllTasks(){this._tasks=[],this._taskMap.clear(),this._timer&&(clearTimeout(this._timer),this._timer=null)}dispose(){this.clearAllTasks()}_sort(){this._tasks.sort(((e,t)=>e.nextExecuteTime-t.nextExecuteTime))}_scheduleNextTask(){this._timer&&(clearTimeout(this._timer),this._timer=null);const e=this._tasks[0];if(e){const t=Math.max(0,e.nextExecuteTime-Date.now());this._timer=setTimeout((()=>this._execute()),t)}}_execute(){const e=Date.now();for(;this._tasks.length&&this._tasks[0].nextExecuteTime<=e;){const t=this._tasks[0];try{t.context?t.callback.call(t.context):t.callback(),t.isOnce?this.removeTask(t.id):(t.nextExecuteTime=e+t.intervalMs,this._sort())}catch(e){console.warn(`Task ${t.id} execution failed:`,e),t.isOnce&&this.removeTask(t.id)}}this._scheduleNextTask()}};function Ge(e){const t=[];for(let n=0;n<e.length;n+=1){const s=e.charCodeAt(n);if(s>=55296&&s<=56319){const i=e.charCodeAt(++n)-56320+(s-55296<<10)+65536;t.push(240|i>>18,128|i>>12&63,128|i>>6&63,128|63&i)}else s<=127?t.push(s):s<=2047?t.push(192|s>>6,128|63&s):t.push(224|s>>12,128|s>>6&63,128|63&s)}return new Uint8Array(t)}function xe(e){const t=Array.isArray(e)?[]:Object.create(null);for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&g(n)&&null!=e[n]&&(null===e[n]||"object"!=typeof e[n]?t[n]=e[n]:t[n]=xe(e[n]));return t}function Be(e,t){if(v.includes(e))return 0;const n=Ge(JSON.stringify(t));let s=4294967295;const{length:i}=n;for(let e=0;e<i;e++){s^=n[e];for(let e=0;e<8;e++)1&~s?s>>>=1:s=s>>>1^3988292384}return(4294967295^s)>>>0}function $e(e){const{servcmd:t,data:n}=e,s=function(e){const t=Re.get("login")||{},n=Re.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:n.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:t.a2Key?void 0:t.userId,usersig:t.a2Key?void 0:t.userSig,sdkability:75689843,sdkability_ext:S(""),cappid:t.cappid||0,tjgID:"",seq:je(),cs:0}}(t),i=xe(n);return s.cs=Be(t,i),{head:s,body:i}}function Ve(e){const{servcmd:t,data:n}=e,s=function(e){const t=Re.get("login")||{},n=Re.get("instance")||{};return{servcmd:e,ver:"v4",platform:x,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:n.sdkAppId,contenttype:"",reqtime:Math.floor(Date.now()/1e3),identifier:"",usersig:"",status_instid:t.statusInstanceId||0,sdkability:75689843,sdkability_ext:S(""),cappid:t.cappid||0,seq:je(),cs:0}}(t),i=xe(n);return s.cs=Be(t,i),{head:s,body:i}}let qe=E();function je(){return qe=qe<2415919103?qe+1:E(),qe}var Ye,We=Object.freeze({__proto__:null,generateCosSpecifiedData:function(e){const{servcmd:t,data:n}=e,s=function(e){const t=Re.get("login")||{},n=Re.get("instance")||{};return{servcmd:e,ver:"v4",platform:x,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:n.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:t.userId,usersig:t.userSig,status_instid:t.statusInstanceId||0,sdkability:75689843,sdkability_ext:S(""),cappid:t.cappid||0,seq:je(),cs:0}}(t),i=xe(n);return s.cs=Be(t,i),{head:s,body:i}},generateProtocolData:$e,generateSSOLogProtocolData:Ve,generateSequence:je,taskScheduler:Fe,timeManager:Pe});!function(e){e[e.info=4]="info",e[e.warning=5]="warning",e[e.error=6]="error"}(Ye||(Ye={}));const Ke={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 He{constructor(e){this.level=Ye.info,this._canSendLog=!0,this._logCreatedAt=Pe.getServerTimeMs(),this.timestamp=0,this.networkType=8,this.code=0,this.moreMessage="",this.method="",this.message="",this.costTime=0,this.duplicate=!1,this.eventType=0,this.uiPlatform=void 0;const{method:t,eventType:n=0}=e||{};this.eventType=n,this.method=t}setMoreMessage(e){this.moreMessage=`${this.moreMessage} ${e}`}updateLogCreatedAtByTimeOffset(){this._logCreatedAt+=Pe.getTimeOffsetWithServer()}end(e=!1){if(!this._canSendLog)return;const t=Pe.getServerTimeMs();0===this.costTime&&(this.costTime=t-this._logCreatedAt),this.setMoreMessage(`startts:${this._logCreatedAt} endts:${t}`),e?(this._canSendLog=!1,this.timestamp=Pe.getServerTimeMs(),this._ssoLogModule.pushToLogQueue(this._convertSSOLogDataKeyToServe())):setTimeout((()=>{this._canSendLog=!1,this.timestamp=Pe.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=Re.get("netWorkMonitor"))||void 0===t?void 0:t.isNetworkOnline)&&(e.errorCode&&(this.code=e.errorCode),e.errorMessage&&this.setMoreMessage(e.errorMessage)),this.level=Ye.error,this}setLogInfo(e){return Object.keys(e).forEach((t=>{Object.keys(Ke).includes(t)&&(this[t]=e[t])})),this}setSSOLogModule(e){this._ssoLogModule=e}_convertSSOLogDataKeyToServe(){const e={};return Object.keys(this).forEach((t=>{const n=t;Ke[n]&&(e[Ke[n]]=this[n])})),e}}var ze;function Je(){const e=Re.get("login")||{},t=Re.get("instance")||{};return{sdk_type:30,sdk_app_id:t.sdkAppId,sdk_version:"1.2.0",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"}(ze||(ze={}));var Ze=ze;const Xe=20,Qe=6e4,et=[4,5,6],nt=[],st=[],it="report-logger";var ot=new class{constructor(){this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._reportLevel=[4,5,6],this._minThreshold=Xe,this._maxThreshold=100,this._waitingTime=Qe,this._lastReportAt=Date.now(),this._ssoLogMap=new Map,o.subscribeInnerEvent(Ze.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),Fe.addTask({id:it,intervalMs:1e3,callback:this._checkAndReportIfDue,context:this}),this._logQueue=[],this._savePlatFormInfo()}_handleCloudConfigUpdate(e){const{evt_rpt_threshold:t=Xe,evt_rpt_waiting:n=Qe,evt_rpt_level:s=et,evt_rpt_sdkappid_bl:i=nt,evt_rpt_tinyid_wl:o=st}=e||{};this._sdkAppIdBlackList=i,this._waitingTime=n,this._minThreshold=t,this._reportLevel=s,this._tinyIdWhiteList=o}createSSOLogData(e){const t=new He(e);return t.setSSOLogModule(this),this._ssoLogMap.set(e.method,t),t}getSSOLogData(e){return this._ssoLogMap.get(e)||{}}pushToLogQueue(e){e&&(this._logQueue.push(e),this._shouldUploadImmediately()&&this._uploadSSOLogData())}_shouldUploadImmediately(){return this._logQueue.length>=this._minThreshold}_isReportDue(){return Date.now()>=this._lastReportAt+this._waitingTime}_checkAndReportIfDue(){this._isReportDue()&&this._logQueue.length>0&&this._uploadSSOLogData()}_uploadSSOLogData(){return a(this,void 0,void 0,(function*(){if(0===this._logQueue.length)return;const e=this._logQueue.slice(),t=this._filterLogs(e);if(this._logQueue=[],0===t.length)return void(this._lastReportAt=Date.now());const n={Header:Je(),Event:t};yield function(e){const t="imopenstat.tim_web_report_v2",n=Ve({servcmd:t,data:e}),s=`${n.head.seq}${t}`;Mt.sendPacket(n,{requestId:s})}(n),this._lastReportAt=Date.now()}))}_savePlatFormInfo(){var e,t;if(C){const n=null===(t=null===(e=wx.getAccountInfoSync)||void 0===e?void 0:e.call(wx))||void 0===t?void 0:t.miniProgram;if(n){const{appId:e,envVersion:t}=n;Re.set("instance",{appId:e,envVersion:t})}}else P&&Re.set("instance",{href:window.location.href})}_filterLogs(e){const{tinyID:t}=Re.get("login")||{},{sdkAppId:n}=Re.get("instance")||{};return this._sdkAppIdBlackList.includes(n)&&!this._tinyIdWhiteList.includes(t)?[]:e.filter((e=>this._reportLevel.includes(e.level)))}reset(){console.log("SSO_LOG_MODULE.reset"),Fe.removeTask(it),o.unSubscribeInnerEvent(Ze.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),this._lastReportAt=0,this._uploadSSOLogData(),this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._minThreshold=Xe,this._maxThreshold=100,this._waitingTime=Qe,this._logQueue=[]}};const rt=15e3,at="Channel",ct="channel_schedule_task",lt="channel_reconnect_task",dt="connected",ut="connecting",_t="disconnected",ht=500,gt="network_status_change",ft="activity_status_change",Et="send_fail",pt="reconnect_failed",St="socket_error",mt="socket_close";function vt(e){return vt="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},vt(e)}function It(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 Ct,yt={exports:{}};var Ot=(Ct||(Ct=1,yt.exports=function e(t,n,s){function i(r,a){if(!n[r]){if(!t[r]){if(!a&&It)return It(r);if(o)return o(r,!0);var c=new Error("Cannot find module '"+r+"'");throw c.code="MODULE_NOT_FOUND",c}var l=n[r]={exports:{}};t[r][0].call(l.exports,(function(e){return i(t[r][1][e]||e)}),l,l.exports,e,t,n,s)}return n[r].exports}for(var o=It,r=0;r<s.length;r++)i(s[r]);return i}({1:[function(e,t,n){var s="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;n.assign=function(e){for(var t,n,s=Array.prototype.slice.call(arguments,1);s.length;){var i=s.shift();if(i){if("object"!=vt(i))throw new TypeError(i+"must be non-object");for(var o in i)t=i,n=o,Object.prototype.hasOwnProperty.call(t,n)&&(e[o]=i[o])}}return e},n.shrinkBuf=function(e,t){return e.length===t?e:e.subarray?e.subarray(0,t):(e.length=t,e)};var i={arraySet:function(e,t,n,s,i){if(t.subarray&&e.subarray)e.set(t.subarray(n,n+s),i);else for(var o=0;o<s;o++)e[i+o]=t[n+o]},flattenChunks:function(e){var t,n,s,i,o,r;for(t=s=0,n=e.length;t<n;t++)s+=e[t].length;for(r=new Uint8Array(s),t=i=0,n=e.length;t<n;t++)o=e[t],r.set(o,i),i+=o.length;return r}},o={arraySet:function(e,t,n,s,i){for(var o=0;o<s;o++)e[i+o]=t[n+o]},flattenChunks:function(e){return[].concat.apply([],e)}};n.setTyped=function(e){e?(n.Buf8=Uint8Array,n.Buf16=Uint16Array,n.Buf32=Int32Array,n.assign(n,i)):(n.Buf8=Array,n.Buf16=Array,n.Buf32=Array,n.assign(n,o))},n.setTyped(s)},{}],2:[function(e,t,n){var s=e("./common"),i=!0,o=!0;try{String.fromCharCode.apply(null,[0])}catch(e){i=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(e){o=!1}for(var r=new s.Buf8(256),a=0;a<256;a++)r[a]=252<=a?6:248<=a?5:240<=a?4:224<=a?3:192<=a?2:1;function c(e,t){if(t<65534&&(e.subarray&&o||!e.subarray&&i))return String.fromCharCode.apply(null,s.shrinkBuf(e,t));for(var n="",r=0;r<t;r++)n+=String.fromCharCode(e[r]);return n}r[254]=r[254]=1,n.string2buf=function(e){var t,n,i,o,r,a=e.length,c=0;for(o=0;o<a;o++)55296==(64512&(n=e.charCodeAt(o)))&&o+1<a&&56320==(64512&(i=e.charCodeAt(o+1)))&&(n=65536+(n-55296<<10)+(i-56320),o++),c+=n<128?1:n<2048?2:n<65536?3:4;for(t=new s.Buf8(c),o=r=0;r<c;o++)55296==(64512&(n=e.charCodeAt(o)))&&o+1<a&&56320==(64512&(i=e.charCodeAt(o+1)))&&(n=65536+(n-55296<<10)+(i-56320),o++),n<128?t[r++]=n:(n<2048?t[r++]=192|n>>>6:(n<65536?t[r++]=224|n>>>12:(t[r++]=240|n>>>18,t[r++]=128|n>>>12&63),t[r++]=128|n>>>6&63),t[r++]=128|63&n);return t},n.buf2binstring=function(e){return c(e,e.length)},n.binstring2buf=function(e){for(var t=new s.Buf8(e.length),n=0,i=t.length;n<i;n++)t[n]=e.charCodeAt(n);return t},n.buf2string=function(e,t){var n,s,i,o,a=t||e.length,l=new Array(2*a);for(n=s=0;n<a;)if((i=e[n++])<128)l[s++]=i;else if(4<(o=r[i]))l[s++]=65533,n+=o-1;else{for(i&=2===o?31:3===o?15:7;1<o&&n<a;)i=i<<6|63&e[n++],o--;1<o?l[s++]=65533:i<65536?l[s++]=i:(i-=65536,l[s++]=55296|i>>10&1023,l[s++]=56320|1023&i)}return c(l,s)},n.utf8border=function(e,t){var n;for((t=t||e.length)>e.length&&(t=e.length),n=t-1;0<=n&&128==(192&e[n]);)n--;return n<0||0===n?t:n+r[e[n]]>t?n:t}},{"./common":1}],3:[function(e,t,n){t.exports=function(e,t,n,s){for(var i=65535&e,o=e>>>16&65535,r=0;0!==n;){for(n-=r=2e3<n?2e3:n;o=o+(i=i+t[s++]|0)|0,--r;);i%=65521,o%=65521}return i|o<<16}},{}],4:[function(e,t,n){t.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],5:[function(e,t,n){var s=function(){for(var e,t=[],n=0;n<256;n++){e=n;for(var s=0;s<8;s++)e=1&e?3988292384^e>>>1:e>>>1;t[n]=e}return t}();t.exports=function(e,t,n,i){var o=s,r=i+n;e^=-1;for(var a=i;a<r;a++)e=e>>>8^o[255&(e^t[a])];return~e}},{}],6:[function(e,t,n){t.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],7:[function(e,t,n){t.exports=function(e,t){var n,s,i,o,r,a,c,l,d,u,_,h,g,f,E,p,S,m,v,I,C,y,O,M,T;n=e.state,s=e.next_in,M=e.input,i=s+(e.avail_in-5),o=e.next_out,T=e.output,r=o-(t-e.avail_out),a=o+(e.avail_out-257),c=n.dmax,l=n.wsize,d=n.whave,u=n.wnext,_=n.window,h=n.hold,g=n.bits,f=n.lencode,E=n.distcode,p=(1<<n.lenbits)-1,S=(1<<n.distbits)-1;e:do{g<15&&(h+=M[s++]<<g,g+=8,h+=M[s++]<<g,g+=8),m=f[h&p];t:for(;;){if(h>>>=v=m>>>24,g-=v,0==(v=m>>>16&255))T[o++]=65535&m;else{if(!(16&v)){if(!(64&v)){m=f[(65535&m)+(h&(1<<v)-1)];continue t}if(32&v){n.mode=12;break e}e.msg="invalid literal/length code",n.mode=30;break e}I=65535&m,(v&=15)&&(g<v&&(h+=M[s++]<<g,g+=8),I+=h&(1<<v)-1,h>>>=v,g-=v),g<15&&(h+=M[s++]<<g,g+=8,h+=M[s++]<<g,g+=8),m=E[h&S];n:for(;;){if(h>>>=v=m>>>24,g-=v,!(16&(v=m>>>16&255))){if(!(64&v)){m=E[(65535&m)+(h&(1<<v)-1)];continue n}e.msg="invalid distance code",n.mode=30;break e}if(C=65535&m,g<(v&=15)&&(h+=M[s++]<<g,(g+=8)<v&&(h+=M[s++]<<g,g+=8)),c<(C+=h&(1<<v)-1)){e.msg="invalid distance too far back",n.mode=30;break e}if(h>>>=v,g-=v,(v=o-r)<C){if(d<(v=C-v)&&n.sane){e.msg="invalid distance too far back",n.mode=30;break e}if(O=_,(y=0)===u){if(y+=l-v,v<I){for(I-=v;T[o++]=_[y++],--v;);y=o-C,O=T}}else if(u<v){if(y+=l+u-v,(v-=u)<I){for(I-=v;T[o++]=_[y++],--v;);if(y=0,u<I){for(I-=v=u;T[o++]=_[y++],--v;);y=o-C,O=T}}}else if(y+=u-v,v<I){for(I-=v;T[o++]=_[y++],--v;);y=o-C,O=T}for(;2<I;)T[o++]=O[y++],T[o++]=O[y++],T[o++]=O[y++],I-=3;I&&(T[o++]=O[y++],1<I&&(T[o++]=O[y++]))}else{for(y=o-C;T[o++]=T[y++],T[o++]=T[y++],T[o++]=T[y++],2<(I-=3););I&&(T[o++]=T[y++],1<I&&(T[o++]=T[y++]))}break}}break}}while(s<i&&o<a);s-=I=g>>3,h&=(1<<(g-=I<<3))-1,e.next_in=s,e.next_out=o,e.avail_in=s<i?i-s+5:5-(s-i),e.avail_out=o<a?a-o+257:257-(o-a),n.hold=h,n.bits=g}},{}],8:[function(e,t,n){var s=e("../utils/common"),i=e("./adler32"),o=e("./crc32"),r=e("./inffast"),a=e("./inftrees"),c=1,l=2,d=0,u=-2,_=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 s.Buf16(320),this.work=new s.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function 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 s.Buf32(h),t.distcode=t.distdyn=new s.Buf32(g),t.sane=1,t.back=-1,d):u}function S(e){var t;return e&&e.state?((t=e.state).wsize=0,t.whave=0,t.wnext=0,p(e)):u}function m(e,t){var n,s;return e&&e.state?(s=e.state,t<0?(n=0,t=-t):(n=1+(t>>4),t<48&&(t&=15)),t&&(t<8||15<t)?u:(null!==s.window&&s.wbits!==t&&(s.window=null),s.wrap=n,s.wbits=t,S(e))):u}function v(e,t){var n,s;return e?(s=new E,(e.state=s).window=null,(n=m(e,t))!==d&&(e.state=null),n):u}var I,C,y=!0;function O(e){if(y){var t;for(I=new s.Buf32(512),C=new s.Buf32(32),t=0;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(a(c,e.lens,0,288,I,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;a(l,e.lens,0,32,C,0,e.work,{bits:5}),y=!1}e.lencode=I,e.lenbits=9,e.distcode=C,e.distbits=5}function M(e,t,n,i){var o,r=e.state;return null===r.window&&(r.wsize=1<<r.wbits,r.wnext=0,r.whave=0,r.window=new s.Buf8(r.wsize)),i>=r.wsize?(s.arraySet(r.window,t,n-r.wsize,r.wsize,0),r.wnext=0,r.whave=r.wsize):(i<(o=r.wsize-r.wnext)&&(o=i),s.arraySet(r.window,t,n-i,o,r.wnext),(i-=o)?(s.arraySet(r.window,t,n-i,i,0),r.wnext=i,r.whave=r.wsize):(r.wnext+=o,r.wnext===r.wsize&&(r.wnext=0),r.whave<r.wsize&&(r.whave+=o))),0}n.inflateReset=S,n.inflateReset2=m,n.inflateResetKeep=p,n.inflateInit=function(e){return v(e,15)},n.inflateInit2=v,n.inflate=function(e,t){var n,h,g,E,p,S,m,v,I,C,y,T,A,N,D,R,b,w,L,k,P,U,F,G,x=0,B=new s.Buf8(4),$=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!e||!e.state||!e.output||!e.input&&0!==e.avail_in)return u;12===(n=e.state).mode&&(n.mode=13),p=e.next_out,g=e.output,m=e.avail_out,E=e.next_in,h=e.input,S=e.avail_in,v=n.hold,I=n.bits,C=S,y=m,U=d;e:for(;;)switch(n.mode){case _:if(0===n.wrap){n.mode=13;break}for(;I<16;){if(0===S)break e;S--,v+=h[E++]<<I,I+=8}if(2&n.wrap&&35615===v){B[n.check=0]=255&v,B[1]=v>>>8&255,n.check=o(n.check,B,2,0),I=v=0,n.mode=2;break}if(n.flags=0,n.head&&(n.head.done=!1),!(1&n.wrap)||(((255&v)<<8)+(v>>8))%31){e.msg="incorrect header check",n.mode=30;break}if(8!=(15&v)){e.msg="unknown compression method",n.mode=30;break}if(I-=4,P=8+(15&(v>>>=4)),0===n.wbits)n.wbits=P;else if(P>n.wbits){e.msg="invalid window size",n.mode=30;break}n.dmax=1<<P,e.adler=n.check=1,n.mode=512&v?10:12,I=v=0;break;case 2:for(;I<16;){if(0===S)break e;S--,v+=h[E++]<<I,I+=8}if(n.flags=v,8!=(255&n.flags)){e.msg="unknown compression method",n.mode=30;break}if(57344&n.flags){e.msg="unknown header flags set",n.mode=30;break}n.head&&(n.head.text=v>>8&1),512&n.flags&&(B[0]=255&v,B[1]=v>>>8&255,n.check=o(n.check,B,2,0)),I=v=0,n.mode=3;case 3:for(;I<32;){if(0===S)break e;S--,v+=h[E++]<<I,I+=8}n.head&&(n.head.time=v),512&n.flags&&(B[0]=255&v,B[1]=v>>>8&255,B[2]=v>>>16&255,B[3]=v>>>24&255,n.check=o(n.check,B,4,0)),I=v=0,n.mode=4;case 4:for(;I<16;){if(0===S)break e;S--,v+=h[E++]<<I,I+=8}n.head&&(n.head.xflags=255&v,n.head.os=v>>8),512&n.flags&&(B[0]=255&v,B[1]=v>>>8&255,n.check=o(n.check,B,2,0)),I=v=0,n.mode=5;case 5:if(1024&n.flags){for(;I<16;){if(0===S)break e;S--,v+=h[E++]<<I,I+=8}n.length=v,n.head&&(n.head.extra_len=v),512&n.flags&&(B[0]=255&v,B[1]=v>>>8&255,n.check=o(n.check,B,2,0)),I=v=0}else n.head&&(n.head.extra=null);n.mode=6;case 6:if(1024&n.flags&&(S<(T=n.length)&&(T=S),T&&(n.head&&(P=n.head.extra_len-n.length,n.head.extra||(n.head.extra=new Array(n.head.extra_len)),s.arraySet(n.head.extra,h,E,T,P)),512&n.flags&&(n.check=o(n.check,h,T,E)),S-=T,E+=T,n.length-=T),n.length))break e;n.length=0,n.mode=7;case 7:if(2048&n.flags){if(0===S)break e;for(T=0;P=h[E+T++],n.head&&P&&n.length<65536&&(n.head.name+=String.fromCharCode(P)),P&&T<S;);if(512&n.flags&&(n.check=o(n.check,h,T,E)),S-=T,E+=T,P)break e}else n.head&&(n.head.name=null);n.length=0,n.mode=8;case 8:if(4096&n.flags){if(0===S)break e;for(T=0;P=h[E+T++],n.head&&P&&n.length<65536&&(n.head.comment+=String.fromCharCode(P)),P&&T<S;);if(512&n.flags&&(n.check=o(n.check,h,T,E)),S-=T,E+=T,P)break e}else n.head&&(n.head.comment=null);n.mode=9;case 9:if(512&n.flags){for(;I<16;){if(0===S)break e;S--,v+=h[E++]<<I,I+=8}if(v!==(65535&n.check)){e.msg="header crc mismatch",n.mode=30;break}I=v=0}n.head&&(n.head.hcrc=n.flags>>9&1,n.head.done=!0),e.adler=n.check=0,n.mode=12;break;case 10:for(;I<32;){if(0===S)break e;S--,v+=h[E++]<<I,I+=8}e.adler=n.check=f(v),I=v=0,n.mode=11;case 11:if(0===n.havedict)return e.next_out=p,e.avail_out=m,e.next_in=E,e.avail_in=S,n.hold=v,n.bits=I,2;e.adler=n.check=1,n.mode=12;case 12:if(5===t||6===t)break e;case 13:if(n.last){v>>>=7&I,I-=7&I,n.mode=27;break}for(;I<3;){if(0===S)break e;S--,v+=h[E++]<<I,I+=8}switch(n.last=1&v,I-=1,3&(v>>>=1)){case 0:n.mode=14;break;case 1:if(O(n),n.mode=20,6!==t)break;v>>>=2,I-=2;break e;case 2:n.mode=17;break;case 3:e.msg="invalid block type",n.mode=30}v>>>=2,I-=2;break;case 14:for(v>>>=7&I,I-=7&I;I<32;){if(0===S)break e;S--,v+=h[E++]<<I,I+=8}if((65535&v)!=(v>>>16^65535)){e.msg="invalid stored block lengths",n.mode=30;break}if(n.length=65535&v,I=v=0,n.mode=15,6===t)break e;case 15:n.mode=16;case 16:if(T=n.length){if(S<T&&(T=S),m<T&&(T=m),0===T)break e;s.arraySet(g,h,E,T,p),S-=T,E+=T,m-=T,p+=T,n.length-=T;break}n.mode=12;break;case 17:for(;I<14;){if(0===S)break e;S--,v+=h[E++]<<I,I+=8}if(n.nlen=257+(31&v),v>>>=5,I-=5,n.ndist=1+(31&v),v>>>=5,I-=5,n.ncode=4+(15&v),v>>>=4,I-=4,286<n.nlen||30<n.ndist){e.msg="too many length or distance symbols",n.mode=30;break}n.have=0,n.mode=18;case 18:for(;n.have<n.ncode;){for(;I<3;){if(0===S)break e;S--,v+=h[E++]<<I,I+=8}n.lens[$[n.have++]]=7&v,v>>>=3,I-=3}for(;n.have<19;)n.lens[$[n.have++]]=0;if(n.lencode=n.lendyn,n.lenbits=7,F={bits:n.lenbits},U=a(0,n.lens,0,19,n.lencode,0,n.work,F),n.lenbits=F.bits,U){e.msg="invalid code lengths set",n.mode=30;break}n.have=0,n.mode=19;case 19:for(;n.have<n.nlen+n.ndist;){for(;R=(x=n.lencode[v&(1<<n.lenbits)-1])>>>16&255,b=65535&x,!((D=x>>>24)<=I);){if(0===S)break e;S--,v+=h[E++]<<I,I+=8}if(b<16)v>>>=D,I-=D,n.lens[n.have++]=b;else{if(16===b){for(G=D+2;I<G;){if(0===S)break e;S--,v+=h[E++]<<I,I+=8}if(v>>>=D,I-=D,0===n.have){e.msg="invalid bit length repeat",n.mode=30;break}P=n.lens[n.have-1],T=3+(3&v),v>>>=2,I-=2}else if(17===b){for(G=D+3;I<G;){if(0===S)break e;S--,v+=h[E++]<<I,I+=8}I-=D,P=0,T=3+(7&(v>>>=D)),v>>>=3,I-=3}else{for(G=D+7;I<G;){if(0===S)break e;S--,v+=h[E++]<<I,I+=8}I-=D,P=0,T=11+(127&(v>>>=D)),v>>>=7,I-=7}if(n.have+T>n.nlen+n.ndist){e.msg="invalid bit length repeat",n.mode=30;break}for(;T--;)n.lens[n.have++]=P}}if(30===n.mode)break;if(0===n.lens[256]){e.msg="invalid code -- missing end-of-block",n.mode=30;break}if(n.lenbits=9,F={bits:n.lenbits},U=a(c,n.lens,0,n.nlen,n.lencode,0,n.work,F),n.lenbits=F.bits,U){e.msg="invalid literal/lengths set",n.mode=30;break}if(n.distbits=6,n.distcode=n.distdyn,F={bits:n.distbits},U=a(l,n.lens,n.nlen,n.ndist,n.distcode,0,n.work,F),n.distbits=F.bits,U){e.msg="invalid distances set",n.mode=30;break}if(n.mode=20,6===t)break e;case 20:n.mode=21;case 21:if(6<=S&&258<=m){e.next_out=p,e.avail_out=m,e.next_in=E,e.avail_in=S,n.hold=v,n.bits=I,r(e,y),p=e.next_out,g=e.output,m=e.avail_out,E=e.next_in,h=e.input,S=e.avail_in,v=n.hold,I=n.bits,12===n.mode&&(n.back=-1);break}for(n.back=0;R=(x=n.lencode[v&(1<<n.lenbits)-1])>>>16&255,b=65535&x,!((D=x>>>24)<=I);){if(0===S)break e;S--,v+=h[E++]<<I,I+=8}if(R&&!(240&R)){for(w=D,L=R,k=b;R=(x=n.lencode[k+((v&(1<<w+L)-1)>>w)])>>>16&255,b=65535&x,!(w+(D=x>>>24)<=I);){if(0===S)break e;S--,v+=h[E++]<<I,I+=8}v>>>=w,I-=w,n.back+=w}if(v>>>=D,I-=D,n.back+=D,n.length=b,0===R){n.mode=26;break}if(32&R){n.back=-1,n.mode=12;break}if(64&R){e.msg="invalid literal/length code",n.mode=30;break}n.extra=15&R,n.mode=22;case 22:if(n.extra){for(G=n.extra;I<G;){if(0===S)break e;S--,v+=h[E++]<<I,I+=8}n.length+=v&(1<<n.extra)-1,v>>>=n.extra,I-=n.extra,n.back+=n.extra}n.was=n.length,n.mode=23;case 23:for(;R=(x=n.distcode[v&(1<<n.distbits)-1])>>>16&255,b=65535&x,!((D=x>>>24)<=I);){if(0===S)break e;S--,v+=h[E++]<<I,I+=8}if(!(240&R)){for(w=D,L=R,k=b;R=(x=n.distcode[k+((v&(1<<w+L)-1)>>w)])>>>16&255,b=65535&x,!(w+(D=x>>>24)<=I);){if(0===S)break e;S--,v+=h[E++]<<I,I+=8}v>>>=w,I-=w,n.back+=w}if(v>>>=D,I-=D,n.back+=D,64&R){e.msg="invalid distance code",n.mode=30;break}n.offset=b,n.extra=15&R,n.mode=24;case 24:if(n.extra){for(G=n.extra;I<G;){if(0===S)break e;S--,v+=h[E++]<<I,I+=8}n.offset+=v&(1<<n.extra)-1,v>>>=n.extra,I-=n.extra,n.back+=n.extra}if(n.offset>n.dmax){e.msg="invalid distance too far back",n.mode=30;break}n.mode=25;case 25:if(0===m)break e;if(T=y-m,n.offset>T){if((T=n.offset-T)>n.whave&&n.sane){e.msg="invalid distance too far back",n.mode=30;break}T>n.wnext?(T-=n.wnext,A=n.wsize-T):A=n.wnext-T,T>n.length&&(T=n.length),N=n.window}else N=g,A=p-n.offset,T=n.length;for(m<T&&(T=m),m-=T,n.length-=T;g[p++]=N[A++],--T;);0===n.length&&(n.mode=21);break;case 26:if(0===m)break e;g[p++]=n.length,m--,n.mode=21;break;case 27:if(n.wrap){for(;I<32;){if(0===S)break e;S--,v|=h[E++]<<I,I+=8}if(y-=m,e.total_out+=y,n.total+=y,y&&(e.adler=n.check=n.flags?o(n.check,g,y,p-y):i(n.check,g,y,p-y)),y=m,(n.flags?v:f(v))!==n.check){e.msg="incorrect data check",n.mode=30;break}I=v=0}n.mode=28;case 28:if(n.wrap&&n.flags){for(;I<32;){if(0===S)break e;S--,v+=h[E++]<<I,I+=8}if(v!==(4294967295&n.total)){e.msg="incorrect length check",n.mode=30;break}I=v=0}n.mode=29;case 29:U=1;break e;case 30:U=-3;break e;case 31:return-4;default:return u}return e.next_out=p,e.avail_out=m,e.next_in=E,e.avail_in=S,n.hold=v,n.bits=I,(n.wsize||y!==e.avail_out&&n.mode<30&&(n.mode<27||4!==t))&&M(e,e.output,e.next_out,y-e.avail_out)?(n.mode=31,-4):(C-=e.avail_in,y-=e.avail_out,e.total_in+=C,e.total_out+=y,n.total+=y,n.wrap&&y&&(e.adler=n.check=n.flags?o(n.check,g,y,e.next_out-y):i(n.check,g,y,e.next_out-y)),e.data_type=n.bits+(n.last?64:0)+(12===n.mode?128:0)+(20===n.mode||15===n.mode?256:0),(0===C&&0===y||4===t)&&U===d&&(U=-5),U)},n.inflateEnd=function(e){if(!e||!e.state)return u;var t=e.state;return t.window&&(t.window=null),e.state=null,d},n.inflateGetHeader=function(e,t){var n;return e&&e.state&&2&(n=e.state).wrap?((n.head=t).done=!1,d):u},n.inflateSetDictionary=function(e,t){var n,s=t.length;return e&&e.state?0!==(n=e.state).wrap&&11!==n.mode?u:11===n.mode&&i(1,t,s,0)!==n.check?-3:M(e,t,s,s)?(n.mode=31,-4):(n.havedict=1,d):u},n.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":1,"./adler32":3,"./crc32":5,"./inffast":7,"./inftrees":9}],9:[function(e,t,n){var s=e("../utils/common"),i=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],o=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],r=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],a=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];t.exports=function(e,t,n,c,l,d,u,_){var h,g,f,E,p,S,m,v,I,C=_.bits,y=0,O=0,M=0,T=0,A=0,N=0,D=0,R=0,b=0,w=0,L=null,k=0,P=new s.Buf16(16),U=new s.Buf16(16),F=null,G=0;for(y=0;y<=15;y++)P[y]=0;for(O=0;O<c;O++)P[t[n+O]]++;for(A=C,T=15;1<=T&&0===P[T];T--);if(T<A&&(A=T),0===T)return l[d++]=20971520,l[d++]=20971520,_.bits=1,0;for(M=1;M<T&&0===P[M];M++);for(A<M&&(A=M),y=R=1;y<=15;y++)if(R<<=1,(R-=P[y])<0)return-1;if(0<R&&(0===e||1!==T))return-1;for(U[1]=0,y=1;y<15;y++)U[y+1]=U[y]+P[y];for(O=0;O<c;O++)0!==t[n+O]&&(u[U[t[n+O]]++]=O);if(0===e?(L=F=u,S=19):1===e?(L=i,k-=257,F=o,G-=257,S=256):(L=r,F=a,S=-1),y=M,p=d,D=O=w=0,f=-1,E=(b=1<<(N=A))-1,1===e&&852<b||2===e&&592<b)return 1;for(;;){for(m=y-D,u[O]<S?(v=0,I=u[O]):u[O]>S?(v=F[G+u[O]],I=L[k+u[O]]):(v=96,I=0),h=1<<y-D,M=g=1<<N;l[p+(w>>D)+(g-=h)]=m<<24|v<<16|I,0!==g;);for(h=1<<y-1;w&h;)h>>=1;if(0!==h?(w&=h-1,w+=h):w=0,O++,0==--P[y]){if(y===T)break;y=t[n+u[O]]}if(A<y&&(w&E)!==f){for(0===D&&(D=A),p+=M,R=1<<(N=y-D);N+D<T&&!((R-=P[N+D])<=0);)N++,R<<=1;if(b+=1<<N,1===e&&852<b||2===e&&592<b)return 1;l[f=w&E]=A<<24|N<<16|p-d}}return 0!==w&&(l[p+w]=y-D<<24|64<<16),_.bits=A,0}},{"../utils/common":1}],10:[function(e,t,n){t.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],11:[function(e,t,n){t.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],"/lib/inflate.js":[function(e,t,n){var s=e("./zlib/inflate"),i=e("./utils/common"),o=e("./utils/strings"),r=e("./zlib/constants"),a=e("./zlib/messages"),c=e("./zlib/zstream"),l=e("./zlib/gzheader"),d=Object.prototype.toString;function u(e){if(!(this instanceof u))return new u(e);this.options=i.assign({chunkSize:16384,windowBits:0,to:""},e||{});var t=this.options;t.raw&&0<=t.windowBits&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(0<=t.windowBits&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),15<t.windowBits&&t.windowBits<48&&!(15&t.windowBits)&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new c,this.strm.avail_out=0;var n=s.inflateInit2(this.strm,t.windowBits);if(n!==r.Z_OK)throw new Error(a[n]);if(this.header=new l,s.inflateGetHeader(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=o.string2buf(t.dictionary):"[object ArrayBuffer]"===d.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(n=s.inflateSetDictionary(this.strm,t.dictionary))!==r.Z_OK))throw new Error(a[n])}function _(e,t){var n=new u(t);if(n.push(e,!0),n.err)throw n.msg||a[n.err];return n.result}u.prototype.push=function(e,t){var n,a,c,l,u,_=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=o.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 i.Buf8(h),_.next_out=0,_.avail_out=h),(n=s.inflate(_,r.Z_NO_FLUSH))===r.Z_NEED_DICT&&g&&(n=s.inflateSetDictionary(this.strm,g)),n===r.Z_BUF_ERROR&&!0===f&&(n=r.Z_OK,f=!1),n!==r.Z_STREAM_END&&n!==r.Z_OK)return this.onEnd(n),!(this.ended=!0);_.next_out&&(0!==_.avail_out&&n!==r.Z_STREAM_END&&(0!==_.avail_in||a!==r.Z_FINISH&&a!==r.Z_SYNC_FLUSH)||("string"===this.options.to?(c=o.utf8border(_.output,_.next_out),l=_.next_out-c,u=o.buf2string(_.output,c),_.next_out=l,_.avail_out=h-l,l&&i.arraySet(_.output,_.output,c,l,0),this.onData(u)):this.onData(i.shrinkBuf(_.output,_.next_out)))),0===_.avail_in&&0===_.avail_out&&(f=!0)}while((0<_.avail_in||0===_.avail_out)&&n!==r.Z_STREAM_END);return n===r.Z_STREAM_END&&(a=r.Z_FINISH),a===r.Z_FINISH?(n=s.inflateEnd(this.strm),this.onEnd(n),this.ended=!0,n===r.Z_OK):a!==r.Z_SYNC_FLUSH||(this.onEnd(r.Z_OK),!(_.avail_out=0))},u.prototype.onData=function(e){this.chunks.push(e)},u.prototype.onEnd=function(e){e===r.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=i.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg},n.Inflate=u,n.inflate=_,n.inflateRaw=function(e,t){return(t=t||{}).raw=!0,_(e,t)},n.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")),yt.exports);var Mt=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=ht,this._currentConnectState=dt,this._beforeSendInterceptors=[]}init(){Fe.addTask({id:ct,intervalMs:1e3,callback:this._executeScheduledTaskIfReady,context:this}),this._updateIsBinarySupported(),this._url=function(e){const t=Re.get("instance"),{sdkAppId:n,testEnv:s}=t,i=Ne(n);return ke(s?Te.TEST[i].DEFAULT:Te.PRODUCTION[i].INITIAL.replace("*",`${n}`),{isBinary:e})}(this._isBinarySupported),o.subscribeInnerEvent("networkStatusChange",this._handleNetworkStatusChange,this),o.subscribeInnerEvent("activityStatusChange",this._handleActivityStatusChange,this),this.connect()}sendPacket(e,t){var n;const{requestId:s,timeout:i=rt,canResend:o=!0}=t||{};if(ue(e))return console.warn(`${at}.sendPacket: packet is empty `,e),null;this._executeBeforeSendInterceptors(e);const r=JSON.stringify(e);let a=null;if(s){const{resolve:e,reject:t,promise:n}=_e();a=n,this._pendingRequests.set(s,{resolve:e,reject:t,timestamp:Date.now(),uplinkData:r,timeout:i,canResend:o})}const c=this._isBinarySupported?Ge(r).buffer:r;return null===(n=this._socketAdapter)||void 0===n||n.send(c),a}connect(){var e;this._socketAdapter=new pe(this._url),this._connectionEstablishedTime=0,this._addEventListeners(),this._connectionStartTime=Date.now();const t=null===(e=this._socketAdapter)||void 0===e?void 0:e.getId(),n=`${at}.connect isWorkerEnabled: false socketID:${t} url:${this._url}`;this._ssoLog({method:"connect",message:n}),console.log(n)}disconnect(){var e,t;const n=null===(e=this._socketAdapter)||void 0===e?void 0:e.getId(),s=`${at}.disconnect socketID:${n}`;this._ssoLog({method:"disconnect",message:s}),console.log(s),this._removeEventListeners(),null===(t=this._socketAdapter)||void 0===t||t.disconnect()}getSocketAdapter(){return this._socketAdapter}dispose(){console.log(`${at}.dispose`),Fe.removeTask(ct),Fe.removeTask(lt),o.unSubscribeInnerEvent("networkStatusChange",this._handleNetworkStatusChange,this),o.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=ht,this._url=""}registerBeforeSendInterceptor(e,t){this._beforeSendInterceptors.push(e.bind(t))}_executeBeforeSendInterceptors(e){for(const t of this._beforeSendInterceptors){const{servcmd:n=""}=null==e?void 0:e.head;t(n.includes(".")?n.split(".").pop():"")}}_shouldSkipReconnect(){const e=this._currentConnectState===ut&&this._isReconnecting;return!this._socketAdapter||e}reconnect(){return a(this,void 0,void 0,(function*(){const e=`${at} 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=Re.get("instance"),{sdkAppId:n,testEnv:s}=t,i=Ne(n);if(s)return ke(Te.TEST[i].DEFAULT,{isBinary:e});const o=Te.PRODUCTION[i],r=P&&o.ANYCAST;return ke({[De.INITIAL]:()=>(we=De.DEFAULT,o.DEFAULT),[De.DEFAULT]:()=>(we=De.BACKUP,o.BACKUP),[De.BACKUP]:()=>(we=r?De.ANYCAST:De.DEFAULT,r?o.ANYCAST:o.DEFAULT),[De.ANYCAST]:()=>(we=De.DEFAULT,o.ANYCAST="",o.DEFAULT)}[we](),{isBinary:e})}(this._isBinarySupported);try{this._isReconnecting=!0,this.disconnect(),this.connect()}catch(e){this._isReconnecting=!1,this._handleConnectStateChange({state:_t,reason:pt}),console.warn(`${at} reconnect failed: `,e)}}}))}_addEventListeners(){var e,t,n,s,i;null===(e=this._socketAdapter)||void 0===e||e.on("connect",this._onConnect,this),null===(t=this._socketAdapter)||void 0===t||t.on("message",this._onMessage,this),null===(n=this._socketAdapter)||void 0===n||n.on("close",this._onClose,this),null===(s=this._socketAdapter)||void 0===s||s.on("error",this._onError,this),null===(i=this._socketAdapter)||void 0===i||i.on("sendFail",this._onSendFail,this)}_removeEventListeners(){var e,t,n,s,i;null===(e=this._socketAdapter)||void 0===e||e.off("connect",this._onConnect,this),null===(t=this._socketAdapter)||void 0===t||t.off("message",this._onMessage,this),null===(n=this._socketAdapter)||void 0===n||n.off("close",this._onClose,this),null===(s=this._socketAdapter)||void 0===s||s.off("error",this._onError,this),null===(i=this._socketAdapter)||void 0===i||i.off("sendFail",this._onSendFail,this)}_onClose(e){const{socketId:t,event:n}=e||{},s=0!==this._connectionEstablishedTime?Date.now()-this._connectionEstablishedTime:0,i=`${at} onClose closeSocketID: ${t} currentSocketID: ${this._connectionId} connectionDuration: ${s} code:${null==n?void 0:n.code} reason:${null==n?void 0:n.reason}`;this._ssoLog({method:"onClose",message:i}),console.warn(i),t===this._connectionId&&this._handleConnectStateChange({state:_t,reason:mt}),this._isReconnecting&&(this._isReconnecting=!1)}_onError(e){const{socketId:t,error:n}=e||{},s=`${at} onError sourceSocketID: ${t} currentSocketID:${this._connectionId} isReconnecting: ${this._isReconnecting} error: ${JSON.stringify(n)}`;this._ssoLog({method:"onError",message:s}),console.warn(s),t===this._connectionId&&this._handleConnectStateChange({state:_t,reason:St}),this._isReconnecting&&(this._isReconnecting=!1)}_onSendFail(e){const{socketId:t,error:n}=e||{},s=`${at} onSendFail sendFailSocketId: ${t} currentSocketID:${this._connectionId} isReconnecting: ${this._isReconnecting} error: ${n}`;this._ssoLog({method:"onSendFail",message:s}),console.warn(s),t===this._connectionId&&this._handleConnectStateChange({state:_t,reason:Et}),this._isReconnecting&&(this._isReconnecting=!1)}_onMessage(e){let t,n;this._updateHeartbeatTime();try{t=this._isBinarySupported?this._isCompressedData(e.data)?(e=>{const t=new Uint8Array(e).slice(4);let n;try{n=Ot.inflate(t,{to:"string"})}catch(e){console.error("inflate error",e)}return n})(e.data):function(e){const t=new Uint8Array(e);let n="",s=0;const{length:i}=t;for(;s<i;){let e=t[s],o=0,r=0;if(e<=127?(o=0,r=255&e):e<=223?(o=1,r=31&e):e<=239?(o=2,r=15&e):e<=244&&(o=3,r=7&e),i-s-o>0)for(let n=0;n<o;n+=1)e=t[s+n+1],r=r<<6|63&e;else r=65533,o=i-s;n+=String.fromCodePoint(r),s+=o+1}return n}(e.data):e.data,n=JSON.parse(t)}catch(t){const n=e.data;return this._ssoLog({method:"jsonParseError",message:n}),void console.error(t)}if(!n||!n.head)return;const{seq:s,servcmd:i}=n.head,o=`${s}${i}`;this._pendingRequests.has(o)?this._handleRequestResponse(n):this._handlePushMessage(n)}_handleRequestResponse(e){const{seq:t,servcmd:n}=e.head,{int32_error_code:s,str_error_message:i,ErrorCode:r=s,ErrorInfo:a=i}=(null==e?void 0:e.body)||{},c=`${t}${n}`,{resolve:l,reject:d,timestamp:u,headSeq:_}=this._pendingRequests.get(c);if(this._pendingRequests.delete(c),r&&0!==r)return o.emitInnerEvent("error",{errorCode:r,errorInfo:a}),void d({errorCode:r,errorInfo:a});l(e.body)}_handlePushMessage(e){const{servcmd:t}=e.head,{NeedAck:n,SessionData:s}=e.body;1===n&&this._sendAck(s),o.emitInnerEvent(t,e)}_checkPendingRequestsAndResend(){var e;console.log(`${at}._checkPendingRequestsAndResend reConnectFlag:${this._isReconnecting} promiseMap.size:${this._pendingRequests.size}`),null===(e=this._pendingRequests)||void 0===e||e.forEach(((e,t)=>{var n;const{uplinkData:s,canResend:i,resolve:o,reject:r,timeout:a}=e;if(i){this._pendingRequests.set(t,{resolve:o,reject:r,timestamp:Date.now(),uplinkData:s,timeout:a,canResend:i});const e=this._isBinarySupported?Ge(s).buffer:s;null===(n=this._socketAdapter)||void 0===n||n.send(e)}else this._pendingRequests.delete(t)}))}_onConnect(e){const{socketId:t,event:n={}}=e||{};this._connectionId=t,this._connectionEstablishedTime=Date.now();const s=Date.now()-this._connectionStartTime,i=`${at} onConnect cost:${s} ms. socketID:${t} res:${JSON.stringify(n)}`;if(this._ssoLog({method:"onConnect",message:i}),console.log(i),this._checkPendingRequestsAndResend(),this._sendHeartbeatIfReady(),this._isReconnecting){const e=`${at} reconnect success`;this._ssoLog({method:"reconnectSuccess",message:e}),console.log(e),o.emitInnerEvent(Ze.RECONNECTED),this._isReconnecting=!1}this._resetReconnectDelay(),this._handleConnectStateChange({state:dt})}_sendAck(e){const t=$e({servcmd:"openim.ws_msg_push_ack",data:{SessionData:e}});this.sendPacket(t)}_executeScheduledTaskIfReady(){return a(this,void 0,void 0,(function*(){this._clearTimeoutRequest(),this._sendHeartbeatIfReady()}))}_canSendHeartbeat(){var e;return(null===(e=this._socketAdapter)||void 0===e?void 0:e.isConnected())&&Date.now()>=this._nextHeartbeatAt&&!this._isHeartbeatInProgress}_sendHeartbeat(){return a(this,void 0,void 0,(function*(){var e;const t=$e({servcmd:"heartbeat.alive",data:{}});try{const e=`${t.head.seq}${t.head.servcmd}`;yield this.sendPacket(t,{requestId:e,timeout:3e3})}catch(t){const n=null===(e=Re.get("netWorkMonitor"))||void 0===e?void 0:e.isNetWorkOnline,s=`${at} sendHeartbeat failed. isNetWorkOnline:${n} error: ${t}`;this._ssoLog({method:"sendHeartbeatError",message:s}),console.debug(s),this._handleConnectStateChange({state:_t,reason:Et})}}))}_sendHeartbeatIfReady(){return a(this,void 0,void 0,(function*(){this._canSendHeartbeat()&&(this._isHeartbeatInProgress=!0,yield this._sendHeartbeat(),this._isHeartbeatInProgress=!1)}))}_updateHeartbeatTime(){this._nextHeartbeatAt=D?Date.now()+5e3:Date.now()+1e4}_handleNetworkStatusChange(e){const t=`${at} networkStatusChange ${JSON.stringify(e)}`;this._ssoLog({method:"networkStatusChange",message:t}),console.warn(t);const{isNetworkOnline:n,networkType:s}=e;n&&"none"!==s?this._handleConnectStateChange({state:dt,reason:gt}):this._handleConnectStateChange({state:_t,reason:gt})}isPrivateNetWork(){const e=Re.get("instance")||{};return e.proxyServer&&!e.fileDownloadProxy}_handleConnectStateChange(e){const{state:t,reason:n}=e;if(this._currentConnectState!==t){const e=`${at}._handleConnectStateChange from ${this._currentConnectState} to ${t} reason: ${n}`;this._ssoLog({method:"handleConnectStateChange",message:e}),console.log(e),this._currentConnectState=t,o.emitOuterEvent("netStateChange",{name:"netStateChange",data:{state:t}}),t===_t&&o.emitInnerEvent(Ze.SOCKET_DISCONNECTED),t!==_t&&t!==dt||(this._resetReconnectDelay(),Fe.addTask({id:lt,intervalMs:this._intendedDelay,callback:this._scheduleReconnectWithBackoff,context:this}))}}_handleActivityStatusChange(e){var t,n;const s=null===(n=null===(t=this._socketAdapter)||void 0===t?void 0:t._ws)||void 0===n?void 0:n.readyState,i=`${at} activityStatusChange ${JSON.stringify(e)} readyState: ${s}`;this._ssoLog({method:"activityStatusChange",message:i}),console.warn(i),3===s&&this._handleConnectStateChange({state:_t,reason:ft})}_resetReconnectDelay(){var e;Fe.removeTask(lt);const t=null===(e=Re.get("activityMonitor"))||void 0===e?void 0:e.isActive;this._intendedDelay=t?ht:1e3}_scheduleReconnectWithBackoff(){var e;const t=null===(e=Re.get("activityMonitor"))||void 0===e?void 0:e.isActive;this._intendedDelay=t?Math.min(5e3,Math.max(ht,1.5*this._intendedDelay)):Math.min(3e5,Math.max(1e3,1.5*this._intendedDelay));const n=(new Date).toTimeString().slice(0,8),s=`${at}.scheduleReconnectWithBackoff timeStr: ${n} intendedDelay: ${this._intendedDelay}`;this._ssoLog({method:"scheduleReconnectWithBackoff",message:s}),console.log(s),this.reconnect(),Fe.updateTaskInterval(lt,this._intendedDelay)}_ssoLog(e){const{method:t,message:n}=e;ot.createSSOLogData({method:t}).setLogInfo({message:n}).end()}_diagnose(){this.isPrivateNetWork()||(this._lastDiagnoseAt=Date.now(),function(e){a(this,void 0,void 0,(function*(){const t=e.split("/")[2];if(!t.startsWith("ws"))return;const n=`https://${t}/v3/netcheck/getconninfo?${e.slice(e.indexOf("info?")+5)}&reqtime=${Date.now()}`;try{yield de({method:"GET",url:n,data:{}})}catch(e){console.warn("diagnoseBySSO failed. error:",e)}}))}(this._url),function(e){a(this,void 0,void 0,(function*(){const t=`https://boce-cdn.my-imcloud.com/v3/netcheck/getconninfo?${e.slice(e.indexOf("info?")+5)}&reqtime=${Date.now()}`;try{yield 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:n,timestamp:s,timeout:i}=t;Date.now()-s>=i&&(this._pendingRequests.delete(e),Date.now()-this._lastDiagnoseAt>=3e4&&this._diagnose(),n({errorCode:ae,errorInfo:"NETWORK_TIMEOUT",data:{requestId:e}}))}}_updateIsBinarySupported(){var e;if(null===(e=Re.get("instance"))||void 0===e?void 0:e.devMode)return void(this._isBinarySupported=!1);const t=oe();(A||C&&"windows"===t||D)&&(this._isBinarySupported=!1)}_isCompressedData(e){const t=new Uint8Array(e);return 67===t[0]&&79===t[1]&&77===t[2]&&80===t[3]}};const Tt={init:function(e){Re.set("instance",e),Mt.init()},destroy:function(){Mt.dispose(),Re.clear(),Fe.dispose()},notificationCenter:o,channel:Mt,store:Re,ssoLog:ot,utils:ge,common:We,constants:I};var At;!function(e){e.SDK_READY="sdkStateReady",e.SDK_NOT_READY="sdkStateNotReady",e.SDK_DESTROY="sdkDestroy",e.MESSAGE_RECEIVED="onMessageReceived",e.ROOM_CUSTOM_DATA_RECEIVED="onRoomCustomDataReceived",e.MESSAGE_MODIFIED="onMessageModified",e.MESSAGE_REVOKED="onMessageRevoked",e.MESSAGE_READ_BY_PEER="onMessageReadByPeer",e.MESSAGE_READ_RECEIPT_RECEIVED="onMessageReadReceiptReceived",e.MESSAGE_EXTENSIONS_UPDATED="onMessageExtensionsUpdated",e.MESSAGE_EXTENSIONS_DELETED="onMessageExtensionsDeleted",e.MESSAGE_REACTIONS_UPDATED="onMessageReactionsUpdated",e.CONVERSATION_LIST_UPDATED="onConversationListUpdated",e.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED="onTotalUnreadMessageCountUpdated",e.CONVERSATION_GROUP_LIST_UPDATED="onConversationGroupListUpdated",e.CONVERSATION_IN_GROUP_UPDATED="onConversationInGroupUpdated",e.GROUP_LIST_UPDATED="onGroupListUpdated",e.GROUP_ATTRIBUTES_UPDATED="groupAttributesUpdated",e.GROUP_COUNTER_UPDATED="onGroupCounterUpdated",e.TOPIC_CREATED="onTopicCreated",e.TOPIC_DELETED="onTopicDeleted",e.TOPIC_UPDATED="onTopicUpdated",e.PROFILE_UPDATED="onProfileUpdated",e.USER_STATUS_UPDATED="onUserStatusUpdated",e.BLACKLIST_UPDATED="blacklistUpdated",e.FRIEND_LIST_UPDATED="onFriendListUpdated",e.FRIEND_GROUP_LIST_UPDATED="onFriendGroupListUpdated",e.FRIEND_APPLICATION_LIST_UPDATED="onFriendApplicationListUpdated",e.MY_FOLLOWERS_LIST_UPDATED="onMyFollowersListUpdated",e.MY_FOLLOWING_LIST_UPDATED="onMyFollowingListUpdated",e.MUTUAL_FOLLOWERS_LIST_UPDATED="onMutualFollowersListUpdated",e.KICKED_OUT="kickedOut",e.ERROR="error",e.NET_STATE_CHANGE="netStateChange",e.ALL_RECEIVE_MESSAGE_OPT_UPDATED="onAllReceiveMessageOptUpdated"}(At||(At={}));var Nt,Dt=At;!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"}(Nt||(Nt={}));var Rt,bt=Nt;!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"}(Rt||(Rt={}));var wt=Rt;const Lt=Object.assign({},{KICKED_OUT_MULT_ACCOUNT:"multipleAccount",KICKED_OUT_MULT_DEVICE:"multipleDevice",KICKED_OUT_USERSIG_EXPIRED:"userSigExpired",KICKED_OUT_REST_API:"REST_API_Kick"}),kt={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 Pt;!function(e){e.UNSENT="unSend",e.SUCCESS="success",e.FAIL="fail"}(Pt||(Pt={}));const Ut={modify:bt.MESSAGE_MODIFIED,delete:bt.MESSAGE_DELETED,revoke:bt.MESSAGE_REVOKED},Ft=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},kt),{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:Pt}),Gt={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"},xt=Object.assign({},Gt),Bt=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"}),$t=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"}),Vt=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"}),qt=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},Lt),Ft),xt),Bt),$t),Vt),{IOS_OFFLINE_PUSH_NO_SOUND:"push.no_sound",IOS_OFFLINE_PUSH_DEFAULT_SOUND:"default"}),{NET_STATE_CONNECTING:"connecting",NET_STATE_DISCONNECTED:"disconnected"}),jt={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},Yt={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"},Wt={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"},Kt={[Yt.SYNC_SERVER_INFO_AFTER_RE_ONLINE]:[{stepId:Wt.USER_STATUS_UPDATE},{stepId:Wt.GROUP_ATTRIBUTE_CACHE_CLEAR},{stepId:Wt.UNREAD_MESSAGE_SYNC},{stepId:Wt.CONVERSATION_RECOVER},{stepId:Wt.HISTORY_MESSAGE_RECOVER,dependency:Wt.CONVERSATION_RECOVER},{stepId:Wt.BLACKLIST_RECOVER},{stepId:Wt.FRIEND_RECOVER},{stepId:Wt.GROUP_REVOKED_NOTICE_RECOVER},{stepId:Wt.HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD,dependency:Wt.UNREAD_MESSAGE_SYNC},{stepId:Wt.HANDLE_GROUP_TIPS_FROM_SYNC_UNREAD,dependency:Wt.UNREAD_MESSAGE_SYNC},{stepId:Wt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[Wt.UNREAD_MESSAGE_SYNC,Wt.CONVERSATION_RECOVER]},{stepId:Wt.EMIT_C2C_MESSAGE_EVENT,dependency:[Wt.UNREAD_MESSAGE_SYNC,Wt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED],skipIfDependencyMissing:!1}],[Yt.SYNC_SERVER_INFO_AFTER_LOGIN]:[{stepId:Wt.COMMERCIAL_CONFIG_UPDATE},{stepId:Wt.CLOUD_CONFIG_SYNC},{stepId:Wt.USER_PROFILE_SYNC},{stepId:Wt.UNREAD_MESSAGE_SYNC},{stepId:Wt.FRIEND_AND_BLACKLIST_SYNC},{stepId:Wt.GROUP_LIST_SYNC},{stepId:Wt.CONVERSATION_LIST_SYNC},{stepId:Wt.SIGNALING_MESSAGE_RECOVER,dependency:Wt.UNREAD_MESSAGE_SYNC},{stepId:Wt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[Wt.UNREAD_MESSAGE_SYNC,Wt.CONVERSATION_LIST_SYNC]},{stepId:Wt.CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED,dependency:[Wt.GROUP_LIST_SYNC,Wt.CONVERSATION_LIST_SYNC]}],[Yt.RECEIVE_C2C_NEW_MESSAGE]:[{stepId:Wt.HANDLE_C2C_NEW_MESSAGE},{stepId:Wt.UNREAD_MESSAGE_SYNC},{stepId:Wt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:Wt.HANDLE_C2C_NEW_MESSAGE},{stepId:Wt.EMIT_C2C_MESSAGE_EVENT,dependency:[Wt.HANDLE_C2C_NEW_MESSAGE,Wt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1},{stepId:Wt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[Wt.UNREAD_MESSAGE_SYNC]}],[Yt.RECEIVE_GROUP_NEW_MESSAGE]:[{stepId:Wt.HANDLE_GROUP_NEW_MESSAGE},{stepId:Wt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:Wt.HANDLE_GROUP_NEW_MESSAGE},{stepId:Wt.UPDATE_GROUP_NEXT_SEQUENCE,dependency:Wt.HANDLE_GROUP_NEW_MESSAGE},{stepId:Wt.EMIT_GROUP_MESSAGE_EVENT,dependency:[Wt.HANDLE_GROUP_NEW_MESSAGE,Wt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1}]};var Ht=Object.freeze({__proto__:null,ERROR_CODE:jt,InnerEvent:bt,OuterConstant:qt,OuterEvent:Dt,SDK_INFO:{VERSION:"1.7.3",APPID:537048168},SignalingEvent:wt,WORKFLOW_DEFINITIONS:Kt,WORKFLOW_NAME:Yt,WORKFLOW_STEP:Wt});function zt(e){var t;try{const n=Re.getStorage("errorMessage");if(!e||!n)return"";const s=(null===(t=JSON.parse(n))||void 0===t?void 0:t.errorMessage)||{},{isIntl:i=!1,code:o,replacement1:r="",replacement2:a=""}=e;if(!o)return"";const c=i?`${o}_en`:`${o}_cn`;let l=s[s[c]?c:o]||"";return l&&(r&&(l=l.replace("$replacement1",r)),a&&(l=l.replace("$replacement2",a))),l}catch(e){return console.warn("Error parsing stored error messages:",e),""}}class Jt extends Error{constructor(e){const{functionName:t="Unknown",code:n,message:s="",data:i=""}=e;let o=s;n&&!s&&(o=zt(e));const r=n?`${t} failed. error: {"message": ${o}, "code": ${n}}`:`${t} failed. error: {"message": ${o}}`;super(),this.code=n,this.errorCode=n,this.errorMessage=r,this.message=r,this.data=i}}function Zt(e,t){var n;if(!e)return;if(!(!0===(null===(n=Tt.store.get("login"))||void 0===n?void 0:n.isLoggedIn)))throw new Jt({code:jt.USER_NOT_LOGGED_IN,functionName:t})}const Xt=e=>"function"==typeof e;function Qt(e,t,n){const s=n||[];if(!e||!t)return!1;const i=Object.keys(e).filter((e=>!s.includes(e))),o=Object.keys(t).filter((e=>!s.includes(e)));return i.length===o.length&&i.every((s=>!!t.hasOwnProperty(s)&&("object"==typeof e[s]&&null!==e[s]?Qt(e[s],t[s],n):e[s]===t[s])))}function en(e,t,n){if(Array.isArray(e))for(let s=0;s<e.length;s++)tn.call(this,Object.assign(Object.assign({},e[s]),{value:t[s],name:n}));else for(const s in e)tn.call(this,Object.assign(Object.assign({},e[s]),{value:t[0][s],name:n,key:s}))}function tn({required:e,rules:t,range:n,value:s,allowEmpty:i,name:o,key:r,customValidator:a}){if(void 0===s){if(e){throw new Jt({functionName:o,message:`[${o}] Missing required params: "${r}"`})}return}let c="";if(!t.some((e=>{return e===(t=s,Object.prototype.toString.call(t).match(/^\[object (.*)\]$/)[1].toLowerCase());var t}))){for(let e=0;e<t.length;e++){let n=t[e];n=n.replace(n[0],n[0].toUpperCase()),c+=`${n}/`}c=c.substring(0,c.length-1);const e=`[${r}] must be type of ${c}, received type: ${function(e){return Reflect.apply(Object.prototype.toString,e,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}(s)}.`;throw new Jt({functionName:o,message:e})}if(!1===i){if(Array.isArray(s)&&(0===s.length||"string"==typeof s[0]&&""===s[0].trim())){throw new Jt({functionName:o,message:`${r} can not be empty.`})}if("string"==typeof s&&""===s.trim()){throw new Jt({functionName:o,message:`${r} can not be empty.`})}}if(a&&"function"==typeof a){const e=a(s);if(!0!==e){throw new Jt({functionName:o,message:`[${r}] custom validation failed: ${e||"Invalid value"}`})}}}const nn=[],sn={},on={};function rn(e,t){Zt(sn[e],e),en(on[e],t,e),function(e){nn.forEach((t=>{const{interceptor:n,context:s}=t;n.apply(s,[e])}))}(e)}function an(e,t){nn.push({interceptor:e,context:t})}function cn(e){const{params:t,auth:n}=e;t&&"object"==typeof t&&Object.assign(on,t),n&&"object"==typeof n&&Object.assign(sn,n)}var ln=new class{constructor(){this._builtInPlugins=new WeakSet,this._externalPlugins=new WeakSet}installBuiltInPlugin(e){e&&this._installPlugin(e,this._builtInPlugins)}installExternalPlugin(e,t){e&&this._installPlugin(e,this._externalPlugins,t)}clear(){this._builtInPlugins=new WeakSet,this._externalPlugins=new WeakSet}_installPlugin(e,t,n){let s=[];s=Array.isArray(e)?e:[e],s.forEach((e=>{t.has(e)||(e&&Xt(e.install)?(t.add(e),e.install(bn(),n),Xt(e.handleLoginSuccess)&&this._isLoggedIn()&&e.handleLoginSuccess()):Xt(e)?(t.add(e),e(bn(),n),Xt(e.handleLoginSuccess)&&this._isLoggedIn()&&e.handleLoginSuccess()):console.warn('A plugin must either be a function or an object with an "install" function.'))}))}_isLoggedIn(){var e;return!0===(null===(e=Tt.store.get("login"))||void 0===e?void 0:e.isLoggedIn)}};function dn(e){return Tt.store.get("commercialConfig").get(e)}const un=new Map;var _n=new class{constructor(){this._handlers=new Map,this._activeWorkflows=new Map,this._stepStartTimes=new Map,this._logHandlers={start:(e,t)=>{const n=Date.now();t?(this._stepStartTimes.set(`${e}-${t}`,n),console.log(`[Workflow ${e}] Step ${t} started at ${new Date(n).toISOString()}`)):(this._workflowStartTimes.set(e,n),console.log(`[Workflow ${e}] started at ${new Date(n).toISOString()}`))},success:(e,t)=>{const n=Date.now();if(t){const s=this._stepStartTimes.get(`${e}-${t}`),i=s?n-s:0;this._stepStartTimes.delete(`${e}-${t}`),console.log(`[Workflow ${e}] Step ${t} completed successfully at ${new Date(n).toISOString()} (${i}ms)`)}else{const t=this._workflowStartTimes.get(e),s=t?n-t:0;this._workflowStartTimes.delete(e),console.log(`[Workflow ${e}] completed successfully at ${new Date(n).toISOString()} (${s}ms)`)}},error:(e,t,n)=>{const s=Date.now();if(t){const i=this._stepStartTimes.get(`${e}-${t}`),o=i?s-i:0;this._stepStartTimes.delete(`${e}-${t}`),console.error(`[Workflow ${e}] Step ${t} failed at ${new Date(s).toISOString()} (${o}ms)`,n)}else{const t=this._workflowStartTimes.get(e),i=t?s-t:0;this._workflowStartTimes.delete(e),console.error(`[Workflow ${e}] failed at ${new Date(s).toISOString()} (${i}ms)`,n)}}}}init(){this._initializeWorkflows()}registerWorkflowStep(e,t,n,s){if(!this._handlers.has(e))return void console.debug(`Workflow '${e}' not defined in core`);if(!Kt[e].find((e=>e.stepId===t)))return void console.debug(`Step '${t}' not defined in workflow '${e}'`);this._handlers.get(e).set(t,s?n.bind(s):n)}executeWorkflow(e,t){return a(this,void 0,void 0,(function*(){if(!this._validateWorkflow(e))return;console.log(`[Workflow ${e}] Started execution at ${(new Date).toISOString()}`);const n=Kt[e],s={},i={cancelled:!1};this._activeWorkflows.set(e,{cancelToken:i});try{const o=new Map;n.forEach((e=>{o.set(e.stepId,e)}));const r={workflowName:e,pendingSteps:new Set(n.map((e=>e.stepId))),completedSteps:new Set,runningSteps:new Set,stepMap:o,stepResults:s,data:t,cancelToken:i};yield new Promise(((t,n)=>{const s=()=>{if(i.cancelled)return void t();this._getExecutableSteps({pendingSteps:r.pendingSteps,completedSteps:r.completedSteps,stepMap:r.stepMap}).filter((e=>!r.runningSteps.has(e))).forEach((i=>this._executeWorkflowStep(i,r,{onComplete:()=>{if(0===r.pendingSteps.size)return void t();0===this._getExecutableSteps({pendingSteps:r.pendingSteps,completedSteps:r.completedSteps,stepMap:r.stepMap}).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:n,onStepComplete:s})))};s()})),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,n){return a(this,void 0,void 0,(function*(){const{workflowName:s,runningSteps:i,stepMap:o,stepResults:r,data:a}=t;i.add(e),this._logWorkflowExecution(s,e,"start");try{const n=o.get(e);let i=null;(null==n?void 0:n.dependency)&&(l(n.dependency)?i=r[n.dependency]:Array.isArray(n.dependency)&&(i={},n.dependency.forEach((e=>{i[e]=r[e]}))));const c=this._handlers.get(s).get(e);if(c){const t=yield Promise.resolve(c({data:a,result:i}));r[e]=t,this._logWorkflowExecution(s,e,"success")}t.completedSteps.add(e)}catch(t){const i=`[Workflow].${s}.${e}`,{errorCode:o,errorInfo:r=`${i} failed`}=t||{},a=new Jt({functionName:i,code:o,message:r});Tt.ssoLog.createSSOLogData({method:"Workflow"}).setLogInfo({message:`workflowName: ${s}, stepId: ${e}`}).setError(a).end(),this._logWorkflowExecution(s,e,"error",t),n.onError(t)}finally{i.delete(e),t.pendingSteps.delete(e),n.onStepComplete(),n.onComplete()}}))}reset(){this._cancelAllWorkflows()}destroy(){this.reset(),this._handlers.clear()}_initializeWorkflows(){Object.keys(Kt).forEach((e=>{this._handlers.set(e,new Map)}))}_cancelWorkFlow(e){const t=this._activeWorkflows.get(e);if(!t)return;const{cancelToken:n}=t;n.cancelled=!0,this._activeWorkflows.delete(e)}_cancelAllWorkflows(){Object.keys(Kt).forEach((e=>{this._cancelWorkFlow(e)}))}_validateWorkflow(e){if(!Kt[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:n,stepMap:s}=e;return Array.from(t).filter((e=>{const t=s.get(e)||{},{dependency:i,skipIfDependencyMissing:o=!0}=t;if(!i)return!0;if(l(i))return s.has(i)?n.has(i):!o;if(u(i)){if(i.filter((e=>!s.has(e))).length>0)return!o;for(const e of i)if(!n.has(e))return!1;return!0}return!1}))}_logWorkflowExecution(e,t,n,s){this._logHandlers[n](e,t)}};const hn=e=>u(e)||_(e),gn=(e,t,n,s)=>{if(!hn(e)||!hn(t))return 0;let i=0;const o=Object.keys(t);let r;for(let a=0,l=o.length;a<l;a++)if(r=o[a],!(c(t[r])||n&&n.includes(r)))if(hn(e[r])&&hn(t[r]))i+=gn(e[r],t[r],n,s);else{if(s&&s.includes(t[r]))continue;e[r]!==t[r]&&(e[r]=t[r],i+=1)}return i};var fn=Object.freeze({__proto__:null,ChatError:Jt,buildAndSendPacket:function(e){return a(this,void 0,void 0,(function*(){const{servcmd:t,data:n}=e,s=Tt.common.generateProtocolData({servcmd:t,data:n}),i=`${s.head.seq}${t}`;return Tt.channel.sendPacket(s,{requestId:i})}))},checkBusinessCapabilityBits:dn,deepMerge:gn,destroy:Dn,exposeApiForClient:Rn,exposeApiForPlugin:bn,getCurrentUserID:function(){var e;return null===(e=Tt.store.get("login"))||void 0===e?void 0:e.userId},getErrorMessage:zt,isUnlimitedAVChatRoom:function(){var e;return!!(null===(e=Tt.store.get("instance"))||void 0===e?void 0:e.isUnlimitedAVChatRoom)},liteChatInstanceMap:un,registerApi:An,registerExperimentalAPI:Nn,registerInterceptor:an,registerPlugin:On,registerValidateConfig:cn,requireAuth:Zt,setLogLevel:Tn,statKeyFeatureUsage:Mn,validateAndExecute:rn,validateParameters:en,workflowManager:_n});var En=new class{constructor(){this._conversationMap=new Map}getConversationMap(){return this._conversationMap}getConversation(e){return this._conversationMap.get(e)}updateConversation(e,t){const n=this._conversationMap.get(e);n&&!ue(t)&&(Object.keys(t).forEach((e=>{n[e]=t[e]})),Tt.notificationCenter.emitInnerEvent(bt.CONVERSATION_UPDATED))}deleteConversation(e){this._conversationMap.has(e)&&(this._conversationMap.delete(e),Tt.notificationCenter.emitInnerEvent(bt.CONVERSATION_UPDATED))}};var pn=new class{constructor(){this._groupMap=new Map}getGroupMap(){return this._groupMap}getGroup(e){return this._groupMap.get(e)}updateGroup(e,t){const n=this._groupMap.get(e);n&&!ue(t)&&Object.keys(t).forEach((e=>{n[e]=t[e]}))}};var Sn=new class{constructor(){this._messagesByConversation=new Map}updateMessage(e,t,n){var s;const{operation:i,updateUnreadCount:o=!0}=n,a=r(n,["operation","updateUnreadCount"]),c=[];for(const n of t){const t=null===(s=this._messagesByConversation.get(e))||void 0===s?void 0:s.get(n);if(!t)return!1;Object.keys(a).forEach((e=>{t[e]=a[e]})),c.push(t)}return this._emitMessageStoreOperationEvent(i,{conversationID:e,messageList:c,updateUnreadCount:o}),c}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){Tt.notificationCenter.emitInnerEvent(e,t)}};var mn=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)}},vn=Object.freeze({__proto__:null,conversationStore:En,groupStore:pn,messageStore:Sn,userStore:mn});const In={on:Tt.notificationCenter.subscribeOuterEvent.bind(Tt.notificationCenter),off:Tt.notificationCenter.unSubscribeOuterEvent.bind(Tt.notificationCenter),destroy:Dn,callExperimentalAPI:function(e,t){if(Cn[e])return Cn[e](t);return Promise.reject(new Error(`API ${e} is not found`))},use:ln.installExternalPlugin.bind(ln),registerPlugin:On,setLogLevel:Tn},Cn={},yn={};function On(e){console.log("registerPlugin",e)}function Mn(e){console.log("statTUIKeyFeatures",e)}function Tn(e){console.log("setLogLevel",e),null==Tt||Tt.setLogLevel(e)}function An(e){const{apiName:t,context:n,methodName:s=t,matcher:i}=e;yn[t]||(yn[t]=[]),yn[t].push({context:n,methodName:s,matcher:i}),In[t]&&1!==yn[t].length||(In[t]=(...e)=>{rn(s,e);const n=yn[t];for(const t of n)if(!t.matcher||t.matcher(e))return t.context[t.methodName].bind(t.context)(...e)})}function Nn(e,t,n){const s=n||e;Cn[e]=t[s].bind(t)}function Dn(){return a(this,void 0,void 0,(function*(){var e,t;try{(null===(e=Tt.store.get("login"))||void 0===e?void 0:e.isLogin)&&(yield In.logout()),Tt.notificationCenter.emitInnerEvent(bt.DESTROY)}catch(e){console.debug("destroy error: ",e)}finally{Tt.notificationCenter.emitOuterEvent(Dt.SDK_DESTROY,{SDKAppID:null===(t=Tt.store.get("instance"))||void 0===t?void 0:t.sdkAppId}),un.clear(),ln.clear(),_n.destroy(),Tt.destroy()}}))}function Rn(){return In}function bn(){return Object.assign(Object.assign({InnerEvent:bt,InnerEventSubType:Tt.notificationCenter.InnerEventSubType,OuterEvent:Dt,OuterConstant:qt,SignalingEvent:wt,helper:Object.assign(Object.assign(Object.assign({},Tt.utils),Tt.common),{registerApi:An,registerExperimentalAPI:Nn,registerInterceptor:an,registerValidateConfig:cn,checkBusinessCapabilityBits:dn,registerWorkflowStep:_n.registerWorkflowStep.bind(_n),ChatError:Jt}),apiMap:In},Tt),{constants:Object.assign(Object.assign({},Ht),Tt.constants),common:Object.assign(Object.assign({},fn),Tt.common),utils:Tt.utils,appStore:vn})}Cn.statTUIKeyFeatures=Mn;var wn,Ln,kn;!function(e){e[e.USER_INITIATED=0]="USER_INITIATED",e[e.KICKED_OUT=1]="KICKED_OUT"}(wn||(wn={})),function(e){e[e.multipleAccount=1]="multipleAccount",e[e.multipleDevice=2]="multipleDevice",e[e.restApi=3]="restApi"}(Ln||(Ln={})),function(e){e[e.multipleDevice=3002]="multipleDevice",e[e.multipleAccount=3003]="multipleAccount",e[e.usersigExpired=70001]="usersigExpired",e[e.restApi=20002]="restApi"}(kn||(kn={}));const Pn={[Ln.multipleAccount]:"multipleAccount",[Ln.multipleDevice]:"multipleDevice",[Ln.restApi]:"REST_API_Kick",[kn.multipleAccount]:"multipleAccount",[kn.multipleDevice]:"multipleDevice",[kn.restApi]:"REST_API_Kick",[kn.usersigExpired]:"userSigExpired"},Un="login_online_presence_task",{ERROR:Fn,DESTROY:Gn,FORCE_OFFLINE:xn}=bt,{KICKED_OUT_MULT_ACCOUNT:Bn,KICKED_OUT_MULT_DEVICE:$n,KICKED_OUT_REST_API:Vn,ACCOUNT_A2KEY_EXPIRED:qn,MSG_A2KEY_EXPIRED:jn}=jt;class Yn{init(){const{notificationCenter:e}=Tt;e.subscribeInnerEvent(xn,this._handleForceOfflineFromServerPush,this),e.subscribeInnerEvent(Fn,jn,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(Fn,qn,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(Fn,Bn,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(Fn,$n,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(Fn,Vn,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(Gn,this._dispose,this)}_handleForceOfflineFromServerPush(e){const{EventArray:t=[]}=(null==e?void 0:e.body)||{};this._extractKickedOutMessages(t).forEach((e=>{const{KickoutMsgNotify:{KickType:t,NewInstInfo:n}}=e;this._processKickedOutReasonInfo({kickedOutReasonCode:t,newInstanceInfo:n})}))}_extractKickedOutMessages(e){return e.reduce(((e,t)=>[...e,...t.C2cNotifyMsgArray||[]]),[]).filter((e=>{var t;return this._isKickedOut(null===(t=null==e?void 0:e.KickoutMsgNotify)||void 0===t?void 0:t.KickType)}))}_handleForceOfflineFromResponse(e){const{errorCode:t}=e;this._processKickedOutReasonInfo({kickedOutReasonCode:t})}_processKickedOutReasonInfo(e){return a(this,void 0,void 0,(function*(){const{kickedOutReasonCode:t}=e;try{yield Tt.login.loginAction.logout(wn.KICKED_OUT)}catch(e){console.debug(e)}finally{this._logKickedOutEvent(e),Tt.notificationCenter.emitOuterEvent(Dt.KICKED_OUT,{data:{type:Pn[t]},name:Dt.KICKED_OUT}),[Ln.restApi,qn,jn].includes(t)&&Tt.channel.reconnect()}}))}_logKickedOutEvent(e){const{kickedOutReasonCode:t,newInstanceInfo:n={}}=e,s=Tt.ssoLog.createSSOLogData({method:"kickedOut"}),i=`type:${Pn[t]} newInstanceInfo: ${JSON.stringify(n)}`;s.setLogInfo({message:i}).end(!0),console.warn(`loginModule.${i}`)}_isKickedOut(e){return[Ln.multipleAccount,Ln.multipleDevice,Ln.restApi].includes(e)}_dispose(){const{notificationCenter:e}=Tt;e.unSubscribeInnerEvent(xn,this._handleForceOfflineFromServerPush,this),e.unSubscribeInnerEvent(Fn,qn,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(Fn,jn,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(Fn,Bn,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(Fn,$n,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(Fn,Vn,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(Gn,this._dispose,this)}}function Wn(){return a(this,void 0,void 0,(function*(){const e="im_open_status.wslogin",t=Tt.common.generateProtocolData({servcmd:e,data:{state:"Online",isWebUniapp:0,InstType:0,customInfo:""}}),n=`${t.head.seq}${e}`;try{const e=yield Tt.channel.sendPacket(t,{timeout:9e4,requestId:n});if(e){const{HelloInterval:t,InstId:n,TinyId:s,TimeStamp:i,CustomStatus:o,PurchaseBits:r,A2Key:a,RichMsgAuthKey:c,ErrorCode:l,ErrorInfo:d,ActionStatus:u}=e;return{helloInterval:t,instanceID:n,tinyID:s,timeStamp:i,customStatus:o,purchaseBits:r,a2Key:a,authKey:c,errorCode:l,errorInfo:d,actionStatus:u}}}catch(e){throw console.warn(e),e}}))}class Kn{constructor(){this._latestLoginAt=0,this._latestSendOnlinePresenceRequestTime=0,this._helloInterval=120}init(){const{notificationCenter:e,store:t}=Tt;t.set("login",{isReady:!1}),An({apiName:"login",context:this}),An({apiName:"logout",context:this}),An({apiName:"getLoginUser",context:this}),An({apiName:"isReady",context:this}),e.subscribeInnerEvent(bt.RECONNECTED,this._reLogin,this),Tt.notificationCenter.subscribeInnerEvent(bt.DESTROY,this._dispose,this)}login(e){return a(this,void 0,void 0,(function*(){const t=Tt.ssoLog.createSSOLogData({method:"login",eventType:4});try{if(this._isLoginIn())return this._createRepeatLoginResponse();if(this._isLoginFrequencyExceeded())throw new Jt({functionName:"login",code:jt.REPEAT_LOGIN});const t=yield this._performLogin(e);return this._validateAfterLogin(t),this._handleLoginSuccess(t),yield this._ensureAsyncComplete(),this._updateAndEmitSDKReady(),{code:0,data:t}}catch(e){const{errorCode:n}=e,s=new Jt({functionName:"login",code:n});throw t.setError(s).end(!0),s}finally{this._latestLoginAt=0}}))}_reLogin(){return a(this,void 0,void 0,(function*(){var e;try{if(!this._isLoginIn())return;const t=Tt.ssoLog.createSSOLogData({method:"reLogin"}),n=yield Wn();if(n){const{instanceID:s,customStatus:i}=n;Tt.store.set("login",{statusInstanceId:s}),_n.executeWorkflow(Yt.SYNC_SERVER_INFO_AFTER_RE_ONLINE,{customStatus:i,statusType:Gt.USER_STATUS_ONLINE});const o=`socketId:${null===(e=Tt.channel.getSocketAdapter())||void 0===e?void 0:e.getId()} instanceId:${s}`;t.setLogInfo({message:o}).end(!0)}}catch(e){console.warn(e)}}))}logout(){return a(this,arguments,void 0,(function*(e=wn.USER_INITIATED){Tt.ssoLog.createSSOLogData({method:"logout"}).setLogInfo({moreMessage:`identifier:${this._getCurrentUserId()}`}).end(!0);try{yield this._performLogout(e)}catch(e){const{errorCode:t}=e,n=new Jt({functionName:"logout",code:t});this._handleLogoutError(n)}finally{this._handleLogoutCompleted()}return{code:0,data:{}}}))}getLoginUser(){return this._isLoginIn()?this._getCurrentUserId():""}isReady(){var e;return null===(e=Tt.store.get("login"))||void 0===e?void 0:e.isReady}_updateAndEmitSDKReady(){Tt.store.set("login",{isReady:!0}),setTimeout((()=>{Tt.notificationCenter.emitOuterEvent(Dt.SDK_READY,{name:Dt.SDK_READY})}),1)}_updateAndEmitSDKNotReady(){Tt.store.set("login",{isReady:!1}),Tt.notificationCenter.emitOuterEvent(Dt.SDK_NOT_READY,{name:Dt.SDK_NOT_READY})}_validateAfterLogin(e){var t,n;const s="login";if(!e)throw new Jt({functionName:s,message:"login response is empty"});const{tinyID:i,a2Key:o}=e||{},r=Tt.ssoLog.getSSOLogData(s);if(!i){const e=new Jt({functionName:s,code:jt.NO_TINYID});throw null===(t=null==r?void 0:r.setError)||void 0===t||t.call(r,e).end(),e}if(!o){const e=new Jt({functionName:s,code:jt.NO_A2KEY});throw null===(n=null==r?void 0:r.setError)||void 0===n||n.call(r,e).end(),e}}_createRepeatLoginResponse(){var e;return{code:0,data:{actionStatus:"OK",errorCode:0,errorInfo:zt({code:"RepeatLogin",replacement1:null===(e=Tt.store.get("login"))||void 0===e?void 0:e.userId}),repeatLogin:!0}}}_performLogin(e){return a(this,void 0,void 0,(function*(){const{userID:t,userSig:n}=e;return Tt.store.set("login",{userId:t,userSig:n}),this._latestLoginAt=Date.now(),Wn()}))}_ensureAsyncComplete(){return a(this,void 0,void 0,(function*(){yield new Promise((e=>{setTimeout((()=>e(null)),1)}))}))}_handleLoginSuccess(e){const{timeManager:t}=Tt.common,{helloInterval:n,timeStamp:s,customStatus:i,purchaseBits:o}=e,r=1e3*s;t.calculateTimeOffsetWithServer(this._latestLoginAt,r),this._helloInterval=n||120,this._updateLoginStore(e),Tt.user.userStatus.setCustomStatus(i),_n.executeWorkflow(Yt.SYNC_SERVER_INFO_AFTER_LOGIN,{purchaseBits:o}),Tt.common.taskScheduler.addTask({id:Un,intervalMs:1e3*this._helloInterval,callback:this._sendOnlinePresenceRequest,context:this}),this._logLoginSuccess(e)}_performLogout(e){return function(e){return a(this,void 0,void 0,(function*(){const{logoutReason:t}=e,n="im_open_status.wslogout",s=Tt.common.generateProtocolData({servcmd:n,data:{wslogout_type:t,isWebUniapp:0}}),i=`${s.head.seq}${n}`;return yield Tt.channel.sendPacket(s,{requestId:i})}))}({logoutReason:e})}_handleLogoutError(e){Tt.ssoLog.getSSOLogData("logout").setError(e).end(),console.error(`logout ${e}`)}_handleLogoutCompleted(){this._updateAndEmitSDKNotReady(),this._reset(),_n.reset(),Tt.notificationCenter.emitInnerEvent("logout")}_updateLoginStore(e){const{a2Key:t,tinyID:n,instanceID:s,authKey:i}=e;Tt.store.set("login",{a2Key:t,tinyID:n,statusInstanceId:s,authKey:i,isLoggedIn:!0})}_logLoginSuccess(e){var t;const n=Tt.ssoLog.getSSOLogData("login"),{helloInterval:s,instanceID:i,timeStamp:o,customStatus:r}=e,a=null===(t=Tt.channel.getSocketAdapter())||void 0===t?void 0:t.getId(),c=Tt.common.timeManager.getTimeOffsetWithServer(),{appId:l,href:d}=Tt.store.get("instance")||{},u=`login._logLoginSuccess socketID:${a} scene: helloInterval:${s} instanceID:${i}\n timeStamp:${o} offset:${c} customStatus:${r} href: ${d} appId: ${l}`;console.log(`login ok. ${u}`),n.updateLogCreatedAtByTimeOffset(),n.setLogInfo({moreMessage:u}).end()}_sendOnlinePresenceRequest(){return a(this,void 0,void 0,(function*(){this._latestSendOnlinePresenceRequestTime=Date.now();try{yield function(){const e="im_open_status.wshello",t=Tt.common.generateProtocolData({servcmd:e,data:{isWebUniapp:0}}),n=`${t.head.seq}${e}`;return Tt.channel.sendPacket(t,{requestId:n})}()}catch(e){console.warn("Login._sendOnlinePresenceRequest error:",e)}}))}_getCurrentUserId(){var e;return null===(e=Tt.store.get("login"))||void 0===e?void 0:e.userId}_isLoginIn(){var e;return!0===(null===(e=Tt.store.get("login"))||void 0===e?void 0:e.isLoggedIn)}_isLoginFrequencyExceeded(){return Date.now()-this._latestLoginAt<=15e3}_reset(){console.log("Login reset"),Tt.common.taskScheduler.removeTask(Un),this._helloInterval=120,this._latestSendOnlinePresenceRequestTime=0,this._latestLoginAt=0,Tt.store.clear("login"),Tt.store.set("login",{isReady:!1})}_dispose(){console.log("Login dispose"),this._reset();const{notificationCenter:e}=Tt;e.unSubscribeInnerEvent(bt.RECONNECTED,this._reLogin,this),e.unSubscribeInnerEvent(bt.DESTROY,this._dispose,this)}}const Hn={login:{userID:{required:!0,rules:["string"],allowEmpty:!1},userSig:{required:!0,rules:["string"],allowEmpty:!1}}},zn={logout:!0};class Jn{constructor(){this.loginAction=new Kn,this.kickedOutHandler=new Yn,this.loginAction.init(),this.kickedOutHandler.init(),cn({auth:zn,params:Hn})}}var Zn,Xn,Qn;!function(e){e.CONV_C2C="C2C",e.CONV_GROUP="GROUP",e.CONV_TOPIC="TOPIC",e.CONV_SYSTEM="@TIM#SYSTEM"}(Zn||(Zn={})),function(e){e.MSG_PRIORITY_HIGH="High",e.MSG_PRIORITY_NORMAL="Normal",e.MSG_PRIORITY_LOW="Low",e.MSG_PRIORITY_LOWEST="Lowest"}(Xn||(Xn={})),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"}(Qn||(Qn={}));const es={1:Xn.MSG_PRIORITY_HIGH,2:Xn.MSG_PRIORITY_NORMAL,3:Xn.MSG_PRIORITY_LOW,4:Xn.MSG_PRIORITY_LOWEST},ts=0,ns=1;var ss;!function(e){e.IN="in",e.OUT="out"}(ss||(ss={}));const is={};function os(e){if(!e)return 0;if(void 0===is[e]){const t=new Date,n=`3${t.getHours()}`.slice(-2),s=`0${t.getMinutes()}`.slice(-2),i=`0${t.getSeconds()}`.slice(-2);is[e]=parseInt([n,s,i,"0001"].join(""),10),console.log(`autoIncrementIndex start index:${is[e]}`)}else is[e]+=1;return is[e]}class rs{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=Xn.MSG_PRIORITY_NORMAL,this._relayFlag=!1;const{clientTime:t=Tt.common.timeManager.getServerTimeSeconds()||0,senderTinyID:n,currentUser:s,needReadReceipt:i,isSupportExtension:o,customModerationConfigurationId:r,to:a,from:c,nick:l="",avatar:d="",time:u,messageControlInfo:_,tinyID:h,cloudCustomData:g="",messageLifeTime:f,messageVersion:E=0,conversationType:p,sequence:S,checkResult:m=0,isPlaceMessage:v=0,messageFlagBits:I,receiverList:C,isSystemMessage:y=!1,status:O=Pt.SUCCESS,revokeReason:M="",conversationSubType:T,clientSequence:A,protocol:N="JSON",revokerInfo:D={userID:"",nick:"",avatar:""},readReceiptInfo:R={readCount:void 0,unreadCount:void 0,isPeerRead:void 0,timestamp:0},random:b,groupProfile:w,atUserList:L,flow:k,isRead:P=!1}=e;var U;this.clientTime=t,this.senderTinyID=n||h,this.needReadReceipt=!0===i||1===i,this.isSupportExtension=!0===o||1===o,this._cmConfigID=r,this.to=a,this.nick=l,this.avatar=d,this.protocol=N,this.random=void 0===b?(U=U||99999999,Math.round(Math.random()*U)):b,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=S||0,this.conversationType=p||Zn.CONV_C2C,this.hasRiskContent=m>1,this.version=E,this.isPlaceMessage=v,this.isRevoked=2===v||8===I,this.isSystemMessage=y,this.readReceiptInfo=R,this.revokeReason=M,this.revokerInfo=D,this._receiverList=C,this.conversationSubType=T,this.revoker=(null==D?void 0:D.revoker)||"",this.clientSequence=A||S||0,this.status=O,this.atUserList=L||[],this.flow=k,this.isRead=P,this.reInitialize(s),this._initC2CReadReceiptInfo(e),this._extractGroupInfo(w)}getElements(){return this._elements}isOnlineMessage(){return 0===this.messageLifeTime}setElement(e){Array.isArray(e)?this._elements=e:this._elements=[e],this._updatePayloadAndType()}convertElementsToBackendFormat(){return this._elements?Array.isArray(this._elements)?this._elements.map((e=>e.convertToBackendFormat())):this._elements.convertToBackendFormat():null}setRelayFlag(e){this._relayFlag=e}validateBeforeSend(){var e,t,n;return this._relayFlag?{isValid:!0}:(null===(e=this._elements)||void 0===e?void 0:e.length)>0?null===(n=null===(t=this._elements[0])||void 0===t?void 0:t.validateBeforeSend)||void 0===n?void 0:n.call(t):{isValid:!1}}_updatePayloadAndType(){this._elements[0]&&(this.payload=this._elements[0].content,this.type=this._elements[0].type)}_initC2CReadReceiptInfo(e){const{readReceiptSentByPeer:t,timestamp:n=0}=e;this.conversationType===Zn.CONV_C2C&&!0===this.needReadReceipt&&(this.readReceiptInfo.isPeerRead=1===t,this.readReceiptInfo.timestamp=n)}_extractGroupInfo(e){if(!e)return;const{From_AccountNick:t,From_AccountHeadurl:n,MsgFrom_AccountExtraInfo:s}=e,{NameCard:i}=s||{};"string"==typeof t&&(this.nick=t),"string"==typeof n&&(this.avatar=n),"string"==typeof i&&(this.nameCard=i)}reInitialize(e){e===this.from&&(this.isRead=!0),this._initSequence(e),this._concatConversationID(e),this.generateMessageID()}_concatConversationID(e){let t="";const n=this.conversationType;n!==Zn.CONV_SYSTEM?(t=n===Zn.CONV_C2C?e===this.from?this.to:this.from:this.to,this.conversationID=t?`${n}${t}`:null):this.conversationID=Zn.CONV_SYSTEM}_initSequence(e){0===this.clientSequence&&e&&(this.clientSequence=os(e)),0===this.sequence&&this.conversationType===Zn.CONV_C2C&&(this.sequence=this.clientSequence)}generateMessageID(){this.from===Zn.CONV_SYSTEM&&(this.senderTinyID="144115198244471703"),this.ID=`${this.senderTinyID}-${this.clientTime}-${this.random}`}setIsRead(e){this.isRead=e}}class as{static parseServerPushElement(e){const{MsgContent:t={}}=e,{Data:n,Ext:s,Desc:i}=t;return new as({data:n,description:i,extension:s})}constructor(e){this.type=Qn.MSG_CUSTOM;const{data:t="",description:n="",extension:s=""}=e;this.content={data:t,description:n,extension:s}}convertToBackendFormat(){const{data:e,description:t,extension:n}=this.content;return{MsgType:this.type,MsgContent:{Data:e,Ext:n,Desc:t}}}validateBeforeSend(){const{isEmpty:e}=Tt.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 cs{static parseServerPushElement(e){const{MsgContent:t={Text:""}}=e,{Text:n}=t;return new cs({text:n})}constructor(e){this.type=kt.MSG_TEXT,this.content={text:e.text||""}}validateBeforeSend(){var e,t;return(null===(t=null===(e=this.content)||void 0===e?void 0:e.text)||void 0===t?void 0:t.length)>0?{isValid:!0}:{isValid:!1,error:{message:"content can not be empty"}}}convertToBackendFormat(){const{text:e}=this.content;return{MsgType:this.type,MsgContent:{Text:e}}}}class ls{constructor(){this._elementClassMap={[Qn.MSG_CUSTOM]:as,[Qn.MSG_TEXT]:cs}}init(){An({apiName:"createCustomMessage",context:this}),An({apiName:"createTextMessage",context:this})}registerElementClass(e,t){var n;void 0!==(n=t).prototype&&"constructor"in n.prototype&&(this._elementClassMap[e]=t)}getElementClass(e){return this._elementClassMap[e]}createMessage(e){const{from:t,flow:n=ss.OUT}=e,{userId:s}=Tt.store.get("login")||{};this._isSendByCurrentInstance({from:t,flow:n,currentUser:s})?this._updateWithSenderInfo(e):this._isMultiEndpointSyncMessage({from:t,flow:n,currentUser:s})&&(e.flow=ss.OUT);const i=Object.assign(Object.assign({},e),{currentUser:s});return new rs(i)}createCustomMessage(e){const t=this._getCurrentUserId(),n=this.createMessage(Object.assign(Object.assign({},e),{from:t})),s=this._elementClassMap[Qn.MSG_CUSTOM];if(!n)return null;if(s){const t=new s(e.payload);n.setElement(t)}return n}createTextMessage(e){var t;if(!e)return null;const n="string"==typeof e.payload?e.payload:(null===(t=null==e?void 0:e.payload)||void 0===t?void 0:t.text)||"",s=new cs({text:n}),i=this._getCurrentUserId(),o=Tt.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{from:i}));return o.setElement(s),o}_updateWithSenderInfo(e){const{nick:t,avatar:n}=e,{userId:s,tinyID:i}=Tt.store.get("login")||{},o=mn.getUserProfile(s);return e.nick=t||(null==o?void 0:o.nick)||"",e.avatar=n||(null==o?void 0:o.avatar)||"",e.tinyID=e.tinyID||i||"",e.from=s,e.status=Pt.UNSENT,e.flow=ss.OUT,e}_isMultiEndpointSyncMessage(e){const{from:t,flow:n,currentUser:s}=e;return t===s&&n===ss.IN}_isSendByCurrentInstance(e){const{from:t,flow:n,currentUser:s}=e;return t===s&&n===ss.OUT}_getCurrentUserId(){var e;return null===(e=Tt.store.get("login"))||void 0===e?void 0:e.userId}}function ds(e){const t=e.lastIndexOf(".");return-1===t?e:e.slice(0,t)}function us(e){const{androidInfo:t={},androidOPPOChannelID:n=""}=e,s=t.OPPOChannelID||n;return Object.assign(Object.assign({},t),{Sound:ds(t.sound||""),OPPOChannelID:s,GoogleChannelID:t.FCMChannelID||""})}function _s(e){const{apnsInfo:t={},ignoreIOSBadge:n=!1,disableVoipPush:s}=e,i=!0===t.ignoreIOSBadge||!0===n?1:0;let o;return void 0!==s&&(o=!1===s?1:0),void 0!==t.disableVoipPush&&(o=!1===t.disableVoipPush?1:0),Object.assign(Object.assign({},t),{badgeMode:i,isVoipPush:o})}function hs(e){return Tt.utils.isPlainObject(e)?{PushFlag:!0===e.disablePush?1:0,Title:e.title||"",Desc:e.description||"",Ext:e.extension||"",ApnsInfo:_s(e),AndroidInfo:us(e)}:null}const{isPlainObject:gs}=Tt.utils;function fs(e,t={}){const{onlineUserOnly:n,messageControlInfo:s}=t;let{offlinePushInfo:i}=t;e.conversationType===Zn.CONV_C2C&&!0===n&&(i?i.disablePush=!0:i={disablePush:!0});let o="";"string"==typeof e.cloudCustomData&&e.cloudCustomData.length>0&&(o=e.cloudCustomData);const r=[];if(s&&gs(s)){const{excludedFromUnreadCount:e,excludedFromLastMessage:t,excludedFromContentModeration:n}=s;!0===e&&r.push("NoUnread"),!0===t&&r.push("NoLastMsg"),!0===n&&r.push("NoMsgCheck")}return{onlineUserOnly:n,cloudCustomData:o,messageControlInfo:r,offlinePushInfo:i}}function Es(e){const{webhookInfo:{disableCloudMessagePreHook:t=!1,disableCloudMessagePostHook:n=!1}={}}=e||{};if(!t&&!n)return;const s=[];return t&&s.push("ForbidBeforeSendMsgCallback"),n&&s.push("ForbidAfterSendMsgCallback"),s}function ps(e,t){return a(this,void 0,void 0,(function*(){const n=e.conversationType===Zn.CONV_GROUP?function(e,t){var n;const s=fs(e,t),{onlineUserOnly:i,cloudCustomData:o,messageControlInfo:r,offlinePushInfo:a}=s,c=JSON.parse(JSON.stringify(e.convertElementsToBackendFormat()));return{servcmd:"group_open_http_svc.send_group_msg",data:{From_Account:null===(n=Tt.store.get("login"))||void 0===n?void 0:n.userId,GroupId:e.to,MsgBody:c,CloudCustomData:o,Random:e.random,MsgPriority:e.priority,ClientSeq:e.clientSequence,GroupAtInfo:e._groupAtInfoList,OnlineOnlyFlag:i?1:0,MsgClientTime:e.clientTime,OfflinePushInfo:hs(a),SendMsgControl:i?void 0:r,NeedReadReceipt:!0===e.needReadReceipt?1:0,receiverList:null,SupportMessageExtension:!0===e.isSupportExtension?1:0,IsRelayMsg:!0===e._relayFlag?1:0,CustomModerationConfigID:e._cmConfigID,ForbidCallbackControl:Es(t)}}}(e,t):function(e,t){var n;const s=fs(e,t),{onlineUserOnly:i,cloudCustomData:o,messageControlInfo:r,offlinePushInfo:a}=s,c=!0===i?0:void 0,l=JSON.parse(JSON.stringify(e.convertElementsToBackendFormat()));return{servcmd:"openim.sendmsg",data:{From_Account:null===(n=Tt.store.get("login"))||void 0===n?void 0:n.userId,To_Account:e.to,MsgBody:l,CloudCustomData:o,MsgSeq:e.sequence,MsgRandom:e.random,MsgLifeTime:c,From_AccountNick:e.nick,From_AccountHeadurl:e.avatar,SendMsgControl:0!==c?r:void 0,MsgClientTime:e.clientTime,IsNeedReadReceipt:!0===e.needReadReceipt?1:0,SupportMessageExtension:!0===e.isSupportExtension?1:0,IsRelayMsg:!0===e._relayFlag?1:0,CustomModerationConfigID:e._cmConfigID,OfflinePushInfo:hs(a),forbidCallbackControl:Es(t)}}}(e,t),s=Tt.common.generateProtocolData(n),i=`${s.head.seq}${s.head.servcmd}`,o=yield Tt.channel.sendPacket(s,{requestId:i});return o?{time:o.MsgTime,messageDropReason:o.MsgDropReason,sequence:o.MsgSeq}:null}))}const{isPlainObject:Ss}=Tt.utils,{MSG_AUDIO:ms,MSG_FILE:vs,MSG_IMAGE:Is,MSG_VIDEO:Cs,MSG_MERGER:ys}=qt;class Os{init(){An({apiName:"sendMessage",context:this,matcher:e=>![ms,vs,Is,Cs,ys].includes(e[0].type)})}sendMessage(e,t){return a(this,void 0,void 0,(function*(){const n=Tt.ssoLog.createSSOLogData({method:"sendMessage"});if(!(e instanceof rs)){const e=new Jt({code:jt.MSG_INSTANCE_REQUIRED});throw n.setError(e).end(),e}const s=e.validateBeforeSend();if(!s.isValid){const{code:e,message:t=""}=s.error||{},i=new Jt({code:e,message:t});throw n.setError(i).end(),i}let i=!1;const{messageDataHandler:o}=Tt.message||{};try{const{messageControlInfo:s}=t||{};let r=null;if(o.addRandomOfSentMessage(e.random),e.conversationType===Zn.CONV_C2C?(i=!0===(null==t?void 0:t.onlineUserOnly),r=yield ps(e,t)):e.conversationType===Zn.CONV_GROUP&&(r=yield ps(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=o.findMessage(e.ID);t&&(console.log(`sendMessage resend ok. ID:${t.ID}`),o.deleteConversationMessage(t))}return e.status=Pt.SUCCESS,e.time=l,e.conversationType===Zn.CONV_GROUP&&(e.sequence=c),i?e._onlineOnlyFlag=!0:(o.storeConversationMessage(e),this._applySentMessageControlInfo(e,s),this._emitOnlineMessageSent(e)),n.setLogInfo({message:`options: ${JSON.stringify(t)}`}).end(),{code:0,data:{message:e}}}}catch(t){e.status=Pt.FAIL,o.removeRandomOfSentMessage(e.random);const{errorCode:n,errorInfo:s=""}=t||{};this._hasRiskContent(n)&&(e.hasRiskContent=!0),i||this._isRejectedByRestApi(n)||o.storeConversationMessage(e);const r=new Jt({code:n,message:s,data:{message:e}});throw this._logSendMessageError({message:e,error:r}),r}}))}_hasRiskContent(e){return 80001===e||80004===e}_isRejectedByRestApi(e){return e>=10100&&e<=10200||e>=120001&&e<=13e4}_logSendMessageError({message:e,error:t}){const n=Tt.ssoLog.createSSOLogData({method:"sendMessage"});let s=`head.seq: type:${e.type} from:${e.from} to:${e.to}`;if(Tt.utils.IN_BROWSER){if("connection"in navigator){const e=navigator.connection;s+=` downlink:${e.downlink} effectiveType:${e.effectiveType} rtt:${e.rtt}`}if("memory"in window.performance){const e=window.performance.memory;s+=` usedJSHeapSize:${e.usedJSHeapSize} totalJSHeapSize:${e.totalJSHeapSize} jsHeapSizeLimit:${e.jsHeapSizeLimit}`}}n.setLogInfo({message:s}).setError(t).end()}_emitOnlineMessageSent(e){const t=e._isExcludedFromLastMessage?"":e,{conversationID:n,conversationType:s}=e;Tt.notificationCenter.emitInnerEvent(bt.NEW_MESSAGE,{result:{conversationUpdateFieldList:[{conversationID:n,type:s,message:e,lastMessage:t,unreadCount:0}]}})}_applySentMessageControlInfo(e,t){t&&Ss(t)&&(!0===t.excludedFromLastMessage&&(e._isExcludedFromLastMessage=!0),!0===t.excludedFromUnreadCount&&(e._isExcludedFromUnreadCount=!0))}_logRateLimitInfo(e,t){const n=Tt.ssoLog.createSSOLogData({method:"messageDropReason"}),s=`from:${e.from} to:${e.to} sequence:${t} messageDropReason:${messageDropReason}`;n.setLogInfo({message:s}).end(),console.warn(`sendMessage ${s}`)}_updateNickAndAvatarOfSentMessageByMe(e){const{messageDataHandler:t}=Tt.message||{};let n=!1;const{conversationID:s}=e,i=t.getLatestMsgSentByMe(s);if(i){const{nick:o,avatar:r}=i;o===e.nick&&r===e.avatar||(n=!0),n&&t.updateNickAndAvatarOfSentMessage({conversationID:s,latestNick:e.nick,latestAvatar:e.avatar,isSentByMe:!0})}}}function Ms(e){const{From_AccountHeadurl:t,From_AccountNick:n,IsNeedReadReceipt:s,IsPeerRead:i,IsSyncMsg:o,MsgBody:r,MsgClientTime:a,MsgLifeTime:c,MsgRandom:l,MsgSeq:d,MsgTimeStamp:u,SendMsgControl:_,SupportMessageExtension:h,TinyId:g,MsgCheckResult:f,CloudCustomData:E,MsgVersion:p,MsgFlagBits:S,RevokerInfo:m}=e;let v,{From_Account:I,To_Account:C}=e;if(1===o){const e=C;C=I,I=e}if(m){const{Reason:e,Revoker_Account:t,Revoker_FromUin:n}=m;v={reason:e,revoker:t,revokerFromUin:n,userID:t}}return{from:I,avatar:t,nick:n,needReadReceipt:1===s,isSyncMessage:o,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:S,readReceiptSentByPeer:i,elements:Ns(r)}}function Ts(e){const{From_Account:t,MsgBody:n,MsgClientTime:s,MsgRandom:i,MsgSeq:o,MsgTimeStamp:r,To_Account:a,MsgVersion:c,CloudCustomData:l}=e;return{from:t,clientTime:s,random:i,sequence:o,time:r,to:a,elements:Ns(n),messageVersion:c,cloudCustomData:l}}function As(e){const{ClientSeq:t,From_Account:n,GroupInfo:s,MsgBody:i,MsgClientTime:o,MsgRandom:r,MsgSeq:a,MsgTimeStamp:c,SendMsgControl:l,SupportMessageExtension:d,TinyId:u,ToGroupId:_,CloudCustomData:h,MsgVersion:g,MsgCheckResult:f,NeedReadReceipt:E,IsPlaceMsg:p,RevokerInfo:S,GroupAtInfo:m}=e;let v,I=Xn.MSG_PRIORITY_NORMAL;if(Object.keys(es).includes(String(e.MsgPriority))&&(I=es[e.MsgPriority]),S){const{Reason:e,Revoker_Account:t,Revoker_FromUin:n}=S;v={reason:e,revoker:t,revokerFromUin:n,userID:t}}const C=function(e){const t=[];Array.isArray(e)&&e.forEach((e=>{e.GroupAtAllFlag===ts?t.push(e.GroupAt_Account):e.GroupAtAllFlag===ns&&t.push(qt.MSG_AT_ALL)}));return t}(m);return{clientSequence:t,from:n,groupProfile:s,clientTime:o,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:Ns(i)}}function Ns(e){if(!e)return null;if(Array.isArray(e))return e.map((e=>{const t=Tt.message.messageFactory.getElementClass(e.MsgType);return null==t?void 0:t.parseServerPushElement(e)}));const t=Tt.message.messageFactory.getElementClass(e.MsgType);return null==t?void 0:t.parseServerPushElement(e)}function Ds({conversationUpdateFields:e,message:t}){const{conversationID:n,conversationType:s,conversationSubType:i,flow:o,_isExcludedFromUnreadCount:r,_isExcludedFromLastMessage:a}=t,c=a?"":t,l=!r&&o===ss.IN;e.has(n)?(e.get(n).lastMessage=c,l&&e.get(n).unreadCount++):e.set(n,{conversationID:n,type:s,subType:i,unreadCount:l?1:0,lastMessage:c})}var Rs=Object.freeze({__proto__:null,autoIncrementIndex:os,parseServerGroupMessage:As,parseServerPushC2CModifyMessage:Ts,parseServerPushMessage:Ms,parseServerPushMessageElement:Ns,updateConversationFields:Ds});class bs{constructor(e){this.value=e,this.next=null}}class ws{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 bs(e);this.head?(this.tail.next=t,this.tail=t):(this.head=t,this.tail=t),this.size+=1}delete(e){if(!this.head)return;if(this.head.value===e)return void(this.head=this.head.next);let t=this.head;for(;t.next;){if(t.next.value===e)return void(t.next=t.next.next);t=t.next}}has(e){if(!this.head)return!1;let t=this.head,n=!1;for(;t;)t.value===e&&(n=!0),t=t.next;return n}removeHead(){this.head&&(this.head===this.tail?(this.head=null,this.tail=null):this.head=this.head.next,this.size-=1)}peek(){var e;return null===(e=this.head)||void 0===e?void 0:e.value}length(){return this.size}isEmpty(){return 0===this.size}isFull(){return this.size===this.capacity}clear(){this.head=null,this.tail=null,this.size=0}}class Ls{constructor(){this._sparseMessagesByConversation=new Map,this._latestMessageSentByPeerMap=new Map,this._latestMessageSentByMeMap=new Map,this._randomOfSentMessageList=new ws(100),Tt.notificationCenter.subscribeInnerEvent(bt.LOGOUT,this._reset,this),Tt.notificationCenter.subscribeInnerEvent(bt.DESTROY,this._dispose,this)}get _messagesByConversation(){return Sn.getMessages()}storeConversationMessage(e,t=!1){const{conversationID:n}=e;if(!n)return!1;if(this._messagesByConversation.has(n)||this._messagesByConversation.set(n,new Map),this._shouldSkipStoreMessage(e,t))return!1;const s=this._getUniqueIdOfMessage(e);return this._messagesByConversation.get(n).set(s,e),this._updateLatestMessageMap(e),!0}_updateLatestMessageMap(e){const{conversationID:t}=e;"out"===e.flow?this._setLatestMsgSentByMe(t,e):t.startsWith("C2C")&&this._setLatestMsgSentByPeer(t,e)}_shouldSkipStoreMessage(e,t){const n=this._getUniqueIdOfMessage(e),s=this._messagesByConversation.get(e.conversationID);if(null==s?void 0:s.has(n)){const e=null==s?void 0:s.get(n);if(!t||!0===(null==e?void 0:e.isModified))return!0}return!1}deleteConversationMessage(e){var t;const{conversationID:n=""}=e,s=this._getUniqueIdOfMessage(e);this._messagesByConversation.has(n)&&(null===(t=this._messagesByConversation.get(n))||void 0===t||t.delete(s))}modifyConversationMessage(e,t){var n;if(!this._messagesByConversation.has(e)&&!this._sparseMessagesByConversation.has(e))return{isUpdated:!1,message:null};const s=this._getUniqueIdOfMessage(t),i=this._getMessageFromLocalMessage(e,s);if(i){const{messageVersion:s,elements:o,cloudCustomData:r,checkResult:a=0}=t,c=a>1;if(console.log(`conversationToMessageMap modifyConversationMessage localVersion:${i.version} remoteVersion:${s}`),i.version<s){const t=this._getUniqueIdOfMessage(i),a=JSON.parse(JSON.stringify(o));return(null===(n=this._messagesByConversation.get(e))||void 0===n?void 0:n.has(t))?Sn.updateMessage(e,[t],{isModified:!0,version:s,_elements:a,payload:a[0].content,type:a[0].type,cloudCustomData:r,hasRiskContent:c,operation:Ut.modify}):(i.version=s,i._elements=JSON.parse(JSON.stringify(o)),i.payload=i._elements[0].content,i.type=i._elements[0].type,i.cloudCustomData=r,i.isModified=!0,i.hasRiskContent=c),{isUpdated:!0,message:i}}return{isUpdated:!1,message:i}}return{isUpdated:!1,message:null}}_getMessageFromLocalMessage(e,t){var n;if(this._messagesByConversation.has(e))return null===(n=this._messagesByConversation.get(e))||void 0===n?void 0:n.get(t);if(this._sparseMessagesByConversation.has(e)){const n=[...this._sparseMessagesByConversation.get(e).values()];for(let e=0;e<n.length;e++)if(this._getUniqueIdOfMessage(n[e])===t)return n[e]}return null}findMessage(e){let t=null;const n=Array.from(this._messagesByConversation.values());for(const s of n){if(t=Array.from(s.values()).find((t=>t.ID===e))||null,t)break}if(!t){const n=Array.from(this._sparseMessagesByConversation.values());for(const s of n)if(t=s.get(e)||null,t)break}return t}deleteConversationMessageList(e){this._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:n,revoker:s}){const i=this._messagesByConversation.get(e);let o=null;if(i){const r=Array.from(i.values());if(o=this._findMessageBySequenceAndRandom({messageList:r,random:n,sequence:t}),o){const t=this._getUniqueIdOfMessage(o);return Sn.updateMessage(e,[t],{isRevoked:!0,revoker:s,operation:Ut.revoke}),o}}if(this._sparseMessagesByConversation.has(e)){const i=Array.from(this._sparseMessagesByConversation.get(e).values());if(o=this._findMessageBySequenceAndRandom({messageList:i,random:n,sequence:t}),o)return o.isRevoked=!0,o.revoker=s,o}}_findMessageBySequenceAndRandom({messageList:e,sequence:t,random:n}){for(let s=0;s<e.length;s+=1){const i=e[s];if(i.sequence===t&&(c(n)||i.random===n))return i}return null}prependLocalMessageList(e){const{messageList:t,conversationID:n}=e;if(0===t.length)return[];const s=[],i=[],o=this._messagesByConversation.get(n)||new Map;for(const e of t){const t=this._getUniqueIdOfMessage(e);o.has(t)||(s.push(e),i.push([t,e]))}if(i.length>0){const e=new Map([...i,...o.entries()]);this._messagesByConversation.set(n,e),this._updateLatestMessageSentByMe(n),this._updateLatestMessageSentByPeer(n)}return s}storeSparseMessageList(e){if(0===e.length)return;const{conversationID:t}=e[0],n=e.length;this._sparseMessagesByConversation.has(t)||this._sparseMessagesByConversation.set(t,new Map);const s=this._sparseMessagesByConversation.get(t);for(let t=0;t<n;t++){const n=e[t];s.has(n.ID)||s.set(n.ID,n)}}_updateLatestMessageSentByMe(e){var t;const n=Array.from((null===(t=this._messagesByConversation.get(e))||void 0===t?void 0:t.values())||[]);if(0!==n.length)for(let t=n.length-1;t>=0;t--)if("out"===n[t].flow){this._setLatestMsgSentByMe(e,n[t]);break}}_updateLatestMessageSentByPeer(e){var t;const n=Array.from((null===(t=this._messagesByConversation.get(e))||void 0===t?void 0:t.values())||[]);if(0!==n.length&&e.startsWith("C2C"))for(let t=n.length-1;t>=0;t--)if("in"===n[t].flow){this._setLatestMsgSentByPeer(e,n[t]);break}}_getUniqueIdOfMessage(e){const{from:t,to:n,random:s,sequence:i,time:o}=e;return`${t}-${n}-${s}-${i}-${o}`}_setLatestMsgSentByPeer(e,t){this._latestMessageSentByPeerMap.set(e,t)}_setLatestMsgSentByMe(e,t){this._latestMessageSentByMeMap.set(e,t)}getLatestMsgSentByPeer(e){return this._latestMessageSentByPeerMap.get(e)}getLatestMsgSentByMe(e){return this._latestMessageSentByMeMap.get(e)}addRandomOfSentMessage(e){this._randomOfSentMessageList.append(e)}removeRandomOfSentMessage(e){this._randomOfSentMessageList.delete(e)}updateNickAndAvatarOfSentMessage(e){const{conversationID:t="",latestAvatar:n,latestNick:s,isSentByMe:i=!0}=e,o=this._messagesByConversation.get(t);if(!o)return;const r=Array.from(o.values()),a=i?"out":"in";r.forEach((e=>{const{nick:t,avatar:i,flow:o}=e;o===a&&(t!==s&&(e.nick=s),i!==n&&(e.avatar=n))}))}isInMessageList(e){var t;const{conversationID:n}=e;if(!n)return!1;if(!this._messagesByConversation.has(n))return!1;const s=this._getUniqueIdOfMessage(e);return null===(t=this._messagesByConversation.get(n))||void 0===t?void 0:t.has(s)}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(),Tt.notificationCenter.unSubscribeInnerEvent(bt.LOGOUT,this._reset,this),Tt.notificationCenter.unSubscribeInnerEvent(bt.DESTROY,this._dispose,this)}}class ks{init(){An({apiName:"modifyMessage",context:this})}modifyMessage(e){return a(this,void 0,void 0,(function*(){const t=Tt.ssoLog.createSSOLogData({method:"modifyMessage"}),{to:n,payload:s,sequence:i,conversationType:o,random:r,time:c,from:l,type:d}=e;if(!this._canModifyMessageElement(d))return void t.setLogInfo({message:`can not modify message element. message type: ${d}`}).end();const u=e.getElements();u.length>1&&(u[0].type=d,u[0].content=s);try{let s=null,d=null;if(t.setLogInfo({message:`to:${n}`}),o===Zn.CONV_C2C)return s=yield function(e){return a(this,void 0,void 0,(function*(){const t="openim.modify_c2c_msg",{from:n,to:s,version:i=0,sequence:o,random:r,time:a,type:c,cloudCustomData:l}=e,d=Tt.common.generateProtocolData({servcmd:t,data:{From_Account:n,To_Account:s,MsgVersion:i,MsgSeq:o,MsgRandom:r,MsgTime:a,MsgType:c,MsgBody:e.convertElementsToBackendFormat(),CloudCustomData:l}}),u=`${d.head.seq}${t}`;try{const e=yield Tt.channel.sendPacket(d,{requestId:u});if(e){const{MsgBody:t,MsgVersion:n,CloudCustomData:s}=e;return{elements:t,messageVersion:n,cloudCustomData:s}}}catch(e){console.warn(e)}}))}(e),t.end(),d={conversationType:o,from:l,to:n,time:c,random:r,sequence:i,elements:null==s?void 0:s.elements,cloudCustomData:null==s?void 0:s.cloudCustomData,messageVersion:null==s?void 0:s.messageVersion,conversationID:`${o}${n}`},this._handleC2CModifyMessageSuccess(d),{code:0,data:{message:e}}}catch(e){const{errorCode:t}=e||{},n=new Jt({functionName:"modifyMessage",code:t});throw this._logModifyMessageError(n),n}}))}_logModifyMessageError(e){Tt.ssoLog.getSSOLogData("modifyMessage").setError(e).end()}_handleC2CModifyMessageSuccess(e){const{conversationID:t}=e,{isUpdated:n,message:s}=Tt.message.messageDataHandler.modifyConversationMessage(t,e);!0===n&&Tt.notificationCenter.emitOuterEvent(Dt.MESSAGE_MODIFIED,[s]),Tt.notificationCenter.emitInnerEvent(bt.MESSAGE_MODIFIED,{conversationID:t,message:s})}_canModifyMessageElement(e){return[Qn.MSG_TEXT,Qn.MSG_CUSTOM,Qn.MSG_LOCATION,Qn.MSG_FACE].includes(e)}}class Ps{init(){const{notificationCenter:e}=Tt,{InnerEventSubType:t}=e;_n.registerWorkflowStep(Yt.RECEIVE_C2C_NEW_MESSAGE,Wt.HANDLE_C2C_NEW_MESSAGE,this._handleC2CMessagePush,this),_n.registerWorkflowStep(Yt.RECEIVE_C2C_NEW_MESSAGE,Wt.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterReceiveNewMessage,this),_n.registerWorkflowStep(Yt.SYNC_SERVER_INFO_AFTER_RE_ONLINE,Wt.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterSyncUnreadMessage,this),e.subscribeInnerEvent(bt.MESSAGE_PUSH,t.C2C_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),e.subscribeInnerEvent(bt.MESSAGE_PUSH,t.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),e.subscribeInnerEvent(bt.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(e){_n.executeWorkflow(Yt.RECEIVE_C2C_NEW_MESSAGE,e)}_handleC2CMessagePush(e){const t=e.data||{},{messageDataHandler:n}=Tt.message||{},s=[],i=new Map;return t.C2cMsgArray.forEach((e=>{const t=this._generateC2CMessage(e);this._updateMessageProfile(t);let o=1===t.isModified;if(n.isMessageSentByCurrentInstance(t)?t.isModified=o:o=!1,t.isOnlineMessage())t._onlineOnlyFlag=!0,n.isMessageSentByCurrentInstance(t)||s.push(t);else if(!n.isInMessageList(t)){n.storeConversationMessage(t)&&Ds({conversationUpdateFields:i,message:t}),n.isMessageSentByCurrentInstance(t)&&!o||s.push(t)}})),{conversationUpdateFieldList:[...i.values()],messages:s}}_emitMessageEventsAfterReceiveNewMessage(e){var t;const{messages:n=[]}=(null===(t=e.result)||void 0===t?void 0:t[Wt.HANDLE_C2C_NEW_MESSAGE])||{};this._emitMessageEvents(n)}_emitMessageEventsAfterSyncUnreadMessage(e){var t;const{messages:n=[]}=(null===(t=e.result)||void 0===t?void 0:t[Wt.UNREAD_MESSAGE_SYNC])||{};this._emitMessageEvents(n)}_emitMessageEvents(e){const t=(null==e?void 0:e.filter((e=>!0===(null==e?void 0:e.isModified))))||[];t.length>0&&Tt.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:t});const n=null==e?void 0:e.filter((e=>!(null==e?void 0:e.isModified)));n.length>0&&Tt.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:n})}_generateC2CMessage(e){const t=Zn.CONV_C2C,n=Ms(e),s=Tt.message.messageFactory.createMessage(Object.assign(Object.assign({},n),{conversationType:t,flow:ss.IN})),{elements:i}=n;return s.setElement(i),s}_updateMessageProfile(e){var t;const{messageDataHandler:n}=Tt.message||{},s=null===(t=Tt.store.get("login"))||void 0===t?void 0:t.userId,{from:i,nick:o,avatar:r,conversationID:a=""}=e;if(i!==s){const t=n.getLatestMsgSentByPeer(a);if(t){const{nick:s,avatar:i}=t;c(o)||c(r)?(e.nick=l(s)?s:e.nick,e.avatar=l(i)?i:e.avatar):o===s&&r===i||(n.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:o,latestAvatar:r,isSentByMe:!1}),this._updateConversationUserProfile({conversationID:a,nick:o,avatar:r}))}}else{const e=n.getLatestMsgSentByMe(a);!e||o===e.nick&&r===e.avatar||n.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:o,latestAvatar:r,isSentByMe:!0})}}_updateConversationUserProfile(e){const{conversationID:t,nick:n,avatar:s}=e,i=En.getConversation(t),{userProfile:o={}}=i||{};o.avatar===s&&o.nick===n||En.updateConversation(t,{userProfile:Object.assign(Object.assign({},o),{nick:n,avatar:s})})}_updateMessageListDueToModify(e){const{conversationID:t}=e,{isUpdated:n,message:s}=Tt.message.messageDataHandler.modifyConversationMessage(t,e);!0===n&&Tt.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[s]}),Tt.notificationCenter.emitInnerEvent("ModifyMessageSuccess",e)}_handleC2CMessageModify(e){e.C2cMsgModNotifys.forEach((e=>{var t;const n=Zn.CONV_C2C;let s=Ts(e);const{to:i,from:o}=s;let r=`${n}${i}`;i===(null===(t=Tt.store.get("login"))||void 0===t?void 0:t.userId)&&(r=`${n}${o}`),s=Object.assign({conversationType:n,conversationID:r},s),this._updateMessageListDueToModify(s)}))}_dispose(){const{notificationCenter:e}=Tt,{InnerEventSubType:t}=e;Tt.notificationCenter.unSubscribeInnerEvent(bt.MESSAGE_PUSH,t.C2C_REALTIME_MESSAGE,this._handleC2CMessagePush,this),Tt.notificationCenter.unSubscribeInnerEvent(bt.MESSAGE_PUSH,t.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),Tt.notificationCenter.unSubscribeInnerEvent(bt.DESTROY,this._dispose,this)}}class Us{init(){const{notificationCenter:e}=Tt,{InnerEventSubType:t}=e;_n.registerWorkflowStep(Yt.RECEIVE_GROUP_NEW_MESSAGE,Wt.HANDLE_GROUP_NEW_MESSAGE,this._handleGroupMessagePush,this),_n.registerWorkflowStep(Yt.RECEIVE_GROUP_NEW_MESSAGE,Wt.EMIT_GROUP_MESSAGE_EVENT,this._emitMessageEvents,this),e.subscribeInnerEvent(bt.MESSAGE_PUSH,t.GROUP_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),e.subscribeInnerEvent(bt.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(e){_n.executeWorkflow(Yt.RECEIVE_GROUP_NEW_MESSAGE,e)}_handleGroupMessagePush(e){const t=e.data||{},{messageDataHandler:n}=Tt.message,s=[],i=new Map,o=null==t?void 0:t.GroupMsgArray;return null==o||o.forEach((e=>{const t=this._generateGroupMessage(e);this.updateMessageProfile(t);let o=1===t.isModified;if(n.isMessageSentByCurrentInstance(t)?t.isModified=o:o=!1,t.isOnlineMessage())t._onlineOnlyFlag=!0,n.isMessageSentByCurrentInstance(t)||s.push(t);else if(!n.isInMessageList(t)){n.storeConversationMessage(t)&&(s.push(t),Ds({conversationUpdateFields:i,message:t}))}})),{conversationUpdateFieldList:[...i.values()],messages:s}}_emitMessageEvents(e){var t;const{messages:n}=(null===(t=e.result)||void 0===t?void 0:t[Wt.HANDLE_GROUP_NEW_MESSAGE])||{},s=(null==n?void 0:n.filter((e=>!0===(null==e?void 0:e.isModified))))||[];s.length>0&&Tt.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:s});const i=(null==n?void 0:n.filter((e=>!(null==e?void 0:e.isModified))))||[];i.length>0&&Tt.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:i})}_generateGroupMessage(e){const t=Zn.CONV_GROUP,n=As(e),s=Tt.message.messageFactory.createMessage(Object.assign(Object.assign({},n),{conversationType:t,flow:ss.IN})),{elements:i}=n;return s.setElement(i),s}updateMessageProfile(e){var t;const{messageDataHandler:n}=Tt.message||{},s=null===(t=Tt.store.get("login"))||void 0===t?void 0:t.userId,{from:i,nick:o,avatar:r,conversationID:a=""}=e;if(i===s){const e=n.getLatestMsgSentByMe(a);!e||o===e.nick&&r===e.avatar||n.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:o,latestAvatar:r,isSentByMe:!0})}}_updateMessageListDueToModify(e){const{conversationID:t}=e,{isUpdated:n,message:s}=Tt.message.messageDataHandler.modifyConversationMessage(t,e);!0===n&&Tt.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[s]}),Tt.notificationCenter.emitInnerEvent(bt.MESSAGE_MODIFIED,e)}_dispose(){const{notificationCenter:e}=Tt,{InnerEventSubType:t}=e;Tt.notificationCenter.unSubscribeInnerEvent("im_open_push.msg_push",t.GROUP_REALTIME_MESSAGE,this._handleGroupMessagePush,this),Tt.notificationCenter.unSubscribeInnerEvent(bt.DESTROY,this._dispose,this)}}class Fs{constructor(){this.c2cMessageReceiver=new Ps,this.groupMessageReceiver=new Us}init(){this.c2cMessageReceiver.init(),this.groupMessageReceiver.init()}}const Gs={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 xs={createCustomMessage:!0,sendMessage:!0,modifyMessage:!0};class Bs{constructor(){this.messageHelper=Rs,this.messageFactory=new ls,this.messageSender=new Os,this.messageAction=new ks,this.messageReceiver=new Fs,this.messageDataHandler=new Ls,this.messageSender.init(),this.messageFactory.init(),this.messageAction.init(),this.messageReceiver.init(),cn({auth:xs,params:Gs})}}function $s(e){return mn.getFriendMap().has(e)}function Vs(){return Tt.store.get("login").userId}const qs="User",js="Tag_Profile_IM_",Ys=100,Ws={NICK:`${js}Nick`,GENDER:`${js}Gender`,BIRTHDAY:`${js}BirthDay`,LOCATION:`${js}Location`,SELFSIGNATURE:`${js}SelfSignature`,ALLOWTYPE:`${js}AllowType`,LANGUAGE:`${js}Language`,AVATAR:`${js}Image`,MESSAGESETTINGS:`${js}MsgSettings`,ADMINFORBIDTYPE:`${js}AdminForbidType`,LEVEL:`${js}Level`,ROLE:`${js}Role`},Ks="USER_STATUS",Hs=1,zs={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:[]},Js=new Map([[Ws.NICK,"nick"],[Ws.GENDER,"gender"],[Ws.BIRTHDAY,"birthday"],[Ws.LOCATION,"location"],[Ws.SELFSIGNATURE,"selfSignature"],[Ws.ALLOWTYPE,"allowType"],[Ws.LANGUAGE,"language"],[Ws.AVATAR,"avatar"],[Ws.MESSAGESETTINGS,"messageSettings"],[Ws.ADMINFORBIDTYPE,"adminForbidType"],[Ws.LEVEL,"level"],[Ws.ROLE,"role"]]);var Zs=new class{createProfile(e,t){const n={userID:e,profileCustomField:[]};return t.forEach((e=>{const{tag:t,value:s}=e;t&&t.indexOf("Tag_Profile_Custom")>-1?n.profileCustomField.push({key:t,value:s}):Js.has(t)&&(n[Js.get(t)]=s)})),Object.assign(Object.assign({},zs),n)}parseProfileItem(e=[]){const t=[];return e.forEach((e=>{t.push({tag:e.Tag,value:e.Value})})),t}parseProfileList(e=[]){const t=[];return e.forEach((e=>{t.push({tag:e.Tag,value:e.ValueBytes})})),t}convertParamsToProfile(e){const t=[];return Object.keys(e).forEach((n=>{t.push({tag:Ws[n.toUpperCase()],value:e[n]})})),t}normalizeProfileFields(e){const t={};return e.forEach((e=>{const{tag:n,value:s}=e;if(Js.has(n)){const e=Js.get(n);t[e]=s}})),t}};const{generateProtocolData:Xs}=Tt.common;function Qs(e){return a(this,void 0,void 0,(function*(){const t="profile.portrait_get_all",n={From_Account:Vs(),UserItem:[]};e.forEach((e=>{n.UserItem.push({CustomSequence:0,StandardSequence:0,To_Account:e})}));const s=Xs({servcmd:t,data:n}),i=`${s.head.seq}${t}`,o=yield Tt.channel.sendPacket(s,{requestId:i});if(o)return function(e){const{ActionStatus:t,ErrorCode:n,ErrorDisplay:s,ErrorInfo:i,UserProfileItem:o}=e,r=[];return o.map((e=>{const{To_Account:t,CustomSequence:n,ResultCode:s,ResultInfo:i,StandardSequence:o,ProfileItem:a}=e,c=Zs.parseProfileItem(a);r.push({userId:t,customSequence:n,resultCode:s,resultInfo:i,standardSequence:o,profileItem:c})})),{actionStatus:t,errorCode:n,errorDisplay:s,errorInfo:i,userProfile:r}}(o)}))}const{isEmpty:ei}=Tt.utils;class ti{init(){An({apiName:"getMyProfile",context:this}),An({apiName:"getUserProfile",context:this}),An({apiName:"updateMyProfile",context:this}),this.createProfile=Zs.createProfile.bind(Zs);const{notificationCenter:e}=Tt;_n.registerWorkflowStep(Yt.SYNC_SERVER_INFO_AFTER_LOGIN,Wt.USER_PROFILE_SYNC,this.getMyProfileCacheThenServer,this),e.subscribeInnerEvent(bt.MESSAGE_PUSH,e.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),e.subscribeInnerEvent(bt.LOGOUT,this._reset,this),e.subscribeInnerEvent(bt.DESTROY,this._dispose,this)}getMyProfile(){return a(this,void 0,void 0,(function*(){const e=Tt.ssoLog.createSSOLogData({method:"getMyProfile"});try{const t=Vs(),n=yield Qs([t]);if(n){const e=this._handleProfileFormResponse(n)[0];return mn.getUserProfileMap().set(t,e),{code:0,data:e}}e.end()}catch(t){const{errorCode:n,errorInfo:s}=t,i=new Jt({functionName:"getMyProfile",code:n,message:s});throw e.setError(i).end(),t}}))}getUserProfile(e){return a(this,void 0,void 0,(function*(){const t=Tt.ssoLog.createSSOLogData({method:"getUserProfile"});try{let{userIDList:n}=e;n.length>Ys&&(n=n.slice(0,Ys));const{userIdListToRequest:s,userIdListToCache:i}=this._filterRequestAndCacheUsers(n),o=[];i.forEach((e=>{const t=mn.getUserProfile(e);o.push(t)}));const r=`userIDList.length:${n.length}`;if(0===s.length)return t.setLogInfo({message:r}).end(),{code:0,data:o};const a=yield Qs(s);if(a){const e=this._handleProfileFormResponse(a);e.forEach((e=>{$s(e.userID)&&mn.getUserProfileMap().set(e.userID,e)}));const n=e.concat(o);return t.setLogInfo({message:r}).end(),{code:0,data:n}}}catch(e){const{errorCode:n}=e,s=new Jt({functionName:"getUserProfile",code:n});throw t.setError(s).end(),s}}))}getMyProfileCacheThenServer(){return a(this,void 0,void 0,(function*(){const e=Vs(),t=mn.getUserProfileMap().has(e);return t?{code:0,data:t}:this.getMyProfile()}))}updateMyProfile(e){return a(this,void 0,void 0,(function*(){const t=Tt.ssoLog.createSSOLogData({method:"updateMyProfile"}),n=Vs(),s={};for(const t in e)void 0!==e[t]&&(s[t]=e[t]);const i=Zs.convertParamsToProfile(s);try{const e={From_Account:n,ProfileItem:i};t.setLogInfo({message:JSON.stringify(i)}),yield function(e){return a(this,void 0,void 0,(function*(){const t="profile.portrait_set",n=Xs({servcmd:t,data:e}),s=`${n.head.seq}${t}`,i=yield Tt.channel.sendPacket(n,{requestId:s});if(i){const{ActionStatus:e,ErrorCode:t,ErrorDisplay:n,ErrorInfo:s}=i;return{actionStatus:e,errorCode:t,errorDisplay:n,errorInfo:s}}}))}(e);const o=mn.getUserProfile(n);let r;r=o?Object.assign(Object.assign({},o),s):Zs.createProfile(n,i);return!Qt(o,r,["lastUpdatedTime","profileCustomField"])&&Tt.notificationCenter.emitOuterEvent(Dt.PROFILE_UPDATED,{name:Dt.PROFILE_UPDATED,data:[r]}),r.lastUpdatedTime=Date.now(),mn.getUserProfileMap().set(n,r),t.end(),{code:0,data:r}}catch(e){const{errorCode:n,errorInfo:s}=e,i=new Jt({functionName:"updateMyProfile",code:n,message:s});throw t.setError(i).end(),i}}))}updateMyNickAndAvatar(e){return a(this,void 0,void 0,(function*(){const t=Vs(),n=Date.now(),s=mn.getUserProfile(t);let i={};i=s?Object.assign(s,e):Zs.createProfile(t,e),i.lastUpdatedTime=n,mn.getUserProfileMap().set(t,i)}))}_onProfileDataModify(e){const t=function(e){const{Profile_Account:t,PushType:n,ProfileList:s}=e;return{userId:t,pushType:n,profileList:Zs.parseProfileList(s)}}(e.ProfileDataMod[0]);if(ei(t))return;const{isProfileUpdated:n,profile:s}=this._handleProfileModified(t);n&&(Tt.notificationCenter.emitInnerEvent(bt.PROFILE_UPDATE,{name:bt.PROFILE_UPDATE,data:[s]}),Tt.notificationCenter.emitOuterEvent(Dt.PROFILE_UPDATED,{name:Dt.PROFILE_UPDATED,data:[s]}))}_dispose(){const{notificationCenter:e}=Tt;e.unSubscribeInnerEvent(bt.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(bt.MESSAGE_PUSH,e.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),e.unSubscribeInnerEvent(bt.DESTROY,this._dispose,this),this._reset()}_handleProfileModified(e){const{userId:t,profileList:n}=e,s=mn.getUserProfile(t);if(!s||!$s(t))return{isProfileUpdated:!1,profile:null};const i=Zs.normalizeProfileFields(n),o=Object.keys(i).some((e=>s[e]!==i[e]));if(!o)return{isProfileUpdated:!1,profile:s};const r=Date.now(),a=Object.assign(Object.assign(Object.assign({},s),i),{lastUpdatedTime:r});return mn.getUserProfileMap().set(t,a),En.updateConversation(`C2C${t}`,{userProfile:a}),{isProfileUpdated:o,profile:a}}_filterRequestAndCacheUsers(e){const t=[],n=[];return e.forEach((e=>{const s=mn.getUserProfileMap().has(e);$s(e)&&s?n.push(e):t.push(e)})),{userIdListToRequest:t,userIdListToCache:n}}_handleProfileFormResponse(e){const{userProfile:t}=e;if(!Array.isArray(t))return[];const n=t.filter((e=>"@TLS#NOT_FOUND"!==e.userId&&""!==e.userId&&!ei(e.profileItem))),s=Date.now();return n.map((e=>{const t=Zs.createProfile(e.userId,e.profileItem);return t.lastUpdatedTime=s,t}))}_reset(){mn.getUserProfileMap().clear()}}const ni=new Map,si=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];for(let e=0,t=si.length;e<t;e++)ni.set(e,si[e]);function ii(e){if(!e)return"";const t=String(e).replace(/[=]+$/,"");let n="";if(t.length%4==1)return"";for(let e,s,i=0,o=0;s=t.charAt(o++);~s&&(e=i%4?64*e+s:s,i++%4)?n+=String.fromCharCode(255&e>>(-2*i&6)):0)s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(s);try{return decodeURIComponent(escape(n))}catch(e){return console.warn(e),""}}const{isEmpty:oi}=Tt.utils,{generateProtocolData:ri}=Tt.common;function ai(e){return a(this,void 0,void 0,(function*(){const t="im_open_status.ws_get_user_status",n=ri({servcmd:t,data:{To_Account:e}}),s=`${n.head.seq}${t}`,i=yield Tt.channel.sendPacket(n,{requestId:s});if(i)return function(e){const{ErrorCode:t,ErrorInfo:n,ErrorList:s=[],UserStatusList:i=[]}=e,o=i.map((e=>{const{To_Account:t,Status:n,CustomStatus:s}=e;return{userID:t,statusType:n,customStatus:ii(s)}})),r=s.map((e=>{const{To_Account:t,Invalid_Account:n,ErrorCode:s,ErrorInfo:i}=e;return{userID:oi(n)?t:n,code:s,message:i}}));return{errorCode:t,errorInfo:n,successUserList:o,failureUserList:r}}(i)}))}class ci{constructor(){this._customStatus=""}init(){const{notificationCenter:e}=Tt;An({apiName:"getUserStatus",context:this}),An({apiName:"setSelfStatus",context:this}),An({apiName:"subscribeUserStatus",context:this}),An({apiName:"unsubscribeUserStatus",context:this}),_n.registerWorkflowStep(Yt.SYNC_SERVER_INFO_AFTER_RE_ONLINE,Wt.USER_STATUS_UPDATE,this._onReOnline,this),e.subscribeInnerEvent(bt.MESSAGE_PUSH,e.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),e.subscribeInnerEvent(bt.LOGOUT,this._reset,this),e.subscribeInnerEvent(bt.DESTROY,this._dispose,this)}setSelfStatus(e){return a(this,void 0,void 0,(function*(){const t=Tt.ssoLog.createSSOLogData({method:"setSelfStatus"}),n=Vs(),{customStatus:s}=e;try{return yield function(e){return a(this,void 0,void 0,(function*(){const t="im_open_status.ws_set_custom_status",n=ri({servcmd:t,data:{CustomStatus:e}}),s=`${n.head.seq}${t}`,i=yield Tt.channel.sendPacket(n,{requestId:s});if(i){const{ErrorCode:e,ErrorInfo:t}=i;return{errorCode:e,errorInfo:t}}}))}(s),this._customStatus=s,t.setLogInfo({message:`customStatus: ${s}`}).end(),{code:0,data:{userID:n,statusType:Hs,customStatus:s}}}catch(e){const{errorCode:n,errorInfo:s}=e,i=new Jt({functionName:"setSelfStatus",code:n,message:s});throw t.setError(i).end(),i}}))}getUserStatus(e){return a(this,void 0,void 0,(function*(){const t=Tt.ssoLog.createSSOLogData({method:"getUserStatus"}),{userIDList:n=[]}=e;return t.setLogInfo({moreMessage:`userIDList length: ${n.length}`}),this._isOnlyMeInArray(n)?this._getMyStatus():this._getUserStatus(n)}))}setCustomStatus(e){const t=ii(e);this._customStatus=t}subscribeUserStatus(e){return a(this,void 0,void 0,(function*(){try{console.log(`${qs} subscribeUserStatus options: `,e);const{userIDList:t=[]}=e;this._checkBusinessCapabilityBits("subscribeUserStatus");const n=this._getMaxUserCount("subscribe"),s=this._sliceUserIDList(t,n),i=yield function(e){return a(this,void 0,void 0,(function*(){const{channel:t}=Tt,n="im_open_status.ws_status_subscribe",s=ri({servcmd:n,data:{To_Account:e}}),i=`${s.head.seq}${n}`;return yield t.sendPacket(s,{requestId:i})}))}(s);return{code:0,data:{failureUserList:this._parseResponse(i)}}}catch(e){throw console.error(`${qs} subscribeUserStatus error:`,e),e}}))}unsubscribeUserStatus(e){return a(this,void 0,void 0,(function*(){try{console.log(`${qs} unsubscribeUserStatus options: `,e),this._checkBusinessCapabilityBits("unsubscribeUserStatus");const{userIDList:t=[]}=e,n=this._getMaxUserCount("unsubscribe"),s=this._sliceUserIDList(t,n),i=yield function(e){return a(this,void 0,void 0,(function*(){const{channel:t}=Tt,n="im_open_status.ws_status_unsubscribe";let s={};s=0===e.length?{UnsubscribeAll:1}:{To_Account:e};const i=ri({servcmd:n,data:s}),o=`${i.head.seq}${n}`;return yield t.sendPacket(i,{requestId:o})}))}(s);return{code:0,data:{failureUserList:this._parseResponse(i)}}}catch(e){throw console.error(`${qs} unsubscribeUserStatus error:`,e),e}}))}_onUserStatusUpdate(e){const{UserStatusList:t=[]}=e||{},n=t.map((e=>{const{To_Account:t,Status:n,CustomStatus:s}=e;return{userID:t,statusType:n,customStatus:ii(s)}}));this._emitUserStatusUpdatedEvent(n)}_onReOnline(e){const t=ii(e.data.customStatus);if(this._customStatus===t)return;this._customStatus=t;const n={userID:Vs(),statusType:Hs,customStatus:t};this._emitUserStatusUpdatedEvent(n)}_emitUserStatusUpdatedEvent(e){Tt.notificationCenter.emitOuterEvent(Dt.USER_STATUS_UPDATED,{name:Dt.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:n,ErrorCode:s,ErrorInfo:i}=e;return{userID:Tt.utils.isEmpty(n)?t:n,code:s,message:i}}))}_checkBusinessCapabilityBits(e){if(!Tt.store.get("commercialConfig").get(Ks))throw new Jt({functionName:e,code:jt.NO_USE,replacement1:e})}_getMaxUserCount(e){const t=Tt.store.get("cloudConfig")||{},n={query:{key:"status_query_count",default:500},subscribe:{key:"status_sub_count",default:Ys},unsubscribe:{key:"status_unsub_count",default:Ys}},{key:s,default:i}=n[e],o=t[s]||i;return parseInt(o,10)}_getMyStatus(){const e=Tt.ssoLog.getSSOLogData("getUserStatus");e.setLogInfo({moreMessage:"getUserStatus._getMyStatus"});const t={userID:Vs(),statusType:Hs,customStatus:this._customStatus};return e.end(),{code:0,data:{successUserList:[t],failureUserList:[]}}}_getUserStatus(e){return a(this,void 0,void 0,(function*(){const t=Tt.ssoLog.getSSOLogData("getUserStatus");t.setLogInfo({moreMessage:"getUserStatus._getUserStatus"});try{this._checkBusinessCapabilityBits("getUserStatus");const n=this._getMaxUserCount("query"),s=this._sliceUserIDList(e,n),i=yield ai(s),{successUserList:o,failureUserList:r}=i||{};return t.end(),{code:0,data:{successUserList:o,failureUserList:r}}}catch(e){const{errorCode:n}=e,s=new Jt({functionName:"getUserStatus",code:n});throw t.setError(s).end(),s}}))}_isOnlyMeInArray(e){const t=Vs();return 1===e.length&&e.indexOf(t)>-1}_dispose(){const{notificationCenter:e}=Tt;e.unSubscribeInnerEvent(bt.MESSAGE_PUSH,e.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),e.unSubscribeInnerEvent(bt.DESTROY,this._dispose,this),e.unSubscribeInnerEvent(bt.LOGOUT,this._reset,this),this._reset()}_reset(){this._customStatus=""}}const li={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}}},di={getMyProfile:!0,getUserProfile:!0,updateMyProfile:!0,setSelfStatus:!0,getUserStatus:!0,subscribeUserStatus:!0,unsubscribeUserStatus:!0};class ui{constructor(){this.userProfile=new ti,this.userStatus=new ci,this.userProfile.init(),this.userStatus.init(),cn({auth:di,params:li})}}const _i=[{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}],hi="im_sdk_config_mgr.fetch_config",gi="im_sdk_config_mgr.push_configv2",fi="cloud-config",Ei=2996;var pi=new class{constructor(){this._core=null,this._expirationTime=0,this._version=0,this._isFetching=!1,this._cmdFrequencyLimitMap=new Map,this._methodCallFrequencyMap=new Map}install(e){this._core=e;const{notificationCenter:t,InnerEvent:n,helper:s,constants:{WORKFLOW_NAME:i,WORKFLOW_STEP:o},channel:r}=e;t.subscribeInnerEvent(gi,this._handlePushedConfig,this),s.registerWorkflowStep(i.SYNC_SERVER_INFO_AFTER_LOGIN,o.CLOUD_CONFIG_SYNC,this._handleLoginSuccess,this),t.subscribeInnerEvent(n.LOGOUT,this._reset,this),t.subscribeInnerEvent(n.DESTROY,this._dispose,this),s.registerExperimentalAPI("getServerConfig",this),this._updateCmdFreqLimitMap(_i),r.registerBeforeSendInterceptor(this.checkMethodCallOverLimit,this)}getServerConfig(e){var t;const n={code:0,data:""};return e?(n.data=(null===(t=this._core.store.get("cloudConfig"))||void 0===t?void 0:t[e])||"",n):n}checkMethodCallOverLimit(e){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:n}=this._cmdFrequencyLimitMap.get(e);let{startTime:s,methodCallCounter:i}=this._methodCallFrequencyMap.get(e);if(Date.now()-s>1e3*n)this._methodCallFrequencyMap.set(e,{startTime:Date.now(),methodCallCounter:1});else if(i+=1,this._methodCallFrequencyMap.set(e,{startTime:s,methodCallCounter:i}),i>t)throw new this._core.helper.ChatError({code:Ei,replacement1:e})}_fetchCloudConfig(){return a(this,void 0,void 0,(function*(){try{const{sdkAppId:e}=this._core.store.get("instance")||{},t=this._core.helper.generateProtocolData({servcmd:hi,data:{uint32_sdkappid:e,uint64_version:this._version}}),n=`${t.head.seq}${hi}`;return yield this._core.channel.sendPacket(t,{requestId:n})}catch(e){throw console.warn("fetch cloudControl fail: ",e),e}}))}_handlePushedConfig(e){this._updateCloudConfig(e)}_handleLoginSuccess(){return a(this,void 0,void 0,(function*(){try{if(this._canFetch()){const e=yield this._fetchCloudConfig();this._updateCloudConfig(e)}this._core.helper.taskScheduler.addTask({id:fi,intervalMs:1e3,callback:this._fetchCloudConfigIfReady,context:this})}catch(e){console.warn(e)}}))}_fetchCloudConfigIfReady(){return a(this,void 0,void 0,(function*(){if(this._canFetch())try{const e=yield this._fetchCloudConfig();this._updateCloudConfig(e)}catch(e){console.warn(e)}}))}_updateCloudConfig(e){const t=this._parseCloudConfig(e);t&&(this._core.store.set("cloudConfig",t),this._parseCmdFreqLimit(),this._core.notificationCenter.emitInnerEvent(this._core.InnerEvent.CLOUD_CONFIG_UPDATE,t))}_canFetch(){const{isLoggedIn:e}=this._core.store.get("login")||{};return e&&!this._isFetching&&Date.now()>=this._expirationTime}_parseCloudConfig(e){const{int32_error_code:t,str_error_message:n,str_json_config:s,uint32_expired_time:i,uint32_sdkappid:o,uint64_version:r}=e;let a=null;if(0===t){if(this._version!==r)try{a=JSON.parse(s),this._version=r}catch(e){}this._expirationTime=Date.now()+1e3*i}else this._expirationTime=void 0===t?Date.now()+36e5:Date.now()+12e4;return a}_parseCmdFreqLimit(){var e;let t=null===(e=this.getServerConfig("cmd_frequency_limit"))||void 0===e?void 0:e.data;const{isEmpty:n}=this._core.utils;if(!n(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(fi),this._core.store.clear("cloudConfig"),this._updateCmdFreqLimitMap(_i),this._methodCallFrequencyMap.clear(),this._expirationTime=0,this._version=0,this._isFetching=!1}_dispose(){const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(gi,this._handlePushedConfig,this),e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this),this._reset()}};class Si{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 mi={SEARCH_GRP_SNS:new Si(0,Math.pow(2,1)).toString(),AV_HISTORY_MSG:new Si(0,Math.pow(2,2)).toString(),GRP_COMMUNITY:new Si(0,Math.pow(2,3)).toString(),MSG_TO_SPECIFIED_GRP_MBR:new Si(0,Math.pow(2,4)).toString(),AV_MBR_LIST:new Si(0,Math.pow(2,6)).toString(),USER_STATUS:new Si(0,Math.pow(2,7)).toString(),CONV_MARK:new Si(0,Math.pow(2,9)).toString(),CONV_GROUP:new Si(0,Math.pow(2,10)).toString(),AV_BAN_MBR:new Si(0,Math.pow(2,11)).toString(),MSG_EXT:new Si(0,Math.pow(2,13)).toString(),GRP_COUNTER:new Si(0,Math.pow(2,15)).toString(),PLUGIN_TRANSLATE:new Si(Math.pow(2,6)).toString(),PLUGIN_VOICE_TO_TEXT:new Si(Math.pow(2,7)).toString(),PLUGIN_CS:new Si(Math.pow(2,8)).toString(),PLUGIN_PUSH:new Si(Math.pow(2,9)).toString(),PLUGIN_BOT:new Si(Math.pow(2,10)).toString(),MSG_REACTION:new Si(Math.pow(2,16)).toString(),FOLLOW:new Si(Math.pow(2,20)).toString()},vi="CommercialConfig",Ii="commercial-config";var Ci=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:n,constants:{WORKFLOW_NAME:s,WORKFLOW_STEP:i,InnerEvent:o}}=e;n.subscribeInnerEvent(o.COMMERCIAL_CONFIG_PUSH,this._handlePushedConfig,this),n.subscribeInnerEvent(o.LOGOUT,this._handleLogout,this),n.subscribeInnerEvent(o.DESTROY,this._dispose,this),t.registerWorkflowStep(s.SYNC_SERVER_INFO_AFTER_LOGIN,i.COMMERCIAL_CONFIG_UPDATE,this._syncCommercialConfig,this),e.helper.registerExperimentalAPI("isCommercialAbilityEnabled",this)}isCommercialAbilityEnabled(e){return a(this,void 0,void 0,(function*(){const t=parseInt(e,10).toString(2),{length:n}=t;let s,i=!0;for(let e=n-1,o=0;e>=0;e--,o++)if("1"===t.charAt(e)&&(s=o<32?new Si(0,2**o).toString():new Si(2**(o-32),0).toString(),!this._featureMap.get(s))){i=!1;break}return console.log(`${vi}.isFeatureEnabled decimalNumber:${e} key:${s} ret:${i}`),{code:0,data:{enabled:i}}}))}_fetchAndParseCommercialConfig(){return a(this,void 0,void 0,(function*(){var e;try{this._isFetching=!0;const t=this._core.helper.generateProtocolData({servcmd:"im_sdk_config_mgr.fetch_imsdk_purchase_bitsv2",data:{uint32_sdkappid:null===(e=this._core.store.get("instance"))||void 0===e?void 0:e.sdkAppId}}),n=yield this._core.channel.sendPacket(t);(null==n?void 0:n.body)&&(this._parseCommercialConfig(n.body),this._core.store.set("commercialConfig",this._methodKeyMap))}catch(e){console.warn("fetch commercial fail: ",e)}finally{this._isFetching=!1}}))}_syncCommercialConfig(e){return a(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:Ii,intervalMs:1e3,callback:this._fetchCommercialConfigIfReady,context:this})}))}_canFetch(){var e;const t=null===(e=this._core.store.get("login"))||void 0===e?void 0:e.isLoggedIn,n=Date.now()>=this._expirationTime;return t&&!this._isFetching&&n}_handlePushedConfig(e){(null==e?void 0:e.body)&&(this._parseCommercialConfig(e.body),this._core.store.set("commercialConfig",this._methodKeyMap))}_fetchCommercialConfigIfReady(){return a(this,void 0,void 0,(function*(){this._canFetch()&&(yield this._fetchAndParseCommercialConfig())}))}_parseCommercialConfig(e){if("object"!=typeof e)return;const{int32_error_code:t,str_error_message:n,str_purchase_bits:s,uint32_expired_time:i}=e;0===t?(this._parsePurchaseBits(s),this._expirationTime=Date.now()+1e3*i):void 0===t?(console.log(`${vi}._parseCommercialConfig failed. Invalid message format:`,e),this._expirationTime=Date.now()+36e5):(console.error(`${vi}._parseCommercialConfig errorCode:${t} errorMessage:${n}`),this._expirationTime=Date.now()+12e4)}_isValidPurchaseBits(e){return e&&"string"==typeof e&&e.length>=1&&e.length<=64&&/[01]{1,64}/.test(e)}_parsePurchaseBits(e){if(this._isValidPurchaseBits(e)){this._featureMap.clear(),this._methodKeyMap.clear();let t=null;for(let n=e.length-1,s=0;n>=0;n--,s++)if(t=s<32?new Si(0,2**s).toString():new Si(2**(s-32),0).toString(),"1"===e[n]){this._featureMap.set(t,!0);const e=this._getKeyByValue(mi,t);e&&this._methodKeyMap.set(e,!0)}else{this._featureMap.set(t,!1);const e=this._getKeyByValue(mi,t);e&&this._methodKeyMap.set(e,!1)}}else console.warn(`${vi}.parsePurchaseBits invalid purchases:${e}`)}_getKeyByValue(e,t){const n=Object.entries(e).find((([e,n])=>n===t));return n?n[0]:void 0}_handleLogout(){this._reset()}_dispose(){this._reset(),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.COMMERCIAL_CONFIG_PUSH,this._handlePushedConfig,this),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}_reset(){this._core.helper.taskScheduler.removeTask(Ii),this._core.store.set("commercialConfig",{}),this._expirationTime=0,this._isFetching=!1,this._featureMap.clear()}};var yi=new class{constructor(){this._core=null,this._serverOverloadInfoMap=new Map}install(e){this._core=e;const{notificationCenter:t,InnerEvent:n,channel:s}=this._core;t.subscribeInnerEvent(n.OVERLOAD_PUSH,this._handleOverLoadPush,this),t.subscribeInnerEvent(n.LOGOUT,this._reset,this),t.subscribeInnerEvent(n.DESTROY,this._dispose,this),s.registerBeforeSendInterceptor(this.checkServerOverload,this)}checkServerOverload(e){if(!this._serverOverloadInfoMap.has(e))return;const{overloadStartTimestamp:t,delaySeconds:n}=this._serverOverloadInfoMap.get(e);if(Date.now()-t<=1e3*n)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:n}=e;this._serverOverloadInfoMap.set(t,{overloadStartTimestamp:Date.now(),delaySeconds:n})}_reset(){this._serverOverloadInfoMap.clear()}_dispose(){this._reset();const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.OVERLOAD_PUSH,this._handleOverLoadPush,this),e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};var Oi=new class{constructor(){this._core=null}install(e){return a(this,void 0,void 0,(function*(){if(this._core=e,this._canFetch()){const e=yield this._fetchErrorMessage();if(!e)return;const t=this._parseResponse(e);this._saveErrorMessage(t)}}))}_canFetch(){const e=this._core.store.getStorage("errorMessage");return!e||this._isExpired(e)}_saveErrorMessage(e){this._core.store.setStorage("errorMessage",{errorMessage:e,errorMessageSavedTime:(new Date).getTime()})}_fetchErrorMessage(){return a(this,void 0,void 0,(function*(){try{return yield this._core.helper.httpRequest({method:"GET",url:"https://web.sdk.qcloud.com/im/download/error-message/v3/0.0.6/tim-error-message.txt"})}catch(e){console.error(e)}}))}_isExpired(e){if(!e)return!0;const{errorMessageSavedTime:t}=e;return t&&(new Date).getTime()-t>=6048e5}_parseResponse(e){if("string"==typeof e){const t=e.split(";\n"),n={},s=new RegExp(/'/g);for(let e=0;e<t.length;e++){const i=t[e].indexOf(":"),o=t[e].slice(0,i);let r=t[e].slice(i+1);if(!o.startsWith("//")){if(""===r)continue;r=r.replace(s,""),n[o]=r}}return n}}};function Mi(e,t){return a(this,void 0,void 0,(function*(){const{cookie:n,syncFlag:s,syncTriggerEvent:i}=e,o="openim.getmsg",r=t.helper.generateProtocolData({servcmd:o,data:{Cookie:n,SyncFlag:s,IsOnlineSync:i,NeedAbstract:1,NeedSignaling:1,NeedCachedMsg:1}}),a=`${r.head.seq}${o}`;try{const e=yield t.channel.sendPacket(r,{requestId:a});if(!e)return null;const{C2CPairUnreadCount:n,C2CRemainingUnreadCount:s,EventArray:i}=e,{unreadMessageList:o,revokedMessageList:c}=function(e,t){const n=[],s=[];return null==e||e.forEach((e=>{var i,o,r;const a=function(e,t){const{From_Account:n,From_AccountHeadurl:s,From_AccountNick:i,IsNeedReadReceipt:o,MsgBody:r,MsgClientTime:a,MsgRandom:c,MsgSeq:l,MsgTimeStamp:d,SendMsgControl:u,SupportMessageExtension:_,To_Account:h,TinyId:g,MsgCheckResult:f,CloudCustomData:E,IsPeerRead:p,MsgFlagBits:S,MsgVersion:m,EventArray:v}=e;return{from:n,avatar:s,nick:i,needReadReceipt:1===o,readReceiptSentByPeer:p,clientTime:a,messageFlagBits:S,random:c,sequence:l,time:d,messageControlInfo:u,isSupportExtension:_,to:h,tinyID:g,checkResult:f,cloudCustomData:E,messageVersion:m,eventArray:v,elements:t.message.messageHelper.parseServerPushMessageElement(r)}}(e,t);if(null===(r=null===(o=null===(i=null==e?void 0:e.EventArray)||void 0===i?void 0:i[0])||void 0===o?void 0:o.hasOwnProperty)||void 0===r?void 0:r.call(o,"C2cNotifyMsgArray"))s.push(...function(e){var t;const n=[];return null===(t=e.EventArray)||void 0===t||t.forEach((e=>{var t,s;const{C2cNotifyMsgArray:i}=e,o=null===(s=null===(t=null==i?void 0:i[0])||void 0===t?void 0:t.WithdrawC2cMsgNotify)||void 0===s?void 0:s.C2cWithdrawInfoArray;Array.isArray(o)&&n.push(...o)})),n}(e));else{const e=t.message.messageFactory.createMessage(Object.assign(Object.assign({},a),{conversationType:"C2C",flow:"in"})),{elements:s}=a;e.setElement(s),n.push(e)}})),{unreadMessageList:n,revokedMessageList:s}}(e.MsgList,t);return{syncFlag:null==e?void 0:e.SyncFlag,unreadMessageList:o,revokedMessageList:c,unreadCountList:n,overflowUnreadCountList:s,cookie:null==e?void 0:e.Cookie,groupTipList:i}}catch(e){console.warn(e)}}))}var Ti,Ai;!function(e){e[e.START_SYNC=0]="START_SYNC",e[e.SYNCING=1]="SYNCING",e[e.SYNC_COMPLETE=2]="SYNC_COMPLETE"}(Ti||(Ti={})),function(e){e[e.LOGIN_SUCCESS=0]="LOGIN_SUCCESS",e[e.NEW_MESSAGE_RECEIVED=1]="NEW_MESSAGE_RECEIVED"}(Ai||(Ai={}));var Ni=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 a(this,void 0,void 0,(function*(){const{isAfterReOnline:t=!1,isAfterNewMessageReceived:n=!1,isAfterLogin:s=!1}=e||{};let i=Ti.START_SYNC;const o=[],r=[],a=[],c=[];for(;this._canContinueSync({cookie:this._cookie,syncFlag:i});){const e=yield this._fetchUnreadDBMessage({cookie:this._cookie,syncFlag:i,syncTriggerEvent:n?Ai.NEW_MESSAGE_RECEIVED:Ai.LOGIN_SUCCESS});if(!e)break;const{unreadMessageList:s=[],revokedMessageList:l=[],overflowUnreadCountList:d,unreadCountList:u,groupTipList:_}=e;if(this._cookie=(null==e?void 0:e.cookie)||"",i=null==e?void 0:e.syncFlag,this._parseAndSaveUnreadMessageList(s),a.push(...l),this._updateConversationUnreadOptions({unreadCountList:u,overflowUnreadCountList:d,conversationUpdateFieldList:o}),Array.isArray(_)&&r.push(..._),t){const{messages:e}=this._handleNewMessageList(s);c.push(...e)}}return t?{conversationUpdateFieldList:o,revokedMessageList:a,unreadMessageMap:this._unreadDBMessageMap,groupTipList:r,messages:c}:{conversationUpdateFieldList:o,isInstantMessage:!s,isUnreadC2CMessage:!0,revokedMessageList:a,unreadMessageMap:this._unreadDBMessageMap,groupTipList:r}}))}_syncUnreadDBMessageAfterLogin(){return a(this,void 0,void 0,(function*(){return this._syncUnreadMessage({isAfterLogin:!0})}))}_syncUnreadDBMessageAfterNewMessageReceived(e){return a(this,void 0,void 0,(function*(){if(1===e.data.Flag)return this._syncUnreadMessage({isAfterNewMessageReceived:!0})}))}_updateConversationUnreadOptions(e){const{unreadCountList:t,overflowUnreadCountList:n,conversationUpdateFieldList:s}=e,{constants:{OuterConstant:{CONV_C2C:i,CONV_SYSTEM:o}}}=this._core;null==t||t.forEach((e=>{const{From_Account:t,UnreadCount:n}=e;if(t!==o){const e=s.find((({conversationID:e})=>e===`${i}${t}`));e?e.unreadCount=n:s.push({conversationID:`${i}${t}`,unreadCount:n,type:i})}})),null==n||n.forEach((e=>{const{From_Account:t,LastMsgTime:n}=e;if(t!==o){s.find((({conversationID:e})=>e===`${i}${t}`))||s.push({conversationID:`${i}${t}`,type:i,lastMsgTime:n})}}))}_syncUnreadDBMessageAfterReOnline(){return a(this,void 0,void 0,(function*(){return this._syncUnreadMessage({isAfterReOnline:!0})}))}_updateMessageProfile(e){var t;const{messageDataHandler:n}=this._core.message||{},s=null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userId,{from:i,nick:o,avatar:r,conversationID:a=""}=e;if(i!==s){const t=n.getLatestMsgSentByPeer(a);if(t){const{nick:s,avatar:i}=t;o&&r?o===s&&r===i||n.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:o,latestAvatar:r,isSentByMe:!1}):(e.nick=s,e.avatar=i)}}else{const e=n.getLatestMsgSentByMe(a);!e||o===e.nick&&r===e.avatar||n.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:o,latestAvatar:r,isSentByMe:!0})}}_handleNewMessageList(e){const{messageDataHandler:t}=this._core.message||{},n=new Map,s=[];return e.forEach((e=>{this._updateMessageProfile(e);let i=1===e.isModified;if(t.isMessageSentByCurrentInstance(e)?e.isModified=i:i=!1,e.isOnlineMessage())e._onlineOnlyFlag=!0,t.isMessageSentByCurrentInstance(e)||s.push(e);else if(!t.isInMessageList(e)){if(t.storeConversationMessage(e)){const{conversationID:t,conversationType:s,conversationSubType:i,flow:o,_isExcludedFromUnreadCount:r,_isExcludedFromLastMessage:a}=e,c=a?"":e;n.has(t)?(n.get(t).lastMessage=c,"in"===o&&(r||n.get(t).unreadCount++)):n.set(t,{conversationID:t,type:s,subType:i,unreadCount:r||"in"!==o?0:1,lastMessage:c})}t.isMessageSentByCurrentInstance(e)&&!i||s.push(e)}})),{messages:s,conversationOptions:n}}_fetchUnreadDBMessage(e){return a(this,void 0,void 0,(function*(){try{const t="unread-message-synchronizer._fetchUnreadDBMessage";console.log(`${t} options:`,e);const n=yield Mi(e,this._core);if(!n)return null;const{syncFlag:s,unreadMessageList:i,revokedMessageList:o,cookie:r,unreadCountList:a,overflowUnreadCountList:c,groupTipList:l}=n;return this._parseAndSaveUnreadMessageList(i),{syncFlag:s,cookie:r,unreadMessageList:i,revokedMessageList:o,unreadCountList:a,overflowUnreadCountList:c,groupTipList:l}}catch(e){console.log(e)}}))}_canContinueSync({cookie:e,syncFlag:t}){var n;return t===Ti.START_SYNC||t===Ti.SYNCING&&!(null===(n=this._core)||void 0===n?void 0:n.helper.isEmpty(e))}_parseAndSaveUnreadMessageList(e){e.forEach((e=>{const{ID:t}=e;this._unreadDBMessageMap.set(t,e)}))}_reset(){this._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 Di=new class{init(e){var t;this._core=e,this._visibilityChangeHandler=this._handleVisibilityChange.bind(this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this),document.addEventListener("visibilitychange",this._visibilityChangeHandler),null===(t=this._core)||void 0===t||t.store.set("activityMonitor",{isActive:!0})}_handleVisibilityChange(){var e,t;const n="visible"===document.visibilityState;null===(e=this._core)||void 0===e||e.store.set("activityMonitor",{isActive:n}),null===(t=this._core)||void 0===t||t.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:n})}_reset(){var e;null===(e=this._core)||void 0===e||e.store.clear("activityMonitor")}_dispose(){document.removeEventListener("visibilitychange",this._visibilityChangeHandler);const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this),this._reset()}};var Ri=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 bi=new class{init(e){const{IN_WX_MINI_APP:t}=e.helper;t?Ri.init(e):Di.init(e)}};const wi="none",Li="online";var ki=new class{init(e){this._core=e,this._activateNetworkMonitoring(),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return a(this,void 0,void 0,(function*(){navigator.onLine?this._onOnline():this._onOffline(),this._onOnlineCallback=this._onOnline.bind(this),this._onOfflineCallback=this._onOffline.bind(this),window.addEventListener("online",this._onOnlineCallback),window.addEventListener("offline",this._onOfflineCallback)}))}_deactivateNetworkMonitoring(){null!==this._onOnlineCallback&&(window.removeEventListener("online",this._onOnlineCallback),this._onOnlineCallback=null),null!==this._onOfflineCallback&&(window.removeEventListener("offline",this._onOfflineCallback),this._onOfflineCallback=null)}_onNetworkStatusChange(e){var t,n;const{isConnected:s,networkType:i}=e;null===(t=this._core)||void 0===t||t.store.set("netWorkMonitor",{isNetworkOnline:s,networkType:i}),null===(n=this._core)||void 0===n||n.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:s,networkType:i})}_onOnline(){this._onNetworkStatusChange({isConnected:!0,networkType:Li})}_onOffline(){this._onNetworkStatusChange({isConnected:!1,networkType:wi})}_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 Pi=new class{init(e){this._core=e,this._activateNetworkMonitoring(),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return a(this,void 0,void 0,(function*(){try{wx.getNetworkType().then((e=>{const{isConnected:t,networkType:n}=e;this._onNetworkStatusChange({isConnected:t,networkType:n})})),this._mpNetworkStatusCallback=this._onNetworkStatusChange.bind(this),wx.onNetworkStatusChange(this._onNetworkStatusChange.bind(this))}catch(e){console.error(e)}}))}_deactivateNetworkMonitoring(){null!==this._mpNetworkStatusCallback&&(wx.offNetworkStatusChange&&wx.offNetworkStatusChange(this._mpNetworkStatusCallback),this._mpNetworkStatusCallback=null)}_onNetworkStatusChange(e){var t,n;const{isConnected:s,networkType:i}=e;null===(t=this._core)||void 0===t||t.store.set("netWorkMonitor",{isNetworkOnline:s,networkType:i}),null===(n=this._core)||void 0===n||n.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:s,networkType:i})}_reset(){var e;this._deactivateNetworkMonitoring(),null===(e=this._core)||void 0===e||e.store.clear("netWorkMonitor")}_dispose(){var e,t;null===(e=this._core)||void 0===e||e.notificationCenter.unSubscribeInnerEvent(null===(t=this._core)||void 0===t?void 0:t.InnerEvent.DESTROY,this._dispose,this),this._reset()}};var Ui=new class{init(e){const{IN_WX_MINI_APP:t}=e.helper;t?Pi.init(e):ki.init(e)}};var Fi=new class{install(e){bi.init(e),Ui.init(e)}};const Gi=1,xi=2,Bi=3,$i=4,Vi=5,qi="TIMCustomElem",ji="C2C",Yi="GROUP",Wi="invite",Ki="accept",Hi="cancel",zi="reject",Ji="modifyInvitation",Zi="signaling",Xi=8010,Qi="signaling-timeout";function eo(e){return e.filter((e=>{if(e.type===qi){const{cloudCustomData:t="",payload:{data:n=""}={}}=e,s=t.match(/"type":"tsignaling"/),i=n.match(/inviteID/),o=n.match(/actionType/);return s||i&&o}return!1}))}function to(e){const{data:t}=e.payload;try{return JSON.parse(t)}catch(e){return console.error(e),null}}function no(e,t){return e.toString(16).padStart(t,"0")}function so(e){if(e<0||e>53)throw new Error("Number of digits must be between 0 and 53");if(e<=30)return Math.floor(Math.random()*(1<<e));const t=e-30;return Math.floor(Math.random()*(1<<t))*(1<<30)+Math.floor(Math.random()*(1<<30))}var io=new class{constructor(){this._onlineSignalingMap=new Map,this._isSignalingListening=!1}init(e){this._core=e,e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.LOGOUT,this._reset,this)}getOnlineSignalingMap(){return this._onlineSignalingMap}hasSignaling(e){return this._onlineSignalingMap.has(e)}getSignaling(e){return this._onlineSignalingMap.get(e)}saveSignaling(e,t){return this._onlineSignalingMap.set(e,t)}removeSignaling(e){return this._onlineSignalingMap.delete(e)}isInvitationValid(e){const t=`${Zi}.isInvitationValid`,{inviteID:n,groupID:s,inviter:i}=e,o=i===this._getCurrentUserId();if(!this._onlineSignalingMap.has(n))return!1;const{inviteeList:r}=this._onlineSignalingMap.get(n);if(console.log(`${t} inviteID:${n} inviteeList:${r} groupID:${s}`),s){if(o)return r.length>0;const e=this._getCurrentUserId();return r.includes(e)}return!0}updateSignaling(e){const t=`${Zi}.updateSignaling`,{inviteID:n,inviter:s,inviteeList:i,groupID:o}=e;if(console.log(`${t} inviteID:${n} inviter:${s} groupID:${o}`),o&&this.hasSignaling(n)){const e=i[0],{inviteeList:s}=this._onlineSignalingMap.get(n);s.includes(e)&&(s.splice(s.indexOf(e),1),console.log(`${t} remove ${e}. localInviteeList.length:${s.length}`)),0===s.length&&this.removeSignaling(n)}else this.removeSignaling(n)}setSignalingListenStatus(e){this._isSignalingListening=e}getSignalingListenStatus(){return this._isSignalingListening}_getCurrentUserId(){var e,t;return null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("login"))||void 0===t?void 0:t.userId}_dispose(){var e,t;this._reset(),null===(e=this._core)||void 0===e||e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),null===(t=this._core)||void 0===t||t.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),this._isSignalingListening=!1}_reset(){this._onlineSignalingMap.clear()}};var oo=new class{init(e){this._core=e}createInviteSignaling(e){const t=this._generateInviteID(),n=this._createInviteSignalingData(Object.assign(Object.assign({},e),{inviteID:t})),{groupID:s,inviteeList:i}=n,o=s||i[0];return{signaling:this._createSignaling(n,o),signalingData:n,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createAcceptSignaling(e){const t=this._createAcceptSignalingData(e),{groupID:n,inviter:s}=t,i=n||s;return{signaling:this._createSignaling(t,i),signalingData:t,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createCancelSignaling(e){const t=this._createCancelSignalingData(e),{groupID:n,inviteeList:s}=t,i=n||s[0];return{signaling:this._createSignaling(t,i),signalingData:t,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createRejectSignaling(e){const t=this._createRejectSignalingData(e),{groupID:n,inviter:s}=t,i=n||s;return{signaling:this._createSignaling(t,i),signalingData:t,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createTimeoutSignaling(e){const{isInviter:t=!1}=e,n=this._createTimeoutSignalingData(e),{groupID:s,inviteeList:i,inviter:o}=n,r=s||(t?i[0]:o);return{signaling:this._createSignaling(n,r),signalingData:n,signalingExtensionOptions:this._createSignalingExtensionOptions(n)}}_createSignalingExtensionOptions(e){var t,n;const{data:s="",onlineUserOnly:i,inviteID:o="",offlinePushInfo:r,actionType:a}=e,c=(null===(n=null===(t=io.getSignaling(o))||void 0===t?void 0:t.signaling)||void 0===n?void 0:n._onlineOnlyFlag)||!1;return{onlineUserOnly:i||c,offlinePushInfo:r,messageControlInfo:this._createMessageControlInfo(s,a)}}_createMessageControlInfo(e,t){const n=t===Vi&&!!e.match(/excludeTimeoutSignalingFromHistoryMessage/),s=!!e.match(/excludeFromHistoryMessage/)||!!e.match(/excludeOriginalSignalingFromHistoryMessage/);return{excludedFromContentModeration:!0,excludedFromUnreadCount:n||s,excludedFromLastMessage:n||s}}_createInviteSignalingData(e){const t=`${Zi}._createInviteSignalingData`,{userID:n,timeout:s=0,groupID:i="",inviteeList:o=[]}=e,r=this._getCurrentUserId(),a=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:Gi,inviter:r,inviteeList:i?o:[n],timeout:s});return console.log(`${t} signalingData:`,a),a}_createAcceptSignalingData(e){const t=`${Zi}._createAcceptSignalingData`,{inviteID:n}=e,s=this._getCurrentUserId(),{inviter:i,groupID:o}=io.getSignaling(n),r=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:Bi,groupID:o,inviter:i,inviteeList:[s]});return console.log(`${t} signalingData:`,r),r}_createCancelSignalingData(e){const t=`${Zi}._createCancelSignalingData`,{inviteID:n}=e,s=this._getCurrentUserId(),{inviteeList:i,groupID:o}=io.getSignaling(n),r=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:xi,groupID:o,inviter:s,inviteeList:i});return console.log(`${t} signalingData:`,r),r}_createRejectSignalingData(e){const t=`${Zi}._createRejectSignalingData`,{inviteID:n}=e,s=this._getCurrentUserId(),{inviter:i,groupID:o}=io.getSignaling(n),r=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:$i,groupID:o,inviter:i,inviteeList:[s]});return console.log(`${t} signalingData:`,r),r}_createTimeoutSignalingData(e){const t=`${Zi}._createTimeoutSignalingData`,{isInviter:n=!1,inviteID:s}=e,{inviteeList:i,inviter:o}=io.getSignaling(s),r=this._getCurrentUserId(),a=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:Vi,inviter:o,inviteeList:n?i:[r]});return console.log(`${t} signalingData:`,a),a}_createSignaling(e,t){var n,s,i;const{groupID:o=""}=e,r={to:t,conversationType:o?Yi:ji,priority:"High",payload:{data:JSON.stringify(e)}};return null===(i=null===(s=null===(n=this._core)||void 0===n?void 0:n.message)||void 0===s?void 0:s.messageFactory)||void 0===i?void 0:i.createCustomMessage(r)}_generateInviteID(){return[no(so(32),8),no(so(16),4),no(16384|so(12),4),no(32768|so(14),4),no(so(48),12)].join("-")}_generateBaseSignalData(e){const{data:t="",inviteID:n="",groupID:s=""}=e;return{businessID:1,timeout:0,data:t,inviteID:n,groupID:s}}_getCurrentUserId(){var e,t;return null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("login"))||void 0===t?void 0:t.userId}};var ro=new class{constructor(){this._isProcessingSignaling=!1}init(e){this._core=e,e.helper.registerApi({apiName:"invite",context:this}),e.helper.registerApi({apiName:"accept",context:this}),e.helper.registerApi({apiName:"cancel",context:this}),e.helper.registerApi({apiName:"reject",context:this}),e.helper.registerApi({apiName:"modifyInvitation",context:this}),e.helper.registerApi({apiName:"getSignalingInfo",context:this}),e.helper.registerApi({apiName:"addSignalingListener",context:this}),e.helper.registerApi({apiName:"removeSignalingListener",context:this}),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.LOGOUT,this._reset,this)}invite(e){return a(this,void 0,void 0,(function*(){var t;console.log(`${Zi}.invite params:${JSON.stringify(e)}`);try{this._validateBeforeInvite(e);const{signaling:n,signalingData:s,signalingExtensionOptions:i}=oo.createInviteSignaling(e),o=yield this._sendSignaling(n,i);if(0===(null==o?void 0:o.code)){const{inviteID:e,timeout:i}=s;return io.saveSignaling(e,Object.assign(Object.assign({},s),{signaling:n})),i>0&&(null===(t=this._core)||void 0===t||t.helper.taskScheduler.addOnceTask({id:`${Qi}-${e}`,intervalMs:1e3*(i+5),callback:this.handleInvitationExpiryTimer.bind(this,e)})),Object.assign(Object.assign({},o),{inviteID:e})}return o}catch(e){throw console.error(`${Zi}.invite error:${e}`),e}}))}accept(e){return a(this,void 0,void 0,(function*(){console.log(`${Zi}.accept params:${JSON.stringify(e)}`);try{const{inviteID:t}=e;this._validateBeforeAccept(t),this._isProcessingSignaling=!0;const{signaling:n,signalingData:s,signalingExtensionOptions:i}=oo.createAcceptSignaling(e),o=yield this._sendSignaling(n,i);return 0===(null==o?void 0:o.code)?(io.updateSignaling(s),Object.assign(Object.assign({},o),{inviteID:t})):o}catch(e){throw console.error(`${Zi}.accept error:${e}`),e}finally{this._isProcessingSignaling=!1}}))}cancel(e){return a(this,void 0,void 0,(function*(){console.log(`${Zi}.cancel params:${JSON.stringify(e)}`);try{const{inviteID:t}=e;this._validateBeforeCancel(t),this._isProcessingSignaling=!0;const{signaling:n,signalingExtensionOptions:s}=oo.createCancelSignaling(e),i=yield this._sendSignaling(n,s);return 0===(null==i?void 0:i.code)?(io.removeSignaling(t),Object.assign(Object.assign({},i),{inviteID:t})):i}catch(e){throw console.error(`${Zi}.cancel error:${e}`),e}finally{this._isProcessingSignaling=!1}}))}reject(e){return a(this,void 0,void 0,(function*(){console.log(`${Zi}.reject params:${JSON.stringify(e)}`);try{const{inviteID:t}=e;this._validateBeforeReject(t),this._isProcessingSignaling=!0;const{signaling:n,signalingExtensionOptions:s}=oo.createRejectSignaling(e),i=yield this._sendSignaling(n,s);return 0===(null==i?void 0:i.code)?(io.removeSignaling(t),Object.assign(Object.assign({},i),{inviteID:t})):i}catch(e){throw console.error(`${Zi}.reject error:${e}`),e}finally{this._isProcessingSignaling=!1}}))}modifyInvitation(e){return a(this,void 0,void 0,(function*(){var t,n;console.log(`${Zi}.modifyInvitation params:${JSON.stringify(e)}`);const{inviteID:s,data:i}=e;let o="";try{this._validateBeforeModifyInvitation(s);const e=io.getSignaling(s),{signaling:a}=e,c=r(e,["signaling"]);o=a.payload.data,c.data=i,a.payload.data=JSON.stringify(c);const l=yield null===(n=null===(t=this._core)||void 0===t?void 0:t.message.messageAction)||void 0===n?void 0:n.modifyMessage(a);return io.hasSignaling(s)&&io.saveSignaling(s,Object.assign(Object.assign({},c),{signaling:a})),l}catch(e){if(o){const{signaling:e}=io.getSignaling(s);e.payload.data=o}throw e}}))}getSignalingInfo(e){if(0===eo([e]).length)return;const t=to(e),n={businessID:t.businessID||1,inviteID:t.inviteID,groupID:t.groupID||"",inviter:t.inviter||"",inviteeList:t.inviteeList||[],data:t.data||"",actionType:t.actionType||Gi,timeout:t.timeout||0};return console.log(`${Zi} getSignalingInfo `,n),n}addSignalingListener(e,t,n){var s,i;e===(null===(s=this._core)||void 0===s?void 0:s.SignalingEvent.NEW_INVITATION_RECEIVED)&&io.setSignalingListenStatus(!0),null===(i=this._core)||void 0===i||i.notificationCenter.subscribeOuterEvent(e,t,n)}removeSignalingListener(e,t,n){var s,i;e===(null===(s=this._core)||void 0===s?void 0:s.SignalingEvent.NEW_INVITATION_RECEIVED)&&io.setSignalingListenStatus(!1),null===(i=this._core)||void 0===i||i.notificationCenter.unSubscribeOuterEvent(e,t,n)}handleInvitationExpiryTimer(e){const t=io.getOnlineSignalingMap(),n=this._getCurrentUserId();if(!t.has(e))return;const s=t.get(e).inviter===n;this._sendTimeoutNotice({inviteID:e,isInviter:s})}_sendSignaling(e,t){return a(this,void 0,void 0,(function*(){var n,s,i;return null===(i=null===(s=null===(n=this._core)||void 0===n?void 0:n.message)||void 0===s?void 0:s.messageSender)||void 0===i?void 0:i.sendMessage(e,t)}))}_sendTimeoutNotice(e){return a(this,void 0,void 0,(function*(){var t,n,s;console.log(`${Zi}._sendTimeoutNotice params:${JSON.stringify(e)}`);const{isInviter:i,inviteID:o}=e,{signaling:r,signalingData:a,signalingExtensionOptions:c}=oo.createTimeoutSignaling(e),l=yield this._sendSignaling(r,c);if(0===(null==l?void 0:l.code)){const{data:e,groupID:c,inviteeList:l,inviter:d}=a;null===(t=this._core)||void 0===t||t.notificationCenter.emitOuterEvent(null===(n=this._core)||void 0===n?void 0:n.SignalingEvent.INVITATION_TIMEOUT,{name:null===(s=this._core)||void 0===s?void 0:s.SignalingEvent.INVITATION_TIMEOUT,data:{data:e,groupID:c,inviteID:o,inviteeList:l,inviter:d,isSelfTimeout:!0,message:r}}),i?io.removeSignaling(o):io.updateSignaling(a)}}))}_validateInviteId(e,t){if(!io.hasSignaling(t))throw new this._core.helper.ChatError({functionName:e,code:Xi})}_validateProcessStatus(e){if(this._isProcessingSignaling)throw new this._core.helper.ChatError({functionName:e,message:"processing other signaling operations"})}_validateBeforeInvite(e){const t=Wi,{userID:n}=e,s=this._getCurrentUserId();if(n===s)throw new this._core.helper.ChatError({functionName:t,message:`cannot invite yourself, currentUserId:${s}, inviteeId:${n}`})}_validateBeforeAccept(e){const t=Ki;this._validateInviteId(t,e),this._validateProcessStatus(t);const n=this._getCurrentUserId(),{inviteeList:s}=io.getSignaling(e);if(!s.includes(n)){const s=`userID:${n} not in inviteeList. inviteID:${e}`;throw new this._core.helper.ChatError({functionName:t,message:s})}}_validateBeforeCancel(e){const t=Hi;this._validateInviteId(t,e),this._validateProcessStatus(t);const n=this._getCurrentUserId(),{inviter:s}=io.getSignaling(e);if(s!==n){const e=`unmatched inviter:${s} and my userID:${n}`;throw new this._core.helper.ChatError({functionName:t,message:e})}}_validateBeforeReject(e){const t=zi;this._validateInviteId(t,e),this._validateProcessStatus(t);const n=this._getCurrentUserId(),{inviteeList:s}=io.getSignaling(e);if(!s.includes(n)){const s=`userID:${n} not in inviteeList. inviteID:${e}`;throw new this._core.helper.ChatError({functionName:t,message:s})}}_validateBeforeModifyInvitation(e){const t=Ji;this._validateInviteId(t,e)}_dispose(){var e,t;this._reset(),null===(e=this._core)||void 0===e||e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),null===(t=this._core)||void 0===t||t.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this)}_reset(){this._isProcessingSignaling=!1}_getCurrentUserId(){var e,t;return null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("login"))||void 0===t?void 0:t.userId}};var ao=new class{constructor(){this._actionProcessor=new Map([[Gi,this._onNewInvitationReceived.bind(this)],[$i,this._onInviteeRejected.bind(this)],[Bi,this._onInviteeAccepted.bind(this)],[xi,this._onInvitationCancelled.bind(this)],[Vi,this._onInvitationTimeout.bind(this)]])}init(e){this._core=e,e.notificationCenter.subscribeOuterEvent(e.OuterEvent.MESSAGE_RECEIVED,this._handleMessageReceived,this),e.notificationCenter.subscribeOuterEvent(e.OuterEvent.MESSAGE_MODIFIED,this._handleMessageModified,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this)}handleActionSignaling(e){e.forEach((e=>{const t=to(e);if(t){const n=this._actionProcessor.get(t.actionType);null==n||n(t,e)}}))}_handleMessageReceived(e){if(!io.getSignalingListenStatus())return;const t=eo(e.data);0!==t.length&&this.handleActionSignaling(t)}_handleMessageModified(e){if(!io.getSignalingListenStatus())return;const t=eo(e.data);t.length>0&&t.forEach((e=>{const t=to(e);t&&this._onInvitationModified(t,e)}))}_onNewInvitationReceived(e,t){var n,s;const i=`${Zi}._onNewInvitationReceived`,{inviteID:o,inviteeList:r,groupID:a}=e,c=this._getCurrentUserId();console.log(`${i} signalingData:${JSON.stringify(e)}}`);if(a&&!r.includes(c))return;let{timeout:l}=e;const d=Date.now()/1e3-t.time;l>0&&d>0&&l>d&&(l-=d);const u=io.getSignaling(o);u!==e&&(u||io.saveSignaling(o,Object.assign(Object.assign({},e),{signaling:t})),l>0&&(null===(n=this._core)||void 0===n||n.helper.taskScheduler.addOnceTask({id:`${Qi}-${o}`,intervalMs:1e3*l,callback:ro.handleInvitationExpiryTimer.bind(ro,o)})),this._emitEvent({name:null===(s=this._core)||void 0===s?void 0:s.SignalingEvent.NEW_INVITATION_RECEIVED,data:Object.assign(Object.assign({},this._generateBaseEmitData(e)),{inviteeList:r})}))}_onInviteeRejected(e){var t;const n=`${Zi}._onInviteeRejected`,{inviteID:s,inviter:i,groupID:o,inviteeList:r}=e,a=io.hasSignaling(s);console.log(`${n} inviteID:${s} hasInviteID:${a} inviter:${i} groupID:${o}`),a&&(io.updateSignaling(e),this._emitEvent({name:null===(t=this._core)||void 0===t?void 0:t.SignalingEvent.INVITEE_REJECTED,data:Object.assign(Object.assign({},this._generateBaseEmitData(e)),{invitee:r[0]})}))}_onInviteeAccepted(e){var t;const n=`${Zi}._onInviteeAccepted`,{inviteID:s,inviter:i,groupID:o,inviteeList:r}=e,a=io.hasSignaling(s);console.log(`${n} inviteID:${s} hasInviteID:${a} inviter:${i} groupID:${o}`),a&&(io.updateSignaling(e),this._emitEvent({name:null===(t=this._core)||void 0===t?void 0:t.SignalingEvent.INVITEE_ACCEPTED,data:Object.assign(Object.assign({},this._generateBaseEmitData(e)),{invitee:r[0]})}))}_onInvitationCancelled(e){var t;const n=`${Zi}._onInvitationCancelled`,{inviteID:s,inviter:i,groupID:o}=e,r=io.hasSignaling(s);console.log(`${n} inviteID:${s} hasInviteID:${r} inviter:${i} groupID:${o}`),r&&(io.removeSignaling(s),this._emitEvent({name:null===(t=this._core)||void 0===t?void 0:t.SignalingEvent.INVITATION_CANCELLED,data:this._generateBaseEmitData(e)}))}_onInvitationTimeout(e){var t;const n=`${Zi}._onInvitationTimeout`,{inviteID:s,inviteeList:i}=e,o=io.hasSignaling(s);console.log(`${n} inviteID:${s} hasInviteID:${o} data:${e.data}`),o&&(io.updateSignaling(e),this._emitEvent({name:null===(t=this._core)||void 0===t?void 0:t.SignalingEvent.INVITATION_TIMEOUT,data:Object.assign(Object.assign({},this._generateBaseEmitData(e)),{inviteeList:i,isSelfTimeout:!1})}))}_onInvitationModified(e,t){var n;const s=`${Zi}._onInvitationModified`,{inviteID:i,data:o}=e,r=io.hasSignaling(i);console.log(`${s} inviteID:${i} data:${o}`),r&&(io.saveSignaling(i,Object.assign(Object.assign({},e),{signaling:t})),this._emitEvent({name:null===(n=this._core)||void 0===n?void 0:n.SignalingEvent.INVITATION_MODIFIED,data:{inviteID:i,data:o}}))}_emitEvent(e){var t;null===(t=this._core)||void 0===t||t.notificationCenter.emitOuterEvent(e.name,e)}_generateBaseEmitData(e){const{inviteID:t,inviter:n,groupID:s,data:i}=e;return{inviteID:t,inviter:n,groupID:s,data:i||""}}_getCurrentUserId(){var e,t;return null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("login"))||void 0===t?void 0:t.userId}_dispose(){var e,t,n;null===(e=this._core)||void 0===e||e.notificationCenter.unSubscribeOuterEvent(this._core.OuterEvent.MESSAGE_RECEIVED,this._handleMessageReceived,this),null===(t=this._core)||void 0===t||t.notificationCenter.unSubscribeOuterEvent(this._core.OuterEvent.MESSAGE_MODIFIED,this._handleMessageModified,this),null===(n=this._core)||void 0===n||n.notificationCenter.unSubscribeOuterEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}};var co=new class{constructor(){this._offlineSignalingMap=new Map}init(e){this._core=e;const{notificationCenter:t,helper:n,constants:{InnerEvent:s,WORKFLOW_STEP:i,WORKFLOW_NAME:o}}=e;t.subscribeInnerEvent(s.DESTROY,this._dispose,this),t.subscribeInnerEvent(s.LOGOUT,this._reset,this),n.registerWorkflowStep(o.SYNC_SERVER_INFO_AFTER_LOGIN,i.SIGNALING_MESSAGE_RECOVER,this._handleC2COfflineMessage,this)}_handleC2COfflineMessage(e){const{result:{unreadMessageMap:t}={}}=e||{};if(!(0!==(null==t?void 0:t.size)&&io.getSignalingListenStatus()))return;const n=eo([...t.values()]);if(0!==n.length&&(n.forEach((e=>{this._handleC2CActionType(e)})),this._offlineSignalingMap.size>0)){const e=this._sortOfflineSignalingByTime();ao.handleActionSignaling(e)}}_handleC2CActionType(e){const t=to(e);if(!t)return;const{actionType:n}=t;n===Gi?this._saveValidOfflineInvite(t,e):this._removeOfflineInvite(t)}_saveValidOfflineInvite(e,t){const{inviteID:n,inviteeList:s=[],timeout:i=0}=e,o=this._getCurrentUserId();if(!s.includes(o))return;const r=Date.now()/1e3-t.time;i>0&&r>i&&0!==i||this._offlineSignalingMap.set(n,Object.assign(Object.assign({},e),{signalingList:[t]}))}_removeOfflineInvite(e){const{inviteID:t=""}=e;this._offlineSignalingMap.has(t)&&this._offlineSignalingMap.delete(t)}_sortOfflineSignalingByTime(){let e=[];return this._offlineSignalingMap.forEach((t=>{e=[...e,...t.signalingList]})),e.sort(((e,t)=>e.time-t.time))}_getCurrentUserId(){var e,t;return null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("login"))||void 0===t?void 0:t.userId}_dispose(){var e,t;this._reset(),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)}_reset(){this._offlineSignalingMap.clear()}};const lo={invite:{userID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0},timeout:{required:!1,rules:["number"],allowEmpty:!1},onlineUserOnly:{required:!1,rules:["boolean"],allowEmpty:!1},offlinePushInfo:{required:!1,rules:["object"],allowEmpty:!1}},cancel:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}},accept:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}},reject:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}},modifyInvitation:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}}},uo={invite:!0,cancel:!0,accept:!0,reject:!0,modifyInvitation:!0};var _o=new class{install(e){ro.init(e),ao.init(e),oo.init(e),io.init(e),co.init(e),e.helper.registerValidateConfig({auth:uo,params:lo})}};const ho=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.*"]),go="tui_room_svr.*";var fo=new class{constructor(){this._transferredCommands=ho}install(e){this._core=e;const{notificationCenter:t,InnerEvent:n,helper:s}=e;t.subscribeInnerEvent(n.CLOUD_CONFIG_UPDATE,this._onCloudConfigUpdate,this),t.subscribeInnerEvent(n.LOGOUT,this._reset,this),t.subscribeInnerEvent(n.DESTROY,this._dispose,this),t.subscribeInnerEvent("im_open_push.msg_push",t.InnerEventSubType.BUSINESS_COMMAND,this._onServerPushBusinessCommand,this),s.registerExperimentalAPI("sendTRTCCustomData",this,"transferBusinessCommand"),s.registerExperimentalAPI("sendRoomCustomData",this,"transferBusinessCommand")}transferBusinessCommand(e){return a(this,void 0,void 0,(function*(){const t="transferBusinessCommand";try{const{serviceCommand:n=go}=e||{};if(!this._isValidTransferredCommand(n))throw new this._core.helper.ChatError({code:2995,functionName:t});const s=yield function(e,t){return a(this,void 0,void 0,(function*(){const{helper:n,channel:s}=t,{serviceCommand:i=go,data:o}=e||{};let r={};try{r="string"==typeof o?JSON.parse(o):o}catch(e){console.warn(e)}const a=n.generateProtocolData({servcmd:i,data:r}),c=`${a.head.seq}${i}`;return s.sendPacket(a,{requestId:c})}))}(e,this._core);return{code:0,data:s||{}}}catch(e){throw console.warn(e),new this._core.helper.ChatError({code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo,data:{},functionName:t})}}))}_onCloudConfigUpdate(e={}){try{if("string"!=typeof e.rtc_cmd)return;const t=JSON.parse(e.rtc_cmd);Array.isArray(t)&&(this._transferredCommands=new Set([...this._transferredCommands,...t]))}catch(e){console.log(e)}}_isValidTransferredCommand(e=""){const t=`${null==e?void 0:e.split(".")[0]}.*`;return this._transferredCommands.has(t)}_onServerPushBusinessCommand(e){const{OuterEvent:t,notificationCenter:n}=this._core,{MsgContent:s}=e||{},{ROOM_CUSTOM_DATA_RECEIVED:i}=t;n.emitOuterEvent(i,{name:i,data:s})}_reset(){this._transferredCommands=ho}_dispose(){const{notificationCenter:e,InnerEvent:t}=this._core;this._reset(),e.unSubscribeInnerEvent(t.CLOUD_CONFIG_UPDATE,this._onCloudConfigUpdate,this),e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this),e.unSubscribeInnerEvent("im_open_push.msg_push",e.InnerEventSubType.BUSINESS_COMMAND,this._onServerPushBusinessCommand,this)}};const Eo=[Oi,function(e){pi.install(e),Ci.install(e),yi.install(e)},Ni,Fi,fo,_o];console.log(`TencentCloudLiteChat.VERSION:${be}`);var po={create:function(e){const{SDKAppID:t,testEnv:n=!1,devMode:s=!1,unlimitedAVChatRoom:i=!1}=e;let o=t;if(!function(e){if("number"==typeof e)return!0;const t=Number(e);return!Number.isNaN(t)}(o))return console.error("Create SDK instance failed. Failed to parse the SDKAppID, please check the arguments"),null;if(o=Number(o),un.has(o))return un.get(o);const r=function(){function e(){return(65536*(1+Math.random())|0).toString(16).substring(1)}return`${e()+e()}${e()}${e()}${e()}${e()}${e()}${e()}`}();Tt.init({sdkAppId:o,instanceId:r,testEnv:n,devMode:s,unlimitedAVChatRoom:i}),_n.init(),Tt.message=new Bs,Tt.user=new ui,Tt.login=new Jn,ln.installBuiltInPlugin(Eo);const a=Rn();return un.set(o,a),a},TSignaling:wt,EVENT:Dt,VERSION:be,TYPES:qt};export{po as default};
1
+ class e{constructor(){this.listeners={}}on(e,t,n){this.listeners[e]||(this.listeners[e]=[]),this.listeners[e].push({fn:t,context:n})}off(e,t,n){var s;t&&(this.listeners[e]=null===(s=this.listeners[e])||void 0===s?void 0:s.filter((e=>{const s=e.fn===t,i=!n||e.context===n;return!(s&&i)})))}emit(e,...t){const n=this.listeners[e];n&&n.forEach((e=>{const{fn:n,context:s}=e;n.apply(s,t)}))}once(e,t,n){const s=(...i)=>{t.apply(n,i),this.off(e,s)};this.on(e,s)}}var t;!function(e){e.BUSINESS_COMMAND="business_command",e.C2C_REALTIME_MESSAGE="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 n=[{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 n;const s=[];return null===(n=null==e?void 0:e.C2cNotifyMsgArray)||void 0===n||n.forEach((e=>{e.WithdrawC2cMsgNotify&&s.push(t.C2C_REVOKED_MESSAGE),e.C2cReadedReceipt&&s.push(t.C2C_MESSAGE_PEER_READ),e.ReadC2cMsgNotify&&s.push(t.C2C_MESSAGE_READ_SYNC),e.MuteNotificationsSync&&s.push(t.C2C_REMIND_TYPE_SYNC)})),s}},{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 n;const s=[];return null===(n=null==e?void 0:e.GroupTips)||void 0===n||n.forEach((e=>{Array.isArray(e.MsgBody.GroupWithdrawInfoArray)&&s.push(t.GROUP_MESSAGE_REVOKED),Array.isArray(e.MsgBody.GroupMsgReceiptList)&&s.push(t.GROUP_MESSAGE_READ_RECEIPT),Array.isArray(e.MsgBody.GroupReadInfoArray)?s.push(t.GROUP_MESSAGE_READ_SYNC):s.push(t.GROUP_SYSTEM_NOTIFICATION)})),s}},{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 s;!function(e){e.SERVER_PUSH_MESSAGE="im_open_push.msg_push",e.ERROR="error"}(s||(s={}));const i={[s.SERVER_PUSH_MESSAGE]:function(e){var t;const i=Array.isArray(null===(t=null==e?void 0:e.body)||void 0===t?void 0:t.EventArray)?e.body.EventArray:[],o=[];return i.forEach((t=>{t.Flag=e.body.Flag;const i=n.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(!i)return null;let r=[];"function"==typeof i.subTypeParser?r=i.subTypeParser(t):i.subType&&(r=i.subType),Array.isArray(r)?r.forEach((e=>{o.push({type:`${s.SERVER_PUSH_MESSAGE}:${e}`,data:t})})):o.push({type:`${s.SERVER_PUSH_MESSAGE}:${r}`,data:t})})),o},[s.ERROR]:function(e){const{errorCode:t}=e;return[{type:`error:${t}`,data:e}]}};const o=new class{constructor(){this._outerEventEmitter=null,this._innerEventEmitter=null,this._outerEventEmitter=new e,this._innerEventEmitter=new e,this.InnerEventSubType=t}subscribeInnerEvent(e,t,n,s){var i,o;if(["string","number"].includes(typeof t)){const o=t,r=n;null===(i=this._innerEventEmitter)||void 0===i||i.on(`${e}:${o}`,r,s)}else{const s=t;null===(o=this._innerEventEmitter)||void 0===o||o.on(e,s,n)}}emitInnerEvent(e,t){var n,s;if(null===(n=this._innerEventEmitter)||void 0===n||n.emit(e,t),Object.keys(i).includes(e)){const n=null===(s=i[e])||void 0===s?void 0:s.call(i,t);null==n||n.forEach((e=>{var t;e&&(null===(t=this._innerEventEmitter)||void 0===t||t.emit(e.type,e.data))}))}}unSubscribeInnerEvent(e,t,n,s){var i,o;if(["string","number"].includes(typeof t)){const o=t,r=n;null===(i=this._innerEventEmitter)||void 0===i||i.off(`${e}:${o}`,r,s)}else{const s=t;null===(o=this._innerEventEmitter)||void 0===o||o.off(e,s,n)}}subscribeOuterEvent(e,t,n){var s;null===(s=this._outerEventEmitter)||void 0===s||s.on(e,t,n)}unSubscribeOuterEvent(e,t,n){var s;null===(s=this._outerEventEmitter)||void 0===s||s.off(e,t,n)}emitOuterEvent(e,t){var n;null===(n=this._outerEventEmitter)||void 0===n||n.emit(e,t)}getOuterEventEmitter(){return this._outerEventEmitter}rest(){this._outerEventEmitter=null,this._innerEventEmitter=null}};function r(e,t){var n={};for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.indexOf(s)<0&&(n[s]=e[s]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(s=Object.getOwnPropertySymbols(e);i<s.length;i++)t.indexOf(s[i])<0&&Object.prototype.propertyIsEnumerable.call(e,s[i])&&(n[s[i]]=e[s[i]])}return n}function a(e,t,n,s){return new(n||(n=Promise))((function(i,o){function r(e){try{c(s.next(e))}catch(e){o(e)}}function a(e){try{c(s.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(r,a)}c((s=s.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const c=e=>void 0===e,l=e=>"string"==typeof e,d=e=>{var t;return null===(t=Object.prototype.toString.call(e).match(/^\[object (.*)\]$/))||void 0===t?void 0:t[1].toLowerCase()},u=e=>"function"==typeof Array.isArray?Array.isArray(e):"array"===d(e),_=e=>null!==e&&"object"==typeof e,h=e=>u(e)||_(e),g=e=>{if("string"!=typeof e)return!1;const t=e[0];return!/[^a-zA-Z0-9]/.test(t)},f=e=>{if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);if(null===t)return!0;let n=t;for(;null!==Object.getPrototypeOf(n);)n=Object.getPrototypeOf(n);return t===n};function E(e=99999999){return Math.round(Math.random()*e)}const p=(e,t,n,s)=>{if(!h(e)||!h(t))return 0;let i=0;const o=Object.keys(t);let r;for(let a=0,l=o.length;a<l;a++)if(r=o[a],!(c(t[r])||n&&n.includes(r)))if(h(e[r])&&h(t[r]))i+=p(e[r],t[r],n,s);else{if(s&&s.includes(t[r]))continue;e[r]!==t[r]&&(e[r]=t[r],i+=1)}return i};function m(e){let t,n,s=e;e.length%8!=0&&(s="0".repeat(8-e.length%8)+e);let i="";for(let e=0,{length:o}=s;e<o;e+=8)t=parseInt(s.slice(e,e+4),2),n=parseInt(s.slice(e+4,e+8),2),i+=base16Map.get(t)+base16Map.get(n);return i}const S={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},v=["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 I=Object.freeze({__proto__:null,ENUM_PLATFORM:S,NOT_NEED_CRC_SERVCMD:v});const C="undefined"!=typeof wx&&"function"==typeof wx.getSystemInfoSync&&Boolean(wx.getSystemInfoSync().fontSizeSetting),y=C&&"function"==typeof wx.createGamePortal,M="undefined"!=typeof qq&&"function"==typeof qq.getSystemInfoSync&&Boolean(qq.getSystemInfoSync().fontSizeSetting),O="undefined"!=typeof tt&&"function"==typeof tt.getSystemInfoSync&&Boolean(tt.getSystemInfoSync().fontSizeSetting),T="undefined"!=typeof swan&&"function"==typeof swan.getSystemInfoSync&&Boolean(swan.getSystemInfoSync().fontSizeSetting),A="undefined"!=typeof my&&"function"==typeof my.getSystemInfoSync&&Boolean(my.getSystemInfoSync().fontSizeSetting),D="undefined"!=typeof jd&&"function"==typeof jd.getSystemInfoSync,N="undefined"!=typeof uni&&"undefined"==typeof window&&"function"==typeof uni.requireNativePlugin,R=C&&"object"==typeof wx.miniapp,b="undefined"!=typeof uni,w=C||M||O||T||A||N||D,k="undefined"==typeof window&&!w&&"undefined"!=typeof global&&void 0!==global.NativeScriptGlobals,L="undefined"!=typeof global&&(void 0!==global.nativeModuleProxy||void 0!==global.ReactNative),P="undefined"!=typeof wx&&"function"==typeof wx.getAccountInfoSync&&Boolean(wx.getAccountInfoSync().plugin),U="undefined"!=typeof uni?!w:"undefined"!=typeof window&&!w&&!L,G=M?qq:O?tt:T?swan:A?my:C?wx:N?uni:D?jd:{},F=U&&window&&window.navigator&&window.navigator.userAgent||"",x=/(micromessenger|webbrowser)/i.test(F),$=function(){let e="WEB";return x?e="WEB":M?e="QQ_MP":O?e="TT_MP":T?e="BAIDU_MP":A?e="ALI_MP":C?e=R?"DONUT_NATIVE_APP":"WX_MP":N?e="UNI_NATIVE_APP":k?e="NS_NATIVE_APP":L&&(e="RN_NATIVE_APP"),S[e]}(),B=/iPad/i.test(F),V=/iPhone/i.test(F)&&!B,q=/iPod/i.test(F),j=V||B||q,W=function(){const e=F.match(/OS (\d+)_/i);return e&&e[1]?e[1]:null}(),Y=/Android/i.test(F),K=function(){const e=F.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(!e)return null;const t=e[1]&&parseFloat(e[1]),n=e[2]&&parseFloat(e[2]);return t&&n?parseFloat(`${e[1]}.${e[2]}`):t||null}(),H=/Firefox/i.test(F),z=/Edge/i.test(F),J=!z&&/Chrome/i.test(F),Z=/MSIE/.test(F)||F.indexOf("Trident")>-1&&F.indexOf("rv:11.0")>-1,X=function(){const e=/MSIE\s(\d+)\.\d/.exec(F);let t=e&&parseFloat(e[1]);return!t&&/Trident\/7.0/i.test(F)&&/rv:11.0/.test(F)&&(t=11),t}(),Q=/Safari/i.test(F)&&!J&&!Y&&!z,ee=/Windows/i.test(F),te=/MAC OS X/i.test(F),ne=U&&"undefined"!=typeof Worker&&!Z,se=Y||j,ie=U&&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!(!j||e||Q)}();function re(){let e="unknown";if(te&&(e="mac"),ee&&(e="windows"),j&&(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 ae=2800,ce=2801,le=3e3,de="application/x-www-form-urlencoded;charset=UTF-8";function ue(e){return a(this,arguments,void 0,(function*({method:e,url:t,data:n,timeout:s=le}){return new Promise(w?(i,o)=>{G.request({url:t,data:n,method:e,timeout:s,header:{"content-type":de},success:e=>i(e.data),fail:()=>o(new Error(`{"message":"Network error","code":${ae}}`))})}:(i,o)=>{const r=new XMLHttpRequest,a=setTimeout((()=>{r.abort(),o(new Error(`{"message":"Request timeout","code":${ce}}`))}),s);r.onreadystatechange=function(){if(4===r.readyState)if(clearTimeout(a),200===r.status||304===r.status)try{i(r.responseText?JSON.parse(r.responseText):null)}catch(e){i(r.responseText)}else o(new Error(`{"message":"Network error","code":${ae}}`))},r.open(e,t,!0),r.setRequestHeader("Content-type",de),r.send(n||null)})}))}function _e(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(f(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 he(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,n)=>{t.set(he(n),he(e))})),t}if(e instanceof Set){const t=new Set;return e.forEach((e=>{t.add(he(e))})),t}if(Array.isArray(e))return e.map((e=>he(e)));const t=Object.getPrototypeOf(e),n=Object.create(t);return[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)].forEach((t=>{const s=Object.getOwnPropertyDescriptor(e,t);s&&(s.get||s.set?Object.defineProperty(n,t,s):n[t]=he(e[t]))})),n}function ge(){let e,t;return{promise:new Promise(((n,s)=>{e=n,t=s})),resolve:e,reject:t}}var fe=Object.freeze({__proto__:null,ANDROID_VERSION:K,IE_VERSION:X,IN_ALIPAY_MINI_APP:A,IN_BAIDU_MINI_APP:T,IN_BROWSER:U,IN_DONUT_NATIVE_APP:R,IN_JD_MINI_APP:D,IN_MINI_APP:w,IN_NS_NATIVE_APP:k,IN_QQ_MINI_APP:M,IN_RN_APP:L,IN_TT_MINI_APP:O,IN_UNI_APP:b,IN_UNI_NATIVE_APP:N,IN_WX_MINI_APP:C,IN_WX_MINI_GAME:y,IN_WX_MINI_PLUGIN:P,IOS_VERSION:W,IS_ANDROID:Y,IS_CHROME:J,IS_EDGE:z,IS_FIREFOX:H,IS_IE:Z,IS_IOS:j,IS_IPAD:B,IS_IPHONE:V,IS_IPOD:q,IS_MAC:te,IS_SAFARI:Q,IS_WECHAT:x,IS_WIN:ee,IS_WORKER_AVAILABLE:ne,MINI_APP_NAMESPACE:G,USER_AGENT:F,base16EncodeBinaryString:m,deepCopyWithMethods:he,deepMerge:p,generatePromise:ge,getPlatformType:re,getType:d,httpRequest:ue,isArray:u,isArrayOrObject:h,isEmpty:_e,isFlutterWeb:ie,isH5:se,isIOSWebView:oe,isNumber:e=>null!==e&&("number"==typeof e&&!Number.isNaN(e-0)||"object"==typeof e&&e.constructor===Number),isObject:_,isPlainObject:f,isString:l,isUndefined:c,isValidRequestKey:g,platform:$,randomInt:E,randomString:function(){const e="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";let t="";for(let n=32;n>0;--n)t+=e[Math.floor(62*Math.random())];return t}});class Ee{constructor(){this._socket=null}connectSocket(e){return this._socket=new WebSocket(e),this._socket}send(e){var t,n;try{null===(t=this._socket)||void 0===t||t.send(e)}catch(e){null===(n=this._onSendFail)||void 0===n||n.call(this,e)}}bindSocketHandlers(e){const{onOpen:t,onMessage:n,onClose:s,onError:i,onSendFail:o}=e;this._socket&&(this._socket.binaryType="arraybuffer",this._socket.onopen=t,this._socket.onmessage=n,this._socket.onclose=s,this._socket.onerror=i,this._onSendFail=o)}unbindSocketHandlers(){this._socket&&(this._socket.onopen=null,this._socket.onmessage=null,this._socket.onclose=null,this._socket.onerror=null)}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}class pe{connectSocket(e){return this._socket=wx.connectSocket({url:e,header:{"content-type":"application/json"},complete:()=>{}}),this._socket}send(e){var t;null===(t=this._socket)||void 0===t||t.send({data:e,fail:this._onSendFail})}bindSocketHandlers(e){const{onOpen:t,onMessage:n,onClose:s,onError:i,onSendFail:o}=e;this._socket.onClose(s),this._socket.onOpen(t),this._socket.onMessage(n),this._socket.onError(i),this._onSendFail=o}unbindSocketHandlers(){this._socket&&(this._socket.onClose((()=>{})),this._socket.onOpen((()=>{})),this._socket.onMessage((()=>{})),this._socket.onError((()=>{})))}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}const me="CONNECT",Se="SEND",ve="DISCONNECT",Ie="OPEN",Ce="MESSAGE",ye="CLOSE",Me="ERROR",Oe="SEND_FAIL";class Te{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:me,url:e})}send(e){var t,n;try{null===(t=this._worker)||void 0===t||t.postMessage({type:Se,data:e})}catch(e){null===(n=this._onSendFail)||void 0===n||n.call(this,e)}}bindSocketHandlers(e){const{onOpen:t,onMessage:n,onClose:s,onError:i,onSendFail:o}=e;if(this._worker){const e={[Ie]:t,[Ce]:n,[ye]:s,[Me]:i,[Oe]:o};this._onSendFail=o,this._worker.onmessage=t=>{var n;const{type:s}=(null==t?void 0:t.data)||{};"function"==typeof e[s]&&(null===(n=e[s])||void 0===n||n.call(e,null==t?void 0:t.data))}}}unbindSocketHandlers(){this._worker&&(this._worker.onmessage=null)}disconnect(){this._worker&&(this._worker.postMessage({type:ve}),this._worker.terminate(),this._worker=null),this._blobUrl&&(URL.revokeObjectURL(this._blobUrl),this._blobUrl=null)}}var Ae,De=new class{constructor(){this._store=new Map}get(e){return this._store.get(e)}getStorage(e){if(w){if(A){return my.getStorageSync({key:e}).data}return G.getStorageSync(e)}return this._canUseLocalStorage()?localStorage.getItem(e):{}}set(e,t){const n=this._store.get(e)||{};t instanceof Map?this._store.set(e,t):this._store.set(e,Object.assign(Object.assign({},n),t))}setStorage(e,t){w?A?my.setStorageSync({key:e,data:JSON.stringify(t)}):G.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"}(Ae||(Ae={}));class Ne{constructor(t){this._url="",this._readyState=Ae.DISCONNECTED,this._url=t,this._id=E(),this._emitter=new e,C?this._socket=new pe:this._canUseWebWorker()?this._socket=new Te:this._socket=new Ee,this.connect()}connect(){this.doOpen(),this._bindSocketHandlers()}doOpen(){[Ae.CONNECTED,Ae.CONNECTING].includes(this._readyState)||(this._readyState=Ae.CONNECTING,this._ws=this._socket.connectSocket(this._url))}send(e){this._readyState!==Ae.CONNECTED?this.reconnect():this._socket.send(e)}reconnect(){[Ae.CONNECTED,Ae.CONNECTING].includes(this._readyState)||(this.disconnect(),this.doOpen())}getId(){return this._id}on(e,t,n){this._emitter.on(e,t,n)}off(e,t,n){this._emitter.off(e,t,n)}isConnected(){return this._readyState===Ae.CONNECTED}disconnect(){this._readyState=Ae.DISCONNECTED,this._unbindSocketHandlers(),this._socket.disconnect()}_onOpen(e){this._readyState===Ae.CONNECTING&&(this._readyState=Ae.CONNECTED,this._emitter.emit("connect",{socketId:this._id,event:e}))}_onMessage(e){this._emitter.emit("message",e)}_onClose(e){this._readyState=Ae.DISCONNECTED,this._emitter.emit("close",{socketId:this._id,event:e})}_onError(e){this._readyState=Ae.DISCONNECTED,this._emitter.emit("error",{socketId:this._id,error:e})}_onSendFail(e){this._readyState=Ae.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=De.get("cloudConfig")||{};return(c(e.isWorkerEnabled)||"1"===e.isWorkerEnabled)&&ne}}const Re="CHINA",be="SINGAPORE",we="KOREA",ke="GERMANY",Le="IND",Pe="JPN",Ue="USA",Ge="INDONESIA",Fe={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"}}},xe={[be]:[[2e7,3e7],[172e7,173e7]],[we]:[[3e7,4e7],[173e7,174e7]],[ke]:[[4e7,5e7],[174e7,175e7]],[Le]:[[5e7,6e7],[175e7,176e7]],[Pe]:[[6e7,7e7],[176e7,177e7]],[Ue]:[[7e7,8e7],[177e7,178e7]],[Ge]:[[8e7,9e7],[178e7,179e7]]};function $e(e){for(const t of Object.keys(xe))for(const[n,s]of xe[t])if(e>=n&&e<s)return t;return Re}var Be,Ve="1.2.0";!function(e){e.INITIAL="INITIAL",e.DEFAULT="DEFAULT",e.BACKUP="BACKUP",e.ANYCAST="ANYCAST"}(Be||(Be={}));let qe=Be.INITIAL;function je(){const e=Math.random();return 0===e?je():e}function We(e,t){const{isBinary:n=!1}=t||{},s=De.get("instance"),{sdkAppId:i,instanceId:o}=s,r=je(),a=re(),c=function(){const e=re();let t=-1;"ios"===e?t=W||-1:"android"===e&&(t=K||-1);return t}(),l=(d={sdkappid:i,instanceid:o,random:r,platform:$,host:a,version:c,sdkversion:Ve},Object.keys(d).map((e=>`${e}=${d[e]}`)).join("&"));var d;return n?`${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 n=Date.now(),s=n-e;this._timeOffsetWithServer=t+s-n}};const Ke=16;var He=new class{constructor(){this._tasks=[],this._timer=null,this._taskMap=new Map}_addTaskToScheduler(e){const{id:t}=e;this.removeTask(t),this._tasks.push(e),this._taskMap.set(t,e),this._sort(),this._scheduleNextTask()}_createTask(e){const{id:t,callback:n,context:s,isOnce:i=!1,intervalMs:o=Ke}=e,r=Math.max(o,Ke);return{id:t,nextExecuteTime:Date.now()+r,intervalMs:o,callback:n,context:s,isOnce:i}}addTask(e){const t=this._createTask(e);this._addTaskToScheduler(t)}addOnceTask(e){const t=this._createTask(Object.assign(Object.assign({},e),{isOnce:!0}));this._addTaskToScheduler(t)}removeTask(e){const t=this._tasks.findIndex((t=>t.id===e));t>-1&&(this._tasks.splice(t,1),this._taskMap.delete(e),this._scheduleNextTask())}updateTaskInterval(e,t){const n=this._taskMap.get(e);n&&(n.intervalMs=t,n.nextExecuteTime=Date.now()+t,this._sort(),this._scheduleNextTask())}clearAllTasks(){this._tasks=[],this._taskMap.clear(),this._timer&&(clearTimeout(this._timer),this._timer=null)}dispose(){this.clearAllTasks()}_sort(){this._tasks.sort(((e,t)=>e.nextExecuteTime-t.nextExecuteTime))}_scheduleNextTask(){this._timer&&(clearTimeout(this._timer),this._timer=null);const e=this._tasks[0];if(e){const t=Math.max(0,e.nextExecuteTime-Date.now());this._timer=setTimeout((()=>this._execute()),t)}}_execute(){const e=Date.now();for(;this._tasks.length&&this._tasks[0].nextExecuteTime<=e;){const t=this._tasks[0];try{t.context?t.callback.call(t.context):t.callback(),t.isOnce?this.removeTask(t.id):(t.nextExecuteTime=e+t.intervalMs,this._sort())}catch(e){console.warn(`Task ${t.id} execution failed:`,e),t.isOnce&&this.removeTask(t.id)}}this._scheduleNextTask()}};function ze(e){const t=[];for(let n=0;n<e.length;n+=1){const s=e.charCodeAt(n);if(s>=55296&&s<=56319){const i=e.charCodeAt(++n)-56320+(s-55296<<10)+65536;t.push(240|i>>18,128|i>>12&63,128|i>>6&63,128|63&i)}else s<=127?t.push(s):s<=2047?t.push(192|s>>6,128|63&s):t.push(224|s>>12,128|s>>6&63,128|63&s)}return new Uint8Array(t)}function Je(e){const t=Array.isArray(e)?[]:Object.create(null);for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&g(n)&&null!=e[n]&&(null===e[n]||"object"!=typeof e[n]?t[n]=e[n]:t[n]=Je(e[n]));return t}function Ze(e,t){if(v.includes(e))return 0;const n=ze(JSON.stringify(t));let s=4294967295;const{length:i}=n;for(let e=0;e<i;e++){s^=n[e];for(let e=0;e<8;e++)1&~s?s>>>=1:s=s>>>1^3988292384}return(4294967295^s)>>>0}function Xe(e){const{servcmd:t,data:n}=e,s=function(e){const t=De.get("login")||{},n=De.get("instance")||{};return{servcmd:e,ver:"v4",platform:$,websdkappid:537048168,websdkversion:"1.7.3",a2:t.a2Key||void 0,tinyid:t.tinyID||void 0,status_instid:t.statusInstanceId||0,sdkappid:n.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:t.a2Key?void 0:t.userId,usersig:t.a2Key?void 0:t.userSig,sdkability:75689843,sdkability_ext:m(""),cappid:t.cappid||0,tjgID:"",seq:nt(),cs:0}}(t),i=Je(n);return s.cs=Ze(t,i),{head:s,body:i}}function Qe(e){const{servcmd:t,data:n}=e,s=function(e){const t=De.get("login")||{},n=De.get("instance")||{};return{servcmd:e,ver:"v4",platform:$,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:n.sdkAppId,contenttype:"",reqtime:Math.floor(Date.now()/1e3),identifier:"",usersig:"",status_instid:t.statusInstanceId||0,sdkability:75689843,sdkability_ext:m(""),cappid:t.cappid||0,seq:nt(),cs:0}}(t),i=Je(n);return s.cs=Ze(t,i),{head:s,body:i}}let et=E();function nt(){return et=et<2415919103?et+1:E(),et}var st,it=Object.freeze({__proto__:null,generateCosSpecifiedData:function(e){const{servcmd:t,data:n}=e,s=function(e){const t=De.get("login")||{},n=De.get("instance")||{};return{servcmd:e,ver:"v4",platform:$,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:n.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:t.userId,usersig:t.userSig,status_instid:t.statusInstanceId||0,sdkability:75689843,sdkability_ext:m(""),cappid:t.cappid||0,seq:nt(),cs:0}}(t),i=Je(n);return s.cs=Ze(t,i),{head:s,body:i}},generateProtocolData:Xe,generateSSOLogProtocolData:Qe,generateSequence:nt,taskScheduler:He,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 rt{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:n=0}=e||{};this.eventType=n,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=De.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 n=t;ot[n]&&(e[ot[n]]=this[n])})),e}}var at;function ct(){const e=De.get("login")||{},t=De.get("instance")||{};return{sdk_type:30,sdk_app_id:t.sdkAppId,sdk_version:"1.2.0",tiny_id:Number(e.tinyID),user_id:e.userId,platform:$,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"}(at||(at={}));var lt=at;const dt=20,ut=6e4,_t=[4,5,6],ht=[],gt=[],ft="report-logger";var Et=new class{constructor(){this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._reportLevel=[4,5,6],this._minThreshold=dt,this._maxThreshold=100,this._waitingTime=ut,this._lastReportAt=Date.now(),this._ssoLogMap=new Map,o.subscribeInnerEvent(lt.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),He.addTask({id:ft,intervalMs:1e3,callback:this._checkAndReportIfDue,context:this}),this._logQueue=[],this._savePlatFormInfo()}_handleCloudConfigUpdate(e){const{evt_rpt_threshold:t=dt,evt_rpt_waiting:n=ut,evt_rpt_level:s=_t,evt_rpt_sdkappid_bl:i=ht,evt_rpt_tinyid_wl:o=gt}=e||{};this._sdkAppIdBlackList=i,this._waitingTime=n,this._minThreshold=t,this._reportLevel=s,this._tinyIdWhiteList=o}createSSOLogData(e){const t=new rt(e);return t.setSSOLogModule(this),this._ssoLogMap.set(e.method,t),t}getSSOLogData(e){return this._ssoLogMap.get(e)||{}}pushToLogQueue(e){e&&(this._logQueue.push(e),this._shouldUploadImmediately()&&this._uploadSSOLogData())}_shouldUploadImmediately(){return this._logQueue.length>=this._minThreshold}_isReportDue(){return Date.now()>=this._lastReportAt+this._waitingTime}_checkAndReportIfDue(){this._isReportDue()&&this._logQueue.length>0&&this._uploadSSOLogData()}_uploadSSOLogData(){return a(this,void 0,void 0,(function*(){if(0===this._logQueue.length)return;const e=this._logQueue.slice(),t=this._filterLogs(e);if(this._logQueue=[],0===t.length)return void(this._lastReportAt=Date.now());const n={Header:ct(),Event:t};yield function(e){const t="imopenstat.tim_web_report_v2",n=Qe({servcmd:t,data:e}),s=`${n.head.seq}${t}`;Ut.sendPacket(n,{requestId:s})}(n),this._lastReportAt=Date.now()}))}_savePlatFormInfo(){var e,t;if(C){const n=null===(t=null===(e=wx.getAccountInfoSync)||void 0===e?void 0:e.call(wx))||void 0===t?void 0:t.miniProgram;if(n){const{appId:e,envVersion:t}=n;De.set("instance",{appId:e,envVersion:t})}}else U&&De.set("instance",{href:window.location.href})}_filterLogs(e){const{tinyID:t}=De.get("login")||{},{sdkAppId:n}=De.get("instance")||{};return this._sdkAppIdBlackList.includes(n)&&!this._tinyIdWhiteList.includes(t)?[]:e.filter((e=>this._reportLevel.includes(e.level)))}reset(){console.log("SSO_LOG_MODULE.reset"),He.removeTask(ft),o.unSubscribeInnerEvent(lt.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),this._lastReportAt=0,this._uploadSSOLogData(),this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._minThreshold=dt,this._maxThreshold=100,this._waitingTime=ut,this._logQueue=[]}};const pt=15e3,mt="Channel",St="channel_schedule_task",vt="channel_reconnect_task",It="connected",Ct="connecting",yt="disconnected",Mt=500,Ot="network_status_change",Tt="activity_status_change",At="send_fail",Dt="reconnect_failed",Nt="socket_error",Rt="socket_close";function bt(e){return bt="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},bt(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 kt,Lt={exports:{}};var Pt=(kt||(kt=1,Lt.exports=function e(t,n,s){function i(r,a){if(!n[r]){if(!t[r]){if(!a&&wt)return wt(r);if(o)return o(r,!0);var c=new Error("Cannot find module '"+r+"'");throw c.code="MODULE_NOT_FOUND",c}var l=n[r]={exports:{}};t[r][0].call(l.exports,(function(e){return i(t[r][1][e]||e)}),l,l.exports,e,t,n,s)}return n[r].exports}for(var o=wt,r=0;r<s.length;r++)i(s[r]);return i}({1:[function(e,t,n){var s="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;n.assign=function(e){for(var t,n,s=Array.prototype.slice.call(arguments,1);s.length;){var i=s.shift();if(i){if("object"!=bt(i))throw new TypeError(i+"must be non-object");for(var o in i)t=i,n=o,Object.prototype.hasOwnProperty.call(t,n)&&(e[o]=i[o])}}return e},n.shrinkBuf=function(e,t){return e.length===t?e:e.subarray?e.subarray(0,t):(e.length=t,e)};var i={arraySet:function(e,t,n,s,i){if(t.subarray&&e.subarray)e.set(t.subarray(n,n+s),i);else for(var o=0;o<s;o++)e[i+o]=t[n+o]},flattenChunks:function(e){var t,n,s,i,o,r;for(t=s=0,n=e.length;t<n;t++)s+=e[t].length;for(r=new Uint8Array(s),t=i=0,n=e.length;t<n;t++)o=e[t],r.set(o,i),i+=o.length;return r}},o={arraySet:function(e,t,n,s,i){for(var o=0;o<s;o++)e[i+o]=t[n+o]},flattenChunks:function(e){return[].concat.apply([],e)}};n.setTyped=function(e){e?(n.Buf8=Uint8Array,n.Buf16=Uint16Array,n.Buf32=Int32Array,n.assign(n,i)):(n.Buf8=Array,n.Buf16=Array,n.Buf32=Array,n.assign(n,o))},n.setTyped(s)},{}],2:[function(e,t,n){var s=e("./common"),i=!0,o=!0;try{String.fromCharCode.apply(null,[0])}catch(e){i=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(e){o=!1}for(var r=new s.Buf8(256),a=0;a<256;a++)r[a]=252<=a?6:248<=a?5:240<=a?4:224<=a?3:192<=a?2:1;function c(e,t){if(t<65534&&(e.subarray&&o||!e.subarray&&i))return String.fromCharCode.apply(null,s.shrinkBuf(e,t));for(var n="",r=0;r<t;r++)n+=String.fromCharCode(e[r]);return n}r[254]=r[254]=1,n.string2buf=function(e){var t,n,i,o,r,a=e.length,c=0;for(o=0;o<a;o++)55296==(64512&(n=e.charCodeAt(o)))&&o+1<a&&56320==(64512&(i=e.charCodeAt(o+1)))&&(n=65536+(n-55296<<10)+(i-56320),o++),c+=n<128?1:n<2048?2:n<65536?3:4;for(t=new s.Buf8(c),o=r=0;r<c;o++)55296==(64512&(n=e.charCodeAt(o)))&&o+1<a&&56320==(64512&(i=e.charCodeAt(o+1)))&&(n=65536+(n-55296<<10)+(i-56320),o++),n<128?t[r++]=n:(n<2048?t[r++]=192|n>>>6:(n<65536?t[r++]=224|n>>>12:(t[r++]=240|n>>>18,t[r++]=128|n>>>12&63),t[r++]=128|n>>>6&63),t[r++]=128|63&n);return t},n.buf2binstring=function(e){return c(e,e.length)},n.binstring2buf=function(e){for(var t=new s.Buf8(e.length),n=0,i=t.length;n<i;n++)t[n]=e.charCodeAt(n);return t},n.buf2string=function(e,t){var n,s,i,o,a=t||e.length,l=new Array(2*a);for(n=s=0;n<a;)if((i=e[n++])<128)l[s++]=i;else if(4<(o=r[i]))l[s++]=65533,n+=o-1;else{for(i&=2===o?31:3===o?15:7;1<o&&n<a;)i=i<<6|63&e[n++],o--;1<o?l[s++]=65533:i<65536?l[s++]=i:(i-=65536,l[s++]=55296|i>>10&1023,l[s++]=56320|1023&i)}return c(l,s)},n.utf8border=function(e,t){var n;for((t=t||e.length)>e.length&&(t=e.length),n=t-1;0<=n&&128==(192&e[n]);)n--;return n<0||0===n?t:n+r[e[n]]>t?n:t}},{"./common":1}],3:[function(e,t,n){t.exports=function(e,t,n,s){for(var i=65535&e,o=e>>>16&65535,r=0;0!==n;){for(n-=r=2e3<n?2e3:n;o=o+(i=i+t[s++]|0)|0,--r;);i%=65521,o%=65521}return i|o<<16}},{}],4:[function(e,t,n){t.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],5:[function(e,t,n){var s=function(){for(var e,t=[],n=0;n<256;n++){e=n;for(var s=0;s<8;s++)e=1&e?3988292384^e>>>1:e>>>1;t[n]=e}return t}();t.exports=function(e,t,n,i){var o=s,r=i+n;e^=-1;for(var a=i;a<r;a++)e=e>>>8^o[255&(e^t[a])];return~e}},{}],6:[function(e,t,n){t.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],7:[function(e,t,n){t.exports=function(e,t){var n,s,i,o,r,a,c,l,d,u,_,h,g,f,E,p,m,S,v,I,C,y,M,O,T;n=e.state,s=e.next_in,O=e.input,i=s+(e.avail_in-5),o=e.next_out,T=e.output,r=o-(t-e.avail_out),a=o+(e.avail_out-257),c=n.dmax,l=n.wsize,d=n.whave,u=n.wnext,_=n.window,h=n.hold,g=n.bits,f=n.lencode,E=n.distcode,p=(1<<n.lenbits)-1,m=(1<<n.distbits)-1;e:do{g<15&&(h+=O[s++]<<g,g+=8,h+=O[s++]<<g,g+=8),S=f[h&p];t:for(;;){if(h>>>=v=S>>>24,g-=v,0==(v=S>>>16&255))T[o++]=65535&S;else{if(!(16&v)){if(!(64&v)){S=f[(65535&S)+(h&(1<<v)-1)];continue t}if(32&v){n.mode=12;break e}e.msg="invalid literal/length code",n.mode=30;break e}I=65535&S,(v&=15)&&(g<v&&(h+=O[s++]<<g,g+=8),I+=h&(1<<v)-1,h>>>=v,g-=v),g<15&&(h+=O[s++]<<g,g+=8,h+=O[s++]<<g,g+=8),S=E[h&m];n: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 n}e.msg="invalid distance code",n.mode=30;break e}if(C=65535&S,g<(v&=15)&&(h+=O[s++]<<g,(g+=8)<v&&(h+=O[s++]<<g,g+=8)),c<(C+=h&(1<<v)-1)){e.msg="invalid distance too far back",n.mode=30;break e}if(h>>>=v,g-=v,(v=o-r)<C){if(d<(v=C-v)&&n.sane){e.msg="invalid distance too far back",n.mode=30;break e}if(M=_,(y=0)===u){if(y+=l-v,v<I){for(I-=v;T[o++]=_[y++],--v;);y=o-C,M=T}}else if(u<v){if(y+=l+u-v,(v-=u)<I){for(I-=v;T[o++]=_[y++],--v;);if(y=0,u<I){for(I-=v=u;T[o++]=_[y++],--v;);y=o-C,M=T}}}else if(y+=u-v,v<I){for(I-=v;T[o++]=_[y++],--v;);y=o-C,M=T}for(;2<I;)T[o++]=M[y++],T[o++]=M[y++],T[o++]=M[y++],I-=3;I&&(T[o++]=M[y++],1<I&&(T[o++]=M[y++]))}else{for(y=o-C;T[o++]=T[y++],T[o++]=T[y++],T[o++]=T[y++],2<(I-=3););I&&(T[o++]=T[y++],1<I&&(T[o++]=T[y++]))}break}}break}}while(s<i&&o<a);s-=I=g>>3,h&=(1<<(g-=I<<3))-1,e.next_in=s,e.next_out=o,e.avail_in=s<i?i-s+5:5-(s-i),e.avail_out=o<a?a-o+257:257-(o-a),n.hold=h,n.bits=g}},{}],8:[function(e,t,n){var s=e("../utils/common"),i=e("./adler32"),o=e("./crc32"),r=e("./inffast"),a=e("./inftrees"),c=1,l=2,d=0,u=-2,_=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 s.Buf16(320),this.work=new s.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function 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 s.Buf32(h),t.distcode=t.distdyn=new s.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 n,s;return e&&e.state?(s=e.state,t<0?(n=0,t=-t):(n=1+(t>>4),t<48&&(t&=15)),t&&(t<8||15<t)?u:(null!==s.window&&s.wbits!==t&&(s.window=null),s.wrap=n,s.wbits=t,m(e))):u}function v(e,t){var n,s;return e?(s=new E,(e.state=s).window=null,(n=S(e,t))!==d&&(e.state=null),n):u}var I,C,y=!0;function M(e){if(y){var t;for(I=new s.Buf32(512),C=new s.Buf32(32),t=0;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(a(c,e.lens,0,288,I,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;a(l,e.lens,0,32,C,0,e.work,{bits:5}),y=!1}e.lencode=I,e.lenbits=9,e.distcode=C,e.distbits=5}function O(e,t,n,i){var o,r=e.state;return null===r.window&&(r.wsize=1<<r.wbits,r.wnext=0,r.whave=0,r.window=new s.Buf8(r.wsize)),i>=r.wsize?(s.arraySet(r.window,t,n-r.wsize,r.wsize,0),r.wnext=0,r.whave=r.wsize):(i<(o=r.wsize-r.wnext)&&(o=i),s.arraySet(r.window,t,n-i,o,r.wnext),(i-=o)?(s.arraySet(r.window,t,n-i,i,0),r.wnext=i,r.whave=r.wsize):(r.wnext+=o,r.wnext===r.wsize&&(r.wnext=0),r.whave<r.wsize&&(r.whave+=o))),0}n.inflateReset=m,n.inflateReset2=S,n.inflateResetKeep=p,n.inflateInit=function(e){return v(e,15)},n.inflateInit2=v,n.inflate=function(e,t){var n,h,g,E,p,m,S,v,I,C,y,T,A,D,N,R,b,w,k,L,P,U,G,F,x=0,$=new s.Buf8(4),B=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!e||!e.state||!e.output||!e.input&&0!==e.avail_in)return u;12===(n=e.state).mode&&(n.mode=13),p=e.next_out,g=e.output,S=e.avail_out,E=e.next_in,h=e.input,m=e.avail_in,v=n.hold,I=n.bits,C=m,y=S,U=d;e:for(;;)switch(n.mode){case _:if(0===n.wrap){n.mode=13;break}for(;I<16;){if(0===m)break e;m--,v+=h[E++]<<I,I+=8}if(2&n.wrap&&35615===v){$[n.check=0]=255&v,$[1]=v>>>8&255,n.check=o(n.check,$,2,0),I=v=0,n.mode=2;break}if(n.flags=0,n.head&&(n.head.done=!1),!(1&n.wrap)||(((255&v)<<8)+(v>>8))%31){e.msg="incorrect header check",n.mode=30;break}if(8!=(15&v)){e.msg="unknown compression method",n.mode=30;break}if(I-=4,P=8+(15&(v>>>=4)),0===n.wbits)n.wbits=P;else if(P>n.wbits){e.msg="invalid window size",n.mode=30;break}n.dmax=1<<P,e.adler=n.check=1,n.mode=512&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(n.flags=v,8!=(255&n.flags)){e.msg="unknown compression method",n.mode=30;break}if(57344&n.flags){e.msg="unknown header flags set",n.mode=30;break}n.head&&(n.head.text=v>>8&1),512&n.flags&&($[0]=255&v,$[1]=v>>>8&255,n.check=o(n.check,$,2,0)),I=v=0,n.mode=3;case 3:for(;I<32;){if(0===m)break e;m--,v+=h[E++]<<I,I+=8}n.head&&(n.head.time=v),512&n.flags&&($[0]=255&v,$[1]=v>>>8&255,$[2]=v>>>16&255,$[3]=v>>>24&255,n.check=o(n.check,$,4,0)),I=v=0,n.mode=4;case 4:for(;I<16;){if(0===m)break e;m--,v+=h[E++]<<I,I+=8}n.head&&(n.head.xflags=255&v,n.head.os=v>>8),512&n.flags&&($[0]=255&v,$[1]=v>>>8&255,n.check=o(n.check,$,2,0)),I=v=0,n.mode=5;case 5:if(1024&n.flags){for(;I<16;){if(0===m)break e;m--,v+=h[E++]<<I,I+=8}n.length=v,n.head&&(n.head.extra_len=v),512&n.flags&&($[0]=255&v,$[1]=v>>>8&255,n.check=o(n.check,$,2,0)),I=v=0}else n.head&&(n.head.extra=null);n.mode=6;case 6:if(1024&n.flags&&(m<(T=n.length)&&(T=m),T&&(n.head&&(P=n.head.extra_len-n.length,n.head.extra||(n.head.extra=new Array(n.head.extra_len)),s.arraySet(n.head.extra,h,E,T,P)),512&n.flags&&(n.check=o(n.check,h,T,E)),m-=T,E+=T,n.length-=T),n.length))break e;n.length=0,n.mode=7;case 7:if(2048&n.flags){if(0===m)break e;for(T=0;P=h[E+T++],n.head&&P&&n.length<65536&&(n.head.name+=String.fromCharCode(P)),P&&T<m;);if(512&n.flags&&(n.check=o(n.check,h,T,E)),m-=T,E+=T,P)break e}else n.head&&(n.head.name=null);n.length=0,n.mode=8;case 8:if(4096&n.flags){if(0===m)break e;for(T=0;P=h[E+T++],n.head&&P&&n.length<65536&&(n.head.comment+=String.fromCharCode(P)),P&&T<m;);if(512&n.flags&&(n.check=o(n.check,h,T,E)),m-=T,E+=T,P)break e}else n.head&&(n.head.comment=null);n.mode=9;case 9:if(512&n.flags){for(;I<16;){if(0===m)break e;m--,v+=h[E++]<<I,I+=8}if(v!==(65535&n.check)){e.msg="header crc mismatch",n.mode=30;break}I=v=0}n.head&&(n.head.hcrc=n.flags>>9&1,n.head.done=!0),e.adler=n.check=0,n.mode=12;break;case 10:for(;I<32;){if(0===m)break e;m--,v+=h[E++]<<I,I+=8}e.adler=n.check=f(v),I=v=0,n.mode=11;case 11:if(0===n.havedict)return e.next_out=p,e.avail_out=S,e.next_in=E,e.avail_in=m,n.hold=v,n.bits=I,2;e.adler=n.check=1,n.mode=12;case 12:if(5===t||6===t)break e;case 13:if(n.last){v>>>=7&I,I-=7&I,n.mode=27;break}for(;I<3;){if(0===m)break e;m--,v+=h[E++]<<I,I+=8}switch(n.last=1&v,I-=1,3&(v>>>=1)){case 0:n.mode=14;break;case 1:if(M(n),n.mode=20,6!==t)break;v>>>=2,I-=2;break e;case 2:n.mode=17;break;case 3:e.msg="invalid block type",n.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",n.mode=30;break}if(n.length=65535&v,I=v=0,n.mode=15,6===t)break e;case 15:n.mode=16;case 16:if(T=n.length){if(m<T&&(T=m),S<T&&(T=S),0===T)break e;s.arraySet(g,h,E,T,p),m-=T,E+=T,S-=T,p+=T,n.length-=T;break}n.mode=12;break;case 17:for(;I<14;){if(0===m)break e;m--,v+=h[E++]<<I,I+=8}if(n.nlen=257+(31&v),v>>>=5,I-=5,n.ndist=1+(31&v),v>>>=5,I-=5,n.ncode=4+(15&v),v>>>=4,I-=4,286<n.nlen||30<n.ndist){e.msg="too many length or distance symbols",n.mode=30;break}n.have=0,n.mode=18;case 18:for(;n.have<n.ncode;){for(;I<3;){if(0===m)break e;m--,v+=h[E++]<<I,I+=8}n.lens[B[n.have++]]=7&v,v>>>=3,I-=3}for(;n.have<19;)n.lens[B[n.have++]]=0;if(n.lencode=n.lendyn,n.lenbits=7,G={bits:n.lenbits},U=a(0,n.lens,0,19,n.lencode,0,n.work,G),n.lenbits=G.bits,U){e.msg="invalid code lengths set",n.mode=30;break}n.have=0,n.mode=19;case 19:for(;n.have<n.nlen+n.ndist;){for(;R=(x=n.lencode[v&(1<<n.lenbits)-1])>>>16&255,b=65535&x,!((N=x>>>24)<=I);){if(0===m)break e;m--,v+=h[E++]<<I,I+=8}if(b<16)v>>>=N,I-=N,n.lens[n.have++]=b;else{if(16===b){for(F=N+2;I<F;){if(0===m)break e;m--,v+=h[E++]<<I,I+=8}if(v>>>=N,I-=N,0===n.have){e.msg="invalid bit length repeat",n.mode=30;break}P=n.lens[n.have-1],T=3+(3&v),v>>>=2,I-=2}else if(17===b){for(F=N+3;I<F;){if(0===m)break e;m--,v+=h[E++]<<I,I+=8}I-=N,P=0,T=3+(7&(v>>>=N)),v>>>=3,I-=3}else{for(F=N+7;I<F;){if(0===m)break e;m--,v+=h[E++]<<I,I+=8}I-=N,P=0,T=11+(127&(v>>>=N)),v>>>=7,I-=7}if(n.have+T>n.nlen+n.ndist){e.msg="invalid bit length repeat",n.mode=30;break}for(;T--;)n.lens[n.have++]=P}}if(30===n.mode)break;if(0===n.lens[256]){e.msg="invalid code -- missing end-of-block",n.mode=30;break}if(n.lenbits=9,G={bits:n.lenbits},U=a(c,n.lens,0,n.nlen,n.lencode,0,n.work,G),n.lenbits=G.bits,U){e.msg="invalid literal/lengths set",n.mode=30;break}if(n.distbits=6,n.distcode=n.distdyn,G={bits:n.distbits},U=a(l,n.lens,n.nlen,n.ndist,n.distcode,0,n.work,G),n.distbits=G.bits,U){e.msg="invalid distances set",n.mode=30;break}if(n.mode=20,6===t)break e;case 20:n.mode=21;case 21:if(6<=m&&258<=S){e.next_out=p,e.avail_out=S,e.next_in=E,e.avail_in=m,n.hold=v,n.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=n.hold,I=n.bits,12===n.mode&&(n.back=-1);break}for(n.back=0;R=(x=n.lencode[v&(1<<n.lenbits)-1])>>>16&255,b=65535&x,!((N=x>>>24)<=I);){if(0===m)break e;m--,v+=h[E++]<<I,I+=8}if(R&&!(240&R)){for(w=N,k=R,L=b;R=(x=n.lencode[L+((v&(1<<w+k)-1)>>w)])>>>16&255,b=65535&x,!(w+(N=x>>>24)<=I);){if(0===m)break e;m--,v+=h[E++]<<I,I+=8}v>>>=w,I-=w,n.back+=w}if(v>>>=N,I-=N,n.back+=N,n.length=b,0===R){n.mode=26;break}if(32&R){n.back=-1,n.mode=12;break}if(64&R){e.msg="invalid literal/length code",n.mode=30;break}n.extra=15&R,n.mode=22;case 22:if(n.extra){for(F=n.extra;I<F;){if(0===m)break e;m--,v+=h[E++]<<I,I+=8}n.length+=v&(1<<n.extra)-1,v>>>=n.extra,I-=n.extra,n.back+=n.extra}n.was=n.length,n.mode=23;case 23:for(;R=(x=n.distcode[v&(1<<n.distbits)-1])>>>16&255,b=65535&x,!((N=x>>>24)<=I);){if(0===m)break e;m--,v+=h[E++]<<I,I+=8}if(!(240&R)){for(w=N,k=R,L=b;R=(x=n.distcode[L+((v&(1<<w+k)-1)>>w)])>>>16&255,b=65535&x,!(w+(N=x>>>24)<=I);){if(0===m)break e;m--,v+=h[E++]<<I,I+=8}v>>>=w,I-=w,n.back+=w}if(v>>>=N,I-=N,n.back+=N,64&R){e.msg="invalid distance code",n.mode=30;break}n.offset=b,n.extra=15&R,n.mode=24;case 24:if(n.extra){for(F=n.extra;I<F;){if(0===m)break e;m--,v+=h[E++]<<I,I+=8}n.offset+=v&(1<<n.extra)-1,v>>>=n.extra,I-=n.extra,n.back+=n.extra}if(n.offset>n.dmax){e.msg="invalid distance too far back",n.mode=30;break}n.mode=25;case 25:if(0===S)break e;if(T=y-S,n.offset>T){if((T=n.offset-T)>n.whave&&n.sane){e.msg="invalid distance too far back",n.mode=30;break}T>n.wnext?(T-=n.wnext,A=n.wsize-T):A=n.wnext-T,T>n.length&&(T=n.length),D=n.window}else D=g,A=p-n.offset,T=n.length;for(S<T&&(T=S),S-=T,n.length-=T;g[p++]=D[A++],--T;);0===n.length&&(n.mode=21);break;case 26:if(0===S)break e;g[p++]=n.length,S--,n.mode=21;break;case 27:if(n.wrap){for(;I<32;){if(0===m)break e;m--,v|=h[E++]<<I,I+=8}if(y-=S,e.total_out+=y,n.total+=y,y&&(e.adler=n.check=n.flags?o(n.check,g,y,p-y):i(n.check,g,y,p-y)),y=S,(n.flags?v:f(v))!==n.check){e.msg="incorrect data check",n.mode=30;break}I=v=0}n.mode=28;case 28:if(n.wrap&&n.flags){for(;I<32;){if(0===m)break e;m--,v+=h[E++]<<I,I+=8}if(v!==(4294967295&n.total)){e.msg="incorrect length check",n.mode=30;break}I=v=0}n.mode=29;case 29:U=1;break e;case 30:U=-3;break e;case 31:return-4;default:return u}return e.next_out=p,e.avail_out=S,e.next_in=E,e.avail_in=m,n.hold=v,n.bits=I,(n.wsize||y!==e.avail_out&&n.mode<30&&(n.mode<27||4!==t))&&O(e,e.output,e.next_out,y-e.avail_out)?(n.mode=31,-4):(C-=e.avail_in,y-=e.avail_out,e.total_in+=C,e.total_out+=y,n.total+=y,n.wrap&&y&&(e.adler=n.check=n.flags?o(n.check,g,y,e.next_out-y):i(n.check,g,y,e.next_out-y)),e.data_type=n.bits+(n.last?64:0)+(12===n.mode?128:0)+(20===n.mode||15===n.mode?256:0),(0===C&&0===y||4===t)&&U===d&&(U=-5),U)},n.inflateEnd=function(e){if(!e||!e.state)return u;var t=e.state;return t.window&&(t.window=null),e.state=null,d},n.inflateGetHeader=function(e,t){var n;return e&&e.state&&2&(n=e.state).wrap?((n.head=t).done=!1,d):u},n.inflateSetDictionary=function(e,t){var n,s=t.length;return e&&e.state?0!==(n=e.state).wrap&&11!==n.mode?u:11===n.mode&&i(1,t,s,0)!==n.check?-3:O(e,t,s,s)?(n.mode=31,-4):(n.havedict=1,d):u},n.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":1,"./adler32":3,"./crc32":5,"./inffast":7,"./inftrees":9}],9:[function(e,t,n){var s=e("../utils/common"),i=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],o=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],r=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],a=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];t.exports=function(e,t,n,c,l,d,u,_){var h,g,f,E,p,m,S,v,I,C=_.bits,y=0,M=0,O=0,T=0,A=0,D=0,N=0,R=0,b=0,w=0,k=null,L=0,P=new s.Buf16(16),U=new s.Buf16(16),G=null,F=0;for(y=0;y<=15;y++)P[y]=0;for(M=0;M<c;M++)P[t[n+M]]++;for(A=C,T=15;1<=T&&0===P[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===P[O];O++);for(A<O&&(A=O),y=R=1;y<=15;y++)if(R<<=1,(R-=P[y])<0)return-1;if(0<R&&(0===e||1!==T))return-1;for(U[1]=0,y=1;y<15;y++)U[y+1]=U[y]+P[y];for(M=0;M<c;M++)0!==t[n+M]&&(u[U[t[n+M]]++]=M);if(0===e?(k=G=u,m=19):1===e?(k=i,L-=257,G=o,F-=257,m=256):(k=r,G=a,m=-1),y=O,p=d,N=M=w=0,f=-1,E=(b=1<<(D=A))-1,1===e&&852<b||2===e&&592<b)return 1;for(;;){for(S=y-N,u[M]<m?(v=0,I=u[M]):u[M]>m?(v=G[F+u[M]],I=k[L+u[M]]):(v=96,I=0),h=1<<y-N,O=g=1<<D;l[p+(w>>N)+(g-=h)]=S<<24|v<<16|I,0!==g;);for(h=1<<y-1;w&h;)h>>=1;if(0!==h?(w&=h-1,w+=h):w=0,M++,0==--P[y]){if(y===T)break;y=t[n+u[M]]}if(A<y&&(w&E)!==f){for(0===N&&(N=A),p+=O,R=1<<(D=y-N);D+N<T&&!((R-=P[D+N])<=0);)D++,R<<=1;if(b+=1<<D,1===e&&852<b||2===e&&592<b)return 1;l[f=w&E]=A<<24|D<<16|p-d}}return 0!==w&&(l[p+w]=y-N<<24|64<<16),_.bits=A,0}},{"../utils/common":1}],10:[function(e,t,n){t.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],11:[function(e,t,n){t.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],"/lib/inflate.js":[function(e,t,n){var s=e("./zlib/inflate"),i=e("./utils/common"),o=e("./utils/strings"),r=e("./zlib/constants"),a=e("./zlib/messages"),c=e("./zlib/zstream"),l=e("./zlib/gzheader"),d=Object.prototype.toString;function u(e){if(!(this instanceof u))return new u(e);this.options=i.assign({chunkSize:16384,windowBits:0,to:""},e||{});var t=this.options;t.raw&&0<=t.windowBits&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(0<=t.windowBits&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),15<t.windowBits&&t.windowBits<48&&!(15&t.windowBits)&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new c,this.strm.avail_out=0;var n=s.inflateInit2(this.strm,t.windowBits);if(n!==r.Z_OK)throw new Error(a[n]);if(this.header=new l,s.inflateGetHeader(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=o.string2buf(t.dictionary):"[object ArrayBuffer]"===d.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(n=s.inflateSetDictionary(this.strm,t.dictionary))!==r.Z_OK))throw new Error(a[n])}function _(e,t){var n=new u(t);if(n.push(e,!0),n.err)throw n.msg||a[n.err];return n.result}u.prototype.push=function(e,t){var n,a,c,l,u,_=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=o.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 i.Buf8(h),_.next_out=0,_.avail_out=h),(n=s.inflate(_,r.Z_NO_FLUSH))===r.Z_NEED_DICT&&g&&(n=s.inflateSetDictionary(this.strm,g)),n===r.Z_BUF_ERROR&&!0===f&&(n=r.Z_OK,f=!1),n!==r.Z_STREAM_END&&n!==r.Z_OK)return this.onEnd(n),!(this.ended=!0);_.next_out&&(0!==_.avail_out&&n!==r.Z_STREAM_END&&(0!==_.avail_in||a!==r.Z_FINISH&&a!==r.Z_SYNC_FLUSH)||("string"===this.options.to?(c=o.utf8border(_.output,_.next_out),l=_.next_out-c,u=o.buf2string(_.output,c),_.next_out=l,_.avail_out=h-l,l&&i.arraySet(_.output,_.output,c,l,0),this.onData(u)):this.onData(i.shrinkBuf(_.output,_.next_out)))),0===_.avail_in&&0===_.avail_out&&(f=!0)}while((0<_.avail_in||0===_.avail_out)&&n!==r.Z_STREAM_END);return n===r.Z_STREAM_END&&(a=r.Z_FINISH),a===r.Z_FINISH?(n=s.inflateEnd(this.strm),this.onEnd(n),this.ended=!0,n===r.Z_OK):a!==r.Z_SYNC_FLUSH||(this.onEnd(r.Z_OK),!(_.avail_out=0))},u.prototype.onData=function(e){this.chunks.push(e)},u.prototype.onEnd=function(e){e===r.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=i.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg},n.Inflate=u,n.inflate=_,n.inflateRaw=function(e,t){return(t=t||{}).raw=!0,_(e,t)},n.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")),Lt.exports);var Ut=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=Mt,this._currentConnectState=It,this._beforeSendInterceptors=[]}init(){He.addTask({id:St,intervalMs:1e3,callback:this._executeScheduledTaskIfReady,context:this}),this._updateIsBinarySupported(),this._url=function(e){const t=De.get("instance"),{sdkAppId:n,testEnv:s}=t,i=$e(n);return We(s?Fe.TEST[i].DEFAULT:Fe.PRODUCTION[i].INITIAL.replace("*",`${n}`),{isBinary:e})}(this._isBinarySupported),o.subscribeInnerEvent("networkStatusChange",this._handleNetworkStatusChange,this),o.subscribeInnerEvent("activityStatusChange",this._handleActivityStatusChange,this),this.connect()}sendPacket(e,t){var n;const{requestId:s,timeout:i=pt,canResend:o=!0}=t||{};if(_e(e))return console.warn(`${mt}.sendPacket: packet is empty `,e),null;this._executeBeforeSendInterceptors(e);const r=JSON.stringify(e);let a=null;if(s){const{resolve:e,reject:t,promise:n}=ge();a=n,this._pendingRequests.set(s,{resolve:e,reject:t,timestamp:Date.now(),uplinkData:r,timeout:i,canResend:o})}const c=this._isBinarySupported?ze(r).buffer:r;return null===(n=this._socketAdapter)||void 0===n||n.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(),n=`${mt}.connect isWorkerEnabled: false socketID:${t} url:${this._url}`;this._ssoLog({method:"connect",message:n}),console.log(n)}disconnect(){var e,t;const n=null===(e=this._socketAdapter)||void 0===e?void 0:e.getId(),s=`${mt}.disconnect socketID:${n}`;this._ssoLog({method:"disconnect",message:s}),console.log(s),this._removeEventListeners(),null===(t=this._socketAdapter)||void 0===t||t.disconnect()}getSocketAdapter(){return this._socketAdapter}dispose(){console.log(`${mt}.dispose`),He.removeTask(St),He.removeTask(vt),o.unSubscribeInnerEvent("networkStatusChange",this._handleNetworkStatusChange,this),o.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=Mt,this._url=""}registerBeforeSendInterceptor(e,t){this._beforeSendInterceptors.push(e.bind(t))}_executeBeforeSendInterceptors(e){for(const t of this._beforeSendInterceptors){const{servcmd:n=""}=null==e?void 0:e.head;t(n.includes(".")?n.split(".").pop():"")}}_shouldSkipReconnect(){const e=this._currentConnectState===Ct&&this._isReconnecting;return!this._socketAdapter||e}reconnect(){return a(this,void 0,void 0,(function*(){const e=`${mt} 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=De.get("instance"),{sdkAppId:n,testEnv:s}=t,i=$e(n);if(s)return We(Fe.TEST[i].DEFAULT,{isBinary:e});const o=Fe.PRODUCTION[i],r=U&&o.ANYCAST;return We({[Be.INITIAL]:()=>(qe=Be.DEFAULT,o.DEFAULT),[Be.DEFAULT]:()=>(qe=Be.BACKUP,o.BACKUP),[Be.BACKUP]:()=>(qe=r?Be.ANYCAST:Be.DEFAULT,r?o.ANYCAST:o.DEFAULT),[Be.ANYCAST]:()=>(qe=Be.DEFAULT,o.ANYCAST="",o.DEFAULT)}[qe](),{isBinary:e})}(this._isBinarySupported);try{this._isReconnecting=!0,this.disconnect(),this.connect()}catch(e){this._isReconnecting=!1,this._handleConnectStateChange({state:yt,reason:Dt}),console.warn(`${mt} reconnect failed: `,e)}}}))}_addEventListeners(){var e,t,n,s,i;null===(e=this._socketAdapter)||void 0===e||e.on("connect",this._onConnect,this),null===(t=this._socketAdapter)||void 0===t||t.on("message",this._onMessage,this),null===(n=this._socketAdapter)||void 0===n||n.on("close",this._onClose,this),null===(s=this._socketAdapter)||void 0===s||s.on("error",this._onError,this),null===(i=this._socketAdapter)||void 0===i||i.on("sendFail",this._onSendFail,this)}_removeEventListeners(){var e,t,n,s,i;null===(e=this._socketAdapter)||void 0===e||e.off("connect",this._onConnect,this),null===(t=this._socketAdapter)||void 0===t||t.off("message",this._onMessage,this),null===(n=this._socketAdapter)||void 0===n||n.off("close",this._onClose,this),null===(s=this._socketAdapter)||void 0===s||s.off("error",this._onError,this),null===(i=this._socketAdapter)||void 0===i||i.off("sendFail",this._onSendFail,this)}_onClose(e){const{socketId:t,event:n}=e||{},s=0!==this._connectionEstablishedTime?Date.now()-this._connectionEstablishedTime:0,i=`${mt} onClose closeSocketID: ${t} currentSocketID: ${this._connectionId} connectionDuration: ${s} code:${null==n?void 0:n.code} reason:${null==n?void 0:n.reason}`;this._ssoLog({method:"onClose",message:i}),console.warn(i),t===this._connectionId&&this._handleConnectStateChange({state:yt,reason:Rt}),this._isReconnecting&&(this._isReconnecting=!1)}_onError(e){const{socketId:t,error:n}=e||{},s=`${mt} onError sourceSocketID: ${t} currentSocketID:${this._connectionId} isReconnecting: ${this._isReconnecting} error: ${JSON.stringify(n)}`;this._ssoLog({method:"onError",message:s}),console.warn(s),t===this._connectionId&&this._handleConnectStateChange({state:yt,reason:Nt}),this._isReconnecting&&(this._isReconnecting=!1)}_onSendFail(e){const{socketId:t,error:n}=e||{},s=`${mt} onSendFail sendFailSocketId: ${t} currentSocketID:${this._connectionId} isReconnecting: ${this._isReconnecting} error: ${n}`;this._ssoLog({method:"onSendFail",message:s}),console.warn(s),t===this._connectionId&&this._handleConnectStateChange({state:yt,reason:At}),this._isReconnecting&&(this._isReconnecting=!1)}_onMessage(e){let t,n;this._updateHeartbeatTime();try{t=this._isBinarySupported?this._isCompressedData(e.data)?(e=>{const t=new Uint8Array(e).slice(4);let n;try{n=Pt.inflate(t,{to:"string"})}catch(e){console.error("inflate error",e)}return n})(e.data):function(e){const t=new Uint8Array(e);let n="",s=0;const{length:i}=t;for(;s<i;){let e=t[s],o=0,r=0;if(e<=127?(o=0,r=255&e):e<=223?(o=1,r=31&e):e<=239?(o=2,r=15&e):e<=244&&(o=3,r=7&e),i-s-o>0)for(let n=0;n<o;n+=1)e=t[s+n+1],r=r<<6|63&e;else r=65533,o=i-s;n+=String.fromCodePoint(r),s+=o+1}return n}(e.data):e.data,n=JSON.parse(t)}catch(t){const n=e.data;return this._ssoLog({method:"jsonParseError",message:n}),void console.error(t)}if(!n||!n.head)return;const{seq:s,servcmd:i}=n.head,o=`${s}${i}`;this._pendingRequests.has(o)?this._handleRequestResponse(n):this._handlePushMessage(n)}_handleRequestResponse(e){const{seq:t,servcmd:n}=e.head,{int32_error_code:s,str_error_message:i,ErrorCode:r=s,ErrorInfo:a=i}=(null==e?void 0:e.body)||{},c=`${t}${n}`,{resolve:l,reject:d,timestamp:u,headSeq:_}=this._pendingRequests.get(c);if(this._pendingRequests.delete(c),r&&0!==r)return o.emitInnerEvent("error",{errorCode:r,errorInfo:a}),void d({errorCode:r,errorInfo:a});l(e.body)}_handlePushMessage(e){const{servcmd:t}=e.head,{NeedAck:n,SessionData:s}=e.body;1===n&&this._sendAck(s),o.emitInnerEvent(t,e)}_checkPendingRequestsAndResend(){var e;console.log(`${mt}._checkPendingRequestsAndResend reConnectFlag:${this._isReconnecting} promiseMap.size:${this._pendingRequests.size}`),null===(e=this._pendingRequests)||void 0===e||e.forEach(((e,t)=>{var n;const{uplinkData:s,canResend:i,resolve:o,reject:r,timeout:a}=e;if(i){this._pendingRequests.set(t,{resolve:o,reject:r,timestamp:Date.now(),uplinkData:s,timeout:a,canResend:i});const e=this._isBinarySupported?ze(s).buffer:s;null===(n=this._socketAdapter)||void 0===n||n.send(e)}else this._pendingRequests.delete(t)}))}_onConnect(e){const{socketId:t,event:n={}}=e||{};this._connectionId=t,this._connectionEstablishedTime=Date.now();const s=Date.now()-this._connectionStartTime,i=`${mt} onConnect cost:${s} ms. socketID:${t} res:${JSON.stringify(n)}`;if(this._ssoLog({method:"onConnect",message:i}),console.log(i),this._checkPendingRequestsAndResend(),this._sendHeartbeatIfReady(),this._isReconnecting){const e=`${mt} reconnect success`;this._ssoLog({method:"reconnectSuccess",message:e}),console.log(e),o.emitInnerEvent(lt.RECONNECTED),this._isReconnecting=!1}this._resetReconnectDelay(),this._handleConnectStateChange({state:It})}_sendAck(e){const t=Xe({servcmd:"openim.ws_msg_push_ack",data:{SessionData:e}});this.sendPacket(t)}_executeScheduledTaskIfReady(){return a(this,void 0,void 0,(function*(){this._clearTimeoutRequest(),this._sendHeartbeatIfReady()}))}_canSendHeartbeat(){var e;return(null===(e=this._socketAdapter)||void 0===e?void 0:e.isConnected())&&Date.now()>=this._nextHeartbeatAt&&!this._isHeartbeatInProgress}_sendHeartbeat(){return a(this,void 0,void 0,(function*(){var e;const t=Xe({servcmd:"heartbeat.alive",data:{}});try{const e=`${t.head.seq}${t.head.servcmd}`;yield this.sendPacket(t,{requestId:e,timeout:3e3})}catch(t){const n=null===(e=De.get("netWorkMonitor"))||void 0===e?void 0:e.isNetWorkOnline,s=`${mt} sendHeartbeat failed. isNetWorkOnline:${n} error: ${t}`;this._ssoLog({method:"sendHeartbeatError",message:s}),console.debug(s),this._handleConnectStateChange({state:yt,reason:At})}}))}_sendHeartbeatIfReady(){return a(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=`${mt} networkStatusChange ${JSON.stringify(e)}`;this._ssoLog({method:"networkStatusChange",message:t}),console.warn(t);const{isNetworkOnline:n,networkType:s}=e;n&&"none"!==s?this._handleConnectStateChange({state:It,reason:Ot}):this._handleConnectStateChange({state:yt,reason:Ot})}isPrivateNetWork(){const e=De.get("instance")||{};return e.proxyServer&&!e.fileDownloadProxy}_handleConnectStateChange(e){const{state:t,reason:n}=e;if(this._currentConnectState!==t){const e=`${mt}._handleConnectStateChange from ${this._currentConnectState} to ${t} reason: ${n}`;this._ssoLog({method:"handleConnectStateChange",message:e}),console.log(e),this._currentConnectState=t,o.emitOuterEvent("netStateChange",{name:"netStateChange",data:{state:t}}),t===yt&&o.emitInnerEvent(lt.SOCKET_DISCONNECTED),t!==yt&&t!==It||(this._resetReconnectDelay(),He.addTask({id:vt,intervalMs:this._intendedDelay,callback:this._scheduleReconnectWithBackoff,context:this}))}}_handleActivityStatusChange(e){var t,n;const s=null===(n=null===(t=this._socketAdapter)||void 0===t?void 0:t._ws)||void 0===n?void 0:n.readyState,i=`${mt} activityStatusChange ${JSON.stringify(e)} readyState: ${s}`;this._ssoLog({method:"activityStatusChange",message:i}),console.warn(i),3===s&&this._handleConnectStateChange({state:yt,reason:Tt})}_resetReconnectDelay(){var e;He.removeTask(vt);const t=null===(e=De.get("activityMonitor"))||void 0===e?void 0:e.isActive;this._intendedDelay=t?Mt:1e3}_scheduleReconnectWithBackoff(){var e;const t=null===(e=De.get("activityMonitor"))||void 0===e?void 0:e.isActive;this._intendedDelay=t?Math.min(5e3,Math.max(Mt,1.5*this._intendedDelay)):Math.min(3e5,Math.max(1e3,1.5*this._intendedDelay));const n=(new Date).toTimeString().slice(0,8),s=`${mt}.scheduleReconnectWithBackoff timeStr: ${n} intendedDelay: ${this._intendedDelay}`;this._ssoLog({method:"scheduleReconnectWithBackoff",message:s}),console.log(s),this.reconnect(),He.updateTaskInterval(vt,this._intendedDelay)}_ssoLog(e){const{method:t,message:n}=e;Et.createSSOLogData({method:t}).setLogInfo({message:n}).end()}_diagnose(){this.isPrivateNetWork()||(this._lastDiagnoseAt=Date.now(),function(e){a(this,void 0,void 0,(function*(){const t=e.split("/")[2];if(!t.startsWith("ws"))return;const n=`https://${t}/v3/netcheck/getconninfo?${e.slice(e.indexOf("info?")+5)}&reqtime=${Date.now()}`;try{yield ue({method:"GET",url:n,data:{}})}catch(e){console.warn("diagnoseBySSO failed. error:",e)}}))}(this._url),function(e){a(this,void 0,void 0,(function*(){const t=`https://boce-cdn.my-imcloud.com/v3/netcheck/getconninfo?${e.slice(e.indexOf("info?")+5)}&reqtime=${Date.now()}`;try{yield ue({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:n,timestamp:s,timeout:i}=t;Date.now()-s>=i&&(this._pendingRequests.delete(e),Date.now()-this._lastDiagnoseAt>=3e4&&this._diagnose(),n({errorCode:ce,errorInfo:"NETWORK_TIMEOUT",data:{requestId:e}}))}}_updateIsBinarySupported(){var e;if(null===(e=De.get("instance"))||void 0===e?void 0:e.devMode)return void(this._isBinarySupported=!1);const t=re();(A||C&&"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 Gt={init:function(e){De.set("instance",e),Ut.init()},destroy:function(){Ut.dispose(),De.clear(),He.dispose()},notificationCenter:o,channel:Ut,store:De,ssoLog:Et,utils:fe,common:it,constants:I};var Ft;!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"}(Ft||(Ft={}));var xt,$t=Ft;!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"}(xt||(xt={}));var Bt,Vt=xt;!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 qt=Bt;const jt=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:Vt.MESSAGE_MODIFIED,delete:Vt.MESSAGE_DELETED,revoke:Vt.MESSAGE_REVOKED},Ht=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}),zt={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"},Jt=Object.assign({},zt),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"}),Xt=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"}),Qt={COMMUNITY:"@TGS#_",TOPIC:"@TOPIC#_"},en=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:Qt}),tn=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},jt),Ht),Jt),Zt),Xt),en),{IOS_OFFLINE_PUSH_NO_SOUND:"push.no_sound",IOS_OFFLINE_PUSH_DEFAULT_SOUND:"default"}),{NET_STATE_CONNECTING:"connecting",NET_STATE_DISCONNECTED:"disconnected"}),nn={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},sn={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"},on={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"},rn={[sn.SYNC_SERVER_INFO_AFTER_RE_ONLINE]:[{stepId:on.USER_STATUS_UPDATE},{stepId:on.GROUP_ATTRIBUTE_CACHE_CLEAR},{stepId:on.UNREAD_MESSAGE_SYNC},{stepId:on.CONVERSATION_RECOVER},{stepId:on.HISTORY_MESSAGE_RECOVER,dependency:on.CONVERSATION_RECOVER},{stepId:on.BLACKLIST_RECOVER},{stepId:on.FRIEND_RECOVER},{stepId:on.GROUP_REVOKED_NOTICE_RECOVER},{stepId:on.HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD,dependency:on.UNREAD_MESSAGE_SYNC},{stepId:on.HANDLE_GROUP_TIPS_FROM_SYNC_UNREAD,dependency:on.UNREAD_MESSAGE_SYNC},{stepId:on.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[on.UNREAD_MESSAGE_SYNC,on.CONVERSATION_RECOVER]},{stepId:on.EMIT_C2C_MESSAGE_EVENT,dependency:[on.UNREAD_MESSAGE_SYNC,on.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED],skipIfDependencyMissing:!1}],[sn.SYNC_SERVER_INFO_AFTER_LOGIN]:[{stepId:on.COMMERCIAL_CONFIG_UPDATE},{stepId:on.CLOUD_CONFIG_SYNC},{stepId:on.USER_PROFILE_SYNC},{stepId:on.UNREAD_MESSAGE_SYNC},{stepId:on.FRIEND_AND_BLACKLIST_SYNC},{stepId:on.GROUP_LIST_SYNC},{stepId:on.CONVERSATION_LIST_SYNC},{stepId:on.SIGNALING_MESSAGE_RECOVER,dependency:on.UNREAD_MESSAGE_SYNC},{stepId:on.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[on.UNREAD_MESSAGE_SYNC,on.CONVERSATION_LIST_SYNC]},{stepId:on.CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED,dependency:[on.GROUP_LIST_SYNC,on.CONVERSATION_LIST_SYNC]}],[sn.RECEIVE_C2C_NEW_MESSAGE]:[{stepId:on.HANDLE_C2C_NEW_MESSAGE},{stepId:on.UNREAD_MESSAGE_SYNC},{stepId:on.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:on.HANDLE_C2C_NEW_MESSAGE},{stepId:on.EMIT_C2C_MESSAGE_EVENT,dependency:[on.HANDLE_C2C_NEW_MESSAGE,on.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1},{stepId:on.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[on.UNREAD_MESSAGE_SYNC]}],[sn.RECEIVE_GROUP_NEW_MESSAGE]:[{stepId:on.HANDLE_GROUP_NEW_MESSAGE},{stepId:on.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:on.HANDLE_GROUP_NEW_MESSAGE},{stepId:on.UPDATE_GROUP_NEXT_SEQUENCE,dependency:on.HANDLE_GROUP_NEW_MESSAGE},{stepId:on.EMIT_GROUP_MESSAGE_EVENT,dependency:[on.HANDLE_GROUP_NEW_MESSAGE,on.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1}]};var an=Object.freeze({__proto__:null,ERROR_CODE:nn,InnerEvent:Vt,OuterConstant:tn,OuterEvent:$t,SDK_INFO:{VERSION:"1.7.3",APPID:537048168},SignalingEvent:qt,WORKFLOW_DEFINITIONS:rn,WORKFLOW_NAME:sn,WORKFLOW_STEP:on});function cn(e){var t;try{const n=De.getStorage("errorMessage");if(!e||!n)return"";const s=(null===(t=JSON.parse(n))||void 0===t?void 0:t.errorMessage)||{},{isIntl:i=!1,code:o,replacement1:r="",replacement2:a=""}=e;if(!o)return"";const c=i?`${o}_en`:`${o}_cn`;let l=s[s[c]?c:o]||"";return l&&(r&&(l=l.replace("$replacement1",r)),a&&(l=l.replace("$replacement2",a))),l}catch(e){return console.warn("Error parsing stored error messages:",e),""}}class ln extends Error{constructor(e){const{functionName:t="Unknown",code:n,message:s="",data:i=""}=e;let o=s;n&&!s&&(o=cn(e));const r=n?`${t} failed. error: {"message": ${o}, "code": ${n}}`:`${t} failed. error: {"message": ${o}}`;super(),this.code=n,this.errorCode=n,this.errorMessage=r,this.message=r,this.data=i}}function dn(e,t){var n;if(!e)return;if(!(!0===(null===(n=Gt.store.get("login"))||void 0===n?void 0:n.isLoggedIn)))throw new ln({code:nn.USER_NOT_LOGGED_IN,functionName:t})}const un=e=>"function"==typeof e;function _n(e,t,n){const s=n||[];if(!e||!t)return!1;const i=Object.keys(e).filter((e=>!s.includes(e))),o=Object.keys(t).filter((e=>!s.includes(e)));return i.length===o.length&&i.every((s=>!!t.hasOwnProperty(s)&&("object"==typeof e[s]&&null!==e[s]?_n(e[s],t[s],n):e[s]===t[s])))}function hn(e,t,n){if(Array.isArray(e))for(let s=0;s<e.length;s++)gn.call(this,Object.assign(Object.assign({},e[s]),{value:t[s],name:n}));else for(const s in e)gn.call(this,Object.assign(Object.assign({},e[s]),{value:t[0][s],name:n,key:s}))}function gn({required:e,rules:t,range:n,value:s,allowEmpty:i,name:o,key:r,customValidator:a}){if(void 0===s){if(e){throw new ln({functionName:o,message:`[${o}] Missing required params: "${r}"`})}return}let c="";if(!t.some((e=>{return e===(t=s,Object.prototype.toString.call(t).match(/^\[object (.*)\]$/)[1].toLowerCase());var t}))){for(let e=0;e<t.length;e++){let n=t[e];n=n.replace(n[0],n[0].toUpperCase()),c+=`${n}/`}c=c.substring(0,c.length-1);const e=`[${r}] must be type of ${c}, received type: ${function(e){return Reflect.apply(Object.prototype.toString,e,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}(s)}.`;throw new ln({functionName:o,message:e})}if(!1===i){if(Array.isArray(s)&&(0===s.length||"string"==typeof s[0]&&""===s[0].trim())){throw new ln({functionName:o,message:`${r} can not be empty.`})}if("string"==typeof s&&""===s.trim()){throw new ln({functionName:o,message:`${r} can not be empty.`})}}if(a&&"function"==typeof a){const e=a(s);if(!0!==e){throw new ln({functionName:o,message:`[${r}] custom validation failed: ${e||"Invalid value"}`})}}}const fn=[],En={},pn={};function mn(e,t){dn(En[e],e),hn(pn[e],t,e),function(e){fn.forEach((t=>{const{interceptor:n,context:s}=t;n.apply(s,[e])}))}(e)}function Sn(e,t){fn.push({interceptor:e,context:t})}function vn(e){const{params:t,auth:n}=e;t&&"object"==typeof t&&Object.assign(pn,t),n&&"object"==typeof n&&Object.assign(En,n)}var In=new class{constructor(){this._builtInPlugins=new WeakSet,this._externalPlugins=new WeakSet}installBuiltInPlugin(e){e&&this._installPlugin(e,this._builtInPlugins)}installExternalPlugin(e,t){e&&this._installPlugin(e,this._externalPlugins,t)}clear(){this._builtInPlugins=new WeakSet,this._externalPlugins=new WeakSet}_installPlugin(e,t,n){let s=[];s=Array.isArray(e)?e:[e],s.forEach((e=>{t.has(e)||(e&&un(e.install)?(t.add(e),e.install(Yn(),n),un(e.handleLoginSuccess)&&this._isLoggedIn()&&e.handleLoginSuccess()):un(e)?(t.add(e),e(Yn(),n),un(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=Gt.store.get("login"))||void 0===e?void 0:e.isLoggedIn)}};function Cn(e){return Gt.store.get("commercialConfig").get(e)}const yn=new Map;var Mn=new class{constructor(){this._handlers=new Map,this._activeWorkflows=new Map,this._stepStartTimes=new Map,this._logHandlers={start:(e,t)=>{const n=Date.now();t?(this._stepStartTimes.set(`${e}-${t}`,n),console.log(`[Workflow ${e}] Step ${t} started at ${new Date(n).toISOString()}`)):(this._workflowStartTimes.set(e,n),console.log(`[Workflow ${e}] started at ${new Date(n).toISOString()}`))},success:(e,t)=>{const n=Date.now();if(t){const s=this._stepStartTimes.get(`${e}-${t}`),i=s?n-s:0;this._stepStartTimes.delete(`${e}-${t}`),console.log(`[Workflow ${e}] Step ${t} completed successfully at ${new Date(n).toISOString()} (${i}ms)`)}else{const t=this._workflowStartTimes.get(e),s=t?n-t:0;this._workflowStartTimes.delete(e),console.log(`[Workflow ${e}] completed successfully at ${new Date(n).toISOString()} (${s}ms)`)}},error:(e,t,n)=>{const s=Date.now();if(t){const i=this._stepStartTimes.get(`${e}-${t}`),o=i?s-i:0;this._stepStartTimes.delete(`${e}-${t}`),console.error(`[Workflow ${e}] Step ${t} failed at ${new Date(s).toISOString()} (${o}ms)`,n)}else{const t=this._workflowStartTimes.get(e),i=t?s-t:0;this._workflowStartTimes.delete(e),console.error(`[Workflow ${e}] failed at ${new Date(s).toISOString()} (${i}ms)`,n)}}}}init(){this._initializeWorkflows()}registerWorkflowStep(e,t,n,s){if(!this._handlers.has(e))return void console.debug(`Workflow '${e}' not defined in core`);if(!rn[e].find((e=>e.stepId===t)))return void console.debug(`Step '${t}' not defined in workflow '${e}'`);this._handlers.get(e).set(t,s?n.bind(s):n)}executeWorkflow(e,t){return a(this,void 0,void 0,(function*(){if(!this._validateWorkflow(e))return;console.log(`[Workflow ${e}] Started execution at ${(new Date).toISOString()}`);const n=rn[e],s={},i={cancelled:!1};this._activeWorkflows.set(e,{cancelToken:i});try{const o=new Map;n.forEach((e=>{o.set(e.stepId,e)}));const r={workflowName:e,pendingSteps:new Set(n.map((e=>e.stepId))),completedSteps:new Set,runningSteps:new Set,stepMap:o,stepResults:s,data:t,cancelToken:i};yield new Promise(((t,n)=>{const s=()=>{if(i.cancelled)return void t();this._getExecutableSteps({pendingSteps:r.pendingSteps,completedSteps:r.completedSteps,stepMap:r.stepMap}).filter((e=>!r.runningSteps.has(e))).forEach((i=>this._executeWorkflowStep(i,r,{onComplete:()=>{if(0===r.pendingSteps.size)return void t();0===this._getExecutableSteps({pendingSteps:r.pendingSteps,completedSteps:r.completedSteps,stepMap:r.stepMap}).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:n,onStepComplete:s})))};s()})),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,n){return a(this,void 0,void 0,(function*(){const{workflowName:s,runningSteps:i,stepMap:o,stepResults:r,data:a}=t;i.add(e),this._logWorkflowExecution(s,e,"start");try{const n=o.get(e);let i=null;(null==n?void 0:n.dependency)&&(l(n.dependency)?i=r[n.dependency]:Array.isArray(n.dependency)&&(i={},n.dependency.forEach((e=>{i[e]=r[e]}))));const c=this._handlers.get(s).get(e);if(c){const t=yield Promise.resolve(c({data:a,result:i}));r[e]=t,this._logWorkflowExecution(s,e,"success")}t.completedSteps.add(e)}catch(t){const i=`[Workflow].${s}.${e}`,{errorCode:o,errorInfo:r=`${i} failed`}=t||{},a=new ln({functionName:i,code:o,message:r});Gt.ssoLog.createSSOLogData({method:"Workflow"}).setLogInfo({message:`workflowName: ${s}, stepId: ${e}`}).setError(a).end(),this._logWorkflowExecution(s,e,"error",t),n.onError(t)}finally{i.delete(e),t.pendingSteps.delete(e),n.onStepComplete(),n.onComplete()}}))}reset(){this._cancelAllWorkflows()}destroy(){this.reset(),this._handlers.clear()}_initializeWorkflows(){Object.keys(rn).forEach((e=>{this._handlers.set(e,new Map)}))}_cancelWorkFlow(e){const t=this._activeWorkflows.get(e);if(!t)return;const{cancelToken:n}=t;n.cancelled=!0,this._activeWorkflows.delete(e)}_cancelAllWorkflows(){Object.keys(rn).forEach((e=>{this._cancelWorkFlow(e)}))}_validateWorkflow(e){if(!rn[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:n,stepMap:s}=e;return Array.from(t).filter((e=>{const t=s.get(e)||{},{dependency:i,skipIfDependencyMissing:o=!0}=t;if(!i)return!0;if(l(i))return s.has(i)?n.has(i):!o;if(u(i)){if(i.filter((e=>!s.has(e))).length>0)return!o;for(const e of i)if(!n.has(e))return!1;return!0}return!1}))}_logWorkflowExecution(e,t,n,s){this._logHandlers[n](e,t)}};function On(){var e;return null===(e=Gt.store.get("login"))||void 0===e?void 0:e.userId}const Tn=e=>u(e)||_(e),An=(e,t,n,s)=>{if(!Tn(e)||!Tn(t))return 0;let i=0;const o=Object.keys(t);let r;for(let a=0,l=o.length;a<l;a++)if(r=o[a],!(c(t[r])||n&&n.includes(r)))if(Tn(e[r])&&Tn(t[r]))i+=An(e[r],t[r],n,s);else{if(s&&s.includes(t[r]))continue;e[r]!==t[r]&&(e[r]=t[r],i+=1)}return i},Dn=e=>`${e}`.startsWith(Qt.COMMUNITY)&&`${e}`.includes(Qt.TOPIC),Nn=(e,t)=>{if(c(t))return"";switch(e){case tn.MSG_TEXT:return t.text||"";case tn.MSG_IMAGE:return"[Image]";case tn.MSG_LOCATION:return"[Location]";case tn.MSG_AUDIO:return"[Voice]";case tn.MSG_VIDEO:return"[Video]";case tn.MSG_FILE:return"[File]";case tn.MSG_CUSTOM:return"[Custom Messages]";case tn.MSG_GRP_TIP:return"[Group Notification]";case tn.MSG_GRP_SYS_NOTICE:return"[Group System Message]";case tn.MSG_FACE:return"[Animated Sticker]";case tn.MSG_MERGER:return"[Chat Record]";default:return""}};var Rn=Object.freeze({__proto__:null,ChatError:ln,buildAndSendPacket:function(e){return a(this,void 0,void 0,(function*(){const{servcmd:t,data:n}=e,s=Gt.common.generateProtocolData({servcmd:t,data:n}),i=`${s.head.seq}${t}`;return Gt.channel.sendPacket(s,{requestId:i})}))},checkBusinessCapabilityBits:Cn,deepMerge:An,destroy:jn,exposeApiForClient:Wn,exposeApiForPlugin:Yn,getCurrentUserID:On,getErrorMessage:cn,getMessagePreviewText:Nn,isTopic:Dn,isUnlimitedAVChatRoom:function(){var e;return!!(null===(e=Gt.store.get("instance"))||void 0===e?void 0:e.unlimitedAVChatRoom)},liteChatInstanceMap:yn,registerApi:Vn,registerExperimentalAPI:qn,registerInterceptor:Sn,registerPlugin:xn,registerValidateConfig:vn,requireAuth:dn,setLogLevel:Bn,statKeyFeatureUsage:$n,validateAndExecute:mn,validateParameters:hn,workflowManager:Mn});var bn=new class{constructor(){this._conversationMap=new Map}getConversationMap(){return this._conversationMap}getConversation(e){return this._conversationMap.get(e)}updateConversation(e,t){const n=this._conversationMap.get(e);n&&!_e(t)&&(Object.keys(t).forEach((e=>{n[e]=t[e]})),Gt.notificationCenter.emitInnerEvent(Vt.CONVERSATION_UPDATED))}deleteConversation(e){this._conversationMap.has(e)&&(this._conversationMap.delete(e),Gt.notificationCenter.emitInnerEvent(Vt.CONVERSATION_UPDATED))}};var wn=new class{constructor(){this._groupMap=new Map}getGroupMap(){return this._groupMap}getGroup(e){return this._groupMap.get(e)}updateGroup(e,t){const n=this._groupMap.get(e);n&&!_e(t)&&Object.keys(t).forEach((e=>{n[e]=t[e]}))}};var kn=new class{constructor(){this._messagesByConversation=new Map}updateMessage(e,t,n){var s;const{operation:i,updateUnreadCount:o=!0}=n,a=r(n,["operation","updateUnreadCount"]),c=[];for(const n of t){const t=null===(s=this._messagesByConversation.get(e))||void 0===s?void 0:s.get(n);if(!t)return!1;Object.keys(a).forEach((e=>{t[e]=a[e]})),c.push(t)}return this._emitMessageStoreOperationEvent(i,{conversationID:e,messageList:c,updateUnreadCount:o}),c}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){Gt.notificationCenter.emitInnerEvent(e,t)}};var Ln=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)}},Pn=Object.freeze({__proto__:null,conversationStore:bn,groupStore:wn,messageStore:kn,userStore:Ln});const Un={on:Gt.notificationCenter.subscribeOuterEvent.bind(Gt.notificationCenter),off:Gt.notificationCenter.unSubscribeOuterEvent.bind(Gt.notificationCenter),destroy:jn,callExperimentalAPI:function(e,t){if(Gn[e])return Gn[e](t);return Promise.reject(new Error(`API ${e} is not found`))},use:In.installExternalPlugin.bind(In),registerPlugin:xn,setLogLevel:Bn},Gn={},Fn={};function xn(e){console.log("registerPlugin",e)}function $n(e){console.log("statTUIKeyFeatures",e)}function Bn(e){console.log("setLogLevel",e),Gt&&"function"==typeof Gt.setLogLevel&&(null==Gt||Gt.setLogLevel(e))}function Vn(e){const{apiName:t,context:n,methodName:s=t,matcher:i}=e;Fn[t]||(Fn[t]=[]),Fn[t].push({context:n,methodName:s,matcher:i}),Un[t]&&1!==Fn[t].length||(Un[t]=(...e)=>{mn(s,e);const n=Fn[t];for(const t of n)if(!t.matcher||t.matcher(e))return t.context[t.methodName].bind(t.context)(...e)})}function qn(e,t,n){const s=n||e;Gn[e]=t[s].bind(t)}function jn(){return a(this,void 0,void 0,(function*(){var e,t;try{(null===(e=Gt.store.get("login"))||void 0===e?void 0:e.isLogin)&&(yield Un.logout()),Gt.notificationCenter.emitInnerEvent(Vt.DESTROY)}catch(e){console.debug("destroy error: ",e)}finally{Gt.notificationCenter.emitOuterEvent($t.SDK_DESTROY,{SDKAppID:null===(t=Gt.store.get("instance"))||void 0===t?void 0:t.sdkAppId}),yn.clear(),In.clear(),Mn.destroy(),Gt.destroy()}}))}function Wn(){return Un}function Yn(){return Object.assign(Object.assign({InnerEvent:Vt,InnerEventSubType:Gt.notificationCenter.InnerEventSubType,OuterEvent:$t,OuterConstant:tn,SignalingEvent:qt,helper:Object.assign(Object.assign(Object.assign({},Gt.utils),Gt.common),{registerApi:Vn,registerExperimentalAPI:qn,registerInterceptor:Sn,registerValidateConfig:vn,checkBusinessCapabilityBits:Cn,registerWorkflowStep:Mn.registerWorkflowStep.bind(Mn),ChatError:ln}),apiMap:Un},Gt),{constants:Object.assign(Object.assign({},an),Gt.constants),common:Object.assign(Object.assign({},Rn),Gt.common),utils:Gt.utils,appStore:Pn})}Gn.statTUIKeyFeatures=$n;var Kn,Hn,zn;!function(e){e[e.USER_INITIATED=0]="USER_INITIATED",e[e.KICKED_OUT=1]="KICKED_OUT"}(Kn||(Kn={})),function(e){e[e.multipleAccount=1]="multipleAccount",e[e.multipleDevice=2]="multipleDevice",e[e.restApi=3]="restApi"}(Hn||(Hn={})),function(e){e[e.multipleDevice=3002]="multipleDevice",e[e.multipleAccount=3003]="multipleAccount",e[e.usersigExpired=70001]="usersigExpired",e[e.restApi=20002]="restApi"}(zn||(zn={}));const Jn={[Hn.multipleAccount]:"multipleAccount",[Hn.multipleDevice]:"multipleDevice",[Hn.restApi]:"REST_API_Kick",[zn.multipleAccount]:"multipleAccount",[zn.multipleDevice]:"multipleDevice",[zn.restApi]:"REST_API_Kick",[zn.usersigExpired]:"userSigExpired"},Zn="login_online_presence_task",{ERROR:Xn,DESTROY:Qn,FORCE_OFFLINE:es}=Vt,{KICKED_OUT_MULT_ACCOUNT:ts,KICKED_OUT_MULT_DEVICE:ns,KICKED_OUT_REST_API:ss,ACCOUNT_A2KEY_EXPIRED:is,MSG_A2KEY_EXPIRED:os}=nn;class rs{init(){const{notificationCenter:e}=Gt;e.subscribeInnerEvent(es,this._handleForceOfflineFromServerPush,this),e.subscribeInnerEvent(Xn,os,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(Xn,is,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(Xn,ts,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(Xn,ns,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(Xn,ss,this._handleForceOfflineFromResponse,this),e.subscribeInnerEvent(Qn,this._dispose,this)}_handleForceOfflineFromServerPush(e){const{EventArray:t=[]}=(null==e?void 0:e.body)||{};this._extractKickedOutMessages(t).forEach((e=>{const{KickoutMsgNotify:{KickType:t,NewInstInfo:n}}=e;this._processKickedOutReasonInfo({kickedOutReasonCode:t,newInstanceInfo:n})}))}_extractKickedOutMessages(e){return e.reduce(((e,t)=>[...e,...t.C2cNotifyMsgArray||[]]),[]).filter((e=>{var t;return this._isKickedOut(null===(t=null==e?void 0:e.KickoutMsgNotify)||void 0===t?void 0:t.KickType)}))}_handleForceOfflineFromResponse(e){const{errorCode:t}=e;this._processKickedOutReasonInfo({kickedOutReasonCode:t})}_processKickedOutReasonInfo(e){return a(this,void 0,void 0,(function*(){const{kickedOutReasonCode:t}=e;try{yield Gt.login.loginAction.logout(Kn.KICKED_OUT)}catch(e){console.debug(e)}finally{this._logKickedOutEvent(e),Gt.notificationCenter.emitOuterEvent($t.KICKED_OUT,{data:{type:Jn[t]},name:$t.KICKED_OUT}),[Hn.restApi,is,os].includes(t)&&Gt.channel.reconnect()}}))}_logKickedOutEvent(e){const{kickedOutReasonCode:t,newInstanceInfo:n={}}=e,s=Gt.ssoLog.createSSOLogData({method:"kickedOut"}),i=`type:${Jn[t]} newInstanceInfo: ${JSON.stringify(n)}`;s.setLogInfo({message:i}).end(!0),console.warn(`loginModule.${i}`)}_isKickedOut(e){return[Hn.multipleAccount,Hn.multipleDevice,Hn.restApi].includes(e)}_dispose(){const{notificationCenter:e}=Gt;e.unSubscribeInnerEvent(es,this._handleForceOfflineFromServerPush,this),e.unSubscribeInnerEvent(Xn,is,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(Xn,os,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(Xn,ts,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(Xn,ns,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(Xn,ss,this._handleForceOfflineFromResponse,this),e.unSubscribeInnerEvent(Qn,this._dispose,this)}}function as(){return a(this,void 0,void 0,(function*(){const e="im_open_status.wslogin",t=Gt.common.generateProtocolData({servcmd:e,data:{state:"Online",isWebUniapp:0,InstType:0,customInfo:""}}),n=`${t.head.seq}${e}`;try{const e=yield Gt.channel.sendPacket(t,{timeout:9e4,requestId:n});if(e){const{HelloInterval:t,InstId:n,TinyId:s,TimeStamp:i,CustomStatus:o,PurchaseBits:r,A2Key:a,RichMsgAuthKey:c,ErrorCode:l,ErrorInfo:d,ActionStatus:u}=e;return{helloInterval:t,instanceID:n,tinyID:s,timeStamp:i,customStatus:o,purchaseBits:r,a2Key:a,authKey:c,errorCode:l,errorInfo:d,actionStatus:u}}}catch(e){throw console.warn(e),e}}))}class cs{constructor(){this._latestLoginAt=0,this._latestSendOnlinePresenceRequestTime=0,this._helloInterval=120}init(){const{notificationCenter:e,store:t}=Gt;t.set("login",{isReady:!1}),Vn({apiName:"login",context:this}),Vn({apiName:"logout",context:this}),Vn({apiName:"getLoginUser",context:this}),Vn({apiName:"isReady",context:this}),e.subscribeInnerEvent(Vt.RECONNECTED,this._reLogin,this),Gt.notificationCenter.subscribeInnerEvent(Vt.DESTROY,this._dispose,this)}login(e){return a(this,void 0,void 0,(function*(){const t=Gt.ssoLog.createSSOLogData({method:"login",eventType:4});try{if(this._isLoginIn())return this._createRepeatLoginResponse();if(this._isLoginFrequencyExceeded())throw new ln({functionName:"login",code:nn.REPEAT_LOGIN});const t=yield this._performLogin(e);return this._validateAfterLogin(t),this._handleLoginSuccess(t),yield this._ensureAsyncComplete(),this._updateAndEmitSDKReady(),{code:0,data:t}}catch(e){const{errorCode:n}=e,s=new ln({functionName:"login",code:n});throw t.setError(s).end(!0),s}finally{this._latestLoginAt=0}}))}_reLogin(){return a(this,void 0,void 0,(function*(){var e;try{if(!this._isLoginIn())return;const t=Gt.ssoLog.createSSOLogData({method:"reLogin"}),n=yield as();if(n){const{instanceID:s,customStatus:i}=n;Gt.store.set("login",{statusInstanceId:s}),Mn.executeWorkflow(sn.SYNC_SERVER_INFO_AFTER_RE_ONLINE,{customStatus:i,statusType:zt.USER_STATUS_ONLINE});const o=`socketId:${null===(e=Gt.channel.getSocketAdapter())||void 0===e?void 0:e.getId()} instanceId:${s}`;t.setLogInfo({message:o}).end(!0)}}catch(e){console.warn(e)}}))}logout(){return a(this,arguments,void 0,(function*(e=Kn.USER_INITIATED){Gt.ssoLog.createSSOLogData({method:"logout"}).setLogInfo({moreMessage:`identifier:${On()}`}).end(!0);try{yield this._performLogout(e)}catch(e){const{errorCode:t}=e,n=new ln({functionName:"logout",code:t});this._handleLogoutError(n)}finally{this._handleLogoutCompleted()}return{code:0,data:{}}}))}getLoginUser(){return this._isLoginIn()?On():""}isReady(){var e;return null===(e=Gt.store.get("login"))||void 0===e?void 0:e.isReady}_updateAndEmitSDKReady(){Gt.store.set("login",{isReady:!0}),setTimeout((()=>{Gt.notificationCenter.emitOuterEvent($t.SDK_READY,{name:$t.SDK_READY})}),1)}_updateAndEmitSDKNotReady(){Gt.store.set("login",{isReady:!1}),Gt.notificationCenter.emitOuterEvent($t.SDK_NOT_READY,{name:$t.SDK_NOT_READY})}_validateAfterLogin(e){var t,n;const s="login";if(!e)throw new ln({functionName:s,message:"login response is empty"});const{tinyID:i,a2Key:o}=e||{},r=Gt.ssoLog.getSSOLogData(s);if(!i){const e=new ln({functionName:s,code:nn.NO_TINYID});throw null===(t=null==r?void 0:r.setError)||void 0===t||t.call(r,e).end(),e}if(!o){const e=new ln({functionName:s,code:nn.NO_A2KEY});throw null===(n=null==r?void 0:r.setError)||void 0===n||n.call(r,e).end(),e}}_createRepeatLoginResponse(){var e;return{code:0,data:{actionStatus:"OK",errorCode:0,errorInfo:cn({code:"RepeatLogin",replacement1:null===(e=Gt.store.get("login"))||void 0===e?void 0:e.userId}),repeatLogin:!0}}}_performLogin(e){return a(this,void 0,void 0,(function*(){const{userID:t,userSig:n}=e;return Gt.store.set("login",{userId:t,userSig:n}),this._latestLoginAt=Date.now(),as()}))}_ensureAsyncComplete(){return a(this,void 0,void 0,(function*(){yield new Promise((e=>{setTimeout((()=>e(null)),1)}))}))}_handleLoginSuccess(e){const{timeManager:t}=Gt.common,{helloInterval:n,timeStamp:s,customStatus:i,purchaseBits:o}=e,r=1e3*s;t.calculateTimeOffsetWithServer(this._latestLoginAt,r),this._helloInterval=n||120,this._updateLoginStore(e),Gt.user.userStatus.setCustomStatus(i),Mn.executeWorkflow(sn.SYNC_SERVER_INFO_AFTER_LOGIN,{purchaseBits:o}),Gt.common.taskScheduler.addTask({id:Zn,intervalMs:1e3*this._helloInterval,callback:this._sendOnlinePresenceRequest,context:this}),this._logLoginSuccess(e)}_performLogout(e){return function(e){return a(this,void 0,void 0,(function*(){const{logoutReason:t}=e,n="im_open_status.wslogout",s=Gt.common.generateProtocolData({servcmd:n,data:{wslogout_type:t,isWebUniapp:0}}),i=`${s.head.seq}${n}`;return yield Gt.channel.sendPacket(s,{requestId:i})}))}({logoutReason:e})}_handleLogoutError(e){Gt.ssoLog.getSSOLogData("logout").setError(e).end(),console.error(`logout ${e}`)}_handleLogoutCompleted(){this._updateAndEmitSDKNotReady(),this._reset(),Mn.reset(),Gt.notificationCenter.emitInnerEvent("logout")}_updateLoginStore(e){const{a2Key:t,tinyID:n,instanceID:s,authKey:i}=e;Gt.store.set("login",{a2Key:t,tinyID:n,statusInstanceId:s,authKey:i,isLoggedIn:!0})}_logLoginSuccess(e){var t;const n=Gt.ssoLog.getSSOLogData("login"),{helloInterval:s,instanceID:i,timeStamp:o,customStatus:r}=e,a=null===(t=Gt.channel.getSocketAdapter())||void 0===t?void 0:t.getId(),c=Gt.common.timeManager.getTimeOffsetWithServer(),{appId:l,href:d}=Gt.store.get("instance")||{},u=`login._logLoginSuccess socketID:${a} scene: helloInterval:${s} instanceID:${i}\n timeStamp:${o} offset:${c} customStatus:${r} href: ${d} appId: ${l}`;console.log(`login ok. ${u}`),n.updateLogCreatedAtByTimeOffset(),n.setLogInfo({moreMessage:u}).end()}_sendOnlinePresenceRequest(){return a(this,void 0,void 0,(function*(){this._latestSendOnlinePresenceRequestTime=Date.now();try{yield function(){const e="im_open_status.wshello",t=Gt.common.generateProtocolData({servcmd:e,data:{isWebUniapp:0}}),n=`${t.head.seq}${e}`;return Gt.channel.sendPacket(t,{requestId:n})}()}catch(e){console.warn("Login._sendOnlinePresenceRequest error:",e)}}))}_isLoginIn(){var e;return!0===(null===(e=Gt.store.get("login"))||void 0===e?void 0:e.isLoggedIn)}_isLoginFrequencyExceeded(){return Date.now()-this._latestLoginAt<=15e3}_reset(){console.log("Login reset"),Gt.common.taskScheduler.removeTask(Zn),this._helloInterval=120,this._latestSendOnlinePresenceRequestTime=0,this._latestLoginAt=0,Gt.store.clear("login"),Gt.store.set("login",{isReady:!1})}_dispose(){console.log("Login dispose"),this._reset();const{notificationCenter:e}=Gt;e.unSubscribeInnerEvent(Vt.RECONNECTED,this._reLogin,this),e.unSubscribeInnerEvent(Vt.DESTROY,this._dispose,this)}}const ls={login:{userID:{required:!0,rules:["string"],allowEmpty:!1},userSig:{required:!0,rules:["string"],allowEmpty:!1}}},ds={logout:!0};class us{constructor(){this.loginAction=new cs,this.kickedOutHandler=new rs,this.loginAction.init(),this.kickedOutHandler.init(),vn({auth:ds,params:ls})}}var _s,hs,gs;!function(e){e.CONV_C2C="C2C",e.CONV_GROUP="GROUP",e.CONV_TOPIC="TOPIC",e.CONV_SYSTEM="@TIM#SYSTEM"}(_s||(_s={})),function(e){e.MSG_PRIORITY_HIGH="High",e.MSG_PRIORITY_NORMAL="Normal",e.MSG_PRIORITY_LOW="Low",e.MSG_PRIORITY_LOWEST="Lowest"}(hs||(hs={})),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"}(gs||(gs={}));const fs={1:hs.MSG_PRIORITY_HIGH,2:hs.MSG_PRIORITY_NORMAL,3:hs.MSG_PRIORITY_LOW,4:hs.MSG_PRIORITY_LOWEST},Es=0,ps=1;var ms;!function(e){e.IN="in",e.OUT="out"}(ms||(ms={}));const Ss={};function vs(e){if(!e)return 0;if(void 0===Ss[e]){const t=new Date,n=`3${t.getHours()}`.slice(-2),s=`0${t.getMinutes()}`.slice(-2),i=`0${t.getSeconds()}`.slice(-2);Ss[e]=parseInt([n,s,i,"0001"].join(""),10),console.log(`autoIncrementIndex start index:${Ss[e]}`)}else Ss[e]+=1;return Ss[e]}class Is{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=hs.MSG_PRIORITY_NORMAL,this._relayFlag=!1;const{clientTime:t=Gt.common.timeManager.getServerTimeSeconds()||0,senderTinyID:n,currentUser:s,needReadReceipt:i,isSupportExtension:o,customModerationConfigurationId:r,to:a,from:c,nick:l="",avatar:d="",time:u,messageControlInfo:_,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:D="JSON",revokerInfo:N={userID:"",nick:"",avatar:""},readReceiptInfo:R={readCount:void 0,unreadCount:void 0,isPeerRead:void 0,timestamp:0},random:b,groupProfile:w,atUserList:k,flow:L,isRead:P=!1}=e;var U;this.clientTime=t,this.senderTinyID=n||h,this.needReadReceipt=!0===i||1===i,this.isSupportExtension=!0===o||1===o,this._cmConfigID=r,this.to=a,this.nick=l,this.avatar=d,this.protocol=D,this.random=void 0===b?(U=U||99999999,Math.round(Math.random()*U)):b,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||_s.CONV_C2C,this.hasRiskContent=S>1,this.version=E,this.isPlaceMessage=v,this.isRevoked=2===v||8===I,this.isSystemMessage=y,this.readReceiptInfo=R,this.revokeReason=O,this.revokerInfo=N,this._receiverList=C,this.conversationSubType=T,this.revoker=(null==N?void 0:N.revoker)||"",this.clientSequence=A||m||0,this.status=M,this.atUserList=k||[],this.flow=L,this.isRead=P,this.reInitialize(s),this._initC2CReadReceiptInfo(e),this._extractGroupInfo(w)}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,n;return this._relayFlag?{isValid:!0}:(null===(e=this._elements)||void 0===e?void 0:e.length)>0?null===(n=null===(t=this._elements[0])||void 0===t?void 0:t.validateBeforeSend)||void 0===n?void 0:n.call(t):{isValid:!1}}_updatePayloadAndType(){this._elements[0]&&(this.payload=this._elements[0].content,this.type=this._elements[0].type)}_initC2CReadReceiptInfo(e){const{readReceiptSentByPeer:t,timestamp:n=0}=e;this.conversationType===_s.CONV_C2C&&!0===this.needReadReceipt&&(this.readReceiptInfo.isPeerRead=1===t,this.readReceiptInfo.timestamp=n)}_extractGroupInfo(e){if(!e)return;const{From_AccountNick:t,From_AccountHeadurl:n,MsgFrom_AccountExtraInfo:s}=e,{NameCard:i}=s||{};"string"==typeof t&&(this.nick=t),"string"==typeof n&&(this.avatar=n),"string"==typeof i&&(this.nameCard=i)}reInitialize(e){e===this.from&&(this.isRead=!0),this._initSequence(e),this._concatConversationID(e),this.generateMessageID()}_concatConversationID(e){let t="";const n=this.conversationType;n!==_s.CONV_SYSTEM?(t=n===_s.CONV_C2C?e===this.from?this.to:this.from:this.to,this.conversationID=t?`${n}${t}`:null):this.conversationID=_s.CONV_SYSTEM}_initSequence(e){0===this.clientSequence&&e&&(this.clientSequence=vs(e)),0===this.sequence&&this.conversationType===_s.CONV_C2C&&(this.sequence=this.clientSequence)}generateMessageID(){this.from===_s.CONV_SYSTEM&&(this.senderTinyID="144115198244471703"),this.ID=`${this.senderTinyID}-${this.clientTime}-${this.random}`}setIsRead(e){this.isRead=e}}class Cs{static parseServerPushElement(e){const{MsgContent:t={}}=e,{Data:n,Ext:s,Desc:i}=t;return new Cs({data:n,description:i,extension:s})}constructor(e){this.type=gs.MSG_CUSTOM;const{data:t="",description:n="",extension:s=""}=e;this.content={data:t,description:n,extension:s}}transformToServerFormat(e){const{isMergerMessage:t=!1}=e||{},n=t?this.payload:this.content,{data:s,description:i,extension:o}=n;return{MsgType:this.type,MsgContent:{Data:s,Ext:o,Desc:i}}}validateBeforeSend(){const{isEmpty:e}=Gt.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 ys{static parseServerPushElement(e){const{MsgContent:t={Text:""}}=e,{Text:n}=t;return new ys({text:n})}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||{},n=t?this.payload:this.content,{text:s}=n;return{MsgType:this.type,MsgContent:{Text:s}}}}class Ms{constructor(){this._elementClassMap={[gs.MSG_CUSTOM]:Cs,[gs.MSG_TEXT]:ys}}init(){Vn({apiName:"createCustomMessage",context:this}),Vn({apiName:"createTextMessage",context:this})}registerElementClass(e,t){var n;void 0!==(n=t).prototype&&"constructor"in n.prototype&&(this._elementClassMap[e]=t)}getElementClass(e){return this._elementClassMap[e]}createMessage(e){const{from:t,flow:n=ms.OUT}=e,{userId:s}=Gt.store.get("login")||{};this._isSendByCurrentInstance({from:t,flow:n,currentUser:s})?this._updateWithSenderInfo(e):this._isMultiEndpointSyncMessage({from:t,flow:n,currentUser:s})&&(e.flow=ms.OUT);const i=Object.assign(Object.assign({},e),{currentUser:s});return new Is(i)}createCustomMessage(e){const t=On(),n=this.createMessage(Object.assign(Object.assign({},e),{from:t})),s=this._elementClassMap[gs.MSG_CUSTOM];if(!n)return null;if(s){const t=new s(e.payload);n.setElement(t)}return n}createTextMessage(e){var t;if(!e)return null;const n="string"==typeof e.payload?e.payload:(null===(t=null==e?void 0:e.payload)||void 0===t?void 0:t.text)||"",s=new ys({text:n}),i=On(),o=Gt.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{from:i}));return o.setElement(s),o}_updateWithSenderInfo(e){const{nick:t,avatar:n}=e,{userId:s,tinyID:i}=Gt.store.get("login")||{},o=Ln.getUserProfile(s);return e.nick=t||(null==o?void 0:o.nick)||"",e.avatar=n||(null==o?void 0:o.avatar)||"",e.tinyID=e.tinyID||i||"",e.from=s,e.status=Yt.UNSENT,e.flow=ms.OUT,e}_isMultiEndpointSyncMessage(e){const{from:t,flow:n,currentUser:s}=e;return t===s&&n===ms.IN}_isSendByCurrentInstance(e){const{from:t,flow:n,currentUser:s}=e;return t===s&&n===ms.OUT}}function Os(e){const t=e.lastIndexOf(".");return-1===t?e:e.slice(0,t)}function Ts(e){const{androidInfo:t={},androidOPPOChannelID:n=""}=e,s=t.OPPOChannelID||n;return Object.assign(Object.assign({},t),{Sound:Os(t.sound||""),OPPOChannelID:s,GoogleChannelID:t.FCMChannelID||""})}function As(e){const{apnsInfo:t={},ignoreIOSBadge:n=!1,disableVoipPush:s}=e,i=!0===t.ignoreIOSBadge||!0===n?1:0;let o;return void 0!==s&&(o=!1===s?1:0),void 0!==t.disableVoipPush&&(o=!1===t.disableVoipPush?1:0),Object.assign(Object.assign({},t),{badgeMode:i,isVoipPush:o})}function Ds(e){return Gt.utils.isPlainObject(e)?{PushFlag:!0===e.disablePush?1:0,Title:e.title||"",Desc:e.description||"",Ext:e.extension||"",ApnsInfo:As(e),AndroidInfo:Ts(e)}:null}function Ns(e){const{From_AccountHeadurl:t,From_AccountNick:n,IsNeedReadReceipt:s,IsPeerRead:i,IsSyncMsg:o,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===o){const e=C;C=I,I=e}if(S){const{Reason:e,Revoker_Account:t,Revoker_FromUin:n}=S;v={reason:e,revoker:t,revokerFromUin:n,userID:t}}return{from:I,avatar:t,nick:n,needReadReceipt:1===s,isSyncMessage:o,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:i,elements:ws(r)}}function Rs(e){const{From_Account:t,MsgBody:n,MsgClientTime:s,MsgRandom:i,MsgSeq:o,MsgTimeStamp:r,To_Account:a,MsgVersion:c,CloudCustomData:l}=e;return{from:t,clientTime:s,random:i,sequence:o,time:r,to:a,elements:ws(n),messageVersion:c,cloudCustomData:l}}function bs(e){const{ClientSeq:t,From_Account:n,GroupInfo:s,MsgBody:i,MsgClientTime:o,MsgRandom:r,MsgSeq:a,MsgTimeStamp:c,SendMsgControl:l,SupportMessageExtension:d,TinyId:u,ToGroupId:_,CloudCustomData:h,MsgVersion:g,MsgCheckResult:f,NeedReadReceipt:E,IsPlaceMsg:p,RevokerInfo:m,GroupAtInfo:S}=e;let v,I=hs.MSG_PRIORITY_NORMAL;if(Object.keys(fs).includes(String(e.MsgPriority))&&(I=fs[e.MsgPriority]),m){const{Reason:e,Revoker_Account:t,Revoker_FromUin:n}=m;v={reason:e,revoker:t,revokerFromUin:n,userID:t}}const C=function(e){const t=[];Array.isArray(e)&&e.forEach((e=>{e.GroupAtAllFlag===Es?t.push(e.GroupAt_Account):e.GroupAtAllFlag===ps&&t.push(tn.MSG_AT_ALL)}));return t}(S);return{clientSequence:t,from:n,groupProfile:s,clientTime:o,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:ws(i)}}function ws(e){if(!e)return null;if(Array.isArray(e))return e.map((e=>{const t=Gt.message.messageFactory.getElementClass(e.MsgType);return null==t?void 0:t.parseServerPushElement(e)}));const t=Gt.message.messageFactory.getElementClass(e.MsgType);return null==t?void 0:t.parseServerPushElement(e)}function ks(e){const{From_Account:t,MsgBody:n,MsgClientTime:s,MsgRandom:i,MsgSeq:o,MsgTimeStamp:r,GroupId:a,TopicId:c,MsgVersion:l,CloudCustomData:d}=e;return{from:t,clientTime:s,random:i,sequence:o,time:r,groupID:a,topicID:c,elements:ws(n),messageVersion:l,cloudCustomData:d}}function Ls({conversationUpdateFields:e,message:t}){const{conversationID:n,conversationType:s,conversationSubType:i,flow:o,_isExcludedFromUnreadCount:r,_isExcludedFromLastMessage:a}=t,c=a?"":t,l=!r&&o===ms.IN;e.has(n)?(e.get(n).lastMessage=c,l&&e.get(n).unreadCount++):e.set(n,{conversationID:n,type:s,subType:i,unreadCount:l?1:0,lastMessage:c})}var Ps=Object.freeze({__proto__:null,autoIncrementIndex:vs,parseServerGroupMessage:bs,parseServerPushC2CModifyMessage:Rs,parseServerPushGroupModifyMessage:ks,parseServerPushMessage:Ns,parseServerPushMessageElement:ws,updateConversationFields:Ls});const{isPlainObject:Us}=Gt.utils;function Gs(e,t={}){const{onlineUserOnly:n,messageControlInfo:s}=t;let{offlinePushInfo:i}=t;e.conversationType===_s.CONV_C2C&&!0===n&&(i?i.disablePush=!0:i={disablePush:!0});let o="";"string"==typeof e.cloudCustomData&&e.cloudCustomData.length>0&&(o=e.cloudCustomData);const r=[];if(s&&Us(s)){const{excludedFromUnreadCount:e,excludedFromLastMessage:t,excludedFromContentModeration:n}=s;!0===e&&r.push("NoUnread"),!0===t&&r.push("NoLastMsg"),!0===n&&r.push("NoMsgCheck")}return{onlineUserOnly:n,cloudCustomData:o,messageControlInfo:r,offlinePushInfo:i}}function Fs(e){const{webhookInfo:{disableCloudMessagePreHook:t=!1,disableCloudMessagePostHook:n=!1}={}}=e||{};if(!t&&!n)return;const s=[];return t&&s.push("ForbidBeforeSendMsgCallback"),n&&s.push("ForbidAfterSendMsgCallback"),s}function xs(e,t){return a(this,void 0,void 0,(function*(){const n=e.conversationType===_s.CONV_GROUP?function(e,t){var n;const s=Gs(e,t),{onlineUserOnly:i,cloudCustomData:o,messageControlInfo:r,offlinePushInfo:a}=s,c=JSON.parse(JSON.stringify(e.transformElementsToServerFormat()));return{servcmd:"group_open_http_svc.send_group_msg",data:{From_Account:null===(n=Gt.store.get("login"))||void 0===n?void 0:n.userId,GroupId:e.to,MsgBody:c,CloudCustomData:o,Random:e.random,MsgPriority:e.priority,ClientSeq:e.clientSequence,GroupAtInfo:e._groupAtInfoList,OnlineOnlyFlag:i?1:0,MsgClientTime:e.clientTime,OfflinePushInfo:Ds(a),SendMsgControl:i?void 0:r,NeedReadReceipt:!0===e.needReadReceipt?1:0,receiverList:null,SupportMessageExtension:!0===e.isSupportExtension?1:0,IsRelayMsg:!0===e._relayFlag?1:0,CustomModerationConfigID:e._cmConfigID,ForbidCallbackControl:Fs(t)}}}(e,t):function(e,t){var n;const s=Gs(e,t),{onlineUserOnly:i,cloudCustomData:o,messageControlInfo:r,offlinePushInfo:a}=s,c=!0===i?0:void 0,l=JSON.parse(JSON.stringify(e.transformElementsToServerFormat()));return{servcmd:"openim.sendmsg",data:{From_Account:null===(n=Gt.store.get("login"))||void 0===n?void 0:n.userId,To_Account:e.to,MsgBody:l,CloudCustomData:o,MsgSeq:e.sequence,MsgRandom:e.random,MsgLifeTime:c,From_AccountNick:e.nick,From_AccountHeadurl:e.avatar,SendMsgControl:0!==c?r:void 0,MsgClientTime:e.clientTime,IsNeedReadReceipt:!0===e.needReadReceipt?1:0,SupportMessageExtension:!0===e.isSupportExtension?1:0,IsRelayMsg:!0===e._relayFlag?1:0,CustomModerationConfigID:e._cmConfigID,OfflinePushInfo:Ds(a),forbidCallbackControl:Fs(t)}}}(e,t),s=Gt.common.generateProtocolData(n),i=`${s.head.seq}${s.head.servcmd}`,o=yield Gt.channel.sendPacket(s,{requestId:i});return o?{time:o.MsgTime,messageDropReason:o.MsgDropReason,sequence:o.MsgSeq}:null}))}const{isPlainObject:$s}=Gt.utils,{MSG_AUDIO:Bs,MSG_FILE:Vs,MSG_IMAGE:qs,MSG_VIDEO:js,MSG_MERGER:Ws}=tn;class Ys{init(){Vn({apiName:"sendMessage",context:this,matcher:e=>![Bs,Vs,qs,js,Ws].includes(e[0].type)})}sendMessage(e,t){return a(this,void 0,void 0,(function*(){const n=Gt.ssoLog.createSSOLogData({method:"sendMessage"});if(!(e instanceof Is)){const e=new ln({code:nn.MSG_INSTANCE_REQUIRED});throw n.setError(e).end(),e}const s=e.validateBeforeSend();if(!s.isValid){const{code:e,message:t=""}=s.error||{},i=new ln({code:e,message:t});throw n.setError(i).end(),i}let i=!1;const{messageDataHandler:o}=Gt.message||{};try{const{messageControlInfo:s}=t||{};let r=null;if(o.addRandomOfSentMessage(e.random),e.conversationType===_s.CONV_C2C?(i=!0===(null==t?void 0:t.onlineUserOnly),r=yield xs(e,t)):e.conversationType===_s.CONV_GROUP&&(r=yield xs(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=o.findMessage(e.ID);t&&(console.log(`sendMessage resend ok. ID:${t.ID}`),o.deleteConversationMessage(t))}return e.status=Yt.SUCCESS,e.time=l,e.conversationType===_s.CONV_GROUP&&(e.sequence=c),i?e._onlineOnlyFlag=!0:(o.storeConversationMessage(e),this._applySentMessageControlInfo(e,s),this._emitOnlineMessageSent(e)),n.setLogInfo({message:`options: ${JSON.stringify(t)}`}).end(),{code:0,data:{message:e}}}}catch(t){e.status=Yt.FAIL,o.removeRandomOfSentMessage(e.random);const{errorCode:n,errorInfo:s=""}=t||{};this._hasRiskContent(n)&&(e.hasRiskContent=!0),i||this._isRejectedByRestApi(n)||o.storeConversationMessage(e);const r=new ln({code:n,message:s,data:{message:e}});throw this._logSendMessageError({message:e,error:r}),r}}))}_hasRiskContent(e){return 80001===e||80004===e}_isRejectedByRestApi(e){return e>=10100&&e<=10200||e>=120001&&e<=13e4}_logSendMessageError({message:e,error:t}){const n=Gt.ssoLog.createSSOLogData({method:"sendMessage"});let s=`head.seq: type:${e.type} from:${e.from} to:${e.to}`;if(Gt.utils.IN_BROWSER){if("connection"in navigator){const e=navigator.connection;s+=` downlink:${e.downlink} effectiveType:${e.effectiveType} rtt:${e.rtt}`}if("memory"in window.performance){const e=window.performance.memory;s+=` usedJSHeapSize:${e.usedJSHeapSize} totalJSHeapSize:${e.totalJSHeapSize} jsHeapSizeLimit:${e.jsHeapSizeLimit}`}}n.setLogInfo({message:s}).setError(t).end()}_emitOnlineMessageSent(e){const t=e._isExcludedFromLastMessage?"":e,{conversationID:n,conversationType:s}=e;Gt.notificationCenter.emitInnerEvent(Vt.NEW_MESSAGE,{result:{conversationUpdateFieldList:[{conversationID:n,type:s,message:e,lastMessage:t,unreadCount:0}]}})}_applySentMessageControlInfo(e,t){t&&$s(t)&&(!0===t.excludedFromLastMessage&&(e._isExcludedFromLastMessage=!0),!0===t.excludedFromUnreadCount&&(e._isExcludedFromUnreadCount=!0))}_logRateLimitInfo(e,t){const n=Gt.ssoLog.createSSOLogData({method:"messageDropReason"}),s=`from:${e.from} to:${e.to} sequence:${t} messageDropReason:${messageDropReason}`;n.setLogInfo({message:s}).end(),console.warn(`sendMessage ${s}`)}_updateNickAndAvatarOfSentMessageByMe(e){const{messageDataHandler:t}=Gt.message||{};let n=!1;const{conversationID:s}=e,i=t.getLatestMsgSentByMe(s);if(i){const{nick:o,avatar:r}=i;o===e.nick&&r===e.avatar||(n=!0),n&&t.updateNickAndAvatarOfSentMessage({conversationID:s,latestNick:e.nick,latestAvatar:e.avatar,isSentByMe:!0})}}}class Ks{constructor(e){this.value=e,this.next=null}}class Hs{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 Ks(e);this.head?(this.tail.next=t,this.tail=t):(this.head=t,this.tail=t),this.size+=1}delete(e){if(!this.head)return;if(this.head.value===e)return void(this.head=this.head.next);let t=this.head;for(;t.next;){if(t.next.value===e)return void(t.next=t.next.next);t=t.next}}has(e){if(!this.head)return!1;let t=this.head,n=!1;for(;t;)t.value===e&&(n=!0),t=t.next;return n}removeHead(){this.head&&(this.head===this.tail?(this.head=null,this.tail=null):this.head=this.head.next,this.size-=1)}peek(){var e;return null===(e=this.head)||void 0===e?void 0:e.value}length(){return this.size}isEmpty(){return 0===this.size}isFull(){return this.size===this.capacity}clear(){this.head=null,this.tail=null,this.size=0}}class zs{constructor(){this._sparseMessagesByConversation=new Map,this._latestMessageSentByPeerMap=new Map,this._latestMessageSentByMeMap=new Map,this._randomOfSentMessageList=new Hs(100),Gt.notificationCenter.subscribeInnerEvent(Vt.LOGOUT,this._reset,this),Gt.notificationCenter.subscribeInnerEvent(Vt.DESTROY,this._dispose,this)}get _messagesByConversation(){return kn.getMessages()}storeConversationMessage(e,t=!1){const{conversationID:n}=e;if(!n)return!1;if(this._messagesByConversation.has(n)||this._messagesByConversation.set(n,new Map),this._shouldSkipStoreMessage(e,t))return!1;const s=this._getUniqueIdOfMessage(e);return this._messagesByConversation.get(n).set(s,e),this._updateLatestMessageMap(e),!0}_updateLatestMessageMap(e){const{conversationID:t}=e;"out"===e.flow?this._setLatestMsgSentByMe(t,e):t.startsWith("C2C")&&this._setLatestMsgSentByPeer(t,e)}_shouldSkipStoreMessage(e,t){const n=this._getUniqueIdOfMessage(e),s=this._messagesByConversation.get(e.conversationID);if(null==s?void 0:s.has(n)){const e=null==s?void 0:s.get(n);if(!t||!0===(null==e?void 0:e.isModified))return!0}return!1}deleteConversationMessage(e){var t;const{conversationID:n=""}=e,s=this._getUniqueIdOfMessage(e);this._messagesByConversation.has(n)&&(null===(t=this._messagesByConversation.get(n))||void 0===t||t.delete(s))}modifyConversationMessage(e,t){var n;if(!this._messagesByConversation.has(e)&&!this._sparseMessagesByConversation.has(e))return{isUpdated:!1,message:null};const s=this._getUniqueIdOfMessage(t),i=this._getMessageFromLocalMessage(e,s);if(i){const{messageVersion:s,elements:o,cloudCustomData:r,checkResult:a=0}=t,c=a>1;if(console.log(`conversationToMessageMap modifyConversationMessage localVersion:${i.version} remoteVersion:${s}`),i.version<s){const t=this._getUniqueIdOfMessage(i),a=he(o);return(null===(n=this._messagesByConversation.get(e))||void 0===n?void 0:n.has(t))?kn.updateMessage(e,[t],{isModified:!0,version:s,_elements:a,payload:a[0].content,type:a[0].type,cloudCustomData:r,hasRiskContent:c,operation:Kt.modify}):(i.version=s,i._elements=a,i.payload=i._elements[0].content,i.type=i._elements[0].type,i.cloudCustomData=r,i.isModified=!0,i.hasRiskContent=c),{isUpdated:!0,message:i}}return{isUpdated:!1,message:i}}return{isUpdated:!1,message:null}}_getMessageFromLocalMessage(e,t){var n;if(this._messagesByConversation.has(e))return null===(n=this._messagesByConversation.get(e))||void 0===n?void 0:n.get(t);if(this._sparseMessagesByConversation.has(e)){const n=[...this._sparseMessagesByConversation.get(e).values()];for(let e=0;e<n.length;e++)if(this._getUniqueIdOfMessage(n[e])===t)return n[e]}return null}findMessage(e){let t=null;const n=Array.from(this._messagesByConversation.values());for(const s of n){if(t=Array.from(s.values()).find((t=>t.ID===e))||null,t)break}if(!t){const n=Array.from(this._sparseMessagesByConversation.values());for(const s of n)if(t=s.get(e)||null,t)break}return t}deleteConversationMessageList(e){this._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:n,revoker:s}){const i=this._messagesByConversation.get(e);let o=null;if(i){const r=Array.from(i.values());if(o=this._findMessageBySequenceAndRandom({messageList:r,random:n,sequence:t}),o){const t=this._getUniqueIdOfMessage(o);return kn.updateMessage(e,[t],{isRevoked:!0,revoker:s,operation:Kt.revoke}),o}}if(this._sparseMessagesByConversation.has(e)){const i=Array.from(this._sparseMessagesByConversation.get(e).values());if(o=this._findMessageBySequenceAndRandom({messageList:i,random:n,sequence:t}),o)return o.isRevoked=!0,o.revoker=s,o}}_findMessageBySequenceAndRandom({messageList:e,sequence:t,random:n}){for(let s=0;s<e.length;s+=1){const i=e[s];if(i.sequence===t&&(c(n)||i.random===n))return i}return null}prependLocalMessageList(e){const{messageList:t,conversationID:n}=e;if(0===t.length)return[];const s=[],i=[],o=this._messagesByConversation.get(n)||new Map;for(const e of t){const t=this._getUniqueIdOfMessage(e);o.has(t)||(s.push(e),i.push([t,e]))}if(i.length>0){const e=new Map([...i,...o.entries()]);this._messagesByConversation.set(n,e),this._updateLatestMessageSentByMe(n),this._updateLatestMessageSentByPeer(n)}return s}storeSparseMessageList(e){if(0===e.length)return;const{conversationID:t}=e[0],n=e.length;this._sparseMessagesByConversation.has(t)||this._sparseMessagesByConversation.set(t,new Map);const s=this._sparseMessagesByConversation.get(t);for(let t=0;t<n;t++){const n=e[t];s.has(n.ID)||s.set(n.ID,n)}}_updateLatestMessageSentByMe(e){var t;const n=Array.from((null===(t=this._messagesByConversation.get(e))||void 0===t?void 0:t.values())||[]);if(0!==n.length)for(let t=n.length-1;t>=0;t--)if("out"===n[t].flow){this._setLatestMsgSentByMe(e,n[t]);break}}_updateLatestMessageSentByPeer(e){var t;const n=Array.from((null===(t=this._messagesByConversation.get(e))||void 0===t?void 0:t.values())||[]);if(0!==n.length&&e.startsWith("C2C"))for(let t=n.length-1;t>=0;t--)if("in"===n[t].flow){this._setLatestMsgSentByPeer(e,n[t]);break}}_getUniqueIdOfMessage(e){const{from:t,to:n,random:s,sequence:i,time:o}=e;return`${t}-${n}-${s}-${i}-${o}`}_setLatestMsgSentByPeer(e,t){this._latestMessageSentByPeerMap.set(e,t)}_setLatestMsgSentByMe(e,t){this._latestMessageSentByMeMap.set(e,t)}getLatestMsgSentByPeer(e){return this._latestMessageSentByPeerMap.get(e)}getLatestMsgSentByMe(e){return this._latestMessageSentByMeMap.get(e)}addRandomOfSentMessage(e){this._randomOfSentMessageList.append(e)}removeRandomOfSentMessage(e){this._randomOfSentMessageList.delete(e)}updateNickAndAvatarOfSentMessage(e){const{conversationID:t="",latestAvatar:n,latestNick:s,isSentByMe:i=!0}=e,o=this._messagesByConversation.get(t);if(!o)return;const r=Array.from(o.values()),a=i?"out":"in";r.forEach((e=>{const{nick:t,avatar:i,flow:o}=e;o===a&&(t!==s&&(e.nick=s),i!==n&&(e.avatar=n))}))}isInMessageList(e){var t;const{conversationID:n}=e;if(!n)return!1;if(!this._messagesByConversation.has(n))return!1;const s=this._getUniqueIdOfMessage(e);return null===(t=this._messagesByConversation.get(n))||void 0===t?void 0:t.has(s)}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(),Gt.notificationCenter.unSubscribeInnerEvent(Vt.LOGOUT,this._reset,this),Gt.notificationCenter.unSubscribeInnerEvent(Vt.DESTROY,this._dispose,this)}}function Js(e,t){const n=bn.getConversation(e);if(null==n?void 0:n.lastMessage){const{lastMessage:s}=n,{lastTime:i,lastSequence:o,version:r}=s,{time:a,sequence:c,messageVersion:l,elements:d,cloudCustomData:u}=t;i===a&&o===c&&r!==l&&(s.type=d[0].type,s.payload=d[0].content,s.messageForShow=Nn(s.type,s.payload),s.cloudCustomData=u,s.version=l,bn.updateConversation(e,{lastMessage:s}))}}class Zs{init(){Vn({apiName:"modifyMessage",context:this})}modifyMessage(e){return a(this,void 0,void 0,(function*(){const t=Gt.ssoLog.createSSOLogData({method:"modifyMessage"}),{to:n,payload:s,sequence:i,conversationType:o,random:r,time:c,from:l,type:d}=e;if(!this._canModifyMessageElement(d))return void t.setLogInfo({message:`can not modify message element. message type: ${d}`}).end();const u=e.getElements();u.length>1&&(u[0].type=d,u[0].content=s);try{let s=null,d=null;if(t.setLogInfo({message:`to:${n}`}),o===_s.CONV_C2C?s=yield function(e){return a(this,void 0,void 0,(function*(){const t="openim.modify_c2c_msg",{from:n,to:s,version:i=0,sequence:o,random:r,time:a,type:c,cloudCustomData:l}=e,d=Gt.common.generateProtocolData({servcmd:t,data:{From_Account:n,To_Account:s,MsgVersion:i,MsgSeq:o,MsgRandom:r,MsgTime:a,MsgType:c,MsgBody:e.transformElementsToServerFormat(),CloudCustomData:l}}),u=`${d.head.seq}${t}`,_=yield Gt.channel.sendPacket(d,{requestId:u});if(_){const{MsgBody:e,MsgVersion:t,CloudCustomData:n}=_;return{elements:ws(e),messageVersion:t,cloudCustomData:n}}}))}(e):o===_s.CONV_GROUP&&(s=yield function(e){return a(this,void 0,void 0,(function*(){const t="openim.modify_group_msg",{to:n,version:s=0,sequence:i,cloudCustomData:o}=e;let r,a=n;Dn(n)&&(a=n.split(Qt.TOPIC)[0],r=n);const c=Gt.common.generateProtocolData({servcmd:t,data:{GroupId:a,TopicId:r,MsgVersion:s,MsgSeq:i,MsgBody:e.transformElementsToServerFormat(),CloudCustomData:o}}),l=`${c.head.seq}${t}`,d=yield Gt.channel.sendPacket(c,{requestId:l});if(d){const{MsgBody:e,MsgVersion:t,CloudCustomData:n}=d;return{elements:ws(e),messageVersion:t,cloudCustomData:n}}}))}(e)),s){t.end();let a=`${o}${n}`;return n===On()&&o===_s.CONV_C2C&&(a=`${o}${l}`),d={conversationType:o,from:l,to:n,time:c,random:r,sequence:i,elements:null==s?void 0:s.elements,cloudCustomData:null==s?void 0:s.cloudCustomData,messageVersion:null==s?void 0:s.messageVersion,conversationID:a},this._handleModifyMessageSuccess(d),{code:0,data:{message:e}}}}catch(e){const{errorCode:t}=e||{},n=new ln({functionName:"modifyMessage",code:t});throw this._logModifyMessageError(n),n}}))}_logModifyMessageError(e){Gt.ssoLog.getSSOLogData("modifyMessage").setError(e).end()}_handleModifyMessageSuccess(e){const{conversationID:t}=e,{isUpdated:n,message:s}=Gt.message.messageDataHandler.modifyConversationMessage(t,e);!0===n&&Gt.notificationCenter.emitOuterEvent($t.MESSAGE_MODIFIED,{name:$t.MESSAGE_MODIFIED,data:[s]}),Gt.notificationCenter.emitInnerEvent(Vt.MESSAGE_MODIFIED,{conversationID:t,message:s}),Js(t,e)}_canModifyMessageElement(e){return[gs.MSG_TEXT,gs.MSG_CUSTOM,gs.MSG_LOCATION,gs.MSG_FACE].includes(e)}}class Xs{init(){const{notificationCenter:e}=Gt,{InnerEventSubType:t}=e;Mn.registerWorkflowStep(sn.RECEIVE_C2C_NEW_MESSAGE,on.HANDLE_C2C_NEW_MESSAGE,this._handleC2CMessagePush,this),Mn.registerWorkflowStep(sn.RECEIVE_C2C_NEW_MESSAGE,on.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterReceiveNewMessage,this),Mn.registerWorkflowStep(sn.SYNC_SERVER_INFO_AFTER_RE_ONLINE,on.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterSyncUnreadMessage,this),e.subscribeInnerEvent(Vt.MESSAGE_PUSH,t.C2C_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),e.subscribeInnerEvent(Vt.MESSAGE_PUSH,t.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),e.subscribeInnerEvent(Vt.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(e){Mn.executeWorkflow(sn.RECEIVE_C2C_NEW_MESSAGE,e)}_handleC2CMessagePush(e){const t=e.data||{},{messageDataHandler:n}=Gt.message||{},s=[],i=new Map;return t.C2cMsgArray.forEach((e=>{const t=this._generateC2CMessage(e);this._updateMessageProfile(t);let o=1===t.isModified;if(n.isMessageSentByCurrentInstance(t)?t.isModified=o:o=!1,t.isOnlineMessage())t._onlineOnlyFlag=!0,n.isMessageSentByCurrentInstance(t)||s.push(t);else if(!n.isInMessageList(t)){n.storeConversationMessage(t)&&Ls({conversationUpdateFields:i,message:t}),n.isMessageSentByCurrentInstance(t)&&!o||s.push(t)}})),{conversationUpdateFieldList:[...i.values()],messages:s}}_emitMessageEventsAfterReceiveNewMessage(e){var t;const{messages:n=[]}=(null===(t=e.result)||void 0===t?void 0:t[on.HANDLE_C2C_NEW_MESSAGE])||{};this._emitMessageEvents(n)}_emitMessageEventsAfterSyncUnreadMessage(e){var t;const{messages:n=[]}=(null===(t=e.result)||void 0===t?void 0:t[on.UNREAD_MESSAGE_SYNC])||{};this._emitMessageEvents(n)}_emitMessageEvents(e){const t=(null==e?void 0:e.filter((e=>!0===(null==e?void 0:e.isModified))))||[];t.length>0&&Gt.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:t});const n=null==e?void 0:e.filter((e=>!(null==e?void 0:e.isModified)));n.length>0&&Gt.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:n})}_generateC2CMessage(e){const t=_s.CONV_C2C,n=Ns(e),s=Gt.message.messageFactory.createMessage(Object.assign(Object.assign({},n),{conversationType:t,flow:ms.IN})),{elements:i}=n;return s.setElement(i),s}_updateMessageProfile(e){var t;const{messageDataHandler:n}=Gt.message||{},s=null===(t=Gt.store.get("login"))||void 0===t?void 0:t.userId,{from:i,nick:o,avatar:r,conversationID:a=""}=e;if(i!==s){const t=n.getLatestMsgSentByPeer(a);if(t){const{nick:s,avatar:i}=t;c(o)||c(r)?(e.nick=l(s)?s:e.nick,e.avatar=l(i)?i:e.avatar):o===s&&r===i||(n.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:o,latestAvatar:r,isSentByMe:!1}),this._updateConversationUserProfile({conversationID:a,nick:o,avatar:r}))}}else{const e=n.getLatestMsgSentByMe(a);!e||o===e.nick&&r===e.avatar||n.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:o,latestAvatar:r,isSentByMe:!0})}}_updateConversationUserProfile(e){const{conversationID:t,nick:n,avatar:s}=e,i=bn.getConversation(t),{userProfile:o={}}=i||{};o.avatar===s&&o.nick===n||bn.updateConversation(t,{userProfile:Object.assign(Object.assign({},o),{nick:n,avatar:s})})}_updateMessageListDueToModify(e){const{conversationID:t}=e,{isUpdated:n,message:s}=Gt.message.messageDataHandler.modifyConversationMessage(t,e);!0===n&&Gt.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[s]}),Gt.notificationCenter.emitInnerEvent("ModifyMessageSuccess",e),Js(t,e)}_handleC2CMessageModify(e){e.C2cMsgModNotifys.forEach((e=>{var t;const n=_s.CONV_C2C;let s=Rs(e);const{to:i,from:o}=s;let r=`${n}${i}`;i===(null===(t=Gt.store.get("login"))||void 0===t?void 0:t.userId)&&(r=`${n}${o}`),s=Object.assign({conversationType:n,conversationID:r},s),this._updateMessageListDueToModify(s)}))}_dispose(){const{notificationCenter:e}=Gt,{InnerEventSubType:t}=e;Gt.notificationCenter.unSubscribeInnerEvent(Vt.MESSAGE_PUSH,t.C2C_REALTIME_MESSAGE,this._handleC2CMessagePush,this),Gt.notificationCenter.unSubscribeInnerEvent(Vt.MESSAGE_PUSH,t.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),Gt.notificationCenter.unSubscribeInnerEvent(Vt.DESTROY,this._dispose,this)}}class Qs{init(){const{notificationCenter:e}=Gt,{InnerEventSubType:t}=e;Mn.registerWorkflowStep(sn.RECEIVE_GROUP_NEW_MESSAGE,on.HANDLE_GROUP_NEW_MESSAGE,this._handleGroupMessagePush,this),Mn.registerWorkflowStep(sn.RECEIVE_GROUP_NEW_MESSAGE,on.EMIT_GROUP_MESSAGE_EVENT,this._emitMessageEvents,this),e.subscribeInnerEvent(Vt.MESSAGE_PUSH,t.GROUP_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),e.subscribeInnerEvent(Vt.MESSAGE_PUSH,t.GROUP_MESSAGE_MODIFIED,this._handleGroupMessageModify,this),e.subscribeInnerEvent(Vt.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(e){Mn.executeWorkflow(sn.RECEIVE_GROUP_NEW_MESSAGE,e)}_handleGroupMessagePush(e){const t=e.data||{},{messageDataHandler:n}=Gt.message,s=[],i=new Map,o=null==t?void 0:t.GroupMsgArray;return null==o||o.forEach((e=>{const t=this._generateGroupMessage(e);this.updateMessageProfile(t);let o=1===t.isModified;if(n.isMessageSentByCurrentInstance(t)?t.isModified=o:o=!1,t.isOnlineMessage())t._onlineOnlyFlag=!0,n.isMessageSentByCurrentInstance(t)||s.push(t);else if(!n.isInMessageList(t)){n.storeConversationMessage(t)&&(s.push(t),Ls({conversationUpdateFields:i,message:t}))}})),{conversationUpdateFieldList:[...i.values()],messages:s}}_emitMessageEvents(e){var t;const{messages:n}=(null===(t=e.result)||void 0===t?void 0:t[on.HANDLE_GROUP_NEW_MESSAGE])||{},s=(null==n?void 0:n.filter((e=>!0===(null==e?void 0:e.isModified))))||[];s.length>0&&Gt.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:s});const i=(null==n?void 0:n.filter((e=>!(null==e?void 0:e.isModified))))||[];i.length>0&&Gt.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:i})}_generateGroupMessage(e){const t=_s.CONV_GROUP,n=bs(e),s=Gt.message.messageFactory.createMessage(Object.assign(Object.assign({},n),{conversationType:t,flow:ms.IN})),{elements:i}=n;return s.setElement(i),s}updateMessageProfile(e){var t;const{messageDataHandler:n}=Gt.message||{},s=null===(t=Gt.store.get("login"))||void 0===t?void 0:t.userId,{from:i,nick:o,avatar:r,conversationID:a=""}=e;if(i===s){const e=n.getLatestMsgSentByMe(a);!e||o===e.nick&&r===e.avatar||n.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:o,latestAvatar:r,isSentByMe:!0})}}_updateMessageListDueToModify(e){const{conversationID:t}=e,{isUpdated:n,message:s}=Gt.message.messageDataHandler.modifyConversationMessage(t,e);!0===n&&Gt.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[s]}),Js(t,e)}_handleGroupMessageModify(e){e.GroupMsgModNotifys.forEach((e=>{const t=_s.CONV_GROUP;let n=ks(e);const{topicID:s,groupID:i}=n,o=s||i,r=`${t}${o}`;n=Object.assign({conversationType:t,conversationID:r,to:o},n),this._updateMessageListDueToModify(n)}))}_dispose(){const{notificationCenter:e}=Gt,{InnerEventSubType:{GROUP_REALTIME_MESSAGE:t,GROUP_MESSAGE_MODIFIED:n}}=e;e.unSubscribeInnerEvent(Vt.MESSAGE_PUSH,t,this._handleGroupMessagePush,this),e.unSubscribeInnerEvent(Vt.MESSAGE_PUSH,n,this._handleGroupMessageModify,this),e.unSubscribeInnerEvent(Vt.DESTROY,this._dispose,this)}}class ei{constructor(){this.c2cMessageReceiver=new Xs,this.groupMessageReceiver=new Qs}init(){this.c2cMessageReceiver.init(),this.groupMessageReceiver.init()}}const ti={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 ni={createCustomMessage:!0,sendMessage:!0,modifyMessage:!0};class si{constructor(){this.messageHelper=Ps,this.messageFactory=new Ms,this.messageSender=new Ys,this.messageAction=new Zs,this.messageReceiver=new ei,this.messageDataHandler=new zs,this.messageSender.init(),this.messageFactory.init(),this.messageAction.init(),this.messageReceiver.init(),vn({auth:ni,params:ti})}}const ii="User",oi="Tag_Profile_IM_",ri=100,ai={NICK:`${oi}Nick`,GENDER:`${oi}Gender`,BIRTHDAY:`${oi}BirthDay`,LOCATION:`${oi}Location`,SELFSIGNATURE:`${oi}SelfSignature`,ALLOWTYPE:`${oi}AllowType`,LANGUAGE:`${oi}Language`,AVATAR:`${oi}Image`,MESSAGESETTINGS:`${oi}MsgSettings`,ADMINFORBIDTYPE:`${oi}AdminForbidType`,LEVEL:`${oi}Level`,ROLE:`${oi}Role`},ci="USER_STATUS",li=1,di={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:[]},ui=new Map([[ai.NICK,"nick"],[ai.GENDER,"gender"],[ai.BIRTHDAY,"birthday"],[ai.LOCATION,"location"],[ai.SELFSIGNATURE,"selfSignature"],[ai.ALLOWTYPE,"allowType"],[ai.LANGUAGE,"language"],[ai.AVATAR,"avatar"],[ai.MESSAGESETTINGS,"messageSettings"],[ai.ADMINFORBIDTYPE,"adminForbidType"],[ai.LEVEL,"level"],[ai.ROLE,"role"]]);var _i=new class{createProfile(e,t){const n={userID:e,profileCustomField:[]};return t.forEach((e=>{const{tag:t,value:s}=e;t&&t.indexOf("Tag_Profile_Custom")>-1?n.profileCustomField.push({key:t,value:s}):ui.has(t)&&(n[ui.get(t)]=s)})),Object.assign(Object.assign({},di),n)}parseProfileItem(e=[]){const t=[];return e.forEach((e=>{t.push({tag:e.Tag,value:e.Value})})),t}parseProfileList(e=[]){const t=[];return e.forEach((e=>{t.push({tag:e.Tag,value:e.ValueBytes})})),t}convertParamsToProfile(e){const t=[];return Object.keys(e).forEach((n=>{t.push({tag:ai[n.toUpperCase()],value:e[n]})})),t}normalizeProfileFields(e){const t={};return e.forEach((e=>{const{tag:n,value:s}=e;if(ui.has(n)){const e=ui.get(n);t[e]=s}})),t}};const{generateProtocolData:hi}=Gt.common;function gi(e){return a(this,void 0,void 0,(function*(){const t="profile.portrait_get_all",n={From_Account:On(),UserItem:[]};e.forEach((e=>{n.UserItem.push({CustomSequence:0,StandardSequence:0,To_Account:e})}));const s=hi({servcmd:t,data:n}),i=`${s.head.seq}${t}`,o=yield Gt.channel.sendPacket(s,{requestId:i});if(o)return function(e){const{ActionStatus:t,ErrorCode:n,ErrorDisplay:s,ErrorInfo:i,UserProfileItem:o}=e,r=[];return o.map((e=>{const{To_Account:t,CustomSequence:n,ResultCode:s,ResultInfo:i,StandardSequence:o,ProfileItem:a}=e,c=_i.parseProfileItem(a);r.push({userId:t,customSequence:n,resultCode:s,resultInfo:i,standardSequence:o,profileItem:c})})),{actionStatus:t,errorCode:n,errorDisplay:s,errorInfo:i,userProfile:r}}(o)}))}function fi(e){return Ln.getFriendMap().has(e)}const{isEmpty:Ei}=Gt.utils;class pi{init(){Vn({apiName:"getMyProfile",context:this}),Vn({apiName:"getUserProfile",context:this}),Vn({apiName:"updateMyProfile",context:this}),this.createProfile=_i.createProfile.bind(_i);const{notificationCenter:e}=Gt;Mn.registerWorkflowStep(sn.SYNC_SERVER_INFO_AFTER_LOGIN,on.USER_PROFILE_SYNC,this.getMyProfileCacheThenServer,this),e.subscribeInnerEvent(Vt.MESSAGE_PUSH,e.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),e.subscribeInnerEvent(Vt.LOGOUT,this._reset,this),e.subscribeInnerEvent(Vt.DESTROY,this._dispose,this)}getMyProfile(){return a(this,void 0,void 0,(function*(){const e=Gt.ssoLog.createSSOLogData({method:"getMyProfile"});try{const t=On(),n=yield gi([t]);if(n){const e=this._handleProfileFormResponse(n)[0];return Ln.getUserProfileMap().set(t,e),{code:0,data:e}}e.end()}catch(t){const{errorCode:n,errorInfo:s}=t,i=new ln({functionName:"getMyProfile",code:n,message:s});throw e.setError(i).end(),t}}))}getUserProfile(e){return a(this,void 0,void 0,(function*(){const t=Gt.ssoLog.createSSOLogData({method:"getUserProfile"});try{let{userIDList:n}=e;n.length>ri&&(n=n.slice(0,ri));const{userIdListToRequest:s,userIdListToCache:i}=this._filterRequestAndCacheUsers(n),o=[];i.forEach((e=>{const t=Ln.getUserProfile(e);o.push(t)}));const r=`userIDList.length:${n.length}`;if(0===s.length)return t.setLogInfo({message:r}).end(),{code:0,data:o};const a=yield gi(s);if(a){const e=this._handleProfileFormResponse(a);e.forEach((e=>{fi(e.userID)&&Ln.getUserProfileMap().set(e.userID,e)}));const n=e.concat(o);return t.setLogInfo({message:r}).end(),{code:0,data:n}}}catch(e){const{errorCode:n}=e,s=new ln({functionName:"getUserProfile",code:n});throw t.setError(s).end(),s}}))}getMyProfileCacheThenServer(){return a(this,void 0,void 0,(function*(){const e=On(),t=Ln.getUserProfileMap().has(e);return t?{code:0,data:t}:this.getMyProfile()}))}updateMyProfile(e){return a(this,void 0,void 0,(function*(){const t=Gt.ssoLog.createSSOLogData({method:"updateMyProfile"}),n=On(),s={};for(const t in e)void 0!==e[t]&&(s[t]=e[t]);const i=_i.convertParamsToProfile(s);try{const e={From_Account:n,ProfileItem:i};t.setLogInfo({message:JSON.stringify(i)}),yield function(e){return a(this,void 0,void 0,(function*(){const t="profile.portrait_set",n=hi({servcmd:t,data:e}),s=`${n.head.seq}${t}`,i=yield Gt.channel.sendPacket(n,{requestId:s});if(i){const{ActionStatus:e,ErrorCode:t,ErrorDisplay:n,ErrorInfo:s}=i;return{actionStatus:e,errorCode:t,errorDisplay:n,errorInfo:s}}}))}(e);const o=Ln.getUserProfile(n);let r;r=o?Object.assign(Object.assign({},o),s):_i.createProfile(n,i);return!_n(o,r,["lastUpdatedTime","profileCustomField"])&&Gt.notificationCenter.emitOuterEvent($t.PROFILE_UPDATED,{name:$t.PROFILE_UPDATED,data:[r]}),r.lastUpdatedTime=Date.now(),Ln.getUserProfileMap().set(n,r),t.end(),{code:0,data:r}}catch(e){const{errorCode:n,errorInfo:s}=e,i=new ln({functionName:"updateMyProfile",code:n,message:s});throw t.setError(i).end(),i}}))}updateMyNickAndAvatar(e){return a(this,void 0,void 0,(function*(){const t=On(),n=Date.now(),s=Ln.getUserProfile(t);let i={};i=s?Object.assign(s,e):_i.createProfile(t,e),i.lastUpdatedTime=n,Ln.getUserProfileMap().set(t,i)}))}_onProfileDataModify(e){const t=function(e){const{Profile_Account:t,PushType:n,ProfileList:s}=e;return{userId:t,pushType:n,profileList:_i.parseProfileList(s)}}(e.ProfileDataMod[0]);if(Ei(t))return;const{isProfileUpdated:n,profile:s}=this._handleProfileModified(t);n&&(Gt.notificationCenter.emitInnerEvent(Vt.PROFILE_UPDATE,{name:Vt.PROFILE_UPDATE,data:[s]}),Gt.notificationCenter.emitOuterEvent($t.PROFILE_UPDATED,{name:$t.PROFILE_UPDATED,data:[s]}))}_dispose(){const{notificationCenter:e}=Gt;e.unSubscribeInnerEvent(Vt.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(Vt.MESSAGE_PUSH,e.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),e.unSubscribeInnerEvent(Vt.DESTROY,this._dispose,this),this._reset()}_handleProfileModified(e){const{userId:t,profileList:n}=e,s=Ln.getUserProfile(t);if(!s||!fi(t))return{isProfileUpdated:!1,profile:null};const i=_i.normalizeProfileFields(n),o=Object.keys(i).some((e=>s[e]!==i[e]));if(!o)return{isProfileUpdated:!1,profile:s};const r=Date.now(),a=Object.assign(Object.assign(Object.assign({},s),i),{lastUpdatedTime:r});return Ln.getUserProfileMap().set(t,a),bn.updateConversation(`C2C${t}`,{userProfile:a}),{isProfileUpdated:o,profile:a}}_filterRequestAndCacheUsers(e){const t=[],n=[];return e.forEach((e=>{const s=Ln.getUserProfileMap().has(e);fi(e)&&s?n.push(e):t.push(e)})),{userIdListToRequest:t,userIdListToCache:n}}_handleProfileFormResponse(e){const{userProfile:t}=e;if(!Array.isArray(t))return[];const n=t.filter((e=>"@TLS#NOT_FOUND"!==e.userId&&""!==e.userId&&!Ei(e.profileItem))),s=Date.now();return n.map((e=>{const t=_i.createProfile(e.userId,e.profileItem);return t.lastUpdatedTime=s,t}))}_reset(){Ln.getUserProfileMap().clear()}}const mi=new Map,Si=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];for(let e=0,t=Si.length;e<t;e++)mi.set(e,Si[e]);function vi(e){if(!e)return"";const t=String(e).replace(/[=]+$/,"");let n="";if(t.length%4==1)return"";for(let e,s,i=0,o=0;s=t.charAt(o++);~s&&(e=i%4?64*e+s:s,i++%4)?n+=String.fromCharCode(255&e>>(-2*i&6)):0)s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(s);try{return decodeURIComponent(escape(n))}catch(e){return console.warn(e),""}}const{isEmpty:Ii}=Gt.utils,{generateProtocolData:Ci}=Gt.common;function yi(e){return a(this,void 0,void 0,(function*(){const t="im_open_status.ws_get_user_status",n=Ci({servcmd:t,data:{To_Account:e}}),s=`${n.head.seq}${t}`,i=yield Gt.channel.sendPacket(n,{requestId:s});if(i)return function(e){const{ErrorCode:t,ErrorInfo:n,ErrorList:s=[],UserStatusList:i=[]}=e,o=i.map((e=>{const{To_Account:t,Status:n,CustomStatus:s}=e;return{userID:t,statusType:n,customStatus:vi(s)}})),r=s.map((e=>{const{To_Account:t,Invalid_Account:n,ErrorCode:s,ErrorInfo:i}=e;return{userID:Ii(n)?t:n,code:s,message:i}}));return{errorCode:t,errorInfo:n,successUserList:o,failureUserList:r}}(i)}))}class Mi{constructor(){this._customStatus=""}init(){const{notificationCenter:e}=Gt;Vn({apiName:"getUserStatus",context:this}),Vn({apiName:"setSelfStatus",context:this}),Vn({apiName:"subscribeUserStatus",context:this}),Vn({apiName:"unsubscribeUserStatus",context:this}),Mn.registerWorkflowStep(sn.SYNC_SERVER_INFO_AFTER_RE_ONLINE,on.USER_STATUS_UPDATE,this._onReOnline,this),e.subscribeInnerEvent(Vt.MESSAGE_PUSH,e.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),e.subscribeInnerEvent(Vt.LOGOUT,this._reset,this),e.subscribeInnerEvent(Vt.DESTROY,this._dispose,this)}setSelfStatus(e){return a(this,void 0,void 0,(function*(){const t=Gt.ssoLog.createSSOLogData({method:"setSelfStatus"}),n=On(),{customStatus:s}=e;try{return yield function(e){return a(this,void 0,void 0,(function*(){const t="im_open_status.ws_set_custom_status",n=Ci({servcmd:t,data:{CustomStatus:e}}),s=`${n.head.seq}${t}`,i=yield Gt.channel.sendPacket(n,{requestId:s});if(i){const{ErrorCode:e,ErrorInfo:t}=i;return{errorCode:e,errorInfo:t}}}))}(s),this._customStatus=s,t.setLogInfo({message:`customStatus: ${s}`}).end(),{code:0,data:{userID:n,statusType:li,customStatus:s}}}catch(e){const{errorCode:n,errorInfo:s}=e,i=new ln({functionName:"setSelfStatus",code:n,message:s});throw t.setError(i).end(),i}}))}getUserStatus(e){return a(this,void 0,void 0,(function*(){const t=Gt.ssoLog.createSSOLogData({method:"getUserStatus"}),{userIDList:n=[]}=e;return t.setLogInfo({moreMessage:`userIDList length: ${n.length}`}),this._isOnlyMeInArray(n)?this._getMyStatus():this._getUserStatus(n)}))}setCustomStatus(e){const t=vi(e);this._customStatus=t}subscribeUserStatus(e){return a(this,void 0,void 0,(function*(){try{console.log(`${ii} subscribeUserStatus options: `,e);const{userIDList:t=[]}=e;this._checkBusinessCapabilityBits("subscribeUserStatus");const n=this._getMaxUserCount("subscribe"),s=this._sliceUserIDList(t,n),i=yield function(e){return a(this,void 0,void 0,(function*(){const{channel:t}=Gt,n="im_open_status.ws_status_subscribe",s=Ci({servcmd:n,data:{To_Account:e}}),i=`${s.head.seq}${n}`;return yield t.sendPacket(s,{requestId:i})}))}(s);return{code:0,data:{failureUserList:this._parseResponse(i)}}}catch(e){throw console.error(`${ii} subscribeUserStatus error:`,e),e}}))}unsubscribeUserStatus(e){return a(this,void 0,void 0,(function*(){try{console.log(`${ii} unsubscribeUserStatus options: `,e),this._checkBusinessCapabilityBits("unsubscribeUserStatus");const{userIDList:t=[]}=e,n=this._getMaxUserCount("unsubscribe"),s=this._sliceUserIDList(t,n),i=yield function(e){return a(this,void 0,void 0,(function*(){const{channel:t}=Gt,n="im_open_status.ws_status_unsubscribe";let s={};s=0===e.length?{UnsubscribeAll:1}:{To_Account:e};const i=Ci({servcmd:n,data:s}),o=`${i.head.seq}${n}`;return yield t.sendPacket(i,{requestId:o})}))}(s);return{code:0,data:{failureUserList:this._parseResponse(i)}}}catch(e){throw console.error(`${ii} unsubscribeUserStatus error:`,e),e}}))}_onUserStatusUpdate(e){const{UserStatusList:t=[]}=e||{},n=t.map((e=>{const{To_Account:t,Status:n,CustomStatus:s}=e;return{userID:t,statusType:n,customStatus:vi(s)}}));this._emitUserStatusUpdatedEvent(n)}_onReOnline(e){const t=vi(e.data.customStatus);if(this._customStatus===t)return;this._customStatus=t;const n={userID:On(),statusType:li,customStatus:t};this._emitUserStatusUpdatedEvent(n)}_emitUserStatusUpdatedEvent(e){Gt.notificationCenter.emitOuterEvent($t.USER_STATUS_UPDATED,{name:$t.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:n,ErrorCode:s,ErrorInfo:i}=e;return{userID:Gt.utils.isEmpty(n)?t:n,code:s,message:i}}))}_checkBusinessCapabilityBits(e){if(!Gt.store.get("commercialConfig").get(ci))throw new ln({functionName:e,code:nn.NO_USE,replacement1:e})}_getMaxUserCount(e){const t=Gt.store.get("cloudConfig")||{},n={query:{key:"status_query_count",default:500},subscribe:{key:"status_sub_count",default:ri},unsubscribe:{key:"status_unsub_count",default:ri}},{key:s,default:i}=n[e],o=t[s]||i;return parseInt(o,10)}_getMyStatus(){const e=Gt.ssoLog.getSSOLogData("getUserStatus");e.setLogInfo({moreMessage:"getUserStatus._getMyStatus"});const t={userID:On(),statusType:li,customStatus:this._customStatus};return e.end(),{code:0,data:{successUserList:[t],failureUserList:[]}}}_getUserStatus(e){return a(this,void 0,void 0,(function*(){const t=Gt.ssoLog.getSSOLogData("getUserStatus");t.setLogInfo({moreMessage:"getUserStatus._getUserStatus"});try{this._checkBusinessCapabilityBits("getUserStatus");const n=this._getMaxUserCount("query"),s=this._sliceUserIDList(e,n),i=yield yi(s),{successUserList:o,failureUserList:r}=i||{};return t.end(),{code:0,data:{successUserList:o,failureUserList:r}}}catch(e){const{errorCode:n}=e,s=new ln({functionName:"getUserStatus",code:n});throw t.setError(s).end(),s}}))}_isOnlyMeInArray(e){const t=On();return 1===e.length&&e.indexOf(t)>-1}_dispose(){const{notificationCenter:e}=Gt;e.unSubscribeInnerEvent(Vt.MESSAGE_PUSH,e.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),e.unSubscribeInnerEvent(Vt.DESTROY,this._dispose,this),e.unSubscribeInnerEvent(Vt.LOGOUT,this._reset,this),this._reset()}_reset(){this._customStatus=""}}const Oi={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}}},Ti={getMyProfile:!0,getUserProfile:!0,updateMyProfile:!0,setSelfStatus:!0,getUserStatus:!0,subscribeUserStatus:!0,unsubscribeUserStatus:!0};class Ai{constructor(){this.userProfile=new pi,this.userStatus=new Mi,this.userProfile.init(),this.userStatus.init(),vn({auth:Ti,params:Oi})}}const Di=[{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}],Ni="im_sdk_config_mgr.fetch_config",Ri="im_sdk_config_mgr.push_configv2",bi="cloud-config",wi=2996;var ki=new class{constructor(){this._core=null,this._expirationTime=0,this._version=0,this._isFetching=!1,this._cmdFrequencyLimitMap=new Map,this._methodCallFrequencyMap=new Map}install(e){this._core=e;const{notificationCenter:t,InnerEvent:n,helper:s,constants:{WORKFLOW_NAME:i,WORKFLOW_STEP:o},channel:r}=e;t.subscribeInnerEvent(Ri,this._handlePushedConfig,this),s.registerWorkflowStep(i.SYNC_SERVER_INFO_AFTER_LOGIN,o.CLOUD_CONFIG_SYNC,this._handleLoginSuccess,this),t.subscribeInnerEvent(n.LOGOUT,this._reset,this),t.subscribeInnerEvent(n.DESTROY,this._dispose,this),s.registerExperimentalAPI("getServerConfig",this),this._updateCmdFreqLimitMap(Di),r.registerBeforeSendInterceptor(this.checkMethodCallOverLimit,this)}getServerConfig(e){var t;const n={code:0,data:""};return e?(n.data=(null===(t=this._core.store.get("cloudConfig"))||void 0===t?void 0:t[e])||"",n):n}checkMethodCallOverLimit(e){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:n}=this._cmdFrequencyLimitMap.get(e);let{startTime:s,methodCallCounter:i}=this._methodCallFrequencyMap.get(e);if(Date.now()-s>1e3*n)this._methodCallFrequencyMap.set(e,{startTime:Date.now(),methodCallCounter:1});else if(i+=1,this._methodCallFrequencyMap.set(e,{startTime:s,methodCallCounter:i}),i>t)throw new this._core.helper.ChatError({code:wi,replacement1:e})}_fetchCloudConfig(){return a(this,void 0,void 0,(function*(){try{const{sdkAppId:e}=this._core.store.get("instance")||{},t=this._core.helper.generateProtocolData({servcmd:Ni,data:{uint32_sdkappid:e,uint64_version:this._version}}),n=`${t.head.seq}${Ni}`;return yield this._core.channel.sendPacket(t,{requestId:n})}catch(e){throw console.warn("fetch cloudControl fail: ",e),e}}))}_handlePushedConfig(e){this._updateCloudConfig(e)}_handleLoginSuccess(){return a(this,void 0,void 0,(function*(){try{if(this._canFetch()){const e=yield this._fetchCloudConfig();this._updateCloudConfig(e)}this._core.helper.taskScheduler.addTask({id:bi,intervalMs:1e3,callback:this._fetchCloudConfigIfReady,context:this})}catch(e){console.warn(e)}}))}_fetchCloudConfigIfReady(){return a(this,void 0,void 0,(function*(){if(this._canFetch())try{const e=yield this._fetchCloudConfig();this._updateCloudConfig(e)}catch(e){console.warn(e)}}))}_updateCloudConfig(e){const t=this._parseCloudConfig(e);t&&(this._core.store.set("cloudConfig",t),this._parseCmdFreqLimit(),this._core.notificationCenter.emitInnerEvent(this._core.InnerEvent.CLOUD_CONFIG_UPDATE,t))}_canFetch(){const{isLoggedIn:e}=this._core.store.get("login")||{};return e&&!this._isFetching&&Date.now()>=this._expirationTime}_parseCloudConfig(e){const{int32_error_code:t,str_error_message:n,str_json_config:s,uint32_expired_time:i,uint32_sdkappid:o,uint64_version:r}=e;let a=null;if(0===t){if(this._version!==r)try{a=JSON.parse(s),this._version=r}catch(e){}this._expirationTime=Date.now()+1e3*i}else this._expirationTime=void 0===t?Date.now()+36e5:Date.now()+12e4;return a}_parseCmdFreqLimit(){var e;let t=null===(e=this.getServerConfig("cmd_frequency_limit"))||void 0===e?void 0:e.data;const{isEmpty:n}=this._core.utils;if(!n(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(bi),this._core.store.clear("cloudConfig"),this._updateCmdFreqLimitMap(Di),this._methodCallFrequencyMap.clear(),this._expirationTime=0,this._version=0,this._isFetching=!1}_dispose(){const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(Ri,this._handlePushedConfig,this),e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this),this._reset()}};class Li{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 Pi={SEARCH_GRP_SNS:new Li(0,Math.pow(2,1)).toString(),AV_HISTORY_MSG:new Li(0,Math.pow(2,2)).toString(),GRP_COMMUNITY:new Li(0,Math.pow(2,3)).toString(),MSG_TO_SPECIFIED_GRP_MBR:new Li(0,Math.pow(2,4)).toString(),AV_MBR_LIST:new Li(0,Math.pow(2,6)).toString(),USER_STATUS:new Li(0,Math.pow(2,7)).toString(),CONV_MARK:new Li(0,Math.pow(2,9)).toString(),CONV_GROUP:new Li(0,Math.pow(2,10)).toString(),AV_BAN_MBR:new Li(0,Math.pow(2,11)).toString(),MSG_EXT:new Li(0,Math.pow(2,13)).toString(),GRP_COUNTER:new Li(0,Math.pow(2,15)).toString(),PLUGIN_TRANSLATE:new Li(Math.pow(2,6)).toString(),PLUGIN_VOICE_TO_TEXT:new Li(Math.pow(2,7)).toString(),PLUGIN_CS:new Li(Math.pow(2,8)).toString(),PLUGIN_PUSH:new Li(Math.pow(2,9)).toString(),PLUGIN_BOT:new Li(Math.pow(2,10)).toString(),MSG_REACTION:new Li(Math.pow(2,16)).toString(),FOLLOW:new Li(Math.pow(2,20)).toString()},Ui="CommercialConfig",Gi="commercial-config";var Fi=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:n,constants:{WORKFLOW_NAME:s,WORKFLOW_STEP:i,InnerEvent:o}}=e;n.subscribeInnerEvent(o.COMMERCIAL_CONFIG_PUSH,this._handlePushedConfig,this),n.subscribeInnerEvent(o.LOGOUT,this._handleLogout,this),n.subscribeInnerEvent(o.DESTROY,this._dispose,this),t.registerWorkflowStep(s.SYNC_SERVER_INFO_AFTER_LOGIN,i.COMMERCIAL_CONFIG_UPDATE,this._syncCommercialConfig,this),e.helper.registerExperimentalAPI("isCommercialAbilityEnabled",this)}isCommercialAbilityEnabled(e){return a(this,void 0,void 0,(function*(){const t=parseInt(e,10).toString(2),{length:n}=t;let s,i=!0;for(let e=n-1,o=0;e>=0;e--,o++)if("1"===t.charAt(e)&&(s=o<32?new Li(0,2**o).toString():new Li(2**(o-32),0).toString(),!this._featureMap.get(s))){i=!1;break}return console.log(`${Ui}.isFeatureEnabled decimalNumber:${e} key:${s} ret:${i}`),{code:0,data:{enabled:i}}}))}_fetchAndParseCommercialConfig(){return a(this,void 0,void 0,(function*(){var e;try{this._isFetching=!0;const t=this._core.helper.generateProtocolData({servcmd:"im_sdk_config_mgr.fetch_imsdk_purchase_bitsv2",data:{uint32_sdkappid:null===(e=this._core.store.get("instance"))||void 0===e?void 0:e.sdkAppId}}),n=yield this._core.channel.sendPacket(t);(null==n?void 0:n.body)&&(this._parseCommercialConfig(n.body),this._core.store.set("commercialConfig",this._methodKeyMap))}catch(e){console.warn("fetch commercial fail: ",e)}finally{this._isFetching=!1}}))}_syncCommercialConfig(e){return a(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:Gi,intervalMs:1e3,callback:this._fetchCommercialConfigIfReady,context:this})}))}_canFetch(){var e;const t=null===(e=this._core.store.get("login"))||void 0===e?void 0:e.isLoggedIn,n=Date.now()>=this._expirationTime;return t&&!this._isFetching&&n}_handlePushedConfig(e){(null==e?void 0:e.body)&&(this._parseCommercialConfig(e.body),this._core.store.set("commercialConfig",this._methodKeyMap))}_fetchCommercialConfigIfReady(){return a(this,void 0,void 0,(function*(){this._canFetch()&&(yield this._fetchAndParseCommercialConfig())}))}_parseCommercialConfig(e){if("object"!=typeof e)return;const{int32_error_code:t,str_error_message:n,str_purchase_bits:s,uint32_expired_time:i}=e;0===t?(this._parsePurchaseBits(s),this._expirationTime=Date.now()+1e3*i):void 0===t?(console.log(`${Ui}._parseCommercialConfig failed. Invalid message format:`,e),this._expirationTime=Date.now()+36e5):(console.error(`${Ui}._parseCommercialConfig errorCode:${t} errorMessage:${n}`),this._expirationTime=Date.now()+12e4)}_isValidPurchaseBits(e){return e&&"string"==typeof e&&e.length>=1&&e.length<=64&&/[01]{1,64}/.test(e)}_parsePurchaseBits(e){if(this._isValidPurchaseBits(e)){this._featureMap.clear(),this._methodKeyMap.clear();let t=null;for(let n=e.length-1,s=0;n>=0;n--,s++)if(t=s<32?new Li(0,2**s).toString():new Li(2**(s-32),0).toString(),"1"===e[n]){this._featureMap.set(t,!0);const e=this._getKeyByValue(Pi,t);e&&this._methodKeyMap.set(e,!0)}else{this._featureMap.set(t,!1);const e=this._getKeyByValue(Pi,t);e&&this._methodKeyMap.set(e,!1)}}else console.warn(`${Ui}.parsePurchaseBits invalid purchases:${e}`)}_getKeyByValue(e,t){const n=Object.entries(e).find((([e,n])=>n===t));return n?n[0]:void 0}_handleLogout(){this._reset()}_dispose(){this._reset(),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.COMMERCIAL_CONFIG_PUSH,this._handlePushedConfig,this),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}_reset(){this._core.helper.taskScheduler.removeTask(Gi),this._core.store.set("commercialConfig",{}),this._expirationTime=0,this._isFetching=!1,this._featureMap.clear()}};var xi=new class{constructor(){this._core=null,this._serverOverloadInfoMap=new Map}install(e){this._core=e;const{notificationCenter:t,InnerEvent:n,channel:s}=this._core;t.subscribeInnerEvent(n.OVERLOAD_PUSH,this._handleOverLoadPush,this),t.subscribeInnerEvent(n.LOGOUT,this._reset,this),t.subscribeInnerEvent(n.DESTROY,this._dispose,this),s.registerBeforeSendInterceptor(this.checkServerOverload,this)}checkServerOverload(e){if(!this._serverOverloadInfoMap.has(e))return;const{overloadStartTimestamp:t,delaySeconds:n}=this._serverOverloadInfoMap.get(e);if(Date.now()-t<=1e3*n)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:n}=e;this._serverOverloadInfoMap.set(t,{overloadStartTimestamp:Date.now(),delaySeconds:n})}_reset(){this._serverOverloadInfoMap.clear()}_dispose(){this._reset();const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.OVERLOAD_PUSH,this._handleOverLoadPush,this),e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};var $i=new class{constructor(){this._core=null}install(e){return a(this,void 0,void 0,(function*(){if(this._core=e,this._canFetch()){const e=yield this._fetchErrorMessage();if(!e)return;const t=this._parseResponse(e);this._saveErrorMessage(t)}}))}_canFetch(){const e=this._core.store.getStorage("errorMessage");return!e||this._isExpired(e)}_saveErrorMessage(e){this._core.store.setStorage("errorMessage",{errorMessage:e,errorMessageSavedTime:(new Date).getTime()})}_fetchErrorMessage(){return a(this,void 0,void 0,(function*(){try{return yield this._core.helper.httpRequest({method:"GET",url:"https://web.sdk.qcloud.com/im/download/error-message/v3/0.0.6/tim-error-message.txt"})}catch(e){console.error(e)}}))}_isExpired(e){if(!e)return!0;const{errorMessageSavedTime:t}=e;return t&&(new Date).getTime()-t>=6048e5}_parseResponse(e){if("string"==typeof e){const t=e.split(";\n"),n={},s=new RegExp(/'/g);for(let e=0;e<t.length;e++){const i=t[e].indexOf(":"),o=t[e].slice(0,i);let r=t[e].slice(i+1);if(!o.startsWith("//")){if(""===r)continue;r=r.replace(s,""),n[o]=r}}return n}}};function Bi(e,t){return a(this,void 0,void 0,(function*(){const{cookie:n,syncFlag:s,syncTriggerEvent:i}=e,o="openim.getmsg",r=t.helper.generateProtocolData({servcmd:o,data:{Cookie:n,SyncFlag:s,IsOnlineSync:i,NeedAbstract:1,NeedSignaling:1,NeedCachedMsg:1}}),a=`${r.head.seq}${o}`;try{const e=yield t.channel.sendPacket(r,{requestId:a});if(!e)return null;const{C2CPairUnreadCount:n,C2CRemainingUnreadCount:s,EventArray:i}=e,{unreadMessageList:o,revokedMessageList:c}=function(e,t){const n=[],s=[];return null==e||e.forEach((e=>{var i,o,r;const a=function(e,t){const{From_Account:n,From_AccountHeadurl:s,From_AccountNick:i,IsNeedReadReceipt:o,MsgBody:r,MsgClientTime:a,MsgRandom:c,MsgSeq:l,MsgTimeStamp:d,SendMsgControl:u,SupportMessageExtension:_,To_Account:h,TinyId:g,MsgCheckResult:f,CloudCustomData:E,IsPeerRead:p,MsgFlagBits:m,MsgVersion:S,EventArray:v}=e;return{from:n,avatar:s,nick:i,needReadReceipt:1===o,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===(o=null===(i=null==e?void 0:e.EventArray)||void 0===i?void 0:i[0])||void 0===o?void 0:o.hasOwnProperty)||void 0===r?void 0:r.call(o,"C2cNotifyMsgArray"))s.push(...function(e){var t;const n=[];return null===(t=e.EventArray)||void 0===t||t.forEach((e=>{var t,s;const{C2cNotifyMsgArray:i}=e,o=null===(s=null===(t=null==i?void 0:i[0])||void 0===t?void 0:t.WithdrawC2cMsgNotify)||void 0===s?void 0:s.C2cWithdrawInfoArray;Array.isArray(o)&&n.push(...o)})),n}(e));else{const e=t.message.messageFactory.createMessage(Object.assign(Object.assign({},a),{conversationType:"C2C",flow:"in"})),{elements:s}=a;e.setElement(s),n.push(e)}})),{unreadMessageList:n,revokedMessageList:s}}(e.MsgList,t);return{syncFlag:null==e?void 0:e.SyncFlag,unreadMessageList:o,revokedMessageList:c,unreadCountList:n,overflowUnreadCountList:s,cookie:null==e?void 0:e.Cookie,groupTipList:i}}catch(e){console.warn(e)}}))}var Vi,qi;!function(e){e[e.START_SYNC=0]="START_SYNC",e[e.SYNCING=1]="SYNCING",e[e.SYNC_COMPLETE=2]="SYNC_COMPLETE"}(Vi||(Vi={})),function(e){e[e.LOGIN_SUCCESS=0]="LOGIN_SUCCESS",e[e.NEW_MESSAGE_RECEIVED=1]="NEW_MESSAGE_RECEIVED"}(qi||(qi={}));var ji=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 a(this,void 0,void 0,(function*(){const{isAfterReOnline:t=!1,isAfterNewMessageReceived:n=!1,isAfterLogin:s=!1}=e||{};let i=Vi.START_SYNC;const o=[],r=[],a=[],c=[];for(;this._canContinueSync({cookie:this._cookie,syncFlag:i});){const e=yield this._fetchUnreadDBMessage({cookie:this._cookie,syncFlag:i,syncTriggerEvent:n?qi.NEW_MESSAGE_RECEIVED:qi.LOGIN_SUCCESS});if(!e)break;const{unreadMessageList:s=[],revokedMessageList:l=[],overflowUnreadCountList:d,unreadCountList:u,groupTipList:_}=e;if(this._cookie=(null==e?void 0:e.cookie)||"",i=null==e?void 0:e.syncFlag,this._parseAndSaveUnreadMessageList(s),a.push(...l),this._updateConversationUnreadOptions({unreadCountList:u,overflowUnreadCountList:d,conversationUpdateFieldList:o}),Array.isArray(_)&&r.push(..._),t){const{messages:e}=this._handleNewMessageList(s);c.push(...e)}}return t?{conversationUpdateFieldList:o,revokedMessageList:a,unreadMessageMap:this._unreadDBMessageMap,groupTipList:r,messages:c}:{conversationUpdateFieldList:o,isInstantMessage:!s,isUnreadC2CMessage:!0,revokedMessageList:a,unreadMessageMap:this._unreadDBMessageMap,groupTipList:r}}))}_syncUnreadDBMessageAfterLogin(){return a(this,void 0,void 0,(function*(){return this._syncUnreadMessage({isAfterLogin:!0})}))}_syncUnreadDBMessageAfterNewMessageReceived(e){return a(this,void 0,void 0,(function*(){if(1===e.data.Flag)return this._syncUnreadMessage({isAfterNewMessageReceived:!0})}))}_updateConversationUnreadOptions(e){const{unreadCountList:t,overflowUnreadCountList:n,conversationUpdateFieldList:s}=e,{constants:{OuterConstant:{CONV_C2C:i,CONV_SYSTEM:o}}}=this._core;null==t||t.forEach((e=>{const{From_Account:t,UnreadCount:n}=e;if(t!==o){const e=s.find((({conversationID:e})=>e===`${i}${t}`));e?e.unreadCount=n:s.push({conversationID:`${i}${t}`,unreadCount:n,type:i})}})),null==n||n.forEach((e=>{const{From_Account:t,LastMsgTime:n}=e;if(t!==o){s.find((({conversationID:e})=>e===`${i}${t}`))||s.push({conversationID:`${i}${t}`,type:i,lastMsgTime:n})}}))}_syncUnreadDBMessageAfterReOnline(){return a(this,void 0,void 0,(function*(){return this._syncUnreadMessage({isAfterReOnline:!0})}))}_updateMessageProfile(e){var t;const{messageDataHandler:n}=this._core.message||{},s=null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userId,{from:i,nick:o,avatar:r,conversationID:a=""}=e;if(i!==s){const t=n.getLatestMsgSentByPeer(a);if(t){const{nick:s,avatar:i}=t;o&&r?o===s&&r===i||n.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:o,latestAvatar:r,isSentByMe:!1}):(e.nick=s,e.avatar=i)}}else{const e=n.getLatestMsgSentByMe(a);!e||o===e.nick&&r===e.avatar||n.updateNickAndAvatarOfSentMessage({conversationID:a,latestNick:o,latestAvatar:r,isSentByMe:!0})}}_handleNewMessageList(e){const{messageDataHandler:t}=this._core.message||{},n=new Map,s=[];return e.forEach((e=>{this._updateMessageProfile(e);let i=1===e.isModified;if(t.isMessageSentByCurrentInstance(e)?e.isModified=i:i=!1,e.isOnlineMessage())e._onlineOnlyFlag=!0,t.isMessageSentByCurrentInstance(e)||s.push(e);else if(!t.isInMessageList(e)){if(t.storeConversationMessage(e)){const{conversationID:t,conversationType:s,conversationSubType:i,flow:o,_isExcludedFromUnreadCount:r,_isExcludedFromLastMessage:a}=e,c=a?"":e;n.has(t)?(n.get(t).lastMessage=c,"in"===o&&(r||n.get(t).unreadCount++)):n.set(t,{conversationID:t,type:s,subType:i,unreadCount:r||"in"!==o?0:1,lastMessage:c})}t.isMessageSentByCurrentInstance(e)&&!i||s.push(e)}})),{messages:s,conversationOptions:n}}_fetchUnreadDBMessage(e){return a(this,void 0,void 0,(function*(){try{const t="unread-message-synchronizer._fetchUnreadDBMessage";console.log(`${t} options:`,e);const n=yield Bi(e,this._core);if(!n)return null;const{syncFlag:s,unreadMessageList:i,revokedMessageList:o,cookie:r,unreadCountList:a,overflowUnreadCountList:c,groupTipList:l}=n;return this._parseAndSaveUnreadMessageList(i),{syncFlag:s,cookie:r,unreadMessageList:i,revokedMessageList:o,unreadCountList:a,overflowUnreadCountList:c,groupTipList:l}}catch(e){console.log(e)}}))}_canContinueSync({cookie:e,syncFlag:t}){var n;return t===Vi.START_SYNC||t===Vi.SYNCING&&!(null===(n=this._core)||void 0===n?void 0:n.helper.isEmpty(e))}_parseAndSaveUnreadMessageList(e){e.forEach((e=>{const{ID:t}=e;this._unreadDBMessageMap.set(t,e)}))}_reset(){this._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 Wi=new class{init(e){var t;this._core=e,this._visibilityChangeHandler=this._handleVisibilityChange.bind(this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this),document.addEventListener("visibilitychange",this._visibilityChangeHandler),null===(t=this._core)||void 0===t||t.store.set("activityMonitor",{isActive:!0})}_handleVisibilityChange(){var e,t;const n="visible"===document.visibilityState;null===(e=this._core)||void 0===e||e.store.set("activityMonitor",{isActive:n}),null===(t=this._core)||void 0===t||t.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:n})}_reset(){var e;null===(e=this._core)||void 0===e||e.store.clear("activityMonitor")}_dispose(){document.removeEventListener("visibilitychange",this._visibilityChangeHandler);const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this),this._reset()}};var Yi=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 Ki=new class{init(e){const{IN_WX_MINI_APP:t,IN_WX_MINI_PLUGIN:n}=e.helper;n||(t?Yi.init(e):Wi.init(e))}};const Hi="none",zi="online";var Ji=new class{init(e){this._core=e,this._activateNetworkMonitoring(),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return a(this,void 0,void 0,(function*(){navigator.onLine?this._onOnline():this._onOffline(),this._onOnlineCallback=this._onOnline.bind(this),this._onOfflineCallback=this._onOffline.bind(this),window.addEventListener("online",this._onOnlineCallback),window.addEventListener("offline",this._onOfflineCallback)}))}_deactivateNetworkMonitoring(){null!==this._onOnlineCallback&&(window.removeEventListener("online",this._onOnlineCallback),this._onOnlineCallback=null),null!==this._onOfflineCallback&&(window.removeEventListener("offline",this._onOfflineCallback),this._onOfflineCallback=null)}_onNetworkStatusChange(e){var t,n;const{isConnected:s,networkType:i}=e;null===(t=this._core)||void 0===t||t.store.set("netWorkMonitor",{isNetworkOnline:s,networkType:i}),null===(n=this._core)||void 0===n||n.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:s,networkType:i})}_onOnline(){this._onNetworkStatusChange({isConnected:!0,networkType:zi})}_onOffline(){this._onNetworkStatusChange({isConnected:!1,networkType:Hi})}_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 Zi=new class{init(e){this._core=e,this._activateNetworkMonitoring(),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return a(this,void 0,void 0,(function*(){try{this._mpNetworkStatusCallback=this._onNetworkStatusChange.bind(this),wx.onNetworkStatusChange(this._onNetworkStatusChange.bind(this))}catch(e){console.error(e)}}))}_deactivateNetworkMonitoring(){null!==this._mpNetworkStatusCallback&&(wx.offNetworkStatusChange&&wx.offNetworkStatusChange(this._mpNetworkStatusCallback),this._mpNetworkStatusCallback=null)}_onNetworkStatusChange(e){var t,n;const{isConnected:s,networkType:i}=e;null===(t=this._core)||void 0===t||t.store.set("netWorkMonitor",{isNetworkOnline:s,networkType:i}),null===(n=this._core)||void 0===n||n.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:s,networkType:i})}_reset(){var e;this._deactivateNetworkMonitoring(),null===(e=this._core)||void 0===e||e.store.clear("netWorkMonitor")}_dispose(){var e,t;null===(e=this._core)||void 0===e||e.notificationCenter.unSubscribeInnerEvent(null===(t=this._core)||void 0===t?void 0:t.InnerEvent.DESTROY,this._dispose,this),this._reset()}};var Xi=new class{init(e){const{IN_WX_MINI_APP:t}=e.helper;t?Zi.init(e):Ji.init(e)}};var Qi=new class{install(e){Ki.init(e),Xi.init(e)}};const eo=1,to=2,no=3,so=4,io=5,oo="TIMCustomElem",ro="C2C",ao="GROUP",co="invite",lo="accept",uo="cancel",_o="reject",ho="modifyInvitation",go="signaling",fo=8010,Eo="signaling-timeout";function po(e){return e.filter((e=>{if(e.type===oo){const{cloudCustomData:t="",payload:{data:n=""}={}}=e,s=t.match(/"type":"tsignaling"/),i=n.match(/inviteID/),o=n.match(/actionType/);return s||i&&o}return!1}))}function mo(e){const{data:t}=e.payload;try{return JSON.parse(t)}catch(e){return console.error(e),null}}function So(e,t){return e.toString(16).padStart(t,"0")}function vo(e){if(e<0||e>53)throw new Error("Number of digits must be between 0 and 53");if(e<=30)return Math.floor(Math.random()*(1<<e));const t=e-30;return Math.floor(Math.random()*(1<<t))*(1<<30)+Math.floor(Math.random()*(1<<30))}var Io=new class{constructor(){this._onlineSignalingMap=new Map,this._isSignalingListening=!1}init(e){this._core=e,e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.LOGOUT,this._reset,this)}getOnlineSignalingMap(){return this._onlineSignalingMap}hasSignaling(e){return this._onlineSignalingMap.has(e)}getSignaling(e){return this._onlineSignalingMap.get(e)}saveSignaling(e,t){return this._onlineSignalingMap.set(e,t)}removeSignaling(e){return this._onlineSignalingMap.delete(e)}isInvitationValid(e){const t=`${go}.isInvitationValid`,{inviteID:n,groupID:s,inviter:i}=e,o=i===this._core.common.getCurrentUserID();if(!this._onlineSignalingMap.has(n))return!1;const{inviteeList:r}=this._onlineSignalingMap.get(n);if(console.log(`${t} inviteID:${n} inviteeList:${r} groupID:${s}`),s){if(o)return r.length>0;const e=this._core.common.getCurrentUserID();return r.includes(e)}return!0}updateSignaling(e){const t=`${go}.updateSignaling`,{inviteID:n,inviter:s,inviteeList:i,groupID:o}=e;if(console.log(`${t} inviteID:${n} inviter:${s} groupID:${o}`),o&&this.hasSignaling(n)){const e=i[0],{inviteeList:s}=this._onlineSignalingMap.get(n);s.includes(e)&&(s.splice(s.indexOf(e),1),console.log(`${t} remove ${e}. localInviteeList.length:${s.length}`)),0===s.length&&this.removeSignaling(n)}else this.removeSignaling(n)}setSignalingListenStatus(e){this._isSignalingListening=e}getSignalingListenStatus(){return this._isSignalingListening}_dispose(){var e,t;this._reset(),null===(e=this._core)||void 0===e||e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),null===(t=this._core)||void 0===t||t.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),this._isSignalingListening=!1}_reset(){this._onlineSignalingMap.clear()}};var Co=new class{init(e){this._core=e}createInviteSignaling(e){const t=this._generateInviteID(),n=this._createInviteSignalingData(Object.assign(Object.assign({},e),{inviteID:t})),{groupID:s,inviteeList:i}=n,o=s||i[0];return{signaling:this._createSignaling(n,o),signalingData:n,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createAcceptSignaling(e){const t=this._createAcceptSignalingData(e),{groupID:n,inviter:s}=t,i=n||s;return{signaling:this._createSignaling(t,i),signalingData:t,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createCancelSignaling(e){const t=this._createCancelSignalingData(e),{groupID:n,inviteeList:s}=t,i=n||s[0];return{signaling:this._createSignaling(t,i),signalingData:t,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createRejectSignaling(e){const t=this._createRejectSignalingData(e),{groupID:n,inviter:s}=t,i=n||s;return{signaling:this._createSignaling(t,i),signalingData:t,signalingExtensionOptions:this._createSignalingExtensionOptions(e)}}createTimeoutSignaling(e){const{isInviter:t=!1}=e,n=this._createTimeoutSignalingData(e),{groupID:s,inviteeList:i,inviter:o}=n,r=s||(t?i[0]:o);return{signaling:this._createSignaling(n,r),signalingData:n,signalingExtensionOptions:this._createSignalingExtensionOptions(n)}}_createSignalingExtensionOptions(e){var t,n;const{data:s="",onlineUserOnly:i,inviteID:o="",offlinePushInfo:r,actionType:a}=e,c=(null===(n=null===(t=Io.getSignaling(o))||void 0===t?void 0:t.signaling)||void 0===n?void 0:n._onlineOnlyFlag)||!1;return{onlineUserOnly:i||c,offlinePushInfo:r,messageControlInfo:this._createMessageControlInfo(s,a)}}_createMessageControlInfo(e,t){const n=t===io&&!!e.match(/excludeTimeoutSignalingFromHistoryMessage/),s=!!e.match(/excludeFromHistoryMessage/)||!!e.match(/excludeOriginalSignalingFromHistoryMessage/);return{excludedFromContentModeration:!0,excludedFromUnreadCount:n||s,excludedFromLastMessage:n||s}}_createInviteSignalingData(e){const t=`${go}._createInviteSignalingData`,{userID:n,timeout:s=0,groupID:i="",inviteeList:o=[]}=e,r=this._core.common.getCurrentUserID(),a=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:eo,inviter:r,inviteeList:i?o:[n],timeout:s});return console.log(`${t} signalingData:`,a),a}_createAcceptSignalingData(e){const t=`${go}._createAcceptSignalingData`,{inviteID:n}=e,s=this._core.common.getCurrentUserID(),{inviter:i,groupID:o}=Io.getSignaling(n),r=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:no,groupID:o,inviter:i,inviteeList:[s]});return console.log(`${t} signalingData:`,r),r}_createCancelSignalingData(e){const t=`${go}._createCancelSignalingData`,{inviteID:n}=e,s=this._core.common.getCurrentUserID(),{inviteeList:i,groupID:o}=Io.getSignaling(n),r=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:to,groupID:o,inviter:s,inviteeList:i});return console.log(`${t} signalingData:`,r),r}_createRejectSignalingData(e){const t=`${go}._createRejectSignalingData`,{inviteID:n}=e,s=this._core.common.getCurrentUserID(),{inviter:i,groupID:o}=Io.getSignaling(n),r=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:so,groupID:o,inviter:i,inviteeList:[s]});return console.log(`${t} signalingData:`,r),r}_createTimeoutSignalingData(e){const t=`${go}._createTimeoutSignalingData`,{isInviter:n=!1,inviteID:s}=e,{inviteeList:i,inviter:o}=Io.getSignaling(s),r=this._core.common.getCurrentUserID(),a=Object.assign(Object.assign({},this._generateBaseSignalData(e)),{actionType:io,inviter:o,inviteeList:n?i:[r]});return console.log(`${t} signalingData:`,a),a}_createSignaling(e,t){var n,s,i;const{groupID:o=""}=e,r={to:t,conversationType:o?ao:ro,priority:"High",payload:{data:JSON.stringify(e)}};return null===(i=null===(s=null===(n=this._core)||void 0===n?void 0:n.message)||void 0===s?void 0:s.messageFactory)||void 0===i?void 0:i.createCustomMessage(r)}_generateInviteID(){return[So(vo(32),8),So(vo(16),4),So(16384|vo(12),4),So(32768|vo(14),4),So(vo(48),12)].join("-")}_generateBaseSignalData(e){const{data:t="",inviteID:n="",groupID:s=""}=e;return{businessID:1,timeout:0,data:t,inviteID:n,groupID:s}}};var yo=new class{constructor(){this._isProcessingSignaling=!1}init(e){this._core=e,e.helper.registerApi({apiName:"invite",context:this}),e.helper.registerApi({apiName:"accept",context:this}),e.helper.registerApi({apiName:"cancel",context:this}),e.helper.registerApi({apiName:"reject",context:this}),e.helper.registerApi({apiName:"modifyInvitation",context:this}),e.helper.registerApi({apiName:"getSignalingInfo",context:this}),e.helper.registerApi({apiName:"addSignalingListener",context:this}),e.helper.registerApi({apiName:"removeSignalingListener",context:this}),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.LOGOUT,this._reset,this)}invite(e){return a(this,void 0,void 0,(function*(){var t;console.log(`${go}.invite params:${JSON.stringify(e)}`);try{this._validateBeforeInvite(e);const{signaling:n,signalingData:s,signalingExtensionOptions:i}=Co.createInviteSignaling(e),o=yield this._sendSignaling(n,i);if(0===(null==o?void 0:o.code)){const{inviteID:e,timeout:i}=s;return Io.saveSignaling(e,Object.assign(Object.assign({},s),{signaling:n})),i>0&&(null===(t=this._core)||void 0===t||t.helper.taskScheduler.addOnceTask({id:`${Eo}-${e}`,intervalMs:1e3*(i+5),callback:this.handleInvitationExpiryTimer.bind(this,e)})),Object.assign(Object.assign({},o),{inviteID:e})}return o}catch(e){throw console.error(`${go}.invite error:${e}`),e}}))}accept(e){return a(this,void 0,void 0,(function*(){console.log(`${go}.accept params:${JSON.stringify(e)}`);try{const{inviteID:t}=e;this._validateBeforeAccept(t),this._isProcessingSignaling=!0;const{signaling:n,signalingData:s,signalingExtensionOptions:i}=Co.createAcceptSignaling(e),o=yield this._sendSignaling(n,i);return 0===(null==o?void 0:o.code)?(Io.updateSignaling(s),Object.assign(Object.assign({},o),{inviteID:t})):o}catch(e){throw console.error(`${go}.accept error:${e}`),e}finally{this._isProcessingSignaling=!1}}))}cancel(e){return a(this,void 0,void 0,(function*(){console.log(`${go}.cancel params:${JSON.stringify(e)}`);try{const{inviteID:t}=e;this._validateBeforeCancel(t),this._isProcessingSignaling=!0;const{signaling:n,signalingExtensionOptions:s}=Co.createCancelSignaling(e),i=yield this._sendSignaling(n,s);return 0===(null==i?void 0:i.code)?(Io.removeSignaling(t),Object.assign(Object.assign({},i),{inviteID:t})):i}catch(e){throw console.error(`${go}.cancel error:${e}`),e}finally{this._isProcessingSignaling=!1}}))}reject(e){return a(this,void 0,void 0,(function*(){console.log(`${go}.reject params:${JSON.stringify(e)}`);try{const{inviteID:t}=e;this._validateBeforeReject(t),this._isProcessingSignaling=!0;const{signaling:n,signalingExtensionOptions:s}=Co.createRejectSignaling(e),i=yield this._sendSignaling(n,s);return 0===(null==i?void 0:i.code)?(Io.removeSignaling(t),Object.assign(Object.assign({},i),{inviteID:t})):i}catch(e){throw console.error(`${go}.reject error:${e}`),e}finally{this._isProcessingSignaling=!1}}))}modifyInvitation(e){return a(this,void 0,void 0,(function*(){var t,n;console.log(`${go}.modifyInvitation params:${JSON.stringify(e)}`);const{inviteID:s,data:i}=e;let o="";try{this._validateBeforeModifyInvitation(s);const e=Io.getSignaling(s),{signaling:a}=e,c=r(e,["signaling"]);o=a.payload.data,c.data=i,a.payload.data=JSON.stringify(c);const l=yield null===(n=null===(t=this._core)||void 0===t?void 0:t.message.messageAction)||void 0===n?void 0:n.modifyMessage(a);return Io.hasSignaling(s)&&Io.saveSignaling(s,Object.assign(Object.assign({},c),{signaling:a})),l}catch(e){if(o){const{signaling:e}=Io.getSignaling(s);e.payload.data=o}throw e}}))}getSignalingInfo(e){if(0===po([e]).length)return;const t=mo(e),n={businessID:t.businessID||1,inviteID:t.inviteID,groupID:t.groupID||"",inviter:t.inviter||"",inviteeList:t.inviteeList||[],data:t.data||"",actionType:t.actionType||eo,timeout:t.timeout||0};return console.log(`${go} getSignalingInfo `,n),n}addSignalingListener(e,t,n){var s,i;e===(null===(s=this._core)||void 0===s?void 0:s.SignalingEvent.NEW_INVITATION_RECEIVED)&&Io.setSignalingListenStatus(!0),null===(i=this._core)||void 0===i||i.notificationCenter.subscribeOuterEvent(e,t,n)}removeSignalingListener(e,t,n){var s,i;e===(null===(s=this._core)||void 0===s?void 0:s.SignalingEvent.NEW_INVITATION_RECEIVED)&&Io.setSignalingListenStatus(!1),null===(i=this._core)||void 0===i||i.notificationCenter.unSubscribeOuterEvent(e,t,n)}handleInvitationExpiryTimer(e){const t=Io.getOnlineSignalingMap(),n=this._core.common.getCurrentUserID();if(!t.has(e))return;const s=t.get(e).inviter===n;this._sendTimeoutNotice({inviteID:e,isInviter:s})}_sendSignaling(e,t){return a(this,void 0,void 0,(function*(){var n,s,i;return null===(i=null===(s=null===(n=this._core)||void 0===n?void 0:n.message)||void 0===s?void 0:s.messageSender)||void 0===i?void 0:i.sendMessage(e,t)}))}_sendTimeoutNotice(e){return a(this,void 0,void 0,(function*(){var t,n,s;console.log(`${go}._sendTimeoutNotice params:${JSON.stringify(e)}`);const{isInviter:i,inviteID:o}=e,{signaling:r,signalingData:a,signalingExtensionOptions:c}=Co.createTimeoutSignaling(e),l=yield this._sendSignaling(r,c);if(0===(null==l?void 0:l.code)){const{data:e,groupID:c,inviteeList:l,inviter:d}=a;null===(t=this._core)||void 0===t||t.notificationCenter.emitOuterEvent(null===(n=this._core)||void 0===n?void 0:n.SignalingEvent.INVITATION_TIMEOUT,{name:null===(s=this._core)||void 0===s?void 0:s.SignalingEvent.INVITATION_TIMEOUT,data:{data:e,groupID:c,inviteID:o,inviteeList:l,inviter:d,isSelfTimeout:!0,message:r}}),i?Io.removeSignaling(o):Io.updateSignaling(a)}}))}_validateInviteId(e,t){if(!Io.hasSignaling(t))throw new this._core.helper.ChatError({functionName:e,code:fo})}_validateProcessStatus(e){if(this._isProcessingSignaling)throw new this._core.helper.ChatError({functionName:e,message:"processing other signaling operations"})}_validateBeforeInvite(e){const t=co,{userID:n}=e,s=this._core.common.getCurrentUserID();if(n===s)throw new this._core.helper.ChatError({functionName:t,message:`cannot invite yourself, currentUserId:${s}, inviteeId:${n}`})}_validateBeforeAccept(e){const t=lo;this._validateInviteId(t,e),this._validateProcessStatus(t);const n=this._core.common.getCurrentUserID(),{inviteeList:s}=Io.getSignaling(e);if(!s.includes(n)){const s=`userID:${n} not in inviteeList. inviteID:${e}`;throw new this._core.helper.ChatError({functionName:t,message:s})}}_validateBeforeCancel(e){const t=uo;this._validateInviteId(t,e),this._validateProcessStatus(t);const n=this._core.common.getCurrentUserID(),{inviter:s}=Io.getSignaling(e);if(s!==n){const e=`unmatched inviter:${s} and my userID:${n}`;throw new this._core.helper.ChatError({functionName:t,message:e})}}_validateBeforeReject(e){const t=_o;this._validateInviteId(t,e),this._validateProcessStatus(t);const n=this._core.common.getCurrentUserID(),{inviteeList:s}=Io.getSignaling(e);if(!s.includes(n)){const s=`userID:${n} not in inviteeList. inviteID:${e}`;throw new this._core.helper.ChatError({functionName:t,message:s})}}_validateBeforeModifyInvitation(e){const t=ho;this._validateInviteId(t,e)}_dispose(){var e,t;this._reset(),null===(e=this._core)||void 0===e||e.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),null===(t=this._core)||void 0===t||t.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this)}_reset(){this._isProcessingSignaling=!1}};var Mo=new class{constructor(){this._actionProcessor=new Map([[eo,this._onNewInvitationReceived.bind(this)],[so,this._onInviteeRejected.bind(this)],[no,this._onInviteeAccepted.bind(this)],[to,this._onInvitationCancelled.bind(this)],[io,this._onInvitationTimeout.bind(this)]])}init(e){this._core=e,e.notificationCenter.subscribeOuterEvent(e.OuterEvent.MESSAGE_RECEIVED,this._handleMessageReceived,this),e.notificationCenter.subscribeOuterEvent(e.OuterEvent.MESSAGE_MODIFIED,this._handleMessageModified,this),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this._dispose,this)}handleActionSignaling(e){e.forEach((e=>{const t=mo(e);if(t){const n=this._actionProcessor.get(t.actionType);null==n||n(t,e)}}))}_handleMessageReceived(e){if(!Io.getSignalingListenStatus())return;const t=po(e.data);0!==t.length&&this.handleActionSignaling(t)}_handleMessageModified(e){if(!Io.getSignalingListenStatus())return;const t=po(e.data);t.length>0&&t.forEach((e=>{const t=mo(e);t&&this._onInvitationModified(t,e)}))}_onNewInvitationReceived(e,t){var n,s;const i=`${go}._onNewInvitationReceived`,{inviteID:o,inviteeList:r,groupID:a}=e,c=this._core.common.getCurrentUserID();console.log(`${i} signalingData:${JSON.stringify(e)}}`);if(a&&!r.includes(c))return;let{timeout:l}=e;const d=Date.now()/1e3-t.time;l>0&&d>0&&l>d&&(l-=d);const u=Io.getSignaling(o);u!==e&&(u||Io.saveSignaling(o,Object.assign(Object.assign({},e),{signaling:t})),l>0&&(null===(n=this._core)||void 0===n||n.helper.taskScheduler.addOnceTask({id:`${Eo}-${o}`,intervalMs:1e3*l,callback:yo.handleInvitationExpiryTimer.bind(yo,o)})),this._emitEvent({name:null===(s=this._core)||void 0===s?void 0:s.SignalingEvent.NEW_INVITATION_RECEIVED,data:Object.assign(Object.assign({},this._generateBaseEmitData(e)),{inviteeList:r})}))}_onInviteeRejected(e){var t;const n=`${go}._onInviteeRejected`,{inviteID:s,inviter:i,groupID:o,inviteeList:r}=e,a=Io.hasSignaling(s);console.log(`${n} inviteID:${s} hasInviteID:${a} inviter:${i} groupID:${o}`),a&&(Io.updateSignaling(e),this._emitEvent({name:null===(t=this._core)||void 0===t?void 0:t.SignalingEvent.INVITEE_REJECTED,data:Object.assign(Object.assign({},this._generateBaseEmitData(e)),{invitee:r[0]})}))}_onInviteeAccepted(e){var t;const n=`${go}._onInviteeAccepted`,{inviteID:s,inviter:i,groupID:o,inviteeList:r}=e,a=Io.hasSignaling(s);console.log(`${n} inviteID:${s} hasInviteID:${a} inviter:${i} groupID:${o}`),a&&(Io.updateSignaling(e),this._emitEvent({name:null===(t=this._core)||void 0===t?void 0:t.SignalingEvent.INVITEE_ACCEPTED,data:Object.assign(Object.assign({},this._generateBaseEmitData(e)),{invitee:r[0]})}))}_onInvitationCancelled(e){var t;const n=`${go}._onInvitationCancelled`,{inviteID:s,inviter:i,groupID:o}=e,r=Io.hasSignaling(s);console.log(`${n} inviteID:${s} hasInviteID:${r} inviter:${i} groupID:${o}`),r&&(Io.removeSignaling(s),this._emitEvent({name:null===(t=this._core)||void 0===t?void 0:t.SignalingEvent.INVITATION_CANCELLED,data:this._generateBaseEmitData(e)}))}_onInvitationTimeout(e){var t;const n=`${go}._onInvitationTimeout`,{inviteID:s,inviteeList:i}=e,o=Io.hasSignaling(s);console.log(`${n} inviteID:${s} hasInviteID:${o} data:${e.data}`),o&&(Io.updateSignaling(e),this._emitEvent({name:null===(t=this._core)||void 0===t?void 0:t.SignalingEvent.INVITATION_TIMEOUT,data:Object.assign(Object.assign({},this._generateBaseEmitData(e)),{inviteeList:i,isSelfTimeout:!1})}))}_onInvitationModified(e,t){var n;const s=`${go}._onInvitationModified`,{inviteID:i,data:o}=e,r=Io.hasSignaling(i);console.log(`${s} inviteID:${i} data:${o}`),r&&(Io.saveSignaling(i,Object.assign(Object.assign({},e),{signaling:t})),this._emitEvent({name:null===(n=this._core)||void 0===n?void 0:n.SignalingEvent.INVITATION_MODIFIED,data:{inviteID:i,data:o}}))}_emitEvent(e){var t;null===(t=this._core)||void 0===t||t.notificationCenter.emitOuterEvent(e.name,e)}_generateBaseEmitData(e){const{inviteID:t,inviter:n,groupID:s,data:i}=e;return{inviteID:t,inviter:n,groupID:s,data:i||""}}_dispose(){var e,t,n;null===(e=this._core)||void 0===e||e.notificationCenter.unSubscribeOuterEvent(this._core.OuterEvent.MESSAGE_RECEIVED,this._handleMessageReceived,this),null===(t=this._core)||void 0===t||t.notificationCenter.unSubscribeOuterEvent(this._core.OuterEvent.MESSAGE_MODIFIED,this._handleMessageModified,this),null===(n=this._core)||void 0===n||n.notificationCenter.unSubscribeOuterEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}};var Oo=new class{constructor(){this._offlineSignalingMap=new Map}init(e){this._core=e;const{notificationCenter:t,helper:n,constants:{InnerEvent:s,WORKFLOW_STEP:i,WORKFLOW_NAME:o}}=e;t.subscribeInnerEvent(s.DESTROY,this._dispose,this),t.subscribeInnerEvent(s.LOGOUT,this._reset,this),n.registerWorkflowStep(o.SYNC_SERVER_INFO_AFTER_LOGIN,i.SIGNALING_MESSAGE_RECOVER,this._handleC2COfflineMessage,this)}_handleC2COfflineMessage(e){const{result:{unreadMessageMap:t}={}}=e||{};if(!(0!==(null==t?void 0:t.size)&&Io.getSignalingListenStatus()))return;const n=po([...t.values()]);if(0!==n.length&&(n.forEach((e=>{this._handleC2CActionType(e)})),this._offlineSignalingMap.size>0)){const e=this._sortOfflineSignalingByTime();Mo.handleActionSignaling(e)}}_handleC2CActionType(e){const t=mo(e);if(!t)return;const{actionType:n}=t;n===eo?this._saveValidOfflineInvite(t,e):this._removeOfflineInvite(t)}_saveValidOfflineInvite(e,t){const{inviteID:n,inviteeList:s=[],timeout:i=0}=e,o=this._core.common.getCurrentUserID();if(!s.includes(o))return;const r=Date.now()/1e3-t.time;i>0&&r>i&&0!==i||this._offlineSignalingMap.set(n,Object.assign(Object.assign({},e),{signalingList:[t]}))}_removeOfflineInvite(e){const{inviteID:t=""}=e;this._offlineSignalingMap.has(t)&&this._offlineSignalingMap.delete(t)}_sortOfflineSignalingByTime(){let e=[];return this._offlineSignalingMap.forEach((t=>{e=[...e,...t.signalingList]})),e.sort(((e,t)=>e.time-t.time))}_dispose(){var e,t;this._reset(),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)}_reset(){this._offlineSignalingMap.clear()}};const To={invite:{userID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0},timeout:{required:!1,rules:["number"],allowEmpty:!1},onlineUserOnly:{required:!1,rules:["boolean"],allowEmpty:!1},offlinePushInfo:{required:!1,rules:["object"],allowEmpty:!1}},cancel:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}},accept:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}},reject:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}},modifyInvitation:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}}},Ao={invite:!0,cancel:!0,accept:!0,reject:!0,modifyInvitation:!0};var Do=new class{install(e){yo.init(e),Mo.init(e),Co.init(e),Io.init(e),Oo.init(e),e.helper.registerValidateConfig({auth:Ao,params:To})}};const No=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.*"]),Ro="tui_room_svr.*";var bo=new class{constructor(){this._transferredCommands=No}install(e){this._core=e;const{notificationCenter:t,InnerEvent:n,helper:s}=e;t.subscribeInnerEvent(n.CLOUD_CONFIG_UPDATE,this._onCloudConfigUpdate,this),t.subscribeInnerEvent(n.LOGOUT,this._reset,this),t.subscribeInnerEvent(n.DESTROY,this._dispose,this),t.subscribeInnerEvent("im_open_push.msg_push",t.InnerEventSubType.BUSINESS_COMMAND,this._onServerPushBusinessCommand,this),s.registerExperimentalAPI("sendTRTCCustomData",this,"transferBusinessCommand"),s.registerExperimentalAPI("sendRoomCustomData",this,"transferBusinessCommand")}transferBusinessCommand(e){return a(this,void 0,void 0,(function*(){const t="transferBusinessCommand";try{const{serviceCommand:n=Ro}=e||{};if(!this._isValidTransferredCommand(n))throw new this._core.helper.ChatError({code:2995,functionName:t});const s=yield function(e,t){return a(this,void 0,void 0,(function*(){const{helper:n,channel:s}=t,{serviceCommand:i=Ro,data:o}=e||{};let r={};try{r="string"==typeof o?JSON.parse(o):o}catch(e){console.warn(e)}const a=n.generateProtocolData({servcmd:i,data:r}),c=`${a.head.seq}${i}`;return s.sendPacket(a,{requestId:c})}))}(e,this._core);return{code:0,data:s||{}}}catch(e){throw console.warn(e),new this._core.helper.ChatError({code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo,data:{},functionName:t})}}))}_onCloudConfigUpdate(e={}){try{if("string"!=typeof e.rtc_cmd)return;const t=JSON.parse(e.rtc_cmd);Array.isArray(t)&&(this._transferredCommands=new Set([...this._transferredCommands,...t]))}catch(e){console.log(e)}}_isValidTransferredCommand(e=""){const t=`${null==e?void 0:e.split(".")[0]}.*`;return this._transferredCommands.has(t)}_onServerPushBusinessCommand(e){const{OuterEvent:t,notificationCenter:n}=this._core,{MsgContent:s}=e||{},{ROOM_CUSTOM_DATA_RECEIVED:i}=t;n.emitOuterEvent(i,{name:i,data:s})}_reset(){this._transferredCommands=No}_dispose(){const{notificationCenter:e,InnerEvent:t}=this._core;this._reset(),e.unSubscribeInnerEvent(t.CLOUD_CONFIG_UPDATE,this._onCloudConfigUpdate,this),e.unSubscribeInnerEvent(t.LOGOUT,this._reset,this),e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this),e.unSubscribeInnerEvent("im_open_push.msg_push",e.InnerEventSubType.BUSINESS_COMMAND,this._onServerPushBusinessCommand,this)}};const wo=[$i,function(e){ki.install(e),Fi.install(e),xi.install(e)},ji,Qi,bo,Do];console.log(`TencentCloudLiteChat.VERSION:${Ve}`);var ko={create:function(e){const{SDKAppID:t,testEnv:n=!1,devMode:s=!1,unlimitedAVChatRoom:i=!1}=e;let o=t;if(!function(e){if("number"==typeof e)return!0;const t=Number(e);return!Number.isNaN(t)}(o))return console.error("Create SDK instance failed. Failed to parse the SDKAppID, please check the arguments"),null;if(o=Number(o),yn.has(o))return yn.get(o);const r=function(){function e(){return(65536*(1+Math.random())|0).toString(16).substring(1)}return`${e()+e()}${e()}${e()}${e()}${e()}${e()}${e()}`}();Gt.init({sdkAppId:o,instanceId:r,testEnv:n,devMode:s,unlimitedAVChatRoom:i}),Mn.init(),Gt.message=new si,Gt.user=new Ai,Gt.login=new us,In.installBuiltInPlugin(wo);const a=Wn();return yn.set(o,a),a},TSignaling:qt,EVENT:$t,VERSION:Ve,TYPES:tn};export{ko as default};