@tencentcloud/chat-uikit-engine 3.0.0-beta.0 → 3.0.0-beta.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.
Files changed (2) hide show
  1. package/index.js +1 -1
  2. package/package.json +2 -2
package/index.js CHANGED
@@ -1 +1 @@
1
- import e from"@tencentcloud/lite-chat";import t from"tim-upload-plugin";import s from"tim-profanity-filter-plugin";function n(e,t){var s={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(s[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(n=Object.getOwnPropertySymbols(e);o<n.length;o++)t.indexOf(n[o])<0&&Object.prototype.propertyIsEnumerable.call(e,n[o])&&(s[n[o]]=e[n[o]])}return s}function o(e,t,s,n){return new(s||(s=Promise))((function(o,i){function r(e){try{c(n.next(e))}catch(e){i(e)}}function a(e){try{c(n.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(r,a)}c((n=n.apply(e,t||[])).next())}))}const i=new class{init(e){this.core=e}};function r(e,t,s,n){return new(s||(s=Promise))((function(o,i){function r(e){try{c(n.next(e))}catch(e){i(e)}}function a(e){try{c(n.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(r,a)}c((n=n.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const a=e=>void 0===e,c=e=>"string"==typeof e,u=e=>"function"==typeof Array.isArray?Array.isArray(e):"array"===(e=>{var t;return null===(t=Object.prototype.toString.call(e).match(/^\[object (.*)\]$/))||void 0===t?void 0:t[1].toLowerCase()})(e),l=e=>null!==e&&"object"==typeof e,d=e=>u(e)||l(e),g=(e,t,s,n)=>{if(!d(e)||!d(t))return 0;let o=0;const i=Object.keys(t);let r;for(let c=0,u=i.length;c<u;c++)if(r=i[c],!(a(t[r])||s&&s.includes(r)))if(d(e[r])&&d(t[r]))o+=g(e[r],t[r],s,n);else{if(n&&n.includes(t[r]))continue;e[r]!==t[r]&&(e[r]=t[r],o+=1)}return o},h=e=>{const{core:{OuterConstant:t}}=i;return c(e)&&e.slice(0,3)===t.CONV_C2C},p=e=>{const{core:{OuterConstant:t}}=i;return c(e)&&e.slice(0,5)===t.CONV_GROUP},m=e=>{const{core:{OuterConstant:t}}=i;return c(e)&&e===t.CONV_SYSTEM},f=(e,t)=>{if(a(t))return"";const{core:{OuterConstant:s}}=i;switch(e){case s.MSG_TEXT:return t.text||"";case s.MSG_IMAGE:return"[Image]";case s.MSG_LOCATION:return"[Location]";case s.MSG_AUDIO:return"[Voice]";case s.MSG_VIDEO:return"[Video]";case s.MSG_FILE:return"[File]";case s.MSG_CUSTOM:return"[Custom Messages]";case s.MSG_GRP_TIP:return"[Group Notification]";case s.MSG_GRP_SYS_NOTICE:return"[Group System Message]";case s.MSG_FACE:return"[Animated Sticker]";case s.MSG_MERGER:return"[Chat Record]";default:return""}},v=e=>({lastTime:(null==e?void 0:e.time)||(null==e?void 0:e.lastTime)||0,lastSequence:(null==e?void 0:e.sequence)||(null==e?void 0:e.lastSequence)||0,fromAccount:(null==e?void 0:e.from)||(null==e?void 0:e.fromAccount)||"",messageForShow:f(null==e?void 0:e.type,null==e?void 0:e.payload),payload:(null==e?void 0:e.payload)||null,type:(null==e?void 0:e.type)||"",isRevoked:(null==e?void 0:e.isRevoked)||!1,cloudCustomData:(null==e?void 0:e.cloudCustomData)||"",onlineOnlyFlag:(null==e?void 0:e._onlineOnlyFlag)||!1,nick:(null==e?void 0:e.nick)||"",nameCard:(null==e?void 0:e.nameCard)||"",version:(null==e?void 0:e.version)||0,isPeerRead:(null==e?void 0:e.isPeerRead)||!1,revoker:(null==e?void 0:e.revoker)||null});function _(e){const t=[];if(!c(e))return t;const s=e.length;if(0===s)return t;for(let n=s-1;n>=0;n--)"1"===e[n]&&t.push(2**(s-n-1));return t}function I(e){const{OuterConstant:t}=i.core;let s;return e.startsWith(t.CONV_C2C)&&(s=e.replace(t.CONV_C2C,"")),"@TLS#ERROR"===s||"@TLS#NOT_FOUND"===s}var y,E,S,C,M,T;!function(e){e.NOT_START="notStart",e.PENDING="pending",e.RESOLVED="resolved",e.REJECTED="rejected"}(y||(y={})),function(e){e[e.C2C=1]="C2C",e[e.GROUP=2]="GROUP"}(E||(E={})),function(e){e[e.C2C=8]="C2C",e[e.GROUP=2]="GROUP"}(S||(S={})),function(e){e[e.ONLY_CONVERSATIONID=1]="ONLY_CONVERSATIONID"}(C||(C={})),function(e){e[e.CONV_DELETED=1]="CONV_DELETED",e[e.CONV_PINED=2]="CONV_PINED",e[e.CONV_UNPINED=3]="CONV_UNPINED",e[e.CONV_MARK_UPDATED=4]="CONV_MARK_UPDATED",e[e.CONV_GROUP_ADDED=5]="CONV_GROUP_ADDED",e[e.CONV_GROUP_DELETED=6]="CONV_GROUP_DELETED",e[e.CONV_GROUP_UPDATED=7]="CONV_GROUP_UPDATED"}(M||(M={})),function(e){e[e.CONV_NOT_FOUND=2500]="CONV_NOT_FOUND",e[e.CONV_UN_RECORDED_TYPE=2502]="CONV_UN_RECORDED_TYPE"}(T||(T={}));class D{constructor(e){this.conversationID=e.conversationID||"",this.unreadCount=e.unreadCount||0,this.type=e.type||"",this.lastMessage=v(e.lastMessage),this.peerReadTime=e.peerReadTime||0,this.groupAtInfoList=[],this.remark="",this.isPinned=e.isPinned||!1,this.messageRemindType=e.messageRemindType,this.markList=e.markList||[],this.customData=e.customData||"",this.conversationGroupList=e.conversationGroupList||[],this.draftText=e.draftText||"",this.userProfile=e.userProfile,this.groupProfile=e.groupProfile,this.subType=e.subType||"",this._isInfoCompleted=!1,this._init()}_init(){const{core:{OuterConstant:e}}=i;a(this.userProfile)&&this.type===e.CONV_C2C?this.userProfile={}:a(this.groupProfile)&&this.type===e.CONV_GROUP&&(this.groupProfile={}),this.subType&&this.type===e.CONV_GROUP&&(this.subType=this.groupProfile.type||"")}updateUnreadCount(e){const{core:{OuterConstant:t}}=i,{nextUnreadCount:s,isFromGetConversations:n,isUnreadC2CMessage:o}=e;a(s)||((e=>{const{core:{OuterConstant:t}}=i;return e===t.GRP_AVCHATROOM})(this.subType)?this.unreadCount=0:n&&this.type===t.CONV_GROUP||n&&this.type===t.CONV_TOPIC||o&&this.type===t.CONV_C2C?this.unreadCount=s:this.unreadCount+=s)}updateLastMessage(e){this.lastMessage=v(e)}reduceUnreadCount(){return this.unreadCount>=1&&(this.unreadCount-=1,!0)}isLastMessageRevoked(e){const{core:{OuterConstant:t}}=i,{sequence:s,time:n}=e;return this.type===t.CONV_C2C&&s===this.lastMessage.lastSequence&&n===this.lastMessage.lastTime||this.type===t.CONV_GROUP&&s===this.lastMessage.lastSequence}setLastMessageRevoked(e){this.lastMessage.isRevoked=e}setLastMessageRevoker(e){this.lastMessage.revoker=e}setDraftText(e){this.draftText=e}updateGroupAtInfoList(e){const{core:{OuterConstant:t}}=i;let[...s]=e.groupAtType;s.includes(t.CONV_AT_ME)||s.includes(t.CONV_AT_ALL)||(s=[t.CONV_AT_ALL_AT_ME]);const n={from:e.from,groupID:e.groupID,messageSequence:e.sequence,atTypeArray:s,__random:e.__random,__sequence:e.__sequence};this.groupAtInfoList.push(n)}clearGroupAtInfoList(){this.groupAtInfoList.length=0}}var b=new class{constructor(){this._name="ConversationDataHandler",this._conversationMap=new Map,this._totalUnreadCount=0,this._groupAtTipsList=[]}init(e){this._core=e;const{notificationCenter:t,InnerEvent:{MESSAGE_PUSH:s,NEW_MESSAGE:n,MESSAGE_DELETED:o,MESSAGE_REVOKED:i,MESSAGE_MODIFIED:r,LOGOUT:a,DESTROY:c}}=e,{InnerEventSubType:{GROUP_AT_TIPS:u}}=t;t.subscribeInnerEvent(n,this._handleNewMessage,this),t.subscribeInnerEvent(s,u,this._handleNewGroupAtTips,this),t.subscribeInnerEvent(o,this._handleMessageDeleted,this),t.subscribeInnerEvent(i,this._handleMessageRevoked,this),t.subscribeInnerEvent(r,this._handleMessageModified,this),t.subscribeInnerEvent(r,this._handleMessageModified,this),t.subscribeInnerEvent(a,this._reset,this),t.subscribeInnerEvent(c,this._dispose,this),console.log(`${this._name}.init`)}_handleNewMessage(e){const{conversationOptionsList:t=[],isInstantMessage:s=!0,isUnreadC2CMessage:n=!1,updateUnreadCount:o=!0}=e;console.log(`${this._name}._handleNewMessage, conversationOptionsList length:`,t.length),0!==t.length&&(this._updateLocalConversationList({conversationOptionsList:t,isInstantMessage:s,isUnreadC2CMessage:n,isFromGetConversations:!1,updateUnreadCount:o}),t.filter((e=>this._isConversationNeedShow(e.conversationID))).length>0&&this.emitConversationListUpdate())}_handleNewGroupAtTips(e){const{GroupTips:t=[]}=e;t.forEach((e=>{const{GroupAtTips:t,MsgBody:s,GroupAtType:n,MsgRandom:o,ClientSeq:i}=e;let r={};t?r=this._convertGroupAtTipsKey(t):s?r=Object.assign(Object.assign({},this._convertGroupAtTipsKey(s)),{sync:!0}):n&&(r=Object.assign(Object.assign({},this._convertGroupAtTipsKey(e)),{sync:!0})),r.__random=o,r.__sequence=i,this._groupAtTipsList.push(r)})),console.log(`${this._name}._handleNewGroupAtTips groupAtTipsList:`,this._groupAtTipsList),this._updateGroupAtInfoToConversation()}_convertGroupAtTipsKey(e){const{From_Account:t,GroupId:s,MsgSeq:n,GroupAtType:o}=e;return{from:t,groupID:s,sequence:n,groupAtType:o}}_updateGroupAtInfoToConversation(){if(0===this._groupAtTipsList.length)return;const{common:e,OuterConstant:t}=this._core,s=e.getCurrentUserID();let n=!1;this._groupAtTipsList.forEach((e=>{const{groupID:o,from:i}=e;if(i!==s){const s=this.getLocalConversation(`${t.CONV_GROUP}${o}`);s&&(s.updateGroupAtInfoList(e),n=!0)}})),n&&this.emitConversationListUpdate(),this._groupAtTipsList.length=0}_handleMessageDeleted(e){var t,s;console.log(`${this._name}._handleMessageDeleted, conversationID:`,e);const{message:{messageStore:n},OuterConstant:o}=this._core,i=(null==n?void 0:n.getLocalMessageList(e))||[];let r={};for(let e=(i.length||0)-1;e>=0;e--)if(!i[e].isDeleted){r=i[e];break}const a=this._conversationMap.get(e);if(!a)return;let c=!1;a.lastMessage.lastSequence===r.sequence&&a.lastMessage.lastTime===r.time||((null===(s=null===(t=this._core)||void 0===t?void 0:t.helper)||void 0===s?void 0:s.isEmpty(r))&&(r=void 0),a.updateLastMessage(r),c=!0),e.startsWith(o.CONV_C2C)&&this.updateUnreadCount(e),c&&(this.emitConversationListUpdate(),console.log(`${this._name}._handleMessageDeleted. update conversationID:${e} with lastMessage:`,a.lastMessage))}_handleMessageRevoked(e){console.log(`${this._name}._handleMessageRevoked`,JSON.stringify(e));const{messageList:t=[],updateUnreadCount:s=!0}=e;if(0===t.length)return;let n=null,o=!1;t.forEach((e=>{n=this._conversationMap.get(e.conversationID),n&&(s&&n.reduceUnreadCount()&&(o=!0),n.isLastMessageRevoked({sequence:e.sequence,time:e.time})&&(n.setLastMessageRevoked(!0),n.setLastMessageRevoker(e.revoker),o=!0))})),o&&this.emitConversationListUpdate()}_handleMessageModified(e){var t,s;console.log(`${this._name}._handleMessageModified`,JSON.stringify(e));const{conversationID:n,message:o}=e,i=this._conversationMap.get(n);if(null===(s=null===(t=this._core)||void 0===t?void 0:t.helper)||void 0===s?void 0:s.isEmpty(i))return;const{lastMessage:r}=i;r&&r.lastTime===o.time&&r.lastSequence===o.sequence&&r.version!==o.version&&(r.type=o.type,r.payload=o.payload,r.messageForShow=f(o.type,o.payload),r.cloudCustomData=o.cloudCustomData,r.version=o.version,this.emitConversationListUpdate(),console.log(`${this._name} conversationID:${n} lastMessage updated`))}updateLocalConversationList(e){const{newConversationList:t}=this._getTmpConversationListMapping(e);this._conversationMap=new Map(this._sortConversationList([...this._conversationMap])),this._core.store.set("conversation",{conversationMap:this._conversationMap}),console.log(`${this._name}._updateLocalConversationList newConversationList: ${t.length}`)}_getTmpConversationListMapping(e){const{OuterConstant:t}=this._core,{conversationOptionsList:s,isFromGetConversations:n,isInstantMessage:o,isUnreadC2CMessage:i=!1,updateUnreadCount:r}=e,a=[],c=null==s?void 0:s.length;for(let e=0;e<c;e++){const c=new D(s[e]),{conversationID:u,type:l}=c;if(!I(u))if(this._conversationMap.has(u)){const a=this._conversationMap.get(u);if(n){this._conversationMap.set(u,c),l===t.CONV_C2C?c.unreadCount=(null==a?void 0:a.unreadCount)||0:l===t.CONV_GROUP&&(c.groupProfile=JSON.parse(JSON.stringify(null==a?void 0:a.groupProfile)));continue}this._mergeConversationInfo({conversationID:u,tmpConversation:c,lastMessage:s[e].lastMessage,isFromGetConversations:n,isInstantMessage:o}),this._patchLastMessage({conversationID:u,lastMessage:s[e].lastMessage,isInstantMessage:o}),!0===r&&(null==a||a.updateUnreadCount({nextUnreadCount:c.unreadCount,isFromGetConversations:n,isUnreadC2CMessage:i}))}else a.push(c),this._conversationMap.set(u,c)}return{newConversationList:a}}_mergeConversationInfo(e){var t,s;const{conversationID:n,tmpConversation:o,lastMessage:i,isFromGetConversations:r,isInstantMessage:c}=e,u=this._conversationMap.get(n),l=["unreadCount","allowType","adminForbidType","payload"];!1===c&&l.push("lastMessage"),r&&l.push("isPinned"),a(c)&&i&&null===(null==u?void 0:u.lastMessage.payload)&&(u.lastMessage.payload=i.payload),(null===(s=null===(t=this._core)||void 0===t?void 0:t.helper)||void 0===s?void 0:s.isEmpty(null==u?void 0:u.lastMessage.revoker))||(u.lastMessage.revoker=null),g(u,o,l,[null,void 0,"",0,NaN])}_patchLastMessage(e){const{OuterConstant:t}=this._core,{conversationID:s,lastMessage:n,isInstantMessage:o}=e,i=this._conversationMap.get(s);if(i&&n){const{payload:e,nameCard:s,nick:r,cloudCustomData:a=""}=n;o&&(e&&(i.lastMessage.payload=e),i.type===t.CONV_GROUP&&(i.lastMessage.nameCard=s,i.lastMessage.nick=r)),i.lastMessage.cloudCustomData!==a&&(i.lastMessage.cloudCustomData=a)}}_sortConversationList(e){const{helper:t}=this._core,s=[],n=[],o=[],i=[];return e.forEach((e=>{var r,a;!0===e[1].isPinned?(null===(a=null===(r=this._core)||void 0===r?void 0:r.helper)||void 0===a?void 0:a.isEmpty(e[1].lastMessage.lastTime))?n.push(e):s.push(e):(null==t?void 0:t.isEmpty(e[1].lastMessage.lastTime))?i.push(e):o.push(e)})),s.sort(((e,t)=>t[1].lastMessage.lastTime-e[1].lastMessage.lastTime)).concat(n).concat(o.sort(((e,t)=>t[1].lastMessage.lastTime-e[1].lastMessage.lastTime))).concat(i)}_isConversationNeedShow(e){const t=this.getLocalConversation(e);if(a(t))return!0;const{OuterConstant:s}=this._core,n=t.type===s.CONV_TOPIC,o=t.type===s.CONV_GROUP&&t.subType===s.GRP_ROOM,i=t.type===s.CONV_GROUP&&t.subType===s.GRP_LIVE;return!(n||o||i)}updateUnreadCount(e,t=!0){var s,n;let o=!1;const i=this.getLocalConversation(e),r=null===(n=null===(s=this._core)||void 0===s?void 0:s.message.messageStore)||void 0===n?void 0:n.getLocalMessageList(e);if(!i)return o;const a=i.unreadCount,c=null==r?void 0:r.filter((e=>!e.isRead&&!e._onlineOnlyFlag&&!e.isDeleted)).length;return a!==c&&(i.unreadCount=c,o=!0,console.log(`${this._name}._updateUnreadCount from ${a} to ${c}, conversationID:${e}`),!0===t&&this.emitConversationListUpdate()),o}emitConversationListUpdate(e=!1){var t;e&&(this._conversationMap=new Map(this._sortConversationList([...this._conversationMap])));const s=this.getLocalConversationList();this._emitEvent({name:null===(t=this._core)||void 0===t?void 0:t.OuterEvent.CONVERSATION_LIST_UPDATED,data:s}),this._emitTotalUnreadCountUpdate()}_emitTotalUnreadCountUpdate(){var e;const t=this.getTotalUnreadMessageCount();this._totalUnreadCount!==t&&(console.log(`${this._name}._emitTotalUnreadCountUpdate from ${this._totalUnreadCount} to ${t}`),this._totalUnreadCount=t,this._emitEvent({name:null===(e=this._core)||void 0===e?void 0:e.OuterEvent.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED,data:t}))}_emitEvent(e){var t;null===(t=this._core)||void 0===t||t.notificationCenter.emitOuterEvent(e.name,e)}getTotalUnreadMessageCount(){const{OuterConstant:e}=this._core,t=this.getLocalConversationList();let s=0;return t.forEach((t=>{t.type!==e.CONV_SYSTEM&&(""!==t.messageRemindType&&t.messageRemindType!==e.MSG_REMIND_ACPT_AND_NOTE||(s+=t.unreadCount))})),s}getLocalConversationList(){return[...this._conversationMap.values()].filter((e=>this._isConversationNeedShow(e.conversationID)))}hasLocalConversation(e){return this._conversationMap.has(e)}getLocalConversation(e){return this._conversationMap.get(e)}setLocalConversation(e,t){return this._conversationMap.set(e,t)}deleteLocalConversation(e){this._conversationMap.delete(e)}patchMessageRemindType(e,t){let s=!1;e.forEach((e=>{const n=this.getLocalConversation(e);(null==n?void 0:n.messageRemindType)!==t&&(n.messageRemindType=t,s=!0)})),console.log(`${this._name}.patchMessageRemindType conversationIDList:${e} messageRemindType:${t} hasUpdated:${s}`),s&&this.emitConversationListUpdate()}_reset(){this._conversationMap.clear(),this._totalUnreadCount=0,this._groupAtTipsList=[]}_dispose(){const{notificationCenter:e,InnerEvent:{NEW_MESSAGE:t,MESSAGE_DELETED:s,MESSAGE_REVOKED:n,MESSAGE_MODIFIED:o,LOGOUT:i,DESTROY:r}}=this._core,{InnerEventSubType:{GROUP_AT_TIPS:a}}=e;e.unSubscribeInnerEvent(t,this._handleNewMessage,this),e.unSubscribeInnerEvent(t,a,this._handleNewGroupAtTips,this),e.unSubscribeInnerEvent(s,this._handleMessageDeleted,this),e.unSubscribeInnerEvent(n,this._handleMessageRevoked,this),e.unSubscribeInnerEvent(o,this._handleMessageModified,this),e.subscribeInnerEvent(i,this._reset,this),e.unSubscribeInnerEvent(r,this._dispose,this)}};function O(e,t,s){return r(this,void 0,void 0,(function*(){const{helper:n,channel:o}=s,i=n.generateProtocolData({servcmd:e,data:t}),r=`${i.head.seq}${e}`;return yield o.sendPacket(i,{requestId:r})}))}var L=new class{constructor(){this._name="SyncConversationList",this._pagingStatus="",this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}init(e){this._core=e;const{notificationCenter:t,InnerEvent:s,helper:n,constants:o}=e;n.registerWorkflowStep(o.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,o.WORKFLOW_STEP.CONVERSATION_RECOVER,this._syncConversationListOnReOnline,this),t.subscribeInnerEvent(s.LOGIN,this.handleLoginSuccess,this),t.subscribeInnerEvent(s.DESTROY,this._dispose,this),console.log(`${this._name}.init`)}handleLoginSuccess(){this._syncConversationList()}isSyncCompleted(){return this._pagingStatus===y.RESOLVED}_syncConversationListOnReOnline(){return r(this,void 0,void 0,(function*(){return this._syncConversationList()}))}_syncConversationList(){return r(this,arguments,void 0,(function*(e=!0){yield this._pagingGetConversationList(e),this._pagingStatus=y.RESOLVED,b.emitConversationListUpdate()}))}_pagingGetConversationList(e){return r(this,void 0,void 0,(function*(){try{this._pagingStatus=y.PENDING;const{common:t}=this._core,s=yield function(e,t){return r(this,void 0,void 0,(function*(){const{fromAccount:s,pagingTimeStamp:n,pagingStartIndex:o,pagingPinnedTimeStamp:i,pagingPinnedStartIndex:r}=e;return O("recentcontact.page_get",{AssistFlags:31,MsgAssistFlags:15,OrderType:1,From_Account:s,StartIndex:o,TimeStamp:n,TopStartIndex:r,TopTimeStamp:i},t)}))}({fromAccount:t.getCurrentUserID(),pagingTimeStamp:e?this._pagingTimeStamp:0,pagingStartIndex:e?this._pagingStartIndex:0,pagingPinnedTimeStamp:e?this._pagingPinnedTimeStamp:0,pagingPinnedStartIndex:e?this._pagingPinnedStartIndex:0},this._core),{CompleteFlag:n,SessionItem:o=[],TimeStamp:i,StartIndex:a,TopTimeStamp:c,TopStartIndex:u}=s||{};if(o.length>0){const e=this._getConversationOptions(o);b.updateLocalConversationList({conversationOptionsList:e,isFromGetConversations:!0,updateUnreadCount:!0}),b.emitConversationListUpdate()}this._pagingTimeStamp=i,this._pagingStartIndex=a,this._pagingPinnedTimeStamp=c,this._pagingPinnedStartIndex=u,1!==n&&this._pagingGetConversationList(e)}catch(e){throw console.error(`${this._name}._pagingGetConversationList fail:`,e),e}}))}_getConversationOptions(e){const t=this._convertConversationKey(e);return this._filterValidConversations(t).map((e=>(a(e.lastMsg)&&(e.lastMsg={elements:[]}),e.type===E.C2C?this._assembleC2COption(e):this._assembleGroupOption(e))))}_filterValidConversations(e){return e.filter((({type:e,userID:t})=>e===E.C2C&&!I(t)||2===e))}_assembleC2COption(e){var t,s,n,o,i,r,a;const{user:c,OuterConstant:u}=this._core,l={userID:e.userID,nick:e.nick,avatar:e.peerAvatar},d=null===(t=null==c?void 0:c.userProfile)||void 0===t?void 0:t.createProfile(e.userID,[l]);return{conversationID:`${u.CONV_C2C}${e.userID}`,type:u.CONV_C2C,lastMessage:{lastTime:e.time,lastSequence:e.sequence,fromAccount:e.lastC2CMsgFromAccount,type:(null===(s=e.lastMsg)||void 0===s?void 0:s.elements[0])?null===(n=e.lastMsg)||void 0===n?void 0:n.elements[0].type:null,payload:(null===(o=e.lastMsg)||void 0===o?void 0:o.elements[0])?this._amendLayersOverLimitProp(e.lastMsg.elements[0].content):null,cloudCustomData:(null===(i=e.lastMsg)||void 0===i?void 0:i.cloudCustomData)||"",isRevoked:e.lastMessageFlag===S.C2C,onlineOnlyFlag:!1,nick:"",nameCard:"",version:0,isPeerRead:this._computeIsPeerRead(e),revoker:(null===(a=null===(r=e.lastMsg)||void 0===r?void 0:r.revokerInfo)||void 0===a?void 0:a.revoker)||null},unreadCount:0,userProfile:d,peerReadTime:e.peerReadTime,isPinned:1===e.isPinned,customData:e.customMark||"",markList:_(e.standardMark),conversationGroupList:[],remark:e.friendRemark||"",messageRemindType:this._transMsgRemindType(e.messageRemindType)}}_computeIsPeerRead(e){const{common:t}=this._core,s=t.getCurrentUserID(),{lastC2CMsgFromAccount:n,time:o,c2cPeerReadTime:i}=e;return n===s&&o<=i}_assembleGroupOption(e){var t,s,n;const{OuterConstant:o}=this._core;return{conversationID:`${o.CONV_GROUP}${e.groupID}`,type:o.CONV_GROUP,lastMessage:Object.assign(Object.assign({lastTime:e.time,lastSequence:e.sequence,fromAccount:e.msgGroupFromAccount},this._patchTypeAndPayload(e)),{cloudCustomData:(null===(t=e.lastMsg)||void 0===t?void 0:t.cloudCustomData)||"",isRevoked:e.lastMessageFlag===S.GROUP,onlineOnlyFlag:!1,nick:e.msgGroupFromNickName||"",nameCard:e.msgGroupFromCardName||"",revoker:(null===(n=null===(s=e.lastMsg)||void 0===s?void 0:s.revokerInfo)||void 0===n?void 0:n.revoker)||null}),groupProfile:{groupID:e.groupID,name:e.groupNick,avatar:e.groupImage,type:e.groupType,nextMessageSeq:e.nextMessageSeq},unreadCount:this._computeGroupUnreadCount(e),peerReadTime:0,isPinned:1===e.isPinned,version:0,customData:e.customMark||"",markList:_(e.standardMark),conversationGroupList:[],messageRemindType:this._transMsgRemindType(e.messageRemindType),subType:e.groupType}}_convertConversationKey(e){return e.map((e=>({type:e.Type,userID:e.To_Account,nick:e.C2cNick,peerAvatar:e.C2cImage,time:e.MsgTimeStamp,sequence:e.MsgSeq,lastC2CMsgFromAccount:e.LastC2cMsgFrom_Account,lastMsg:this._convertLastMsgKey(e.LastMsg),lastMessageFlag:e.LastMsgFlags,c2cPeerReadTime:e.LastC2cMsgPeerReadTime,peerReadTime:e.C2cPeerReadTime,friendRemark:e.C2cRemark,isPinned:e.TopFlags,standardMark:e.StandardMark,customMark:e.CustomMark,messageRemindType:e.MsgRecvOption,groupID:e.ToAccount,groupNick:e.GroupNick,groupImage:e.GroupImage,groupType:e.GroupType,nextMessageSeq:e.GroupNextMsgSeq,msgGroupFromAccount:e.MsgGroupFrom_Account,msgGroupFromNickName:e.MsgGroupFromNickName,MsgGroupFromCardName:e.MsgGroupFromCardName,unreadCount:e.UnreadMsgCount,noUnreadCount:e.GroupIgnoredUnreadSeqCount})))}_convertLastMsgKey(e){var t,s,n,o;if(null===(s=null===(t=this._core)||void 0===t?void 0:t.helper)||void 0===s?void 0:s.isEmpty(e))return null;let i="",r=null;return e.MsgBody&&(i=null===(n=e.MsgBody[0])||void 0===n?void 0:n.MsgType,r=this._parseContent(i,e.MsgBody[0])),{event:e.Event,elements:[{type:i,content:r,cloudCustomData:e.CloudCustomData}],revokerInfo:{revoker:null===(o=e.RevokerInfo)||void 0===o?void 0:o.revoker}}}_parseContent(e,t){var s;if(!t)return t;const n=this._core.message.messageFactory.getElementClass(e);return n?null===(s=n.parseServerPushElement(t))||void 0===s?void 0:s.content:t}_amendLayersOverLimitProp(e){const{LayersOverLimit:t}=e;return(function(e,t){var s={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(s[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(n=Object.getOwnPropertySymbols(e);o<n.length;o++)t.indexOf(n[o])<0&&Object.prototype.propertyIsEnumerable.call(e,n[o])&&(s[n[o]]=e[n[o]])}return s}(e,["LayersOverLimit"])).layersOverLimit=1===t,e}_transMsgRemindType(e){const{OuterConstant:t}=this._core;let s="";return 0===e?s=t.MSG_REMIND_ACPT_AND_NOTE:1===e?s=t.MSG_REMIND_DISCARD:2===e?s=t.MSG_REMIND_ACPT_NOT_NOTE:3===e&&(s=t.NOT_RECEIVE_OFFLINE_PUSH_EXCEPT_AT),s}_patchTypeAndPayload(e){const{OuterConstant:t}=this._core,{event:s,elements:n=[]}=e.lastMsg||{};return a(s)?{type:n[0]?n[0].type:null,payload:n[0]?this._amendLayersOverLimitProp(n[0].content):null}:{type:t.MSG_GRP_TIP,payload:{}}}_computeGroupUnreadCount(e){const{unreadCount:t=0,noUnreadCount:s=0}=e,n=t-s;return n>0?n:0}_dispose(){const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.LOGIN,this.handleLoginSuccess,this),e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}},A=new class{constructor(){this._name="GetConversationList"}init(e){this._core=e;const{helper:t}=e;t.registerApi("getConversationList",this)}getConversationList(e){return r(this,void 0,void 0,(function*(){return{code:0,data:{conversationList:this._getConversationList(e),isSyncCompleted:L.isSyncCompleted()}}}))}_getConversationList(e){if(a(e))return b.getLocalConversationList();if(u(e))return 0===e.length?[]:b.getLocalConversationList().filter((t=>e.includes(t.conversationID)));if((e=>{if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);if(null===t)return!0;let s=t;for(;null!==Object.getPrototypeOf(s);)s=Object.getPrototypeOf(s);return t===s})(e)){const{type:t,markType:s,groupName:n,hasUnreadCount:o,hasGroupAtInfo:i}=e;return b.getLocalConversationList().filter((e=>this._filterType(e,t)&&this._filterMarkType(e,s)&&this._filterGroupName(e,n)&&this._filterUnreadCount(e,o)&&this._filterGroupAtInfo(e,i)))}return[]}_filterType(e,t){const{OuterConstant:s}=this._core;return t!==s.CONV_C2C&&t!==s.CONV_GROUP||e.type===t}_filterGroupName(e,t){return!c(t)||(""===t?0===e.conversationGroupList.length:e.conversationGroupList.includes(t))}_filterMarkType(e,t){return null===(s=t)||!("number"==typeof s&&!Number.isNaN(s-0)||"object"==typeof s&&s.constructor===Number)||(0===t?0===e.markList.length:e.markList.includes(t));var s}_filterUnreadCount(e,t){let s=!0;return!0===t?s=e.unreadCount>=1:!1===t&&(s=0===e.unreadCount),s}_filterGroupAtInfo(e,t){let s=!0;return!0===t?s=e.groupAtInfoList.length>=1:!1===t&&(s=0===e.groupAtInfoList.length),s}},U=new class{constructor(){this._name="GetConversationProfile"}init(e){this._core=e;const{helper:t}=e;t.registerApi("getConversationProfile",this)}getConversationProfile(e){return r(this,void 0,void 0,(function*(){let t;if(b.hasLocalConversation(e))t=b.getLocalConversation(e);else{t=new D({conversationID:e});const{OuterConstant:s}=this._core;h(e)?(t.type=s.CONV_C2C,t.userProfile={userID:e.replace(s.CONV_C2C,"")}):(t.type=s.CONV_GROUP,t.groupProfile={groupID:e.replace(s.CONV_GROUP,"")}),b.setLocalConversation(e,t)}return{code:0,data:{conversation:t}}}))}},R=new class{init(e){const{helper:t}=e;t.registerApi("getTotalUnreadMessageCount",this)}getTotalUnreadMessageCount(){return b.getTotalUnreadMessageCount()}},P=new class{constructor(){this._name="SetMessageRead"}init(e){this._core=e;const{helper:t}=e;t.registerApi("setMessageRead",this)}setMessageRead(e){return r(this,void 0,void 0,(function*(){var t,s;const{OuterConstant:n}=this._core,{conversationID:o}=e,i={code:0,data:{}},r=b.getLocalConversation(o);if(console.log(`${this._name}.setMessageRead conversationID:${o} unreadCount:${(null==r?void 0:r.unreadCount)||0}`),!r)return i;const a=!(null===(s=null===(t=this._core)||void 0===t?void 0:t.helper)||void 0===s?void 0:s.isEmpty(r.groupAtInfoList));if(r.type===n.CONV_GROUP&&a&&this._deleteGroupAtTips(o),0===r.unreadCount)return i;if(r.type===n.CONV_C2C){const e=this._getLocalMessageMaxTime(r);yield this._setC2CMessageRead(o,e)}if(r.type===n.CONV_GROUP){const e=this._getLocalMessageMaxSequence(r);yield this._setGroupMessageRead(o,e)}return r.type===n.CONV_SYSTEM&&(r.unreadCount=0),b.emitConversationListUpdate(),i}))}_deleteGroupAtTips(e){return r(this,void 0,void 0,(function*(){console.log(`${this._name}._deleteGroupAtTips conversationID:${e}`);const t=b.getLocalConversation(e);if(!t)return;const s=(null==t?void 0:t.groupAtInfoList)||[];if(0!==s.length)try{const t=s.map((e=>({From_Account:e.from,To_Account:this._core.store.get("login").userId,MsgSeq:e.__sequence,MsgRandom:e.__random,GroupId:e.groupID})));yield function(e,t){return r(this,void 0,void 0,(function*(){const{messageListToDelete:s}=e;return O("openim.deletemsg",{DelMsgList:s},t)}))}({messageListToDelete:t},this._core),console.log(`${this._name}._deleteGroupAtTips ok. count:${s.length}`),this._clearGroupAtInfoList(e)}catch(e){console.error(`${this._name}._deleteGroupAtTips fail:`,e)}}))}_clearGroupAtInfoList(e){const t=b.getLocalConversation(e);if(!t)return;let s=!1;t.groupAtInfoList.length>0&&(t.clearGroupAtInfoList(),s=!0,console.log(`${this._name}._clearGroupAtInfoList conversationID:${e} needEmitConversationUpdate:${s}`)),s&&b.emitConversationListUpdate()}_getLocalMessageMaxTime(e){var t;const{conversationID:s}=e,n=this._core.message.messageStore.getLocalMessageList(s),o=Math.max(...n.map((e=>e.time)));let i=(null===(t=null==e?void 0:e.lastMessage)||void 0===t?void 0:t.lastTime)||0;return o>i&&(console.log(`${this._name}._getLocalMessageMaxTime update lastMessageTime from ${i} to ${o}`),i=o),i}_getLocalMessageMaxSequence(e){var t;const{conversationID:s}=e,n=this._core.message.messageStore.getLocalMessageList(s),o=Math.max(...n.map((e=>e.sequence)));let i=(null===(t=null==e?void 0:e.lastMessage)||void 0===t?void 0:t.lastSequence)||0;return o>i&&(console.log(`${this._name}._getLocalMessageMaxSequence update lastMessageSequence from ${i} to ${o}`),i=o),i}_setC2CMessageRead(e,t){return r(this,void 0,void 0,(function*(){try{yield function(e,t){return r(this,void 0,void 0,(function*(){return O("openim.msgreaded",e,t)}))}({C2CMsgReaded:{Cookie:"",C2CMsgReadedItem:[{To_Account:e.replace("C2C",""),LastedMsgTime:t,Receipt:1}]}},this._core),console.log(`${this._name}._setC2CMessageRead ok.`),b.updateUnreadCount(e)}catch(e){throw console.warn(`${this._name}._setC2CMessageRead fail:`,e),e}}))}_setGroupMessageRead(e,t){return r(this,void 0,void 0,(function*(){try{yield function(e,t){return r(this,void 0,void 0,(function*(){const{groupID:s,lastMessageSequence:n}=e;return O("group_open_http_svc.msg_read_report",{GroupId:s,MsgReadedSeq:n},t)}))}({groupID:e.replace("GROUP",""),lastMessageSequence:t},this._core),console.log(`${this._name}._setGroupMessageRead ok.`),b.updateUnreadCount(e)}catch(e){throw console.warn(`${this._name}._setGroupMessageRead fail:`,e),e}}))}},G=new class{constructor(){this._name="PinConversation"}init(e){this._core=e;const{helper:t}=e;t.registerApi("pinConversation",this)}handleConversationPinned(e,t){if(!u(e))return;const{OuterConstant:s}=this._core;let n=!1;e.forEach((e=>{const{Type:o,To_Account:i,GroupId:r}=e;let a;1===o?a=b.getLocalConversation(`${s.CONV_C2C}${i}`):2===o&&(a=b.getLocalConversation(`${s.CONV_GROUP}${r}`)),a&&(console.log(`${this._name}.handleConversationPinned conversationID:${a.conversationID} localPinned:${a.isPinned} remotePinned:${t}`),t&&!a.isPinned&&(a.isPinned=!0,n=!0),!t&&a.isPinned&&(a.isPinned=!1,n=!0))})),n&&b.emitConversationListUpdate(!0)}pinConversation(e){return r(this,void 0,void 0,(function*(){const{OuterConstant:t,common:s}=this._core,{conversationID:n,isPinned:o}=e,i={code:0,data:{conversationID:n}},a=b.getLocalConversation(n);if(a&&a.isPinned===o)return i;if(m(n))return a&&(a.isPinned=o),b.emitConversationListUpdate(!0),i;try{let e=null;h(n)?e={Type:1,To_Account:n.replace(t.CONV_C2C,"")}:p(n)&&(e={Type:2,GroupId:n.replace(t.CONV_GROUP,"")});const c=yield function(e,t){return r(this,void 0,void 0,(function*(){const{fromAccount:s,operationType:n,itemList:o}=e;return O("recentcontact.top",{From_Account:s,OperationType:n,RecentContactItem:o},t)}))}({fromAccount:s.getCurrentUserID(),operationType:!0===o?1:2,itemList:[e]},this._core);if(console.log(`${this._name}.pinConversation ok, conversationID:${n} isPinned:${o}.`),c){if(a)a.isPinned!==o&&(a.isPinned=o);else{const e=new D({conversationID:n,type:h(n)?t.CONV_C2C:t.CONV_GROUP,isPinned:o});b.setLocalConversation(n,e)}b.emitConversationListUpdate(!0)}return i}catch(e){throw console.error(`${this._name}.pinConversation fail:`,e),e}}))}},w=new class{constructor(){this._name="DeleteConversation"}init(e){this._core=e;const{helper:t}=e;t.registerApi("deleteConversation",this)}handleConversationDeleted(e){if(!u(e))return;const{OuterConstant:t}=this._core,s=[];e.forEach((e=>{const{Type:n,Peer_Account:o,GroupId:i}=e;1===n&&s.push(`${t.CONV_C2C}${o}`),2===n&&s.push(`${t.CONV_GROUP}${i}`)})),console.log(`${this._name}.handleConversationDeleted conversationIDList:${s}`),this._deleteLocalConversationList(s)}deleteConversation(e){return r(this,void 0,void 0,(function*(){c(e)&&(console.log(`${this._name}.deleteConversation conversationID:${e}`),yield this._deleteConversation({conversationIDList:[e],flag:C.ONLY_CONVERSATIONID}));const t=Object.assign({},e);t.conversationIDList.length>100&&(t.conversationIDList=t.conversationIDList.slice(0,100)),yield this._deleteConversation(t)}))}_deleteConversation(e){return r(this,void 0,void 0,(function*(){const{conversationIDList:t,clearHistoryMessage:s=!0,flag:n=0}=e;console.log(`${this._name}._deleteConversation conversationIDList:${t} clearHistoryMessage:${s}`);try{const e=yield Promise.all([this._deleteConversationFromLocal(t),this._deleteConversationFromServer(t,s)]),o=[...e[0],...e[1]];if(0===o.length)throw new this._core.helper.ChatError({code:T.CONV_NOT_FOUND});return console.log(`${this._name}._deleteConversation ok.`),{code:0,data:n===C.ONLY_CONVERSATIONID?{conversationID:o[0]}:{conversationIDList:o}}}catch(e){throw console.error(`${this._name}._deleteConversation fail:`,e),e}}))}_deleteConversationFromLocal(e){const{OuterConstant:t}=this._core;return e.filter((e=>{var s;if(!b.hasLocalConversation(e))return!1;const n=null===(s=b.getLocalConversation(e))||void 0===s?void 0:s.type;return n!==t.CONV_GROUP||this._hasLocalGroup(e)?n===t.CONV_SYSTEM&&(this._deleteLocalConversation(e),!0):(this._deleteLocalConversation(e),!0)}))}_deleteConversationFromServer(e,t){return r(this,void 0,void 0,(function*(){const{OuterConstant:s,common:n}=this._core,o={fromAccount:n.getCurrentUserID(),conversationList:[],clearHistoryMessage:t?1:0};if(e.forEach((e=>{var t;if(b.hasLocalConversation(e)){const n=(null===(t=b.getLocalConversation(e))||void 0===t?void 0:t.type)||"",i=e.replace(n,"");n===s.CONV_C2C?o.conversationList.push({To_Account:i,Type:1}):n===s.CONV_GROUP&&this._hasLocalGroup(e)&&o.conversationList.push({ToGroupid:i,Type:2})}})),0===o.conversationList.length)return[];const i=yield function(e,t){return r(this,void 0,void 0,(function*(){const{fromAccount:s,conversationList:n,clearHistoryMessage:o}=e;return O("recentcontact.batch_delete",{From_Account:s,ContactItem:n,ClearRamble:o},t)}))}(o,this._core);if(i){const{ResultItem:e=[]}=i,t=[];return e.length>0&&e.forEach((e=>{if(0===e.ResultCode){const n=1===e.type?`${s.CONV_C2C}${e.To_Account}`:`${s.CONV_GROUP}${e.ToGroupid}`;t.push(n)}})),this._deleteLocalConversationList(t),t}return[]}))}_deleteLocalConversationList(e){let t=!1;e.forEach((e=>{b.hasLocalConversation(e)&&(this._deleteLocalConversation(e,!1),t=!0)})),console.log(`${this._name}._deleteLocalConversationList isUpdate:${t}`),t&&b.emitConversationListUpdate()}_deleteLocalConversation(e,t=!0){const s=b.hasLocalConversation(e);console.log(`${this._name}._deleteLocalConversation conversationID:${e} has:${s}`),s&&(b.deleteLocalConversation(e),this._deleteConversationLocalMessage(e),t&&b.emitConversationListUpdate())}_hasLocalGroup(e){const{OuterConstant:t}=this._core;return!!e.replace(t.CONV_GROUP,"")}_deleteConversationLocalMessage(e){console.log(`${this._name}._deleteConversationLocalMessage conversationID:${e}`),this._core.message.messageStore.deleteConversationMessageList(e)}},N=new class{constructor(){this._name="SetConversationDraft"}init(e){this._core=e;const{helper:t}=e;t.registerApi("setConversationDraft",this)}setConversationDraft(e){return r(this,void 0,void 0,(function*(){const{conversationID:t,draftText:s}=e;if(console.log(`${this._name} conversationID:${t} draftText:${s}`),!b.hasLocalConversation(t))throw new this._core.helper.ChatError({code:T.CONV_NOT_FOUND});const n=b.getLocalConversation(t);return null==n||n.setDraftText(s),b.emitConversationListUpdate(),{code:0,data:{conversation:n}}}))}};function k(e,t,s){return r(this,void 0,void 0,(function*(){const{helper:n,channel:o}=s,i=n.generateProtocolData({servcmd:e,data:t}),r=`${i.head.seq}${e}`;return yield o.sendPacket(i,{requestId:r})}))}var F=new class{constructor(){this._name="SetC2CMessageRemindType"}init(e){this._core=e}set(e,t){return r(this,void 0,void 0,(function*(){e.length>30&&(console.warn(`${this._name}.set userIDList length:${e.length} exceeds limit 30`),e.splice(30));const s=function(){const{MSG_REMIND_ACPT_AND_NOTE:e,MSG_REMIND_DISCARD:t,MSG_REMIND_ACPT_NOT_NOTE:s}=i.core.OuterConstant;return{[e]:0,[t]:1,[s]:2}}()[t],n=yield function(e,t){return r(this,void 0,void 0,(function*(){const{userIDList:s,receiveMessageOption:n}=e;return k("openim.set_c2c_peer_mute_notifications",{Peer_Account:s,Mute_Notifications:n},t)}))}({userIDList:e,receiveMessageOption:s},this._core),{ErrorList:o=[]}=n||{},a=[];o.forEach((t=>{const{Peer_Account:s,ErrorCode:n}=t;a.push({userID:s,code:n});const o=e.indexOf(s);o>-1&&e.splice(o,1)}));const c=[],u=[],{OuterConstant:l}=this._core;return e.forEach((e=>{u.push(`${l.CONV_C2C}${e}`),c.push({userID:e})})),b.patchMessageRemindType(u,t),{code:0,data:{successUserIDList:c,failureUserIDList:a}}}))}},$=new class{constructor(){this._name="SetGroupMessageRemindType"}init(e){this._core=e}set(e,t){return r(this,void 0,void 0,(function*(){const{common:s,OuterConstant:n}=this._core;yield function(e,t){return r(this,void 0,void 0,(function*(){const{groupID:s,userID:n,receiveMessageOption:o}=e;return k("group_open_http_svc.modify_group_member_info",{GroupId:s,Member_Account:n,MsgFlag:o},t)}))}({groupID:e,userID:s.getCurrentUserID(),receiveMessageOption:t},this._core);const o=`${n.CONV_GROUP}${e}`;return b.patchMessageRemindType([o],t),{code:0,data:{groupID:e,messageRemindType:t}}}))}},x=new class{constructor(){this._name="SetMessageRemindType"}init(e){this._core=e;const{helper:t}=e;t.registerApi("setMessageRemindType",this)}setMessageRemindType(e){return r(this,void 0,void 0,(function*(){const t="setMessageRemindType",{groupID:s,userIDList:n,messageRemindType:o}=e,{helper:i}=this._core;console.log(`${this._name}.${t} groupID:${s} userIDList:${null==n?void 0:n.length} messageRemindType:${o}`);try{if(!a(s))return yield $.set(s,o);if(!a(n))return yield F.set(n,o);throw new i.ChatError({functionName:t,message:"userIDList or groupID is required"})}catch(e){const s=new i.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,s),s}}))}},j=new class{init(e){console.log("ConversationAction.init"),this._core=e,L.init(e),A.init(e),U.init(e),R.init(e),P.init(e),G.init(e),w.init(e),N.init(e),x.init(e);const{notificationCenter:t,InnerEvent:{MESSAGE_PUSH:s,DESTROY:n}}=this._core,{InnerEventSubType:{CONV_MODIFIED:o}}=t;t.subscribeInnerEvent(s,o,this._handleConversationModified,this),t.subscribeInnerEvent(n,this._dispose,this)}handleLoginSuccess(){L.handleLoginSuccess()}_handleConversationModified(e){const{RecentContactMod:t=[]}=e;t.forEach((e=>{const{PushType:t}=e;if(t===M.CONV_DELETED){const{RecentContactList:t}=e.RecentContactDeleteItem;w.handleConversationDeleted(t)}if(t===M.CONV_PINED){const{RecentContactList:t}=e.RecentContactTopItem;G.handleConversationPinned(t,!0)}if(t===M.CONV_UNPINED){const{RecentContactList:t}=e.RecentContactTopItem;G.handleConversationPinned(t,!1)}}))}_dispose(){const{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t,DESTROY:s}}=this._core,{InnerEventSubType:{CONV_MODIFIED:n}}=e;e.unSubscribeInnerEvent(t,n,this._handleConversationModified,this),e.unSubscribeInnerEvent(s,this._dispose,this)}},V=new class{init(e){console.log("ReceiveMessageOptions.init"),this._core=e,F.init(e),$.init(e)}};const q=e=>!h(e)&&!p(e)&&!m(e),H={getConversationProfile:[{key:"conversationID",required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!q(e)||"conversationID is invalid."}],setMessageRead:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!q(e)||"conversationID is invalid."}},pinConversation:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!q(e)||"conversationID is invalid."},isPinned:{required:!0,rules:["boolean"],allowEmpty:!1}},deleteConversation:[{key:"options",required:!0,rules:["string","object"],allowEmpty:!1,customValidator:e=>{if(!c(e)&&!l(e))return"options is String or Object.";if(c(e)&&q(e))return"conversationID is invalid.";if(l(e)){if(!u(e.conversationIDList))return"conversationIDList is not Array.";if(0===e.conversationIDList.length)return"conversationIDList is empty.";if(e.conversationIDList.some((e=>{if(q(e))return!0})))return"conversationIDList includes invalid conversationID.";if(e.clearHistoryMessage&&"boolean"!=typeof e.clearHistoryMessage)return"clearHistoryMessage is not Boolean."}return!0}}],setConversationDraft:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>!(!h(e)&&!p(e))||"conversationID is invalid."},draftText:{required:!0,rules:["string"],allowEmpty:!0}}},B={getConversationList:!0,getConversationProfile:!0,getTotalUnreadCount:!0,setMessageRead:!0,pinConversation:!0,deleteConversation:!0,setConversationDraft:!0,setMessageRemindType:!0};var K=new class{install(e){i.init(e),j.init(e),V.init(e),b.init(e),e.helper.registerValidateConfig({auth:B,params:H})}handleLoginSuccess(){j.handleLoginSuccess()}};const Y=new class{init(e){this.core=e}},W=["Type","Name","Introduction","Notification","FaceUrl","Owner_Account","CreateTime","InfoSeq","LastInfoTime","LastMsgTime","MemberNum","MaxMemberNum","ApplyJoinOption","NextMsgSeq","ShutUpAllMember","InviteJoinOption"],z=["Type","Name","Introduction","Notification","FaceUrl","CreateTime","Owner_Account","LastInfoTime","LastMsgTime","NextMsgSeq","MemberNum","MaxMemberNum","ApplyJoinOption","InviteJoinOption"],J=["Role","JoinTime","MsgFlag","MsgSeq"],X=["Role","JoinTime","MsgSeq","MsgFlag","NameCard"],Q="notStart",Z="resolved",ee="rejected",te=["Owner","Admin","Member"],se=["Role","JoinTime","NameCard","ShutUpUntil","OnlineStatus"],ne=2687,oe=e=>e===Y.core.OuterConstant.GRP_PUBLIC,ie=e=>e===Y.core.OuterConstant.GRP_AVCHATROOM,re=({type:e,groupID:t})=>e===Y.core.OuterConstant.GRP_COMMUNITY||`${t}`.startsWith("@TGS#_")&&!`${t}`.includes("@TOPIC#_"),ae=e=>void 0===e,ce=e=>"function"==typeof Array.isArray?Array.isArray(e):"array"===(e=>{var t;return null===(t=Object.prototype.toString.call(e).match(/^\[object (.*)\]$/))||void 0===t?void 0:t[1].toLowerCase()})(e),ue=e=>ce(e)||(e=>null!==e&&"object"==typeof e)(e),le=(e,t,s,n)=>{if(!ue(e)||!ue(t))return 0;let o=0;const i=Object.keys(t);let r;for(let a=0,c=i.length;a<c;a++)if(r=i[a],!(ae(t[r])||s&&s.includes(r)))if(ue(e[r])&&ue(t[r]))o+=le(e[r],t[r],s,n);else{if(n&&n.includes(t[r]))continue;e[r]!==t[r]&&(e[r]=t[r],o+=1)}return o};function de(e,t){if(!ce(e)||!ce(t))return!1;let s=!1;return t.forEach((({key:t,value:n})=>{const o=e.find((e=>e.key===t));o?o.value!==n&&(o.value=n,s=!0):(e.push({key:t,value:n}),s=!0)})),s}function ge(e){const t=[];if(!e)return t;for(let s=0,n=e.length;s<n;s++){const{Key:n,Value:o}=e[s];t.push({key:n,value:o})}return t}function he(e){const t=[];for(let s=0,n=e.length;s<n;s++){const{key:n,value:o}=e[s];t.push({Key:n,Value:o})}return t}const pe=["groupID","name","avatar","type","introduction","notification","ownerID","selfInfo","createTime","infoSequence","lastInfoTime","lastMessage","nextMessageSeq","memberNum","maxMemberNum","memberList","joinOption","groupCustomField","muteAllMembers","isSupportTopic","inviteOption","_lastRevokedTime"];class me{constructor(e){this.groupID="",this.name="",this.avatar="",this.type="",this.introduction="",this.notification="",this.ownerID="",this.createTime=0,this.selfInfo={messageRemindType:"",joinTime:"",nameCard:"",role:"",userID:"",memberCustomField:void 0,readedSequence:0,excludedUnreadSequenceList:void 0},this.lastMessage={lastTime:0,lastSequence:0,fromAccount:"",messageForShow:""},this.nextMessageSeq=0,this.memberNum=0,this.memberCount=0,this.maxMemberNum=0,this.maxMemberCount=0,this.joinOption="",this.inviteOption="",this.groupCustomField=[],this.muteAllMembers=!1,this.isSupportTopic=!1,this._lastRevokedTime=0,this._initGroup(e)}_initGroup(e){for(const t in e)pe.indexOf(t)<0||("selfInfo"!==t?"isSupportTopic"!==t?("memberNum"===t&&(this.memberCount=e[t]),"maxMemberNum"===t&&(this.maxMemberCount=e[t]),this[t]=e[t]):this.isSupportTopic=1===e[t]:this.updateSelfInfo(e[t]))}updateGroup(e){e.appid=void 0,e.grossTopicNextMsgSeq=void 0,e.selfInfo&&(e.selfInfo.grossTopicReadSeq=void 0);const t=JSON.parse(JSON.stringify(e));var s;t.lastMsgTime&&(this.lastMessage.lastTime=t.lastMsgTime),ae(t.muteAllMembers)||(t.muteAllMembers="On"===t.muteAllMembers),t.groupCustomField&&de(this.groupCustomField,t.groupCustomField),ae(t.memberNum)||(this.memberCount=t.memberNum),ae(t.maxMemberNum)||(this.maxMemberCount=t.maxMemberNum),ae(t.isSupportTopic)||(this.isSupportTopic=null!==(s=t.isSupportTopic)&&("number"==typeof s&&!Number.isNaN(s-0)||"object"==typeof s&&s.constructor===Number)?1===t.isSupportTopic:t.isSupportTopic),le(this,t,["members","errorCode","lastMsgTime","groupCustomField","memberNum","maxMemberNum","isSupportTopic"]),ce(t.members)&&t.members.length>0&&t.members.forEach((e=>{e.userID===this.selfInfo.userID&&le(this.selfInfo,e,["sequence"])}))}updateSelfInfo(e){const{nameCard:t,joinTime:s,role:n,messageRemindType:o,readedSequence:i,excludedUnreadSequenceList:r}=e;le(this.selfInfo,{nameCard:t,joinTime:s,role:n,messageRemindType:o,readedSequence:i,excludedUnreadSequenceList:r},[],["",null,void 0,0,NaN])}setSelfNameCard(e){this.selfInfo.nameCard=e}}var fe=new class{constructor(){this._name="GroupStore",this._groupMap=new Map}init(e){console.log(`${this._name}.init`),this._core=e}hasLocalGroup(e){return this._groupMap.has(e)}getLocalGroup(e){return this._groupMap.get(e)}updateLocalGroup(e){let t;e.forEach((e=>{t=e.groupID,this.hasLocalGroup(t)?this.getLocalGroup(t).updateGroup(e):this._groupMap.set(t,new me(e))}));const s=this._core.store.get("login").userId;for(const[,e]of this._groupMap)e.selfInfo.userID=s,"Owner"===e.selfInfo.role&&(e.ownerID=s)}deleteLocalGroup(e){this._groupMap.delete(e)}clearLocalGroup(){this._groupMap.clear()}getLocalGroupList(){return[...this._groupMap.values()]}emitGroupListUpdate(){var e;const t=this.getLocalGroupList();this._emitEvent({name:null===(e=this._core)||void 0===e?void 0:e.OuterEvent.GROUP_LIST_UPDATED,data:t})}_emitEvent(e){var t;null===(t=this._core)||void 0===t||t.notificationCenter.emitOuterEvent(e.name,e)}reset(){this.clearLocalGroup()}};function ve(e,t){var s={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(s[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(n=Object.getOwnPropertySymbols(e);o<n.length;o++)t.indexOf(n[o])<0&&Object.prototype.propertyIsEnumerable.call(e,n[o])&&(s[n[o]]=e[n[o]])}return s}function _e(e,t,s,n){return new(s||(s=Promise))((function(o,i){function r(e){try{c(n.next(e))}catch(e){i(e)}}function a(e){try{c(n.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(r,a)}c((n=n.apply(e,t||[])).next())}))}function Ie(e,t,s){return _e(this,void 0,void 0,(function*(){const{helper:n,channel:o}=s,i=n.generateProtocolData({servcmd:e,data:t}),r=`${i.head.seq}${e}`;return yield o.sendPacket(i,{requestId:r})}))}"function"==typeof SuppressedError&&SuppressedError;const ye=function(e){return{code:0,data:e||{}}};var Ee=new class{constructor(){this._name="GetGroupList",this._pagingStatus=Q,this.PAGING_GRP_COUNT_LIMIT=200}init(e){this._core=e;const{helper:t}=e;t.registerApi("getGroupList",this)}handleLoginSuccess(){this._syncGroupList()}getGroupList(){return _e(this,void 0,void 0,(function*(){if(console.log(`${this._name}.getGroupList pagingStatus:${this._pagingStatus}`),this._pagingStatus===ee||this._pagingStatus===Q)return this._syncGroupList().then((()=>{const e=fe.getLocalGroupList();return ye({groupList:e,isSyncCompleted:this._isSyncCompleted()})})).catch((e=>{throw console.error(`${this._name}.getGroupList fail:`,e),e}));const e=fe.getLocalGroupList();return console.log(`${this._name}.getGroupList return group count:${e.length}`),ye({groupList:e,isSyncCompleted:this._isSyncCompleted()})}))}_syncGroupList(){return _e(this,void 0,void 0,(function*(){this._pagingStatus===Q&&fe.clearLocalGroup();const e=this.PAGING_GRP_COUNT_LIMIT,t=[];try{yield this._pagingGetGroupList({limit:e,offset:0,groupList:t}),this._pagingStatus=Z,this._groupListTreeShaking(t),fe.updateLocalGroup(t);const s=fe.getLocalGroupList().length;return console.log(`${this._name}._syncGroupList ok, count:${s}`),fe.emitGroupListUpdate(),t}catch(e){throw this._pagingStatus=ee,console.error(`${this._name}._syncGroupList fail:`,e),e}}))}_pagingGetGroupList(e){return _e(this,void 0,void 0,(function*(){const{isCommunityRelay:t=!1,groupList:s}=e;let n,{limit:o,offset:i}=e;const r=[...W];t&&(n=this._core.OuterConstant.GRP_COMMUNITY,r.push("AtInfoList"));try{const e=yield function(e,t){return _e(this,void 0,void 0,(function*(){const{type:s,limit:n,offset:o,memberAccount:i,responseFilter:r}=e;return Ie(s?"million_group_open_http_svc.get_joined_group_list":"group_open_http_svc.get_joined_group_list",{Limit:n,Offset:o,Member_Account:i,ResponseFilter:r,SupportTopic:0,NeedAppDefineData:1},t)}))}({type:n,limit:o,offset:i,memberAccount:this._core.store.get("login").userId,responseFilter:{GroupBaseInfoFilter:r,SelfInfoFilter:[...J]}},this._core),{GroupIdList:a=[],TotalCount:c=0}=e||{},u=this._convertGroupKey(a);s.push(...u);const l=i+o,d=!(c>l),g=`offset:${i} limit:${o} total:${c} isCompleted:${d} current:${s.length} isCommunityRelay:${t}`;return console.log(`${this._name}._pagingGetGroupList ok. ${g}`),t?d?s:(i=l,this._pagingGetGroupList({isCommunityRelay:!0,limit:o,offset:i,groupList:s})):d?(console.log(`${this._name}._pagingGetGroupList start to get community list`),i=0,this._pagingGetGroupList({isCommunityRelay:!0,limit:o,offset:i,groupList:s})):(i=l,this._pagingGetGroupList({limit:o,offset:i,groupList:s}))}catch(e){if(10018===e.ErrorCode)return console.warn(`${this._name}._pagingGetGroupList response size exceeds the limit, request count:${o}`),o=50,this._pagingGetGroupList({isCommunityRelay:t,limit:o,offset:i,groupList:s});if(t)return 11e3===e.code&&console.log(`${this._name}._pagingGetGroupList ok. community unavailable`),s;throw e}}))}_groupListTreeShaking(e){const t=new Map([...fe.getLocalGroupList()]);for(let s=0,n=e.length;s<n;s++)t.delete(e[s].groupID);const s=[...t.keys()];for(let e=0,t=s.length;e<t;e++)fe.deleteLocalGroup(s[e])}_isSyncCompleted(){return this._pagingStatus===Z}_convertGroupKey(e){const t=[];for(let s=0,n=e.length;s<n;s++){const{AppDefinedData:n,ApplyJoinOption:o,CreateTime:i,FaceUrl:r,GroupId:a,Introduction:c,InviteJoinOption:u,LastInfoTime:l,LastMsgTime:d,MaxMemberNum:g,MuteAllMember:h,Name:p,NextMsgSeq:m,Notification:f,Owner_Account:v,ShutUpAllMember:_,Type:I,SelfInfo:y}=e[s],E=ge(n),S=this._convertSelfInfo(y);t.push({groupCustomField:E,joinOption:o,createTime:i,avatar:r,groupID:a,introduction:c,inviteOption:u,lastInfoTime:l,lastMsgTime:d,maxMemberNum:g,muteAllMember:h,name:p,nextMessageSeq:m,notification:f,ownerID:v,shutUpAllMember:_,type:I,selfInfo:S})}return t}_convertSelfInfo(e){const{JoinTime:t,MsgFlag:s,MsgSeq:n,NoUnreadSeqList:o,Role:i}=e;return{joinTime:t,messageRemindType:s,readedSequence:n,excludedUnreadSequenceList:o,role:i}}},Se=new class{constructor(){this._name="CreateGroup"}init(e){this._core=e;const{helper:t}=e;t.registerApi("createGroup",this)}createGroup(e){return _e(this,void 0,void 0,(function*(){var t;this._preCheckParams(e),console.log(`${this._name}.createGroup options:`,e);try{const{store:s,helper:n}=this._core,o=yield function(e,t){return _e(this,void 0,void 0,(function*(){const{name:s,type:n,groupID:o,introduction:i,notification:r,avatar:a,maxMemberNum:c,joinOption:u,inviteOption:l,memberList:d,groupCustomField:g,isSupportTopic:h}=e;return Ie("group_open_http_svc.create_group",{Name:s,Type:n,GroupId:o,Introduction:i,Notification:r,FaceUrl:a,MaxMemberCount:c,ApplyJoinOption:u,InviteJoinOption:l,MemberList:d,AppDefinedData:g,SupportTopic:h,webPushFlag:1},t)}))}(Object.assign(Object.assign({},e),{ownerID:s.get("login").userId}),this._core),{GroupId:i,OverJoinedGroupLimit_Account:r=[]}=o||{};if(console.log(`${this._name}.createGroup ok, groupType:${e.type} groupID:${i} overLimitUserIDList:${r}`),n.isEmpty(e.memberList)||n.isEmpty(r)||(e.memberList=null===(t=e.memberList)||void 0===t?void 0:t.filter((e=>r.includes(e.userID)))),this._notNeedUpdateLocalGroup(e))return ye({group:new me(e)});fe.updateLocalGroup([Object.assign(Object.assign({},e),{groupID:i})]),this._sendCustomMessage(i,e.type);const a=fe.getLocalGroup(i);return fe.emitGroupListUpdate(),ye({group:a})}catch(e){throw console.error(`${this._name}.createGroup fail:`,e),e}}))}_preCheckParams(e){const{type:t,groupID:s}=e,n=!this._core.helper.isEmpty(s);if(!function(){const{GRP_PUBLIC:e,GRP_WORK:t,GRP_MEETING:s,GRP_AVCHATROOM:n,GRP_COMMUNITY:o}=Y.core.OuterConstant;return[e,t,s,n,o]}().includes(t))throw new this._core.helper.ChatError({code:2600});if(!re({type:t})){if(n&&re({groupID:s}))throw new this._core.helper.ChatError({code:2602});ae(e.isSupportTopic)||(e.isSupportTopic=void 0)}if(this._canIUseMemberList(t)||ae(e.memberList)||(e.memberList=void 0),this._canIUseJoinOption(t)||ae(e.joinOption)||(e.joinOption=void 0),this._canIUseTopic(e)&&(e.isSupportTopic=!0===e.isSupportTopic?1:0),re({type:t})&&n&&!re({groupID:s}))throw new this._core.helper.ChatError({code:2602})}_canIUseMemberList(e){return!ie(e)}_canIUseJoinOption(e){return oe(e)||re({type:e})}_canIUseTopic(e){const{type:t,isSupportTopic:s}=e;return re({type:t})&&ae(s)}_notNeedUpdateLocalGroup(e){const{type:t,isSupportTopic:s}=e,{OuterConstant:n}=this._core;return t===n.GRP_AVCHATROOM||t===n.GRP_COMMUNITY&&1===s}_sendCustomMessage(e,t){var s,n,o,i,r,a;const{OuterConstant:c}=this._core;let u="Create Group",l=0;t===c.GRP_COMMUNITY&&(u="Create Community",l=1);const d={to:e,conversationType:"GROUP",payload:{data:JSON.stringify({businessID:"group_create",content:u,cmd:l,opUser:this._core.store.get("login").userId,version:4})}},g=null===(o=null===(n=null===(s=this._core)||void 0===s?void 0:s.message)||void 0===n?void 0:n.messageFactory)||void 0===o?void 0:o.createCustomMessage(d);null===(a=null===(r=null===(i=this._core)||void 0===i?void 0:i.message)||void 0===r?void 0:r.messageSender)||void 0===a||a.sendMessage(g,{})}},Ce=new class{constructor(){this._name="DismissGroup"}init(e){this._core=e;const{helper:t}=e;t.registerApi("dismissGroup",this)}dismissGroup(e){return _e(this,void 0,void 0,(function*(){console.log(`${this._name}.dismissGroup groupID:${e}`);try{return yield function(e,t){return _e(this,void 0,void 0,(function*(){return Ie("group_open_http_svc.destroy_group",{GroupId:e},t)}))}(e,this._core),console.log(`${this._name}.dismissGroup ok.`),fe.deleteLocalGroup(e),fe.emitGroupListUpdate(),ye({groupID:e})}catch(e){throw console.error(`${this._name}.dismissGroup fail:`,e),e}}))}},Me=new class{constructor(){this._name="GetGroupProfile"}init(e){this._core=e;const{helper:t}=e;t.registerApi("getGroupProfile",this)}getGroupProfile(e){return _e(this,void 0,void 0,(function*(){const{groupID:t,groupCustomFieldFilter:s}=e,n={groupIDList:[t],responseFilter:{GroupBaseInfoFilter:[...W],AppDefinedDataFilter_Group:s,MemberInfoFilter:[...X]}};try{const e=yield this.getGroupProfileAdvance(n),{successGroupList:s,failureGroupList:o}=e;if(o.length>0)throw o[0];let i;return!fe.hasLocalGroup(t)&&ie(s[0].type)?i=new me(s[0]):(fe.updateLocalGroup(s),i=fe.getLocalGroup(t)),console.log(`${this._name}.getGroupProfile ok.`),ye({group:i})}catch(e){throw console.error(`${this._name}.getGroupProfile fail:`,e),e}}))}getGroupProfileAdvance(e){return _e(this,void 0,void 0,(function*(){const{groupIDList:t}=e,s=t.filter((e=>!re({groupID:e}))),n=t.filter((e=>re({groupID:e})));s.length>50&&(s.length=50),n.length>50&&(n.length=50);const o=yield Promise.all([this._getGroupProfileAdvance(Object.assign(Object.assign({},e),{groupIDList:s})),this._getGroupProfileAdvance(Object.assign(Object.assign({},e),{groupIDList:n,isCommunityProfile:!0}))]),i=[],r=[];return o.forEach((e=>{i.push(...e.successGroupList),r.push(...e.failureGroupList)})),{successGroupList:i,failureGroupList:r}}))}_getGroupProfileAdvance(e){return _e(this,void 0,void 0,(function*(){const{isCommunityProfile:t=!1}=e,s=ve(e,["isCommunityProfile"]);if(0===s.groupIDList.length)return{successGroupList:[],failureGroupList:[]};try{const e=yield function(e,t){return _e(this,void 0,void 0,(function*(){const{groupIDList:s,responseFilter:n}=e;return Ie("group_open_http_svc.get_group_self_member_info",{GroupIdList:s,ResponseFilter:n},t)}))}(s,this._core),{GroupInfo:t=[]}=e||{},n=this._convertGroupProfileKey(t),o=n.filter((e=>ae(e.errorCode)||0===e.errorCode)),i=n.filter((e=>e.errorCode&&0!==e.errorCode)).map((e=>({code:e.errorCode,message:e.errorInfo,data:{groupID:e.groupID}})));return console.log(`${this._name}._getGroupProfileAdvance ok, groupID:${s.groupIDList.join(",")}`),{successGroupList:o,failureGroupList:i}}catch(e){if(t)return{successGroupList:[],failureGroupList:[]};throw e}}))}_convertGroupProfileKey(e){const t=[];for(let s=0,n=e.length;s<n;s++){const{AppDefinedData:n,ApplyJoinOption:o,CreateTime:i,FaceUrl:r,GroupId:a,InfoSeq:c,Introduction:u,InviteJoinOption:l,LastInfoTime:d,LastMsgTime:g,MaxMemberNum:h,MemberNum:p,MuteAllMember:m,Name:f,NextMsgSeq:v,Notification:_,Owner_Account:I,ShutUpAllMember:y,ShutUpUntil:E,Type:S,MemberList:C,ErrorCode:M,ErrorInfo:T}=e[s],D=ge(n),b=this._convertMembers(C);t.push({groupCustomField:D,joinOption:o,createTime:i,avatar:r,groupID:a,infoSequence:c,introduction:u,inviteOption:l,lastInfoTime:d,lastMsgTime:g,maxMemberNum:h,memberNum:p,muteAllMember:m,name:f,nextMessageSeq:v,notification:_,ownerID:I,shutUpAllMember:y,muteUntil:E,type:S,members:b,errorCode:M,errorInfo:T})}return t}_convertMembers(e){const t=[];for(let s=0,n=e.length;s<n;s++){const{AppMemberDefinedData:n,JoinTime:o,Member_Account:i,MsgFlag:r,MsgSeq:a,NameCard:c,Role:u}=e[s],l=ge(n);t.push({memberCustomField:l,joinTime:o,userID:i,messageRemindType:r,sequence:a,nameCard:c,role:u})}return t}},Te=new class{constructor(){this._name="JoinGroup"}init(e){this._core=e;const{helper:t}=e;t.registerApi("joinGroup",this)}joinGroup(e){return _e(this,void 0,void 0,(function*(){const{groupID:t}=e;try{if(fe.hasLocalGroup(t))try{return yield Me.getGroupProfile({groupID:t}),ye({status:this._core.OuterConstant.JOIN_STATUS_SUCCESS})}catch(s){return console.warn(`${this._name}.joinGroup ${t} was unjoined, start to join!`),fe.deleteLocalGroup(t),yield this._applyJoinGroup(e)}return yield this._applyJoinGroup(e)}catch(e){throw console.error(`${this._name}.joinGroup fail:`,e),e}}))}_applyJoinGroup(e){return _e(this,void 0,void 0,(function*(){const t=Object.assign({},e),s=yield function(e,t){return _e(this,void 0,void 0,(function*(){const{groupID:s,applyMessage:n,historyMessageFlag:o}=e;return Ie("group_open_http_svc.apply_join_group",{GroupId:s,ApplyMsg:n,HugeGroupHistoryMsgFlag:o},t)}))}(t,this._core),{JoinedStatus:n,LongPollingKey:o,StartSeq:i,HugeGroupFlag:r,AVChatRoomKey:a,RspMsgList:c}=s||{},u=`groupID:${e.groupID} joinedStatus:${n} longPollingKey:${o} startSeq:${i} avChatRoomFlag:${r} canGetAVChatRoomHistoryMsg:false, historyMsgCount:${(null==c?void 0:c.length)||0}`;console.log(`${this._name}._applyJoinGroup ok, ${u}`);const{OuterConstant:l}=this._core;if(n===l.JOIN_STATUS_WAIT_APPROVAL)return{code:0,data:{status:l.JOIN_STATUS_WAIT_APPROVAL}};if(n===l.JOIN_STATUS_SUCCESS)return this._handleJoinResult({group:new me({groupID:e.groupID}),avChatRoomFlag:r,longPollingKey:o,startSeq:i,avChatRoomKey:a,messageList:c});throw new this._core.helper.ChatError({code:2660})}))}_handleJoinResult(e){const{group:t,avChatRoomFlag:s}=e;return 1===s?{}:(fe.updateLocalGroup([t]),fe.emitGroupListUpdate(),ye({status:this._core.OuterConstant.JOIN_STATUS_SUCCESS,group:t}))}},De=new class{constructor(){this._name="QuitGroup"}init(e){this._core=e;const{helper:t}=e;t.registerApi("quitGroup",this)}quitGroup(e){return _e(this,void 0,void 0,(function*(){if(console.log(`${this._name}.quitGroup groupID:${e}`),!fe.hasLocalGroup(e))throw new this._core.helper.ChatError({code:2623});try{return yield function(e,t){return _e(this,void 0,void 0,(function*(){return Ie("group_open_http_svc.quit_group",{GroupId:e},t)}))}(e,this._core),console.log(`${this._name}.quitGroup ok.`),fe.deleteLocalGroup(e),fe.emitGroupListUpdate(),ye({groupID:e})}catch(e){throw console.error(`${this._name}.quitGroup fail:`,e),e}}))}},be=new class{constructor(){this._name="SearchGroup"}init(e){this._core=e;const{helper:t}=e;t.registerApi("searchGroupByID",this)}searchGroupByID(e){return _e(this,void 0,void 0,(function*(){console.log(`${this._name}.searchGroupByID groupID:${e}`);try{const t=yield function(e,t){return _e(this,void 0,void 0,(function*(){return Ie("group_open_http_svc.get_group_public_info",{GroupIdList:[e],GroupBasePublicInfoFilter:[...z]},t)}))}(e,this._core),{GroupInfo:s=[]}=t||{},{AppDefinedData:n=[],ApplyJoinOption:o,CreateTime:i,FaceUrl:r,Introduction:a,InviteJoinOption:c,MaxMemberNum:u,MemberNum:l,Name:d,Owner_Account:g,Type:h,ErrorCode:p,ErrorInfo:m}=s[0];if(0!==p)throw new this._core.helper.ChatError({code:p,message:m});console.log(`${this._name}.searchGroupByID ok.`);const f=ge(n),v=new me({groupID:e,name:d,avatar:r,introduction:a,joinOption:o,inviteOption:c,maxMemberNum:u,memberNum:l,type:h,ownerID:g,createTime:i,groupCustomField:f});return ye({group:v})}catch(e){throw console.error(`${this._name}.searchGroupByID fail:`,e),e}}))}},Oe=new class{constructor(){this._name="UpdateGroupProfile"}init(e){this._core=e;const{helper:t}=e;t.registerApi("updateGroupProfile",this)}updateGroupProfile(e){return _e(this,void 0,void 0,(function*(){const{groupID:t}=e;let s=fe.getLocalGroup(t);if(s){const{type:t}=s;this._canIUseJoinOption(t)||ae(e.joinOption)||(console.warn(`${this._name}.updateGroupProfile joinOption is unavailable for Work/Meeting/AVChatRoom`),e.joinOption=void 0)}ae(e.muteAllMembers)||(e.muteAllMembers=!0===e.muteAllMembers?"On":"Off");try{return yield function(e,t){return _e(this,void 0,void 0,(function*(){const{groupID:s,name:n,avatar:o,introduction:i,notification:r,muteAllMembers:a,joinOption:c,inviteOption:u,groupCustomField:l}=e;return Ie("group_open_http_svc.modify_group_base_info",{GroupId:s,Name:n,FaceUrl:o,Introduction:i,Notification:r,ShutUpAllMember:a,ApplyJoinOption:c,InviteJoinOption:u,AppDefinedData:l?he(l):void 0},t)}))}(e,this._core),console.log(`${this._name}.updateGroupProfile groupID:${t} ok.`),s?(s.updateGroup(e),fe.emitGroupListUpdate()):s=new me(e),ye({group:s})}catch(e){throw console.error(`${this._name}.updateGroupProfile groupID:${t} fail:`,e),e}}))}_canIUseJoinOption(e){return oe(e)||re({type:e})}},Le=new class{constructor(){this._name="ChangeGroupOwner"}init(e){this._core=e;const{helper:t}=e;t.registerApi("changeGroupOwner",this)}changeGroupOwner(e){return _e(this,void 0,void 0,(function*(){const t="changeGroupOwner",{groupID:s,newOwnerID:n}=e,o=fe.getLocalGroup(s),{store:i,helper:r,OuterConstant:a}=this._core;if((null==o?void 0:o.type)===a.GRP_AVCHATROOM)throw new r.ChatError({functionName:t,code:2620});if(n===i.get("login").userId)throw new r.ChatError({functionName:t,code:2621});console.log(`${this._name}.${t} groupID:${s} newOwnerID:${n}`);try{return yield function(e,t){return _e(this,void 0,void 0,(function*(){const{groupID:s,newOwnerID:n}=e;return Ie("group_open_http_svc.change_group_owner",{GroupId:s,NewOwner_Account:n},t)}))}(e,this._core),console.log(`${this._name}.${t} ok.`),o.ownerID=n,fe.emitGroupListUpdate(),ye({group:o})}catch(e){const s=new r.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,s),s}}))}},Ae=new class{constructor(){this._name="GetGroupOnlineMemberCount",this._onlineMemberCountMap=new Map}init(e){this._core=e;const{helper:t}=e;t.registerApi("getGroupOnlineMemberCount",this)}getGroupOnlineMemberCount(e){return _e(this,void 0,void 0,(function*(){const t="getGroupOnlineMemberCount",s=fe.hasLocalGroup(e);if(console.log(`${this._name}.${t} groupID:${e} isAVChatRoom:false hasGroup:${s}`),!s)return ye({memberCount:0});const n=Date.now();if(this._onlineMemberCountMap.has(e)){const t=this._onlineMemberCountMap.get(e),{lastReqTime:s=0,memberCount:o=0}=t||{};if(n-s<=6e4)return ye({memberCount:o})}try{const s=yield function(e,t){return _e(this,void 0,void 0,(function*(){return Ie("group_open_http_svc.get_online_member_num",{GroupId:e},t)}))}(e,this._core),{OnlineMemberNum:n=0}=s||{};return this._onlineMemberCountMap.set(e,{lastReqTime:Date.now(),memberCount:n}),console.log(`${this._name}.${t} ok. groupID:${e} memberCount:${n}`),ye({memberCount:n})}catch(e){const s=new this._core.helper.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,s),s}}))}},Ue=new class{init(e){console.log("GroupAction.init"),Ee.init(e),Se.init(e),Ce.init(e),Te.init(e),De.init(e),be.init(e),Me.init(e),Oe.init(e),Le.init(e),Ae.init(e)}handleLoginSuccess(){Ee.handleLoginSuccess()}};function Re(e,t,s){return _e(this,void 0,void 0,(function*(){const{helper:n,channel:o}=s,i=n.generateProtocolData({servcmd:e,data:t}),r=`${i.head.seq}${e}`;return yield o.sendPacket(i,{requestId:r})}))}var Pe=new class{constructor(){this._name="GetGroupApplicationList"}init(e){this._core=e;const{helper:t}=e;t.registerApi("getGroupApplicationList",this)}getGroupApplicationList(){return _e(this,void 0,void 0,(function*(){const e="getGroupApplicationList";try{const t=yield Promise.all([this._getGroupApplicationList(),this._getGroupApplicationList({type:this._core.OuterConstant.GRP_COMMUNITY})]);console.log(`${this._name}.${e} ok.`,t);const s=this._handleGroupApplicationResult([...t[0],...t[1]]);return ye({applicationList:s})}catch(t){const s=new this._core.helper.ChatError({functionName:e,code:null==t?void 0:t.errorCode,message:null==t?void 0:t.errorInfo});throw console.error(`${this._name}.${e} fail:`,s),s}}))}_getGroupApplicationList(e){return _e(this,void 0,void 0,(function*(){const{type:t,startTime:s=0,limit:n=20}=e||{},o=yield function(e,t){return _e(this,void 0,void 0,(function*(){const{type:s,startTime:n,limit:o,handleAccount:i}=e;return Re(re({type:s})?"million_group_open_http_svc.get_pendency":"group_open_http_svc.get_pendency",{StartTime:n,Limit:o,Handle_Account:i},t)}))}({type:t,startTime:s,limit:n,handleAccount:this._core.store.get("login").userId},this._core),{NextStartTime:i=0,PendencyList:r=[]}=o;if(0===i)return r;const a=yield this._getGroupApplicationList(Object.assign(Object.assign({},e),{startTime:i}));return[...r,...a]}))}_handleGroupApplicationResult(e){const t=[];return e.forEach((e=>{const s=this._convertApplicationData(e),{handled:n}=s,o=ve(s,["handled"]);0===n&&t.push(o)})),t}_convertApplicationData(e){const{Handled:t,AddTime:s,ApplyInviteMsg:n,Authentication:o,FromUserNickName:i,From_Account:r,GroupId:a,GroupName:c,PendencyType:u,To_Account:l}=e;return{handled:t,messageKey:s,applicant:r,applicantNick:i,groupID:a,groupName:c,authentication:o,applicationType:u,userID:l,note:n}}},Ge=new class{constructor(){this._name="HandleGroupApplication"}init(e){this._core=e;const{helper:t}=e;t.registerApi("handleGroupApplication",this)}handleGroupApplication(e){return _e(this,void 0,void 0,(function*(){const t="handleGroupApplication",{application:s}=e,n=this._handleParams(e);try{2===(null==s?void 0:s.applicationType)?yield function(e,t){return _e(this,void 0,void 0,(function*(){const{groupID:s,handleAction:n,handleMessage:o,applicant:i,authentication:r,invitee:a}=e;return Re(re({groupID:s})?"million_group_open_http_svc.handle_invite_join_permission_group":"group_open_http_svc.handle_invite_join_permission_group",{GroupId:s,HandleMsg:n,ApprovalMsg:o,Applicant_Account:i,Authentication:r,Invited_Account:a},t)}))}(n,this._core):yield function(e,t){return _e(this,void 0,void 0,(function*(){const{groupID:s,handleAction:n,handleMessage:o,applicant:i,authentication:r,messageKey:a}=e;return Re(re({groupID:s})?"million_group_open_http_svc.handle_apply_join_group":"group_open_http_svc.handle_apply_join_group",{GroupId:s,HandleMsg:n,ApprovalMsg:o,Applicant_Account:i,Authentication:r,MsgKey:a},t)}))}(n,this._core),console.log(`${this._name}.${t} ok.`);const e=fe.getLocalGroup(n.groupID);return ye({group:e})}catch(e){const s=new this._core.helper.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,s),s}}))}_handleParams(e){var t;const{handleAction:s,handleMessage:n,message:o,application:i}=e;let r,a,c,u,l;if(o){const{payload:e}=o||{};r=e.operatorID,a=null===(t=e.groupProfile)||void 0===t?void 0:t.groupID,c=e.authentication,u=e.messageKey}else r=(null==i?void 0:i.applicant)||"",a=(null==i?void 0:i.groupID)||"",c=(null==i?void 0:i.authentication)||"",u=(null==i?void 0:i.messageKey)||0;return 2===(null==i?void 0:i.applicationType)&&(l=i.userID),{handleAction:s,handleMessage:n,applicant:r,invitee:l,groupID:a,authentication:c,messageKey:u}}},we=new class{init(e){console.log("GroupApplication.init"),Pe.init(e),Ge.init(e)}};let Ne=class{constructor(e){this.userID="",this.avatar="",this.nick="",this.role="",this.joinTime="",this.nameCard="",this.muteUntil=0,this.memberCustomField=[],this.isOnline=!1,this.updateMember(e)}updateMember(e){ae(e.muteTime)||(this.muteUntil=Math.floor((Date.now()+1e3*e.muteTime)/1e3)),ae(e.onlineStatus)||(this.isOnline="Online"===e.onlineStatus);const t=[null,void 0,"",0,NaN];e.memberCustomField&&de(this.memberCustomField,e.memberCustomField),le(this,e,["memberCustomField","marks","onlineStatus","muteTime"],t)}};function ke(e,t,s){return _e(this,void 0,void 0,(function*(){const{helper:n,channel:o}=s,i=n.generateProtocolData({servcmd:e,data:t}),r=`${i.head.seq}${e}`;return yield o.sendPacket(i,{requestId:r})}))}function Fe(e,t){return _e(this,void 0,void 0,(function*(){const{groupID:s,userID:n,muteTime:o,role:i,nameCard:r,memberCustomField:a}=e;let c;return a&&(c=he(a)),ke("group_open_http_svc.modify_group_member_info",{GroupId:s,Member_Account:n,ShutUpTime:o,Role:i,NameCard:r,AppMemberDefinedData:c},t)}))}var $e=new class{constructor(){this._name="GetGroupMemberList"}init(e){this._core=e;const{helper:t}=e;t.registerApi("getGroupMemberList",this)}getGroupMemberList(e){return _e(this,void 0,void 0,(function*(){const t="getGroupMemberList",{groupID:s,offset:n=0,count:o=100,role:i="",filter:r=""}=e;console.log(`${this._name}.${t} groupID:${s} offset:${n} count:${o} role:${i} filter:${r}`);const a=fe.getLocalGroup(s);a&&ie(a.type);const c=o>100?100:o,u={groupID:s,offset:n,limit:c,memberRoleFilter:te.includes(i)?[i]:void 0,memberInfoFilter:se};try{const e=yield function(e,t){return _e(this,void 0,void 0,(function*(){const{groupID:s,offset:n,limit:o,memberRoleFilter:i,memberInfoFilter:r}=e;return ke("group_open_http_svc.get_group_member_info",{GroupId:s,Offset:n,Limit:o,MemberRoleFilter:i,MemberInfoFilter:r},t)}))}(u,this._core),{MemberList:o,MemberNum:i,Next:r}=e||{};if(console.log(`${this._name}.${t} ok, totalMemberCount:${i} next:${r}`),a&&(a.memberNum=i),!ce(o)||0===o.length)return ye({memberList:[],offset:0});let l=n+c;re({groupID:s})&&(l=this._core.helper.isEmpty(r)?0:r),o.length<c&&(l=0);let d=this._convertMemberInfo(o);d=yield this._patchAvatarAndNick(d);const g=this._generateGroupMember(d);return ye({memberList:g,offset:l})}catch(e){const s=new this._core.helper.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,s),s}}))}_convertMemberInfo(e){const t=[];for(let s=0,n=e.length;s<n;s++){const{AppMemberDefinedData:n,JoinTime:o,Member_Account:i,OnlineStatus:r,Role:a,ShutUpUntil:c}=e[s],u=ge(n);t.push({userID:i,joinTime:o,onlineStatus:r,role:a,muteUntil:c,memberCustomField:u})}return t}_patchAvatarAndNick(e){return _e(this,void 0,void 0,(function*(){var t;const s=e.map((e=>e.userID)),n=yield null===(t=this._core.user.userProfile)||void 0===t?void 0:t.getUserProfile({userIDList:s}),o=(null==n?void 0:n.data)||[],i=new Map(o.map((e=>[e.userID,e])));return e.forEach((e=>{if(i.has(e.userID)){const{nick:t="",avatar:s=""}=i.get(e.userID);e.nick=t,e.avatar=s}})),e}))}_generateGroupMember(e){const t=[];for(let s=0,n=e.length;s<n;s++){const n=new Ne(e[s]);t.push(n)}return t}},xe=new class{constructor(){this._name="GetGroupMemberProfile"}init(e){this._core=e;const{helper:t}=e;t.registerApi("getGroupMemberProfile",this)}getGroupMemberProfile(e){return _e(this,void 0,void 0,(function*(){const t="getGroupMemberProfile",{groupID:s,userIDList:n,memberCustomFieldFilter:o}=e,i=fe.getLocalGroup(s),{helper:r}=this._core;if(i&&ie(i.type))throw new r.ChatError({functionName:t,code:ne});n.length>50&&(console.warn(`${this._name}.${t} userIDList length:${n.length} exceeds limit 50`),n.splice(50));try{const e=yield function(e,t){return _e(this,void 0,void 0,(function*(){const{groupID:s,userIDList:n,memberInfoFilter:o,memberCustomFieldFilter:i}=e;return ke("group_open_http_svc.get_specified_group_member_info",{GroupId:s,Member_List_Account:n,MemberInfoFilter:o,AppDefinedDataFilter_GroupMember:i},t)}))}({groupID:s,userIDList:n,memberCustomFieldFilter:o,memberInfoFilter:[...se]},this._core);console.log(`${this._name}.${t} ok.`);const{MemberList:i}=e||{};if(!ce(i)||0===i.length)return ye({memberList:[]});let r=this._convertMemberInfo(i);r=yield this._getMemberAvatarAndNick(r);const a=this._generateGroupMember(r);return ye({memberList:a})}catch(e){const s=new r.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,s),s}}))}_convertMemberInfo(e){const t=[];for(let s=0,n=e.length;s<n;s++){const{AppMemberDefinedData:n,JoinTime:o,Member_Account:i,OnlineStatus:r,Role:a,ShutUpUntil:c}=e[s],u=ge(n);t.push({userID:i,joinTime:o,onlineStatus:r,role:a,muteUntil:c,memberCustomField:u})}return t}_getMemberAvatarAndNick(e){return _e(this,void 0,void 0,(function*(){var t;const s=e.map((e=>e.userID)),n=yield null===(t=this._core.user.userProfile)||void 0===t?void 0:t.getUserProfile({userIDList:s}),o=(null==n?void 0:n.data)||[],i=new Map(o.map((e=>[e.userID,e])));return e.forEach((e=>{if(i.has(e.userID)){const{nick:t="",avatar:s=""}=i.get(e.userID);e.nick=t,e.avatar=s}})),e}))}_generateGroupMember(e){const t=[];for(let s=0,n=e.length;s<n;s++){const n=new Ne(e[s]);t.push(n)}return t}},je=new class{constructor(){this._name="AddGroupMember"}init(e){this._core=e;const{helper:t}=e;t.registerApi("addGroupMember",this)}addGroupMember(e){return _e(this,void 0,void 0,(function*(){const t="addGroupMember",{groupID:s,userIDList:n}=e,o=fe.getLocalGroup(s),{helper:i}=this._core;if(o&&ie(o.type))throw new i.ChatError({functionName:t,code:2661});const r=n.map((e=>({Member_Account:e})));try{const e=yield function(e,t){return _e(this,void 0,void 0,(function*(){const{groupID:s,userIDList:n}=e;return ke("group_open_http_svc.add_group_member",{GroupId:s,MemberList:n},t)}))}({groupID:s,userIDList:r},this._core),{MemberList:n=[]}=e||{},{failureUserIDList:i,successUserIDList:a,existedUserIDList:c,overLimitUserIDList:u}=this._handleResult(n);return console.log(`${this._name}.${t} groupID:${s} ok, successUserIDList:${a} failureUserIDList:${i} existedUserIDList:${c} overLimitUserIDList:${u}`),ye({failureUserIDList:i,successUserIDList:a,existedUserIDList:c,overLimitUserIDList:u,group:o})}catch(e){const s=new i.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,s),s}}))}_handleResult(e){const t=[],s=[],n=[],o=[];return e.forEach((e=>{const{Result:i,Member_Account:r}=e;0===i?t.push(r):1===i?s.push(r):2===i?n.push(r):4===i&&o.push(r)})),{failureUserIDList:t,successUserIDList:s,existedUserIDList:n,overLimitUserIDList:o}}},Ve=new class{constructor(){this._name="DeleteGroupMember"}init(e){this._core=e;const{helper:t}=e;t.registerApi("deleteGroupMember",this)}deleteGroupMember(e){return _e(this,void 0,void 0,(function*(){const t="deleteGroupMember",{groupID:s,userIDList:n}=e,o=fe.getLocalGroup(s),{helper:i}=this._core;if(ae(o))throw new i.ChatError({functionName:t,code:2603});if(ie(o.type))throw new i.ChatError({functionName:t,code:3122});n.length>20&&(console.warn(`${this._name}.${t} userIDList length:${n.length} exceeds limit 20`),n.splice(20));try{return yield function(e,t){return _e(this,void 0,void 0,(function*(){const{groupID:s,userIDList:n,reason:o}=e;return ke("group_open_http_svc.delete_group_member",{GroupId:s,MemberToDel_Account:n,Reason:o},t)}))}({groupID:s,userIDList:n},this._core),console.log(`${this._name}.${t} ok, groupID:${s} userIDList length:${n.length}`),ye({group:o,userIDList:n})}catch(e){const s=new i.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,s),s}}))}},qe=new class{constructor(){this._name="SetGroupMemberMuteTime"}init(e){this._core=e;const{helper:t}=e;t.registerApi("setGroupMemberMuteTime",this)}setGroupMemberMuteTime(e){return _e(this,void 0,void 0,(function*(){const t="setGroupMemberMuteTime",{helper:s}=this._core;this._preCheckSettingMuteParams(e);try{yield Fe(e,this._core);const{groupID:s,userID:n,muteTime:o}=e;console.log(`${this._name}.${t} ok, groupID:${s} userID:${n} muteTime:${o}`);const i=fe.getLocalGroup(s),r=new Ne({userID:n,muteTime:o});return ye({group:i,member:r})}catch(e){const n=new s.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,n),n}}))}_preCheckSettingMuteParams(e){const{userID:t}=e,{store:s,helper:n}=this._core;if(t===s.get("login").userId)throw new n.ChatError({functionName:"setGroupMemberMuteTime",code:2685})}},He=new class{constructor(){this._name="SetGroupMemberRole"}init(e){this._core=e;const{helper:t}=e;t.registerApi("setGroupMemberRole",this)}setGroupMemberRole(e){return _e(this,void 0,void 0,(function*(){const t="setGroupMemberRole",{helper:s}=this._core;this._preCheckSettingRoleParams(e);try{yield Fe(e,this._core);const{groupID:s,userID:n,role:o}=e;console.log(`${this._name}.${t} ok, groupID:${s} userID:${n} role:${o}`);const i=fe.getLocalGroup(s),r=new Ne({userID:n,role:o});return ye({group:i,member:r})}catch(e){const n=new s.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,n),n}}))}_preCheckSettingRoleParams(e){var t;const{groupID:s,userID:n,role:o}=e,{store:i,helper:r,OuterConstant:a}=this._core,c=fe.getLocalGroup(s);if((null===(t=null==c?void 0:c.selfInfo)||void 0===t?void 0:t.role)!==a.GRP_MBR_ROLE_OWNER)throw new r.ChatError({functionName:"setGroupMemberRole",code:2681});if(n===i.get("login").userId)throw new r.ChatError({functionName:"setGroupMemberRole",code:2684});const u=[...te];if(re({groupID:s})&&u.push(a.GRP_MBR_ROLE_CUSTOM),!u.includes(o))throw new r.ChatError({functionName:"setGroupMemberRole",code:2683})}},Be=new class{constructor(){this._name="SetGroupMemberNameCard"}init(e){this._core=e;const{helper:t}=e;t.registerApi("setGroupMemberNameCard",this)}setGroupMemberNameCard(e){return _e(this,void 0,void 0,(function*(){const t="setGroupMemberNameCard",{helper:s}=this._core;this._preCheckSettingNameCardParams(e);try{yield Fe(e,this._core);const{groupID:s,userID:n,nameCard:o}=e;console.log(`${this._name}.${t} ok, groupID:${s} userID:${n} nameCard:${o}`);const i=fe.getLocalGroup(s),r=new Ne({userID:n,nameCard:o});return ye({group:i,member:r})}catch(e){const n=new s.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,n),n}}))}_preCheckSettingNameCardParams(e){const{groupID:t}=e,{helper:s}=this._core,n=fe.getLocalGroup(t);if(ie(null==n?void 0:n.type))throw new s.ChatError({functionName:"setGroupMemberNameCard",code:ne})}},Ke=new class{constructor(){this._name="SetGroupMemberCustomField"}init(e){this._core=e;const{helper:t}=e;t.registerApi("setGroupMemberCustomField",this)}setGroupMemberCustomField(e){return _e(this,void 0,void 0,(function*(){const t="setGroupMemberCustomField",{helper:s}=this._core;this._preCheckSettingCustomFiledParams(e);try{yield Fe(e,this._core);const{groupID:s,userID:n,memberCustomField:o}=e;console.log(`${this._name}.${t} ok, groupID:${s} userID:${n} memberCustomField:${JSON.stringify(o)}`);const i=fe.getLocalGroup(s),r=new Ne({userID:n,memberCustomField:o});return ye({group:i,member:r})}catch(e){const n=new s.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,n),n}}))}_preCheckSettingCustomFiledParams(e){const{groupID:t}=e,{helper:s}=this._core,n=fe.getLocalGroup(t);if(ie(null==n?void 0:n.type))throw new s.ChatError({functionName:"setGroupMemberCustomField",code:ne})}},Ye=new class{constructor(){this._name="MarkGroupMemberList"}init(e){this._core=e;const{helper:t}=e;t.registerApi("markGroupMemberList",this)}markGroupMemberList(e){return _e(this,void 0,void 0,(function*(){const t="markGroupMemberList",{helper:s}=this._core,{groupID:n,markType:o,enableMark:i,userIDList:r=[]}=e;r.length>500&&(console.warn(`${this._name}.${t} userIDList length:${r.length} exceeds limit 500`),r.splice(500));const a=r.map((e=>({Member_Account:e,Marks:[o]}))),c=i?1:2;try{const e=yield function(e,t){return _e(this,void 0,void 0,(function*(){const{groupID:s,operationType:n,memberList:o}=e;return ke("group_open_avchatroom_http_svc.modify_user_info",{GroupId:s,CommandType:n,MemberList:o},t)}))}({groupID:n,memberList:a,operationType:c},this._core),{MemberList:s=[]}=e||{},{successUserIDList:o,failureUserIDList:i}=this._handleResult(s,r);return console.log(`${this._name}.${t} ok, groupID:${n} success count:${o.length} fail count:${i.length}`),ye({successUserIDList:o,failureUserIDList:i})}catch(e){const n=new s.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,n),n}}))}_handleResult(e,t){const s=[],n=[];return e.length===t.length?(s.push(...t),{successUserIDList:s,failureUserIDList:n}):(t.forEach((t=>{e.find((e=>e.Member_Account===t))?s.push(t):n.push(t)})),{successUserIDList:s,failureUserIDList:n})}},We=new class{init(e){console.log("GroupMember.init"),$e.init(e),xe.init(e),je.init(e),Ve.init(e),qe.init(e),He.init(e),Be.init(e),Ke.init(e),Ye.init(e)}},ze=new class{init(e){this._core=e}};function Je(e,t,s){return _e(this,void 0,void 0,(function*(){const{helper:n,channel:o}=s,i=n.generateProtocolData({servcmd:e,data:t}),r=`${i.head.seq}${e}`;return yield o.sendPacket(i,{requestId:r})}))}var Xe=new class{constructor(){this._name="AttributesDataHandler",this._groupAttributesCache=new Map,this._groupAttributesCacheValuesCopy={}}init(e){this._core=e;const{helper:t,constants:s}=e;t.registerWorkflowStep(s.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,s.WORKFLOW_STEP.GROUP_ATTRIBUTE_CACHE_CLEAR,this.clearLocalMainSequence,this)}clearLocalMainSequence(){this._groupAttributesCache.forEach((e=>{e.localMainSequence=0}))}isGroupAttributesUpdated(e){const{elements:{newGroupProfile:t}}=e,{helper:s}=this._core;return!ae(t)&&!s.isEmpty(t.groupAttributeOption)}handleGroupAttributesUpdated(e){const{groupID:t,groupAttributeOption:s}=e,{serverMainSequence:n,groupAttributeList:o=[],operation:i}=s;console.log(`${this._name}.handleGroupAttributesUpdated groupID:${t} operation:${i}`),ae(i)||(this.refreshGroupAttributesCache({groupID:t,serverMainSequence:n,groupAttributeList:o,operation:i}),this.emitGroupAttributesUpdated(t))}initGroupAttributesCache(e){const{groupID:t,avChatRoomKey:s}=e;this._groupAttributesCache.set(t,{lastUpdateTime:0,localMainSequence:0,serverMainSequence:0,avChatRoomKey:s,values:new Map}),console.log(`${this._name}.initGroupAttributesCache. groupID:${t} avChatRoomKey:${s}`)}hasGroupAttributesCache(e){return this._groupAttributesCache.has(e)}getGroupAttributesCache(e){return this.hasGroupAttributesCache(e)||this.initGroupAttributesCache({groupID:e}),this._groupAttributesCache.get(e)}refreshGroupAttributesCache(e){const{groupID:t,serverMainSequence:s,groupAttributeList:n,operation:o}=e;if(this.hasGroupAttributesCache(t)){const e=this.getGroupAttributesCache(t),{localMainSequence:i}=e;5!==o&&s-i!=1||(e.serverMainSequence=s,e.localMainSequence=s,e.lastUpdateTime=Date.now(),this._updateGroupAttributesCacheValues({groupAttributes:e,groupAttributeList:n,operation:o})),s-i>1&&(e.serverMainSequence=s),this._groupAttributesCache.set(t,e),console.log(`${this._name}.refreshGroupAttributesCache. operation:${o} localMainSequence:${i} serverMainSequence:${s}`)}}_updateGroupAttributesCacheValues(e){const{groupAttributes:t,groupAttributeList:s=[],operation:n}=e;3!==n?4!==n?(1===n&&t.values.clear(),s.forEach((e=>{const{key:s,value:n,sequence:o}=e;t.values.set(s,{value:n,sequence:o})}))):s.forEach((e=>{t.values.delete(e.key)})):t.values.clear()}getGroupAttributesCacheValues(e){var t;const{groupID:s,keyList:n=[]}=e,o={};if(this.hasGroupAttributesCache(s)){const{values:e}=this.getGroupAttributesCache(s);if(0===n.length){for(const s of e.keys())o[s]=(null===(t=e.get(s))||void 0===t?void 0:t.value)||"";return o}return n.forEach((t=>{var s;e.has(t)&&(o[t]=(null===(s=e.get(t))||void 0===s?void 0:s.value)||"")})),o}return o}saveGroupAttributesCacheValuesCopy(e){this._groupAttributesCacheValuesCopy=this.getGroupAttributesCacheValues({groupID:e})}emitGroupAttributesUpdated(e){var t;const s=this.getGroupAttributesCacheValues({groupID:e}),{updatedKeyList:n,deletedKeyList:o}=this._computeValuesChangedData(s);console.log(`${this._name}.emitGroupAttributesUpdated update count:${n.length}, delete count:${o.length}`),0===n.length&&0===o.length||this._emitEvent({name:null===(t=this._core)||void 0===t?void 0:t.OuterEvent.GROUP_ATTRIBUTES_UPDATED,data:{groupID:e,groupAttributes:s,updatedKeyList:n,deletedKeyList:o}})}_computeValuesChangedData(e){const t=[],s=[];return Object.keys(e).forEach((s=>{e[s]!==this._groupAttributesCacheValuesCopy[s]&&t.push(s)})),Object.keys(this._groupAttributesCacheValuesCopy).forEach((t=>{ae(e[t])&&s.push(t)})),this._groupAttributesCacheValuesCopy={},{updatedKeyList:t,deletedKeyList:s}}_emitEvent(e){var t;null===(t=this._core)||void 0===t||t.notificationCenter.emitOuterEvent(e.name,e)}convertKeyValueMapToList(e){const t=[];return Object.keys(e).forEach((s=>{t.push({key:s,value:e[s]})})),t}},Qe=new class{constructor(){this._name="InitGroupAttributes"}init(e){this._core=e;const{helper:t}=e;t.registerApi("initGroupAttributes",this)}initGroupAttributes(e){return _e(this,void 0,void 0,(function*(){const t="initGroupAttributes",{groupID:s,groupAttributes:n}=e,{serverMainSequence:o,avChatRoomKey:i}=Xe.getGroupAttributesCache(s),r=Xe.convertKeyValueMapToList(n);try{const e=yield function(e,t){return _e(this,void 0,void 0,(function*(){const{groupID:s,mainSequence:n,groupAttributeList:o,avChatRoomKey:i}=e;return Je("group_open_http_svc.set_group_attr",{GroupId:s,AttrMainSeq:n,GroupAttr:o,BytesKey:i,AttrControl:["RaceConflict"]},t)}))}({groupID:s,avChatRoomKey:i,groupAttributeList:r,mainSequence:o},this._core),{AttrMainSeq:a,GroupAttr:c}=e||{};console.log(`${this._name}.${t} ok. groupID:${s} serverMainSequence:${a}`);const u=c.map((e=>{const{Key:t,seq:s}=e;return{key:t,value:n[t],sequence:s}}));return Xe.saveGroupAttributesCacheValuesCopy(s),Xe.refreshGroupAttributesCache({groupID:s,serverMainSequence:a,groupAttributeList:u,operation:1}),Xe.emitGroupAttributesUpdated(s),ye({groupAttributes:n})}catch(e){const s=new this._core.helper.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,s),s}}))}},Ze=new class{constructor(){this._name="SetGroupAttributes"}init(e){this._core=e;const{helper:t}=e;t.registerApi("setGroupAttributes",this)}setGroupAttributes(e){return _e(this,void 0,void 0,(function*(){const t="setGroupAttributes",{groupID:s,groupAttributes:n}=e,{serverMainSequence:o,avChatRoomKey:i,values:r}=Xe.getGroupAttributesCache(s),a=Xe.convertKeyValueMapToList(n).map((e=>{var t;const{key:s,value:n}=e;return{key:s,value:n,seq:(null===(t=r.get(e.key))||void 0===t?void 0:t.sequence)||0}}));try{const e=yield function(e,t){return _e(this,void 0,void 0,(function*(){const{groupID:s,mainSequence:n,groupAttributeList:o,avChatRoomKey:i}=e;return Je("group_open_http_svc.modify_group_attr",{GroupId:s,AttrMainSeq:n,GroupAttr:o,BytesKey:i,AttrControl:["RaceConflict"]},t)}))}({groupID:s,avChatRoomKey:i,groupAttributeList:a,mainSequence:o},this._core),{AttrMainSeq:r,GroupAttr:c}=e||{};console.log(`${this._name}.${t} ok. groupID:${s} serverMainSequence:${r}`);const u=c.map((e=>{const{Key:t,seq:s}=e;return{key:t,value:n[t],sequence:s}}));return Xe.saveGroupAttributesCacheValuesCopy(s),Xe.refreshGroupAttributesCache({groupID:s,serverMainSequence:r,groupAttributeList:u,operation:2}),Xe.emitGroupAttributesUpdated(s),ye({groupAttributes:n})}catch(e){const s=new this._core.helper.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,s),s}}))}},et=new class{constructor(){this._name="DeleteGroupAttributes"}init(e){this._core=e;const{helper:t}=e;t.registerApi("deleteGroupAttributes",this)}deleteGroupAttributes(e){return _e(this,void 0,void 0,(function*(){const t="deleteGroupAttributes",{groupID:s,keyList:n=[]}=e;try{let e;e=0===n.length?yield this._clearGroupAttributes(s):yield this._deleteGroupAttributes(s,n);const{resultList:o,serverMainSequence:i,operation:r,groupAttributeList:a}=e||{};return console.log(`${this._name}.${t} ok. groupID:${s} operation: ${r}`),Xe.saveGroupAttributesCacheValuesCopy(s),Xe.refreshGroupAttributesCache({groupID:s,serverMainSequence:i,groupAttributeList:a,operation:r}),Xe.emitGroupAttributesUpdated(s),ye({keyList:o})}catch(e){const s=new this._core.helper.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,s),s}}))}_deleteGroupAttributes(e,t){return _e(this,void 0,void 0,(function*(){const{serverMainSequence:s,avChatRoomKey:n,values:o}=Xe.getGroupAttributesCache(e),i=[],r=[];t.forEach((e=>{if(o.has(e)){const{sequence:t=0}=o.get(e)||{};r.push({key:e,seq:t}),i.push(e)}}));const a=yield function(e,t){return _e(this,void 0,void 0,(function*(){const{groupID:s,mainSequence:n,groupAttributeList:o,avChatRoomKey:i}=e;return Je("group_open_http_svc.delete_group_attr",{GroupId:s,AttrMainSeq:n,GroupAttr:o,BytesKey:i,AttrControl:["RaceConflict"]},t)}))}({groupID:e,avChatRoomKey:n,groupAttributeList:r,mainSequence:s},this._core),{AttrMainSeq:c}=a||{};return{resultList:i,serverMainSequence:c,groupAttributeList:r,operation:4}}))}_clearGroupAttributes(e){return _e(this,void 0,void 0,(function*(){const{serverMainSequence:t,avChatRoomKey:s,values:n}=Xe.getGroupAttributesCache(e),o=[...n.keys()],i=yield function(e,t){return _e(this,void 0,void 0,(function*(){const{groupID:s,mainSequence:n,avChatRoomKey:o}=e;return Je("group_open_http_svc.clear_group_attr",{GroupId:s,AttrMainSeq:n,BytesKey:o,AttrControl:["RaceConflict"]},t)}))}({groupID:e,avChatRoomKey:s,mainSequence:t},this._core),{AttrMainSeq:r}=i||{};return{resultList:o,serverMainSequence:r,operation:3}}))}},tt=new class{constructor(){this._name="GetGroupAttributes"}init(e){this._core=e;const{helper:t}=e;t.registerApi("getGroupAttributes",this)}getGroupAttributes(e){return _e(this,void 0,void 0,(function*(){const t="getGroupAttributes",{groupID:s}=e,{avChatRoomKey:n,lastUpdateTime:o,localMainSequence:i,serverMainSequence:r}=Xe.getGroupAttributesCache(s);if(Date.now()-o>=3e4||i<r)try{yield this.getGroupAttributesFromServer({groupID:s,avChatRoomKey:n});const o=Xe.getGroupAttributesCacheValues(e);return console.log(`${this._name}.${t} from server. groupID:${s}`),ye({groupAttributes:o})}catch(e){const s=new this._core.helper.ChatError({functionName:t,code:null==e?void 0:e.errorCode,message:null==e?void 0:e.errorInfo});throw console.error(`${this._name}.${t} fail:`,s),s}const a=Xe.getGroupAttributesCacheValues(e);return console.log(`${this._name}.${t} from cache. groupID:${s}`),ye({groupAttributes:a})}))}getGroupAttributesFromServer(e){return _e(this,void 0,void 0,(function*(){const{groupID:t,avChatRoomKey:s}=e,n=ae(s)?0:1,o=yield function(e,t){return _e(this,void 0,void 0,(function*(){const{groupID:s,groupType:n,avChatRoomKey:o}=e;return Je("group_open_attr_http_svc.get_group_attr",{GroupId:s,GroupType:n,Key:o},t)}))}({groupID:t,avChatRoomKey:s,groupType:n},this._core),{AttrMainSeq:i,GroupAttrAry:r}=o||{};if(console.log(`${this._name}._getGroupAttributesFromServer ok. groupID:${t} serverMainSequence:${i}`),!ae(i)){const e=r.map((e=>{const{key:t,value:s,seq:n}=e;return{key:t,value:s,sequence:n}}));Xe.refreshGroupAttributesCache({groupID:t,serverMainSequence:i,groupAttributeList:e,operation:5})}}))}},st=new class{init(e){console.log("GroupAttribute.init"),Qe.init(e),Ze.init(e),et.init(e),tt.init(e),Xe.init(e)}isGroupAttributesUpdated(e){return Xe.isGroupAttributesUpdated(e)}handleGroupAttributesUpdated(e){const{to:t,elements:{newGroupProfile:s}}=e,{groupAttributeOption:n}=s,{serverMainSequence:o,withChangedAttributeInfo:i}=n,{localMainSequence:r}=Xe.getGroupAttributesCache(t),a=o-r;if(console.log(`GroupAttribute.handleGroupAttributesUpdated groupID:${t} withChangedAttributeInfo:${i} diffSequence:${a}`),0!==a)if(Xe.saveGroupAttributesCacheValuesCopy(t),1!==i||1!==a){if(Xe.hasGroupAttributesCache(t)){const{avChatRoomKey:e}=Xe.getGroupAttributesCache(t);tt.getGroupAttributesFromServer({groupID:t,avChatRoomKey:e}).then((()=>{Xe.emitGroupAttributesUpdated(t)})).catch((()=>{}))}}else Xe.handleGroupAttributesUpdated({groupID:t,groupAttributeOption:n})}};const nt={required:!0,rules:["string"],allowEmpty:!1},ot={required:!0,rules:["number"],allowEmpty:!1},it={required:!0,rules:["array"],allowEmpty:!1},rt={required:!0,rules:["object"],allowEmpty:!1},at={createGroup:{name:nt,type:nt},dismissGroup:[Object.assign({key:"groupID"},nt)],joinGroup:{groupID:nt,applyMessage:{required:!1,rules:["string"],allowEmpty:!0}},quitGroup:[Object.assign({key:"groupID"},nt)],searchGroupByID:[Object.assign({key:"groupID"},nt)],getGroupProfile:{groupID:nt,groupCustomFieldFilter:{required:!1,rules:["array"],allowEmpty:!0}},updateGroupProfile:{groupID:nt,muteAllMembers:{required:!1,rules:["boolean"],allowEmpty:!1}},changeGroupOwner:{groupID:nt,newOwnerID:nt},getGroupOnlineMemberCount:[Object.assign({key:"groupID"},nt)],handleGroupApplication:{handleAction:nt},getGroupMemberList:{groupID:nt},getGroupMemberProfile:{groupID:nt,userIDList:it,memberCustomFieldFilter:{required:!1,rules:["array"],allowEmpty:!0}},addGroupMember:{groupID:nt,userIDList:it},deleteGroupMember:{groupID:nt,userIDList:it},setGroupMemberMuteTime:{groupID:nt,userID:it,muteTime:Object.assign(Object.assign({},ot),{customValidator:e=>!(e<0)||"muteTime must be a non-negative number."})},setGroupMemberRole:{groupID:nt,userID:nt,role:nt},setGroupMemberNameCard:{groupID:nt,userID:{required:!1,rules:["string"],allowEmpty:!1},nameCard:nt},setGroupMemberCustomField:{groupID:nt,userID:{required:!1,rules:["string"],allowEmpty:!1},memberCustomField:it},markGroupMemberList:{groupID:nt,markType:Object.assign(Object.assign({},ot),{customValidator:e=>!(e<1e3)||"markType must be greater than or equal to 1000."}),enableMark:{required:!0,rules:["boolean"],allowEmpty:!1},userIDList:it},initGroupAttributes:{groupID:nt,groupAttributes:rt},setGroupAttributes:{groupID:nt,groupAttributes:rt},deleteGroupAttributes:{groupID:nt,keyList:Object.assign(Object.assign({},it),{allowEmpty:!0})},getGroupAttributes:{groupID:nt,keyList:Object.assign(Object.assign({},it),{allowEmpty:!0})}},ct={getGroupList:!0,createGroup:!0,dismissGroup:!0,joinGroup:!0,quitGroup:!0,searchGroupByID:!0,getGroupProfile:!0,updateGroupProfile:!0,changeGroupOwner:!0,getGroupOnlineMemberCount:!0,getGroupApplicationList:!0,handleGroupApplication:!0,getGroupMemberList:!0,getGroupMemberProfile:!0,addGroupMember:!0,deleteGroupMember:!0,setGroupMemberMuteTime:!0,setGroupMemberRole:!0,setGroupMemberNameCard:!0,setGroupMemberCustomField:!0,markGroupMemberList:!0,initGroupAttributes:!0,setGroupAttributes:!0,getGroupAttributes:!0,deleteGroupAttributes:!0};var ut=new class{install(e){this._core=e,Y.init(e),fe.init(e),Ue.init(e),we.init(e),We.init(e),ze.init(e),st.init(e),e.helper.registerValidateConfig({auth:ct,params:at});const{notificationCenter:t,InnerEvent:s}=e;t.subscribeInnerEvent(s.LOGIN,this.handleLoginSuccess,this),t.subscribeInnerEvent(s.DESTROY,this._dispose,this)}handleLoginSuccess(){Ue.handleLoginSuccess()}_dispose(){const{notificationCenter:e,InnerEvent:t}=this._core;fe.reset(),e.unSubscribeInnerEvent(t.LOGIN,this.handleLoginSuccess,this),e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};function lt(e,t,s,n){return new(s||(s=Promise))((function(o,i){function r(e){try{c(n.next(e))}catch(e){i(e)}}function a(e){try{c(n.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(r,a)}c((n=n.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const dt=new class{init(e){this.core=e}},gt="C2C",ht="GROUP",pt=20;function mt(e){return lt(this,void 0,void 0,(function*(){var t,s;const{messageList:n,conversationID:o}=e,i=null===(t=dt.core.store.get("conversation"))||void 0===t?void 0:t.conversationMap;let r=null===(s=i.get(o))||void 0===s?void 0:s.peerReadTime;if(!r){const e=o.replace(gt,""),t=yield function(e){return lt(this,void 0,void 0,(function*(){const t={To_Account:e};return dt.core.common.buildAndSendPacket({servcmd:"openim.get_peer_read_time",data:t})}))}([e]);if(t){const{ReadTime:e}=t;r=null==e?void 0:e[0],i.has(o)&&(i.get(o).peerReadTime=r)}}n.forEach((e=>{e.time<=r&&!e.isPeerRead&&"out"===e.flow&&(e.isPeerRead=!0)}))}))}function ft(e){return lt(this,void 0,void 0,(function*(){var t,s;const{store:n,message:o,user:i}=dt.core,r=null===(t=n.get("conversation"))||void 0===t?void 0:t.conversationMap;if(r.has(e)){const t=null===(s=r.get(e))||void 0===s?void 0:s.userprofile;if(t){const{avatar:s,nick:n}=t;dt.core.message.messageStore.updateNickAndAvatarOfSentMessage({conversationID:e,latestAvatar:s,latestNick:n,isSentByMe:!1})}const{data:n}=(yield i.userProfile.getMyProfile())||{};if(n){const{avatar:t,nick:s}=n;o.messageStore.updateNickAndAvatarOfSentMessage({conversationID:e,latestAvatar:t,latestNick:s,isSentByMe:!0})}}}))}var vt,_t,It;!function(e){e.MSG_TEXT="TIMTextElem",e.MSG_CUSTOM="TIMCustomElem",e.MSG_LOCATION="TIMLocationElem",e.MSG_FACE="TIMFaceElem"}(vt||(vt={})),function(e){e[e.DATA_HAS_EXPIRED=0]="DATA_HAS_EXPIRED",e[e.HAS_MORE_DATA=1]="HAS_MORE_DATA",e[e.NO_MORE_DATA=2]="NO_MORE_DATA"}(_t||(_t={})),function(e){e[e.FORWARD=0]="FORWARD",e[e.BACKWARD=1]="BACKWARD"}(It||(It={}));const yt={ZH_CN:"zh (cmn-Hans-CN)",EN_US:"en-US",YUE_HK:"yue-Hant-HK",JA_JP:"ja-JP",ZH_PY:"zh-PY"},Et="16k_zh-PY",St={[yt.ZH_CN]:"16k_zh",[yt.EN_US]:"16k_en",[yt.YUE_HK]:"16k_yue",[yt.JA_JP]:"16k_ja",[yt.ZH_PY]:Et},Ct=/\.(wav|pcm|ogg-opus|speex|silk|mp3|m4a|aac|amr)/,Mt="@TOPIC#_",Tt={READ:0,UNREAD:1};function Dt(e){return`${e}`.startsWith("@TGS#_")&&`${e}`.includes(Mt)}function bt(e){let t;const{message:s}=dt.core,{conversationID:n,messageID:o}=e;return t=s.messageStore.getLocalMessageList(n).find((e=>e.ID===o)),t||(t=s.messageStore.getSparseMessageList(n).find((e=>e.ID===o))),t}var Ot=new class{constructor(){this._reactionsMap=new Map}init(e){this._core=e;const{helper:t,notificationCenter:s,InnerEvent:{MESSAGE_PUSH:n},InnerEventSubType:{MESSAGE_REACTION_UPDATED:o,MESSAGE_REACTION_UPDATED_SYNC:i}}=e;t.registerApi("addMessageReaction",this),t.registerApi("removeMessageReaction",this),t.registerApi("getMessageReactions",this),t.registerApi("getAllUserListOfMessageReaction",this),s.subscribeInnerEvent(n,o,this._handleReactionUpdated,this),s.subscribeInnerEvent(n,i,this._handleReactionSync,this)}addMessageReaction(e,t){return lt(this,void 0,void 0,(function*(){const{OuterConstant:s,ssoLog:n,helper:o}=this._core;this._validateMessageReactionBusinessCapability();const i=n.createSSOLogData({method:"addMessageReaction"}),{conversationID:r,ID:a,conversationType:c,from:u,to:l,clientSequence:d,random:g,time:h,sequence:p}=e;try{return this._recordMessageReactedByMe(a,t),c===s.CONV_C2C?yield function(e,t){return lt(this,void 0,void 0,(function*(){var s;const{from:n,to:o,clientSequence:i,random:r,time:a,reactionID:c}=e,u={From_Account:n,To_Account:o,MsgKey:`${i}_${r}_${a}`,Reaction:c,Add_Account:[null===(s=t.store.get("login"))||void 0===s?void 0:s.userId]};return dt.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_add",data:u})}))}({from:u,to:l,clientSequence:d,random:g,time:h,reactionID:t},this._core):c===s.CONV_GROUP&&(yield function(e,t){return lt(this,void 0,void 0,(function*(){var s;const{to:n,reactionID:o,sequence:i}=e,r={GroupId:n,MsgSeq:i,Reaction:o,Add_Account:[null===(s=t.store.get("login"))||void 0===s?void 0:s.userId]};return dt.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_add",data:r})}))}({to:l,reactionID:t,sequence:p},this._core)),i.setLogInfo({message:`conversationID:${r} messageID:${a} reactionID:${t}`}).end(),{code:0}}catch(e){this._removeMyReactionRecord(a,t);const{errorCode:s}=e||{},n=new o.ChatError({functionName:"addMessageReaction",code:s});i.setError(n).end(),console.error("addMessageReaction error: ",e)}}))}removeMessageReaction(e,t){return lt(this,void 0,void 0,(function*(){const{OuterConstant:s,ssoLog:n,helper:o}=this._core;this._validateMessageReactionBusinessCapability();const i=n.createSSOLogData({method:"removeMessageReaction"});try{const{conversationID:n,ID:o,conversationType:r,from:a,to:c,clientSequence:u,random:l,time:d,sequence:g}=e;return this._removeMyReactionRecord(o,t),r===s.CONV_C2C?yield function(e,t){return lt(this,void 0,void 0,(function*(){var s;const{from:n,to:o,clientSequence:i,random:r,time:a,reactionID:c}=e,u={From_Account:n,To_Account:o,MsgKey:`${i}_${r}_${a}`,Reaction:c,Del_Account:[null===(s=t.store.get("login"))||void 0===s?void 0:s.userId]};return dt.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_del",data:u})}))}({from:a,to:c,clientSequence:u,random:l,time:d,reactionID:t},this._core):r===s.CONV_GROUP&&(yield function(e,t){return lt(this,void 0,void 0,(function*(){var s;const{to:n,reactionID:o,sequence:i}=e,r=null===(s=t.store.get("login"))||void 0===s?void 0:s.userId;let a,c=n;Dt(n)&&(a=n,c=a.split(Mt)[0]);const u={TopicId:a,GroupId:c,MsgSeq:i,Reaction:o,Del_Account:[r]};return dt.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_del",data:u},t)}))}({to:c,reactionID:t,sequence:g},this._core)),i.setLogInfo({message:`conversationID:${n} messageID:${o} reactionID:${t}`}).end(),{code:0}}catch(e){const{errorCode:t}=e||{},s=new o.ChatError({functionName:"removeMessageReaction",code:t});i.setError(s).end(),console.error("removeMessageReaction error: ",e)}}))}getAllUserListOfMessageReaction(e){return lt(this,void 0,void 0,(function*(){this._validateMessageReactionBusinessCapability();const{message:t,reactionID:s,nextSeq:n,count:o}=e,{conversationID:i}=t,{ssoLog:r,helper:a,constants:c}=this._core;try{let e=null;if(e=i.startsWith(c.OuterConstant.CONV_C2C)?yield function(e){return lt(this,void 0,void 0,(function*(){const{message:t,nextSeq:s,reactionID:n,count:o}=e,{from:i,to:r,clientSequence:a,random:c,time:u}=t,l={Reaction:n,NextSeq:s,Count:o,From_Account:i,To_Account:r,MsgKey:`${a}_${c}_${u}`};return dt.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_iterate",data:l})}))}({message:t,reactionID:s,nextSeq:n,count:o}):yield function(e){return lt(this,void 0,void 0,(function*(){const{message:t,nextSeq:s,reactionID:n,count:o}=e,{sequence:i}=t;let r,a=t.to;Dt(t.to)&&(r=t.to,a=r.split(Mt)[0]);const c={Reaction:n,NextSeq:s,TopicId:r,GroupId:a,Count:o,MsgSeq:i};return dt.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_iterate",data:c})}))}({message:t,reactionID:s,nextSeq:n,count:o}),e){const{Reaction_Account:t,NextSeq:s}=e;return{code:0,data:{nextSeq:s,isCompleted:0===n,userList:yield this._getUserProfileList(t)}}}}catch(e){const{errorCode:t}=e||{},s=new a.ChatError({functionName:"getAllUserListOfMessageReaction",code:t});r.createSSOLogData({method:"removeMessageReaction"}).setError(s).end(),console.error("getAllUserListOfMessageReaction error: ",e)}}))}getMessageReactions(e){return lt(this,void 0,void 0,(function*(){const{constants:t}=this._core;this._validateMessageReactionBusinessCapability();const{messageList:s,maxUserCountPerReaction:n}=e,o=s[0];let i=null;const r=new Map,{from:a,to:c,conversationType:u}=o,l=this._generateMessageKeyList(s,r);u===t.OuterConstant.CONV_C2C?i=yield function(e){return lt(this,void 0,void 0,(function*(){const{from:t,to:s,messageKeyList:n,maxUserCountPerReaction:o}=e,i={From_Account:t,To_Account:s,MsgKeyList:n,Count:o};return dt.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_multi_stat",data:i})}))}({from:a,to:c,messageKeyList:l,maxUserCountPerReaction:n}):u===t.OuterConstant.CONV_GROUP&&(i=yield function(e){return lt(this,void 0,void 0,(function*(){let t,{groupId:s,messageSequenceList:n,maxUserCountPerReaction:o}=e;Dt(s)&&(t=s,s=s.split(Mt)[0]);const i={GroupId:s,TopicId:t,MsgSeqList:n,Count:o};return dt.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_multi_stat",data:i})}))}({groupId:c,messageSequenceList:l,maxUserCountPerReaction:n}));const{Results:d=[]}=i||{},g=this._extractUserIDsFromReactionResults(d),h=yield this._getUserProfileMap(g);return{code:0,resultList:d.map((e=>{const{ReactionList:t,MsgSeq:s,MsgKey:n}=e;return{messageID:this._generateMessageID({messageSequence:s,messageKey:n,messageIDMap:r}),reactionList:t.map((e=>{const{Reaction:t,Count:s,Reaction_Account:n,ReactedByMe:o}=e;return{reactionID:t,totalUserCount:s,partialUserList:this._generatePartialUserInfo({userIDList:n,userProfileMap:h}),reactedByMyself:1===o}}))}}))}}))}dispose(){this._reactionsMap.clear()}_extractUserIDsFromReactionResults(e){const t=[];return null==e||e.forEach((e=>{const{ReactionList:s=[]}=e;s.forEach((e=>{e.Reaction_Account&&t.push(...e.Reaction_Account)}))})),t}_getUserProfileList(e){return lt(this,void 0,void 0,(function*(){var t;try{const s=yield null===(t=this._core.user.userProfile)||void 0===t?void 0:t.getUserProfile({userIDList:e});return s?s.data:[]}catch(t){return[]}}))}_getUserProfileMap(e){return lt(this,void 0,void 0,(function*(){const t=new Map;return(yield this._getUserProfileList(e)).forEach((e=>{const{nick:s,avatar:n,userID:o}=e;t.set(o,{nick:s,avatar:n,userID:o})})),t}))}_recordMessageReactedByMe(e,t){const s=`${e}-${t}`;this._reactionsMap.has(s)?this._reactionsMap.get(s).reactedByMe=!0:this._reactionsMap.set(s,{reactedByMe:!0})}_removeMyReactionRecord(e,t){const s=`${e}-${t}`;this._reactionsMap.has(s)&&(this._reactionsMap.get(s).reactedByMe=!1)}_recordMessageReactionInfo(e){const{messageID:t,reactionID:s,reactionInfo:n}=e,o=`${t}-${s}`,i=this._reactionsMap.get(o)||{};this._reactionsMap.set(o,Object.assign(Object.assign({},i),n))}_validateMessageReactionBusinessCapability(){const{helper:e,constants:t}=this._core;if(!e.checkBusinessCapabilityBits("MSG_REACTION"))throw new e.ChatError({functionName:"addMessageReaction",code:t.ERROR_CODE.NO_USE,replacement1:"addMessageReaction"})}_handleReactionUpdated(e){const{MsgReactionNotifyList:t}=e,{notificationCenter:s,constants:n}=this._core;t.forEach((e=>lt(this,void 0,void 0,(function*(){const{C2CMsgInfo:t,GroupMsgInfo:o,MsgReactionSummary:i}=e,{TinyId:r,MsgClientTime:a,MsgRandom:c}=Object.assign(Object.assign({},t),o),u=`${r}-${a}-${c}`,l=this._extractUserIDsFromReactionResults([{ReactionList:i}]),d=yield this._getUserProfileMap(l),g=i.map((e=>{var t;const{Reaction:s,Reaction_Account:n}=e,o=this._generatePartialUserInfo({userIDList:n,userProfileMap:d}),i=n?e.Count:0,r=(null===(t=this._reactionsMap.get(`${u}-${s}`))||void 0===t?void 0:t.reactedByMe)||!1;return this._recordMessageReactionInfo({messageID:u,reactionID:s,reactionInfo:{reactionID:s,totalUserCount:i,partialUserList:o}}),{reactionID:s,totalUserCount:i,partialUserList:o,reactedByMyself:r}}));s.emitOuterEvent(n.OuterEvent.MESSAGE_REACTIONS_UPDATED,{name:n.OuterEvent.MESSAGE_REACTIONS_UPDATED,data:{messageID:u,reactionList:g}})}))))}_handleReactionSync(e){var t;const{notificationCenter:s,constants:n}=this._core,{C2CMsgInfo:o={},GroupMsgInfo:i={},Reaction:r,OperateType:a}=e.MsgReactionNotify,{TinyId:c="",MsgClientTime:u=0,MsgRandom:l=0}=Object.assign(Object.assign({},o),i),d=`${c}-${u}-${l}`,g=`${d}-${r}`;if(1===a?this._recordMessageReactedByMe(d,r):this._removeMyReactionRecord(d,r),null===(t=this._reactionsMap.get(g))||void 0===t?void 0:t.reactionID){const e=this._reactionsMap.get(g);e.reactedByMyself=1===a,s.emitOuterEvent(n.OuterEvent.MESSAGE_REACTIONS_UPDATED,{name:n.OuterEvent.MESSAGE_REACTIONS_UPDATED,data:{messageID:d,reactionList:[e]}})}}_generatePartialUserInfo({userIDList:e,userProfileMap:t}){const s=[];return null==e||e.forEach((e=>{t.has(e)&&s.push(t.get(e))})),s}_generateMessageID(e){const{messageSequence:t,messageKey:s,messageIDMap:n}=e;return s?n.get(s):n.get(t)}_generateMessageKeyList(e,t){const{constants:s}=this._core,n=e[0],{conversationType:o}=n;let i=[];return o===s.OuterConstant.CONV_C2C?i=e.map((e=>{const{clientSequence:s,random:n,time:o,ID:i}=e,r=`${s}_${n}_${o}`;return t.set(r,i),r})):o===s.OuterConstant.CONV_GROUP&&(i=e.map((e=>{const{ID:s,sequence:n}=e;return t.set(n,s),n}))),i}},Lt=new class{init(e){this._core=e;const{helper:t,InnerEvent:{MESSAGE_PUSH:s},InnerEventSubType:{C2C_MESSAGE_READ_RECEIPT:n,GROUP_MESSAGE_READ_RECEIPT:o},notificationCenter:i}=e;t.registerApi("sendMessageReadReceipt",this),t.registerApi("getMessageReadReceiptList",this),t.registerApi("getGroupMessageReadMemberList",this),i.subscribeInnerEvent(s,n,this._handleC2CMessageReadReceipt,this),i.subscribeInnerEvent(s,o,this._handleGroupMessageReadReceipt,this)}sendMessageReadReceipt(e){return lt(this,void 0,void 0,(function*(){const{common:t,constants:s}=this._core,n=this._filterValidMessageSendByOther(e);if(0===n.length)throw new t.ChatError({code:s.ERROR_CODE.READ_RECEIPT_MSG_LIST_EMPTY});try{const{conversationType:e}=n[0];return e===s.OuterConstant.CONV_C2C?yield function(e){return lt(this,void 0,void 0,(function*(){const{common:t,constants:s}=dt.core,n={Peer_Account:e[0].conversationID.replace(s.OuterConstant.CONV_C2C,""),C2CMsgInfo:e.map((e=>{const{from:t,to:s,sequence:n,random:o,time:i,clientTime:r}=e;return{From_Account:t,To_Account:s,MsgSeq:n,MsgRandom:o,MsgTime:i,MsgClientTime:r}}))};return t.buildAndSendPacket({servcmd:"openim.c2c_msg_read_receipt",data:n})}))}(n):yield function(e){return lt(this,void 0,void 0,(function*(){const{common:t,constants:s}=dt.core,n={GroupId:e[0].conversationID.replace(s.OuterConstant.CONV_GROUP,""),MsgSeqList:e.map((e=>({MsgSeq:e.sequence})))};return t.buildAndSendPacket({servcmd:"group_open_http_svc.group_msg_receipt",data:n})}))}(n),{code:0,data:{}}}catch(e){const{errorCode:s,errorInfo:n}=e;throw new t.ChatError({code:s,message:n})}}))}getMessageReadReceiptList(e){return lt(this,void 0,void 0,(function*(){const{common:t,constants:s}=this._core;try{const{conversationType:t}=e[0];if(t===s.OuterConstant.CONV_GROUP){const t=this._filterValidMessageSendByMe(e),s=yield function(e){return lt(this,void 0,void 0,(function*(){const{common:t,constants:s}=dt.core,n={GroupId:e[0].conversationID.replace(s.OuterConstant.CONV_GROUP,""),MsgSeqList:e.map((e=>({MsgSeq:e.sequence})))};return t.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_msg_receipt",data:n})}))}(t),{GroupMsgReceiptList:n}=s||{};this._updateGroupMessagesReadReceiptInfo({messageList:e,readReceiptList:n})}return{code:0,data:{messageList:e}}}catch(e){const{errorCode:s,errorInfo:n}=e;throw new t.ChatError({code:s,message:n})}}))}getGroupMessageReadMemberList(e){return lt(this,void 0,void 0,(function*(){const{constants:t,common:s}=this._core,{message:n,filter:o=Tt.READ,cursor:i=""}=e,{conversationID:r,sequence:a,ID:c}=n,u=r.replace(t.OuterConstant.CONV_GROUP,""),l=e.count>=100?100:e.count;try{const e=yield function(e){return lt(this,void 0,void 0,(function*(){const{sequence:t,groupID:s,filter:n,cursor:o,count:i}=e,r={MsgSeq:t,GroupId:s,Filter:n,Cursor:o,Num:i};return dt.core.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_msg_receipt_detail",data:r})}))}({groupID:u,sequence:a,filter:o,cursor:i,count:l});if(e){const{Cursor:t,IsFinish:s,UnreadList:n,ReadList:i}=e,r={cursor:t,isCompleted:1===s,messageID:c,unreadUserIDList:[],readUserIDList:[]};return o===Tt.READ?r.readUserIDList=i.map((e=>e.Read_Account)):o===Tt.UNREAD&&(r.unreadUserIDList=n.map((e=>e.Unread_Account))),{code:0,data:r}}}catch(e){const{errorCode:t,errorInfo:n}=e;throw new s.ChatError({code:t,message:n})}}))}_handleC2CMessageReadReceipt(e){const t=[],{constants:s,helper:n}=this._core,{C2cMsgInfo:o,PeerReadTime:i,Peer_Account:r}=e;if(n.isEmpty(o))return;const a=`${s.OuterConstant.CONV_C2C}${r}`;null==o||o.forEach((e=>{const{TinyId:s,MsgClientTime:n,MsgRandom:o}=e,c=`${s}-${n}-${o}`,u=bt({conversationID:a,messageID:c});u&&!u.readReceiptInfo.isPeerRead&&(u.readReceiptInfo.isPeerRead=!0,u.readReceiptInfo.timestamp=i,t.push({userID:r,messageID:c,isPeerRead:!0,timestamp:i}))})),this._emitReadReceiptEventIfNeed(t)}_updateGroupMessagesReadReceiptInfo(e){const{messageList:t,readReceiptList:s}=e,n=new Map;t.forEach((e=>{n.set(e.sequence,e)})),null==s||s.forEach((e=>{if(0===e.Code){const{MsgSeq:t,ReadNum:s,UnreadNum:o}=e,i=n.get(t);i&&(i.readReceiptInfo.readCount=s,i.readReceiptInfo.unreadCount=o)}}))}_handleGroupMessageReadReceipt(e){const t=[],{constants:s}=this._core,{GroupTips:n}=e;n.forEach((e=>{const{MsgBody:{GroupMsgReceiptList:n},GroupInfo:{GroupId:o}}=e,i=`${s.OuterConstant.CONV_GROUP}${o}`;null==n||n.forEach((e=>{const{TinyId:s,MsgClientTime:n,MsgRandom:r,ReadNum:a,UnreadNum:c}=e,u=`${s}-${n}-${r}`,l=bt({conversationID:i,messageID:u}),d={groupID:o,messageID:u,readCount:0,unreadCount:0};l&&("number"==typeof a&&(l.readReceiptInfo.readCount=a,d.readCount=a),"number"==typeof c&&(l.readReceiptInfo.unreadCount=c,d.unreadCount=c),t.push(d))}))})),this._emitReadReceiptEventIfNeed(t)}_emitReadReceiptEventIfNeed(e){const{notificationCenter:t,OuterEvent:s}=this._core;e.length>0&&t.emitOuterEvent(s.MESSAGE_READ_RECEIPT_RECEIVED,{name:s.MESSAGE_READ_RECEIPT_RECEIVED,data:e})}_filterValidMessageSendByOther(e){return this._filterNeedReadReceiptMessages(e).filter((e=>{const{from:t}=e;return t!==this._core.common.getCurrentUserID()}))}_filterValidMessageSendByMe(e){const{OuterConstant:t}=this._core.constants;return this._filterNeedReadReceiptMessages(e).filter((e=>{const{from:s,status:n}=e;return s===this._core.common.getCurrentUserID()&&n===t.MessageStatus.SUCCESS}))}_filterNeedReadReceiptMessages(e){return e.filter((e=>!0===e.needReadReceipt))}dispose(){const{InnerEvent:{MESSAGE_PUSH:e},InnerEventSubType:{C2C_MESSAGE_READ_RECEIPT:t,GROUP_MESSAGE_READ_RECEIPT:s},notificationCenter:n}=this._core;n.unSubscribeInnerEvent(e,t,this._handleC2CMessageReadReceipt,this),n.unSubscribeInnerEvent(e,s,this._handleGroupMessageReadReceipt,this)}};const At=Object.assign(Object.assign({deleteMessage:[{required:!0,rules:["array"],allowEmpty:!1}],revokeMessage:[{required:!0,rules:["object"],allowEmpty:!1}],resendMessage:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"options",required:!1,rules:["object"],allowEmpty:!1}],getMessageList:{conversationID:{required:!0,rules:["string"],allowEmpty:!1},nextReqMessageID:{required:!1,rules:["string"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0}},getMessageListHopping:{conversationID:{required:!0,rules:["string"],allowEmpty:!1},sequence:{required:!1,rules:["number"],allowEmpty:!0},direction:{required:!1,rules:["number"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0}},createTextAtMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1,customValidator:e=>"GROUP"===e||"conversationType should be GROUP."},payload:{required:!0,rules:["object"],allowEmpty:!1,customValidator:e=>{const t=function(e){var t;return"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))||"payload.text is invalid."}(e);return!0!==t?t:!((null==e?void 0:e.atUserList)&&!Array.isArray(e.atUserList))||"atUserList should be an array or undefind."}}},findMessage:[{required:!0,rules:["string"],allowEmpty:!1}],translateText:{sourceTextList:{required:!0,rules:["array"],allowEmpty:!1},sourceLanguage:{required:!0,rules:["string"],allowEmpty:!1},targetLanguage:{required:!0,rules:["string"],allowEmpty:!1}},createForwardMessage:{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}}},{addMessageReaction:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"reactionID",required:!0,rules:["string"],allowEmpty:!1}],removeMessageReaction:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"reactionID",required:!0,rules:["string"],allowEmpty:!1}],getMessageReactions:{messageList:{required:!0,rules:["array"],allowEmpty:!1},maxUserCountPerReaction:{required:!0,rules:["number"],allowEmpty:!1,customValidator:e=>"number"!=typeof e?"maxUserCountPerReaction is invalid.":!(e<0||e>10)||"maxUserCountPerReaction should between [0, 10]."}}}),{sendMessageReadReceipt:[{required:!0,rules:["array"],allowEmpty:!1}],getMessageReadReceiptList:[{required:!0,rules:["array"],allowEmpty:!1}],getGroupMessageReadMemberList:{message:{required:!0,rules:["string"],allowEmpty:!1},filter:{required:!1,rules:["string"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0},cursor:{required:!1,rules:["string"],allowEmpty:!0}}}),Ut=Object.assign(Object.assign({deleteMessage:!0,revokeMessage:!0,resendMessage:!0,getMessageList:!0,getMessageListHopping:!0,createTextAtMessage:!0,findMessage:!0,translateText:!0,createForwardMessage:!0},{addMessageReaction:!0,removeMessageReaction:!0,getMessageReactions:!0}),{sendMessageReadReceipt:!0,getMessageReadReceiptList:!0,getGroupMessageReadMemberList:!0});class Rt{constructor(e){this._core=e}deleteMessage(e){return lt(this,void 0,void 0,(function*(){const{to:t,messageIdentifiers:s}=e,n="openim.delete_c2c_msg_ramble",o={From_Account:this._getCurrentUserId(),To_Account:t,MsgKeyList:s},i=this._core.helper.generateProtocolData({servcmd:n,data:o}),r=`${i.head.seq}${n}`;return this._core.channel.sendPacket(i,{requestId:r})}))}revokeMessage(e){return lt(this,void 0,void 0,(function*(){const{to:t,from:s,sequence:n,time:o,random:i}=e,r="openim.msgwithdraw",a={MsgInfo:{From_Account:s,To_Account:t,MsgSeq:n,MsgRandom:i,MsgTimeStamp:o}},c=this._core.helper.generateProtocolData({servcmd:r,data:a}),u=`${c.head.seq}${r}`;return this._core.channel.sendPacket(c,{requestId:u})}))}_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}}class Pt{constructor(e){this._core=e}deleteMessage(e){return lt(this,void 0,void 0,(function*(){const{to:t,messageIdentifiers:s}=e,n="group_open_http_svc.delete_group_ramble_msg_by_seq",o={GroupId:t,Deleter_Account:this._getCurrentUserId(),Seqs:s},i=this._core.helper.generateProtocolData({servcmd:n,data:o}),r=`${i.head.seq}${n}`;return this._core.channel.sendPacket(i,{requestId:r})}))}revokeMessage(e){return lt(this,void 0,void 0,(function*(){const{to:t,sequence:s}=e,n="group_open_http_svc.group_msg_recall",o={GroupId:t,MsgSeqList:[{MsgSeq:s}]},i=this._core.helper.generateProtocolData({servcmd:n,data:o}),r=`${i.head.seq}${n}`;return this._core.channel.sendPacket(i,{requestId:r})}))}_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}}class Gt{constructor(e){this._core=e}generateRevokeMessage(e){const{conversationID:t,sequence:s,random:n,tinyID:o,clientTime:i,revokeReason:r,revoker:a}=e;let c={};const{messageStore:u}=this._core.message;return c=u.revokeMessage({conversationID:t,sequence:s,random:n}),c||(c={conversationID:t,sequence:s},o&&i&&n&&(c.ID=`${o}-${i}-${n}`)),c=Object.assign(Object.assign({},c),{revoker:a,revokeReason:r,revokerInfo:{userID:a,nick:"",avatar:""}}),c}updateRevokerInfo(e){return lt(this,void 0,void 0,(function*(){const t=e.map((e=>e.revoker));try{const s=yield this._fetchUserInfos(t);s&&e.forEach((e=>{const{revoker:t}=e;s[t]&&(e.revokerInfo.nick=s[t].nick||"",e.revokerInfo.avatar=s[t].avatar||"",e.revokerInfo.userID=t)}))}catch(t){console.debug(t)}}))}filterValidMessages(e){return e.filter((e=>{const t=!this._core.helper.isEmpty(null==e?void 0:e.getElements()),s=1===(null==e?void 0:e.isPlaceMessage);return t||this._core.ssoLog.createSSOLogData({method:"emptyMessageBody"}).setLogInfo({message:`from:${e.from} to:${e.to} sequence:${e.sequence}`}).end(),t&&!s}))}_fetchUserInfos(e){return lt(this,void 0,void 0,(function*(){var t,s;const n=yield null===(t=this._core.user.userProfile)||void 0===t?void 0:t.getUserProfile({userIDList:e});return(null==n?void 0:n.data)?null===(s=n.data)||void 0===s?void 0:s.reduce(((e,{userID:t,nick:s,avatar:n})=>(e[t]={nick:s||"",avatar:n||""},e)),{}):null}))}}var wt=new class{constructor(){this._core=null,this._c2cMessageAction=null,this._groupMessageAction=null}init(e){this._core=e,this._groupMessageAction=new Pt(e),this._c2cMessageAction=new Rt(e),this._messageHelper=new Gt(e);const{helper:t}=e;t.registerApi("deleteMessage",this),t.registerApi("revokeMessage",this),t.registerApi("resendMessage",this),t.registerApi("findMessage",this)}deleteMessage(e){return lt(this,void 0,void 0,(function*(){let t=[],s=[];const{conversationID:n,conversationType:o}=e[0],i=n.replace(o,"");if("@TIM#SYSTEM"===o)throw new this._core.helper.ChatError({code:2116});if(e.forEach((e=>{const{conversationID:i,conversationType:r,status:a,_onlineOnlyFlag:c,sequence:u,random:l,time:d}=e||{};if("success"===a&&i===n&&r===o){if(!c){const e="C2C"===r?`${u}_${l}_${d}`:String(u);t.push(e)}s.push(e)}})),0===t.length)return this._handleDeleteMessageSuccess(s),{code:0,data:{messageList:s}};t.length>30&&(t=t.slice(0,30),s=s.slice(0,30));try{return"C2C"===o?yield this._c2cMessageAction.deleteMessage({to:i,messageIdentifiers:t}):yield this._groupMessageAction.deleteMessage({to:i,messageIdentifiers:t}),this._handleDeleteMessageSuccess(s),{code:0,data:{messageList:s}}}catch(t){const{errorCode:e}=t;throw new this._core.helper.ChatError({functionName:"deleteMessage",code:e})}}))}revokeMessage(e){return lt(this,void 0,void 0,(function*(){var t;const s=this._core.ssoLog.createSSOLogData({method:"revokeMessage"}),{conversationType:n,isRevoked:o}=e;let i=null;if("@TIM#SYSTEM"===n)throw new this._core.helper.ChatError({message:"system message cannot be revoked"});if(o)throw new this._core.helper.ChatError({message:"message has been revoked"});s.setLogInfo({message:`type:${e.type} from:${e.from} to:${e.to}`});try{if(i="C2C"===n?yield this._c2cMessageAction.revokeMessage(e):yield this._groupMessageAction.revokeMessage(e),i){const{RecallRetList:n}=i,o=(null===(t=null==n?void 0:n[0])||void 0===t?void 0:t.RetCode)||0;if(0!==o)throw new this._core.helper.ChatError({code:o});return s.end(),yield this._handleRevokeMessageSuccess(e),{code:0,data:{message:e}}}}catch(t){const{errorCode:e}=t,s=new this._core.helper.ChatError({functionName:"revokeMessage",code:e});throw this._core.ssoLog.getSSOLogData("revokeMessage").setError(s).end(),s}}))}resendMessage(e,t){return lt(this,void 0,void 0,(function*(){var s,n;return e.isResend=!0,e.status="unSend",null===(n=null===(s=this._core)||void 0===s?void 0:s.apiMap)||void 0===n?void 0:n.sendMessage(e,t)}))}findMessage(e){return this._core.message.messageStore.findMessage(e)}_handleDeleteMessageSuccess(e){0!==e.length&&(e.forEach((e=>{e.isDeleted=!0;const t=this._core.message.messageStore.getLocalMessageList(e.conversationID);null==t||t.forEach((t=>{t.ID===e.ID&&(t.isDeleted=!0)}))})),this._core.notificationCenter.emitInnerEvent(this._core.InnerEvent.MESSAGE_DELETED,e[0].conversationID))}_handleRevokeMessageSuccess(e){return lt(this,void 0,void 0,(function*(){var t;e.isRevoked=!0,e.revoker=null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userId,yield this._messageHelper.updateRevokerInfo([e]),this._core.notificationCenter.emitInnerEvent(this._core.InnerEvent.MESSAGE_REVOKED,[e])}))}};class Nt{static parseServerPushElement(e){const{MsgContent:t={}}=e,{Index:s,Data:n}=t;return new Nt({index:s,data:n})}constructor(e){this.type=vt.MSG_FACE;const{index:t,data:s}=e;this.content={index:t,data:s}}validateBeforeSend(){var e,t;return"number"==typeof(null===(e=this.content)||void 0===e?void 0:e.index)&&"string"==typeof(null===(t=this.content)||void 0===t?void 0:t.data)?{isValid:!0}:{isValid:!1,error:{message:"content is invalid"}}}convertToBackendFormat(){const{index:e,data:t}=this.content;return{MsgType:this.type,MsgContent:{Index:e,Data:t}}}}var kt=new class{init(e){this._core=e,e.message.messageFactory.registerElementClass(vt.MSG_FACE,Nt),e.helper.registerApi("createFaceMessage",this),e.helper.registerApi("createTextAtMessage",this),e.helper.registerApi("createForwardMessage",this)}createFaceMessage(e){if(!e)return null;const{index:t,data:s}=(null==e?void 0:e.payload)||{},n=new Nt({index:t,data:s}),o=this._getCurrentUserId(),i=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},e),{from:o}));return i.setElement(n),i}createTextAtMessage(e){const{atUserList:t}=(null==e?void 0:e.payload)||{},s=this._core.apiMap.createTextMessage(e),{OuterConstant:n}=this._core;if(!s)return null;if(Array.isArray(t)){const e=[],o=[];t.forEach((t=>{t!==n.MSG_AT_ALL?(e.push({GroupAtAllFlag:0,GroupAt_Account:t}),o.push(t)):(e.push({GroupAtAllFlag:1}),o.push(n.MSG_AT_ALL))})),s._groupAtInfoList=e,s.atUserList=o}return s}createForwardMessage(e){const{helper:t,OuterConstant:s}=this._core,{to:n,conversationType:o,priority:i,payload:r,needReadReceipt:a,receiverList:c,cloudCustomData:u="",isSupportExtension:l=!1}=e;if(!Array.isArray(r._elements))throw new t.ChatError({functionName:"createForwardMessage",code:2454});if(r.type===s.MSG_GRP_TIP)throw new t.ChatError({functionName:"createForwardMessage",code:2453});const d=this._getCurrentUserId(),g=this._core.message.messageFactory.createMessage({to:n,from:d,conversationType:o,isPlaceMessage:0,priority:i,payload:r,needReadReceipt:a,isSupportExtension:l,cloudCustomData:u,receiverList:c,_relayFlag:!0});return g.setElement(r._elements[0]),g}_getCurrentUserId(){var e;return null===(e=this._core.store.get("login"))||void 0===e?void 0:e.userId}};class Ft{init(e){this._messageHelper=new Gt(e),this._core=e;const{notificationCenter:t,InnerEvent:{MESSAGE_PUSH:s},InnerEventSubType:{C2C_REVOKED_MESSAGE:n}}=e;t.subscribeInnerEvent(s,n,this._handleC2CNotifyMessage,this)}_handleC2CNotifyMessage(e){const{C2cNotifyMsgArray:t}=e;null==t||t.forEach((e=>{Object.keys(e).includes("WithdrawC2cMsgNotify")&&this._handleC2CRevokeMessage(e)}))}_handleC2CRevokeMessage(e){return lt(this,void 0,void 0,(function*(){try{const{WithdrawC2cMsgNotify:{C2cWithdrawInfoArray:t}}=e,s=[],{notificationCenter:n,OuterEvent:o,InnerEvent:i}=this._core;t.forEach((e=>{const{MsgRand:t,MsgSeq:n,To_Account:o,From_Account:i,RevokerInfo:{Revoker_Account:r,Reason:a}}=e,c=this._getCurrentUserId()===i?`C2C${o}`:`C2C${i}`,u=this._messageHelper.generateRevokeMessage({conversationID:c,sequence:n,random:t,revoker:r,revokeReason:a});s.push(u)})),0!==s.length&&n.emitInnerEvent(i.MESSAGE_REVOKED,{revokedMessages:s,updateUnreadCount:!0}),yield this._messageHelper.updateRevokerInfo(s),n.emitOuterEvent(o.MESSAGE_REVOKED,{name:o.MESSAGE_REVOKED,data:s})}catch(e){console.debug(e)}}))}_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(){const{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t},InnerEventSubType:{C2C_REVOKED_MESSAGE:s}}=this._core;e.unSubscribeInnerEvent(t,s,this._handleC2CNotifyMessage,this)}}class $t{init(e){this._messageHelper=new Gt(e),this._core=e;const{notificationCenter:t,InnerEvent:{MESSAGE_PUSH:s},InnerEventSubType:{GROUP_MESSAGE_REVOKED:n}}=e;t.subscribeInnerEvent(s,n,this._handleGroupNotifyMessage,this)}_handleGroupNotifyMessage(e){const{GroupTips:t}=e;null==t||t.forEach((e=>{var t;Array.isArray(null===(t=null==e?void 0:e.MsgBody)||void 0===t?void 0:t.GroupWithdrawInfoArray)&&this._handleGroupRevokeMessage(e)}))}_handleGroupRevokeMessage(e){return lt(this,void 0,void 0,(function*(){try{const{RevokerInfo:t,MsgBody:{GroupWithdrawInfoArray:s}}=e,n=[],{notificationCenter:o,OuterEvent:i,InnerEvent:r}=this._core;s.forEach((e=>{const{Random:s,MsgSeq:o,GroupId:i,MsgClientTime:r,TinyId:a,TopicId:c,RevokerInfo:{Revoker_Account:u=(null==t?void 0:t.Revoker_Account)||"",Reason:l=(null==t?void 0:t.Reason)||""}}=e,d=c?`GROUP${c}`:`GROUP${i}`,g=this._messageHelper.generateRevokeMessage({conversationID:d,sequence:o,random:s,tinyID:a,clientTime:r,revoker:u,revokeReason:l});n.push(g)})),0!==n.length&&(o.emitInnerEvent(r.MESSAGE_REVOKED,{revokedMessages:n,updateUnreadCount:!0}),yield this._messageHelper.updateRevokerInfo(n),o.emitOuterEvent(i.MESSAGE_REVOKED,{name:i.MESSAGE_REVOKED,data:n}))}catch(e){console.debug(e)}}))}dispose(){const{notificationCenter:e,InnerEvent:{MESSAGE_PUSH:t},InnerEventSubType:{GROUP_MESSAGE_REVOKED:s}}=this._core;e.unSubscribeInnerEvent(t,s,this._handleGroupNotifyMessage,this)}}var xt=new class{constructor(){this._c2cMessageReceiver=new Ft,this._groupMessageReceiver=new $t}init(e){this._c2cMessageReceiver.init(e),this._groupMessageReceiver.init(e)}dispose(){this._c2cMessageReceiver.dispose(),this._groupMessageReceiver.dispose()}};class jt{constructor(e){this._lastMessageSequenceMapOnDisconnect=new Map,this._core=e,this._messageHelper=new Gt(e)}getRoamingMessagesByAnchor(e){return lt(this,void 0,void 0,(function*(){try{const t=this._core.ssoLog.createSSOLogData({method:"getRoamingMessagesByAnchor"}),{conversationID:s,count:n,direction:o,sequence:i}=e,r=s.replace(ht,"");let a=i;if(o===It.BACKWARD){if("number"!=typeof i)return{messageList:[],hasNoMoreHistoryMessage:!1,nextReqMessageIDFromServer:""};a=i+n-1}const c={GroupId:r,ReqMsgNumber:n,WithRecalledMsg:1,Version:1};a&&(c.ReqMsgSeq=a);const u="group_open_http_svc.group_msg_get",l=this._core.helper.generateProtocolData({servcmd:u,data:c}),d=`${l.head.seq}${u}`,g=yield this._core.channel.sendPacket(l,{requestId:d});if(g){const{RspMsgList:e,NextReqMsgSeq:s=0,IsFinished:n,InvisibleMsgSeq:c}=g;t.setLogInfo({message:`groupID:${r} sequence:${i} reqSeq:${a} direction:${o}\n complete:${n} nextSequence:${s} remoteMsgCount:${e.length} invisibleSequenceList:${c}`}).end();const u=[];for(let t=0;t<e.length;t++){const s=e[t],n=this._parseMessage(s);u.push(n)}u.reverse();const l=[_t.NO_MORE_DATA,_t.DATA_HAS_EXPIRED].includes(n);return{messageList:this._messageHelper.filterValidMessages(u),invisibleSequenceList:c,nextReqMessageIDFromServer:s,hasNoMoreHistoryMessage:l}}}catch(e){const t=new this._core.helper.ChatError({code:null==e?void 0:e.code});this._core.ssoLog.getSSOLogData("getRoamingMessagesByAnchor").setError(t).end()}}))}recoverHistoryMessage(e){return lt(this,void 0,void 0,(function*(){const{message:{messageReceiver:t,messageStore:s},notificationCenter:n,OuterEvent:o}=this._core;null==e||e.forEach((e=>lt(this,void 0,void 0,(function*(){const{conversationID:i,lastMessage:r}=e;let a=this._getLocalLastMessageSequence(i);const c=r.lastSequence;if(this._shouldRecoverHistory({localLastMessageSequence:a,serverLastMessageSequence:c})){const e=c-a;let r=!1;const u=Math.ceil(e/20);for(let e=0;e<u;e++)try{const e=c-a,u=Math.min(20,e),l=yield this.getRoamingMessagesByAnchor({conversationID:i,sequence:a+u,direction:It.FORWARD,count:u}),{nextReqMessageIDFromServer:d,hasNoMoreHistoryMessage:g,messageList:h}=l;r=g&&d<0,a=h[h.length-1].sequence;const p=[];if(Array.isArray(h)&&(h.forEach((e=>{t.groupMessageReceiver.updateMessageProfile(e),s.storeConversationMessage(e)&&p.push(e)})),p.length>0&&n.emitOuterEvent(o.MESSAGE_RECEIVED,{name:o.MESSAGE_RECEIVED,data:p})),r)break}catch(i){console.debug(i);break}}}))))}))}updateLastMessageSequenceMapOnDisconnect(){const e=this._core.message.messageStore.getContinuousMessagesByConversation();for(const[t,s]of e){if(t.startsWith("C2C"))continue;const e=Array.from(s.values());if((null==e?void 0:e.length)>0){const s=e[e.length-1].sequence;this._lastMessageSequenceMapOnDisconnect.set(t,s)}}}_shouldRecoverHistory(e){const{localLastMessageSequence:t,serverLastMessageSequence:s}=e;if("number"!=typeof t||"number"!=typeof s)return!1;const n=s-t;return 0!==s&&t&&n>=1&&n<300}_getLocalLastMessageSequence(e){if(this._lastMessageSequenceMapOnDisconnect.has(e))return this._lastMessageSequenceMapOnDisconnect.get(e);const t=this._core.message.messageStore.getLocalMessageList(e),s=t[t.length-1];return null==s?void 0:s.sequence}_parseMessage(e){const t=ht,s=this._core.message.messageHelper.parseServerGroupMessage(e),n=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{conversationType:t,flow:"in"}));return n.setElement(s.elements),n}}class Vt{constructor(e){this._historyMessageListFetchAnchors=new Map,this._core=e,this._messageHelper=new Gt(e)}getRoamingMessagesByAnchor(e){return lt(this,void 0,void 0,(function*(){var t;try{const{conversationID:s,count:n,messageID:o,time:i,direction:r}=e;let a=i,c="";if(!i){const e=o?this._core.message.messageStore.findMessage(o):null;if(a=(null==e?void 0:e.time)||0,o&&this._historyMessageListFetchAnchors.has(s)){const e=this._historyMessageListFetchAnchors.get(s);a=e.lastMessageTime,c=e.messageKey}}const u=s.replace(gt,""),l=yield function(e){return lt(this,void 0,void 0,(function*(){const{peerAccount:t,count:s,lastMessageTime:n,messageKey:o,direction:i}=e,r={Peer_Account:t,MaxCnt:s,WithRecalledMsg:1,LastMsgTime:n,MsgKey:o,GetDirection:i};return dt.core.common.buildAndSendPacket({servcmd:"openim.getroammsg",data:r})}))}({count:n,lastMessageTime:a,messageKey:c,peerAccount:u,direction:r});if(l){const{MsgList:e,Complete:n,MsgKey:o,LastMsgTime:i}=l;this._historyMessageListFetchAnchors.set(s,{messageKey:o,lastMessageTime:i});const r=[];for(let t=0;t<e.length;t++){const s=e[t],n=this._parseMessage(s);r.push(n)}yield ft(s),yield mt({messageList:r,conversationID:s});const a=this._messageHelper.filterValidMessages(r);return{messageList:a,nextReqMessageIDFromServer:null===(t=a[0])||void 0===t?void 0:t.ID,lastMessageTime:i,hasNoMoreHistoryMessage:1===n}}}catch(e){throw new this._core.helper.ChatError({code:null==e?void 0:e.code})}}))}_parseMessage(e){const t=gt,s=this._core.message.messageHelper.parseServerPushMessage(e),n=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{conversationType:t,flow:"in"}));return n.setElement(s.elements),n}}var qt=new class{constructor(){this._clearedConversations=new Set,this._fetchedCompleteConversations=new Set}init(e){this._core=e,this._groupMessageHistory=new jt(e),this._c2cMessageHistory=new Vt(e),this._messageHelper=new Gt(e);const{InnerEvent:t,notificationCenter:s,constants:n}=e;e.helper.registerApi("getMessageList",this),e.helper.registerApi("getMessageListHopping",this),e.helper.registerWorkflowStep(n.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,n.WORKFLOW_STEP.HISTORY_MESSAGE_RECOVER,this._recoverHistoryMessage,this),s.subscribeInnerEvent(t.SOCKET_DISCONNECTED,this._handleSocketDisconnected,this)}getMessageList(e){return lt(this,void 0,void 0,(function*(){try{const t=this._core.ssoLog.createSSOLogData({method:"getMessageList"});let{conversationID:s,nextReqMessageID:n}=e;const o=pt;if("@TIM#SYSTEM"===s)return{code:0,data:{messageList:[],isCompleted:!1,nextMessageSeq:""}};const i=this._getAvailableLocalMessagesCount({conversationID:s,nextReqMessageID:n});if(this._needFetchHistoryMessageList({conversationID:s,availableLocalMessagesCount:i,targetCount:o})){let e=null;if(s.startsWith(ht)?e=yield this._groupMessageHistory.getRoamingMessagesByAnchor({conversationID:s,sequence:Number(n),count:o,direction:It.FORWARD}):s.startsWith(gt)&&(e=yield this._c2cMessageHistory.getRoamingMessagesByAnchor({conversationID:s,messageID:n,count:o,direction:It.FORWARD})),e){const{nextReqMessageIDFromServer:o,hasNoMoreHistoryMessage:r,messageList:a}=e,c=this._core.message.messageStore.prependLocalMessageList({messageList:a,conversationID:s}),u=this._core.message.messageStore.getLocalMessageList(s).slice(0,c.length+i),l=u.filter((e=>e.isRevoked));yield this._messageHelper.updateRevokerInfo(l);const d={nextReqMessageID:r?"":String(o),messageList:u,isCompleted:r},g=u.map((e=>e.sequence));return t.setLogInfo({message:`conversationID: ${s} nextReqMessageID: ${n} \n availableLocalMessagesCount: ${i} sequenceList: ${JSON.stringify(g)} `}).end(),{code:0,data:d}}return{code:0,data:{messageList:[],isCompleted:!1,nextMessageSeq:""}}}return t.setLogInfo({message:`conversationID: ${s} nextReqMessageID: ${n} availableLocalMessagesCount: ${i}}`}).end(),{code:0,data:yield this._getMessageListFromMemory({conversationID:s,nextReqMessageID:n,count:o})}}catch(e){const t=new this._core.helper.ChatError({code:null==e?void 0:e.code});this._core.ssoLog.getSSOLogData("getMessageList").setError(t).end(),console.debug(t)}}))}getMessageListHopping(e){return lt(this,void 0,void 0,(function*(){var t,s;const{conversationID:n,sequence:o,time:i,direction:r=It.FORWARD}=e,{isEmpty:a}=this._core.helper;if(![It.BACKWARD,It.FORWARD].includes(r))throw new this._core.helper.ChatError({message:"direction must be 0 or 1"});let{count:c=pt}=e;c=c>pt?pt:c;let u=null;if(n.startsWith(ht)){if(u=yield this._groupMessageHistory.getRoamingMessagesByAnchor({conversationID:n,sequence:o,count:c,direction:r}),u){const{nextReqMessageIDFromServer:e,hasNoMoreHistoryMessage:n,messageList:i,invisibleSequenceList:c}=u;if(this._core.message.messageStore.storeSparseMessageList(i),r===It.FORWARD){const t=n&&e<1;return{code:0,data:{messageList:i,isCompleted:t,nextMessageSeq:t?"":e}}}if(r===It.BACKWARD){if(a(i)&&a(c))return{code:0,data:{messageList:[],isCompleted:!0,nextMessageSeq:""}};const e=(null===(t=null==i?void 0:i[i.length-1])||void 0===t?void 0:t.sequence)||0,n=(null===(s=null==c?void 0:c[c.length-1])||void 0===s?void 0:s.sequence)||0;return{code:0,data:{messageList:i.filter((e=>e.sequence>=o)),isCompleted:!1,nextMessageSeq:Math.max(e,n)+1}}}return{code:0,data:u}}}else if(n.startsWith(gt)&&(u=yield this._c2cMessageHistory.getRoamingMessagesByAnchor({conversationID:n,count:c+1,time:i,direction:r}),u)){const{messageList:e,lastMessageTime:t,hasNoMoreHistoryMessage:s}=u;return s||(r===It.FORWARD?e.shift():e.pop()),this._core.message.messageStore.storeSparseMessageList(e),{code:0,data:{messageList:e,isCompleted:s,nextMessageTime:s?"":t}}}}))}_getAvailableLocalMessagesCount({conversationID:e,nextReqMessageID:t}){const s=this._core.message.messageStore.getLocalMessageList(e),{length:n}=s;if(!t)return n;let o=-1;return(null==e?void 0:e.startsWith(gt))?o=s.findIndex((e=>e.ID===t)):(null==e?void 0:e.startsWith(ht))&&(o=s.findIndex((e=>t.includes("-")?e.ID===t:String(e.sequence)===t))),-1===o?0:o}_needFetchHistoryMessageList({conversationID:e,availableLocalMessagesCount:t,targetCount:s}){return!!this._clearedConversations.has(e)||t<=s&&!this._fetchedCompleteConversations.has(e)}_getMessageListFromMemory(e){return lt(this,arguments,void 0,(function*({conversationID:e,nextReqMessageID:t,count:s}){const n=this._core.message.messageStore.getLocalMessageList(e),o=n.length;let i=o,r={isCompleted:!1,nextReqMessageID:"",messageList:[]},a=0,c=o;return t?t&&(c=n.findIndex((s=>e.startsWith(gt)?s.ID===t:String(s.sequence)===t)),a=c>s?c-s:0,i=c):a=o>s?o-s:0,r.nextReqMessageID=0===a?"":this._generateNextReqMessageID({conversationID:e,targetIndex:a}),r.messageList=n.slice(a,c),r.isCompleted=i<=s,e.startsWith(gt)&&(yield ft(e),yield mt({messageList:r.messageList,conversationID:e})),r}))}_generateNextReqMessageID({conversationID:e,targetIndex:t}){const s=this._core.message.messageStore.getLocalMessageList(e);return e.startsWith("C2C")?s[t].ID:String(s[t].sequence)}_recoverHistoryMessage(){const{conversationMap:e}=this._core.store.get("conversation")||{};if(e instanceof Map){const t=[...e.values()].filter((e=>e.type===ht));this._groupMessageHistory.recoverHistoryMessage(t)}}_handleSocketDisconnected(){this._groupMessageHistory.updateLastMessageSequenceMapOnDisconnect()}dispose(){const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.SOCKET_DISCONNECTED,this._handleSocketDisconnected,this)}},Ht=new class{constructor(){this._core=null}init(e){this._core=e;const{helper:t}=e;t.registerApi("translateText",this)}translateText(e){return lt(this,void 0,void 0,(function*(){try{const{sourceLanguage:t,sourceTextList:s,targetLanguage:n}=e,o=yield function(e,t){return lt(this,void 0,void 0,(function*(){var s,n;const{sourceTextList:o,sourceLanguage:i,targetLanguage:r}=e,{store:a,helper:c,channel:u}=t,l="im_open_translate.ws_batch_trans_text",d={SourceText:o,Source:i,Target:r,FromAccount:null===(s=a.get("login"))||void 0===s?void 0:s.tinyID,SDKAppID:null===(n=a.get("instance"))||void 0===n?void 0:n.sdkAppId},g=c.generateProtocolData({servcmd:l,data:d}),h=`${g.head.seq}${l}`,p=yield u.sendPacket(g,{requestId:h});if(p){const{CmdErrorCode:e,TargetText:t}=p;return{cmdErrorCode:e,translatedTextList:t}}}))}({sourceLanguage:t,sourceTextList:s,targetLanguage:n},this._core);if(o){const{cmdErrorCode:{ErrorCode:e,ErrorInfo:t},translatedTextList:s}=o;if(0===e)return{code:0,data:{translatedTextList:s}};throw{errorCode:e,errorInfo:t,message:t}}}catch(e){const{errorCode:t,errorInfo:s}=e||{};throw new this._core.helper.ChatError({functionName:"translateText",code:t,message:s})}}))}},Bt=new class{init(e){this._core=e,e.common.registerApi("convertVoiceToText",this)}convertVoiceToText(e){return lt(this,void 0,void 0,(function*(){var t,s;const{message:n,language:o=yt.ZH_PY}=e;let{url:i}=n.payload||{};const r=null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userID;n.from===r&&"out"===n.flow&&(i=n.payload.remoteAudioUrl),this._validateVoiceFormat(i);const a=(null===(s=Ct.exec(i))||void 0===s?void 0:s[1])||"mp3",c=St[o]||Et;try{const e=yield function(e){var t;const{store:s,common:n}=dt.core,{url:o,format:i,serverLanguageType:r}=e,a={BytesUrl:o,BytesEngServiceType:r,BytesVoiceFormat:i,Uint32Sdkappid:null===(t=s.get("instance"))||void 0===t?void 0:t.sdkAppId,Uint64SourceType:0};return n.buildAndSendPacket({servcmd:"im_open_speech.ws_sentence_recognition",data:a})}({url:i,format:a,serverLanguageType:c});if(e){const{CmdErrorCode:t,BytesResult:s}=e;if(0===t.ErrorCode)return{code:0,data:{result:s}};throw{code:t.ErrorCode,message:t.ErrorInfo}}}catch(t){const{code:e,message:s}=t||{},n=new this._core.common.ChatError({functionName:"convertVoiceToText",code:e,message:s});console.error(n),this._core.ssoLog.createSSOLogData({method:"convertVoiceToText"}).setError(n).end()}}))}_validateVoiceFormat(e){if(!Ct.test(e))throw new this._core.common.ChatError({code:2119})}},Kt=new class{install(e){this._core=e,dt.init(e),wt.init(e),kt.init(e),xt.init(e),qt.init(e),Ot.init(e),Ht.init(e),Bt.init(e),Lt.init(e),e.helper.registerValidateConfig({auth:Ut,params:At}),e.notificationCenter.subscribeInnerEvent(e.InnerEvent.DESTROY,this.dispose,this)}dispose(){const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this.dispose,this),xt.dispose(),qt.dispose(),Lt.dispose()}};function Yt(e,t){var s={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(s[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(n=Object.getOwnPropertySymbols(e);o<n.length;o++)t.indexOf(n[o])<0&&Object.prototype.propertyIsEnumerable.call(e,n[o])&&(s[n[o]]=e[n[o]])}return s}function Wt(e,t,s,n){return new(s||(s=Promise))((function(o,i){function r(e){try{c(n.next(e))}catch(e){i(e)}}function a(e){try{c(n.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(r,a)}c((n=n.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;var zt=new class{constructor(){this._name="WebRequest"}init(e){this._core=e}request(e,t){return Wt(this,void 0,void 0,(function*(){var s;const{isEmpty:n}=null===(s=this._core)||void 0===s?void 0:s.utils,{downloadUrl:o="",method:i="PUT",url:r,qs:a,headers:c={},resources:u,dataType:l="text",uploadByIP:d,uploadIP:g}=e;let h=r;if(a){const e=this._queryString(a);e&&(h+=`${h.includes("?")?"&":"?"}${e}`)}const p=new XMLHttpRequest;p.open(i.toUpperCase(),h,!0),p.responseType=l;const m=Object.assign({},c);if(d&&g&&(m.host=g),!n(m))for(const e in m)m.hasOwnProperty(e)&&!["content-length","user-agent","origin","host"].includes(e.toLowerCase())&&p.setRequestHeader(e,m[e]);return p.onload=()=>{const s=this._getResponseBody(p,o,d&&g),n=this._buildResponse(p,s);if(200===p.status)t(null,n);else{if(g&&!h.includes(g))return e.url=this._domainName2IP(h,g),e.uploadByIP=!0,this.request(e,t);t({code:p.status,message:JSON.stringify(p.responseText)},n)}},p.onerror=()=>{const e=this._getResponseBody(p,o,d&&g),s=this._buildResponse(p,e),n={code:p.status,message:0===p.status?"CORS blocked or network error":JSON.stringify(p.responseText)};t(n,s)},e.onProgress&&p.upload&&(p.upload.onprogress=t=>{const{total:s,loaded:n}=t,o=Math.min(Math.floor(100*n/s),100);e.onProgress({total:s,loaded:n,percent:o/100})}),p.send(u),p}))}_buildResponse(e,t){const s={};return e.getAllResponseHeaders().trim().split("\n").forEach((e=>{if(e){const[t,n]=e.split(":").map((e=>e.trim()));s[t.toLowerCase()]=n}})),{statusCode:e.status,statusMessage:e.statusText,headers:s,data:t}}_getResponseBody(e,t,s){return 200===e.status&&t?{location:t,uploadIP:s}:{response:e.responseText,uploadIP:s}}_queryString(e,t="&",s="="){var n;const{isEmpty:o,isPlainObject:i}=null===(n=this._core)||void 0===n?void 0:n.utils;return o(e)?"":i(e)?Object.keys(e).map((n=>{const o=encodeURIComponent(n)+s;return Array.isArray(e[n])?e[n].map((e=>o+encodeURIComponent(e))).join(t):o+encodeURIComponent(e[n])})).filter(Boolean).join(t):void 0}_domainName2IP(e,t){return e.replace(/^http(s)?:\/\/(.*?)\//,`https://${t}/`)}};const Jt=["unknown","image","video","audio","log"];var Xt=new class{init(e){this._core=e}request(e,t){var s;const{MINI_APP_NAMESPACE:n,IN_ALIPAY_MINI_APP:o,IN_UNI_IOS_APP:i}=null===(s=this._core)||void 0===s?void 0:s.utils,{resources:r="",headers:a={},url:c,downloadUrl:u=""}=e;let l=c,d=null;const g=u?u.match(/^(https?:\/\/[^/]+\/)([^/]*\/?)(.*)$/):null;if(!g)return void console.warn("message Invalid download URL format");const h=decodeURIComponent(g[3]),p=h.includes("?")?h.split("?")[0]:h||"",m={key:e.fileKey||p,success_action_status:200,"Content-Type":""},f={};if(i){const[e,t]=c.split("?sign=");t&&(l=`${e}?sign=${encodeURIComponent(t)}`,f.sign=decodeURIComponent(t),f.signature=decodeURIComponent(t))}let v={url:l,header:a,name:"file",filePath:r,formData:Object.assign(Object.assign({},m),f),timeout:e.timeout||3e5};if(o){const t=Yt(v,["name"]);v=Object.assign(Object.assign({},t),{fileName:"file",fileType:e.fileType?Jt[e.fileType]:"image"})}return d=n.uploadFile(Object.assign(Object.assign({},v),{success:e=>{this._handleResponse({response:e,downloadUrl:u,callback:t})},fail:e=>{this._handleResponse({response:e,downloadUrl:u,callback:t})}})),d.onProgressUpdate&&d.onProgressUpdate((t=>{e.onProgress&&e.onProgress({total:t.totalBytesExpectedToSend||0,loaded:t.totalBytesSent||0,percent:t.progress?Math.floor(t.progress)/100:0})})),d}_handleResponse(e){const{downloadUrl:t,response:s,callback:n}=e,o={};if(s.header)for(const e in s.header)s.header.hasOwnProperty(e)&&(o[e.toLowerCase()]=s.header[e]);const i=+s.statusCode;200===i?n(null,{statusCode:i,headers:o,data:Object.assign(Object.assign({},s.data),{location:t})}):n({code:i,message:JSON.stringify(s.data)},{statusCode:i,headers:o,data:void 0})}};function Qt(e){return"file"===function(e){return Object.prototype.toString.call(e).match(/^\[object (.*)\]$/)[1].toLowerCase()}(e)}function Zt(e){const t=e||99999999;return Math.round(Math.random()*t)}function es(e,t=!0,s=!0){const n=Date.now();return t?s?n-e+" ms":`${Math.round((n-e)/1e3)} s`:s?n-e:Math.round((n-e)/1e3)}function ts(e){return`${Array.from({length:8},(()=>Math.floor(65536*(1+Math.random())).toString(16).substring(1))).join("")}-${e}`}function ss(e,t){return Math.round(Number(e)*10**t)/10**t}function ns(e){const t=1048576;return e<1024?`${e}B`:e<t?`${Math.floor(e/1024)}KB`:`${Math.floor(e/t)}MB`}function os(e){return e<=1048576?`${ss(e/1024,1)}KB/s`:`${ss(e/1048576,1)}MB/s`}const is="TIMImageElem",rs="TIMSoundElem",as="TIMFileElem",cs="TIMVideoFileElem",us="RichMediaMessagePlugin",ls=["rich.my-imcloud.com","imrich.qcloud.com"];var ds;!function(e){e.UNSENT="unSend",e.SUCCESS="success",e.FAIL="fail"}(ds||(ds={}));var gs=new class{init(e){this._core=e}addAuthToUrl(e){const t=function(e){return e?e.startsWith("https://")?e:e.startsWith("http://")?e.replace("http://","https://"):e:""}(e);return this.processResourceUrl(t)}removeAuthToUrl(e){return function(e){const[t,s]=e.split("?");if(!s)return t;const n=s.split("&").reduce(((e,t)=>{const[s,n]=t.split("=");return s&&"authKey"!==s&&(e[s]=n||""),e}),{}),o=Object.keys(n).map((e=>`${e}${n[e]?`=${n[e]}`:""}`)).join("&");return o?`${t}?${o}`:t}(e)}extractFileFromInput(e){return Qt(e)?e:function(e){if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);if(null===t)return!0;let s=t;for(;null!==Object.getPrototypeOf(s);)s=Object.getPrototypeOf(s);return t===s}(e)&&"undefined"!=typeof uni?Array.isArray(e.tempFiles)&&e.tempFiles.length>0?e.tempFiles[0]:null:e instanceof HTMLInputElement&&e.files&&e.files.length>0?e.files[0]:null}probeImageWidthHeight(e){return Wt(this,void 0,void 0,(function*(){var t;const{IN_MINI_APP:s,IN_BROWSER:n}=(null===(t=this._core)||void 0===t?void 0:t.utils)||{};return this._shouldSkipProbing()?{width:0,height:0}:n?this._probeImageDimensionsWeb(e):s?this._probeImageDimensionsMiniApp(e):void 0}))}isSimpleCos(){var e;const t=(null===(e=this._core)||void 0===e?void 0:e.store.get("cloudConfig"))||{},{simple_cos:s}=t;return"0"!==s}getFileDNList(){var e;let t=ls;const s=(null===(e=this._core)||void 0===e?void 0:e.store.get("cloudConfig"))||{},{file_dn_list:n}=s;if(void 0===n)return t;try{JSON.parse(n).forEach((e=>{t.includes(e)||t.push(e)}))}catch(e){console.warn(e),t=ls}return t}getPlatform(){var e;return null===(e=this._core)||void 0===e?void 0:e.utils.platform}generateUUID(e,t){let s=`${this.getSDKAppID()}-${this.getCurrentUserID()}-${function(){let e="";for(let t=32;t>0;--t)e+="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"[Math.floor(62*Math.random())];return e}()}`;if(t)return`${s}.${t}`;const n=e.name||e.value||e.url||e.tempFilePath,o=n&&n.slice(n.lastIndexOf(".")+1);return o&&(s=`${s}.${o}`),s}processResourceUrl(e){if(!e)return"";let t=e;const s=this.getFileDownloadProxy(),n=this.getAuthKey(),o=this.getFileDNList();s&&(e.startsWith("http://")?t=e.replace(/^http:\/\/[^/]+/,s):e.startsWith("https://")&&(t=e.replace(/^https:\/\/[^/]+/,s)));const i=n&&-1===t.indexOf("authKey=")&&function(e,t){let s=!1;if(e){const n=e.match(/:\/\/([0-9]?\.)?(.[^/:]+)/),o=n&&n[2]||"";if(o.includes("rich-dev"))return!0;for(let e=0;e<t.length;e++)if(o.endsWith(t[e])){s=!0;break}}return s}(t,o);return i&&(t=t.indexOf("?")>-1?`${t}&authKey=${n}`:`${t}?authKey=${n}`),t}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}getSDKAppID(){var e,t;return null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("instance"))||void 0===t?void 0:t.sdkAppId}getFileDownloadProxy(){var e,t;return(null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("instance"))||void 0===t?void 0:t.fileDownloadProxy)||""}getFileUploadProxy(){var e,t;return(null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("instance"))||void 0===t?void 0:t.fileUploadProxy)||""}getAuthKey(){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.authKey)||""}isPrivateNetWork(){var e,t;return null===(t=null===(e=this._core)||void 0===e?void 0:e.store.get("instance"))||void 0===t?void 0:t.proxyServer}getPlatformFlags(){var e;const{IN_BROWSER:t,IN_MINI_APP:s,IN_RN_APP:n,IN_UNI_NATIVE_APP:o}=null===(e=this._core)||void 0===e?void 0:e.utils;return{IN_BROWSER:t,IN_MINI_APP:s,IN_RN_APP:n,IN_UNI_NATIVE_APP:o}}isEmpty(e){var t;const{isEmpty:s}=null===(t=this._core)||void 0===t?void 0:t.utils;return s(e)}_probeImageDimensionsMiniApp(e){var t;const{MINI_APP_NAMESPACE:s}=(null===(t=this._core)||void 0===t?void 0:t.utils)||{};return new Promise((t=>{s.getImageInfo({src:e,success:e=>t({width:e.width,height:e.height}),fail:()=>t({width:0,height:0})})}))}_shouldSkipProbing(){var e;const{IN_RN_APP:t,IS_IE:s,IE_VERSION:n}=(null===(e=this._core)||void 0===e?void 0:e.utils)||{};return t||s&&9===n}_probeImageDimensionsWeb(e){return new Promise((t=>{const s=new Image,n=()=>{s.onload=null,s.onerror=null,s.src=""};s.onload=()=>{t({width:s.width,height:s.height}),n()},s.onerror=()=>{t({width:0,height:0}),n()},s.src=e}))}},hs=new class{constructor(){this.uploadFileTryCount=0,this.maxRetries=1,this.systemClockOffset=0,this.httpRequest=null,this.uploadFileType="",this.duration=900,this.fetchCosTryCount=0}init(e){var t;this._core=e;const{IN_MINI_APP:s}=e.utils;this.httpRequest=s?Xt:zt,null===(t=this.httpRequest)||void 0===t||t.init(e)}uploadToCOS(e){return Wt(this,void 0,void 0,(function*(){const t=`${us} uploadToCOS`,{file:s}=e;this.uploadFileType=e.uploadFileType,console.log(`${t} options:`,e);try{const n=Date.now(),o=yield this._createCosOptions(e),i=yield this._uploadFile(o);this._handleUploadError(i,e);const r=this._createUploadResult(s,i),a=Date.now()-n,c=`size:${ns(s.size)} time:${a}ms speed:${os(1e3*s.size/a)}`;return console.log(`${t} ok. name:${s.name} ${c}`),{uploadOptions:o,response:r}}catch(e){throw console.warn(`${t} failed, error:`,e),e}}))}_handleUploadError(e,t){var s,n;const{ChatError:o}=null===(s=this._core)||void 0===s?void 0:s.helper;if(403===e.statusCode)throw t.url,(null===(n=null==e?void 0:e.data)||void 0===n?void 0:n.uploadIP)&&e.data.uploadIP,new o({message:"Upload failed with status 403"})}_createUploadResult(e,t){return{fileName:e.name,fileSize:e.size,fileType:e.type.slice(e.type.indexOf("/")+1).toLowerCase(),location:t.data.location||"",uploadTime:es(Date.now(),!1),uploadSpeed:os(1e3*e.size/es(Date.now(),!1))}}_createCosOptions(e){return Wt(this,void 0,void 0,(function*(){const{fileName:t,resources:s,uploadMethod:n}=this._prepareUploadParams(e),o=this._isC2CConversation(e.message.conversationID)?1:2;try{const i=yield this._fetchCosSignatureUrl({fileType:this.uploadFileType,fileName:t,uploadMethod:n,duration:this.duration,userID:e.message.from,conversationType:o}),{uploadUrl:r,downloadUrl:a,requestSnapshotUrl:c,thumbUrl:u,largeUrl:l,fileKey:d}=i,g=!gs.isPrivateNetWork()&&i.uploadIP;return{url:this._getRawOrUploadProxyUrl(r),fileType:this.uploadFileType,fileName:t,resources:s,downloadUrl:a,requestSnapshotUrl:c,thumbUrl:u,largeUrl:l,fileKey:d,uploadIP:g||"",onProgress:t=>this._handleUploadProgress(t,e)}}catch(e){throw console.error("Failed to create COS pre-signed URL options:",e),e}}))}_prepareUploadParams(e){console.log(`${us} prepareUploadParams:`,e);const{file:t}=e,{IN_MINI_APP:s,IN_RN_APP:n}=gs.getPlatformFlags(),o=s||n,i=o&&e.message.type!==as,{name:r}=t,a=r.slice(r.lastIndexOf(".")),c=`${Zt(999999)}${a}`;return{fileName:ts(i?t.name:c),resources:o?t.url:t,uploadMethod:o?1:0}}_handleUploadProgress(e,t){if("function"==typeof t.onProgress)try{t.onProgress(e.percent)}catch(e){throw console.warn("Upload progress callback error:",e),e}}_fetchCosSignatureUrl(e){return Wt(this,void 0,void 0,(function*(){const t=`${us} fetchCosSignatureUrl`,s=gs.isSimpleCos(),n=this._prepareCosRequestData(e),o=s?"im_cos_msg.simple_sig":"im_cos_msg.pre_sig";try{const e=yield function(e,t,s){return Wt(this,void 0,void 0,(function*(){try{const{helper:n,channel:o}=s,i=n.generateCosSpecifiedData({servcmd:e,data:t}),r=`${i.head.seq}${e}`;return yield o.sendPacket(i,{requestId:r})}catch(e){throw console.warn("getCosSig error:",e),e}}))}(o,n,this._core);this.fetchCosTryCount=0;const i=this._processResponse(e);return console.log(`${t} ok. isSimpleCos:${s} data:`,i),i||{}}catch(s){if(console.error(`${t} failed, error:`,s),this.fetchCosTryCount<1)return this.fetchCosTryCount++,this._fetchCosSignatureUrl(e);throw this.fetchCosTryCount=0,s}}))}_processResponse(e){var t;const s=gs.isSimpleCos(),n=s?null===(t=null==e?void 0:e.rpt_pre_sig)||void 0===t?void 0:t[0]:e;if(!n)return{};if(s){const{str_final_ip:e,rpt_pre_sig:t,uint32_file_id:s,uint32_exist_flag:o,str_download_url:i,str_upload_url:r,str_snapshot_url:a,str_file_key:c}=n;return{uploadIP:e,preSig:t,fileID:s,existFlag:o,downloadUrl:i,uploadUrl:r,requestSnapshotUrl:a,fileKey:c}}const{upload_url:o,download_url:i,snapshot_url:r,thumb_url:a,large_url:c,file_key:u}=n;return{uploadUrl:o,downloadUrl:i,requestSnapshotUrl:r,thumbUrl:a,largeUrl:c,fileKey:u}}_prepareCosRequestData(e){return gs.isSimpleCos()?{uint32_upload_method:e.uploadMethod,uint32_platform:gs.getPlatform(),uint32_sdkappid:gs.getSDKAppID(),str_user_id:e.userID,uint32_scene:e.conversationType,rpt_upload_object:[{uint32_file_id:1,uint32_file_type:e.fileType,str_file_name:e.fileName}]}:{file_type:e.fileType,file_name:e.fileName,upload_method:e.uploadMethod,Duration:e.duration}}_uploadFile(e){return Wt(this,void 0,void 0,(function*(){return new Promise(((t,s)=>{this.httpRequest.request(e,((n,o)=>{n&&this.uploadFileTryCount<this.maxRetries&&this.shouldRetry(n)?(this.uploadFileTryCount++,this._uploadFile(e).then(t).catch(s)):(this.uploadFileTryCount=0,n?s(n):t(o))}))}))}))}shouldRetry(e){return!!e&&(5===Math.floor(e.statusCode/100)||!(!this.isTimeRelatedError(e)||!this._isClockOutOfSync(e)||(this._syncSystemClock(e),0)))}isTimeRelatedError(e){var t,s;try{const n=null===(t=e.error)||void 0===t?void 0:t.Code,o=null===(s=e.error)||void 0===s?void 0:s.Message;return"RequestTimeTooSkewed"===n||"AccessDenied"===n&&"Request has expired"===o}catch(e){return!1}}_isClockOutOfSync(e){var t,s,n;const o=(null===(t=e.headers)||void 0===t?void 0:t.date)||(null===(s=e.headers)||void 0===s?void 0:s.Date)||(null===(n=e.error)||void 0===n?void 0:n.ServerTime);if(!o)return!1;const i=Date.now(),r=Date.parse(o);return Math.abs(i+this.systemClockOffset-r)>=3e4}_syncSystemClock(e){var t,s,n;const o=(null===(t=e.headers)||void 0===t?void 0:t.date)||(null===(s=e.headers)||void 0===s?void 0:s.Date)||(null===(n=e.error)||void 0===n?void 0:n.ServerTime);if(o){const e=Date.now(),t=Date.parse(o);this.systemClockOffset=t-e}}_getRawOrUploadProxyUrl(e){const t=gs.getFileUploadProxy();let s=e;return t&&(s=e.replace(/^https:\/\/[^/]+/,t)),s}_isC2CConversation(e){return"C2C"===e.slice(0,3)}};const ps=["jpg","jpeg","gif","png","bmp","image","webp"],ms=20971520,fs={JPG:1,JPEG:1,GIF:2,PNG:3,BMP:4,UNKNOWN:255};class vs{constructor(e,t){this.instanceID=Zt(9999999),this.sizeType=e.type||0,this.type=0,this.size=e.size||0,this.width=e.width||0,this.height=e.height||0,this.imageUrl=gs.addAuthToUrl(e.imageUrl||e.url||""),this.url=gs.addAuthToUrl(e.url||t)}setSizeType(e){this.sizeType=e}setType(e){this.type=e}setImageUrl(e){e&&(this.imageUrl=gs.addAuthToUrl(e))}getImageUrl(){return this.imageUrl}}function _s(e){const{originUrl:t,originWidth:s,originHeight:n,min:o=198}=e,i=parseInt(s)||0,r=parseInt(n)||0,a={url:void 0,width:0,height:0};if((i<=r?i:r)<=o)a.url=t,a.width=i,a.height=r;else{r<=i?(a.width=Math.ceil(i*o/r),a.height=o):(a.width=o,a.height=Math.ceil(r*o/i));const e=t&&t.indexOf("?")>-1?`${t}&`:`${t}?`;a.url=198===o?`${e}imageView2/3/w/198/h/198`:`${e}imageView2/3/w/720/h/720`}return void 0===t?Yt(a,["url"]):a}class Is{constructor(e){this._imageMemoryURL="",this._percent=0,this.type=is;const{uuid:t,file:s,imageFormat:n,imageInfoArray:o=[]}=e;this._imageMemoryURL=this.createImageDataAsURL(s),this.content={imageFormat:n,uuid:t,imageInfoArray:[]},this.initImageInfoArray(o),this.autoFixUrl()}static parseServerPushElement(e){const{MsgContent:t}=e,{ImageFormat:s,ImageInfoArray:n,UUID:o}=t,i=function(e){return e.map((e=>({size:e.Size,type:e.Type,width:e.Width,height:e.Height,url:e.URL})))}(n);return new Is({imageFormat:s,imageInfoArray:i,uuid:o})}createImageDataAsURL(e){let t="";const{IN_MINI_APP:s,IN_RN_APP:n,IN_BROWSER:o}=gs.getPlatformFlags();return e?((s||n)&&(t=e.url),o&&(t=window.URL.createObjectURL(e)),t):t}initImageInfoArray(e=[]){const t={type:0,size:0,width:0,height:0,url:""};for(let s=0;s<3;s++){const n=e[s]||Object.assign({},t),o=new vs(n,this._imageMemoryURL);o.setSizeType(s+1),o.setType(s),this.addImageInfo(o)}this.updateAccessSideImageInfoArray()}autoFixUrl(){const e=["http","https"];this.content.imageInfoArray.forEach((t=>{if(!t.url||""===t.imageUrl)return;const[s,...n]=t.imageUrl.split("://"),o=n.join("://");e.includes(s)||t.setImageUrl(`https://${o}`)}))}updatePercent(e){this._percent=Math.min(e,1)}updateImageFormat(e){this.content.imageFormat=fs[e.toUpperCase()]||fs.UNKNOWN}addImageInfo(e){this.content.imageInfoArray.length>=3||this.content.imageInfoArray.push(e)}updateImageInfoArray(e){const t=this.content.imageInfoArray.length;let s;for(let n=0;n<t;n++)s=this.content.imageInfoArray[n],e[n].size&&(s.size=e[n].size),e[n].url&&s.setImageUrl(e[n].url),e[n].width&&(s.width=e[n].width),e[n].height&&(s.height=e[n].height)}updateAccessSideImageInfoArray(){const[e]=this.content.imageInfoArray;e&&0!==e.width&&0!==e.height&&(function(e){const t=e[2];e[2]=e[1],e[1]=t;for(let t=0;t<e.length;t++)e[t].setType(t)}(this.content.imageInfoArray),Object.assign(this.content.imageInfoArray[2],_s({originWidth:e.width,originHeight:e.height,min:720})))}validateBeforeSend(){const[e]=this.content.imageInfoArray,t=!!e&&""!==e.imageUrl&&0!==e.size;return{isValid:t,error:t?null:{message:"content can not be empty"}}}convertToBackendFormat(){const{uuid:e,imageFormat:t,imageInfoArray:s}=this.content;return{MsgType:this.type,MsgContent:{ImageFormat:t,ImageInfoArray:this.parseImageInfoArray(s),UUID:e}}}parseImageInfoArray(e){return e.map((e=>({InstanceId:e.instanceID,Type:e.sizeType,MsgType:e.type,Size:e.size,Width:e.width,Height:e.height,URL:gs.removeAuthToUrl(e.imageUrl)})))}}var ys=new class{constructor(){this._messageOptionsMap=new Map}init(e){var t;this._core=e;const{notificationCenter:s,helper:n,InnerEvent:o,message:i}=e;n.registerApi("createImageMessage",this),null===(t=null==i?void 0:i.messageFactory)||void 0===t||t.registerElementClass(is,Is),s.subscribeInnerEvent(o.DESTROY,this._dispose,this)}createImageMessage(e){var t,s,n,o,i;try{const o=this._core.ssoLog.createSSOLogData({method:"createImageMessage"});console.log(`${us} createImageMessage options:`,e);const i=null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userId,r=null===(n=null===(s=this._core)||void 0===s?void 0:s.message.messageFactory)||void 0===n?void 0:n.createMessage(Object.assign(Object.assign({},e),{from:i})),a=this._processImage(e);e.payload.file=a;const c={imageFormat:fs.UNKNOWN,uuid:gs.generateUUID(a),file:a,imageInfoArray:[]},u=new Is(c);return r.setElement(u),this._messageOptionsMap.set(r.clientSequence,e),console.log(`${us} createImageMessage OK imageMessage:`,r),o.end(),r}catch(e){throw null===(i=(o=this._core.ssoLog.getSSOLogData("createImageMessage")).setError)||void 0===i||i.call(o,e).end(),console.error(`${us} createImageMessage error:`,e),e}}upload(e){return Wt(this,void 0,void 0,(function*(){console.log(`${us} uploadImage message:`,e);const t=e.getElements()[0],{file:s}=this._messageOptionsMap.get(e.clientSequence).payload;this._validateBeforeUploadImage(s);const n=yield this._performImageUpload(t,e,s),o=this._generateImageInfo(n);return t.updateImageInfoArray(o),e}))}_performImageUpload(e,t,s){return Wt(this,void 0,void 0,(function*(){const{to:n}=t,o={uploadFileType:1,file:s,to:n,message:t,onProgress:s=>{var n,o;e.updatePercent(s),null===(o=null===(n=this._messageOptionsMap.get(t.clientSequence))||void 0===n?void 0:n.onProgress)||void 0===o||o.call(n,s)}},{uploadOptions:i,response:r}=yield hs.uploadToCOS(o);return this._parseResponse(i,r)}))}_generateImageInfo(e){console.log(`${us} generateImageInfo`);const{location:t,fileSize:s,width:n,height:o,smallImageUrl:i,smallImageWidth:r,smallImageHeight:a,largeImageUrl:c,largeImageWidth:u,largeImageHeight:l,imageInfoArray:d}=e,g=gs.addAuthToUrl(t),h={size:s,url:g,width:n,height:o};return(null==d?void 0:d.length)>0?this._processImageInfoArray(d,s):i&&c?[Object.assign({},h),{largeImageUrl:c,largeImageWidth:u,largeImageHeight:l},{smallImageUrl:i,smallImageWidth:r,smallImageHeight:a}]:[Object.assign({},h),this._generateThumbInfo(g,n,o,720),this._generateThumbInfo(g,n,o,198)]}_generateThumbInfo(e,t,s,n){return _s({originUrl:e,originWidth:t,originHeight:s,min:n})}_processImageInfoArray(e,t){let s,n,o;for(const i of e)1===i.type?(n=i,n.size=t):2===i.type?(o=i,o.size=t):(s=i,s.size=t);return[Object.assign({},s),Object.assign({},o),Object.assign({},n)]}_parseResponse(e,t){return Wt(this,void 0,void 0,(function*(){console.log(`${us} parseResponse`);try{const{thumbUrl:s,largeUrl:n,downloadUrl:o}=e;if(s&&n&&(yield this._getImageInfoByUrl(s,t,"thumb"),yield this._getImageInfoByUrl(n,t,"large")),gs.isSimpleCos()&&!gs.isPrivateNetWork()&&(yield this._getImageInfoArray(o,t),null==t?void 0:t.uploadIP)){const e=this._extractDomainFromUrl(o);e&&(yield this._getDownloadIP(e,t))}return t}catch(e){throw console.error("Failed to parse response:",e),e}}))}_extractDomainFromUrl(e){try{const t=e.match(/:\/\/([^\/]+)/);return t?t[1]:null}catch(e){return console.warn("Failed to extract domain from URL:",e),null}}_getImageInfoByUrl(e,t,s){return Wt(this,void 0,void 0,(function*(){try{const n=gs.addAuthToUrl(e),{width:o=0,height:i=0}=yield gs.probeImageWidthHeight(n);t.width=o,t.height=i,"thumb"===s?(t.smallImageUrl=e,t.smallImageWidth=o,t.smallImageHeight=i):(t.largeImageUrl=e,t.largeImageWidth=o,t.largeImageHeight=i)}catch(e){console.warn(`Failed to get ${s} image info:`,e)}}))}_validateBeforeUploadImage(e){var t;const{ChatError:s}=null===(t=this._core)||void 0===t?void 0:t.helper;if(!e)throw new s({code:2251});this._checkImageType(e),this._checkImageSize(e)}_processImage(e){var t;try{const{IN_MINI_APP:s}=null===(t=this._core)||void 0===t?void 0:t.utils;let{file:n}=e.payload;return n=s?this._processMiniAppImageFile(n):this._processWebImageFile(n),n}catch(e){throw console.warn(`${us} _processImage error:`,e),e}}_processMiniAppImageFile(e){Qt(e)&&console.warn("FileUnsupportedInMiniApp","createImageMessage");const t=e.tempFiles[0].path||e.tempFiles[0].tempFilePath;return{url:t,name:t.slice(t.lastIndexOf("/")+1),size:e.tempFiles&&e.tempFiles[0].size||1,type:t.slice(t.lastIndexOf(".")+1).toLowerCase()}}_processWebImageFile(e){var t;const{ChatError:s}=null===(t=this._core)||void 0===t?void 0:t.helper,n=gs.extractFileFromInput(e);if(!n)throw new s({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});return n}_getDownloadIP(e,t){return Wt(this,void 0,void 0,(function*(){const s=`${us} getDownloadIP domainName: ${e}`;try{const n=yield function(e,t){return Wt(this,void 0,void 0,(function*(){try{const{helper:s,channel:n}=t,o="im_cos_msg.get_final_ip",i={str_domain:e},r=s.generateProtocolData({servcmd:o,data:i}),a=`${r.head.seq}${o}`;return yield n.sendPacket(r,{requestId:a})}catch(e){throw console.warn("getFinalIP error:",e),e}}))}(e,this._core);if(!n||!n.str_final_ip)return;console.log(`${s} ok. downloadIP:${n}`);const o=t.location.split("/");o[0]=n.str_final_ip,t.location=o.join("/")}catch(e){console.warn(e)}}))}_getImageInfoArray(e,t){return Wt(this,void 0,void 0,(function*(){const s=`${us}._getImageInfoArray`;try{const n=yield function(e,t){return Wt(this,void 0,void 0,(function*(){try{const{helper:s,channel:n}=t,o="im_cos_msg.get_imageinfo",i={str_image_url:e},r=s.generateProtocolData({servcmd:o,data:i}),a=`${r.head.seq}${o}`;return yield n.sendPacket(r,{requestId:a})}catch(e){throw console.warn("getImageInfo error:",e),e}}))}(e,this._core);return t.imageInfoArray=this._processImageInfoResponse(n),console.log(`${s} ok`),t}catch(e){throw t.imageInfoArray=void 0,console.warn(`${s} failed, error:`,e),e}}))}_processImageInfoResponse(e){if(!e)return[];const{rpt_msg_image_info:t}=e;return t.map((e=>({type:e.uint32_image_type,url:e.str_url,width:e.uint32_width,height:e.uint32_height,imageFormat:e.str_image_format})))}_checkImageType(e){const{utils:t,helper:s}=this._core;let n="";if(t.IN_MINI_APP&&(n=e.url.slice(e.url.lastIndexOf(".")+1)),t.IN_BROWSER&&(n=e.name.slice(e.name.lastIndexOf(".")+1)),ps.indexOf(n.toLowerCase())<0)throw new s.ChatError({code:2252})}_checkImageSize(e){const{utils:t,helper:s}=this._core;let n=0;if(t.IN_MINI_APP,n=e.size,0===n)throw new s.ChatError({code:2108});if(n>=ms)throw new s.ChatError({message:`File size exceeds limit: ${ns(ms)}`})}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};const Es="2.5.0",Ss="1.18.0",Cs=104857600;function Ms(e,t){const s=e.split("."),n=t.split("."),o=Math.max(s.length,n.length);for(;s.length<o;)s.push("0");for(;n.length<o;)n.push("0");for(let e=0;e<o;e++){const t=parseInt(s[e]),o=parseInt(n[e]);if(t>o)return 1;if(t<o)return-1}return 0}class Ts{constructor(e){this.type=as,this.uploadProgress=0;const t=this._getFileInfo(e);this.content={downloadFlag:2,fileUrl:gs.addAuthToUrl(e.url||e.fileUrl)||"",uuid:e.uuid,fileName:t.name||"",fileSize:t.size||0}}static parseServerPushElement(e){const{MsgContent:t}=e,{Download_Flag:s,Url:n,FileName:o,FileSize:i,UUID:r}=t;return new Ts({downloadFlag:s,url:n,fileName:o,fileSize:i,uuid:r})}updatePercent(e){this.uploadProgress=Math.min(e,1)}updateFileUrl(e){this.content.fileUrl=e}validateBeforeSend(){const e=""!==this.content.fileUrl&&""!==this.content.fileName&&this.content.fileSize>0;return{isValid:e,error:e?null:{message:"content can not be empty"}}}convertToBackendFormat(){const{uuid:e,downloadFlag:t,fileUrl:s,fileName:n,fileSize:o}=this.content;return{MsgType:this.type,MsgContent:{Download_Flag:t,Url:gs.removeAuthToUrl(s),FileName:n,FileSize:o,UUID:e}}}_getFileInfo(e){if(e.fileName&&e.fileSize)return{size:e.fileSize,name:e.fileName};const{file:t}=e;return t?(gs.getPlatform().IN_UNI_NATIVE_APP&&this._processNativeAppFile(t),{size:t.size,name:t.name}):{size:0,name:""}}_processNativeAppFile(e){if(e.path&&e.path.includes(".")){const t=e.path.slice(e.path.lastIndexOf(".")+1).toLowerCase();e.type=t,e.name||(e.name=`${Zt(999999)}.${t}`)}e.name||(e.type="",e.name=e.path.slice(e.path.lastIndexOf("/")+1).toLowerCase()),e.suffix&&(e.type=e.suffix),e.url||(e.url=e.path)}}var Ds=new class{constructor(){this._messageOptionsMap=new Map}init(e){var t;this._core=e;const{notificationCenter:s,helper:n,InnerEvent:o,message:i}=e;n.registerApi("createFileMessage",this),null===(t=null==i?void 0:i.messageFactory)||void 0===t||t.registerElementClass(as,Ts),s.subscribeInnerEvent(o.DESTROY,this._dispose,this)}createFileMessage(e){var t,s,n,o,i;try{const o=this._core.ssoLog.createSSOLogData({method:"createFileMessage"});console.log(`${us} createFileMessage options:`,e),this._checkVersion();const i=this._processFile(e.payload.file);e.payload.file=i;const r=null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userId,a=null===(n=null===(s=this._core)||void 0===s?void 0:s.message.messageFactory)||void 0===n?void 0:n.createMessage(Object.assign(Object.assign({},e),{from:r})),c={uuid:gs.generateUUID(i),file:i},u=new Ts(c);return a.setElement(u),this._messageOptionsMap.set(a.clientSequence,e),console.log(`${us} createFileMessage success fileMessage:`,a),o.end(),a}catch(e){throw null===(i=(o=this._core.ssoLog.getSSOLogData("createFileMessage")).setError)||void 0===i||i.call(o,e).end(),console.error(`${us} createFileMessage error:`,e),e}}upload(e){return Wt(this,void 0,void 0,(function*(){console.log(`${us} uploadFile message:`,e);const{file:t}=this._messageOptionsMap.get(e.clientSequence).payload;this._validateBeforeUploadFile(t);const s=e.getElements()[0],n=yield this._performFileUpload(s,e,t),o=gs.addAuthToUrl(null==n?void 0:n.location);return s.updateFileUrl(o),e}))}_validateBeforeUploadFile(e){var t;const{ChatError:s}=null===(t=this._core)||void 0===t?void 0:t.helper;if(!e)throw new s({code:2401});if(e.size>Cs)throw new s({message:`File size exceeds limit: ${ns(Cs)}`});if(0===e.size)throw new s({code:2108})}_performFileUpload(e,t,s){return Wt(this,void 0,void 0,(function*(){const{to:n}=t,o={uploadFileType:1,file:s,to:n,message:t,onProgress:s=>{var n,o;e.updatePercent(s),null===(o=null===(n=this._messageOptionsMap.get(t.clientSequence))||void 0===n?void 0:n.onProgress)||void 0===o||o.call(n,s)}},{response:i}=yield hs.uploadToCOS(o);return i}))}_processFile(e){var t,s;const{IN_BROWSER:n,IN_RN_APP:o,IN_WX_MINI_APP:i,IN_QQ_MINI_APP:r,IN_UNI_NATIVE_APP:a}=null===(t=this._core)||void 0===t?void 0:t.utils,{ChatError:c}=null===(s=this._core)||void 0===s?void 0:s.helper;if(n||a){const t=gs.extractFileFromInput(e);if(!t)throw new c({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});return t}if(i||r){const{tempFiles:t}=e;return Object.assign(Object.assign({},t[0]),{url:t[0].path})}return o?Object.assign(Object.assign({},e),{url:e.uri}):e}_checkVersion(){var e,t;const{MINI_APP_NAMESPACE:s,IN_MINI_APP:n,IN_WX_MINI_APP:o,IN_QQ_MINI_APP:i,IN_UNI_NATIVE_APP:r}=null===(e=this._core)||void 0===e?void 0:e.utils,{ChatError:a}=null===(t=this._core)||void 0===t?void 0:t.helper;if(n){if(!(o||i||r))throw new a({message:"Unsupported mini app environment"});const e=s.getSystemInfoSync().SDKVersion;if(o&&Ms(e,Es)<0)throw new a({message:`WXChooseMessageFile requires SDK version ${Es} or higher`});if(i&&Ms(e,Ss)<0)throw new a({message:`QQChooseMessageFile requires SDK version ${Ss} or higher`})}}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};const bs=["mp4","quicktime","mov"],Os=104857600;class Ls{constructor(e){this.type=cs,this.uploadProgress=0;const t="number"==typeof(null==e?void 0:e.videoSecond)?null==e?void 0:e.videoSecond:0;this.content={remoteVideoUrl:gs.addAuthToUrl(e.remoteVideoUrl||e.videoUrl||""),videoFormat:e.videoFormat,videoSecond:parseInt(null==t?void 0:t.toString(),10),videoSize:e.videoSize,videoUrl:gs.addAuthToUrl(e.videoUrl),videoDownloadFlag:2,videoUUID:e.videoUUID,thumbUUID:e.thumbUUID,thumbFormat:e.thumbFormat,thumbWidth:e.thumbWidth,snapshotWidth:e.thumbWidth,thumbHeight:e.thumbHeight,snapshotHeight:e.thumbHeight,thumbSize:e.thumbSize,snapshotSize:e.thumbSize,thumbDownloadFlag:2,thumbUrl:gs.addAuthToUrl(e.thumbUrl),snapshotUrl:gs.addAuthToUrl(e.thumbUrl)}}static parseServerPushElement(e){const{MsgContent:t}=e,{VideoUrl:s,VideoFormat:n,VideoSecond:o,VideoSize:i,VideoDownloadFlag:r,VideoUUID:a,ThumbUUID:c,ThumbFormat:u,ThumbWidth:l,SnapshotWidth:d,ThumbHeight:g,SnapshotHeight:h,ThumbSize:p,SnapshotSize:m,ThumbDownloadFlag:f,ThumbUrl:v,SnapshotUrl:_}=t;return new Ls({videoUrl:s,videoFormat:n,videoSecond:o,videoSize:i,videoDownloadFlag:r,videoUUID:a,thumbUUID:c,thumbFormat:u,thumbWidth:l,snapshotWidth:d,thumbHeight:g,snapshotHeight:h,thumbSize:p,snapshotSize:m,thumbDownloadFlag:f,thumbUrl:v,snapshotUrl:_})}updatePercent(e){this.uploadProgress=Math.min(e,1)}updateVideoUrl(e){e&&(this.content.remoteVideoUrl=e)}updateSnapshotInfo(e){const{snapshotUrl:t,snapshotWidth:s,snapshotHeight:n}=e;gs.isEmpty(t)||(this.content.thumbUrl=this.content.snapshotUrl=t),gs.isEmpty(s)||(this.content.thumbWidth=this.content.snapshotWidth=Number(s)),gs.isEmpty(n)||(this.content.thumbHeight=this.content.snapshotHeight=Number(n))}validateBeforeSend(){const e=""!==this.content.remoteVideoUrl;return{isValid:e,error:e?null:{message:"content can not be empty"}}}convertToBackendFormat(){const{remoteVideoUrl:e,videoFormat:t,videoSecond:s,videoSize:n,videoDownloadFlag:o,videoUUID:i,thumbUUID:r,thumbFormat:a,thumbWidth:c,snapshotWidth:u,thumbHeight:l,snapshotHeight:d,thumbSize:g,snapshotSize:h,thumbDownloadFlag:p,thumbUrl:m,snapshotUrl:f}=this.content;return{MsgType:this.type,MsgContent:{VideoUrl:gs.removeAuthToUrl(e),VideoFormat:t,VideoSecond:s,VideoSize:n,VideoDownloadFlag:o,VideoUUID:i,ThumbUUID:r,ThumbFormat:a,ThumbWidth:c,SnapshotWidth:u,ThumbHeight:l,SnapshotHeight:d,ThumbSize:g,SnapshotSize:h,ThumbDownloadFlag:p,ThumbUrl:gs.removeAuthToUrl(m),SnapshotUrl:gs.removeAuthToUrl(f)}}}}var As=new class{constructor(){this._messageOptionsMap=new Map}init(e){var t;this._core=e;const{notificationCenter:s,helper:n,InnerEvent:o,message:i}=e;n.registerApi("createVideoMessage",this),null===(t=null==i?void 0:i.messageFactory)||void 0===t||t.registerElementClass(cs,Ls),s.subscribeInnerEvent(o.DESTROY,this._dispose,this)}createVideoMessage(e){var t,s,n,o,i;try{const o=this._core.ssoLog.createSSOLogData({method:"createVideoMessage"});console.log(`${us} createVideoMessage options:`,e);const i=this._processVideo(e);e.payload.file=i;const r=null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userId,a=null===(n=null===(s=this._core)||void 0===s?void 0:s.message.messageFactory)||void 0===n?void 0:n.createMessage(Object.assign(Object.assign({},e),{from:r})),c={videoFormat:i.videoFile.type,videoSecond:ss(i.videoFile.second,0),videoSize:i.videoFile.size,remoteVideoUrl:"",videoUrl:i.videoFile.url,videoUUID:gs.generateUUID(i.videoFile),thumbUUID:gs.generateUUID(i.videoFile,"jpg"),thumbWidth:i.width||200,thumbHeight:i.height||200,thumbUrl:i.thumbUrl,thumbSize:i.thumbSize,thumbFormat:"jpg"},u=new Ls(c);return a.setElement(u),this._messageOptionsMap.set(a.clientSequence,e),o.end(),a}catch(e){throw null===(i=(o=this._core.ssoLog.getSSOLogData("createVideoMessage")).setError)||void 0===i||i.call(o,e).end(),console.error(`${us} createVideoMessage error:`,e),e}}upload(e){return Wt(this,void 0,void 0,(function*(){console.log(`${us} uploadVideo message:`,e);const t=e.getElements()[0],{file:s}=this._messageOptionsMap.get(e.clientSequence).payload;this._validateBeforeUploadVideo(s);const n=yield this._performVideoUpload(t,e,s),{location:o,snapshotInfo:i}=n,r=gs.addAuthToUrl(o);return t.updateVideoUrl(r),gs.isEmpty(i)||t.updateSnapshotInfo(i),e}))}_validateBeforeUploadVideo(e){var t;const{ChatError:s}=null===(t=this._core)||void 0===t?void 0:t.helper;if(e.videoFile.size>Os)throw new s({message:`File size exceeds limit: ${ns(Os)}`});if(0===e.videoFile.size)throw new s({code:2108});if(-1===bs.indexOf(e.videoFile.type))throw new s({code:2352})}_performVideoUpload(e,t,s){return Wt(this,void 0,void 0,(function*(){const{to:n}=t,o={uploadFileType:2,file:s,to:n,message:t,onProgress:s=>{var n,o;e.updatePercent(s),null===(o=null===(n=this._messageOptionsMap.get(t.clientSequence))||void 0===n?void 0:n.onProgress)||void 0===o||o.call(n,s)}},{response:i,uploadOptions:r}=yield hs.uploadToCOS(o);return{snapshotInfo:yield this._getSnapshotInfoByUrl(r.requestSnapshotUrl),location:i.location}}))}_processVideo(e){var t,s;try{const{ChatError:n}=null===(t=this._core)||void 0===t?void 0:t.helper,{IN_MINI_APP:o,IN_BROWSER:i}=null===(s=this._core)||void 0===s?void 0:s.utils;let{file:r}=e.payload,a={};if(o&&(a=this._processMiniVideoFile(r)),i){const e=gs.extractFileFromInput(r);if(!e)throw new n({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});r=e,a=this._processWebVideoFile(r)}return r.videoFile=a,r.thumbUrl="",r.thumbSize=0,r}catch(e){throw console.warn(`${us} _processFile error:`,e),e}}_processMiniVideoFile(e){var t,s;const{IN_ALIPAY_MINI_APP:n}=null===(t=this._core)||void 0===t?void 0:t.utils,{ChatError:o}=null===(s=this._core)||void 0===s?void 0:s.helper;if(n)throw new o({message:"VideoUnsupportedInAlipay"});if(Qt(e))throw new o({message:"FileUnsupportedInMiniApp"});return Array.isArray(e.tempFiles)&&(e=e.tempFiles[0]),{url:e.tempFilePath,name:e.tempFilePath.slice(e.tempFilePath.lastIndexOf("/")+1),size:e.size||1,second:e.duration||0,type:e.tempFilePath.slice(e.tempFilePath.lastIndexOf(".")+1).toLowerCase()}}_processWebVideoFile(e){const{name:t,size:s=1,duration:n=0,type:o}=e,i=o.split("/")[1];return{url:window.URL.createObjectURL(e),name:t,size:s,second:n,type:i}}_getSnapshotInfoByUrl(e){return Wt(this,void 0,void 0,(function*(){try{console.log(`${us} _getSnapshotInfoByUrl url:`,e);const t={version:1,platform:gs.getPlatform(),cover_name:ts(Zt(99999)),snapshot_url:e},s=yield function(e,t){return Wt(this,void 0,void 0,(function*(){try{const s="im_cos_msg.video_cover",{helper:n,channel:o}=t,i=n.generateCosSpecifiedData({servcmd:s,data:e}),r=`${i.head.seq}${s}`;return yield o.sendPacket(i,{requestId:r})}catch(e){throw console.warn("getSnapshotInfo error:",e),e}}))}(t,this._core),{download_url:n}=s||{};if(console.log(`${us} _getSnapshotInfoByUrl OK snapshotUrl:`,n),gs.isEmpty(n))return{};const o=gs.addAuthToUrl(n),{width:i=0,height:r=0}=yield gs.probeImageWidthHeight(o);return{snapshotUrl:o,snapshotWidth:i,snapshotHeight:r}}catch(e){throw console.error(`${us} _getSnapshotInfoByUrl error:`,e),e}}))}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};class Us{constructor(e){this.uploadProgress=0,this.type=rs,this.content={downloadFlag:2,second:e.second,size:e.size,url:gs.addAuthToUrl(e.url),remoteAudioUrl:gs.addAuthToUrl(e.url||""),uuid:e.uuid}}static parseServerPushElement(e){const{MsgContent:t}=e,{Url:s,Download_Flag:n,Second:o,Size:i,UUID:r}=t;return new Us({url:s,downloadFlag:n,second:o,size:i,uuid:r})}updatePercent(e){this.uploadProgress=Math.min(e,1)}updateAudioUrl(e){this.content.remoteAudioUrl=e}validateBeforeSend(){const e=""!==this.content.remoteAudioUrl;return{isValid:e,error:e?null:{message:"content can not be empty"}}}convertToBackendFormat(){const{uuid:e,downloadFlag:t,remoteAudioUrl:s,size:n,second:o}=this.content;return{MsgType:this.type,MsgContent:{Url:gs.removeAuthToUrl(s),Download_Flag:t,Second:o,Size:n,UUID:e}}}}const Rs=20971520;var Ps=new class{constructor(){this._messageOptionsMap=new Map}init(e){var t;this._core=e;const{notificationCenter:s,helper:n,InnerEvent:o,message:i}=e;n.registerApi("createAudioMessage",this),null===(t=null==i?void 0:i.messageFactory)||void 0===t||t.registerElementClass(rs,Us),s.subscribeInnerEvent(o.DESTROY,this._dispose,this)}createAudioMessage(e){var t,s,n,o,i;try{const o=this._core.ssoLog.createSSOLogData({method:"createAudioMessage"});console.log(`${us} createAudioMessage options:`,e);let{file:i}=e.payload;i=this._processAudioFile(e.payload.file),e.payload.file=i;const r=null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userId,a=null===(n=null===(s=this._core)||void 0===s?void 0:s.message.messageFactory)||void 0===n?void 0:n.createMessage(Object.assign(Object.assign({},e),{from:r})),c={second:Math.floor((i.duration||i.second)/1e3),size:i.fileSize||i.size||1,url:i.tempFilePath||i.uri,uuid:gs.generateUUID(i)},u=new Us(c);return a.setElement(u),this._messageOptionsMap.set(a.clientSequence,e),o.end(),a}catch(e){throw null===(i=(o=this._core.ssoLog.getSSOLogData("createAudioMessage")).setError)||void 0===i||i.call(o,e).end(),console.error(`${us} createAudioMessage error:`,e),e}}upload(e){return Wt(this,void 0,void 0,(function*(){console.log(`${us} uploadAudio message:`,e);const{file:t}=this._messageOptionsMap.get(e.clientSequence).payload;this._validateBeforeUploadAudio(t);const s=e.getElements()[0],n=yield this._performAudioUpload(s,e,t),o=gs.addAuthToUrl(null==n?void 0:n.location);return s.updateAudioUrl(o),e}))}_validateBeforeUploadAudio(e){var t;const{ChatError:s}=null===(t=this._core)||void 0===t?void 0:t.helper;if(!e)throw new s({code:2300});if(e.size>Rs)throw new s({message:`File size exceeds limit: ${ns(Rs)}`});if(0===e.size)throw new s({code:2108})}_performAudioUpload(e,t,s){return Wt(this,void 0,void 0,(function*(){const{to:n}=t,o={uploadFileType:3,file:s,to:n,message:t,onProgress:s=>{var n,o;e.updatePercent(s),null===(o=null===(n=this._messageOptionsMap.get(t.clientSequence))||void 0===n?void 0:n.onProgress)||void 0===o||o.call(n,s)}},{response:i}=yield hs.uploadToCOS(o);return i}))}_processAudioFile(e){var t;const{IN_MINI_APP:s,IN_BROWSER:n}=null===(t=this._core)||void 0===t?void 0:t.utils;return s?this._processMiniFile(e):n?this._processWebFile(e):void 0}_processMiniFile(e){return{url:e.tempFilePath,name:e.tempFilePath.slice(e.tempFilePath.lastIndexOf("/")+1),size:e.fileSize,second:e.duration,type:e.tempFilePath.slice(e.tempFilePath.lastIndexOf(".")+1).toLowerCase()}}_processWebFile(e){if(e.tempFilePath||e.uri)return e;const t=URL.createObjectURL(e);return e.tempFilePath=t,e}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.DESTROY,this._dispose,this)}};const Gs={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},onProgress:{required:!1,rules:["function"],allowEmpty:!1}},ws={createImageMessage:Gs,createAudioMessage:Gs,createVideoMessage:Gs,createFileMessage:Gs},Ns={createImageMessage:!0,createAudioMessage:!0,createVideoMessage:!0,createFileMessage:!0},ks={[is]:ys,[as]:Ds,[cs]:As,[rs]:Ps};var Fs=new class{install(e){this._core=e,ys.init(e),Ds.init(e),As.init(e),Ps.init(e),hs.init(e),gs.init(e),e.helper.registerApi("sendMessage",this),e.helper.registerValidateConfig({auth:Ns,params:ws})}sendMessage(e,t){return Wt(this,void 0,void 0,(function*(){var s,n,o;try{return console.log("sendMessage message:",e),yield this._upload(e),yield null===(o=null===(n=null===(s=this._core)||void 0===s?void 0:s.message)||void 0===n?void 0:n.messageSender)||void 0===o?void 0:o.sendMessage(e,t)}catch(e){throw console.error("sendMessage error:",e),e}}))}_upload(e){return Wt(this,void 0,void 0,(function*(){var t,s;if(!0!==e._relayFlag)try{const t=ks[e.type];if(t){const s=this._core.ssoLog.createSSOLogData({method:"upload"});s.setLogInfo({message:`type:${e.type}`}),yield t.upload(e),s.end()}}catch(n){throw e.status=ds.FAIL,n instanceof Error&&(n.data={message:e}),this._core.message.messageStore.storeConversationMessage(e),null===(s=(t=this._core.ssoLog.getSSOLogData("upload")).setError)||void 0===s||s.call(t,n).end(),n}}))}};function $s(e,t,s,n){return new(s||(s=Promise))((function(o,i){function r(e){try{c(n.next(e))}catch(e){i(e)}}function a(e){try{c(n.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(r,a)}c((n=n.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const xs="friend",js=100,Vs="Tag_SNS_IM_",qs={GROUP:`${Vs}Group`,REMARK:`${Vs}Remark`,ADDSOURCE:`${Vs}AddSource`,ADDWORDING:`${Vs}Wording`,ADDTIME:`${Vs}AddTime`},Hs=e=>void 0===e;function Bs(e,t){return $s(this,void 0,void 0,(function*(){return function(e){return Ys(e,"ResultItem",(e=>({to:e.To_Account,resultCode:e.ResultCode,resultInfo:e.ResultInfo})))}(yield t.common.buildAndSendPacket({servcmd:"sns.friend_update",data:e}))}))}function Ks(e,t){return $s(this,void 0,void 0,(function*(){return function(e){return Ys(e,"InfoItem",(e=>({userID:e.To_Account,relation:e.Relation,resultCode:e.ResultCode,resultInfo:e.ResultInfo})))}(yield t.common.buildAndSendPacket({servcmd:"sns.friend_check",data:e}))}))}function Ys(e,t="ResultItem",s=e=>({userID:e.To_Account,resultCode:e.ResultCode,resultInfo:e.ResultInfo})){const{[t]:n=[],ActionStatus:o,ErrorCode:i,ErrorInfo:r,ErrorDisplay:a}=e;return{resultList:n.map(s),actionStatus:o,errorCode:i,errorInfo:r,errorDisplay:a}}const Ws={[qs.REMARK]:(e,t)=>{e.remark=t},[qs.GROUP]:(e,t)=>{e.groupList=t?JSON.parse(JSON.stringify(t)):[]},[qs.ADDSOURCE]:(e,t)=>{e.source=t},[qs.ADDWORDING]:(e,t)=>{e.wording=t},[qs.ADDTIME]:(e,t)=>{e.addTime=t}};let zs=class{constructor(e){var t;this.userID="",this.source="",this.wording="",this.remark="",this.addTime=0,this.groupList=[],this.friendCustomField=[];const{userID:s,tagValueList:n=[],core:o}=e,i=null===(t=o.user.userProfile)||void 0===t?void 0:t.createProfile(s,n);this.userID=s,this.profile=i,n.forEach((e=>{const{tag:t,value:s}=e;t.indexOf("Tag_Profile_Custom")>-1&&this.friendCustomField.push({key:t,value:s});const n=Ws[t];null==n||n(this,s)}))}update(e){const t=[];this.friendCustomField.forEach((e=>{t.push(e.key)})),e.forEach((e=>{const{tag:s,value:n}=e;s.indexOf("Tag_Profile_Custom")>-1&&(t.indexOf(s)>-1?this.friendCustomField.forEach((e=>{e.key===s&&(e.value=n)})):this.friendCustomField.push({key:s,value:n}));const o=Ws[s];null==o||o(this,n)}))}};var Js=new class{constructor(){this._friendMap=new Map,this._startIndex=0,this._standardSequence=0,this._customSequence=0}init(e){this._core=e;const{helper:t,constants:s}=e;t.registerApi("getFriendList",this,"getFriendListFromCache"),t.registerApi("getFriendProfile",this),t.registerApi("addFriend",this),t.registerApi("deleteFriend",this),t.registerApi("updateFriend",this),t.registerApi("checkFriend",this),t.registerWorkflowStep(s.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,s.WORKFLOW_STEP.FRIEND_RECOVER,this.syncFriendListFromServer,this)}getFriendListFromCache(){const e=[...this._friendMap.values()];return console.log(`${xs} getFriendListFromCache, data `,e),{code:0,data:e}}syncFriendListFromServer(){return $s(this,void 0,void 0,(function*(){var e;try{console.log(`${xs} syncFriendListFromServer`);const t={From_Account:null===(e=this._core.store.get("login"))||void 0===e?void 0:e.userId,StartIndex:this._startIndex,StandardSequence:this._standardSequence,CustomSequence:this._customSequence},s=yield function(e,t){return $s(this,void 0,void 0,(function*(){return function(e){const{UserDataItem:t=[],StandardSequence:s,CustomSequence:n,FriendNum:o,CompleteFlag:i,NextStartIndex:r,ActionStatus:a,ErrorCode:c,ErrorInfo:u,ErrorDisplay:l}=e;return{friendList:t.map((e=>{var t;return{userID:e.To_Account,tagValueList:null===(t=e.ValueItem)||void 0===t?void 0:t.map((e=>({tag:e.Tag,value:e.Value})))}})),standardSequence:s,customSequence:n,friendNumber:o,completeFlag:i,nextStartIndex:r,actionStatus:a,errorCode:c,errorInfo:u,errorDisplay:l}}(yield t.common.buildAndSendPacket({servcmd:"sns.friend_get",data:e}))}))}(t,this._core),{friendList:n,nextStartIndex:o,standardSequence:i,customSequence:r,completeFlag:a}=s;this._startIndex=o,this._standardSequence=i,this._customSequence=r,this._processFriendList(n),0===a?yield this.syncFriendListFromServer():(this._emitFriendListUpdated(),this._fetchFriendProfile()),console.log(`${xs} syncFriendListFromServer ok`)}catch(e){throw console.error(`${xs} syncFriendListFromServer error:`,e),e}}))}getFriendProfile(e){return $s(this,void 0,void 0,(function*(){var t;try{console.log(`${xs} getFriendProfile params:`,e);let{userIDList:s}=e;s.length>js&&(s=s.slice(0,js));const{friendUserIdList:n,unFriendUserIdList:o}=this._partitionByIsFriend(s),i=this._createNonFriendErrorList(o);if(0===n.length)return{code:0,data:{friendList:[],failureUserIDList:i}};const r={From_Account:null===(t=this._core.store.get("login"))||void 0===t?void 0:t.userId,To_Account:n},a=(yield function(e,t){return $s(this,void 0,void 0,(function*(){return function(e){const{InfoItem:t=[],ActionStatus:s,ErrorCode:n,ErrorInfo:o,ErrorDisplay:i}=e;return{friendProfileList:t.map((e=>{var t;return{userID:e.To_Account,resultCode:e.ResultCode,resultInfo:e.ResultInfo,relation:e.Relation,standardSequence:e.StandardSequence,customSequence:e.CustomSequence,profileItem:(null===(t=e.SnsProfileItem)||void 0===t?void 0:t.map((e=>({tag:e.Tag,value:e.Value}))))||[]}})),actionStatus:s,errorCode:n,errorInfo:o,errorDisplay:i}}(yield t.common.buildAndSendPacket({servcmd:"sns.friend_get_specified",data:e}))}))}(r,this._core))||{},{successProfiles:c,failedProfiles:u}=this._processFriendProfileResponse(a);return{code:0,data:{friendList:c,failureUserIDList:[...u,...i]}}}catch(e){throw console.error(`${xs} getFriendProfile error:`,e),e}}))}addFriend(e){return $s(this,void 0,void 0,(function*(){var t;try{console.log(`${xs} addFriend options:`,e);const{helper:s,OuterConstant:n,store:o}=this._core,{to:i,source:r,type:a,wording:c,remark:u,groupName:l}=e,d={From_Account:null===(t=o.get("login"))||void 0===t?void 0:t.userId,AddFriendItem:[{To_Account:i,AddSource:r,AddWording:c,GroupName:l,Remark:u}],AddType:a===n.SNS_ADD_TYPE_SINGLE?a:n.SNS_ADD_TYPE_BOTH},g=yield function(e,t){return $s(this,void 0,void 0,(function*(){return Ys(yield t.common.buildAndSendPacket({servcmd:"sns.friend_add",data:e}))}))}(d,this._core),{resultList:h=[]}=g,{userID:p,resultCode:m}=h[0];if(0===m)return console.log(`${xs} addFriend ok`),{code:0,data:{userID:p}};if(30539===m)return console.log(`${xs} addFriend wait for the other party to agree`),{code:0,data:{userID:p,code:m,message:"wait for the other party to agree"}};throw new s.ChatError({functionName:"addFriend",code:m})}catch(e){throw console.error(`${xs} addFriend error:`,e),e}}))}deleteFriend(e){return $s(this,void 0,void 0,(function*(){var t;try{console.log(`${xs} deleteFriend options:`,e);const{OuterConstant:s,store:n}=this._core;let{userIDList:o,type:i}=e;const r=null===(t=n.get("login"))||void 0===t?void 0:t.userId;o.length>1e3&&(console.warn(`${xs} deleteFriend the length of userIDList cannot exceed:`,1e3),o=o.slice(0,js));const{friendUserIdList:a,unFriendUserIdList:c}=this._partitionByIsFriend(o);if(0===a.length)return{code:0,data:{friendList:[],failureUserIDList:this._createNonFriendErrorList(c)}};const u={From_Account:r,To_Account:a,DeleteType:i===s.SNS_DELETE_TYPE_SINGLE?i:s.SNS_DELETE_TYPE_BOTH},l=yield function(e,t){return $s(this,void 0,void 0,(function*(){return Ys(yield t.common.buildAndSendPacket({servcmd:"sns.friend_delete",data:e}))}))}(u,this._core),{successUserIDList:d,failureUserIDList:g}=this._processOperationResult({resultList:l.resultList,includeRelation:!1});return console.log(`${xs} deleteFriend ok`),{code:0,data:{successUserIDList:d,failureUserIDList:g}}}catch(e){throw console.error(`${xs} deleteFriend error:`,e),e}}))}updateFriend(e){return $s(this,void 0,void 0,(function*(){var t;try{console.log(`${xs} updateFriend options:`,e);const{userID:s,remark:n,friendCustomField:o}=e,{helper:i,store:r}=this._core,a=null===(t=r.get("login"))||void 0===t?void 0:t.userId;if(!this._friendMap.has(s))throw new i.ChatError({functionName:"updateFriend",code:2700});const c={From_Account:a,UpdateItem:[{To_Account:s,SnsItem:this._buildSnsItemList(n,o)}]},u=yield Bs(c,this._core),{resultList:l}=u,{to:d,resultCode:g,resultInfo:h}=l[0];if(Hs(g)||0===g)return{code:0,data:this._updateLocalFriend({userID:d,remark:n,friendCustomField:o})};throw new i.ChatError({functionName:"updateFriend",code:g,message:h})}catch(t){throw console.error(`${xs} updateFriend error:`,t),t}}))}checkFriend(e){return $s(this,void 0,void 0,(function*(){var t;try{console.log(`${xs} checkFriend options:`,e);const{userIDList:s,type:n}=e,{OuterConstant:o,store:i}=this._core,r={From_Account:null===(t=i.get("login"))||void 0===t?void 0:t.userId,To_Account:s,CheckType:n===o.SNS_CHECK_TYPE_SINGLE?n:o.SNS_CHECK_TYPE_BOTH},a=yield Ks(r,this._core),{successUserIDList:c=[],failureUserIDList:u=[]}=this._processOperationResult({resultList:a.resultList,includeRelation:!0});return{code:0,data:{successUserIDList:c,failureUserIDList:u}}}catch(t){throw console.error(`${xs} checkFriend error:`,t),t}}))}dispose(){this.reset();const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.LOGOUT,this.reset,this)}reset(){this._friendMap.clear(),this._startIndex=0,this._standardSequence=0,this._customSequence=0}updateFriendList(e){return $s(this,void 0,void 0,(function*(){console.log(`${xs} updateFriendList data:`,e);const{addedFriendList:t=[],removedFriendList:s=[]}=e;t.length>0&&(t.forEach((e=>{const t=new zs({userID:e,core:this._core});this._friendMap.set(e,t)})),yield this.getFriendProfile({userIDList:t}),this._emitFriendListUpdated()),s.length>0&&(s.forEach((e=>{this._friendMap.delete(e)})),this._emitFriendListUpdated())}))}_processFriendList(e){this._core.utils.isEmpty(e)||e.forEach((e=>{const{userID:t,tagValueList:s}=e;if(this._isInvalidFriend(t))return;const n=new zs({userID:t,tagValueList:s,core:this._core});this._friendMap.set(t,n)}))}_isInvalidFriend(e){return"@TLS#NOT_FOUND"===e||""===e}_fetchFriendProfile(){return $s(this,void 0,void 0,(function*(){var e;try{console.log(`${xs} _fetchFriendProfile`);const t=[...this._friendMap.keys()],s=100,n=Math.ceil(t.length/s);for(let o=0;o<n;o++){const n=o*s,i=Math.min(n+s,t.length),r=t.slice(n,i),a=yield null===(e=this._core.user.userProfile)||void 0===e?void 0:e.getUserProfile({userIDList:r});a&&a.data&&a.data.forEach((e=>{const t=this._friendMap.get(e.userID);t&&(t.profile=e)})),this._emitFriendListUpdated()}}catch(e){throw console.error(`${xs} _fetchFriendProfile error:`,e),e}}))}_emitFriendListUpdated(){const{notificationCenter:e,OuterEvent:t}=this._core,s=Array.from(this._friendMap.values());console.log(`${xs} _emitFriendListUpdated friendList:`,s),e.emitOuterEvent(t.FRIEND_LIST_UPDATED,{name:t.FRIEND_LIST_UPDATED,data:s})}_updateCustomField(e,t){if(!Array.isArray(e)||!Array.isArray(t))return!1;let s=!1;return t.forEach((({key:t,value:n})=>{const o=e.find((e=>e.key===t));o?o.value!==n&&(o.value=n,s=!0):(e.push({key:t,value:n}),s=!0)})),s}_updateLocalFriend(e){const{userID:t,remark:s,friendCustomField:n}=e,o=this._friendMap.get(t);if(o)return Hs(s)||(o.remark=s),Array.isArray(n)&&n.length>0&&this._updateCustomField(o.friendCustomField,n),this._emitFriendListUpdated(),o}_processOperationResult(e){const{resultList:t,includeRelation:s=!1}=e,{isEmpty:n}=this._core.utils,o=[],i=[];return Array.isArray(t)&&!n(t)&&t.forEach((e=>{const{userID:t,relation:n,resultCode:r,resultInfo:a}=e;if(Hs(r)||0===r){const e={userID:t};s&&(e.code=0,e.relation=n),o.push(e)}else i.push({userID:t,code:r,message:a})})),{successUserIDList:o,failureUserIDList:i}}_createNonFriendErrorList(e){return e.map((e=>({userID:e,code:2700,message:"The specified userID is not my friend"})))}_buildSnsItemList(e,t){const s=[];return Hs(e)||s.push({Tag:qs.REMARK,Value:e}),Array.isArray(t)&&t.length>0&&t.forEach((e=>{s.push({tag:e.key,value:e.value})})),s}_processFriendProfileResponse(e){const{friendProfileList:t=[]}=e,s=[],n=[];return t.forEach((e=>{const{userID:t,resultCode:o,resultInfo:i,profileItem:r}=e;if(0===o){const e=new zs({userID:t,profile:r,core:this._core});s.push(e),this._friendMap.set(t,e)}else n.push({userID:t,code:o,message:i})})),console.log(`${xs} _processFriendProfileResponse successProfiles:`,s),{successProfiles:s,failedProfiles:n}}_partitionByIsFriend(e){const t=[],s=[];return e.forEach((e=>{this._friendMap.has(e)?t.push(e):s.push(e)})),console.log(`${xs} _partitionByIsFriend, friendUserIdList: ${t}, unFriendUserIdList: ${s}`),{friendUserIdList:t,unFriendUserIdList:s}}},Xs=new class{init(e){this._core=e;const{helper:t}=e;t.registerApi("getFriendApplicationList",this)}getFriendApplicationList(){return $s(this,void 0,void 0,(function*(){return console.log(`${xs} getFriendApplicationList`),{code:0,data:{friendApplicationList:[],unreadCount:0}}}))}},Qs=new class{init(e){this._core=e}};function Zs(e){return e&&0!==e.length?e.map((e=>({userID:e.To_Account,addBlackTimeStamp:e.AddBlackTimeStamp}))):[]}var en=new class{constructor(){this._blacklistMap=new Map,this._retryCount=0,this._startIndex=0}init(e){this._core=e;const{helper:t,constants:s}=e;t.registerApi("getBlacklist",this,"getBlacklistFromCache"),t.registerApi("addToBlacklist",this),t.registerApi("removeFromBlacklist",this),t.registerWorkflowStep(s.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,s.WORKFLOW_STEP.BLACKLIST_RECOVER,this.syncBlacklistFromServer,this)}getBlacklistFromCache(){return $s(this,void 0,void 0,(function*(){return console.log(`${xs} getBlacklistFromCache`),{code:0,data:Array.from(this._blacklistMap.keys())}}))}syncBlacklistFromServer(){return $s(this,void 0,void 0,(function*(){try{console.log(`${xs} syncBlacklistFromServer`);const e={From_Account:this._getCurrentUserId(),MaxLimited:js,StartIndex:this._startIndex},t=yield function(e,t){return $s(this,void 0,void 0,(function*(){const{helper:s,channel:n}=t,o="sns.black_list_get",i=s.generateProtocolData({servcmd:o,data:e}),r=`${i.head.seq}${o}`,a=yield n.sendPacket(i,{requestId:r}),{BlackListItem:c=[],StartIndex:u=0}=a;return{blackList:Zs(c),startIndex:u}}))}(e,this._core),{blackList:s=[],startIndex:n=0}=t;return this._startIndex=n,this._addBlacklistMap(s),this._emitBlackListUpdated(),0!==this._startIndex&&this._retryCount<10?(this._retryCount++,yield this.syncBlacklistFromServer()):this._retryCount=0,{code:0,data:Array.from(this._blacklistMap.keys())}}catch(e){throw this._retryCount=0,console.error(`${xs} syncBlacklistFromServer error:`,e),e}}))}addToBlacklist(e){return $s(this,void 0,void 0,(function*(){try{console.log(`${xs} addToBlacklist options:`,e);const t=this._preprocessBlacklist(e),s={From_Account:this._getCurrentUserId(),To_Account:t},n=yield function(e,t){return $s(this,void 0,void 0,(function*(){const{helper:s,channel:n}=t,o="sns.black_list_add",i=s.generateProtocolData({servcmd:o,data:e}),r=`${i.head.seq}${o}`,a=yield n.sendPacket(i,{requestId:r}),{ResultItem:c=[]}=a;return{blackList:Zs(c)}}))}(s,this._core),{blackList:o=[]}=n;return this._addBlacklistMap(o),{code:0,data:Array.from(this._blacklistMap.keys())}}catch(e){throw console.error(`${xs} addToBlacklist error:`,e),e}}))}removeFromBlacklist(e){return $s(this,void 0,void 0,(function*(){try{console.log(`${xs} removeFromBlacklist options:`,e);const t={From_Account:this._getCurrentUserId(),To_Account:e.userIDList},s=yield function(e,t){return $s(this,void 0,void 0,(function*(){const{helper:s,channel:n}=t,o="sns.black_list_delete",i=s.generateProtocolData({servcmd:o,data:e}),r=`${i.head.seq}${o}`,a=yield n.sendPacket(i,{requestId:r}),{ResultItem:c=[]}=a;return{blackList:Zs(c)}}))}(t,this._core),{blackList:n=[]}=s;return this._deleteBlacklistMap(n),{code:0,data:Array.from(this._blacklistMap.keys())}}catch(e){throw console.error(`${xs} removeFromBlacklist error:`,e),e}}))}dispose(){this.reset()}reset(){this._retryCount=0,this._startIndex=0,this._blacklistMap.clear()}updateBlacklist(e){console.log(`${xs} updateBlacklist data:`,e);const{addedBlacklist:t=[],removedBlacklist:s=[]}=e;let n=!1;t.length>0&&t.some((e=>!this._blacklistMap.has(e)))&&(n=!0,this._addBlacklistMap(t.map((e=>({userID:e}))))),s.length>0&&s.some((e=>this._blacklistMap.has(e)))&&(n=!0,this._deleteBlacklistMap(s.map((e=>({userID:e}))))),n&&this._emitBlackListUpdated()}_addBlacklistMap(e){console.log(`${xs} _addBlacklistMap blackList:`,e),e.forEach((e=>{const{userID:t,addBlackTimeStamp:s=Date.now()}=e;t&&!this._blacklistMap.has(t)&&this._blacklistMap.set(t,{userID:t,addBlackTimeStamp:s})}))}_deleteBlacklistMap(e){console.log(`${xs} _deleteBlacklistMap blackList:`,e),e.forEach((e=>{const{userID:t}=e;t&&this._blacklistMap.has(t)&&this._blacklistMap.delete(t)}))}_preprocessBlacklist(e){let{userIDList:t}=e;const s=this._getCurrentUserId();if(1===t.length&&t[0]===s)throw new this._core.helper.ChatError({functionName:"addToBlacklist",code:2742});return t.includes(s)&&(t=e.userIDList.filter((e=>e!==s))),t}_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}_emitBlackListUpdated(){const{notificationCenter:e,OuterEvent:t}=this._core,s=Array.from(this._blacklistMap.keys());console.log(`${xs} _emitBlackListUpdated blackList:`,s),e.emitOuterEvent(t.BLACKLIST_UPDATED,{name:t.BLACKLIST_UPDATED,data:s})}};const tn={addToBlacklist:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}},removeFromBlacklist:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}},getFriendProfile:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}},addFriend:{to:{required:!0,rules:["string"],allowEmpty:!1},source:{required:!0,rules:["string"],allowEmpty:!1},wording:{required:!1,rules:["string"],allowEmpty:!0},type:{required:!1,rules:["string"],allowEmpty:!0},remark:{required:!1,rules:["string"],allowEmpty:!0},groupName:{required:!1,rules:["string"],allowEmpty:!0}},deleteFriend:{userIDList:{required:!0,rules:["array"],allowEmpty:!1},type:{required:!1,rules:["string"],allowEmpty:!0}},checkFriend:{userIDList:{required:!0,rules:["array"],allowEmpty:!1},type:{required:!1,rules:["string"],allowEmpty:!0}},updateFriend:{userID:{required:!0,rules:["string"],allowEmpty:!1},remark:{required:!1,rules:["string"],allowEmpty:!0},friendCustomField:{required:!1,rules:["array"],allowEmpty:!0}}},sn={getBlacklist:!0,addToBlacklist:!0,removeFromBlacklist:!0,getFriendList:!0,addFriend:!0,deleteFriend:!0,updateFriend:!0,checkFriend:!0,getFriendProfile:!0,getFriendApplicationList:!0};var nn,on,rn,an,cn,un,ln,dn,gn,hn=new class{install(e){console.log(`${xs} install`),this._core=e;const{helper:t,notificationCenter:s,InnerEvent:n}=e;Js.init(e),Xs.init(e),Qs.init(e),en.init(e),t.registerValidateConfig({auth:sn,params:tn}),s.subscribeInnerEvent(n.LOGIN,this.handleLoginSuccess,this),s.subscribeInnerEvent(n.LOGOUT,this.reset,this),s.subscribeInnerEvent(n.MESSAGE_PUSH,s.InnerEventSubType.FRIEND_LIST_MODIFIED,this.onFriendModified,this)}handleLoginSuccess(){console.log(`${xs} handleLoginSuccess`),en.syncBlacklistFromServer(),Js.syncFriendListFromServer()}onFriendModified(e){const{addedBlacklist:t,removedBlacklist:s,addedFriendList:n,removedFriendList:o}=this._parseFriendListModification(null==e?void 0:e.FriendListMod[0]),{isEmpty:i}=this._core.utils;i(t)&&i(s)||en.updateBlacklist({addedBlacklist:t,removedBlacklist:s}),i(n)&&i(o)||Js.updateFriendList({addedFriendList:n,removedFriendList:o})}_parseFriendListModification(e){const{PushType:t,From_Account:s,To_Account:n,BlackListAdd_Account:o=[],BlackListDel_Account:i=[],FriendAdd_Account:r=[],FriendDel_Account:a=[]}=e;return{pushType:t,from:s,to:n,addedBlacklist:o,removedBlacklist:i,addedFriendList:r,removedFriendList:a}}reset(){console.log(`${xs} reset`),en.reset(),Js.reset()}dispose(){console.log(`${xs} dispose`);const{notificationCenter:e,InnerEvent:t}=this._core;e.unSubscribeInnerEvent(t.LOGIN,this.handleLoginSuccess,this),e.unSubscribeInnerEvent(t.LOGOUT,this.reset,this),e.unSubscribeInnerEvent(t.MESSAGE_PUSH,e.InnerEventSubType.FRIEND_LIST_MODIFIED,this.onFriendModified,this),en.dispose(),Js.dispose()}};class pn{constructor(e){return pn.instance||(pn.instance=this,this.engine=e,this.events={},this.bindIMEvents()),pn.instance}addEvent(e,t){this.events[e]||(this.events[e]=new Map),this.events[e].set(t,1)}removeEvents(){Object.keys(this.events).forEach((e=>{this.events[e].clear()})),this.events={}}dispatch(e,t){if(this.events[e])for(const s of this.events[e].keys())s.call(this,t)}bindIMEvents(){this.engine.chat.on(this.engine.EVENT.SDK_READY,this.onSDKReady,this),this.engine.chat.on(this.engine.EVENT.SDK_NOT_READY,this.onSDKNotReady,this),this.engine.chat.on(this.engine.EVENT.KICKED_OUT,this.onKickedOut,this),this.engine.chat.on(this.engine.EVENT.NET_STATE_CHANGE,this.onNetStateChange,this),this.engine.chat.on(this.engine.EVENT.MESSAGE_RECEIVED,this.onReceiveMessage,this),this.engine.chat.on(this.engine.EVENT.MESSAGE_MODIFIED,this.onMessageModified,this),this.engine.chat.on(this.engine.EVENT.MESSAGE_REVOKED,this.onMessageRevoked,this),this.engine.chat.on(this.engine.EVENT.MESSAGE_READ_BY_PEER,this.onMessageReadByPeer,this),this.engine.chat.on(this.engine.EVENT.MESSAGE_READ_RECEIPT_RECEIVED,this.onMessageReadReceiptReceived,this),this.engine.chat.on(this.engine.EVENT.MESSAGE_REACTIONS_UPDATED,this.onMessageReactionsUpdated,this),this.engine.chat.on(this.engine.EVENT.CONVERSATION_LIST_UPDATED,this.onConversationListUpdated,this),this.engine.chat.on(this.engine.EVENT.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED,this.onTotalMessageCountUpdated,this),this.engine.chat.on(this.engine.EVENT.PROFILE_UPDATED,this.onProfileUpdated,this),this.engine.chat.on(this.engine.EVENT.BLACKLIST_UPDATED,this.onBlacklistUpdated,this),this.engine.chat.on(this.engine.EVENT.USER_STATUS_UPDATED,this.onUserStatusUpdated,this),this.engine.chat.on(this.engine.EVENT.GROUP_LIST_UPDATED,this.onGroupListUpdated,this),this.engine.chat.on(this.engine.EVENT.GROUP_ATTRIBUTES_UPDATED,this.onGroupAttributesUpdated,this),this.engine.chat.on(this.engine.EVENT.GROUP_COUNTER_UPDATED,this.onGroupCounterUpdated,this),this.engine.chat.on(this.engine.EVENT.FRIEND_LIST_UPDATED,this.onFriendListUpdated,this),this.engine.chat.on(this.engine.EVENT.FRIEND_APPLICATION_LIST_UPDATED,this.onFriendApplicationListUpdated,this)}unbindIMEvents(){this.engine.chat.off(this.engine.EVENT.SDK_READY,this.onSDKReady,this),this.engine.chat.off(this.engine.EVENT.SDK_NOT_READY,this.onSDKNotReady,this),this.engine.chat.off(this.engine.EVENT.KICKED_OUT,this.onKickedOut,this),this.engine.chat.off(this.engine.EVENT.NET_STATE_CHANGE,this.onNetStateChange,this),this.engine.chat.off(this.engine.EVENT.MESSAGE_RECEIVED,this.onReceiveMessage,this),this.engine.chat.off(this.engine.EVENT.MESSAGE_MODIFIED,this.onMessageModified,this),this.engine.chat.off(this.engine.EVENT.MESSAGE_REVOKED,this.onMessageRevoked,this),this.engine.chat.off(this.engine.EVENT.MESSAGE_READ_BY_PEER,this.onMessageReadByPeer,this),this.engine.chat.off(this.engine.EVENT.MESSAGE_READ_RECEIPT_RECEIVED,this.onMessageReadReceiptReceived,this),this.engine.chat.off(this.engine.EVENT.MESSAGE_REACTIONS_UPDATED,this.onMessageReactionsUpdated,this),this.engine.chat.off(this.engine.EVENT.CONVERSATION_LIST_UPDATED,this.onConversationListUpdated,this),this.engine.chat.off(this.engine.EVENT.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED,this.onTotalMessageCountUpdated,this),this.engine.chat.off(this.engine.EVENT.PROFILE_UPDATED,this.onProfileUpdated,this),this.engine.chat.off(this.engine.EVENT.BLACKLIST_UPDATED,this.onBlacklistUpdated,this),this.engine.chat.off(this.engine.EVENT.USER_STATUS_UPDATED,this.onUserStatusUpdated,this),this.engine.chat.off(this.engine.EVENT.GROUP_LIST_UPDATED,this.onGroupListUpdated,this),this.engine.chat.off(this.engine.EVENT.GROUP_ATTRIBUTES_UPDATED,this.onGroupAttributesUpdated,this),this.engine.chat.off(this.engine.EVENT.GROUP_COUNTER_UPDATED,this.onGroupCounterUpdated,this),this.engine.chat.off(this.engine.EVENT.FRIEND_LIST_UPDATED,this.onFriendListUpdated,this),this.engine.chat.off(this.engine.EVENT.FRIEND_APPLICATION_LIST_UPDATED,this.onFriendApplicationListUpdated,this),pn.instance=null}onSDKReady(e){this.dispatch(this.engine.EVENT.SDK_READY,e.data)}onSDKNotReady(e){this.dispatch(this.engine.EVENT.SDK_NOT_READY,e.data)}onKickedOut(e){this.dispatch(this.engine.EVENT.KICKED_OUT,e.data)}onNetStateChange(e){this.dispatch(this.engine.EVENT.NET_STATE_CHANGE,e.data)}onReceiveMessage(e){this.dispatch(this.engine.EVENT.MESSAGE_RECEIVED,e.data)}onMessageModified(e){this.dispatch(this.engine.EVENT.MESSAGE_MODIFIED,e.data)}onMessageRevoked(e){this.dispatch(this.engine.EVENT.MESSAGE_REVOKED,e.data)}onMessageReadByPeer(e){this.dispatch(this.engine.EVENT.MESSAGE_READ_BY_PEER,e.data)}onMessageReadReceiptReceived(e){this.dispatch(this.engine.EVENT.MESSAGE_READ_RECEIPT_RECEIVED,e.data)}onMessageReactionsUpdated(e){this.dispatch(this.engine.EVENT.MESSAGE_REACTIONS_UPDATED,e.data)}onConversationListUpdated(e){this.dispatch(this.engine.EVENT.CONVERSATION_LIST_UPDATED,e.data)}onTotalMessageCountUpdated(e){this.dispatch(this.engine.EVENT.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED,e.data)}onProfileUpdated(e){this.dispatch(this.engine.EVENT.PROFILE_UPDATED,e.data)}onBlacklistUpdated(e){this.dispatch(this.engine.EVENT.BLACKLIST_UPDATED,e.data)}onUserStatusUpdated(e){this.dispatch(this.engine.EVENT.USER_STATUS_UPDATED,e.data)}onGroupListUpdated(e){this.dispatch(this.engine.EVENT.GROUP_LIST_UPDATED,e.data)}onGroupAttributesUpdated(e){this.dispatch(this.engine.EVENT.GROUP_ATTRIBUTES_UPDATED,e.data)}onGroupCounterUpdated(e){this.dispatch(this.engine.EVENT.GROUP_COUNTER_UPDATED,e.data)}onFriendListUpdated(e){this.dispatch(this.engine.EVENT.FRIEND_LIST_UPDATED,e.data)}onFriendApplicationListUpdated(e){this.dispatch(this.engine.EVENT.FRIEND_APPLICATION_LIST_UPDATED,e.data)}}!function(e){e.TUIStore="TUIStore",e.TUITranslate="TUITranslate",e.TUIConversation="TUIConversation",e.TUIChat="TUIChat",e.TUIGroup="TUIGroup",e.TUIUser="TUIUser",e.TUIFriend="TUIFriend",e.TUIReport="TUIReport",e.TUISearch="TUISearch"}(nn||(nn={})),function(e){e.APP="application",e.CONV="conversation",e.CHAT="chat",e.GRP="group",e.USER="user",e.FRIEND="friend",e.SEARCH="search",e.CUSTOM="custom"}(on||(on={})),function(e){e[e.UNSUB_USER=-1]="UNSUB_USER"}(rn||(rn={})),function(e){e.BUSINESS_ID="user_typing_status",e[e.STATUS_START=1]="STATUS_START",e[e.STATUS_END=0]="STATUS_END",e[e.VERSION=1]="VERSION",e[e.ACTION_START_ID=14]="ACTION_START_ID",e[e.ACTION_END_ID=0]="ACTION_END_ID",e.ACTION_START="EIMAMSG_InputStatus_Ing",e.ACTION_END="EIMAMSG_InputStatus_End",e[e.NEED_TYPING=1]="NEED_TYPING"}(an||(an={})),function(e){e.ADD="add",e.REMOVE="remove"}(cn||(cn={})),function(e){e[e.MSG_MODIFY_CONFLICT=2480]="MSG_MODIFY_CONFLICT",e[e.MSG_MODIFY_DISABLED_IN_AVCHATROOM=2481]="MSG_MODIFY_DISABLED_IN_AVCHATROOM",e[e.MODIFY_MESSAGE_NOT_EXIST=20026]="MODIFY_MESSAGE_NOT_EXIST"}(un||(un={})),function(e){e[e.NOT_INIT=-1e5]="NOT_INIT",e[e.INVALID_CONV_ID=-100001]="INVALID_CONV_ID",e[e.CONV_ID_SAME=-100002]="CONV_ID_SAME",e[e.CONV_NOT_EXIST=-100003]="CONV_NOT_EXIST",e[e.GET_MSG_LIST_ERROR=-100004]="GET_MSG_LIST_ERROR",e[e.MISMATCH_TYPE_AND_PAYLOAD=-100005]="MISMATCH_TYPE_AND_PAYLOAD"}(ln||(ln={})),function(e){e.MSG_MODIFY_CONFLICT="MODIFY_MESSAGE_ERROR,修改消息发生冲突, data.message 是最新的消息",e.MSG_MODIFY_DISABLED_IN_AVCHATROOM="MODIFY_MESSAGE_ERROR,不支持修改直播群消息.",e.MODIFY_MESSAGE_NOT_EXIST="MODIFY_MESSAGE_ERROR,消息不存在."}(dn||(dn={})),function(e){e.NOT_INIT="TUIChatEngine 初始化未完成,请确认 TUIChatEngine.login 接口调用是否正常。",e.INVALID_CONV_ID="会话 ID 无效",e.CONV_ID_SAME="您切换的是同一个会话 ID",e.CONV_NOT_EXIST="会话不存在",e.GET_MSG_LIST_ERROR="Chat SDK is not ready.",e.MISMATCH_TYPE_AND_PAYLOAD="type 与 payload 不匹配."}(gn||(gn={}));const mn={logout:1,destroy:1},fn={deleteConversation:1,pinConversation:1,muteConversation:1,switchConversation:1,getConversationProfile:1,clearHistoryMessage:1},vn={modifyMessage:1,revokeMessage:1,resendMessage:1,deleteMessage:1,quoteMessage:1,replyMessage:1,setMessageExtensions:1,deleteMessageExtensions:1,getMessageExtensions:1,sendTextMessage:1,sendTextAtMessage:1,sendImageMessage:1,sendAudioMessage:1,sendVideoMessage:1,sendFileMessage:1,sendCustomMessage:1,sendFaceMessage:1,sendLocationMessage:1,sendForwardMessage:1,enterTypingState:1,leaveTypingState:1,sendMessageReadReceipt:1,getGroupMessageReadMemberList:1,getMessageList:1,downloadMergedMessages:1,setTranslationLanguage:1,translateText:1,searchCloudMessages:1,addMessageReaction:1,removeMessageReaction:1,getMessageReactions:1,getAllUserListOfMessageReaction:1},_n={switchGroup:1,getGroupProfile:1,updateGroupProfile:1,createGroup:1,dismissGroup:1,searchGroupByID:1,joinGroup:1,quitGroup:1,getGroupApplicationList:1,handleGroupApplication:1,getGroupOnlineMemberCount:1,changeGroupOwner:1,initGroupAttributes:1,setGroupAttributes:1,deleteGroupAttributes:1,getGroupAttributes:1,setGroupCounters:1,increaseGroupCounter:1,decreaseGroupCounter:1,getGroupCounters:1,getGroupMemberList:1,getGroupMemberProfile:1,addGroupMember:1,deleteGroupMember:1,setGroupMemberMuteTime:1,setGroupMemberRole:1,setGroupMemberNameCard:1,setGroupMemberCustomField:1,markGroupMemberList:1},In={switchUserStatus:1,switchMessageReadStatus:1,getUserProfile:1,updateMyProfile:1,addToBlacklist:1,removeFromBlacklist:1},yn={getFriendList:1,addFriend:1,deleteFriend:1,checkFriend:1,getFriendProfile:1,updateFriend:1,acceptFriendApplication:1,refuseFriendApplication:1,deleteFriendApplication:1,setFriendApplicationRead:1},En=function(e){return void 0===e},Sn=function(e){return e.startsWith("_")},Cn=function(e){return/^(https?:\/\/(([a-zA-Z0-9]+-?)+[a-zA-Z0-9]+\.)+[a-zA-Z]+)(:\d+)?(\/.*)?(\?.*)?(#.*)?$/.test(e)};const Mn=function(e){return e&&function(e){if("string"==typeof e)try{return!!JSON.parse(e)}catch(e){return!1}return!1}(e)?JSON.parse(e):e},Tn=function(e){let t="";return t=e>=1048576?`${(e/1048576).toFixed(2)} Mb`:e>=1024?`${(e/1024).toFixed(2)} Kb`:`${e.toFixed(2)}B`,t},Dn="https://web.sdk.qcloud.com/component/TUIKit/assets/avatar_16.png",bn="https://web.sdk.qcloud.com/im/demo/TUIkit/web/img/constomer.png",On="https://web.sdk.qcloud.com/component/TUIKit/assets/group_avatar.png",Ln="https://web.sdk.qcloud.com/im/assets/emoji-plugin/",An="https://web.sdk.qcloud.com/im/assets/face-elem/",Un="https://map.qq.com/?type=marker&isopeninfowin=1&markertype=1&",Rn="https://apis.map.qq.com/ws/staticmap/v2/?",Pn={"[TUIEmoji_Expect]":"emoji_0@2x.png","[TUIEmoji_Blink]":"emoji_1@2x.png","[TUIEmoji_Guffaw]":"emoji_2@2x.png","[TUIEmoji_KindSmile]":"emoji_3@2x.png","[TUIEmoji_Haha]":"emoji_4@2x.png","[TUIEmoji_Cheerful]":"emoji_5@2x.png","[TUIEmoji_Smile]":"emoji_6@2x.png","[TUIEmoji_Sorrow]":"emoji_7@2x.png","[TUIEmoji_Speechless]":"emoji_8@2x.png","[TUIEmoji_Amazed]":"emoji_9@2x.png","[TUIEmoji_Complacent]":"emoji_10@2x.png","[TUIEmoji_Lustful]":"emoji_11@2x.png","[TUIEmoji_Stareyes]":"emoji_12@2x.png","[TUIEmoji_Giggle]":"emoji_13@2x.png","[TUIEmoji_Daemon]":"emoji_14@2x.png","[TUIEmoji_Rage]":"emoji_15@2x.png","[TUIEmoji_Yawn]":"emoji_16@2x.png","[TUIEmoji_TearsLaugh]":"emoji_17@2x.png","[TUIEmoji_Silly]":"emoji_18@2x.png","[TUIEmoji_Wail]":"emoji_19@2x.png","[TUIEmoji_Kiss]":"emoji_20@2x.png","[TUIEmoji_Trapped]":"emoji_21@2x.png","[TUIEmoji_Fear]":"emoji_22@2x.png","[TUIEmoji_BareTeeth]":"emoji_23@2x.png","[TUIEmoji_FlareUp]":"emoji_24@2x.png","[TUIEmoji_Tact]":"emoji_25@2x.png","[TUIEmoji_Shit]":"emoji_26@2x.png","[TUIEmoji_ShutUp]":"emoji_27@2x.png","[TUIEmoji_Sigh]":"emoji_28@2x.png","[TUIEmoji_Hehe]":"emoji_29@2x.png","[TUIEmoji_Silent]":"emoji_30@2x.png","[TUIEmoji_Skull]":"emoji_31@2x.png","[TUIEmoji_Mask]":"emoji_32@2x.png","[TUIEmoji_Beer]":"emoji_33@2x.png","[TUIEmoji_Cake]":"emoji_34@2x.png","[TUIEmoji_RedPacket]":"emoji_35@2x.png","[TUIEmoji_Bombs]":"emoji_36@2x.png","[TUIEmoji_Ai]":"emoji_37@2x.png","[TUIEmoji_Celebrate]":"emoji_38@2x.png","[TUIEmoji_Bless]":"emoji_39@2x.png","[TUIEmoji_Flower]":"emoji_40@2x.png","[TUIEmoji_Watermelon]":"emoji_41@2x.png","[TUIEmoji_Cow]":"emoji_42@2x.png","[TUIEmoji_Fool]":"emoji_43@2x.png","[TUIEmoji_Surprised]":"emoji_44@2x.png","[TUIEmoji_Askance]":"emoji_45@2x.png","[TUIEmoji_Monster]":"emoji_46@2x.png","[TUIEmoji_Pig]":"emoji_47@2x.png","[TUIEmoji_Coffee]":"emoji_48@2x.png","[TUIEmoji_Ok]":"emoji_49@2x.png","[TUIEmoji_Heart]":"emoji_50@2x.png","[TUIEmoji_Sun]":"emoji_51@2x.png","[TUIEmoji_Moon]":"emoji_52@2x.png","[TUIEmoji_Star]":"emoji_53@2x.png","[TUIEmoji_Rich]":"emoji_54@2x.png","[TUIEmoji_Fortune]":"emoji_55@2x.png","[TUIEmoji_857]":"emoji_56@2x.png","[TUIEmoji_666]":"emoji_57@2x.png","[TUIEmoji_Prohibit]":"emoji_58@2x.png","[TUIEmoji_Convinced]":"emoji_59@2x.png","[TUIEmoji_Knife]":"emoji_60@2x.png","[TUIEmoji_Like]":"emoji_61@2x.png"},Gn={"[TUIEmoji_Smile]":"[微笑]","[TUIEmoji_Expect]":"[期待]","[TUIEmoji_Blink]":"[眨眼]","[TUIEmoji_Guffaw]":"[大笑]","[TUIEmoji_KindSmile]":"[姨母笑]","[TUIEmoji_Haha]":"[哈哈哈]","[TUIEmoji_Cheerful]":"[愉快]","[TUIEmoji_Speechless]":"[无语]","[TUIEmoji_Amazed]":"[惊讶]","[TUIEmoji_Sorrow]":"[悲伤]","[TUIEmoji_Complacent]":"[得意]","[TUIEmoji_Silly]":"[傻了]","[TUIEmoji_Lustful]":"[色]","[TUIEmoji_Giggle]":"[憨笑]","[TUIEmoji_Kiss]":"[亲亲]","[TUIEmoji_Wail]":"[大哭]","[TUIEmoji_TearsLaugh]":"[哭笑]","[TUIEmoji_Trapped]":"[困]","[TUIEmoji_Mask]":"[口罩]","[TUIEmoji_Fear]":"[恐惧]","[TUIEmoji_BareTeeth]":"[龇牙]","[TUIEmoji_FlareUp]":"[发怒]","[TUIEmoji_Yawn]":"[打哈欠]","[TUIEmoji_Tact]":"[机智]","[TUIEmoji_Stareyes]":"[星星眼]","[TUIEmoji_ShutUp]":"[闭嘴]","[TUIEmoji_Sigh]":"[叹气]","[TUIEmoji_Hehe]":"[呵呵]","[TUIEmoji_Silent]":"[收声]","[TUIEmoji_Surprised]":"[惊喜]","[TUIEmoji_Askance]":"[白眼]","[TUIEmoji_Ok]":"[OK]","[TUIEmoji_Shit]":"[便便]","[TUIEmoji_Monster]":"[怪兽]","[TUIEmoji_Daemon]":"[恶魔]","[TUIEmoji_Rage]":"[恶魔怒]","[TUIEmoji_Fool]":"[衰]","[TUIEmoji_Pig]":"[猪]","[TUIEmoji_Cow]":"[牛]","[TUIEmoji_Ai]":"[AI]","[TUIEmoji_Skull]":"[骷髅]","[TUIEmoji_Bombs]":"[炸弹]","[TUIEmoji_Coffee]":"[咖啡]","[TUIEmoji_Cake]":"[蛋糕]","[TUIEmoji_Beer]":"[啤酒]","[TUIEmoji_Flower]":"[花]","[TUIEmoji_Watermelon]":"[瓜]","[TUIEmoji_Rich]":"[壕]","[TUIEmoji_Heart]":"[爱心]","[TUIEmoji_Moon]":"[月亮]","[TUIEmoji_Sun]":"[太阳]","[TUIEmoji_Star]":"[星星]","[TUIEmoji_RedPacket]":"[红包]","[TUIEmoji_Celebrate]":"[庆祝]","[TUIEmoji_Bless]":"[福]","[TUIEmoji_Fortune]":"[发]","[TUIEmoji_Convinced]":"[服]","[TUIEmoji_Prohibit]":"[禁]","[TUIEmoji_666]":"[666]","[TUIEmoji_857]":"[857]","[TUIEmoji_Knife]":"[刀]","[TUIEmoji_Like]":"[赞]"},wn={enabledMessageReadReceipt:Math.pow(2,5),enabledEmojiPlugin:Math.pow(2,48),enabledOnlineStatus:Math.pow(2,7),enabledCustomerServicePlugin:Math.pow(2,40),enabledTranslationPlugin:Math.pow(2,38),enabledVoiceToText:Math.pow(2,39)},Nn=["messageList","conversationList","newMessageList"],kn=["translateTextInfo","voiceToTextInfo"],Fn="undefined"!=typeof wx&&"function"==typeof wx.getSystemInfoSync&&Boolean(wx.getSystemInfoSync().fontSizeSetting),$n="undefined"!=typeof uni&&"undefined"==typeof window,xn=Fn||$n,jn="undefined"!=typeof uni,Vn=("undefined"!=typeof uni||"undefined"!=typeof window)&&!xn,qn=Fn?wx:jn?uni:window,Hn=Vn&&window&&window.navigator&&window.navigator.userAgent||"",Bn=/Android/i.test(Hn),Kn=/(?:Windows Phone)/.test(Hn),Yn=/(?:SymbianOS)/.test(Hn),Wn=/iPad/i.test(Hn)||/iPhone/i.test(Hn)||/iPod/i.test(Hn),zn=Bn||Kn||Yn||Wn,Jn=Vn&&!zn;class Xn{constructor(){this.global=qn,this.isOfficial=!1}static getInstance(){return Xn.instance||(Xn.instance=new Xn),Xn.instance}initOfficial(e){this.isOfficial=e}getPlatform(){let e="";return Jn?e="pc":zn?e="h5":Fn?e="wechat":$n&&!Fn&&(e="app"),e}}const Qn="group-module",Zn="relationship-module";class eo{constructor(){this.EVENT=e.EVENT,this.TYPES=e.TYPES,this.loginStatusPromise=new Map,this.userID="",this.isInited=!1}static getInstance(){return eo.instance||(eo.instance=new eo),eo.instance}mount(e,t){this[e]=t}login(t){const{chat:s,SDKAppID:n,userID:o}=t,i=1400187352===n||1400188366===n;return this.createChat(t),this.userID=o,Xn.getInstance().initOfficial(i),this.TUIStore.update(on.APP,"isOfficial",i),this.TUIStore.update(on.APP,"SDKVersion",e.VERSION),this.eventCenter=new pn(this),this.eventCenter.removeEvents(),this.resetStore(),this.initService(),s&&s.isReady()?(console.log("TUIChatEngine.login ok, from TUICore."),this.TUIUser.getUserProfile(),this.checkCommercialAbility(),Promise.resolve({})):(this.registerPlugin(t),this.eventCenter.addEvent(this.EVENT.SDK_READY,(()=>{this.onSDKReady()})),this.eventCenter.addEvent(this.EVENT.SDK_NOT_READY,(()=>{this.onSDKNotReady()})),this.loginChat(t))}logout(){return this.userID="",this.isInited=!1,this.resetStore(),this.chat.logout()}isReady(){var e;return(null===(e=this.chat)||void 0===e?void 0:e.isReady())||!1}setLogLevel(e){this.chat?this.chat.setLogLevel(e):console.warn("TUIChatEngine 初始化未完成,请确认 TUIChatEngine.login 接口调用是否正常。")}destroy(){return this.eventCenter.unbindIMEvents(),this.isInited=!1,this.resetStore(),this.chat.destroy()}getMyUserID(){return this.userID}resetStore(){this.TUIStore.reset(on.CHAT),this.TUIStore.reset(on.CONV),this.TUIStore.reset(on.GRP),this.TUIStore.reset(on.USER),this.TUIStore.reset(on.SEARCH),this.TUIStore.reset(on.FRIEND),this.TUIStore.reset(on.CUSTOM),console.log("TUIChatEngine.resetStore ok.")}initService(){this.TUIChat.init(),this.TUIConversation.init(),this.TUIUser.init(),this.initOptionalServices(),this.isInited=!0,console.log("TUIChatEngine.initService ok.")}initOptionalServices(){const t=e.VERSION.split(".");t[0]>3||3===t[0]&&t[1]>=3&&t[2]>0?(!0===this.chat.callExperimentalAPI("canIUseModule",[Qn])&&this.TUIGroup.init(),!0===this.chat.callExperimentalAPI("canIUseModule",[Zn])&&this.TUIFriend.init()):(this.TUIGroup.init(),this.TUIFriend.init())}createChat(t){const{chat:s}=t,o=n(t,["chat"]);En(s)?(this.chat=e.create(Object.assign(Object.assign({},o),{scene:"chat-uikit-engine"})),this.chat.use(K),this.chat.use(ut),this.chat.use(Kt),this.chat.use(Fs),this.chat.use(hn)):this.chat=s}loginChat(e){const{userID:t,userSig:s}=e;return new Promise(((e,n)=>{this.chat.login({userID:t,userSig:s}).then((t=>{console.log("TUIChatEngine.loginChat ok."),this.checkCommercialAbility(),t.data.repeatLogin&&this.chat.isReady()&&e(t),this.loginStatusPromise.set("login",{resolve:e,reject:n,imResponse:t})})).catch((e=>{n(e)}))}))}registerPlugin(e){const{useUploadPlugin:n=!1,useProfanityFilterPlugin:o=!1,TIMPush:i,pushConfig:r,TUIOfflinePush:a,offlinePushConfig:c}=e;!0===n&&this.chat.registerPlugin({"tim-upload-plugin":t}),!0===o&&this.chat.registerPlugin({"tim-profanity-filter-plugin":s}),!$n||Fn||En(i)||En(r)||this.chat.registerPlugin({"tim-push":i,pushConfig:r}),!$n||Fn||En(a)||En(c)||this.chat.registerPlugin({"tim-offline-push-plugin":a,offlinePushConfig:c})}onSDKReady(){if(this.loginStatusPromise.has("login")){const e=this.loginStatusPromise.get("login");e.resolve(e.imResponse),this.TUIUser.getUserProfile()}this.loginStatusPromise.delete("login")}onSDKNotReady(){if(this.loginStatusPromise.has("login")){this.loginStatusPromise.get("login").reject(new Error("sdk not ready"))}this.loginStatusPromise.delete("login"),this.resetStore()}checkCommercialAbility(){Object.keys(wn).forEach((e=>{const t=wn[e];this.chat.callExperimentalAPI("isCommercialAbilityEnabled",t).then((t=>{const{enabled:s=!1}=t.data;this.TUIStore.update(on.APP,e,s)}))}))}}class to{constructor(){this.defaultStore={enabledMessageReadReceipt:!1,enabledEmojiPlugin:!1,enabledOnlineStatus:!1,enabledCustomerServicePlugin:!1,enabledTranslationPlugin:!1,enabledVoiceToText:!1,enableTyping:!0,enableConversationDraft:!0,isOfficial:!1,SDKVersion:"3.0.0",tasks:{sendMessage:!1,revokeMessage:!1,modifyNickName:!1,groupChat:!1,muteGroup:!1,dismissGroup:!1,call:!1,searchCloudMessage:!1,customerService:!1,translateTextMessage:!1}},this.store={enabledEmojiPlugin:!1,enabledMessageReadReceipt:!1,enabledOnlineStatus:!1,enabledCustomerServicePlugin:!1,enabledTranslationPlugin:!1,enabledVoiceToText:!1,enableTyping:!0,enableConversationDraft:!0,isOfficial:!1,SDKVersion:"3.0.0",tasks:{sendMessage:!1,revokeMessage:!1,modifyNickName:!1,groupChat:!1,muteGroup:!1,dismissGroup:!1,call:!1,searchCloudMessage:!1,customerService:!1,translateTextMessage:!1}}}update(e,t){this.store[e]=t}getData(e){return this.store[e]}reset(e=[]){this.store=Object.assign(Object.assign(Object.assign({},this.defaultStore),this.store),e.reduce(((e,t)=>Object.assign(Object.assign({},e),{[t]:this.defaultStore[t]})),{}))}}class so{constructor(){this.defaultStore={userProfile:{},displayOnlineStatus:!1,displayMessageReadReceipt:!0,userStatusList:new Map,kickedOut:"",netStateChange:"",userBlacklist:[],targetLanguage:"zh"},this.store={userProfile:{},displayOnlineStatus:!1,displayMessageReadReceipt:!0,userStatusList:new Map,kickedOut:"",netStateChange:"",userBlacklist:[],targetLanguage:"zh"}}update(e,t){if("userStatusList"===e)this.updateUserStatusList(t);else this.store[e]=t}getData(e){return this.store[e]}reset(e=[]){this.store=Object.assign(Object.assign(Object.assign({},this.defaultStore),this.store),e.reduce(((e,t)=>Object.assign(Object.assign({},e),{[t]:this.defaultStore[t]})),{}))}updateUserStatusList(e){0!==e.length?e.forEach((e=>{const{userID:t,statusType:s=0,customStatus:n=""}=e;s===rn.UNSUB_USER?this.store.userStatusList.delete(t):this.store.userStatusList.set(t,{statusType:s,customStatus:n})})):this.store.userStatusList.clear()}}class no{getEngine(){return eo.getInstance()}}const oo=function(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(function(e){if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);if(null===t)return!0;let s=t;for(;null!==Object.getPrototypeOf(s);)s=Object.getPrototypeOf(s);return t===s}(e)){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}return!1},io=["[图片]","[语音]","[视频]","[文件]","[位置]","[地理位置]","[动画表情]","[自定义消息]","[群提示消息]","[聊天记录]"];class ro extends no{constructor(e){super(),this.initProxy(e),this.isMuted=this.messageRemindType===this.getEngine().TYPES.MSG_REMIND_ACPT_NOT_NOTE||this.messageRemindType===this.getEngine().TYPES.MSG_REMIND_DISCARD,this.operationType=0,this._conversation=e}initProxy(e){Object.keys(e).forEach((t=>{Sn(t)||(this[t]=e[t])}))}updateProperties(e){Object.keys(e).forEach((t=>{Sn(t)||(this[t]=e[t])}))}updateOperationType(e){this.operationType=e}getConversation(){return this._conversation}deleteConversation(){return this.getEngine().TUIConversation.deleteConversation(this.conversationID)}pinConversation(){return this.getEngine().TUIConversation.pinConversation({conversationID:this.conversationID,isPinned:!this.isPinned})}muteConversation(){const e=this.getEngine(),t={messageRemindType:!0===this.isMuted?e.TYPES.MSG_REMIND_ACPT_AND_NOTE:e.TYPES.MSG_REMIND_ACPT_NOT_NOTE};if(this.type===e.TYPES.CONV_C2C){const s=this.conversationID.replace(e.TYPES.CONV_C2C,"");t.userIDList=[s]}else if(this.type===e.TYPES.CONV_GROUP){const s=this.conversationID.replace(e.TYPES.CONV_GROUP,"");t.groupID=s}return e.TUIConversation.muteConversation(t)}getAvatar(){var e,t,s,n,o,i;const r=this.getEngine();let a="";switch(this.type){case r.TYPES.CONV_C2C:a=Cn(null===(e=this.userProfile)||void 0===e?void 0:e.avatar)?null===(t=this.userProfile)||void 0===t?void 0:t.avatar:Dn;break;case r.TYPES.CONV_GROUP:a=Cn(null===(s=this.groupProfile)||void 0===s?void 0:s.avatar)?null===(n=this.groupProfile)||void 0===n?void 0:n.avatar:bn;break;case r.TYPES.CONV_SYSTEM:a=Cn(null===(o=this.groupProfile)||void 0===o?void 0:o.avatar)?null===(i=this.groupProfile)||void 0===i?void 0:i.avatar:On}return a}getShowName(){var e,t,s,n;const o=this.getEngine();let i="";switch(this.type){case o.TYPES.CONV_C2C:i=this.remark||(null===(e=this.userProfile)||void 0===e?void 0:e.nick)||(null===(t=this.userProfile)||void 0===t?void 0:t.userID)||"";break;case o.TYPES.CONV_GROUP:i=(null===(s=this.groupProfile)||void 0===s?void 0:s.name)||(null===(n=this.groupProfile)||void 0===n?void 0:n.groupID)||"";break;case o.TYPES.CONV_SYSTEM:i=o.TUITranslate.t("系统通知")}return i}getGroupAtInfo(){const e=this.getEngine(),t=e.TUITranslate.t.bind(e.TUITranslate),s=[`[${t("TUIConversation.有人@我")}]`,`[${t("TUIConversation.@所有人")}]`,`[${t("TUIConversation.@所有人")}][${t("TUIConversation.有人@我")}]`];let n="";for(let e=0;e<this.groupAtInfoList.length;e++)this.groupAtInfoList[e].atTypeArray[0]&&this.unreadCount>0&&(n=s[this.groupAtInfoList[e].atTypeArray[0]-1]);return n}getLastMessage(e){return"time"===e?this.getLastMessageTime():"text"===e?this.getLastMessageText():(console.warn(`ConversationModel.getLastMessage key:${e} is invalid.`),null)}getLastMessageTime(){var e;const t=this.getEngine();let s="";return(null===(e=this.lastMessage)||void 0===e?void 0:e.lastTime)>0&&(s=function(e,t){const s=6e4,n=36e5,o=24*n,i=7*o,r=(new Date).getTime()-e;let a="";if(r<0)return a;const c=r/s,u=r/n,l=r/o,d=r/i;if(d>=1&&d<=4)a=` ${parseInt(`${d}`,10)} ${t("time.周")}${t("time.前")}`;else if(l>=1&&l<=6)a=` ${parseInt(`${l}`,10)} ${t("time.天")}${t("time.前")}`;else if(u>=1&&u<=23)a=` ${parseInt(`${u}`,10)} ${t("time.小时")}${t("time.前")}`;else if(c>=1&&c<=59)a=` ${parseInt(`${c}`,10)} ${t("time.分钟")}${t("time.前")}`;else if(r>=0&&r<=s)a=`${t("time.刚刚")}`;else{const t=new Date;t.setTime(e),a=`${t.getFullYear()}-${t.getMonth()+1<10?`0${t.getMonth()+1}`:t.getMonth()+1}-${t.getDate()<10?`0${t.getDate()}`:t.getDate()}`}return a}(1e3*this.lastMessage.lastTime,t.TUITranslate.t.bind(t.TUITranslate))),s}getLastMessageText(){var e;if(this.draftText){return Mn(this.draftText).abstract}const t=this.getEngine(),s=t.TUITranslate.t.bind(t.TUITranslate);if(4===this.operationType)return s("TUIConversation.您已被群管理员移出群聊");if(5===this.operationType)return s("TUIConversation.该群聊已被解散");if(8===this.operationType)return s("TUIConversation.您已退出该群聊");const n=this._conversation,{lastMessage:o}=this;let i="",r="";const a=n.unreadCount>0&&n.messageRemindType===t.TYPES.MSG_REMIND_ACPT_NOT_NOTE?`[${n.unreadCount>99?"99+":n.unreadCount}${s("TUIConversation.条")}]`:"";if(n.type===t.TYPES.CONV_GROUP)if(o.fromAccount===t.getMyUserID())i=s("TUIConversation.我");else{const e=o.fromAccount;i=t.TUIFriend.getFriendRemark([e])[e]||o.nameCard||o.nick||e}if(o.type===t.TYPES.MSG_TEXT)r=this.decodeTextMessage(o.payload.text);else if(o.type===t.TYPES.MSG_CUSTOM){const n=Mn(null===(e=null==o?void 0:o.payload)||void 0===e?void 0:e.data);if(1===(null==n?void 0:n.businessID))return r=t.TUIChat.messageHandler.handleCallKitSignaling(o),r;r=io.includes(o.messageForShow)?s(`TUIChat.${o.messageForShow}`):o.messageForShow}else r=io.includes(o.messageForShow)?s(`TUIChat.${o.messageForShow}`):o.messageForShow;return o.isRevoked&&(r=s("TUIChat.撤回了一条消息")),n.type===t.TYPES.CONV_GROUP&&o.type===t.TYPES.MSG_GRP_TIP?r:`${a}${i?`${i}:`:""}${r}`}decodeTextMessage(e){if(oo(e))return e;const t=/(\[.+?\])/g;let s=e;if(t.test(e)){const n=this.getEngine(),o=n.TUITranslate.t.bind(n.TUITranslate);s=e.replace(t,(e=>{const t=o(`Emoji.${e}`);return Fn||!t||t.startsWith("Emoji.")?Gn[e]||e:t}))}return s}}class ao{constructor(){this.defaultStore={currentConversationID:"",totalUnreadCount:0,conversationList:[],currentConversation:null,operationTypeMap:new Map},this.store={currentConversationID:"",totalUnreadCount:0,conversationList:[],currentConversation:null,operationTypeMap:new Map}}update(e,t){switch(e){case"conversationList":this.updateConversationList(t);break;case"operationTypeMap":this.updateOperationTypeMap(t);break;default:this.store[e]=t}}getData(e){return this.store[e]}getModel(e){return this.store.conversationList.find((t=>t.conversationID===e))}reset(e=[]){this.store=Object.assign(Object.assign(Object.assign({},this.defaultStore),this.store),e.reduce(((e,t)=>Object.assign(Object.assign({},e),{[t]:this.defaultStore[t]})),{}))}updateConversationList(e){const t=[];e.forEach((e=>{let s=e;e instanceof ro?s.updateProperties(e):s=new ro(e);const n=this.getOperationType(e);s.updateOperationType(n),t.push(s)})),this.store.conversationList=t}updateOperationTypeMap(e){const{conversationID:t,operationType:s=0}=e;this.store.operationTypeMap.set(t,s)}getOperationType(e){const{conversationID:t}=e;return this.store.operationTypeMap.get(t)||0}}class co extends no{constructor(e){super(),this.messageHandlers={[this.getEngine().TYPES.MSG_TEXT]:e=>this.getEngine().TUIChat.messageHandler.handleTextMessage(e),[this.getEngine().TYPES.MSG_FACE]:e=>this.getEngine().TUIChat.messageHandler.handleFaceMessage(e),[this.getEngine().TYPES.MSG_LOCATION]:e=>this.getEngine().TUIChat.messageHandler.handleLocationMessage(e),[this.getEngine().TYPES.MSG_IMAGE]:e=>this.getEngine().TUIChat.messageHandler.handleImageMessage(e),[this.getEngine().TYPES.MSG_AUDIO]:e=>this.getEngine().TUIChat.messageHandler.handleAudioMessage(e),[this.getEngine().TYPES.MSG_VIDEO]:e=>this.getEngine().TUIChat.messageHandler.handleVideoMessage(e),[this.getEngine().TYPES.MSG_FILE]:e=>this.getEngine().TUIChat.messageHandler.handleFileMessage(e),[this.getEngine().TYPES.MSG_CUSTOM]:e=>this.getEngine().TUIChat.messageHandler.handleCustomMessage(e),[this.getEngine().TYPES.MSG_MERGER]:e=>this.getEngine().TUIChat.messageHandler.handleMergeMessage(e),[this.getEngine().TYPES.MSG_GRP_TIP]:e=>this.getEngine().TUIChat.messageHandler.handleGroupTipsMessage(e)},this._message=e,this._signalingInfo=void 0,this.progress=0,this.reactionList=[],this.initProperties(e)}initProperties(e){Object.keys(e).forEach((t=>{Sn(t)||(this[t]=e[t])}))}updateProperties(e){this._message=e,Object.keys(e).forEach((t=>{Sn(t)||(this[t]=e[t])}))}getMessage(){return this._message}modifyMessage(e){return e.type&&this._message.type!==e.type&&!e.payload?Promise.reject({code:ln.MISMATCH_TYPE_AND_PAYLOAD,message:gn.MISMATCH_TYPE_AND_PAYLOAD}):(this._message.type=e.type||this._message.type,this._message.payload=e.payload||this._message.payload,this._message.cloudCustomData=e.cloudCustomData||this._message.cloudCustomData,this.getEngine().TUIChat.modifyMessage(this._message))}revokeMessage(){return this.getEngine().TUIChat.revokeMessage(this._message)}resendMessage(){return this.getEngine().TUIChat.resendMessage(this._message)}deleteMessage(){return this.getEngine().TUIChat.deleteMessage([this._message])}quoteMessage(){return this.getEngine().TUIChat.quoteMessage(this._message)}replyMessage(){return this.getEngine().TUIChat.replyMessage(this._message)}setMessageExtensions(e){return this.getEngine().TUIChat.setMessageExtensions(this._message,e)}getMessageExtensions(){return this.getEngine().TUIChat.getMessageExtensions(this._message)}deleteMessageExtensions(e){return this.getEngine().TUIChat.deleteMessageExtensions(this._message,e)}getSignalingInfo(){return this.type!==this.getEngine().TYPES.MSG_CUSTOM?null:En(this._signalingInfo)?(this._signalingInfo=this.getEngine().chat.getSignalingInfo(this._message),this._signalingInfo):this._signalingInfo}getMessageContent(){const e=this.messageHandlers[this.type];if(En(e))return{};if(this.type===this.getEngine().TYPES.MSG_GRP_TIP)return e(this._message);const t=this.getEngine().TUIFriend.getFriendRemark([this.from]);return Object.assign(Object.assign({},e(this._message)),{showName:t[this.from]||this.nameCard||this.nick||this.from})}sendForwardMessage(e){return this.getEngine().TUIChat.sendForwardMessage(e,[this._message])}}class uo{constructor(){this.defaultStore={messageList:[],isCompleted:!1,nextReqMessageID:"",quoteMessage:{},newMessageList:[],typingStatus:!1,messageSource:void 0,translateTextInfo:void 0,voiceToTextInfo:void 0,userInfo:{}},this.store={messageList:[],isCompleted:!1,nextReqMessageID:"",quoteMessage:{},newMessageList:[],typingStatus:!1,messageSource:void 0,translateTextInfo:void 0,voiceToTextInfo:void 0,userInfo:{}}}update(e,t){switch(e){case"messageList":this.updateMessageList(t);break;case"translateTextInfo":this.updateTranslateTextInfo(t);break;case"voiceToTextInfo":this.updateVoiceToTextInfo(t);break;default:this.store[e]=t}}getData(e){return this.store[e]}getModel(e){return this.store.messageList.find((t=>t.ID===e))}reset(e=[]){const t=e.filter((e=>!kn.includes(e)));this.store=Object.assign(Object.assign(Object.assign({},this.defaultStore),this.store),null==t?void 0:t.reduce(((e,t)=>Object.assign(Object.assign({},e),{[t]:this.defaultStore[t]})),{}))}updateMessageList(e){const t=[];e.forEach((e=>{let s=e;e instanceof co||(s=this.getModel(e.ID),s?s.updateProperties(e):s=new co(e)),t.push(s)})),this.store.messageList=t}updateTranslateTextInfo(e){this.updateBykey("translateTextInfo",e)}updateVoiceToTextInfo(e){this.updateBykey("voiceToTextInfo",e)}updateBykey(e,t){const{conversationID:s,messageID:n,visible:o=!1}=t;this.store[e]||(this.store[e]=new Map),this.store[e].has(s)||this.store[e].set(s,[]);const i=this.store[e].get(s)||[];let r=!0;for(let e=0;e<i.length;e++)if(i[e].messageID===n){i[e].visible=o,r=!1;break}r&&i.push({messageID:n,visible:o}),this.store[e].set(s,i)}}class lo{constructor(e){this.groupAttributes={},this.groupCounters={},this.initProxy(e)}initProxy(e){Object.keys(e).forEach((t=>{Sn(t)||(this[t]=e[t])}))}}class go{constructor(){this.defaultStore={currentGroupID:"",currentGroup:{},currentGroupAttributes:{},currentGroupCounters:{},currentGroupMemberList:[],groupList:[],groupSystemNoticeList:[],isCompleted:!1,offset:0},this.store={currentGroupID:"",currentGroup:void 0,currentGroupAttributes:{},currentGroupCounters:{},currentGroupMemberList:[],groupList:[],groupSystemNoticeList:[],isCompleted:!1,offset:0}}update(e,t){switch(e){case"groupList":this.updateGroupList(t);break;case"currentGroup":this.store.currentGroup=t instanceof lo?t:new lo(t);break;default:this.store[e]=t}}getData(e){if("groupSystemNoticeList"===e){const e=[...this.store.groupSystemNoticeList];return this.store.groupSystemNoticeList.length=0,e}return this.store[e]}reset(e=[]){this.store=Object.assign(Object.assign(Object.assign({},this.defaultStore),this.store),e.reduce(((e,t)=>Object.assign(Object.assign({},e),{[t]:this.defaultStore[t]})),{}))}updateGroupList(e){this.store.groupList=e.map((e=>e instanceof lo?e:new lo(e)))}}class ho{constructor(){this.store={}}update(e,t){this.store[e]=t}getData(e){return this.store[e]}reset(e=[]){0===e.length&&(this.store={}),this.store=Object.assign(Object.assign({},this.store),e.reduce(((e,t)=>Object.assign(Object.assign({},e),{[t]:void 0})),{}))}}class po{constructor(){this.defaultStore={friendList:[],friendApplicationList:[],friendApplicationUnreadCount:0},this.store={friendList:[],friendApplicationList:[],friendApplicationUnreadCount:0}}update(e,t){this.store[e]=t}getData(e){return this.store[e]}reset(e=[]){this.store=Object.assign(Object.assign(Object.assign({},this.defaultStore),this.store),e.reduce(((e,t)=>Object.assign(Object.assign({},e),{[t]:this.defaultStore[t]})),{}))}}class mo{constructor(){this.defaultStore={searchMessagesResult:{resultList:[],hasMore:!1,cursor:"",params:void 0,totalCount:0},searchChatMessagesResult:{resultList:[],hasMore:!1,cursor:"",params:void 0,totalCount:0},searchUserResult:{resultList:[],hasMore:!1,cursor:"",params:void 0,totalCount:0},searchGroupResult:{resultList:[],hasMore:!1,cursor:"",params:void 0,totalCount:0},searchMessageParams:{},searchChatMessageParams:{},searchUserParams:{},searchGroupParams:{},error:null},this.store=this.defaultStore}update(e,t){this.store[e]=t}getData(e){return this.store[e]}reset(e=[]){this.store=Object.assign(Object.assign(Object.assign({},this.defaultStore),this.store),null==e?void 0:e.reduce(((e,t)=>Object.assign(Object.assign({},e),{[t]:this.defaultStore[t]})),{}))}}class fo{constructor(){this.storeMap={[on.APP]:new to,[on.USER]:new so,[on.CONV]:new ao,[on.CHAT]:new uo,[on.GRP]:new go,[on.FRIEND]:new po,[on.SEARCH]:new mo},this.task={}}static getInstance(){return fo.instance||(fo.instance=new fo),fo.instance}watch(e,t){this.task[e]||(this.task[e]={});const s=this.task[e];Object.keys(t).forEach((n=>{const o=t[n];s[n]||(s[n]=new Map),s[n].set(o,1),this.notifyOnWatch(e,n,o)}))}unwatch(e,t){if(!this.task[e])return;const s=this.task[e];Object.keys(t).forEach((e=>{var n;null===(n=s[e])||void 0===n||n.delete(t[e])}))}update(e,t,s){var n;e!==on.CUSTOM||this.storeMap[e]||(this.storeMap[e]=new ho),null===(n=this.storeMap[e])||void 0===n||n.update(t,s),this.notify(e,t)}getData(e,t){var s;return e!==on.CUSTOM||this.storeMap[e]||(this.storeMap[e]=new ho),null===(s=this.storeMap[e])||void 0===s?void 0:s.getData(t)}getConversationModel(e){var t;return null===(t=this.storeMap[on.CONV])||void 0===t?void 0:t.getModel(e)}getMessageModel(e){var t;return null===(t=this.storeMap[on.CHAT])||void 0===t?void 0:t.getModel(e)}reset(e,t=[],s=!1){if(e in this.storeMap){const n=this.storeMap[e];0===t.length&&(t=Object.keys(null==n?void 0:n.store)),n.reset(t),s&&t.forEach((t=>{this.notify(e,t)}))}}notifyOnWatch(e,t,s){const n=this.getData(e,t);Nn.indexOf(t)>-1&&0===n.length||s&&s.call(this,n)}notify(e,t){if(!this.task[e])return;const s=this.task[e];if(s[t]){const n=s[t],o=this.getData(e,t);for(const[e]of n.entries())e.call(this,o)}}}function vo(e){return vo="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},vo(e)}function _o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function Io(e){var t=function(e,t){if("object"!=vo(e)||!e)return e;var s=e[Symbol.toPrimitive];if(void 0!==s){var n=s.call(e,t||"default");if("object"!=vo(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==vo(t)?t:t+""}function yo(e,t){for(var s=0;s<t.length;s++){var n=t[s];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,Io(n.key),n)}}function Eo(e,t,s){return t&&yo(e.prototype,t),s&&yo(e,s),Object.defineProperty(e,"prototype",{writable:!1}),e}function So(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function Co(e,t){return Co=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},Co(e,t)}function Mo(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Co(e,t)}function To(e,t){if(t&&("object"==vo(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return So(e)}function Do(e){return Do=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},Do(e)}function bo(e,t,s){return(t=Io(t))in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}function Oo(e,t){(null==t||t>e.length)&&(t=e.length);for(var s=0,n=Array(t);s<t;s++)n[s]=e[s];return n}function Lo(e){return function(e){if(Array.isArray(e))return e}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||function(e,t){if(e){if("string"==typeof e)return Oo(e,t);var s={}.toString.call(e).slice(8,-1);return"Object"===s&&e.constructor&&(s=e.constructor.name),"Map"===s||"Set"===s?Array.from(e):"Arguments"===s||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s)?Oo(e,t):void 0}}(e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function Ao(e,t){var s=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),s.push.apply(s,n)}return s}function Uo(e){for(var t=1;t<arguments.length;t++){var s=null!=arguments[t]?arguments[t]:{};t%2?Ao(Object(s),!0).forEach((function(t){bo(e,t,s[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(s)):Ao(Object(s)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(s,t))}))}return e}var Ro={type:"logger",log:function(e){this.output("log",e)},warn:function(e){this.output("warn",e)},error:function(e){this.output("error",e)},output:function(e,t){console&&console[e]&&console[e].apply(console,t)}},Po=new(function(){function e(t){var s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};_o(this,e),this.init(t,s)}return Eo(e,[{key:"init",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.prefix=t.prefix||"i18next:",this.logger=e||Ro,this.options=t,this.debug=t.debug}},{key:"setDebug",value:function(e){this.debug=e}},{key:"log",value:function(){for(var e=arguments.length,t=new Array(e),s=0;s<e;s++)t[s]=arguments[s];return this.forward(t,"log","",!0)}},{key:"warn",value:function(){for(var e=arguments.length,t=new Array(e),s=0;s<e;s++)t[s]=arguments[s];return this.forward(t,"warn","",!0)}},{key:"error",value:function(){for(var e=arguments.length,t=new Array(e),s=0;s<e;s++)t[s]=arguments[s];return this.forward(t,"error","")}},{key:"deprecate",value:function(){for(var e=arguments.length,t=new Array(e),s=0;s<e;s++)t[s]=arguments[s];return this.forward(t,"warn","WARNING DEPRECATED: ",!0)}},{key:"forward",value:function(e,t,s,n){return n&&!this.debug?null:("string"==typeof e[0]&&(e[0]="".concat(s).concat(this.prefix," ").concat(e[0])),this.logger[t](e))}},{key:"create",value:function(t){return new e(this.logger,Uo(Uo({},{prefix:"".concat(this.prefix,":").concat(t,":")}),this.options))}},{key:"clone",value:function(t){return(t=t||this.options).prefix=t.prefix||this.prefix,new e(this.logger,t)}}]),e}()),Go=function(){function e(){_o(this,e),this.observers={}}return Eo(e,[{key:"on",value:function(e,t){var s=this;return e.split(" ").forEach((function(e){s.observers[e]=s.observers[e]||[],s.observers[e].push(t)})),this}},{key:"off",value:function(e,t){this.observers[e]&&(t?this.observers[e]=this.observers[e].filter((function(e){return e!==t})):delete this.observers[e])}},{key:"emit",value:function(e){for(var t=arguments.length,s=new Array(t>1?t-1:0),n=1;n<t;n++)s[n-1]=arguments[n];this.observers[e]&&[].concat(this.observers[e]).forEach((function(e){e.apply(void 0,s)}));this.observers["*"]&&[].concat(this.observers["*"]).forEach((function(t){t.apply(t,[e].concat(s))}))}}]),e}();function wo(){var e,t,s=new Promise((function(s,n){e=s,t=n}));return s.resolve=e,s.reject=t,s}function No(e){return null==e?"":""+e}function ko(e,t,s){function n(e){return e&&e.indexOf("###")>-1?e.replace(/###/g,"."):e}function o(){return!e||"string"==typeof e}for(var i="string"!=typeof t?[].concat(t):t.split(".");i.length>1;){if(o())return{};var r=n(i.shift());!e[r]&&s&&(e[r]=new s),e=Object.prototype.hasOwnProperty.call(e,r)?e[r]:{}}return o()?{}:{obj:e,k:n(i.shift())}}function Fo(e,t,s){var n=ko(e,t,Object);n.obj[n.k]=s}function $o(e,t){var s=ko(e,t),n=s.obj,o=s.k;if(n)return n[o]}function xo(e,t,s){var n=$o(e,s);return void 0!==n?n:$o(t,s)}function jo(e,t,s){for(var n in t)"__proto__"!==n&&"constructor"!==n&&(n in e?"string"==typeof e[n]||e[n]instanceof String||"string"==typeof t[n]||t[n]instanceof String?s&&(e[n]=t[n]):jo(e[n],t[n],s):e[n]=t[n]);return e}function Vo(e){return e.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")}var qo={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;"};function Ho(e){return"string"==typeof e?e.replace(/[&<>"'\/]/g,(function(e){return qo[e]})):e}var Bo="undefined"!=typeof window&&window.navigator&&void 0===window.navigator.userAgentData&&window.navigator.userAgent&&window.navigator.userAgent.indexOf("MSIE")>-1,Ko=[" ",",","?","!",";"];function Yo(e,t){var s=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),s.push.apply(s,n)}return s}function Wo(e){for(var t=1;t<arguments.length;t++){var s=null!=arguments[t]?arguments[t]:{};t%2?Yo(Object(s),!0).forEach((function(t){bo(e,t,s[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(s)):Yo(Object(s)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(s,t))}))}return e}function zo(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var s,n=Do(e);if(t){var o=Do(this).constructor;s=Reflect.construct(n,arguments,o)}else s=n.apply(this,arguments);return To(this,s)}}function Jo(e,t){var s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:".";if(e){if(e[t])return e[t];for(var n=t.split(s),o=e,i=0;i<n.length;++i){if(!o)return;if("string"==typeof o[n[i]]&&i+1<n.length)return;if(void 0===o[n[i]]){for(var r=2,a=n.slice(i,i+r).join(s),c=o[a];void 0===c&&n.length>i+r;)r++,c=o[a=n.slice(i,i+r).join(s)];if(void 0===c)return;if(null===c)return null;if(t.endsWith(a)){if("string"==typeof c)return c;if(a&&"string"==typeof c[a])return c[a]}var u=n.slice(i+r).join(s);return u?Jo(c,u,s):void 0}o=o[n[i]]}return o}}var Xo=function(){Mo(t,Go);var e=zo(t);function t(s){var n,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{ns:["translation"],defaultNS:"translation"};return _o(this,t),n=e.call(this),Bo&&Go.call(So(n)),n.data=s||{},n.options=o,void 0===n.options.keySeparator&&(n.options.keySeparator="."),void 0===n.options.ignoreJSONStructure&&(n.options.ignoreJSONStructure=!0),n}return Eo(t,[{key:"addNamespaces",value:function(e){this.options.ns.indexOf(e)<0&&this.options.ns.push(e)}},{key:"removeNamespaces",value:function(e){var t=this.options.ns.indexOf(e);t>-1&&this.options.ns.splice(t,1)}},{key:"getResource",value:function(e,t,s){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},o=void 0!==n.keySeparator?n.keySeparator:this.options.keySeparator,i=void 0!==n.ignoreJSONStructure?n.ignoreJSONStructure:this.options.ignoreJSONStructure,r=[e,t];s&&"string"!=typeof s&&(r=r.concat(s)),s&&"string"==typeof s&&(r=r.concat(o?s.split(o):s)),e.indexOf(".")>-1&&(r=e.split("."));var a=$o(this.data,r);return a||!i||"string"!=typeof s?a:Jo(this.data&&this.data[e]&&this.data[e][t],s,o)}},{key:"addResource",value:function(e,t,s,n){var o=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{silent:!1},i=this.options.keySeparator;void 0===i&&(i=".");var r=[e,t];s&&(r=r.concat(i?s.split(i):s)),e.indexOf(".")>-1&&(n=t,t=(r=e.split("."))[1]),this.addNamespaces(t),Fo(this.data,r,n),o.silent||this.emit("added",e,t,s,n)}},{key:"addResources",value:function(e,t,s){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{silent:!1};for(var o in s)"string"!=typeof s[o]&&"[object Array]"!==Object.prototype.toString.apply(s[o])||this.addResource(e,t,o,s[o],{silent:!0});n.silent||this.emit("added",e,t,s)}},{key:"addResourceBundle",value:function(e,t,s,n,o){var i=arguments.length>5&&void 0!==arguments[5]?arguments[5]:{silent:!1},r=[e,t];e.indexOf(".")>-1&&(n=s,s=t,t=(r=e.split("."))[1]),this.addNamespaces(t);var a=$o(this.data,r)||{};n?jo(a,s,o):a=Wo(Wo({},a),s),Fo(this.data,r,a),i.silent||this.emit("added",e,t,s)}},{key:"removeResourceBundle",value:function(e,t){this.hasResourceBundle(e,t)&&delete this.data[e][t],this.removeNamespaces(t),this.emit("removed",e,t)}},{key:"hasResourceBundle",value:function(e,t){return void 0!==this.getResource(e,t)}},{key:"getResourceBundle",value:function(e,t){return t||(t=this.options.defaultNS),"v1"===this.options.compatibilityAPI?Wo(Wo({},{}),this.getResource(e,t)):this.getResource(e,t)}},{key:"getDataByLanguage",value:function(e){return this.data[e]}},{key:"hasLanguageSomeTranslations",value:function(e){var t=this.getDataByLanguage(e);return!!(t&&Object.keys(t)||[]).find((function(e){return t[e]&&Object.keys(t[e]).length>0}))}},{key:"toJSON",value:function(){return this.data}}]),t}(),Qo={processors:{},addPostProcessor:function(e){this.processors[e.name]=e},handle:function(e,t,s,n,o){var i=this;return e.forEach((function(e){i.processors[e]&&(t=i.processors[e].process(t,s,n,o))})),t}};function Zo(e,t){var s=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),s.push.apply(s,n)}return s}function ei(e){for(var t=1;t<arguments.length;t++){var s=null!=arguments[t]?arguments[t]:{};t%2?Zo(Object(s),!0).forEach((function(t){bo(e,t,s[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(s)):Zo(Object(s)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(s,t))}))}return e}function ti(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var s,n=Do(e);if(t){var o=Do(this).constructor;s=Reflect.construct(n,arguments,o)}else s=n.apply(this,arguments);return To(this,s)}}var si={},ni=function(){Mo(t,Go);var e=ti(t);function t(s){var n,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return _o(this,t),n=e.call(this),Bo&&Go.call(So(n)),function(e,t,s){e.forEach((function(e){t[e]&&(s[e]=t[e])}))}(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],s,So(n)),n.options=o,void 0===n.options.keySeparator&&(n.options.keySeparator="."),n.logger=Po.create("translator"),n}return Eo(t,[{key:"changeLanguage",value:function(e){e&&(this.language=e)}},{key:"exists",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{interpolation:{}};if(null==e)return!1;var s=this.resolve(e,t);return s&&void 0!==s.res}},{key:"extractFromKey",value:function(e,t){var s=void 0!==t.nsSeparator?t.nsSeparator:this.options.nsSeparator;void 0===s&&(s=":");var n=void 0!==t.keySeparator?t.keySeparator:this.options.keySeparator,o=t.ns||this.options.defaultNS||[],i=s&&e.indexOf(s)>-1,r=!(this.options.userDefinedKeySeparator||t.keySeparator||this.options.userDefinedNsSeparator||t.nsSeparator||function(e,t,s){t=t||"",s=s||"";var n=Ko.filter((function(e){return t.indexOf(e)<0&&s.indexOf(e)<0}));if(0===n.length)return!0;var o=new RegExp("(".concat(n.map((function(e){return"?"===e?"\\?":e})).join("|"),")")),i=!o.test(e);if(!i){var r=e.indexOf(s);r>0&&!o.test(e.substring(0,r))&&(i=!0)}return i}(e,s,n));if(i&&!r){var a=e.match(this.interpolator.nestingRegexp);if(a&&a.length>0)return{key:e,namespaces:o};var c=e.split(s);(s!==n||s===n&&this.options.ns.indexOf(c[0])>-1)&&(o=c.shift()),e=c.join(n)}return"string"==typeof o&&(o=[o]),{key:e,namespaces:o}}},{key:"translate",value:function(e,s,n){var o=this;if("object"!==vo(s)&&this.options.overloadTranslationOptionHandler&&(s=this.options.overloadTranslationOptionHandler(arguments)),s||(s={}),null==e)return"";Array.isArray(e)||(e=[String(e)]);var i=void 0!==s.returnDetails?s.returnDetails:this.options.returnDetails,r=void 0!==s.keySeparator?s.keySeparator:this.options.keySeparator,a=this.extractFromKey(e[e.length-1],s),c=a.key,u=a.namespaces,l=u[u.length-1],d=s.lng||this.language,g=s.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if(d&&"cimode"===d.toLowerCase()){if(g){var h=s.nsSeparator||this.options.nsSeparator;return i?{res:"".concat(l).concat(h).concat(c),usedKey:c,exactUsedKey:c,usedLng:d,usedNS:l}:"".concat(l).concat(h).concat(c)}return i?{res:c,usedKey:c,exactUsedKey:c,usedLng:d,usedNS:l}:c}var p=this.resolve(e,s),m=p&&p.res,f=p&&p.usedKey||c,v=p&&p.exactUsedKey||c,_=Object.prototype.toString.apply(m),I=void 0!==s.joinArrays?s.joinArrays:this.options.joinArrays,y=!this.i18nFormat||this.i18nFormat.handleAsObject;if(y&&m&&("string"!=typeof m&&"boolean"!=typeof m&&"number"!=typeof m)&&["[object Number]","[object Function]","[object RegExp]"].indexOf(_)<0&&("string"!=typeof I||"[object Array]"!==_)){if(!s.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");var E=this.options.returnedObjectHandler?this.options.returnedObjectHandler(f,m,ei(ei({},s),{},{ns:u})):"key '".concat(c," (").concat(this.language,")' returned an object instead of string.");return i?(p.res=E,p):E}if(r){var S="[object Array]"===_,C=S?[]:{},M=S?v:f;for(var T in m)if(Object.prototype.hasOwnProperty.call(m,T)){var D="".concat(M).concat(r).concat(T);C[T]=this.translate(D,ei(ei({},s),{joinArrays:!1,ns:u})),C[T]===D&&(C[T]=m[T])}m=C}}else if(y&&"string"==typeof I&&"[object Array]"===_)(m=m.join(I))&&(m=this.extendTranslation(m,e,s,n));else{var b=!1,O=!1,L=void 0!==s.count&&"string"!=typeof s.count,A=t.hasDefaultValue(s),U=L?this.pluralResolver.getSuffix(d,s.count,s):"",R=s["defaultValue".concat(U)]||s.defaultValue;!this.isValidLookup(m)&&A&&(b=!0,m=R),this.isValidLookup(m)||(O=!0,m=c);var P=(s.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&O?void 0:m,G=A&&R!==m&&this.options.updateMissing;if(O||b||G){if(this.logger.log(G?"updateKey":"missingKey",d,l,c,G?R:m),r){var w=this.resolve(c,ei(ei({},s),{},{keySeparator:!1}));w&&w.res&&this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.")}var N=[],k=this.languageUtils.getFallbackCodes(this.options.fallbackLng,s.lng||this.language);if("fallback"===this.options.saveMissingTo&&k&&k[0])for(var F=0;F<k.length;F++)N.push(k[F]);else"all"===this.options.saveMissingTo?N=this.languageUtils.toResolveHierarchy(s.lng||this.language):N.push(s.lng||this.language);var $=function(e,t,n){var i=A&&n!==m?n:P;o.options.missingKeyHandler?o.options.missingKeyHandler(e,l,t,i,G,s):o.backendConnector&&o.backendConnector.saveMissing&&o.backendConnector.saveMissing(e,l,t,i,G,s),o.emit("missingKey",e,l,t,m)};this.options.saveMissing&&(this.options.saveMissingPlurals&&L?N.forEach((function(e){o.pluralResolver.getSuffixes(e,s).forEach((function(t){$([e],c+t,s["defaultValue".concat(t)]||R)}))})):$(N,c,R))}m=this.extendTranslation(m,e,s,p,n),O&&m===c&&this.options.appendNamespaceToMissingKey&&(m="".concat(l,":").concat(c)),(O||b)&&this.options.parseMissingKeyHandler&&(m="v1"!==this.options.compatibilityAPI?this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?"".concat(l,":").concat(c):c,b?m:void 0):this.options.parseMissingKeyHandler(m))}return i?(p.res=m,p):m}},{key:"extendTranslation",value:function(e,t,s,n,o){var i=this;if(this.i18nFormat&&this.i18nFormat.parse)e=this.i18nFormat.parse(e,ei(ei({},this.options.interpolation.defaultVariables),s),n.usedLng,n.usedNS,n.usedKey,{resolved:n});else if(!s.skipInterpolation){s.interpolation&&this.interpolator.init(ei(ei({},s),{interpolation:ei(ei({},this.options.interpolation),s.interpolation)}));var r,a="string"==typeof e&&(s&&s.interpolation&&void 0!==s.interpolation.skipOnVariables?s.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables);if(a){var c=e.match(this.interpolator.nestingRegexp);r=c&&c.length}var u=s.replace&&"string"!=typeof s.replace?s.replace:s;if(this.options.interpolation.defaultVariables&&(u=ei(ei({},this.options.interpolation.defaultVariables),u)),e=this.interpolator.interpolate(e,u,s.lng||this.language,s),a){var l=e.match(this.interpolator.nestingRegexp);r<(l&&l.length)&&(s.nest=!1)}!1!==s.nest&&(e=this.interpolator.nest(e,(function(){for(var e=arguments.length,n=new Array(e),r=0;r<e;r++)n[r]=arguments[r];return o&&o[0]===n[0]&&!s.context?(i.logger.warn("It seems you are nesting recursively key: ".concat(n[0]," in key: ").concat(t[0])),null):i.translate.apply(i,n.concat([t]))}),s)),s.interpolation&&this.interpolator.reset()}var d=s.postProcess||this.options.postProcess,g="string"==typeof d?[d]:d;return null!=e&&g&&g.length&&!1!==s.applyPostProcessor&&(e=Qo.handle(g,e,t,this.options&&this.options.postProcessPassResolved?ei({i18nResolved:n},s):s,this)),e}},{key:"resolve",value:function(e){var t,s,n,o,i,r=this,a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return"string"==typeof e&&(e=[e]),e.forEach((function(e){if(!r.isValidLookup(t)){var c=r.extractFromKey(e,a),u=c.key;s=u;var l=c.namespaces;r.options.fallbackNS&&(l=l.concat(r.options.fallbackNS));var d=void 0!==a.count&&"string"!=typeof a.count,g=d&&!a.ordinal&&0===a.count&&r.pluralResolver.shouldUseIntlApi(),h=void 0!==a.context&&("string"==typeof a.context||"number"==typeof a.context)&&""!==a.context,p=a.lngs?a.lngs:r.languageUtils.toResolveHierarchy(a.lng||r.language,a.fallbackLng);l.forEach((function(e){r.isValidLookup(t)||(i=e,!si["".concat(p[0],"-").concat(e)]&&r.utils&&r.utils.hasLoadedNamespace&&!r.utils.hasLoadedNamespace(i)&&(si["".concat(p[0],"-").concat(e)]=!0,r.logger.warn('key "'.concat(s,'" for languages "').concat(p.join(", "),'" won\'t get resolved as namespace "').concat(i,'" was not yet loaded'),"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!")),p.forEach((function(s){if(!r.isValidLookup(t)){o=s;var i,c=[u];if(r.i18nFormat&&r.i18nFormat.addLookupKeys)r.i18nFormat.addLookupKeys(c,u,s,e,a);else{var l;d&&(l=r.pluralResolver.getSuffix(s,a.count,a));var p="".concat(r.options.pluralSeparator,"zero");if(d&&(c.push(u+l),g&&c.push(u+p)),h){var m="".concat(u).concat(r.options.contextSeparator).concat(a.context);c.push(m),d&&(c.push(m+l),g&&c.push(m+p))}}for(;i=c.pop();)r.isValidLookup(t)||(n=i,t=r.getResource(s,e,i,a))}})))}))}})),{res:t,usedKey:s,exactUsedKey:n,usedLng:o,usedNS:i}}},{key:"isValidLookup",value:function(e){return!(void 0===e||!this.options.returnNull&&null===e||!this.options.returnEmptyString&&""===e)}},{key:"getResource",value:function(e,t,s){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};return this.i18nFormat&&this.i18nFormat.getResource?this.i18nFormat.getResource(e,t,s,n):this.resourceStore.getResource(e,t,s,n)}}],[{key:"hasDefaultValue",value:function(e){var t="defaultValue";for(var s in e)if(Object.prototype.hasOwnProperty.call(e,s)&&t===s.substring(0,12)&&void 0!==e[s])return!0;return!1}}]),t}();function oi(e){return e.charAt(0).toUpperCase()+e.slice(1)}var ii=function(){function e(t){_o(this,e),this.options=t,this.supportedLngs=this.options.supportedLngs||!1,this.logger=Po.create("languageUtils")}return Eo(e,[{key:"getScriptPartFromCode",value:function(e){if(!e||e.indexOf("-")<0)return null;var t=e.split("-");return 2===t.length?null:(t.pop(),"x"===t[t.length-1].toLowerCase()?null:this.formatLanguageCode(t.join("-")))}},{key:"getLanguagePartFromCode",value:function(e){if(!e||e.indexOf("-")<0)return e;var t=e.split("-");return this.formatLanguageCode(t[0])}},{key:"formatLanguageCode",value:function(e){if("string"==typeof e&&e.indexOf("-")>-1){var t=["hans","hant","latn","cyrl","cans","mong","arab"],s=e.split("-");return this.options.lowerCaseLng?s=s.map((function(e){return e.toLowerCase()})):2===s.length?(s[0]=s[0].toLowerCase(),s[1]=s[1].toUpperCase(),t.indexOf(s[1].toLowerCase())>-1&&(s[1]=oi(s[1].toLowerCase()))):3===s.length&&(s[0]=s[0].toLowerCase(),2===s[1].length&&(s[1]=s[1].toUpperCase()),"sgn"!==s[0]&&2===s[2].length&&(s[2]=s[2].toUpperCase()),t.indexOf(s[1].toLowerCase())>-1&&(s[1]=oi(s[1].toLowerCase())),t.indexOf(s[2].toLowerCase())>-1&&(s[2]=oi(s[2].toLowerCase()))),s.join("-")}return this.options.cleanCode||this.options.lowerCaseLng?e.toLowerCase():e}},{key:"isSupportedCode",value:function(e){return("languageOnly"===this.options.load||this.options.nonExplicitSupportedLngs)&&(e=this.getLanguagePartFromCode(e)),!this.supportedLngs||!this.supportedLngs.length||this.supportedLngs.indexOf(e)>-1}},{key:"getBestMatchFromCodes",value:function(e){var t,s=this;return e?(e.forEach((function(e){if(!t){var n=s.formatLanguageCode(e);s.options.supportedLngs&&!s.isSupportedCode(n)||(t=n)}})),!t&&this.options.supportedLngs&&e.forEach((function(e){if(!t){var n=s.getLanguagePartFromCode(e);if(s.isSupportedCode(n))return t=n;t=s.options.supportedLngs.find((function(e){if(0===e.indexOf(n))return e}))}})),t||(t=this.getFallbackCodes(this.options.fallbackLng)[0]),t):null}},{key:"getFallbackCodes",value:function(e,t){if(!e)return[];if("function"==typeof e&&(e=e(t)),"string"==typeof e&&(e=[e]),"[object Array]"===Object.prototype.toString.apply(e))return e;if(!t)return e.default||[];var s=e[t];return s||(s=e[this.getScriptPartFromCode(t)]),s||(s=e[this.formatLanguageCode(t)]),s||(s=e[this.getLanguagePartFromCode(t)]),s||(s=e.default),s||[]}},{key:"toResolveHierarchy",value:function(e,t){var s=this,n=this.getFallbackCodes(t||this.options.fallbackLng||[],e),o=[],i=function(e){e&&(s.isSupportedCode(e)?o.push(e):s.logger.warn("rejecting language code not found in supportedLngs: ".concat(e)))};return"string"==typeof e&&e.indexOf("-")>-1?("languageOnly"!==this.options.load&&i(this.formatLanguageCode(e)),"languageOnly"!==this.options.load&&"currentOnly"!==this.options.load&&i(this.getScriptPartFromCode(e)),"currentOnly"!==this.options.load&&i(this.getLanguagePartFromCode(e))):"string"==typeof e&&i(this.formatLanguageCode(e)),n.forEach((function(e){o.indexOf(e)<0&&i(s.formatLanguageCode(e))})),o}}]),e}(),ri=[{lngs:["ach","ak","am","arn","br","fil","gun","ln","mfe","mg","mi","oc","pt","pt-BR","tg","tl","ti","tr","uz","wa"],nr:[1,2],fc:1},{lngs:["af","an","ast","az","bg","bn","ca","da","de","dev","el","en","eo","es","et","eu","fi","fo","fur","fy","gl","gu","ha","hi","hu","hy","ia","it","kk","kn","ku","lb","mai","ml","mn","mr","nah","nap","nb","ne","nl","nn","no","nso","pa","pap","pms","ps","pt-PT","rm","sco","se","si","so","son","sq","sv","sw","ta","te","tk","ur","yo"],nr:[1,2],fc:2},{lngs:["ay","bo","cgg","fa","ht","id","ja","jbo","ka","km","ko","ky","lo","ms","sah","su","th","tt","ug","vi","wo","zh"],nr:[1],fc:3},{lngs:["be","bs","cnr","dz","hr","ru","sr","uk"],nr:[1,2,5],fc:4},{lngs:["ar"],nr:[0,1,2,3,11,100],fc:5},{lngs:["cs","sk"],nr:[1,2,5],fc:6},{lngs:["csb","pl"],nr:[1,2,5],fc:7},{lngs:["cy"],nr:[1,2,3,8],fc:8},{lngs:["fr"],nr:[1,2],fc:9},{lngs:["ga"],nr:[1,2,3,7,11],fc:10},{lngs:["gd"],nr:[1,2,3,20],fc:11},{lngs:["is"],nr:[1,2],fc:12},{lngs:["jv"],nr:[0,1],fc:13},{lngs:["kw"],nr:[1,2,3,4],fc:14},{lngs:["lt"],nr:[1,2,10],fc:15},{lngs:["lv"],nr:[1,2,0],fc:16},{lngs:["mk"],nr:[1,2],fc:17},{lngs:["mnk"],nr:[0,1,2],fc:18},{lngs:["mt"],nr:[1,2,11,20],fc:19},{lngs:["or"],nr:[2,1],fc:2},{lngs:["ro"],nr:[1,2,20],fc:20},{lngs:["sl"],nr:[5,1,2,3],fc:21},{lngs:["he","iw"],nr:[1,2,20,21],fc:22}],ai={1:function(e){return Number(e>1)},2:function(e){return Number(1!=e)},3:function(e){return 0},4:function(e){return Number(e%10==1&&e%100!=11?0:e%10>=2&&e%10<=4&&(e%100<10||e%100>=20)?1:2)},5:function(e){return Number(0==e?0:1==e?1:2==e?2:e%100>=3&&e%100<=10?3:e%100>=11?4:5)},6:function(e){return Number(1==e?0:e>=2&&e<=4?1:2)},7:function(e){return Number(1==e?0:e%10>=2&&e%10<=4&&(e%100<10||e%100>=20)?1:2)},8:function(e){return Number(1==e?0:2==e?1:8!=e&&11!=e?2:3)},9:function(e){return Number(e>=2)},10:function(e){return Number(1==e?0:2==e?1:e<7?2:e<11?3:4)},11:function(e){return Number(1==e||11==e?0:2==e||12==e?1:e>2&&e<20?2:3)},12:function(e){return Number(e%10!=1||e%100==11)},13:function(e){return Number(0!==e)},14:function(e){return Number(1==e?0:2==e?1:3==e?2:3)},15:function(e){return Number(e%10==1&&e%100!=11?0:e%10>=2&&(e%100<10||e%100>=20)?1:2)},16:function(e){return Number(e%10==1&&e%100!=11?0:0!==e?1:2)},17:function(e){return Number(1==e||e%10==1&&e%100!=11?0:1)},18:function(e){return Number(0==e?0:1==e?1:2)},19:function(e){return Number(1==e?0:0==e||e%100>1&&e%100<11?1:e%100>10&&e%100<20?2:3)},20:function(e){return Number(1==e?0:0==e||e%100>0&&e%100<20?1:2)},21:function(e){return Number(e%100==1?1:e%100==2?2:e%100==3||e%100==4?3:0)},22:function(e){return Number(1==e?0:2==e?1:(e<0||e>10)&&e%10==0?2:3)}},ci=["v1","v2","v3"],ui={zero:0,one:1,two:2,few:3,many:4,other:5};var li=function(){function e(t){var s,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};_o(this,e),this.languageUtils=t,this.options=n,this.logger=Po.create("pluralResolver"),this.options.compatibilityJSON&&"v4"!==this.options.compatibilityJSON||"undefined"!=typeof Intl&&Intl.PluralRules||(this.options.compatibilityJSON="v3",this.logger.error("Your environment seems not to be Intl API compatible, use an Intl.PluralRules polyfill. Will fallback to the compatibilityJSON v3 format handling.")),this.rules=(s={},ri.forEach((function(e){e.lngs.forEach((function(t){s[t]={numbers:e.nr,plurals:ai[e.fc]}}))})),s)}return Eo(e,[{key:"addRule",value:function(e,t){this.rules[e]=t}},{key:"getRule",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this.shouldUseIntlApi())try{return new Intl.PluralRules(e,{type:t.ordinal?"ordinal":"cardinal"})}catch(e){return}return this.rules[e]||this.rules[this.languageUtils.getLanguagePartFromCode(e)]}},{key:"needsPlural",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},s=this.getRule(e,t);return this.shouldUseIntlApi()?s&&s.resolvedOptions().pluralCategories.length>1:s&&s.numbers.length>1}},{key:"getPluralFormsOfKey",value:function(e,t){var s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return this.getSuffixes(e,s).map((function(e){return"".concat(t).concat(e)}))}},{key:"getSuffixes",value:function(e){var t=this,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=this.getRule(e,s);return n?this.shouldUseIntlApi()?n.resolvedOptions().pluralCategories.sort((function(e,t){return ui[e]-ui[t]})).map((function(e){return"".concat(t.options.prepend).concat(e)})):n.numbers.map((function(n){return t.getSuffix(e,n,s)})):[]}},{key:"getSuffix",value:function(e,t){var s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=this.getRule(e,s);return n?this.shouldUseIntlApi()?"".concat(this.options.prepend).concat(n.select(t)):this.getSuffixRetroCompatible(n,t):(this.logger.warn("no plural rule found for: ".concat(e)),"")}},{key:"getSuffixRetroCompatible",value:function(e,t){var s=this,n=e.noAbs?e.plurals(t):e.plurals(Math.abs(t)),o=e.numbers[n];this.options.simplifyPluralSuffix&&2===e.numbers.length&&1===e.numbers[0]&&(2===o?o="plural":1===o&&(o=""));var i=function(){return s.options.prepend&&o.toString()?s.options.prepend+o.toString():o.toString()};return"v1"===this.options.compatibilityJSON?1===o?"":"number"==typeof o?"_plural_".concat(o.toString()):i():"v2"===this.options.compatibilityJSON||this.options.simplifyPluralSuffix&&2===e.numbers.length&&1===e.numbers[0]?i():this.options.prepend&&n.toString()?this.options.prepend+n.toString():n.toString()}},{key:"shouldUseIntlApi",value:function(){return!ci.includes(this.options.compatibilityJSON)}}]),e}();function di(e,t){var s=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),s.push.apply(s,n)}return s}function gi(e){for(var t=1;t<arguments.length;t++){var s=null!=arguments[t]?arguments[t]:{};t%2?di(Object(s),!0).forEach((function(t){bo(e,t,s[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(s)):di(Object(s)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(s,t))}))}return e}var hi=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};_o(this,e),this.logger=Po.create("interpolator"),this.options=t,this.format=t.interpolation&&t.interpolation.format||function(e){return e},this.init(t)}return Eo(e,[{key:"init",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};e.interpolation||(e.interpolation={escapeValue:!0});var t=e.interpolation;this.escape=void 0!==t.escape?t.escape:Ho,this.escapeValue=void 0===t.escapeValue||t.escapeValue,this.useRawValueToEscape=void 0!==t.useRawValueToEscape&&t.useRawValueToEscape,this.prefix=t.prefix?Vo(t.prefix):t.prefixEscaped||"{{",this.suffix=t.suffix?Vo(t.suffix):t.suffixEscaped||"}}",this.formatSeparator=t.formatSeparator?t.formatSeparator:t.formatSeparator||",",this.unescapePrefix=t.unescapeSuffix?"":t.unescapePrefix||"-",this.unescapeSuffix=this.unescapePrefix?"":t.unescapeSuffix||"",this.nestingPrefix=t.nestingPrefix?Vo(t.nestingPrefix):t.nestingPrefixEscaped||Vo("$t("),this.nestingSuffix=t.nestingSuffix?Vo(t.nestingSuffix):t.nestingSuffixEscaped||Vo(")"),this.nestingOptionsSeparator=t.nestingOptionsSeparator?t.nestingOptionsSeparator:t.nestingOptionsSeparator||",",this.maxReplaces=t.maxReplaces?t.maxReplaces:1e3,this.alwaysFormat=void 0!==t.alwaysFormat&&t.alwaysFormat,this.resetRegExp()}},{key:"reset",value:function(){this.options&&this.init(this.options)}},{key:"resetRegExp",value:function(){var e="".concat(this.prefix,"(.+?)").concat(this.suffix);this.regexp=new RegExp(e,"g");var t="".concat(this.prefix).concat(this.unescapePrefix,"(.+?)").concat(this.unescapeSuffix).concat(this.suffix);this.regexpUnescape=new RegExp(t,"g");var s="".concat(this.nestingPrefix,"(.+?)").concat(this.nestingSuffix);this.nestingRegexp=new RegExp(s,"g")}},{key:"interpolate",value:function(e,t,s,n){var o,i,r,a=this,c=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{};function u(e){return e.replace(/\$/g,"$$$$")}var l=function(e){if(e.indexOf(a.formatSeparator)<0){var o=xo(t,c,e);return a.alwaysFormat?a.format(o,void 0,s,gi(gi(gi({},n),t),{},{interpolationkey:e})):o}var i=e.split(a.formatSeparator),r=i.shift().trim(),u=i.join(a.formatSeparator).trim();return a.format(xo(t,c,r),u,s,gi(gi(gi({},n),t),{},{interpolationkey:r}))};this.resetRegExp();var d=n&&n.missingInterpolationHandler||this.options.missingInterpolationHandler,g=n&&n.interpolation&&void 0!==n.interpolation.skipOnVariables?n.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:function(e){return u(e)}},{regex:this.regexp,safeValue:function(e){return a.escapeValue?u(a.escape(e)):u(e)}}].forEach((function(t){for(r=0;o=t.regex.exec(e);){var s=o[1].trim();if(void 0===(i=l(s)))if("function"==typeof d){var c=d(e,o,n);i="string"==typeof c?c:""}else if(n&&Object.prototype.hasOwnProperty.call(n,s))i="";else{if(g){i=o[0];continue}a.logger.warn("missed to pass in variable ".concat(s," for interpolating ").concat(e)),i=""}else"string"==typeof i||a.useRawValueToEscape||(i=No(i));var u=t.safeValue(i);if(e=e.replace(o[0],u),g?(t.regex.lastIndex+=i.length,t.regex.lastIndex-=o[0].length):t.regex.lastIndex=0,++r>=a.maxReplaces)break}})),e}},{key:"nest",value:function(e,t){var s,n,o,i=this,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};function a(e,t){var s=this.nestingOptionsSeparator;if(e.indexOf(s)<0)return e;var n=e.split(new RegExp("".concat(s,"[ ]*{"))),i="{".concat(n[1]);e=n[0];var r=(i=this.interpolate(i,o)).match(/'/g),a=i.match(/"/g);(r&&r.length%2==0&&!a||a.length%2!=0)&&(i=i.replace(/'/g,'"'));try{o=JSON.parse(i),t&&(o=gi(gi({},t),o))}catch(t){return this.logger.warn("failed parsing options string in nesting for key ".concat(e),t),"".concat(e).concat(s).concat(i)}return delete o.defaultValue,e}for(;s=this.nestingRegexp.exec(e);){var c=[];(o=(o=gi({},r)).replace&&"string"!=typeof o.replace?o.replace:o).applyPostProcessor=!1,delete o.defaultValue;var u=!1;if(-1!==s[0].indexOf(this.formatSeparator)&&!/{.*}/.test(s[1])){var l=s[1].split(this.formatSeparator).map((function(e){return e.trim()}));s[1]=l.shift(),c=l,u=!0}if((n=t(a.call(this,s[1].trim(),o),o))&&s[0]===e&&"string"!=typeof n)return n;"string"!=typeof n&&(n=No(n)),n||(this.logger.warn("missed to resolve ".concat(s[1]," for nesting ").concat(e)),n=""),u&&(n=c.reduce((function(e,t){return i.format(e,t,r.lng,gi(gi({},r),{},{interpolationkey:s[1].trim()}))}),n.trim())),e=e.replace(s[0],n),this.regexp.lastIndex=0}return e}}]),e}();function pi(e,t){var s=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),s.push.apply(s,n)}return s}function mi(e){for(var t=1;t<arguments.length;t++){var s=null!=arguments[t]?arguments[t]:{};t%2?pi(Object(s),!0).forEach((function(t){bo(e,t,s[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(s)):pi(Object(s)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(s,t))}))}return e}function fi(e){var t={};return function(s,n,o){var i=n+JSON.stringify(o),r=t[i];return r||(r=e(n,o),t[i]=r),r(s)}}var vi=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};_o(this,e),this.logger=Po.create("formatter"),this.options=t,this.formats={number:fi((function(e,t){var s=new Intl.NumberFormat(e,mi({},t));return function(e){return s.format(e)}})),currency:fi((function(e,t){var s=new Intl.NumberFormat(e,mi(mi({},t),{},{style:"currency"}));return function(e){return s.format(e)}})),datetime:fi((function(e,t){var s=new Intl.DateTimeFormat(e,mi({},t));return function(e){return s.format(e)}})),relativetime:fi((function(e,t){var s=new Intl.RelativeTimeFormat(e,mi({},t));return function(e){return s.format(e,t.range||"day")}})),list:fi((function(e,t){var s=new Intl.ListFormat(e,mi({},t));return function(e){return s.format(e)}}))},this.init(t)}return Eo(e,[{key:"init",value:function(e){var t=(arguments.length>1&&void 0!==arguments[1]?arguments[1]:{interpolation:{}}).interpolation;this.formatSeparator=t.formatSeparator?t.formatSeparator:t.formatSeparator||","}},{key:"add",value:function(e,t){this.formats[e.toLowerCase().trim()]=t}},{key:"addCached",value:function(e,t){this.formats[e.toLowerCase().trim()]=fi(t)}},{key:"format",value:function(e,t,s){var n=this,o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},i=t.split(this.formatSeparator).reduce((function(e,t){var i=function(e){var t=e.toLowerCase().trim(),s={};if(e.indexOf("(")>-1){var n=e.split("(");t=n[0].toLowerCase().trim();var o=n[1].substring(0,n[1].length-1);"currency"===t&&o.indexOf(":")<0?s.currency||(s.currency=o.trim()):"relativetime"===t&&o.indexOf(":")<0?s.range||(s.range=o.trim()):o.split(";").forEach((function(e){if(e){var t=Lo(e.split(":")),n=t[0],o=t.slice(1).join(":").trim().replace(/^'+|'+$/g,"");s[n.trim()]||(s[n.trim()]=o),"false"===o&&(s[n.trim()]=!1),"true"===o&&(s[n.trim()]=!0),isNaN(o)||(s[n.trim()]=parseInt(o,10))}}))}return{formatName:t,formatOptions:s}}(t),r=i.formatName,a=i.formatOptions;if(n.formats[r]){var c=e;try{var u=o&&o.formatParams&&o.formatParams[o.interpolationkey]||{},l=u.locale||u.lng||o.locale||o.lng||s;c=n.formats[r](e,l,mi(mi(mi({},a),o),u))}catch(e){n.logger.warn(e)}return c}return n.logger.warn("there was no format function for ".concat(r)),e}),e);return i}}]),e}();function _i(e,t){var s=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),s.push.apply(s,n)}return s}function Ii(e){for(var t=1;t<arguments.length;t++){var s=null!=arguments[t]?arguments[t]:{};t%2?_i(Object(s),!0).forEach((function(t){bo(e,t,s[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(s)):_i(Object(s)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(s,t))}))}return e}function yi(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var s,n=Do(e);if(t){var o=Do(this).constructor;s=Reflect.construct(n,arguments,o)}else s=n.apply(this,arguments);return To(this,s)}}var Ei=function(){Mo(t,Go);var e=yi(t);function t(s,n,o){var i,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};return _o(this,t),i=e.call(this),Bo&&Go.call(So(i)),i.backend=s,i.store=n,i.services=o,i.languageUtils=o.languageUtils,i.options=r,i.logger=Po.create("backendConnector"),i.waitingReads=[],i.maxParallelReads=r.maxParallelReads||10,i.readingCalls=0,i.maxRetries=r.maxRetries>=0?r.maxRetries:5,i.retryTimeout=r.retryTimeout>=1?r.retryTimeout:350,i.state={},i.queue=[],i.backend&&i.backend.init&&i.backend.init(o,r.backend,r),i}return Eo(t,[{key:"queueLoad",value:function(e,t,s,n){var o=this,i={},r={},a={},c={};return e.forEach((function(e){var n=!0;t.forEach((function(t){var a="".concat(e,"|").concat(t);!s.reload&&o.store.hasResourceBundle(e,t)?o.state[a]=2:o.state[a]<0||(1===o.state[a]?void 0===r[a]&&(r[a]=!0):(o.state[a]=1,n=!1,void 0===r[a]&&(r[a]=!0),void 0===i[a]&&(i[a]=!0),void 0===c[t]&&(c[t]=!0)))})),n||(a[e]=!0)})),(Object.keys(i).length||Object.keys(r).length)&&this.queue.push({pending:r,pendingCount:Object.keys(r).length,loaded:{},errors:[],callback:n}),{toLoad:Object.keys(i),pending:Object.keys(r),toLoadLanguages:Object.keys(a),toLoadNamespaces:Object.keys(c)}}},{key:"loaded",value:function(e,t,s){var n=e.split("|"),o=n[0],i=n[1];t&&this.emit("failedLoading",o,i,t),s&&this.store.addResourceBundle(o,i,s),this.state[e]=t?-1:2;var r={};this.queue.forEach((function(s){!function(e,t,s,n){var o=ko(e,t,Object),i=o.obj,r=o.k;i[r]=i[r]||[],n&&(i[r]=i[r].concat(s)),n||i[r].push(s)}(s.loaded,[o],i),function(e,t){void 0!==e.pending[t]&&(delete e.pending[t],e.pendingCount--)}(s,e),t&&s.errors.push(t),0!==s.pendingCount||s.done||(Object.keys(s.loaded).forEach((function(e){r[e]||(r[e]={});var t=s.loaded[e];t.length&&t.forEach((function(t){void 0===r[e][t]&&(r[e][t]=!0)}))})),s.done=!0,s.errors.length?s.callback(s.errors):s.callback())})),this.emit("loaded",r),this.queue=this.queue.filter((function(e){return!e.done}))}},{key:"read",value:function(e,t,s){var n=this,o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:this.retryTimeout,r=arguments.length>5?arguments[5]:void 0;if(!e.length)return r(null,{});if(this.readingCalls>=this.maxParallelReads)this.waitingReads.push({lng:e,ns:t,fcName:s,tried:o,wait:i,callback:r});else{this.readingCalls++;var a=function(a,c){if(n.readingCalls--,n.waitingReads.length>0){var u=n.waitingReads.shift();n.read(u.lng,u.ns,u.fcName,u.tried,u.wait,u.callback)}a&&c&&o<n.maxRetries?setTimeout((function(){n.read.call(n,e,t,s,o+1,2*i,r)}),i):r(a,c)},c=this.backend[s].bind(this.backend);if(2!==c.length)return c(e,t,a);try{var u=c(e,t);u&&"function"==typeof u.then?u.then((function(e){return a(null,e)})).catch(a):a(null,u)}catch(e){a(e)}}}},{key:"prepareLoading",value:function(e,t){var s=this,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},o=arguments.length>3?arguments[3]:void 0;if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),o&&o();"string"==typeof e&&(e=this.languageUtils.toResolveHierarchy(e)),"string"==typeof t&&(t=[t]);var i=this.queueLoad(e,t,n,o);if(!i.toLoad.length)return i.pending.length||o(),null;i.toLoad.forEach((function(e){s.loadOne(e)}))}},{key:"load",value:function(e,t,s){this.prepareLoading(e,t,{},s)}},{key:"reload",value:function(e,t,s){this.prepareLoading(e,t,{reload:!0},s)}},{key:"loadOne",value:function(e){var t=this,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",n=e.split("|"),o=n[0],i=n[1];this.read(o,i,"read",void 0,void 0,(function(n,r){n&&t.logger.warn("".concat(s,"loading namespace ").concat(i," for language ").concat(o," failed"),n),!n&&r&&t.logger.log("".concat(s,"loaded namespace ").concat(i," for language ").concat(o),r),t.loaded(e,n,r)}))}},{key:"saveMissing",value:function(e,t,s,n,o){var i=arguments.length>5&&void 0!==arguments[5]?arguments[5]:{},r=arguments.length>6&&void 0!==arguments[6]?arguments[6]:function(){};if(this.services.utils&&this.services.utils.hasLoadedNamespace&&!this.services.utils.hasLoadedNamespace(t))this.logger.warn('did not save key "'.concat(s,'" as the namespace "').concat(t,'" was not yet loaded'),"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");else if(null!=s&&""!==s){if(this.backend&&this.backend.create){var a=Ii(Ii({},i),{},{isUpdate:o}),c=this.backend.create.bind(this.backend);if(c.length<6)try{var u;(u=5===c.length?c(e,t,s,n,a):c(e,t,s,n))&&"function"==typeof u.then?u.then((function(e){return r(null,e)})).catch(r):r(null,u)}catch(e){r(e)}else c(e,t,s,n,r,a)}e&&e[0]&&this.store.addResource(e[0],t,s,n)}}}]),t}();function Si(){return{debug:!1,initImmediate:!0,ns:["translation"],defaultNS:["translation"],fallbackLng:["dev"],fallbackNS:!1,supportedLngs:!1,nonExplicitSupportedLngs:!1,load:"all",preload:!1,simplifyPluralSuffix:!0,keySeparator:".",nsSeparator:":",pluralSeparator:"_",contextSeparator:"_",partialBundledLanguages:!1,saveMissing:!1,updateMissing:!1,saveMissingTo:"fallback",saveMissingPlurals:!0,missingKeyHandler:!1,missingInterpolationHandler:!1,postProcess:!1,postProcessPassResolved:!1,returnNull:!0,returnEmptyString:!0,returnObjects:!1,joinArrays:!1,returnedObjectHandler:!1,parseMissingKeyHandler:!1,appendNamespaceToMissingKey:!1,appendNamespaceToCIMode:!1,overloadTranslationOptionHandler:function(e){var t={};if("object"===vo(e[1])&&(t=e[1]),"string"==typeof e[1]&&(t.defaultValue=e[1]),"string"==typeof e[2]&&(t.tDescription=e[2]),"object"===vo(e[2])||"object"===vo(e[3])){var s=e[3]||e[2];Object.keys(s).forEach((function(e){t[e]=s[e]}))}return t},interpolation:{escapeValue:!0,format:function(e,t,s,n){return e},prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!0}}}function Ci(e){return"string"==typeof e.ns&&(e.ns=[e.ns]),"string"==typeof e.fallbackLng&&(e.fallbackLng=[e.fallbackLng]),"string"==typeof e.fallbackNS&&(e.fallbackNS=[e.fallbackNS]),e.supportedLngs&&e.supportedLngs.indexOf("cimode")<0&&(e.supportedLngs=e.supportedLngs.concat(["cimode"])),e}function Mi(e,t){var s=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),s.push.apply(s,n)}return s}function Ti(e){for(var t=1;t<arguments.length;t++){var s=null!=arguments[t]?arguments[t]:{};t%2?Mi(Object(s),!0).forEach((function(t){bo(e,t,s[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(s)):Mi(Object(s)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(s,t))}))}return e}function Di(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var s,n=Do(e);if(t){var o=Do(this).constructor;s=Reflect.construct(n,arguments,o)}else s=n.apply(this,arguments);return To(this,s)}}function bi(){}var Oi=function(){Mo(t,Go);var e=Di(t);function t(){var s,n,o=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},i=arguments.length>1?arguments[1]:void 0;if(_o(this,t),s=e.call(this),Bo&&Go.call(So(s)),s.options=Ci(o),s.services={},s.logger=Po,s.modules={external:[]},n=So(s),Object.getOwnPropertyNames(Object.getPrototypeOf(n)).forEach((function(e){"function"==typeof n[e]&&(n[e]=n[e].bind(n))})),i&&!s.isInitialized&&!o.isClone){if(!s.options.initImmediate)return s.init(o,i),To(s,So(s));setTimeout((function(){s.init(o,i)}),0)}return s}return Eo(t,[{key:"init",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},s=arguments.length>1?arguments[1]:void 0;"function"==typeof t&&(s=t,t={}),!t.defaultNS&&!1!==t.defaultNS&&t.ns&&("string"==typeof t.ns?t.defaultNS=t.ns:t.ns.indexOf("translation")<0&&(t.defaultNS=t.ns[0]));var n=Si();function o(e){return e?"function"==typeof e?new e:e:null}if(this.options=Ti(Ti(Ti({},n),this.options),Ci(t)),"v1"!==this.options.compatibilityAPI&&(this.options.interpolation=Ti(Ti({},n.interpolation),this.options.interpolation)),void 0!==t.keySeparator&&(this.options.userDefinedKeySeparator=t.keySeparator),void 0!==t.nsSeparator&&(this.options.userDefinedNsSeparator=t.nsSeparator),!this.options.isClone){var i;this.modules.logger?Po.init(o(this.modules.logger),this.options):Po.init(null,this.options),this.modules.formatter?i=this.modules.formatter:"undefined"!=typeof Intl&&(i=vi);var r=new ii(this.options);this.store=new Xo(this.options.resources,this.options);var a=this.services;a.logger=Po,a.resourceStore=this.store,a.languageUtils=r,a.pluralResolver=new li(r,{prepend:this.options.pluralSeparator,compatibilityJSON:this.options.compatibilityJSON,simplifyPluralSuffix:this.options.simplifyPluralSuffix}),!i||this.options.interpolation.format&&this.options.interpolation.format!==n.interpolation.format||(a.formatter=o(i),a.formatter.init(a,this.options),this.options.interpolation.format=a.formatter.format.bind(a.formatter)),a.interpolator=new hi(this.options),a.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},a.backendConnector=new Ei(o(this.modules.backend),a.resourceStore,a,this.options),a.backendConnector.on("*",(function(t){for(var s=arguments.length,n=new Array(s>1?s-1:0),o=1;o<s;o++)n[o-1]=arguments[o];e.emit.apply(e,[t].concat(n))})),this.modules.languageDetector&&(a.languageDetector=o(this.modules.languageDetector),a.languageDetector.init&&a.languageDetector.init(a,this.options.detection,this.options)),this.modules.i18nFormat&&(a.i18nFormat=o(this.modules.i18nFormat),a.i18nFormat.init&&a.i18nFormat.init(this)),this.translator=new ni(this.services,this.options),this.translator.on("*",(function(t){for(var s=arguments.length,n=new Array(s>1?s-1:0),o=1;o<s;o++)n[o-1]=arguments[o];e.emit.apply(e,[t].concat(n))})),this.modules.external.forEach((function(t){t.init&&t.init(e)}))}if(this.format=this.options.interpolation.format,s||(s=bi),this.options.fallbackLng&&!this.services.languageDetector&&!this.options.lng){var c=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);c.length>0&&"dev"!==c[0]&&(this.options.lng=c[0])}this.services.languageDetector||this.options.lng||this.logger.warn("init: no languageDetector is used and no lng is defined");["getResource","hasResourceBundle","getResourceBundle","getDataByLanguage"].forEach((function(t){e[t]=function(){var s;return(s=e.store)[t].apply(s,arguments)}}));["addResource","addResources","addResourceBundle","removeResourceBundle"].forEach((function(t){e[t]=function(){var s;return(s=e.store)[t].apply(s,arguments),e}}));var u=wo(),l=function(){var t=function(t,n){e.isInitialized&&!e.initializedStoreOnce&&e.logger.warn("init: i18next is already initialized. You should call init just once!"),e.isInitialized=!0,e.options.isClone||e.logger.log("initialized",e.options),e.emit("initialized",e.options),u.resolve(n),s(t,n)};if(e.languages&&"v1"!==e.options.compatibilityAPI&&!e.isInitialized)return t(null,e.t.bind(e));e.changeLanguage(e.options.lng,t)};return this.options.resources||!this.options.initImmediate?l():setTimeout(l,0),u}},{key:"loadResources",value:function(e){var t=this,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:bi,n="string"==typeof e?e:this.language;if("function"==typeof e&&(s=e),!this.options.resources||this.options.partialBundledLanguages){if(n&&"cimode"===n.toLowerCase())return s();var o=[],i=function(e){e&&t.services.languageUtils.toResolveHierarchy(e).forEach((function(e){o.indexOf(e)<0&&o.push(e)}))};if(n)i(n);else this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach((function(e){return i(e)}));this.options.preload&&this.options.preload.forEach((function(e){return i(e)})),this.services.backendConnector.load(o,this.options.ns,(function(e){e||t.resolvedLanguage||!t.language||t.setResolvedLanguage(t.language),s(e)}))}else s(null)}},{key:"reloadResources",value:function(e,t,s){var n=wo();return e||(e=this.languages),t||(t=this.options.ns),s||(s=bi),this.services.backendConnector.reload(e,t,(function(e){n.resolve(),s(e)})),n}},{key:"use",value:function(e){if(!e)throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");if(!e.type)throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");return"backend"===e.type&&(this.modules.backend=e),("logger"===e.type||e.log&&e.warn&&e.error)&&(this.modules.logger=e),"languageDetector"===e.type&&(this.modules.languageDetector=e),"i18nFormat"===e.type&&(this.modules.i18nFormat=e),"postProcessor"===e.type&&Qo.addPostProcessor(e),"formatter"===e.type&&(this.modules.formatter=e),"3rdParty"===e.type&&this.modules.external.push(e),this}},{key:"setResolvedLanguage",value:function(e){if(e&&this.languages&&!(["cimode","dev"].indexOf(e)>-1))for(var t=0;t<this.languages.length;t++){var s=this.languages[t];if(!(["cimode","dev"].indexOf(s)>-1)&&this.store.hasLanguageSomeTranslations(s)){this.resolvedLanguage=s;break}}}},{key:"changeLanguage",value:function(e,t){var s=this;this.isLanguageChangingTo=e;var n=wo();this.emit("languageChanging",e);var o=function(e){s.language=e,s.languages=s.services.languageUtils.toResolveHierarchy(e),s.resolvedLanguage=void 0,s.setResolvedLanguage(e)},i=function(i){e||i||!s.services.languageDetector||(i=[]);var r="string"==typeof i?i:s.services.languageUtils.getBestMatchFromCodes(i);r&&(s.language||o(r),s.translator.language||s.translator.changeLanguage(r),s.services.languageDetector&&s.services.languageDetector.cacheUserLanguage&&s.services.languageDetector.cacheUserLanguage(r)),s.loadResources(r,(function(e){!function(e,i){i?(o(i),s.translator.changeLanguage(i),s.isLanguageChangingTo=void 0,s.emit("languageChanged",i),s.logger.log("languageChanged",i)):s.isLanguageChangingTo=void 0,n.resolve((function(){return s.t.apply(s,arguments)})),t&&t(e,(function(){return s.t.apply(s,arguments)}))}(e,r)}))};return e||!this.services.languageDetector||this.services.languageDetector.async?!e&&this.services.languageDetector&&this.services.languageDetector.async?0===this.services.languageDetector.detect.length?this.services.languageDetector.detect().then(i):this.services.languageDetector.detect(i):i(e):i(this.services.languageDetector.detect()),n}},{key:"getFixedT",value:function(e,t,s){var n=this,o=function e(t,o){var i;if("object"!==vo(o)){for(var r=arguments.length,a=new Array(r>2?r-2:0),c=2;c<r;c++)a[c-2]=arguments[c];i=n.options.overloadTranslationOptionHandler([t,o].concat(a))}else i=Ti({},o);i.lng=i.lng||e.lng,i.lngs=i.lngs||e.lngs,i.ns=i.ns||e.ns,i.keyPrefix=i.keyPrefix||s||e.keyPrefix;var u,l=n.options.keySeparator||".";return u=i.keyPrefix&&Array.isArray(t)?t.map((function(e){return"".concat(i.keyPrefix).concat(l).concat(e)})):i.keyPrefix?"".concat(i.keyPrefix).concat(l).concat(t):t,n.t(u,i)};return"string"==typeof e?o.lng=e:o.lngs=e,o.ns=t,o.keyPrefix=s,o}},{key:"t",value:function(){var e;return this.translator&&(e=this.translator).translate.apply(e,arguments)}},{key:"exists",value:function(){var e;return this.translator&&(e=this.translator).exists.apply(e,arguments)}},{key:"setDefaultNamespace",value:function(e){this.options.defaultNS=e}},{key:"hasLoadedNamespace",value:function(e){var t=this,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!this.isInitialized)return this.logger.warn("hasLoadedNamespace: i18next was not initialized",this.languages),!1;if(!this.languages||!this.languages.length)return this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty",this.languages),!1;var n=this.resolvedLanguage||this.languages[0],o=!!this.options&&this.options.fallbackLng,i=this.languages[this.languages.length-1];if("cimode"===n.toLowerCase())return!0;var r=function(e,s){var n=t.services.backendConnector.state["".concat(e,"|").concat(s)];return-1===n||2===n};if(s.precheck){var a=s.precheck(this,r);if(void 0!==a)return a}return!!this.hasResourceBundle(n,e)||(!(this.services.backendConnector.backend&&(!this.options.resources||this.options.partialBundledLanguages))||!(!r(n,e)||o&&!r(i,e)))}},{key:"loadNamespaces",value:function(e,t){var s=this,n=wo();return this.options.ns?("string"==typeof e&&(e=[e]),e.forEach((function(e){s.options.ns.indexOf(e)<0&&s.options.ns.push(e)})),this.loadResources((function(e){n.resolve(),t&&t(e)})),n):(t&&t(),Promise.resolve())}},{key:"loadLanguages",value:function(e,t){var s=wo();"string"==typeof e&&(e=[e]);var n=this.options.preload||[],o=e.filter((function(e){return n.indexOf(e)<0}));return o.length?(this.options.preload=n.concat(o),this.loadResources((function(e){s.resolve(),t&&t(e)})),s):(t&&t(),Promise.resolve())}},{key:"dir",value:function(e){if(e||(e=this.resolvedLanguage||(this.languages&&this.languages.length>0?this.languages[0]:this.language)),!e)return"rtl";var t=this.services&&this.services.languageUtils||new ii(Si());return["ar","shu","sqr","ssh","xaa","yhd","yud","aao","abh","abv","acm","acq","acw","acx","acy","adf","ads","aeb","aec","afb","ajp","apc","apd","arb","arq","ars","ary","arz","auz","avl","ayh","ayl","ayn","ayp","bbz","pga","he","iw","ps","pbt","pbu","pst","prp","prd","ug","ur","ydd","yds","yih","ji","yi","hbo","men","xmn","fa","jpr","peo","pes","prs","dv","sam","ckb"].indexOf(t.getLanguagePartFromCode(e))>-1||e.toLowerCase().indexOf("-arab")>1?"rtl":"ltr"}},{key:"cloneInstance",value:function(){var e=this,s=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:bi,o=Ti(Ti(Ti({},this.options),s),{isClone:!0}),i=new t(o);void 0===s.debug&&void 0===s.prefix||(i.logger=i.logger.clone(s));return["store","services","language"].forEach((function(t){i[t]=e[t]})),i.services=Ti({},this.services),i.services.utils={hasLoadedNamespace:i.hasLoadedNamespace.bind(i)},i.translator=new ni(i.services,i.options),i.translator.on("*",(function(e){for(var t=arguments.length,s=new Array(t>1?t-1:0),n=1;n<t;n++)s[n-1]=arguments[n];i.emit.apply(i,[e].concat(s))})),i.init(o,n),i.translator.options=i.options,i.translator.backendConnector.services.utils={hasLoadedNamespace:i.hasLoadedNamespace.bind(i)},i}},{key:"toJSON",value:function(){return{options:this.options,store:this.store,language:this.language,languages:this.languages,resolvedLanguage:this.resolvedLanguage}}}]),t}();bo(Oi,"createInstance",(function(){return new Oi(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},arguments.length>1?arguments[1]:void 0)}));var Li,Ai,Ui,Ri=Oi.createInstance();Ri.createInstance=Oi.createInstance,Ri.createInstance,Ri.dir,Ri.init,Ri.loadResources,Ri.reloadResources,Ri.use,Ri.changeLanguage,Ri.getFixedT,Ri.t,Ri.exists,Ri.setDefaultNamespace,Ri.hasLoadedNamespace,Ri.loadNamespaces,Ri.loadLanguages;class Pi extends no{constructor(){super(),this.languages=null,this.keyMap={}}static getInstance(){return Pi.instance||(Pi.instance=new Pi),Pi.instance}provideLanguages(e){var t;Fn||(this.languages=e,(null===(t=e["zh-CN"])||void 0===t?void 0:t.Chat)&&this.setKeyMap(e["zh-CN"]),console.log("TUITranslateService.provideLanguages ok."))}useI18n(e){var t;if(Fn)return;if(!this.languages)return void console.warn("TUITranslateService.useI18next not have messages.");const s={};for(const[e,t]of Object.entries(this.languages)){s["zh_cn"===e?"zh":e]={translation:t}}Ri.init({compatibilityJSON:"v3",lng:e||"zh",fallbackLng:"zh",detection:{order:["querystring","navigator"],caches:["localStorage","cookie"]},resources:s});let n=this.normalizeLanguageKey(e||"zh");null===(t=this.getEngine().TUIReport)||void 0===t||t.reportFeature(201,n)}changeLanguage(e){let t=this.normalizeLanguageKey(e);return this.getEngine().TUIReport.reportFeature(201,t),Ri.changeLanguage(e)}normalizeLanguageKey(e){return e.includes("en")?"en-us":e.includes("tw")?"zh-tw":e.includes("zh")||e.includes("cn")?"zh-cn":e.includes("ko")||e.includes("kr")?"ko-kr":e.includes("ja")||e.includes("jp")?"ja-jp":"other-"+e}t(e){if(!this.languages){let t=e;return!En(e)&&e.indexOf(".")>-1&&(t=e.split(".").pop()||""),t}const t=this.keyMap[e];return t?Ri.t(t):Ri.t(e)}setKeyMap(e,t){for(const s in e)if(Object.prototype.hasOwnProperty.call(e,s)){const n=t?`${t}.${s}`:s;if(e[s]&&"object"==typeof e[s]&&!Array.isArray(e[s])&&null!==e[s])this.setKeyMap(e[s],n);else{let n=t?`${t}.${e[s]}`:e[s];n=this.replaceKey(n),this.keyMap[n]=`${t}.${s}`}}}replaceKey(e){return e.startsWith("Chat")?e.replace("Chat","TUIChat"):e.startsWith("Conversation")?e.replace("Conversation","TUIConversation"):e.startsWith("Message")?e.replace("Message","message.tip"):e.startsWith("Call")?e.replace("Call","message.custom"):e}}class Gi extends no{constructor(){super(),this.serv="TUIConversationService"}static getInstance(){return Gi.instance||(Gi.instance=new Gi),Gi.instance}init(){const e=this.getEngine();e.eventCenter.addEvent(e.EVENT.CONVERSATION_LIST_UPDATED,this.onConversationListUpdated.bind(this)),e.eventCenter.addEvent(e.EVENT.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED,this.onTotalUnreadCountUpdated.bind(this)),e.eventCenter.addEvent(e.EVENT.MESSAGE_RECEIVED,this.onMessageReceived.bind(this)),this.getConversationInitData()}onConversationListUpdated(e){const t=this.filterSystemConversation(e);this.getEngine().TUIStore.update(on.CONV,"conversationList",t),this.updateCurrentConversation()}onTotalUnreadCountUpdated(e){this.getEngine().TUIStore.update(on.CONV,"totalUnreadCount",e)}onMessageReceived(e){const t=this.getEngine(),s=this.getEngine().TUIStore.getData(on.CONV,"conversationList");let n=!1;for(let o=0;o<e.length;o++){if(e[o].type!==t.TYPES.MSG_GRP_SYS_NOTICE)continue;const{operationType:i}=e[o].payload,r=`GROUP${e[o].to}`,a=4===i||5===i||8===i,c=2===i||6===i||7===i;if(a||c)for(let e=0;e<s.length;e++)if(s[e].type!==t.TYPES.CONV_C2C&&s[e].conversationID===r){if(a){this.getEngine().TUIStore.update(on.CONV,"operationTypeMap",{conversationID:r,operationType:i}),n=!0;break}if(c&&s[e].operationType>0){this.getEngine().TUIStore.update(on.CONV,"operationTypeMap",{conversationID:r,operationType:0}),n=!0;break}}}if(n){this.getEngine().TUIStore.update(on.CONV,"conversationList",s);const e=this.getEngine().TUIStore.getData(on.CONV,"currentConversationID")||"",t=this.findConversation(e);t&&this.getEngine().TUIStore.update(on.CONV,"currentConversation",t)}}getConversationInitData(){const e=this.getEngine();e.chat.isReady()&&e.chat.getConversationList().then((t=>{const{conversationList:s,isSyncCompleted:n}=t.data;if(console.log(`${this.serv}.init, getConversationList count:${s.length} isSyncCompleted:${n}`),s.length>0){this.onConversationListUpdated(s);const t=e.chat.getTotalUnreadMessageCount();this.onTotalUnreadCountUpdated(t)}}))}switchConversation(e){return o(this,void 0,void 0,(function*(){const t=`${this.serv}.switchConversation`,s=this.getEngine();if(!e)return s.TUIStore.reset(on.CHAT,["messageList","isCompleted","nextReqMessageID"]),s.TUIStore.update(on.CONV,"currentConversationID",""),s.TUIStore.update(on.CONV,"currentConversation",null),console.log(`${t} conversationID is empty, conversationID:${e}`),Promise.resolve({});if(!e.startsWith(s.TYPES.CONV_C2C)&&!e.startsWith(s.TYPES.CONV_GROUP))return console.warn(`${t} conversationID is invalid, conversationID:${e}`),Promise.reject({code:ln.INVALID_CONV_ID,message:gn.INVALID_CONV_ID});const n=s.TUIStore.getData(on.CONV,"currentConversationID");if(n&&n===e)return this.setMessageRead(n),console.warn(`${t} please check conversationID, conversationID:${e}`),Promise.resolve({code:ln.CONV_ID_SAME,message:gn.CONV_ID_SAME});const o=yield this.getConversationModel(e);return En(o)?(console.warn(`${t} target conversation is not exist, conversationID:${e}`),Promise.reject({code:ln.CONV_NOT_EXIST,message:gn.CONV_NOT_EXIST})):(n&&this.setMessageRead(n),e&&this.setMessageRead(e),s.TUIStore.reset(on.CHAT,["messageList","isCompleted","nextReqMessageID"]),s.TUIStore.update(on.CONV,"currentConversationID",e),s.TUIStore.update(on.CONV,"currentConversation",o),Promise.resolve(o))}))}getConversationModel(e){return o(this,void 0,void 0,(function*(){let t=this.findConversation(e);if(En(t))try{const s=yield this.getConversationProfile(e);s.data&&s.data.conversation&&(t=new ro(s.data.conversation))}catch(e){t=void 0}return t}))}findConversation(e){let t;const s=this.getEngine().TUIStore.getData(on.CONV,"conversationList");for(let n=0;n<s.length;n++)if(s[n].conversationID===e){t=s[n];break}return t}updateCurrentConversation(){const e=this.getEngine(),t=e.TUIStore.getData(on.CONV,"currentConversationID"),s=this.findConversation(t);s&&e.TUIStore.update(on.CONV,"currentConversation",s)}getConversationList(){return this.getEngine().chat.getConversationList()}getConversationProfile(e){return this.getEngine().chat.getConversationProfile(e)}deleteConversation(e){return this.getEngine().chat.deleteConversation(e).then((t=>{const s=this.getEngine().TUIStore.getData(on.CONV,"currentConversationID");return console.log(`${this.serv}.deleteConversation conversationID:${e} currentConversationID:${s}`),e===s&&(this.getEngine().TUIStore.update(on.CONV,"currentConversationID",""),this.getEngine().TUIStore.update(on.CONV,"currentConversation",null)),t}))}pinConversation(e){return this.getEngine().chat.pinConversation(e)}muteConversation(e){return this.getEngine().chat.setMessageRemindType(e)}clearHistoryMessage(e){return this.getEngine().chat.clearHistoryMessage(e).then((e=>(this.getEngine().TUIStore.update(on.CHAT,"messageList",[]),this.getEngine().TUIStore.update(on.CHAT,"nextReqMessageID",""),this.getEngine().TUIStore.update(on.CHAT,"isCompleted",!0),e)))}setMessageRead(e){return this.getEngine().chat.setMessageRead({conversationID:e})}setConversationDraft(e){const{conversationID:t,draftInfo:s}=e;let n="";return s&&(n=JSON.stringify(s)),this.getEngine().chat.setConversationDraft({conversationID:t,draftText:n}).then((e=>{const{conversation:t}=e.data;this.updateConversation(t)}))}updateConversation(e){let t=!1;const s=this.getEngine().TUIStore.getData(on.CONV,"conversationList");for(let n=0;n<s.length;n++)if(s[n].conversationID===e.conversationID){s[n]=e,t=!0;break}t&&this.getEngine().TUIStore.update(on.CONV,"conversationList",s)}filterSystemConversation(e){return e.filter((e=>e.type!==this.getEngine().TYPES.CONV_SYSTEM))}}class wi{constructor(e){this.TUIUserService=e}getEngine(){return this.TUIUserService.getEngine()}init(){this.getEngine().eventCenter.addEvent(this.getEngine().EVENT.PROFILE_UPDATED,this.onProfileUpdated.bind(this)),this.getEngine().eventCenter.addEvent(this.getEngine().EVENT.BLACKLIST_UPDATED,this.onBlacklistUpdated.bind(this)),this.getUserProfileInitData()}onProfileUpdated(e){const t=this.getEngine(),s=t.TUIStore.getData(on.USER,"userProfile");e.forEach((e=>{e.userID===s.userID&&t.TUIStore.update(on.USER,"userProfile",e)}))}onBlacklistUpdated(e){const t=this.getEngine();this.getBlacklistProfile(e).then((e=>{t.TUIStore.update(on.USER,"userBlacklist",e)}))}getUserProfileInitData(){const e=this.getEngine();e.chat.isReady()&&e.chat.getBlacklist().then((e=>{const t=e.data||[];console.log(`TUIUserProfileHandler.init, getBlacklist count:${t.length}`),t.length>0&&this.onBlacklistUpdated(t)}))}getBlacklistProfile(e){const t=[];let s=0;for(;s<e.length;)t.push(e.slice(s,s+=100));const n=[];t.forEach((e=>{n.push(this.TUIUserService.getUserProfile({userIDList:e}))}));const o=[];return Promise.all(n).then((e=>(e.forEach((e=>{const t=e.data.map((e=>{const{userID:t,nick:s,avatar:n}=e;return{userID:t,nick:s,avatar:n}}));o.push(...t)})),o)))}getUserProfile(e){const t=this.getEngine();return En(e)?t.chat.getMyProfile().then((e=>(t.TUIStore.update(on.USER,"userProfile",e.data),e))).catch((e=>Promise.reject(e))):t.chat.getUserProfile(e)}updateMyProfile(e){return this.getEngine().chat.updateMyProfile(e)}addToBlacklist(e){return this.getEngine().chat.addToBlacklist(e)}removeFromBlacklist(e){return this.getEngine().chat.removeFromBlacklist(e)}}function Ni(e,t,s=!0){!function(e,t){xn?qn.setStorageSync(e,t):$i()&&localStorage.setItem(e,JSON.stringify(t))}(s?Fi(e):e,t)}function ki(e,t=!0){try{return function(e){if(xn)return qn.getStorageSync(e);if($i()){const t=localStorage.getItem(e);if("undefined"!==t)return JSON.parse(t)}return}(t?Fi(e):e)}catch(e){return void console.warn("Storage.getStorageItem error:",e)}}function Fi(e){return`chat_engine_${e}`}function $i(){return navigator&&navigator.cookieEnabled&&localStorage}class xi{constructor(e){this.TUIUserService=e}getEngine(){return this.TUIUserService.getEngine()}init(){const e=this.getEngine(),t=ki("displayOnlineStatus")||!1;e.TUIStore.update(on.USER,"displayOnlineStatus",t),e.eventCenter.addEvent(e.EVENT.USER_STATUS_UPDATED,this.onUserStatusUpdated.bind(this)),this.onConversationListUpdated()}onConversationListUpdated(){const e=this.getEngine();e.TUIStore.watch(on.CONV,{conversationList:()=>{const t=e.TUIStore.getData(on.APP,"enabledOnlineStatus"),s=e.TUIStore.getData(on.USER,"displayOnlineStatus");t&&s&&this.startToSubscribe()}})}onUserStatusUpdated(e){this.getEngine().TUIStore.update(on.USER,"userStatusList",e)}switchUserStatus(e){const t=this.getEngine(),{displayOnlineStatus:s=!1}=e;t.TUIStore.update(on.USER,"displayOnlineStatus",s),Ni("displayOnlineStatus",s);const n=t.TUIStore.getData(on.APP,"enabledOnlineStatus");n?!0===s?this.startToSubscribe():this.unsubscribeUserStatus():console.warn(`UserStatusHandler.switchUserStatus enabledOnlineStatus:${n} displayOnlineStatus:${s}`)}getUserStatus(e){const t=this.getEngine();return t.chat.getUserStatus(e).then((e=>{const{successUserList:s}=e.data;return s.length>0&&t.TUIStore.update(on.USER,"userStatusList",s),e})).catch((e=>Promise.reject(e)))}subscribeUserStatus(e){var t;const s=(null===(t=null==e?void 0:e.userIDList)||void 0===t?void 0:t.length)||0;return 0===s?(console.warn(`UserStatusHandler.subscribeUserStatus userID count:${s}`),Promise.resolve()):this.getEngine().chat.subscribeUserStatus(e)}unsubscribeUserStatus(e){const t=this.getEngine(),{userIDList:s=[]}=e||{};return t.chat.unsubscribeUserStatus({userIDList:s}).then((e=>{const{failureUserList:n}=e.data,o=[];return s.forEach((e=>{n.includes(e)||o.push({userID:e,statusType:rn.UNSUB_USER})})),t.TUIStore.update(on.USER,"userStatusList",o),e})).catch((e=>Promise.reject(e)))}startToSubscribe(){const e=this.getEngine(),t=e.TUIStore.getData(on.CONV,"conversationList"),s=e.TUIStore.getData(on.USER,"userStatusList"),n=[];t.forEach((t=>{if(t.type===e.TYPES.CONV_C2C){const o=t.conversationID.replace(e.TYPES.CONV_C2C,"");s.has(o)||n.push(o)}})),0!==n.length&&e.chat.isReady()&&(this.subscribeUserStatus({userIDList:n}),this.getUserStatus({userIDList:n}))}}class ji extends no{constructor(){super(),this.userProfileHandler=new wi(this),this.userStatusHandler=new xi(this)}static getInstance(){return ji.instance||(ji.instance=new ji),ji.instance}init(){const e=this.getEngine();e.eventCenter.addEvent(e.EVENT.KICKED_OUT,this.onKickedOut.bind(this)),e.eventCenter.addEvent(e.EVENT.NET_STATE_CHANGE,this.onNetStateChange.bind(this)),this.userProfileHandler.init(),this.userStatusHandler.init(),this.initMessageReadReceipt()}onKickedOut(e){this.getEngine().TUIStore.update(on.USER,"kickedOut",e.type)}onNetStateChange(e){this.getEngine().TUIStore.update(on.USER,"netStateChange",e.state)}initMessageReadReceipt(){const e=ki("displayMessageReadReceipt")||!0;this.getEngine().TUIStore.update(on.USER,"displayMessageReadReceipt",e)}switchUserStatus(e){return this.userStatusHandler.switchUserStatus(e)}switchMessageReadStatus(e){this.getEngine().TUIStore.update(on.USER,"displayMessageReadReceipt",e),Ni("displayMessageReadReceipt",e)}getUserProfile(e){return this.userProfileHandler.getUserProfile(e)}updateMyProfile(e){return this.userProfileHandler.updateMyProfile(e)}addToBlacklist(e){return this.userProfileHandler.addToBlacklist(e)}removeFromBlacklist(e){return this.userProfileHandler.removeFromBlacklist(e)}getUserStatus(e){return this.userStatusHandler.getUserStatus(e)}subscribeUserStatus(e){return this.userStatusHandler.subscribeUserStatus(e)}unsubscribeUserStatus(e){return this.userStatusHandler.unsubscribeUserStatus(e)}}class Vi{constructor(e){this.TUIChatService=e,this.userShowNameMap=new Map,this.requestedUserMap=new Map}getEngine(){return this.TUIChatService.getEngine()}t(e){return this.getEngine().TUITranslate.t(e)}handleTextMessage(e){return{text:this.decodeText(e.payload)}}handleFaceMessage(e){const t={name:"",url:"",type:""};return e.payload.data.indexOf("@custom")>-1?(t.name=e.payload.data,t.type="custom",t):(t.name=e.payload.data.indexOf("@2x")<0?`${e.payload.data}@2x`:e.payload.data,t.url=`${An}${t.name}.png`,t)}handleLocationMessage(e){const t={lon:"",lat:"",href:"",url:"",description:""};return t.lon=e.payload.longitude.toFixed(6),t.lat=e.payload.latitude.toFixed(6),t.href=`${Un}pointx=${t.lon}&pointy=${t.lat}&name=${e.payload.description}`,t.url=`${Rn}center=${t.lat},${t.lon}&zoom=10&size=300*150&maptype=roadmap&markers=size:large|color:0xFFCCFF|label:k|${t.lat},${t.lon}&key=UBNBZ-PTP3P-TE7DB-LHRTI-Y4YLE-VWBBD`,t.description=e.payload.description,t}handleImageMessage(e){return{url:e.payload.imageInfoArray[0].url,width:e.payload.imageInfoArray[0].width,height:e.payload.imageInfoArray[0].height}}handleAudioMessage(e){return{url:e.payload.url,second:e.payload.second}}handleVideoMessage(e){return{url:e.payload.videoUrl,snapshotUrl:e.payload.snapshotUrl,snapshotWidth:e.payload.snapshotWidth,snapshotHeight:e.payload.snapshotHeight}}handleFileMessage(e){return{url:e.payload.fileUrl,name:e.payload.fileName,size:Tn(e.payload.fileSize)}}handleCustomMessage(e){var t;const s=this.handleCreateGroupCustomMessage(e);return{custom:this.handleCallKitSignaling(e)||s||(null===(t=null==e?void 0:e.payload)||void 0===t?void 0:t.extension)||`${this.t("TUIChat.[自定义消息]")}`,businessID:s?"group_create":""}}handleMergeMessage(e){return Object.assign({},e.payload)}handleGroupTipsMessage(e){var t,s,n,o,i,r;const a=this.getEngine(),c={text:""};let u=(null==e?void 0:e.nick)||(null===(s=null===(t=null==e?void 0:e.payload)||void 0===t?void 0:t.userIDList)||void 0===s?void 0:s.join(","));switch((null===(o=null===(n=null==e?void 0:e.payload)||void 0===n?void 0:n.memberList)||void 0===o?void 0:o.length)>0&&(u="",null===(r=null===(i=null==e?void 0:e.payload)||void 0===i?void 0:i.memberList)||void 0===r||r.map((e=>{const t=(null==e?void 0:e.nick)||(null==e?void 0:e.userID);return u+=`${this.substringByLength(t)},`,e})),u=null==u?void 0:u.slice(0,-1)),e.payload.operationType){case a.TYPES.GRP_TIP_MBR_JOIN:c.text=`${u} ${this.t("message.tip.加入群组")}`;break;case a.TYPES.GRP_TIP_MBR_QUIT:c.text=`${this.t("message.tip.群成员")}:${u} ${this.t("message.tip.退出群组")}`;break;case a.TYPES.GRP_TIP_MBR_KICKED_OUT:c.text=`${this.t("message.tip.群成员")}:${u} ${this.t("message.tip.被")}${this.t("message.tip.踢出群组")}`;break;case a.TYPES.GRP_TIP_MBR_SET_ADMIN:c.text=`${this.t("message.tip.群成员")}:${u} ${this.t("message.tip.成为管理员")}`;break;case a.TYPES.GRP_TIP_MBR_CANCELED_ADMIN:c.text=`${this.t("message.tip.群成员")}:${u} ${this.t("message.tip.被撤销管理员")}`;break;case a.TYPES.GRP_TIP_GRP_PROFILE_UPDATED:c.text=this.handleGroupProfileUpdated(e);break;case a.TYPES.GRP_TIP_MBR_PROFILE_UPDATED:for(const t of e.payload.memberList)t.muteTime>0?c.text=`${this.t("message.tip.群成员")}:${u} ${this.t("message.tip.被禁言")}`:c.text=`${this.t("message.tip.群成员")}:${u} ${this.t("message.tip.被取消禁言")}`;break;default:c.text=`[${this.t("message.tip.群提示消息")}]`}return c}handleGroupSystemMessage(e){const t=e.payload.groupProfile.name||e.payload.groupProfile.groupID,s={text:""};switch(e.payload.operationType){case 1:s.text=`${e.payload.operatorID} ${this.t("message.tip.申请加入群组")}:${t}`;break;case 2:s.text=`${this.t("message.tip.成功加入群组")}:${t}`;break;case 3:s.text=`${this.t("message.tip.申请加入群组")}:${t} ${this.t("message.tip.被拒绝")}`;break;case 4:s.text=`${this.t("message.tip.你被管理员")}${e.payload.operatorID} ${this.t("message.tip.踢出群组")}:${t}`;break;case 5:s.text=`${this.t("message.tip.群")}:${t} ${this.t("message.tip.被")} ${e.payload.operatorID} ${this.t("message.tip.解散")}`;break;case 6:s.text=`${e.payload.operatorID} ${this.t("message.tip.创建群")}:${t}`;break;case 7:case 12:s.text=`${e.payload.operatorID} ${this.t("message.tip.邀请你加群")}:${t}`;break;case 8:s.text=`${this.t("message.tip.你退出群组")}:${t}`;break;case 9:s.text=`${this.t("message.tip.你被")}${e.payload.operatorID} ${this.t("message.tip.设置为群")}:${t} ${this.t("message.tip.的管理员")}`;break;case 10:s.text=`${this.t("message.tip.你被")}${e.payload.operatorID} ${this.t("message.tip.撤销群")}:${t} ${this.t("message.tip.的管理员身份")}`;break;case 13:s.text=`${e.payload.operatorID} ${this.t("message.tip.同意加群")}:${t}`;break;case 14:s.text=`${e.payload.operatorID} ${this.t("message.tip.拒接加群")}:${t}`;break;case 255:s.text=`${this.t("message.tip.自定义群系统通知")}: ${e.payload.userDefinedField}`;break;default:s.text="未解析的群系统通知"}return s}handleCallKitSignaling(e){var t,s,n,o,i,r,a,c,u,l;const d=Mn(e.payload.data);if(1!==(null==d?void 0:d.businessID))return"";const g=Mn(null==d?void 0:d.data),h=e.fromAccount||e.from,p=this.getEngine().TUIFriend.getFriendRemark([h]),m=this.getEngine().getMyUserID();let f=p[h]||e.nameCard||e.nick||h;switch(f=this.substringByLength(f),null==d?void 0:d.actionType){case 1:return"audioCall"!==(null===(t=null==g?void 0:g.data)||void 0===t?void 0:t.cmd)&&"videoCall"!==(null===(s=null==g?void 0:g.data)||void 0===s?void 0:s.cmd)||!(null==d?void 0:d.groupID)?"hangup"===(null===(n=null==g?void 0:g.data)||void 0===n?void 0:n.cmd)?(null==d?void 0:d.groupID)?`${this.t("message.custom.通话结束")}`:`${this.t("message.custom.通话时长")}:${function(e){const t=e;let s,n,o,i="";return t>=3600?(s=parseInt(""+t/3600,10)<10?`0${parseInt(""+t/3600,10)}`:parseInt(""+t/3600,10),n=parseInt(""+t%60/60,10)<10?`0${parseInt(""+t%60/60,10)}`:parseInt(""+t%60/60,10),o=t%3600<10?"0"+t%3600:t%3600,o>60&&(n=parseInt(""+o/60,10)<10?`0${parseInt(""+o/60,10)}`:parseInt(""+o/60,10),o=o%60<10?"0"+o%60:o%60),i=`${s}:${n}:${o}`):t>=60&&t<3600?(n=parseInt(""+t/60,10)<10?`0${parseInt(""+t/60,10)}`:parseInt(""+t/60,10),o=t%60<10?"0"+t%60:t%60,i=`00:${n}:${o}`):t<60&&(o=t<10?`0${t}`:t,i=`00:00:${o}`),i}(null==g?void 0:g.call_end)}`:"switchToAudio"===(null===(o=null==g?void 0:g.data)||void 0===o?void 0:o.cmd)?`${this.t("message.custom.切换语音通话")}`:"switchToVideo"===(null===(i=null==g?void 0:g.data)||void 0===i?void 0:i.cmd)?`${this.t("message.custom.切换视频通话")}`:`${this.t("message.custom.发起通话")}`:`${f} ${this.t("message.custom.发起通话")}`;case 2:return(null==d?void 0:d.groupID)?`${f} ${this.t("message.custom.取消通话")}`:this.isOldUIKit("message.custom.已取消")?this.t("message.custom.取消通话"):(null==d?void 0:d.inviter)===m?this.t("message.custom.已取消"):this.t("message.custom.对方已取消");case 3:return"switchToAudio"===(null===(r=null==g?void 0:g.data)||void 0===r?void 0:r.cmd)?`${this.t("message.custom.切换语音通话")}`:"switchToVideo"===(null===(a=null==g?void 0:g.data)||void 0===a?void 0:a.cmd)?`${this.t("message.custom.切换视频通话")}`:(null==d?void 0:d.groupID)?`${f} ${this.t("message.custom.已接听")}`:this.t("message.custom.已接听");case 4:return(null==d?void 0:d.groupID)?`${f} ${this.t("message.custom.拒绝通话")}`:this.isOldUIKit("message.custom.已拒绝")?this.t("message.custom.拒绝通话"):"line_busy"===(null==g?void 0:g.line_busy)||"lineBusy"===(null==g?void 0:g.data.message)?(null==d?void 0:d.inviter)===m?this.t("message.custom.对方忙线中"):this.t("message.custom.忙线未接听"):(null==d?void 0:d.inviter)===m?this.t("message.custom.对方已拒绝"):this.t("message.custom.已拒绝");case 5:if("switchToAudio"===(null===(c=null==g?void 0:g.data)||void 0===c?void 0:c.cmd))return`${this.t("message.custom.切换语音通话")}`;if("switchToVideo"===(null===(u=null==g?void 0:g.data)||void 0===u?void 0:u.cmd))return`${this.t("message.custom.切换视频通话")}`;if(null==d?void 0:d.groupID){if(h===(null==d?void 0:d.inviter)){this.handleCallkitTimeoutSignaling(d.inviteeList);let e="";return null===(l=d.inviteeList)||void 0===l||l.forEach((t=>{const s=this.userShowNameMap.get(t)||t;e+=`${this.substringByLength(s)}、`})),e=e.substring(0,e.lastIndexOf("、")),`${e} ${this.t("message.custom.无应答")}`}return`${f} ${this.t("message.custom.无应答")}`}return this.isOldUIKit("message.custom.对方无应答")?this.t("message.custom.无应答"):(null==d?void 0:d.inviter)===m?this.t("message.custom.对方无应答"):this.t("message.custom.超时无应答");default:return""}}handleCreateGroupCustomMessage(e){let t;const s=Mn(e.payload.data);return"group_create"===(null==s?void 0:s.businessID)&&(t=`${s.opUser} ${s.content}`),t}decodeText(e){const t=[];let s=e.text,n=-1,o=-1;for(;""!==s;)switch(n=s.indexOf("["),o=s.indexOf("]"),n){case 0:if(-1===o)t.push({name:"text",text:s}),s="";else{const e=s.slice(0,o+1);e.indexOf("@custom")>-1?(t.push({name:"img",src:"",type:"custom",emojiKey:e}),s=s.substring(o+1)):Pn[e]?(t.push({name:"img",src:Ln+Pn[e],emojiKey:e}),s=s.substring(o+1)):(t.push({name:"text",text:"["}),s=s.slice(1))}break;case-1:t.push({name:"text",text:s}),s="";break;default:t.push({name:"text",text:s.slice(0,n)}),s=s.substring(n)}return t}handleGroupProfileUpdated(e){const{nick:t,payload:s}=e,{newGroupProfile:n,memberList:o,operatorID:i}=s;let r="";const a=t||i,c=Object.keys(n)[0];switch(c){case"muteAllMembers":r=n[c]?`${this.t("message.tip.管理员")} ${a} ${this.t("message.tip.开启全员禁言")}`:`${this.t("message.tip.管理员")} ${a} ${this.t("message.tip.取消全员禁言")}`;break;case"ownerID":r=`${o[0].nick||o[0].userID} ${this.t("message.tip.成为新的群主")}`;break;case"groupName":r=`${a} ${this.t("message.tip.修改群名为")} ${n[c]}`;break;case"notification":r=this.isOldUIKit("message.tip.把群公告修改为")?`${a} ${this.t("message.tip.发布新公告")}`:`${a} ${this.t("message.tip.把群公告修改为")} "${n[c]}"`}return r}handleCallkitTimeoutSignaling(e=[]){if(0===e.length)return;const t=this.getEngine().TUIFriend.getFriendRemark(e),s=[];e.forEach((e=>{const n=t[e];n?this.userShowNameMap.set(e,n):this.requestedUserMap.has(e)||(s.push(e),this.requestedUserMap.set(e,1))})),s.length>0&&this.getEngine().TUIUser.getUserProfile({userIDList:s}).then((e=>{(e.data||[]).forEach((e=>{const{userID:t,nick:s}=e,n=s||t;this.userShowNameMap.set(t,n)}))})).catch((()=>{}))}substringByLength(e,t=12){return e.length>t?`${e.slice(0,t)}...`:e}isOldUIKit(e){var t;const s=e.lastIndexOf("."),n=e.slice(0,s+1);return null===(t=this.t(e))||void 0===t?void 0:t.startsWith(n)}}class qi{constructor(e){this.TUIChatService=e,this.typingTo="",this.timer=null}getEngine(){return this.TUIChatService.getEngine()}clearTypingStatus(){this.getEngine().TUIStore.getData(on.CHAT,"typingStatus")&&this.getEngine().TUIStore.update(on.CHAT,"typingStatus",!1),this.timer&&clearTimeout(this.timer),this.timer=null}handleLastMessage(e){const t=this.getEngine(),s=t.TUIStore.getData(on.CHAT,"typingStatus");if(e.type===this.getEngine().TYPES.MSG_CUSTOM&&"in"===e.flow){const n=Mn(e.payload.data);if(n.businessID===an.BUSINESS_ID){const{typingStatus:e,userAction:o}=n;if(e===an.STATUS_START||o===an.ACTION_START_ID)return s?(this.timer&&clearTimeout(this.timer),this.timer=null):t.TUIStore.update(on.CHAT,"typingStatus",!0),this.timer=setTimeout((()=>{this.clearTypingStatus()}),3e4),t.TUIStore.getData(on.CHAT,"typingStatus");e!==an.STATUS_END&&o!==an.ACTION_END_ID||this.clearTypingStatus()}}}filterTypingMessage(e=[]){if(0===e.length)return[];return this.getEngine().TUIStore.getData(on.APP,"enableTyping")&&this.handleLastMessage(e[e.length-1]),e.filter((e=>{if(e.type===this.getEngine().TYPES.MSG_CUSTOM){return Mn(e.payload.data).businessID!==an.BUSINESS_ID}return!0}))}createTypingMessage(e=an.STATUS_END,t=""){const{BUSINESS_ID:s,STATUS_START:n,VERSION:o,ACTION_START_ID:i,ACTION_END_ID:r,ACTION_START:a,ACTION_END:c,NEED_TYPING:u}=an;return{to:t,conversationType:this.getEngine().TYPES.CONV_C2C,payload:{data:JSON.stringify({businessID:s,typingStatus:e,version:o,userAction:e===n?i:r,actionParam:e===n?a:c}),description:"",extension:""},cloudCustomData:JSON.stringify({messageFeature:{needTyping:u,version:o}})}}sendTyping(e=!1,t=""){if(e){this.typingTo=t;const e=this.createTypingMessage(an.STATUS_START,t);this.getEngine().TUIChat.sendCustomMessage(e,{onlineUserOnly:!0})}else this.sendTypingEnd()}sendTypingEnd(){if(this.typingTo){const e=this.createTypingMessage(an.STATUS_END,this.typingTo);this.getEngine().TUIChat.sendCustomMessage(e,{onlineUserOnly:!0})}this.typingTo=""}}class Hi{constructor(e){this.TUIChatService=e}getEngine(){return this.TUIChatService.getEngine()}init(){const e=this.getEngine();e.eventCenter.addEvent(e.EVENT.MESSAGE_READ_RECEIPT_RECEIVED,this.onMessageReadReceiptReceived.bind(this))}onMessageReadReceiptReceived(e){const t=this.getEngine(),s=t.TUIStore.getData(on.CONV,"currentConversationID"),n=[];e.forEach((e=>{const{messageID:o}=e,i=t.chat.findMessage(o);i&&s===i.conversationID&&n.push(i)})),n.length>0&&t.TUIChat.updateMessageList(n,"edit")}sendMessageReadReceipt(e){const t=[];return e.forEach((e=>{const s=e.getMessage();t.push(s)})),this.getEngine().chat.sendMessageReadReceipt(t)}getGroupMessageReadMemberList(e){const t=e.message.getMessage(),s=Object.assign(Object.assign({},e),{message:t});return this.getEngine().chat.getGroupMessageReadMemberList(s)}getMessageReadReceiptList(e){const t=this.getEngine(),s=t.TUIStore.getData(on.APP,"enabledMessageReadReceipt"),n=t.TUIStore.getData(on.USER,"displayMessageReadReceipt");!s||!n||0===e.length||e[0].conversationType!==t.TYPES.CONV_GROUP||t.chat.getMessageReadReceiptList(e).then((e=>{const{messageList:t}=e.data;this.TUIChatService.updateMessageList(t,"edit")})).catch((e=>{console.warn(`ReadReceiptHandler.getMessageReadReceiptList error:${e.message}`)}))}}class Bi extends no{constructor(){super(),this.serv="TUIChatService",this.messageHandler=new Vi(this),this.typingHandler=new qi(this),this.readReceiptHandler=new Hi(this),this.isSwitching=!0,this.delayGetHoppingFunction=void 0,this.hoppingConfigMap=new Map}static getInstance(){return Bi.instance||(Bi.instance=new Bi),Bi.instance}init(){const e=this.getEngine();e.eventCenter.addEvent(e.EVENT.MESSAGE_RECEIVED,this.onMessageReceived.bind(this)),e.eventCenter.addEvent(e.EVENT.MESSAGE_MODIFIED,this.onMessageModified.bind(this)),e.eventCenter.addEvent(e.EVENT.MESSAGE_REVOKED,this.onMessageRevoked.bind(this)),e.eventCenter.addEvent(e.EVENT.MESSAGE_READ_BY_PEER,this.onMessageReadByPeer.bind(this)),e.eventCenter.addEvent(e.EVENT.MESSAGE_REACTIONS_UPDATED,this.onMessageReactionsUpdated.bind(this)),this.onCurrentConversationIDUpdated(),this.onMessageSource(),this.readReceiptHandler.init()}onMessageReceived(e){this.updateMessageList(e,"received"),this.getEngine().TUIStore.update(on.CHAT,"newMessageList",e)}onMessageModified(e){this.updateMessageList(e,"edit")}onMessageRevoked(e){this.updateMessageList(e,"edit")}onMessageReadByPeer(e){this.updateMessageList(e,"edit")}onMessageReactionsUpdated(e){this.updateMessageReactionList([e])}onCurrentConversationIDUpdated(){const e=this.getEngine();e.TUIStore.watch(on.CONV,{currentConversationID:t=>{this.isSwitching=!0,this.delayGetHoppingFunction=void 0,this.hoppingConfigMap.clear(),e.TUIStore.reset(on.CHAT),this.typingHandler.clearTypingStatus(),this.typingHandler.sendTypingEnd(),oo(t)||this.getMessageList().finally((()=>{this.isSwitching=!1,this.delayGetHoppingFunction&&this.delayGetHoppingFunction()}))}})}onMessageSource(){const e=this.getEngine();e.TUIStore.watch(on.CHAT,{messageSource:t=>{const s=this.getStoreData(on.CONV,"currentConversationID");if(!s||t&&t.conversationID!==s)return;if(En(t))return this.hoppingConfigMap.clear(),e.TUIStore.update(on.CHAT,"messageList",[]),e.TUIStore.update(on.CHAT,"nextReqMessageID",""),e.TUIStore.update(on.CHAT,"isCompleted",!1),void this.getMessageList();const n=this.getStoreData(on.CHAT,"messageList");n&&n.find((e=>t&&e.ID===t.ID))||(this.isSwitching?this.delayGetHoppingFunction=this.getMessageListHoppingForDown:this.getMessageListHoppingForDown())}})}getMessageListHoppingForDown(){const e=this.getStoreData(on.CHAT,"messageList"),{conversationID:t,sequence:s,time:n,ID:o}=this.getStoreData(on.CHAT,"messageSource");if(e&&e.find((e=>o&&e.ID===o)))return;const i=this.getEngine();i.TUIStore.update(on.CHAT,"messageList",[]),i.TUIStore.update(on.CHAT,"nextReqMessageID",""),i.TUIStore.update(on.CHAT,"isCompleted",!1),this.getMessageListHopping({conversationID:t,sequence:s,time:n,direction:1})}getStoreData(e,t){return this.getEngine().TUIStore.getData(e,t)}sendMessage(e,t){this.updateMessageList([e],"send");const s=this.getEngine().chat.sendMessage(e,t);return this.getResponse(s)}getResponse(e,t=!0,s=!0){return e.then((e=>{const s=e.data.messageList?e.data.messageList:[e.data.message];return t&&this.updateMessageList(s,"edit"),e})).catch((e=>{var t;return s&&(null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.message)&&this.updateMessageList([e.data.message],"edit"),Promise.reject(e)}))}updateMessageList(e,t=""){if(this.getStoreData(on.CHAT,"messageSource")&&"unshift"!==t&&"edit"!==t)return;const s=this.getStoreData(on.CHAT,"messageList"),n=this.updateTargetMessageList(e,s,t);this.getEngine().TUIStore.update(on.CHAT,"messageList",n)}updateTargetMessageList(e,t,s=""){const n=this.getStoreData(on.CONV,"currentConversationID");let o=e.filter((e=>e.conversationID===n));if(o=this.handleC2CCallSignaling(o),!s||0===o.length)return t;const i=t||[];let r=[];if("send"===s||"push"===s){const e=this.getStoreData(on.CHAT,"userInfo");Object.keys(e).length>0&&this.updateLocalMessage(o,e)}switch(s){case"edit":for(const e of t){const t=o.find((t=>t.ID===e.ID));r.push(t||e)}break;case"resend":r=i.filter((e=>e.ID!==o[0].ID)).concat(o);break;case"send":r=i.concat(this.typingHandler.filterTypingMessage(o));break;case"push":r=i.concat(this.typingHandler.filterTypingMessage(o)),this.getEngine().chat.setMessageRead({conversationID:n});break;case"received":r=i.concat(this.typingHandler.filterTypingMessage(o)),r=this.sortMessageList(r),this.getEngine().chat.setMessageRead({conversationID:n});break;case"unshift":r=o.filter((e=>0===i.length||!i.find((t=>t.ID===e.ID)))),r.push(...i),r=this.sortMessageList(r)}return r}enterTypingState(){this.getStoreData(on.APP,"enableTyping")&&this.sendTyping(!0)}leaveTypingState(){this.getStoreData(on.APP,"enableTyping")&&this.sendTyping(!1)}sendTyping(e){const t=this.getEngine(),s=this.getStoreData(on.CONV,"currentConversationID");if(!s.startsWith(t.TYPES.CONV_C2C))return;const n=s.replace(t.TYPES.CONV_C2C,"");if(e){const e=this.getStoreData(on.CHAT,"messageList").filter((e=>"in"===e.flow));if(0===e.length)return;const t=1e3*e[e.length-1].time;if((new Date).getTime()-t>3e4)return}this.typingHandler.sendTyping(e,n)}quoteMessage(e){var t;return this.getEngine().TUIStore.update(on.CHAT,"quoteMessage",{message:e,type:"quote"}),null===(t=this.getEngine().TUIReport)||void 0===t||t.reportFeature(205),e}replyMessage(e){return this.getEngine().TUIStore.update(on.CHAT,"quoteMessage",{message:e,type:"reply"}),e}getCurrentConvInfo(){const{conversationID:e="",type:t}=this.getStoreData(on.CONV,"currentConversation")||{};return{to:e.replace(t,""),conversationType:t}}t(e){return this.getEngine().TUITranslate.t(e)||e}getMessageAbstractAndType(e){var t,s;const n=this.getEngine(),o={abstract:"",type:0};switch(e.type){case n.TYPES.MSG_TEXT:o.abstract=null===(t=null==e?void 0:e.payload)||void 0===t?void 0:t.text,o.type=1;break;case n.TYPES.MSG_CUSTOM:o.abstract="[自定义消息]",o.type=2;break;case n.TYPES.MSG_IMAGE:o.abstract="[图片]",o.type=3;break;case n.TYPES.MSG_AUDIO:o.abstract="[语音]",o.type=4;break;case n.TYPES.MSG_VIDEO:o.abstract="[视频]",o.type=5;break;case n.TYPES.MSG_FILE:o.abstract="[文件]",o.type=6;break;case n.TYPES.MSG_LOCATION:o.type=7;break;case n.TYPES.MSG_FACE:o.abstract="[表情]",o.type=8;break;case n.TYPES.MSG_GRP_TIP:o.type=9;break;case n.TYPES.MSG_MERGER:o.abstract=null===(s=null==e?void 0:e.payload)||void 0===s?void 0:s.title,o.type=10}return o}genMessageReply(e,t){if("reply"!==t&&"quote"!==t)return{};const{abstract:s,type:n}=this.getMessageAbstractAndType(e),o={messageAbstract:s,messageSender:e.nick||e.from,messageID:e.ID},i=Object.assign(Object.assign({},o),{messageType:n,messageTime:null==e?void 0:e.time,messageSequence:null==e?void 0:e.sequence,version:1});if("reply"===t&&(i.messageRootID=e.ID,e.cloudCustomData)){const t=Mn(e.cloudCustomData);t.messageReply&&t.messageReply.messageRootID&&(i.messageRootID=t.messageReply.messageRootID)}return{messageReply:i,messageReplyRoot:o}}getMessageInfo(e,t,s){const{messageReply:n,messageReplyRoot:o}=this.genMessageReply(t,s),i=e.cloudCustomData?Mn(e.cloudCustomData):{};let r;if(i.messageReply?i.messageReply=Object.assign(Object.assign({},n),i.messageReply):i.messageReply=n,"reply"===s){const{messageRootID:e}=n;r=this.getEngine().chat.findMessage(e);const t=(null==r?void 0:r.cloudCustomData)?Mn(r.cloudCustomData):{};t.messageReplies||(t.messageReplies={}),a=t.messageReplies.replies,("function"==typeof Array.isArray?Array.isArray(a):"array"===Object.prototype.toString.call(a).match(/^\[object (.*)\]$/)[1].toLowerCase())||(t.messageReplies.replies=[]),t.messageReplies.replies.push(o),r.cloudCustomData=JSON.stringify(t)}var a;return{cloudCustomData:JSON.stringify(i),rootMessage:r}}sendTextMessage(e,t){const s=this.getEngine(),{message:n,type:o}=this.getStoreData(on.CHAT,"quoteMessage");let i={cloudCustomData:e.cloudCustomData||"",rootMessage:void 0};n&&(i=this.getMessageInfo(e,n,o));const r=s.chat.createTextMessage(Object.assign(Object.assign(Object.assign({},this.getCurrentConvInfo()),e),{cloudCustomData:i.cloudCustomData}));return this.sendMessage(r,t).then((e=>(i.rootMessage&&this.modifyMessage(i.rootMessage),s.TUIStore.reset(on.CHAT,["quoteMessage"],!0),e)))}sendTextAtMessage(e,t){const s=this.getEngine(),{message:n,type:o}=this.getStoreData(on.CHAT,"quoteMessage");let i={cloudCustomData:e.cloudCustomData||"",rootMessage:void 0};n&&(i=this.getMessageInfo(e,n,o));const r=s.chat.createTextAtMessage(Object.assign(Object.assign(Object.assign({},this.getCurrentConvInfo()),e),{cloudCustomData:i.cloudCustomData}));return this.sendMessage(r,t).then((e=>(i.rootMessage&&this.modifyMessage(i.rootMessage),s.TUIStore.reset(on.CHAT,["quoteMessage"],!0),e)))}sendImageMessage(e,t){const s=this.getEngine().chat.createImageMessage(Object.assign(Object.assign(Object.assign({},this.getCurrentConvInfo()),e),{onProgress:e=>{this.onProgress(s.ID,e)}}));return this.sendMessage(s,t)}sendAudioMessage(e,t){const s=this.getEngine().chat.createAudioMessage(Object.assign(Object.assign(Object.assign({},this.getCurrentConvInfo()),e),{onProgress:e=>{this.onProgress(s.ID,e)}}));return this.sendMessage(s,t)}sendVideoMessage(e,t){const s=this.getEngine().chat.createVideoMessage(Object.assign(Object.assign(Object.assign({},this.getCurrentConvInfo()),e),{onProgress:e=>{this.onProgress(s.ID,e)}}));return this.sendMessage(s,t)}sendCustomMessage(e,t){const s=this.getEngine().chat.createCustomMessage(Object.assign(Object.assign({},this.getCurrentConvInfo()),e));return this.sendMessage(s,t)}sendFaceMessage(e,t){const s=this.getEngine().chat.createFaceMessage(Object.assign(Object.assign({},this.getCurrentConvInfo()),e));return this.sendMessage(s,t)}sendFileMessage(e,t){const s=this.getEngine().chat.createFileMessage(Object.assign(Object.assign(Object.assign({},this.getCurrentConvInfo()),e),{onProgress:e=>{this.onProgress(s.ID,e)}}));return this.sendMessage(s,t)}sendLocationMessage(e,t){const s=this.getEngine().chat.createLocationMessage(Object.assign(Object.assign({},this.getCurrentConvInfo()),e));return this.sendMessage(s,t)}onProgress(e,t){const s=this.getEngine().TUIStore.getMessageModel(e);if(s){(t-s.progress>=.1||1===t)&&(s.progress=t,this.updateMessageList([s],"edit"))}}setAbstractList(e){const t=this.getEngine(),s=e.nick||e.from;let n="";switch(e.type){case t.TYPES.MSG_TEXT:n=e.payload.text||"",n.length>20&&(n=n.slice(0,20));break;case t.TYPES.MSG_MERGER:n=`${this.t("TUIChat.[聊天记录]")}`;break;case t.TYPES.MSG_IMAGE:n=`${this.t("TUIChat.[图片]")}`;break;case t.TYPES.MSG_AUDIO:n=`${this.t("TUIChat.[音频]")}`;break;case t.TYPES.MSG_VIDEO:n=`${this.t("TUIChat.[视频]")}`;break;case t.TYPES.MSG_CUSTOM:n=`${this.t("TUIChat.[自定义消息]")}`;break;case t.TYPES.MSG_FILE:n=`${this.t("TUIChat.[文件]")}`;break;case t.TYPES.MSG_FACE:n=`${this.t("TUIChat.[动画表情]")}`}return`${s}: ${n}`}genMergerForwardPayload(e,t){const{abstractList:s=[],compatibleText:n="",title:o}=t;return 0===s.length&&e.forEach((e=>{s.push(this.setAbstractList(e))})),{messageList:e,title:o,abstractList:s,compatibleText:n||this.t("TUIChat.请升级IMSDK到v2.10.1或更高版本查看此消息")}}genSendMergerForwardMessage(e){const{conversationList:t,messageList:s,params:n,mergeInfo:o,sendMessageOptions:i}=e,r=[];for(let e=0;e<t.length;e++){const{conversationID:a,type:c}=t[e],u=Object.assign({to:a.replace(`${c}`,""),conversationType:c,payload:this.genMergerForwardPayload(s,o)},n),l=this.getEngine().chat.createMergerMessage(u);r.push(this.sendMessage(l,i))}return r}genTitle(e,t){const{nick:s,from:n,to:o}=e;return`${s||n} ${this.t("TUIChat.和")} ${t||o} ${this.t("TUIChat.的聊天记录")}`}genMergeInfo(e){var t;return o(this,void 0,void 0,(function*(){const{messageList:s,mergeInfo:n}=e;if(n.title)return n;if(s[0].conversationType===this.getEngine().TYPES.CONV_GROUP)return n.title=this.t("TUIChat.群聊的聊天记录"),n;try{const{data:e=[]}=yield this.getEngine().TUIUser.getUserProfile({userIDList:[s[0].to]});n.title=this.genTitle(s[0],null===(t=e[0])||void 0===t?void 0:t.nick)}catch(e){n.title=this.genTitle(s[0])}return n}))}sendMergerForwardMessage(e){return o(this,void 0,void 0,(function*(){return e.mergeInfo=yield this.genMergeInfo(e),Promise.all(this.genSendMergerForwardMessage(e))}))}getOriginMessageList(e){return e.map((e=>e instanceof co?e.getMessage():e))}sendForwardMessage(e,t,s){t=this.getOriginMessageList(t);const o=s||{},{needMerge:i=!1,params:r={},mergeInfo:a={}}=o,c=n(o,["needMerge","params","mergeInfo"]);if(i)return this.sendMergerForwardMessage({conversationList:e,messageList:t,params:r,mergeInfo:a,sendMessageOptions:c});const u=[];for(let s=0;s<e.length;s++){const{conversationID:n,type:o}=e[s],i=Object.assign({to:n.replace(`${o}`,""),conversationType:o},r),a=c[n]||c;for(let e=0;e<t.length;e++){Reflect.set(i,"payload",t[e]);const s=this.getEngine().chat.createForwardMessage(i);u.push(this.sendMessage(s,a))}}return Promise.all(u)}revokeMessage(e){const t=this.getEngine().chat.revokeMessage(e);return this.getResponse(t,!0,!1)}resendMessage(e){e.status="unSend",this.updateMessageList([e],"resend");const t=this.getEngine().chat.resendMessage(e);return this.getResponse(t,!0,!0)}deleteMessage(e){const t=this.getEngine().chat.deleteMessage(e);return this.getResponse(t,!0,!1)}setMessageExtensions(e,t){return this.getEngine().chat.setMessageExtensions(e,t)}getMessageExtensions(e){return this.getEngine().chat.getMessageExtensions(e)}deleteMessageExtensions(e,t){return this.getEngine().chat.deleteMessageExtensions(e,t)}modifyMessage(e){const t=this.getEngine().chat.modifyMessage(e);return this.getResponse(t,!0,!1).catch((e=>{const{code:t=0,data:s={}}=e.code;throw t===un.MSG_MODIFY_CONFLICT?console.warn(`${dn.MSG_MODIFY_CONFLICT} data.message: ${null==s?void 0:s.message}`):t===un.MSG_MODIFY_DISABLED_IN_AVCHATROOM?console.warn(dn.MSG_MODIFY_DISABLED_IN_AVCHATROOM):t===un.MODIFY_MESSAGE_NOT_EXIST&&console.warn(dn.MODIFY_MESSAGE_NOT_EXIST),e}))}getMessageList(e={conversationID:this.getStoreData(on.CONV,"currentConversationID"),nextReqMessageID:this.getStoreData(on.CHAT,"nextReqMessageID")}){const t=this.getEngine();if(!t.chat.isReady())return Promise.reject({code:ln.GET_MSG_LIST_ERROR,message:gn.GET_MSG_LIST_ERROR});if(this.getStoreData(on.CHAT,"isCompleted"))return Promise.resolve({data:{messageList:[],nextReqMessageID:"",isCompleted:!0}});const s=this.getStoreData(on.CHAT,"messageSource"),n=this.hoppingConfigMap.get("nextMessageSeq"),o=this.hoppingConfigMap.get("nextMessageTime"),i=n||o;return s&&s.conversationID===(null==e?void 0:e.conversationID)&&i?this.getMessageListHopping():t.chat.getMessageList(e).then((e=>{var s;const{messageList:n,nextReqMessageID:o,isCompleted:i}=e.data,r=this.getStoreData(on.CHAT,"userInfo");Object.keys(r).length>0&&this.updateLocalMessage(n,r),this.updateMessageList(n,"unshift"),t.TUIStore.update(on.CHAT,"nextReqMessageID",o),t.TUIStore.update(on.CHAT,"isCompleted",i);const a=null===(s=n[0])||void 0===s?void 0:s.conversationID,{operationType:c=0}=this.getEngine().TUIStore.getConversationModel(a)||{};return 0===c&&(this.getMessageReactions({messageList:n}),this.readReceiptHandler.getMessageReadReceiptList(n)),e})).catch((e=>Promise.reject(e)))}getMessageListHopping(e){var t;void 0===e&&(e={conversationID:null===(t=this.getStoreData(on.CHAT,"messageSource"))||void 0===t?void 0:t.conversationID,sequence:this.hoppingConfigMap.get("nextMessageSeq"),time:this.hoppingConfigMap.get("nextMessageTime")});const s=this.getEngine();return s.chat.getMessageListHopping(e).then((t=>{const{messageList:n,nextMessageSeq:o,nextMessageTime:i,isCompleted:r}=t.data,a=1===e.direction?e.sequence:o,c=1===e.direction?e.time:i;return this.updateMessageList(n,"unshift"),this.delayGetHoppingFunction=void 0,this.hoppingConfigMap.set("nextMessageSeq",a),this.hoppingConfigMap.set("nextMessageTime",c),s.TUIStore.update(on.CHAT,"isCompleted",r),t})).catch((e=>Promise.reject(e)))}sendMessageReadReceipt(e){return this.readReceiptHandler.sendMessageReadReceipt(e)}getGroupMessageReadMemberList(e){return this.readReceiptHandler.getGroupMessageReadMemberList(e).then((e=>{const{isCompleted:t,cursor:s,messageID:n,unreadUserIDList:o,readUserIDList:i}=e.data,r={code:0,data:{cursor:s,isCompleted:t,messageID:n,unreadUserInfoList:[],readUserInfoList:[]}},a=[...o,...i];return 0===a.length?r:this.getEngine().TUIUser.getUserProfile({userIDList:a}).then((e=>(o.length>0?e.data.forEach((e=>{const{userID:t,nick:s="",avatar:n=""}=e;r.data.unreadUserInfoList.push({userID:t,nick:s,avatar:n})})):e.data.forEach((e=>{const{userID:t,nick:s="",avatar:n=""}=e;r.data.readUserInfoList.push({userID:t,nick:s,avatar:n})})),r)))}))}downloadMergedMessages(e){return this.getEngine().chat.downloadMergerMessage(e)}setTranslationLanguage(e){this.getEngine().TUIStore.update(on.USER,"targetLanguage",e)}translateText(e){const t=this.getStoreData(on.USER,"targetLanguage"),s=Object.assign({targetLanguage:t,sourceLanguage:"auto"},e);return this.getEngine().chat.translateText(s)}searchCloudMessages(e){return this.getEngine().TUISearch.searchCloudMessages(e)}addMessageReaction(e,t){return this.getEngine().chat.addMessageReaction(e.getMessage(),t)}removeMessageReaction(e,t){return this.getEngine().chat.removeMessageReaction(e.getMessage(),t)}getMessageReactions(e){const{messageList:t=[]}=e,s=this.getStoreData(on.APP,"enabledEmojiPlugin");console.log(`TUIChatService.getMessageReactions enabledEmojiPlugin:${s} messageList length:${t.length}`),s&&t.length>0&&this.getEngine().chat.getMessageReactions(e).then((e=>{const t=e.data.resultList||e.data;this.updateMessageReactionList(t)})).catch((()=>{}))}getAllUserListOfMessageReaction(e){var t;return this.getEngine().chat.getAllUserListOfMessageReaction(Object.assign(Object.assign({},e),{message:null===(t=null==e?void 0:e.message)||void 0===t?void 0:t.getMessage()}))}updateMessageReactionList(e){const t=[];e.forEach((e=>{const{messageID:s,reactionList:n}=e,o=this.getEngine().TUIStore.getMessageModel(s);if(o){const e=[];for(let t=0;t<n.length;t++){let s=!0;for(let e=0;e<o.reactionList.length;e++)if(n[t].reactionID===o.reactionList[e].reactionID){o.reactionList[e]=n[t],s=!1;break}s&&e.push(n[t])}o.reactionList.push(...e),e.length=0,t.push(o)}})),t.length>0&&this.updateMessageList(t,"edit")}convertVoiceToText(e){const{message:t,language:s="zh"}=e,n=t.getMessage();return this.getEngine().chat.convertVoiceToText({message:n,language:s})}clearHistoryMessage(e){const t=this.getEngine();return t.chat.clearHistoryMessage(e).then((e=>(t.TUIStore.update(on.CHAT,"messageList",[]),t.TUIStore.update(on.CHAT,"nextReqMessageID",""),t.TUIStore.update(on.CHAT,"isCompleted",!1),e)))}updateMessageInfo(e){const t=this.getStoreData(on.CHAT,"userInfo");this.getEngine().TUIStore.update(on.CHAT,"userInfo",Object.assign(t,e));const s=this.getStoreData(on.CHAT,"messageList");if(s.length>0){this.updateLocalMessage(s,e)&&this.getEngine().TUIStore.update(on.CHAT,"messageList",s)}}updateLocalMessage(e,t){let s=!1;return e.forEach((e=>{if(t[e.from]){const{nick:n,nameCard:o,avatar:i}=t[e.from];n&&(e.nick=n,s=!0),o&&(e.nameCard=o,s=!0),i&&(e.avatar=i,s=!0)}})),s}handleC2CCallSignaling(e){const t=this.getEngine(),s=t.getMyUserID(),n=e.filter((e=>{var n,o,i,r,a;const{conversationType:c,type:u,payload:l}=e;let d=!0;if(c===t.TYPES.CONV_C2C&&u===t.TYPES.MSG_CUSTOM){if(t.chat.getSignalingInfo(e)){const t=Mn(l.data);if(1===(null==t?void 0:t.businessID)){const c=Mn(t.data);if(d=!(e._isExcludedFromUnreadCount&&e._isExcludedFromLastMessage),d&&!0!==(null===(n=null==c?void 0:c.data)||void 0===n?void 0:n.consumed)){let n=null===(o=null==c?void 0:c.data)||void 0===o?void 0:o.inviter;"line_busy"!==(null==c?void 0:c.line_busy)&&"lineBusy"!==(null===(i=null==c?void 0:c.data)||void 0===i?void 0:i.message)||(n=t.inviter);const{from:u,to:l}=e;if(n!==s&&e.from===s){const t=this.getStoreData(on.CONV,"currentConversation");e.from=l,e.to=u,e.flow="in",e.avatar=(null===(r=null==t?void 0:t.userProfile)||void 0===r?void 0:r.avatar)||""}if(n===s&&e.from!==s){const t=this.getStoreData(on.USER,"userProfile");e.from=l,e.to=u,e.flow="out",e.avatar=null==t?void 0:t.avatar}console.log(`${this.serv}.handleC2CCallSignaling myUserID:${s} callSignaling.inviter:${t.inviter} customData.data.inviter:${null===(a=null==c?void 0:c.data)||void 0===a?void 0:a.inviter}`)}}}}return d}));return n}sortMessageList(e){const{conversationType:t}=e[0];if(t===this.getEngine().TYPES.CONV_C2C)return e.sort(((e,t)=>e.time-t.time));const s=e.filter((e=>"success"===e.status)).sort(((e,t)=>e.sequence-t.sequence));for(let t=0;t<e.length;t++)"success"!==e[t].status&&s.splice(t,0,e[t]);return s}}class Ki extends no{constructor(){super(),this.groupMap=new Map}static getInstance(){return Ki.instance||(Ki.instance=new Ki),Ki.instance}init(){const e=this.getEngine();e.eventCenter.addEvent(e.EVENT.GROUP_LIST_UPDATED,this.onGroupListUpdated.bind(this)),e.eventCenter.addEvent(e.EVENT.GROUP_ATTRIBUTES_UPDATED,this.onGroupAttributesUpdated.bind(this)),e.eventCenter.addEvent(e.EVENT.GROUP_COUNTER_UPDATED,this.onGroupCounterUpdated.bind(this)),e.eventCenter.addEvent(e.EVENT.MESSAGE_RECEIVED,this.onMessageReceived.bind(this)),this.getGroupInitData()}onGroupListUpdated(e){const t=this.getEngine();t.TUIStore.update(on.GRP,"groupList",e);const s=t.TUIStore.getData(on.GRP,"currentGroupID");e.forEach((e=>{e.groupID===s&&t.TUIStore.update(on.GRP,"currentGroup",e)}))}onGroupAttributesUpdated(e){const t=this.getEngine(),s=t.TUIStore.getData(on.GRP,"currentGroupID");let n=t.TUIStore.getData(on.GRP,"groupList");const{groupID:o,groupAttributes:i}=e;s===o&&t.TUIStore.update(on.GRP,"currentGroupAttributes",i),n=n.map((e=>(e.groupID===o&&(e.groupAttributes=i),e))),t.TUIStore.update(on.GRP,"groupList",n)}onGroupCounterUpdated(e){const t=this.getEngine(),s=t.TUIStore.getData(on.GRP,"currentGroupID"),n=t.TUIStore.getData(on.GRP,"currentGroupCounters")||{};let o=t.TUIStore.getData(on.GRP,"groupList");const{groupID:i,key:r,value:a}=e;s===i&&(n[r]=a,t.TUIStore.update(on.GRP,"currentGroupCounters",n)),o=o.map((e=>(e.groupID===i&&(e.groupCounters=Object.assign(Object.assign({},e.groupCounters),{[r]:a})),e))),t.TUIStore.update(on.GRP,"groupList",o)}onMessageReceived(e){const t=this.getEngine(),s=[];e.forEach((e=>{if(e.type===t.TYPES.MSG_GRP_TIP){const{payload:s}=e,{operationType:n,userIDList:o}=s;switch(n){case t.TYPES.GRP_TIP_MBR_JOIN:this.addMemberList(o);break;case t.TYPES.GRP_TIP_MBR_QUIT:case t.TYPES.GRP_TIP_MBR_KICKED_OUT:this.removeMemberList(o);break;case t.TYPES.GRP_TIP_MBR_SET_ADMIN:case t.TYPES.GRP_TIP_MBR_CANCELED_ADMIN:this.updateGroupMember(o);break;case t.TYPES.GRP_TIP_GRP_PROFILE_UPDATED:break;case t.TYPES.GRP_TIP_MBR_PROFILE_UPDATED:case t.TYPES.GRP_TIP_BAN_AVCHATROOM_MEMBER:case t.TYPES.GRP_TIP_UNBAN_AVCHATROOM_MEMBER:this.updateGroupMember(o)}}e.type===t.TYPES.MSG_GRP_SYS_NOTICE&&s.push(e)})),s.length>0&&t.TUIStore.update(on.GRP,"groupSystemNoticeList",s)}getGroupInitData(){const e=this.getEngine();e.chat.isReady()&&e.chat.getGroupList().then((e=>{const{groupList:t=[]}=e.data;console.log(`TUIGroupService.init, getGroupList count:${t.length}`),t.length>0&&this.onGroupListUpdated(t)}))}updateGroupMember(e){return o(this,void 0,void 0,(function*(){const t=this.getEngine().TUIStore.getData(on.GRP,"currentGroupID");if(t){const s=yield this.getGroupMemberProfile({groupID:t,userIDList:e}),{memberList:n}=s.data;this.updateMemberList(n)}}))}resetCurrentStore(){this.getEngine().TUIStore.reset(on.GRP,["currentGroupID","currentGroup","currentGroupAttributes","currentGroupCounters","currentGroupMemberList"],!0)}switchGroup(e){return o(this,void 0,void 0,(function*(){const t=this.getEngine();t.TUIStore.update(on.GRP,"offset",0),t.TUIStore.update(on.GRP,"isCompleted",!1);const s=t.TUIStore.getConversationModel(`GROUP${e}`);if((null==s?void 0:s.operationType)>0){const e=t.TUIStore.getData(on.GRP,"currentGroup");return Promise.resolve(e)}const n=t.TUIStore.getData(on.GRP,"currentGroupID");if(!e)return this.resetCurrentStore(),Promise.resolve({});if(n===e){const e=t.TUIStore.getData(on.GRP,"currentGroup");return Promise.resolve(e)}this.resetCurrentStore(),t.TUIStore.update(on.GRP,"currentGroupID",e);try{yield this.getGroupInfo(e)}catch(e){Promise.reject(e)}const o=setTimeout((()=>{this.groupMap.delete(e),clearTimeout(o)}),5e3),i=t.TUIStore.getData(on.GRP,"currentGroup");return Promise.resolve(i)}))}getGroupInfo(e){return o(this,void 0,void 0,(function*(){const t=this.getEngine(),s=this.groupMap.get(e);if(s)return this.updateMemberList((null==s?void 0:s.memberList)||[]),t.TUIStore.update(on.GRP,"currentGroup",s.group),t.TUIStore.update(on.GRP,"currentGroupAttributes",s.groupAttributes||{}),void t.TUIStore.update(on.GRP,"currentGroupCounters",s.counters||{});const n={group:{},memberList:[],groupAttributes:void 0,counters:void 0},{data:{group:o}}=yield this.getGroupProfile({groupID:e});n.group=o;const{data:{memberList:i}}=yield this.getGroupMemberList({groupID:e});n.memberList=i;const r=yield this.getGroupAttributes({groupID:e,keyList:[]}),{groupAttributes:a}=r.data;n.groupAttributes=a,t.TUIStore.update(on.GRP,"currentGroupAttributes",a);try{const s=yield this.getGroupCounters({groupID:e,keyList:[]}),{counters:o}=s.data;n.counters=o,t.TUIStore.update(on.GRP,"currentGroupCounters",o)}catch(e){console.warn(null==e?void 0:e.message)}this.groupMap.set(e,n)}))}getGroupProfile(e){const t=this.getEngine();return t.chat.getGroupProfile(e).then((s=>o(this,void 0,void 0,(function*(){if(t.TUIStore.getData(on.GRP,"currentGroupID")===e.groupID){const{group:e}=s.data;t.TUIStore.update(on.GRP,"currentGroup",e)}return s}))))}updateGroupProfile(e){return this.getEngine().chat.updateGroupProfile(e)}createGroup(e){return this.getEngine().chat.createGroup(e)}dismissGroup(e){return this.getEngine().chat.dismissGroup(e)}searchGroupByID(e){const t=this.getEngine();return t.chat.searchGroupByID(e).then((e=>{const{group:s}=e.data,n=t.TUIStore.getData(on.GRP,"groupList");return e.data.group.isJoinedGroup=n.some((e=>e.groupID===s.groupID)),e}))}joinGroup(e){return this.getEngine().chat.joinGroup(e)}quitGroup(e){return this.getEngine().chat.quitGroup(e)}getGroupApplicationList(){return this.getEngine().chat.getGroupApplicationList()}handleGroupApplication(e){return this.getEngine().chat.handleGroupApplication(e)}getGroupOnlineMemberCount(e){return this.getEngine().chat.getGroupOnlineMemberCount(e)}changeGroupOwner(e){return this.getEngine().chat.changeGroupOwner(e)}initGroupAttributes(e){return this.getEngine().chat.initGroupAttributes(e)}setGroupAttributes(e){return this.getEngine().chat.setGroupAttributes(e)}deleteGroupAttributes(e){return this.getEngine().chat.deleteGroupAttributes(e)}getGroupAttributes(e){return this.getEngine().chat.getGroupAttributes(e)}setGroupCounters(e){return this.getEngine().chat.setGroupCounters(e)}increaseGroupCounter(e){return this.getEngine().chat.increaseGroupCounter(e)}decreaseGroupCounter(e){return this.getEngine().chat.decreaseGroupCounter(e)}getGroupCounters(e){return this.getEngine().chat.getGroupCounters(e)}updateMemberList(e){const t=this.getEngine(),s=[...(t.TUIStore.getData(on.GRP,"currentGroupMemberList")||[]).filter((t=>!e.find((e=>e.userID===t.userID)))),...e];t.TUIStore.update(on.GRP,"currentGroupMemberList",s)}addMemberList(e){return o(this,void 0,void 0,(function*(){const t=this.getEngine().TUIStore.getData(on.GRP,"currentGroupID");if(t)try{const s=yield this.getGroupMemberProfile({groupID:t,userIDList:e}),{memberList:n}=s.data;this.updateMemberList(n)}catch(t){const s=e.map((e=>({userID:e,avatar:"",nick:"",role:"",joinTime:0,nameCard:"",muteUntil:0,memberCustomField:[]})));this.updateMemberList(s)}}))}removeMemberList(e){const t=this.getEngine(),s=t.TUIStore.getData(on.GRP,"currentGroupMemberList").filter((t=>-1===e.indexOf(t.userID)));t.TUIStore.update(on.GRP,"currentGroupMemberList",s)}getGroupMemberList(e){const t=this.getEngine();if(En(e.offset)){const s=t.TUIStore.getData(on.GRP,"offset");e.offset=s}return t.chat.getGroupMemberList(e).then((s=>{if(t.TUIStore.getData(on.GRP,"currentGroupID")===e.groupID){const{memberList:e,offset:n=0}=s.data;this.updateMemberList(e),t.TUIStore.update(on.GRP,"offset",n),0===n&&t.TUIStore.update(on.GRP,"isCompleted",!0)}return s}))}getGroupMemberProfile(e){return this.getEngine().chat.getGroupMemberProfile(e)}addGroupMember(e){const t=this.getEngine();return t.chat.addGroupMember(e).then((s=>o(this,void 0,void 0,(function*(){if(t.TUIStore.getData(on.GRP,"currentGroupID")===e.groupID){const{successUserIDList:e,group:n}=s.data;t.TUIStore.update(on.GRP,"currentGroup",n),this.addMemberList(e)}return s}))))}deleteGroupMember(e){const t=this.getEngine();return t.chat.deleteGroupMember(e).then((s=>{if(t.TUIStore.getData(on.GRP,"currentGroupID")===e.groupID){const{userIDList:e,group:n}=s.data;this.removeMemberList(e),t.TUIStore.update(on.GRP,"currentGroup",n)}return s}))}setGroupMemberMuteTime(e){return this.getEngine().chat.setGroupMemberMuteTime(e)}setGroupMemberRole(e){return this.getEngine().chat.setGroupMemberRole(e)}setGroupMemberNameCard(e){return this.getEngine().chat.setGroupMemberNameCard(e)}setGroupMemberCustomField(e){return this.getEngine().chat.setGroupMemberCustomField(e)}markGroupMemberList(e){return this.getEngine().chat.markGroupMemberList(e)}}class Yi extends no{constructor(){super()}static getInstance(){return Yi.instance||(Yi.instance=new Yi),Yi.instance}init(){const e=this.getEngine();e.eventCenter.addEvent(e.EVENT.FRIEND_LIST_UPDATED,this.onFriendListUpdated.bind(this)),e.eventCenter.addEvent(e.EVENT.FRIEND_APPLICATION_LIST_UPDATED,this.onFriendApplicationListUpdated.bind(this)),this.getFriendInitData()}onFriendListUpdated(e){this.getEngine().TUIStore.update(on.FRIEND,"friendList",e)}onFriendApplicationListUpdated(e){const{friendApplicationList:t,unreadCount:s=0}=e,n=this.getEngine();n.TUIStore.update(on.FRIEND,"friendApplicationList",t),n.TUIStore.update(on.FRIEND,"friendApplicationUnreadCount",s)}getFriendInitData(){const e=this.getEngine();e.chat.isReady()&&(e.chat.getFriendList().then((e=>{const t=e.data||[];console.log(`TUIFriendService.init, getFriendList count:${t.length}`),t.length>0&&this.onFriendListUpdated(t)})),e.chat.getFriendApplicationList().then((e=>{this.onFriendApplicationListUpdated(e.data)})))}getFriendList(){return this.getEngine().chat.getFriendList()}getFriendRemark(e){const t=this.getEngine().TUIStore.getData(on.FRIEND,"friendList"),s={};return e.forEach((e=>{for(let n=0;n<t.length;n++)t[n].userID!==e||(s[e]=t[n].remark)})),s}addFriend(e){return this.getEngine().chat.addFriend(e)}deleteFriend(e){return this.getEngine().chat.deleteFriend(e)}checkFriend(e){return this.getEngine().chat.checkFriend(e)}getFriendProfile(e){return this.getEngine().chat.getFriendProfile(e)}updateFriend(e){return this.getEngine().chat.updateFriend(e)}acceptFriendApplication(e){return this.getEngine().chat.acceptFriendApplication(e)}refuseFriendApplication(e){return this.getEngine().chat.refuseFriendApplication({userID:e})}deleteFriendApplication(e){return this.getEngine().chat.deleteFriendApplication(e)}setFriendApplicationRead(){return this.getEngine().chat.setFriendApplicationRead()}}class Wi extends no{static getInstance(){return Wi.instance||(Wi.instance=new Wi),Wi.instance}reportFeature(e,t){var s;return null===(s=this.getEngine().chat)||void 0===s?void 0:s.callExperimentalAPI("statTUIKeyFeatures",{code:e,msg:t?`${e}-${t}`:""})}}!function(e){e.MESSAGE="message",e.CHAT_MESSAGE="chat_message",e.USER="user",e.GROUP="group"}(Li||(Li={})),function(e){e.MSG_TEXT="TIMTextElem",e.MSG_IMAGE="TIMImageElem",e.MSG_SOUND="TIMSoundElem",e.MSG_FILE="TIMFileElem",e.MSG_VIDEO="TIMVideoFileElem",e.MSG_LOCATION="TIMLocationElem",e.MSG_CUSTOM="TIMCustomElem",e.MSG_MERGER="TIMRelayElem"}(Ai||(Ai={})),function(e){e.GRP_WORK="Private",e.GRP_PUBLIC="Public",e.GRP_MEETING="ChatRoom",e.GRP_COMMUNITY="Community"}(Ui||(Ui={}));class zi extends no{constructor(){super(),this.resultKeyMap={[Li.MESSAGE]:"searchMessagesResult",[Li.CHAT_MESSAGE]:"searchChatMessagesResult",[Li.USER]:"searchUserResult",[Li.GROUP]:"searchGroupResult"},this.paramsKeyMap={[Li.MESSAGE]:"searchMessageParams",[Li.CHAT_MESSAGE]:"searchChatMessageParams",[Li.USER]:"searchUserParams",[Li.GROUP]:"searchGroupParams"}}static getInstance(){return zi.instance||(zi.instance=new zi),zi.instance}getStoreData(e,t){return this.getEngine().TUIStore.getData(e,t)}handleSearchResult(e,t){const{resultList:s}=this.getStoreData(on.SEARCH,this.resultKeyMap[e]),{cursor:n,searchResultList:o,params:i,totalCount:r}=t,a=[];if(e===Li.CHAT_MESSAGE){const{conversation:e}=s[0]||{},{conversation:t}=o[0];(null==e?void 0:e.conversationID)===t.conversationID&&1===s.length&&(o[0].messageList=[...s[0].messageList,...o[0].messageList]),a.push(...o)}else a.push(...s,...o);this.getEngine().TUIStore.update(on.SEARCH,this.resultKeyMap[e],{resultList:a,params:i,hasMore:!!n,cursor:n,totalCount:r})}searchParamsValidate(e,t){const s=this.getStoreData(on.SEARCH,this.paramsKeyMap[e]),{cursor:o}=s,i=n(s,["cursor"]),{cursor:r}=t,a=n(t,["cursor"]),c=JSON.stringify(i)===JSON.stringify(a),u=!!r,l=r===o;return c?c&&!u?(this.getEngine().TUIStore.reset(on.SEARCH,[this.resultKeyMap[e]]),this.getEngine().TUIStore.update(on.SEARCH,this.paramsKeyMap[e],t),!0):!(!c||!u||l):(this.getEngine().TUIStore.reset(on.SEARCH,[this.resultKeyMap[e]]),this.getEngine().TUIStore.update(on.SEARCH,this.paramsKeyMap[e],t),!0)}searchCloudMessages(e){const{keyword:t,keywordList:s,conversationID:o}=e,i=n(e,["keyword","keywordList","conversationID"]);let r=!0;if(r=o?this.searchParamsValidate(Li.CHAT_MESSAGE,e):this.searchParamsValidate(Li.MESSAGE,e),!r)return Promise.resolve();const a=this.getStoreData(on.CONV,"conversationList");return this.getEngine().chat.searchCloudMessages(Object.assign({keywordList:t?[t]:s||void 0,keywordListMatchType:"or",conversationID:o},i)).then((t=>{const{searchResultList:s}=t.data;return(null==s?void 0:s.length)>0&&(t.data.searchResultList=s.map((e=>{const{messageList:t,conversationID:s}=e,o=n(e,["messageList","conversationID"]),i=t.map((e=>new co(e))),r=a.find((e=>e.conversationID===s));return Object.assign(Object.assign({},o),{messageList:i.sort(((e,t)=>t.time-e.time)),conversation:r})}))),t.data.params=e,o?this.handleSearchResult(Li.CHAT_MESSAGE,t.data):this.handleSearchResult(Li.MESSAGE,t.data),t})).catch((e=>{this.getEngine().TUIStore.update(on.SEARCH,"error",e),Promise.resolve(e)}))}searchCloudUsers(t){const{keyword:s,keywordList:o}=t,i=n(t,["keyword","keywordList"]),r=this.getStoreData(on.FRIEND,"friendList");return this.searchParamsValidate(Li.USER,t)?this.getEngine().chat.searchCloudUsers(Object.assign({keywordList:s?[s]:o||void 0,keywordListMatchType:"or"},i)).then((s=>{const{searchResultList:n}=s.data;if(n.length>0){const t=new Map(n.map((t=>[t.userID,{profile:t,relation:e.TYPES.SNS_TYPE_NO_RELATION}])));r.forEach((s=>{const{userID:n}=s,o=t.get(n);o&&(o.relation=e.TYPES.SNS_TYPE_BOTH_WAY)})),s.data.searchResultList=Array.from(t.values())}return s.data.params=t,this.handleSearchResult(Li.USER,s.data),s})).catch((e=>{this.getEngine().TUIStore.update(on.SEARCH,"error",e),Promise.resolve(e)})):Promise.resolve()}searchCloudGroups(e){const{keyword:t,keywordList:s}=e,o=n(e,["keyword","keywordList"]),i=this.getStoreData(on.CONV,"conversationList"),r=this.getStoreData(on.GRP,"groupList");return this.searchParamsValidate(Li.GROUP,e)?this.getEngine().chat.searchCloudGroups(Object.assign({keywordList:t?[t]:s||void 0,keywordListMatchType:"or"},o)).then((t=>{const{searchResultList:s}=t.data;return s.length>0&&(t.data.searchResultList=s.map((e=>{const t=r.find((t=>t.groupID===e.groupID)),s=i.find((t=>t.conversationID===`GROUP${e.groupID}`));return{groupInfo:t||e,conversation:s}}))),t.data.params=e,this.handleSearchResult(Li.GROUP,t.data),t})).catch((e=>{this.getEngine().TUIStore.update(on.SEARCH,"error",e),Promise.resolve(e)})):Promise.resolve()}}class Ji{constructor(){this.cache=[],this.middlewares=[],this.options=null}use(e){return"function"!=typeof e&&console.error("middleware must be a function"),this.cache.push(e),this}next(){if(this.middlewares&&this.middlewares.length>0){return this.middlewares.shift().call(this,this.options,this.next.bind(this))}}run(e){return this.middlewares=this.cache.map((e=>e)),this.options=e,this.next()}}function Xi(e,t,s){const n=Object.create(null);Object.keys(s).forEach((s=>{if(!t[s])return;n[s]=t[s];const o=new Ji;t[s]=function(){const i=Array.from(arguments);return o.use(((t,n)=>e.isInited?n():Promise.reject({code:ln.NOT_INIT,message:`${s} | ${gn.NOT_INIT}`}))).use((e=>n[s].apply(t,e))),o.run(i)}}))}console.log("TUIChatEngine.VERSION:3.0.0-beta.0");const Qi=eo.getInstance(),Zi=Xn.getInstance(),er=fo.getInstance(),tr=Pi.getInstance(),sr=Gi.getInstance(),nr=ji.getInstance(),or=Bi.getInstance(),ir=Ki.getInstance(),rr=Yi.getInstance(),ar=Wi.getInstance(),cr=zi.getInstance();Qi.mount(nn.TUIStore,er),Qi.mount(nn.TUITranslate,tr),Qi.mount(nn.TUIConversation,sr),Qi.mount(nn.TUIUser,nr),Qi.mount(nn.TUIChat,or),Qi.mount(nn.TUIGroup,ir),Qi.mount(nn.TUIFriend,rr),Qi.mount(nn.TUIReport,ar),Qi.mount(nn.TUISearch,cr),Xi(Qi,Qi,mn),Xi(Qi,sr,fn),Xi(Qi,or,vn),Xi(Qi,ir,_n),Xi(Qi,nr,In),Xi(Qi,rr,yn),Xi(Qi,ar,mn),Xi(Qi,cr,mn);export{Ui as GroupType,Li as ISearchType,Ai as MessageType,on as StoreName,Qi as TUIChatEngine,or as TUIChatService,sr as TUIConversationService,rr as TUIFriendService,Zi as TUIGlobal,ir as TUIGroupService,ar as TUIReportService,cr as TUISearchService,er as TUIStore,tr as TUITranslateService,nr as TUIUserService,Qi as default};
1
+ import e from"@tencentcloud/lite-chat";import t from"@tencentcloud/lite-chat/plugins/conversation";import s from"@tencentcloud/lite-chat/plugins/group";import n from"@tencentcloud/lite-chat/plugins/message-enhancer";import i from"@tencentcloud/lite-chat/plugins/rich-media-message";import r from"@tencentcloud/lite-chat/plugins/cloud-search";import a from"@tencentcloud/lite-chat/plugins/friend";import o from"tim-upload-plugin";import u from"tim-profanity-filter-plugin";function c(e,t){var s={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(s[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(n=Object.getOwnPropertySymbols(e);i<n.length;i++)t.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(e,n[i])&&(s[n[i]]=e[n[i]])}return s}function g(e,t,s,n){return new(s||(s=Promise))((function(i,r){function a(e){try{u(n.next(e))}catch(e){r(e)}}function o(e){try{u(n.throw(e))}catch(e){r(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(a,o)}u((n=n.apply(e,t||[])).next())}))}class l{constructor(e){return l.instance||(l.instance=this,this.engine=e,this.events={},this.bindIMEvents()),l.instance}addEvent(e,t){this.events[e]||(this.events[e]=new Map),this.events[e].set(t,1)}removeEvents(){Object.keys(this.events).forEach((e=>{this.events[e].clear()})),this.events={}}dispatch(e,t){if(this.events[e])for(const s of this.events[e].keys())s.call(this,t)}bindIMEvents(){this.engine.chat.on(this.engine.EVENT.SDK_READY,this.onSDKReady,this),this.engine.chat.on(this.engine.EVENT.SDK_NOT_READY,this.onSDKNotReady,this),this.engine.chat.on(this.engine.EVENT.KICKED_OUT,this.onKickedOut,this),this.engine.chat.on(this.engine.EVENT.NET_STATE_CHANGE,this.onNetStateChange,this),this.engine.chat.on(this.engine.EVENT.MESSAGE_RECEIVED,this.onReceiveMessage,this),this.engine.chat.on(this.engine.EVENT.MESSAGE_MODIFIED,this.onMessageModified,this),this.engine.chat.on(this.engine.EVENT.MESSAGE_REVOKED,this.onMessageRevoked,this),this.engine.chat.on(this.engine.EVENT.MESSAGE_READ_BY_PEER,this.onMessageReadByPeer,this),this.engine.chat.on(this.engine.EVENT.MESSAGE_READ_RECEIPT_RECEIVED,this.onMessageReadReceiptReceived,this),this.engine.chat.on(this.engine.EVENT.MESSAGE_REACTIONS_UPDATED,this.onMessageReactionsUpdated,this),this.engine.chat.on(this.engine.EVENT.CONVERSATION_LIST_UPDATED,this.onConversationListUpdated,this),this.engine.chat.on(this.engine.EVENT.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED,this.onTotalMessageCountUpdated,this),this.engine.chat.on(this.engine.EVENT.PROFILE_UPDATED,this.onProfileUpdated,this),this.engine.chat.on(this.engine.EVENT.BLACKLIST_UPDATED,this.onBlacklistUpdated,this),this.engine.chat.on(this.engine.EVENT.USER_STATUS_UPDATED,this.onUserStatusUpdated,this),this.engine.chat.on(this.engine.EVENT.GROUP_LIST_UPDATED,this.onGroupListUpdated,this),this.engine.chat.on(this.engine.EVENT.GROUP_ATTRIBUTES_UPDATED,this.onGroupAttributesUpdated,this),this.engine.chat.on(this.engine.EVENT.GROUP_COUNTER_UPDATED,this.onGroupCounterUpdated,this),this.engine.chat.on(this.engine.EVENT.FRIEND_LIST_UPDATED,this.onFriendListUpdated,this),this.engine.chat.on(this.engine.EVENT.FRIEND_APPLICATION_LIST_UPDATED,this.onFriendApplicationListUpdated,this)}unbindIMEvents(){this.engine.chat.off(this.engine.EVENT.SDK_READY,this.onSDKReady,this),this.engine.chat.off(this.engine.EVENT.SDK_NOT_READY,this.onSDKNotReady,this),this.engine.chat.off(this.engine.EVENT.KICKED_OUT,this.onKickedOut,this),this.engine.chat.off(this.engine.EVENT.NET_STATE_CHANGE,this.onNetStateChange,this),this.engine.chat.off(this.engine.EVENT.MESSAGE_RECEIVED,this.onReceiveMessage,this),this.engine.chat.off(this.engine.EVENT.MESSAGE_MODIFIED,this.onMessageModified,this),this.engine.chat.off(this.engine.EVENT.MESSAGE_REVOKED,this.onMessageRevoked,this),this.engine.chat.off(this.engine.EVENT.MESSAGE_READ_BY_PEER,this.onMessageReadByPeer,this),this.engine.chat.off(this.engine.EVENT.MESSAGE_READ_RECEIPT_RECEIVED,this.onMessageReadReceiptReceived,this),this.engine.chat.off(this.engine.EVENT.MESSAGE_REACTIONS_UPDATED,this.onMessageReactionsUpdated,this),this.engine.chat.off(this.engine.EVENT.CONVERSATION_LIST_UPDATED,this.onConversationListUpdated,this),this.engine.chat.off(this.engine.EVENT.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED,this.onTotalMessageCountUpdated,this),this.engine.chat.off(this.engine.EVENT.PROFILE_UPDATED,this.onProfileUpdated,this),this.engine.chat.off(this.engine.EVENT.BLACKLIST_UPDATED,this.onBlacklistUpdated,this),this.engine.chat.off(this.engine.EVENT.USER_STATUS_UPDATED,this.onUserStatusUpdated,this),this.engine.chat.off(this.engine.EVENT.GROUP_LIST_UPDATED,this.onGroupListUpdated,this),this.engine.chat.off(this.engine.EVENT.GROUP_ATTRIBUTES_UPDATED,this.onGroupAttributesUpdated,this),this.engine.chat.off(this.engine.EVENT.GROUP_COUNTER_UPDATED,this.onGroupCounterUpdated,this),this.engine.chat.off(this.engine.EVENT.FRIEND_LIST_UPDATED,this.onFriendListUpdated,this),this.engine.chat.off(this.engine.EVENT.FRIEND_APPLICATION_LIST_UPDATED,this.onFriendApplicationListUpdated,this),l.instance=null}onSDKReady(e){this.dispatch(this.engine.EVENT.SDK_READY,e.data)}onSDKNotReady(e){this.dispatch(this.engine.EVENT.SDK_NOT_READY,e.data)}onKickedOut(e){this.dispatch(this.engine.EVENT.KICKED_OUT,e.data)}onNetStateChange(e){this.dispatch(this.engine.EVENT.NET_STATE_CHANGE,e.data)}onReceiveMessage(e){this.dispatch(this.engine.EVENT.MESSAGE_RECEIVED,e.data)}onMessageModified(e){this.dispatch(this.engine.EVENT.MESSAGE_MODIFIED,e.data)}onMessageRevoked(e){this.dispatch(this.engine.EVENT.MESSAGE_REVOKED,e.data)}onMessageReadByPeer(e){this.dispatch(this.engine.EVENT.MESSAGE_READ_BY_PEER,e.data)}onMessageReadReceiptReceived(e){this.dispatch(this.engine.EVENT.MESSAGE_READ_RECEIPT_RECEIVED,e.data)}onMessageReactionsUpdated(e){this.dispatch(this.engine.EVENT.MESSAGE_REACTIONS_UPDATED,e.data)}onConversationListUpdated(e){this.dispatch(this.engine.EVENT.CONVERSATION_LIST_UPDATED,e.data)}onTotalMessageCountUpdated(e){this.dispatch(this.engine.EVENT.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED,e.data)}onProfileUpdated(e){this.dispatch(this.engine.EVENT.PROFILE_UPDATED,e.data)}onBlacklistUpdated(e){this.dispatch(this.engine.EVENT.BLACKLIST_UPDATED,e.data)}onUserStatusUpdated(e){this.dispatch(this.engine.EVENT.USER_STATUS_UPDATED,e.data)}onGroupListUpdated(e){this.dispatch(this.engine.EVENT.GROUP_LIST_UPDATED,e.data)}onGroupAttributesUpdated(e){this.dispatch(this.engine.EVENT.GROUP_ATTRIBUTES_UPDATED,e.data)}onGroupCounterUpdated(e){this.dispatch(this.engine.EVENT.GROUP_COUNTER_UPDATED,e.data)}onFriendListUpdated(e){this.dispatch(this.engine.EVENT.FRIEND_LIST_UPDATED,e.data)}onFriendApplicationListUpdated(e){this.dispatch(this.engine.EVENT.FRIEND_APPLICATION_LIST_UPDATED,e.data)}}var h,p,d,f,m,E,v,T,S;!function(e){e.TUIStore="TUIStore",e.TUITranslate="TUITranslate",e.TUIConversation="TUIConversation",e.TUIChat="TUIChat",e.TUIGroup="TUIGroup",e.TUIUser="TUIUser",e.TUIFriend="TUIFriend",e.TUIReport="TUIReport",e.TUISearch="TUISearch"}(h||(h={})),function(e){e.APP="application",e.CONV="conversation",e.CHAT="chat",e.GRP="group",e.USER="user",e.FRIEND="friend",e.SEARCH="search",e.CUSTOM="custom"}(p||(p={})),function(e){e[e.UNSUB_USER=-1]="UNSUB_USER"}(d||(d={})),function(e){e.BUSINESS_ID="user_typing_status",e[e.STATUS_START=1]="STATUS_START",e[e.STATUS_END=0]="STATUS_END",e[e.VERSION=1]="VERSION",e[e.ACTION_START_ID=14]="ACTION_START_ID",e[e.ACTION_END_ID=0]="ACTION_END_ID",e.ACTION_START="EIMAMSG_InputStatus_Ing",e.ACTION_END="EIMAMSG_InputStatus_End",e[e.NEED_TYPING=1]="NEED_TYPING"}(f||(f={})),function(e){e.ADD="add",e.REMOVE="remove"}(m||(m={})),function(e){e[e.MSG_MODIFY_CONFLICT=2480]="MSG_MODIFY_CONFLICT",e[e.MSG_MODIFY_DISABLED_IN_AVCHATROOM=2481]="MSG_MODIFY_DISABLED_IN_AVCHATROOM",e[e.MODIFY_MESSAGE_NOT_EXIST=20026]="MODIFY_MESSAGE_NOT_EXIST"}(E||(E={})),function(e){e[e.NOT_INIT=-1e5]="NOT_INIT",e[e.INVALID_CONV_ID=-100001]="INVALID_CONV_ID",e[e.CONV_ID_SAME=-100002]="CONV_ID_SAME",e[e.CONV_NOT_EXIST=-100003]="CONV_NOT_EXIST",e[e.GET_MSG_LIST_ERROR=-100004]="GET_MSG_LIST_ERROR",e[e.MISMATCH_TYPE_AND_PAYLOAD=-100005]="MISMATCH_TYPE_AND_PAYLOAD"}(v||(v={})),function(e){e.MSG_MODIFY_CONFLICT="MODIFY_MESSAGE_ERROR,修改消息发生冲突, data.message 是最新的消息",e.MSG_MODIFY_DISABLED_IN_AVCHATROOM="MODIFY_MESSAGE_ERROR,不支持修改直播群消息.",e.MODIFY_MESSAGE_NOT_EXIST="MODIFY_MESSAGE_ERROR,消息不存在."}(T||(T={})),function(e){e.NOT_INIT="TUIChatEngine 初始化未完成,请确认 TUIChatEngine.login 接口调用是否正常。",e.INVALID_CONV_ID="会话 ID 无效",e.CONV_ID_SAME="您切换的是同一个会话 ID",e.CONV_NOT_EXIST="会话不存在",e.GET_MSG_LIST_ERROR="Chat SDK is not ready.",e.MISMATCH_TYPE_AND_PAYLOAD="type 与 payload 不匹配."}(S||(S={}));const I={logout:1,destroy:1},y={deleteConversation:1,pinConversation:1,muteConversation:1,switchConversation:1,getConversationProfile:1,clearHistoryMessage:1},b={modifyMessage:1,revokeMessage:1,resendMessage:1,deleteMessage:1,quoteMessage:1,replyMessage:1,setMessageExtensions:1,deleteMessageExtensions:1,getMessageExtensions:1,sendTextMessage:1,sendTextAtMessage:1,sendImageMessage:1,sendAudioMessage:1,sendVideoMessage:1,sendFileMessage:1,sendCustomMessage:1,sendFaceMessage:1,sendLocationMessage:1,sendForwardMessage:1,enterTypingState:1,leaveTypingState:1,sendMessageReadReceipt:1,getGroupMessageReadMemberList:1,getMessageList:1,downloadMergedMessages:1,setTranslationLanguage:1,translateText:1,searchCloudMessages:1,addMessageReaction:1,removeMessageReaction:1,getMessageReactions:1,getAllUserListOfMessageReaction:1},M={switchGroup:1,getGroupProfile:1,updateGroupProfile:1,createGroup:1,dismissGroup:1,searchGroupByID:1,joinGroup:1,quitGroup:1,getGroupApplicationList:1,handleGroupApplication:1,getGroupOnlineMemberCount:1,changeGroupOwner:1,initGroupAttributes:1,setGroupAttributes:1,deleteGroupAttributes:1,getGroupAttributes:1,setGroupCounters:1,increaseGroupCounter:1,decreaseGroupCounter:1,getGroupCounters:1,getGroupMemberList:1,getGroupMemberProfile:1,addGroupMember:1,deleteGroupMember:1,setGroupMemberMuteTime:1,setGroupMemberRole:1,setGroupMemberNameCard:1,setGroupMemberCustomField:1,markGroupMemberList:1},U={switchUserStatus:1,switchMessageReadStatus:1,getUserProfile:1,updateMyProfile:1,addToBlacklist:1,removeFromBlacklist:1},C={getFriendList:1,addFriend:1,deleteFriend:1,checkFriend:1,getFriendProfile:1,updateFriend:1,acceptFriendApplication:1,refuseFriendApplication:1,deleteFriendApplication:1,setFriendApplicationRead:1},O=function(e){return void 0===e},_=function(e){return e.startsWith("_")},D=function(e){return/^(https?:\/\/(([a-zA-Z0-9]+-?)+[a-zA-Z0-9]+\.)+[a-zA-Z]+)(:\d+)?(\/.*)?(\?.*)?(#.*)?$/.test(e)};const P=function(e){return e&&function(e){if("string"==typeof e)try{return!!JSON.parse(e)}catch(e){return!1}return!1}(e)?JSON.parse(e):e},R=function(e){let t="";return t=e>=1048576?`${(e/1048576).toFixed(2)} Mb`:e>=1024?`${(e/1024).toFixed(2)} Kb`:`${e.toFixed(2)}B`,t},L="https://web.sdk.qcloud.com/component/TUIKit/assets/avatar_16.png",A="https://web.sdk.qcloud.com/im/demo/TUIkit/web/img/constomer.png",j="https://web.sdk.qcloud.com/component/TUIKit/assets/group_avatar.png",k="https://web.sdk.qcloud.com/im/assets/emoji-plugin/",N="https://web.sdk.qcloud.com/im/assets/face-elem/",G="https://map.qq.com/?type=marker&isopeninfowin=1&markertype=1&",x="https://apis.map.qq.com/ws/staticmap/v2/?",w={"[TUIEmoji_Expect]":"emoji_0@2x.png","[TUIEmoji_Blink]":"emoji_1@2x.png","[TUIEmoji_Guffaw]":"emoji_2@2x.png","[TUIEmoji_KindSmile]":"emoji_3@2x.png","[TUIEmoji_Haha]":"emoji_4@2x.png","[TUIEmoji_Cheerful]":"emoji_5@2x.png","[TUIEmoji_Smile]":"emoji_6@2x.png","[TUIEmoji_Sorrow]":"emoji_7@2x.png","[TUIEmoji_Speechless]":"emoji_8@2x.png","[TUIEmoji_Amazed]":"emoji_9@2x.png","[TUIEmoji_Complacent]":"emoji_10@2x.png","[TUIEmoji_Lustful]":"emoji_11@2x.png","[TUIEmoji_Stareyes]":"emoji_12@2x.png","[TUIEmoji_Giggle]":"emoji_13@2x.png","[TUIEmoji_Daemon]":"emoji_14@2x.png","[TUIEmoji_Rage]":"emoji_15@2x.png","[TUIEmoji_Yawn]":"emoji_16@2x.png","[TUIEmoji_TearsLaugh]":"emoji_17@2x.png","[TUIEmoji_Silly]":"emoji_18@2x.png","[TUIEmoji_Wail]":"emoji_19@2x.png","[TUIEmoji_Kiss]":"emoji_20@2x.png","[TUIEmoji_Trapped]":"emoji_21@2x.png","[TUIEmoji_Fear]":"emoji_22@2x.png","[TUIEmoji_BareTeeth]":"emoji_23@2x.png","[TUIEmoji_FlareUp]":"emoji_24@2x.png","[TUIEmoji_Tact]":"emoji_25@2x.png","[TUIEmoji_Shit]":"emoji_26@2x.png","[TUIEmoji_ShutUp]":"emoji_27@2x.png","[TUIEmoji_Sigh]":"emoji_28@2x.png","[TUIEmoji_Hehe]":"emoji_29@2x.png","[TUIEmoji_Silent]":"emoji_30@2x.png","[TUIEmoji_Skull]":"emoji_31@2x.png","[TUIEmoji_Mask]":"emoji_32@2x.png","[TUIEmoji_Beer]":"emoji_33@2x.png","[TUIEmoji_Cake]":"emoji_34@2x.png","[TUIEmoji_RedPacket]":"emoji_35@2x.png","[TUIEmoji_Bombs]":"emoji_36@2x.png","[TUIEmoji_Ai]":"emoji_37@2x.png","[TUIEmoji_Celebrate]":"emoji_38@2x.png","[TUIEmoji_Bless]":"emoji_39@2x.png","[TUIEmoji_Flower]":"emoji_40@2x.png","[TUIEmoji_Watermelon]":"emoji_41@2x.png","[TUIEmoji_Cow]":"emoji_42@2x.png","[TUIEmoji_Fool]":"emoji_43@2x.png","[TUIEmoji_Surprised]":"emoji_44@2x.png","[TUIEmoji_Askance]":"emoji_45@2x.png","[TUIEmoji_Monster]":"emoji_46@2x.png","[TUIEmoji_Pig]":"emoji_47@2x.png","[TUIEmoji_Coffee]":"emoji_48@2x.png","[TUIEmoji_Ok]":"emoji_49@2x.png","[TUIEmoji_Heart]":"emoji_50@2x.png","[TUIEmoji_Sun]":"emoji_51@2x.png","[TUIEmoji_Moon]":"emoji_52@2x.png","[TUIEmoji_Star]":"emoji_53@2x.png","[TUIEmoji_Rich]":"emoji_54@2x.png","[TUIEmoji_Fortune]":"emoji_55@2x.png","[TUIEmoji_857]":"emoji_56@2x.png","[TUIEmoji_666]":"emoji_57@2x.png","[TUIEmoji_Prohibit]":"emoji_58@2x.png","[TUIEmoji_Convinced]":"emoji_59@2x.png","[TUIEmoji_Knife]":"emoji_60@2x.png","[TUIEmoji_Like]":"emoji_61@2x.png"},V={"[TUIEmoji_Smile]":"[微笑]","[TUIEmoji_Expect]":"[期待]","[TUIEmoji_Blink]":"[眨眼]","[TUIEmoji_Guffaw]":"[大笑]","[TUIEmoji_KindSmile]":"[姨母笑]","[TUIEmoji_Haha]":"[哈哈哈]","[TUIEmoji_Cheerful]":"[愉快]","[TUIEmoji_Speechless]":"[无语]","[TUIEmoji_Amazed]":"[惊讶]","[TUIEmoji_Sorrow]":"[悲伤]","[TUIEmoji_Complacent]":"[得意]","[TUIEmoji_Silly]":"[傻了]","[TUIEmoji_Lustful]":"[色]","[TUIEmoji_Giggle]":"[憨笑]","[TUIEmoji_Kiss]":"[亲亲]","[TUIEmoji_Wail]":"[大哭]","[TUIEmoji_TearsLaugh]":"[哭笑]","[TUIEmoji_Trapped]":"[困]","[TUIEmoji_Mask]":"[口罩]","[TUIEmoji_Fear]":"[恐惧]","[TUIEmoji_BareTeeth]":"[龇牙]","[TUIEmoji_FlareUp]":"[发怒]","[TUIEmoji_Yawn]":"[打哈欠]","[TUIEmoji_Tact]":"[机智]","[TUIEmoji_Stareyes]":"[星星眼]","[TUIEmoji_ShutUp]":"[闭嘴]","[TUIEmoji_Sigh]":"[叹气]","[TUIEmoji_Hehe]":"[呵呵]","[TUIEmoji_Silent]":"[收声]","[TUIEmoji_Surprised]":"[惊喜]","[TUIEmoji_Askance]":"[白眼]","[TUIEmoji_Ok]":"[OK]","[TUIEmoji_Shit]":"[便便]","[TUIEmoji_Monster]":"[怪兽]","[TUIEmoji_Daemon]":"[恶魔]","[TUIEmoji_Rage]":"[恶魔怒]","[TUIEmoji_Fool]":"[衰]","[TUIEmoji_Pig]":"[猪]","[TUIEmoji_Cow]":"[牛]","[TUIEmoji_Ai]":"[AI]","[TUIEmoji_Skull]":"[骷髅]","[TUIEmoji_Bombs]":"[炸弹]","[TUIEmoji_Coffee]":"[咖啡]","[TUIEmoji_Cake]":"[蛋糕]","[TUIEmoji_Beer]":"[啤酒]","[TUIEmoji_Flower]":"[花]","[TUIEmoji_Watermelon]":"[瓜]","[TUIEmoji_Rich]":"[壕]","[TUIEmoji_Heart]":"[爱心]","[TUIEmoji_Moon]":"[月亮]","[TUIEmoji_Sun]":"[太阳]","[TUIEmoji_Star]":"[星星]","[TUIEmoji_RedPacket]":"[红包]","[TUIEmoji_Celebrate]":"[庆祝]","[TUIEmoji_Bless]":"[福]","[TUIEmoji_Fortune]":"[发]","[TUIEmoji_Convinced]":"[服]","[TUIEmoji_Prohibit]":"[禁]","[TUIEmoji_666]":"[666]","[TUIEmoji_857]":"[857]","[TUIEmoji_Knife]":"[刀]","[TUIEmoji_Like]":"[赞]"},F={enabledMessageReadReceipt:Math.pow(2,5),enabledEmojiPlugin:Math.pow(2,48),enabledOnlineStatus:Math.pow(2,7),enabledCustomerServicePlugin:Math.pow(2,40),enabledTranslationPlugin:Math.pow(2,38),enabledVoiceToText:Math.pow(2,39)},$=["messageList","conversationList","newMessageList"],H=["translateTextInfo","voiceToTextInfo"],Y="undefined"!=typeof wx&&"function"==typeof wx.getSystemInfoSync&&Boolean(wx.getSystemInfoSync().fontSizeSetting),B="undefined"!=typeof uni&&"undefined"==typeof window,K=Y||B,q="undefined"!=typeof uni,z=("undefined"!=typeof uni||"undefined"!=typeof window)&&!K,J=Y?wx:q?uni:window,W=z&&window&&window.navigator&&window.navigator.userAgent||"",X=/Android/i.test(W),Z=/(?:Windows Phone)/.test(W),Q=/(?:SymbianOS)/.test(W),ee=/iPad/i.test(W)||/iPhone/i.test(W)||/iPod/i.test(W),te=X||Z||Q||ee,se=z&&!te;class ne{constructor(){this.global=J,this.isOfficial=!1}static getInstance(){return ne.instance||(ne.instance=new ne),ne.instance}initOfficial(e){this.isOfficial=e}getPlatform(){let e="";return se?e="pc":te?e="h5":Y?e="wechat":B&&!Y&&(e="app"),e}}const ie="group-module",re="relationship-module";class ae{constructor(){this.EVENT=e.EVENT,this.TYPES=e.TYPES,this.loginStatusPromise=new Map,this.userID="",this.isInited=!1}static getInstance(){return ae.instance||(ae.instance=new ae),ae.instance}mount(e,t){this[e]=t}login(t){const{chat:s,SDKAppID:n,userID:i}=t,r=1400187352===n||1400188366===n;return this.createChat(t),this.userID=i,ne.getInstance().initOfficial(r),this.TUIStore.update(p.APP,"isOfficial",r),this.TUIStore.update(p.APP,"SDKVersion",e.VERSION),this.eventCenter=new l(this),this.eventCenter.removeEvents(),this.resetStore(),this.initService(),s&&s.isReady()?(console.log("TUIChatEngine.login ok, from TUICore."),this.TUIUser.getUserProfile(),this.checkCommercialAbility(),Promise.resolve({})):(this.registerPlugin(t),this.eventCenter.addEvent(this.EVENT.SDK_READY,(()=>{this.onSDKReady()})),this.eventCenter.addEvent(this.EVENT.SDK_NOT_READY,(()=>{this.onSDKNotReady()})),this.loginChat(t))}logout(){return this.userID="",this.isInited=!1,this.resetStore(),this.chat.logout()}isReady(){var e;return(null===(e=this.chat)||void 0===e?void 0:e.isReady())||!1}setLogLevel(e){this.chat?this.chat.setLogLevel(e):console.warn("TUIChatEngine 初始化未完成,请确认 TUIChatEngine.login 接口调用是否正常。")}destroy(){return this.eventCenter.unbindIMEvents(),this.isInited=!1,this.resetStore(),this.chat.destroy()}getMyUserID(){return this.userID}resetStore(){this.TUIStore.reset(p.CHAT),this.TUIStore.reset(p.CONV),this.TUIStore.reset(p.GRP),this.TUIStore.reset(p.USER),this.TUIStore.reset(p.SEARCH),this.TUIStore.reset(p.FRIEND),this.TUIStore.reset(p.CUSTOM),console.log("TUIChatEngine.resetStore ok.")}initService(){this.TUIChat.init(),this.TUIConversation.init(),this.TUIUser.init(),this.initOptionalServices(),this.isInited=!0,console.log("TUIChatEngine.initService ok.")}initOptionalServices(){const t=e.VERSION.split(".");t[0]>3||3===t[0]&&t[1]>=3&&t[2]>0?(!0===this.chat.callExperimentalAPI("canIUseModule",[ie])&&this.TUIGroup.init(),!0===this.chat.callExperimentalAPI("canIUseModule",[re])&&this.TUIFriend.init()):(this.TUIGroup.init(),this.TUIFriend.init())}createChat(o){const{chat:u}=o,g=c(o,["chat"]);O(u)?(this.chat=e.create(Object.assign(Object.assign({},g),{scene:"chat-uikit-engine"})),this.chat.use(t),this.chat.use(s),this.chat.use(n),this.chat.use(i),this.chat.use(r),this.chat.use(a)):this.chat=u}loginChat(e){const{userID:t,userSig:s}=e;return new Promise(((e,n)=>{this.chat.login({userID:t,userSig:s}).then((t=>{console.log("TUIChatEngine.loginChat ok."),this.checkCommercialAbility(),t.data.repeatLogin&&this.chat.isReady()&&e(t),this.loginStatusPromise.set("login",{resolve:e,reject:n,imResponse:t})})).catch((e=>{n(e)}))}))}registerPlugin(e){const{useUploadPlugin:t=!1,useProfanityFilterPlugin:s=!1,TIMPush:n,pushConfig:i,TUIOfflinePush:r,offlinePushConfig:a}=e;!0===t&&this.chat.registerPlugin({"tim-upload-plugin":o}),!0===s&&this.chat.registerPlugin({"tim-profanity-filter-plugin":u}),!B||Y||O(n)||O(i)||this.chat.registerPlugin({"tim-push":n,pushConfig:i}),!B||Y||O(r)||O(a)||this.chat.registerPlugin({"tim-offline-push-plugin":r,offlinePushConfig:a})}onSDKReady(){if(this.loginStatusPromise.has("login")){const e=this.loginStatusPromise.get("login");e.resolve(e.imResponse),this.TUIUser.getUserProfile()}this.loginStatusPromise.delete("login")}onSDKNotReady(){if(this.loginStatusPromise.has("login")){this.loginStatusPromise.get("login").reject(new Error("sdk not ready"))}this.loginStatusPromise.delete("login"),this.resetStore()}checkCommercialAbility(){Object.keys(F).forEach((e=>{const t=F[e];this.chat.callExperimentalAPI("isCommercialAbilityEnabled",t).then((t=>{const{enabled:s=!1}=t.data;this.TUIStore.update(p.APP,e,s)}))}))}}class oe{constructor(){this.defaultStore={enabledMessageReadReceipt:!1,enabledEmojiPlugin:!1,enabledOnlineStatus:!1,enabledCustomerServicePlugin:!1,enabledTranslationPlugin:!1,enabledVoiceToText:!1,enableTyping:!0,enableConversationDraft:!0,isOfficial:!1,SDKVersion:"3.0.0",tasks:{sendMessage:!1,revokeMessage:!1,modifyNickName:!1,groupChat:!1,muteGroup:!1,dismissGroup:!1,call:!1,searchCloudMessage:!1,customerService:!1,translateTextMessage:!1}},this.store={enabledEmojiPlugin:!1,enabledMessageReadReceipt:!1,enabledOnlineStatus:!1,enabledCustomerServicePlugin:!1,enabledTranslationPlugin:!1,enabledVoiceToText:!1,enableTyping:!0,enableConversationDraft:!0,isOfficial:!1,SDKVersion:"3.0.0",tasks:{sendMessage:!1,revokeMessage:!1,modifyNickName:!1,groupChat:!1,muteGroup:!1,dismissGroup:!1,call:!1,searchCloudMessage:!1,customerService:!1,translateTextMessage:!1}}}update(e,t){this.store[e]=t}getData(e){return this.store[e]}reset(e=[]){this.store=Object.assign(Object.assign(Object.assign({},this.defaultStore),this.store),e.reduce(((e,t)=>Object.assign(Object.assign({},e),{[t]:this.defaultStore[t]})),{}))}}class ue{constructor(){this.defaultStore={userProfile:{},displayOnlineStatus:!1,displayMessageReadReceipt:!0,userStatusList:new Map,kickedOut:"",netStateChange:"",userBlacklist:[],targetLanguage:"zh"},this.store={userProfile:{},displayOnlineStatus:!1,displayMessageReadReceipt:!0,userStatusList:new Map,kickedOut:"",netStateChange:"",userBlacklist:[],targetLanguage:"zh"}}update(e,t){if("userStatusList"===e)this.updateUserStatusList(t);else this.store[e]=t}getData(e){return this.store[e]}reset(e=[]){this.store=Object.assign(Object.assign(Object.assign({},this.defaultStore),this.store),e.reduce(((e,t)=>Object.assign(Object.assign({},e),{[t]:this.defaultStore[t]})),{}))}updateUserStatusList(e){0!==e.length?e.forEach((e=>{const{userID:t,statusType:s=0,customStatus:n=""}=e;s===d.UNSUB_USER?this.store.userStatusList.delete(t):this.store.userStatusList.set(t,{statusType:s,customStatus:n})})):this.store.userStatusList.clear()}}class ce{getEngine(){return ae.getInstance()}}const ge=function(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(function(e){if("object"!=typeof e||null===e)return!1;const t=Object.getPrototypeOf(e);if(null===t)return!0;let s=t;for(;null!==Object.getPrototypeOf(s);)s=Object.getPrototypeOf(s);return t===s}(e)){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}return!1},le=["[图片]","[语音]","[视频]","[文件]","[位置]","[地理位置]","[动画表情]","[自定义消息]","[群提示消息]","[聊天记录]"];class he extends ce{constructor(e){super(),this.initProxy(e),this.isMuted=this.messageRemindType===this.getEngine().TYPES.MSG_REMIND_ACPT_NOT_NOTE||this.messageRemindType===this.getEngine().TYPES.MSG_REMIND_DISCARD,this.operationType=0,this._conversation=e}initProxy(e){Object.keys(e).forEach((t=>{_(t)||(this[t]=e[t])}))}updateProperties(e){Object.keys(e).forEach((t=>{_(t)||(this[t]=e[t])}))}updateOperationType(e){this.operationType=e}getConversation(){return this._conversation}deleteConversation(){return this.getEngine().TUIConversation.deleteConversation(this.conversationID)}pinConversation(){return this.getEngine().TUIConversation.pinConversation({conversationID:this.conversationID,isPinned:!this.isPinned})}muteConversation(){const e=this.getEngine(),t={messageRemindType:!0===this.isMuted?e.TYPES.MSG_REMIND_ACPT_AND_NOTE:e.TYPES.MSG_REMIND_ACPT_NOT_NOTE};if(this.type===e.TYPES.CONV_C2C){const s=this.conversationID.replace(e.TYPES.CONV_C2C,"");t.userIDList=[s]}else if(this.type===e.TYPES.CONV_GROUP){const s=this.conversationID.replace(e.TYPES.CONV_GROUP,"");t.groupID=s}return e.TUIConversation.muteConversation(t)}getAvatar(){var e,t,s,n,i,r;const a=this.getEngine();let o="";switch(this.type){case a.TYPES.CONV_C2C:o=D(null===(e=this.userProfile)||void 0===e?void 0:e.avatar)?null===(t=this.userProfile)||void 0===t?void 0:t.avatar:L;break;case a.TYPES.CONV_GROUP:o=D(null===(s=this.groupProfile)||void 0===s?void 0:s.avatar)?null===(n=this.groupProfile)||void 0===n?void 0:n.avatar:A;break;case a.TYPES.CONV_SYSTEM:o=D(null===(i=this.groupProfile)||void 0===i?void 0:i.avatar)?null===(r=this.groupProfile)||void 0===r?void 0:r.avatar:j}return o}getShowName(){var e,t,s,n;const i=this.getEngine();let r="";switch(this.type){case i.TYPES.CONV_C2C:r=this.remark||(null===(e=this.userProfile)||void 0===e?void 0:e.nick)||(null===(t=this.userProfile)||void 0===t?void 0:t.userID)||"";break;case i.TYPES.CONV_GROUP:r=(null===(s=this.groupProfile)||void 0===s?void 0:s.name)||(null===(n=this.groupProfile)||void 0===n?void 0:n.groupID)||"";break;case i.TYPES.CONV_SYSTEM:r=i.TUITranslate.t("系统通知")}return r}getGroupAtInfo(){const e=this.getEngine(),t=e.TUITranslate.t.bind(e.TUITranslate),s=[`[${t("TUIConversation.有人@我")}]`,`[${t("TUIConversation.@所有人")}]`,`[${t("TUIConversation.@所有人")}][${t("TUIConversation.有人@我")}]`];let n="";for(let e=0;e<this.groupAtInfoList.length;e++)this.groupAtInfoList[e].atTypeArray[0]&&this.unreadCount>0&&(n=s[this.groupAtInfoList[e].atTypeArray[0]-1]);return n}getLastMessage(e){return"time"===e?this.getLastMessageTime():"text"===e?this.getLastMessageText():(console.warn(`ConversationModel.getLastMessage key:${e} is invalid.`),null)}getLastMessageTime(){var e;const t=this.getEngine();let s="";return(null===(e=this.lastMessage)||void 0===e?void 0:e.lastTime)>0&&(s=function(e,t){const s=6e4,n=36e5,i=24*n,r=7*i,a=(new Date).getTime()-e;let o="";if(a<0)return o;const u=a/s,c=a/n,g=a/i,l=a/r;if(l>=1&&l<=4)o=` ${parseInt(`${l}`,10)} ${t("time.周")}${t("time.前")}`;else if(g>=1&&g<=6)o=` ${parseInt(`${g}`,10)} ${t("time.天")}${t("time.前")}`;else if(c>=1&&c<=23)o=` ${parseInt(`${c}`,10)} ${t("time.小时")}${t("time.前")}`;else if(u>=1&&u<=59)o=` ${parseInt(`${u}`,10)} ${t("time.分钟")}${t("time.前")}`;else if(a>=0&&a<=s)o=`${t("time.刚刚")}`;else{const t=new Date;t.setTime(e),o=`${t.getFullYear()}-${t.getMonth()+1<10?`0${t.getMonth()+1}`:t.getMonth()+1}-${t.getDate()<10?`0${t.getDate()}`:t.getDate()}`}return o}(1e3*this.lastMessage.lastTime,t.TUITranslate.t.bind(t.TUITranslate))),s}getLastMessageText(){var e;if(this.draftText){return P(this.draftText).abstract}const t=this.getEngine(),s=t.TUITranslate.t.bind(t.TUITranslate);if(4===this.operationType)return s("TUIConversation.您已被群管理员移出群聊");if(5===this.operationType)return s("TUIConversation.该群聊已被解散");if(8===this.operationType)return s("TUIConversation.您已退出该群聊");const n=this._conversation,{lastMessage:i}=this;let r="",a="";const o=n.unreadCount>0&&n.messageRemindType===t.TYPES.MSG_REMIND_ACPT_NOT_NOTE?`[${n.unreadCount>99?"99+":n.unreadCount}${s("TUIConversation.条")}]`:"";if(n.type===t.TYPES.CONV_GROUP)if(i.fromAccount===t.getMyUserID())r=s("TUIConversation.我");else{const e=i.fromAccount;r=t.TUIFriend.getFriendRemark([e])[e]||i.nameCard||i.nick||e}if(i.type===t.TYPES.MSG_TEXT)a=this.decodeTextMessage(i.payload.text);else if(i.type===t.TYPES.MSG_CUSTOM){const n=P(null===(e=null==i?void 0:i.payload)||void 0===e?void 0:e.data);if(1===(null==n?void 0:n.businessID))return a=t.TUIChat.messageHandler.handleCallKitSignaling(i),a;a=le.includes(i.messageForShow)?s(`TUIChat.${i.messageForShow}`):i.messageForShow}else a=le.includes(i.messageForShow)?s(`TUIChat.${i.messageForShow}`):i.messageForShow;return i.isRevoked&&(a=s("TUIChat.撤回了一条消息")),n.type===t.TYPES.CONV_GROUP&&i.type===t.TYPES.MSG_GRP_TIP?a:`${o}${r?`${r}:`:""}${a}`}decodeTextMessage(e){if(ge(e))return e;const t=/(\[.+?\])/g;let s=e;if(t.test(e)){const n=this.getEngine(),i=n.TUITranslate.t.bind(n.TUITranslate);s=e.replace(t,(e=>{const t=i(`Emoji.${e}`);return Y||!t||t.startsWith("Emoji.")?V[e]||e:t}))}return s}}class pe{constructor(){this.defaultStore={currentConversationID:"",totalUnreadCount:0,conversationList:[],currentConversation:null,operationTypeMap:new Map},this.store={currentConversationID:"",totalUnreadCount:0,conversationList:[],currentConversation:null,operationTypeMap:new Map}}update(e,t){switch(e){case"conversationList":this.updateConversationList(t);break;case"operationTypeMap":this.updateOperationTypeMap(t);break;default:this.store[e]=t}}getData(e){return this.store[e]}getModel(e){return this.store.conversationList.find((t=>t.conversationID===e))}reset(e=[]){this.store=Object.assign(Object.assign(Object.assign({},this.defaultStore),this.store),e.reduce(((e,t)=>Object.assign(Object.assign({},e),{[t]:this.defaultStore[t]})),{}))}updateConversationList(e){const t=[];e.forEach((e=>{let s=e;e instanceof he?s.updateProperties(e):s=new he(e);const n=this.getOperationType(e);s.updateOperationType(n),t.push(s)})),this.store.conversationList=t}updateOperationTypeMap(e){const{conversationID:t,operationType:s=0}=e;this.store.operationTypeMap.set(t,s)}getOperationType(e){const{conversationID:t}=e;return this.store.operationTypeMap.get(t)||0}}class de extends ce{constructor(e){super(),this.messageHandlers={[this.getEngine().TYPES.MSG_TEXT]:e=>this.getEngine().TUIChat.messageHandler.handleTextMessage(e),[this.getEngine().TYPES.MSG_FACE]:e=>this.getEngine().TUIChat.messageHandler.handleFaceMessage(e),[this.getEngine().TYPES.MSG_LOCATION]:e=>this.getEngine().TUIChat.messageHandler.handleLocationMessage(e),[this.getEngine().TYPES.MSG_IMAGE]:e=>this.getEngine().TUIChat.messageHandler.handleImageMessage(e),[this.getEngine().TYPES.MSG_AUDIO]:e=>this.getEngine().TUIChat.messageHandler.handleAudioMessage(e),[this.getEngine().TYPES.MSG_VIDEO]:e=>this.getEngine().TUIChat.messageHandler.handleVideoMessage(e),[this.getEngine().TYPES.MSG_FILE]:e=>this.getEngine().TUIChat.messageHandler.handleFileMessage(e),[this.getEngine().TYPES.MSG_CUSTOM]:e=>this.getEngine().TUIChat.messageHandler.handleCustomMessage(e),[this.getEngine().TYPES.MSG_MERGER]:e=>this.getEngine().TUIChat.messageHandler.handleMergeMessage(e),[this.getEngine().TYPES.MSG_GRP_TIP]:e=>this.getEngine().TUIChat.messageHandler.handleGroupTipsMessage(e)},this._message=e,this._signalingInfo=void 0,this.progress=0,this.reactionList=[],this.initProperties(e)}initProperties(e){Object.keys(e).forEach((t=>{_(t)||(this[t]=e[t])}))}updateProperties(e){this._message=e,Object.keys(e).forEach((t=>{_(t)||(this[t]=e[t])}))}getMessage(){return this._message}modifyMessage(e){return e.type&&this._message.type!==e.type&&!e.payload?Promise.reject({code:v.MISMATCH_TYPE_AND_PAYLOAD,message:S.MISMATCH_TYPE_AND_PAYLOAD}):(this._message.type=e.type||this._message.type,this._message.payload=e.payload||this._message.payload,this._message.cloudCustomData=e.cloudCustomData||this._message.cloudCustomData,this.getEngine().TUIChat.modifyMessage(this._message))}revokeMessage(){return this.getEngine().TUIChat.revokeMessage(this._message)}resendMessage(){return this.getEngine().TUIChat.resendMessage(this._message)}deleteMessage(){return this.getEngine().TUIChat.deleteMessage([this._message])}quoteMessage(){return this.getEngine().TUIChat.quoteMessage(this._message)}replyMessage(){return this.getEngine().TUIChat.replyMessage(this._message)}setMessageExtensions(e){return this.getEngine().TUIChat.setMessageExtensions(this._message,e)}getMessageExtensions(){return this.getEngine().TUIChat.getMessageExtensions(this._message)}deleteMessageExtensions(e){return this.getEngine().TUIChat.deleteMessageExtensions(this._message,e)}getSignalingInfo(){return this.type!==this.getEngine().TYPES.MSG_CUSTOM?null:O(this._signalingInfo)?(this._signalingInfo=this.getEngine().chat.getSignalingInfo(this._message),this._signalingInfo):this._signalingInfo}getMessageContent(){const e=this.messageHandlers[this.type];if(O(e))return{};if(this.type===this.getEngine().TYPES.MSG_GRP_TIP)return e(this._message);const t=this.getEngine().TUIFriend.getFriendRemark([this.from]);return Object.assign(Object.assign({},e(this._message)),{showName:t[this.from]||this.nameCard||this.nick||this.from})}sendForwardMessage(e){return this.getEngine().TUIChat.sendForwardMessage(e,[this._message])}}class fe{constructor(){this.defaultStore={messageList:[],isCompleted:!1,nextReqMessageID:"",quoteMessage:{},newMessageList:[],typingStatus:!1,messageSource:void 0,translateTextInfo:void 0,voiceToTextInfo:void 0,userInfo:{}},this.store={messageList:[],isCompleted:!1,nextReqMessageID:"",quoteMessage:{},newMessageList:[],typingStatus:!1,messageSource:void 0,translateTextInfo:void 0,voiceToTextInfo:void 0,userInfo:{}}}update(e,t){switch(e){case"messageList":this.updateMessageList(t);break;case"translateTextInfo":this.updateTranslateTextInfo(t);break;case"voiceToTextInfo":this.updateVoiceToTextInfo(t);break;default:this.store[e]=t}}getData(e){return this.store[e]}getModel(e){return this.store.messageList.find((t=>t.ID===e))}reset(e=[]){const t=e.filter((e=>!H.includes(e)));this.store=Object.assign(Object.assign(Object.assign({},this.defaultStore),this.store),null==t?void 0:t.reduce(((e,t)=>Object.assign(Object.assign({},e),{[t]:this.defaultStore[t]})),{}))}updateMessageList(e){const t=[];e.forEach((e=>{let s=e;e instanceof de||(s=this.getModel(e.ID),s?s.updateProperties(e):s=new de(e)),t.push(s)})),this.store.messageList=t}updateTranslateTextInfo(e){this.updateBykey("translateTextInfo",e)}updateVoiceToTextInfo(e){this.updateBykey("voiceToTextInfo",e)}updateBykey(e,t){const{conversationID:s,messageID:n,visible:i=!1}=t;this.store[e]||(this.store[e]=new Map),this.store[e].has(s)||this.store[e].set(s,[]);const r=this.store[e].get(s)||[];let a=!0;for(let e=0;e<r.length;e++)if(r[e].messageID===n){r[e].visible=i,a=!1;break}a&&r.push({messageID:n,visible:i}),this.store[e].set(s,r)}}class me{constructor(e){this.groupAttributes={},this.groupCounters={},this.initProxy(e)}initProxy(e){Object.keys(e).forEach((t=>{_(t)||(this[t]=e[t])}))}}class Ee{constructor(){this.defaultStore={currentGroupID:"",currentGroup:{},currentGroupAttributes:{},currentGroupCounters:{},currentGroupMemberList:[],groupList:[],groupSystemNoticeList:[],isCompleted:!1,offset:0},this.store={currentGroupID:"",currentGroup:void 0,currentGroupAttributes:{},currentGroupCounters:{},currentGroupMemberList:[],groupList:[],groupSystemNoticeList:[],isCompleted:!1,offset:0}}update(e,t){switch(e){case"groupList":this.updateGroupList(t);break;case"currentGroup":this.store.currentGroup=t instanceof me?t:new me(t);break;default:this.store[e]=t}}getData(e){if("groupSystemNoticeList"===e){const e=[...this.store.groupSystemNoticeList];return this.store.groupSystemNoticeList.length=0,e}return this.store[e]}reset(e=[]){this.store=Object.assign(Object.assign(Object.assign({},this.defaultStore),this.store),e.reduce(((e,t)=>Object.assign(Object.assign({},e),{[t]:this.defaultStore[t]})),{}))}updateGroupList(e){this.store.groupList=e.map((e=>e instanceof me?e:new me(e)))}}class ve{constructor(){this.store={}}update(e,t){this.store[e]=t}getData(e){return this.store[e]}reset(e=[]){0===e.length&&(this.store={}),this.store=Object.assign(Object.assign({},this.store),e.reduce(((e,t)=>Object.assign(Object.assign({},e),{[t]:void 0})),{}))}}class Te{constructor(){this.defaultStore={friendList:[],friendApplicationList:[],friendApplicationUnreadCount:0},this.store={friendList:[],friendApplicationList:[],friendApplicationUnreadCount:0}}update(e,t){this.store[e]=t}getData(e){return this.store[e]}reset(e=[]){this.store=Object.assign(Object.assign(Object.assign({},this.defaultStore),this.store),e.reduce(((e,t)=>Object.assign(Object.assign({},e),{[t]:this.defaultStore[t]})),{}))}}class Se{constructor(){this.defaultStore={searchMessagesResult:{resultList:[],hasMore:!1,cursor:"",params:void 0,totalCount:0},searchChatMessagesResult:{resultList:[],hasMore:!1,cursor:"",params:void 0,totalCount:0},searchUserResult:{resultList:[],hasMore:!1,cursor:"",params:void 0,totalCount:0},searchGroupResult:{resultList:[],hasMore:!1,cursor:"",params:void 0,totalCount:0},searchMessageParams:{},searchChatMessageParams:{},searchUserParams:{},searchGroupParams:{},error:null},this.store=this.defaultStore}update(e,t){this.store[e]=t}getData(e){return this.store[e]}reset(e=[]){this.store=Object.assign(Object.assign(Object.assign({},this.defaultStore),this.store),null==e?void 0:e.reduce(((e,t)=>Object.assign(Object.assign({},e),{[t]:this.defaultStore[t]})),{}))}}class Ie{constructor(){this.storeMap={[p.APP]:new oe,[p.USER]:new ue,[p.CONV]:new pe,[p.CHAT]:new fe,[p.GRP]:new Ee,[p.FRIEND]:new Te,[p.SEARCH]:new Se},this.task={}}static getInstance(){return Ie.instance||(Ie.instance=new Ie),Ie.instance}watch(e,t){this.task[e]||(this.task[e]={});const s=this.task[e];Object.keys(t).forEach((n=>{const i=t[n];s[n]||(s[n]=new Map),s[n].set(i,1),this.notifyOnWatch(e,n,i)}))}unwatch(e,t){if(!this.task[e])return;const s=this.task[e];Object.keys(t).forEach((e=>{var n;null===(n=s[e])||void 0===n||n.delete(t[e])}))}update(e,t,s){var n;e!==p.CUSTOM||this.storeMap[e]||(this.storeMap[e]=new ve),null===(n=this.storeMap[e])||void 0===n||n.update(t,s),this.notify(e,t)}getData(e,t){var s;return e!==p.CUSTOM||this.storeMap[e]||(this.storeMap[e]=new ve),null===(s=this.storeMap[e])||void 0===s?void 0:s.getData(t)}getConversationModel(e){var t;return null===(t=this.storeMap[p.CONV])||void 0===t?void 0:t.getModel(e)}getMessageModel(e){var t;return null===(t=this.storeMap[p.CHAT])||void 0===t?void 0:t.getModel(e)}reset(e,t=[],s=!1){if(e in this.storeMap){const n=this.storeMap[e];0===t.length&&(t=Object.keys(null==n?void 0:n.store)),n.reset(t),s&&t.forEach((t=>{this.notify(e,t)}))}}notifyOnWatch(e,t,s){const n=this.getData(e,t);$.indexOf(t)>-1&&0===n.length||s&&s.call(this,n)}notify(e,t){if(!this.task[e])return;const s=this.task[e];if(s[t]){const n=s[t],i=this.getData(e,t);for(const[e]of n.entries())e.call(this,i)}}}function ye(e){return ye="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},ye(e)}function be(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function Me(e){var t=function(e,t){if("object"!=ye(e)||!e)return e;var s=e[Symbol.toPrimitive];if(void 0!==s){var n=s.call(e,t||"default");if("object"!=ye(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==ye(t)?t:t+""}function Ue(e,t){for(var s=0;s<t.length;s++){var n=t[s];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,Me(n.key),n)}}function Ce(e,t,s){return t&&Ue(e.prototype,t),s&&Ue(e,s),Object.defineProperty(e,"prototype",{writable:!1}),e}function Oe(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function _e(e,t){return _e=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},_e(e,t)}function De(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&_e(e,t)}function Pe(e,t){if(t&&("object"==ye(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return Oe(e)}function Re(e){return Re=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},Re(e)}function Le(e,t,s){return(t=Me(t))in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}function Ae(e,t){(null==t||t>e.length)&&(t=e.length);for(var s=0,n=Array(t);s<t;s++)n[s]=e[s];return n}function je(e){return function(e){if(Array.isArray(e))return e}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||function(e,t){if(e){if("string"==typeof e)return Ae(e,t);var s={}.toString.call(e).slice(8,-1);return"Object"===s&&e.constructor&&(s=e.constructor.name),"Map"===s||"Set"===s?Array.from(e):"Arguments"===s||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s)?Ae(e,t):void 0}}(e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function ke(e,t){var s=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),s.push.apply(s,n)}return s}function Ne(e){for(var t=1;t<arguments.length;t++){var s=null!=arguments[t]?arguments[t]:{};t%2?ke(Object(s),!0).forEach((function(t){Le(e,t,s[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(s)):ke(Object(s)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(s,t))}))}return e}var Ge={type:"logger",log:function(e){this.output("log",e)},warn:function(e){this.output("warn",e)},error:function(e){this.output("error",e)},output:function(e,t){console&&console[e]&&console[e].apply(console,t)}},xe=new(function(){function e(t){var s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};be(this,e),this.init(t,s)}return Ce(e,[{key:"init",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.prefix=t.prefix||"i18next:",this.logger=e||Ge,this.options=t,this.debug=t.debug}},{key:"setDebug",value:function(e){this.debug=e}},{key:"log",value:function(){for(var e=arguments.length,t=new Array(e),s=0;s<e;s++)t[s]=arguments[s];return this.forward(t,"log","",!0)}},{key:"warn",value:function(){for(var e=arguments.length,t=new Array(e),s=0;s<e;s++)t[s]=arguments[s];return this.forward(t,"warn","",!0)}},{key:"error",value:function(){for(var e=arguments.length,t=new Array(e),s=0;s<e;s++)t[s]=arguments[s];return this.forward(t,"error","")}},{key:"deprecate",value:function(){for(var e=arguments.length,t=new Array(e),s=0;s<e;s++)t[s]=arguments[s];return this.forward(t,"warn","WARNING DEPRECATED: ",!0)}},{key:"forward",value:function(e,t,s,n){return n&&!this.debug?null:("string"==typeof e[0]&&(e[0]="".concat(s).concat(this.prefix," ").concat(e[0])),this.logger[t](e))}},{key:"create",value:function(t){return new e(this.logger,Ne(Ne({},{prefix:"".concat(this.prefix,":").concat(t,":")}),this.options))}},{key:"clone",value:function(t){return(t=t||this.options).prefix=t.prefix||this.prefix,new e(this.logger,t)}}]),e}()),we=function(){function e(){be(this,e),this.observers={}}return Ce(e,[{key:"on",value:function(e,t){var s=this;return e.split(" ").forEach((function(e){s.observers[e]=s.observers[e]||[],s.observers[e].push(t)})),this}},{key:"off",value:function(e,t){this.observers[e]&&(t?this.observers[e]=this.observers[e].filter((function(e){return e!==t})):delete this.observers[e])}},{key:"emit",value:function(e){for(var t=arguments.length,s=new Array(t>1?t-1:0),n=1;n<t;n++)s[n-1]=arguments[n];this.observers[e]&&[].concat(this.observers[e]).forEach((function(e){e.apply(void 0,s)}));this.observers["*"]&&[].concat(this.observers["*"]).forEach((function(t){t.apply(t,[e].concat(s))}))}}]),e}();function Ve(){var e,t,s=new Promise((function(s,n){e=s,t=n}));return s.resolve=e,s.reject=t,s}function Fe(e){return null==e?"":""+e}function $e(e,t,s){function n(e){return e&&e.indexOf("###")>-1?e.replace(/###/g,"."):e}function i(){return!e||"string"==typeof e}for(var r="string"!=typeof t?[].concat(t):t.split(".");r.length>1;){if(i())return{};var a=n(r.shift());!e[a]&&s&&(e[a]=new s),e=Object.prototype.hasOwnProperty.call(e,a)?e[a]:{}}return i()?{}:{obj:e,k:n(r.shift())}}function He(e,t,s){var n=$e(e,t,Object);n.obj[n.k]=s}function Ye(e,t){var s=$e(e,t),n=s.obj,i=s.k;if(n)return n[i]}function Be(e,t,s){var n=Ye(e,s);return void 0!==n?n:Ye(t,s)}function Ke(e,t,s){for(var n in t)"__proto__"!==n&&"constructor"!==n&&(n in e?"string"==typeof e[n]||e[n]instanceof String||"string"==typeof t[n]||t[n]instanceof String?s&&(e[n]=t[n]):Ke(e[n],t[n],s):e[n]=t[n]);return e}function qe(e){return e.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")}var ze={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;"};function Je(e){return"string"==typeof e?e.replace(/[&<>"'\/]/g,(function(e){return ze[e]})):e}var We="undefined"!=typeof window&&window.navigator&&void 0===window.navigator.userAgentData&&window.navigator.userAgent&&window.navigator.userAgent.indexOf("MSIE")>-1,Xe=[" ",",","?","!",";"];function Ze(e,t){var s=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),s.push.apply(s,n)}return s}function Qe(e){for(var t=1;t<arguments.length;t++){var s=null!=arguments[t]?arguments[t]:{};t%2?Ze(Object(s),!0).forEach((function(t){Le(e,t,s[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(s)):Ze(Object(s)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(s,t))}))}return e}function et(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var s,n=Re(e);if(t){var i=Re(this).constructor;s=Reflect.construct(n,arguments,i)}else s=n.apply(this,arguments);return Pe(this,s)}}function tt(e,t){var s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:".";if(e){if(e[t])return e[t];for(var n=t.split(s),i=e,r=0;r<n.length;++r){if(!i)return;if("string"==typeof i[n[r]]&&r+1<n.length)return;if(void 0===i[n[r]]){for(var a=2,o=n.slice(r,r+a).join(s),u=i[o];void 0===u&&n.length>r+a;)a++,u=i[o=n.slice(r,r+a).join(s)];if(void 0===u)return;if(null===u)return null;if(t.endsWith(o)){if("string"==typeof u)return u;if(o&&"string"==typeof u[o])return u[o]}var c=n.slice(r+a).join(s);return c?tt(u,c,s):void 0}i=i[n[r]]}return i}}var st=function(){De(t,we);var e=et(t);function t(s){var n,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{ns:["translation"],defaultNS:"translation"};return be(this,t),n=e.call(this),We&&we.call(Oe(n)),n.data=s||{},n.options=i,void 0===n.options.keySeparator&&(n.options.keySeparator="."),void 0===n.options.ignoreJSONStructure&&(n.options.ignoreJSONStructure=!0),n}return Ce(t,[{key:"addNamespaces",value:function(e){this.options.ns.indexOf(e)<0&&this.options.ns.push(e)}},{key:"removeNamespaces",value:function(e){var t=this.options.ns.indexOf(e);t>-1&&this.options.ns.splice(t,1)}},{key:"getResource",value:function(e,t,s){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},i=void 0!==n.keySeparator?n.keySeparator:this.options.keySeparator,r=void 0!==n.ignoreJSONStructure?n.ignoreJSONStructure:this.options.ignoreJSONStructure,a=[e,t];s&&"string"!=typeof s&&(a=a.concat(s)),s&&"string"==typeof s&&(a=a.concat(i?s.split(i):s)),e.indexOf(".")>-1&&(a=e.split("."));var o=Ye(this.data,a);return o||!r||"string"!=typeof s?o:tt(this.data&&this.data[e]&&this.data[e][t],s,i)}},{key:"addResource",value:function(e,t,s,n){var i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{silent:!1},r=this.options.keySeparator;void 0===r&&(r=".");var a=[e,t];s&&(a=a.concat(r?s.split(r):s)),e.indexOf(".")>-1&&(n=t,t=(a=e.split("."))[1]),this.addNamespaces(t),He(this.data,a,n),i.silent||this.emit("added",e,t,s,n)}},{key:"addResources",value:function(e,t,s){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{silent:!1};for(var i in s)"string"!=typeof s[i]&&"[object Array]"!==Object.prototype.toString.apply(s[i])||this.addResource(e,t,i,s[i],{silent:!0});n.silent||this.emit("added",e,t,s)}},{key:"addResourceBundle",value:function(e,t,s,n,i){var r=arguments.length>5&&void 0!==arguments[5]?arguments[5]:{silent:!1},a=[e,t];e.indexOf(".")>-1&&(n=s,s=t,t=(a=e.split("."))[1]),this.addNamespaces(t);var o=Ye(this.data,a)||{};n?Ke(o,s,i):o=Qe(Qe({},o),s),He(this.data,a,o),r.silent||this.emit("added",e,t,s)}},{key:"removeResourceBundle",value:function(e,t){this.hasResourceBundle(e,t)&&delete this.data[e][t],this.removeNamespaces(t),this.emit("removed",e,t)}},{key:"hasResourceBundle",value:function(e,t){return void 0!==this.getResource(e,t)}},{key:"getResourceBundle",value:function(e,t){return t||(t=this.options.defaultNS),"v1"===this.options.compatibilityAPI?Qe(Qe({},{}),this.getResource(e,t)):this.getResource(e,t)}},{key:"getDataByLanguage",value:function(e){return this.data[e]}},{key:"hasLanguageSomeTranslations",value:function(e){var t=this.getDataByLanguage(e);return!!(t&&Object.keys(t)||[]).find((function(e){return t[e]&&Object.keys(t[e]).length>0}))}},{key:"toJSON",value:function(){return this.data}}]),t}(),nt={processors:{},addPostProcessor:function(e){this.processors[e.name]=e},handle:function(e,t,s,n,i){var r=this;return e.forEach((function(e){r.processors[e]&&(t=r.processors[e].process(t,s,n,i))})),t}};function it(e,t){var s=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),s.push.apply(s,n)}return s}function rt(e){for(var t=1;t<arguments.length;t++){var s=null!=arguments[t]?arguments[t]:{};t%2?it(Object(s),!0).forEach((function(t){Le(e,t,s[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(s)):it(Object(s)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(s,t))}))}return e}function at(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var s,n=Re(e);if(t){var i=Re(this).constructor;s=Reflect.construct(n,arguments,i)}else s=n.apply(this,arguments);return Pe(this,s)}}var ot={},ut=function(){De(t,we);var e=at(t);function t(s){var n,i,r,a,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return be(this,t),n=e.call(this),We&&we.call(Oe(n)),i=["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],r=s,a=Oe(n),i.forEach((function(e){r[e]&&(a[e]=r[e])})),n.options=o,void 0===n.options.keySeparator&&(n.options.keySeparator="."),n.logger=xe.create("translator"),n}return Ce(t,[{key:"changeLanguage",value:function(e){e&&(this.language=e)}},{key:"exists",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{interpolation:{}};if(null==e)return!1;var s=this.resolve(e,t);return s&&void 0!==s.res}},{key:"extractFromKey",value:function(e,t){var s=void 0!==t.nsSeparator?t.nsSeparator:this.options.nsSeparator;void 0===s&&(s=":");var n=void 0!==t.keySeparator?t.keySeparator:this.options.keySeparator,i=t.ns||this.options.defaultNS||[],r=s&&e.indexOf(s)>-1,a=!(this.options.userDefinedKeySeparator||t.keySeparator||this.options.userDefinedNsSeparator||t.nsSeparator||function(e,t,s){t=t||"",s=s||"";var n=Xe.filter((function(e){return t.indexOf(e)<0&&s.indexOf(e)<0}));if(0===n.length)return!0;var i=new RegExp("(".concat(n.map((function(e){return"?"===e?"\\?":e})).join("|"),")")),r=!i.test(e);if(!r){var a=e.indexOf(s);a>0&&!i.test(e.substring(0,a))&&(r=!0)}return r}(e,s,n));if(r&&!a){var o=e.match(this.interpolator.nestingRegexp);if(o&&o.length>0)return{key:e,namespaces:i};var u=e.split(s);(s!==n||s===n&&this.options.ns.indexOf(u[0])>-1)&&(i=u.shift()),e=u.join(n)}return"string"==typeof i&&(i=[i]),{key:e,namespaces:i}}},{key:"translate",value:function(e,s,n){var i=this;if("object"!==ye(s)&&this.options.overloadTranslationOptionHandler&&(s=this.options.overloadTranslationOptionHandler(arguments)),s||(s={}),null==e)return"";Array.isArray(e)||(e=[String(e)]);var r=void 0!==s.returnDetails?s.returnDetails:this.options.returnDetails,a=void 0!==s.keySeparator?s.keySeparator:this.options.keySeparator,o=this.extractFromKey(e[e.length-1],s),u=o.key,c=o.namespaces,g=c[c.length-1],l=s.lng||this.language,h=s.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if(l&&"cimode"===l.toLowerCase()){if(h){var p=s.nsSeparator||this.options.nsSeparator;return r?{res:"".concat(g).concat(p).concat(u),usedKey:u,exactUsedKey:u,usedLng:l,usedNS:g}:"".concat(g).concat(p).concat(u)}return r?{res:u,usedKey:u,exactUsedKey:u,usedLng:l,usedNS:g}:u}var d=this.resolve(e,s),f=d&&d.res,m=d&&d.usedKey||u,E=d&&d.exactUsedKey||u,v=Object.prototype.toString.apply(f),T=void 0!==s.joinArrays?s.joinArrays:this.options.joinArrays,S=!this.i18nFormat||this.i18nFormat.handleAsObject;if(S&&f&&("string"!=typeof f&&"boolean"!=typeof f&&"number"!=typeof f)&&["[object Number]","[object Function]","[object RegExp]"].indexOf(v)<0&&("string"!=typeof T||"[object Array]"!==v)){if(!s.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");var I=this.options.returnedObjectHandler?this.options.returnedObjectHandler(m,f,rt(rt({},s),{},{ns:c})):"key '".concat(u," (").concat(this.language,")' returned an object instead of string.");return r?(d.res=I,d):I}if(a){var y="[object Array]"===v,b=y?[]:{},M=y?E:m;for(var U in f)if(Object.prototype.hasOwnProperty.call(f,U)){var C="".concat(M).concat(a).concat(U);b[U]=this.translate(C,rt(rt({},s),{joinArrays:!1,ns:c})),b[U]===C&&(b[U]=f[U])}f=b}}else if(S&&"string"==typeof T&&"[object Array]"===v)(f=f.join(T))&&(f=this.extendTranslation(f,e,s,n));else{var O=!1,_=!1,D=void 0!==s.count&&"string"!=typeof s.count,P=t.hasDefaultValue(s),R=D?this.pluralResolver.getSuffix(l,s.count,s):"",L=s["defaultValue".concat(R)]||s.defaultValue;!this.isValidLookup(f)&&P&&(O=!0,f=L),this.isValidLookup(f)||(_=!0,f=u);var A=(s.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&_?void 0:f,j=P&&L!==f&&this.options.updateMissing;if(_||O||j){if(this.logger.log(j?"updateKey":"missingKey",l,g,u,j?L:f),a){var k=this.resolve(u,rt(rt({},s),{},{keySeparator:!1}));k&&k.res&&this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.")}var N=[],G=this.languageUtils.getFallbackCodes(this.options.fallbackLng,s.lng||this.language);if("fallback"===this.options.saveMissingTo&&G&&G[0])for(var x=0;x<G.length;x++)N.push(G[x]);else"all"===this.options.saveMissingTo?N=this.languageUtils.toResolveHierarchy(s.lng||this.language):N.push(s.lng||this.language);var w=function(e,t,n){var r=P&&n!==f?n:A;i.options.missingKeyHandler?i.options.missingKeyHandler(e,g,t,r,j,s):i.backendConnector&&i.backendConnector.saveMissing&&i.backendConnector.saveMissing(e,g,t,r,j,s),i.emit("missingKey",e,g,t,f)};this.options.saveMissing&&(this.options.saveMissingPlurals&&D?N.forEach((function(e){i.pluralResolver.getSuffixes(e,s).forEach((function(t){w([e],u+t,s["defaultValue".concat(t)]||L)}))})):w(N,u,L))}f=this.extendTranslation(f,e,s,d,n),_&&f===u&&this.options.appendNamespaceToMissingKey&&(f="".concat(g,":").concat(u)),(_||O)&&this.options.parseMissingKeyHandler&&(f="v1"!==this.options.compatibilityAPI?this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?"".concat(g,":").concat(u):u,O?f:void 0):this.options.parseMissingKeyHandler(f))}return r?(d.res=f,d):f}},{key:"extendTranslation",value:function(e,t,s,n,i){var r=this;if(this.i18nFormat&&this.i18nFormat.parse)e=this.i18nFormat.parse(e,rt(rt({},this.options.interpolation.defaultVariables),s),n.usedLng,n.usedNS,n.usedKey,{resolved:n});else if(!s.skipInterpolation){s.interpolation&&this.interpolator.init(rt(rt({},s),{interpolation:rt(rt({},this.options.interpolation),s.interpolation)}));var a,o="string"==typeof e&&(s&&s.interpolation&&void 0!==s.interpolation.skipOnVariables?s.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables);if(o){var u=e.match(this.interpolator.nestingRegexp);a=u&&u.length}var c=s.replace&&"string"!=typeof s.replace?s.replace:s;if(this.options.interpolation.defaultVariables&&(c=rt(rt({},this.options.interpolation.defaultVariables),c)),e=this.interpolator.interpolate(e,c,s.lng||this.language,s),o){var g=e.match(this.interpolator.nestingRegexp);a<(g&&g.length)&&(s.nest=!1)}!1!==s.nest&&(e=this.interpolator.nest(e,(function(){for(var e=arguments.length,n=new Array(e),a=0;a<e;a++)n[a]=arguments[a];return i&&i[0]===n[0]&&!s.context?(r.logger.warn("It seems you are nesting recursively key: ".concat(n[0]," in key: ").concat(t[0])),null):r.translate.apply(r,n.concat([t]))}),s)),s.interpolation&&this.interpolator.reset()}var l=s.postProcess||this.options.postProcess,h="string"==typeof l?[l]:l;return null!=e&&h&&h.length&&!1!==s.applyPostProcessor&&(e=nt.handle(h,e,t,this.options&&this.options.postProcessPassResolved?rt({i18nResolved:n},s):s,this)),e}},{key:"resolve",value:function(e){var t,s,n,i,r,a=this,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return"string"==typeof e&&(e=[e]),e.forEach((function(e){if(!a.isValidLookup(t)){var u=a.extractFromKey(e,o),c=u.key;s=c;var g=u.namespaces;a.options.fallbackNS&&(g=g.concat(a.options.fallbackNS));var l=void 0!==o.count&&"string"!=typeof o.count,h=l&&!o.ordinal&&0===o.count&&a.pluralResolver.shouldUseIntlApi(),p=void 0!==o.context&&("string"==typeof o.context||"number"==typeof o.context)&&""!==o.context,d=o.lngs?o.lngs:a.languageUtils.toResolveHierarchy(o.lng||a.language,o.fallbackLng);g.forEach((function(e){a.isValidLookup(t)||(r=e,!ot["".concat(d[0],"-").concat(e)]&&a.utils&&a.utils.hasLoadedNamespace&&!a.utils.hasLoadedNamespace(r)&&(ot["".concat(d[0],"-").concat(e)]=!0,a.logger.warn('key "'.concat(s,'" for languages "').concat(d.join(", "),'" won\'t get resolved as namespace "').concat(r,'" was not yet loaded'),"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!")),d.forEach((function(s){if(!a.isValidLookup(t)){i=s;var r,u=[c];if(a.i18nFormat&&a.i18nFormat.addLookupKeys)a.i18nFormat.addLookupKeys(u,c,s,e,o);else{var g;l&&(g=a.pluralResolver.getSuffix(s,o.count,o));var d="".concat(a.options.pluralSeparator,"zero");if(l&&(u.push(c+g),h&&u.push(c+d)),p){var f="".concat(c).concat(a.options.contextSeparator).concat(o.context);u.push(f),l&&(u.push(f+g),h&&u.push(f+d))}}for(;r=u.pop();)a.isValidLookup(t)||(n=r,t=a.getResource(s,e,r,o))}})))}))}})),{res:t,usedKey:s,exactUsedKey:n,usedLng:i,usedNS:r}}},{key:"isValidLookup",value:function(e){return!(void 0===e||!this.options.returnNull&&null===e||!this.options.returnEmptyString&&""===e)}},{key:"getResource",value:function(e,t,s){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};return this.i18nFormat&&this.i18nFormat.getResource?this.i18nFormat.getResource(e,t,s,n):this.resourceStore.getResource(e,t,s,n)}}],[{key:"hasDefaultValue",value:function(e){var t="defaultValue";for(var s in e)if(Object.prototype.hasOwnProperty.call(e,s)&&t===s.substring(0,12)&&void 0!==e[s])return!0;return!1}}]),t}();function ct(e){return e.charAt(0).toUpperCase()+e.slice(1)}var gt=function(){function e(t){be(this,e),this.options=t,this.supportedLngs=this.options.supportedLngs||!1,this.logger=xe.create("languageUtils")}return Ce(e,[{key:"getScriptPartFromCode",value:function(e){if(!e||e.indexOf("-")<0)return null;var t=e.split("-");return 2===t.length?null:(t.pop(),"x"===t[t.length-1].toLowerCase()?null:this.formatLanguageCode(t.join("-")))}},{key:"getLanguagePartFromCode",value:function(e){if(!e||e.indexOf("-")<0)return e;var t=e.split("-");return this.formatLanguageCode(t[0])}},{key:"formatLanguageCode",value:function(e){if("string"==typeof e&&e.indexOf("-")>-1){var t=["hans","hant","latn","cyrl","cans","mong","arab"],s=e.split("-");return this.options.lowerCaseLng?s=s.map((function(e){return e.toLowerCase()})):2===s.length?(s[0]=s[0].toLowerCase(),s[1]=s[1].toUpperCase(),t.indexOf(s[1].toLowerCase())>-1&&(s[1]=ct(s[1].toLowerCase()))):3===s.length&&(s[0]=s[0].toLowerCase(),2===s[1].length&&(s[1]=s[1].toUpperCase()),"sgn"!==s[0]&&2===s[2].length&&(s[2]=s[2].toUpperCase()),t.indexOf(s[1].toLowerCase())>-1&&(s[1]=ct(s[1].toLowerCase())),t.indexOf(s[2].toLowerCase())>-1&&(s[2]=ct(s[2].toLowerCase()))),s.join("-")}return this.options.cleanCode||this.options.lowerCaseLng?e.toLowerCase():e}},{key:"isSupportedCode",value:function(e){return("languageOnly"===this.options.load||this.options.nonExplicitSupportedLngs)&&(e=this.getLanguagePartFromCode(e)),!this.supportedLngs||!this.supportedLngs.length||this.supportedLngs.indexOf(e)>-1}},{key:"getBestMatchFromCodes",value:function(e){var t,s=this;return e?(e.forEach((function(e){if(!t){var n=s.formatLanguageCode(e);s.options.supportedLngs&&!s.isSupportedCode(n)||(t=n)}})),!t&&this.options.supportedLngs&&e.forEach((function(e){if(!t){var n=s.getLanguagePartFromCode(e);if(s.isSupportedCode(n))return t=n;t=s.options.supportedLngs.find((function(e){if(0===e.indexOf(n))return e}))}})),t||(t=this.getFallbackCodes(this.options.fallbackLng)[0]),t):null}},{key:"getFallbackCodes",value:function(e,t){if(!e)return[];if("function"==typeof e&&(e=e(t)),"string"==typeof e&&(e=[e]),"[object Array]"===Object.prototype.toString.apply(e))return e;if(!t)return e.default||[];var s=e[t];return s||(s=e[this.getScriptPartFromCode(t)]),s||(s=e[this.formatLanguageCode(t)]),s||(s=e[this.getLanguagePartFromCode(t)]),s||(s=e.default),s||[]}},{key:"toResolveHierarchy",value:function(e,t){var s=this,n=this.getFallbackCodes(t||this.options.fallbackLng||[],e),i=[],r=function(e){e&&(s.isSupportedCode(e)?i.push(e):s.logger.warn("rejecting language code not found in supportedLngs: ".concat(e)))};return"string"==typeof e&&e.indexOf("-")>-1?("languageOnly"!==this.options.load&&r(this.formatLanguageCode(e)),"languageOnly"!==this.options.load&&"currentOnly"!==this.options.load&&r(this.getScriptPartFromCode(e)),"currentOnly"!==this.options.load&&r(this.getLanguagePartFromCode(e))):"string"==typeof e&&r(this.formatLanguageCode(e)),n.forEach((function(e){i.indexOf(e)<0&&r(s.formatLanguageCode(e))})),i}}]),e}(),lt=[{lngs:["ach","ak","am","arn","br","fil","gun","ln","mfe","mg","mi","oc","pt","pt-BR","tg","tl","ti","tr","uz","wa"],nr:[1,2],fc:1},{lngs:["af","an","ast","az","bg","bn","ca","da","de","dev","el","en","eo","es","et","eu","fi","fo","fur","fy","gl","gu","ha","hi","hu","hy","ia","it","kk","kn","ku","lb","mai","ml","mn","mr","nah","nap","nb","ne","nl","nn","no","nso","pa","pap","pms","ps","pt-PT","rm","sco","se","si","so","son","sq","sv","sw","ta","te","tk","ur","yo"],nr:[1,2],fc:2},{lngs:["ay","bo","cgg","fa","ht","id","ja","jbo","ka","km","ko","ky","lo","ms","sah","su","th","tt","ug","vi","wo","zh"],nr:[1],fc:3},{lngs:["be","bs","cnr","dz","hr","ru","sr","uk"],nr:[1,2,5],fc:4},{lngs:["ar"],nr:[0,1,2,3,11,100],fc:5},{lngs:["cs","sk"],nr:[1,2,5],fc:6},{lngs:["csb","pl"],nr:[1,2,5],fc:7},{lngs:["cy"],nr:[1,2,3,8],fc:8},{lngs:["fr"],nr:[1,2],fc:9},{lngs:["ga"],nr:[1,2,3,7,11],fc:10},{lngs:["gd"],nr:[1,2,3,20],fc:11},{lngs:["is"],nr:[1,2],fc:12},{lngs:["jv"],nr:[0,1],fc:13},{lngs:["kw"],nr:[1,2,3,4],fc:14},{lngs:["lt"],nr:[1,2,10],fc:15},{lngs:["lv"],nr:[1,2,0],fc:16},{lngs:["mk"],nr:[1,2],fc:17},{lngs:["mnk"],nr:[0,1,2],fc:18},{lngs:["mt"],nr:[1,2,11,20],fc:19},{lngs:["or"],nr:[2,1],fc:2},{lngs:["ro"],nr:[1,2,20],fc:20},{lngs:["sl"],nr:[5,1,2,3],fc:21},{lngs:["he","iw"],nr:[1,2,20,21],fc:22}],ht={1:function(e){return Number(e>1)},2:function(e){return Number(1!=e)},3:function(e){return 0},4:function(e){return Number(e%10==1&&e%100!=11?0:e%10>=2&&e%10<=4&&(e%100<10||e%100>=20)?1:2)},5:function(e){return Number(0==e?0:1==e?1:2==e?2:e%100>=3&&e%100<=10?3:e%100>=11?4:5)},6:function(e){return Number(1==e?0:e>=2&&e<=4?1:2)},7:function(e){return Number(1==e?0:e%10>=2&&e%10<=4&&(e%100<10||e%100>=20)?1:2)},8:function(e){return Number(1==e?0:2==e?1:8!=e&&11!=e?2:3)},9:function(e){return Number(e>=2)},10:function(e){return Number(1==e?0:2==e?1:e<7?2:e<11?3:4)},11:function(e){return Number(1==e||11==e?0:2==e||12==e?1:e>2&&e<20?2:3)},12:function(e){return Number(e%10!=1||e%100==11)},13:function(e){return Number(0!==e)},14:function(e){return Number(1==e?0:2==e?1:3==e?2:3)},15:function(e){return Number(e%10==1&&e%100!=11?0:e%10>=2&&(e%100<10||e%100>=20)?1:2)},16:function(e){return Number(e%10==1&&e%100!=11?0:0!==e?1:2)},17:function(e){return Number(1==e||e%10==1&&e%100!=11?0:1)},18:function(e){return Number(0==e?0:1==e?1:2)},19:function(e){return Number(1==e?0:0==e||e%100>1&&e%100<11?1:e%100>10&&e%100<20?2:3)},20:function(e){return Number(1==e?0:0==e||e%100>0&&e%100<20?1:2)},21:function(e){return Number(e%100==1?1:e%100==2?2:e%100==3||e%100==4?3:0)},22:function(e){return Number(1==e?0:2==e?1:(e<0||e>10)&&e%10==0?2:3)}},pt=["v1","v2","v3"],dt={zero:0,one:1,two:2,few:3,many:4,other:5};var ft=function(){function e(t){var s,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};be(this,e),this.languageUtils=t,this.options=n,this.logger=xe.create("pluralResolver"),this.options.compatibilityJSON&&"v4"!==this.options.compatibilityJSON||"undefined"!=typeof Intl&&Intl.PluralRules||(this.options.compatibilityJSON="v3",this.logger.error("Your environment seems not to be Intl API compatible, use an Intl.PluralRules polyfill. Will fallback to the compatibilityJSON v3 format handling.")),this.rules=(s={},lt.forEach((function(e){e.lngs.forEach((function(t){s[t]={numbers:e.nr,plurals:ht[e.fc]}}))})),s)}return Ce(e,[{key:"addRule",value:function(e,t){this.rules[e]=t}},{key:"getRule",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this.shouldUseIntlApi())try{return new Intl.PluralRules(e,{type:t.ordinal?"ordinal":"cardinal"})}catch(e){return}return this.rules[e]||this.rules[this.languageUtils.getLanguagePartFromCode(e)]}},{key:"needsPlural",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},s=this.getRule(e,t);return this.shouldUseIntlApi()?s&&s.resolvedOptions().pluralCategories.length>1:s&&s.numbers.length>1}},{key:"getPluralFormsOfKey",value:function(e,t){var s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return this.getSuffixes(e,s).map((function(e){return"".concat(t).concat(e)}))}},{key:"getSuffixes",value:function(e){var t=this,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=this.getRule(e,s);return n?this.shouldUseIntlApi()?n.resolvedOptions().pluralCategories.sort((function(e,t){return dt[e]-dt[t]})).map((function(e){return"".concat(t.options.prepend).concat(e)})):n.numbers.map((function(n){return t.getSuffix(e,n,s)})):[]}},{key:"getSuffix",value:function(e,t){var s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=this.getRule(e,s);return n?this.shouldUseIntlApi()?"".concat(this.options.prepend).concat(n.select(t)):this.getSuffixRetroCompatible(n,t):(this.logger.warn("no plural rule found for: ".concat(e)),"")}},{key:"getSuffixRetroCompatible",value:function(e,t){var s=this,n=e.noAbs?e.plurals(t):e.plurals(Math.abs(t)),i=e.numbers[n];this.options.simplifyPluralSuffix&&2===e.numbers.length&&1===e.numbers[0]&&(2===i?i="plural":1===i&&(i=""));var r=function(){return s.options.prepend&&i.toString()?s.options.prepend+i.toString():i.toString()};return"v1"===this.options.compatibilityJSON?1===i?"":"number"==typeof i?"_plural_".concat(i.toString()):r():"v2"===this.options.compatibilityJSON||this.options.simplifyPluralSuffix&&2===e.numbers.length&&1===e.numbers[0]?r():this.options.prepend&&n.toString()?this.options.prepend+n.toString():n.toString()}},{key:"shouldUseIntlApi",value:function(){return!pt.includes(this.options.compatibilityJSON)}}]),e}();function mt(e,t){var s=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),s.push.apply(s,n)}return s}function Et(e){for(var t=1;t<arguments.length;t++){var s=null!=arguments[t]?arguments[t]:{};t%2?mt(Object(s),!0).forEach((function(t){Le(e,t,s[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(s)):mt(Object(s)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(s,t))}))}return e}var vt=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};be(this,e),this.logger=xe.create("interpolator"),this.options=t,this.format=t.interpolation&&t.interpolation.format||function(e){return e},this.init(t)}return Ce(e,[{key:"init",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};e.interpolation||(e.interpolation={escapeValue:!0});var t=e.interpolation;this.escape=void 0!==t.escape?t.escape:Je,this.escapeValue=void 0===t.escapeValue||t.escapeValue,this.useRawValueToEscape=void 0!==t.useRawValueToEscape&&t.useRawValueToEscape,this.prefix=t.prefix?qe(t.prefix):t.prefixEscaped||"{{",this.suffix=t.suffix?qe(t.suffix):t.suffixEscaped||"}}",this.formatSeparator=t.formatSeparator?t.formatSeparator:t.formatSeparator||",",this.unescapePrefix=t.unescapeSuffix?"":t.unescapePrefix||"-",this.unescapeSuffix=this.unescapePrefix?"":t.unescapeSuffix||"",this.nestingPrefix=t.nestingPrefix?qe(t.nestingPrefix):t.nestingPrefixEscaped||qe("$t("),this.nestingSuffix=t.nestingSuffix?qe(t.nestingSuffix):t.nestingSuffixEscaped||qe(")"),this.nestingOptionsSeparator=t.nestingOptionsSeparator?t.nestingOptionsSeparator:t.nestingOptionsSeparator||",",this.maxReplaces=t.maxReplaces?t.maxReplaces:1e3,this.alwaysFormat=void 0!==t.alwaysFormat&&t.alwaysFormat,this.resetRegExp()}},{key:"reset",value:function(){this.options&&this.init(this.options)}},{key:"resetRegExp",value:function(){var e="".concat(this.prefix,"(.+?)").concat(this.suffix);this.regexp=new RegExp(e,"g");var t="".concat(this.prefix).concat(this.unescapePrefix,"(.+?)").concat(this.unescapeSuffix).concat(this.suffix);this.regexpUnescape=new RegExp(t,"g");var s="".concat(this.nestingPrefix,"(.+?)").concat(this.nestingSuffix);this.nestingRegexp=new RegExp(s,"g")}},{key:"interpolate",value:function(e,t,s,n){var i,r,a,o=this,u=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{};function c(e){return e.replace(/\$/g,"$$$$")}var g=function(e){if(e.indexOf(o.formatSeparator)<0){var i=Be(t,u,e);return o.alwaysFormat?o.format(i,void 0,s,Et(Et(Et({},n),t),{},{interpolationkey:e})):i}var r=e.split(o.formatSeparator),a=r.shift().trim(),c=r.join(o.formatSeparator).trim();return o.format(Be(t,u,a),c,s,Et(Et(Et({},n),t),{},{interpolationkey:a}))};this.resetRegExp();var l=n&&n.missingInterpolationHandler||this.options.missingInterpolationHandler,h=n&&n.interpolation&&void 0!==n.interpolation.skipOnVariables?n.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:function(e){return c(e)}},{regex:this.regexp,safeValue:function(e){return o.escapeValue?c(o.escape(e)):c(e)}}].forEach((function(t){for(a=0;i=t.regex.exec(e);){var s=i[1].trim();if(void 0===(r=g(s)))if("function"==typeof l){var u=l(e,i,n);r="string"==typeof u?u:""}else if(n&&Object.prototype.hasOwnProperty.call(n,s))r="";else{if(h){r=i[0];continue}o.logger.warn("missed to pass in variable ".concat(s," for interpolating ").concat(e)),r=""}else"string"==typeof r||o.useRawValueToEscape||(r=Fe(r));var c=t.safeValue(r);if(e=e.replace(i[0],c),h?(t.regex.lastIndex+=r.length,t.regex.lastIndex-=i[0].length):t.regex.lastIndex=0,++a>=o.maxReplaces)break}})),e}},{key:"nest",value:function(e,t){var s,n,i,r=this,a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};function o(e,t){var s=this.nestingOptionsSeparator;if(e.indexOf(s)<0)return e;var n=e.split(new RegExp("".concat(s,"[ ]*{"))),r="{".concat(n[1]);e=n[0];var a=(r=this.interpolate(r,i)).match(/'/g),o=r.match(/"/g);(a&&a.length%2==0&&!o||o.length%2!=0)&&(r=r.replace(/'/g,'"'));try{i=JSON.parse(r),t&&(i=Et(Et({},t),i))}catch(t){return this.logger.warn("failed parsing options string in nesting for key ".concat(e),t),"".concat(e).concat(s).concat(r)}return delete i.defaultValue,e}for(;s=this.nestingRegexp.exec(e);){var u=[];(i=(i=Et({},a)).replace&&"string"!=typeof i.replace?i.replace:i).applyPostProcessor=!1,delete i.defaultValue;var c=!1;if(-1!==s[0].indexOf(this.formatSeparator)&&!/{.*}/.test(s[1])){var g=s[1].split(this.formatSeparator).map((function(e){return e.trim()}));s[1]=g.shift(),u=g,c=!0}if((n=t(o.call(this,s[1].trim(),i),i))&&s[0]===e&&"string"!=typeof n)return n;"string"!=typeof n&&(n=Fe(n)),n||(this.logger.warn("missed to resolve ".concat(s[1]," for nesting ").concat(e)),n=""),c&&(n=u.reduce((function(e,t){return r.format(e,t,a.lng,Et(Et({},a),{},{interpolationkey:s[1].trim()}))}),n.trim())),e=e.replace(s[0],n),this.regexp.lastIndex=0}return e}}]),e}();function Tt(e,t){var s=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),s.push.apply(s,n)}return s}function St(e){for(var t=1;t<arguments.length;t++){var s=null!=arguments[t]?arguments[t]:{};t%2?Tt(Object(s),!0).forEach((function(t){Le(e,t,s[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(s)):Tt(Object(s)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(s,t))}))}return e}function It(e){var t={};return function(s,n,i){var r=n+JSON.stringify(i),a=t[r];return a||(a=e(n,i),t[r]=a),a(s)}}var yt=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};be(this,e),this.logger=xe.create("formatter"),this.options=t,this.formats={number:It((function(e,t){var s=new Intl.NumberFormat(e,St({},t));return function(e){return s.format(e)}})),currency:It((function(e,t){var s=new Intl.NumberFormat(e,St(St({},t),{},{style:"currency"}));return function(e){return s.format(e)}})),datetime:It((function(e,t){var s=new Intl.DateTimeFormat(e,St({},t));return function(e){return s.format(e)}})),relativetime:It((function(e,t){var s=new Intl.RelativeTimeFormat(e,St({},t));return function(e){return s.format(e,t.range||"day")}})),list:It((function(e,t){var s=new Intl.ListFormat(e,St({},t));return function(e){return s.format(e)}}))},this.init(t)}return Ce(e,[{key:"init",value:function(e){var t=(arguments.length>1&&void 0!==arguments[1]?arguments[1]:{interpolation:{}}).interpolation;this.formatSeparator=t.formatSeparator?t.formatSeparator:t.formatSeparator||","}},{key:"add",value:function(e,t){this.formats[e.toLowerCase().trim()]=t}},{key:"addCached",value:function(e,t){this.formats[e.toLowerCase().trim()]=It(t)}},{key:"format",value:function(e,t,s){var n=this,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};return t.split(this.formatSeparator).reduce((function(e,t){var r=function(e){var t=e.toLowerCase().trim(),s={};if(e.indexOf("(")>-1){var n=e.split("(");t=n[0].toLowerCase().trim();var i=n[1].substring(0,n[1].length-1);"currency"===t&&i.indexOf(":")<0?s.currency||(s.currency=i.trim()):"relativetime"===t&&i.indexOf(":")<0?s.range||(s.range=i.trim()):i.split(";").forEach((function(e){if(e){var t=je(e.split(":")),n=t[0],i=t.slice(1).join(":").trim().replace(/^'+|'+$/g,"");s[n.trim()]||(s[n.trim()]=i),"false"===i&&(s[n.trim()]=!1),"true"===i&&(s[n.trim()]=!0),isNaN(i)||(s[n.trim()]=parseInt(i,10))}}))}return{formatName:t,formatOptions:s}}(t),a=r.formatName,o=r.formatOptions;if(n.formats[a]){var u=e;try{var c=i&&i.formatParams&&i.formatParams[i.interpolationkey]||{},g=c.locale||c.lng||i.locale||i.lng||s;u=n.formats[a](e,g,St(St(St({},o),i),c))}catch(e){n.logger.warn(e)}return u}return n.logger.warn("there was no format function for ".concat(a)),e}),e)}}]),e}();function bt(e,t){var s=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),s.push.apply(s,n)}return s}function Mt(e){for(var t=1;t<arguments.length;t++){var s=null!=arguments[t]?arguments[t]:{};t%2?bt(Object(s),!0).forEach((function(t){Le(e,t,s[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(s)):bt(Object(s)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(s,t))}))}return e}function Ut(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var s,n=Re(e);if(t){var i=Re(this).constructor;s=Reflect.construct(n,arguments,i)}else s=n.apply(this,arguments);return Pe(this,s)}}var Ct=function(){De(t,we);var e=Ut(t);function t(s,n,i){var r,a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};return be(this,t),r=e.call(this),We&&we.call(Oe(r)),r.backend=s,r.store=n,r.services=i,r.languageUtils=i.languageUtils,r.options=a,r.logger=xe.create("backendConnector"),r.waitingReads=[],r.maxParallelReads=a.maxParallelReads||10,r.readingCalls=0,r.maxRetries=a.maxRetries>=0?a.maxRetries:5,r.retryTimeout=a.retryTimeout>=1?a.retryTimeout:350,r.state={},r.queue=[],r.backend&&r.backend.init&&r.backend.init(i,a.backend,a),r}return Ce(t,[{key:"queueLoad",value:function(e,t,s,n){var i=this,r={},a={},o={},u={};return e.forEach((function(e){var n=!0;t.forEach((function(t){var o="".concat(e,"|").concat(t);!s.reload&&i.store.hasResourceBundle(e,t)?i.state[o]=2:i.state[o]<0||(1===i.state[o]?void 0===a[o]&&(a[o]=!0):(i.state[o]=1,n=!1,void 0===a[o]&&(a[o]=!0),void 0===r[o]&&(r[o]=!0),void 0===u[t]&&(u[t]=!0)))})),n||(o[e]=!0)})),(Object.keys(r).length||Object.keys(a).length)&&this.queue.push({pending:a,pendingCount:Object.keys(a).length,loaded:{},errors:[],callback:n}),{toLoad:Object.keys(r),pending:Object.keys(a),toLoadLanguages:Object.keys(o),toLoadNamespaces:Object.keys(u)}}},{key:"loaded",value:function(e,t,s){var n=e.split("|"),i=n[0],r=n[1];t&&this.emit("failedLoading",i,r,t),s&&this.store.addResourceBundle(i,r,s),this.state[e]=t?-1:2;var a={};this.queue.forEach((function(s){var n,o,u,c,g,l;n=s.loaded,o=r,c=$e(n,[i],Object),g=c.obj,l=c.k,g[l]=g[l]||[],u&&(g[l]=g[l].concat(o)),u||g[l].push(o),function(e,t){void 0!==e.pending[t]&&(delete e.pending[t],e.pendingCount--)}(s,e),t&&s.errors.push(t),0!==s.pendingCount||s.done||(Object.keys(s.loaded).forEach((function(e){a[e]||(a[e]={});var t=s.loaded[e];t.length&&t.forEach((function(t){void 0===a[e][t]&&(a[e][t]=!0)}))})),s.done=!0,s.errors.length?s.callback(s.errors):s.callback())})),this.emit("loaded",a),this.queue=this.queue.filter((function(e){return!e.done}))}},{key:"read",value:function(e,t,s){var n=this,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:this.retryTimeout,a=arguments.length>5?arguments[5]:void 0;if(!e.length)return a(null,{});if(this.readingCalls>=this.maxParallelReads)this.waitingReads.push({lng:e,ns:t,fcName:s,tried:i,wait:r,callback:a});else{this.readingCalls++;var o=function(o,u){if(n.readingCalls--,n.waitingReads.length>0){var c=n.waitingReads.shift();n.read(c.lng,c.ns,c.fcName,c.tried,c.wait,c.callback)}o&&u&&i<n.maxRetries?setTimeout((function(){n.read.call(n,e,t,s,i+1,2*r,a)}),r):a(o,u)},u=this.backend[s].bind(this.backend);if(2!==u.length)return u(e,t,o);try{var c=u(e,t);c&&"function"==typeof c.then?c.then((function(e){return o(null,e)})).catch(o):o(null,c)}catch(e){o(e)}}}},{key:"prepareLoading",value:function(e,t){var s=this,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=arguments.length>3?arguments[3]:void 0;if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),i&&i();"string"==typeof e&&(e=this.languageUtils.toResolveHierarchy(e)),"string"==typeof t&&(t=[t]);var r=this.queueLoad(e,t,n,i);if(!r.toLoad.length)return r.pending.length||i(),null;r.toLoad.forEach((function(e){s.loadOne(e)}))}},{key:"load",value:function(e,t,s){this.prepareLoading(e,t,{},s)}},{key:"reload",value:function(e,t,s){this.prepareLoading(e,t,{reload:!0},s)}},{key:"loadOne",value:function(e){var t=this,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",n=e.split("|"),i=n[0],r=n[1];this.read(i,r,"read",void 0,void 0,(function(n,a){n&&t.logger.warn("".concat(s,"loading namespace ").concat(r," for language ").concat(i," failed"),n),!n&&a&&t.logger.log("".concat(s,"loaded namespace ").concat(r," for language ").concat(i),a),t.loaded(e,n,a)}))}},{key:"saveMissing",value:function(e,t,s,n,i){var r=arguments.length>5&&void 0!==arguments[5]?arguments[5]:{},a=arguments.length>6&&void 0!==arguments[6]?arguments[6]:function(){};if(this.services.utils&&this.services.utils.hasLoadedNamespace&&!this.services.utils.hasLoadedNamespace(t))this.logger.warn('did not save key "'.concat(s,'" as the namespace "').concat(t,'" was not yet loaded'),"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");else if(null!=s&&""!==s){if(this.backend&&this.backend.create){var o=Mt(Mt({},r),{},{isUpdate:i}),u=this.backend.create.bind(this.backend);if(u.length<6)try{var c;(c=5===u.length?u(e,t,s,n,o):u(e,t,s,n))&&"function"==typeof c.then?c.then((function(e){return a(null,e)})).catch(a):a(null,c)}catch(e){a(e)}else u(e,t,s,n,a,o)}e&&e[0]&&this.store.addResource(e[0],t,s,n)}}}]),t}();function Ot(){return{debug:!1,initImmediate:!0,ns:["translation"],defaultNS:["translation"],fallbackLng:["dev"],fallbackNS:!1,supportedLngs:!1,nonExplicitSupportedLngs:!1,load:"all",preload:!1,simplifyPluralSuffix:!0,keySeparator:".",nsSeparator:":",pluralSeparator:"_",contextSeparator:"_",partialBundledLanguages:!1,saveMissing:!1,updateMissing:!1,saveMissingTo:"fallback",saveMissingPlurals:!0,missingKeyHandler:!1,missingInterpolationHandler:!1,postProcess:!1,postProcessPassResolved:!1,returnNull:!0,returnEmptyString:!0,returnObjects:!1,joinArrays:!1,returnedObjectHandler:!1,parseMissingKeyHandler:!1,appendNamespaceToMissingKey:!1,appendNamespaceToCIMode:!1,overloadTranslationOptionHandler:function(e){var t={};if("object"===ye(e[1])&&(t=e[1]),"string"==typeof e[1]&&(t.defaultValue=e[1]),"string"==typeof e[2]&&(t.tDescription=e[2]),"object"===ye(e[2])||"object"===ye(e[3])){var s=e[3]||e[2];Object.keys(s).forEach((function(e){t[e]=s[e]}))}return t},interpolation:{escapeValue:!0,format:function(e,t,s,n){return e},prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!0}}}function _t(e){return"string"==typeof e.ns&&(e.ns=[e.ns]),"string"==typeof e.fallbackLng&&(e.fallbackLng=[e.fallbackLng]),"string"==typeof e.fallbackNS&&(e.fallbackNS=[e.fallbackNS]),e.supportedLngs&&e.supportedLngs.indexOf("cimode")<0&&(e.supportedLngs=e.supportedLngs.concat(["cimode"])),e}function Dt(e,t){var s=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),s.push.apply(s,n)}return s}function Pt(e){for(var t=1;t<arguments.length;t++){var s=null!=arguments[t]?arguments[t]:{};t%2?Dt(Object(s),!0).forEach((function(t){Le(e,t,s[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(s)):Dt(Object(s)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(s,t))}))}return e}function Rt(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var s,n=Re(e);if(t){var i=Re(this).constructor;s=Reflect.construct(n,arguments,i)}else s=n.apply(this,arguments);return Pe(this,s)}}function Lt(){}var At=function(){De(t,we);var e=Rt(t);function t(){var s,n,i=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=arguments.length>1?arguments[1]:void 0;if(be(this,t),s=e.call(this),We&&we.call(Oe(s)),s.options=_t(i),s.services={},s.logger=xe,s.modules={external:[]},n=Oe(s),Object.getOwnPropertyNames(Object.getPrototypeOf(n)).forEach((function(e){"function"==typeof n[e]&&(n[e]=n[e].bind(n))})),r&&!s.isInitialized&&!i.isClone){if(!s.options.initImmediate)return s.init(i,r),Pe(s,Oe(s));setTimeout((function(){s.init(i,r)}),0)}return s}return Ce(t,[{key:"init",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},s=arguments.length>1?arguments[1]:void 0;"function"==typeof t&&(s=t,t={}),!t.defaultNS&&!1!==t.defaultNS&&t.ns&&("string"==typeof t.ns?t.defaultNS=t.ns:t.ns.indexOf("translation")<0&&(t.defaultNS=t.ns[0]));var n=Ot();function i(e){return e?"function"==typeof e?new e:e:null}if(this.options=Pt(Pt(Pt({},n),this.options),_t(t)),"v1"!==this.options.compatibilityAPI&&(this.options.interpolation=Pt(Pt({},n.interpolation),this.options.interpolation)),void 0!==t.keySeparator&&(this.options.userDefinedKeySeparator=t.keySeparator),void 0!==t.nsSeparator&&(this.options.userDefinedNsSeparator=t.nsSeparator),!this.options.isClone){var r;this.modules.logger?xe.init(i(this.modules.logger),this.options):xe.init(null,this.options),this.modules.formatter?r=this.modules.formatter:"undefined"!=typeof Intl&&(r=yt);var a=new gt(this.options);this.store=new st(this.options.resources,this.options);var o=this.services;o.logger=xe,o.resourceStore=this.store,o.languageUtils=a,o.pluralResolver=new ft(a,{prepend:this.options.pluralSeparator,compatibilityJSON:this.options.compatibilityJSON,simplifyPluralSuffix:this.options.simplifyPluralSuffix}),!r||this.options.interpolation.format&&this.options.interpolation.format!==n.interpolation.format||(o.formatter=i(r),o.formatter.init(o,this.options),this.options.interpolation.format=o.formatter.format.bind(o.formatter)),o.interpolator=new vt(this.options),o.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},o.backendConnector=new Ct(i(this.modules.backend),o.resourceStore,o,this.options),o.backendConnector.on("*",(function(t){for(var s=arguments.length,n=new Array(s>1?s-1:0),i=1;i<s;i++)n[i-1]=arguments[i];e.emit.apply(e,[t].concat(n))})),this.modules.languageDetector&&(o.languageDetector=i(this.modules.languageDetector),o.languageDetector.init&&o.languageDetector.init(o,this.options.detection,this.options)),this.modules.i18nFormat&&(o.i18nFormat=i(this.modules.i18nFormat),o.i18nFormat.init&&o.i18nFormat.init(this)),this.translator=new ut(this.services,this.options),this.translator.on("*",(function(t){for(var s=arguments.length,n=new Array(s>1?s-1:0),i=1;i<s;i++)n[i-1]=arguments[i];e.emit.apply(e,[t].concat(n))})),this.modules.external.forEach((function(t){t.init&&t.init(e)}))}if(this.format=this.options.interpolation.format,s||(s=Lt),this.options.fallbackLng&&!this.services.languageDetector&&!this.options.lng){var u=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);u.length>0&&"dev"!==u[0]&&(this.options.lng=u[0])}this.services.languageDetector||this.options.lng||this.logger.warn("init: no languageDetector is used and no lng is defined");["getResource","hasResourceBundle","getResourceBundle","getDataByLanguage"].forEach((function(t){e[t]=function(){var s;return(s=e.store)[t].apply(s,arguments)}}));["addResource","addResources","addResourceBundle","removeResourceBundle"].forEach((function(t){e[t]=function(){var s;return(s=e.store)[t].apply(s,arguments),e}}));var c=Ve(),g=function(){var t=function(t,n){e.isInitialized&&!e.initializedStoreOnce&&e.logger.warn("init: i18next is already initialized. You should call init just once!"),e.isInitialized=!0,e.options.isClone||e.logger.log("initialized",e.options),e.emit("initialized",e.options),c.resolve(n),s(t,n)};if(e.languages&&"v1"!==e.options.compatibilityAPI&&!e.isInitialized)return t(null,e.t.bind(e));e.changeLanguage(e.options.lng,t)};return this.options.resources||!this.options.initImmediate?g():setTimeout(g,0),c}},{key:"loadResources",value:function(e){var t=this,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Lt,n="string"==typeof e?e:this.language;if("function"==typeof e&&(s=e),!this.options.resources||this.options.partialBundledLanguages){if(n&&"cimode"===n.toLowerCase())return s();var i=[],r=function(e){e&&t.services.languageUtils.toResolveHierarchy(e).forEach((function(e){i.indexOf(e)<0&&i.push(e)}))};if(n)r(n);else this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach((function(e){return r(e)}));this.options.preload&&this.options.preload.forEach((function(e){return r(e)})),this.services.backendConnector.load(i,this.options.ns,(function(e){e||t.resolvedLanguage||!t.language||t.setResolvedLanguage(t.language),s(e)}))}else s(null)}},{key:"reloadResources",value:function(e,t,s){var n=Ve();return e||(e=this.languages),t||(t=this.options.ns),s||(s=Lt),this.services.backendConnector.reload(e,t,(function(e){n.resolve(),s(e)})),n}},{key:"use",value:function(e){if(!e)throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");if(!e.type)throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");return"backend"===e.type&&(this.modules.backend=e),("logger"===e.type||e.log&&e.warn&&e.error)&&(this.modules.logger=e),"languageDetector"===e.type&&(this.modules.languageDetector=e),"i18nFormat"===e.type&&(this.modules.i18nFormat=e),"postProcessor"===e.type&&nt.addPostProcessor(e),"formatter"===e.type&&(this.modules.formatter=e),"3rdParty"===e.type&&this.modules.external.push(e),this}},{key:"setResolvedLanguage",value:function(e){if(e&&this.languages&&!(["cimode","dev"].indexOf(e)>-1))for(var t=0;t<this.languages.length;t++){var s=this.languages[t];if(!(["cimode","dev"].indexOf(s)>-1)&&this.store.hasLanguageSomeTranslations(s)){this.resolvedLanguage=s;break}}}},{key:"changeLanguage",value:function(e,t){var s=this;this.isLanguageChangingTo=e;var n=Ve();this.emit("languageChanging",e);var i=function(e){s.language=e,s.languages=s.services.languageUtils.toResolveHierarchy(e),s.resolvedLanguage=void 0,s.setResolvedLanguage(e)},r=function(r){e||r||!s.services.languageDetector||(r=[]);var a="string"==typeof r?r:s.services.languageUtils.getBestMatchFromCodes(r);a&&(s.language||i(a),s.translator.language||s.translator.changeLanguage(a),s.services.languageDetector&&s.services.languageDetector.cacheUserLanguage&&s.services.languageDetector.cacheUserLanguage(a)),s.loadResources(a,(function(e){!function(e,r){r?(i(r),s.translator.changeLanguage(r),s.isLanguageChangingTo=void 0,s.emit("languageChanged",r),s.logger.log("languageChanged",r)):s.isLanguageChangingTo=void 0,n.resolve((function(){return s.t.apply(s,arguments)})),t&&t(e,(function(){return s.t.apply(s,arguments)}))}(e,a)}))};return e||!this.services.languageDetector||this.services.languageDetector.async?!e&&this.services.languageDetector&&this.services.languageDetector.async?0===this.services.languageDetector.detect.length?this.services.languageDetector.detect().then(r):this.services.languageDetector.detect(r):r(e):r(this.services.languageDetector.detect()),n}},{key:"getFixedT",value:function(e,t,s){var n=this,i=function e(t,i){var r;if("object"!==ye(i)){for(var a=arguments.length,o=new Array(a>2?a-2:0),u=2;u<a;u++)o[u-2]=arguments[u];r=n.options.overloadTranslationOptionHandler([t,i].concat(o))}else r=Pt({},i);r.lng=r.lng||e.lng,r.lngs=r.lngs||e.lngs,r.ns=r.ns||e.ns,r.keyPrefix=r.keyPrefix||s||e.keyPrefix;var c,g=n.options.keySeparator||".";return c=r.keyPrefix&&Array.isArray(t)?t.map((function(e){return"".concat(r.keyPrefix).concat(g).concat(e)})):r.keyPrefix?"".concat(r.keyPrefix).concat(g).concat(t):t,n.t(c,r)};return"string"==typeof e?i.lng=e:i.lngs=e,i.ns=t,i.keyPrefix=s,i}},{key:"t",value:function(){var e;return this.translator&&(e=this.translator).translate.apply(e,arguments)}},{key:"exists",value:function(){var e;return this.translator&&(e=this.translator).exists.apply(e,arguments)}},{key:"setDefaultNamespace",value:function(e){this.options.defaultNS=e}},{key:"hasLoadedNamespace",value:function(e){var t=this,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!this.isInitialized)return this.logger.warn("hasLoadedNamespace: i18next was not initialized",this.languages),!1;if(!this.languages||!this.languages.length)return this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty",this.languages),!1;var n=this.resolvedLanguage||this.languages[0],i=!!this.options&&this.options.fallbackLng,r=this.languages[this.languages.length-1];if("cimode"===n.toLowerCase())return!0;var a=function(e,s){var n=t.services.backendConnector.state["".concat(e,"|").concat(s)];return-1===n||2===n};if(s.precheck){var o=s.precheck(this,a);if(void 0!==o)return o}return!!this.hasResourceBundle(n,e)||(!(this.services.backendConnector.backend&&(!this.options.resources||this.options.partialBundledLanguages))||!(!a(n,e)||i&&!a(r,e)))}},{key:"loadNamespaces",value:function(e,t){var s=this,n=Ve();return this.options.ns?("string"==typeof e&&(e=[e]),e.forEach((function(e){s.options.ns.indexOf(e)<0&&s.options.ns.push(e)})),this.loadResources((function(e){n.resolve(),t&&t(e)})),n):(t&&t(),Promise.resolve())}},{key:"loadLanguages",value:function(e,t){var s=Ve();"string"==typeof e&&(e=[e]);var n=this.options.preload||[],i=e.filter((function(e){return n.indexOf(e)<0}));return i.length?(this.options.preload=n.concat(i),this.loadResources((function(e){s.resolve(),t&&t(e)})),s):(t&&t(),Promise.resolve())}},{key:"dir",value:function(e){if(e||(e=this.resolvedLanguage||(this.languages&&this.languages.length>0?this.languages[0]:this.language)),!e)return"rtl";var t=this.services&&this.services.languageUtils||new gt(Ot());return["ar","shu","sqr","ssh","xaa","yhd","yud","aao","abh","abv","acm","acq","acw","acx","acy","adf","ads","aeb","aec","afb","ajp","apc","apd","arb","arq","ars","ary","arz","auz","avl","ayh","ayl","ayn","ayp","bbz","pga","he","iw","ps","pbt","pbu","pst","prp","prd","ug","ur","ydd","yds","yih","ji","yi","hbo","men","xmn","fa","jpr","peo","pes","prs","dv","sam","ckb"].indexOf(t.getLanguagePartFromCode(e))>-1||e.toLowerCase().indexOf("-arab")>1?"rtl":"ltr"}},{key:"cloneInstance",value:function(){var e=this,s=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Lt,i=Pt(Pt(Pt({},this.options),s),{isClone:!0}),r=new t(i);void 0===s.debug&&void 0===s.prefix||(r.logger=r.logger.clone(s));return["store","services","language"].forEach((function(t){r[t]=e[t]})),r.services=Pt({},this.services),r.services.utils={hasLoadedNamespace:r.hasLoadedNamespace.bind(r)},r.translator=new ut(r.services,r.options),r.translator.on("*",(function(e){for(var t=arguments.length,s=new Array(t>1?t-1:0),n=1;n<t;n++)s[n-1]=arguments[n];r.emit.apply(r,[e].concat(s))})),r.init(i,n),r.translator.options=r.options,r.translator.backendConnector.services.utils={hasLoadedNamespace:r.hasLoadedNamespace.bind(r)},r}},{key:"toJSON",value:function(){return{options:this.options,store:this.store,language:this.language,languages:this.languages,resolvedLanguage:this.resolvedLanguage}}}]),t}();Le(At,"createInstance",(function(){return new At(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},arguments.length>1?arguments[1]:void 0)}));var jt,kt,Nt,Gt=At.createInstance();Gt.createInstance=At.createInstance,Gt.createInstance,Gt.dir,Gt.init,Gt.loadResources,Gt.reloadResources,Gt.use,Gt.changeLanguage,Gt.getFixedT,Gt.t,Gt.exists,Gt.setDefaultNamespace,Gt.hasLoadedNamespace,Gt.loadNamespaces,Gt.loadLanguages;class xt extends ce{constructor(){super(),this.languages=null,this.keyMap={}}static getInstance(){return xt.instance||(xt.instance=new xt),xt.instance}provideLanguages(e){var t;Y||(this.languages=e,(null===(t=e["zh-CN"])||void 0===t?void 0:t.Chat)&&this.setKeyMap(e["zh-CN"]),console.log("TUITranslateService.provideLanguages ok."))}useI18n(e){var t;if(Y)return;if(!this.languages)return void console.warn("TUITranslateService.useI18next not have messages.");const s={};for(const[e,t]of Object.entries(this.languages)){s["zh_cn"===e?"zh":e]={translation:t}}Gt.init({compatibilityJSON:"v3",lng:e||"zh",fallbackLng:"zh",detection:{order:["querystring","navigator"],caches:["localStorage","cookie"]},resources:s});let n=this.normalizeLanguageKey(e||"zh");null===(t=this.getEngine().TUIReport)||void 0===t||t.reportFeature(201,n)}changeLanguage(e){let t=this.normalizeLanguageKey(e);return this.getEngine().TUIReport.reportFeature(201,t),Gt.changeLanguage(e)}normalizeLanguageKey(e){return e.includes("en")?"en-us":e.includes("tw")?"zh-tw":e.includes("zh")||e.includes("cn")?"zh-cn":e.includes("ko")||e.includes("kr")?"ko-kr":e.includes("ja")||e.includes("jp")?"ja-jp":"other-"+e}t(e){if(!this.languages){let t=e;return!O(e)&&e.indexOf(".")>-1&&(t=e.split(".").pop()||""),t}const t=this.keyMap[e];return t?Gt.t(t):Gt.t(e)}setKeyMap(e,t){for(const s in e)if(Object.prototype.hasOwnProperty.call(e,s)){const n=t?`${t}.${s}`:s;if(e[s]&&"object"==typeof e[s]&&!Array.isArray(e[s])&&null!==e[s])this.setKeyMap(e[s],n);else{let n=t?`${t}.${e[s]}`:e[s];n=this.replaceKey(n),this.keyMap[n]=`${t}.${s}`}}}replaceKey(e){return e.startsWith("Chat")?e.replace("Chat","TUIChat"):e.startsWith("Conversation")?e.replace("Conversation","TUIConversation"):e.startsWith("Message")?e.replace("Message","message.tip"):e.startsWith("Call")?e.replace("Call","message.custom"):e}}class wt extends ce{constructor(){super(),this.serv="TUIConversationService"}static getInstance(){return wt.instance||(wt.instance=new wt),wt.instance}init(){const e=this.getEngine();e.eventCenter.addEvent(e.EVENT.CONVERSATION_LIST_UPDATED,this.onConversationListUpdated.bind(this)),e.eventCenter.addEvent(e.EVENT.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED,this.onTotalUnreadCountUpdated.bind(this)),e.eventCenter.addEvent(e.EVENT.MESSAGE_RECEIVED,this.onMessageReceived.bind(this)),this.getConversationInitData()}onConversationListUpdated(e){const t=this.filterSystemConversation(e);this.getEngine().TUIStore.update(p.CONV,"conversationList",t),this.updateCurrentConversation()}onTotalUnreadCountUpdated(e){this.getEngine().TUIStore.update(p.CONV,"totalUnreadCount",e)}onMessageReceived(e){const t=this.getEngine(),s=this.getEngine().TUIStore.getData(p.CONV,"conversationList");let n=!1;for(let i=0;i<e.length;i++){if(e[i].type!==t.TYPES.MSG_GRP_SYS_NOTICE)continue;const{operationType:r}=e[i].payload,a=`GROUP${e[i].to}`,o=4===r||5===r||8===r,u=2===r||6===r||7===r;if(o||u)for(let e=0;e<s.length;e++)if(s[e].type!==t.TYPES.CONV_C2C&&s[e].conversationID===a){if(o){this.getEngine().TUIStore.update(p.CONV,"operationTypeMap",{conversationID:a,operationType:r}),n=!0;break}if(u&&s[e].operationType>0){this.getEngine().TUIStore.update(p.CONV,"operationTypeMap",{conversationID:a,operationType:0}),n=!0;break}}}if(n){this.getEngine().TUIStore.update(p.CONV,"conversationList",s);const e=this.getEngine().TUIStore.getData(p.CONV,"currentConversationID")||"",t=this.findConversation(e);t&&this.getEngine().TUIStore.update(p.CONV,"currentConversation",t)}}getConversationInitData(){const e=this.getEngine();e.chat.isReady()&&e.chat.getConversationList().then((t=>{const{conversationList:s,isSyncCompleted:n}=t.data;if(console.log(`${this.serv}.init, getConversationList count:${s.length} isSyncCompleted:${n}`),s.length>0){this.onConversationListUpdated(s);const t=e.chat.getTotalUnreadMessageCount();this.onTotalUnreadCountUpdated(t)}}))}switchConversation(e){return g(this,void 0,void 0,(function*(){const t=`${this.serv}.switchConversation`,s=this.getEngine();if(!e)return s.TUIStore.reset(p.CHAT,["messageList","isCompleted","nextReqMessageID"]),s.TUIStore.update(p.CONV,"currentConversationID",""),s.TUIStore.update(p.CONV,"currentConversation",null),console.log(`${t} conversationID is empty, conversationID:${e}`),Promise.resolve({});if(!e.startsWith(s.TYPES.CONV_C2C)&&!e.startsWith(s.TYPES.CONV_GROUP))return console.warn(`${t} conversationID is invalid, conversationID:${e}`),Promise.reject({code:v.INVALID_CONV_ID,message:S.INVALID_CONV_ID});const n=s.TUIStore.getData(p.CONV,"currentConversationID");if(n&&n===e)return this.setMessageRead(n),console.warn(`${t} please check conversationID, conversationID:${e}`),Promise.resolve({code:v.CONV_ID_SAME,message:S.CONV_ID_SAME});const i=yield this.getConversationModel(e);return O(i)?(console.warn(`${t} target conversation is not exist, conversationID:${e}`),Promise.reject({code:v.CONV_NOT_EXIST,message:S.CONV_NOT_EXIST})):(n&&this.setMessageRead(n),e&&this.setMessageRead(e),s.TUIStore.reset(p.CHAT,["messageList","isCompleted","nextReqMessageID"]),s.TUIStore.update(p.CONV,"currentConversationID",e),s.TUIStore.update(p.CONV,"currentConversation",i),Promise.resolve(i))}))}getConversationModel(e){return g(this,void 0,void 0,(function*(){let t=this.findConversation(e);if(O(t))try{const s=yield this.getConversationProfile(e);s.data&&s.data.conversation&&(t=new he(s.data.conversation))}catch(e){t=void 0}return t}))}findConversation(e){let t;const s=this.getEngine().TUIStore.getData(p.CONV,"conversationList");for(let n=0;n<s.length;n++)if(s[n].conversationID===e){t=s[n];break}return t}updateCurrentConversation(){const e=this.getEngine(),t=e.TUIStore.getData(p.CONV,"currentConversationID"),s=this.findConversation(t);s&&e.TUIStore.update(p.CONV,"currentConversation",s)}getConversationList(){return this.getEngine().chat.getConversationList()}getConversationProfile(e){return this.getEngine().chat.getConversationProfile(e)}deleteConversation(e){return this.getEngine().chat.deleteConversation(e).then((t=>{const s=this.getEngine().TUIStore.getData(p.CONV,"currentConversationID");return console.log(`${this.serv}.deleteConversation conversationID:${e} currentConversationID:${s}`),e===s&&(this.getEngine().TUIStore.update(p.CONV,"currentConversationID",""),this.getEngine().TUIStore.update(p.CONV,"currentConversation",null)),t}))}pinConversation(e){return this.getEngine().chat.pinConversation(e)}muteConversation(e){return this.getEngine().chat.setMessageRemindType(e)}clearHistoryMessage(e){return this.getEngine().chat.clearHistoryMessage(e).then((e=>(this.getEngine().TUIStore.update(p.CHAT,"messageList",[]),this.getEngine().TUIStore.update(p.CHAT,"nextReqMessageID",""),this.getEngine().TUIStore.update(p.CHAT,"isCompleted",!0),e)))}setMessageRead(e){return this.getEngine().chat.setMessageRead({conversationID:e})}setConversationDraft(e){const{conversationID:t,draftInfo:s}=e;let n="";return s&&(n=JSON.stringify(s)),this.getEngine().chat.setConversationDraft({conversationID:t,draftText:n}).then((e=>{const{conversation:t}=e.data;this.updateConversation(t)}))}updateConversation(e){let t=!1;const s=this.getEngine().TUIStore.getData(p.CONV,"conversationList");for(let n=0;n<s.length;n++)if(s[n].conversationID===e.conversationID){s[n]=e,t=!0;break}t&&this.getEngine().TUIStore.update(p.CONV,"conversationList",s)}filterSystemConversation(e){return e.filter((e=>e.type!==this.getEngine().TYPES.CONV_SYSTEM))}}class Vt{constructor(e){this.TUIUserService=e}getEngine(){return this.TUIUserService.getEngine()}init(){this.getEngine().eventCenter.addEvent(this.getEngine().EVENT.PROFILE_UPDATED,this.onProfileUpdated.bind(this)),this.getEngine().eventCenter.addEvent(this.getEngine().EVENT.BLACKLIST_UPDATED,this.onBlacklistUpdated.bind(this)),this.getUserProfileInitData()}onProfileUpdated(e){const t=this.getEngine(),s=t.TUIStore.getData(p.USER,"userProfile");e.forEach((e=>{e.userID===s.userID&&t.TUIStore.update(p.USER,"userProfile",e)}))}onBlacklistUpdated(e){const t=this.getEngine();this.getBlacklistProfile(e).then((e=>{t.TUIStore.update(p.USER,"userBlacklist",e)}))}getUserProfileInitData(){const e=this.getEngine();e.chat.isReady()&&e.chat.getBlacklist().then((e=>{const t=e.data||[];console.log(`TUIUserProfileHandler.init, getBlacklist count:${t.length}`),t.length>0&&this.onBlacklistUpdated(t)}))}getBlacklistProfile(e){const t=[];let s=0;for(;s<e.length;)t.push(e.slice(s,s+=100));const n=[];t.forEach((e=>{n.push(this.TUIUserService.getUserProfile({userIDList:e}))}));const i=[];return Promise.all(n).then((e=>(e.forEach((e=>{const t=e.data.map((e=>{const{userID:t,nick:s,avatar:n}=e;return{userID:t,nick:s,avatar:n}}));i.push(...t)})),i)))}getUserProfile(e){const t=this.getEngine();return O(e)?t.chat.getMyProfile().then((e=>(t.TUIStore.update(p.USER,"userProfile",e.data),e))).catch((e=>Promise.reject(e))):t.chat.getUserProfile(e)}updateMyProfile(e){return this.getEngine().chat.updateMyProfile(e)}addToBlacklist(e){return this.getEngine().chat.addToBlacklist(e)}removeFromBlacklist(e){return this.getEngine().chat.removeFromBlacklist(e)}}function Ft(e,t,s=!0){!function(e,t){K?J.setStorageSync(e,t):Yt()&&localStorage.setItem(e,JSON.stringify(t))}(s?Ht(e):e,t)}function $t(e,t=!0){try{return function(e){if(K)return J.getStorageSync(e);if(Yt()){const t=localStorage.getItem(e);if("undefined"!==t)return JSON.parse(t)}return}(t?Ht(e):e)}catch(e){return void console.warn("Storage.getStorageItem error:",e)}}function Ht(e){return`chat_engine_${e}`}function Yt(){return navigator&&navigator.cookieEnabled&&localStorage}class Bt{constructor(e){this.TUIUserService=e}getEngine(){return this.TUIUserService.getEngine()}init(){const e=this.getEngine(),t=$t("displayOnlineStatus")||!1;e.TUIStore.update(p.USER,"displayOnlineStatus",t),e.eventCenter.addEvent(e.EVENT.USER_STATUS_UPDATED,this.onUserStatusUpdated.bind(this)),this.onConversationListUpdated()}onConversationListUpdated(){const e=this.getEngine();e.TUIStore.watch(p.CONV,{conversationList:()=>{const t=e.TUIStore.getData(p.APP,"enabledOnlineStatus"),s=e.TUIStore.getData(p.USER,"displayOnlineStatus");t&&s&&this.startToSubscribe()}})}onUserStatusUpdated(e){this.getEngine().TUIStore.update(p.USER,"userStatusList",e)}switchUserStatus(e){const t=this.getEngine(),{displayOnlineStatus:s=!1}=e;t.TUIStore.update(p.USER,"displayOnlineStatus",s),Ft("displayOnlineStatus",s);const n=t.TUIStore.getData(p.APP,"enabledOnlineStatus");n?!0===s?this.startToSubscribe():this.unsubscribeUserStatus():console.warn(`UserStatusHandler.switchUserStatus enabledOnlineStatus:${n} displayOnlineStatus:${s}`)}getUserStatus(e){const t=this.getEngine();return t.chat.getUserStatus(e).then((e=>{const{successUserList:s}=e.data;return s.length>0&&t.TUIStore.update(p.USER,"userStatusList",s),e})).catch((e=>Promise.reject(e)))}subscribeUserStatus(e){var t;const s=(null===(t=null==e?void 0:e.userIDList)||void 0===t?void 0:t.length)||0;return 0===s?(console.warn(`UserStatusHandler.subscribeUserStatus userID count:${s}`),Promise.resolve()):this.getEngine().chat.subscribeUserStatus(e)}unsubscribeUserStatus(e){const t=this.getEngine(),{userIDList:s=[]}=e||{};return t.chat.unsubscribeUserStatus({userIDList:s}).then((e=>{const{failureUserList:n}=e.data,i=[];return s.forEach((e=>{n.includes(e)||i.push({userID:e,statusType:d.UNSUB_USER})})),t.TUIStore.update(p.USER,"userStatusList",i),e})).catch((e=>Promise.reject(e)))}startToSubscribe(){const e=this.getEngine(),t=e.TUIStore.getData(p.CONV,"conversationList"),s=e.TUIStore.getData(p.USER,"userStatusList"),n=[];t.forEach((t=>{if(t.type===e.TYPES.CONV_C2C){const i=t.conversationID.replace(e.TYPES.CONV_C2C,"");s.has(i)||n.push(i)}})),0!==n.length&&e.chat.isReady()&&(this.subscribeUserStatus({userIDList:n}),this.getUserStatus({userIDList:n}))}}class Kt extends ce{constructor(){super(),this.userProfileHandler=new Vt(this),this.userStatusHandler=new Bt(this)}static getInstance(){return Kt.instance||(Kt.instance=new Kt),Kt.instance}init(){const e=this.getEngine();e.eventCenter.addEvent(e.EVENT.KICKED_OUT,this.onKickedOut.bind(this)),e.eventCenter.addEvent(e.EVENT.NET_STATE_CHANGE,this.onNetStateChange.bind(this)),this.userProfileHandler.init(),this.userStatusHandler.init(),this.initMessageReadReceipt()}onKickedOut(e){this.getEngine().TUIStore.update(p.USER,"kickedOut",e.type)}onNetStateChange(e){this.getEngine().TUIStore.update(p.USER,"netStateChange",e.state)}initMessageReadReceipt(){const e=$t("displayMessageReadReceipt")||!0;this.getEngine().TUIStore.update(p.USER,"displayMessageReadReceipt",e)}switchUserStatus(e){return this.userStatusHandler.switchUserStatus(e)}switchMessageReadStatus(e){this.getEngine().TUIStore.update(p.USER,"displayMessageReadReceipt",e),Ft("displayMessageReadReceipt",e)}getUserProfile(e){return this.userProfileHandler.getUserProfile(e)}updateMyProfile(e){return this.userProfileHandler.updateMyProfile(e)}addToBlacklist(e){return this.userProfileHandler.addToBlacklist(e)}removeFromBlacklist(e){return this.userProfileHandler.removeFromBlacklist(e)}getUserStatus(e){return this.userStatusHandler.getUserStatus(e)}subscribeUserStatus(e){return this.userStatusHandler.subscribeUserStatus(e)}unsubscribeUserStatus(e){return this.userStatusHandler.unsubscribeUserStatus(e)}}class qt{constructor(e){this.TUIChatService=e,this.userShowNameMap=new Map,this.requestedUserMap=new Map}getEngine(){return this.TUIChatService.getEngine()}t(e){return this.getEngine().TUITranslate.t(e)}handleTextMessage(e){return{text:this.decodeText(e.payload)}}handleFaceMessage(e){const t={name:"",url:"",type:""};return e.payload.data.indexOf("@custom")>-1?(t.name=e.payload.data,t.type="custom",t):(t.name=e.payload.data.indexOf("@2x")<0?`${e.payload.data}@2x`:e.payload.data,t.url=`${N}${t.name}.png`,t)}handleLocationMessage(e){const t={lon:"",lat:"",href:"",url:"",description:""};return t.lon=e.payload.longitude.toFixed(6),t.lat=e.payload.latitude.toFixed(6),t.href=`${G}pointx=${t.lon}&pointy=${t.lat}&name=${e.payload.description}`,t.url=`${x}center=${t.lat},${t.lon}&zoom=10&size=300*150&maptype=roadmap&markers=size:large|color:0xFFCCFF|label:k|${t.lat},${t.lon}&key=UBNBZ-PTP3P-TE7DB-LHRTI-Y4YLE-VWBBD`,t.description=e.payload.description,t}handleImageMessage(e){return{url:e.payload.imageInfoArray[0].url,width:e.payload.imageInfoArray[0].width,height:e.payload.imageInfoArray[0].height}}handleAudioMessage(e){return{url:e.payload.url,second:e.payload.second}}handleVideoMessage(e){return{url:e.payload.videoUrl,snapshotUrl:e.payload.snapshotUrl,snapshotWidth:e.payload.snapshotWidth,snapshotHeight:e.payload.snapshotHeight}}handleFileMessage(e){return{url:e.payload.fileUrl,name:e.payload.fileName,size:R(e.payload.fileSize)}}handleCustomMessage(e){var t;const s=this.handleCreateGroupCustomMessage(e);return{custom:this.handleCallKitSignaling(e)||s||(null===(t=null==e?void 0:e.payload)||void 0===t?void 0:t.extension)||`${this.t("TUIChat.[自定义消息]")}`,businessID:s?"group_create":""}}handleMergeMessage(e){return Object.assign({},e.payload)}handleGroupTipsMessage(e){var t,s,n,i,r,a;const o=this.getEngine(),u={text:""};let c=(null==e?void 0:e.nick)||(null===(s=null===(t=null==e?void 0:e.payload)||void 0===t?void 0:t.userIDList)||void 0===s?void 0:s.join(","));switch((null===(i=null===(n=null==e?void 0:e.payload)||void 0===n?void 0:n.memberList)||void 0===i?void 0:i.length)>0&&(c="",null===(a=null===(r=null==e?void 0:e.payload)||void 0===r?void 0:r.memberList)||void 0===a||a.map((e=>{const t=(null==e?void 0:e.nick)||(null==e?void 0:e.userID);return c+=`${this.substringByLength(t)},`,e})),c=null==c?void 0:c.slice(0,-1)),e.payload.operationType){case o.TYPES.GRP_TIP_MBR_JOIN:u.text=`${c} ${this.t("message.tip.加入群组")}`;break;case o.TYPES.GRP_TIP_MBR_QUIT:u.text=`${this.t("message.tip.群成员")}:${c} ${this.t("message.tip.退出群组")}`;break;case o.TYPES.GRP_TIP_MBR_KICKED_OUT:u.text=`${this.t("message.tip.群成员")}:${c} ${this.t("message.tip.被")}${this.t("message.tip.踢出群组")}`;break;case o.TYPES.GRP_TIP_MBR_SET_ADMIN:u.text=`${this.t("message.tip.群成员")}:${c} ${this.t("message.tip.成为管理员")}`;break;case o.TYPES.GRP_TIP_MBR_CANCELED_ADMIN:u.text=`${this.t("message.tip.群成员")}:${c} ${this.t("message.tip.被撤销管理员")}`;break;case o.TYPES.GRP_TIP_GRP_PROFILE_UPDATED:u.text=this.handleGroupProfileUpdated(e);break;case o.TYPES.GRP_TIP_MBR_PROFILE_UPDATED:for(const t of e.payload.memberList)t.muteTime>0?u.text=`${this.t("message.tip.群成员")}:${c} ${this.t("message.tip.被禁言")}`:u.text=`${this.t("message.tip.群成员")}:${c} ${this.t("message.tip.被取消禁言")}`;break;default:u.text=`[${this.t("message.tip.群提示消息")}]`}return u}handleGroupSystemMessage(e){const t=e.payload.groupProfile.name||e.payload.groupProfile.groupID,s={text:""};switch(e.payload.operationType){case 1:s.text=`${e.payload.operatorID} ${this.t("message.tip.申请加入群组")}:${t}`;break;case 2:s.text=`${this.t("message.tip.成功加入群组")}:${t}`;break;case 3:s.text=`${this.t("message.tip.申请加入群组")}:${t} ${this.t("message.tip.被拒绝")}`;break;case 4:s.text=`${this.t("message.tip.你被管理员")}${e.payload.operatorID} ${this.t("message.tip.踢出群组")}:${t}`;break;case 5:s.text=`${this.t("message.tip.群")}:${t} ${this.t("message.tip.被")} ${e.payload.operatorID} ${this.t("message.tip.解散")}`;break;case 6:s.text=`${e.payload.operatorID} ${this.t("message.tip.创建群")}:${t}`;break;case 7:case 12:s.text=`${e.payload.operatorID} ${this.t("message.tip.邀请你加群")}:${t}`;break;case 8:s.text=`${this.t("message.tip.你退出群组")}:${t}`;break;case 9:s.text=`${this.t("message.tip.你被")}${e.payload.operatorID} ${this.t("message.tip.设置为群")}:${t} ${this.t("message.tip.的管理员")}`;break;case 10:s.text=`${this.t("message.tip.你被")}${e.payload.operatorID} ${this.t("message.tip.撤销群")}:${t} ${this.t("message.tip.的管理员身份")}`;break;case 13:s.text=`${e.payload.operatorID} ${this.t("message.tip.同意加群")}:${t}`;break;case 14:s.text=`${e.payload.operatorID} ${this.t("message.tip.拒接加群")}:${t}`;break;case 255:s.text=`${this.t("message.tip.自定义群系统通知")}: ${e.payload.userDefinedField}`;break;default:s.text="未解析的群系统通知"}return s}handleCallKitSignaling(e){var t,s,n,i,r,a,o,u,c,g;const l=P(e.payload.data);if(1!==(null==l?void 0:l.businessID))return"";const h=P(null==l?void 0:l.data),p=e.fromAccount||e.from,d=this.getEngine().TUIFriend.getFriendRemark([p]),f=this.getEngine().getMyUserID();let m=d[p]||e.nameCard||e.nick||p;switch(m=this.substringByLength(m),null==l?void 0:l.actionType){case 1:return"audioCall"!==(null===(t=null==h?void 0:h.data)||void 0===t?void 0:t.cmd)&&"videoCall"!==(null===(s=null==h?void 0:h.data)||void 0===s?void 0:s.cmd)||!(null==l?void 0:l.groupID)?"hangup"===(null===(n=null==h?void 0:h.data)||void 0===n?void 0:n.cmd)?(null==l?void 0:l.groupID)?`${this.t("message.custom.通话结束")}`:`${this.t("message.custom.通话时长")}:${function(e){const t=e;let s,n,i,r="";return t>=3600?(s=parseInt(""+t/3600,10)<10?`0${parseInt(""+t/3600,10)}`:parseInt(""+t/3600,10),n=parseInt(""+t%60/60,10)<10?`0${parseInt(""+t%60/60,10)}`:parseInt(""+t%60/60,10),i=t%3600<10?"0"+t%3600:t%3600,i>60&&(n=parseInt(""+i/60,10)<10?`0${parseInt(""+i/60,10)}`:parseInt(""+i/60,10),i=i%60<10?"0"+i%60:i%60),r=`${s}:${n}:${i}`):t>=60&&t<3600?(n=parseInt(""+t/60,10)<10?`0${parseInt(""+t/60,10)}`:parseInt(""+t/60,10),i=t%60<10?"0"+t%60:t%60,r=`00:${n}:${i}`):t<60&&(i=t<10?`0${t}`:t,r=`00:00:${i}`),r}(null==h?void 0:h.call_end)}`:"switchToAudio"===(null===(i=null==h?void 0:h.data)||void 0===i?void 0:i.cmd)?`${this.t("message.custom.切换语音通话")}`:"switchToVideo"===(null===(r=null==h?void 0:h.data)||void 0===r?void 0:r.cmd)?`${this.t("message.custom.切换视频通话")}`:`${this.t("message.custom.发起通话")}`:`${m} ${this.t("message.custom.发起通话")}`;case 2:return(null==l?void 0:l.groupID)?`${m} ${this.t("message.custom.取消通话")}`:this.isOldUIKit("message.custom.已取消")?this.t("message.custom.取消通话"):(null==l?void 0:l.inviter)===f?this.t("message.custom.已取消"):this.t("message.custom.对方已取消");case 3:return"switchToAudio"===(null===(a=null==h?void 0:h.data)||void 0===a?void 0:a.cmd)?`${this.t("message.custom.切换语音通话")}`:"switchToVideo"===(null===(o=null==h?void 0:h.data)||void 0===o?void 0:o.cmd)?`${this.t("message.custom.切换视频通话")}`:(null==l?void 0:l.groupID)?`${m} ${this.t("message.custom.已接听")}`:this.t("message.custom.已接听");case 4:return(null==l?void 0:l.groupID)?`${m} ${this.t("message.custom.拒绝通话")}`:this.isOldUIKit("message.custom.已拒绝")?this.t("message.custom.拒绝通话"):"line_busy"===(null==h?void 0:h.line_busy)||"lineBusy"===(null==h?void 0:h.data.message)?(null==l?void 0:l.inviter)===f?this.t("message.custom.对方忙线中"):this.t("message.custom.忙线未接听"):(null==l?void 0:l.inviter)===f?this.t("message.custom.对方已拒绝"):this.t("message.custom.已拒绝");case 5:if("switchToAudio"===(null===(u=null==h?void 0:h.data)||void 0===u?void 0:u.cmd))return`${this.t("message.custom.切换语音通话")}`;if("switchToVideo"===(null===(c=null==h?void 0:h.data)||void 0===c?void 0:c.cmd))return`${this.t("message.custom.切换视频通话")}`;if(null==l?void 0:l.groupID){if(p===(null==l?void 0:l.inviter)){this.handleCallkitTimeoutSignaling(l.inviteeList);let e="";return null===(g=l.inviteeList)||void 0===g||g.forEach((t=>{const s=this.userShowNameMap.get(t)||t;e+=`${this.substringByLength(s)}、`})),e=e.substring(0,e.lastIndexOf("、")),`${e} ${this.t("message.custom.无应答")}`}return`${m} ${this.t("message.custom.无应答")}`}return this.isOldUIKit("message.custom.对方无应答")?this.t("message.custom.无应答"):(null==l?void 0:l.inviter)===f?this.t("message.custom.对方无应答"):this.t("message.custom.超时无应答");default:return""}}handleCreateGroupCustomMessage(e){let t;const s=P(e.payload.data);return"group_create"===(null==s?void 0:s.businessID)&&(t=`${s.opUser} ${s.content}`),t}decodeText(e){const t=[];let s=e.text,n=-1,i=-1;for(;""!==s;)switch(n=s.indexOf("["),i=s.indexOf("]"),n){case 0:if(-1===i)t.push({name:"text",text:s}),s="";else{const e=s.slice(0,i+1);e.indexOf("@custom")>-1?(t.push({name:"img",src:"",type:"custom",emojiKey:e}),s=s.substring(i+1)):w[e]?(t.push({name:"img",src:k+w[e],emojiKey:e}),s=s.substring(i+1)):(t.push({name:"text",text:"["}),s=s.slice(1))}break;case-1:t.push({name:"text",text:s}),s="";break;default:t.push({name:"text",text:s.slice(0,n)}),s=s.substring(n)}return t}handleGroupProfileUpdated(e){const{nick:t,payload:s}=e,{newGroupProfile:n,memberList:i,operatorID:r}=s;let a="";const o=t||r,u=Object.keys(n)[0];switch(u){case"muteAllMembers":a=n[u]?`${this.t("message.tip.管理员")} ${o} ${this.t("message.tip.开启全员禁言")}`:`${this.t("message.tip.管理员")} ${o} ${this.t("message.tip.取消全员禁言")}`;break;case"ownerID":a=`${i[0].nick||i[0].userID} ${this.t("message.tip.成为新的群主")}`;break;case"groupName":a=`${o} ${this.t("message.tip.修改群名为")} ${n[u]}`;break;case"notification":a=this.isOldUIKit("message.tip.把群公告修改为")?`${o} ${this.t("message.tip.发布新公告")}`:`${o} ${this.t("message.tip.把群公告修改为")} "${n[u]}"`}return a}handleCallkitTimeoutSignaling(e=[]){if(0===e.length)return;const t=this.getEngine().TUIFriend.getFriendRemark(e),s=[];e.forEach((e=>{const n=t[e];n?this.userShowNameMap.set(e,n):this.requestedUserMap.has(e)||(s.push(e),this.requestedUserMap.set(e,1))})),s.length>0&&this.getEngine().TUIUser.getUserProfile({userIDList:s}).then((e=>{(e.data||[]).forEach((e=>{const{userID:t,nick:s}=e,n=s||t;this.userShowNameMap.set(t,n)}))})).catch((()=>{}))}substringByLength(e,t=12){return e.length>t?`${e.slice(0,t)}...`:e}isOldUIKit(e){var t;const s=e.lastIndexOf("."),n=e.slice(0,s+1);return null===(t=this.t(e))||void 0===t?void 0:t.startsWith(n)}}class zt{constructor(e){this.TUIChatService=e,this.typingTo="",this.timer=null}getEngine(){return this.TUIChatService.getEngine()}clearTypingStatus(){this.getEngine().TUIStore.getData(p.CHAT,"typingStatus")&&this.getEngine().TUIStore.update(p.CHAT,"typingStatus",!1),this.timer&&clearTimeout(this.timer),this.timer=null}handleLastMessage(e){const t=this.getEngine(),s=t.TUIStore.getData(p.CHAT,"typingStatus");if(e.type===this.getEngine().TYPES.MSG_CUSTOM&&"in"===e.flow){const n=P(e.payload.data);if(n.businessID===f.BUSINESS_ID){const{typingStatus:e,userAction:i}=n;if(e===f.STATUS_START||i===f.ACTION_START_ID)return s?(this.timer&&clearTimeout(this.timer),this.timer=null):t.TUIStore.update(p.CHAT,"typingStatus",!0),this.timer=setTimeout((()=>{this.clearTypingStatus()}),3e4),t.TUIStore.getData(p.CHAT,"typingStatus");e!==f.STATUS_END&&i!==f.ACTION_END_ID||this.clearTypingStatus()}}}filterTypingMessage(e=[]){if(0===e.length)return[];return this.getEngine().TUIStore.getData(p.APP,"enableTyping")&&this.handleLastMessage(e[e.length-1]),e.filter((e=>{if(e.type===this.getEngine().TYPES.MSG_CUSTOM){return P(e.payload.data).businessID!==f.BUSINESS_ID}return!0}))}createTypingMessage(e=f.STATUS_END,t=""){const{BUSINESS_ID:s,STATUS_START:n,VERSION:i,ACTION_START_ID:r,ACTION_END_ID:a,ACTION_START:o,ACTION_END:u,NEED_TYPING:c}=f;return{to:t,conversationType:this.getEngine().TYPES.CONV_C2C,payload:{data:JSON.stringify({businessID:s,typingStatus:e,version:i,userAction:e===n?r:a,actionParam:e===n?o:u}),description:"",extension:""},cloudCustomData:JSON.stringify({messageFeature:{needTyping:c,version:i}})}}sendTyping(e=!1,t=""){if(e){this.typingTo=t;const e=this.createTypingMessage(f.STATUS_START,t);this.getEngine().TUIChat.sendCustomMessage(e,{onlineUserOnly:!0})}else this.sendTypingEnd()}sendTypingEnd(){if(this.typingTo){const e=this.createTypingMessage(f.STATUS_END,this.typingTo);this.getEngine().TUIChat.sendCustomMessage(e,{onlineUserOnly:!0})}this.typingTo=""}}class Jt{constructor(e){this.TUIChatService=e}getEngine(){return this.TUIChatService.getEngine()}init(){const e=this.getEngine();e.eventCenter.addEvent(e.EVENT.MESSAGE_READ_RECEIPT_RECEIVED,this.onMessageReadReceiptReceived.bind(this))}onMessageReadReceiptReceived(e){const t=this.getEngine(),s=t.TUIStore.getData(p.CONV,"currentConversationID"),n=[];e.forEach((e=>{const{messageID:i}=e,r=t.chat.findMessage(i);r&&s===r.conversationID&&n.push(r)})),n.length>0&&t.TUIChat.updateMessageList(n,"edit")}sendMessageReadReceipt(e){const t=[];return e.forEach((e=>{const s=e.getMessage();t.push(s)})),this.getEngine().chat.sendMessageReadReceipt(t)}getGroupMessageReadMemberList(e){const t=e.message.getMessage(),s=Object.assign(Object.assign({},e),{message:t});return this.getEngine().chat.getGroupMessageReadMemberList(s)}getMessageReadReceiptList(e){const t=this.getEngine(),s=t.TUIStore.getData(p.APP,"enabledMessageReadReceipt"),n=t.TUIStore.getData(p.USER,"displayMessageReadReceipt");!s||!n||0===e.length||e[0].conversationType!==t.TYPES.CONV_GROUP||t.chat.getMessageReadReceiptList(e).then((e=>{const{messageList:t}=e.data;this.TUIChatService.updateMessageList(t,"edit")})).catch((e=>{console.warn(`ReadReceiptHandler.getMessageReadReceiptList error:${e.message}`)}))}}class Wt extends ce{constructor(){super(),this.serv="TUIChatService",this.messageHandler=new qt(this),this.typingHandler=new zt(this),this.readReceiptHandler=new Jt(this),this.isSwitching=!0,this.delayGetHoppingFunction=void 0,this.hoppingConfigMap=new Map}static getInstance(){return Wt.instance||(Wt.instance=new Wt),Wt.instance}init(){const e=this.getEngine();e.eventCenter.addEvent(e.EVENT.MESSAGE_RECEIVED,this.onMessageReceived.bind(this)),e.eventCenter.addEvent(e.EVENT.MESSAGE_MODIFIED,this.onMessageModified.bind(this)),e.eventCenter.addEvent(e.EVENT.MESSAGE_REVOKED,this.onMessageRevoked.bind(this)),e.eventCenter.addEvent(e.EVENT.MESSAGE_READ_BY_PEER,this.onMessageReadByPeer.bind(this)),e.eventCenter.addEvent(e.EVENT.MESSAGE_REACTIONS_UPDATED,this.onMessageReactionsUpdated.bind(this)),this.onCurrentConversationIDUpdated(),this.onMessageSource(),this.readReceiptHandler.init()}onMessageReceived(e){this.updateMessageList(e,"received"),this.getEngine().TUIStore.update(p.CHAT,"newMessageList",e)}onMessageModified(e){this.updateMessageList(e,"edit")}onMessageRevoked(e){this.updateMessageList(e,"edit")}onMessageReadByPeer(e){this.updateMessageList(e,"edit")}onMessageReactionsUpdated(e){this.updateMessageReactionList([e])}onCurrentConversationIDUpdated(){const e=this.getEngine();e.TUIStore.watch(p.CONV,{currentConversationID:t=>{this.isSwitching=!0,this.delayGetHoppingFunction=void 0,this.hoppingConfigMap.clear(),e.TUIStore.reset(p.CHAT),this.typingHandler.clearTypingStatus(),this.typingHandler.sendTypingEnd(),ge(t)||this.getMessageList().finally((()=>{this.isSwitching=!1,this.delayGetHoppingFunction&&this.delayGetHoppingFunction()}))}})}onMessageSource(){const e=this.getEngine();e.TUIStore.watch(p.CHAT,{messageSource:t=>{const s=this.getStoreData(p.CONV,"currentConversationID");if(!s||t&&t.conversationID!==s)return;if(O(t))return this.hoppingConfigMap.clear(),e.TUIStore.update(p.CHAT,"messageList",[]),e.TUIStore.update(p.CHAT,"nextReqMessageID",""),e.TUIStore.update(p.CHAT,"isCompleted",!1),void this.getMessageList();const n=this.getStoreData(p.CHAT,"messageList");n&&n.find((e=>t&&e.ID===t.ID))||(this.isSwitching?this.delayGetHoppingFunction=this.getMessageListHoppingForDown:this.getMessageListHoppingForDown())}})}getMessageListHoppingForDown(){const e=this.getStoreData(p.CHAT,"messageList"),{conversationID:t,sequence:s,time:n,ID:i}=this.getStoreData(p.CHAT,"messageSource");if(e&&e.find((e=>i&&e.ID===i)))return;const r=this.getEngine();r.TUIStore.update(p.CHAT,"messageList",[]),r.TUIStore.update(p.CHAT,"nextReqMessageID",""),r.TUIStore.update(p.CHAT,"isCompleted",!1),this.getMessageListHopping({conversationID:t,sequence:s,time:n,direction:1})}getStoreData(e,t){return this.getEngine().TUIStore.getData(e,t)}sendMessage(e,t){this.updateMessageList([e],"send");const s=this.getEngine().chat.sendMessage(e,t);return this.getResponse(s)}getResponse(e,t=!0,s=!0){return e.then((e=>{const s=e.data.messageList?e.data.messageList:[e.data.message];return t&&this.updateMessageList(s,"edit"),e})).catch((e=>{var t;return s&&(null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.message)&&this.updateMessageList([e.data.message],"edit"),Promise.reject(e)}))}updateMessageList(e,t=""){if(this.getStoreData(p.CHAT,"messageSource")&&"unshift"!==t&&"edit"!==t)return;const s=this.getStoreData(p.CHAT,"messageList"),n=this.updateTargetMessageList(e,s,t);this.getEngine().TUIStore.update(p.CHAT,"messageList",n)}updateTargetMessageList(e,t,s=""){const n=this.getStoreData(p.CONV,"currentConversationID");let i=e.filter((e=>e.conversationID===n));if(i=this.handleC2CCallSignaling(i),!s||0===i.length)return t;const r=t||[];let a=[];if("send"===s||"push"===s){const e=this.getStoreData(p.CHAT,"userInfo");Object.keys(e).length>0&&this.updateLocalMessage(i,e)}switch(s){case"edit":for(const e of t){const t=i.find((t=>t.ID===e.ID));a.push(t||e)}break;case"resend":a=r.filter((e=>e.ID!==i[0].ID)).concat(i);break;case"send":a=r.concat(this.typingHandler.filterTypingMessage(i));break;case"push":a=r.concat(this.typingHandler.filterTypingMessage(i)),this.getEngine().chat.setMessageRead({conversationID:n});break;case"received":a=r.concat(this.typingHandler.filterTypingMessage(i)),a=this.sortMessageList(a),this.getEngine().chat.setMessageRead({conversationID:n});break;case"unshift":a=i.filter((e=>0===r.length||!r.find((t=>t.ID===e.ID)))),a.push(...r),a=this.sortMessageList(a)}return a}enterTypingState(){this.getStoreData(p.APP,"enableTyping")&&this.sendTyping(!0)}leaveTypingState(){this.getStoreData(p.APP,"enableTyping")&&this.sendTyping(!1)}sendTyping(e){const t=this.getEngine(),s=this.getStoreData(p.CONV,"currentConversationID");if(!s.startsWith(t.TYPES.CONV_C2C))return;const n=s.replace(t.TYPES.CONV_C2C,"");if(e){const e=this.getStoreData(p.CHAT,"messageList").filter((e=>"in"===e.flow));if(0===e.length)return;const t=1e3*e[e.length-1].time;if((new Date).getTime()-t>3e4)return}this.typingHandler.sendTyping(e,n)}quoteMessage(e){var t;return this.getEngine().TUIStore.update(p.CHAT,"quoteMessage",{message:e,type:"quote"}),null===(t=this.getEngine().TUIReport)||void 0===t||t.reportFeature(205),e}replyMessage(e){return this.getEngine().TUIStore.update(p.CHAT,"quoteMessage",{message:e,type:"reply"}),e}getCurrentConvInfo(){const{conversationID:e="",type:t}=this.getStoreData(p.CONV,"currentConversation")||{};return{to:e.replace(t,""),conversationType:t}}t(e){return this.getEngine().TUITranslate.t(e)||e}getMessageAbstractAndType(e){var t,s;const n=this.getEngine(),i={abstract:"",type:0};switch(e.type){case n.TYPES.MSG_TEXT:i.abstract=null===(t=null==e?void 0:e.payload)||void 0===t?void 0:t.text,i.type=1;break;case n.TYPES.MSG_CUSTOM:i.abstract="[自定义消息]",i.type=2;break;case n.TYPES.MSG_IMAGE:i.abstract="[图片]",i.type=3;break;case n.TYPES.MSG_AUDIO:i.abstract="[语音]",i.type=4;break;case n.TYPES.MSG_VIDEO:i.abstract="[视频]",i.type=5;break;case n.TYPES.MSG_FILE:i.abstract="[文件]",i.type=6;break;case n.TYPES.MSG_LOCATION:i.type=7;break;case n.TYPES.MSG_FACE:i.abstract="[表情]",i.type=8;break;case n.TYPES.MSG_GRP_TIP:i.type=9;break;case n.TYPES.MSG_MERGER:i.abstract=null===(s=null==e?void 0:e.payload)||void 0===s?void 0:s.title,i.type=10}return i}genMessageReply(e,t){if("reply"!==t&&"quote"!==t)return{};const{abstract:s,type:n}=this.getMessageAbstractAndType(e),i={messageAbstract:s,messageSender:e.nick||e.from,messageID:e.ID},r=Object.assign(Object.assign({},i),{messageType:n,messageTime:null==e?void 0:e.time,messageSequence:null==e?void 0:e.sequence,version:1});if("reply"===t&&(r.messageRootID=e.ID,e.cloudCustomData)){const t=P(e.cloudCustomData);t.messageReply&&t.messageReply.messageRootID&&(r.messageRootID=t.messageReply.messageRootID)}return{messageReply:r,messageReplyRoot:i}}getMessageInfo(e,t,s){const{messageReply:n,messageReplyRoot:i}=this.genMessageReply(t,s),r=e.cloudCustomData?P(e.cloudCustomData):{};let a;if(r.messageReply?r.messageReply=Object.assign(Object.assign({},n),r.messageReply):r.messageReply=n,"reply"===s){const{messageRootID:e}=n;a=this.getEngine().chat.findMessage(e);const t=(null==a?void 0:a.cloudCustomData)?P(a.cloudCustomData):{};t.messageReplies||(t.messageReplies={}),o=t.messageReplies.replies,("function"==typeof Array.isArray?Array.isArray(o):"array"===Object.prototype.toString.call(o).match(/^\[object (.*)\]$/)[1].toLowerCase())||(t.messageReplies.replies=[]),t.messageReplies.replies.push(i),a.cloudCustomData=JSON.stringify(t)}var o;return{cloudCustomData:JSON.stringify(r),rootMessage:a}}sendTextMessage(e,t){const s=this.getEngine(),{message:n,type:i}=this.getStoreData(p.CHAT,"quoteMessage");let r={cloudCustomData:e.cloudCustomData||"",rootMessage:void 0};n&&(r=this.getMessageInfo(e,n,i));const a=s.chat.createTextMessage(Object.assign(Object.assign(Object.assign({},this.getCurrentConvInfo()),e),{cloudCustomData:r.cloudCustomData}));return this.sendMessage(a,t).then((e=>(r.rootMessage&&this.modifyMessage(r.rootMessage),s.TUIStore.reset(p.CHAT,["quoteMessage"],!0),e)))}sendTextAtMessage(e,t){const s=this.getEngine(),{message:n,type:i}=this.getStoreData(p.CHAT,"quoteMessage");let r={cloudCustomData:e.cloudCustomData||"",rootMessage:void 0};n&&(r=this.getMessageInfo(e,n,i));const a=s.chat.createTextAtMessage(Object.assign(Object.assign(Object.assign({},this.getCurrentConvInfo()),e),{cloudCustomData:r.cloudCustomData}));return this.sendMessage(a,t).then((e=>(r.rootMessage&&this.modifyMessage(r.rootMessage),s.TUIStore.reset(p.CHAT,["quoteMessage"],!0),e)))}sendImageMessage(e,t){const s=this.getEngine().chat.createImageMessage(Object.assign(Object.assign(Object.assign({},this.getCurrentConvInfo()),e),{onProgress:e=>{this.onProgress(s.ID,e)}}));return this.sendMessage(s,t)}sendAudioMessage(e,t){const s=this.getEngine().chat.createAudioMessage(Object.assign(Object.assign(Object.assign({},this.getCurrentConvInfo()),e),{onProgress:e=>{this.onProgress(s.ID,e)}}));return this.sendMessage(s,t)}sendVideoMessage(e,t){const s=this.getEngine().chat.createVideoMessage(Object.assign(Object.assign(Object.assign({},this.getCurrentConvInfo()),e),{onProgress:e=>{this.onProgress(s.ID,e)}}));return this.sendMessage(s,t)}sendCustomMessage(e,t){const s=this.getEngine().chat.createCustomMessage(Object.assign(Object.assign({},this.getCurrentConvInfo()),e));return this.sendMessage(s,t)}sendFaceMessage(e,t){const s=this.getEngine().chat.createFaceMessage(Object.assign(Object.assign({},this.getCurrentConvInfo()),e));return this.sendMessage(s,t)}sendFileMessage(e,t){const s=this.getEngine().chat.createFileMessage(Object.assign(Object.assign(Object.assign({},this.getCurrentConvInfo()),e),{onProgress:e=>{this.onProgress(s.ID,e)}}));return this.sendMessage(s,t)}sendLocationMessage(e,t){const s=this.getEngine().chat.createLocationMessage(Object.assign(Object.assign({},this.getCurrentConvInfo()),e));return this.sendMessage(s,t)}onProgress(e,t){const s=this.getEngine().TUIStore.getMessageModel(e);if(s){(t-s.progress>=.1||1===t)&&(s.progress=t,this.updateMessageList([s],"edit"))}}setAbstractList(e){const t=this.getEngine(),s=e.nick||e.from;let n="";switch(e.type){case t.TYPES.MSG_TEXT:n=e.payload.text||"",n.length>20&&(n=n.slice(0,20));break;case t.TYPES.MSG_MERGER:n=`${this.t("TUIChat.[聊天记录]")}`;break;case t.TYPES.MSG_IMAGE:n=`${this.t("TUIChat.[图片]")}`;break;case t.TYPES.MSG_AUDIO:n=`${this.t("TUIChat.[音频]")}`;break;case t.TYPES.MSG_VIDEO:n=`${this.t("TUIChat.[视频]")}`;break;case t.TYPES.MSG_CUSTOM:n=`${this.t("TUIChat.[自定义消息]")}`;break;case t.TYPES.MSG_FILE:n=`${this.t("TUIChat.[文件]")}`;break;case t.TYPES.MSG_FACE:n=`${this.t("TUIChat.[动画表情]")}`}return`${s}: ${n}`}genMergerForwardPayload(e,t){const{abstractList:s=[],compatibleText:n="",title:i}=t;return 0===s.length&&e.forEach((e=>{s.push(this.setAbstractList(e))})),{messageList:e,title:i,abstractList:s,compatibleText:n||this.t("TUIChat.请升级IMSDK到v2.10.1或更高版本查看此消息")}}genSendMergerForwardMessage(e){const{conversationList:t,messageList:s,params:n,mergeInfo:i,sendMessageOptions:r}=e,a=[];for(let e=0;e<t.length;e++){const{conversationID:o,type:u}=t[e],c=Object.assign({to:o.replace(`${u}`,""),conversationType:u,payload:this.genMergerForwardPayload(s,i)},n),g=this.getEngine().chat.createMergerMessage(c);a.push(this.sendMessage(g,r))}return a}genTitle(e,t){const{nick:s,from:n,to:i}=e;return`${s||n} ${this.t("TUIChat.和")} ${t||i} ${this.t("TUIChat.的聊天记录")}`}genMergeInfo(e){var t;return g(this,void 0,void 0,(function*(){const{messageList:s,mergeInfo:n}=e;if(n.title)return n;if(s[0].conversationType===this.getEngine().TYPES.CONV_GROUP)return n.title=this.t("TUIChat.群聊的聊天记录"),n;try{const{data:e=[]}=yield this.getEngine().TUIUser.getUserProfile({userIDList:[s[0].to]});n.title=this.genTitle(s[0],null===(t=e[0])||void 0===t?void 0:t.nick)}catch(e){n.title=this.genTitle(s[0])}return n}))}sendMergerForwardMessage(e){return g(this,void 0,void 0,(function*(){return e.mergeInfo=yield this.genMergeInfo(e),Promise.all(this.genSendMergerForwardMessage(e))}))}getOriginMessageList(e){return e.map((e=>e instanceof de?e.getMessage():e))}sendForwardMessage(e,t,s){t=this.getOriginMessageList(t);const n=s||{},{needMerge:i=!1,params:r={},mergeInfo:a={}}=n,o=c(n,["needMerge","params","mergeInfo"]);if(i)return this.sendMergerForwardMessage({conversationList:e,messageList:t,params:r,mergeInfo:a,sendMessageOptions:o});const u=[];for(let s=0;s<e.length;s++){const{conversationID:n,type:i}=e[s],a=Object.assign({to:n.replace(`${i}`,""),conversationType:i},r),c=o[n]||o;for(let e=0;e<t.length;e++){Reflect.set(a,"payload",t[e]);const s=this.getEngine().chat.createForwardMessage(a);u.push(this.sendMessage(s,c))}}return Promise.all(u)}revokeMessage(e){const t=this.getEngine().chat.revokeMessage(e);return this.getResponse(t,!0,!1)}resendMessage(e){e.status="unSend",this.updateMessageList([e],"resend");const t=this.getEngine().chat.resendMessage(e);return this.getResponse(t,!0,!0)}deleteMessage(e){const t=this.getEngine().chat.deleteMessage(e);return this.getResponse(t,!0,!1)}setMessageExtensions(e,t){return this.getEngine().chat.setMessageExtensions(e,t)}getMessageExtensions(e){return this.getEngine().chat.getMessageExtensions(e)}deleteMessageExtensions(e,t){return this.getEngine().chat.deleteMessageExtensions(e,t)}modifyMessage(e){const t=this.getEngine().chat.modifyMessage(e);return this.getResponse(t,!0,!1).catch((e=>{const{code:t=0,data:s={}}=e.code;throw t===E.MSG_MODIFY_CONFLICT?console.warn(`${T.MSG_MODIFY_CONFLICT} data.message: ${null==s?void 0:s.message}`):t===E.MSG_MODIFY_DISABLED_IN_AVCHATROOM?console.warn(T.MSG_MODIFY_DISABLED_IN_AVCHATROOM):t===E.MODIFY_MESSAGE_NOT_EXIST&&console.warn(T.MODIFY_MESSAGE_NOT_EXIST),e}))}getMessageList(e={conversationID:this.getStoreData(p.CONV,"currentConversationID"),nextReqMessageID:this.getStoreData(p.CHAT,"nextReqMessageID")}){const t=this.getEngine();if(!t.chat.isReady())return Promise.reject({code:v.GET_MSG_LIST_ERROR,message:S.GET_MSG_LIST_ERROR});if(this.getStoreData(p.CHAT,"isCompleted"))return Promise.resolve({data:{messageList:[],nextReqMessageID:"",isCompleted:!0}});const s=this.getStoreData(p.CHAT,"messageSource"),n=this.hoppingConfigMap.get("nextMessageSeq"),i=this.hoppingConfigMap.get("nextMessageTime"),r=n||i;return s&&s.conversationID===(null==e?void 0:e.conversationID)&&r?this.getMessageListHopping():t.chat.getMessageList(e).then((e=>{var s;const{messageList:n,nextReqMessageID:i,isCompleted:r}=e.data,a=this.getStoreData(p.CHAT,"userInfo");Object.keys(a).length>0&&this.updateLocalMessage(n,a),this.updateMessageList(n,"unshift"),t.TUIStore.update(p.CHAT,"nextReqMessageID",i),t.TUIStore.update(p.CHAT,"isCompleted",r);const o=null===(s=n[0])||void 0===s?void 0:s.conversationID,{operationType:u=0}=this.getEngine().TUIStore.getConversationModel(o)||{};return 0===u&&(this.getMessageReactions({messageList:n}),this.readReceiptHandler.getMessageReadReceiptList(n)),e})).catch((e=>Promise.reject(e)))}getMessageListHopping(e){var t;void 0===e&&(e={conversationID:null===(t=this.getStoreData(p.CHAT,"messageSource"))||void 0===t?void 0:t.conversationID,sequence:this.hoppingConfigMap.get("nextMessageSeq"),time:this.hoppingConfigMap.get("nextMessageTime")});const s=this.getEngine();return s.chat.getMessageListHopping(e).then((t=>{const{messageList:n,nextMessageSeq:i,nextMessageTime:r,isCompleted:a}=t.data,o=1===e.direction?e.sequence:i,u=1===e.direction?e.time:r;return this.updateMessageList(n,"unshift"),this.delayGetHoppingFunction=void 0,this.hoppingConfigMap.set("nextMessageSeq",o),this.hoppingConfigMap.set("nextMessageTime",u),s.TUIStore.update(p.CHAT,"isCompleted",a),t})).catch((e=>Promise.reject(e)))}sendMessageReadReceipt(e){return this.readReceiptHandler.sendMessageReadReceipt(e)}getGroupMessageReadMemberList(e){return this.readReceiptHandler.getGroupMessageReadMemberList(e).then((e=>{const{isCompleted:t,cursor:s,messageID:n,unreadUserIDList:i,readUserIDList:r}=e.data,a={code:0,data:{cursor:s,isCompleted:t,messageID:n,unreadUserInfoList:[],readUserInfoList:[]}},o=[...i,...r];return 0===o.length?a:this.getEngine().TUIUser.getUserProfile({userIDList:o}).then((e=>(i.length>0?e.data.forEach((e=>{const{userID:t,nick:s="",avatar:n=""}=e;a.data.unreadUserInfoList.push({userID:t,nick:s,avatar:n})})):e.data.forEach((e=>{const{userID:t,nick:s="",avatar:n=""}=e;a.data.readUserInfoList.push({userID:t,nick:s,avatar:n})})),a)))}))}downloadMergedMessages(e){return this.getEngine().chat.downloadMergerMessage(e)}setTranslationLanguage(e){this.getEngine().TUIStore.update(p.USER,"targetLanguage",e)}translateText(e){const t=this.getStoreData(p.USER,"targetLanguage"),s=Object.assign({targetLanguage:t,sourceLanguage:"auto"},e);return this.getEngine().chat.translateText(s)}searchCloudMessages(e){return this.getEngine().TUISearch.searchCloudMessages(e)}addMessageReaction(e,t){return this.getEngine().chat.addMessageReaction(e.getMessage(),t)}removeMessageReaction(e,t){return this.getEngine().chat.removeMessageReaction(e.getMessage(),t)}getMessageReactions(e){const{messageList:t=[]}=e,s=this.getStoreData(p.APP,"enabledEmojiPlugin");console.log(`TUIChatService.getMessageReactions enabledEmojiPlugin:${s} messageList length:${t.length}`),s&&t.length>0&&this.getEngine().chat.getMessageReactions(e).then((e=>{const t=e.data.resultList||e.data;this.updateMessageReactionList(t)})).catch((()=>{}))}getAllUserListOfMessageReaction(e){var t;return this.getEngine().chat.getAllUserListOfMessageReaction(Object.assign(Object.assign({},e),{message:null===(t=null==e?void 0:e.message)||void 0===t?void 0:t.getMessage()}))}updateMessageReactionList(e){const t=[];e.forEach((e=>{const{messageID:s,reactionList:n}=e,i=this.getEngine().TUIStore.getMessageModel(s);if(i){const e=[];for(let t=0;t<n.length;t++){let s=!0;for(let e=0;e<i.reactionList.length;e++)if(n[t].reactionID===i.reactionList[e].reactionID){i.reactionList[e]=n[t],s=!1;break}s&&e.push(n[t])}i.reactionList.push(...e),e.length=0,t.push(i)}})),t.length>0&&this.updateMessageList(t,"edit")}convertVoiceToText(e){const{message:t,language:s="zh"}=e,n=t.getMessage();return this.getEngine().chat.convertVoiceToText({message:n,language:s})}clearHistoryMessage(e){const t=this.getEngine();return t.chat.clearHistoryMessage(e).then((e=>(t.TUIStore.update(p.CHAT,"messageList",[]),t.TUIStore.update(p.CHAT,"nextReqMessageID",""),t.TUIStore.update(p.CHAT,"isCompleted",!1),e)))}updateMessageInfo(e){const t=this.getStoreData(p.CHAT,"userInfo");this.getEngine().TUIStore.update(p.CHAT,"userInfo",Object.assign(t,e));const s=this.getStoreData(p.CHAT,"messageList");if(s.length>0){this.updateLocalMessage(s,e)&&this.getEngine().TUIStore.update(p.CHAT,"messageList",s)}}updateLocalMessage(e,t){let s=!1;return e.forEach((e=>{if(t[e.from]){const{nick:n,nameCard:i,avatar:r}=t[e.from];n&&(e.nick=n,s=!0),i&&(e.nameCard=i,s=!0),r&&(e.avatar=r,s=!0)}})),s}handleC2CCallSignaling(e){const t=this.getEngine(),s=t.getMyUserID();return e.filter((e=>{var n,i,r,a,o;const{conversationType:u,type:c,payload:g}=e;let l=!0;if(u===t.TYPES.CONV_C2C&&c===t.TYPES.MSG_CUSTOM){if(t.chat.getSignalingInfo(e)){const t=P(g.data);if(1===(null==t?void 0:t.businessID)){const u=P(t.data);if(l=!(e._isExcludedFromUnreadCount&&e._isExcludedFromLastMessage),l&&!0!==(null===(n=null==u?void 0:u.data)||void 0===n?void 0:n.consumed)){let n=null===(i=null==u?void 0:u.data)||void 0===i?void 0:i.inviter;"line_busy"!==(null==u?void 0:u.line_busy)&&"lineBusy"!==(null===(r=null==u?void 0:u.data)||void 0===r?void 0:r.message)||(n=t.inviter);const{from:c,to:g}=e;if(n!==s&&e.from===s){const t=this.getStoreData(p.CONV,"currentConversation");e.from=g,e.to=c,e.flow="in",e.avatar=(null===(a=null==t?void 0:t.userProfile)||void 0===a?void 0:a.avatar)||""}if(n===s&&e.from!==s){const t=this.getStoreData(p.USER,"userProfile");e.from=g,e.to=c,e.flow="out",e.avatar=null==t?void 0:t.avatar}console.log(`${this.serv}.handleC2CCallSignaling myUserID:${s} callSignaling.inviter:${t.inviter} customData.data.inviter:${null===(o=null==u?void 0:u.data)||void 0===o?void 0:o.inviter}`)}}}}return l}))}sortMessageList(e){const{conversationType:t}=e[0];if(t===this.getEngine().TYPES.CONV_C2C)return e.sort(((e,t)=>e.time-t.time));const s=e.filter((e=>"success"===e.status)).sort(((e,t)=>e.sequence-t.sequence));for(let t=0;t<e.length;t++)"success"!==e[t].status&&s.splice(t,0,e[t]);return s}}class Xt extends ce{constructor(){super(),this.groupMap=new Map}static getInstance(){return Xt.instance||(Xt.instance=new Xt),Xt.instance}init(){const e=this.getEngine();e.eventCenter.addEvent(e.EVENT.GROUP_LIST_UPDATED,this.onGroupListUpdated.bind(this)),e.eventCenter.addEvent(e.EVENT.GROUP_ATTRIBUTES_UPDATED,this.onGroupAttributesUpdated.bind(this)),e.eventCenter.addEvent(e.EVENT.GROUP_COUNTER_UPDATED,this.onGroupCounterUpdated.bind(this)),e.eventCenter.addEvent(e.EVENT.MESSAGE_RECEIVED,this.onMessageReceived.bind(this)),this.getGroupInitData()}onGroupListUpdated(e){const t=this.getEngine();t.TUIStore.update(p.GRP,"groupList",e);const s=t.TUIStore.getData(p.GRP,"currentGroupID");e.forEach((e=>{e.groupID===s&&t.TUIStore.update(p.GRP,"currentGroup",e)}))}onGroupAttributesUpdated(e){const t=this.getEngine(),s=t.TUIStore.getData(p.GRP,"currentGroupID");let n=t.TUIStore.getData(p.GRP,"groupList");const{groupID:i,groupAttributes:r}=e;s===i&&t.TUIStore.update(p.GRP,"currentGroupAttributes",r),n=n.map((e=>(e.groupID===i&&(e.groupAttributes=r),e))),t.TUIStore.update(p.GRP,"groupList",n)}onGroupCounterUpdated(e){const t=this.getEngine(),s=t.TUIStore.getData(p.GRP,"currentGroupID"),n=t.TUIStore.getData(p.GRP,"currentGroupCounters")||{};let i=t.TUIStore.getData(p.GRP,"groupList");const{groupID:r,key:a,value:o}=e;s===r&&(n[a]=o,t.TUIStore.update(p.GRP,"currentGroupCounters",n)),i=i.map((e=>(e.groupID===r&&(e.groupCounters=Object.assign(Object.assign({},e.groupCounters),{[a]:o})),e))),t.TUIStore.update(p.GRP,"groupList",i)}onMessageReceived(e){const t=this.getEngine(),s=[];e.forEach((e=>{if(e.type===t.TYPES.MSG_GRP_TIP){const{payload:s}=e,{operationType:n,userIDList:i}=s;switch(n){case t.TYPES.GRP_TIP_MBR_JOIN:this.addMemberList(i);break;case t.TYPES.GRP_TIP_MBR_QUIT:case t.TYPES.GRP_TIP_MBR_KICKED_OUT:this.removeMemberList(i);break;case t.TYPES.GRP_TIP_MBR_SET_ADMIN:case t.TYPES.GRP_TIP_MBR_CANCELED_ADMIN:this.updateGroupMember(i);break;case t.TYPES.GRP_TIP_GRP_PROFILE_UPDATED:break;case t.TYPES.GRP_TIP_MBR_PROFILE_UPDATED:case t.TYPES.GRP_TIP_BAN_AVCHATROOM_MEMBER:case t.TYPES.GRP_TIP_UNBAN_AVCHATROOM_MEMBER:this.updateGroupMember(i)}}e.type===t.TYPES.MSG_GRP_SYS_NOTICE&&s.push(e)})),s.length>0&&t.TUIStore.update(p.GRP,"groupSystemNoticeList",s)}getGroupInitData(){const e=this.getEngine();e.chat.isReady()&&e.chat.getGroupList().then((e=>{const{groupList:t=[]}=e.data;console.log(`TUIGroupService.init, getGroupList count:${t.length}`),t.length>0&&this.onGroupListUpdated(t)}))}updateGroupMember(e){return g(this,void 0,void 0,(function*(){const t=this.getEngine().TUIStore.getData(p.GRP,"currentGroupID");if(t){const s=yield this.getGroupMemberProfile({groupID:t,userIDList:e}),{memberList:n}=s.data;this.updateMemberList(n)}}))}resetCurrentStore(){this.getEngine().TUIStore.reset(p.GRP,["currentGroupID","currentGroup","currentGroupAttributes","currentGroupCounters","currentGroupMemberList"],!0)}switchGroup(e){return g(this,void 0,void 0,(function*(){const t=this.getEngine();t.TUIStore.update(p.GRP,"offset",0),t.TUIStore.update(p.GRP,"isCompleted",!1);const s=t.TUIStore.getConversationModel(`GROUP${e}`);if((null==s?void 0:s.operationType)>0){const e=t.TUIStore.getData(p.GRP,"currentGroup");return Promise.resolve(e)}const n=t.TUIStore.getData(p.GRP,"currentGroupID");if(!e)return this.resetCurrentStore(),Promise.resolve({});if(n===e){const e=t.TUIStore.getData(p.GRP,"currentGroup");return Promise.resolve(e)}this.resetCurrentStore(),t.TUIStore.update(p.GRP,"currentGroupID",e);try{yield this.getGroupInfo(e)}catch(e){Promise.reject(e)}const i=setTimeout((()=>{this.groupMap.delete(e),clearTimeout(i)}),5e3),r=t.TUIStore.getData(p.GRP,"currentGroup");return Promise.resolve(r)}))}getGroupInfo(e){return g(this,void 0,void 0,(function*(){const t=this.getEngine(),s=this.groupMap.get(e);if(s)return this.updateMemberList((null==s?void 0:s.memberList)||[]),t.TUIStore.update(p.GRP,"currentGroup",s.group),t.TUIStore.update(p.GRP,"currentGroupAttributes",s.groupAttributes||{}),void t.TUIStore.update(p.GRP,"currentGroupCounters",s.counters||{});const n={group:{},memberList:[],groupAttributes:void 0,counters:void 0},{data:{group:i}}=yield this.getGroupProfile({groupID:e});n.group=i;const{data:{memberList:r}}=yield this.getGroupMemberList({groupID:e});n.memberList=r;const a=yield this.getGroupAttributes({groupID:e,keyList:[]}),{groupAttributes:o}=a.data;n.groupAttributes=o,t.TUIStore.update(p.GRP,"currentGroupAttributes",o);try{const s=yield this.getGroupCounters({groupID:e,keyList:[]}),{counters:i}=s.data;n.counters=i,t.TUIStore.update(p.GRP,"currentGroupCounters",i)}catch(e){console.warn(null==e?void 0:e.message)}this.groupMap.set(e,n)}))}getGroupProfile(e){const t=this.getEngine();return t.chat.getGroupProfile(e).then((s=>g(this,void 0,void 0,(function*(){if(t.TUIStore.getData(p.GRP,"currentGroupID")===e.groupID){const{group:e}=s.data;t.TUIStore.update(p.GRP,"currentGroup",e)}return s}))))}updateGroupProfile(e){return this.getEngine().chat.updateGroupProfile(e)}createGroup(e){return this.getEngine().chat.createGroup(e)}dismissGroup(e){return this.getEngine().chat.dismissGroup(e)}searchGroupByID(e){const t=this.getEngine();return t.chat.searchGroupByID(e).then((e=>{const{group:s}=e.data,n=t.TUIStore.getData(p.GRP,"groupList");return e.data.group.isJoinedGroup=n.some((e=>e.groupID===s.groupID)),e}))}joinGroup(e){return this.getEngine().chat.joinGroup(e)}quitGroup(e){return this.getEngine().chat.quitGroup(e)}getGroupApplicationList(){return this.getEngine().chat.getGroupApplicationList()}handleGroupApplication(e){return this.getEngine().chat.handleGroupApplication(e)}getGroupOnlineMemberCount(e){return this.getEngine().chat.getGroupOnlineMemberCount(e)}changeGroupOwner(e){return this.getEngine().chat.changeGroupOwner(e)}initGroupAttributes(e){return this.getEngine().chat.initGroupAttributes(e)}setGroupAttributes(e){return this.getEngine().chat.setGroupAttributes(e)}deleteGroupAttributes(e){return this.getEngine().chat.deleteGroupAttributes(e)}getGroupAttributes(e){return this.getEngine().chat.getGroupAttributes(e)}setGroupCounters(e){return this.getEngine().chat.setGroupCounters(e)}increaseGroupCounter(e){return this.getEngine().chat.increaseGroupCounter(e)}decreaseGroupCounter(e){return this.getEngine().chat.decreaseGroupCounter(e)}getGroupCounters(e){return this.getEngine().chat.getGroupCounters(e)}updateMemberList(e){const t=this.getEngine(),s=[...(t.TUIStore.getData(p.GRP,"currentGroupMemberList")||[]).filter((t=>!e.find((e=>e.userID===t.userID)))),...e];t.TUIStore.update(p.GRP,"currentGroupMemberList",s)}addMemberList(e){return g(this,void 0,void 0,(function*(){const t=this.getEngine().TUIStore.getData(p.GRP,"currentGroupID");if(t)try{const s=yield this.getGroupMemberProfile({groupID:t,userIDList:e}),{memberList:n}=s.data;this.updateMemberList(n)}catch(t){const s=e.map((e=>({userID:e,avatar:"",nick:"",role:"",joinTime:0,nameCard:"",muteUntil:0,memberCustomField:[]})));this.updateMemberList(s)}}))}removeMemberList(e){const t=this.getEngine(),s=t.TUIStore.getData(p.GRP,"currentGroupMemberList").filter((t=>-1===e.indexOf(t.userID)));t.TUIStore.update(p.GRP,"currentGroupMemberList",s)}getGroupMemberList(e){const t=this.getEngine();if(O(e.offset)){const s=t.TUIStore.getData(p.GRP,"offset");e.offset=s}return t.chat.getGroupMemberList(e).then((s=>{if(t.TUIStore.getData(p.GRP,"currentGroupID")===e.groupID){const{memberList:e,offset:n=0}=s.data;this.updateMemberList(e),t.TUIStore.update(p.GRP,"offset",n),0===n&&t.TUIStore.update(p.GRP,"isCompleted",!0)}return s}))}getGroupMemberProfile(e){return this.getEngine().chat.getGroupMemberProfile(e)}addGroupMember(e){const t=this.getEngine();return t.chat.addGroupMember(e).then((s=>g(this,void 0,void 0,(function*(){if(t.TUIStore.getData(p.GRP,"currentGroupID")===e.groupID){const{successUserIDList:e,group:n}=s.data;t.TUIStore.update(p.GRP,"currentGroup",n),this.addMemberList(e)}return s}))))}deleteGroupMember(e){const t=this.getEngine();return t.chat.deleteGroupMember(e).then((s=>{if(t.TUIStore.getData(p.GRP,"currentGroupID")===e.groupID){const{userIDList:e,group:n}=s.data;this.removeMemberList(e),t.TUIStore.update(p.GRP,"currentGroup",n)}return s}))}setGroupMemberMuteTime(e){return this.getEngine().chat.setGroupMemberMuteTime(e)}setGroupMemberRole(e){return this.getEngine().chat.setGroupMemberRole(e)}setGroupMemberNameCard(e){return this.getEngine().chat.setGroupMemberNameCard(e)}setGroupMemberCustomField(e){return this.getEngine().chat.setGroupMemberCustomField(e)}markGroupMemberList(e){return this.getEngine().chat.markGroupMemberList(e)}}class Zt extends ce{constructor(){super()}static getInstance(){return Zt.instance||(Zt.instance=new Zt),Zt.instance}init(){const e=this.getEngine();e.eventCenter.addEvent(e.EVENT.FRIEND_LIST_UPDATED,this.onFriendListUpdated.bind(this)),e.eventCenter.addEvent(e.EVENT.FRIEND_APPLICATION_LIST_UPDATED,this.onFriendApplicationListUpdated.bind(this)),this.getFriendInitData()}onFriendListUpdated(e){this.getEngine().TUIStore.update(p.FRIEND,"friendList",e)}onFriendApplicationListUpdated(e){const{friendApplicationList:t,unreadCount:s=0}=e,n=this.getEngine();n.TUIStore.update(p.FRIEND,"friendApplicationList",t),n.TUIStore.update(p.FRIEND,"friendApplicationUnreadCount",s)}getFriendInitData(){const e=this.getEngine();e.chat.isReady()&&(e.chat.getFriendList().then((e=>{const t=e.data||[];console.log(`TUIFriendService.init, getFriendList count:${t.length}`),t.length>0&&this.onFriendListUpdated(t)})),e.chat.getFriendApplicationList().then((e=>{this.onFriendApplicationListUpdated(e.data)})))}getFriendList(){return this.getEngine().chat.getFriendList()}getFriendRemark(e){const t=this.getEngine().TUIStore.getData(p.FRIEND,"friendList"),s={};return e.forEach((e=>{for(let n=0;n<t.length;n++)t[n].userID!==e||(s[e]=t[n].remark)})),s}addFriend(e){return this.getEngine().chat.addFriend(e)}deleteFriend(e){return this.getEngine().chat.deleteFriend(e)}checkFriend(e){return this.getEngine().chat.checkFriend(e)}getFriendProfile(e){return this.getEngine().chat.getFriendProfile(e)}updateFriend(e){return this.getEngine().chat.updateFriend(e)}acceptFriendApplication(e){return this.getEngine().chat.acceptFriendApplication(e)}refuseFriendApplication(e){return this.getEngine().chat.refuseFriendApplication({userID:e})}deleteFriendApplication(e){return this.getEngine().chat.deleteFriendApplication(e)}setFriendApplicationRead(){return this.getEngine().chat.setFriendApplicationRead()}}class Qt extends ce{static getInstance(){return Qt.instance||(Qt.instance=new Qt),Qt.instance}reportFeature(e,t){var s;return null===(s=this.getEngine().chat)||void 0===s?void 0:s.callExperimentalAPI("statTUIKeyFeatures",{code:e,msg:t?`${e}-${t}`:""})}}!function(e){e.MESSAGE="message",e.CHAT_MESSAGE="chat_message",e.USER="user",e.GROUP="group"}(jt||(jt={})),function(e){e.MSG_TEXT="TIMTextElem",e.MSG_IMAGE="TIMImageElem",e.MSG_SOUND="TIMSoundElem",e.MSG_FILE="TIMFileElem",e.MSG_VIDEO="TIMVideoFileElem",e.MSG_LOCATION="TIMLocationElem",e.MSG_CUSTOM="TIMCustomElem",e.MSG_MERGER="TIMRelayElem"}(kt||(kt={})),function(e){e.GRP_WORK="Private",e.GRP_PUBLIC="Public",e.GRP_MEETING="ChatRoom",e.GRP_COMMUNITY="Community"}(Nt||(Nt={}));class es extends ce{constructor(){super(),this.resultKeyMap={[jt.MESSAGE]:"searchMessagesResult",[jt.CHAT_MESSAGE]:"searchChatMessagesResult",[jt.USER]:"searchUserResult",[jt.GROUP]:"searchGroupResult"},this.paramsKeyMap={[jt.MESSAGE]:"searchMessageParams",[jt.CHAT_MESSAGE]:"searchChatMessageParams",[jt.USER]:"searchUserParams",[jt.GROUP]:"searchGroupParams"}}static getInstance(){return es.instance||(es.instance=new es),es.instance}getStoreData(e,t){return this.getEngine().TUIStore.getData(e,t)}handleSearchResult(e,t){const{resultList:s}=this.getStoreData(p.SEARCH,this.resultKeyMap[e]),{cursor:n,searchResultList:i,params:r,totalCount:a}=t,o=[];if(e===jt.CHAT_MESSAGE){const{conversation:e}=s[0]||{},{conversation:t}=i[0];(null==e?void 0:e.conversationID)===t.conversationID&&1===s.length&&(i[0].messageList=[...s[0].messageList,...i[0].messageList]),o.push(...i)}else o.push(...s,...i);this.getEngine().TUIStore.update(p.SEARCH,this.resultKeyMap[e],{resultList:o,params:r,hasMore:!!n,cursor:n,totalCount:a})}searchParamsValidate(e,t){const s=this.getStoreData(p.SEARCH,this.paramsKeyMap[e]),{cursor:n}=s,i=c(s,["cursor"]),{cursor:r}=t,a=c(t,["cursor"]),o=JSON.stringify(i)===JSON.stringify(a),u=!!r,g=r===n;return o?o&&!u?(this.getEngine().TUIStore.reset(p.SEARCH,[this.resultKeyMap[e]]),this.getEngine().TUIStore.update(p.SEARCH,this.paramsKeyMap[e],t),!0):!(!o||!u||g):(this.getEngine().TUIStore.reset(p.SEARCH,[this.resultKeyMap[e]]),this.getEngine().TUIStore.update(p.SEARCH,this.paramsKeyMap[e],t),!0)}searchCloudMessages(e){const{keyword:t,keywordList:s,conversationID:n}=e,i=c(e,["keyword","keywordList","conversationID"]);let r=!0;if(r=n?this.searchParamsValidate(jt.CHAT_MESSAGE,e):this.searchParamsValidate(jt.MESSAGE,e),!r)return Promise.resolve();const a=this.getStoreData(p.CONV,"conversationList");return this.getEngine().chat.searchCloudMessages(Object.assign({keywordList:t?[t]:s||void 0,keywordListMatchType:"or",conversationID:n},i)).then((t=>{const{searchResultList:s}=t.data;return(null==s?void 0:s.length)>0&&(t.data.searchResultList=s.map((e=>{const{messageList:t,conversationID:s}=e,n=c(e,["messageList","conversationID"]),i=t.map((e=>new de(e))),r=a.find((e=>e.conversationID===s));return Object.assign(Object.assign({},n),{messageList:i.sort(((e,t)=>t.time-e.time)),conversation:r})}))),t.data.params=e,n?this.handleSearchResult(jt.CHAT_MESSAGE,t.data):this.handleSearchResult(jt.MESSAGE,t.data),t})).catch((e=>{this.getEngine().TUIStore.update(p.SEARCH,"error",e),Promise.resolve(e)}))}searchCloudUsers(t){const{keyword:s,keywordList:n}=t,i=c(t,["keyword","keywordList"]),r=this.getStoreData(p.FRIEND,"friendList");return this.searchParamsValidate(jt.USER,t)?this.getEngine().chat.searchCloudUsers(Object.assign({keywordList:s?[s]:n||void 0,keywordListMatchType:"or"},i)).then((s=>{const{searchResultList:n}=s.data;if(n.length>0){const t=new Map(n.map((t=>[t.userID,{profile:t,relation:e.TYPES.SNS_TYPE_NO_RELATION}])));r.forEach((s=>{const{userID:n}=s,i=t.get(n);i&&(i.relation=e.TYPES.SNS_TYPE_BOTH_WAY)})),s.data.searchResultList=Array.from(t.values())}return s.data.params=t,this.handleSearchResult(jt.USER,s.data),s})).catch((e=>{this.getEngine().TUIStore.update(p.SEARCH,"error",e),Promise.resolve(e)})):Promise.resolve()}searchCloudGroups(e){const{keyword:t,keywordList:s}=e,n=c(e,["keyword","keywordList"]),i=this.getStoreData(p.CONV,"conversationList"),r=this.getStoreData(p.GRP,"groupList");return this.searchParamsValidate(jt.GROUP,e)?this.getEngine().chat.searchCloudGroups(Object.assign({keywordList:t?[t]:s||void 0,keywordListMatchType:"or"},n)).then((t=>{const{searchResultList:s}=t.data;return s.length>0&&(t.data.searchResultList=s.map((e=>{const t=r.find((t=>t.groupID===e.groupID)),s=i.find((t=>t.conversationID===`GROUP${e.groupID}`));return{groupInfo:t||e,conversation:s}}))),t.data.params=e,this.handleSearchResult(jt.GROUP,t.data),t})).catch((e=>{this.getEngine().TUIStore.update(p.SEARCH,"error",e),Promise.resolve(e)})):Promise.resolve()}}class ts{constructor(){this.cache=[],this.middlewares=[],this.options=null}use(e){return"function"!=typeof e&&console.error("middleware must be a function"),this.cache.push(e),this}next(){if(this.middlewares&&this.middlewares.length>0){return this.middlewares.shift().call(this,this.options,this.next.bind(this))}}run(e){return this.middlewares=this.cache.map((e=>e)),this.options=e,this.next()}}function ss(e,t,s){const n=Object.create(null);Object.keys(s).forEach((s=>{if(!t[s])return;n[s]=t[s];const i=new ts;t[s]=function(){const r=Array.from(arguments);return i.use(((t,n)=>e.isInited?n():Promise.reject({code:v.NOT_INIT,message:`${s} | ${S.NOT_INIT}`}))).use((e=>n[s].apply(t,e))),i.run(r)}}))}console.log("TUIChatEngine.VERSION:3.0.0-beta.1");const ns=ae.getInstance(),is=ne.getInstance(),rs=Ie.getInstance(),as=xt.getInstance(),os=wt.getInstance(),us=Kt.getInstance(),cs=Wt.getInstance(),gs=Xt.getInstance(),ls=Zt.getInstance(),hs=Qt.getInstance(),ps=es.getInstance();ns.mount(h.TUIStore,rs),ns.mount(h.TUITranslate,as),ns.mount(h.TUIConversation,os),ns.mount(h.TUIUser,us),ns.mount(h.TUIChat,cs),ns.mount(h.TUIGroup,gs),ns.mount(h.TUIFriend,ls),ns.mount(h.TUIReport,hs),ns.mount(h.TUISearch,ps),ss(ns,ns,I),ss(ns,os,y),ss(ns,cs,b),ss(ns,gs,M),ss(ns,us,U),ss(ns,ls,C),ss(ns,hs,I),ss(ns,ps,I);export{Nt as GroupType,jt as ISearchType,kt as MessageType,p as StoreName,ns as TUIChatEngine,cs as TUIChatService,os as TUIConversationService,ls as TUIFriendService,is as TUIGlobal,gs as TUIGroupService,hs as TUIReportService,ps as TUISearchService,rs as TUIStore,as as TUITranslateService,us as TUIUserService,ns as default};