nim-web-sdk-ng
Version:
Yunxin IM SDK next generation
22 lines • 693 kB
JavaScript
/**
*
* Version: 10.9.70
*
* Git Hash: 98a6d08e82089d389591ebeca24397f8350ec392
*
* Created At: 12/4/2025, 9:55:00 AM
*
* Target: nim.js
*
*/
var t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function createCommonjsModule(t){var i={exports:{}};return t(i,i.exports),i.exports}var i,o,m,h,u,v,I,_,M,E,S,T,C,N,A,O,R,V,k,P,L,w,D,U,x,B,$,j,G,q,H,z,Y,J,K,W,X,Q,Z,ee,te,ie,re,ne,oe,se,ae,ce,de,le,pe,me,he,ue,ge,ve,fe,Ie=createCommonjsModule((function(t){var i=Object.prototype.hasOwnProperty,o="~";function Events(){}function EE(t,i,o){this.fn=t,this.context=i,this.once=o||!1}function addListener(t,i,m,h,u){if("function"!=typeof m)throw new TypeError("The listener must be a function");var v=new EE(m,h||t,u),I=o?o+i:i;return t._events[I]?t._events[I].fn?t._events[I]=[t._events[I],v]:t._events[I].push(v):(t._events[I]=v,t._eventsCount++),t}function clearEvent(t,i){0==--t._eventsCount?t._events=new Events:delete t._events[i]}function EventEmitter(){this._events=new Events,this._eventsCount=0}Object.create&&(Events.prototype=Object.create(null),(new Events).__proto__||(o=!1)),EventEmitter.prototype.eventNames=function eventNames(){var t,m,h=[];if(0===this._eventsCount)return h;for(m in t=this._events)i.call(t,m)&&h.push(o?m.slice(1):m);return Object.getOwnPropertySymbols?h.concat(Object.getOwnPropertySymbols(t)):h},EventEmitter.prototype.listeners=function listeners(t){var i=o?o+t:t,m=this._events[i];if(!m)return[];if(m.fn)return[m.fn];for(var h=0,u=m.length,v=new Array(u);h<u;h++)v[h]=m[h].fn;return v},EventEmitter.prototype.listenerCount=function listenerCount(t){var i=o?o+t:t,m=this._events[i];return m?m.fn?1:m.length:0},EventEmitter.prototype.emit=function emit(t,i,m,h,u,v){var I=o?o+t:t;if(!this._events[I])return!1;var _,M,E=this._events[I],S=arguments.length;if(E.fn){switch(E.once&&this.removeListener(t,E.fn,void 0,!0),S){case 1:return E.fn.call(E.context),!0;case 2:return E.fn.call(E.context,i),!0;case 3:return E.fn.call(E.context,i,m),!0;case 4:return E.fn.call(E.context,i,m,h),!0;case 5:return E.fn.call(E.context,i,m,h,u),!0;case 6:return E.fn.call(E.context,i,m,h,u,v),!0}for(M=1,_=new Array(S-1);M<S;M++)_[M-1]=arguments[M];E.fn.apply(E.context,_)}else{var T,C=E.length;for(M=0;M<C;M++)switch(E[M].once&&this.removeListener(t,E[M].fn,void 0,!0),S){case 1:E[M].fn.call(E[M].context);break;case 2:E[M].fn.call(E[M].context,i);break;case 3:E[M].fn.call(E[M].context,i,m);break;case 4:E[M].fn.call(E[M].context,i,m,h);break;default:if(!_)for(T=1,_=new Array(S-1);T<S;T++)_[T-1]=arguments[T];E[M].fn.apply(E[M].context,_)}}return!0},EventEmitter.prototype.on=function on(t,i,o){return addListener(this,t,i,o,!1)},EventEmitter.prototype.once=function once(t,i,o){return addListener(this,t,i,o,!0)},EventEmitter.prototype.removeListener=function removeListener(t,i,m,h){var u=o?o+t:t;if(!this._events[u])return this;if(!i)return clearEvent(this,u),this;var v=this._events[u];if(v.fn)v.fn!==i||h&&!v.once||m&&v.context!==m||clearEvent(this,u);else{for(var I=0,_=[],M=v.length;I<M;I++)(v[I].fn!==i||h&&!v[I].once||m&&v[I].context!==m)&&_.push(v[I]);_.length?this._events[u]=1===_.length?_[0]:_:clearEvent(this,u)}return this},EventEmitter.prototype.removeAllListeners=function removeAllListeners(t){var i;return t?(i=o?o+t:t,this._events[i]&&clearEvent(this,i)):(this._events=new Events,this._eventsCount=0),this},EventEmitter.prototype.off=EventEmitter.prototype.removeListener,EventEmitter.prototype.addListener=EventEmitter.prototype.on,EventEmitter.prefixed=o,EventEmitter.EventEmitter=EventEmitter,t.exports=EventEmitter})),ye=createCommonjsModule((function(t,i){t.exports=function(){function _regeneratorRuntime(){
/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
_regeneratorRuntime=function(){return t};var t={},i=Object.prototype,o=i.hasOwnProperty,m="function"==typeof Symbol?Symbol:{},h=m.iterator||"@@iterator",u=m.asyncIterator||"@@asyncIterator",v=m.toStringTag||"@@toStringTag";function define(t,i,o){return Object.defineProperty(t,i,{value:o,enumerable:!0,configurable:!0,writable:!0}),t[i]}try{define({},"")}catch(t){define=function(t,i,o){return t[i]=o}}function wrap(t,i,o,m){var h=i&&i.prototype instanceof Generator?i:Generator,u=Object.create(h.prototype),v=new Context(m||[]);return u._invoke=function(t,i,o){var m="suspendedStart";return function(h,u){if("executing"===m)throw new Error("Generator is already running");if("completed"===m){if("throw"===h)throw u;return doneResult()}for(o.method=h,o.arg=u;;){var v=o.delegate;if(v){var _=maybeInvokeDelegate(v,o);if(_){if(_===I)continue;return _}}if("next"===o.method)o.sent=o._sent=o.arg;else if("throw"===o.method){if("suspendedStart"===m)throw m="completed",o.arg;o.dispatchException(o.arg)}else"return"===o.method&&o.abrupt("return",o.arg);m="executing";var M=tryCatch(t,i,o);if("normal"===M.type){if(m=o.done?"completed":"suspendedYield",M.arg===I)continue;return{value:M.arg,done:o.done}}"throw"===M.type&&(m="completed",o.method="throw",o.arg=M.arg)}}}(t,o,v),u}function tryCatch(t,i,o){try{return{type:"normal",arg:t.call(i,o)}}catch(t){return{type:"throw",arg:t}}}t.wrap=wrap;var I={};function Generator(){}function GeneratorFunction(){}function GeneratorFunctionPrototype(){}var _={};define(_,h,(function(){return this}));var M=Object.getPrototypeOf,E=M&&M(M(values([])));E&&E!==i&&o.call(E,h)&&(_=E);var S=GeneratorFunctionPrototype.prototype=Generator.prototype=Object.create(_);function defineIteratorMethods(t){["next","throw","return"].forEach((function(i){define(t,i,(function(t){return this._invoke(i,t)}))}))}function AsyncIterator(t,i){function invoke(m,h,u,v){var I=tryCatch(t[m],t,h);if("throw"!==I.type){var _=I.arg,M=_.value;return M&&"object"==typeof M&&o.call(M,"__await")?i.resolve(M.__await).then((function(t){invoke("next",t,u,v)}),(function(t){invoke("throw",t,u,v)})):i.resolve(M).then((function(t){_.value=t,u(_)}),(function(t){return invoke("throw",t,u,v)}))}v(I.arg)}var m;this._invoke=function(t,o){function callInvokeWithMethodAndArg(){return new i((function(i,m){invoke(t,o,i,m)}))}return m=m?m.then(callInvokeWithMethodAndArg,callInvokeWithMethodAndArg):callInvokeWithMethodAndArg()}}function maybeInvokeDelegate(t,i){var o=t.iterator[i.method];if(void 0===o){if(i.delegate=null,"throw"===i.method){if(t.iterator.return&&(i.method="return",i.arg=void 0,maybeInvokeDelegate(t,i),"throw"===i.method))return I;i.method="throw",i.arg=new TypeError("The iterator does not provide a 'throw' method")}return I}var m=tryCatch(o,t.iterator,i.arg);if("throw"===m.type)return i.method="throw",i.arg=m.arg,i.delegate=null,I;var h=m.arg;return h?h.done?(i[t.resultName]=h.value,i.next=t.nextLoc,"return"!==i.method&&(i.method="next",i.arg=void 0),i.delegate=null,I):h:(i.method="throw",i.arg=new TypeError("iterator result is not an object"),i.delegate=null,I)}function pushTryEntry(t){var i={tryLoc:t[0]};1 in t&&(i.catchLoc=t[1]),2 in t&&(i.finallyLoc=t[2],i.afterLoc=t[3]),this.tryEntries.push(i)}function resetTryEntry(t){var i=t.completion||{};i.type="normal",delete i.arg,t.completion=i}function Context(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(pushTryEntry,this),this.reset(!0)}function values(t){if(t){var i=t[h];if(i)return i.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var m=-1,u=function next(){for(;++m<t.length;)if(o.call(t,m))return next.value=t[m],next.done=!1,next;return next.value=void 0,next.done=!0,next};return u.next=u}}return{next:doneResult}}function doneResult(){return{value:void 0,done:!0}}return GeneratorFunction.prototype=GeneratorFunctionPrototype,define(S,"constructor",GeneratorFunctionPrototype),define(GeneratorFunctionPrototype,"constructor",GeneratorFunction),GeneratorFunction.displayName=define(GeneratorFunctionPrototype,v,"GeneratorFunction"),t.isGeneratorFunction=function(t){var i="function"==typeof t&&t.constructor;return!!i&&(i===GeneratorFunction||"GeneratorFunction"===(i.displayName||i.name))},t.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,GeneratorFunctionPrototype):(t.__proto__=GeneratorFunctionPrototype,define(t,v,"GeneratorFunction")),t.prototype=Object.create(S),t},t.awrap=function(t){return{__await:t}},defineIteratorMethods(AsyncIterator.prototype),define(AsyncIterator.prototype,u,(function(){return this})),t.AsyncIterator=AsyncIterator,t.async=function(i,o,m,h,u){void 0===u&&(u=Promise);var v=new AsyncIterator(wrap(i,o,m,h),u);return t.isGeneratorFunction(o)?v:v.next().then((function(t){return t.done?t.value:v.next()}))},defineIteratorMethods(S),define(S,v,"Generator"),define(S,h,(function(){return this})),define(S,"toString",(function(){return"[object Generator]"})),t.keys=function(t){var i=[];for(var o in t)i.push(o);return i.reverse(),function next(){for(;i.length;){var o=i.pop();if(o in t)return next.value=o,next.done=!1,next}return next.done=!0,next}},t.values=values,Context.prototype={constructor:Context,reset:function(t){if(this.prev=0,this.next=0,this.sent=this._sent=void 0,this.done=!1,this.delegate=null,this.method="next",this.arg=void 0,this.tryEntries.forEach(resetTryEntry),!t)for(var i in this)"t"===i.charAt(0)&&o.call(this,i)&&!isNaN(+i.slice(1))&&(this[i]=void 0)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(t){if(this.done)throw t;var i=this;function handle(o,m){return u.type="throw",u.arg=t,i.next=o,m&&(i.method="next",i.arg=void 0),!!m}for(var m=this.tryEntries.length-1;m>=0;--m){var h=this.tryEntries[m],u=h.completion;if("root"===h.tryLoc)return handle("end");if(h.tryLoc<=this.prev){var v=o.call(h,"catchLoc"),I=o.call(h,"finallyLoc");if(v&&I){if(this.prev<h.catchLoc)return handle(h.catchLoc,!0);if(this.prev<h.finallyLoc)return handle(h.finallyLoc)}else if(v){if(this.prev<h.catchLoc)return handle(h.catchLoc,!0)}else{if(!I)throw new Error("try statement without catch or finally");if(this.prev<h.finallyLoc)return handle(h.finallyLoc)}}}},abrupt:function(t,i){for(var m=this.tryEntries.length-1;m>=0;--m){var h=this.tryEntries[m];if(h.tryLoc<=this.prev&&o.call(h,"finallyLoc")&&this.prev<h.finallyLoc){var u=h;break}}u&&("break"===t||"continue"===t)&&u.tryLoc<=i&&i<=u.finallyLoc&&(u=null);var v=u?u.completion:{};return v.type=t,v.arg=i,u?(this.method="next",this.next=u.finallyLoc,I):this.complete(v)},complete:function(t,i){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&i&&(this.next=i),I},finish:function(t){for(var i=this.tryEntries.length-1;i>=0;--i){var o=this.tryEntries[i];if(o.finallyLoc===t)return this.complete(o.completion,o.afterLoc),resetTryEntry(o),I}},catch:function(t){for(var i=this.tryEntries.length-1;i>=0;--i){var o=this.tryEntries[i];if(o.tryLoc===t){var m=o.completion;if("throw"===m.type){var h=m.arg;resetTryEntry(o)}return h}}throw new Error("illegal catch attempt")},delegateYield:function(t,i,o){return this.delegate={iterator:values(t),resultName:i,nextLoc:o},"next"===this.method&&(this.arg=void 0),I}},t}function _typeof(t){return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},_typeof(t)}function _classCallCheck(t,i){if(!(t instanceof i))throw new TypeError("Cannot call a class as a function")}function _defineProperties(t,i){for(var o=0;o<i.length;o++){var m=i[o];m.enumerable=m.enumerable||!1,m.configurable=!0,"value"in m&&(m.writable=!0),Object.defineProperty(t,m.key,m)}}function _createClass(t,i,o){return i&&_defineProperties(t.prototype,i),o&&_defineProperties(t,o),Object.defineProperty(t,"prototype",{writable:!1}),t}function __awaiter(t,i,o,m){function adopt(t){return t instanceof o?t:new o((function(i){i(t)}))}return new(o||(o=Promise))((function(o,h){function fulfilled(t){try{step(m.next(t))}catch(t){h(t)}}function rejected(t){try{step(m.throw(t))}catch(t){h(t)}}function step(t){t.done?o(t.value):adopt(t.value).then(fulfilled,rejected)}step((m=m.apply(t,i||[])).next())}))}var t={isDataReportEnable:!0,maxSize:100,msgListMaxSize:1e3,cacheMaxSize:1e3,maxDelay:3e5,maxInterval:3e4,minInterval:1e4,timeout:5e3,autoStart:!0,loginFailIgnoreInterval:72e5},i=12,o=8e3,m=function emptyFn(){},h=function(){function Reporter(i){_classCallCheck(this,Reporter),this.isUploadEnable=!0,this.serverAllowUpload=!1,this.initConfigLoaded=!1,this.loading=!1,this.isDestroyed=!1,this.reportConfig=t,this.configPath="dispatcher/req",this.dataReportPath="statics/report/common/form",this.traceMsgCache={},this.reqRetryCount=0,this.highPriorityMsgList=[],this.msgList=[],this.lowPriorityMsgList=[],this.cacheMsgList=[],this.lastReportTime=Date.now(),this.timer=null,this.endedAsyncMsgByModule={},this.lastFailLogin={},this.setConfig(i),this.reportConfig.isDataReportEnable&&this.reportConfig.autoStart&&this.initUploadConfig()}return _createClass(Reporter,[{key:"setConfig",value:function setConfig(t){var i=Object.assign({},this.reportConfig.common,t.common);this.reportConfig=Object.assign({},this.reportConfig,t),this.reportConfig.common=i,this.reportConfig.common.sdk_type||(this.reportConfig.common.sdk_type="im")}},{key:"reportImmediately",value:function reportImmediately(t,i){var o=this;this.reportConfig.isDataReportEnable&&this.reportConfig.request(t,Object.assign({dataType:"json",method:"POST",timeout:this.reportConfig.timeout},i)).catch((function(t){var i,m;null===(m=null===(i=o.reportConfig)||void 0===i?void 0:i.logger)||void 0===m||m.warn("Reporter immediately upload failed",t)}))}},{key:"report",value:function report(i,o){var m=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(m.priority||(m.priority=this.getEventPriority(i,o)),this.reportConfig.isDataReportEnable&&i){if("login"===i&&!1===o.succeed&&o.process_id){var h=o.extension&&o.extension.find((function(t){return"TCP"===t.operation_type})),u=h&&h.target||"",v=o.process_id+u,I=this.lastFailLogin[v]||0;if(o.start_time-I<t.loginFailIgnoreInterval)return;this.lastFailLogin[v]=o.start_time}var _=Date.now();"HIGH"===m.priority?this.highPriorityMsgList.push({module:i,msg:o,createTime:_}):"NORMAL"===m.priority?this.msgList.push({module:i,msg:o,createTime:_}):"LOW"===m.priority&&this.lowPriorityMsgList.push({module:i,msg:o,createTime:_}),this.highPriorityMsgList.length>this.reportConfig.msgListMaxSize&&this.highPriorityMsgList.shift(),this.msgList.length>this.reportConfig.msgListMaxSize&&this.msgList.shift(),this.lowPriorityMsgList.length>this.reportConfig.msgListMaxSize&&this.lowPriorityMsgList.shift(),this.doReport()}}},{key:"reportTraceStart",value:function reportTraceStart(t,i){if(this.reportConfig.isDataReportEnable&&t&&!this.traceMsgCache[t]){var o=Object.assign(Object.assign({start_time:Date.now()},i),{extension:[]});this.traceMsgCache[t]=o}}},{key:"reportTraceUpdate",value:function reportTraceUpdate(t){}},{key:"reportTraceUpdateV2",value:function reportTraceUpdateV2(t,i,o){var m,h=this;if(this.reportConfig.isDataReportEnable&&this.traceMsgCache[t]){var u=this.traceMsgCache[t].extension,v=u.length,I=(new Date).getTime();0===v?i.duration=I-this.traceMsgCache[t].start_time:u[v-1].end_time?i.duration=I-u[v-1].end_time:i.duration=I-this.traceMsgCache[t].start_time,u.push(Object.assign({end_time:I},i));var _=u.length-1;(null==o?void 0:o.asyncParams)&&((m=this.traceMsgCache[t]).asyncPromiseArray||(m.asyncPromiseArray=[]),this.traceMsgCache[t].asyncPromiseArray.push(o.asyncParams.then((function(i){h.traceMsgCache[t]&&h.traceMsgCache[t].extension[_]&&Object.assign(h.traceMsgCache[t].extension[_],i)}))))}}},{key:"reportTraceEnd",value:function reportTraceEnd(t){var i,o=this,m=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(this.reportConfig.isDataReportEnable&&this.traceMsgCache[t])if("nos"!==t||!1===m){"boolean"==typeof m?this.traceMsgCache[t].succeed=!!m:this.traceMsgCache[t].state=m,this.traceMsgCache[t].duration=Date.now()-this.traceMsgCache[t].start_time,this.traceMsgCache[t].extension.forEach((function(t){delete t.end_time}));var h=this.traceMsgCache[t];if(this.traceMsgCache[t]=null,h.asyncPromiseArray){(i=this.endedAsyncMsgByModule)[t]||(i[t]=[]),this.endedAsyncMsgByModule[t].push(h);var u=function asyncCallback(){o.endedAsyncMsgByModule[t]&&o.endedAsyncMsgByModule[t].includes(h)&&(delete h.asyncPromiseArray,o.report(t,h,{priority:o.getEventPriority(t,h)}))};Promise.all(h.asyncPromiseArray).then(u).catch(u)}else this.report(t,h,{priority:this.getEventPriority(t,h)})}else this.traceMsgCache[t]=null}},{key:"getEventPriority",value:function getEventPriority(t,i){if("exceptions"===t){if(0===i.action)return"HIGH";if(2===i.action)return"HIGH";if(1===i.action&&0!==i.exception_service)return"HIGH"}else{if("msgReceive"===t)return"LOW";if("nim_api_trace"===t)return"LOW"}return"NORMAL"}},{key:"reportTraceCancel",value:function reportTraceCancel(t){this.reportConfig.isDataReportEnable&&(this.endedAsyncMsgByModule[t]=[],this.traceMsgCache[t]=null)}},{key:"pause",value:function pause(){this.reportConfig.isDataReportEnable&&(this.isUploadEnable=!1)}},{key:"restore",value:function restore(){this.reportConfig.isDataReportEnable&&(this.isUploadEnable=!0,this.initConfigLoaded||this.initUploadConfig())}},{key:"destroy",value:function destroy(){var t=this;this.reportConfig.isDataReportEnable&&(Object.keys(this.traceMsgCache).forEach((function(i){t.reportTraceEnd(i,1)})),null!==this.timer&&clearTimeout(this.timer),this.setConfig=m,this.report=m,this.reportTraceStart=m,this.reportTraceUpdate=m,this.reportTraceEnd=m,this.pause=m,this.restore=m,this.destroy=m,this.reqRetryCount=0,this.cacheMsgList=[],this.traceMsgCache={},this.lowPriorityMsgList=[],this.msgList=[],this.highPriorityMsgList=[],this.reportConfig={},this.isDestroyed=!0)}},{key:"initUploadConfig",value:function initUploadConfig(){var t,m;return __awaiter(this,void 0,void 0,_regeneratorRuntime().mark((function _callee(){var h,u,v,I,_,M=this;return _regeneratorRuntime().wrap((function _callee$(E){for(;;)switch(E.prev=E.next){case 0:if(!this.loading){E.next=2;break}return E.abrupt("return");case 2:this.loading=!0,h=this.reportConfig.common||{},u=this.reportConfig.compassDataEndpoint.split(",").map((function(t){return"".concat(t,"/").concat(M.configPath)})),v=_regeneratorRuntime().mark((function _loop(v){return _regeneratorRuntime().wrap((function _loop$(I){for(;;)switch(I.prev=I.next){case 0:if(!M.initConfigLoaded&&!M.isDestroyed){I.next=2;break}return I.abrupt("return","break");case 2:return I.prev=2,I.next=5,M.reportConfig.request(u[v],{method:"GET",dataType:"json",params:{deviceId:h.dev_id,sdkVer:h.sdk_ver,platform:h.platform,hostEnv:h.host_env,appkey:h.app_key},timeout:M.reportConfig.timeout}).then((function(t){var i,o;if(!M.isDestroyed){if(200===t.status&&t.data&&200===t.data.code){M.initConfigLoaded=!0;var m=t.data.data||{};M.reportConfig.maxSize=m.maxSize>1e3?1e3:m.maxSize,M.reportConfig.maxInterval=m.maxInterval>1e4?1e4:m.maxInterval,M.reportConfig.maxInterval=m.maxInterval<10?10:m.maxInterval,M.reportConfig.minInterval=m.minInterval<2?2:m.minInterval,M.reportConfig.maxDelay=m.maxDelay||300,M.reportConfig.maxInterval=1e3*M.reportConfig.maxInterval,M.reportConfig.minInterval=1e3*M.reportConfig.minInterval,M.reportConfig.maxDelay=1e3*M.reportConfig.maxDelay,m.endpoint?M.dataReportEndpoint=m.endpoint:M.dataReportEndpoint=u[v],M.serverAllowUpload=!0,M.loading=!1,M.reportHeartBeat()}else 200===t.status&&(M.initConfigLoaded=!0);null===(o=null===(i=M.reportConfig)||void 0===i?void 0:i.logger)||void 0===o||o.log("Get reporter upload config success")}})).catch((function(t){var m,h;M.isDestroyed||(M.loading=!1,null===(h=null===(m=M.reportConfig)||void 0===m?void 0:m.logger)||void 0===h||h.error("Get reporter upload config failed",t),M.reqRetryCount<i&&(M.reqRetryCount++,setTimeout((function(){M.isDestroyed||M.initUploadConfig()}),o)))}));case 5:I.next=14;break;case 7:if(I.prev=7,I.t0=I.catch(2),!M.isDestroyed){I.next=11;break}return I.abrupt("return",{v:void 0});case 11:M.loading=!1,null===(m=null===(t=M.reportConfig)||void 0===t?void 0:t.logger)||void 0===m||m.error("Exec reporter request failed",I.t0),M.reqRetryCount<i&&(M.reqRetryCount++,setTimeout((function(){M.isDestroyed||M.initUploadConfig()}),o));case 14:case"end":return I.stop()}}),_loop,null,[[2,7]])})),I=0;case 7:if(!(I<u.length)){E.next=17;break}return E.delegateYield(v(I),"t0",9);case 9:if("break"!==(_=E.t0)){E.next=12;break}return E.abrupt("break",17);case 12:if("object"!==_typeof(_)){E.next=14;break}return E.abrupt("return",_.v);case 14:I++,E.next=7;break;case 17:case"end":return E.stop()}}),_callee,this)})))}},{key:"reportHeartBeat",value:function reportHeartBeat(){var t=this;this.isDestroyed||(this.timer=setTimeout((function(){t.reportHeartBeat()}),this.reportConfig.minInterval),this.doReport())}},{key:"doReport",value:function doReport(){if(!this.isDestroyed){var t=this.highPriorityMsgList.length+this.msgList.length+this.lowPriorityMsgList.length+this.cacheMsgList.length>2*this.reportConfig.maxSize?this.reportConfig.minInterval:this.reportConfig.maxInterval;Date.now()-this.lastReportTime>=t&&this.upload()}}},{key:"getUploadMsg",value:function getUploadMsg(){var t=this,i={},o=Date.now();this.highPriorityMsgList=this.highPriorityMsgList.filter((function(i){return o-i.createTime<t.reportConfig.maxDelay})),this.msgList=this.msgList.filter((function(i){return o-i.createTime<t.reportConfig.maxDelay})),this.lowPriorityMsgList=this.lowPriorityMsgList.filter((function(i){return o-i.createTime<t.reportConfig.maxDelay})),this.cacheMsgList=this.cacheMsgList.filter((function(i){return o-i.createTime<t.reportConfig.maxDelay}));var m=this.highPriorityMsgList.slice(0,this.reportConfig.maxSize);if(this.highPriorityMsgList=this.highPriorityMsgList.slice(m.length),m.length<this.reportConfig.maxSize){var h=this.reportConfig.maxSize-m.length;m=m.concat(this.msgList.slice(0,h)),this.msgList=this.msgList.slice(h)}if(m.length<this.reportConfig.maxSize){var u=this.reportConfig.maxSize-m.length;m=m.concat(this.lowPriorityMsgList.slice(0,u)),this.lowPriorityMsgList=this.lowPriorityMsgList.slice(u)}if(m.length<this.reportConfig.maxSize){var v=this.reportConfig.maxSize-m.length;m=m.concat(this.cacheMsgList.slice(0,v)),this.cacheMsgList=this.cacheMsgList.slice(v)}return m.forEach((function(t){i[t.module]?i[t.module].push(t.msg):i[t.module]=[t.msg]})),{uploadMsgArr:m,uploadMsg:i}}},{key:"upload",value:function upload(){var t,i,o=this;if(this.isUploadEnable&&this.serverAllowUpload&&!(this.lastReportTime&&Date.now()-this.lastReportTime<this.reportConfig.minInterval)){var m=this.getUploadMsg(),h=m.uploadMsgArr,u=m.uploadMsg;if(h.length){this.lastReportTime=Date.now();try{var v="".concat(this.dataReportEndpoint,"/").concat(this.dataReportPath);this.reportConfig.request(v,{dataType:"json",method:"POST",data:{common:this.reportConfig.common,event:u},headers:{sdktype:"im"},timeout:this.reportConfig.timeout}).catch((function(t){var i,m;o.cacheMsgList=o.cacheMsgList.concat(h).slice(0,o.reportConfig.cacheMaxSize),null===(m=null===(i=o.reportConfig)||void 0===i?void 0:i.logger)||void 0===m||m.warn("Reporter upload failed",t)}))}catch(o){null===(i=null===(t=this.reportConfig)||void 0===t?void 0:t.logger)||void 0===i||i.warn("Exec reporter request failed",o)}clearTimeout(this.timer),this.reportHeartBeat()}}}}]),Reporter}();return h}()}));!function(t){t[t.V2NIM_DATA_SYNC_TYPE_LEVEL_FULL=0]="V2NIM_DATA_SYNC_TYPE_LEVEL_FULL",t[t.V2NIM_DATA_SYNC_TYPE_LEVEL_BASIC=1]="V2NIM_DATA_SYNC_TYPE_LEVEL_BASIC"}(i||(i={})),function(t){t[t.V2NIM_DATA_SYNC_TYPE_MAIN=1]="V2NIM_DATA_SYNC_TYPE_MAIN",t[t.V2NIM_DATA_SYNC_TYPE_TEAM_MEMBER=2]="V2NIM_DATA_SYNC_TYPE_TEAM_MEMBER",t[t.V2NIM_DATA_SYNC_TYPE_SUPER_TEAM_MEMBER=3]="V2NIM_DATA_SYNC_TYPE_SUPER_TEAM_MEMBER"}(o||(o={})),function(t){t[t.V2NIM_DATA_SYNC_STATE_WAITING=1]="V2NIM_DATA_SYNC_STATE_WAITING",t[t.V2NIM_DATA_SYNC_STATE_SYNCING=2]="V2NIM_DATA_SYNC_STATE_SYNCING",t[t.V2NIM_DATA_SYNC_STATE_COMPLETED=3]="V2NIM_DATA_SYNC_STATE_COMPLETED"}(m||(m={})),function(t){t[t.V2NIM_CONVERSATION_TYPE_UNKNOWN=0]="V2NIM_CONVERSATION_TYPE_UNKNOWN",t[t.V2NIM_CONVERSATION_TYPE_P2P=1]="V2NIM_CONVERSATION_TYPE_P2P",t[t.V2NIM_CONVERSATION_TYPE_TEAM=2]="V2NIM_CONVERSATION_TYPE_TEAM",t[t.V2NIM_CONVERSATION_TYPE_SUPER_TEAM=3]="V2NIM_CONVERSATION_TYPE_SUPER_TEAM"}(h||(h={})),function(t){t[t.V2NIM_MESSAGE_STATUS_DEFAULT=0]="V2NIM_MESSAGE_STATUS_DEFAULT",t[t.V2NIM_MESSAGE_STATUS_REVOKE=1]="V2NIM_MESSAGE_STATUS_REVOKE",t[t.V2NIM_MESSAGE_STATUS_BACKFILL=2]="V2NIM_MESSAGE_STATUS_BACKFILL"}(u||(u={})),function(t){t[t.V2NIM_FRIEND_MODE_TYPE_ADD=1]="V2NIM_FRIEND_MODE_TYPE_ADD",t[t.V2NIM_FRIEND_MODE_TYPE_APPLY=2]="V2NIM_FRIEND_MODE_TYPE_APPLY"}(v||(v={})),function(t){t[t.V2NIM_FRIEND_ADD_APPLICATION_TYPE_LEGACY=0]="V2NIM_FRIEND_ADD_APPLICATION_TYPE_LEGACY",t[t.V2NIM_FRIEND_ADD_APPLICATION_TYPE_FROM_SELF=1]="V2NIM_FRIEND_ADD_APPLICATION_TYPE_FROM_SELF",t[t.V2NIM_FRIEND_ADD_APPLICATION_TYPE_TO_SELF=2]="V2NIM_FRIEND_ADD_APPLICATION_TYPE_TO_SELF",t[t.V2NIM_FRIEND_ADD_APPLICATION_TYPE_ALL=3]="V2NIM_FRIEND_ADD_APPLICATION_TYPE_ALL"}(I||(I={})),function(t){t[t.V2NIM_FRIEND_ADD_APPLICATION_STATUS_INIT=0]="V2NIM_FRIEND_ADD_APPLICATION_STATUS_INIT",t[t.V2NIM_FRIEND_ADD_APPLICATION_STATUS_AGREED=1]="V2NIM_FRIEND_ADD_APPLICATION_STATUS_AGREED",t[t.V2NIM_FRIEND_ADD_APPLICATION_STATUS_REJECTED=2]="V2NIM_FRIEND_ADD_APPLICATION_STATUS_REJECTED",t[t.V2NIM_FRIEND_ADD_APPLICATION_STATUS_EXPIRED=3]="V2NIM_FRIEND_ADD_APPLICATION_STATUS_EXPIRED",t[t.V2NIM_FRIEND_ADD_APPLICATION_STATUS_DIRECT_ADD=4]="V2NIM_FRIEND_ADD_APPLICATION_STATUS_DIRECT_ADD"}(_||(_={})),function(t){t[t.V2NIM_FRIEND_DELETION_TYPE_BY_SELF=1]="V2NIM_FRIEND_DELETION_TYPE_BY_SELF",t[t.V2NIM_FRIEND_DELETION_TYPE_BY_PEER=2]="V2NIM_FRIEND_DELETION_TYPE_BY_PEER"}(M||(M={})),function(t){t[t.V2NIM_FRIEND_VERIFY_TYPE_ADD=1]="V2NIM_FRIEND_VERIFY_TYPE_ADD",t[t.V2NIM_FRIEND_VERIFY_TYPE_APPLY=2]="V2NIM_FRIEND_VERIFY_TYPE_APPLY",t[t.V2NIM_FRIEND_VERIFY_TYPE_ACCEPT=3]="V2NIM_FRIEND_VERIFY_TYPE_ACCEPT",t[t.V2NIM_FRIEND_VERIFY_TYPE_REJECT=4]="V2NIM_FRIEND_VERIFY_TYPE_REJECT"}(E||(E={})),function(t){t[t.V2NIM_LOGIN_AUTH_TYPE_DEFAULT=0]="V2NIM_LOGIN_AUTH_TYPE_DEFAULT",t[t.V2NIM_LOGIN_AUTH_TYPE_DYNAMIC_TOKEN=1]="V2NIM_LOGIN_AUTH_TYPE_DYNAMIC_TOKEN",t[t.V2NIM_LOGIN_AUTH_TYPE_THIRD_PARTY=2]="V2NIM_LOGIN_AUTH_TYPE_THIRD_PARTY"}(S||(S={})),function(t){t[t.V2NIM_LOGIN_STATUS_LOGOUT=0]="V2NIM_LOGIN_STATUS_LOGOUT",t[t.V2NIM_LOGIN_STATUS_LOGINED=1]="V2NIM_LOGIN_STATUS_LOGINED",t[t.V2NIM_LOGIN_STATUS_LOGINING=2]="V2NIM_LOGIN_STATUS_LOGINING",t[t.V2NIM_LOGIN_STATUS_UNLOGIN=3]="V2NIM_LOGIN_STATUS_UNLOGIN"}(T||(T={})),function(t){t[t.V2NIM_LOGIN_CLIENT_TYPE_UNKNOWN=0]="V2NIM_LOGIN_CLIENT_TYPE_UNKNOWN",t[t.V2NIM_LOGIN_CLIENT_TYPE_ANDROID=1]="V2NIM_LOGIN_CLIENT_TYPE_ANDROID",t[t.V2NIM_LOGIN_CLIENT_TYPE_IOS=2]="V2NIM_LOGIN_CLIENT_TYPE_IOS",t[t.V2NIM_LOGIN_CLIENT_TYPE_PC=4]="V2NIM_LOGIN_CLIENT_TYPE_PC",t[t.V2NIM_LOGIN_CLIENT_TYPE_WP=8]="V2NIM_LOGIN_CLIENT_TYPE_WP",t[t.V2NIM_LOGIN_CLIENT_TYPE_WEB=16]="V2NIM_LOGIN_CLIENT_TYPE_WEB",t[t.V2NIM_LOGIN_CLIENT_TYPE_RESTFUL=32]="V2NIM_LOGIN_CLIENT_TYPE_RESTFUL",t[t.V2NIM_LOGIN_CLIENT_TYPE_MAC_OS=64]="V2NIM_LOGIN_CLIENT_TYPE_MAC_OS",t[t.V2NIM_LOGIN_CLIENT_TYPE_HARMONY_OS=65]="V2NIM_LOGIN_CLIENT_TYPE_HARMONY_OS"}(C||(C={})),function(t){t[t.V2NIM_KICKED_OFFLINE_REASON_CLIENT_EXCLUSIVE=1]="V2NIM_KICKED_OFFLINE_REASON_CLIENT_EXCLUSIVE",t[t.V2NIM_KICKED_OFFLINE_REASON_SERVER=2]="V2NIM_KICKED_OFFLINE_REASON_SERVER",t[t.V2NIM_KICKED_OFFLINE_REASON_CLIENT=3]="V2NIM_KICKED_OFFLINE_REASON_CLIENT",t[t.V2NIM_KICKED_OFFLINE_REASON_CLIENT_QUIETLY=4]="V2NIM_KICKED_OFFLINE_REASON_CLIENT_QUIETLY"}(N||(N={})),function(t){t[t.V2NIM_LOGIN_CLIENT_CHANGE_LIST=1]="V2NIM_LOGIN_CLIENT_CHANGE_LIST",t[t.V2NIM_LOGIN_CLIENT_CHANGE_LOGIN=2]="V2NIM_LOGIN_CLIENT_CHANGE_LOGIN",t[t.V2NIM_LOGIN_CLIENT_CHANGE_LOGOUT=3]="V2NIM_LOGIN_CLIENT_CHANGE_LOGOUT"}(A||(A={})),function(t){t[t.V2NIM_CONNECT_STATUS_DISCONNECTED=0]="V2NIM_CONNECT_STATUS_DISCONNECTED",t[t.V2NIM_CONNECT_STATUS_CONNECTED=1]="V2NIM_CONNECT_STATUS_CONNECTED",t[t.V2NIM_CONNECT_STATUS_CONNECTING=2]="V2NIM_CONNECT_STATUS_CONNECTING",t[t.V2NIM_CONNECT_STATUS_WAITING=3]="V2NIM_CONNECT_STATUS_WAITING"}(O||(O={})),function(t){t[t.NIM_MESSAGE_AI_STREAM_STATUS_STREAMING=-1]="NIM_MESSAGE_AI_STREAM_STATUS_STREAMING",t[t.NIM_MESSAGE_AI_STREAM_STATUS_NONE=0]="NIM_MESSAGE_AI_STREAM_STATUS_NONE",t[t.NIM_MESSAGE_AI_STREAM_STATUS_PLACEHOLDER=1]="NIM_MESSAGE_AI_STREAM_STATUS_PLACEHOLDER",t[t.NIM_MESSAGE_AI_STREAM_STATUS_CANCEL=2]="NIM_MESSAGE_AI_STREAM_STATUS_CANCEL",t[t.NIM_MESSAGE_AI_STREAM_STATUS_UPDATE=3]="NIM_MESSAGE_AI_STREAM_STATUS_UPDATE",t[t.NIM_MESSAGE_AI_STREAM_STATUS_COMPLETE=4]="NIM_MESSAGE_AI_STREAM_STATUS_COMPLETE",t[t.NIM_MESSAGE_AI_STREAM_STATUS_EXCEPTION=5]="NIM_MESSAGE_AI_STREAM_STATUS_EXCEPTION"}(R||(R={})),function(t){t[t.V2NIM_MESSAGE_AI_STREAM_STOP_OP_DEFAULT=0]="V2NIM_MESSAGE_AI_STREAM_STOP_OP_DEFAULT",t[t.V2NIM_MESSAGE_AI_STREAM_STOP_OP_REVOKE=1]="V2NIM_MESSAGE_AI_STREAM_STOP_OP_REVOKE",t[t.V2NIM_MESSAGE_AI_STREAM_STOP_OP_UPDATE=2]="V2NIM_MESSAGE_AI_STREAM_STOP_OP_UPDATE"}(V||(V={})),function(t){t[t.V2NIM_MESSAGE_AI_REGEN_OP_UPDATE=1]="V2NIM_MESSAGE_AI_REGEN_OP_UPDATE",t[t.V2NIM_MESSAGE_AI_REGEN_OP_NEW=2]="V2NIM_MESSAGE_AI_REGEN_OP_NEW"}(k||(k={})),function(t){t[t.V2NIM_MESSAGE_AI_STATUS_UNKNOW=0]="V2NIM_MESSAGE_AI_STATUS_UNKNOW",t[t.V2NIM_MESSAGE_AI_STATUS_AT=1]="V2NIM_MESSAGE_AI_STATUS_AT",t[t.V2NIM_MESSAGE_AI_STATUS_RESPONSE=2]="V2NIM_MESSAGE_AI_STATUS_RESPONSE"}(P||(P={})),function(t){t[t.V2NIM_MESSAGE_TYPE_INVALID=-1]="V2NIM_MESSAGE_TYPE_INVALID",t[t.V2NIM_MESSAGE_TYPE_TEXT=0]="V2NIM_MESSAGE_TYPE_TEXT",t[t.V2NIM_MESSAGE_TYPE_IMAGE=1]="V2NIM_MESSAGE_TYPE_IMAGE",t[t.V2NIM_MESSAGE_TYPE_AUDIO=2]="V2NIM_MESSAGE_TYPE_AUDIO",t[t.V2NIM_MESSAGE_TYPE_VIDEO=3]="V2NIM_MESSAGE_TYPE_VIDEO",t[t.V2NIM_MESSAGE_TYPE_LOCATION=4]="V2NIM_MESSAGE_TYPE_LOCATION",t[t.V2NIM_MESSAGE_TYPE_NOTIFICATION=5]="V2NIM_MESSAGE_TYPE_NOTIFICATION",t[t.V2NIM_MESSAGE_TYPE_FILE=6]="V2NIM_MESSAGE_TYPE_FILE",t[t.V2NIM_MESSAGE_TYPE_AVCHAT=7]="V2NIM_MESSAGE_TYPE_AVCHAT",t[t.V2NIM_MESSAGE_TYPE_TIPS=10]="V2NIM_MESSAGE_TYPE_TIPS",t[t.V2NIM_MESSAGE_TYPE_ROBOT=11]="V2NIM_MESSAGE_TYPE_ROBOT",t[t.V2NIM_MESSAGE_TYPE_CALL=12]="V2NIM_MESSAGE_TYPE_CALL",t[t.V2NIM_MESSAGE_TYPE_CUSTOM=100]="V2NIM_MESSAGE_TYPE_CUSTOM"}(L||(L={})),function(t){t[t.V2NIM_SEARCH_KEYWORD_MATCH_TYPE_OR=0]="V2NIM_SEARCH_KEYWORD_MATCH_TYPE_OR",t[t.V2NIM_SEARCH_KEYWORD_MATCH_TYPE_AND=1]="V2NIM_SEARCH_KEYWORD_MATCH_TYPE_AND"}(w||(w={})),function(t){t[t.V2NIM_SEARCH_DIRECTION_BACKWARD=0]="V2NIM_SEARCH_DIRECTION_BACKWARD",t[t.V2NIM_SEARCH_DIRECTION_FORWARD=1]="V2NIM_SEARCH_DIRECTION_FORWARD"}(D||(D={})),function(t){t[t.V2NIM_MESSAGE_NOTIFICATION_TYPE_UNDEFINED=-1]="V2NIM_MESSAGE_NOTIFICATION_TYPE_UNDEFINED",t[t.V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_INVITE=0]="V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_INVITE",t[t.V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_KICK=1]="V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_KICK",t[t.V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_LEAVE=2]="V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_LEAVE",t[t.V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_UPDATE_TINFO=3]="V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_UPDATE_TINFO",t[t.V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_DISMISS=4]="V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_DISMISS",t[t.V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_APPLY_PASS=5]="V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_APPLY_PASS",t[t.V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_OWNER_TRANSFER=6]="V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_OWNER_TRANSFER",t[t.V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_ADD_MANAGER=7]="V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_ADD_MANAGER",t[t.V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_REMOVE_MANAGER=8]="V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_REMOVE_MANAGER",t[t.V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_INVITE_ACCEPT=9]="V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_INVITE_ACCEPT",t[t.V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_BANNED_TEAM_MEMBER=10]="V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_BANNED_TEAM_MEMBER",t[t.V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_INVITE=401]="V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_INVITE",t[t.V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_KICK=402]="V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_KICK",t[t.V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_LEAVE=403]="V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_LEAVE",t[t.V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_UPDATE_TINFO=404]="V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_UPDATE_TINFO",t[t.V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_DISMISS=405]="V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_DISMISS",t[t.V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_APPLY_PASS=410]="V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_APPLY_PASS",t[t.V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_OWNER_TRANSFER=406]="V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_OWNER_TRANSFER",t[t.V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_ADD_MANAGER=407]="V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_ADD_MANAGER",t[t.V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_REMOVE_MANAGER=408]="V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_REMOVE_MANAGER",t[t.V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_INVITE_ACCEPT=411]="V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_INVITE_ACCEPT",t[t.V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_BANNED_TEAM_MEMBER=409]="V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_BANNED_TEAM_MEMBER"}(U||(U={})),function(t){t[t.V2NIM_MESSAGE_ATTACHMENT_UPLOAD_STATE_UNKNOWN=0]="V2NIM_MESSAGE_ATTACHMENT_UPLOAD_STATE_UNKNOWN",t[t.V2NIM_MESSAGE_ATTACHMENT_UPLOAD_STATE_SUCCESS=1]="V2NIM_MESSAGE_ATTACHMENT_UPLOAD_STATE_SUCCESS",t[t.V2NIM_MESSAGE_ATTACHMENT_UPLOAD_STATE_FAILED=2]="V2NIM_MESSAGE_ATTACHMENT_UPLOAD_STATE_FAILED",t[t.V2NIM_MESSAGE_ATTACHMENT_UPLOAD_STATE_UPLOADING=3]="V2NIM_MESSAGE_ATTACHMENT_UPLOAD_STATE_UPLOADING"}(x||(x={})),function(t){t[t.V2NIM_MESSAGE_SENDING_STATE_UNKNOWN=0]="V2NIM_MESSAGE_SENDING_STATE_UNKNOWN",t[t.V2NIM_MESSAGE_SENDING_STATE_SUCCEEDED=1]="V2NIM_MESSAGE_SENDING_STATE_SUCCEEDED",t[t.V2NIM_MESSAGE_SENDING_STATE_FAILED=2]="V2NIM_MESSAGE_SENDING_STATE_FAILED",t[t.V2NIM_MESSAGE_SENDING_STATE_SENDING=3]="V2NIM_MESSAGE_SENDING_STATE_SENDING"}(B||(B={})),function(t){t[t.V2NIM_QUERY_DIRECTION_DESC=0]="V2NIM_QUERY_DIRECTION_DESC",t[t.V2NIM_QUERY_DIRECTION_ASC=1]="V2NIM_QUERY_DIRECTION_ASC"}($||($={})),function(t){t[t.V2NIM_CLEAR_HISTORY_MODE_ALL=0]="V2NIM_CLEAR_HISTORY_MODE_ALL",t[t.V2NIM_CLEAR_HISTORY_MODE_LOCAL=1]="V2NIM_CLEAR_HISTORY_MODE_LOCAL",t[t.V2NIM_CLEAR_HISTORY_MODE_LOCAL_IRREPARABLY=2]="V2NIM_CLEAR_HISTORY_MODE_LOCAL_IRREPARABLY"}(j||(j={})),function(t){t[t.V2NIM_MESSAGE_REVOKE_TYPE_UNDEFINED=0]="V2NIM_MESSAGE_REVOKE_TYPE_UNDEFINED",t[t.V2NIM_MESSAGE_REVOKE_TYPE_P2P_BOTHWAY=1]="V2NIM_MESSAGE_REVOKE_TYPE_P2P_BOTHWAY",t[t.V2NIM_MESSAGE_REVOKE_TYPE_TEAM_BOTHWAY=2]="V2NIM_MESSAGE_REVOKE_TYPE_TEAM_BOTHWAY",t[t.V2NIM_MESSAGE_REVOKE_TYPE_SUPERTEAM_BOTHWAY=3]="V2NIM_MESSAGE_REVOKE_TYPE_SUPERTEAM_BOTHWAY",t[t.V2NIM_MESSAGE_REVOKE_TYPE_P2P_ONEWAY=4]="V2NIM_MESSAGE_REVOKE_TYPE_P2P_ONEWAY",t[t.V2NIM_MESSAGE_REVOKE_TYPE_TEAM_ONEWAY=5]="V2NIM_MESSAGE_REVOKE_TYPE_TEAM_ONEWAY"}(G||(G={})),function(t){t[t.V2NIM_MESSAGE_PIN_STATE_NOT_PINNED=0]="V2NIM_MESSAGE_PIN_STATE_NOT_PINNED",t[t.V2NIM_MESSAGE_PIN_STATE_PINNED=1]="V2NIM_MESSAGE_PIN_STATE_PINNED",t[t.V2NIM_MESSAGE_PIN_STATE_UPDATED=2]="V2NIM_MESSAGE_PIN_STATE_UPDATED"}(q||(q={})),function(t){t[t.V2NIM_QUICK_COMMENT_STATE_ADD=1]="V2NIM_QUICK_COMMENT_STATE_ADD",t[t.V2NIM_QUICK_COMMENT_STATE_REMOVE=2]="V2NIM_QUICK_COMMENT_STATE_REMOVE"}(H||(H={})),function(t){t[t.V2NIM_CLIENT_ANTISPAM_OPERATE_NONE=0]="V2NIM_CLIENT_ANTISPAM_OPERATE_NONE",t[t.V2NIM_CLIENT_ANTISPAM_OPERATE_REPLACE=1]="V2NIM_CLIENT_ANTISPAM_OPERATE_REPLACE",t[t.V2NIM_CLIENT_ANTISPAM_OPERATE_CLIENT_SHIELD=2]="V2NIM_CLIENT_ANTISPAM_OPERATE_CLIENT_SHIELD",t[t.V2NIM_CLIENT_ANTISPAM_OPERATE_SERVER_SHIELD=3]="V2NIM_CLIENT_ANTISPAM_OPERATE_SERVER_SHIELD"}(z||(z={})),function(t){t[t.V2NIM_SORT_ORDER_DESC=0]="V2NIM_SORT_ORDER_DESC",t[t.V2NIM_SORT_ORDER_ASC=1]="V2NIM_SORT_ORDER_ASC"}(Y||(Y={})),function(t){t[t.P2P_DELETE_MSG=7]="P2P_DELETE_MSG",t[t.TEAM_DELETE_MSG=8]="TEAM_DELETE_MSG",t[t.SUPERTEAM_DELETE_MSG=12]="SUPERTEAM_DELETE_MSG",t[t.P2P_ONE_WAY_DELETE_MSG=13]="P2P_ONE_WAY_DELETE_MSG",t[t.TEAM_ONE_WAY_DELETE_MSG=14]="TEAM_ONE_WAY_DELETE_MSG",t[t.CUSTOM_P2P_MSG=100]="CUSTOM_P2P_MSG",t[t.CUSTOM_TEAM_MSG=101]="CUSTOM_TEAM_MSG",t[t.CUSTOM_SUPERTEAM_MSG=103]="CUSTOM_SUPERTEAM_MSG"}(J||(J={})),function(t){t[t.NIM_MESSAGE_STREAM_STATUS_STREAMING=-1]="NIM_MESSAGE_STREAM_STATUS_STREAMING",t[t.NIM_MESSAGE_STREAM_STATUS_NONE=0]="NIM_MESSAGE_STREAM_STATUS_NONE",t[t.NIM_MESSAGE_STREAM_STATUS_PLACEHOLDER=1]="NIM_MESSAGE_STREAM_STATUS_PLACEHOLDER",t[t.NIM_MESSAGE_STREAM_STATUS_CANCEL=2]="NIM_MESSAGE_STREAM_STATUS_CANCEL",t[t.NIM_MESSAGE_AI_STREAM_STATUS_UPDATE=3]="NIM_MESSAGE_AI_STREAM_STATUS_UPDATE",t[t.NIM_MESSAGE_STREAM_STATUS_COMPLETE=4]="NIM_MESSAGE_STREAM_STATUS_COMPLETE",t[t.NIM_MESSAGE_STREAM_STATUS_EXCEPTION=5]="NIM_MESSAGE_STREAM_STATUS_EXCEPTION"}(K||(K={})),function(t){t[t.V2NIM_MESSAGE_SOURCE_UNKNOWN=0]="V2NIM_MESSAGE_SOURCE_UNKNOWN",t[t.V2NIM_MESSAGE_SOURCE_ONLINE=1]="V2NIM_MESSAGE_SOURCE_ONLINE",t[t.V2NIM_MESSAGE_SOURCE_OFFLINE=2]="V2NIM_MESSAGE_SOURCE_OFFLINE",t[t.V2NIM_MESSAGE_SOURCE_ROAMING=3]="V2NIM_MESSAGE_SOURCE_ROAMING"}(W||(W={})),function(t){t[t.V2NIM_TEAM_MESSAGE_MUTE_MODE_OFF=0]="V2NIM_TEAM_MESSAGE_MUTE_MODE_OFF",t[t.V2NIM_TEAM_MESSAGE_MUTE_MODE_ON=1]="V2NIM_TEAM_MESSAGE_MUTE_MODE_ON",t[t.V2NIM_TEAM_MESSAGE_MUTE_MODE_NORMAL_ON=2]="V2NIM_TEAM_MESSAGE_MUTE_MODE_NORMAL_ON"}(X||(X={})),function(t){t[t.V2NIM_P2P_MESSAGE_MUTE_MODE_OFF=0]="V2NIM_P2P_MESSAGE_MUTE_MODE_OFF",t[t.V2NIM_P2P_MESSAGE_MUTE_MODE_ON=1]="V2NIM_P2P_MESSAGE_MUTE_MODE_ON"}(Q||(Q={})),function(t){t[t.V2NIM_TEAM_JOIN_ACTION_TEAM_TYPE_NORMAL=1]="V2NIM_TEAM_JOIN_ACTION_TEAM_TYPE_NORMAL",t[t.V2NIM_TEAM_JOIN_ACTION_TEAM_TYPE_SUPER=2]="V2NIM_TEAM_JOIN_ACTION_TEAM_TYPE_SUPER",t[t.V2NIM_TEAM_JOIN_ACTION_TEAM_TYPE_ALL=3]="V2NIM_TEAM_JOIN_ACTION_TEAM_TYPE_ALL"}(Z||(Z={})),function(t){t[t.V2NIM_TEAM_MEMBER_ROLE_QUERY_TYPE_ALL=0]="V2NIM_TEAM_MEMBER_ROLE_QUERY_TYPE_ALL",t[t.V2NIM_TEAM_MEMBER_ROLE_QUERY_TYPE_NORMAL=1]="V2NIM_TEAM_MEMBER_ROLE_QUERY_TYPE_NORMAL",t[t.V2NIM_TEAM_MEMBER_ROLE_QUERY_TYPE_MANAGER=2]="V2NIM_TEAM_MEMBER_ROLE_QUERY_TYPE_MANAGER"}(ee||(ee={})),function(t){t[t.V2NIM_TEAM_TYPE_INVALID=0]="V2NIM_TEAM_TYPE_INVALID",t[t.V2NIM_TEAM_TYPE_ADVANCED=1]="V2NIM_TEAM_TYPE_ADVANCED",t[t.V2NIM_TEAM_TYPE_SUPER=2]="V2NIM_TEAM_TYPE_SUPER"}(te||(te={})),function(t){t[t.V2NIM_TEAM_JOIN_MODE_FREE=0]="V2NIM_TEAM_JOIN_MODE_FREE",t[t.V2NIM_TEAM_JOIN_MODE_APPLY=1]="V2NIM_TEAM_JOIN_MODE_APPLY",t[t.V2NIM_TEAM_JOIN_MODE_INVITE=2]="V2NIM_TEAM_JOIN_MODE_INVITE"}(ie||(ie={})),function(t){t[t.V2NIM_TEAM_AGREE_MODE_AUTH=0]="V2NIM_TEAM_AGREE_MODE_AUTH",t[t.V2NIM_TEAM_AGREE_MODE_NO_AUTH=1]="V2NIM_TEAM_AGREE_MODE_NO_AUTH"}(re||(re={})),function(t){t[t.V2NIM_TEAM_INVITE_MODE_MANAGER=0]="V2NIM_TEAM_INVITE_MODE_MANAGER",t[t.V2NIM_TEAM_INVITE_MODE_ALL=1]="V2NIM_TEAM_INVITE_MODE_ALL"}(ne||(ne={})),function(t){t[t.V2NIM_TEAM_UPDATE_INFO_MODE_MANAGER=0]="V2NIM_TEAM_UPDATE_INFO_MODE_MANAGER",t[t.V2NIM_TEAM_UPDATE_INFO_MODE_ALL=1]="V2NIM_TEAM_UPDATE_INFO_MODE_ALL"}(oe||(oe={})),function(t){t[t.V2NIM_TEAM_CHAT_BANNED_MODE_UNBAN=0]="V2NIM_TEAM_CHAT_BANNED_MODE_UNBAN",t[t.V2NIM_TEAM_CHAT_BANNED_MODE_BANNED_NORMAL=1]="V2NIM_TEAM_CHAT_BANNED_MODE_BANNED_NORMAL",t[t.V2NIM_TEAM_CHAT_BANNED_MODE_BANNED_ALL=3]="V2NIM_TEAM_CHAT_BANNED_MODE_BANNED_ALL"}(se||(se={})),function(t){t[t.V2NIM_TEAM_UPDATE_EXTENSION_MODE_MANAGER=0]="V2NIM_TEAM_UPDATE_EXTENSION_MODE_MANAGER",t[t.V2NIM_TEAM_UPDATE_EXTENSION_MODE_ALL=1]="V2NIM_TEAM_UPDATE_EXTENSION_MODE_ALL"}(ae||(ae={})),function(t){t[t.V2NIM_TEAM_MEMBER_ROLE_NORMAL=0]="V2NIM_TEAM_MEMBER_ROLE_NORMAL",t[t.V2NIM_TEAM_MEMBER_ROLE_OWNER=1]="V2NIM_TEAM_MEMBER_ROLE_OWNER",t[t.V2NIM_TEAM_MEMBER_ROLE_MANAGER=2]="V2NIM_TEAM_MEMBER_ROLE_MANAGER"}(ce||(ce={})),function(t){t[t.V2NIM_TEAM_JOIN_ACTION_TYPE_APPLICATION=0]="V2NIM_TEAM_JOIN_ACTION_TYPE_APPLICATION",t[t.V2NIM_TEAM_JOIN_ACTION_TYPE_REJECT_APPLICATION=1]="V2NIM_TEAM_JOIN_ACTION_TYPE_REJECT_APPLICATION",t[t.V2NIM_TEAM_JOIN_ACTION_TYPE_INVITATION=2]="V2NIM_TEAM_JOIN_ACTION_TYPE_INVITATION",t[t.V2NIM_TEAM_JOIN_ACTION_TYPE_REJECT_INVITATION=3]="V2NIM_TEAM_JOIN_ACTION_TYPE_REJECT_INVITATION",t[t.V2NIM_TEAM_JOIN_ACTION_TYPE_ACCEPT_APPLICATION=4]="V2NIM_TEAM_JOIN_ACTION_TYPE_ACCEPT_APPLICATION",t[t.V2NIM_TEAM_JOIN_ACTION_TYPE_ACCEPT_INVITATION=5]="V2NIM_TEAM_JOIN_ACTION_TYPE_ACCEPT_INVITATION"}(de||(de={})),function(t){t[t.V2NIM_TEAM_JOIN_ACTION_STATUS_INIT=0]="V2NIM_TEAM_JOIN_ACTION_STATUS_INIT",t[t.V2NIM_TEAM_JOIN_ACTION_STATUS_AGREED=1]="V2NIM_TEAM_JOIN_ACTION_STATUS_AGREED",t[t.V2NIM_TEAM_JOIN_ACTION_STATUS_REJECTED=2]="V2NIM_TEAM_JOIN_ACTION_STATUS_REJECTED",t[t.V2NIM_TEAM_JOIN_ACTION_STATUS_EXPIRED=3]="V2NIM_TEAM_JOIN_ACTION_STATUS_EXPIRED"}(le||(le={})),function(t){t[t.teamApply=0]="teamApply",t[t.teamApplyReject=1]="teamApplyReject",t[t.teamInvite=2]="teamInvite",t[t.teamInviteReject=3]="teamInviteReject",t[t.tlistUpdate=4]="tlistUpdate",t[t.superTeamApply=15]="superTeamApply",t[t.superTeamApplyReject=16]="superTeamApplyReject",t[t.superTeamInvite=17]="superTeamInvite",t[t.superTeamInviteReject=18]="superTeamInviteReject"}(pe||(pe={})),function(t){t[t.V2NIM_AI_MODEL_TYPE_UNKNOW=0]="V2NIM_AI_MODEL_TYPE_UNKNOW",t[t.V2NIM_AI_MODEL_TYPE_QWEN=1]="V2NIM_AI_MODEL_TYPE_QWEN",t[t.V2NIM_AI_MODEL_TYPE_AZURE=2]="V2NIM_AI_MODEL_TYPE_AZURE",t[t.V2NIM_AI_MODEL_TYPE_PRIVATE=3]="V2NIM_AI_MODEL_TYPE_PRIVATE"}(me||(me={})),function(t){t[t.V2NIM_AI_MODEL_STREAM_CALL_STATUS_NONE=0]="V2NIM_AI_MODEL_STREAM_CALL_STATUS_NONE",t[t.V2NIM_AI_MODEL_STREAM_CALL_STATUS_CANCEL=2]="V2NIM_AI_MODEL_STREAM_CALL_STATUS_CANCEL",t[t.V2NIM_AI_MODEL_STREAM_CALL_STATUS_COMPLETE=4]="V2NIM_AI_MODEL_STREAM_CALL_STATUS_COMPLETE",t[t.V2NIM_AI_MODEL_STREAM_CALL_STATUS_EXCEPTION=5]="V2NIM_AI_MODEL_STREAM_CALL_STATUS_EXCEPTION"}(he||(he={})),function(t){t.V2NIM_AI_MODEL_ROLE_TYPE_SYSTEM="system",t.V2NIM_AI_MODEL_ROLE_TYPE_USER="user",t.V2NIM_AI_MODEL_ROLE_TYPE_ASSISTANT="assistant"}(ue||(ue={})),function(t){t[t.V2NIM_SIGNALLING_EVENT_TYPE_UNKNOWN=0]="V2NIM_SIGNALLING_EVENT_TYPE_UNKNOWN",t[t.V2NIM_SIGNALLING_EVENT_TYPE_CLOSE=1]="V2NIM_SIGNALLING_EVENT_TYPE_CLOSE",t[t.V2NIM_SIGNALLING_EVENT_TYPE_JOIN=2]="V2NIM_SIGNALLING_EVENT_TYPE_JOIN",t[t.V2NIM_SIGNALLING_EVENT_TYPE_INVITE=3]="V2NIM_SIGNALLING_EVENT_TYPE_INVITE",t[t.V2NIM_SIGNALLING_EVENT_TYPE_CANCEL_INVITE=4]="V2NIM_SIGNALLING_EVENT_TYPE_CANCEL_INVITE",t[t.V2NIM_SIGNALLING_EVENT_TYPE_REJECT=5]="V2NIM_SIGNALLING_EVENT_TYPE_REJECT",t[t.V2NIM_SIGNALLING_EVENT_TYPE_ACCEPT=6]="V2NIM_SIGNALLING_EVENT_TYPE_ACCEPT",t[t.V2NIM_SIGNALLING_EVENT_TYPE_LEAVE=7]="V2NIM_SIGNALLING_EVENT_TYPE_LEAVE",t[t.V2NIM_SIGNALLING_EVENT_TYPE_CONTROL=8]="V2NIM_SIGNALLING_EVENT_TYPE_CONTROL",t[t.V2NIM_SIGNALLING_EVENT_TYPE_KICK=9]="V2NIM_SIGNALLING_EVENT_TYPE_KICK"}(ge||(ge={})),function(t){t[t.V2NIM_SIGNALLING_CHANNEL_TYPE_AUDIO=1]="V2NIM_SIGNALLING_CHANNEL_TYPE_AUDIO",t[t.V2NIM_SIGNALLING_CHANNEL_TYPE_VIDEO=2]="V2NIM_SIGNALLING_CHANNEL_TYPE_VIDEO",t[t.V2NIM_SIGNALLING_CHANNEL_TYPE_CUSTOM=3]="V2NIM_SIGNALLING_CHANNEL_TYPE_CUSTOM"}(ve||(ve={})),function(t){t[t.V2NIM_USER_STATUS_TYPE_UNKNOWN=0]="V2NIM_USER_STATUS_TYPE_UNKNOWN",t[t.V2NIM_USER_STATUS_TYPE_LOGIN=1]="V2NIM_USER_STATUS_TYPE_LOGIN",t[t.V2NIM_USER_STATUS_TYPE_LOGOUT=2]="V2NIM_USER_STATUS_TYPE_LOGOUT",t[t.V2NIM_USER_STATUS_TYPE_DISCONNECT=3]="V2NIM_USER_STATUS_TYPE_DISCONNECT"}(fe||(fe={}));var _e={V2NIM_ERROR_CODE_UNKNOWN:{code:0,message:"unknown error"},V2NIM_ERROR_CODE_SUCCESS:{code:200,message:"success"},V2NIM_ERROR_CODE_HANDSHAKE:{code:201,message:"handshake error"},V2NIM_ERROR_CODE_REQUEST_TEMPERARY_FORBIDDEN:{code:398,message:"request temprary forbidden"},V2NIM_ERROR_CODE_SERVER_UNIT_ERROR:{code:399,message:"server unit error"},V2NIM_ERROR_CODE_FORBIDDEN:{code:403,message:"forbidden"},V2NIM_ERROR_CODE_NOT_FOUND:{code:404,message:"not found"},V2NIM_ERROR_CODE_PARAMETER_ERROR:{code:414,message:"parameter error"},V2NIM_ERROR_CODE_RATE_LIMIT_REACHED:{code:416,message:"rate limit reached"},V2NIM_ERROR_CODE_MULTI_LOGIN_FORBIDDEN:{code:417,message:"multi login forbidden"},V2NIM_ERROR_CODE_SERVER_INTERNAL_ERROR:{code:500,message:"server internal error"},V2NIM_ERROR_CODE_SERVER_BUSY:{code:503,message:"server busy"},V2NIM_ERROR_CODE_APP_UNREACHABLE:{code:511,message:"app server unreachable"},V2NIM_ERROR_CODE_SERVICE_UNAVAILABLE:{code:514,message:"service unavailable"},V2NIM_ERROR_CODE_PROTOCOL_BLACKHOLE_FILTERED:{code:599,message:"protocol filtered by blackhole rule"},V2NIM_ERROR_CODE_NO_PERMISSION:{code:997,message:"appid has no permission to call the protocol"},V2NIM_ERROR_CODE_UNPACK_ERROR:{code:998,message:"unpack error"},V2NIM_ERROR_CODE_PACK_ERROR:{code:999,message:"pack error"},V2NIM_ERROR_CODE_IM_DISABLED:{code:101301,message:"IM disabled"},V2NIM_ERROR_CODE_SERVICE_ADDRESS_INVALID:{code:101302,message:"service address invalid"},V2NIM_ERROR_CODE_APPKEY_NOT_EXIST:{code:101303,message:"appkey not exist"},V2NIM_ERROR_CODE_BUNDLEID_CHECK_FAILED:{code:101304,message:"bundleid check failed"},V2NIM_ERROR_CODE_APPKEY_BLOCKED:{code:101403,message:"appkey blocked"},V2NIM_ERROR_CODE_INVALID_TOKEN:{code:102302,message:"invalid token"},V2NIM_ERROR_CODE_ROBOT_NOT_ALLOWED:{code:102303,message:"robot not allowed"},V2NIM_ERROR_CODE_ACCOUNT_NOT_EXIST:{code:102404,message:"account not exist"},V2NIM_ERROR_CODE_ACCOUNT_CHAT_BANNED:{code:102421,message:"account chat banned"},V2NIM_ERROR_CODE_ACCOUNT_BANNED:{code:102422,message:"account banned"},V2NIM_ERROR_CODE_ACCOUNT_IN_BLOCK_LIST:{code:102426,message:"account in block list"},V2NIM_ERROR_CODE_USER_PROFILE_NOT_EXIST:{code:103404,message:"user profile not exist"},V2NIM_ERROR_CODE_USER_PROFILE_HIT_ANTISPAM:{code:103451,message:"user profile hit antispam"},V2NIM_ERROR_CODE_PEER_FRIEND_LIMIT:{code:104301,message:"peer friend limit"},V2NIM_ERROR_CODE_FRIEND_APPLICATION_NOT_EXIST:{code:104302,message:"friend application not exist"},V2NIM_ERROR_CODE_FRIEND_NOT_EXIST:{code:104404,message:"friend not exist"},V2NIM_ERROR_CODE_FRIEND_ALREADY_EXIST:{code:104405,message:"friend already exist"},V2NIM_ERROR_CODE_SELF_FRIEND_OPERATION_NOT_ALLOWED:{code:104429,message:"self friend operation not allowed"},V2NIM_ERROR_CODE_FRIEND_LIMIT:{code:104435,message:"friend limit"},V2NIM_ERROR_CODE_FRIEND_OPERATION_RATE_LIMIT:{code:104449,message:"friend operation rate limit"},V2NIM_ERROR_CODE_FRIEND_HIT_ANTISPAM:{code:104451,message:"friend hit antispam"},V2NIM_ERROR_CODE_SELF_MUTE_OPERATION_NOT_ALLOWED:{code:105429,message:"self mute operation not allowed"},V2NIM_ERROR_CODE_MUTE_LIST_LIMIT:{code:105435,message:"mute list limit"},V2NIM_ERROR_CODE_SELF_BLOCK_LIST_OPERATION_NOT_ALLOWED:{code:106429,message:"self block list operation not allowed"},V2NIM_ERROR_CODE_BLOCK_LIST_LIMIT:{code:106435,message:"block list limit"},V2NIM_ERROR_CODE_REVOKE_THIRD_PARTY_MESSAGE_NOT_ALLOWED:{code:107301,message:"revoke third party message not allowed"},V2NIM_ERROR_CODE_SHORT_TO_LONG_URL_FAILED:{code:107307,message:"short to long URL failed"},V2NIM_ERROR_CODE_URL_INVALID:{code:107308,message:"URL invalid"},V2NIM_ERROR_CODE_DURATION_OUT_OF_RANGE:{code:107309,message:"duration out of range"},V2NIM_ERROR_CODE_GET_FILE_META_INFO_FAILED:{code:107310,message:"get file meta info failed"},V2NIM_ERROR_CODE_AUDIO_FILE_SIZE_LIMIT:{code:107311,message:"audio file size limit"},V2NIM_ERROR_CODE_VOICE_TO_TEXT_TIMEOUT:{code:107312,message:"voice to text timeout"},V2NIM_ERROR_CODE_VOICE_TO_TEXT_FAILED:{code:107313,message:"voice to text failed"},V2NIM_ERROR_CODE_REVOKE_EXCEED_TIME_LIMIT:{code:107314,message:"revoke message exceed time limit"},V2NIM_ERROR_CODE_REVOKE_MESSAGE_NOT_ALLOWED:{code:107315,message:"revoke specific message not allowed"},V2NIM_ERROR_CODE_FORCE_PUSH_LIST_LIMIT:{code:107316,message:"force push list limit"},V2NIM_ERROR_CODE_TEAM_MESSAGE_RECEIPT_RATE_LIMIT:{code:107317,message:"team message receipt rate limit"},V2NIM_ERROR_CODE_SNAPSHOT_NOT_EXIST:{code:107318,message:"snapshot not exist"},V2NIM_ERROR_CODE_PIN_LIMIT:{code:107319,message:"pin limit"},V2NIM_ERROR_CODE_PIN_NOT_EXIST:{code:107320,message:"pin not exist"},V2NIM_ERROR_CODE_QUICK_COMMENT_LIMIT:{code:107321,message:"quick comment limit"},V2NIM_ERROR_CODE_PIN_ALREADY_EXIST:{code:107322,message:"pin already exist"},V2NIM_ERROR_CODE_VOICE_TO_TEXT_FUNCTION_DISABLED:{code:107333,message:"voice to text function disabled"},V2NIM_ERROR_CODE_CLOUD_SEARCH_FUNCTION_DISABLED:{code:107334,message:"cloud search function disabled"},V2NIM_ERROR_CODE_ONE_WAY_DELETE_FUNCTION_DISABLED:{code:107335,message:"one-way delete function disabled"},V2NIM_ERRPR_CODE_ONEWAY_DELETION_NOT_ALLOW_FOR_TARGET_MESSAGES:{code:107338,message:"one-way deletion is not allowed for target messages"},V2NIM_ERRPR_CODE_SENDER_CANNOT_INCLUDED_IN_TARGET_LIST:{code:107339,message:"The message sender cannot be included in the target list"},V2NIM_ERROR_CODE_ROBOT_CANNOT_SEND_TARGET_MESSAGE:{code:107340,message:"Robot can not send target message"},V2NIM_ERROR_CODE_PIN_TARGET_MESSAGE_NOT_ALLOWED:{code:107345,message:"Pin target message is not allowed"},V2NIM_ERROR_CODE_TARGET_MESSAGE_NOT_ALLOWED_REPLY:{code:107346,message:"Target message not allowed reply"},V2NIM_ERROR_CODE_TARGET_MESSAGE_NOT_ALLOWED_QUICK_COMMENT:{code:107347,message:"Target message not allowed quick comment"},V2NIM_ERROR_CODE_REVOKE_MESSAGE_TO_SELF_NOT_ALLOWED:{code:107429,message:"revoke message to self not allowed"},V2NIM_ERROR_CODE_APP_CHAT_BANNED:{code:107410,message:"app chat banned"},V2NIM_ERROR_CODE_QUICK_COMMENT_FUNCTION_DISABLED:{code:107326,message:"quick comment function disabled"},V2NIM_ERROR_CODE_PIN_FUNCTION_DISABLED:{code:107327,message:"PIN function disabled"},V2NIM_ERROR_CODE_TEAM_READ_RECEIPT_FUNCTION_DISABLED:{code:107324,message:"read receipt for team messages function disabled"},V2NIM_ERROR_CODE_P2P_READ_RECEIPT_FUNCTION_DISABLED:{code:107325,message:"read receipt for p2p messages function disabled"},V2NIM_ERROR_CODE_RATE_LIMIT_FOR_MESSAGING_REACHED:{code:107323,message:"rate limit for messaging reached"},V2NIM_ERROR_CODE_MESSAGE_HIT_ANTISPAM:{code:107451,message:"message hit antispam"},V2NIM_ERROR_CODE_MESSAGE_NOT_EXIST:{code:107404,message:"message not exist"},V2NIM_ERROR_CODE_UNSENDING_MESSAGE_EXPIRED:{code:107406,message:"unsending message expired"},V2NIM_ERROR_CODE_TEAM_MARK_READ_FAILED:{code:107302,message:"sending message failed for marking message read failed for too many team members"},V2NIM_ERROR_CODE_SENDER_OR_MANAGER_PERMISSION_ONLY_REVOKE:{code:107303,message:"only sender or manager can revoke message"},V2NIM_ERROR_CODE_DELETE_SELF_MESSAGE_NOT_ALLOWED:{code:107328,message:"delete self message not allowed"},V2NIM_ERROR_CODE_NOT_CHATBOT_ACCOUNT:{code:107329,message:"is not chatbot account"},V2NIM_ERROR_CODE_MESSAGE_SENSE_REQUIRED:{code:107330,message:"sender or receiver must sense message"},V2NIM_ERROR_CODE_HIGH_PRIORITY_MESSAGE_RATE_LIMIT:{code:107304,message:"rate limit of high-priority messages exceeded"},ACK_MESSAGE_BE_HIGH_PRIORITY:{code:107305,message:"ack message should be high-priority"},V2NIM_ERROR_CODE_DUPLICATE_CLIENT_MESSAGE_ID:{code:107306,message:"duplicate client message ID"},V2NIM_ERROR_CODE_INVALID_TIME_RANGE:{code:107439,message:"invalid time range"},V2NIM_ERROR_CODE_NOT_ADVANCED_TEAM:{code:108302,message:"not advanced team"},V2NIM_ERROR_CODE_TEAM_MANAGER_LIMIT:{code:108303,message:"team manager limit"},V2NIM_ERROR_CODE_JOINED_TEAM_LIMIT:{code:108305,message:"joined team limit"},V2NIM_ERROR_CODE_TEAM_NORMAL_MEMBER_CHAT_BANNED:{code:108306,message:"team normal member chat banned"},V2NIM_ERROR_CODE_INVITED_ACCOUNT_NOT_FRIEND:{code:108307,message:"invited account not friend"},V2NIM_ERROR_CODE_REJECT_ALL_TEAM_APPLICATIONS:{code:108308,message:"reject all team applications"},V2NIM_ERROR_CODE_TARGETING_MESSAGE_FOR_TEAM_DISABLED:{code:108318,message:"Targeting messages for group chat is disabled"},V2NIM_ERROR_CODE_INCLUSIVE_AS_FALSE_NOT_ALLOWED_FOR_SUPER_TEAM:{code:108319,message:'Setting "inclusive" to false for super teams is not allowed'},V2NIM_ERROR_CODE_CANNOT_MAKE_SUPER_TEAM_MESSAGE_VISIBLE_TO_NEW_MEMBERS:{code:108320,message:"Cannot make super team targeted messages visible to new members"},V2NIM_ERROR_CODE_CANNOT_ALLOW_TARGETED_MESSAGES_INCLUSIVE_TO_NEW_MEMBERS:{code:108321,message:"Cannot allow targeted messages inclusive to new members"},V2NIM_ERROR_CODE_TEAM_NOT_EXIST:{code:108404,message:"team not exist"},V2NIM_ERROR_CODE_TEAM_ALREADY_CHAT_BANNED:{code:108420,message:"team already chat banned"},V2NIM_ERROR_CODE_ALL_TEAM_MEMBER_CHAT_BANNED:{code:108423,message:"all team member chat banned"},V2NIM_ERROR_CODE_EXTENDED_SUPER_TEAM_LIMIT:{code:108434,message:"extended super team limit"},V2NIM_ERROR_CODE_CREATED_TEAM_LIMIT:{code:108435,message:"created team limit"},V2NIM_ERROR_CODE_TEAM_INVITATION_LIMIT:{code:108437,message:"team invitation limit"},V2NIM_ERROR_CODE_TEAM_HIT_ANTISPAM:{code:108451,message:"team hit antispam"},V2NIM_ERROR_CODE_EXTENDED_SUPER_TEAM_LIMIT_NOT_CONFIGURED:{code:108304,message:"extended super team limit not configured"},V2NIM_ERROR_CODE_SUPER_TEAM_SERVICE_DISABLED:{code:108311,message:"super team service disabled"},V2NIM_ERROR_CODE_TEAM_READ_RECEIPT_RECORD_NOT_FOUND:{code:108301,message:"read receipt record for the team message not found"},V2NIM_ERROR_CODE_NOT_MANAGER:{code:108430,message:"unable to assign owner manager"},V2NIM_ERROR_CODE_ONLINE_MEMBER_COUNT_DISABLED:{code:108406,message:"number of online users service disabled"},V2NIM_ERROR_CODE_TRANSFER_DISABLED:{code:108310,message:"unable to transfer the ownership to owner"},V2NIM_ERROR_CODE_CREATE_TEAM_DISABLED:{code:108309,message:"unable to create team with more than %s people"},V2NIM_ERROR_CODE_EXTENDED_SUPER_TEAM_CREATE_FAILED:{code:108313,message:"/ extended super team creation failed,use open api to create the team"},V2NIM_ERROR_CODE_TEAM_MESSAGE_READ_RECEIPT_DISABLED:{code:108312,message:"read receipt for team messages function disabled"},V2NIM_ERROR_CODE_RETRY:{code:108449,message:"an error occurred, try again"},V2NIM_ERROR_CODE_CHAT_BAN_LIST_CONTAIN_NOT_TEAM_MEMBER:{code:109301,message:"list of chat banned users contains non team members"},V2NIM_ERROR_CODE_CHAT_BAN_LIST_CONTAIN_OPERATOR:{code:109303,message:"list of chat banned users contains the operator"},V2NIM_ERROR_CODE_CHAT_BAN_LIST_CONTAIN_TEAM_OWNER:{code:109304,message:"list of chat banned users contains the team owner"},V2NIM_ERROR_CODE_OPERATION_ON_TEAM_MANAGER_NOT_ALLOWED:{code:109305,message:"operation on team manager not allowed"},V2NIM_ERROR_CODE_NO_TEAM_INVITE_PERMISSION:{code:109306,message:"no team invite permission"},V2NIM_ERROR_CODE_TEAM_OWNER_QUIT_NOT_ALLOWED:{code:109307,message:"team owner quit not allowed"},V2NIM_ERROR_CODE_TEAM_OWNER_IN_KICK_LIST:{code:109308,message:"list of kicked user contains the team owner"},V2NIM_ERROR_CODE_INVITE_ROBOT_ACCOUNT_NOT_ALLOWED:{code:109309,message:"invite robot account not allowed"},V2NIM_ERROR_CODE_KICK_OPERATOR_NOT_ALLOWED:{code:109310,message:"kick operator not allowed"},V2NIM_ERROR_CODE_TEAM_MEMBER_ALREADY_EXIST:{code:109311,message:"team member already exist"},V2NIM_ERROR_CODE_TEAM_INVITATION_OR_APPLICATION_NOT_EXIST:{code:109313,message:"team invitation or application not exist"},V2NIM_ERROR_CODE_OPERATION_ON_TEAM_OWNER_NOT_ALLOWED:{code:109314,message:"operation on team owner not allowed"},V2NIM_ERROR_CODE_FORCED_PUSH_LIST_INCLUDES_NON_TARGETED_ACCOUNTS:{code:109318,message:"The forced push list includes non-targeted accounts"},V2NIM_ERROR_CODE_TEAM_MEMBER_NOT_EXIST:{code:109404,message:"team member not exist"},V2NIM_ERROR_CODE_TEAM_MEMBER_CHAT_BANNED:{code:109424,message:"team member chat banned"},V2NIM_ERROR_CODE_TEAM_OWNER_OPERATION_PERMISSION_REQUIRED:{code:109427,message:"team owner operation permission required"},V2NIM_ERROR_CODE_TEAM_OWNER_OR_MANAGER_OPERATION_PERMISSION_REQUIRED:{code:109432,message:"team owner or manager operation permission required"},V2NIM_ERROR_CODE_TEAM_MEMBER_CONCURRENT_OPERATION_FAILED:{code:109449,message:"team member concurrent operation failed"},V2NIM_ERROR_CODE_TEAM_MEMBER_HIT_ANTISPAM:{code:109451,message:"team member hit antispam"},V2NIM_ERROR_CODE_CONVERSATION_AND_ACCOUNT_MISMATCH:{code:110302,message:"conversation and account mismatch"},V2NIM_ERROR_CODE_CONVERSATION_STICK_TOP_LIMIT:{code:110303,message:"conversation stick top limit"},V2NIM_ERROR_CODE_CONVERSATION_BELONGED_GROUP_LIMIT:{code:110304,message:"conversation belonged group limit"},V2NIM_ERROR_CODE_CONVERSATION_IS_NOT_STICK_TOP:{code:110305,message:"conversation is not stick top"},V2NIM_ERROR_CODE_STICK_TOP_DISABLED:{code:110306,message:"conversation stick top disabled"},V2NIM_ERROR_CODE_CONVERSATION_NOT_EXIST:{code:110404,message:"conversation not exist"},V2NIM_ERROR_CODE_CHATROOM_LINK_UNAVAILABLE:{code:113304,message:"chatroom link unavailable"},V2NIM_ERROR_CODE_IM_CONNECTION_ABNORMAL:{code:113305,message:"IM connection abnormal"},V2NIM_ERROR_CODE_CHATROOM_NOT_EXIST:{code:113404,message:"chatroom not exist"},V2NIM_ERROR_CODE_CHATROOM_CLOSED:{code:113406,message:"chatroom closed"},V2NIM_ERROR_CODE_CHATROOM_REPEATED_OPERATION:{code:113409,message:"chatroom repeated operation"},V2NIM_ERROR_CODE_CHATROOM_DISABLED:{code:113410,message:"chatroom disabled"},V2NIM_ERROR_CODE_ALL_CHATROOM_MEMBER_CHAT_BANNED:{code:113423,message:"all chatroom member chat banned"},V2NIM_ERROR_CODE_CHATROOM_HIT_ANTISPAM:{code:113451,message:"chatroom hit antispam"},V2NIM_ERROR_CODE_ANONYMOUS_MEMBER_FORBIDDEN:{code:114303,message:"anonymous member forbidden"},V2NIM_ERROR_CODE_CHATROOM_MEMBER_NOT_EXIST:{code:114404,message:"chatroom member not exist"},V2NIM_ERROR_CODE_CHATROOM_MEMBER_REPEATED_OPERATION:{code:114405,message:"chatroom member repeated operation"},V2NIM_ERROR_CODE_CHATROOM_MEMBER_CHAT_BANNED:{code:114421,message:"chatroom member chat banned"},V2NIM_ERROR_CODE_ACCOUNT_IN_CHATROOM_BLOCK_LIST:{code:114426,message:"account in chatroom block list"},V2NIM_ERROR_CODE_CHATROOM_OWNER_OPERATION_PERMISSION_REQUIRED:{code:114427,message:"chatroom owner operation permission required"},V2NIM_ERROR_CODE_SELF_IN_CHATROOM_MEMBER_OPERATION_LIST:{code:114429,message:"self in chatroom member operation list"},V2NIM_ERROR_CODE_CHATROOM_OWNER_OR_MANAGER_OPERATION_PERMISSION_REQUIRED:{code:114432,message:"chatroom owner or manager operation permission required"},V2NIM_ERROR_CODE_CHATROOM_MEMBER_LIMIT:{code:114437,message:"chatroom member limit"},V2NIM_ERROR_CODE_CHATROOM_MEMBER_CONCURRENT_OPERATION_FAILED:{code:114449,message:"chatroom member concurrent operation failed"},V2NIM_ERROR_CODE_CHATROOM_MEMBER_HIT_ANTISPAM:{code:114451,message:"chatroom member hit antispam"},V2NIM_ERROR_CODE_CONVERSATION_GROUP_NOT_EXIST:{code:116404,message:"conversation group not exist"},V2NIM_ERROR_CODE_CONVERSATION_GROUP_LIMIT:{code:116435,message:"conversation group limit"},V2NIM_ERROR_CODE_CONVERSATIONS_IN_GROUP_LIMIT:{code:116437,message:"conversations in group limit"},V2NIM_ERROR_CODE_COLLECTION_LIMIT:{code:189301,message:"collection limit"},V2NIM_ERROR_CODE_COLLECTION_NOT_EXIST:{code:189302,message:"collection not exist"},V2NIM_ERROR_CODE_COLLECTION_CONCURRENT_OPERATION_FAILED:{code:189449,message:"collection concurrent operation failed"},V2NIM_ERROR_CODE_INTERNAL:{code:190001,message:"internal error"},V2NIM_ERROR_CODE_ILLEGAL_STATE:{code:190002,message:"illegal state"},V2NIM_ERROR_CODE_MISUSE:{code:191001,message:"misuse"},V2NIM_ERROR_CODE_CANCELLED:{code:191002,message:"operation cancelled"},V2NIM_ERROR_CODE_CALLBACK_FAILED:{code:191003,message:"callback failed"},V2NIM_ERROR_CODE_INVALID_PARAMETER:{code:191004,message:"invalid parameter"},V2NIM_ERROR_CODE_TIMEOUT:{code:191005,message:"timeout"},V2NIM_ERROR_CODE_RESOURCE_NOT_EXIST:{code:191006,message:"resource not exist"},V2NIM_ERROR_CODE_RESOURCE_ALREADY_EXIST:{code:191007,message:"resource already exist"},V2NIM_ERROR_CODE_CONNECT_FAILED:{code:192001,message:"connect failed"},V2NIM_ERROR_CODE_CONNECT_TIMEOUT:{code:192002,message:"connect timeout"},V2NIM_ERROR_CODE_DISCONNECT:{code:192003,message:"disconnect"},V2NIM_ERROR_CODE_PROTOCOL_TIMEOUT:{code:192004,message:"protocol timeout"},V2NIM_ERROR_CODE_PROTOCOL_SEND_FAILED:{code:192005,message:"protocol send failed"},V2NIM_ERROR_CODE_REQUEST_FAILED:{code:192006,message:"request failed"},V2NIM_ERROR_CODE_FILE_NOT_FOUND:{code:194001,message:"file not found"},V2NIM_ERROR_CODE_FILE_CREATE_FAILED:{code:194002,message:"file create failed"},V2NIM_ERROR_CODE_FILE_OPEN_FAILED:{code:194003,message:"file open failed"},V2NIM_ERROR_CODE_FILE_WRITE_FAILED:{code:194004,message:"file write failed"},V2NIM_ERROR_CODE_FILE_READ_FAILED:{code:194005,message:"file read failed"},V2NIM_ERROR_CODE_FILE_UPLOAD_FAILED:{code:194006,message:"file upload failed"},V2NIM_ERROR_CODE_FILE_DOWNLOAD_FAILED:{code:194007,message:"file download failed"},V2NIM_ERROR_CODE_CLIENT_ANTISPAM:{code:195001,message:"client anti-spam"},V2NIM_ERROR_CODE_SERVER_ANTISPAM:{code:195002,message:"server anti-spam"},V2NIM_ERROR_CODE_STREAM_OUTPUT_STOPPED:{code:189318,message:"Streaming text response stopped"},V2NIM_ERROR_CODE_STREAM_OUTPUT_GENERATED:{code:189319,message:"Streaming text response generated"},V2NIM_ERROR_CODE_STREAM_OUTPUT_ABORTED:{code:189320,message:"Streaming text response aborted due to exception"},V2NIM_ERROR_CODE_INTERRUPTION_REJECTED:{code:189321,message:"Non-streaming messages cannot be interrupted"}},Me=Object.keys(_e),Ee=Me.reduce((function(t,i){var o=_e[i];return t[i]=o.code,t}),{}),Se=Me.reduce((function(t,i){var o=_e[i];return t[o.code]=o.message,t}),{}),Te=Object.freeze({__proto__:null,V2NIMErrorCode:Ee,V2NIMErrorDesc:Se,get V2NIMDataSyncLevel(){return i},get V2NIMDataSyncType(){return o},get V2NIMDataSyncState(){return m},get V2NIMConversationType(){return h},get V2NIMLastMessageState(){return u},get V2NIMFriendAddMode(){return v},get V2NIMFriendAddApplicationType(){return I},get V2NIMFriendAddApplicationStatus(){return _},get V2NIMFriendDeletionType(){return M},get V2NIMFriendVerifyType(){return E},get V2NIMLoginAuthType(){return S},get V2NIMLoginStatus(){return T},get V2NIMLoginClientType(){return C},get V2NIMKickedOfflineReason(){return N},get V2NIMLoginClientChange(){return A},get V2NIMConnectStatus(){return O},get V2NIMMessageType(){return L},get V2NIMMessageNotificationType(){return U},get V2NIMMessageAttachmentUploadState(){return x},get V2NIMMessageSendingState(){return B},get V2NIMQueryDirection(){return $},get V2NIMMessageRevokeType(){return G},get V2NIMMessagePinState(){return q},get V2NIMMessageQuickCommentType(){return H},get V2NIMClientAntispamOperateType(){return z},get V2NIMSortOrder(){return Y},get V2NIMSystemMessageType(){return J},get V2NIMMessageAIStreamStatus(){return R},get V2NIMMessageAIStreamStopOpType(){return V},get V2NIMMessageAIRegenOpType(){return k},get V2NIMMessageAIStatus(){return P},get V2NIMSearchKeywordMatchType(){return w},get V2NIMClearHistoryMode(){return j},get V2NIMMessageStreamStatus(){return K},get V2NIMTeamMessageMuteMode(){return X},get V2NIMP2PMessageMuteMode(){return Q},get V2NIMTeamMemberRoleQueryType(){return ee},get V2NIMTeamType(){return te},get V2NIMTeamJoinMode(){return ie},get V2NIMTeamAgreeMode(){return re},get V2NIMTeamInviteMode(){return ne},get V2NIMTeamUpdateInfoMode(){return oe},get V2NIMTeamChatBannedMode(){return se},get V2NIMTeamUpdateExtensionMode(){return ae},get V2NIMTeamJoinActionType(){return de},get V2NIMTeamJoinActionStatus(){return le},get V2NIMTeamNotificationType(){return pe},get V2NIMTeamMemberRole(){return ce},get V2NIMTeamJoinActionTeamType(){return Z},get V2NIMAIModelRoleType(){return ue},get V2NIMAIModelType(){return me},get V2NIMAIModelStreamCallStatus(){return he},get V2NIMSignallingChannelType(){return ve},get V2NIMSignallingEventType(){return ge},get V2NIMUserStatusType(){return fe}});class V2NIMErrorImpl extends Error{constructor(t){super(t.desc),this.name="V2NIMError",this.code=t.code||0,this.desc=t.desc||Se[this.code]||Ce[this.code]||"",this.message=this.desc,this.detail=t.detail||{}}toString(){var t,i=`${this.name}\n code: ${this.code}\n message: "${this.message}"\n detail: ${this.detail?JSON.stringify(this.detail):""}`;return(null===(t=null==this?void 0:this.detail)||void 0===t?void 0:t.rawError)&&(i+=`\n rawError: ${this.detail.rawError.message}`),i}}class ValidateError extends V2NIMErrorImpl{constructor(t,i={},o){super({code:Ee.V2NIM_ERROR_CODE_PARAMETER_ERROR,detail:{reason:t,rules:o,data:i}}),this.name="validateError",this.message=this.message+"\n"+JSON.stringify(this.detail,null,2),this.data=i,this.rules=o}}class ValidateErrorV2 extends V2NIMErrorImpl{constructor(t){var i,o,m;super({code:Ee.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:null===(i=t.detail)||void 0===i?void 0:i.reason,rules:null===(o=t.detail)||void 0===o?void 0:o.rules,data:null===(m=t.detail)||void 0===m?void 0:m.data}}),this.name="ValidateErrorV2"}}class UploadError extends V2NIMErrorImpl{constructor(t){super(Object.assign({code:400},t)),this.desc=this.desc||"upload file error",this.message=this.desc,this.name="uploadError"}}var Ce={200:null,406:null,808:null,810:null,302:"The user name or password is incorrect.",405:"Parameter length too long",408:"Client request timed out",415:"Client network unavailable",422:"Account disabled",508:"Expiration date",509:"Invalid",7101:"Be pulled black",700:"Partial failure of batch operation",801:"The number of people in the team has reached the upper limit",802:"No permission",803:"The team does not exist or has not changed",804:"The user is not in the team",805:"Team type mismatch",806:"The number of teams created has reached the limit",807:"Team member not valid",809:"Already in the team",811:"The number of accounts in the forced push list exceeds the limit",812:"The team is muted",813:"Due to the limited number of team, some pull people successfully",814:"Disable team message read service",815:"Maximum number of team administrators",816:"Batch operation partial failure",9102:"Channel failure",9103:"This call has been answered / rejected at another end",10201:"Signaling: target NIM client is offline",10202:"Signaling: push is unreachable",10404:"Signaling: channel not exists",10405:"Signaling: channel already exists",10406:"Signaling: member of channel not exists",10407:"Signaling: member of channel already exists",10408:"Signaling: the invitation request does not exist or has expired",10409:"Signaling: the invitation request has been rejected",10410:"Signaling: the invitation request has been accepted",10414:"Signaling: request parameter error",10417:"Signaling: uid conflict",10419:"Signaling: the number of members of channel exceed the limit",10420:"Signaling: member is already in the channel on other client",10700:"Signaling: phased success",13002:"Abnormal chatroom status",13003:"In the blacklist",13004:"In the mute list",13006:"All members are muted, and only the administrator can speak"};function replacer(t,i){return i instanceof RegExp?"__REGEXP "+i.toString():i}function validate(t,i={},o,m=!1){var h={};return Object.keys(t).forEach((u=>{var v=t[u].type,I=o?`In ${o}, `:"";if(null==i){var _=`${I}param is null or undefined`;throw m?new ValidateErrorV2({detail:{reason:_,data:{key:u},rules:"required"}}):new ValidateError(_,{key:u},"required")}if(void 0===i[u]){if(!1===t[u].required)return void(h[u]=i[u]);var M=`${I}param '${u}' is required`;throw m?new ValidateErrorV2({detail:{reason:M,data:{key:u},rules:"required"}}):new ValidateError(M,{key:u},"required")}var E=Ne[v];if(E&&!E(i,u,t[u],m)){var S=`${I}param '${u}' unexpected`,T={key:u,value:i[u]};throw m?new ValidateErrorV2({detail:{reason:S,data:T,rules:JSON.stringify(t[u],replacer)}}):new ValidateError(S,T,JSON.stringify(t[u],replacer))}h[u]=i[u]})),h}var Ne={string:function(t,i,o){var{allowEmpty:m,max:h,min:u,regExp:v}=o,I=t[i];return"string"==typeof I&&((!1!==m||""!==I)&&(!("number"==typeof h&&I.length>h)&&(!("number"==typeof u&&I.length<u)&&!(function isRegExp(t){return"[object RegExp]"===Object.prototype.toString.call(t)}(v)&&!v.test(I)))))},number:function(t,i,o){var{min:m,max:h}=o,u=t[i];return"number"==typeof u&&(!("number"==typeof m&&u<m)&&!("number"==typeof h&&u>h))},boolean:function(t,i){return"boolean"==typeof t[i]},file:function(t,i){return!0},enum:function(t,i,o){var{values:m}=o,h=t[i];return!m||m.indexOf(h)>-1},jsonstr:function(t,i){try{var o=JSON.parse(t[i]);return"object"==typeof o&&null!==o}catch(t){return!1}},func:function(t,i){return"function"==typeof t[i]},array:function(t,i,o,m=!1){var{itemType:h,itemRules:u,rules:v,min:I,max:_,values:M}=o,E=t[i];if(!Array.isArray(E))return!1;if("number"==typeof _&&E.length>_)return!1;if("number"==typeof I&&E.length<I)return!1;if(u)E.forEach(((t,o)=>{validate({[o]:u},{[o]:t},`${i}[${o}]`,m)}));else if(v)E.forEach(((t,o)=>validate(v,t,`${i}[${o}]`,m)));else if("enum"===h){if(M&&function difference(t,i){return i=i||[],(t=t||[]).filter((t=>-1===i.indexOf(t)))}(E,M).length)return!1}else if(h&&!E.every((t=>typeof t===h)))return!1;return!0},object:function(t,i,o,m=!1){var{rules:h,allowEmpty:u}=o,v=t[i];if("object"!=typeof v||null===v)return!1;if(h){var I=Object.keys(h),_=Object.keys(v).filter((t=>I.indexOf(t)>-1));if(!1===u&&0===_.length)return!1;validate(h,v,i,m)}return!0}};function validateConversationId(t,i){if(!t)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_ILLEGAL_STATE});validate({conversationId:{type:"string",allowEmpty:!1,regExp:new RegExp(`^${t}\\|[1-3]\\|`)}},{conversationId:i},"",!0)}class TimerManager{constructor(){this.timerList=[],this.id=1,this.timer=null,this.timeout=0}addTimer(t,i=0,o=1){var m=(new Date).getTime(),h=this.id;return this.timerList.push({id:h,loop:o,count:0,timeout:m+i,interval:i,callback:t}),this.id++,this.checkTimer(m),h}checkTimer(t=(new Date).getTime()){if(this.removeFinished(),0!==this.timerList.length||null==this.timer){var i=0;for(var o of this.timerList)(0===i||i>o.timeout)&&(i=o.timeout);0!==this.timerList.length&&(null===this.timer||i<this.timeout||this.timeout<t)&&(this.timer=setTimeout(this.nowTime.bind(this),i-t),this.timeout=i)}}nowTime(){var t=(new Date).getTime();for(var i of this.timerList)t>=i.timeout&&(i.callback(),i.count++,i.timeout=t+i.interval);this.clerTime(),this.checkTimer(t)}clerTime(){null!==this.timer&&(clearTimeout(this.timer),this.timer=null)}deleteTimer(t){for(var i=this.timerList.length-1;i>=0;i--){this.timerList[i].id===t&&this.timerList.splice(i,1)}}removeFinished(){for(var t=this.timerList.length-1;t>=0;t--){var i=this.timerList[t];i.loop>=0&&i.count>=i.loop&&this.timerList.splice(t,1)}}destroy(){this.clerTime(),this.timerList=[],this.id=1,this.timer=null}}function __rest(t,i){var o={};for(var m in t)Object.prototype.hasOwnProperty.call(t,m)&&i.indexOf(m)<0&&(o[m]=t[m]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var h=0;for(m=Object.getOwnPropertySymbols(t);h<m.length;h++)i.indexOf(m[h])<0&&Object.prototype.propertyIsEnumerable.call(t,m[h])&&(o[m[h]]=t[m[h]])}return o}function __awaiter(t,i,o,m){return new(o||(o=Promise))((function(h,u){function fulfilled(t){try{step(m.next(t))}catch(t){u(t)}}function rejected(t){try{step(m.throw(t))}catch(t){u(t)}}function step(t){t.done?h(t.value):function adopt(t){return t instanceof o?t:new o((function(i){i(t)}))}(t.value).then(fulfilled,rejected)}step((m=m.apply(t,i||[])).next())}))}function isPlainObject(t){return null!=t&&"object"==typeof t&&Object.getPrototypeOf(t)==Object.prototype}function merge(t,i){var o=isPlainObject(t)||Array.isArray(t),m=isPlainObject(i)||Array.isArray(i);if(o&&m){for(var h in i){var u=merge(t[h],i[h]);void 0!==u&&(t[h]=u)}return t}return i}var Ae={getNetworkStatus:()=>Promise.resolve({net_type:0,net_connect:!0}),onNetworkStatusChange(t){},offNetworkStatusChange(){}},Oe={isActive:()=>!0,getStatus:()=>0,setStatus(t){},destroy(){}};var Re={setLogger:function(t){throw new Error("setLogger not implemented.")},platform:"",WebSocket:class AdapterSocket{constructor(t,i){throw this.CONNECTING=0,this.OPEN=1,this.CLOSING=2,this.CLOSED=3,this.binaryType="",new Error("Method not implemented.")}close(t,i){throw new Error("Method not implemented.")}send(t){throw new Error("Method not implemented.")}onclose(t){throw new Error("Method not implemented.")}onerror(t){throw new Error("Method not implemented.")}onmessage(t){throw new Error("Method not implemented.")}onopen(t){throw new Error("Method not implemented.")}},localStorage:{},request:function(t,i){throw new Error("request not implemented.")},uploadFile:function(t){throw new Error("uploadFile not implemented.")},getSystemInfo:function(){throw new Error("getSystemInfo not implemented.")},getFileUploadInformation(t){throw new Error("getFileUploadInformation not implemented.")},envPayload:{},net:Ae,powerMonitor:Oe,logStorage:class AdapterLogStorageImpl{constructor(t){}open(){return Promise.resolve()}close(){}addLogs(t){return Promise.resolve()}extractLogs(){return Promise.resolve()}afterUpload(){return Promise.resolve()}}};function setAdapters(t){merge(Re,t())}var be=["error","warn","log","debug"],emptyFunc$1=function(){},Ve=["off","error","warn","log","debug"];class Logger{constructor(t,i={}){this.storageArr=[],this.debugLevel="off",this.timer=0,this.strategies={debug:{name:"debg",func:console.log},log:{name:"info",func:console.log},warn:{name:"warn",func:console.warn},error:{name:"erro",func:console.error}},this.debug=emptyFunc$1,this.log=emptyFunc$1,this.warn=emptyFunc$1,this.error=emptyFunc$1,this.iid=Math.round(1e3*Math.random()),this.debugLevel=Ve.indexOf(t)>-1?t:"off",i.debugLevel&&(this.debugLevel=Ve.indexOf(i.debugLevel)>-1?i.debugLevel:this.debugLevel),this.logStorage=!1===i.storageEnable?null:new Re.logStorage({logDirPath:i.logDirPath||i.storageName||"nim_logs",logRetentionDays:i.logRetentionDays||10,totalLogSizeInMB:i.totalLogSizeInMB||200,maxLogFileSizeInMB:i.maxLogFileSizeInMB||10}),this.setOptions(i),this.setLogFunc(this.debugLevel),this.setTimer(),Re.setLogger(this),this.open()}getDebugMode(){return"debug"===this.debugLevel}open(){this.logStorage&&this.logStorage.open().then((()=>{this.log("Logger::open success")})).catch((t=>{this.warn("Logger::open failed",t)}))}setOptions(t){if(t&&t.logFunc){var i=t.logFunc;for(var o in i){var m=o,h=i[m];h&&(this.strategies[m].func=h)}}}setLogFunc(t,i="log"){var o=be.findIndex((i=>i===t)),m=be.findIndex((t=>t===i));be.forEach(((t,i)=>{this[t]=function(){if(!(i>o&&i>m)){var h=Array.prototype.slice.call(arguments),u=this.strategies[t],v=this.formatArgs(h,u.name);i<=m&&this.logStorage&&this.prepareSaveLog(v,t),i<=o&&u.func(v)}}}))}extractLogs(){var t;return this.logStorage?null===(t=this.logStorage)||void 0===t?void 0:t.extractLogs():Promise.resolve("")}afterUpload(){var t;return this.logStorage?null===(t=this.logStorage)||void 0===t?void 0:t.afterUpload():Promise.resolve("")}prepareSaveLog(t,i){this.storageArr.push({text:t,level:i,time:Date.now(),iid:this.iid}),this.timer||this.setTimer(),this.storageArr.length>=100&&(this.triggerTimer(),this.storageArr=[])}saveLogs(){return __awaiter(this,void 0,void 0,(function*(){if(this.logStorage){var t=this.storageArr;this.storageArr=[];try{yield this.logStorage.addLogs(t)}catch(t){}}}))}clearTimer(){this.timer&&clearTimeout(this.timer),this.timer=0}setTimer(){this.clearTimer(),this.timer=setTimeout(this.triggerTimer.bind(this),5e3)}triggerTimer(){this.clearTimer(),this.saveLogs()}formatArgs(t,i){var o=new Date;return`[NIM ${this.iid} ${i} ${`${o.getMonth()+1}-${o.getDate()} ${o.getHours()}:${o.getMinutes()}:${o.getSeconds()}:${o.getMilliseconds()}`}] `+t.map((t=>t instanceof V2NIMErrorImpl?t.toString():t instanceof Error?t&&t.message?t.message:t:"object"==typeof t?JSON.stringify(t):t)).join(" ")}destroy(){this.debug=emptyFunc$1,this.log=emptyFunc$1,this.warn=emptyFunc$1,this.error=emptyFunc$1,this.saveLogs(),this.clearTimer(),this.storageArr=[],this.logStorage&&this.logStorage.close()}}function get(t,i){if("object"!=typeof t||null===t)return t;for(var o=(i=i||"").split("."),m=0;m<o.length;m++){var h=o[m],u=t[h],v=h.indexOf("["),I=h.indexOf("]");if(-1!==v&&-1!==I&&v<I){var _=h.slice(0,v),M=parseInt(h.slice(v+1,I));u=t[_],u=Array.isArray(u)?u[M]:void 0}if(null==u)return u;t=u}return t}var ke,Pe=(ke=function(){return(65536*(1+Math.random())|0).toString(16).substring(1)},function(){return ke()+ke()+ke()+ke()+ke()+ke()+ke()+ke()});function pendingIsMiniappEnv(){var{hostEnvEnum:t}=Re.getSystemInfo();return 6===t||102===t||103===t||104===t}function assignOptions(t,i){return function assignWith(t,i,o,m){for(var h in t=t||{},o=o||{},m=m||(()=>{}),i=i||{}){var u=m(t[h],i[h]);t[h]=void 0===u?i[h]:u}for(var v in o){var I=m(t[v],o[v]);t[v]=void 0===I?o[v]:I}return t}({},t,i,(function(t,i){return void 0===i?t:i}))}function emptyFuncWithPromise(){return Promise.resolve()}function emptyFunc(){}function getFileExtension(t){var i=t.lastIndexOf("."),o=i>-1?t.slice(i+1):"";return/^\d+$/.test(o.trim())&&(o=""),o}function findIndexWithinTargetValue(t,i,o){return 0===t.length||t[0][i]<=o?0:t[t.length-1][i]>o?t.length:t.findIndex(((m,h)=>{if(t[h-1]&&t[h-1][i]>o&&o>=m[i])return!0}))}function fillIdServer(t,i,o,m){var h="number"==typeof get(t,"raw.r[0]")?`${t.raw.r[0]}`:void 0;return i[o]=i[o]||h||m,i}class CoreAdapters{constructor(t){this.lastSuccUploadHost="",this.core=t}getFileUploadInformation(t){return Re.getFileUploadInformation(t)}request(t,i,o){var m=(new Date).getTime(),h=(null==o?void 0:o.exception_service)||0;return Re.request(t,i).catch((o=>{var u,v,I,_,M=o;throw this.core.reporter.reportTraceStart("exceptions",{user_id:this.core.options.account||(null===(v=null===(u=this.core)||void 0===u?void 0:u.auth)||void 0===v?void 0:v.account),trace_id:null===(_=null===(I=this.core.clientSocket)||void 0===I?void 0:I.socket)||void 0===_?void 0:_.sessionId,start_time:m,action:1,exception_service:h}),this.core.reporter.reportTraceUpdateV2("exceptions",{code:"number"==typeof M.code?M.code:0,description:M.message||`${M.code}`,operation_type:0,target:t,context:i?JSON.stringify(i):""},{asyncParams:Re.net.getNetworkStatus()}),this.core.reporter.reportTraceEnd("exceptions",1),o}))}uploadFile(t,i){var o,m,h,u;return __awaiter(this,void 0,void 0,(function*(){for(var v="BROWSER"===Re.platform,I=v?t.chunkUploadHostBackupList:t.commonUploadHostBackupList,_=v?t.chunkUploadHost:t.commonUploadHost,M=I.indexOf(_),E=-1===M?[_,...I]:[_,...I.slice(0,M),...I.slice(M+1)],S=Math.max(E.indexOf(this.lastSuccUploadHost),0),T=null,C=0;C<E.length;C++){var N=(new Date).getTime(),A=E[(C+S)%E.length];null==i||i.update({retry_times:C});try{var O=yield Re.uploadFile(Object.assign(Object.assign({},t),v?{chunkUploadHost:A}:{commonUploadHost:A}));return this.lastSuccUploadHost=A,"string"==typeof O.size&&(O.size=parseInt(O.size)),"string"==typeof O.dur&&(O.dur=parseInt(O.dur)),"string"==typeof O.w&&(O.w=parseInt(O.w)),"string"==typeof O.h&&(O.h=parseInt(O.h)),O}catch(t){this.core.cloudStorage.nos.nosErrorCount--,T=t;var R=t;this.core.reporter.reportTraceStart("exceptions",{user_id:this.core.options.account||(null===(m=null===(o=this.core)||void 0===o?void 0:o.auth)||void 0===m?void 0:m.account),trace_id:null===(u=null===(h=this.core.clientSocket)||void 0===h?void 0:h.socket)||void 0===u?void 0:u.sessionId,start_time:N,action:1,exception_service:3}),this.core.reporter.reportTraceUpdateV2("exceptions",{code:"number"==typeof R.code?R.code:0,description:R.message||`${R.code}`,operation_type:1,target:A},{asyncParams:Re.net.getNetworkStatus()}),this.core.reporter.reportTraceEnd("exceptions",1),this._uploadFileErrHanler(t)}}throw T}))}_uploadFileErrHanler(t){if(t&&(t.code>200||t.errCode>200))throw t}}var Le="https://abt-online.netease.im/v1/api/abt/client/getExperimentInfo";class ABTest{constructor(t,i){this.abtInfo={},this.core=t,this.config=assignOptions({isAbtestEnable:!0,abtestUrl:Le,abtestProjectKey:"imElite_sdk_abtest_web"},i)}setOptions(t){this.config=assignOptions(this.config,t)}abtRequest(){var t,i;return __awaiter(this,void 0,void 0,(function*(){if(this.config.isAbtestEnable&&!this.abtInfo.experiments&&this.config.abtestUrl){var o;try{o=yield this.core.adapters.request(this.config.abtestUrl,{method:"POST",dataType:"json",headers:{sdktype:"ABTest"},data:{clientInfo:{projectKey:this.config.abtestProjectKey,appKey:this.core.options.appkey,osType:"Web",sdkVersion:"10.9.70",deviceId:this.core.config.deviceId},useLocalCache:!0}},{exception_service:7})}catch(t){this.core.logger.warn("ABTest request failed")}this.abtInfo=(null===(i=null===(t=null==o?void 0:o.data)||void 0===t?void 0:t.data)||void 0===i?void 0:i.abtInfo)||{}}}))}}class PromiseManager{constructor(){this.abortFns=[]}add(t){var i=function getPromiseWithAbort(t){var i={},o=new Promise((function(t,o){i.abort=o}));return i.promise=Promise.race([t,o]),i}(t);return this.abortFns.push(i.abort),i.promise}clear(t){this.abortFns.forEach((i=>i(t||new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_CANCELLED,detail:{reason:"Aborted"}})))),this.abortFns=[]}destroy(){this.clear()}}var we={tolerantRTT:3e3,bestRTT:100,maxChances:5,enable:!0},De={timestamp:0,rtt:0,baseClock:0,baseTime:0};class TimeOrigin{constructor(t,i,o="getServerTime"){this.serverOrigin=De,this.config=we,this.isSettingNTP=!1,this.currentChance=0,this.failedDelay=2e3,this.successDelay=3e5,this.timer=0,this.cmdName="getServerTime",this.core=t,this.logger=t.logger,this.promiseManager=new PromiseManager,this.cmdName=o,i&&this.setOptions(i)}setOptions(t){this.config=Object.assign({},we,this.config,t)}reset(){this.timer&&clearTimeout(this.timer),this.promiseManager.clear(),this.serverOrigin=De,this.currentChance=0}setOriginTimetick(){return __awaiter(this,void 0,void 0,(function*(){if(this.config.enable&&!(this.isSettingNTP||this.currentChance>=this.config.maxChances)){var t=get(this.core,"auth.status"),i=get(this.core,"status"),o=get(this.core,"V2NIMLoginService.lifeCycle.loginStatus");if("logined"===t||"logined"===i||1===o){this.isSettingNTP=!0,this.currentChance++,this.timer&&clearTimeout(this.timer),this.timer=0;var m,h="TimeOrigin::setOriginTimetick:",u=Date.now();this.core.logger.debug(`${h} getServerTime start, times ${this.currentChance}`);try{m=get(yield this.promiseManager.add(this.core.sendCmd(this.cmdName)),"content.time"),this.isSettingNTP=!1}catch(t){var v=t;return this.isSettingNTP=!1,this.logger.warn(`${h} Calculate Delay time, getServerTime error`,v),void(v.code!==Ee.V2NIM_ERROR_CODE_CANCELLED&&(clearTimeout(this.timer),this.timer=setTimeout(this.setOriginTimetick.bind(this),this.failedDelay)))}if(!m)return this.core.logger.warn(`${h} Calculate Delay time incorrect format`),void(this.config.enable=!1);var I=Date.now()-u;this.doSet(m,I)}}}))}doSet(t,i){var o="TimeOrigin::setOriginTimetick:";i>this.config.tolerantRTT?(this.logger.warn(`${o} denied RTT:${i}`),clearTimeout(this.timer),this.timer=setTimeout(this.setOriginTimetick.bind(this),this.failedDelay)):i>this.config.bestRTT?(this.serverOrigin.rtt&&i>=this.serverOrigin.rtt?this.logger.warn(`${o} ignore RTT:${i}`):(this.setServerOrigin(i,t),this.logger.log(`${o} accept reluctantly RTT:${i}`)),clearTimeout(this.timer),this.timer=setTimeout(this.setOriginTimetick.bind(this),this.failedDelay)):(this.setServerOrigin(i,t),this.logger.debug(`${o} accept best RTT:${i}`),this.currentChance=0,clearTimeout(this.timer),this.timer=setTimeout(this.setOriginTimetick.bind(this),this.successDelay))}getNTPTime(t){if(void 0===t&&(t=this.getTimeNode()),this.checkNodeReliable(t)){var i=Math.floor(t.time-this.serverOrigin.baseTime);return this.serverOrigin.timestamp+i}return Date.now()}checkNodeReliable(t){if(void 0===t&&(t=this.getTimeNode()),this.serverOrigin.timestamp){if(0===this.serverOrigin.baseClock)return!0;var i=t.clock-this.serverOrigin.baseClock,o=t.time-this.serverOrigin.baseTime;return Math.abs(o-i)<500}return!1}checkPerformance(){return"BROWSER"===Re.platform&&!("undefined"==typeof performance||!performance.now)}static checkPerformance(){return"BROWSER"===Re.platform&&!("undefined"==typeof performance||!performance.now)}getTimeNode(){return{clock:this.checkPerformance()?performance.now():0,time:Date.now()}}static getTimeNode(){return{clock:TimeOrigin.checkPerformance()?performance.now():0,time:Date.now()}}setServerOrigin(t,i){this.serverOrigin={timestamp:i+Math.floor(t/2),rtt:t,baseClock:this.checkPerformance()?performance.now():0,baseTime:Date.now()}}}var Ue={user_id:"",trace_id:"",action:7,exception_service:6,duration:0,start_time:0,state:1,extension:[]};class ReporterHookLinkKeep{constructor(t,i){this.traceData=Ue,this.core=t,this.traceData=Object.assign({},Ue,i),this.traceData.extension=[]}reset(){this.traceData=Object.assign({},Ue),this.traceData.extension=[]}start(){var t,i;this.reset(),this.traceData.user_id=this.core.account,this.traceData.trace_id=(null===(i=null===(t=this.core.clientSocket)||void 0===t?void 0:t.socket)||void 0===i?void 0:i.sessionId)||"",this.traceData.start_time=(new Date).getTime()}update(t){return __awaiter(this,void 0,void 0,(function*(){var{net_type:i,net_connect:o}=yield Re.net.getNetworkStatus();this.traceData.extension.push(Object.assign({code:0,foreground:!0,foreg_backg_switch:!1,net_type:i,net_connect:o},t))}))}end(t){var i=this.traceData.extension[0],o=this.traceData.extension[1];if(i&&0===i.operation_type&&o&&1===o.operation_type){var m=i.net_type!==o.net_type||i.net_connect!==o.net_connect;if(t||!m)return this.traceData.duration=(new Date).getTime()-this.traceData.start_time,this.core.reporter.report("exceptions",this.traceData),void this.reset();this.reset()}else this.reset()}}var xe={user_id:"",trace_id:"",net_connect:!0,net_type:0,duration:0,start_time:0,history:[],succeed:!1};class ReporterHookLBS{constructor(t){this.traceData=xe,this.core=t,this.reset()}reset(){this.traceData=Object.assign({},xe),this.traceData.history=[]}start(t){this.reset(),this.traceData.user_id=t,this.traceData.start_time=Date.now()}updateBegin(t){this.traceData.history.push(Object.assign({head:"",body:"",start_time:Date.now(),httpdns:!1,index:0},t))}updateComplete(t){this.traceData.history.forEach((i=>{i.target===t.target&&(Object.assign(i,t),i.duration=Date.now()-i.start_time)}))}end(t){return __awaiter(this,void 0,void 0,(function*(){if(this.traceData.succeed=t,this.traceData.history=this.traceData.history.filter((t=>void 0!==t.code)),0!==this.traceData.history.length){this.traceData.duration=Date.now()-this.traceData.start_time;var{net_type:i,net_connect:o}=yield Re.net.getNetworkStatus();this.traceData.net_type=i,this.traceData.net_connect=o,this.core.reporter.report("nim_sdk_lbs_records",this.traceData),this.reset()}else this.reset()}))}}function getIsDataReportEnable(t){var i,o,m=!0;return"boolean"==typeof(null===(i=null==t?void 0:t.reporterConfig)||void 0===i?void 0:i.enableCompass)?m=t.reporterConfig.enableCompass:"boolean"==typeof(null===(o=null==t?void 0:t.reporterConfig)||void 0===o?void 0:o.isDataReportEnable)&&(m=t.reporterConfig.isDataReportEnable),m}var Fe={},Be={},$e={},je={apiVersion:"v1",debugLevel:"off",needReconnect:!0,reconnectionAttempts:Number.MAX_SAFE_INTEGER,lbsUrls:["https://lbs.netease.im/lbs/webconf.jsp"],linkUrl:"weblink.netease.im:443",abtestUrl:Le,isAbtestEnable:!0};class NIM$1 extends Ie{constructor(t,i={}){if(super(),this.instanceName="NIM",this.pluginMap={},this.eventBus=new Ie,this.options={},this.V2NIMConversationIdUtil={},this.V2NIMMessageCreator={},this.V2NIMMessageAttachmentCreator={},this.V2NIMClientAntispamUtil={},this.DataStructureConverter={},this.V2NIMMessageConverter={},this.V2NIMMessageLogUtil={},this.V2NIMMessageExtendUtil={},this.V2NIMStorageUtil={},this.V2NIMNotificationService={},this.V2NIMStorageService={},this.auth={},this.V1NIMLoginService={},this.V2NIMLoginService={},this.clientSocket={},this.V2NIMSyncService={},this.V2NIMLocalConversationService={},this.V2NIMConversationService={},this.V2NIMConversationGroupService={},this.V2NIMMessageService={},this.V2NIMTeamService={},this.V2NIMUserService={},this.V2NIMFriendService={},this.V2NIMSettingService={},this.V2NIMAIService={},this.V2NIMSignallingService={},this.V2NIMSubscriptionService={},this.V2NIMPassthroughService={},this.YSFService={},this.offlinePush={},this.sync={},this.msg={},this.msgLog={},this.session={},this.cloudSession={},this.misc={},this.user={},this.friend={},this.systemMessage={},this.team={},this.event={},this.msgExtend={},this.cloudStorage={},this.passThrough={},this.superTeam={},this.plugin={},this.signaling={},this.qchatChannel={},this.qchatMedia={},this.qchatMsg={},this.qchatRole={},this.qchatServer={},this.pluginMap=$e,this.logger=new Logger(t.debugLevel,i.loggerConfig),i.privateConf){var{authConfig:o,cloudStorageConfig:m,reporterConfig:h}=this.getConfigFromPrivate(i.privateConf);Object.assign(t,o),this.setInitOptions(t),this.otherOptions=Object.assign(Object.assign({},i),{cloudStorageConfig:Object.assign(Object.assign({storageKeyPrefix:"NIM"},i.cloudStorageConfig),m),reporterConfig:Object.assign(Object.assign({},i.reporterConfig),h),V1NIMLoginServiceConfig:Object.assign(Object.assign(Object.assign({},t),i.V1NIMLoginServiceConfig),o),V2NIMLoginServiceConfig:Object.assign(Object.assign({},i.V2NIMLoginServiceConfig),o)})}else this.setInitOptions(t),this.otherOptions=Object.assign(Object.assign({},i),{V1NIMLoginServiceConfig:Object.assign(Object.assign({},t),i.V1NIMLoginServiceConfig),cloudStorageConfig:Object.assign({storageKeyPrefix:"NIM"},i.cloudStorageConfig)});this.timerManager=new TimerManager,this.timeOrigin=new TimeOrigin(this),this.adapters=new CoreAdapters(this),this.abtest=new ABTest(this,Object.assign(Object.assign({isAbtestEnable:this.options.isAbtestEnable,abtestUrl:this.options.abtestUrl},this.otherOptions.abtestConfig),{abtestProjectKey:"imElite_sdk_abtest_web"}));var u=Re.getSystemInfo(),v=function getCompassDataEndpoint(t,i){var o,m,h=null===(o=null==i?void 0:i.reporterConfig)||void 0===o?void 0:o.compassDataEndpoint,u=null===(m=null==i?void 0:i.reporterConfig)||void 0===m?void 0:m.reportConfigUrl;if(h)return h;if(u){var v=u.match(/^https:\/\/([^/]+)\/*/);if(Array.isArray(v)&&v.length>=1)return`https://${v[1]}`;t.error(`Invalid reportConfigUrl: ${u}`)}return pendingIsMiniappEnv()?"https://statistic.live.126.net":"https://statistic.live.126.net,https://statistic-overseas.yunxinfw.com"}(this.logger,this.otherOptions);this.reporter=new ye(Object.assign(Object.assign({},v?{compassDataEndpoint:v}:{}),{isDataReportEnable:getIsDataReportEnable(this.otherOptions),common:{app_key:t.appkey,dev_id:"",platform:"Web",sdk_ver:"10.9.70",env:"online",os_name:u.os,os_ver:u.osVer,lib_env:u.libEnv,host_env:u.hostEnv,host_env_ver:u.hostEnvVer,manufactor:u.manufactor,model:u.model,v2:"v1"!==this.options.apiVersion},request:Re.request,logger:this.logger,autoStart:!0})),this.reporterHookLinkKeep=new ReporterHookLinkKeep(this),this.reporterHookLBS=new ReporterHookLBS(this),this.getServiceKeys(Object.keys(Fe)).forEach((t=>{if(!this[t]||!this[t].name){var i=Fe[t];this[t]=new i(this)}})),Object.keys(Fe).forEach((t=>{this.callSetOptions(t)})),Object.keys(Be).forEach((t=>{var i=Be[t];void 0!==i&&(this[t]=new i(this))})),NIM$1.instance=this,this.logger.log(`NIM init, version:10.9.70, sdk version:100970, appkey:${t.appkey}`)}getServiceKeys(t){var i=t.findIndex((t=>"V1NIMLoginService"===t));if(i>-1){var o=t[i];t.splice(i,1),"v1"===this.options.apiVersion&&t.unshift(o)}var m=t.findIndex((t=>"V2NIMLoginService"===t));if(m>-1){var h=t[m];t.splice(m,1),"v2"===this.options.apiVersion&&t.unshift(h)}var u=t.findIndex((t=>"sync"===t));if(u>-1){var v=t[u];t.splice(u,1),"v1"===this.options.apiVersion&&t.push(v)}var I=t.findIndex((t=>"V2NIMSyncService"===t));if(I>-1){var _=t[I];t.splice(I,1),"v2"===this.options.apiVersion&&t.push(_)}return t}static getInstance(t,i){if(!NIM$1.instance){if(t)return new NIM$1(t,i);throw new Error("Instance not exist, please input options")}if(t){if(NIM$1.instance.options.account===t.account&&NIM$1.instance.options.appkey===t.appkey)return NIM$1.instance.setOptions(t),NIM$1.instance;throw new Error("Unexpected login")}return NIM$1.instance}setInitOptions(t){validate({appkey:{type:"string"},apiVersion:{type:"enum",values:["v1","v2"],required:!1},binaryWebsocket:{type:"boolean",required:!1},needReconnect:{type:"boolean",required:!1},reconnectionAttempts:{type:"number",required:!1},customClientType:{type:"number",min:1,required:!1},authType:{type:"number",min:0,max:2,required:!1},lbsUrls:{type:"array",itemType:"string",min:1,required:!1},linkUrl:{type:"string",allowEmpty:!1,required:!1}},t),this.options=Object.assign(Object.assign({},je),t)}getConfigFromPrivate(t){var i;return t?{authConfig:JSON.parse(JSON.stringify({appkey:t.appkey||void 0,lbsUrls:t.weblbsUrl?[t.weblbsUrl]:void 0,linkUrl:t.link_web||void 0,linkSSL:null!==(i=t.websdkSsl)&&void 0!==i?i:void 0})),cloudStorageConfig:JSON.parse(JSON.stringify({chunkUploadHost:t.nos_uploader||void 0,commonUploadHost:t.nos_uploader||void 0,commonUploadHostBackupList:t.nos_uploader?[t.nos_uploader]:void 0,chunkUploadHostBackupList:t.nos_uploader?[t.nos_uploader]:void 0,uploadReplaceFormat:t.nos_downloader_v2?`${t.nosSsl?"https://":"http://"}${t.nos_downloader_v2}`:void 0,downloadUrl:void 0!==t.nos_accelerate?t.nos_accelerate:void 0,downloadHostList:""===t.nos_accelerate_host?[]:"string"==typeof t.nos_accelerate_host?[t.nos_accelerate_host]:Array.isArray(t.nos_accelerate_host)?t.nos_accelerate_host:void 0})),reporterConfig:JSON.parse(JSON.stringify({enableCompass:"boolean"==typeof t.enableCompass?t.enableCompass:void 0,compassDataEndpoint:t.compassDataEndpoint||void 0}))}:{authConfig:{},cloudStorageConfig:{},reporterConfig:{}}}connect(t={}){return this.V1NIMLoginService.login(t)}setOptions(t){if("object"==typeof t&&null!==t){if(Object.prototype.hasOwnProperty.call(t,"account")&&t.account!==this.options.account||Object.prototype.hasOwnProperty.call(t,"appkey")&&t.appkey!==this.options.appkey)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_MISUSE,detail:{reason:"NIM::setOptions account and appkey is not allowed to reset"}});if(Object.prototype.hasOwnProperty.call(t,"apiVersion")&&t.apiVersion!==this.options.apiVersion)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_MISUSE,detail:{reason:"NIM::setOptions apiVersion is not allowed to reset"}});if(Object.prototype.hasOwnProperty.call(t,"binaryWebsocket")&&t.binaryWebsocket!==this.options.binaryWebsocket)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_MISUSE,detail:{reason:"NIM::setOptions binaryWebsocket is not allowed to reset"}});validate({token:{type:"string",required:!1},needReconnect:{type:"boolean",required:!1},reconnectionAttempts:{type:"number",required:!1},customClientType:{type:"number",min:1,required:!1},authType:{type:"number",min:0,max:2,required:!1},lbsUrls:{type:"array",itemType:"string",min:1,required:!1},linkUrl:{type:"string",allowEmpty:!1,required:!1}},t),this.logger.log("NIM::setOptions options is",t),this.options=Object.assign(Object.assign({},this.options),t),this.V1NIMLoginService.setOptions&&this.V1NIMLoginService.setOptions(this.options)}}getOptions(){return this.options}disconnect(){return this.V1NIMLoginService.logout()}_disconnect(){return"v1"===this.options.apiVersion?this.V1NIMLoginService.logout():"v2"===this.options.apiVersion?0===get(this.V2NIMLoginService,"lifeCycle.connectStatus")&&0===get(this.V2NIMLoginService,"lifeCycle.loginStatus")?Promise.resolve():this.V2NIMLoginService.logout():Promise.resolve()}destroy(){return NIM$1.instance=void 0,this._disconnect().then((()=>{this.status="destroyed",this.removeAllListeners(),this.eventBus.removeAllListeners(),this.logger.destroy(),this.reporter.destroy(),this.timerManager.destroy(),this._clearModuleData("destroy"),this._removeAllModuleListeners(),this.connect=emptyFuncWithPromise,this.disconnect=emptyFuncWithPromise,this._disconnect=emptyFuncWithPromise,this.destroy=emptyFuncWithPromise}))}_clearModuleData(t="logout"){Object.values(this).forEach((i=>{i&&"function"==typeof i.reset&&i.reset(t)}))}_removeAllModuleListeners(){Object.values(this).forEach((t=>{t&&"function"==typeof t.removeAllListeners&&t.removeAllListeners()}))}kick(t){return this.V1NIMLoginService.kick(t)}sendCmd(t,i,o){return this.clientSocket.sendCmd(t,i,o)}emit(t,...i){try{var o=Date.now(),m=super.emit(t,...i),h=Date.now()-o;return h>=10&&this.logger.warn(`Core::emit event: ${t} process takes: ${h}ms`),m}catch(i){return this.logger.error(`Core::emit event: ${t}. Error: ${i}`),setTimeout((()=>{throw this.logger.error(`Core::emit throw error in setTimeout. event: ${t}. Error: ${i}`),i}),0),!1}}get account(){return this.auth.account}get status(){return this.V1NIMLoginService.status}set status(t){this.V1NIMLoginService.status=t}get config(){return{timeout:8e3,deviceId:this.auth.deviceId}}_registerDep(t,i){this[i]&&this[i].name||(this[i]=new t(this),this.callSetOptions(i))}callSetOptions(t){var i=`${t}Config`,o=`${t}Options`,m=this.otherOptions[i]||this.otherOptions[o]||{},h=get(this,`${t}.setOptions`);"function"==typeof h&&("cloudStorage"===t&&(m=this.otherOptions[i]||this.otherOptions.serverConfig||{}),h.call(this[t],m))}static registerService(t,i){Fe[i]=t}static registerPrivateService(t,i){Be[i]=t}static registerPlugin(t,i){$e[i]=t}}NIM$1.sdkVersion=100970,NIM$1.sdkVersionFormat="10.9.70";var Ge={},qe={};function createCmd(t,i,o,m){var h=Ge[t];if(!h)return o.error("createCmd:: can not find cmd config: ",t),null;var u={SER:i,SID:h.sid,CID:h.cid,Q:[]};return h.params&&m&&h.params.forEach((function(t){var i=m[t.name];if(null!=i){var o=t.type,{reflectMapper:h,select:v}=t;switch(t.type){case"PropertyArray":o="ArrayMable",i=i.map((t=>({t:"Property",v:h?serialize(t,h,v):t})));break;case"Property":i=h?serialize(i,h,v):i;break;case"Bool":i=i?"true":"false"}u.Q.push({t:o,v:i})}})),{packet:u,hasPacketResponse:"boolean"!=typeof h.hasPacketResponse||h.hasPacketResponse,hasPacketTimer:"boolean"!=typeof h.hasPacketTimer||h.hasPacketTimer}}function parseCmd(t,i){var o;try{o=JSON.parse(t)}catch(o){return void i.error(`Parse command error:"${t}"`)}var m=o.sid+"_"+o.cid,h=o.r;if(["4_1","4_2","4_10","4_11"].includes(m)){var u=o.r[1].headerPacket;m=`${u.sid}_${u.cid}`,o.sid=u.sid,o.cid=u.cid,h=o.r[1].body}var v=qe[m],I=[];if(v&&v.length>0){for(var _ of v)I.push(parseEachCmd(o,_.config,_.cmd,h,i));return I}i.error("parseCmd:: mapper not exist",m,o.code)}function parseEachCmd(t,i,o,m,h){var u,v={cmd:o,raw:t,error:null,service:null==i?void 0:i.service,content:{},__receiveTimeNode:TimeOrigin.getTimeNode()};(function isV2Sid(t){return[18,19,26,27,28,29,30,31,32,33,34,35,36].includes(t)})(i.sid)&&(t.code=function toReadableCode(t){if("number"!=typeof t||t!=t)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INTERNAL,detail:{reason:"Read code failed",rawData:`${t}`}});if(t<0||t>=0&&t<1e3||t>=2e4&&t<=20099)return t;var i=(65535&t)>>9;i-=i<=38?1:2;return 1e5+1e3*i+(511&t)}(t.code));var I=function genCmdError(t,i){var o=Se[t],m=Ce[t];return null===m?null:new V2NIMErrorImpl({code:t,desc:o||m||t,detail:{cmd:i,timetag:Date.now()}})}(t.code,o);if(v.error=I,v.error){if(v.error.detail.cmd=o,!(null===(u=null==i?void 0:i.ignoreErrCodes)||void 0===u?void 0:u.includes(t.code)))return v;h.warn("parseCmd:: ignore error ",v.error),v.error.detail.ignore=!0}return i.response&&i.response.forEach(((t,i)=>{var o=m[i],h=t.type,u=t.name,I=t.reflectMapper;if(void 0!==o)switch(h){case"Property":v.content[u]=I?deserialize(o,I):o;break;case"PropertyArray":v.content[u]=o.map((t=>I?deserialize(t,I):t));break;case"Int":case"Long":case"Byte":v.content[u]=+o;break;case"Bool":v.content[u]="true"===o||!0===o||1===o;break;default:v.content[u]=o}})),v}function serialize(t,i,o){var m={};for(var h in t=function flattenObjByMapper(t,i){var o={};for(var m in i){var h=i[m],u="number"==typeof h?m:h.access?h.access:m,v=u.split("."),I=t;for(var _ of v){if(void 0===I[_]||null===I[_]){I=void 0;break}I=I[_]}void 0!==I&&(o[u]=I)}return o}(t,i),i){var u=i[h],v="number"==typeof u?h:u.access?u.access:h;if(!o||o.includes(h))if(v in t){if("number"==typeof u)m[u]=t[v];else if("object"==typeof u)if(u.converter){var I=u.converter(t[v],t);void 0!==I&&(m[u.id]=I)}else m[u.id]=t[v]}else"object"==typeof u&&u.def&&("function"==typeof u.def?m[u.id]=u.def(t):m[u.id]=u.def)}return m}function deserialize(t,i){var o={};for(var m in t){var h=i[m];if("string"==typeof h)o[h]=t[m];else if("object"==typeof h&&"prop"in h){var u=h.access?h.access:h.prop;if(h.converter){var v=h.converter(t[m],t);void 0!==v&&(o[u]=v)}else h.type&&"number"===h.type?o[u]=+t[m]:h.type&&"boolean"===h.type?o[u]=!("0"===t[m]||!t[m]):o[u]=t[m]}}for(var I in i){var _=i[I];if(_&&void 0!==_.def){var M=_.access?_.access:_.prop;M in o||("function"==typeof _.def?o[M]=_.def(t):o[M]=_.def)}}return o=function unflattenObj(t){var i={},_loop=function(o){var m=o.split(".");m.reduce((function(i,h,u){return i[h]||(i[h]=isNaN(Number(m[u+1]))?m.length-1==u?t[o]:{}:[])}),i)};for(var o in t)_loop(o);return i}(o),o}function registerParser(t){for(var i in Object.assign(Ge,t.cmdConfig),t.cmdMap){var o=t.cmdMap[i],m=t.cmdConfig[o];if(m)if(Array.isArray(qe[i])){var h=!1;for(var u of qe[i])if(u.cmd===o&&u.config.service===m.service){h=!0;break}h||qe[i].push({config:m,cmd:o})}else qe[i]=[{config:m,cmd:o}]}}function invertSerializeItem(t){var i={};for(var o in t){var m=t[o];"number"==typeof m?i[m]=o:"object"==typeof m&&(i[m.id]={prop:o,type:m.retType,access:m.retAccess?m.retAccess:m.access?m.access:o,def:m.retDef,converter:m.retConverter})}return i}function boolToInt(t){return t?1:0}function intToBool(t){return 1===parseInt(t)}function objectToJSONString(t){if(t&&"object"==typeof t)try{return JSON.stringify(t)}catch(t){return}}function stringToJSONObject(t){if(t&&"string"==typeof t)try{return JSON.parse(t)}catch(t){return}}function format(t,i){if(!isPlainObject(i))return{};var o=JSON.parse(JSON.stringify(i)),m=doFormat(t,o);return JSON.parse(JSON.stringify(Object.assign(Object.assign({},o),m)))}function doFormat(t,i){if(!isPlainObject(i))return{};var o={};return Object.keys(t).forEach((m=>{var h=t[m].type;if("string"!=typeof h){var u=doFormat(t[m],i);Object.keys(u).length>0&&(o[m]=u)}else{var v=t[m],I=v.rawKey||m,_=He[h](i,I,v);void 0!==_&&(i[I]=void 0,o[m]=_)}})),o}var He={number:function(t,i){if(void 0!==t[i])return+t[i]},string:function(t,i){if(void 0!==t[i])return t[i]},boolean:function(t,i){return+t[i]>0||0!=+t[i]&&void 0},enum:function(t,i,o){return o.values[t[i]]},object:function(t,i){if(void 0!==t[i])try{return JSON.parse(t[i])}catch(t){return{}}}};function formatLoginInfo(t){return format({type:{type:"number"},port:{type:"number"},customClientType:{type:"number"},timestamp:{type:"number"},loginType:{type:"number"}},t)}var ze={"26_3":"v2Login","26_5":"v2Logout","26_8":"v2KickOffline","26_9":"v2BeKicked","26_10":"v2LoginClientChange","36_1":"v2GetChatroomLinkAddress"},Ye={"1_2":"heartbeat","2_7":"nimLoginClientChange","24_8":"qchatLoginClientChange"},Je={webLoginReqTag:{clientType:3,os:4,sdkVersion:6,appLogin:8,protocolVersion:9,pushTokenName:10,pushToken:11,clientId:13,appkey:18,account:19,browser:24,clientSession:26,deviceInfo:32,isReactNative:112,customTag:38,customClientType:39,sdkHumanVersion:40,hostEnv:41,userAgent:42,libEnv:44,authType:115,thirdPartyExtension:116,env:119,isRoutable:120,token:1e3},mixAuthRepTag:{clientId:1,consid:2,clientIP:3,port:4,type:5,customClientType:6,timestamp:7,customTag:8,os:9,pushType:10,hasTokenPreviously:11,loginType:12},nimAuthRepTag:{type:3,os:4,mac:5,clientId:13,account:19,deviceInfo:32,customTag:38,customClientType:39,consid:102,clientIP:103,port:104,timestamp:109,pushType:110,hasTokenPreviously:111},qchatAuthRepTag:{clientId:8,consid:102,clientIP:103,port:104,type:6,customClientType:13,timestamp:105,os:30,pushType:100,hasTokenPreviously:101}},Ke={v2Login:{sid:26,cid:3,service:"auth",params:[{type:"Property",name:"tag",reflectMapper:Je.webLoginReqTag}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Je.mixAuthRepTag)},{type:"PropertyArray",name:"loginClients",reflectMapper:invertSerializeItem(Je.mixAuthRepTag)}]},v2Logout:{sid:26,cid:5,service:"auth"},v2KickOffline:{sid:26,cid:8,service:"auth",params:[{type:"StrArray",name:"clientIds"}],response:[{type:"StrArray",name:"clientIds"}]},v2BeKicked:{sid:26,cid:9,service:"auth",response:[{type:"Int",name:"clientType"},{type:"Int",name:"reason"},{type:"String",name:"reasonDesc"},{type:"Int",name:"customClientType"}]},v2LoginClientChange:{sid:26,cid:10,service:"auth",response:[{type:"Byte",name:"state"},{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(Je.mixAuthRepTag)}]},v2GetChatroomLinkAddress:{sid:36,cid:1,service:"auth",params:[{type:"Long",name:"roomId"},{type:"Bool",name:"miniProgram"}],response:[{type:"StrArray",name:"linkAddress"}]}},We={heartbeat:{sid:1,cid:2,service:"auth"},nimLoginClientChange:{sid:2,cid:7,service:"auth",response:[{type:"Byte",name:"state"},{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(Je.nimAuthRepTag)}]},qchatLoginClientChange:{sid:24,cid:8,service:"auth",response:[{type:"Byte",name:"state"},{type:"Property",name:"data",reflectMapper:invertSerializeItem(Je.qchatAuthRepTag)}]}};class Backoff{constructor(t={}){this.attempts=0,this.ms=t.min||100,this.max=t.max||1e4,this.jitter=t.jitter||0,this.factor=t.factor||2}duration(){var t,i=Math.pow(this.factor,this.attempts++);if(i===1/0||!isFinite(i))return 0|this.max;if(t=this.ms*i,!isFinite(t)||t>=this.max)return 0|this.max;if(this.jitter){var o=Math.random(),m=Math.floor(o*this.jitter*t);t=0==(1&Math.floor(10*o))?t-m:t+m,t=Math.max(Math.min(t,this.max),this.ms)}return 0|t}reset(){this.attempts=0}setMin(t){this.ms=t}setMax(t){this.max=t}setJitter(t){this.jitter=t}}var abs=function(t){var i;if(void 0!==t)return(i=BigNumber(t)).sign=1,i},isArray=function(t){return"[object Array]"===Object.prototype.toString.call(t)},isValidType=function(t){return["number"==typeof t,"string"==typeof t&&t.length>0,isArray(t)&&t.length>0,t instanceof BigNumber].some((function(t){return!0===t}))},Xe="Invalid Number",Qe="Invalid Number - Division By Zero";function BigNumber(t){var i;if(!(this instanceof BigNumber))return new BigNumber(t);if(this.number=[],this.sign=1,this.rest=0,isValidType(t)){if(isArray(t)){for((t.length&&"-"===t[0]||"+"===t[0])&&(this.sign="+"===t[0]?1:-1,t.shift(0)),i=t.length-1;i>=0;i--)if(!this.addDigit(t[i]))return}else for("-"!==(t=t.toString()).charAt(0)&&"+"!==t.charAt(0)||(this.sign="+"===t.charAt(0)?1:-1,t=t.substring(1)),i=t.length-1;i>=0;i--)if(!this.addDigit(parseInt(t.charAt(i),10)))return}else this.number=Xe}BigNumber.prototype.addDigit=function(t){return function(t){return/^\d$/.test(t)}(t)?(this.number.push(t),this):(this.number=Xe,!1)},BigNumber.prototype._compare=function(t){var i,o;if(!isValidType(t))return null;if(i=BigNumber(t),this.sign!==i.sign)return this.sign;if(this.number.length>i.number.length)return this.sign;if(this.number.length<i.number.length)return-1*this.sign;for(o=this.number.length-1;o>=0;o--){if(this.number[o]>i.number[o])return this.sign;if(this.number[o]<i.number[o])return-1*this.sign}return 0},BigNumber.prototype.gt=function(t){return this._compare(t)>0},BigNumber.prototype.gte=function(t){return this._compare(t)>=0},BigNumber.prototype.equals=function(t){return 0===this._compare(t)},BigNumber.prototype.lte=function(t){return this._compare(t)<=0},BigNumber.prototype.lt=function(t){return this._compare(t)<0},BigNumber.prototype.subtract=function(t){var i;return void 0===t?this:(i=BigNumber(t),this.sign!==i.sign?(this.number=BigNumber._add(this,i),this):(this.sign=this.lt(i)?-1:1,this.number=abs(this).lt(abs(i))?BigNumber._subtract(i,this):BigNumber._subtract(this,i),this))},BigNumber._add=function(t,i){var o,m=0,h=Math.max(t.number.length,i.number.length);for(o=0;o<h||m>0;o++)t.number[o]=(m+=(t.number[o]||0)+(i.number[o]||0))%10,m=Math.floor(m/10);return t.number},BigNumber._subtract=function(t,i){var o,m=0,h=t.number.length;for(o=0;o<h;o++)t.number[o]-=(i.number[o]||0)+m,t.number[o]+=10*(m=t.number[o]<0?1:0);for(o=0,h=t.number.length-1;0===t.number[h-o]&&h-o>0;)o++;return o>0&&t.number.splice(-o),t.number},BigNumber.prototype.multiply=function(t){if(void 0===t)return this;var i,o,m=BigNumber(t),h=0,u=[];if(this.isZero()||m.isZero())return BigNumber(0);for(this.sign*=m.sign,i=0;i<this.number.length;i++)for(h=0,o=0;o<m.number.length||h>0;o++)u[i+o]=(h+=(u[i+o]||0)+this.number[i]*(m.number[o]||0))%10,h=Math.floor(h/10);return this.number=u,this},BigNumber.prototype.divide=function(t){if(void 0===t)return this;var i,o,m=BigNumber(t),h=[],u=BigNumber(0);if(m.isZero())return this.number=Qe,this;if(this.isZero())return this.rest=BigNumber(0),this;if(this.sign*=m.sign,m.sign=1,1===m.number.length&&1===m.number[0])return this.rest=BigNumber(0),this;for(i=this.number.length-1;i>=0;i--)for(u.multiply(10),u.number[0]=this.number[i],h[i]=0;m.lte(u);)h[i]++,u.subtract(m);for(i=0,o=h.length-1;0===h[o-i]&&o-i>0;)i++;return i>0&&h.splice(-i),this.rest=u,this.number=h,this},BigNumber.prototype.mod=function(t){return this.divide(t).rest},BigNumber.prototype.isZero=function(){var t;for(t=0;t<this.number.length;t++)if(0!==this.number[t])return!1;return!0},BigNumber.prototype.toString=function(){var t,i="";if("string"==typeof this.number)return this.number;for(t=this.number.length-1;t>=0;t--)i+=this.number[t];return this.sign>0?i:"-"+i};var Ze,et=Math.pow(2,32);function varintToBytes(t){for(var i=new Uint8Array(5),o=new DataView(i.buffer),m=0;0!=(4294967168&t);)o.setUint8(m++,127&t|128),t>>>=7;return o.setUint8(m++,127&t),i.slice(0,m)}function decodeText(t){return"function"==typeof TextDecoder?new TextDecoder("utf-8").decode(t):function textDecoder(t){for(var i="",o=0;o<t.length;){var m=t[o],h=0,u=0;if(m<=127?(h=0,u=255&m):m<=223?(h=1,u=31&m):m<=239?(h=2,u=15&m):m<=244&&(h=3,u=7&m),t.length-o-h>0)for(var v=0;v<h;)u=u<<6|63&(m=t[o+v+1]),v+=1;else u=65533,h=t.length-o;i+=String.fromCodePoint(u),o+=h+1}return i}(t)}class Unpack{constructor(t){this.offset=0,this.buffer=new Uint8Array(t),this.view=new DataView(t)}checkBufferBoundaryAccess(){return this.offset>=this.buffer.byteLength}length(){var t;return(null===(t=this.view)||void 0===t?void 0:t.byteLength)||0}getBuffer(){return this.view.buffer}getOffset(){return this.offset}popRaw(t){try{var i=this.buffer.slice(this.offset,this.offset+t);return this.offset+=t,i}catch(t){throw new Error(`UnpackException raw ${t&&t.message}`)}}popByte(){try{var t=this.view.getUint8(this.offset);return this.offset+=1,t}catch(t){throw new Error(`UnpackException byte ${t&&t.message}`)}}popVarbin(){return this.popRaw(this.popVarInt())}popString(){try{return decodeText(this.popVarbin())}catch(t){throw new Error(`UnpackException string ${t&&t.message}`)}}popInt(){try{var t=this.view.getUint32(this.offset,!0);return this.offset+=4,t}catch(t){throw new Error(`UnpackException int ${t&&t.message}`)}}popVarInt(){var t=1,i=0,o=0,m=0;do{if(i+=(127&(o=this.popByte()))*t,t*=128,(m+=1)>5)throw new Error("Variable length quantity is too long")}while(0!=(128&o));return i}popLong(){try{var t=function getBigUint64(t,i=!1){var o=new DataView(t.buffer),[m,h]=i?[4,0]:[0,4],u=o.getUint32(m,i),v=o.getUint32(h,i);return u>0?u*et+v:v}(this.buffer.slice(this.offset,this.offset+8),!0);return this.offset+=8,Number(t)}catch(t){throw new Error(`UnpackException long ${t&&t.message}`)}}popShort(){try{var t=this.view.getUint16(this.offset,!0);return this.offset+=2,t}catch(t){throw new Error(`UnpackException short ${t&&t.message}`)}}popBoolean(){return this.popByte()>0}toString(){return Array.from(new Uint8Array(this.buffer)).toString()}reset(){this.offset=0,this.buffer=null,this.view=null}}class PacketDecoder{constructor(t){this.packetLength=0,this.serviceId=0,this.commandId=0,this.serialId=0,this.tag=0,this.resCode=200,this.innerHeader=null,this.msgId=0,this.bodyArr=[],this.unpack=new Unpack(t)}reset(){this.innerHeader=null,this.bodyArr=[],this.unpack.reset()}getBodyDetail(){return this.bodyArr.join("")}unmarshalHeader(){var t=this._unmarshalHeader();this.packetLength=t.packetLength,this.serviceId=t.serviceId,this.commandId=t.commandId,this.serialId=t.serialId,this.tag=t.tag,this.resCode=t.resCode,4===t.serviceId&&[1,2,10,11].includes(t.commandId)&&(this.msgId=this.unmarshalLong(),this.innerHeader=this._unmarshalHeader())}_unmarshalHeader(){var t=this.unpack.popVarInt(),i=this.unpack.popByte(),o=this.unpack.popByte(),m=this.unpack.popShort(),h=this.unpack.popByte(),u=200;return this.hasRescode(h)&&(u=this.unpack.popShort()),{packetLength:t,serviceId:i,commandId:o,serialId:m,tag:h,resCode:u}}hasRescode(t){return 0!=((t=t||this.tag)&PacketDecoder.RES_CODE)}getHeader(){return{packetLength:this.packetLength,sid:this.serviceId,cid:this.commandId,ser:this.serialId,code:this.resCode}}getInnerHeader(){return this.innerHeader?{sid:this.innerHeader.serviceId,cid:this.innerHeader.commandId}:null}unmarshalProperty(){var t=this.unpack.popVarInt(),i={};this.bodyArr.push(`\nProperty(${t}) {`);for(var o=0;o<t;o++){var m=this.unpack.popVarInt();this.bodyArr.push(`${m}:`);var h=this.unpack.popString();this.bodyArr.push(`"${h.length} ${this.unpack.getOffset()}",`),i[m]=h}return this.bodyArr.push("},"),i}unmarshalPropertyArray(){var t=this.unpack.popVarInt(),i=[];this.bodyArr.push(`\nPropertyArray(${t}) [`);for(var o=0;o<t;o++)i.push(this.unmarshalProperty());return this.bodyArr.push("],"),i}unmarshalLong(){var t=this.unpack.popLong();return this.bodyArr.push(`\nLong:${t}`),t}unmarshalLongArray(){var t=this.unpack.popVarInt(),i=[];this.bodyArr.push(`\nLongArray ${t}:`);for(var o=0;o<t;o++){var m=this.unpack.popLong();this.bodyArr.push(`${m},`),i.push(m)}return i}unmarshalStrArray(){var t=this.unpack.popVarInt(),i=[];this.bodyArr.push(`\nStrArray ${t}:`);for(var o=0;o<t;o++){var m=this.unpack.popString();this.bodyArr.push(`${m},`),i.push(m)}return i}unmarshalStrLongMap(){var t=this.unpack.popVarInt(),i={};this.bodyArr.push(`\nStrLongMap ${t}:`);for(var o=0;o<t;o++){var m=this.unpack.popString();this.bodyArr.push(`${m},`);var h=this.unpack.popLong();this.bodyArr.push(`${h};`),i[m]=h}return i}unmarshalStrStrMap(){var t=this.unpack.popVarInt(),i={};this.bodyArr.push(`\nStrStrMap ${t}:`);for(var o=0;o<t;o++){var m=this.unpack.popString();this.bodyArr.push(`${m},`);var h=this.unpack.popString();this.bodyArr.push(`${h};`),i[m]=h}return i}unmarshalLongLongMap(){var t=this.unpack.popVarInt(),i={};this.bodyArr.push(`\nStrLongLongMap ${t}:`);for(var o=0;o<t;o++){var m=this.unpack.popLong();this.bodyArr.push(`${m},`);var h=this.unpack.popLong();this.bodyArr.push(`${h};`),i[m]=h}return{m_map:i}}unmarshalKVArray(){var t=this.unpack.popVarInt(),i=[];this.bodyArr.push(`\nKVArray ${t}:`);for(var o=0;o<t;o++)i.push(this.unmarshalStrStrMap());return i}unmarshal(t){var i=Object.assign(Object.assign({},this.getHeader()),{r:[]});if(this.innerHeader&&(i.r[0]=this.msgId,i.r[1]={body:[],headerPacket:this.getInnerHeader()}),![200,406,808,810,7101].includes(i.code))return JSON.stringify(i);if(this.packetLength>0&&this.packetLength>this.unpack.length())throw new Error(`UnpackException packetLength(${this.packetLength}) greater than bufferLength(${this.unpack.length()})`);var o=[];return t&&t.forEach((t=>{if(!this.unpack.checkBufferBoundaryAccess())switch(t.type){case"PropertyArray":o.push(this.unmarshalPropertyArray());break;case"Property":o.push(this.unmarshalProperty());break;case"Byte":o.push(this.unpack.popByte());break;case"Int":o.push(this.unpack.popInt());break;case"Bool":o.push(this.unpack.popBoolean());break;case"Long":o.push(this.unmarshalLong());break;case"LongArray":o.push(this.unmarshalLongArray());break;case"String":o.push(this.unpack.popString());break;case"StrArray":o.push(this.unmarshalStrArray());break;case"StrStrMap":o.push(this.unmarshalStrStrMap());break;case"StrLongMap":o.push(this.unmarshalStrLongMap());break;case"LongLongMap":o.push(this.unmarshalLongLongMap());break;case"KVArray":o.push(this.unmarshalKVArray())}})),this.innerHeader?i.r[1].body=o:i.r=o,JSON.stringify(i)}}PacketDecoder.RES_CODE=2;class Pack{constructor(){this.offset=0,this.pageSize=1024,this.capacity=1048576,this.buffer=new Uint8Array(this.pageSize),this.view=new DataView(this.buffer.buffer)}reset(){this.offset=0,this.buffer=null,this.view=null}size(){return this.offset}getBuffer(){return this.buffer.slice(0,this.offset).buffer}ensureCapacity(t){var i=this.offset+t;if(i>this.capacity)throw new Error("PackException over limit");if(i>this.buffer.byteLength){var o=Math.ceil(i/this.pageSize)*this.pageSize,m=new Uint8Array(o);m.set(this.buffer),this.buffer=m,this.view=new DataView(this.buffer.buffer)}}putRaw(t){this.ensureCapacity(t.length);try{this.buffer.set(t,this.offset),this.offset+=t.length}catch(t){throw new Error("PackException raw")}}putByte(t){this.ensureCapacity(1);try{this.view.setUint8(this.offset++,t)}catch(t){throw new Error("PackException byte")}}putString(t){try{var i=function encodeText(t){if("function"==typeof TextEncoder)return(new TextEncoder).encode(t);var i=function textEncoder(t){for(var i=[],o=t.length,m=0;m<o;){var h=t.codePointAt(m),u=0,v=0;for(h<=127?(u=0,v=0):h<=2047?(u=6,v=192):h<=65535?(u=12,v=224):h<=2097151&&(u=18,v=240),i.push(v|h>>u),u-=6;u>=0;)i.push(128|h>>u&63),u-=6;m+=h>=65536?2:1}return i}(t);return new Uint8Array(i)}(t);this.putVarbin(i)}catch(t){throw new Error("PackException string")}}putInt(t){this.ensureCapacity(4);try{this.view.setInt32(this.offset,t,!0),this.offset+=4}catch(t){throw new Error("PackException int")}}putVarInt(t){var i=varintToBytes(t);this.putRaw(i)}putBoolean(t){this.ensureCapacity(1);try{this.view.setUint8(this.offset++,t?1:0)}catch(t){throw new Error("PackException boolean")}}putLong(t){this.ensureCapacity(8);try{var i=function setBigUint64(t,i=!1){var o=new Uint8Array(8),m=new DataView(o.buffer),h=Number(t>et-1?t/et:0),u=Number(4294967295&t),[v,I]=i?[4,0]:[0,4];return m.setUint32(v,h,i),m.setUint32(I,u,i),o}(t,!0);this.buffer.set(i,this.offset),this.offset+=8}catch(t){throw new Error("PackException long")}}putStringAsLong(t){this.ensureCapacity(8);try{var i=function setBigUint64ForNumberOverflow(t,i=!1){var o=new Uint8Array(8),m=new DataView(o.buffer),h=BigNumber(t).divide(et).number.reverse().join(""),u=BigNumber(t).mod(et).number.reverse().join(""),v=Number(h),I=Number(u),[_,M]=i?[4,0]:[0,4];return m.setUint32(_,v,i),m.setUint32(M,I,i),o}(t,!0);this.buffer.set(i,this.offset),this.offset+=8}catch(t){throw new Error("PackException stringAsLong")}}putShort(t){this.ensureCapacity(2);try{this.view.setInt16(this.offset,t,!0),this.offset+=2}catch(t){throw new Error("PackException short")}}putVarbin(t){if(!t)return this.ensureCapacity(1),this.putVarInt(0);if(t.byteLength>Math.pow(2,31)-2)throw new Error("PackException varbin. too long");var i=varintToBytes(t.length);this.ensureCapacity(i.length+t.length);try{this.buffer.set(i,this.offset),this.offset+=i.length,this.buffer.set(t,this.offset),this.offset+=t.length}catch(t){throw new Error("PackException varbin")}}}function isConvertibleToNumber(t){if("number"!=typeof t){if(null==t)return!1;t=Number(t)}if(isNaN(t))throw new Error("Number type conversion error");return!0}function isUndefinedOrNull(t){return null==t}class PacketEncoder{constructor(t,i,o){this.pack=new Pack,this.packetLength=0,this.serviceId=0,this.commandId=0,this.serialId=0,this.tag=0,this.serviceId=t,this.commandId=i,this.serialId=o}marshalHeader(){this.pack.putVarInt(this.packetLength),this.pack.putByte(this.serviceId),this.pack.putByte(this.commandId),this.pack.putShort(this.serialId),this.pack.putByte(this.tag)}marshalProperty(t){var i=Object.keys(t).filter((t=>!isUndefinedOrNull(t)));this.pack.putVarInt(i.length),i.forEach((i=>{this.pack.putVarInt(Number(i)),Array.isArray(t[i])||"[object Object]"===Object.prototype.toString.call(t[i])?this.pack.putString(JSON.stringify(t[i])):this.pack.putString(String(t[i]))}))}marshalPropertyArray(t){var i=t.length;this.pack.putVarInt(i),t.forEach((t=>{this.marshalProperty(null==t?void 0:t.v)}))}marshalStrArray(t){var i=t.filter((t=>!isUndefinedOrNull(t))),o=i.length;this.pack.putVarInt(o),i.forEach((t=>{this.pack.putString(String(t))}))}marshalLongArray(t){var i=t.filter((t=>isConvertibleToNumber(t))),o=i.length;this.pack.putVarInt(o),i.forEach((t=>{this.putLong(t)}))}marshalStrStrMap(t){var i=Object.keys(t).filter((i=>!isUndefinedOrNull(t[i])&&!isUndefinedOrNull(i)));this.pack.putVarInt(i.length),i.forEach((i=>{this.pack.putString(String(i)),this.pack.putString(String(t[i]))}))}marshalStrLongMap(t){var i=Object.keys(t).filter((i=>isConvertibleToNumber(t[i])&&!isUndefinedOrNull(i)));this.pack.putVarInt(i.length),i.forEach((i=>{this.pack.putString(String(i)),this.putLong(t[i])}))}marshalLongLongMap(t){var i=Object.keys(t).filter((i=>{var o=Number(i);return isConvertibleToNumber(o)&&isConvertibleToNumber(t[o])}));this.pack.putVarInt(i.length),i.forEach((i=>{var o=Number(i);this.putLong(o),this.putLong(t[o])}))}marshalKVArray(t){var i=t.length;this.pack.putVarInt(i),t.forEach((t=>{this.marshalStrStrMap(t)}))}putLong(t){"string"==typeof t&&t.length>15?this.pack.putStringAsLong(t):this.pack.putLong(Number(t))}marshal(t,i){return this.marshalHeader(),i&&i.forEach(((i,o)=>{var m,h=i.type,u=null===(m=t[o])||void 0===m?void 0:m.v;if(!isUndefinedOrNull(u))switch(h){case"PropertyArray":this.marshalPropertyArray(u);break;case"Property":this.marshalProperty(u);break;case"Byte":if(!isConvertibleToNumber(u))return;this.pack.putByte(Number(u));break;case"Int":if(!isConvertibleToNumber(u))return;this.pack.putInt(Number(u));break;case"Bool":"false"===u?u=!1:"true"===u&&(u=!0),this.pack.putBoolean(u);break;case"Long":if(!isConvertibleToNumber(u))return;this.putLong(u);break;case"LongArray":this.marshalLongArray(u);break;case"String":this.pack.putString(String(u));break;case"StrArray":this.marshalStrArray(u);break;case"StrStrMap":this.marshalStrStrMap(u);break;case"StrLongMap":this.marshalStrLongMap(u);break;case"LongLongMap":this.marshalLongLongMap(u);break;case"KVArray":this.marshalKVArray(u)}})),this.pack.getBuffer()}reset(){this.pack.reset()}}class BaseWebsocket$1 extends Ie{constructor(t,i,o){super(),this.websocket=null,this.socketConnectTimer=0,this.linkSSL=!0,this.url="",this.core=t,this.url=i,this.linkSSL=o,this.status="disconnected",this.logger=t.logger,this.connect()}connect(){"connecting"!==this.status&&"connected"!==this.status?(this.status="connecting",this._createWebsocket(`${this.linkSSL?"wss":"ws"}://${this.url}/websocket`)):this.logger.warn("imsocket::socket is connecting or connected",this.status)}close(){if(this.status="disconnected",this.websocket){this.logger.log("imsocket:: close websocket");try{this.websocket.close()}catch(t){this.logger.warn("imsocket::attempt to close websocket error",t)}this.clean(),this.emit("disconnect")}}clean(){this.status="disconnected",clearTimeout(this.socketConnectTimer),this.websocket&&(this.socketUrl=void 0,this.websocket.onmessage=null,this.websocket.onopen=null,this.websocket.onerror=null,this.websocket.onclose=null,this.websocket=null)}onConnect(){this.status="connected",this.emit("connect"),clearTimeout(this.socketConnectTimer)}_createWebsocket(t){this.socketConnectTimer=setTimeout((()=>{this.logger.error("imsocket::Websocket connect timeout. url: ",t),this.emit("connectFailed",new V2NIMErrorImpl({code:"v2"===get(this.core,"options.apiVersion")?Ee.V2NIM_ERROR_CODE_CONNECT_TIMEOUT:415,detail:{reason:`imsocket::Websocket connect timeout. url: ${t}`}}))}),this.core.options.socketConnectTimeout||8e3),this.socketUrl=t,this.websocket=new Re.WebSocket(t),this.websocket.binaryType="arraybuffer",this.websocket.onmessage=this.onMessage.bind(this),this.websocket.onclose=t=>{t=t||{},this.logger.log(`imsocket::Websocket onclose done ${t.wasClean}/${t.code}/${t.reason}`),"connected"===this.status?(this.clean(),this.emit("disconnect")):(this.clean(),this.emit("connectFailed",new V2NIMErrorImpl({code:"v2"===get(this.core,"options.apiVersion")?Ee.V2NIM_ERROR_CODE_CONNECT_FAILED:414,detail:{reason:"imsocket::Websocket onclose done"}})))},this.websocket.onerror=t=>{this.logger.error("imsocket::Websocket onerror",t),"connected"===this.status?(this.clean(),this.emit("disconnect")):(this.clean(),this.emit("connectFailed",new V2NIMErrorImpl({code:"v2"===get(this.core,"options.apiVersion")?Ee.V2NIM_ERROR_CODE_CONNECT_FAILED:414,detail:{reason:"imsocket::Websocket onerror."}})))},this.websocket.onopen=()=>{this.onConnect()}}onMessage(t){if(t.data){var i=new PacketDecoder(t.data),o={sid:-1,cid:-1,ser:-1,packetLength:-1},m=null;try{i.unmarshalHeader(),o=i.getHeader(),m=i.getInnerHeader()}catch(i){this.reportBinaryError({err:i,sid:m?m.sid:null==o?void 0:o.sid,cid:m?m.cid:null==o?void 0:o.cid,rawBuf:t.data,type:"decode"})}var h=m?m.sid:o.sid,u=m?m.cid:o.cid,v=`${h}_${u}`,I=qe[v];if(I&&I.length>0){var _,M=I[0].config;try{_=i.unmarshal(M.response)}catch(m){var E=i.getBodyDetail();this.reportBinaryError({err:m,rawBuf:t.data,sid:h,cid:u,parseDetail:E,type:"decode"}),i.reset();var S=Object.assign(Object.assign({},o),{sid:h,cid:u,code:Ee.V2NIM_ERROR_CODE_UNPACK_ERROR});return this.logger.error(`imsocket::onMessage "${S.sid}_${S.cid}", ser ${S.ser}, packetLength ${S.packetLength} unmarshal error. ${E} \n`,m),void this.emit("message",JSON.stringify(S))}this.emit("message",_)}else this.core.logger.warn("imsocket::onMessage cmd not found",v);i.reset()}}send(t,i,o,m,h){var u,v,I=new PacketEncoder(t,i,o),_=Ge[m],M="";try{M=JSON.stringify(h),v=I.marshal(JSON.parse(M),_.params)}catch(m){throw this.reportBinaryError({err:m,sid:t,cid:i,rawStr:M,type:"encode"}),I.reset(),new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_PACK_ERROR,detail:{reason:`${t}-${i}, ser ${o} marshal error`,rawError:m}})}null===(u=this.websocket)||void 0===u||u.send(v),I.reset()}reportBinaryError(t){var i,o,m,{err:h,rawStr:u,sid:v,cid:I,type:_,parseDetail:M}=t,E=t.rawBuf;if(E){try{m=function arrayBufferToBase64(t){if("function"!=typeof btoa)return"";for(var i="",o=new Uint8Array(t),m=o.byteLength,h=0;h<m;h++)i+=String.fromCharCode(o[h]);return o=null,btoa(i)}(E)}catch(t){m=`reportBinaryError::arrayBufferToBase64 parsing failed, error: ${null==t?void 0:t.message}, sid: ${v}, cid: ${I}`,this.core.logger.error(m)}E=null}this.core.reporter.reportTraceStart("exceptions",{user_id:null===(i=this.core.auth)||void 0===i?void 0:i.account,trace_id:null===(o=this.core.clientSocket.socket)||void 0===o?void 0:o.sessionId,start_time:Date.now(),action:2,exception_service:9});var S=h?(`${h.message};;;`||`${h.code};;;`)+(M?`parseDetail: ${M};;;`:"")+(u?` rawStr: ${u}`:"")+(m?` rawBuf: ${m}`:""):"";this.core.reporter.reportTraceUpdateV2("exceptions",{code:"encode"===_?Ee.V2NIM_ERROR_CODE_PACK_ERROR:Ee.V2NIM_ERROR_CODE_UNPACK_ERROR,description:S,operation_type:"encode"===_?3:4,target:`${v}-${I}`},{asyncParams:Re.net.getNetworkStatus()}),this.core.reporter.reportTraceEnd("exceptions",1)}}!function(t){t[t.ACTIVE=1]="ACTIVE",t[t.KICKED=2]="KICKED",t[t.OFFLINE=3]="OFFLINE"}(Ze||(Ze={}));class V2BinaryClientSocket{constructor(t){this.isReconnect=!1,this.packetTimeout=8e3,this.linkSSL=!0,this.packetSer=1,this.backoff=new Backoff({max:8e3,min:1600,jitter:.01}),this.sendingCmdMap=new Map,this.pingTimer=0,this.hasNetworkListener=!1,this.core=t,this.auth=t.auth,this.logger=t.logger,this.reporter=t.reporter,this.timerManager=t.timerManager,this.eventBus=t.eventBus,this.setListener()}setListener(){this.core.eventBus.on("V2NIMLoginService/loginLifeCycleLoginSucc",(()=>{this.isReconnect=!0}))}setSessionId(t){this.socket&&(this.socket.sessionId=t)}setLinkSSL(t){this.linkSSL=t}connect(t,i=!1){var o,m;return __awaiter(this,void 0,void 0,(function*(){this.isReconnect=i;var h=this.core.auth.getConnectStatus();if(1===h){var u=`clientSocket::connect status is ${h}, and would not repeat connect`,v=new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_ILLEGAL_STATE,detail:{reason:u}});return this.logger.warn(u),Promise.reject(v)}this.auth.lifeCycle.processEvent("connect");try{yield this.auth.doLoginStepsManager.add(this.doConnect(t)),this.logger.log(`clientSocketV2:: connect success with link url: ${t}, isReconnect: ${i}`),this.core.reporter.reportTraceUpdateV2("login",{operation_type:"TCP",target:t,code:200,mixlink:!0,succeed:!0},{asyncParams:Re.net.getNetworkStatus()}),this.auth.lifeCycle.processEvent("connectSucc")}catch(i){var I=i;if(this.core.reporter.reportTraceUpdateV2("login",{operation_type:"TCP",target:t,code:I.code||0,description:`connectFailed:${I.message}`,mixlink:!0,succeed:!1},{asyncParams:Re.net.getNetworkStatus()}),I.code===Ee.V2NIM_ERROR_CODE_CANCELLED||I.code===Ee.V2NIM_ERROR_CODE_TIMEOUT)throw null===(o=this.socket)||void 0===o||o.close(),null===(m=this.socket)||void 0===m||m.removeAllListeners(),this.socket=void 0,i;throw this.logger.warn(`clientSocketV2::connect failed with link url: ${t}`,I),this.auth.lifeCycle.processEvent("connectFail",I),i}}))}doConnect(t){var i=!1;return new Promise(((o,m)=>{this.socket=new BaseWebsocket$1(this.core,t,this.linkSSL),this.socket.on("connect",(()=>{this.logger.log("clientSocketV2::socket on connect",t),this.core.reporterHookLinkKeep.start(),this.core.reporterHookLinkKeep.update({code:0,description:"connection begin",operation_type:0,target:t}),i=!0,o()})),this.socket.on("message",this.onMessage.bind(this)),this.socket.on("disconnect",(o=>__awaiter(this,void 0,void 0,(function*(){i=!0,this.logger.log(`clientSocketV2::socket on disconnect ${t}`,o),yield this.core.reporterHookLinkKeep.update({code:(null==o?void 0:o.code)||0,description:(null==o?void 0:o.reason)||"socket on disconnect",operation_type:1,target:t}),this.core.reporterHookLinkKeep.end(!1),this.doDisconnect(Ze.OFFLINE,"SocketOnDisconnect")})))),this.socket.on("connectFailed",(o=>{i?this.ping():(this.logger.error(`clientSocketV2::connectFailed:${t}, reason:${o&&o.message}`),this.cleanSocket()),i=!0,m(o)}))}))}cleanSocket(){this.socket&&("function"==typeof this.socket.removeAllListeners&&this.socket.removeAllListeners(),"function"==typeof this.socket.close&&this.socket.close(),this.socket=void 0)}resetSocketConfig(){this.backoff.reset(),this.initOnlineListener()}doDisconnect(t,i){if(this.logger.log(`clientSocketV2::doDisconnect:type:${t},reason:`,i),0!==this.core.auth.getConnectStatus()){var o={1:"close",2:"kicked",3:"broken"}[t]||"";this.markAllCmdInvaild(new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_DISCONNECT,detail:{reason:"Packet timeout due to instance disconnect",disconnect_reason:o}})),this.timerManager.destroy(),clearTimeout(this.pingTimer),this.cleanSocket(),t===Ze.ACTIVE||t===Ze.KICKED?this.destroyOnlineListener():t===Ze.OFFLINE&&(this.auth.lifeCycle.processEvent("connectionBroken",new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_DISCONNECT,detail:{reason:"connection broken due to internal reasons"}})),this.logger.log(`clientSocketV2::doDisconnect: pending reconnect ${this.isReconnect}`),this.isReconnect&&this.auth.lifeCycle.processEvent("waiting"))}else this.logger.warn("clientSocketV2::doDisconnect:already disconnected")}sendCmd(t,i,o){var m=this.core.auth.getLoginStatus(),h={cmd:t};if(1!==m&&!["v2Login","login","chatroomLogin","v2ChatroomLogin"].includes(t))return this.logger.warn(`clientSocketV2::NIM login status is ${m}, so can not sendCmd ${t}`),Promise.reject(new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_ILLEGAL_STATE,detail:Object.assign({reason:"Can not sendCmd due to no logined"},h)}));var u="heartbeat"!==t,v=u?this.packetSer++:0,I=createCmd(t,v,this.logger,i);if(!I){var _=new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INTERNAL,detail:Object.assign(Object.assign({},h),{reason:`SendCmd::createCmd error: ${v} ${t}`})});return this.logger.error(_),Promise.reject(_)}var{packet:M,hasPacketResponse:E,hasPacketTimer:S}=I,T=JSON.stringify(M);u&&(this.logger.getDebugMode()?this.logger.debug(`clientSocketV2::sendCmd: ${M.SID}_${M.CID},${t},ser:${v}`,T):this.logger.log(`clientSocketV2::sendCmd: ${M.SID}_${M.CID},${t},ser:${v}`));var C=(new Date).getTime();return new Promise(((m,u)=>{E&&this.sendingCmdMap.set(v,{cmd:t,params:i,callback:[m,u],timer:S?setTimeout((()=>{var i=new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_PROTOCOL_TIMEOUT,detail:Object.assign({ser:v,reason:`Packet Timeout: ser ${v} cmd ${t}`,timetag:(new Date).getTime()},h)});this.markCmdInvalid(v,i,t)}),o&&o.timeout?o.timeout:this.packetTimeout):null});try{this.socket.send(M.SID,M.CID,v,t,M.Q),E||m(M)}catch(i){var I=new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_PROTOCOL_SEND_FAILED,detail:Object.assign({ser:v,reason:"Unable to send packet"+(i&&i.message?": "+i.message:""),timetag:(new Date).getTime(),rawError:i},h)});this.markCmdInvalid(v,I,t),u(I)}})).catch((t=>__awaiter(this,void 0,void 0,(function*(){var i=t;return[Ee.V2NIM_ERROR_CODE_DISCONNECT,Ee.V2NIM_ERROR_CODE_PROTOCOL_TIMEOUT,Ee.V2NIM_ERROR_CODE_PROTOCOL_SEND_FAILED].includes(i.code)?(this.reportSendCmdFailed(i,{sid:M.SID,cid:M.CID,ser:v},C),Promise.reject(i)):Promise.reject(i)}))))}reportSendCmdFailed(t,i,o){var m;this.reporter.reportTraceStart("exceptions",{user_id:this.core.auth.getLoginUser(),trace_id:null===(m=this.socket)||void 0===m?void 0:m.sessionId,start_time:o,action:2,exception_service:6});var h=get(t,"detail.disconnect_reason")||"",u=t.code===Ee.V2NIM_ERROR_CODE_DISCONNECT?JSON.stringify({disconnect_reason:h}):t.detail.reason;this.reporter.reportTraceUpdateV2("exceptions",{code:t.code,description:u,operation_type:1,target:`${i.sid}-${i.cid}`,context:`${i.ser}`},{asyncParams:Re.net.getNetworkStatus()}),this.reporter.reportTraceEnd("exceptions",1)}onMessage(t){var i=parseCmd(t,this.logger);if(i&&i.length>0){var o=i[0],m=o.raw.ser;for(var h of(o.error&&(this.logger.error("clientSocketV2::onMessage packet error",`${o.raw.sid}_${o.raw.cid}, ser:${m},`,o.error),o.error.code===Ee.V2NIM_ERROR_CODE_UNPACK_ERROR&&this.core.eventBus.emit("BinaryClientSocket/unpackError")),"heartbeat"!==o.cmd&&(this.logger.getDebugMode()?this.logger.debug(`clientSocketV2::recvCmd ${o.raw.sid}_${o.raw.cid},${o.cmd},ser:${m}`,t):this.logger.log(`clientSocketV2::recvCmd ${o.raw.sid}_${o.raw.cid},${o.cmd},ser:${m},code:${o.raw.code}`)),i))this.packetHandler(h)}}packetHandler(t){var i,o,m,h;if(t){var u=t.raw.ser,v=this.sendingCmdMap.get(u);if(v&&v.cmd===t.cmd){var{callback:I,timer:_,params:M}=v;if(clearTimeout(_),t.params=M,this.sendingCmdMap.delete(u),"heartbeat"===t.cmd)return void I[0]();var E=null===(o=null===(i=this.core[t.service])||void 0===i?void 0:i.process)||void 0===o?void 0:o.call(i,t);E&&"function"==typeof E.then?E.then((t=>{I[0](t)})).catch((t=>{I[1](t)})):(this.logger.log("clientSocketV2::handlerFn without promise",t.service,t.cmd),I[0](t))}else{var S=null===(h=null===(m=this.core[t.service])||void 0===m?void 0:m.process)||void 0===h?void 0:h.call(m,t);S&&"function"==typeof S.then&&S.catch((t=>{this.logger.error("clientSocketV2::no obj cache, no process handler",t)}))}}}markCmdInvalid(t,i,o){var m=this.sendingCmdMap.get(t);if(m){var{callback:h,timer:u}=m;u&&clearTimeout(u),this.sendingCmdMap.delete(t),this.logger.warn(`clientSocketV2::packet ${t}, ${o} is invalid:`,i),h[1](i)}}markAllCmdInvaild(t){this.logger.log("markAllCmdInvaild",t),this.sendingCmdMap.forEach((i=>{var{callback:o,timer:m,cmd:h}=i;this.logger.log(`clientSocketV2::markAllCmdInvaild:cmd ${h}`),m&&clearTimeout(m),o[1](t)})),this.sendingCmdMap.clear()}ping(){var t;return __awaiter(this,void 0,void 0,(function*(){clearTimeout(this.pingTimer);try{yield this.sendCmd("heartbeat")}catch(i){if(i.code===Ee.V2NIM_ERROR_CODE_DISCONNECT)return;if(yield this.testHeartBeat5Timeout())return yield this.core.reporterHookLinkKeep.update({code:0,description:"Heartbeat-discovered link failure",operation_type:1,target:null===(t=this.socket)||void 0===t?void 0:t.url}),this.core.reporterHookLinkKeep.end(!0),void this.doDisconnect(Ze.OFFLINE,"PingError")}this.pingTimer=setTimeout((()=>{this.ping()}),3e4)}))}testHeartBeat5Timeout(){return __awaiter(this,void 0,void 0,(function*(){clearTimeout(this.pingTimer);for(var t=0;t<5;t++)try{return yield this.sendCmd("heartbeat",{},{timeout:3e3}),!1}catch(i){this.logger.log(`clientSocketV2::test heartbeat ${t} Timeout`)}return!0}))}initOnlineListener(){this.hasNetworkListener||(this.logger.log("clientSocketV2::onlineListener:init"),this.hasNetworkListener=!0,Re.net.onNetworkStatusChange((t=>{this.logger.log("clientSocketV2::onlineListener:network change",t);var i=this.auth.getLoginStatus();t.isConnected&&1===i?this.ping():t.isConnected&&3===i?(this.logger.log("clientSocketV2::onlineListener:online and connectStatus is waiting, do reLogin"),this.auth.reconnect.clearReconnectTimer(),this.auth.reconnect.doReLogin()):t.isConnected||this.doDisconnect(Ze.OFFLINE,"OfflineListener")})))}destroyOnlineListener(){this.logger.log("clientSocketV2::onlineListener:destroy"),Re.net.offNetworkStatusChange(),this.hasNetworkListener=!1}}var it,rt=["disconnect","connect","heartbeat","message","json","event","ack","error","noop"],nt=["transport not supported","client not handshaken","unauthorized"],ot=["reconnect"];class BaseWebsocket extends Ie{constructor(t,i,o){super(),this.websocket=null,this.socketConnectTimer=0,this.url="",this.linkSSL=!0,this.core=t,this.url=i,this.linkSSL=o,this.status="disconnected",this.logger=t.logger,this.connect()}connect(){"connecting"!==this.status&&"connected"!==this.status?(this.status="connecting",this.core.adapters.request(`${this.linkSSL?"https":"http"}://${this.url}/socket.io/1/?t=${Date.now()}`,{method:"GET",dataType:"text",timeout:this.core.options.xhrConnectTimeout||8e3},{exception_service:6}).then((t=>{if("connecting"===this.status){var[i,o]=t.data.split(":");return this.sessionId=i,this.logger.log(`imsocket::XHR success. status ${this.status}, ${"connecting"===this.status?"continue websocket connection":"stop websocket connection"}`),this._createWebsocket(`${this.linkSSL?"wss":"ws"}://${this.url}/socket.io/1/websocket/${i}`)}})).catch((t=>{if("connecting"===this.status){var i=`imsocket::XHR fail. raw message: "${(t=t||{}).message}", code: "${t.code}"`,o=t.code;o="v2"===get(this.core,"options.apiVersion")?t.code===Ee.V2NIM_ERROR_CODE_CONNECT_TIMEOUT?Ee.V2NIM_ERROR_CODE_CONNECT_TIMEOUT:Ee.V2NIM_ERROR_CODE_CONNECT_FAILED:408===t.code?408:415;var m=new V2NIMErrorImpl({code:o,detail:{reason:i,rawError:t}});this.logger.error(i),this.status="disconnected",this.emit("handshakeFailed",m)}}))):this.logger.warn("imsocket::socket is connecting or connected",this.status)}close(){if(this.status="disconnected",this.websocket){this.logger.log("imsocket:: close websocket");try{this.websocket.send(this.encodePacket({type:"disconnect"}))}catch(t){this.logger.warn("imsocket::attempt to send encodePacket error",t)}try{this.websocket.close()}catch(t){this.logger.warn("imsocket::attempt to close websocket error",t)}this.clean(),this.emit("disconnect",{code:0,reason:"Active close websocket"})}}clean(){this.status="disconnected",clearTimeout(this.socketConnectTimer),this.websocket&&(this.socketUrl=void 0,this.websocket.onmessage=null,this.websocket.onopen=null,this.websocket.onerror=null,this.websocket.onclose=null,this.websocket=null)}onConnect(){this.status="connected",this.emit("connect"),clearTimeout(this.socketConnectTimer)}_createWebsocket(t){this.socketConnectTimer=setTimeout((()=>{this.logger.error("imsocket::Websocket connect timeout. url: ",this.socketUrl),this.emit("handshakeFailed",new V2NIMErrorImpl({code:"v2"===get(this.core,"options.apiVersion")?Ee.V2NIM_ERROR_CODE_CONNECT_TIMEOUT:415,detail:{reason:`imsocket::Websocket connect timeout. url: ${this.socketUrl}`}}))}),this.core.options.socketConnectTimeout||8e3),this.socketUrl=t,this.websocket=new Re.WebSocket(t),this.websocket.onmessage=this.onMessage.bind(this),this.websocket.onclose=t=>{t=t||{},this.logger.log(`imsocket::Websocket onclose done ${t.wasClean}/${t.code}/${t.reason}`),this.clean(),this.emit("disconnect",{code:t.code||0,reason:t.reason})},this.websocket.onerror=t=>{this.logger.error("imsocket::Websocket onerror",t),"logined"===this.core.status&&this.core.clientSocket.ping()}}onMessage(t){var i,o=this.decodePacket(t.data);if(o)switch(o.type){case"connect":this.onConnect();break;case"disconnect":this.close(),this.emit("disconnect",{code:0,reason:"MessageEvent type disconnect"});break;case"message":case"json":this.emit("message",o.data);break;case"event":o.name&&this.emit(o.name,o.args);break;case"error":"unauthorized"===o.reason?this.emit("connect_failed",o.reason):this.emit("error",o.reason),this.logger.error("imsocket::Websocket connect failed, onmessage type error. url: ",this.socketUrl),clearTimeout(this.socketConnectTimer),this.emit("handshakeFailed",new V2NIMErrorImpl({code:"v2"===get(this.core,"options.apiVersion")?Ee.V2NIM_ERROR_CODE_CONNECT_FAILED:408,detail:{reason:`imsocket::Websocket connect failed, onMessage socket error. url: ${this.socketUrl}`}}));break;case"heartbeat":null===(i=this.websocket)||void 0===i||i.send(this.encodePacket({type:"heartbeat"}));break;default:this.logger.warn("imsocket::Websocket no handler type",o.type)}}encodePacket(t){var i,o,{type:m,id:h="",endpoint:u="",ack:v}=t,I=null;if(!m)return"";switch(m){case"error":i=t.reason?nt.indexOf(t.reason):"",o=t.advice?ot.indexOf(t.advice):"",""===i&&""===o||(I=i+(""!==o?"+"+o:""));break;case"message":""!==t.data&&(I=t.data);break;case"event":i={name:t.name},i=t.args&&t.args.length?{name:t.name,args:t.args}:{name:t.name},I=JSON.stringify(i);break;case"json":I=JSON.stringify(t.data);break;case"connect":t.qs&&(I=t.qs);break;case"ack":I=t.ackId+(t.args&&t.args.length?"+"+JSON.stringify(t.args):"")}var _=[rt.indexOf(m),h+("data"===v?"+":""),u];return null!=I&&_.push(I),_.join(":")}decodePacket(t){if(t)if("�"!=t.charAt(0)){var i=t.match(/([^:]+):([0-9]+)?(\+)?:([^:]+)?:?([\s\S]*)?/);if(i){var o,[,m,h,u,v,I]=i,_={type:rt[+m],endpoint:v};switch(h&&(_.id=h,_.ack=!u||"data"),_.type){case"error":o=I.split("+"),_.reason=nt[+o[0]]||"";break;case"message":_.data=I||"";break;case"connect":_.qs=I||"";break;case"event":try{var M=JSON.parse(I);_.name=M.name,_.args=M.args}catch(t){this.logger.error("imsocket::parseData::type::event error",t)}_.args=_.args||[];break;case"json":try{_.data=JSON.parse(I)}catch(t){this.logger.error("imsocket::parseData::type::json error",t)}break;case"ack":if((o=I.match(/^([0-9]+)(\+)?(.*)/))&&(_.ackId=o[1],_.args=[],o[3]))try{_.args=o[3]?JSON.parse(o[3]):[]}catch(t){this.logger.error("imsocket::parseData::type::ack error",t)}}return _}}else this.logger.error("imsocket::unrecognize dataStr",t.slice(0,20))}send(t){var i,o={data:t,type:"message",endpoint:""};null===(i=this.websocket)||void 0===i||i.send(this.encodePacket(o))}}!function(t){t[t.ACTIVE=1]="ACTIVE",t[t.KICKED=2]="KICKED",t[t.OFFLINE=3]="OFFLINE"}(it||(it={}));class V2ClientSocket{constructor(t){this.isReconnect=!1,this.packetTimeout=8e3,this.linkSSL=!0,this.packetSer=1,this.backoff=new Backoff({max:8e3,min:1600,jitter:.01}),this.sendingCmdMap=new Map,this.pingTimer=0,this.hasNetworkListener=!1,this.core=t,this.auth=t.auth,this.logger=t.logger,this.reporter=t.reporter,this.timerManager=t.timerManager,this.eventBus=t.eventBus,this.setListener()}setListener(){this.core.eventBus.on("V2NIMLoginService/loginLifeCycleLoginSucc",(()=>{this.isReconnect=!0}))}setSessionId(t){this.socket&&(this.socket.sessionId=t)}setLinkSSL(t){this.linkSSL=t}connect(t,i=!1){var o,m;return __awaiter(this,void 0,void 0,(function*(){this.isReconnect=i;var h=this.core.auth.getConnectStatus();if(1===h){var u=`clientSocket::connect status is ${h}, and would not repeat connect`,v=new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_ILLEGAL_STATE,detail:{reason:u}});return this.logger.warn(u),Promise.reject(v)}this.auth.lifeCycle.processEvent("connect");try{yield this.auth.doLoginStepsManager.add(this.doConnect(t)),this.logger.log(`clientSocketV2:: connect success with link url: ${t}, isReconnect: ${i}`),this.core.reporter.reportTraceUpdateV2("login",{operation_type:"TCP",target:t,code:200,mixlink:!0,succeed:!0},{asyncParams:Re.net.getNetworkStatus()}),this.auth.lifeCycle.processEvent("connectSucc")}catch(i){var I=i;if(this.core.reporter.reportTraceUpdateV2("login",{operation_type:"TCP",target:t,code:I.code||0,description:`connectFailed:${I.message}`,mixlink:!0,succeed:!1},{asyncParams:Re.net.getNetworkStatus()}),I.code===Ee.V2NIM_ERROR_CODE_CANCELLED||I.code===Ee.V2NIM_ERROR_CODE_TIMEOUT)throw null===(o=this.socket)||void 0===o||o.close(),null===(m=this.socket)||void 0===m||m.removeAllListeners(),this.socket=void 0,i;throw this.logger.warn(`clientSocketV2::connect failed with link url: ${t}`,I),this.auth.lifeCycle.processEvent("connectFail",I),i}}))}doConnect(t){var i=!1;return new Promise(((o,m)=>{this.socket=new BaseWebsocket(this.core,t,this.linkSSL),this.socket.on("connect",(()=>{this.logger.log("clientSocketV2::socket on connect",t),this.core.reporterHookLinkKeep.start(),this.core.reporterHookLinkKeep.update({code:0,description:"connection begin",operation_type:0,target:t}),i=!0,o()})),this.socket.on("message",this.onMessage.bind(this)),this.socket.on("disconnect",(o=>__awaiter(this,void 0,void 0,(function*(){i=!0,this.logger.log("clientSocketV2::socket on disconnect",o),yield this.core.reporterHookLinkKeep.update({code:(null==o?void 0:o.code)||0,description:(null==o?void 0:o.reason)||"socket on disconnect",operation_type:1,target:t}),this.core.reporterHookLinkKeep.end(!1),this.doDisconnect(it.OFFLINE,"SocketOnDisconnect")})))),this.socket.on("handshakeFailed",(t=>{i?this.ping():(this.logger.error(`clientSocketV2::handshake failed: "${t&&t.message}"`),this.cleanSocket()),i=!0,m(t)}))}))}cleanSocket(){this.socket&&("function"==typeof this.socket.removeAllListeners&&this.socket.removeAllListeners(),"function"==typeof this.socket.close&&this.socket.close(),this.socket=void 0)}resetSocketConfig(){this.backoff.reset(),this.initOnlineListener()}doDisconnect(t,i){if(this.logger.log(`clientSocketV2::doDisconnect:type:${t},reason:`,i),0!==this.core.auth.getConnectStatus()){var o={1:"close",2:"kicked",3:"broken"}[t]||"";this.markAllCmdInvaild(new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_DISCONNECT,detail:{reason:"Packet timeout due to instance disconnect",disconnect_reason:o}})),this.timerManager.destroy(),clearTimeout(this.pingTimer),this.cleanSocket(),t===it.ACTIVE||t===it.KICKED?this.destroyOnlineListener():t===it.OFFLINE&&(this.auth.lifeCycle.processEvent("connectionBroken",new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_DISCONNECT,detail:{reason:"connection broken due to internal reasons"}})),this.logger.log(`clientSocketV2::doDisconnect: pending reconnect ${this.isReconnect}`),this.isReconnect&&this.auth.lifeCycle.processEvent("waiting"))}else this.logger.warn("clientSocketV2::doDisconnect:already disconnected")}sendCmd(t,i,o){var m=this.core.auth.getLoginStatus(),h={cmd:t};if(1!==m&&!["v2Login","login","chatroomLogin","v2ChatroomLogin"].includes(t))return this.logger.warn(`clientSocketV2::NIM login status is ${m}, so can not sendCmd ${t}`),Promise.reject(new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_ILLEGAL_STATE,detail:Object.assign({reason:"Can not sendCmd due to no logined"},h)}));var u="heartbeat"!==t,v=u?this.packetSer++:0,I=createCmd(t,v,this.logger,i);if(!I){var _=new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INTERNAL,detail:Object.assign(Object.assign({},h),{reason:`SendCmd::createCmd error: ${v} ${t}`})});return this.logger.error(_),Promise.reject(_)}var{packet:M,hasPacketResponse:E,hasPacketTimer:S}=I,T=JSON.stringify(M);u&&(this.logger.getDebugMode()?this.logger.debug(`clientSocketV2::sendCmd: ${M.SID}_${M.CID},${t},ser:${v}`,T):this.logger.log(`clientSocketV2::sendCmd: ${M.SID}_${M.CID},${t},ser:${v}`));var C=(new Date).getTime();return new Promise(((m,u)=>{E&&this.sendingCmdMap.set(v,{cmd:t,params:i,callback:[m,u],timer:S?setTimeout((()=>{var i=new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_PROTOCOL_TIMEOUT,detail:Object.assign({ser:v,reason:`Packet Timeout: ser ${v} cmd ${t}`,timetag:(new Date).getTime()},h)});this.markCmdInvalid(v,i,t)}),o&&o.timeout?o.timeout:this.packetTimeout):null});try{this.socket.send(T),E||m(M)}catch(i){var I=new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_PROTOCOL_SEND_FAILED,detail:Object.assign({ser:v,reason:"Unable to send packet"+(i&&i.message?": "+i.message:""),timetag:(new Date).getTime(),rawError:i},h)});this.markCmdInvalid(v,I,t),u(I)}})).catch((t=>__awaiter(this,void 0,void 0,(function*(){var i,o=t;if(![Ee.V2NIM_ERROR_CODE_DISCONNECT,Ee.V2NIM_ERROR_CODE_PROTOCOL_TIMEOUT,Ee.V2NIM_ERROR_CODE_PROTOCOL_SEND_FAILED].includes(o.code))return Promise.reject(o);this.reporter.reportTraceStart("exceptions",{user_id:this.core.auth.getLoginUser(),trace_id:null===(i=this.socket)||void 0===i?void 0:i.sessionId,start_time:C,action:2,exception_service:6});var m=get(o,"detail.disconnect_reason")||"",h=o.code===Ee.V2NIM_ERROR_CODE_DISCONNECT?JSON.stringify({disconnect_reason:m}):o.detail.reason;return this.reporter.reportTraceUpdateV2("exceptions",{code:o.code,description:h,operation_type:1,target:`${M.SID}-${M.CID}`,context:`${M.SER}`},{asyncParams:Re.net.getNetworkStatus()}),this.reporter.reportTraceEnd("exceptions",1),Promise.reject(o)}))))}onMessage(t){var i=parseCmd(t,this.logger);if(i&&i.length>0){var o=i[0],m=o.raw.ser;for(var h of(o.error&&this.logger.error("clientSocketV2::onMessage packet error",`${o.raw.sid}_${o.raw.cid}, ser:${m},`,o.error),"heartbeat"!==o.cmd&&(this.logger.getDebugMode()?this.logger.debug(`clientSocketV2::recvCmd ${o.raw.sid}_${o.raw.cid},${o.cmd},ser:${m}`,o.content):this.logger.log(`clientSocketV2::recvCmd ${o.raw.sid}_${o.raw.cid},${o.cmd},ser:${m};code:${o.raw.code}`)),i))this.packetHandler(h)}}packetHandler(t){var i,o,m,h;if(t){var u=t.raw.ser,v=this.sendingCmdMap.get(u);if(v&&v.cmd===t.cmd){var{callback:I,timer:_,params:M}=v;if(clearTimeout(_),t.params=M,this.sendingCmdMap.delete(u),"heartbeat"===t.cmd)return void I[0]();var E=null===(o=null===(i=this.core[t.service])||void 0===i?void 0:i.process)||void 0===o?void 0:o.call(i,t);E&&"function"==typeof E.then?E.then((t=>{I[0](t)})).catch((t=>{I[1](t)})):(this.logger.log("clientSocketV2::handlerFn without promise",t.service,t.cmd),I[0](t))}else{var S=null===(h=null===(m=this.core[t.service])||void 0===m?void 0:m.process)||void 0===h?void 0:h.call(m,t);S&&"function"==typeof S.then&&S.catch((t=>{this.logger.error("clientSocketV2::no obj cache, no process handler",t)}))}}}markCmdInvalid(t,i,o){var m=this.sendingCmdMap.get(t);if(m){var{callback:h,timer:u}=m;u&&clearTimeout(u),this.sendingCmdMap.delete(t),this.logger.warn(`clientSocketV2::packet ${t}, ${o} is invalid:`,i),h[1](i)}}markAllCmdInvaild(t){this.logger.log("markAllCmdInvaild",t),this.sendingCmdMap.forEach((i=>{var{callback:o,timer:m,cmd:h}=i;this.logger.log(`clientSocketV2::markAllCmdInvaild:cmd ${h}`),m&&clearTimeout(m),o[1](t)})),this.sendingCmdMap.clear()}ping(){var t;return __awaiter(this,void 0,void 0,(function*(){clearTimeout(this.pingTimer);try{yield this.sendCmd("heartbeat")}catch(i){if(i.code===Ee.V2NIM_ERROR_CODE_DISCONNECT)return;if(yield this.testHeartBeat5Timeout())return yield this.core.reporterHookLinkKeep.update({code:0,description:"Heartbeat-discovered link failure",operation_type:1,target:null===(t=this.socket)||void 0===t?void 0:t.url}),this.core.reporterHookLinkKeep.end(!0),void this.doDisconnect(it.OFFLINE,"PingError")}this.pingTimer=setTimeout((()=>{this.ping()}),3e4)}))}testHeartBeat5Timeout(){return __awaiter(this,void 0,void 0,(function*(){clearTimeout(this.pingTimer);for(var t=0;t<5;t++)try{return yield this.sendCmd("heartbeat",{},{timeout:3e3}),!1}catch(i){this.logger.log(`clientSocketV2::test heartbeat ${t} Timeout`)}return!0}))}initOnlineListener(){this.hasNetworkListener||(this.logger.log("clientSocketV2::onlineListener:init"),this.hasNetworkListener=!0,Re.net.onNetworkStatusChange((t=>{this.logger.log("clientSocketV2::onlineListener:network change",t);var i=this.auth.getConnectStatus(),o=this.auth.getLoginStatus();t.isConnected&&1===o?this.ping():t.isConnected&&3===i?(this.logger.log("clientSocketV2::onlineListener:online and connectStatus is waiting, do reLogin"),this.auth.reconnect.clearReconnectTimer(),this.auth.reconnect.doReLogin()):t.isConnected||this.doDisconnect(it.OFFLINE,"OfflineListener")})))}destroyOnlineListener(){this.logger.log("clientSocketV2::onlineListener:destroy"),Re.net.offNetworkStatusChange(),this.hasNetworkListener=!1}}class V2NIMLoginReconnect{constructor(t){var i,o;this.currenRetryCount=0,this.backoff=new Backoff({max:8e3,min:1600,jitter:.01}),this.reconnectTimer=0,this.core=t,this.auth=t.V2NIMLoginService,null===(o=(i=Re.powerMonitor).on)||void 0===o||o.call(i,"onPowerMonitorTurnActive",(()=>{this.core.logger.debug("reconnect::powerMonitor turn active"),3===this.auth.getLoginStatus()&&(this.core.logger.log("reconnect::powerMonitor turn active, try to reconnect"),this.auth.reconnect.clearReconnectTimer(),this.auth.reconnect.doReLogin())}))}reset(){this.currenRetryCount=0,this.backoff.reset(),this.reconnectTimer&&clearTimeout(this.reconnectTimer)}destroy(){var t,i;this.currenRetryCount=0,this.backoff.reset(),this.reconnectTimer&&clearTimeout(this.reconnectTimer),Re.powerMonitor.destroy(),null===(i=(t=Re.powerMonitor).off)||void 0===i||i.call(t,"onPowerMonitorTurnActive")}clearReconnectTimer(){this.reconnectTimer&&clearTimeout(this.reconnectTimer)}attempToReLogin(){var t=this.backoff.duration();if("function"==typeof this.reconnectDelayProvider)try{var i=this.reconnectDelayProvider(t);"number"==typeof i&&i>=0&&(t=i>=1e3?i:i+200+Math.ceil(300*Math.random()))}catch(t){this.core.logger.error("reconnect::connectDelayProvider excute failed,",t)}return this.currenRetryCount++,this.core.logger.log(`reconnect::reconnect timer is about to be set, delay ${t} ms, current retry count is ${this.currenRetryCount}`),this.core.reporter.reportTraceStart("login",{user_id:this.auth.getLoginUser(),action:"auto_login",binary_websocket:this.auth.binaryWebsocket}),this.clearReconnectTimer(),this.reconnectTimer=setTimeout((()=>{this.core.logger.log("reconnect::reconnect timer is now triggered");var t=this.auth.getConnectStatus();3===t?this.doReLogin():this.core.logger.warn(`reconnect::reconnect timer is over because connect status now is ${t}`)}),t),!0}doReLogin(){if(!Re.powerMonitor.isActive())return this.core.logger.log("reconnect::reLogin skip, cause app powerMonitor is not active"),void this.auth.lifeCycle.processEvent("waiting");this.auth.loginOption.forceMode=!1,this.auth.originLoginPromise=this.auth.doLogin(!0);var t=this.auth.previousLoginManager.add(this.auth.originLoginPromise);return t.then((()=>{this.core.reporter.reportTraceEnd("login",!0)})).catch((t=>{var i=t;if(this.core.logger.warn("reconnect::try login but failed due to",i),this.core.reporter.reportTraceEnd("login",!1),this.auth.checkLoginTerminalCode(i&&i.code))return this.auth.clientSocket.doDisconnect(Ze.ACTIVE,"ReloginTerminated"),void this.auth.lifeCycle.processEvent("exited",i);i&&399===i.code&&this.auth.lbs.reset(),this.auth.lifeCycle.processEvent("waiting")})),t}_setReconnectDelayProvider(t){this.reconnectDelayProvider=t}}function uniq(t){t=t||[];for(var i=[],o=0;o<t.length;o++)-1===i.indexOf(t[o])&&i.push(t[o]);return i}class V2NIMLoginLbs{constructor(t){this.socketLinkUrls=[],this.timer=0,this.failedCount=0,this.core=t,this.auth=t.V2NIMLoginService}getLbsInfos(){return __awaiter(this,void 0,void 0,(function*(){if(this.socketLinkUrls.length>0){var t=this.socketLinkUrls.shift();return this.core.logger.log("V2NIMLoginService::getLbsInfos:use cache link",t),Promise.resolve(t)}this.auth.lifeCycle.processEvent("addressing"),this.core.reporterHookLBS.start(this.core.account);var i=uniq(this.auth.config.lbsUrls);try{var o=yield this.ladderLoad(i);if(200!==o.status||!o.data)throw this.core.logger.error("V1NIMLoginService::getLbsInfos:error status",o.status,o),new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INTERNAL,detail:{reason:`V2NIMLoginService::getLbsInfos failed, status ${o.status}`}});this.success(o)}catch(t){var m=t;if(this.core.logger.error(`V2NIMLoginService::lbs getLbsInfos error, use default link: ${this.auth.config.linkUrl}. error:`,t),this.reportForFail(i[0],m.code,m.message),this.checkTerminator(m.code))throw t;this.socketLinkUrls=[this.auth.config.linkUrl]}return this.socketLinkUrls.shift()}))}checkTerminator(t){return t===Ee.V2NIM_ERROR_CODE_CANCELLED||t===Ee.V2NIM_ERROR_CODE_TIMEOUT}generateUrl(t){var i=(t=this.processLbsUrl(t)).indexOf("?")>-1?"&":"?";return t+i+"k="+this.core.options.appkey+"&id="+this.core.auth.getLoginUser()+"&sv=180&pv=1&networkType=0&lv=1"}processLbsUrl(t){return pendingIsMiniappEnv()?t.replace("/webconf","/wxwebconf"):t}requstLbs(t){return this.auth.doLoginStepsManager.add(this.core.adapters.request(this.generateUrl(t),{method:"GET",dataType:"json",timeout:8e3}))}setLadderTimer(t,i,o,m){this.timer&&clearTimeout(this.timer);var h=t[i];this.timer=setTimeout((()=>{h&&(this.setLadderTimer(t,i+1,o,m),this.core.logger.log(`V2NIMLoginService::getLbsInfos ${i}:`,this.processLbsUrl(h)),this.reportForLbsStart(h,i),this.requstLbs(h).then((t=>{this.reset(),o(Object.assign(Object.assign({},t),{url:h}))})).catch((o=>{var u;if(this.core.logger.warn(`V2NIMLoginService::getLbsInfos ${i} failed:`,o),this.failedCount+=1,this.reportForFailOnce(h,o.code,(null===(u=o.detail)||void 0===u?void 0:u.reason)||o.message),this.failedCount>=t.length||this.checkTerminator(o.code))return this.reset(),void m(o)})))}),2e3)}ladderLoad(t){return new Promise(((i,o)=>{t.length>1&&this.setLadderTimer(t,1,i,o);var m=t[0];this.core.logger.log("V2NIMLoginService::getLbsInfos 0:",m),this.reportForLbsStart(m,0),this.requstLbs(m).then((t=>{this.reset(),i(Object.assign(Object.assign({},t),{url:m}))})).catch((i=>{var h;this.failedCount+=1,this.core.logger.warn("V2NIMLoginService::getLbsInfos 0 failed:",i),this.reportForFailOnce(m,i.code,(null===(h=i.detail)||void 0===h?void 0:h.reason)||i.message),(this.failedCount>=t.length||this.checkTerminator(i.code))&&(this.reset(),o(i))}))}))}success(t){var i,o,m=t.data.common,h=m["mix.link"]||[],u=m["link.default"]||[];this.socketLinkUrls=h.concat(u).concat(this.auth.config.linkUrl),t.data["nos-chunk"]&&(null===(i=this.core.cloudStorage)||void 0===i?void 0:i.setOptions)&&(this.core.logger.log("getLbsInfos success. lbs.nos-chunk",t.data["nos-chunk"]),this.core.cloudStorage.setOptions({chunkUploadHost:t.data["nos-chunk"]})),Array.isArray(t.data.nosup)&&t.data.nosup.length>0&&(null===(o=this.core.cloudStorage)||void 0===o?void 0:o.setOptions)&&(this.core.logger.log("getLbsInfos success. lbs.nosup",t.data.nosup),this.core.cloudStorage.setOptions({commonUploadHostBackupList:t.data.nosup,commonUploadHost:t.data.nosup[0]})),this.core.logger.log("V2NIMLoginService::getLbsInfos success, socket link:",this.socketLinkUrls.slice(0),"chunkUploadHost: ",t.data["nos-chunk"]),this.reportForLbsSuccess(t.url,t.data)}reportForLbsStart(t,i){this.core.reporterHookLBS.updateBegin({target:t,index:i})}reportForLbsSuccess(t,i){this.core.reporterHookLBS.updateComplete({target:t,code:200,body:JSON.stringify(i)}),this.core.reporterHookLBS.end(!0),this.core.reporter.reportTraceUpdateV2("login",{operation_type:"HTTP",target:t,code:200,succeed:!0},{asyncParams:Re.net.getNetworkStatus()})}reportForFailOnce(t,i,o){this.core.reporterHookLBS.updateComplete({target:t,code:i,body:o})}reportForFail(t,i,o){this.core.reporterHookLBS.end(!1),this.core.reporter.reportTraceUpdateV2("login",{operation_type:"HTTP",target:t,description:o,code:i,succeed:!1},{asyncParams:Re.net.getNetworkStatus()})}reset(){this.socketLinkUrls=[],this.failedCount=0,clearTimeout(this.timer)}}class V2NIMLoginAuthenticator{constructor(t){this.lastLoginClientKey="__NIM_LAST_LOGIN_CLIENT__",this.loginClients=[],this.loginClientOfThisConnection={},this.core=t,this.auth=t.V2NIMLoginService}verifyAuthentication(t){var i,o;return __awaiter(this,void 0,void 0,(function*(){var m=yield this.auth.doLoginStepsManager.add(this.refreshLoginToken(this.auth.account)),h=yield this.auth.doLoginStepsManager.add(this.refreshThirdPartyExt(this.auth.account));this.auth.token=m;var u,v=Re.getSystemInfo(),I={appkey:this.core.options.appkey,account:this.auth.account,token:m,authType:this.auth.loginOption.authType,appLogin:t?0:1,clientType:16,clientSession:this.auth.clientSession,clientId:this.auth.deviceId,sdkVersion:100970,userAgent:this.core.options.loginSDKTypeParamCompat?"Native/10.9.70":v.userAgent.replace("{{appkey}}",this.core.options.appkey).slice(0,299),libEnv:this.core.options.flutterSdkVersion?"FLUTTER":this.core.options.loginSDKTypeParamCompat?void 0:v.libEnv,hostEnv:this.core.options.flutterSdkVersion?4:this.core.options.loginSDKTypeParamCompat?0:v.hostEnvEnum,sdkHumanVersion:this.core.options.flutterSdkVersion||"10.9.70",os:v.os,browser:v.browser,protocolVersion:1,customClientType:this.auth.config.customClientType,customTag:this.auth.config.customTag,thirdPartyExtension:h,isRoutable:!1===(null===(i=this.auth.loginOption.routeConfig)||void 0===i?void 0:i.routeEnabled)?0:1,env:null===(o=this.auth.loginOption.routeConfig)||void 0===o?void 0:o.routeEnvironment},_=v.os.toLowerCase(),M=110===v.hostEnvEnum;"UNIAPP"===Re.platform&&M?(I.isReactNative=1,I.clientType="ios"===_?2:"android"===_?1:65,v.pushDeviceInfo&&v.pushDeviceInfo.MANUFACTURER&&(I.deviceInfo=JSON.stringify(Object.assign({IS_SUPPORT_HONOR:!0},v.pushDeviceInfo)))):"React Native"===Re.platform&&(this.core.logger.log("V2NIMLoginService deviceInfo",this.core.V2NIMLoginService.deviceInfo,"os",_),I.isReactNative=1,I.clientType="ios"===_?2:1,I.deviceInfo=JSON.stringify(Object.assign({IS_SUPPORT_HONOR:!0},this.core.V2NIMLoginService.deviceInfo))),this.core.logger.log(`V2NIMLoginService::do login,accid:${I.account};clientSession:${I.clientSession};appLogin:${I.appLogin}`);try{u=yield this.auth.doLoginStepsManager.add(this.auth.clientSocket.sendCmd("v2Login",{tag:I}))}catch(t){var E=t;if(this.core.reporter.reportTraceUpdateV2("login",{operation_type:"protocol",target:"26-3",code:E.code||0,succeed:!1,description:E.message},{asyncParams:Re.net.getNetworkStatus()}),E.code===Ee.V2NIM_ERROR_CODE_CANCELLED||E.code===Ee.V2NIM_ERROR_CODE_TIMEOUT)throw E;throw this.processLoginFailed(E),E}var{data:S,loginClients:T}=u.content;return this.changeLoginClient(1,T),this.core.reporter.reportTraceUpdateV2("login",{operation_type:"protocol",target:"26-3",code:200,succeed:!0},{asyncParams:Re.net.getNetworkStatus()}),this.loginClientOfThisConnection=formatLoginInfo(S),this.core.clientSocket.setSessionId(S.consid),Re.localStorage.setItem(this.lastLoginClientKey,JSON.stringify(Object.assign({account:this.auth.account},this.loginClientOfThisConnection))),this.loginClientOfThisConnection}))}refreshLoginToken(t){return __awaiter(this,void 0,void 0,(function*(){if(0===this.auth.loginOption.authType)return this.auth.token;if("function"!=typeof this.auth.loginOption.tokenProvider)return this.auth.token;try{var i=yield this.auth.loginOption.tokenProvider(t);if("string"==typeof i)return i;throw this.core.logger.error("V2NIMLoginService::excute tokenProvider complete but got Unexpected value:",i),new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_CALLBACK_FAILED,detail:{reason:"Excute tokenProvider complete but got Unexpected value",rawData:i}})}catch(t){var o=t,m=o;throw o.code!==Ee.V2NIM_ERROR_CODE_CALLBACK_FAILED&&(this.core.logger.error("V2NIMLoginService::excute tokenProvider error:",o),m=new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_CALLBACK_FAILED,desc:"Excute tokenProvider error",detail:{rawError:t}})),this.processLoginFailed(o),m}}))}refreshThirdPartyExt(t){return __awaiter(this,void 0,void 0,(function*(){if("function"!=typeof this.auth.loginOption.loginExtensionProvider)return"";try{var i=yield this.auth.loginOption.loginExtensionProvider(t);if("string"==typeof i)return i;throw this.core.logger.error("V2NIMLoginService::excute loginExtensionProvider complete but got Unexpected value:",i),new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_CALLBACK_FAILED,detail:{reason:"Excute loginExtensionProvider complete but got Unexpected value",rawData:i}})}catch(t){var o=t,m=o;if(o.code!==Ee.V2NIM_ERROR_CODE_CALLBACK_FAILED&&(this.core.logger.error("V2NIMLoginService::excute loginExtensionProvider error:",o),m=new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_CALLBACK_FAILED,detail:{reason:"Excute loginExtensionProvider error",rawError:t}})),2===this.auth.loginOption.authType)throw this.processLoginFailed(o),m;return""}}))}processLoginFailed(t){this.auth.clientSocket.doDisconnect(Ze.ACTIVE,t),this.checkLoginTerminalCode(t.code)&&(this.auth.authenticator.reset(),this.auth.authenticator.clearLastLoginClient()),this.auth.lifeCycle.processEvent("loginFail",t)}changeLoginClient(t,i){var o=i.map((t=>formatLoginInfo(t)));if(1===t)this.loginClients=o,this.auth.emit("onLoginClientChanged",t,this.loginClients);else if(2===t){var m=o.filter((t=>{var i=this.loginClients.filter((i=>i.clientId===t.clientId));return this.loginClients.push(t),0===i.length}));m.length>0&&this.auth.emit("onLoginClientChanged",t,m)}else if(3===t){var h=o.filter((t=>(function remove(t,i){i=i||(()=>!0);for(var o=[],m=(t=t||[]).length,h=0,u=0;u<m;u++)i(t[u-h])&&(o.push(t.splice(u-h,1)[0]),h+=1);return o}(this.loginClients,(i=>i.clientId===t.clientId&&i.consid===t.consid)),0===this.loginClients.filter((i=>i.clientId===t.clientId)).length)));h.length>0&&this.auth.emit("onLoginClientChanged",t,h)}}checkAutoLogin(t){if(t)return!1;var i=Re.localStorage.getItem(this.lastLoginClientKey);if(!i)return!1;var o="",m="";try{var h=JSON.parse(i);o=get(h,"clientId"),m=get(h,"account")}catch(t){return!1}return o===this.auth.deviceId&&m===this.auth.account}checkLoginTerminalCode(t){return[Ee.V2NIM_ERROR_CODE_CANCELLED,Ee.V2NIM_ERROR_CODE_TIMEOUT,Ee.V2NIM_ERROR_CODE_HANDSHAKE,302,317,Ee.V2NIM_ERROR_CODE_FORBIDDEN,Ee.V2NIM_ERROR_CODE_NOT_FOUND,Ee.V2NIM_ERROR_CODE_PARAMETER_ERROR,Ee.V2NIM_ERROR_CODE_MULTI_LOGIN_FORBIDDEN,422,Ee.V2NIM_ERROR_CODE_IM_DISABLED,Ee.V2NIM_ERROR_CODE_APPKEY_NOT_EXIST,Ee.V2NIM_ERROR_CODE_BUNDLEID_CHECK_FAILED,Ee.V2NIM_ERROR_CODE_APPKEY_BLOCKED,Ee.V2NIM_ERROR_CODE_INVALID_TOKEN,Ee.V2NIM_ERROR_CODE_ROBOT_NOT_ALLOWED,Ee.V2NIM_ERROR_CODE_ACCOUNT_NOT_EXIST,Ee.V2NIM_ERROR_CODE_ACCOUNT_BANNED,Ee.V2NIM_ERROR_CODE_USER_PROFILE_NOT_EXIST].includes(t)}reset(){this.loginClients=[],this.loginClientOfThisConnection={}}clearLastLoginClient(){Re.localStorage.removeItem(this.lastLoginClientKey)}}class V2Service extends Ie{constructor(t,i){super(),this.name=t,this.logger=i.logger,this.core=i}checkV2(){var t=this.core.options.apiVersion;if("v2"===t)return!0;throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_MISUSE,detail:{reason:`The version "${t}" of client is not supported.`}})}checkLogin(){if(0===this.core.V2NIMLoginService.getLoginStatus())throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_ILLEGAL_STATE,detail:{reason:"Client logout."}})}emit(t,...i){this.logger.debug(`${this.name}::emit event: '${t.toString()}',`,void 0!==i[0]?i[0]:"",void 0!==i[1]?i[1]:"",void 0!==i[2]?i[2]:"");try{return super.emit(t,...i)}catch(i){return setTimeout((()=>{throw this.logger.error(`${this.name}::emit throw error in setTimeout. event: ${t.toString()}. Error`,i),i}),0),!1}}process(t){var i=this[t.cmd+"Handler"],o=this.handler&&this.handler[t.cmd+"Handler"];if("function"==typeof i||"function"==typeof o){if(t.error)return this.logger.error(`${t.cmd}::recvError`,t.error),Promise.reject(t.error);try{var m=i?i.call(this,t):o.call(this.handler,t);return Promise.resolve(m)}catch(t){return Promise.reject(t)}}var h=get(t,"error.detail.ignore");return t.error&&!h?Promise.reject(t.error):Promise.resolve(t)}}class V2NIMLoginLifeCycle{constructor(t){this.name="V2NIMLoginLifeCycle",this.loginStatus=0,this.connectStatus=0,this.core=t,this.auth=t.V2NIMLoginService,this.logger=t.logger}processEvent(t,i,o){var m=this.getConnectStatus();switch(t){case"addressing":this.logger.log(`${this.name}::addressing`),this.setLoginStatus(2),this.setConnectStatus(2);break;case"connect":this.logger.log(`${this.name}::connecting`),this.setLoginStatus(2),this.setConnectStatus(2);break;case"connectSucc":this.logger.log(`${this.name}::connect success`),this.setLoginStatus(2),this.setConnectStatus(1);break;case"connectFail":this.logger.log(`${this.name}::connect fail`,i),this.setLoginStatus(3),this.setConnectStatus(0,i);break;case"connectionBroken":this.logger.log(`${this.name}::connectionBroken:`,i),this.setLoginStatus(3),this.setConnectStatus(0,i),this.core.eventBus.emit("V2NIMLoginService/loginLifeCycleDisconnected",i);break;case"loginSucc":this.logger.log(`${this.name}::login success, verify authentication success`),this.setLoginStatus(1),this.core.eventBus.emit("V2NIMLoginService/loginLifeCycleLoginSucc",o);break;case"loginFail":if(this.logger.log(`${this.name}::login fail due to verify authentication failed:`,i),!i)return;this.setLoginStatus(this.auth.authenticator.checkLoginTerminalCode(i.code)?0:3),this.setConnectStatus(0,i),this.auth.emit("onLoginFailed",i);break;case"logout":this.logger.log(`${this.name}::logout`),this.setLoginStatus(0),this.setConnectStatus(0),this.core.eventBus.emit("V2NIMLoginService/loginLifeCycleLogout");break;case"kicked":this.logger.log(`${this.name}::kicked`,o),this.setLoginStatus(0),this.setConnectStatus(0,i),this.core.eventBus.emit("V2NIMLoginService/loginLifeCycleKicked");break;case"exited":this.logger.log(`${this.name}::exited`,i),this.setLoginStatus(0),this.setConnectStatus(0,i);break;case"waiting":this.logger.log(`${this.name}::waiting to reconnect`),this.setLoginStatus(3),this.setConnectStatus(3),2!==m&&this.auth.reconnect.attempToReLogin()}}getConnectStatus(){return this.connectStatus}getLoginStatus(){return this.loginStatus}setLoginStatus(t){t!==this.loginStatus&&(this.loginStatus=t,this.auth.emit("onLoginStatus",t))}setConnectStatus(t,i){if(t!==this.connectStatus){var o=this.connectStatus;this.connectStatus=t,this.auth.emit("onConnectStatus",t),this.delegateConnectEvent(o,t,i)}}delegateConnectEvent(t,i,o){1===t&&0===i&&o&&this.auth.emit("onDisconnected",o),2===t&&0===i&&o&&this.auth.emit("onConnectFailed",o)}}class V2NIMLoginDataSync{constructor(t){this.core=t,this.auth=t.V2NIMLoginService,this.datas=[]}switchDataSync(t){return __awaiter(this,void 0,void 0,(function*(){var{type:i,state:o,error:m,subType:h}=t,u=this.datas.filter((t=>t.type===i&&t.subType===h));u.length>0?(u[0].state=o,u[0].error=m):this.datas.push({type:i,state:o,subType:h});var v=this.datas.every((t=>3===t.state));1===i&&(2===o&&"mainSync"===h?(this.core.eventBus.emit("V2NIMLoginService/syncing"),this.auth.emit("onDataSync",i,o)):3===o&&v&&(this.core.eventBus.emit("V2NIMLoginService/syncDone",m),this.auth.emit("onDataSync",i,o,m)))}))}checkSyncing(){return this.datas.some((t=>"mainSync"===t.subType&&2===t.state))}reset(){this.datas=[]}}var st={"6_3":"notifylog","6_4":"uploadLog","6_23":"getServerTime","6_31":"notifyDetect","6_32":"uploadDetect","6_37":"wsDetect"},at={type:1,params:2,result:3,t1:100,t2:101,t3:102,t4:103,t5:104,t6:105},ct={k1:1,k2:2,k3:3,k4:4,k5:5,k6:6,k7:7,k8:8,k9:9,k10:10},dt={notifylog:{sid:6,cid:3,service:"misc"},uploadLog:{sid:6,cid:4,service:"misc",hasPacketResponse:!1,params:[{type:"String",name:"url"},{type:"Property",name:"data",reflectMapper:{type:1,content:2}}]},getServerTime:{sid:6,cid:23,service:"misc",response:[{type:"Long",name:"time"}]},notifyDetect:{sid:6,cid:31,service:"misc",response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(at)}]},uploadDetect:{sid:6,cid:32,service:"misc",hasPacketResponse:!1,params:[{type:"Property",name:"data",reflectMapper:at}]},wsDetect:{sid:6,cid:37,service:"misc",params:[{type:"Property",name:"tag",reflectMapper:ct}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(ct)}]}},lt={type:{type:"number"},t1:{type:"number"},t2:{type:"number"},t3:{type:"number"},t4:{type:"number"},t5:{type:"number"},t6:{type:"number"}};class MiscService extends class Service{constructor(t,i){this.name=t,this.core=i,this.name=t,this.logger=i.logger,this.core=i}process(t){var i=this[t.cmd+"Handler"];if("function"==typeof i)return i.call(this,t);var o=get(t,"error.detail.ignore");return t.error&&!o?Promise.reject(t.error):Promise.resolve(t)}}{constructor(t){super("misc",t),this.logLock=!1,this.core=t,registerParser({cmdMap:st,cmdConfig:dt}),this.setListener()}setListener(){this.core.eventBus.on("BinaryClientSocket/unpackError",this.wsDetect.bind(this)),this.core.eventBus.on("V2NIMLoginService/loginLifeCycleLoginSucc",(()=>{this.core.timeOrigin.setOriginTimetick()})),this.core.eventBus.on("logined",(()=>{this.core.timeOrigin.setOriginTimetick()}))}getServerTime(){return __awaiter(this,void 0,void 0,(function*(){var t=yield this.core.clientSocket.sendCmd("getServerTime");return parseInt(t.content.time)}))}wsDetect(t){return __awaiter(this,void 0,void 0,(function*(){var i=Object.assign({k1:"val1",k2:"val2"},t),o=null;try{o=(yield this.core.clientSocket.sendCmd("wsDetect",{tag:i})).content.data}catch(t){var m=t;return void(m.code===Ee.V2NIM_ERROR_CODE_UNPACK_ERROR?(this.logger.warn("misc::wsDetect:998"),this.wsDetectUnreliable(),this.reportBinarySocketDetectResult("packet 998")):this.logger.warn(`misc::wsDetect:failed ${m.code}`))}o&&JSON.stringify(o)!==JSON.stringify(i)?(this.logger.warn("misc::wsDetect:content unreliable"),this.wsDetectUnreliable(),this.reportBinarySocketDetectResult("content unreliable")):this.logger.log("misc::wsDetect:success")}))}wsDetectUnreliable(){this.core.clientSocket.doDisconnect(3,"WSDetectUnreliable")}reportBinarySocketDetectResult(t){var i;this.core.reporter.reportTraceStart("exceptions",{user_id:this.core.account,trace_id:null===(i=this.core.clientSocket.socket)||void 0===i?void 0:i.sessionId,start_time:Date.now(),action:2,exception_service:9}),this.core.reporter.reportTraceUpdateV2("exceptions",{code:998,description:`wsDetect::reconnect cause: ${t}`,operation_type:"5",target:"6-37"}),this.core.reporter.reportTraceEnd("exceptions",1)}notifyDetectHandler(t){return __awaiter(this,void 0,void 0,(function*(){var i=function formatNotifyDetectTag(t){return format(lt,t)}(t.content.data);i.t3=t.__receiveTimeNode.time,i.t4=Date.now();try{yield this.core.clientSocket.sendCmd("uploadDetect",{data:i})}catch(t){this.core.logger.warn("misc::notifyDetectHandler:upload failed",t)}}))}notifylogHandler(){return __awaiter(this,void 0,void 0,(function*(){var t=void 0;if(this.logLock)this.core.logger.warn("misc::notifylogHandler:locked");else{this.logLock=!0;try{t=yield this.core.logger.extractLogs()}catch(t){return void(this.logLock=!1)}if(t){var i="";try{i=(yield this.core.cloudStorage.uploadFile("string"==typeof t?{type:"file",filePath:t}:{type:"file",file:t})).url}catch(t){return void(this.logLock=!1)}if(i){var o=i.indexOf("?")>0?"&":"?",m="string"==typeof t&&t.indexOf(".zip")>0?"zip":"log";i+=`${o}download=${Date.now()}_web.${m}`;try{yield this.core.clientSocket.sendCmd("uploadLog",{url:i})}catch(t){return void(this.logLock=!1)}try{yield this.logger.afterUpload()}catch(t){}this.logLock=!1}else this.logLock=!1}else this.logLock=!1}}))}}function pick(t,i){t=t||{};var o={};return(i=i||[]).forEach((i=>{void 0!==t[i]&&(o[i]=t[i])})),o}var pt={retryCount:{type:"number",min:0,required:!1},forceMode:{type:"boolean",required:!1},authType:{type:"enum",values:[0,1,2],required:!1},syncLevel:{type:"enum",values:[1,0],required:!1},routeConfig:{type:"object",required:!1,rules:{routeEnabled:{type:"boolean",required:!1},routeEnvironment:{type:"string",required:!1}}}},mt=["https://lbs.netease.im/lbs/webconf.jsp"],ht={retryCount:3,timeout:6e4,forceMode:!1,authType:0,syncLevel:0};var ut={"27_1":"v2NIMSync","27_10":"v2QChatSync"},gt={v2NIMSync:{sid:27,cid:1,service:"V2NIMSyncService",hasPacketTimer:!1,params:[{type:"Property",name:"tag",reflectMapper:{myInfo:1,offlineMsgs:2,teams:3,roamingMsgs:7,relations:9,friends:11,friendUsers:13,msgReceipts:14,myTeamMembers:15,donnop:16,recallMsg:17,sessionAck:18,broadcastMsgs:20,avSignal:21,superTeams:22,mySuperTeamMembers:23,superTeamRoamingMsgs:24,deleteSuperTeamMsg:25,superTeamSessionAck:26,deleteSelfMsgs:27,stickTopSessions:28,sessionHistoryMsgsDelete:29,p2pTeamModifyMessage:30,superTeamModifyMessage:31,friendOperatorList:32,p2pMsgReceiptV2:33,p2pSessionAckV2:34,teamSessionAckV2:35,superTeamSessionAckV2:36,teamApplyList:38,friendApplyInfoDeleteOrClear:39,filterMsgs:100}}],response:[{type:"Long",name:"timetag"}]},v2QChatSync:{sid:27,cid:10,service:"V2NIMSyncService",hasPacketTimer:!1,params:[{type:"Property",name:"tag",reflectMapper:{systemNotification:1,pushConfig:2}}],response:[{type:"Long",name:"timetag"}]}};var vt={debug(...t){},log(...t){},warn(...t){},error(...t){}};function setLogger(t){vt=t}function getLogger(){return vt}function base64ToArrayBuffer(t){for(var i=function base64Decode(t){var i=String(t).replace(/[=]+$/,"");if(i.length%4==1)throw new Error("'atob' failed: The string to be decoded is not correctly encoded.");for(var o,m="",h=0,u=0,v=0;o=i.charAt(v++);~o&&(u=h%4?64*u+o:o,h++%4)?m+=String.fromCharCode(255&u>>(-2*h&6)):0)o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(o);return m}(t),o=i.length,m=new Uint8Array(o),h=0;h<o;h++)m[h]=i.charCodeAt(h);return m.buffer}function isMobile(){if(!navigator||!navigator.userAgent)return!1;return[/Android/i,/webOS/i,/iPhone/i,/iPad/i,/iPod/i,/BlackBerry/i,/Windows Phone/i].some((t=>navigator.userAgent.match(t)))}function isElectron(){return!(!navigator||!navigator.userAgent)&&("object"==typeof navigator&&"string"==typeof navigator.userAgent&&navigator.userAgent.indexOf("Electron")>=0)}function isBrowser(){return navigator&&navigator.userAgent}function to(t){try{return t.then((t=>[null,t])).catch((t=>[t,void 0]))}catch(t){var i=t;return Promise.resolve([i,void 0])}}var ft={clear(){uni.clearStorageSync()},getItem:t=>uni.getStorageSync(t),setItem:(t,i)=>uni.setStorageSync(t,i),removeItem:t=>uni.removeStorageSync(t)};function formatDateToYYYYMMDD$1(t){var i=t.getFullYear(),o=t.getMonth()+1,m=t.getDate();return`${i}${o<10?`0${o}`:String(o)}${m<10?`0${m}`:String(m)}`}class LogStorageForAppImpl{constructor(t){this.fileSystem=null,this.dirEntry=null,this.currentLogFile=null,this.isInitialized=!1,this.dirPath="",this.filePath="",this.logRetentionDays=10,this.totalLogSize=209715200,this.maxSingleLogFileSize=10485760,this.lastErrorMsg=void 0,this.logFiles=[],t.logRetentionDays>=1&&t.logRetentionDays<=30&&(this.logRetentionDays=t.logRetentionDays),t.totalLogSizeInMB>=10&&t.totalLogSizeInMB<=500&&(this.totalLogSize=1024*t.totalLogSizeInMB*1024),t.maxLogFileSizeInMB>=1&&t.maxLogFileSizeInMB<=200&&(this.maxSingleLogFileSize=1024*t.maxLogFileSizeInMB*1024),this.dirPath=t.logDirPath||"nim_logs",this.dirPath.endsWith("/")||(this.dirPath+="/");var i=formatDateToYYYYMMDD$1(new Date);this.filePath=`${this.dirPath}${i}.log`}isPlusAvailable(){return"undefined"!=typeof plus&&void 0!==plus.io&&"function"==typeof plus.io.requestFileSystem}getFileEntry(t,i={}){return new Promise(((o,m)=>{this.dirEntry?this.dirEntry.getFile(t,i,(t=>{o(t)}),(t=>{m(t)})):m(new Error("LogStorage::No directory entry available"))}))}deleteFile(t){return new Promise(((i,o)=>{t.remove((()=>{i()}),(t=>{o(t)}))}))}deleteFileByName(t){return __awaiter(this,void 0,void 0,(function*(){var i=yield this.getFileEntry(t);yield this.deleteFile(i)}))}getFileSize(t){return new Promise(((i,o)=>{t.file((t=>{i(t.size||0)}),(t=>{o(t)}))}))}writeFile(t,i){return new Promise(((o,m)=>{t.createWriter((t=>{t.onwrite=()=>{o()},t.onerror=t=>{m(t)},t.write(i)}),(t=>{m(t)}))}))}appendFile(t,i){return new Promise(((o,m)=>{t.createWriter((t=>{t.onwrite=()=>{o()},t.onerror=t=>{m(t)},t.seek(t.length||0),t.write(i)}),(t=>{m(t)}))}))}getDirectory(t,i={}){var o=getLogger();return new Promise(((m,h)=>{this.fileSystem&&this.fileSystem.root?this.fileSystem.root.getDirectory(t,i,(t=>{m(t)}),(i=>{o.warn(`LogStorage::getDirectory failed: ${t}; ${i&&i.message}`),h(i)})):h(new Error("LogStorage::File system not initialized"))}))}initializeFileSystem(){return __awaiter(this,void 0,void 0,(function*(){var t=getLogger();if(!this.isPlusAvailable())return t.error("LogStorage::plus.io API unavailable"),Promise.reject(new Error("LogStorage::plus.io API unavailable"));try{this.fileSystem=yield new Promise(((i,o)=>{plus.io.requestFileSystem(plus.io.PRIVATE_DOC,(t=>{t.root?i(t):o(new Error("LogStorage::fs.root empty"))}),(i=>{t.error(`LogStorage::requestFileSystem failed;${i&&i.message}`),o(i)}))})),t.log("LogStorage::requestFileSystemOk"),this.dirEntry=yield this.getDirectory(this.dirPath,{create:!0}),t.log("LogStorage::initDirectoryOk"),this.isInitialized=!0}catch(i){return t.error(`LogStorage:initFailed;${i&&i.message}`),Promise.reject(i)}}))}collectFileInfo(t){var i=this,o=getLogger();this.logFiles=[];var m=[],_loop=function(){var t=h,u=t.name;if(!u)return 0;if(!u.endsWith(".log")&&!/\.log\.\d+$/.test(u))return 0;var v=i.getFileSize(t).then((o=>{i.logFiles.push({fileName:u,size:o,fullPath:t.fullPath})})).catch((t=>{o.warn(`LogStorage::collectFileInfo:getFileFailed;${u};${t&&t.message}`)}));m.push(v)};for(var h of t)_loop();return Promise.all(m)}sortLogFiles(){this.logFiles.sort(((t,i)=>{var[o,m,h]=t.fileName.split("."),[u,v,I]=i.fileName.split(".");return o!==u?parseInt(u)-parseInt(o):h&&!I?1:!h&&I?-1:h&&I?parseInt(I)-parseInt(h):0}))}listLogFiles(){var t=getLogger();return this.isInitialized&&this.dirEntry?new Promise(((i,o)=>{this.dirEntry?this.dirEntry.createReader().readEntries((m=>{var h=m;h=h.filter((t=>t.isFile)),this.collectFileInfo(h).then((()=>{this.sortLogFiles(),t.log(`LogStorage::collectFileInfoOk,numbers of files is ${this.logFiles.length}`),i()})).catch((i=>{t.warn(`LogStorage::collectFileInfoFailed;${i&&i.message}`),o(i)}))}),(i=>{t.error(`LogStorage::readEntriesFailed;${i&&i.message}`),o(i)})):o(new Error("LogStorage::dirEntryEmpty"))})):Promise.reject(new Error("LogStorage::uninitialized"))}openCurrentLogFile(){return __awaiter(this,void 0,void 0,(function*(){var t=getLogger(),i=`${formatDateToYYYYMMDD$1(new Date)}.log`;return this.filePath=`${this.dirPath}${i}`,new Promise(((o,m)=>{if(!this.isInitialized||!this.dirEntry)return m(new Error("LogStorage::uninitialized"));this.dirEntry.getFile(i,{create:!0},(t=>{this.currentLogFile=t,o()}),(i=>{t.error(`LogStorage::openCurrentLogFileFailed:${this.filePath};${i&&i.message}`),m(i)}))}))}))}checkRetentionDays(){return __awaiter(this,void 0,void 0,(function*(){var t=getLogger(),i=new Date,o=this.logRetentionDays,m=new Date(i);m.setDate(i.getDate()-o);var h=+formatDateToYYYYMMDD$1(m);t.log(`LogStorage:checkRetentionDays;expiryDate:${h}`);var u=[];for(var v of this.logFiles){var I=v.fileName,[_]=I.split(".");if(parseInt(_)<h){t.log(`LogStorage::checkRetentionDays expireFile:${I}`);try{yield this.deleteFileByName(I)}catch(i){t.warn(`LogStorage:checkRetentionDays deleteFailed:${I};${i&&i.message}`)}}else u.push(v)}this.logFiles=u}))}checkTotalLogSize(){return __awaiter(this,void 0,void 0,(function*(){var t=getLogger(),i=this.logFiles.reduce(((t,i)=>t+i.size),0);if(i>this.totalLogSize)for(t.warn(`LogStorage::checkTotalLogSize:overlimit.totalSize(${i}B),limit(${this.totalLogSize}B)`);this.logFiles.length>1&&this.logFiles.reduce(((t,i)=>t+i.size),0)>this.totalLogSize;){var o=this.logFiles[this.logFiles.length-1];if(!o)break;try{yield this.deleteFileByName(o.fileName),this.logFiles.pop(),t.log(`LogStorage::deleteFileOk:${o.fileName}`)}catch(i){t.warn(`LogStorage::deleteFileFailed:${o.fileName};${i&&i.message}`);break}}}))}checkCurrentFileSize(){return __awaiter(this,void 0,void 0,(function*(){var t=getLogger();if(this.currentLogFile)try{var i=yield this.getFileSize(this.currentLogFile);this.logFiles.length>0&&(this.logFiles[0].size=i),i>this.maxSingleLogFileSize&&(t.log(`LogStorage::checkCurrentFileSizeOk:needArchive.currenFileSize(${i}B),limit(${this.maxSingleLogFileSize}B)`),yield this.archiveLog())}catch(i){t.warn(`LogStorage::checkCurrentFileSizeFailed;${i&&i.message}`)}}))}copyFile(t,i,o){return new Promise(((m,h)=>{t.copyTo(i,o,(t=>{m(t)}),(t=>{h(t)}))}))}archiveLog(){return __awaiter(this,void 0,void 0,(function*(){var t=getLogger();if(this.currentLogFile&&this.dirEntry){var i=formatDateToYYYYMMDD$1(new Date),o=0;for(var m of this.logFiles){var h=m.fileName.split(".");if(h[0]===i&&h.length>=3&&"log"===h[1]){var u=parseInt(h[2],10);!isNaN(u)&&u>o&&(o=u)}}var v=`${i}.log.${o+1}`,[I,_]=yield to(this.copyFile(this.currentLogFile,this.dirEntry,v));if(I||void 0===_)t.error(`LogStorage::archiveLog:copyFailed;${I&&I.message}`);else{var[M,E]=yield to(this.getFileSize(_));if(M||void 0===E)t.error(`LogStorage::archiveLog:getFileSizeFailed;${M&&M.message}`);else{this.logFiles.splice(1,0,{fileName:v,size:E,fullPath:_.fullPath});var[S]=yield to(this.writeFile(this.currentLogFile,"==="));S?t.error(`LogStorage::archiveLog:writeFileFailed;${S&&S.message}`):(this.logFiles.length>0&&(this.logFiles[0].size=3),t.log(`LogStorage::archiveLogOk:${v}`),yield this.checkTotalLogSize())}}}}))}open(){return __awaiter(this,void 0,void 0,(function*(){var t=getLogger();t.log("LogStorage::opening");try{this.isInitialized||(yield this.initializeFileSystem()),yield this.listLogFiles(),yield this.openCurrentLogFile(),yield this.checkRetentionDays(),yield this.checkCurrentFileSize(),yield this.checkTotalLogSize(),t.log("LogStorage::openOK")}catch(i){t.error(`LogStorage:openFailed;${i&&i.message}`)}}))}close(){}addLogs(t){return __awaiter(this,void 0,void 0,(function*(){var i=getLogger();if(this.isInitialized&&this.currentLogFile){var o=t.map((t=>t.text)).concat("").join("\n"),[m]=yield to(this.appendFile(this.currentLogFile,o));if(m){var h=m.message;return this.lastErrorMsg!==h&&i.warn(`LogStorage::addLogFailed:${h}`),void(this.lastErrorMsg=h)}this.logFiles.length>0&&(this.logFiles[0].size+=o.length),this.lastErrorMsg=void 0,yield this.checkCurrentFileSize(),yield this.checkTotalLogSize()}}))}isZipAvailable(){return"undefined"!=typeof plus&&void 0!==plus.zip&&"function"==typeof plus.zip.compress}compressToZip(t,i){return new Promise(((o,m)=>{this.isZipAvailable()?plus.zip.compress(t,i,(()=>{o(i)}),(t=>{m(t)})):m(new Error("LogStorage:plus.zip API unavailable"))}))}extractLogs(){return __awaiter(this,void 0,void 0,(function*(){var t=getLogger();if(this.isInitialized&&this.currentLogFile&&this.dirEntry)if(this.isZipAvailable())if(0!==this.logFiles.length){var i=this.dirEntry.fullPath;if(i){var o="_nim_logs.zip",m=i+o;t.warn(`LogStorage::ready to extract;${i};${m}`);var[h]=yield to(this.deleteFileByName(o));h&&t.warn(`LogStorage::extractLog:deleteTempZipFileFailed;${h&&h.message}`);var[u]=yield to(this.compressToZip(i,m));if(u)throw t.error(`LogStorage::compressToZipFailed:${u&&u.message}`),u;return t.log(`LogStorage::compressToZipOk:${m}`),m}t.warn("LogStorage::fullPath not exist")}else t.warn("LogStorage::no log files to extract");else t.error("LogStorage::LogStorage:plus.zip API unavailable")}))}afterUpload(){return __awaiter(this,void 0,void 0,(function*(){var t=getLogger(),[i]=yield to(this.deleteFileByName("_nim_logs.zip"));i?t.warn(`LogStorage::afterUpload:deleteTempZipFileFailed;${i&&i.message}`):t.log("LogStorage::afterUpload:deleteTempZipFileOk")}))}clearAllFile(){return __awaiter(this,void 0,void 0,(function*(){var t=getLogger();try{for(var i of this.logFiles)yield this.deleteFileByName(i.fileName)}catch(i){t.warn(`LogStorage:clearFailed;${i&&i.message}`)}t.log("LogStorage:clearAllOk")}))}}class LogStorageForMiniAppImpl{constructor(t){this.dirPath="",this.filePath="",this.copyFilePath="",this.enable=!1,this.maxCapacity=26214400,this.remainCapacity=8388608,this.count=0,this.maxCount=100,this.lastErrorMsg=void 0;var i=uni.getSystemInfoSync(),o="mp-weixin"===i.uniPlatform||"mp-alipay"===i.uniPlatform;if(this.enable=o,o){var m=this.getAPIEnv();m&&(this.dirPath=`${m.env.USER_DATA_PATH}/__nim`,this.filePath=`${this.dirPath}/${t.logDirPath}.log`,this.copyFilePath=`${this.dirPath}/${t.logDirPath}_copy.log`)}}getAPIEnv(){if(!("undefined"!=typeof tt&&tt.getSystemInfoSync||"undefined"!=typeof swan&&swan.getSystemInfoSync))return"undefined"!=typeof my&&my.getSystemInfoSync?my:"undefined"!=typeof wx&&wx.getAppBaseInfo?wx:void 0}makeDir(){if(this.enable){var t=this.getAPIEnv();if(t){var i=getLogger(),o=t.getFileSystemManager();try{var m=o.accessSync(this.dirPath);i.log("logStorage::access dir:",m),("object"==typeof m&&null!==m?m.error||m.errno||m.errCode||m.errNo:0)>200&&o.mkdirSync(this.dirPath,!0)}catch(t){o.mkdirSync(this.dirPath,!0)}try{var h=o.accessSync(this.filePath);i.log("logStorage::access file:",h),("object"==typeof h&&null!==h?h.error||h.errno||h.errCode||h.errNo:0)>200&&o.writeFileSync(this.filePath,"===","utf8")}catch(t){o.writeFileSync(this.filePath,"===","utf8")}}}}open(){return __awaiter(this,void 0,void 0,(function*(){if(this.enable){var t=getLogger();try{this.makeDir(),t.log(`logStorage::open log file success:${this.filePath}`)}catch(i){t.warn(`logStorage::open log file failed:${this.filePath}`,i)}yield this.checkCapacity(this.remainCapacity)}}))}checkCapacity(t){return __awaiter(this,void 0,void 0,(function*(){if(this.enable){var i=this.getAPIEnv();if(i){var o=getLogger(),m=i.getFileSystemManager(),h=this.getSize();if(h>this.maxCapacity){o.log(`logStorage::checksize:exceed,${h} byte`);var u="";try{u=yield this.readLogs(h-t)}catch(t){return void o.log("logStorage::checkCapacity:read failed",t)}o.log(`logStorage::checksize:read success ${h-t} byte`);try{m.unlinkSync(this.filePath)}catch(t){return void o.log("logStorage::checkCapacity:unlink failed",t)}try{m.writeFileSync(this.filePath,u,"utf8")}catch(t){return void o.log("logStorage::checkCapacity:write failed",t)}}else o.log(`logStorage::checkCapacity:not exceeding,${h} byte`)}}}))}getSize(){var t;if(!this.enable)return 0;var i=this.getAPIEnv();if(!i)return 0;var o,m=getLogger(),h=i.getFileSystemManager();try{o=h.statSync(this.filePath,!1)}catch(t){return m.warn("logStorage::stat failed",t),0}return o.size||(null===(t=o.stats)||void 0===t?void 0:t.size)}readLogs(t=0){if(!this.enable)return Promise.resolve("");var i=this.getAPIEnv();if(!i)return Promise.resolve("");var o=getLogger(),m=i.getFileSystemManager();return new Promise(((i,h)=>{m.readFile({filePath:this.filePath,encoding:"utf8",position:t,success:t=>{var m=t.data;"string"==typeof m?(o.warn(`logStorage::readLogs success ${m.length}`),i(m)):(o.warn("logStorage::readLogs empty"),h(new Error("logStorage::readLogs empty")))},fail:t=>{var i=t.errMsg||t.errorMessage||t.message;o.warn(`logStorage::readLogs failed ${i}`);var m={code:t.errCode||0,message:i};h(m)}})}))}close(){}addLogs(t){if(!this.enable)return Promise.resolve();var i=this.getAPIEnv();if(!i)return Promise.resolve();var o=getLogger(),m=t.map((t=>t.text)).concat("").join("\n");try{i.getFileSystemManager().appendFileSync(this.filePath,m,"utf8")}catch(t){var h=t.errMsg||t.errorMessage||t.message;this.lastErrorMsg!==h&&o.warn("logStorage::append failed",t),this.lastErrorMsg=h}return this.count+=1,this.count>this.maxCount&&(this.count=0,this.checkCapacity(this.remainCapacity)),Promise.resolve()}extractLogs(){return __awaiter(this,void 0,void 0,(function*(){if(this.enable){var t=this.getAPIEnv();if(t){var i=getLogger(),o=t.getFileSystemManager();if(this.getSize()>0){try{o.copyFileSync(this.filePath,this.copyFilePath)}catch(t){return void i.warn("logStorage::copyFileSync failed",t)}return this.copyFilePath}i.warn("logStorage::extractLogs empty")}}}))}afterUpload(){return __awaiter(this,void 0,void 0,(function*(){if(this.enable){var t=this.getAPIEnv();if(t){var i=getLogger(),o=t.getFileSystemManager();try{o.unlinkSync(this.copyFilePath)}catch(t){return void i.log("logStorage::delete copyFilePath failed",t)}}}}))}}var It={wifi:2,"2g":3,"3g":4,"4g":5,"5g":6,ethernet:1,unknown:0,none:0,notreachable:0,wwan:0};function getNetFn(t){var i=null;return{getNetworkStatus:()=>new Promise(((i,o)=>{t.getNetworkType({success:function(t){var o=t.networkType||t.subtype||"unknown",m=!1;m="boolean"==typeof t.networkAvailable?t.networkAvailable:"none"!==o.toLowerCase(),i({net_type:It[o.toLowerCase()]||0,net_connect:m})},fail:function(){o(new Error("getNetworkType failed"))}})})),onNetworkStatusChange(o){this.offNetworkStatusChange(),t.onNetworkStatusChange&&(i=function(t){var i=(t.networkType||t.subtype||"unknown").toLowerCase();o({isConnected:t.isConnected||"none"!==i,networkType:It[i]})},t.onNetworkStatusChange(i))},offNetworkStatusChange(){t.offNetworkStatusChange&&(i&&t.offNetworkStatusChange(i),i=null)}}}var yt={__onNetworkStatusChangeFn:null,getNetworkStatus(){var t=uni.getSystemInfoSync()||{};return"app"===t.uniPlatform&&"harmonyos"===t.osName?Promise.resolve({net_type:0,net_connect:!0}):new Promise(((t,i)=>{uni.getNetworkType({success:function(i){var o=!1;o="boolean"==typeof i.networkAvailable?i.networkAvailable:"none"!==i.networkType.toLowerCase(),t({net_type:It[i.networkType.toLowerCase()],net_connect:o})},fail:function(){i(new Error("getNetworkType failed"))}})}))},onNetworkStatusChange(t){this.offNetworkStatusChange(),uni.onNetworkStatusChange&&(this.__onNetworkStatusChangeFn=function(i){var o=i.networkType.toLowerCase();t({isConnected:i.isConnected||"none"!==o,networkType:It[o]})},uni.onNetworkStatusChange(this.__onNetworkStatusChangeFn))},offNetworkStatusChange(){uni.offNetworkStatusChange&&(this.__onNetworkStatusChangeFn&&uni.offNetworkStatusChange(this.__onNetworkStatusChangeFn),this.__onNetworkStatusChangeFn=null)}},_t=getLogger();class PowerMonitor$2 extends Ie{constructor(){super(),this.status=0,this.appShowListener=null,this.appHideListener=null,this.flag=!1,this._initAppLifecycleListener()}isActive(){return 0===this.status}getStatus(){return this.status}setStatus(t){var i=this.status;t!==i&&(this.status=t,0===t&&1===i&&this.emit("onPowerMonitorTurnActive"),_t.log("Adapter powerMonitor::setStatus: ",t))}destroy(){this.status=0,this.flag=!1,this._canIUse()&&(this.appShowListener&&(uni.offAppShow(this.appShowListener),this.appShowListener=null),this.appHideListener&&(uni.offAppHide(this.appHideListener),this.appHideListener=null))}_initAppLifecycleListener(){this.flag||(!1!==this._canIUse()?(this.appShowListener=()=>{var t=this.status;this.status=0,1===t&&this.emit("onPowerMonitorTurnActive"),_t.log("Adapter powerMonitor::onAppShow status:",this.status)},this.appHideListener=()=>{this.status=1,_t.log("Adapter powerMonitor::onAppHide status:",this.status)},uni.onAppShow(this.appShowListener),uni.onAppHide(this.appHideListener),this.flag=!0,_t.log("Adapter powerMonitor::_initAppLifecycleListener success")):_t.warn("Adapter powerMonitor::_initAppLifecycleListener env.onAppShow/env.onAppHide not available"))}_canIUse(){return"undefined"!=typeof uni&&"function"==typeof uni.onAppShow&&"function"==typeof uni.onAppHide&&"function"==typeof uni.offAppShow&&"function"==typeof uni.offAppHide}}function requestFn$1(t,i){return i&&(i.data=i.data||(null==i?void 0:i.params)||{}),new Promise(((o,m)=>{uni.request(Object.assign(Object.assign({method:"GET",url:t},i),{success:function(i){"number"==typeof(i=i||{}).statusCode&&i.statusCode.toString().startsWith("2")?(i={data:i.data,status:i.statusCode,errMsg:i.errMsg,header:i.header},o(i)):m({code:i.statusCode||0,message:i.data||`uniApp request fail. url: ${t}`})},fail:function(i){var o=`uniApp request fail. url: ${t}`;m(i?{code:i.errCode||0,message:i.errMsg||o}:{code:0,message:o})}}))}))}var getUserAgent=function(){var t=uni.getSystemInfoSync()||{};if("mp-weixin"===t.uniPlatform&&"undefined"!=typeof wx&&wx.getAppBaseInfo){var i=wx.getAppBaseInfo();return`NIM/Web/UNIAPP(${t.uniRuntimeVersion})/WeChatMiniApp(${i.SDKVersion})/V10.9.70/{{appkey}}`}if("undefined"!=typeof tt&&tt.getSystemInfoSync){var o=tt.getSystemInfoSync();return`NIM/Web/UNIAPP(${t.uniRuntimeVersion})/TiktokMiniApp(${o.SDKVersion})/V10.9.70/{{appkey}}`}if("undefined"!=typeof swan&&swan.getSystemInfoSync){var m=swan.getSystemInfoSync();return`NIM/Web/UNIAPP(${t.uniRuntimeVersion})/BaiduMiniApp(${m.SDKVersion})/V10.9.70/{{appkey}}`}if("undefined"!=typeof my&&my.getSystemInfoSync){var h=my.getSystemInfoSync();return`NIM/Web/UNIAPP(${t.uniRuntimeVersion})/AliMiniApp(${h.SDKVersion})/V10.9.70/{{appkey}}`}if(navigator&&navigator.userAgent)return navigator.userAgent;if(t.ua)return t.ua;var u=uni.getSystemInfoSync();return`NIM/Web/UNIAPP(${u.uniRuntimeVersion})/${u.osName}(${u.osVersion})/V10.9.70/{{appkey}}`},getHostEnvVer=function(){var t=uni.getSystemInfoSync()||{};if("mp-weixin"===t.uniPlatform&&"undefined"!=typeof wx&&wx.getAppBaseInfo){var i=wx.getAppBaseInfo();return`${t.uniRuntimeVersion}/${i.version}`}if("undefined"!=typeof tt&&tt.getSystemInfoSync){var o=tt.getSystemInfoSync();return`${t.uniRuntimeVersion}/${o.version}`}if("undefined"!=typeof swan&&swan.getSystemInfoSync){var m=swan.getSystemInfoSync();return`${t.uniRuntimeVersion}/${m.version}`}if("undefined"!=typeof my&&my.getSystemInfoSync){var h=my.getSystemInfoSync();return`${t.uniRuntimeVersion}/${h.version}`}return`${t.uniRuntimeVersion}`},getModel=function(){var t=uni.getSystemInfoSync()||{};if("mp-weixin"===t.uniPlatform&&"undefined"!=typeof wx&&wx.getAppBaseInfo){var i=wx.getAppBaseInfo();return`${t.uniRuntimeVersion}/${i.SDKVersion}`}if("undefined"!=typeof tt&&tt.getSystemInfoSync){var o=tt.getSystemInfoSync();return`${t.uniRuntimeVersion}/${o.SDKVersion}`}if("undefined"!=typeof swan&&swan.getSystemInfoSync){var m=swan.getSystemInfoSync();return`${t.uniRuntimeVersion}/${m.SDKVersion}`}return"undefined"!=typeof my&&my.getSystemInfoSync?(my.getSystemInfoSync(),`${t.uniRuntimeVersion}/${my.SDKVersion}`):`${t.uniRuntimeVersion}`};function getSystemInfoFn$6(){var t,i="app"===(t=(uni.getSystemInfoSync()||{}).uniPlatform)?[110,"APP"]:"web"===t||"h5"===t?[101,"H5"]:"mp-weixin"===t?[6,"WeiXin"]:"mp-alipay"===t?[102,"Ali"]:"mp-baidu"===t?[103,"Baidu"]:"mp-toutiao"===t?[104,"Tiktok"]:0===t.indexOf("mp-")||0===t.indexOf("quickapp")?[105,"OtherMiniProgram"]:[0,"Unset"],o=uni.getSystemInfoSync()||{};return{os:o.osName||"UNIAPP_UNKNOW",osVer:o.osVersion,browser:o.browserName||"",browserVer:o.browserVersion||"",libEnv:"UNIAPP",hostEnv:i[1],hostEnvEnum:i[0],hostEnvVer:getHostEnvVer(),userAgent:getUserAgent(),model:getModel(),manufactor:i[1],pushDeviceInfo:{PRODUCT:o.model,DEVICE:o.model,MANUFACTURER:o.brand}}}function uploadFileFn$2(t){var i=getLogger(),o=t.headers||{};return t.md5&&(o["Content-MD5"]=t.md5),new Promise(((m,h)=>{var u=uni.uploadFile(Object.assign(Object.assign({url:`${t.commonUploadHost}/${t.nosToken.bucket}`},Object.keys(o).length>0?{header:o}:{}),{formData:{Object:decodeURIComponent(t.nosToken.objectName),"x-nos-token":t.nosToken.token,"x-nos-entity-type":"json"},name:"file",fileName:"file",fileType:t.type,filePath:t.filePath,success(i){if(200==i.statusCode){t.onUploadInfo&&t.onUploadInfo({http_code:i.statusCode});var u={};if("string"==typeof i.data)try{u=JSON.parse(i.data)}catch(o){t.onUploadInfo&&t.onUploadInfo({exception:`JSON parse error:${i.data}`}),h({code:i.statusCode,message:i.errMsg,rawData:i.data})}u.name=t.filePath,u.ext=u.name&&u.name.lastIndexOf(".")>-1?u.name.slice(u.name.lastIndexOf(".")+1).toLowerCase():"",m(u)}else t.onUploadInfo&&t.onUploadInfo({http_code:i.statusCode,exception:i.data,rsp_headers:i.header,req_headers:o}),h({code:i.statusCode,message:i.errMsg,rawData:i.data})},fail(i){t.onUploadInfo&&t.onUploadInfo({http_code:0,exception:i,req_headers:o}),"string"==typeof i.errMsg&&i.errMsg.indexOf("abort")>-1&&(i.code=Ee.V2NIM_ERROR_CODE_CANCELLED),i.message=i.errMsg,h(i)}}));try{t.onUploadStart&&t.onUploadStart(u)}catch(t){i.error("Adapter uploadFile: options.onUploadStart error",t&&t.message),u.abort(),h(t)}t.onUploadProgress&&u.onProgressUpdate((function(i){var o=i.totalBytesExpectedToWrite||i.totalBytesExpectedToSend,m=i.totalBytesWritten||i.totalBytesSent;t.onUploadProgress&&t.onUploadProgress({total:o,loaded:m,percentage:parseFloat((m/o).toFixed(2)),percentageText:i.progress+"%"})}))}))}function getFileUploadInformationFn$2(t){return null}class WebsocketFn{constructor(t,i=""){if(this.CONNECTING=0,this.OPEN=1,this.CLOSING=2,this.CLOSED=3,this.binaryType="",this.onclose=function(t){getLogger().log("Adapter uniapp: sockets on close ",t)},this.onerror=function(t){getLogger().error("Adapter uniapp: sockets error ",t)},this.onmessage=function(t){},this.onopen=function(){},!t)throw new Error("Failed to construct 'socket': url required");this.url=t.replace(/:443(\/|$)/,"$1"),this.protocol=i,this.readyState=this.CONNECTING;var o=this.protocol?{protocols:this.protocol}:{};this.socketTask=uni.connectSocket(Object.assign(Object.assign({url:this.url},o),{multiple:!0,fail:t=>{this.errorHandler(t)}})),this.socketTask.onOpen((t=>{getLogger().log("Adapter uniapp:: onOpen. event: ",t),this.readyState=this.OPEN,this.binaryType?this.onopen():this.onmessage&&this.onmessage({type:"open",header:t})})),this.socketTask.onError((t=>{getLogger().log("Adapter uniapp:: onError. event: ",t),this.errorHandler(t)})),this.socketTask.onClose((t=>{(this.readyState=this.CLOSED,"function"==typeof this.onclose)&&(this.onclose&&this.onclose(t),getLogger().log("Adapter uniapp:: onClose. event: ",t));this.socketTask=null})),this.socketTask.onMessage((t=>{var i;i="string"==typeof t.data||t.data instanceof ArrayBuffer?t.data:t.data.isBuffer&&"string"==typeof t.data.data?base64ToArrayBuffer(t.data.data):t.data.data,this.onmessage&&this.onmessage({data:i})}))}close(){getLogger().log("Adapter uniapp:: close uni socket actively"),this.socketTask.close({code:1e3,reason:"user force close websocket",complete:()=>{this.socketTask=null}})}send(t){if(this.readyState!==this.OPEN)throw new Error(`Adapter uniapp:: socket sendMsg when readyState=${this.readyState}`);if(!("string"==typeof t||t instanceof ArrayBuffer))throw new TypeError("Adapter uniapp:: socket sendMsg only String/ArrayBuffer supported");this.socketTask.send({data:t})}errorHandler(t){getLogger().error("Adapter uniapp:: errorHandler. event: ",t),this.readyState=this.CLOSED,this.onerror&&this.onerror({type:"error",message:t&&t.errMsg}),t.errMsg&&"[object Array]"===Object.prototype.toString.call(t.errMsg)&&(t.errMsg.indexOf("断裂管道")>0||t.errMsg.indexOf("broken pipe")>0)&&this.onclose&&this.onclose(t)}}var getAdapter$2=()=>{var t=uni.getSystemInfoSync()||{},i="app"===t.uniPlatform,o="mp-weixin"===t.uniPlatform;return Object.assign({setLogger:setLogger,platform:"UNIAPP",localStorage:ft,request:requestFn$1,WebSocket:WebsocketFn,uploadFile:uploadFileFn$2,getFileUploadInformation:getFileUploadInformationFn$2,getSystemInfo:getSystemInfoFn$6,net:yt,powerMonitor:new PowerMonitor$2},i?{logStorage:LogStorageForAppImpl}:o?{logStorage:LogStorageForMiniAppImpl}:{})},Mt=createCommonjsModule((function(t,i){t.exports=function(){function object2String(t){if(t){var i="";return Object.keys(t).forEach((function(o,m){i+=0===m?"?":"&",i+=`${o}=${t[o]}`})),i}return""}class V2NIMError extends Error{constructor(t,i,o,m){super(o),this.source=t,this.code=i,this.desc=o,this.detail=m||{}}}function request(t,i={dataType:"json",method:"GET",timeout:5e3}){var o="text"===i.dataType?"text/plain; charset=UTF-8":"application/json; charset=UTF-8",m="GET"===i.method?object2String(i.params):"";return new Promise((function(h,u){if(window.XMLHttpRequest){var v,I=new XMLHttpRequest;if(I.onreadystatechange=function(){if(4===I.readyState)if(200===I.status){try{v=JSON.parse(I.response||"{}")}catch(t){v=I.response}h({status:I.status,data:v})}else setTimeout((()=>{u(new V2NIMError(1,I.status,`readyState: ${I.readyState}; statusText: ${I.statusText}`))}),0)},I.open(i.method,`${t}${m}`),I.timeout=i.timeout||5e3,I.setRequestHeader("Content-Type",o),i.headers)for(var _ in i.headers)I.setRequestHeader(_,i.headers[_]);I.ontimeout=function(t){u(new V2NIMError(1,408,t&&t.message?t.message:"request timeout"))},I.send(JSON.stringify(i.data))}else u(new V2NIMError(2,10400,"request no suppout"))}))}return request}()})),Et=createCommonjsModule((function(t,i){self,t.exports=function(){var t={d:function(i,o){for(var m in o)t.o(o,m)&&!t.o(i,m)&&Object.defineProperty(i,m,{enumerable:!0,get:o[m]})},o:function(t,i){return Object.prototype.hasOwnProperty.call(t,i)}},i={};t.d(i,{default:function(){return S}});var o=function e(t){for(var i in function(t,i){if(!(t instanceof i))throw new TypeError("Cannot call a class as a function")}(this,e),this.directUploadAddr="https://wanproxy-web.127.net",this.retryCount=4,this.trunkSize=4194304,this.trunkUploadTimeout=0,this.getOffsetTimeout=1e4,this.version="1.0",this.enableCache=!0,this.logger=console,this.onError=function(t){},this.onProgress=function(t){},this.onUploadProgress=function(t){},this.onComplete=function(t){},this.onUploadInfo=function(t){},t)this[i]=t[i]};function n(t,i){var o="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!o){if(Array.isArray(t)||(o=function(t,i){if(t){if("string"==typeof t)return r(t,i);var o=Object.prototype.toString.call(t).slice(8,-1);return"Object"===o&&t.constructor&&(o=t.constructor.name),"Map"===o||"Set"===o?Array.from(t):"Arguments"===o||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(o)?r(t,i):void 0}}(t))||i&&t&&"number"==typeof t.length){o&&(t=o);var m=0,a=function(){};return{s:a,n:function(){return m>=t.length?{done:!0}:{done:!1,value:t[m++]}},e:function(t){throw t},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var h,u=!0,v=!1;return{s:function(){o=o.call(t)},n:function(){var t=o.next();return u=t.done,t},e:function(t){v=!0,h=t},f:function(){try{u||null==o.return||o.return()}finally{if(v)throw h}}}}function r(t,i){(null==i||i>t.length)&&(i=t.length);for(var o=0,m=new Array(i);o<i;o++)m[o]=t[o];return m}var m={privateObj:{},setItem:function(t,i){m.privateObj[t]=i},getItem:function(t){return m.privateObj[t]},removeItem:function(t){delete m.privateObj[t]},getKeys:function(){return Object.keys(m.privateObj)}},h={getFileKey:function(t){var i=t.size.toString(),o=t.lastModified.toString();return"_NosUploader_"+t.name+i.slice(i.length-5)+o.slice(o.length-5)},getFileInfo:function(t){var i=m.getItem(t);if(!i)return null;try{return JSON.parse(i)}catch(t){return null}},initFile:function(t,i,o){h.clearExpiredInfo();var u=this.getFileKey(i),v={ctx:void 0!==t.ctx?t.ctx:"",bucket:t.bucketName,obj:t.objectName,token:t.token,modifyAt:Date.now(),end:!1};return t.payload&&(v.payload=t.payload),o&&m.setItem(u,JSON.stringify(v)),u},setUploadContext:function(t,i,o){var h=this.getFileInfo(t);h&&(h.ctx=i,o&&m.setItem(t,JSON.stringify(h)))},setComplete:function(t,i){var o=this.getFileInfo(t);o&&(o.modifyAt=Date.now(),o.end=!0,i&&m.setItem(t,JSON.stringify(o)))},getUploadContext:function(t){var i=this.getFileInfo(t);return i?i.ctx:""},removeFileInfo:function(t){0===t.indexOf("_NosUploader_")&&m.removeItem(t)},clearExpiredInfo:function(){var t,i="function"==typeof m.getKeys?m.getKeys():Object.keys(m),o=Date.now(),u=[],v=n(i);try{for(v.s();!(t=v.n()).done;){var I=t.value;if(0===I.indexOf("_NosUploader_")){var _=h.getFileInfo(I);null===_||o-_.modifyAt>S.expireTime?m.removeItem(I):u.push({fileInfo:_,key:I})}}}catch(t){v.e(t)}finally{v.f()}if(u.length>S.maxFileCache){var M,E=n(u.sort((function(t,i){return i.fileInfo.modifyAt-t.fileInfo.modifyAt})).slice(S.maxFileCache));try{for(E.s();!(M=E.n()).done;){var T=M.value;0===T.key.indexOf("_NosUploader_")&&m.removeItem(T.key)}}catch(t){E.e(t)}finally{E.f()}}}},u=h;function c(t){return(c="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function l(t,i){return!i||"object"!==c(i)&&"function"!=typeof i?function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t):i}function s(t){var i="function"==typeof Map?new Map:void 0;return(s=function(t){if(null===t||(o=t,-1===Function.toString.call(o).indexOf("[native code]")))return t;var o;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==i){if(i.has(t))return i.get(t);i.set(t,n)}function n(){return f(t,arguments,y(this).constructor)}return n.prototype=Object.create(t.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),d(n,t)})(t)}function f(t,i,o){return(f=p()?Reflect.construct:function(t,i,o){var m=[null];m.push.apply(m,i);var h=new(Function.bind.apply(t,m));return o&&d(h,o.prototype),h}).apply(null,arguments)}function p(){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(t){return!1}}function d(t,i){return(d=Object.setPrototypeOf||function(t,i){return t.__proto__=i,t})(t,i)}function y(t){return(y=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}var v=function(t){!function(t,i){if("function"!=typeof i&&null!==i)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(i&&i.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),i&&d(t,i)}(r,t);var i,o,m=(i=r,o=p(),function(){var t,m=y(i);if(o){var h=y(this).constructor;t=Reflect.construct(m,arguments,h)}else t=m.apply(this,arguments);return l(this,t)});function r(t,i){var o;return function(t,i){if(!(t instanceof i))throw new TypeError("Cannot call a class as a function")}(this,r),(o=m.call(this,"NosUploadError:"+t)).errCode=i,o.errMsg=t,o}return r}(s(Error)),I=function e(t,i,o){if("uploading"===t.uploadState){var m=t.config,h=t.param,I=u.getUploadContext(t.fileKey);if(!I)return o(0);var _=new XMLHttpRequest,M=m.directUploadAddr+"/".concat(h.bucketName)+"/".concat(encodeURIComponent(h.objectName))+"?uploadContext"+"&context=".concat(I)+"&version=".concat(m.version);_.onreadystatechange=function(){var h;if("abort"!==t.uploadState&&4===_.readyState){var I;try{I=JSON.parse(_.responseText)}catch(t){I={errMsg:"JsonParseError in getOffset. xhr.status = "+_.status+". xhr.responseText: "+_.responseText,errCode:500}}200===_.status?I.errCode?t.config.onError(new v(I.errMsg,I.errCode)):o(I.offset):_.status.toString().match(/^5/)?e(t,i-1,o):i>0?("function"==typeof(null===(h=m.logger)||void 0===h?void 0:h.error)&&m.logger.error("getOffset(".concat(M,") error. retry after 3 seconds. ").concat((new Date).toTimeString())),setTimeout((function(){e(t,i-1,o)}),3500)):_.status?(u.removeFileInfo(t.fileKey),m.onError(new v("getOffset(".concat(M,") error: ").concat(_.status," ").concat(_.statusText)))):m.onError(new v("getOffset(".concat(M,") error. no Error Code")))}},_.open("get",M),_.setRequestHeader("x-nos-token",h.token),_.timeout=m.getOffsetTimeout,_.send()}};function g(t,i){(null==i||i>t.length)&&(i=t.length);for(var o=0,m=new Array(i);o<i;o++)m[o]=t[o];return m}var _=function e(t,i,o,m){if("uploading"===t.uploadState){var h=t.param,I=t.config,_=File.prototype.slice,M=void 0!==h.ctx?h.ctx:"",E=i+I.trunkSize>=t.file.size,S=E?t.file.size:i+I.trunkSize,T=Date.now(),C=new XMLHttpRequest,N=I.directUploadAddr+"/".concat(h.bucketName)+"/".concat(encodeURIComponent(h.objectName)),A={};C.upload.onprogress=function(o){if("abort"!==t.uploadState){var m=0;if(o.lengthComputable){var h=i+o.loaded;m=h/t.file.size,I.onProgress(m),I.onUploadProgress({loaded:h,total:t.file.size,percentage:m,percentageText:(100*m).toFixed(2)+"%"})}else I.onError(new v("browser does not support query upload progress"))}},C.onload=function(){if(200!==C.status){var t=C.getAllResponseHeaders();if(t){var i=t.split("\n").reduce((function(t,i){if(0===i.length)return t;var o,m,h=(m=2,function(t){if(Array.isArray(t))return t}(o=i.split(": "))||function(t,i){var o=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=o){var m,h,u=[],v=!0,I=!1;try{for(o=o.call(t);!(v=(m=o.next()).done)&&(u.push(m.value),!i||u.length!==i);v=!0);}catch(t){I=!0,h=t}finally{try{v||null==o.return||o.return()}finally{if(I)throw h}}return u}}(o,m)||function(t,i){if(t){if("string"==typeof t)return g(t,i);var o=Object.prototype.toString.call(t).slice(8,-1);return"Object"===o&&t.constructor&&(o=t.constructor.name),"Map"===o||"Set"===o?Array.from(t):"Arguments"===o||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(o)?g(t,i):void 0}}(o,m)||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.")}()),u=h[0],v=h[1];return t[u]=v,t}),{});I.onUploadInfo({rsp_headers:i})}}},C.onreadystatechange=function(){var h,_,M;if("abort"!==t.uploadState&&4===C.readyState){var S;if(C.responseText)try{S=JSON.parse(C.responseText)}catch(t){"function"==typeof(null===(h=I.logger)||void 0===h?void 0:h.error)&&I.logger.error("JsonParseError in uploadTrunk. xhr.status = "+C.status+". xhr.responseText: "+C.responseText,t),S={errMsg:"JsonParseError in uploadTrunk. xhr.status = "+C.status+". xhr.responseText: "+C.responseText}}else"function"==typeof(null===(_=I.logger)||void 0===_?void 0:_.error)&&I.logger.error("xhr.status = "+C.status+" and xhr.responseText empty");I.onUploadInfo({transfer_latency:Date.now()-T}),200===C.status?(I.onUploadInfo({http_code:200}),t.setContext(S.context),E?(m(),t.setComplete()):e(t,S.offset,I.retryCount,m)):C.status.toString().match(/^5/)?(I.onUploadInfo({http_code:C.status,req_headers:A}),o>0?e(t,i,o-1,m):(u.removeFileInfo(t.fileKey),I.onError(new v(S.errMsg,S.errCode)))):(I.onUploadInfo({http_code:C.status||0,req_headers:A}),o>0?("function"==typeof(null===(M=I.logger)||void 0===M?void 0:M.error)&&I.logger.error("uploadTrunk(".concat(N,") error. retry after 3 seconds. ").concat((new Date).toTimeString())),setTimeout((function(){e(t,i,o-1,m)}),3500)):C.status?(u.removeFileInfo(t.fileKey),I.onError(new v("uploadTrunk(".concat(N,") error: ").concat(C.status," ").concat(C.statusText)))):I.onError(new v("uploadTrunk(".concat(N,") error. no Error Code. Please check your network"))))}};var O=N+"?offset=".concat(i)+"&complete=".concat(E)+"&context=".concat(M)+"&version=".concat(I.version);if(I.onUploadInfo({remote_addr:O,part_size:E?t.file.size-i:I.trunkSize,index:Math.ceil(i/I.trunkSize)}),C.open("post",O),C.setRequestHeader("x-nos-token",h.token),A["x-nos-token"]=h.token,h.md5&&(C.setRequestHeader("content-md5",h.md5),A["content-md5"]=h.md5),t.file.type&&(C.setRequestHeader("content-type",t.file.type),A["content-type"]=t.file.type),I.trunkUploadTimeout&&I.trunkUploadTimeout>0&&(C.timeout=I.trunkUploadTimeout),"undefined"!=typeof FileReader){var R=new FileReader;R.onload=function(t){var i;(null===(i=null==t?void 0:t.target)||void 0===i?void 0:i.result)instanceof ArrayBuffer&&t.target.result.byteLength>0?C.send(t.target.result):I.onError(new v("Read ArrayBuffer failed",194003))},R.onerror=function(t){var i=t.target.error;I.onError(new v("Read ArrayBuffer error. ".concat(i.toString()),194003))},R.readAsArrayBuffer(_.call(t.file,i,S))}else C.send(_.call(t.file,i,S))}};function b(t,i){for(var o=0;o<i.length;o++){var m=i[o];m.enumerable=m.enumerable||!1,m.configurable=!0,"value"in m&&(m.writable=!0),Object.defineProperty(t,m.key,m)}}var M=function(){function e(t,i,o){!function(t,i){if(!(t instanceof i))throw new TypeError("Cannot call a class as a function")}(this,e),this.uploadState="paused",this.config=o,this.file=t,this.param=i,this.fileKey=u.initFile(i,t,this.config.enableCache),this.resume()}var t;return(t=[{key:"resume",value:function(){var t=this;if("uploading"!==this.uploadState){this.setUploadState("uploading");var i=this.config;I(this,i.retryCount,(function(o){_(t,o,i.retryCount,(function(){t.setUploadState("ended"),"function"==typeof i.onComplete&&i.onComplete(t.param)}))}))}}},{key:"pause",value:function(){this.setUploadState("paused")}},{key:"abort",value:function(){"ended"!==this.uploadState&&"abort"!==this.uploadState&&(this.setUploadState("abort"),this.config.onError(new v("Upload Aborted",10499)))}},{key:"setUploadState",value:function(t){t!==this.uploadState&&(this.uploadState=t)}},{key:"setContext",value:function(t){u.setUploadContext(this.fileKey,t,this.config.enableCache),this.param.ctx=t}},{key:"setComplete",value:function(){u.setComplete(this.fileKey,this.config.enableCache),this.setUploadState("ended")}}])&&b(e.prototype,t),e}(),E={maxFileCache:1/0,expireTime:864e5,getFileUploadInformation:function(t){var i=u.getFileKey(t),o=u.getFileInfo(i);return null===o?null:Date.now()-o.modifyAt>E.expireTime?(u.removeFileInfo(i),null):{uploadInfo:Object.assign({bucketName:o.bucket,objectName:o.obj,token:o.token,ctx:o.ctx},o.payload?{payload:o.payload}:{}),complete:o.end}},setMaxFileCache:function(t){E.maxFileCache=t},setExpireTime:function(t){E.expireTime=t},printCaches:function(){if("undefined"!=typeof localStorage)for(var t=0,i=Object.keys(localStorage);t<i.length;t++){var o=i[t],m=u.getFileInfo(o);m&&console.log(m,"modifiedAt",new Date(m.modifyAt).toTimeString())}},createConfig:function(t){return new o(t)},createTask:function(t,i,o){return new M(t,i,o)}},S=E;return i.default}()}));function uploadFileFn$1(t){return __awaiter(this,void 0,void 0,(function*(){var i,o=getLogger();if(!t.fileInput&&!t.file)throw new Error("File not exist");if(t.file)i=t.file;else if("string"==typeof t.fileInput){var m=document.getElementById(t.fileInput);if(!(m&&m.files&&m.files[0]))throw new Error("Can not get file from fileInput");i=m.files[0]}else{if(!(t.fileInput&&t.fileInput.files&&t.fileInput.files[0]))throw new Error(`Can not get file from fileInput ${t.fileInput}`);i=t.fileInput.files[0]}if(t.maxSize&&i.size>t.maxSize)throw new Error(`The file exceeds maxSize limit. maxSize: ${t.maxSize}, get ${i.size}`);var h=yield new Promise(((m,h)=>{var u,v=Et.getFileUploadInformation(i),I=Et.createConfig({enableCache:!0,retryCount:0,directUploadAddr:t.chunkUploadHost,onError:function(t){h(t)},onUploadProgress:t.onUploadProgress||function(){},onComplete:function(t){m(t)},onUploadInfo:function(i){t.onUploadInfo&&t.onUploadInfo(i)}});if(v)if(v.complete)t.onUploadProgress&&t.onUploadProgress({total:i.size,loaded:i.size,percentage:1,percentageText:"100%"}),m(v.uploadInfo);else{u=Et.createTask(i,v.uploadInfo,I);try{t.onUploadStart&&t.onUploadStart(u)}catch(t){o.error("Adapter uploadFile: options.onUploadStart error",t&&t.message),u.abort(),h(t)}}else{u=Et.createTask(i,Object.assign(Object.assign({bucketName:t.nosToken.bucket,objectName:decodeURIComponent(t.nosToken.objectName),token:t.nosToken.token},t.md5?{md5:t.md5}:{}),t.payload?{payload:t.payload}:{}),I);try{t.onUploadStart&&t.onUploadStart(u)}catch(t){o.error("Adapter uploadFile: options.onUploadStart error",t&&t.message),u.abort(),h(t)}}}));return h.name=i.name,h.size=i.size,h.type=i.type,h.ext=h.name.lastIndexOf(".")>-1?h.name.slice(h.name.lastIndexOf(".")+1).toLowerCase():"",h}))}function getFileUploadInformationFn$1(t){var i;if(t.file)i=t.file;else if("string"==typeof t.fileInput){var o=document.getElementById(t.fileInput);if(!(o&&o.files&&o.files[0]))throw new Error("Can not get file from fileInput");i=o.files[0]}else{if(!(t.fileInput&&t.fileInput.files&&t.fileInput.files[0]))throw new Error(`Can not get file from fileInput ${t.fileInput}`);i=t.fileInput.files[0]}return Et.getFileUploadInformation(i)}
/*!
* Platform.js v1.3.6
* Copyright 2014-2020 Benjamin Tan
* Copyright 2011-2013 John-David Dalton
* Available under MIT license
*/var St=createCommonjsModule((function(i,o){(function(){var m={function:!0,object:!0}[typeof window]&&window||this,h=o,u=i&&!i.nodeType&&i,v=h&&u&&"object"==typeof t&&t;!v||v.global!==v&&v.window!==v&&v.self!==v||(m=v);var I=Math.pow(2,53)-1,_=/\bOpera/,M=Object.prototype,E=M.hasOwnProperty,S=M.toString;function capitalize(t){return(t=String(t)).charAt(0).toUpperCase()+t.slice(1)}function format(t){return t=trim(t),/^(?:webOS|i(?:OS|P))/.test(t)?t:capitalize(t)}function forOwn(t,i){for(var o in t)E.call(t,o)&&i(t[o],o,t)}function getClassOf(t){return null==t?capitalize(t):S.call(t).slice(8,-1)}function qualify(t){return String(t).replace(/([ -])(?!$)/g,"$1?")}function reduce(t,i){var o=null;return function each(t,i){var o=-1,m=t?t.length:0;if("number"==typeof m&&m>-1&&m<=I)for(;++o<m;)i(t[o],o,t);else forOwn(t,i)}(t,(function(m,h){o=i(o,m,h,t)})),o}function trim(t){return String(t).replace(/^ +| +$/g,"")}var T=function parse(t){var i=m,o=t&&"object"==typeof t&&"String"!=getClassOf(t);o&&(i=t,t=null);var h=i.navigator||{},u=h.userAgent||"";t||(t=u);var v,I,M=o?!!h.likeChrome:/\bChrome\b/.test(t)&&!/internal|\n/i.test(S.toString()),E="Object",T=o?E:"ScriptBridgingProxyObject",C=o?E:"Environment",N=o&&i.java?"JavaPackage":getClassOf(i.java),A=o?E:"RuntimeObject",O=/\bJava/.test(N)&&i.java,R=O&&getClassOf(i.environment)==C,V=O?"a":"α",k=O?"b":"β",P=i.document||{},L=i.operamini||i.opera,w=_.test(w=o&&L?L["[[Class]]"]:getClassOf(L))?w:L=null,D=t,U=[],x=null,B=t==u,$=B&&L&&"function"==typeof L.version&&L.version(),j=function getLayout(i){return reduce(i,(function(i,o){return i||RegExp("\\b"+(o.pattern||qualify(o))+"\\b","i").exec(t)&&(o.label||o)}))}([{label:"EdgeHTML",pattern:"Edge"},"Trident",{label:"WebKit",pattern:"AppleWebKit"},"iCab","Presto","NetFront","Tasman","KHTML","Gecko"]),G=function getName(i){return reduce(i,(function(i,o){return i||RegExp("\\b"+(o.pattern||qualify(o))+"\\b","i").exec(t)&&(o.label||o)}))}(["Adobe AIR","Arora","Avant Browser","Breach","Camino","Electron","Epiphany","Fennec","Flock","Galeon","GreenBrowser","iCab","Iceweasel","K-Meleon","Konqueror","Lunascape","Maxthon",{label:"Microsoft Edge",pattern:"(?:Edge|Edg|EdgA|EdgiOS)"},"Midori","Nook Browser","PaleMoon","PhantomJS","Raven","Rekonq","RockMelt",{label:"Samsung Internet",pattern:"SamsungBrowser"},"SeaMonkey",{label:"Silk",pattern:"(?:Cloud9|Silk-Accelerated)"},"Sleipnir","SlimBrowser",{label:"SRWare Iron",pattern:"Iron"},"Sunrise","Swiftfox","Vivaldi","Waterfox","WebPositive",{label:"Yandex Browser",pattern:"YaBrowser"},{label:"UC Browser",pattern:"UCBrowser"},"Opera Mini",{label:"Opera Mini",pattern:"OPiOS"},"Opera",{label:"Opera",pattern:"OPR"},"Chromium","Chrome",{label:"Chrome",pattern:"(?:HeadlessChrome)"},{label:"Chrome Mobile",pattern:"(?:CriOS|CrMo)"},{label:"Firefox",pattern:"(?:Firefox|Minefield)"},{label:"Firefox for iOS",pattern:"FxiOS"},{label:"IE",pattern:"IEMobile"},{label:"IE",pattern:"MSIE"},"Safari"]),q=getProduct([{label:"BlackBerry",pattern:"BB10"},"BlackBerry",{label:"Galaxy S",pattern:"GT-I9000"},{label:"Galaxy S2",pattern:"GT-I9100"},{label:"Galaxy S3",pattern:"GT-I9300"},{label:"Galaxy S4",pattern:"GT-I9500"},{label:"Galaxy S5",pattern:"SM-G900"},{label:"Galaxy S6",pattern:"SM-G920"},{label:"Galaxy S6 Edge",pattern:"SM-G925"},{label:"Galaxy S7",pattern:"SM-G930"},{label:"Galaxy S7 Edge",pattern:"SM-G935"},"Google TV","Lumia","iPad","iPod","iPhone","Kindle",{label:"Kindle Fire",pattern:"(?:Cloud9|Silk-Accelerated)"},"Nexus","Nook","PlayBook","PlayStation Vita","PlayStation","TouchPad","Transformer",{label:"Wii U",pattern:"WiiU"},"Wii","Xbox One",{label:"Xbox 360",pattern:"Xbox"},"Xoom"]),H=function getManufacturer(i){return reduce(i,(function(i,o,m){return i||(o[q]||o[/^[a-z]+(?: +[a-z]+\b)*/i.exec(q)]||RegExp("\\b"+qualify(m)+"(?:\\b|\\w*\\d)","i").exec(t))&&m}))}({Apple:{iPad:1,iPhone:1,iPod:1},Alcatel:{},Archos:{},Amazon:{Kindle:1,"Kindle Fire":1},Asus:{Transformer:1},"Barnes & Noble":{Nook:1},BlackBerry:{PlayBook:1},Google:{"Google TV":1,Nexus:1},HP:{TouchPad:1},HTC:{},Huawei:{},Lenovo:{},LG:{},Microsoft:{Xbox:1,"Xbox One":1},Motorola:{Xoom:1},Nintendo:{"Wii U":1,Wii:1},Nokia:{Lumia:1},Oppo:{},Samsung:{"Galaxy S":1,"Galaxy S2":1,"Galaxy S3":1,"Galaxy S4":1},Sony:{PlayStation:1,"PlayStation Vita":1},Xiaomi:{Mi:1,Redmi:1}}),z=function getOS(i){return reduce(i,(function(i,o){var m=o.pattern||qualify(o);return!i&&(i=RegExp("\\b"+m+"(?:/[\\d.]+|[ \\w.]*)","i").exec(t))&&(i=function cleanupOS(t,i,o){var m={"10.0":"10",6.4:"10 Technical Preview",6.3:"8.1",6.2:"8",6.1:"Server 2008 R2 / 7","6.0":"Server 2008 / Vista",5.2:"Server 2003 / XP 64-bit",5.1:"XP",5.01:"2000 SP1","5.0":"2000","4.0":"NT","4.90":"ME"};return i&&o&&/^Win/i.test(t)&&!/^Windows Phone /i.test(t)&&(m=m[/[\d.]+$/.exec(t)])&&(t="Windows "+m),t=String(t),i&&o&&(t=t.replace(RegExp(i,"i"),o)),format(t.replace(/ ce$/i," CE").replace(/\bhpw/i,"web").replace(/\bMacintosh\b/,"Mac OS").replace(/_PowerPC\b/i," OS").replace(/\b(OS X) [^ \d]+/i,"$1").replace(/\bMac (OS X)\b/,"$1").replace(/\/(\d)/," $1").replace(/_/g,".").replace(/(?: BePC|[ .]*fc[ \d.]+)$/i,"").replace(/\bx86\.64\b/gi,"x86_64").replace(/\b(Windows Phone) OS\b/,"$1").replace(/\b(Chrome OS \w+) [\d.]+\b/,"$1").split(" on ")[0])}(i,m,o.label||o)),i}))}(["Windows Phone","KaiOS","Android","CentOS",{label:"Chrome OS",pattern:"CrOS"},"Debian",{label:"DragonFly BSD",pattern:"DragonFly"},"Fedora","FreeBSD","Gentoo","Haiku","Kubuntu","Linux Mint","OpenBSD","Red Hat","SuSE","Ubuntu","Xubuntu","Cygwin","Symbian OS","hpwOS","webOS ","webOS","Tablet OS","Tizen","Linux","Mac OS X","Macintosh","Mac","Windows 98;","Windows "]);function getProduct(i){return reduce(i,(function(i,o){var m=o.pattern||qualify(o);return!i&&(i=RegExp("\\b"+m+" *\\d+[.\\w_]*","i").exec(t)||RegExp("\\b"+m+" *\\w+-[\\w]*","i").exec(t)||RegExp("\\b"+m+"(?:; *(?:[a-z]+[_-])?[a-z]+\\d+|[^ ();-]*)","i").exec(t))&&((i=String(o.label&&!RegExp(m,"i").test(o.label)?o.label:i).split("/"))[1]&&!/[\d.]+/.test(i[0])&&(i[0]+=" "+i[1]),o=o.label||o,i=format(i[0].replace(RegExp(m,"i"),o).replace(RegExp("; *(?:"+o+"[_-])?","i")," ").replace(RegExp("("+o+")[-_.]?(\\w)","i"),"$1 $2"))),i}))}function getVersion(i){return reduce(i,(function(i,o){return i||(RegExp(o+"(?:-[\\d.]+/|(?: for [\\w-]+)?[ /-])([\\d.]+[^ ();/_-]*)","i").exec(t)||0)[1]||null}))}if(j&&(j=[j]),/\bAndroid\b/.test(z)&&!q&&(v=/\bAndroid[^;]*;(.*?)(?:Build|\) AppleWebKit)\b/i.exec(t))&&(q=trim(v[1]).replace(/^[a-z]{2}-[a-z]{2};\s*/i,"")||null),H&&!q?q=getProduct([H]):H&&q&&(q=q.replace(RegExp("^("+qualify(H)+")[-_.\\s]","i"),H+" ").replace(RegExp("^("+qualify(H)+")[-_.]?(\\w)","i"),H+" $2")),(v=/\bGoogle TV\b/.exec(q))&&(q=v[0]),/\bSimulator\b/i.test(t)&&(q=(q?q+" ":"")+"Simulator"),"Opera Mini"==G&&/\bOPiOS\b/.test(t)&&U.push("running in Turbo/Uncompressed mode"),"IE"==G&&/\blike iPhone OS\b/.test(t)?(H=(v=parse(t.replace(/like iPhone OS/,""))).manufacturer,q=v.product):/^iP/.test(q)?(G||(G="Safari"),z="iOS"+((v=/ OS ([\d_]+)/i.exec(t))?" "+v[1].replace(/_/g,"."):"")):"Konqueror"==G&&/^Linux\b/i.test(z)?z="Kubuntu":H&&"Google"!=H&&(/Chrome/.test(G)&&!/\bMobile Safari\b/i.test(t)||/\bVita\b/.test(q))||/\bAndroid\b/.test(z)&&/^Chrome/.test(G)&&/\bVersion\//i.test(t)?(G="Android Browser",z=/\bAndroid\b/.test(z)?z:"Android"):"Silk"==G?(/\bMobi/i.test(t)||(z="Android",U.unshift("desktop mode")),/Accelerated *= *true/i.test(t)&&U.unshift("accelerated")):"UC Browser"==G&&/\bUCWEB\b/.test(t)?U.push("speed mode"):"PaleMoon"==G&&(v=/\bFirefox\/([\d.]+)\b/.exec(t))?U.push("identifying as Firefox "+v[1]):"Firefox"==G&&(v=/\b(Mobile|Tablet|TV)\b/i.exec(t))?(z||(z="Firefox OS"),q||(q=v[1])):!G||(v=!/\bMinefield\b/i.test(t)&&/\b(?:Firefox|Safari)\b/.exec(G))?(G&&!q&&/[\/,]|^[^(]+?\)/.test(t.slice(t.indexOf(v+"/")+8))&&(G=null),(v=q||H||z)&&(q||H||/\b(?:Android|Symbian OS|Tablet OS|webOS)\b/.test(z))&&(G=/[a-z]+(?: Hat)?/i.exec(/\bAndroid\b/.test(z)?z:v)+" Browser")):"Electron"==G&&(v=(/\bChrome\/([\d.]+)\b/.exec(t)||0)[1])&&U.push("Chromium "+v),$||($=getVersion(["(?:Cloud9|CriOS|CrMo|Edge|Edg|EdgA|EdgiOS|FxiOS|HeadlessChrome|IEMobile|Iron|Opera ?Mini|OPiOS|OPR|Raven|SamsungBrowser|Silk(?!/[\\d.]+$)|UCBrowser|YaBrowser)","Version",qualify(G),"(?:Firefox|Minefield|NetFront)"])),(v=("iCab"==j&&parseFloat($)>3?"WebKit":/\bOpera\b/.test(G)&&(/\bOPR\b/.test(t)?"Blink":"Presto"))||/\b(?:Midori|Nook|Safari)\b/i.test(t)&&!/^(?:Trident|EdgeHTML)$/.test(j)&&"WebKit"||!j&&/\bMSIE\b/i.test(t)&&("Mac OS"==z?"Tasman":"Trident")||"WebKit"==j&&/\bPlayStation\b(?! Vita\b)/i.test(G)&&"NetFront")&&(j=[v]),"IE"==G&&(v=(/; *(?:XBLWP|ZuneWP)(\d+)/i.exec(t)||0)[1])?(G+=" Mobile",z="Windows Phone "+(/\+$/.test(v)?v:v+".x"),U.unshift("desktop mode")):/\bWPDesktop\b/i.test(t)?(G="IE Mobile",z="Windows Phone 8.x",U.unshift("desktop mode"),$||($=(/\brv:([\d.]+)/.exec(t)||0)[1])):"IE"!=G&&"Trident"==j&&(v=/\brv:([\d.]+)/.exec(t))&&(G&&U.push("identifying as "+G+($?" "+$:"")),G="IE",$=v[1]),B){if(function isHostType(t,i){var o=null!=t?typeof t[i]:"number";return!(/^(?:boolean|number|string|undefined)$/.test(o)||"object"==o&&!t[i])}(i,"global"))if(O&&(D=(v=O.lang.System).getProperty("os.arch"),z=z||v.getProperty("os.name")+" "+v.getProperty("os.version")),R){try{$=i.require("ringo/engine").version.join("."),G="RingoJS"}catch(t){(v=i.system)&&v.global.system==i.system&&(G="Narwhal",z||(z=v[0].os||null))}G||(G="Rhino")}else"object"==typeof i.process&&!i.process.browser&&(v=i.process)&&("object"==typeof v.versions&&("string"==typeof v.versions.electron?(U.push("Node "+v.versions.node),G="Electron",$=v.versions.electron):"string"==typeof v.versions.nw&&(U.push("Chromium "+$,"Node "+v.versions.node),G="NW.js",$=v.versions.nw)),G||(G="Node.js",D=v.arch,z=v.platform,$=($=/[\d.]+/.exec(v.version))?$[0]:null));else getClassOf(v=i.runtime)==T?(G="Adobe AIR",z=v.flash.system.Capabilities.os):getClassOf(v=i.phantom)==A?(G="PhantomJS",$=(v=v.version||null)&&v.major+"."+v.minor+"."+v.patch):"number"==typeof P.documentMode&&(v=/\bTrident\/(\d+)/i.exec(t))?($=[$,P.documentMode],(v=+v[1]+4)!=$[1]&&(U.push("IE "+$[1]+" mode"),j&&(j[1]=""),$[1]=v),$="IE"==G?String($[1].toFixed(1)):$[0]):"number"==typeof P.documentMode&&/^(?:Chrome|Firefox)\b/.test(G)&&(U.push("masking as "+G+" "+$),G="IE",$="11.0",j=["Trident"],z="Windows");z=z&&format(z)}if($&&(v=/(?:[ab]|dp|pre|[ab]\d+pre)(?:\d+\+?)?$/i.exec($)||/(?:alpha|beta)(?: ?\d)?/i.exec(t+";"+(B&&h.appMinorVersion))||/\bMinefield\b/i.test(t)&&"a")&&(x=/b/i.test(v)?"beta":"alpha",$=$.replace(RegExp(v+"\\+?$"),"")+("beta"==x?k:V)+(/\d+\+?/.exec(v)||"")),"Fennec"==G||"Firefox"==G&&/\b(?:Android|Firefox OS|KaiOS)\b/.test(z))G="Firefox Mobile";else if("Maxthon"==G&&$)$=$.replace(/\.[\d.]+/,".x");else if(/\bXbox\b/i.test(q))"Xbox 360"==q&&(z=null),"Xbox 360"==q&&/\bIEMobile\b/.test(t)&&U.unshift("mobile mode");else if(!/^(?:Chrome|IE|Opera)$/.test(G)&&(!G||q||/Browser|Mobi/.test(G))||"Windows CE"!=z&&!/Mobi/i.test(t))if("IE"==G&&B)try{null===i.external&&U.unshift("platform preview")}catch(t){U.unshift("embedded")}else(/\bBlackBerry\b/.test(q)||/\bBB10\b/.test(t))&&(v=(RegExp(q.replace(/ +/g," *")+"/([.\\d]+)","i").exec(t)||0)[1]||$)?(z=((v=[v,/BB10/.test(t)])[1]?(q=null,H="BlackBerry"):"Device Software")+" "+v[0],$=null):this!=forOwn&&"Wii"!=q&&(B&&L||/Opera/.test(G)&&/\b(?:MSIE|Firefox)\b/i.test(t)||"Firefox"==G&&/\bOS X (?:\d+\.){2,}/.test(z)||"IE"==G&&(z&&!/^Win/.test(z)&&$>5.5||/\bWindows XP\b/.test(z)&&$>8||8==$&&!/\bTrident\b/.test(t)))&&!_.test(v=parse.call(forOwn,t.replace(_,"")+";"))&&v.name&&(v="ing as "+v.name+((v=v.version)?" "+v:""),_.test(G)?(/\bIE\b/.test(v)&&"Mac OS"==z&&(z=null),v="identify"+v):(v="mask"+v,G=w?format(w.replace(/([a-z])([A-Z])/g,"$1 $2")):"Opera",/\bIE\b/.test(v)&&(z=null),B||($=null)),j=["Presto"],U.push(v));else G+=" Mobile";(v=(/\bAppleWebKit\/([\d.]+\+?)/i.exec(t)||0)[1])&&(v=[parseFloat(v.replace(/\.(\d)$/,".0$1")),v],"Safari"==G&&"+"==v[1].slice(-1)?(G="WebKit Nightly",x="alpha",$=v[1].slice(0,-1)):$!=v[1]&&$!=(v[2]=(/\bSafari\/([\d.]+\+?)/i.exec(t)||0)[1])||($=null),v[1]=(/\b(?:Headless)?Chrome\/([\d.]+)/i.exec(t)||0)[1],537.36==v[0]&&537.36==v[2]&&parseFloat(v[1])>=28&&"WebKit"==j&&(j=["Blink"]),B&&(M||v[1])?(j&&(j[1]="like Chrome"),v=v[1]||((v=v[0])<530?1:v<532?2:v<532.05?3:v<533?4:v<534.03?5:v<534.07?6:v<534.1?7:v<534.13?8:v<534.16?9:v<534.24?10:v<534.3?11:v<535.01?12:v<535.02?"13+":v<535.07?15:v<535.11?16:v<535.19?17:v<536.05?18:v<536.1?19:v<537.01?20:v<537.11?"21+":v<537.13?23:v<537.18?24:v<537.24?25:v<537.36?26:"Blink"!=j?"27":"28")):(j&&(j[1]="like Safari"),v=(v=v[0])<400?1:v<500?2:v<526?3:v<533?4:v<534?"4+":v<535?5:v<537?6:v<538?7:v<601?8:v<602?9:v<604?10:v<606?11:v<608?12:"12"),j&&(j[1]+=" "+(v+="number"==typeof v?".x":/[.+]/.test(v)?"":"+")),"Safari"==G&&(!$||parseInt($)>45)?$=v:"Chrome"==G&&/\bHeadlessChrome/i.test(t)&&U.unshift("headless")),"Opera"==G&&(v=/\bzbov|zvav$/.exec(z))?(G+=" ",U.unshift("desktop mode"),"zvav"==v?(G+="Mini",$=null):G+="Mobile",z=z.replace(RegExp(" *"+v+"$"),"")):"Safari"==G&&/\bChrome\b/.exec(j&&j[1])?(U.unshift("desktop mode"),G="Chrome Mobile",$=null,/\bOS X\b/.test(z)?(H="Apple",z="iOS 4.3+"):z=null):/\bSRWare Iron\b/.test(G)&&!$&&($=getVersion("Chrome")),$&&0==$.indexOf(v=/[\d.]+$/.exec(z))&&t.indexOf("/"+v+"-")>-1&&(z=trim(z.replace(v,""))),z&&-1!=z.indexOf(G)&&!RegExp(G+" OS").test(z)&&(z=z.replace(RegExp(" *"+qualify(G)+" *"),"")),j&&!/\b(?:Avant|Nook)\b/.test(G)&&(/Browser|Lunascape|Maxthon/.test(G)||"Safari"!=G&&/^iOS/.test(z)&&/\bSafari\b/.test(j[1])||/^(?:Adobe|Arora|Breach|Midori|Opera|Phantom|Rekonq|Rock|Samsung Internet|Sleipnir|SRWare Iron|Vivaldi|Web)/.test(G)&&j[1])&&(v=j[j.length-1])&&U.push(v),U.length&&(U=["("+U.join("; ")+")"]),H&&q&&q.indexOf(H)<0&&U.push("on "+H),q&&U.push((/^on /.test(U[U.length-1])?"":"on ")+q),z&&(v=/ ([\d.+]+)$/.exec(z),I=v&&"/"==z.charAt(z.length-v[0].length-1),z={architecture:32,family:v&&!I?z.replace(v[0],""):z,version:v?v[1]:null,toString:function(){var t=this.version;return this.family+(t&&!I?" "+t:"")+(64==this.architecture?" 64-bit":"")}}),(v=/\b(?:AMD|IA|Win|WOW|x86_|x)64\b/i.exec(D))&&!/\bi686\b/i.test(D)?(z&&(z.architecture=64,z.family=z.family.replace(RegExp(" *"+v),"")),G&&(/\bWOW64\b/i.test(t)||B&&/\w(?:86|32)$/.test(h.cpuClass||h.platform)&&!/\bWin64; x64\b/i.test(t))&&U.unshift("32-bit")):z&&/^OS X/.test(z.family)&&"Chrome"==G&&parseFloat($)>=39&&(z.architecture=64),t||(t=null);var Y={};return Y.description=t,Y.layout=j&&j[0],Y.manufacturer=H,Y.name=G,Y.prerelease=x,Y.product=q,Y.ua=t,Y.version=G&&$,Y.os=z||{architecture:null,family:null,version:null,toString:function(){return"null"}},Y.parse=parse,Y.toString=function toStringPlatform(){return this.description||""},Y.version&&U.unshift($),Y.name&&U.unshift(G),z&&G&&(z!=String(z).split(" ")[0]||z!=G.split(" ")[0]&&!q)&&U.push(q?"("+z+")":"on "+z),U.length&&(Y.description=U.join(" ")),Y}();h&&u?forOwn(T,(function(t,i){h[i]=t})):m.platform=T}).call(t)}));function getSystemInfoFn$5(){var t,i,o=St.version||"";if(isElectron())try{var m=navigator.userAgent.match(/Electron\/([\d.]+\d+)/);m&&m[1]&&"string"==typeof m[1]&&(o=m[1])}catch(t){}return{os:(null===(t=St.os)||void 0===t?void 0:t.family)||"",osVer:(null===(i=St.os)||void 0===i?void 0:i.version)||"",browser:St.name||"",browserVer:St.version||"",libEnv:"BROWSER",hostEnv:isElectron()?"Electron":isMobile()?"H5":isBrowser()?"BROWSER":"Unset",hostEnvEnum:isElectron()?5:isMobile()?101:isBrowser()?100:0,hostEnvVer:o,userAgent:navigator&&navigator.userAgent,model:o,manufactor:St.name||""}}var Tt=null,Ct=null,Nt={getNetworkStatus:()=>Promise.resolve({net_type:0,net_connect:"undefined"==typeof navigator||"boolean"!=typeof navigator.onLine||navigator.onLine}),onNetworkStatusChange(t){Tt=function(){t({isConnected:!0,networkType:0})},Ct=function(){t({isConnected:!1,networkType:0})},window.addEventListener("online",Tt),window.addEventListener("offline",Ct)},offNetworkStatusChange(){Tt&&window.removeEventListener("online",Tt),Ct&&window.removeEventListener("offline",Ct),Tt=null,Ct=null}},At=getLogger(),getVisibilityEvent=()=>{var t="hidden",i="visibilitychange";return"undefined"==typeof document||void 0!==document.hidden||(void 0!==document.webkitHidden?(t="webkitHidden",i="webkitvisibilitychange"):void 0!==document.msHidden?(t="msHidden",i="msvisibilitychange"):void 0!==document.mozHidden&&(t="mozHidden",i="mozvisibilitychange")),{hidden:t,visibilityChange:i}};class PowerMonitor$1 extends Ie{constructor(){super(),this.status=0,this.visibilityListener=null,this.flag=!1,this._initVisibilityListener()}isActive(){return 0===this.status}getStatus(){return this.status}setStatus(t){var i=this.status;t!==i&&(this.status=t,0===t&&1===i&&this.emit("onPowerMonitorTurnActive"),At.log("Adapter powerMonitor::setStatus: ",t))}destroy(){if(this.status=0,this.flag=!1,this._canIUse()&&this.visibilityListener){var{visibilityChange:t}=getVisibilityEvent();document.removeEventListener(t,this.visibilityListener),this.visibilityListener=null}}_initVisibilityListener(){if(!this.flag)if(!1!==this._canIUse()){var t,{hidden:i,visibilityChange:o}=getVisibilityEvent();i&&void 0!==document[i]&&(this.visibilityListener=(t=this,()=>{var i=t.status,{hidden:o}=getVisibilityEvent();o&&document[o]?t.status=1:(t.status=0,1===i&&t.emit("onPowerMonitorTurnActive")),At.log("Adapter powerMonitor::visibility change status:",t.status)}),document.addEventListener(o,this.visibilityListener),this.flag=!0,At.log("Adapter powerMonitor::_initVisibilityListener success, isHidden:",null===document||void 0===document?void 0:document[i]))}else At.warn("Adapter powerMonitor::_initVisibilityListener no document.addEventListener")}_canIUse(){return"undefined"!=typeof document&&void 0!==document.addEventListener}}class IDB{constructor(t,i){this.db=null,this.stores=[],this.name=t,this.version=i}getDB(){if(!this.db)throw new Error("DB not ready");return this.db}getStore(t){var i=this.stores.find((i=>i.storeName===t));if(!i)throw new Error(`LogStorage: store not found. ${t}`);return i}open(){var t=window.indexedDB.open(this.name,this.version);return new Promise(((i,o)=>{t.onerror=t=>{var i=t.target;o(i.error)},t.onsuccess=t=>{var o=t.target;this.db=o.result,this.db.removeEventListener("close",this.triggerDBCloseEvt.bind(this)),this.db.addEventListener("close",this.triggerDBCloseEvt.bind(this)),this.stores.push(new IDBStore("log",this)),i()},t.onupgradeneeded=t=>{var i=t.target;this.upgradeDBBySchema(i)}}))}triggerDBCloseEvt(){try{this.db&&this.db.close(),this.db=null}catch(t){}this.open()}upgradeDBBySchema(t){var i=t.result,o=t.transaction&&i.objectStoreNames.contains("log")?t.transaction.objectStore("log"):i.createObjectStore("log",{keyPath:"id",autoIncrement:!0});try{o.index("time")}catch(t){o.createIndex("time","time",{unique:!1})}}close(){this.db&&(this.db.removeEventListener("close",this.triggerDBCloseEvt.bind(this)),this.db.close(),this.stores=[],this.db=null)}}class IDBStore{constructor(t,i){this.idb=null,this.storeName=t,this.idb=i}getDB(){if(!this.idb)throw new Error("DB not ready");return this.idb.getDB()}getStoreName(){return this.storeName}bulkCreate(t){var i=this.getDB(),o=this.getStoreName(),m=i.transaction(o,"readwrite"),h=m.objectStore(o);return t.forEach((t=>{h.add(t)})),new Promise((function(t,i){m.oncomplete=function(){t()},m.onerror=function(t){var o=t.target;i(o.error)},m.onabort=function(t){var o=t.target;o.error instanceof Error?i(o.error):i(new Error("TransactionAborted"))}}))}bulkDelete(t){var{keyName:i,lower:o,upper:m,lowerOpen:h=!1,upperOpen:u=!1}=t,v=IDBKeyRange.bound(o,m,h,u),I=this.getDB(),_=this.getStoreName(),M=I.transaction(_,"readwrite"),E=M.objectStore(_).index(i).openCursor(v),S=0;return E.onsuccess=function(t){var i=t.target.result;i&&(i.delete(),S++,i.continue())},new Promise((function(t,i){M.oncomplete=function(){t(S)},M.onerror=function(t){var o=t.target;i(o.error)},M.onabort=function(t){var o=t.target;o.error instanceof Error?i(o.error):i(new Error("TransactionAborted"))}}))}readAll(){var t=this.getDB(),i=this.getStoreName(),o=t.transaction(i,"readonly").objectStore(i);if(!o.getAll)throw new Error("IDBExtract not support");var m=o.getAll();return new Promise(((t,i)=>{m.onsuccess=function(i){var o=i.target;t(o.result)},m.onerror=function(t){var o=t.target;i(o.error)}}))}}class LogStorageImpl$1{constructor(t){this.logRetentionDays=10,this.idb=new IDB(t.logDirPath,1),this.logRetentionDays=t.logRetentionDays>=1?t.logRetentionDays:10}open(){return __awaiter(this,void 0,void 0,(function*(){yield this.idb.open();var t=this.idb.getStore("log");try{yield t.bulkDelete({keyName:"time",lower:0,upper:Date.now()-24*this.logRetentionDays*60*60*1e3})}catch(t){}}))}close(){this.idb.close()}addLogs(t){return this.idb.getStore("log").bulkCreate(t)}extractLogs(){return __awaiter(this,void 0,void 0,(function*(){var t=this.idb.getStore("log"),i=yield t.readAll();if(0!==i.length){var o=i.reduce(((t,i)=>{var o=i.iid;return t[o]||(t[o]=[]),t[o].push(i),t}),{}),m=Object.keys(o).map((t=>`==========iid:${t}==========\n ${o[t].map((t=>t.text)).join("\n")}`)).join("\n");return new File([m],"nim-logs.txt",{type:"text/plain"})}}))}afterUpload(){return Promise.resolve()}}var getAdapter$1=()=>({setLogger:setLogger,platform:"BROWSER",localStorage:window.localStorage,request:Mt,WebSocket:window.WebSocket,uploadFile:uploadFileFn$1,getFileUploadInformation:getFileUploadInformationFn$1,getSystemInfo:getSystemInfoFn$5,net:Nt,powerMonitor:new PowerMonitor$1,logStorage:LogStorageImpl$1}),Ot=getLogger();class PowerMonitor extends Ie{constructor(t){super(),this.env=t,this.status=0,this.appShowListener=null,this.appHideListener=null,this.flag=!1,this._initAppLifecycleListener()}isActive(){return 0===this.status}getStatus(){return this.status}setStatus(t){var i=this.status;t!==i&&(this.status=t,0===t&&1===i&&this.emit("onPowerMonitorTurnActive"),Ot.log("Adapter powerMonitor::setStatus: ",t))}destroy(){this.status=0,this.flag=!1,this._canIUse()&&(this.appShowListener&&(this.env.offAppShow(this.appShowListener),this.appShowListener=null),this.appHideListener&&(this.env.offAppHide(this.appHideListener),this.appHideListener=null))}_initAppLifecycleListener(){this.flag||(!1!==this._canIUse()?(this.appShowListener=()=>{var t=this.status;this.status=0,1===t&&this.emit("onPowerMonitorTurnActive"),Ot.log("Adapter powerMonitor::onAppShow status:",this.status)},this.appHideListener=()=>{this.status=1,Ot.log("Adapter powerMonitor::onAppHide status:",this.status)},this.env.onAppShow(this.appShowListener),this.env.onAppHide(this.appHideListener),this.flag=!0,Ot.log("Adapter powerMonitor::_initAppLifecycleListener success")):Ot.warn("Adapter powerMonitor::_initAppLifecycleListener env.onAppShow/env.onAppHide not available"))}_canIUse(){return void 0!==this.env&&"function"==typeof this.env.onAppShow&&"function"==typeof this.env.onAppHide&&"function"==typeof this.env.offAppShow&&"function"==typeof this.env.offAppHide}}function getAPIEnv(){return"undefined"!=typeof qq&&"function"==typeof qq.request?qq:"undefined"!=typeof tt&&"function"==typeof tt.request?tt:"undefined"!=typeof swan&&"function"==typeof swan.request?swan:"undefined"!=typeof my&&"function"==typeof my.request?my:("undefined"!=typeof wx&&wx.request,wx)}function getBaseSystemInfo(){var t=getAPIEnv(),i=t?t.getSystemInfoSync():{};return{libEnv:"MINIAPP",os:i.platform||"",osVer:i.system||"",browser:"",browserVer:"",hostEnvVer:i.version,model:i.SDKVersion,pushDeviceInfo:{PRODUCT:i.model,DEVICE:i.model,MANUFACTURER:i.brand}}}class LogStorageImpl{constructor(t){this.dirPath="",this.filePath="",this.copyFilePath="",this.maxCapacity=26214400,this.remainCapacity=8388608,this.count=0,this.maxCount=60,this.lastErrorMsg=void 0,this.fileNames=[],this.param=t;var i=getAPIEnv();if(i){this.dirPath=`${i.env.USER_DATA_PATH}/${t.logDirPath}`;var o=function formatDateToYYYYMMDD(t){return`${t.getFullYear()}${String(t.getMonth()+1).padStart(2,"0")}${String(t.getDate()).padStart(2,"0")}`}(new Date);this.filePath=`${this.dirPath}/${o}.log`}}makeDir(){var t=getAPIEnv();if(t){var i=getLogger(),o=t.getFileSystemManager();try{var m=o.accessSync(this.dirPath);i.log("logStorage::access dir:",m),("object"==typeof m&&null!==m?m.error||m.errno||m.errCode||m.errNo:0)>200&&o.mkdirSync(this.dirPath,!0)}catch(t){o.mkdirSync(this.dirPath,!0)}try{var h=o.accessSync(this.filePath);i.log("logStorage::access file:",h),("object"==typeof h&&null!==h?h.error||h.errno||h.errCode||h.errNo:0)>200&&o.writeFileSync(this.filePath,"===","utf8")}catch(t){o.writeFileSync(this.filePath,"===","utf8")}}}open(){return __awaiter(this,void 0,void 0,(function*(){if(getAPIEnv()){var t=getLogger();try{this.makeDir(),t.log(`logStorage::open log file success:${this.filePath}`)}catch(i){t.warn(`logStorage::open log file failed:${this.filePath}`,i)}yield this.checkCapacity(this.remainCapacity)}}))}checkCapacity(t){return __awaiter(this,void 0,void 0,(function*(){var i=getAPIEnv();if(i){var o=getLogger(),m=i.getFileSystemManager(),h=this.getSize();if(h>this.maxCapacity){o.log(`logStorage::checksize:exceed,${h} byte`);var u="";try{u=yield this.readLogs(h-t)}catch(t){return void o.log("logStorage::checkCapacity:read failed",t)}o.log(`logStorage::checksize:read success ${h-t} byte`);try{m.unlinkSync(this.filePath)}catch(t){return void o.log("logStorage::checkCapacity:unlink failed",t)}try{m.writeFileSync(this.filePath,u,"utf8")}catch(t){return void o.log("logStorage::checkCapacity:write failed",t)}}else o.log(`logStorage::checkCapacity:not exceeding,${h} byte`)}}))}getSize(){var t,i=getAPIEnv();if(!i)return 0;var o,m=getLogger(),h=i.getFileSystemManager();try{o=h.statSync(this.filePath,!1)}catch(t){return m.warn("logStorage::stat failed",t),0}return o.size||(null===(t=o.stats)||void 0===t?void 0:t.size)}readLogs(t=0){var i=getAPIEnv();if(!i)return Promise.resolve("");var o=getLogger(),m=i.getFileSystemManager();return new Promise(((i,h)=>{m.readFile({filePath:this.filePath,encoding:"utf8",position:t,success:t=>{var m=t.data;"string"==typeof m?(o.warn(`logStorage::readLogs success ${m.length}`),i(m)):(o.warn("logStorage::readLogs empty"),h(new Error("logStorage::readLogs empty")))},fail:t=>{var i=t.errMsg||t.errorMessage||t.message;o.warn(`logStorage::readLogs failed ${i}`);var m={code:t.errCode||0,message:i};h(m)}})}))}close(){}addLogs(t){var i=getAPIEnv();if(!i)return Promise.resolve();var o=getLogger(),m=t.map((t=>t.text)).concat("").join("\n");try{i.getFileSystemManager().appendFileSync(this.filePath,m,"utf8")}catch(t){var h=t.errMsg||t.errorMessage||t.message;this.lastErrorMsg!==h&&o.warn("logStorage::append failed",t),this.lastErrorMsg=h}return this.count+=1,this.count>this.maxCount&&(this.count=0,this.checkCapacity(this.remainCapacity)),Promise.resolve()}extractLogs(){return __awaiter(this,void 0,void 0,(function*(){var t=getAPIEnv();if(t){var i=getLogger(),o=this.getSize(),m=t.getFileSystemManager();if(o>0){try{m.copyFileSync(this.filePath,this.copyFilePath)}catch(t){return void i.warn("logStorage::copyFileSync failed",t)}return this.copyFilePath}i.warn("logStorage::extractLogs empty")}}))}afterUpload(){return __awaiter(this,void 0,void 0,(function*(){var t=getAPIEnv();if(t){var i=getLogger(),o=t.getFileSystemManager();try{o.unlinkSync(this.copyFilePath)}catch(t){return void i.log("logStorage::delete copyFilePath failed",t)}}}))}}function uploadFileFn(t){var i=getLogger(),o=getAPIEnv(),m=t.headers||{};return t.md5&&(m["Content-MD5"]=t.md5),new Promise(((h,u)=>{var v=o.uploadFile(Object.assign(Object.assign({url:`${t.commonUploadHost}/${t.nosToken.bucket}`},Object.keys(m).length>0?{header:m}:{}),{formData:{Object:decodeURIComponent(t.nosToken.objectName),"x-nos-token":t.nosToken.token,"x-nos-entity-type":"json"},name:"file",fileName:"file",fileType:t.type,filePath:t.filePath,success(i){if(200==i.statusCode){t.onUploadInfo&&t.onUploadInfo({http_code:i.statusCode});var o={};if("string"==typeof i.data)try{o=JSON.parse(i.data)}catch(o){t.onUploadInfo&&t.onUploadInfo({exception:`JSON parse error:${i.data}`}),u({code:i.statusCode,message:i.errMsg,rawData:i.data})}o.name=t.filePath,o.ext=o.name&&o.name.lastIndexOf(".")>-1?o.name.slice(o.name.lastIndexOf(".")+1).toLowerCase():"",h(o)}else t.onUploadInfo&&t.onUploadInfo({http_code:i.statusCode,exception:i.data,rsp_headers:i.header,req_headers:m}),u({code:i.statusCode,message:i.errMsg,rawData:i.data})},fail(i){t.onUploadInfo&&t.onUploadInfo({http_code:0,exception:i,req_headers:m}),9===i.error||21104===i.errNo||"string"==typeof i.errMsg&&i.errMsg.indexOf("abort")>-1?i.code=Ee.V2NIM_ERROR_CODE_CANCELLED:i.code=i.error||i.errNo||i.errno||i.errCode||i.code,i.message=i.errMsg||i.errorMessage,u(i)}}));try{t.onUploadStart&&t.onUploadStart(v)}catch(t){i.error("uploadFile: options.onUploadStart error",t),v.abort(),u(t)}t.onUploadProgress&&v.onProgressUpdate((function(i){var o=i.totalBytesExpectedToWrite||i.totalBytesExpectedToSend,m=i.totalBytesWritten||i.totalBytesSent;t.onUploadProgress&&t.onUploadProgress({total:o,loaded:m,percentage:parseFloat((m/o).toFixed(2)),percentageText:i.progress+"%"})}))}))}function getFileUploadInformationFn(t){return null}var Rt={clear(){my.clearStorageSync()},getItem:t=>my.getStorageSync({key:t}).data,setItem:(t,i)=>my.setStorageSync({key:t,data:i}),removeItem:t=>my.removeStorageSync({key:t})};function requestFn(t,i){return i&&(i.header=i.headers,i.data=i.data||(null==i?void 0:i.params)||{}),new Promise(((o,m)=>{getAPIEnv().request(Object.assign(Object.assign({url:t},i),{success:function(i){var h=(i=i||{}).statusCode||i.status;"number"==typeof h&&h.toString().startsWith("2")?(i={data:i.data,status:h,errMsg:i.errMsg,header:i.header},o(i)):m({code:h||0,message:i.data||`miniapp request fail. url: ${t}`})},fail:function(i){var o=`miniapp request fail. url: ${t}`;i?(1===i.errCode||13===i.error||5===i.errNo||21103===i.errNo||"string"==typeof i.errMsg&&i.errMsg.indexOf("timeout")>-1?i.code=Ee.V2NIM_ERROR_CODE_TIMEOUT:i.code=i.error||i.errNo||i.errno||i.errCode||i.code,i.message=i.errMsg||i.errorMessage||o,m({code:i.code,message:i.message})):m({code:0,message:o})}}))}))}function getSystemInfoFn$4(){var t=getBaseSystemInfo();return Object.assign(Object.assign({},t),{hostEnv:"Ali",hostEnvEnum:102,manufactor:"Ali",model:my.SDKVersion,userAgent:`NIM/Web/AliMiniApp(${my.SDKVersion})/V10.9.70/{{appkey}}`})}class WebSocketFn$1{constructor(t,i=""){if(this.CONNECTING=0,this.OPEN=1,this.CLOSING=2,this.CLOSED=3,this.binaryType="",this.onclose=function(t){getLogger().log("my-app: sockets on close ",t)},this.onerror=function(t){getLogger().error("my-app: sockets error ",t)},this.onmessage=function(t){},this.onopen=function(){},!t)throw new Error("Failed to construct 'socket': url required");this.url=t.replace(/:443(\/|$)/,"$1"),this.protocol=i,this.readyState=this.CONNECTING,this.socketTask=my.connectSocket({url:this.url,multiple:!0,fail:t=>{this.errorHandler(t)},success:()=>{this.readyState=this.OPEN}}),this.socketTask.onOpen((t=>{this.readyState=this.OPEN,this.binaryType?this.onopen():this.onmessage&&this.onmessage({type:"open",header:t})})),this.socketTask.onError((t=>{this.errorHandler(t)})),this.socketTask.onClose((t=>{this.readyState=this.CLOSED;var{code:i,reason:o,wasClean:m}=t;"function"==typeof this.onclose&&this.onclose&&this.onclose({code:i,reason:o,wasClean:m,type:"close"}),this.socketTask=null})),this.socketTask.onMessage((t=>{var i,o=null===(i=t.data)||void 0===i?void 0:i.data,m=o;t.data.isBuffer&&(m=base64ToArrayBuffer(o)),this.onmessage&&this.onmessage({data:m})}))}close(){this.socketTask&&this.socketTask.close({code:1e3,reason:"user force close websocket",complete:()=>{this.socketTask=null}})}send(t){if(this.readyState!==this.OPEN)throw new Error(`my-app: socket sendMsg when readyState=${this.readyState}`);if(!("string"==typeof t||t instanceof ArrayBuffer))throw new TypeError("my-app: socket sendMsg only String/ArrayBuffer supported");this.socketTask&&this.socketTask.send({data:t,isBuffer:t instanceof ArrayBuffer})}errorHandler(t){getLogger().error("my-app::ws: onerror ",t),this.readyState=this.CLOSED,this.onerror&&this.onerror({type:"error",code:null==t?void 0:t.error,message:null==t?void 0:t.errorMessage})}}var getAdapterForAli=()=>({setLogger:setLogger,platform:"ALIAPP",localStorage:Rt,request:requestFn,WebSocket:WebSocketFn$1,uploadFile:uploadFileFn,getSystemInfo:getSystemInfoFn$4,getFileUploadInformation:getFileUploadInformationFn,net:getNetFn(my),powerMonitor:new PowerMonitor(my),logStorage:LogStorageImpl}),bt={clear(){getAPIEnv().clearStorageSync()},getItem:t=>getAPIEnv().getStorageSync(t),setItem:(t,i)=>getAPIEnv().setStorageSync(t,i),removeItem:t=>getAPIEnv().removeStorageSync(t)};function getSystemInfoFn$3(){var t=getBaseSystemInfo(),i=wx.getSystemInfoSync()||{};return Object.assign(Object.assign({},t),{hostEnv:"WeiXin",hostEnvEnum:6,manufactor:"WeiXin",userAgent:`NIM/Web/WeChatMiniApp(${i.SDKVersion})/V10.9.70/{{appkey}}`})}class WebSocketFn{constructor(t,i=""){if(this.CONNECTING=0,this.OPEN=1,this.CLOSING=2,this.CLOSED=3,this.binaryType="",this.onclose=function(t){getLogger().log("miniapp: sockets on close ",t)},this.onerror=function(t){getLogger().error("miniapp: sockets error ",t)},this.onmessage=function(t){},this.onopen=function(){},!t)throw new Error("Failed to construct 'socket': url required");this.url=t.replace(/:443(\/|$)/,"$1"),this.protocol=i,this.readyState=this.CONNECTING;var o=this.protocol?{protocols:[this.protocol]}:{},m=getAPIEnv();this.socketTask=m.connectSocket(Object.assign(Object.assign({url:this.url},o),{fail:t=>{this.errorHandler(t)},success:()=>{}})),this.socketTask.onOpen((t=>{this.readyState=this.OPEN,this.binaryType?this.onopen():this.onmessage&&this.onmessage({type:"open",header:t})})),this.socketTask.onError((t=>{this.errorHandler(t)})),this.socketTask.onClose((t=>{this.readyState=this.CLOSED;var{code:i,reason:o,wasClean:m}=t;"function"==typeof this.onclose&&this.onclose&&this.onclose({code:i,reason:o,wasClean:m,type:"close"})})),this.socketTask.onMessage((t=>{if(this.onmessage&&t)return"string"==typeof t||"byteLength"in t?this.onmessage({data:t}):"string"==typeof t.data||"byteLength"in t.data?this.onmessage({data:t.data}):t.data&&("string"==typeof t.data.data||"byteLength"in t.data.data)?this.onmessage({data:t.data.data}):void this.onmessage(t)}))}close(){this.socketTask.close({code:1e3,reason:"user force close websocket",complete:()=>{this.socketTask=null}})}send(t){if(this.readyState!==this.OPEN)throw new Error(`miniapp: socket sendMsg when readyState=${this.readyState}`);if(!("string"==typeof t||t instanceof ArrayBuffer))throw new TypeError("miniapp: socket sendMsg only String/ArrayBuffer supported");this.socketTask.send({data:t})}errorHandler(t){getLogger().error("miniapp::ws: onerror ",t),this.readyState=this.CLOSED,this.onerror&&this.onerror({type:"error",message:t&&(t.errMsg||t.errorMessage)})}}var getAdapterForWx=()=>({setLogger:setLogger,platform:"WXAPP",localStorage:bt,request:requestFn,WebSocket:WebSocketFn,uploadFile:uploadFileFn,getFileUploadInformation:getFileUploadInformationFn,getSystemInfo:getSystemInfoFn$3,net:getNetFn(wx),powerMonitor:new PowerMonitor(wx),logStorage:LogStorageImpl});function getSystemInfoFn$2(){var t=getBaseSystemInfo(),i=swan.getSystemInfoSync()||{};return Object.assign(Object.assign({},t),{hostEnv:"Baidu",hostEnvEnum:103,manufactor:"Baidu",userAgent:`NIM/Web/BaiduMiniApp(${i.SDKVersion})/V10.9.70/{{appkey}}`})}var getAdapterForBaidu=()=>({setLogger:setLogger,platform:"BAIDUAPP",localStorage:bt,request:requestFn,WebSocket:WebSocketFn,uploadFile:uploadFileFn,getFileUploadInformation:getFileUploadInformationFn,getSystemInfo:getSystemInfoFn$2,net:getNetFn(swan)});function getSystemInfoFn$1(){var t=getBaseSystemInfo(),i=tt.getSystemInfoSync()||{};return Object.assign(Object.assign({},t),{hostEnv:"Tiktok",hostEnvEnum:104,manufactor:"Tiktok",userAgent:`NIM/Web/TiktokMiniApp(${i.SDKVersion})/V10.9.70/{{appkey}}`})}var getAdapterForTt=()=>({setLogger:setLogger,platform:"TTAPP",localStorage:bt,request:requestFn,WebSocket:WebSocketFn,uploadFile:uploadFileFn,getSystemInfo:getSystemInfoFn$1,getFileUploadInformation:getFileUploadInformationFn,net:getNetFn(tt)});function getSystemInfoFn(){var t=getBaseSystemInfo(),i=wx.getSystemInfoSync()||{};return Object.assign(Object.assign({},t),{hostEnv:"QQ",hostEnvEnum:6,manufactor:"QQ",userAgent:`NIM/Web/QQMiniApp(${i.SDKVersion})/V10.9.70/{{appkey}}`})}function getAdapter(){if("undefined"!=typeof qq&&"function"==typeof qq.request)return{setLogger:setLogger,platform:"QQAPP",localStorage:bt,request:requestFn,WebSocket:WebSocketFn,uploadFile:uploadFileFn,getFileUploadInformation:getFileUploadInformationFn,getSystemInfo:getSystemInfoFn,net:getNetFn(qq),powerMonitor:new PowerMonitor(qq)};if("undefined"!=typeof tt&&"function"==typeof tt.request)return getAdapterForTt();if("undefined"!=typeof swan&&"function"==typeof swan.request)return getAdapterForBaidu();if("undefined"!=typeof my&&"function"==typeof my.request)return getAdapterForAli();if("undefined"!=typeof wx&&"function"==typeof wx.request)return getAdapterForWx();throw new Error("No adapter found!")}class V2NIMConversationIdUtilImpl{constructor(t){this.name="V2NIMConversationIdUtil",this.core=t}conversationId(t,i){return`${this.core.account}|${t}|${i}`}p2pConversationId(t){return`${this.core.account}|1|${t}`}teamConversationId(t){return`${this.core.account}|2|${t}`}superTeamConversationId(t){return`${this.core.account}|3|${t}`}messageConversationId(t){return 1===t.conversationType?t.senderId===this.core.account?this.p2pConversationId(t.receiverId):this.p2pConversationId(t.senderId):2===t.conversationType?this.teamConversationId(t.receiverId):this.superTeamConversationId(t.receiverId)}parseConversationType(t){try{if(t&&t.startsWith(`${this.core.account}|`)){var i=t.replace(`${this.core.account}|`,"");return Number(i[0])}return this.core.logger.warn(`conversationId is not start with ${this.core.account}`),0}catch(t){return 0}}parseConversationTargetId(t){try{return t&&t.startsWith(`${this.core.account}|`)?t.replace(`${this.core.account}|`,"").slice(2):(this.core.logger.warn(`conversationId is not start with ${this.core.account}`),"")}catch(t){return""}}convertToV1ConversationId(t){var i=this.parseConversationType(t);return`${1===i?"p2p":2===i?"team":"superTeam"}|${this.parseConversationTargetId(t)}`}}class V2NIMMessageModelImpl{constructor(){this.messages=new Map,this.capacity=1e4}reset(){this.messages.clear()}getMessageById(t){if(t)return this.messages.get(t)}getMessagesByConversationId(t){var i=[];return this.messages.forEach((o=>{o.conversationId===t&&i.push(o)})),i}getLastMessageOfConversation(t){var i=this.getMessagesByConversationId(t);if(0!==i.length)return i.reduce(((t,i)=>i.createTime>t.createTime?i:t),i[0])}upsertMessages(t){t.forEach((t=>{this.setLRU(t.messageClientId,t)}))}setLRU(t,i){if(this.messages.has(t))this.messages.delete(t);else if(this.messages.size>=this.capacity){var o=this.messages.keys().next().value;o&&this.messages.delete(o)}this.messages.set(t,i)}deleteMessage(t){this.messages.delete(t)}deleteMessages(t,i){this.messages.forEach((o=>{t===o.conversationId&&(!i||i&&o.createTime<i)&&this.messages.delete(o.messageClientId)}))}}var Vt={accountId:{type:"string",allowEmpty:!1},content:{type:"object",required:!1,rules:{msg:{type:"string",allowEmpty:!1},type:{type:"number",allowEmpty:!1}}},messages:{type:"array",required:!1,rules:{msg:{type:"string",allowEmpty:!1},type:{type:"number"},role:{type:"enum",values:["assistant","user","system"]}}},promptVariables:{type:"jsonstr",required:!1},modelConfigParams:{type:"object",required:!1,rules:{prompt:{type:"string",required:!1},maxTokens:{type:"number",required:!1},topP:{type:"number",required:!1},temperature:{type:"number",required:!1}}},aiStream:{type:"boolean",required:!1}},kt=Object.assign({requestId:{type:"string",allowEmpty:!1}},Vt),Pt={requestId:{type:"string",allowEmpty:!1},accountId:{type:"string",allowEmpty:!1}},Lt=[1,3,2,0],wt=[2,7,12,100,6,1,-1,4,5,11,0,10,3],Dt={routeEnabled:{type:"boolean",required:!1},routeEnvironment:{type:"string",required:!1}},Ut={pushEnabled:{type:"boolean",required:!1},pushNickEnabled:{type:"boolean",required:!1},pushContent:{type:"string",required:!1},pushPayload:{type:"string",required:!1},forcePush:{type:"boolean",required:!1},forceContent:{type:"string",required:!1},forcePushAccountIds:{type:"array",required:!1,itemType:"string"}},xt={antispamEnabled:{type:"boolean",required:!1},antispamBusinessId:{type:"string",required:!1},antispamCustomMessage:{type:"string",required:!1},antispamCheating:{type:"string",required:!1},antispamExtension:{type:"string",required:!1}},Ft={messageConfig:{type:"object",required:!1,rules:{readReceiptEnabled:{type:"boolean",required:!1},lastMessageUpdateEnabled:{type:"boolean",required:!1},historyEnabled:{type:"boolean",required:!1},roamingEnabled:{type:"boolean",required:!1},onlineSyncEnabled:{type:"boolean",required:!1},offlineEnabled:{type:"boolean",required:!1},unreadEnabled:{type:"boolean",required:!1}}},routeConfig:{type:"object",required:!1,rules:Dt},pushConfig:{type:"object",required:!1,rules:Ut},antiSpamConfig:{type:"object",required:!1,rules:xt},robotConfig:{type:"object",required:!1,rules:{accountId:{type:"string",required:!1},topic:{type:"string",required:!1},function:{type:"string",required:!1},customContent:{type:"string",required:!1}}},aiConfig:{type:"object",required:!1,rules:Vt},targetConfig:{type:"object",required:!1,rules:{receiverIds:{type:"array",itemType:"string"},inclusive:{type:"boolean"},newMemberVisible:{type:"boolean",required:!1}}},clientAntispamEnabled:{type:"boolean",required:!1},clientAntispamReplace:{type:"string",required:!1}},Bt={message:{type:"object",rules:{text:{type:"string",required:!1},messageType:{type:"enum",values:wt},messageClientId:{type:"string",allowEmpty:!1}}},params:{type:"object",rules:Ft,required:!1},replyMessage:{type:"object",rules:{conversationType:{type:"enum",values:[1,3,2,0]},receiverId:{type:"string",allowEmpty:!1},senderId:{type:"string",allowEmpty:!1},messageClientId:{type:"string",allowEmpty:!1},messageServerId:{type:"string",allowEmpty:!1},createTime:{type:"number"}}}},$t={conversationId:{type:"string",allowEmpty:!1},message:{type:"object",rules:{text:{type:"string",required:!1},messageType:{type:"enum",values:wt},messageClientId:{type:"string",allowEmpty:!1},attachment:{type:"object",required:!1,rules:{file:{type:"file",required:!1}}}}},params:{type:"object",required:!1,rules:Ft}},jt={message:{type:"object",rules:{messageClientId:{type:"string",allowEmpty:!1},messageServerId:{type:"string",allowEmpty:!1},conversationType:{type:"enum",values:Lt},createTime:{type:"number"}}},params:{type:"object",rules:{postscript:{type:"string",required:!1},serverExtension:{type:"string",required:!1},pushContent:{type:"string",required:!1},pushPayload:{type:"string",required:!1},env:{type:"string",required:!1}},required:!1}},Gt={conversationId:{type:"string",allowEmpty:!1},messageTypes:{type:"array",required:!1,itemType:"enum",values:wt},beginTime:{type:"number",required:!1},endTime:{type:"number",required:!1},limit:{type:"number",min:1,required:!1},direction:{type:"enum",values:[1,0],required:!1},anchorMessage:{type:"object",required:!1,rules:{messageServerId:{type:"string",allowEmpty:!1},createTime:{type:"number"}}}},qt={conversationType:{type:"enum",values:Lt},receiverId:{type:"string",allowEmpty:!1},senderId:{type:"string",allowEmpty:!1},messageServerId:{type:"string",allowEmpty:!1},messageClientId:{type:"string",allowEmpty:!1}},Ht={messageRefers:{type:"array",required:!0,rules:qt}},zt={conversationId:{type:"string",allowEmpty:!1},conversationType:{type:"enum",values:Lt},receiverId:{type:"string",allowEmpty:!1},senderId:{type:"string",allowEmpty:!1},messageClientId:{type:"string",allowEmpty:!1},createTime:{type:"number"}},Yt={messages:{type:"array",rules:zt}},Jt={conversationId:{type:"string",allowEmpty:!1},serverExtension:{type:"string",required:!1},onlineSync:{type:"boolean",required:!1},deleteRoam:{type:"boolean",required:!1},clearMode:{type:"enum",values:[0,1,2],required:!1}},Kt={serverExtension:{type:"string",required:!1}},Wt={messageClientId:{type:"string",allowEmpty:!1},conversationType:{type:"enum",values:[1]},receiverId:{type:"string",allowEmpty:!1},createTime:{type:"number"}},Xt={messages:{type:"array",rules:{messageClientId:{type:"string",allowEmpty:!1},conversationType:{type:"enum",values:[2]},receiverId:{type:"string",allowEmpty:!1},createTime:{type:"number"}},min:1}},Qt={voiceUrl:{type:"string",required:!1,allowEmpty:!1},file:{type:"file",required:!1},voicePath:{type:"string",required:!1,allowEmpty:!1},mimeType:{type:"string",required:!1,allowEmpty:!1},sampleRate:{type:"string",required:!1,allowEmpty:!1},duration:{type:"number",required:!0,min:0},sceneName:{type:"string",required:!1}},Zt={message:{type:"object",rules:{conversationType:{type:"enum",values:Lt},receiverId:{type:"string",allowEmpty:!1},senderId:{type:"string",allowEmpty:!1},messageServerId:{type:"string",allowEmpty:!1},messageClientId:{type:"string",allowEmpty:!1},createTime:{type:"number"}}},index:{type:"number",min:1},serverExtension:{type:"string",required:!1},pushConfig:{type:"object",required:!1,rules:{pushEnabled:{type:"boolean",required:!1},needBadge:{type:"boolean",required:!1},title:{type:"string",required:!1,allowEmpty:!1},content:{type:"string",required:!1,allowEmpty:!1},pushPayload:{type:"string",required:!1,allowEmpty:!1}}}},ei={messages:{type:"array",rules:{conversationType:{type:"enum",values:[1,3,2,0]},receiverId:{type:"string",allowEmpty:!1},senderId:{type:"string",allowEmpty:!1},messageServerId:{type:"string",allowEmpty:!1},messageClientId:{type:"string",allowEmpty:!1},createTime:{type:"number"}}}},ti={params:{type:"object",rules:{collectionType:{type:"number",min:1},collectionData:{type:"string",allowEmpty:!1},serverExtension:{type:"string",required:!1},uniqueId:{type:"string",required:!1}}}},ii={collections:{type:"array",min:1,rules:{collectionId:{type:"string",allowEmpty:!1},createTime:{type:"number"}}}},ri={serverExtension:{type:"string",required:!1},collection:{type:"object",rules:{collectionId:{type:"string",allowEmpty:!1},collectionType:{type:"number"},createTime:{type:"number"}}}},ni={beginTime:{type:"number",required:!1},endTime:{type:"number",required:!1},limit:{type:"number",min:1,required:!1},direction:{type:"enum",required:!1,values:[1,0]},collectionType:{type:"number",required:!1},anchorCollection:{type:"object",required:!1,rules:{collectionId:{type:"string",allowEmpty:!1,required:!1},createTime:{type:"number",required:!1}}}},oi={keyword:{type:"string",allowEmpty:!1},beginTime:{type:"number",required:!1},endTime:{type:"number",required:!1},sortOrder:{type:"enum",values:[1,0],required:!1},conversationLimit:{type:"number",min:0,required:!1},messageLimit:{type:"number",min:1,required:!1},p2pAccountIds:{type:"array",required:!1,itemType:"string"},teamIds:{type:"array",required:!1,itemType:"string"},senderAccountIds:{type:"array",required:!1,itemType:"string"},messageTypes:{type:"array",required:!1,itemType:"enum",values:wt},messageSubtypes:{type:"array",required:!1,itemType:"number"}},si={conversationId:{type:"string",required:!1,allowEmpty:!1},keywordList:{type:"array",required:!1,itemType:"string"},keywordMatchType:{type:"enum",values:[1,0],required:!1},senderAccountIds:{type:"array",required:!1,itemType:"string"},messageTypes:{type:"array",required:!1,itemType:"enum",values:wt},messageSubtypes:{type:"array",required:!1,itemType:"number"},searchStartTime:{type:"number",required:!1},searchTimePeriod:{type:"number",required:!1},limit:{type:"number",min:1,required:!1},direction:{type:"enum",values:[0,1],required:!1},pageToken:{type:"string",required:!1}},ai={message:{type:"object",rules:{receiverId:{type:"string",allowEmpty:!1},messageServerId:{type:"string",allowEmpty:!1},conversationType:{type:"enum",values:[2]}}}},ci={messages:{type:"array",rules:{receiverId:{type:"string",allowEmpty:!1},messageServerId:{type:"string",allowEmpty:!1},conversationType:{type:"enum",values:[2]}},min:1}},di={sceneName:{type:"string",required:!1},name:{type:"string",required:!1}},li=Object.assign(Object.assign({},di),{duration:{type:"number",required:!1}}),pi=Object.assign(Object.assign({},li),{width:{type:"number",required:!1},height:{type:"number",required:!1}}),mi=Object.assign(Object.assign({},di),{width:{type:"number",required:!1},height:{type:"number",required:!1}}),hi={messageRefer:{type:"object",required:!0,rules:qt},beginTime:{type:"number",required:!1},endTime:{type:"number",required:!1},limit:{type:"number",min:1,required:!1},direction:{type:"enum",values:[1,0],required:!1},excludeMessageServerId:{type:"string",required:!1,allowEmpty:!1}},ui={senderId:{type:"string",allowEmpty:!1},receiverId:{type:"string",allowEmpty:!1},createTime:{type:"number"},messageClientId:{type:"string",allowEmpty:!1},messageServerId:{type:"string",allowEmpty:!1}},gi={subType:{type:"number",min:0,required:!1},text:{type:"string",required:!1},attachment:{type:"object",required:!1},serverExtension:{type:"string",required:!1},routeConfig:{type:"object",required:!1,rules:Dt},pushConfig:{type:"object",required:!1,rules:Ut},antiSpamConfig:{type:"object",required:!1,rules:xt},clientAntispamEnabled:{type:"boolean",required:!1},clientAntispamReplace:{type:"string",required:!1}},vi={messageClientId:{type:"string",allowEmpty:!1},messageServerId:{type:"string",allowEmpty:!1},createTime:{type:"number"},aiConfig:{type:"object",rules:Vt}},fi={operationType:{type:"enum",values:[0,1,2]},updateContent:{type:"string",allowEmpty:!0,required:!1}},Ii={operationType:{type:"enum",values:[2,1],required:!0}};class ReceiptUtil{constructor(t,i){this.receiptDatas={},this.minActionTime=0,this.core=t,this.service=i}reset(){this.receiptDatas={}}checkReceiptDataReliable(t){if(!this.minActionTime)return!0;var i=this.getReceiptData(t);return!!i&&(!!i.actionTime&&i.actionTime>=this.minActionTime)}getReceiptData(t){return this.receiptDatas[t]}setReceiptData(t,i){this.receiptDatas[t]=this.receiptDatas[t]||{},Object.assign(this.receiptDatas[t],i)}sendP2PMessageReceipt(t){return __awaiter(this,void 0,void 0,(function*(){if(validate(Wt,t,"",!0),t.senderId===this.core.account)throw new ValidateErrorV2({detail:{reason:`sendP2PMessageReceipt. sender: ${t.senderId} is not allowed to send msg receipt`}});yield this.core.sendCmd("v2SendP2PMessageReceipt",{tag:{receiverId:t.senderId,messageClientId:t.messageClientId,createTime:t.createTime}})}))}isPeerRead(t){var i;if(1!==t.conversationType)return!1;if(t.senderId!==this.core.account)return!1;if(t.senderId===this.core.account&&t.receiverId===this.core.account)return!0;var o=this.core.V2NIMConversationIdUtil.messageConversationId(t),m=(null===(i=this.getReceiptData(o))||void 0===i?void 0:i.receiptTime)||0;return this.checkReceiptDataReliable(o)||this.getP2pMessageReceiptsFromServer([o]),t.createTime<=m}getP2PMessageReceipt(t){var i;return __awaiter(this,void 0,void 0,(function*(){if(validateConversationId(this.core.account,t),1!==this.core.V2NIMConversationIdUtil.parseConversationType(t))throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"getP2PMessageReceipt: conversationId is not p2p conversationId"}});return this.checkReceiptDataReliable(t)||(yield this.getP2pMessageReceiptsFromServer([t])),{conversationId:t,timestamp:(null===(i=this.getReceiptData(t))||void 0===i?void 0:i.receiptTime)||0}}))}getP2pMessageReceiptsFromServer(t){return __awaiter(this,void 0,void 0,(function*(){if(t.length){var i=yield this.core.sendCmd("v2GetP2PMessageReceipts",{tags:t.map((t=>({type:1,id:this.core.V2NIMConversationIdUtil.parseConversationTargetId(t)})))}),{datas:o}=i.content,m=i.content.actionTime||this.core.timeOrigin.getNTPTime();this.core.eventBus.emit("V2NIMSync/updateTimetag",{p2pMsgReceiptV2:m}),t.forEach((t=>{this.setReceiptData(t,{receiptTime:0,actionTime:m})}));var h=[];o.forEach((t=>{var i,o=this.core.V2NIMConversationIdUtil.p2pConversationId(t.id),u=+t.msgTime||0;u>((null===(i=this.getReceiptData(o))||void 0===i?void 0:i.receiptTime)||0)&&h.push({conversationId:o,timestamp:u}),this.setReceiptData(o,{receiptTime:u,actionTime:m})})),h.length>0&&this.service.emit("onReceiveP2PMessageReadReceipts",h)}}))}getTeamMessageReceipts(t){return __awaiter(this,void 0,void 0,(function*(){if(validate(ci,{messages:t},"",!0),t.some((t=>t.senderId!==this.core.account)))throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"getTeamMessageReceipts: exist messages senderId is not current user"}});if(t.some((i=>i.receiverId!==t[0].receiverId)))throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_MISUSE,detail:{reason:"getTeamMessageReceipts: exist messages receiverId is not same"}});return(yield this.core.sendCmd("v2GetTeamMessageReceipts",{tag:t})).content.data.map((t=>Object.assign(Object.assign({},t),{conversationId:this.core.V2NIMConversationIdUtil.teamConversationId(t.receiverId)})))}))}getTeamMessageReceiptDetail(t){return __awaiter(this,void 0,void 0,(function*(){if(validate(ai,{message:t},"",!0),t.senderId!==this.core.account)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:`getTeamMessageReceiptDetail::senderId ${t.senderId} incorrect`}});var i=yield this.core.sendCmd("v2GetTeamMessageReceiptDetail",{tag:t});return{readReceipt:{conversationId:this.core.V2NIMConversationIdUtil.teamConversationId(t.receiverId),messageClientId:t.messageClientId,messageServerId:t.messageServerId,readCount:i.content.readAccountList.length,unreadCount:i.content.unreadAccountList.length},readAccountList:i.content.readAccountList,unreadAccountList:i.content.unreadAccountList}}))}sendTeamMessageReceipts(t){return __awaiter(this,void 0,void 0,(function*(){if(t.some((i=>i.conversationId!==t[0].conversationId)))throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_MISUSE,detail:{reason:"getTeamMessageReceipts: conversationId not same"}});if(validate(Xt,{messages:t},"",!0),t.some((t=>t.senderId===this.core.account)))throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"getTeamMessageReceipts: exist messages senderId is not current user"}});yield this.core.sendCmd("v2SendTeamMessageReceipts",{tag:t})}))}syncP2PMessagReceiptsHandler(t){var i=t.content.data.map((t=>{var i=this.core.V2NIMConversationIdUtil.p2pConversationId(t.senderId),o=t.createTime;return this.setReceiptData(i,{receiptTime:o}),{conversationId:i,timestamp:o}}));this.service.emit("onReceiveP2PMessageReadReceipts",i)}syncP2pMessagReceiptsV2Handler(t){var{ctx:i,contents:o}=t.content,{minTimetag:m,maxTimetag:h}=i;for(var u in this.minActionTime=m,o.forEach((t=>{var i=this.core.V2NIMConversationIdUtil.p2pConversationId(t.id);this.setReceiptData(i,{receiptTime:t.msgTime})})),this.receiptDatas){var v=this.receiptDatas[u];(!v.actionTime||v.actionTime>=m)&&this.setReceiptData(u,{actionTime:h})}}onP2PMessageReceiptsHandler(t){var{senderId:i,createTime:o,actionTime:m}=t.content.data,h=this.core.V2NIMConversationIdUtil.p2pConversationId(i);this.setReceiptData(h,{receiptTime:o,actionTime:m}),this.core.eventBus.emit("V2NIMSync/updateTimetag",{p2pMsgReceiptV2:m}),this.service.emit("onReceiveP2PMessageReadReceipts",[{conversationId:h,timestamp:o}])}onTeamMessageReceiptsHandler(t){var i=t.content.data.map((t=>({conversationId:this.core.V2NIMConversationIdUtil.teamConversationId(t.receiverId),messageServerId:t.messageServerId,messageClientId:t.messageClientId,readCount:t.readCount,unreadCount:t.unreadCount,latestReadAccount:t.latestReadAccount})));this.service.emit("onReceiveTeamMessageReadReceipts",i)}}var yi={"4_37":"v2TeamJoinActionList","4_38":"v2TeamJoinActionListSync","4_39":"v2TeamJoinActionClearSync","31_1":"v2TeamCreate","32_1":"v2SuperTeamCreate","31_5":"v2TeamInviteMembers","32_5":"v2SuperTeamInviteMembers","31_6":"v2TeamKickMembers","32_6":"v2SuperTeamKickMembers","31_8":"v2TeamLeave","32_7":"v2SuperTeamLeave","31_7":"v2TeamUpdateInfo","32_8":"v2SuperTeamUpdateInfo","31_9":"v2TeamGetInfo","32_9":"v2SuperTeamGetInfo","31_12":"v2TeamDismiss","32_4":"v2SuperTeamDismiss","31_13":"v2TeamApplyToJoin","32_20":"v2SuperTeamApplyToJoin","31_14":"v2TeamAcceptJoinApplication","32_21":"v2SuperTeamAcceptJoinApplication","31_15":"v2TeamRejectJoinApplication","32_22":"v2SuperTeamRejectJoinApplication","31_16":"v2TeamAddManagers","32_26":"v2SuperTeamAddManagers","31_17":"v2TeamRemoveManagers","32_27":"v2SuperTeamRemoveManagers","31_18":"v2TeamTransferOwner","32_31":"v2SuperTeamTransferOwner","31_19":"v2TeamUpdateSelfMemberInfo","32_10":"v2SuperTeamUpdateSelfMemberInfo","31_20":"v2TeamUpdateMember","32_30":"v2SuperTeamUpdateMember","31_21":"v2TeamAcceptInvitation","32_23":"v2SuperTeamAcceptInvitation","31_22":"v2TeamRejectInvite","32_24":"v2SuperTeamRejectInvite","31_33":"v2TeamGetMemberInvitor","32_35":"v2SuperTeamGetMemberInvitor","31_25":"v2TeamMemberSetChatBannedStatus","32_29":"v2SuperTeamMemberSetChatBannedStatus","31_32":"v2TeamSetChatBannedMode","32_28":"v2SuperTeamSetChatBannedMode","31_34":"v2TeamGetByIds","32_36":"v2SuperTeamGetByIds","31_35":"v2TeamMemberGetListByIds","32_37":"v2SuperTeamMemberGetListByIds","31_36":"v2TeamMemberGetList","31_39":"v2TeamJoinActionDelete","31_40":"v2TeamJoinActionClear","8_41":"v2TeamJoinActionDeleteMultiSync","8_42":"v2TeamJoinActionClearMultiSync","8_101":"v2TeamCreateMultiSync","8_109":"v2TeamSync","8_119":"v2TeamMemberUpdateMultiSync","8_126":"v2TeamMembersOfSelfInSync","21_101":"v2SuperTeamCreateMultiSync","21_109":"v2SuperTeamSync","21_110":"v2SuperTeamMemberUpdateMultiSync","21_111":"v2SuperTeamMembersOfSelfInSync"},_i={antispamBusinessId:1},Mi="V2NIMTeamService",Ei={teamId:1,name:3,teamType:{id:4,retConverter:t=>0==+t?1:+t},ownerAccountId:5,memberLimit:{id:6,retType:"number"},isTeamEffective:{id:8,converter:boolToInt,retType:"boolean"},memberCount:{id:9,retType:"number"},memberUpdateTime:{id:10,retType:"number"},createTime:{id:11,retType:"number"},updateTime:{id:12,retType:"number"},isValidTeam:{id:13,retDef:!0,retConverter:(t,i)=>1==+i[8]&&1==+t},intro:14,announcement:15,joinMode:{id:16,retType:"number"},serverExtension:18,customerExtension:19,avatar:20,agreeMode:{id:21,retType:"number"},inviteMode:{id:22,retType:"number"},updateInfoMode:{id:23,retType:"number"},updateExtensionMode:{id:24,retType:"number"},chatBannedMode:{id:101,retType:"number"}},Si={teamId:1,accountId:3,memberRole:{id:4,retType:"number"},teamNick:5,bits:{id:7,retType:"number"},inTeam:{id:9,retType:"boolean"},joinTime:{id:10,retType:"number"},updateTime:{id:11,retType:"number"},serverExtension:12,chatBanned:{id:13,retType:"boolean"},invitorAccountId:14,followAccountIds:{id:16,retConverter:t=>{try{return JSON.parse(t)}catch(t){return[]}}}},Ti={teamId:1,accountId:3,memberRole:{id:4,retType:"number"},teamNick:5,bits:{id:7,retType:"number"},inTeam:{id:9,retType:"boolean"},updateTime:{id:11,retType:"number"},serverExtension:12,chatBanned:{id:13,retType:"boolean"},invitorAccountId:14,joinTime:{id:15,retType:"number"},followAccountIds:{id:17,retConverter:t=>{try{return JSON.parse(t)}catch(t){return[]}}}},Ci={accountIds:{id:1,converter:t=>JSON.stringify(t)},operation:2},Ni={fromAccountId:1,targetAccountId:2,operatorAccountId:3,status:{id:4,retType:"number"},timestamp:{id:5,retType:"number"},updateTimestamp:{id:6,retType:"number"},postscriptHistory:{id:7,retConverter:t=>{if(t&&"string"==typeof t)try{return JSON.parse(t).map((t=>({fromAccount:t.accid,time:t.time,content:t.msg})))}catch(t){return}}},serverId:8,teamId:9,teamType:{id:10,retType:"number"},finished:{id:11,retType:"boolean"},serverExtension:12},Ai={serverId:1,teamType:{id:2,retType:"number"},teamId:3,serverTime:{id:4,retType:"number"}},Oi={timestamp:{id:1,retType:"number"},type:{id:2,retType:"number"},serverTime:{id:3,retType:"number"}},Ri={teamId:1,teamType:2,roleQueryType:3,onlyChatBanned:{id:4,converter:t=>+t},nextToken:5,limit:6,direction:7},bi={v2TeamCreate:{sid:31,cid:1,service:Mi,params:[{type:"Property",name:"team",reflectMapper:Ei},{type:"StrArray",name:"inviteeAccountIds"},{type:"String",name:"postscript"},{type:"Property",name:"antispamConfig",reflectMapper:_i}],response:[{type:"Property",name:"team",reflectMapper:invertSerializeItem(Ei)},{type:"StrArray",name:"failedList"}]},v2SuperTeamCreate:{sid:32,cid:1,service:Mi,params:[{type:"Property",name:"team",reflectMapper:Ei},{type:"StrArray",name:"inviteeAccountIds"},{type:"String",name:"postscript"},{type:"Property",name:"antispamConfig",reflectMapper:_i}],response:[{type:"Property",name:"team",reflectMapper:invertSerializeItem(Ei)},{type:"StrArray",name:"failedList"}]},v2TeamInviteMembers:{sid:31,cid:5,service:Mi,params:[{type:"Long",name:"teamId"},{type:"StrArray",name:"accounts"},{type:"String",name:"ps"},{type:"String",name:"attach"}],response:[{type:"Long",name:"time"},{type:"StrArray",name:"abortedAccidList"}]},v2SuperTeamInviteMembers:{sid:32,cid:5,service:Mi,params:[{type:"Long",name:"teamId"},{type:"StrArray",name:"accounts"},{type:"String",name:"ps"},{type:"String",name:"attach"}],response:[{type:"StrArray",name:"abortedAccidList"},{type:"Long",name:"time"}]},v2TeamUpdateInfo:{sid:31,cid:7,service:Mi,params:[{type:"Property",name:"team",reflectMapper:Ei},{type:"Property",name:"antispamConfig",reflectMapper:_i}],response:[{type:"Long",name:"teamId"},{type:"Long",name:"timestamp"}]},v2SuperTeamUpdateInfo:{sid:32,cid:8,service:Mi,params:[{type:"Property",name:"team",reflectMapper:Ei},{type:"Property",name:"antispamConfig",reflectMapper:_i}],response:[{type:"Long",name:"timestamp"}]},v2TeamLeave:{sid:31,cid:8,service:Mi,params:[{type:"Long",name:"teamId"}]},v2SuperTeamLeave:{sid:32,cid:7,service:Mi,params:[{type:"Long",name:"teamId"}]},v2TeamGetInfo:{sid:31,cid:9,service:Mi,params:[{type:"Long",name:"teamId"}],response:[{type:"Property",name:"team",reflectMapper:invertSerializeItem(Ei)}]},v2SuperTeamGetInfo:{sid:32,cid:9,service:Mi,params:[{type:"Long",name:"teamId"}],response:[{type:"Property",name:"team",reflectMapper:invertSerializeItem(Ei)}]},v2TeamGetByIds:{sid:31,cid:34,service:Mi,params:[{type:"LongArray",name:"teamIds"}],response:[{type:"PropertyArray",name:"teams",reflectMapper:invertSerializeItem(Ei)},{type:"LongArray",name:"tids"}]},v2SuperTeamGetByIds:{sid:32,cid:36,service:Mi,params:[{type:"LongArray",name:"teamIds"}],response:[{type:"PropertyArray",name:"teams",reflectMapper:invertSerializeItem(Ei)},{type:"LongArray",name:"tids"}]},v2TeamDismiss:{sid:31,cid:12,service:Mi,params:[{type:"Long",name:"teamId"}]},v2SuperTeamDismiss:{sid:32,cid:4,service:Mi,params:[{type:"Long",name:"teamId"}]},v2TeamAcceptInvitation:{sid:31,cid:21,service:Mi,params:[{type:"Long",name:"teamId"},{type:"String",name:"from"}],response:[{type:"Property",name:"team",reflectMapper:invertSerializeItem(Ei)}]},v2SuperTeamAcceptInvitation:{sid:32,cid:23,service:Mi,params:[{type:"Long",name:"teamId"},{type:"String",name:"from"}],response:[{type:"Property",name:"team",reflectMapper:invertSerializeItem(Ei)}]},v2TeamRejectInvite:{sid:31,cid:22,service:Mi,params:[{type:"Long",name:"teamId"},{type:"String",name:"from"},{type:"String",name:"ps"}]},v2SuperTeamRejectInvite:{sid:32,cid:24,service:Mi,params:[{type:"Long",name:"teamId"},{type:"String",name:"from"},{type:"String",name:"ps"}]},v2TeamKickMembers:{sid:31,cid:6,service:Mi,params:[{type:"Long",name:"teamId"},{type:"StrArray",name:"accounts"}]},v2SuperTeamKickMembers:{sid:32,cid:6,service:Mi,params:[{type:"Long",name:"teamId"},{type:"StrArray",name:"accounts"}]},v2TeamApplyToJoin:{sid:31,cid:13,service:Mi,params:[{type:"Long",name:"teamId"},{type:"String",name:"ps"}],response:[{type:"Property",name:"team",reflectMapper:invertSerializeItem(Ei)},{type:"Int",name:"isInTeam"}]},v2SuperTeamApplyToJoin:{sid:32,cid:20,service:Mi,params:[{type:"Long",name:"teamId"},{type:"String",name:"ps"}],response:[{type:"Property",name:"team",reflectMapper:invertSerializeItem(Ei)},{type:"Int",name:"isInTeam"}]},v2TeamAcceptJoinApplication:{sid:31,cid:14,service:Mi,params:[{type:"Long",name:"teamId"},{type:"String",name:"from"}]},v2SuperTeamAcceptJoinApplication:{sid:32,cid:21,service:Mi,params:[{type:"Long",name:"teamId"},{type:"String",name:"from"}]},v2TeamRejectJoinApplication:{sid:31,cid:15,service:Mi,params:[{type:"Long",name:"teamId"},{type:"String",name:"from"},{type:"String",name:"ps"}]},v2SuperTeamRejectJoinApplication:{sid:32,cid:22,service:Mi,params:[{type:"Long",name:"teamId"},{type:"String",name:"from"},{type:"String",name:"ps"}]},v2TeamAddManagers:{sid:31,cid:16,service:Mi,params:[{type:"Long",name:"teamId"},{type:"StrArray",name:"accounts"}]},v2SuperTeamAddManagers:{sid:32,cid:26,service:Mi,params:[{type:"Long",name:"teamId"},{type:"StrArray",name:"accounts"}]},v2TeamRemoveManagers:{sid:31,cid:17,service:Mi,params:[{type:"Long",name:"teamId"},{type:"StrArray",name:"accounts"}]},v2SuperTeamRemoveManagers:{sid:32,cid:27,service:Mi,params:[{type:"Long",name:"teamId"},{type:"StrArray",name:"accounts"}]},v2TeamTransferOwner:{sid:31,cid:18,service:Mi,params:[{type:"Long",name:"teamId"},{type:"String",name:"account"},{type:"Bool",name:"leave"}]},v2SuperTeamTransferOwner:{sid:32,cid:31,service:Mi,params:[{type:"Long",name:"teamId"},{type:"String",name:"account"},{type:"Bool",name:"leave"}]},v2TeamUpdateSelfMemberInfo:{sid:31,cid:19,service:Mi,params:[{type:"Property",name:"teamMember",reflectMapper:Si},{type:"Property",name:"specialFollowUpdate",reflectMapper:Ci},{type:"Property",name:"antispam",reflectMapper:_i}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Si)}]},v2SuperTeamUpdateSelfMemberInfo:{sid:32,cid:10,service:Mi,params:[{type:"Property",name:"teamMember",reflectMapper:Ti},{type:"Property",name:"specialFollowUpdate",reflectMapper:Ci},{type:"Property",name:"antispam",reflectMapper:_i}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Ti)}]},v2TeamUpdateMember:{sid:31,cid:20,service:Mi,params:[{type:"Property",name:"teamMember",reflectMapper:Si},{type:"Property",name:"antispam",reflectMapper:_i}]},v2SuperTeamUpdateMember:{sid:32,cid:30,service:Mi,params:[{type:"Property",name:"teamMember",reflectMapper:Ti},{type:"Property",name:"antispam",reflectMapper:_i}]},v2TeamGetMemberInvitor:{sid:31,cid:33,service:Mi,params:[{type:"Long",name:"teamId"},{type:"StrArray",name:"accounts"}],response:[{type:"StrStrMap",name:"accountsMap"}]},v2SuperTeamGetMemberInvitor:{sid:32,cid:35,service:Mi,params:[{type:"Long",name:"teamId"},{type:"StrArray",name:"accounts"}],response:[{type:"StrStrMap",name:"accountsMap"}]},v2TeamMemberSetChatBannedStatus:{sid:31,cid:25,service:Mi,params:[{type:"Long",name:"teamId"},{type:"String",name:"accountId"},{type:"Int",name:"chatBanned"}]},v2SuperTeamMemberSetChatBannedStatus:{sid:32,cid:29,service:Mi,params:[{type:"Long",name:"teamId"},{type:"StrArray",name:"accountId"},{type:"Int",name:"chatBanned"}]},v2TeamSetChatBannedMode:{sid:31,cid:32,service:Mi,params:[{type:"Long",name:"teamId"},{type:"Int",name:"chatBannedMode"}]},v2SuperTeamSetChatBannedMode:{sid:32,cid:28,service:Mi,params:[{type:"Long",name:"teamId"},{type:"Int",name:"chatBannedMode"}]},v2TeamMemberGetListByIds:{sid:31,cid:35,service:Mi,params:[{type:"StrArray",name:"tag"}],response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(Si)}]},v2SuperTeamMemberGetListByIds:{sid:32,cid:37,service:Mi,params:[{type:"StrArray",name:"tag"}],response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(Ti)}]},v2TeamMemberGetList:{sid:31,cid:36,service:Mi,params:[{type:"Property",name:"tag",reflectMapper:Ri}],response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(Si)},{type:"Property",name:"pageInfo",reflectMapper:{1:"hasMore",2:"nextToken"}}]},v2TeamSync:{sid:8,cid:109,service:Mi,response:[{type:"Long",name:"timetag"},{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(Ei)}]},v2TeamCreateMultiSync:{sid:8,cid:101,service:Mi,response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Ei)}]},v2TeamMemberUpdateMultiSync:{sid:8,cid:119,service:Mi,response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Si)}]},v2TeamMembersOfSelfInSync:{sid:8,cid:126,service:Mi,response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(Si)},{type:"Long",name:"timetag"}]},v2SuperTeamSync:{sid:21,cid:109,service:Mi,response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(Object.assign(Object.assign({},Ei),{teamType:{id:4,retConverter:()=>2}}))},{type:"Bool",name:"isAll"},{type:"Long",name:"timetag"}]},v2SuperTeamCreateMultiSync:{sid:21,cid:101,service:Mi,response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Object.assign(Object.assign({},Ei),{teamType:{id:4,retConverter:()=>2}}))}]},v2SuperTeamMemberUpdateMultiSync:{sid:21,cid:110,service:Mi,response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Ti)}]},v2SuperTeamMembersOfSelfInSync:{sid:21,cid:111,service:Mi,response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(Ti)},{type:"Long",name:"timetag"}]},v2TeamJoinActionDelete:{sid:31,cid:39,service:Mi,params:[{type:"Property",name:"tag",reflectMapper:Ai}],response:[{type:"Long",name:"serverTime"}]},v2TeamJoinActionClear:{sid:31,cid:40,service:Mi,params:[{type:"Property",name:"tag",reflectMapper:Oi}],response:[{type:"Long",name:"serverTime"}]},v2TeamJoinActionDeleteMultiSync:{sid:8,cid:41,service:Mi,response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Ai)}]},v2TeamJoinActionClearMultiSync:{sid:8,cid:42,service:Mi,response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Oi)}]},v2TeamJoinActionList:{sid:4,cid:37,service:Mi,response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(Ni)},{type:"Long",name:"serverTime"}]},v2TeamJoinActionListSync:{sid:4,cid:38,service:Mi,response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(Ni)},{type:"Long",name:"serverTime"}]},v2TeamJoinActionClearSync:{sid:4,cid:39,service:Mi,response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(Ni)},{type:"PropertyArray",name:"clearInfos",reflectMapper:invertSerializeItem(Oi)},{type:"Long",name:"serverTime"}]}};function formatTeamNotificationAttachData(t,i){if(!t)return{};var o=t;return o.tinfo&&(o.tinfo=function formatTeamFromTinfo(t){return deserialize(t,invertSerializeItem(Ei))}(o.tinfo),o.tinfo.teamType=i),o.uinfos,void 0!==o.mute&&(o.mute=parseInt(o.mute)),o}function generateTeamByTeamId(t,i,o={}){return Object.assign({teamId:t,teamType:i,name:"",ownerAccountId:"",memberLimit:0,memberCount:0,createTime:0,updateTime:0,intro:"",announcement:"",avatar:"",joinMode:0,agreeMode:0,inviteMode:0,updateInfoMode:0,updateExtensionMode:0,chatBannedMode:0,isValidTeam:!0,isTeamEffective:!0},o)}function generateMemberByTeamId(t,i,o,m={}){return Object.assign({teamId:t,teamType:i,accountId:o,joinTime:0,inTeam:!0,memberRole:0,chatBanned:!1},m)}function processTeamMembers(t,i=1){return t.map((t=>function processTeamMember(t,i=1){return t.teamType=i,t.chatBanned=void 0!==t.chatBanned&&t.chatBanned,t}(t,i)))}function completeMessage(t,i,o){var m,h=Object.assign(Object.assign({},i),{conversationId:t.V2NIMConversationIdUtil.messageConversationId(i),isSelf:i.senderId===t.account,sendingState:1,messageStatus:{errorCode:(null===(m=null==i?void 0:i.messageStatus)||void 0===m?void 0:m.errorCode)||200},messageSource:o||0});if(h.threadReply&&(h.threadReply=Object.assign(Object.assign({},h.threadReply),{conversationType:h.conversationType,conversationId:h.conversationId})),h.threadRoot&&(h.threadRoot=Object.assign(Object.assign({},h.threadRoot),{conversationType:h.conversationType,conversationId:h.conversationId})),h.isInBlackList&&(h.sendingState=2,h.messageStatus.errorCode=Ee.V2NIM_ERROR_CODE_ACCOUNT_IN_BLOCK_LIST,delete h.isInBlackList),h.streamConfig){var u=get(h.streamConfig,"isStream");if(!1===u)delete h.streamConfig;else if(!0===u&&void 0===h.streamConfig.status)delete h.streamConfig,i.aiConfig&&(i.aiConfig.aiStream=!0,i.aiConfig.aiStreamStatus=0);else if("number"==typeof h.streamConfig.status)return h.streamConfig={status:h.streamConfig.status},function completeMessageStreamConfig(t){t.streamConfig&&t.aiConfig&&(t.aiConfig.aiStream=!0,t.aiConfig.aiStreamStatus=t.streamConfig.status,t.aiConfig.aiRAGs&&(t.streamConfig.rags=t.aiConfig.aiRAGs));if(t.attachment&&t.streamConfig){var i=t.attachment;t.streamConfig.lastChunk={content:i.msg,messageTime:t.createTime,chunkTime:i.timestamp,type:i.type,index:i.index},t.aiConfig&&(t.aiConfig.aiStreamLastChunk=t.streamConfig.lastChunk),delete t.attachment}t.aiConfig&&void 0===t.aiConfig.accountId&&delete t.aiConfig;return t}(h)}return h.aiConfig&&void 0===h.aiConfig.accountId&&delete h.aiConfig,formatMessageAttachment(h,t)}function formatMessageAttachment(t,i){return 5===t.messageType?function formatNotificationMessage(t,i){var o,m,h,u,v,I=i.attachment||{};if(i.attachment&&"type"in i.attachment)return i;var _=void 0;if(null===(o=I.data)||void 0===o?void 0:o.tinfo){var{id:M,data:E}=I,S=M>400?2:1,{tinfo:T}=formatTeamNotificationAttachData(Object.assign({},E),S);_={},_=__rest(T,["teamId"])}var C=Object.assign(Object.assign(Object.assign(Object.assign({raw:I.raw,type:convertNotificationType(t,I.id)},_?{updatedTeamInfo:_}:{}),{targetIds:(null===(m=I.data)||void 0===m?void 0:m.ids)||((null===(h=I.data)||void 0===h?void 0:h.id)?[I.data.id]:[])}),"string"==typeof(null===(u=I.data)||void 0===u?void 0:u.attach)?{serverExtension:I.data.attach}:{}),"number"==typeof(null===(v=I.data)||void 0===v?void 0:v.mute)?{chatBanned:0!==I.data.mute}:{});return Object.assign(Object.assign({},i),{attachment:C})}(i,t):100===t.messageType?function formatCustomMessage(t,i){var o,m,h;if("string"==typeof(null===(o=i.attachment)||void 0===o?void 0:o.raw)&&(null===(h=null===(m=t.V2NIMMessageService)||void 0===m?void 0:m.customAttachmentParsers)||void 0===h?void 0:h.length)>0){var u=i.subType||0,v=t.V2NIMMessageService.customAttachmentParsers,I=i.attachment.raw;v.some((o=>{try{var m=o(u,I);if(isPlainObject(m))return m.raw=I,i.attachment=m,!0}catch(i){return t.logger.warn(`customAttachmentParser: subType ${u}, raw: ${I}. parse error with ${i}`),!1}return!1}))}return i}(i,t):t}function completeMessageRefer(t,i){return Object.assign(Object.assign({},i),{conversationId:t.V2NIMConversationIdUtil.messageConversationId(i)})}function formatMessageRefer(t,i){var{createTime:o,senderId:m,receiverId:h,conversationType:u}=i;return{conversationType:u,conversationId:t.V2NIMConversationIdUtil.messageConversationId({conversationType:u,senderId:m,receiverId:h}),senderId:i.senderId,receiverId:i.receiverId,messageServerId:i.messageServerId,createTime:o,messageClientId:i.messageClientId}}function formatRevokeMessage(t,i){var o={7:1,8:2,12:3,13:1,14:2}[i.sysMsgType];return{postscript:i.postscript,revokeType:{7:1,8:2,12:3,13:4,14:5}[i.sysMsgType]||0,revokeAccountId:i.opeAccount||i.senderId,callbackExtension:i.callbackExtension,serverExtension:i.attach||"",messageRefer:{conversationType:o,conversationId:t.V2NIMConversationIdUtil.messageConversationId(Object.assign(Object.assign({},i),{conversationType:o,senderId:i.senderId,receiverId:i.receiverId})),senderId:i.senderId,receiverId:i.receiverId,messageServerId:i.messageServerId,createTime:i.deleteMsgCreatetime,messageClientId:i.messageClientId}}}function formatClearHistoryNotification(t,i){return{conversationId:1===i.conversationType?t.V2NIMConversationIdUtil.p2pConversationId(i.receiverId):2===i.conversationType?t.V2NIMConversationIdUtil.teamConversationId(i.teamId):t.V2NIMConversationIdUtil.superTeamConversationId(i.teamId),deleteTime:i.deleteTime,serverExtension:i.serverExtension}}function convertNotificationType(t,i){var o={0:0,401:401,1:1,402:402,2:2,403:403,3:3,404:404,4:4,405:405,5:5,410:410,6:6,406:406,7:7,407:407,8:8,408:408,9:9,411:411,10:10,409:409};return void 0===o[i]&&t.logger.warn(`[V2NIMMessageService] undefined notification type: ${i}`),"number"==typeof o[i]?o[i]:-1}function formatSearchCloudMessageListEx(t,i){var o=[],m={};for(var h in i.forEach((t=>{var i=t.conversationId;m[i]||(m[i]={conversationId:i,messages:[],count:0}),m[i].messages.push(t),m[i].count++})),m){var u=m[h];o.push(u)}return o}function attachmentToRaw(t,i){if(!i)return"";switch(t){case 100:return i.raw||"";case 1:case 3:case 2:case 6:return function mediaAttachmentToRaw(t){var i=t,{width:o,height:m,duration:h,path:u,file:v,raw:I,ctx:_,payload:M,bucketName:E,objectName:S,token:T,ext:C}=i,N=__rest(i,["width","height","duration","path","file","raw","ctx","payload","bucketName","objectName","token","ext"]),A="string"==typeof C&&"."===C[0]?C.slice(1):C;return JSON.stringify(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},N),void 0===C?{}:{ext:A}),void 0===o?{}:{w:o}),void 0===m?{}:{h:m}),void 0===h?{}:{dur:h}))}(i);case 4:return function locationAttachmentToRaw(t){return JSON.stringify({lat:t.latitude,lng:t.longitude,title:t.address})}(i);case 12:return function callAttachmentToRaw(t){var i=__rest(t,["raw"]);try{return JSON.stringify(Object.assign(Object.assign({},i),{durations:t.durations.map((t=>({accid:t.accountId,duration:t.duration})))}))}catch(i){return JSON.stringify(t)}}(i);default:return i.raw||JSON.stringify(i)}}function rawToAttachment(t,i){var o;try{switch(o=JSON.parse(t),i){case 100:return{raw:t};case 4:return function locationRawToAttachment(t,i){return{latitude:i.lat,longitude:i.lng,address:i.title,raw:t}}(t,o);case 2:case 3:case 1:case 6:return function mediaRawToAttachment(t,i){var{w:o,h:m,dur:h,ext:u}=i,v=__rest(i,["w","h","dur","ext"]),I="string"==typeof u&&"."!==u[0]?`.${u}`:u;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},v),void 0===u?{}:{ext:I}),void 0===o?{}:{width:o}),void 0===m?{}:{height:m}),void 0===h?{}:{duration:h}),{raw:t})}(t,o);case 12:return function callRawToAttachment(t,i){return Object.assign(Object.assign({},i),{durations:i.durations.map((t=>({accountId:t.accid,duration:t.duration}))),raw:t})}(t,o);default:return"object"==typeof o&&o?Object.assign(Object.assign({},o),{raw:t}):{raw:t}}}catch(i){return"object"==typeof o&&o?Object.assign(Object.assign({},o),{raw:t}):{raw:t}}}class FileUtil{constructor(t){this.core=t}doSendFile(t,i){return __awaiter(this,void 0,void 0,(function*(){var o=t.attachment;try{var[m,h]=yield this.core.V2NIMStorageService._uploadFile({taskId:t.messageClientId,uploadParams:{fileObj:(null==o?void 0:o.file)||(null==o?void 0:o.path),sceneName:null==o?void 0:o.sceneName}},i,{fileType:t.messageType}),u=Object.assign(Object.assign({},o),{uploadState:1});void 0!==h.w&&(u.width=u.width||h.w),void 0!==h.h&&(u.height=u.height||h.h),void 0!==h.dur&&(u.duration=u.duration||h.dur),u.ext=u.ext&&-1===u.ext.indexOf(".")?`.${u.ext}`:u.ext;var v=["w","h","dur","ext","name"];for(var I in h)v.includes(I)||(u[I]=h[I]);var{raw:_,file:M,path:E}=u,S=__rest(u,["raw","file","path"]);t.attachment=JSON.parse(JSON.stringify(S)),t.attachment&&(t.attachment.raw=attachmentToRaw(t.messageType,t.attachment))}catch(i){throw t.attachment&&(t.attachment.uploadState=2),i}}))}cancelMessageAttachmentUpload(t){return __awaiter(this,void 0,void 0,(function*(){if(validate({messageClientId:{type:"string",allowEmpty:!1}},t,"",!0),![2,6,1,3].includes(t.messageType))throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_MISUSE,detail:{reason:`cancelMessageAttachmentUpload: messageType ${t.messageType} incorrect`}});if(2===t.sendingState||1===t.sendingState)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_RESOURCE_NOT_EXIST,detail:{reason:"cancelMessageAttachmentUpload: message is already failed or succeeded"}});yield this.core.V2NIMStorageService._cancelUploadFile(t.messageClientId)}))}}var Vi="V2NIMMessageService",ki={"30_1":"v2SendP2pMessage","31_2":"v2SendTeamMessage","30_31":"v2MessageP2pModify","31_37":"v2MessageTeamModify","32_38":"v2MessageSuperTeamModify","7_33":"v2MessageOnModified","4_27":"v2MessageSyncModified","4_28":"v2MessageSuperTeamSyncModified","4_5":"v2BatchMarkRead","4_12":"syncP2PMessagReceipts","4_32":"syncP2pMessagReceiptsV2","30_11":"v2SendP2PMessageReceipt","31_28":"v2SendTeamMessageReceipts","32_2":"v2SendSuperTeamMessage","7_12":"onP2PMessageReceipts","8_31":"onTeamMessageReceipts","31_29":"v2GetTeamMessageReceipts","31_30":"v2GetTeamMessageReceiptDetail","30_35":"v2GetP2PMessageReceipts","7_2":"onMsg","8_3":"onMsg","7_101":"onMsg","8_102":"onMsg","21_3":"onMsg","21_102":"onMsg","4_4":"syncOfflineMsgs","4_9":"syncRoamingMsgs","4_17":"syncRoamingMsgs","30_13":"v2RevokeMessage","32_17":"v2RevokeSuperTeamMessage","7_14":"onRevokeMessage","7_15":"syncRevokeMessage","21_18":"onRevokeMessage","21_117":"onRevokeMessage","30_23":"v2DeleteMessage","30_24":"v2DeleteMessages","4_21":"syncOnDeleteMessages","7_123":"onDeleteMessage","7_124":"onDeleteMessages","29_17":"v2DownloadLocalAntiSpamVocabs"};var Pi={conversationType:{id:0,converter:conversationTypeV2ToV1,retConverter:conversationTypeV1ToV2},receiverId:1,senderId:2,fromClientType:{id:4,retType:"number"},fromDeviceId:5,fromNick:6,createTime:{id:7,retType:"number"},messageType:{id:8,retType:"number"},text:9,attachment:{id:10,converter:(t,i)=>attachmentToRaw(i.messageType,t),retConverter:(t,i)=>rawToAttachment(t,Number(i[8]))},messageClientId:11,messageServerId:12,resend:{id:13,converter:boolToInt,retType:"boolean"},userUpdateTime:{id:14,retType:"number"},serverExtension:15,pushPayload:{id:16,access:"pushConfig.pushPayload"},pushContent:{id:17,access:"pushConfig.pushContent"},forcePushAccountIds:{id:18,access:"pushConfig.forcePushAccountIds",def:t=>{if(t["pushConfig.forcePush"])return"#%@all@%#"},converter:(t,i)=>{if(i["pushConfig.forcePush"])return t?JSON.stringify(t):"#%@all@%#"},retConverter(t){if("#%@all@%#"!==t&&t)try{return JSON.parse(t)}catch(t){return[]}}},forcePushContent:{id:19,access:"pushConfig.forcePushContent"},forcePush:{id:20,access:"pushConfig.forcePush",converter:boolToInt,retType:"boolean"},antispamCustomMessageEnabled:{id:21,def:t=>get(t,"antispamConfig.antispamCustomMessage")?1:void 0,retConverter:()=>{}},antispamCustomMessage:{id:22,access:"antispamConfig.antispamCustomMessage"},antispamBusinessId:{id:23,access:"antispamConfig.antispamBusinessId"},clientAntispamHit:{id:24,access:"clientAntispamHit",converter:boolToInt,retType:"boolean"},antispamEnabled:{id:25,access:"antispamConfig.antispamEnabled",converter:boolToInt,retType:"boolean"},needAck:{id:26,access:"messageConfig.readReceiptEnabled",converter:boolToInt,retType:"boolean"},lastMessageUpdateEnabled:{id:28,access:"messageConfig.lastMessageUpdateEnabled",converter:boolToInt,retType:"boolean"},threadReplySenderId:{id:29,access:"threadReply.senderId"},threadReplyReceiverId:{id:30,access:"threadReply.receiverId"},threadReplyTime:{id:31,access:"threadReply.createTime",retType:"number"},threadReplyServerId:{id:32,access:"threadReply.messageServerId"},threadReplyClientId:{id:33,access:"threadReply.messageClientId"},threadRootSenderId:{id:34,access:"threadRoot.senderId"},threadRootReceiverId:{id:35,access:"threadRoot.receiverId"},threadRootTime:{id:36,access:"threadRoot.createTime",retType:"number"},threadRootServerId:{id:37,access:"threadRoot.messageServerId"},threadRootClientId:{id:38,access:"threadRoot.messageClientId"},isDeleted:{id:39,converter:boolToInt,retType:"boolean"},callbackExtension:40,subType:{id:41,retType:"number"},antispamCheating:{id:42,access:"antispamConfig.antispamCheating"},routeEnvironment:{id:43,access:"routeConfig.routeEnvironment"},antispamExtension:{id:44,access:"antispamConfig.antispamExtension"},antispamResult:45,__clientExt:{id:46,converter:objectToJSONString,retConverter:stringToJSONObject},robotFunction:{id:47,access:"robotConfig.function"},robotTopic:{id:48,access:"robotConfig.topic"},robotCustomContent:{id:49,access:"robotConfig.customContent"},robotAccount:{id:50,access:"robotConfig.accountId"},_conversationOnlineSyncNotify:{id:51},_conversationOnlineSyncData:{id:52},aiAgentMsgDirection:{id:55,access:"aiConfig.aiStatus",retAccess:"aiConfig.aiStatus",retType:"number"},aiAgentAccount:{id:56,access:"aiConfig.accountId",retAccess:"aiConfig.accountId"},aiAgentContent:{id:57,access:"aiConfig.content",converter:objectToJSONString,retConverter:emptyFunc},aiAgentMessages:{id:58,access:"aiConfig.messages",converter:objectToJSONString,retConverter:emptyFunc},aiAgentPromptVariables:{id:59,access:"aiConfig.promptVariables",retConverter:emptyFunc},aiAgentModelConfigParams:{id:60,access:"aiConfig.modelConfigParams",converter:objectToJSONString,retConverter:emptyFunc},errorCode:{id:61,access:"messageStatus.errorCode",converter:emptyFunc,retType:"number"},modifyTime:{id:62,retType:"number"},modifyAccountId:63,aiStream:{id:65,access:"aiConfig.aiStream",retAccess:"streamConfig.isStream",converter:boolToInt,retConverter:intToBool},aiRAGs:{id:66,access:"aiConfig.aiRAGs",retConverter:function aiAgentStreamAIRAGsRetConverter$1(t){try{var i=JSON.parse(t);return i&&i.length>0?i.map((t=>(t.desc&&(t.description=t.desc,delete t.desc),t))):[]}catch(t){return[]}}},aiStreamStatus:{id:67,access:"streamConfig.status",retType:"number"},historyEnabled:{id:100,access:"messageConfig.historyEnabled",converter:boolToInt,retType:"boolean"},roamingEnabled:{id:101,access:"messageConfig.roamingEnabled",converter:boolToInt,retType:"boolean"},onlineSyncEnabled:{id:102,access:"messageConfig.onlineSyncEnabled",converter:boolToInt,retType:"boolean"},routeEnabled:{id:105,access:"routeConfig.routeEnabled",converter:boolToInt,retType:"boolean"},isInBlackList:{id:106,access:"isInBlackList",converter:boolToInt,retType:"boolean"},pushEnable:{id:107,access:"pushConfig.pushEnabled",converter:boolToInt,retType:"boolean"},offlineEnabled:{id:108,access:"messageConfig.offlineEnabled",converter:boolToInt,retType:"boolean"},unreadEnabled:{id:109,access:"messageConfig.unreadEnabled",converter:boolToInt,retType:"boolean"},pushNickEnabled:{id:110,access:"pushConfig.pushNickEnabled",converter:boolToInt,retType:"boolean"},msgAckSnapshot:{id:112,retType:"number"},receiverIds:{id:154,access:"targetConfig.receiverIds",converter:objectToJSONString,retConverter:()=>{}},inclusive:{id:155,access:"targetConfig.inclusive",converter:t=>t?1:2,retConverter:()=>{}},newMemberVisible:{id:156,access:"targetConfig.newMemberVisible",converter:t=>t?1:2,retConverter:()=>{}},actionTime:{id:163,retType:"number"}},Li=invertSerializeItem(Pi),wi={conversationType:{id:1,access:"messageRefer.conversationType",retType:"number"},senderId:{id:2,access:"messageRefer.senderId"},receiverId:{id:3,access:"messageRefer.receiverId"},messageServerId:{id:4,access:"messageRefer.messageServerId"},messageClientId:{id:5,access:"messageRefer.messageClientId"},createTime:{id:6,access:"messageRefer.createTime",retType:"number"},deleteTime:{id:7,retType:"number"},serverExtension:8};invertSerializeItem(wi);var Di={version:1,md5:2,nosurl:3,thesaurus:4},Ui={createTime:{id:0,retType:"number"},sysMsgType:1,receiverId:2,senderId:3,postscript:4,attach:5,pushContent:8,pushPayload:9,messageClientId:10,messageServerId:11,deleteMsgCreatetime:{id:14,retType:"number"},opeAccount:16,env:21,callbackExtension:22},xi={receiverId:0,messageServerId:1,readCount:{id:100,retType:"number"},unreadCount:{id:101,retType:"number"},messageClientId:102,latestReadAccount:103},Fi={v2BatchMarkRead:{sid:4,cid:5,service:Vi,hasPacketResponse:!1,params:[{type:"Byte",name:"sid"},{type:"Byte",name:"cid"},{type:"LongArray",name:"ids"}]},v2SendP2pMessage:{sid:30,cid:1,service:Vi,params:[{type:"Property",name:"tag",reflectMapper:Pi}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Pi)}]},onMsg:{sid:7,cid:2,service:Vi,response:[{type:"Property",name:"msg",reflectMapper:invertSerializeItem(Pi)}]},syncOfflineMsgs:{sid:4,cid:4,service:Vi,response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(Pi)}]},syncRoamingMsgs:{sid:4,cid:9,service:Vi,response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(Pi)}]},v2SendP2PMessageReceipt:{sid:30,cid:11,service:Vi,params:[{type:"Property",name:"tag",reflectMapper:Pi}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem({actionTime:{id:163,retType:"number"}})}]},v2RevokeMessage:{sid:30,cid:13,service:Vi,params:[{type:"Property",name:"tag",reflectMapper:Ui}]},v2DeleteMessage:{sid:30,cid:23,service:Vi,params:[{type:"Property",name:"tag",reflectMapper:wi}],response:[{type:"Long",name:"timetag"}]},v2DeleteMessages:{sid:30,cid:24,service:Vi,params:[{type:"PropertyArray",name:"tag",reflectMapper:wi}],response:[{type:"Long",name:"timetag"}]},v2SendTeamMessage:{sid:31,cid:2,service:Vi,params:[{type:"Property",name:"tag",reflectMapper:Pi}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Pi)}]},v2SendTeamMessageReceipts:{sid:31,cid:28,service:Vi,params:[{type:"PropertyArray",name:"tag",reflectMapper:xi}],response:[{type:"PropertyArray",name:"tag",reflectMapper:invertSerializeItem(xi)}]},v2SendSuperTeamMessage:{sid:32,cid:2,service:Vi,params:[{type:"Property",name:"tag",reflectMapper:Pi}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Pi)}]},v2RevokeSuperTeamMessage:{sid:32,cid:17,service:Vi,params:[{type:"Property",name:"tag",reflectMapper:Ui}]},syncP2PMessagReceipts:{sid:4,cid:12,service:Vi,response:[{type:"PropertyArray",name:"data",reflectMapper:invertSerializeItem(Pi)}]},syncP2pMessagReceiptsV2:{sid:4,cid:32,service:Vi,response:[{type:"Property",name:"ctx",reflectMapper:invertSerializeItem({minTimetag:{id:1,retType:"number"},maxTimetag:{id:2,retType:"number"}})},{type:"PropertyArray",name:"contents",reflectMapper:invertSerializeItem({id:1,msgTime:{id:2,retType:"number"}})}]},onP2PMessageReceipts:{sid:7,cid:12,service:Vi,response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Pi)}]},v2GetTeamMessageReceipts:{sid:31,cid:29,service:Vi,params:[{type:"PropertyArray",name:"tag",reflectMapper:xi}],response:[{type:"PropertyArray",name:"data",reflectMapper:invertSerializeItem(xi)}]},v2GetTeamMessageReceiptDetail:{sid:31,cid:30,service:Vi,params:[{type:"Property",name:"tag",reflectMapper:xi,select:["receiverId","messageServerId"]}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(xi)},{type:"StrArray",name:"readAccountList"},{type:"StrArray",name:"unreadAccountList"}]},onTeamMessageReceipts:{sid:8,cid:31,service:Vi,response:[{type:"PropertyArray",name:"data",reflectMapper:invertSerializeItem(xi)}]},onRevokeMessage:{sid:7,cid:14,service:Vi,response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Ui)}]},syncRevokeMessage:{sid:7,cid:15,service:Vi,response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(Ui)}]},syncOnDeleteMessages:{sid:4,cid:21,service:Vi,response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(wi)}]},onDeleteMessage:{sid:7,cid:123,service:Vi,response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(wi)}]},onDeleteMessages:{sid:7,cid:124,service:Vi,response:[{type:"PropertyArray",name:"data",reflectMapper:invertSerializeItem(wi)}]},v2DownloadLocalAntiSpamVocabs:{sid:29,cid:17,service:Vi,params:[{type:"Property",name:"tag",reflectMapper:Di}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Di)}]},v2MessageP2pModify:{sid:30,cid:31,service:Vi,params:[{type:"Property",name:"tag",reflectMapper:Pi}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Pi)}]},v2MessageTeamModify:{sid:31,cid:37,service:Vi,params:[{type:"Property",name:"tag",reflectMapper:Pi}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Pi)}]},v2MessageSuperTeamModify:{sid:32,cid:38,service:Vi,params:[{type:"Property",name:"tag",reflectMapper:Pi}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Pi)}]},v2MessageOnModified:{sid:7,cid:33,service:Vi,response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Pi)}]},v2MessageSyncModified:{sid:4,cid:27,service:Vi,response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(Pi)},{type:"Long",name:"time"}]},v2MessageSuperTeamSyncModified:{sid:4,cid:28,service:Vi,response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(Pi)},{type:"Long",name:"time"}]},v2GetP2PMessageReceipts:{sid:30,cid:35,service:Vi,params:[{type:"PropertyArray",name:"tags",reflectMapper:{type:1,id:2}}],response:[{type:"Long",name:"actionTime"},{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem({type:1,id:2,msgTime:3})}]}};function conversationTypeV2ToV1(t){return 1===t?0:2===t?1:3===t?5:void 0}function conversationTypeV1ToV2(t){var i=parseInt(t);return 0===i?1:1===i?2:5===i?3:0}var Bi="V2NIMNotificationService",$i={"30_7":"v2SendCustomNotification","32_16":"v2SendCustomNotificationWithSuperTeam","7_3":"onSysNotification","21_19":"onSysNotification","4_6":"v2SyncOfflineSysNotifications","4_18":"v2SyncOfflineSysNotifications","7_14":"v2NotificationRevoke","21_18":"v2NotificationRevoke","21_117":"v2NotificationRevoke","4_19":"v2NotificationSyncRevoke","7_15":"v2NotificationSyncRevoke","4_16":"syncBroadcastMsg","7_17":"onBroadcastMsg"},ji={timestamp:{id:0,retType:"number"},type:{id:1,retType:"number"},receiverId:2,senderId:3,postscript:4,content:5,idServer:6,offlineEnabled:{id:7,converter:boolToInt,retConverter:function(t,i){return"0"!==i[6]&&!!parseInt(t)},access:"notificationConfig.offlineEnabled"},pushContent:{id:8,access:"pushConfig.pushContent"},pushPayload:{id:9,access:"pushConfig.pushPayload"},deletedIdClient:10,deletedIdServer:11,antispamEnabled:{id:12,converter:boolToInt,retType:"boolean",access:"antispamConfig.antispamEnabled"},antispamCustomNotification:{id:13,access:"antispamConfig.antispamCustomNotification"},deletedMsgCreateTime:14,deletedMsgFromNick:15,opeAccount:16,forcePushAccountIds:{id:18,access:"pushConfig.forcePushAccountIds",def:t=>{if(101===t.type&&t["pushConfig.forcePush"])return"#%@all@%#"},converter:(t,i)=>{if(i["pushConfig.forcePush"])return t?JSON.stringify(t):"#%@all@%#"},retConverter(t){if("#%@all@%#"!==t&&t)try{return JSON.parse(t)}catch(t){return[]}}},forcePushContent:{id:19,access:"pushConfig.forcePushContent"},forcePush:{id:20,converter:boolToInt,retType:"boolean",access:"pushConfig.forcePush"},routeEnvironment:{id:21,access:"routeConfig.routeEnvironment"},callbackExt:22,clientNotificationId:{id:23,access:"notificationConfig.clientNotificationId"},conversationOnlineSyncNotify:24,conversationOnlineSyncData:25,routeEnabled:{id:105,converter:boolToInt,retType:"boolean",access:"routeConfig.routeEnabled"},pushEnabled:{id:107,converter:boolToInt,retType:"boolean",access:"pushConfig.pushEnabled"},unreadEnabled:{id:109,converter:boolToInt,retType:"boolean",access:"notificationConfig.unreadEnabled"},pushNickEnabled:{id:110,converter:boolToInt,retType:"boolean",access:"pushConfig.pushNickEnabled"}},Gi={id:1,senderId:2,timestamp:{id:4,retType:"number"},content:5},qi={v2SendCustomNotification:{sid:30,cid:7,service:Bi,params:[{type:"Property",name:"tag",reflectMapper:ji}]},v2SendCustomNotificationWithSuperTeam:{sid:32,cid:16,service:Bi,params:[{type:"Property",name:"tag",reflectMapper:ji}]},onSysNotification:{sid:7,cid:3,service:Bi,response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(ji)}]},syncBroadcastMsg:{sid:4,cid:16,service:Bi,response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(Gi)}]},onBroadcastMsg:{sid:7,cid:17,service:Bi,response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Gi)}]},v2SyncOfflineSysNotifications:{sid:4,cid:9,service:Bi,response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(ji)}]},v2NotificationRevoke:{sid:7,cid:14,service:Bi,response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(ji)}]},v2NotificationSyncRevoke:{sid:7,cid:15,service:Bi,response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(ji)},{type:"Long",name:"timetag"},{type:"Byte",name:"type"}]}},Hi={"4_5":"ysfBatchMarkRead","101_1":"ysfSendMessage","101_2":"ysfOnMsg","4_100":"ysfSyncOfflineMsgs","101_3":"ysfOnSysNotification","101_7":"ysfSendCustomNotification","4_101":"ysfSyncSysNotification"},zi={ysfBatchMarkRead:{sid:4,cid:5,service:"YSFService",hasPacketResponse:!1,params:[{type:"Byte",name:"sid"},{type:"Byte",name:"cid"},{type:"LongArray",name:"ids"}]},ysfSendMessage:{sid:101,cid:1,service:"YSFService",params:[{type:"Property",name:"tag",reflectMapper:Pi}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Pi)}]},ysfOnMsg:{sid:101,cid:2,service:"YSFService",response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Pi)}]},ysfSyncOfflineMsgs:{sid:4,cid:100,service:"YSFService",response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(Pi)}]},ysfOnSysNotification:{sid:101,cid:3,service:"YSFService",response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(ji)}]},ysfSendCustomNotification:{sid:101,cid:7,service:"YSFService",params:[{type:"Property",name:"tag",reflectMapper:ji}]},ysfSyncSysNotification:{sid:4,cid:101,service:"YSFService",response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(ji)}]}},Yi={content:{type:"string",allowEmpty:!1},params:{type:"object",required:!1,rules:{notificationConfig:{type:"object",required:!1,rules:{offlineEnabled:{type:"boolean",required:!1},unreadEnabled:{type:"boolean",required:!1}}},pushConfig:{type:"object",required:!1,rules:{pushEnabled:{type:"boolean",required:!1},pushNickEnabled:{type:"boolean",required:!1},pushContent:{type:"string",required:!1},pushPayload:{type:"string",required:!1},forcePush:{type:"boolean",required:!1},forcePushContent:{type:"string",required:!1},forcePushAccountIds:{type:"array",required:!1,itemType:"string"}}},antispamConfig:{type:"object",required:!1,rules:{antispamEnabled:{type:"boolean",required:!1},antispamCustomNotification:{type:"string",required:!1}}},routeConfig:{type:"object",required:!1,rules:{routeEnabled:{type:"boolean",required:!1},routeEnvironment:{type:"string",required:!1}}}}}};class NotificationUtil{constructor(t){this.core=t}generateNotificationTag(t,i,o={}){var m=this.core.V2NIMConversationIdUtil.parseConversationType(t),h=this.core.V2NIMConversationIdUtil.parseConversationTargetId(t),u=Date.now(),v={1:100,2:101,3:103};return Object.assign(Object.assign({},o),{notificationConfig:Object.assign({unreadEnabled:!0,offlineEnabled:!0},null==o?void 0:o.notificationConfig),pushConfig:Object.assign({pushEnabled:!0,pushNickEnabled:!0},null==o?void 0:o.pushConfig),antispamConfig:Object.assign({antispamEnabled:!0},null==o?void 0:o.antispamConfig),routeConfig:Object.assign({routeEnabled:!0},null==o?void 0:o.routeConfig),timestamp:u,type:v[m],receiverId:h,content:i})}}function getFileOrPath(t){var i="object"==typeof t?t:void 0,o="string"==typeof t?t:void 0;if(!i&&!o)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_MISUSE,detail:{reason:"getFileOrPath::incorrect file and path"}});if("string"==typeof o)if(0===o.indexOf("nim-external")){var m=document.getElementById(o);if(!(m&&m.files&&m.files[0]))throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_FILE_NOT_FOUND,detail:{reason:`getFileOrPath::file not exist: ${o}`}});i=m.files[0]}else if("BROWSER"===Re.platform)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_MISUSE,detail:{reason:`getFileOrPath::incorrect path: ${o}`}});if("object"==typeof i&&void 0===i.size)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_MISUSE,detail:{reason:"getFileOrPath::file no size"}});return{file:i,path:o}}var Ji={attachment:{type:"object",rules:{url:{type:"string",allowEmpty:!1}}},thumbSize:{type:"object",rules:{width:{type:"number",required:!1,min:0},height:{type:"number",required:!1,min:0}}}};class V2NIMStorageUtil extends V2Service{constructor(t){super("V2NIMStorageUtil",t),this.core=t}imageThumbUrl(t,i){return t+`?imageView&thumbnail=${i}z${i}`}videoCoverUrl(t,i){return t+`?vframe&offset=${i}`}getImageThumbUrl(t,i){return __awaiter(this,void 0,void 0,(function*(){this.checkV2();var o=t;validate(Ji,{attachment:o,thumbSize:i},"",!0),i.width=i.width||0,i.height=i.height||0,0===i.width&&0===i.height&&(i.width=150);var m=o.url;try{m=yield this.core.V2NIMStorageService.shortUrlToLong(o.url)}catch(t){this.core.logger.warn("shortUrlToLong error:",t)}return{url:this.core.cloudStorage.getThumbUrl(m,i)}}))}getVideoCoverUrl(t,i){return __awaiter(this,void 0,void 0,(function*(){this.checkV2();var o=t;validate(Ji,{attachment:o,thumbSize:i},"",!0),i.width=i.width||0,i.height=i.height||0,0===i.width&&0===i.height&&(i.width=150);var m=o.url;try{m=yield this.core.V2NIMStorageService.shortUrlToLong(o.url)}catch(t){this.core.logger.warn("shortUrlToLong error:",t)}return{url:this.core.cloudStorage.getVideoCoverUrl(m,i)}}))}}var Ki,Wi,Xi={file:{md5:"$(Etag)",size:"$(ObjectSize)"},image:{md5:"$(Etag)",size:"$(ObjectSize)",w:"$(ImageInfo.Width)",h:"$(ImageInfo.Height)",orientation:"$(ImageInfo.Orientation)"},audio:{md5:"$(Etag)",size:"$(ObjectSize)",dur:"$(AVinfo.Audio.Duration)"},video:{md5:"$(Etag)",size:"$(ObjectSize)",dur:"$(AVinfo.Video.Duration)",w:"$(AVinfo.Video.Width)",h:"$(AVinfo.Video.Height)"}},Qi={accessKeyId:"",secretAccessKey:"",sessionToken:"",region:"",maxRetries:0,bucket:"",objectName:"",token:"",shortUrl:""};function getUploadResponseFormat(t="file"){var i=Xi[t]||{};return JSON.stringify(i).replace(/"/gi,'\\"')}!function(t){t[t.nos=1]="nos",t[t.s3=2]="s3"}(Ki||(Ki={})),function(t){t[t.dontNeed=-1]="dontNeed",t[t.time=2]="time",t[t.urls=3]="urls"}(Wi||(Wi={}));var Zi={chunkUploadHost:"https://wannos-web.127.net",chunkUploadHostBackupList:["https://fileup.chatnos.com","https://oss.chatnos.com"],commonUploadHost:"https://fileup.chatnos.com",commonUploadHostBackupList:["https://upload.chatnos.com","https://oss.chatnos.com"],chunkMaxSize:4194304e4,commonMaxSize:104857600,uploadReplaceFormat:"https://{host}/{object}",cdn:{defaultCdnDomain:"nim-nosdn.netease.im",cdnDomain:"",bucket:"nim",objectNamePrefix:""},downloadUrl:"https://{bucket}-nosdn.netease.im/{object}",downloadHostList:["nos.netease.com"],nosCdnEnable:!0,isNeedToGetUploadPolicyFromServer:!0};function pickBy(t,i){t=t||{},i=i||(()=>!0);var o={};for(var m in t)i(t[m])&&(o[m]=t[m]);return o}class NOS{constructor(t,i){this.nosCdnHostTimer=0,this.nosErrorCount=0,this.core=t,this.cloudStorage=i}get config(){return this.cloudStorage.config}reset(){this.nosErrorCount=0}getNosAccessToken(t){return __awaiter(this,void 0,void 0,(function*(){var i=get(yield this.core.sendCmd("getNosAccessToken",{tag:t}),"content.nosAccessTokenTag.token"),o=t.url;return{token:i,url:-1!==o.indexOf("?")?o+"&token="+i:o+"?token="+i}}))}deleteNosAccessToken(t){return __awaiter(this,void 0,void 0,(function*(){yield this.core.sendCmd("deleteNosAccessToken",{tag:t})}))}nosUpload(t,i,o){var m,h,u,v,I,_,M,E,S,T;return __awaiter(this,void 0,void 0,(function*(){var C=get(this.core,"config.cdn.bucket"),N={tag:t.nosScenes||C||"nim"};t.nosSurvivalTime&&(N.expireSec=t.nosSurvivalTime);var A,O=this.core.adapters.getFileUploadInformation(t);if(O&&O.complete&&i.destroy(),!o&&!O)try{A=yield this.core.sendCmd("getNosToken",{responseBody:getUploadResponseFormat(t.type),nosToken:N})}catch(t){if(this.core.logger.error("uploadFile:: getNosToken error",t),i.destroy(),t instanceof V2NIMErrorImpl)throw t;throw new UploadError({code:"v2"===get(this.core,"options.apiVersion")?Ee.V2NIM_ERROR_CODE_FILE_UPLOAD_FAILED:400,detail:{reason:"getNosToken error",rawError:t,curProvider:1}})}var R=this.config.uploadReplaceFormat.replace("{bucket}",this.config.cdn.bucket).replace("{host}",this.config.cdn.cdnDomain||this.config.cdn.defaultCdnDomain).replace("{object}",O?null===(m=O.uploadInfo)||void 0===m?void 0:m.objectName:o?null==o?void 0:o.objectName:A.content.nosToken.objectName),V="";o&&o.shortUrl&&(V=o.shortUrl),(null===(v=null===(u=null===(h=null==O?void 0:O.uploadInfo)||void 0===h?void 0:h.payload)||void 0===u?void 0:u.mixStoreToken)||void 0===v?void 0:v.shortUrl)&&(V=O.uploadInfo.payload.mixStoreToken.shortUrl);var k,P=V||R;try{var L=O?{token:null===(I=null==O?void 0:O.uploadInfo)||void 0===I?void 0:I.token,bucket:null===(_=null==O?void 0:O.uploadInfo)||void 0===_?void 0:_.bucketName,objectName:null===(M=null==O?void 0:O.uploadInfo)||void 0===M?void 0:M.objectName}:o||A.content.nosToken;this.core.logger.log("uploadFile:: uploadFile params",{nosToken:L,chunkUploadHost:this.config.chunkUploadHost,chunkUploadHostBackupList:this.config.chunkUploadHostBackupList,commonUploadHost:this.config.commonUploadHost,commonUploadHostBackupList:this.config.commonUploadHostBackupList,platform:Re.platform});var w="BROWSER"===Re.platform?this.config.chunkUploadHost:`${this.config.commonUploadHost}/${L&&L.bucket}`,D="UNIAPP"===Re.platform||"MINIAPP"===(null===(E=Re.getSystemInfo())||void 0===E?void 0:E.libEnv)?4:o?2:0,U=t.filePath?t.filePath:"object"==typeof t.file?t.file.name:"";i.update({remote_addr:w,operation_type:D}),U&&i.update({local_file:U}),k=yield this.core.adapters.uploadFile(Object.assign(Object.assign(Object.assign(Object.assign({},t),{nosToken:L,chunkUploadHost:this.config.chunkUploadHost,chunkUploadHostBackupList:this.config.chunkUploadHostBackupList,commonUploadHost:this.config.commonUploadHost,commonUploadHostBackupList:this.config.commonUploadHostBackupList,maxSize:t.maxSize||this.config.chunkMaxSize}),o?{payload:{mixStoreToken:o}}:{}),{onUploadInfo:t=>{i.update(Object.assign({},t))}}),i)}catch(m){this.core.logger.error("uploadFile::nos uploadFile error:",m);var x="v2"===get(this.core,"options.apiVersion");if(m.code===Ee.V2NIM_ERROR_CODE_CANCELLED||10499===m.errCode)throw new UploadError({code:x?Ee.V2NIM_ERROR_CODE_CANCELLED:400,detail:{reason:get(m,"message")||"Request abort",rawError:m,curProvider:1}});if(x&&m.errCode===Ee.V2NIM_ERROR_CODE_FILE_OPEN_FAILED)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_FILE_OPEN_FAILED,detail:{reason:get(m,"message")||"Read file failed",rawError:m,curProvider:1}});var{net_connect:B}=yield Re.net.getNetworkStatus();if(!1===B)throw new UploadError({code:"v2"===get(this.core,"options.apiVersion")?Ee.V2NIM_ERROR_CODE_FILE_UPLOAD_FAILED:400,detail:{reason:"No network",rawError:m,curProvider:1}});if(o){if(this.nosErrorCount<=0){try{this.cloudStorage.mixStorage._addCircuitTimer()}catch(i){throw new UploadError({code:"v2"===get(this.core,"options.apiVersion")?Ee.V2NIM_ERROR_CODE_FILE_UPLOAD_FAILED:400,detail:{reason:"All upload attempts failed",rawError:i,curProvider:this.cloudStorage.mixStorage.curProvider,mixStorePolicy:this.cloudStorage.mixStorage.mixStorePolicy,file:t.file||t.filePath}})}return this.nosErrorCount=get(this.cloudStorage,"mixStorePolicy.nosPolicy.uploadConfig.retryPolicy.retry"),this.cloudStorage._uploadFile(t,i)}return this.nosErrorCount--,this.nosUpload(t,i,o)}throw new UploadError({code:"v2"===get(this.core,"options.apiVersion")?Ee.V2NIM_ERROR_CODE_FILE_UPLOAD_FAILED:400,detail:{reason:"NOS attempts failed",rawError:m,curProvider:1}})}var $=null==k?void 0:k.type,j=$&&$.indexOf("/")>-1?$.slice(0,$.indexOf("/")):"";j||(j=t.type||"");var G,q={image:"imageInfo",video:"vinfo",audio:"vinfo"};if(!q[j])return Object.assign({url:P},k);if(k.w&&k.h||k.dur)return Object.assign({url:P},k);try{G=yield this.core.adapters.request(`${R}?${q[j]}`,{method:"GET",dataType:"json",timeout:5e3},{exception_service:3})}catch(t){var H=t;return i.update({exception:`Fetch media info failed;url:${R}?${q[j]};errMsg:${(null===(S=H.detail)||void 0===S?void 0:S.reason)||H.message}`,external_code:H.code}),this.core.logger.error("uploadFile:: fetch file info error",t),Object.assign({url:P},k)}if(G){var{data:z}=G,Y="imageInfo"===q[j]?z:null===(T=null==z?void 0:z.GetVideoInfo)||void 0===T?void 0:T.VideoInfo;return pickBy({url:P,name:k.name,size:k.size,ext:k.ext,w:null==Y?void 0:Y.Width,h:null==Y?void 0:Y.Height,orientation:null==Y?void 0:Y.Orientation,dur:null==Y?void 0:Y.Duration,audioCodec:null==Y?void 0:Y.AudioCodec,videoCodec:null==Y?void 0:Y.VideoCodec,container:null==Y?void 0:Y.Container},(function(t){return void 0!==t}))}return Object.assign({url:P},k)}))}_getNosCdnHost(){var t;return __awaiter(this,void 0,void 0,(function*(){var i;try{i=yield this.core.sendCmd("getNosCdnHost")}catch(t){return void this.core.logger.error("getNosCdnHost::error",t)}if(i){var o=null===(t=null==i?void 0:i.content)||void 0===t?void 0:t.nosConfigTag,m=parseInt(null==o?void 0:o.expire);0!==m&&o.cdnDomain?-1===m?(this.config.cdn.bucket=o.bucket,this.config.cdn.cdnDomain=o.cdnDomain,this.config.cdn.objectNamePrefix=o.objectNamePrefix):(this.config.cdn.bucket=o.bucket,this.config.cdn.cdnDomain=o.cdnDomain,this.config.cdn.objectNamePrefix=o.objectNamePrefix,this.nosCdnHostTimer=this.core.timerManager.addTimer((()=>{this._getNosCdnHost()}),1e3*m)):(this.config.cdn.bucket="",this.config.cdn.cdnDomain="",this.config.cdn.objectNamePrefix="")}}))}}var er={"6_2":"getNosToken","6_22":"getOriginUrl","6_24":"getNosAccessToken","6_25":"deleteNosAccessToken","6_26":"getNosCdnHost","6_27":"getGrayscaleConfig","6_28":"getMixStorePolicy","6_29":"getMixStoreToken","6_30":"getFileAuthToken"},tr={nosToken:{objectName:1,token:2,bucket:3,expireTime:4,expireSec:7,tag:8,shortUrl:9},mixStoreTokenReqTag:{provider:0,tokenCount:1,nosSurvivalTime:2,tag:3,returnBody:4,policyVersion:5},nosConfigTag:{bucket:1,cdnDomain:2,expire:3,objectNamePrefix:4},grayConfigTag:{config:0,ttl:1},mixStorePolicyTag:{providers:0,ttl:1,mixEnable:2,nosPolicy:3,s3Policy:4,policyVersion:5},mixStoreTokenResTag:{provider:0,accessKeyId:1,secretAccessKey:2,sessionToken:3,token:4,expireTime:5,bucket:6,objectName:7,fileExpireSec:8,tag:9,shortUrl:10,region:11},nosSafeUrlTag:{safeUrl:0,originUrl:1},mixStoreAuthTokenReqTag:{type:1,urls:2},mixStoreAuthTokenResTag:{type:1,tokens:2,token:3,ttl:4},nosAccessTokenTag:{token:0,url:1,userAgent:2,ext:3}},ir={getNosToken:{sid:6,cid:2,service:"cloudStorage",params:[{type:"String",name:"responseBody"},{type:"Property",name:"nosToken",entity:"nosToken",reflectMapper:tr.nosToken}],response:[{type:"Property",name:"nosToken",reflectMapper:invertSerializeItem(tr.nosToken)}]},getOriginUrl:{sid:6,cid:22,service:"cloudStorage",params:[{type:"Property",name:"nosSafeUrlTag",reflectMapper:tr.nosSafeUrlTag}],response:[{type:"Property",name:"nosSafeUrlTag",reflectMapper:invertSerializeItem(tr.nosSafeUrlTag)}]},getNosCdnHost:{sid:6,cid:26,service:"cloudStorage",response:[{type:"Property",name:"nosConfigTag",reflectMapper:invertSerializeItem(tr.nosConfigTag)}]},getGrayscaleConfig:{sid:6,cid:27,service:"cloudStorage",params:[{type:"Property",name:"config"}],response:[{type:"Property",name:"grayConfigTag",reflectMapper:invertSerializeItem(tr.grayConfigTag)}]},getMixStorePolicy:{sid:6,cid:28,service:"cloudStorage",params:[{type:"LongArray",name:"supportType"}],response:[{type:"Property",name:"mixStorePolicyTag",reflectMapper:invertSerializeItem(tr.mixStorePolicyTag)}]},getMixStoreToken:{sid:6,cid:29,service:"cloudStorage",params:[{type:"Property",name:"mixStoreTokenReqTag",reflectMapper:tr.mixStoreTokenReqTag}],response:[{type:"Property",name:"mixStoreTokenResTag",reflectMapper:invertSerializeItem(tr.mixStoreTokenResTag)}]},getFileAuthToken:{sid:6,cid:30,service:"cloudStorage",params:[{type:"Property",name:"mixStoreAuthTokenReqTag",reflectMapper:tr.mixStoreAuthTokenReqTag}],response:[{type:"Property",name:"mixStoreAuthTokenResTag",reflectMapper:invertSerializeItem(tr.mixStoreAuthTokenResTag)}]},getNosAccessToken:{sid:6,cid:24,service:"cloudStorage",params:[{type:"Property",name:"tag",reflectMapper:tr.nosAccessTokenTag}],response:[{type:"Property",name:"tag",reflectMapper:invertSerializeItem(tr.nosAccessTokenTag)}]},deleteNosAccessToken:{sid:6,cid:25,service:"cloudStorage",params:[{type:"Property",name:"tag",reflectMapper:tr.nosAccessTokenTag}]}};class MixStorage{constructor(t,i){this.GRAYKEY="AllGrayscaleConfig",this.MIXSTOREKEY="AllMixStorePolicy",this.grayConfig={mixStoreEnable:!1,timeStamp:0,ttl:0},this.mixStorePolicy={providers:[],timeStamp:0,ttl:0,s3Policy:null,nosPolicy:null,policyVersion:void 0},this.curProvider=1,this.mixStoreErrorCount=10,this.circuitTimer=0,this.core=t,this.cloudStorage=i,this.logger=t.logger}reset(){this.grayConfig=null,this.mixStorePolicy={providers:[],timeStamp:0,ttl:0,s3Policy:null,nosPolicy:null,policyVersion:void 0},this.curProvider=1,this.mixStoreErrorCount=10}getGrayscaleConfig(t,i){var o;return __awaiter(this,void 0,void 0,(function*(){if(Re.localStorage)try{Re.localStorage.getItem&&Re.localStorage.getItem(this.GRAYKEY)&&(this.grayConfig=JSON.parse(Re.localStorage.getItem(this.GRAYKEY))[t])}catch(t){Re.localStorage.getItem(this.GRAYKEY)&&this.core.logger.error("uploadFile:: JSON.parse grayscaleConfig error ",t)}if(!this.grayConfig||this.grayConfig.timeStamp+1e3*this.grayConfig.ttl<i){var m=yield this.core.sendCmd("getGrayscaleConfig",{config:{}});if(m.content&&m.content.grayConfigTag){this.logger.log("uploadFile::getAppGrayConfigRequest success ");try{this.grayConfig=JSON.parse(m.content.grayConfigTag.config),this.grayConfig.ttl=JSON.parse(m.content.grayConfigTag.ttl)}catch(t){this.logger.error("getGrayscaleConfig error",t)}if(!this.grayConfig)return;var h=Re.localStorage.getItem(this.GRAYKEY)?JSON.parse(Re.localStorage.getItem(this.GRAYKEY)):{};this.grayConfig.timeStamp=(new Date).getTime(),h[t]=this.grayConfig,Re.localStorage.setItem(this.GRAYKEY,JSON.stringify(h))}else this.logger.log("uploadFile:: result grayConfig:",m.content)}(null===(o=this.grayConfig)||void 0===o?void 0:o.mixStoreEnable)&&(yield this._getMixStorePolicy(t))}))}_getMixStorePolicy(t){return __awaiter(this,void 0,void 0,(function*(){var i=(new Date).getTime();if(Re.localStorage)try{if(this.mixStorePolicy=JSON.parse(Re.localStorage.getItem(this.MIXSTOREKEY))[t],this.curProvider=parseInt(this.mixStorePolicy.providers[0]),this.mixStorePolicy.timeStamp&&this.mixStorePolicy.timeStamp+1e3*this.mixStorePolicy.ttl>i){var o=this.mixStorePolicy.timeStamp+1e3*this.mixStorePolicy.ttl-i;this.core.timerManager.addTimer(this._getMixStorePolicy.bind(this,t),o)}}catch(i){Re.localStorage.getItem(this.MIXSTOREKEY)&&JSON.parse(Re.localStorage.getItem(this.MIXSTOREKEY))[t]&&this.core.logger.error("uploadFile:: JSON.parse mixStorePolicy error ",i)}if(!this.mixStorePolicy||this.mixStorePolicy.timeStamp+1e3*this.mixStorePolicy.ttl<=i)try{var m=(yield this.core.sendCmd("getMixStorePolicy",{supportType:this.cloudStorage.aws.s3?[1,2]:[1]})).content.mixStorePolicyTag;this.mixStorePolicy={providers:[],timeStamp:0,ttl:0,s3Policy:null,nosPolicy:null,policyVersion:void 0},this.mixStorePolicy.policyVersion=m.policyVersion,this.mixStorePolicy.ttl=Number(m.ttl),this.mixStorePolicy.providers=m.providers.split(","),this.circuitTimer&&this.core.timerManager.deleteTimer(this.circuitTimer),this.curProvider=parseInt(this.mixStorePolicy.providers[0]),this.mixStorePolicy.nosPolicy=m.nosPolicy?JSON.parse(m.nosPolicy):null,this.mixStorePolicy.s3Policy=m.s3Policy?JSON.parse(m.s3Policy):null,null===this.mixStorePolicy.s3Policy?this.mixStorePolicy.providers=["1"]:null===this.mixStorePolicy.nosPolicy?this.mixStorePolicy.providers=["2"]:this.mixStorePolicy.providers=this.mixStorePolicy.s3Policy.priority<this.mixStorePolicy.nosPolicy.priority?["2","1"]:["1","2"],this.core.timerManager.addTimer(this._getMixStorePolicy.bind(this,t),1e3*this.mixStorePolicy.ttl);var h=Re.localStorage.getItem(this.MIXSTOREKEY)?JSON.parse(Re.localStorage.getItem(this.MIXSTOREKEY)):{};this.mixStorePolicy.timeStamp=(new Date).getTime(),h[t]=this.mixStorePolicy,Re.localStorage.setItem(this.MIXSTOREKEY,JSON.stringify(h))}catch(i){if(this.logger.error("getMixStorePolicy error",i),0===this.mixStoreErrorCount)throw new Error("getMixStorePolicy all count error");this._getMixStorePolicy(t),this.mixStoreErrorCount--}this.mixStorePolicy.nosPolicy&&(this.cloudStorage.nos.nosErrorCount=this.mixStorePolicy.nosPolicy.uploadConfig.retryPolicy.retry)}))}_addCircuitTimer(){var t=this.mixStorePolicy.providers,i=t[(t.indexOf(String(this.curProvider))+1)%t.length];if(!i)throw new Error("uploadFile nextProvider error");if(i===t[0])throw new Error("uploadFile all policy fail");if(this.logger.log(`uploadFile:: upload policy will change,now policy:${this.curProvider} nextProvider:${i}`),this.curProvider=parseInt(i),this.mixStorePolicy.nosPolicy&&this.mixStorePolicy.s3Policy){var o=this.mixStorePolicy[1===this.curProvider?"nosPolicy":"s3Policy"].uploadConfig.retryPolicy.circuit;if(!o||0===o)throw new Error("uploadFile circuit error");this.circuitTimer=this.core.timerManager.addTimer((()=>{this.logger.log(`uploadFile:: upload policy will change,now policy:${this.curProvider} nextProvider:${parseInt(this.mixStorePolicy.providers[0])}`),this.curProvider=parseInt(this.mixStorePolicy.providers[0]),this.core.timerManager.deleteTimer(this.circuitTimer)}),1e3*o)}throw new Error("uploadFile will not retry again")}getFileAuthToken(t){return __awaiter(this,void 0,void 0,(function*(){return(yield this.core.sendCmd("getFileAuthToken",{mixStoreAuthTokenReqTag:t})).content.mixStoreAuthTokenResTag}))}}var rr=-1;class AWS{constructor(t,i){this.s3=null,this.core=t,this.cloudStorage=i,this.logger=t.logger}get mixStorePolicy(){return this.cloudStorage.mixStorage.mixStorePolicy}s3Upload(t,i,o){return __awaiter(this,void 0,void 0,(function*(){var m;if(rr+=1,t.file)m=t.file;else if("string"==typeof t.fileInput){this.logger.warn("fileInput will abandon,Please use file or filepath");var h=document.getElementById(t.fileInput);if(!(h&&h.files&&h.files[0]))throw new Error("Can not get file from fileInput");m=h.files[0]}else{if(!(t.fileInput&&t.fileInput.files&&t.fileInput.files[0]))throw new Error(`Can not get file from fileInput ${t.fileInput}`);m=t.fileInput.files[0]}if(!this.mixStorePolicy.s3Policy)throw new Error("dont get s3 policy");var u={accessKeyId:o.accessKeyId,secretAccessKey:o.secretAccessKey,sessionToken:o.sessionToken,region:o.region,maxRetries:this.mixStorePolicy.s3Policy.uploadConfig.retryPolicy.retry},v=this.s3,I=decodeURIComponent(o.bucket),_=decodeURIComponent(o.objectName),M=m,E=`https://${I}.s3.amazonaws.com/${_}`,S={},T=this.mixStorePolicy.s3Policy;if(T&&T.uploadConfig&&Array.isArray(T.uploadConfig.uploadUrl)&&T.uploadConfig.uploadUrl.length>0){var C=T.uploadConfig.uploadUrl.length;rr%=C,S.endpoint=T.uploadConfig.uploadUrl[rr],S.s3ForcePathStyle=!0,E=`${S.endpoint}/${I}/${_}`}i.update({local_file:m.name,remote_addr:E,operation_type:1});var N=new v(S);N.config.update(u);var A={Bucket:I,Key:_,Body:M,Metadata:{token:o.token},ContentType:M.type||"application/octet-stream"};this.core.logger.log("uploadFile:: s3 upload params:",A);var O=N.upload(A);return O.on("httpUploadProgress",(o=>{i.update({index:o.part});var m=parseFloat((o.loaded/o.total).toFixed(2));t.onUploadProgress&&t.onUploadProgress({total:o.total,loaded:o.loaded,percentage:m,percentageText:Math.round(100*m)+"%"})})),new Promise(((m,h)=>{var u=(new Date).getTime();O.send(((v,E)=>__awaiter(this,void 0,void 0,(function*(){var S,T,C;if(v&&"RequestAbortedError"===v.code)this.logger.error("uploadFile:","api::s3:upload file abort.",v),i.update({http_code:v.statusCode,exception:v}),h(new UploadError({code:"v2"===get(this.core,"options.apiVersion")?Ee.V2NIM_ERROR_CODE_CANCELLED:400,detail:{reason:"S3RequestAbortedError",rawError:v,curProvider:2}}));else{if(!v){i.update({http_code:200});var N=this.mixStorePolicy.s3Policy.cdnSchema;N=(N=N.replace("{cdnDomain}",this.mixStorePolicy.s3Policy.dlcdn)).replace("{objectName}",E.Key);var A={size:M.size,name:M.name,url:o.shortUrl?o.shortUrl:N,ext:M.name.split(".")[1]||"unknown"},O=t.type||"",R={image:"imageInfo"};return m(R[O]?yield this.getS3FileInfo({url:N,infoSuffix:R[O],s3Result:A}):A)}i.update({http_code:v.statusCode,exception:v}),this.core.reporter.reportTraceStart("exceptions",{user_id:this.core.options.account||(null===(T=null===(S=this.core)||void 0===S?void 0:S.auth)||void 0===T?void 0:T.account),trace_id:null===(C=this.core.clientSocket.socket)||void 0===C?void 0:C.sessionId,start_time:u,action:1,exception_service:4}),this.core.reporter.reportTraceUpdateV2("exceptions",{code:"number"==typeof v.status?v.status:"number"==typeof v.code?v.code:0,description:v.message||`${v.code}`,operation_type:1,target:JSON.stringify({bucket:I,object:_})},{asyncParams:Re.net.getNetworkStatus()}),this.core.reporter.reportTraceEnd("exceptions",1);var{net_connect:V}=yield Re.net.getNetworkStatus();if(!1===V)return h(new UploadError({code:"v2"===get(this.core,"options.apiVersion")?Ee.V2NIM_ERROR_CODE_FILE_UPLOAD_FAILED:400,detail:{reason:"No network",rawError:v,curProvider:this.cloudStorage.mixStorage.curProvider}}));try{this.cloudStorage.mixStorage._addCircuitTimer()}catch(i){return h(new UploadError({code:"v2"===get(this.core,"options.apiVersion")?Ee.V2NIM_ERROR_CODE_FILE_UPLOAD_FAILED:400,detail:{reason:"All upload attempts failed",rawError:i,curProvider:this.cloudStorage.mixStorage.curProvider,mixStorePolicy:this.mixStorePolicy,file:t.file||t.filePath}}))}m(this.cloudStorage._uploadFile(t,i))}})))),t.onUploadStart&&t.onUploadStart(O)}))}))}getS3FileInfo(t){var i;return __awaiter(this,void 0,void 0,(function*(){var o,{url:m,infoSuffix:h,s3Result:u}=t;try{o=yield this.core.adapters.request(`${m}?${h}`,{method:"GET",dataType:"text",timeout:5e3},{exception_service:3})}catch(t){return this.core.logger.error("uploadFile:: fetch file info error",t),u}if(o){var{data:v}=o,I="imageInfo"===h?v:null===(i=null==v?void 0:v.GetVideoInfo)||void 0===i?void 0:i.VideoInfo;return pickBy(Object.assign(Object.assign({},u),{w:null==I?void 0:I.Width,h:null==I?void 0:I.Height,orientation:null==I?void 0:I.Orientation,dur:null==I?void 0:I.Duration,audioCodec:null==I?void 0:I.AudioCodec,videoCodec:null==I?void 0:I.VideoCodec,container:null==I?void 0:I.Container}),(function(t){return void 0!==t}))}return this.core.logger.error("uploadFile:: fetch s3 file info no result",`${m}?${h}`),u}))}}var nr={user_id:"",trace_id:"",action:0,state:0,duration:0,start_time:0,offset:0,full_size:0,transferred_size:0,operation_type:0,remote_addr:"",local_file:"",retry_times:0,index:0,part_size:0,transfer_latency:0,http_code:0,exception:"",req_headers:"",rsp_headers:""},or="ReporterHook::setMonitorForResources:";class ReporterHookCloudStorage{constructor(t,i){this.traceData=nr,this.core=t,this.id=Math.round(1e3*Math.random()),this.traceData=Object.assign({},nr,i)}start(){var t,i;this.core&&(this.reset(),this.traceData.user_id=this.core.account,this.traceData.trace_id=(null===(i=null===(t=this.core.clientSocket)||void 0===t?void 0:t.socket)||void 0===i?void 0:i.sessionId)||"",this.traceData.start_time="timeOrigin"in this.core?this.core.timeOrigin.getNTPTime():Date.now())}update(t){return __awaiter(this,void 0,void 0,(function*(){if(this.core&&this.traceData.user_id){if(t.transferred_size&&this.core.logger.log(`${this.id}.${or} upload update`,t),"object"==typeof t.exception)try{t.exception=JSON.stringify(t.exception)}catch(i){t.exception="UnknownObject"}if("object"==typeof t.req_headers)try{t.req_headers=JSON.stringify(t.req_headers)}catch(i){t.req_headers="UnknownObject"}if("object"==typeof t.rsp_headers)try{t.rsp_headers=JSON.stringify(t.rsp_headers)}catch(i){t.rsp_headers="UnknownObject"}Object.assign(this.traceData,t)}}))}end(t){this.core&&this.traceData.user_id&&(this.core.logger.log(`${or} upload end cause of ${t}`),this.traceData.state=t,this.traceData.duration=("timeOrigin"in this.core?this.core.timeOrigin.getNTPTime():Date.now())-(this.traceData.start_time||0),this.core.reporter.report("nim_sdk_resources",this.traceData),this.traceData=nr,this.destroy())}reset(){this.traceData=Object.assign({},nr)}destroy(){this.core=void 0,this.traceData=nr}}class CloudStorageService{constructor(t,i={}){this.config={},this.uploadTaskMap={},this.name="cloudStorage",this.logger=t.logger,this.core=t,this.nos=new NOS(t,this),this.mixStorage=new MixStorage(t,this),this.aws=new AWS(t,this),registerParser({cmdMap:er,cmdConfig:ir}),this.setOptions(i),this.setListeners()}setOptions(t={}){var i=t.storageKeyPrefix||"NIMClient";this.mixStorage.GRAYKEY=i+"-AllGrayscaleConfig",this.mixStorage.MIXSTOREKEY=i+"-AllMixStorePolicy";var{s3:o}=t,m=__rest(t,["s3"]),h=Object.assign({},Zi,this.config);if(m&&Object.prototype.hasOwnProperty.call(m,"cdn")){var u=Object.assign(Object.assign({},h.cdn),m.cdn);this.config=Object.assign({},h,m),this.config.cdn=u}else this.config=Object.assign({},h,m);o&&(this.aws.s3=o)}setListeners(){this.core.eventBus.on("kicked",this._clearUnCompleteTask.bind(this)),this.core.eventBus.on("disconnect",this._clearUnCompleteTask.bind(this)),this.core.eventBus.on("V2NIMLoginService/loginLifeCycleLogout",this._clearUnCompleteTask.bind(this)),this.core.eventBus.on("V2NIMLoginService/loginLifeCycleKicked",this._clearUnCompleteTask.bind(this))}_clearUnCompleteTask(){Object.keys(this.uploadTaskMap).forEach((t=>{var i=this.uploadTaskMap[t];i&&i.abort&&i.abort()})),this.uploadTaskMap={}}init(t=Date.now()){return __awaiter(this,void 0,void 0,(function*(){this.mixStorage.reset(),this.nos.reset(),this.config.isNeedToGetUploadPolicyFromServer&&(yield this.mixStorage.getGrayscaleConfig(this.core.options.appkey,t)),yield this.nos._getNosCdnHost()}))}processCallback(t,i,o){var m=t.onUploadProgress,h=t.onUploadDone,u=t.onUploadStart;return{onUploadStart:"function"==typeof u?t=>{this.uploadTaskMap[i]=t;try{u(t)}catch(t){this.logger.error("CloudStorage::uploadFile:options.onUploadStart execute error",t)}}:t=>{this.uploadTaskMap[i]=t},onUploadProgress:"function"==typeof m?t=>{o.update({transferred_size:t.loaded,full_size:t.total});try{m(t)}catch(t){this.logger.error("CloudStorage::uploadFile:options.onUploadProgress execute error",t)}}:t=>{o.update({transferred_size:t.loaded,full_size:t.total})},onUploadDone:"function"==typeof h?t=>{o.end(0);try{h(t)}catch(t){this.logger.error("CloudStorage::uploadFile:options.onUploadDone execute error",t)}}:()=>{o.end(0)},taskKey:i}}uploadFile(t){return __awaiter(this,void 0,void 0,(function*(){if(validate({maxSize:{type:"number",required:!1},type:{type:"enum",values:["file","image","audio","video"]}},t),!t.fileInput&&!t.file&&!t.filePath)throw new Error("uploadFile needs target file object or a filePath");if(t.type&&"file"!==t.type){var i=get(t,"file.type");if(i&&"string"==typeof i&&-1===i.indexOf(t.type))throw new Error(`The meta type "${i}" does not match "${t.type}"`)}var o=new ReporterHookCloudStorage(this.core);if(o.start(),t.file)o.update({full_size:t.file.size,local_file:t.file.name});else if("string"==typeof t.fileInput){var m=document.getElementById(t.fileInput);m&&m.files&&m.files[0]&&o.update({full_size:m.files[0].size,local_file:m.files[0].name})}else t.fileInput&&t.fileInput.files&&t.fileInput.files[0]&&o.update({full_size:t.fileInput.files[0].size,local_file:t.fileInput.files[0].name});var h=Pe(),{onUploadStart:u,onUploadProgress:v,onUploadDone:I}=this.processCallback(t,h,o);t.onUploadStart=u,t.onUploadProgress=v,t.onUploadDone=I;var _=null;try{_=yield this._uploadFile(t,o),t.md5&&(_.md5=t.md5),delete this.uploadTaskMap[h]}catch(t){throw delete this.uploadTaskMap[h],o.end((t&&t.code)===Ee.V2NIM_ERROR_CODE_CANCELLED?3:1),t}return _&&(_.size=void 0===_.size?void 0:Number(_.size),_.w=void 0===_.w?void 0:Number(_.w),_.h=void 0===_.h?void 0:Number(_.h),_.dur=void 0===_.dur?void 0:Number(_.dur)),_.url=decodeURIComponent(_.url),t.onUploadDone({size:_.size,name:_.name,url:_.url,ext:_.name.split(".")[1]||"unknown"}),_}))}_uploadFile(t,i){var o,m;return __awaiter(this,void 0,void 0,(function*(){if(!get(this.mixStorage,"grayConfig.mixStoreEnable")||!get(this.mixStorage,"mixStorePolicy.providers.length"))return this.logger.log("uploadFile:: uploadFile begin, use old nos"),this.nos.nosUpload(t,i);this.logger.log(`uploadFile::_uploadFile, grayConfig enable:${get(this.mixStorage,"grayConfig.mixStoreEnable")} curProvider:${get(this.mixStorage,"curProvider")}`);var h=this.core.adapters.getFileUploadInformation(t),u=!0;h?!1===h.complete&&2===this.mixStorage.curProvider?u=!1:h.complete&&i.destroy():u=!1,this.aws.s3||(this.mixStorage.curProvider=1);var v=Qi;if(!u)try{v=(yield this.core.sendCmd("getMixStoreToken",{mixStoreTokenReqTag:{provider:this.mixStorage.curProvider,tokenCount:1,tag:"qchat",nosSurvivalTime:t.nosSurvivalTime,returnBody:getUploadResponseFormat(t.type),policyVersion:this.mixStorage.mixStorePolicy.policyVersion}})).content.mixStoreTokenResTag}catch(t){if(this.core.logger.error("uploadFile:: getMixStoreToken error",t),i.destroy(),t instanceof V2NIMErrorImpl)throw t;throw new UploadError({code:"v2"===get(this.core,"options.apiVersion")?Ee.V2NIM_ERROR_CODE_FILE_UPLOAD_FAILED:400,detail:{reason:"getMixStoreToken error",rawError:t,curProvider:this.mixStorage.curProvider,mixStorePolicy:this.mixStorage.mixStorePolicy}})}return u?this.nos.nosUpload(t,i,null===(m=null===(o=null==h?void 0:h.uploadInfo)||void 0===o?void 0:o.payload)||void 0===m?void 0:m.mixStoreToken):2===this.mixStorage.curProvider?this.aws.s3Upload(t,i,v):this.nos.nosUpload(t,i,v)}))}getThumbUrl(t,i){var o,m,h,u,v;if(!new RegExp(/http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- ./?%&=]*)?/).test(t))return this.logger.error("illegal file url:"+t),t;var[I,_,M,E,S,T,C,N]=/^(?:([A-Za-z]+):)?(\/{0,3})([0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/.exec(t);if(null===(o=this.grayConfig)||void 0===o?void 0:o.mixStoreEnable){var A=this._getUrlType(t);if(2===A&&this.mixStorePolicy.s3Policy&&get(this.mixStorePolicy,"s3Policy.thumbPolicy.imagethumb"))return(null===(h=null===(m=this.mixStorePolicy.s3Policy)||void 0===m?void 0:m.thumbPolicy)||void 0===h?void 0:h.imagethumb).replace("{cdnDomain}",this.mixStorePolicy.s3Policy.dlcdn).replace("{objectName}",T).replace("{x}",i.width.toString()).replace("{y}",i.height.toString());if(1===A&&this.mixStorePolicy.nosPolicy&&get(this.mixStorePolicy,"nosPolicy.thumbPolicy.imagethumb"))return(null===(v=null===(u=this.mixStorePolicy.nosPolicy)||void 0===u?void 0:u.thumbPolicy)||void 0===v?void 0:v.imagethumb).replace("{cdnDomain}",this.mixStorePolicy.nosPolicy.dlcdn).replace("{objectName}",T).replace("{x}",i.width.toString()).replace("{y}",i.height.toString())}return t.includes("?")?t+`&imageView&thumbnail=${i.width}x${i.height}`:t+`?imageView&thumbnail=${i.width}x${i.height}`}getVideoCoverUrl(t,i){var o,m,h,u,v;if(!new RegExp(/http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- ./?%&=]*)?/).test(t))return this.logger.error("illegal file url:"+t),t;var[I,_,M,E,S,T,C,N]=/^(?:([A-Za-z]+):)?(\/{0,3})([0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/.exec(t);if(null===(o=this.grayConfig)||void 0===o?void 0:o.mixStoreEnable){var A=this._getUrlType(t);if(2===A&&this.mixStorePolicy.s3Policy&&get(this.mixStorePolicy,"s3Policy.thumbPolicy.vframe"))return(null===(h=null===(m=this.mixStorePolicy.s3Policy)||void 0===m?void 0:m.thumbPolicy)||void 0===h?void 0:h.vframe).replace("{cdnDomain}",this.mixStorePolicy.s3Policy.dlcdn).replace("{objectName}",T).replace("{x}",i.width.toString()).replace("{y}",i.height.toString()).replace("{offset}","0").replace("{type}","png");if(1===A&&this.mixStorePolicy.nosPolicy&&get(this.mixStorePolicy,"nosPolicy.thumbPolicy.vframe"))return(null===(v=null===(u=this.mixStorePolicy.nosPolicy)||void 0===u?void 0:u.thumbPolicy)||void 0===v?void 0:v.vframe).replace("{cdnDomain}",this.mixStorePolicy.nosPolicy.dlcdn).replace("{objectName}",T).replace("{x}",i.width.toString()).replace("{y}",i.height.toString()).replace("{offset}","0").replace("{type}","png")}return t.includes("?")?t+`&vframe&offset=0&resize=${i.width}x${i.height}&type=png`:t+`?vframe&offset=0&resize=${i.width}x${i.height}&type=png`}getPrivateUrl(t){var i;if(!new RegExp(/http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- ./?%&=]*)?/).test(t))return this.logger.error("illegal file url:"+t),"";var[o,m,h,u,v,I,_,M]=/^(?:([A-Za-z]+):)?(\/{0,3})([0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/.exec(t);if(null===(i=this.grayConfig)||void 0===i?void 0:i.mixStoreEnable){var E=this._getUrlType(t);return 2===E&&this.mixStorePolicy.s3Policy&&(t=this.mixStorePolicy.s3Policy.cdnSchema.replace("{cdnDomain}",this.mixStorePolicy.s3Policy.dlcdn).replace("{objectName}",I)),1===E&&this.mixStorePolicy.nosPolicy&&(t=this.mixStorePolicy.nosPolicy.cdnSchema.replace("{cdnDomain}",this.mixStorePolicy.nosPolicy.dlcdn).replace("{objectName}",I)),t}var{downloadUrl:S,downloadHostList:T,nosCdnEnable:C}=this.config,N=this.config.cdn.cdnDomain,A=this.config.cdn.objectNamePrefix?decodeURIComponent(this.config.cdn.objectNamePrefix):"",O=decodeURIComponent(I),R=O.indexOf(A);if(N&&R>-1&&C)return`${m}:${h}${N}/${O.slice(R)}`;if(T.includes(u)&&I.includes("/")){var V=I.indexOf("/"),k=I.substring(0,V),P=I.substring(V+1);return S.replace("{bucket}",k).replace("{object}",P)}var L=T.filter((t=>"string"==typeof u&&u.includes(t)))[0],w=L?u.replace(L,"").replace(/\W/g,""):null;return w?S.replace("{bucket}",w).replace("{object}",I):t}getOriginUrl(t){return __awaiter(this,void 0,void 0,(function*(){return"string"==typeof t&&t.includes("_im_url=1")?(yield this.core.sendCmd("getOriginUrl",{nosSafeUrlTag:{safeUrl:t}})).content.nosSafeUrlTag.originUrl:t}))}getFileToken(t){return __awaiter(this,void 0,void 0,(function*(){validate({type:{type:"number",min:2,max:3},urls:{type:"array",required:!1,itemType:"string"}},t);var i=this.mixStorePolicy.nosPolicy?this.mixStorePolicy.nosPolicy.authPolicy.policyType:null,o=this.mixStorePolicy.s3Policy?this.mixStorePolicy.s3Policy.authPolicy.policyType:null;if(i===String(-1)&&o===String(-1))throw this.logger.error("don't need token"),new Error("don't need token");if(2===t.type){if(i&&i.indexOf(String(2))>=0||o&&o.indexOf(String(2))>0)return this.mixStorage.getFileAuthToken(t);throw this.logger.error("don't support time token "),new Error("don't support type time token ")}if(!t.urls||!t.urls.length)throw this.logger.error("urls is required when urls token"),new Error("urls is required when urls token");var m=[],h=[];if(t.urls.forEach((t=>{var i=this._getUrlType(t);1===i&&h.push(t),2===i&&m.push(t)})),(!o||0!==m.length&&o.indexOf(String(3))<0)&&(this.logger.warn("s3 url don't support url token"),m=[]),(!i||0!==h.length&&i.indexOf(String(3))<0)&&(this.logger.warn("nos url don't support url token"),h=[]),0===m.length&&0===h.length)throw this.logger.error("not support urls"),new Error("not support urls");if(0===m.length||0===h.length)return t.urls=JSON.stringify(t.urls),this.mixStorage.getFileAuthToken(t)}))}_getUrlType(t){return this.mixStorePolicy.nosPolicy&&this.mixStorePolicy.nosPolicy.dlcdns.some((i=>t.indexOf(i)>=0))?1:this.mixStorePolicy.s3Policy&&this.mixStorePolicy.s3Policy.dlcdns.some((i=>t.indexOf(i)>=0))?2:null}getNosAccessToken(t){return validate({url:{type:"string",allowEmpty:!1}},t),this.nos.getNosAccessToken(t)}deleteNosAccessToken(t){return validate({token:{type:"string",allowEmpty:!1}},t),this.nos.deleteNosAccessToken(t)}get grayConfig(){return this.mixStorage.grayConfig}get mixStorePolicy(){return this.mixStorage.mixStorePolicy}process(t){var i=get(t,"error.detail.ignore");return t.error&&!i?Promise.reject(t.error):Promise.resolve(t)}}class V2NIMStorageServiceImpl extends V2Service{constructor(t){super("V2NIMStorageService",t),this.sceneMap={nim_default_profile_icon:{sceneName:"nim_default_profile_icon",expireTime:0},nim_default_im:{sceneName:"nim_default_im",expireTime:0},nim_system_nos_scene:{sceneName:"nim_system_nos_scene",expireTime:0},nim_security:{sceneName:"nim_security",expireTime:0}},this.uploadingMessageInfo={},this.core=t,this.core._registerDep(CloudStorageService,"cloudStorage"),this.core._registerDep(V2NIMStorageUtil,"V2NIMStorageUtil")}addCustomStorageScene(t,i){return this.checkV2(),validate({sceneName:{type:"string",allowEmpty:!1},expireTime:{type:"number",min:0}},{sceneName:t,expireTime:i},"",!0),this.sceneMap[t]={sceneName:t,expireTime:i},{sceneName:t,expireTime:i}}getStorageSceneList(){return this.checkV2(),Object.values(this.sceneMap)}getStorageScene(t){return t&&this.sceneMap[t]||this.sceneMap.nim_default_im}hasStorageScene(t){return void 0!==this.sceneMap[t]}createUploadFileTask(t){if(this.checkV2(),"string"==typeof t.fileObj&&0===t.fileObj.indexOf("nim-external")){var i=document.getElementById(t.fileObj);i&&i.files&&i.files[0]&&(t.fileObj=i.files[0])}return{taskId:Pe(),uploadParams:t}}uploadFile(t,i){return __awaiter(this,void 0,void 0,(function*(){return this.checkV2(),validate({taskId:{type:"string",allowEmpty:!1}},t,"fileTask",!0),(yield this._uploadFile(t,i))[0]}))}uploadFileWithMetaInfo(t,i){return __awaiter(this,void 0,void 0,(function*(){return this.checkV2(),validate({taskId:{type:"string",allowEmpty:!1}},t,"fileTask",!0),function formatV2NIMFileMetaInfo(t){var{url:i,name:o,size:m,ext:h,md5:u,h:v,w:I,orientation:_,dur:M,audioCodec:E,videoCodec:S,container:T}=t;return JSON.parse(JSON.stringify({url:i,name:o,size:m,ext:h,md5:u,height:v,width:I,orientation:_,duration:M,audioCodec:E,videoCodec:S,container:T}))}((yield this._uploadFile(t,i))[1])}))}_uploadFile(t,i,o){var m;return __awaiter(this,void 0,void 0,(function*(){if(!this.core.cloudStorage||!this.core.cloudStorage.uploadFile)throw new Error('Service "cloudStorage" does not exist');var{uploadParams:h,taskId:u}=t,{file:v,path:I}=getFileOrPath(h.fileObj),{fileType:_}=o||{};if(this.uploadingMessageInfo[u])throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_RESOURCE_ALREADY_EXIST,detail:{reason:"V2NIMStorageService.uploadFile: repeat upload"}});try{var M={};v?M.file=v:I&&(0===(null==I?void 0:I.indexOf("nim-external"))?M.fileInput=I:M.filePath=I);var E=this.getStorageScene(h.sceneName);if(M.nosScenes=E.sceneName,M.nosSurvivalTime=E.expireTime,M.type=1===_?"image":2===_?"audio":3===_?"video":"file",M.file&&this.core.pluginMap["browser-md5-file"]){var S=yield this.getFileMd5(this.core.pluginMap["browser-md5-file"],u,M.file);M.md5=S}M.onUploadProgress=t=>{"function"==typeof i&&i(Math.round(100*t.percentage))},M.onUploadStart=t=>{var i;if(null===(i=this.uploadingMessageInfo[u])||void 0===i?void 0:i.abort)return t.abort(),void delete this.uploadingMessageInfo[u];this.uploadingMessageInfo[u]={abort:!1,task:t}},this.uploadingMessageInfo[u]={abort:!1};var T=yield this.core.cloudStorage.uploadFile(M);if(null===(m=this.uploadingMessageInfo[u])||void 0===m?void 0:m.abort)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_CANCELLED,detail:{reason:"upload file aborted"}});return delete this.uploadingMessageInfo[u],[T.url,T]}catch(t){throw delete this.uploadingMessageInfo[u],this.core.logger.error("sendFile:: upload File error or abort.",t),t}}))}cancelUploadFile(t){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),yield this._cancelUploadFile(t.taskId)}))}_cancelUploadFile(t){return __awaiter(this,void 0,void 0,(function*(){this.checkV2();var i=this.uploadingMessageInfo[t];if(null==i?void 0:i.task)try{this.logger.log("V2NIMStorageService.cancelUploadFile: uploadInfo task exist"),yield i.task.abort(),delete this.uploadingMessageInfo[t]}catch(i){delete this.uploadingMessageInfo[t],this.core.logger.error("cancelMessageAttachmentUpload::abort error.",i)}else{if(!i)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_RESOURCE_NOT_EXIST,detail:{reason:"V2NIMStorageService.cancelUploadFile: uploadInfo not exist"}});this.logger.log("V2NIMStorageService.cancelUploadFile: uploadInfo task not exist"),i.abort=!0}}))}getFileMd5(t,i,o){return __awaiter(this,void 0,void 0,(function*(){return new Promise(((m,h)=>{var u,v=new t;(null===(u=this.uploadingMessageInfo[i])||void 0===u?void 0:u.abort)?h(new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_CANCELLED,detail:{reason:"upload file aborted"}})):this.uploadingMessageInfo[i]={abort:!1,task:v};try{v.md5(o,((t,i)=>{"aborted"===t?h(new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_CANCELLED,detail:{reason:t}})):t?h(new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INTERNAL,detail:{reason:"md5 calculate error in callback",rawError:t}})):m(i)}))}catch(t){h(new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INTERNAL,detail:{reason:"md5 calculate error",rawError:t}}))}}))}))}shortUrlToLong(t){return __awaiter(this,void 0,void 0,(function*(){return this.checkV2(),this.core.cloudStorage.getOriginUrl(t)}))}getImageThumbUrl(t,i){return __awaiter(this,void 0,void 0,(function*(){return this.core.V2NIMStorageUtil.getImageThumbUrl(t,i)}))}getVideoCoverUrl(t,i){return __awaiter(this,void 0,void 0,(function*(){return this.core.V2NIMStorageUtil.getVideoCoverUrl(t,i)}))}}class V2NIMMessageCreatorImpl extends V2Service{constructor(t){super("V2NIMMessageCreator",t),this.name="V2NIMMessageCreator",this.defaultNosSceneName="nim_default_im",this.core=t}createMessage(t,i){return Object.assign(Object.assign(Object.assign({messageClientId:Pe(),messageType:t,createTime:this.core.timeOrigin.getNTPTime(),sendingState:0,messageStatus:{errorCode:200},messageSource:0,fromClientType:16,isSelf:!0},i),i.attachment?{attachment:Object.assign(Object.assign({},i.attachment),{raw:attachmentToRaw(t,i.attachment)})}:{}),{senderId:"",receiverId:"",conversationType:0,conversationId:"",messageServerId:"",messageConfig:Object.assign({unreadEnabled:!0,roamingEnabled:!0,readReceiptEnabled:!1,lastMessageUpdateEnabled:!0,historyEnabled:!0,onlineSyncEnabled:!0,offlineEnabled:!0},i.messageConfig),pushConfig:Object.assign({pushEnabled:!0,pushNickEnabled:!0,forcePush:!1},i.pushConfig),routeConfig:Object.assign({routeEnabled:!0},i.routeConfig),antispamConfig:Object.assign({antispamEnabled:!0},i.antispamConfig)})}createTextMessage(t){return this.checkV2(),validate({text:{type:"string",allowEmpty:!1}},{text:t},"",!0),this.createMessage(0,{text:t})}createImageMessage(t,i,o,m,h){this.checkV2(),validate(mi,{name:i,sceneName:o,width:m,height:h},"",!0);var u=this.createGenericFileMessageAttachment(t,i,o,void 0,m,h,"jpeg");return this.createMessage(1,{attachment:u,attachmentUploadState:0})}createAudioMessage(t,i,o,m){this.checkV2(),validate(li,{name:i,sceneName:o,duration:m},"",!0);var h=this.createGenericFileMessageAttachment(t,i,o,m,void 0,void 0,"aac");return this.createMessage(2,{attachment:h,attachmentUploadState:0})}createVideoMessage(t,i,o,m,h,u){this.checkV2(),validate(pi,{name:i,sceneName:o,duration:m,width:h,height:u},"",!0);var v=this.createGenericFileMessageAttachment(t,i,o,m,h,u,"mp4");return this.createMessage(3,{attachment:v,attachmentUploadState:0})}createFileMessage(t,i,o){this.checkV2(),validate(di,{name:i,sceneName:o},"",!0);var m=this.createGenericFileMessageAttachment(t,i,o,void 0,void 0,void 0,"txt");return this.createMessage(6,{attachment:m,attachmentUploadState:0})}createGenericFileMessageAttachment(t,i,o,m,h,u,v){if(o=o||this.defaultNosSceneName,!this.core.V2NIMStorageService.hasStorageScene)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_MISUSE,detail:{reason:"V2NIMStorageService not exist"}});if(!this.core.V2NIMStorageService.hasStorageScene(o))throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"sceneName: "+o+" has not been added"}});var{file:I,path:_}=getFileOrPath(t),M=Object.assign(Object.assign(Object.assign({name:i,uploadState:0,sceneName:o||this.defaultNosSceneName},m?{duration:m}:{}),h?{width:h}:{}),u?{height:u}:{});if(I){var E=I.name.lastIndexOf("."),S=-1===E?I.name:I.name.substring(0,E);M.name=M.name||S,M.size=I.size,M.ext=`.${getFileExtension(I.name)||getFileExtension(i||"")||v}`}else if(_){var T=_.lastIndexOf("/"),C=_.lastIndexOf("."),N=-1===C?_.substring(T+1):_.substring(T+1,C);M.name=M.name||N,M.ext=`.${getFileExtension(_)||getFileExtension(i||"")||v}`}return M=JSON.parse(JSON.stringify(M)),_?M.path=_:I&&(M.file=I),M}createLocationMessage(t,i,o){return this.checkV2(),validate({latitude:{type:"number",allowEmpty:!1},longitude:{type:"number",allowEmpty:!1},address:{type:"string",allowEmpty:!1}},{latitude:t,longitude:i,address:o},"",!0),this.createMessage(4,{attachment:{latitude:t,longitude:i,address:o}})}createCustomMessage(t,i){return this.checkV2(),validate({text:{type:"string"}},{text:t},"",!0),validate({rawAttachment:{type:"string"}},{rawAttachment:i},"",!0),this.createMessage(100,{text:t,attachment:{raw:i}})}createCustomMessageWithAttachment(t,i){return this.checkV2(),validate({raw:{type:"string"}},t,"attachment",!0),validate({subType:{type:"number",min:0,required:!1}},{subType:i},"",!0),this.createMessage(100,i?{attachment:t,subType:i}:{attachment:t})}createCallMessage(t,i,o,m,h){return this.checkV2(),validate({type:{type:"number",allowEmpty:!1}},{type:t},"",!0),validate({channelId:{type:"string",allowEmpty:!1}},{channelId:i},"",!0),validate({status:{type:"number",allowEmpty:!1}},{status:o},"",!0),validate({durations:{type:"array",allowEmpty:!1}},{durations:m},"",!0),this.createMessage(12,{text:h||"",attachment:{type:t,channelId:i,durations:m,status:o}})}createForwardMessage(t){this.checkV2();if(!t||[11,5,7,10].includes(t.messageType))return null;var i={messageClientId:Pe(),messageType:t.messageType};return t.text&&(i.text=t.text),t.attachment&&(i.attachment=t.attachment),t.attachment&&"uploadState"in t.attachment&&(i.attachmentUploadState=t.attachment.uploadState),this.createMessage(t.messageType,i)}createTipsMessage(t){return this.checkV2(),validate({text:{type:"string",allowEmpty:!1}},{text:t},"",!0),this.createMessage(10,{text:t})}}class V2NIMMessageAttachmentCreatorImpl{constructor(){this.name="V2NIMMessageAttachmentCreator"}createLocationMessageAttachment(t,i,o){return{latitude:"number"==typeof t?t:0,longitude:"number"==typeof i?i:0,address:"string"==typeof o?o:""}}createCustomMessageAttachment(t){return{raw:"string"==typeof t?t:""}}}class V2NIMClientAntispamUtilImpl{constructor(t){this.config={enable:!1},this.name="V2NIMClientAntispamUtil",this.core=t}setOptions(t){this.config=Object.assign(this.config,t)}reset(t){"destroy"===t&&(this.vocabInfo=void 0)}downloadLocalAntiSpamVocabs(){return __awaiter(this,void 0,void 0,(function*(){if(this.config.enable&&!this.vocabInfo)try{var t=yield this.core.sendCmd("v2DownloadLocalAntiSpamVocabs",{tag:{version:0,md5:""}});this.vocabInfo=Object.assign(Object.assign({},t.content.data),{thesaurus:JSON.parse(t.content.data.thesaurus).thesaurus})}catch(t){this.core.logger.warn("V2NIMLocalAntispamUtil::downloadLocalAntiSpamVocabs error",t)}}))}checkTextAntispam(t,i="**"){if(!this.config.enable)return{operateType:0,replacedText:t};if(validate({text:{type:"string",required:!0,allowEmpty:!1},replace:{type:"string"}},{text:t,replace:i},"",!0),!this.vocabInfo)return{operateType:0,replacedText:t};for(var o=t,m=0;m<this.vocabInfo.thesaurus.length;m++){var h=this.filterContent(o,this.vocabInfo.thesaurus[m],i);if(o=h.replacedText,2===h.operateType||3===h.operateType)return h}return{operateType:o===t?0:1,replacedText:o}}filterContent(t,i,o){for(var m=0;m<i.keys.length;m++){var h=i.keys[m],u=h.match||i.match,v=h.operate||i.operate,I=void 0;try{I=this.matchContent(t,h.key,u,v,o)}catch(t){}if(I&&(t=I.replacedText,2===I.operateType||3===I.operateType))return I}return{operateType:1,replacedText:t}}matchContent(t,i,o,m,h){var u=!1,v=null;if(1===o){if(t.indexOf(i)>=0){u=!0;var I=i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");v=new RegExp(I,"g")}}else 2===o&&(v=new RegExp(i,"g")).test(t)&&(u=!0);if(u&&v)switch(m){case 1:return{operateType:1,replacedText:t.replace(v,h)};case 2:return{operateType:2,replacedText:t};case 3:return{operateType:3,replacedText:t}}return{operateType:0,replacedText:t}}}class YSFServiceImpl extends V2Service{constructor(t){super("YSFService",t),this.core._registerDep(V2NIMConversationIdUtilImpl,"V2NIMConversationIdUtil"),this.core._registerDep(V2NIMMessageCreatorImpl,"V2NIMMessageCreator"),this.core._registerDep(V2NIMMessageAttachmentCreatorImpl,"V2NIMMessageAttachmentCreator"),this.core._registerDep(V2NIMClientAntispamUtilImpl,"V2NIMClientAntispamUtil"),this.core._registerDep(V2NIMStorageServiceImpl,"V2NIMStorageService"),this.sendUtil=new SendUtil(this.core,this),this.fileUtil=new FileUtil(this.core),this.model=new V2NIMMessageModelImpl,this.notificationUtil=new NotificationUtil(this.core),registerParser({cmdMap:Hi,cmdConfig:zi})}emit(t,...i){var o,m=`${this.name}::emit ${t.toString()}`;if("onSendMessage"===t){var h=i[0];this.logger.log(`${m}`,`${h.messageClientId}/${h.messageServerId};createTime:${h.createTime};`,`sendingState:${h.sendingState};attachmentUploadState:${h.attachmentUploadState||0};messageStatus:${null===(o=h.messageStatus)||void 0===o?void 0:o.errorCode}`)}else if("onReceiveMessages"===t){var u=i[0];this.logger.log(`${m}`,u.map((t=>`${t.messageClientId}/${t.messageServerId};createTime:${t.createTime}`)))}else if("onReceiveCustomNotifications"===t){var v=i[0];this.logger.log(`${m}`,v.map((t=>`sender:${t.senderId};receiver:${t.receiverId};ctype:${t.conversationType};time:${t.timestamp}`)))}else this.logger.log(`${m}`,...i);return super.emit(t,...i)}sendMessage(t,i,o={},m){return __awaiter(this,void 0,void 0,(function*(){validate({message:{type:"object"}},{message:t},"",!0),t.messageClientId=t.messageClientId||Pe(),validate($t,{conversationId:i,message:t,params:o},"",!0),validateConversationId(this.core.account,i);var h=this.core.timeOrigin.getTimeNode(),{messageBeforeSend:u,clientAntispamResult:v,hiddenParams:I}=this.sendUtil.prepareMessage(t,i,o),_=yield this.sendUtil.doSendMessage({apiCallingTimeNode:h,messageBeforeSend:u,clientAntispamResult:v,hiddenParams:I,progress:m});return _.message.senderId===_.message.receiverId&&this.markMsgsAck([_.message]),_}))}sendCustomNotification(t,i,o){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validateConversationId(this.core.account,t),validate(Yi,{content:i,params:o},"",!0);var m=this.notificationUtil.generateNotificationTag(t,i,o);m.type=100,yield this.core.sendCmd("ysfSendCustomNotification",{tag:m})}))}sendMessageFn(t){}cancelMessageAttachmentUpload(t){return this.fileUtil.cancelMessageAttachmentUpload(t)}markMsgsAck(t){if(t&&t.length>0){var i=t.map((t=>t.messageServerId)).filter((t=>t&&"0"!==t));0!==i.length&&this.core.sendCmd("ysfBatchMarkRead",{sid:101,cid:2,ids:i})}}markNotificationAck(t){if(t&&t.length>0){var i=t.map((t=>t.idServer)).filter((t=>t&&"0"!==t));0!==i.length&&this.core.sendCmd("ysfBatchMarkRead",{sid:101,cid:3,ids:i})}}ysfOnMsgHandler(t){var i=fillIdServer(t,t.content.data,"messageServerId"),o=completeMessage(this.core,i);delete o.__clientExt,this.emit("onReceiveMessages",[o]),this.model.upsertMessages([o]),this.markMsgsAck([o])}ysfSyncOfflineMsgsHandler(t){var i=t.content.datas;i=i.map((t=>completeMessage(this.core,t))),this.markMsgsAck(i),this.emit("onReceiveMessages",i),this.model.upsertMessages(i)}ysfOnSysNotificationHandler(t){var i=fillIdServer(t,t.content.data,"idServer");this.markNotificationAck([i]);var o=this.processSystemNotification(i);o&&this.emit("onReceiveCustomNotifications",[o])}processSystemNotification(t){var i=Object.assign(Object.assign({},t),{conversationType:1});return delete i.type,i}ysfSyncSysNotificationHandler(t){this.markNotificationAck(t.content.datas);var i=t.content.datas.sort(((t,i)=>t.timestamp-i.timestamp)).map((t=>this.processSystemNotification(t))).filter((t=>t));i&&this.emit("onReceiveCustomNotifications",i)}}class SendUtil{constructor(t,i){this.uploadingMessageInfo={},this.core=t,this.service=i}prepareMessage(t,i,o,m){var h=this.checkIfResend(t),u=this.generateSendMessage({message:t,params:o,resend:h,conversationId:i,replyMessage:m}),v=Object.assign({},o.targetConfig?{targetConfig:o.targetConfig}:{}),{clientAntispamResult:I,text:_}=this.checkIfAntispam(o,u);return u.text=_,u.clientAntispamHit=!!I&&3===I.operateType,{messageBeforeSend:u,clientAntispamResult:I,hiddenParams:v}}checkIfAntispam(t,i){var o,m=i.text;if(t.clientAntispamEnabled&&(0===i.messageType||10===i.messageType))if(1===(o=this.core.V2NIMClientAntispamUtil.checkTextAntispam?this.core.V2NIMClientAntispamUtil.checkTextAntispam(i.text||"",t.clientAntispamReplace):{operateType:0,replacedText:""}).operateType)m=o.replacedText;else if(2===o.operateType)throw this.service.emit("onSendMessage",Object.assign(Object.assign({},i),{sendingState:2,messageStatus:{errorCode:Ee.V2NIM_ERROR_CODE_CLIENT_ANTISPAM}})),new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_CLIENT_ANTISPAM,detail:{reason:"sendMessage: text intercepted by client antispam"}});return{clientAntispamResult:o,text:m}}doMsgReceiveReport(t,i){if(t.senderId!==this.core.account){var o=get(t,"__clientExt.statistics.apiCallingTime")||0,m=get(t,"__clientExt.statistics.sendTime")||0,h=get(t,"__clientExt.statistics.attachUploadDuration")||0,u=this.core.timeOrigin.getNTPTime(),v=t.createTime,I=this.core.timeOrigin.checkNodeReliable(i.__receiveTimeNode)?this.core.timeOrigin.getNTPTime(i.__receiveTimeNode):u;this.core.reporter.report("msgReceive",{msgId:t.messageServerId,clientId:t.messageClientId,serverTime:t.createTime,receiveTime:I,fromAccid:t.senderId,toAccid:t.receiverId,type:conversationTypeV2ToV1(t.conversationType),tid:1===t.conversationType?"":t.receiverId,apiCallingTime:o,sendTime:m,attachUploadDuration:h,callbackTime:u,preHandleTime:u,result:200,failReason:"",rt:u-v})}}checkIfResend(t){var i=this.service.model.getMessageById(t.messageClientId),o=!1;if("messageServerId"in t&&"0"!==t.messageServerId&&""!==t.messageServerId)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"sendMessage: message has already been sent"}});if(i&&"messageServerId"in i&&"0"!==i.messageServerId&&""!==i.messageServerId)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"sendMessage: message has already been sent"}});return i&&(o=!0),o}doSendMessage(t){var i;return __awaiter(this,void 0,void 0,(function*(){var o,m,{apiCallingTimeNode:h,messageBeforeSend:u,clientAntispamResult:v,hiddenParams:I,progress:_}=t,M={},E=this.service instanceof YSFServiceImpl;if(E)o="ysfSendMessage";else if(1===u.conversationType)o="v2SendP2pMessage";else if(2===u.conversationType)o="v2SendTeamMessage";else{if(3!==u.conversationType)throw new ValidateErrorV2({detail:{reason:`conversationType: ${u.conversationType} is not supported`}});o="v2SendSuperTeamMessage"}if(this.service.sendMessageFn(u),!E&&this.core.eventBus.emit("forwardSend/V2NIMMessageService/sendMsg",u),!u.attachment||!("uploadState"in u.attachment)||u.attachment.url||0!==u.attachment.uploadState&&2!==u.attachment.uploadState)this.service.emit("onSendMessage",u);else{var S=Date.now();try{u.attachmentUploadState=3,u.attachment.uploadState=3,this.service.emit("onSendMessage",u),yield this.service.fileUtil.doSendFile(u,_),u.attachmentUploadState=1,u.attachment.uploadState=1,this.service.emit("onSendMessage",u)}catch(t){throw u.attachmentUploadState=2,u.attachment.uploadState=2,u.sendingState=2,u.messageStatus={errorCode:t.code||Ee.V2NIM_ERROR_CODE_UNKNOWN},this.service.emit("onSendMessage",u),M.attachUploadDuration=Date.now()-S,this.doSendMessageFailed(h,M,u,t),t}M.attachUploadDuration=Date.now()-S}this.core.timeOrigin.checkNodeReliable(h)&&(M.apiCallingTime=this.core.timeOrigin.getNTPTime(h),M.sendTime=this.core.timeOrigin.getNTPTime(),u.__clientExt={statistics:M});try{m=yield this.core.sendCmd(o,{tag:Object.assign({},u,I)})}catch(t){throw this.doSendMessageFailed(h,M,u,t),u.sendingState=2,u.messageStatus={errorCode:t.code||Ee.V2NIM_ERROR_CODE_UNKNOWN},this.service.emit("onSendMessage",u),t}var T=get(m,"content.data.errorCode"),C=Object.assign(Object.assign(Object.assign(Object.assign({},u),m.content.data),u.aiConfig?{aiConfig:Object.assign(Object.assign({},u.aiConfig),(null===(i=m.content.data)||void 0===i?void 0:i.aiConfig)||{})}:{}),{sendingState:1,messageStatus:{errorCode:T&&200!==T?T:200}});this.service.sendMessageFn(C),!E&&this.core.eventBus.emit("forwardSend/V2NIMMessageService/sendMsg",C),this.doMsgSendReport(h,M,C);var N=C.antispamResult;return N&&(C.messageStatus.errorCode=Ee.V2NIM_ERROR_CODE_SERVER_ANTISPAM),delete C.antispamResult,this.service.emit("onSendMessage",C),Object.assign(Object.assign({message:C},N?{antispamResult:N}:{}),v?{clientAntispamResult:v}:{})}))}doSendMessageFailed(t,i,o,m){var h=Object.assign(Object.assign({},o),{sendingState:2});this.core.eventBus.emit("forwardSend/V2NIMMessageService/sendMsg",h),this.service.sendMessageFn(h),this.doMsgSendReport(t,i,o,m)}doMsgSendReport(t,i,o,m){i.apiCallingTime=this.core.timeOrigin.getNTPTime(t),i.sendTime=this.core.timeOrigin.getNTPTime();var h=this.core.timeOrigin.getNTPTime(),u=get(m,"detail.reason");this.core.reporter.report("msgSend",{msgId:o.messageServerId,clientId:o.messageClientId,msgTime:o.createTime,fromAccid:o.senderId,toAccid:o.receiverId,type:conversationTypeV2ToV1(o.conversationType),tid:1===o.conversationType?"":o.receiverId,result:m?m.code:200,failReason:u||(null==m?void 0:m.message)||"",rt:h-i.apiCallingTime,apiCallingTime:i.apiCallingTime,sendTime:i.sendTime,attachUploadDuration:i.attachUploadDuration,apiCallbackTime:h})}generateSendMessage(t){var i,o,{conversationId:m,replyMessage:h,resend:u,message:v,params:I}=t,_={};if(h){var M=h.threadRoot;_={threadReply:{senderId:h.senderId,receiverId:h.receiverId,messageServerId:h.messageServerId,createTime:h.createTime,messageClientId:h.messageClientId,conversationType:h.conversationType,conversationId:h.conversationId},threadRoot:{senderId:M?M.senderId:h.senderId,receiverId:M?M.receiverId:h.receiverId,messageServerId:M?M.messageServerId:h.messageServerId,createTime:M?M.createTime:h.createTime,messageClientId:M?M.messageClientId:h.messageClientId,conversationType:M?M.conversationType:h.conversationType,conversationId:M?M.conversationId:h.conversationId}}}var E=this.core.V2NIMConversationIdUtil.parseConversationType(m),S=this.core.V2NIMConversationIdUtil.parseConversationTargetId(m);I.pushConfig&&!0!==I.pushConfig.forcePush&&(delete I.pushConfig.forcePushContent,delete I.pushConfig.forcePushAccountIds);var T={},C={};if(I.aiConfig){var N=get(I,"aiConfig.content.msg"),A=get(I,"aiConfig.content.type")||0;N?C={msg:N,type:A}:void 0===N&&0===v.messageType&&(C={msg:v.text||"",type:A}),(T=Object.assign({aiStreamStatus:0,aiStream:!1},I.aiConfig)).aiStatus=1,void 0!==C.msg&&(T.content=C)}var O=null===(o=null===(i=this.core.V2NIMUserService)||void 0===i?void 0:i.model)||void 0===o?void 0:o.getUser(this.core.account),R=(null==O?void 0:O.updateTime)||0;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},v),_),{messageConfig:Object.assign(Object.assign({},v.messageConfig),I.messageConfig),routeConfig:Object.assign(Object.assign({},v.routeConfig),I.routeConfig),pushConfig:Object.assign(Object.assign({},v.pushConfig),I.pushConfig),antispamConfig:Object.assign(Object.assign({},v.antispamConfig),I.antispamConfig),robotConfig:Object.assign(Object.assign({},v.robotConfig),I.robotConfig)}),T&&T.accountId?{aiConfig:T}:{}),v.attachment?{attachment:Object.assign({},v.attachment)}:{}),{resend:u,senderId:this.core.account,conversationType:E,receiverId:S,conversationId:this.core.V2NIMConversationIdUtil.messageConversationId({conversationType:E,senderId:this.core.account,receiverId:S})}),R?{userUpdateTime:R}:{}),{sendingState:3})}}class ModifyUtil{constructor(t,i){this.core=t,this.service=i}checkIfModify(t,i){if("0"===t.messageServerId)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"modifyMessage: messageServerId cannot be empty"}});if(![0,1,2,3,4,6,10,12,100].includes(t.messageType))throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:`modifyMessage: messageType ${t.messageType} not correct`}});if([0,1,2,3,6,10,12].includes(t.messageType)&&i.attachment)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:`modifyMessage: messageType ${t.messageType} can not modify attachment`}});var o=["subType","text","serverExtension","attachment"];if(!o.some((t=>void 0!==get(i,t))))throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"modifyMessage: missing modified params"}});if(o.every((o=>"attachment"===o?t.attachment&&i.attachment?attachmentToRaw(t.messageType,t.attachment)===attachmentToRaw(t.messageType,i.attachment):!i.attachment:get(t,o)===get(i,o))))throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"modifyMessage: no change"}})}prepareMessage(t,i){var o=this.generateSendMessage(t,i),{clientAntispamResult:m,text:h}=this.checkIfAntispam(i,o);return o.text=h,o.clientAntispamHit=!!m&&3===m.operateType,{messageBeforeSend:o,clientAntispamResult:m}}modifyMessage(t,i){return __awaiter(this,void 0,void 0,(function*(){var o;if(1===t.conversationType)o="v2MessageP2pModify";else if(2===t.conversationType)o="v2MessageTeamModify";else{if(3!==t.conversationType)throw new ValidateErrorV2({detail:{reason:`conversationType: ${t.conversationType} is not supported`}});o="v2MessageSuperTeamModify"}var m=yield this.core.sendCmd(o,{tag:t});if(i&&3===i.operateType)return{errorCode:Ee.V2NIM_ERROR_CODE_CLIENT_ANTISPAM,clientAntispamResult:i};var h=Object.assign(Object.assign({},t),m.content.data),u=h.antispamResult;if(u)return Object.assign({errorCode:Ee.V2NIM_ERROR_CODE_SERVER_ANTISPAM,antispamResult:u},i?{clientAntispamResult:i}:{});delete h.antispamResult;var v=completeMessage(this.core,h);return this.service.model.upsertMessages([v]),this.core.eventBus.emit("V2NIMMessageService/modifyMsg",v),this.core.eventBus.emit("forwardSend/V2NIMMessageService/modifyMsg",v),Object.assign(Object.assign({errorCode:200,message:v},u?{antispamResult:u}:{}),i?{clientAntispamResult:i}:{})}))}checkIfAntispam(t,i){var o,m=i.text;if(t.clientAntispamEnabled&&(0===i.messageType||10===i.messageType))if(1===(o=this.core.V2NIMClientAntispamUtil.checkTextAntispam?this.core.V2NIMClientAntispamUtil.checkTextAntispam(i.text||"",t.clientAntispamReplace):{operateType:0,replacedText:""}).operateType)m=o.replacedText;else if(2===o.operateType)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_CLIENT_ANTISPAM,detail:{reason:"sendMessage: text intercepted by client antispam"}});return{clientAntispamResult:o,text:m}}generateSendMessage(t,i){var o;return Object.assign(Object.assign({messageConfig:{lastMessageUpdateEnabled:null===(o=t.messageConfig)||void 0===o?void 0:o.lastMessageUpdateEnabled},routeConfig:Object.assign({routeEnabled:!0},i.routeConfig),pushConfig:Object.assign({pushEnabled:!0,pushNickEnabled:!0,forcePush:!1},i.pushConfig),antispamConfig:Object.assign({antispamEnabled:!0},i.antispamConfig)},i.attachment?{attachment:i.attachment}:{}),{conversationType:t.conversationType,senderId:t.senderId,receiverId:t.receiverId,createTime:t.createTime,messageClientId:t.messageClientId,messageServerId:t.messageServerId,messageType:t.messageType,subType:i.subType,text:i.text,serverExtension:i.serverExtension})}}class DeleteUtil{constructor(t,i){this.emitRevokeMessage=t=>{var i=t.map((t=>{var i=formatRevokeMessage(this.core,t);return 3===i.messageRefer.conversationType?this.core.eventBus.emit("V2NIMSync/updateTimetag",{deleteSuperTeamMsg:t.createTime}):this.core.eventBus.emit("V2NIMSync/updateTimetag",{recallMsg:t.createTime}),i}));i.forEach((t=>{this.service.model.deleteMessage(t.messageRefer.messageClientId)})),this.service.emit("onMessageRevokeNotifications",i),this.core.eventBus.emit("V2NIMMessageService/revokeMessages",i)},this.core=t,this.service=i,this.logger=t.logger}revokeMessage(t,i){return __awaiter(this,void 0,void 0,(function*(){if(validate(jt,{message:t,params:i},"",!0),validateConversationId(this.core.account,t.conversationId),1===t.conversationType&&t.senderId!==this.core.account)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"revokeMessage: p2p message senderId is not current user"}});if(!t.messageServerId||"0"===t.messageServerId)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"revokeMessage: cannot revoke message with invalid messageServerId: "+t.messageServerId}});var o=3===t.conversationType?"v2RevokeSuperTeamMessage":"v2RevokeMessage",m={1:7,2:8,3:12},h=Object.assign(Object.assign(Object.assign({},t),i),{attach:i&&i.serverExtension,sysMsgType:m[t.conversationType],opeAccount:this.core.account});yield this.core.sendCmd(o,{tag:h});var u={1:1,2:2,3:3},v=[JSON.parse(JSON.stringify({postscript:i&&i.postscript,revokeType:u[t.conversationType],revokeAccountId:this.core.account,serverExtension:i&&i.serverExtension,messageRefer:formatMessageRefer(this.core,t)}))];this.revokeMessagesFn(v),this.core.eventBus.emit("forwardSend/V2NIMMessageService/revokeMessage",h)}))}deleteMessage(t,i){return __awaiter(this,void 0,void 0,(function*(){if(validate(zt,t,"",!0),3===t.sendingState)this.service.fileUtil.cancelMessageAttachmentUpload(t);else if(1!==t.sendingState&&2!==t.sendingState)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:`deleteMessage: cannot delete message with sendingState: ${t.sendingState}`}});var o={messageRefer:formatMessageRefer(this.core,t),serverExtension:i},m=this.core.timeOrigin.getNTPTime();t.messageServerId&&"0"!==t.messageServerId&&1===t.sendingState&&(m=(yield this.core.sendCmd("v2DeleteMessage",{tag:o})).content.timetag);var h=[{serverExtension:i,messageRefer:formatMessageRefer(this.core,t),deleteTime:m}];this.core.eventBus.emit("forwardSend/V2NIMMessageService/deleteSelfMsgs",[Object.assign(Object.assign({},o),{deleteTime:m})]),this.deleteMessagesFn(h)}))}deleteMessages(t,i){return __awaiter(this,void 0,void 0,(function*(){validate(Yt,{messages:t},"",!0);var o=[],m=[];if(0===t.length)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"deleteMessages: message array length is 0"}});for(var h=t[0].conversationId,u=0;u<t.length;u++){if(3===t[u].sendingState)this.service.fileUtil.cancelMessageAttachmentUpload(t[u]);else if(1!==t[u].sendingState&&2!==t[u].sendingState)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:`deleteMessages: sendingState incorrect:${t[u].sendingState}, please check message at index: ${u}`}});if(u>=1&&t[u].conversationId!==h)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"deleteMessages: only allow to delete messages from same conversation"}});t[u].messageServerId&&"0"!==t[u].messageServerId?o.push(t[u]):m.push(t[u])}var v=this.core.timeOrigin.getNTPTime(),I=[...m];try{if(o.length>0){var _=yield this.core.sendCmd("v2DeleteMessages",{tag:o.map((t=>({messageRefer:t,serverExtension:i})))});v=_.content.timetag,I=[...I,...o]}}catch(t){if(0===m.length)throw t;this.logger.warn("V2NIMMessageService:deleteMessages: delete messages with serverId failed")}var M=I.map((t=>({serverExtension:i,messageRefer:formatMessageRefer(this.core,t),deleteTime:v})));this.core.eventBus.emit("forwardSend/V2NIMMessageService/deleteSelfMsgs",I.map((t=>({messageRefer:t,serverExtension:i,deleteTime:v})))),this.deleteMessagesFn(M)}))}revokeMessagesFn(t){t.forEach((t=>{this.service.model.deleteMessage(t.messageRefer.messageClientId)})),this.service.emit("onMessageRevokeNotifications",t),this.core.eventBus.emit("V2NIMMessageService/revokeMessages",t)}deleteMessagesFn(t){t.forEach((t=>{this.service.model.deleteMessage(t.messageRefer.messageClientId),this.core.eventBus.emit("V2NIMSync/updateTimetag",{deleteSelfMsgs:t.deleteTime})})),this.service.emit("onMessageDeletedNotifications",t),this.core.eventBus.emit("V2NIMMessageService/deleteMessages",t)}}class AIUtil{constructor(t,i){this.core=t,this.service=i,this.logger=t.logger}stopAIStreamMessage(t,i){var o;return __awaiter(this,void 0,void 0,(function*(){this.checkAI(),yield this.core.sendCmd("v2AIStopModelStreamCall",{tag:{serverId:t.messageServerId,clientId:t.messageClientId,type:t.conversationType,from:t.senderId,to:t.receiverId,aiAccount:null===(o=t.aiConfig)||void 0===o?void 0:o.accountId,opeType:i.operationType,updateContent:i.updateContent,messageTime:t.createTime}}),this.logger.log(`V2AIUtil::streamMessageStop,clientId:${t.messageClientId}`),this.core.V2NIMAIService.model.completeAiStream(t.messageClientId)}))}regenAIMessage(t,i){var o,m,h,u,v,I,_,M;return __awaiter(this,void 0,void 0,(function*(){this.checkAI();var E=this.core.V2NIMAIService.model.getAiStream(t.messageClientId);if(E){if(!(null==E?void 0:E.isComplete))throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_MISUSE,detail:{reason:`msg::regenAIMessage streamCache is not complete, msgId:${t.messageClientId}`}})}else if(-1===(null===(o=t.streamConfig)||void 0===o?void 0:o.status)||1===(null===(m=t.streamConfig)||void 0===m?void 0:m.status))throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_MISUSE,detail:{reason:`msg::regenAIMessage message streamConfig.status forbidden ${t.streamConfig.status}`}});yield this.core.sendCmd("v2AIRegenMessage",{tag:{fromAccount:t.senderId,to:t.receiverId,aiAccount:null===(h=t.aiConfig)||void 0===h?void 0:h.accountId,serverId:t.messageServerId,clientId:t.messageClientId,time:t.createTime,type:t.conversationType,opeType:i.operationType,replyMsgFromAccount:null===(u=t.threadReply)||void 0===u?void 0:u.senderId,replyMsgToAccount:null===(v=t.threadReply)||void 0===v?void 0:v.receiverId,replyMsgTime:null===(I=t.threadReply)||void 0===I?void 0:I.createTime,replyMsgIdServer:null===(_=t.threadReply)||void 0===_?void 0:_.messageServerId,replyMsgIdClient:null===(M=t.threadReply)||void 0===M?void 0:M.messageClientId}}),1===i.operationType&&this.core.V2NIMAIService.model.setAiStream(t.messageClientId,{isComplete:!1,queryStatus:0,chunks:[]})}))}checkAI(){if(!this.hasAI())throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_MISUSE,detail:{reason:"V2NIMAIService is not registered"}})}hasAI(){var t;return!!(null===(t=this.core.V2NIMAIService)||void 0===t?void 0:t.name)}}class V2NIMMMessageHandlerImpl{constructor(t,i){this.core=t,this.service=i,this.model=i.model,this.receiptUtil=i.receiptUtil,this.logger=this.core.logger}setAIStreamPlaceholder(t){this.service.aiUtil.hasAI()&&t.forEach((t=>{var i;1===(null===(i=t.streamConfig)||void 0===i?void 0:i.status)&&this.core.V2NIMAIService.model.setAiStream(t.messageClientId,{isComplete:!1,queryStatus:0,chunks:[],msg:t},!0)}))}onMsgHandler(t){var i=fillIdServer(t,t.content.msg,"messageServerId"),{_conversationOnlineSyncNotify:o,_conversationOnlineSyncData:m}=i,h=__rest(i,["_conversationOnlineSyncNotify","_conversationOnlineSyncData"]),u=completeMessage(this.core,h,1),v=this.service._filterMessage(u);this.logger.log(`v2OnMsgHandler::recvMsg ${u.messageClientId}/${u.messageServerId}/${u.createTime};isHitFilter:${v}`),3===u.conversationType?this.core.eventBus.emit("V2NIMSync/updateTimetag",{superTeamRoamingMsgs:u.createTime,offlineMsgs:u.createTime}):this.core.eventBus.emit("V2NIMSync/updateTimetag",{roamingMsgs:u.createTime,offlineMsgs:u.createTime}),this.service.config.compatibleWithV1||(this.service.markMsgsAck([u]),this.service.sendUtil.doMsgReceiveReport(u,t)),delete u.__clientExt,this.setAIStreamPlaceholder([u]),5!==u.messageType&&this.core.V2NIMUserService.checkUserUpdate&&this.core.V2NIMUserService.checkUserUpdate(u,u.userUpdateTime),5===u.messageType&&this.core.eventBus.emit("V2NIMTeamService/notification",i),v||(this.service.emit("onReceiveMessages",[u]),this.model.upsertMessages([u]),o&&this.core.eventBus.emit("V2NIMConversationService/conversationOnlineSyncNotify",{content:{info:JSON.parse(o),data:JSON.parse(m)}},u),this.core.eventBus.emit("V2NIMMessageService/onMsg",u))}syncOfflineMsgsHandler(t){var i=t.content.datas;i=i.map((t=>completeMessage(this.core,t,2))),0!==(i=this.service._filterMessagesByFn(i)).length&&(!this.service.config.compatibleWithV1&&this.service.markMsgsAck(i),this.service.emit("onReceiveMessages",i),this.model.upsertMessages(i),this.core.eventBus.emit("V2NIMMessageService/offlineMsgs",i))}syncRoamingMsgsHandler(t){var i=t.content.datas;i=i.map((t=>completeMessage(this.core,t,3))),this.setAIStreamPlaceholder(i),0!==(i=this.service._filterMessagesByFn(i)).length&&(this.service.emit("onReceiveMessages",i),this.model.upsertMessages(i),this.core.eventBus.emit("V2NIMMessageService/roamingMsgs",i))}onP2PMessageReceiptsHandler(t){this.receiptUtil.onP2PMessageReceiptsHandler(t)}onTeamMessageReceiptsHandler(t){this.receiptUtil.onTeamMessageReceiptsHandler(t)}syncP2PMessagReceiptsHandler(t){this.receiptUtil.syncP2PMessagReceiptsHandler(t)}syncP2pMessagReceiptsV2Handler(t){this.receiptUtil.syncP2pMessagReceiptsV2Handler(t)}syncRevokeMessageHandler(t){this.service.deleteUtil.emitRevokeMessage(t.content.datas)}onRevokeMessageHandler(t){var i=t.content.data;this.service.deleteUtil.emitRevokeMessage([i])}onDeleteMessageHandler(t){var i=t.content.data,o={serverExtension:i.serverExtension,deleteTime:i.deleteTime,messageRefer:completeMessageRefer(this.core,i.messageRefer)};this.service.deleteUtil.deleteMessagesFn([o])}onDeleteMessagesHandler(t){var i=t.content.data.map((t=>({serverExtension:t.serverExtension,deleteTime:t.deleteTime,messageRefer:completeMessageRefer(this.core,t.messageRefer)})));this.service.deleteUtil.deleteMessagesFn(i)}syncOnDeleteMessagesHandler(t){var i=t.content.datas.map((t=>({serverExtension:t.serverExtension,deleteTime:t.deleteTime,messageRefer:completeMessageRefer(this.core,t.messageRefer)})));this.service.emit("onMessageDeletedNotifications",i)}v2MessageOnModifiedHandler(t){var i=completeMessage(this.core,t.content.data);this.model.upsertMessages([i]),this.service.aiUtil.hasAI()&&this.core.V2NIMAIService.model.completeAiStream(i.messageClientId),this.core.eventBus.emit("forwardSend/V2NIMMessageService/modifyMsg",i),this.core.eventBus.emit("V2NIMMessageService/modifyMsg",i),this.core.eventBus.emit("V2NIMSync/updateTimetag",3===i.conversationType?{superTeamModifyMessage:i.modifyTime}:{p2pTeamModifyMessage:i.modifyTime}),this.service.emit("onReceiveMessagesModified",[i])}v2MessageSyncModifiedHandler(t){var i=t.content.datas.map((t=>completeMessage(this.core,t))).filter((t=>{var i,o=(null===(i=this.model.getMessageById(t.messageClientId))||void 0===i?void 0:i.modifyTime)||0;return(t.modifyTime||0)>o}));i.length>0&&(this.model.upsertMessages(i),i.forEach((t=>{this.service.aiUtil.hasAI()&&this.core.V2NIMAIService.model.completeAiStream(t.messageClientId),this.core.eventBus.emit("forwardSend/V2NIMMessageService/modifyMsg",t)})),this.service.emit("onReceiveMessagesModified",i))}v2MessageSyncSuperTeamModifiedHandler(t){this.v2MessageSyncModifiedHandler(t)}}class V2NIMMessageEventImpl{constructor(t,i){this.core=t,this.service=i,this.logger=this.core.logger}setListener(){this.core.eventBus.on("forwardReceive/V2NIMMessageService/sendMsg",this.service.sendMessageFn.bind(this.service)),this.core.eventBus.on("forwardReceive/V2NIMMessageService/revokeMessages",this.service.deleteUtil.emitRevokeMessage.bind(this.service.deleteUtil)),this.core.eventBus.on("forwardReceive/V2NIMMessageService/deleteMessages",this.service.deleteUtil.deleteMessagesFn.bind(this.service.deleteUtil)),this.core.eventBus.on("V2NIMConversationService/deleteConversation",(t=>{t.forEach((t=>this.service.model.deleteMessages(t)))})),this.core.eventBus.on("V2NIMAIService/receiveMessagesModified",(t=>this.service.emit("onReceiveMessagesModified",t)))}beforeEmit(t,...i){var o,m,h,u=`${this.service.name}::emit ${t.toString()}`;if("onSendMessage"===t){var v=i[0];this.logger.log(`${u}`,`${v.messageClientId}/${v.messageServerId}/${v.createTime};`,`sendingState:${v.sendingState};attachmentUploadState:${v.attachmentUploadState||0};messageStatus:${null===(o=v.messageStatus)||void 0===o?void 0:o.errorCode};config.lastMsg:${null===(m=v.messageConfig)||void 0===m?void 0:m.lastMessageUpdateEnabled};config.unread:${null===(h=v.messageConfig)||void 0===h?void 0:h.unreadEnabled}`)}else if("onReceiveMessages"===t||"onReceiveMessagesModified"===t){var I=i[0];this.logger.log(`${u}`,I.map((t=>{var i,o;return`${t.messageClientId}/${t.messageServerId}/${t.createTime};config.lastMsg:${null===(i=t.messageConfig)||void 0===i?void 0:i.lastMessageUpdateEnabled};config.unread:${null===(o=t.messageConfig)||void 0===o?void 0:o.unreadEnabled}`})))}else if("onMessageRevokeNotifications"===t){var _=i[0];this.logger.log(`${u}`,_.map((t=>`msg:${t.messageRefer.messageClientId}/${t.messageRefer.messageServerId};revokeAccountId:${t.revokeAccountId}`)))}else if("onMessageDeletedNotifications"===t){var M=i[0];this.logger.log(`${u}`,M.map((t=>`msg:${t.messageRefer.messageClientId}/${t.messageRefer.messageServerId};deleteTime:${t.deleteTime}`)))}else this.logger.log(`${u}`,...i)}}class V2NIMMessageServiceImpl extends V2Service{constructor(t,i={}){super("V2NIMMessageService",t),this.customAttachmentParsers=[],this.config={compatibleWithV1:!0},this.filterFn=void 0,this.core._registerDep(V2NIMConversationIdUtilImpl,"V2NIMConversationIdUtil"),this.core._registerDep(V2NIMMessageCreatorImpl,"V2NIMMessageCreator"),this.core._registerDep(V2NIMMessageAttachmentCreatorImpl,"V2NIMMessageAttachmentCreator"),this.core._registerDep(V2NIMClientAntispamUtilImpl,"V2NIMClientAntispamUtil"),this.receiptUtil=new ReceiptUtil(this.core,this),this.fileUtil=new FileUtil(this.core),this.sendUtil=new SendUtil(this.core,this),this.modifyUtil=new ModifyUtil(this.core,this),this.deleteUtil=new DeleteUtil(this.core,this),this.aiUtil=new AIUtil(this.core,this),this.model=new V2NIMMessageModelImpl,this.event=new V2NIMMessageEventImpl(this.core,this),this.handler=new V2NIMMMessageHandlerImpl(this.core,this),"v2"===this.core.options.apiVersion&&(registerParser({cmdMap:ki,cmdConfig:Fi}),this.setOptions(i),this.setListener())}setOptions(t){var i;(null===(i=this.core.msg)||void 0===i?void 0:i.name)?this.config.compatibleWithV1=!0:this.config.compatibleWithV1=!1,this.config=Object.assign(this.config,t)}setListener(){this.event.setListener()}reset(){this.model.reset(),this.receiptUtil.reset()}emit(t,...i){return this.event.beforeEmit(t,...i),super.emit(t,...i)}checkExtendUtil(){var t;if(!(null===(t=this.core.V2NIMMessageExtendUtil)||void 0===t?void 0:t.name))throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_MISUSE,detail:{reason:"V2NIMMessageLogUtil is not registered"}})}checkLogUtil(){var t;if(!(null===(t=this.core.V2NIMMessageLogUtil)||void 0===t?void 0:t.name))throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_MISUSE,detail:{reason:"V2NIMMessageExtendUtil is not registered"}})}getMessageList(t){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),this.checkLogUtil();var i=yield this.core.V2NIMMessageLogUtil.getMessageList(t);return i=this._filterMessageByClearTime(t.conversationId,i),i=this._filterMessagesByFn(i)}))}getMessageListEx(t){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),this.checkLogUtil();var i=yield this.core.V2NIMMessageLogUtil.getMessageList(t);return i=this._filterMessageByClearTime(t.conversationId,i),{messages:this._filterMessagesByFn(i),anchorMessage:i.length>0?i[i.length-1]:null}}))}getMessageListByRefers(t){return this.checkV2(),this.checkLogUtil(),this.core.V2NIMMessageLogUtil.getMessageListByRefers(t)}clearHistoryMessage(t){return this.checkV2(),this.checkLogUtil(),this.core.V2NIMMessageLogUtil.clearHistoryMessage(t)}clearRoamingMessage(t){return this.checkV2(),this.checkLogUtil(),this.core.V2NIMMessageLogUtil.clearRoamingMessage(t)}pinMessage(t,i){return this.checkV2(),this.checkExtendUtil(),this.core.V2NIMMessageExtendUtil.pinMessage(t,i)}unpinMessage(t,i){return this.checkV2(),this.checkExtendUtil(),this.core.V2NIMMessageExtendUtil.unpinMessage(t,i)}updatePinMessage(t,i){return this.checkV2(),this.checkExtendUtil(),this.core.V2NIMMessageExtendUtil.updatePinMessage(t,i)}voiceToText(t){return this.checkV2(),this.checkExtendUtil(),"string"==typeof t.duration&&(t.duration=Number(t.duration)),this.core.V2NIMMessageExtendUtil.voiceToText(t)}getPinnedMessageList(t){return this.checkV2(),this.checkExtendUtil(),this.core.V2NIMMessageExtendUtil.getPinnedMessageList(t)}addQuickComment(t,i,o,m){return this.checkV2(),this.checkExtendUtil(),this.core.V2NIMMessageExtendUtil.addQuickComment(t,i,o,m)}removeQuickComment(t,i,o){return this.checkV2(),this.checkExtendUtil(),this.core.V2NIMMessageExtendUtil.removeQuickComment(t,i,o)}getQuickCommentList(t){return this.checkV2(),this.checkExtendUtil(),this.core.V2NIMMessageExtendUtil.getQuickCommentList(t)}addCollection(t){return this.checkV2(),this.checkExtendUtil(),this.core.V2NIMMessageExtendUtil.addCollection(t)}removeCollections(t){return this.checkV2(),this.checkExtendUtil(),this.core.V2NIMMessageExtendUtil.removeCollections(t)}updateCollectionExtension(t,i){return this.checkV2(),this.checkExtendUtil(),this.core.V2NIMMessageExtendUtil.updateCollectionExtension(t,i)}getCollectionListByOption(t){return this.checkV2(),this.checkExtendUtil(),this.core.V2NIMMessageExtendUtil.getCollectionListByOption(t)}getCollectionListExByOption(t){return this.checkV2(),this.checkExtendUtil(),this.core.V2NIMMessageExtendUtil.getCollectionListExByOption(t)}searchCloudMessages(t){return this.checkV2(),this.checkExtendUtil(),this.core.V2NIMMessageExtendUtil.searchCloudMessages(t)}searchCloudMessagesEx(t){return this.checkV2(),this.checkExtendUtil(),this.core.V2NIMMessageExtendUtil.searchCloudMessagesEx(t)}getThreadMessageList(t){return this.checkV2(),this.checkExtendUtil(),this.core.V2NIMMessageExtendUtil.getThreadMessageList(t)}registerCustomAttachmentParser(t){"function"==typeof t&&-1===this.customAttachmentParsers.indexOf(t)&&this.customAttachmentParsers.unshift(t)}unregisterCustomAttachmentParser(t){var i=this.customAttachmentParsers.indexOf(t);i>-1&&this.customAttachmentParsers.splice(i,1)}sendP2PMessageReceipt(t){return this.checkV2(),this.receiptUtil.sendP2PMessageReceipt(t)}isPeerRead(t){return this.checkV2(),this.receiptUtil.isPeerRead(t)}getP2PMessageReceipt(t){return this.checkV2(),this.receiptUtil.getP2PMessageReceipt(t)}getTeamMessageReceipts(t){return this.checkV2(),this.receiptUtil.getTeamMessageReceipts(t)}getTeamMessageReceiptDetail(t){return this.checkV2(),this.receiptUtil.getTeamMessageReceiptDetail(t)}sendTeamMessageReceipts(t){return this.checkV2(),this.receiptUtil.sendTeamMessageReceipts(t)}revokeMessage(t,i){return __awaiter(this,void 0,void 0,(function*(){return this.checkV2(),this.deleteUtil.revokeMessage(t,i)}))}deleteMessage(t,i){return this.checkV2(),this.deleteUtil.deleteMessage(t,i)}deleteMessages(t,i){return this.checkV2(),this.deleteUtil.deleteMessages(t,i)}cancelMessageAttachmentUpload(t){return this.checkV2(),this.fileUtil.cancelMessageAttachmentUpload(t)}markMsgsAck(t){if(t&&t.length>0){var i=[],o=[];t.forEach((t=>{t.senderId===this.core.account&&t.senderId!==t.receiverId||(1===t.conversationType?i.push(t):2===t.conversationType&&o.push(t))})),i.length>0&&this.core.sendCmd("v2BatchMarkRead",{sid:7,cid:2,ids:i.map((t=>t.messageServerId))}),o.length>0&&this.core.sendCmd("v2BatchMarkRead",{sid:8,cid:3,ids:o.map((t=>t.messageServerId))})}}sendMessage(t,i,o={},m){var h;return __awaiter(this,void 0,void 0,(function*(){if(this.checkV2(),validate({message:{type:"object"}},{message:t},"",!0),t.messageClientId=t.messageClientId||Pe(),t.conversationId&&t.conversationId!==i)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"sendMessage: message.conversationId is not equal to conversationId"}});validate($t,{conversationId:i,message:t,params:o},"",!0),validateConversationId(this.core.account,i);var u=this.core.V2NIMConversationIdUtil.parseConversationType(i);if((2===u||3===u)&&o.robotConfig&&!o.robotConfig.accountId)throw new ValidateErrorV2({detail:{reason:"When conversationType is team or superTeam, account is required in robotInfo account is required"}});if(2!==u&&3!==u||!o.targetConfig)o.targetConfig=void 0;else{var v=o.targetConfig.receiverIds;if(3===u&&!1===o.targetConfig.inclusive)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"setting inclusive to false for super teams is not allowed"}});if(0===(v=v.filter((t=>t&&t!==this.core.account))).length)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"receiverIds cannot be empty or only contain yourself"}});o.targetConfig.receiverIds=v}(null===(h=o.aiConfig)||void 0===h?void 0:h.aiStream)&&this.aiUtil.checkAI();var I,_=this.core.timeOrigin.getTimeNode(),{messageBeforeSend:M,clientAntispamResult:E,hiddenParams:S}=this.sendUtil.prepareMessage(t,i,o);this.logger.log(`V2SendMessage start:${M.messageClientId}/${M.createTime};conversation:${i};`,`NTPTime:${this.core.timeOrigin.getNTPTime(_)}`);try{I=yield this.sendUtil.doSendMessage({apiCallingTimeNode:_,messageBeforeSend:M,clientAntispamResult:E,hiddenParams:S,progress:m})}catch(t){throw this.logger.warn(`V2SendMessage end:${M.messageClientId}.`,t instanceof V2NIMErrorImpl?`failed:${t.code}`:"failed"),t}return I.message.senderId===I.message.receiverId&&this.markMsgsAck([I.message]),this.logger.log(`V2SendMessage end:${I.message.messageClientId}/${I.message.messageServerId}/${I.message.createTime}`),I}))}replyMessage(t,i,o={},m){return __awaiter(this,void 0,void 0,(function*(){if(this.checkV2(),validate({message:{type:"object"}},{message:t},"",!0),t.messageClientId=t.messageClientId||Pe(),validate(Bt,{message:t,replyMessage:i,params:o},"",!0),validateConversationId(this.core.account,i.conversationId),(2===t.conversationType||3===t.conversationType)&&o.robotConfig&&!o.robotConfig.accountId)throw new ValidateErrorV2({detail:{reason:"When conversationType is team or superTeam, account is required in robotInfo account is required"}});var h=this.core.timeOrigin.getTimeNode(),{messageBeforeSend:u,clientAntispamResult:v,hiddenParams:I}=this.sendUtil.prepareMessage(t,i.conversationId,o,i),_=yield this.sendUtil.doSendMessage({apiCallingTimeNode:h,messageBeforeSend:u,clientAntispamResult:v,hiddenParams:I,progress:m});return _.message.senderId===_.message.receiverId&&this.markMsgsAck([_.message]),_}))}modifyMessage(t,i){this.checkV2(),this.checkLogin(),validate(ui,t,"message",!0),validate(gi,i,"params",!0),this.modifyUtil.checkIfModify(t,i);var{messageBeforeSend:o,clientAntispamResult:m}=this.modifyUtil.prepareMessage(t,i);return this.modifyUtil.modifyMessage(o,m)}stopAIStreamMessage(t,i){if(this.checkV2(),this.aiUtil.checkAI(),validate(vi,t,"message",!0),validate(fi,i,"params",!0),2===i.operationType&&!i.updateContent)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"V2NIMMessage::stopAIStreamMessage updateContent empty"}});return this.aiUtil.stopAIStreamMessage(t,i)}regenAIMessage(t,i){return this.checkV2(),this.aiUtil.checkAI(),validate(vi,t,"message",!0),validate(Ii,i,"params",!0),this.aiUtil.regenAIMessage(t,i)}sendMessageFn(t){if(t.msgAckSnapshot){var i=t.msgAckSnapshot,o={conversationId:t.conversationId,messageServerId:t.messageServerId,messageClientId:t.messageClientId,readCount:0,unreadCount:Number(i)};delete t.msgAckSnapshot,this.emit("onReceiveTeamMessageReadReceipts",[o])}t=formatMessageAttachment(t,this.core),this.model.upsertMessages([t]),this.core.eventBus.emit("V2NIMMessageService/sendMessage",t,t.sendingState)}setMessageFilter(t){null!=t?t&&"function"==typeof t.shouldIgnore&&(this.filterFn=t.shouldIgnore):this.filterFn=void 0}_filterMessage(t){if("function"==typeof this.filterFn)try{return!0===this.filterFn(t)}catch(i){return this.logger.error(`V2NIMMessage::triggerMessageFilter ${t.messageClientId} error:`,i),!1}return!1}_filterMessagesByFn(t){return t.filter((t=>!this._filterMessage(t)))}_filterMessageByClearTime(t,i){var o=Re.localStorage.getItem(`nim_${this.core.account}_${t}_clearTime`),m=o?parseInt(o):0;return m>0?i.filter((t=>t.createTime>=m)):i}}var sr={super_team:3,p2p:1,team:2},ar={3:"super_team",1:"p2p",0:"p2p",2:"team"};function getConvInfoFromSessionId(t,i="|"){var o=t.indexOf(i);if(-1===o)return{target:"",type:0};var m=t.slice(0,o);return{target:t.slice(o+1),type:sr[m]||0}}function getSessionIdFromConvInfo(t,i){return`${ar[t]}|${i}`}class V2NIMLocalConversationModelImpl{constructor(){this.map=new Map,this.capacity=1e4,this.readTimeMap=new Map,this.stickTopMap=new Map}reset(){this.map.clear(),this.readTimeMap.clear(),this.stickTopMap.clear()}count(){return this.map.size}sort(){var t=Array.from(this.map.values());t.sort(((t,i)=>i.sortOrder-t.sortOrder)),this.map.clear(),t.forEach((t=>{this.map.set(t.conversationId,t)}))}processConversation(t){return"string"==typeof t.lastMessage&&delete t.lastMessage,void 0===t.localExtension&&(t.localExtension=""),t}getById(t){return this.map.get(t)}getAll(){return Array.from(this.map.values()).sort(((t,i)=>i.sortOrder-t.sortOrder))}getStickTopList(){return Array.from(this.map.values()).filter((t=>t.stickTop)).sort(((t,i)=>i.sortOrder-t.sortOrder))}getByOption(t,i,o){var{conversationTypes:m,onlyUnread:h}=o,u=[];this.map.forEach((t=>{m&&m.length>0&&!m.includes(t.type)||h&&!t.unreadCount||o.ignoreMuted&&t.mute||u.push(t)})),u=u.sort(((t,i)=>i.sortOrder-t.sortOrder));var v=0;t>0&&(v=findIndexWithinTargetValue(u,"sortOrder",t),u[v]&&u[v].sortOrder===t&&(v+=1));var I=u.slice(v).length;return(u=u.slice(v,v+i)).length>0?{offset:I>i?u[u.length-1].sortOrder:0,finished:!(I>i),conversationList:u}:{offset:0,finished:!0,conversationList:u}}upsert(t){var i=t.conversationId,o=this.map.get(i);if(!o){var m=this.processConversation(Object.assign({stickTop:this.getStickTop(i),localExtension:"",lastMessage:null,unreadCount:0,sortOrder:0,createTime:0,updateTime:0},t));return this.setLRU(i,m),m.unreadCount>0}var h=t.unreadCount!==o.unreadCount,u=Object.assign({},o,t);return u=this.processConversation(u),this.setLRU(i,u),h}setLRU(t,i){if(this.map.has(t))this.map.delete(t);else if(this.map.size>=this.capacity){var o=this.map.keys().next().value;o&&this.map.delete(o)}this.map.set(t,i)}bulkUpsert(t){var i=!1;return t.forEach((t=>{this.upsert(t)&&(i=!0)})),i}deleteById(t){var i=this.getById(t);if(i)return this.map.delete(t),i}updateReadTime(t,i){this.readTimeMap.set(t,i)}getReadTime(t){return this.readTimeMap.get(t)||0}updateStickTop(t,i){i?this.stickTopMap.set(t,!0):this.stickTopMap.delete(t)}getStickTop(t){return this.stickTopMap.get(t)||!1}}var cr={"4_14":"v2LocalConvSyncReadTime","4_20":"v2LocalConvSyncSuperTeamReadTime","4_33":"v2LocalConvSyncP2pReadTimeV2","4_34":"v2LocalConvSyncTeamReadTimeV2","4_35":"v2LocalConvSyncSuperTeamReadTimeV2","4_22":"v2LocalConvSyncMoreRoaming","4_23":"v2LocalConvSyncStickTop","4_25":"v2LocalConvSyncReliableInfo","7_16":"v2LocalConvMarkReadTime","7_25":"v2LocalConvMultiMarkReadTime","7_116":"v2LocalConvMultiSyncReadTime","21_25":"v2LocalConvSuperTeamMarkReadTime","21_32":"v2LocalConvSuperTeamMultiMarkReadTime","21_125":"v2LocalConvSuperTeamMultiSyncReadTime","33_12":"v2LocalConvStickTopAdd","33_13":"v2LocalConvStickTopDelete","23_112":"v2LocalConvStickTopMultiSyncAdd","23_113":"v2LocalConvStickTopMultiSyncDelete","23_114":"v2LocalConvStickTopMultiSyncUpdate"},dr="V2NIMLocalConversationService",lr={id:1,ext:2,createTime:{id:3,retType:"number"},updateTime:{id:4,retType:"number"}},pr={scene:1,to:2,timetag:3},mr={actionTime:1},hr={minTimetag:{id:1,retType:"number"},maxTimetag:{id:2,retType:"number"}},ur={id:1,msgTime:{id:2,retType:"number"}},gr={v2LocalConvSyncReadTime:{sid:4,cid:14,service:dr,response:[{type:"StrLongMap",name:"p2p"},{type:"LongLongMap",name:"team"},{type:"Long",name:"timetag"}]},v2LocalConvSyncSuperTeamReadTime:{sid:4,cid:20,service:dr,response:[{type:"LongLongMap",name:"superTeam"}]},v2LocalConvSyncP2pReadTimeV2:{sid:4,cid:33,service:dr,response:[{type:"Property",name:"ctx",reflectMapper:invertSerializeItem(hr)},{type:"PropertyArray",name:"contents",reflectMapper:invertSerializeItem(ur)}]},v2LocalConvSyncTeamReadTimeV2:{sid:4,cid:34,service:dr,response:[{type:"Property",name:"ctx",reflectMapper:invertSerializeItem(hr)},{type:"PropertyArray",name:"contents",reflectMapper:invertSerializeItem(ur)}]},v2LocalConvSyncSuperTeamReadTimeV2:{sid:4,cid:35,service:dr,response:[{type:"Property",name:"ctx",reflectMapper:invertSerializeItem(hr)},{type:"PropertyArray",name:"contents",reflectMapper:invertSerializeItem(ur)}]},v2LocalConvSyncMoreRoaming:{sid:4,cid:22,service:dr,response:[]},v2LocalConvSyncStickTop:{sid:4,cid:23,service:dr,response:[{type:"Long",name:"timetag"},{type:"Bool",name:"isThereAnyChange"},{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(lr)}]},v2LocalConvSyncReliableInfo:{sid:4,cid:25,service:dr,response:[]},v2LocalConvMarkReadTime:{sid:7,cid:16,service:dr,params:[{type:"Byte",name:"scene"},{type:"String",name:"to"},{type:"Long",name:"timetag"}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(mr)}]},v2LocalConvMultiMarkReadTime:{sid:7,cid:25,service:dr,ignoreErrCodes:[700],params:[{type:"PropertyArray",name:"tags",reflectMapper:pr}],response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(pr)},{type:"Property",name:"data",reflectMapper:invertSerializeItem(mr)}]},v2LocalConvMultiSyncReadTime:{sid:7,cid:116,service:dr,response:[{type:"Byte",name:"scene"},{type:"String",name:"to"},{type:"Long",name:"timetag"},{type:"Long",name:"actionTime"}]},v2LocalConvSuperTeamMarkReadTime:{sid:21,cid:25,service:dr,params:[{type:"Long",name:"to"},{type:"Long",name:"timetag"}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(mr)}]},v2LocalConvSuperTeamMultiMarkReadTime:{sid:21,cid:32,service:dr,ignoreErrCodes:[700],params:[{type:"PropertyArray",name:"tags",reflectMapper:pr}],response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(pr)},{type:"Property",name:"data",reflectMapper:invertSerializeItem(mr)}]},v2LocalConvSuperTeamMultiSyncReadTime:{sid:21,cid:125,service:dr,response:[{type:"Long",name:"to"},{type:"Long",name:"timetag"},{type:"Long",name:"actionTime"}]},v2LocalConvStickTopAdd:{sid:33,cid:12,service:dr,params:[{type:"Property",name:"tag",reflectMapper:lr}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(lr)}]},v2LocalConvStickTopDelete:{sid:33,cid:13,service:dr,params:[{type:"Property",name:"tag",reflectMapper:lr}],response:[{type:"Long",name:"timetag"}]},v2LocalConvStickTopMultiSyncAdd:{sid:23,cid:112,service:dr,response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(lr)}]},v2LocalConvStickTopMultiSyncDelete:{sid:23,cid:113,service:dr,response:[{type:"Long",name:"timetag"},{type:"Property",name:"data",reflectMapper:invertSerializeItem(lr)}]},v2LocalConvStickTopMultiSyncUpdate:{sid:23,cid:114,service:dr,response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(lr)}]}};function chunk(t,i){t=t||[],i=i||1,i=Math.max(Math.floor(i),1);for(var o=[],m=0;m<t.length;m+=i)o.push(t.slice(m,m+i));return o}function isObject(t){var i=typeof t;return null!=t&&("object"==i||"function"==i)}var vr=Math.max,fr=Math.min;function debounce(t,i,o){var m,h,u,v,I,_,M=0,E=!1,S=!1,T=!0;if("function"!=typeof t)throw new TypeError("Expected a function");function invokeFunc(i){var o=m,u=h;return m=h=void 0,M=i,v=t.apply(u,o)}function leadingEdge(t){return M=t,I=setTimeout(timerExpired,i),E?invokeFunc(t):v}function shouldInvoke(t){var o=t-_;return void 0===_||o>=i||o<0||S&&t-M>=u}function timerExpired(){var t=Date.now();if(shouldInvoke(t))return trailingEdge(t);I=setTimeout(timerExpired,function remainingWait(t){var o=i-(t-_);return S?fr(o,u-(t-M)):o}(t))}function trailingEdge(t){return I=void 0,T&&m?invokeFunc(t):(m=h=void 0,v)}function debounced(){var t=Date.now(),o=shouldInvoke(t);if(m=arguments,h=this,_=t,o){if(void 0===I)return leadingEdge(_);if(S)return clearTimeout(I),I=setTimeout(timerExpired,i),invokeFunc(_)}return void 0===I&&(I=setTimeout(timerExpired,i)),v}return i=Number(i)||0,isObject(o)&&(E=!!o.leading,u=(S="maxWait"in o)?vr(Number(o.maxWait)||0,i):u,T="trailing"in o?!!o.trailing:T),debounced.cancel=function cancel(){void 0!==I&&clearTimeout(I),M=0,m=_=h=I=void 0},debounced.flush=function flush(){return void 0===I?v:trailingEdge(Date.now())},debounced}var Ir;class V2NIMLocalConversationUnreadImpl{constructor(t,i){this.totalUnreadCount=void 0,this.unreadCountByFilter={},this.currentConversationId=void 0,this._setCurrConvThrottle=function throttle(t,i,o){var m=!0,h=!0;if("function"!=typeof t)throw new TypeError("Expected a function");return isObject(o)&&(m="leading"in o?!!o.leading:m,h="trailing"in o?!!o.trailing:h),debounce(t,i,{leading:m,maxWait:i,trailing:h})}((()=>{this.currentConversationId&&this._setCurrConv(this.currentConversationId)}),5e3,{leading:!1}),this.core=t,this.service=i,this.model=i.model,this.logger=i.logger}reset(){this.totalUnreadCount=void 0,this.unreadCountByFilter={},this.currentConversationId=void 0,this._setCurrConvThrottle.flush()}getTotalUnreadCount(){return this.totalUnreadCount||0}resetTotalAfterSyncDone(){var t=this.service.model.getAll().reduce(((t,i)=>t+(i.unreadCount||0)),0),i=this.totalUnreadCount;return void 0!==i&&i===t||(this.totalUnreadCount=t,this.service.emit("onTotalUnreadCountChanged",t)),t}digestUnreadCountChange(){this._digest()}_digest(){var t=this.totalUnreadCount||0,i=this.service.model.getAll().reduce(((t,i)=>t+(i.unreadCount||0)),0);this.core.logger.log(`V2NIMConversation::digestUnreadCountChange:oldUnreadCount ${t}, newUnreadCount ${i}`),t!==i&&(this.totalUnreadCount=i,this.service.emit("onTotalUnreadCountChanged",i)),Object.keys(this.unreadCountByFilter).forEach((t=>{var i=JSON.parse(t),o=this.getUnreadCountByFilter(i),m=this.unreadCountByFilter[t];this.unreadCountByFilter[t]=o,i.equals=equals$1.bind(i),m!==o&&this.service.emit("onUnreadCountChangedByFilter",i,o)}))}clearUnreadCount(t){var i=t.reduce(((t,i)=>(this.service.model.upsert({conversationId:i.conversationId,type:i.type,unreadCount:0})&&t.push(i.conversationId),t)),[]);if(i.length>0){var o=i.map((t=>this.service.model.getById(t)));this.service.triggerConversationChanged(o),this.digestUnreadCountChange()}}getUnreadCountByIds(t){return(t=uniq(t)).reduce(((t,i)=>{var o=this.service.model.getById(i);return t+(o&&o.unreadCount||0)}),0)}getUnreadCountByFilter(t){var i=this.service.model.count();return this.service.model.getByOption(0,i,{conversationTypes:t.conversationTypes,ignoreMuted:t.ignoreMuted}).conversationList.reduce(((t,i)=>t+(i.unreadCount||0)),0)}isMessageUnread(t,i=0){var o;return t.createTime>i&&t.senderId!==this.core.account&&!1!==(null===(o=t.messageConfig)||void 0===o?void 0:o.unreadEnabled)}isMessageReferUnread(t,i=0){var o=this.core.V2NIMMessageService.model.getMessageById(t.messageClientId);return o?this.isMessageUnread(o,i):t.createTime>i&&t.senderId!==this.core.account}countUnreadByMessageInMemory(t,i=0){var o=0;return this.core.V2NIMMessageService.model.getMessagesByConversationId(t).forEach((t=>{this.isMessageUnread(t,i)&&o++})),o}addFilter(t){var i=generateFilterKey$1(t);if(void 0!==this.unreadCountByFilter[i])throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_RESOURCE_ALREADY_EXIST});var o=JSON.parse(i),m=this.getUnreadCountByFilter(o);this.unreadCountByFilter[i]=m,this.service.emit("onUnreadCountChangedByFilter",o,m)}deleteFilter(t){var i=generateFilterKey$1(t);if(void 0===this.unreadCountByFilter[i])throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_RESOURCE_NOT_EXIST});delete this.unreadCountByFilter[i]}markConversationRead(t){return __awaiter(this,void 0,void 0,(function*(){var i=this.model.getById(t),o=this.core.V2NIMConversationIdUtil.parseConversationTargetId(t),m=this.core.V2NIMConversationIdUtil.parseConversationType(t),h=this.model.getReadTime(t);if(!i)return h||this.core.timeOrigin.getNTPTime();var u=this.service.compute.computeReadTimeForMark(i);return h>=u?(this.logger.log(`V2LocalConv::markConversationRead currentReadTime >= readTime ${t},${h},${u}`),h):(3===m?yield this.core.sendCmd("v2LocalConvSuperTeamMarkReadTime",{timetag:u,to:o}):yield this.core.sendCmd("v2LocalConvMarkReadTime",{scene:1===m?0:2===m?1:2,timetag:u,to:o}),this.model.updateReadTime(t,u),u)}))}markMultiConversationRead(t){return __awaiter(this,void 0,void 0,(function*(){var i={cmd:"v2LocalConvSuperTeamMultiMarkReadTime",params:[]},o={cmd:"v2LocalConvMultiMarkReadTime",params:[]};t.forEach((t=>{var m=this.model.getById(t);if(m){var h=this.core.V2NIMConversationIdUtil.parseConversationTargetId(t),u=this.core.V2NIMConversationIdUtil.parseConversationType(t),v=this.model.getReadTime(t),I=this.service.compute.computeReadTimeForMark(m);if(!(v>=I)){var _={conversationId:t,scene:1===u?0:2===u?1:2,timetag:I,to:h};3===u?i.params.push(_):o.params.push(_)}}}));var m=chunk(i.params,50),h=chunk(o.params,50);for(var u of m){try{yield this.core.sendCmd(i.cmd,{tags:u})}catch(t){this.logger.warn("markMultiConversationRead::error:",u.map((t=>t.conversationId)),t)}u.forEach((t=>{this.model.updateReadTime(t.conversationId,t.timetag)}))}for(var v of h){try{yield this.core.sendCmd(o.cmd,{tags:v})}catch(t){this.logger.warn("markMultiConversationRead::error:",v.map((t=>t.conversationId)),t)}v.forEach((t=>{this.model.updateReadTime(t.conversationId,t.timetag)}))}}))}setCurrentConversation(t){var i=this.currentConversationId;this.currentConversationId=t,this.currentConversationId&&this._setCurrConv(this.currentConversationId),i&&i!==this.currentConversationId&&(this._setCurrConvThrottle.flush(),this._setCurrConv(i))}_setCurrConv(t){var i=this.model.getById(t),o=(null==i?void 0:i.unreadCount)||0;i&&(i.unreadCount=0),i&&o>0&&(this.service.triggerConversationChanged([i]),this._digest()),this.markConversationRead(t).catch((t=>{this.logger.warn("_setConv markRead failed",t)}))}}function generateFilterKey$1(t){var{conversationTypes:i}=t;return i&&(i=i.sort()),JSON.stringify({conversationGroupId:t.conversationGroupId,conversationTypes:i,ignoreMuted:t.ignoreMuted})}function equals$1(t){return JSON.stringify(this)===generateFilterKey$1(t)}function formatLastMessageFromMessage(t,i,o=0,m){var h,u;i=formatMessageAttachment(i,t);var{messageType:v,subType:I,text:_,attachment:M,serverExtension:E}=i,S="";if(i.senderId!==t.account&&5!==v){S=get(i,"fromNick");var T=null===(u=null===(h=t.V2NIMFriendService)||void 0===h?void 0:h.model)||void 0===u?void 0:u.getFriend(i.senderId);T&&T.alias&&(S=T.alias)}return JSON.parse(JSON.stringify({lastMessageState:o,messageRefer:formatMessageRefer(t,i),messageType:v,subType:I,text:_,attachment:M,serverExtension:E,callbackExtension:i.callbackExtension,sendingState:m,senderName:S}))}function formatConversationFields(t,i){return i&&i.length>0?i.map((i=>formatConversationField(t,i))):[]}function formatConversationField(t,i){var o=i;if("string"==typeof o.lastMessage)if(""===o.lastMessage);else if(1===o.lastMessageState){var m=formatRevokeMessage(t,deserialize(JSON.parse(o.lastMessage),invertSerializeItem(Ui)));o.lastMessage=function formatLastMessageFromNotification(t,i){var{messageRefer:o,revokeAccountId:m,revokeType:h,callbackExtension:u,serverExtension:v,postscript:I}=i,_=function calcSenderNameFromNotification(t,i,o,m){var h,u,v,I,_,M,E,S;if(i!==t.account){var T=null===(u=null===(h=t.V2NIMFriendService)||void 0===h?void 0:h.model)||void 0===u?void 0:u.getFriend(i);if(T&&T.alias)return T.alias;if(2===o){var C=null===(I=null===(v=t.V2NIMTeamService)||void 0===v?void 0:v.memberModel)||void 0===I?void 0:I.getById(m,1,i);if(C&&C.teamNick)return C.teamNick}else if(3===o){var N=null===(M=null===(_=t.V2NIMTeamService)||void 0===_?void 0:_.memberModel)||void 0===M?void 0:M.getById(m,1,i);if(N&&N.teamNick)return N.teamNick}var A=null===(S=null===(E=t.V2NIMUserService)||void 0===E?void 0:E.model)||void 0===S?void 0:S.getUser(i);return A&&A.name?A.name:void 0}}(t,i.revokeAccountId,i.messageRefer.conversationType,i.messageRefer.receiverId)||"";return JSON.parse(JSON.stringify({lastMessageState:1,messageRefer:o,revokeAccountId:m,revokeType:h,callbackExtension:u,serverExtension:v,text:I||"",senderName:_}))}(t,m)}else if(0===o.lastMessageState){var h=deserialize(JSON.parse(o.lastMessage),invertSerializeItem(Pi));o.lastMessage=formatLastMessageFromMessage(t,h,o.lastMessageState,h.senderId===t.account?1:void 0)}else 2===o.lastMessageState&&delete o.lastMessage;return o}function formatConversationByField(t){var{version:i,deleteFlag:o}=t;return{conversation:__rest(t,["version","deleteFlag"]),version:i,deleteFlag:o}}!function(t){t[t.createConversation=1]="createConversation",t[t.deleteConversation=2]="deleteConversation",t[t.updateConversation=3]="updateConversation",t[t.setConversationTop=4]="setConversationTop",t[t.clearConversationUnread=5]="clearConversationUnread",t[t.addConversationToGroup=6]="addConversationToGroup",t[t.removeConversationFromGroup=7]="removeConversationFromGroup",t[t.modifyConversationOnSendMessage=8]="modifyConversationOnSendMessage",t[t.modifyConversationOnDeleteMessage=9]="modifyConversationOnDeleteMessage",t[t.modifyConversationOnRecallMessage=10]="modifyConversationOnRecallMessage",t[t.modifyConversationOnClearMessage=11]="modifyConversationOnClearMessage",t[t.oneClickClearConversationUnread=12]="oneClickClearConversationUnread",t[t.modifyConversationOnUpdateMessage=13]="modifyConversationOnUpdateMessage"}(Ir||(Ir={}));class V2NIMLocalConversationComputeImpl{constructor(t,i){this.core=t,this.service=i}get hasUserService(){var t;return!!(null===(t=this.core.V2NIMUserService)||void 0===t?void 0:t.name)}get hasFriendService(){var t;return!!(null===(t=this.core.V2NIMFriendService)||void 0===t?void 0:t.name)}get hasTeamService(){var t;return!!(null===(t=this.core.V2NIMTeamService)||void 0===t?void 0:t.name)}get hasMessageService(){var t;return!!(null===(t=this.core.V2NIMMessageService)||void 0===t?void 0:t.name)}computeFromExternal(t){var i,o,m;if(0===t.type)return t;var h=this.core.V2NIMConversationIdUtil.parseConversationType(t.conversationId),u=this.core.V2NIMConversationIdUtil.parseConversationTargetId(t.conversationId),v={};if((null===(i=this.core.V2NIMSettingService)||void 0===i?void 0:i.name)&&(v.mute=this.core.V2NIMSettingService.getConversationMuteStatus(t.conversationId)),1===h&&this.hasUserService){var I,_=this.core.V2NIMUserService.model.getUser(u),M=this.hasFriendService?this.core.V2NIMFriendService.model.getFriend(u):void 0;t.conversationId===(null===(o=t.lastMessage)||void 0===o?void 0:o.messageRefer.conversationId)&&(I=null===(m=t.lastMessage)||void 0===m?void 0:m.senderName),v.name=(null==M?void 0:M.alias)||(null==_?void 0:_.name)||I||u,v.avatar=(null==_?void 0:_.avatar)||""}else if(2===h&&this.hasTeamService){var E=this.core.V2NIMTeamService.model.getById(u,1);v.name=(null==E?void 0:E.name)||u,v.avatar=(null==E?void 0:E.avatar)||""}else if(3===h&&this.hasTeamService){var S=this.core.V2NIMTeamService.model.getById(u,2);v.name=(null==S?void 0:S.name)||u,v.avatar=(null==S?void 0:S.avatar)||""}return Object.assign(t,v),t}computeSortOrder(t,i){return i?t?i+1e15:i:t?1e15:0}computeReadTimeForMark(t){var i,o,m,h=t.conversationId,u=this.service.model.getReadTime(h);if(null===(o=null===(i=null==t?void 0:t.lastMessage)||void 0===i?void 0:i.messageRefer)||void 0===o?void 0:o.createTime)m=t.lastMessage.messageRefer.createTime;else{if(0===t.unreadCount&&u>0)return u;if(!this.core.timeOrigin.checkNodeReliable())return u||0;m=this.core.timeOrigin.getNTPTime()}return m}computeConvWithLastMsg(t,i){var o,m=i||this.core.V2NIMMessageService.model.getLastMessageOfConversation(t.conversationId);if(m&&!1!==(null===(o=m.messageConfig)||void 0===o?void 0:o.lastMessageUpdateEnabled)){var h=formatLastMessageFromMessage(this.core,m,0,m.sendingState);t.lastMessage=h,t.createTime=t.createTime||m.createTime,t.updateTime=m.createTime,t.sortOrder=this.computeSortOrder(t.stickTop,m.createTime)}return t}computeConvWithUnread(t,i){var o=this.service.model.getReadTime(t.conversationId),m=this.service.unread.currentConversationId;if(m&&(null==i?void 0:i.conversationId)===m)return t.unreadCount=0,this.service.unread._setCurrConvThrottle(),t;var h=t.unreadCount||0;return i?i&&this.service.unread.isMessageUnread(i)&&(h+=1):h=this.service.unread.countUnreadByMessageInMemory(t.conversationId,o),t.unreadCount=h,t}computeConvByMsgsCache(t,i){var o,m=this.service.model.getById(t),h=this.core.V2NIMConversationIdUtil.parseConversationType(t),u=this.core.V2NIMMessageService.model.getLastMessageOfConversation(t),v=null==i?void 0:i.updateTime,I=0;I=v||(u&&u.createTime?u.createTime:m&&m.updateTime?m.updateTime:this.core.timeOrigin.getNTPTime());var _=this.service.model.getStickTop(t),M=Object.assign(Object.assign({conversationId:t,type:h,stickTop:_,localExtension:(null==m?void 0:m.localExtension)||"",lastMessage:null,unreadCount:0},i),{createTime:(null==m?void 0:m.createTime)||I,updateTime:I,sortOrder:this.computeSortOrder(_,I)});if(u&&!1!==(null===(o=u.messageConfig)||void 0===o?void 0:o.lastMessageUpdateEnabled)){var E=formatLastMessageFromMessage(this.core,u,0,u.sendingState);M.lastMessage=E}return M}}class V2NIMLocalConversationHandlerImpl{constructor(t,i){this.core=t,this.service=i,this.model=this.service.model,this.unread=this.service.unread,this.logger=this.core.logger}v2LocalConvSyncStickTopHandler(t){var{timetag:i,isThereAnyChange:o,datas:m}=t.content;if(o){var h=this.model.getAll(),u=m.map((t=>{var{target:i,type:o}=getConvInfoFromSessionId(t.id),m=this.core.V2NIMConversationIdUtil.conversationId(o,i);return this.model.updateStickTop(m,!0),m}));h.forEach((t=>{u.includes(t.conversationId)?(t.stickTop=!0,t.updateTime=t.updateTime>i?t.updateTime:i):t.stickTop=!1,this.model.updateStickTop(t.conversationId,t.stickTop)})),this.model.bulkUpsert(h)}}v2LocalConvSyncReadTimeHandler(t){var i=t.content.p2p||{},o=t.content.team.m_map||{};this.logger.log("v2SyncLocalConvAck::",i,o),Object.keys(i).forEach((t=>{var o=this.core.V2NIMConversationIdUtil.p2pConversationId(t),m=this.model.getReadTime(o);i[t]>m&&(this.model.updateReadTime(o,i[t]),this.service.emit("onConversationReadTimeUpdated",o,i[t]))})),Object.keys(o).forEach((t=>{var i=this.core.V2NIMConversationIdUtil.teamConversationId(t),m=this.model.getReadTime(i);o[t]>m&&(this.model.updateReadTime(i,o[t]),this.service.emit("onConversationReadTimeUpdated",i,o[t]))}))}v2LocalConvSyncSuperTeamReadTimeHandler(t){var i=t.content.superTeam.m_map;this.logger.log("v2SyncLocalSuperTeamConvAck::",i),Object.keys(i).forEach((t=>{var o=this.core.V2NIMConversationIdUtil.superTeamConversationId(t),m=this.model.getReadTime(o);i[t]>m&&(this.model.updateReadTime(o,i[t]),this.service.emit("onConversationReadTimeUpdated",o,i[t]))}))}v2LocalConvSyncP2pReadTimeV2Handler(){}v2LocalConvSyncTeamReadTimeV2Handler(){}v2LocalConvSyncSuperTeamReadTimeV2Handler(){}v2LocalConvMultiSyncReadTimeHandler(t){var i=t.content,o=`${0===i.scene?"p2p":1===i.scene?"team":"super_team"}-${i.to}`,{type:m,target:h}=getConvInfoFromSessionId(o,"-"),u=this.core.V2NIMConversationIdUtil.conversationId(m,h),v=this.model.getById(u),I=null==v?void 0:v.unreadCount,_=this.model.getReadTime(u);i.timetag<=_?this.logger.warn(`v2LocalConvMultiSyncReadTimeHandler: ${u} do not need update ack ${i.timetag}/${_}`):(this.model.updateReadTime(u,i.timetag),this.service.emit("onConversationReadTimeUpdated",u,i.timetag),v?(v=this.service.compute.computeConvWithUnread(v),this.model.upsert(v),this.service.unread.digestUnreadCountChange(),void 0===I&&v.unreadCount>0?this.service.triggerConversationCreated(v):"number"==typeof I&&v.unreadCount!==I&&this.service.triggerConversationChanged([v])):this.logger.log(`v2LocalConvMultiSyncReadTimeHandler: ${u} not exist`))}v2LocalConvSuperTeamMultiSyncReadTimeHandler(t){this.v2LocalConvMultiSyncReadTimeHandler(t)}v2LocalConvStickTopMultiSyncAddHandler(t){var{data:i}=t.content,{target:o,type:m}=getConvInfoFromSessionId(i.id),h=this.core.V2NIMConversationIdUtil.conversationId(m,o);this.model.updateStickTop(h,!0);var u=this.model.getById(h);u&&(u.stickTop=!0,u.updateTime=u.updateTime>i.updateTime?u.updateTime:i.updateTime,u.sortOrder=this.service.compute.computeSortOrder(!0,i.updateTime),this.model.upsert(u),this.service.triggerConversationChanged([u]))}v2LocalConvStickTopMultiSyncDeleteHandler(t){var{data:i,timetag:o}=t.content,{target:m,type:h}=getConvInfoFromSessionId(i.id),u=this.core.V2NIMConversationIdUtil.conversationId(h,m);this.model.updateStickTop(u,!1);var v=this.model.getById(u);v&&(v.stickTop=!1,v.updateTime=v.updateTime>o?v.updateTime:o,v.sortOrder=this.service.compute.computeSortOrder(!1,o),this.model.upsert(v),this.service.triggerConversationChanged([v]))}}class V2NIMLocalConversationEventImpl{constructor(t,i){this.core=t,this.service=i,this.model=this.service.model,this.compute=this.service.compute,this.logger=this.core.logger}setListener(){this.core.eventBus.on("V2NIMLoginService/syncing",(()=>this.service.emit("onSyncStarted"))),this.core.eventBus.on("V2NIMLoginService/syncDone",this.onSyncDone.bind(this)),this.core.eventBus.on("V2NIMMessageService/sendMessage",this.sendMsg.bind(this)),this.core.eventBus.on("V2NIMMessageService/onMsg",this.recvMsg.bind(this)),this.core.eventBus.on("V2NIMMessageService/modifyMsg",this.modifyMsg.bind(this)),this.core.eventBus.on("V2NIMMessageService/deleteMessages",this.deleteMessages.bind(this)),this.core.eventBus.on("V2NIMMessageService/revokeMessages",this.deleteMessages.bind(this)),this.core.eventBus.on("V2NIMMessageLogUtil/onClearHistoryNotifications",this.clearMessages.bind(this)),this.core.eventBus.on("V2NIMMessageService/roamingMsgs",this.generateConv.bind(this)),this.core.eventBus.on("V2NIMMessageService/offlineMsgs",this.generateConv.bind(this)),this.core.eventBus.on("V2NIMSettingService/setMute",this.setMute.bind(this))}beforeEmit(t,...i){var o,m=`${this.service.name}::emit ${t.toString()}`;if("onConversationCreated"===t){var h=i[0],u=null===(o=h.lastMessage)||void 0===o?void 0:o.messageRefer;this.logger.log(`${m}`,`id:${h.conversationId};unread:${h.unreadCount};lastMsg:${(null==u?void 0:u.messageClientId)||""}/${(null==u?void 0:u.messageServerId)||""}`)}else if("onConversationChanged"===t){var v=i[0];this.logger.log(`${m}`,v.map((t=>{var i,o=null===(i=t.lastMessage)||void 0===i?void 0:i.messageRefer;return`id:${t.conversationId};unread:${t.unreadCount};lastMsg:${(null==o?void 0:o.messageClientId)||""}/${(null==o?void 0:o.messageServerId)||""}`})))}else this.logger.log(`${m}`,...i)}onSyncDone(t){if(t)this.service.emit("onSyncFailed",t);else{var i=this.model.getAll();(i=i.map((t=>{var i=t.conversationId,o=this.compute.computeConvByMsgsCache(i);return o=this.compute.computeConvWithUnread(o),o=this.compute.computeFromExternal(o),this.model.upsert(o),this.model.getById(i)}))).length>0&&(this.service.triggerConversationChanged(i),this.service.unread.resetTotalAfterSyncDone()),this.service.emit("onSyncFinished")}}generateConv(t){uniq(t.map((t=>t.conversationId))).forEach((t=>{var i=this.compute.computeConvByMsgsCache(t);this.model.upsert(i)}))}setMute(t,i){var o=this.model.getById(t);o&&o.mute!==i&&(o.mute=i,this.model.upsert(o),this.service.triggerConversationChanged([o]))}deleteMessages(t){var i=new Set;t.forEach((t=>{var o,m=t.messageRefer.conversationId,h=this.model.getById(m);if(h){if(t.messageRefer.messageClientId===(null===(o=h.lastMessage)||void 0===o?void 0:o.messageRefer.messageClientId)){i.add(m);var u=this.core.V2NIMMessageService.model.getLastMessageOfConversation(m);h.lastMessage=u?formatLastMessageFromMessage(this.core,u,0,u.sendingState):void 0}var v=this.model.getReadTime(m);if(h.unreadCount>0&&this.service.unread.isMessageReferUnread(t.messageRefer,v)&&(i.add(m),h.unreadCount--),"deleteTime"in t)t.deleteTime>h.updateTime&&(h.updateTime=t.deleteTime,h.sortOrder=this.compute.computeSortOrder(h.stickTop,h.updateTime));else{var I=this.core.timeOrigin.getNTPTime();h.updateTime=I,h.sortOrder=this.compute.computeSortOrder(h.stickTop,I)}this.model.upsert(h)}}));var o=Array.from(i);!this.core.V2NIMLoginService.dataSync.checkSyncing()&&o.length>0&&(this.service.triggerConversationChanged(o.map((t=>this.model.getById(t)))),this.service.unread.digestUnreadCountChange())}sendMsg(t){var i=t.conversationId,o=this.model.getById(i);if(o){var m=o.lastMessage,h=this.updateCauseMessage(o,t);m!==h.lastMessage&&this.service.triggerConversationChanged([h])}else{var u=this.createCauseMessage(i,t);if(!u)return;this.service.triggerConversationCreated(u)}}recvMsg(t){var i=t.conversationId,o=this.model.getById(i);if(o){var m=o.lastMessage,h=o.unreadCount,u=this.updateCauseMessage(o,t);u=this.compute.computeConvWithUnread(u,t);var v=m!==(u=this.compute.computeFromExternal(u)).lastMessage,I=h!==u.unreadCount;this.model.upsert(u),(v||I)&&this.service.triggerConversationChanged([u])}else{var _=this.createCauseMessage(i,t);if(!_)return;_=this.compute.computeConvWithUnread(_,t),_=this.compute.computeFromExternal(_),this.model.upsert(_),this.service.triggerConversationCreated(_)}this.service.unread.digestUnreadCountChange()}updateCauseMessage(t,i){return t=this.compute.computeConvWithLastMsg(t,i),this.model.upsert(t),this.model.getById(t.conversationId)}createCauseMessage(t,i){var o,m,h;if(!1!==(null===(o=i.messageConfig)||void 0===o?void 0:o.unreadEnabled)||!1!==(null===(m=i.messageConfig)||void 0===m?void 0:m.lastMessageUpdateEnabled)){var u=this.core.V2NIMConversationIdUtil.parseConversationType(t),v=this.model.getStickTop(t),I=!1===(null===(h=i.messageConfig)||void 0===h?void 0:h.lastMessageUpdateEnabled)?void 0:formatLastMessageFromMessage(this.core,i,0,i.sendingState),_=this.core.timeOrigin.getNTPTime(),M={conversationId:t,type:u,createTime:I?i.createTime:_,updateTime:I?i.createTime:_,sortOrder:this.compute.computeSortOrder(v,I?i.createTime:_),stickTop:v,localExtension:"",lastMessage:I,unreadCount:0};return this.model.upsert(M),M}}clearMessages(t){var i=new Set;t.forEach((t=>{var{conversationId:o,deleteTime:m}=t,h=this.model.getById(o);h&&(h.unreadCount>0&&(h.unreadCount=0,i.add(o)),h.lastMessage&&h.lastMessage.messageRefer.createTime<=t.deleteTime&&(h.lastMessage=void 0,i.add(o)),m>h.updateTime&&(h.updateTime=m,h.sortOrder=this.compute.computeSortOrder(h.stickTop,h.updateTime)),this.model.upsert(h))}));var o=Array.from(i);!this.core.V2NIMLoginService.dataSync.checkSyncing()&&o.length>0&&(this.service.triggerConversationChanged(o.map((t=>this.model.getById(t)))),this.service.unread.digestUnreadCountChange())}modifyMsg(t){var i,o=t.conversationId,m=t.messageClientId,h=this.model.getById(o),u=this.core.V2NIMMessageService.model.getMessageById(m);if(h||u)if(h)t.messageClientId===(null===(i=h.lastMessage)||void 0===i?void 0:i.messageRefer.messageClientId)&&(h.lastMessage=formatLastMessageFromMessage(this.core,t,0,t.sendingState),this.service.triggerConversationChanged([h]));else{var v=this.createCauseMessage(o,t);if(!v)return;this.service.triggerConversationCreated(v)}}}var yr={type:"array",itemRules:{type:"enum",values:[1,2,3]},min:1};class V2NIMLocalConversationServiceImpl extends V2Service{constructor(t,i={}){super("V2NIMLocalConversationService",t),this.config={},this.model=new V2NIMLocalConversationModelImpl,this.unread=new V2NIMLocalConversationUnreadImpl(this.core,this),this.compute=new V2NIMLocalConversationComputeImpl(this.core,this),this.event=new V2NIMLocalConversationEventImpl(this.core,this),this.handler=new V2NIMLocalConversationHandlerImpl(this.core,this),this.core._registerDep(V2NIMConversationIdUtilImpl,"V2NIMConversationIdUtil"),this.core._registerDep(V2NIMMessageServiceImpl,"V2NIMMessageService"),"v2"===this.core.options.apiVersion&&(registerParser({cmdMap:cr,cmdConfig:gr}),this.setOptions(i),this.setListener())}setOptions(t){this.config=Object.assign(this.config,t)}setListener(){this.event.setListener()}reset(){this.model.reset(),this.unread.reset()}emit(t,...i){return this.event.beforeEmit(t,...i),super.emit(t,...i)}getConversationList(t,i){this.checkV2(),validate({offset:{type:"number",min:0}},{offset:t},"",!0),validate({limit:{type:"number",min:1}},{limit:i},"",!0),this.core.V2NIMLoginService.checkIllegalState();var o=this.model.getByOption(t,i,{});return o.conversationList=o.conversationList.map((t=>this.compute.computeFromExternal(t))),Promise.resolve(o)}getConversationListByOption(t,i,o){this.checkV2(),validate({offset:{type:"number",min:0}},{offset:t},"",!0),validate({limit:{type:"number",min:1}},{limit:i},"",!0),validate({conversationTypes:{type:"array",itemType:"number",required:!1},onlyUnread:{type:"boolean",required:!1}},o,"option",!0),this.core.V2NIMLoginService.checkIllegalState();var m=this.model.getByOption(t,i,o);return m.conversationList=m.conversationList.map((t=>this.compute.computeFromExternal(t))),Promise.resolve(m)}getConversation(t){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validateConversationId(this.core.account,t);var i=this.model.getById(t);if(i)return this.compute.computeFromExternal(i);throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_RESOURCE_NOT_EXIST})}))}getConversationListByIds(t){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate({conversationIds:{type:"array",itemType:"string",min:1}},{conversationIds:t},"",!0),this.core.V2NIMLoginService.checkIllegalState();var i=t.map((t=>this.model.getById(t))).filter((t=>!!t));return i=i.map((t=>this.compute.computeFromExternal(t)))}))}createConversation(t){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validateConversationId(this.core.account,t);var i=this.model.getById(t);if(i)return this.compute.computeFromExternal(i);var o=this.compute.computeConvByMsgsCache(t,{updateTime:this.core.timeOrigin.getNTPTime()});o=this.compute.computeConvWithUnread(o),o=this.compute.computeFromExternal(o),this.model.upsert(o);var m=this.model.getById(t);return this.triggerConversationCreated(m),m}))}deleteConversation(t,i){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validateConversationId(this.core.account,t),validate({clearMessage:{type:"boolean",required:!1}},{clearMessage:i},"",!0),yield this.unread.markConversationRead(t);var o=this.model.deleteById(t);if(!o)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_RESOURCE_NOT_EXIST});i&&this.core.V2NIMMessageService.model.deleteMessages(t),!!(o&&o.unreadCount>0)&&this.unread.digestUnreadCountChange(),this.emit("onConversationDeleted",[t])}))}deleteConversationListByIds(t,i){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate({conversationIds:{type:"array",itemType:"string",min:1}},{conversationIds:t},"",!0),validate({clearMessage:{type:"boolean",required:!1}},{clearMessage:i},"",!0),yield this.unread.markMultiConversationRead(t);var o=!1;return t.forEach((t=>{i&&this.core.V2NIMMessageService.model.deleteMessages(t),this.model.deleteById(t)&&(o=!0)})),o&&this.unread.digestUnreadCountChange(),this.emit("onConversationDeleted",t),[]}))}getStickTopConversationList(){return __awaiter(this,void 0,void 0,(function*(){return this.checkV2(),this.core.V2NIMLoginService.checkIllegalState(),this.model.getStickTopList()}))}stickTopConversation(t,i){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validateConversationId(this.core.account,t),validate({stickTop:{type:"boolean"}},{stickTop:i},"",!0);var o=this.model.getById(t);if((null==o?void 0:o.stickTop)!==i){var m=this.core.V2NIMConversationIdUtil.parseConversationTargetId(t),h=this.core.V2NIMConversationIdUtil.parseConversationType(t),u=yield this.core.sendCmd(i?"v2LocalConvStickTopAdd":"v2LocalConvStickTopDelete",{tag:{id:getSessionIdFromConvInfo(h,m)}});this.model.updateStickTop(t,i);var v=u.content.timetag||u.content.data.updateTime;this.model.upsert({conversationId:t,type:h,stickTop:i,updateTime:v,sortOrder:this.compute.computeSortOrder(i,v)});var I=[this.model.getById(t)];this.triggerConversationChanged(I)}}))}updateConversationLocalExtension(t,i){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validateConversationId(this.core.account,t),validate({localExtension:{type:"string"}},{localExtension:i},"",!0);var o=this.model.getById(t);if(!o)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_RESOURCE_NOT_EXIST});if(o.localExtension!==i){var m=Object.assign(Object.assign({},o),{localExtension:i});this.model.upsert(m),this.triggerConversationChanged([m])}}))}getTotalUnreadCount(){return this.checkV2(),this.unread.getTotalUnreadCount()||0}getUnreadCountByIds(t){this.checkV2(),validate({conversationIds:{type:"array",itemType:"string",min:1}},{conversationIds:t},"",!0);var i=this.unread.getUnreadCountByIds(t);return Promise.resolve(i)}getUnreadCountByFilter(t){this.checkV2(),this.valiteFilter(t);var i=this.unread.getUnreadCountByFilter(t);return Promise.resolve(i)}clearTotalUnreadCount(){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),this.checkLogin();var t=this.model.getAll();yield this.unread.markMultiConversationRead(t.map((t=>t.conversationId))),this.unread.clearUnreadCount(t)}))}clearUnreadCountByIds(t){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),this.checkLogin(),validate({conversationIds:{type:"array",itemType:"string",min:1}},{conversationIds:t},"",!0);var i=[],o=[],m=new RegExp(`^${this.core.account}\\|[1-3]\\|`);if(t.forEach((t=>{m.test(t)?i.push(t):o.push(t)})),i.length>0){var h=i.map((t=>this.model.getById(t))).filter((t=>!!t));yield this.unread.markMultiConversationRead(i),this.unread.clearUnreadCount(h)}return o.map((t=>({conversationId:t,error:new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_RESOURCE_NOT_EXIST})})))}))}clearUnreadCountByTypes(t){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),this.checkLogin(),validate({types:yr},{types:t},"",!0);var i=this.model.getByOption(0,1e3,{conversationTypes:t});yield this.unread.markMultiConversationRead(i.conversationList.map((t=>t.conversationId))),this.unread.clearUnreadCount(i.conversationList)}))}subscribeUnreadCountByFilter(t){var i;this.checkV2(),this.checkLogin(),this.valiteFilter(t),0===(null===(i=t.conversationTypes)||void 0===i?void 0:i.length)&&delete t.conversationTypes,this.unread.addFilter(t)}unsubscribeUnreadCountByFilter(t){var i;this.checkV2(),this.checkLogin(),this.valiteFilter(t),0===(null===(i=t.conversationTypes)||void 0===i?void 0:i.length)&&delete t.conversationTypes,this.unread.deleteFilter(t)}getConversationReadTime(t){return __awaiter(this,void 0,void 0,(function*(){return this.checkV2(),validateConversationId(this.core.account,t),this.model.getReadTime(t)}))}markConversationRead(t){return __awaiter(this,void 0,void 0,(function*(){return this.checkV2(),this.checkLogin(),validateConversationId(this.core.account,t),this.unread.markConversationRead(t)}))}setCurrentConversation(t){this.checkV2(),t&&validateConversationId(this.core.account,t),this.unread.setCurrentConversation(t)}valiteFilter(t){if(validate({filter:{type:"object",required:!0,rules:{conversationTypes:{type:"array",itemType:"number",required:!1},ignoreMuted:{type:"boolean",required:!1}}}},{filter:t},"",!0),void 0===t.conversationTypes&&!0!==t.ignoreMuted)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"Filter cannot be empty"}})}triggerConversationChanged(t){t=t.map((t=>this.compute.computeFromExternal(t))),(t=JSON.parse(JSON.stringify(t))).forEach((t=>{t.lastMessage||(t.lastMessage=void 0),delete t.lastMessageState})),this.emit("onConversationChanged",t)}triggerConversationCreated(t){t=this.compute.computeFromExternal(t),delete(t=JSON.parse(JSON.stringify(t))).lastMessageState,this.emit("onConversationCreated",t)}}class V2NIMConversationModelImpl{constructor(){this.map=new Map,this.readTimeMap=new Map}set(t){t.forEach((t=>{t=this.processConversation(t),this.map.set(t.conversationId,t)}))}reset(){this.map.clear(),this.readTimeMap.clear()}count(){return this.map.size}sort(){var t=Array.from(this.map.values());t.sort(((t,i)=>i.sortOrder-t.sortOrder)),this.map.clear(),t.forEach((t=>{this.map.set(t.conversationId,t)}))}processConversation(t){return"string"==typeof t.lastMessage&&delete t.lastMessage,void 0===t.localExtension&&(t.localExtension=""),t}getById(t){return this.map.get(t)}getStickTopList(){return Array.from(this.map.values()).filter((t=>t.stickTop)).sort(((t,i)=>i.sortOrder-t.sortOrder))}getAll(){return Array.from(this.map.values()).sort(((t,i)=>i.sortOrder-t.sortOrder))}getByOption(t,i,o){var{conversationTypes:m,onlyUnread:h,conversationGroupIds:u}=o,v=[];this.map.forEach((t=>{if((!(m&&m.length>0)||m.includes(t.type))&&(!h||t.unreadCount)&&(!o.ignoreMuted||!t.mute)){if(u){var i=t.groupIds,I=(null==i?void 0:i.length)||0;if(0===u.length&&I>0)return;if(u.length>0&&0===I)return;if(u.length>0&&I>0&&!u.some((t=>i&&i.includes(t))))return}v.push(t)}})),v=v.sort(((t,i)=>i.sortOrder-t.sortOrder));var I=0;t>0&&(I=findIndexWithinTargetValue(v,"sortOrder",t),v[I]&&v[I].sortOrder===t&&(I+=1));var _=v.slice(I).length;return(v=v.slice(I,I+i)).length>0?{offset:_>i?v[v.length-1].sortOrder:0,finished:!(_>i),conversationList:v}:{offset:0,finished:!0,conversationList:v}}upsert(t){var i=t.conversationId,o=this.map.get(i);if(!o)return t=this.processConversation(Object.assign({},t)),this.map.set(i,t),t.unreadCount>0;var m=t.unreadCount!==o.unreadCount,h=Object.assign({},o,t);return h=this.processConversation(h),this.map.set(i,h),m}bulkUpsert(t){var i=!1;return t.forEach((t=>{this.upsert(t)&&(i=!0)})),i}deleteById(t){var i=this.getById(t);if(i)return this.map.delete(t),i}updateReadTime(t,i){this.readTimeMap.set(t,i)}getReadTime(t){return this.readTimeMap.get(t)||0}}function isEqual(t,i){var o=typeof t;if(o!==typeof i)return!1;if("object"===o){if(Object.prototype.toString.call(t)!==Object.prototype.toString.call(i))return!1;if(Array.isArray(t)){if(t.length!==i.length)return!1;for(var m=0;m<t.length;m++)if(!isEqual(t[m],i[m]))return!1;return!0}if(t instanceof RegExp&&i instanceof RegExp)return t.toString()===i.toString();if(t instanceof Date&&i instanceof Date)return t.getTime()===i.getTime();if(null===t&&null===i)return!0;if(Object.keys(t).length!==Object.keys(i).length)return!1;for(var h in t)if(!isEqual(t[h],i[h]))return!1;return!0}return t===i}class V2NIMConversationVersionCacheImpl{constructor(t,i){this.fieldVersion={},this.conversationIdsForBackFill={},this.tempPacket=[],this.isSyncing=!1,this.nextCursor=0,this.core=t,this.service=i}reset(){this.tempPacket=[],this.fieldVersion={},this.conversationIdsForBackFill={},this.isSyncing=!1,this.nextCursor=0}doSync(){return __awaiter(this,void 0,void 0,(function*(){var t;this.isSyncing=!0,this.service.emit("onSyncStarted"),this.core.V2NIMLoginService.dataSync.switchDataSync({type:1,state:2,subType:"conversationSync"});try{t=yield this.core.sendCmd("v2ConversationSync",{tag:{cursor:this.nextCursor}})}catch(t){var i=t;if(i.code===Ee.V2NIM_ERROR_CODE_CANCELLED)return;return this.isSyncing=!1,this.service.emit("onSyncFailed",i),this.core.V2NIMLoginService.dataSync.switchDataSync({type:1,state:3,error:i,subType:"conversationSync"}),void this.processTempPacket()}var o=0===parseInt(get(t,"content.info.syncType")),m=get(t,"content.info.nextCursor");this.doSyncAndSuccess(o,m)}))}doSyncAndSuccess(t,i){t&&this.service.model.sort(),this.isSyncing=!1,this.nextCursor=parseInt(i)||0,this.service.unread.resetTotalAfterSyncDone(),this.service.unread.digestUnreadCountChange(),this.service.emit("onSyncFinished"),this.core.V2NIMLoginService.dataSync.switchDataSync({type:1,state:3,subType:"conversationSync"}),this.processTempPacket()}setBackFillIds(t){return t.forEach((t=>{if(2===t.lastMessageState&&this.service.compute.hasMessageService){this.conversationIdsForBackFill[t.conversationId]=!0;var i=this.core.V2NIMMessageService.model.getLastMessageOfConversation(t.conversationId);t.lastMessage=i?formatLastMessageFromMessage(this.core,i,t.lastMessageState,i.sendingState):""}else this.conversationIdsForBackFill[t.conversationId]=!1;delete t.lastMessageState})),t}recvConversationFromSyncAction(t){var{syncType:i}=get(t,"content.info"),o=formatConversationFields(this.core,get(t,"content.datas"));0===(i=parseInt(i))?(o.forEach((t=>{this.initFieldVersion(t.conversationId,t.version)})),o=this.setBackFillIds(o),this.setModel(o)):(o=this.setBackFillIds(o),this.recvConversationForCreated(o)<o.length&&this.recvConversationForChanged(o))}recvConversation(t){if(this.isSyncing)this.tempPacket.push(t);else{var i=formatConversationFields(this.core,get(t,"content.datas")).filter((t=>!!t.conversationId)),o=get(t,"content.info"),m=i.map((t=>`id:${t.conversationId}, ver:${t.version}`)).join(";");if(this.core.logger.getDebugMode()?this.core.logger.debug(`V2NIMConversation::recvConversation: ${m}.`,o,i):this.core.logger.log(`V2NIMConversation::recvConversation: ${m}.`,o),2===o.type){var h=i.map((t=>(delete this.fieldVersion[t.conversationId],this.service.model.deleteById(t.conversationId),t.conversationId)));return this.service.emit("onConversationDeleted",h),void this.service.unread.digestUnreadCountChange()}if(12!==o.type)o.type,i=this.setBackFillIds(i),this.recvConversationForCreated(i)<i.length&&this.recvConversationForChanged(i);else this.compareAndClearUnreadInModel(o)}}recvConversationForCreated(t){var i=t.filter((t=>!this.fieldVersion[t.conversationId]));return i.reduce(((t,i)=>{if(!this.fieldVersion[i.conversationId]){this.initFieldVersion(i.conversationId,i.version),t=!!this.updateModel(i)||t;var o=this.service.model.getById(i.conversationId);return o&&this.service.triggerConversationCreated(o),t}return t}),!1)&&this.service.unread.digestUnreadCountChange(),i.length}recvConversationForChanged(t){var i=this.bulkCompare(t);if(0!==i.length){this.bulkUpdateModel(i);var o=i.map((t=>this.service.model.getById(t.conversationId))).filter((t=>!!t));this.service.triggerConversationChanged(o)}}processTempPacket(){this.tempPacket.forEach((t=>{this.recvConversation(t)})),this.tempPacket=[]}bulkCompare(t){return t.map((t=>this.compare(t))).filter((t=>!!t))}compare(t){var{version:i,conversationId:o,deleteFlag:m,type:h}=t,u={},v=0;return["stickTop","groupIds","serverExtension","localExtension","lastMessage","lastMessageState","unreadCount","sortOrder","createTime","updateTime","lastReadTime"].forEach((m=>{var h=m;if(void 0!==t[h]){var I=this.fieldVersion[o];I&&"number"==typeof I[h]&&I[h]>=i||(this.fieldVersion[o]=this.fieldVersion[o]||{},this.fieldVersion[o][h]=i,u[h]=t[h],v+=1)}})),v?Object.assign(Object.assign({},u),{conversationId:o,deleteFlag:m,version:i,type:h}):void 0}bulkUpdateModel(t){var i=!1;t.forEach((t=>{this.updateModel(t)&&(i=!0)})),i&&this.service.unread.digestUnreadCountChange()}initFieldVersion(t,i){this.fieldVersion[t]={stickTop:i,groupIds:i,serverExtension:i,lastMessage:i,lastMessageState:i,unreadCount:i,sortOrder:i,createTime:i,updateTime:i,lastReadTime:i}}initConversation(t,i){var o=Date.now();return Object.assign({conversationId:t,type:this.core.V2NIMConversationIdUtil.parseConversationType(t),stickTop:!1,localExtension:"",serverExtension:"",unreadCount:0,lastReadTime:0,createTime:o,updateTime:o,sortOrder:o},i)}updateModel(t){var{deleteFlag:i,conversation:o}=formatConversationByField(t);if(i){var m=this.service.model.deleteById(o.conversationId);return!!(m&&m.unreadCount>0)}return this.service.model.upsert(o)}setModel(t){var i=t.filter((t=>!t.deleteFlag)).map((t=>formatConversationByField(t).conversation));this.service.model.set(i)}updateModelWithLastMessage(t,i,o,m){var h=this.service.model.getById(t),u=i?formatLastMessageFromMessage(this.core,i,o,m):void 0;if(!isEqual(null==h?void 0:h.lastMessage,u))if(h){var v=Object.assign(Object.assign({},h),{sortOrder:u?h.stickTop?u.messageRefer.createTime+1e15:u.messageRefer.createTime:h.sortOrder,lastMessage:u});this.service.model.upsert(v),this.service.triggerConversationChanged([v])}else{this.initFieldVersion(t,-1);var I=this.initConversation(t,{lastMessage:u});this.service.model.upsert(I),this.service.triggerConversationCreated(I)}}updateModelByRevoke(t){var i=[];t.forEach((t=>{var{postscript:o,messageRefer:m}=t,h=__rest(t,["postscript","messageRefer"]),u=m.conversationId,v=this.service.model.getById(u);v&&v.lastMessage&&v.lastMessage.messageRefer.messageClientId===m.messageClientId&&1!==v.lastMessage.lastMessageState&&(v.lastMessage.lastMessageState=1,o&&(v.lastMessage.text=o),Object.assign(v.lastMessage,h),this.service.model.upsert(v),i.push(v))})),i.length>0&&this.service.triggerConversationChanged(i)}compareAndUpdateModel(t){this.core.logger.log("V2NIMConversation::compareAndUpdateModel",t.map((t=>t.conversationId)));var i=!1,o=[];t.forEach((t=>{var m=this.compare(t);if(m){var h=this.service.model.getById(t.conversationId);this.updateModel(m)&&(i=!0);var u=this.service.model.getById(t.conversationId);u&&(h?o.push(u):this.service.triggerConversationCreated(u))}})),o.length>0&&this.service.triggerConversationChanged(o),i&&this.service.unread.digestUnreadCountChange()}compareAndDeleteModel(t){this.core.logger.log("V2NIMConversation::compareAndDeleteModel",t);var i=t.reduce(((t,i)=>{delete this.fieldVersion[i];var o=this.service.model.deleteById(i);return!!!!(o&&o.unreadCount>0)||t}),!1);this.service.emit("onConversationDeleted",t),i&&this.service.unread.digestUnreadCountChange()}compareAndDeleteGroupInModel(t,i){this.core.logger.log("V2NIMConversation::compareAndDeleteGroupInModel",t,i);var o=[];Object.keys(this.fieldVersion).forEach((m=>{var h=this.fieldVersion[m];if(void 0===h.groupIds||t>h.groupIds){h.groupIds=t;var u=this.service.model.getById(m);if(u&&u.groupIds&&u.groupIds.length>0){var v=u.groupIds.filter((t=>t!==i));if(v.length!==u.groupIds.length){var I=Object.assign(Object.assign({},u),{groupIds:v});this.service.model.upsert(I),I&&o.push(I)}}}})),o.length>0&&this.service.triggerConversationChanged(o)}compareAndClearUnreadInModel(t){var{oneClickClearUnreadType:i,oneClickClearUnreadVersion:o,oneClickClearUnreadLastReadTime:m,oneClickClearUnreadConversationType:h,oneClickClearUnreadGroupId:u}=t;this.core.logger.log(`V2NIMConversation::compareAndClearUnreadInModel.ver:${o};type:${i};lastReadTime:${m};filter:${h||""};grounp:${u||""}`);var v=[],I=[];if(1===i)I=this.service.model.getAll();else if(h||u){var _=this.service.model.count();I=this.service.model.getByOption(0,_,{conversationTypes:h,conversationGroupIds:u?[u]:void 0}).conversationList}I.forEach((t=>{var i=t.conversationId,h=this.fieldVersion[i];if(void 0===h.unreadCount||o>h.unreadCount){h.unreadCount=o,h.lastReadTime=o;var u=t.unreadCount,I=Object.assign(Object.assign({},t),{lastReadTime:m,unreadCount:0});this.service.model.upsert(I),u>0&&v.push(I)}})),v.length>0&&this.service.triggerConversationChanged(v),this.service.unread.digestUnreadCountChange()}backfillLastMsg(t,i){var o=t=uniq(t);(i||0!==(o=t.filter((t=>this.conversationIdsForBackFill[t]))).length)&&o.forEach((t=>{var i=get(this.service.model.getById(t),"lastMessage.messageRefer.messageClientId"),o=this.service.compute.hasMessageService?this.core.V2NIMMessageService.model.getLastMessageOfConversation(t):void 0;(o&&o.messageClientId)!==i&&(this.conversationIdsForBackFill[t]=!1,o?this.updateModelWithLastMessage(t,o,2,o.sendingState):this.updateModelWithLastMessage(t,void 0,2,0))}))}}var _r={"28_1":"v2ConversationCreate","28_2":"v2ConversationDelete","28_3":"v2ConversationUpdate","28_4":"v2ConversationSetTop","28_5":"v2ConversationUnreadClear","28_6":"v2ConversationGet","28_7":"v2ConversationGetByIds","28_8":"v2ConversationGetList","28_17":"v2ConversationsDelete","28_18":"v2ConversationsUnreadClear","28_19":"v2ConversationSync","28_20":"v2ConversationNotifySync","28_21":"v2ConversationNotifySyncOnline","28_23":"v2ConversationClearTotalUnread","28_24":"v2ConversationClearTypeUnread","28_25":"v2ConversationClearGroupUnread","4_14":"syncConversationReadTime","4_20":"syncSuperTeamReadTime","4_22":"v2SyncSessionsWithMoreRoaming","4_25":"v2SyncSessionReliableInfo","30_16":"v2MarkConversationReadTime","32_25":"v2MarkSuperTeamReadTime","7_116":"v2MultiDeviceConversationReadTime","21_125":"v2MultiDeviceSuperTeamReadTime"},Mr="V2NIMConversationService",Er={conversationId:1,type:{id:2,retType:"number"},serverExtension:3,groupIds:{id:4,retConverter:t=>t?JSON.parse(t):void 0},lastMessage:5,lastMessageState:{id:6,retType:"number"},unreadCount:{id:7,retType:"number"},stickTop:{id:8,retType:"boolean"},sortOrder:{id:9,retType:"number"},version:{id:10,retType:"number"},deleteFlag:{id:11,retType:"boolean"},createTime:{id:12,retType:"number"},updateTime:{id:13,retType:"number"},lastReadTime:{id:14,retType:"number"}},Sr={type:{id:1,retType:"number"},oneClickClearUnreadType:{id:2,retType:"number"},oneClickClearUnreadConversationType:{id:3,retConverter:stringToJSONObject},oneClickClearUnreadGroupId:{id:4,retType:"string"},oneClickClearUnreadVersion:{id:5,retType:"number"},oneClickClearUnreadLastReadTime:{id:6,retType:"number"}},Tr={v2ConversationCreate:{sid:28,cid:1,service:Mr,params:[{type:"Property",name:"tag",reflectMapper:{conversationId:1}}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Er)}]},v2ConversationDelete:{sid:28,cid:2,service:Mr,params:[{type:"Property",name:"tag",reflectMapper:{conversationId:1,clearMessage:2}}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Er)}]},v2ConversationUpdate:{sid:28,cid:3,service:Mr,params:[{type:"Property",name:"tag",reflectMapper:{conversationId:1,serverExtension:2}}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Er)}]},v2ConversationSetTop:{sid:28,cid:4,service:Mr,params:[{type:"Property",name:"tag",reflectMapper:{conversationId:1,stickTop:2}}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Er)}]},v2ConversationUnreadClear:{sid:28,cid:5,service:Mr,params:[{type:"Property",name:"tag",reflectMapper:{conversationId:1}}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Er)}]},v2ConversationGet:{sid:28,cid:6,service:Mr,params:[{type:"Property",name:"tag",reflectMapper:{conversationId:1}}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Er)}]},v2ConversationGetByIds:{sid:28,cid:7,service:Mr,params:[{type:"Property",name:"tag",reflectMapper:{conversationIds:1}}],response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(Er)},{type:"Property",name:"info",reflectMapper:{1:"failedMap"}}]},v2ConversationGetList:{sid:28,cid:8,service:Mr,params:[{type:"Property",name:"tag",reflectMapper:{cursor:1,limit:2}}],response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(Er)},{type:"Property",name:"info",reflectMapper:{1:"hasMore",2:"offset"}}]},v2ConversationsDelete:{sid:28,cid:17,service:Mr,params:[{type:"Property",name:"tag",reflectMapper:{conversationIds:1,clearMessage:2}}],response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(Er)},{type:"Property",name:"info",reflectMapper:{1:"failedMap"}}]},v2ConversationsUnreadClear:{sid:28,cid:18,service:Mr,params:[{type:"Property",name:"tag",reflectMapper:{conversationIds:1}}],response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(Er)},{type:"Property",name:"info",reflectMapper:{1:"failedMap"}}]},v2ConversationSync:{sid:28,cid:19,service:Mr,params:[{type:"Property",name:"tag",reflectMapper:{cursor:1}}],response:[{type:"Property",name:"info",reflectMapper:{1:"nextCursor",2:"syncType"}}]},v2ConversationNotifySync:{sid:28,cid:20,service:Mr,response:[{type:"Property",name:"info",reflectMapper:{1:"nextCursor",2:"syncType"}},{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(Er)}]},v2ConversationNotifySyncOnline:{sid:28,cid:21,service:Mr,response:[{type:"Property",name:"info",reflectMapper:invertSerializeItem(Sr)},{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(Er)}]},v2ConversationClearTotalUnread:{sid:28,cid:23,service:Mr,response:[{type:"Property",name:"info",reflectMapper:invertSerializeItem(Sr)}]},v2ConversationClearTypeUnread:{sid:28,cid:24,service:Mr,params:[{type:"Property",name:"tag",reflectMapper:{conversationType:1}}],response:[{type:"Property",name:"info",reflectMapper:invertSerializeItem(Sr)}]},v2ConversationClearGroupUnread:{sid:28,cid:25,service:Mr,params:[{type:"Property",name:"tag",reflectMapper:{groupId:1}}],response:[{type:"Property",name:"info",reflectMapper:invertSerializeItem(Sr)}]},syncConversationReadTime:{sid:4,cid:14,service:Mr,response:[{type:"StrLongMap",name:"p2p"},{type:"LongLongMap",name:"team"},{type:"Long",name:"timetag"}]},syncSuperTeamReadTime:{sid:4,cid:20,service:Mr,response:[{type:"LongLongMap",name:"superTeam"}]},v2SyncSessionsWithMoreRoaming:{sid:4,cid:22,service:Mr,response:[]},v2SyncSessionReliableInfo:{sid:4,cid:25,service:Mr,response:[]},v2MarkConversationReadTime:{sid:30,cid:16,service:Mr,params:[{type:"Byte",name:"scene"},{type:"String",name:"to"},{type:"Long",name:"timetag"}]},v2MarkSuperTeamReadTime:{sid:32,cid:25,service:Mr,params:[{type:"Long",name:"to"},{type:"Long",name:"timetag"}]},v2MultiDeviceConversationReadTime:{sid:30,cid:116,service:Mr,response:[{type:"Byte",name:"scene"},{type:"String",name:"to"},{type:"Long",name:"timetag"}]},v2MultiDeviceSuperTeamReadTime:{sid:21,cid:125,service:Mr,response:[{type:"Long",name:"to"},{type:"Long",name:"timetag"}]}};class V2NIMConversationUnreadImpl{constructor(t,i){this.totalUnreadCount=void 0,this.unreadCountByFilter={},this.core=t,this.service=i}reset(){this.totalUnreadCount=void 0,this.unreadCountByFilter={}}getTotalUnreadCount(){return this.totalUnreadCount}resetTotalAfterSyncDone(){var t=this.service.model.getAll().reduce(((t,i)=>t+(i.unreadCount||0)),0),i=this.totalUnreadCount;return void 0!==i&&i===t||(this.totalUnreadCount=t,this.service.emit("onTotalUnreadCountChanged",t)),t}digestUnreadCountChange(){this._digest()}_digest(){var t=this.totalUnreadCount,i=this.service.model.getAll().reduce(((t,i)=>t+(i.unreadCount||0)),0);this.core.logger.log(`V2NIMConversation::digestUnreadCountChange:oldUnreadCount ${t}, newUnreadCount ${i}`),t!==i&&(this.totalUnreadCount=i,this.service.emit("onTotalUnreadCountChanged",i)),Object.keys(this.unreadCountByFilter).forEach((t=>{var i=JSON.parse(t),o=this.getUnreadCountByFilter(i),m=this.unreadCountByFilter[t];this.unreadCountByFilter[t]=o,i.equals=equals.bind(i),m!==o&&this.service.emit("onUnreadCountChangedByFilter",i,o)}))}getUnreadCountByIds(t){return t.reduce(((t,i)=>{var o=this.service.model.getById(i);return t+(o&&o.unreadCount||0)}),0)}getUnreadCountByFilter(t){var i=this.service.model.count();return this.service.model.getByOption(0,i,{conversationTypes:t.conversationTypes,conversationGroupIds:t.conversationGroupId?[t.conversationGroupId]:void 0,ignoreMuted:t.ignoreMuted}).conversationList.reduce(((t,i)=>t+(i.unreadCount||0)),0)}addFilter(t){var i=generateFilterKey(t);if(void 0!==this.unreadCountByFilter[i])throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_RESOURCE_ALREADY_EXIST});var o=JSON.parse(i),m=this.getUnreadCountByFilter(o);this.unreadCountByFilter[i]=m,this.service.emit("onUnreadCountChangedByFilter",o,m)}deleteFilter(t){var i=generateFilterKey(t);if(void 0===this.unreadCountByFilter[i])throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_RESOURCE_NOT_EXIST});delete this.unreadCountByFilter[i]}}function generateFilterKey(t){var{conversationTypes:i}=t;return i&&(i=i.sort()),JSON.stringify({conversationGroupId:t.conversationGroupId,conversationTypes:i,ignoreMuted:t.ignoreMuted})}function equals(t){return JSON.stringify(this)===generateFilterKey(t)}var Cr={createTime:{type:"number"},updateTime:{type:"number"}};function formatConversationGroups(t){return t&&t.length>0?t.map((t=>formatConversationGroup(t))):[]}function formatConversationGroup(t){return format(Cr,t)}function formatFailedMap(t){var i=JSON.parse(t);return Object.keys(i).map((t=>({conversationId:t,error:new V2NIMErrorImpl({code:i[t]})})))}var Nr,Ar={type:{type:"number"},deleteVersion:{type:"number"},conversationIds:{type:"object"}};function formatConversationGroupNotify(t){return format(Ar,t)}!function(t){t[t.createConversationGroup=1]="createConversationGroup",t[t.deleteConversationGroup=2]="deleteConversationGroup",t[t.updateConversationGroup=3]="updateConversationGroup",t[t.addConversationToGroup=4]="addConversationToGroup",t[t.removeConversationFromGroup=5]="removeConversationFromGroup"}(Nr||(Nr={}));class V2NIMConversationComputeImpl{constructor(t,i){this.core=t,this.service=i}get hasUserService(){var t;return!!(null===(t=this.core.V2NIMUserService)||void 0===t?void 0:t.name)}get hasFriendService(){var t;return!!(null===(t=this.core.V2NIMFriendService)||void 0===t?void 0:t.name)}get hasTeamService(){var t;return!!(null===(t=this.core.V2NIMTeamService)||void 0===t?void 0:t.name)}get hasMessageService(){var t;return!!(null===(t=this.core.V2NIMMessageService)||void 0===t?void 0:t.name)}computeConvs(t){return t.map((t=>this.computeConv(t)))}computeConv(t){var i,o,m,h,u;if(0===t.type)return t;var v=this.core.V2NIMConversationIdUtil.parseConversationType(t.conversationId),I=this.core.V2NIMConversationIdUtil.parseConversationTargetId(t.conversationId),_={};if(t.lastReadTime||(_.lastReadTime=this.service.model.getReadTime(t.conversationId)),(null===(i=this.core.V2NIMSettingService)||void 0===i?void 0:i.name)&&(_.mute=this.core.V2NIMSettingService.getConversationMuteStatus(t.conversationId)),1===v&&this.hasUserService){var M,E=this.core.V2NIMUserService.model.getUser(I),S=this.hasFriendService?this.core.V2NIMFriendService.model.getFriend(I):void 0;t.conversationId!==(null===(o=t.lastMessage)||void 0===o?void 0:o.messageRefer.conversationId)||0!==(null===(m=t.lastMessage)||void 0===m?void 0:m.lastMessageState)&&2!==(null===(h=t.lastMessage)||void 0===h?void 0:h.lastMessageState)||(M=null===(u=t.lastMessage)||void 0===u?void 0:u.senderName),_.name=(null==S?void 0:S.alias)||(null==E?void 0:E.name)||M||I,_.avatar=(null==E?void 0:E.avatar)||""}else if(2===v&&this.hasTeamService){var T=this.core.V2NIMTeamService.model.getById(I,1);_.name=(null==T?void 0:T.name)||I,_.avatar=(null==T?void 0:T.avatar)||""}else if(3===v&&this.hasTeamService){var C=this.core.V2NIMTeamService.model.getById(I,2);_.name=(null==C?void 0:C.name)||I,_.avatar=(null==C?void 0:C.avatar)||""}return Object.assign(t,_),t}computeReadTimeForMark(t){var i,o,m,h=t.conversationId,u=this.service.model.getReadTime(h);if(null===(o=null===(i=null==t?void 0:t.lastMessage)||void 0===i?void 0:i.messageRefer)||void 0===o?void 0:o.createTime)m=t.lastMessage.messageRefer.createTime;else{if(!this.core.timeOrigin.checkNodeReliable())return u||0;m=this.core.timeOrigin.getNTPTime()}return m}}class V2NIMConversationHandlerImpl{constructor(t,i){this.core=t,this.service=i,this.model=this.service.model,this.logger=this.core.logger}get ifEnabled(){return!0===this.core.options.enableV2CloudConversation}v2ConversationNotifySyncHandler(t){this.ifEnabled&&this.service.versionCache.recvConversationFromSyncAction(t)}v2ConversationNotifySyncOnlineHandler(t){this.ifEnabled&&this.service.versionCache.recvConversation(t)}syncConversationReadTimeHandler(t){var i,o,m;if(this.ifEnabled){if(null===(i=null==t?void 0:t.content)||void 0===i?void 0:i.p2p)for(var[h,u]of Object.entries(t.content.p2p))this.model.updateReadTime(this.core.V2NIMConversationIdUtil.p2pConversationId(h),u),this.service.emit("onConversationReadTimeUpdated",this.core.V2NIMConversationIdUtil.p2pConversationId(h),u);if(null===(m=null===(o=null==t?void 0:t.content)||void 0===o?void 0:o.team)||void 0===m?void 0:m.m_map)for(var[v,I]of Object.entries(t.content.team.m_map))this.model.updateReadTime(this.core.V2NIMConversationIdUtil.teamConversationId(v),I),this.service.emit("onConversationReadTimeUpdated",this.core.V2NIMConversationIdUtil.teamConversationId(v),I)}}syncSuperTeamReadTimeHandler(t){var i,o;if(this.ifEnabled&&(null===(o=null===(i=null==t?void 0:t.content)||void 0===i?void 0:i.superTeam)||void 0===o?void 0:o.m_map))for(var[m,h]of Object.entries(t.content.superTeam.m_map))this.model.updateReadTime(this.core.V2NIMConversationIdUtil.superTeamConversationId(m),h),this.service.emit("onConversationReadTimeUpdated",this.core.V2NIMConversationIdUtil.superTeamConversationId(m),h)}v2MultiDeviceConversationReadTimeHandler(t){var i;this.ifEnabled&&(null===(i=null==t?void 0:t.content)||void 0===i?void 0:i.to)&&(0===t.content.scene?(this.model.updateReadTime(this.core.V2NIMConversationIdUtil.p2pConversationId(t.content.to),t.content.timetag),this.service.emit("onConversationReadTimeUpdated",this.core.V2NIMConversationIdUtil.p2pConversationId(t.content.to),t.content.timetag)):(this.model.updateReadTime(this.core.V2NIMConversationIdUtil.teamConversationId(t.content.to),t.content.timetag),this.service.emit("onConversationReadTimeUpdated",this.core.V2NIMConversationIdUtil.teamConversationId(t.content.to),t.content.timetag)))}v2MultiDeviceSuperTeamReadTimeHandler(t){var i;this.ifEnabled&&(null===(i=null==t?void 0:t.content)||void 0===i?void 0:i.to)&&(this.model.updateReadTime(this.core.V2NIMConversationIdUtil.superTeamConversationId(t.content.to),t.content.timetag),this.service.emit("onConversationReadTimeUpdated",this.core.V2NIMConversationIdUtil.superTeamConversationId(t.content.to),t.content.timetag))}}class V2NIMConversationEventImpl{constructor(t,i){this.core=t,this.service=i,this.model=this.service.model,this.versionCache=this.service.versionCache,this.logger=this.core.logger}setListener(){this.core.eventBus.on("V2NIMLoginService/loginLifeCycleLoginSucc",(()=>this.versionCache.doSync())),this.core.eventBus.on("V2NIMConversationService/conversationOnlineSyncNotify",this.conversationOnlineSyncNotify.bind(this)),this.core.eventBus.on("V2NIMMessageService/sendMessage",this.sendMessage.bind(this)),this.core.eventBus.on("V2NIMMessageService/deleteMessages",this.deleteMessages.bind(this)),this.core.eventBus.on("V2NIMMessageService/revokeMessages",this.revokeMessages.bind(this)),this.core.eventBus.on("V2NIMMessageService/roamingMsgs",this.roamingOrOfflineMsgs.bind(this)),this.core.eventBus.on("V2NIMMessageService/offlineMsgs",this.roamingOrOfflineMsgs.bind(this)),this.core.eventBus.on("V2NIMSettingService/setMute",this.setMute.bind(this))}beforeEmit(t,...i){var o,m,h=`${this.service.name}::emit ${t.toString()}`;if("onConversationCreated"===t){var u=i[0];this.logger.log(`${h}`,`id:${u.conversationId};unread:${u.unreadCount};lastMsg:${null===(o=u.lastMessage)||void 0===o?void 0:o.messageRefer.messageClientId}/${null===(m=u.lastMessage)||void 0===m?void 0:m.messageRefer.messageServerId}`)}else if("onConversationChanged"===t){var v=i[0];this.logger.log(`${h}`,v.map((t=>{var i,o;return`id:${t.conversationId};unread:${t.unreadCount};lastMsg:${null===(i=t.lastMessage)||void 0===i?void 0:i.messageRefer.messageClientId}/${null===(o=t.lastMessage)||void 0===o?void 0:o.messageRefer.messageServerId}`})))}else this.logger.log(`${h}`,...i)}conversationOnlineSyncNotify(t,i){var o;!1!==(null===(o=null==i?void 0:i.messageConfig)||void 0===o?void 0:o.lastMessageUpdateEnabled)&&(t.content.info=deserialize(t.content.info,invertSerializeItem(Sr)),t.content.data=deserialize(t.content.data,invertSerializeItem(Er)),i&&(t.content.data.lastMessage=formatLastMessageFromMessage(this.core,i,0)),t.content.datas=[t.content.data],this.service.handler.v2ConversationNotifySyncOnlineHandler.call(this,t))}sendMessage(t,i){var o,m;1===i&&!0===(null===(o=t.messageConfig)||void 0===o?void 0:o.historyEnabled)||!1!==(null===(m=null==t?void 0:t.messageConfig)||void 0===m?void 0:m.lastMessageUpdateEnabled)&&this.versionCache.updateModelWithLastMessage(t.conversationId,t,2,i)}deleteMessages(t){var i=t.map((t=>t.messageRefer.conversationId));this.versionCache.backfillLastMsg(i,!0)}revokeMessages(t){this.versionCache.updateModelByRevoke(t)}roamingOrOfflineMsgs(t){var i=uniq(t.map((t=>t.conversationId)));this.versionCache.backfillLastMsg(i,!1)}setMute(t,i){var o=this.model.getById(t);o&&o.mute!==i&&(o.mute=i,this.model.upsert(o),this.service.triggerConversationChanged([o]))}}class V2NIMConversationServiceImpl extends V2Service{constructor(t,i={}){super("V2NIMConversationService",t),this.config={},this.model=new V2NIMConversationModelImpl,this.versionCache=new V2NIMConversationVersionCacheImpl(this.core,this),this.unread=new V2NIMConversationUnreadImpl(this.core,this),this.compute=new V2NIMConversationComputeImpl(this.core,this),this.event=new V2NIMConversationEventImpl(this.core,this),this.handler=new V2NIMConversationHandlerImpl(this.core,this),this.core._registerDep(V2NIMConversationIdUtilImpl,"V2NIMConversationIdUtil"),"v2"===this.core.options.apiVersion&&!0===this.core.options.enableV2CloudConversation&&(registerParser({cmdMap:_r,cmdConfig:Tr}),this.setOptions(i),this.setListener())}setOptions(t){this.config=Object.assign(this.config,t)}setListener(){this.event.setListener()}reset(){this.versionCache.reset(),this.model.reset(),this.unread.reset()}emit(t,...i){return this.event.beforeEmit(t,...i),super.emit(t,...i)}checkEnable(){if(!0!==this.core.options.enableV2CloudConversation)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_MISUSE,detail:{reason:"V2CloudConversation is not enabled"}})}getConversationList(t,i){this.checkEnable(),this.checkV2(),validate({offset:{type:"number",min:0}},{offset:t},"",!0),validate({limit:{type:"number",min:1}},{limit:i},"",!0),this.core.V2NIMLoginService.checkIllegalState();var o=this.model.getByOption(t,i,{});return o.conversationList=this.compute.computeConvs(o.conversationList),Promise.resolve(o)}getConversationListByOption(t,i,o){this.checkEnable(),this.checkV2(),validate({offset:{type:"number",min:0}},{offset:t},"",!0),validate({limit:{type:"number",min:1}},{limit:i},"",!0),validate({option:{type:"object",required:!0,rules:{conversationTypes:{type:"array",itemType:"number",required:!1},onlyUnread:{type:"boolean",required:!1},conversationGroupIds:{type:"array",itemType:"string",required:!1}}}},{option:o},"",!0),this.core.V2NIMLoginService.checkIllegalState();var m=this.model.getByOption(t,i,o);return m.conversationList=this.compute.computeConvs(m.conversationList),Promise.resolve(m)}getConversation(t){return __awaiter(this,void 0,void 0,(function*(){this.checkEnable(),this.checkV2(),validateConversationId(this.core.account,t);var i=this.model.getById(t);if(i)return this.compute.computeConv(i);throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_RESOURCE_NOT_EXIST})}))}getConversationListByIds(t){return __awaiter(this,void 0,void 0,(function*(){this.checkEnable(),this.checkV2(),validate({conversationIds:{type:"array",itemType:"string",min:1}},{conversationIds:t},"",!0),this.core.V2NIMLoginService.checkIllegalState();var i=t.map((t=>this.model.getById(t))).filter((t=>!!t));return i=this.compute.computeConvs(i)}))}createConversation(t){return __awaiter(this,void 0,void 0,(function*(){this.checkEnable(),this.checkV2(),validateConversationId(this.core.account,t);var i=get(yield this.core.sendCmd("v2ConversationCreate",{tag:{conversationId:t}}),"content.data"),o=formatConversationField(this.core,i);this.versionCache.compareAndUpdateModel([o]);var m=this.model.getById(t);if(m)return this.compute.computeConv(m);throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_RESOURCE_NOT_EXIST})}))}deleteConversation(t,i){return __awaiter(this,void 0,void 0,(function*(){this.checkEnable(),this.checkV2(),validateConversationId(this.core.account,t),validate({clearMessage:{type:"boolean",required:!1}},{clearMessage:i},"",!0);try{yield this.core.sendCmd("v2ConversationDelete",{tag:{conversationId:t,clearMessage:Number(i||!1)}})}catch(i){this.logger.warn(`V2NIMConversationService:deleteConversation: delete conversation failed: ${t}`)}this.model.getById(t)&&(i&&this.core.eventBus.emit("V2NIMConversationService/deleteConversation",[t]),this.versionCache.compareAndDeleteModel([t]))}))}deleteConversationListByIds(t,i){return __awaiter(this,void 0,void 0,(function*(){this.checkEnable(),this.checkV2(),validate({conversationIds:{type:"array",itemType:"string",min:1}},{conversationIds:t},"",!0),validate({clearMessage:{type:"boolean",required:!1}},{clearMessage:i},"",!0);var o=formatFailedMap(get(yield this.core.sendCmd("v2ConversationsDelete",{tag:{conversationIds:JSON.stringify(t),clearMessage:Number(i||!1)}}),"content.info.failedMap")).filter((t=>t.error.code!==Ee.V2NIM_ERROR_CODE_CONVERSATION_NOT_EXIST||!this.model.getById(t.conversationId)));return o.length<t.length&&(i&&this.core.eventBus.emit("V2NIMConversationService/deleteConversation",t),this.versionCache.compareAndDeleteModel(t)),o}))}getStickTopConversationList(){return __awaiter(this,void 0,void 0,(function*(){return this.checkV2(),this.core.V2NIMLoginService.checkIllegalState(),this.model.getStickTopList()}))}stickTopConversation(t,i){return __awaiter(this,void 0,void 0,(function*(){this.checkEnable(),this.checkV2(),validateConversationId(this.core.account,t),validate({stickTop:{type:"boolean"}},{stickTop:i},"",!0);var o=get(yield this.core.sendCmd("v2ConversationSetTop",{tag:{conversationId:t,stickTop:Number(i)}}),"content.data"),m=formatConversationField(this.core,o);this.versionCache.compareAndUpdateModel([m])}))}updateConversation(t,i){return __awaiter(this,void 0,void 0,(function*(){this.checkEnable(),this.checkV2(),validateConversationId(this.core.account,t),validate({updateInfo:{type:"object",required:!0,rules:{serverExtension:{type:"string"}}}},{updateInfo:i},"",!0);var o=get(yield this.core.sendCmd("v2ConversationUpdate",{tag:Object.assign({conversationId:t},i)}),"content.data"),m=formatConversationField(this.core,o);this.versionCache.compareAndUpdateModel([m])}))}updateConversationLocalExtension(t,i){return __awaiter(this,void 0,void 0,(function*(){this.checkEnable(),this.checkV2(),validateConversationId(this.core.account,t),validate({localExtension:{type:"string"}},{localExtension:i},"",!0);var o=this.model.getById(t);if(!o)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_RESOURCE_NOT_EXIST});if(o.localExtension!==i){var m=Object.assign(Object.assign({},o),{localExtension:i});this.model.upsert(m),this.triggerConversationChanged([m])}}))}getTotalUnreadCount(){return this.checkEnable(),this.checkV2(),this.unread.getTotalUnreadCount()||0}getUnreadCountByIds(t){this.checkEnable(),this.checkV2(),validate({conversationIds:{type:"array",itemType:"string",min:1}},{conversationIds:t},"",!0);var i=this.unread.getUnreadCountByIds(t);return Promise.resolve(i)}getUnreadCountByFilter(t){this.checkEnable(),this.checkV2(),this.valiteFilter(t);var i=this.unread.getUnreadCountByFilter(t);return Promise.resolve(i)}clearTotalUnreadCount(){return __awaiter(this,void 0,void 0,(function*(){this.checkEnable(),this.checkV2();var t=get(yield this.core.sendCmd("v2ConversationClearTotalUnread"),"content.info");this.versionCache.compareAndClearUnreadInModel(t)}))}clearUnreadCountByIds(t){return __awaiter(this,void 0,void 0,(function*(){this.checkEnable(),this.checkV2(),validate({conversationIds:{type:"array",itemType:"string",min:1}},{conversationIds:t},"",!0);var i=yield this.core.sendCmd("v2ConversationsUnreadClear",{tag:{conversationIds:JSON.stringify(t)}}),o=formatConversationFields(this.core,get(i,"content.datas")),m=formatFailedMap(get(i,"content.info.failedMap"));return this.versionCache.compareAndUpdateModel(o),m}))}clearUnreadCountByGroupId(t){return __awaiter(this,void 0,void 0,(function*(){this.checkEnable(),this.checkV2(),validate({groupId:{type:"string"}},{groupId:t},"",!0),yield this.core.sendCmd("v2ConversationClearGroupUnread",{tag:{groupId:t}})}))}clearUnreadCountByTypes(t){return __awaiter(this,void 0,void 0,(function*(){this.checkEnable(),this.checkV2(),validate({types:yr},{types:t},"",!0);var i=get(yield this.core.sendCmd("v2ConversationClearTypeUnread",{tag:{conversationType:JSON.stringify(t)}}),"content.info");this.versionCache.compareAndClearUnreadInModel(i)}))}markConversationRead(t){return __awaiter(this,void 0,void 0,(function*(){this.checkEnable(),this.checkV2(),this.checkLogin(),validateConversationId(this.core.account,t);var i=this.model.getById(t);if(!i)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"Conversation not exist"}});var o=this.core.V2NIMConversationIdUtil.parseConversationTargetId(t),m=this.core.V2NIMConversationIdUtil.parseConversationType(t),h=this.model.getReadTime(t),u=this.compute.computeReadTimeForMark(i);return h>=u?(this.logger.log(`V2Conv::markConversationRead currentReadTime >= readTime ${t},${h},${u}`),h):(3===m?yield this.core.sendCmd("v2MarkSuperTeamReadTime",{timetag:u,to:o}):yield this.core.sendCmd("v2MarkConversationReadTime",{scene:1===m?0:2===m?1:2,timetag:u,to:o}),this.model.updateReadTime(t,u),u)}))}getConversationReadTime(t){return __awaiter(this,void 0,void 0,(function*(){return this.checkEnable(),this.checkV2(),validateConversationId(this.core.account,t),this.model.getReadTime(t)}))}subscribeUnreadCountByFilter(t){var i;this.checkEnable(),this.checkV2(),this.checkLogin(),this.valiteFilter(t),0===(null===(i=t.conversationTypes)||void 0===i?void 0:i.length)&&delete t.conversationTypes,this.unread.addFilter(t)}unsubscribeUnreadCountByFilter(t){var i;this.checkEnable(),this.checkV2(),this.checkLogin(),this.valiteFilter(t),0===(null===(i=t.conversationTypes)||void 0===i?void 0:i.length)&&delete t.conversationTypes,this.unread.deleteFilter(t)}valiteFilter(t){if(validate({filter:{type:"object",required:!0,rules:{conversationTypes:{type:"array",itemType:"number",required:!1},conversationGroupId:{type:"string",allowEmpty:!1,required:!1},ignoreMuted:{type:"boolean",required:!1}}}},{filter:t},"",!0),void 0===t.conversationTypes&&void 0===t.conversationGroupId&&!0!==t.ignoreMuted)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"Filter cannot be empty"}})}triggerConversationChanged(t){t=this.compute.computeConvs(t),(t=JSON.parse(JSON.stringify(t))).forEach((t=>{t.lastMessage||(t.lastMessage=void 0),delete t.lastMessageState})),this.emit("onConversationChanged",t)}triggerConversationCreated(t){t=this.compute.computeConv(t),delete(t=JSON.parse(JSON.stringify(t))).lastMessageState,this.emit("onConversationCreated",t)}}var Or={"28_9":"v2ConversationGroupCreate","28_10":"v2ConversationGroupDelete","28_11":"v2ConversationGroupUpdate","28_12":"v2ConversationGroupGet","28_13":"v2ConversationGroupsGet","28_14":"v2ConversationGroupListGet","28_15":"v2ConversationGroupAddTo","28_16":"v2ConversationGroupRemoveFrom","28_22":"v2ConversationGroupNotifySyncOnline"},Rr="V2NIMConversationGroupService",br={groupId:1,name:2,serverExtension:3,createTime:4,updateTime:5},Vr={v2ConversationGroupCreate:{sid:28,cid:9,service:Rr,params:[{type:"Property",name:"tag",reflectMapper:{conversationIds:1,name:2,serverExtension:3}}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(br)},{type:"PropertyArray",name:"conversations",reflectMapper:invertSerializeItem(Er)},{type:"Property",name:"info",reflectMapper:{1:"failedMap"}}]},v2ConversationGroupDelete:{sid:28,cid:10,service:Rr,params:[{type:"Property",name:"tag",reflectMapper:{groupId:1}}],response:[{type:"Property",name:"info",reflectMapper:{1:"type",2:"deleteVersion",3:"groupList"}}]},v2ConversationGroupUpdate:{sid:28,cid:11,service:Rr,params:[{type:"Property",name:"tag",reflectMapper:{groupId:1,name:2,serverExtension:3}}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(br)}]},v2ConversationGroupGet:{sid:28,cid:12,service:Rr,params:[{type:"Property",name:"tag",reflectMapper:{groupId:1}}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(br)}]},v2ConversationGroupsGet:{sid:28,cid:13,service:Rr,params:[{type:"Property",name:"tag",reflectMapper:{groupIds:1}}],response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(br)},{type:"Property",name:"info",reflectMapper:{1:"failedMap"}}]},v2ConversationGroupListGet:{sid:28,cid:14,service:Rr,response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(br)}]},v2ConversationGroupAddTo:{sid:28,cid:15,service:Rr,params:[{type:"Property",name:"tag",reflectMapper:{groupId:1,conversationIds:2}}],response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(Er)},{type:"Property",name:"info",reflectMapper:{1:"failedMap"}}]},v2ConversationGroupRemoveFrom:{sid:28,cid:16,service:Rr,params:[{type:"Property",name:"tag",reflectMapper:{groupId:1,conversationIds:2}}],response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(Er)},{type:"Property",name:"info",reflectMapper:{1:"failedMap"}}]},v2ConversationGroupNotifySyncOnline:{sid:28,cid:22,service:Rr,response:[{type:"Property",name:"info",reflectMapper:{1:"type",2:"deleteVersion",3:"conversationIds"}},{type:"Property",name:"data",reflectMapper:invertSerializeItem(br)}]}};class V2NIMConversationGroupServiceImpl extends V2Service{constructor(t,i={}){super("V2NIMConversationGroupService",t),this.config={},this.core._registerDep(V2NIMConversationServiceImpl,"V2NIMConversationService"),"v2"===this.core.options.apiVersion&&!0===this.core.options.enableV2CloudConversation&&(registerParser({cmdMap:Or,cmdConfig:Vr}),this.setOptions(i))}setOptions(t){this.config=Object.assign(this.config,t)}emit(t,...i){var o=`${this.name}::emit ${t.toString()}`;if("onConversationsAddedToGroup"===t){var m=i[0],h=i[1];this.logger.log(`${o}`,`groupId:${m}`,`conversations:${h.map((t=>t.conversationId)).join(",")}`)}else this.logger.log(`${o}`,...i);return super.emit(t,...i)}get ifEnabled(){return!0===this.core.options.enableV2CloudConversation}checkEnable(){if(!0!==this.core.options.enableV2CloudConversation)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_MISUSE,detail:{reason:"V2CloudConversation is not enabled"}})}createConversationGroup(t,i,o){return __awaiter(this,void 0,void 0,(function*(){this.checkEnable(),this.checkV2(),validate({name:{type:"string",allowEmpty:!1}},{name:t},"",!0),validate({serverExtension:{type:"string",required:!1}},{serverExtension:i},"",!0),validate({conversationIds:{type:"array",itemType:"string",required:!1}},{conversationIds:o},"",!0);var m=yield this.core.sendCmd("v2ConversationGroupCreate",{tag:{name:t,serverExtension:i||"",conversationIds:o&&JSON.stringify(o)}}),h=formatConversationGroup(get(m,"content.data")),u=formatConversationFields(this.core,get(m,"content.conversations")),v=formatFailedMap(get(m,"content.info.failedMap"));return this.emit("onConversationGroupCreated",h),u.length>0&&(this.core.V2NIMConversationService.versionCache.compareAndUpdateModel(u),this.emit("onConversationsAddedToGroup",h.groupId,u.map((t=>this.core.V2NIMConversationService.model.getById(t.conversationId))).filter((t=>!!t)))),{group:h,failedList:v}}))}deleteConversationGroup(t){return __awaiter(this,void 0,void 0,(function*(){this.checkEnable(),this.checkV2(),validate({groupId:{type:"string",allowEmpty:!1}},{groupId:t},"",!0);var i=formatConversationGroupNotify(get(yield this.core.sendCmd("v2ConversationGroupDelete",{tag:{groupId:t}}),"content.info"));this.core.V2NIMConversationService.versionCache.compareAndDeleteGroupInModel(i.deleteVersion,t),this.emit("onConversationGroupDeleted",t)}))}updateConversationGroup(t,i,o){return __awaiter(this,void 0,void 0,(function*(){if(this.checkEnable(),this.checkV2(),validate({groupId:{type:"string",allowEmpty:!1}},{groupId:t},"",!0),validate({name:{type:"string",required:!1}},{name:i},"",!0),validate({serverExtension:{type:"string",required:!1}},{serverExtension:o},"",!0),void 0===i&&void 0===o)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INVALID_PARAMETER});var m=formatConversationGroup(get(yield this.core.sendCmd("v2ConversationGroupUpdate",{tag:{groupId:t,name:i,serverExtension:o}}),"content.data"));this.emit("onConversationGroupChanged",m)}))}addConversationsToGroup(t,i){return __awaiter(this,void 0,void 0,(function*(){this.checkEnable(),this.checkV2(),validate({groupId:{type:"string",allowEmpty:!1}},{groupId:t},"",!0),validate({conversationIds:{type:"array",itemType:"string",min:1,allowEmpty:!1}},{conversationIds:i},"",!0);var o=yield this.core.sendCmd("v2ConversationGroupAddTo",{tag:{groupId:t,conversationIds:JSON.stringify(i)}}),m=get(o,"content.info.failedMap")||"",h=[];m&&(h=formatFailedMap(m));var u=formatConversationFields(this.core,get(o,"content.datas"));this.core.V2NIMConversationService.versionCache.compareAndUpdateModel(u);var v=u.map((t=>this.core.V2NIMConversationService.model.getById(t.conversationId))).filter((t=>!!t));return v.length>0&&this.emit("onConversationsAddedToGroup",t,v),h}))}removeConversationsFromGroup(t,i){return __awaiter(this,void 0,void 0,(function*(){this.checkEnable(),this.checkV2(),validate({groupId:{type:"string",allowEmpty:!1}},{groupId:t},"",!0),validate({conversationIds:{type:"array",itemType:"string",min:1,allowEmpty:!1}},{conversationIds:i},"",!0);var o=yield this.core.sendCmd("v2ConversationGroupRemoveFrom",{tag:{groupId:t,conversationIds:JSON.stringify(i)}}),m=get(o,"content.info.failedMap")||"",h=[];m&&(h=formatFailedMap(m));var u=formatConversationFields(this.core,get(o,"content.datas"));return this.core.V2NIMConversationService.versionCache.compareAndUpdateModel(u),this.emit("onConversationsRemovedFromGroup",t,u.map((t=>t.conversationId))),h}))}getConversationGroup(t){return __awaiter(this,void 0,void 0,(function*(){return this.checkEnable(),this.checkV2(),validate({groupId:{type:"string",allowEmpty:!1}},{groupId:t},"",!0),formatConversationGroup(get(yield this.core.sendCmd("v2ConversationGroupGet",{tag:{groupId:t}}),"content.data"))}))}getConversationGroupList(){return __awaiter(this,void 0,void 0,(function*(){return this.checkEnable(),this.checkV2(),formatConversationGroups(get(yield this.core.sendCmd("v2ConversationGroupListGet"),"content.datas"))}))}getConversationGroupListByIds(t){return __awaiter(this,void 0,void 0,(function*(){this.checkEnable(),this.checkV2(),validate({groupIds:{type:"array",itemType:"string",min:1}},{groupIds:t},"",!0);var i=formatConversationGroups(get(yield this.core.sendCmd("v2ConversationGroupsGet",{tag:{groupIds:t&&JSON.stringify(t)}}),"content.datas"));return t.map((t=>i.filter((i=>i.groupId===t))[0])).filter((t=>!!t))}))}v2ConversationGroupNotifySyncOnlineHandler(t){if(this.ifEnabled){var i=formatConversationGroupNotify(get(t,"content.info")),{type:o,deleteVersion:m,conversationIds:h}=i,u=formatConversationGroup(get(t,"content.data"));if(this.core.logger.log("v2ConversationGroupNotifySyncOnlineHandler",i,u),1===o)this.emit("onConversationGroupCreated",u),h&&h.length>0&&this.emit("onConversationsAddedToGroup",u.groupId,h.map((t=>this.core.V2NIMConversationService.model.getById(t))).filter((t=>!!t)));else if(2===o)this.emit("onConversationGroupDeleted",u.groupId),this.core.V2NIMConversationService.versionCache.compareAndDeleteGroupInModel(m,u.groupId);else if(3===o)this.emit("onConversationGroupChanged",u);else if(4===o){var v=h.map((t=>this.core.V2NIMConversationService.model.getById(t))).filter((t=>!!t));this.emit("onConversationsAddedToGroup",u.groupId,v)}else 5===o&&this.emit("onConversationsRemovedFromGroup",u.groupId,h)}}}class V2NIMMessageConverterImpl{constructor(t){this.name="V2NIMMessageConverter",this.core=t}messageSerialization(t){if(!t)return null;var i=serialize(t,Pi);return JSON.stringify(i)}messageDeserialization(t){var i,o,m,h,u,v,I,_,M,E,S,T,C,N,A,O,R,V,k,P,L,w,D;if(!t)return null;try{var U=deserialize(JSON.parse(t),Li);return U.sendingState=0,1!==U.conversationType||U.senderId!==this.core.account&&U.receiverId!==this.core.account?2===U.conversationType?U.conversationId=this.core.V2NIMConversationIdUtil.teamConversationId(U.receiverId):3===U.conversationType&&(U.conversationId=this.core.V2NIMConversationIdUtil.superTeamConversationId(U.receiverId)):U.conversationId=this.core.V2NIMConversationIdUtil.p2pConversationId(U.senderId===this.core.account?U.receiverId:U.senderId),U.threadReply&&(U.threadReply.conversationType=U.conversationType,U.threadReply=completeMessageRefer(this.core,U.threadReply)),U.threadRoot&&(U.threadRoot.conversationType=U.conversationType,U.threadRoot=completeMessageRefer(this.core,U.threadRoot)),[1,3,2,0].includes(U.conversationType)||this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid conversationType(enum): ${U.conversationType}`),U.senderId&&"string"!=typeof U.senderId&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid senderId(string): ${U.senderId}`),U.receiverId&&"string"!=typeof U.receiverId&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid receiverId(string): ${U.receiverId}`),"createTime"in U&&isNaN(U.createTime)&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid createTime(number): ${U.createTime}`),[2,7,12,100,6,1,-1,4,5,11,0,10,3].includes(U.messageType)||this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid messageType(enum): ${U.messageType}`),"subType"in U&&isNaN(U.subType)&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid subType(number): ${U.subType}`),U.messageClientId&&"string"!=typeof U.messageClientId&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid messageClientId(string): ${U.messageClientId}`),U.messageServerId&&"string"!=typeof U.messageServerId&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid messageServerId(string): ${U.messageServerId}`),U.attachment&&"object"!=typeof U.attachment&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid attachment(object): ${U.attachment}`),U.text&&"string"!=typeof U.text&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid text(string): ${U.text}`),U.serverExtension&&"string"!=typeof U.serverExtension&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid serverExtension(string): ${U.serverExtension}`),U.callbackExtension&&"string"!=typeof U.callbackExtension&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid callbackExtension(string): ${U.callbackExtension}`),(null===(i=U.pushConfig)||void 0===i?void 0:i.pushContent)&&"string"!=typeof U.pushConfig.pushContent&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid pushContent(string): ${U.pushConfig.pushContent}`),(null===(o=U.pushConfig)||void 0===o?void 0:o.pushPayload)&&"string"!=typeof U.pushConfig.pushPayload&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid pushPayload(string): ${U.pushConfig.pushPayload}`),(null===(m=U.pushConfig)||void 0===m?void 0:m.forcePushContent)&&"string"!=typeof U.pushConfig.forcePushContent&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid forcePushContent(string): ${U.pushConfig.forcePushContent}`),(null===(h=U.pushConfig)||void 0===h?void 0:h.forcePushAccountIds)&&!Array.isArray(U.pushConfig.forcePushAccountIds)&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid forcePushAccountIds(array): ${U.pushConfig.forcePushAccountIds}`),(null===(u=U.routeConfig)||void 0===u?void 0:u.routeEnvironment)&&"string"!=typeof U.routeConfig.routeEnvironment&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid routeEnvironment(string): ${U.routeConfig.routeEnvironment}`),(null===(v=U.antispamConfig)||void 0===v?void 0:v.antispamBusinessId)&&"string"!=typeof U.antispamConfig.antispamBusinessId&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid antispamBusinessId(string): ${U.antispamConfig.antispamBusinessId}`),(null===(I=U.antispamConfig)||void 0===I?void 0:I.antispamCustomMessage)&&"string"!=typeof U.antispamConfig.antispamCustomMessage&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid antispamCustomMessage(string): ${U.antispamConfig.antispamCustomMessage}`),(null===(_=U.antispamConfig)||void 0===_?void 0:_.antispamCheating)&&"string"!=typeof U.antispamConfig.antispamCheating&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid antispamCheating(string): ${U.antispamConfig.antispamCheating}`),(null===(M=U.antispamConfig)||void 0===M?void 0:M.antispamExtension)&&"string"!=typeof U.antispamConfig.antispamExtension&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid antispamExtension(string): ${U.antispamConfig.antispamExtension}`),(null===(E=U.robotConfig)||void 0===E?void 0:E.accountId)&&"string"!=typeof U.robotConfig.accountId&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid accountId(string): ${U.robotConfig.accountId}`),(null===(S=U.robotConfig)||void 0===S?void 0:S.topic)&&"string"!=typeof U.robotConfig.topic&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid topic(string): ${U.robotConfig.topic}`),(null===(T=U.robotConfig)||void 0===T?void 0:T.function)&&"string"!=typeof U.robotConfig.function&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid function(string): ${U.robotConfig.function}`),(null===(C=U.robotConfig)||void 0===C?void 0:C.customContent)&&"string"!=typeof U.robotConfig.customContent&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid customContent(string): ${U.robotConfig.customContent}`),(null===(N=U.threadRoot)||void 0===N?void 0:N.senderId)&&"string"!=typeof U.threadRoot.senderId&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid senderId(string): ${U.threadRoot.senderId}`),(null===(A=U.threadRoot)||void 0===A?void 0:A.receiverId)&&"string"!=typeof U.threadRoot.receiverId&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid receiverId(string): ${U.threadRoot.receiverId}`),(null===(O=U.threadRoot)||void 0===O?void 0:O.messageClientId)&&"string"!=typeof U.threadRoot.messageClientId&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid messageClientId(string): ${U.threadRoot.messageClientId}`),(null===(R=U.threadRoot)||void 0===R?void 0:R.messageServerId)&&"string"!=typeof U.threadRoot.messageServerId&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid messageServerId(string): ${U.threadRoot.messageServerId}`),U.threadRoot&&"createTime"in U.threadRoot&&isNaN(U.threadRoot.createTime)&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid createTime(number): ${U.threadRoot.createTime}`),U.threadRoot&&![1,3,2,0].includes(U.threadRoot.conversationType)&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid conversationType(enum): ${U.threadRoot.conversationType}`),(null===(V=U.threadRoot)||void 0===V?void 0:V.conversationId)&&"string"!=typeof U.threadRoot.conversationId&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid conversationId(string): ${U.threadRoot.conversationId}`),(null===(k=U.threadReply)||void 0===k?void 0:k.senderId)&&"string"!=typeof U.threadReply.senderId&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid senderId(string): ${U.threadReply.senderId}`),(null===(P=U.threadReply)||void 0===P?void 0:P.receiverId)&&"string"!=typeof U.threadReply.receiverId&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid receiverId(string): ${U.threadReply.receiverId}`),(null===(L=U.threadReply)||void 0===L?void 0:L.messageClientId)&&"string"!=typeof U.threadReply.messageClientId&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid messageClientId(string): ${U.threadReply.messageClientId}`),(null===(w=U.threadReply)||void 0===w?void 0:w.messageServerId)&&"string"!=typeof U.threadReply.messageServerId&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid messageServerId(string): ${U.threadReply.messageServerId}`),U.threadReply&&"createTime"in U.threadReply&&isNaN(U.threadReply.createTime)&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid createTime(number): ${U.threadReply.createTime}`),U.threadReply&&![1,3,2,0].includes(U.threadReply.conversationType)&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid conversationType(enum): ${U.threadReply.conversationType}`),(null===(D=U.threadReply)||void 0===D?void 0:D.conversationId)&&"string"!=typeof U.threadReply.conversationId&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid conversationId(string): ${U.threadReply.conversationId}`),delete U.__clientExt,delete U.userUpdateTime,U}catch(i){return this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid message string: ${t}`),null}}}var kr="V2NIMMessageLogUtil",Pr={"30_6":"v2GetMessageList","33_2":"v2GetMessageListByRefers","30_9":"v2ClearRoamingMessage","30_18":"v2ClearHistoryMessage","7_118":"onClearHistoryMessage","4_24":"syncClearHistoryMessage","31_23":"v2GetTeamMessageList","32_14":"v2GetSuperTeamMessageList"},Lr={conversationType:{id:0,retType:"number"},receiverId:1,deleteRoam:{id:2,converter:boolToInt},teamId:3,onlineSync:{id:4,converter:boolToInt},deleteTime:{id:6,retType:"number"},serverExtension:7},wr=[{type:"Long",name:"beginTime"},{type:"Long",name:"endTime"},{type:"Long",name:"lastMsgId"},{type:"Int",name:"limit"},{type:"Bool",name:"direction"},{type:"LongArray",name:"msgTypes"}],Dr={v2GetMessageList:{sid:30,cid:6,service:kr,params:[{type:"String",name:"to"},...wr],response:[{type:"PropertyArray",name:"msgs",reflectMapper:invertSerializeItem(Pi)}]},v2GetMessageListByRefers:{sid:33,cid:2,service:kr,params:[{type:"PropertyArray",name:"tag",reflectMapper:Pi,select:["conversationType","senderId","receiverId","createTime","messageServerId"]}],response:[{type:"PropertyArray",name:"msgs",reflectMapper:invertSerializeItem(Pi)}]},v2ClearRoamingMessage:{sid:30,cid:9,service:kr,params:[{type:"StrArray",name:"conversationIds"}]},v2ClearHistoryMessage:{sid:30,cid:18,service:kr,params:[{type:"Property",name:"tag",reflectMapper:Lr}],response:[{type:"Long",name:"timetag"}]},v2GetTeamMessageList:{sid:31,cid:23,service:kr,params:[{type:"Long",name:"to"},...wr],response:[{type:"PropertyArray",name:"msgs",reflectMapper:invertSerializeItem(Pi)}]},v2GetSuperTeamMessageList:{sid:32,cid:14,service:kr,params:[{type:"Long",name:"to"},...wr],response:[{type:"PropertyArray",name:"msgs",reflectMapper:invertSerializeItem(Pi)}]},onClearHistoryMessage:{sid:7,cid:118,service:kr,response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Lr)}]},syncClearHistoryMessage:{sid:4,cid:24,service:kr,response:[{type:"PropertyArray",name:"data",reflectMapper:invertSerializeItem(Lr)}]}};class V2NIMMessageLogUtil extends V2Service{constructor(t){super("V2NIMMessageLogUtil",t),this.clearHistoryMessageFn=t=>{var i=formatClearHistoryNotification(this.core,t);this.emitClearHistoryMessage([i])},this.core=t,this.service=this.core.V2NIMMessageService,"v2"===this.core.options.apiVersion&&(registerParser({cmdMap:Pr,cmdConfig:Dr}),this.setListener())}setListener(){this.core.eventBus.on("forwardReceive/V2NIMMessageLogService/clearHistoryMessage",this.clearHistoryMessageFn)}getMessageListByRefers(t){return __awaiter(this,void 0,void 0,(function*(){if(this.checkV2(),validate(Ht,{messageRefers:t},"",!0),0===t.length)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"getMessageListByRefers: messageRefers cannot be an empty array"}});var i=[],o=t.map((t=>{var o=this.service.model.getMessageById(t.messageClientId);return!o&&t.messageServerId&&"0"!==t.messageServerId&&i.push(t),o})),m=[];if(i.length>0){var h=yield this.core.sendCmd("v2GetMessageListByRefers",{tag:i});m=h.content.msgs}return o=o.map(((i,o)=>{if(i)return i;var h=t[o],u=m.find((t=>t.messageServerId===h.messageServerId));return u?completeMessage(this.core,u):void 0})).filter((t=>void 0!==t&&!this.service._filterMessage(t))),o=this._fillAIStreamMessages(o)}))}getMessageList(t){var i;return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(Gt,t,"",!0),validateConversationId(this.core.account,t.conversationId);var o=this.core.V2NIMConversationIdUtil.parseConversationType(t.conversationId),m=this.core.V2NIMConversationIdUtil.parseConversationTargetId(t.conversationId),h=1===o?"v2GetMessageList":2===o?"v2GetTeamMessageList":"v2GetSuperTeamMessageList",u=t.beginTime||0,v=t.endTime||0;if(0!==u&&0!==v&&u>v)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"getMessageList: beginTime cannot be greater than endTime"}});var I=void 0===t.direction?0:t.direction;if(t.anchorMessage)if(0===I){if(0===v)v=t.anchorMessage.createTime;else if(v!==t.anchorMessage.createTime)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"getMessageList: When providing anchorMessage, when sorting in descending order, endTime does not need to be provided, or endTime should be equal to anchorMessage.createTime"}})}else if(0===u)u=t.anchorMessage.createTime;else if(u!==t.anchorMessage.createTime)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"getMessageList: When providing anchorMessage, when sorting in ascending order, there is no need to provide beginTime, or beginTime should be equal to anchorMessage.createTime"}});var _=null===(i=t.anchorMessage)||void 0===i?void 0:i.messageServerId,M=yield this.core.sendCmd(h,{beginTime:u,endTime:v,lastMsgId:_||0,limit:t.limit||50,direction:I,msgTypes:t.messageTypes?t.messageTypes.slice():[],to:m}),{content:E}=M,S=E.msgs.map((t=>completeMessage(this.core,t)));_&&(S=S.filter((t=>t.messageServerId!==_)));var T=this.getMessageListMonkeyPatch(S,t);return T=this._fillAIStreamMessages(T)}))}getMessageListMonkeyPatch(t,i){var o=i.conversationId,m=t,h=m.reduce(((t,i)=>(t[i.messageClientId]=!0,t)),{}),u=this.service.model.getMessagesByConversationId(o);u=u.sort(((t,o)=>1===i.direction?t.createTime-o.createTime:o.createTime-t.createTime));var v=0,I=i.beginTime||0,_=i.endTime||0;i.anchorMessage&&(0===i.direction?_=i.anchorMessage.createTime:I=i.anchorMessage.createTime,v=u.findIndex((t=>{var o;return t.messageClientId===(null===(o=i.anchorMessage)||void 0===o?void 0:o.messageClientId)})),v+=1);for(var M=v;M<u.length;M++){var E=u[M],S=!h[E.messageClientId],T=void 0===E.sendingState||1===E.sendingState,C=E.conversationId===o,N=E.createTime>I&&(E.createTime<_||0===_),A=!i.messageTypes||i.messageTypes.includes(E.messageType);S&&T&&C&&N&&A&&m.push(u[M])}return(m=m.sort(((t,o)=>1===i.direction?t.createTime-o.createTime:o.createTime-t.createTime))).slice(0,i.limit||50)}clearHistoryMessage(t){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(Jt,t,"",!0),validateConversationId(this.core.account,t.conversationId);var{conversationId:i,deleteRoam:o,onlineSync:m,serverExtension:h}=t,u=this.core.V2NIMConversationIdUtil.parseConversationType(i),v=this.core.V2NIMConversationIdUtil.parseConversationTargetId(i),I={deleteRoam:o,onlineSync:m,serverExtension:h,conversationType:u};1===u?I.receiverId=v:I.teamId=v;var _=this.core.timeOrigin.getNTPTime();(t.clearMode=t.clearMode||0,0===t.clearMode)&&(_=(yield this.core.sendCmd("v2ClearHistoryMessage",{tag:I})).content.timetag);2===t.clearMode&&Re.localStorage.setItem(`nim_${this.core.account}_${i}_clearTime`,_.toString()),this.core.eventBus.emit("forwardSend/V2NIMMessageLogService/clearHistoryMessage",Object.assign(Object.assign({},I),{deleteTime:_})),this.emitClearHistoryMessage([{deleteTime:_,serverExtension:h,conversationId:i}])}))}clearRoamingMessage(t){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate({conversationIds:{type:"array",itemType:"string",min:1}},{conversationIds:t},void 0,!0);var i=[];try{i=t.map((t=>{var i=this.core.V2NIMConversationIdUtil.parseConversationTargetId(t);return getSessionIdFromConvInfo(this.core.V2NIMConversationIdUtil.parseConversationType(t),i)}))}catch(i){throw this.logger.error(`V2NIMMessage::clearRoamingMessage with ${t}`,i),new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_PARAMETER_ERROR,detail:{reason:"Failed to create session",rawData:`${t}`}})}yield this.core.sendCmd("v2ClearRoamingMessage",{conversationIds:i})}))}syncClearHistoryMessageHandler(t){var i=t.content.data.map((t=>formatClearHistoryNotification(this.core,t)));this.emitClearHistoryMessage(i)}onClearHistoryMessageHandler(t){var i=formatClearHistoryNotification(this.core,t.content.data);this.emitClearHistoryMessage([i])}emitClearHistoryMessage(t){t.forEach((t=>{this.service.model.deleteMessages(t.conversationId,t.deleteTime),this.core.eventBus.emit("V2NIMSync/updateTimetag",{sessionHistoryMsgsDelete:t.deleteTime})})),this.core.eventBus.emit("V2NIMMessageLogUtil/onClearHistoryNotifications",t),this.service.emit("onClearHistoryNotifications",t)}_fillAIStreamMessages(t){var i;return(null===(i=this.core)||void 0===i?void 0:i.V2NIMMessageService.aiUtil.hasAI())?t.map((t=>{var i,o,m;if(-1===(null===(i=null==t?void 0:t.streamConfig)||void 0===i?void 0:i.status)||1===(null===(o=null==t?void 0:t.streamConfig)||void 0===o?void 0:o.status)){var h=this.core.V2NIMAIService.model.getAiStream(t.messageClientId);t.text=(null===(m=null==h?void 0:h.chunks)||void 0===m?void 0:m.join(""))||t.text||"",(null==h?void 0:h.aiRAGs)&&(t.streamConfig.rags=h.aiRAGs),t.streamConfig.status=-1}return t})):t}}var Ur="V2NIMMessageExtendUtil",xr={"29_5":"v2VoiceToText","33_15":"v2PinMessage","33_16":"v2UpdatePinMessage","33_17":"v2UnpinMessage","23_18":"onPinMessage","23_19":"onUpdatePinMessage","23_20":"onUnpinMessage","23_115":"onPinMessage","23_116":"onUpdatePinMessage","23_117":"onUnpinMessage","33_21":"v2GetPinMessageList","33_3":"v2AddQuickComment","33_4":"v2RemoveQuickComment","33_7":"v2GetQuickComment","23_5":"onAddQuickComment","23_6":"onRemoveQuickComment","23_103":"onAddQuickComment","23_104":"onRemoveQuickComment","33_8":"v2AddCollection","33_9":"v2RemoveCollections","33_10":"v2UpdateCollectionExtension","33_11":"v2GetCollectionListByOption","30_26":"v2SearchCloudMessagesGroupByConversation","30_27":"v2SearchCloudMessages","30_34":"v2SearchCloudMessagesEx","33_1":"v2GetThreadMessageList"},Fr={conversationType:{id:1,converter:conversationTypeV2ToV1,retConverter:conversationTypeV1ToV2,access:"messageRefer.conversationType"},senderId:{id:2,access:"messageRefer.senderId"},receiverId:{id:3,access:"messageRefer.receiverId"},createTime:{id:4,retType:"number",access:"messageRefer.createTime"},messageServerId:{id:5,access:"messageRefer.messageServerId"},messageClientId:{id:6,access:"messageRefer.messageClientId"},detail:7,modify:{id:8,retType:"number"}},Br={conversationType:{id:1,access:"messageRefer.conversationType",retConverter:conversationTypeV1ToV2},senderId:{id:2,access:"messageRefer.senderId"},receiverId:{id:3,access:"messageRefer.receiverId"},time:{id:4,access:"messageRefer.createTime",converter:boolToInt,retType:"number"},messageServerId:{id:5,access:"messageRefer.messageServerId"},messageClientId:{id:6,access:"messageRefer.messageClientId"},operatorId:7,serverExtension:8,createTime:{id:9,converter:boolToInt,retType:"number"},updateTime:{id:10,converter:boolToInt,retType:"number"}},$r={operatorId:1,index:{id:2,retType:"number"},createTime:{id:3,retType:"number"},serverExtension:4,pushEnabled:{id:5,access:"pushConfig.pushEnabled",converter:boolToInt},needBadge:{id:6,access:"pushConfig.needBadge",converter:boolToInt},title:{id:7,access:"pushConfig.title"},pushContent:{id:8,access:"pushConfig.pushContent"},pushPayload:{id:9,access:"pushConfig.pushPayload"}},jr={accid:1,serverExtension:2,createTime:{id:3,retType:"number"},updateTime:{id:4,retType:"number"}},Gr={collectionId:1,collectionType:{id:2,retType:"number"},collectionData:3,serverExtension:4,uniqueId:5,createTime:{id:6,retType:"number"},updateTime:{id:7,retType:"number"}},qr={keyword:1,beginTime:2,endTime:3,messageLimit:5,sortOrder:{id:6,converter:t=>0===t?2:1},p2pAccountIds:{id:7,converter:t=>t.join(",")},teamIds:{id:8,converter:t=>t.join(",")},senderAccountIds:{id:9,converter:t=>t.join(",")},messageTypes:{id:10,converter:t=>t.join(",")},messageSubtypes:{id:11,converter:t=>t.join(",")}},Hr={keywordList:{id:1,converter:t=>objectToJSONString(t)},keywordMatchType:2,searchStartTime:3,searchTimePeriod:4,pageToken:5,limit:7,direction:8,conversationId:9,senderAccountIds:{id:12,converter:t=>t.join(",")},messageTypes:{id:13,converter:t=>t.join(",")},messageSubtypes:{id:14,converter:t=>t.join(",")}},zr=Object.assign(Object.assign({},qr),{conversationLimit:4}),Yr={v2PinMessage:{sid:33,cid:15,service:Ur,params:[{type:"Property",name:"msg",reflectMapper:Pi,select:["conversationType","receiverId","senderId","createTime","messageClientId","messageServerId"]},{type:"Property",name:"msgPin",reflectMapper:jr}],response:[{type:"Long",name:"timetag"}]},v2UnpinMessage:{sid:33,cid:17,service:Ur,params:[{type:"Property",name:"msg",reflectMapper:Pi,select:["conversationType","receiverId","senderId","createTime","messageClientId","messageServerId"]},{type:"Property",name:"msgPin",reflectMapper:jr}],response:[{type:"Long",name:"timetag"}]},v2UpdatePinMessage:{sid:33,cid:16,service:Ur,params:[{type:"Property",name:"msg",reflectMapper:Pi,select:["conversationType","receiverId","senderId","createTime","messageClientId","messageServerId"]},{type:"Property",name:"msgPin",reflectMapper:jr}],response:[{type:"Long",name:"timetag"}]},v2GetPinMessageList:{sid:33,cid:21,service:Ur,params:[{type:"Property",name:"tag",reflectMapper:{conversationId:1,timetag:2}}],response:[{type:"Long",name:"timetag"},{type:"Bool",name:"changed"},{type:"PropertyArray",name:"data",reflectMapper:invertSerializeItem(Br)}]},v2VoiceToText:{sid:29,cid:5,service:Ur,params:[{type:"Property",name:"tag",reflectMapper:{mimeType:0,sampleRate:1,voiceUrl:2,duration:3}}],response:[{type:"String",name:"data"}]},v2AddQuickComment:{sid:33,cid:3,service:Ur,params:[{type:"Property",name:"message",reflectMapper:Pi,select:["conversationType","senderId","receiverId","createTime","messageClientId","messageServerId"]},{type:"Property",name:"quickComment",reflectMapper:$r}],response:[{type:"Long",name:"timetag"}]},v2RemoveQuickComment:{sid:33,cid:4,service:Ur,params:[{type:"Property",name:"message",reflectMapper:Pi,select:["conversationType","senderId","receiverId","createTime","messageClientId","messageServerId"]},{type:"Property",name:"quickComment",reflectMapper:$r}],response:[{type:"Long",name:"timetag"}]},onAddQuickComment:{sid:23,cid:5,service:Ur,response:[{type:"Property",name:"message",reflectMapper:invertSerializeItem(Pi)},{type:"Property",name:"quickComment",reflectMapper:invertSerializeItem($r)}]},onRemoveQuickComment:{sid:23,cid:6,service:Ur,response:[{type:"Property",name:"message",reflectMapper:invertSerializeItem(Pi)},{type:"Property",name:"quickComment",reflectMapper:invertSerializeItem($r)}]},v2GetQuickComment:{sid:33,cid:7,service:Ur,params:[{type:"PropertyArray",name:"tag",reflectMapper:Fr}],response:[{type:"PropertyArray",name:"data",reflectMapper:invertSerializeItem(Fr)}]},onPinMessage:{sid:23,cid:18,service:Ur,response:[{type:"Property",name:"msg",reflectMapper:invertSerializeItem(Pi)},{type:"Property",name:"pinInfo",reflectMapper:invertSerializeItem(jr)}]},onUpdatePinMessage:{sid:23,cid:19,service:Ur,response:[{type:"Property",name:"msg",reflectMapper:invertSerializeItem(Pi)},{type:"Property",name:"pinInfo",reflectMapper:invertSerializeItem(jr)}]},onUnpinMessage:{sid:23,cid:20,service:Ur,response:[{type:"Property",name:"msg",reflectMapper:invertSerializeItem(Pi)},{type:"Property",name:"pinInfo",reflectMapper:invertSerializeItem(jr)}]},v2AddCollection:{sid:33,cid:8,service:Ur,params:[{type:"Property",name:"tag",reflectMapper:Gr}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Gr)}]},v2RemoveCollections:{sid:33,cid:9,service:Ur,params:[{type:"PropertyArray",name:"tag",reflectMapper:Gr,select:["collectionId","createTime"]}],response:[{type:"Int",name:"data"}]},v2UpdateCollectionExtension:{sid:33,cid:10,service:Ur,params:[{type:"Property",name:"tag",reflectMapper:Gr}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Gr)}]},v2GetCollectionListByOption:{sid:33,cid:11,service:Ur,params:[{type:"Property",name:"tag",reflectMapper:{beginTime:1,endTime:2,excludeId:3,limit:4,direction:5,collectionType:6}}],response:[{type:"Long",name:"total"},{type:"PropertyArray",name:"data",reflectMapper:invertSerializeItem(Gr)}]},v2SearchCloudMessagesGroupByConversation:{sid:30,cid:26,service:Ur,params:[{type:"Property",name:"tag",reflectMapper:zr}],response:[{type:"PropertyArray",name:"data",reflectMapper:invertSerializeItem(Pi)}]},v2SearchCloudMessages:{sid:30,cid:27,service:Ur,params:[{type:"Property",name:"tag",reflectMapper:qr}],response:[{type:"PropertyArray",name:"data",reflectMapper:invertSerializeItem(Pi)}]},v2SearchCloudMessagesEx:{sid:30,cid:34,service:Ur,params:[{type:"Property",name:"tag",reflectMapper:Hr}],response:[{type:"PropertyArray",name:"msgs",reflectMapper:invertSerializeItem(Pi)},{type:"Int",name:"hasMore"},{type:"String",name:"nextPageToken"}]},v2GetThreadMessageList:{sid:33,cid:1,service:Ur,params:[{type:"Property",name:"messageRefer",reflectMapper:Pi},{type:"Property",name:"tag",reflectMapper:{beginTime:1,endTime:2,excludeMessageServerId:3,limit:4,reverse:5}}],response:[{type:"Property",name:"message",reflectMapper:invertSerializeItem(Pi)},{type:"Property",name:"replyResult",reflectMapper:invertSerializeItem({total:{id:1,retType:"number"},timestamp:{id:2,retType:"number"}})},{type:"PropertyArray",name:"replyList",reflectMapper:invertSerializeItem(Pi)}]}};class V2NIMMessageExtendUtil extends V2Service{constructor(t){super("V2NIMMessageExtendUtil",t),this.core=t,this.service=this.core.V2NIMMessageService,"v2"===this.core.options.apiVersion&®isterParser({cmdMap:xr,cmdConfig:Yr})}pinMessage(t,i){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(qt,t,"message",!0),validate(Kt,{serverExtension:i},"",!0);var o=yield this.core.sendCmd("v2PinMessage",{msg:t,msgPin:{serverExtension:i}});this.emitPinNotification({pinState:1,message:t,serverExtension:i,createTime:o.content.timetag,updateTime:o.content.timetag,operatorId:this.core.account})}))}unpinMessage(t,i){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(qt,t,"messageRefer",!0),validate(Kt,{serverExtension:i},"",!0);var o=yield this.core.sendCmd("v2UnpinMessage",{msg:t,msgPin:{serverExtension:i}});this.emitPinNotification({pinState:0,message:t,serverExtension:i,updateTime:o.content.timetag,operatorId:this.core.account})}))}updatePinMessage(t,i){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(qt,t,"message",!0),validate(Kt,{serverExtension:i},"",!0);var o=yield this.core.sendCmd("v2UpdatePinMessage",{msg:t,msgPin:{serverExtension:i}});this.emitPinNotification({pinState:2,message:t,serverExtension:i,updateTime:o.content.timetag,operatorId:this.core.account})}))}getPinnedMessageList(t){return __awaiter(this,void 0,void 0,(function*(){if(this.checkV2(),!this.core.V2NIMConversationIdUtil||!this.core.V2NIMConversationIdUtil.parseConversationType)throw new Error('Service "V2NIMConversationService" does not exist');validateConversationId(this.core.account,t);var i=this.core.V2NIMConversationIdUtil.convertToV1ConversationId(t);return i=i.replace("superTeam","super_team"),(yield this.core.sendCmd("v2GetPinMessageList",{tag:{conversationId:i,timetag:0}})).content.data.map((t=>Object.assign(Object.assign({},t),{messageRefer:Object.assign(Object.assign({},t.messageRefer),{conversationId:this.core.V2NIMConversationIdUtil.messageConversationId(t.messageRefer)})}))).sort(((t,i)=>i.updateTime-t.updateTime))}))}addQuickComment(t,i,o,m){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(Zt,{message:t,index:i,serverExtension:o,pushConfig:m},"",!0);var h=yield this.core.sendCmd("v2AddQuickComment",{message:t,quickComment:{index:i,serverExtension:o,pushConfig:m}}),u={operationType:1,quickComment:{messageRefer:formatMessageRefer(this.core,t),createTime:h.content.timetag,index:i,serverExtension:o||"",operatorId:this.core.account}};this.core.V2NIMMessageService.emit("onMessageQuickCommentNotification",u)}))}removeQuickComment(t,i,o){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(qt,t,"messageRefer",!0),validate({index:{type:"number",min:1}},{index:i},"",!0),validate({serverExtension:{type:"string",required:!1}},{serverExtension:o},"",!0);var m=yield this.core.sendCmd("v2RemoveQuickComment",{message:t,quickComment:{index:i,serverExtension:o}}),h={operationType:2,quickComment:{messageRefer:formatMessageRefer(this.core,t),createTime:m.content.timetag,index:i,serverExtension:o||"",operatorId:this.core.account}};this.core.V2NIMMessageService.emit("onMessageQuickCommentNotification",h)}))}getQuickCommentList(t){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(ei,{messages:t},"",!0);var i={};return(yield this.core.sendCmd("v2GetQuickComment",{tag:t.map((t=>({messageRefer:t})))})).content.data.forEach((t=>{var o,m;try{if(!t.detail)return void(i[o=t.messageRefer.messageClientId]||(i[o]=[]));var h=JSON.parse(t.detail);i[m=t.messageRefer.messageClientId]||(i[m]=[]),h.forEach((o=>{i[t.messageRefer.messageClientId].push({messageRefer:Object.assign(Object.assign({},t.messageRefer),{conversationId:this.core.V2NIMConversationIdUtil.messageConversationId(t.messageRefer)}),operatorId:o[1],index:parseInt(o[2]),createTime:parseInt(o[3]),serverExtension:o[4]})}))}catch(i){this.logger.error("getQuickCommentList JSON Parse Error",t.detail,i)}})),i}))}voiceToText(t){return __awaiter(this,void 0,void 0,(function*(){if(this.checkV2(),validate(Qt,t,"",!0),!t.voicePath&&!t.voiceUrl&&!t.file)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"voiceToText: voicePath、voiceUrl、file cannot be empty at the same time"}});var{voicePath:i,file:o,mimeType:m,sampleRate:h,duration:u,sceneName:v}=t,I=v?this.core.V2NIMStorageService.getStorageScene(v):null,_=t.voiceUrl;if(!_){var M={};o?M.file=o:0===(null==i?void 0:i.indexOf("nim-external"))?M.fileInput=i:M.filePath=i,_=(yield this.core.cloudStorage.uploadFile(Object.assign({type:"audio",nosScenes:I?I.sceneName:void 0,nosSurvivalTime:I?I.expireTime:void 0},M))).url}return(yield this.core.sendCmd("v2VoiceToText",{tag:{voiceUrl:_,mimeType:m,sampleRate:h,duration:u}},{timeout:3e4})).content.data}))}onPinMessageHandler(t){return this.pinMessageChangeHandler(t,1)}onUnpinMessageHandler(t){return this.pinMessageChangeHandler(t,0)}onUpdatePinMessageHandler(t){return this.pinMessageChangeHandler(t,2)}pinMessageChangeHandler(t,i){var o=t.content.msg,m=t.content.pinInfo;o.conversationId=this.core.V2NIMConversationIdUtil.messageConversationId(o),this.emitPinNotification({pinState:i,message:o,serverExtension:m.serverExtension,createTime:m.createTime,updateTime:m.updateTime,operatorId:m.accid})}emitPinNotification(t){var i={pinState:t.pinState,pin:Object.assign(Object.assign({serverExtension:t.serverExtension||"",operatorId:t.operatorId},t.createTime?{createTime:t.createTime}:{}),{updateTime:t.updateTime,messageRefer:formatMessageRefer(this.core,t.message)})};this.core.V2NIMMessageService.emit("onMessagePinNotification",i)}onAddQuickCommentHandler(t){return this.onQuickCommentNotificationHandler(t,1)}onRemoveQuickCommentHandler(t){return this.onQuickCommentNotificationHandler(t,2)}onQuickCommentNotificationHandler(t,i){var o={operationType:i,quickComment:Object.assign({messageRefer:Object.assign(Object.assign({},t.content.message),{conversationId:this.core.V2NIMConversationIdUtil.messageConversationId(t.content.message)})},t.content.quickComment)};this.core.V2NIMMessageService.emit("onMessageQuickCommentNotification",o)}addCollection(t){return __awaiter(this,void 0,void 0,(function*(){return this.checkV2(),validate(ti,{params:t},"",!0),(yield this.core.sendCmd("v2AddCollection",{tag:t})).content.data}))}removeCollections(t){return __awaiter(this,void 0,void 0,(function*(){return this.checkV2(),validate(ii,{collections:t},"",!0),(yield this.core.sendCmd("v2RemoveCollections",{tag:t})).content.data}))}updateCollectionExtension(t,i){return __awaiter(this,void 0,void 0,(function*(){return this.checkV2(),validate(ri,{collection:t,serverExtension:i},"",!0),(yield this.core.sendCmd("v2UpdateCollectionExtension",{tag:Object.assign(Object.assign({},t),{serverExtension:i})})).content.data}))}getCollectionListByOption(t){return __awaiter(this,void 0,void 0,(function*(){return this.checkV2(),validate(ni,t,"",!0),(yield this.getCollectionListExByOption(t)).collectionList}))}getCollectionListExByOption(t){var i,o;return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(ni,t,"",!0);var m=t.beginTime||0,h=t.endTime||0,u=void 0===t.direction?0:t.direction;if(void 0!==(null===(i=t.anchorCollection)||void 0===i?void 0:i.collectionId))if(0===t.direction){if(0===h)h=t.anchorCollection.createTime;else if(h!==t.anchorCollection.createTime)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"getCollectionListExByOption: When providing anchorCollection, when sorting in descending order, endTime does not need to be provided, or endTime should be equal to anchorCollection.createTime"}})}else if(0===m)m=t.anchorCollection.createTime;else if(m!==t.anchorCollection.createTime)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"getCollectionListExByOption: When providing anchorCollection, when sorting in ascending order, there is no need to provide beginTime, or beginTime should be equal to anchorCollection.createTime"}});if(0!==m&&0!==h&&m>=h)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"getCollectionListExByOption: beginTime cannot be greater than endTime"}});var v={beginTime:m,endTime:h,direction:u,limit:t.limit,collectionType:t.collectionType,excludeId:(null===(o=t.anchorCollection)||void 0===o?void 0:o.collectionId)?t.anchorCollection.collectionId:0};v.collectionType||delete v.collectionType;var I=yield this.core.sendCmd("v2GetCollectionListByOption",{tag:v});return{totalCount:I.content.total,collectionList:I.content.data}}))}searchCloudMessages(t){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(oi,t,"",!0);var i=t.beginTime||0,o=t.endTime||0;if(0!==i&&0!==o&&i>o)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"searchCloudMessages: beginTime cannot be greater than endTime"}});var m=void 0===t.sortOrder?0:t.sortOrder,h=t.conversationLimit||0,u=t.messageLimit||10,v=h>0?"v2SearchCloudMessagesGroupByConversation":"v2SearchCloudMessages",I=yield this.core.sendCmd(v,{tag:Object.assign(Object.assign({},t),{beginTime:i,endTime:o,sortOrder:m,conversationLimit:h,messageLimit:u})});return this.service._filterMessagesByFn(I.content.data.map((t=>completeMessage(this.core,t))))}))}searchCloudMessagesEx(t){var i,o,m;return __awaiter(this,void 0,void 0,(function*(){if(this.checkV2(),validate(si,t,"",!0),t.conversationId&&validateConversationId(this.core.account,t.conversationId),!(null===(i=t.keywordList)||void 0===i?void 0:i.length)&&!(null===(o=t.senderAccountIds)||void 0===o?void 0:o.length)&&!(null===(m=t.messageTypes)||void 0===m?void 0:m.length))throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"searchCloudMessagesEx: keywordList senderAccountIds messageTypes cannot be empty at the same time"}});0===t.searchTimePeriod&&delete t.searchTimePeriod;var h=yield this.core.sendCmd("v2SearchCloudMessagesEx",{tag:Object.assign({},t)}),{msgs:u,hasMore:v,nextPageToken:I}=h.content,_=this.service._filterMessagesByFn(u.map((t=>completeMessage(this.core,t)))).sort(((t,i)=>i.createTime-t.createTime));return{count:u.length,items:formatSearchCloudMessageListEx(this.core,_),hasMore:intToBool(v),nextPageToken:I}}))}getThreadMessageList(t){return __awaiter(this,void 0,void 0,(function*(){if(validate(hi,t,"getThreadMessageList",!0),t.beginTime=t.beginTime||0,t.endTime&&t.beginTime>t.endTime)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"getThreadMessageList: beginTime cannot be greater than endTime"}});var i=yield this.core.sendCmd("v2GetThreadMessageList",{messageRefer:t.messageRefer,tag:{beginTime:t.beginTime,endTime:t.endTime,limit:t.limit,reverse:1===t.direction?1:0,excludeMessageServerId:t.excludeMessageServerId}}),{message:o,replyResult:m,replyList:h}=i.content,u=completeMessage(this.core,o),v=h.map((t=>completeMessage(this.core,t)));return v=this.service._filterMessagesByFn(v),v=this.service._filterMessageByClearTime(u.conversationId,v),{message:u,timestamp:m.timestamp,replyCount:m.total,replyList:v}}))}}class V2NIMNotificationServiceImpl extends V2Service{constructor(t,i){super("V2NIMNotificationService",t),this.config={compatibleWithV1:!0},this.notificationUtil=new NotificationUtil(this.core),this.core._registerDep(V2NIMConversationIdUtilImpl,"V2NIMConversationIdUtil"),"v2"===this.core.options.apiVersion&&(registerParser({cmdMap:$i,cmdConfig:qi}),this.setOptions(i))}setOptions(t){var i;(null===(i=this.core.systemMessage)||void 0===i?void 0:i.name)?this.config.compatibleWithV1=!0:this.config.compatibleWithV1=!1,this.config=Object.assign(this.config,t)}emit(t,...i){var o=`${this.name}::emit ${t.toString()}`;if("onReceiveCustomNotifications"===t){var m=i[0];this.logger.log(`${o}`,m.map((t=>`sender:${t.senderId};receiver:${t.receiverId};ctype:${t.conversationType};time:${t.timestamp}`)))}else if("onReceiveBroadcastNotifications"===t){var h=i[0];this.logger.log(`${o}`,h.map((t=>`id:${t.id};sender:${t.senderId};time:${t.timestamp}`)))}else this.logger.log(`${o}`,...i);return super.emit(t,...i)}sendCustomNotification(t,i,o){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validateConversationId(this.core.account,t),validate(Yi,{content:i,params:o},"",!0);var m=3===this.core.V2NIMConversationIdUtil.parseConversationType(t)?"v2SendCustomNotificationWithSuperTeam":"v2SendCustomNotification",h=this.notificationUtil.generateNotificationTag(t,i,o);yield this.core.sendCmd(m,{tag:h})}))}processSystemNotification(t){var i=t.type;if([0,1,2,3,4,15,16,17,18].includes(i))this.core.eventBus.emit("V2NIMTeamService/sysNotification",t);else{if(![5,6].includes(i)){var o=Object.assign(Object.assign({},t),{conversationType:{100:1,101:2,102:1,103:3}[i]});return delete o.type,o}this.core.eventBus.emit("V2NIMFriendService/sysNotification",t)}}markBroadcastMsgAck(t){this.config.compatibleWithV1||this.core.sendCmd("v2BatchMarkRead",{sid:7,cid:17,ids:t.map((t=>t.id))})}syncBroadcastMsgHandler(t){var i=t.content.datas;this.markBroadcastMsgAck(i),i.forEach((t=>{this.core.eventBus.emit("V2NIMSync/updateTimetag",{broadcastMsgs:parseInt(t.id)})})),this.emit("onReceiveBroadcastNotifications",i)}onBroadcastMsgHandler(t){var i=t.content.data;this.markBroadcastMsgAck([i]),this.core.eventBus.emit("V2NIMSync/updateTimetag",{broadcastMsgs:parseInt(i.id)}),this.emit("onReceiveBroadcastNotifications",[i])}onSysNotificationHandler(t){var i=fillIdServer(t,t.content.data,"idServer");this.markSysNotificationAck([i]);var o=this.processSystemNotification(i);o&&this.emit("onReceiveCustomNotifications",[o])}v2SyncOfflineSysNotificationsHandler(t){this.markSysNotificationAck(t.content.datas);var i=t.content.datas.sort(((t,i)=>t.timestamp-i.timestamp)).map((t=>this.processSystemNotification(t))).filter((t=>t));i&&this.emit("onReceiveCustomNotifications",i)}v2NotificationRevokeHandler(t){var i=fillIdServer(t,t.content.data,"idServer");this.markSysNotificationAck([i])}v2NotificationSyncRevokeHandler(t){var{type:i}=t.content;1===parseInt(i)&&this.markSysNotificationAck(t.content.datas)}markSysNotificationAck(t){if(!this.config.compatibleWithV1){var i=[],o=[],m=[15,16,17,18,103];t.forEach((t=>{t.idServer&&(m.includes(t.type)?o.push(t.idServer):i.push(t.idServer))})),i.length>0&&this.core.sendCmd("v2BatchMarkRead",{sid:"7",cid:"3",ids:i}),o.length>0&&this.core.sendCmd("v2BatchMarkRead",{sid:"21",cid:"19",ids:o})}}}var Jr,Kr={joinMode:{type:"enum",values:[1,0,2],required:!1},agreeMode:{type:"enum",values:[0,1],required:!1},inviteMode:{type:"enum",values:[1,0],required:!1},updateInfoMode:{type:"enum",values:[1,0],required:!1},updateExtensionMode:{type:"enum",values:[1,0],required:!1},chatBannedMode:{type:"enum",values:[0,1],required:!1}},Wr={type:"object",required:!0,rules:Object.assign({name:{type:"string",allowEmpty:!1},teamType:{type:"enum",values:[1,2]},memberLimit:{type:"number",min:1,required:!1}},Kr)},Xr={type:"array",min:1,itemType:"string"},Qr={type:"boolean"},Zr={type:"string"},en={type:"string",allowEmpty:!1},tn={type:"object",rules:{antispamBusinessId:{type:"string",required:!1}},required:!1},rn={teamId:{type:"string",regExp:/^[1-9]\d*$/,allowEmpty:!1}},nn={teamIds:{type:"array",itemRules:{type:"string",allowEmpty:!1,regExp:/^[1-9]\d*$/},min:1}},sn={teamType:{type:"enum",values:[1,2]}},an={teamTypes:{type:"array",itemType:"enum",values:[1,2],required:!1}},cn={inviteeParams:{type:"object",required:!0,rules:{inviteeAccountIds:Xr,postscript:Object.assign(Object.assign({},Zr),{required:!1}),serverExtension:Object.assign(Object.assign({},Zr),{required:!1})}}},dn={updateTeamInfoParams:{type:"object",required:!0,rules:Object.assign({name:{type:"string",allowEmpty:!1,required:!1},memberLimit:{type:"number",min:1,required:!1}},Kr)}},ln={type:"enum",values:[0,2]},pn={memberInfoParams:{type:"object",rules:{teamNick:{type:"string",required:!1},serverExtension:{type:"string",required:!1},antispamConfig:{type:"object",required:!1,rules:{antispamBusinessId:{type:"string",required:!1}}}}}},mn={chatBannedMode:{type:"enum",values:[0,1]}},hn={queryOption:{type:"object",rules:{roleQueryType:{type:"enum",values:[0,2,1]},onlyChatBanned:{type:"boolean",required:!1},direction:{type:"enum",values:[1,0],required:!1},limit:{type:"number",min:1,required:!1},nextToken:{type:"string",required:!1}}}},un={teamId:rn.teamId,teamType:{type:"enum",values:[1,2]},operatorAccountId:{type:"string",allowEmpty:!1}},gn={actionType:{type:"enum",values:[0,2,1,3,4,5]}},vn={actionType:{type:"enum",values:[2]}},fn={actionType:{type:"enum",values:[0]}},In={types:{type:"array",itemType:"enum",values:[0,2,1,3,4,5],required:!1},status:{type:"array",itemType:"enum",values:[1,3,0,2],required:!1},offset:{type:"number",min:0,required:!1},limit:{type:"number",min:1,required:!1}},yn={teamId:rn.teamId,teamType:sn.teamType,accountIds:Xr},_n={accountId:{type:"string",allowEmpty:!1},teamNick:{type:"string"},antispamConfig:{type:"object",required:!1,rules:{antispamBusinessId:{type:"string",required:!1}}}};class V2NIMTeamModelImpl{constructor(){this.teamMap=new Map,this.superTeamMap=new Map}set(t){t.forEach((t=>{this.chooseMap(t.teamType).set(t.teamId,t)}))}reset(){this.teamMap.clear(),this.superTeamMap.clear()}count(t,i=!0){var o=this.chooseMap(t),m=0;return o.forEach((t=>{i&&t.isValidTeam&&m++,i||m++})),m}chooseMap(t){return 2===t?this.superTeamMap:1===t?this.teamMap:new Map}getById(t,i,o=!0){var m=this.chooseMap(i).get(t);if(m){if(o&&m.isValidTeam)return m;if(!o)return m}}getAll(t,i=!0){var o=this.chooseMap(t);return Array.from(o.values()).filter((t=>!(!i||!t.isValidTeam)||(!i||void 0))).sort(((t,i)=>i.updateTime-t.updateTime))}upsert(t){var i=t.teamId,o=t.teamType,m=this.chooseMap(o),h=m.get(i)||{},u=Object.assign({},h,t);return m.set(i,u),u}deleteById(t,i){var o=this.getById(t,i);if(o)return o.isValidTeam=!1,o}searchTeamByKeyword(t){var i=[];return this.teamMap.forEach((o=>{o.name.includes(t)&&i.push(o)})),this.superTeamMap.forEach((o=>{o.name.includes(t)&&i.push(o)})),i}}class V2NIMTeamMemberModelImpl{constructor(){this.teamMembers=[],this.superTeamMembers=[],this.maxSize=11e3}reset(){this.teamMembers=[],this.superTeamMembers=[]}setData(t){t.forEach((t=>{this.chooseList(t.teamType).push(t)}))}chooseList(t){return 2===t?this.superTeamMembers:1===t?this.teamMembers:[]}getById(t,i,o){return this.chooseList(i).find((i=>i.teamId===t&&i.accountId===o))}upsert(t){var i=t.teamType,o=t.teamId,m=this.chooseList(i),h=m.findIndex((i=>i.teamId===o&&i.accountId===t.accountId));-1===h?m.push(t):m[h]=Object.assign(Object.assign({},m[h]),t),m.length>this.maxSize&&m.shift()}deleteByAccount(t,i,o){var m=this.chooseList(i),h=m.findIndex((i=>i.teamId===t&&i.accountId===o));if(-1!==h){var u=m[h];return u.inTeam=!1,m.splice(h,1),u}}deleteByTeamId(t,i){var o=this.chooseList(i).filter((i=>i.teamId!==t));2===i?this.superTeamMembers=o:this.teamMembers=o}}class V2NIMTeamNotificationImpl{constructor(t,i){this.core=t,this.service=i}processNotification(t){var{attachment:i,senderId:o,receiverId:m,createTime:h}=t,{id:u,data:v}=i,I=u>400?2:1,{id:_,ids:M,tinfo:E,mute:S}=formatTeamNotificationAttachData(v,I),T=this.service.model.getById(m,I);switch(this.core.logger.log(`v2Team::processNotification, notificationType:${u}, teamId:${m}`,v),u){case Jr.SUPER_TEAM_INVITATION:case Jr.TEAM_INVITATION:M.includes(this.core.account)&&this.onTeamJoined(E),this.onTeamMembersJoined(E,M.filter((t=>t!==this.core.account)));break;case Jr.SUPER_TEAM_INVITE_ACCEPT:case Jr.TEAM_INVITE_ACCEPT:o===this.core.account?(this.onTeamJoined(E),this.service.notificationModel.markExpired(E.teamId,E.teamType,o,h)):this.onTeamMemberJoined(E,o);break;case Jr.SUPER_TEAM_APPLY_ACCEPT:case Jr.TEAM_APPLY_ACCEPT:_===this.core.account?(this.onTeamJoined(E),this.service.notificationModel.markExpired(E.teamId,E.teamType,_,h)):this.onTeamMemberJoined(E,_);break;case Jr.SUPER_TEAM_ADD_MANAGER:case Jr.TEAM_ADD_MANAGER:this.updateTeamMemberRole(m,I,M,{memberRole:2,updateTime:h});break;case Jr.SUPER_TEAM_REMOVE_MANAGER:case Jr.TEAM_REMOVE_MANAGER:this.updateTeamMemberRole(m,I,M,{memberRole:0,updateTime:h});break;case Jr.SUPER_TEAM_KICK:case Jr.TEAM_KICK:this.onTeamInfoUpdated(E),M.forEach((t=>{t===this.core.account?this.onTeamLeft(m,I,!0):this.onTeamMemberKicked(o,E.teamId,E.teamType,t)}));break;case Jr.SUPER_TEAM_LEAVE:case Jr.TEAM_LEAVE:E?this.onTeamInfoUpdated(E):T&&o===this.core.account&&(T.isValidTeam=!1,this.onTeamInfoUpdated(T)),o===this.core.account?this.onTeamLeft(m,I,!1):this.onTeamMemberLeft(m,I,o);break;case Jr.SUPER_TEAM_DISMISS:case Jr.TEAM_DISMISS:this.onTeamDismissed(m,I);break;case Jr.SUPER_TEAM_UPDATE:case Jr.TEAM_UPDATED:this.onTeamInfoUpdated(E);break;case Jr.SUPER_TEAM_TRANSFER_OWNER:case Jr.TEAM_TRANSFER_OWNER:this.onTeamInfoUpdated(E),this.updateTeamMemberRole(m,I,[o,E.ownerAccountId],[{memberRole:0,updateTime:h},{memberRole:1,updateTime:h,joinTime:h}],!1);break;case Jr.SUPER_TEAM_MEMBER_MUTE:case Jr.TEAM_MEMBER_MUTE:this.service.model.upsert(E),this.updateTeamMemberRole(m,I,_?[_]:M,{chatBanned:0!==S,updateTime:h})}}onTeamJoined(t){this.service.model.upsert(t),this.service.emit("onTeamJoined",t),this.service.getTeamMemberListByIds(t.teamId,t.teamType,[this.core.account]).catch((t=>{this.core.logger.error("Get Member error after onTeamJoined",t)}))}onTeamLeft(t,i,o){var m=this.service.model.deleteById(t,i)||generateTeamByTeamId(t,i,{isValidTeam:!1,isTeamEffective:!0});this.service.memberModel.deleteByAccount(t,i,this.core.account),this.service.emit("onTeamLeft",m,o)}onTeamDismissed(t,i){var o=this.service.model.deleteById(t,i);o||(o=generateTeamByTeamId(t,i,{isValidTeam:!1,isTeamEffective:!1})),o.isTeamEffective=!1,this.service.model.upsert(o),this.service.memberModel.deleteByTeamId(t,i),this.service.emit("onTeamDismissed",o)}onTeamInfoUpdated(t){var i=this.service.model.upsert(t);this.service.emit("onTeamInfoUpdated",i)}onTeamMemberJoined(t,i){this.service.model.upsert(t),this.service.emit("onTeamInfoUpdated",t);var o=t.updateTime||t.createTime,m=generateMemberByTeamId(t.teamId,t.teamType,i,{joinTime:o,updateTime:o});this.service.emit("onTeamMemberJoined",[m])}onTeamMembersJoined(t,i){var o=t.updateTime||t.createTime,m=i.map((i=>generateMemberByTeamId(t.teamId,t.teamType,i,{joinTime:o,updateTime:o})));0!==m.length&&(this.service.model.upsert(t),this.service.emit("onTeamInfoUpdated",t),this.service.emit("onTeamMemberJoined",m))}onTeamMemberLeft(t,i,o){var m=this.service.memberModel.deleteByAccount(t,i,o);m||(m=generateMemberByTeamId(t,i,o,{inTeam:!1})),this.service.emit("onTeamMemberLeft",[m])}onTeamMemberKicked(t,i,o,m){var h=this.service.memberModel.deleteByAccount(i,o,m);h||(h=generateMemberByTeamId(i,o,m,{inTeam:!1})),this.service.emit("onTeamMemberKicked",t,[h])}onTeamMemberInfoUpdated(t){t.forEach((t=>{if(t.accountId===this.core.account&&this.core.V2NIMSettingService.name&&this.core.V2NIMConversationIdUtil.name){var i=1===t.teamType?this.core.V2NIMConversationIdUtil.teamConversationId(t.teamId):this.core.V2NIMConversationIdUtil.superTeamConversationId(t.teamId),o=this.core.V2NIMSettingService.getConversationMuteStatus(i);this.core.eventBus.emit("V2NIMSettingService/setMute",i,o)}})),this.service.emit("onTeamMemberInfoUpdated",t)}updateTeamMemberRole(t,i,o,m,h=!0){return __awaiter(this,void 0,void 0,(function*(){var u=o.filter(((o,h)=>{var u=this.service.memberModel.getById(t,i,o);return u&&this.service.memberModel.upsert(Object.assign(Object.assign({},u),Array.isArray(m)?m[h]:m)),!u}));if(h&&u.length>0)try{(yield this.service.getTeamMemberListByIds(t,i,u)).forEach((t=>this.service.memberModel.upsert(t)))}catch(t){this.core.logger.warn("v2Team::processNotification, getTeamMemberListByIds failed",t)}var v=o.map(((o,u)=>{var v=this.service.memberModel.getById(t,i,o);return v||h?v:generateMemberByTeamId(t,i,o,Array.isArray(m)?m[u]:m)})).filter((t=>!!t));v.length>0&&this.onTeamMemberInfoUpdated(v)}))}processSysNotification(t){if(!this.service.config.enableServerV2TeamJoinActionInfo){var{receiverId:i,postscript:o,senderId:m,timestamp:h,content:u}=t,v={};try{v=JSON.parse(u)}catch(t){this.core.logger.warn("v2Team::processSysNotification, parse content failed",u)}var I={0:0,1:1,2:2,3:3,15:0,16:1,17:2,18:3}[t.type],_=this.core.account,M="",E="";switch(I){case 0:M=m,E="";break;case 1:M=_,E="";break;case 2:M=m,E=_;break;case 3:M=_,E=m}var S={actionType:I,teamId:i,teamType:t.type>=15?2:1,operatorAccountId:m,postscript:o,timestamp:h,actionStatus:0,read:!1,fromAccountId:M,targetAccountId:E,serverId:"",updateTimestamp:h};v.attach&&(S.serverExtension=v.attach),this.core.logger.log("v2Team::processSysNotification, type:",t.type,S),this.service.notificationModelOld.create(S),this.service.emit("onReceiveTeamJoinActionInfo",S)}}updateTeamActionStatus(t,i){this.service.notificationModelOld.update({teamId:t.teamId,teamType:t.teamType,operatorAccountId:t.operatorAccountId,actionType:t.actionType,actionStatus:i})}checkIfExpired(t){return!!t&&(509===t||!(t>=500&&t<=599)&&!(t>=19e4))}setSyncTimestamp(t){t&&this.core.eventBus.emit("V2NIMSync/updateTimetag",{teamApplyList:t})}}!function(t){t[t.TEAM_INVITATION=0]="TEAM_INVITATION",t[t.TEAM_KICK=1]="TEAM_KICK",t[t.TEAM_LEAVE=2]="TEAM_LEAVE",t[t.TEAM_UPDATED=3]="TEAM_UPDATED",t[t.TEAM_DISMISS=4]="TEAM_DISMISS",t[t.TEAM_APPLY_ACCEPT=5]="TEAM_APPLY_ACCEPT",t[t.TEAM_TRANSFER_OWNER=6]="TEAM_TRANSFER_OWNER",t[t.TEAM_ADD_MANAGER=7]="TEAM_ADD_MANAGER",t[t.TEAM_REMOVE_MANAGER=8]="TEAM_REMOVE_MANAGER",t[t.TEAM_INVITE_ACCEPT=9]="TEAM_INVITE_ACCEPT",t[t.TEAM_MEMBER_MUTE=10]="TEAM_MEMBER_MUTE",t[t.SUPER_TEAM_INVITATION=401]="SUPER_TEAM_INVITATION",t[t.SUPER_TEAM_KICK=402]="SUPER_TEAM_KICK",t[t.SUPER_TEAM_LEAVE=403]="SUPER_TEAM_LEAVE",t[t.SUPER_TEAM_UPDATE=404]="SUPER_TEAM_UPDATE",t[t.SUPER_TEAM_DISMISS=405]="SUPER_TEAM_DISMISS",t[t.SUPER_TEAM_TRANSFER_OWNER=406]="SUPER_TEAM_TRANSFER_OWNER",t[t.SUPER_TEAM_ADD_MANAGER=407]="SUPER_TEAM_ADD_MANAGER",t[t.SUPER_TEAM_REMOVE_MANAGER=408]="SUPER_TEAM_REMOVE_MANAGER",t[t.SUPER_TEAM_MEMBER_MUTE=409]="SUPER_TEAM_MEMBER_MUTE",t[t.SUPER_TEAM_APPLY_ACCEPT=410]="SUPER_TEAM_APPLY_ACCEPT",t[t.SUPER_TEAM_INVITE_ACCEPT=411]="SUPER_TEAM_INVITE_ACCEPT"}(Jr||(Jr={}));class V2NIMTeamNotificationModelImpl{constructor(){this.datas=new Map,this.readTime=0,this.prefix="NIM_TEAM_OPERATION_READ_TIME_{ACCOUNT_ID}",this.maxCount=1e3}reset(){this.datas.clear()}setReadTimePrefix(t){this.prefix="NIM_TEAM_OPERATION_READ_TIME_{ACCOUNT_ID}".replace("{ACCOUNT_ID}",t),this.readTime=Number(Re.localStorage.getItem(this.prefix))||0,this.readTime>0&&this.datas.forEach((t=>{t.updateTimestamp<=this.readTime&&(t.read=!0)}))}getReadTime(){return this.readTime}getByOption(t){var{types:i,status:o,offset:m=0,limit:h=50}=t,u=Array.from(this.datas.values()).filter((t=>!(i&&i.length>0&&!i.includes(t.actionType))&&!(o&&o.length>0&&!o.includes(t.actionStatus)))).sort(((t,i)=>i.updateTimestamp-t.updateTimestamp)),v=u.slice(m,m+h),I=m+h>=u.length;return{infos:v,finished:I,offset:I?0:m+h}}setAllRead(){var t=0;this.datas.forEach((i=>{i.read=!0,t=Math.max(t,i.updateTimestamp)})),t&&(this.readTime=t,Re.localStorage.setItem(this.prefix,t.toString()))}setRead(t){var i=this.datas.get(t.serverId);i&&i.updateTimestamp&&(this.datas.forEach((t=>{t.updateTimestamp<=i.updateTimestamp&&(t.read=!0)})),this.readTime=i.updateTimestamp,Re.localStorage.setItem(this.prefix,i.updateTimestamp.toString()))}getUnreadCount(){var t=0;return this.datas.forEach((i=>{i.read||t++})),t}delete(t){this.datas.delete(t)}deleteByOption(t){var i=t.timestamp,o=t.type;this.datas.forEach((t=>{t.updateTimestamp<=i&&(o===Z.V2NIM_TEAM_JOIN_ACTION_TEAM_TYPE_ALL||o===Z.V2NIM_TEAM_JOIN_ACTION_TEAM_TYPE_NORMAL&&1===t.teamType||o===Z.V2NIM_TEAM_JOIN_ACTION_TEAM_TYPE_SUPER&&2===t.teamType)&&this.datas.delete(t.serverId)}))}upsert(t){t.serverId&&this.setLRU(t.serverId,t)}setLRU(t,i){if(this.datas.has(t))this.datas.delete(t);else if(this.datas.size>=this.maxCount){var o=this.datas.keys().next().value;o&&this.datas.delete(o)}this.datas.set(t,i)}updateStatus(t,i){if(0!==i){var o=this.datas.get(t);o&&0===o.actionStatus&&(o.actionStatus=i,this.datas.set(t,o))}}markExpired(t,i,o,m){this.datas.forEach((h=>{h.teamId===t&&h.teamType===i&&(h.fromAccountId===o&&0===h.actionType||h.targetAccountId===o&&2===h.actionType)&&0===h.actionStatus&&(h.actionStatus=3,h.updateTimestamp=m,this.datas.set(h.serverId,h))}))}getById(t){return this.datas.get(t)}}class V2NIMTeamNotificationModelOldImpl{constructor(){this.list=[],this.maxCount=1e3}reset(){this.list=[]}checkSameAction(t,i,o=!1){return t.teamId===i.teamId&&t.teamType===i.teamType&&t.actionType===i.actionType&&t.operatorAccountId===i.operatorAccountId&&(!o||t.timestamp===i.timestamp)}create(t){this.list.push(t),this.list.length>this.maxCount&&this.list.shift()}update(t){this.list.forEach((i=>{this.checkSameAction(i,t)&&0===i.actionStatus&&Object.assign(i,t)}))}delete(t){this.list=this.list.map((i=>{if(!this.checkSameAction(i,t,!1))return i})).filter((t=>t))}deleteByOption(t){var i=t.timestamp,o=t.type;this.list=this.list.filter((t=>!(t.updateTimestamp<=i&&(o===Z.V2NIM_TEAM_JOIN_ACTION_TEAM_TYPE_ALL||o===Z.V2NIM_TEAM_JOIN_ACTION_TEAM_TYPE_NORMAL&&1===t.teamType||o===Z.V2NIM_TEAM_JOIN_ACTION_TEAM_TYPE_SUPER&&2===t.teamType))))}getByOption(t){var{types:i,status:o,offset:m=0,limit:h=50}=t,u=[];this.list.forEach((t=>{i&&i.length>0&&!i.includes(t.actionType)||o&&o.length>0&&!o.includes(t.actionStatus)||u.push(t)})),u=u.sort(((t,i)=>i.timestamp-t.timestamp));var v=0;m>0&&(v=findIndexWithinTargetValue(u,"timestamp",m),u[v]&&u[v].timestamp===m&&(v+=1));var I=u.slice(v).length;return(u=u.slice(v,v+h)).length>0?{offset:I>h?u[u.length-1].timestamp:0,finished:!(I>h),infos:u}:{offset:0,finished:!0,infos:u}}setRead(t){for(var i of this.list)this.checkSameAction(i,t)&&(i.read=!0)}setAllRead(){for(var t of this.list)t.read=!0}getUnreadCount(){var t=new Set;for(var i of this.list)i.read||0!==i.actionStatus||0!==i.actionType&&2!==i.actionType||t.add(`${i.operatorAccountId}_${i.teamType}_${i.teamId}`);return t.size}}class V2NIMTeamEventImpl{constructor(t,i){this.core=t,this.service=i,this.model=i.model,this.memberModel=i.memberModel,this.notification=i.notification,this.logger=this.core.logger}setListener(){this.core.eventBus.on("V2NIMTeamService/onSyncStarted",(()=>{this.service.notificationModel.setReadTimePrefix(this.core.account),this.service.emit("onSyncStarted")})),this.core.eventBus.on("V2NIMTeamService/onSyncFinished",(()=>{this.service.emit("onSyncFinished")})),this.core.eventBus.on("V2NIMTeamService/onSyncFailed",(t=>{this.service.emit("onSyncFailed",t)})),this.core.eventBus.on("forwardReceive/V2NIMTeamService/created",(t=>{this.model.upsert(t);var i=generateMemberByTeamId(t.teamId,t.teamType,this.core.account,{memberRole:1});this.memberModel.upsert(i),this.service.emit("onTeamCreated",t)})),this.core.eventBus.on("forwardReceive/V2NIMTeamService/updateSelfTeamMemberInfo",(t=>{this.memberModel.upsert(t),this.service.emit("onTeamInfoUpdated",[t])})),this.core.eventBus.on("forwardReceive/V2NIMTeamService/updateTeamActionStatus",this.notification.updateTeamActionStatus.bind(this.notification)),this.core.eventBus.on("V2NIMTeamService/sysNotification",this.notification.processSysNotification.bind(this.notification)),this.core.eventBus.on("V2NIMTeamService/notification",this.notification.processNotification.bind(this.notification))}beforeEmit(t,...i){var o=`${this.service.name}::emit ${t.toString()}`;if("onTeamCreated"===t||"onTeamDismissed"===t||"onTeamJoined"===t||"onTeamLeft"===t||"onTeamInfoUpdated"===t){var m=i[0];this.logger.log(`${o}`,`team:${m.teamId}_${m.teamType};updateTime:${m.updateTime}`)}else if("onTeamMemberJoined"===t||"onTeamMemberLeft"===t||"onTeamMemberInfoUpdated"===t){var h=i[0];this.logger.log(`${o}`,h.map((t=>`team:${t.teamId}_${t.teamType};account:${t.accountId}`)))}else if("onTeamMemberKicked"===t){var u=i[0],v=i[1];this.logger.log(`${o}`,`operator${u}`,v.map((t=>`team:${t.teamId}_${t.teamType};account:${t.accountId}`)))}else this.logger.log(`${o}`,...i)}onSyncDone(t){t?this.service.emit("onSyncFailed",t):this.service.emit("onSyncFinished")}}var Mn={1:2,2:5,3:3,4:0,5:4,6:1},En={1:0,2:1,3:2,4:0,5:1,6:2};class V2NIMTeamHandlerImpl{constructor(t,i){this.core=t,this.service=i,this.model=i.model,this.memberModel=i.memberModel,this.notificationModel=i.notificationModel,this.notificationModelOld=i.notificationModelOld,this.logger=this.core.logger}get useServerNotification(){return this.service.config.enableServerV2TeamJoinActionInfo}v2TeamSyncHandler(t){this.model.set(t.content.datas)}v2SuperTeamSyncHandler(t){this.model.set(t.content.datas)}v2TeamCreateMultiSyncHandler(t){var i=t.content.data;this.model.upsert(i);var o=generateMemberByTeamId(i.teamId,i.teamType,this.core.account,{memberRole:1});this.memberModel.upsert(o),this.service.emit("onTeamCreated",i)}v2SuperTeamCreateMultiSyncHandler(t){var i=t.content.data;this.model.upsert(i);var o=generateMemberByTeamId(i.teamId,i.teamType,this.core.account,{memberRole:1});this.memberModel.upsert(o),this.service.emit("onTeamCreated",i)}v2TeamMemberUpdateMultiSyncHandler(t){var i=t.content.data;i.teamType=1;var o=this.memberModel.getById(i.teamId,i.teamType,i.accountId);this.service.notification.updateTeamMemberRole(i.teamId,i.teamType,[i.accountId],i),i.accountId===this.core.account&&o&&o.bits!==i.bits&&this.core.eventBus.emit("V2NIMSettingService/updateBits",i.teamId,i.teamType,i.bits)}v2SuperTeamMemberUpdateMultiSyncHandler(t){var i=t.content.data;i.teamType=2;var o=this.memberModel.getById(i.teamId,i.teamType,i.accountId);this.service.notification.updateTeamMemberRole(i.teamId,i.teamType,[i.accountId],i),i.accountId===this.core.account&&o&&o.bits!==i.bits&&this.core.eventBus.emit("V2NIMSettingService/updateBits",i.teamId,i.teamType,i.bits)}v2TeamMembersOfSelfInSyncHandler(t){t.content.datas.forEach((t=>{t.teamType=1,this.memberModel.upsert(t),this.service.notificationModel.markExpired(t.teamId,t.teamType,t.accountId,t.joinTime)}))}v2SuperTeamMembersOfSelfInSyncHandler(t){t.content.datas.forEach((t=>{t.teamType=2,this.memberModel.upsert(t),this.service.notificationModel.markExpired(t.teamId,t.teamType,t.accountId,t.joinTime)}))}v2TeamJoinActionDeleteMultiSyncHandler(t){if(this.useServerNotification){var i=t.content.data;i&&(this.notificationModel.delete(i.serverId),this.service.notification.setSyncTimestamp(i.serverTime))}}v2TeamJoinActionClearMultiSyncHandler(t){if(this.useServerNotification){var i=t.content.data;this.notificationModel.deleteByOption({timestamp:i.timestamp,type:i.type}),this.service.notification.setSyncTimestamp(i.serverTime)}}v2TeamJoinActionListHandler(t){if(this.useServerNotification){var i=t.content.datas,o=t.content.serverTime;i.forEach((t=>{var i=this.completeTeamJoinAction(t);this.notificationModel.upsert(i),this.triggerEventFromJoinAction(i)})),this.service.notification.setSyncTimestamp(o)}}triggerEventFromJoinAction(t){this.service.emit("onReceiveTeamJoinActionInfo",t)}v2TeamJoinActionListSyncHandler(t){if(this.useServerNotification){var i=t.content.datas,o=t.content.serverTime;i.forEach((t=>{var i=this.notificationModel.getById(t.serverId),o=this.completeTeamJoinAction(t);this.notificationModel.upsert(o),i&&i.actionStatus!==o.actionStatus?this.triggerEventFromJoinAction(o):i||!1!==o.read||0!==o.actionStatus||this.triggerEventFromJoinAction(o)})),this.service.notification.setSyncTimestamp(o)}}completeTeamJoinAction(t){var i=this.notificationModel.getReadTime(),o=this.core.account,m=this.notificationModel.getById(t.serverId),h=!!this.model.getById(t.teamId,t.teamType);if("number"==typeof t.status){t.actionType=Mn[t.status];var u=t.finished||!1,v=En[t.status];t.actionStatus=u&&0===v?3:v}return delete t.status,delete t.finished,0===t.actionStatus&&h&&(t.fromAccountId===o&&0===t.actionType||t.targetAccountId===o&&2===t.actionType)&&(t.actionStatus=3),t.updateTimestamp<=i?t.read=!0:t.operatorAccountId===o?t.read="boolean"!=typeof(null==m?void 0:m.read)||m.read:t.operatorAccountId!==o&&(t.read=!1),t.postscriptHistory&&t.postscriptHistory.length>0&&(t.postscript=t.postscriptHistory[t.postscriptHistory.length-1].content),t}v2TeamJoinActionClearSyncHandler(t){t.content.datas.forEach((t=>{this.notificationModel.delete(t.serverId),this.notificationModelOld.delete(t)})),t.content.clearInfos.forEach((t=>{var i=t.timestamp,o=t.type,m={timestamp:i||this.core.timeOrigin.getNTPTime(),type:o||Z.V2NIM_TEAM_JOIN_ACTION_TEAM_TYPE_ALL};this.notificationModel.deleteByOption(m),this.notificationModelOld.deleteByOption(m)}));var i=t.content.serverTime;this.service.notification.setSyncTimestamp(i)}}class V2NIMTeamServiceImpl extends V2Service{constructor(t){super("V2NIMTeamService",t),this.config={enableServerV2TeamJoinActionInfo:!1},this.core._registerDep(V2NIMConversationIdUtilImpl,"V2NIMConversationIdUtil"),this.model=new V2NIMTeamModelImpl,this.memberModel=new V2NIMTeamMemberModelImpl,this.notificationModel=new V2NIMTeamNotificationModelImpl,this.notificationModelOld=new V2NIMTeamNotificationModelOldImpl,this.notification=new V2NIMTeamNotificationImpl(t,this),this.event=new V2NIMTeamEventImpl(t,this),this.handler=new V2NIMTeamHandlerImpl(t,this),"v2"===this.core.options.apiVersion&&(registerParser({cmdMap:yi,cmdConfig:bi}),this.setListener())}setOptions(t){this.config=Object.assign(this.config,t)}setListener(){this.event.setListener()}reset(){this.model.reset(),this.memberModel.reset(),this.notificationModel.reset(),this.notificationModelOld.reset()}emit(t,...i){return this.event.beforeEmit(t,...i),super.emit(t,...i)}createTeam(t,i,o,m){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate({createTeamParams:Wr},{createTeamParams:t},"",!0),validate({inviteeAccountIds:Object.assign(Object.assign({},Xr),{min:0,required:!1})},{inviteeAccountIds:i},"",!0),validate({antispamConfig:tn},{antispamConfig:m},"",!0);var h=2===t.teamType?"v2SuperTeamCreate":"v2TeamCreate",u=yield this.core.sendCmd(h,{team:t,inviteeAccountIds:i||[],postscript:o||"",antispamConfig:m}),v=u.content.team;return this.model.upsert(v),this.getTeamMemberListByIds(v.teamId,v.teamType,[this.core.account]).catch((t=>{this.core.logger.error("Get Member error after createTeam",t)})),this.emit("onTeamCreated",v),{team:v,failedList:u.content.failedList}}))}updateTeamInfo(t,i,o,m){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(rn,{teamId:t},"",!0),validate(sn,{teamType:i},"",!0),validate(dn,{updateTeamInfoParams:o},"",!0),validate({antispamConfig:tn},{antispamConfig:m},"",!0);var h=Object.assign({teamId:t,teamType:i},o),u=2===i?"v2SuperTeamUpdateInfo":"v2TeamUpdateInfo";yield this.core.sendCmd(u,{team:h,antispamConfig:m}),this.model.upsert(h)}))}leaveTeam(t,i){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(rn,{teamId:t},"",!0),validate(sn,{teamType:i},"",!0);var o=2===i?"v2SuperTeamLeave":"v2TeamLeave";yield this.core.sendCmd(o,{teamId:t}),this.model.deleteById(t,i)}))}getTeamInfo(t,i){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(rn,{teamId:t},"",!0),validate(sn,{teamType:i},"",!0);var o=2===i?"v2SuperTeamGetInfo":"v2TeamGetInfo",m=this.model.getById(t,i,!1);if(m)return m;var h=(yield this.core.sendCmd(o,{teamId:t})).content.team;return this.model.upsert(h),h}))}getTeamInfoFromCloud(t,i){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(rn,{teamId:t},"",!0),validate(sn,{teamType:i},"",!0);var o=this.model.getById(t,i,!1),m=2===i?"v2SuperTeamGetInfo":"v2TeamGetInfo",h=(yield this.core.sendCmd(m,{teamId:t})).content.team,u=!1;o?o.updateTime!==h.updateTime&&(u=!0):u=!0;var v=this.model.upsert(h);return u&&this.emit("onTeamInfoUpdated",v),h}))}getJoinedTeamList(t){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(an,{teamTypes:t},"",!0),this.core.V2NIMLoginService.checkIllegalState(),t&&0!==t.length||(t=[1,2]);var i=[];return t.forEach((t=>{i=i.concat(this.model.getAll(t))})),i.sort(((t,i)=>t.createTime-i.createTime))}))}getOwnerTeamList(t){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(an,{teamTypes:t},"",!0),this.core.V2NIMLoginService.checkIllegalState(),t&&0!==t.length||(t=[1,2]);var i=[];return t.forEach((t=>{var o=this.model.getAll(t).filter((t=>t.ownerAccountId===this.core.account));i=i.concat(o)})),i.sort(((t,i)=>t.createTime-i.createTime))}))}getManagerTeamList(t){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(an,{teamTypes:t},"",!0),this.core.V2NIMLoginService.checkIllegalState(),t&&0!==t.length||(t=[1,2]);var i=[],o=yield this.getJoinedTeamMembers(t),m=new Map;return o.filter((t=>1===t.memberRole||2===t.memberRole)).forEach((t=>{m.has(t.teamType)||m.set(t.teamType,new Set);var i=m.get(t.teamType);i&&i.add(t.teamId)})),t.forEach((t=>{var o=m.get(t);if(o&&o.size>0){var h=this.model.getAll(t).filter((t=>o.has(t.teamId)));i=i.concat(h)}})),i.sort(((t,i)=>t.createTime-i.createTime))}))}getJoinedTeamCount(t){this.checkV2(),validate(an,{teamTypes:t},"",!0),this.core.V2NIMLoginService.checkIllegalState(),t&&0!==t.length||(t=[1,2]);var i=0;return t.forEach((t=>{i+=this.model.count(t)})),i}getJoinedTeamMembers(t){this.checkV2(),validate(an,{teamTypes:t},"",!0),this.core.V2NIMLoginService.checkIllegalState(),t&&0!==t.length||(t=[1,2]);var i=[];return t.forEach((t=>{var o=this.memberModel.chooseList(t).filter((t=>t.accountId===this.core.account));i=i.concat(o)})),Promise.resolve(i)}getTeamInfoByIds(t,i){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(nn,{teamIds:t},"",!0),validate(sn,{teamType:i},"",!0);var o=2===i?"v2SuperTeamGetByIds":"v2TeamGetByIds",m=t.map((t=>this.model.getById(t,i,!1))),h=t.filter(((t,i)=>!m[i]));if(0===h.length)return m;var u=(yield this.core.sendCmd(o,{teamIds:h})).content.teams;return m.map(((i,o)=>{if(i)return i;var m=t[o],h=u.find((t=>t.teamId===m));return h&&this.model.upsert(h),h})).filter((t=>!!t))}))}dismissTeam(t,i){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(rn,{teamId:t},"",!0),validate(sn,{teamType:i},"",!0);var o=2===i?"v2SuperTeamDismiss":"v2TeamDismiss";yield this.core.sendCmd(o,{teamId:t})}))}inviteMember(t,i,o,m){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(rn,{teamId:t},"",!0),validate(sn,{teamType:i},"",!0),validate({inviteeAccountIds:Xr},{inviteeAccountIds:o},"",!0),validate({postscript:Object.assign(Object.assign({},Zr),{required:!1})},{postscript:m},"",!0);var h=2===i?"v2SuperTeamInviteMembers":"v2TeamInviteMembers";return(yield this.core.sendCmd(h,{teamId:t,accounts:o,ps:m||""})).content.abortedAccidList}))}inviteMemberEx(t,i,o){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(rn,{teamId:t},"",!0),validate(sn,{teamType:i},"",!0),validate(cn,{inviteeParams:o},"",!0);var m=2===i?"v2SuperTeamInviteMembers":"v2TeamInviteMembers";return(yield this.core.sendCmd(m,{teamId:t,accounts:o.inviteeAccountIds,ps:o.postscript||"",attach:o.serverExtension})).content.abortedAccidList}))}acceptInvitation(t){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(un,t,"invitationInfo",!0),validate(vn,t,"invitationInfo",!0);var{teamType:i,teamId:o,operatorAccountId:m}=t,h=2===i?"v2SuperTeamAcceptInvitation":"v2TeamAcceptInvitation";try{var u=yield this.core.sendCmd(h,{teamId:o,from:m});return this.notification.updateTeamActionStatus(t,1),u.content.team}catch(i){var v=i;throw this.notification.checkIfExpired(v.code)&&this.notification.updateTeamActionStatus(t,3),i}}))}rejectInvitation(t,i){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(un,t,"invitationInfo",!0),validate(vn,t,"invitationInfo",!0),validate({postscript:Object.assign(Object.assign({},Zr),{required:!1})},{postscript:i},"",!0);var{teamType:o,teamId:m,operatorAccountId:h}=t,u=2===o?"v2SuperTeamRejectInvite":"v2TeamRejectInvite";try{yield this.core.sendCmd(u,{teamId:m,from:h,ps:i||""}),this.notification.updateTeamActionStatus(t,2)}catch(i){var v=i;throw this.notification.checkIfExpired(v.code)&&this.notification.updateTeamActionStatus(t,3),i}}))}kickMember(t,i,o){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(rn,{teamId:t},"",!0),validate(sn,{teamType:i},"",!0),validate({memberAccountIds:Xr},{memberAccountIds:o},"",!0);var m=2===i?"v2SuperTeamKickMembers":"v2TeamKickMembers";yield this.core.sendCmd(m,{teamId:t,accounts:o})}))}applyJoinTeam(t,i,o){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(rn,{teamId:t},"",!0),validate(sn,{teamType:i},"",!0);var m=2===i?"v2SuperTeamApplyToJoin":"v2TeamApplyToJoin",h=yield this.core.sendCmd(m,{teamId:t,ps:o||""}),u=h.content.team,v=h.content.isInTeam;return u.isValidTeam=!!u.isValidTeam&&!!v,u}))}acceptJoinApplication(t){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(un,t,"applicationInfo",!0),validate(fn,t,"applicationInfo",!0);var{teamType:i,teamId:o,operatorAccountId:m}=t,h=2===i?"v2SuperTeamAcceptJoinApplication":"v2TeamAcceptJoinApplication";try{yield this.core.sendCmd(h,{teamId:o,from:m}),this.notification.updateTeamActionStatus(t,1)}catch(i){var u=i;throw this.notification.checkIfExpired(u.code)&&this.notification.updateTeamActionStatus(t,3),i}}))}rejectJoinApplication(t,i){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(un,t,"applicationInfo",!0),validate(fn,t,"applicationInfo",!0),validate({postscript:Object.assign(Object.assign({},Zr),{required:!1})},{postscript:i},"",!0);var{teamType:o,teamId:m,operatorAccountId:h}=t,u=2===o?"v2SuperTeamRejectJoinApplication":"v2TeamRejectJoinApplication";try{yield this.core.sendCmd(u,{teamId:m,from:h,ps:i||""}),this.notification.updateTeamActionStatus(t,2)}catch(i){var v=i;throw this.notification.checkIfExpired(v.code)&&this.notification.updateTeamActionStatus(t,3),i}}))}updateTeamMemberRole(t,i,o,m){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(rn,{teamId:t},"",!0),validate(sn,{teamType:i},"",!0),validate({memberAccountIds:Xr},{memberAccountIds:o},"",!0),validate({memberRole:ln},{memberRole:m},"",!0);var h=2===m?"AddManagers":"RemoveManagers";h=2===i?`v2SuperTeam${h}`:`v2Team${h}`,yield this.core.sendCmd(h,{teamId:t,accounts:uniq(o)})}))}transferTeamOwner(t,i,o,m){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(rn,{teamId:t},"",!0),validate(sn,{teamType:i},"",!0),validate({accountId:en},{accountId:o},"",!0),validate({leave:{type:"boolean",required:!1}},{leave:m},"",!0);var h=this.model.getById(t,i);if(h&&h.ownerAccountId===o)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"Transfer to self is not allowed"}});var u=2===i?"v2SuperTeamTransferOwner":"v2TeamTransferOwner";yield this.core.sendCmd(u,{teamId:t,account:o,leave:m||!1})}))}updateSelfTeamMemberInfo(t,i,o){return __awaiter(this,void 0,void 0,(function*(){if(this.checkV2(),validate(rn,{teamId:t},"",!0),validate(sn,{teamType:i},"",!0),validate(pn,{memberInfoParams:o},"",!0),void 0===o.teamNick&&void 0===o.serverExtension)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INVALID_PARAMETER});var m=2===i?"v2SuperTeamUpdateSelfMemberInfo":"v2TeamUpdateSelfMemberInfo",h=Object.assign(Object.assign({},o),{teamId:t,accountId:this.core.account}),u=o.antispamConfig?{teamMember:h,specialFollowUpdate:{},antispam:o.antispamConfig}:{teamMember:h};yield this.core.sendCmd(m,u),yield this.notification.updateTeamMemberRole(t,i,[this.core.account],h);var v=this.memberModel.getById(t,i,this.core.account);if(this.core.V2NIMSettingService.name&&this.core.V2NIMConversationIdUtil.name){var I=1===i?this.core.V2NIMConversationIdUtil.teamConversationId(t):this.core.V2NIMConversationIdUtil.superTeamConversationId(t),_=this.core.V2NIMSettingService.getConversationMuteStatus(I);this.core.eventBus.emit("V2NIMSettingService/setMute",I,_)}this.core.eventBus.emit("forwardSend/V2NIMTeamService/updateSelfTeamMemberInfo",v)}))}updateTeamMemberNick(t,i,o,m){return __awaiter(this,void 0,void 0,(function*(){if(this.checkV2(),validate(rn,{teamId:t},"",!0),validate(sn,{teamType:i},"",!0),validate({accountId:en},{accountId:o},"",!0),validate({nick:Zr},{nick:m},"",!0),o===this.core.account)return this.updateSelfTeamMemberInfo(t,i,{teamNick:m});var h=2===i?"v2SuperTeamUpdateMember":"v2TeamUpdateMember";yield this.core.sendCmd(h,{teamMember:{teamNick:m,teamId:t,accountId:o}})}))}updateTeamMemberNickEx(t,i,o){return __awaiter(this,void 0,void 0,(function*(){if(this.checkV2(),validate(rn,{teamId:t},"",!0),validate(sn,{teamType:i},"",!0),validate(_n,o,"",!0),o.accountId===this.core.account)return this.updateSelfTeamMemberInfo(t,i,{teamNick:o.teamNick,antispamConfig:o.antispamConfig});var m=2===i?"v2SuperTeamUpdateMember":"v2TeamUpdateMember";yield this.core.sendCmd(m,{teamMember:{teamNick:o.teamNick,teamId:t,accountId:o.accountId},antispam:o.antispamConfig})}))}setTeamChatBannedMode(t,i,o){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(rn,{teamId:t},"",!0),validate(sn,{teamType:i},"",!0),validate(mn,{chatBannedMode:o},"",!0);var m=2===i?"v2SuperTeamSetChatBannedMode":"v2TeamSetChatBannedMode";yield this.core.sendCmd(m,{teamId:t,chatBannedMode:o}),this.model.upsert({teamId:t,teamType:i,chatBannedMode:o})}))}setTeamMemberChatBannedStatus(t,i,o,m){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(rn,{teamId:t},"",!0),validate(sn,{teamType:i},"",!0),validate({accountId:en},{accountId:o},"",!0),validate({chatBanned:Qr},{chatBanned:m},"",!0);var h=2===i?"v2SuperTeamMemberSetChatBannedStatus":"v2TeamMemberSetChatBannedStatus";yield this.core.sendCmd(h,{teamId:t,accountId:2===i?[o]:o,chatBanned:m?1:0})}))}getTeamMemberList(t,i,o){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(rn,{teamId:t},"",!0),validate(sn,{teamType:i},"",!0),validate(hn,{queryOption:o},"",!0);var m=void 0===o.direction?0:o.direction;m=0===m?1:0;var h=yield this.core.sendCmd("v2TeamMemberGetList",{tag:Object.assign(Object.assign({teamId:t,teamType:i,onlyChatBanned:!1,nextToken:"",limit:100},o),{direction:m})}),u=h.content.datas,v=get(h,"raw.r.0");return 2===i&&v&&v.map&&(u=v.map((t=>deserialize(t,invertSerializeItem(Ti))))),{nextToken:h.content.pageInfo.nextToken||"",finished:!+h.content.pageInfo.hasMore,memberList:processTeamMembers(u,i)}}))}getTeamMemberListByIds(t,i,o){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(rn,{teamId:t},"",!0),validate(sn,{teamType:i},"",!0),validate({accountIds:Xr},{accountIds:o},"",!0);for(var m=2===i?"v2SuperTeamMemberGetListByIds":"v2TeamMemberGetListByIds",h=o.map((i=>`${t}|${i}`)),u=[],v=0;v<h.length;v+=20){var I=processTeamMembers((yield this.core.sendCmd(m,{tag:h.slice(v,v+20)})).content.datas,i);u=u.concat(I),I.forEach((t=>this.memberModel.upsert(t)))}return u}))}getTeamMemberInvitor(t,i,o){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(rn,{teamId:t},"",!0),validate(sn,{teamType:i},"",!0),validate({accountIds:Xr},{accountIds:o},"",!0);var m=2===i?"v2SuperTeamGetMemberInvitor":"v2TeamGetMemberInvitor";return(yield this.core.sendCmd(m,{teamId:t,accounts:o})).content.accountsMap}))}searchTeamByKeyword(t){return __awaiter(this,void 0,void 0,(function*(){return this.checkV2(),this.checkLogin(),validate({keyword:en},{keyword:t},"",!0),this.model.searchTeamByKeyword(t)}))}addTeamMembersFollow(t,i,o){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(yn,{teamId:t,teamType:i,accountIds:o},"",!0);var m=2===i?"v2SuperTeamUpdateSelfMemberInfo":"v2TeamUpdateSelfMemberInfo",[h]=yield this.getTeamMemberListByIds(t,i,[this.core.account]),u=(yield this.core.sendCmd(m,{teamMember:{teamId:t},specialFollowUpdate:{accountIds:o,operation:1}})).content.data;Object.keys(u).length>0&&(Object.assign(h,u),this.emit("onTeamMemberInfoUpdated",[h]),this.memberModel.upsert(h))}))}removeTeamMembersFollow(t,i,o){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(yn,{teamId:t,teamType:i,accountIds:o},"",!0);var[m]=yield this.getTeamMemberListByIds(t,i,[this.core.account]),h=2===i?"v2SuperTeamUpdateSelfMemberInfo":"v2TeamUpdateSelfMemberInfo",u=(yield this.core.sendCmd(h,{teamMember:{teamId:t},specialFollowUpdate:{accountIds:o,operation:0}})).content.data;Object.keys(u).length>0&&(Object.assign(m,u),this.emit("onTeamMemberInfoUpdated",[m]),this.memberModel.upsert(m))}))}getTeamJoinActionInfoList(t){return this.checkV2(),validate(In,t,"option",!0),this.core.V2NIMLoginService.checkIllegalState(),Promise.resolve(this.config.enableServerV2TeamJoinActionInfo?this.notificationModel.getByOption(t):this.notificationModelOld.getByOption(t))}clearAllTeamJoinActionInfo(){return __awaiter(this,void 0,void 0,(function*(){if(this.checkV2(),this.core.V2NIMLoginService.checkIllegalState(),this.config.enableServerV2TeamJoinActionInfo){var t=yield this.core.sendCmd("v2TeamJoinActionClear",{tag:{timestamp:this.core.timeOrigin.getNTPTime(),type:Z.V2NIM_TEAM_JOIN_ACTION_TEAM_TYPE_ALL}});this.notification.setSyncTimestamp(t.content.serverTime),this.notificationModel.reset()}this.notificationModelOld.reset()}))}clearAllTeamJoinActionInfoEx(t){return __awaiter(this,void 0,void 0,(function*(){this.core.V2NIMLoginService.checkIllegalState(),validate({timestamp:{type:"number",required:!1},type:{type:"enum",values:[Z.V2NIM_TEAM_JOIN_ACTION_TEAM_TYPE_ALL,Z.V2NIM_TEAM_JOIN_ACTION_TEAM_TYPE_NORMAL,Z.V2NIM_TEAM_JOIN_ACTION_TEAM_TYPE_SUPER],required:!1}},t,"",!0);var i={timestamp:t.timestamp||this.core.timeOrigin.getNTPTime(),type:t.type||Z.V2NIM_TEAM_JOIN_ACTION_TEAM_TYPE_ALL};if(this.config.enableServerV2TeamJoinActionInfo){var o=yield this.core.sendCmd("v2TeamJoinActionClear",{tag:i});this.notification.setSyncTimestamp(o.content.serverTime),this.notificationModel.deleteByOption(i)}this.notificationModelOld.deleteByOption(i)}))}deleteTeamJoinActionInfo(t){return __awaiter(this,void 0,void 0,(function*(){if(this.checkV2(),this.core.V2NIMLoginService.checkIllegalState(),validate(un,t,"",!0),validate(gn,t,"",!0),validate({timestamp:{type:"number",min:1}},t,"",!0),this.config.enableServerV2TeamJoinActionInfo&&t.serverId){var i=yield this.core.sendCmd("v2TeamJoinActionDelete",{tag:{serverId:t.serverId,teamType:t.teamType,teamId:t.teamId}});this.notification.setSyncTimestamp(i.content.serverTime),this.notificationModel.delete(t.serverId)}this.notificationModelOld.delete(t)}))}setTeamJoinActionInfoRead(t){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),this.core.V2NIMLoginService.checkIllegalState(),t?(validate(un,t,"",!0),validate(gn,t,"",!0),this.notificationModel.setRead(t),this.notificationModelOld.setRead(t)):(this.notificationModel.setAllRead(),this.notificationModelOld.setAllRead())}))}getTeamJoinActionInfoUnreadCount(){return __awaiter(this,void 0,void 0,(function*(){return this.checkV2(),this.core.V2NIMLoginService.checkIllegalState(),this.config.enableServerV2TeamJoinActionInfo?this.notificationModel.getUnreadCount():this.notificationModelOld.getUnreadCount()}))}}var Sn="V2NIMUserService",Tn={"34_3":"v2UpdateBlockList","34_7":"v2GetUserList","34_10":"v2UpdateSelfUserProfile","3_109":"v2SyncSelfUserInfo","3_110":"onUpdateUserProfile","3_103":"onUpdateBlockList","3_8":"syncBlockAndMuteList","34_5":"v2SetP2PMessageMuteMode","3_105":"v2OnUpdateMuteList"},Cn={accountId:1,name:3,avatar:4,sign:5,gender:{id:6,retType:"number"},email:7,birthday:8,mobile:9,serverExtension:10,createTime:{id:12,retType:"number"},updateTime:{id:13,retType:"number"}},Nn={v2UpdateBlockList:{sid:34,cid:3,service:Sn,params:[{type:"String",name:"accountId"},{type:"Bool",name:"addToBlockList"}]},v2GetUserList:{sid:34,cid:7,service:Sn,params:[{type:"StrArray",name:"accountIds"}],response:[{type:"PropertyArray",name:"data",reflectMapper:invertSerializeItem(Cn)}]},v2UpdateSelfUserProfile:{sid:34,cid:10,service:Sn,params:[{type:"Property",name:"tag",reflectMapper:Cn}],response:[{type:"Long",name:"updateTime"}]},onUpdateUserProfile:{sid:3,cid:110,service:Sn,response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Cn)}]},onUpdateBlockList:{sid:3,cid:103,service:Sn,response:[{type:"String",name:"accountId"},{type:"Bool",name:"addToBlockList"}]},syncBlockAndMuteList:{sid:3,cid:8,service:Sn,response:[{type:"PropertyArray",name:"data",reflectMapper:invertSerializeItem({accountId:0,isMute:{id:1,retType:"boolean"},isBlock:{id:2,retType:"boolean"}})},{type:"Long",name:"timetag"}]},v2SyncSelfUserInfo:{sid:3,cid:109,service:Sn,response:[{type:"Property",name:"user",reflectMapper:invertSerializeItem(Cn)}]},v2SetP2PMessageMuteMode:{sid:34,cid:5,service:Sn,params:[{type:"String",name:"accountId"},{type:"Bool",name:"muteMode"}]},v2OnUpdateMuteList:{sid:3,cid:105,service:Sn,response:[{type:"String",name:"accountId"},{type:"Bool",name:"mute"}]}};class V2NIMUserModelImpl{constructor(){this.muteList=new Set,this.userMap=new Map,this.blockList=[]}reset(){this.muteList.clear(),this.userMap.clear(),this.blockList=[]}setAccountMuteMode(t,i){1===i?this.muteList.add(t):this.muteList.delete(t)}setUser(t){this.userMap.set(t.accountId,t)}getUser(t){return this.userMap.get(t)}getUserListBySearchOption(t){return Array.from(this.userMap.values()).filter((i=>!(void 0!==t.searchName&&!t.searchName||!i.name.includes(t.keyword))||(!(!t.searchAccountId||!i.accountId.includes(t.keyword))||!!(i.mobile&&t.searchMobile&&i.mobile.includes(t.keyword)))))}addToBlockList(t){t.forEach((t=>{this.blockList.includes(t)||this.blockList.push(t)}))}removeFromBlockList(t){t.forEach((t=>{var i=this.blockList.indexOf(t);-1!==i&&this.blockList.splice(i,1)}))}checkBlock(t){var i={};return t.forEach((t=>{i[t]=this.blockList.includes(t)})),i}}var An={type:"string",required:!0,allowEmpty:!1},On={type:"string",required:!1,allowEmpty:!0},Rn={name:{type:"string",required:!1,allowEmpty:!0},avatar:On,sign:On,email:On,birthday:On,mobile:On,gender:{type:"number",required:!1},serverExtension:On};class V2NIMUserServiceImpl extends V2Service{constructor(t){super("V2NIMUserService",t),registerParser({cmdMap:Tn,cmdConfig:Nn}),this.model=new V2NIMUserModelImpl,"v2"===this.core.options.apiVersion&&this.setListener()}reset(){this.model.reset()}setListener(){this.core.eventBus.on("forwardReceive/V2NIMUserService/updateBlockList",((t,i)=>{i?this.model.addToBlockList([t]):this.model.removeFromBlockList([t]),i?this.emitBlockListAdded(t):this.emit("onBlockListRemoved",t)})),this.core.eventBus.on("forwardReceive/V2NIMUserService/updateUserProfile",(t=>{this.updateUserProfileInMemory(t)}))}emit(t,...i){var o=`${this.name}::emit ${t.toString()}`;if("onUserProfileChanged"===t){var m=i[0];this.logger.log(`${o}`,m.map((t=>`id:${t.accountId};name:${t.name};updateTime:${t.updateTime}`)))}else if("onBlockListAdded"===t){var h=i[0];this.logger.log(`${o}`,`id:${h.accountId};name:${h.name};updateTime:${h.updateTime}`)}else this.logger.log(`${o}`,...i);return super.emit(t,...i)}getUserList(t){return __awaiter(this,void 0,void 0,(function*(){return this.checkV2(),this._getUserList(t)}))}_getUserList(t){var i;return __awaiter(this,void 0,void 0,(function*(){validate({accountIds:Xr},{accountIds:t},"",!0);var o=[];t.forEach((t=>{this.model.getUser(t)||o.push(t)}));var m=null;o.length>0&&(m=yield this.core.sendCmd("v2GetUserList",{accountIds:o})),((null===(i=null==m?void 0:m.content)||void 0===i?void 0:i.data)||[]).forEach((t=>{this.model.setUser(t)}));var h=[];return t.forEach((t=>{var i=this.model.getUser(t);i&&h.push(i)})),h}))}getUserListFromCloud(t){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate({accountIds:{type:"array",min:1,max:500,itemType:"string"}},{accountIds:t},"",!0);var i=(yield this.core.sendCmd("v2GetUserList",{accountIds:t})).content.data||[],o=[];i.forEach((t=>{var i=this.model.getUser(t.accountId);this.compareUserForUpdate(i,t)&&o.push(t),this.model.setUser(t)}));var m=t.reduce(((t,i)=>{var o=this.model.getUser(i);return o&&t.push(o),t}),[]);return o.length>0&&this.emit("onUserProfileChanged",o),m}))}compareUserForUpdate(t,i){return!t||!("number"==typeof t.updateTime&&"number"==typeof i.updateTime&&t.updateTime>=i.updateTime)}updateSelfUserProfile(t){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(Rn,t,"",!0);var i=yield this.core.sendCmd("v2UpdateSelfUserProfile",{tag:Object.assign(Object.assign({},t),{accountId:this.core.account})});yield this.updateUserProfileInMemory(Object.assign(Object.assign({},t),{updateTime:i.content.updateTime}))}))}addUserToBlockList(t){return __awaiter(this,void 0,void 0,(function*(){if(this.checkV2(),t===this.core.account)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"Cannot block yourself"}});validate({accountId:An},{accountId:t},"",!0),yield this.core.sendCmd("v2UpdateBlockList",{accountId:t,addToBlockList:!0}),this.model.addToBlockList([t]),this.emitBlockListAdded(t)}))}removeUserFromBlockList(t){return __awaiter(this,void 0,void 0,(function*(){if(this.checkV2(),t===this.core.account)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"Cannot unblock yourself"}});validate({accountId:An},{accountId:t},"",!0),yield this.core.sendCmd("v2UpdateBlockList",{accountId:t,addToBlockList:!1}),this.model.removeFromBlockList([t]),this.emit("onBlockListRemoved",t)}))}searchUserByOption(t){return __awaiter(this,void 0,void 0,(function*(){if(this.checkV2(),this.core.V2NIMLoginService.checkIllegalState(),validate({keyword:{type:"string",allowEmpty:!1},searchName:{type:"boolean",required:!1},searchAccountId:{type:"boolean",required:!1},searchMobile:{type:"boolean",required:!1}},t,"",!0),!1===(void 0===t.searchName||t.searchName)&&!t.searchAccountId&&!t.searchMobile)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"one of searchName, searchAccountId, searchMobile must be true"}});return this.model.getUserListBySearchOption(t)}))}getBlockList(){return this.checkV2(),Promise.resolve(this.model.blockList)}checkBlock(t){return this.checkV2(),validate({accountIds:Xr},{accountIds:t},"",!0),Promise.resolve(this.model.checkBlock(t))}updateUserProfileInMemory(t){return __awaiter(this,void 0,void 0,(function*(){var i=this.model.getUser(this.core.account);i?(Object.assign(i,t),this.model.setUser(i)):i=(yield this._getUserList([this.core.account]))[0];i&&this.emit("onUserProfileChanged",[i])}))}onUpdateUserProfileHandler(t){return __awaiter(this,void 0,void 0,(function*(){var i=t.content.data;yield this.updateUserProfileInMemory(i)}))}onUpdateBlockListHandler(t){var i=t.content.accountId;t.content.addToBlockList?(this.model.addToBlockList([i]),this.emitBlockListAdded(i)):(this.model.removeFromBlockList([i]),this.emit("onBlockListRemoved",i))}syncBlockAndMuteListHandler(t){t.content.data.forEach((t=>{t.isBlock?this.model.addToBlockList([t.accountId]):this.model.setAccountMuteMode(t.accountId,t.isMute?1:0)}))}v2SyncSelfUserInfoHandler(t){var i=t.content.user;this.model.setUser(i)}checkUserUpdate(t,i){var o=t.senderId;o!==this.core.account&&this.refreshUserInfo(o,i)}refreshUserInfo(t,i=0){return __awaiter(this,void 0,void 0,(function*(){if(t&&"string"==typeof t){var o=this.model.getUser(t),m=[];if(!o||o&&"number"==typeof o.updateTime&&"number"==typeof i&&!isNaN(o.updateTime)&&!isNaN(i)&&o.updateTime<i)try{m=(yield this.core.sendCmd("v2GetUserList",{accountIds:[t]})).content.data}catch(i){return void this.logger.warn(`V2NIMUserService:refreshUserInfo: failed for ${t}`)}for(var h of m)this.model.setUser(h),this.emit("onUserProfileChanged",[h])}}))}emitBlockListAdded(t){return __awaiter(this,void 0,void 0,(function*(){var i=yield this._getUserList([t]);1===i.length&&this.emit("onBlockListAdded",i[0])}))}v2OnUpdateMuteListHandler(t){return __awaiter(this,void 0,void 0,(function*(){var{accountId:i,mute:o}=t.content,m=o?1:0;this.core.eventBus.emit("v2NIMUserService/updateMuteList",i,m)}))}}var bn="V2NIMFriendService",Vn={"35_1":"v2AddFriend","35_2":"v2DeleteFriend","35_3":"v2SetFriendInfo","35_4":"v2IncFriendInfo","35_8":"v2FriendOperationDelete","35_9":"v2FriendOperationClear","12_108":"v2FriendOperationDeleteMultiSync","12_109":"v2FriendOperationClearMultiSync","12_101":"v2OnAddFriend","12_102":"v2OnDeleteFriend","12_103":"v2OnUpdateFriendInfo","12_5":"v2SyncFriendList","12_6":"v2SyncFriendUserList","12_107":"v2FriendOperationListSync","4_31":"v2FriendOperationListOnline","4_40":"v2FriendJoinActionClearSync"},kn={applicantAccountId:1,recipientAccountId:2,operatorAccountId:3,status:{id:4,retConverter:t=>{switch(t){case"1":return 4;case"2":return 0;case"3":return 1;case"4":return 2}}},timestamp:{id:6,retType:"number"},updateTimestamp:{id:7,retType:"number"},postscriptHistory:{id:8,retConverter:t=>{if(t&&"string"==typeof t)try{return JSON.parse(t).map((t=>({fromAccount:t.accid,time:t.time,content:t.msg})))}catch(t){return}}},serverId:9},Pn={serverId:1,serverTime:{id:2,retType:"number"}},Ln={serverTime:{id:1,retType:"number"}},wn={timestamp:{id:1,retType:"number"},type:{id:2,retType:"number"},serverTime:{id:3,retType:"number"}},Dn={accountId:4,relationShip:{id:5,retType:"number"},source:{id:7,retType:"number"},alias:8,serverExtension:10,createTime:{id:11,retType:"number"},updateTime:{id:12,retType:"number"},customerExtension:13},Un={v2AddFriend:{sid:35,cid:1,service:bn,params:[{type:"String",name:"accountId"},{type:"Byte",name:"verifyType"},{type:"String",name:"postscript"}],response:[]},v2DeleteFriend:{sid:35,cid:2,service:bn,params:[{type:"String",name:"accountId"},{type:"Property",name:"params",reflectMapper:{deleteAlias:{id:1,converter:boolToInt}}}]},v2SetFriendInfo:{sid:35,cid:3,service:bn,params:[{type:"Property",name:"tag",reflectMapper:Dn}]},v2OnAddFriend:{sid:12,cid:101,service:bn,response:[{type:"String",name:"accountId"},{type:"Byte",name:"verifyType"},{type:"String",name:"postscript"},{type:"Property",name:"ext",reflectMapper:invertSerializeItem({serverExt:1})}]},v2OnDeleteFriend:{sid:12,cid:102,service:bn,response:[{type:"String",name:"accountId"}]},v2OnUpdateFriendInfo:{sid:12,cid:103,service:bn,response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Dn)}]},v2SyncFriendList:{sid:12,cid:5,service:bn,response:[{type:"PropertyArray",name:"friends",reflectMapper:invertSerializeItem(Dn)},{type:"Long",name:"timetag"}]},v2SyncFriendUserList:{sid:12,cid:6,service:bn,response:[{type:"PropertyArray",name:"users",reflectMapper:invertSerializeItem(Cn)}]},v2IncFriendInfo:{sid:35,cid:4,service:bn,params:[{type:"Long",name:"timetag"}],response:[{type:"PropertyArray",name:"friends",reflectMapper:invertSerializeItem(Dn)},{type:"Long",name:"timetag"}]},v2FriendOperationListSync:{sid:12,cid:107,service:bn,response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(kn)},{type:"Long",name:"serverTime"}]},v2FriendOperationListOnline:{sid:4,cid:31,service:bn,response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(kn)}]},v2FriendOperationDelete:{sid:35,cid:8,service:bn,params:[{type:"Property",name:"tag",reflectMapper:Pn}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Ln)}]},v2FriendOperationDeleteMultiSync:{sid:12,cid:108,service:bn,response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Pn)}]},v2FriendOperationClearMultiSync:{sid:12,cid:109,service:bn,response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(wn)}]},v2FriendOperationClear:{sid:35,cid:9,service:bn,params:[{type:"Property",name:"tag",reflectMapper:wn}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Ln)}]},v2FriendJoinActionClearSync:{sid:4,cid:40,service:bn,response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(kn)},{type:"PropertyArray",name:"clearInfos",reflectMapper:invertSerializeItem(wn)},{type:"Long",name:"serverTime"}]}},xn={accountId:{type:"string",required:!0,allowEmpty:!1},params:{type:"object",required:!0,rules:{addMode:{type:"enum",required:!0,values:[1,2]},postscript:{type:"string",required:!1,allowEmpty:!0}}}},Fn={accountId:{type:"string",required:!0,allowEmpty:!1},params:{type:"object",required:!1,rules:{deleteAlias:{type:"boolean",required:!1}}}},Bn={accountId:{type:"string",required:!0,allowEmpty:!1},params:{type:"object",required:!1,rules:{alias:{type:"string",required:!1,allowEmpty:!0},serverExtension:{type:"string",required:!1,allowEmpty:!0}}}},$n={applicantAccountId:{type:"string",allowEmpty:!1},recipientAccountId:{type:"string",allowEmpty:!1},operatorAccountId:{type:"string",required:!1,allowEmpty:!1},postscript:{type:"string",required:!1,allowEmpty:!0},status:{type:"enum",values:[1,4,3,0,2]},timestamp:{type:"number",min:1},serverId:{type:"string",required:!1}};function checkApplication(t,i){if(validate($n,t,"",!0),t&&t.applicantAccountId!==i&&t.recipientAccountId!==i)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"Friend application is not your own"}})}var jn={offset:{type:"number",required:!1},limit:{type:"number",required:!1},status:{type:"array",itemType:"enum",required:!1,values:[1,4,3,0,2]}};class V2NIMFriendNotificationImpl{constructor(t,i){this.core=t,this.service=i}processSysNotification(t){if(6===t.type){var i=t.senderId;this.core.V2NIMFriendService.handleDeleteFriend(i,2)}else if(5===t.type&&!this.service.config.enableServerV2FriendAddApplication)try{var o=JSON.parse(t.content);if(1===(null==o?void 0:o.vt)){this.core.V2NIMFriendService.handleAddFriend(t.senderId);var m={applicantAccountId:t.senderId,recipientAccountId:t.receiverId,operatorAccountId:t.senderId,postscript:t.postscript,serverId:"",timestamp:t.timestamp,updateTimestamp:t.timestamp,status:4,read:!1};this.service.notificationModelOld.appendFriendAddApplication(m),this.service.notificationModelOld.updateFriendAddApplicationStatus(m.applicantAccountId,4,m.applicantAccountId)}else if(2===(null==o?void 0:o.vt)){var h={applicantAccountId:t.senderId,recipientAccountId:t.receiverId,operatorAccountId:t.senderId,postscript:t.postscript,timestamp:t.timestamp,serverId:"",updateTimestamp:t.timestamp,status:0,read:!1};this.service.handleApplyFriend(h),this.service.notificationModelOld.appendFriendAddApplication(h)}else if(3===(null==o?void 0:o.vt)){this.core.V2NIMFriendService.handleAddFriend(t.senderId);var u={applicantAccountId:t.receiverId,recipientAccountId:t.senderId,operatorAccountId:t.senderId,timestamp:t.timestamp,serverId:"",updateTimestamp:t.timestamp,postscript:t.postscript,status:1,read:!1};this.service.notificationModelOld.appendFriendAddApplication(u)}else if(4===(null==o?void 0:o.vt)){var v={applicantAccountId:t.receiverId,recipientAccountId:t.senderId,operatorAccountId:t.senderId,timestamp:t.timestamp,serverId:"",updateTimestamp:t.timestamp,postscript:t.postscript,status:2,read:!1};this.service.notificationModelOld.appendFriendAddApplication(v),this.service.emit("onFriendAddRejected",v)}}catch(t){this.core.logger.warn("V2NIMFriendNotificationImpl::processSysNotification, parse content error:",t)}}setSyncTimestamp(t){t&&this.core.eventBus.emit("V2NIMSync/updateTimetag",{friendOperatorList:t,friendApplyInfoDeleteOrClear:t})}}class V2NIMFriendModelImpl{constructor(){this.validFriendIds=new Set,this.friendMap=new Map,this.friendTimetag=0}reset(){this.friendMap.clear(),this.validFriendIds.clear()}upsertFriend(t,i){delete i.relationShip;var o=this.friendMap.get(t)||{},m=Object.assign({accountId:t},o,i);return this.friendMap.set(t,m),this.validFriendIds.add(t),m}addFriend(t){this.validFriendIds.add(t)}deleteFriend(t){this.validFriendIds.delete(t)}getFriend(t){return this.validFriendIds.has(t)?this.friendMap.get(t):void 0}getFriendList(){return Array.from(this.validFriendIds.values()).map((t=>this.getFriend(t))).filter((t=>!!t))}getFriendListBySearchOption(t){return Array.from(this.validFriendIds.values()).map((t=>this.getFriend(t))).filter((i=>{var o=void 0===t.searchAlias||t.searchAlias;return void 0!==i&&(!!(o&&i.alias&&i.alias.includes(t.keyword))||!(!t.searchAccountId||!i.accountId.includes(t.keyword)))}))}getFriendByIds(t){return t.map((t=>this.getFriend(t))).filter((t=>!!t))}setFriendTimetag(t){this.friendTimetag=t}getFriendTimetag(){return this.friendTimetag}}var Gn="NIM_FRIEND_OPERATION_READ_TIME_{ACCOUNT_ID}";class V2NIMFriendNotificationModelImpl{constructor(){this.datas=new Map,this.readTime=0,this.prefix=Gn,this.maxCount=1e3}reset(){this.datas.clear()}setReadTimePrefix(t){this.prefix=Gn.replace("{ACCOUNT_ID}",t),this.readTime=Number(Re.localStorage.getItem(this.prefix))||0,this.readTime>0&&this.datas.forEach((t=>{t.updateTimestamp<=this.readTime&&(t.read=!0)}))}getReadTime(){return this.readTime}getByOption(t,i){var o=void 0===t.offset?0:t.offset,m=Array.from(this.datas.values()).sort(((t,i)=>i.updateTimestamp-t.updateTimestamp));t.status&&t.status.length>0&&(m=m.filter((i=>{var o;return null===(o=t.status)||void 0===o?void 0:o.includes(i.status)})));var h=t.type?t.type:0;m=m.filter((t=>0===h?t.operatorAccountId!==i:1===h?t.applicantAccountId===i:2!==h||t.recipientAccountId===i));var u=t.limit||50,v=m.slice(o,o+u),I=o+u>=m.length;return{infos:v,finished:I,offset:I?0:o+u}}setAllRead(){var t=0;this.datas.forEach((i=>{i.read=!0,t=Math.max(t,i.updateTimestamp)})),t&&(this.readTime=t,Re.localStorage.setItem(this.prefix,t.toString()))}setRead(t){var i=this.datas.get(t.serverId);i&&i.updateTimestamp&&(this.datas.forEach((t=>{t.updateTimestamp<=i.updateTimestamp&&(t.read=!0)})),this.readTime=i.updateTimestamp,Re.localStorage.setItem(this.prefix,i.updateTimestamp.toString()))}getUnreadCount(){var t=0;return this.datas.forEach((i=>{i.read||t++})),t}delete(t){this.datas.delete(t)}deleteByOption(t,i){var o=t.timestamp,m=t.type;this.datas.forEach((t=>{t.updateTimestamp<=o&&(3===m||1===m&&t.applicantAccountId===i||2===m&&t.recipientAccountId===i)&&this.datas.delete(t.serverId)}))}upsert(t){t.serverId&&this.setLRU(t.serverId,t)}setLRU(t,i){if(this.datas.has(t))this.datas.delete(t);else if(this.datas.size>=this.maxCount){var o=this.datas.keys().next().value;o&&this.datas.delete(o)}this.datas.set(t,i)}clear(){this.datas.clear()}updateStatus(t,i){if(0!==i){var o=this.datas.get(t);o&&0===o.status&&(o.status=i,this.datas.set(t,o))}}getById(t){return this.datas.get(t)}}class V2NIFriendEventImpl{constructor(t,i){this.core=t,this.service=i,this.logger=this.core.logger}setListener(){this.core.eventBus.on("V2NIMFriendService/sysNotification",this.service.notification.processSysNotification.bind(this.service.notification)),this.core.eventBus.on("V2NIMLoginService/loginLifeCycleLoginSucc",this.setOperationReadTime.bind(this))}beforeEmit(t,...i){var o=`${this.service.name}::emit ${t.toString()}`;if("onFriendAdded"===t||"onFriendInfoChanged"===t){var m=i[0];this.logger.log(`${o}`,`${m.accountId};updateTime:${m.updateTime}`)}else this.logger.log(`${o}`,...i)}setOperationReadTime(){this.service.notificationModel.setReadTimePrefix(this.core.account)}}function completeFriendOperation(t,i,o,m){return t.updateTimestamp<=i?t.read=!0:0!==t.status&&4!==t.status||t.applicantAccountId!==o?(m&&0===m.status&&t.status,t.read=!1):t.read=!0,t.postscriptHistory&&t.postscriptHistory.length>0&&(t.postscript=t.postscriptHistory[t.postscriptHistory.length-1].content),t}class V2NIMMFriendHandlerImpl{constructor(t,i){this.core=t,this.service=i,this.model=i.model,this.notificationModel=i.notificationModel,this.notificationModelOld=i.notificationModelOld,this.logger=this.core.logger}get useServerNotification(){return this.service.config.enableServerV2FriendAddApplication}v2OnAddFriendHandler(t){if(!this.useServerNotification){var{accountId:i,verifyType:o,postscript:m}=t.content;if(1===o)this.service.handleAddFriend(i),this.notificationModelOld.updateFriendAddApplicationStatus(i,4,this.core.account);else if(2===o){var h={applicantAccountId:this.core.account,recipientAccountId:i,operatorAccountId:this.core.account,postscript:m,timestamp:this.core.timeOrigin.getNTPTime(),updateTimestamp:this.core.timeOrigin.getNTPTime(),serverId:"",status:0,read:!1};this.service.handleApplyFriend(h)}else if(3===o)this.service.handlePassFriendApply(i);else if(4===o){var u={applicantAccountId:i,recipientAccountId:this.core.account,operatorAccountId:this.core.account,postscript:m,timestamp:this.core.timeOrigin.getNTPTime(),serverId:"",updateTimestamp:this.core.timeOrigin.getNTPTime(),status:2,read:!1};this.service.handleRejectFriendApply(u)}}}v2OnDeleteFriendHandler(t){var{accountId:i}=t.content;this.service.handleDeleteFriend(i)}v2OnUpdateFriendInfoHandler(t){var{data:i}=t.content,o=this.model.upsertFriend(i.accountId,i);this.service.emit("onFriendInfoChanged",this.service.computedField(o))}v2SyncFriendListHandler(t){var{friends:i,timetag:o}=t.content;this.model.setFriendTimetag(o),i.forEach((t=>{t.serverExtension||(t.serverExtension=""),t.customerExtension||(t.customerExtension=""),0===t.relationShip?this.model.deleteFriend(t.accountId):this.model.upsertFriend(t.accountId,t)}))}v2SyncFriendUserListHandler(t){var{users:i}=t.content;this.hasUserService&&i.forEach((t=>{this.core.V2NIMUserService.model.setUser(t)}))}v2FriendOperationListSyncHandler(t){if(this.useServerNotification){var i=t.content.datas,o=t.content.serverTime,m=this.notificationModel.getReadTime();i.map((t=>completeFriendOperation(t,m,this.core.account))).forEach((t=>{var i=this.notificationModel.getById(t.serverId);i&&i.status!==t.status?this.triggerEventFromOperation(t):i||!1!==t.read||0!==t.status||this.triggerEventFromOperation(t),this.notificationModel.upsert(t)})),this.service.notification.setSyncTimestamp(o)}}v2FriendOperationListOnlineHandler(t){if(this.useServerNotification){var i=t.content.data,o=this.notificationModel.getReadTime(),m=this.notificationModel.getById(i.serverId),h=completeFriendOperation(i,o,this.core.account,m);this.notificationModel.upsert(h),this.triggerEventFromOperation(h),this.service.notification.setSyncTimestamp(h.updateTimestamp)}}triggerEventFromOperation(t){var i=this.core.account;0===t.status&&t.operatorAccountId!==i?this.service.emit("onFriendAddApplication",t):2===t.status&&t.operatorAccountId!==i?this.service.emit("onFriendAddRejected",t):(1===t.status||4===t.status)&&this.service.handleAddFriend(t.applicantAccountId===this.core.account?t.recipientAccountId:t.applicantAccountId)}get hasUserService(){var t;return!!(null===(t=this.core.V2NIMUserService)||void 0===t?void 0:t.name)}v2FriendOperationDeleteMultiSyncHandler(t){if(this.useServerNotification){var i=t.content.data,o=i.serverTime;this.notificationModel.delete(i.serverId),this.service.notification.setSyncTimestamp(o)}}v2FriendOperationClearMultiSyncHandler(t){if(this.useServerNotification){var i=t.content.data,o=i.serverTime;this.notificationModel.deleteByOption({timestamp:i.timestamp,type:i.type},this.core.account),this.service.notification.setSyncTimestamp(o)}}v2FriendJoinActionClearSyncHandler(t){t.content.datas.forEach((t=>{this.notificationModel.delete(t.serverId),this.notificationModelOld.deleteApplication(t)})),t.content.clearInfos.forEach((t=>{var i=t.timestamp,o=t.type,m={timestamp:i||this.core.timeOrigin.getNTPTime(),type:o||3};this.notificationModel.deleteByOption(m,this.core.account),this.notificationModelOld.deleteByOption(m,this.core.account)}));var i=t.content.serverTime;this.service.notification.setSyncTimestamp(i)}}class V2NIMFriendNotificationModelOldImpl{constructor(){this.list=[],this.maxCount=1e3}reset(){this.list=[]}updateFriendAddApplicationStatus(t,i,o){if(0!==i)for(var m of this.list)m.applicantAccountId===t&&0===m.status&&(m.status=i,m.operatorAccountId=o)}getAddApplicationList(t){var i=void 0===t.offset?0:t.offset,o=this.list.filter((i=>{var o=t.status||[];return 0===o.length||!!o.includes(i.status)})).reverse(),m=t.limit||50,h=o.slice(i,i+m),u=i+m>=o.length;return{infos:h,finished:u,offset:u?0:i+m}}checkSameApplication(t,i,o=!1){return t.applicantAccountId===i.applicantAccountId&&t.recipientAccountId===i.recipientAccountId&&(!o||t.timestamp===i.timestamp)}setAllApplicationRead(){for(var t of this.list)t.read=!0}setApplicationRead(t){for(var i of this.list)this.checkSameApplication(i,t)&&(i.read=!0)}getAddApplicationUnreadCount(){var t=new Set;for(var i of this.list)i.read||0!==i.status||t.add(i.applicantAccountId);return t.size}appendFriendAddApplication(t){this.list.push(t),this.list.length>this.maxCount&&this.list.shift()}clearApplicationList(){this.list=[]}deleteApplication(t){this.list=this.list.map((i=>{if(!this.checkSameApplication(i,t,!1))return i})).filter((t=>t))}deleteByOption(t,i){var o=t.timestamp,m=t.type;this.list=this.list.filter((t=>!(t.timestamp<=o&&(3===m||1===m&&t.applicantAccountId===i||2===m&&t.recipientAccountId===i))))}}class V2NIMFriendServiceImpl extends V2Service{constructor(t){super("V2NIMFriendService",t),this.config={enableServerV2FriendAddApplication:!1},this.notification=new V2NIMFriendNotificationImpl(this.core,this),this.model=new V2NIMFriendModelImpl,this.notificationModel=new V2NIMFriendNotificationModelImpl,this.notificationModelOld=new V2NIMFriendNotificationModelOldImpl,this.event=new V2NIFriendEventImpl(this.core,this),this.handler=new V2NIMMFriendHandlerImpl(this.core,this),this.core._registerDep(V2NIMUserServiceImpl,"V2NIMUserService"),"v2"===this.core.options.apiVersion&&(registerParser({cmdMap:Vn,cmdConfig:Un}),this.setListener())}reset(){this.model.reset(),this.notificationModel.reset(),this.notificationModelOld.reset()}setListener(){this.event.setListener()}setOptions(t){this.config=Object.assign(this.config,t)}emit(t,...i){return this.event.beforeEmit(t,...i),super.emit(t,...i)}addFriend(t,i){return __awaiter(this,void 0,void 0,(function*(){if(this.checkV2(),t===this.core.account)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"Cannot add yourself"}});validate(xn,{accountId:t,params:i},"",!0),yield this.core.sendCmd("v2AddFriend",{accountId:t,verifyType:i.addMode,postscript:i.postscript||""}),1===i.addMode&&(yield this.handleAddFriend(t),this.notificationModelOld.updateFriendAddApplicationStatus(t,4,this.core.account))}))}deleteFriend(t,i){return __awaiter(this,void 0,void 0,(function*(){if(this.checkV2(),t===this.core.account)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"Cannot delete yourself"}});validate(Fn,{accountId:t,params:i},"",!0),yield this.core.sendCmd("v2DeleteFriend",{accountId:t,params:i}),i.deleteAlias&&this.model.upsertFriend(t,{alias:""}),this.handleDeleteFriend(t)}))}acceptAddApplication(t){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),checkApplication(t,this.core.account);try{yield this.core.sendCmd("v2AddFriend",{accountId:t.applicantAccountId,verifyType:3,postscript:""}),this.handlePassFriendApply(t.applicantAccountId)}catch(i){throw this.handlePassFriendApply(t.applicantAccountId,i),i}}))}rejectAddApplication(t,i){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),checkApplication(t,this.core.account);try{yield this.core.sendCmd("v2AddFriend",{accountId:t.applicantAccountId,verifyType:4,postscript:i||""}),this.handleRejectFriendApply(Object.assign(Object.assign({},t),{postscript:i||"",operatorAccountId:this.core.account,updateTimestamp:this.core.timeOrigin.getNTPTime(),read:!1,status:2}))}catch(o){throw this.handleRejectFriendApply({applicantAccountId:t.applicantAccountId,recipientAccountId:t.recipientAccountId,operatorAccountId:this.core.account,postscript:i||"",serverId:"",timestamp:this.core.timeOrigin.getNTPTime(),updateTimestamp:this.core.timeOrigin.getNTPTime(),read:!1,status:3},o),o}}))}setFriendInfo(t,i){return __awaiter(this,void 0,void 0,(function*(){if(this.checkV2(),validate(Bn,{accountId:t,params:i},"",!0),t===this.core.account)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"Cannot set yourself"}});yield this.core.sendCmd("v2SetFriendInfo",{tag:Object.assign({accountId:t},i)}),this.handleSetFriendInfo(t,i)}))}getFriendList(){return __awaiter(this,void 0,void 0,(function*(){return this.checkV2(),this.core.V2NIMLoginService.checkIllegalState(),this.computedFields(this.model.getFriendList())}))}getFriendByIds(t){return __awaiter(this,void 0,void 0,(function*(){return this.checkV2(),this.core.V2NIMLoginService.checkIllegalState(),validate({accountIds:{type:"array",itemType:"string",required:!0,min:1}},{accountIds:t},"",!0),this.computedFields(this.model.getFriendByIds(t))}))}checkFriend(t){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),this.core.V2NIMLoginService.checkIllegalState(),validate({accountIds:{type:"array",itemType:"string",required:!0,min:1}},{accountIds:t},"",!0);var i={};return t.forEach((t=>{i[t]=!!this.model.getFriend(t)})),i}))}getAddApplicationList(t){return __awaiter(this,void 0,void 0,(function*(){return this.checkV2(),this.core.V2NIMLoginService.checkIllegalState(),validate(jn,t,"",!0),this.config.enableServerV2FriendAddApplication?this.notificationModel.getByOption(t,this.core.account):this.notificationModelOld.getAddApplicationList(t)}))}setAddApplicationRead(){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),this.core.V2NIMLoginService.checkIllegalState(),this.notificationModel.setAllRead(),this.notificationModelOld.setAllApplicationRead()}))}setAddApplicationReadEx(t){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),this.core.V2NIMLoginService.checkIllegalState(),t?(checkApplication(t,this.core.account),this.notificationModel.setRead(t),this.notificationModelOld.setApplicationRead(t)):(this.notificationModel.setAllRead(),this.notificationModelOld.setAllApplicationRead())}))}getAddApplicationUnreadCount(){return __awaiter(this,void 0,void 0,(function*(){return this.checkV2(),this.core.V2NIMLoginService.checkIllegalState(),this.config.enableServerV2FriendAddApplication?this.notificationModel.getUnreadCount():this.notificationModelOld.getAddApplicationUnreadCount()}))}clearAllAddApplication(){var t;return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),this.core.V2NIMLoginService.checkIllegalState();var i=yield this.core.sendCmd("v2FriendOperationClear",{tag:{}}),o=null===(t=i.content.data)||void 0===t?void 0:t.serverTime;o&&this.core.eventBus.emit("V2NIMSync/updateTimetag",{friendOperatorList:o,friendApplyInfoDeleteOrClear:o}),this.notificationModel.clear(),this.notificationModelOld.clearApplicationList()}))}clearAllAddApplicationEx(t){var i;return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),this.core.V2NIMLoginService.checkIllegalState(),validate({timestamp:{type:"number",required:!1},type:{type:"enum",values:[1,2,3],required:!1}},t,"",!0);var o=yield this.core.sendCmd("v2FriendOperationClear",{tag:t}),m=null===(i=o.content.data)||void 0===i?void 0:i.serverTime;m&&this.core.eventBus.emit("V2NIMSync/updateTimetag",{friendOperatorList:m,friendApplyInfoDeleteOrClear:m});var h={timestamp:"number"==typeof(null==t?void 0:t.timestamp)?t.timestamp:this.core.timeOrigin.getNTPTime(),type:"number"==typeof(null==t?void 0:t.type)?t.type:3};this.notificationModel.deleteByOption(h,this.core.account),this.notificationModelOld.deleteByOption(h,this.core.account)}))}deleteAddApplication(t){var i;return __awaiter(this,void 0,void 0,(function*(){if(this.checkV2(),this.core.V2NIMLoginService.checkIllegalState(),checkApplication(t,this.core.account),t.serverId){var o=yield this.core.sendCmd("v2FriendOperationDelete",{tag:{serverId:t.serverId}});this.notification.setSyncTimestamp(null===(i=o.content.data)||void 0===i?void 0:i.serverTime)}this.notificationModel.delete(t.serverId),this.notificationModelOld.deleteApplication(t)}))}searchFriendByOption(t){return __awaiter(this,void 0,void 0,(function*(){if(this.checkV2(),this.core.V2NIMLoginService.checkIllegalState(),validate({keyword:{type:"string",allowEmpty:!1},searchAccountId:{type:"boolean",required:!1}},t,"",!0),!(void 0===t.searchAlias||t.searchAlias)&&!t.searchAccountId)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"searchAlias and searchAccountId cannot be false at the same time"}});return this.computedFields(this.model.getFriendListBySearchOption(t))}))}handleApplyFriend(t){this.emit("onFriendAddApplication",t)}handleAddFriend(t){return __awaiter(this,void 0,void 0,(function*(){this.model.addFriend(t),yield this.incrementSyncFriend(),yield this.core.V2NIMUserService.refreshUserInfo(t);var i=this.model.getFriend(t);i&&this.emit("onFriendAdded",this.computedField(i))}))}handleDeleteFriend(t,i){i=void 0===i?1:i,this.emit("onFriendDeleted",t,i),this.model.deleteFriend(t)}handleSetFriendInfo(t,i){var o=this.model.upsertFriend(t,i);this.emit("onFriendInfoChanged",this.computedField(o))}handlePassFriendApply(t,i){if(!this.config.enableServerV2FriendAddApplication){var o=i?null==i?void 0:i.code:200;if(!(o>=19e4||o===Ee.V2NIM_ERROR_CODE_FRIEND_OPERATION_RATE_LIMIT))if(200===o||o===Ee.V2NIM_ERROR_CODE_FRIEND_ALREADY_EXIST)this.notificationModelOld.updateFriendAddApplicationStatus(t,1,this.core.account),this.handleAddFriend(t);else{if(o>=500&&o<=599&&509!==o)return;this.notificationModelOld.updateFriendAddApplicationStatus(t,3,this.core.account)}}}handleRejectFriendApply(t,i){if(!this.config.enableServerV2FriendAddApplication){var o=i?null==i?void 0:i.code:200;if(!(o>=19e4||o===Ee.V2NIM_ERROR_CODE_FRIEND_OPERATION_RATE_LIMIT))if(200===o)this.emit("onFriendAddRejected",t),this.notificationModelOld.updateFriendAddApplicationStatus(t.applicantAccountId,2,this.core.account);else if(o===Ee.V2NIM_ERROR_CODE_FRIEND_ALREADY_EXIST)this.notificationModelOld.updateFriendAddApplicationStatus(t.applicantAccountId,1,this.core.account);else{if(o>=500&&o<=599&&509!==o)return;this.notificationModelOld.updateFriendAddApplicationStatus(t.applicantAccountId,3,this.core.account)}}}incrementSyncFriend(){return __awaiter(this,void 0,void 0,(function*(){var t=yield this.core.sendCmd("v2IncFriendInfo",{timetag:this.model.getFriendTimetag()}),{friends:i,timetag:o}=t.content;this.model.setFriendTimetag(o),i.forEach((t=>{this.model.upsertFriend(t.accountId,t)}))}))}computedFields(t){return t.map((t=>this.computedField(t)))}computedField(t){var i,o,m=null===(o=null===(i=this.core.V2NIMUserService)||void 0===i?void 0:i.model)||void 0===o?void 0:o.getUser(t.accountId);return m?Object.assign({},t,{userProfile:m}):t}}var qn={muteMode:{type:"enum",values:[2,0,1]}},Hn={accountId:{type:"string",required:!0,allowEmpty:!1},muteMode:{type:"enum",required:!0,values:[2,0,1]}},zn={type:"object",required:!1,rules:{certificateName:{type:"string",required:!0,allowEmpty:!1},appId:{type:"string",required:!1,allowEmpty:!1},appKey:{type:"string",required:!1,allowEmpty:!1},secret:{type:"string",required:!1,allowEmpty:!1}}},Yn={config:{type:"object",required:!0,rules:{apns:zn,hwPush:zn,miPush:zn,vivoPush:zn,oppoPush:zn,honorPush:zn,fcmPush:zn,mzPush:zn}}},Jn="V2NIMSettingService",Kn={"34_1":"v2SetDeviceToken","34_2":"v2SetAppBackground","34_15":"v2SetPushMobileOnDesktopOnline","3_115":"v2SettingMutilSyncDonnop","4_13":"v2SettingSyncDonnop"},Wn={need:{id:1,converter:t=>t?2:1,retConverter:t=>"2"===t}},Xn={v2SetDeviceToken:{sid:34,cid:1,service:Jn,params:[{type:"String",name:"certificateName"},{type:"String",name:"pushDeviceToken"},{type:"Int",name:"pushkit"}]},v2SetAppBackground:{sid:34,cid:2,service:Jn,params:[{type:"Bool",name:"isBackground"},{type:"Int",name:"badge"}]},v2SetPushMobileOnDesktopOnline:{sid:34,cid:15,service:Jn,params:[{type:"Property",name:"tag",reflectMapper:Wn}]},v2SettingMutilSyncDonnop:{sid:3,cid:115,service:Jn,response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Wn)},{type:"Long",name:"timetag"}]},v2SettingSyncDonnop:{sid:4,cid:13,service:Jn,response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Wn)},{type:"Long",name:"timetag"}]}};class V2NIMSettingHandlerImpl{constructor(t,i){this.core=t,this.service=i}v2SettingMutilSyncDonnopHandler(t){var{need:i}=t.content.data;this.service.needToPushMobileOnDesktopOnline=i,this.service.emit("onPushMobileOnDesktopOnline",i)}v2SettingSyncDonnopHandler(t){var{need:i}=t.content.data;this.service.needToPushMobileOnDesktopOnline=i,this.service.emit("onPushMobileOnDesktopOnline",i)}}var Qn=Qn||function(t){var i;"undefined"!=typeof window&&window.crypto&&(i=window.crypto),"undefined"!=typeof self&&self.crypto&&(i=self.crypto),"undefined"!=typeof globalThis&&globalThis.crypto&&(i=globalThis.crypto),!i&&"undefined"!=typeof window&&window.msCrypto&&(i=window.msCrypto),!i&&"undefined"!=typeof global&&global.crypto&&(i=global.crypto);var cryptoSecureRandomInt=function(){if(i){if("function"==typeof i.getRandomValues)try{return i.getRandomValues(new Uint32Array(1))[0]}catch(t){}if("function"==typeof i.randomBytes)try{return i.randomBytes(4).readInt32LE()}catch(t){}}throw new Error("Native crypto module could not be used to get secure random number.")},o=Object.create||function(){function F(){}return function(t){var i;return F.prototype=t,i=new F,F.prototype=null,i}}(),m={},h=m.lib={},u=h.Base={extend:function(t){var i=o(this);return t&&i.mixIn(t),i.hasOwnProperty("init")&&this.init!==i.init||(i.init=function(){i.$super.init.apply(this,arguments)}),i.init.prototype=i,i.$super=this,i},create:function(){var t=this.extend();return t.init.apply(t,arguments),t},init:function(){},mixIn:function(t){for(var i in t)t.hasOwnProperty(i)&&(this[i]=t[i]);t.hasOwnProperty("toString")&&(this.toString=t.toString)},clone:function(){return this.init.prototype.extend(this)}},v=h.WordArray=u.extend({init:function(t,i){t=this.words=t||[],this.sigBytes=null!=i?i:4*t.length},toString:function(t){return(t||_).stringify(this)},concat:function(t){var i=this.words,o=t.words,m=this.sigBytes,h=t.sigBytes;if(this.clamp(),m%4)for(var u=0;u<h;u++){var v=o[u>>>2]>>>24-u%4*8&255;i[m+u>>>2]|=v<<24-(m+u)%4*8}else for(var I=0;I<h;I+=4)i[m+I>>>2]=o[I>>>2];return this.sigBytes+=h,this},clamp:function(){var i=this.words,o=this.sigBytes;i[o>>>2]&=4294967295<<32-o%4*8,i.length=t.ceil(o/4)},clone:function(){var t=u.clone.call(this);return t.words=this.words.slice(0),t},random:function(t){for(var i=[],o=0;o<t;o+=4)i.push(cryptoSecureRandomInt());return new v.init(i,t)}}),I=m.enc={},_=I.Hex={stringify:function(t){for(var i=t.words,o=t.sigBytes,m=[],h=0;h<o;h++){var u=i[h>>>2]>>>24-h%4*8&255;m.push((u>>>4).toString(16)),m.push((15&u).toString(16))}return m.join("")},parse:function(t){for(var i=t.length,o=[],m=0;m<i;m+=2)o[m>>>3]|=parseInt(t.substr(m,2),16)<<24-m%8*4;return new v.init(o,i/2)}},M=I.Latin1={stringify:function(t){for(var i=t.words,o=t.sigBytes,m=[],h=0;h<o;h++){var u=i[h>>>2]>>>24-h%4*8&255;m.push(String.fromCharCode(u))}return m.join("")},parse:function(t){for(var i=t.length,o=[],m=0;m<i;m++)o[m>>>2]|=(255&t.charCodeAt(m))<<24-m%4*8;return new v.init(o,i)}},E=I.Utf8={stringify:function(t){try{return decodeURIComponent(escape(M.stringify(t)))}catch(t){throw new Error("Malformed UTF-8 data")}},parse:function(t){return M.parse(unescape(encodeURIComponent(t)))}},S=h.BufferedBlockAlgorithm=u.extend({reset:function(){this._data=new v.init,this._nDataBytes=0},_append:function(t){"string"==typeof t&&(t=E.parse(t)),this._data.concat(t),this._nDataBytes+=t.sigBytes},_process:function(i){var o,m=this._data,h=m.words,u=m.sigBytes,I=this.blockSize,_=u/(4*I),M=(_=i?t.ceil(_):t.max((0|_)-this._minBufferSize,0))*I,E=t.min(4*M,u);if(M){for(var S=0;S<M;S+=I)this._doProcessBlock(h,S);o=h.splice(0,M),m.sigBytes-=E}return new v.init(o,E)},clone:function(){var t=u.clone.call(this);return t._data=this._data.clone(),t},_minBufferSize:0});h.Hasher=S.extend({cfg:u.extend(),init:function(t){this.cfg=this.cfg.extend(t),this.reset()},reset:function(){S.reset.call(this),this._doReset()},update:function(t){return this._append(t),this._process(),this},finalize:function(t){return t&&this._append(t),this._doFinalize()},blockSize:16,_createHelper:function(t){return function(i,o){return new t.init(o).finalize(i)}},_createHmacHelper:function(t){return function(i,o){return new T.HMAC.init(t,o).finalize(i)}}});var T=m.algo={};return m}(Math),Zn=Qn.enc.Utf8,eo=Qn,io=eo.lib,ro=io.Base,no=io.WordArray,oo=eo.algo,so=oo.MD5,ao=oo.EvpKDF=ro.extend({cfg:ro.extend({keySize:4,hasher:so,iterations:1}),init:function(t){this.cfg=this.cfg.extend(t)},compute:function(t,i){for(var o,m=this.cfg,h=m.hasher.create(),u=no.create(),v=u.words,I=m.keySize,_=m.iterations;v.length<I;){o&&h.update(o),o=h.update(t).finalize(i),h.reset();for(var M=1;M<_;M++)o=h.finalize(o),h.reset();u.concat(o)}return u.sigBytes=4*I,u}});eo.EvpKDF=function(t,i,o){return ao.create(o).compute(t,i)},Qn.EvpKDF;var co=Qn,lo=co.lib.WordArray;co.enc.Base64={stringify:function(t){var i=t.words,o=t.sigBytes,m=this._map;t.clamp();for(var h=[],u=0;u<o;u+=3)for(var v=(i[u>>>2]>>>24-u%4*8&255)<<16|(i[u+1>>>2]>>>24-(u+1)%4*8&255)<<8|i[u+2>>>2]>>>24-(u+2)%4*8&255,I=0;I<4&&u+.75*I<o;I++)h.push(m.charAt(v>>>6*(3-I)&63));var _=m.charAt(64);if(_)for(;h.length%4;)h.push(_);return h.join("")},parse:function(t){var i=t.length,o=this._map,m=this._reverseMap;if(!m){m=this._reverseMap=[];for(var h=0;h<o.length;h++)m[o.charCodeAt(h)]=h}var u=o.charAt(64);if(u){var v=t.indexOf(u);-1!==v&&(i=v)}return function parseLoop(t,i,o){for(var m=[],h=0,u=0;u<i;u++)if(u%4){var v=o[t.charCodeAt(u-1)]<<u%4*2|o[t.charCodeAt(u)]>>>6-u%4*2;m[h>>>2]|=v<<24-h%4*8,h++}return lo.create(m,h)}(t,i,m)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="},Qn.enc.Base64,function(t){t.lib.Cipher||function(){var i=t,o=i.lib,m=o.Base,h=o.WordArray,u=o.BufferedBlockAlgorithm,v=i.enc;v.Utf8;var I=v.Base64,_=i.algo.EvpKDF,M=o.Cipher=u.extend({cfg:m.extend(),createEncryptor:function(t,i){return this.create(this._ENC_XFORM_MODE,t,i)},createDecryptor:function(t,i){return this.create(this._DEC_XFORM_MODE,t,i)},init:function(t,i,o){this.cfg=this.cfg.extend(o),this._xformMode=t,this._key=i,this.reset()},reset:function(){u.reset.call(this),this._doReset()},process:function(t){return this._append(t),this._process()},finalize:function(t){return t&&this._append(t),this._doFinalize()},keySize:4,ivSize:4,_ENC_XFORM_MODE:1,_DEC_XFORM_MODE:2,_createHelper:function(){function selectCipherStrategy(t){return"string"==typeof t?V:O}return function(t){return{encrypt:function(i,o,m){return selectCipherStrategy(o).encrypt(t,i,o,m)},decrypt:function(i,o,m){return selectCipherStrategy(o).decrypt(t,i,o,m)}}}}()});o.StreamCipher=M.extend({_doFinalize:function(){return this._process(!0)},blockSize:1});var E=i.mode={},S=o.BlockCipherMode=m.extend({createEncryptor:function(t,i){return this.Encryptor.create(t,i)},createDecryptor:function(t,i){return this.Decryptor.create(t,i)},init:function(t,i){this._cipher=t,this._iv=i}}),T=E.CBC=function(){var t=S.extend();function xorBlock(t,i,o){var m,h=this._iv;h?(m=h,this._iv=void 0):m=this._prevBlock;for(var u=0;u<o;u++)t[i+u]^=m[u]}return t.Encryptor=t.extend({processBlock:function(t,i){var o=this._cipher,m=o.blockSize;xorBlock.call(this,t,i,m),o.encryptBlock(t,i),this._prevBlock=t.slice(i,i+m)}}),t.Decryptor=t.extend({processBlock:function(t,i){var o=this._cipher,m=o.blockSize,h=t.slice(i,i+m);o.decryptBlock(t,i),xorBlock.call(this,t,i,m),this._prevBlock=h}}),t}(),C=(i.pad={}).Pkcs7={pad:function(t,i){for(var o=4*i,m=o-t.sigBytes%o,u=m<<24|m<<16|m<<8|m,v=[],I=0;I<m;I+=4)v.push(u);var _=h.create(v,m);t.concat(_)},unpad:function(t){var i=255&t.words[t.sigBytes-1>>>2];t.sigBytes-=i}};o.BlockCipher=M.extend({cfg:M.cfg.extend({mode:T,padding:C}),reset:function(){var t;M.reset.call(this);var i=this.cfg,o=i.iv,m=i.mode;this._xformMode==this._ENC_XFORM_MODE?t=m.createEncryptor:(t=m.createDecryptor,this._minBufferSize=1),this._mode&&this._mode.__creator==t?this._mode.init(this,o&&o.words):(this._mode=t.call(m,this,o&&o.words),this._mode.__creator=t)},_doProcessBlock:function(t,i){this._mode.processBlock(t,i)},_doFinalize:function(){var t,i=this.cfg.padding;return this._xformMode==this._ENC_XFORM_MODE?(i.pad(this._data,this.blockSize),t=this._process(!0)):(t=this._process(!0),i.unpad(t)),t},blockSize:4});var N=o.CipherParams=m.extend({init:function(t){this.mixIn(t)},toString:function(t){return(t||this.formatter).stringify(this)}}),A=(i.format={}).OpenSSL={stringify:function(t){var i=t.ciphertext,o=t.salt;return(o?h.create([1398893684,1701076831]).concat(o).concat(i):i).toString(I)},parse:function(t){var i,o=I.parse(t),m=o.words;return 1398893684==m[0]&&1701076831==m[1]&&(i=h.create(m.slice(2,4)),m.splice(0,4),o.sigBytes-=16),N.create({ciphertext:o,salt:i})}},O=o.SerializableCipher=m.extend({cfg:m.extend({format:A}),encrypt:function(t,i,o,m){m=this.cfg.extend(m);var h=t.createEncryptor(o,m),u=h.finalize(i),v=h.cfg;return N.create({ciphertext:u,key:o,iv:v.iv,algorithm:t,mode:v.mode,padding:v.padding,blockSize:t.blockSize,formatter:m.format})},decrypt:function(t,i,o,m){return m=this.cfg.extend(m),i=this._parse(i,m.format),t.createDecryptor(o,m).finalize(i.ciphertext)},_parse:function(t,i){return"string"==typeof t?i.parse(t,this):t}}),R=(i.kdf={}).OpenSSL={execute:function(t,i,o,m){m||(m=h.random(8));var u=_.create({keySize:i+o}).compute(t,m),v=h.create(u.words.slice(i),4*o);return u.sigBytes=4*i,N.create({key:u,iv:v,salt:m})}},V=o.PasswordBasedCipher=O.extend({cfg:O.cfg.extend({kdf:R}),encrypt:function(t,i,o,m){var h=(m=this.cfg.extend(m)).kdf.execute(o,t.keySize,t.ivSize);m.iv=h.iv;var u=O.encrypt.call(this,t,i,h.key,m);return u.mixIn(h),u},decrypt:function(t,i,o,m){m=this.cfg.extend(m),i=this._parse(i,m.format);var h=m.kdf.execute(o,t.keySize,t.ivSize,i.salt);return m.iv=h.iv,O.decrypt.call(this,t,i,h.key,m)}})}()}(Qn);var po=Qn,mo=po.lib.StreamCipher,ho=po.algo,uo=ho.RC4=mo.extend({_doReset:function(){for(var t=this._key,i=t.words,o=t.sigBytes,m=this._S=[],h=0;h<256;h++)m[h]=h;h=0;for(var u=0;h<256;h++){var v=h%o,I=i[v>>>2]>>>24-v%4*8&255;u=(u+m[h]+I)%256;var _=m[h];m[h]=m[u],m[u]=_}this._i=this._j=0},_doProcessBlock:function(t,i){t[i]^=generateKeystreamWord.call(this)},keySize:8,ivSize:0});function generateKeystreamWord(){for(var t=this._S,i=this._i,o=this._j,m=0,h=0;h<4;h++){o=(o+t[i=(i+1)%256])%256;var u=t[i];t[i]=t[o],t[o]=u,m|=t[(t[i]+t[o])%256]<<24-8*h}return this._i=i,this._j=o,m}po.RC4=mo._createHelper(uo);var go=ho.RC4Drop=uo.extend({cfg:uo.cfg.extend({drop:192}),_doReset:function(){uo._doReset.call(this);for(var t=this.cfg.drop;t>0;t--)generateKeystreamWord.call(this)}});po.RC4Drop=mo._createHelper(go);var vo=Qn.RC4;class V2NIMSettingPushImpl{constructor(t,i){this.offlinePushPlugin=void 0,this.offlinePushConfig=void 0,this.authConfig=void 0,this.aosPushInfo=void 0,this.appBackgroundOptions={badge:0,isBackground:!1},this.setTokenAndBackgroundStateAfterLogin=t=>{this.aosPushInfo=t,this.logger.log("OfflinePushService: setToken, deviceClientId:",null==t?void 0:t.clientId),this.offlinePushPlugin&&(this.logger.log("OfflinePushService: setToken plugin is provided"),this.logger.log("OfflinePushService: setToken pushType is: ",t&&t.pushType),this.regToken(),this.core.sendCmd("v2SetAppBackground",{isBackground:this.appBackgroundOptions.isBackground,badge:this.appBackgroundOptions.badge||0}))},this.core=t,this.service=i,this.logger=t.logger}getRNDeviceInfo(){var t;return this.logger.log("OfflinePushService:getDeviceInfo start"),null===(t=this.offlinePushPlugin)||void 0===t||t.init(JSON.stringify(this.authConfig),((t,i,o)=>{if(this.logger.log(`OfflinePushService:: type: ${t}, tokenName: ${i}, token: ${o}`),o){var m="",h=Re.getSystemInfo()||{},u=h.os?h.os.toLowerCase():"";this.aosPushInfo&&this.aosPushInfo.pushType?m=this.aosPushInfo.pushType:"ios"===u?m="":"android"===u&&(m="8"),this.pushTokenToServer(m,o)}else this.logger.warn("OfflinePushService:: token is empty. Please check your parameters")})),new Promise(((t,i)=>{var o;null===(o=this.offlinePushPlugin)||void 0===o||o.getDeviceInfo((o=>{try{this.logger.log(`OfflinePushService:getDeviceInfo result ${o?JSON.stringify(o):""}`),t(JSON.parse(o))}catch(t){i(new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INTERNAL,detail:{reason:"OfflinePushService:getDeviceInfo error"}}))}})),setTimeout((()=>{i(new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INTERNAL,detail:{reason:"OfflinePushService:getDeviceInfo timeout"}}))}),2e3)}))}pushTokenToServer(t,i){var o,m,h,u,v,I,_,M,E="",S=this.offlinePushConfig;switch(t){case"5":E=null===(o=null==S?void 0:S.miPush)||void 0===o?void 0:o.certificateName;break;case"6":E=null===(m=null==S?void 0:S.hwPush)||void 0===m?void 0:m.certificateName;break;case"7":E=null===(h=null==S?void 0:S.mzPush)||void 0===h?void 0:h.certificateName;break;case"8":E=null===(u=null==S?void 0:S.fcmPush)||void 0===u?void 0:u.certificateName;break;case"9":E=null===(v=null==S?void 0:S.vivoPush)||void 0===v?void 0:v.certificateName;break;case"10":E=null===(I=null==S?void 0:S.oppoPush)||void 0===I?void 0:I.certificateName;break;case"11":E=null===(_=null==S?void 0:S.honorPush)||void 0===_?void 0:_.certificateName;break;default:E=null===(M=null==S?void 0:S.apns)||void 0===M?void 0:M.certificateName}if(""===E||void 0===E)this.logger.warn("OfflinePushService:: certificate name is empty for push type: ",t);else try{if("UNIAPP"===Re.platform){var T=Zn.parse("557d1e3cafa43e2589a588270c53d56f"),C=Zn.stringify(vo.decrypt(i,T));this.logger.log("OfflinePushService:: token",C),this.core.sendCmd("v2SetDeviceToken",{certificateName:E,pushDeviceToken:C,pushkit:0})}else this.core.sendCmd("v2SetDeviceToken",{certificateName:E,pushDeviceToken:i,pushkit:0})}catch(t){return this.logger.log("OfflinePushService:: decrypt error",t),void this.logger.warn("OfflinePushService:: token before decrypt",i)}}regToken(){var t=Re.getSystemInfo()||{},i=t.os?t.os.toLowerCase():"";if(this.logger.log("OfflinePushService: os",i),"ios"===i||"android"===i)if(!this.offlinePushPlugin||"UNIAPP"===Re.platform&&"function"!=typeof this.offlinePushPlugin.getDeviceToken||"React Native"===Re.platform&&"android"===i&&"function"!=typeof this.offlinePushPlugin.init||"React Native"===Re.platform&&"ios"===i&&"function"!=typeof this.offlinePushPlugin.checkPermissions)this.logger.warn("OfflinePushService: plugin is not correct, please check your plugin according to Yunxin Official Documentation");else{"React Native"===Re.platform&&Re.envPayload.AppState&&Re.envPayload.AppState.addEventListener("change",this.handleRNAppStateChange.bind(this));var o="";this.aosPushInfo&&this.aosPushInfo.pushType?o=this.aosPushInfo.pushType:"ios"===i?o="":"android"===i&&(o="8"),this.logger.log("OfflinePushService:: prepare to get device token. suggestPushType: "+o),this.logger.log("OfflinePushService push config",JSON.stringify(this.authConfig,null,2),"platform",Re.platform),"UNIAPP"===Re.platform?this.offlinePushPlugin.getDeviceToken({suggestPushType:o,config:this.authConfig},(t=>{t?(this.logger.log("OfflinePushService:: token is :"+t),this.pushTokenToServer(o,t)):this.logger.warn("OfflinePushService:: token is empty. Please check your parameters")})):"React Native"===Re.platform&&"android"===i?(this.logger.log("OfflinePushService:: onLogin",this.core.account,typeof o,o),this.offlinePushPlugin.onLogin(this.core.account,parseInt(o),!1,"")):"React Native"===Re.platform&&"ios"===i?this.offlinePushPlugin.checkPermissions((()=>{this.logger.log("OfflinePushService addEventListener requestPermissions");try{this.offlinePushPlugin.requestPermissions()}catch(t){this.logger.log("OfflinePushService:: requestPermissions error",t)}this.offlinePushPlugin.addEventListener("register",(t=>{this.logger.log(`OfflinePushService:: ios token: ${t}`),this.pushTokenToServer(o,t)})),this.offlinePushPlugin.addEventListener("registrationError",(t=>{this.logger.log("OfflinePushService:: ios registerError",t)}))})):this.logger.error(`OfflinePushService:: platform is not supported. Please check your parameters. Platform: ${Re.platform}. os: ${i}`)}else this.logger.warn("OfflinePushService: only Android or IOS support offline push")}handleRNAppStateChange(t){this.logger.log(`push::handleAppStateChange: pushConfig ios/aos; state: ${t}`),this.appBackgroundOptions={badge:this.core.V2NIMLocalConversationService.getTotalUnreadCount(),isBackground:"background"===t||"inactive"===t},this.setAppBackground(this.appBackgroundOptions.isBackground,this.appBackgroundOptions.badge)}setOfflinePushConfig(t,i){var o,m,h,u,v,I,_,M,E,S,T,C,N,A,O,R,V,k,P,L,w,D,U,x,B,$,j,G,q,H,z,Y,J,K,W,X;this.logger.log("setOfflinePushConfig","plugin",t,"config",i),this.offlinePushPlugin=t,this.offlinePushConfig=i,this.authConfig={xmAppId:null===(m=null===(o=this.offlinePushConfig)||void 0===o?void 0:o.miPush)||void 0===m?void 0:m.appId,xmAppKey:null===(u=null===(h=this.offlinePushConfig)||void 0===h?void 0:h.miPush)||void 0===u?void 0:u.appKey,xmCertificateName:null===(I=null===(v=this.offlinePushConfig)||void 0===v?void 0:v.miPush)||void 0===I?void 0:I.certificateName,hwAppId:null===(M=null===(_=this.offlinePushConfig)||void 0===_?void 0:_.hwPush)||void 0===M?void 0:M.appId,hwCertificateName:null===(S=null===(E=this.offlinePushConfig)||void 0===E?void 0:E.hwPush)||void 0===S?void 0:S.certificateName,oppoAppId:null===(C=null===(T=this.offlinePushConfig)||void 0===T?void 0:T.oppoPush)||void 0===C?void 0:C.appId,oppoAppKey:null===(A=null===(N=this.offlinePushConfig)||void 0===N?void 0:N.oppoPush)||void 0===A?void 0:A.appKey,oppoAppSecret:null===(R=null===(O=this.offlinePushConfig)||void 0===O?void 0:O.oppoPush)||void 0===R?void 0:R.secret,oppoCertificateName:null===(k=null===(V=this.offlinePushConfig)||void 0===V?void 0:V.oppoPush)||void 0===k?void 0:k.certificateName,vivoAppId:null===(L=null===(P=this.offlinePushConfig)||void 0===P?void 0:P.vivoPush)||void 0===L?void 0:L.appId,vivoAppKey:null===(D=null===(w=this.offlinePushConfig)||void 0===w?void 0:w.vivoPush)||void 0===D?void 0:D.appKey,vivoCertificateName:null===(x=null===(U=this.offlinePushConfig)||void 0===U?void 0:U.vivoPush)||void 0===x?void 0:x.certificateName,fcmCertificateName:null===($=null===(B=this.offlinePushConfig)||void 0===B?void 0:B.fcmPush)||void 0===$?void 0:$.certificateName,mzAppId:null===(G=null===(j=this.offlinePushConfig)||void 0===j?void 0:j.mzPush)||void 0===G?void 0:G.appId,mzAppKey:null===(H=null===(q=this.offlinePushConfig)||void 0===q?void 0:q.mzPush)||void 0===H?void 0:H.appKey,mzCertificateName:null===(Y=null===(z=this.offlinePushConfig)||void 0===z?void 0:z.mzPush)||void 0===Y?void 0:Y.certificateName,apnsCertificateName:null===(K=null===(J=this.offlinePushConfig)||void 0===J?void 0:J.apns)||void 0===K?void 0:K.certificateName,honorCertificateName:null===(X=null===(W=this.offlinePushConfig)||void 0===W?void 0:W.honorPush)||void 0===X?void 0:X.certificateName}}setAppBackground(t,i){return __awaiter(this,void 0,void 0,(function*(){this.appBackgroundOptions={isBackground:t,badge:i||0},yield this.core.sendCmd("v2SetAppBackground",{isBackground:t,badge:i||0})}))}}class V2NIMSettingMuteImpl{constructor(t,i){this.p2pMessageMuteModeChangeHandler=(t,i)=>{this.service.emit("onP2PMessageMuteModeChanged",t,i),this.hasUserService&&this.core.V2NIMUserService.model.setAccountMuteMode(t,i);var o=this.core.V2NIMConversationIdUtil.p2pConversationId(t),m=1===i;this.core.eventBus.emit("V2NIMSettingService/setMute",o,m)},this.core=t,this.service=i}get hasUserService(){var t;return!!(null===(t=this.core.V2NIMUserService)||void 0===t?void 0:t.name)}get hasTeamService(){var t;return!!(null===(t=this.core.V2NIMTeamService)||void 0===t?void 0:t.name)}getConversationMuteStatus(t){if("string"!=typeof t)return!1;var i=this.core.V2NIMConversationIdUtil.parseConversationType(t),o=this.core.V2NIMConversationIdUtil.parseConversationTargetId(t);return 3===i?0!==this.getTeamMessageMuteMode(o,2):2===i?0!==this.getTeamMessageMuteMode(o,1):!(1!==i||!this.hasUserService)&&!!this.core.V2NIMUserService.model.muteList.has(o)}setTeamMessageMuteMode(t,i,o){return __awaiter(this,void 0,void 0,(function*(){var m=2===i?"v2SuperTeamUpdateSelfMemberInfo":"v2TeamUpdateSelfMemberInfo",h={teamId:t,teamType:i,accountId:this.core.account,bits:o};yield this.core.sendCmd(m,{teamMember:h}),this.core.V2NIMTeamService.memberModel.upsert(h),this.service.emit("onTeamMessageMuteModeChanged",t,i,o);var u=1===i?this.core.V2NIMConversationIdUtil.teamConversationId(t):this.core.V2NIMConversationIdUtil.superTeamConversationId(t),v=this.getConversationMuteStatus(u);this.core.eventBus.emit("V2NIMSettingService/setMute",u,v)}))}getTeamMessageMuteMode(t,i){var o;return"string"!=typeof t||"number"!=typeof i?0:this.hasTeamService?3&((null===(o=this.core.V2NIMTeamService.memberModel.getById(t,i,this.core.account))||void 0===o?void 0:o.bits)||0):0}getAllTeamMessageMuteMode(t){if(!this.hasTeamService)return Promise.resolve({});var i=this.core.V2NIMTeamService.memberModel.chooseList(t),o={};return i.forEach((t=>{if(t.accountId===this.core.account){var i=t.bits||0;o[t.teamId]=3&i}})),Promise.resolve(o)}setP2PMessageMuteMode(t,i){return __awaiter(this,void 0,void 0,(function*(){yield this.core.sendCmd("v2SetP2PMessageMuteMode",{accountId:t,muteMode:1===i}),this.p2pMessageMuteModeChangeHandler(t,i)}))}getP2PMessageMuteMode(t){return this.hasUserService&&this.core.V2NIMUserService.model.muteList.has(t)?1:0}getP2PMessageMuteList(){return this.hasUserService?Promise.resolve(Array.from(this.core.V2NIMUserService.model.muteList)):Promise.resolve([])}}class V2NIMSettingEventImpl{constructor(t,i){this.core=t,this.service=i,this.push=i.push,this.mute=i.mute}setListener(){this.core.eventBus.on("V2NIMSettingService/updateBits",((t,i,o)=>{this.service.emit("onTeamMessageMuteModeChanged",t,i,o)})),this.core.eventBus.on("V2NIMLoginService/loginLifeCycleLoginSucc",this.push.setTokenAndBackgroundStateAfterLogin.bind(this.push)),this.core.eventBus.on("v2NIMUserService/updateMuteList",this.mute.p2pMessageMuteModeChangeHandler.bind(this.mute)),this.core.eventBus.on("forwardReceive/v2NIMSettingService/setP2PMessageMuteMode",this.mute.p2pMessageMuteModeChangeHandler.bind(this.mute))}}class V2NIMSettingServiceImpl extends V2Service{constructor(t){super("V2NIMSettingService",t),this.needToPushMobileOnDesktopOnline=!0,this.core._registerDep(V2NIMConversationIdUtilImpl,"V2NIMConversationIdUtil"),this.push=new V2NIMSettingPushImpl(t,this),this.mute=new V2NIMSettingMuteImpl(t,this),this.event=new V2NIMSettingEventImpl(t,this),this.handler=new V2NIMSettingHandlerImpl(t,this),"v2"===this.core.options.apiVersion&&(this.setListener(),registerParser({cmdMap:Kn,cmdConfig:Xn}))}get hasUserService(){var t;return!!(null===(t=this.core.V2NIMUserService)||void 0===t?void 0:t.name)}get hasTeamService(){var t;return!!(null===(t=this.core.V2NIMTeamService)||void 0===t?void 0:t.name)}setListener(){this.event.setListener()}emit(t,...i){var o=`${this.name}::emit ${t.toString()}`;return this.logger.log(`${o}`,...i),super.emit(t,...i)}getConversationMuteStatus(t){return this.mute.getConversationMuteStatus(t)}setTeamMessageMuteMode(t,i,o){if(!this.hasTeamService)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_MISUSE,detail:{reason:"setTeamMessageMuteMode: no team service"}});return this.checkV2(),validate(rn,{teamId:t},"",!0),validate(sn,{teamType:i},"",!0),validate(qn,{muteMode:o},"",!0),this.mute.setTeamMessageMuteMode(t,i,o)}getTeamMessageMuteMode(t,i){return this.mute.getTeamMessageMuteMode(t,i)}getAllTeamMessageMuteMode(t){return this.checkV2(),this.checkLogin(),validate(sn,{teamType:t},"",!0),this.mute.getAllTeamMessageMuteMode(t)}setP2PMessageMuteMode(t,i){if(this.checkV2(),validate(Hn,{accountId:t,muteMode:i},"",!0),t===this.core.account)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"can not set mute mode for self"}});return this.mute.setP2PMessageMuteMode(t,i)}getP2PMessageMuteMode(t){return validate({accountId:{type:"string",required:!0,allowEmpty:!1}},{accountId:t},"",!0),this.mute.getP2PMessageMuteMode(t)}getP2PMessageMuteList(){return this.mute.getP2PMessageMuteList()}setAppBackground(t,i){return this.checkV2(),validate({isBackground:{type:"boolean"},badge:{type:"number",required:!1}},{isBackground:t,badge:i},"",!0),this.push.setAppBackground(t,i)}setOfflinePushConfig(t,i){validate(Yn,{config:i},"",!0),this.push.setOfflinePushConfig(t,i)}setPushMobileOnDesktopOnline(t){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate({need:{type:"boolean",required:!1}},{need:t},"",!0),t=void 0===t||t,yield this.core.sendCmd("v2SetPushMobileOnDesktopOnline",{tag:{need:t}}),this.needToPushMobileOnDesktopOnline=t,this.emit("onPushMobileOnDesktopOnline",t)}))}getPushMobileOnDesktopOnline(){return this.checkLogin(),Promise.resolve(this.needToPushMobileOnDesktopOnline)}}class V2NIMAIModelImpl{constructor(){this.aiStreamMap=new Map}reset(){this.aiStreamMap.clear()}getAiStream(t){return this.aiStreamMap.get(t)}getAiStreamIsComplete(t){var i=this.aiStreamMap.get(t);return!i||i.isComplete}getAiStreamQueryStatus(t){var i=this.aiStreamMap.get(t);return i?i.queryStatus:0}upsertAiStreamChunks(t,i,o){var m=this.aiStreamMap.get(t);return m&&!m.isComplete&&(m.chunks[i]=o),m||{isComplete:!1,queryStatus:0,chunks:[]}}setAiStream(t,i,o=!1){var m=this.aiStreamMap.get(t);return m?this.aiStreamMap.set(t,Object.assign(Object.assign({},m),i)):o&&this.aiStreamMap.set(t,Object.assign({isComplete:!1,queryStatus:0,chunks:[]},i)),this.aiStreamMap.get(t)||{isComplete:!1,queryStatus:0,chunks:[]}}completeAiStream(t){var i=this.aiStreamMap.get(t);i&&this.aiStreamMap.set(t,Object.assign(Object.assign({},i),{isComplete:!0,queryStatus:0,chunks:[],aiRAGs:void 0}))}}var fo={"4_26":"v2AIChatNotify","29_35":"v2AIProxyModelCall","29_36":"v2AIGetUserList","4_29":"v2AIOnStreamMessageChunk","4_30":"v2AIChatStreamNotify","29_38":"v2AIStopModelStreamCall","29_39":"v2AIStreamQuery","29_40":"v2AIRegenMessage"},Io={accountId:1,messages:{id:2,converter:objectToJSONString,retConverter:stringToJSONObject},requestId:3,content:{id:4,converter:objectToJSONString,retConverter:stringToJSONObject},promptVariables:5,modelConfigParams:{id:6,converter:objectToJSONString,retConverter:stringToJSONObject},antispamBusinessId:7,antispamEnabled:{id:8,converter:boolToInt},aiStream:{id:9,converter:boolToInt}},yo={accountId:1,name:3,avatar:4,sign:5,gender:{id:6,retType:"number"},email:7,birthday:8,mobile:9,serverExtension:10,aiModelType:{id:11,retType:"number"},modelConfig:{id:12,retConverter:t=>{if(t=stringToJSONObject(t)){var i=Object.keys(t).reduce(((i,o)=>(i[function camelCase(t){return(t=t||"").split("_").map(((t,i)=>0===i?t:t[0].toUpperCase()+t.slice(1))).join("")}(o)]=t[o],i)),{});if("string"==typeof i.promptKeys)try{i.promptKeys=JSON.parse(i.promptKeys)}catch(t){}return i}}},yunxinConfig:{id:13,retConverter:t=>{if(t=stringToJSONObject(t))return t}},valid:{id:14,retType:"boolean"},createTime:{id:15,retType:"number"},updateTime:{id:16,retType:"number"}};function aiAgentStreamContentRetConverter(t){try{var i=JSON.parse(t);return"number"==typeof i.index?{msg:i.msg||"",type:i.type,lastChunk:{content:i.msg,chunkTime:parseInt(i.timestamp),type:i.type,index:parseInt(i.index)}}:i}catch(t){return}}function aiAgentStreamAIRAGsRetConverter(t){try{var i=JSON.parse(t);return i&&i.length>0?i.map((t=>(t.description=t.desc,delete t.desc,t))):[]}catch(t){return[]}}var _o={code:{id:1,retType:"number"},accountId:2,requestId:3,content:{id:4,retConverter:aiAgentStreamContentRetConverter},aiRAGs:{id:5,retConverter:aiAgentStreamAIRAGsRetConverter},timestamp:{id:6,retType:"number"},aiStreamStatus:{id:7,retType:"number"},aiStream:{id:8,retType:"boolean"}},Mo={serverId:1,clientId:2,type:{id:3,retType:"number"},from:4,to:5,aiAccount:6,startIndex:{id:7,retType:"number"},endIndex:{id:8,retType:"number"},excludeIndex:{id:9,converter:objectToJSONString}},Eo={serverId:1,clientId:2,type:{id:3,retType:"number"},content:{id:4,retConverter:aiAgentStreamContentRetConverter},aiRAGs:{id:6,retConverter:aiAgentStreamAIRAGsRetConverter}},So={v2AIChatNotify:{sid:4,cid:26,service:"V2NIMAIService",response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(_o)}]},v2AIProxyModelCall:{sid:29,cid:35,service:"V2NIMAIService",params:[{type:"Property",name:"tag",reflectMapper:Io}]},v2AIGetUserList:{sid:29,cid:36,service:"V2NIMAIService",params:[{type:"Property",name:"tag",reflectMapper:{pageToken:1,limit:2}}],response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(yo)},{type:"Property",name:"queryTag",reflectMapper:invertSerializeItem({hasMore:{id:16,retType:"boolean"},nextToken:2})}]},v2AIOnStreamMessageChunk:{sid:4,cid:29,service:"V2NIMAIService",response:[{type:"Property",name:"msg",reflectMapper:invertSerializeItem(Pi)}]},v2AIChatStreamNotify:{sid:4,cid:30,service:"V2NIMAIService",response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(_o)}]},v2AIStopModelStreamCall:{sid:29,cid:38,service:"V2NIMAIService",params:[{type:"Property",name:"tag",reflectMapper:{serverId:1,clientId:2,type:{id:3,retType:"number"},from:4,to:5,aiAccount:6,opeType:{id:7,retType:"number"},updateContent:{id:8},messageTime:{id:11,retType:"number"}}}]},v2AIStreamQuery:{sid:29,cid:39,service:"V2NIMAIService",params:[{type:"Property",name:"tag",reflectMapper:Mo}],response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(Eo)}]},v2AIRegenMessage:{sid:29,cid:40,service:"V2NIMAIService",params:[{type:"Property",name:"tag",reflectMapper:{fromAccount:1,to:2,aiAccount:3,serverId:4,clientId:5,time:{id:6,retType:"number"},type:{id:7,retType:"number"},opeType:{id:8,retType:"number"},replyMsgFromAccount:9,replyMsgToAccount:10,replyMsgTime:{id:11,retType:"number"},replyMsgIdServer:12,replyMsgIdClient:13}}]}};class V2NIMAIEventImpl{constructor(t,i){this.core=t,this.service=i,this.logger=this.core.logger}setListener(){}beforeEmit(t,...i){var o,m,h=`${this.service.name}::emit ${t.toString()}`;if("onProxyAIModelCall"===t){var u=i[0];this.logger.log(`${h}`,`requestId:${u.requestId};aiStreamStatus:${u.aiStreamStatus}`)}else if("onProxyAIModelStreamCall"===t){var v=i[0];this.logger.log(`${h}`,`requestId:${v.requestId};chunkIndex:${null===(o=v.content)||void 0===o?void 0:o.lastChunk.index};chunkTime:${null===(m=v.content)||void 0===m?void 0:m.lastChunk.chunkTime}`)}else this.logger.log(`${h}`,...i)}}class V2NIMAIHandlerImpl{constructor(t,i){this.core=t,this.service=i,this.model=i.model,this.logger=this.core.logger}v2AIChatNotifyHandler(t){var i=t.content.data;i&&i.requestId&&(this.model.completeAiStream(i.requestId),i.aiStreamStatus=i.aiStreamStatus||0,i.aiStream=i.aiStream||!1,i.content&&(i.content.msg=i.content.msg||""),this.service.emit("onProxyAIModelCall",i))}v2AIChatStreamNotifyHandler(t){var i=t.content.data;if(i&&i.requestId&&i.content&&i.content.msg){var o=this.model.getAiStream(i.requestId);if(o||(o=this.model.setAiStream(i.requestId,{isComplete:!1,queryStatus:0,chunks:[]},!0)),!o.isComplete){var{lastChunk:m}=i.content;if(0===m.index&&i.aiRAGs&&(o=this.model.setAiStream(i.requestId,{aiRAGs:i.aiRAGs})),this.logger.log(`V2AI::streamNotify requestId:${i.requestId};index:${m.index};cacheChunkLength:${o.chunks.length};chunkTime:${m.chunkTime}.`),0===o.chunks.length&&m.index>0)this.logger.log(`V2AI::streamNotify requestId:${i.requestId};chunks missing 0,currentIdx:${m.index},needQuery:${0===o.queryStatus}.`),0===o.queryStatus&&(o=this.model.setAiStream(i.requestId,{queryStatus:1}),this.service._queryAiStream({clientId:i.requestId,type:4,from:this.core.account,aiAccount:i.accountId,startIndex:0,endIndex:m.index-1}));else if(m.index>0&&o.chunks.length>0&&void 0===o.chunks[m.index-1]){var h=o.chunks.reduce(((t,i,o)=>(void 0!==i&&t.push(o),t)),[]);this.logger.log(`V2AI::streamNotify requestId:${i.requestId};out of order,currenIdx:${m.index},cacheIdx:[${h.join(",")}],needReport:${!o.hasReported}.`),o.hasReported||(o=this.model.setAiStream(i.requestId,{hasReported:!0}),this.reportOutOfOrder({requestId:i.requestId,cacheIds:h,targetIndex:m.index,target:"4-30"}))}(o=this.model.upsertAiStreamChunks(i.requestId,m.index,m.content)).chunks[0]||1!==o.queryStatus?(i.content.msg=o.chunks.join(""),o.aiRAGs&&(i.aiRAGs=o.aiRAGs),this.service.emit("onProxyAIModelStreamCall",i)):this.logger.log(`V2AI::streamNotify requestId:${i.requestId};chunks ignore index:${m.index};queryStatus:${o.queryStatus}.`)}}}v2AIOnStreamMessageChunkHandler(t){var i,o,m;return __awaiter(this,void 0,void 0,(function*(){var h=completeMessage(this.core,t.content.msg);if(h.streamConfig&&h.streamConfig.lastChunk){var u=this.model.getAiStream(h.messageClientId);if(!u||!u.isComplete){u||(u=this.model.setAiStream(h.messageClientId,{isComplete:!1,queryStatus:0,chunks:[]},!0));var v=h.streamConfig.lastChunk,I=h.messageClientId,_=(null===(i=h.aiConfig)||void 0===i?void 0:i.aiRAGs)||h.streamConfig.rags;if(_&&(u.aiRAGs&&(_=[...u.aiRAGs,..._]),u=this.model.setAiStream(I,{aiRAGs:_})),this.logger.log(`V2AI::aiStream requestId:${I};index:${v.index};cacheChunkLength:${u.chunks.length};chunkTime:${v.chunkTime}.`),0===u.chunks.length&&v.index>0){if(this.logger.log(`V2AI::msg:aiStream requestId:${I};chunks missing 0,currentIdx:${v.index},needQuery:${0===u.queryStatus}.`),0===u.queryStatus){u=this.model.setAiStream(I,{queryStatus:1});var M={0:0,1:5,2:6,3:7},E=(null===(o=h.aiConfig)||void 0===o?void 0:o.accountId)?h.conversationType:M[h.conversationType];this.service._queryAiStream({serverId:h.messageServerId,clientId:I,type:E,from:h.senderId,to:h.receiverId,aiAccount:null===(m=h.aiConfig)||void 0===m?void 0:m.accountId,startIndex:0,endIndex:v.index-1})}}else if(v.index>0&&u.chunks.length>0&&void 0===u.chunks[v.index-1]){var S=u.chunks.reduce(((t,i,o)=>(void 0!==i&&t.push(o),t)),[]);this.logger.log(`V2AI::msg:aiStream requestId:${I};out of order,currenIdx:${v.index};streamCache.chunks:${JSON.stringify(u.chunks)},cacheIdx:[${S.join(",")}],needReport:${!u.hasReported}.`),u.hasReported||(u=this.model.setAiStream(I,{hasReported:!0}),this.reportOutOfOrder({requestId:I,cacheIds:S,targetIndex:v.index,target:"4-29"}))}(u=this.model.upsertAiStreamChunks(I,v.index,v.content)).chunks[0]||1!==u.queryStatus?(h.streamConfig.status=-1,h.aiConfig&&(h.aiConfig.aiStreamStatus=-1),h.text=u.chunks.join(""),u.aiRAGs&&h.aiConfig&&(h.aiConfig.aiRAGs=u.aiRAGs),u.aiRAGs&&h.streamConfig&&(h.streamConfig.rags=u.aiRAGs),u.msg&&(h=Object.assign({},u.msg,Object.assign({text:h.text,modifyTime:v.chunkTime,modifyAccountId:u.msg.senderId,streamConfig:h.streamConfig},h.aiConfig?{aiConfig:h.aiConfig}:{}))),this.core.eventBus.emit("V2NIMAIService/receiveMessagesModified",[h])):this.logger.log(`V2AI::msg:callStream requestId:${I};chunks ignore index:${v.index};queryStatus:${u.queryStatus}.`)}}}))}reportOutOfOrder(t){this.core.reporter.reportTraceStart("exceptions",{user_id:this.core.account,trace_id:get(this.core,"clientSocket.socket.sessionId"),action:2,exception_service:0}),this.core.reporter.reportTraceUpdateV2("exceptions",{code:0,context:t.requestId,description:`[${t.cacheIds.join(",")}],${t.targetIndex}`,operation_type:2,target:t.target,net_connect:!0}),this.core.reporter.reportTraceEnd("exceptions",4)}}class V2NIMAIServiceImpl extends V2Service{constructor(t){super("V2NIMAIService",t),this.model=new V2NIMAIModelImpl,this.event=new V2NIMAIEventImpl(this.core,this),this.handler=new V2NIMAIHandlerImpl(this.core,this),registerParser({cmdMap:fo,cmdConfig:So})}setListener(){this.event.setListener()}reset(){this.model.reset()}emit(t,...i){return this.event.beforeEmit(t,...i),super.emit(t,...i)}getAIUserList(){return __awaiter(this,void 0,void 0,(function*(){return this.checkV2(),function formatAIUsers(t){return t&&t.length>0?t.map((t=>(t.modelType=t.aiModelType,t))):[]}((yield this.core.sendCmd("v2AIGetUserList",{tag:{}})).content.datas)}))}proxyAIModelCall(t){return __awaiter(this,void 0,void 0,(function*(){if(validate(kt,t,"",!0),this.model.getAiStream(t.requestId))throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INVALID_PARAMETER,desc:"Same requestId",detail:{rawData:t.requestId}});this.model.setAiStream(t.requestId,{isComplete:!1,queryStatus:0,chunks:[]},!0),yield this.core.sendCmd("v2AIProxyModelCall",{tag:t})}))}stopAIModelStreamCall(t){return __awaiter(this,void 0,void 0,(function*(){validate(Pt,t,"",!0),yield this.core.sendCmd("v2AIStopModelStreamCall",{tag:{clientId:t.requestId,aiAccount:t.accountId,type:4,from:this.core.account}}),this.logger.log(`V2AI::streamCallStop,requestId:${t.requestId}`),this.model.completeAiStream(t.requestId)}))}_queryAiStream(t){return __awaiter(this,void 0,void 0,(function*(){this.model.setAiStream(t.clientId,{queryStatus:1});try{var i=yield this.core.sendCmd("v2AIStreamQuery",{tag:t});this.model.setAiStream(t.clientId,{queryStatus:2});var o=i.content.datas;if(!(o&&o.length>0))return;o.forEach((t=>{var i=t.clientId,o=this.model.getAiStream(i);if(o&&(!o||!o.isComplete)&&t.content&&t.content.lastChunk){var m=t.content.lastChunk;this.model.upsertAiStreamChunks(i,m.index,m.content),0===m.index&&t.aiRAGs&&this.model.setAiStream(i,{aiRAGs:t.aiRAGs}),this.logger.log(`V2AI::queryAiStream requestId:${i};index:${m.index};cacheChunkLength:${o.chunks.length};chunkTime:${m.chunkTime}.`)}}))}catch(i){this.logger.warn(`V2AI::queryAiStream requestId:${t.clientId};error:`,i),this.model.setAiStream(t.clientId,{queryStatus:2})}}))}}var To={"18_1":"v2SignallingCreateRoom","18_2":"v2SignallingDelayRoom","18_3":"v2SignallingCloseRoom","18_4":"v2SignallingJoinRoom","18_5":"v2SignallingLeaveRoom","18_6":"v2SignallingInvite","18_7":"v2SignallingCancelInvite","18_16":"v2SignallingCall","18_17":"v2SignallingCallSetup","18_8":"v2SignallingRejectInvite","18_9":"v2SignallingAcceptInvite","18_10":"v2SignallingSendControl","15_11":"v2SignallingOnlineEvent","15_12":"v2SignallingMultiClientEvent","15_13":"v2SignallingOfflineEvent","15_14":"v2SignallingSyncChannels","18_15":"v2SignallingGetRoomInfo"},Co="V2NIMSignallingService",No={accountId:1,uid:{id:2,retType:"number"},joinTime:{id:3,retType:"number"},expireTime:{id:4,retType:"number"},deviceId:5},Ao={channelType:{id:1,retType:"number",retAccess:"channelInfo.channelType"},channelName:{id:2,retAccess:"channelInfo.channelName"},channelId:{id:3,retAccess:"channelInfo.channelId"},createTime:{id:4,retType:"number",retAccess:"channelInfo.createTime"},expireTime:{id:5,retType:"number",retAccess:"channelInfo.expireTime"},creatorAccountId:{id:6,retAccess:"channelInfo.creatorAccountId"},channelExtension:{id:7,retAccess:"channelInfo.channelExtension"},channelValid:{id:8,retDef:!0,retAccess:"channelInfo.channelValid",retConverter:t=>1!==parseInt(t)},fromAccid:10,toAccid:11,requestId:12,pushEnabled:{id:13,access:"pushConfig.pushEnabled",converter:boolToInt,retType:"boolean"},pushTitle:{id:14,access:"pushConfig.pushTitle"},pushContent:{id:15,access:"pushConfig.pushContent"},pushPayload:{id:16,access:"pushConfig.pushPayload"},unreadEnabled:{id:17,access:"signallingConfig.unreadEnabled",converter:boolToInt,retType:"boolean",def:1},members:{id:18,retAccess:"members",retConverter:t=>{try{return JSON.parse(t).map((t=>deserialize(t,invertSerializeItem(No))))}catch(t){return}}},attach:{id:19,retConverter:stringToJSONObject},serverExtension:{id:20,retDef:""},offlineEnabled:{id:21,converter:boolToInt,retType:"boolean",def:1},msgId:22,selfUid:{id:23,retType:"number",access:"signallingConfig.selfUid"},time:{id:24,retType:"number"},rtcChannelName:{id:25,access:"rtcConfig.rtcChannelName"},rtcTokenTtl:{id:26,retType:"number",access:"rtcConfig.rtcTokenTtl",retAccess:"rtcInfo.rtcTokenTtl"},rtcToken:{id:27,retAccess:"rtcInfo.rtcToken"},rtcParams:{id:28,access:"rtcConfig.rtcParams",retAccess:"rtcInfo.rtcParams"},callStatus:{id:30,retType:"number"}},Oo={v2SignallingCall:{sid:18,cid:16,service:Co,params:[{type:"Property",name:"tag",reflectMapper:Ao}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Ao)}]},v2SignallingCallSetup:{sid:18,cid:17,service:Co,params:[{type:"Property",name:"tag",reflectMapper:Ao}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Ao)}]},v2SignallingCreateRoom:{sid:18,cid:1,service:Co,params:[{type:"Property",name:"tag",reflectMapper:Ao}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Ao)}]},v2SignallingDelayRoom:{sid:18,cid:2,service:Co,params:[{type:"Property",name:"tag",reflectMapper:Ao}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Ao)}]},v2SignallingCloseRoom:{sid:18,cid:3,service:Co,params:[{type:"Property",name:"tag",reflectMapper:Ao}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Ao)}]},v2SignallingJoinRoom:{sid:18,cid:4,service:Co,params:[{type:"Property",name:"tag",reflectMapper:Ao}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Ao)}]},v2SignallingLeaveRoom:{sid:18,cid:5,service:Co,params:[{type:"Property",name:"tag",reflectMapper:Ao}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Ao)}]},v2SignallingInvite:{sid:18,cid:6,service:Co,params:[{type:"Property",name:"tag",reflectMapper:Ao}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Ao)}]},v2SignallingCancelInvite:{sid:18,cid:7,service:Co,params:[{type:"Property",name:"tag",reflectMapper:Ao}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Ao)}]},v2SignallingRejectInvite:{sid:18,cid:8,service:Co,params:[{type:"Property",name:"tag",reflectMapper:Ao}]},v2SignallingAcceptInvite:{sid:18,cid:9,service:Co,params:[{type:"Property",name:"tag",reflectMapper:Ao}]},v2SignallingSendControl:{sid:18,cid:10,service:Co,params:[{type:"Property",name:"tag",reflectMapper:Ao}]},v2SignallingOnlineEvent:{sid:15,cid:11,service:Co,response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Ao)}]},v2SignallingMultiClientEvent:{sid:15,cid:12,service:Co,response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Ao)}]},v2SignallingOfflineEvent:{sid:15,cid:13,service:Co,response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(Ao)}]},v2SignallingSyncChannels:{sid:15,cid:14,service:Co,response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(Ao)}]},v2SignallingGetRoomInfo:{sid:18,cid:15,service:Co,params:[{type:"Property",name:"tag",reflectMapper:Ao}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Ao)}]},v2SignallingBatchMarkRead:{sid:4,cid:5,hasPacketResponse:!1,service:Co,params:[{type:"Byte",name:"sid"},{type:"Byte",name:"cid"},{type:"LongArray",name:"ids"}]}},Ro={calleeAccountId:{type:"string",required:!0,allowEmpty:!1},requestId:{type:"string",required:!0,allowEmpty:!1},channelType:{type:"enum",values:[1,3,2]},channelName:{type:"string",required:!1,allowEmpty:!0},channelExtension:{type:"string",required:!1,allowEmpty:!0},serverExtension:{type:"string",required:!1,allowEmpty:!0},signallingConfig:{type:"object",required:!1,rules:{offlineEnabled:{type:"boolean",required:!1},unreadEnabled:{type:"boolean",required:!1},selfUid:{type:"number",required:!1}}},pushConfig:{type:"object",required:!1,rules:{pushEnabled:{type:"boolean",required:!1},pushTitle:{type:"string",required:!1,allowEmpty:!0},pushContent:{type:"string",required:!1,allowEmpty:!0},pushPayload:{type:"string",required:!1,allowEmpty:!0}}},rtcConfig:{type:"object",required:!1,rules:{rtcChannelName:{type:"string",required:!1,allowEmpty:!0},rtcTokenTtl:{type:"number",required:!1},rtcParams:{type:"string",required:!1,allowEmpty:!0}}}},bo={channelId:{type:"string",required:!0,allowEmpty:!1},callerAccountId:{type:"string",required:!0,allowEmpty:!1},requestId:{type:"string",required:!0,allowEmpty:!1},serverExtension:{type:"string",required:!1,allowEmpty:!0},signallingConfig:{type:"object",required:!1,rules:{offlineEnabled:{type:"boolean",required:!1},unreadEnabled:{type:"boolean",required:!1},selfUid:{type:"number",required:!1}}},rtcConfig:{type:"object",required:!1,rules:{rtcChannelName:{type:"string",required:!1,allowEmpty:!0},rtcTokenTtl:{type:"number",required:!1},rtcParams:{type:"string",required:!1,allowEmpty:!0}}}},Vo={channelType:{type:"enum",values:[1,3,2]},channelName:{type:"string",required:!1,allowEmpty:!0},channelExtension:{type:"string",required:!1,allowEmpty:!0}},ko={channelId:{type:"string",required:!0,allowEmpty:!1},offlineEnabled:{type:"boolean",required:!1},serverExtension:{type:"string",required:!1,allowEmpty:!0}},Po={channelId:{type:"string",required:!0,allowEmpty:!1},serverExtension:{type:"string",required:!1,allowEmpty:!0},signallingConfig:{type:"object",required:!1,rules:{offlineEnabled:{type:"boolean",required:!1},unreadEnabled:{type:"boolean",required:!1},selfUid:{type:"number",required:!1}}},rtcConfig:{type:"object",required:!1,rules:{rtcChannelName:{type:"string",required:!1,allowEmpty:!0},rtcTokenTtl:{type:"number",required:!1},rtcParams:{type:"string",required:!1,allowEmpty:!0}}}},Lo={channelId:{type:"string",required:!0,allowEmpty:!1},offlineEnabled:{type:"boolean",required:!1},serverExtension:{type:"string",required:!1,allowEmpty:!0}},wo={channelId:{type:"string",required:!0,allowEmpty:!1},inviteeAccountId:{type:"string",required:!0,allowEmpty:!1},requestId:{type:"string",required:!0,allowEmpty:!1},serverExtension:{type:"string",required:!1,allowEmpty:!0},signallingConfig:{type:"object",required:!1,rules:{offlineEnabled:{type:"boolean",required:!1},unreadEnabled:{type:"boolean",required:!1},selfUid:{type:"number",required:!1}}},pushConfig:{type:"object",required:!1,rules:{pushEnabled:{type:"boolean",required:!1},pushTitle:{type:"string",required:!1,allowEmpty:!0},pushContent:{type:"string",required:!1,allowEmpty:!0},pushPayload:{type:"string",required:!1,allowEmpty:!0}}}},Do={channelId:{type:"string",required:!0,allowEmpty:!1},inviteeAccountId:{type:"string",required:!0,allowEmpty:!1},requestId:{type:"string",required:!0,allowEmpty:!1},serverExtension:{type:"string",required:!1,allowEmpty:!0},offlineEnabled:{type:"boolean",required:!1},pushConfig:{type:"object",required:!1,rules:{pushEnabled:{type:"boolean",required:!1},pushTitle:{type:"string",required:!1,allowEmpty:!0},pushContent:{type:"string",required:!1,allowEmpty:!0},pushPayload:{type:"string",required:!1,allowEmpty:!0}}}},Uo={channelId:{type:"string",allowEmpty:!1},receiverAccountId:{type:"string",required:!1},serverExtension:{type:"string",required:!1,allowEmpty:!0}},xo={channelId:{type:"string",allowEmpty:!1},inviterAccountId:{type:"string",allowEmpty:!1},requestId:{type:"string",allowEmpty:!1},serverExtension:{type:"string",required:!1,allowEmpty:!0},offlineEnabled:{type:"boolean",required:!1}},Fo=xo;function formatSignalingEvent(t){var i,o=t.attach,m={eventType:o.type,channelInfo:t.channelInfo,operatorAccountId:t.fromAccid,time:t.time,serverExtension:t.serverExtension,requestId:t.requestId,pushConfig:t.pushConfig,unreadEnabled:null===(i=t.signallingConfig)||void 0===i?void 0:i.unreadEnabled},{fromAccid:h,toAccid:u}=t;switch(m.eventType){case 1:break;case 2:m.member={accountId:o.member[1],uid:Number(o.member[2]),joinTime:Number(o.member[3]),expireTime:Number(o.member[4]),deviceId:o.member[5]};break;case 3:case 4:m.operatorAccountId=h,m.inviteeAccountId=u,m.inviterAccountId=h;break;case 5:case 6:m.operatorAccountId=h,m.inviterAccountId=u,m.inviteeAccountId=h}return JSON.parse(JSON.stringify(m))}function cloneDeep(t,i){if((i=new Map).get(t))return t;if(t instanceof RegExp)return new RegExp(t);if(t instanceof Date)return new Date(t.getTime());if(Array.isArray(t))return i.set(t,!0),t.map((t=>cloneDeep(t,i)));if("object"==typeof t&&null!==t){i.set(t,!0);var o={};return Object.keys(t).forEach((m=>{o[m]=cloneDeep(t[m],i)})),o}return t}class V2NIMSignallingServiceImpl extends V2Service{constructor(t,i={}){super("V2NIMSignallingService",t),this.config={compatibleWithV1:!0},this.channels={},this.timer=0,this.pollingInterval=12e4,"v2"===this.core.options.apiVersion&&(registerParser({cmdMap:To,cmdConfig:Oo}),this.setOptions(i))}reset(){this.timer=0,this.channels={}}setOptions(t){var i;(null===(i=this.core.signaling)||void 0===i?void 0:i.name)?this.config.compatibleWithV1=!0:this.config.compatibleWithV1=!1,this.config=Object.assign(this.config,t)}emit(t,...i){var o=`${this.name}::emit ${t.toString()}`;return this.logger.log(`${o}`,...i),super.emit(t,...i)}call(t){var i;return __awaiter(this,void 0,void 0,(function*(){if(this.checkV2(),validate(Ro,t,"",!0),t.calleeAccountId===this.core.account)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"You cannot call yourself"}});var o=void 0!==t.pushConfig&&(void 0!==t.pushConfig.pushEnabled&&t.pushConfig.pushEnabled),m=(yield this.core.sendCmd("v2SignallingCall",{tag:Object.assign(Object.assign({},t),{toAccid:t.calleeAccountId,offlineEnabled:void 0===(null===(i=t.signallingConfig)||void 0===i?void 0:i.offlineEnabled)||t.signallingConfig.offlineEnabled,pushConfig:Object.assign(Object.assign({},t.pushConfig||{}),{pushEnabled:o})})})).content.data;return this.channels[m.channelInfo.channelId]=cloneDeep(m.channelInfo),this.timer||(this.timer=this.core.timerManager.addTimer(this.aotoDelay.bind(this),this.pollingInterval,-1)),{callStatus:m.callStatus,rtcInfo:m.rtcInfo,roomInfo:{channelInfo:m.channelInfo,members:m.members}}}))}callSetup(t){var i;return __awaiter(this,void 0,void 0,(function*(){if(this.checkV2(),validate(bo,t,"",!0),t.callerAccountId===this.core.account)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"callSetup: cannot be yourself"}});var o=(yield this.core.sendCmd("v2SignallingCallSetup",{tag:Object.assign(Object.assign({},t),{toAccid:t.callerAccountId,offlineEnabled:void 0===(null===(i=t.signallingConfig)||void 0===i?void 0:i.offlineEnabled)||t.signallingConfig.offlineEnabled})})).content.data;return this.channels[o.channelInfo.channelId]=cloneDeep(o.channelInfo),this.timer||(this.timer=this.core.timerManager.addTimer(this.aotoDelay.bind(this),this.pollingInterval,-1)),{callStatus:o.callStatus,rtcInfo:o.rtcInfo,roomInfo:{channelInfo:o.channelInfo,members:o.members}}}))}createRoom(t,i,o){return __awaiter(this,void 0,void 0,(function*(){return this.checkV2(),validate(Vo,{channelType:t,channelName:i,channelExtension:o},"",!0),(yield this.core.sendCmd("v2SignallingCreateRoom",{tag:{channelType:t,channelName:i,channelExtension:o}})).content.data.channelInfo}))}delayRoom(t){return __awaiter(this,void 0,void 0,(function*(){this.checkV2();var i=yield this.core.sendCmd("v2SignallingDelayRoom",{tag:{channelId:t}});return{channelInfo:i.content.data.channelInfo,members:i.content.data.members}}))}closeRoom(t,i,o){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(ko,{channelId:t,offlineEnabled:i,serverExtension:o},"",!0),yield this.core.sendCmd("v2SignallingCloseRoom",{tag:{channelId:t,offlineEnabled:void 0!==i&&i,serverExtension:o}})}))}joinRoom(t){var i;return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(Po,t,"",!0);var o=(yield this.core.sendCmd("v2SignallingJoinRoom",{tag:Object.assign(Object.assign({},t),{offlineEnabled:void 0===(null===(i=t.signallingConfig)||void 0===i?void 0:i.offlineEnabled)||t.signallingConfig.offlineEnabled})})).content.data;this.channels[o.channelInfo.channelId]=cloneDeep(o.channelInfo),this.timer||(this.timer=this.core.timerManager.addTimer(this.aotoDelay.bind(this),this.pollingInterval,-1));var{channelInfo:m,members:h,rtcInfo:u}=o;return{roomInfo:{channelInfo:m,members:h},rtcInfo:u}}))}leaveRoom(t,i,o){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(Lo,{channelId:t,offlineEnabled:i,serverExtension:o},"",!0),yield this.core.sendCmd("v2SignallingLeaveRoom",{tag:{channelId:t,offlineEnabled:void 0!==i&&i,serverExtension:o}}),delete this.channels[t]}))}invite(t){var i;return __awaiter(this,void 0,void 0,(function*(){if(this.checkV2(),validate(wo,t,"",!0),t.inviteeAccountId===this.core.account)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"invite: cannot be yourself"}});var o=void 0!==t.pushConfig&&(void 0!==t.pushConfig.pushEnabled&&t.pushConfig.pushEnabled);return(yield this.core.sendCmd("v2SignallingInvite",{tag:Object.assign(Object.assign({},t),{toAccid:t.inviteeAccountId,offlineEnabled:void 0===(null===(i=t.signallingConfig)||void 0===i?void 0:i.offlineEnabled)||t.signallingConfig.offlineEnabled,pushConfig:Object.assign(Object.assign({},t.pushConfig||{}),{pushEnabled:o})})})).content.data}))}cancelInvite(t){return __awaiter(this,void 0,void 0,(function*(){return this.checkV2(),validate(Do,t,"",!0),(yield this.core.sendCmd("v2SignallingCancelInvite",{tag:Object.assign(Object.assign({},t),{toAccid:t.inviteeAccountId})})).content.data}))}rejectInvite(t){return __awaiter(this,void 0,void 0,(function*(){if(validate(xo,t,"",!0),t.inviterAccountId===this.core.account)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"rejectInvite: cannot be yourself"}});yield this.core.sendCmd("v2SignallingRejectInvite",{tag:Object.assign(Object.assign({},t),{toAccid:t.inviterAccountId})})}))}acceptInvite(t){return __awaiter(this,void 0,void 0,(function*(){if(validate(Fo,t,"",!0),t.inviterAccountId===this.core.account)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"acceptInvite: cannot be yourself"}});yield this.core.sendCmd("v2SignallingAcceptInvite",{tag:Object.assign(Object.assign({},t),{toAccid:t.inviterAccountId})})}))}sendControl(t,i,o){return __awaiter(this,void 0,void 0,(function*(){validate(Uo,{channelId:t,receiverAccountId:i,serverExtension:o},"",!0),yield this.core.sendCmd("v2SignallingSendControl",{tag:{channelId:t,toAccid:i,serverExtension:o}})}))}getRoomInfoByChannelName(t){return __awaiter(this,void 0,void 0,(function*(){validate({channelName:{type:"string",allowEmpty:!1}},{channelName:t},"",!0);var i=yield this.core.sendCmd("v2SignallingGetRoomInfo",{tag:{channelName:t}}),{members:o,channelInfo:m}=i.content.data;return{channelInfo:m,members:o||[]}}))}aotoDelay(){return __awaiter(this,void 0,void 0,(function*(){var t=Object.keys(this.channels);if(0===t.length)return this.timer&&this.core.timerManager.deleteTimer(this.timer),void(this.timer=0);this.logger.log("v2Signlling:autoDelay",t);for(var i=0;i<t.length;i++){var o=t[i];try{var m=yield this.core.sendCmd("v2SignallingDelayRoom",{tag:{channelId:o}});this.channels[o]=m.content.data.channelInfo}catch(t){this.logger.warn(`signling:autoDelay ${o} failed`,t),delete this.channels[o]}}}))}v2SignallingOnlineEventHandler(t){var i=fillIdServer(t,t.content.data,"msgId","0"),o=i.msgId;!this.config.compatibleWithV1&&o&&parseInt(o)&&this.core.sendCmd("v2SignallingBatchMarkRead",{sid:15,cid:11,ids:[o]}),this.handleLeaveRoom(i),this.emit("onOnlineEvent",formatSignalingEvent(i))}v2SignallingMultiClientEventHandler(t){this.handleLeaveRoom(t.content.data),this.emit("onMultiClientEvent",formatSignalingEvent(t.content.data))}v2SignallingOfflineEventHandler(t){if(t.content.datas&&t.content.datas.length>0){if(!this.config.compatibleWithV1){var i=t.content.datas.map((t=>t.msgId));i.length>0&&this.core.sendCmd("v2SignallingBatchMarkRead",{sid:15,cid:11,ids:i})}var o=t.content.datas.map((t=>(this.handleLeaveRoom(t),formatSignalingEvent(t))));this.emit("onOfflineEvent",o)}}v2SignallingSyncChannelsHandler(t){if(this.timer=0,this.channels={},t.content.datas&&t.content.datas.length>0){var i=t.content.datas;i.forEach((t=>{var i=t.channelInfo.channelId;this.channels[i]=cloneDeep(t.channelInfo)})),this.timer||(this.timer=this.core.timerManager.addTimer(this.aotoDelay.bind(this),this.pollingInterval,-1)),this.emit("onSyncRoomInfoList",i)}}handleLeaveRoom(t){switch(t.attach.type){case 1:case 7:case 9:delete this.channels[t.channelInfo.channelId]}}}var Bo,$o={"19_1":"v2PublishEvent","14_2":"v2OnUserStatusChange","19_3":"v2SubscribeUserStatus","19_4":"v2UnsubscribeUserStatus","19_5":"v2UnsubscribeAllUserStatus","19_6":"v2QuerySubscribeEvent","19_7":"v2QueryAllSubscribeEvent","14_9":"v2OnMultiUserStatusChange"},jo="V2NIMSubscriptionService",Go={eventType:{id:1,retType:"number"},statusType:{id:2,retType:"number"},uniqueId:3,extension:4,duration:{id:5,retType:"number"},onlineOnly:{id:6,retType:"boolean",converter:t=>t?1:2},multiSync:{id:7,retType:"boolean",converter:boolToInt},publishTime:{id:10,retType:"number"},serverId:11,clientType:{id:12,retType:"number"},serverExtension:13,extensionReceived:14,accountId:103},qo={eventType:{id:1,retType:"number"},duration:{id:2,retType:"number"},immediateSync:{id:3,retType:"number",converter:boolToInt},accountId:102,subscribeTime:{id:105,retType:"number"}},Ho={v2PublishEvent:{sid:19,cid:1,service:jo,params:[{type:"Property",name:"tag",reflectMapper:Go}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Go)}]},v2OnUserStatusChange:{sid:14,cid:2,service:jo,response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Go)}]},v2SubscribeUserStatus:{sid:19,cid:3,service:jo,params:[{type:"Property",name:"tag",reflectMapper:qo},{type:"StrArray",name:"accountIds"}],response:[{type:"StrArray",name:"failedList"}]},v2UnsubscribeUserStatus:{sid:19,cid:4,service:jo,params:[{type:"Property",name:"tag",reflectMapper:qo},{type:"StrArray",name:"accountIds"}],response:[{type:"StrArray",name:"failedList"}]},v2UnsubscribeAllUserStatus:{sid:19,cid:5,service:jo,params:[{type:"Property",name:"tag",reflectMapper:qo}]},v2QuerySubscribeEvent:{sid:19,cid:6,service:jo,params:[{type:"Property",name:"tag",reflectMapper:qo},{type:"StrArray",name:"accountIds"}],response:[{type:"PropertyArray",name:"data",reflectMapper:invertSerializeItem(qo)}]},v2QueryAllSubscribeEvent:{sid:19,cid:7,service:jo,params:[{type:"Property",name:"tag",reflectMapper:qo}],response:[{type:"PropertyArray",name:"data",reflectMapper:invertSerializeItem(qo)}]},v2OnMultiUserStatusChange:{sid:14,cid:9,service:jo,response:[{type:"PropertyArray",name:"data",reflectMapper:invertSerializeItem(Go)}]}},zo={accountIds:{type:"array",required:!0,itemType:"string",min:1,max:100},duration:{type:"number",required:!1,min:60,max:2592e3},immediateSync:{type:"boolean",required:!1}},Yo={accountIds:{type:"array",required:!1,itemType:"string",max:100}},Jo={statusType:{type:"number",required:!0,min:1e4,max:2147483647},duration:{type:"number",required:!1,min:60,max:604800},extension:{type:"jsonstr",required:!1},onlineOnly:{type:"boolean",required:!1},multiSync:{type:"boolean",required:!1}};class V2NIMSubscriptionServiceImpl extends V2Service{constructor(t){super("V2NIMSubscriptionService",t),"v2"===this.core.options.apiVersion&®isterParser({cmdMap:$o,cmdConfig:Ho})}emit(t,...i){var o=`${this.name}::emit ${t.toString()}`;return this.logger.log(`${o}`,...i),super.emit(t,...i)}subscribeUserStatus(t){return __awaiter(this,void 0,void 0,(function*(){return this.checkLogin(),this.checkV2(),validate(zo,t,"",!0),(yield this.core.sendCmd("v2SubscribeUserStatus",{tag:{eventType:1,duration:t.duration||60,immediateSync:void 0!==t.immediateSync&&t.immediateSync},accountIds:t.accountIds})).content.failedList}))}unsubscribeUserStatus(t){return __awaiter(this,void 0,void 0,(function*(){this.checkLogin(),this.checkV2(),validate(Yo,t,"",!0);var i=[];t.accountIds.length>0?i=(yield this.core.sendCmd("v2UnsubscribeUserStatus",{tag:{eventType:1},accountIds:t.accountIds})).content.failedList:(yield this.core.sendCmd("v2UnsubscribeAllUserStatus",{tag:{eventType:1}}),i=[]);return i}))}publishCustomUserStatus(t){return __awaiter(this,void 0,void 0,(function*(){return this.checkLogin(),this.checkV2(),validate(Jo,t,"",!0),(yield this.core.sendCmd("v2PublishEvent",{tag:Object.assign(Object.assign({},t),{eventType:1,uniqueId:Pe(),duration:t.duration||60,onlineOnly:void 0===t.onlineOnly||t.onlineOnly,multiSync:void 0!==t.multiSync&&t.multiSync})})).content.data}))}queryUserStatusSubscriptions(t){return __awaiter(this,void 0,void 0,(function*(){this.checkLogin(),this.checkV2(),validate({accountIds:{type:"array",required:!0,itemType:"string",max:3e3}},{accountIds:t},"",!0);var i=[];if(t.length>0)for(var o=0;o<t.length;o+=100){var m=yield this.core.sendCmd("v2QuerySubscribeEvent",{tag:{eventType:1},accountIds:t.slice(o,o+100)});i=i.concat(m.content.data.map((t=>({accountId:t.accountId,subscribeTime:t.subscribeTime,duration:t.duration}))))}else{var h=yield this.core.sendCmd("v2QueryAllSubscribeEvent",{tag:{eventType:1}});i=i.concat(h.content.data.map((t=>({accountId:t.accountId,subscribeTime:t.subscribeTime,duration:t.duration}))))}return i}))}v2OnUserStatusChangeHandler(t){var i=t.content.data,{eventType:o,extensionReceived:m}=i,h=__rest(i,["eventType","extensionReceived"]);1===o?this.emit("onUserStatusChanged",[Object.assign(Object.assign({},h),{extension:m})]):this.logger.log("v2OnUserStatusChangeHandler eventType = ",o,"msgEvent = ",i)}v2OnMultiUserStatusChangeHandler(t){var i=t.content.data.filter((t=>1===t.eventType)).map((t=>{var{eventType:i,extensionReceived:o}=t,m=__rest(t,["eventType","extensionReceived"]);return Object.assign(Object.assign({},m),{extension:o})}));i.length>0&&this.emit("onUserStatusChanged",i)}}!function(t){t[t.V2NIM_PROXY_REQUEST_METHOD_GET=1]="V2NIM_PROXY_REQUEST_METHOD_GET",t[t.V2NIM_PROXY_REQUEST_METHOD_POST=2]="V2NIM_PROXY_REQUEST_METHOD_POST",t[t.V2NIM_PROXY_REQUEST_METHOD_PUT=3]="V2NIM_PROXY_REQUEST_METHOD_PUT",t[t.V2NIM_PROXY_REQUEST_METHOD_DELETE=4]="V2NIM_PROXY_REQUEST_METHOD_DELETE"}(Bo||(Bo={}));var Ko={"22_1":"v2ProxyRequest","22_2":"v2ProxyOnRequest"},Wo={zone:1,path:2,method:3,header:4,body:5},Xo={v2ProxyRequest:{sid:22,cid:1,service:"V2NIMPassthroughService",params:[{type:"Property",name:"tag",reflectMapper:Wo}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Wo)}]},v2ProxyOnRequest:{sid:22,cid:2,service:"V2NIMPassthroughService",response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem({fromAccountId:1,body:2,time:{id:3,retType:"number"}})}]}},Qo={path:{type:"string",allowEmpty:!1},zone:{type:"string",required:!1},method:{type:"enum",values:[Bo.V2NIM_PROXY_REQUEST_METHOD_DELETE,Bo.V2NIM_PROXY_REQUEST_METHOD_GET,Bo.V2NIM_PROXY_REQUEST_METHOD_POST,Bo.V2NIM_PROXY_REQUEST_METHOD_PUT],required:!1},header:{type:"jsonstr",required:!1},body:{type:"string",required:!1}};class V2NIMPassthroughServiceImpl extends V2Service{constructor(t){super("V2NIMPassthroughService",t),registerParser({cmdMap:Ko,cmdConfig:Xo})}emit(t,...i){var o=`${this.name}::emit ${t.toString()}`;return this.logger.log(`${o}`,...i),super.emit(t,...i)}httpProxy(t){return __awaiter(this,void 0,void 0,(function*(){if(validate(Qo,t,"",!0),t.method===Bo.V2NIM_PROXY_REQUEST_METHOD_GET&&t.body||t.method===Bo.V2NIM_PROXY_REQUEST_METHOD_POST&&!t.body||t.method===Bo.V2NIM_PROXY_REQUEST_METHOD_PUT&&!t.body)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:`method ${t.method}, incorrect body`}});return(yield this.core.sendCmd("v2ProxyRequest",{tag:t})).content.data}))}v2ProxyOnRequestHandler(t){var{data:i}=t.content;this.emit("onProxyNotify",i)}}var Zo=NIM$1;Zo.registerService(class V2NIMLoginServiceImpl extends V2Service{constructor(t,i={}){var o;super("V2NIMLoginService",t),this.account="",this.previousLoginAccount="",this.token="",this.deviceId="",this.clientSession="",this.processId="",this.kickedDetail=null,this.binaryWebsocket=!0,this.core._registerDep(MiscService,"misc"),registerParser({cmdMap:ze,cmdConfig:Ke}),"v2"===t.options.apiVersion&&(registerParser({cmdMap:Ye,cmdConfig:We}),this.core.auth=this),this.previousLoginManager=new PromiseManager,this.doLoginStepsManager=new PromiseManager,this.loginTimerManager=new TimerManager,this.loginOption=Object.assign({},ht),this.config={lbsUrls:mt,linkUrl:"weblink.netease.im:443",linkSSL:!0},this.setOptions(i),t.V2NIMLoginService=this,!1!==this.core.options.binaryWebsocket&&"function"==typeof Uint8Array?(this.binaryWebsocket=!0,o=new V2BinaryClientSocket(this.core)):(this.binaryWebsocket=!1,o=new V2ClientSocket(this.core)),this.clientSocket=o,"v2"===this.core.options.apiVersion&&(this.core.clientSocket=o),this.lifeCycle=new V2NIMLoginLifeCycle(t),this.reconnect=new V2NIMLoginReconnect(t),this.lbs=new V2NIMLoginLbs(t),this.authenticator=new V2NIMLoginAuthenticator(t),this.dataSync=new V2NIMLoginDataSync(t)}get hasSettingService(){var t;return!!(null===(t=this.core.V2NIMSettingService)||void 0===t?void 0:t.name)}setOptions(t){var i,o,m;validate({lbsUrls:{type:"array",itemType:"string",min:1,required:!1},linkUrl:{type:"string",allowEmpty:!1,required:!1}},t,"",!0),this.config=assignOptions(this.config,t),null===(o=null===(i=this.core.clientSocket)||void 0===i?void 0:i.setLinkSSL)||void 0===o||o.call(i,null===(m=this.config.linkSSL)||void 0===m||m);var h="",u="";this.config.isFixedDeviceId?(h=Re.localStorage.getItem("__NIM_DEVC_ID__")||Pe(),u=Re.localStorage.getItem("__NIM_CLIENT_SESSION_ID__")||Pe(),Re.localStorage.setItem("__NIM_DEVC_ID__",h),Re.localStorage.setItem("__NIM_CLIENT_SESSION_ID__",u)):(h=Pe(),u=Pe()),this.deviceId=h,this.clientSession=u,this.core.reporter.setConfig({common:{dev_id:h}})}reset(){this.account="",this.token="",this.processId="",this.lbs.reset(),this.reconnect.destroy(),this.authenticator.reset(),this.authenticator.clearLastLoginClient(),this.dataSync.reset()}login(t,i,o={}){return __awaiter(this,void 0,void 0,(function*(){this._checkApiVersion();var m=Re.getSystemInfo()||{},h=m.os?m.os.toLowerCase():"";if("React Native"===Re.platform&&"android"===h&&this.hasSettingService&&get(this.core.V2NIMSettingService,"push.offlinePushPlugin"))try{this.deviceInfo=yield this.core.V2NIMSettingService.push.getRNDeviceInfo()}catch(t){this.logger.error(t)}if("string"!=typeof t||""===t.trim())throw new ValidateErrorV2({detail:{reason:"Account must be string"}});if(validate(pt,o,"",!0),0===(o=assignOptions(ht,o)).authType&&!i)throw new ValidateErrorV2({detail:{reason:"When authType is 0, token cannot be empty"}});if(""!==this.previousLoginAccount&&this.previousLoginAccount!==t&&this.core._clearModuleData(),0===this.getLoginStatus())this.logger.log(`V2NIMLoginService::login:allowLogin:${t}`,o);else{if(1===this.getLoginStatus())return this.smoothForLogined(t,i,o);if(2===this.getLoginStatus())return this.smoothForLogining(t,i,o)}this.account=t,this.previousLoginAccount=t,this.token=i,this.processId=Pe(),this.loginOption=assignOptions(ht,o),this.kickedDetail=null,this.loginTimerManager.destroy(),this.loginTimerManager.addTimer((()=>{var t=new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_TIMEOUT,detail:{reason:"Login API timeout"}});this.doLoginStepsManager.clear(t),this.previousLoginManager.clear(t),this.originLoginPromise=void 0,this.lifeCycle.processEvent("exited",t)}),this.loginOption.timeout>0?this.loginOption.timeout:6e4,1);try{yield this.multiTryDoLogin(),this.loginTimerManager.destroy()}catch(t){throw this.loginTimerManager.destroy(),t}}))}setAppVisibility(){this.logger.warn("V2NIMLoginService::setAppVisibility is deprecated @v10.9.40")}getChatroomLinkAddress(t,i){return __awaiter(this,void 0,void 0,(function*(){return validate({roomId:{type:"string",regExp:/^\d+$/,required:!0,allowEmpty:!1},miniProgram:{type:"boolean",required:!1}},{roomId:t,miniProgram:i},"",!0),i=void 0===i?pendingIsMiniappEnv():i,(yield this.clientSocket.sendCmd("v2GetChatroomLinkAddress",{roomId:t,miniProgram:i})).content.linkAddress}))}multiTryDoLogin(t){return __awaiter(this,void 0,void 0,(function*(){for(var i=new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INTERNAL,detail:{reason:"loginFailed"}}),o=0;o<=this.loginOption.retryCount;o++){var m=`V2NIMLoginService::times of login try: ${o}`;o>0?this.logger.warn(m):this.logger.log(m);try{this.originLoginPromise=t||this.doLogin(!1),t=void 0;var h=yield this.previousLoginManager.add(this.originLoginPromise);return this.core.reporter.reportTraceEnd("login",!0),this.doLoginStepsManager.clear(),this.previousLoginManager.clear(),this.originLoginPromise=void 0,h}catch(t){if(i=t||i,this.logger.error(`V2NIMLoginService::login failed, times of login try: ${o}, err.code: ${null==i?void 0:i.code}, err.message: "${null==i?void 0:i.message}"`),i.code!==Ee.V2NIM_ERROR_CODE_CANCELLED&&this.core.reporter.reportTraceEnd("login",!1),this.reconnect.clearReconnectTimer(),this.checkLoginTerminalCode(i&&i.code))throw this.lifeCycle.processEvent("exited",i),i;i&&399===i.code&&this.lbs.reset()}}throw this.lifeCycle.processEvent("exited",i),i}))}doLogin(t){var i,o;return __awaiter(this,void 0,void 0,(function*(){var m=!!t||this.authenticator.checkAutoLogin(this.loginOption.forceMode);this.core.reporter.reportTraceCancel("login"),this.core.reporter.reportTraceStart("login",m?{user_id:this.account,action:"auto_login",process_id:this.processId,binary_websocket:this.binaryWebsocket}:{user_id:this.account,action:"manual_login",process_id:this.processId,binary_websocket:this.binaryWebsocket}),this.core.reporter.reportTraceUpdateV2("login",{code:0,description:JSON.stringify(this.loginOption),operation_type:"conf_init",succeed:!0,duration:0,target:""},{asyncParams:Re.net.getNetworkStatus()});var h=yield this.doLoginStepsManager.add(this.lbs.getLbsInfos());yield this.doLoginStepsManager.add(this.clientSocket.connect(h,t));var u=yield this.doLoginStepsManager.add(this.authenticator.verifyAuthentication(m));if(this.processId=Pe(),this.clientSocket.resetSocketConfig(),this.reconnect.reset(),this.dataSync.reset(),this.lifeCycle.processEvent("loginSucc",void 0,Object.assign(Object.assign({},u),{isReconnect:t})),this.clientSocket.ping(),this.core.abtest.abtRequest(),"function"==typeof(null===(i=this.core.V2NIMClientAntispamUtil)||void 0===i?void 0:i.downloadLocalAntiSpamVocabs)&&this.core.V2NIMClientAntispamUtil.downloadLocalAntiSpamVocabs(),"function"==typeof(null===(o=this.core.cloudStorage)||void 0===o?void 0:o.init))try{yield this.core.cloudStorage.init(u.timestamp)}catch(t){this.logger.warn("doLogin::cloudStorage init error",t)}return u}))}smoothForLogined(t,i,o){return __awaiter(this,void 0,void 0,(function*(){var m=this.checkIsSameLogin(t,i,o);return this.logger.warn(`V2NIMLoginService::smoothForLogined:Logined, isSameLogin ${m}`),m?void 0:(yield this.logout(),this.login(t,i,o))}))}smoothForLogining(t,i,o){return __awaiter(this,void 0,void 0,(function*(){var m=this.checkIsSameLogin(t,i,o);if(this.logger.warn(`V2NIMLoginService::smoothForLogining:Logining progress exists, abort the previous login attempt and start next attempt, isSameLogin ${m}`),this.previousLoginManager.clear(),this.reconnect.reset(),this.account=t,this.previousLoginAccount=t,this.token=i,this.loginOption=assignOptions(this.loginOption,o),!m)return this.doLoginStepsManager.clear(),this.clientSocket.doDisconnect(Ze.ACTIVE,"Aborted"),this.reset(),this.lifeCycle.processEvent("logout"),yield Promise.resolve(),this.login(t,i,o);if(!this.originLoginPromise)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_INTERNAL,detail:{reason:"NoPreviousLoginExists"}});this.reconnect.reset(),yield Promise.resolve(),yield this.multiTryDoLogin(this.originLoginPromise)}))}checkIsSameLogin(t,i,o){return this.account===t&&this.loginOption.authType===o.authType&&(0!==o.authType||this.token===i)}logout(){return __awaiter(this,void 0,void 0,(function*(){this._checkApiVersion(),this.doLoginStepsManager.clear(),this.previousLoginManager.clear(),this.loginTimerManager.destroy(),this.originLoginPromise=void 0;var t=this.getConnectStatus(),i=this.getLoginStatus();switch(i){case 1:try{yield this.clientSocket.sendCmd("v2Logout",void 0,{timeout:1e3}),this.clientSocket.doDisconnect(Ze.ACTIVE,"UserActiveDisconnect"),this.core._clearModuleData(),this.lifeCycle.processEvent("logout")}catch(t){this.logger.error("Instance::disconnect sendCmd:logout error",t),this.clientSocket.doDisconnect(Ze.ACTIVE,"UserActiveDisconnect"),this.core._clearModuleData(),this.lifeCycle.processEvent("logout")}break;case 2:case 3:this.clientSocket.doDisconnect(Ze.ACTIVE,"UserActiveDisconnect"),this.core._clearModuleData(),this.lifeCycle.processEvent("logout");break;case 0:throw this.core._clearModuleData(),new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_ILLEGAL_STATE,detail:{reason:`Illegal logout. loginStatus ${i}. connectStatus ${t}`}});default:throw this.core._clearModuleData(),new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_ILLEGAL_STATE,detail:{reason:`Illegal logout. illegal status: loginStatus ${i}. connectStatus ${t}`}})}}))}getConnectStatus(){return this.lifeCycle.getConnectStatus()}getLoginStatus(){return this.lifeCycle.getLoginStatus()}getLoginUser(){return this.account}getLoginClients(){return function uniqBy(t,i){t=t||[],i=i||"";for(var o=[],m=[],h=0;h<t.length;h++){var u=t[h][i];-1===m.indexOf(u)&&(m.push(u),o.push(t[h]))}return o}(this.authenticator.loginClients,"clientId").map((t=>pick(t,["type","os","timestamp","customTag","customClientType","clientId","clientIP"])))}getCurrentLoginClient(){var t;if(null===(t=this.authenticator.loginClientOfThisConnection)||void 0===t?void 0:t.clientId)return pick(this.authenticator.loginClientOfThisConnection,["type","os","timestamp","customTag","customClientType","clientId","clientIP"])}getDataSync(){var t=this.dataSync.datas;return t&&t.length>0?t.map((t=>({type:t.type,state:t.state}))):null}setReconnectDelayProvider(t){this.reconnect._setReconnectDelayProvider(t)}kickOffline(t){return __awaiter(this,void 0,void 0,(function*(){if(this._checkApiVersion(),validate({clientId:{type:"string",allowEmpty:!1}},t,"",!0),0===get(yield this.clientSocket.sendCmd("v2KickOffline",{clientIds:[t.clientId]}),"content.clientIds.length"))throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_REQUEST_FAILED})}))}getKickedOfflineDetail(){return this.kickedDetail}checkLoginTerminalCode(t){return this.authenticator.checkLoginTerminalCode(t)}checkIllegalState(){if(!this.getLoginUser())throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_ILLEGAL_STATE})}_checkApiVersion(){if("v2"!==this.core.options.apiVersion)throw new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_MISUSE,detail:{reason:'apiVersion is not "v2"'}})}v2LoginHandler(t){if(t.error)throw this.clientSocket.doDisconnect(Ze.ACTIVE,t.error),t.error;return t}v2LoginClientChangeHandler(t){this.authenticator.changeLoginClient(parseInt(t.content.state),t.content.datas)}nimLoginClientChangeHandler(t){this.authenticator.changeLoginClient(parseInt(t.content.state),t.content.datas)}qchatLoginClientChangeHandler(t){var i=parseInt(t.content.state);i=1===i?2:3,this.authenticator.changeLoginClient(i,[t.content.data])}v2BeKickedHandler(t){if(t.error)this.core.logger.error("v2BeKickedHandler error, ",t.error);else{var i=function formatBeKickedTag(t){return format({reason:{type:"number"},clientType:{type:"number"},customClientType:{type:"number"}},t)}(t.content);this.core.logger.warn("v2Bekicked::",i),this.kickedDetail=i,this.clientSocket.doDisconnect(Ze.KICKED,i),this.core._clearModuleData(),this.lifeCycle.processEvent("kicked",new V2NIMErrorImpl({code:Ee.V2NIM_ERROR_CODE_DISCONNECT,detail:{reason:"disconnect due to kicked"}}),i),this.emit("onKickedOffline",i)}}emit(t,...i){var o=`${this.name}::emit ${t.toString()}`;if("onLoginFailed"===t||"onDisconnected"===t||"onConnectFailed"===t){var m=i[0];this.logger.log(`${o}`,m.toString())}else if("onDataSync"===t){var h=i[2];this.logger.log(`${o}`,i[0],i[1],h&&h.toString())}else this.logger.log(`${o}`,...i);return super.emit(t,...i)}},"V2NIMLoginService"),Zo.registerService(class V2NIMSyncServiceImpl extends V2Service{constructor(t){super("V2NIMSyncService",t),this.teamKey=["teams","superTeams","myTeamMembers","mySuperTeamMembers","teamApplyList"],this.config={},this.timetags={},"v2"===this.core.options.apiVersion&&(registerParser({cmdMap:ut,cmdConfig:gt}),this.setListener())}reset(){this.timetags={}}setListener(){this.core.eventBus.on("V2NIMLoginService/loginLifeCycleLoginSucc",(()=>{this.doSync()})),this.core.eventBus.on("V2NIMSync/updateTimetag",(t=>{Object.keys(t).forEach((i=>{t[i]>(this.timetags[i]||0)&&(this.timetags[i]=t[i])}))}))}setOptions(t){var i=this.core,o=!(!i.V2NIMConversationService.name&&!i.V2NIMLocalConversationService.name),m=!!i.V2NIMFriendService.name&&get(i.otherOptions,"V2NIMFriendServiceConfig.enableServerV2FriendAddApplication"),h=!!i.V2NIMTeamService.name&&get(i.otherOptions,"V2NIMTeamServiceConfig.enableServerV2TeamJoinActionInfo");return this.config=Object.assign({myInfo:!!i.V2NIMUserService.name,offlineMsgs:!!i.V2NIMMessageService.name,roamingMsgs:!!i.V2NIMMessageService.name,relations:!!i.V2NIMUserService.name,friends:!!i.V2NIMFriendService.name,friendUsers:!!i.V2NIMUserService.name,friendOperatorList:m,friendApplyInfoDeleteOrClear:m,msgReceipts:!!i.V2NIMMessageService.name,p2pMsgReceiptV2:!!i.V2NIMMessageService.name,broadcastMsgs:!!i.V2NIMNotificationService.name,recallMsg:!!i.V2NIMMessageService.name,sessionAck:o,superTeamSessionAck:o,stickTopSessions:o,superTeamRoamingMsgs:!!i.V2NIMTeamService.name,deleteSuperTeamMsg:!!i.V2NIMTeamService.name,deleteSelfMsgs:!!i.V2NIMMessageService.name,sessionHistoryMsgsDelete:!!i.V2NIMMessageService.name,avSignal:!!i.V2NIMSignallingService.name,teams:!!i.V2NIMTeamService.name,superTeams:!!i.V2NIMTeamService.name,teamApplyList:h,myTeamMembers:!!i.V2NIMTeamService.name,mySuperTeamMembers:!!i.V2NIMTeamService.name,donnop:!!i.V2NIMSettingService.name,p2pTeamModifyMessage:!!i.V2NIMMessageService.name,superTeamModifyMessage:!!i.V2NIMMessageService.name},t),this.config}doBasicSync(){return __awaiter(this,void 0,void 0,(function*(){var t=Object.keys(this.config).filter((t=>!this.teamKey.includes(t)&&this.config[t])),i=this.genSyncParams(t);this.logger.log("V2Sync:basic",i);var o=(yield this.core.clientSocket.sendCmd("v2NIMSync",{tag:i})).content.timetag;this.setTimetags(o,t.filter((t=>"broadcastMsgs"!==t))),yield this.delaySyncDone(),yield this.handleImmediate(),this.core.logger.log("sync::basic sync complete in",o)}))}doTeamSync(){return __awaiter(this,void 0,void 0,(function*(){var t=this.teamKey.filter((t=>this.config[t]));if(0!==t.length){var i=this.genSyncParams(t);this.core.eventBus.emit("V2NIMTeamService/onSyncStarted"),this.logger.log("V2Sync:team",i);var o=null;try{o=yield this.core.clientSocket.sendCmd("v2NIMSync",{tag:i})}catch(t){throw this.core.eventBus.emit("V2NIMTeamService/onSyncFailed",t),t}this.core.eventBus.emit("V2NIMTeamService/onSyncFinished");var m=o.content.timetag;this.setTimetags(m,this.teamKey),this.core.logger.log("sync::team sync complete in",m)}}))}doQchatSync(){return __awaiter(this,void 0,void 0,(function*(){var t=yield this.core.clientSocket.sendCmd("v2QChatSync",{tag:{systemNotification:0}});this.core.logger.log("sync::qchat sync complete in",t.content.timetag)}))}doSync(){return __awaiter(this,void 0,void 0,(function*(){var t=get(this.core,"V2NIMLoginService.authenticator.loginClientOfThisConnection.loginType");if(void 0!==t){if(this.logger.log(`sync::doSync:type ${t}`),this.core.V2NIMLoginService.dataSync.switchDataSync({type:1,state:2,subType:"mainSync"}),1===t)try{yield this.doBasicSync(),yield this.doTeamSync()}catch(t){return void this.doSyncComplete(t)}else if(2===t)try{yield this.doQchatSync()}catch(t){return void this.doSyncComplete(t)}else{if(3!==t)return;try{yield this.doBasicSync(),yield this.doTeamSync(),yield this.doQchatSync()}catch(t){return void this.doSyncComplete(t)}}this.doSyncComplete()}else this.logger.warn("sync::doSync: no loginType, stop sync")}))}doSyncComplete(t){t&&this.core.logger.log("sync::doSync complete but got error",t),this.core.V2NIMLoginService.dataSync.switchDataSync({type:1,state:3,error:t,subType:"mainSync"})}genSyncParams(t){return t.reduce(((t,i)=>{var o=i;return t[o]=this.timetags[o]||0,t}),{})}setTimetags(t,i){i.forEach((i=>{this.timetags[i]=t}))}handleImmediate(){return this.core.session&&this.core.session.onSyncDone&&this.core.session.onSyncDone(),Promise.resolve()}delaySyncDone(){var{hostEnvEnum:t}=Re.getSystemInfo();return 102===t?(this.core.logger.log("sync: emit ALIAPP sycnHandler, handle later"),new Promise((t=>{setTimeout((()=>{t()}),100)}))):Promise.resolve()}},"V2NIMSyncService");export{Zo as NIM,V2NIMAIServiceImpl as V2NIMAIService,Te as V2NIMConst,V2NIMConversationGroupServiceImpl as V2NIMConversationGroupService,V2NIMConversationServiceImpl as V2NIMConversationService,V2NIMFriendServiceImpl as V2NIMFriendService,V2NIMLocalConversationServiceImpl as V2NIMLocalConversationService,V2NIMMessageConverterImpl as V2NIMMessageConverter,V2NIMMessageExtendUtil,V2NIMMessageLogUtil,V2NIMMessageServiceImpl as V2NIMMessageService,V2NIMNotificationServiceImpl as V2NIMNotificationService,V2NIMPassthroughServiceImpl as V2NIMPassthroughService,V2NIMSettingServiceImpl as V2NIMSettingService,V2NIMSignallingServiceImpl as V2NIMSignallingService,V2NIMStorageServiceImpl as V2NIMStorageService,V2NIMSubscriptionServiceImpl as V2NIMSubscriptionService,V2NIMTeamServiceImpl as V2NIMTeamService,V2NIMUserServiceImpl as V2NIMUserService,YSFServiceImpl as YSFService,getAdapterForAli as aliAdapters,getAdapterForBaidu as baiduAdapters,getAdapter$1 as browserAdapters,getAdapter as miniappAdapters,setAdapters,getAdapterForTt as ttAdapters,getAdapter$2 as uniAppAdapters,getAdapterForWx as wxAdapters};