UNPKG

nim-web-sdk-ng

Version:

Yunxin IM SDK next generation

22 lines 659 kB
/**
 * 
 *   Version: 10.9.41
 * 
 *   Git Hash: 5b4fa64fd28f6f2c4dc5e957f39887f24696a2ae
 * 
 *   Created At: 8/14/2025, 7:24:13 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 o={exports:{}};return t(o,o.exports),o.exports}var o,a,m,u,h,g,I,M,_,E,S,T,C,N,A,O,R,b,V,k,P,L,w,D,U,x,B,$,j,G,q,H,z,Y,K,W,J,X,Q,Z,ee,te,re,ie,oe,se,ne,ae,ce,de,le,pe,me,ue,he,ge,ve=createCommonjsModule((function(t){var o=Object.prototype.hasOwnProperty,a="~";function Events(){}function EE(t,o,a){this.fn=t,this.context=o,this.once=a||!1}function addListener(t,o,m,u,h){if("function"!=typeof m)throw new TypeError("The listener must be a function");var g=new EE(m,u||t,h),I=a?a+o:o;return t._events[I]?t._events[I].fn?t._events[I]=[t._events[I],g]:t._events[I].push(g):(t._events[I]=g,t._eventsCount++),t}function clearEvent(t,o){0==--t._eventsCount?t._events=new Events:delete t._events[o]}function EventEmitter(){this._events=new Events,this._eventsCount=0}Object.create&&(Events.prototype=Object.create(null),(new Events).__proto__||(a=!1)),EventEmitter.prototype.eventNames=function eventNames(){var t,m,u=[];if(0===this._eventsCount)return u;for(m in t=this._events)o.call(t,m)&&u.push(a?m.slice(1):m);return Object.getOwnPropertySymbols?u.concat(Object.getOwnPropertySymbols(t)):u},EventEmitter.prototype.listeners=function listeners(t){var o=a?a+t:t,m=this._events[o];if(!m)return[];if(m.fn)return[m.fn];for(var u=0,h=m.length,g=new Array(h);u<h;u++)g[u]=m[u].fn;return g},EventEmitter.prototype.listenerCount=function listenerCount(t){var o=a?a+t:t,m=this._events[o];return m?m.fn?1:m.length:0},EventEmitter.prototype.emit=function emit(t,o,m,u,h,g){var I=a?a+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,o),!0;case 3:return E.fn.call(E.context,o,m),!0;case 4:return E.fn.call(E.context,o,m,u),!0;case 5:return E.fn.call(E.context,o,m,u,h),!0;case 6:return E.fn.call(E.context,o,m,u,h,g),!0}for(_=1,M=new Array(S-1);_<S;_++)M[_-1]=arguments[_];E.fn.apply(E.context,M)}else{var T,C=E.length;for(_=0;_<C;_++)switch(E[_].once&&this.removeListener(t,E[_].fn,void 0,!0),S){case 1:E[_].fn.call(E[_].context);break;case 2:E[_].fn.call(E[_].context,o);break;case 3:E[_].fn.call(E[_].context,o,m);break;case 4:E[_].fn.call(E[_].context,o,m,u);break;default:if(!M)for(T=1,M=new Array(S-1);T<S;T++)M[T-1]=arguments[T];E[_].fn.apply(E[_].context,M)}}return!0},EventEmitter.prototype.on=function on(t,o,a){return addListener(this,t,o,a,!1)},EventEmitter.prototype.once=function once(t,o,a){return addListener(this,t,o,a,!0)},EventEmitter.prototype.removeListener=function removeListener(t,o,m,u){var h=a?a+t:t;if(!this._events[h])return this;if(!o)return clearEvent(this,h),this;var g=this._events[h];if(g.fn)g.fn!==o||u&&!g.once||m&&g.context!==m||clearEvent(this,h);else{for(var I=0,M=[],_=g.length;I<_;I++)(g[I].fn!==o||u&&!g[I].once||m&&g[I].context!==m)&&M.push(g[I]);M.length?this._events[h]=1===M.length?M[0]:M:clearEvent(this,h)}return this},EventEmitter.prototype.removeAllListeners=function removeAllListeners(t){var o;return t?(o=a?a+t:t,this._events[o]&&clearEvent(this,o)):(this._events=new Events,this._eventsCount=0),this},EventEmitter.prototype.off=EventEmitter.prototype.removeListener,EventEmitter.prototype.addListener=EventEmitter.prototype.on,EventEmitter.prefixed=a,EventEmitter.EventEmitter=EventEmitter,t.exports=EventEmitter})),fe=createCommonjsModule((function(t,o){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={},o=Object.prototype,a=o.hasOwnProperty,m="function"==typeof Symbol?Symbol:{},u=m.iterator||"@@iterator",h=m.asyncIterator||"@@asyncIterator",g=m.toStringTag||"@@toStringTag";function define(t,o,a){return Object.defineProperty(t,o,{value:a,enumerable:!0,configurable:!0,writable:!0}),t[o]}try{define({},"")}catch(t){define=function(t,o,a){return t[o]=a}}function wrap(t,o,a,m){var u=o&&o.prototype instanceof Generator?o:Generator,h=Object.create(u.prototype),g=new Context(m||[]);return h._invoke=function(t,o,a){var m="suspendedStart";return function(u,h){if("executing"===m)throw new Error("Generator is already running");if("completed"===m){if("throw"===u)throw h;return doneResult()}for(a.method=u,a.arg=h;;){var g=a.delegate;if(g){var M=maybeInvokeDelegate(g,a);if(M){if(M===I)continue;return M}}if("next"===a.method)a.sent=a._sent=a.arg;else if("throw"===a.method){if("suspendedStart"===m)throw m="completed",a.arg;a.dispatchException(a.arg)}else"return"===a.method&&a.abrupt("return",a.arg);m="executing";var _=tryCatch(t,o,a);if("normal"===_.type){if(m=a.done?"completed":"suspendedYield",_.arg===I)continue;return{value:_.arg,done:a.done}}"throw"===_.type&&(m="completed",a.method="throw",a.arg=_.arg)}}}(t,a,g),h}function tryCatch(t,o,a){try{return{type:"normal",arg:t.call(o,a)}}catch(t){return{type:"throw",arg:t}}}t.wrap=wrap;var I={};function Generator(){}function GeneratorFunction(){}function GeneratorFunctionPrototype(){}var M={};define(M,u,(function(){return this}));var _=Object.getPrototypeOf,E=_&&_(_(values([])));E&&E!==o&&a.call(E,u)&&(M=E);var S=GeneratorFunctionPrototype.prototype=Generator.prototype=Object.create(M);function defineIteratorMethods(t){["next","throw","return"].forEach((function(o){define(t,o,(function(t){return this._invoke(o,t)}))}))}function AsyncIterator(t,o){function invoke(m,u,h,g){var I=tryCatch(t[m],t,u);if("throw"!==I.type){var M=I.arg,_=M.value;return _&&"object"==typeof _&&a.call(_,"__await")?o.resolve(_.__await).then((function(t){invoke("next",t,h,g)}),(function(t){invoke("throw",t,h,g)})):o.resolve(_).then((function(t){M.value=t,h(M)}),(function(t){return invoke("throw",t,h,g)}))}g(I.arg)}var m;this._invoke=function(t,a){function callInvokeWithMethodAndArg(){return new o((function(o,m){invoke(t,a,o,m)}))}return m=m?m.then(callInvokeWithMethodAndArg,callInvokeWithMethodAndArg):callInvokeWithMethodAndArg()}}function maybeInvokeDelegate(t,o){var a=t.iterator[o.method];if(void 0===a){if(o.delegate=null,"throw"===o.method){if(t.iterator.return&&(o.method="return",o.arg=void 0,maybeInvokeDelegate(t,o),"throw"===o.method))return I;o.method="throw",o.arg=new TypeError("The iterator does not provide a 'throw' method")}return I}var m=tryCatch(a,t.iterator,o.arg);if("throw"===m.type)return o.method="throw",o.arg=m.arg,o.delegate=null,I;var u=m.arg;return u?u.done?(o[t.resultName]=u.value,o.next=t.nextLoc,"return"!==o.method&&(o.method="next",o.arg=void 0),o.delegate=null,I):u:(o.method="throw",o.arg=new TypeError("iterator result is not an object"),o.delegate=null,I)}function pushTryEntry(t){var o={tryLoc:t[0]};1 in t&&(o.catchLoc=t[1]),2 in t&&(o.finallyLoc=t[2],o.afterLoc=t[3]),this.tryEntries.push(o)}function resetTryEntry(t){var o=t.completion||{};o.type="normal",delete o.arg,t.completion=o}function Context(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(pushTryEntry,this),this.reset(!0)}function values(t){if(t){var o=t[u];if(o)return o.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var m=-1,h=function next(){for(;++m<t.length;)if(a.call(t,m))return next.value=t[m],next.done=!1,next;return next.value=void 0,next.done=!0,next};return h.next=h}}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,g,"GeneratorFunction"),t.isGeneratorFunction=function(t){var o="function"==typeof t&&t.constructor;return!!o&&(o===GeneratorFunction||"GeneratorFunction"===(o.displayName||o.name))},t.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,GeneratorFunctionPrototype):(t.__proto__=GeneratorFunctionPrototype,define(t,g,"GeneratorFunction")),t.prototype=Object.create(S),t},t.awrap=function(t){return{__await:t}},defineIteratorMethods(AsyncIterator.prototype),define(AsyncIterator.prototype,h,(function(){return this})),t.AsyncIterator=AsyncIterator,t.async=function(o,a,m,u,h){void 0===h&&(h=Promise);var g=new AsyncIterator(wrap(o,a,m,u),h);return t.isGeneratorFunction(a)?g:g.next().then((function(t){return t.done?t.value:g.next()}))},defineIteratorMethods(S),define(S,g,"Generator"),define(S,u,(function(){return this})),define(S,"toString",(function(){return"[object Generator]"})),t.keys=function(t){var o=[];for(var a in t)o.push(a);return o.reverse(),function next(){for(;o.length;){var a=o.pop();if(a in t)return next.value=a,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 o in this)"t"===o.charAt(0)&&a.call(this,o)&&!isNaN(+o.slice(1))&&(this[o]=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 o=this;function handle(a,m){return h.type="throw",h.arg=t,o.next=a,m&&(o.method="next",o.arg=void 0),!!m}for(var m=this.tryEntries.length-1;m>=0;--m){var u=this.tryEntries[m],h=u.completion;if("root"===u.tryLoc)return handle("end");if(u.tryLoc<=this.prev){var g=a.call(u,"catchLoc"),I=a.call(u,"finallyLoc");if(g&&I){if(this.prev<u.catchLoc)return handle(u.catchLoc,!0);if(this.prev<u.finallyLoc)return handle(u.finallyLoc)}else if(g){if(this.prev<u.catchLoc)return handle(u.catchLoc,!0)}else{if(!I)throw new Error("try statement without catch or finally");if(this.prev<u.finallyLoc)return handle(u.finallyLoc)}}}},abrupt:function(t,o){for(var m=this.tryEntries.length-1;m>=0;--m){var u=this.tryEntries[m];if(u.tryLoc<=this.prev&&a.call(u,"finallyLoc")&&this.prev<u.finallyLoc){var h=u;break}}h&&("break"===t||"continue"===t)&&h.tryLoc<=o&&o<=h.finallyLoc&&(h=null);var g=h?h.completion:{};return g.type=t,g.arg=o,h?(this.method="next",this.next=h.finallyLoc,I):this.complete(g)},complete:function(t,o){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&&o&&(this.next=o),I},finish:function(t){for(var o=this.tryEntries.length-1;o>=0;--o){var a=this.tryEntries[o];if(a.finallyLoc===t)return this.complete(a.completion,a.afterLoc),resetTryEntry(a),I}},catch:function(t){for(var o=this.tryEntries.length-1;o>=0;--o){var a=this.tryEntries[o];if(a.tryLoc===t){var m=a.completion;if("throw"===m.type){var u=m.arg;resetTryEntry(a)}return u}}throw new Error("illegal catch attempt")},delegateYield:function(t,o,a){return this.delegate={iterator:values(t),resultName:o,nextLoc:a},"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,o){if(!(t instanceof o))throw new TypeError("Cannot call a class as a function")}function _defineProperties(t,o){for(var a=0;a<o.length;a++){var m=o[a];m.enumerable=m.enumerable||!1,m.configurable=!0,"value"in m&&(m.writable=!0),Object.defineProperty(t,m.key,m)}}function _createClass(t,o,a){return o&&_defineProperties(t.prototype,o),a&&_defineProperties(t,a),Object.defineProperty(t,"prototype",{writable:!1}),t}function __awaiter(t,o,a,m){function adopt(t){return t instanceof a?t:new a((function(o){o(t)}))}return new(a||(a=Promise))((function(a,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?a(t.value):adopt(t.value).then(fulfilled,rejected)}step((m=m.apply(t,o||[])).next())}))}var t={isDataReportEnable:!0,maxSize:100,msgListMaxSize:1e3,cacheMaxSize:1e3,maxDelay:3e5,maxInterval:3e4,minInterval:1e4,timeout:5e3,autoStart:!0,loginFailIgnoreInterval:72e5},o=12,a=8e3,m=function emptyFn(){},u=function(){function Reporter(o){_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(o),this.reportConfig.isDataReportEnable&&this.reportConfig.autoStart&&this.initUploadConfig()}return _createClass(Reporter,[{key:"setConfig",value:function setConfig(t){var o=Object.assign({},this.reportConfig.common,t.common);this.reportConfig=Object.assign({},this.reportConfig,t),this.reportConfig.common=o,this.reportConfig.common.sdk_type||(this.reportConfig.common.sdk_type="im")}},{key:"reportImmediately",value:function reportImmediately(t,o){var a=this;this.reportConfig.isDataReportEnable&&this.reportConfig.request(t,Object.assign({dataType:"json",method:"POST",timeout:this.reportConfig.timeout},o)).catch((function(t){var o,m;null===(m=null===(o=a.reportConfig)||void 0===o?void 0:o.logger)||void 0===m||m.warn("Reporter immediately upload failed",t)}))}},{key:"report",value:function report(o,a){var m=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(m.priority||(m.priority=this.getEventPriority(o,a)),this.reportConfig.isDataReportEnable&&o){if("login"===o&&!1===a.succeed&&a.process_id){var u=a.extension&&a.extension.find((function(t){return"TCP"===t.operation_type})),h=u&&u.target||"",g=a.process_id+h,I=this.lastFailLogin[g]||0;if(a.start_time-I<t.loginFailIgnoreInterval)return;this.lastFailLogin[g]=a.start_time}var M=Date.now();"HIGH"===m.priority?this.highPriorityMsgList.push({module:o,msg:a,createTime:M}):"NORMAL"===m.priority?this.msgList.push({module:o,msg:a,createTime:M}):"LOW"===m.priority&&this.lowPriorityMsgList.push({module:o,msg:a,createTime:M}),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,o){if(this.reportConfig.isDataReportEnable&&t&&!this.traceMsgCache[t]){var a=Object.assign(Object.assign({start_time:Date.now()},o),{extension:[]});this.traceMsgCache[t]=a}}},{key:"reportTraceUpdate",value:function reportTraceUpdate(t){}},{key:"reportTraceUpdateV2",value:function reportTraceUpdateV2(t,o,a){var m,u=this;if(this.reportConfig.isDataReportEnable&&this.traceMsgCache[t]){var h=this.traceMsgCache[t].extension,g=h.length,I=(new Date).getTime();0===g?o.duration=I-this.traceMsgCache[t].start_time:h[g-1].end_time?o.duration=I-h[g-1].end_time:o.duration=I-this.traceMsgCache[t].start_time,h.push(Object.assign({end_time:I},o));var M=h.length-1;(null==a?void 0:a.asyncParams)&&((m=this.traceMsgCache[t]).asyncPromiseArray||(m.asyncPromiseArray=[]),this.traceMsgCache[t].asyncPromiseArray.push(a.asyncParams.then((function(o){u.traceMsgCache[t]&&u.traceMsgCache[t].extension[M]&&Object.assign(u.traceMsgCache[t].extension[M],o)}))))}}},{key:"reportTraceEnd",value:function reportTraceEnd(t){var o,a=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 u=this.traceMsgCache[t];if(this.traceMsgCache[t]=null,u.asyncPromiseArray){(o=this.endedAsyncMsgByModule)[t]||(o[t]=[]),this.endedAsyncMsgByModule[t].push(u);var h=function asyncCallback(){a.endedAsyncMsgByModule[t]&&a.endedAsyncMsgByModule[t].includes(u)&&(delete u.asyncPromiseArray,a.report(t,u,{priority:a.getEventPriority(t,u)}))};Promise.all(u.asyncPromiseArray).then(h).catch(h)}else this.report(t,u,{priority:this.getEventPriority(t,u)})}else this.traceMsgCache[t]=null}},{key:"getEventPriority",value:function getEventPriority(t,o){if("exceptions"===t){if(0===o.action)return"HIGH";if(2===o.action)return"HIGH";if(1===o.action&&0!==o.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(o){t.reportTraceEnd(o,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 u,h,g,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,u=this.reportConfig.common||{},h=this.reportConfig.compassDataEndpoint.split(",").map((function(t){return"".concat(t,"/").concat(_.configPath)})),g=_regeneratorRuntime().mark((function _loop(g){return _regeneratorRuntime().wrap((function _loop$(I){for(;;)switch(I.prev=I.next){case 0:if(!_.initConfigLoaded&&!_.isDestroyed){I.next=2;break}return I.abrupt("return","break");case 2:return I.prev=2,I.next=5,_.reportConfig.request(h[g],{method:"GET",dataType:"json",params:{deviceId:u.dev_id,sdkVer:u.sdk_ver,platform:u.platform,hostEnv:u.host_env,appkey:u.app_key},timeout:_.reportConfig.timeout}).then((function(t){var o,a;if(!_.isDestroyed){if(200===t.status&&t.data&&200===t.data.code){_.initConfigLoaded=!0;var m=t.data.data||{};_.reportConfig.maxSize=m.maxSize>1e3?1e3:m.maxSize,_.reportConfig.maxInterval=m.maxInterval>1e4?1e4:m.maxInterval,_.reportConfig.maxInterval=m.maxInterval<10?10:m.maxInterval,_.reportConfig.minInterval=m.minInterval<2?2:m.minInterval,_.reportConfig.maxDelay=m.maxDelay||300,_.reportConfig.maxInterval=1e3*_.reportConfig.maxInterval,_.reportConfig.minInterval=1e3*_.reportConfig.minInterval,_.reportConfig.maxDelay=1e3*_.reportConfig.maxDelay,m.endpoint?_.dataReportEndpoint=m.endpoint:_.dataReportEndpoint=h[g],_.serverAllowUpload=!0,_.loading=!1,_.reportHeartBeat()}else 200===t.status&&(_.initConfigLoaded=!0);null===(a=null===(o=_.reportConfig)||void 0===o?void 0:o.logger)||void 0===a||a.log("Get reporter upload config success")}})).catch((function(t){var m,u;_.isDestroyed||(_.loading=!1,null===(u=null===(m=_.reportConfig)||void 0===m?void 0:m.logger)||void 0===u||u.error("Get reporter upload config failed",t),_.reqRetryCount<o&&(_.reqRetryCount++,setTimeout((function(){_.isDestroyed||_.initUploadConfig()}),a)))}));case 5:I.next=14;break;case 7:if(I.prev=7,I.t0=I.catch(2),!_.isDestroyed){I.next=11;break}return I.abrupt("return",{v:void 0});case 11:_.loading=!1,null===(m=null===(t=_.reportConfig)||void 0===t?void 0:t.logger)||void 0===m||m.error("Exec reporter request failed",I.t0),_.reqRetryCount<o&&(_.reqRetryCount++,setTimeout((function(){_.isDestroyed||_.initUploadConfig()}),a));case 14:case"end":return I.stop()}}),_loop,null,[[2,7]])})),I=0;case 7:if(!(I<h.length)){E.next=17;break}return E.delegateYield(g(I),"t0",9);case 9:if("break"!==(M=E.t0)){E.next=12;break}return E.abrupt("break",17);case 12:if("object"!==_typeof(M)){E.next=14;break}return E.abrupt("return",M.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,o={},a=Date.now();this.highPriorityMsgList=this.highPriorityMsgList.filter((function(o){return a-o.createTime<t.reportConfig.maxDelay})),this.msgList=this.msgList.filter((function(o){return a-o.createTime<t.reportConfig.maxDelay})),this.lowPriorityMsgList=this.lowPriorityMsgList.filter((function(o){return a-o.createTime<t.reportConfig.maxDelay})),this.cacheMsgList=this.cacheMsgList.filter((function(o){return a-o.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 u=this.reportConfig.maxSize-m.length;m=m.concat(this.msgList.slice(0,u)),this.msgList=this.msgList.slice(u)}if(m.length<this.reportConfig.maxSize){var h=this.reportConfig.maxSize-m.length;m=m.concat(this.lowPriorityMsgList.slice(0,h)),this.lowPriorityMsgList=this.lowPriorityMsgList.slice(h)}if(m.length<this.reportConfig.maxSize){var g=this.reportConfig.maxSize-m.length;m=m.concat(this.cacheMsgList.slice(0,g)),this.cacheMsgList=this.cacheMsgList.slice(g)}return m.forEach((function(t){o[t.module]?o[t.module].push(t.msg):o[t.module]=[t.msg]})),{uploadMsgArr:m,uploadMsg:o}}},{key:"upload",value:function upload(){var t,o,a=this;if(this.isUploadEnable&&this.serverAllowUpload&&!(this.lastReportTime&&Date.now()-this.lastReportTime<this.reportConfig.minInterval)){var m=this.getUploadMsg(),u=m.uploadMsgArr,h=m.uploadMsg;if(u.length){this.lastReportTime=Date.now();try{var g="".concat(this.dataReportEndpoint,"/").concat(this.dataReportPath);this.reportConfig.request(g,{dataType:"json",method:"POST",data:{common:this.reportConfig.common,event:h},headers:{sdktype:"im"},timeout:this.reportConfig.timeout}).catch((function(t){var o,m;a.cacheMsgList=a.cacheMsgList.concat(u).slice(0,a.reportConfig.cacheMaxSize),null===(m=null===(o=a.reportConfig)||void 0===o?void 0:o.logger)||void 0===m||m.warn("Reporter upload failed",t)}))}catch(a){null===(o=null===(t=this.reportConfig)||void 0===t?void 0:t.logger)||void 0===o||o.warn("Exec reporter request failed",a)}clearTimeout(this.timer),this.reportHeartBeat()}}}}]),Reporter}();return u}()}));!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"}(o||(o={})),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"}(a||(a={})),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"}(u||(u={})),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"}(h||(h={})),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"}(g||(g={})),function(t){t[t.V2NIM_FRIEND_ADD_APPLICATION_TYPE_RECEIVED=1]="V2NIM_FRIEND_ADD_APPLICATION_TYPE_RECEIVED",t[t.V2NIM_FRIEND_ADD_APPLICATION_TYPE_REJECTED=2]="V2NIM_FRIEND_ADD_APPLICATION_TYPE_REJECTED"}(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"}(M||(M={})),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"}(_||(_={})),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"}(b||(b={})),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"}(V||(V={})),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"}(k||(k={})),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"}(P||(P={})),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"}(L||(L={})),function(t){t[t.V2NIM_SEARCH_DIRECTION_BACKWARD=0]="V2NIM_SEARCH_DIRECTION_BACKWARD",t[t.V2NIM_SEARCH_DIRECTION_FORWARD=1]="V2NIM_SEARCH_DIRECTION_FORWARD"}(w||(w={})),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"}(D||(D={})),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"}(U||(U={})),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"}(x||(x={})),function(t){t[t.V2NIM_QUERY_DIRECTION_DESC=0]="V2NIM_QUERY_DIRECTION_DESC",t[t.V2NIM_QUERY_DIRECTION_ASC=1]="V2NIM_QUERY_DIRECTION_ASC"}(B||(B={})),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"}($||($={})),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"}(j||(j={})),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"}(G||(G={})),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"}(q||(q={})),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"}(H||(H={})),function(t){t[t.V2NIM_SORT_ORDER_DESC=0]="V2NIM_SORT_ORDER_DESC",t[t.V2NIM_SORT_ORDER_ASC=1]="V2NIM_SORT_ORDER_ASC"}(z||(z={})),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"}(Y||(Y={})),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"}(J||(J={})),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"}(X||(X={})),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"}(Q||(Q={})),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"}(Z||(Z={})),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"}(ee||(ee={})),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"}(te||(te={})),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"}(re||(re={})),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"}(ie||(ie={})),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"}(oe||(oe={})),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"}(se||(se={})),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"}(ne||(ne={})),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"}(ae||(ae={})),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"}(ce||(ce={})),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"}(de||(de={})),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"}(le||(le={})),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"}(pe||(pe={})),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"}(me||(me={})),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"}(ue||(ue={})),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"}(he||(he={})),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"}(ge||(ge={}));var Ie={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"}},ye=Object.keys(Ie),Me=ye.reduce((function(t,o){var a=Ie[o];return t[o]=a.code,t}),{}),_e=ye.reduce((function(t,o){var a=Ie[o];return t[a.code]=a.message,t}),{}),Ee=Object.freeze({__proto__:null,V2NIMErrorCode:Me,V2NIMErrorDesc:_e,get V2NIMDataSyncLevel(){return o},get V2NIMDataSyncType(){return a},get V2NIMDataSyncState(){return m},get V2NIMConversationType(){return u},get V2NIMLastMessageState(){return h},get V2NIMFriendAddMode(){return g},get V2NIMFriendAddApplicationType(){return I},get V2NIMFriendAddApplicationStatus(){return M},get V2NIMFriendDeletionType(){return _},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 P},get V2NIMMessageNotificationType(){return D},get V2NIMMessageAttachmentUploadState(){return U},get V2NIMMessageSendingState(){return x},get V2NIMQueryDirection(){return B},get V2NIMMessageRevokeType(){return j},get V2NIMMessagePinState(){return G},get V2NIMMessageQuickCommentType(){return q},get V2NIMClientAntispamOperateType(){return H},get V2NIMSortOrder(){return z},get V2NIMSystemMessageType(){return Y},get V2NIMMessageAIStreamStatus(){return R},get V2NIMMessageAIStreamStopOpType(){return b},get V2NIMMessageAIRegenOpType(){return V},get V2NIMMessageAIStatus(){return k},get V2NIMSearchKeywordMatchType(){return L},get V2NIMClearHistoryMode(){return $},get V2NIMMessageStreamStatus(){return K},get V2NIMTeamMessageMuteMode(){return J},get V2NIMP2PMessageMuteMode(){return X},get V2NIMTeamMemberRoleQueryType(){return Q},get V2NIMTeamType(){return Z},get V2NIMTeamJoinMode(){return ee},get V2NIMTeamAgreeMode(){return te},get V2NIMTeamInviteMode(){return re},get V2NIMTeamUpdateInfoMode(){return ie},get V2NIMTeamChatBannedMode(){return oe},get V2NIMTeamUpdateExtensionMode(){return se},get V2NIMTeamJoinActionType(){return ae},get V2NIMTeamJoinActionStatus(){return ce},get V2NIMTeamNotificationType(){return de},get V2NIMTeamMemberRole(){return ne},get V2NIMAIModelRoleType(){return me},get V2NIMAIModelType(){return le},get V2NIMAIModelStreamCallStatus(){return pe},get V2NIMSignallingChannelType(){return he},get V2NIMSignallingEventType(){return ue},get V2NIMUserStatusType(){return ge}});class V2NIMErrorImpl extends Error{constructor(t){super(t.desc),this.name="V2NIMError",this.code=t.code||0,this.desc=t.desc||_e[this.code]||Se[this.code]||"",this.message=this.desc,this.detail=t.detail||{}}toString(){var t,o=`${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)&&(o+=`\n rawError: ${this.detail.rawError.message}`),o}}class ValidateError extends V2NIMErrorImpl{constructor(t,o={},a){super({code:Me.V2NIM_ERROR_CODE_PARAMETER_ERROR,detail:{reason:t,rules:a,data:o}}),this.name="validateError",this.message=this.message+"\n"+JSON.stringify(this.detail,null,2),this.data=o,this.rules=a}}class ValidateErrorV2 extends V2NIMErrorImpl{constructor(t){var o,a,m;super({code:Me.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:null===(o=t.detail)||void 0===o?void 0:o.reason,rules:null===(a=t.detail)||void 0===a?void 0:a.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 Se={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,o){return o instanceof RegExp?"__REGEXP "+o.toString():o}function validate(t,o={},a,m=!1){var u={};return Object.keys(t).forEach((h=>{var g=t[h].type,I=a?`In ${a}, `:"";if(null==o){var M=`${I}param is null or undefined`;throw m?new ValidateErrorV2({detail:{reason:M,data:{key:h},rules:"required"}}):new ValidateError(M,{key:h},"required")}if(void 0===o[h]){if(!1===t[h].required)return void(u[h]=o[h]);var _=`${I}param '${h}' is required`;throw m?new ValidateErrorV2({detail:{reason:_,data:{key:h},rules:"required"}}):new ValidateError(_,{key:h},"required")}var E=Te[g];if(E&&!E(o,h,t[h],m)){var S=`${I}param '${h}' unexpected`,T={key:h,value:o[h]};throw m?new ValidateErrorV2({detail:{reason:S,data:T,rules:JSON.stringify(t[h],replacer)}}):new ValidateError(S,T,JSON.stringify(t[h],replacer))}u[h]=o[h]})),u}var Te={string:function(t,o,a){var{allowEmpty:m,max:u,min:h,regExp:g}=a,I=t[o];return"string"==typeof I&&((!1!==m||""!==I)&&(!("number"==typeof u&&I.length>u)&&(!("number"==typeof h&&I.length<h)&&!(function isRegExp(t){return"[object RegExp]"===Object.prototype.toString.call(t)}(g)&&!g.test(I)))))},number:function(t,o,a){var{min:m,max:u}=a,h=t[o];return"number"==typeof h&&(!("number"==typeof m&&h<m)&&!("number"==typeof u&&h>u))},boolean:function(t,o){return"boolean"==typeof t[o]},file:function(t,o){return!0},enum:function(t,o,a){var{values:m}=a,u=t[o];return!m||m.indexOf(u)>-1},jsonstr:function(t,o){try{var a=JSON.parse(t[o]);return"object"==typeof a&&null!==a}catch(t){return!1}},func:function(t,o){return"function"==typeof t[o]},array:function(t,o,a,m=!1){var{itemType:u,itemRules:h,rules:g,min:I,max:M,values:_}=a,E=t[o];if(!Array.isArray(E))return!1;if("number"==typeof M&&E.length>M)return!1;if("number"==typeof I&&E.length<I)return!1;if(h)E.forEach(((t,a)=>{validate({[a]:h},{[a]:t},`${o}[${a}]`,m)}));else if(g)E.forEach(((t,a)=>validate(g,t,`${o}[${a}]`,m)));else if("enum"===u){if(_&&function difference(t,o){return o=o||[],(t=t||[]).filter((t=>-1===o.indexOf(t)))}(E,_).length)return!1}else if(u&&!E.every((t=>typeof t===u)))return!1;return!0},object:function(t,o,a,m=!1){var{rules:u,allowEmpty:h}=a,g=t[o];if("object"!=typeof g||null===g)return!1;if(u){var I=Object.keys(u),M=Object.keys(g).filter((t=>I.indexOf(t)>-1));if(!1===h&&0===M.length)return!1;validate(u,g,o,m)}return!0}};function validateConversationId(t,o){if(!t)throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_ILLEGAL_STATE});validate({conversationId:{type:"string",allowEmpty:!1,regExp:new RegExp(`^${t}\\|[1-3]\\|`)}},{conversationId:o},"",!0)}class TimerManager{constructor(){this.timerList=[],this.id=1,this.timer=null,this.timeout=0}addTimer(t,o=0,a=1){var m=(new Date).getTime(),u=this.id;return this.timerList.push({id:u,loop:a,count:0,timeout:m+o,interval:o,callback:t}),this.id++,this.checkTimer(m),u}checkTimer(t=(new Date).getTime()){if(this.removeFinished(),0!==this.timerList.length||null==this.timer){var o=0;for(var a of this.timerList)(0===o||o>a.timeout)&&(o=a.timeout);0!==this.timerList.length&&(null===this.timer||o<this.timeout||this.timeout<t)&&(this.timer=setTimeout(this.nowTime.bind(this),o-t),this.timeout=o)}}nowTime(){var t=(new Date).getTime();for(var o of this.timerList)t>=o.timeout&&(o.callback(),o.count++,o.timeout=t+o.interval);this.clerTime(),this.checkTimer(t)}clerTime(){null!==this.timer&&(clearTimeout(this.timer),this.timer=null)}deleteTimer(t){for(var o=this.timerList.length-1;o>=0;o--){this.timerList[o].id===t&&this.timerList.splice(o,1)}}removeFinished(){for(var t=this.timerList.length-1;t>=0;t--){var o=this.timerList[t];o.loop>=0&&o.count>=o.loop&&this.timerList.splice(t,1)}}destroy(){this.clerTime(),this.timerList=[],this.id=1,this.timer=null}}function __rest(t,o){var a={};for(var m in t)Object.prototype.hasOwnProperty.call(t,m)&&o.indexOf(m)<0&&(a[m]=t[m]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var u=0;for(m=Object.getOwnPropertySymbols(t);u<m.length;u++)o.indexOf(m[u])<0&&Object.prototype.propertyIsEnumerable.call(t,m[u])&&(a[m[u]]=t[m[u]])}return a}function __awaiter(t,o,a,m){return new(a||(a=Promise))((function(u,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?u(t.value):function adopt(t){return t instanceof a?t:new a((function(o){o(t)}))}(t.value).then(fulfilled,rejected)}step((m=m.apply(t,o||[])).next())}))}function isPlainObject(t){return null!=t&&"object"==typeof t&&Object.getPrototypeOf(t)==Object.prototype}function merge(t,o){var a=isPlainObject(t)||Array.isArray(t),m=isPlainObject(o)||Array.isArray(o);if(a&&m){for(var u in o){var h=merge(t[u],o[u]);void 0!==h&&(t[u]=h)}return t}return o}var Ce={getNetworkStatus:()=>Promise.resolve({net_type:0,net_connect:!0}),onNetworkStatusChange(t){},offNetworkStatusChange(){}},Ne={isActive:()=>!0,getStatus:()=>0,setStatus(t){},destroy(){}};var Ae={setLogger:function(t){throw new Error("setLogger not implemented.")},platform:"",WebSocket:class AdapterSocket{constructor(t,o){throw this.CONNECTING=0,this.OPEN=1,this.CLOSING=2,this.CLOSED=3,this.binaryType="",new Error("Method not implemented.")}close(t,o){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,o){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:Ce,powerMonitor:Ne,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(Ae,t())}var Oe=["error","warn","log","debug"],emptyFunc$1=function(){},Re=["off","error","warn","log","debug"];class Logger{constructor(t,o={}){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=Re.includes(t)?t:"off",o.debugLevel&&(this.debugLevel=Re.includes(o.debugLevel)?o.debugLevel:this.debugLevel),this.logStorage=!1===o.storageEnable?null:new Ae.logStorage(null==o?void 0:o.storageName),this.setOptions(o),this.setLogFunc(this.debugLevel),this.setTimer(),Ae.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 o=t.logFunc;for(var a in o){var m=a,u=o[m];u&&(this.strategies[m].func=u)}}}setLogFunc(t,o="log"){var a=Oe.findIndex((o=>o===t)),m=Oe.findIndex((t=>t===o));Oe.forEach(((t,o)=>{this[t]=function(){if(!(o>a&&o>m)){var u=Array.prototype.slice.call(arguments),h=this.strategies[t],g=this.formatArgs(u,h.name);o<=m&&this.logStorage&&this.prepareSaveLog(g,t),o<=a&&h.func(g)}}}))}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,o){this.storageArr.push({text:t,level:o,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,o){var a=new Date;return`[NIM ${this.iid} ${o} ${`${a.getMonth()+1}-${a.getDate()} ${a.getHours()}:${a.getMinutes()}:${a.getSeconds()}:${a.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,o){if("object"!=typeof t||null===t)return t;for(var a=(o=o||"").split("."),m=0;m<a.length;m++){var u=a[m],h=t[u],g=u.indexOf("["),I=u.indexOf("]");if(-1!==g&&-1!==I&&g<I){var M=u.slice(0,g),_=parseInt(u.slice(g+1,I));h=t[M],h=Array.isArray(h)?h[_]:void 0}if(null==h)return h;t=h}return t}var be,Ve=(be=function(){return(65536*(1+Math.random())|0).toString(16).substring(1)},function(){return be()+be()+be()+be()+be()+be()+be()+be()});function pendingIsMiniappEnv(){var{hostEnvEnum:t}=Ae.getSystemInfo();return 6===t||102===t||103===t||104===t}function assignOptions(t,o){return function assignWith(t,o,a,m){for(var u in t=t||{},a=a||{},m=m||(()=>{}),o=o||{}){var h=m(t[u],o[u]);t[u]=void 0===h?o[u]:h}for(var g in a){var I=m(t[g],a[g]);t[g]=void 0===I?a[g]:I}return t}({},t,o,(function(t,o){return void 0===o?t:o}))}function emptyFuncWithPromise(){return Promise.resolve()}function emptyFunc(){}function getFileExtension(t){var o=t.lastIndexOf("."),a=o>-1?t.slice(o+1):"";return/^\d+$/.test(a.trim())&&(a=""),a}function findIndexWithinTargetValue(t,o,a){return 0===t.length||t[0][o]<=a?0:t[t.length-1][o]>a?t.length:t.findIndex(((m,u)=>{if(t[u-1]&&t[u-1][o]>a&&a>=m[o])return!0}))}function fillIdServer(t,o,a,m){var u="number"==typeof get(t,"raw.r[0]")?`${t.raw.r[0]}`:void 0;return o[a]=o[a]||u||m,o}class CoreAdapters{constructor(t){this.lastSuccUploadHost="",this.core=t}getFileUploadInformation(t){return Ae.getFileUploadInformation(t)}request(t,o,a){var m=(new Date).getTime(),u=(null==a?void 0:a.exception_service)||0;return Ae.request(t,o).catch((a=>{var h,g,I,M,_=a;throw this.core.reporter.reportTraceStart("exceptions",{user_id:this.core.options.account||(null===(g=null===(h=this.core)||void 0===h?void 0:h.auth)||void 0===g?void 0:g.account),trace_id:null===(M=null===(I=this.core.clientSocket)||void 0===I?void 0:I.socket)||void 0===M?void 0:M.sessionId,start_time:m,action:1,exception_service:u}),this.core.reporter.reportTraceUpdateV2("exceptions",{code:"number"==typeof _.code?_.code:0,description:_.message||`${_.code}`,operation_type:0,target:t,context:o?JSON.stringify(o):""},{asyncParams:Ae.net.getNetworkStatus()}),this.core.reporter.reportTraceEnd("exceptions",1),a}))}uploadFile(t){var o,a,m,u;return __awaiter(this,void 0,void 0,(function*(){for(var h="BROWSER"===Ae.platform,g=h?t.chunkUploadHostBackupList:t.commonUploadHostBackupList,I=h?t.chunkUploadHost:t.commonUploadHost,M=g.indexOf(I),_=-1===M?[I,...g]:[I,...g.slice(0,M),...g.slice(M+1)],E=Math.max(_.indexOf(this.lastSuccUploadHost),0),S=null,T=0;T<_.length;T++){var C=(new Date).getTime(),N=_[(T+E)%_.length];try{var A=yield Ae.uploadFile(Object.assign(Object.assign({},t),h?{chunkUploadHost:N}:{commonUploadHost:N}));return this.lastSuccUploadHost=N,"string"==typeof A.size&&(A.size=parseInt(A.size)),"string"==typeof A.dur&&(A.dur=parseInt(A.dur)),"string"==typeof A.w&&(A.w=parseInt(A.w)),"string"==typeof A.h&&(A.h=parseInt(A.h)),A}catch(t){this.core.cloudStorage.nos.nosErrorCount--,S=t;var O=t;this.core.reporter.reportTraceStart("exceptions",{user_id:this.core.options.account||(null===(a=null===(o=this.core)||void 0===o?void 0:o.auth)||void 0===a?void 0:a.account),trace_id:null===(u=null===(m=this.core.clientSocket)||void 0===m?void 0:m.socket)||void 0===u?void 0:u.sessionId,start_time:C,action:1,exception_service:3}),this.core.reporter.reportTraceUpdateV2("exceptions",{code:"number"==typeof O.code?O.code:0,description:O.message||`${O.code}`,operation_type:1,target:N},{asyncParams:Ae.net.getNetworkStatus()}),this.core.reporter.reportTraceEnd("exceptions",1),this._uploadFileErrHanler(t)}}throw S}))}_uploadFileErrHanler(t){if(t&&(t.code>200||t.errCode>200))throw t}}var ke="https://abt-online.netease.im/v1/api/abt/client/getExperimentInfo";class ABTest{constructor(t,o){this.abtInfo={},this.core=t,this.config=assignOptions({isAbtestEnable:!0,abtestUrl:ke,abtestProjectKey:"imElite_sdk_abtest_web"},o)}setOptions(t){this.config=assignOptions(this.config,t)}abtRequest(){var t,o;return __awaiter(this,void 0,void 0,(function*(){if(this.config.isAbtestEnable&&!this.abtInfo.experiments&&this.config.abtestUrl){var a;try{a=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.41",deviceId:this.core.config.deviceId},useLocalCache:!0}},{exception_service:7})}catch(t){this.core.logger.warn("ABTest request failed")}this.abtInfo=(null===(o=null===(t=null==a?void 0:a.data)||void 0===t?void 0:t.data)||void 0===o?void 0:o.abtInfo)||{}}}))}}class PromiseManager{constructor(){this.abortFns=[]}add(t){var o=function getPromiseWithAbort(t){var o={},a=new Promise((function(t,a){o.abort=a}));return o.promise=Promise.race([t,a]),o}(t);return this.abortFns.push(o.abort),o.promise}clear(t){this.abortFns.forEach((o=>o(t||new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_CANCELLED,detail:{reason:"Aborted"}})))),this.abortFns=[]}destroy(){this.clear()}}var Pe={tolerantRTT:3e3,bestRTT:100,maxChances:5,enable:!0},Le={timestamp:0,rtt:0,baseClock:0,baseTime:0};class TimeOrigin{constructor(t,o,a="getServerTime"){this.serverOrigin=Le,this.config=Pe,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=a,o&&this.setOptions(o)}setOptions(t){this.config=Object.assign({},Pe,this.config,t)}reset(){this.timer&&clearTimeout(this.timer),this.promiseManager.clear(),this.serverOrigin=Le,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"),o=get(this.core,"status"),a=get(this.core,"V2NIMLoginService.lifeCycle.loginStatus");if("logined"===t||"logined"===o||1===a){this.isSettingNTP=!0,this.currentChance++,this.timer&&clearTimeout(this.timer),this.timer=0;var m,u="TimeOrigin::setOriginTimetick:",h=Date.now();this.core.logger.debug(`${u} 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 g=t;return this.isSettingNTP=!1,this.logger.warn(`${u} Calculate Delay time, getServerTime error`,g),void(g.code!==Me.V2NIM_ERROR_CODE_CANCELLED&&(clearTimeout(this.timer),this.timer=setTimeout(this.setOriginTimetick.bind(this),this.failedDelay)))}if(!m)return this.core.logger.warn(`${u} Calculate Delay time incorrect format`),void(this.config.enable=!1);var I=Date.now()-h;this.doSet(m,I)}}}))}doSet(t,o){var a="TimeOrigin::setOriginTimetick:";o>this.config.tolerantRTT?(this.logger.warn(`${a} denied RTT:${o}`),clearTimeout(this.timer),this.timer=setTimeout(this.setOriginTimetick.bind(this),this.failedDelay)):o>this.config.bestRTT?(this.serverOrigin.rtt&&o>=this.serverOrigin.rtt?this.logger.warn(`${a} ignore RTT:${o}`):(this.setServerOrigin(o,t),this.logger.log(`${a} accept reluctantly RTT:${o}`)),clearTimeout(this.timer),this.timer=setTimeout(this.setOriginTimetick.bind(this),this.failedDelay)):(this.setServerOrigin(o,t),this.logger.debug(`${a} accept best RTT:${o}`),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 o=Math.floor(t.time-this.serverOrigin.baseTime);return this.serverOrigin.timestamp+o}return Date.now()}checkNodeReliable(t){if(void 0===t&&(t=this.getTimeNode()),this.serverOrigin.timestamp){if(0===this.serverOrigin.baseClock)return!0;var o=t.clock-this.serverOrigin.baseClock,a=t.time-this.serverOrigin.baseTime;return Math.abs(a-o)<500}return!1}checkPerformance(){return"BROWSER"===Ae.platform&&!("undefined"==typeof performance||!performance.now)}static checkPerformance(){return"BROWSER"===Ae.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,o){this.serverOrigin={timestamp:o+Math.floor(t/2),rtt:t,baseClock:this.checkPerformance()?performance.now():0,baseTime:Date.now()}}}var we={user_id:"",trace_id:"",action:7,exception_service:6,duration:0,start_time:0,state:1,extension:[]};class ReporterHookLinkKeep{constructor(t,o){this.traceData=we,this.core=t,this.traceData=Object.assign({},we,o),this.traceData.extension=[]}reset(){this.traceData=Object.assign({},we),this.traceData.extension=[]}start(){var t,o;this.reset(),this.traceData.user_id=this.core.account,this.traceData.trace_id=(null===(o=null===(t=this.core.clientSocket)||void 0===t?void 0:t.socket)||void 0===o?void 0:o.sessionId)||"",this.traceData.start_time=(new Date).getTime()}update(t){return __awaiter(this,void 0,void 0,(function*(){var{net_type:o,net_connect:a}=yield Ae.net.getNetworkStatus();this.traceData.extension.push(Object.assign({code:0,foreground:!0,foreg_backg_switch:!1,net_type:o,net_connect:a},t))}))}end(t){var o=this.traceData.extension[0],a=this.traceData.extension[1];if(o&&0===o.operation_type&&a&&1===a.operation_type){var m=o.net_type!==a.net_type||o.net_connect!==a.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 De={user_id:"",trace_id:"",net_connect:!0,net_type:0,duration:0,start_time:0,history:[],succeed:!1};class ReporterHookLBS{constructor(t){this.traceData=De,this.core=t,this.reset()}reset(){this.traceData=Object.assign({},De),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((o=>{o.target===t.target&&(Object.assign(o,t),o.duration=Date.now()-o.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:o,net_connect:a}=yield Ae.net.getNetworkStatus();this.traceData.net_type=o,this.traceData.net_connect=a,this.core.reporter.report("nim_sdk_lbs_records",this.traceData),this.reset()}else this.reset()}))}}function getIsDataReportEnable(t){var o,a,m=!0;return"boolean"==typeof(null===(o=null==t?void 0:t.reporterConfig)||void 0===o?void 0:o.enableCompass)?m=t.reporterConfig.enableCompass:"boolean"==typeof(null===(a=null==t?void 0:t.reporterConfig)||void 0===a?void 0:a.isDataReportEnable)&&(m=t.reporterConfig.isDataReportEnable),m}var Ue={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:""},xe="ReporterHook::setMonitorForResources:";class ReporterHookCloudStorage{constructor(t,o){this.traceData=Ue,this.core=t,this.traceData=Object.assign({},Ue,o)}reset(){this.traceData=Object.assign({},Ue)}start(){var t,o;this.reset(),this.traceData.user_id=this.core.account,this.traceData.trace_id=(null===(o=null===(t=this.core.clientSocket)||void 0===t?void 0:t.socket)||void 0===o?void 0:o.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*(){this.traceData.user_id&&(this.core.logger.log(`${xe} upload update`,t),Object.assign(this.traceData,t))}))}end(t){this.traceData.user_id&&(this.core.logger.log(`${xe} 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,this.core.reporter.report("nim_sdk_resources",this.traceData),this.traceData=Ue)}}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:ke,isAbtestEnable:!0};class NIM$1 extends ve{constructor(t,o={}){if(super(),this.instanceName="NIM",this.pluginMap={},this.eventBus=new ve,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,o.loggerConfig),o.privateConf){var{authConfig:a,cloudStorageConfig:m,reporterConfig:u}=this.getConfigFromPrivate(o.privateConf);Object.assign(t,a),this.setInitOptions(t),this.otherOptions=Object.assign(Object.assign({},o),{cloudStorageConfig:Object.assign(Object.assign({storageKeyPrefix:"NIM"},o.cloudStorageConfig),m),reporterConfig:Object.assign(Object.assign({},o.reporterConfig),u),V1NIMLoginServiceConfig:Object.assign(Object.assign(Object.assign({},t),o.V1NIMLoginServiceConfig),a),V2NIMLoginServiceConfig:Object.assign(Object.assign({},o.V2NIMLoginServiceConfig),a)})}else this.setInitOptions(t),this.otherOptions=Object.assign(Object.assign({},o),{V1NIMLoginServiceConfig:Object.assign(Object.assign({},t),o.V1NIMLoginServiceConfig),cloudStorageConfig:Object.assign({storageKeyPrefix:"NIM"},o.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 h=Ae.getSystemInfo(),g=function getCompassDataEndpoint(t,o){var a,m,u=null===(a=null==o?void 0:o.reporterConfig)||void 0===a?void 0:a.compassDataEndpoint,h=null===(m=null==o?void 0:o.reporterConfig)||void 0===m?void 0:m.reportConfigUrl;if(u)return u;if(h){var g=h.match(/^https:\/\/([^/]+)\/*/);if(Array.isArray(g)&&g.length>=1)return`https://${g[1]}`;t.error(`Invalid reportConfigUrl: ${h}`)}return pendingIsMiniappEnv()?"https://statistic.live.126.net":"https://statistic.live.126.net,https://statistic-overseas.yunxinfw.com"}(this.logger,this.otherOptions);this.reporter=new fe(Object.assign(Object.assign({},g?{compassDataEndpoint:g}:{}),{isDataReportEnable:getIsDataReportEnable(this.otherOptions),common:{app_key:t.appkey,dev_id:"",platform:"Web",sdk_ver:"10.9.41",env:"online",os_name:h.os,os_ver:h.osVer,lib_env:h.libEnv,host_env:h.hostEnv,host_env_ver:h.hostEnvVer,manufactor:h.manufactor,model:h.model,v2:"v1"!==this.options.apiVersion},request:Ae.request,logger:this.logger,autoStart:!0})),this.reporterHookLinkKeep=new ReporterHookLinkKeep(this),this.reporterHookCloudStorage=new ReporterHookCloudStorage(this),this.reporterHookLBS=new ReporterHookLBS(this),this.getServiceKeys(Object.keys(Fe)).forEach((t=>{if(!this[t]||!this[t].name){var o=Fe[t];this[t]=new o(this)}})),Object.keys(Fe).forEach((t=>{this.callSetOptions(t)})),Object.keys(Be).forEach((t=>{var o=Be[t];void 0!==o&&(this[t]=new o(this))})),NIM$1.instance=this,this.logger.log(`NIM init, version:10.9.41, sdk version:100941, appkey:${t.appkey}`)}getServiceKeys(t){var o=t.findIndex((t=>"V1NIMLoginService"===t));if(o>-1){var a=t[o];t.splice(o,1),"v1"===this.options.apiVersion&&t.unshift(a)}var m=t.findIndex((t=>"V2NIMLoginService"===t));if(m>-1){var u=t[m];t.splice(m,1),"v2"===this.options.apiVersion&&t.unshift(u)}var h=t.findIndex((t=>"sync"===t));if(h>-1){var g=t[h];t.splice(h,1),"v1"===this.options.apiVersion&&t.push(g)}var I=t.findIndex((t=>"V2NIMSyncService"===t));if(I>-1){var M=t[I];t.splice(I,1),"v2"===this.options.apiVersion&&t.push(M)}return t}static getInstance(t,o){if(!NIM$1.instance){if(t)return new NIM$1(t,o);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 o;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!==(o=t.websdkSsl)&&void 0!==o?o: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:Me.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:Me.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:Me.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((o=>{o&&"function"==typeof o.reset&&o.reset(t)}))}_removeAllModuleListeners(){Object.values(this).forEach((t=>{t&&"function"==typeof t.removeAllListeners&&t.removeAllListeners()}))}kick(t){return this.V1NIMLoginService.kick(t)}sendCmd(t,o,a){return this.clientSocket.sendCmd(t,o,a)}emit(t,...o){try{var a=Date.now(),m=super.emit(t,...o),u=Date.now()-a;return u>=10&&this.logger.warn(`Core::emit event: ${t} process takes: ${u}ms`),m}catch(o){return this.logger.error(`Core::emit event: ${t}. Error: ${o}`),setTimeout((()=>{throw this.logger.error(`Core::emit throw error in setTimeout. event: ${t}. Error: ${o}`),o}),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,o){this[o]&&this[o].name||(this[o]=new t(this),this.callSetOptions(o))}callSetOptions(t){var o=`${t}Config`,a=`${t}Options`,m=this.otherOptions[o]||this.otherOptions[a]||{},u=get(this,`${t}.setOptions`);"function"==typeof u&&("cloudStorage"===t&&(m=this.otherOptions[o]||this.otherOptions.serverConfig||{}),u.call(this[t],m))}static registerService(t,o){Fe[o]=t}static registerPrivateService(t,o){Be[o]=t}static registerPlugin(t,o){$e[o]=t}}NIM$1.sdkVersion=100941,NIM$1.sdkVersionFormat="10.9.41";var Ge={},qe={};function createCmd(t,o,a,m){var u=Ge[t];if(!u)return a.error("createCmd:: can not find cmd config: ",t),null;var h={SER:o,SID:u.sid,CID:u.cid,Q:[]};return u.params&&m&&u.params.forEach((function(t){var o=m[t.name];if(null!=o){var a=t.type,{reflectMapper:u,select:g}=t;switch(t.type){case"PropertyArray":a="ArrayMable",o=o.map((t=>({t:"Property",v:u?serialize(t,u,g):t})));break;case"Property":o=u?serialize(o,u,g):o;break;case"Bool":o=o?"true":"false"}h.Q.push({t:a,v:o})}})),{packet:h,hasPacketResponse:"boolean"!=typeof u.hasPacketResponse||u.hasPacketResponse,hasPacketTimer:"boolean"!=typeof u.hasPacketTimer||u.hasPacketTimer}}function parseCmd(t,o){var a;try{a=JSON.parse(t)}catch(a){return void o.error(`Parse command error:"${t}"`)}var m=a.sid+"_"+a.cid,u=a.r;if(["4_1","4_2","4_10","4_11"].includes(m)){var h=a.r[1].headerPacket;m=`${h.sid}_${h.cid}`,a.sid=h.sid,a.cid=h.cid,u=a.r[1].body}var g=qe[m],I=[];if(g&&g.length>0){for(var M of g)I.push(parseEachCmd(a,M.config,M.cmd,u,o));return I}o.error("parseCmd:: mapper not exist",m,a.code)}function parseEachCmd(t,o,a,m,u){var h,g={cmd:a,raw:t,error:null,service:null==o?void 0:o.service,content:{},__receiveTimeNode:TimeOrigin.getTimeNode()};(18===o.sid||o.sid>=26&&o.sid<100)&&(t.code=function toReadableCode(t){if("number"!=typeof t||t!=t)throw new V2NIMErrorImpl({code:Me.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 o=(65535&t)>>9;o-=o<=38?1:2;return 1e5+1e3*o+(511&t)}(t.code));var I=function genCmdError(t,o){var a=_e[t],m=Se[t];return null===m?null:new V2NIMErrorImpl({code:t,desc:a||m||t,detail:{cmd:o,timetag:Date.now()}})}(t.code,a);if(g.error=I,g.error){if(g.error.detail.cmd=a,!(null===(h=null==o?void 0:o.ignoreErrCodes)||void 0===h?void 0:h.includes(t.code)))return g;u.warn("parseCmd:: ignore error ",g.error),g.error.detail.ignore=!0}return o.response&&o.response.forEach(((t,o)=>{var a=m[o],u=t.type,h=t.name,I=t.reflectMapper;if(void 0!==a)switch(u){case"Property":g.content[h]=I?deserialize(a,I):a;break;case"PropertyArray":g.content[h]=a.map((t=>I?deserialize(t,I):t));break;case"Int":case"Long":case"Byte":g.content[h]=+a;break;case"Bool":g.content[h]="true"===a||!0===a||1===a;break;default:g.content[h]=a}})),g}function serialize(t,o,a){var m={};for(var u in t=function flattenObjByMapper(t,o){var a={};for(var m in o){var u=o[m],h="number"==typeof u?m:u.access?u.access:m,g=h.split("."),I=t;for(var M of g){if(void 0===I[M]||null===I[M]){I=void 0;break}I=I[M]}void 0!==I&&(a[h]=I)}return a}(t,o),o){var h=o[u],g="number"==typeof h?u:h.access?h.access:u;if(!a||a.includes(u))if(g in t){if("number"==typeof h)m[h]=t[g];else if("object"==typeof h)if(h.converter){var I=h.converter(t[g],t);void 0!==I&&(m[h.id]=I)}else m[h.id]=t[g]}else"object"==typeof h&&h.def&&("function"==typeof h.def?m[h.id]=h.def(t):m[h.id]=h.def)}return m}function deserialize(t,o){var a={};for(var m in t){var u=o[m];if("string"==typeof u)a[u]=t[m];else if("object"==typeof u&&"prop"in u){var h=u.access?u.access:u.prop;if(u.converter){var g=u.converter(t[m],t);void 0!==g&&(a[h]=g)}else u.type&&"number"===u.type?a[h]=+t[m]:u.type&&"boolean"===u.type?a[h]=!("0"===t[m]||!t[m]):a[h]=t[m]}}for(var I in o){var M=o[I];if(M&&void 0!==M.def){var _=M.access?M.access:M.prop;_ in a||("function"==typeof M.def?a[_]=M.def(t):a[_]=M.def)}}return a=function unflattenObj(t){var o={},_loop=function(a){var m=a.split(".");m.reduce((function(o,u,h){return o[u]||(o[u]=isNaN(Number(m[h+1]))?m.length-1==h?t[a]:{}:[])}),o)};for(var a in t)_loop(a);return o}(a),a}function registerParser(t){for(var o in Object.assign(Ge,t.cmdConfig),t.cmdMap){var a=t.cmdMap[o],m=t.cmdConfig[a];if(m)if(Array.isArray(qe[o])){var u=!1;for(var h of qe[o])if(h.cmd===a&&h.config.service===m.service){u=!0;break}u||qe[o].push({config:m,cmd:a})}else qe[o]=[{config:m,cmd:a}]}}function invertSerializeItem(t){var o={};for(var a in t){var m=t[a];"number"==typeof m?o[m]=a:"object"==typeof m&&(o[m.id]={prop:a,type:m.retType,access:m.retAccess?m.retAccess:m.access?m.access:a,def:m.retDef,converter:m.retConverter})}return o}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,o){if(!isPlainObject(o))return{};var a=JSON.parse(JSON.stringify(o)),m=doFormat(t,a);return JSON.parse(JSON.stringify(Object.assign(Object.assign({},a),m)))}function doFormat(t,o){if(!isPlainObject(o))return{};var a={};return Object.keys(t).forEach((m=>{var u=t[m].type;if("string"!=typeof u){var h=doFormat(t[m],o);Object.keys(h).length>0&&(a[m]=h)}else{var g=t[m],I=g.rawKey||m,M=He[u](o,I,g);void 0!==M&&(o[I]=void 0,a[m]=M)}})),a}var He={number:function(t,o){if(void 0!==t[o])return+t[o]},string:function(t,o){if(void 0!==t[o])return t[o]},boolean:function(t,o){return+t[o]>0||0!=+t[o]&&void 0},enum:function(t,o,a){return a.values[t[o]]},object:function(t,o){if(void 0!==t[o])try{return JSON.parse(t[o])}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"},Ke={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}},We={v2Login:{sid:26,cid:3,service:"auth",params:[{type:"Property",name:"tag",reflectMapper:Ke.webLoginReqTag}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Ke.mixAuthRepTag)},{type:"PropertyArray",name:"loginClients",reflectMapper:invertSerializeItem(Ke.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(Ke.mixAuthRepTag)}]},v2GetChatroomLinkAddress:{sid:36,cid:1,service:"auth",params:[{type:"Long",name:"roomId"},{type:"Bool",name:"miniProgram"}],response:[{type:"StrArray",name:"linkAddress"}]}},Je={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(Ke.nimAuthRepTag)}]},qchatLoginClientChange:{sid:24,cid:8,service:"auth",response:[{type:"Byte",name:"state"},{type:"Property",name:"data",reflectMapper:invertSerializeItem(Ke.qchatAuthRepTag)}]}},Xe=Backoff;function Backoff(t){t=t||{},this.ms=t.min||100,this.max=t.max||1e4,this.factor=t.factor||2,this.jitter=t.jitter>0&&t.jitter<=1?t.jitter:0,this.attempts=0}Backoff.prototype.duration=function(){var t=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var o=Math.random(),a=Math.floor(o*this.jitter*t);t=0==(1&Math.floor(10*o))?t-a:t+a}return 0|Math.min(t,this.max)},Backoff.prototype.reset=function(){this.attempts=0},Backoff.prototype.setMin=function(t){this.ms=t},Backoff.prototype.setMax=function(t){this.max=t},Backoff.prototype.setJitter=function(t){this.jitter=t};var abs=function(t){var o;if(void 0!==t)return(o=BigNumber(t)).sign=1,o},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}))},Qe="Invalid Number",Ze="Invalid Number - Division By Zero";function BigNumber(t){var o;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)),o=t.length-1;o>=0;o--)if(!this.addDigit(t[o]))return}else for("-"!==(t=t.toString()).charAt(0)&&"+"!==t.charAt(0)||(this.sign="+"===t.charAt(0)?1:-1,t=t.substring(1)),o=t.length-1;o>=0;o--)if(!this.addDigit(parseInt(t.charAt(o),10)))return}else this.number=Qe}BigNumber.prototype.addDigit=function(t){return function(t){return/^\d$/.test(t)}(t)?(this.number.push(t),this):(this.number=Qe,!1)},BigNumber.prototype._compare=function(t){var o,a;if(!isValidType(t))return null;if(o=BigNumber(t),this.sign!==o.sign)return this.sign;if(this.number.length>o.number.length)return this.sign;if(this.number.length<o.number.length)return-1*this.sign;for(a=this.number.length-1;a>=0;a--){if(this.number[a]>o.number[a])return this.sign;if(this.number[a]<o.number[a])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 o;return void 0===t?this:(o=BigNumber(t),this.sign!==o.sign?(this.number=BigNumber._add(this,o),this):(this.sign=this.lt(o)?-1:1,this.number=abs(this).lt(abs(o))?BigNumber._subtract(o,this):BigNumber._subtract(this,o),this))},BigNumber._add=function(t,o){var a,m=0,u=Math.max(t.number.length,o.number.length);for(a=0;a<u||m>0;a++)t.number[a]=(m+=(t.number[a]||0)+(o.number[a]||0))%10,m=Math.floor(m/10);return t.number},BigNumber._subtract=function(t,o){var a,m=0,u=t.number.length;for(a=0;a<u;a++)t.number[a]-=(o.number[a]||0)+m,t.number[a]+=10*(m=t.number[a]<0?1:0);for(a=0,u=t.number.length-1;0===t.number[u-a]&&u-a>0;)a++;return a>0&&t.number.splice(-a),t.number},BigNumber.prototype.multiply=function(t){if(void 0===t)return this;var o,a,m=BigNumber(t),u=0,h=[];if(this.isZero()||m.isZero())return BigNumber(0);for(this.sign*=m.sign,o=0;o<this.number.length;o++)for(u=0,a=0;a<m.number.length||u>0;a++)h[o+a]=(u+=(h[o+a]||0)+this.number[o]*(m.number[a]||0))%10,u=Math.floor(u/10);return this.number=h,this},BigNumber.prototype.divide=function(t){if(void 0===t)return this;var o,a,m=BigNumber(t),u=[],h=BigNumber(0);if(m.isZero())return this.number=Ze,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(o=this.number.length-1;o>=0;o--)for(h.multiply(10),h.number[0]=this.number[o],u[o]=0;m.lte(h);)u[o]++,h.subtract(m);for(o=0,a=u.length-1;0===u[a-o]&&a-o>0;)o++;return o>0&&u.splice(-o),this.rest=h,this.number=u,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,o="";if("string"==typeof this.number)return this.number;for(t=this.number.length-1;t>=0;t--)o+=this.number[t];return this.sign>0?o:"-"+o};var et,rt=Math.pow(2,32);function varintToBytes(t){for(var o=new Uint8Array(5),a=new DataView(o.buffer),m=0;0!=(4294967168&t);)a.setUint8(m++,127&t|128),t>>>=7;return a.setUint8(m++,127&t),o.slice(0,m)}function decodeText(t){return"function"==typeof TextDecoder?new TextDecoder("utf-8").decode(t):function textDecoder(t){for(var o="",a=0;a<t.length;){var m=t[a],u=0,h=0;if(m<=127?(u=0,h=255&m):m<=223?(u=1,h=31&m):m<=239?(u=2,h=15&m):m<=244&&(u=3,h=7&m),t.length-a-u>0)for(var g=0;g<u;)h=h<<6|63&(m=t[a+g+1]),g+=1;else h=65533,u=t.length-a;o+=String.fromCodePoint(h),a+=u+1}return o}(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 o=this.buffer.slice(this.offset,this.offset+t);return this.offset+=t,o}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,o=0,a=0,m=0;do{if(o+=(127&(a=this.popByte()))*t,t*=128,(m+=1)>5)throw new Error("Variable length quantity is too long")}while(0!=(128&a));return o}popLong(){try{var t=function getBigUint64(t,o=!1){var a=new DataView(t.buffer),[m,u]=o?[4,0]:[0,4],h=a.getUint32(m,o),g=a.getUint32(u,o);return h>0?h*rt+g:g}(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(),o=this.unpack.popByte(),a=this.unpack.popByte(),m=this.unpack.popShort(),u=this.unpack.popByte(),h=200;return this.hasRescode(u)&&(h=this.unpack.popShort()),{packetLength:t,serviceId:o,commandId:a,serialId:m,tag:u,resCode:h}}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(),o={};this.bodyArr.push(`\nProperty(${t}) {`);for(var a=0;a<t;a++){var m=this.unpack.popVarInt();this.bodyArr.push(`${m}:`);var u=this.unpack.popString();this.bodyArr.push(`"${u.length} ${this.unpack.getOffset()}",`),o[m]=u}return this.bodyArr.push("},"),o}unmarshalPropertyArray(){var t=this.unpack.popVarInt(),o=[];this.bodyArr.push(`\nPropertyArray(${t}) [`);for(var a=0;a<t;a++)o.push(this.unmarshalProperty());return this.bodyArr.push("],"),o}unmarshalLong(){var t=this.unpack.popLong();return this.bodyArr.push(`\nLong:${t}`),t}unmarshalLongArray(){var t=this.unpack.popVarInt(),o=[];this.bodyArr.push(`\nLongArray ${t}:`);for(var a=0;a<t;a++){var m=this.unpack.popLong();this.bodyArr.push(`${m},`),o.push(m)}return o}unmarshalStrArray(){var t=this.unpack.popVarInt(),o=[];this.bodyArr.push(`\nStrArray ${t}:`);for(var a=0;a<t;a++){var m=this.unpack.popString();this.bodyArr.push(`${m},`),o.push(m)}return o}unmarshalStrLongMap(){var t=this.unpack.popVarInt(),o={};this.bodyArr.push(`\nStrLongMap ${t}:`);for(var a=0;a<t;a++){var m=this.unpack.popString();this.bodyArr.push(`${m},`);var u=this.unpack.popLong();this.bodyArr.push(`${u};`),o[m]=u}return o}unmarshalStrStrMap(){var t=this.unpack.popVarInt(),o={};this.bodyArr.push(`\nStrStrMap ${t}:`);for(var a=0;a<t;a++){var m=this.unpack.popString();this.bodyArr.push(`${m},`);var u=this.unpack.popString();this.bodyArr.push(`${u};`),o[m]=u}return o}unmarshalLongLongMap(){var t=this.unpack.popVarInt(),o={};this.bodyArr.push(`\nStrLongLongMap ${t}:`);for(var a=0;a<t;a++){var m=this.unpack.popLong();this.bodyArr.push(`${m},`);var u=this.unpack.popLong();this.bodyArr.push(`${u};`),o[m]=u}return{m_map:o}}unmarshalKVArray(){var t=this.unpack.popVarInt(),o=[];this.bodyArr.push(`\nKVArray ${t}:`);for(var a=0;a<t;a++)o.push(this.unmarshalStrStrMap());return o}unmarshal(t){var o=Object.assign(Object.assign({},this.getHeader()),{r:[]});if(this.innerHeader&&(o.r[0]=this.msgId,o.r[1]={body:[],headerPacket:this.getInnerHeader()}),![200,406,808,810,7101].includes(o.code))return JSON.stringify(o);if(this.packetLength>0&&this.packetLength>this.unpack.length())throw new Error(`UnpackException packetLength(${this.packetLength}) greater than bufferLength(${this.unpack.length()})`);var a=[];return t&&t.forEach((t=>{if(!this.unpack.checkBufferBoundaryAccess())switch(t.type){case"PropertyArray":a.push(this.unmarshalPropertyArray());break;case"Property":a.push(this.unmarshalProperty());break;case"Byte":a.push(this.unpack.popByte());break;case"Int":a.push(this.unpack.popInt());break;case"Bool":a.push(this.unpack.popBoolean());break;case"Long":a.push(this.unmarshalLong());break;case"LongArray":a.push(this.unmarshalLongArray());break;case"String":a.push(this.unpack.popString());break;case"StrArray":a.push(this.unmarshalStrArray());break;case"StrStrMap":a.push(this.unmarshalStrStrMap());break;case"StrLongMap":a.push(this.unmarshalStrLongMap());break;case"LongLongMap":a.push(this.unmarshalLongLongMap());break;case"KVArray":a.push(this.unmarshalKVArray())}})),this.innerHeader?o.r[1].body=a:o.r=a,JSON.stringify(o)}}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 o=this.offset+t;if(o>this.capacity)throw new Error("PackException over limit");if(o>this.buffer.byteLength){var a=Math.ceil(o/this.pageSize)*this.pageSize,m=new Uint8Array(a);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 o=function encodeText(t){if("function"==typeof TextEncoder)return(new TextEncoder).encode(t);var o=function textEncoder(t){for(var o=[],a=t.length,m=0;m<a;){var u=t.codePointAt(m),h=0,g=0;for(u<=127?(h=0,g=0):u<=2047?(h=6,g=192):u<=65535?(h=12,g=224):u<=2097151&&(h=18,g=240),o.push(g|u>>h),h-=6;h>=0;)o.push(128|u>>h&63),h-=6;m+=u>=65536?2:1}return o}(t);return new Uint8Array(o)}(t);this.putVarbin(o)}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 o=varintToBytes(t);this.putRaw(o)}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 o=function setBigUint64(t,o=!1){var a=new Uint8Array(8),m=new DataView(a.buffer),u=Number(t>rt-1?t/rt:0),h=Number(4294967295&t),[g,I]=o?[4,0]:[0,4];return m.setUint32(g,u,o),m.setUint32(I,h,o),a}(t,!0);this.buffer.set(o,this.offset),this.offset+=8}catch(t){throw new Error("PackException long")}}putStringAsLong(t){this.ensureCapacity(8);try{var o=function setBigUint64ForNumberOverflow(t,o=!1){var a=new Uint8Array(8),m=new DataView(a.buffer),u=BigNumber(t).divide(rt).number.reverse().join(""),h=BigNumber(t).mod(rt).number.reverse().join(""),g=Number(u),I=Number(h),[M,_]=o?[4,0]:[0,4];return m.setUint32(M,g,o),m.setUint32(_,I,o),a}(t,!0);this.buffer.set(o,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 o=varintToBytes(t.length);this.ensureCapacity(o.length+t.length);try{this.buffer.set(o,this.offset),this.offset+=o.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,o,a){this.pack=new Pack,this.packetLength=0,this.serviceId=0,this.commandId=0,this.serialId=0,this.tag=0,this.serviceId=t,this.commandId=o,this.serialId=a}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 o=Object.keys(t).filter((t=>!isUndefinedOrNull(t)));this.pack.putVarInt(o.length),o.forEach((o=>{this.pack.putVarInt(Number(o)),Array.isArray(t[o])||"[object Object]"===Object.prototype.toString.call(t[o])?this.pack.putString(JSON.stringify(t[o])):this.pack.putString(String(t[o]))}))}marshalPropertyArray(t){var o=t.length;this.pack.putVarInt(o),t.forEach((t=>{this.marshalProperty(null==t?void 0:t.v)}))}marshalStrArray(t){var o=t.filter((t=>!isUndefinedOrNull(t))),a=o.length;this.pack.putVarInt(a),o.forEach((t=>{this.pack.putString(String(t))}))}marshalLongArray(t){var o=t.filter((t=>isConvertibleToNumber(t))),a=o.length;this.pack.putVarInt(a),o.forEach((t=>{this.putLong(t)}))}marshalStrStrMap(t){var o=Object.keys(t).filter((o=>!isUndefinedOrNull(t[o])&&!isUndefinedOrNull(o)));this.pack.putVarInt(o.length),o.forEach((o=>{this.pack.putString(String(o)),this.pack.putString(String(t[o]))}))}marshalStrLongMap(t){var o=Object.keys(t).filter((o=>isConvertibleToNumber(t[o])&&!isUndefinedOrNull(o)));this.pack.putVarInt(o.length),o.forEach((o=>{this.pack.putString(String(o)),this.putLong(t[o])}))}marshalLongLongMap(t){var o=Object.keys(t).filter((o=>{var a=Number(o);return isConvertibleToNumber(a)&&isConvertibleToNumber(t[a])}));this.pack.putVarInt(o.length),o.forEach((o=>{var a=Number(o);this.putLong(a),this.putLong(t[a])}))}marshalKVArray(t){var o=t.length;this.pack.putVarInt(o),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,o){return this.marshalHeader(),o&&o.forEach(((o,a)=>{var m,u=o.type,h=null===(m=t[a])||void 0===m?void 0:m.v;if(!isUndefinedOrNull(h))switch(u){case"PropertyArray":this.marshalPropertyArray(h);break;case"Property":this.marshalProperty(h);break;case"Byte":if(!isConvertibleToNumber(h))return;this.pack.putByte(Number(h));break;case"Int":if(!isConvertibleToNumber(h))return;this.pack.putInt(Number(h));break;case"Bool":"false"===h?h=!1:"true"===h&&(h=!0),this.pack.putBoolean(h);break;case"Long":if(!isConvertibleToNumber(h))return;this.putLong(h);break;case"LongArray":this.marshalLongArray(h);break;case"String":this.pack.putString(String(h));break;case"StrArray":this.marshalStrArray(h);break;case"StrStrMap":this.marshalStrStrMap(h);break;case"StrLongMap":this.marshalStrLongMap(h);break;case"LongLongMap":this.marshalLongLongMap(h);break;case"KVArray":this.marshalKVArray(h)}})),this.pack.getBuffer()}reset(){this.pack.reset()}}class BaseWebsocket$1 extends ve{constructor(t,o,a){super(),this.websocket=null,this.socketConnectTimer=0,this.linkSSL=!0,this.url="",this.core=t,this.url=o,this.linkSSL=a,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")?Me.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 Ae.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")?Me.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")?Me.V2NIM_ERROR_CODE_CONNECT_FAILED:414,detail:{reason:"imsocket::Websocket onerror."}})))},this.websocket.onopen=()=>{this.onConnect()}}onMessage(t){if(t.data){var o=new PacketDecoder(t.data),a={sid:-1,cid:-1,ser:-1,packetLength:-1},m=null;try{o.unmarshalHeader(),a=o.getHeader(),m=o.getInnerHeader()}catch(o){this.reportBinaryError({err:o,sid:m?m.sid:null==a?void 0:a.sid,cid:m?m.cid:null==a?void 0:a.cid,rawBuf:t.data,type:"decode"})}var u=m?m.sid:a.sid,h=m?m.cid:a.cid,g=`${u}_${h}`,I=qe[g];if(I&&I.length>0){var M,_=I[0].config;try{M=o.unmarshal(_.response)}catch(m){var E=o.getBodyDetail();this.reportBinaryError({err:m,rawBuf:t.data,sid:u,cid:h,parseDetail:E,type:"decode"}),o.reset();var S=Object.assign(Object.assign({},a),{sid:u,cid:h,code:Me.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",M)}else this.core.logger.warn("imsocket::onMessage cmd not found",g);o.reset()}}send(t,o,a,m,u){var h,g,I=new PacketEncoder(t,o,a),M=Ge[m],_="";try{_=JSON.stringify(u),g=I.marshal(JSON.parse(_),M.params)}catch(m){throw this.reportBinaryError({err:m,sid:t,cid:o,rawStr:_,type:"encode"}),I.reset(),new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_PACK_ERROR,detail:{reason:`${t}-${o}, ser ${a} marshal error`,rawError:m}})}null===(h=this.websocket)||void 0===h||h.send(g),I.reset()}reportBinaryError(t){var o,a,m,{err:u,rawStr:h,sid:g,cid:I,type:M,parseDetail:_}=t,E=t.rawBuf;if(E){try{m=function arrayBufferToBase64(t){if("function"!=typeof btoa)return"";for(var o="",a=new Uint8Array(t),m=a.byteLength,u=0;u<m;u++)o+=String.fromCharCode(a[u]);return a=null,btoa(o)}(E)}catch(t){m=`reportBinaryError::arrayBufferToBase64 parsing failed, error: ${null==t?void 0:t.message}, sid: ${g}, cid: ${I}`,this.core.logger.error(m)}E=null}this.core.reporter.reportTraceStart("exceptions",{user_id:null===(o=this.core.auth)||void 0===o?void 0:o.account,trace_id:null===(a=this.core.clientSocket.socket)||void 0===a?void 0:a.sessionId,start_time:Date.now(),action:2,exception_service:9});var S=u?(`${u.message};;;`||`${u.code};;;`)+(_?`parseDetail: ${_};;;`:"")+(h?` rawStr: ${h}`:"")+(m?` rawBuf: ${m}`:""):"";this.core.reporter.reportTraceUpdateV2("exceptions",{code:"encode"===M?Me.V2NIM_ERROR_CODE_PACK_ERROR:Me.V2NIM_ERROR_CODE_UNPACK_ERROR,description:S,operation_type:"encode"===M?3:4,target:`${g}-${I}`},{asyncParams:Ae.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"}(et||(et={}));class V2BinaryClientSocket{constructor(t){this.isReconnect=!1,this.packetTimeout=8e3,this.linkSSL=!0,this.packetSer=1,this.backoff=new Xe({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,o=!1){var a,m;return __awaiter(this,void 0,void 0,(function*(){this.isReconnect=o;var u=this.core.auth.getConnectStatus();if(1===u){var h=`clientSocket::connect status is ${u}, and would not repeat connect`,g=new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_ILLEGAL_STATE,detail:{reason:h}});return this.logger.warn(h),Promise.reject(g)}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: ${o}`),this.core.reporter.reportTraceUpdateV2("login",{operation_type:"TCP",target:t,code:200,mixlink:!0,succeed:!0},{asyncParams:Ae.net.getNetworkStatus()}),this.auth.lifeCycle.processEvent("connectSucc")}catch(o){var I=o;if(this.core.reporter.reportTraceUpdateV2("login",{operation_type:"TCP",target:t,code:I.code||0,description:`connectFailed:${I.message}`,mixlink:!0,succeed:!1},{asyncParams:Ae.net.getNetworkStatus()}),I.code===Me.V2NIM_ERROR_CODE_CANCELLED||I.code===Me.V2NIM_ERROR_CODE_TIMEOUT)throw null===(a=this.socket)||void 0===a||a.close(),null===(m=this.socket)||void 0===m||m.removeAllListeners(),this.socket=void 0,o;throw this.logger.warn(`clientSocketV2::connect failed with link url: ${t}`,I),this.auth.lifeCycle.processEvent("connectFail",I),o}}))}doConnect(t){var o=!1;return new Promise(((a,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}),o=!0,a()})),this.socket.on("message",this.onMessage.bind(this)),this.socket.on("disconnect",(a=>__awaiter(this,void 0,void 0,(function*(){o=!0,this.logger.log(`clientSocketV2::socket on disconnect ${t}`,a),yield this.core.reporterHookLinkKeep.update({code:(null==a?void 0:a.code)||0,description:(null==a?void 0:a.reason)||"socket on disconnect",operation_type:1,target:t}),this.core.reporterHookLinkKeep.end(!1),this.doDisconnect(et.OFFLINE,"SocketOnDisconnect")})))),this.socket.on("connectFailed",(a=>{o?this.ping():(this.logger.error(`clientSocketV2::connectFailed:${t}, reason:${a&&a.message}`),this.cleanSocket()),o=!0,m(a)}))}))}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,o){if(this.logger.log(`clientSocketV2::doDisconnect:type:${t},reason:`,o),0!==this.core.auth.getConnectStatus()){var a={1:"close",2:"kicked",3:"broken"}[t]||"";this.markAllCmdInvaild(new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_DISCONNECT,detail:{reason:"Packet timeout due to instance disconnect",disconnect_reason:a}})),this.timerManager.destroy(),clearTimeout(this.pingTimer),this.cleanSocket(),t===et.ACTIVE||t===et.KICKED?this.destroyOnlineListener():t===et.OFFLINE&&(this.auth.lifeCycle.processEvent("connectionBroken",new V2NIMErrorImpl({code:Me.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,o,a){var m=this.core.auth.getLoginStatus(),u={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:Me.V2NIM_ERROR_CODE_ILLEGAL_STATE,detail:Object.assign({reason:"Can not sendCmd due to no logined"},u)}));var h="heartbeat"!==t,g=h?this.packetSer++:0,I=createCmd(t,g,this.logger,o);if(!I){var M=new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_INTERNAL,detail:Object.assign(Object.assign({},u),{reason:`SendCmd::createCmd error: ${g} ${t}`})});return this.logger.error(M),Promise.reject(M)}var{packet:_,hasPacketResponse:E,hasPacketTimer:S}=I,T=JSON.stringify(_);h&&(this.logger.getDebugMode()?this.logger.debug(`clientSocketV2::sendCmd: ${_.SID}_${_.CID},${t},ser:${g}`,T):this.logger.log(`clientSocketV2::sendCmd: ${_.SID}_${_.CID},${t},ser:${g}`));var C=(new Date).getTime();return new Promise(((m,h)=>{E&&this.sendingCmdMap.set(g,{cmd:t,params:o,callback:[m,h],timer:S?setTimeout((()=>{var o=new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_PROTOCOL_TIMEOUT,detail:Object.assign({ser:g,reason:`Packet Timeout: ser ${g} cmd ${t}`,timetag:(new Date).getTime()},u)});this.markCmdInvalid(g,o,t)}),a&&a.timeout?a.timeout:this.packetTimeout):null});try{this.socket.send(_.SID,_.CID,g,t,_.Q),E||m(_)}catch(o){var I=new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_PROTOCOL_SEND_FAILED,detail:Object.assign({ser:g,reason:"Unable to send packet"+(o&&o.message?": "+o.message:""),timetag:(new Date).getTime(),rawError:o},u)});this.markCmdInvalid(g,I,t),h(I)}})).catch((t=>__awaiter(this,void 0,void 0,(function*(){var o=t;return[Me.V2NIM_ERROR_CODE_DISCONNECT,Me.V2NIM_ERROR_CODE_PROTOCOL_TIMEOUT,Me.V2NIM_ERROR_CODE_PROTOCOL_SEND_FAILED].includes(o.code)?(this.reportSendCmdFailed(o,{sid:_.SID,cid:_.CID,ser:g},C),Promise.reject(o)):Promise.reject(o)}))))}reportSendCmdFailed(t,o,a){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:a,action:2,exception_service:6});var u=get(t,"detail.disconnect_reason")||"",h=t.code===Me.V2NIM_ERROR_CODE_DISCONNECT?JSON.stringify({disconnect_reason:u}):t.detail.reason;this.reporter.reportTraceUpdateV2("exceptions",{code:t.code,description:h,operation_type:1,target:`${o.sid}-${o.cid}`,context:`${o.ser}`},{asyncParams:Ae.net.getNetworkStatus()}),this.reporter.reportTraceEnd("exceptions",1)}onMessage(t){var o=parseCmd(t,this.logger);if(o&&o.length>0){var a=o[0],m=a.raw.ser;for(var u of(a.error&&(this.logger.error("clientSocketV2::onMessage packet error",`${a.raw.sid}_${a.raw.cid}, ser:${m},`,a.error),a.error.code===Me.V2NIM_ERROR_CODE_UNPACK_ERROR&&this.core.eventBus.emit("BinaryClientSocket/unpackError")),"heartbeat"!==a.cmd&&(this.logger.getDebugMode()?this.logger.debug(`clientSocketV2::recvCmd ${a.raw.sid}_${a.raw.cid},${a.cmd},ser:${m}`,t):this.logger.log(`clientSocketV2::recvCmd ${a.raw.sid}_${a.raw.cid},${a.cmd},ser:${m},code:${a.raw.code}`)),o))this.packetHandler(u)}}packetHandler(t){var o,a,m,u;if(t){var h=t.raw.ser,g=this.sendingCmdMap.get(h);if(g&&g.cmd===t.cmd){var{callback:I,timer:M,params:_}=g;if(clearTimeout(M),t.params=_,this.sendingCmdMap.delete(h),"heartbeat"===t.cmd)return void I[0]();var E=null===(a=null===(o=this.core[t.service])||void 0===o?void 0:o.process)||void 0===a?void 0:a.call(o,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===(u=null===(m=this.core[t.service])||void 0===m?void 0:m.process)||void 0===u?void 0:u.call(m,t);S&&"function"==typeof S.then&&S.catch((t=>{this.logger.error("clientSocketV2::no obj cache, no process handler",t)}))}}}markCmdInvalid(t,o,a){var m=this.sendingCmdMap.get(t);if(m){var{callback:u,timer:h}=m;h&&clearTimeout(h),this.sendingCmdMap.delete(t),this.logger.warn(`clientSocketV2::packet ${t}, ${a} is invalid:`,o),u[1](o)}}markAllCmdInvaild(t){this.logger.log("markAllCmdInvaild",t),this.sendingCmdMap.forEach((o=>{var{callback:a,timer:m,cmd:u}=o;this.logger.log(`clientSocketV2::markAllCmdInvaild:cmd ${u}`),m&&clearTimeout(m),a[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(o){if(o.code===Me.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(et.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(o){this.logger.log(`clientSocketV2::test heartbeat ${t} Timeout`)}return!0}))}initOnlineListener(){this.hasNetworkListener||(this.logger.log("clientSocketV2::onlineListener:init"),this.hasNetworkListener=!0,Ae.net.onNetworkStatusChange((t=>{this.logger.log("clientSocketV2::onlineListener:network change",t);var o=this.auth.getLoginStatus();t.isConnected&&1===o?this.ping():t.isConnected&&3===o?(this.logger.log("clientSocketV2::onlineListener:online and connectStatus is waiting, do reLogin"),this.auth.reconnect.clearReconnectTimer(),this.auth.reconnect.doReLogin()):t.isConnected||this.doDisconnect(et.OFFLINE,"OfflineListener")})))}destroyOnlineListener(){this.logger.log("clientSocketV2::onlineListener:destroy"),Ae.net.offNetworkStatusChange(),this.hasNetworkListener=!1}}var it,ot=["disconnect","connect","heartbeat","message","json","event","ack","error","noop"],st=["transport not supported","client not handshaken","unauthorized"],nt=["reconnect"];class BaseWebsocket extends ve{constructor(t,o,a){super(),this.websocket=null,this.socketConnectTimer=0,this.url="",this.linkSSL=!0,this.core=t,this.url=o,this.linkSSL=a,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[o,a]=t.data.split(":");return this.sessionId=o,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/${o}`)}})).catch((t=>{if("connecting"===this.status){var o=`imsocket::XHR fail. raw message: "${(t=t||{}).message}", code: "${t.code}"`,a=t.code;a="v2"===get(this.core,"options.apiVersion")?t.code===Me.V2NIM_ERROR_CODE_CONNECT_TIMEOUT?Me.V2NIM_ERROR_CODE_CONNECT_TIMEOUT:Me.V2NIM_ERROR_CODE_CONNECT_FAILED:408===t.code?408:415;var m=new V2NIMErrorImpl({code:a,detail:{reason:o,rawError:t}});this.logger.error(o),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")?Me.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 Ae.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 o,a=this.decodePacket(t.data);if(a)switch(a.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",a.data);break;case"event":a.name&&this.emit(a.name,a.args);break;case"error":"unauthorized"===a.reason?this.emit("connect_failed",a.reason):this.emit("error",a.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")?Me.V2NIM_ERROR_CODE_CONNECT_FAILED:408,detail:{reason:`imsocket::Websocket connect failed, onMessage socket error. url: ${this.socketUrl}`}}));break;case"heartbeat":null===(o=this.websocket)||void 0===o||o.send(this.encodePacket({type:"heartbeat"}));break;default:this.logger.warn("imsocket::Websocket no handler type",a.type)}}encodePacket(t){var o,a,{type:m,id:u="",endpoint:h="",ack:g}=t,I=null;if(!m)return"";switch(m){case"error":o=t.reason?st.indexOf(t.reason):"",a=t.advice?nt.indexOf(t.advice):"",""===o&&""===a||(I=o+(""!==a?"+"+a:""));break;case"message":""!==t.data&&(I=t.data);break;case"event":o={name:t.name},o=t.args&&t.args.length?{name:t.name,args:t.args}:{name:t.name},I=JSON.stringify(o);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 M=[ot.indexOf(m),u+("data"===g?"+":""),h];return null!=I&&M.push(I),M.join(":")}decodePacket(t){if(t)if("�"!=t.charAt(0)){var o=t.match(/([^:]+):([0-9]+)?(\+)?:([^:]+)?:?([\s\S]*)?/);if(o){var a,[,m,u,h,g,I]=o,M={type:ot[+m],endpoint:g};switch(u&&(M.id=u,M.ack=!h||"data"),M.type){case"error":a=I.split("+"),M.reason=st[+a[0]]||"";break;case"message":M.data=I||"";break;case"connect":M.qs=I||"";break;case"event":try{var _=JSON.parse(I);M.name=_.name,M.args=_.args}catch(t){this.logger.error("imsocket::parseData::type::event error",t)}M.args=M.args||[];break;case"json":try{M.data=JSON.parse(I)}catch(t){this.logger.error("imsocket::parseData::type::json error",t)}break;case"ack":if((a=I.match(/^([0-9]+)(\+)?(.*)/))&&(M.ackId=a[1],M.args=[],a[3]))try{M.args=a[3]?JSON.parse(a[3]):[]}catch(t){this.logger.error("imsocket::parseData::type::ack error",t)}}return M}}else this.logger.error("imsocket::unrecognize dataStr",t.slice(0,20))}send(t){var o,a={data:t,type:"message",endpoint:""};null===(o=this.websocket)||void 0===o||o.send(this.encodePacket(a))}}!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 Xe({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,o=!1){var a,m;return __awaiter(this,void 0,void 0,(function*(){this.isReconnect=o;var u=this.core.auth.getConnectStatus();if(1===u){var h=`clientSocket::connect status is ${u}, and would not repeat connect`,g=new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_ILLEGAL_STATE,detail:{reason:h}});return this.logger.warn(h),Promise.reject(g)}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: ${o}`),this.core.reporter.reportTraceUpdateV2("login",{operation_type:"TCP",target:t,code:200,mixlink:!0,succeed:!0},{asyncParams:Ae.net.getNetworkStatus()}),this.auth.lifeCycle.processEvent("connectSucc")}catch(o){var I=o;if(this.core.reporter.reportTraceUpdateV2("login",{operation_type:"TCP",target:t,code:I.code||0,description:`connectFailed:${I.message}`,mixlink:!0,succeed:!1},{asyncParams:Ae.net.getNetworkStatus()}),I.code===Me.V2NIM_ERROR_CODE_CANCELLED||I.code===Me.V2NIM_ERROR_CODE_TIMEOUT)throw null===(a=this.socket)||void 0===a||a.close(),null===(m=this.socket)||void 0===m||m.removeAllListeners(),this.socket=void 0,o;throw this.logger.warn(`clientSocketV2::connect failed with link url: ${t}`,I),this.auth.lifeCycle.processEvent("connectFail",I),o}}))}doConnect(t){var o=!1;return new Promise(((a,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}),o=!0,a()})),this.socket.on("message",this.onMessage.bind(this)),this.socket.on("disconnect",(a=>__awaiter(this,void 0,void 0,(function*(){o=!0,this.logger.log("clientSocketV2::socket on disconnect",a),yield this.core.reporterHookLinkKeep.update({code:(null==a?void 0:a.code)||0,description:(null==a?void 0:a.reason)||"socket on disconnect",operation_type:1,target:t}),this.core.reporterHookLinkKeep.end(!1),this.doDisconnect(it.OFFLINE,"SocketOnDisconnect")})))),this.socket.on("handshakeFailed",(t=>{o?this.ping():(this.logger.error(`clientSocketV2::handshake failed: "${t&&t.message}"`),this.cleanSocket()),o=!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,o){if(this.logger.log(`clientSocketV2::doDisconnect:type:${t},reason:`,o),0!==this.core.auth.getConnectStatus()){var a={1:"close",2:"kicked",3:"broken"}[t]||"";this.markAllCmdInvaild(new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_DISCONNECT,detail:{reason:"Packet timeout due to instance disconnect",disconnect_reason:a}})),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:Me.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,o,a){var m=this.core.auth.getLoginStatus(),u={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:Me.V2NIM_ERROR_CODE_ILLEGAL_STATE,detail:Object.assign({reason:"Can not sendCmd due to no logined"},u)}));var h="heartbeat"!==t,g=h?this.packetSer++:0,I=createCmd(t,g,this.logger,o);if(!I){var M=new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_INTERNAL,detail:Object.assign(Object.assign({},u),{reason:`SendCmd::createCmd error: ${g} ${t}`})});return this.logger.error(M),Promise.reject(M)}var{packet:_,hasPacketResponse:E,hasPacketTimer:S}=I,T=JSON.stringify(_);h&&(this.logger.getDebugMode()?this.logger.debug(`clientSocketV2::sendCmd: ${_.SID}_${_.CID},${t},ser:${g}`,T):this.logger.log(`clientSocketV2::sendCmd: ${_.SID}_${_.CID},${t},ser:${g}`));var C=(new Date).getTime();return new Promise(((m,h)=>{E&&this.sendingCmdMap.set(g,{cmd:t,params:o,callback:[m,h],timer:S?setTimeout((()=>{var o=new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_PROTOCOL_TIMEOUT,detail:Object.assign({ser:g,reason:`Packet Timeout: ser ${g} cmd ${t}`,timetag:(new Date).getTime()},u)});this.markCmdInvalid(g,o,t)}),a&&a.timeout?a.timeout:this.packetTimeout):null});try{this.socket.send(T),E||m(_)}catch(o){var I=new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_PROTOCOL_SEND_FAILED,detail:Object.assign({ser:g,reason:"Unable to send packet"+(o&&o.message?": "+o.message:""),timetag:(new Date).getTime(),rawError:o},u)});this.markCmdInvalid(g,I,t),h(I)}})).catch((t=>__awaiter(this,void 0,void 0,(function*(){var o,a=t;if(![Me.V2NIM_ERROR_CODE_DISCONNECT,Me.V2NIM_ERROR_CODE_PROTOCOL_TIMEOUT,Me.V2NIM_ERROR_CODE_PROTOCOL_SEND_FAILED].includes(a.code))return Promise.reject(a);this.reporter.reportTraceStart("exceptions",{user_id:this.core.auth.getLoginUser(),trace_id:null===(o=this.socket)||void 0===o?void 0:o.sessionId,start_time:C,action:2,exception_service:6});var m=get(a,"detail.disconnect_reason")||"",u=a.code===Me.V2NIM_ERROR_CODE_DISCONNECT?JSON.stringify({disconnect_reason:m}):a.detail.reason;return this.reporter.reportTraceUpdateV2("exceptions",{code:a.code,description:u,operation_type:1,target:`${_.SID}-${_.CID}`,context:`${_.SER}`},{asyncParams:Ae.net.getNetworkStatus()}),this.reporter.reportTraceEnd("exceptions",1),Promise.reject(a)}))))}onMessage(t){var o=parseCmd(t,this.logger);if(o&&o.length>0){var a=o[0],m=a.raw.ser;for(var u of(a.error&&this.logger.error("clientSocketV2::onMessage packet error",`${a.raw.sid}_${a.raw.cid}, ser:${m},`,a.error),"heartbeat"!==a.cmd&&(this.logger.getDebugMode()?this.logger.debug(`clientSocketV2::recvCmd ${a.raw.sid}_${a.raw.cid},${a.cmd},ser:${m}`,a.content):this.logger.log(`clientSocketV2::recvCmd ${a.raw.sid}_${a.raw.cid},${a.cmd},ser:${m};code:${a.raw.code}`)),o))this.packetHandler(u)}}packetHandler(t){var o,a,m,u;if(t){var h=t.raw.ser,g=this.sendingCmdMap.get(h);if(g&&g.cmd===t.cmd){var{callback:I,timer:M,params:_}=g;if(clearTimeout(M),t.params=_,this.sendingCmdMap.delete(h),"heartbeat"===t.cmd)return void I[0]();var E=null===(a=null===(o=this.core[t.service])||void 0===o?void 0:o.process)||void 0===a?void 0:a.call(o,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===(u=null===(m=this.core[t.service])||void 0===m?void 0:m.process)||void 0===u?void 0:u.call(m,t);S&&"function"==typeof S.then&&S.catch((t=>{this.logger.error("clientSocketV2::no obj cache, no process handler",t)}))}}}markCmdInvalid(t,o,a){var m=this.sendingCmdMap.get(t);if(m){var{callback:u,timer:h}=m;h&&clearTimeout(h),this.sendingCmdMap.delete(t),this.logger.warn(`clientSocketV2::packet ${t}, ${a} is invalid:`,o),u[1](o)}}markAllCmdInvaild(t){this.logger.log("markAllCmdInvaild",t),this.sendingCmdMap.forEach((o=>{var{callback:a,timer:m,cmd:u}=o;this.logger.log(`clientSocketV2::markAllCmdInvaild:cmd ${u}`),m&&clearTimeout(m),a[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(o){if(o.code===Me.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(o){this.logger.log(`clientSocketV2::test heartbeat ${t} Timeout`)}return!0}))}initOnlineListener(){this.hasNetworkListener||(this.logger.log("clientSocketV2::onlineListener:init"),this.hasNetworkListener=!0,Ae.net.onNetworkStatusChange((t=>{this.logger.log("clientSocketV2::onlineListener:network change",t);var o=this.auth.getConnectStatus(),a=this.auth.getLoginStatus();t.isConnected&&1===a?this.ping():t.isConnected&&3===o?(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"),Ae.net.offNetworkStatusChange(),this.hasNetworkListener=!1}}class V2NIMLoginReconnect{constructor(t){var o,a;this.currenRetryCount=0,this.backoff=new Xe({max:8e3,min:1600,jitter:.01}),this.reconnectTimer=0,this.core=t,this.auth=t.V2NIMLoginService,null===(a=(o=Ae.powerMonitor).on)||void 0===a||a.call(o,"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,o;this.currenRetryCount=0,this.backoff.reset(),this.reconnectTimer&&clearTimeout(this.reconnectTimer),Ae.powerMonitor.destroy(),null===(o=(t=Ae.powerMonitor).off)||void 0===o||o.call(t,"onPowerMonitorTurnActive")}clearReconnectTimer(){this.reconnectTimer&&clearTimeout(this.reconnectTimer)}attempToReLogin(){var t=this.backoff.duration();if("function"==typeof this.reconnectDelayProvider)try{var o=this.reconnectDelayProvider(t);"number"==typeof o&&o>=0&&(t=o>=1e3?o:o+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(!Ae.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 o=t;if(this.core.logger.warn("reconnect::try login but failed due to",o),this.core.reporter.reportTraceEnd("login",!1),this.auth.checkLoginTerminalCode(o&&o.code))return this.auth.clientSocket.doDisconnect(et.ACTIVE,"ReloginTerminated"),void this.auth.lifeCycle.processEvent("exited",o);o&&399===o.code&&this.auth.lbs.reset(),this.auth.lifeCycle.processEvent("waiting")})),t}_setReconnectDelayProvider(t){this.reconnectDelayProvider=t}}function uniq(t){t=t||[];for(var o=[],a=0;a<t.length;a++)-1===o.indexOf(t[a])&&o.push(t[a]);return o}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 o=uniq(this.auth.config.lbsUrls);try{var a=yield this.ladderLoad(o);if(200!==a.status||!a.data)throw this.core.logger.error("V1NIMLoginService::getLbsInfos:error status",a.status,a),new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_INTERNAL,detail:{reason:`V2NIMLoginService::getLbsInfos failed, status ${a.status}`}});this.success(a)}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(o[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===Me.V2NIM_ERROR_CODE_CANCELLED||t===Me.V2NIM_ERROR_CODE_TIMEOUT}generateUrl(t){var o=(t=this.processLbsUrl(t)).indexOf("?")>-1?"&":"?";return t+o+"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,o,a,m){this.timer&&clearTimeout(this.timer);var u=t[o];this.timer=setTimeout((()=>{u&&(this.setLadderTimer(t,o+1,a,m),this.core.logger.log(`V2NIMLoginService::getLbsInfos ${o}:`,this.processLbsUrl(u)),this.reportForLbsStart(u,o),this.requstLbs(u).then((t=>{this.reset(),a(Object.assign(Object.assign({},t),{url:u}))})).catch((a=>{var h;if(this.core.logger.warn(`V2NIMLoginService::getLbsInfos ${o} failed:`,a),this.failedCount+=1,this.reportForFailOnce(u,a.code,(null===(h=a.detail)||void 0===h?void 0:h.reason)||a.message),this.failedCount>=t.length||this.checkTerminator(a.code))return this.reset(),void m(a)})))}),2e3)}ladderLoad(t){return new Promise(((o,a)=>{t.length>1&&this.setLadderTimer(t,1,o,a);var m=t[0];this.core.logger.log("V2NIMLoginService::getLbsInfos 0:",m),this.reportForLbsStart(m,0),this.requstLbs(m).then((t=>{this.reset(),o(Object.assign(Object.assign({},t),{url:m}))})).catch((o=>{var u;this.failedCount+=1,this.core.logger.warn("V2NIMLoginService::getLbsInfos 0 failed:",o),this.reportForFailOnce(m,o.code,(null===(u=o.detail)||void 0===u?void 0:u.reason)||o.message),(this.failedCount>=t.length||this.checkTerminator(o.code))&&(this.reset(),a(o))}))}))}success(t){var o,a,m=t.data.common,u=m["mix.link"]||[],h=m["link.default"]||[];this.socketLinkUrls=u.concat(h).concat(this.auth.config.linkUrl),t.data["nos-chunk"]&&(null===(o=this.core.cloudStorage)||void 0===o?void 0:o.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===(a=this.core.cloudStorage)||void 0===a?void 0:a.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,o){this.core.reporterHookLBS.updateBegin({target:t,index:o})}reportForLbsSuccess(t,o){this.core.reporterHookLBS.updateComplete({target:t,code:200,body:JSON.stringify(o)}),this.core.reporterHookLBS.end(!0),this.core.reporter.reportTraceUpdateV2("login",{operation_type:"HTTP",target:t,code:200,succeed:!0},{asyncParams:Ae.net.getNetworkStatus()})}reportForFailOnce(t,o,a){this.core.reporterHookLBS.updateComplete({target:t,code:o,body:a})}reportForFail(t,o,a){this.core.reporterHookLBS.end(!1),this.core.reporter.reportTraceUpdateV2("login",{operation_type:"HTTP",target:t,description:a,code:o,succeed:!1},{asyncParams:Ae.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 o,a;return __awaiter(this,void 0,void 0,(function*(){var m=yield this.auth.doLoginStepsManager.add(this.refreshLoginToken(this.auth.account)),u=yield this.auth.doLoginStepsManager.add(this.refreshThirdPartyExt(this.auth.account));this.auth.token=m;var h,g=Ae.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:100941,userAgent:this.core.options.loginSDKTypeParamCompat?"Native/10.9.41":g.userAgent.replace("{{appkey}}",this.core.options.appkey).slice(0,299),libEnv:this.core.options.flutterSdkVersion?"FLUTTER":this.core.options.loginSDKTypeParamCompat?void 0:g.libEnv,hostEnv:this.core.options.flutterSdkVersion?4:this.core.options.loginSDKTypeParamCompat?0:g.hostEnvEnum,sdkHumanVersion:this.core.options.flutterSdkVersion||"10.9.41",os:g.os,browser:g.browser,protocolVersion:1,customClientType:this.auth.config.customClientType,customTag:this.auth.config.customTag,thirdPartyExtension:u,isRoutable:!1===(null===(o=this.auth.loginOption.routeConfig)||void 0===o?void 0:o.routeEnabled)?0:1,env:null===(a=this.auth.loginOption.routeConfig)||void 0===a?void 0:a.routeEnvironment},M=g.os.toLowerCase(),_=110===g.hostEnvEnum;"UNIAPP"===Ae.platform&&_?(I.isReactNative=1,I.clientType="ios"===M?2:"android"===M?1:65,g.pushDeviceInfo&&g.pushDeviceInfo.MANUFACTURER&&(I.deviceInfo=JSON.stringify(Object.assign({IS_SUPPORT_HONOR:!0},g.pushDeviceInfo)))):"React Native"===Ae.platform&&(this.core.logger.log("V2NIMLoginService deviceInfo",this.core.V2NIMLoginService.deviceInfo,"os",M),I.isReactNative=1,I.clientType="ios"===M?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{h=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:Ae.net.getNetworkStatus()}),E.code===Me.V2NIM_ERROR_CODE_CANCELLED||E.code===Me.V2NIM_ERROR_CODE_TIMEOUT)throw E;throw this.processLoginFailed(E),E}var{data:S,loginClients:T}=h.content;return this.changeLoginClient(1,T),this.core.reporter.reportTraceUpdateV2("login",{operation_type:"protocol",target:"26-3",code:200,succeed:!0},{asyncParams:Ae.net.getNetworkStatus()}),this.loginClientOfThisConnection=formatLoginInfo(S),this.core.clientSocket.setSessionId(S.consid),Ae.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 o=yield this.auth.loginOption.tokenProvider(t);if("string"==typeof o)return o;throw this.core.logger.error("V2NIMLoginService::excute tokenProvider complete but got Unexpected value:",o),new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_CALLBACK_FAILED,detail:{reason:"Excute tokenProvider complete but got Unexpected value",rawData:o}})}catch(t){var a=t,m=a;throw a.code!==Me.V2NIM_ERROR_CODE_CALLBACK_FAILED&&(this.core.logger.error("V2NIMLoginService::excute tokenProvider error:",a),m=new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_CALLBACK_FAILED,desc:"Excute tokenProvider error",detail:{rawError:t}})),this.processLoginFailed(a),m}}))}refreshThirdPartyExt(t){return __awaiter(this,void 0,void 0,(function*(){if("function"!=typeof this.auth.loginOption.loginExtensionProvider)return"";try{var o=yield this.auth.loginOption.loginExtensionProvider(t);if("string"==typeof o)return o;throw this.core.logger.error("V2NIMLoginService::excute loginExtensionProvider complete but got Unexpected value:",o),new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_CALLBACK_FAILED,detail:{reason:"Excute loginExtensionProvider complete but got Unexpected value",rawData:o}})}catch(t){var a=t,m=a;if(a.code!==Me.V2NIM_ERROR_CODE_CALLBACK_FAILED&&(this.core.logger.error("V2NIMLoginService::excute loginExtensionProvider error:",a),m=new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_CALLBACK_FAILED,detail:{reason:"Excute loginExtensionProvider error",rawError:t}})),2===this.auth.loginOption.authType)throw this.processLoginFailed(a),m;return""}}))}processLoginFailed(t){this.auth.clientSocket.doDisconnect(et.ACTIVE,t),this.checkLoginTerminalCode(t.code)&&(this.auth.authenticator.reset(),this.auth.authenticator.clearLastLoginClient()),this.auth.lifeCycle.processEvent("loginFail",t)}changeLoginClient(t,o){var a=o.map((t=>formatLoginInfo(t)));if(1===t)this.loginClients=a,this.auth.emit("onLoginClientChanged",t,this.loginClients);else if(2===t){var m=a.filter((t=>{var o=this.loginClients.filter((o=>o.clientId===t.clientId));return this.loginClients.push(t),0===o.length}));m.length>0&&this.auth.emit("onLoginClientChanged",t,m)}else if(3===t){var u=a.filter((t=>(function remove(t,o){o=o||(()=>!0);for(var a=[],m=(t=t||[]).length,u=0,h=0;h<m;h++)o(t[h-u])&&(a.push(t.splice(h-u,1)[0]),u+=1);return a}(this.loginClients,(o=>o.clientId===t.clientId&&o.consid===t.consid)),0===this.loginClients.filter((o=>o.clientId===t.clientId)).length)));u.length>0&&this.auth.emit("onLoginClientChanged",t,u)}}checkAutoLogin(t){if(t)return!1;var o=Ae.localStorage.getItem(this.lastLoginClientKey);if(!o)return!1;var a="",m="";try{var u=JSON.parse(o);a=get(u,"clientId"),m=get(u,"account")}catch(t){return!1}return a===this.auth.deviceId&&m===this.auth.account}checkLoginTerminalCode(t){return[Me.V2NIM_ERROR_CODE_CANCELLED,Me.V2NIM_ERROR_CODE_TIMEOUT,Me.V2NIM_ERROR_CODE_HANDSHAKE,302,317,Me.V2NIM_ERROR_CODE_FORBIDDEN,Me.V2NIM_ERROR_CODE_NOT_FOUND,Me.V2NIM_ERROR_CODE_PARAMETER_ERROR,Me.V2NIM_ERROR_CODE_MULTI_LOGIN_FORBIDDEN,422,Me.V2NIM_ERROR_CODE_IM_DISABLED,Me.V2NIM_ERROR_CODE_APPKEY_NOT_EXIST,Me.V2NIM_ERROR_CODE_BUNDLEID_CHECK_FAILED,Me.V2NIM_ERROR_CODE_APPKEY_BLOCKED,Me.V2NIM_ERROR_CODE_INVALID_TOKEN,Me.V2NIM_ERROR_CODE_ROBOT_NOT_ALLOWED,Me.V2NIM_ERROR_CODE_ACCOUNT_NOT_EXIST,Me.V2NIM_ERROR_CODE_ACCOUNT_BANNED,Me.V2NIM_ERROR_CODE_USER_PROFILE_NOT_EXIST].includes(t)}reset(){this.loginClients=[],this.loginClientOfThisConnection={}}clearLastLoginClient(){Ae.localStorage.removeItem(this.lastLoginClientKey)}}class V2Service extends ve{constructor(t,o){super(),this.name=t,this.logger=o.logger,this.core=o}checkV2(){var t=this.core.options.apiVersion;if("v2"===t)return!0;throw new V2NIMErrorImpl({code:Me.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:Me.V2NIM_ERROR_CODE_ILLEGAL_STATE,detail:{reason:"Client logout."}})}emit(t,...o){this.logger.debug(`${this.name}::emit event: '${t.toString()}',`,void 0!==o[0]?o[0]:"",void 0!==o[1]?o[1]:"",void 0!==o[2]?o[2]:"");try{return super.emit(t,...o)}catch(o){return setTimeout((()=>{throw this.logger.error(`${this.name}::emit throw error in setTimeout. event: ${t.toString()}. Error`,o),o}),0),!1}}process(t){var o=this[t.cmd+"Handler"],a=this.handler&&this.handler[t.cmd+"Handler"];if("function"==typeof o||"function"==typeof a){if(t.error)return this.logger.error(`${t.cmd}::recvError`,t.error),Promise.reject(t.error);try{var m=o?o.call(this,t):a.call(this.handler,t);return Promise.resolve(m)}catch(t){return Promise.reject(t)}}var u=get(t,"error.detail.ignore");return t.error&&!u?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,o,a){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`,o),this.setLoginStatus(3),this.setConnectStatus(0,o);break;case"connectionBroken":this.logger.log(`${this.name}::connectionBroken:`,o),this.setLoginStatus(3),this.setConnectStatus(0,o),this.core.eventBus.emit("V2NIMLoginService/loginLifeCycleDisconnected",o);break;case"loginSucc":this.logger.log(`${this.name}::login success, verify authentication success`),this.setLoginStatus(1),this.core.eventBus.emit("V2NIMLoginService/loginLifeCycleLoginSucc",a);break;case"loginFail":if(this.logger.log(`${this.name}::login fail due to verify authentication failed:`,o),!o)return;this.setLoginStatus(this.auth.authenticator.checkLoginTerminalCode(o.code)?0:3),this.setConnectStatus(0,o),this.auth.emit("onLoginFailed",o);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`,a),this.setLoginStatus(0),this.setConnectStatus(0,o),this.core.eventBus.emit("V2NIMLoginService/loginLifeCycleKicked");break;case"exited":this.logger.log(`${this.name}::exited`,o),this.setLoginStatus(0),this.setConnectStatus(0,o);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,o){if(t!==this.connectStatus){var a=this.connectStatus;this.connectStatus=t,this.auth.emit("onConnectStatus",t),this.delegateConnectEvent(a,t,o)}}delegateConnectEvent(t,o,a){1===t&&0===o&&a&&this.auth.emit("onDisconnected",a),2===t&&0===o&&a&&this.auth.emit("onConnectFailed",a)}}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:o,state:a,error:m,subType:u}=t,h=this.datas.filter((t=>t.type===o&&t.subType===u));h.length>0?(h[0].state=a,h[0].error=m):this.datas.push({type:o,state:a,subType:u});var g=this.datas.every((t=>3===t.state));1===o&&(2===a&&"mainSync"===u?(this.core.eventBus.emit("V2NIMLoginService/syncing"),this.auth.emit("onDataSync",o,a)):3===a&&g&&(this.core.eventBus.emit("V2NIMLoginService/syncDone",m),this.auth.emit("onDataSync",o,a,m)))}))}checkSyncing(){return this.datas.some((t=>"mainSync"===t.subType&&2===t.state))}reset(){this.datas=[]}}var at={"6_3":"notifylog","6_4":"uploadLog","6_23":"getServerTime","6_31":"notifyDetect","6_32":"uploadDetect","6_37":"wsDetect"},ct={type:1,params:2,result:3,t1:100,t2:101,t3:102,t4:103,t5:104,t6:105},dt={k1:1,k2:2,k3:3,k4:4,k5:5,k6:6,k7:7,k8:8,k9:9,k10:10},lt={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(ct)}]},uploadDetect:{sid:6,cid:32,service:"misc",hasPacketResponse:!1,params:[{type:"Property",name:"data",reflectMapper:ct}]},wsDetect:{sid:6,cid:37,service:"misc",params:[{type:"Property",name:"tag",reflectMapper:dt}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(dt)}]}},pt={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,o){this.name=t,this.core=o,this.name=t,this.logger=o.logger,this.core=o}process(t){var o=this[t.cmd+"Handler"];if("function"==typeof o)return o.call(this,t);var a=get(t,"error.detail.ignore");return t.error&&!a?Promise.reject(t.error):Promise.resolve(t)}}{constructor(t){super("misc",t),this.logLock=!1,this.core=t,registerParser({cmdMap:at,cmdConfig:lt}),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 o=Object.assign({k1:"val1",k2:"val2"},t),a=null;try{a=(yield this.core.clientSocket.sendCmd("wsDetect",{tag:o})).content.data}catch(t){var m=t;return void(m.code===Me.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}`))}a&&JSON.stringify(a)!==JSON.stringify(o)?(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 o;this.core.reporter.reportTraceStart("exceptions",{user_id:this.core.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}),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 o=function formatNotifyDetectTag(t){return format(pt,t)}(t.content.data);o.t3=t.__receiveTimeNode.time,o.t4=Date.now();try{yield this.core.clientSocket.sendCmd("uploadDetect",{data:o})}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 o="";try{o=(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(o){o+=(o.indexOf("?")>0?"&":"?")+"download="+(new Date).getTime()+"_web.log";try{yield this.core.clientSocket.sendCmd("uploadLog",{url:o})}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,o){t=t||{};var a={};return(o=o||[]).forEach((o=>{void 0!==t[o]&&(a[o]=t[o])})),a}var mt={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}}}},ut=["https://lbs.netease.im/lbs/webconf.jsp"],ht={retryCount:3,timeout:6e4,forceMode:!1,authType:0,syncLevel:0};var gt={"27_1":"v2NIMSync","27_10":"v2QChatSync"},vt={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,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 ft={debug(...t){},log(...t){},warn(...t){},error(...t){}};function setLogger(t){ft=t}function getLogger(){return ft}function base64ToArrayBuffer(t){for(var o=function base64Decode(t){var o=String(t).replace(/[=]+$/,"");if(o.length%4==1)throw new Error("'atob' failed: The string to be decoded is not correctly encoded.");for(var a,m="",u=0,h=0,g=0;a=o.charAt(g++);~a&&(h=u%4?64*h+a:a,u++%4)?m+=String.fromCharCode(255&h>>(-2*u&6)):0)a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(a);return m}(t),a=o.length,m=new Uint8Array(a),u=0;u<a;u++)m[u]=o.charCodeAt(u);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}var It={clear(){uni.clearStorageSync()},getItem:t=>uni.getStorageSync(t),setItem:(t,o)=>uni.setStorageSync(t,o),removeItem:t=>uni.removeStorageSync(t)};class LogStorageImpl$2{constructor(t="nim_logs"){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 o=uni.getSystemInfoSync(),a="mp-weixin"===o.uniPlatform||"mp-alipay"===o.uniPlatform;if(this.enable=a,a){var m=this.getAPIEnv();m&&(this.dirPath=`${m.env.USER_DATA_PATH}/__nim`,this.filePath=`${this.dirPath}/${t}.log`,this.copyFilePath=`${this.dirPath}/${t}_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 o=getLogger(),a=t.getFileSystemManager();try{var m=a.accessSync(this.dirPath);o.log("logStorage::access dir:",m),("object"==typeof m&&null!==m?m.error||m.errno||m.errCode||m.errNo:0)>200&&a.mkdirSync(this.dirPath,!0)}catch(t){a.mkdirSync(this.dirPath,!0)}try{var u=a.accessSync(this.filePath);o.log("logStorage::access file:",u),("object"==typeof u&&null!==u?u.error||u.errno||u.errCode||u.errNo:0)>200&&a.writeFileSync(this.filePath,"===","utf8")}catch(t){a.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(o){t.warn(`logStorage::open log file failed:${this.filePath}`,o)}yield this.checkCapacity(this.remainCapacity)}}))}checkCapacity(t){return __awaiter(this,void 0,void 0,(function*(){if(this.enable){var o=this.getAPIEnv();if(o){var a=getLogger(),m=o.getFileSystemManager(),u=this.getSize();if(u>this.maxCapacity){a.log(`logStorage::checksize:exceed,${u} byte`);var h="";try{h=yield this.readLogs(u-t)}catch(t){return void a.log("logStorage::checkCapacity:read failed",t)}a.log(`logStorage::checksize:read success ${u-t} byte`);try{m.unlinkSync(this.filePath)}catch(t){return void a.log("logStorage::checkCapacity:unlink failed",t)}try{m.writeFileSync(this.filePath,h,"utf8")}catch(t){return void a.log("logStorage::checkCapacity:write failed",t)}}else a.log(`logStorage::checkCapacity:not exceeding,${u} byte`)}}}))}getSize(){var t;if(!this.enable)return 0;var o=this.getAPIEnv();if(!o)return 0;var a,m=getLogger(),u=o.getFileSystemManager();try{a=u.statSync(this.filePath,!1)}catch(t){return m.warn("logStorage::stat failed",t),0}return a.size||(null===(t=a.stats)||void 0===t?void 0:t.size)}readLogs(t=0){if(!this.enable)return Promise.resolve("");var o=this.getAPIEnv();if(!o)return Promise.resolve("");var a=getLogger(),m=o.getFileSystemManager();return new Promise(((o,u)=>{m.readFile({filePath:this.filePath,encoding:"utf8",position:t,success:t=>{var m=t.data;"string"==typeof m?(a.warn(`logStorage::readLogs success ${m.length}`),o(m)):(a.warn("logStorage::readLogs empty"),u(new Error("logStorage::readLogs empty")))},fail:t=>{var o=t.errMsg||t.errorMessage||t.message;a.warn(`logStorage::readLogs failed ${o}`);var m={code:t.errCode||0,message:o};u(m)}})}))}close(){}addLogs(t){if(!this.enable)return Promise.resolve();var o=this.getAPIEnv();if(!o)return Promise.resolve();var a=getLogger(),m=t.map((t=>t.text)).concat("").join("\n");try{o.getFileSystemManager().appendFileSync(this.filePath,m,"utf8")}catch(t){var u=t.errMsg||t.errorMessage||t.message;this.lastErrorMsg!==u&&a.warn("logStorage::append failed",t),this.lastErrorMsg=u}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 o=getLogger(),a=t.getFileSystemManager();if(this.getSize()>0){try{a.copyFileSync(this.filePath,this.copyFilePath)}catch(t){return void o.warn("logStorage::copyFileSync failed",t)}return this.copyFilePath}o.warn("logStorage::extractLogs empty")}}}))}afterUpload(){return __awaiter(this,void 0,void 0,(function*(){if(this.enable){var t=this.getAPIEnv();if(t){var o=getLogger(),a=t.getFileSystemManager();try{a.unlinkSync(this.copyFilePath)}catch(t){return void o.log("logStorage::delete copyFilePath failed",t)}}}}))}}var yt={wifi:2,"2g":3,"3g":4,"4g":5,"5g":6,ethernet:1,unknown:0,none:0,notreachable:0,wwan:0};function getNetFn(t){var o=null;return{getNetworkStatus:()=>new Promise(((o,a)=>{t.getNetworkType({success:function(t){var a=!1;a="boolean"==typeof t.networkAvailable?t.networkAvailable:"none"!==t.networkType.toLowerCase(),o({net_type:yt[t.networkType.toLowerCase()],net_connect:a})},fail:function(){a(new Error("getNetworkType failed"))}})})),onNetworkStatusChange(a){this.offNetworkStatusChange(),t.onNetworkStatusChange&&(o=function(t){var o=t.networkType.toLowerCase();a({isConnected:t.isConnected||"none"!==o,networkType:yt[o]})},t.onNetworkStatusChange(o))},offNetworkStatusChange(){t.offNetworkStatusChange&&(o&&t.offNetworkStatusChange(o),o=null)}}}var Mt={__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,o)=>{uni.getNetworkType({success:function(o){var a=!1;a="boolean"==typeof o.networkAvailable?o.networkAvailable:"none"!==o.networkType.toLowerCase(),t({net_type:yt[o.networkType.toLowerCase()],net_connect:a})},fail:function(){o(new Error("getNetworkType failed"))}})}))},onNetworkStatusChange(t){this.offNetworkStatusChange(),uni.onNetworkStatusChange&&(this.__onNetworkStatusChangeFn=function(o){var a=o.networkType.toLowerCase();t({isConnected:o.isConnected||"none"!==a,networkType:yt[a]})},uni.onNetworkStatusChange(this.__onNetworkStatusChangeFn))},offNetworkStatusChange(){uni.offNetworkStatusChange&&(this.__onNetworkStatusChangeFn&&uni.offNetworkStatusChange(this.__onNetworkStatusChangeFn),this.__onNetworkStatusChangeFn=null)}},_t=getLogger();class PowerMonitor$2 extends ve{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 o=this.status;t!==o&&(this.status=t,0===t&&1===o&&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$4(t,o){return o&&(o.data=o.data||(null==o?void 0:o.params)||{}),new Promise(((a,m)=>{uni.request(Object.assign(Object.assign({method:"GET",url:t},o),{success:function(o){"number"==typeof(o=o||{}).statusCode&&o.statusCode.toString().startsWith("2")?(o={data:o.data,status:o.statusCode,errMsg:o.errMsg,header:o.header},a(o)):m({code:o.statusCode||0,message:o.data||`uniApp request fail. url: ${t}`})},fail:function(o){var a=`uniApp request fail. url: ${t}`;m(o?{code:o.errCode||0,message:o.errMsg||a}:{code:0,message:a})}}))}))}var getUserAgent=function(){var t=uni.getSystemInfoSync()||{};if("mp-weixin"===t.uniPlatform&&"undefined"!=typeof wx&&wx.getAppBaseInfo){var o=wx.getAppBaseInfo();return`NIM/Web/UNIAPP(${t.uniRuntimeVersion})/WeChatMiniApp(${o.SDKVersion})/V10.9.41/{{appkey}}`}if("undefined"!=typeof tt&&tt.getSystemInfoSync){var a=tt.getSystemInfoSync();return`NIM/Web/UNIAPP(${t.uniRuntimeVersion})/TiktokMiniApp(${a.SDKVersion})/V10.9.41/{{appkey}}`}if("undefined"!=typeof swan&&swan.getSystemInfoSync){var m=swan.getSystemInfoSync();return`NIM/Web/UNIAPP(${t.uniRuntimeVersion})/BaiduMiniApp(${m.SDKVersion})/V10.9.41/{{appkey}}`}if("undefined"!=typeof my&&my.getSystemInfoSync){var u=my.getSystemInfoSync();return`NIM/Web/UNIAPP(${t.uniRuntimeVersion})/AliMiniApp(${u.SDKVersion})/V10.9.41/{{appkey}}`}if(navigator&&navigator.userAgent)return navigator.userAgent;if(t.ua)return t.ua;var h=uni.getSystemInfoSync();return`NIM/Web/UNIAPP(${h.uniRuntimeVersion})/${h.osName}(${h.osVersion})/V10.9.41/{{appkey}}`},getHostEnvVer=function(){var t=uni.getSystemInfoSync()||{};if("mp-weixin"===t.uniPlatform&&"undefined"!=typeof wx&&wx.getAppBaseInfo){var o=wx.getAppBaseInfo();return`${t.uniRuntimeVersion}/${o.version}`}if("undefined"!=typeof tt&&tt.getSystemInfoSync){var a=tt.getSystemInfoSync();return`${t.uniRuntimeVersion}/${a.version}`}if("undefined"!=typeof swan&&swan.getSystemInfoSync){var m=swan.getSystemInfoSync();return`${t.uniRuntimeVersion}/${m.version}`}if("undefined"!=typeof my&&my.getSystemInfoSync){var u=my.getSystemInfoSync();return`${t.uniRuntimeVersion}/${u.version}`}return`${t.uniRuntimeVersion}`},getModel=function(){var t=uni.getSystemInfoSync()||{};if("mp-weixin"===t.uniPlatform&&"undefined"!=typeof wx&&wx.getAppBaseInfo){var o=wx.getAppBaseInfo();return`${t.uniRuntimeVersion}/${o.SDKVersion}`}if("undefined"!=typeof tt&&tt.getSystemInfoSync){var a=tt.getSystemInfoSync();return`${t.uniRuntimeVersion}/${a.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$5(){var t,o="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"],a=uni.getSystemInfoSync()||{};return{os:a.osName||"UNIAPP_UNKNOW",osVer:a.osVersion,browser:a.browserName||"",browserVer:a.browserVersion||"",libEnv:"UNIAPP",hostEnv:o[1],hostEnvEnum:o[0],hostEnvVer:getHostEnvVer(),userAgent:getUserAgent(),model:getModel(),manufactor:o[1],pushDeviceInfo:{PRODUCT:a.model,DEVICE:a.model,MANUFACTURER:a.brand}}}function uploadFileFn$5(t){var o=getLogger(),a=t.headers||{};return t.md5&&(a["Content-MD5"]=t.md5),new Promise(((m,u)=>{var h=uni.uploadFile(Object.assign(Object.assign({url:`${t.commonUploadHost}/${t.nosToken.bucket}`},Object.keys(a).length>0?{header:a}:{}),{formData:{Object:decodeURIComponent(t.nosToken.objectName),"x-nos-token":t.nosToken.token,"x-nos-entity-type":"json"},name:"file",fileType:t.type,filePath:t.filePath,success(o){if(200==o.statusCode)try{var a;try{a=JSON.parse(o.data)}catch(t){a={}}a.name=t.filePath,a.ext=a.name.lastIndexOf(".")>-1?a.name.slice(a.name.lastIndexOf(".")+1).toLowerCase():"",m(a)}catch(t){u({code:o.statusCode,message:o.errMsg,rawData:o.data})}else u({code:o.statusCode,message:o.errMsg,rawData:o.data})},fail(t){"uploadFile:fail abort"===t.errMsg&&(t.code=Me.V2NIM_ERROR_CODE_CANCELLED),t.message=t.errMsg,u(t)}}));try{t.onUploadStart&&t.onUploadStart(h)}catch(t){o.error("Adapter uploadFile: options.onUploadStart error",t&&t.message),h.abort(),u(t)}t.onUploadProgress&&h.onProgressUpdate((function(o){t.onUploadProgress&&t.onUploadProgress({total:o.totalBytesExpectedToSend,loaded:o.totalBytesSent,percentage:parseFloat((o.totalBytesSent/o.totalBytesExpectedToSend).toFixed(2)),percentageText:o.progress+"%"})}))}))}function getFileUploadInformationFn$5(t){return null}class WebsocketFn{constructor(t,o=""){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=o,this.readyState=this.CONNECTING;var a=this.protocol?{protocols:this.protocol}:{};this.socketTask=uni.connectSocket(Object.assign(Object.assign({url:this.url},a),{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 o;o="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:o})}))}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$5=()=>({setLogger:setLogger,platform:"UNIAPP",localStorage:It,request:requestFn$4,WebSocket:WebsocketFn,uploadFile:uploadFileFn$5,getFileUploadInformation:getFileUploadInformationFn$5,getSystemInfo:getSystemInfoFn$5,net:Mt,powerMonitor:new PowerMonitor$2,logStorage:LogStorageImpl$2}),Et=createCommonjsModule((function(t,o){t.exports=function(){function object2String(t){if(t){var o="";return Object.keys(t).forEach((function(a,m){o+=0===m?"?":"&",o+=`${a}=${t[a]}`})),o}return""}class V2NIMError extends Error{constructor(t,o,a,m){super(a),this.source=t,this.code=o,this.desc=a,this.detail=m||{}}}function request(t,o={dataType:"json",method:"GET",timeout:5e3}){var a="text"===o.dataType?"text/plain; charset=UTF-8":"application/json; charset=UTF-8",m="GET"===o.method?object2String(o.params):"";return new Promise((function(u,h){if(window.XMLHttpRequest){var g,I=new XMLHttpRequest;if(I.onreadystatechange=function(){if(4===I.readyState)if(200===I.status){try{g=JSON.parse(I.response||"{}")}catch(t){g=I.response}u({status:I.status,data:g})}else setTimeout((()=>{h(new V2NIMError(1,I.status,`readyState: ${I.readyState}; statusText: ${I.statusText}`))}),0)},I.open(o.method,`${t}${m}`),I.timeout=o.timeout||5e3,I.setRequestHeader("Content-Type",a),o.headers)for(var M in o.headers)I.setRequestHeader(M,o.headers[M]);I.ontimeout=function(t){h(new V2NIMError(1,408,t&&t.message?t.message:"request timeout"))},I.send(JSON.stringify(o.data))}else h(new V2NIMError(2,10400,"request no suppout"))}))}return request}()})),St=createCommonjsModule((function(t,o){self,t.exports=function(){var t={d:function(o,a){for(var m in a)t.o(a,m)&&!t.o(o,m)&&Object.defineProperty(o,m,{enumerable:!0,get:a[m]})},o:function(t,o){return Object.prototype.hasOwnProperty.call(t,o)}},o={};t.d(o,{default:function(){return S}});var a=function e(t){for(var o in function(t,o){if(!(t instanceof o))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=5e4,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){},t)this[o]=t[o]};function n(t,o){var a="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!a){if(Array.isArray(t)||(a=function(t,o){if(t){if("string"==typeof t)return r(t,o);var a=Object.prototype.toString.call(t).slice(8,-1);return"Object"===a&&t.constructor&&(a=t.constructor.name),"Map"===a||"Set"===a?Array.from(t):"Arguments"===a||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(a)?r(t,o):void 0}}(t))||o&&t&&"number"==typeof t.length){a&&(t=a);var m=0,i=function(){};return{s:i,n:function(){return m>=t.length?{done:!0}:{done:!1,value:t[m++]}},e:function(t){throw t},f:i}}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 u,h=!0,g=!1;return{s:function(){a=a.call(t)},n:function(){var t=a.next();return h=t.done,t},e:function(t){g=!0,u=t},f:function(){try{h||null==a.return||a.return()}finally{if(g)throw u}}}}function r(t,o){(null==o||o>t.length)&&(o=t.length);for(var a=0,m=new Array(o);a<o;a++)m[a]=t[a];return m}var m={privateObj:{},setItem:function(t,o){m.privateObj[t]=o},getItem:function(t){return m.privateObj[t]},removeItem:function(t){delete m.privateObj[t]},getKeys:function(){return Object.keys(m.privateObj)}},u={getFileKey:function(t){var o=t.size.toString(),a=t.lastModified.toString();return"_NosUploader_"+t.name+o.slice(o.length-5)+a.slice(a.length-5)},getFileInfo:function(t){var o=m.getItem(t);if(!o)return null;try{return JSON.parse(o)}catch(t){return null}},initFile:function(t,o,a){u.clearExpiredInfo();var h=this.getFileKey(o),g={ctx:void 0!==t.ctx?t.ctx:"",bucket:t.bucketName,obj:t.objectName,token:t.token,modifyAt:Date.now(),end:!1};return t.payload&&(g.payload=t.payload),a&&m.setItem(h,JSON.stringify(g)),h},setUploadContext:function(t,o,a){var u=this.getFileInfo(t);u&&(u.ctx=o,a&&m.setItem(t,JSON.stringify(u)))},setComplete:function(t,o){var a=this.getFileInfo(t);a&&(a.modifyAt=Date.now(),a.end=!0,o&&m.setItem(t,JSON.stringify(a)))},getUploadContext:function(t){var o=this.getFileInfo(t);return o?o.ctx:""},removeFileInfo:function(t){0===t.indexOf("_NosUploader_")&&m.removeItem(t)},clearExpiredInfo:function(){var t,o="function"==typeof m.getKeys?m.getKeys():Object.keys(m),a=Date.now(),h=[],g=n(o);try{for(g.s();!(t=g.n()).done;){var I=t.value;if(0===I.indexOf("_NosUploader_")){var M=u.getFileInfo(I);null===M||a-M.modifyAt>S.expireTime?m.removeItem(I):h.push({fileInfo:M,key:I})}}}catch(t){g.e(t)}finally{g.f()}if(h.length>S.maxFileCache){var _,E=n(h.sort((function(t,o){return o.fileInfo.modifyAt-t.fileInfo.modifyAt})).slice(S.maxFileCache));try{for(E.s();!(_=E.n()).done;){var T=_.value;0===T.key.indexOf("_NosUploader_")&&m.removeItem(T.key)}}catch(t){E.e(t)}finally{E.f()}}}},h=u;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 s(t,o){return!o||"object"!==c(o)&&"function"!=typeof o?function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t):o}function f(t){var o="function"==typeof Map?new Map:void 0;return(f=function(t){if(null===t||(a=t,-1===Function.toString.call(a).indexOf("[native code]")))return t;var a;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==o){if(o.has(t))return o.get(t);o.set(t,n)}function n(){return l(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 l(t,o,a){return(l=p()?Reflect.construct:function(t,o,a){var m=[null];m.push.apply(m,o);var u=new(Function.bind.apply(t,m));return a&&d(u,a.prototype),u}).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,o){return(d=Object.setPrototypeOf||function(t,o){return t.__proto__=o,t})(t,o)}function y(t){return(y=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}var g=function(t){!function(t,o){if("function"!=typeof o&&null!==o)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(o&&o.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),o&&d(t,o)}(r,t);var o,a,m=(o=r,a=p(),function(){var t,m=y(o);if(a){var u=y(this).constructor;t=Reflect.construct(m,arguments,u)}else t=m.apply(this,arguments);return s(this,t)});function r(t,o){var a;return function(t,o){if(!(t instanceof o))throw new TypeError("Cannot call a class as a function")}(this,r),(a=m.call(this,"NosUploadError:"+t)).errCode=o,a.errMsg=t,a}return r}(f(Error)),I=function e(t,o,a){if("uploading"===t.uploadState){var m=t.config,u=t.param,I=h.getUploadContext(t.fileKey);if(!I)return a(0);var M=new XMLHttpRequest,_=m.directUploadAddr+"/".concat(u.bucketName)+"/".concat(encodeURIComponent(u.objectName))+"?uploadContext"+"&context=".concat(I)+"&version=".concat(m.version);M.onreadystatechange=function(){var u;if("abort"!==t.uploadState&&4===M.readyState){var I;try{I=JSON.parse(M.responseText)}catch(t){I={errMsg:"JsonParseError in getOffset. xhr.status = "+M.status+". xhr.responseText: "+M.responseText,errCode:500}}200===M.status?I.errCode?t.config.onError(new g(I.errMsg,I.errCode)):a(I.offset):M.status.toString().match(/^5/)?e(t,o-1,a):o>0?("function"==typeof(null===(u=m.logger)||void 0===u?void 0:u.error)&&m.logger.error("getOffset(".concat(_,") error. retry after 3 seconds. ").concat((new Date).toTimeString())),setTimeout((function(){e(t,o-1,a)}),3500)):M.status?(h.removeFileInfo(t.fileKey),m.onError(new g("getOffset(".concat(_,") error: ").concat(M.status," ").concat(M.statusText)))):m.onError(new g("getOffset(".concat(_,") error. no Error Code")))}},M.open("get",_),M.setRequestHeader("x-nos-token",u.token),M.timeout=m.getOffsetTimeout,M.send()}},M=function e(t,o,a,m){if("uploading"===t.uploadState){var u=t.param,I=t.config,M=File.prototype.slice,_=void 0!==u.ctx?u.ctx:"",E=o+I.trunkSize>=t.file.size,S=E?t.file.size:o+I.trunkSize,T=new XMLHttpRequest,C=I.directUploadAddr+"/".concat(u.bucketName)+"/".concat(encodeURIComponent(u.objectName));if(T.upload.onprogress=function(a){if("abort"!==t.uploadState){var m=0;a.lengthComputable?(m=(o+a.loaded)/t.file.size,I.onProgress(m),I.onUploadProgress({loaded:a.loaded,total:t.file.size,percentage:m,percentageText:(100*m).toFixed(2)+"%"})):I.onError(new g("browser does not support query upload progress"))}},T.onreadystatechange=function(){var u,M;if("abort"!==t.uploadState&&4===T.readyState){var _;try{_=JSON.parse(T.responseText)}catch(t){"function"==typeof(null===(u=I.logger)||void 0===u?void 0:u.error)&&I.logger.error("JsonParseError in uploadTrunk. xhr.status = "+T.status+". xhr.responseText: "+T.responseText,t),_={errMsg:"JsonParseError in uploadTrunk. xhr.status = "+T.status+". xhr.responseText: "+T.responseText}}200===T.status?(t.setContext(_.context),E?(m(),t.setComplete()):e(t,_.offset,I.retryCount,m)):T.status.toString().match(/^5/)?a>0?e(t,o,a-1,m):(h.removeFileInfo(t.fileKey),I.onError(new g(_.errMsg,_.errCode))):a>0?("function"==typeof(null===(M=I.logger)||void 0===M?void 0:M.error)&&I.logger.error("uploadTrunk(".concat(C,") error. retry after 3 seconds. ").concat((new Date).toTimeString())),setTimeout((function(){e(t,o,a-1,m)}),3500)):T.status?(h.removeFileInfo(t.fileKey),I.onError(new g("uploadTrunk(".concat(C,") error: ").concat(T.status," ").concat(T.statusText)))):I.onError(new g("uploadTrunk(".concat(C,") error. no Error Code. Please check your network")))}},T.open("post",C+"?offset=".concat(o)+"&complete=".concat(E)+"&context=".concat(_)+"&version=".concat(I.version)),T.setRequestHeader("x-nos-token",u.token),u.md5&&T.setRequestHeader("content-md5",u.md5),t.file.type&&T.setRequestHeader("content-type",t.file.type),T.timeout=I.trunkUploadTimeout,"undefined"!=typeof FileReader){var N=new FileReader;N.addEventListener("load",(function(t){var o;(null===(o=null==t?void 0:t.target)||void 0===o?void 0:o.result)instanceof ArrayBuffer&&t.target.result.byteLength>0?T.send(t.target.result):I.onError(new g("Read ArrayBuffer failed",194003))})),N.addEventListener("error",(function(t){var o=t.target.error;I.onError(new g("Read ArrayBuffer error. ".concat(o.toString()),194003))})),N.readAsArrayBuffer(M.call(t.file,o,S))}else T.send(M.call(t.file,o,S))}};function v(t,o){for(var a=0;a<o.length;a++){var m=o[a];m.enumerable=m.enumerable||!1,m.configurable=!0,"value"in m&&(m.writable=!0),Object.defineProperty(t,m.key,m)}}var _=function(){function e(t,o,a){!function(t,o){if(!(t instanceof o))throw new TypeError("Cannot call a class as a function")}(this,e),this.uploadState="paused",this.config=a,this.file=t,this.param=o,this.fileKey=h.initFile(o,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 o=this.config;I(this,o.retryCount,(function(a){M(t,a,o.retryCount,(function(){t.setUploadState("ended"),"function"==typeof o.onComplete&&o.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 g("Upload Aborted",10499)))}},{key:"setUploadState",value:function(t){t!==this.uploadState&&(this.uploadState=t)}},{key:"setContext",value:function(t){h.setUploadContext(this.fileKey,t,this.config.enableCache),this.param.ctx=t}},{key:"setComplete",value:function(){h.setComplete(this.fileKey,this.config.enableCache),this.setUploadState("ended")}}])&&v(e.prototype,t),e}(),E={maxFileCache:1/0,expireTime:864e5,getFileUploadInformation:function(t){var o=h.getFileKey(t),a=h.getFileInfo(o);return null===a?null:Date.now()-a.modifyAt>E.expireTime?(h.removeFileInfo(o),null):{uploadInfo:Object.assign({bucketName:a.bucket,objectName:a.obj,token:a.token,ctx:a.ctx},a.payload?{payload:a.payload}:{}),complete:a.end}},setMaxFileCache:function(t){E.maxFileCache=t},setExpireTime:function(t){E.expireTime=t},printCaches:function(){if("undefined"!=typeof localStorage)for(var t=0,o=Object.keys(localStorage);t<o.length;t++){var a=o[t],m=h.getFileInfo(a);m&&console.log(m,"modifiedAt",new Date(m.modifyAt).toTimeString())}},createConfig:function(t){return new a(t)},createTask:function(t,o,a){return new _(t,o,a)}},S=E;return o.default}()}));function uploadFileFn$4(t){return __awaiter(this,void 0,void 0,(function*(){var o,a=getLogger();if(!t.fileInput&&!t.file)throw new Error("File not exist");if(t.file)o=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");o=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}`);o=t.fileInput.files[0]}if(t.maxSize&&o.size>t.maxSize)throw new Error(`The file exceeds maxSize limit. maxSize: ${t.maxSize}, get ${o.size}`);var u=yield new Promise(((m,u)=>{var h,g=St.getFileUploadInformation(o),I=St.createConfig({enableCache:!0,retryCount:0,directUploadAddr:t.chunkUploadHost,onError:function(t){u(t)},onUploadProgress:t.onUploadProgress||function(){},onComplete:function(t){m(t)}});if(g)if(g.complete)t.onUploadProgress&&t.onUploadProgress({total:o.size,loaded:o.size,percentage:1,percentageText:"100%"}),m(g.uploadInfo);else{h=St.createTask(o,g.uploadInfo,I);try{t.onUploadStart&&t.onUploadStart(h)}catch(t){a.error("Adapter uploadFile: options.onUploadStart error",t&&t.message),h.abort(),u(t)}}else{h=St.createTask(o,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(h)}catch(t){a.error("Adapter uploadFile: options.onUploadStart error",t&&t.message),h.abort(),u(t)}}}));return u.name=o.name,u.size=o.size,u.type=o.type,u.ext=u.name.lastIndexOf(".")>-1?u.name.slice(u.name.lastIndexOf(".")+1).toLowerCase():"",u}))}function getFileUploadInformationFn$4(t){var o;if(t.file)o=t.file;else if("string"==typeof t.fileInput){var a=document.getElementById(t.fileInput);if(!(a&&a.files&&a.files[0]))throw new Error("Can not get file from fileInput");o=a.files[0]}else{if(!(t.fileInput&&t.fileInput.files&&t.fileInput.files[0]))throw new Error(`Can not get file from fileInput ${t.fileInput}`);o=t.fileInput.files[0]}return St.getFileUploadInformation(o)}
/*!
 * Platform.js v1.3.6
 * Copyright 2014-2020 Benjamin Tan
 * Copyright 2011-2013 John-David Dalton
 * Available under MIT license
 */var Tt=createCommonjsModule((function(o,a){(function(){var m={function:!0,object:!0}[typeof window]&&window||this,u=a,h=o&&!o.nodeType&&o,g=u&&h&&"object"==typeof t&&t;!g||g.global!==g&&g.window!==g&&g.self!==g||(m=g);var I=Math.pow(2,53)-1,M=/\bOpera/,_=Object.prototype,E=_.hasOwnProperty,S=_.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,o){for(var a in t)E.call(t,a)&&o(t[a],a,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,o){var a=null;return function each(t,o){var a=-1,m=t?t.length:0;if("number"==typeof m&&m>-1&&m<=I)for(;++a<m;)o(t[a],a,t);else forOwn(t,o)}(t,(function(m,u){a=o(a,m,u,t)})),a}function trim(t){return String(t).replace(/^ +| +$/g,"")}var T=function parse(t){var o=m,a=t&&"object"==typeof t&&"String"!=getClassOf(t);a&&(o=t,t=null);var u=o.navigator||{},h=u.userAgent||"";t||(t=h);var g,I,_=a?!!u.likeChrome:/\bChrome\b/.test(t)&&!/internal|\n/i.test(S.toString()),E="Object",T=a?E:"ScriptBridgingProxyObject",C=a?E:"Environment",N=a&&o.java?"JavaPackage":getClassOf(o.java),A=a?E:"RuntimeObject",O=/\bJava/.test(N)&&o.java,R=O&&getClassOf(o.environment)==C,b=O?"a":"α",V=O?"b":"β",k=o.document||{},P=o.operamini||o.opera,L=M.test(L=a&&P?P["[[Class]]"]:getClassOf(P))?L:P=null,w=t,D=[],U=null,x=t==h,B=x&&P&&"function"==typeof P.version&&P.version(),$=function getLayout(o){return reduce(o,(function(o,a){return o||RegExp("\\b"+(a.pattern||qualify(a))+"\\b","i").exec(t)&&(a.label||a)}))}([{label:"EdgeHTML",pattern:"Edge"},"Trident",{label:"WebKit",pattern:"AppleWebKit"},"iCab","Presto","NetFront","Tasman","KHTML","Gecko"]),j=function getName(o){return reduce(o,(function(o,a){return o||RegExp("\\b"+(a.pattern||qualify(a))+"\\b","i").exec(t)&&(a.label||a)}))}(["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"]),G=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"]),q=function getManufacturer(o){return reduce(o,(function(o,a,m){return o||(a[G]||a[/^[a-z]+(?: +[a-z]+\b)*/i.exec(G)]||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}}),H=function getOS(o){return reduce(o,(function(o,a){var m=a.pattern||qualify(a);return!o&&(o=RegExp("\\b"+m+"(?:/[\\d.]+|[ \\w.]*)","i").exec(t))&&(o=function cleanupOS(t,o,a){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 o&&a&&/^Win/i.test(t)&&!/^Windows Phone /i.test(t)&&(m=m[/[\d.]+$/.exec(t)])&&(t="Windows "+m),t=String(t),o&&a&&(t=t.replace(RegExp(o,"i"),a)),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])}(o,m,a.label||a)),o}))}(["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(o){return reduce(o,(function(o,a){var m=a.pattern||qualify(a);return!o&&(o=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))&&((o=String(a.label&&!RegExp(m,"i").test(a.label)?a.label:o).split("/"))[1]&&!/[\d.]+/.test(o[0])&&(o[0]+=" "+o[1]),a=a.label||a,o=format(o[0].replace(RegExp(m,"i"),a).replace(RegExp("; *(?:"+a+"[_-])?","i")," ").replace(RegExp("("+a+")[-_.]?(\\w)","i"),"$1 $2"))),o}))}function getVersion(o){return reduce(o,(function(o,a){return o||(RegExp(a+"(?:-[\\d.]+/|(?: for [\\w-]+)?[ /-])([\\d.]+[^ ();/_-]*)","i").exec(t)||0)[1]||null}))}if($&&($=[$]),/\bAndroid\b/.test(H)&&!G&&(g=/\bAndroid[^;]*;(.*?)(?:Build|\) AppleWebKit)\b/i.exec(t))&&(G=trim(g[1]).replace(/^[a-z]{2}-[a-z]{2};\s*/i,"")||null),q&&!G?G=getProduct([q]):q&&G&&(G=G.replace(RegExp("^("+qualify(q)+")[-_.\\s]","i"),q+" ").replace(RegExp("^("+qualify(q)+")[-_.]?(\\w)","i"),q+" $2")),(g=/\bGoogle TV\b/.exec(G))&&(G=g[0]),/\bSimulator\b/i.test(t)&&(G=(G?G+" ":"")+"Simulator"),"Opera Mini"==j&&/\bOPiOS\b/.test(t)&&D.push("running in Turbo/Uncompressed mode"),"IE"==j&&/\blike iPhone OS\b/.test(t)?(q=(g=parse(t.replace(/like iPhone OS/,""))).manufacturer,G=g.product):/^iP/.test(G)?(j||(j="Safari"),H="iOS"+((g=/ OS ([\d_]+)/i.exec(t))?" "+g[1].replace(/_/g,"."):"")):"Konqueror"==j&&/^Linux\b/i.test(H)?H="Kubuntu":q&&"Google"!=q&&(/Chrome/.test(j)&&!/\bMobile Safari\b/i.test(t)||/\bVita\b/.test(G))||/\bAndroid\b/.test(H)&&/^Chrome/.test(j)&&/\bVersion\//i.test(t)?(j="Android Browser",H=/\bAndroid\b/.test(H)?H:"Android"):"Silk"==j?(/\bMobi/i.test(t)||(H="Android",D.unshift("desktop mode")),/Accelerated *= *true/i.test(t)&&D.unshift("accelerated")):"UC Browser"==j&&/\bUCWEB\b/.test(t)?D.push("speed mode"):"PaleMoon"==j&&(g=/\bFirefox\/([\d.]+)\b/.exec(t))?D.push("identifying as Firefox "+g[1]):"Firefox"==j&&(g=/\b(Mobile|Tablet|TV)\b/i.exec(t))?(H||(H="Firefox OS"),G||(G=g[1])):!j||(g=!/\bMinefield\b/i.test(t)&&/\b(?:Firefox|Safari)\b/.exec(j))?(j&&!G&&/[\/,]|^[^(]+?\)/.test(t.slice(t.indexOf(g+"/")+8))&&(j=null),(g=G||q||H)&&(G||q||/\b(?:Android|Symbian OS|Tablet OS|webOS)\b/.test(H))&&(j=/[a-z]+(?: Hat)?/i.exec(/\bAndroid\b/.test(H)?H:g)+" Browser")):"Electron"==j&&(g=(/\bChrome\/([\d.]+)\b/.exec(t)||0)[1])&&D.push("Chromium "+g),B||(B=getVersion(["(?:Cloud9|CriOS|CrMo|Edge|Edg|EdgA|EdgiOS|FxiOS|HeadlessChrome|IEMobile|Iron|Opera ?Mini|OPiOS|OPR|Raven|SamsungBrowser|Silk(?!/[\\d.]+$)|UCBrowser|YaBrowser)","Version",qualify(j),"(?:Firefox|Minefield|NetFront)"])),(g=("iCab"==$&&parseFloat(B)>3?"WebKit":/\bOpera\b/.test(j)&&(/\bOPR\b/.test(t)?"Blink":"Presto"))||/\b(?:Midori|Nook|Safari)\b/i.test(t)&&!/^(?:Trident|EdgeHTML)$/.test($)&&"WebKit"||!$&&/\bMSIE\b/i.test(t)&&("Mac OS"==H?"Tasman":"Trident")||"WebKit"==$&&/\bPlayStation\b(?! Vita\b)/i.test(j)&&"NetFront")&&($=[g]),"IE"==j&&(g=(/; *(?:XBLWP|ZuneWP)(\d+)/i.exec(t)||0)[1])?(j+=" Mobile",H="Windows Phone "+(/\+$/.test(g)?g:g+".x"),D.unshift("desktop mode")):/\bWPDesktop\b/i.test(t)?(j="IE Mobile",H="Windows Phone 8.x",D.unshift("desktop mode"),B||(B=(/\brv:([\d.]+)/.exec(t)||0)[1])):"IE"!=j&&"Trident"==$&&(g=/\brv:([\d.]+)/.exec(t))&&(j&&D.push("identifying as "+j+(B?" "+B:"")),j="IE",B=g[1]),x){if(function isHostType(t,o){var a=null!=t?typeof t[o]:"number";return!(/^(?:boolean|number|string|undefined)$/.test(a)||"object"==a&&!t[o])}(o,"global"))if(O&&(w=(g=O.lang.System).getProperty("os.arch"),H=H||g.getProperty("os.name")+" "+g.getProperty("os.version")),R){try{B=o.require("ringo/engine").version.join("."),j="RingoJS"}catch(t){(g=o.system)&&g.global.system==o.system&&(j="Narwhal",H||(H=g[0].os||null))}j||(j="Rhino")}else"object"==typeof o.process&&!o.process.browser&&(g=o.process)&&("object"==typeof g.versions&&("string"==typeof g.versions.electron?(D.push("Node "+g.versions.node),j="Electron",B=g.versions.electron):"string"==typeof g.versions.nw&&(D.push("Chromium "+B,"Node "+g.versions.node),j="NW.js",B=g.versions.nw)),j||(j="Node.js",w=g.arch,H=g.platform,B=(B=/[\d.]+/.exec(g.version))?B[0]:null));else getClassOf(g=o.runtime)==T?(j="Adobe AIR",H=g.flash.system.Capabilities.os):getClassOf(g=o.phantom)==A?(j="PhantomJS",B=(g=g.version||null)&&g.major+"."+g.minor+"."+g.patch):"number"==typeof k.documentMode&&(g=/\bTrident\/(\d+)/i.exec(t))?(B=[B,k.documentMode],(g=+g[1]+4)!=B[1]&&(D.push("IE "+B[1]+" mode"),$&&($[1]=""),B[1]=g),B="IE"==j?String(B[1].toFixed(1)):B[0]):"number"==typeof k.documentMode&&/^(?:Chrome|Firefox)\b/.test(j)&&(D.push("masking as "+j+" "+B),j="IE",B="11.0",$=["Trident"],H="Windows");H=H&&format(H)}if(B&&(g=/(?:[ab]|dp|pre|[ab]\d+pre)(?:\d+\+?)?$/i.exec(B)||/(?:alpha|beta)(?: ?\d)?/i.exec(t+";"+(x&&u.appMinorVersion))||/\bMinefield\b/i.test(t)&&"a")&&(U=/b/i.test(g)?"beta":"alpha",B=B.replace(RegExp(g+"\\+?$"),"")+("beta"==U?V:b)+(/\d+\+?/.exec(g)||"")),"Fennec"==j||"Firefox"==j&&/\b(?:Android|Firefox OS|KaiOS)\b/.test(H))j="Firefox Mobile";else if("Maxthon"==j&&B)B=B.replace(/\.[\d.]+/,".x");else if(/\bXbox\b/i.test(G))"Xbox 360"==G&&(H=null),"Xbox 360"==G&&/\bIEMobile\b/.test(t)&&D.unshift("mobile mode");else if(!/^(?:Chrome|IE|Opera)$/.test(j)&&(!j||G||/Browser|Mobi/.test(j))||"Windows CE"!=H&&!/Mobi/i.test(t))if("IE"==j&&x)try{null===o.external&&D.unshift("platform preview")}catch(t){D.unshift("embedded")}else(/\bBlackBerry\b/.test(G)||/\bBB10\b/.test(t))&&(g=(RegExp(G.replace(/ +/g," *")+"/([.\\d]+)","i").exec(t)||0)[1]||B)?(H=((g=[g,/BB10/.test(t)])[1]?(G=null,q="BlackBerry"):"Device Software")+" "+g[0],B=null):this!=forOwn&&"Wii"!=G&&(x&&P||/Opera/.test(j)&&/\b(?:MSIE|Firefox)\b/i.test(t)||"Firefox"==j&&/\bOS X (?:\d+\.){2,}/.test(H)||"IE"==j&&(H&&!/^Win/.test(H)&&B>5.5||/\bWindows XP\b/.test(H)&&B>8||8==B&&!/\bTrident\b/.test(t)))&&!M.test(g=parse.call(forOwn,t.replace(M,"")+";"))&&g.name&&(g="ing as "+g.name+((g=g.version)?" "+g:""),M.test(j)?(/\bIE\b/.test(g)&&"Mac OS"==H&&(H=null),g="identify"+g):(g="mask"+g,j=L?format(L.replace(/([a-z])([A-Z])/g,"$1 $2")):"Opera",/\bIE\b/.test(g)&&(H=null),x||(B=null)),$=["Presto"],D.push(g));else j+=" Mobile";(g=(/\bAppleWebKit\/([\d.]+\+?)/i.exec(t)||0)[1])&&(g=[parseFloat(g.replace(/\.(\d)$/,".0$1")),g],"Safari"==j&&"+"==g[1].slice(-1)?(j="WebKit Nightly",U="alpha",B=g[1].slice(0,-1)):B!=g[1]&&B!=(g[2]=(/\bSafari\/([\d.]+\+?)/i.exec(t)||0)[1])||(B=null),g[1]=(/\b(?:Headless)?Chrome\/([\d.]+)/i.exec(t)||0)[1],537.36==g[0]&&537.36==g[2]&&parseFloat(g[1])>=28&&"WebKit"==$&&($=["Blink"]),x&&(_||g[1])?($&&($[1]="like Chrome"),g=g[1]||((g=g[0])<530?1:g<532?2:g<532.05?3:g<533?4:g<534.03?5:g<534.07?6:g<534.1?7:g<534.13?8:g<534.16?9:g<534.24?10:g<534.3?11:g<535.01?12:g<535.02?"13+":g<535.07?15:g<535.11?16:g<535.19?17:g<536.05?18:g<536.1?19:g<537.01?20:g<537.11?"21+":g<537.13?23:g<537.18?24:g<537.24?25:g<537.36?26:"Blink"!=$?"27":"28")):($&&($[1]="like Safari"),g=(g=g[0])<400?1:g<500?2:g<526?3:g<533?4:g<534?"4+":g<535?5:g<537?6:g<538?7:g<601?8:g<602?9:g<604?10:g<606?11:g<608?12:"12"),$&&($[1]+=" "+(g+="number"==typeof g?".x":/[.+]/.test(g)?"":"+")),"Safari"==j&&(!B||parseInt(B)>45)?B=g:"Chrome"==j&&/\bHeadlessChrome/i.test(t)&&D.unshift("headless")),"Opera"==j&&(g=/\bzbov|zvav$/.exec(H))?(j+=" ",D.unshift("desktop mode"),"zvav"==g?(j+="Mini",B=null):j+="Mobile",H=H.replace(RegExp(" *"+g+"$"),"")):"Safari"==j&&/\bChrome\b/.exec($&&$[1])?(D.unshift("desktop mode"),j="Chrome Mobile",B=null,/\bOS X\b/.test(H)?(q="Apple",H="iOS 4.3+"):H=null):/\bSRWare Iron\b/.test(j)&&!B&&(B=getVersion("Chrome")),B&&0==B.indexOf(g=/[\d.]+$/.exec(H))&&t.indexOf("/"+g+"-")>-1&&(H=trim(H.replace(g,""))),H&&-1!=H.indexOf(j)&&!RegExp(j+" OS").test(H)&&(H=H.replace(RegExp(" *"+qualify(j)+" *"),"")),$&&!/\b(?:Avant|Nook)\b/.test(j)&&(/Browser|Lunascape|Maxthon/.test(j)||"Safari"!=j&&/^iOS/.test(H)&&/\bSafari\b/.test($[1])||/^(?:Adobe|Arora|Breach|Midori|Opera|Phantom|Rekonq|Rock|Samsung Internet|Sleipnir|SRWare Iron|Vivaldi|Web)/.test(j)&&$[1])&&(g=$[$.length-1])&&D.push(g),D.length&&(D=["("+D.join("; ")+")"]),q&&G&&G.indexOf(q)<0&&D.push("on "+q),G&&D.push((/^on /.test(D[D.length-1])?"":"on ")+G),H&&(g=/ ([\d.+]+)$/.exec(H),I=g&&"/"==H.charAt(H.length-g[0].length-1),H={architecture:32,family:g&&!I?H.replace(g[0],""):H,version:g?g[1]:null,toString:function(){var t=this.version;return this.family+(t&&!I?" "+t:"")+(64==this.architecture?" 64-bit":"")}}),(g=/\b(?:AMD|IA|Win|WOW|x86_|x)64\b/i.exec(w))&&!/\bi686\b/i.test(w)?(H&&(H.architecture=64,H.family=H.family.replace(RegExp(" *"+g),"")),j&&(/\bWOW64\b/i.test(t)||x&&/\w(?:86|32)$/.test(u.cpuClass||u.platform)&&!/\bWin64; x64\b/i.test(t))&&D.unshift("32-bit")):H&&/^OS X/.test(H.family)&&"Chrome"==j&&parseFloat(B)>=39&&(H.architecture=64),t||(t=null);var z={};return z.description=t,z.layout=$&&$[0],z.manufacturer=q,z.name=j,z.prerelease=U,z.product=G,z.ua=t,z.version=j&&B,z.os=H||{architecture:null,family:null,version:null,toString:function(){return"null"}},z.parse=parse,z.toString=function toStringPlatform(){return this.description||""},z.version&&D.unshift(B),z.name&&D.unshift(j),H&&j&&(H!=String(H).split(" ")[0]||H!=j.split(" ")[0]&&!G)&&D.push(G?"("+H+")":"on "+H),D.length&&(z.description=D.join(" ")),z}();u&&h?forOwn(T,(function(t,o){u[o]=t})):m.platform=T}).call(t)}));function getSystemInfoFn$4(){var t,o,a=Tt.version||"";if(isElectron())try{var m=navigator.userAgent.match(/Electron\/([\d.]+\d+)/);m&&m[1]&&"string"==typeof m[1]&&(a=m[1])}catch(t){}return{os:(null===(t=Tt.os)||void 0===t?void 0:t.family)||"",osVer:(null===(o=Tt.os)||void 0===o?void 0:o.version)||"",browser:Tt.name||"",browserVer:Tt.version||"",libEnv:"BROWSER",hostEnv:isElectron()?"Electron":isMobile()?"H5":isBrowser()?"BROWSER":"Unset",hostEnvEnum:isElectron()?5:isMobile()?101:isBrowser()?100:0,hostEnvVer:a,userAgent:navigator&&navigator.userAgent,model:a,manufactor:Tt.name||""}}var Ct=null,Nt=null,At={getNetworkStatus:()=>Promise.resolve({net_type:0,net_connect:"undefined"==typeof navigator||"boolean"!=typeof navigator.onLine||navigator.onLine}),onNetworkStatusChange(t){Ct=function(){t({isConnected:!0,networkType:0})},Nt=function(){t({isConnected:!1,networkType:0})},window.addEventListener("online",Ct),window.addEventListener("offline",Nt)},offNetworkStatusChange(){Ct&&window.removeEventListener("online",Ct),Nt&&window.removeEventListener("offline",Nt),Ct=null,Nt=null}},Ot=getLogger(),getVisibilityEvent=()=>{var t="hidden",o="visibilitychange";return"undefined"==typeof document||void 0!==document.hidden||(void 0!==document.webkitHidden?(t="webkitHidden",o="webkitvisibilitychange"):void 0!==document.msHidden?(t="msHidden",o="msvisibilitychange"):void 0!==document.mozHidden&&(t="mozHidden",o="mozvisibilitychange")),{hidden:t,visibilityChange:o}};class PowerMonitor$1 extends ve{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 o=this.status;t!==o&&(this.status=t,0===t&&1===o&&this.emit("onPowerMonitorTurnActive"),Ot.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:o,visibilityChange:a}=getVisibilityEvent();o&&void 0!==document[o]&&(this.visibilityListener=(t=this,()=>{var o=t.status,{hidden:a}=getVisibilityEvent();a&&document[a]?t.status=1:(t.status=0,1===o&&t.emit("onPowerMonitorTurnActive")),Ot.log("Adapter powerMonitor::visibility change status:",t.status)}),document.addEventListener(a,this.visibilityListener),this.flag=!0,Ot.log("Adapter powerMonitor::_initVisibilityListener success, isHidden:",null===document||void 0===document?void 0:document[o]))}else Ot.warn("Adapter powerMonitor::_initVisibilityListener no document.addEventListener")}_canIUse(){return"undefined"!=typeof document&&void 0!==document.addEventListener}}class IDB{constructor(t,o){this.db=null,this.stores=[],this.name=t,this.version=o}getDB(){if(!this.db)throw new Error("DB not ready");return this.db}getStore(t){var o=this.stores.find((o=>o.storeName===t));if(!o)throw new Error(`LogStorage: store not found. ${t}`);return o}open(){var t=window.indexedDB.open(this.name,this.version);return new Promise(((o,a)=>{t.onerror=t=>{var o=t.target;a(o.error)},t.onsuccess=t=>{var a=t.target;this.db=a.result,this.db.removeEventListener("close",this.triggerDBCloseEvt.bind(this)),this.db.addEventListener("close",this.triggerDBCloseEvt.bind(this)),this.stores.push(new IDBStore("log",this)),o()},t.onupgradeneeded=t=>{var o=t.target;this.upgradeDBBySchema(o)}}))}triggerDBCloseEvt(){try{this.db&&this.db.close(),this.db=null}catch(t){}this.open()}upgradeDBBySchema(t){var o=t.result,a=t.transaction&&o.objectStoreNames.contains("log")?t.transaction.objectStore("log"):o.createObjectStore("log",{keyPath:"id",autoIncrement:!0});try{a.index("time")}catch(t){a.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,o){this.idb=null,this.storeName=t,this.idb=o}getDB(){if(!this.idb)throw new Error("DB not ready");return this.idb.getDB()}getStoreName(){return this.storeName}bulkCreate(t){var o=this.getDB(),a=this.getStoreName(),m=o.transaction(a,"readwrite"),u=m.objectStore(a);return t.forEach((t=>{u.add(t)})),new Promise((function(t,o){m.oncomplete=function(){t()},m.onerror=function(t){var a=t.target;o(a.error)},m.onabort=function(t){var a=t.target;a.error instanceof Error?o(a.error):o(new Error("TransactionAborted"))}}))}bulkDelete(t){var{keyName:o,lower:a,upper:m,lowerOpen:u=!1,upperOpen:h=!1}=t,g=IDBKeyRange.bound(a,m,u,h),I=this.getDB(),M=this.getStoreName(),_=I.transaction(M,"readwrite"),E=_.objectStore(M).index(o).openCursor(g),S=0;return E.onsuccess=function(t){var o=t.target.result;o&&(o.delete(),S++,o.continue())},new Promise((function(t,o){_.oncomplete=function(){t(S)},_.onerror=function(t){var a=t.target;o(a.error)},_.onabort=function(t){var a=t.target;a.error instanceof Error?o(a.error):o(new Error("TransactionAborted"))}}))}readAll(){var t=this.getDB(),o=this.getStoreName(),a=t.transaction(o,"readonly").objectStore(o);if(!a.getAll)throw new Error("IDBExtract not support");var m=a.getAll();return new Promise(((t,o)=>{m.onsuccess=function(o){var a=o.target;t(a.result)},m.onerror=function(t){var a=t.target;o(a.error)}}))}}class LogStorageImpl$1{constructor(t="nim_logs"){this.idb=new IDB(t,1)}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()-2592e5})}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"),o=yield t.readAll();if(0!==o.length){var a=o.reduce(((t,o)=>{var a=o.iid;return t[a]||(t[a]=[]),t[a].push(o),t}),{}),m=Object.keys(a).map((t=>`==========iid:${t}==========\n ${a[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$4=()=>({setLogger:setLogger,platform:"BROWSER",localStorage:window.localStorage,request:Et,WebSocket:window.WebSocket,uploadFile:uploadFileFn$4,getFileUploadInformation:getFileUploadInformationFn$4,getSystemInfo:getSystemInfoFn$4,net:At,powerMonitor:new PowerMonitor$1,logStorage:LogStorageImpl$1}),Rt=getLogger();class PowerMonitor extends ve{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 o=this.status;t!==o&&(this.status=t,0===t&&1===o&&this.emit("onPowerMonitorTurnActive"),Rt.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"),Rt.log("Adapter powerMonitor::onAppShow status:",this.status)},this.appHideListener=()=>{this.status=1,Rt.log("Adapter powerMonitor::onAppHide status:",this.status)},this.env.onAppShow(this.appShowListener),this.env.onAppHide(this.appHideListener),this.flag=!0,Rt.log("Adapter powerMonitor::_initAppLifecycleListener success")):Rt.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 tt&&tt.getSystemInfoSync?tt:"undefined"!=typeof swan&&swan.getSystemInfoSync?swan:"undefined"!=typeof my&&my.getSystemInfoSync?my:"undefined"!=typeof wx&&wx.getAppBaseInfo?wx:void 0}class LogStorageImpl{constructor(t="nim_logs"){this.dirPath="",this.filePath="",this.copyFilePath="",this.maxCapacity=26214400,this.remainCapacity=8388608,this.count=0,this.maxCount=60,this.lastErrorMsg=void 0;var o=getAPIEnv();o&&(this.dirPath=`${o.env.USER_DATA_PATH}/__nim`,this.filePath=`${this.dirPath}/${t}.log`,this.copyFilePath=`${this.dirPath}/${t}_copy.log`)}makeDir(){var t=getAPIEnv();if(t){var o=getLogger(),a=t.getFileSystemManager();try{var m=a.accessSync(this.dirPath);o.log("logStorage::access dir:",m),("object"==typeof m&&null!==m?m.error||m.errno||m.errCode||m.errNo:0)>200&&a.mkdirSync(this.dirPath,!0)}catch(t){a.mkdirSync(this.dirPath,!0)}try{var u=a.accessSync(this.filePath);o.log("logStorage::access file:",u),("object"==typeof u&&null!==u?u.error||u.errno||u.errCode||u.errNo:0)>200&&a.writeFileSync(this.filePath,"===","utf8")}catch(t){a.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(o){t.warn(`logStorage::open log file failed:${this.filePath}`,o)}yield this.checkCapacity(this.remainCapacity)}}))}checkCapacity(t){return __awaiter(this,void 0,void 0,(function*(){var o=getAPIEnv();if(o){var a=getLogger(),m=o.getFileSystemManager(),u=this.getSize();if(u>this.maxCapacity){a.log(`logStorage::checksize:exceed,${u} byte`);var h="";try{h=yield this.readLogs(u-t)}catch(t){return void a.log("logStorage::checkCapacity:read failed",t)}a.log(`logStorage::checksize:read success ${u-t} byte`);try{m.unlinkSync(this.filePath)}catch(t){return void a.log("logStorage::checkCapacity:unlink failed",t)}try{m.writeFileSync(this.filePath,h,"utf8")}catch(t){return void a.log("logStorage::checkCapacity:write failed",t)}}else a.log(`logStorage::checkCapacity:not exceeding,${u} byte`)}}))}getSize(){var t,o=getAPIEnv();if(!o)return 0;var a,m=getLogger(),u=o.getFileSystemManager();try{a=u.statSync(this.filePath,!1)}catch(t){return m.warn("logStorage::stat failed",t),0}return a.size||(null===(t=a.stats)||void 0===t?void 0:t.size)}readLogs(t=0){var o=getAPIEnv();if(!o)return Promise.resolve("");var a=getLogger(),m=o.getFileSystemManager();return new Promise(((o,u)=>{m.readFile({filePath:this.filePath,encoding:"utf8",position:t,success:t=>{var m=t.data;"string"==typeof m?(a.warn(`logStorage::readLogs success ${m.length}`),o(m)):(a.warn("logStorage::readLogs empty"),u(new Error("logStorage::readLogs empty")))},fail:t=>{var o=t.errMsg||t.errorMessage||t.message;a.warn(`logStorage::readLogs failed ${o}`);var m={code:t.errCode||0,message:o};u(m)}})}))}close(){}addLogs(t){var o=getAPIEnv();if(!o)return Promise.resolve();var a=getLogger(),m=t.map((t=>t.text)).concat("").join("\n");try{o.getFileSystemManager().appendFileSync(this.filePath,m,"utf8")}catch(t){var u=t.errMsg||t.errorMessage||t.message;this.lastErrorMsg!==u&&a.warn("logStorage::append failed",t),this.lastErrorMsg=u}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 o=getLogger(),a=this.getSize(),m=t.getFileSystemManager();if(a>0){try{m.copyFileSync(this.filePath,this.copyFilePath)}catch(t){return void o.warn("logStorage::copyFileSync failed",t)}return this.copyFilePath}o.warn("logStorage::extractLogs empty")}}))}afterUpload(){return __awaiter(this,void 0,void 0,(function*(){var t=getAPIEnv();if(t){var o=getLogger(),a=t.getFileSystemManager();try{a.unlinkSync(this.copyFilePath)}catch(t){return void o.log("logStorage::delete copyFilePath failed",t)}}}))}}var bt={clear:()=>wx.clearStorageSync(),getItem:t=>wx.getStorageSync(t),setItem:(t,o)=>wx.setStorageSync(t,o),removeItem:t=>wx.removeStorageSync(t)};function requestFn$3(t,o){return o&&(o.header=o.headers,o.data=o.data||(null==o?void 0:o.params)||{}),new Promise(((a,m)=>{wx.request(Object.assign(Object.assign({url:t},o),{success:function(o){"number"==typeof(o=o||{}).statusCode&&o.statusCode.toString().startsWith("2")?(o={data:o.data,status:o.statusCode,errMsg:o.errMsg,header:o.header},a(o)):m({code:o.statusCode||0,message:o.data||`wechat request fail. url: ${t}`})},fail:function(o){var a=`wechat request fail. url: ${t}`;m(o?{code:5===o.errno?Me.V2NIM_ERROR_CODE_TIMEOUT:o.errno,message:o.errMsg||a}:{code:0,message:a})}}))}))}function getSystemInfoFn$3(){var t=wx.getSystemInfoSync()||{};return{os:t.platform||"",osVer:t.system||"",browser:"",browserVer:"",libEnv:"MINIAPP",hostEnv:"WeiXin",hostEnvEnum:6,hostEnvVer:t.version,model:t.SDKVersion,manufactor:"WeiXin",userAgent:`NIM/Web/WeChatMiniApp(${t.SDKVersion})/V10.9.41/{{appkey}}`,pushDeviceInfo:{PRODUCT:t.model,DEVICE:t.model,MANUFACTURER:t.brand}}}function uploadFileFn$3(t){var o=getLogger(),a=t.headers||{};return t.md5&&(a["Content-MD5"]=t.md5),new Promise(((m,u)=>{var h=wx.uploadFile(Object.assign(Object.assign({url:`${t.commonUploadHost}/${t.nosToken.bucket}`,header:a},Object.keys(a).length>0?{header:a}:{}),{formData:{Object:decodeURIComponent(t.nosToken.objectName),"x-nos-token":t.nosToken.token,"x-nos-entity-type":"json"},name:"file",filePath:t.filePath,success(o){if(200==o.statusCode)try{var a=JSON.parse(o.data);a.name=t.filePath,a.ext=a.name.lastIndexOf(".")>-1?a.name.slice(a.name.lastIndexOf(".")+1).toLowerCase():"",m(a)}catch(t){u({code:o.statusCode,message:o.errMsg,rawData:o.data})}else u({code:o.statusCode,message:o.errMsg,rawData:o.data})},fail(t){t.code="uploadFile:fail abort"===t.errMsg?Me.V2NIM_ERROR_CODE_CANCELLED:t.errno,t.message=t.errMsg,u(t)}}));try{t.onUploadStart&&t.onUploadStart(h)}catch(t){o.error("uploadFile: options.onUploadStart error",t),h.abort(),u(t)}t.onUploadProgress&&h.onProgressUpdate((function(o){t.onUploadProgress&&t.onUploadProgress({total:o.totalBytesExpectedToSend,loaded:o.totalBytesSent,percentage:parseFloat((o.totalBytesSent/o.totalBytesExpectedToSend).toFixed(2)),percentageText:o.progress+"%"})}))}))}function getFileUploadInformationFn$3(t){return null}class WebSocketFn$3{constructor(t,o=""){if(this.CONNECTING=0,this.OPEN=1,this.CLOSING=2,this.CLOSED=3,this.binaryType="",this.onclose=function(t){getLogger().log("wx-app: sockets on close ",t)},this.onerror=function(t){getLogger().error("wx-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=o,this.readyState=this.CONNECTING;var a=this.protocol?{protocols:[this.protocol]}:{};this.socketTask=wx.connectSocket(Object.assign(Object.assign({url:this.url},a),{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:o,reason:a,wasClean:m}=t;"function"==typeof this.onclose&&this.onclose&&this.onclose({code:o,reason:a,wasClean:m,type:"close"})})),this.socketTask.onMessage((t=>{this.onmessage&&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(`wx-app: socket sendMsg when readyState=${this.readyState}`);if(!("string"==typeof t||t instanceof ArrayBuffer))throw new TypeError("wx-app: socket sendMsg only String/ArrayBuffer supported");this.socketTask.send({data:t})}errorHandler(t){getLogger().error("wx-app::ws: onerror ",t),this.readyState=this.CLOSED,this.onerror&&this.onerror({type:"error",message:t&&t.errMsg})}}var getAdapter$3=()=>({setLogger:setLogger,platform:"WXAPP",localStorage:bt,request:requestFn$3,WebSocket:WebSocketFn$3,uploadFile:uploadFileFn$3,getFileUploadInformation:getFileUploadInformationFn$3,getSystemInfo:getSystemInfoFn$3,net:getNetFn(wx),powerMonitor:new PowerMonitor(wx),logStorage:LogStorageImpl}),Vt={clear(){my.clearStorageSync()},getItem:t=>my.getStorageSync({key:t}).data,setItem:(t,o)=>my.setStorageSync({key:t,data:o}),removeItem:t=>my.removeStorageSync({key:t})};function requestFn$2(t,o){return o&&(o.data=o.data||(null==o?void 0:o.params)||{}),new Promise(((a,m)=>{my.request(Object.assign(Object.assign({url:t},o),{success:function(o){"number"==typeof(o=o||{}).status&&o.status.toString().startsWith("2")?(o={data:o.data,status:o.status,errMsg:o.errMsg,header:o.header},a(o)):m({code:o.status||0,message:o.data||`ali request fail. url: ${t}`})},fail:function(o){var a=`ali request fail. url: ${t}`;m(o?{code:13===o.error?Me.V2NIM_ERROR_CODE_TIMEOUT:o.error,message:o.errorMessage||a}:{code:0,message:a})}}))}))}function getSystemInfoFn$2(){var t=my.getSystemInfoSync()||{};return{libEnv:"MINIAPP",os:t.platform||"",osVer:t.system||"",browser:"",browserVer:"",hostEnv:"Ali",hostEnvEnum:102,hostEnvVer:t.version,userAgent:`NIM/Web/AliMiniApp(${my.SDKVersion})/V10.9.41/{{appkey}}`,model:my.SDKVersion,manufactor:"Ali",pushDeviceInfo:{PRODUCT:t.model,DEVICE:t.model,MANUFACTURER:t.brand}}}function uploadFileFn$2(t){var o=getLogger(),a=t.headers||{};return t.md5&&(a["Content-MD5"]=t.md5),new Promise(((m,u)=>{var h=my.uploadFile(Object.assign(Object.assign({url:`${t.commonUploadHost}/${t.nosToken.bucket}`},Object.keys(a).length>0?{header:a}:{}),{formData:{Object:decodeURIComponent(t.nosToken.objectName),"x-nos-token":t.nosToken.token,"x-nos-entity-type":"json"},fileType:t.type,fileName:"file",filePath:t.filePath,success(o){if(200==o.statusCode)try{var a=JSON.parse(o.data);a.name=t.filePath,a.ext=a.name.lastIndexOf(".")>-1?a.name.slice(a.name.lastIndexOf(".")+1).toLowerCase():"",m(a)}catch(t){u({code:o.statusCode,message:o.errMsg,rawData:o.data})}else u({code:o.statusCode,message:o.errMsg,rawData:o.data})},fail(t){t.code=9===t.error?Me.V2NIM_ERROR_CODE_CANCELLED:t.error,t.message=t.errorMessage,u(t)}}));try{t.onUploadStart&&t.onUploadStart(h)}catch(t){o.error("uploadFile: options.onUploadStart error",t),h.abort(),u(t)}t.onUploadProgress&&h.onProgressUpdate((function(o){t.onUploadProgress&&t.onUploadProgress({total:o.totalBytesExpectedToWrite,loaded:o.totalBytesWritten,percentage:parseFloat((o.totalBytesWritten/o.totalBytesExpectedToWrite).toFixed(2)),percentageText:o.progress+"%"})}))}))}function getFileUploadInformationFn$2(t){return null}class WebSocketFn$2{constructor(t,o=""){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=o,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:o,reason:a,wasClean:m}=t;"function"==typeof this.onclose&&this.onclose&&this.onclose({code:o,reason:a,wasClean:m,type:"close"}),this.socketTask=null})),this.socketTask.onMessage((t=>{var o,a=null===(o=t.data)||void 0===o?void 0:o.data,m=a;t.data.isBuffer&&(m=base64ToArrayBuffer(a)),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 getAdapter$2=()=>({setLogger:setLogger,platform:"ALIAPP",localStorage:Vt,request:requestFn$2,WebSocket:WebSocketFn$2,uploadFile:uploadFileFn$2,getSystemInfo:getSystemInfoFn$2,getFileUploadInformation:getFileUploadInformationFn$2,net:getNetFn(my),powerMonitor:new PowerMonitor(my),logStorage:LogStorageImpl}),kt={clear(){swan.clearStorageSync()},getItem:t=>swan.getStorageSync(t),setItem:(t,o)=>swan.setStorageSync(t,o),removeItem:t=>swan.removeStorageSync(t)};function requestFn$1(t,o){return o&&(o.header=o.headers,o.data=o.data||(null==o?void 0:o.params)||{}),new Promise(((a,m)=>{swan.request(Object.assign(Object.assign({url:t},o),{success:function(o){"number"==typeof(o=o||{}).statusCode&&o.statusCode.toString().startsWith("2")?(o={data:o.data,status:o.statusCode,errMsg:o.errMsg,header:o.header},a(o)):m({code:o.statusCode||0,message:o.data||`baidu request fail. url: ${t}`})},fail:function(o){var a=`baidu request fail. url: ${t}`;m(o?{code:1===o.errCode?Me.V2NIM_ERROR_CODE_TIMEOUT:o.errCode,message:o.errMsg||a}:{code:0,message:a})}}))}))}function getSystemInfoFn$1(){var t=swan.getSystemInfoSync()||{};return{os:t.platform||"",osVer:t.system||"",browser:"",browserVer:"",libEnv:"MINIAPP",hostEnv:"Baidu",userAgent:`NIM/Web/BaiduMiniApp(${t.SDKVersion})/V10.9.41/{{appkey}}`,hostEnvVer:t.version,hostEnvEnum:103,model:t.SDKVersion,manufactor:"Baidu",pushDeviceInfo:{PRODUCT:t.model,DEVICE:t.model,MANUFACTURER:t.brand}}}function uploadFileFn$1(t){var o=getLogger(),a=t.headers||{};return t.md5&&(a["Content-MD5"]=t.md5),new Promise(((m,u)=>{var h=swan.uploadFile(Object.assign(Object.assign({url:`${t.commonUploadHost}/${t.nosToken.bucket}`},Object.keys(a).length>0?{header:a}:{}),{formData:{Object:decodeURIComponent(t.nosToken.objectName),"x-nos-token":t.nosToken.token,"x-nos-entity-type":"json"},name:"file",filePath:t.filePath,success(o){if(200==o.statusCode)try{var a=JSON.parse(o.data);a.name=t.filePath,a.ext=a.name.lastIndexOf(".")>-1?a.name.slice(a.name.lastIndexOf(".")+1).toLowerCase():"",m(a)}catch(t){u({code:o.statusCode,message:o.errMsg,rawData:o.data})}else u({code:o.statusCode,message:o.errMsg,rawData:o.data})},fail(t){t.code="uploadFile:fail abort"===t.errMsg?Me.V2NIM_ERROR_CODE_CANCELLED:t.errCode,t.message=t.errMsg,u(t)}}));try{t.onUploadStart&&t.onUploadStart(h)}catch(t){o.error("uploadFile: options.onUploadStart error",t),h.abort(),u(t)}t.onUploadProgress&&h.onProgressUpdate((function(o){t.onUploadProgress&&t.onUploadProgress({total:o.totalBytesExpectedToSend,loaded:o.totalBytesSent,percentage:parseFloat((o.totalBytesSent/o.totalBytesExpectedToSend).toFixed(2)),percentageText:o.progress+"%"})}))}))}function getFileUploadInformationFn$1(t){return null}class WebSocketFn$1{constructor(t,o=""){if(this.CONNECTING=0,this.OPEN=1,this.CLOSING=2,this.CLOSED=3,this.binaryType="",this.onclose=function(t){getLogger().log("baidu-app: sockets on close ",t)},this.onerror=function(t){getLogger().error("baidu-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=o,this.readyState=this.CONNECTING;var a=this.protocol?{protocols:[this.protocol]}:{};this.socketTask=swan.connectSocket(Object.assign(Object.assign({url:this.url},a),{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:o,reason:a,wasClean:m}=t;"function"==typeof this.onclose&&this.onclose&&this.onclose({code:o,reason:a,wasClean:m,type:"close"})})),this.socketTask.onMessage((t=>{this.onmessage&&this.onmessage({data:t.data})}))}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(`wx-app: socket sendMsg when readyState=${this.readyState}`);if(!("string"==typeof t||t instanceof ArrayBuffer))throw new TypeError("wx-app: socket sendMsg only String/ArrayBuffer supported");this.socketTask.send({data:t})}errorHandler(t){this.readyState=this.CLOSED,this.onerror&&this.onerror({type:"error",message:t&&t.errMsg})}}var getAdapter$1=()=>({setLogger:setLogger,platform:"BAIDUAPP",localStorage:kt,request:requestFn$1,WebSocket:WebSocketFn$1,uploadFile:uploadFileFn$1,getFileUploadInformation:getFileUploadInformationFn$1,getSystemInfo:getSystemInfoFn$1,net:getNetFn(swan)}),Pt={clear(){tt.clearStorageSync()},getItem:t=>tt.getStorageSync(t),setItem:(t,o)=>tt.setStorageSync(t,o),removeItem:t=>tt.removeStorageSync(t)};function requestFn(t,o){return o&&(o.header=o.headers,o.data=o.data||(null==o?void 0:o.params)||{}),new Promise(((a,m)=>{tt.request(Object.assign(Object.assign({url:t},o),{success:function(o){"number"==typeof(o=o||{}).statusCode&&o.statusCode.toString().startsWith("2")?(o={data:o.data,status:o.statusCode,errMsg:o.errMsg,header:o.header},a(o)):m({code:o.statusCode||0,message:o.data||`tt request fail. url: ${t}`})},fail:function(o){var a=`tt request fail. url: ${t}`;m(o?{code:21103===o.errNo?Me.V2NIM_ERROR_CODE_TIMEOUT:o.errNo,message:o.errMsg||a}:{code:0,message:a})}}))}))}function getSystemInfoFn(){var t=tt.getSystemInfoSync()||{};return{os:t.platform||"",osVer:t.system||"",browser:"",browserVer:"",libEnv:"MINIAPP",hostEnv:"Tiktok",hostEnvEnum:104,hostEnvVer:t.version,model:t.SDKVersion,manufactor:"Tiktok",userAgent:`NIM/Web/TiktokMiniApp(${t.SDKVersion})/V10.9.41/{{appkey}}`,pushDeviceInfo:{PRODUCT:t.model,DEVICE:t.model,MANUFACTURER:t.brand}}}function uploadFileFn(t){var o=getLogger(),a=t.headers||{};return t.md5&&(a["Content-MD5"]=t.md5),new Promise(((m,u)=>{var h=tt.uploadFile(Object.assign(Object.assign({url:`${t.commonUploadHost}/${t.nosToken.bucket}`},Object.keys(a).length>0?{header:a}:{}),{formData:{Object:decodeURIComponent(t.nosToken.objectName),"x-nos-token":t.nosToken.token,"x-nos-entity-type":"json"},name:"file",filePath:t.filePath,success(o){if(200==o.statusCode)try{var a=JSON.parse(o.data);a.name=t.filePath,a.ext=a.name.lastIndexOf(".")>-1?a.name.slice(a.name.lastIndexOf(".")+1).toLowerCase():"",m(a)}catch(t){u({code:o.statusCode,message:o.errMsg,rawData:o.data})}else u({code:o.statusCode,message:o.errMsg,rawData:o.data})},fail(t){t.code=21104===t.errNo?Me.V2NIM_ERROR_CODE_CANCELLED:t.errNo,t.message=t.errMsg,u(t)}}));try{t.onUploadStart&&t.onUploadStart(h)}catch(t){o.error("uploadFile: options.onUploadStart error",t),h.abort(),u(t)}t.onUploadProgress&&h.onProgressUpdate((function(o){t.onUploadProgress&&t.onUploadProgress({total:o.totalBytesExpectedToSend,loaded:o.totalBytesSent,percentage:parseFloat((o.totalBytesSent/o.totalBytesExpectedToSend).toFixed(2)),percentageText:o.progress+"%"})}))}))}function getFileUploadInformationFn(t){return null}class WebSocketFn{constructor(t,o=""){if(this.CONNECTING=0,this.OPEN=1,this.CLOSING=2,this.CLOSED=3,this.binaryType="",this.onclose=function(t){getLogger().log("wx-app: sockets on close ",t)},this.onerror=function(t){getLogger().error("wx-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=o,this.readyState=this.CONNECTING;var a=this.protocol?{protocols:[this.protocol]}:{};this.socketTask=tt.connectSocket(Object.assign(Object.assign({url:this.url},a),{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.header})})),this.socketTask.onError((t=>{this.errorHandler(t)})),this.socketTask.onClose((t=>{this.readyState=this.CLOSED;var{code:o,reason:a,wasClean:m}=t;"function"==typeof this.onclose&&this.onclose&&this.onclose({code:o,reason:a,wasClean:m,type:"close"})})),this.socketTask.onMessage((t=>{this.onmessage&&this.onmessage({data:t.data})}))}close(){this.socketTask&&this.socketTask.close({code:1e3,reason:"user force close websocket",complete:()=>{}})}send(t){if(this.readyState!==this.OPEN)throw new Error(`tt-app: socket sendMsg when readyState=${this.readyState}`);if(!("string"==typeof t||t instanceof ArrayBuffer))throw new TypeError("tt-app: socket sendMsg only String/ArrayBuffer supported");this.socketTask&&this.socketTask.send({data:t})}errorHandler(t){getLogger().error("tt-app::ws: onerror ",t),this.readyState=this.CLOSED,this.onerror&&this.onerror({type:"error",message:t&&t.errMsg})}}var getAdapter=()=>({setLogger:setLogger,platform:"TTAPP",localStorage:Pt,request:requestFn,WebSocket:WebSocketFn,uploadFile:uploadFileFn,getSystemInfo:getSystemInfoFn,getFileUploadInformation:getFileUploadInformationFn,net:getNetFn(tt)});class V2NIMConversationIdUtilImpl{constructor(t){this.name="V2NIMConversationIdUtil",this.core=t}conversationId(t,o){return`${this.core.account}|${t}|${o}`}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 o=t.replace(`${this.core.account}|`,"");return Number(o[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 o=this.parseConversationType(t);return`${1===o?"p2p":2===o?"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 o=[];return this.messages.forEach((a=>{a.conversationId===t&&o.push(a)})),o}getLastMessageOfConversation(t){var o=this.getMessagesByConversationId(t);if(0!==o.length)return o.reduce(((t,o)=>o.createTime>t.createTime?o:t),o[0])}upsertMessages(t){t.forEach((t=>{this.setLRU(t.messageClientId,t)}))}setLRU(t,o){if(this.messages.has(t))this.messages.delete(t);else if(this.messages.size>=this.capacity){var a=this.messages.keys().next().value;a&&this.messages.delete(a)}this.messages.set(t,o)}deleteMessage(t){this.messages.delete(t)}deleteMessages(t,o){this.messages.forEach((a=>{t===a.conversationId&&(!o||o&&a.createTime<o)&&this.messages.delete(a.messageClientId)}))}}var Lt={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}},wt=Object.assign({requestId:{type:"string",allowEmpty:!1}},Lt),Dt={requestId:{type:"string",allowEmpty:!1},accountId:{type:"string",allowEmpty:!1}},Ut=[1,3,2,0],xt=[2,7,12,100,6,1,-1,4,5,11,0,10,3],Ft={routeEnabled:{type:"boolean",required:!1},routeEnvironment:{type:"string",required:!1}},Bt={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"}},$t={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}},jt={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:Ft},pushConfig:{type:"object",required:!1,rules:Bt},antiSpamConfig:{type:"object",required:!1,rules:$t},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:Lt},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}},Gt={message:{type:"object",rules:{text:{type:"string",required:!1},messageType:{type:"enum",values:xt},messageClientId:{type:"string",allowEmpty:!1}}},params:{type:"object",rules:jt,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"}}}},qt={conversationId:{type:"string",allowEmpty:!1},message:{type:"object",rules:{text:{type:"string",required:!1},messageType:{type:"enum",values:xt},messageClientId:{type:"string",allowEmpty:!1},attachment:{type:"object",required:!1,rules:{file:{type:"file",required:!1}}}}},params:{type:"object",required:!1,rules:jt}},Ht={message:{type:"object",rules:{messageClientId:{type:"string",allowEmpty:!1},messageServerId:{type:"string",allowEmpty:!1},conversationType:{type:"enum",values:Ut},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}},zt={conversationId:{type:"string",allowEmpty:!1},messageTypes:{type:"array",required:!1,itemType:"enum",values:xt},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"}}}},Yt={conversationType:{type:"enum",values:Ut},receiverId:{type:"string",allowEmpty:!1},senderId:{type:"string",allowEmpty:!1},messageServerId:{type:"string",allowEmpty:!1},messageClientId:{type:"string",allowEmpty:!1}},Kt={messageRefers:{type:"array",required:!0,rules:Yt}},Wt={conversationId:{type:"string",allowEmpty:!1},conversationType:{type:"enum",values:Ut},receiverId:{type:"string",allowEmpty:!1},senderId:{type:"string",allowEmpty:!1},messageClientId:{type:"string",allowEmpty:!1},createTime:{type:"number"}},Jt={messages:{type:"array",rules:Wt}},Xt={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}},Qt={serverExtension:{type:"string",required:!1}},Zt={messageClientId:{type:"string",allowEmpty:!1},conversationType:{type:"enum",values:[1]},receiverId:{type:"string",allowEmpty:!1},createTime:{type:"number"}},er={messages:{type:"array",rules:{messageClientId:{type:"string",allowEmpty:!1},conversationType:{type:"enum",values:[2]},receiverId:{type:"string",allowEmpty:!1},createTime:{type:"number"}},min:1}},tr={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}},rr={message:{type:"object",rules:{conversationType:{type:"enum",values:Ut},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}}}},ir={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"}}}},or={params:{type:"object",rules:{collectionType:{type:"number",min:1},collectionData:{type:"string",allowEmpty:!1},serverExtension:{type:"string",required:!1},uniqueId:{type:"string",required:!1}}}},sr={collections:{type:"array",min:1,rules:{collectionId:{type:"string",allowEmpty:!1},createTime:{type:"number"}}}},nr={serverExtension:{type:"string",required:!1},collection:{type:"object",rules:{collectionId:{type:"string",allowEmpty:!1},collectionType:{type:"number"},createTime:{type:"number"}}}},ar={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}}}},cr={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:xt},messageSubtypes:{type:"array",required:!1,itemType:"number"}},dr={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:xt},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}},lr={message:{type:"object",rules:{receiverId:{type:"string",allowEmpty:!1},messageServerId:{type:"string",allowEmpty:!1},conversationType:{type:"enum",values:[2]}}}},pr={messages:{type:"array",rules:{receiverId:{type:"string",allowEmpty:!1},messageServerId:{type:"string",allowEmpty:!1},conversationType:{type:"enum",values:[2]}},min:1}},mr={sceneName:{type:"string",required:!1},name:{type:"string",required:!1}},ur=Object.assign(Object.assign({},mr),{duration:{type:"number",required:!1}}),hr=Object.assign(Object.assign({},ur),{width:{type:"number",required:!1},height:{type:"number",required:!1}}),gr=Object.assign(Object.assign({},mr),{width:{type:"number",required:!1},height:{type:"number",required:!1}}),vr={messageRefer:{type:"object",required:!0,rules:Yt},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}},fr={senderId:{type:"string",allowEmpty:!1},receiverId:{type:"string",allowEmpty:!1},createTime:{type:"number"},messageClientId:{type:"string",allowEmpty:!1},messageServerId:{type:"string",allowEmpty:!1}},Ir={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:Ft},pushConfig:{type:"object",required:!1,rules:Bt},antiSpamConfig:{type:"object",required:!1,rules:$t},clientAntispamEnabled:{type:"boolean",required:!1},clientAntispamReplace:{type:"string",required:!1}},yr={messageClientId:{type:"string",allowEmpty:!1},messageServerId:{type:"string",allowEmpty:!1},createTime:{type:"number"},aiConfig:{type:"object",rules:Lt}},Mr={operationType:{type:"enum",values:[0,1,2]},updateContent:{type:"string",allowEmpty:!0,required:!1}},_r={operationType:{type:"enum",values:[2,1],required:!0}};class ReceiptUtil{constructor(t,o){this.p2pMessageReceipts={},this.core=t,this.service=o}reset(){this.p2pMessageReceipts={}}sendP2PMessageReceipt(t){return __awaiter(this,void 0,void 0,(function*(){if(validate(Zt,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){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),a=this.p2pMessageReceipts[o]||0;return t.createTime<=a}getP2PMessageReceipt(t){return __awaiter(this,void 0,void 0,(function*(){if(validateConversationId(this.core.account,t),1!==this.core.V2NIMConversationIdUtil.parseConversationType(t))throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"getP2PMessageReceipt: conversationId is not p2p conversationId"}});return{conversationId:t,timestamp:this.p2pMessageReceipts[t]||0}}))}getTeamMessageReceipts(t){return __awaiter(this,void 0,void 0,(function*(){if(validate(pr,{messages:t},"",!0),t.some((t=>t.senderId!==this.core.account)))throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"getTeamMessageReceipts: exist messages senderId is not current user"}});if(t.some((o=>o.receiverId!==t[0].receiverId)))throw new V2NIMErrorImpl({code:Me.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(lr,{message:t},"",!0),t.senderId!==this.core.account)throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:`getTeamMessageReceiptDetail::senderId ${t.senderId} incorrect`}});var o=yield this.core.sendCmd("v2GetTeamMessageReceiptDetail",{tag:t});return{readReceipt:{conversationId:this.core.V2NIMConversationIdUtil.teamConversationId(t.receiverId),messageClientId:t.messageClientId,messageServerId:t.messageServerId,readCount:o.content.readAccountList.length,unreadCount:o.content.unreadAccountList.length},readAccountList:o.content.readAccountList,unreadAccountList:o.content.unreadAccountList}}))}sendTeamMessageReceipts(t){return __awaiter(this,void 0,void 0,(function*(){if(t.some((o=>o.conversationId!==t[0].conversationId)))throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_MISUSE,detail:{reason:"getTeamMessageReceipts: conversationId not same"}});if(validate(er,{messages:t},"",!0),t.some((t=>t.senderId===this.core.account)))throw new V2NIMErrorImpl({code:Me.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 o=t.content.data.map((t=>{var o=this.core.V2NIMConversationIdUtil.p2pConversationId(t.senderId),a=t.createTime;return this.p2pMessageReceipts[o]=a,{conversationId:o,timestamp:a}}));this.service.emit("onReceiveP2PMessageReadReceipts",o)}onP2PMessageReceiptsHandler(t){var o=this.core.V2NIMConversationIdUtil.p2pConversationId(t.content.data.senderId),a=t.content.data.createTime;this.p2pMessageReceipts[o]=a,this.service.emit("onReceiveP2PMessageReadReceipts",[{conversationId:o,timestamp:a}])}onTeamMessageReceiptsHandler(t){var o=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",o)}}var Er={"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","8_101":"v2TeamCreateMultiSync","8_109":"v2TeamSync","8_119":"v2TeamMemberUpdateMultiSync","8_126":"v2TeamMembersOfSelfInSync","21_101":"v2SuperTeamCreateMultiSync","21_109":"v2SuperTeamSync","21_110":"v2SuperTeamMemberUpdateMultiSync","21_111":"v2SuperTeamMembersOfSelfInSync"},Sr={antispamBusinessId:1},Tr="V2NIMTeamService",Cr={teamId:1,name:3,teamType:{id:4,retConverter:t=>0==+t?1:+t},ownerAccountId:5,memberLimit:{id:6,retType:"number"},isValidTeam:{id:8,retConverter:(t,o)=>1==+t&&(void 0===o[13]||1==+o[13])},memberCount:{id:9,retType:"number"},memberUpdateTime:{id:10,retType:"number"},createTime:{id:11,retType:"number"},updateTime:{id:12,retType:"number"},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"}},Nr={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[]}}}},Ar={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[]}}}},Or={accountIds:{id:1,converter:t=>JSON.stringify(t)},operation:2},Rr={teamId:1,teamType:2,roleQueryType:3,onlyChatBanned:{id:4,converter:t=>+t},nextToken:5,limit:6,direction:7},br={v2TeamCreate:{sid:31,cid:1,service:Tr,params:[{type:"Property",name:"team",reflectMapper:Cr},{type:"StrArray",name:"inviteeAccountIds"},{type:"String",name:"postscript"},{type:"Property",name:"antispamConfig",reflectMapper:Sr}],response:[{type:"Property",name:"team",reflectMapper:invertSerializeItem(Cr)},{type:"StrArray",name:"failedList"}]},v2SuperTeamCreate:{sid:32,cid:1,service:Tr,params:[{type:"Property",name:"team",reflectMapper:Cr},{type:"StrArray",name:"inviteeAccountIds"},{type:"String",name:"postscript"},{type:"Property",name:"antispamConfig",reflectMapper:Sr}],response:[{type:"Property",name:"team",reflectMapper:invertSerializeItem(Cr)},{type:"StrArray",name:"failedList"}]},v2TeamInviteMembers:{sid:31,cid:5,service:Tr,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:Tr,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:Tr,params:[{type:"Property",name:"team",reflectMapper:Cr},{type:"Property",name:"antispamConfig",reflectMapper:Sr}],response:[{type:"Long",name:"teamId"},{type:"Long",name:"timestamp"}]},v2SuperTeamUpdateInfo:{sid:32,cid:8,service:Tr,params:[{type:"Property",name:"team",reflectMapper:Cr},{type:"Property",name:"antispamConfig",reflectMapper:Sr}],response:[{type:"Long",name:"timestamp"}]},v2TeamLeave:{sid:31,cid:8,service:Tr,params:[{type:"Long",name:"teamId"}]},v2SuperTeamLeave:{sid:32,cid:7,service:Tr,params:[{type:"Long",name:"teamId"}]},v2TeamGetInfo:{sid:31,cid:9,service:Tr,params:[{type:"Long",name:"teamId"}],response:[{type:"Property",name:"team",reflectMapper:invertSerializeItem(Cr)}]},v2SuperTeamGetInfo:{sid:32,cid:9,service:Tr,params:[{type:"Long",name:"teamId"}],response:[{type:"Property",name:"team",reflectMapper:invertSerializeItem(Cr)}]},v2TeamGetByIds:{sid:31,cid:34,service:Tr,params:[{type:"LongArray",name:"teamIds"}],response:[{type:"PropertyArray",name:"teams",reflectMapper:invertSerializeItem(Cr)},{type:"LongArray",name:"tids"}]},v2SuperTeamGetByIds:{sid:32,cid:36,service:Tr,params:[{type:"LongArray",name:"teamIds"}],response:[{type:"PropertyArray",name:"teams",reflectMapper:invertSerializeItem(Cr)},{type:"LongArray",name:"tids"}]},v2TeamDismiss:{sid:31,cid:12,service:Tr,params:[{type:"Long",name:"teamId"}]},v2SuperTeamDismiss:{sid:32,cid:4,service:Tr,params:[{type:"Long",name:"teamId"}]},v2TeamAcceptInvitation:{sid:31,cid:21,service:Tr,params:[{type:"Long",name:"teamId"},{type:"String",name:"from"}],response:[{type:"Property",name:"team",reflectMapper:invertSerializeItem(Cr)}]},v2SuperTeamAcceptInvitation:{sid:32,cid:23,service:Tr,params:[{type:"Long",name:"teamId"},{type:"String",name:"from"}],response:[{type:"Property",name:"team",reflectMapper:invertSerializeItem(Cr)}]},v2TeamRejectInvite:{sid:31,cid:22,service:Tr,params:[{type:"Long",name:"teamId"},{type:"String",name:"from"},{type:"String",name:"ps"}]},v2SuperTeamRejectInvite:{sid:32,cid:24,service:Tr,params:[{type:"Long",name:"teamId"},{type:"String",name:"from"},{type:"String",name:"ps"}]},v2TeamKickMembers:{sid:31,cid:6,service:Tr,params:[{type:"Long",name:"teamId"},{type:"StrArray",name:"accounts"}]},v2SuperTeamKickMembers:{sid:32,cid:6,service:Tr,params:[{type:"Long",name:"teamId"},{type:"StrArray",name:"accounts"}]},v2TeamApplyToJoin:{sid:31,cid:13,service:Tr,params:[{type:"Long",name:"teamId"},{type:"String",name:"ps"}],response:[{type:"Property",name:"team",reflectMapper:invertSerializeItem(Cr)},{type:"Int",name:"isInTeam"}]},v2SuperTeamApplyToJoin:{sid:32,cid:20,service:Tr,params:[{type:"Long",name:"teamId"},{type:"String",name:"ps"}],response:[{type:"Property",name:"team",reflectMapper:invertSerializeItem(Cr)},{type:"Int",name:"isInTeam"}]},v2TeamAcceptJoinApplication:{sid:31,cid:14,service:Tr,params:[{type:"Long",name:"teamId"},{type:"String",name:"from"}]},v2SuperTeamAcceptJoinApplication:{sid:32,cid:21,service:Tr,params:[{type:"Long",name:"teamId"},{type:"String",name:"from"}]},v2TeamRejectJoinApplication:{sid:31,cid:15,service:Tr,params:[{type:"Long",name:"teamId"},{type:"String",name:"from"},{type:"String",name:"ps"}]},v2SuperTeamRejectJoinApplication:{sid:32,cid:22,service:Tr,params:[{type:"Long",name:"teamId"},{type:"String",name:"from"},{type:"String",name:"ps"}]},v2TeamAddManagers:{sid:31,cid:16,service:Tr,params:[{type:"Long",name:"teamId"},{type:"StrArray",name:"accounts"}]},v2SuperTeamAddManagers:{sid:32,cid:26,service:Tr,params:[{type:"Long",name:"teamId"},{type:"StrArray",name:"accounts"}]},v2TeamRemoveManagers:{sid:31,cid:17,service:Tr,params:[{type:"Long",name:"teamId"},{type:"StrArray",name:"accounts"}]},v2SuperTeamRemoveManagers:{sid:32,cid:27,service:Tr,params:[{type:"Long",name:"teamId"},{type:"StrArray",name:"accounts"}]},v2TeamTransferOwner:{sid:31,cid:18,service:Tr,params:[{type:"Long",name:"teamId"},{type:"String",name:"account"},{type:"Bool",name:"leave"}]},v2SuperTeamTransferOwner:{sid:32,cid:31,service:Tr,params:[{type:"Long",name:"teamId"},{type:"String",name:"account"},{type:"Bool",name:"leave"}]},v2TeamUpdateSelfMemberInfo:{sid:31,cid:19,service:Tr,params:[{type:"Property",name:"teamMember",reflectMapper:Nr},{type:"Property",name:"specialFollowUpdate",reflectMapper:Or},{type:"Property",name:"antispam",reflectMapper:Sr}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Nr)}]},v2SuperTeamUpdateSelfMemberInfo:{sid:32,cid:10,service:Tr,params:[{type:"Property",name:"teamMember",reflectMapper:Ar},{type:"Property",name:"specialFollowUpdate",reflectMapper:Or},{type:"Property",name:"antispam",reflectMapper:Sr}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Ar)}]},v2TeamUpdateMember:{sid:31,cid:20,service:Tr,params:[{type:"Property",name:"teamMember",reflectMapper:Nr},{type:"Property",name:"antispam",reflectMapper:Sr}]},v2SuperTeamUpdateMember:{sid:32,cid:30,service:Tr,params:[{type:"Property",name:"teamMember",reflectMapper:Ar},{type:"Property",name:"antispam",reflectMapper:Sr}]},v2TeamGetMemberInvitor:{sid:31,cid:33,service:Tr,params:[{type:"Long",name:"teamId"},{type:"StrArray",name:"accounts"}],response:[{type:"StrStrMap",name:"accountsMap"}]},v2SuperTeamGetMemberInvitor:{sid:32,cid:35,service:Tr,params:[{type:"Long",name:"teamId"},{type:"StrArray",name:"accounts"}],response:[{type:"StrStrMap",name:"accountsMap"}]},v2TeamMemberSetChatBannedStatus:{sid:31,cid:25,service:Tr,params:[{type:"Long",name:"teamId"},{type:"String",name:"accountId"},{type:"Int",name:"chatBanned"}]},v2SuperTeamMemberSetChatBannedStatus:{sid:32,cid:29,service:Tr,params:[{type:"Long",name:"teamId"},{type:"StrArray",name:"accountId"},{type:"Int",name:"chatBanned"}]},v2TeamSetChatBannedMode:{sid:31,cid:32,service:Tr,params:[{type:"Long",name:"teamId"},{type:"Int",name:"chatBannedMode"}]},v2SuperTeamSetChatBannedMode:{sid:32,cid:28,service:Tr,params:[{type:"Long",name:"teamId"},{type:"Int",name:"chatBannedMode"}]},v2TeamMemberGetListByIds:{sid:31,cid:35,service:Tr,params:[{type:"StrArray",name:"tag"}],response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(Nr)}]},v2SuperTeamMemberGetListByIds:{sid:32,cid:37,service:Tr,params:[{type:"StrArray",name:"tag"}],response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(Ar)}]},v2TeamMemberGetList:{sid:31,cid:36,service:Tr,params:[{type:"Property",name:"tag",reflectMapper:Rr}],response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(Nr)},{type:"Property",name:"pageInfo",reflectMapper:{1:"hasMore",2:"nextToken"}}]},v2TeamSync:{sid:8,cid:109,service:Tr,response:[{type:"Long",name:"timetag"},{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(Cr)}]},v2TeamCreateMultiSync:{sid:8,cid:101,service:Tr,response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Cr)}]},v2TeamMemberUpdateMultiSync:{sid:8,cid:119,service:Tr,response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Nr)}]},v2TeamMembersOfSelfInSync:{sid:8,cid:126,service:Tr,response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(Nr)},{type:"Long",name:"timetag"}]},v2SuperTeamSync:{sid:21,cid:109,service:Tr,response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(Cr)},{type:"Bool",name:"isAll"},{type:"Long",name:"timetag"}]},v2SuperTeamCreateMultiSync:{sid:21,cid:101,service:Tr,response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Cr)}]},v2SuperTeamMemberUpdateMultiSync:{sid:21,cid:110,service:Tr,response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Ar)}]},v2SuperTeamMembersOfSelfInSync:{sid:21,cid:111,service:Tr,response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(Ar)},{type:"Long",name:"timetag"}]}};function formatTeamNotificationAttachData(t,o){if(!t)return{};var a=t;return a.tinfo&&(a.tinfo=function formatTeamFromTinfo(t){return deserialize(t,invertSerializeItem(Cr))}(a.tinfo),a.tinfo.teamType=o),a.uinfos,void 0!==a.mute&&(a.mute=parseInt(a.mute)),a}function generateTeamByTeamId(t,o,a={}){return Object.assign({teamId:t,teamType:o,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},a)}function generateMemberByTeamId(t,o,a,m={}){return Object.assign({teamId:t,teamType:o,accountId:a,joinTime:0,inTeam:!0,memberRole:0,chatBanned:!1},m)}function processTeamMembers(t,o=1){return t.map((t=>function processTeamMember(t,o=1){return t.teamType=o,t.chatBanned=void 0!==t.chatBanned&&t.chatBanned,t}(t,o)))}function completeMessage(t,o,a){var m,u=Object.assign(Object.assign({},o),{conversationId:t.V2NIMConversationIdUtil.messageConversationId(o),isSelf:o.senderId===t.account,sendingState:1,messageStatus:{errorCode:(null===(m=null==o?void 0:o.messageStatus)||void 0===m?void 0:m.errorCode)||200},messageSource:a||0});if(u.threadReply&&(u.threadReply=Object.assign(Object.assign({},u.threadReply),{conversationType:u.conversationType,conversationId:u.conversationId})),u.threadRoot&&(u.threadRoot=Object.assign(Object.assign({},u.threadRoot),{conversationType:u.conversationType,conversationId:u.conversationId})),u.isInBlackList&&(u.sendingState=2,u.messageStatus.errorCode=Me.V2NIM_ERROR_CODE_ACCOUNT_IN_BLOCK_LIST,delete u.isInBlackList),u.streamConfig){var h=get(u.streamConfig,"isStream");if(!1===h)delete u.streamConfig;else if(!0===h&&void 0===u.streamConfig.status)delete u.streamConfig,o.aiConfig&&(o.aiConfig.aiStream=!0,o.aiConfig.aiStreamStatus=0);else if("number"==typeof u.streamConfig.status)return u.streamConfig={status:u.streamConfig.status},function completeMessageStreamConfig(t){t.streamConfig&&t.aiConfig&&(t.aiConfig.aiStream=!0,t.aiConfig.aiStreamStatus=t.streamConfig.status);if(t.attachment&&t.streamConfig){var o=t.attachment;t.streamConfig.lastChunk={content:o.msg,messageTime:t.createTime,chunkTime:o.timestamp,type:o.type,index:o.index},t.aiConfig&&(t.aiConfig.aiStreamLastChunk=t.streamConfig.lastChunk),delete t.attachment}return t}(u)}return formatMessageAttachment(u,t)}function formatMessageAttachment(t,o){return 5===t.messageType?function formatNotificationMessage(t,o){var a,m,u,h,g,I=o.attachment||{};if(o.attachment&&"type"in o.attachment)return o;var M=void 0;if(null===(a=I.data)||void 0===a?void 0:a.tinfo){var{id:_,data:E}=I,S=_>400?2:1,{tinfo:T}=formatTeamNotificationAttachData(Object.assign({},E),S);M={},M=__rest(T,["teamId"])}var C=Object.assign(Object.assign(Object.assign(Object.assign({raw:I.raw,type:convertNotificationType(t,I.id)},M?{updatedTeamInfo:M}:{}),{targetIds:(null===(m=I.data)||void 0===m?void 0:m.ids)||((null===(u=I.data)||void 0===u?void 0:u.id)?[I.data.id]:[])}),"string"==typeof(null===(h=I.data)||void 0===h?void 0:h.attach)?{serverExtension:I.data.attach}:{}),"number"==typeof(null===(g=I.data)||void 0===g?void 0:g.mute)?{chatBanned:0!==I.data.mute}:{});return Object.assign(Object.assign({},o),{attachment:C})}(o,t):100===t.messageType?function formatCustomMessage(t,o){var a,m,u;if("string"==typeof(null===(a=o.attachment)||void 0===a?void 0:a.raw)&&(null===(u=null===(m=t.V2NIMMessageService)||void 0===m?void 0:m.customAttachmentParsers)||void 0===u?void 0:u.length)>0){var h=o.subType||0,g=t.V2NIMMessageService.customAttachmentParsers,I=o.attachment.raw;g.some((a=>{try{var m=a(h,I);if(isPlainObject(m))return m.raw=I,o.attachment=m,!0}catch(o){return t.logger.warn(`customAttachmentParser: subType ${h}, raw: ${I}. parse error with ${o}`),!1}return!1}))}return o}(o,t):t}function completeMessageRefer(t,o){return Object.assign(Object.assign({},o),{conversationId:t.V2NIMConversationIdUtil.messageConversationId(o)})}function formatMessageRefer(t,o){var{createTime:a,senderId:m,receiverId:u,conversationType:h}=o;return{conversationType:h,conversationId:t.V2NIMConversationIdUtil.messageConversationId({conversationType:h,senderId:m,receiverId:u}),senderId:o.senderId,receiverId:o.receiverId,messageServerId:o.messageServerId,createTime:a,messageClientId:o.messageClientId}}function formatRevokeMessage(t,o){var a={7:1,8:2,12:3,13:1,14:2}[o.sysMsgType];return{postscript:o.postscript,revokeType:{7:1,8:2,12:3,13:4,14:5}[o.sysMsgType]||0,revokeAccountId:o.opeAccount||o.senderId,callbackExtension:o.callbackExtension,serverExtension:o.attach||"",messageRefer:{conversationType:a,conversationId:t.V2NIMConversationIdUtil.messageConversationId(Object.assign(Object.assign({},o),{conversationType:a,senderId:o.senderId,receiverId:o.receiverId})),senderId:o.senderId,receiverId:o.receiverId,messageServerId:o.messageServerId,createTime:o.deleteMsgCreatetime,messageClientId:o.messageClientId}}}function formatClearHistoryNotification(t,o){return{conversationId:1===o.conversationType?t.V2NIMConversationIdUtil.p2pConversationId(o.receiverId):2===o.conversationType?t.V2NIMConversationIdUtil.teamConversationId(o.teamId):t.V2NIMConversationIdUtil.superTeamConversationId(o.teamId),deleteTime:o.deleteTime,serverExtension:o.serverExtension}}function convertNotificationType(t,o){var a={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===a[o]&&t.logger.warn(`[V2NIMMessageService] undefined notification type: ${o}`),"number"==typeof a[o]?a[o]:-1}function formatSearchCloudMessageListEx(t,o){var a=[],m={};for(var u in o.forEach((t=>{var o=t.conversationId;m[o]||(m[o]={conversationId:o,messages:[],count:0}),m[o].messages.push(t),m[o].count++})),m){var h=m[u];a.push(h)}return a}function attachmentToRaw(t,o){if(!o)return"";switch(t){case 100:return o.raw||"";case 1:case 3:case 2:case 6:return function mediaAttachmentToRaw(t){var o=t,{width:a,height:m,duration:u,path:h,file:g,raw:I,ctx:M,payload:_,bucketName:E,objectName:S,token:T,ext:C}=o,N=__rest(o,["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===a?{}:{w:a}),void 0===m?{}:{h:m}),void 0===u?{}:{dur:u}))}(o);case 4:return function locationAttachmentToRaw(t){return JSON.stringify({lat:t.latitude,lng:t.longitude,title:t.address})}(o);case 12:return function callAttachmentToRaw(t){var o=__rest(t,["raw"]);try{return JSON.stringify(Object.assign(Object.assign({},o),{durations:t.durations.map((t=>({accid:t.accountId,duration:t.duration})))}))}catch(o){return JSON.stringify(t)}}(o);default:return o.raw||JSON.stringify(o)}}function rawToAttachment(t,o){var a;try{switch(a=JSON.parse(t),o){case 100:return{raw:t};case 4:return function locationRawToAttachment(t,o){return{latitude:o.lat,longitude:o.lng,address:o.title,raw:t}}(t,a);case 2:case 3:case 1:case 6:return function mediaRawToAttachment(t,o){var{w:a,h:m,dur:u,ext:h}=o,g=__rest(o,["w","h","dur","ext"]),I="string"==typeof h&&"."!==h[0]?`.${h}`:h;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},g),void 0===h?{}:{ext:I}),void 0===a?{}:{width:a}),void 0===m?{}:{height:m}),void 0===u?{}:{duration:u}),{raw:t})}(t,a);case 12:return function callRawToAttachment(t,o){return Object.assign(Object.assign({},o),{durations:o.durations.map((t=>({accountId:t.accid,duration:t.duration}))),raw:t})}(t,a);default:return"object"==typeof a&&a?Object.assign(Object.assign({},a),{raw:t}):{raw:t}}}catch(o){return"object"==typeof a&&a?Object.assign(Object.assign({},a),{raw:t}):{raw:t}}}class FileUtil{constructor(t){this.core=t}doSendFile(t,o){return __awaiter(this,void 0,void 0,(function*(){var a=t.attachment;try{var[m,u]=yield this.core.V2NIMStorageService._uploadFile({taskId:t.messageClientId,uploadParams:{fileObj:(null==a?void 0:a.file)||(null==a?void 0:a.path),sceneName:null==a?void 0:a.sceneName}},o,{fileType:t.messageType}),h=Object.assign(Object.assign({},a),{uploadState:1});void 0!==u.w&&(h.width=h.width||u.w),void 0!==u.h&&(h.height=h.height||u.h),void 0!==u.dur&&(h.duration=h.duration||u.dur),h.ext=h.ext&&-1===h.ext.indexOf(".")?`.${h.ext}`:h.ext;var g=["w","h","dur","ext","name"];for(var I in u)g.includes(I)||(h[I]=u[I]);var{raw:M,file:_,path:E}=h,S=__rest(h,["raw","file","path"]);t.attachment=JSON.parse(JSON.stringify(S)),t.attachment&&(t.attachment.raw=attachmentToRaw(t.messageType,t.attachment))}catch(o){throw t.attachment&&(t.attachment.uploadState=2),o}}))}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:Me.V2NIM_ERROR_CODE_MISUSE,detail:{reason:`cancelMessageAttachmentUpload: messageType ${t.messageType} incorrect`}});if(2===t.sendingState||1===t.sendingState)throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_RESOURCE_NOT_EXIST,detail:{reason:"cancelMessageAttachmentUpload: message is already failed or succeeded"}});yield this.core.V2NIMStorageService._cancelUploadFile(t.messageClientId)}))}}var Vr="V2NIMMessageService",kr={"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","30_11":"v2SendP2PMessageReceipt","31_28":"v2SendTeamMessageReceipts","32_2":"v2SendSuperTeamMessage","7_12":"onP2PMessageReceipts","8_31":"onTeamMessageReceipts","31_29":"v2GetTeamMessageReceipts","31_30":"v2GetTeamMessageReceiptDetail","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 Pr={conversationType:{id:0,converter:conversationTypeV2ToV1,retConverter:conversationTypeV1ToV2},receiverId:1,senderId:2,fromClientType:4,fromDeviceId:5,fromNick:6,createTime:{id:7,retType:"number"},messageType:{id:8,retType:"number"},text:9,attachment:{id:10,converter:(t,o)=>attachmentToRaw(o.messageType,t),retConverter:(t,o)=>rawToAttachment(t,Number(o[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,o)=>{if(o["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 o=JSON.parse(t);return o&&o.length>0?o.map((t=>(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:()=>{}}},Lr=invertSerializeItem(Pr),wr={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(wr);var Dr={version:1,md5:2,nosurl:3,thesaurus:4},Ur={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},xr={receiverId:0,messageServerId:1,readCount:{id:100,retType:"number"},unreadCount:{id:101,retType:"number"},messageClientId:102,latestReadAccount:103},Fr={v2BatchMarkRead:{sid:4,cid:5,service:Vr,hasPacketResponse:!1,params:[{type:"Byte",name:"sid"},{type:"Byte",name:"cid"},{type:"LongArray",name:"ids"}]},v2SendP2pMessage:{sid:30,cid:1,service:Vr,params:[{type:"Property",name:"tag",reflectMapper:Pr}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Pr)}]},onMsg:{sid:7,cid:2,service:Vr,response:[{type:"Property",name:"msg",reflectMapper:invertSerializeItem(Pr)}]},syncOfflineMsgs:{sid:4,cid:4,service:Vr,response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(Pr)}]},syncRoamingMsgs:{sid:4,cid:9,service:Vr,response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(Pr)}]},v2SendP2PMessageReceipt:{sid:30,cid:11,service:Vr,params:[{type:"Property",name:"tag",reflectMapper:Pr}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Pr)}]},v2RevokeMessage:{sid:30,cid:13,service:Vr,params:[{type:"Property",name:"tag",reflectMapper:Ur}]},v2DeleteMessage:{sid:30,cid:23,service:Vr,params:[{type:"Property",name:"tag",reflectMapper:wr}],response:[{type:"Long",name:"timetag"}]},v2DeleteMessages:{sid:30,cid:24,service:Vr,params:[{type:"PropertyArray",name:"tag",reflectMapper:wr}],response:[{type:"Long",name:"timetag"}]},v2SendTeamMessage:{sid:31,cid:2,service:Vr,params:[{type:"Property",name:"tag",reflectMapper:Pr}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Pr)}]},v2SendTeamMessageReceipts:{sid:31,cid:28,service:Vr,params:[{type:"PropertyArray",name:"tag",reflectMapper:xr}],response:[{type:"PropertyArray",name:"tag",reflectMapper:invertSerializeItem(xr)}]},v2SendSuperTeamMessage:{sid:32,cid:2,service:Vr,params:[{type:"Property",name:"tag",reflectMapper:Pr}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Pr)}]},v2RevokeSuperTeamMessage:{sid:32,cid:17,service:Vr,params:[{type:"Property",name:"tag",reflectMapper:Ur}]},syncP2PMessagReceipts:{sid:4,cid:12,service:Vr,response:[{type:"PropertyArray",name:"data",reflectMapper:invertSerializeItem(Pr)}]},onP2PMessageReceipts:{sid:7,cid:12,service:Vr,response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Pr)}]},v2GetTeamMessageReceipts:{sid:31,cid:29,service:Vr,params:[{type:"PropertyArray",name:"tag",reflectMapper:xr}],response:[{type:"PropertyArray",name:"data",reflectMapper:invertSerializeItem(xr)}]},v2GetTeamMessageReceiptDetail:{sid:31,cid:30,service:Vr,params:[{type:"Property",name:"tag",reflectMapper:xr,select:["receiverId","messageServerId"]}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(xr)},{type:"StrArray",name:"readAccountList"},{type:"StrArray",name:"unreadAccountList"}]},onTeamMessageReceipts:{sid:8,cid:31,service:Vr,response:[{type:"PropertyArray",name:"data",reflectMapper:invertSerializeItem(xr)}]},onRevokeMessage:{sid:7,cid:14,service:Vr,response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Ur)}]},syncRevokeMessage:{sid:7,cid:15,service:Vr,response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(Ur)}]},syncOnDeleteMessages:{sid:4,cid:21,service:Vr,response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(wr)}]},onDeleteMessage:{sid:7,cid:123,service:Vr,response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(wr)}]},onDeleteMessages:{sid:7,cid:124,service:Vr,response:[{type:"PropertyArray",name:"data",reflectMapper:invertSerializeItem(wr)}]},v2DownloadLocalAntiSpamVocabs:{sid:29,cid:17,service:Vr,params:[{type:"Property",name:"tag",reflectMapper:Dr}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Dr)}]},v2MessageP2pModify:{sid:30,cid:31,service:Vr,params:[{type:"Property",name:"tag",reflectMapper:Pr}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Pr)}]},v2MessageTeamModify:{sid:31,cid:37,service:Vr,params:[{type:"Property",name:"tag",reflectMapper:Pr}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Pr)}]},v2MessageSuperTeamModify:{sid:32,cid:38,service:Vr,params:[{type:"Property",name:"tag",reflectMapper:Pr}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Pr)}]},v2MessageOnModified:{sid:7,cid:33,service:Vr,response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Pr)}]},v2MessageSyncModified:{sid:4,cid:27,service:Vr,response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(Pr)},{type:"Long",name:"time"}]},v2MessageSuperTeamSyncModified:{sid:4,cid:28,service:Vr,response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(Pr)},{type:"Long",name:"time"}]}};function conversationTypeV2ToV1(t){return 1===t?0:2===t?1:3===t?5:void 0}function conversationTypeV1ToV2(t){var o=parseInt(t);return 0===o?1:1===o?2:5===o?3:0}var Br="V2NIMNotificationService",$r={"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"},jr={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,o){return"0"!==o[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,o)=>{if(o["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"}},Gr={id:1,senderId:2,timestamp:{id:4,retType:"number"},content:5},qr={v2SendCustomNotification:{sid:30,cid:7,service:Br,params:[{type:"Property",name:"tag",reflectMapper:jr}]},v2SendCustomNotificationWithSuperTeam:{sid:32,cid:16,service:Br,params:[{type:"Property",name:"tag",reflectMapper:jr}]},onSysNotification:{sid:7,cid:3,service:Br,response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(jr)}]},syncBroadcastMsg:{sid:4,cid:16,service:Br,response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(Gr)}]},onBroadcastMsg:{sid:7,cid:17,service:Br,response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Gr)}]},v2SyncOfflineSysNotifications:{sid:4,cid:9,service:Br,response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(jr)}]},v2NotificationRevoke:{sid:7,cid:14,service:Br,response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(jr)}]},v2NotificationSyncRevoke:{sid:7,cid:15,service:Br,response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(jr)},{type:"Long",name:"timetag"},{type:"Byte",name:"type"}]}},Hr={"4_5":"ysfBatchMarkRead","101_1":"ysfSendMessage","101_2":"ysfOnMsg","4_100":"ysfSyncOfflineMsgs","101_3":"ysfOnSysNotification","101_7":"ysfSendCustomNotification","4_101":"ysfSyncSysNotification"},zr={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:Pr}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Pr)}]},ysfOnMsg:{sid:101,cid:2,service:"YSFService",response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Pr)}]},ysfSyncOfflineMsgs:{sid:4,cid:100,service:"YSFService",response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(Pr)}]},ysfOnSysNotification:{sid:101,cid:3,service:"YSFService",response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(jr)}]},ysfSendCustomNotification:{sid:101,cid:7,service:"YSFService",params:[{type:"Property",name:"tag",reflectMapper:jr}]},ysfSyncSysNotification:{sid:4,cid:101,service:"YSFService",response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(jr)}]}},Yr={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,o,a={}){var m=this.core.V2NIMConversationIdUtil.parseConversationType(t),u=this.core.V2NIMConversationIdUtil.parseConversationTargetId(t),h=Date.now(),g={1:100,2:101,3:103};return Object.assign(Object.assign({},a),{notificationConfig:Object.assign({unreadEnabled:!0,offlineEnabled:!0},null==a?void 0:a.notificationConfig),pushConfig:Object.assign({pushEnabled:!0,pushNickEnabled:!0},null==a?void 0:a.pushConfig),antispamConfig:Object.assign({antispamEnabled:!0},null==a?void 0:a.antispamConfig),routeConfig:Object.assign({routeEnabled:!0},null==a?void 0:a.routeConfig),timestamp:h,type:g[m],receiverId:u,content:o})}}function getFileOrPath(t){var o="object"==typeof t?t:void 0,a="string"==typeof t?t:void 0;if(!o&&!a)throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_MISUSE,detail:{reason:"getFileOrPath::incorrect file and path"}});if("string"==typeof a)if(0===a.indexOf("nim-external")){var m=document.getElementById(a);if(!(m&&m.files&&m.files[0]))throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_FILE_NOT_FOUND,detail:{reason:`getFileOrPath::file not exist: ${a}`}});o=m.files[0]}else if("BROWSER"===Ae.platform)throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_MISUSE,detail:{reason:`getFileOrPath::incorrect path: ${a}`}});if("object"==typeof o&&void 0===o.size)throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_MISUSE,detail:{reason:"getFileOrPath::file no size"}});return{file:o,path:a}}var Kr={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,o){return t+`?imageView&thumbnail=${o}z${o}`}videoCoverUrl(t,o){return t+`?vframe&offset=${o}`}getImageThumbUrl(t,o){return __awaiter(this,void 0,void 0,(function*(){this.checkV2();var a=t;validate(Kr,{attachment:a,thumbSize:o},"",!0),o.width=o.width||0,o.height=o.height||0,0===o.width&&0===o.height&&(o.width=150);var m=a.url;try{m=yield this.core.V2NIMStorageService.shortUrlToLong(a.url)}catch(t){this.core.logger.warn("shortUrlToLong error:",t)}return{url:this.core.cloudStorage.getThumbUrl(m,o)}}))}getVideoCoverUrl(t,o){return __awaiter(this,void 0,void 0,(function*(){this.checkV2();var a=t;validate(Kr,{attachment:a,thumbSize:o},"",!0),o.width=o.width||0,o.height=o.height||0,0===o.width&&0===o.height&&(o.width=150);var m=a.url;try{m=yield this.core.V2NIMStorageService.shortUrlToLong(a.url)}catch(t){this.core.logger.warn("shortUrlToLong error:",t)}return{url:this.core.cloudStorage.getVideoCoverUrl(m,o)}}))}}var Wr,Jr,Xr={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)"}},Qr={accessKeyId:"",secretAccessKey:"",sessionToken:"",region:"",maxRetries:0,bucket:"",objectName:"",token:"",shortUrl:""};function getUploadResponseFormat(t="file"){var o=Xr[t]||{};return JSON.stringify(o).replace(/"/gi,'\\"')}!function(t){t[t.nos=1]="nos",t[t.s3=2]="s3"}(Wr||(Wr={})),function(t){t[t.dontNeed=-1]="dontNeed",t[t.time=2]="time",t[t.urls=3]="urls"}(Jr||(Jr={}));var Zr={chunkUploadHost:"https://wannos-web.127.net",chunkUploadHostBackupList:["https://fileup.chatnos.com","https://oss.chatnos.com"],commonUploadHost:"https://fileup.chatnos.com",commonUploadHostBackupList:["https://oss.chatnos.com"],chunkMaxSize:4194304e4,commonMaxSize:104857600,uploadReplaceFormat:"https://{host}/{object}",cdn:{defaultCdnDomain:"nim-nosdn.netease.im",cdnDomain:"",bucket:"",objectNamePrefix:""},downloadUrl:"https://{bucket}-nosdn.netease.im/{object}",downloadHostList:["nos.netease.com"],nosCdnEnable:!0,isNeedToGetUploadPolicyFromServer:!0};function pickBy(t,o){t=t||{},o=o||(()=>!0);var a={};for(var m in t)o(t[m])&&(a[m]=t[m]);return a}class NOS{constructor(t,o){this.nosCdnHostTimer=0,this.nosErrorCount=0,this.core=t,this.cloudStorage=o}get config(){return this.cloudStorage.config}reset(){this.nosErrorCount=0}getNosAccessToken(t){return __awaiter(this,void 0,void 0,(function*(){var o=get(yield this.core.sendCmd("getNosAccessToken",{tag:t}),"content.nosAccessTokenTag.token"),a=t.url;return{token:o,url:-1!==a.indexOf("?")?a+"&token="+o:a+"?token="+o}}))}deleteNosAccessToken(t){return __awaiter(this,void 0,void 0,(function*(){yield this.core.sendCmd("deleteNosAccessToken",{tag:t})}))}nosUpload(t,o){var a,m,u,h,g,I,M,_;return __awaiter(this,void 0,void 0,(function*(){var E=get(this.core,"config.cdn.bucket"),S={tag:t.nosScenes||E||"nim"};t.nosSurvivalTime&&(S.expireSec=t.nosSurvivalTime);var T,C=this.core.adapters.getFileUploadInformation(t);if(!o&&!C)try{T=yield this.core.sendCmd("getNosToken",{responseBody:getUploadResponseFormat(t.type),nosToken:S})}catch(t){if(this.core.logger.error("uploadFile:: getNosToken error",t),t instanceof V2NIMErrorImpl)throw t;throw new UploadError({code:"v2"===get(this.core,"options.apiVersion")?Me.V2NIM_ERROR_CODE_FILE_UPLOAD_FAILED:400,detail:{reason:"getNosToken error",rawError:t,curProvider:1}})}var N=this.config.uploadReplaceFormat.replace("{host}",this.config.cdn.cdnDomain||this.config.cdn.defaultCdnDomain).replace("{object}",C?null===(a=C.uploadInfo)||void 0===a?void 0:a.objectName:o?null==o?void 0:o.objectName:T.content.nosToken.objectName),A="";o&&o.shortUrl&&(A=o.shortUrl),(null===(h=null===(u=null===(m=null==C?void 0:C.uploadInfo)||void 0===m?void 0:m.payload)||void 0===u?void 0:u.mixStoreToken)||void 0===h?void 0:h.shortUrl)&&(A=C.uploadInfo.payload.mixStoreToken.shortUrl);var O,R=A||N;try{var b=C?{token:null===(g=null==C?void 0:C.uploadInfo)||void 0===g?void 0:g.token,bucket:null===(I=null==C?void 0:C.uploadInfo)||void 0===I?void 0:I.bucketName,objectName:null===(M=null==C?void 0:C.uploadInfo)||void 0===M?void 0:M.objectName}:o||T.content.nosToken;this.core.logger.log("uploadFile:: uploadFile params",{nosToken:b,chunkUploadHost:this.config.chunkUploadHost,chunkUploadHostBackupList:this.config.chunkUploadHostBackupList,commonUploadHost:this.config.commonUploadHost,commonUploadHostBackupList:this.config.commonUploadHostBackupList,platform:Ae.platform});var V="BROWSER"===Ae.platform?this.config.chunkUploadHost:`${this.config.commonUploadHost}/${b&&b.bucket}`;this.core.reporterHookCloudStorage.update({remote_addr:V,operation_type:o?2:0}),O=yield this.core.adapters.uploadFile(Object.assign(Object.assign(Object.assign({},t),{nosToken:b,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}}:{}))}catch(a){this.core.logger.error("uploadFile::nos uploadFile error:",a);var k="v2"===get(this.core,"options.apiVersion");if(a.code===Me.V2NIM_ERROR_CODE_CANCELLED||10499===a.errCode)throw new UploadError({code:k?Me.V2NIM_ERROR_CODE_CANCELLED:400,detail:{reason:get(a,"message")||"Request abort",rawError:a,curProvider:1}});if(k&&a.errCode===Me.V2NIM_ERROR_CODE_FILE_OPEN_FAILED)throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_FILE_OPEN_FAILED,detail:{reason:get(a,"message")||"Read file failed",rawError:a,curProvider:1}});var{net_connect:P}=yield Ae.net.getNetworkStatus();if(!1===P)throw new UploadError({code:"v2"===get(this.core,"options.apiVersion")?Me.V2NIM_ERROR_CODE_FILE_UPLOAD_FAILED:400,detail:{reason:"No network",rawError:a,curProvider:1}});if(o){if(this.nosErrorCount<=0){try{this.cloudStorage.mixStorage._addCircuitTimer()}catch(o){throw new UploadError({code:"v2"===get(this.core,"options.apiVersion")?Me.V2NIM_ERROR_CODE_FILE_UPLOAD_FAILED:400,detail:{reason:"All upload attempts failed",rawError:o,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)}return this.nosErrorCount--,this.nosUpload(t,o)}throw new UploadError({code:"v2"===get(this.core,"options.apiVersion")?Me.V2NIM_ERROR_CODE_FILE_UPLOAD_FAILED:400,detail:{reason:"NOS attempts failed",rawError:a,curProvider:1}})}var L=null==O?void 0:O.type,w=L&&L.indexOf("/")>-1?L.slice(0,L.indexOf("/")):"";w||(w=t.type||"");var D,U={image:"imageInfo",video:"vinfo",audio:"vinfo"};if(!U[w])return Object.assign({url:R},O);try{D=yield this.core.adapters.request(`${N}?${U[w]}`,{method:"GET",dataType:"json",timeout:5e3},{exception_service:3})}catch(t){return this.core.logger.error("uploadFile:: fetch file info error",t),Object.assign({url:R},O)}if(D){var{data:x}=D,B="imageInfo"===U[w]?x:null===(_=null==x?void 0:x.GetVideoInfo)||void 0===_?void 0:_.VideoInfo;return pickBy({url:R,name:O.name,size:O.size,ext:O.ext,w:null==B?void 0:B.Width,h:null==B?void 0:B.Height,orientation:null==B?void 0:B.Orientation,dur:null==B?void 0:B.Duration,audioCodec:null==B?void 0:B.AudioCodec,videoCodec:null==B?void 0:B.VideoCodec,container:null==B?void 0:B.Container},(function(t){return void 0!==t}))}return Object.assign({url:R},O)}))}_getNosCdnHost(){var t;return __awaiter(this,void 0,void 0,(function*(){var o;try{o=yield this.core.sendCmd("getNosCdnHost")}catch(t){return void this.core.logger.error("getNosCdnHost::error",t)}if(o){var a=null===(t=null==o?void 0:o.content)||void 0===t?void 0:t.nosConfigTag,m=parseInt(null==a?void 0:a.expire);0!==m&&a.cdnDomain?-1===m?(this.config.cdn.bucket=a.bucket,this.config.cdn.cdnDomain=a.cdnDomain,this.config.cdn.objectNamePrefix=a.objectNamePrefix):(this.config.cdn.bucket=a.bucket,this.config.cdn.cdnDomain=a.cdnDomain,this.config.cdn.objectNamePrefix=a.objectNamePrefix,this.nosCdnHostTimer=this.core.timerManager.addTimer((()=>{this._getNosCdnHost()}),1e3*m)):(this.config.cdn.bucket="",this.config.cdn.cdnDomain="",this.config.cdn.objectNamePrefix="")}}))}}var ei={"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"},ti={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}},ri={getNosToken:{sid:6,cid:2,service:"cloudStorage",params:[{type:"String",name:"responseBody"},{type:"Property",name:"nosToken",entity:"nosToken",reflectMapper:ti.nosToken}],response:[{type:"Property",name:"nosToken",reflectMapper:invertSerializeItem(ti.nosToken)}]},getOriginUrl:{sid:6,cid:22,service:"cloudStorage",params:[{type:"Property",name:"nosSafeUrlTag",reflectMapper:ti.nosSafeUrlTag}],response:[{type:"Property",name:"nosSafeUrlTag",reflectMapper:invertSerializeItem(ti.nosSafeUrlTag)}]},getNosCdnHost:{sid:6,cid:26,service:"cloudStorage",response:[{type:"Property",name:"nosConfigTag",reflectMapper:invertSerializeItem(ti.nosConfigTag)}]},getGrayscaleConfig:{sid:6,cid:27,service:"cloudStorage",params:[{type:"Property",name:"config"}],response:[{type:"Property",name:"grayConfigTag",reflectMapper:invertSerializeItem(ti.grayConfigTag)}]},getMixStorePolicy:{sid:6,cid:28,service:"cloudStorage",params:[{type:"LongArray",name:"supportType"}],response:[{type:"Property",name:"mixStorePolicyTag",reflectMapper:invertSerializeItem(ti.mixStorePolicyTag)}]},getMixStoreToken:{sid:6,cid:29,service:"cloudStorage",params:[{type:"Property",name:"mixStoreTokenReqTag",reflectMapper:ti.mixStoreTokenReqTag}],response:[{type:"Property",name:"mixStoreTokenResTag",reflectMapper:invertSerializeItem(ti.mixStoreTokenResTag)}]},getFileAuthToken:{sid:6,cid:30,service:"cloudStorage",params:[{type:"Property",name:"mixStoreAuthTokenReqTag",reflectMapper:ti.mixStoreAuthTokenReqTag}],response:[{type:"Property",name:"mixStoreAuthTokenResTag",reflectMapper:invertSerializeItem(ti.mixStoreAuthTokenResTag)}]},getNosAccessToken:{sid:6,cid:24,service:"cloudStorage",params:[{type:"Property",name:"tag",reflectMapper:ti.nosAccessTokenTag}],response:[{type:"Property",name:"tag",reflectMapper:invertSerializeItem(ti.nosAccessTokenTag)}]},deleteNosAccessToken:{sid:6,cid:25,service:"cloudStorage",params:[{type:"Property",name:"tag",reflectMapper:ti.nosAccessTokenTag}]}};class MixStorage{constructor(t,o){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=o,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,o){var a;return __awaiter(this,void 0,void 0,(function*(){if(Ae.localStorage)try{Ae.localStorage.getItem&&Ae.localStorage.getItem(this.GRAYKEY)&&(this.grayConfig=JSON.parse(Ae.localStorage.getItem(this.GRAYKEY))[t])}catch(t){Ae.localStorage.getItem(this.GRAYKEY)&&this.core.logger.error("uploadFile:: JSON.parse grayscaleConfig error ",t)}if(!this.grayConfig||this.grayConfig.timeStamp+1e3*this.grayConfig.ttl<o){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 u=Ae.localStorage.getItem(this.GRAYKEY)?JSON.parse(Ae.localStorage.getItem(this.GRAYKEY)):{};this.grayConfig.timeStamp=(new Date).getTime(),u[t]=this.grayConfig,Ae.localStorage.setItem(this.GRAYKEY,JSON.stringify(u))}else this.logger.log("uploadFile:: result grayConfig:",m.content)}(null===(a=this.grayConfig)||void 0===a?void 0:a.mixStoreEnable)&&(yield this._getMixStorePolicy(t))}))}_getMixStorePolicy(t){return __awaiter(this,void 0,void 0,(function*(){var o=(new Date).getTime();if(Ae.localStorage)try{if(this.mixStorePolicy=JSON.parse(Ae.localStorage.getItem(this.MIXSTOREKEY))[t],this.curProvider=parseInt(this.mixStorePolicy.providers[0]),this.mixStorePolicy.timeStamp&&this.mixStorePolicy.timeStamp+1e3*this.mixStorePolicy.ttl>o){var a=this.mixStorePolicy.timeStamp+1e3*this.mixStorePolicy.ttl-o;this.core.timerManager.addTimer(this._getMixStorePolicy.bind(this,t),a)}}catch(o){Ae.localStorage.getItem(this.MIXSTOREKEY)&&JSON.parse(Ae.localStorage.getItem(this.MIXSTOREKEY))[t]&&this.core.logger.error("uploadFile:: JSON.parse mixStorePolicy error ",o)}if(!this.mixStorePolicy||this.mixStorePolicy.timeStamp+1e3*this.mixStorePolicy.ttl<=o)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 u=Ae.localStorage.getItem(this.MIXSTOREKEY)?JSON.parse(Ae.localStorage.getItem(this.MIXSTOREKEY)):{};this.mixStorePolicy.timeStamp=(new Date).getTime(),u[t]=this.mixStorePolicy,Ae.localStorage.setItem(this.MIXSTOREKEY,JSON.stringify(u))}catch(o){if(this.logger.error("getMixStorePolicy error",o),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,o=t[(t.indexOf(String(this.curProvider))+1)%t.length];if(!o)throw new Error("uploadFile nextProvider error");if(o===t[0])throw new Error("uploadFile all policy fail");if(this.logger.log(`uploadFile:: upload policy will change,now policy:${this.curProvider} nextProvider:${o}`),this.curProvider=parseInt(o),this.mixStorePolicy.nosPolicy&&this.mixStorePolicy.s3Policy){var a=this.mixStorePolicy[1===this.curProvider?"nosPolicy":"s3Policy"].uploadConfig.retryPolicy.circuit;if(!a||0===a)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*a)}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 ii=-1;class AWS{constructor(t,o){this.s3=null,this.core=t,this.cloudStorage=o,this.logger=t.logger}get mixStorePolicy(){return this.cloudStorage.mixStorage.mixStorePolicy}s3Upload(t,o){return __awaiter(this,void 0,void 0,(function*(){var a;if(ii+=1,t.file)a=t.file;else if("string"==typeof t.fileInput){this.logger.warn("fileInput will abandon,Please use file or filepath");var m=document.getElementById(t.fileInput);if(!(m&&m.files&&m.files[0]))throw new Error("Can not get file from fileInput");a=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}`);a=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},h=this.s3,g=decodeURIComponent(o.bucket),I=decodeURIComponent(o.objectName),M=a,_=`https://${g}.s3.amazonaws.com/${I}`,E={},S=this.mixStorePolicy.s3Policy;if(S&&S.uploadConfig&&Array.isArray(S.uploadConfig.uploadUrl)&&S.uploadConfig.uploadUrl.length>0){var T=S.uploadConfig.uploadUrl.length;ii%=T,E.endpoint=S.uploadConfig.uploadUrl[ii],E.s3ForcePathStyle=!0,_=`${E.endpoint}/${g}/${I}`}this.core.reporterHookCloudStorage.update({remote_addr:_,operation_type:1});var C=new h(E);C.config.update(u);var N={Bucket:g,Key:I,Body:M,Metadata:{token:o.token},ContentType:M.type||"application/octet-stream"};this.core.logger.log("uploadFile:: s3 upload params:",N);var A=C.upload(N);return A.on("httpUploadProgress",(o=>{var a=parseFloat((o.loaded/o.total).toFixed(2));t.onUploadProgress&&t.onUploadProgress({total:o.total,loaded:o.loaded,percentage:a,percentageText:Math.round(100*a)+"%"})})),new Promise(((a,m)=>{var u=(new Date).getTime();A.send(((h,_)=>__awaiter(this,void 0,void 0,(function*(){var E,S,T;if(h&&"RequestAbortedError"===h.code)this.logger.error("uploadFile:","api::s3:upload file abort.",h),m(new UploadError({code:"v2"===get(this.core,"options.apiVersion")?Me.V2NIM_ERROR_CODE_CANCELLED:400,detail:{reason:"S3RequestAbortedError",rawError:h,curProvider:2}}));else{if(!h){var C=this.mixStorePolicy.s3Policy.cdnSchema;C=(C=C.replace("{cdnDomain}",this.mixStorePolicy.s3Policy.dlcdn)).replace("{objectName}",_.Key);var N={size:M.size,name:M.name,url:o.shortUrl?o.shortUrl:C,ext:M.name.split(".")[1]||"unknown"},A=t.type||"",O={image:"imageInfo"};return a(O[A]?yield this.getS3FileInfo({url:C,infoSuffix:O[A],s3Result:N}):N)}this.logger.error("uploadFile:","api::s3:upload file failed.",h),this.core.reporter.reportTraceStart("exceptions",{user_id:this.core.options.account||(null===(S=null===(E=this.core)||void 0===E?void 0:E.auth)||void 0===S?void 0:S.account),trace_id:null===(T=this.core.clientSocket.socket)||void 0===T?void 0:T.sessionId,start_time:u,action:1,exception_service:4}),this.core.reporter.reportTraceUpdateV2("exceptions",{code:"number"==typeof h.status?h.status:"number"==typeof h.code?h.code:0,description:h.message||`${h.code}`,operation_type:1,target:JSON.stringify({bucket:g,object:I})},{asyncParams:Ae.net.getNetworkStatus()}),this.core.reporter.reportTraceEnd("exceptions",1);var{net_connect:R}=yield Ae.net.getNetworkStatus();if(!1===R)return m(new UploadError({code:"v2"===get(this.core,"options.apiVersion")?Me.V2NIM_ERROR_CODE_FILE_UPLOAD_FAILED:400,detail:{reason:"No network",rawError:h,curProvider:this.cloudStorage.mixStorage.curProvider}}));try{this.cloudStorage.mixStorage._addCircuitTimer()}catch(o){return m(new UploadError({code:"v2"===get(this.core,"options.apiVersion")?Me.V2NIM_ERROR_CODE_FILE_UPLOAD_FAILED:400,detail:{reason:"All upload attempts failed",rawError:o,curProvider:this.cloudStorage.mixStorage.curProvider,mixStorePolicy:this.mixStorePolicy,file:t.file||t.filePath}}))}a(this.cloudStorage._uploadFile(t))}})))),t.onUploadStart&&t.onUploadStart(A)}))}))}getS3FileInfo(t){var o;return __awaiter(this,void 0,void 0,(function*(){var a,{url:m,infoSuffix:u,s3Result:h}=t;try{a=yield this.core.adapters.request(`${m}?${u}`,{method:"GET",dataType:"text",timeout:5e3},{exception_service:3})}catch(t){return this.core.logger.error("uploadFile:: fetch file info error",t),h}if(a){var{data:g}=a,I="imageInfo"===u?g:null===(o=null==g?void 0:g.GetVideoInfo)||void 0===o?void 0:o.VideoInfo;return pickBy(Object.assign(Object.assign({},h),{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}?${u}`),h}))}}class CloudStorageService{constructor(t,o={}){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:ei,cmdConfig:ri}),this.setOptions(o),this.setListeners()}setOptions(t={}){var o=t.storageKeyPrefix||"NIMClient";this.mixStorage.GRAYKEY=o+"-AllGrayscaleConfig",this.mixStorage.MIXSTOREKEY=o+"-AllMixStorePolicy";var{s3:a}=t,m=__rest(t,["s3"]),u=Object.assign({},Zr,this.config);if(m&&Object.prototype.hasOwnProperty.call(m,"cdn")){var h=Object.assign(Object.assign({},u.cdn),m.cdn);this.config=Object.assign({},u,m),this.config.cdn=h}else this.config=Object.assign({},u,m);a&&(this.aws.s3=a)}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 o=this.uploadTaskMap[t];o&&o.abort&&o.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,o){var a=t.onUploadProgress,m=t.onUploadDone,u=t.onUploadStart;return{onUploadStart:"function"==typeof u?t=>{this.uploadTaskMap[o]=t;try{u(t)}catch(t){this.logger.error("CloudStorage::uploadFile:options.onUploadStart execute error",t)}}:t=>{this.uploadTaskMap[o]=t},onUploadProgress:"function"==typeof a?t=>{this.core.reporterHookCloudStorage.update({transferred_size:t.loaded,full_size:t.total});try{a(t)}catch(t){this.logger.error("CloudStorage::uploadFile:options.onUploadProgress execute error",t)}}:t=>{this.core.reporterHookCloudStorage.update({transferred_size:t.loaded,full_size:t.total})},onUploadDone:"function"==typeof m?t=>{this.core.reporterHookCloudStorage.end(0);try{m(t)}catch(t){this.logger.error("CloudStorage::uploadFile:options.onUploadDone execute error",t)}}:()=>{this.core.reporterHookCloudStorage.end(0)},taskKey:o}}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 o=get(t,"file.type");if(o&&"string"==typeof o&&-1===o.indexOf(t.type))throw new Error(`The meta type "${o}" does not match "${t.type}"`)}if(this.core.reporterHookCloudStorage.start(),t.file)this.core.reporterHookCloudStorage.update({full_size:t.file.size});else if("string"==typeof t.fileInput){var a=document.getElementById(t.fileInput);a&&a.files&&a.files[0]&&this.core.reporterHookCloudStorage.update({full_size:a.files[0].size})}else t.fileInput&&t.fileInput.files&&t.fileInput.files[0]&&this.core.reporterHookCloudStorage.update({full_size:t.fileInput.files[0].size});var m=Ve(),{onUploadStart:u,onUploadProgress:h,onUploadDone:g}=this.processCallback(t,m);t.onUploadStart=u,t.onUploadProgress=h,t.onUploadDone=g;var I=null;try{I=yield this._uploadFile(t),t.md5&&(I.md5=t.md5),delete this.uploadTaskMap[m]}catch(t){throw delete this.uploadTaskMap[m],this.core.reporterHookCloudStorage.end((t&&t.code)===Me.V2NIM_ERROR_CODE_CANCELLED?3:1),t}return I&&(I.size=void 0===I.size?void 0:Number(I.size),I.w=void 0===I.w?void 0:Number(I.w),I.h=void 0===I.h?void 0:Number(I.h),I.dur=void 0===I.dur?void 0:Number(I.dur)),I.url=decodeURIComponent(I.url),t.onUploadDone({size:I.size,name:I.name,url:I.url,ext:I.name.split(".")[1]||"unknown"}),I}))}_uploadFile(t){var o,a;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);this.logger.log(`uploadFile::_uploadFile, grayConfig enable:${get(this.mixStorage,"grayConfig.mixStoreEnable")} curProvider:${get(this.mixStorage,"curProvider")}`);var m=this.core.adapters.getFileUploadInformation(t),u=!0;m?!1===m.complete&&2===this.mixStorage.curProvider&&(u=!1):u=!1,this.aws.s3||(this.mixStorage.curProvider=1);var h=Qr;if(!u)try{h=(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),t instanceof V2NIMErrorImpl)throw t;throw new UploadError({code:"v2"===get(this.core,"options.apiVersion")?Me.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,null===(a=null===(o=null==m?void 0:m.uploadInfo)||void 0===o?void 0:o.payload)||void 0===a?void 0:a.mixStoreToken):2===this.mixStorage.curProvider?this.aws.s3Upload(t,h):this.nos.nosUpload(t,h)}))}getThumbUrl(t,o){var a,m,u,h,g;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===(a=this.grayConfig)||void 0===a?void 0:a.mixStoreEnable){var A=this._getUrlType(t);if(2===A&&this.mixStorePolicy.s3Policy&&get(this.mixStorePolicy,"s3Policy.thumbPolicy.imagethumb"))return(null===(u=null===(m=this.mixStorePolicy.s3Policy)||void 0===m?void 0:m.thumbPolicy)||void 0===u?void 0:u.imagethumb).replace("{cdnDomain}",this.mixStorePolicy.s3Policy.dlcdn).replace("{objectName}",T).replace("{x}",o.width.toString()).replace("{y}",o.height.toString());if(1===A&&this.mixStorePolicy.nosPolicy&&get(this.mixStorePolicy,"nosPolicy.thumbPolicy.imagethumb"))return(null===(g=null===(h=this.mixStorePolicy.nosPolicy)||void 0===h?void 0:h.thumbPolicy)||void 0===g?void 0:g.imagethumb).replace("{cdnDomain}",this.mixStorePolicy.nosPolicy.dlcdn).replace("{objectName}",T).replace("{x}",o.width.toString()).replace("{y}",o.height.toString())}return t.includes("?")?t+`&imageView&thumbnail=${o.width}x${o.height}`:t+`?imageView&thumbnail=${o.width}x${o.height}`}getVideoCoverUrl(t,o){var a,m,u,h,g;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===(a=this.grayConfig)||void 0===a?void 0:a.mixStoreEnable){var A=this._getUrlType(t);if(2===A&&this.mixStorePolicy.s3Policy&&get(this.mixStorePolicy,"s3Policy.thumbPolicy.vframe"))return(null===(u=null===(m=this.mixStorePolicy.s3Policy)||void 0===m?void 0:m.thumbPolicy)||void 0===u?void 0:u.vframe).replace("{cdnDomain}",this.mixStorePolicy.s3Policy.dlcdn).replace("{objectName}",T).replace("{x}",o.width.toString()).replace("{y}",o.height.toString()).replace("{offset}","0").replace("{type}","png");if(1===A&&this.mixStorePolicy.nosPolicy&&get(this.mixStorePolicy,"nosPolicy.thumbPolicy.vframe"))return(null===(g=null===(h=this.mixStorePolicy.nosPolicy)||void 0===h?void 0:h.thumbPolicy)||void 0===g?void 0:g.vframe).replace("{cdnDomain}",this.mixStorePolicy.nosPolicy.dlcdn).replace("{objectName}",T).replace("{x}",o.width.toString()).replace("{y}",o.height.toString()).replace("{offset}","0").replace("{type}","png")}return t.includes("?")?t+`&vframe&offset=0&resize=${o.width}x${o.height}&type=png`:t+`?vframe&offset=0&resize=${o.width}x${o.height}&type=png`}getPrivateUrl(t){var o;if(!new RegExp(/http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- ./?%&=]*)?/).test(t))return this.logger.error("illegal file url:"+t),"";var[a,m,u,h,g,I,M,_]=/^(?:([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 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}${N}/${O.slice(R)}`;if(T.includes(h)&&I.includes("/")){var b=I.indexOf("/"),V=I.substring(0,b),k=I.substring(b+1);return S.replace("{bucket}",V).replace("{object}",k)}var P=T.filter((t=>"string"==typeof h&&h.includes(t)))[0],L=P?h.replace(P,"").replace(/\W/g,""):null;return L?S.replace("{bucket}",L).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 o=this.mixStorePolicy.nosPolicy?this.mixStorePolicy.nosPolicy.authPolicy.policyType:null,a=this.mixStorePolicy.s3Policy?this.mixStorePolicy.s3Policy.authPolicy.policyType:null;if(o===String(-1)&&a===String(-1))throw this.logger.error("don't need token"),new Error("don't need token");if(2===t.type){if(o&&o.indexOf(String(2))>=0||a&&a.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=[],u=[];if(t.urls.forEach((t=>{var o=this._getUrlType(t);1===o&&u.push(t),2===o&&m.push(t)})),(!a||0!==m.length&&a.indexOf(String(3))<0)&&(this.logger.warn("s3 url don't support url token"),m=[]),(!o||0!==u.length&&o.indexOf(String(3))<0)&&(this.logger.warn("nos url don't support url token"),u=[]),0===m.length&&0===u.length)throw this.logger.error("not support urls"),new Error("not support urls");if(0===m.length||0===u.length)return t.urls=JSON.stringify(t.urls),this.mixStorage.getFileAuthToken(t)}))}_getUrlType(t){return this.mixStorePolicy.nosPolicy&&this.mixStorePolicy.nosPolicy.dlcdns.some((o=>t.indexOf(o)>=0))?1:this.mixStorePolicy.s3Policy&&this.mixStorePolicy.s3Policy.dlcdns.some((o=>t.indexOf(o)>=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 o=get(t,"error.detail.ignore");return t.error&&!o?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,o){return this.checkV2(),validate({sceneName:{type:"string",allowEmpty:!1},expireTime:{type:"number",min:0}},{sceneName:t,expireTime:o},"",!0),this.sceneMap[t]={sceneName:t,expireTime:o},{sceneName:t,expireTime:o}}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 o=document.getElementById(t.fileObj);o&&o.files&&o.files[0]&&(t.fileObj=o.files[0])}return{taskId:Ve(),uploadParams:t}}uploadFile(t,o){return __awaiter(this,void 0,void 0,(function*(){return this.checkV2(),validate({taskId:{type:"string",allowEmpty:!1}},t,"fileTask",!0),(yield this._uploadFile(t,o))[0]}))}uploadFileWithMetaInfo(t,o){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:o,name:a,size:m,ext:u,md5:h,h:g,w:I,orientation:M,dur:_,audioCodec:E,videoCodec:S,container:T}=t;return JSON.parse(JSON.stringify({url:o,name:a,size:m,ext:u,md5:h,height:g,width:I,orientation:M,duration:_,audioCodec:E,videoCodec:S,container:T}))}((yield this._uploadFile(t,o))[1])}))}_uploadFile(t,o,a){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:u,taskId:h}=t,{file:g,path:I}=getFileOrPath(u.fileObj),{fileType:M}=a||{};if(this.uploadingMessageInfo[h])throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_RESOURCE_ALREADY_EXIST,detail:{reason:"V2NIMStorageService.uploadFile: repeat upload"}});try{var _={};g?_.file=g:I&&(0===(null==I?void 0:I.indexOf("nim-external"))?_.fileInput=I:_.filePath=I);var E=this.getStorageScene(u.sceneName);if(_.nosScenes=E.sceneName,_.nosSurvivalTime=E.expireTime,_.type=1===M?"image":2===M?"audio":3===M?"video":"file",_.file&&this.core.pluginMap["browser-md5-file"]){var S=yield this.getFileMd5(this.core.pluginMap["browser-md5-file"],h,_.file);_.md5=S}_.onUploadProgress=t=>{"function"==typeof o&&o(Math.round(100*t.percentage))},_.onUploadStart=t=>{var o;if(null===(o=this.uploadingMessageInfo[h])||void 0===o?void 0:o.abort)return t.abort(),void delete this.uploadingMessageInfo[h];this.uploadingMessageInfo[h]={abort:!1,task:t}},this.uploadingMessageInfo[h]={abort:!1};var T=yield this.core.cloudStorage.uploadFile(_);if(null===(m=this.uploadingMessageInfo[h])||void 0===m?void 0:m.abort)throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_CANCELLED,detail:{reason:"upload file aborted"}});return delete this.uploadingMessageInfo[h],[T.url,T]}catch(t){throw delete this.uploadingMessageInfo[h],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 o=this.uploadingMessageInfo[t];if(null==o?void 0:o.task)try{this.logger.log("V2NIMStorageService.cancelUploadFile: uploadInfo task exist"),yield o.task.abort(),delete this.uploadingMessageInfo[t]}catch(o){delete this.uploadingMessageInfo[t],this.core.logger.error("cancelMessageAttachmentUpload::abort error.",o)}else{if(!o)throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_RESOURCE_NOT_EXIST,detail:{reason:"V2NIMStorageService.cancelUploadFile: uploadInfo not exist"}});this.logger.log("V2NIMStorageService.cancelUploadFile: uploadInfo task not exist"),o.abort=!0}}))}getFileMd5(t,o,a){return __awaiter(this,void 0,void 0,(function*(){return new Promise(((m,u)=>{var h,g=new t;(null===(h=this.uploadingMessageInfo[o])||void 0===h?void 0:h.abort)?u(new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_CANCELLED,detail:{reason:"upload file aborted"}})):this.uploadingMessageInfo[o]={abort:!1,task:g};try{g.md5(a,((t,o)=>{"aborted"===t?u(new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_CANCELLED,detail:{reason:t}})):t?u(new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_INTERNAL,detail:{reason:"md5 calculate error in callback",rawError:t}})):m(o)}))}catch(t){u(new V2NIMErrorImpl({code:Me.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,o){return __awaiter(this,void 0,void 0,(function*(){return this.core.V2NIMStorageUtil.getImageThumbUrl(t,o)}))}getVideoCoverUrl(t,o){return __awaiter(this,void 0,void 0,(function*(){return this.core.V2NIMStorageUtil.getVideoCoverUrl(t,o)}))}}class V2NIMMessageCreatorImpl extends V2Service{constructor(t){super("V2NIMMessageCreator",t),this.name="V2NIMMessageCreator",this.defaultNosSceneName="nim_default_im",this.core=t}createMessage(t,o){return Object.assign(Object.assign(Object.assign({messageClientId:Ve(),messageType:t,createTime:this.core.timeOrigin.getNTPTime(),sendingState:0,messageStatus:{errorCode:200},messageSource:0,isSelf:!0},o),o.attachment?{attachment:Object.assign(Object.assign({},o.attachment),{raw:attachmentToRaw(t,o.attachment)})}:{}),{senderId:"",receiverId:"",conversationType:0,conversationId:"",messageServerId:"",messageConfig:Object.assign({unreadEnabled:!0,roamingEnabled:!0,readReceiptEnabled:!1,lastMessageUpdateEnabled:!0,historyEnabled:!0,onlineSyncEnabled:!0,offlineEnabled:!0},o.messageConfig),pushConfig:Object.assign({pushEnabled:!0,pushNickEnabled:!0,forcePush:!1},o.pushConfig),routeConfig:Object.assign({routeEnabled:!0},o.routeConfig),antispamConfig:Object.assign({antispamEnabled:!0},o.antispamConfig)})}createTextMessage(t){return this.checkV2(),validate({text:{type:"string",allowEmpty:!1}},{text:t},"",!0),this.createMessage(0,{text:t})}createImageMessage(t,o,a,m,u){this.checkV2(),validate(gr,{name:o,sceneName:a,width:m,height:u},"",!0);var h=this.createGenericFileMessageAttachment(t,o,a,void 0,m,u,"jpeg");return this.createMessage(1,{attachment:h,attachmentUploadState:0})}createAudioMessage(t,o,a,m){this.checkV2(),validate(ur,{name:o,sceneName:a,duration:m},"",!0);var u=this.createGenericFileMessageAttachment(t,o,a,m,void 0,void 0,"aac");return this.createMessage(2,{attachment:u,attachmentUploadState:0})}createVideoMessage(t,o,a,m,u,h){this.checkV2(),validate(hr,{name:o,sceneName:a,duration:m,width:u,height:h},"",!0);var g=this.createGenericFileMessageAttachment(t,o,a,m,u,h,"mp4");return this.createMessage(3,{attachment:g,attachmentUploadState:0})}createFileMessage(t,o,a){this.checkV2(),validate(mr,{name:o,sceneName:a},"",!0);var m=this.createGenericFileMessageAttachment(t,o,a,void 0,void 0,void 0,"txt");return this.createMessage(6,{attachment:m,attachmentUploadState:0})}createGenericFileMessageAttachment(t,o,a,m,u,h,g){if(a=a||this.defaultNosSceneName,!this.core.V2NIMStorageService.hasStorageScene)throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_MISUSE,detail:{reason:"V2NIMStorageService not exist"}});if(!this.core.V2NIMStorageService.hasStorageScene(a))throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"sceneName: "+a+" has not been added"}});var{file:I,path:M}=getFileOrPath(t),_=Object.assign(Object.assign(Object.assign({name:o,uploadState:0,sceneName:a||this.defaultNosSceneName},m?{duration:m}:{}),u?{width:u}:{}),h?{height:h}:{});if(I){var E=I.name.lastIndexOf("."),S=-1===E?I.name:I.name.substring(0,E);_.name=_.name||S,_.size=I.size,_.ext=`.${getFileExtension(I.name)||getFileExtension(o||"")||g}`}else if(M){var T=M.lastIndexOf("/"),C=M.lastIndexOf("."),N=-1===C?M.substring(T+1):M.substring(T+1,C);_.name=_.name||N,_.ext=`.${getFileExtension(M)||getFileExtension(o||"")||g}`}return _=JSON.parse(JSON.stringify(_)),M?_.path=M:I&&(_.file=I),_}createLocationMessage(t,o,a){return this.checkV2(),validate({latitude:{type:"number",allowEmpty:!1},longitude:{type:"number",allowEmpty:!1},address:{type:"string",allowEmpty:!1}},{latitude:t,longitude:o,address:a},"",!0),this.createMessage(4,{attachment:{latitude:t,longitude:o,address:a}})}createCustomMessage(t,o){return this.checkV2(),validate({text:{type:"string"}},{text:t},"",!0),validate({rawAttachment:{type:"string"}},{rawAttachment:o},"",!0),this.createMessage(100,{text:t,attachment:{raw:o}})}createCustomMessageWithAttachment(t,o){return this.checkV2(),validate({raw:{type:"string"}},t,"attachment",!0),validate({subType:{type:"number",min:0,required:!1}},{subType:o},"",!0),this.createMessage(100,o?{attachment:t,subType:o}:{attachment:t})}createCallMessage(t,o,a,m,u){return this.checkV2(),validate({type:{type:"number",allowEmpty:!1}},{type:t},"",!0),validate({channelId:{type:"string",allowEmpty:!1}},{channelId:o},"",!0),validate({status:{type:"number",allowEmpty:!1}},{status:a},"",!0),validate({durations:{type:"array",allowEmpty:!1}},{durations:m},"",!0),this.createMessage(12,{text:u||"",attachment:{type:t,channelId:o,durations:m,status:a}})}createForwardMessage(t){this.checkV2();if(!t||[11,5,7,10].includes(t.messageType))return null;var o={messageClientId:Ve(),messageType:t.messageType};return t.text&&(o.text=t.text),t.attachment&&(o.attachment=t.attachment),t.attachment&&"uploadState"in t.attachment&&(o.attachmentUploadState=t.attachment.uploadState),this.createMessage(t.messageType,o)}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,o,a){return{latitude:"number"==typeof t?t:0,longitude:"number"==typeof o?o:0,address:"string"==typeof a?a:""}}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,o="**"){if(!this.config.enable)return{operateType:0,replacedText:t};if(validate({text:{type:"string",required:!0,allowEmpty:!1},replace:{type:"string"}},{text:t,replace:o},"",!0),!this.vocabInfo)return{operateType:0,replacedText:t};for(var a=t,m=0;m<this.vocabInfo.thesaurus.length;m++){var u=this.filterContent(a,this.vocabInfo.thesaurus[m],o);if(a=u.replacedText,2===u.operateType||3===u.operateType)return u}return{operateType:a===t?0:1,replacedText:a}}filterContent(t,o,a){for(var m=0;m<o.keys.length;m++){var u=o.keys[m],h=u.match||o.match,g=u.operate||o.operate,I=void 0;try{I=this.matchContent(t,u.key,h,g,a)}catch(t){}if(I&&(t=I.replacedText,2===I.operateType||3===I.operateType))return I}return{operateType:1,replacedText:t}}matchContent(t,o,a,m,u){var h=!1,g=null;if(1===a){if(t.indexOf(o)>=0){h=!0;var I=o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");g=new RegExp(I,"g")}}else 2===a&&(g=new RegExp(o,"g")).test(t)&&(h=!0);if(h&&g)switch(m){case 1:return{operateType:1,replacedText:t.replace(g,u)};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:Hr,cmdConfig:zr})}emit(t,...o){var a,m=`${this.name}::emit ${t.toString()}`;if("onSendMessage"===t){var u=o[0];this.logger.log(`${m}`,`${u.messageClientId}/${u.messageServerId};createTime:${u.createTime};`,`sendingState:${u.sendingState};attachmentUploadState:${u.attachmentUploadState||0};messageStatus:${null===(a=u.messageStatus)||void 0===a?void 0:a.errorCode}`)}else if("onReceiveMessages"===t){var h=o[0];this.logger.log(`${m}`,h.map((t=>`${t.messageClientId}/${t.messageServerId};createTime:${t.createTime}`)))}else if("onReceiveCustomNotifications"===t){var g=o[0];this.logger.log(`${m}`,g.map((t=>`sender:${t.senderId};receiver:${t.receiverId};ctype:${t.conversationType};time:${t.timestamp}`)))}else this.logger.log(`${m}`,...o);return super.emit(t,...o)}sendMessage(t,o,a={},m){return __awaiter(this,void 0,void 0,(function*(){validate({message:{type:"object"}},{message:t},"",!0),t.messageClientId=t.messageClientId||Ve(),validate(qt,{conversationId:o,message:t,params:a},"",!0),validateConversationId(this.core.account,o);var u=this.core.timeOrigin.getTimeNode(),{messageBeforeSend:h,clientAntispamResult:g,hiddenParams:I}=this.sendUtil.prepareMessage(t,o,a),M=yield this.sendUtil.doSendMessage({apiCallingTimeNode:u,messageBeforeSend:h,clientAntispamResult:g,hiddenParams:I,progress:m});return M.message.senderId===M.message.receiverId&&this.markMsgsAck([M.message]),M}))}sendCustomNotification(t,o,a){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validateConversationId(this.core.account,t),validate(Yr,{content:o,params:a},"",!0);var m=this.notificationUtil.generateNotificationTag(t,o,a);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 o=t.map((t=>t.messageServerId)).filter((t=>t&&"0"!==t));0!==o.length&&this.core.sendCmd("ysfBatchMarkRead",{sid:101,cid:2,ids:o})}}markNotificationAck(t){if(t&&t.length>0){var o=t.map((t=>t.idServer)).filter((t=>t&&"0"!==t));0!==o.length&&this.core.sendCmd("ysfBatchMarkRead",{sid:101,cid:3,ids:o})}}ysfOnMsgHandler(t){var o=fillIdServer(t,t.content.data,"messageServerId"),a=completeMessage(this.core,o);delete a.__clientExt,this.emit("onReceiveMessages",[a]),this.model.upsertMessages([a]),this.markMsgsAck([a])}ysfSyncOfflineMsgsHandler(t){var o=t.content.datas;o=o.map((t=>completeMessage(this.core,t))),this.markMsgsAck(o),this.emit("onReceiveMessages",o),this.model.upsertMessages(o)}ysfOnSysNotificationHandler(t){var o=fillIdServer(t,t.content.data,"idServer");this.markNotificationAck([o]);var a=this.processSystemNotification(o);a&&this.emit("onReceiveCustomNotifications",[a])}processSystemNotification(t){var o=Object.assign(Object.assign({},t),{conversationType:1});return delete o.type,o}ysfSyncSysNotificationHandler(t){this.markNotificationAck(t.content.datas);var o=t.content.datas.sort(((t,o)=>t.timestamp-o.timestamp)).map((t=>this.processSystemNotification(t))).filter((t=>t));o&&this.emit("onReceiveCustomNotifications",o)}}class SendUtil{constructor(t,o){this.uploadingMessageInfo={},this.core=t,this.service=o}prepareMessage(t,o,a,m){var u=this.checkIfResend(t),h=this.generateSendMessage({message:t,params:a,resend:u,conversationId:o,replyMessage:m}),g=Object.assign({},a.targetConfig?{targetConfig:a.targetConfig}:{}),{clientAntispamResult:I,text:M}=this.checkIfAntispam(a,h);return h.text=M,h.clientAntispamHit=!!I&&3===I.operateType,{messageBeforeSend:h,clientAntispamResult:I,hiddenParams:g}}checkIfAntispam(t,o){var a,m=o.text;if(t.clientAntispamEnabled&&(0===o.messageType||10===o.messageType))if(1===(a=this.core.V2NIMClientAntispamUtil.checkTextAntispam?this.core.V2NIMClientAntispamUtil.checkTextAntispam(o.text||"",t.clientAntispamReplace):{operateType:0,replacedText:""}).operateType)m=a.replacedText;else if(2===a.operateType)throw this.service.emit("onSendMessage",Object.assign(Object.assign({},o),{sendingState:2,messageStatus:{errorCode:Me.V2NIM_ERROR_CODE_CLIENT_ANTISPAM}})),new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_CLIENT_ANTISPAM,detail:{reason:"sendMessage: text intercepted by client antispam"}});return{clientAntispamResult:a,text:m}}doMsgReceiveReport(t,o){if(t.senderId!==this.core.account){var a=get(t,"__clientExt.statistics.apiCallingTime")||0,m=get(t,"__clientExt.statistics.sendTime")||0,u=get(t,"__clientExt.statistics.attachUploadDuration")||0,h=this.core.timeOrigin.getNTPTime(),g=t.createTime,I=this.core.timeOrigin.checkNodeReliable(o.__receiveTimeNode)?this.core.timeOrigin.getNTPTime(o.__receiveTimeNode):h;this.core.reporter.report("msgReceive",{msgId:t.messageServerId,clientId:t.messageClientId,serverTime:t.createTime,receiveTime:I,fromAccid:1===t.conversationType?t.senderId:"",toAccid:t.receiverId,type:conversationTypeV2ToV1(t.conversationType),tid:1===t.conversationType?"":t.receiverId,apiCallingTime:a,sendTime:m,attachUploadDuration:u,callbackTime:h,preHandleTime:h,result:200,failReason:"",rt:h-g})}}checkIfResend(t){var o=this.service.model.getMessageById(t.messageClientId),a=!1;if("messageServerId"in t&&"0"!==t.messageServerId&&""!==t.messageServerId)throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"sendMessage: message has already been sent"}});if(o&&"messageServerId"in o&&"0"!==o.messageServerId&&""!==o.messageServerId)throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"sendMessage: message has already been sent"}});return o&&(a=!0),a}doSendMessage(t){var o;return __awaiter(this,void 0,void 0,(function*(){var a,m,{apiCallingTimeNode:u,messageBeforeSend:h,clientAntispamResult:g,hiddenParams:I,progress:M}=t,_={},E=this.service instanceof YSFServiceImpl;if(E)a="ysfSendMessage";else if(1===h.conversationType)a="v2SendP2pMessage";else if(2===h.conversationType)a="v2SendTeamMessage";else{if(3!==h.conversationType)throw new ValidateErrorV2({detail:{reason:`conversationType: ${h.conversationType} is not supported`}});a="v2SendSuperTeamMessage"}if(this.service.sendMessageFn(h),!E&&this.core.eventBus.emit("forwardSend/V2NIMMessageService/sendMsg",h),!h.attachment||!("uploadState"in h.attachment)||h.attachment.url||0!==h.attachment.uploadState&&2!==h.attachment.uploadState)this.service.emit("onSendMessage",h);else{var S=Date.now();try{h.attachmentUploadState=3,h.attachment.uploadState=3,this.service.emit("onSendMessage",h),yield this.service.fileUtil.doSendFile(h,M),h.attachmentUploadState=1,h.attachment.uploadState=1,this.service.emit("onSendMessage",h)}catch(t){throw h.attachmentUploadState=2,h.attachment.uploadState=2,h.sendingState=2,h.messageStatus={errorCode:t.code||Me.V2NIM_ERROR_CODE_UNKNOWN},this.service.emit("onSendMessage",h),_.attachUploadDuration=Date.now()-S,this.doSendMessageFailed(u,_,h,t),t}_.attachUploadDuration=Date.now()-S}this.core.timeOrigin.checkNodeReliable(u)&&(_.apiCallingTime=this.core.timeOrigin.getNTPTime(u),_.sendTime=this.core.timeOrigin.getNTPTime(),h.__clientExt={statistics:_});try{m=yield this.core.sendCmd(a,{tag:Object.assign({},h,I)})}catch(t){throw this.doSendMessageFailed(u,_,h,t),h.sendingState=2,h.messageStatus={errorCode:t.code||Me.V2NIM_ERROR_CODE_UNKNOWN},this.service.emit("onSendMessage",h),t}var T=get(m,"content.data.errorCode"),C=Object.assign(Object.assign(Object.assign(Object.assign({},h),m.content.data),h.aiConfig?{aiConfig:Object.assign(Object.assign({},h.aiConfig),(null===(o=m.content.data)||void 0===o?void 0:o.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(u,_,h);var N=C.antispamResult;return N&&(C.messageStatus.errorCode=Me.V2NIM_ERROR_CODE_SERVER_ANTISPAM),delete C.antispamResult,this.service.emit("onSendMessage",C),Object.assign(Object.assign({message:C},N?{antispamResult:N}:{}),g?{clientAntispamResult:g}:{})}))}doSendMessageFailed(t,o,a,m){var u=Object.assign(Object.assign({},a),{sendingState:2});this.core.eventBus.emit("forwardSend/V2NIMMessageService/sendMsg",u),this.service.sendMessageFn(u),this.doMsgSendReport(t,o,a,m)}doMsgSendReport(t,o,a,m){o.apiCallingTime=this.core.timeOrigin.getNTPTime(t),o.sendTime=this.core.timeOrigin.getNTPTime();var u=this.core.timeOrigin.getNTPTime(),h=get(m,"detail.reason");this.core.reporter.report("msgSend",{msgId:a.messageServerId,clientId:a.messageClientId,msgTime:a.createTime,fromAccid:1===a.conversationType?a.senderId:"",toAccid:a.receiverId,type:conversationTypeV2ToV1(a.conversationType),tid:1===a.conversationType?"":a.receiverId,result:m?m.code:200,failReason:h||(null==m?void 0:m.message)||"",rt:u-o.apiCallingTime,apiCallingTime:o.apiCallingTime,sendTime:o.sendTime,attachUploadDuration:o.attachUploadDuration,apiCallbackTime:u})}generateSendMessage(t){var o,a,{conversationId:m,replyMessage:u,resend:h,message:g,params:I}=t,M={};if(u){var _=u.threadRoot;M={threadReply:{senderId:u.senderId,receiverId:u.receiverId,messageServerId:u.messageServerId,createTime:u.createTime,messageClientId:u.messageClientId,conversationType:u.conversationType,conversationId:u.conversationId},threadRoot:{senderId:_?_.senderId:u.senderId,receiverId:_?_.receiverId:u.receiverId,messageServerId:_?_.messageServerId:u.messageServerId,createTime:_?_.createTime:u.createTime,messageClientId:_?_.messageClientId:u.messageClientId,conversationType:_?_.conversationType:u.conversationType,conversationId:_?_.conversationId:u.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===g.messageType&&(C={msg:g.text||"",type:A}),(T=Object.assign({aiStreamStatus:0,aiStream:!1},I.aiConfig)).aiStatus=1,void 0!==C.msg&&(T.content=C)}var O=null===(a=null===(o=this.core.V2NIMUserService)||void 0===o?void 0:o.model)||void 0===a?void 0:a.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({},g),M),{messageConfig:Object.assign(Object.assign({},g.messageConfig),I.messageConfig),routeConfig:Object.assign(Object.assign({},g.routeConfig),I.routeConfig),pushConfig:Object.assign(Object.assign({},g.pushConfig),I.pushConfig),antispamConfig:Object.assign(Object.assign({},g.antispamConfig),I.antispamConfig),robotConfig:Object.assign(Object.assign({},g.robotConfig),I.robotConfig)}),T&&T.accountId?{aiConfig:T}:{}),g.attachment?{attachment:Object.assign({},g.attachment)}:{}),{resend:h,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,o){this.core=t,this.service=o}checkIfModify(t,o){if("0"===t.messageServerId)throw new V2NIMErrorImpl({code:Me.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:Me.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:`modifyMessage: messageType ${t.messageType} not correct`}});if([0,1,2,3,6,10,12].includes(t.messageType)&&o.attachment)throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:`modifyMessage: messageType ${t.messageType} can not modify attachment`}});var a=["subType","text","serverExtension","attachment"];if(!a.some((t=>void 0!==get(o,t))))throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"modifyMessage: missing modified params"}});if(a.every((a=>"attachment"===a?t.attachment&&o.attachment?attachmentToRaw(t.messageType,t.attachment)===attachmentToRaw(t.messageType,o.attachment):!o.attachment:get(t,a)===get(o,a))))throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"modifyMessage: no change"}})}prepareMessage(t,o){var a=this.generateSendMessage(t,o),{clientAntispamResult:m,text:u}=this.checkIfAntispam(o,a);return a.text=u,a.clientAntispamHit=!!m&&3===m.operateType,{messageBeforeSend:a,clientAntispamResult:m}}modifyMessage(t,o){return __awaiter(this,void 0,void 0,(function*(){var a;if(1===t.conversationType)a="v2MessageP2pModify";else if(2===t.conversationType)a="v2MessageTeamModify";else{if(3!==t.conversationType)throw new ValidateErrorV2({detail:{reason:`conversationType: ${t.conversationType} is not supported`}});a="v2MessageSuperTeamModify"}var m=yield this.core.sendCmd(a,{tag:t});if(o&&3===o.operateType)return{errorCode:Me.V2NIM_ERROR_CODE_CLIENT_ANTISPAM,clientAntispamResult:o};var u=Object.assign(Object.assign({},t),m.content.data),h=u.antispamResult;if(h)return Object.assign({errorCode:Me.V2NIM_ERROR_CODE_SERVER_ANTISPAM,antispamResult:h},o?{clientAntispamResult:o}:{});delete u.antispamResult;var g=completeMessage(this.core,u);return this.service.model.upsertMessages([g]),this.core.eventBus.emit("V2NIMMessageService/modifyMsg",g),this.core.eventBus.emit("forwardSend/V2NIMMessageService/modifyMsg",g),Object.assign(Object.assign({errorCode:200,message:g},h?{antispamResult:h}:{}),o?{clientAntispamResult:o}:{})}))}checkIfAntispam(t,o){var a,m=o.text;if(t.clientAntispamEnabled&&(0===o.messageType||10===o.messageType))if(1===(a=this.core.V2NIMClientAntispamUtil.checkTextAntispam?this.core.V2NIMClientAntispamUtil.checkTextAntispam(o.text||"",t.clientAntispamReplace):{operateType:0,replacedText:""}).operateType)m=a.replacedText;else if(2===a.operateType)throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_CLIENT_ANTISPAM,detail:{reason:"sendMessage: text intercepted by client antispam"}});return{clientAntispamResult:a,text:m}}generateSendMessage(t,o){var a;return Object.assign(Object.assign({messageConfig:{lastMessageUpdateEnabled:null===(a=t.messageConfig)||void 0===a?void 0:a.lastMessageUpdateEnabled},routeConfig:Object.assign({routeEnabled:!0},o.routeConfig),pushConfig:Object.assign({pushEnabled:!0,pushNickEnabled:!0,forcePush:!1},o.pushConfig),antispamConfig:Object.assign({antispamEnabled:!0},o.antispamConfig)},o.attachment?{attachment:o.attachment}:{}),{conversationType:t.conversationType,senderId:t.senderId,receiverId:t.receiverId,createTime:t.createTime,messageClientId:t.messageClientId,messageServerId:t.messageServerId,messageType:t.messageType,subType:o.subType,text:o.text,serverExtension:o.serverExtension})}}class DeleteUtil{constructor(t,o){this.emitRevokeMessage=t=>{var o=t.map((t=>{var o=formatRevokeMessage(this.core,t);return 3===o.messageRefer.conversationType?this.core.eventBus.emit("V2NIMSync/updateTimetag",{deleteSuperTeamMsg:t.createTime}):this.core.eventBus.emit("V2NIMSync/updateTimetag",{recallMsg:t.createTime}),o}));o.forEach((t=>{this.service.model.deleteMessage(t.messageRefer.messageClientId)})),this.service.emit("onMessageRevokeNotifications",o),this.core.eventBus.emit("V2NIMMessageService/revokeMessages",o)},this.core=t,this.service=o,this.logger=t.logger}revokeMessage(t,o){return __awaiter(this,void 0,void 0,(function*(){if(validate(Ht,{message:t,params:o},"",!0),validateConversationId(this.core.account,t.conversationId),1===t.conversationType&&t.senderId!==this.core.account)throw new V2NIMErrorImpl({code:Me.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:Me.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"revokeMessage: cannot revoke message with invalid messageServerId: "+t.messageServerId}});var a=3===t.conversationType?"v2RevokeSuperTeamMessage":"v2RevokeMessage",m={1:7,2:8,3:12},u=Object.assign(Object.assign(Object.assign({},t),o),{attach:o&&o.serverExtension,sysMsgType:m[t.conversationType],opeAccount:this.core.account});yield this.core.sendCmd(a,{tag:u});var h={1:1,2:2,3:3},g=[JSON.parse(JSON.stringify({postscript:o&&o.postscript,revokeType:h[t.conversationType],revokeAccountId:this.core.account,serverExtension:o&&o.serverExtension,messageRefer:formatMessageRefer(this.core,t)}))];this.revokeMessagesFn(g),this.core.eventBus.emit("forwardSend/V2NIMMessageService/revokeMessage",u)}))}deleteMessage(t,o){return __awaiter(this,void 0,void 0,(function*(){if(validate(Wt,t,"",!0),3===t.sendingState)this.service.fileUtil.cancelMessageAttachmentUpload(t);else if(t.sendingState&&1!==t.sendingState)throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"deleteMessage: cannot delete unsent message"}});var a={messageRefer:formatMessageRefer(this.core,t),serverExtension:o},m=Date.now();t.messageServerId&&"0"!==t.messageServerId&&(m=(yield this.core.sendCmd("v2DeleteMessage",{tag:a})).content.timetag);var u=[{serverExtension:o,messageRefer:formatMessageRefer(this.core,t),deleteTime:m}];this.core.eventBus.emit("forwardSend/V2NIMMessageService/deleteSelfMsgs",[Object.assign(Object.assign({},a),{deleteTime:m})]),this.deleteMessagesFn(u)}))}deleteMessages(t,o){return __awaiter(this,void 0,void 0,(function*(){validate(Jt,{messages:t},"",!0);var a=[],m=[];if(0===t.length)throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"deleteMessages: message array length is 0"}});for(var u=t[0].conversationId,h=0;h<t.length;h++){if(3===t[h].sendingState)this.service.fileUtil.cancelMessageAttachmentUpload(t[h]);else if(t[h].sendingState&&1!==t[h].sendingState)throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:`deleteMessage: sendingState should be succeeded, please check message at index: ${h}`}});if(h>=1&&t[h].conversationId!==u)throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"deleteMessages: only allow to delete messages from same conversation"}});t[h].messageServerId&&"0"!==t[h].messageServerId?a.push(t[h]):m.push(t[h])}var g=Date.now(),I=[...m];try{if(a.length>0){var M=yield this.core.sendCmd("v2DeleteMessages",{tag:a.map((t=>({messageRefer:t,serverExtension:o})))});g=M.content.timetag,I=[...I,...a]}}catch(t){if(0===m.length)throw t;this.logger.warn("V2NIMMessageService:deleteMessages: delete messages with serverId failed")}var _=I.map((t=>({serverExtension:o,messageRefer:formatMessageRefer(this.core,t),deleteTime:g})));this.core.eventBus.emit("forwardSend/V2NIMMessageService/deleteSelfMsgs",I.map((t=>({messageRefer:t,serverExtension:o,deleteTime:g})))),this.deleteMessagesFn(_)}))}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,o){this.core=t,this.service=o,this.logger=t.logger}stopAIStreamMessage(t,o){var a;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===(a=t.aiConfig)||void 0===a?void 0:a.accountId,opeType:o.operationType,updateContent:o.updateContent,messageTime:t.createTime}}),this.logger.log(`V2AIUtil::streamMessageStop,clientId:${t.messageClientId}`),this.core.V2NIMAIService.model.completeAiStream(t.messageClientId)}))}regenAIMessage(t,o){var a,m,u,h,g,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:Me.V2NIM_ERROR_CODE_MISUSE,detail:{reason:`msg::regenAIMessage streamCache is not complete, msgId:${t.messageClientId}`}})}else if(-1===(null===(a=t.streamConfig)||void 0===a?void 0:a.status)||1===(null===(m=t.streamConfig)||void 0===m?void 0:m.status))throw new V2NIMErrorImpl({code:Me.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===(u=t.aiConfig)||void 0===u?void 0:u.accountId,serverId:t.messageServerId,clientId:t.messageClientId,time:t.createTime,type:t.conversationType,opeType:o.operationType,replyMsgFromAccount:null===(h=t.threadReply)||void 0===h?void 0:h.senderId,replyMsgToAccount:null===(g=t.threadReply)||void 0===g?void 0:g.receiverId,replyMsgTime:null===(I=t.threadReply)||void 0===I?void 0:I.createTime,replyMsgIdServer:null===(M=t.threadReply)||void 0===M?void 0:M.messageServerId,replyMsgIdClient:null===(_=t.threadReply)||void 0===_?void 0:_.messageClientId}}),1===o.operationType&&this.core.V2NIMAIService.model.setAiStream(t.messageClientId,{isComplete:!1,queryStatus:0,chunks:[]})}))}checkAI(){if(!this.hasAI())throw new V2NIMErrorImpl({code:Me.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,o){this.core=t,this.service=o,this.model=o.model,this.receiptUtil=o.receiptUtil,this.logger=this.core.logger}setAIStreamPlaceholder(t){this.service.aiUtil.hasAI()&&t.forEach((t=>{var o;1===(null===(o=t.streamConfig)||void 0===o?void 0:o.status)&&this.core.V2NIMAIService.model.setAiStream(t.messageClientId,{isComplete:!1,queryStatus:0,chunks:[],msg:t},!0)}))}onMsgHandler(t){var o=fillIdServer(t,t.content.msg,"messageServerId"),{_conversationOnlineSyncNotify:a,_conversationOnlineSyncData:m}=o,u=__rest(o,["_conversationOnlineSyncNotify","_conversationOnlineSyncData"]),h=completeMessage(this.core,u,1),g=this.service._filterMessage(h);this.logger.log(`v2OnMsgHandler::recvMsg ${h.messageClientId}/${h.messageServerId}/${h.createTime};isHitFilter:${g}`),3===h.conversationType?this.core.eventBus.emit("V2NIMSync/updateTimetag",{superTeamRoamingMsgs:h.createTime,offlineMsgs:h.createTime}):this.core.eventBus.emit("V2NIMSync/updateTimetag",{roamingMsgs:h.createTime,offlineMsgs:h.createTime}),this.service.config.compatibleWithV1||(this.service.markMsgsAck([h]),this.service.sendUtil.doMsgReceiveReport(h,t)),delete h.__clientExt,this.setAIStreamPlaceholder([h]),5!==h.messageType&&this.core.V2NIMUserService.checkUserUpdate&&this.core.V2NIMUserService.checkUserUpdate(h,h.userUpdateTime),5===h.messageType&&this.core.eventBus.emit("V2NIMTeamService/notification",o),g||(this.service.emit("onReceiveMessages",[h]),this.model.upsertMessages([h]),a&&this.core.eventBus.emit("V2NIMConversationService/conversationOnlineSyncNotify",{content:{info:JSON.parse(a),data:JSON.parse(m)}},h),this.core.eventBus.emit("V2NIMMessageService/onMsg",h))}syncOfflineMsgsHandler(t){var o=t.content.datas;o=o.map((t=>completeMessage(this.core,t,2))),0!==(o=this.service._filterMessagesByFn(o)).length&&(!this.service.config.compatibleWithV1&&this.service.markMsgsAck(o),this.service.emit("onReceiveMessages",o),this.model.upsertMessages(o),this.core.eventBus.emit("V2NIMMessageService/offlineMsgs",o))}syncRoamingMsgsHandler(t){var o=t.content.datas;o=o.map((t=>completeMessage(this.core,t,3))),this.setAIStreamPlaceholder(o),0!==(o=this.service._filterMessagesByFn(o)).length&&(this.service.emit("onReceiveMessages",o),this.model.upsertMessages(o),this.core.eventBus.emit("V2NIMMessageService/roamingMsgs",o))}onP2PMessageReceiptsHandler(t){this.receiptUtil.onP2PMessageReceiptsHandler(t)}onTeamMessageReceiptsHandler(t){this.receiptUtil.onTeamMessageReceiptsHandler(t)}syncP2PMessagReceiptsHandler(t){this.receiptUtil.syncP2PMessagReceiptsHandler(t)}syncRevokeMessageHandler(t){this.service.deleteUtil.emitRevokeMessage(t.content.datas)}onRevokeMessageHandler(t){var o=t.content.data;this.service.deleteUtil.emitRevokeMessage([o])}onDeleteMessageHandler(t){var o=t.content.data,a={serverExtension:o.serverExtension,deleteTime:o.deleteTime,messageRefer:completeMessageRefer(this.core,o.messageRefer)};this.service.deleteUtil.deleteMessagesFn([a])}onDeleteMessagesHandler(t){var o=t.content.data.map((t=>({serverExtension:t.serverExtension,deleteTime:t.deleteTime,messageRefer:completeMessageRefer(this.core,t.messageRefer)})));this.service.deleteUtil.deleteMessagesFn(o)}syncOnDeleteMessagesHandler(t){var o=t.content.datas.map((t=>({serverExtension:t.serverExtension,deleteTime:t.deleteTime,messageRefer:completeMessageRefer(this.core,t.messageRefer)})));this.service.emit("onMessageDeletedNotifications",o)}v2MessageOnModifiedHandler(t){var o=completeMessage(this.core,t.content.data);this.model.upsertMessages([o]),this.service.aiUtil.hasAI()&&this.core.V2NIMAIService.model.completeAiStream(o.messageClientId),this.core.eventBus.emit("forwardSend/V2NIMMessageService/modifyMsg",o),this.core.eventBus.emit("V2NIMMessageService/modifyMsg",o),this.core.eventBus.emit("V2NIMSync/updateTimetag",3===o.conversationType?{superTeamModifyMessage:o.modifyTime}:{p2pTeamModifyMessage:o.modifyTime}),this.service.emit("onReceiveMessagesModified",[o])}v2MessageSyncModifiedHandler(t){var o=t.content.datas.map((t=>completeMessage(this.core,t))).filter((t=>{var o,a=(null===(o=this.model.getMessageById(t.messageClientId))||void 0===o?void 0:o.modifyTime)||0;return(t.modifyTime||0)>a}));o.length>0&&(this.model.upsertMessages(o),o.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",o))}v2MessageSyncSuperTeamModifiedHandler(t){this.v2MessageSyncModifiedHandler(t)}}class V2NIMMessageEventImpl{constructor(t,o){this.core=t,this.service=o,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,...o){var a,m,u,h=`${this.service.name}::emit ${t.toString()}`;if("onSendMessage"===t){var g=o[0];this.logger.log(`${h}`,`${g.messageClientId}/${g.messageServerId}/${g.createTime};`,`sendingState:${g.sendingState};attachmentUploadState:${g.attachmentUploadState||0};messageStatus:${null===(a=g.messageStatus)||void 0===a?void 0:a.errorCode};config.lastMsg:${null===(m=g.messageConfig)||void 0===m?void 0:m.lastMessageUpdateEnabled};config.unread:${null===(u=g.messageConfig)||void 0===u?void 0:u.unreadEnabled}`)}else if("onReceiveMessages"===t||"onReceiveMessagesModified"===t){var I=o[0];this.logger.log(`${h}`,I.map((t=>{var o,a;return`${t.messageClientId}/${t.messageServerId}/${t.createTime};config.lastMsg:${null===(o=t.messageConfig)||void 0===o?void 0:o.lastMessageUpdateEnabled};config.unread:${null===(a=t.messageConfig)||void 0===a?void 0:a.unreadEnabled}`})))}else if("onMessageRevokeNotifications"===t){var M=o[0];this.logger.log(`${h}`,M.map((t=>`msg:${t.messageRefer.messageClientId}/${t.messageRefer.messageServerId};revokeAccountId:${t.revokeAccountId}`)))}else if("onMessageDeletedNotifications"===t){var _=o[0];this.logger.log(`${h}`,_.map((t=>`msg:${t.messageRefer.messageClientId}/${t.messageRefer.messageServerId};deleteTime:${t.deleteTime}`)))}else this.logger.log(`${h}`,...o)}}class V2NIMMessageServiceImpl extends V2Service{constructor(t,o={}){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:kr,cmdConfig:Fr}),this.setOptions(o),this.setListener())}setOptions(t){var o;(null===(o=this.core.msg)||void 0===o?void 0:o.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,...o){return this.event.beforeEmit(t,...o),super.emit(t,...o)}checkExtendUtil(){var t;if(!(null===(t=this.core.V2NIMMessageExtendUtil)||void 0===t?void 0:t.name))throw new V2NIMErrorImpl({code:Me.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:Me.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 o=yield this.core.V2NIMMessageLogUtil.getMessageList(t);return o=this._filterMessageByClearTime(t.conversationId,o),o=this._filterMessagesByFn(o)}))}getMessageListEx(t){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),this.checkLogUtil();var o=yield this.core.V2NIMMessageLogUtil.getMessageList(t);return o=this._filterMessageByClearTime(t.conversationId,o),{messages:this._filterMessagesByFn(o),anchorMessage:o.length>0?o[o.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,o){return this.checkV2(),this.checkExtendUtil(),this.core.V2NIMMessageExtendUtil.pinMessage(t,o)}unpinMessage(t,o){return this.checkV2(),this.checkExtendUtil(),this.core.V2NIMMessageExtendUtil.unpinMessage(t,o)}updatePinMessage(t,o){return this.checkV2(),this.checkExtendUtil(),this.core.V2NIMMessageExtendUtil.updatePinMessage(t,o)}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,o,a,m){return this.checkV2(),this.checkExtendUtil(),this.core.V2NIMMessageExtendUtil.addQuickComment(t,o,a,m)}removeQuickComment(t,o,a){return this.checkV2(),this.checkExtendUtil(),this.core.V2NIMMessageExtendUtil.removeQuickComment(t,o,a)}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,o){return this.checkV2(),this.checkExtendUtil(),this.core.V2NIMMessageExtendUtil.updateCollectionExtension(t,o)}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 o=this.customAttachmentParsers.indexOf(t);o>-1&&this.customAttachmentParsers.splice(o,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,o){return __awaiter(this,void 0,void 0,(function*(){return this.checkV2(),this.deleteUtil.revokeMessage(t,o)}))}deleteMessage(t,o){return this.checkV2(),this.deleteUtil.deleteMessage(t,o)}deleteMessages(t,o){return this.checkV2(),this.deleteUtil.deleteMessages(t,o)}cancelMessageAttachmentUpload(t){return this.checkV2(),this.fileUtil.cancelMessageAttachmentUpload(t)}markMsgsAck(t){if(t&&t.length>0){var o=[],a=[];t.forEach((t=>{t.senderId===this.core.account&&t.senderId!==t.receiverId||(1===t.conversationType?o.push(t):2===t.conversationType&&a.push(t))})),o.length>0&&this.core.sendCmd("v2BatchMarkRead",{sid:7,cid:2,ids:o.map((t=>t.messageServerId))}),a.length>0&&this.core.sendCmd("v2BatchMarkRead",{sid:8,cid:3,ids:a.map((t=>t.messageServerId))})}}sendMessage(t,o,a={},m){var u;return __awaiter(this,void 0,void 0,(function*(){if(this.checkV2(),validate({message:{type:"object"}},{message:t},"",!0),t.messageClientId=t.messageClientId||Ve(),t.conversationId&&t.conversationId!==o)throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"sendMessage: message.conversationId is not equal to conversationId"}});validate(qt,{conversationId:o,message:t,params:a},"",!0),validateConversationId(this.core.account,o);var h=this.core.V2NIMConversationIdUtil.parseConversationType(o);if((2===h||3===h)&&a.robotConfig&&!a.robotConfig.accountId)throw new ValidateErrorV2({detail:{reason:"When conversationType is team or superTeam, account is required in robotInfo account is required"}});if(2!==h&&3!==h||!a.targetConfig)a.targetConfig=void 0;else{var g=a.targetConfig.receiverIds;if(3===h&&!1===a.targetConfig.inclusive)throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"setting inclusive to false for super teams is not allowed"}});if(0===(g=g.filter((t=>t&&t!==this.core.account))).length)throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"receiverIds cannot be empty or only contain yourself"}});a.targetConfig.receiverIds=g}(null===(u=a.aiConfig)||void 0===u?void 0:u.aiStream)&&this.aiUtil.checkAI();var I,M=this.core.timeOrigin.getTimeNode(),{messageBeforeSend:_,clientAntispamResult:E,hiddenParams:S}=this.sendUtil.prepareMessage(t,o,a);this.logger.log(`V2SendMessage start:${_.messageClientId}/${_.createTime};conversation:${o};`,`NTPTime:${this.core.timeOrigin.getNTPTime(M)}`);try{I=yield this.sendUtil.doSendMessage({apiCallingTimeNode:M,messageBeforeSend:_,clientAntispamResult:E,hiddenParams:S,progress:m})}catch(t){throw this.logger.warn(`V2SendMessage end:${_.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,o,a={},m){return __awaiter(this,void 0,void 0,(function*(){if(this.checkV2(),validate({message:{type:"object"}},{message:t},"",!0),t.messageClientId=t.messageClientId||Ve(),validate(Gt,{message:t,replyMessage:o,params:a},"",!0),validateConversationId(this.core.account,o.conversationId),(2===t.conversationType||3===t.conversationType)&&a.robotConfig&&!a.robotConfig.accountId)throw new ValidateErrorV2({detail:{reason:"When conversationType is team or superTeam, account is required in robotInfo account is required"}});var u=this.core.timeOrigin.getTimeNode(),{messageBeforeSend:h,clientAntispamResult:g,hiddenParams:I}=this.sendUtil.prepareMessage(t,o.conversationId,a,o),M=yield this.sendUtil.doSendMessage({apiCallingTimeNode:u,messageBeforeSend:h,clientAntispamResult:g,hiddenParams:I,progress:m});return M.message.senderId===M.message.receiverId&&this.markMsgsAck([M.message]),M}))}modifyMessage(t,o){this.checkV2(),this.checkLogin(),validate(fr,t,"message",!0),validate(Ir,o,"params",!0),this.modifyUtil.checkIfModify(t,o);var{messageBeforeSend:a,clientAntispamResult:m}=this.modifyUtil.prepareMessage(t,o);return this.modifyUtil.modifyMessage(a,m)}stopAIStreamMessage(t,o){if(this.checkV2(),this.aiUtil.checkAI(),validate(yr,t,"message",!0),validate(Mr,o,"params",!0),2===o.operationType&&!o.updateContent)throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"V2NIMMessage::stopAIStreamMessage updateContent empty"}});return this.aiUtil.stopAIStreamMessage(t,o)}regenAIMessage(t,o){return this.checkV2(),this.aiUtil.checkAI(),validate(yr,t,"message",!0),validate(_r,o,"params",!0),this.aiUtil.regenAIMessage(t,o)}sendMessageFn(t){if(t.msgAckSnapshot){var o=t.msgAckSnapshot,a={conversationId:t.conversationId,messageServerId:t.messageServerId,messageClientId:t.messageClientId,readCount:0,unreadCount:Number(o)};delete t.msgAckSnapshot,this.emit("onReceiveTeamMessageReadReceipts",[a])}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(o){return this.logger.error(`V2NIMMessage::triggerMessageFilter ${t.messageClientId} error:`,o),!1}return!1}_filterMessagesByFn(t){return t.filter((t=>!this._filterMessage(t)))}_filterMessageByClearTime(t,o){var a=Ae.localStorage.getItem(`nim_${this.core.account}_${t}_clearTime`),m=a?parseInt(a):0;return m>0?o.filter((t=>t.createTime>=m)):o}}var oi={super_team:3,p2p:1,team:2},si={3:"super_team",1:"p2p",0:"p2p",2:"team"};function getConvInfoFromSessionId(t,o="|"){var a=t.indexOf(o);if(-1===a)return{target:"",type:0};var m=t.slice(0,a);return{target:t.slice(a+1),type:oi[m]||0}}function getSessionIdFromConvInfo(t,o){return`${si[t]}|${o}`}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,o)=>o.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,o)=>o.sortOrder-t.sortOrder))}getStickTopList(){return Array.from(this.map.values()).filter((t=>t.stickTop)).sort(((t,o)=>o.sortOrder-t.sortOrder))}getByOption(t,o,a){var{conversationTypes:m,onlyUnread:u}=a,h=[];this.map.forEach((t=>{m&&m.length>0&&!m.includes(t.type)||u&&!t.unreadCount||a.ignoreMuted&&t.mute||h.push(t)})),h=h.sort(((t,o)=>o.sortOrder-t.sortOrder));var g=0;t>0&&(g=findIndexWithinTargetValue(h,"sortOrder",t),h[g]&&h[g].sortOrder===t&&(g+=1));var I=h.slice(g).length;return(h=h.slice(g,g+o)).length>0?{offset:I>o?h[h.length-1].sortOrder:0,finished:!(I>o),conversationList:h}:{offset:0,finished:!0,conversationList:h}}upsert(t){var o=t.conversationId,a=this.map.get(o);if(!a){var m=this.processConversation(Object.assign({stickTop:this.getStickTop(o),localExtension:"",lastMessage:null,unreadCount:0,sortOrder:0,createTime:0,updateTime:0},t));return this.setLRU(o,m),m.unreadCount>0}var u=t.unreadCount!==a.unreadCount,h=Object.assign({},a,t);return h=this.processConversation(h),this.setLRU(o,h),u}setLRU(t,o){if(this.map.has(t))this.map.delete(t);else if(this.map.size>=this.capacity){var a=this.map.keys().next().value;a&&this.map.delete(a)}this.map.set(t,o)}bulkUpsert(t){var o=!1;return t.forEach((t=>{this.upsert(t)&&(o=!0)})),o}deleteById(t){var o=this.getById(t);if(o)return this.map.delete(t),o}updateReadTime(t,o){this.readTimeMap.set(t,o)}getReadTime(t){return this.readTimeMap.get(t)||0}updateStickTop(t,o){o?this.stickTopMap.set(t,!0):this.stickTopMap.delete(t)}getStickTop(t){return this.stickTopMap.get(t)||!1}}var ni={"4_14":"v2LocalConvSyncReadTime","4_20":"v2LocalConvSyncSuperTeamReadTime","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"},ai="V2NIMLocalConversationService",ci={id:1,ext:2,createTime:{id:3,retType:"number"},updateTime:{id:4,retType:"number"}},di={scene:1,to:2,timetag:3},li={v2LocalConvSyncReadTime:{sid:4,cid:14,service:ai,response:[{type:"StrLongMap",name:"p2p"},{type:"LongLongMap",name:"team"},{type:"Long",name:"timetag"}]},v2LocalConvSyncSuperTeamReadTime:{sid:4,cid:20,service:ai,response:[{type:"LongLongMap",name:"superTeam"}]},v2LocalConvSyncMoreRoaming:{sid:4,cid:22,service:ai,response:[]},v2LocalConvSyncStickTop:{sid:4,cid:23,service:ai,response:[{type:"Long",name:"timetag"},{type:"Bool",name:"isThereAnyChange"},{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(ci)}]},v2LocalConvSyncReliableInfo:{sid:4,cid:25,service:ai,response:[]},v2LocalConvMarkReadTime:{sid:7,cid:16,service:ai,params:[{type:"Byte",name:"scene"},{type:"String",name:"to"},{type:"Long",name:"timetag"}]},v2LocalConvMultiMarkReadTime:{sid:7,cid:25,service:ai,ignoreErrCodes:[700],params:[{type:"PropertyArray",name:"tags",reflectMapper:di}]},v2LocalConvMultiSyncReadTime:{sid:7,cid:116,service:ai,response:[{type:"Byte",name:"scene"},{type:"String",name:"to"},{type:"Long",name:"timetag"}]},v2LocalConvSuperTeamMarkReadTime:{sid:21,cid:25,service:ai,params:[{type:"Long",name:"to"},{type:"Long",name:"timetag"}]},v2LocalConvSuperTeamMultiMarkReadTime:{sid:21,cid:32,service:ai,ignoreErrCodes:[700],params:[{type:"PropertyArray",name:"tags",reflectMapper:di}]},v2LocalConvSuperTeamMultiSyncReadTime:{sid:21,cid:125,service:ai,response:[{type:"Long",name:"to"},{type:"Long",name:"timetag"}]},v2LocalConvStickTopAdd:{sid:33,cid:12,service:ai,params:[{type:"Property",name:"tag",reflectMapper:ci}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(ci)}]},v2LocalConvStickTopDelete:{sid:33,cid:13,service:ai,params:[{type:"Property",name:"tag",reflectMapper:ci}],response:[{type:"Long",name:"timetag"}]},v2LocalConvStickTopMultiSyncAdd:{sid:23,cid:112,service:ai,response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(ci)}]},v2LocalConvStickTopMultiSyncDelete:{sid:23,cid:113,service:ai,response:[{type:"Long",name:"timetag"},{type:"Property",name:"data",reflectMapper:invertSerializeItem(ci)}]},v2LocalConvStickTopMultiSyncUpdate:{sid:23,cid:114,service:ai,response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(ci)}]}};function chunk(t,o){t=t||[],o=o||1,o=Math.max(Math.floor(o),1);for(var a=[],m=0;m<t.length;m+=o)a.push(t.slice(m,m+o));return a}function isObject(t){var o=typeof t;return null!=t&&("object"==o||"function"==o)}var pi=Math.max,mi=Math.min;function debounce(t,o,a){var m,u,h,g,I,M,_=0,E=!1,S=!1,T=!0;if("function"!=typeof t)throw new TypeError("Expected a function");function invokeFunc(o){var a=m,h=u;return m=u=void 0,_=o,g=t.apply(h,a)}function leadingEdge(t){return _=t,I=setTimeout(timerExpired,o),E?invokeFunc(t):g}function shouldInvoke(t){var a=t-M;return void 0===M||a>=o||a<0||S&&t-_>=h}function timerExpired(){var t=Date.now();if(shouldInvoke(t))return trailingEdge(t);I=setTimeout(timerExpired,function remainingWait(t){var a=o-(t-M);return S?mi(a,h-(t-_)):a}(t))}function trailingEdge(t){return I=void 0,T&&m?invokeFunc(t):(m=u=void 0,g)}function debounced(){var t=Date.now(),a=shouldInvoke(t);if(m=arguments,u=this,M=t,a){if(void 0===I)return leadingEdge(M);if(S)return clearTimeout(I),I=setTimeout(timerExpired,o),invokeFunc(M)}return void 0===I&&(I=setTimeout(timerExpired,o)),g}return o=Number(o)||0,isObject(a)&&(E=!!a.leading,h=(S="maxWait"in a)?pi(Number(a.maxWait)||0,o):h,T="trailing"in a?!!a.trailing:T),debounced.cancel=function cancel(){void 0!==I&&clearTimeout(I),_=0,m=M=u=I=void 0},debounced.flush=function flush(){return void 0===I?g:trailingEdge(Date.now())},debounced}var ui;class V2NIMLocalConversationUnreadImpl{constructor(t,o){this.totalUnreadCount=void 0,this.unreadCountByFilter={},this.currentConversationId=void 0,this._setCurrConvThrottle=function throttle(t,o,a){var m=!0,u=!0;if("function"!=typeof t)throw new TypeError("Expected a function");return isObject(a)&&(m="leading"in a?!!a.leading:m,u="trailing"in a?!!a.trailing:u),debounce(t,o,{leading:m,maxWait:o,trailing:u})}((()=>{this.currentConversationId&&this._setCurrConv(this.currentConversationId)}),5e3,{leading:!1}),this.core=t,this.service=o,this.model=o.model,this.logger=o.logger}reset(){this.totalUnreadCount=void 0,this.unreadCountByFilter={},this.currentConversationId=void 0,this._setCurrConvThrottle.flush()}getTotalUnreadCount(){return this.totalUnreadCount}resetTotalAfterSyncDone(){var t=this.service.model.getAll().reduce(((t,o)=>t+(o.unreadCount||0)),0),o=this.totalUnreadCount;return void 0!==o&&o===t||(this.totalUnreadCount=t,this.service.emit("onTotalUnreadCountChanged",t)),t}digestUnreadCountChange(){this._digest()}_digest(){var t=this.totalUnreadCount,o=this.service.model.getAll().reduce(((t,o)=>t+(o.unreadCount||0)),0);this.core.logger.log(`V2NIMConversation::digestUnreadCountChange:oldUnreadCount ${t}, newUnreadCount ${o}`),t!==o&&(this.totalUnreadCount=o,this.service.emit("onTotalUnreadCountChanged",o)),Object.keys(this.unreadCountByFilter).forEach((t=>{var o=JSON.parse(t),a=this.getUnreadCountByFilter(o),m=this.unreadCountByFilter[t];this.unreadCountByFilter[t]=a,o.equals=equals$1.bind(o),m!==a&&this.service.emit("onUnreadCountChangedByFilter",o,a)}))}clearUnreadCount(t){var o=t.reduce(((t,o)=>(this.service.model.upsert({conversationId:o.conversationId,type:o.type,unreadCount:0})&&t.push(o.conversationId),t)),[]);if(o.length>0){var a=o.map((t=>this.service.model.getById(t)));this.service.triggerConversationChanged(a),this.digestUnreadCountChange()}}getUnreadCountByIds(t){return(t=uniq(t)).reduce(((t,o)=>{var a=this.service.model.getById(o);return t+(a&&a.unreadCount||0)}),0)}getUnreadCountByFilter(t){var o=this.service.model.count();return this.service.model.getByOption(0,o,{conversationTypes:t.conversationTypes,ignoreMuted:t.ignoreMuted}).conversationList.reduce(((t,o)=>t+(o.unreadCount||0)),0)}isMessageUnread(t,o=0){var a;return t.createTime>o&&t.senderId!==this.core.account&&200===t.messageStatus.errorCode&&!1!==(null===(a=t.messageConfig)||void 0===a?void 0:a.unreadEnabled)}isMessageReferUnread(t,o=0){var a=this.core.V2NIMMessageService.model.getMessageById(t.messageClientId);return a?this.isMessageUnread(a,o):t.createTime>o&&t.senderId!==this.core.account}countUnreadByMessageInMemory(t,o=0){var a=0;return this.core.V2NIMMessageService.model.getMessagesByConversationId(t).forEach((t=>{this.isMessageUnread(t,o)&&a++})),a}addFilter(t){var o=generateFilterKey$1(t);if(void 0!==this.unreadCountByFilter[o])throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_RESOURCE_ALREADY_EXIST});var a=JSON.parse(o),m=this.getUnreadCountByFilter(a);this.unreadCountByFilter[o]=m,this.service.emit("onUnreadCountChangedByFilter",a,m)}deleteFilter(t){var o=generateFilterKey$1(t);if(void 0===this.unreadCountByFilter[o])throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_RESOURCE_NOT_EXIST});delete this.unreadCountByFilter[o]}markConversationRead(t){return __awaiter(this,void 0,void 0,(function*(){var o=this.model.getById(t),a=this.core.V2NIMConversationIdUtil.parseConversationTargetId(t),m=this.core.V2NIMConversationIdUtil.parseConversationType(t),u=this.model.getReadTime(t);if(!o)return u||this.core.timeOrigin.getNTPTime();var h=this.service.compute.computeReadTimeForMark(o);return u>=h?(this.logger.log(`V2LocalConv::markConversationRead currentReadTime >= readTime ${t},${u},${h}`),u):(3===m?yield this.core.sendCmd("v2LocalConvSuperTeamMarkReadTime",{timetag:h,to:a}):yield this.core.sendCmd("v2LocalConvMarkReadTime",{scene:1===m?0:2===m?1:2,timetag:h,to:a}),this.model.updateReadTime(t,h),h)}))}markMultiConversationRead(t){return __awaiter(this,void 0,void 0,(function*(){var o={cmd:"v2LocalConvSuperTeamMultiMarkReadTime",params:[]},a={cmd:"v2LocalConvMultiMarkReadTime",params:[]};t.forEach((t=>{var m=this.model.getById(t);if(m){var u=this.core.V2NIMConversationIdUtil.parseConversationTargetId(t),h=this.core.V2NIMConversationIdUtil.parseConversationType(t),g=this.model.getReadTime(t),I=this.service.compute.computeReadTimeForMark(m);if(!(g>=I)){var M={conversationId:t,scene:1===h?0:2===h?1:2,timetag:I,to:u};3===h?o.params.push(M):a.params.push(M)}}}));var m=chunk(o.params,50),u=chunk(a.params,50);for(var h of m){try{yield this.core.sendCmd(o.cmd,{tags:h})}catch(t){this.logger.warn("markMultiConversationRead::error:",h.map((t=>t.conversationId)),t)}h.forEach((t=>{this.model.updateReadTime(t.conversationId,t.timetag)}))}for(var g of u){try{yield this.core.sendCmd(a.cmd,{tags:g})}catch(t){this.logger.warn("markMultiConversationRead::error:",g.map((t=>t.conversationId)),t)}g.forEach((t=>{this.model.updateReadTime(t.conversationId,t.timetag)}))}}))}setCurrentConversation(t){var o=this.currentConversationId;this.currentConversationId=t,this.currentConversationId&&this._setCurrConv(this.currentConversationId),o&&o!==this.currentConversationId&&(this._setCurrConvThrottle.flush(),this._setCurrConv(o))}_setCurrConv(t){var o=this.model.getById(t),a=(null==o?void 0:o.unreadCount)||0;o&&(o.unreadCount=0),o&&a>0&&(this.service.triggerConversationChanged([o]),this._digest()),this.markConversationRead(t).catch((t=>{this.logger.warn("_setConv markRead failed",t)}))}}function generateFilterKey$1(t){var{conversationTypes:o}=t;return o&&(o=o.sort()),JSON.stringify({conversationGroupId:t.conversationGroupId,conversationTypes:o,ignoreMuted:t.ignoreMuted})}function equals$1(t){return JSON.stringify(this)===generateFilterKey$1(t)}function formatLastMessageFromMessage(t,o,a=0,m){var u,h;o=formatMessageAttachment(o,t);var{messageType:g,subType:I,text:M,attachment:_,serverExtension:E}=o,S="";if(o.senderId!==t.account&&5!==g){S=get(o,"fromNick");var T=null===(h=null===(u=t.V2NIMFriendService)||void 0===u?void 0:u.model)||void 0===h?void 0:h.getFriend(o.senderId);T&&T.alias&&(S=T.alias)}return JSON.parse(JSON.stringify({lastMessageState:a,messageRefer:formatMessageRefer(t,o),messageType:g,subType:I,text:M,attachment:_,serverExtension:E,callbackExtension:o.callbackExtension,sendingState:m,senderName:S}))}function formatConversationFields(t,o){return o&&o.length>0?o.map((o=>formatConversationField(t,o))):[]}function formatConversationField(t,o){var a=o;if("string"==typeof a.lastMessage)if(""===a.lastMessage);else if(1===a.lastMessageState){var m=formatRevokeMessage(t,deserialize(JSON.parse(a.lastMessage),invertSerializeItem(Ur)));a.lastMessage=function formatLastMessageFromNotification(t,o){var{messageRefer:a,revokeAccountId:m,revokeType:u,callbackExtension:h,serverExtension:g,postscript:I}=o,M=function calcSenderNameFromNotification(t,o,a,m){var u,h,g,I,M,_,E,S;if(o!==t.account){var T=null===(h=null===(u=t.V2NIMFriendService)||void 0===u?void 0:u.model)||void 0===h?void 0:h.getFriend(o);if(T&&T.alias)return T.alias;if(2===a){var C=null===(I=null===(g=t.V2NIMTeamService)||void 0===g?void 0:g.memberModel)||void 0===I?void 0:I.getById(m,1,o);if(C&&C.teamNick)return C.teamNick}else if(3===a){var N=null===(_=null===(M=t.V2NIMTeamService)||void 0===M?void 0:M.memberModel)||void 0===_?void 0:_.getById(m,1,o);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(o);return A&&A.name?A.name:void 0}}(t,o.revokeAccountId,o.messageRefer.conversationType,o.messageRefer.receiverId)||"";return JSON.parse(JSON.stringify({lastMessageState:1,messageRefer:a,revokeAccountId:m,revokeType:u,callbackExtension:h,serverExtension:g,text:I||"",senderName:M}))}(t,m)}else if(0===a.lastMessageState){var u=deserialize(JSON.parse(a.lastMessage),invertSerializeItem(Pr));a.lastMessage=formatLastMessageFromMessage(t,u,a.lastMessageState,u.senderId===t.account?1:void 0)}else 2===a.lastMessageState&&delete a.lastMessage;return a}function formatConversationByField(t){var{version:o,deleteFlag:a}=t;return{conversation:__rest(t,["version","deleteFlag"]),version:o,deleteFlag:a}}!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"}(ui||(ui={}));class V2NIMLocalConversationComputeImpl{constructor(t,o){this.core=t,this.service=o}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 o,a,m;if(0===t.type)return t;var u=this.core.V2NIMConversationIdUtil.parseConversationType(t.conversationId),h=this.core.V2NIMConversationIdUtil.parseConversationTargetId(t.conversationId),g={};if((null===(o=this.core.V2NIMSettingService)||void 0===o?void 0:o.name)&&(g.mute=this.core.V2NIMSettingService.getConversationMuteStatus(t.conversationId)),1===u&&this.hasUserService){var I,M=this.core.V2NIMUserService.model.getUser(h),_=this.hasFriendService?this.core.V2NIMFriendService.model.getFriend(h):void 0;t.conversationId===(null===(a=t.lastMessage)||void 0===a?void 0:a.messageRefer.conversationId)&&(I=null===(m=t.lastMessage)||void 0===m?void 0:m.senderName),g.name=(null==_?void 0:_.alias)||(null==M?void 0:M.name)||I||h,g.avatar=(null==M?void 0:M.avatar)||""}else if(2===u&&this.hasTeamService){var E=this.core.V2NIMTeamService.model.getById(h,1);g.name=(null==E?void 0:E.name)||h,g.avatar=(null==E?void 0:E.avatar)||""}else if(3===u&&this.hasTeamService){var S=this.core.V2NIMTeamService.model.getById(h,2);g.name=(null==S?void 0:S.name)||h,g.avatar=(null==S?void 0:S.avatar)||""}return Object.assign(t,g),t}computeSortOrder(t,o){return o?t?o+1e15:o:t?1e15:0}computeReadTimeForMark(t){var o,a,m,u=t.conversationId,h=this.service.model.getReadTime(u);if(null===(a=null===(o=null==t?void 0:t.lastMessage)||void 0===o?void 0:o.messageRefer)||void 0===a?void 0:a.createTime)m=t.lastMessage.messageRefer.createTime;else{if(0===t.unreadCount&&h>0)return h;if(!this.core.timeOrigin.checkNodeReliable())return h||0;m=this.core.timeOrigin.getNTPTime()}return m}computeConvWithLastMsg(t,o){var a,m=o||this.core.V2NIMMessageService.model.getLastMessageOfConversation(t.conversationId);if(m&&!1!==(null===(a=m.messageConfig)||void 0===a?void 0:a.lastMessageUpdateEnabled)){var u=formatLastMessageFromMessage(this.core,m,0,m.sendingState);t.lastMessage=u,t.createTime=t.createTime||m.createTime,t.updateTime=m.createTime,t.sortOrder=this.computeSortOrder(t.stickTop,m.createTime)}return t}computeConvWithUnread(t,o){var a=this.service.model.getReadTime(t.conversationId),m=this.service.unread.currentConversationId;if(m&&(null==o?void 0:o.conversationId)===m)return t.unreadCount=0,this.service.unread._setCurrConvThrottle(),t;var u=t.unreadCount||0;return o?o&&this.service.unread.isMessageUnread(o)&&(u+=1):u=this.service.unread.countUnreadByMessageInMemory(t.conversationId,a),t.unreadCount=u,t}computeConvByMsgsCache(t,o){var a,m=this.service.model.getById(t),u=this.core.V2NIMConversationIdUtil.parseConversationType(t),h=this.core.V2NIMMessageService.model.getLastMessageOfConversation(t),g=null==o?void 0:o.updateTime,I=0;I=g||(h&&h.createTime?h.createTime:m&&m.updateTime?m.updateTime:this.core.timeOrigin.getNTPTime());var M=this.service.model.getStickTop(t),_=Object.assign(Object.assign({conversationId:t,type:u,stickTop:M,localExtension:(null==m?void 0:m.localExtension)||"",lastMessage:null,unreadCount:0},o),{createTime:(null==m?void 0:m.createTime)||I,updateTime:I,sortOrder:this.computeSortOrder(M,I)});if(h&&!1!==(null===(a=h.messageConfig)||void 0===a?void 0:a.lastMessageUpdateEnabled)){var E=formatLastMessageFromMessage(this.core,h,0,h.sendingState);_.lastMessage=E}return _}}class V2NIMLocalConversationHandlerImpl{constructor(t,o){this.core=t,this.service=o,this.model=this.service.model,this.logger=this.core.logger}v2LocalConvSyncStickTopHandler(t){var{timetag:o,isThereAnyChange:a,datas:m}=t.content;if(a){var u=this.model.getAll(),h=m.map((t=>{var{target:o,type:a}=getConvInfoFromSessionId(t.id),m=this.core.V2NIMConversationIdUtil.conversationId(a,o);return this.model.updateStickTop(m,!0),m}));u.forEach((t=>{h.includes(t.conversationId)?(t.stickTop=!0,t.updateTime=t.updateTime>o?t.updateTime:o):t.stickTop=!1,this.model.updateStickTop(t.conversationId,t.stickTop)})),this.model.bulkUpsert(u)}}v2LocalConvSyncReadTimeHandler(t){var o=t.content.p2p||{},a=t.content.team.m_map||{};this.logger.log("v2SyncLocalConvAck::",o,a),Object.keys(o).forEach((t=>{var a=this.core.V2NIMConversationIdUtil.p2pConversationId(t),m=this.model.getReadTime(a);o[t]>m&&(this.model.updateReadTime(a,o[t]),this.service.emit("onConversationReadTimeUpdated",a,o[t]))})),Object.keys(a).forEach((t=>{var o=this.core.V2NIMConversationIdUtil.teamConversationId(t),m=this.model.getReadTime(o);a[t]>m&&(this.model.updateReadTime(o,a[t]),this.service.emit("onConversationReadTimeUpdated",o,a[t]))}))}v2LocalConvSyncSuperTeamReadTimeHandler(t){var o=t.content.superTeam.m_map;this.logger.log("v2SyncLocalSuperTeamConvAck::",o),Object.keys(o).forEach((t=>{var a=this.core.V2NIMConversationIdUtil.superTeamConversationId(t),m=this.model.getReadTime(a);o[t]>m&&(this.model.updateReadTime(a,o[t]),this.service.emit("onConversationReadTimeUpdated",a,o[t]))}))}v2LocalConvMultiSyncReadTimeHandler(t){var o=t.content,a=`${0===o.scene?"p2p":1===o.scene?"team":"super_team"}-${o.to}`,{type:m,target:u}=getConvInfoFromSessionId(a,"-"),h=this.core.V2NIMConversationIdUtil.conversationId(m,u),g=this.model.getById(h),I=null==g?void 0:g.unreadCount,M=this.model.getReadTime(h);o.timetag<=M?this.logger.warn(`v2LocalConvMultiSyncReadTimeHandler: ${h} do not need update ack ${o.timetag}/${M}`):(this.model.updateReadTime(h,o.timetag),this.service.emit("onConversationReadTimeUpdated",h,o.timetag),g?(g=this.service.compute.computeConvWithUnread(g),this.model.upsert(g),this.service.unread.digestUnreadCountChange(),void 0===I&&g.unreadCount>0?this.service.triggerConversationCreated(g):"number"==typeof I&&g.unreadCount!==I&&this.service.triggerConversationChanged([g])):this.logger.log(`v2LocalConvMultiSyncReadTimeHandler: ${h} not exist`))}v2LocalConvSuperTeamMultiSyncReadTimeHandler(t){this.v2LocalConvMultiSyncReadTimeHandler(t)}v2LocalConvStickTopMultiSyncAddHandler(t){var{data:o}=t.content,{target:a,type:m}=getConvInfoFromSessionId(o.id),u=this.core.V2NIMConversationIdUtil.conversationId(m,a);this.model.updateStickTop(u,!0);var h=this.model.getById(u);h&&(h.stickTop=!0,h.updateTime=h.updateTime>o.updateTime?h.updateTime:o.updateTime,h.sortOrder=this.service.compute.computeSortOrder(!0,o.updateTime),this.model.upsert(h),this.service.triggerConversationChanged([h]))}v2LocalConvStickTopMultiSyncDeleteHandler(t){var{data:o,timetag:a}=t.content,{target:m,type:u}=getConvInfoFromSessionId(o.id),h=this.core.V2NIMConversationIdUtil.conversationId(u,m);this.model.updateStickTop(h,!1);var g=this.model.getById(h);g&&(g.stickTop=!1,g.updateTime=g.updateTime>a?g.updateTime:a,g.sortOrder=this.service.compute.computeSortOrder(!1,a),this.model.upsert(g),this.service.triggerConversationChanged([g]))}}class V2NIMLocalConversationEventImpl{constructor(t,o){this.core=t,this.service=o,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,...o){var a,m=`${this.service.name}::emit ${t.toString()}`;if("onConversationCreated"===t){var u=o[0],h=null===(a=u.lastMessage)||void 0===a?void 0:a.messageRefer;this.logger.log(`${m}`,`id:${u.conversationId};unread:${u.unreadCount};lastMsg:${(null==h?void 0:h.messageClientId)||""}/${(null==h?void 0:h.messageServerId)||""}`)}else if("onConversationChanged"===t){var g=o[0];this.logger.log(`${m}`,g.map((t=>{var o,a=null===(o=t.lastMessage)||void 0===o?void 0:o.messageRefer;return`id:${t.conversationId};unread:${t.unreadCount};lastMsg:${(null==a?void 0:a.messageClientId)||""}/${(null==a?void 0:a.messageServerId)||""}`})))}else this.logger.log(`${m}`,...o)}onSyncDone(t){if(t)this.service.emit("onSyncFailed",t);else{var o=this.model.getAll();(o=o.map((t=>{var o=t.conversationId,a=this.compute.computeConvByMsgsCache(o);return a=this.compute.computeConvWithUnread(a),a=this.compute.computeFromExternal(a),this.model.upsert(a),this.model.getById(o)}))).length>0&&(this.service.triggerConversationChanged(o),this.service.unread.resetTotalAfterSyncDone()),this.service.emit("onSyncFinished")}}generateConv(t){uniq(t.map((t=>t.conversationId))).forEach((t=>{var o=this.compute.computeConvByMsgsCache(t);this.model.upsert(o)}))}setMute(t,o){var a=this.model.getById(t);a&&a.mute!==o&&(a.mute=o,this.model.upsert(a),this.service.triggerConversationChanged([a]))}deleteMessages(t){var o=new Set;t.forEach((t=>{var a,m=t.messageRefer.conversationId,u=this.model.getById(m);if(u){if(t.messageRefer.messageClientId===(null===(a=u.lastMessage)||void 0===a?void 0:a.messageRefer.messageClientId)){o.add(m);var h=this.core.V2NIMMessageService.model.getLastMessageOfConversation(m);u.lastMessage=h?formatLastMessageFromMessage(this.core,h,0,h.sendingState):void 0}var g=this.model.getReadTime(m);if(u.unreadCount>0&&this.service.unread.isMessageReferUnread(t.messageRefer,g)&&(o.add(m),u.unreadCount--),"deleteTime"in t)t.deleteTime>u.updateTime&&(u.updateTime=t.deleteTime,u.sortOrder=this.compute.computeSortOrder(u.stickTop,u.updateTime));else{var I=this.core.timeOrigin.getNTPTime();u.updateTime=I,u.sortOrder=this.compute.computeSortOrder(u.stickTop,I)}this.model.upsert(u)}}));var a=Array.from(o);!this.core.V2NIMLoginService.dataSync.checkSyncing()&&a.length>0&&(this.service.triggerConversationChanged(a.map((t=>this.model.getById(t)))),this.service.unread.digestUnreadCountChange())}sendMsg(t){var o=t.conversationId,a=this.model.getById(o);if(a){var m=a.lastMessage,u=this.updateCauseMessage(a,t);m!==u.lastMessage&&this.service.triggerConversationChanged([u])}else{var h=this.createCauseMessage(o,t);if(!h)return;this.service.triggerConversationCreated(h)}}recvMsg(t){var o=t.conversationId,a=this.model.getById(o);if(a){var m=a.lastMessage,u=a.unreadCount,h=this.updateCauseMessage(a,t);h=this.compute.computeConvWithUnread(h,t);var g=m!==(h=this.compute.computeFromExternal(h)).lastMessage,I=u!==h.unreadCount;this.model.upsert(h),(g||I)&&this.service.triggerConversationChanged([h])}else{var M=this.createCauseMessage(o,t);if(!M)return;M=this.compute.computeConvWithUnread(M,t),M=this.compute.computeFromExternal(M),this.model.upsert(M),this.service.triggerConversationCreated(M)}this.service.unread.digestUnreadCountChange()}updateCauseMessage(t,o){return t=this.compute.computeConvWithLastMsg(t,o),this.model.upsert(t),this.model.getById(t.conversationId)}createCauseMessage(t,o){var a,m,u;if(!1!==(null===(a=o.messageConfig)||void 0===a?void 0:a.unreadEnabled)||!1!==(null===(m=o.messageConfig)||void 0===m?void 0:m.lastMessageUpdateEnabled)){var h=this.core.V2NIMConversationIdUtil.parseConversationType(t),g=this.model.getStickTop(t),I=!1===(null===(u=o.messageConfig)||void 0===u?void 0:u.lastMessageUpdateEnabled)?void 0:formatLastMessageFromMessage(this.core,o,0,o.sendingState),M=this.core.timeOrigin.getNTPTime(),_={conversationId:t,type:h,createTime:I?o.createTime:M,updateTime:I?o.createTime:M,sortOrder:this.compute.computeSortOrder(g,I?o.createTime:M),stickTop:g,localExtension:"",lastMessage:I,unreadCount:0};return this.model.upsert(_),_}}clearMessages(t){var o=new Set;t.forEach((t=>{var{conversationId:a,deleteTime:m}=t,u=this.model.getById(a);u&&(u.unreadCount>0&&(u.unreadCount=0,o.add(a)),u.lastMessage&&u.lastMessage.messageRefer.createTime<=t.deleteTime&&(u.lastMessage=void 0,o.add(a)),m>u.updateTime&&(u.updateTime=m,u.sortOrder=this.compute.computeSortOrder(u.stickTop,u.updateTime)),this.model.upsert(u))}));var a=Array.from(o);!this.core.V2NIMLoginService.dataSync.checkSyncing()&&a.length>0&&(this.service.triggerConversationChanged(a.map((t=>this.model.getById(t)))),this.service.unread.digestUnreadCountChange())}modifyMsg(t){var o,a=t.conversationId,m=t.messageClientId,u=this.model.getById(a),h=this.core.V2NIMMessageService.model.getMessageById(m);if(u||h)if(u)t.messageClientId===(null===(o=u.lastMessage)||void 0===o?void 0:o.messageRefer.messageClientId)&&(u.lastMessage=formatLastMessageFromMessage(this.core,t,0,t.sendingState),this.service.triggerConversationChanged([u]));else{var g=this.createCauseMessage(a,t);if(!g)return;this.service.triggerConversationCreated(g)}}}var hi={type:"array",itemRules:{type:"enum",values:[1,2,3]},min:1};class V2NIMLocalConversationServiceImpl extends V2Service{constructor(t,o={}){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:ni,cmdConfig:li}),this.setOptions(o),this.setListener())}setOptions(t){this.config=Object.assign(this.config,t)}setListener(){this.event.setListener()}reset(){this.model.reset(),this.unread.reset()}emit(t,...o){return this.event.beforeEmit(t,...o),super.emit(t,...o)}getConversationList(t,o){this.checkV2(),validate({offset:{type:"number",min:0}},{offset:t},"",!0),validate({limit:{type:"number",min:1}},{limit:o},"",!0),this.core.V2NIMLoginService.checkIllegalState();var a=this.model.getByOption(t,o,{});return a.conversationList=a.conversationList.map((t=>this.compute.computeFromExternal(t))),Promise.resolve(a)}getConversationListByOption(t,o,a){this.checkV2(),validate({offset:{type:"number",min:0}},{offset:t},"",!0),validate({limit:{type:"number",min:1}},{limit:o},"",!0),validate({conversationTypes:{type:"array",itemType:"number",required:!1},onlyUnread:{type:"boolean",required:!1}},a,"option",!0),this.core.V2NIMLoginService.checkIllegalState();var m=this.model.getByOption(t,o,a);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 o=this.model.getById(t);if(o)return this.compute.computeFromExternal(o);throw new V2NIMErrorImpl({code:Me.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 o=t.map((t=>this.model.getById(t))).filter((t=>!!t));return o=o.map((t=>this.compute.computeFromExternal(t)))}))}createConversation(t){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validateConversationId(this.core.account,t);var o=this.model.getById(t);if(o)return this.compute.computeFromExternal(o);var a=this.compute.computeConvByMsgsCache(t,{updateTime:this.core.timeOrigin.getNTPTime()});a=this.compute.computeConvWithUnread(a),a=this.compute.computeFromExternal(a),this.model.upsert(a);var m=this.model.getById(t);return this.triggerConversationCreated(m),m}))}deleteConversation(t,o){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validateConversationId(this.core.account,t),validate({clearMessage:{type:"boolean",required:!1}},{clearMessage:o},"",!0),yield this.unread.markConversationRead(t);var a=this.model.deleteById(t);if(!a)throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_RESOURCE_NOT_EXIST});o&&this.core.V2NIMMessageService.model.deleteMessages(t),!!(a&&a.unreadCount>0)&&this.unread.digestUnreadCountChange(),this.emit("onConversationDeleted",[t])}))}deleteConversationListByIds(t,o){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:o},"",!0),yield this.unread.markMultiConversationRead(t);var a=!1;return t.forEach((t=>{o&&this.core.V2NIMMessageService.model.deleteMessages(t),this.model.deleteById(t)&&(a=!0)})),a&&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,o){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validateConversationId(this.core.account,t),validate({stickTop:{type:"boolean"}},{stickTop:o},"",!0);var a=this.model.getById(t);if((null==a?void 0:a.stickTop)!==o){var m=this.core.V2NIMConversationIdUtil.parseConversationTargetId(t),u=this.core.V2NIMConversationIdUtil.parseConversationType(t),h=yield this.core.sendCmd(o?"v2LocalConvStickTopAdd":"v2LocalConvStickTopDelete",{tag:{id:getSessionIdFromConvInfo(u,m)}});this.model.updateStickTop(t,o);var g=h.content.timetag||h.content.data.updateTime;this.model.upsert({conversationId:t,type:u,stickTop:o,updateTime:g,sortOrder:this.compute.computeSortOrder(o,g)});var I=[this.model.getById(t)];this.triggerConversationChanged(I)}}))}updateConversationLocalExtension(t,o){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validateConversationId(this.core.account,t),validate({localExtension:{type:"string"}},{localExtension:o},"",!0);var a=this.model.getById(t);if(!a)throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_RESOURCE_NOT_EXIST});if(a.localExtension!==o){var m=Object.assign(Object.assign({},a),{localExtension:o});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 o=this.unread.getUnreadCountByIds(t);return Promise.resolve(o)}getUnreadCountByFilter(t){this.checkV2(),this.valiteFilter(t);var o=this.unread.getUnreadCountByFilter(t);return Promise.resolve(o)}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 o=[],a=[],m=new RegExp(`^${this.core.account}\\|[1-3]\\|`);if(t.forEach((t=>{m.test(t)?o.push(t):a.push(t)})),o.length>0){var u=o.map((t=>this.model.getById(t))).filter((t=>!!t));yield this.unread.markMultiConversationRead(o),this.unread.clearUnreadCount(u)}return a.map((t=>({conversationId:t,error:new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_RESOURCE_NOT_EXIST})})))}))}clearUnreadCountByTypes(t){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),this.checkLogin(),validate({types:hi},{types:t},"",!0);var o=this.model.getByOption(0,1e3,{conversationTypes:t});yield this.unread.markMultiConversationRead(o.conversationList.map((t=>t.conversationId))),this.unread.clearUnreadCount(o.conversationList)}))}subscribeUnreadCountByFilter(t){var o;this.checkV2(),this.checkLogin(),this.valiteFilter(t),0===(null===(o=t.conversationTypes)||void 0===o?void 0:o.length)&&delete t.conversationTypes,this.unread.addFilter(t)}unsubscribeUnreadCountByFilter(t){var o;this.checkV2(),this.checkLogin(),this.valiteFilter(t),0===(null===(o=t.conversationTypes)||void 0===o?void 0:o.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:Me.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,o)=>o.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,o)=>o.sortOrder-t.sortOrder))}getAll(){return Array.from(this.map.values()).sort(((t,o)=>o.sortOrder-t.sortOrder))}getByOption(t,o,a){var{conversationTypes:m,onlyUnread:u,conversationGroupIds:h}=a,g=[];this.map.forEach((t=>{if((!(m&&m.length>0)||m.includes(t.type))&&(!u||t.unreadCount)&&(!a.ignoreMuted||!t.mute)){if(h){var o=t.groupIds,I=(null==o?void 0:o.length)||0;if(0===h.length&&I>0)return;if(h.length>0&&0===I)return;if(h.length>0&&I>0&&!h.some((t=>o&&o.includes(t))))return}g.push(t)}})),g=g.sort(((t,o)=>o.sortOrder-t.sortOrder));var I=0;t>0&&(I=findIndexWithinTargetValue(g,"sortOrder",t),g[I]&&g[I].sortOrder===t&&(I+=1));var M=g.slice(I).length;return(g=g.slice(I,I+o)).length>0?{offset:M>o?g[g.length-1].sortOrder:0,finished:!(M>o),conversationList:g}:{offset:0,finished:!0,conversationList:g}}upsert(t){var o=t.conversationId,a=this.map.get(o);if(!a)return t=this.processConversation(Object.assign({},t)),this.map.set(o,t),t.unreadCount>0;var m=t.unreadCount!==a.unreadCount,u=Object.assign({},a,t);return u=this.processConversation(u),this.map.set(o,u),m}bulkUpsert(t){var o=!1;return t.forEach((t=>{this.upsert(t)&&(o=!0)})),o}deleteById(t){var o=this.getById(t);if(o)return this.map.delete(t),o}updateReadTime(t,o){this.readTimeMap.set(t,o)}getReadTime(t){return this.readTimeMap.get(t)||0}}function isEqual(t,o){var a=typeof t;if(a!==typeof o)return!1;if("object"===a){if(Object.prototype.toString.call(t)!==Object.prototype.toString.call(o))return!1;if(Array.isArray(t)){if(t.length!==o.length)return!1;for(var m=0;m<t.length;m++)if(!isEqual(t[m],o[m]))return!1;return!0}if(t instanceof RegExp&&o instanceof RegExp)return t.toString()===o.toString();if(t instanceof Date&&o instanceof Date)return t.getTime()===o.getTime();if(null===t&&null===o)return!0;if(Object.keys(t).length!==Object.keys(o).length)return!1;for(var u in t)if(!isEqual(t[u],o[u]))return!1;return!0}return t===o}class V2NIMConversationVersionCacheImpl{constructor(t,o){this.fieldVersion={},this.conversationIdsForBackFill={},this.tempPacket=[],this.isSyncing=!1,this.nextCursor=0,this.core=t,this.service=o}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 o=t;if(o.code===Me.V2NIM_ERROR_CODE_CANCELLED)return;return this.isSyncing=!1,this.service.emit("onSyncFailed",o),this.core.V2NIMLoginService.dataSync.switchDataSync({type:1,state:3,error:o,subType:"conversationSync"}),void this.processTempPacket()}var a=0===parseInt(get(t,"content.info.syncType")),m=get(t,"content.info.nextCursor");this.doSyncAndSuccess(a,m)}))}doSyncAndSuccess(t,o){t&&this.service.model.sort(),this.isSyncing=!1,this.nextCursor=parseInt(o)||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 o=this.core.V2NIMMessageService.model.getLastMessageOfConversation(t.conversationId);t.lastMessage=o?formatLastMessageFromMessage(this.core,o,t.lastMessageState,o.sendingState):""}else this.conversationIdsForBackFill[t.conversationId]=!1;delete t.lastMessageState})),t}recvConversationFromSyncAction(t){var{syncType:o}=get(t,"content.info"),a=formatConversationFields(this.core,get(t,"content.datas"));0===(o=parseInt(o))?(a.forEach((t=>{this.initFieldVersion(t.conversationId,t.version)})),a=this.setBackFillIds(a),this.setModel(a)):(a=this.setBackFillIds(a),this.recvConversationForCreated(a)<a.length&&this.recvConversationForChanged(a))}recvConversation(t){if(this.isSyncing)this.tempPacket.push(t);else{var o=formatConversationFields(this.core,get(t,"content.datas")).filter((t=>!!t.conversationId)),a=get(t,"content.info"),m=o.map((t=>`id:${t.conversationId}, ver:${t.version}`)).join(";");if(this.core.logger.getDebugMode()?this.core.logger.debug(`V2NIMConversation::recvConversation: ${m}.`,a,o):this.core.logger.log(`V2NIMConversation::recvConversation: ${m}.`,a),2===a.type){var u=o.map((t=>(delete this.fieldVersion[t.conversationId],this.service.model.deleteById(t.conversationId),t.conversationId)));return this.service.emit("onConversationDeleted",u),void this.service.unread.digestUnreadCountChange()}if(12!==a.type)a.type,o=this.setBackFillIds(o),this.recvConversationForCreated(o)<o.length&&this.recvConversationForChanged(o);else this.compareAndClearUnreadInModel(a)}}recvConversationForCreated(t){var o=t.filter((t=>!this.fieldVersion[t.conversationId]));return o.reduce(((t,o)=>{if(!this.fieldVersion[o.conversationId]){this.initFieldVersion(o.conversationId,o.version),t=!!this.updateModel(o)||t;var a=this.service.model.getById(o.conversationId);return a&&this.service.triggerConversationCreated(a),t}return t}),!1)&&this.service.unread.digestUnreadCountChange(),o.length}recvConversationForChanged(t){var o=this.bulkCompare(t);if(0!==o.length){this.bulkUpdateModel(o);var a=o.map((t=>this.service.model.getById(t.conversationId))).filter((t=>!!t));this.service.triggerConversationChanged(a)}}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:o,conversationId:a,deleteFlag:m,type:u}=t,h={},g=0;return["stickTop","groupIds","serverExtension","localExtension","lastMessage","lastMessageState","unreadCount","sortOrder","createTime","updateTime","lastReadTime"].forEach((m=>{var u=m;if(void 0!==t[u]){var I=this.fieldVersion[a];I&&"number"==typeof I[u]&&I[u]>=o||(this.fieldVersion[a]=this.fieldVersion[a]||{},this.fieldVersion[a][u]=o,h[u]=t[u],g+=1)}})),g?Object.assign(Object.assign({},h),{conversationId:a,deleteFlag:m,version:o,type:u}):void 0}bulkUpdateModel(t){var o=!1;t.forEach((t=>{this.updateModel(t)&&(o=!0)})),o&&this.service.unread.digestUnreadCountChange()}initFieldVersion(t,o){this.fieldVersion[t]={stickTop:o,groupIds:o,serverExtension:o,lastMessage:o,lastMessageState:o,unreadCount:o,sortOrder:o,createTime:o,updateTime:o,lastReadTime:o}}initConversation(t,o){var a=Date.now();return Object.assign({conversationId:t,type:this.core.V2NIMConversationIdUtil.parseConversationType(t),stickTop:!1,localExtension:"",serverExtension:"",unreadCount:0,lastReadTime:0,createTime:a,updateTime:a,sortOrder:a},o)}updateModel(t){var{deleteFlag:o,conversation:a}=formatConversationByField(t);if(o){var m=this.service.model.deleteById(a.conversationId);return!!(m&&m.unreadCount>0)}return this.service.model.upsert(a)}setModel(t){var o=t.filter((t=>!t.deleteFlag)).map((t=>formatConversationByField(t).conversation));this.service.model.set(o)}updateModelWithLastMessage(t,o,a,m){var u=this.service.model.getById(t),h=o?formatLastMessageFromMessage(this.core,o,a,m):void 0;if(!isEqual(null==u?void 0:u.lastMessage,h))if(u){var g=Object.assign(Object.assign({},u),{sortOrder:h?u.stickTop?h.messageRefer.createTime+1e15:h.messageRefer.createTime:u.sortOrder,lastMessage:h});this.service.model.upsert(g),this.service.triggerConversationChanged([g])}else{this.initFieldVersion(t,-1);var I=this.initConversation(t,{lastMessage:h});this.service.model.upsert(I),this.service.triggerConversationCreated(I)}}updateModelByRevoke(t){var o=[];t.forEach((t=>{var{postscript:a,messageRefer:m}=t,u=__rest(t,["postscript","messageRefer"]),h=m.conversationId,g=this.service.model.getById(h);g&&g.lastMessage&&g.lastMessage.messageRefer.messageClientId===m.messageClientId&&1!==g.lastMessage.lastMessageState&&(g.lastMessage.lastMessageState=1,a&&(g.lastMessage.text=a),Object.assign(g.lastMessage,u),this.service.model.upsert(g),o.push(g))})),o.length>0&&this.service.triggerConversationChanged(o)}compareAndUpdateModel(t){this.core.logger.log("V2NIMConversation::compareAndUpdateModel",t.map((t=>t.conversationId)));var o=!1,a=[];t.forEach((t=>{var m=this.compare(t);if(m){var u=this.service.model.getById(t.conversationId);this.updateModel(m)&&(o=!0);var h=this.service.model.getById(t.conversationId);h&&(u?a.push(h):this.service.triggerConversationCreated(h))}})),a.length>0&&this.service.triggerConversationChanged(a),o&&this.service.unread.digestUnreadCountChange()}compareAndDeleteModel(t){this.core.logger.log("V2NIMConversation::compareAndDeleteModel",t);var o=t.reduce(((t,o)=>{delete this.fieldVersion[o];var a=this.service.model.deleteById(o);return!!!!(a&&a.unreadCount>0)||t}),!1);this.service.emit("onConversationDeleted",t),o&&this.service.unread.digestUnreadCountChange()}compareAndDeleteGroupInModel(t,o){this.core.logger.log("V2NIMConversation::compareAndDeleteGroupInModel",t,o);var a=[];Object.keys(this.fieldVersion).forEach((m=>{var u=this.fieldVersion[m];if(void 0===u.groupIds||t>u.groupIds){u.groupIds=t;var h=this.service.model.getById(m);if(h&&h.groupIds&&h.groupIds.length>0){var g=h.groupIds.filter((t=>t!==o));if(g.length!==h.groupIds.length){var I=Object.assign(Object.assign({},h),{groupIds:g});this.service.model.upsert(I),I&&a.push(I)}}}})),a.length>0&&this.service.triggerConversationChanged(a)}compareAndClearUnreadInModel(t){var{oneClickClearUnreadType:o,oneClickClearUnreadVersion:a,oneClickClearUnreadLastReadTime:m,oneClickClearUnreadConversationType:u,oneClickClearUnreadGroupId:h}=t;this.core.logger.log(`V2NIMConversation::compareAndClearUnreadInModel.ver:${a};type:${o};lastReadTime:${m};filter:${u||""};grounp:${h||""}`);var g=[],I=[];if(1===o)I=this.service.model.getAll();else if(u||h){var M=this.service.model.count();I=this.service.model.getByOption(0,M,{conversationTypes:u,conversationGroupIds:h?[h]:void 0}).conversationList}I.forEach((t=>{var o=t.conversationId,u=this.fieldVersion[o];if(void 0===u.unreadCount||a>u.unreadCount){u.unreadCount=a,u.lastReadTime=a;var h=t.unreadCount,I=Object.assign(Object.assign({},t),{lastReadTime:m,unreadCount:0});this.service.model.upsert(I),h>0&&g.push(I)}})),g.length>0&&this.service.triggerConversationChanged(g),this.service.unread.digestUnreadCountChange()}backfillLastMsg(t,o){var a=t=uniq(t);(o||0!==(a=t.filter((t=>this.conversationIdsForBackFill[t]))).length)&&a.forEach((t=>{var o=get(this.service.model.getById(t),"lastMessage.messageRefer.messageClientId"),a=this.service.compute.hasMessageService?this.core.V2NIMMessageService.model.getLastMessageOfConversation(t):void 0;(a&&a.messageClientId)!==o&&(this.conversationIdsForBackFill[t]=!1,a?this.updateModelWithLastMessage(t,a,2,a.sendingState):this.updateModelWithLastMessage(t,void 0,2,0))}))}}var gi={"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"},vi="V2NIMConversationService",fi={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"}},Ii={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"}},yi={v2ConversationCreate:{sid:28,cid:1,service:vi,params:[{type:"Property",name:"tag",reflectMapper:{conversationId:1}}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(fi)}]},v2ConversationDelete:{sid:28,cid:2,service:vi,params:[{type:"Property",name:"tag",reflectMapper:{conversationId:1,clearMessage:2}}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(fi)}]},v2ConversationUpdate:{sid:28,cid:3,service:vi,params:[{type:"Property",name:"tag",reflectMapper:{conversationId:1,serverExtension:2}}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(fi)}]},v2ConversationSetTop:{sid:28,cid:4,service:vi,params:[{type:"Property",name:"tag",reflectMapper:{conversationId:1,stickTop:2}}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(fi)}]},v2ConversationUnreadClear:{sid:28,cid:5,service:vi,params:[{type:"Property",name:"tag",reflectMapper:{conversationId:1}}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(fi)}]},v2ConversationGet:{sid:28,cid:6,service:vi,params:[{type:"Property",name:"tag",reflectMapper:{conversationId:1}}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(fi)}]},v2ConversationGetByIds:{sid:28,cid:7,service:vi,params:[{type:"Property",name:"tag",reflectMapper:{conversationIds:1}}],response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(fi)},{type:"Property",name:"info",reflectMapper:{1:"failedMap"}}]},v2ConversationGetList:{sid:28,cid:8,service:vi,params:[{type:"Property",name:"tag",reflectMapper:{cursor:1,limit:2}}],response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(fi)},{type:"Property",name:"info",reflectMapper:{1:"hasMore",2:"offset"}}]},v2ConversationsDelete:{sid:28,cid:17,service:vi,params:[{type:"Property",name:"tag",reflectMapper:{conversationIds:1,clearMessage:2}}],response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(fi)},{type:"Property",name:"info",reflectMapper:{1:"failedMap"}}]},v2ConversationsUnreadClear:{sid:28,cid:18,service:vi,params:[{type:"Property",name:"tag",reflectMapper:{conversationIds:1}}],response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(fi)},{type:"Property",name:"info",reflectMapper:{1:"failedMap"}}]},v2ConversationSync:{sid:28,cid:19,service:vi,params:[{type:"Property",name:"tag",reflectMapper:{cursor:1}}],response:[{type:"Property",name:"info",reflectMapper:{1:"nextCursor",2:"syncType"}}]},v2ConversationNotifySync:{sid:28,cid:20,service:vi,response:[{type:"Property",name:"info",reflectMapper:{1:"nextCursor",2:"syncType"}},{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(fi)}]},v2ConversationNotifySyncOnline:{sid:28,cid:21,service:vi,response:[{type:"Property",name:"info",reflectMapper:invertSerializeItem(Ii)},{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(fi)}]},v2ConversationClearTotalUnread:{sid:28,cid:23,service:vi,response:[{type:"Property",name:"info",reflectMapper:invertSerializeItem(Ii)}]},v2ConversationClearTypeUnread:{sid:28,cid:24,service:vi,params:[{type:"Property",name:"tag",reflectMapper:{conversationType:1}}],response:[{type:"Property",name:"info",reflectMapper:invertSerializeItem(Ii)}]},v2ConversationClearGroupUnread:{sid:28,cid:25,service:vi,params:[{type:"Property",name:"tag",reflectMapper:{groupId:1}}],response:[{type:"Property",name:"info",reflectMapper:invertSerializeItem(Ii)}]},syncConversationReadTime:{sid:4,cid:14,service:vi,response:[{type:"StrLongMap",name:"p2p"},{type:"LongLongMap",name:"team"},{type:"Long",name:"timetag"}]},syncSuperTeamReadTime:{sid:4,cid:20,service:vi,response:[{type:"LongLongMap",name:"superTeam"}]},v2SyncSessionsWithMoreRoaming:{sid:4,cid:22,service:vi,response:[]},v2SyncSessionReliableInfo:{sid:4,cid:25,service:vi,response:[]},v2MarkConversationReadTime:{sid:30,cid:16,service:vi,params:[{type:"Byte",name:"scene"},{type:"String",name:"to"},{type:"Long",name:"timetag"}]},v2MarkSuperTeamReadTime:{sid:32,cid:25,service:vi,params:[{type:"Long",name:"to"},{type:"Long",name:"timetag"}]},v2MultiDeviceConversationReadTime:{sid:30,cid:116,service:vi,response:[{type:"Byte",name:"scene"},{type:"String",name:"to"},{type:"Long",name:"timetag"}]},v2MultiDeviceSuperTeamReadTime:{sid:21,cid:125,service:vi,response:[{type:"Long",name:"to"},{type:"Long",name:"timetag"}]}};class V2NIMConversationUnreadImpl{constructor(t,o){this.totalUnreadCount=void 0,this.unreadCountByFilter={},this.core=t,this.service=o}reset(){this.totalUnreadCount=void 0,this.unreadCountByFilter={}}getTotalUnreadCount(){return this.totalUnreadCount}resetTotalAfterSyncDone(){var t=this.service.model.getAll().reduce(((t,o)=>t+(o.unreadCount||0)),0),o=this.totalUnreadCount;return void 0!==o&&o===t||(this.totalUnreadCount=t,this.service.emit("onTotalUnreadCountChanged",t)),t}digestUnreadCountChange(){this._digest()}_digest(){var t=this.totalUnreadCount,o=this.service.model.getAll().reduce(((t,o)=>t+(o.unreadCount||0)),0);this.core.logger.log(`V2NIMConversation::digestUnreadCountChange:oldUnreadCount ${t}, newUnreadCount ${o}`),t!==o&&(this.totalUnreadCount=o,this.service.emit("onTotalUnreadCountChanged",o)),Object.keys(this.unreadCountByFilter).forEach((t=>{var o=JSON.parse(t),a=this.getUnreadCountByFilter(o),m=this.unreadCountByFilter[t];this.unreadCountByFilter[t]=a,o.equals=equals.bind(o),m!==a&&this.service.emit("onUnreadCountChangedByFilter",o,a)}))}getUnreadCountByIds(t){return t.reduce(((t,o)=>{var a=this.service.model.getById(o);return t+(a&&a.unreadCount||0)}),0)}getUnreadCountByFilter(t){var o=this.service.model.count();return this.service.model.getByOption(0,o,{conversationTypes:t.conversationTypes,conversationGroupIds:t.conversationGroupId?[t.conversationGroupId]:void 0,ignoreMuted:t.ignoreMuted}).conversationList.reduce(((t,o)=>t+(o.unreadCount||0)),0)}addFilter(t){var o=generateFilterKey(t);if(void 0!==this.unreadCountByFilter[o])throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_RESOURCE_ALREADY_EXIST});var a=JSON.parse(o),m=this.getUnreadCountByFilter(a);this.unreadCountByFilter[o]=m,this.service.emit("onUnreadCountChangedByFilter",a,m)}deleteFilter(t){var o=generateFilterKey(t);if(void 0===this.unreadCountByFilter[o])throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_RESOURCE_NOT_EXIST});delete this.unreadCountByFilter[o]}}function generateFilterKey(t){var{conversationTypes:o}=t;return o&&(o=o.sort()),JSON.stringify({conversationGroupId:t.conversationGroupId,conversationTypes:o,ignoreMuted:t.ignoreMuted})}function equals(t){return JSON.stringify(this)===generateFilterKey(t)}var Mi={createTime:{type:"number"},updateTime:{type:"number"}};function formatConversationGroups(t){return t&&t.length>0?t.map((t=>formatConversationGroup(t))):[]}function formatConversationGroup(t){return format(Mi,t)}function formatFailedMap(t){var o=JSON.parse(t);return Object.keys(o).map((t=>({conversationId:t,error:new V2NIMErrorImpl({code:o[t]})})))}var _i,Ei={type:{type:"number"},deleteVersion:{type:"number"},conversationIds:{type:"object"}};function formatConversationGroupNotify(t){return format(Ei,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"}(_i||(_i={}));class V2NIMConversationComputeImpl{constructor(t,o){this.core=t,this.service=o}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 o,a,m,u,h;if(0===t.type)return t;var g=this.core.V2NIMConversationIdUtil.parseConversationType(t.conversationId),I=this.core.V2NIMConversationIdUtil.parseConversationTargetId(t.conversationId),M={};if(t.lastReadTime||(M.lastReadTime=this.service.model.getReadTime(t.conversationId)),(null===(o=this.core.V2NIMSettingService)||void 0===o?void 0:o.name)&&(M.mute=this.core.V2NIMSettingService.getConversationMuteStatus(t.conversationId)),1===g&&this.hasUserService){var _,E=this.core.V2NIMUserService.model.getUser(I),S=this.hasFriendService?this.core.V2NIMFriendService.model.getFriend(I):void 0;t.conversationId!==(null===(a=t.lastMessage)||void 0===a?void 0:a.messageRefer.conversationId)||0!==(null===(m=t.lastMessage)||void 0===m?void 0:m.lastMessageState)&&2!==(null===(u=t.lastMessage)||void 0===u?void 0:u.lastMessageState)||(_=null===(h=t.lastMessage)||void 0===h?void 0:h.senderName),M.name=(null==S?void 0:S.alias)||(null==E?void 0:E.name)||_||I,M.avatar=(null==E?void 0:E.avatar)||""}else if(2===g&&this.hasTeamService){var T=this.core.V2NIMTeamService.model.getById(I,1);M.name=(null==T?void 0:T.name)||I,M.avatar=(null==T?void 0:T.avatar)||""}else if(3===g&&this.hasTeamService){var C=this.core.V2NIMTeamService.model.getById(I,2);M.name=(null==C?void 0:C.name)||I,M.avatar=(null==C?void 0:C.avatar)||""}return Object.assign(t,M),t}computeReadTimeForMark(t){var o,a,m,u=t.conversationId,h=this.service.model.getReadTime(u);if(null===(a=null===(o=null==t?void 0:t.lastMessage)||void 0===o?void 0:o.messageRefer)||void 0===a?void 0:a.createTime)m=t.lastMessage.messageRefer.createTime;else{if(!this.core.timeOrigin.checkNodeReliable())return h||0;m=this.core.timeOrigin.getNTPTime()}return m}}class V2NIMConversationHandlerImpl{constructor(t,o){this.core=t,this.service=o,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 o,a,m;if(this.ifEnabled){if(null===(o=null==t?void 0:t.content)||void 0===o?void 0:o.p2p)for(var[u,h]of Object.entries(t.content.p2p))this.model.updateReadTime(this.core.V2NIMConversationIdUtil.p2pConversationId(u),h),this.service.emit("onConversationReadTimeUpdated",this.core.V2NIMConversationIdUtil.p2pConversationId(u),h);if(null===(m=null===(a=null==t?void 0:t.content)||void 0===a?void 0:a.team)||void 0===m?void 0:m.m_map)for(var[g,I]of Object.entries(t.content.team.m_map))this.model.updateReadTime(this.core.V2NIMConversationIdUtil.teamConversationId(g),I),this.service.emit("onConversationReadTimeUpdated",this.core.V2NIMConversationIdUtil.teamConversationId(g),I)}}syncSuperTeamReadTimeHandler(t){var o,a;if(this.ifEnabled&&(null===(a=null===(o=null==t?void 0:t.content)||void 0===o?void 0:o.superTeam)||void 0===a?void 0:a.m_map))for(var[m,u]of Object.entries(t.content.superTeam.m_map))this.model.updateReadTime(this.core.V2NIMConversationIdUtil.superTeamConversationId(m),u),this.service.emit("onConversationReadTimeUpdated",this.core.V2NIMConversationIdUtil.superTeamConversationId(m),u)}v2MultiDeviceConversationReadTimeHandler(t){var o;this.ifEnabled&&(null===(o=null==t?void 0:t.content)||void 0===o?void 0:o.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 o;this.ifEnabled&&(null===(o=null==t?void 0:t.content)||void 0===o?void 0:o.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,o){this.core=t,this.service=o,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,...o){var a,m,u=`${this.service.name}::emit ${t.toString()}`;if("onConversationCreated"===t){var h=o[0];this.logger.log(`${u}`,`id:${h.conversationId};unread:${h.unreadCount};lastMsg:${null===(a=h.lastMessage)||void 0===a?void 0:a.messageRefer.messageClientId}/${null===(m=h.lastMessage)||void 0===m?void 0:m.messageRefer.messageServerId}`)}else if("onConversationChanged"===t){var g=o[0];this.logger.log(`${u}`,g.map((t=>{var o,a;return`id:${t.conversationId};unread:${t.unreadCount};lastMsg:${null===(o=t.lastMessage)||void 0===o?void 0:o.messageRefer.messageClientId}/${null===(a=t.lastMessage)||void 0===a?void 0:a.messageRefer.messageServerId}`})))}else this.logger.log(`${u}`,...o)}conversationOnlineSyncNotify(t,o){var a;!1!==(null===(a=null==o?void 0:o.messageConfig)||void 0===a?void 0:a.lastMessageUpdateEnabled)&&(t.content.info=deserialize(t.content.info,invertSerializeItem(Ii)),t.content.data=deserialize(t.content.data,invertSerializeItem(fi)),o&&(t.content.data.lastMessage=formatLastMessageFromMessage(this.core,o,0)),t.content.datas=[t.content.data],this.service.handler.v2ConversationNotifySyncOnlineHandler.call(this,t))}sendMessage(t,o){var a,m;1===o&&!0===(null===(a=t.messageConfig)||void 0===a?void 0:a.historyEnabled)||!1!==(null===(m=null==t?void 0:t.messageConfig)||void 0===m?void 0:m.lastMessageUpdateEnabled)&&this.versionCache.updateModelWithLastMessage(t.conversationId,t,2,o)}deleteMessages(t){var o=t.map((t=>t.messageRefer.conversationId));this.versionCache.backfillLastMsg(o,!0)}revokeMessages(t){this.versionCache.updateModelByRevoke(t)}roamingOrOfflineMsgs(t){var o=uniq(t.map((t=>t.conversationId)));this.versionCache.backfillLastMsg(o,!1)}setMute(t,o){var a=this.model.getById(t);a&&a.mute!==o&&(a.mute=o,this.model.upsert(a),this.service.triggerConversationChanged([a]))}}class V2NIMConversationServiceImpl extends V2Service{constructor(t,o={}){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:gi,cmdConfig:yi}),this.setOptions(o),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,...o){return this.event.beforeEmit(t,...o),super.emit(t,...o)}checkEnable(){if(!0!==this.core.options.enableV2CloudConversation)throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_MISUSE,detail:{reason:"V2CloudConversation is not enabled"}})}getConversationList(t,o){this.checkEnable(),this.checkV2(),validate({offset:{type:"number",min:0}},{offset:t},"",!0),validate({limit:{type:"number",min:1}},{limit:o},"",!0),this.core.V2NIMLoginService.checkIllegalState();var a=this.model.getByOption(t,o,{});return a.conversationList=this.compute.computeConvs(a.conversationList),Promise.resolve(a)}getConversationListByOption(t,o,a){this.checkEnable(),this.checkV2(),validate({offset:{type:"number",min:0}},{offset:t},"",!0),validate({limit:{type:"number",min:1}},{limit:o},"",!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:a},"",!0),this.core.V2NIMLoginService.checkIllegalState();var m=this.model.getByOption(t,o,a);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 o=this.model.getById(t);if(o)return this.compute.computeConv(o);throw new V2NIMErrorImpl({code:Me.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 o=t.map((t=>this.model.getById(t))).filter((t=>!!t));return o=this.compute.computeConvs(o)}))}createConversation(t){return __awaiter(this,void 0,void 0,(function*(){this.checkEnable(),this.checkV2(),validateConversationId(this.core.account,t);var o=get(yield this.core.sendCmd("v2ConversationCreate",{tag:{conversationId:t}}),"content.data"),a=formatConversationField(this.core,o);this.versionCache.compareAndUpdateModel([a]);var m=this.model.getById(t);if(m)return this.compute.computeConv(m);throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_RESOURCE_NOT_EXIST})}))}deleteConversation(t,o){return __awaiter(this,void 0,void 0,(function*(){this.checkEnable(),this.checkV2(),validateConversationId(this.core.account,t),validate({clearMessage:{type:"boolean",required:!1}},{clearMessage:o},"",!0);try{yield this.core.sendCmd("v2ConversationDelete",{tag:{conversationId:t,clearMessage:Number(o||!1)}})}catch(o){this.logger.warn(`V2NIMConversationService:deleteConversation: delete conversation failed: ${t}`)}this.model.getById(t)&&(o&&this.core.eventBus.emit("V2NIMConversationService/deleteConversation",[t]),this.versionCache.compareAndDeleteModel([t]))}))}deleteConversationListByIds(t,o){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:o},"",!0);var a=formatFailedMap(get(yield this.core.sendCmd("v2ConversationsDelete",{tag:{conversationIds:JSON.stringify(t),clearMessage:Number(o||!1)}}),"content.info.failedMap")).filter((t=>t.error.code!==Me.V2NIM_ERROR_CODE_CONVERSATION_NOT_EXIST||!this.model.getById(t.conversationId)));return a.length<t.length&&(o&&this.core.eventBus.emit("V2NIMConversationService/deleteConversation",t),this.versionCache.compareAndDeleteModel(t)),a}))}getStickTopConversationList(){return __awaiter(this,void 0,void 0,(function*(){return this.checkV2(),this.core.V2NIMLoginService.checkIllegalState(),this.model.getStickTopList()}))}stickTopConversation(t,o){return __awaiter(this,void 0,void 0,(function*(){this.checkEnable(),this.checkV2(),validateConversationId(this.core.account,t),validate({stickTop:{type:"boolean"}},{stickTop:o},"",!0);var a=get(yield this.core.sendCmd("v2ConversationSetTop",{tag:{conversationId:t,stickTop:Number(o)}}),"content.data"),m=formatConversationField(this.core,a);this.versionCache.compareAndUpdateModel([m])}))}updateConversation(t,o){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:o},"",!0);var a=get(yield this.core.sendCmd("v2ConversationUpdate",{tag:Object.assign({conversationId:t},o)}),"content.data"),m=formatConversationField(this.core,a);this.versionCache.compareAndUpdateModel([m])}))}updateConversationLocalExtension(t,o){return __awaiter(this,void 0,void 0,(function*(){this.checkEnable(),this.checkV2(),validateConversationId(this.core.account,t),validate({localExtension:{type:"string"}},{localExtension:o},"",!0);var a=this.model.getById(t);if(!a)throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_RESOURCE_NOT_EXIST});if(a.localExtension!==o){var m=Object.assign(Object.assign({},a),{localExtension:o});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 o=this.unread.getUnreadCountByIds(t);return Promise.resolve(o)}getUnreadCountByFilter(t){this.checkEnable(),this.checkV2(),this.valiteFilter(t);var o=this.unread.getUnreadCountByFilter(t);return Promise.resolve(o)}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 o=yield this.core.sendCmd("v2ConversationsUnreadClear",{tag:{conversationIds:JSON.stringify(t)}}),a=formatConversationFields(this.core,get(o,"content.datas")),m=formatFailedMap(get(o,"content.info.failedMap"));return this.versionCache.compareAndUpdateModel(a),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:hi},{types:t},"",!0);var o=get(yield this.core.sendCmd("v2ConversationClearTypeUnread",{tag:{conversationType:JSON.stringify(t)}}),"content.info");this.versionCache.compareAndClearUnreadInModel(o)}))}markConversationRead(t){return __awaiter(this,void 0,void 0,(function*(){this.checkEnable(),this.checkV2(),this.checkLogin(),validateConversationId(this.core.account,t);var o=this.model.getById(t);if(!o)throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"Conversation not exist"}});var a=this.core.V2NIMConversationIdUtil.parseConversationTargetId(t),m=this.core.V2NIMConversationIdUtil.parseConversationType(t),u=this.model.getReadTime(t),h=this.compute.computeReadTimeForMark(o);return u>=h?(this.logger.log(`V2Conv::markConversationRead currentReadTime >= readTime ${t},${u},${h}`),u):(3===m?yield this.core.sendCmd("v2MarkSuperTeamReadTime",{timetag:h,to:a}):yield this.core.sendCmd("v2MarkConversationReadTime",{scene:1===m?0:2===m?1:2,timetag:h,to:a}),this.model.updateReadTime(t,h),h)}))}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 o;this.checkEnable(),this.checkV2(),this.checkLogin(),this.valiteFilter(t),0===(null===(o=t.conversationTypes)||void 0===o?void 0:o.length)&&delete t.conversationTypes,this.unread.addFilter(t)}unsubscribeUnreadCountByFilter(t){var o;this.checkEnable(),this.checkV2(),this.checkLogin(),this.valiteFilter(t),0===(null===(o=t.conversationTypes)||void 0===o?void 0:o.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:Me.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 Si={"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"},Ti="V2NIMConversationGroupService",Ci={groupId:1,name:2,serverExtension:3,createTime:4,updateTime:5},Ni={v2ConversationGroupCreate:{sid:28,cid:9,service:Ti,params:[{type:"Property",name:"tag",reflectMapper:{conversationIds:1,name:2,serverExtension:3}}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Ci)},{type:"PropertyArray",name:"conversations",reflectMapper:invertSerializeItem(fi)},{type:"Property",name:"info",reflectMapper:{1:"failedMap"}}]},v2ConversationGroupDelete:{sid:28,cid:10,service:Ti,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:Ti,params:[{type:"Property",name:"tag",reflectMapper:{groupId:1,name:2,serverExtension:3}}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Ci)}]},v2ConversationGroupGet:{sid:28,cid:12,service:Ti,params:[{type:"Property",name:"tag",reflectMapper:{groupId:1}}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Ci)}]},v2ConversationGroupsGet:{sid:28,cid:13,service:Ti,params:[{type:"Property",name:"tag",reflectMapper:{groupIds:1}}],response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(Ci)},{type:"Property",name:"info",reflectMapper:{1:"failedMap"}}]},v2ConversationGroupListGet:{sid:28,cid:14,service:Ti,response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(Ci)}]},v2ConversationGroupAddTo:{sid:28,cid:15,service:Ti,params:[{type:"Property",name:"tag",reflectMapper:{groupId:1,conversationIds:2}}],response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(fi)},{type:"Property",name:"info",reflectMapper:{1:"failedMap"}}]},v2ConversationGroupRemoveFrom:{sid:28,cid:16,service:Ti,params:[{type:"Property",name:"tag",reflectMapper:{groupId:1,conversationIds:2}}],response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(fi)},{type:"Property",name:"info",reflectMapper:{1:"failedMap"}}]},v2ConversationGroupNotifySyncOnline:{sid:28,cid:22,service:Ti,response:[{type:"Property",name:"info",reflectMapper:{1:"type",2:"deleteVersion",3:"conversationIds"}},{type:"Property",name:"data",reflectMapper:invertSerializeItem(Ci)}]}};class V2NIMConversationGroupServiceImpl extends V2Service{constructor(t,o={}){super("V2NIMConversationGroupService",t),this.config={},this.core._registerDep(V2NIMConversationServiceImpl,"V2NIMConversationService"),"v2"===this.core.options.apiVersion&&!0===this.core.options.enableV2CloudConversation&&(registerParser({cmdMap:Si,cmdConfig:Ni}),this.setOptions(o))}setOptions(t){this.config=Object.assign(this.config,t)}emit(t,...o){var a=`${this.name}::emit ${t.toString()}`;if("onConversationsAddedToGroup"===t){var m=o[0],u=o[1];this.logger.log(`${a}`,`groupId:${m}`,`conversations:${u.map((t=>t.conversationId)).join(",")}`)}else this.logger.log(`${a}`,...o);return super.emit(t,...o)}get ifEnabled(){return!0===this.core.options.enableV2CloudConversation}checkEnable(){if(!0!==this.core.options.enableV2CloudConversation)throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_MISUSE,detail:{reason:"V2CloudConversation is not enabled"}})}createConversationGroup(t,o,a){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:o},"",!0),validate({conversationIds:{type:"array",itemType:"string",required:!1}},{conversationIds:a},"",!0);var m=yield this.core.sendCmd("v2ConversationGroupCreate",{tag:{name:t,serverExtension:o||"",conversationIds:a&&JSON.stringify(a)}}),u=formatConversationGroup(get(m,"content.data")),h=formatConversationFields(this.core,get(m,"content.conversations")),g=formatFailedMap(get(m,"content.info.failedMap"));return this.emit("onConversationGroupCreated",u),h.length>0&&(this.core.V2NIMConversationService.versionCache.compareAndUpdateModel(h),this.emit("onConversationsAddedToGroup",u.groupId,h.map((t=>this.core.V2NIMConversationService.model.getById(t.conversationId))).filter((t=>!!t)))),{group:u,failedList:g}}))}deleteConversationGroup(t){return __awaiter(this,void 0,void 0,(function*(){this.checkEnable(),this.checkV2(),validate({groupId:{type:"string",allowEmpty:!1}},{groupId:t},"",!0);var o=formatConversationGroupNotify(get(yield this.core.sendCmd("v2ConversationGroupDelete",{tag:{groupId:t}}),"content.info"));this.core.V2NIMConversationService.versionCache.compareAndDeleteGroupInModel(o.deleteVersion,t),this.emit("onConversationGroupDeleted",t)}))}updateConversationGroup(t,o,a){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:o},"",!0),validate({serverExtension:{type:"string",required:!1}},{serverExtension:a},"",!0),void 0===o&&void 0===a)throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_INVALID_PARAMETER});var m=formatConversationGroup(get(yield this.core.sendCmd("v2ConversationGroupUpdate",{tag:{groupId:t,name:o,serverExtension:a}}),"content.data"));this.emit("onConversationGroupChanged",m)}))}addConversationsToGroup(t,o){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:o},"",!0);var a=yield this.core.sendCmd("v2ConversationGroupAddTo",{tag:{groupId:t,conversationIds:JSON.stringify(o)}}),m=get(a,"content.info.failedMap")||"",u=[];m&&(u=formatFailedMap(m));var h=formatConversationFields(this.core,get(a,"content.datas"));this.core.V2NIMConversationService.versionCache.compareAndUpdateModel(h);var g=h.map((t=>this.core.V2NIMConversationService.model.getById(t.conversationId))).filter((t=>!!t));return g.length>0&&this.emit("onConversationsAddedToGroup",t,g),u}))}removeConversationsFromGroup(t,o){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:o},"",!0);var a=yield this.core.sendCmd("v2ConversationGroupRemoveFrom",{tag:{groupId:t,conversationIds:JSON.stringify(o)}}),m=get(a,"content.info.failedMap")||"",u=[];m&&(u=formatFailedMap(m));var h=formatConversationFields(this.core,get(a,"content.datas"));return this.core.V2NIMConversationService.versionCache.compareAndUpdateModel(h),this.emit("onConversationsRemovedFromGroup",t,h.map((t=>t.conversationId))),u}))}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 o=formatConversationGroups(get(yield this.core.sendCmd("v2ConversationGroupsGet",{tag:{groupIds:t&&JSON.stringify(t)}}),"content.datas"));return t.map((t=>o.filter((o=>o.groupId===t))[0])).filter((t=>!!t))}))}v2ConversationGroupNotifySyncOnlineHandler(t){if(this.ifEnabled){var o=formatConversationGroupNotify(get(t,"content.info")),{type:a,deleteVersion:m,conversationIds:u}=o,h=formatConversationGroup(get(t,"content.data"));if(this.core.logger.log("v2ConversationGroupNotifySyncOnlineHandler",o,h),1===a)this.emit("onConversationGroupCreated",h),u&&u.length>0&&this.emit("onConversationsAddedToGroup",h.groupId,u.map((t=>this.core.V2NIMConversationService.model.getById(t))).filter((t=>!!t)));else if(2===a)this.emit("onConversationGroupDeleted",h.groupId),this.core.V2NIMConversationService.versionCache.compareAndDeleteGroupInModel(m,h.groupId);else if(3===a)this.emit("onConversationGroupChanged",h);else if(4===a){var g=u.map((t=>this.core.V2NIMConversationService.model.getById(t))).filter((t=>!!t));this.emit("onConversationsAddedToGroup",h.groupId,g)}else 5===a&&this.emit("onConversationsRemovedFromGroup",h.groupId,u)}}}class V2NIMMessageConverterImpl{constructor(t){this.name="V2NIMMessageConverter",this.core=t}messageSerialization(t){if(!t)return null;var o=serialize(t,Pr);return JSON.stringify(o)}messageDeserialization(t){var o,a,m,u,h,g,I,M,_,E,S,T,C,N,A,O,R,b,V,k,P,L,w;if(!t)return null;try{var D=deserialize(JSON.parse(t),Lr);return D.sendingState=0,1!==D.conversationType||D.senderId!==this.core.account&&D.receiverId!==this.core.account?2===D.conversationType?D.conversationId=this.core.V2NIMConversationIdUtil.teamConversationId(D.receiverId):3===D.conversationType&&(D.conversationId=this.core.V2NIMConversationIdUtil.superTeamConversationId(D.receiverId)):D.conversationId=this.core.V2NIMConversationIdUtil.p2pConversationId(D.senderId===this.core.account?D.receiverId:D.senderId),D.threadReply&&(D.threadReply.conversationType=D.conversationType,D.threadReply=completeMessageRefer(this.core,D.threadReply)),D.threadRoot&&(D.threadRoot.conversationType=D.conversationType,D.threadRoot=completeMessageRefer(this.core,D.threadRoot)),[1,3,2,0].includes(D.conversationType)||this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid conversationType(enum): ${D.conversationType}`),D.senderId&&"string"!=typeof D.senderId&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid senderId(string): ${D.senderId}`),D.receiverId&&"string"!=typeof D.receiverId&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid receiverId(string): ${D.receiverId}`),"createTime"in D&&isNaN(D.createTime)&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid createTime(number): ${D.createTime}`),[2,7,12,100,6,1,-1,4,5,11,0,10,3].includes(D.messageType)||this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid messageType(enum): ${D.messageType}`),"subType"in D&&isNaN(D.subType)&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid subType(number): ${D.subType}`),D.messageClientId&&"string"!=typeof D.messageClientId&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid messageClientId(string): ${D.messageClientId}`),D.messageServerId&&"string"!=typeof D.messageServerId&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid messageServerId(string): ${D.messageServerId}`),D.attachment&&"object"!=typeof D.attachment&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid attachment(object): ${D.attachment}`),D.text&&"string"!=typeof D.text&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid text(string): ${D.text}`),D.serverExtension&&"string"!=typeof D.serverExtension&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid serverExtension(string): ${D.serverExtension}`),D.callbackExtension&&"string"!=typeof D.callbackExtension&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid callbackExtension(string): ${D.callbackExtension}`),(null===(o=D.pushConfig)||void 0===o?void 0:o.pushContent)&&"string"!=typeof D.pushConfig.pushContent&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid pushContent(string): ${D.pushConfig.pushContent}`),(null===(a=D.pushConfig)||void 0===a?void 0:a.pushPayload)&&"string"!=typeof D.pushConfig.pushPayload&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid pushPayload(string): ${D.pushConfig.pushPayload}`),(null===(m=D.pushConfig)||void 0===m?void 0:m.forcePushContent)&&"string"!=typeof D.pushConfig.forcePushContent&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid forcePushContent(string): ${D.pushConfig.forcePushContent}`),(null===(u=D.pushConfig)||void 0===u?void 0:u.forcePushAccountIds)&&!Array.isArray(D.pushConfig.forcePushAccountIds)&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid forcePushAccountIds(array): ${D.pushConfig.forcePushAccountIds}`),(null===(h=D.routeConfig)||void 0===h?void 0:h.routeEnvironment)&&"string"!=typeof D.routeConfig.routeEnvironment&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid routeEnvironment(string): ${D.routeConfig.routeEnvironment}`),(null===(g=D.antispamConfig)||void 0===g?void 0:g.antispamBusinessId)&&"string"!=typeof D.antispamConfig.antispamBusinessId&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid antispamBusinessId(string): ${D.antispamConfig.antispamBusinessId}`),(null===(I=D.antispamConfig)||void 0===I?void 0:I.antispamCustomMessage)&&"string"!=typeof D.antispamConfig.antispamCustomMessage&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid antispamCustomMessage(string): ${D.antispamConfig.antispamCustomMessage}`),(null===(M=D.antispamConfig)||void 0===M?void 0:M.antispamCheating)&&"string"!=typeof D.antispamConfig.antispamCheating&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid antispamCheating(string): ${D.antispamConfig.antispamCheating}`),(null===(_=D.antispamConfig)||void 0===_?void 0:_.antispamExtension)&&"string"!=typeof D.antispamConfig.antispamExtension&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid antispamExtension(string): ${D.antispamConfig.antispamExtension}`),(null===(E=D.robotConfig)||void 0===E?void 0:E.accountId)&&"string"!=typeof D.robotConfig.accountId&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid accountId(string): ${D.robotConfig.accountId}`),(null===(S=D.robotConfig)||void 0===S?void 0:S.topic)&&"string"!=typeof D.robotConfig.topic&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid topic(string): ${D.robotConfig.topic}`),(null===(T=D.robotConfig)||void 0===T?void 0:T.function)&&"string"!=typeof D.robotConfig.function&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid function(string): ${D.robotConfig.function}`),(null===(C=D.robotConfig)||void 0===C?void 0:C.customContent)&&"string"!=typeof D.robotConfig.customContent&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid customContent(string): ${D.robotConfig.customContent}`),(null===(N=D.threadRoot)||void 0===N?void 0:N.senderId)&&"string"!=typeof D.threadRoot.senderId&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid senderId(string): ${D.threadRoot.senderId}`),(null===(A=D.threadRoot)||void 0===A?void 0:A.receiverId)&&"string"!=typeof D.threadRoot.receiverId&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid receiverId(string): ${D.threadRoot.receiverId}`),(null===(O=D.threadRoot)||void 0===O?void 0:O.messageClientId)&&"string"!=typeof D.threadRoot.messageClientId&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid messageClientId(string): ${D.threadRoot.messageClientId}`),(null===(R=D.threadRoot)||void 0===R?void 0:R.messageServerId)&&"string"!=typeof D.threadRoot.messageServerId&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid messageServerId(string): ${D.threadRoot.messageServerId}`),D.threadRoot&&"createTime"in D.threadRoot&&isNaN(D.threadRoot.createTime)&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid createTime(number): ${D.threadRoot.createTime}`),D.threadRoot&&![1,3,2,0].includes(D.threadRoot.conversationType)&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid conversationType(enum): ${D.threadRoot.conversationType}`),(null===(b=D.threadRoot)||void 0===b?void 0:b.conversationId)&&"string"!=typeof D.threadRoot.conversationId&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid conversationId(string): ${D.threadRoot.conversationId}`),(null===(V=D.threadReply)||void 0===V?void 0:V.senderId)&&"string"!=typeof D.threadReply.senderId&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid senderId(string): ${D.threadReply.senderId}`),(null===(k=D.threadReply)||void 0===k?void 0:k.receiverId)&&"string"!=typeof D.threadReply.receiverId&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid receiverId(string): ${D.threadReply.receiverId}`),(null===(P=D.threadReply)||void 0===P?void 0:P.messageClientId)&&"string"!=typeof D.threadReply.messageClientId&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid messageClientId(string): ${D.threadReply.messageClientId}`),(null===(L=D.threadReply)||void 0===L?void 0:L.messageServerId)&&"string"!=typeof D.threadReply.messageServerId&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid messageServerId(string): ${D.threadReply.messageServerId}`),D.threadReply&&"createTime"in D.threadReply&&isNaN(D.threadReply.createTime)&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid createTime(number): ${D.threadReply.createTime}`),D.threadReply&&![1,3,2,0].includes(D.threadReply.conversationType)&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid conversationType(enum): ${D.threadReply.conversationType}`),(null===(w=D.threadReply)||void 0===w?void 0:w.conversationId)&&"string"!=typeof D.threadReply.conversationId&&this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid conversationId(string): ${D.threadReply.conversationId}`),delete D.__clientExt,delete D.userUpdateTime,D}catch(o){return this.core.logger.error(`V2NIMMessageConverterImpl.messageDeserialization: invalid message string: ${t}`),null}}}var Ai="V2NIMMessageLogUtil",Oi={"30_6":"v2GetMessageList","33_2":"v2GetMessageListByRefers","30_9":"v2ClearRoamingMessage","30_18":"v2ClearHistoryMessage","7_118":"onClearHistoryMessage","4_24":"syncClearHistoryMessage","31_23":"v2GetTeamMessageList","32_14":"v2GetSuperTeamMessageList"},Ri={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},bi=[{type:"Long",name:"beginTime"},{type:"Long",name:"endTime"},{type:"Long",name:"lastMsgId"},{type:"Int",name:"limit"},{type:"Bool",name:"direction"},{type:"LongArray",name:"msgTypes"}],Vi={v2GetMessageList:{sid:30,cid:6,service:Ai,params:[{type:"String",name:"to"},...bi],response:[{type:"PropertyArray",name:"msgs",reflectMapper:invertSerializeItem(Pr)}]},v2GetMessageListByRefers:{sid:33,cid:2,service:Ai,params:[{type:"PropertyArray",name:"tag",reflectMapper:Pr,select:["conversationType","senderId","receiverId","createTime","messageServerId"]}],response:[{type:"PropertyArray",name:"msgs",reflectMapper:invertSerializeItem(Pr)}]},v2ClearRoamingMessage:{sid:30,cid:9,service:Ai,params:[{type:"StrArray",name:"conversationIds"}]},v2ClearHistoryMessage:{sid:30,cid:18,service:Ai,params:[{type:"Property",name:"tag",reflectMapper:Ri}],response:[{type:"Long",name:"timetag"}]},v2GetTeamMessageList:{sid:31,cid:23,service:Ai,params:[{type:"Long",name:"to"},...bi],response:[{type:"PropertyArray",name:"msgs",reflectMapper:invertSerializeItem(Pr)}]},v2GetSuperTeamMessageList:{sid:32,cid:14,service:Ai,params:[{type:"Long",name:"to"},...bi],response:[{type:"PropertyArray",name:"msgs",reflectMapper:invertSerializeItem(Pr)}]},onClearHistoryMessage:{sid:7,cid:118,service:Ai,response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Ri)}]},syncClearHistoryMessage:{sid:4,cid:24,service:Ai,response:[{type:"PropertyArray",name:"data",reflectMapper:invertSerializeItem(Ri)}]}};class V2NIMMessageLogUtil extends V2Service{constructor(t){super("V2NIMMessageLogUtil",t),this.clearHistoryMessageFn=t=>{var o=formatClearHistoryNotification(this.core,t);this.emitClearHistoryMessage([o])},this.core=t,this.service=this.core.V2NIMMessageService,"v2"===this.core.options.apiVersion&&(registerParser({cmdMap:Oi,cmdConfig:Vi}),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(Kt,{messageRefers:t},"",!0),0===t.length)throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"getMessageListByRefers: messageRefers cannot be an empty array"}});var o=[],a=t.map((t=>{var a=this.service.model.getMessageById(t.messageClientId);return!a&&t.messageServerId&&"0"!==t.messageServerId&&o.push(t),a})),m=[];if(o.length>0){var u=yield this.core.sendCmd("v2GetMessageListByRefers",{tag:o});m=u.content.msgs}return a.map(((o,a)=>{if(o)return o;var u=t[a],h=m.find((t=>t.messageServerId===u.messageServerId));return h?completeMessage(this.core,h):void 0})).filter((t=>void 0!==t&&!this.service._filterMessage(t)))}))}getMessageList(t){var o;return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(zt,t,"",!0),validateConversationId(this.core.account,t.conversationId);var a=this.core.V2NIMConversationIdUtil.parseConversationType(t.conversationId),m=this.core.V2NIMConversationIdUtil.parseConversationTargetId(t.conversationId),u=1===a?"v2GetMessageList":2===a?"v2GetTeamMessageList":"v2GetSuperTeamMessageList",h=t.beginTime||0,g=t.endTime||0;if(0!==h&&0!==g&&h>g)throw new V2NIMErrorImpl({code:Me.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===g)g=t.anchorMessage.createTime;else if(g!==t.anchorMessage.createTime)throw new V2NIMErrorImpl({code:Me.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===h)h=t.anchorMessage.createTime;else if(h!==t.anchorMessage.createTime)throw new V2NIMErrorImpl({code:Me.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 M=null===(o=t.anchorMessage)||void 0===o?void 0:o.messageServerId,_=yield this.core.sendCmd(u,{beginTime:h,endTime:g,lastMsgId:M||0,limit:t.limit||50,direction:I,msgTypes:t.messageTypes?t.messageTypes.slice():[],to:m}),{content:E}=_,S=E.msgs.map((t=>completeMessage(this.core,t)));return M&&(S=S.filter((t=>t.messageServerId!==M))),this.getMessageListMonkeyPatch(S,t)}))}getMessageListMonkeyPatch(t,o){var a=o.conversationId,m=t,u=m.reduce(((t,o)=>(t[o.messageClientId]=!0,t)),{}),h=this.service.model.getMessagesByConversationId(a);h=h.sort(((t,a)=>1===o.direction?t.createTime-a.createTime:a.createTime-t.createTime));var g=0,I=o.beginTime||0,M=o.endTime||0;o.anchorMessage&&(0===o.direction?M=o.anchorMessage.createTime:I=o.anchorMessage.createTime,g=h.findIndex((t=>{var a;return t.messageClientId===(null===(a=o.anchorMessage)||void 0===a?void 0:a.messageClientId)})),g+=1);for(var _=g;_<h.length;_++){var E=h[_],S=!u[E.messageClientId],T=void 0===E.sendingState||1===E.sendingState,C=E.conversationId===a,N=E.createTime>I&&(E.createTime<M||0===M),A=!o.messageTypes||o.messageTypes.includes(E.messageType);S&&T&&C&&N&&A&&m.push(h[_])}return(m=m.sort(((t,a)=>1===o.direction?t.createTime-a.createTime:a.createTime-t.createTime))).slice(0,o.limit||50)}clearHistoryMessage(t){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(Xt,t,"",!0),validateConversationId(this.core.account,t.conversationId);var{conversationId:o,deleteRoam:a,onlineSync:m,serverExtension:u}=t,h=this.core.V2NIMConversationIdUtil.parseConversationType(o),g=this.core.V2NIMConversationIdUtil.parseConversationTargetId(o),I={deleteRoam:a,onlineSync:m,serverExtension:u,conversationType:h};1===h?I.receiverId=g:I.teamId=g;var M=this.core.timeOrigin.getNTPTime();(t.clearMode=t.clearMode||0,0===t.clearMode)&&(M=(yield this.core.sendCmd("v2ClearHistoryMessage",{tag:I})).content.timetag);2===t.clearMode&&Ae.localStorage.setItem(`nim_${this.core.account}_${o}_clearTime`,M.toString()),this.core.eventBus.emit("forwardSend/V2NIMMessageLogService/clearHistoryMessage",Object.assign(Object.assign({},I),{deleteTime:M})),this.emitClearHistoryMessage([{deleteTime:M,serverExtension:u,conversationId:o}])}))}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 o=[];try{o=t.map((t=>{var o=this.core.V2NIMConversationIdUtil.parseConversationTargetId(t);return getSessionIdFromConvInfo(this.core.V2NIMConversationIdUtil.parseConversationType(t),o)}))}catch(o){throw this.logger.error(`V2NIMMessage::clearRoamingMessage with ${t}`,o),new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_PARAMETER_ERROR,detail:{reason:"Failed to create session",rawData:`${t}`}})}yield this.core.sendCmd("v2ClearRoamingMessage",{conversationIds:o})}))}syncClearHistoryMessageHandler(t){var o=t.content.data.map((t=>formatClearHistoryNotification(this.core,t)));this.emitClearHistoryMessage(o)}onClearHistoryMessageHandler(t){var o=formatClearHistoryNotification(this.core,t.content.data);this.emitClearHistoryMessage([o])}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)}}var ki="V2NIMMessageExtendUtil",Pi={"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"},Li={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"}},wi={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"}},Di={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"}},Ui={accid:1,serverExtension:2,createTime:{id:3,retType:"number"},updateTime:{id:4,retType:"number"}},xi={collectionId:1,collectionType:{id:2,retType:"number"},collectionData:3,serverExtension:4,uniqueId:5,createTime:{id:6,retType:"number"},updateTime:{id:7,retType:"number"}},Fi={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(",")}},Bi={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(",")}},$i=Object.assign(Object.assign({},Fi),{conversationLimit:4}),ji={v2PinMessage:{sid:33,cid:15,service:ki,params:[{type:"Property",name:"msg",reflectMapper:Pr,select:["conversationType","receiverId","senderId","createTime","messageClientId","messageServerId"]},{type:"Property",name:"msgPin",reflectMapper:Ui}],response:[{type:"Long",name:"timetag"}]},v2UnpinMessage:{sid:33,cid:17,service:ki,params:[{type:"Property",name:"msg",reflectMapper:Pr,select:["conversationType","receiverId","senderId","createTime","messageClientId","messageServerId"]},{type:"Property",name:"msgPin",reflectMapper:Ui}],response:[{type:"Long",name:"timetag"}]},v2UpdatePinMessage:{sid:33,cid:16,service:ki,params:[{type:"Property",name:"msg",reflectMapper:Pr,select:["conversationType","receiverId","senderId","createTime","messageClientId","messageServerId"]},{type:"Property",name:"msgPin",reflectMapper:Ui}],response:[{type:"Long",name:"timetag"}]},v2GetPinMessageList:{sid:33,cid:21,service:ki,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(wi)}]},v2VoiceToText:{sid:29,cid:5,service:ki,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:ki,params:[{type:"Property",name:"message",reflectMapper:Pr,select:["conversationType","senderId","receiverId","createTime","messageClientId","messageServerId"]},{type:"Property",name:"quickComment",reflectMapper:Di}],response:[{type:"Long",name:"timetag"}]},v2RemoveQuickComment:{sid:33,cid:4,service:ki,params:[{type:"Property",name:"message",reflectMapper:Pr,select:["conversationType","senderId","receiverId","createTime","messageClientId","messageServerId"]},{type:"Property",name:"quickComment",reflectMapper:Di}],response:[{type:"Long",name:"timetag"}]},onAddQuickComment:{sid:23,cid:5,service:ki,response:[{type:"Property",name:"message",reflectMapper:invertSerializeItem(Pr)},{type:"Property",name:"quickComment",reflectMapper:invertSerializeItem(Di)}]},onRemoveQuickComment:{sid:23,cid:6,service:ki,response:[{type:"Property",name:"message",reflectMapper:invertSerializeItem(Pr)},{type:"Property",name:"quickComment",reflectMapper:invertSerializeItem(Di)}]},v2GetQuickComment:{sid:33,cid:7,service:ki,params:[{type:"PropertyArray",name:"tag",reflectMapper:Li}],response:[{type:"PropertyArray",name:"data",reflectMapper:invertSerializeItem(Li)}]},onPinMessage:{sid:23,cid:18,service:ki,response:[{type:"Property",name:"msg",reflectMapper:invertSerializeItem(Pr)},{type:"Property",name:"pinInfo",reflectMapper:invertSerializeItem(Ui)}]},onUpdatePinMessage:{sid:23,cid:19,service:ki,response:[{type:"Property",name:"msg",reflectMapper:invertSerializeItem(Pr)},{type:"Property",name:"pinInfo",reflectMapper:invertSerializeItem(Ui)}]},onUnpinMessage:{sid:23,cid:20,service:ki,response:[{type:"Property",name:"msg",reflectMapper:invertSerializeItem(Pr)},{type:"Property",name:"pinInfo",reflectMapper:invertSerializeItem(Ui)}]},v2AddCollection:{sid:33,cid:8,service:ki,params:[{type:"Property",name:"tag",reflectMapper:xi}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(xi)}]},v2RemoveCollections:{sid:33,cid:9,service:ki,params:[{type:"PropertyArray",name:"tag",reflectMapper:xi,select:["collectionId","createTime"]}],response:[{type:"Int",name:"data"}]},v2UpdateCollectionExtension:{sid:33,cid:10,service:ki,params:[{type:"Property",name:"tag",reflectMapper:xi}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(xi)}]},v2GetCollectionListByOption:{sid:33,cid:11,service:ki,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(xi)}]},v2SearchCloudMessagesGroupByConversation:{sid:30,cid:26,service:ki,params:[{type:"Property",name:"tag",reflectMapper:$i}],response:[{type:"PropertyArray",name:"data",reflectMapper:invertSerializeItem(Pr)}]},v2SearchCloudMessages:{sid:30,cid:27,service:ki,params:[{type:"Property",name:"tag",reflectMapper:Fi}],response:[{type:"PropertyArray",name:"data",reflectMapper:invertSerializeItem(Pr)}]},v2SearchCloudMessagesEx:{sid:30,cid:34,service:ki,params:[{type:"Property",name:"tag",reflectMapper:Bi}],response:[{type:"PropertyArray",name:"msgs",reflectMapper:invertSerializeItem(Pr)},{type:"Int",name:"hasMore"},{type:"String",name:"nextPageToken"}]},v2GetThreadMessageList:{sid:33,cid:1,service:ki,params:[{type:"Property",name:"messageRefer",reflectMapper:Pr},{type:"Property",name:"tag",reflectMapper:{beginTime:1,endTime:2,excludeMessageServerId:3,limit:4,reverse:5}}],response:[{type:"Property",name:"message",reflectMapper:invertSerializeItem(Pr)},{type:"Property",name:"replyResult",reflectMapper:invertSerializeItem({total:{id:1,retType:"number"},timestamp:{id:2,retType:"number"}})},{type:"PropertyArray",name:"replyList",reflectMapper:invertSerializeItem(Pr)}]}};class V2NIMMessageExtendUtil extends V2Service{constructor(t){super("V2NIMMessageExtendUtil",t),this.core=t,this.service=this.core.V2NIMMessageService,"v2"===this.core.options.apiVersion&&registerParser({cmdMap:Pi,cmdConfig:ji})}pinMessage(t,o){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(Yt,t,"message",!0),validate(Qt,{serverExtension:o},"",!0);var a=yield this.core.sendCmd("v2PinMessage",{msg:t,msgPin:{serverExtension:o}});this.emitPinNotification({pinState:1,message:t,serverExtension:o,createTime:a.content.timetag,updateTime:a.content.timetag,operatorId:this.core.account})}))}unpinMessage(t,o){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(Yt,t,"messageRefer",!0),validate(Qt,{serverExtension:o},"",!0);var a=yield this.core.sendCmd("v2UnpinMessage",{msg:t,msgPin:{serverExtension:o}});this.emitPinNotification({pinState:0,message:t,serverExtension:o,updateTime:a.content.timetag,operatorId:this.core.account})}))}updatePinMessage(t,o){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(Yt,t,"message",!0),validate(Qt,{serverExtension:o},"",!0);var a=yield this.core.sendCmd("v2UpdatePinMessage",{msg:t,msgPin:{serverExtension:o}});this.emitPinNotification({pinState:2,message:t,serverExtension:o,updateTime:a.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 o=this.core.V2NIMConversationIdUtil.convertToV1ConversationId(t);return o=o.replace("superTeam","super_team"),(yield this.core.sendCmd("v2GetPinMessageList",{tag:{conversationId:o,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,o)=>o.updateTime-t.updateTime))}))}addQuickComment(t,o,a,m){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(rr,{message:t,index:o,serverExtension:a,pushConfig:m},"",!0);var u=yield this.core.sendCmd("v2AddQuickComment",{message:t,quickComment:{index:o,serverExtension:a,pushConfig:m}}),h={operationType:1,quickComment:{messageRefer:formatMessageRefer(this.core,t),createTime:u.content.timetag,index:o,serverExtension:a||"",operatorId:this.core.account}};this.core.V2NIMMessageService.emit("onMessageQuickCommentNotification",h)}))}removeQuickComment(t,o,a){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(Yt,t,"messageRefer",!0),validate({index:{type:"number",min:1}},{index:o},"",!0),validate({serverExtension:{type:"string",required:!1}},{serverExtension:a},"",!0);var m=yield this.core.sendCmd("v2RemoveQuickComment",{message:t,quickComment:{index:o,serverExtension:a}}),u={operationType:2,quickComment:{messageRefer:formatMessageRefer(this.core,t),createTime:m.content.timetag,index:o,serverExtension:a||"",operatorId:this.core.account}};this.core.V2NIMMessageService.emit("onMessageQuickCommentNotification",u)}))}getQuickCommentList(t){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(ir,{messages:t},"",!0);var o={};return(yield this.core.sendCmd("v2GetQuickComment",{tag:t.map((t=>({messageRefer:t})))})).content.data.forEach((t=>{var a,m;try{if(!t.detail)return void(o[a=t.messageRefer.messageClientId]||(o[a]=[]));var u=JSON.parse(t.detail);o[m=t.messageRefer.messageClientId]||(o[m]=[]),u.forEach((a=>{o[t.messageRefer.messageClientId].push({messageRefer:Object.assign(Object.assign({},t.messageRefer),{conversationId:this.core.V2NIMConversationIdUtil.messageConversationId(t.messageRefer)}),operatorId:a[1],index:parseInt(a[2]),createTime:parseInt(a[3]),serverExtension:a[4]})}))}catch(o){this.logger.error("getQuickCommentList JSON Parse Error",t.detail,o)}})),o}))}voiceToText(t){return __awaiter(this,void 0,void 0,(function*(){if(this.checkV2(),validate(tr,t,"",!0),!t.voicePath&&!t.voiceUrl&&!t.file)throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"voiceToText: voicePath、voiceUrl、file cannot be empty at the same time"}});var{voicePath:o,file:a,mimeType:m,sampleRate:u,duration:h,sceneName:g}=t,I=g?this.core.V2NIMStorageService.getStorageScene(g):null,M=t.voiceUrl;if(!M){var _={};a?_.file=a:0===(null==o?void 0:o.indexOf("nim-external"))?_.fileInput=o:_.filePath=o,M=(yield this.core.cloudStorage.uploadFile(Object.assign({type:"audio",nosScenes:I?I.sceneName:void 0,nosSurvivalTime:I?I.expireTime:void 0},_))).url}return(yield this.core.sendCmd("v2VoiceToText",{tag:{voiceUrl:M,mimeType:m,sampleRate:u,duration:h}},{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,o){var a=t.content.msg,m=t.content.pinInfo;a.conversationId=this.core.V2NIMConversationIdUtil.messageConversationId(a),this.emitPinNotification({pinState:o,message:a,serverExtension:m.serverExtension,createTime:m.createTime,updateTime:m.updateTime,operatorId:m.accid})}emitPinNotification(t){var o={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",o)}onAddQuickCommentHandler(t){return this.onQuickCommentNotificationHandler(t,1)}onRemoveQuickCommentHandler(t){return this.onQuickCommentNotificationHandler(t,2)}onQuickCommentNotificationHandler(t,o){var a={operationType:o,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",a)}addCollection(t){return __awaiter(this,void 0,void 0,(function*(){return this.checkV2(),validate(or,{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(sr,{collections:t},"",!0),(yield this.core.sendCmd("v2RemoveCollections",{tag:t})).content.data}))}updateCollectionExtension(t,o){return __awaiter(this,void 0,void 0,(function*(){return this.checkV2(),validate(nr,{collection:t,serverExtension:o},"",!0),(yield this.core.sendCmd("v2UpdateCollectionExtension",{tag:Object.assign(Object.assign({},t),{serverExtension:o})})).content.data}))}getCollectionListByOption(t){return __awaiter(this,void 0,void 0,(function*(){return this.checkV2(),validate(ar,t,"",!0),(yield this.getCollectionListExByOption(t)).collectionList}))}getCollectionListExByOption(t){var o,a;return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(ar,t,"",!0);var m=t.beginTime||0,u=t.endTime||0,h=void 0===t.direction?0:t.direction;if(void 0!==(null===(o=t.anchorCollection)||void 0===o?void 0:o.collectionId))if(0===t.direction){if(0===u)u=t.anchorCollection.createTime;else if(u!==t.anchorCollection.createTime)throw new V2NIMErrorImpl({code:Me.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:Me.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!==u&&m>=u)throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"getCollectionListExByOption: beginTime cannot be greater than endTime"}});var g={beginTime:m,endTime:u,direction:h,limit:t.limit,collectionType:t.collectionType,excludeId:(null===(a=t.anchorCollection)||void 0===a?void 0:a.collectionId)?t.anchorCollection.collectionId:0};g.collectionType||delete g.collectionType;var I=yield this.core.sendCmd("v2GetCollectionListByOption",{tag:g});return{totalCount:I.content.total,collectionList:I.content.data}}))}searchCloudMessages(t){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(cr,t,"",!0);var o=t.beginTime||0,a=t.endTime||0;if(0!==o&&0!==a&&o>a)throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"searchCloudMessages: beginTime cannot be greater than endTime"}});var m=void 0===t.sortOrder?0:t.sortOrder,u=t.conversationLimit||0,h=t.messageLimit||10,g=u>0?"v2SearchCloudMessagesGroupByConversation":"v2SearchCloudMessages",I=yield this.core.sendCmd(g,{tag:Object.assign(Object.assign({},t),{beginTime:o,endTime:a,sortOrder:m,conversationLimit:u,messageLimit:h})});return this.service._filterMessagesByFn(I.content.data.map((t=>completeMessage(this.core,t))))}))}searchCloudMessagesEx(t){var o,a,m;return __awaiter(this,void 0,void 0,(function*(){if(this.checkV2(),validate(dr,t,"",!0),t.conversationId&&validateConversationId(this.core.account,t.conversationId),!(null===(o=t.keywordList)||void 0===o?void 0:o.length)&&!(null===(a=t.senderAccountIds)||void 0===a?void 0:a.length)&&!(null===(m=t.messageTypes)||void 0===m?void 0:m.length))throw new V2NIMErrorImpl({code:Me.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 u=yield this.core.sendCmd("v2SearchCloudMessagesEx",{tag:Object.assign({},t)}),{msgs:h,hasMore:g,nextPageToken:I}=u.content,M=this.service._filterMessagesByFn(h.map((t=>completeMessage(this.core,t)))).sort(((t,o)=>o.createTime-t.createTime));return{count:h.length,items:formatSearchCloudMessageListEx(this.core,M),hasMore:intToBool(g),nextPageToken:I}}))}getThreadMessageList(t){return __awaiter(this,void 0,void 0,(function*(){if(validate(vr,t,"getThreadMessageList",!0),t.beginTime=t.beginTime||0,t.endTime&&t.beginTime>t.endTime)throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"getThreadMessageList: beginTime cannot be greater than endTime"}});var o=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:a,replyResult:m,replyList:u}=o.content,h=completeMessage(this.core,a),g=u.map((t=>completeMessage(this.core,t)));return g=this.service._filterMessagesByFn(g),g=this.service._filterMessageByClearTime(h.conversationId,g),{message:h,timestamp:m.timestamp,replyCount:m.total,replyList:g}}))}}class V2NIMNotificationServiceImpl extends V2Service{constructor(t,o){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:$r,cmdConfig:qr}),this.setOptions(o))}setOptions(t){var o;(null===(o=this.core.systemMessage)||void 0===o?void 0:o.name)?this.config.compatibleWithV1=!0:this.config.compatibleWithV1=!1,this.config=Object.assign(this.config,t)}emit(t,...o){var a=`${this.name}::emit ${t.toString()}`;if("onReceiveCustomNotifications"===t){var m=o[0];this.logger.log(`${a}`,m.map((t=>`sender:${t.senderId};receiver:${t.receiverId};ctype:${t.conversationType};time:${t.timestamp}`)))}else if("onReceiveBroadcastNotifications"===t){var u=o[0];this.logger.log(`${a}`,u.map((t=>`id:${t.id};sender:${t.senderId};time:${t.timestamp}`)))}else this.logger.log(`${a}`,...o);return super.emit(t,...o)}sendCustomNotification(t,o,a){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validateConversationId(this.core.account,t),validate(Yr,{content:o,params:a},"",!0);var m=3===this.core.V2NIMConversationIdUtil.parseConversationType(t)?"v2SendCustomNotificationWithSuperTeam":"v2SendCustomNotification",u=this.notificationUtil.generateNotificationTag(t,o,a);yield this.core.sendCmd(m,{tag:u})}))}processSystemNotification(t){var o=t.type;if([0,1,2,3,4,15,16,17,18].includes(o))this.core.eventBus.emit("V2NIMTeamService/sysNotification",t);else{if(![5,6].includes(o)){var a=Object.assign(Object.assign({},t),{conversationType:{100:1,101:2,102:1,103:3}[o]});return delete a.type,a}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 o=t.content.datas;this.markBroadcastMsgAck(o),o.forEach((t=>{this.core.eventBus.emit("V2NIMSync/updateTimetag",{broadcastMsgs:parseInt(t.id)})})),this.emit("onReceiveBroadcastNotifications",o)}onBroadcastMsgHandler(t){var o=t.content.data;this.markBroadcastMsgAck([o]),this.core.eventBus.emit("V2NIMSync/updateTimetag",{broadcastMsgs:parseInt(o.id)}),this.emit("onReceiveBroadcastNotifications",[o])}onSysNotificationHandler(t){var o=fillIdServer(t,t.content.data,"idServer");this.markSysNotificationAck([o]);var a=this.processSystemNotification(o);a&&this.emit("onReceiveCustomNotifications",[a])}v2SyncOfflineSysNotificationsHandler(t){this.markSysNotificationAck(t.content.datas);var o=t.content.datas.sort(((t,o)=>t.timestamp-o.timestamp)).map((t=>this.processSystemNotification(t))).filter((t=>t));o&&this.emit("onReceiveCustomNotifications",o)}v2NotificationRevokeHandler(t){var o=fillIdServer(t,t.content.data,"idServer");this.markSysNotificationAck([o])}v2NotificationSyncRevokeHandler(t){var{type:o}=t.content;1===parseInt(o)&&this.markSysNotificationAck(t.content.datas)}markSysNotificationAck(t){if(!this.config.compatibleWithV1){var o=[],a=[],m=[15,16,17,18,103];t.forEach((t=>{t.idServer&&(m.includes(t.type)?a.push(t.idServer):o.push(t.idServer))})),o.length>0&&this.core.sendCmd("v2BatchMarkRead",{sid:"7",cid:"3",ids:o}),a.length>0&&this.core.sendCmd("v2BatchMarkRead",{sid:"21",cid:"19",ids:a})}}}var Gi,qi={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}},Hi={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}},qi)},zi={type:"array",min:1,itemType:"string"},Yi={type:"boolean"},Ki={type:"string"},Wi={type:"string",allowEmpty:!1},Ji={type:"object",rules:{antispamBusinessId:{type:"string",required:!1}},required:!1},Xi={teamId:{type:"string",regExp:/^[1-9]\d*$/,allowEmpty:!1}},Qi={teamIds:{type:"array",itemRules:{type:"string",allowEmpty:!1,regExp:/^[1-9]\d*$/},min:1}},Zi={teamType:{type:"enum",values:[1,2]}},eo={teamTypes:{type:"array",itemType:"enum",values:[1,2],required:!1}},to={inviteeParams:{type:"object",required:!0,rules:{inviteeAccountIds:zi,postscript:Object.assign(Object.assign({},Ki),{required:!1}),serverExtension:Object.assign(Object.assign({},Ki),{required:!1})}}},ro={updateTeamInfoParams:{type:"object",required:!0,rules:Object.assign({name:{type:"string",allowEmpty:!1,required:!1},memberLimit:{type:"number",min:1,required:!1}},qi)}},io={type:"enum",values:[0,2]},oo={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}}}}}},so={chatBannedMode:{type:"enum",values:[0,1]}},no={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}}}},ao={teamId:Xi.teamId,teamType:{type:"enum",values:[1,2]},operatorAccountId:{type:"string",allowEmpty:!1}},co={actionType:{type:"enum",values:[2,0,1,3]}},lo={actionType:{type:"enum",values:[2]}},po={actionType:{type:"enum",values:[0]}},mo={types:{type:"array",itemType:"enum",values:[0,2,1,3],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}},uo={teamId:Xi.teamId,teamType:Zi.teamType,accountIds:zi},ho={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,o=!0){var a=this.chooseMap(t),m=0;return a.forEach((t=>{o&&t.isValidTeam&&m++,o||m++})),m}chooseMap(t){return 2===t?this.superTeamMap:1===t?this.teamMap:new Map}getById(t,o,a=!0){var m=this.chooseMap(o).get(t);if(m){if(a&&m.isValidTeam)return m;if(!a)return m}}getAll(t,o=!0){var a=this.chooseMap(t);return Array.from(a.values()).filter((t=>!(!o||!t.isValidTeam)||(!o||void 0))).sort(((t,o)=>o.updateTime-t.updateTime))}upsert(t){var o=t.teamId,a=t.teamType,m=this.chooseMap(a),u=m.get(o)||{},h=Object.assign({},u,t);return m.set(o,h),h}deleteById(t,o){var a=this.getById(t,o);if(a)return a.isValidTeam=!1,a}searchTeamByKeyword(t){var o=[];return this.teamMap.forEach((a=>{a.name.includes(t)&&o.push(a)})),this.superTeamMap.forEach((a=>{a.name.includes(t)&&o.push(a)})),o}}class V2NIMTeamMemberModelImpl{constructor(){this.teamMembers=[],this.superTeamMembers=[],this.maxSize=2e3}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,o,a){return this.chooseList(o).find((o=>o.teamId===t&&o.accountId===a))}upsert(t){var o=t.teamType,a=t.teamId,m=this.chooseList(o),u=m.findIndex((o=>o.teamId===a&&o.accountId===t.accountId));-1===u?m.push(t):m[u]=Object.assign(Object.assign({},m[u]),t),m.length>this.maxSize&&m.shift()}deleteByAccount(t,o,a){var m=this.chooseList(o),u=m.findIndex((o=>o.teamId===t&&o.accountId===a));if(-1!==u){var h=m[u];return h.inTeam=!1,m.splice(u,1),h}}deleteByTeamId(t,o){var a=this.chooseList(o).filter((o=>o.teamId!==t));2===o?this.superTeamMembers=a:this.teamMembers=a}}class V2NIMTeamNotificationImpl{constructor(t,o){this.core=t,this.service=o}processNotification(t){var{attachment:o,senderId:a,receiverId:m,createTime:u}=t,{id:h,data:g}=o,I=h>400?2:1,{id:M,ids:_,tinfo:E,mute:S}=formatTeamNotificationAttachData(g,I),T=this.service.model.getById(m,I);switch(this.core.logger.log(`v2Team::processNotification, notificationType:${h}, teamId:${m}`,g),h){case Gi.SUPER_TEAM_INVITATION:case Gi.TEAM_INVITATION:_.includes(this.core.account)&&this.onTeamJoined(E),this.onTeamMembersJoined(E,_.filter((t=>t!==this.core.account)));break;case Gi.SUPER_TEAM_INVITE_ACCEPT:case Gi.TEAM_INVITE_ACCEPT:a===this.core.account?this.onTeamJoined(E):this.onTeamMemberJoined(E,a);break;case Gi.SUPER_TEAM_APPLY_ACCEPT:case Gi.TEAM_APPLY_ACCEPT:M===this.core.account?this.onTeamJoined(E):this.onTeamMemberJoined(E,M);break;case Gi.SUPER_TEAM_ADD_MANAGER:case Gi.TEAM_ADD_MANAGER:this.updateTeamMemberRole(m,I,_,{memberRole:2,updateTime:u});break;case Gi.SUPER_TEAM_REMOVE_MANAGER:case Gi.TEAM_REMOVE_MANAGER:this.updateTeamMemberRole(m,I,_,{memberRole:0,updateTime:u});break;case Gi.SUPER_TEAM_KICK:case Gi.TEAM_KICK:this.onTeamInfoUpdated(E),_.forEach((t=>{t===this.core.account?this.onTeamLeft(m,I,!0):this.onTeamMemberKicked(a,E.teamId,E.teamType,t)}));break;case Gi.SUPER_TEAM_LEAVE:case Gi.TEAM_LEAVE:E?this.onTeamInfoUpdated(E):T&&a===this.core.account&&(T.isValidTeam=!1,this.onTeamInfoUpdated(T)),a===this.core.account?this.onTeamLeft(m,I,!1):this.onTeamMemberLeft(m,I,a);break;case Gi.SUPER_TEAM_DISMISS:case Gi.TEAM_DISMISS:this.onTeamDismissed(m,I);break;case Gi.SUPER_TEAM_UPDATE:case Gi.TEAM_UPDATED:this.onTeamInfoUpdated(E);break;case Gi.SUPER_TEAM_TRANSFER_OWNER:case Gi.TEAM_TRANSFER_OWNER:this.onTeamInfoUpdated(E),this.updateTeamMemberRole(m,I,[a,E.ownerAccountId],[{memberRole:0,updateTime:u},{memberRole:1,updateTime:u,joinTime:u}],!1);break;case Gi.SUPER_TEAM_MEMBER_MUTE:case Gi.TEAM_MEMBER_MUTE:this.service.model.upsert(E),this.updateTeamMemberRole(m,I,M?[M]:_,{chatBanned:0!==S,updateTime:u})}}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,o,a){var m=this.service.model.deleteById(t,o)||generateTeamByTeamId(t,o,{isValidTeam:!1});this.service.memberModel.deleteByAccount(t,o,this.core.account),this.service.emit("onTeamLeft",m,a)}onTeamDismissed(t,o){var a=this.service.model.deleteById(t,o);a||(a=generateTeamByTeamId(t,o,{isValidTeam:!1})),this.service.memberModel.deleteByTeamId(t,o),this.service.emit("onTeamDismissed",a)}onTeamInfoUpdated(t){var o=this.service.model.upsert(t);this.service.emit("onTeamInfoUpdated",o)}onTeamMemberJoined(t,o){this.service.model.upsert(t),this.service.emit("onTeamInfoUpdated",t);var a=t.updateTime||t.createTime,m=generateMemberByTeamId(t.teamId,t.teamType,o,{joinTime:a,updateTime:a});this.service.emit("onTeamMemberJoined",[m])}onTeamMembersJoined(t,o){var a=t.updateTime||t.createTime,m=o.map((o=>generateMemberByTeamId(t.teamId,t.teamType,o,{joinTime:a,updateTime:a})));0!==m.length&&(this.service.model.upsert(t),this.service.emit("onTeamInfoUpdated",t),this.service.emit("onTeamMemberJoined",m))}onTeamMemberLeft(t,o,a){var m=this.service.memberModel.deleteByAccount(t,o,a);m||(m=generateMemberByTeamId(t,o,a,{inTeam:!1})),this.service.emit("onTeamMemberLeft",[m])}onTeamMemberKicked(t,o,a,m){var u=this.service.memberModel.deleteByAccount(o,a,m);u||(u=generateMemberByTeamId(o,a,m,{inTeam:!1})),this.service.emit("onTeamMemberKicked",t,[u])}onTeamMemberInfoUpdated(t){t.forEach((t=>{if(t.accountId===this.core.account&&this.core.V2NIMSettingService.name&&this.core.V2NIMConversationIdUtil.name){var o=1===t.teamType?this.core.V2NIMConversationIdUtil.teamConversationId(t.teamId):this.core.V2NIMConversationIdUtil.superTeamConversationId(t.teamId),a=this.core.V2NIMSettingService.getConversationMuteStatus(o);this.core.eventBus.emit("V2NIMSettingService/setMute",o,a)}})),this.service.emit("onTeamMemberInfoUpdated",t)}updateTeamMemberRole(t,o,a,m,u=!0){return __awaiter(this,void 0,void 0,(function*(){var h=a.filter(((a,u)=>{var h=this.service.memberModel.getById(t,o,a);return h&&this.service.memberModel.upsert(Object.assign(Object.assign({},h),Array.isArray(m)?m[u]:m)),!h}));if(u&&h.length>0)try{(yield this.service.getTeamMemberListByIds(t,o,h)).forEach((t=>this.service.memberModel.upsert(t)))}catch(t){this.core.logger.warn("v2Team::processNotification, getTeamMemberListByIds failed",t)}var g=a.map(((a,h)=>{var g=this.service.memberModel.getById(t,o,a);return g||u?g:generateMemberByTeamId(t,o,a,Array.isArray(m)?m[h]:m)})).filter((t=>!!t));g.length>0&&this.onTeamMemberInfoUpdated(g)}))}processSysNotification(t){var{receiverId:o,postscript:a,senderId:m,timestamp:u,content:h}=t,g={};try{g=JSON.parse(h)}catch(t){this.core.logger.warn("v2Team::processSysNotification, parse content failed",h)}var I={actionType:{0:0,1:1,2:2,3:3,15:0,16:1,17:2,18:3}[t.type],teamId:o,teamType:t.type>=15?2:1,operatorAccountId:m,postscript:a,timestamp:u,actionStatus:0,read:!1};g.attach&&(I.serverExtension=g.attach),this.core.logger.log("v2Team::processSysNotification, type:",t.type,I),this.service.notificationModel.create(I),this.service.emit("onReceiveTeamJoinActionInfo",I)}updateTeamActionStatus(t,o){this.service.notificationModel.update({teamId:t.teamId,teamType:t.teamType,operatorAccountId:t.operatorAccountId,actionType:t.actionType,actionStatus:o})}checkIfExpired(t){return!!t&&(509===t||!(t>=500&&t<=599)&&!(t>=19e4))}}!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"}(Gi||(Gi={}));class V2NIMTeamNotificationModelImpl{constructor(){this.list=[],this.maxCount=1e3}reset(){this.list=[]}checkSameAction(t,o,a=!1){return t.teamId===o.teamId&&t.teamType===o.teamType&&t.actionType===o.actionType&&t.operatorAccountId===o.operatorAccountId&&(!a||t.timestamp===o.timestamp)}create(t){this.list.push(t),this.list.length>this.maxCount&&this.list.shift()}update(t){this.list.forEach((o=>{this.checkSameAction(o,t)&&0===o.actionStatus&&Object.assign(o,t)}))}delete(t){this.list=this.list.map((o=>{if(!this.checkSameAction(o,t,!1))return o})).filter((t=>t))}getByOption(t){var{types:o,status:a,offset:m=0,limit:u=50}=t,h=[];this.list.forEach((t=>{o&&o.length>0&&!o.includes(t.actionType)||a&&a.length>0&&!a.includes(t.actionStatus)||h.push(t)})),h=h.sort(((t,o)=>o.timestamp-t.timestamp));var g=0;m>0&&(g=findIndexWithinTargetValue(h,"timestamp",m),h[g]&&h[g].timestamp===m&&(g+=1));var I=h.slice(g).length;return(h=h.slice(g,g+u)).length>0?{offset:I>u?h[h.length-1].timestamp:0,finished:!(I>u),infos:h}:{offset:0,finished:!0,infos:h}}setRead(t){for(var o of this.list)this.checkSameAction(o,t)&&(o.read=!0)}setAllRead(){for(var t of this.list)t.read=!0}getUnreadCount(){var t=new Set;for(var o of this.list)o.read||0!==o.actionStatus||0!==o.actionType&&2!==o.actionType||t.add(`${o.operatorAccountId}_${o.teamType}_${o.teamId}`);return t.size}}class V2NIMTeamEventImpl{constructor(t,o){this.core=t,this.service=o,this.model=o.model,this.memberModel=o.memberModel,this.notification=o.notification,this.logger=this.core.logger}setListener(){this.core.eventBus.on("V2NIMTeamService/onSyncStarted",(()=>{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 o=generateMemberByTeamId(t.teamId,t.teamType,this.core.account,{memberRole:1});this.memberModel.upsert(o),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,...o){var a=`${this.service.name}::emit ${t.toString()}`;if("onTeamCreated"===t||"onTeamDismissed"===t||"onTeamJoined"===t||"onTeamLeft"===t||"onTeamInfoUpdated"===t){var m=o[0];this.logger.log(`${a}`,`team:${m.teamId}_${m.teamType};updateTime:${m.updateTime}`)}else if("onTeamMemberJoined"===t||"onTeamMemberLeft"===t||"onTeamMemberInfoUpdated"===t){var u=o[0];this.logger.log(`${a}`,u.map((t=>`team:${t.teamId}_${t.teamType};account:${t.accountId}`)))}else if("onTeamMemberKicked"===t){var h=o[0],g=o[1];this.logger.log(`${a}`,`operator${h}`,g.map((t=>`team:${t.teamId}_${t.teamType};account:${t.accountId}`)))}else this.logger.log(`${a}`,...o)}onSyncDone(t){t?this.service.emit("onSyncFailed",t):this.service.emit("onSyncFinished")}}class V2NIMTeamHandlerImpl{constructor(t,o){this.core=t,this.service=o,this.model=o.model,this.memberModel=o.memberModel,this.logger=this.core.logger}v2TeamSyncHandler(t){this.model.set(t.content.datas)}v2SuperTeamSyncHandler(t){this.model.set(t.content.datas)}v2TeamCreateMultiSyncHandler(t){var o=t.content.data;this.model.upsert(o);var a=generateMemberByTeamId(o.teamId,o.teamType,this.core.account,{memberRole:1});this.memberModel.upsert(a),this.service.emit("onTeamCreated",o)}v2SuperTeamCreateMultiSyncHandler(t){var o=t.content.data;this.model.upsert(o);var a=generateMemberByTeamId(o.teamId,o.teamType,this.core.account,{memberRole:1});this.memberModel.upsert(a),this.service.emit("onTeamCreated",o)}v2TeamMemberUpdateMultiSyncHandler(t){var o=t.content.data;o.teamType=1;var a=this.memberModel.getById(o.teamId,o.teamType,o.accountId);this.service.notification.updateTeamMemberRole(o.teamId,o.teamType,[o.accountId],o),o.accountId===this.core.account&&a&&a.bits!==o.bits&&this.core.eventBus.emit("V2NIMSettingService/updateBits",o.teamId,o.teamType,o.bits)}v2SuperTeamMemberUpdateMultiSyncHandler(t){var o=t.content.data;o.teamType=2;var a=this.memberModel.getById(o.teamId,o.teamType,o.accountId);this.service.notification.updateTeamMemberRole(o.teamId,o.teamType,[o.accountId],o),o.accountId===this.core.account&&a&&a.bits!==o.bits&&this.core.eventBus.emit("V2NIMSettingService/updateBits",o.teamId,o.teamType,o.bits)}v2TeamMembersOfSelfInSyncHandler(t){t.content.datas.forEach((t=>{t.teamType=1,this.memberModel.upsert(t)}))}v2SuperTeamMembersOfSelfInSyncHandler(t){t.content.datas.forEach((t=>{t.teamType=2,this.memberModel.upsert(t)}))}}class V2NIMTeamServiceImpl extends V2Service{constructor(t){super("V2NIMTeamService",t),this.core._registerDep(V2NIMConversationIdUtilImpl,"V2NIMConversationIdUtil"),this.model=new V2NIMTeamModelImpl,this.memberModel=new V2NIMTeamMemberModelImpl,this.notificationModel=new V2NIMTeamNotificationModelImpl,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:Er,cmdConfig:br}),this.setListener())}setListener(){this.event.setListener()}reset(){this.model.reset(),this.memberModel.reset(),this.notificationModel.reset()}emit(t,...o){return this.event.beforeEmit(t,...o),super.emit(t,...o)}createTeam(t,o,a,m){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate({createTeamParams:Hi},{createTeamParams:t},"",!0),validate({inviteeAccountIds:Object.assign(Object.assign({},zi),{min:0,required:!1})},{inviteeAccountIds:o},"",!0),validate({antispamConfig:Ji},{antispamConfig:m},"",!0);var u=2===t.teamType?"v2SuperTeamCreate":"v2TeamCreate",h=yield this.core.sendCmd(u,{team:t,inviteeAccountIds:o||[],postscript:a||"",antispamConfig:m}),g=h.content.team;return this.model.upsert(g),this.getTeamMemberListByIds(g.teamId,g.teamType,[this.core.account]).catch((t=>{this.core.logger.error("Get Member error after createTeam",t)})),this.emit("onTeamCreated",g),{team:g,failedList:h.content.failedList}}))}updateTeamInfo(t,o,a,m){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(Xi,{teamId:t},"",!0),validate(Zi,{teamType:o},"",!0),validate(ro,{updateTeamInfoParams:a},"",!0),validate({antispamConfig:Ji},{antispamConfig:m},"",!0);var u=Object.assign({teamId:t,teamType:o},a),h=2===o?"v2SuperTeamUpdateInfo":"v2TeamUpdateInfo";yield this.core.sendCmd(h,{team:u,antispamConfig:m}),this.model.upsert(u)}))}leaveTeam(t,o){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(Xi,{teamId:t},"",!0),validate(Zi,{teamType:o},"",!0);var a=2===o?"v2SuperTeamLeave":"v2TeamLeave";yield this.core.sendCmd(a,{teamId:t}),this.model.deleteById(t,o)}))}getTeamInfo(t,o){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(Xi,{teamId:t},"",!0),validate(Zi,{teamType:o},"",!0);var a=2===o?"v2SuperTeamGetInfo":"v2TeamGetInfo",m=this.model.getById(t,o,!1);if(m)return m;var u=(yield this.core.sendCmd(a,{teamId:t})).content.team;return this.model.upsert(u),u}))}getJoinedTeamList(t){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(eo,{teamTypes:t},"",!0),this.core.V2NIMLoginService.checkIllegalState(),t&&0!==t.length||(t=[1,2]);var o=[];return t.forEach((t=>{o=o.concat(this.model.getAll(t))})),o.sort(((t,o)=>t.createTime-o.createTime))}))}getJoinedTeamCount(t){this.checkV2(),validate(eo,{teamTypes:t},"",!0),this.core.V2NIMLoginService.checkIllegalState(),t&&0!==t.length||(t=[1,2]);var o=0;return t.forEach((t=>{o+=this.model.count(t)})),o}getJoinedTeamMembers(t){this.checkV2(),validate(eo,{teamTypes:t},"",!0),this.core.V2NIMLoginService.checkIllegalState(),t&&0!==t.length||(t=[1,2]);var o=[];return t.forEach((t=>{var a=this.memberModel.chooseList(t).filter((t=>t.accountId===this.core.account));o=o.concat(a)})),Promise.resolve(o)}getTeamInfoByIds(t,o){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(Qi,{teamIds:t},"",!0),validate(Zi,{teamType:o},"",!0);var a=2===o?"v2SuperTeamGetByIds":"v2TeamGetByIds",m=t.map((t=>this.model.getById(t,o,!1))),u=t.filter(((t,o)=>!m[o]));if(0===u.length)return m;var h=(yield this.core.sendCmd(a,{teamIds:u})).content.teams;return m.map(((o,a)=>{if(o)return o;var m=t[a],u=h.find((t=>t.teamId===m));return u&&this.model.upsert(u),u})).filter((t=>!!t))}))}dismissTeam(t,o){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(Xi,{teamId:t},"",!0),validate(Zi,{teamType:o},"",!0);var a=2===o?"v2SuperTeamDismiss":"v2TeamDismiss";yield this.core.sendCmd(a,{teamId:t})}))}inviteMember(t,o,a,m){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(Xi,{teamId:t},"",!0),validate(Zi,{teamType:o},"",!0),validate({inviteeAccountIds:zi},{inviteeAccountIds:a},"",!0),validate({postscript:Object.assign(Object.assign({},Ki),{required:!1})},{postscript:m},"",!0);var u=2===o?"v2SuperTeamInviteMembers":"v2TeamInviteMembers";return(yield this.core.sendCmd(u,{teamId:t,accounts:a,ps:m||""})).content.abortedAccidList}))}inviteMemberEx(t,o,a){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(Xi,{teamId:t},"",!0),validate(Zi,{teamType:o},"",!0),validate(to,{inviteeParams:a},"",!0);var m=2===o?"v2SuperTeamInviteMembers":"v2TeamInviteMembers";return(yield this.core.sendCmd(m,{teamId:t,accounts:a.inviteeAccountIds,ps:a.postscript||"",attach:a.serverExtension})).content.abortedAccidList}))}acceptInvitation(t){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(ao,t,"invitationInfo",!0),validate(lo,t,"invitationInfo",!0);var{teamType:o,teamId:a,operatorAccountId:m}=t,u=2===o?"v2SuperTeamAcceptInvitation":"v2TeamAcceptInvitation";try{var h=yield this.core.sendCmd(u,{teamId:a,from:m});return this.notification.updateTeamActionStatus(t,1),h.content.team}catch(o){var g=o;throw this.notification.checkIfExpired(g.code)&&this.notification.updateTeamActionStatus(t,3),o}}))}rejectInvitation(t,o){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(ao,t,"invitationInfo",!0),validate(lo,t,"invitationInfo",!0),validate({postscript:Object.assign(Object.assign({},Ki),{required:!1})},{postscript:o},"",!0);var{teamType:a,teamId:m,operatorAccountId:u}=t,h=2===a?"v2SuperTeamRejectInvite":"v2TeamRejectInvite";try{yield this.core.sendCmd(h,{teamId:m,from:u,ps:o||""}),this.notification.updateTeamActionStatus(t,2)}catch(o){var g=o;throw this.notification.checkIfExpired(g.code)&&this.notification.updateTeamActionStatus(t,3),o}}))}kickMember(t,o,a){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(Xi,{teamId:t},"",!0),validate(Zi,{teamType:o},"",!0),validate({memberAccountIds:zi},{memberAccountIds:a},"",!0);var m=2===o?"v2SuperTeamKickMembers":"v2TeamKickMembers";yield this.core.sendCmd(m,{teamId:t,accounts:a})}))}applyJoinTeam(t,o,a){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(Xi,{teamId:t},"",!0),validate(Zi,{teamType:o},"",!0);var m=2===o?"v2SuperTeamApplyToJoin":"v2TeamApplyToJoin",u=yield this.core.sendCmd(m,{teamId:t,ps:a||""}),h=u.content.team,g=u.content.isInTeam;return h.isValidTeam=!!h.isValidTeam&&!!g,h}))}acceptJoinApplication(t){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(ao,t,"applicationInfo",!0),validate(po,t,"applicationInfo",!0);var{teamType:o,teamId:a,operatorAccountId:m}=t,u=2===o?"v2SuperTeamAcceptJoinApplication":"v2TeamAcceptJoinApplication";try{yield this.core.sendCmd(u,{teamId:a,from:m}),this.notification.updateTeamActionStatus(t,1)}catch(o){var h=o;throw this.notification.checkIfExpired(h.code)&&this.notification.updateTeamActionStatus(t,3),o}}))}rejectJoinApplication(t,o){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(ao,t,"applicationInfo",!0),validate(po,t,"applicationInfo",!0),validate({postscript:Object.assign(Object.assign({},Ki),{required:!1})},{postscript:o},"",!0);var{teamType:a,teamId:m,operatorAccountId:u}=t,h=2===a?"v2SuperTeamRejectJoinApplication":"v2TeamRejectJoinApplication";try{yield this.core.sendCmd(h,{teamId:m,from:u,ps:o||""}),this.notification.updateTeamActionStatus(t,2)}catch(o){var g=o;throw this.notification.checkIfExpired(g.code)&&this.notification.updateTeamActionStatus(t,3),o}}))}updateTeamMemberRole(t,o,a,m){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(Xi,{teamId:t},"",!0),validate(Zi,{teamType:o},"",!0),validate({memberAccountIds:zi},{memberAccountIds:a},"",!0),validate({memberRole:io},{memberRole:m},"",!0);var u=2===m?"AddManagers":"RemoveManagers";u=2===o?`v2SuperTeam${u}`:`v2Team${u}`,yield this.core.sendCmd(u,{teamId:t,accounts:uniq(a)})}))}transferTeamOwner(t,o,a,m){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(Xi,{teamId:t},"",!0),validate(Zi,{teamType:o},"",!0),validate({accountId:Wi},{accountId:a},"",!0),validate({leave:{type:"boolean",required:!1}},{leave:m},"",!0);var u=this.model.getById(t,o);if(u&&u.ownerAccountId===a)throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"Transfer to self is not allowed"}});var h=2===o?"v2SuperTeamTransferOwner":"v2TeamTransferOwner";yield this.core.sendCmd(h,{teamId:t,account:a,leave:m||!1})}))}updateSelfTeamMemberInfo(t,o,a){return __awaiter(this,void 0,void 0,(function*(){if(this.checkV2(),validate(Xi,{teamId:t},"",!0),validate(Zi,{teamType:o},"",!0),validate(oo,{memberInfoParams:a},"",!0),void 0===a.teamNick&&void 0===a.serverExtension)throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_INVALID_PARAMETER});var m=2===o?"v2SuperTeamUpdateSelfMemberInfo":"v2TeamUpdateSelfMemberInfo",u=Object.assign(Object.assign({},a),{teamId:t,accountId:this.core.account}),h=a.antispamConfig?{teamMember:u,specialFollowUpdate:{},antispam:a.antispamConfig}:{teamMember:u};yield this.core.sendCmd(m,h),yield this.notification.updateTeamMemberRole(t,o,[this.core.account],u);var g=this.memberModel.getById(t,o,this.core.account);if(this.core.V2NIMSettingService.name&&this.core.V2NIMConversationIdUtil.name){var I=1===o?this.core.V2NIMConversationIdUtil.teamConversationId(t):this.core.V2NIMConversationIdUtil.superTeamConversationId(t),M=this.core.V2NIMSettingService.getConversationMuteStatus(I);this.core.eventBus.emit("V2NIMSettingService/setMute",I,M)}this.core.eventBus.emit("forwardSend/V2NIMTeamService/updateSelfTeamMemberInfo",g)}))}updateTeamMemberNick(t,o,a,m){return __awaiter(this,void 0,void 0,(function*(){if(this.checkV2(),validate(Xi,{teamId:t},"",!0),validate(Zi,{teamType:o},"",!0),validate({accountId:Wi},{accountId:a},"",!0),validate({nick:Ki},{nick:m},"",!0),a===this.core.account)return this.updateSelfTeamMemberInfo(t,o,{teamNick:m});var u=2===o?"v2SuperTeamUpdateMember":"v2TeamUpdateMember";yield this.core.sendCmd(u,{teamMember:{teamNick:m,teamId:t,accountId:a}})}))}updateTeamMemberNickEx(t,o,a){return __awaiter(this,void 0,void 0,(function*(){if(this.checkV2(),validate(Xi,{teamId:t},"",!0),validate(Zi,{teamType:o},"",!0),validate(ho,a,"",!0),a.accountId===this.core.account)return this.updateSelfTeamMemberInfo(t,o,{teamNick:a.teamNick,antispamConfig:a.antispamConfig});var m=2===o?"v2SuperTeamUpdateMember":"v2TeamUpdateMember";yield this.core.sendCmd(m,{teamMember:{teamNick:a.teamNick,teamId:t,accountId:a.accountId},antispam:a.antispamConfig})}))}setTeamChatBannedMode(t,o,a){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(Xi,{teamId:t},"",!0),validate(Zi,{teamType:o},"",!0),validate(so,{chatBannedMode:a},"",!0);var m=2===o?"v2SuperTeamSetChatBannedMode":"v2TeamSetChatBannedMode";yield this.core.sendCmd(m,{teamId:t,chatBannedMode:a}),this.model.upsert({teamId:t,teamType:o,chatBannedMode:a})}))}setTeamMemberChatBannedStatus(t,o,a,m){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(Xi,{teamId:t},"",!0),validate(Zi,{teamType:o},"",!0),validate({accountId:Wi},{accountId:a},"",!0),validate({chatBanned:Yi},{chatBanned:m},"",!0);var u=2===o?"v2SuperTeamMemberSetChatBannedStatus":"v2TeamMemberSetChatBannedStatus";yield this.core.sendCmd(u,{teamId:t,accountId:2===o?[a]:a,chatBanned:m?1:0})}))}getTeamMemberList(t,o,a){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(Xi,{teamId:t},"",!0),validate(Zi,{teamType:o},"",!0),validate(no,{queryOption:a},"",!0);var m=void 0===a.direction?0:a.direction;m=0===m?1:0;var u=yield this.core.sendCmd("v2TeamMemberGetList",{tag:Object.assign(Object.assign({teamId:t,teamType:o,onlyChatBanned:!1,nextToken:"",limit:100},a),{direction:m})}),h=u.content.datas,g=get(u,"raw.r.0");return 2===o&&g&&g.map&&(h=g.map((t=>deserialize(t,invertSerializeItem(Ar))))),{nextToken:u.content.pageInfo.nextToken||"",finished:!+u.content.pageInfo.hasMore,memberList:processTeamMembers(h,o)}}))}getTeamMemberListByIds(t,o,a){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(Xi,{teamId:t},"",!0),validate(Zi,{teamType:o},"",!0),validate({accountIds:zi},{accountIds:a},"",!0);for(var m=2===o?"v2SuperTeamMemberGetListByIds":"v2TeamMemberGetListByIds",u=a.map((o=>`${t}|${o}`)),h=[],g=0;g<u.length;g+=20){var I=processTeamMembers((yield this.core.sendCmd(m,{tag:u.slice(g,g+20)})).content.datas,o);h=h.concat(I),I.forEach((t=>this.memberModel.upsert(t)))}return h}))}getTeamMemberInvitor(t,o,a){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(Xi,{teamId:t},"",!0),validate(Zi,{teamType:o},"",!0),validate({accountIds:zi},{accountIds:a},"",!0);var m=2===o?"v2SuperTeamGetMemberInvitor":"v2TeamGetMemberInvitor";return(yield this.core.sendCmd(m,{teamId:t,accounts:a})).content.accountsMap}))}searchTeamByKeyword(t){return __awaiter(this,void 0,void 0,(function*(){return this.checkV2(),this.checkLogin(),validate({keyword:Wi},{keyword:t},"",!0),this.model.searchTeamByKeyword(t)}))}addTeamMembersFollow(t,o,a){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(uo,{teamId:t,teamType:o,accountIds:a},"",!0);var m=2===o?"v2SuperTeamUpdateSelfMemberInfo":"v2TeamUpdateSelfMemberInfo",[u]=yield this.getTeamMemberListByIds(t,o,[this.core.account]),h=(yield this.core.sendCmd(m,{teamMember:{teamId:t},specialFollowUpdate:{accountIds:a,operation:1}})).content.data;Object.keys(h).length>0&&(Object.assign(u,h),this.emit("onTeamMemberInfoUpdated",[u]),this.memberModel.upsert(u))}))}removeTeamMembersFollow(t,o,a){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(uo,{teamId:t,teamType:o,accountIds:a},"",!0);var[m]=yield this.getTeamMemberListByIds(t,o,[this.core.account]),u=2===o?"v2SuperTeamUpdateSelfMemberInfo":"v2TeamUpdateSelfMemberInfo",h=(yield this.core.sendCmd(u,{teamMember:{teamId:t},specialFollowUpdate:{accountIds:a,operation:0}})).content.data;Object.keys(h).length>0&&(Object.assign(m,h),this.emit("onTeamMemberInfoUpdated",[m]),this.memberModel.upsert(m))}))}getTeamJoinActionInfoList(t){return this.checkV2(),validate(mo,t,"option",!0),this.core.V2NIMLoginService.checkIllegalState(),Promise.resolve(this.notificationModel.getByOption(t))}clearAllTeamJoinActionInfo(){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),this.core.V2NIMLoginService.checkIllegalState(),this.notificationModel.reset()}))}deleteTeamJoinActionInfo(t){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),this.core.V2NIMLoginService.checkIllegalState(),validate(ao,t,"",!0),validate(co,t,"",!0),validate({timestamp:{type:"number",min:1}},t,"",!0),this.notificationModel.delete(t)}))}setTeamJoinActionInfoRead(t){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),this.core.V2NIMLoginService.checkIllegalState(),t?(validate(ao,t,"",!0),validate(co,t,"",!0),this.notificationModel.setRead(t)):this.notificationModel.setAllRead()}))}getTeamJoinActionInfoUnreadCount(){return __awaiter(this,void 0,void 0,(function*(){return this.checkV2(),this.core.V2NIMLoginService.checkIllegalState(),this.notificationModel.getUnreadCount()}))}}var go="V2NIMUserService",vo={"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"},fo={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"}},Io={v2UpdateBlockList:{sid:34,cid:3,service:go,params:[{type:"String",name:"accountId"},{type:"Bool",name:"addToBlockList"}]},v2GetUserList:{sid:34,cid:7,service:go,params:[{type:"StrArray",name:"accountIds"}],response:[{type:"PropertyArray",name:"data",reflectMapper:invertSerializeItem(fo)}]},v2UpdateSelfUserProfile:{sid:34,cid:10,service:go,params:[{type:"Property",name:"tag",reflectMapper:fo}],response:[{type:"Long",name:"updateTime"}]},onUpdateUserProfile:{sid:3,cid:110,service:go,response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(fo)}]},onUpdateBlockList:{sid:3,cid:103,service:go,response:[{type:"String",name:"accountId"},{type:"Bool",name:"addToBlockList"}]},syncBlockAndMuteList:{sid:3,cid:8,service:go,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:go,response:[{type:"Property",name:"user",reflectMapper:invertSerializeItem(fo)}]},v2SetP2PMessageMuteMode:{sid:34,cid:5,service:go,params:[{type:"String",name:"accountId"},{type:"Bool",name:"muteMode"}]},v2OnUpdateMuteList:{sid:3,cid:105,service:go,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,o){1===o?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((o=>!(void 0!==t.searchName&&!t.searchName||!o.name.includes(t.keyword))||(!(!t.searchAccountId||!o.accountId.includes(t.keyword))||!!(o.mobile&&t.searchMobile&&o.mobile.includes(t.keyword)))))}addToBlockList(t){t.forEach((t=>{this.blockList.includes(t)||this.blockList.push(t)}))}removeFromBlockList(t){t.forEach((t=>{var o=this.blockList.indexOf(t);-1!==o&&this.blockList.splice(o,1)}))}checkBlock(t){var o={};return t.forEach((t=>{o[t]=this.blockList.includes(t)})),o}}var yo={type:"string",required:!0,allowEmpty:!1},Mo={type:"string",required:!1,allowEmpty:!0},_o={name:{type:"string",required:!1,allowEmpty:!0},avatar:Mo,sign:Mo,email:Mo,birthday:Mo,mobile:Mo,gender:{type:"number",required:!1},serverExtension:Mo};class V2NIMUserServiceImpl extends V2Service{constructor(t){super("V2NIMUserService",t),registerParser({cmdMap:vo,cmdConfig:Io}),this.model=new V2NIMUserModelImpl,"v2"===this.core.options.apiVersion&&this.setListener()}reset(){this.model.reset()}setListener(){this.core.eventBus.on("forwardReceive/V2NIMUserService/updateBlockList",((t,o)=>{o?this.model.addToBlockList([t]):this.model.removeFromBlockList([t]),o?this.emitBlockListAdded(t):this.emit("onBlockListRemoved",t)})),this.core.eventBus.on("forwardReceive/V2NIMUserService/updateUserProfile",(t=>{this.updateUserProfileInMemory(t)}))}emit(t,...o){var a=`${this.name}::emit ${t.toString()}`;if("onUserProfileChanged"===t){var m=o[0];this.logger.log(`${a}`,m.map((t=>`id:${t.accountId};name:${t.name};updateTime:${t.updateTime}`)))}else if("onBlockListAdded"===t){var u=o[0];this.logger.log(`${a}`,`id:${u.accountId};name:${u.name};updateTime:${u.updateTime}`)}else this.logger.log(`${a}`,...o);return super.emit(t,...o)}getUserList(t){return __awaiter(this,void 0,void 0,(function*(){return this.checkV2(),this._getUserList(t)}))}_getUserList(t){var o;return __awaiter(this,void 0,void 0,(function*(){validate({accountIds:zi},{accountIds:t},"",!0);var a=[];t.forEach((t=>{this.model.getUser(t)||a.push(t)}));var m=null;a.length>0&&(m=yield this.core.sendCmd("v2GetUserList",{accountIds:a})),((null===(o=null==m?void 0:m.content)||void 0===o?void 0:o.data)||[]).forEach((t=>{this.model.setUser(t)}));var u=[];return t.forEach((t=>{var o=this.model.getUser(t);o&&u.push(o)})),u}))}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 o=(yield this.core.sendCmd("v2GetUserList",{accountIds:t})).content.data||[],a=[];o.forEach((t=>{var o=this.model.getUser(t.accountId);this.compareUserForUpdate(o,t)&&a.push(t),this.model.setUser(t)}));var m=t.reduce(((t,o)=>{var a=this.model.getUser(o);return a&&t.push(a),t}),[]);return a.length>0&&this.emit("onUserProfileChanged",a),m}))}compareUserForUpdate(t,o){return!t||!("number"==typeof t.updateTime&&"number"==typeof o.updateTime&&t.updateTime>=o.updateTime)}updateSelfUserProfile(t){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(_o,t,"",!0);var o=yield this.core.sendCmd("v2UpdateSelfUserProfile",{tag:Object.assign(Object.assign({},t),{accountId:this.core.account})});yield this.updateUserProfileInMemory(Object.assign(Object.assign({},t),{updateTime:o.content.updateTime}))}))}addUserToBlockList(t){return __awaiter(this,void 0,void 0,(function*(){if(this.checkV2(),t===this.core.account)throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"Cannot block yourself"}});validate({accountId:yo},{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:Me.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"Cannot unblock yourself"}});validate({accountId:yo},{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:Me.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:zi},{accountIds:t},"",!0),Promise.resolve(this.model.checkBlock(t))}updateUserProfileInMemory(t){return __awaiter(this,void 0,void 0,(function*(){var o=this.model.getUser(this.core.account);o?(Object.assign(o,t),this.model.setUser(o)):o=(yield this._getUserList([this.core.account]))[0];o&&this.emit("onUserProfileChanged",[o])}))}onUpdateUserProfileHandler(t){return __awaiter(this,void 0,void 0,(function*(){var o=t.content.data;yield this.updateUserProfileInMemory(o)}))}onUpdateBlockListHandler(t){var o=t.content.accountId;t.content.addToBlockList?(this.model.addToBlockList([o]),this.emitBlockListAdded(o)):(this.model.removeFromBlockList([o]),this.emit("onBlockListRemoved",o))}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 o=t.content.user;this.model.setUser(o)}checkUserUpdate(t,o){var a=t.senderId;a!==this.core.account&&this.refreshUserInfo(a,o)}refreshUserInfo(t,o=0){return __awaiter(this,void 0,void 0,(function*(){if(t&&"string"==typeof t){var a=this.model.getUser(t),m=[];if(!a||a&&"number"==typeof a.updateTime&&"number"==typeof o&&!isNaN(a.updateTime)&&!isNaN(o)&&a.updateTime<o)try{m=(yield this.core.sendCmd("v2GetUserList",{accountIds:[t]})).content.data}catch(o){return void this.logger.warn(`V2NIMUserService:refreshUserInfo: failed for ${t}`)}for(var u of m)this.model.setUser(u),this.emit("onUserProfileChanged",[u])}}))}emitBlockListAdded(t){return __awaiter(this,void 0,void 0,(function*(){var o=yield this._getUserList([t]);1===o.length&&this.emit("onBlockListAdded",o[0])}))}v2OnUpdateMuteListHandler(t){return __awaiter(this,void 0,void 0,(function*(){var{accountId:o,mute:a}=t.content,m=a?1:0;this.core.eventBus.emit("v2NIMUserService/updateMuteList",o,m)}))}}var Eo="V2NIMFriendService",So={"35_1":"v2AddFriend","35_2":"v2DeleteFriend","35_3":"v2SetFriendInfo","35_4":"v2IncFriendInfo","12_101":"v2OnAddFriend","12_102":"v2OnDeleteFriend","12_103":"v2OnUpdateFriendInfo","12_5":"v2SyncFriendList","12_6":"v2SyncFriendUserList"},To={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},Co={v2AddFriend:{sid:35,cid:1,service:Eo,params:[{type:"String",name:"accountId"},{type:"Byte",name:"verifyType"},{type:"String",name:"postscript"}],response:[]},v2DeleteFriend:{sid:35,cid:2,service:Eo,params:[{type:"String",name:"accountId"},{type:"Property",name:"params",reflectMapper:{deleteAlias:{id:1,converter:boolToInt}}}]},v2SetFriendInfo:{sid:35,cid:3,service:Eo,params:[{type:"Property",name:"tag",reflectMapper:To}]},v2OnAddFriend:{sid:12,cid:101,service:Eo,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:Eo,response:[{type:"String",name:"accountId"}]},v2OnUpdateFriendInfo:{sid:12,cid:103,service:Eo,response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(To)}]},v2SyncFriendList:{sid:12,cid:5,service:Eo,response:[{type:"PropertyArray",name:"friends",reflectMapper:invertSerializeItem(To)},{type:"Long",name:"timetag"}]},v2SyncFriendUserList:{sid:12,cid:6,service:Eo,response:[{type:"PropertyArray",name:"users",reflectMapper:invertSerializeItem(fo)}]},v2IncFriendInfo:{sid:35,cid:4,service:Eo,params:[{type:"Long",name:"timetag"}],response:[{type:"PropertyArray",name:"friends",reflectMapper:invertSerializeItem(To)},{type:"Long",name:"timetag"}]}},No={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}}}},Ao={accountId:{type:"string",required:!0,allowEmpty:!1},params:{type:"object",required:!1,rules:{deleteAlias:{type:"boolean",required:!1}}}},Oo={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}}}},Ro={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}};function checkApplication(t,o){if(validate(Ro,t,"",!0),t&&t.applicantAccountId!==o&&t.recipientAccountId!==o)throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"Friend application is not your own"}})}var bo={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,o){this.core=t,this.service=o}processSysNotification(t){if(6===t.type){var o=t.senderId;this.core.V2NIMFriendService.handleDeleteFriend(o,2)}else if(5===t.type)try{var a=JSON.parse(t.content);if(1===(null==a?void 0:a.vt)){this.core.V2NIMFriendService.handleAddFriend(t.senderId,t.timestamp);var m={applicantAccountId:t.senderId,recipientAccountId:t.receiverId,operatorAccountId:t.senderId,postscript:t.postscript,timestamp:t.timestamp,status:4,read:!1};this.service.notificationModel.appendFriendAddApplication(m),this.service.notificationModel.updateFriendAddApplicationStatus(m.applicantAccountId,4,m.applicantAccountId)}else if(2===(null==a?void 0:a.vt)){var u={applicantAccountId:t.senderId,recipientAccountId:t.receiverId,operatorAccountId:t.senderId,postscript:t.postscript,timestamp:t.timestamp,status:0,read:!1};this.service.handleApplyFriend(u),this.service.notificationModel.appendFriendAddApplication(u)}else if(3===(null==a?void 0:a.vt)){this.core.V2NIMFriendService.handleAddFriend(t.senderId,t.timestamp);var h={applicantAccountId:t.receiverId,recipientAccountId:t.senderId,operatorAccountId:t.senderId,timestamp:t.timestamp,postscript:t.postscript,status:1,read:!1};this.service.notificationModel.appendFriendAddApplication(h)}else if(4===(null==a?void 0:a.vt)){var g={applicantAccountId:t.receiverId,recipientAccountId:t.senderId,operatorAccountId:t.senderId,timestamp:t.timestamp,postscript:t.postscript,status:2,read:!1};this.service.notificationModel.appendFriendAddApplication(g),this.service.emit("onFriendAddRejected",g)}}catch(t){this.core.logger.warn("V2NIMFriendNotificationImpl::processSysNotification, parse content error:",t)}}}class V2NIMFriendModelImpl{constructor(){this.validFriendIds=new Set,this.friendMap=new Map,this.friendTimetag=0}reset(){this.friendMap.clear(),this.validFriendIds.clear()}upsertFriend(t,o){delete o.relationShip;var a=this.friendMap.get(t)||{},m=Object.assign({accountId:t},a,o);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((o=>{var a=void 0===t.searchAlias||t.searchAlias;return void 0!==o&&(!!(a&&o.alias&&o.alias.includes(t.keyword))||!(!t.searchAccountId||!o.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}}class V2NIMFriendNotificationModelImpl{constructor(){this.list=[],this.maxCount=1e3}reset(){this.list=[]}updateFriendAddApplicationStatus(t,o,a){if(0!==o)for(var m of this.list)m.applicantAccountId===t&&0===m.status&&(m.status=o,m.operatorAccountId=a)}getAddApplicationList(t){var o=void 0===t.offset?0:t.offset,a=this.list.filter((o=>{var a=t.status||[];return 0===a.length||!!a.includes(o.status)})).reverse(),m=t.limit||50,u=a.slice(o,o+m),h=o+m>=a.length;return{infos:u,finished:h,offset:h?0:o+m}}checkSameApplication(t,o,a=!1){return t.applicantAccountId===o.applicantAccountId&&t.recipientAccountId===o.recipientAccountId&&(!a||t.timestamp===o.timestamp)}setAllApplicationRead(){for(var t of this.list)t.read=!0}setApplicationRead(t){for(var o of this.list)this.checkSameApplication(o,t)&&(o.read=!0)}getAddApplicationUnreadCount(){var t=new Set;for(var o of this.list)o.read||0!==o.status||t.add(o.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((o=>{if(!this.checkSameApplication(o,t,!1))return o})).filter((t=>t))}}class V2NIMUFriendServiceImpl extends V2Service{constructor(t){super("V2NIMFriendService",t),this.notification=new V2NIMFriendNotificationImpl(this.core,this),this.model=new V2NIMFriendModelImpl,this.notificationModel=new V2NIMFriendNotificationModelImpl,this.core._registerDep(V2NIMUserServiceImpl,"V2NIMUserService"),"v2"===this.core.options.apiVersion&&(registerParser({cmdMap:So,cmdConfig:Co}),this.setListener())}reset(){this.model.reset()}setListener(){this.core.eventBus.on("V2NIMFriendService/sysNotification",this.notification.processSysNotification.bind(this.notification)),this.core.eventBus.on("forwardReceive/V2NIMFriendService/addFriend",this.handleAddFriend.bind(this)),this.core.eventBus.on("forwardReceive/V2NIMFriendService/deleteFriend",this.handleDeleteFriend.bind(this)),this.core.eventBus.on("forwardReceive/V2NIMFriendService/setFriendInfo",this.handleSetFriendInfo.bind(this)),this.core.eventBus.on("forwardReceive/V2NIMFriendService/acceptAddApplication",this.handlePassFriendApply.bind(this)),this.core.eventBus.on("forwardReceive/V2NIMFriendService/rejectAddApplication",this.handleRejectFriendApply.bind(this))}emit(t,...o){var a=`${this.name}::emit ${t.toString()}`;if("onFriendAdded"===t||"onFriendInfoChanged"===t){var m=o[0];this.logger.log(`${a}`,`${m.accountId};updateTime:${m.updateTime}`)}else this.logger.log(`${a}`,...o);return super.emit(t,...o)}get hasUserService(){var t;return!!(null===(t=this.core.V2NIMUserService)||void 0===t?void 0:t.name)}addFriend(t,o){return __awaiter(this,void 0,void 0,(function*(){if(this.checkV2(),t===this.core.account)throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"Cannot add yourself"}});validate(No,{accountId:t,params:o},"",!0),yield this.core.sendCmd("v2AddFriend",{accountId:t,verifyType:o.addMode,postscript:o.postscript||""}),1===o.addMode&&(yield this.handleAddFriend(t),this.notificationModel.updateFriendAddApplicationStatus(t,4,this.core.account))}))}deleteFriend(t,o){return __awaiter(this,void 0,void 0,(function*(){if(this.checkV2(),t===this.core.account)throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"Cannot delete yourself"}});validate(Ao,{accountId:t,params:o},"",!0),yield this.core.sendCmd("v2DeleteFriend",{accountId:t,params:o}),o.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(o){throw this.handlePassFriendApply(t.applicantAccountId,o),o}}))}rejectAddApplication(t,o){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:o||""}),this.handleRejectFriendApply({applicantAccountId:t.applicantAccountId,recipientAccountId:t.recipientAccountId,operatorAccountId:this.core.account,postscript:o||"",timestamp:this.core.timeOrigin.getNTPTime(),read:!1,status:2})}catch(a){throw this.handleRejectFriendApply({applicantAccountId:t.applicantAccountId,recipientAccountId:t.recipientAccountId,operatorAccountId:this.core.account,postscript:o||"",timestamp:this.core.timeOrigin.getNTPTime(),read:!1,status:3},a),a}}))}setFriendInfo(t,o){return __awaiter(this,void 0,void 0,(function*(){if(this.checkV2(),validate(Oo,{accountId:t,params:o},"",!0),t===this.core.account)throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"Cannot set yourself"}});yield this.core.sendCmd("v2SetFriendInfo",{tag:Object.assign({accountId:t},o)}),this.handleSetFriendInfo(t,o)}))}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 o={};return t.forEach((t=>{o[t]=!!this.model.getFriend(t)})),o}))}getAddApplicationList(t){return __awaiter(this,void 0,void 0,(function*(){return this.checkV2(),this.core.V2NIMLoginService.checkIllegalState(),validate(bo,t,"",!0),this.notificationModel.getAddApplicationList(t)}))}setAddApplicationRead(){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),this.core.V2NIMLoginService.checkIllegalState(),this.notificationModel.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.setApplicationRead(t)):this.notificationModel.setAllApplicationRead()}))}getAddApplicationUnreadCount(){return __awaiter(this,void 0,void 0,(function*(){return this.checkV2(),this.core.V2NIMLoginService.checkIllegalState(),this.notificationModel.getAddApplicationUnreadCount()}))}clearAllAddApplication(){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),this.core.V2NIMLoginService.checkIllegalState(),this.notificationModel.clearApplicationList()}))}deleteAddApplication(t){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),this.core.V2NIMLoginService.checkIllegalState(),checkApplication(t,this.core.account),this.notificationModel.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:Me.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"searchAlias and searchAccountId cannot be false at the same time"}});return this.computedFields(this.model.getFriendListBySearchOption(t))}))}v2OnAddFriendHandler(t){var{accountId:o,verifyType:a,postscript:m}=t.content;if(1===a)this.handleAddFriend(o),this.notificationModel.updateFriendAddApplicationStatus(o,4,this.core.account);else if(2===a){var u={applicantAccountId:this.core.account,recipientAccountId:o,operatorAccountId:this.core.account,postscript:m,timestamp:this.core.timeOrigin.getNTPTime(),status:0,read:!1};this.handleApplyFriend(u)}else if(3===a)this.handlePassFriendApply(o);else if(4===a){var h={applicantAccountId:o,recipientAccountId:this.core.account,operatorAccountId:this.core.account,postscript:m,timestamp:this.core.timeOrigin.getNTPTime(),status:2,read:!1};this.handleRejectFriendApply(h)}}v2OnDeleteFriendHandler(t){var{accountId:o}=t.content;this.handleDeleteFriend(o)}v2OnUpdateFriendInfoHandler(t){var{data:o}=t.content,a=this.model.upsertFriend(o.accountId,o);this.emit("onFriendInfoChanged",this.computedField(a))}v2SyncFriendListHandler(t){var{friends:o,timetag:a}=t.content;this.model.setFriendTimetag(a),o.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:o}=t.content;this.hasUserService&&o.forEach((t=>{this.core.V2NIMUserService.model.setUser(t)}))}handleApplyFriend(t){this.emit("onFriendAddApplication",t)}handleAddFriend(t,o){return __awaiter(this,void 0,void 0,(function*(){this.model.addFriend(t),yield this.incrementSyncFriend(),yield this.core.V2NIMUserService.refreshUserInfo(t);var o=this.model.getFriend(t);o&&this.emit("onFriendAdded",this.computedField(o))}))}handleDeleteFriend(t,o){o=void 0===o?1:o,this.emit("onFriendDeleted",t,o),this.model.deleteFriend(t)}handleSetFriendInfo(t,o){var a=this.model.upsertFriend(t,o);this.emit("onFriendInfoChanged",this.computedField(a))}handlePassFriendApply(t,o){var a=o?null==o?void 0:o.code:200;if(!(a>=19e4||a===Me.V2NIM_ERROR_CODE_FRIEND_OPERATION_RATE_LIMIT))if(200===a||a===Me.V2NIM_ERROR_CODE_FRIEND_ALREADY_EXIST)this.notificationModel.updateFriendAddApplicationStatus(t,1,this.core.account),this.handleAddFriend(t);else{if(a>=500&&a<=599&&509!==a)return;this.notificationModel.updateFriendAddApplicationStatus(t,3,this.core.account)}}handleRejectFriendApply(t,o){var a=o?null==o?void 0:o.code:200;if(!(a>=19e4||a===Me.V2NIM_ERROR_CODE_FRIEND_OPERATION_RATE_LIMIT))if(200===a)this.emit("onFriendAddRejected",t),this.notificationModel.updateFriendAddApplicationStatus(t.applicantAccountId,2,this.core.account);else if(a===Me.V2NIM_ERROR_CODE_FRIEND_ALREADY_EXIST)this.notificationModel.updateFriendAddApplicationStatus(t.applicantAccountId,1,this.core.account);else{if(a>=500&&a<=599&&509!==a)return;this.notificationModel.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:o,timetag:a}=t.content;this.model.setFriendTimetag(a),o.forEach((t=>{this.model.upsertFriend(t.accountId,t)}))}))}computedFields(t){return t.map((t=>this.computedField(t)))}computedField(t){var o,a,m=null===(a=null===(o=this.core.V2NIMUserService)||void 0===o?void 0:o.model)||void 0===a?void 0:a.getUser(t.accountId);return m?Object.assign({},t,{userProfile:m}):t}}var Vo={muteMode:{type:"enum",values:[2,0,1]}},ko={accountId:{type:"string",required:!0,allowEmpty:!1},muteMode:{type:"enum",required:!0,values:[2,0,1]}},Po={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}}},Lo={config:{type:"object",required:!0,rules:{apns:Po,hwPush:Po,miPush:Po,vivoPush:Po,oppoPush:Po,honorPush:Po,fcmPush:Po,mzPush:Po}}},wo="V2NIMSettingService",Do={"34_1":"v2SetDeviceToken","34_2":"v2SetAppBackground","34_15":"v2SetPushMobileOnDesktopOnline","3_115":"v2SettingMutilSyncDonnop","4_13":"v2SettingSyncDonnop"},Uo={need:{id:1,converter:t=>t?2:1,retConverter:t=>"2"===t}},xo={v2SetDeviceToken:{sid:34,cid:1,service:wo,params:[{type:"String",name:"certificateName"},{type:"String",name:"pushDeviceToken"},{type:"Int",name:"pushkit"}]},v2SetAppBackground:{sid:34,cid:2,service:wo,params:[{type:"Bool",name:"isBackground"},{type:"Int",name:"badge"}]},v2SetPushMobileOnDesktopOnline:{sid:34,cid:15,service:wo,params:[{type:"Property",name:"tag",reflectMapper:Uo}]},v2SettingMutilSyncDonnop:{sid:3,cid:115,service:wo,response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Uo)},{type:"Long",name:"timetag"}]},v2SettingSyncDonnop:{sid:4,cid:13,service:wo,response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Uo)},{type:"Long",name:"timetag"}]}};class V2NIMSettingHandlerImpl{constructor(t,o){this.core=t,this.service=o}v2SettingMutilSyncDonnopHandler(t){var{need:o}=t.content.data;this.service.needToPushMobileOnDesktopOnline=o,this.service.emit("onPushMobileOnDesktopOnline",o)}v2SettingSyncDonnopHandler(t){var{need:o}=t.content.data;this.service.needToPushMobileOnDesktopOnline=o,this.service.emit("onPushMobileOnDesktopOnline",o)}}var Fo=Fo||function(t){var o;"undefined"!=typeof window&&window.crypto&&(o=window.crypto),"undefined"!=typeof self&&self.crypto&&(o=self.crypto),"undefined"!=typeof globalThis&&globalThis.crypto&&(o=globalThis.crypto),!o&&"undefined"!=typeof window&&window.msCrypto&&(o=window.msCrypto),!o&&"undefined"!=typeof global&&global.crypto&&(o=global.crypto);var cryptoSecureRandomInt=function(){if(o){if("function"==typeof o.getRandomValues)try{return o.getRandomValues(new Uint32Array(1))[0]}catch(t){}if("function"==typeof o.randomBytes)try{return o.randomBytes(4).readInt32LE()}catch(t){}}throw new Error("Native crypto module could not be used to get secure random number.")},a=Object.create||function(){function F(){}return function(t){var o;return F.prototype=t,o=new F,F.prototype=null,o}}(),m={},u=m.lib={},h=u.Base={extend:function(t){var o=a(this);return t&&o.mixIn(t),o.hasOwnProperty("init")&&this.init!==o.init||(o.init=function(){o.$super.init.apply(this,arguments)}),o.init.prototype=o,o.$super=this,o},create:function(){var t=this.extend();return t.init.apply(t,arguments),t},init:function(){},mixIn:function(t){for(var o in t)t.hasOwnProperty(o)&&(this[o]=t[o]);t.hasOwnProperty("toString")&&(this.toString=t.toString)},clone:function(){return this.init.prototype.extend(this)}},g=u.WordArray=h.extend({init:function(t,o){t=this.words=t||[],this.sigBytes=null!=o?o:4*t.length},toString:function(t){return(t||M).stringify(this)},concat:function(t){var o=this.words,a=t.words,m=this.sigBytes,u=t.sigBytes;if(this.clamp(),m%4)for(var h=0;h<u;h++){var g=a[h>>>2]>>>24-h%4*8&255;o[m+h>>>2]|=g<<24-(m+h)%4*8}else for(var I=0;I<u;I+=4)o[m+I>>>2]=a[I>>>2];return this.sigBytes+=u,this},clamp:function(){var o=this.words,a=this.sigBytes;o[a>>>2]&=4294967295<<32-a%4*8,o.length=t.ceil(a/4)},clone:function(){var t=h.clone.call(this);return t.words=this.words.slice(0),t},random:function(t){for(var o=[],a=0;a<t;a+=4)o.push(cryptoSecureRandomInt());return new g.init(o,t)}}),I=m.enc={},M=I.Hex={stringify:function(t){for(var o=t.words,a=t.sigBytes,m=[],u=0;u<a;u++){var h=o[u>>>2]>>>24-u%4*8&255;m.push((h>>>4).toString(16)),m.push((15&h).toString(16))}return m.join("")},parse:function(t){for(var o=t.length,a=[],m=0;m<o;m+=2)a[m>>>3]|=parseInt(t.substr(m,2),16)<<24-m%8*4;return new g.init(a,o/2)}},_=I.Latin1={stringify:function(t){for(var o=t.words,a=t.sigBytes,m=[],u=0;u<a;u++){var h=o[u>>>2]>>>24-u%4*8&255;m.push(String.fromCharCode(h))}return m.join("")},parse:function(t){for(var o=t.length,a=[],m=0;m<o;m++)a[m>>>2]|=(255&t.charCodeAt(m))<<24-m%4*8;return new g.init(a,o)}},E=I.Utf8={stringify:function(t){try{return decodeURIComponent(escape(_.stringify(t)))}catch(t){throw new Error("Malformed UTF-8 data")}},parse:function(t){return _.parse(unescape(encodeURIComponent(t)))}},S=u.BufferedBlockAlgorithm=h.extend({reset:function(){this._data=new g.init,this._nDataBytes=0},_append:function(t){"string"==typeof t&&(t=E.parse(t)),this._data.concat(t),this._nDataBytes+=t.sigBytes},_process:function(o){var a,m=this._data,u=m.words,h=m.sigBytes,I=this.blockSize,M=h/(4*I),_=(M=o?t.ceil(M):t.max((0|M)-this._minBufferSize,0))*I,E=t.min(4*_,h);if(_){for(var S=0;S<_;S+=I)this._doProcessBlock(u,S);a=u.splice(0,_),m.sigBytes-=E}return new g.init(a,E)},clone:function(){var t=h.clone.call(this);return t._data=this._data.clone(),t},_minBufferSize:0});u.Hasher=S.extend({cfg:h.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(o,a){return new t.init(a).finalize(o)}},_createHmacHelper:function(t){return function(o,a){return new T.HMAC.init(t,a).finalize(o)}}});var T=m.algo={};return m}(Math),Bo=Fo.enc.Utf8,$o=Fo,jo=$o.lib,Go=jo.Base,qo=jo.WordArray,Ho=$o.algo,zo=Ho.MD5,Yo=Ho.EvpKDF=Go.extend({cfg:Go.extend({keySize:4,hasher:zo,iterations:1}),init:function(t){this.cfg=this.cfg.extend(t)},compute:function(t,o){for(var a,m=this.cfg,u=m.hasher.create(),h=qo.create(),g=h.words,I=m.keySize,M=m.iterations;g.length<I;){a&&u.update(a),a=u.update(t).finalize(o),u.reset();for(var _=1;_<M;_++)a=u.finalize(a),u.reset();h.concat(a)}return h.sigBytes=4*I,h}});$o.EvpKDF=function(t,o,a){return Yo.create(a).compute(t,o)},Fo.EvpKDF;var Ko=Fo,Wo=Ko.lib.WordArray;Ko.enc.Base64={stringify:function(t){var o=t.words,a=t.sigBytes,m=this._map;t.clamp();for(var u=[],h=0;h<a;h+=3)for(var g=(o[h>>>2]>>>24-h%4*8&255)<<16|(o[h+1>>>2]>>>24-(h+1)%4*8&255)<<8|o[h+2>>>2]>>>24-(h+2)%4*8&255,I=0;I<4&&h+.75*I<a;I++)u.push(m.charAt(g>>>6*(3-I)&63));var M=m.charAt(64);if(M)for(;u.length%4;)u.push(M);return u.join("")},parse:function(t){var o=t.length,a=this._map,m=this._reverseMap;if(!m){m=this._reverseMap=[];for(var u=0;u<a.length;u++)m[a.charCodeAt(u)]=u}var h=a.charAt(64);if(h){var g=t.indexOf(h);-1!==g&&(o=g)}return function parseLoop(t,o,a){for(var m=[],u=0,h=0;h<o;h++)if(h%4){var g=a[t.charCodeAt(h-1)]<<h%4*2|a[t.charCodeAt(h)]>>>6-h%4*2;m[u>>>2]|=g<<24-u%4*8,u++}return Wo.create(m,u)}(t,o,m)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="},Fo.enc.Base64,function(t){t.lib.Cipher||function(){var o=t,a=o.lib,m=a.Base,u=a.WordArray,h=a.BufferedBlockAlgorithm,g=o.enc;g.Utf8;var I=g.Base64,M=o.algo.EvpKDF,_=a.Cipher=h.extend({cfg:m.extend(),createEncryptor:function(t,o){return this.create(this._ENC_XFORM_MODE,t,o)},createDecryptor:function(t,o){return this.create(this._DEC_XFORM_MODE,t,o)},init:function(t,o,a){this.cfg=this.cfg.extend(a),this._xformMode=t,this._key=o,this.reset()},reset:function(){h.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?b:O}return function(t){return{encrypt:function(o,a,m){return selectCipherStrategy(a).encrypt(t,o,a,m)},decrypt:function(o,a,m){return selectCipherStrategy(a).decrypt(t,o,a,m)}}}}()});a.StreamCipher=_.extend({_doFinalize:function(){return this._process(!0)},blockSize:1});var E=o.mode={},S=a.BlockCipherMode=m.extend({createEncryptor:function(t,o){return this.Encryptor.create(t,o)},createDecryptor:function(t,o){return this.Decryptor.create(t,o)},init:function(t,o){this._cipher=t,this._iv=o}}),T=E.CBC=function(){var t=S.extend();function xorBlock(t,o,a){var m,u=this._iv;u?(m=u,this._iv=void 0):m=this._prevBlock;for(var h=0;h<a;h++)t[o+h]^=m[h]}return t.Encryptor=t.extend({processBlock:function(t,o){var a=this._cipher,m=a.blockSize;xorBlock.call(this,t,o,m),a.encryptBlock(t,o),this._prevBlock=t.slice(o,o+m)}}),t.Decryptor=t.extend({processBlock:function(t,o){var a=this._cipher,m=a.blockSize,u=t.slice(o,o+m);a.decryptBlock(t,o),xorBlock.call(this,t,o,m),this._prevBlock=u}}),t}(),C=(o.pad={}).Pkcs7={pad:function(t,o){for(var a=4*o,m=a-t.sigBytes%a,h=m<<24|m<<16|m<<8|m,g=[],I=0;I<m;I+=4)g.push(h);var M=u.create(g,m);t.concat(M)},unpad:function(t){var o=255&t.words[t.sigBytes-1>>>2];t.sigBytes-=o}};a.BlockCipher=_.extend({cfg:_.cfg.extend({mode:T,padding:C}),reset:function(){var t;_.reset.call(this);var o=this.cfg,a=o.iv,m=o.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,a&&a.words):(this._mode=t.call(m,this,a&&a.words),this._mode.__creator=t)},_doProcessBlock:function(t,o){this._mode.processBlock(t,o)},_doFinalize:function(){var t,o=this.cfg.padding;return this._xformMode==this._ENC_XFORM_MODE?(o.pad(this._data,this.blockSize),t=this._process(!0)):(t=this._process(!0),o.unpad(t)),t},blockSize:4});var N=a.CipherParams=m.extend({init:function(t){this.mixIn(t)},toString:function(t){return(t||this.formatter).stringify(this)}}),A=(o.format={}).OpenSSL={stringify:function(t){var o=t.ciphertext,a=t.salt;return(a?u.create([1398893684,1701076831]).concat(a).concat(o):o).toString(I)},parse:function(t){var o,a=I.parse(t),m=a.words;return 1398893684==m[0]&&1701076831==m[1]&&(o=u.create(m.slice(2,4)),m.splice(0,4),a.sigBytes-=16),N.create({ciphertext:a,salt:o})}},O=a.SerializableCipher=m.extend({cfg:m.extend({format:A}),encrypt:function(t,o,a,m){m=this.cfg.extend(m);var u=t.createEncryptor(a,m),h=u.finalize(o),g=u.cfg;return N.create({ciphertext:h,key:a,iv:g.iv,algorithm:t,mode:g.mode,padding:g.padding,blockSize:t.blockSize,formatter:m.format})},decrypt:function(t,o,a,m){return m=this.cfg.extend(m),o=this._parse(o,m.format),t.createDecryptor(a,m).finalize(o.ciphertext)},_parse:function(t,o){return"string"==typeof t?o.parse(t,this):t}}),R=(o.kdf={}).OpenSSL={execute:function(t,o,a,m){m||(m=u.random(8));var h=M.create({keySize:o+a}).compute(t,m),g=u.create(h.words.slice(o),4*a);return h.sigBytes=4*o,N.create({key:h,iv:g,salt:m})}},b=a.PasswordBasedCipher=O.extend({cfg:O.cfg.extend({kdf:R}),encrypt:function(t,o,a,m){var u=(m=this.cfg.extend(m)).kdf.execute(a,t.keySize,t.ivSize);m.iv=u.iv;var h=O.encrypt.call(this,t,o,u.key,m);return h.mixIn(u),h},decrypt:function(t,o,a,m){m=this.cfg.extend(m),o=this._parse(o,m.format);var u=m.kdf.execute(a,t.keySize,t.ivSize,o.salt);return m.iv=u.iv,O.decrypt.call(this,t,o,u.key,m)}})}()}(Fo);var Jo=Fo,Xo=Jo.lib.StreamCipher,Qo=Jo.algo,Zo=Qo.RC4=Xo.extend({_doReset:function(){for(var t=this._key,o=t.words,a=t.sigBytes,m=this._S=[],u=0;u<256;u++)m[u]=u;u=0;for(var h=0;u<256;u++){var g=u%a,I=o[g>>>2]>>>24-g%4*8&255;h=(h+m[u]+I)%256;var M=m[u];m[u]=m[h],m[h]=M}this._i=this._j=0},_doProcessBlock:function(t,o){t[o]^=generateKeystreamWord.call(this)},keySize:8,ivSize:0});function generateKeystreamWord(){for(var t=this._S,o=this._i,a=this._j,m=0,u=0;u<4;u++){a=(a+t[o=(o+1)%256])%256;var h=t[o];t[o]=t[a],t[a]=h,m|=t[(t[o]+t[a])%256]<<24-8*u}return this._i=o,this._j=a,m}Jo.RC4=Xo._createHelper(Zo);var es=Qo.RC4Drop=Zo.extend({cfg:Zo.cfg.extend({drop:192}),_doReset:function(){Zo._doReset.call(this);for(var t=this.cfg.drop;t>0;t--)generateKeystreamWord.call(this)}});Jo.RC4Drop=Xo._createHelper(es);var ts=Fo.RC4;class V2NIMSettingPushImpl{constructor(t,o){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=o,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,o,a)=>{if(this.logger.log(`OfflinePushService:: type: ${t}, tokenName: ${o}, token: ${a}`),a){var m="",u=Ae.getSystemInfo()||{},h=u.os?u.os.toLowerCase():"";this.aosPushInfo&&this.aosPushInfo.pushType?m=this.aosPushInfo.pushType:"ios"===h?m="":"android"===h&&(m="8"),this.pushTokenToServer(m,a)}else this.logger.warn("OfflinePushService:: token is empty. Please check your parameters")})),new Promise(((t,o)=>{var a;null===(a=this.offlinePushPlugin)||void 0===a||a.getDeviceInfo((a=>{try{this.logger.log(`OfflinePushService:getDeviceInfo result ${a?JSON.stringify(a):""}`),t(JSON.parse(a))}catch(t){o(new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_INTERNAL,detail:{reason:"OfflinePushService:getDeviceInfo error"}}))}})),setTimeout((()=>{o(new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_INTERNAL,detail:{reason:"OfflinePushService:getDeviceInfo timeout"}}))}),2e3)}))}pushTokenToServer(t,o){var a,m,u,h,g,I,M,_,E="",S=this.offlinePushConfig;switch(t){case"5":E=null===(a=null==S?void 0:S.miPush)||void 0===a?void 0:a.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===(u=null==S?void 0:S.mzPush)||void 0===u?void 0:u.certificateName;break;case"8":E=null===(h=null==S?void 0:S.fcmPush)||void 0===h?void 0:h.certificateName;break;case"9":E=null===(g=null==S?void 0:S.vivoPush)||void 0===g?void 0:g.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===(M=null==S?void 0:S.honorPush)||void 0===M?void 0:M.certificateName;break;default:E=null===(_=null==S?void 0:S.apns)||void 0===_?void 0:_.certificateName}if(""===E||void 0===E)this.logger.warn("OfflinePushService:: certificate name is empty for push type: ",t);else try{if("UNIAPP"===Ae.platform){var T=Bo.parse("557d1e3cafa43e2589a588270c53d56f"),C=Bo.stringify(ts.decrypt(o,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:o,pushkit:0})}catch(t){return this.logger.log("OfflinePushService:: decrypt error",t),void this.logger.warn("OfflinePushService:: token before decrypt",o)}}regToken(){var t=Ae.getSystemInfo()||{},o=t.os?t.os.toLowerCase():"";if(this.logger.log("OfflinePushService: os",o),"ios"===o||"android"===o)if(!this.offlinePushPlugin||"UNIAPP"===Ae.platform&&"function"!=typeof this.offlinePushPlugin.getDeviceToken||"React Native"===Ae.platform&&"android"===o&&"function"!=typeof this.offlinePushPlugin.init||"React Native"===Ae.platform&&"ios"===o&&"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"===Ae.platform&&Ae.envPayload.AppState&&Ae.envPayload.AppState.addEventListener("change",this.handleRNAppStateChange.bind(this));var a="";this.aosPushInfo&&this.aosPushInfo.pushType?a=this.aosPushInfo.pushType:"ios"===o?a="":"android"===o&&(a="8"),this.logger.log("OfflinePushService:: prepare to get device token. suggestPushType: "+a),this.logger.log("OfflinePushService push config",JSON.stringify(this.authConfig,null,2),"platform",Ae.platform),"UNIAPP"===Ae.platform?this.offlinePushPlugin.getDeviceToken({suggestPushType:a,config:this.authConfig},(t=>{t?(this.logger.log("OfflinePushService:: token is :"+t),this.pushTokenToServer(a,t)):this.logger.warn("OfflinePushService:: token is empty. Please check your parameters")})):"React Native"===Ae.platform&&"android"===o?(this.logger.log("OfflinePushService:: onLogin",this.core.account,typeof a,a),this.offlinePushPlugin.onLogin(this.core.account,parseInt(a),!1,"")):"React Native"===Ae.platform&&"ios"===o?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(a,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: ${Ae.platform}. os: ${o}`)}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.V2NIMConversationService.getTotalUnreadCount(),isBackground:"background"===t||"inactive"===t},this.setAppBackground(this.appBackgroundOptions.isBackground,this.appBackgroundOptions.badge)}setOfflinePushConfig(t,o){var a,m,u,h,g,I,M,_,E,S,T,C,N,A,O,R,b,V,k,P,L,w,D,U,x,B,$,j,G,q,H,z,Y,K,W,J;this.logger.log("setOfflinePushConfig","plugin",t,"config",o),this.offlinePushPlugin=t,this.offlinePushConfig=o,this.authConfig={xmAppId:null===(m=null===(a=this.offlinePushConfig)||void 0===a?void 0:a.miPush)||void 0===m?void 0:m.appId,xmAppKey:null===(h=null===(u=this.offlinePushConfig)||void 0===u?void 0:u.miPush)||void 0===h?void 0:h.appKey,xmCertificateName:null===(I=null===(g=this.offlinePushConfig)||void 0===g?void 0:g.miPush)||void 0===I?void 0:I.certificateName,hwAppId:null===(_=null===(M=this.offlinePushConfig)||void 0===M?void 0:M.hwPush)||void 0===_?void 0:_.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===(V=null===(b=this.offlinePushConfig)||void 0===b?void 0:b.oppoPush)||void 0===V?void 0:V.certificateName,vivoAppId:null===(P=null===(k=this.offlinePushConfig)||void 0===k?void 0:k.vivoPush)||void 0===P?void 0:P.appId,vivoAppKey:null===(w=null===(L=this.offlinePushConfig)||void 0===L?void 0:L.vivoPush)||void 0===w?void 0:w.appKey,vivoCertificateName:null===(U=null===(D=this.offlinePushConfig)||void 0===D?void 0:D.vivoPush)||void 0===U?void 0:U.certificateName,fcmCertificateName:null===(B=null===(x=this.offlinePushConfig)||void 0===x?void 0:x.fcmPush)||void 0===B?void 0:B.certificateName,mzAppId:null===(j=null===($=this.offlinePushConfig)||void 0===$?void 0:$.mzPush)||void 0===j?void 0:j.appId,mzAppKey:null===(q=null===(G=this.offlinePushConfig)||void 0===G?void 0:G.mzPush)||void 0===q?void 0:q.appKey,mzCertificateName:null===(z=null===(H=this.offlinePushConfig)||void 0===H?void 0:H.mzPush)||void 0===z?void 0:z.certificateName,apnsCertificateName:null===(K=null===(Y=this.offlinePushConfig)||void 0===Y?void 0:Y.apns)||void 0===K?void 0:K.certificateName,honorCertificateName:null===(J=null===(W=this.offlinePushConfig)||void 0===W?void 0:W.honorPush)||void 0===J?void 0:J.certificateName}}setAppBackground(t,o){return __awaiter(this,void 0,void 0,(function*(){this.appBackgroundOptions={isBackground:t,badge:o||0},yield this.core.sendCmd("v2SetAppBackground",{isBackground:t,badge:o||0})}))}}class V2NIMSettingMuteImpl{constructor(t,o){this.p2pMessageMuteModeChangeHandler=(t,o)=>{this.service.emit("onP2PMessageMuteModeChanged",t,o),this.hasUserService&&this.core.V2NIMUserService.model.setAccountMuteMode(t,o);var a=this.core.V2NIMConversationIdUtil.p2pConversationId(t),m=1===o;this.core.eventBus.emit("V2NIMSettingService/setMute",a,m)},this.core=t,this.service=o}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 o=this.core.V2NIMConversationIdUtil.parseConversationType(t),a=this.core.V2NIMConversationIdUtil.parseConversationTargetId(t);return 3===o?0!==this.getTeamMessageMuteMode(a,2):2===o?0!==this.getTeamMessageMuteMode(a,1):!(1!==o||!this.hasUserService)&&!!this.core.V2NIMUserService.model.muteList.has(a)}setTeamMessageMuteMode(t,o,a){return __awaiter(this,void 0,void 0,(function*(){var m=2===o?"v2SuperTeamUpdateSelfMemberInfo":"v2TeamUpdateSelfMemberInfo",u={teamId:t,teamType:o,accountId:this.core.account,bits:a};yield this.core.sendCmd(m,{teamMember:u}),this.core.V2NIMTeamService.memberModel.upsert(u),this.service.emit("onTeamMessageMuteModeChanged",t,o,a);var h=1===o?this.core.V2NIMConversationIdUtil.teamConversationId(t):this.core.V2NIMConversationIdUtil.superTeamConversationId(t),g=this.getConversationMuteStatus(h);this.core.eventBus.emit("V2NIMSettingService/setMute",h,g)}))}getTeamMessageMuteMode(t,o){var a;return"string"!=typeof t||"number"!=typeof o?0:this.hasTeamService?3&((null===(a=this.core.V2NIMTeamService.memberModel.getById(t,o,this.core.account))||void 0===a?void 0:a.bits)||0):0}getAllTeamMessageMuteMode(t){if(!this.hasTeamService)return Promise.resolve({});var o=this.core.V2NIMTeamService.memberModel.chooseList(t),a={};return o.forEach((t=>{if(t.accountId===this.core.account){var o=t.bits||0;a[t.teamId]=3&o}})),Promise.resolve(a)}setP2PMessageMuteMode(t,o){return __awaiter(this,void 0,void 0,(function*(){yield this.core.sendCmd("v2SetP2PMessageMuteMode",{accountId:t,muteMode:1===o}),this.p2pMessageMuteModeChangeHandler(t,o)}))}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,o){this.core=t,this.service=o,this.push=o.push,this.mute=o.mute}setListener(){this.core.eventBus.on("V2NIMSettingService/updateBits",((t,o,a)=>{this.service.emit("onTeamMessageMuteModeChanged",t,o,a)})),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:Do,cmdConfig:xo}))}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,...o){var a=`${this.name}::emit ${t.toString()}`;return this.logger.log(`${a}`,...o),super.emit(t,...o)}getConversationMuteStatus(t){return this.mute.getConversationMuteStatus(t)}setTeamMessageMuteMode(t,o,a){if(!this.hasTeamService)throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_MISUSE,detail:{reason:"setTeamMessageMuteMode: no team service"}});return this.checkV2(),validate(Xi,{teamId:t},"",!0),validate(Zi,{teamType:o},"",!0),validate(Vo,{muteMode:a},"",!0),this.mute.setTeamMessageMuteMode(t,o,a)}getTeamMessageMuteMode(t,o){return this.mute.getTeamMessageMuteMode(t,o)}getAllTeamMessageMuteMode(t){return this.checkV2(),this.checkLogin(),validate(Zi,{teamType:t},"",!0),this.mute.getAllTeamMessageMuteMode(t)}setP2PMessageMuteMode(t,o){if(this.checkV2(),validate(ko,{accountId:t,muteMode:o},"",!0),t===this.core.account)throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"can not set mute mode for self"}});return this.mute.setP2PMessageMuteMode(t,o)}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,o){return this.checkV2(),validate({isBackground:{type:"boolean"},badge:{type:"number",required:!1}},{isBackground:t,badge:o},"",!0),this.push.setAppBackground(t,o)}setOfflinePushConfig(t,o){validate(Lo,{config:o},"",!0),this.push.setOfflinePushConfig(t,o)}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 o=this.aiStreamMap.get(t);return!o||o.isComplete}getAiStreamQueryStatus(t){var o=this.aiStreamMap.get(t);return o?o.queryStatus:0}upsertAiStreamChunks(t,o,a){var m=this.aiStreamMap.get(t);return m&&!m.isComplete&&(m.chunks[o]=a),m||{isComplete:!1,queryStatus:0,chunks:[]}}setAiStream(t,o,a=!1){var m=this.aiStreamMap.get(t);return m?this.aiStreamMap.set(t,Object.assign(Object.assign({},m),o)):a&&this.aiStreamMap.set(t,Object.assign({isComplete:!1,queryStatus:0,chunks:[]},o)),this.aiStreamMap.get(t)||{isComplete:!1,queryStatus:0,chunks:[]}}completeAiStream(t){var o=this.aiStreamMap.get(t);o&&this.aiStreamMap.set(t,Object.assign(Object.assign({},o),{isComplete:!0,queryStatus:0,chunks:[],aiRAGs:void 0}))}}var rs={"4_26":"v2AIChatNotify","29_35":"v2AIProxyModelCall","29_36":"v2AIGetUserList","4_29":"v2AIOnStreamMessageChunk","4_30":"v2AIChatStreamNotify","29_38":"v2AIStopModelStreamCall","29_39":"v2AIStreamQuery","29_40":"v2AIRegenMessage"},is={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}},os={accountId:1,name:3,avatar:4,sign:5,gender:{id:6,retType:"number"},email:7,birthday:8,mobile:9,serverExtension:10,modelType:{id:11,retType:"number"},modelConfig:{id:12,retConverter:t=>{if(t=stringToJSONObject(t)){var o=Object.keys(t).reduce(((o,a)=>(o[function camelCase(t){return(t=t||"").split("_").map(((t,o)=>0===o?t:t[0].toUpperCase()+t.slice(1))).join("")}(a)]=t[a],o)),{});if("string"==typeof o.promptKeys)try{o.promptKeys=JSON.parse(o.promptKeys)}catch(t){}return o}}},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 o=JSON.parse(t);return"number"==typeof o.index?{msg:o.msg||"",type:o.type,lastChunk:{content:o.msg,chunkTime:parseInt(o.timestamp),type:o.type,index:parseInt(o.index)}}:o}catch(t){return}}function aiAgentStreamAIRAGsRetConverter(t){try{var o=JSON.parse(t);return o&&o.length>0?o.map((t=>(t.description=t.desc,delete t.desc,t))):[]}catch(t){return[]}}var ss={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"}},ns={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}},as={serverId:1,clientId:2,type:{id:3,retType:"number"},content:{id:4,retConverter:aiAgentStreamContentRetConverter},aiRAGs:{id:6,retConverter:aiAgentStreamAIRAGsRetConverter}},cs={v2AIChatNotify:{sid:4,cid:26,service:"V2NIMAIService",response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(ss)}]},v2AIProxyModelCall:{sid:29,cid:35,service:"V2NIMAIService",params:[{type:"Property",name:"tag",reflectMapper:is}]},v2AIGetUserList:{sid:29,cid:36,service:"V2NIMAIService",params:[{type:"Property",name:"tag",reflectMapper:{pageToken:1,limit:2}}],response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(os)},{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(Pr)}]},v2AIChatStreamNotify:{sid:4,cid:30,service:"V2NIMAIService",response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(ss)}]},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:ns}],response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(as)}]},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,o){this.core=t,this.service=o,this.logger=this.core.logger}setListener(){}beforeEmit(t,...o){var a,m,u=`${this.service.name}::emit ${t.toString()}`;if("onProxyAIModelCall"===t){var h=o[0];this.logger.log(`${u}`,`requestId:${h.requestId};aiStreamStatus:${h.aiStreamStatus}`)}else if("onProxyAIModelStreamCall"===t){var g=o[0];this.logger.log(`${u}`,`requestId:${g.requestId};chunkIndex:${null===(a=g.content)||void 0===a?void 0:a.lastChunk.index};chunkTime:${null===(m=g.content)||void 0===m?void 0:m.lastChunk.chunkTime}`)}else this.logger.log(`${u}`,...o)}}class V2NIMAIHandlerImpl{constructor(t,o){this.core=t,this.service=o,this.model=o.model,this.logger=this.core.logger}v2AIChatNotifyHandler(t){var o=t.content.data;o&&o.requestId&&(this.model.completeAiStream(o.requestId),o.aiStreamStatus=o.aiStreamStatus||0,o.aiStream=o.aiStream||!1,o.content&&(o.content.msg=o.content.msg||""),this.service.emit("onProxyAIModelCall",o))}v2AIChatStreamNotifyHandler(t){var o=t.content.data;if(o&&o.requestId&&o.content&&o.content.msg){var a=this.model.getAiStream(o.requestId);if(a||(a=this.model.setAiStream(o.requestId,{isComplete:!1,queryStatus:0,chunks:[]},!0)),!a.isComplete){var{lastChunk:m}=o.content;if(0===m.index&&o.aiRAGs&&(a=this.model.setAiStream(o.requestId,{aiRAGs:o.aiRAGs})),this.logger.log(`V2AI::streamNotify requestId:${o.requestId};index:${m.index};cacheChunkLength:${a.chunks.length};chunkTime:${m.chunkTime}.`),0===a.chunks.length&&m.index>0)this.logger.log(`V2AI::streamNotify requestId:${o.requestId};chunks missing 0,currentIdx:${m.index},needQuery:${0===a.queryStatus}.`),0===a.queryStatus&&(a=this.model.setAiStream(o.requestId,{queryStatus:1}),this.service._queryAiStream({clientId:o.requestId,type:4,from:this.core.account,aiAccount:o.accountId,startIndex:0,endIndex:m.index-1}));else if(m.index>0&&a.chunks.length>0&&void 0===a.chunks[m.index-1]){var u=a.chunks.reduce(((t,o,a)=>(void 0!==o&&t.push(a),t)),[]);this.logger.log(`V2AI::streamNotify requestId:${o.requestId};out of order,currenIdx:${m.index},cacheIdx:[${u.join(",")}],needReport:${!a.hasReported}.`),a.hasReported||(a=this.model.setAiStream(o.requestId,{hasReported:!0}),this.reportOutOfOrder({requestId:o.requestId,cacheIds:u,targetIndex:m.index,target:"4-30"}))}(a=this.model.upsertAiStreamChunks(o.requestId,m.index,m.content)).chunks[0]||1!==a.queryStatus?(o.content.msg=a.chunks.join(""),a.aiRAGs&&(o.aiRAGs=a.aiRAGs),this.service.emit("onProxyAIModelStreamCall",o)):this.logger.log(`V2AI::streamNotify requestId:${o.requestId};chunks ignore index:${m.index};queryStatus:${a.queryStatus}.`)}}}v2AIOnStreamMessageChunkHandler(t){var o,a,m,u=completeMessage(this.core,t.content.msg);if(u.streamConfig&&u.streamConfig.lastChunk){var h=this.model.getAiStream(u.messageClientId);if(!h||!h.isComplete){h||(h=this.model.setAiStream(u.messageClientId,{isComplete:!1,queryStatus:0,chunks:[]},!0));var g=u.streamConfig.lastChunk,I=u.messageClientId;if(0===g.index&&(null===(o=u.aiConfig)||void 0===o?void 0:o.aiRAGs)&&(h=this.model.setAiStream(I,{aiRAGs:u.aiConfig.aiRAGs})),this.logger.log(`V2AI::aiStream requestId:${I};index:${g.index};cacheChunkLength:${h.chunks.length};chunkTime:${g.chunkTime}.`),0===h.chunks.length&&g.index>0)this.logger.log(`V2AI::msg:aiStream requestId:${I};chunks missing 0,currentIdx:${g.index},needQuery:${0===h.queryStatus}.`),0===h.queryStatus&&(h=this.model.setAiStream(I,{queryStatus:1}),this.service._queryAiStream({serverId:u.messageServerId,clientId:I,type:(null===(a=u.aiConfig)||void 0===a?void 0:a.accountId)?u.conversationType:5,from:u.senderId,to:u.receiverId,aiAccount:null===(m=u.aiConfig)||void 0===m?void 0:m.accountId,startIndex:0,endIndex:g.index-1}));else if(g.index>0&&h.chunks.length>0&&void 0===h.chunks[g.index-1]){var M=h.chunks.reduce(((t,o,a)=>(void 0!==o&&t.push(a),t)),[]);this.logger.log(`V2AI::msg:aiStream requestId:${I};out of order,currenIdx:${g.index};streamCache.chunks:${JSON.stringify(h.chunks)},cacheIdx:[${M.join(",")}],needReport:${!h.hasReported}.`),h.hasReported||(h=this.model.setAiStream(I,{hasReported:!0}),this.reportOutOfOrder({requestId:I,cacheIds:M,targetIndex:g.index,target:"4-29"}))}(h=this.model.upsertAiStreamChunks(I,g.index,g.content)).chunks[0]||1!==h.queryStatus?(u.streamConfig.status=-1,u.aiConfig&&(u.aiConfig.aiStreamStatus=-1),u.text=h.chunks.join(""),h.aiRAGs&&u.aiConfig&&(u.aiConfig.aiRAGs=h.aiRAGs),h.msg&&(u=Object.assign({},h.msg,Object.assign({text:u.text,modifyTime:g.chunkTime,modifyAccountId:h.msg.senderId,streamConfig:u.streamConfig},u.aiConfig?{aiConfig:u.aiConfig}:{}))),this.core.eventBus.emit("V2NIMAIService/receiveMessagesModified",[u])):this.logger.log(`V2AI::msg:callStream requestId:${I};chunks ignore index:${g.index};queryStatus:${h.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:rs,cmdConfig:cs})}setListener(){this.event.setListener()}reset(){this.model.reset()}emit(t,...o){return this.event.beforeEmit(t,...o),super.emit(t,...o)}getAIUserList(){return __awaiter(this,void 0,void 0,(function*(){return this.checkV2(),(yield this.core.sendCmd("v2AIGetUserList",{tag:{}})).content.datas}))}proxyAIModelCall(t){return __awaiter(this,void 0,void 0,(function*(){if(validate(wt,t,"",!0),this.model.getAiStream(t.requestId))throw new V2NIMErrorImpl({code:Me.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(Dt,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 o=yield this.core.sendCmd("v2AIStreamQuery",{tag:t});this.model.setAiStream(t.clientId,{queryStatus:2});var a=o.content.datas;if(!(a&&a.length>0))return;a.forEach((t=>{var o=t.clientId,a=this.model.getAiStream(o);if(a&&(!a||!a.isComplete)&&t.content&&t.content.lastChunk){var m=t.content.lastChunk;this.model.upsertAiStreamChunks(o,m.index,m.content),0===m.index&&t.aiRAGs&&this.model.setAiStream(o,{aiRAGs:t.aiRAGs}),this.logger.log(`V2AI::queryAiStream requestId:${o};index:${m.index};cacheChunkLength:${a.chunks.length};chunkTime:${m.chunkTime}.`)}}))}catch(o){this.logger.warn(`V2AI::queryAiStream requestId:${t.clientId};error:`,o),this.model.setAiStream(t.clientId,{queryStatus:2})}}))}}var ds={"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"},ls="V2NIMSignallingService",ps={accountId:1,uid:{id:2,retType:"number"},joinTime:{id:3,retType:"number"},expireTime:{id:4,retType:"number"},deviceId:5},ms={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(ps))))}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"}},us={v2SignallingCall:{sid:18,cid:16,service:ls,params:[{type:"Property",name:"tag",reflectMapper:ms}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(ms)}]},v2SignallingCallSetup:{sid:18,cid:17,service:ls,params:[{type:"Property",name:"tag",reflectMapper:ms}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(ms)}]},v2SignallingCreateRoom:{sid:18,cid:1,service:ls,params:[{type:"Property",name:"tag",reflectMapper:ms}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(ms)}]},v2SignallingDelayRoom:{sid:18,cid:2,service:ls,params:[{type:"Property",name:"tag",reflectMapper:ms}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(ms)}]},v2SignallingCloseRoom:{sid:18,cid:3,service:ls,params:[{type:"Property",name:"tag",reflectMapper:ms}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(ms)}]},v2SignallingJoinRoom:{sid:18,cid:4,service:ls,params:[{type:"Property",name:"tag",reflectMapper:ms}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(ms)}]},v2SignallingLeaveRoom:{sid:18,cid:5,service:ls,params:[{type:"Property",name:"tag",reflectMapper:ms}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(ms)}]},v2SignallingInvite:{sid:18,cid:6,service:ls,params:[{type:"Property",name:"tag",reflectMapper:ms}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(ms)}]},v2SignallingCancelInvite:{sid:18,cid:7,service:ls,params:[{type:"Property",name:"tag",reflectMapper:ms}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(ms)}]},v2SignallingRejectInvite:{sid:18,cid:8,service:ls,params:[{type:"Property",name:"tag",reflectMapper:ms}]},v2SignallingAcceptInvite:{sid:18,cid:9,service:ls,params:[{type:"Property",name:"tag",reflectMapper:ms}]},v2SignallingSendControl:{sid:18,cid:10,service:ls,params:[{type:"Property",name:"tag",reflectMapper:ms}]},v2SignallingOnlineEvent:{sid:15,cid:11,service:ls,response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(ms)}]},v2SignallingMultiClientEvent:{sid:15,cid:12,service:ls,response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(ms)}]},v2SignallingOfflineEvent:{sid:15,cid:13,service:ls,response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(ms)}]},v2SignallingSyncChannels:{sid:15,cid:14,service:ls,response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(ms)}]},v2SignallingGetRoomInfo:{sid:18,cid:15,service:ls,params:[{type:"Property",name:"tag",reflectMapper:ms}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(ms)}]},v2SignallingBatchMarkRead:{sid:4,cid:5,hasPacketResponse:!1,service:ls,params:[{type:"Byte",name:"sid"},{type:"Byte",name:"cid"},{type:"LongArray",name:"ids"}]}},hs={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}}}},gs={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}}}},vs={channelType:{type:"enum",values:[1,3,2]},channelName:{type:"string",required:!1,allowEmpty:!0},channelExtension:{type:"string",required:!1,allowEmpty:!0}},fs={channelId:{type:"string",required:!0,allowEmpty:!1},offlineEnabled:{type:"boolean",required:!1},serverExtension:{type:"string",required:!1,allowEmpty:!0}},Is={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}}}},ys={channelId:{type:"string",required:!0,allowEmpty:!1},offlineEnabled:{type:"boolean",required:!1},serverExtension:{type:"string",required:!1,allowEmpty:!0}},Ms={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}}}},_s={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}}}},Es={channelId:{type:"string",allowEmpty:!1},receiverAccountId:{type:"string",required:!1},serverExtension:{type:"string",required:!1,allowEmpty:!0}},Ss={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}},Ts=Ss;function formatSignalingEvent(t){var o,a=t.attach,m={eventType:a.type,channelInfo:t.channelInfo,operatorAccountId:t.fromAccid,time:t.time,serverExtension:t.serverExtension,requestId:t.requestId,pushConfig:t.pushConfig,unreadEnabled:null===(o=t.signallingConfig)||void 0===o?void 0:o.unreadEnabled},{fromAccid:u,toAccid:h}=t;switch(m.eventType){case 1:break;case 2:m.member={accountId:a.member[1],uid:Number(a.member[2]),joinTime:Number(a.member[3]),expireTime:Number(a.member[4]),deviceId:a.member[5]};break;case 3:case 4:m.operatorAccountId=u,m.inviteeAccountId=h,m.inviterAccountId=u;break;case 5:case 6:m.operatorAccountId=u,m.inviterAccountId=h,m.inviteeAccountId=u}return JSON.parse(JSON.stringify(m))}function cloneDeep(t,o){if((o=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 o.set(t,!0),t.map((t=>cloneDeep(t,o)));if("object"==typeof t&&null!==t){o.set(t,!0);var a={};return Object.keys(t).forEach((m=>{a[m]=cloneDeep(t[m],o)})),a}return t}class V2NIMSignallingServiceImpl extends V2Service{constructor(t,o={}){super("V2NIMSignallingService",t),this.config={compatibleWithV1:!0},this.channels={},this.timer=0,this.pollingInterval=12e4,"v2"===this.core.options.apiVersion&&(registerParser({cmdMap:ds,cmdConfig:us}),this.setOptions(o))}reset(){this.timer=0,this.channels={}}setOptions(t){var o;(null===(o=this.core.signaling)||void 0===o?void 0:o.name)?this.config.compatibleWithV1=!0:this.config.compatibleWithV1=!1,this.config=Object.assign(this.config,t)}emit(t,...o){var a=`${this.name}::emit ${t.toString()}`;return this.logger.log(`${a}`,...o),super.emit(t,...o)}call(t){var o;return __awaiter(this,void 0,void 0,(function*(){if(this.checkV2(),validate(hs,t,"",!0),t.calleeAccountId===this.core.account)throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"You cannot call yourself"}});var a=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===(o=t.signallingConfig)||void 0===o?void 0:o.offlineEnabled)||t.signallingConfig.offlineEnabled,pushConfig:Object.assign(Object.assign({},t.pushConfig||{}),{pushEnabled:a})})})).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 o;return __awaiter(this,void 0,void 0,(function*(){if(this.checkV2(),validate(gs,t,"",!0),t.callerAccountId===this.core.account)throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"callSetup: cannot be yourself"}});var a=(yield this.core.sendCmd("v2SignallingCallSetup",{tag:Object.assign(Object.assign({},t),{toAccid:t.callerAccountId,offlineEnabled:void 0===(null===(o=t.signallingConfig)||void 0===o?void 0:o.offlineEnabled)||t.signallingConfig.offlineEnabled})})).content.data;return this.channels[a.channelInfo.channelId]=cloneDeep(a.channelInfo),this.timer||(this.timer=this.core.timerManager.addTimer(this.aotoDelay.bind(this),this.pollingInterval,-1)),{callStatus:a.callStatus,rtcInfo:a.rtcInfo,roomInfo:{channelInfo:a.channelInfo,members:a.members}}}))}createRoom(t,o,a){return __awaiter(this,void 0,void 0,(function*(){return this.checkV2(),validate(vs,{channelType:t,channelName:o,channelExtension:a},"",!0),(yield this.core.sendCmd("v2SignallingCreateRoom",{tag:{channelType:t,channelName:o,channelExtension:a}})).content.data.channelInfo}))}delayRoom(t){return __awaiter(this,void 0,void 0,(function*(){this.checkV2();var o=yield this.core.sendCmd("v2SignallingDelayRoom",{tag:{channelId:t}});return{channelInfo:o.content.data.channelInfo,members:o.content.data.members}}))}closeRoom(t,o,a){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(fs,{channelId:t,offlineEnabled:o,serverExtension:a},"",!0),yield this.core.sendCmd("v2SignallingCloseRoom",{tag:{channelId:t,offlineEnabled:void 0!==o&&o,serverExtension:a}})}))}joinRoom(t){var o;return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(Is,t,"",!0);var a=(yield this.core.sendCmd("v2SignallingJoinRoom",{tag:Object.assign(Object.assign({},t),{offlineEnabled:void 0===(null===(o=t.signallingConfig)||void 0===o?void 0:o.offlineEnabled)||t.signallingConfig.offlineEnabled})})).content.data;this.channels[a.channelInfo.channelId]=cloneDeep(a.channelInfo),this.timer||(this.timer=this.core.timerManager.addTimer(this.aotoDelay.bind(this),this.pollingInterval,-1));var{channelInfo:m,members:u,rtcInfo:h}=a;return{roomInfo:{channelInfo:m,members:u},rtcInfo:h}}))}leaveRoom(t,o,a){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),validate(ys,{channelId:t,offlineEnabled:o,serverExtension:a},"",!0),yield this.core.sendCmd("v2SignallingLeaveRoom",{tag:{channelId:t,offlineEnabled:void 0!==o&&o,serverExtension:a}}),delete this.channels[t]}))}invite(t){var o;return __awaiter(this,void 0,void 0,(function*(){if(this.checkV2(),validate(Ms,t,"",!0),t.inviteeAccountId===this.core.account)throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"invite: cannot be yourself"}});var a=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===(o=t.signallingConfig)||void 0===o?void 0:o.offlineEnabled)||t.signallingConfig.offlineEnabled,pushConfig:Object.assign(Object.assign({},t.pushConfig||{}),{pushEnabled:a})})})).content.data}))}cancelInvite(t){return __awaiter(this,void 0,void 0,(function*(){return this.checkV2(),validate(_s,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(Ss,t,"",!0),t.inviterAccountId===this.core.account)throw new V2NIMErrorImpl({code:Me.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(Ts,t,"",!0),t.inviterAccountId===this.core.account)throw new V2NIMErrorImpl({code:Me.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,o,a){return __awaiter(this,void 0,void 0,(function*(){validate(Es,{channelId:t,receiverAccountId:o,serverExtension:a},"",!0),yield this.core.sendCmd("v2SignallingSendControl",{tag:{channelId:t,toAccid:o,serverExtension:a}})}))}getRoomInfoByChannelName(t){return __awaiter(this,void 0,void 0,(function*(){validate({channelName:{type:"string",allowEmpty:!1}},{channelName:t},"",!0);var o=yield this.core.sendCmd("v2SignallingGetRoomInfo",{tag:{channelName:t}}),{members:a,channelInfo:m}=o.content.data;return{channelInfo:m,members:a||[]}}))}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 o=0;o<t.length;o++){var a=t[o];try{var m=yield this.core.sendCmd("v2SignallingDelayRoom",{tag:{channelId:a}});this.channels[a]=m.content.data.channelInfo}catch(t){this.logger.warn(`signling:autoDelay ${a} failed`,t),delete this.channels[a]}}}))}v2SignallingOnlineEventHandler(t){var o=fillIdServer(t,t.content.data,"msgId","0"),a=o.msgId;!this.config.compatibleWithV1&&a&&parseInt(a)&&this.core.sendCmd("v2SignallingBatchMarkRead",{sid:15,cid:11,ids:[a]}),this.handleLeaveRoom(o),this.emit("onOnlineEvent",formatSignalingEvent(o))}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 o=t.content.datas.map((t=>t.msgId));o.length>0&&this.core.sendCmd("v2SignallingBatchMarkRead",{sid:15,cid:11,ids:o})}var a=t.content.datas.map((t=>(this.handleLeaveRoom(t),formatSignalingEvent(t))));this.emit("onOfflineEvent",a)}}v2SignallingSyncChannelsHandler(t){if(this.timer=0,this.channels={},t.content.datas&&t.content.datas.length>0){var o=t.content.datas;o.forEach((t=>{var o=t.channelInfo.channelId;this.channels[o]=cloneDeep(t.channelInfo)})),this.timer||(this.timer=this.core.timerManager.addTimer(this.aotoDelay.bind(this),this.pollingInterval,-1)),this.emit("onSyncRoomInfoList",o)}}handleLeaveRoom(t){switch(t.attach.type){case 1:case 7:case 9:delete this.channels[t.channelInfo.channelId]}}}var Cs,Ns={"19_1":"v2PublishEvent","14_2":"v2OnUserStatusChange","19_3":"v2SubscribeUserStatus","19_4":"v2UnsubscribeUserStatus","19_5":"v2UnsubscribeAllUserStatus","19_6":"v2QuerySubscribeEvent","19_7":"v2QueryAllSubscribeEvent","14_9":"v2OnMultiUserStatusChange"},As="V2NIMSubscriptionService",Os={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},Rs={eventType:{id:1,retType:"number"},duration:{id:2,retType:"number"},immediateSync:{id:3,retType:"number",converter:boolToInt},accountId:102,subscribeTime:{id:105,retType:"number"}},bs={v2PublishEvent:{sid:19,cid:1,service:As,params:[{type:"Property",name:"tag",reflectMapper:Os}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Os)}]},v2OnUserStatusChange:{sid:14,cid:2,service:As,response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Os)}]},v2SubscribeUserStatus:{sid:19,cid:3,service:As,params:[{type:"Property",name:"tag",reflectMapper:Rs},{type:"StrArray",name:"accountIds"}],response:[{type:"StrArray",name:"failedList"}]},v2UnsubscribeUserStatus:{sid:19,cid:4,service:As,params:[{type:"Property",name:"tag",reflectMapper:Rs},{type:"StrArray",name:"accountIds"}],response:[{type:"StrArray",name:"failedList"}]},v2UnsubscribeAllUserStatus:{sid:19,cid:5,service:As,params:[{type:"Property",name:"tag",reflectMapper:Rs}]},v2QuerySubscribeEvent:{sid:19,cid:6,service:As,params:[{type:"Property",name:"tag",reflectMapper:Rs},{type:"StrArray",name:"accountIds"}],response:[{type:"PropertyArray",name:"data",reflectMapper:invertSerializeItem(Rs)}]},v2QueryAllSubscribeEvent:{sid:19,cid:7,service:As,params:[{type:"Property",name:"tag",reflectMapper:Rs}],response:[{type:"PropertyArray",name:"data",reflectMapper:invertSerializeItem(Rs)}]},v2OnMultiUserStatusChange:{sid:14,cid:9,service:As,response:[{type:"PropertyArray",name:"data",reflectMapper:invertSerializeItem(Os)}]}},Vs={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}},ks={accountIds:{type:"array",required:!1,itemType:"string",max:100}},Ps={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&&registerParser({cmdMap:Ns,cmdConfig:bs})}emit(t,...o){var a=`${this.name}::emit ${t.toString()}`;return this.logger.log(`${a}`,...o),super.emit(t,...o)}subscribeUserStatus(t){return __awaiter(this,void 0,void 0,(function*(){return this.checkLogin(),this.checkV2(),validate(Vs,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(ks,t,"",!0);var o=[];t.accountIds.length>0?o=(yield this.core.sendCmd("v2UnsubscribeUserStatus",{tag:{eventType:1},accountIds:t.accountIds})).content.failedList:(yield this.core.sendCmd("v2UnsubscribeAllUserStatus",{tag:{eventType:1}}),o=[]);return o}))}publishCustomUserStatus(t){return __awaiter(this,void 0,void 0,(function*(){return this.checkLogin(),this.checkV2(),validate(Ps,t,"",!0),(yield this.core.sendCmd("v2PublishEvent",{tag:Object.assign(Object.assign({},t),{eventType:1,uniqueId:Ve(),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 o=[];if(t.length>0)for(var a=0;a<t.length;a+=100){var m=yield this.core.sendCmd("v2QuerySubscribeEvent",{tag:{eventType:1},accountIds:t.slice(a,a+100)});o=o.concat(m.content.data.map((t=>({accountId:t.accountId,subscribeTime:t.subscribeTime,duration:t.duration}))))}else{var u=yield this.core.sendCmd("v2QueryAllSubscribeEvent",{tag:{eventType:1}});o=o.concat(u.content.data.map((t=>({accountId:t.accountId,subscribeTime:t.subscribeTime,duration:t.duration}))))}return o}))}v2OnUserStatusChangeHandler(t){var o=t.content.data,{eventType:a,extensionReceived:m}=o,u=__rest(o,["eventType","extensionReceived"]);1===a?this.emit("onUserStatusChanged",[Object.assign(Object.assign({},u),{extension:m})]):this.logger.log("v2OnUserStatusChangeHandler eventType = ",a,"msgEvent = ",o)}v2OnMultiUserStatusChangeHandler(t){var o=t.content.data.filter((t=>1===t.eventType)).map((t=>{var{eventType:o,extensionReceived:a}=t,m=__rest(t,["eventType","extensionReceived"]);return Object.assign(Object.assign({},m),{extension:a})}));o.length>0&&this.emit("onUserStatusChanged",o)}}!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"}(Cs||(Cs={}));var Ls={"22_1":"v2ProxyRequest","22_2":"v2ProxyOnRequest"},ws={zone:1,path:2,method:3,header:4,body:5},Ds={v2ProxyRequest:{sid:22,cid:1,service:"V2NIMPassthroughService",params:[{type:"Property",name:"tag",reflectMapper:ws}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(ws)}]},v2ProxyOnRequest:{sid:22,cid:2,service:"V2NIMPassthroughService",response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem({fromAccountId:1,body:2,time:{id:3,retType:"number"}})}]}},Us={path:{type:"string",allowEmpty:!1},zone:{type:"string",required:!1},method:{type:"enum",values:[Cs.V2NIM_PROXY_REQUEST_METHOD_DELETE,Cs.V2NIM_PROXY_REQUEST_METHOD_GET,Cs.V2NIM_PROXY_REQUEST_METHOD_POST,Cs.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:Ls,cmdConfig:Ds})}emit(t,...o){var a=`${this.name}::emit ${t.toString()}`;return this.logger.log(`${a}`,...o),super.emit(t,...o)}httpProxy(t){return __awaiter(this,void 0,void 0,(function*(){if(validate(Us,t,"",!0),t.method===Cs.V2NIM_PROXY_REQUEST_METHOD_GET&&t.body||t.method===Cs.V2NIM_PROXY_REQUEST_METHOD_POST&&!t.body||t.method===Cs.V2NIM_PROXY_REQUEST_METHOD_PUT&&!t.body)throw new V2NIMErrorImpl({code:Me.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:o}=t.content;this.emit("onProxyNotify",o)}}var xs=NIM$1;xs.registerService(class V2NIMLoginServiceImpl extends V2Service{constructor(t,o={}){var a;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:We}),"v2"===t.options.apiVersion&&(registerParser({cmdMap:Ye,cmdConfig:Je}),this.core.auth=this),this.previousLoginManager=new PromiseManager,this.doLoginStepsManager=new PromiseManager,this.loginTimerManager=new TimerManager,this.loginOption=Object.assign({},ht),this.config={lbsUrls:ut,linkUrl:"weblink.netease.im:443",linkSSL:!0},this.setOptions(o),t.V2NIMLoginService=this,!1!==this.core.options.binaryWebsocket&&"function"==typeof Uint8Array?(this.binaryWebsocket=!0,a=new V2BinaryClientSocket(this.core)):(this.binaryWebsocket=!1,a=new V2ClientSocket(this.core)),this.clientSocket=a,"v2"===this.core.options.apiVersion&&(this.core.clientSocket=a),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 o,a,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===(a=null===(o=this.core.clientSocket)||void 0===o?void 0:o.setLinkSSL)||void 0===a||a.call(o,null===(m=this.config.linkSSL)||void 0===m||m);var u="",h="";this.config.isFixedDeviceId?(u=Ae.localStorage.getItem("__NIM_DEVC_ID__")||Ve(),h=Ae.localStorage.getItem("__NIM_CLIENT_SESSION_ID__")||Ve(),Ae.localStorage.setItem("__NIM_DEVC_ID__",u),Ae.localStorage.setItem("__NIM_CLIENT_SESSION_ID__",h)):(u=Ve(),h=Ve()),this.deviceId=u,this.clientSession=h,this.core.reporter.setConfig({common:{dev_id:u}})}reset(){this.account="",this.token="",this.processId="",this.lbs.reset(),this.reconnect.destroy(),this.authenticator.reset(),this.authenticator.clearLastLoginClient(),this.dataSync.reset()}login(t,o,a={}){return __awaiter(this,void 0,void 0,(function*(){this._checkApiVersion();var m=Ae.getSystemInfo()||{},u=m.os?m.os.toLowerCase():"";if("React Native"===Ae.platform&&"android"===u&&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(mt,a,"",!0),0===(a=assignOptions(ht,a)).authType&&!o)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}`,a);else{if(1===this.getLoginStatus())return this.smoothForLogined(t,o,a);if(2===this.getLoginStatus())return this.smoothForLogining(t,o,a)}this.account=t,this.previousLoginAccount=t,this.token=o,this.processId=Ve(),this.loginOption=assignOptions(ht,a),this.kickedDetail=null,this.loginTimerManager.destroy(),this.loginTimerManager.addTimer((()=>{var t=new V2NIMErrorImpl({code:Me.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,o){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:o},"",!0),o=void 0===o?pendingIsMiniappEnv():o,(yield this.clientSocket.sendCmd("v2GetChatroomLinkAddress",{roomId:t,miniProgram:o})).content.linkAddress}))}multiTryDoLogin(t){return __awaiter(this,void 0,void 0,(function*(){for(var o=new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_INTERNAL,detail:{reason:"loginFailed"}}),a=0;a<=this.loginOption.retryCount;a++){var m=`V2NIMLoginService::times of login try: ${a}`;a>0?this.logger.warn(m):this.logger.log(m);try{this.originLoginPromise=t||this.doLogin(!1),t=void 0;var u=yield this.previousLoginManager.add(this.originLoginPromise);return this.core.reporter.reportTraceEnd("login",!0),this.doLoginStepsManager.clear(),this.previousLoginManager.clear(),this.originLoginPromise=void 0,u}catch(t){if(o=t||o,this.logger.error(`V2NIMLoginService::login failed, times of login try: ${a}, err.code: ${null==o?void 0:o.code}, err.message: "${null==o?void 0:o.message}"`),o.code!==Me.V2NIM_ERROR_CODE_CANCELLED&&this.core.reporter.reportTraceEnd("login",!1),this.reconnect.clearReconnectTimer(),this.checkLoginTerminalCode(o&&o.code))throw this.lifeCycle.processEvent("exited",o),o;o&&399===o.code&&this.lbs.reset()}}throw this.lifeCycle.processEvent("exited",o),o}))}doLogin(t){var o,a;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:Ae.net.getNetworkStatus()});var u=yield this.doLoginStepsManager.add(this.lbs.getLbsInfos());yield this.doLoginStepsManager.add(this.clientSocket.connect(u,t));var h=yield this.doLoginStepsManager.add(this.authenticator.verifyAuthentication(m));if(this.processId=Ve(),this.clientSocket.resetSocketConfig(),this.reconnect.reset(),this.dataSync.reset(),this.lifeCycle.processEvent("loginSucc",void 0,Object.assign(Object.assign({},h),{isReconnect:t})),this.clientSocket.ping(),this.core.abtest.abtRequest(),"function"==typeof(null===(o=this.core.V2NIMClientAntispamUtil)||void 0===o?void 0:o.downloadLocalAntiSpamVocabs)&&this.core.V2NIMClientAntispamUtil.downloadLocalAntiSpamVocabs(),"function"==typeof(null===(a=this.core.cloudStorage)||void 0===a?void 0:a.init))try{yield this.core.cloudStorage.init(h.timestamp)}catch(t){this.logger.warn("doLogin::cloudStorage init error",t)}return h}))}smoothForLogined(t,o,a){return __awaiter(this,void 0,void 0,(function*(){var m=this.checkIsSameLogin(t,o,a);return this.logger.warn(`V2NIMLoginService::smoothForLogined:Logined, isSameLogin ${m}`),m?void 0:(yield this.logout(),this.login(t,o,a))}))}smoothForLogining(t,o,a){return __awaiter(this,void 0,void 0,(function*(){var m=this.checkIsSameLogin(t,o,a);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=o,this.loginOption=assignOptions(this.loginOption,a),!m)return this.doLoginStepsManager.clear(),this.clientSocket.doDisconnect(et.ACTIVE,"Aborted"),this.reset(),this.lifeCycle.processEvent("logout"),yield Promise.resolve(),this.login(t,o,a);if(!this.originLoginPromise)throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_INTERNAL,detail:{reason:"NoPreviousLoginExists"}});this.reconnect.reset(),yield Promise.resolve(),yield this.multiTryDoLogin(this.originLoginPromise)}))}checkIsSameLogin(t,o,a){return this.account===t&&this.loginOption.authType===a.authType&&(0!==a.authType||this.token===o)}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(),o=this.getLoginStatus();switch(o){case 1:try{yield this.clientSocket.sendCmd("v2Logout",void 0,{timeout:1e3}),this.clientSocket.doDisconnect(et.ACTIVE,"UserActiveDisconnect"),this.core._clearModuleData(),this.lifeCycle.processEvent("logout")}catch(t){this.logger.error("Instance::disconnect sendCmd:logout error",t),this.clientSocket.doDisconnect(et.ACTIVE,"UserActiveDisconnect"),this.core._clearModuleData(),this.lifeCycle.processEvent("logout")}break;case 2:case 3:this.clientSocket.doDisconnect(et.ACTIVE,"UserActiveDisconnect"),this.core._clearModuleData(),this.lifeCycle.processEvent("logout");break;case 0:throw this.core._clearModuleData(),new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_ILLEGAL_STATE,detail:{reason:`Illegal logout. loginStatus ${o}. connectStatus ${t}`}});default:throw this.core._clearModuleData(),new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_ILLEGAL_STATE,detail:{reason:`Illegal logout. illegal status: loginStatus ${o}. connectStatus ${t}`}})}}))}getConnectStatus(){return this.lifeCycle.getConnectStatus()}getLoginStatus(){return this.lifeCycle.getLoginStatus()}getLoginUser(){return this.account}getLoginClients(){return function uniqBy(t,o){t=t||[],o=o||"";for(var a=[],m=[],u=0;u<t.length;u++){var h=t[u][o];-1===m.indexOf(h)&&(m.push(h),a.push(t[u]))}return a}(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:Me.V2NIM_ERROR_CODE_REQUEST_FAILED})}))}getKickedOfflineDetail(){return this.kickedDetail}checkLoginTerminalCode(t){return this.authenticator.checkLoginTerminalCode(t)}checkIllegalState(){if(!this.getLoginUser())throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_ILLEGAL_STATE})}_checkApiVersion(){if("v2"!==this.core.options.apiVersion)throw new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_MISUSE,detail:{reason:'apiVersion is not "v2"'}})}v2LoginHandler(t){if(t.error)throw this.clientSocket.doDisconnect(et.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 o=parseInt(t.content.state);o=1===o?2:3,this.authenticator.changeLoginClient(o,[t.content.data])}v2BeKickedHandler(t){if(t.error)this.core.logger.error("v2BeKickedHandler error, ",t.error);else{var o=function formatBeKickedTag(t){return format({reason:{type:"number"},clientType:{type:"number"},customClientType:{type:"number"}},t)}(t.content);this.core.logger.warn("v2Bekicked::",o),this.kickedDetail=o,this.clientSocket.doDisconnect(et.KICKED,o),this.core._clearModuleData(),this.lifeCycle.processEvent("kicked",new V2NIMErrorImpl({code:Me.V2NIM_ERROR_CODE_DISCONNECT,detail:{reason:"disconnect due to kicked"}}),o),this.emit("onKickedOffline",o)}}emit(t,...o){var a=`${this.name}::emit ${t.toString()}`;if("onLoginFailed"===t||"onDisconnected"===t||"onConnectFailed"===t){var m=o[0];this.logger.log(`${a}`,m.toString())}else if("onDataSync"===t){var u=o[2];this.logger.log(`${a}`,o[0],o[1],u&&u.toString())}else this.logger.log(`${a}`,...o);return super.emit(t,...o)}},"V2NIMLoginService"),xs.registerService(class V2NIMSyncServiceImpl extends V2Service{constructor(t){super("V2NIMSyncService",t),this.teamKey=["teams","superTeams","myTeamMembers","mySuperTeamMembers"],this.config={},this.timetags={},"v2"===this.core.options.apiVersion&&(this.initEventListeners(),registerParser({cmdMap:gt,cmdConfig:vt}),this.setListener())}reset(){this.timetags={}}setListener(){this.core.eventBus.on("V2NIMSync/updateTimetag",(t=>{Object.keys(t).forEach((o=>{t[o]>(this.timetags[o]||0)&&(this.timetags[o]=t[o])}))}))}setOptions(t){var o=this.core,a=!(!o.V2NIMConversationService.name&&!o.V2NIMLocalConversationService.name);return this.config=Object.assign({myInfo:!!o.V2NIMUserService.name,offlineMsgs:!!o.V2NIMMessageService.name,roamingMsgs:!!o.V2NIMMessageService.name,relations:!!o.V2NIMUserService.name,friends:!!o.V2NIMFriendService.name,friendUsers:!!o.V2NIMUserService.name,msgReceipts:!!o.V2NIMMessageService.name,broadcastMsgs:!!o.V2NIMNotificationService.name,recallMsg:!!o.V2NIMMessageService.name,sessionAck:a,superTeamSessionAck:a,stickTopSessions:a,superTeamRoamingMsgs:!!o.V2NIMTeamService.name,deleteSuperTeamMsg:!!o.V2NIMTeamService.name,deleteSelfMsgs:!!o.V2NIMMessageService.name,sessionHistoryMsgsDelete:!!o.V2NIMMessageService.name,avSignal:!!o.V2NIMSignallingService.name,teams:!!o.V2NIMTeamService.name,superTeams:!!o.V2NIMTeamService.name,myTeamMembers:!!o.V2NIMTeamService.name,mySuperTeamMembers:!!o.V2NIMTeamService.name,donnop:!!o.V2NIMSettingService.name,p2pTeamModifyMessage:!!o.V2NIMMessageService.name,superTeamModifyMessage:!!o.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])),o=this.genSyncParams(t);this.logger.log("V2Sync:basic",o);var a=(yield this.core.clientSocket.sendCmd("v2NIMSync",{tag:o})).content.timetag;this.setTimetags(a,t.filter((t=>"broadcastMsgs"!==t))),yield this.delaySyncDone(),yield this.handleImmediate(),this.core.logger.log("sync::basic sync complete in",a)}))}doTeamSync(){return __awaiter(this,void 0,void 0,(function*(){var t=this.teamKey.filter((t=>this.config[t]));if(0!==t.length){var o=this.genSyncParams(t);this.core.eventBus.emit("V2NIMTeamService/onSyncStarted"),this.logger.log("V2Sync:team",o);var a=null;try{a=yield this.core.clientSocket.sendCmd("v2NIMSync",{tag:o})}catch(t){throw this.core.eventBus.emit("V2NIMTeamService/onSyncFailed",t),t}this.core.eventBus.emit("V2NIMTeamService/onSyncFinished");var m=a.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"})}initEventListeners(){this.core.eventBus.on("V2NIMLoginService/loginLifeCycleLoginSucc",(()=>{this.doSync()}))}genSyncParams(t){return t.reduce(((t,o)=>{var a=o;return t[a]=this.timetags[a]||0,t}),{})}setTimetags(t,o){o.forEach((o=>{this.timetags[o]=t}))}handleImmediate(){return this.core.session&&this.core.session.onSyncDone&&this.core.session.onSyncDone(),Promise.resolve()}delaySyncDone(){var{hostEnvEnum:t}=Ae.getSystemInfo();return 102===t?(this.core.logger.log("sync: emit ALIAPP sycnHandler, handle later"),new Promise((t=>{setTimeout((()=>{t()}),100)}))):Promise.resolve()}},"V2NIMSyncService");export{xs as NIM,V2NIMAIServiceImpl as V2NIMAIService,Ee as V2NIMConst,V2NIMConversationGroupServiceImpl as V2NIMConversationGroupService,V2NIMConversationServiceImpl as V2NIMConversationService,V2NIMUFriendServiceImpl 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,getAdapter$2 as aliAdapters,getAdapter$1 as baiduAdapters,getAdapter$4 as browserAdapters,setAdapters,getAdapter as ttAdapters,getAdapter$5 as uniAppAdapters,getAdapter$3 as wxAdapters};