UNPKG

nim-web-sdk-ng

Version:

Yunxin IM SDK next generation

16 lines 321 kB
/**
 * 
 *   Version: 10.9.71
 * 
 *   Git Hash: f2dd8dce716f63985d0823f710605b924090d68b
 * 
 *   Created At: 1/5/2026, 9:48:45 AM
 * 
 *   Target: CHATROOM_MINIAPP_SDK.js
 *   
 */

!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).Chatroom={})}(this,(function(e){"use strict";function __rest(e,t){var r={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(r[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(i=Object.getOwnPropertySymbols(e);o<i.length;o++)t.indexOf(i[o])<0&&Object.prototype.propertyIsEnumerable.call(e,i[o])&&(r[i[o]]=e[i[o]])}return r}function __awaiter(e,t,r,i){return new(r||(r=Promise))((function(o,n){function fulfilled(e){try{step(i.next(e))}catch(e){n(e)}}function rejected(e){try{step(i.throw(e))}catch(e){n(e)}}function step(e){e.done?o(e.value):function adopt(e){return e instanceof r?e:new r((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))}"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;function createCommonjsModule(e){var t={exports:{}};return e(t,t.exports),t.exports}var t=createCommonjsModule((function(e,t){e.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 e};var e={},t=Object.prototype,r=t.hasOwnProperty,i="function"==typeof Symbol?Symbol:{},o=i.iterator||"@@iterator",n=i.asyncIterator||"@@asyncIterator",s=i.toStringTag||"@@toStringTag";function define(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{define({},"")}catch(e){define=function(e,t,r){return e[t]=r}}function wrap(e,t,r,i){var o=t&&t.prototype instanceof Generator?t:Generator,n=Object.create(o.prototype),s=new Context(i||[]);return n._invoke=function(e,t,r){var i="suspendedStart";return function(o,n){if("executing"===i)throw new Error("Generator is already running");if("completed"===i){if("throw"===o)throw n;return doneResult()}for(r.method=o,r.arg=n;;){var s=r.delegate;if(s){var c=maybeInvokeDelegate(s,r);if(c){if(c===a)continue;return c}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if("suspendedStart"===i)throw i="completed",r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);i="executing";var _=tryCatch(e,t,r);if("normal"===_.type){if(i=r.done?"completed":"suspendedYield",_.arg===a)continue;return{value:_.arg,done:r.done}}"throw"===_.type&&(i="completed",r.method="throw",r.arg=_.arg)}}}(e,r,s),n}function tryCatch(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}e.wrap=wrap;var a={};function Generator(){}function GeneratorFunction(){}function GeneratorFunctionPrototype(){}var c={};define(c,o,(function(){return this}));var _=Object.getPrototypeOf,l=_&&_(_(values([])));l&&l!==t&&r.call(l,o)&&(c=l);var d=GeneratorFunctionPrototype.prototype=Generator.prototype=Object.create(c);function defineIteratorMethods(e){["next","throw","return"].forEach((function(t){define(e,t,(function(e){return this._invoke(t,e)}))}))}function AsyncIterator(e,t){function invoke(i,o,n,s){var a=tryCatch(e[i],e,o);if("throw"!==a.type){var c=a.arg,_=c.value;return _&&"object"==typeof _&&r.call(_,"__await")?t.resolve(_.__await).then((function(e){invoke("next",e,n,s)}),(function(e){invoke("throw",e,n,s)})):t.resolve(_).then((function(e){c.value=e,n(c)}),(function(e){return invoke("throw",e,n,s)}))}s(a.arg)}var i;this._invoke=function(e,r){function callInvokeWithMethodAndArg(){return new t((function(t,i){invoke(e,r,t,i)}))}return i=i?i.then(callInvokeWithMethodAndArg,callInvokeWithMethodAndArg):callInvokeWithMethodAndArg()}}function maybeInvokeDelegate(e,t){var r=e.iterator[t.method];if(void 0===r){if(t.delegate=null,"throw"===t.method){if(e.iterator.return&&(t.method="return",t.arg=void 0,maybeInvokeDelegate(e,t),"throw"===t.method))return a;t.method="throw",t.arg=new TypeError("The iterator does not provide a 'throw' method")}return a}var i=tryCatch(r,e.iterator,t.arg);if("throw"===i.type)return t.method="throw",t.arg=i.arg,t.delegate=null,a;var o=i.arg;return o?o.done?(t[e.resultName]=o.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=void 0),t.delegate=null,a):o:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,a)}function pushTryEntry(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function resetTryEntry(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function Context(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(pushTryEntry,this),this.reset(!0)}function values(e){if(e){var t=e[o];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var i=-1,n=function next(){for(;++i<e.length;)if(r.call(e,i))return next.value=e[i],next.done=!1,next;return next.value=void 0,next.done=!0,next};return n.next=n}}return{next:doneResult}}function doneResult(){return{value:void 0,done:!0}}return GeneratorFunction.prototype=GeneratorFunctionPrototype,define(d,"constructor",GeneratorFunctionPrototype),define(GeneratorFunctionPrototype,"constructor",GeneratorFunction),GeneratorFunction.displayName=define(GeneratorFunctionPrototype,s,"GeneratorFunction"),e.isGeneratorFunction=function(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===GeneratorFunction||"GeneratorFunction"===(t.displayName||t.name))},e.mark=function(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,GeneratorFunctionPrototype):(e.__proto__=GeneratorFunctionPrototype,define(e,s,"GeneratorFunction")),e.prototype=Object.create(d),e},e.awrap=function(e){return{__await:e}},defineIteratorMethods(AsyncIterator.prototype),define(AsyncIterator.prototype,n,(function(){return this})),e.AsyncIterator=AsyncIterator,e.async=function(t,r,i,o,n){void 0===n&&(n=Promise);var s=new AsyncIterator(wrap(t,r,i,o),n);return e.isGeneratorFunction(r)?s:s.next().then((function(e){return e.done?e.value:s.next()}))},defineIteratorMethods(d),define(d,s,"Generator"),define(d,o,(function(){return this})),define(d,"toString",(function(){return"[object Generator]"})),e.keys=function(e){var t=[];for(var r in e)t.push(r);return t.reverse(),function next(){for(;t.length;){var r=t.pop();if(r in e)return next.value=r,next.done=!1,next}return next.done=!0,next}},e.values=values,Context.prototype={constructor:Context,reset:function(e){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),!e)for(var t in this)"t"===t.charAt(0)&&r.call(this,t)&&!isNaN(+t.slice(1))&&(this[t]=void 0)},stop:function(){this.done=!0;var e=this.tryEntries[0].completion;if("throw"===e.type)throw e.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var t=this;function handle(r,i){return n.type="throw",n.arg=e,t.next=r,i&&(t.method="next",t.arg=void 0),!!i}for(var i=this.tryEntries.length-1;i>=0;--i){var o=this.tryEntries[i],n=o.completion;if("root"===o.tryLoc)return handle("end");if(o.tryLoc<=this.prev){var s=r.call(o,"catchLoc"),a=r.call(o,"finallyLoc");if(s&&a){if(this.prev<o.catchLoc)return handle(o.catchLoc,!0);if(this.prev<o.finallyLoc)return handle(o.finallyLoc)}else if(s){if(this.prev<o.catchLoc)return handle(o.catchLoc,!0)}else{if(!a)throw new Error("try statement without catch or finally");if(this.prev<o.finallyLoc)return handle(o.finallyLoc)}}}},abrupt:function(e,t){for(var i=this.tryEntries.length-1;i>=0;--i){var o=this.tryEntries[i];if(o.tryLoc<=this.prev&&r.call(o,"finallyLoc")&&this.prev<o.finallyLoc){var n=o;break}}n&&("break"===e||"continue"===e)&&n.tryLoc<=t&&t<=n.finallyLoc&&(n=null);var s=n?n.completion:{};return s.type=e,s.arg=t,n?(this.method="next",this.next=n.finallyLoc,a):this.complete(s)},complete:function(e,t){if("throw"===e.type)throw e.arg;return"break"===e.type||"continue"===e.type?this.next=e.arg:"return"===e.type?(this.rval=this.arg=e.arg,this.method="return",this.next="end"):"normal"===e.type&&t&&(this.next=t),a},finish:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),resetTryEntry(r),a}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var i=r.completion;if("throw"===i.type){var o=i.arg;resetTryEntry(r)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,r){return this.delegate={iterator:values(e),resultName:t,nextLoc:r},"next"===this.method&&(this.arg=void 0),a}},e}function _typeof(e){return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_typeof(e)}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}function _createClass(e,t,r){return t&&_defineProperties(e.prototype,t),r&&_defineProperties(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function __awaiter(e,t,r,i){function adopt(e){return e instanceof r?e:new r((function(t){t(e)}))}return new(r||(r=Promise))((function(r,o){function fulfilled(e){try{step(i.next(e))}catch(e){o(e)}}function rejected(e){try{step(i.throw(e))}catch(e){o(e)}}function step(e){e.done?r(e.value):adopt(e.value).then(fulfilled,rejected)}step((i=i.apply(e,t||[])).next())}))}var e={isDataReportEnable:!0,maxSize:100,msgListMaxSize:1e3,cacheMaxSize:1e3,maxDelay:3e5,maxInterval:3e4,minInterval:1e4,timeout:5e3,autoStart:!0,loginFailIgnoreInterval:72e5},t=12,r=8e3,i=function emptyFn(){},o=function(){function Reporter(t){_classCallCheck(this,Reporter),this.isUploadEnable=!0,this.serverAllowUpload=!1,this.initConfigLoaded=!1,this.loading=!1,this.isDestroyed=!1,this.reportConfig=e,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(t),this.reportConfig.isDataReportEnable&&this.reportConfig.autoStart&&this.initUploadConfig()}return _createClass(Reporter,[{key:"setConfig",value:function setConfig(e){var t=Object.assign({},this.reportConfig.common,e.common);this.reportConfig=Object.assign({},this.reportConfig,e),this.reportConfig.common=t,this.reportConfig.common.sdk_type||(this.reportConfig.common.sdk_type="im")}},{key:"reportImmediately",value:function reportImmediately(e,t){var r=this;this.reportConfig.isDataReportEnable&&this.reportConfig.request(e,Object.assign({dataType:"json",method:"POST",timeout:this.reportConfig.timeout},t)).catch((function(e){var t,i;null===(i=null===(t=r.reportConfig)||void 0===t?void 0:t.logger)||void 0===i||i.warn("Reporter immediately upload failed",e)}))}},{key:"report",value:function report(t,r){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(i.priority||(i.priority=this.getEventPriority(t,r)),this.reportConfig.isDataReportEnable&&t){if("login"===t&&!1===r.succeed&&r.process_id){var o=r.extension&&r.extension.find((function(e){return"TCP"===e.operation_type})),n=o&&o.target||"",s=r.process_id+n,a=this.lastFailLogin[s]||0;if(r.start_time-a<e.loginFailIgnoreInterval)return;this.lastFailLogin[s]=r.start_time}var c=Date.now();"HIGH"===i.priority?this.highPriorityMsgList.push({module:t,msg:r,createTime:c}):"NORMAL"===i.priority?this.msgList.push({module:t,msg:r,createTime:c}):"LOW"===i.priority&&this.lowPriorityMsgList.push({module:t,msg:r,createTime:c}),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(e,t){if(this.reportConfig.isDataReportEnable&&e&&!this.traceMsgCache[e]){var r=Object.assign(Object.assign({start_time:Date.now()},t),{extension:[]});this.traceMsgCache[e]=r}}},{key:"reportTraceUpdate",value:function reportTraceUpdate(e){}},{key:"reportTraceUpdateV2",value:function reportTraceUpdateV2(e,t,r){var i,o=this;if(this.reportConfig.isDataReportEnable&&this.traceMsgCache[e]){var n=this.traceMsgCache[e].extension,s=n.length,a=(new Date).getTime();0===s?t.duration=a-this.traceMsgCache[e].start_time:n[s-1].end_time?t.duration=a-n[s-1].end_time:t.duration=a-this.traceMsgCache[e].start_time,n.push(Object.assign({end_time:a},t));var c=n.length-1;(null==r?void 0:r.asyncParams)&&((i=this.traceMsgCache[e]).asyncPromiseArray||(i.asyncPromiseArray=[]),this.traceMsgCache[e].asyncPromiseArray.push(r.asyncParams.then((function(t){o.traceMsgCache[e]&&o.traceMsgCache[e].extension[c]&&Object.assign(o.traceMsgCache[e].extension[c],t)}))))}}},{key:"reportTraceEnd",value:function reportTraceEnd(e){var t,r=this,i=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(this.reportConfig.isDataReportEnable&&this.traceMsgCache[e])if("nos"!==e||!1===i){"boolean"==typeof i?this.traceMsgCache[e].succeed=!!i:this.traceMsgCache[e].state=i,this.traceMsgCache[e].duration=Date.now()-this.traceMsgCache[e].start_time,this.traceMsgCache[e].extension.forEach((function(e){delete e.end_time}));var o=this.traceMsgCache[e];if(this.traceMsgCache[e]=null,o.asyncPromiseArray){(t=this.endedAsyncMsgByModule)[e]||(t[e]=[]),this.endedAsyncMsgByModule[e].push(o);var n=function asyncCallback(){r.endedAsyncMsgByModule[e]&&r.endedAsyncMsgByModule[e].includes(o)&&(delete o.asyncPromiseArray,r.report(e,o,{priority:r.getEventPriority(e,o)}))};Promise.all(o.asyncPromiseArray).then(n).catch(n)}else this.report(e,o,{priority:this.getEventPriority(e,o)})}else this.traceMsgCache[e]=null}},{key:"getEventPriority",value:function getEventPriority(e,t){if("exceptions"===e){if(0===t.action)return"HIGH";if(2===t.action)return"HIGH";if(1===t.action&&0!==t.exception_service)return"HIGH"}else{if("msgReceive"===e)return"LOW";if("nim_api_trace"===e)return"LOW"}return"NORMAL"}},{key:"reportTraceCancel",value:function reportTraceCancel(e){this.reportConfig.isDataReportEnable&&(this.endedAsyncMsgByModule[e]=[],this.traceMsgCache[e]=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 e=this;this.reportConfig.isDataReportEnable&&(Object.keys(this.traceMsgCache).forEach((function(t){e.reportTraceEnd(t,1)})),null!==this.timer&&clearTimeout(this.timer),this.setConfig=i,this.report=i,this.reportTraceStart=i,this.reportTraceUpdate=i,this.reportTraceEnd=i,this.pause=i,this.restore=i,this.destroy=i,this.reqRetryCount=0,this.cacheMsgList=[],this.traceMsgCache={},this.lowPriorityMsgList=[],this.msgList=[],this.highPriorityMsgList=[],this.reportConfig={},this.isDestroyed=!0)}},{key:"initUploadConfig",value:function initUploadConfig(){var e,i;return __awaiter(this,void 0,void 0,_regeneratorRuntime().mark((function _callee(){var o,n,s,a,c,_=this;return _regeneratorRuntime().wrap((function _callee$(l){for(;;)switch(l.prev=l.next){case 0:if(!this.loading){l.next=2;break}return l.abrupt("return");case 2:this.loading=!0,o=this.reportConfig.common||{},n=this.reportConfig.compassDataEndpoint.split(",").map((function(e){return"".concat(e,"/").concat(_.configPath)})),s=_regeneratorRuntime().mark((function _loop(s){return _regeneratorRuntime().wrap((function _loop$(a){for(;;)switch(a.prev=a.next){case 0:if(!_.initConfigLoaded&&!_.isDestroyed){a.next=2;break}return a.abrupt("return","break");case 2:return a.prev=2,a.next=5,_.reportConfig.request(n[s],{method:"GET",dataType:"json",params:{deviceId:o.dev_id,sdkVer:o.sdk_ver,platform:o.platform,hostEnv:o.host_env,appkey:o.app_key},timeout:_.reportConfig.timeout}).then((function(e){var t,r;if(!_.isDestroyed){if(200===e.status&&e.data&&200===e.data.code){_.initConfigLoaded=!0;var i=e.data.data||{};_.reportConfig.maxSize=i.maxSize>1e3?1e3:i.maxSize,_.reportConfig.maxInterval=i.maxInterval>1e4?1e4:i.maxInterval,_.reportConfig.maxInterval=i.maxInterval<10?10:i.maxInterval,_.reportConfig.minInterval=i.minInterval<2?2:i.minInterval,_.reportConfig.maxDelay=i.maxDelay||300,_.reportConfig.maxInterval=1e3*_.reportConfig.maxInterval,_.reportConfig.minInterval=1e3*_.reportConfig.minInterval,_.reportConfig.maxDelay=1e3*_.reportConfig.maxDelay,i.endpoint?_.dataReportEndpoint=i.endpoint:_.dataReportEndpoint=n[s],_.serverAllowUpload=!0,_.loading=!1,_.reportHeartBeat()}else 200===e.status&&(_.initConfigLoaded=!0);null===(r=null===(t=_.reportConfig)||void 0===t?void 0:t.logger)||void 0===r||r.log("Get reporter upload config success")}})).catch((function(e){var i,o;_.isDestroyed||(_.loading=!1,null===(o=null===(i=_.reportConfig)||void 0===i?void 0:i.logger)||void 0===o||o.error("Get reporter upload config failed",e),_.reqRetryCount<t&&(_.reqRetryCount++,setTimeout((function(){_.isDestroyed||_.initUploadConfig()}),r)))}));case 5:a.next=14;break;case 7:if(a.prev=7,a.t0=a.catch(2),!_.isDestroyed){a.next=11;break}return a.abrupt("return",{v:void 0});case 11:_.loading=!1,null===(i=null===(e=_.reportConfig)||void 0===e?void 0:e.logger)||void 0===i||i.error("Exec reporter request failed",a.t0),_.reqRetryCount<t&&(_.reqRetryCount++,setTimeout((function(){_.isDestroyed||_.initUploadConfig()}),r));case 14:case"end":return a.stop()}}),_loop,null,[[2,7]])})),a=0;case 7:if(!(a<n.length)){l.next=17;break}return l.delegateYield(s(a),"t0",9);case 9:if("break"!==(c=l.t0)){l.next=12;break}return l.abrupt("break",17);case 12:if("object"!==_typeof(c)){l.next=14;break}return l.abrupt("return",c.v);case 14:a++,l.next=7;break;case 17:case"end":return l.stop()}}),_callee,this)})))}},{key:"reportHeartBeat",value:function reportHeartBeat(){var e=this;this.isDestroyed||(this.timer=setTimeout((function(){e.reportHeartBeat()}),this.reportConfig.minInterval),this.doReport())}},{key:"doReport",value:function doReport(){if(!this.isDestroyed){var e=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>=e&&this.upload()}}},{key:"getUploadMsg",value:function getUploadMsg(){var e=this,t={},r=Date.now();this.highPriorityMsgList=this.highPriorityMsgList.filter((function(t){return r-t.createTime<e.reportConfig.maxDelay})),this.msgList=this.msgList.filter((function(t){return r-t.createTime<e.reportConfig.maxDelay})),this.lowPriorityMsgList=this.lowPriorityMsgList.filter((function(t){return r-t.createTime<e.reportConfig.maxDelay})),this.cacheMsgList=this.cacheMsgList.filter((function(t){return r-t.createTime<e.reportConfig.maxDelay}));var i=this.highPriorityMsgList.slice(0,this.reportConfig.maxSize);if(this.highPriorityMsgList=this.highPriorityMsgList.slice(i.length),i.length<this.reportConfig.maxSize){var o=this.reportConfig.maxSize-i.length;i=i.concat(this.msgList.slice(0,o)),this.msgList=this.msgList.slice(o)}if(i.length<this.reportConfig.maxSize){var n=this.reportConfig.maxSize-i.length;i=i.concat(this.lowPriorityMsgList.slice(0,n)),this.lowPriorityMsgList=this.lowPriorityMsgList.slice(n)}if(i.length<this.reportConfig.maxSize){var s=this.reportConfig.maxSize-i.length;i=i.concat(this.cacheMsgList.slice(0,s)),this.cacheMsgList=this.cacheMsgList.slice(s)}return i.forEach((function(e){t[e.module]?t[e.module].push(e.msg):t[e.module]=[e.msg]})),{uploadMsgArr:i,uploadMsg:t}}},{key:"upload",value:function upload(){var e,t,r=this;if(this.isUploadEnable&&this.serverAllowUpload&&!(this.lastReportTime&&Date.now()-this.lastReportTime<this.reportConfig.minInterval)){var i=this.getUploadMsg(),o=i.uploadMsgArr,n=i.uploadMsg;if(o.length){this.lastReportTime=Date.now();try{var s="".concat(this.dataReportEndpoint,"/").concat(this.dataReportPath);this.reportConfig.request(s,{dataType:"json",method:"POST",data:{common:this.reportConfig.common,event:n},headers:{sdktype:"im"},timeout:this.reportConfig.timeout}).catch((function(e){var t,i;r.cacheMsgList=r.cacheMsgList.concat(o).slice(0,r.reportConfig.cacheMaxSize),null===(i=null===(t=r.reportConfig)||void 0===t?void 0:t.logger)||void 0===i||i.warn("Reporter upload failed",e)}))}catch(r){null===(t=null===(e=this.reportConfig)||void 0===e?void 0:e.logger)||void 0===t||t.warn("Exec reporter request failed",r)}clearTimeout(this.timer),this.reportHeartBeat()}}}}]),Reporter}();return o}()}));function isPlainObject(e){return null!=e&&"object"==typeof e&&Object.getPrototypeOf(e)==Object.prototype}function merge(e,t){var r=isPlainObject(e)||Array.isArray(e),i=isPlainObject(t)||Array.isArray(t);if(r&&i){for(var o in t){var n=merge(e[o],t[o]);void 0!==n&&(e[o]=n)}return e}return t}var r={getNetworkStatus:()=>Promise.resolve({net_type:0,net_connect:!0}),onNetworkStatusChange(e){},offNetworkStatusChange(){}},i={isActive:()=>!0,getStatus:()=>0,setStatus(e){},destroy(){}};var o,n,s,a,c,_,l,d,E,h,u,m,g,p,I,N,T,O,M,f,S,R,A,C,v,y,D,V,L,b,P,k,w,U,x,G,B,H,Y,j,$,K,q,W,z,J,Q,X,Z,ee,te,re,ie,oe,ne,se,ae,ce={setLogger:function(e){throw new Error("setLogger not implemented.")},platform:"",WebSocket:class AdapterSocket{constructor(e,t){throw this.CONNECTING=0,this.OPEN=1,this.CLOSING=2,this.CLOSED=3,this.binaryType="",new Error("Method not implemented.")}close(e,t){throw new Error("Method not implemented.")}send(e){throw new Error("Method not implemented.")}onclose(e){throw new Error("Method not implemented.")}onerror(e){throw new Error("Method not implemented.")}onmessage(e){throw new Error("Method not implemented.")}onopen(e){throw new Error("Method not implemented.")}},localStorage:{},request:function(e,t){throw new Error("request not implemented.")},uploadFile:function(e){throw new Error("uploadFile not implemented.")},getSystemInfo:function(){throw new Error("getSystemInfo not implemented.")},getFileUploadInformation(e){throw new Error("getFileUploadInformation not implemented.")},envPayload:{},net:r,powerMonitor:i,logStorage:class AdapterLogStorageImpl{constructor(e){}open(){return Promise.resolve()}close(){}addLogs(e){return Promise.resolve()}extractLogs(){return Promise.resolve()}afterUpload(){return Promise.resolve()}}};!function(e){e[e.V2NIM_DATA_SYNC_TYPE_LEVEL_FULL=0]="V2NIM_DATA_SYNC_TYPE_LEVEL_FULL",e[e.V2NIM_DATA_SYNC_TYPE_LEVEL_BASIC=1]="V2NIM_DATA_SYNC_TYPE_LEVEL_BASIC"}(o||(o={})),function(e){e[e.V2NIM_DATA_SYNC_TYPE_MAIN=1]="V2NIM_DATA_SYNC_TYPE_MAIN",e[e.V2NIM_DATA_SYNC_TYPE_TEAM_MEMBER=2]="V2NIM_DATA_SYNC_TYPE_TEAM_MEMBER",e[e.V2NIM_DATA_SYNC_TYPE_SUPER_TEAM_MEMBER=3]="V2NIM_DATA_SYNC_TYPE_SUPER_TEAM_MEMBER"}(n||(n={})),function(e){e[e.V2NIM_DATA_SYNC_STATE_WAITING=1]="V2NIM_DATA_SYNC_STATE_WAITING",e[e.V2NIM_DATA_SYNC_STATE_SYNCING=2]="V2NIM_DATA_SYNC_STATE_SYNCING",e[e.V2NIM_DATA_SYNC_STATE_COMPLETED=3]="V2NIM_DATA_SYNC_STATE_COMPLETED"}(s||(s={})),function(e){e[e.V2NIM_CONVERSATION_TYPE_UNKNOWN=0]="V2NIM_CONVERSATION_TYPE_UNKNOWN",e[e.V2NIM_CONVERSATION_TYPE_P2P=1]="V2NIM_CONVERSATION_TYPE_P2P",e[e.V2NIM_CONVERSATION_TYPE_TEAM=2]="V2NIM_CONVERSATION_TYPE_TEAM",e[e.V2NIM_CONVERSATION_TYPE_SUPER_TEAM=3]="V2NIM_CONVERSATION_TYPE_SUPER_TEAM"}(a||(a={})),function(e){e[e.V2NIM_MESSAGE_STATUS_DEFAULT=0]="V2NIM_MESSAGE_STATUS_DEFAULT",e[e.V2NIM_MESSAGE_STATUS_REVOKE=1]="V2NIM_MESSAGE_STATUS_REVOKE",e[e.V2NIM_MESSAGE_STATUS_BACKFILL=2]="V2NIM_MESSAGE_STATUS_BACKFILL"}(c||(c={})),function(e){e[e.V2NIM_FRIEND_MODE_TYPE_ADD=1]="V2NIM_FRIEND_MODE_TYPE_ADD",e[e.V2NIM_FRIEND_MODE_TYPE_APPLY=2]="V2NIM_FRIEND_MODE_TYPE_APPLY"}(_||(_={})),function(e){e[e.V2NIM_FRIEND_ADD_APPLICATION_TYPE_LEGACY=0]="V2NIM_FRIEND_ADD_APPLICATION_TYPE_LEGACY",e[e.V2NIM_FRIEND_ADD_APPLICATION_TYPE_FROM_SELF=1]="V2NIM_FRIEND_ADD_APPLICATION_TYPE_FROM_SELF",e[e.V2NIM_FRIEND_ADD_APPLICATION_TYPE_TO_SELF=2]="V2NIM_FRIEND_ADD_APPLICATION_TYPE_TO_SELF",e[e.V2NIM_FRIEND_ADD_APPLICATION_TYPE_ALL=3]="V2NIM_FRIEND_ADD_APPLICATION_TYPE_ALL"}(l||(l={})),function(e){e[e.V2NIM_FRIEND_ADD_APPLICATION_STATUS_INIT=0]="V2NIM_FRIEND_ADD_APPLICATION_STATUS_INIT",e[e.V2NIM_FRIEND_ADD_APPLICATION_STATUS_AGREED=1]="V2NIM_FRIEND_ADD_APPLICATION_STATUS_AGREED",e[e.V2NIM_FRIEND_ADD_APPLICATION_STATUS_REJECTED=2]="V2NIM_FRIEND_ADD_APPLICATION_STATUS_REJECTED",e[e.V2NIM_FRIEND_ADD_APPLICATION_STATUS_EXPIRED=3]="V2NIM_FRIEND_ADD_APPLICATION_STATUS_EXPIRED",e[e.V2NIM_FRIEND_ADD_APPLICATION_STATUS_DIRECT_ADD=4]="V2NIM_FRIEND_ADD_APPLICATION_STATUS_DIRECT_ADD"}(d||(d={})),function(e){e[e.V2NIM_FRIEND_DELETION_TYPE_BY_SELF=1]="V2NIM_FRIEND_DELETION_TYPE_BY_SELF",e[e.V2NIM_FRIEND_DELETION_TYPE_BY_PEER=2]="V2NIM_FRIEND_DELETION_TYPE_BY_PEER"}(E||(E={})),function(e){e[e.V2NIM_FRIEND_VERIFY_TYPE_ADD=1]="V2NIM_FRIEND_VERIFY_TYPE_ADD",e[e.V2NIM_FRIEND_VERIFY_TYPE_APPLY=2]="V2NIM_FRIEND_VERIFY_TYPE_APPLY",e[e.V2NIM_FRIEND_VERIFY_TYPE_ACCEPT=3]="V2NIM_FRIEND_VERIFY_TYPE_ACCEPT",e[e.V2NIM_FRIEND_VERIFY_TYPE_REJECT=4]="V2NIM_FRIEND_VERIFY_TYPE_REJECT"}(h||(h={})),function(e){e[e.V2NIM_LOGIN_AUTH_TYPE_DEFAULT=0]="V2NIM_LOGIN_AUTH_TYPE_DEFAULT",e[e.V2NIM_LOGIN_AUTH_TYPE_DYNAMIC_TOKEN=1]="V2NIM_LOGIN_AUTH_TYPE_DYNAMIC_TOKEN",e[e.V2NIM_LOGIN_AUTH_TYPE_THIRD_PARTY=2]="V2NIM_LOGIN_AUTH_TYPE_THIRD_PARTY"}(u||(u={})),function(e){e[e.V2NIM_LOGIN_STATUS_LOGOUT=0]="V2NIM_LOGIN_STATUS_LOGOUT",e[e.V2NIM_LOGIN_STATUS_LOGINED=1]="V2NIM_LOGIN_STATUS_LOGINED",e[e.V2NIM_LOGIN_STATUS_LOGINING=2]="V2NIM_LOGIN_STATUS_LOGINING",e[e.V2NIM_LOGIN_STATUS_UNLOGIN=3]="V2NIM_LOGIN_STATUS_UNLOGIN"}(m||(m={})),function(e){e[e.V2NIM_LOGIN_CLIENT_TYPE_UNKNOWN=0]="V2NIM_LOGIN_CLIENT_TYPE_UNKNOWN",e[e.V2NIM_LOGIN_CLIENT_TYPE_ANDROID=1]="V2NIM_LOGIN_CLIENT_TYPE_ANDROID",e[e.V2NIM_LOGIN_CLIENT_TYPE_IOS=2]="V2NIM_LOGIN_CLIENT_TYPE_IOS",e[e.V2NIM_LOGIN_CLIENT_TYPE_PC=4]="V2NIM_LOGIN_CLIENT_TYPE_PC",e[e.V2NIM_LOGIN_CLIENT_TYPE_WP=8]="V2NIM_LOGIN_CLIENT_TYPE_WP",e[e.V2NIM_LOGIN_CLIENT_TYPE_WEB=16]="V2NIM_LOGIN_CLIENT_TYPE_WEB",e[e.V2NIM_LOGIN_CLIENT_TYPE_RESTFUL=32]="V2NIM_LOGIN_CLIENT_TYPE_RESTFUL",e[e.V2NIM_LOGIN_CLIENT_TYPE_MAC_OS=64]="V2NIM_LOGIN_CLIENT_TYPE_MAC_OS",e[e.V2NIM_LOGIN_CLIENT_TYPE_HARMONY_OS=65]="V2NIM_LOGIN_CLIENT_TYPE_HARMONY_OS"}(g||(g={})),function(e){e[e.V2NIM_KICKED_OFFLINE_REASON_CLIENT_EXCLUSIVE=1]="V2NIM_KICKED_OFFLINE_REASON_CLIENT_EXCLUSIVE",e[e.V2NIM_KICKED_OFFLINE_REASON_SERVER=2]="V2NIM_KICKED_OFFLINE_REASON_SERVER",e[e.V2NIM_KICKED_OFFLINE_REASON_CLIENT=3]="V2NIM_KICKED_OFFLINE_REASON_CLIENT",e[e.V2NIM_KICKED_OFFLINE_REASON_CLIENT_QUIETLY=4]="V2NIM_KICKED_OFFLINE_REASON_CLIENT_QUIETLY"}(p||(p={})),function(e){e[e.V2NIM_LOGIN_CLIENT_CHANGE_LIST=1]="V2NIM_LOGIN_CLIENT_CHANGE_LIST",e[e.V2NIM_LOGIN_CLIENT_CHANGE_LOGIN=2]="V2NIM_LOGIN_CLIENT_CHANGE_LOGIN",e[e.V2NIM_LOGIN_CLIENT_CHANGE_LOGOUT=3]="V2NIM_LOGIN_CLIENT_CHANGE_LOGOUT"}(I||(I={})),function(e){e[e.V2NIM_CONNECT_STATUS_DISCONNECTED=0]="V2NIM_CONNECT_STATUS_DISCONNECTED",e[e.V2NIM_CONNECT_STATUS_CONNECTED=1]="V2NIM_CONNECT_STATUS_CONNECTED",e[e.V2NIM_CONNECT_STATUS_CONNECTING=2]="V2NIM_CONNECT_STATUS_CONNECTING",e[e.V2NIM_CONNECT_STATUS_WAITING=3]="V2NIM_CONNECT_STATUS_WAITING"}(N||(N={})),function(e){e[e.NIM_MESSAGE_AI_STREAM_STATUS_STREAMING=-1]="NIM_MESSAGE_AI_STREAM_STATUS_STREAMING",e[e.NIM_MESSAGE_AI_STREAM_STATUS_NONE=0]="NIM_MESSAGE_AI_STREAM_STATUS_NONE",e[e.NIM_MESSAGE_AI_STREAM_STATUS_PLACEHOLDER=1]="NIM_MESSAGE_AI_STREAM_STATUS_PLACEHOLDER",e[e.NIM_MESSAGE_AI_STREAM_STATUS_CANCEL=2]="NIM_MESSAGE_AI_STREAM_STATUS_CANCEL",e[e.NIM_MESSAGE_AI_STREAM_STATUS_UPDATE=3]="NIM_MESSAGE_AI_STREAM_STATUS_UPDATE",e[e.NIM_MESSAGE_AI_STREAM_STATUS_COMPLETE=4]="NIM_MESSAGE_AI_STREAM_STATUS_COMPLETE",e[e.NIM_MESSAGE_AI_STREAM_STATUS_EXCEPTION=5]="NIM_MESSAGE_AI_STREAM_STATUS_EXCEPTION"}(T||(T={})),function(e){e[e.V2NIM_MESSAGE_AI_STREAM_STOP_OP_DEFAULT=0]="V2NIM_MESSAGE_AI_STREAM_STOP_OP_DEFAULT",e[e.V2NIM_MESSAGE_AI_STREAM_STOP_OP_REVOKE=1]="V2NIM_MESSAGE_AI_STREAM_STOP_OP_REVOKE",e[e.V2NIM_MESSAGE_AI_STREAM_STOP_OP_UPDATE=2]="V2NIM_MESSAGE_AI_STREAM_STOP_OP_UPDATE"}(O||(O={})),function(e){e[e.V2NIM_MESSAGE_AI_REGEN_OP_UPDATE=1]="V2NIM_MESSAGE_AI_REGEN_OP_UPDATE",e[e.V2NIM_MESSAGE_AI_REGEN_OP_NEW=2]="V2NIM_MESSAGE_AI_REGEN_OP_NEW"}(M||(M={})),function(e){e[e.V2NIM_MESSAGE_AI_STATUS_UNKNOW=0]="V2NIM_MESSAGE_AI_STATUS_UNKNOW",e[e.V2NIM_MESSAGE_AI_STATUS_AT=1]="V2NIM_MESSAGE_AI_STATUS_AT",e[e.V2NIM_MESSAGE_AI_STATUS_RESPONSE=2]="V2NIM_MESSAGE_AI_STATUS_RESPONSE"}(f||(f={})),function(e){e[e.V2NIM_MESSAGE_TYPE_INVALID=-1]="V2NIM_MESSAGE_TYPE_INVALID",e[e.V2NIM_MESSAGE_TYPE_TEXT=0]="V2NIM_MESSAGE_TYPE_TEXT",e[e.V2NIM_MESSAGE_TYPE_IMAGE=1]="V2NIM_MESSAGE_TYPE_IMAGE",e[e.V2NIM_MESSAGE_TYPE_AUDIO=2]="V2NIM_MESSAGE_TYPE_AUDIO",e[e.V2NIM_MESSAGE_TYPE_VIDEO=3]="V2NIM_MESSAGE_TYPE_VIDEO",e[e.V2NIM_MESSAGE_TYPE_LOCATION=4]="V2NIM_MESSAGE_TYPE_LOCATION",e[e.V2NIM_MESSAGE_TYPE_NOTIFICATION=5]="V2NIM_MESSAGE_TYPE_NOTIFICATION",e[e.V2NIM_MESSAGE_TYPE_FILE=6]="V2NIM_MESSAGE_TYPE_FILE",e[e.V2NIM_MESSAGE_TYPE_AVCHAT=7]="V2NIM_MESSAGE_TYPE_AVCHAT",e[e.V2NIM_MESSAGE_TYPE_TIPS=10]="V2NIM_MESSAGE_TYPE_TIPS",e[e.V2NIM_MESSAGE_TYPE_ROBOT=11]="V2NIM_MESSAGE_TYPE_ROBOT",e[e.V2NIM_MESSAGE_TYPE_CALL=12]="V2NIM_MESSAGE_TYPE_CALL",e[e.V2NIM_MESSAGE_TYPE_CUSTOM=100]="V2NIM_MESSAGE_TYPE_CUSTOM"}(S||(S={})),function(e){e[e.V2NIM_SEARCH_KEYWORD_MATCH_TYPE_OR=0]="V2NIM_SEARCH_KEYWORD_MATCH_TYPE_OR",e[e.V2NIM_SEARCH_KEYWORD_MATCH_TYPE_AND=1]="V2NIM_SEARCH_KEYWORD_MATCH_TYPE_AND"}(R||(R={})),function(e){e[e.V2NIM_SEARCH_DIRECTION_BACKWARD=0]="V2NIM_SEARCH_DIRECTION_BACKWARD",e[e.V2NIM_SEARCH_DIRECTION_FORWARD=1]="V2NIM_SEARCH_DIRECTION_FORWARD"}(A||(A={})),function(e){e[e.V2NIM_MESSAGE_NOTIFICATION_TYPE_UNDEFINED=-1]="V2NIM_MESSAGE_NOTIFICATION_TYPE_UNDEFINED",e[e.V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_INVITE=0]="V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_INVITE",e[e.V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_KICK=1]="V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_KICK",e[e.V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_LEAVE=2]="V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_LEAVE",e[e.V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_UPDATE_TINFO=3]="V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_UPDATE_TINFO",e[e.V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_DISMISS=4]="V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_DISMISS",e[e.V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_APPLY_PASS=5]="V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_APPLY_PASS",e[e.V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_OWNER_TRANSFER=6]="V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_OWNER_TRANSFER",e[e.V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_ADD_MANAGER=7]="V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_ADD_MANAGER",e[e.V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_REMOVE_MANAGER=8]="V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_REMOVE_MANAGER",e[e.V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_INVITE_ACCEPT=9]="V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_INVITE_ACCEPT",e[e.V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_BANNED_TEAM_MEMBER=10]="V2NIM_MESSAGE_NOTIFICATION_TYPE_TEAM_BANNED_TEAM_MEMBER",e[e.V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_INVITE=401]="V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_INVITE",e[e.V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_KICK=402]="V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_KICK",e[e.V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_LEAVE=403]="V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_LEAVE",e[e.V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_UPDATE_TINFO=404]="V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_UPDATE_TINFO",e[e.V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_DISMISS=405]="V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_DISMISS",e[e.V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_APPLY_PASS=410]="V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_APPLY_PASS",e[e.V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_OWNER_TRANSFER=406]="V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_OWNER_TRANSFER",e[e.V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_ADD_MANAGER=407]="V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_ADD_MANAGER",e[e.V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_REMOVE_MANAGER=408]="V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_REMOVE_MANAGER",e[e.V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_INVITE_ACCEPT=411]="V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_INVITE_ACCEPT",e[e.V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_BANNED_TEAM_MEMBER=409]="V2NIM_MESSAGE_NOTIFICATION_TYPE_SUPER_TEAM_BANNED_TEAM_MEMBER"}(C||(C={})),function(e){e[e.V2NIM_MESSAGE_ATTACHMENT_UPLOAD_STATE_UNKNOWN=0]="V2NIM_MESSAGE_ATTACHMENT_UPLOAD_STATE_UNKNOWN",e[e.V2NIM_MESSAGE_ATTACHMENT_UPLOAD_STATE_SUCCESS=1]="V2NIM_MESSAGE_ATTACHMENT_UPLOAD_STATE_SUCCESS",e[e.V2NIM_MESSAGE_ATTACHMENT_UPLOAD_STATE_FAILED=2]="V2NIM_MESSAGE_ATTACHMENT_UPLOAD_STATE_FAILED",e[e.V2NIM_MESSAGE_ATTACHMENT_UPLOAD_STATE_UPLOADING=3]="V2NIM_MESSAGE_ATTACHMENT_UPLOAD_STATE_UPLOADING"}(v||(v={})),function(e){e[e.V2NIM_MESSAGE_SENDING_STATE_UNKNOWN=0]="V2NIM_MESSAGE_SENDING_STATE_UNKNOWN",e[e.V2NIM_MESSAGE_SENDING_STATE_SUCCEEDED=1]="V2NIM_MESSAGE_SENDING_STATE_SUCCEEDED",e[e.V2NIM_MESSAGE_SENDING_STATE_FAILED=2]="V2NIM_MESSAGE_SENDING_STATE_FAILED",e[e.V2NIM_MESSAGE_SENDING_STATE_SENDING=3]="V2NIM_MESSAGE_SENDING_STATE_SENDING"}(y||(y={})),function(e){e[e.V2NIM_QUERY_DIRECTION_DESC=0]="V2NIM_QUERY_DIRECTION_DESC",e[e.V2NIM_QUERY_DIRECTION_ASC=1]="V2NIM_QUERY_DIRECTION_ASC"}(D||(D={})),function(e){e[e.V2NIM_CLEAR_HISTORY_MODE_ALL=0]="V2NIM_CLEAR_HISTORY_MODE_ALL",e[e.V2NIM_CLEAR_HISTORY_MODE_LOCAL=1]="V2NIM_CLEAR_HISTORY_MODE_LOCAL",e[e.V2NIM_CLEAR_HISTORY_MODE_LOCAL_IRREPARABLY=2]="V2NIM_CLEAR_HISTORY_MODE_LOCAL_IRREPARABLY"}(V||(V={})),function(e){e[e.V2NIM_MESSAGE_REVOKE_TYPE_UNDEFINED=0]="V2NIM_MESSAGE_REVOKE_TYPE_UNDEFINED",e[e.V2NIM_MESSAGE_REVOKE_TYPE_P2P_BOTHWAY=1]="V2NIM_MESSAGE_REVOKE_TYPE_P2P_BOTHWAY",e[e.V2NIM_MESSAGE_REVOKE_TYPE_TEAM_BOTHWAY=2]="V2NIM_MESSAGE_REVOKE_TYPE_TEAM_BOTHWAY",e[e.V2NIM_MESSAGE_REVOKE_TYPE_SUPERTEAM_BOTHWAY=3]="V2NIM_MESSAGE_REVOKE_TYPE_SUPERTEAM_BOTHWAY",e[e.V2NIM_MESSAGE_REVOKE_TYPE_P2P_ONEWAY=4]="V2NIM_MESSAGE_REVOKE_TYPE_P2P_ONEWAY",e[e.V2NIM_MESSAGE_REVOKE_TYPE_TEAM_ONEWAY=5]="V2NIM_MESSAGE_REVOKE_TYPE_TEAM_ONEWAY"}(L||(L={})),function(e){e[e.V2NIM_MESSAGE_PIN_STATE_NOT_PINNED=0]="V2NIM_MESSAGE_PIN_STATE_NOT_PINNED",e[e.V2NIM_MESSAGE_PIN_STATE_PINNED=1]="V2NIM_MESSAGE_PIN_STATE_PINNED",e[e.V2NIM_MESSAGE_PIN_STATE_UPDATED=2]="V2NIM_MESSAGE_PIN_STATE_UPDATED"}(b||(b={})),function(e){e[e.V2NIM_QUICK_COMMENT_STATE_ADD=1]="V2NIM_QUICK_COMMENT_STATE_ADD",e[e.V2NIM_QUICK_COMMENT_STATE_REMOVE=2]="V2NIM_QUICK_COMMENT_STATE_REMOVE"}(P||(P={})),function(e){e[e.V2NIM_CLIENT_ANTISPAM_OPERATE_NONE=0]="V2NIM_CLIENT_ANTISPAM_OPERATE_NONE",e[e.V2NIM_CLIENT_ANTISPAM_OPERATE_REPLACE=1]="V2NIM_CLIENT_ANTISPAM_OPERATE_REPLACE",e[e.V2NIM_CLIENT_ANTISPAM_OPERATE_CLIENT_SHIELD=2]="V2NIM_CLIENT_ANTISPAM_OPERATE_CLIENT_SHIELD",e[e.V2NIM_CLIENT_ANTISPAM_OPERATE_SERVER_SHIELD=3]="V2NIM_CLIENT_ANTISPAM_OPERATE_SERVER_SHIELD"}(k||(k={})),function(e){e[e.V2NIM_SORT_ORDER_DESC=0]="V2NIM_SORT_ORDER_DESC",e[e.V2NIM_SORT_ORDER_ASC=1]="V2NIM_SORT_ORDER_ASC"}(w||(w={})),function(e){e[e.P2P_DELETE_MSG=7]="P2P_DELETE_MSG",e[e.TEAM_DELETE_MSG=8]="TEAM_DELETE_MSG",e[e.SUPERTEAM_DELETE_MSG=12]="SUPERTEAM_DELETE_MSG",e[e.P2P_ONE_WAY_DELETE_MSG=13]="P2P_ONE_WAY_DELETE_MSG",e[e.TEAM_ONE_WAY_DELETE_MSG=14]="TEAM_ONE_WAY_DELETE_MSG",e[e.CUSTOM_P2P_MSG=100]="CUSTOM_P2P_MSG",e[e.CUSTOM_TEAM_MSG=101]="CUSTOM_TEAM_MSG",e[e.CUSTOM_SUPERTEAM_MSG=103]="CUSTOM_SUPERTEAM_MSG"}(U||(U={})),function(e){e[e.NIM_MESSAGE_STREAM_STATUS_STREAMING=-1]="NIM_MESSAGE_STREAM_STATUS_STREAMING",e[e.NIM_MESSAGE_STREAM_STATUS_NONE=0]="NIM_MESSAGE_STREAM_STATUS_NONE",e[e.NIM_MESSAGE_STREAM_STATUS_PLACEHOLDER=1]="NIM_MESSAGE_STREAM_STATUS_PLACEHOLDER",e[e.NIM_MESSAGE_STREAM_STATUS_CANCEL=2]="NIM_MESSAGE_STREAM_STATUS_CANCEL",e[e.NIM_MESSAGE_AI_STREAM_STATUS_UPDATE=3]="NIM_MESSAGE_AI_STREAM_STATUS_UPDATE",e[e.NIM_MESSAGE_STREAM_STATUS_COMPLETE=4]="NIM_MESSAGE_STREAM_STATUS_COMPLETE",e[e.NIM_MESSAGE_STREAM_STATUS_EXCEPTION=5]="NIM_MESSAGE_STREAM_STATUS_EXCEPTION"}(x||(x={})),function(e){e[e.V2NIM_MESSAGE_SOURCE_UNKNOWN=0]="V2NIM_MESSAGE_SOURCE_UNKNOWN",e[e.V2NIM_MESSAGE_SOURCE_ONLINE=1]="V2NIM_MESSAGE_SOURCE_ONLINE",e[e.V2NIM_MESSAGE_SOURCE_OFFLINE=2]="V2NIM_MESSAGE_SOURCE_OFFLINE",e[e.V2NIM_MESSAGE_SOURCE_ROAMING=3]="V2NIM_MESSAGE_SOURCE_ROAMING"}(G||(G={})),function(e){e[e.V2NIM_TEAM_MESSAGE_MUTE_MODE_OFF=0]="V2NIM_TEAM_MESSAGE_MUTE_MODE_OFF",e[e.V2NIM_TEAM_MESSAGE_MUTE_MODE_ON=1]="V2NIM_TEAM_MESSAGE_MUTE_MODE_ON",e[e.V2NIM_TEAM_MESSAGE_MUTE_MODE_NORMAL_ON=2]="V2NIM_TEAM_MESSAGE_MUTE_MODE_NORMAL_ON"}(B||(B={})),function(e){e[e.V2NIM_P2P_MESSAGE_MUTE_MODE_OFF=0]="V2NIM_P2P_MESSAGE_MUTE_MODE_OFF",e[e.V2NIM_P2P_MESSAGE_MUTE_MODE_ON=1]="V2NIM_P2P_MESSAGE_MUTE_MODE_ON"}(H||(H={})),function(e){e[e.V2NIM_TEAM_JOIN_ACTION_TEAM_TYPE_NORMAL=1]="V2NIM_TEAM_JOIN_ACTION_TEAM_TYPE_NORMAL",e[e.V2NIM_TEAM_JOIN_ACTION_TEAM_TYPE_SUPER=2]="V2NIM_TEAM_JOIN_ACTION_TEAM_TYPE_SUPER",e[e.V2NIM_TEAM_JOIN_ACTION_TEAM_TYPE_ALL=3]="V2NIM_TEAM_JOIN_ACTION_TEAM_TYPE_ALL"}(Y||(Y={})),function(e){e[e.V2NIM_TEAM_MEMBER_ROLE_QUERY_TYPE_ALL=0]="V2NIM_TEAM_MEMBER_ROLE_QUERY_TYPE_ALL",e[e.V2NIM_TEAM_MEMBER_ROLE_QUERY_TYPE_NORMAL=1]="V2NIM_TEAM_MEMBER_ROLE_QUERY_TYPE_NORMAL",e[e.V2NIM_TEAM_MEMBER_ROLE_QUERY_TYPE_MANAGER=2]="V2NIM_TEAM_MEMBER_ROLE_QUERY_TYPE_MANAGER"}(j||(j={})),function(e){e[e.V2NIM_TEAM_TYPE_INVALID=0]="V2NIM_TEAM_TYPE_INVALID",e[e.V2NIM_TEAM_TYPE_ADVANCED=1]="V2NIM_TEAM_TYPE_ADVANCED",e[e.V2NIM_TEAM_TYPE_SUPER=2]="V2NIM_TEAM_TYPE_SUPER"}($||($={})),function(e){e[e.V2NIM_TEAM_JOIN_MODE_FREE=0]="V2NIM_TEAM_JOIN_MODE_FREE",e[e.V2NIM_TEAM_JOIN_MODE_APPLY=1]="V2NIM_TEAM_JOIN_MODE_APPLY",e[e.V2NIM_TEAM_JOIN_MODE_INVITE=2]="V2NIM_TEAM_JOIN_MODE_INVITE"}(K||(K={})),function(e){e[e.V2NIM_TEAM_AGREE_MODE_AUTH=0]="V2NIM_TEAM_AGREE_MODE_AUTH",e[e.V2NIM_TEAM_AGREE_MODE_NO_AUTH=1]="V2NIM_TEAM_AGREE_MODE_NO_AUTH"}(q||(q={})),function(e){e[e.V2NIM_TEAM_INVITE_MODE_MANAGER=0]="V2NIM_TEAM_INVITE_MODE_MANAGER",e[e.V2NIM_TEAM_INVITE_MODE_ALL=1]="V2NIM_TEAM_INVITE_MODE_ALL"}(W||(W={})),function(e){e[e.V2NIM_TEAM_UPDATE_INFO_MODE_MANAGER=0]="V2NIM_TEAM_UPDATE_INFO_MODE_MANAGER",e[e.V2NIM_TEAM_UPDATE_INFO_MODE_ALL=1]="V2NIM_TEAM_UPDATE_INFO_MODE_ALL"}(z||(z={})),function(e){e[e.V2NIM_TEAM_CHAT_BANNED_MODE_UNBAN=0]="V2NIM_TEAM_CHAT_BANNED_MODE_UNBAN",e[e.V2NIM_TEAM_CHAT_BANNED_MODE_BANNED_NORMAL=1]="V2NIM_TEAM_CHAT_BANNED_MODE_BANNED_NORMAL",e[e.V2NIM_TEAM_CHAT_BANNED_MODE_BANNED_ALL=3]="V2NIM_TEAM_CHAT_BANNED_MODE_BANNED_ALL"}(J||(J={})),function(e){e[e.V2NIM_TEAM_UPDATE_EXTENSION_MODE_MANAGER=0]="V2NIM_TEAM_UPDATE_EXTENSION_MODE_MANAGER",e[e.V2NIM_TEAM_UPDATE_EXTENSION_MODE_ALL=1]="V2NIM_TEAM_UPDATE_EXTENSION_MODE_ALL"}(Q||(Q={})),function(e){e[e.V2NIM_TEAM_MEMBER_ROLE_NORMAL=0]="V2NIM_TEAM_MEMBER_ROLE_NORMAL",e[e.V2NIM_TEAM_MEMBER_ROLE_OWNER=1]="V2NIM_TEAM_MEMBER_ROLE_OWNER",e[e.V2NIM_TEAM_MEMBER_ROLE_MANAGER=2]="V2NIM_TEAM_MEMBER_ROLE_MANAGER"}(X||(X={})),function(e){e[e.V2NIM_TEAM_JOIN_ACTION_TYPE_APPLICATION=0]="V2NIM_TEAM_JOIN_ACTION_TYPE_APPLICATION",e[e.V2NIM_TEAM_JOIN_ACTION_TYPE_REJECT_APPLICATION=1]="V2NIM_TEAM_JOIN_ACTION_TYPE_REJECT_APPLICATION",e[e.V2NIM_TEAM_JOIN_ACTION_TYPE_INVITATION=2]="V2NIM_TEAM_JOIN_ACTION_TYPE_INVITATION",e[e.V2NIM_TEAM_JOIN_ACTION_TYPE_REJECT_INVITATION=3]="V2NIM_TEAM_JOIN_ACTION_TYPE_REJECT_INVITATION",e[e.V2NIM_TEAM_JOIN_ACTION_TYPE_ACCEPT_APPLICATION=4]="V2NIM_TEAM_JOIN_ACTION_TYPE_ACCEPT_APPLICATION",e[e.V2NIM_TEAM_JOIN_ACTION_TYPE_ACCEPT_INVITATION=5]="V2NIM_TEAM_JOIN_ACTION_TYPE_ACCEPT_INVITATION"}(Z||(Z={})),function(e){e[e.V2NIM_TEAM_JOIN_ACTION_STATUS_INIT=0]="V2NIM_TEAM_JOIN_ACTION_STATUS_INIT",e[e.V2NIM_TEAM_JOIN_ACTION_STATUS_AGREED=1]="V2NIM_TEAM_JOIN_ACTION_STATUS_AGREED",e[e.V2NIM_TEAM_JOIN_ACTION_STATUS_REJECTED=2]="V2NIM_TEAM_JOIN_ACTION_STATUS_REJECTED",e[e.V2NIM_TEAM_JOIN_ACTION_STATUS_EXPIRED=3]="V2NIM_TEAM_JOIN_ACTION_STATUS_EXPIRED"}(ee||(ee={})),function(e){e[e.teamApply=0]="teamApply",e[e.teamApplyReject=1]="teamApplyReject",e[e.teamInvite=2]="teamInvite",e[e.teamInviteReject=3]="teamInviteReject",e[e.tlistUpdate=4]="tlistUpdate",e[e.superTeamApply=15]="superTeamApply",e[e.superTeamApplyReject=16]="superTeamApplyReject",e[e.superTeamInvite=17]="superTeamInvite",e[e.superTeamInviteReject=18]="superTeamInviteReject"}(te||(te={})),function(e){e[e.V2NIM_AI_MODEL_TYPE_UNKNOW=0]="V2NIM_AI_MODEL_TYPE_UNKNOW",e[e.V2NIM_AI_MODEL_TYPE_QWEN=1]="V2NIM_AI_MODEL_TYPE_QWEN",e[e.V2NIM_AI_MODEL_TYPE_AZURE=2]="V2NIM_AI_MODEL_TYPE_AZURE",e[e.V2NIM_AI_MODEL_TYPE_PRIVATE=3]="V2NIM_AI_MODEL_TYPE_PRIVATE"}(re||(re={})),function(e){e[e.V2NIM_AI_MODEL_STREAM_CALL_STATUS_NONE=0]="V2NIM_AI_MODEL_STREAM_CALL_STATUS_NONE",e[e.V2NIM_AI_MODEL_STREAM_CALL_STATUS_CANCEL=2]="V2NIM_AI_MODEL_STREAM_CALL_STATUS_CANCEL",e[e.V2NIM_AI_MODEL_STREAM_CALL_STATUS_COMPLETE=4]="V2NIM_AI_MODEL_STREAM_CALL_STATUS_COMPLETE",e[e.V2NIM_AI_MODEL_STREAM_CALL_STATUS_EXCEPTION=5]="V2NIM_AI_MODEL_STREAM_CALL_STATUS_EXCEPTION"}(ie||(ie={})),function(e){e.V2NIM_AI_MODEL_ROLE_TYPE_SYSTEM="system",e.V2NIM_AI_MODEL_ROLE_TYPE_USER="user",e.V2NIM_AI_MODEL_ROLE_TYPE_ASSISTANT="assistant"}(oe||(oe={})),function(e){e[e.V2NIM_SIGNALLING_EVENT_TYPE_UNKNOWN=0]="V2NIM_SIGNALLING_EVENT_TYPE_UNKNOWN",e[e.V2NIM_SIGNALLING_EVENT_TYPE_CLOSE=1]="V2NIM_SIGNALLING_EVENT_TYPE_CLOSE",e[e.V2NIM_SIGNALLING_EVENT_TYPE_JOIN=2]="V2NIM_SIGNALLING_EVENT_TYPE_JOIN",e[e.V2NIM_SIGNALLING_EVENT_TYPE_INVITE=3]="V2NIM_SIGNALLING_EVENT_TYPE_INVITE",e[e.V2NIM_SIGNALLING_EVENT_TYPE_CANCEL_INVITE=4]="V2NIM_SIGNALLING_EVENT_TYPE_CANCEL_INVITE",e[e.V2NIM_SIGNALLING_EVENT_TYPE_REJECT=5]="V2NIM_SIGNALLING_EVENT_TYPE_REJECT",e[e.V2NIM_SIGNALLING_EVENT_TYPE_ACCEPT=6]="V2NIM_SIGNALLING_EVENT_TYPE_ACCEPT",e[e.V2NIM_SIGNALLING_EVENT_TYPE_LEAVE=7]="V2NIM_SIGNALLING_EVENT_TYPE_LEAVE",e[e.V2NIM_SIGNALLING_EVENT_TYPE_CONTROL=8]="V2NIM_SIGNALLING_EVENT_TYPE_CONTROL",e[e.V2NIM_SIGNALLING_EVENT_TYPE_KICK=9]="V2NIM_SIGNALLING_EVENT_TYPE_KICK"}(ne||(ne={})),function(e){e[e.V2NIM_SIGNALLING_CHANNEL_TYPE_AUDIO=1]="V2NIM_SIGNALLING_CHANNEL_TYPE_AUDIO",e[e.V2NIM_SIGNALLING_CHANNEL_TYPE_VIDEO=2]="V2NIM_SIGNALLING_CHANNEL_TYPE_VIDEO",e[e.V2NIM_SIGNALLING_CHANNEL_TYPE_CUSTOM=3]="V2NIM_SIGNALLING_CHANNEL_TYPE_CUSTOM"}(se||(se={})),function(e){e[e.V2NIM_USER_STATUS_TYPE_UNKNOWN=0]="V2NIM_USER_STATUS_TYPE_UNKNOWN",e[e.V2NIM_USER_STATUS_TYPE_LOGIN=1]="V2NIM_USER_STATUS_TYPE_LOGIN",e[e.V2NIM_USER_STATUS_TYPE_LOGOUT=2]="V2NIM_USER_STATUS_TYPE_LOGOUT",e[e.V2NIM_USER_STATUS_TYPE_DISCONNECT=3]="V2NIM_USER_STATUS_TYPE_DISCONNECT"}(ae||(ae={}));var _e={V2NIM_ERROR_CODE_UNKNOWN:{code:0,message:"unknown error"},V2NIM_ERROR_CODE_SUCCESS:{code:200,message:"success"},V2NIM_ERROR_CODE_HANDSHAKE:{code:201,message:"handshake error"},V2NIM_ERROR_CODE_REQUEST_TEMPERARY_FORBIDDEN:{code:398,message:"request temprary forbidden"},V2NIM_ERROR_CODE_SERVER_UNIT_ERROR:{code:399,message:"server unit error"},V2NIM_ERROR_CODE_FORBIDDEN:{code:403,message:"forbidden"},V2NIM_ERROR_CODE_NOT_FOUND:{code:404,message:"not found"},V2NIM_ERROR_CODE_PARAMETER_ERROR:{code:414,message:"parameter error"},V2NIM_ERROR_CODE_RATE_LIMIT_REACHED:{code:416,message:"rate limit reached"},V2NIM_ERROR_CODE_MULTI_LOGIN_FORBIDDEN:{code:417,message:"multi login forbidden"},V2NIM_ERROR_CODE_SERVER_INTERNAL_ERROR:{code:500,message:"server internal error"},V2NIM_ERROR_CODE_SERVER_BUSY:{code:503,message:"server busy"},V2NIM_ERROR_CODE_APP_UNREACHABLE:{code:511,message:"app server unreachable"},V2NIM_ERROR_CODE_SERVICE_UNAVAILABLE:{code:514,message:"service unavailable"},V2NIM_ERROR_CODE_PROTOCOL_BLACKHOLE_FILTERED:{code:599,message:"protocol filtered by blackhole rule"},V2NIM_ERROR_CODE_NO_PERMISSION:{code:997,message:"appid has no permission to call the protocol"},V2NIM_ERROR_CODE_UNPACK_ERROR:{code:998,message:"unpack error"},V2NIM_ERROR_CODE_PACK_ERROR:{code:999,message:"pack error"},V2NIM_ERROR_CODE_IM_DISABLED:{code:101301,message:"IM disabled"},V2NIM_ERROR_CODE_SERVICE_ADDRESS_INVALID:{code:101302,message:"service address invalid"},V2NIM_ERROR_CODE_APPKEY_NOT_EXIST:{code:101303,message:"appkey not exist"},V2NIM_ERROR_CODE_BUNDLEID_CHECK_FAILED:{code:101304,message:"bundleid check failed"},V2NIM_ERROR_CODE_APPKEY_BLOCKED:{code:101403,message:"appkey blocked"},V2NIM_ERROR_CODE_INVALID_TOKEN:{code:102302,message:"invalid token"},V2NIM_ERROR_CODE_ROBOT_NOT_ALLOWED:{code:102303,message:"robot not allowed"},V2NIM_ERROR_CODE_ACCOUNT_NOT_EXIST:{code:102404,message:"account not exist"},V2NIM_ERROR_CODE_ACCOUNT_CHAT_BANNED:{code:102421,message:"account chat banned"},V2NIM_ERROR_CODE_ACCOUNT_BANNED:{code:102422,message:"account banned"},V2NIM_ERROR_CODE_ACCOUNT_IN_BLOCK_LIST:{code:102426,message:"account in block list"},V2NIM_ERROR_CODE_USER_PROFILE_NOT_EXIST:{code:103404,message:"user profile not exist"},V2NIM_ERROR_CODE_USER_PROFILE_HIT_ANTISPAM:{code:103451,message:"user profile hit antispam"},V2NIM_ERROR_CODE_PEER_FRIEND_LIMIT:{code:104301,message:"peer friend limit"},V2NIM_ERROR_CODE_FRIEND_APPLICATION_NOT_EXIST:{code:104302,message:"friend application not exist"},V2NIM_ERROR_CODE_FRIEND_NOT_EXIST:{code:104404,message:"friend not exist"},V2NIM_ERROR_CODE_FRIEND_ALREADY_EXIST:{code:104405,message:"friend already exist"},V2NIM_ERROR_CODE_SELF_FRIEND_OPERATION_NOT_ALLOWED:{code:104429,message:"self friend operation not allowed"},V2NIM_ERROR_CODE_FRIEND_LIMIT:{code:104435,message:"friend limit"},V2NIM_ERROR_CODE_FRIEND_OPERATION_RATE_LIMIT:{code:104449,message:"friend operation rate limit"},V2NIM_ERROR_CODE_FRIEND_HIT_ANTISPAM:{code:104451,message:"friend hit antispam"},V2NIM_ERROR_CODE_SELF_MUTE_OPERATION_NOT_ALLOWED:{code:105429,message:"self mute operation not allowed"},V2NIM_ERROR_CODE_MUTE_LIST_LIMIT:{code:105435,message:"mute list limit"},V2NIM_ERROR_CODE_SELF_BLOCK_LIST_OPERATION_NOT_ALLOWED:{code:106429,message:"self block list operation not allowed"},V2NIM_ERROR_CODE_BLOCK_LIST_LIMIT:{code:106435,message:"block list limit"},V2NIM_ERROR_CODE_REVOKE_THIRD_PARTY_MESSAGE_NOT_ALLOWED:{code:107301,message:"revoke third party message not allowed"},V2NIM_ERROR_CODE_SHORT_TO_LONG_URL_FAILED:{code:107307,message:"short to long URL failed"},V2NIM_ERROR_CODE_URL_INVALID:{code:107308,message:"URL invalid"},V2NIM_ERROR_CODE_DURATION_OUT_OF_RANGE:{code:107309,message:"duration out of range"},V2NIM_ERROR_CODE_GET_FILE_META_INFO_FAILED:{code:107310,message:"get file meta info failed"},V2NIM_ERROR_CODE_AUDIO_FILE_SIZE_LIMIT:{code:107311,message:"audio file size limit"},V2NIM_ERROR_CODE_VOICE_TO_TEXT_TIMEOUT:{code:107312,message:"voice to text timeout"},V2NIM_ERROR_CODE_VOICE_TO_TEXT_FAILED:{code:107313,message:"voice to text failed"},V2NIM_ERROR_CODE_REVOKE_EXCEED_TIME_LIMIT:{code:107314,message:"revoke message exceed time limit"},V2NIM_ERROR_CODE_REVOKE_MESSAGE_NOT_ALLOWED:{code:107315,message:"revoke specific message not allowed"},V2NIM_ERROR_CODE_FORCE_PUSH_LIST_LIMIT:{code:107316,message:"force push list limit"},V2NIM_ERROR_CODE_TEAM_MESSAGE_RECEIPT_RATE_LIMIT:{code:107317,message:"team message receipt rate limit"},V2NIM_ERROR_CODE_SNAPSHOT_NOT_EXIST:{code:107318,message:"snapshot not exist"},V2NIM_ERROR_CODE_PIN_LIMIT:{code:107319,message:"pin limit"},V2NIM_ERROR_CODE_PIN_NOT_EXIST:{code:107320,message:"pin not exist"},V2NIM_ERROR_CODE_QUICK_COMMENT_LIMIT:{code:107321,message:"quick comment limit"},V2NIM_ERROR_CODE_PIN_ALREADY_EXIST:{code:107322,message:"pin already exist"},V2NIM_ERROR_CODE_VOICE_TO_TEXT_FUNCTION_DISABLED:{code:107333,message:"voice to text function disabled"},V2NIM_ERROR_CODE_CLOUD_SEARCH_FUNCTION_DISABLED:{code:107334,message:"cloud search function disabled"},V2NIM_ERROR_CODE_ONE_WAY_DELETE_FUNCTION_DISABLED:{code:107335,message:"one-way delete function disabled"},V2NIM_ERRPR_CODE_ONEWAY_DELETION_NOT_ALLOW_FOR_TARGET_MESSAGES:{code:107338,message:"one-way deletion is not allowed for target messages"},V2NIM_ERRPR_CODE_SENDER_CANNOT_INCLUDED_IN_TARGET_LIST:{code:107339,message:"The message sender cannot be included in the target list"},V2NIM_ERROR_CODE_ROBOT_CANNOT_SEND_TARGET_MESSAGE:{code:107340,message:"Robot can not send target message"},V2NIM_ERROR_CODE_PIN_TARGET_MESSAGE_NOT_ALLOWED:{code:107345,message:"Pin target message is not allowed"},V2NIM_ERROR_CODE_TARGET_MESSAGE_NOT_ALLOWED_REPLY:{code:107346,message:"Target message not allowed reply"},V2NIM_ERROR_CODE_TARGET_MESSAGE_NOT_ALLOWED_QUICK_COMMENT:{code:107347,message:"Target message not allowed quick comment"},V2NIM_ERROR_CODE_REVOKE_MESSAGE_TO_SELF_NOT_ALLOWED:{code:107429,message:"revoke message to self not allowed"},V2NIM_ERROR_CODE_APP_CHAT_BANNED:{code:107410,message:"app chat banned"},V2NIM_ERROR_CODE_QUICK_COMMENT_FUNCTION_DISABLED:{code:107326,message:"quick comment function disabled"},V2NIM_ERROR_CODE_PIN_FUNCTION_DISABLED:{code:107327,message:"PIN function disabled"},V2NIM_ERROR_CODE_TEAM_READ_RECEIPT_FUNCTION_DISABLED:{code:107324,message:"read receipt for team messages function disabled"},V2NIM_ERROR_CODE_P2P_READ_RECEIPT_FUNCTION_DISABLED:{code:107325,message:"read receipt for p2p messages function disabled"},V2NIM_ERROR_CODE_RATE_LIMIT_FOR_MESSAGING_REACHED:{code:107323,message:"rate limit for messaging reached"},V2NIM_ERROR_CODE_MESSAGE_HIT_ANTISPAM:{code:107451,message:"message hit antispam"},V2NIM_ERROR_CODE_MESSAGE_NOT_EXIST:{code:107404,message:"message not exist"},V2NIM_ERROR_CODE_UNSENDING_MESSAGE_EXPIRED:{code:107406,message:"unsending message expired"},V2NIM_ERROR_CODE_TEAM_MARK_READ_FAILED:{code:107302,message:"sending message failed for marking message read failed for too many team members"},V2NIM_ERROR_CODE_SENDER_OR_MANAGER_PERMISSION_ONLY_REVOKE:{code:107303,message:"only sender or manager can revoke message"},V2NIM_ERROR_CODE_DELETE_SELF_MESSAGE_NOT_ALLOWED:{code:107328,message:"delete self message not allowed"},V2NIM_ERROR_CODE_NOT_CHATBOT_ACCOUNT:{code:107329,message:"is not chatbot account"},V2NIM_ERROR_CODE_MESSAGE_SENSE_REQUIRED:{code:107330,message:"sender or receiver must sense message"},V2NIM_ERROR_CODE_HIGH_PRIORITY_MESSAGE_RATE_LIMIT:{code:107304,message:"rate limit of high-priority messages exceeded"},ACK_MESSAGE_BE_HIGH_PRIORITY:{code:107305,message:"ack message should be high-priority"},V2NIM_ERROR_CODE_DUPLICATE_CLIENT_MESSAGE_ID:{code:107306,message:"duplicate client message ID"},V2NIM_ERROR_CODE_INVALID_TIME_RANGE:{code:107439,message:"invalid time range"},V2NIM_ERROR_CODE_NOT_ADVANCED_TEAM:{code:108302,message:"not advanced team"},V2NIM_ERROR_CODE_TEAM_MANAGER_LIMIT:{code:108303,message:"team manager limit"},V2NIM_ERROR_CODE_JOINED_TEAM_LIMIT:{code:108305,message:"joined team limit"},V2NIM_ERROR_CODE_TEAM_NORMAL_MEMBER_CHAT_BANNED:{code:108306,message:"team normal member chat banned"},V2NIM_ERROR_CODE_INVITED_ACCOUNT_NOT_FRIEND:{code:108307,message:"invited account not friend"},V2NIM_ERROR_CODE_REJECT_ALL_TEAM_APPLICATIONS:{code:108308,message:"reject all team applications"},V2NIM_ERROR_CODE_TARGETING_MESSAGE_FOR_TEAM_DISABLED:{code:108318,message:"Targeting messages for group chat is disabled"},V2NIM_ERROR_CODE_INCLUSIVE_AS_FALSE_NOT_ALLOWED_FOR_SUPER_TEAM:{code:108319,message:'Setting "inclusive" to false for super teams is not allowed'},V2NIM_ERROR_CODE_CANNOT_MAKE_SUPER_TEAM_MESSAGE_VISIBLE_TO_NEW_MEMBERS:{code:108320,message:"Cannot make super team targeted messages visible to new members"},V2NIM_ERROR_CODE_CANNOT_ALLOW_TARGETED_MESSAGES_INCLUSIVE_TO_NEW_MEMBERS:{code:108321,message:"Cannot allow targeted messages inclusive to new members"},V2NIM_ERROR_CODE_TEAM_NOT_EXIST:{code:108404,message:"team not exist"},V2NIM_ERROR_CODE_TEAM_ALREADY_CHAT_BANNED:{code:108420,message:"team already chat banned"},V2NIM_ERROR_CODE_ALL_TEAM_MEMBER_CHAT_BANNED:{code:108423,message:"all team member chat banned"},V2NIM_ERROR_CODE_EXTENDED_SUPER_TEAM_LIMIT:{code:108434,message:"extended super team limit"},V2NIM_ERROR_CODE_CREATED_TEAM_LIMIT:{code:108435,message:"created team limit"},V2NIM_ERROR_CODE_TEAM_INVITATION_LIMIT:{code:108437,message:"team invitation limit"},V2NIM_ERROR_CODE_TEAM_HIT_ANTISPAM:{code:108451,message:"team hit antispam"},V2NIM_ERROR_CODE_EXTENDED_SUPER_TEAM_LIMIT_NOT_CONFIGURED:{code:108304,message:"extended super team limit not configured"},V2NIM_ERROR_CODE_SUPER_TEAM_SERVICE_DISABLED:{code:108311,message:"super team service disabled"},V2NIM_ERROR_CODE_TEAM_READ_RECEIPT_RECORD_NOT_FOUND:{code:108301,message:"read receipt record for the team message not found"},V2NIM_ERROR_CODE_NOT_MANAGER:{code:108430,message:"unable to assign owner manager"},V2NIM_ERROR_CODE_ONLINE_MEMBER_COUNT_DISABLED:{code:108406,message:"number of online users service disabled"},V2NIM_ERROR_CODE_TRANSFER_DISABLED:{code:108310,message:"unable to transfer the ownership to owner"},V2NIM_ERROR_CODE_CREATE_TEAM_DISABLED:{code:108309,message:"unable to create team with more than %s people"},V2NIM_ERROR_CODE_EXTENDED_SUPER_TEAM_CREATE_FAILED:{code:108313,message:"/ extended super team creation failed,use open api to create the team"},V2NIM_ERROR_CODE_TEAM_MESSAGE_READ_RECEIPT_DISABLED:{code:108312,message:"read receipt for team messages function disabled"},V2NIM_ERROR_CODE_RETRY:{code:108449,message:"an error occurred, try again"},V2NIM_ERROR_CODE_CHAT_BAN_LIST_CONTAIN_NOT_TEAM_MEMBER:{code:109301,message:"list of chat banned users contains non team members"},V2NIM_ERROR_CODE_CHAT_BAN_LIST_CONTAIN_OPERATOR:{code:109303,message:"list of chat banned users contains the operator"},V2NIM_ERROR_CODE_CHAT_BAN_LIST_CONTAIN_TEAM_OWNER:{code:109304,message:"list of chat banned users contains the team owner"},V2NIM_ERROR_CODE_OPERATION_ON_TEAM_MANAGER_NOT_ALLOWED:{code:109305,message:"operation on team manager not allowed"},V2NIM_ERROR_CODE_NO_TEAM_INVITE_PERMISSION:{code:109306,message:"no team invite permission"},V2NIM_ERROR_CODE_TEAM_OWNER_QUIT_NOT_ALLOWED:{code:109307,message:"team owner quit not allowed"},V2NIM_ERROR_CODE_TEAM_OWNER_IN_KICK_LIST:{code:109308,message:"list of kicked user contains the team owner"},V2NIM_ERROR_CODE_INVITE_ROBOT_ACCOUNT_NOT_ALLOWED:{code:109309,message:"invite robot account not allowed"},V2NIM_ERROR_CODE_KICK_OPERATOR_NOT_ALLOWED:{code:109310,message:"kick operator not allowed"},V2NIM_ERROR_CODE_TEAM_MEMBER_ALREADY_EXIST:{code:109311,message:"team member already exist"},V2NIM_ERROR_CODE_TEAM_INVITATION_OR_APPLICATION_NOT_EXIST:{code:109313,message:"team invitation or application not exist"},V2NIM_ERROR_CODE_OPERATION_ON_TEAM_OWNER_NOT_ALLOWED:{code:109314,message:"operation on team owner not allowed"},V2NIM_ERROR_CODE_FORCED_PUSH_LIST_INCLUDES_NON_TARGETED_ACCOUNTS:{code:109318,message:"The forced push list includes non-targeted accounts"},V2NIM_ERROR_CODE_TEAM_MEMBER_NOT_EXIST:{code:109404,message:"team member not exist"},V2NIM_ERROR_CODE_TEAM_MEMBER_CHAT_BANNED:{code:109424,message:"team member chat banned"},V2NIM_ERROR_CODE_TEAM_OWNER_OPERATION_PERMISSION_REQUIRED:{code:109427,message:"team owner operation permission required"},V2NIM_ERROR_CODE_TEAM_OWNER_OR_MANAGER_OPERATION_PERMISSION_REQUIRED:{code:109432,message:"team owner or manager operation permission required"},V2NIM_ERROR_CODE_TEAM_MEMBER_CONCURRENT_OPERATION_FAILED:{code:109449,message:"team member concurrent operation failed"},V2NIM_ERROR_CODE_TEAM_MEMBER_HIT_ANTISPAM:{code:109451,message:"team member hit antispam"},V2NIM_ERROR_CODE_CONVERSATION_AND_ACCOUNT_MISMATCH:{code:110302,message:"conversation and account mismatch"},V2NIM_ERROR_CODE_CONVERSATION_STICK_TOP_LIMIT:{code:110303,message:"conversation stick top limit"},V2NIM_ERROR_CODE_CONVERSATION_BELONGED_GROUP_LIMIT:{code:110304,message:"conversation belonged group limit"},V2NIM_ERROR_CODE_CONVERSATION_IS_NOT_STICK_TOP:{code:110305,message:"conversation is not stick top"},V2NIM_ERROR_CODE_STICK_TOP_DISABLED:{code:110306,message:"conversation stick top disabled"},V2NIM_ERROR_CODE_CONVERSATION_NOT_EXIST:{code:110404,message:"conversation not exist"},V2NIM_ERROR_CODE_CHATROOM_LINK_UNAVAILABLE:{code:113304,message:"chatroom link unavailable"},V2NIM_ERROR_CODE_IM_CONNECTION_ABNORMAL:{code:113305,message:"IM connection abnormal"},V2NIM_ERROR_CODE_CHATROOM_NOT_EXIST:{code:113404,message:"chatroom not exist"},V2NIM_ERROR_CODE_CHATROOM_CLOSED:{code:113406,message:"chatroom closed"},V2NIM_ERROR_CODE_CHATROOM_REPEATED_OPERATION:{code:113409,message:"chatroom repeated operation"},V2NIM_ERROR_CODE_CHATROOM_DISABLED:{code:113410,message:"chatroom disabled"},V2NIM_ERROR_CODE_ALL_CHATROOM_MEMBER_CHAT_BANNED:{code:113423,message:"all chatroom member chat banned"},V2NIM_ERROR_CODE_CHATROOM_HIT_ANTISPAM:{code:113451,message:"chatroom hit antispam"},V2NIM_ERROR_CODE_ANONYMOUS_MEMBER_FORBIDDEN:{code:114303,message:"anonymous member forbidden"},V2NIM_ERROR_CODE_CHATROOM_MEMBER_NOT_EXIST:{code:114404,message:"chatroom member not exist"},V2NIM_ERROR_CODE_CHATROOM_MEMBER_REPEATED_OPERATION:{code:114405,message:"chatroom member repeated operation"},V2NIM_ERROR_CODE_CHATROOM_MEMBER_CHAT_BANNED:{code:114421,message:"chatroom member chat banned"},V2NIM_ERROR_CODE_ACCOUNT_IN_CHATROOM_BLOCK_LIST:{code:114426,message:"account in chatroom block list"},V2NIM_ERROR_CODE_CHATROOM_OWNER_OPERATION_PERMISSION_REQUIRED:{code:114427,message:"chatroom owner operation permission required"},V2NIM_ERROR_CODE_SELF_IN_CHATROOM_MEMBER_OPERATION_LIST:{code:114429,message:"self in chatroom member operation list"},V2NIM_ERROR_CODE_CHATROOM_OWNER_OR_MANAGER_OPERATION_PERMISSION_REQUIRED:{code:114432,message:"chatroom owner or manager operation permission required"},V2NIM_ERROR_CODE_CHATROOM_MEMBER_LIMIT:{code:114437,message:"chatroom member limit"},V2NIM_ERROR_CODE_CHATROOM_MEMBER_CONCURRENT_OPERATION_FAILED:{code:114449,message:"chatroom member concurrent operation failed"},V2NIM_ERROR_CODE_CHATROOM_MEMBER_HIT_ANTISPAM:{code:114451,message:"chatroom member hit antispam"},V2NIM_ERROR_CODE_CONVERSATION_GROUP_NOT_EXIST:{code:116404,message:"conversation group not exist"},V2NIM_ERROR_CODE_CONVERSATION_GROUP_LIMIT:{code:116435,message:"conversation group limit"},V2NIM_ERROR_CODE_CONVERSATIONS_IN_GROUP_LIMIT:{code:116437,message:"conversations in group limit"},V2NIM_ERROR_CODE_COLLECTION_LIMIT:{code:189301,message:"collection limit"},V2NIM_ERROR_CODE_COLLECTION_NOT_EXIST:{code:189302,message:"collection not exist"},V2NIM_ERROR_CODE_COLLECTION_CONCURRENT_OPERATION_FAILED:{code:189449,message:"collection concurrent operation failed"},V2NIM_ERROR_CODE_INTERNAL:{code:190001,message:"internal error"},V2NIM_ERROR_CODE_ILLEGAL_STATE:{code:190002,message:"illegal state"},V2NIM_ERROR_CODE_MISUSE:{code:191001,message:"misuse"},V2NIM_ERROR_CODE_CANCELLED:{code:191002,message:"operation cancelled"},V2NIM_ERROR_CODE_CALLBACK_FAILED:{code:191003,message:"callback failed"},V2NIM_ERROR_CODE_INVALID_PARAMETER:{code:191004,message:"invalid parameter"},V2NIM_ERROR_CODE_TIMEOUT:{code:191005,message:"timeout"},V2NIM_ERROR_CODE_RESOURCE_NOT_EXIST:{code:191006,message:"resource not exist"},V2NIM_ERROR_CODE_RESOURCE_ALREADY_EXIST:{code:191007,message:"resource already exist"},V2NIM_ERROR_CODE_CONNECT_FAILED:{code:192001,message:"connect failed"},V2NIM_ERROR_CODE_CONNECT_TIMEOUT:{code:192002,message:"connect timeout"},V2NIM_ERROR_CODE_DISCONNECT:{code:192003,message:"disconnect"},V2NIM_ERROR_CODE_PROTOCOL_TIMEOUT:{code:192004,message:"protocol timeout"},V2NIM_ERROR_CODE_PROTOCOL_SEND_FAILED:{code:192005,message:"protocol send failed"},V2NIM_ERROR_CODE_REQUEST_FAILED:{code:192006,message:"request failed"},V2NIM_ERROR_CODE_FILE_NOT_FOUND:{code:194001,message:"file not found"},V2NIM_ERROR_CODE_FILE_CREATE_FAILED:{code:194002,message:"file create failed"},V2NIM_ERROR_CODE_FILE_OPEN_FAILED:{code:194003,message:"file open failed"},V2NIM_ERROR_CODE_FILE_WRITE_FAILED:{code:194004,message:"file write failed"},V2NIM_ERROR_CODE_FILE_READ_FAILED:{code:194005,message:"file read failed"},V2NIM_ERROR_CODE_FILE_UPLOAD_FAILED:{code:194006,message:"file upload failed"},V2NIM_ERROR_CODE_FILE_DOWNLOAD_FAILED:{code:194007,message:"file download failed"},V2NIM_ERROR_CODE_CLIENT_ANTISPAM:{code:195001,message:"client anti-spam"},V2NIM_ERROR_CODE_SERVER_ANTISPAM:{code:195002,message:"server anti-spam"},V2NIM_ERROR_CODE_STREAM_OUTPUT_STOPPED:{code:189318,message:"Streaming text response stopped"},V2NIM_ERROR_CODE_STREAM_OUTPUT_GENERATED:{code:189319,message:"Streaming text response generated"},V2NIM_ERROR_CODE_STREAM_OUTPUT_ABORTED:{code:189320,message:"Streaming text response aborted due to exception"},V2NIM_ERROR_CODE_INTERRUPTION_REJECTED:{code:189321,message:"Non-streaming messages cannot be interrupted"}},le=Object.keys(_e),de=le.reduce((function(e,t){var r=_e[t];return e[t]=r.code,e}),{}),Ee=le.reduce((function(e,t){var r=_e[t];return e[r.code]=r.message,e}),{});class V2NIMErrorImpl extends Error{constructor(e){super(e.desc),this.name="V2NIMError",this.code=e.code||0,this.desc=e.desc||Ee[this.code]||he[this.code]||"",this.message=this.desc,this.detail=e.detail||{}}toString(){var e,t=`${this.name}\n code: ${this.code}\n message: "${this.message}"\n detail: ${this.detail?JSON.stringify(this.detail):""}`;return(null===(e=null==this?void 0:this.detail)||void 0===e?void 0:e.rawError)&&(t+=`\n rawError: ${this.detail.rawError.message}`),t}}class ValidateError extends V2NIMErrorImpl{constructor(e,t={},r){super({code:de.V2NIM_ERROR_CODE_PARAMETER_ERROR,detail:{reason:e,rules:r,data:t}}),this.name="validateError",this.message=this.message+"\n"+JSON.stringify(this.detail,null,2),this.data=t,this.rules=r}}class ValidateErrorV2 extends V2NIMErrorImpl{constructor(e){var t,r,i;super({code:de.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:null===(t=e.detail)||void 0===t?void 0:t.reason,rules:null===(r=e.detail)||void 0===r?void 0:r.rules,data:null===(i=e.detail)||void 0===i?void 0:i.data}}),this.name="ValidateErrorV2"}}class UploadError extends V2NIMErrorImpl{constructor(e){super(Object.assign({code:400},e)),this.desc=this.desc||"upload file error",this.message=this.desc,this.name="uploadError"}}var he={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"},ue=["error","warn","log","debug"],emptyFunc=function(){},me=["off","error","warn","log","debug"];class Logger{constructor(e,t={}){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,this.log=emptyFunc,this.warn=emptyFunc,this.error=emptyFunc,this.iid=Math.round(1e3*Math.random()),this.debugLevel=me.indexOf(e)>-1?e:"off",t.debugLevel&&(this.debugLevel=me.indexOf(t.debugLevel)>-1?t.debugLevel:this.debugLevel),this.logStorage=!1===t.storageEnable?null:new ce.logStorage({logDirPath:t.logDirPath||t.storageName||"nim_logs",logRetentionDays:t.logRetentionDays||10,totalLogSizeInMB:t.totalLogSizeInMB||200,maxLogFileSizeInMB:t.maxLogFileSizeInMB||10}),this.setOptions(t),this.setLogFunc(this.debugLevel),this.setTimer(),ce.setLogger(this),this.open()}getDebugMode(){return"debug"===this.debugLevel}open(){this.logStorage&&this.logStorage.open().then((()=>{this.log("Logger::open success")})).catch((e=>{this.warn("Logger::open failed",e)}))}setOptions(e){if(e&&e.logFunc){var t=e.logFunc;for(var r in t){var i=r,o=t[i];o&&(this.strategies[i].func=o)}}}setLogFunc(e,t="log"){var r=ue.findIndex((t=>t===e)),i=ue.findIndex((e=>e===t));ue.forEach(((e,t)=>{this[e]=function(){if(!(t>r&&t>i)){var o=Array.prototype.slice.call(arguments),n=this.strategies[e],s=this.formatArgs(o,n.name);t<=i&&this.logStorage&&this.prepareSaveLog(s,e),t<=r&&n.func(s)}}}))}extractLogs(){var e;return this.logStorage?null===(e=this.logStorage)||void 0===e?void 0:e.extractLogs():Promise.resolve("")}afterUpload(){var e;return this.logStorage?null===(e=this.logStorage)||void 0===e?void 0:e.afterUpload():Promise.resolve("")}prepareSaveLog(e,t){this.storageArr.push({text:e,level:t,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 e=this.storageArr;this.storageArr=[];try{yield this.logStorage.addLogs(e)}catch(e){}}}))}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(e,t){var r=new Date;return`[NIM ${this.iid} ${t} ${`${r.getMonth()+1}-${r.getDate()} ${r.getHours()}:${r.getMinutes()}:${r.getSeconds()}:${r.getMilliseconds()}`}] `+e.map((e=>e instanceof V2NIMErrorImpl?e.toString():e instanceof Error?e&&e.message?e.message:e:"object"==typeof e?JSON.stringify(e):e)).join(" ")}destroy(){this.debug=emptyFunc,this.log=emptyFunc,this.warn=emptyFunc,this.error=emptyFunc,this.saveLogs(),this.clearTimer(),this.storageArr=[],this.logStorage&&this.logStorage.close()}}var ge="https://abt-online.netease.im/v1/api/abt/client/getExperimentInfo",pe="imElite_sdk_abtest_web";class Backoff{constructor(e={}){this.attempts=0,this.ms=e.min||100,this.max=e.max||1e4,this.jitter=e.jitter||0,this.factor=e.factor||2}duration(){var e,t=Math.pow(this.factor,this.attempts++);if(t===1/0||!isFinite(t))return 0|this.max;if(e=this.ms*t,!isFinite(e)||e>=this.max)return 0|this.max;if(this.jitter){var r=Math.random(),i=Math.floor(r*this.jitter*e);e=0==(1&Math.floor(10*r))?e-i:e+i,e=Math.max(Math.min(e,this.max),this.ms)}return 0|e}reset(){this.attempts=0}setMin(e){this.ms=e}setMax(e){this.max=e}setJitter(e){this.jitter=e}}var Ie=createCommonjsModule((function(e){var t=Object.prototype.hasOwnProperty,r="~";function Events(){}function EE(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function addListener(e,t,i,o,n){if("function"!=typeof i)throw new TypeError("The listener must be a function");var s=new EE(i,o||e,n),a=r?r+t:t;return e._events[a]?e._events[a].fn?e._events[a]=[e._events[a],s]:e._events[a].push(s):(e._events[a]=s,e._eventsCount++),e}function clearEvent(e,t){0==--e._eventsCount?e._events=new Events:delete e._events[t]}function EventEmitter(){this._events=new Events,this._eventsCount=0}Object.create&&(Events.prototype=Object.create(null),(new Events).__proto__||(r=!1)),EventEmitter.prototype.eventNames=function eventNames(){var e,i,o=[];if(0===this._eventsCount)return o;for(i in e=this._events)t.call(e,i)&&o.push(r?i.slice(1):i);return Object.getOwnPropertySymbols?o.concat(Object.getOwnPropertySymbols(e)):o},EventEmitter.prototype.listeners=function listeners(e){var t=r?r+e:e,i=this._events[t];if(!i)return[];if(i.fn)return[i.fn];for(var o=0,n=i.length,s=new Array(n);o<n;o++)s[o]=i[o].fn;return s},EventEmitter.prototype.listenerCount=function listenerCount(e){var t=r?r+e:e,i=this._events[t];return i?i.fn?1:i.length:0},EventEmitter.prototype.emit=function emit(e,t,i,o,n,s){var a=r?r+e:e;if(!this._events[a])return!1;var c,_,l=this._events[a],d=arguments.length;if(l.fn){switch(l.once&&this.removeListener(e,l.fn,void 0,!0),d){case 1:return l.fn.call(l.context),!0;case 2:return l.fn.call(l.context,t),!0;case 3:return l.fn.call(l.context,t,i),!0;case 4:return l.fn.call(l.context,t,i,o),!0;case 5:return l.fn.call(l.context,t,i,o,n),!0;case 6:return l.fn.call(l.context,t,i,o,n,s),!0}for(_=1,c=new Array(d-1);_<d;_++)c[_-1]=arguments[_];l.fn.apply(l.context,c)}else{var E,h=l.length;for(_=0;_<h;_++)switch(l[_].once&&this.removeListener(e,l[_].fn,void 0,!0),d){case 1:l[_].fn.call(l[_].context);break;case 2:l[_].fn.call(l[_].context,t);break;case 3:l[_].fn.call(l[_].context,t,i);break;case 4:l[_].fn.call(l[_].context,t,i,o);break;default:if(!c)for(E=1,c=new Array(d-1);E<d;E++)c[E-1]=arguments[E];l[_].fn.apply(l[_].context,c)}}return!0},EventEmitter.prototype.on=function on(e,t,r){return addListener(this,e,t,r,!1)},EventEmitter.prototype.once=function once(e,t,r){return addListener(this,e,t,r,!0)},EventEmitter.prototype.removeListener=function removeListener(e,t,i,o){var n=r?r+e:e;if(!this._events[n])return this;if(!t)return clearEvent(this,n),this;var s=this._events[n];if(s.fn)s.fn!==t||o&&!s.once||i&&s.context!==i||clearEvent(this,n);else{for(var a=0,c=[],_=s.length;a<_;a++)(s[a].fn!==t||o&&!s[a].once||i&&s[a].context!==i)&&c.push(s[a]);c.length?this._events[n]=1===c.length?c[0]:c:clearEvent(this,n)}return this},EventEmitter.prototype.removeAllListeners=function removeAllListeners(e){var t;return e?(t=r?r+e:e,this._events[t]&&clearEvent(this,t)):(this._events=new Events,this._eventsCount=0),this},EventEmitter.prototype.off=EventEmitter.prototype.removeListener,EventEmitter.prototype.addListener=EventEmitter.prototype.on,EventEmitter.prefixed=r,EventEmitter.EventEmitter=EventEmitter,e.exports=EventEmitter}));function get(e,t){if("object"!=typeof e||null===e)return e;for(var r=(t=t||"").split("."),i=0;i<r.length;i++){var o=r[i],n=e[o],s=o.indexOf("["),a=o.indexOf("]");if(-1!==s&&-1!==a&&s<a){var c=o.slice(0,s),_=parseInt(o.slice(s+1,a));n=e[c],n=Array.isArray(n)?n[_]:void 0}if(null==n)return n;e=n}return e}var abs=function(e){var t;if(void 0!==e)return(t=BigNumber(e)).sign=1,t},isArray=function(e){return"[object Array]"===Object.prototype.toString.call(e)},isValidType=function(e){return["number"==typeof e,"string"==typeof e&&e.length>0,isArray(e)&&e.length>0,e instanceof BigNumber].some((function(e){return!0===e}))},Ne="Invalid Number",Te="Invalid Number - Division By Zero";function BigNumber(e){var t;if(!(this instanceof BigNumber))return new BigNumber(e);if(this.number=[],this.sign=1,this.rest=0,isValidType(e)){if(isArray(e)){for((e.length&&"-"===e[0]||"+"===e[0])&&(this.sign="+"===e[0]?1:-1,e.shift(0)),t=e.length-1;t>=0;t--)if(!this.addDigit(e[t]))return}else for("-"!==(e=e.toString()).charAt(0)&&"+"!==e.charAt(0)||(this.sign="+"===e.charAt(0)?1:-1,e=e.substring(1)),t=e.length-1;t>=0;t--)if(!this.addDigit(parseInt(e.charAt(t),10)))return}else this.number=Ne}BigNumber.prototype.addDigit=function(e){return function(e){return/^\d$/.test(e)}(e)?(this.number.push(e),this):(this.number=Ne,!1)},BigNumber.prototype._compare=function(e){var t,r;if(!isValidType(e))return null;if(t=BigNumber(e),this.sign!==t.sign)return this.sign;if(this.number.length>t.number.length)return this.sign;if(this.number.length<t.number.length)return-1*this.sign;for(r=this.number.length-1;r>=0;r--){if(this.number[r]>t.number[r])return this.sign;if(this.number[r]<t.number[r])return-1*this.sign}return 0},BigNumber.prototype.gt=function(e){return this._compare(e)>0},BigNumber.prototype.gte=function(e){return this._compare(e)>=0},BigNumber.prototype.equals=function(e){return 0===this._compare(e)},BigNumber.prototype.lte=function(e){return this._compare(e)<=0},BigNumber.prototype.lt=function(e){return this._compare(e)<0},BigNumber.prototype.subtract=function(e){var t;return void 0===e?this:(t=BigNumber(e),this.sign!==t.sign?(this.number=BigNumber._add(this,t),this):(this.sign=this.lt(t)?-1:1,this.number=abs(this).lt(abs(t))?BigNumber._subtract(t,this):BigNumber._subtract(this,t),this))},BigNumber._add=function(e,t){var r,i=0,o=Math.max(e.number.length,t.number.length);for(r=0;r<o||i>0;r++)e.number[r]=(i+=(e.number[r]||0)+(t.number[r]||0))%10,i=Math.floor(i/10);return e.number},BigNumber._subtract=function(e,t){var r,i=0,o=e.number.length;for(r=0;r<o;r++)e.number[r]-=(t.number[r]||0)+i,e.number[r]+=10*(i=e.number[r]<0?1:0);for(r=0,o=e.number.length-1;0===e.number[o-r]&&o-r>0;)r++;return r>0&&e.number.splice(-r),e.number},BigNumber.prototype.multiply=function(e){if(void 0===e)return this;var t,r,i=BigNumber(e),o=0,n=[];if(this.isZero()||i.isZero())return BigNumber(0);for(this.sign*=i.sign,t=0;t<this.number.length;t++)for(o=0,r=0;r<i.number.length||o>0;r++)n[t+r]=(o+=(n[t+r]||0)+this.number[t]*(i.number[r]||0))%10,o=Math.floor(o/10);return this.number=n,this},BigNumber.prototype.divide=function(e){if(void 0===e)return this;var t,r,i=BigNumber(e),o=[],n=BigNumber(0);if(i.isZero())return this.number=Te,this;if(this.isZero())return this.rest=BigNumber(0),this;if(this.sign*=i.sign,i.sign=1,1===i.number.length&&1===i.number[0])return this.rest=BigNumber(0),this;for(t=this.number.length-1;t>=0;t--)for(n.multiply(10),n.number[0]=this.number[t],o[t]=0;i.lte(n);)o[t]++,n.subtract(i);for(t=0,r=o.length-1;0===o[r-t]&&r-t>0;)t++;return t>0&&o.splice(-t),this.rest=n,this.number=o,this},BigNumber.prototype.mod=function(e){return this.divide(e).rest},BigNumber.prototype.isZero=function(){var e;for(e=0;e<this.number.length;e++)if(0!==this.number[e])return!1;return!0},BigNumber.prototype.toString=function(){var e,t="";if("string"==typeof this.number)return this.number;for(e=this.number.length-1;e>=0;e--)t+=this.number[e];return this.sign>0?t:"-"+t};var Oe=Math.pow(2,32);function varintToBytes(e){for(var t=new Uint8Array(5),r=new DataView(t.buffer),i=0;0!=(4294967168&e);)r.setUint8(i++,127&e|128),e>>>=7;return r.setUint8(i++,127&e),t.slice(0,i)}function decodeText(e){return"function"==typeof TextDecoder?new TextDecoder("utf-8").decode(e):function textDecoder(e){for(var t="",r=0;r<e.length;){var i=e[r],o=0,n=0;if(i<=127?(o=0,n=255&i):i<=223?(o=1,n=31&i):i<=239?(o=2,n=15&i):i<=244&&(o=3,n=7&i),e.length-r-o>0)for(var s=0;s<o;)n=n<<6|63&(i=e[r+s+1]),s+=1;else n=65533,o=e.length-r;t+=String.fromCodePoint(n),r+=o+1}return t}(e)}class Unpack{constructor(e){this.offset=0,this.buffer=new Uint8Array(e),this.view=new DataView(e)}checkBufferBoundaryAccess(){return this.offset>=this.buffer.byteLength}length(){var e;return(null===(e=this.view)||void 0===e?void 0:e.byteLength)||0}getBuffer(){return this.view.buffer}getOffset(){return this.offset}popRaw(e){try{var t=this.buffer.slice(this.offset,this.offset+e);return this.offset+=e,t}catch(e){throw new Error(`UnpackException raw ${e&&e.message}`)}}popByte(){try{var e=this.view.getUint8(this.offset);return this.offset+=1,e}catch(e){throw new Error(`UnpackException byte ${e&&e.message}`)}}popVarbin(){return this.popRaw(this.popVarInt())}popString(){try{return decodeText(this.popVarbin())}catch(e){throw new Error(`UnpackException string ${e&&e.message}`)}}popInt(){try{var e=this.view.getUint32(this.offset,!0);return this.offset+=4,e}catch(e){throw new Error(`UnpackException int ${e&&e.message}`)}}popVarInt(){var e=1,t=0,r=0,i=0;do{if(t+=(127&(r=this.popByte()))*e,e*=128,(i+=1)>5)throw new Error("Variable length quantity is too long")}while(0!=(128&r));return t}popLong(){try{var e=function getBigUint64(e,t=!1){var r=new DataView(e.buffer),[i,o]=t?[4,0]:[0,4],n=r.getUint32(i,t),s=r.getUint32(o,t);return n>0?n*Oe+s:s}(this.buffer.slice(this.offset,this.offset+8),!0);return this.offset+=8,Number(e)}catch(e){throw new Error(`UnpackException long ${e&&e.message}`)}}popShort(){try{var e=this.view.getUint16(this.offset,!0);return this.offset+=2,e}catch(e){throw new Error(`UnpackException short ${e&&e.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(e){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(e)}reset(){this.innerHeader=null,this.bodyArr=[],this.unpack.reset()}getBodyDetail(){return this.bodyArr.join("")}unmarshalHeader(){var e=this._unmarshalHeader();this.packetLength=e.packetLength,this.serviceId=e.serviceId,this.commandId=e.commandId,this.serialId=e.serialId,this.tag=e.tag,this.resCode=e.resCode,4===e.serviceId&&[1,2,10,11].includes(e.commandId)&&(this.msgId=this.unmarshalLong(),this.innerHeader=this._unmarshalHeader())}_unmarshalHeader(){var e=this.unpack.popVarInt(),t=this.unpack.popByte(),r=this.unpack.popByte(),i=this.unpack.popShort(),o=this.unpack.popByte(),n=200;return this.hasRescode(o)&&(n=this.unpack.popShort()),{packetLength:e,serviceId:t,commandId:r,serialId:i,tag:o,resCode:n}}hasRescode(e){return 0!=((e=e||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 e=this.unpack.popVarInt(),t={};this.bodyArr.push(`\nProperty(${e}) {`);for(var r=0;r<e;r++){var i=this.unpack.popVarInt();this.bodyArr.push(`${i}:`);var o=this.unpack.popString();this.bodyArr.push(`"${o.length} ${this.unpack.getOffset()}",`),t[i]=o}return this.bodyArr.push("},"),t}unmarshalPropertyArray(){var e=this.unpack.popVarInt(),t=[];this.bodyArr.push(`\nPropertyArray(${e}) [`);for(var r=0;r<e;r++)t.push(this.unmarshalProperty());return this.bodyArr.push("],"),t}unmarshalLong(){var e=this.unpack.popLong();return this.bodyArr.push(`\nLong:${e}`),e}unmarshalLongArray(){var e=this.unpack.popVarInt(),t=[];this.bodyArr.push(`\nLongArray ${e}:`);for(var r=0;r<e;r++){var i=this.unpack.popLong();this.bodyArr.push(`${i},`),t.push(i)}return t}unmarshalStrArray(){var e=this.unpack.popVarInt(),t=[];this.bodyArr.push(`\nStrArray ${e}:`);for(var r=0;r<e;r++){var i=this.unpack.popString();this.bodyArr.push(`${i},`),t.push(i)}return t}unmarshalStrLongMap(){var e=this.unpack.popVarInt(),t={};this.bodyArr.push(`\nStrLongMap ${e}:`);for(var r=0;r<e;r++){var i=this.unpack.popString();this.bodyArr.push(`${i},`);var o=this.unpack.popLong();this.bodyArr.push(`${o};`),t[i]=o}return t}unmarshalStrStrMap(){var e=this.unpack.popVarInt(),t={};this.bodyArr.push(`\nStrStrMap ${e}:`);for(var r=0;r<e;r++){var i=this.unpack.popString();this.bodyArr.push(`${i},`);var o=this.unpack.popString();this.bodyArr.push(`${o};`),t[i]=o}return t}unmarshalLongLongMap(){var e=this.unpack.popVarInt(),t={};this.bodyArr.push(`\nStrLongLongMap ${e}:`);for(var r=0;r<e;r++){var i=this.unpack.popLong();this.bodyArr.push(`${i},`);var o=this.unpack.popLong();this.bodyArr.push(`${o};`),t[i]=o}return{m_map:t}}unmarshalKVArray(){var e=this.unpack.popVarInt(),t=[];this.bodyArr.push(`\nKVArray ${e}:`);for(var r=0;r<e;r++)t.push(this.unmarshalStrStrMap());return t}unmarshal(e){var t=Object.assign(Object.assign({},this.getHeader()),{r:[]});if(this.innerHeader&&(t.r[0]=this.msgId,t.r[1]={body:[],headerPacket:this.getInnerHeader()}),![200,406,808,810,7101].includes(t.code))return JSON.stringify(t);if(this.packetLength>0&&this.packetLength>this.unpack.length())throw new Error(`UnpackException packetLength(${this.packetLength}) greater than bufferLength(${this.unpack.length()})`);var r=[];return e&&e.forEach((e=>{if(!this.unpack.checkBufferBoundaryAccess())switch(e.type){case"PropertyArray":r.push(this.unmarshalPropertyArray());break;case"Property":r.push(this.unmarshalProperty());break;case"Byte":r.push(this.unpack.popByte());break;case"Int":r.push(this.unpack.popInt());break;case"Bool":r.push(this.unpack.popBoolean());break;case"Long":r.push(this.unmarshalLong());break;case"LongArray":r.push(this.unmarshalLongArray());break;case"String":r.push(this.unpack.popString());break;case"StrArray":r.push(this.unmarshalStrArray());break;case"StrStrMap":r.push(this.unmarshalStrStrMap());break;case"StrLongMap":r.push(this.unmarshalStrLongMap());break;case"LongLongMap":r.push(this.unmarshalLongLongMap());break;case"KVArray":r.push(this.unmarshalKVArray())}})),this.innerHeader?t.r[1].body=r:t.r=r,JSON.stringify(t)}}PacketDecoder.RES_CODE=2;class PromiseManager{constructor(){this.abortFns=[]}add(e){var t=function getPromiseWithAbort(e){var t={},r=new Promise((function(e,r){t.abort=r}));return t.promise=Promise.race([e,r]),t}(e);return this.abortFns.push(t.abort),t.promise}clear(e){this.abortFns.forEach((t=>t(e||new V2NIMErrorImpl({code:de.V2NIM_ERROR_CODE_CANCELLED,detail:{reason:"Aborted"}})))),this.abortFns=[]}destroy(){this.clear()}}var Me={tolerantRTT:3e3,bestRTT:100,maxChances:5,enable:!0},fe={timestamp:0,rtt:0,baseClock:0,baseTime:0};class TimeOrigin{constructor(e,t,r="getServerTime"){this.serverOrigin=fe,this.config=Me,this.isSettingNTP=!1,this.currentChance=0,this.failedDelay=2e3,this.successDelay=3e5,this.timer=0,this.cmdName="getServerTime",this.core=e,this.logger=e.logger,this.promiseManager=new PromiseManager,this.cmdName=r,t&&this.setOptions(t)}setOptions(e){this.config=Object.assign({},Me,this.config,e)}reset(){this.timer&&clearTimeout(this.timer),this.promiseManager.clear(),this.serverOrigin=fe,this.currentChance=0}setOriginTimetick(){return __awaiter(this,void 0,void 0,(function*(){if(this.config.enable&&!(this.isSettingNTP||this.currentChance>=this.config.maxChances)){var e=get(this.core,"auth.status"),t=get(this.core,"status"),r=get(this.core,"V2NIMLoginService.lifeCycle.loginStatus");if("logined"===e||"logined"===t||1===r){this.isSettingNTP=!0,this.currentChance++,this.timer&&clearTimeout(this.timer),this.timer=0;var i,o="TimeOrigin::setOriginTimetick:",n=Date.now();this.core.logger.debug(`${o} getServerTime start, times ${this.currentChance}`);try{i=get(yield this.promiseManager.add(this.core.sendCmd(this.cmdName)),"content.time"),this.isSettingNTP=!1}catch(e){var s=e;return this.isSettingNTP=!1,this.logger.warn(`${o} Calculate Delay time, getServerTime error`,s),void(s.code!==de.V2NIM_ERROR_CODE_CANCELLED&&(clearTimeout(this.timer),this.timer=setTimeout(this.setOriginTimetick.bind(this),this.failedDelay)))}if(!i)return this.core.logger.warn(`${o} Calculate Delay time incorrect format`),void(this.config.enable=!1);var a=Date.now()-n;this.doSet(i,a)}}}))}doSet(e,t){var r="TimeOrigin::setOriginTimetick:";t>this.config.tolerantRTT?(this.logger.warn(`${r} denied RTT:${t}`),clearTimeout(this.timer),this.timer=setTimeout(this.setOriginTimetick.bind(this),this.failedDelay)):t>this.config.bestRTT?(this.serverOrigin.rtt&&t>=this.serverOrigin.rtt?this.logger.warn(`${r} ignore RTT:${t}`):(this.setServerOrigin(t,e),this.logger.log(`${r} accept reluctantly RTT:${t}`)),clearTimeout(this.timer),this.timer=setTimeout(this.setOriginTimetick.bind(this),this.failedDelay)):(this.setServerOrigin(t,e),this.logger.debug(`${r} accept best RTT:${t}`),this.currentChance=0,clearTimeout(this.timer),this.timer=setTimeout(this.setOriginTimetick.bind(this),this.successDelay))}getNTPTime(e){if(void 0===e&&(e=this.getTimeNode()),this.checkNodeReliable(e)){var t=Math.floor(e.time-this.serverOrigin.baseTime);return this.serverOrigin.timestamp+t}return Date.now()}checkNodeReliable(e){if(void 0===e&&(e=this.getTimeNode()),this.serverOrigin.timestamp){if(0===this.serverOrigin.baseClock)return!0;var t=e.clock-this.serverOrigin.baseClock,r=e.time-this.serverOrigin.baseTime;return Math.abs(r-t)<500}return!1}checkPerformance(){return"BROWSER"===ce.platform&&!("undefined"==typeof performance||!performance.now)}static checkPerformance(){return"BROWSER"===ce.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(e,t){this.serverOrigin={timestamp:t+Math.floor(e/2),rtt:e,baseClock:this.checkPerformance()?performance.now():0,baseTime:Date.now()}}}var Se={},Re={};function createCmd(e,t,r,i){var o=Se[e];if(!o)return r.error("createCmd:: can not find cmd config: ",e),null;var n={SER:t,SID:o.sid,CID:o.cid,Q:[]};return o.params&&i&&o.params.forEach((function(e){var t=i[e.name];if(null!=t){var r=e.type,{reflectMapper:o,select:s}=e;switch(e.type){case"PropertyArray":r="ArrayMable",t=t.map((e=>({t:"Property",v:o?serialize(e,o,s):e})));break;case"Property":t=o?serialize(t,o,s):t;break;case"Bool":t=t?"true":"false"}n.Q.push({t:r,v:t})}})),{packet:n,hasPacketResponse:"boolean"!=typeof o.hasPacketResponse||o.hasPacketResponse,hasPacketTimer:"boolean"!=typeof o.hasPacketTimer||o.hasPacketTimer}}function parseCmd(e,t){var r;try{r=JSON.parse(e)}catch(r){return void t.error(`Parse command error:"${e}"`)}var i=r.sid+"_"+r.cid,o=r.r;if(["4_1","4_2","4_10","4_11"].includes(i)){var n=r.r[1].headerPacket;i=`${n.sid}_${n.cid}`,r.sid=n.sid,r.cid=n.cid,o=r.r[1].body}var s=Re[i],a=[];if(s&&s.length>0){for(var c of s)a.push(parseEachCmd(r,c.config,c.cmd,o,t));return a}t.error("parseCmd:: mapper not exist",i,r.code)}function parseEachCmd(e,t,r,i,o){var n,s={cmd:r,raw:e,error:null,service:null==t?void 0:t.service,content:{},__receiveTimeNode:TimeOrigin.getTimeNode()};(function isV2Sid(e){return[18,19,26,27,28,29,30,31,32,33,34,35,36].includes(e)})(t.sid)&&(e.code=function toReadableCode(e){if("number"!=typeof e||e!=e)throw new V2NIMErrorImpl({code:de.V2NIM_ERROR_CODE_INTERNAL,detail:{reason:"Read code failed",rawData:`${e}`}});if(e<0||e>=0&&e<1e3||e>=2e4&&e<=20099)return e;var t=(65535&e)>>9;t-=t<=38?1:2;return 1e5+1e3*t+(511&e)}(e.code));var a=function genCmdError(e,t){var r=Ee[e],i=he[e];return null===i?null:new V2NIMErrorImpl({code:e,desc:r||i||e,detail:{cmd:t,timetag:Date.now()}})}(e.code,r);if(s.error=a,s.error){if(s.error.detail.cmd=r,!(null===(n=null==t?void 0:t.ignoreErrCodes)||void 0===n?void 0:n.includes(e.code)))return s;o.warn("parseCmd:: ignore error ",s.error),s.error.detail.ignore=!0}return t.response&&t.response.forEach(((e,t)=>{var r=i[t],o=e.type,n=e.name,a=e.reflectMapper;if(void 0!==r)switch(o){case"Property":s.content[n]=a?deserialize(r,a):r;break;case"PropertyArray":s.content[n]=r.map((e=>a?deserialize(e,a):e));break;case"Int":case"Long":case"Byte":s.content[n]=+r;break;case"Bool":s.content[n]="true"===r||!0===r||1===r;break;default:s.content[n]=r}})),s}function serialize(e,t,r){var i={};for(var o in e=function flattenObjByMapper(e,t){var r={};for(var i in t){var o=t[i],n="number"==typeof o?i:o.access?o.access:i,s=n.split("."),a=e;for(var c of s){if(void 0===a[c]||null===a[c]){a=void 0;break}a=a[c]}void 0!==a&&(r[n]=a)}return r}(e,t),t){var n=t[o],s="number"==typeof n?o:n.access?n.access:o;if(!r||r.includes(o))if(s in e){if("number"==typeof n)i[n]=e[s];else if("object"==typeof n)if(n.converter){var a=n.converter(e[s],e);void 0!==a&&(i[n.id]=a)}else i[n.id]=e[s]}else"object"==typeof n&&n.def&&("function"==typeof n.def?i[n.id]=n.def(e):i[n.id]=n.def)}return i}function deserialize(e,t){var r={};for(var i in e){var o=t[i];if("string"==typeof o)r[o]=e[i];else if("object"==typeof o&&"prop"in o){var n=o.access?o.access:o.prop;if(o.converter){var s=o.converter(e[i],e);void 0!==s&&(r[n]=s)}else o.type&&"number"===o.type?r[n]=+e[i]:o.type&&"boolean"===o.type?r[n]=!("0"===e[i]||!e[i]):r[n]=e[i]}}for(var a in t){var c=t[a];if(c&&void 0!==c.def){var _=c.access?c.access:c.prop;_ in r||("function"==typeof c.def?r[_]=c.def(e):r[_]=c.def)}}return r=function unflattenObj(e){var t={},_loop=function(r){var i=r.split(".");i.reduce((function(t,o,n){return t[o]||(t[o]=isNaN(Number(i[n+1]))?i.length-1==n?e[r]:{}:[])}),t)};for(var r in e)_loop(r);return t}(r),r}function registerParser(e){for(var t in Object.assign(Se,e.cmdConfig),e.cmdMap){var r=e.cmdMap[t],i=e.cmdConfig[r];if(i)if(Array.isArray(Re[t])){var o=!1;for(var n of Re[t])if(n.cmd===r&&n.config.service===i.service){o=!0;break}o||Re[t].push({config:i,cmd:r})}else Re[t]=[{config:i,cmd:r}]}}function invertSerializeItem(e){var t={};for(var r in e){var i=e[r];"number"==typeof i?t[i]=r:"object"==typeof i&&(t[i.id]={prop:r,type:i.retType,access:i.retAccess?i.retAccess:i.access?i.access:r,def:i.retDef,converter:i.retConverter})}return t}function boolToInt(e){return e?1:0}function objectToJSONString(e){if(e&&"object"==typeof e)try{return JSON.stringify(e)}catch(e){return}}function stringToJSONObject(e){if(e&&"string"==typeof e)try{return JSON.parse(e)}catch(e){return}}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(e){var t=this.offset+e;if(t>this.capacity)throw new Error("PackException over limit");if(t>this.buffer.byteLength){var r=Math.ceil(t/this.pageSize)*this.pageSize,i=new Uint8Array(r);i.set(this.buffer),this.buffer=i,this.view=new DataView(this.buffer.buffer)}}putRaw(e){this.ensureCapacity(e.length);try{this.buffer.set(e,this.offset),this.offset+=e.length}catch(e){throw new Error("PackException raw")}}putByte(e){this.ensureCapacity(1);try{this.view.setUint8(this.offset++,e)}catch(e){throw new Error("PackException byte")}}putString(e){try{var t=function encodeText(e){if("function"==typeof TextEncoder)return(new TextEncoder).encode(e);var t=function textEncoder(e){for(var t=[],r=e.length,i=0;i<r;){var o=e.codePointAt(i),n=0,s=0;for(o<=127?(n=0,s=0):o<=2047?(n=6,s=192):o<=65535?(n=12,s=224):o<=2097151&&(n=18,s=240),t.push(s|o>>n),n-=6;n>=0;)t.push(128|o>>n&63),n-=6;i+=o>=65536?2:1}return t}(e);return new Uint8Array(t)}(e);this.putVarbin(t)}catch(e){throw new Error("PackException string")}}putInt(e){this.ensureCapacity(4);try{this.view.setInt32(this.offset,e,!0),this.offset+=4}catch(e){throw new Error("PackException int")}}putVarInt(e){var t=varintToBytes(e);this.putRaw(t)}putBoolean(e){this.ensureCapacity(1);try{this.view.setUint8(this.offset++,e?1:0)}catch(e){throw new Error("PackException boolean")}}putLong(e){this.ensureCapacity(8);try{var t=function setBigUint64(e,t=!1){var r=new Uint8Array(8),i=new DataView(r.buffer),o=Number(e>Oe-1?e/Oe:0),n=Number(4294967295&e),[s,a]=t?[4,0]:[0,4];return i.setUint32(s,o,t),i.setUint32(a,n,t),r}(e,!0);this.buffer.set(t,this.offset),this.offset+=8}catch(e){throw new Error("PackException long")}}putStringAsLong(e){this.ensureCapacity(8);try{var t=function setBigUint64ForNumberOverflow(e,t=!1){var r=new Uint8Array(8),i=new DataView(r.buffer),o=BigNumber(e).divide(Oe).number.reverse().join(""),n=BigNumber(e).mod(Oe).number.reverse().join(""),s=Number(o),a=Number(n),[c,_]=t?[4,0]:[0,4];return i.setUint32(c,s,t),i.setUint32(_,a,t),r}(e,!0);this.buffer.set(t,this.offset),this.offset+=8}catch(e){throw new Error("PackException stringAsLong")}}putShort(e){this.ensureCapacity(2);try{this.view.setInt16(this.offset,e,!0),this.offset+=2}catch(e){throw new Error("PackException short")}}putVarbin(e){if(!e)return this.ensureCapacity(1),this.putVarInt(0);if(e.byteLength>Math.pow(2,31)-2)throw new Error("PackException varbin. too long");var t=varintToBytes(e.length);this.ensureCapacity(t.length+e.length);try{this.buffer.set(t,this.offset),this.offset+=t.length,this.buffer.set(e,this.offset),this.offset+=e.length}catch(e){throw new Error("PackException varbin")}}}function isConvertibleToNumber(e){if("number"!=typeof e){if(null==e)return!1;e=Number(e)}if(isNaN(e))throw new Error("Number type conversion error");return!0}function isUndefinedOrNull(e){return null==e}class PacketEncoder{constructor(e,t,r){this.pack=new Pack,this.packetLength=0,this.serviceId=0,this.commandId=0,this.serialId=0,this.tag=0,this.serviceId=e,this.commandId=t,this.serialId=r}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(e){var t=Object.keys(e).filter((e=>!isUndefinedOrNull(e)));this.pack.putVarInt(t.length),t.forEach((t=>{this.pack.putVarInt(Number(t)),Array.isArray(e[t])||"[object Object]"===Object.prototype.toString.call(e[t])?this.pack.putString(JSON.stringify(e[t])):this.pack.putString(String(e[t]))}))}marshalPropertyArray(e){var t=e.length;this.pack.putVarInt(t),e.forEach((e=>{this.marshalProperty(null==e?void 0:e.v)}))}marshalStrArray(e){var t=e.filter((e=>!isUndefinedOrNull(e))),r=t.length;this.pack.putVarInt(r),t.forEach((e=>{this.pack.putString(String(e))}))}marshalLongArray(e){var t=e.filter((e=>isConvertibleToNumber(e))),r=t.length;this.pack.putVarInt(r),t.forEach((e=>{this.putLong(e)}))}marshalStrStrMap(e){var t=Object.keys(e).filter((t=>!isUndefinedOrNull(e[t])&&!isUndefinedOrNull(t)));this.pack.putVarInt(t.length),t.forEach((t=>{this.pack.putString(String(t)),this.pack.putString(String(e[t]))}))}marshalStrLongMap(e){var t=Object.keys(e).filter((t=>isConvertibleToNumber(e[t])&&!isUndefinedOrNull(t)));this.pack.putVarInt(t.length),t.forEach((t=>{this.pack.putString(String(t)),this.putLong(e[t])}))}marshalLongLongMap(e){var t=Object.keys(e).filter((t=>{var r=Number(t);return isConvertibleToNumber(r)&&isConvertibleToNumber(e[r])}));this.pack.putVarInt(t.length),t.forEach((t=>{var r=Number(t);this.putLong(r),this.putLong(e[r])}))}marshalKVArray(e){var t=e.length;this.pack.putVarInt(t),e.forEach((e=>{this.marshalStrStrMap(e)}))}putLong(e){"string"==typeof e&&e.length>15?this.pack.putStringAsLong(e):this.pack.putLong(Number(e))}marshal(e,t){return this.marshalHeader(),t&&t.forEach(((t,r)=>{var i,o=t.type,n=null===(i=e[r])||void 0===i?void 0:i.v;if(!isUndefinedOrNull(n))switch(o){case"PropertyArray":this.marshalPropertyArray(n);break;case"Property":this.marshalProperty(n);break;case"Byte":if(!isConvertibleToNumber(n))return;this.pack.putByte(Number(n));break;case"Int":if(!isConvertibleToNumber(n))return;this.pack.putInt(Number(n));break;case"Bool":"false"===n?n=!1:"true"===n&&(n=!0),this.pack.putBoolean(n);break;case"Long":if(!isConvertibleToNumber(n))return;this.putLong(n);break;case"LongArray":this.marshalLongArray(n);break;case"String":this.pack.putString(String(n));break;case"StrArray":this.marshalStrArray(n);break;case"StrStrMap":this.marshalStrStrMap(n);break;case"StrLongMap":this.marshalStrLongMap(n);break;case"LongLongMap":this.marshalLongLongMap(n);break;case"KVArray":this.marshalKVArray(n)}})),this.pack.getBuffer()}reset(){this.pack.reset()}}var Ae,Ce,ve=(Ae=function(){return(65536*(1+Math.random())|0).toString(16).substring(1)},function(){return Ae()+Ae()+Ae()+Ae()+Ae()+Ae()+Ae()+Ae()});function assignOptions(e,t){return function assignWith(e,t,r,i){for(var o in e=e||{},r=r||{},i=i||(()=>{}),t=t||{}){var n=i(e[o],t[o]);e[o]=void 0===n?t[o]:n}for(var s in r){var a=i(e[s],r[s]);e[s]=void 0===a?r[s]:a}return e}({},e,t,(function(e,t){return void 0===t?e:t}))}function getFileExtension(e){var t=e.lastIndexOf("."),r=t>-1?e.slice(t+1):"";return/^\d+$/.test(r.trim())&&(r=""),r}class BaseWebsocket$1 extends Ie{constructor(e,t,r){super(),this.websocket=null,this.socketConnectTimer=0,this.linkSSL=!0,this.url="",this.core=e,this.url=t,this.linkSSL=r,this.status="disconnected",this.logger=e.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(e){this.logger.warn("imsocket::attempt to close websocket error",e)}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(e){this.socketConnectTimer=setTimeout((()=>{this.logger.error("imsocket::Websocket connect timeout. url: ",e),this.emit("connectFailed",new V2NIMErrorImpl({code:"v2"===get(this.core,"options.apiVersion")?de.V2NIM_ERROR_CODE_CONNECT_TIMEOUT:415,detail:{reason:`imsocket::Websocket connect timeout. url: ${e}`}}))}),this.core.options.socketConnectTimeout||8e3),this.socketUrl=e,this.websocket=new ce.WebSocket(e),this.websocket.binaryType="arraybuffer",this.websocket.onmessage=this.onMessage.bind(this),this.websocket.onclose=e=>{e=e||{},this.logger.log(`imsocket::Websocket onclose done ${e.wasClean}/${e.code}/${e.reason}`),"connected"===this.status?(this.clean(),this.emit("disconnect")):(this.clean(),this.emit("connectFailed",new V2NIMErrorImpl({code:"v2"===get(this.core,"options.apiVersion")?de.V2NIM_ERROR_CODE_CONNECT_FAILED:414,detail:{reason:"imsocket::Websocket onclose done"}})))},this.websocket.onerror=e=>{this.logger.error("imsocket::Websocket onerror",e),"connected"===this.status?(this.clean(),this.emit("disconnect")):(this.clean(),this.emit("connectFailed",new V2NIMErrorImpl({code:"v2"===get(this.core,"options.apiVersion")?de.V2NIM_ERROR_CODE_CONNECT_FAILED:414,detail:{reason:"imsocket::Websocket onerror."}})))},this.websocket.onopen=()=>{this.onConnect()}}onMessage(e){if(e.data){var t=new PacketDecoder(e.data),r={sid:-1,cid:-1,ser:-1,packetLength:-1},i=null;try{t.unmarshalHeader(),r=t.getHeader(),i=t.getInnerHeader()}catch(t){this.reportBinaryError({err:t,sid:i?i.sid:null==r?void 0:r.sid,cid:i?i.cid:null==r?void 0:r.cid,rawBuf:e.data,type:"decode"})}var o=i?i.sid:r.sid,n=i?i.cid:r.cid,s=`${o}_${n}`,a=Re[s];if(a&&a.length>0){var c,_=a[0].config;try{c=t.unmarshal(_.response)}catch(i){var l=t.getBodyDetail();this.reportBinaryError({err:i,rawBuf:e.data,sid:o,cid:n,parseDetail:l,type:"decode"}),t.reset();var d=Object.assign(Object.assign({},r),{sid:o,cid:n,code:de.V2NIM_ERROR_CODE_UNPACK_ERROR});return this.logger.error(`imsocket::onMessage "${d.sid}_${d.cid}", ser ${d.ser}, packetLength ${d.packetLength} unmarshal error. ${l} \n`,i),void this.emit("message",JSON.stringify(d))}this.emit("message",c)}else this.core.logger.warn("imsocket::onMessage cmd not found",s);t.reset()}}send(e,t,r,i,o){var n,s,a=new PacketEncoder(e,t,r),c=Se[i],_="";try{_=JSON.stringify(o),s=a.marshal(JSON.parse(_),c.params)}catch(i){throw this.reportBinaryError({err:i,sid:e,cid:t,rawStr:_,type:"encode"}),a.reset(),new V2NIMErrorImpl({code:de.V2NIM_ERROR_CODE_PACK_ERROR,detail:{reason:`${e}-${t}, ser ${r} marshal error`,rawError:i}})}null===(n=this.websocket)||void 0===n||n.send(s),a.reset()}reportBinaryError(e){var t,r,i,{err:o,rawStr:n,sid:s,cid:a,type:c,parseDetail:_}=e,l=e.rawBuf;if(l){try{i=function arrayBufferToBase64(e){if("function"!=typeof btoa)return"";for(var t="",r=new Uint8Array(e),i=r.byteLength,o=0;o<i;o++)t+=String.fromCharCode(r[o]);return r=null,btoa(t)}(l)}catch(e){i=`reportBinaryError::arrayBufferToBase64 parsing failed, error: ${null==e?void 0:e.message}, sid: ${s}, cid: ${a}`,this.core.logger.error(i)}l=null}this.core.reporter.reportTraceStart("exceptions",{user_id:null===(t=this.core.auth)||void 0===t?void 0:t.account,trace_id:null===(r=this.core.clientSocket.socket)||void 0===r?void 0:r.sessionId,start_time:Date.now(),action:2,exception_service:9});var d=o?(`${o.message};;;`||`${o.code};;;`)+(_?`parseDetail: ${_};;;`:"")+(n?` rawStr: ${n}`:"")+(i?` rawBuf: ${i}`:""):"";this.core.reporter.reportTraceUpdateV2("exceptions",{code:"encode"===c?de.V2NIM_ERROR_CODE_PACK_ERROR:de.V2NIM_ERROR_CODE_UNPACK_ERROR,description:d,operation_type:"encode"===c?3:4,target:`${s}-${a}`},{asyncParams:ce.net.getNetworkStatus()}),this.core.reporter.reportTraceEnd("exceptions",1)}}!function(e){e[e.ACTIVE=1]="ACTIVE",e[e.KICKED=2]="KICKED",e[e.OFFLINE=3]="OFFLINE"}(Ce||(Ce={}));class V2BinaryClientSocket{constructor(e){this.isReconnect=!1,this.packetTimeout=8e3,this.linkSSL=!0,this.packetSer=1,this.backoff=new Backoff({max:8e3,min:1600,jitter:.01}),this.sendingCmdMap=new Map,this.pingTimer=0,this.hasNetworkListener=!1,this.core=e,this.auth=e.auth,this.logger=e.logger,this.reporter=e.reporter,this.timerManager=e.timerManager,this.eventBus=e.eventBus,this.setListener()}setListener(){this.core.eventBus.on("V2NIMLoginService/loginLifeCycleLoginSucc",(()=>{this.isReconnect=!0}))}setSessionId(e){this.socket&&(this.socket.sessionId=e)}setLinkSSL(e){this.linkSSL=e}connect(e,t=!1){var r,i;return __awaiter(this,void 0,void 0,(function*(){this.isReconnect=t;var o=this.core.auth.getConnectStatus();if(1===o){var n=`clientSocket::connect status is ${o}, and would not repeat connect`,s=new V2NIMErrorImpl({code:de.V2NIM_ERROR_CODE_ILLEGAL_STATE,detail:{reason:n}});return this.logger.warn(n),Promise.reject(s)}this.auth.lifeCycle.processEvent("connect");try{yield this.auth.doLoginStepsManager.add(this.doConnect(e)),this.logger.log(`clientSocketV2:: connect success with link url: ${e}, isReconnect: ${t}`),this.core.reporter.reportTraceUpdateV2("login",{operation_type:"TCP",target:e,code:200,mixlink:!0,succeed:!0},{asyncParams:ce.net.getNetworkStatus()}),this.auth.lifeCycle.processEvent("connectSucc")}catch(t){var a=t;if(this.core.reporter.reportTraceUpdateV2("login",{operation_type:"TCP",target:e,code:a.code||0,description:`connectFailed:${a.message}`,mixlink:!0,succeed:!1},{asyncParams:ce.net.getNetworkStatus()}),a.code===de.V2NIM_ERROR_CODE_CANCELLED||a.code===de.V2NIM_ERROR_CODE_TIMEOUT)throw null===(r=this.socket)||void 0===r||r.close(),null===(i=this.socket)||void 0===i||i.removeAllListeners(),this.socket=void 0,t;throw this.logger.warn(`clientSocketV2::connect failed with link url: ${e}`,a),this.auth.lifeCycle.processEvent("connectFail",a),t}}))}doConnect(e){var t=!1;return new Promise(((r,i)=>{this.socket=new BaseWebsocket$1(this.core,e,this.linkSSL),this.socket.on("connect",(()=>{this.logger.log("clientSocketV2::socket on connect",e),this.core.reporterHookLinkKeep.start(),this.core.reporterHookLinkKeep.update({code:0,description:"connection begin",operation_type:0,target:e}),t=!0,r()})),this.socket.on("message",this.onMessage.bind(this)),this.socket.on("disconnect",(r=>__awaiter(this,void 0,void 0,(function*(){t=!0,this.logger.log(`clientSocketV2::socket on disconnect ${e}`,r),yield this.core.reporterHookLinkKeep.update({code:(null==r?void 0:r.code)||0,description:(null==r?void 0:r.reason)||"socket on disconnect",operation_type:1,target:e}),this.core.reporterHookLinkKeep.end(!1),this.doDisconnect(Ce.OFFLINE,"SocketOnDisconnect")})))),this.socket.on("connectFailed",(r=>{t?this.ping():(this.logger.error(`clientSocketV2::connectFailed:${e}, reason:${r&&r.message}`),this.cleanSocket()),t=!0,i(r)}))}))}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(e,t){if(this.logger.log(`clientSocketV2::doDisconnect:type:${e},reason:`,t),0!==this.core.auth.getConnectStatus()){var r={1:"close",2:"kicked",3:"broken"}[e]||"";this.markAllCmdInvaild(new V2NIMErrorImpl({code:de.V2NIM_ERROR_CODE_DISCONNECT,detail:{reason:"Packet timeout due to instance disconnect",disconnect_reason:r}})),this.timerManager.destroy(),clearTimeout(this.pingTimer),this.cleanSocket(),e===Ce.ACTIVE||e===Ce.KICKED?this.destroyOnlineListener():e===Ce.OFFLINE&&(this.auth.lifeCycle.processEvent("connectionBroken",new V2NIMErrorImpl({code:de.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(e,t,r){var i=this.core.auth.getLoginStatus(),o={cmd:e};if(1!==i&&!["v2Login","login","chatroomLogin","v2ChatroomLogin"].includes(e))return this.logger.warn(`clientSocketV2::NIM login status is ${i}, so can not sendCmd ${e}`),Promise.reject(new V2NIMErrorImpl({code:de.V2NIM_ERROR_CODE_ILLEGAL_STATE,detail:Object.assign({reason:"Can not sendCmd due to no logined"},o)}));var n="heartbeat"!==e,s=n?this.packetSer++:0,a=createCmd(e,s,this.logger,t);if(!a){var c=new V2NIMErrorImpl({code:de.V2NIM_ERROR_CODE_INTERNAL,detail:Object.assign(Object.assign({},o),{reason:`SendCmd::createCmd error: ${s} ${e}`})});return this.logger.error(c),Promise.reject(c)}var{packet:_,hasPacketResponse:l,hasPacketTimer:d}=a,E=JSON.stringify(_);n&&(this.logger.getDebugMode()?this.logger.debug(`clientSocketV2::sendCmd: ${_.SID}_${_.CID},${e},ser:${s}`,E):this.logger.log(`clientSocketV2::sendCmd: ${_.SID}_${_.CID},${e},ser:${s}`));var h=(new Date).getTime();return new Promise(((i,n)=>{l&&this.sendingCmdMap.set(s,{cmd:e,params:t,callback:[i,n],timer:d?setTimeout((()=>{var t=new V2NIMErrorImpl({code:de.V2NIM_ERROR_CODE_PROTOCOL_TIMEOUT,detail:Object.assign({ser:s,reason:`Packet Timeout: ser ${s} cmd ${e}`,timetag:(new Date).getTime()},o)});this.markCmdInvalid(s,t,e)}),r&&r.timeout?r.timeout:this.packetTimeout):null});try{this.socket.send(_.SID,_.CID,s,e,_.Q),l||i(_)}catch(t){var a=new V2NIMErrorImpl({code:de.V2NIM_ERROR_CODE_PROTOCOL_SEND_FAILED,detail:Object.assign({ser:s,reason:"Unable to send packet"+(t&&t.message?": "+t.message:""),timetag:(new Date).getTime(),rawError:t},o)});this.markCmdInvalid(s,a,e),n(a)}})).catch((e=>__awaiter(this,void 0,void 0,(function*(){var t=e;return[de.V2NIM_ERROR_CODE_DISCONNECT,de.V2NIM_ERROR_CODE_PROTOCOL_TIMEOUT,de.V2NIM_ERROR_CODE_PROTOCOL_SEND_FAILED].includes(t.code)?(this.reportSendCmdFailed(t,{sid:_.SID,cid:_.CID,ser:s},h),Promise.reject(t)):Promise.reject(t)}))))}reportSendCmdFailed(e,t,r){var i;this.reporter.reportTraceStart("exceptions",{user_id:this.core.auth.getLoginUser(),trace_id:null===(i=this.socket)||void 0===i?void 0:i.sessionId,start_time:r,action:2,exception_service:6});var o=get(e,"detail.disconnect_reason")||"",n=e.code===de.V2NIM_ERROR_CODE_DISCONNECT?JSON.stringify({disconnect_reason:o}):e.detail.reason;this.reporter.reportTraceUpdateV2("exceptions",{code:e.code,description:n,operation_type:1,target:`${t.sid}-${t.cid}`,context:`${t.ser}`},{asyncParams:ce.net.getNetworkStatus()}),this.reporter.reportTraceEnd("exceptions",1)}onMessage(e){var t=parseCmd(e,this.logger);if(t&&t.length>0){var r=t[0],i=r.raw.ser;for(var o of(r.error&&(this.logger.error("clientSocketV2::onMessage packet error",`${r.raw.sid}_${r.raw.cid}, ser:${i},`,r.error),r.error.code===de.V2NIM_ERROR_CODE_UNPACK_ERROR&&this.core.eventBus.emit("BinaryClientSocket/unpackError")),"heartbeat"!==r.cmd&&(this.logger.getDebugMode()?this.logger.debug(`clientSocketV2::recvCmd ${r.raw.sid}_${r.raw.cid},${r.cmd},ser:${i}`,e):this.logger.log(`clientSocketV2::recvCmd ${r.raw.sid}_${r.raw.cid},${r.cmd},ser:${i},code:${r.raw.code}`)),t))this.packetHandler(o)}}packetHandler(e){var t,r,i,o;if(e){var n=e.raw.ser,s=this.sendingCmdMap.get(n);if(s&&s.cmd===e.cmd){var{callback:a,timer:c,params:_}=s;if(clearTimeout(c),e.params=_,this.sendingCmdMap.delete(n),"heartbeat"===e.cmd)return void a[0]();var l=null===(r=null===(t=this.core[e.service])||void 0===t?void 0:t.process)||void 0===r?void 0:r.call(t,e);l&&"function"==typeof l.then?l.then((e=>{a[0](e)})).catch((e=>{a[1](e)})):(this.logger.log("clientSocketV2::handlerFn without promise",e.service,e.cmd),a[0](e))}else{var d=null===(o=null===(i=this.core[e.service])||void 0===i?void 0:i.process)||void 0===o?void 0:o.call(i,e);d&&"function"==typeof d.then&&d.catch((e=>{this.logger.error("clientSocketV2::no obj cache, no process handler",e)}))}}}markCmdInvalid(e,t,r){var i=this.sendingCmdMap.get(e);if(i){var{callback:o,timer:n}=i;n&&clearTimeout(n),this.sendingCmdMap.delete(e),this.logger.warn(`clientSocketV2::packet ${e}, ${r} is invalid:`,t),o[1](t)}}markAllCmdInvaild(e){this.logger.log("markAllCmdInvaild",e),this.sendingCmdMap.forEach((t=>{var{callback:r,timer:i,cmd:o}=t;this.logger.log(`clientSocketV2::markAllCmdInvaild:cmd ${o}`),i&&clearTimeout(i),r[1](e)})),this.sendingCmdMap.clear()}ping(){var e;return __awaiter(this,void 0,void 0,(function*(){clearTimeout(this.pingTimer);try{yield this.sendCmd("heartbeat")}catch(t){if(t.code===de.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===(e=this.socket)||void 0===e?void 0:e.url}),this.core.reporterHookLinkKeep.end(!0),void this.doDisconnect(Ce.OFFLINE,"PingError")}this.pingTimer=setTimeout((()=>{this.ping()}),3e4)}))}testHeartBeat5Timeout(){return __awaiter(this,void 0,void 0,(function*(){clearTimeout(this.pingTimer);for(var e=0;e<5;e++)try{return yield this.sendCmd("heartbeat",{},{timeout:3e3}),!1}catch(t){this.logger.log(`clientSocketV2::test heartbeat ${e} Timeout`)}return!0}))}initOnlineListener(){this.hasNetworkListener||(this.logger.log("clientSocketV2::onlineListener:init"),this.hasNetworkListener=!0,ce.net.onNetworkStatusChange((e=>{this.logger.log("clientSocketV2::onlineListener:network change",e);var t=this.auth.getLoginStatus();e.isConnected&&1===t?this.ping():e.isConnected&&3===t?(this.logger.log("clientSocketV2::onlineListener:online and connectStatus is waiting, do reLogin"),this.auth.reconnect.clearReconnectTimer(),this.auth.reconnect.doReLogin()):e.isConnected||this.doDisconnect(Ce.OFFLINE,"OfflineListener")})))}destroyOnlineListener(){this.logger.log("clientSocketV2::onlineListener:destroy"),ce.net.offNetworkStatusChange(),this.hasNetworkListener=!1}}var ye,De=["disconnect","connect","heartbeat","message","json","event","ack","error","noop"],Ve=["transport not supported","client not handshaken","unauthorized"],Le=["reconnect"];class BaseWebsocket extends Ie{constructor(e,t,r){super(),this.websocket=null,this.socketConnectTimer=0,this.url="",this.linkSSL=!0,this.core=e,this.url=t,this.linkSSL=r,this.status="disconnected",this.logger=e.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((e=>{if("connecting"===this.status){var[t,r]=e.data.split(":");return this.sessionId=t,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/${t}`)}})).catch((e=>{if("connecting"===this.status){var t=`imsocket::XHR fail. raw message: "${(e=e||{}).message}", code: "${e.code}"`,r=e.code;r="v2"===get(this.core,"options.apiVersion")?e.code===de.V2NIM_ERROR_CODE_CONNECT_TIMEOUT?de.V2NIM_ERROR_CODE_CONNECT_TIMEOUT:de.V2NIM_ERROR_CODE_CONNECT_FAILED:408===e.code?408:415;var i=new V2NIMErrorImpl({code:r,detail:{reason:t,rawError:e}});this.logger.error(t),this.status="disconnected",this.emit("handshakeFailed",i)}}))):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(e){this.logger.warn("imsocket::attempt to send encodePacket error",e)}try{this.websocket.close()}catch(e){this.logger.warn("imsocket::attempt to close websocket error",e)}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(e){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")?de.V2NIM_ERROR_CODE_CONNECT_TIMEOUT:415,detail:{reason:`imsocket::Websocket connect timeout. url: ${this.socketUrl}`}}))}),this.core.options.socketConnectTimeout||8e3),this.socketUrl=e,this.websocket=new ce.WebSocket(e),this.websocket.onmessage=this.onMessage.bind(this),this.websocket.onclose=e=>{e=e||{},this.logger.log(`imsocket::Websocket onclose done ${e.wasClean}/${e.code}/${e.reason}`),this.clean(),this.emit("disconnect",{code:e.code||0,reason:e.reason})},this.websocket.onerror=e=>{this.logger.error("imsocket::Websocket onerror",e),"logined"===this.core.status&&this.core.clientSocket.ping()}}onMessage(e){var t,r=this.decodePacket(e.data);if(r)switch(r.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",r.data);break;case"event":r.name&&this.emit(r.name,r.args);break;case"error":"unauthorized"===r.reason?this.emit("connect_failed",r.reason):this.emit("error",r.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")?de.V2NIM_ERROR_CODE_CONNECT_FAILED:408,detail:{reason:`imsocket::Websocket connect failed, onMessage socket error. url: ${this.socketUrl}`}}));break;case"heartbeat":null===(t=this.websocket)||void 0===t||t.send(this.encodePacket({type:"heartbeat"}));break;default:this.logger.warn("imsocket::Websocket no handler type",r.type)}}encodePacket(e){var t,r,{type:i,id:o="",endpoint:n="",ack:s}=e,a=null;if(!i)return"";switch(i){case"error":t=e.reason?Ve.indexOf(e.reason):"",r=e.advice?Le.indexOf(e.advice):"",""===t&&""===r||(a=t+(""!==r?"+"+r:""));break;case"message":""!==e.data&&(a=e.data);break;case"event":t={name:e.name},t=e.args&&e.args.length?{name:e.name,args:e.args}:{name:e.name},a=JSON.stringify(t);break;case"json":a=JSON.stringify(e.data);break;case"connect":e.qs&&(a=e.qs);break;case"ack":a=e.ackId+(e.args&&e.args.length?"+"+JSON.stringify(e.args):"")}var c=[De.indexOf(i),o+("data"===s?"+":""),n];return null!=a&&c.push(a),c.join(":")}decodePacket(e){if(e)if("�"!=e.charAt(0)){var t=e.match(/([^:]+):([0-9]+)?(\+)?:([^:]+)?:?([\s\S]*)?/);if(t){var r,[,i,o,n,s,a]=t,c={type:De[+i],endpoint:s};switch(o&&(c.id=o,c.ack=!n||"data"),c.type){case"error":r=a.split("+"),c.reason=Ve[+r[0]]||"";break;case"message":c.data=a||"";break;case"connect":c.qs=a||"";break;case"event":try{var _=JSON.parse(a);c.name=_.name,c.args=_.args}catch(e){this.logger.error("imsocket::parseData::type::event error",e)}c.args=c.args||[];break;case"json":try{c.data=JSON.parse(a)}catch(e){this.logger.error("imsocket::parseData::type::json error",e)}break;case"ack":if((r=a.match(/^([0-9]+)(\+)?(.*)/))&&(c.ackId=r[1],c.args=[],r[3]))try{c.args=r[3]?JSON.parse(r[3]):[]}catch(e){this.logger.error("imsocket::parseData::type::ack error",e)}}return c}}else this.logger.error("imsocket::unrecognize dataStr",e.slice(0,20))}send(e){var t,r={data:e,type:"message",endpoint:""};null===(t=this.websocket)||void 0===t||t.send(this.encodePacket(r))}}!function(e){e[e.ACTIVE=1]="ACTIVE",e[e.KICKED=2]="KICKED",e[e.OFFLINE=3]="OFFLINE"}(ye||(ye={}));class V2ClientSocket{constructor(e){this.isReconnect=!1,this.packetTimeout=8e3,this.linkSSL=!0,this.packetSer=1,this.backoff=new Backoff({max:8e3,min:1600,jitter:.01}),this.sendingCmdMap=new Map,this.pingTimer=0,this.hasNetworkListener=!1,this.core=e,this.auth=e.auth,this.logger=e.logger,this.reporter=e.reporter,this.timerManager=e.timerManager,this.eventBus=e.eventBus,this.setListener()}setListener(){this.core.eventBus.on("V2NIMLoginService/loginLifeCycleLoginSucc",(()=>{this.isReconnect=!0}))}setSessionId(e){this.socket&&(this.socket.sessionId=e)}setLinkSSL(e){this.linkSSL=e}connect(e,t=!1){var r,i;return __awaiter(this,void 0,void 0,(function*(){this.isReconnect=t;var o=this.core.auth.getConnectStatus();if(1===o){var n=`clientSocket::connect status is ${o}, and would not repeat connect`,s=new V2NIMErrorImpl({code:de.V2NIM_ERROR_CODE_ILLEGAL_STATE,detail:{reason:n}});return this.logger.warn(n),Promise.reject(s)}this.auth.lifeCycle.processEvent("connect");try{yield this.auth.doLoginStepsManager.add(this.doConnect(e)),this.logger.log(`clientSocketV2:: connect success with link url: ${e}, isReconnect: ${t}`),this.core.reporter.reportTraceUpdateV2("login",{operation_type:"TCP",target:e,code:200,mixlink:!0,succeed:!0},{asyncParams:ce.net.getNetworkStatus()}),this.auth.lifeCycle.processEvent("connectSucc")}catch(t){var a=t;if(this.core.reporter.reportTraceUpdateV2("login",{operation_type:"TCP",target:e,code:a.code||0,description:`connectFailed:${a.message}`,mixlink:!0,succeed:!1},{asyncParams:ce.net.getNetworkStatus()}),a.code===de.V2NIM_ERROR_CODE_CANCELLED||a.code===de.V2NIM_ERROR_CODE_TIMEOUT)throw null===(r=this.socket)||void 0===r||r.close(),null===(i=this.socket)||void 0===i||i.removeAllListeners(),this.socket=void 0,t;throw this.logger.warn(`clientSocketV2::connect failed with link url: ${e}`,a),this.auth.lifeCycle.processEvent("connectFail",a),t}}))}doConnect(e){var t=!1;return new Promise(((r,i)=>{this.socket=new BaseWebsocket(this.core,e,this.linkSSL),this.socket.on("connect",(()=>{this.logger.log("clientSocketV2::socket on connect",e),this.core.reporterHookLinkKeep.start(),this.core.reporterHookLinkKeep.update({code:0,description:"connection begin",operation_type:0,target:e}),t=!0,r()})),this.socket.on("message",this.onMessage.bind(this)),this.socket.on("disconnect",(r=>__awaiter(this,void 0,void 0,(function*(){t=!0,this.logger.log("clientSocketV2::socket on disconnect",r),yield this.core.reporterHookLinkKeep.update({code:(null==r?void 0:r.code)||0,description:(null==r?void 0:r.reason)||"socket on disconnect",operation_type:1,target:e}),this.core.reporterHookLinkKeep.end(!1),this.doDisconnect(ye.OFFLINE,"SocketOnDisconnect")})))),this.socket.on("handshakeFailed",(e=>{t?this.ping():(this.logger.error(`clientSocketV2::handshake failed: "${e&&e.message}"`),this.cleanSocket()),t=!0,i(e)}))}))}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(e,t){if(this.logger.log(`clientSocketV2::doDisconnect:type:${e},reason:`,t),0!==this.core.auth.getConnectStatus()){var r={1:"close",2:"kicked",3:"broken"}[e]||"";this.markAllCmdInvaild(new V2NIMErrorImpl({code:de.V2NIM_ERROR_CODE_DISCONNECT,detail:{reason:"Packet timeout due to instance disconnect",disconnect_reason:r}})),this.timerManager.destroy(),clearTimeout(this.pingTimer),this.cleanSocket(),e===ye.ACTIVE||e===ye.KICKED?this.destroyOnlineListener():e===ye.OFFLINE&&(this.auth.lifeCycle.processEvent("connectionBroken",new V2NIMErrorImpl({code:de.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(e,t,r){var i=this.core.auth.getLoginStatus(),o={cmd:e};if(1!==i&&!["v2Login","login","chatroomLogin","v2ChatroomLogin"].includes(e))return this.logger.warn(`clientSocketV2::NIM login status is ${i}, so can not sendCmd ${e}`),Promise.reject(new V2NIMErrorImpl({code:de.V2NIM_ERROR_CODE_ILLEGAL_STATE,detail:Object.assign({reason:"Can not sendCmd due to no logined"},o)}));var n="heartbeat"!==e,s=n?this.packetSer++:0,a=createCmd(e,s,this.logger,t);if(!a){var c=new V2NIMErrorImpl({code:de.V2NIM_ERROR_CODE_INTERNAL,detail:Object.assign(Object.assign({},o),{reason:`SendCmd::createCmd error: ${s} ${e}`})});return this.logger.error(c),Promise.reject(c)}var{packet:_,hasPacketResponse:l,hasPacketTimer:d}=a,E=JSON.stringify(_);n&&(this.logger.getDebugMode()?this.logger.debug(`clientSocketV2::sendCmd: ${_.SID}_${_.CID},${e},ser:${s}`,E):this.logger.log(`clientSocketV2::sendCmd: ${_.SID}_${_.CID},${e},ser:${s}`));var h=(new Date).getTime();return new Promise(((i,n)=>{l&&this.sendingCmdMap.set(s,{cmd:e,params:t,callback:[i,n],timer:d?setTimeout((()=>{var t=new V2NIMErrorImpl({code:de.V2NIM_ERROR_CODE_PROTOCOL_TIMEOUT,detail:Object.assign({ser:s,reason:`Packet Timeout: ser ${s} cmd ${e}`,timetag:(new Date).getTime()},o)});this.markCmdInvalid(s,t,e)}),r&&r.timeout?r.timeout:this.packetTimeout):null});try{this.socket.send(E),l||i(_)}catch(t){var a=new V2NIMErrorImpl({code:de.V2NIM_ERROR_CODE_PROTOCOL_SEND_FAILED,detail:Object.assign({ser:s,reason:"Unable to send packet"+(t&&t.message?": "+t.message:""),timetag:(new Date).getTime(),rawError:t},o)});this.markCmdInvalid(s,a,e),n(a)}})).catch((e=>__awaiter(this,void 0,void 0,(function*(){var t,r=e;if(![de.V2NIM_ERROR_CODE_DISCONNECT,de.V2NIM_ERROR_CODE_PROTOCOL_TIMEOUT,de.V2NIM_ERROR_CODE_PROTOCOL_SEND_FAILED].includes(r.code))return Promise.reject(r);this.reporter.reportTraceStart("exceptions",{user_id:this.core.auth.getLoginUser(),trace_id:null===(t=this.socket)||void 0===t?void 0:t.sessionId,start_time:h,action:2,exception_service:6});var i=get(r,"detail.disconnect_reason")||"",o=r.code===de.V2NIM_ERROR_CODE_DISCONNECT?JSON.stringify({disconnect_reason:i}):r.detail.reason;return this.reporter.reportTraceUpdateV2("exceptions",{code:r.code,description:o,operation_type:1,target:`${_.SID}-${_.CID}`,context:`${_.SER}`},{asyncParams:ce.net.getNetworkStatus()}),this.reporter.reportTraceEnd("exceptions",1),Promise.reject(r)}))))}onMessage(e){var t=parseCmd(e,this.logger);if(t&&t.length>0){var r=t[0],i=r.raw.ser;for(var o of(r.error&&this.logger.error("clientSocketV2::onMessage packet error",`${r.raw.sid}_${r.raw.cid}, ser:${i},`,r.error),"heartbeat"!==r.cmd&&(this.logger.getDebugMode()?this.logger.debug(`clientSocketV2::recvCmd ${r.raw.sid}_${r.raw.cid},${r.cmd},ser:${i}`,r.content):this.logger.log(`clientSocketV2::recvCmd ${r.raw.sid}_${r.raw.cid},${r.cmd},ser:${i};code:${r.raw.code}`)),t))this.packetHandler(o)}}packetHandler(e){var t,r,i,o;if(e){var n=e.raw.ser,s=this.sendingCmdMap.get(n);if(s&&s.cmd===e.cmd){var{callback:a,timer:c,params:_}=s;if(clearTimeout(c),e.params=_,this.sendingCmdMap.delete(n),"heartbeat"===e.cmd)return void a[0]();var l=null===(r=null===(t=this.core[e.service])||void 0===t?void 0:t.process)||void 0===r?void 0:r.call(t,e);l&&"function"==typeof l.then?l.then((e=>{a[0](e)})).catch((e=>{a[1](e)})):(this.logger.log("clientSocketV2::handlerFn without promise",e.service,e.cmd),a[0](e))}else{var d=null===(o=null===(i=this.core[e.service])||void 0===i?void 0:i.process)||void 0===o?void 0:o.call(i,e);d&&"function"==typeof d.then&&d.catch((e=>{this.logger.error("clientSocketV2::no obj cache, no process handler",e)}))}}}markCmdInvalid(e,t,r){var i=this.sendingCmdMap.get(e);if(i){var{callback:o,timer:n}=i;n&&clearTimeout(n),this.sendingCmdMap.delete(e),this.logger.warn(`clientSocketV2::packet ${e}, ${r} is invalid:`,t),o[1](t)}}markAllCmdInvaild(e){this.logger.log("markAllCmdInvaild",e),this.sendingCmdMap.forEach((t=>{var{callback:r,timer:i,cmd:o}=t;this.logger.log(`clientSocketV2::markAllCmdInvaild:cmd ${o}`),i&&clearTimeout(i),r[1](e)})),this.sendingCmdMap.clear()}ping(){var e;return __awaiter(this,void 0,void 0,(function*(){clearTimeout(this.pingTimer);try{yield this.sendCmd("heartbeat")}catch(t){if(t.code===de.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===(e=this.socket)||void 0===e?void 0:e.url}),this.core.reporterHookLinkKeep.end(!0),void this.doDisconnect(ye.OFFLINE,"PingError")}this.pingTimer=setTimeout((()=>{this.ping()}),3e4)}))}testHeartBeat5Timeout(){return __awaiter(this,void 0,void 0,(function*(){clearTimeout(this.pingTimer);for(var e=0;e<5;e++)try{return yield this.sendCmd("heartbeat",{},{timeout:3e3}),!1}catch(t){this.logger.log(`clientSocketV2::test heartbeat ${e} Timeout`)}return!0}))}initOnlineListener(){this.hasNetworkListener||(this.logger.log("clientSocketV2::onlineListener:init"),this.hasNetworkListener=!0,ce.net.onNetworkStatusChange((e=>{this.logger.log("clientSocketV2::onlineListener:network change",e);var t=this.auth.getConnectStatus(),r=this.auth.getLoginStatus();e.isConnected&&1===r?this.ping():e.isConnected&&3===t?(this.logger.log("clientSocketV2::onlineListener:online and connectStatus is waiting, do reLogin"),this.auth.reconnect.clearReconnectTimer(),this.auth.reconnect.doReLogin()):e.isConnected||this.doDisconnect(ye.OFFLINE,"OfflineListener")})))}destroyOnlineListener(){this.logger.log("clientSocketV2::onlineListener:destroy"),ce.net.offNetworkStatusChange(),this.hasNetworkListener=!1}}class TimerManager{constructor(){this.timerList=[],this.id=1,this.timer=null,this.timeout=0}addTimer(e,t=0,r=1){var i=(new Date).getTime(),o=this.id;return this.timerList.push({id:o,loop:r,count:0,timeout:i+t,interval:t,callback:e}),this.id++,this.checkTimer(i),o}checkTimer(e=(new Date).getTime()){if(this.removeFinished(),0!==this.timerList.length||null==this.timer){var t=0;for(var r of this.timerList)(0===t||t>r.timeout)&&(t=r.timeout);0!==this.timerList.length&&(null===this.timer||t<this.timeout||this.timeout<e)&&(this.timer=setTimeout(this.nowTime.bind(this),t-e),this.timeout=t)}}nowTime(){var e=(new Date).getTime();for(var t of this.timerList)e>=t.timeout&&(t.callback(),t.count++,t.timeout=e+t.interval);this.clerTime(),this.checkTimer(e)}clerTime(){null!==this.timer&&(clearTimeout(this.timer),this.timer=null)}deleteTimer(e){for(var t=this.timerList.length-1;t>=0;t--){this.timerList[t].id===e&&this.timerList.splice(t,1)}}removeFinished(){for(var e=this.timerList.length-1;e>=0;e--){var t=this.timerList[e];t.loop>=0&&t.count>=t.loop&&this.timerList.splice(e,1)}}destroy(){this.clerTime(),this.timerList=[],this.id=1,this.timer=null}}class CoreAdapters{constructor(e){this.lastSuccUploadHost="",this.core=e}getFileUploadInformation(e){return ce.getFileUploadInformation(e)}request(e,t,r){var i=(new Date).getTime(),o=(null==r?void 0:r.exception_service)||0;return ce.request(e,t).catch((r=>{var n,s,a,c,_=r;throw this.core.reporter.reportTraceStart("exceptions",{user_id:this.core.options.account||(null===(s=null===(n=this.core)||void 0===n?void 0:n.auth)||void 0===s?void 0:s.account),trace_id:null===(c=null===(a=this.core.clientSocket)||void 0===a?void 0:a.socket)||void 0===c?void 0:c.sessionId,start_time:i,action:1,exception_service:o}),this.core.reporter.reportTraceUpdateV2("exceptions",{code:"number"==typeof _.code?_.code:0,description:_.message||`${_.code}`,operation_type:0,target:e,context:t?JSON.stringify(t):""},{asyncParams:ce.net.getNetworkStatus()}),this.core.reporter.reportTraceEnd("exceptions",1),r}))}uploadFile(e,t){var r,i,o,n;return __awaiter(this,void 0,void 0,(function*(){for(var s="BROWSER"===ce.platform,a=s?e.chunkUploadHostBackupList:e.commonUploadHostBackupList,c=s?e.chunkUploadHost:e.commonUploadHost,_=a.indexOf(c),l=-1===_?[c,...a]:[c,...a.slice(0,_),...a.slice(_+1)],d=Math.max(l.indexOf(this.lastSuccUploadHost),0),E=null,h=0;h<l.length;h++){var u=(new Date).getTime(),m=l[(h+d)%l.length];null==t||t.update({retry_times:h});try{var g=yield ce.uploadFile(Object.assign(Object.assign({},e),s?{chunkUploadHost:m}:{commonUploadHost:m}));return this.lastSuccUploadHost=m,"string"==typeof g.size&&(g.size=parseInt(g.size)),"string"==typeof g.dur&&(g.dur=parseInt(g.dur)),"string"==typeof g.w&&(g.w=parseInt(g.w)),"string"==typeof g.h&&(g.h=parseInt(g.h)),g}catch(e){this.core.cloudStorage.nos.nosErrorCount--,E=e;var p=e;this.core.reporter.reportTraceStart("exceptions",{user_id:this.core.options.account||(null===(i=null===(r=this.core)||void 0===r?void 0:r.auth)||void 0===i?void 0:i.account),trace_id:null===(n=null===(o=this.core.clientSocket)||void 0===o?void 0:o.socket)||void 0===n?void 0:n.sessionId,start_time:u,action:1,exception_service:3}),this.core.reporter.reportTraceUpdateV2("exceptions",{code:"number"==typeof p.code?p.code:0,description:p.message||`${p.code}`,operation_type:1,target:m},{asyncParams:ce.net.getNetworkStatus()}),this.core.reporter.reportTraceEnd("exceptions",1),this._uploadFileErrHanler(e)}}throw E}))}_uploadFileErrHanler(e){if(e&&(e.code>200||e.errCode>200))throw e}}class ABTest{constructor(e,t){this.abtInfo={},this.core=e,this.config=assignOptions({isAbtestEnable:!0,abtestUrl:ge,abtestProjectKey:pe},t)}setOptions(e){this.config=assignOptions(this.config,e)}abtRequest(){var e,t;return __awaiter(this,void 0,void 0,(function*(){if(this.config.isAbtestEnable&&!this.abtInfo.experiments&&this.config.abtestUrl){var r;try{r=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.71",deviceId:this.core.config.deviceId},useLocalCache:!0}},{exception_service:7})}catch(e){this.core.logger.warn("ABTest request failed")}this.abtInfo=(null===(t=null===(e=null==r?void 0:r.data)||void 0===e?void 0:e.data)||void 0===t?void 0:t.abtInfo)||{}}}))}}function pickBy(e,t){e=e||{},t=t||(()=>!0);var r={};for(var i in e)t(e[i])&&(r[i]=e[i]);return r}function formatQueueElementsFromKVObject(e){return Object.keys(e).map((t=>({key:t,value:e[t]})))}function formatQueueElementsFromElements(e){return e&&e.length>0?e.map((e=>({key:e.key,value:e.value,accountId:e.accid,nick:e.nick}))):[]}function formatMessage(e,t,r){if(t.isSelf=t.senderId===r,delete t.resend,0===t.messageType||10===t.messageType){var i="string"==typeof t.attachment?t.attachment:"object"==typeof t.attachment?t.attachment.raw:"";t.text=t.text||i,delete t.attachment}return 5===t.messageType?t.attachment=function formatNotificationAttachment(e,t){var r,i,o,n,s,a,c,_,l,d,E,h,u,m,g,p,I,N,T={type:"number"==typeof be[e.id]?be[e.id]:e.id,targetIds:null===(r=e.data)||void 0===r?void 0:r.target,targetNicks:null===(i=e.data)||void 0===i?void 0:i.tarNick,targetTag:null===(o=e.data)||void 0===o?void 0:o.targetTag,operatorId:null===(n=e.data)||void 0===n?void 0:n.operator,operatorNick:null===(s=e.data)||void 0===s?void 0:s.opeNick,notificationExtension:null===(a=e.data)||void 0===a?void 0:a.ext,tags:null===(c=e.data)||void 0===c?void 0:c.tags,messageClientId:null===(_=e.data)||void 0===_?void 0:_.msgId,messageTime:null===(l=e.data)||void 0===l?void 0:l.msgTime,chatBanned:void 0!==(null===(d=e.data)||void 0===d?void 0:d.muted)?Boolean(null===(E=e.data)||void 0===E?void 0:E.muted):void 0,tempChatBanned:void 0!==(null===(h=e.data)||void 0===h?void 0:h.tempMuted)?Boolean(null===(u=e.data)||void 0===u?void 0:u.tempMuted):void 0,previousRole:null===(m=e.data)||void 0===m?void 0:m.previousRole,tempChatBannedDuration:"number"==typeof(null===(g=e.data)||void 0===g?void 0:g.muteTtl)?e.data.muteTtl:null===(p=e.data)||void 0===p?void 0:p.muteDuration};14===(T=pickBy(T,(e=>void 0!==e))).type?T.tempChatBanned=!0:15===T.type&&(T.tempChatBanned=!1);if(null===(I=e.data)||void 0===I?void 0:I.member){var O=e.data.member;T.currentMember=pickBy({roomId:t,accountId:O.accountId,memberRole:O.memberRole,memberLevel:O.memberLevel,roomNick:O.nick,roomAvatar:O.avatar,serverExtension:O.ext,isOnline:!!O.onlineStat,blocked:!!O.blockList,chatBanned:!!O.chatBanned,tempChatBanned:!!O.tempChatBanned,tempChatBannedDuration:"number"==typeof O.muteTtl?O.muteTtl:O.muteDuration,tags:stringToJSONObject(O.tags),notifyTargetTags:O.notifyTargetTags,enterTime:O.enterTime,updateTime:O.updateTime,valid:void 0===O.valid||!!O.valid,multiEnterInfo:formatMultiEnterInfo(O.onlineList)},(e=>void 0!==e))}if(null===(N=e.data)||void 0===N?void 0:N.queueChange){var{elements:M,queueChangeType:f}=function formatNotificationAttachmentForQueue(e){try{var t=JSON.parse(e);if("OFFER"===t._e)return{elements:[{key:t.key,value:t.content}],queueChangeType:1};if("POLL"===t._e)return{elements:[{key:t.key,value:t.content}],queueChangeType:2};if("DROP"===t._e)return{elements:[],queueChangeType:3};if("BATCH_UPDATE"===t._e)return{elements:formatQueueElementsFromKVObject(t.kvObject),queueChangeType:5};if("PARTCLEAR"===t._e)return{elements:formatQueueElementsFromKVObject(t.kvObject),queueChangeType:4};if("BATCH_OFFER"===t._e)return{elements:formatQueueElementsFromElements(t.elements),queueChangeType:6}}catch(e){}return{elements:[],queueChangeType:0}}(e.data.queueChange);T.elements=M,f>0&&(T.queueChangeType=f)}return T.raw=e.raw,T}(t.attachment,t.roomId):100===t.messageType&&(t=function formatCustomAttachment(e,t){var r,i,o;if("string"==typeof(null===(r=t.attachment)||void 0===r?void 0:r.raw)&&(null===(o=null===(i=e.V2NIMChatroomMessageService)||void 0===i?void 0:i.customAttachmentParsers)||void 0===o?void 0:o.length)>0){var n=t.subType||0,s=e.V2NIMChatroomMessageService.customAttachmentParsers,a=t.attachment.raw;s.some((r=>{try{var i=r(n,a);if(isPlainObject(i))return i.raw=a,t.attachment=i,!0}catch(t){return e.logger.warn(`customAttachmentParser: subType ${n}, raw: ${a}. parse error with ${t}`),!1}}))}return t}(e,t)),t}function formatMultiEnterInfo(e){if(e&&"string"==typeof e)try{return JSON.parse(e).map((e=>({roomNick:e.room_nick,roomAvatar:e.room_avatar,enterTime:e.enter_time,clientType:e.client_type})))}catch(e){return}}var be={301:0,302:1,303:2,304:3,305:4,306:5,312:6,313:7,314:8,315:9,316:10,317:11,320:11,324:11,318:12,319:13,321:14,322:15,323:16,325:17,326:18};function attachmentToRaw(e,t){if(!t)return"";switch(e){case 100:return t.raw||"";case 1:case 3:case 2:case 6:return function mediaAttachmentToRaw(e){var t=e,{width:r,height:i,duration:o,path:n,file:s,raw:a,ctx:c,payload:_,bucketName:l,objectName:d,token:E,ext:h}=t,u=__rest(t,["width","height","duration","path","file","raw","ctx","payload","bucketName","objectName","token","ext"]),m="string"==typeof h&&"."===h[0]?h.slice(1):h;return JSON.stringify(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},u),void 0===h?{}:{ext:m}),void 0===r?{}:{w:r}),void 0===i?{}:{h:i}),void 0===o?{}:{dur:o}))}(t);case 4:return function locationAttachmentToRaw(e){return JSON.stringify({lat:e.latitude,lng:e.longitude,title:e.address})}(t);case 12:return function callAttachmentToRaw(e){var t=__rest(e,["raw"]);try{return JSON.stringify(Object.assign(Object.assign({},t),{durations:e.durations.map((e=>({accid:e.accountId,duration:e.duration})))}))}catch(t){return JSON.stringify(e)}}(t);default:return"string"==typeof t?t:JSON.stringify(t)}}function rawToAttachment(e,t){var r;try{switch(r=JSON.parse(e),t){case 100:return{raw:e};case 4:return function locationRawToAttachment(e,t){return{latitude:t.lat,longitude:t.lng,address:t.title,raw:e}}(e,r);case 2:case 3:case 1:case 6:return function mediaRawToAttachment(e,t){var{w:r,h:i,dur:o,ext:n}=t,s=__rest(t,["w","h","dur","ext"]),a="string"==typeof n&&"."!==n[0]?`.${n}`:n;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},s),void 0===n?{}:{ext:a}),void 0===r?{}:{width:r}),void 0===i?{}:{height:i}),void 0===o?{}:{duration:o}),{raw:e})}(e,r);case 12:return function callRawToAttachment(e,t){return Object.assign(Object.assign({},t),{durations:t.durations.map((e=>({accountId:e.accid,duration:e.duration}))),raw:e})}(e,r);default:return"object"==typeof r&&r?Object.assign(Object.assign({},r),{raw:e}):{raw:e}}}catch(t){return"object"==typeof r&&r?Object.assign(Object.assign({},r),{raw:e}):{raw:e}}}var Pe,ke,we,Ue,xe,Ge,Fe,Be,He,Ye,je,$e,Ke,qe,We,ze,Je,Qe="V2NIMChatroomMemberService",Xe={"36_15":"v2ChatroomUpdateSelfMemberInfo","36_16":"v2ChatroomGetMemberByIds","36_17":"v2ChatroomKickMember","36_19":"v2ChatroomSetMemberTempChatBanned","36_41":"v2ChatroomGetMemberListByTag","36_32":"v2ChatroomGetMemberCountByTag","36_37":"v2ChatroomGetMemberListByOption","36_38":"v2ChatroomUpdateMemberRole","36_39":"v2ChatroomSetMemberBlockedStatus","36_40":"v2ChatroomSetMemberChatBannedStatus","13_101":"v2ChatroomOnMemberTagUpdated"},Ze={roomId:1,accountId:2,memberRole:{id:3,retType:"number"},memberLevel:{id:4,retDef:0,retType:"number"},roomNick:5,roomAvatar:6,serverExtension:7,isOnline:{id:8,retType:"boolean"},enterTime:{id:10,retType:"number"},blocked:{id:12,retType:"boolean"},chatBanned:{id:13,retType:"boolean"},valid:{id:14,retDef:!0,retType:"boolean"},updateTime:{id:15,retDef:0,retType:"number"},tempChatBanned:{id:16,retType:"boolean",retDef:!1},tempChatBannedDuration:{id:17,retType:"number"},tags:{id:18,converter:objectToJSONString,retConverter:stringToJSONObject},notifyTargetTags:19,multiEnterInfo:{id:20,retConverter:formatMultiEnterInfo}},et={memberRoles:{id:1,converter:e=>e.join(",")},onlyBlocked:{id:2,converter:boolToInt},onlyChatBanned:{id:3,converter:boolToInt},onlyOnline:{id:4,converter:boolToInt},pageToken:5,limit:6},rt={v2ChatroomGetMemberByIds:{sid:36,cid:16,service:Qe,params:[{type:"StrArray",name:"accountIds"}],response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(Ze)}]},v2ChatroomGetMemberListByOption:{sid:36,cid:37,service:Qe,params:[{type:"Property",name:"tag",reflectMapper:et}],response:[{type:"Int",name:"hasMore"},{type:"String",name:"pageToken"},{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(Ze)}]},v2ChatroomUpdateSelfMemberInfo:{sid:36,cid:15,service:Qe,params:[{type:"Property",name:"tag",reflectMapper:Ze},{type:"Bool",name:"notificationEnabled"},{type:"String",name:"notificationExtension"},{type:"Bool",name:"persistence"},{type:"Property",name:"antispamConfig",reflectMapper:{antispamBusinessId:1}}]},v2ChatroomSetMemberTempChatBanned:{sid:36,cid:19,service:Qe,params:[{type:"String",name:"accountId"},{type:"Long",name:"tempChatBannedDuration"},{type:"Bool",name:"notificationEnabled"},{type:"String",name:"notificationExtension"}]},v2ChatroomGetMemberListByTag:{sid:36,cid:41,service:Qe,params:[{type:"Property",name:"tag",reflectMapper:{tag:1,pageToken:2,limit:3}}],response:[{type:"Int",name:"hasMore"},{type:"String",name:"pageToken"},{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(Ze)}]},v2ChatroomGetMemberCountByTag:{sid:36,cid:32,service:Qe,params:[{type:"String",name:"tag"}],response:[{type:"Long",name:"data"}]},v2ChatroomKickMember:{sid:36,cid:17,service:Qe,params:[{type:"String",name:"accountId"},{type:"String",name:"notificationExtension"}]},v2ChatroomUpdateMemberRole:{sid:36,cid:38,service:Qe,params:[{type:"Property",name:"tag",reflectMapper:{accountId:1,memberRole:2,memberLevel:3,notificationExtension:4}}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Ze)}]},v2ChatroomSetMemberBlockedStatus:{sid:36,cid:39,service:Qe,params:[{type:"String",name:"accountId"},{type:"Bool",name:"blocked"},{type:"String",name:"notificationExtension"}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Ze)}]},v2ChatroomSetMemberChatBannedStatus:{sid:36,cid:40,service:Qe,params:[{type:"String",name:"accountId"},{type:"Bool",name:"chatBanned"},{type:"String",name:"notificationExtension"}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Ze)}]},v2ChatroomOnMemberTagUpdated:{sid:36,cid:101,service:Qe,response:[{type:"Property",name:"data",reflectMapper:{1:"tag"}}]}},it="V2NIMChatroomLoginService",ot={"1_2":"heartbeat","36_2":"v2ChatroomLogin","13_3":"v2ChatroomBeKicked","36_4":"v2ChatroomLogout"},nt={roomId:1,roomName:3,announcement:4,liveUrl:5,isValidRoom:{id:9,retType:"boolean"},serverExtension:12,queueLevelMode:{id:16,retType:"number"},creatorAccountId:100,onlineUserCount:{id:101,retType:"number"},chatBanned:{id:102,retType:"boolean"}},st={enabled:{id:1,retType:"boolean"},cdnUrls:{id:2,retConverter(e){if("string"==typeof e&&""!==e)return e.split("|")}},timestamp:{id:3,retType:"number"},pollingIntervalSeconds:{id:4,retType:"number"},decryptType:{id:5,retType:"number"},decryptKey:6,pollingTimeoutMillis:{id:7,retType:"number"}},at={heartbeat:{sid:1,cid:2,service:it},v2ChatroomLogin:{sid:36,cid:2,service:it,params:[{type:"Byte",name:"type"},{type:"Property",name:"chatroomLogin",reflectMapper:{appkey:1,account:2,deviceId:3,chatroomId:5,appLogin:8,chatroomNick:20,chatroomAvatar:21,serverExtension:22,notificationExtension:23,clientSession:26,isAnonymous:{id:38,converter:e=>+e},tags:{id:39,converter:e=>{if(Array.isArray(e)&&e.length>0)return JSON.stringify(e)}},notifyTargetTags:40,authType:41,loginExt:42,x:43,y:44,z:45,distance:46,antiSpamBusinessId:47,env:49,isRoutable:{id:50,converter:boolToInt}}},{type:"Property",name:"chatroomIMLogin",reflectMapper:{clientType:3,os:4,sdkVersion:6,appLogin:8,protocolVersion:9,pushTokenName:10,pushToken:11,deviceId:13,appkey:18,account:19,browser:24,clientSession:26,deviceInfo:32,customTag:38,customClientType:39,sdkHumanVersion:40,hostEnv:41,userAgent:42,libEnv:44,isReactNative:{id:112,converter:e=>+e},authType:115,loginExt:116,token:1e3}}],response:[{type:"Property",name:"chatroomInfo",reflectMapper:invertSerializeItem(nt)},{type:"Property",name:"chatroomMember",reflectMapper:invertSerializeItem(Ze)},{type:"Property",name:"chatroomCdnInfo",reflectMapper:invertSerializeItem(st)}]},v2ChatroomLogout:{sid:36,cid:4,service:it,params:[]},v2ChatroomBeKicked:{sid:13,cid:3,service:it,response:[{type:"Int",name:"kickedReason"},{type:"String",name:"serverExtension"}]}};!function(e){e[e.V2NIM_LOGIN_AUTH_TYPE_DEFAULT=0]="V2NIM_LOGIN_AUTH_TYPE_DEFAULT",e[e.V2NIM_LOGIN_AUTH_TYPE_DYNAMIC_TOKEN=1]="V2NIM_LOGIN_AUTH_TYPE_DYNAMIC_TOKEN",e[e.V2NIM_LOGIN_AUTH_TYPE_THIRD_PARTY=2]="V2NIM_LOGIN_AUTH_TYPE_THIRD_PARTY"}(Pe||(Pe={})),function(e){e[e.V2NIM_LOGIN_STATUS_LOGOUT=0]="V2NIM_LOGIN_STATUS_LOGOUT",e[e.V2NIM_LOGIN_STATUS_LOGINED=1]="V2NIM_LOGIN_STATUS_LOGINED",e[e.V2NIM_LOGIN_STATUS_LOGINING=2]="V2NIM_LOGIN_STATUS_LOGINING",e[e.V2NIM_LOGIN_STATUS_UNLOGIN=3]="V2NIM_LOGIN_STATUS_UNLOGIN"}(ke||(ke={})),function(e){e[e.V2NIM_LOGIN_CLIENT_TYPE_UNKNOWN=0]="V2NIM_LOGIN_CLIENT_TYPE_UNKNOWN",e[e.V2NIM_LOGIN_CLIENT_TYPE_ANDROID=1]="V2NIM_LOGIN_CLIENT_TYPE_ANDROID",e[e.V2NIM_LOGIN_CLIENT_TYPE_IOS=2]="V2NIM_LOGIN_CLIENT_TYPE_IOS",e[e.V2NIM_LOGIN_CLIENT_TYPE_PC=4]="V2NIM_LOGIN_CLIENT_TYPE_PC",e[e.V2NIM_LOGIN_CLIENT_TYPE_WP=8]="V2NIM_LOGIN_CLIENT_TYPE_WP",e[e.V2NIM_LOGIN_CLIENT_TYPE_WEB=16]="V2NIM_LOGIN_CLIENT_TYPE_WEB",e[e.V2NIM_LOGIN_CLIENT_TYPE_RESTFUL=32]="V2NIM_LOGIN_CLIENT_TYPE_RESTFUL",e[e.V2NIM_LOGIN_CLIENT_TYPE_MAC_OS=64]="V2NIM_LOGIN_CLIENT_TYPE_MAC_OS",e[e.V2NIM_LOGIN_CLIENT_TYPE_HARMONY_OS=65]="V2NIM_LOGIN_CLIENT_TYPE_HARMONY_OS"}(we||(we={})),function(e){e[e.V2NIM_LOGIN_CLIENT_CHANGE_LIST=1]="V2NIM_LOGIN_CLIENT_CHANGE_LIST",e[e.V2NIM_LOGIN_CLIENT_CHANGE_LOGIN=2]="V2NIM_LOGIN_CLIENT_CHANGE_LOGIN",e[e.V2NIM_LOGIN_CLIENT_CHANGE_LOGOUT=3]="V2NIM_LOGIN_CLIENT_CHANGE_LOGOUT"}(Ue||(Ue={})),function(e){e[e.V2NIM_CONNECT_STATUS_DISCONNECTED=0]="V2NIM_CONNECT_STATUS_DISCONNECTED",e[e.V2NIM_CONNECT_STATUS_CONNECTED=1]="V2NIM_CONNECT_STATUS_CONNECTED",e[e.V2NIM_CONNECT_STATUS_CONNECTING=2]="V2NIM_CONNECT_STATUS_CONNECTING",e[e.V2NIM_CONNECT_STATUS_WAITING=3]="V2NIM_CONNECT_STATUS_WAITING"}(xe||(xe={})),function(e){e[e.V2NIM_CHATROOM_KICKED_REASON_UNKNOWN=-1]="V2NIM_CHATROOM_KICKED_REASON_UNKNOWN",e[e.V2NIM_CHATROOM_KICKED_REASON_CHATROOM_INVALID=1]="V2NIM_CHATROOM_KICKED_REASON_CHATROOM_INVALID",e[e.V2NIM_CHATROOM_KICKED_REASON_BY_MANAGER=2]="V2NIM_CHATROOM_KICKED_REASON_BY_MANAGER",e[e.V2NIM_CHATROOM_KICKED_REASON_BY_CONFLICT_LOGIN=3]="V2NIM_CHATROOM_KICKED_REASON_BY_CONFLICT_LOGIN",e[e.V2NIM_CHATROOM_KICKED_REASON_SILENTLY=4]="V2NIM_CHATROOM_KICKED_REASON_SILENTLY",e[e.V2NIM_CHATROOM_KICKED_REASON_BE_BLOCKED=5]="V2NIM_CHATROOM_KICKED_REASON_BE_BLOCKED"}(Ge||(Ge={})),function(e){e[e.V2NIM_CHATROOM_MEMBER_ROLE_NORMAL=0]="V2NIM_CHATROOM_MEMBER_ROLE_NORMAL",e[e.V2NIM_CHATROOM_MEMBER_ROLE_CREATOR=1]="V2NIM_CHATROOM_MEMBER_ROLE_CREATOR",e[e.V2NIM_CHATROOM_MEMBER_ROLE_MANAGER=2]="V2NIM_CHATROOM_MEMBER_ROLE_MANAGER",e[e.V2NIM_CHATROOM_MEMBER_ROLE_NORMAL_GUEST=3]="V2NIM_CHATROOM_MEMBER_ROLE_NORMAL_GUEST",e[e.V2NIM_CHATROOM_MEMBER_ROLE_ANONYMOUS_GUEST=4]="V2NIM_CHATROOM_MEMBER_ROLE_ANONYMOUS_GUEST",e[e.V2NIM_CHATROOM_MEMBER_ROLE_VIRTUAL=5]="V2NIM_CHATROOM_MEMBER_ROLE_VIRTUAL"}(Fe||(Fe={})),function(e){e[e.V2NIM_MESSAGE_SENDING_STATE_UNKNOWN=0]="V2NIM_MESSAGE_SENDING_STATE_UNKNOWN",e[e.V2NIM_MESSAGE_SENDING_STATE_SUCCEEDED=1]="V2NIM_MESSAGE_SENDING_STATE_SUCCEEDED",e[e.V2NIM_MESSAGE_SENDING_STATE_FAILED=2]="V2NIM_MESSAGE_SENDING_STATE_FAILED",e[e.V2NIM_MESSAGE_SENDING_STATE_SENDING=3]="V2NIM_MESSAGE_SENDING_STATE_SENDING"}(Be||(Be={})),function(e){e[e.V2NIM_MESSAGE_ATTACHMENT_UPLOAD_STATE_UNKNOWN=0]="V2NIM_MESSAGE_ATTACHMENT_UPLOAD_STATE_UNKNOWN",e[e.V2NIM_MESSAGE_ATTACHMENT_UPLOAD_STATE_SUCCESS=1]="V2NIM_MESSAGE_ATTACHMENT_UPLOAD_STATE_SUCCESS",e[e.V2NIM_MESSAGE_ATTACHMENT_UPLOAD_STATE_FAILED=2]="V2NIM_MESSAGE_ATTACHMENT_UPLOAD_STATE_FAILED",e[e.V2NIM_MESSAGE_ATTACHMENT_UPLOAD_STATE_UPLOADING=3]="V2NIM_MESSAGE_ATTACHMENT_UPLOAD_STATE_UPLOADING"}(He||(He={})),function(e){e[e.V2NIM_MESSAGE_TYPE_INVALID=-1]="V2NIM_MESSAGE_TYPE_INVALID",e[e.V2NIM_MESSAGE_TYPE_TEXT=0]="V2NIM_MESSAGE_TYPE_TEXT",e[e.V2NIM_MESSAGE_TYPE_IMAGE=1]="V2NIM_MESSAGE_TYPE_IMAGE",e[e.V2NIM_MESSAGE_TYPE_AUDIO=2]="V2NIM_MESSAGE_TYPE_AUDIO",e[e.V2NIM_MESSAGE_TYPE_VIDEO=3]="V2NIM_MESSAGE_TYPE_VIDEO",e[e.V2NIM_MESSAGE_TYPE_LOCATION=4]="V2NIM_MESSAGE_TYPE_LOCATION",e[e.V2NIM_MESSAGE_TYPE_NOTIFICATION=5]="V2NIM_MESSAGE_TYPE_NOTIFICATION",e[e.V2NIM_MESSAGE_TYPE_FILE=6]="V2NIM_MESSAGE_TYPE_FILE",e[e.V2NIM_MESSAGE_TYPE_AVCHAT=7]="V2NIM_MESSAGE_TYPE_AVCHAT",e[e.V2NIM_MESSAGE_TYPE_TIPS=10]="V2NIM_MESSAGE_TYPE_TIPS",e[e.V2NIM_MESSAGE_TYPE_ROBOT=11]="V2NIM_MESSAGE_TYPE_ROBOT",e[e.V2NIM_MESSAGE_TYPE_CALL=12]="V2NIM_MESSAGE_TYPE_CALL",e[e.V2NIM_MESSAGE_TYPE_CUSTOM=100]="V2NIM_MESSAGE_TYPE_CUSTOM"}(Ye||(Ye={})),function(e){e[e.V2NIM_QUERY_DIRECTION_DESC=0]="V2NIM_QUERY_DIRECTION_DESC",e[e.V2NIM_QUERY_DIRECTION_ASC=1]="V2NIM_QUERY_DIRECTION_ASC"}(je||(je={})),function(e){e[e.V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_MEMBER_ENTER=0]="V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_MEMBER_ENTER",e[e.V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_MEMBER_EXIT=1]="V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_MEMBER_EXIT",e[e.V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_MEMBER_BLOCK_ADDED=2]="V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_MEMBER_BLOCK_ADDED",e[e.V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_MEMBER_BLOCK_REMOVED=3]="V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_MEMBER_BLOCK_REMOVED",e[e.V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_MEMBER_CHAT_BANNED_ADDED=4]="V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_MEMBER_CHAT_BANNED_ADDED",e[e.V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_MEMBER_CHAT_BANNED_REMOVED=5]="V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_MEMBER_CHAT_BANNED_REMOVED",e[e.V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_ROOM_INFO_UPDATED=6]="V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_ROOM_INFO_UPDATED",e[e.V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_MEMBER_KICKED=7]="V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_MEMBER_KICKED",e[e.V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_MEMBER_TEMP_CHAT_BANNED_ADDED=8]="V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_MEMBER_TEMP_CHAT_BANNED_ADDED",e[e.V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_MEMBER_TEMP_CHAT_BANNED_REMOVED=9]="V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_MEMBER_TEMP_CHAT_BANNED_REMOVED",e[e.V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_MEMBER_INFO_UPDATED=10]="V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_MEMBER_INFO_UPDATED",e[e.V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_QUEUE_CHANGE=11]="V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_QUEUE_CHANGE",e[e.V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_CHAT_BANNED=12]="V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_CHAT_BANNED",e[e.V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_CHAT_BANNED_REMOVED=13]="V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_CHAT_BANNED_REMOVED",e[e.V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_TAG_TEMP_CHAT_BANNED_ADDED=14]="V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_TAG_TEMP_CHAT_BANNED_ADDED",e[e.V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_TAG_TEMP_CHAT_BANNED_REMOVED=15]="V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_TAG_TEMP_CHAT_BANNED_REMOVED",e[e.V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_MESSAGE_REVOKE=16]="V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_MESSAGE_REVOKE",e[e.V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_TAGS_UPDATE=17]="V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_TAGS_UPDATE",e[e.V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_ROLE_UPDATE=18]="V2NIM_CHATROOM_MESSAGE_NOTIFICATION_TYPE_ROLE_UPDATE"}($e||($e={})),function(e){e[e.V2NIM_CLIENT_ANTISPAM_OPERATE_NONE=0]="V2NIM_CLIENT_ANTISPAM_OPERATE_NONE",e[e.V2NIM_CLIENT_ANTISPAM_OPERATE_REPLACE=1]="V2NIM_CLIENT_ANTISPAM_OPERATE_REPLACE",e[e.V2NIM_CLIENT_ANTISPAM_OPERATE_CLIENT_SHIELD=2]="V2NIM_CLIENT_ANTISPAM_OPERATE_CLIENT_SHIELD",e[e.V2NIM_CLIENT_ANTISPAM_OPERATE_SERVER_SHIELD=3]="V2NIM_CLIENT_ANTISPAM_OPERATE_SERVER_SHIELD"}(Ke||(Ke={})),function(e){e[e.V2NIM_CHATROOM_STATUS_DISCONNECTED=0]="V2NIM_CHATROOM_STATUS_DISCONNECTED",e[e.V2NIM_CHATROOM_STATUS_WAITING=1]="V2NIM_CHATROOM_STATUS_WAITING",e[e.V2NIM_CHATROOM_STATUS_CONNECTING=2]="V2NIM_CHATROOM_STATUS_CONNECTING",e[e.V2NIM_CHATROOM_STATUS_CONNECTED=3]="V2NIM_CHATROOM_STATUS_CONNECTED",e[e.V2NIM_CHATROOM_STATUS_ENTERING=4]="V2NIM_CHATROOM_STATUS_ENTERING",e[e.V2NIM_CHATROOM_STATUS_ENTERED=5]="V2NIM_CHATROOM_STATUS_ENTERED",e[e.V2NIM_CHATROOM_STATUS_EXITED=6]="V2NIM_CHATROOM_STATUS_EXITED"}(qe||(qe={})),function(e){e.off="off",e.error="error",e.warn="warn",e.log="log",e.debug="debug"}(We||(We={})),function(e){e[e.V2NIM_CHATROOM_QUEUE_CHANGE_TYPE_UNKNOWN=0]="V2NIM_CHATROOM_QUEUE_CHANGE_TYPE_UNKNOWN",e[e.V2NIM_CHATROOM_QUEUE_CHANGE_TYPE_OFFER=1]="V2NIM_CHATROOM_QUEUE_CHANGE_TYPE_OFFER",e[e.V2NIM_CHATROOM_QUEUE_CHANGE_TYPE_POLL=2]="V2NIM_CHATROOM_QUEUE_CHANGE_TYPE_POLL",e[e.V2NIM_CHATROOM_QUEUE_CHANGE_TYPE_DROP=3]="V2NIM_CHATROOM_QUEUE_CHANGE_TYPE_DROP",e[e.V2NIM_CHATROOM_QUEUE_CHANGE_TYPE_PARTCLEAR=4]="V2NIM_CHATROOM_QUEUE_CHANGE_TYPE_PARTCLEAR",e[e.V2NIM_CHATROOM_QUEUE_CHANGE_TYPE_BATCH_UPDATE=5]="V2NIM_CHATROOM_QUEUE_CHANGE_TYPE_BATCH_UPDATE",e[e.V2NIM_CHATROOM_QUEUE_CHANGE_TYPE_BATCH_OFFER=6]="V2NIM_CHATROOM_QUEUE_CHANGE_TYPE_BATCH_OFFER"}(ze||(ze={})),function(e){e[e.V2NIM_CHATROOM_QUEUE_LEVEL_MODE_ANY=0]="V2NIM_CHATROOM_QUEUE_LEVEL_MODE_ANY",e[e.V2NIM_CHATROOM_QUEUE_LEVEL_MODE_MANAGER=1]="V2NIM_CHATROOM_QUEUE_LEVEL_MODE_MANAGER"}(Je||(Je={}));var ct={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_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_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_MEMBER_CAN_NOT_MODIFY_SELF:{code:109312,message:"operation on self not allowed"},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_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_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"}},_t=Object.keys(ct),lt=_t.reduce((function(e,t){var r=ct[t];return e[t]=r.code,e}),{}),dt=_t.reduce((function(e,t){var r=ct[t];return e[r.code]=r.message,e}),{}),Et=Object.freeze({__proto__:null,V2NIMErrorCode:lt,V2NIMErrorDesc:dt,get V2NIMLoginAuthType(){return Pe},get V2NIMLoginStatus(){return ke},get V2NIMLoginClientType(){return we},get V2NIMLoginClientChange(){return Ue},get V2NIMConnectStatus(){return xe},get V2NIMChatroomKickedReason(){return Ge},get V2NIMChatroomMemberRole(){return Fe},get V2NIMMessageSendingState(){return Be},get V2NIMMessageAttachmentUploadState(){return He},get V2NIMMessageType(){return Ye},get V2NIMQueryDirection(){return je},get V2NIMChatroomMessageNotificationType(){return $e},get V2NIMClientAntispamOperateType(){return Ke},get V2NIMChatroomStatus(){return qe},get V2NIMChatroomQueueLevelMode(){return Je}});class V2NIMLoginReconnect{constructor(e){this.currenRetryCount=0,this.reconnectTimer=0,this.backoffIntervals=[1e3,2e3,3e3],this.currReconnectInterval=0,this.core=e,this.auth=e.auth}reset(){this.currenRetryCount=0,this.reconnectTimer&&clearTimeout(this.reconnectTimer)}clearReconnectTimer(){this.reconnectTimer&&clearTimeout(this.reconnectTimer)}attempToReLogin(){var e=this.backoffIntervals[this.currReconnectInterval];return this.currReconnectInterval=(this.currReconnectInterval+1)%this.backoffIntervals.length,this.currenRetryCount++,this.core.logger.log(`reconnect::reconnect timer is about to be set, delay ${e} ms, current retry count is ${this.currenRetryCount}`),this.clearReconnectTimer(),this.reconnectTimer=setTimeout((()=>{this.core.logger.log("reconnect::reconnect timer is now triggered");var e=this.auth.getConnectStatus();3===e?this.doReLogin():this.core.logger.warn(`reconnect::reconnect timer is over because connect status now is ${e}`)}),e),!0}doReLogin(){return __awaiter(this,void 0,void 0,(function*(){this.auth.connectParams.forceMode=!1;try{yield this.auth.updateDynamicParamters(!1)}catch(e){return this.auth.lifeCycle.processEvent("waiting")}var e=this.core.timeOrigin.getTimeNode();this.auth.originLoginPromise=this.auth.doLogin(!0);try{yield this.auth.previousLoginManager.add(this.auth.originLoginPromise),this.currReconnectInterval=0,this.auth.reportLoginSucc(e)}catch(r){var t=r;if(this.core.logger.warn("reconnect::try login but failed due to",t),this.auth.reportLoginFail(e,t),this.auth.checkLoginTerminalCode(t&&t.code))return this.auth.clientSocket.doDisconnect(Ce.ACTIVE,"ReloginTerminated}"),void this.auth.lifeCycle.processEvent("exited",t);t&&t.code===lt.V2NIM_ERROR_CODE_SERVER_UNIT_ERROR?this.auth.updateLinkAddress().then((()=>{this.auth.lifeCycle.processEvent("waiting")})).catch((e=>{this.auth.lifeCycle.processEvent("reconnectFail",e)})):this.auth.lifeCycle.processEvent("waiting")}}))}}class V2NIMLoginAuthenticator{constructor(e){this.lastLoginClientKey="__NIM_LAST_LOGIN_CLIENT__",this.loginClients=[],this.loginClientOfThisConnection={},this.core=e,this.auth=e.auth}verifyAuthentication(e){var t,r,i,o,n,s,a,c,_,l,d,E,h,u;return __awaiter(this,void 0,void 0,(function*(){var m,g=ce.getSystemInfo(),p={clientType:16,os:g.os,sdkVersion:100971,appLogin:e?0:1,protocolVersion:1,deviceId:this.auth.deviceId,appkey:this.auth.appkey,account:this.auth.account,browser:g.browser,clientSession:this.auth.clientSession,customClientType:this.core.options.customClientType,sdkHumanVersion:"10.9.71",userAgent:this.core.options.loginSDKTypeParamCompat?"Native/10.9.71":g.userAgent.replace("{{appkey}}",this.auth.appkey).slice(0,299),libEnv:this.core.options.loginSDKTypeParamCompat?void 0:g.libEnv,hostEnv:this.core.options.loginSDKTypeParamCompat?0:g.hostEnvEnum,authType:this.auth.authType,loginExt:this.auth.loginExt,token:this.auth.token},I=Object.assign(Object.assign({appkey:this.auth.appkey,account:this.auth.account,deviceId:this.auth.deviceId,chatroomId:this.auth.roomId,appLogin:e?0:1,chatroomNick:null===(t=this.auth.enterParams)||void 0===t?void 0:t.roomNick,chatroomAvatar:(null===(r=this.auth.enterParams)||void 0===r?void 0:r.roomAvatar)||"",serverExtension:null===(i=this.auth.enterParams)||void 0===i?void 0:i.serverExtension,notificationExtension:null===(o=this.auth.enterParams)||void 0===o?void 0:o.notificationExtension,clientSession:this.auth.clientSession,isAnonymous:this.auth.isAnonymous,tags:null===(s=null===(n=this.auth.enterParams)||void 0===n?void 0:n.tagConfig)||void 0===s?void 0:s.tags,notifyTargetTags:null===(c=null===(a=this.auth.enterParams)||void 0===a?void 0:a.tagConfig)||void 0===c?void 0:c.notifyTargetTags,authType:this.auth.authType,loginExt:this.auth.loginExt},null===(l=null===(_=this.auth.enterParams)||void 0===_?void 0:_.locationConfig)||void 0===l?void 0:l.locationInfo),{distance:null===(E=null===(d=this.auth.enterParams)||void 0===d?void 0:d.locationConfig)||void 0===E?void 0:E.distance,antiSpamBusinessId:null===(u=null===(h=this.auth.enterParams)||void 0===h?void 0:h.antispamConfig)||void 0===u?void 0:u.antispamBusinessId,isRoutable:!1===get(this.auth,"enterParams.loginOption.routeConfig.routeEnabled")?0:1,env:get(this.auth,"enterParams.loginOption.routeConfig.routeEnvironment")});try{this.auth.lifeCycle.processEvent("loginStart"),m=yield this.auth.doLoginStepsManager.add(this.auth.clientSocket.sendCmd("v2ChatroomLogin",{type:1,chatroomLogin:I,chatroomIMLogin:p}))}catch(e){var N=e;if(this.core.reporter.reportTraceUpdateV2("login",{operation_type:"protocol",target:"26-3",code:N.code||0,succeed:!1,description:N.message},{asyncParams:ce.net.getNetworkStatus()}),N.code===lt.V2NIM_ERROR_CODE_CANCELLED||N.code===lt.V2NIM_ERROR_CODE_TIMEOUT)throw N;throw this.processLoginFailed(N),N}var{chatroomInfo:T,chatroomMember:O,chatroomCdnInfo:M}=m.content;return this.core.V2NIMChatroomMessageService.cdnUtil.setOptions(M),{chatroom:T,selfMember:O}}))}processLoginFailed(e){this.auth.clientSocket.doDisconnect(Ce.ACTIVE,e),this.checkLoginTerminalCode(e.code)&&(this.auth.authenticator.reset(),this.auth.authenticator.clearLastLoginClient()),this.auth.lifeCycle.processEvent("loginFail",e)}changeLoginClient(e,t){}checkAutoLogin(e){if(e)return!1;var t=ce.localStorage.getItem(this.lastLoginClientKey);if(!t)return!1;var r="",i="";try{var o=JSON.parse(t);r=get(o,"clientId"),i=get(o,"account")}catch(e){return!1}return r===this.auth.deviceId&&i===this.auth.account}checkLoginTerminalCode(e){return[lt.V2NIM_ERROR_CODE_CANCELLED,lt.V2NIM_ERROR_CODE_TIMEOUT,lt.V2NIM_ERROR_CODE_HANDSHAKE,302,317,lt.V2NIM_ERROR_CODE_FORBIDDEN,lt.V2NIM_ERROR_CODE_NOT_FOUND,lt.V2NIM_ERROR_CODE_PARAMETER_ERROR,lt.V2NIM_ERROR_CODE_MULTI_LOGIN_FORBIDDEN,422,lt.V2NIM_ERROR_CODE_IM_DISABLED,lt.V2NIM_ERROR_CODE_APPKEY_NOT_EXIST,lt.V2NIM_ERROR_CODE_BUNDLEID_CHECK_FAILED,lt.V2NIM_ERROR_CODE_APPKEY_BLOCKED,lt.V2NIM_ERROR_CODE_INVALID_TOKEN,lt.V2NIM_ERROR_CODE_ROBOT_NOT_ALLOWED,lt.V2NIM_ERROR_CODE_ACCOUNT_NOT_EXIST,lt.V2NIM_ERROR_CODE_ACCOUNT_BANNED,lt.V2NIM_ERROR_CODE_SERVICE_ADDRESS_INVALID,lt.V2NIM_ERROR_CODE_CHATROOM_DISABLED,lt.V2NIM_ERROR_CODE_CHATROOM_NOT_EXIST,lt.V2NIM_ERROR_CODE_CHATROOM_CLOSED,lt.V2NIM_ERROR_CODE_ACCOUNT_IN_CHATROOM_BLOCK_LIST].includes(e)}reset(){this.loginClients=[],this.loginClientOfThisConnection={}}clearLastLoginClient(){ce.localStorage.removeItem(this.lastLoginClientKey)}}class V2NIMLoginLifeCycle{constructor(e){this.name="V2NIMLoginLifeCycle",this.chatroomStatus=6,this.entered=!1,this.core=e,this.auth=e.auth,this.logger=e.logger}processEvent(e,t,r){var i=this.getConnectStatus();switch(e){case"connect":this.logger.log(`${this.name}::connecting`),this.setChatroomStatus(2);break;case"connectSucc":this.logger.log(`${this.name}::connect success`),this.setChatroomStatus(3);break;case"connectFail":this.logger.log(`${this.name}::connect fail`,t),this.setChatroomStatus(0,t);break;case"connectionBroken":this.logger.log(`${this.name}::connectionBroken`,t),this.setChatroomStatus(0,t);break;case"loginStart":this.logger.log(`${this.name}::login start`),this.setChatroomStatus(4);break;case"loginSucc":this.logger.log(`${this.name}::login success, verify authentication success`),this.setChatroomStatus(5),this.core.eventBus.emit("V2NIMLoginService/loginLifeCycleLoginSucc",r);break;case"loginFail":this.logger.log(`${this.name}::login fail due to verify authentication failed:`,t),this.setChatroomStatus(0,t);break;case"logout":this.logger.log(`${this.name}::logout`),this.setChatroomStatus(6),this.core.eventBus.emit("V2NIMLoginService/loginLifeCycleLogout");break;case"kicked":this.logger.log(`${this.name}::kicked`,r),this.setChatroomStatus(6,t),this.core.eventBus.emit("V2NIMLoginService/loginLifeCycleKicked");break;case"reconnectFail":this.logger.log(`${this.name}::reconnect fail`,t),this.setChatroomStatus(6,t),this.core.eventBus.emit("V2NIMLoginService/loginLifeCycleLogout");break;case"exited":if(this.logger.log(`${this.name}::exited, isEntered: ${this.entered}`,t),6===this.chatroomStatus)return;this.setChatroomStatus(this.entered?6:0,t);break;case"waiting":this.logger.log(`${this.name}::waiting to reconnect`),this.setChatroomStatus(1),2!==i&&this.auth.reconnect.attempToReLogin()}}getConnectStatus(){switch(this.chatroomStatus){case 6:case 0:return 0;case 5:case 4:case 3:return 1;case 2:return 2;case 1:return 3}}getLoginStatus(){switch(this.chatroomStatus){case 1:return 3;case 6:case 0:return 0;case 3:case 2:case 4:return 2;case 5:return 1}}setChatroomStatus(e,t){5===e&&(this.entered=!0),this.chatroomStatus!==e&&(this.chatroomStatus=e,6===e&&this.core._clearModuleData(),this.core.emit("onChatroomStatus",e,t),6===e&&this.entered&&(this.entered=!1,this.core.emit("onChatroomExited",t)))}}function replacer(e,t){return t instanceof RegExp?"__REGEXP "+t.toString():t}function validate(e,t={},r,i=!1){var o={};return Object.keys(e).forEach((n=>{var s=e[n].type,a=r?`In ${r}, `:"";if(null==t){var c=`${a}param is null or undefined`;throw i?new ValidateErrorV2({detail:{reason:c,data:{key:n},rules:"required"}}):new ValidateError(c,{key:n},"required")}if(void 0===t[n]){if(!1===e[n].required)return void(o[n]=t[n]);var _=`${a}param '${n}' is required`;throw i?new ValidateErrorV2({detail:{reason:_,data:{key:n},rules:"required"}}):new ValidateError(_,{key:n},"required")}var l=ht[s];if(l&&!l(t,n,e[n],i)){var d=`${a}param '${n}' unexpected`,E={key:n,value:t[n]};throw i?new ValidateErrorV2({detail:{reason:d,data:E,rules:JSON.stringify(e[n],replacer)}}):new ValidateError(d,E,JSON.stringify(e[n],replacer))}o[n]=t[n]})),o}var ht={string:function(e,t,r){var{allowEmpty:i,max:o,min:n,regExp:s}=r,a=e[t];return"string"==typeof a&&((!1!==i||""!==a)&&(!("number"==typeof o&&a.length>o)&&(!("number"==typeof n&&a.length<n)&&!(function isRegExp(e){return"[object RegExp]"===Object.prototype.toString.call(e)}(s)&&!s.test(a)))))},number:function(e,t,r){var{min:i,max:o}=r,n=e[t];return"number"==typeof n&&(!("number"==typeof i&&n<i)&&!("number"==typeof o&&n>o))},boolean:function(e,t){return"boolean"==typeof e[t]},file:function(e,t){return!0},enum:function(e,t,r){var{values:i}=r,o=e[t];return!i||i.indexOf(o)>-1},jsonstr:function(e,t){try{var r=JSON.parse(e[t]);return"object"==typeof r&&null!==r}catch(e){return!1}},func:function(e,t){return"function"==typeof e[t]},array:function(e,t,r,i=!1){var{itemType:o,itemRules:n,rules:s,min:a,max:c,values:_}=r,l=e[t];if(!Array.isArray(l))return!1;if("number"==typeof c&&l.length>c)return!1;if("number"==typeof a&&l.length<a)return!1;if(n)l.forEach(((e,r)=>{validate({[r]:n},{[r]:e},`${t}[${r}]`,i)}));else if(s)l.forEach(((e,r)=>validate(s,e,`${t}[${r}]`,i)));else if("enum"===o){if(_&&function difference(e,t){return t=t||[],(e=e||[]).filter((e=>-1===t.indexOf(e)))}(l,_).length)return!1}else if(o&&!l.every((e=>typeof e===o)))return!1;return!0},object:function(e,t,r,i=!1){var{rules:o,allowEmpty:n}=r,s=e[t];if("object"!=typeof s||null===s)return!1;if(o){var a=Object.keys(o),c=Object.keys(s).filter((e=>a.indexOf(e)>-1));if(!1===n&&0===c.length)return!1;validate(o,s,t,i)}return!0}},ut={updateParams:{type:"object",allowEmpty:!1,rules:{roomName:{type:"string",required:!1,allowEmpty:!1},announcement:{type:"string",required:!1},liveUrl:{type:"string",required:!1},serverExtension:{type:"string",required:!1},notificationEnabled:{type:"boolean",required:!1},notificationExtension:{type:"string",required:!1}}},antispamConfig:{type:"object",required:!1,rules:{antispamBusinessId:{type:"string",required:!1}}}},mt={locationInfo:{type:"object",rules:{x:{type:"number"},y:{type:"number"},z:{type:"number"}}},distance:{type:"number"}},gt={updateParams:{type:"object",allowEmpty:!1,rules:{tags:{type:"array",required:!1,itemType:"string"},notifyTargetTags:{type:"string",required:!1},notificationEnabled:{type:"boolean",required:!1},notificationExtension:{type:"string",required:!1}}}},pt={targetTag:{type:"string",required:!0,allowEmpty:!1},notifyTargetTags:{type:"string",required:!1},duration:{type:"number",required:!1},notificationEnabled:{type:"boolean",required:!1},notificationExtension:{type:"string",required:!1}},It={roomId:{allowEmpty:!1,type:"string"},enterParams:{type:"object",required:!0,rules:{anonymousMode:{required:!1,type:"boolean"},accountId:{required:!1,type:"string",allowEmpty:!1},token:{required:!1,type:"string",allowEmpty:!1},roomNick:{required:!1,type:"string"},roomAvatar:{required:!1,type:"string"},loginOption:{type:"object",required:!1,rules:{authType:{type:"enum",required:!1,values:[0,1,2]},tokenProvider:{required:!1,type:"func"},loginExtensionProvider:{required:!1,type:"func"},routeConfig:{type:"object",required:!1,rules:{routeEnabled:{type:"boolean",required:!1},routeEnv:{type:"string",required:!1}}}}},linkProvider:{type:"func"},serverExtension:{type:"string",required:!1,allowEmpty:!1},notificationExtension:{type:"string",required:!1,allowEmpty:!1},tagConfig:{type:"object",required:!1,rules:{notifyTargetTags:{type:"string",required:!1},tags:{type:"array",required:!1,itemType:"string"}}},locationConfig:{type:"object",required:!1,rules:mt},antispamConfig:{type:"object",required:!1,rules:{antispamBusinessId:{type:"string",required:!1,allowEmpty:!1}}}}}};class V2ChatroomService extends Ie{constructor(e,t){super(),this.name=e,this.logger=t.logger,this.core=t}emit(e,...t){this.logger.debug(`${this.name}::emit event: '${e.toString()}',`,void 0!==t[0]?t[0]:"",void 0!==t[1]?t[1]:"",void 0!==t[2]?t[2]:"");try{return super.emit(e,...t)}catch(t){return setTimeout((()=>{throw this.logger.error(`${this.name}::emit throw error in setTimeout. event: ${e.toString()}. Error`,t),t}),0),!1}}process(e){var t=this[e.cmd+"Handler"];if("function"==typeof t){if(e.error)return this.logger.error(`${e.cmd}::recvError`,e.error),Promise.reject(e.error);try{var r=t.call(this,e);return Promise.resolve(r)}catch(e){return Promise.reject(e)}}var i=get(e,"error.detail.ignore");return e.error&&!i?Promise.reject(e.error):Promise.resolve(e)}}class V2NIMChatroomLoginServiceImpl extends V2ChatroomService{constructor(e){super("V2NIMChatroomLoginService",e),this.roomId="",this.token="",this.loginExt="",this.authType=0,this.linkAddressArray=[],this.currLinkIdx=-1,this.isAnonymous=!1,this.processId="",this.connectParams={forceMode:!1},registerParser({cmdMap:ot,cmdConfig:at}),e.auth=this,this.previousLoginManager=new PromiseManager,this.doLoginStepsManager=new PromiseManager,this.loginTimerManager=new TimerManager,this.lifeCycle=new V2NIMLoginLifeCycle(e),this.reconnect=new V2NIMLoginReconnect(e),this.authenticator=new V2NIMLoginAuthenticator(e)}get clientSocket(){return this.core.clientSocket}get account(){return this.core.options.account}get appkey(){return this.core.options.appkey}get deviceId(){return this.core.config.deviceId}get clientSession(){return this.core.config.clientSession}getNextLink(){return this.currLinkIdx=(this.currLinkIdx+1)%this.linkAddressArray.length,this.linkAddressArray[this.currLinkIdx]}getCurrLink(){return this.linkAddressArray[this.currLinkIdx]}reset(){this.roomId="",this.token="",this.loginExt="",this.processId="",this.reconnect.reset(),this.authenticator.reset(),this.authenticator.clearLastLoginClient()}login(e,t,r){return __awaiter(this,void 0,void 0,(function*(){if(validate(It,{appkey:e,roomId:t,enterParams:r},"",!0),0===this.getLoginStatus())this.logger.log(`V2NIMChatroomLoginService::login:allowLogin. appkey:${e};roomId:${t};accountId:${r.accountId} `);else{if(1===this.getLoginStatus())return this.smoothForLogined(e,t,r);if(2===this.getLoginStatus())return this.smoothForLogining(e,t,r)}this.processId=ve(),yield this.setLoginParams(e,t,r),this.loginTimerManager.destroy(),this.loginTimerManager.addTimer((()=>{var e=new V2NIMErrorImpl({code:lt.V2NIM_ERROR_CODE_TIMEOUT,detail:{reason:"Login API timeout"}});this.doLoginStepsManager.clear(e),this.previousLoginManager.clear(e),this.originLoginPromise=void 0,this.lifeCycle.processEvent("exited",e)}),r.timeout?1e3*r.timeout:6e4,1);try{var i=yield this.multiTryDoLogin();return this.core.emit("onChatroomEntered"),this.loginTimerManager.destroy(),i}catch(e){throw this.loginTimerManager.destroy(),e}}))}multiTryDoLogin(e){return __awaiter(this,void 0,void 0,(function*(){for(var t=this.core.timeOrigin.getTimeNode(),r=new V2NIMErrorImpl({code:lt.V2NIM_ERROR_CODE_INTERNAL,detail:{reason:"loginFailed"}}),i=0;i<this.linkAddressArray.length;i++){var o=`V2NIMChatroomLoginService:: ${i+1}th login attempt.`;i>0?this.logger.warn(o):this.logger.log(o);try{this.originLoginPromise=e||this.doLogin(!1),e=void 0;var n=yield this.previousLoginManager.add(this.originLoginPromise);return this.doLoginStepsManager.clear(),this.previousLoginManager.clear(),this.originLoginPromise=void 0,this.reportLoginSucc(t),n}catch(e){if(r=e||r,this.logger.error(`V2NIMChatroomLoginService::login failed, times of login try: ${i}, err.code: ${null==r?void 0:r.code}, err.message: "${null==r?void 0:r.message}"`),this.reportLoginFail(t,r),this.reconnect.clearReconnectTimer(),this.checkLoginTerminalCode(r&&r.code)||r&&r.code===lt.V2NIM_ERROR_CODE_SERVER_UNIT_ERROR)throw this.lifeCycle.processEvent("exited",r),r}}throw this.lifeCycle.processEvent("exited",r),r}))}doLogin(e){var t;return __awaiter(this,void 0,void 0,(function*(){var r=!!e||this.authenticator.checkAutoLogin(this.connectParams.forceMode);yield this.doLoginStepsManager.add(this.clientSocket.connect(this.getNextLink(),e));var i=yield this.doLoginStepsManager.add(this.authenticator.verifyAuthentication(r));this.lifeCycle.processEvent("loginSucc",void 0,Object.assign(Object.assign({},i),{isReconnect:e})),this.clientSocket.resetSocketConfig(),this.reconnect.reset(),this.clientSocket.ping(),this.core.abtest.abtRequest(),this.core.V2NIMClientAntispamUtil.downloadLocalAntiSpamVocabs();try{yield this.core.cloudStorage.init(null===(t=i.selfMember)||void 0===t?void 0:t.enterTime)}catch(e){this.logger.warn("doLogin::cloudStorage init error",e)}return this.prevLoginResult=i,i}))}reportLoginSucc(e){return __awaiter(this,void 0,void 0,(function*(){var t=this.core.timeOrigin.getNTPTime(),r=Date.now()-e.time;this.core.timeOrigin.checkNodeReliable(e)&&(r=t-this.core.timeOrigin.getNTPTime(e));var{net_connect:i}=yield ce.net.getNetworkStatus();this.core.reporter.report("chatroomLogin",{accid:this.account,roomId:this.roomId,serverIps:this.linkAddressArray,currentServerIp:this.getCurrLink(),rt:r,result:200,failReason:"",time:t,net_connect:i,binary_websocket:this.core.config.binaryWebsocket})}))}reportLoginFail(e,t){return __awaiter(this,void 0,void 0,(function*(){var r=get(t,"code")||get(t,"detail.rawError.code")||0,i=get(t,"detail.rawError.message")||get(t,"message")||"login failed";if(r!==lt.V2NIM_ERROR_CODE_CANCELLED){var o=this.core.timeOrigin.getNTPTime(),n=Date.now()-e.time;this.core.timeOrigin.checkNodeReliable(e)&&(n=o-this.core.timeOrigin.getNTPTime(e));var{net_connect:s}=yield ce.net.getNetworkStatus();this.core.reporter.report("chatroomLogin",{accid:this.account,roomId:this.roomId,serverIps:this.linkAddressArray,currentServerIp:this.getCurrLink(),rt:n,result:r,failReason:i,time:o,net_connect:s,binary_websocket:this.core.config.binaryWebsocket})}}))}smoothForLogined(e,t,r){return __awaiter(this,void 0,void 0,(function*(){var i=this.checkIsSameLogin(e,t,r);return this.logger.warn(`V2NIMChatroomLoginService::smoothForLogined:Logined, isSameLogin ${i}`),i?this.prevLoginResult:(yield this.logout(),this.login(e,t,r))}))}smoothForLogining(e,t,r){return __awaiter(this,void 0,void 0,(function*(){var i=this.checkIsSameLogin(e,t,r);if(this.previousLoginManager.clear(),this.reconnect.reset(),i){if(!this.originLoginPromise)throw new V2NIMErrorImpl({code:lt.V2NIM_ERROR_CODE_INTERNAL,detail:{reason:"NoPreviousLoginExists"}});return this.reconnect.reset(),yield Promise.resolve(),yield this.multiTryDoLogin(this.originLoginPromise)}return this.doLoginStepsManager.clear(),this.clientSocket.doDisconnect(Ce.ACTIVE,"Aborted"),this.reset(),this.lifeCycle.processEvent("logout",new V2NIMErrorImpl({code:lt.V2NIM_ERROR_CODE_DISCONNECT,detail:{reason:"disconnect due to logout. aborted previous login."}})),yield Promise.resolve(),this.login(e,t,r)}))}checkIsSameLogin(e,t,r){var i,o,n,s,a,c,_,l=void 0!==r.anonymousMode&&r.anonymousMode,d=(null===(i=r.loginOption)||void 0===i?void 0:i.authType)||0,E=JSON.stringify((null===(n=null===(o=this.enterParams)||void 0===o?void 0:o.tagConfig)||void 0===n?void 0:n.tags)||[]),h=JSON.stringify((null===(s=r.tagConfig)||void 0===s?void 0:s.tags)||[]),u=JSON.stringify((null===(a=this.enterParams)||void 0===a?void 0:a.locationConfig)||{}),m=JSON.stringify(r.locationConfig||{});return this.appkey===e&&this.roomId===t&&this.authType===d&&this.isAnonymous===l&&this.account===r.accountId&&(null===(c=this.enterParams)||void 0===c?void 0:c.roomNick)===r.roomNick&&(null===(_=this.enterParams)||void 0===_?void 0:_.roomAvatar)===r.roomAvatar&&E===h&&u===m}logout(){return __awaiter(this,void 0,void 0,(function*(){this.doLoginStepsManager.clear(),this.previousLoginManager.clear(),this.loginTimerManager.destroy(),this.originLoginPromise=void 0;var e=this.getConnectStatus(),t=this.getLoginStatus(),r=new V2NIMErrorImpl({code:lt.V2NIM_ERROR_CODE_DISCONNECT,detail:{reason:"disconnect due to logout"}});switch(t){case 1:try{yield this.clientSocket.sendCmd("v2ChatroomLogout",void 0,{timeout:1e3}),this.clientSocket.doDisconnect(Ce.ACTIVE,"UserActiveDisconnect"),this.lifeCycle.processEvent("logout",r)}catch(e){this.logger.error("Instance::disconnect sendCmd:logout error",e),this.clientSocket.doDisconnect(Ce.ACTIVE,"UserActiveDisconnect"),this.lifeCycle.processEvent("logout",r)}break;case 2:this.clientSocket.doDisconnect(Ce.ACTIVE,"UserActiveDisconnect"),this.lifeCycle.processEvent("logout",r);break;case 3:this.clientSocket.doDisconnect(Ce.ACTIVE,"UserActiveDisconnect"),this.core._clearModuleData(),this.lifeCycle.processEvent("logout",r);break;case 0:throw this.core._clearModuleData(),new V2NIMErrorImpl({code:lt.V2NIM_ERROR_CODE_ILLEGAL_STATE,detail:{reason:`Illegal logout. loginStatus ${t}. connectStatus ${e}`}});default:throw this.core._clearModuleData(),new V2NIMErrorImpl({code:lt.V2NIM_ERROR_CODE_ILLEGAL_STATE,detail:{reason:`Illegal logout. illegal status: loginStatus ${t}. connectStatus ${e}`}})}}))}getConnectStatus(){return this.lifeCycle.getConnectStatus()}getLoginStatus(){return this.lifeCycle.getLoginStatus()}getLoginUser(){return this.account}getRoomId(){return this.roomId}checkLoginTerminalCode(e){return this.authenticator.checkLoginTerminalCode(e)}updateLinkAddress(){var e;return __awaiter(this,void 0,void 0,(function*(){if(null===(e=this.enterParams)||void 0===e?void 0:e.linkProvider)try{this.linkAddressArray=yield this.enterParams.linkProvider(this.account,this.roomId),this.currLinkIdx=-1,(e=>{if(!Array.isArray(e))throw new V2NIMErrorImpl({code:400,message:"linkAddressArray must be an array"});if(0===e.length)throw new V2NIMErrorImpl({code:400,message:"linkAddressArray must not be empty"});e.forEach((e=>{if(!e)throw new V2NIMErrorImpl({code:400,message:"linkAddress must not be empty"})}))})(this.linkAddressArray)}catch(e){throw new V2NIMErrorImpl({code:lt.V2NIM_ERROR_CODE_INTERNAL,detail:{reason:"linkProvider error: "+e}})}}))}updateDynamicParamters(e){var t,r,i,o;return __awaiter(this,void 0,void 0,(function*(){if(this.enterParams){if(e&&(yield this.updateLinkAddress()),0!==this.authType&&(null===(r=null===(t=this.enterParams)||void 0===t?void 0:t.loginOption)||void 0===r?void 0:r.tokenProvider)){try{this.token=yield this.enterParams.loginOption.tokenProvider(this.appkey,this.roomId,this.account)}catch(e){throw new V2NIMErrorImpl({code:lt.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"tokenProvider error: "+e}})}if(null===this.token||void 0===this.token)throw new V2NIMErrorImpl({code:lt.V2NIM_ERROR_CODE_CALLBACK_FAILED,detail:{reason:"tokenProvider should not return null or undefined when authType === 1 or authType === 2"}});if(!this.token&&1===this.authType)throw new V2NIMErrorImpl({code:lt.V2NIM_ERROR_CODE_CALLBACK_FAILED,detail:{reason:"tokenProvider should not return empty string when authType === 1"}})}if(null===(o=null===(i=this.enterParams)||void 0===i?void 0:i.loginOption)||void 0===o?void 0:o.loginExtensionProvider){try{this.loginExt=yield this.enterParams.loginOption.loginExtensionProvider(this.appkey,this.roomId,this.account)}catch(e){throw new V2NIMErrorImpl({code:lt.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"loginExtensionProvider error: "+e}})}if((null===this.loginExt||void 0===this.loginExt)&&2===this.authType)throw new V2NIMErrorImpl({code:lt.V2NIM_ERROR_CODE_CALLBACK_FAILED,detail:{reason:"loginExtensionProvider should not return null or undefined when authType === 2"}})}}}))}setLoginParams(e,t,r){var i,o;return __awaiter(this,void 0,void 0,(function*(){if(this.reset(),this.roomId=t,this.enterParams=r,this.core.options.appkey=e,this.core.options.tags=(null===(i=r.tagConfig)||void 0===i?void 0:i.tags)||[],r.token&&(this.token=r.token),r.anonymousMode&&!r.accountId?this.core.options.account=`nimanon_${ve()}`:this.core.options.account=r.accountId,this.isAnonymous=void 0!==r.anonymousMode&&r.anonymousMode,this.isAnonymous&&!r.roomNick){if(void 0!==r.roomNick)throw new V2NIMErrorImpl({code:lt.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"roomNick is required when anonymousMode is true"}});r.roomNick=this.core.options.account}this.authType=(null===(o=r.loginOption)||void 0===o?void 0:o.authType)||0,yield this.updateDynamicParamters(!0)}))}v2LoginHandler(e){if(e.error)throw this.clientSocket.doDisconnect(Ce.ACTIVE,e.error),e.error;return e}v2LoginClientChangeHandler(e){this.authenticator.changeLoginClient(parseInt(e.content.state),e.content.datas)}nimLoginClientChangeHandler(e){this.authenticator.changeLoginClient(parseInt(e.content.state),e.content.datas)}v2ChatroomBeKickedHandler(e){var t=e.content,{kickedReason:r,serverExtension:i}=t;this.clientSocket.doDisconnect(Ce.KICKED,r),this.core._clearModuleData(),this.lifeCycle.processEvent("kicked",new V2NIMErrorImpl({code:lt.V2NIM_ERROR_CODE_DISCONNECT,detail:{reason:"disconnect due to kicked"}}),r),this.core.emit("onChatroomKicked",{kickedReason:r,serverExtension:i})}}var Nt={user_id:"",trace_id:"",action:7,exception_service:6,duration:0,start_time:0,state:1,extension:[]};class ReporterHookLinkKeep{constructor(e,t){this.traceData=Nt,this.core=e,this.traceData=Object.assign({},Nt,t),this.traceData.extension=[]}reset(){this.traceData=Object.assign({},Nt),this.traceData.extension=[]}start(){var e,t;this.reset(),this.traceData.user_id=this.core.account,this.traceData.trace_id=(null===(t=null===(e=this.core.clientSocket)||void 0===e?void 0:e.socket)||void 0===t?void 0:t.sessionId)||"",this.traceData.start_time=(new Date).getTime()}update(e){return __awaiter(this,void 0,void 0,(function*(){var{net_type:t,net_connect:r}=yield ce.net.getNetworkStatus();this.traceData.extension.push(Object.assign({code:0,foreground:!0,foreg_backg_switch:!1,net_type:t,net_connect:r},e))}))}end(e){var t=this.traceData.extension[0],r=this.traceData.extension[1];if(t&&0===t.operation_type&&r&&1===r.operation_type){var i=t.net_type!==r.net_type||t.net_connect!==r.net_connect;if(e||!i)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 Tt="V2NIMChatroomInfoService",Ot={"36_13":"v2GetChatroomInfo","36_14":"v2UpdateChatroomInfo","36_30":"v2SetTempChatBannedByTag","13_33":"v2UpdateChatroomLocation","36_34":"v2UpdateChatroomTags"},Mt={tags:{id:1,converter:e=>JSON.stringify(e)},notifyTargetTags:2,notificationEnabled:{id:3,converter:e=>+e},notificationExtension:4},ft={v2GetChatroomInfo:{sid:36,cid:13,service:Tt,response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(nt)}]},v2UpdateChatroomInfo:{sid:36,cid:14,service:Tt,params:[{type:"Property",name:"chatroom",reflectMapper:nt},{type:"Bool",name:"notificationEnabled"},{type:"String",name:"notificationExtension"}]},v2SetTempChatBannedByTag:{sid:36,cid:30,service:Tt,params:[{type:"Property",name:"tag",reflectMapper:{targetTag:1,duration:2,notificationEnabled:{id:3,converter:e=>+e},notificationExtension:4,notifyTargetTags:5}}]},v2UpdateChatroomLocation:{sid:13,cid:33,service:Tt,params:[{type:"Property",name:"tag",reflectMapper:{x:1,y:2,z:3,distance:4}}]},v2UpdateChatroomTags:{sid:36,cid:34,service:Tt,params:[{type:"Property",name:"tag",reflectMapper:Mt}]}};class Service{constructor(e,t){this.name=e,this.core=t,this.name=e,this.logger=t.logger,this.core=t}process(e){var t=this[e.cmd+"Handler"];if("function"==typeof t)return t.call(this,e);var r=get(e,"error.detail.ignore");return e.error&&!r?Promise.reject(e.error):Promise.resolve(e)}}class V2NIMChatroomInfoModel{constructor(){this.chatroomInfo=null}reset(){this.chatroomInfo=null}}class V2NIMChatroomInfoServiceImpl extends Service{constructor(e){super("V2NIMChatroomInfoService",e),registerParser({cmdMap:Ot,cmdConfig:ft}),this.model=new V2NIMChatroomInfoModel,this.setListener()}setListener(){this.core.eventBus.on("V2NIMChatroomMessageService/onReceiveNotification",((e,t)=>__awaiter(this,void 0,void 0,(function*(){var r,i;if(6===e.attachment.type){var o=null===(r=t.data.roomInfo)||void 0===r?void 0:r.extension,n=null===(i=t.data.roomInfo)||void 0===i?void 0:i.queueLevel,s=Object.assign(Object.assign(Object.assign({},t.data.roomInfo||{}),void 0!==o?{serverExtension:o}:{}),void 0!==n?{queueLevelMode:n}:{});delete s.extension,delete s.queueLevel;var a=yield this._updateChatroomInfo(s);this.core.V2NIMChatroomService.emit("onChatroomInfoUpdated",a)}}))))}reset(){this.model.reset()}getChatroomInfo(){return this.model.chatroomInfo}updateChatroomInfo(e,t){return __awaiter(this,void 0,void 0,(function*(){if(validate(ut,{updateParams:e,antispamConfig:t},"",!0),!(e.announcement||e.liveUrl||e.roomName||e.serverExtension))throw new V2NIMErrorImpl({code:lt.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"updateParams.announcement, updateParams.liveUrl, updateParams.roomName, updateParams.serverExtension 至少有一个不为空"}});var r=void 0===e.notificationEnabled||e.notificationEnabled;yield this.core.sendCmd("v2UpdateChatroomInfo",{chatroom:e,notificationEnabled:r,notificationExtension:e.notificationExtension||""}),this._updateChatroomInfo(function pick(e,t){e=e||{};var r={};return(t=t||[]).forEach((t=>{void 0!==e[t]&&(r[t]=e[t])})),r}(e,["announcement","liveUrl","roomName","serverExtension"]))}))}updateChatroomLocationInfo(e){return __awaiter(this,void 0,void 0,(function*(){validate(mt,e,"",!0),yield this.core.sendCmd("v2UpdateChatroomLocation",{tag:Object.assign(Object.assign({},e.locationInfo),{distance:e.distance})})}))}updateChatroomTags(e){return __awaiter(this,void 0,void 0,(function*(){if(validate(gt,{updateParams:e},"",!0),!e.tags&&void 0===e.notifyTargetTags)throw new V2NIMErrorImpl({code:lt.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"updateParams.tags, updateParams.notifyTargetTags 至少有一个不为空"}});e.notificationEnabled=void 0===e.notificationEnabled||e.notificationEnabled,yield this.core.sendCmd("v2UpdateChatroomTags",{tag:e})}))}setTempChatBannedByTag(e){return __awaiter(this,void 0,void 0,(function*(){validate(pt,e,"",!0),e.notificationEnabled=void 0===e.notificationEnabled||e.notificationEnabled,yield this.core.sendCmd("v2SetTempChatBannedByTag",{tag:e})}))}_updateChatroomInfo(e){return __awaiter(this,void 0,void 0,(function*(){return this.model.chatroomInfo?Object.assign(this.model.chatroomInfo,e):yield this._getChatroomInfoAsync(),this.model.chatroomInfo}))}_getChatroomInfoAsync(){return __awaiter(this,void 0,void 0,(function*(){var e=yield this.core.sendCmd("v2GetChatroomInfo");this._setChatroomInfo(e.content.data)}))}_setChatroomInfo(e){this.model.chatroomInfo=e}}var St,Rt,At={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)"}},Ct={accessKeyId:"",secretAccessKey:"",sessionToken:"",region:"",maxRetries:0,bucket:"",objectName:"",token:"",shortUrl:""};function getUploadResponseFormat(e="file"){var t=At[e]||{};return JSON.stringify(t).replace(/"/gi,'\\"')}!function(e){e[e.nos=1]="nos",e[e.s3=2]="s3"}(St||(St={})),function(e){e[e.dontNeed=-1]="dontNeed",e[e.time=2]="time",e[e.urls=3]="urls"}(Rt||(Rt={}));var vt={chunkUploadHost:"https://wannos-web.127.net",chunkUploadHostBackupList:["https://fileup.chatnos.com","https://oss.chatnos.com"],commonUploadHost:"https://fileup.chatnos.com",commonUploadHostBackupList:["https://upload.chatnos.com","https://oss.chatnos.com"],chunkMaxSize:4194304e4,commonMaxSize:104857600,uploadReplaceFormat:"https://{host}/{object}",cdn:{defaultCdnDomain:"nim-nosdn.netease.im",cdnDomain:"",bucket:"nim",objectNamePrefix:""},downloadUrl:"https://{bucket}-nosdn.netease.im/{object}",downloadHostList:["nos.netease.com"],nosCdnEnable:!0,isNeedToGetUploadPolicyFromServer:!0};class NOS{constructor(e,t){this.nosCdnHostTimer=0,this.nosErrorCount=0,this.core=e,this.cloudStorage=t}get config(){return this.cloudStorage.config}reset(){this.nosErrorCount=0}getNosAccessToken(e){return __awaiter(this,void 0,void 0,(function*(){var t=get(yield this.core.sendCmd("getNosAccessToken",{tag:e}),"content.nosAccessTokenTag.token"),r=e.url;return{token:t,url:-1!==r.indexOf("?")?r+"&token="+t:r+"?token="+t}}))}deleteNosAccessToken(e){return __awaiter(this,void 0,void 0,(function*(){yield this.core.sendCmd("deleteNosAccessToken",{tag:e})}))}nosUpload(e,t,r){var i,o,n,s,a,c,_,l,d,E;return __awaiter(this,void 0,void 0,(function*(){var h=get(this.core,"config.cdn.bucket"),u={tag:e.nosScenes||h||"nim"};e.nosSurvivalTime&&(u.expireSec=e.nosSurvivalTime);var m,g=this.core.adapters.getFileUploadInformation(e);if(g&&g.complete&&t.destroy(),!r&&!g)try{m=yield this.core.sendCmd("getNosToken",{responseBody:getUploadResponseFormat(e.type),nosToken:u})}catch(e){if(this.core.logger.error("uploadFile:: getNosToken error",e),t.destroy(),e instanceof V2NIMErrorImpl)throw e;throw new UploadError({code:"v2"===get(this.core,"options.apiVersion")?de.V2NIM_ERROR_CODE_FILE_UPLOAD_FAILED:400,detail:{reason:"getNosToken error",rawError:e,curProvider:1}})}var p=this.config.uploadReplaceFormat.replace("{bucket}",this.config.cdn.bucket).replace("{host}",this.config.cdn.cdnDomain||this.config.cdn.defaultCdnDomain).replace("{object}",g?null===(i=g.uploadInfo)||void 0===i?void 0:i.objectName:r?null==r?void 0:r.objectName:m.content.nosToken.objectName),I="";r&&r.shortUrl&&(I=r.shortUrl),(null===(s=null===(n=null===(o=null==g?void 0:g.uploadInfo)||void 0===o?void 0:o.payload)||void 0===n?void 0:n.mixStoreToken)||void 0===s?void 0:s.shortUrl)&&(I=g.uploadInfo.payload.mixStoreToken.shortUrl);var N,T=I||p;try{var O=g?{token:null===(a=null==g?void 0:g.uploadInfo)||void 0===a?void 0:a.token,bucket:null===(c=null==g?void 0:g.uploadInfo)||void 0===c?void 0:c.bucketName,objectName:null===(_=null==g?void 0:g.uploadInfo)||void 0===_?void 0:_.objectName}:r||m.content.nosToken;this.core.logger.log("uploadFile:: uploadFile params",{nosToken:O,chunkUploadHost:this.config.chunkUploadHost,chunkUploadHostBackupList:this.config.chunkUploadHostBackupList,commonUploadHost:this.config.commonUploadHost,commonUploadHostBackupList:this.config.commonUploadHostBackupList,platform:ce.platform});var M="BROWSER"===ce.platform?this.config.chunkUploadHost:`${this.config.commonUploadHost}/${O&&O.bucket}`,f="UNIAPP"===ce.platform||"MINIAPP"===(null===(l=ce.getSystemInfo())||void 0===l?void 0:l.libEnv)?4:r?2:0,S=e.filePath?e.filePath:"object"==typeof e.file?e.file.name:"";t.update({remote_addr:M,operation_type:f}),S&&t.update({local_file:S}),N=yield this.core.adapters.uploadFile(Object.assign(Object.assign(Object.assign(Object.assign({},e),{nosToken:O,chunkUploadHost:this.config.chunkUploadHost,chunkUploadHostBackupList:this.config.chunkUploadHostBackupList,commonUploadHost:this.config.commonUploadHost,commonUploadHostBackupList:this.config.commonUploadHostBackupList,maxSize:e.maxSize||this.config.chunkMaxSize}),r?{payload:{mixStoreToken:r}}:{}),{onUploadInfo:e=>{t.update(Object.assign({},e))}}),t)}catch(i){this.core.logger.error("uploadFile::nos uploadFile error:",i);var R="v2"===get(this.core,"options.apiVersion");if(i.code===de.V2NIM_ERROR_CODE_CANCELLED||10499===i.errCode)throw new UploadError({code:R?de.V2NIM_ERROR_CODE_CANCELLED:400,detail:{reason:get(i,"message")||"Request abort",rawError:i,curProvider:1}});if(R&&i.errCode===de.V2NIM_ERROR_CODE_FILE_OPEN_FAILED)throw new V2NIMErrorImpl({code:de.V2NIM_ERROR_CODE_FILE_OPEN_FAILED,detail:{reason:get(i,"message")||"Read file failed",rawError:i,curProvider:1}});var{net_connect:A}=yield ce.net.getNetworkStatus();if(!1===A)throw new UploadError({code:"v2"===get(this.core,"options.apiVersion")?de.V2NIM_ERROR_CODE_FILE_UPLOAD_FAILED:400,detail:{reason:"No network",rawError:i,curProvider:1}});if(r){if(this.nosErrorCount<=0){try{this.cloudStorage.mixStorage._addCircuitTimer()}catch(t){throw new UploadError({code:"v2"===get(this.core,"options.apiVersion")?de.V2NIM_ERROR_CODE_FILE_UPLOAD_FAILED:400,detail:{reason:"All upload attempts failed",rawError:t,curProvider:this.cloudStorage.mixStorage.curProvider,mixStorePolicy:this.cloudStorage.mixStorage.mixStorePolicy,file:e.file||e.filePath}})}return this.nosErrorCount=get(this.cloudStorage,"mixStorePolicy.nosPolicy.uploadConfig.retryPolicy.retry"),this.cloudStorage._uploadFile(e,t)}return this.nosErrorCount--,this.nosUpload(e,t,r)}throw new UploadError({code:"v2"===get(this.core,"options.apiVersion")?de.V2NIM_ERROR_CODE_FILE_UPLOAD_FAILED:400,detail:{reason:"NOS attempts failed",rawError:i,curProvider:1}})}var C=null==N?void 0:N.type,v=C&&C.indexOf("/")>-1?C.slice(0,C.indexOf("/")):"";v||(v=e.type||"");var y,D={image:"imageInfo",video:"vinfo",audio:"vinfo"};if(!D[v])return Object.assign({url:T},N);if(N.w&&N.h||N.dur)return Object.assign({url:T},N);try{y=yield this.core.adapters.request(`${p}?${D[v]}`,{method:"GET",dataType:"json",timeout:5e3},{exception_service:3})}catch(e){var V=e;return t.update({exception:`Fetch media info failed;url:${p}?${D[v]};errMsg:${(null===(d=V.detail)||void 0===d?void 0:d.reason)||V.message}`,external_code:V.code}),this.core.logger.error("uploadFile:: fetch file info error",e),Object.assign({url:T},N)}if(y){var{data:L}=y,b="imageInfo"===D[v]?L:null===(E=null==L?void 0:L.GetVideoInfo)||void 0===E?void 0:E.VideoInfo;return pickBy({url:T,name:N.name,size:N.size,ext:N.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(e){return void 0!==e}))}return Object.assign({url:T},N)}))}_getNosCdnHost(){var e;return __awaiter(this,void 0,void 0,(function*(){var t;try{t=yield this.core.sendCmd("getNosCdnHost")}catch(e){return void this.core.logger.error("getNosCdnHost::error",e)}if(t){var r=null===(e=null==t?void 0:t.content)||void 0===e?void 0:e.nosConfigTag,i=parseInt(null==r?void 0:r.expire);0!==i&&r.cdnDomain?-1===i?(this.config.cdn.bucket=r.bucket,this.config.cdn.cdnDomain=r.cdnDomain,this.config.cdn.objectNamePrefix=r.objectNamePrefix):(this.config.cdn.bucket=r.bucket,this.config.cdn.cdnDomain=r.cdnDomain,this.config.cdn.objectNamePrefix=r.objectNamePrefix,this.nosCdnHostTimer=this.core.timerManager.addTimer((()=>{this._getNosCdnHost()}),1e3*i)):(this.config.cdn.bucket="",this.config.cdn.cdnDomain="",this.config.cdn.objectNamePrefix="")}}))}}var yt={"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"},Dt={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}},Vt={getNosToken:{sid:6,cid:2,service:"cloudStorage",params:[{type:"String",name:"responseBody"},{type:"Property",name:"nosToken",entity:"nosToken",reflectMapper:Dt.nosToken}],response:[{type:"Property",name:"nosToken",reflectMapper:invertSerializeItem(Dt.nosToken)}]},getOriginUrl:{sid:6,cid:22,service:"cloudStorage",params:[{type:"Property",name:"nosSafeUrlTag",reflectMapper:Dt.nosSafeUrlTag}],response:[{type:"Property",name:"nosSafeUrlTag",reflectMapper:invertSerializeItem(Dt.nosSafeUrlTag)}]},getNosCdnHost:{sid:6,cid:26,service:"cloudStorage",response:[{type:"Property",name:"nosConfigTag",reflectMapper:invertSerializeItem(Dt.nosConfigTag)}]},getGrayscaleConfig:{sid:6,cid:27,service:"cloudStorage",params:[{type:"Property",name:"config"}],response:[{type:"Property",name:"grayConfigTag",reflectMapper:invertSerializeItem(Dt.grayConfigTag)}]},getMixStorePolicy:{sid:6,cid:28,service:"cloudStorage",params:[{type:"LongArray",name:"supportType"}],response:[{type:"Property",name:"mixStorePolicyTag",reflectMapper:invertSerializeItem(Dt.mixStorePolicyTag)}]},getMixStoreToken:{sid:6,cid:29,service:"cloudStorage",params:[{type:"Property",name:"mixStoreTokenReqTag",reflectMapper:Dt.mixStoreTokenReqTag}],response:[{type:"Property",name:"mixStoreTokenResTag",reflectMapper:invertSerializeItem(Dt.mixStoreTokenResTag)}]},getFileAuthToken:{sid:6,cid:30,service:"cloudStorage",params:[{type:"Property",name:"mixStoreAuthTokenReqTag",reflectMapper:Dt.mixStoreAuthTokenReqTag}],response:[{type:"Property",name:"mixStoreAuthTokenResTag",reflectMapper:invertSerializeItem(Dt.mixStoreAuthTokenResTag)}]},getNosAccessToken:{sid:6,cid:24,service:"cloudStorage",params:[{type:"Property",name:"tag",reflectMapper:Dt.nosAccessTokenTag}],response:[{type:"Property",name:"tag",reflectMapper:invertSerializeItem(Dt.nosAccessTokenTag)}]},deleteNosAccessToken:{sid:6,cid:25,service:"cloudStorage",params:[{type:"Property",name:"tag",reflectMapper:Dt.nosAccessTokenTag}]}};class MixStorage{constructor(e,t){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=e,this.cloudStorage=t,this.logger=e.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(e,t){var r;return __awaiter(this,void 0,void 0,(function*(){if(ce.localStorage)try{ce.localStorage.getItem&&ce.localStorage.getItem(this.GRAYKEY)&&(this.grayConfig=JSON.parse(ce.localStorage.getItem(this.GRAYKEY))[e])}catch(e){ce.localStorage.getItem(this.GRAYKEY)&&this.core.logger.error("uploadFile:: JSON.parse grayscaleConfig error ",e)}if(!this.grayConfig||this.grayConfig.timeStamp+1e3*this.grayConfig.ttl<t){var i=yield this.core.sendCmd("getGrayscaleConfig",{config:{}});if(i.content&&i.content.grayConfigTag){this.logger.log("uploadFile::getAppGrayConfigRequest success ");try{this.grayConfig=JSON.parse(i.content.grayConfigTag.config),this.grayConfig.ttl=JSON.parse(i.content.grayConfigTag.ttl)}catch(e){this.logger.error("getGrayscaleConfig error",e)}if(!this.grayConfig)return;var o=ce.localStorage.getItem(this.GRAYKEY)?JSON.parse(ce.localStorage.getItem(this.GRAYKEY)):{};this.grayConfig.timeStamp=(new Date).getTime(),o[e]=this.grayConfig,ce.localStorage.setItem(this.GRAYKEY,JSON.stringify(o))}else this.logger.log("uploadFile:: result grayConfig:",i.content)}(null===(r=this.grayConfig)||void 0===r?void 0:r.mixStoreEnable)&&(yield this._getMixStorePolicy(e))}))}_getMixStorePolicy(e){return __awaiter(this,void 0,void 0,(function*(){var t=(new Date).getTime();if(ce.localStorage)try{if(this.mixStorePolicy=JSON.parse(ce.localStorage.getItem(this.MIXSTOREKEY))[e],this.curProvider=parseInt(this.mixStorePolicy.providers[0]),this.mixStorePolicy.timeStamp&&this.mixStorePolicy.timeStamp+1e3*this.mixStorePolicy.ttl>t){var r=this.mixStorePolicy.timeStamp+1e3*this.mixStorePolicy.ttl-t;this.core.timerManager.addTimer(this._getMixStorePolicy.bind(this,e),r)}}catch(t){ce.localStorage.getItem(this.MIXSTOREKEY)&&JSON.parse(ce.localStorage.getItem(this.MIXSTOREKEY))[e]&&this.core.logger.error("uploadFile:: JSON.parse mixStorePolicy error ",t)}if(!this.mixStorePolicy||this.mixStorePolicy.timeStamp+1e3*this.mixStorePolicy.ttl<=t)try{var i=(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=i.policyVersion,this.mixStorePolicy.ttl=Number(i.ttl),this.mixStorePolicy.providers=i.providers.split(","),this.circuitTimer&&this.core.timerManager.deleteTimer(this.circuitTimer),this.curProvider=parseInt(this.mixStorePolicy.providers[0]),this.mixStorePolicy.nosPolicy=i.nosPolicy?JSON.parse(i.nosPolicy):null,this.mixStorePolicy.s3Policy=i.s3Policy?JSON.parse(i.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,e),1e3*this.mixStorePolicy.ttl);var o=ce.localStorage.getItem(this.MIXSTOREKEY)?JSON.parse(ce.localStorage.getItem(this.MIXSTOREKEY)):{};this.mixStorePolicy.timeStamp=(new Date).getTime(),o[e]=this.mixStorePolicy,ce.localStorage.setItem(this.MIXSTOREKEY,JSON.stringify(o))}catch(t){if(this.logger.error("getMixStorePolicy error",t),0===this.mixStoreErrorCount)throw new Error("getMixStorePolicy all count error");this._getMixStorePolicy(e),this.mixStoreErrorCount--}this.mixStorePolicy.nosPolicy&&(this.cloudStorage.nos.nosErrorCount=this.mixStorePolicy.nosPolicy.uploadConfig.retryPolicy.retry)}))}_addCircuitTimer(){var e=this.mixStorePolicy.providers,t=e[(e.indexOf(String(this.curProvider))+1)%e.length];if(!t)throw new Error("uploadFile nextProvider error");if(t===e[0])throw new Error("uploadFile all policy fail");if(this.logger.log(`uploadFile:: upload policy will change,now policy:${this.curProvider} nextProvider:${t}`),this.curProvider=parseInt(t),this.mixStorePolicy.nosPolicy&&this.mixStorePolicy.s3Policy){var r=this.mixStorePolicy[1===this.curProvider?"nosPolicy":"s3Policy"].uploadConfig.retryPolicy.circuit;if(!r||0===r)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*r)}throw new Error("uploadFile will not retry again")}getFileAuthToken(e){return __awaiter(this,void 0,void 0,(function*(){return(yield this.core.sendCmd("getFileAuthToken",{mixStoreAuthTokenReqTag:e})).content.mixStoreAuthTokenResTag}))}}var Lt=-1;class AWS{constructor(e,t){this.s3=null,this.core=e,this.cloudStorage=t,this.logger=e.logger}get mixStorePolicy(){return this.cloudStorage.mixStorage.mixStorePolicy}s3Upload(e,t,r){return __awaiter(this,void 0,void 0,(function*(){var i;if(Lt+=1,e.file)i=e.file;else if("string"==typeof e.fileInput){this.logger.warn("fileInput will abandon,Please use file or filepath");var o=document.getElementById(e.fileInput);if(!(o&&o.files&&o.files[0]))throw new Error("Can not get file from fileInput");i=o.files[0]}else{if(!(e.fileInput&&e.fileInput.files&&e.fileInput.files[0]))throw new Error(`Can not get file from fileInput ${e.fileInput}`);i=e.fileInput.files[0]}if(!this.mixStorePolicy.s3Policy)throw new Error("dont get s3 policy");var n={accessKeyId:r.accessKeyId,secretAccessKey:r.secretAccessKey,sessionToken:r.sessionToken,region:r.region,maxRetries:this.mixStorePolicy.s3Policy.uploadConfig.retryPolicy.retry},s=this.s3,a=decodeURIComponent(r.bucket),c=decodeURIComponent(r.objectName),_=i,l=`https://${a}.s3.amazonaws.com/${c}`,d={},E=this.mixStorePolicy.s3Policy;if(E&&E.uploadConfig&&Array.isArray(E.uploadConfig.uploadUrl)&&E.uploadConfig.uploadUrl.length>0){var h=E.uploadConfig.uploadUrl.length;Lt%=h,d.endpoint=E.uploadConfig.uploadUrl[Lt],d.s3ForcePathStyle=!0,l=`${d.endpoint}/${a}/${c}`}t.update({local_file:i.name,remote_addr:l,operation_type:1});var u=new s(d);u.config.update(n);var m={Bucket:a,Key:c,Body:_,Metadata:{token:r.token},ContentType:_.type||"application/octet-stream"};this.core.logger.log("uploadFile:: s3 upload params:",m);var g=u.upload(m);return g.on("httpUploadProgress",(r=>{t.update({index:r.part});var i=parseFloat((r.loaded/r.total).toFixed(2));e.onUploadProgress&&e.onUploadProgress({total:r.total,loaded:r.loaded,percentage:i,percentageText:Math.round(100*i)+"%"})})),new Promise(((i,o)=>{var n=(new Date).getTime();g.send(((s,l)=>__awaiter(this,void 0,void 0,(function*(){var d,E,h;if(s&&"RequestAbortedError"===s.code)this.logger.error("uploadFile:","api::s3:upload file abort.",s),t.update({http_code:s.statusCode,exception:s}),o(new UploadError({code:"v2"===get(this.core,"options.apiVersion")?de.V2NIM_ERROR_CODE_CANCELLED:400,detail:{reason:"S3RequestAbortedError",rawError:s,curProvider:2}}));else{if(!s){t.update({http_code:200});var u=this.mixStorePolicy.s3Policy.cdnSchema;u=(u=u.replace("{cdnDomain}",this.mixStorePolicy.s3Policy.dlcdn)).replace("{objectName}",l.Key);var m={size:_.size,name:_.name,url:r.shortUrl?r.shortUrl:u,ext:_.name.split(".")[1]||"unknown"},g=e.type||"",p={image:"imageInfo"};return i(p[g]?yield this.getS3FileInfo({url:u,infoSuffix:p[g],s3Result:m}):m)}t.update({http_code:s.statusCode,exception:s}),this.core.reporter.reportTraceStart("exceptions",{user_id:this.core.options.account||(null===(E=null===(d=this.core)||void 0===d?void 0:d.auth)||void 0===E?void 0:E.account),trace_id:null===(h=this.core.clientSocket.socket)||void 0===h?void 0:h.sessionId,start_time:n,action:1,exception_service:4}),this.core.reporter.reportTraceUpdateV2("exceptions",{code:"number"==typeof s.status?s.status:"number"==typeof s.code?s.code:0,description:s.message||`${s.code}`,operation_type:1,target:JSON.stringify({bucket:a,object:c})},{asyncParams:ce.net.getNetworkStatus()}),this.core.reporter.reportTraceEnd("exceptions",1);var{net_connect:I}=yield ce.net.getNetworkStatus();if(!1===I)return o(new UploadError({code:"v2"===get(this.core,"options.apiVersion")?de.V2NIM_ERROR_CODE_FILE_UPLOAD_FAILED:400,detail:{reason:"No network",rawError:s,curProvider:this.cloudStorage.mixStorage.curProvider}}));try{this.cloudStorage.mixStorage._addCircuitTimer()}catch(t){return o(new UploadError({code:"v2"===get(this.core,"options.apiVersion")?de.V2NIM_ERROR_CODE_FILE_UPLOAD_FAILED:400,detail:{reason:"All upload attempts failed",rawError:t,curProvider:this.cloudStorage.mixStorage.curProvider,mixStorePolicy:this.mixStorePolicy,file:e.file||e.filePath}}))}i(this.cloudStorage._uploadFile(e,t))}})))),e.onUploadStart&&e.onUploadStart(g)}))}))}getS3FileInfo(e){var t;return __awaiter(this,void 0,void 0,(function*(){var r,{url:i,infoSuffix:o,s3Result:n}=e;try{r=yield this.core.adapters.request(`${i}?${o}`,{method:"GET",dataType:"text",timeout:5e3},{exception_service:3})}catch(e){return this.core.logger.error("uploadFile:: fetch file info error",e),n}if(r){var{data:s}=r,a="imageInfo"===o?s:null===(t=null==s?void 0:s.GetVideoInfo)||void 0===t?void 0:t.VideoInfo;return pickBy(Object.assign(Object.assign({},n),{w:null==a?void 0:a.Width,h:null==a?void 0:a.Height,orientation:null==a?void 0:a.Orientation,dur:null==a?void 0:a.Duration,audioCodec:null==a?void 0:a.AudioCodec,videoCodec:null==a?void 0:a.VideoCodec,container:null==a?void 0:a.Container}),(function(e){return void 0!==e}))}return this.core.logger.error("uploadFile:: fetch s3 file info no result",`${i}?${o}`),n}))}}var bt={user_id:"",trace_id:"",action:0,state:0,duration:0,start_time:0,offset:0,full_size:0,transferred_size:0,operation_type:0,remote_addr:"",local_file:"",retry_times:0,index:0,part_size:0,transfer_latency:0,http_code:0,exception:"",req_headers:"",rsp_headers:""},Pt="ReporterHook::setMonitorForResources:";class ReporterHookCloudStorage{constructor(e,t){this.traceData=bt,this.core=e,this.id=Math.round(1e3*Math.random()),this.traceData=Object.assign({},bt,t)}start(){var e,t;this.core&&(this.reset(),this.traceData.user_id=this.core.account,this.traceData.trace_id=(null===(t=null===(e=this.core.clientSocket)||void 0===e?void 0:e.socket)||void 0===t?void 0:t.sessionId)||"",this.traceData.start_time="timeOrigin"in this.core?this.core.timeOrigin.getNTPTime():Date.now())}update(e){return __awaiter(this,void 0,void 0,(function*(){if(this.core&&this.traceData.user_id){if(e.transferred_size&&this.core.logger.log(`${this.id}.${Pt} upload update`,e),"object"==typeof e.exception)try{e.exception=JSON.stringify(e.exception)}catch(t){e.exception="UnknownObject"}if("object"==typeof e.req_headers)try{e.req_headers=JSON.stringify(e.req_headers)}catch(t){e.req_headers="UnknownObject"}if("object"==typeof e.rsp_headers)try{e.rsp_headers=JSON.stringify(e.rsp_headers)}catch(t){e.rsp_headers="UnknownObject"}Object.assign(this.traceData,e)}}))}end(e){this.core&&this.traceData.user_id&&(this.core.logger.log(`${Pt} upload end cause of ${e}`),this.traceData.state=e,this.traceData.duration=("timeOrigin"in this.core?this.core.timeOrigin.getNTPTime():Date.now())-(this.traceData.start_time||0),this.core.reporter.report("nim_sdk_resources",this.traceData),this.traceData=bt,this.destroy())}reset(){this.traceData=Object.assign({},bt)}destroy(){this.core=void 0,this.traceData=bt}}class CloudStorageService{constructor(e,t={}){this.config={},this.uploadTaskMap={},this.name="cloudStorage",this.logger=e.logger,this.core=e,this.nos=new NOS(e,this),this.mixStorage=new MixStorage(e,this),this.aws=new AWS(e,this),registerParser({cmdMap:yt,cmdConfig:Vt}),this.setOptions(t),this.setListeners()}setOptions(e={}){var t=e.storageKeyPrefix||"NIMClient";this.mixStorage.GRAYKEY=t+"-AllGrayscaleConfig",this.mixStorage.MIXSTOREKEY=t+"-AllMixStorePolicy";var{s3:r}=e,i=__rest(e,["s3"]),o=Object.assign({},vt,this.config);if(i&&Object.prototype.hasOwnProperty.call(i,"cdn")){var n=Object.assign(Object.assign({},o.cdn),i.cdn);this.config=Object.assign({},o,i),this.config.cdn=n}else this.config=Object.assign({},o,i);r&&(this.aws.s3=r)}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((e=>{var t=this.uploadTaskMap[e];t&&t.abort&&t.abort()})),this.uploadTaskMap={}}init(e=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,e)),yield this.nos._getNosCdnHost()}))}processCallback(e,t,r){var i=e.onUploadProgress,o=e.onUploadDone,n=e.onUploadStart;return{onUploadStart:"function"==typeof n?e=>{this.uploadTaskMap[t]=e;try{n(e)}catch(e){this.logger.error("CloudStorage::uploadFile:options.onUploadStart execute error",e)}}:e=>{this.uploadTaskMap[t]=e},onUploadProgress:"function"==typeof i?e=>{r.update({transferred_size:e.loaded,full_size:e.total});try{i(e)}catch(e){this.logger.error("CloudStorage::uploadFile:options.onUploadProgress execute error",e)}}:e=>{r.update({transferred_size:e.loaded,full_size:e.total})},onUploadDone:"function"==typeof o?e=>{r.end(0);try{o(e)}catch(e){this.logger.error("CloudStorage::uploadFile:options.onUploadDone execute error",e)}}:()=>{r.end(0)},taskKey:t}}uploadFile(e){return __awaiter(this,void 0,void 0,(function*(){if(validate({maxSize:{type:"number",required:!1},type:{type:"enum",values:["file","image","audio","video"]}},e),!e.fileInput&&!e.file&&!e.filePath)throw new Error("uploadFile needs target file object or a filePath");if(e.type&&"file"!==e.type){var t=get(e,"file.type");if(t&&"string"==typeof t&&-1===t.indexOf(e.type))throw new Error(`The meta type "${t}" does not match "${e.type}"`)}var r=new ReporterHookCloudStorage(this.core);if(r.start(),e.file)r.update({full_size:e.file.size,local_file:e.file.name});else if("string"==typeof e.fileInput){var i=document.getElementById(e.fileInput);i&&i.files&&i.files[0]&&r.update({full_size:i.files[0].size,local_file:i.files[0].name})}else e.fileInput&&e.fileInput.files&&e.fileInput.files[0]&&r.update({full_size:e.fileInput.files[0].size,local_file:e.fileInput.files[0].name});var o=ve(),{onUploadStart:n,onUploadProgress:s,onUploadDone:a}=this.processCallback(e,o,r);e.onUploadStart=n,e.onUploadProgress=s,e.onUploadDone=a;var c=null;try{c=yield this._uploadFile(e,r),e.md5&&(c.md5=e.md5),delete this.uploadTaskMap[o]}catch(e){throw delete this.uploadTaskMap[o],r.end((e&&e.code)===de.V2NIM_ERROR_CODE_CANCELLED?3:1),e}return c&&(c.size=void 0===c.size?void 0:Number(c.size),c.w=void 0===c.w?void 0:Number(c.w),c.h=void 0===c.h?void 0:Number(c.h),c.dur=void 0===c.dur?void 0:Number(c.dur)),c.url=decodeURIComponent(c.url),e.onUploadDone({size:c.size,name:c.name,url:c.url,ext:c.name.split(".")[1]||"unknown"}),c}))}_uploadFile(e,t){var r,i;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(e,t);this.logger.log(`uploadFile::_uploadFile, grayConfig enable:${get(this.mixStorage,"grayConfig.mixStoreEnable")} curProvider:${get(this.mixStorage,"curProvider")}`);var o=this.core.adapters.getFileUploadInformation(e),n=!0;o?!1===o.complete&&2===this.mixStorage.curProvider?n=!1:o.complete&&t.destroy():n=!1,this.aws.s3||(this.mixStorage.curProvider=1);var s=Ct;if(!n)try{s=(yield this.core.sendCmd("getMixStoreToken",{mixStoreTokenReqTag:{provider:this.mixStorage.curProvider,tokenCount:1,tag:"qchat",nosSurvivalTime:e.nosSurvivalTime,returnBody:getUploadResponseFormat(e.type),policyVersion:this.mixStorage.mixStorePolicy.policyVersion}})).content.mixStoreTokenResTag}catch(e){if(this.core.logger.error("uploadFile:: getMixStoreToken error",e),t.destroy(),e instanceof V2NIMErrorImpl)throw e;throw new UploadError({code:"v2"===get(this.core,"options.apiVersion")?de.V2NIM_ERROR_CODE_FILE_UPLOAD_FAILED:400,detail:{reason:"getMixStoreToken error",rawError:e,curProvider:this.mixStorage.curProvider,mixStorePolicy:this.mixStorage.mixStorePolicy}})}return n?this.nos.nosUpload(e,t,null===(i=null===(r=null==o?void 0:o.uploadInfo)||void 0===r?void 0:r.payload)||void 0===i?void 0:i.mixStoreToken):2===this.mixStorage.curProvider?this.aws.s3Upload(e,t,s):this.nos.nosUpload(e,t,s)}))}getThumbUrl(e,t){var r,i,o,n,s;if(!new RegExp(/http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- ./?%&=]*)?/).test(e))return this.logger.error("illegal file url:"+e),e;var[a,c,_,l,d,E,h,u]=/^(?:([A-Za-z]+):)?(\/{0,3})([0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/.exec(e);if(null===(r=this.grayConfig)||void 0===r?void 0:r.mixStoreEnable){var m=this._getUrlType(e);if(2===m&&this.mixStorePolicy.s3Policy&&get(this.mixStorePolicy,"s3Policy.thumbPolicy.imagethumb"))return(null===(o=null===(i=this.mixStorePolicy.s3Policy)||void 0===i?void 0:i.thumbPolicy)||void 0===o?void 0:o.imagethumb).replace("{cdnDomain}",this.mixStorePolicy.s3Policy.dlcdn).replace("{objectName}",E).replace("{x}",t.width.toString()).replace("{y}",t.height.toString());if(1===m&&this.mixStorePolicy.nosPolicy&&get(this.mixStorePolicy,"nosPolicy.thumbPolicy.imagethumb"))return(null===(s=null===(n=this.mixStorePolicy.nosPolicy)||void 0===n?void 0:n.thumbPolicy)||void 0===s?void 0:s.imagethumb).replace("{cdnDomain}",this.mixStorePolicy.nosPolicy.dlcdn).replace("{objectName}",E).replace("{x}",t.width.toString()).replace("{y}",t.height.toString())}return e.includes("?")?e+`&imageView&thumbnail=${t.width}x${t.height}`:e+`?imageView&thumbnail=${t.width}x${t.height}`}getVideoCoverUrl(e,t){var r,i,o,n,s;if(!new RegExp(/http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- ./?%&=]*)?/).test(e))return this.logger.error("illegal file url:"+e),e;var[a,c,_,l,d,E,h,u]=/^(?:([A-Za-z]+):)?(\/{0,3})([0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/.exec(e);if(null===(r=this.grayConfig)||void 0===r?void 0:r.mixStoreEnable){var m=this._getUrlType(e);if(2===m&&this.mixStorePolicy.s3Policy&&get(this.mixStorePolicy,"s3Policy.thumbPolicy.vframe"))return(null===(o=null===(i=this.mixStorePolicy.s3Policy)||void 0===i?void 0:i.thumbPolicy)||void 0===o?void 0:o.vframe).replace("{cdnDomain}",this.mixStorePolicy.s3Policy.dlcdn).replace("{objectName}",E).replace("{x}",t.width.toString()).replace("{y}",t.height.toString()).replace("{offset}","0").replace("{type}","png");if(1===m&&this.mixStorePolicy.nosPolicy&&get(this.mixStorePolicy,"nosPolicy.thumbPolicy.vframe"))return(null===(s=null===(n=this.mixStorePolicy.nosPolicy)||void 0===n?void 0:n.thumbPolicy)||void 0===s?void 0:s.vframe).replace("{cdnDomain}",this.mixStorePolicy.nosPolicy.dlcdn).replace("{objectName}",E).replace("{x}",t.width.toString()).replace("{y}",t.height.toString()).replace("{offset}","0").replace("{type}","png")}return e.includes("?")?e+`&vframe&offset=0&resize=${t.width}x${t.height}&type=png`:e+`?vframe&offset=0&resize=${t.width}x${t.height}&type=png`}getPrivateUrl(e){var t;if(!new RegExp(/http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- ./?%&=]*)?/).test(e))return this.logger.error("illegal file url:"+e),"";var[r,i,o,n,s,a,c,_]=/^(?:([A-Za-z]+):)?(\/{0,3})([0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/.exec(e);if(null===(t=this.grayConfig)||void 0===t?void 0:t.mixStoreEnable){var l=this._getUrlType(e);return 2===l&&this.mixStorePolicy.s3Policy&&(e=this.mixStorePolicy.s3Policy.cdnSchema.replace("{cdnDomain}",this.mixStorePolicy.s3Policy.dlcdn).replace("{objectName}",a)),1===l&&this.mixStorePolicy.nosPolicy&&(e=this.mixStorePolicy.nosPolicy.cdnSchema.replace("{cdnDomain}",this.mixStorePolicy.nosPolicy.dlcdn).replace("{objectName}",a)),e}var{downloadUrl:d,downloadHostList:E,nosCdnEnable:h}=this.config,u=this.config.cdn.cdnDomain,m=this.config.cdn.objectNamePrefix?decodeURIComponent(this.config.cdn.objectNamePrefix):"",g=decodeURIComponent(a),p=g.indexOf(m);if(u&&p>-1&&h)return`${i}:${o}${u}/${g.slice(p)}`;if(E.includes(n)&&a.includes("/")){var I=a.indexOf("/"),N=a.substring(0,I),T=a.substring(I+1);return d.replace("{bucket}",N).replace("{object}",T)}var O=E.filter((e=>"string"==typeof n&&n.includes(e)))[0],M=O?n.replace(O,"").replace(/\W/g,""):null;return M?d.replace("{bucket}",M).replace("{object}",a):e}getOriginUrl(e){return __awaiter(this,void 0,void 0,(function*(){return"string"==typeof e&&e.includes("_im_url=1")?(yield this.core.sendCmd("getOriginUrl",{nosSafeUrlTag:{safeUrl:e}})).content.nosSafeUrlTag.originUrl:e}))}getFileToken(e){return __awaiter(this,void 0,void 0,(function*(){validate({type:{type:"number",min:2,max:3},urls:{type:"array",required:!1,itemType:"string"}},e);var t=this.mixStorePolicy.nosPolicy?this.mixStorePolicy.nosPolicy.authPolicy.policyType:null,r=this.mixStorePolicy.s3Policy?this.mixStorePolicy.s3Policy.authPolicy.policyType:null;if(t===String(-1)&&r===String(-1))throw this.logger.error("don't need token"),new Error("don't need token");if(2===e.type){if(t&&t.indexOf(String(2))>=0||r&&r.indexOf(String(2))>0)return this.mixStorage.getFileAuthToken(e);throw this.logger.error("don't support time token "),new Error("don't support type time token ")}if(!e.urls||!e.urls.length)throw this.logger.error("urls is required when urls token"),new Error("urls is required when urls token");var i=[],o=[];if(e.urls.forEach((e=>{var t=this._getUrlType(e);1===t&&o.push(e),2===t&&i.push(e)})),(!r||0!==i.length&&r.indexOf(String(3))<0)&&(this.logger.warn("s3 url don't support url token"),i=[]),(!t||0!==o.length&&t.indexOf(String(3))<0)&&(this.logger.warn("nos url don't support url token"),o=[]),0===i.length&&0===o.length)throw this.logger.error("not support urls"),new Error("not support urls");if(0===i.length||0===o.length)return e.urls=JSON.stringify(e.urls),this.mixStorage.getFileAuthToken(e)}))}_getUrlType(e){return this.mixStorePolicy.nosPolicy&&this.mixStorePolicy.nosPolicy.dlcdns.some((t=>e.indexOf(t)>=0))?1:this.mixStorePolicy.s3Policy&&this.mixStorePolicy.s3Policy.dlcdns.some((t=>e.indexOf(t)>=0))?2:null}getNosAccessToken(e){return validate({url:{type:"string",allowEmpty:!1}},e),this.nos.getNosAccessToken(e)}deleteNosAccessToken(e){return validate({token:{type:"string",allowEmpty:!1}},e),this.nos.deleteNosAccessToken(e)}get grayConfig(){return this.mixStorage.grayConfig}get mixStorePolicy(){return this.mixStorage.mixStorePolicy}process(e){var t=get(e,"error.detail.ignore");return e.error&&!t?Promise.reject(e.error):Promise.resolve(e)}}function getFileOrPath(e){var t="object"==typeof e?e:void 0,r="string"==typeof e?e:void 0;if(!t&&!r)throw new V2NIMErrorImpl({code:de.V2NIM_ERROR_CODE_MISUSE,detail:{reason:"getFileOrPath::incorrect file and path"}});if("string"==typeof r)if(0===r.indexOf("nim-external")){var i=document.getElementById(r);if(!(i&&i.files&&i.files[0]))throw new V2NIMErrorImpl({code:de.V2NIM_ERROR_CODE_FILE_NOT_FOUND,detail:{reason:`getFileOrPath::file not exist: ${r}`}});t=i.files[0]}else if("BROWSER"===ce.platform)throw new V2NIMErrorImpl({code:de.V2NIM_ERROR_CODE_MISUSE,detail:{reason:`getFileOrPath::incorrect path: ${r}`}});if("object"==typeof t&&void 0===t.size)throw new V2NIMErrorImpl({code:de.V2NIM_ERROR_CODE_MISUSE,detail:{reason:"getFileOrPath::file no size"}});return{file:t,path:r}}class V2Service extends Ie{constructor(e,t){super(),this.name=e,this.logger=t.logger,this.core=t}checkV2(){var e=this.core.options.apiVersion;if("v2"===e)return!0;throw new V2NIMErrorImpl({code:de.V2NIM_ERROR_CODE_MISUSE,detail:{reason:`The version "${e}" of client is not supported.`}})}checkLogin(){if(0===this.core.V2NIMLoginService.getLoginStatus())throw new V2NIMErrorImpl({code:de.V2NIM_ERROR_CODE_ILLEGAL_STATE,detail:{reason:"Client logout."}})}emit(e,...t){this.logger.debug(`${this.name}::emit event: '${e.toString()}',`,void 0!==t[0]?t[0]:"",void 0!==t[1]?t[1]:"",void 0!==t[2]?t[2]:"");try{return super.emit(e,...t)}catch(t){return setTimeout((()=>{throw this.logger.error(`${this.name}::emit throw error in setTimeout. event: ${e.toString()}. Error`,t),t}),0),!1}}process(e){var t=this[e.cmd+"Handler"],r=this.handler&&this.handler[e.cmd+"Handler"];if("function"==typeof t||"function"==typeof r){if(e.error)return this.logger.error(`${e.cmd}::recvError`,e.error),Promise.reject(e.error);try{var i=t?t.call(this,e):r.call(this.handler,e);return Promise.resolve(i)}catch(e){return Promise.reject(e)}}var o=get(e,"error.detail.ignore");return e.error&&!o?Promise.reject(e.error):Promise.resolve(e)}}var kt={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(e){super("V2NIMStorageUtil",e),this.core=e}imageThumbUrl(e,t){return e+`?imageView&thumbnail=${t}z${t}`}videoCoverUrl(e,t){return e+`?vframe&offset=${t}`}getImageThumbUrl(e,t){return __awaiter(this,void 0,void 0,(function*(){this.checkV2();var r=e;validate(kt,{attachment:r,thumbSize:t},"",!0),t.width=t.width||0,t.height=t.height||0,0===t.width&&0===t.height&&(t.width=150);var i=r.url;try{i=yield this.core.V2NIMStorageService.shortUrlToLong(r.url)}catch(e){this.core.logger.warn("shortUrlToLong error:",e)}return{url:this.core.cloudStorage.getThumbUrl(i,t)}}))}getVideoCoverUrl(e,t){return __awaiter(this,void 0,void 0,(function*(){this.checkV2();var r=e;validate(kt,{attachment:r,thumbSize:t},"",!0),t.width=t.width||0,t.height=t.height||0,0===t.width&&0===t.height&&(t.width=150);var i=r.url;try{i=yield this.core.V2NIMStorageService.shortUrlToLong(r.url)}catch(e){this.core.logger.warn("shortUrlToLong error:",e)}return{url:this.core.cloudStorage.getVideoCoverUrl(i,t)}}))}}class V2NIMStorageServiceImpl extends V2Service{constructor(e){super("V2NIMStorageService",e),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=e,this.core._registerDep(CloudStorageService,"cloudStorage"),this.core._registerDep(V2NIMStorageUtil,"V2NIMStorageUtil")}addCustomStorageScene(e,t){return this.checkV2(),validate({sceneName:{type:"string",allowEmpty:!1},expireTime:{type:"number",min:0}},{sceneName:e,expireTime:t},"",!0),this.sceneMap[e]={sceneName:e,expireTime:t},{sceneName:e,expireTime:t}}getStorageSceneList(){return this.checkV2(),Object.values(this.sceneMap)}getStorageScene(e){return e&&this.sceneMap[e]||this.sceneMap.nim_default_im}hasStorageScene(e){return void 0!==this.sceneMap[e]}createUploadFileTask(e){if(this.checkV2(),"string"==typeof e.fileObj&&0===e.fileObj.indexOf("nim-external")){var t=document.getElementById(e.fileObj);t&&t.files&&t.files[0]&&(e.fileObj=t.files[0])}return{taskId:ve(),uploadParams:e}}uploadFile(e,t){return __awaiter(this,void 0,void 0,(function*(){return this.checkV2(),validate({taskId:{type:"string",allowEmpty:!1}},e,"fileTask",!0),(yield this._uploadFile(e,t))[0]}))}uploadFileWithMetaInfo(e,t){return __awaiter(this,void 0,void 0,(function*(){return this.checkV2(),validate({taskId:{type:"string",allowEmpty:!1}},e,"fileTask",!0),function formatV2NIMFileMetaInfo(e){var{url:t,name:r,size:i,ext:o,md5:n,h:s,w:a,orientation:c,dur:_,audioCodec:l,videoCodec:d,container:E}=e;return JSON.parse(JSON.stringify({url:t,name:r,size:i,ext:o,md5:n,height:s,width:a,orientation:c,duration:_,audioCodec:l,videoCodec:d,container:E}))}((yield this._uploadFile(e,t))[1])}))}_uploadFile(e,t,r){var i;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:o,taskId:n}=e,{file:s,path:a}=getFileOrPath(o.fileObj),{fileType:c}=r||{};if(this.uploadingMessageInfo[n])throw new V2NIMErrorImpl({code:de.V2NIM_ERROR_CODE_RESOURCE_ALREADY_EXIST,detail:{reason:"V2NIMStorageService.uploadFile: repeat upload"}});try{var _={};s?_.file=s:a&&(0===(null==a?void 0:a.indexOf("nim-external"))?_.fileInput=a:_.filePath=a);var l=this.getStorageScene(o.sceneName);if(_.nosScenes=l.sceneName,_.nosSurvivalTime=l.expireTime,_.type=1===c?"image":2===c?"audio":3===c?"video":"file",_.file&&this.core.pluginMap["browser-md5-file"]){var d=yield this.getFileMd5(this.core.pluginMap["browser-md5-file"],n,_.file);_.md5=d}_.onUploadProgress=e=>{"function"==typeof t&&t(Math.round(100*e.percentage))},_.onUploadStart=e=>{var t;if(null===(t=this.uploadingMessageInfo[n])||void 0===t?void 0:t.abort)return e.abort(),void delete this.uploadingMessageInfo[n];this.uploadingMessageInfo[n]={abort:!1,task:e}},this.uploadingMessageInfo[n]={abort:!1};var E=yield this.core.cloudStorage.uploadFile(_);if(null===(i=this.uploadingMessageInfo[n])||void 0===i?void 0:i.abort)throw new V2NIMErrorImpl({code:de.V2NIM_ERROR_CODE_CANCELLED,detail:{reason:"upload file aborted"}});return delete this.uploadingMessageInfo[n],[E.url,E]}catch(e){throw delete this.uploadingMessageInfo[n],this.core.logger.error("sendFile:: upload File error or abort.",e),e}}))}cancelUploadFile(e){return __awaiter(this,void 0,void 0,(function*(){this.checkV2(),yield this._cancelUploadFile(e.taskId)}))}_cancelUploadFile(e){return __awaiter(this,void 0,void 0,(function*(){this.checkV2();var t=this.uploadingMessageInfo[e];if(null==t?void 0:t.task)try{this.logger.log("V2NIMStorageService.cancelUploadFile: uploadInfo task exist"),yield t.task.abort(),delete this.uploadingMessageInfo[e]}catch(t){delete this.uploadingMessageInfo[e],this.core.logger.error("cancelMessageAttachmentUpload::abort error.",t)}else{if(!t)throw new V2NIMErrorImpl({code:de.V2NIM_ERROR_CODE_RESOURCE_NOT_EXIST,detail:{reason:"V2NIMStorageService.cancelUploadFile: uploadInfo not exist"}});this.logger.log("V2NIMStorageService.cancelUploadFile: uploadInfo task not exist"),t.abort=!0}}))}getFileMd5(e,t,r){return __awaiter(this,void 0,void 0,(function*(){return new Promise(((i,o)=>{var n,s=new e;(null===(n=this.uploadingMessageInfo[t])||void 0===n?void 0:n.abort)?o(new V2NIMErrorImpl({code:de.V2NIM_ERROR_CODE_CANCELLED,detail:{reason:"upload file aborted"}})):this.uploadingMessageInfo[t]={abort:!1,task:s};try{s.md5(r,((e,t)=>{"aborted"===e?o(new V2NIMErrorImpl({code:de.V2NIM_ERROR_CODE_CANCELLED,detail:{reason:e}})):e?o(new V2NIMErrorImpl({code:de.V2NIM_ERROR_CODE_INTERNAL,detail:{reason:"md5 calculate error in callback",rawError:e}})):i(t)}))}catch(e){o(new V2NIMErrorImpl({code:de.V2NIM_ERROR_CODE_INTERNAL,detail:{reason:"md5 calculate error",rawError:e}}))}}))}))}shortUrlToLong(e){return __awaiter(this,void 0,void 0,(function*(){return this.checkV2(),this.core.cloudStorage.getOriginUrl(e)}))}getImageThumbUrl(e,t){return __awaiter(this,void 0,void 0,(function*(){return this.core.V2NIMStorageUtil.getImageThumbUrl(e,t)}))}getVideoCoverUrl(e,t){return __awaiter(this,void 0,void 0,(function*(){return this.core.V2NIMStorageUtil.getVideoCoverUrl(e,t)}))}}class FileUtil{constructor(e,t){this.core=e,this.service=t}doSendFile(e,t){return __awaiter(this,void 0,void 0,(function*(){var r=e.attachment;try{var[i,o]=yield this.core.V2NIMStorageService._uploadFile({taskId:e.messageClientId,uploadParams:{fileObj:(null==r?void 0:r.file)||(null==r?void 0:r.path),sceneName:null==r?void 0:r.sceneName}},t,{fileType:e.messageType}),n=Object.assign(Object.assign({},r),{uploadState:1});o.w&&(n.width=n.width||o.w),o.h&&(n.height=n.height||o.h),o.dur&&(n.duration=n.duration||o.dur),n.ext=n.ext&&-1===n.ext.indexOf(".")?`.${n.ext}`:n.ext;var s=["w","h","dur","ext","name"];for(var a in o)s.includes(a)||(n[a]=o[a]);var{raw:c,file:_,path:l}=n,d=__rest(n,["raw","file","path"]);e.attachment=JSON.parse(JSON.stringify(d)),e.attachment&&(e.attachment.raw=attachmentToRaw(e.messageType,e.attachment))}catch(t){throw e.attachment&&(e.attachment.uploadState=2),t}}))}cancelMessageAttachmentUpload(e){return __awaiter(this,void 0,void 0,(function*(){if(validate({messageClientId:{type:"string",allowEmpty:!1}},e,"",!0),![2,6,1,3].includes(e.messageType))throw new V2NIMErrorImpl({code:lt.V2NIM_ERROR_CODE_MISUSE,detail:{reason:`cancelMessageAttachmentUpload: messageType ${e.messageType} incorrect`}});if(2===e.sendingState||1===e.sendingState)throw new V2NIMErrorImpl({code:lt.V2NIM_ERROR_CODE_RESOURCE_NOT_EXIST,detail:{reason:"cancelMessageAttachmentUpload: message is already failed or succeeded"}});yield this.core.V2NIMStorageService._cancelUploadFile(e.messageClientId)}))}}class SendUtil{constructor(e,t){this.msgs=[],this.maxIdCount=100,this.core=e,this.service=t}reset(){this.msgs=[]}prepareMessage(e,t={}){var r=this.checkIfResend(e),i=this.generateSendMessage({message:e,params:t,resend:r}),{clientAntispamResult:o,text:n}=this.checkIfAntispam(t,i);return i.text=n,i.clientAntispamHit=!!o&&3===o.operateType,{messageBeforeSend:i,clientAntispamResult:o}}doSendMessage(e,t,r,i){return __awaiter(this,void 0,void 0,(function*(){var o,n={enabled:!1};if(!t.attachment||"object"!=typeof t.attachment||!("uploadState"in t.attachment)||t.attachment.url||0!==t.attachment.uploadState&&2!==t.attachment.uploadState)this.core.V2NIMChatroomService.emit("onSendMessage",t);else{var s=Date.now();try{t.attachmentUploadState=3,t.attachment.uploadState=3,this.core.V2NIMChatroomService.emit("onSendMessage",t),yield this.service.fileUtil.doSendFile(t,i),t.attachmentUploadState=1,t.attachment.uploadState=1,this.core.V2NIMChatroomService.emit("onSendMessage",t)}catch(r){throw t.attachmentUploadState=2,t.attachment.uploadState=2,t.sendingState=2,this.core.V2NIMChatroomService.emit("onSendMessage",t),n.attachUploadDuration=Date.now()-s,this.doMsgSendReport(e,n,t,r),r}n.attachUploadDuration=Date.now()-s}this.cacheMsg(t),this.core.timeOrigin.checkNodeReliable(e)&&(n.apiCallingTime=this.core.timeOrigin.getNTPTime(e),n.sendTime=this.core.timeOrigin.getNTPTime(),t.__clientExt={statistics:n});try{o=yield this.core.clientSocket.sendCmd("v2ChatroomSendMessage",{tag:t})}catch(r){throw t.sendingState=2,this.core.V2NIMChatroomService.emit("onSendMessage",t),this.doMsgSendReport(e,n,t,r),r}var a=formatMessage(this.core,Object.assign(Object.assign(Object.assign({},t),o.content.data),{sendingState:1}),this.core.account);this.doMsgSendReport(e,n,a);var c=a.antispamResult;return delete a.antispamResult,delete a.__clientExt,this.core.V2NIMChatroomService.emit("onSendMessage",a),Object.assign(Object.assign({message:a},c?{antispamResult:c}:{}),r?{clientAntispamResult:r}:{})}))}doMsgSendReport(e,t,r,i){t.apiCallingTime=this.core.timeOrigin.getNTPTime(e),t.sendTime=this.core.timeOrigin.getNTPTime();var o=this.core.timeOrigin.getNTPTime(),n=get(i,"detail.reason");this.core.reporter.report("msgSend",{clientId:r.messageClientId,msgTime:r.createTime,fromAccid:r.senderId,type:4,roomId:r.roomId,result:i?i.code:200,failReason:n||(null==i?void 0:i.message)||"",rt:o-t.apiCallingTime,apiCallingTime:t.apiCallingTime,sendTime:t.sendTime,attachUploadDuration:t.attachUploadDuration,apiCallbackTime:o})}doMsgReceiveReport(e,t){if(e.senderId!==this.core.account){var r=get(e,"__clientExt.statistics.apiCallingTime")||0,i=get(e,"__clientExt.statistics.sendTime")||0,o=get(e,"__clientExt.statistics.attachUploadDuration")||0,n=this.core.timeOrigin.getNTPTime(),s=e.createTime,a=this.core.timeOrigin.checkNodeReliable(t.__receiveTimeNode)?this.core.timeOrigin.getNTPTime(t.__receiveTimeNode):n;this.core.reporter.report("msgReceive",{clientId:e.messageClientId,receiveTime:a,serverTime:s,apiCallingTime:r,sendTime:i,attachUploadDuration:o,callbackTime:n,preHandleTime:n,fromAccid:e.senderId,type:4,roomId:e.roomId,result:200,failReason:"",rt:n-s})}}cacheMsg(e){this.msgs.push({messageClientId:e.messageClientId,senderId:e.senderId}),this.msgs.length>this.maxIdCount&&this.msgs.shift()}checkIfResend(e){return this.msgs.some((t=>t.messageClientId===e.messageClientId))}generateSendMessage(e){var t,r,i,{message:o,params:n,resend:s}=e,a={};(o.locationInfo||n.locationInfo)&&(a.x=(null===(t=o.locationInfo||n.locationInfo)||void 0===t?void 0:t.x)||0,a.y=(null===(r=o.locationInfo||n.locationInfo)||void 0===r?void 0:r.y)||0,a.z=(null===(i=o.locationInfo||n.locationInfo)||void 0===i?void 0:i.z)||0);var c=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},o),n),{messageConfig:Object.assign(Object.assign({},o.messageConfig),n.messageConfig),routeConfig:Object.assign(Object.assign({},o.routeConfig),n.routeConfig),antispamConfig:Object.assign(Object.assign({},o.antispamConfig),n.antispamConfig)}),o.attachment?{attachment:Object.assign({},o.attachment)}:{}),{locationInfo:a,resend:s,sendingState:3});return 0!==c.messageType&&10!==c.messageType||(c.attachment=c.text),c}checkIfAntispam(e,t){var r,i=t.text;if(e.clientAntispamEnabled&&100!==t.messageType&&t.text)if(1===(r=this.core.V2NIMClientAntispamUtil.checkTextAntispam(t.text||"",e.clientAntispamReplace)).operateType)i=r.replacedText;else if(2===r.operateType)throw this.core.V2NIMChatroomService.emit("onSendMessage",Object.assign(Object.assign({},t),{sendingState:2})),new V2NIMErrorImpl({code:lt.V2NIM_ERROR_CODE_CLIENT_ANTISPAM,detail:{reason:"sendMessage: text intercepted by client antispam"}});return{clientAntispamResult:r,text:i}}}var wt=[2,7,12,100,6,1,-1,4,5,11,0,10,3],Ut={message:{type:"object",rules:{messageClientId:{type:"string",allowEmpty:!1},senderId:{type:"string",allowEmpty:!1},roomId:{type:"string",allowEmpty:!1},text:{type:"string",required:!1},attachment:{type:"object",required:!1,rules:{file:{type:"file",required:!1}}}}}},xt={params:{type:"object",required:!1,rules:{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:{routeEnabled:{type:"boolean",required:!1},routeEnvironment:{type:"string",required:!1}}},antiSpamConfig:{type:"object",required:!1,rules:{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}}},receiverIds:{type:"array",required:!1},notifyTargetTags:{type:"string",required:!1},locationInfo:{type:"object",required:!1,rules:{x:{type:"number"},y:{type:"number"},z:{type:"number"}}}}}},Gt={sceneName:{type:"string",required:!1},name:{type:"string",required:!1}},Ft=Object.assign(Object.assign({},Gt),{duration:{type:"number",required:!1}}),Bt=Object.assign(Object.assign({},Ft),{width:{type:"number",required:!1},height:{type:"number",required:!1}}),Ht=Object.assign(Object.assign({},Gt),{width:{type:"number",required:!1},height:{type:"number",required:!1}}),Yt={option:{type:"object",rules:{direction:{type:"enum",values:[1,0],required:!1},messageTypes:{type:"array",required:!1,itemType:"enum",values:wt},beginTime:{type:"number",min:0,required:!1},limit:{type:"number",min:1,required:!1}}}},jt={messageOption:{type:"object",rules:{tags:{type:"array",min:1,itemType:"string"},direction:{type:"enum",values:[1,0],required:!1},messageTypes:{type:"array",required:!1,itemType:"enum",values:wt},beginTime:{type:"number",min:0,required:!1},endTime:{type:"number",min:0,required:!1},limit:{type:"number",min:1,required:!1}}}},$t="V2NIMChatroomMessageService",Kt={"36_6":"v2ChatroomSendMessage","36_9":"v2ChatroomGetMessageList","36_35":"v2ChatroomMessageAck","36_36":"v2ChatroomGetMessageListByTag","13_7":"v2ChatroomOnMessage","29_17":"v2ChatroomDownloadLocalAntiSpamVocabs","6_23":"v2ChatroomGetServerTime","13_99":"v2ChatroomUpdateCDNInfo"},qt={version:1,md5:2,nosurl:3,thesaurus:4},Wt={messageClientId:1,messageType:{id:2,retType:"number"},attachment:{id:3,converter:(e,t)=>attachmentToRaw(t.messageType,e),retConverter:(e,t)=>rawToAttachment(e,Number(t[2]))},serverExtension:4,resend:{id:5,converter:boolToInt,retType:"boolean"},userInfoTimestamp:{id:6,access:"userInfoConfig.userInfoTimestamp",retType:"number"},senderNick:{id:7,access:"userInfoConfig.senderNick"},senderAvatar:{id:8,access:"userInfoConfig.senderAvatar"},senderExtension:{id:9,access:"userInfoConfig.senderExtension"},antispamCustomMessageEnabled:{id:10,def:e=>get(e,"antispamConfig.antispamCustomMessage")?1:void 0,retConverter:()=>{}},antispamCustomMessage:{id:11,access:"antispamConfig.antispamCustomMessage"},historyEnabled:{id:12,access:"messageConfig.historyEnabled",converter:e=>e?0:1,retConverter:e=>!parseInt(e)},text:13,antiSpamBusinessId:{id:14,access:"antispamConfig.antispamBusinessId"},clientAntispamHit:{id:15,access:"clientAntispamHit",converter:boolToInt,retType:"boolean"},antispamEnabled:{id:16,access:"antispamConfig.antispamEnabled",converter:boolToInt,retType:"boolean"},createTime:{id:20,retType:"number"},senderId:21,roomId:22,senderClientType:{id:23,retType:"number"},highPriority:{id:25,access:"messageConfig.highPriority",converter:boolToInt,retType:"boolean"},callbackExtension:27,subType:{id:28,retType:"number"},antispamCheating:{id:29,access:"antispamConfig.antispamCheating"},routeEnvironment:{id:30,access:"routeConfig.routeEnvironment"},notifyTargetTags:31,antispamExtension:{id:32,access:"antispamConfig.antispamExtension"},antispamResult:33,x:{id:34,access:"locationInfo.x",retType:"number"},y:{id:35,access:"locationInfo.y",retType:"number"},z:{id:36,access:"locationInfo.z",retType:"number"},receiverIds:{id:37,converter:objectToJSONString},__clientExt:{id:39,converter:objectToJSONString,retConverter:stringToJSONObject},routeEnabled:{id:100,access:"routeConfig.routeEnabled",converter:boolToInt,retType:"boolean",retDef:!0}},zt={v2ChatroomSendMessage:{sid:36,cid:6,service:$t,params:[{type:"Property",name:"tag",reflectMapper:Wt}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Wt)}]},v2ChatroomOnMessage:{sid:13,cid:7,service:$t,response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(Wt)}]},v2ChatroomGetMessageList:{sid:36,cid:9,service:$t,params:[{type:"Long",name:"beginTime"},{type:"Int",name:"limit"},{type:"Bool",name:"reverse"},{type:"LongArray",name:"messageTypes"}],response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(Wt)}]},v2ChatroomMessageAck:{sid:36,cid:35,service:$t,params:[{type:"Property",name:"tag",reflectMapper:{messageClientId:1,roomId:2}}]},v2ChatroomGetMessageListByTag:{sid:36,cid:36,service:$t,params:[{type:"Property",name:"tag",reflectMapper:{tags:1,messageTypes:2,beginTime:3,endTime:4,limit:5,reverse:6}}],response:[{type:"PropertyArray",name:"datas",reflectMapper:invertSerializeItem(Wt)}]},v2ChatroomDownloadLocalAntiSpamVocabs:{sid:29,cid:17,service:$t,params:[{type:"Property",name:"tag",reflectMapper:qt}],response:[{type:"Property",name:"data",reflectMapper:invertSerializeItem(qt)}]},v2ChatroomGetServerTime:{sid:6,cid:23,service:$t,response:[{type:"Long",name:"time"}]},v2ChatroomUpdateCDNInfo:{sid:13,cid:99,service:$t,response:[{type:"Property",name:"chatroomCdnInfo",reflectMapper:invertSerializeItem(st)}]}},Jt=Jt||function(e){var t;"undefined"!=typeof window&&window.crypto&&(t=window.crypto),"undefined"!=typeof self&&self.crypto&&(t=self.crypto),"undefined"!=typeof globalThis&&globalThis.crypto&&(t=globalThis.crypto),!t&&"undefined"!=typeof window&&window.msCrypto&&(t=window.msCrypto),!t&&"undefined"!=typeof global&&global.crypto&&(t=global.crypto);var cryptoSecureRandomInt=function(){if(t){if("function"==typeof t.getRandomValues)try{return t.getRandomValues(new Uint32Array(1))[0]}catch(e){}if("function"==typeof t.randomBytes)try{return t.randomBytes(4).readInt32LE()}catch(e){}}throw new Error("Native crypto module could not be used to get secure random number.")},r=Object.create||function(){function F(){}return function(e){var t;return F.prototype=e,t=new F,F.prototype=null,t}}(),i={},o=i.lib={},n=o.Base={extend:function(e){var t=r(this);return e&&t.mixIn(e),t.hasOwnProperty("init")&&this.init!==t.init||(t.init=function(){t.$super.init.apply(this,arguments)}),t.init.prototype=t,t.$super=this,t},create:function(){var e=this.extend();return e.init.apply(e,arguments),e},init:function(){},mixIn:function(e){for(var t in e)e.hasOwnProperty(t)&&(this[t]=e[t]);e.hasOwnProperty("toString")&&(this.toString=e.toString)},clone:function(){return this.init.prototype.extend(this)}},s=o.WordArray=n.extend({init:function(e,t){e=this.words=e||[],this.sigBytes=null!=t?t:4*e.length},toString:function(e){return(e||c).stringify(this)},concat:function(e){var t=this.words,r=e.words,i=this.sigBytes,o=e.sigBytes;if(this.clamp(),i%4)for(var n=0;n<o;n++){var s=r[n>>>2]>>>24-n%4*8&255;t[i+n>>>2]|=s<<24-(i+n)%4*8}else for(var a=0;a<o;a+=4)t[i+a>>>2]=r[a>>>2];return this.sigBytes+=o,this},clamp:function(){var t=this.words,r=this.sigBytes;t[r>>>2]&=4294967295<<32-r%4*8,t.length=e.ceil(r/4)},clone:function(){var e=n.clone.call(this);return e.words=this.words.slice(0),e},random:function(e){for(var t=[],r=0;r<e;r+=4)t.push(cryptoSecureRandomInt());return new s.init(t,e)}}),a=i.enc={},c=a.Hex={stringify:function(e){for(var t=e.words,r=e.sigBytes,i=[],o=0;o<r;o++){var n=t[o>>>2]>>>24-o%4*8&255;i.push((n>>>4).toString(16)),i.push((15&n).toString(16))}return i.join("")},parse:function(e){for(var t=e.length,r=[],i=0;i<t;i+=2)r[i>>>3]|=parseInt(e.substr(i,2),16)<<24-i%8*4;return new s.init(r,t/2)}},_=a.Latin1={stringify:function(e){for(var t=e.words,r=e.sigBytes,i=[],o=0;o<r;o++){var n=t[o>>>2]>>>24-o%4*8&255;i.push(String.fromCharCode(n))}return i.join("")},parse:function(e){for(var t=e.length,r=[],i=0;i<t;i++)r[i>>>2]|=(255&e.charCodeAt(i))<<24-i%4*8;return new s.init(r,t)}},l=a.Utf8={stringify:function(e){try{return decodeURIComponent(escape(_.stringify(e)))}catch(e){throw new Error("Malformed UTF-8 data")}},parse:function(e){return _.parse(unescape(encodeURIComponent(e)))}},d=o.BufferedBlockAlgorithm=n.extend({reset:function(){this._data=new s.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=l.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var r,i=this._data,o=i.words,n=i.sigBytes,a=this.blockSize,c=n/(4*a),_=(c=t?e.ceil(c):e.max((0|c)-this._minBufferSize,0))*a,l=e.min(4*_,n);if(_){for(var d=0;d<_;d+=a)this._doProcessBlock(o,d);r=o.splice(0,_),i.sigBytes-=l}return new s.init(r,l)},clone:function(){var e=n.clone.call(this);return e._data=this._data.clone(),e},_minBufferSize:0});o.Hasher=d.extend({cfg:n.extend(),init:function(e){this.cfg=this.cfg.extend(e),this.reset()},reset:function(){d.reset.call(this),this._doReset()},update:function(e){return this._append(e),this._process(),this},finalize:function(e){return e&&this._append(e),this._doFinalize()},blockSize:16,_createHelper:function(e){return function(t,r){return new e.init(r).finalize(t)}},_createHmacHelper:function(e){return function(t,r){return new E.HMAC.init(e,r).finalize(t)}}});var E=i.algo={};return i}(Math),Qt=Jt,Xt=Qt.lib,Zt=Xt.Base,er=Xt.WordArray,tr=Qt.algo,rr=tr.MD5,ir=tr.EvpKDF=Zt.extend({cfg:Zt.extend({keySize:4,hasher:rr,iterations:1}),init:function(e){this.cfg=this.cfg.extend(e)},compute:function(e,t){for(var r,i=this.cfg,o=i.hasher.create(),n=er.create(),s=n.words,a=i.keySize,c=i.iterations;s.length<a;){r&&o.update(r),r=o.update(e).finalize(t),o.reset();for(var _=1;_<c;_++)r=o.finalize(r),o.reset();n.concat(r)}return n.sigBytes=4*a,n}});Qt.EvpKDF=function(e,t,r){return ir.create(r).compute(e,t)},Jt.EvpKDF;var or=Jt,nr=or.lib.WordArray;or.enc.Base64={stringify:function(e){var t=e.words,r=e.sigBytes,i=this._map;e.clamp();for(var o=[],n=0;n<r;n+=3)for(var s=(t[n>>>2]>>>24-n%4*8&255)<<16|(t[n+1>>>2]>>>24-(n+1)%4*8&255)<<8|t[n+2>>>2]>>>24-(n+2)%4*8&255,a=0;a<4&&n+.75*a<r;a++)o.push(i.charAt(s>>>6*(3-a)&63));var c=i.charAt(64);if(c)for(;o.length%4;)o.push(c);return o.join("")},parse:function(e){var t=e.length,r=this._map,i=this._reverseMap;if(!i){i=this._reverseMap=[];for(var o=0;o<r.length;o++)i[r.charCodeAt(o)]=o}var n=r.charAt(64);if(n){var s=e.indexOf(n);-1!==s&&(t=s)}return function parseLoop(e,t,r){for(var i=[],o=0,n=0;n<t;n++)if(n%4){var s=r[e.charCodeAt(n-1)]<<n%4*2|r[e.charCodeAt(n)]>>>6-n%4*2;i[o>>>2]|=s<<24-o%4*8,o++}return nr.create(i,o)}(e,t,i)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="};var sr=Jt.enc.Base64;!function(e){e.lib.Cipher||function(){var t=e,r=t.lib,i=r.Base,o=r.WordArray,n=r.BufferedBlockAlgorithm,s=t.enc;s.Utf8;var a=s.Base64,c=t.algo.EvpKDF,_=r.Cipher=n.extend({cfg:i.extend(),createEncryptor:function(e,t){return this.create(this._ENC_XFORM_MODE,e,t)},createDecryptor:function(e,t){return this.create(this._DEC_XFORM_MODE,e,t)},init:function(e,t,r){this.cfg=this.cfg.extend(r),this._xformMode=e,this._key=t,this.reset()},reset:function(){n.reset.call(this),this._doReset()},process:function(e){return this._append(e),this._process()},finalize:function(e){return e&&this._append(e),this._doFinalize()},keySize:4,ivSize:4,_ENC_XFORM_MODE:1,_DEC_XFORM_MODE:2,_createHelper:function(){function selectCipherStrategy(e){return"string"==typeof e?I:g}return function(e){return{encrypt:function(t,r,i){return selectCipherStrategy(r).encrypt(e,t,r,i)},decrypt:function(t,r,i){return selectCipherStrategy(r).decrypt(e,t,r,i)}}}}()});r.StreamCipher=_.extend({_doFinalize:function(){return this._process(!0)},blockSize:1});var l=t.mode={},d=r.BlockCipherMode=i.extend({createEncryptor:function(e,t){return this.Encryptor.create(e,t)},createDecryptor:function(e,t){return this.Decryptor.create(e,t)},init:function(e,t){this._cipher=e,this._iv=t}}),E=l.CBC=function(){var e=d.extend();function xorBlock(e,t,r){var i,o=this._iv;o?(i=o,this._iv=void 0):i=this._prevBlock;for(var n=0;n<r;n++)e[t+n]^=i[n]}return e.Encryptor=e.extend({processBlock:function(e,t){var r=this._cipher,i=r.blockSize;xorBlock.call(this,e,t,i),r.encryptBlock(e,t),this._prevBlock=e.slice(t,t+i)}}),e.Decryptor=e.extend({processBlock:function(e,t){var r=this._cipher,i=r.blockSize,o=e.slice(t,t+i);r.decryptBlock(e,t),xorBlock.call(this,e,t,i),this._prevBlock=o}}),e}(),h=(t.pad={}).Pkcs7={pad:function(e,t){for(var r=4*t,i=r-e.sigBytes%r,n=i<<24|i<<16|i<<8|i,s=[],a=0;a<i;a+=4)s.push(n);var c=o.create(s,i);e.concat(c)},unpad:function(e){var t=255&e.words[e.sigBytes-1>>>2];e.sigBytes-=t}};r.BlockCipher=_.extend({cfg:_.cfg.extend({mode:E,padding:h}),reset:function(){var e;_.reset.call(this);var t=this.cfg,r=t.iv,i=t.mode;this._xformMode==this._ENC_XFORM_MODE?e=i.createEncryptor:(e=i.createDecryptor,this._minBufferSize=1),this._mode&&this._mode.__creator==e?this._mode.init(this,r&&r.words):(this._mode=e.call(i,this,r&&r.words),this._mode.__creator=e)},_doProcessBlock:function(e,t){this._mode.processBlock(e,t)},_doFinalize:function(){var e,t=this.cfg.padding;return this._xformMode==this._ENC_XFORM_MODE?(t.pad(this._data,this.blockSize),e=this._process(!0)):(e=this._process(!0),t.unpad(e)),e},blockSize:4});var u=r.CipherParams=i.extend({init:function(e){this.mixIn(e)},toString:function(e){return(e||this.formatter).stringify(this)}}),m=(t.format={}).OpenSSL={stringify:function(e){var t=e.ciphertext,r=e.salt;return(r?o.create([1398893684,1701076831]).concat(r).concat(t):t).toString(a)},parse:function(e){var t,r=a.parse(e),i=r.words;return 1398893684==i[0]&&1701076831==i[1]&&(t=o.create(i.slice(2,4)),i.splice(0,4),r.sigBytes-=16),u.create({ciphertext:r,salt:t})}},g=r.SerializableCipher=i.extend({cfg:i.extend({format:m}),encrypt:function(e,t,r,i){i=this.cfg.extend(i);var o=e.createEncryptor(r,i),n=o.finalize(t),s=o.cfg;return u.create({ciphertext:n,key:r,iv:s.iv,algorithm:e,mode:s.mode,padding:s.padding,blockSize:e.blockSize,formatter:i.format})},decrypt:function(e,t,r,i){return i=this.cfg.extend(i),t=this._parse(t,i.format),e.createDecryptor(r,i).finalize(t.ciphertext)},_parse:function(e,t){return"string"==typeof e?t.parse(e,this):e}}),p=(t.kdf={}).OpenSSL={execute:function(e,t,r,i){i||(i=o.random(8));var n=c.create({keySize:t+r}).compute(e,i),s=o.create(n.words.slice(t),4*r);return n.sigBytes=4*t,u.create({key:n,iv:s,salt:i})}},I=r.PasswordBasedCipher=g.extend({cfg:g.cfg.extend({kdf:p}),encrypt:function(e,t,r,i){var o=(i=this.cfg.extend(i)).kdf.execute(r,e.keySize,e.ivSize);i.iv=o.iv;var n=g.encrypt.call(this,e,t,o.key,i);return n.mixIn(o),n},decrypt:function(e,t,r,i){i=this.cfg.extend(i),t=this._parse(t,i.format);var o=i.kdf.execute(r,e.keySize,e.ivSize,t.salt);return i.iv=o.iv,g.decrypt.call(this,e,t,o.key,i)}})}()}(Jt);var ar=Jt,cr=ar.lib.BlockCipher,_r=ar.algo,lr=[],dr=[],Er=[],hr=[],ur=[],mr=[],gr=[],pr=[],Ir=[],Nr=[];!function(){for(var e=[],t=0;t<256;t++)e[t]=t<128?t<<1:t<<1^283;var r=0,i=0;for(t=0;t<256;t++){var o=i^i<<1^i<<2^i<<3^i<<4;o=o>>>8^255&o^99,lr[r]=o,dr[o]=r;var n=e[r],s=e[n],a=e[s],c=257*e[o]^16843008*o;Er[r]=c<<24|c>>>8,hr[r]=c<<16|c>>>16,ur[r]=c<<8|c>>>24,mr[r]=c;c=16843009*a^65537*s^257*n^16843008*r;gr[o]=c<<24|c>>>8,pr[o]=c<<16|c>>>16,Ir[o]=c<<8|c>>>24,Nr[o]=c,r?(r=n^e[e[e[a^n]]],i^=e[e[i]]):r=i=1}}();var Tr=[0,1,2,4,8,16,32,64,128,27,54],Or=_r.AES=cr.extend({_doReset:function(){if(!this._nRounds||this._keyPriorReset!==this._key){for(var e=this._keyPriorReset=this._key,t=e.words,r=e.sigBytes/4,i=4*((this._nRounds=r+6)+1),o=this._keySchedule=[],n=0;n<i;n++)n<r?o[n]=t[n]:(c=o[n-1],n%r?r>6&&n%r==4&&(c=lr[c>>>24]<<24|lr[c>>>16&255]<<16|lr[c>>>8&255]<<8|lr[255&c]):(c=lr[(c=c<<8|c>>>24)>>>24]<<24|lr[c>>>16&255]<<16|lr[c>>>8&255]<<8|lr[255&c],c^=Tr[n/r|0]<<24),o[n]=o[n-r]^c);for(var s=this._invKeySchedule=[],a=0;a<i;a++){n=i-a;if(a%4)var c=o[n];else c=o[n-4];s[a]=a<4||n<=4?c:gr[lr[c>>>24]]^pr[lr[c>>>16&255]]^Ir[lr[c>>>8&255]]^Nr[lr[255&c]]}}},encryptBlock:function(e,t){this._doCryptBlock(e,t,this._keySchedule,Er,hr,ur,mr,lr)},decryptBlock:function(e,t){var r=e[t+1];e[t+1]=e[t+3],e[t+3]=r,this._doCryptBlock(e,t,this._invKeySchedule,gr,pr,Ir,Nr,dr);r=e[t+1];e[t+1]=e[t+3],e[t+3]=r},_doCryptBlock:function(e,t,r,i,o,n,s,a){for(var c=this._nRounds,_=e[t]^r[0],l=e[t+1]^r[1],d=e[t+2]^r[2],E=e[t+3]^r[3],h=4,u=1;u<c;u++){var m=i[_>>>24]^o[l>>>16&255]^n[d>>>8&255]^s[255&E]^r[h++],g=i[l>>>24]^o[d>>>16&255]^n[E>>>8&255]^s[255&_]^r[h++],p=i[d>>>24]^o[E>>>16&255]^n[_>>>8&255]^s[255&l]^r[h++],I=i[E>>>24]^o[_>>>16&255]^n[l>>>8&255]^s[255&d]^r[h++];_=m,l=g,d=p,E=I}m=(a[_>>>24]<<24|a[l>>>16&255]<<16|a[d>>>8&255]<<8|a[255&E])^r[h++],g=(a[l>>>24]<<24|a[d>>>16&255]<<16|a[E>>>8&255]<<8|a[255&_])^r[h++],p=(a[d>>>24]<<24|a[E>>>16&255]<<16|a[_>>>8&255]<<8|a[255&l])^r[h++],I=(a[E>>>24]<<24|a[_>>>16&255]<<16|a[l>>>8&255]<<8|a[255&d])^r[h++];e[t]=m,e[t+1]=g,e[t+2]=p,e[t+3]=I},keySize:8});ar.AES=cr._createHelper(Or);var Mr,fr=Jt.AES;Jt.mode.ECB=((Mr=Jt.lib.BlockCipherMode.extend()).Encryptor=Mr.extend({processBlock:function(e,t){this._cipher.encryptBlock(e,t)}}),Mr.Decryptor=Mr.extend({processBlock:function(e,t){this._cipher.decryptBlock(e,t)}}),Mr);var Sr=Jt.mode.ECB,Rr=Jt.enc.Utf8,Ar=Jt.pad.Pkcs7;var Cr={enabled:!1,cdnUrls:[],timestamp:Date.now(),pollingIntervalSeconds:5,pollingTimeoutMillis:1e3},vr=invertSerializeItem(Wt);class CDNUtil{constructor(e,t){this.config=Cr,this.lastSuccessTimestamp=0,this.pollingTimer=0,this.msgBufferInterval=300,this.emitTimer=0,this.core=e,this.service=t,this.promiseManager=new PromiseManager}reset(){this.config=Cr,this.lastSuccessTimestamp=0,this.pollingTimer&&clearInterval(this.pollingTimer),this.pollingTimer=0,this.emitTimer&&clearInterval(this.emitTimer),this.emitTimer=0}setOptions(e){this.config=Object.assign({},this.config,e),this.core.logger.log("CDNUtil::setOptions",this.config),this.polling()}polling(){this.pollingTimer&&clearInterval(this.pollingTimer),this.pollingTimer=0,this.config.enabled&&(this.pollingTimer=setInterval(this.fetchMsgs.bind(this),1e3*this.config.pollingIntervalSeconds))}fetchMsgs(e=0){return __awaiter(this,void 0,void 0,(function*(){var t=this.config.cdnUrls;if(t&&t.length>0){var r=t.shift();if(r){this.config.cdnUrls.push(r);var i=this.core.timeOrigin.getNTPTime();if(i-=i%(1e3*this.config.pollingIntervalSeconds),this.lastSuccessTimestamp!==i){r=r.replace("#time",`${i}`);var o=this.config.pollingTimeoutMillis||1e3*this.config.pollingIntervalSeconds/2;this.core.logger.log("CDNUtil::fetchMsgs start:",r);var n={};try{n=yield this.promiseManager.add(this.core.adapters.request(r,{method:"GET",dataType:"json",timeout:o},{exception_service:8}))}catch(t){this.core.logger.warn("CDNUtil::fetchMsgs failed:",t);var s=t;if(s.code===lt.V2NIM_ERROR_CODE_CANCELLED)return;if(e>=3)return;return 404===s.code&&this.core.timeOrigin.setOriginTimetick(),this.fetchMsgs(e+1)}this.requestSuccess(n,i)}}}}))}requestSuccess(e,t){if(this.lastSuccessTimestamp>t)return this.core.logger.warn("CDNUtil::fetchMsgs:ignore",this.lastSuccessTimestamp,t),void(this.lastSuccessTimestamp=0);this.lastSuccessTimestamp=t;var r=get(e,"data.data");if(r){if(e.data.ptm&&(this.config.pollingTimeoutMillis=e.data.ptm),e.data.pis){var i=this.config.pollingIntervalSeconds;this.config.pollingIntervalSeconds=e.data.pis,e.data.pis!==i&&this.polling()}var o=!0===e.data.e?this.decryptAES(r,this.config.decryptKey):r,n=this.formatMessages(o);n=function uniqBy(e,t){e=e||[],t=t||"";for(var r=[],i=[],o=0;o<e.length;o++){var n=e[o][t];-1===i.indexOf(n)&&(i.push(n),r.push(e[o]))}return r}(n,"messageClientId"),n=n.filter((e=>!this.service.sendUtil.checkIfResend(e)&&(this.service.sendUtil.cacheMsg(e),!0))),this.core.logger.log(`CDNUtil::fetchMsgs success at ${t}, msg.length: ${n.length}`),this.emitSmoothly(n,1e3*e.data.c)}}decryptAES(e,t){if(!e||!t)return"[]";try{return fr.decrypt(e,sr.parse(t),{mode:Sr,padding:Ar}).toString(Rr)}catch(e){var r=e;throw new V2NIMErrorImpl({code:lt.V2NIM_ERROR_CODE_INTERNAL,detail:{reason:"Decrypt AES failed",rawError:r}})}}formatMessages(e){var t=[];try{t=JSON.parse(e)}catch(t){var r=t;throw new V2NIMErrorImpl({code:lt.V2NIM_ERROR_CODE_INTERNAL,detail:{reason:"JSON parse error",rawData:e,rawError:r}})}return t.map((e=>formatMessage(this.core,deserialize(e,vr),this.core.account)))}emitSmoothly(e,t){if(e&&e.length>0){var r=Math.ceil(t/this.msgBufferInterval),i=Math.ceil(e.length*this.msgBufferInterval/t);this.core.logger.log(`CDNUtil::emitSmoothly total length: ${e.length}, group length: ${i}, times: ${r}`),this.emitTimer&&clearInterval(this.emitTimer),this.emitTimer=0,this.emitTimer=setInterval((()=>{var t=e.splice(0,i);if(0===t.length)return this.emitTimer&&clearInterval(this.emitTimer),void(this.emitTimer=0);this.core.V2NIMChatroomService.emit("onReceiveMessages",t)}),this.msgBufferInterval)}}}class V2NIMChatroomMessageServiceImpl extends Service{constructor(e){super("V2NIMChatroomMessageService",e),this.customAttachmentParsers=[],registerParser({cmdMap:Kt,cmdConfig:zt}),this.fileUtil=new FileUtil(this.core,this),this.sendUtil=new SendUtil(this.core,this),this.cdnUtil=new CDNUtil(this.core,this),this.setListener()}reset(e){this.sendUtil.reset(),this.cdnUtil.reset(),this.core.V2NIMClientAntispamUtil.reset(e)}setListener(){this.core.eventBus.on("V2NIMLoginService/loginLifeCycleLoginSucc",(()=>{this.core.timeOrigin.setOriginTimetick()})),this.core.eventBus.on("V2NIMChatroomMessageService/onReceiveNotification",((e,t)=>{16===get(e,"attachment.type")&&this.core.V2NIMChatroomService.emit("onMessageRevokedNotification",t.data.msgId,t.data.msgTime)}))}getMessageList(e){return __awaiter(this,void 0,void 0,(function*(){validate(Yt,{option:e},"",!0);var t=(yield this.core.clientSocket.sendCmd("v2ChatroomGetMessageList",Object.assign(Object.assign({beginTime:0,limit:100},e),{reverse:1===e.direction}))).content.datas;return t.map((e=>formatMessage(this.core,e,this.core.account))),t}))}getMessageListByTag(e){return __awaiter(this,void 0,void 0,(function*(){if(validate(jt,{messageOption:e},"",!0),"number"==typeof(null==e?void 0:e.beginTime)&&"number"==typeof(null==e?void 0:e.endTime)&&e.beginTime>e.endTime)throw new V2NIMErrorImpl({code:lt.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"beginTime must be less than endTime"}});var t=(yield this.core.clientSocket.sendCmd("v2ChatroomGetMessageListByTag",{tag:Object.assign(Object.assign({},e),{tags:JSON.stringify(e.tags),messageType:e.messageTypes?JSON.stringify(e.messageTypes):void 0,reverse:1===e.direction?0:1})})).content.datas;return t.map((e=>formatMessage(this.core,e,this.core.account))),t}))}sendMessage(e,t={},r){return __awaiter(this,void 0,void 0,(function*(){if(validate(Ut,{message:e},"",!0),validate(xt,{params:t},"",!0),e.senderId!==this.core.account)throw new V2NIMErrorImpl({code:lt.V2NIM_ERROR_CODE_MISUSE,detail:{reason:"message.senderId must be self"}});var i=this.core.timeOrigin.getTimeNode(),{messageBeforeSend:o,clientAntispamResult:n}=this.sendUtil.prepareMessage(e,t);return yield this.sendUtil.doSendMessage(i,o,n,r)}))}registerCustomAttachmentParser(e){"function"==typeof e&&-1===this.customAttachmentParsers.indexOf(e)&&this.customAttachmentParsers.unshift(e)}unregisterCustomAttachmentParser(e){var t=this.customAttachmentParsers.indexOf(e);t>-1&&this.customAttachmentParsers.splice(t,1)}v2ChatroomMessageAck(e,t){this.core.clientSocket.sendCmd("v2ChatroomMessageAck",{tag:{messageClientId:e,roomId:t}})}v2ChatroomOnMessageHandler(e){var t=e.content.data,r=t.attachment,i=formatMessage(this.core,t,this.core.account);this.sendUtil.checkIfResend(i)||(5===t.messageType?this.core.eventBus.emit("V2NIMChatroomMessageService/onReceiveNotification",i,r):this.sendUtil.cacheMsg(i),this.sendUtil.doMsgReceiveReport(i,e),delete i.__clientExt,this.core.V2NIMChatroomService.emit("onReceiveMessages",[i]))}v2ChatroomUpdateCDNInfoHandler(e){var t=e.content.chatroomCdnInfo;this.cdnUtil.setOptions(t)}}class V2NIMChatroomMessageCreatorImpl{constructor(e){this.name="V2NIMChatroomMessageCreator",this.defaultNosSceneName="nim_default_im",this.core=e}createMessage(e,t){return Object.assign(Object.assign(Object.assign({messageClientId:ve(),createTime:this.core.timeOrigin.getNTPTime(),senderId:this.core.auth.getLoginUser(),roomId:this.core.auth.getRoomId(),isSelf:!0,sendingState:0,messageType:e,senderClientType:16},t),t.attachment?{attachment:Object.assign(Object.assign({},t.attachment),{raw:attachmentToRaw(e,t.attachment)})}:{}),{messageConfig:Object.assign({historyEnabled:!0,highPriority:!1},t.messageConfig),routeConfig:Object.assign({routeEnabled:!0},t.routeConfig),antispamConfig:Object.assign({antispamEnabled:!0},t.antispamConfig)})}createTextMessage(e){return validate({text:{type:"string",allowEmpty:!1}},{text:e},"",!0),this.createMessage(0,{text:e})}createImageMessage(e,t,r,i,o){validate(Ht,{name:t,sceneName:r,width:i,height:o},"",!0);var n=this.createGenericFileMessageAttachment(e,t,r,void 0,i,o,"jpeg");return this.createMessage(1,{attachment:n,attachmentUploadState:0})}createAudioMessage(e,t,r,i){validate(Ft,{name:t,sceneName:r,duration:i},"",!0);var o=this.createGenericFileMessageAttachment(e,t,r,i,void 0,void 0,"aac");return this.createMessage(2,{attachment:o,attachmentUploadState:0})}createVideoMessage(e,t,r,i,o,n){validate(Bt,{name:t,sceneName:r,duration:i,width:o,height:n},"",!0);var s=this.createGenericFileMessageAttachment(e,t,r,i,o,n,"mp4");return this.createMessage(3,{attachment:s,attachmentUploadState:0})}createFileMessage(e,t,r){validate(Gt,{name:t,sceneName:r},"",!0);var i=this.createGenericFileMessageAttachment(e,t,r,void 0,void 0,void 0,"txt");return this.createMessage(6,{attachment:i,attachmentUploadState:0})}createGenericFileMessageAttachment(e,t,r,i,o,n,s){if(r=r||this.defaultNosSceneName,!this.core.V2NIMStorageService.hasStorageScene(r))throw new V2NIMErrorImpl({code:lt.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"sceneName: "+r+" has not been added"}});var{file:a,path:c}=getFileOrPath(e),_=Object.assign(Object.assign(Object.assign({name:t,uploadState:0,sceneName:r||this.defaultNosSceneName},i?{duration:i}:{}),o?{width:o}:{}),n?{height:n}:{});if(a){var l=a.name.lastIndexOf("."),d=-1===l?a.name:a.name.substring(0,l);_.name=_.name||d,_.size=a.size,_.ext=`.${getFileExtension(a.name)||getFileExtension(t||"")||s}`}else if(c){var E=c.lastIndexOf("/"),h=c.lastIndexOf("."),u=-1===h?c.substring(E+1):c.substring(E+1,h);_.name=_.name||u,_.ext=`.${getFileExtension(c)||getFileExtension(t||"")||s}`}return _=JSON.parse(JSON.stringify(_)),c?_.path=c:a&&(_.file=a),_}createLocationMessage(e,t,r){return validate({latitude:{type:"number",allowEmpty:!1},longitude:{type:"number",allowEmpty:!1},address:{type:"string",allowEmpty:!1}},{latitude:e,longitude:t,address:r},"",!0),this.createMessage(4,{attachment:{latitude:e,longitude:t,address:r}})}createCustomMessage(e){return validate({rawAttachment:{type:"string"}},{rawAttachment:e},"",!0),this.createMessage(100,{attachment:{raw:e}})}createCustomMessageWithAttachment(e,t){return validate({raw:{type:"string"}},e,"attachment",!0),validate({subType:{type:"number",min:0,required:!1}},{subType:t},"",!0),this.createMessage(100,t?{attachment:e,subType:t}:{attachment:e})}createForwardMessage(e){if([11,5,7,10].includes(e.messageType))return null;var t={messageClientId:ve(),messageType:e.messageType};return e.text&&(t.text=e.text),e.attachment&&(t.attachment=e.attachment),e.attachment&&"uploadState"in e.attachment&&(t.attachmentUploadState=e.attachment.uploadState),this.createMessage(e.messageType,t)}createTipsMessage(e){return validate({text:{type:"string",allowEmpty:!1}},{text:e},"",!0),this.createMessage(10,{text:e})}}var yr={option:{type:"object",rules:{memberRoles:{type:"array",itemType:"enum",values:[4,1,2,0,3,5],required:!1},onlyBlocked:{type:"boolean",required:!1},onlyChatBanned:{type:"boolean",required:!1},onlyOnline:{type:"boolean",required:!1},pageToken:{type:"string",required:!1},limit:{type:"number",min:1,required:!1}}}},Dr={accountId:{type:"string",allowEmpty:!1},updateParams:{type:"object",rules:{memberRole:{type:"enum",values:[2,0,3]},memberLevel:{type:"number",min:0,required:!1},notificationExtension:{type:"string",required:!1}}}},Vr={accountId:{type:"string",allowEmpty:!1},blocked:{type:"boolean"},notificationExtension:{type:"string",required:!1}},Lr={accountId:{type:"string",allowEmpty:!1},chatBanned:{type:"boolean"},notificationExtension:{type:"string",required:!1}},br={updateParams:{type:"object",rules:{roomNick:{type:"string",allowEmpty:!1,required:!1},roomAvatar:{type:"string",required:!1},serverExtension:{type:"string",required:!1},notificationEnabled:{type:"boolean",required:!1},notificationExtension:{type:"string",required:!1},persistence:{type:"boolean",required:!1}}},antispamConfig:{type:"object",required:!1,rules:{antispamBusinessId:{type:"string",required:!1}}}},Pr={accountId:{type:"string",allowEmpty:!1},tempChatBannedDuration:{type:"number",min:0},notificationEnabled:{type:"boolean"},notificationExtension:{type:"string",required:!1}},kr={option:{type:"object",rules:{tag:{type:"string",allowEmpty:!1},pageToken:{type:"string",required:!1},limit:{type:"number",min:1,required:!1}}}};class V2NIMChatroomMemberServiceImpl extends Service{constructor(e){super("V2NIMChatroomMemberService",e),registerParser({cmdMap:Xe,cmdConfig:rt})}getMemberListByOption(e){return __awaiter(this,void 0,void 0,(function*(){validate(yr,{option:e},"",!0);var t=yield this.core.clientSocket.sendCmd("v2ChatroomGetMemberListByOption",{tag:e});return{finished:!t.content.hasMore,pageToken:t.content.pageToken,memberList:t.content.datas}}))}updateMemberRole(e,t){return __awaiter(this,void 0,void 0,(function*(){validate(Dr,{accountId:e,updateParams:t},"",!0),yield this.core.sendCmd("v2ChatroomUpdateMemberRole",{tag:Object.assign(Object.assign({notificationExtension:""},t),{accountId:e})})}))}setMemberBlockedStatus(e,t,r){return __awaiter(this,void 0,void 0,(function*(){var i={accountId:e,blocked:t,notificationExtension:r};i.notificationExtension=i.notificationExtension||"",validate(Vr,i,"",!0),yield this.core.sendCmd("v2ChatroomSetMemberBlockedStatus",i)}))}setMemberChatBannedStatus(e,t,r){return __awaiter(this,void 0,void 0,(function*(){var i={accountId:e,chatBanned:t,notificationExtension:r};i.notificationExtension=i.notificationExtension||"",validate(Lr,i,"",!0),yield this.core.sendCmd("v2ChatroomSetMemberChatBannedStatus",i)}))}setMemberTempChatBanned(e,t,r,i){return __awaiter(this,void 0,void 0,(function*(){var o={accountId:e,tempChatBannedDuration:t,notificationEnabled:r,notificationExtension:i};validate(Pr,o,"",!0),o.notificationExtension=o.notificationExtension||"",yield this.core.sendCmd("v2ChatroomSetMemberTempChatBanned",o)}))}updateSelfMemberInfo(e,t){return __awaiter(this,void 0,void 0,(function*(){if(validate(br,{updateParams:e,antispamConfig:t},"",!0),void 0===e.roomAvatar&&void 0===e.roomNick&&void 0===e.serverExtension)throw new V2NIMErrorImpl({code:lt.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"updateSelfMemberInfo: nothing to update"}});yield this.core.clientSocket.sendCmd("v2ChatroomUpdateSelfMemberInfo",{tag:e,notificationEnabled:"boolean"!=typeof e.notificationEnabled||e.notificationEnabled,notificationExtension:e.notificationExtension||"",persistence:"boolean"==typeof e.persistence&&e.persistence,antispamConfig:t})}))}getMemberByIds(e){return __awaiter(this,void 0,void 0,(function*(){return validate({accountIds:{type:"array",itemType:"string",min:1}},{accountIds:e},"",!0),(yield this.core.clientSocket.sendCmd("v2ChatroomGetMemberByIds",{accountIds:e})).content.datas}))}kickMember(e,t){return __awaiter(this,void 0,void 0,(function*(){validate({accountId:{type:"string",allowEmpty:!1}},{accountId:e},"",!0),validate({notificationExtension:{type:"string",required:!1}},{notificationExtension:t},"",!0),yield this.core.clientSocket.sendCmd("v2ChatroomKickMember",{accountId:e,notificationExtension:t})}))}getMemberListByTag(e){return __awaiter(this,void 0,void 0,(function*(){validate(kr,{option:e},"",!0);var t=yield this.core.clientSocket.sendCmd("v2ChatroomGetMemberListByTag",{tag:Object.assign({limit:100},e)});return{finished:!t.content.hasMore,pageToken:t.content.pageToken,memberList:t.content.datas}}))}getMemberCountByTag(e){return __awaiter(this,void 0,void 0,(function*(){return validate({tag:{type:"string",allowEmpty:!1}},{tag:e},"",!0),(yield this.core.clientSocket.sendCmd("v2ChatroomGetMemberCountByTag",{tag:e})).content.data}))}v2ChatroomOnMemberTagUpdatedHandler(e){var t;if(null===(t=e.content.data)||void 0===t?void 0:t.tag){var r=JSON.parse(e.content.data.tag);this.core.V2NIMChatroomService.emit("onChatroomTagsUpdated",r)}}}class V2NIMChatroomServiceEventImpl{constructor(e,t){this.core=e,this.service=t,this.logger=this.core.logger}setListener(){this.core.eventBus.on("V2NIMChatroomMessageService/onReceiveNotification",this.onReceiveNotification.bind(this))}onReceiveNotification(e,t){return __awaiter(this,void 0,void 0,(function*(){var r=e.attachment;switch(get(e,"attachment.type")){case 0:var i=e.attachment.currentMember;i&&this.service.emit("onChatroomMemberEnter",i),r.operatorId!==this.core.account&&this.core.V2NIMChatroomInfoService.model.chatroomInfo&&this.core.V2NIMChatroomInfoService.model.chatroomInfo.onlineUserCount++;break;case 7:if(Array.isArray(r.targetIds))for(var o=0;o<r.targetIds.length;o++)this.service.emit("onChatroomMemberExit",r.targetIds[o]);break;case 1:this.service.emit("onChatroomMemberExit",r.operatorId),r.operatorId!==this.core.account&&this.core.V2NIMChatroomInfoService.model.chatroomInfo&&this.core.V2NIMChatroomInfoService.model.chatroomInfo.onlineUserCount--;break;case 3:break;case 4:r.targetIds&&r.targetIds.includes(this.core.account)&&this.service.emit("onSelfChatBannedUpdated",!0);break;case 5:r.targetIds&&r.targetIds.includes(this.core.account)&&this.service.emit("onSelfChatBannedUpdated",!1);break;case 18:"currentMember"in r&&"previousRole"in r&&this.service.emit("onChatroomMemberRoleUpdated",r.previousRole,r.currentMember);break;case 8:if(e.attachment.targetIds.includes(this.core.account)){var n=t.data.muteDuration;this.service.emit("onSelfTempChatBannedUpdated",!0,n)}break;case 14:if(this.core.tags.includes(t.data.targetTag)){var s=t.data.muteDuration;this.service.emit("onSelfTempChatBannedUpdated",!0,s)}break;case 9:e.attachment.targetIds.includes(this.core.account)&&this.service.emit("onSelfTempChatBannedUpdated",!1,0);break;case 15:this.service.emit("onSelfTempChatBannedUpdated",!1,0);break;case 12:this.service.emit("onChatroomChatBannedUpdated",!0),this.core.V2NIMChatroomInfoService.model.chatroomInfo&&(this.core.V2NIMChatroomInfoService.model.chatroomInfo.chatBanned=!0);break;case 13:this.service.emit("onChatroomChatBannedUpdated",!1),this.core.V2NIMChatroomInfoService.model.chatroomInfo&&(this.core.V2NIMChatroomInfoService.model.chatroomInfo.chatBanned=!1);break;case 17:this.core.options.tags=t.data.tags||[],this.service.emit("onChatroomTagsUpdated",t.data.tags);break;case 10:var a=e.attachment.currentMember;a&&(a.memberLevel=a.memberLevel||0,this.service.emit("onChatroomMemberInfoUpdated",a))}}))}beforeEmit(e,...t){var r=`${this.service.name}::emit ${e.toString()}`;if("onSendMessage"===e){var i=t[0];this.logger.log(`${r}`,`${i.messageClientId};createTime:${i.createTime};`,`sendingState:${i.sendingState};attachmentUploadState:${i.attachmentUploadState||0}`)}else if("onReceiveMessages"===e){var o=t[0];this.logger.log(`${r}`,o.map((e=>`${e.messageClientId};createTime:${e.createTime}`)))}else if("onChatroomMemberEnter"===e||"onChatroomMemberInfoUpdated"===e){var n=t[0];this.logger.log(`${r}`,`accountId:${n.accountId}`)}else if("onChatroomMemberRoleUpdated"===e){var s=t[1];this.logger.log(`${r}`,t[0],`accountId:${s.accountId};memberRole:${s.memberRole}`)}else this.logger.log(`${r}`,...t)}}class V2NIMChatroomServiceImpl extends V2ChatroomService{constructor(e){super("V2NIMChatroomService",e),this.event=new V2NIMChatroomServiceEventImpl(e,this),this.setListener()}setListener(){this.event.setListener()}emit(e,...t){return this.event.beforeEmit(e,...t),super.emit(e,...t)}sendMessage(e,t,r){return this.core.V2NIMChatroomMessageService.sendMessage(e,t,r)}cancelMessageAttachmentUpload(e){return this.core.V2NIMChatroomMessageService.fileUtil.cancelMessageAttachmentUpload(e)}registerCustomAttachmentParser(e){this.core.V2NIMChatroomMessageService.registerCustomAttachmentParser(e)}unregisterCustomAttachmentParser(e){this.core.V2NIMChatroomMessageService.unregisterCustomAttachmentParser(e)}getMessageList(e){return this.core.V2NIMChatroomMessageService.getMessageList(e)}getMessageListByTag(e){return this.core.V2NIMChatroomMessageService.getMessageListByTag(e)}getMemberListByOption(e){return this.core.V2NIMChatroomMemberService.getMemberListByOption(e)}updateMemberRole(e,t){return this.core.V2NIMChatroomMemberService.updateMemberRole(e,t)}setMemberBlockedStatus(e,t,r){return this.core.V2NIMChatroomMemberService.setMemberBlockedStatus(e,t,r)}setMemberChatBannedStatus(e,t,r){return this.core.V2NIMChatroomMemberService.setMemberChatBannedStatus(e,t,r)}setMemberTempChatBanned(e,t,r,i){return this.core.V2NIMChatroomMemberService.setMemberTempChatBanned(e,t,r,i)}updateSelfMemberInfo(e,t){return this.core.V2NIMChatroomMemberService.updateSelfMemberInfo(e,t)}getMemberByIds(e){return this.core.V2NIMChatroomMemberService.getMemberByIds(e)}kickMember(e,t){return this.core.V2NIMChatroomMemberService.kickMember(e,t)}getMemberListByTag(e){return this.core.V2NIMChatroomMemberService.getMemberListByTag(e)}getMemberCountByTag(e){return this.core.V2NIMChatroomMemberService.getMemberCountByTag(e)}getChatroomInfo(){return this.core.V2NIMChatroomInfoService.getChatroomInfo()}updateChatroomInfo(e,t){return __awaiter(this,void 0,void 0,(function*(){return this.core.V2NIMChatroomInfoService.updateChatroomInfo(e,t)}))}updateChatroomLocationInfo(e){return __awaiter(this,void 0,void 0,(function*(){return this.core.V2NIMChatroomInfoService.updateChatroomLocationInfo(e)}))}updateChatroomTags(e){return __awaiter(this,void 0,void 0,(function*(){return this.core.V2NIMChatroomInfoService.updateChatroomTags(e)}))}setTempChatBannedByTag(e){return __awaiter(this,void 0,void 0,(function*(){return this.core.V2NIMChatroomInfoService.setTempChatBannedByTag(e)}))}}class V2NIMClientAntispamUtilImpl{constructor(e,t){this.config={enable:!1},this.core=e,t&&this.setOptions(t)}setOptions(e){this.config=Object.assign(this.config,e)}reset(e){"destroy"===e&&(this.vocabInfo=void 0)}downloadLocalAntiSpamVocabs(){return __awaiter(this,void 0,void 0,(function*(){if(this.config.enable&&!this.vocabInfo)try{var e=yield this.core.sendCmd("v2ChatroomDownloadLocalAntiSpamVocabs",{tag:{version:0,md5:""}});e.content.data&&(this.vocabInfo=Object.assign(Object.assign({},e.content.data),{thesaurus:e.content.data.thesaurus?JSON.parse(e.content.data.thesaurus).thesaurus:[]}))}catch(e){this.core.logger.warn("V2NIMLocalAntispamUtil::downloadLocalAntiSpamVocabs error",e)}}))}checkTextAntispam(e,t="**"){if(!this.config.enable)return{operateType:0,replacedText:e};if(validate({text:{type:"string",required:!0,allowEmpty:!1},replace:{type:"string"}},{text:e,replace:t},"",!0),!this.vocabInfo)return{operateType:0,replacedText:e};for(var r=e,i=0;i<this.vocabInfo.thesaurus.length;i++){var o=this.filterContent(r,this.vocabInfo.thesaurus[i],t);if(r=o.replacedText,2===o.operateType||3===o.operateType)return o}return{operateType:r===e?0:1,replacedText:r}}filterContent(e,t,r){for(var i=0;i<t.keys.length;i++){var o=t.keys[i],n=o.match||t.match,s=o.operate||t.operate,a=void 0;try{a=this.matchContent(e,o.key,n,s,r)}catch(e){}if(a&&(e=a.replacedText,2===a.operateType||3===a.operateType))return a}return{operateType:1,replacedText:e}}matchContent(e,t,r,i,o){var n=!1,s=null;if(1===r){if(e.indexOf(t)>=0){n=!0;var a=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");s=new RegExp(a,"g")}}else 2===r&&(s=new RegExp(t,"g")).test(e)&&(n=!0);if(n&&s)switch(i){case 1:return{operateType:1,replacedText:e.replace(s,o)};case 2:return{operateType:2,replacedText:e};case 3:return{operateType:3,replacedText:e}}return{operateType:0,replacedText:e}}}var wr={initParams:{type:"object",rules:{appkey:{type:"string",allowEmpty:!1},customClientType:{type:"number",required:!1},isFixedDeviceId:{type:"boolean",required:!1},debugLevel:{type:"enum",values:["off","error","warn","log","debug"],required:!1}}},otherParams:{type:"object",rules:{cloudStorageConfig:{type:"object",required:!1,rules:{commonUploadHost:{type:"string",required:!1},commonUploadHostBackupList:{type:"array",required:!1,itemType:"string"},chunkUploadHost:{type:"string",required:!1},uploadReplaceFormat:{type:"string",required:!1},downloadUrl:{type:"string",required:!1},downloadHostList:{type:"array",required:!1},nosCdnEnable:{type:"boolean",required:!1},storageKeyPrefix:{type:"string",required:!1},isNeedToGetUploadPolicyFromServer:{type:"boolean",required:!1},cdn:{type:"object",required:!1,allowEmpty:!1,rules:{defaultCdnDomain:{type:"string",required:!1},cdnDomain:{type:"string",required:!1},bucket:{type:"string",required:!1},objectNamePrefix:{type:"string",required:!1}}}}},reporterConfig:{type:"object",allowEmpty:!1,required:!1,rules:{enableCompass:{type:"boolean",required:!1},compassDataEndpoint:{type:"string",required:!1},isDataReportEnable:{type:"boolean",required:!1}}},abtestConfig:{type:"object",allowEmpty:!1,required:!1,rules:{isAbtestEnable:{type:"boolean",required:!1},abtestUrl:{type:"string",required:!1}}}}}};function getIsDataReportEnable(e){var t,r,i=!0;return"boolean"==typeof(null===(t=null==e?void 0:e.reporterConfig)||void 0===t?void 0:t.enableCompass)?i=e.reporterConfig.enableCompass:"boolean"==typeof(null===(r=null==e?void 0:e.reporterConfig)||void 0===r?void 0:r.isDataReportEnable)&&(i=e.reporterConfig.isDataReportEnable),i}function getCompassDataEndpoint(e,t){var r,i,o=null===(r=null==t?void 0:t.reporterConfig)||void 0===r?void 0:r.compassDataEndpoint,n=null===(i=null==t?void 0:t.reporterConfig)||void 0===i?void 0:i.reportConfigUrl;if(o)return o;if(n){var s=n.match(/^https:\/\/([^/]+)\/*/);if(Array.isArray(s)&&s.length>=1)return`https://${s[1]}`;e.error(`Invalid reportConfigUrl: ${n}`)}return function pendingIsMiniappEnv(){var{hostEnvEnum:e}=ce.getSystemInfo();return 6===e||102===e||103===e||104===e}()?"https://statistic.live.126.net":"https://statistic.live.126.net,https://statistic-overseas.yunxinfw.com"}var Ur="V2NIMChatroomQueueService",xr={"36_20":"v2ChatroomQueueOffer","36_21":"v2ChatroomQueuePoll","36_22":"v2ChatroomQueueList","36_23":"v2ChatroomQueuePeek","36_24":"v2ChatroomQueueDrop","36_25":"v2ChatroomQueueInit","36_26":"v2ChatroomQueueBatchUpdate"},Gr={v2ChatroomQueueOffer:{sid:36,cid:20,service:Ur,params:[{type:"String",name:"elementKey"},{type:"String",name:"elementValue"},{type:"Bool",name:"transient"},{type:"String",name:"elementOwnerAccountId"}]},v2ChatroomQueuePoll:{sid:36,cid:21,service:Ur,params:[{type:"String",name:"elementKey"}],response:[{type:"String",name:"elementKey"},{type:"String",name:"elementValue"}]},v2ChatroomQueueList:{sid:36,cid:22,service:Ur,params:[],response:[{type:"KVArray",name:"datas"}]},v2ChatroomQueuePeek:{sid:36,cid:23,service:Ur,params:[],response:[{type:"String",name:"elementKey"},{type:"String",name:"elementValue"}]},v2ChatroomQueueDrop:{sid:36,cid:24,service:Ur,params:[]},v2ChatroomQueueInit:{sid:36,cid:25,service:Ur,params:[{type:"Int",name:"size"}]},v2ChatroomQueueBatchUpdate:{sid:36,cid:26,service:Ur,params:[{type:"StrStrMap",name:"keyValues"},{type:"Bool",name:"notificationEnabled"},{type:"String",name:"notificationExtension"}],response:[{type:"StrArray",name:"datas"}]}},Fr={elementKey:{type:"string",required:!0,allowEmpty:!1},elementValue:{type:"string",required:!0,allowEmpty:!1},transient:{type:"boolean",required:!1},elementOwnerAccountId:{type:"string",required:!1,allowEmpty:!1}},Br={elements:{type:"array",min:1,max:100,rules:{key:{type:"string",required:!0,allowEmpty:!1},value:{type:"string",required:!0,allowEmpty:!1}},required:!0},notificationEnabled:{type:"boolean",required:!1},notificationExtension:{type:"string",required:!1}};class V2NIMChatroomQueueServiceImpl extends V2ChatroomService{constructor(e){super("V2NIMChatroomQueueService",e),registerParser({cmdMap:xr,cmdConfig:Gr}),this.setListeners()}setListeners(){this.core.eventBus.on("V2NIMChatroomMessageService/onReceiveNotification",(e=>__awaiter(this,void 0,void 0,(function*(){if(11===e.attachment.type)try{var t=JSON.parse(e.attachment.raw),r=JSON.parse(t.data.queueChange);if("OFFER"===r._e)this.emit("onChatroomQueueOffered",{key:r.key,value:r.content});else if("POLL"===r._e)this.emit("onChatroomQueuePolled",{key:r.key,value:r.content});else if("DROP"===r._e)this.emit("onChatroomQueueDropped");else if("BATCH_UPDATE"===r._e){var i=formatQueueElementsFromKVObject(r.kvObject);i.length>0&&this.emit("onChatroomQueueBatchUpdated",i)}else if("PARTCLEAR"===r._e){var o=formatQueueElementsFromKVObject(r.kvObject);o.length>0&&this.emit("onChatroomQueuePartCleared",o)}else if("BATCH_OFFER"===r._e){var n=formatQueueElementsFromElements(r.elements);n.length>0&&this.emit("onChatroomQueueBatchOffered",n)}}catch(t){this.logger.error("V2NIMChatroomQueueServiceImpl json parse error",t," raw = ",e.attachment.raw)}}))))}emit(e,...t){var r=`${this.name}::emit ${e.toString()}`;return this.logger.log(`${r}`,...t),super.emit(e,...t)}queueOffer(e){return __awaiter(this,void 0,void 0,(function*(){validate(Fr,e,"",!0),yield this.core.sendCmd("v2ChatroomQueueOffer",e)}))}queuePoll(e){return __awaiter(this,void 0,void 0,(function*(){e="string"==typeof e?e:"";var t=yield this.core.sendCmd("v2ChatroomQueuePoll",{elementKey:e});return{key:t.content.elementKey,value:t.content.elementValue}}))}queueList(){return __awaiter(this,void 0,void 0,(function*(){return function formatQueueElements(e){return e&&e.length>0?e.map((e=>{var t=Object.keys(e)[0];return{key:t,value:e[t]}})):[]}((yield this.core.sendCmd("v2ChatroomQueueList")).content.datas)}))}queuePeek(){return __awaiter(this,void 0,void 0,(function*(){var e=yield this.core.sendCmd("v2ChatroomQueuePeek");return{key:e.content.elementKey,value:e.content.elementValue}}))}queueDrop(){return __awaiter(this,void 0,void 0,(function*(){yield this.core.sendCmd("v2ChatroomQueueDrop")}))}queueInit(e){return __awaiter(this,void 0,void 0,(function*(){validate({size:{type:"number",min:0,max:1e3}},{size:e},"",!0),yield this.core.sendCmd("v2ChatroomQueueInit",{size:e})}))}queueBatchUpdate(e,t=!0,r){return __awaiter(this,void 0,void 0,(function*(){validate(Br,{elements:e,notificationEnabled:t,notificationExtension:r},"",!0);var i=e.reduce(((e,t)=>(e[t.key]=t.value,e)),{});return(yield this.core.sendCmd("v2ChatroomQueueBatchUpdate",{keyValues:i,notificationEnabled:t,notificationExtension:r})).content.datas}))}}var Hr=1,Yr={};class V2NIMChatroomClient extends Ie{constructor(e,r={}){var i,o,n;if(super(),this.pluginMap={},this.eventBus=new Ie,this.options={appkey:"",account:"",tags:[],debugLevel:"debug",xhrConnectTimeout:8e3,socketConnectTimeout:8e3,apiVersion:"v2",isFixedDeviceId:!1,loginSDKTypeParamCompat:!1,binaryWebsocket:!0},this.config={deviceId:"",clientSession:"",binaryWebsocket:!0},this.options.appkey=e.appkey,this.options.customClientType=e.customClientType,this.options.isFixedDeviceId=e.isFixedDeviceId,this.options.loginSDKTypeParamCompat=e.loginSDKTypeParamCompat,this.instanceId=Hr,Hr+=1,this.logger=new Logger(e.debugLevel||"debug",r.loggerConfig),r.privateConf){var{cloudStorageConfig:s,reporterConfig:a}=this.getConfigFromPrivate(r.privateConf);r=Object.assign(Object.assign({},r),{cloudStorageConfig:Object.assign(Object.assign({},r.cloudStorageConfig||{}),s),reporterConfig:Object.assign(Object.assign({},r.reporterConfig||{}),a)})}this.timerManager=new TimerManager,this.adapters=new CoreAdapters(this),this.timeOrigin=new TimeOrigin(this,{},"v2ChatroomGetServerTime"),this.reporterHookLinkKeep=new ReporterHookLinkKeep(this),"boolean"==typeof e.binaryWebsocket&&(this.options.binaryWebsocket=e.binaryWebsocket),this.options.isFixedDeviceId?(this.config.deviceId=ce.localStorage.getItem("__CHATROOM_DEVC_ID__")||ve(),this.config.clientSession=ce.localStorage.getItem("__CHATROOM_CLIENT_SESSION_ID__")||ve(),ce.localStorage.setItem("__CHATROOM_DEVC_ID__",this.config.deviceId),ce.localStorage.setItem("__CHATROOM_CLIENT_SESSION_ID__",this.config.clientSession)):(this.config.deviceId=ve(),this.config.clientSession=ve()),this.abtest=new ABTest(this,{isAbtestEnable:void 0===(null===(i=r.abtestConfig)||void 0===i?void 0:i.isAbtestEnable)||(null===(o=r.abtestConfig)||void 0===o?void 0:o.isAbtestEnable),abtestUrl:(null===(n=r.abtestConfig)||void 0===n?void 0:n.abtestUrl)||ge,abtestProjectKey:pe});var c=ce.getSystemInfo(),_=getCompassDataEndpoint(this.logger,r);this.reporter=new t(Object.assign(Object.assign({},_?{compassDataEndpoint:_}:{}),{isDataReportEnable:getIsDataReportEnable(r),common:{app_key:e.appkey,dev_id:this.config.deviceId,platform:"Web",sdk_ver:"10.9.71",env:"online",os_name:c.os,os_ver:c.osVer,lib_env:c.libEnv,host_env:c.hostEnv,host_env_ver:c.hostEnvVer,manufactor:c.manufactor,model:c.model,v2:!0},request:ce.request,logger:this.logger,autoStart:!0})),ce.setLogger(this.logger),this.auth=new V2NIMChatroomLoginServiceImpl(this),this.V2NIMChatroomLoginService=this.auth,!1!==this.options.binaryWebsocket&&"function"==typeof Uint8Array?(this.config.binaryWebsocket=!0,this.clientSocket=new V2BinaryClientSocket(this)):(this.config.binaryWebsocket=!1,this.clientSocket=new V2ClientSocket(this)),this.cloudStorage=new CloudStorageService(this,Object.assign({storageKeyPrefix:"V2NIMChatroomClient"},r.cloudStorageConfig)),this.V2NIMChatroomQueueService=new V2NIMChatroomQueueServiceImpl(this),this.V2NIMChatroomInfoService=new V2NIMChatroomInfoServiceImpl(this),this.V2NIMStorageService=new V2NIMStorageServiceImpl(this),this.V2NIMStorageUtil=new V2NIMStorageUtil(this),this.V2NIMChatroomMessageService=new V2NIMChatroomMessageServiceImpl(this),this.V2NIMChatroomMessageCreator=new V2NIMChatroomMessageCreatorImpl(this),this.V2NIMClientAntispamUtil=new V2NIMClientAntispamUtilImpl(this,r.V2NIMClientAntispamUtilConfig),this.V2NIMChatroomMemberService=new V2NIMChatroomMemberServiceImpl(this),this.V2NIMChatroomService=new V2NIMChatroomServiceImpl(this),this.logger.log(`NIM chatroom init, version:10.9.71, sdk version:100971, appkey:${e.appkey}`)}static getInstanceList(){return Object.values(Yr)}static getInstance(e){return validate({instanceId:{type:"number",allowEmpty:!1}},{instanceId:e},"",!0),Yr[e]}static newInstance(e,t={}){validate(wr,{initParams:e,otherParams:t},"",!0);var r=new V2NIMChatroomClient(e,t);return Yr[r.instanceId]=r,r}static destroyInstance(e){var t=this.getInstance(e);if(t)return delete Yr[e],t._exitAsync().then((()=>{t._clear()})).catch((()=>{t._clear()}))}static destroyAll(){for(var e in Yr)this.destroyInstance(Number(e))}getConfigFromPrivate(e){return e?{cloudStorageConfig:JSON.parse(JSON.stringify({chunkUploadHost:e.nos_uploader||void 0,commonUploadHost:e.nos_uploader||void 0,commonUploadHostBackupList:e.nos_uploader?[e.nos_uploader]:void 0,chunkUploadHostBackupList:e.nos_uploader?[e.nos_uploader]:void 0,uploadReplaceFormat:e.nos_downloader_v2?`${e.nosSsl?"https://":"http://"}${e.nos_downloader_v2}`:void 0,downloadUrl:void 0!==e.nos_accelerate?e.nos_accelerate:void 0,downloadHostList:""===e.nos_accelerate_host?[]:"string"==typeof e.nos_accelerate_host?[e.nos_accelerate_host]:Array.isArray(e.nos_accelerate_host)?e.nos_accelerate_host:void 0})),reporterConfig:JSON.parse(JSON.stringify({enableCompass:"boolean"==typeof e.enableCompass?e.enableCompass:void 0,compassDataEndpoint:e.compassDataEndpoint||void 0}))}:{cloudStorageConfig:{},reporterConfig:{}}}getInstanceId(){return this.instanceId}_clearModuleData(e="logout"){Object.values(this).forEach((t=>{t&&"function"==typeof t.reset&&t.reset(e)}))}_removeAllModuleListeners(){Object.values(this).forEach((e=>{e&&"function"==typeof e.removeAllListeners&&e.removeAllListeners()}))}_clear(){this.removeAllListeners(),this.eventBus.removeAllListeners(),this.logger.destroy(),this.reporter.destroy(),this.timerManager.destroy(),this._clearModuleData("destroy"),this._removeAllModuleListeners()}enter(e,t){var r;return __awaiter(this,void 0,void 0,(function*(){if(validate(It,{roomId:e,enterParams:t},"",!0),!t.accountId&&!t.anonymousMode)throw new V2NIMErrorImpl({code:lt.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"accountId is required"}});var i=get(t,"loginOption.authType")||0;if(t.loginOption=t.loginOption||{authType:i},0===i&&!t.anonymousMode&&!t.token)throw new V2NIMErrorImpl({code:lt.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"token is required when authType == 0"}});if(1===i&&!(null===(r=t.loginOption)||void 0===r?void 0:r.tokenProvider))throw new V2NIMErrorImpl({code:lt.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:"tokenProvider is required when authType == 1"}});var o=yield this.auth.login(this.options.appkey,e,t);return this.V2NIMChatroomInfoService._setChatroomInfo(o.chatroom),o}))}_exitAsync(){return __awaiter(this,void 0,void 0,(function*(){this.auth.reset();try{return void(yield this.auth.logout())}catch(e){return Promise.resolve()}}))}exit(){this._exitAsync()}sendCmd(e,t,r){return this.clientSocket.sendCmd(e,t,r)}get account(){return this.options.account}get tags(){return this.options.tags}get status(){return 5===this.auth.lifeCycle.chatroomStatus?"logined":""}getChatroomInfo(){return this.V2NIMChatroomInfoService.getChatroomInfo()}_registerDep(e,t){}emit(e,...t){var r=`core::emit ${e.toString()}`;return this.logger.log(`${r}`,...t),super.emit(e,...t)}}V2NIMChatroomClient.sdkVersion=100971,V2NIMChatroomClient.sdkVersionFormat="10.9.71";var jr={wifi:2,"2g":3,"3g":4,"4g":5,"5g":6,ethernet:1,unknown:0,none:0,notreachable:0,wwan:0};function getNetFn(e){var t=null;return{getNetworkStatus:()=>new Promise(((t,r)=>{e.getNetworkType({success:function(e){var r=e.networkType||e.subtype||"unknown",i=!1;i="boolean"==typeof e.networkAvailable?e.networkAvailable:"none"!==r.toLowerCase(),t({net_type:jr[r.toLowerCase()]||0,net_connect:i})},fail:function(){r(new Error("getNetworkType failed"))}})})),onNetworkStatusChange(r){this.offNetworkStatusChange(),e.onNetworkStatusChange&&(t=function(e){var t=(e.networkType||e.subtype||"unknown").toLowerCase();r({isConnected:e.isConnected||"none"!==t,networkType:jr[t]})},e.onNetworkStatusChange(t))},offNetworkStatusChange(){e.offNetworkStatusChange&&(t&&e.offNetworkStatusChange(t),t=null)}}}var $r={debug(...e){},log(...e){},warn(...e){},error(...e){}};function setLogger(e){$r=e}function getLogger(){return $r}function base64ToArrayBuffer(e){for(var t=function base64Decode(e){var t=String(e).replace(/[=]+$/,"");if(t.length%4==1)throw new Error("'atob' failed: The string to be decoded is not correctly encoded.");for(var r,i="",o=0,n=0,s=0;r=t.charAt(s++);~r&&(n=o%4?64*n+r:r,o++%4)?i+=String.fromCharCode(255&n>>(-2*o&6)):0)r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(r);return i}(e),r=t.length,i=new Uint8Array(r),o=0;o<r;o++)i[o]=t.charCodeAt(o);return i.buffer}var Kr=getLogger();class PowerMonitor extends Ie{constructor(e){super(),this.env=e,this.status=0,this.appShowListener=null,this.appHideListener=null,this.flag=!1,this._initAppLifecycleListener()}isActive(){return 0===this.status}getStatus(){return this.status}setStatus(e){var t=this.status;e!==t&&(this.status=e,0===e&&1===t&&this.emit("onPowerMonitorTurnActive"),Kr.log("Adapter powerMonitor::setStatus: ",e))}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 e=this.status;this.status=0,1===e&&this.emit("onPowerMonitorTurnActive"),Kr.log("Adapter powerMonitor::onAppShow status:",this.status)},this.appHideListener=()=>{this.status=1,Kr.log("Adapter powerMonitor::onAppHide status:",this.status)},this.env.onAppShow(this.appShowListener),this.env.onAppHide(this.appHideListener),this.flag=!0,Kr.log("Adapter powerMonitor::_initAppLifecycleListener success")):Kr.warn("Adapter powerMonitor::_initAppLifecycleListener env.onAppShow/env.onAppHide not available"))}_canIUse(){return void 0!==this.env&&"function"==typeof this.env.onAppShow&&"function"==typeof this.env.onAppHide&&"function"==typeof this.env.offAppShow&&"function"==typeof this.env.offAppHide}}function getAPIEnv(){return"undefined"!=typeof qq&&"function"==typeof qq.request?qq:"undefined"!=typeof tt&&"function"==typeof tt.request?tt:"undefined"!=typeof swan&&"function"==typeof swan.request?swan:"undefined"!=typeof my&&"function"==typeof my.request?my:("undefined"!=typeof wx&&wx.request,wx)}function getBaseSystemInfo(){var e=getAPIEnv(),t=e?e.getSystemInfoSync():{};return{libEnv:"MINIAPP",os:t.platform||"",osVer:t.system||"",browser:"",browserVer:"",hostEnvVer:t.version,model:t.SDKVersion,pushDeviceInfo:{PRODUCT:t.model,DEVICE:t.model,MANUFACTURER:t.brand}}}class LogStorageImpl{constructor(e){this.dirPath="",this.filePath="",this.copyFilePath="",this.maxCapacity=26214400,this.remainCapacity=8388608,this.count=0,this.maxCount=60,this.lastErrorMsg=void 0,this.fileNames=[],this.param=e;var t=getAPIEnv();if(t){this.dirPath=`${t.env.USER_DATA_PATH}/${e.logDirPath}`;var r=function formatDateToYYYYMMDD(e){return`${e.getFullYear()}${String(e.getMonth()+1).padStart(2,"0")}${String(e.getDate()).padStart(2,"0")}`}(new Date);this.filePath=`${this.dirPath}/${r}.log`}}makeDir(){var e=getAPIEnv();if(e){var t=getLogger(),r=e.getFileSystemManager();try{var i=r.accessSync(this.dirPath);t.log("logStorage::access dir:",i),("object"==typeof i&&null!==i?i.error||i.errno||i.errCode||i.errNo:0)>200&&r.mkdirSync(this.dirPath,!0)}catch(e){r.mkdirSync(this.dirPath,!0)}try{var o=r.accessSync(this.filePath);t.log("logStorage::access file:",o),("object"==typeof o&&null!==o?o.error||o.errno||o.errCode||o.errNo:0)>200&&r.writeFileSync(this.filePath,"===","utf8")}catch(e){r.writeFileSync(this.filePath,"===","utf8")}}}open(){return __awaiter(this,void 0,void 0,(function*(){if(getAPIEnv()){var e=getLogger();try{this.makeDir(),e.log(`logStorage::open log file success:${this.filePath}`)}catch(t){e.warn(`logStorage::open log file failed:${this.filePath}`,t)}yield this.checkCapacity(this.remainCapacity)}}))}checkCapacity(e){return __awaiter(this,void 0,void 0,(function*(){var t=getAPIEnv();if(t){var r=getLogger(),i=t.getFileSystemManager(),o=this.getSize();if(o>this.maxCapacity){r.log(`logStorage::checksize:exceed,${o} byte`);var n="";try{n=yield this.readLogs(o-e)}catch(e){return void r.log("logStorage::checkCapacity:read failed",e)}r.log(`logStorage::checksize:read success ${o-e} byte`);try{i.unlinkSync(this.filePath)}catch(e){return void r.log("logStorage::checkCapacity:unlink failed",e)}try{i.writeFileSync(this.filePath,n,"utf8")}catch(e){return void r.log("logStorage::checkCapacity:write failed",e)}}else r.log(`logStorage::checkCapacity:not exceeding,${o} byte`)}}))}getSize(){var e,t=getAPIEnv();if(!t)return 0;var r,i=getLogger(),o=t.getFileSystemManager();try{r=o.statSync(this.filePath,!1)}catch(e){return i.warn("logStorage::stat failed",e),0}return r.size||(null===(e=r.stats)||void 0===e?void 0:e.size)}readLogs(e=0){var t=getAPIEnv();if(!t)return Promise.resolve("");var r=getLogger(),i=t.getFileSystemManager();return new Promise(((t,o)=>{i.readFile({filePath:this.filePath,encoding:"utf8",position:e,success:e=>{var i=e.data;"string"==typeof i?(r.warn(`logStorage::readLogs success ${i.length}`),t(i)):(r.warn("logStorage::readLogs empty"),o(new Error("logStorage::readLogs empty")))},fail:e=>{var t=e.errMsg||e.errorMessage||e.message;r.warn(`logStorage::readLogs failed ${t}`);var i={code:e.errCode||0,message:t};o(i)}})}))}close(){}addLogs(e){var t=getAPIEnv();if(!t)return Promise.resolve();var r=getLogger(),i=e.map((e=>e.text)).concat("").join("\n");try{t.getFileSystemManager().appendFileSync(this.filePath,i,"utf8")}catch(e){var o=e.errMsg||e.errorMessage||e.message;this.lastErrorMsg!==o&&r.warn("logStorage::append failed",e),this.lastErrorMsg=o}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 e=getAPIEnv();if(e){var t=getLogger(),r=this.getSize(),i=e.getFileSystemManager();if(r>0){try{i.copyFileSync(this.filePath,this.copyFilePath)}catch(e){return void t.warn("logStorage::copyFileSync failed",e)}return this.copyFilePath}t.warn("logStorage::extractLogs empty")}}))}afterUpload(){return __awaiter(this,void 0,void 0,(function*(){var e=getAPIEnv();if(e){var t=getLogger(),r=e.getFileSystemManager();try{r.unlinkSync(this.copyFilePath)}catch(e){return void t.log("logStorage::delete copyFilePath failed",e)}}}))}}function uploadFileFn(e){var t=getLogger(),r=getAPIEnv(),i=e.headers||{};return e.md5&&(i["Content-MD5"]=e.md5),new Promise(((o,n)=>{var s=r.uploadFile(Object.assign(Object.assign({url:`${e.commonUploadHost}/${e.nosToken.bucket}`},Object.keys(i).length>0?{header:i}:{}),{formData:{Object:decodeURIComponent(e.nosToken.objectName),"x-nos-token":e.nosToken.token,"x-nos-entity-type":"json"},name:"file",fileName:"file",fileType:e.type,filePath:e.filePath,success(t){if(200==t.statusCode){e.onUploadInfo&&e.onUploadInfo({http_code:t.statusCode});var r={};if("string"==typeof t.data)try{r=JSON.parse(t.data)}catch(r){e.onUploadInfo&&e.onUploadInfo({exception:`JSON parse error:${t.data}`}),n({code:t.statusCode,message:t.errMsg,rawData:t.data})}r.name=e.filePath,r.ext=r.name&&r.name.lastIndexOf(".")>-1?r.name.slice(r.name.lastIndexOf(".")+1).toLowerCase():"",o(r)}else e.onUploadInfo&&e.onUploadInfo({http_code:t.statusCode,exception:t.data,rsp_headers:t.header,req_headers:i}),n({code:t.statusCode,message:t.errMsg,rawData:t.data})},fail(t){e.onUploadInfo&&e.onUploadInfo({http_code:0,exception:t,req_headers:i}),9===t.error||21104===t.errNo||"string"==typeof t.errMsg&&t.errMsg.indexOf("abort")>-1?t.code=de.V2NIM_ERROR_CODE_CANCELLED:t.code=t.error||t.errNo||t.errno||t.errCode||t.code,t.message=t.errMsg||t.errorMessage,n(t)}}));try{e.onUploadStart&&e.onUploadStart(s)}catch(e){t.error("uploadFile: options.onUploadStart error",e),s.abort(),n(e)}e.onUploadProgress&&s.onProgressUpdate((function(t){var r=t.totalBytesExpectedToWrite||t.totalBytesExpectedToSend,i=t.totalBytesWritten||t.totalBytesSent;e.onUploadProgress&&e.onUploadProgress({total:r,loaded:i,percentage:parseFloat((i/r).toFixed(2)),percentageText:t.progress+"%"})}))}))}function getFileUploadInformationFn(e){return null}var qr={clear(){my.clearStorageSync()},getItem:e=>my.getStorageSync({key:e}).data,setItem:(e,t)=>my.setStorageSync({key:e,data:t}),removeItem:e=>my.removeStorageSync({key:e})};function requestFn(e,t){return t&&(t.header=t.headers,t.data=t.data||(null==t?void 0:t.params)||{}),new Promise(((r,i)=>{getAPIEnv().request(Object.assign(Object.assign({url:e},t),{success:function(t){var o=(t=t||{}).statusCode||t.status;"number"==typeof o&&o.toString().startsWith("2")?(t={data:t.data,status:o,errMsg:t.errMsg,header:t.header},r(t)):i({code:o||0,message:t.data||`miniapp request fail. url: ${e}`})},fail:function(t){var r=`miniapp request fail. url: ${e}`;t?(1===t.errCode||13===t.error||5===t.errNo||21103===t.errNo||"string"==typeof t.errMsg&&t.errMsg.indexOf("timeout")>-1?t.code=de.V2NIM_ERROR_CODE_TIMEOUT:t.code=t.error||t.errNo||t.errno||t.errCode||t.code,t.message=t.errMsg||t.errorMessage||r,i({code:t.code,message:t.message})):i({code:0,message:r})}}))}))}function getSystemInfoFn$4(){var e=getBaseSystemInfo();return Object.assign(Object.assign({},e),{hostEnv:"Ali",hostEnvEnum:102,manufactor:"Ali",model:my.SDKVersion,userAgent:`NIM/Web/AliMiniApp(${my.SDKVersion})/V10.9.71/{{appkey}}`})}class WebSocketFn$1{constructor(e,t=""){if(this.CONNECTING=0,this.OPEN=1,this.CLOSING=2,this.CLOSED=3,this.binaryType="",this.onclose=function(e){getLogger().log("my-app: sockets on close ",e)},this.onerror=function(e){getLogger().error("my-app: sockets error ",e)},this.onmessage=function(e){},this.onopen=function(){},!e)throw new Error("Failed to construct 'socket': url required");this.url=e.replace(/:443(\/|$)/,"$1"),this.protocol=t,this.readyState=this.CONNECTING,this.socketTask=my.connectSocket({url:this.url,multiple:!0,fail:e=>{this.errorHandler(e)},success:()=>{this.readyState=this.OPEN}}),this.socketTask.onOpen((e=>{this.readyState=this.OPEN,this.binaryType?this.onopen():this.onmessage&&this.onmessage({type:"open",header:e})})),this.socketTask.onError((e=>{this.errorHandler(e)})),this.socketTask.onClose((e=>{this.readyState=this.CLOSED;var{code:t,reason:r,wasClean:i}=e;"function"==typeof this.onclose&&this.onclose&&this.onclose({code:t,reason:r,wasClean:i,type:"close"}),this.socketTask=null})),this.socketTask.onMessage((e=>{var t,r=null===(t=e.data)||void 0===t?void 0:t.data,i=r;e.data.isBuffer&&(i=base64ToArrayBuffer(r)),this.onmessage&&this.onmessage({data:i})}))}close(){this.socketTask&&this.socketTask.close({code:1e3,reason:"user force close websocket",complete:()=>{this.socketTask=null}})}send(e){if(this.readyState!==this.OPEN)throw new Error(`my-app: socket sendMsg when readyState=${this.readyState}`);if(!("string"==typeof e||e instanceof ArrayBuffer))throw new TypeError("my-app: socket sendMsg only String/ArrayBuffer supported");this.socketTask&&this.socketTask.send({data:e,isBuffer:e instanceof ArrayBuffer})}errorHandler(e){getLogger().error("my-app::ws: onerror ",e),this.readyState=this.CLOSED,this.onerror&&this.onerror({type:"error",code:null==e?void 0:e.error,message:null==e?void 0:e.errorMessage})}}var Wr={clear(){getAPIEnv().clearStorageSync()},getItem:e=>getAPIEnv().getStorageSync(e),setItem:(e,t)=>getAPIEnv().setStorageSync(e,t),removeItem:e=>getAPIEnv().removeStorageSync(e)};function getSystemInfoFn$3(){var e=getBaseSystemInfo(),t=wx.getSystemInfoSync()||{};return Object.assign(Object.assign({},e),{hostEnv:"WeiXin",hostEnvEnum:6,manufactor:"WeiXin",userAgent:`NIM/Web/WeChatMiniApp(${t.SDKVersion})/V10.9.71/{{appkey}}`})}class WebSocketFn{constructor(e,t=""){if(this.CONNECTING=0,this.OPEN=1,this.CLOSING=2,this.CLOSED=3,this.binaryType="",this.onclose=function(e){getLogger().log("miniapp: sockets on close ",e)},this.onerror=function(e){getLogger().error("miniapp: sockets error ",e)},this.onmessage=function(e){},this.onopen=function(){},!e)throw new Error("Failed to construct 'socket': url required");this.url=e.replace(/:443(\/|$)/,"$1"),this.protocol=t,this.readyState=this.CONNECTING;var r=this.protocol?{protocols:[this.protocol]}:{},i=getAPIEnv();this.socketTask=i.connectSocket(Object.assign(Object.assign({url:this.url},r),{fail:e=>{this.errorHandler(e)},success:()=>{}})),this.socketTask.onOpen((e=>{this.readyState=this.OPEN,this.binaryType?this.onopen():this.onmessage&&this.onmessage({type:"open",header:e})})),this.socketTask.onError((e=>{this.errorHandler(e)})),this.socketTask.onClose((e=>{this.readyState=this.CLOSED;var{code:t,reason:r,wasClean:i}=e;"function"==typeof this.onclose&&this.onclose&&this.onclose({code:t,reason:r,wasClean:i,type:"close"})})),this.socketTask.onMessage((e=>{if(this.onmessage&&e)return"string"==typeof e||"byteLength"in e?this.onmessage({data:e}):"string"==typeof e.data||"byteLength"in e.data?this.onmessage({data:e.data}):e.data&&("string"==typeof e.data.data||"byteLength"in e.data.data)?this.onmessage({data:e.data.data}):void this.onmessage(e)}))}close(){this.socketTask.close({code:1e3,reason:"user force close websocket",complete:()=>{this.socketTask=null}})}send(e){if(this.readyState!==this.OPEN)throw new Error(`miniapp: socket sendMsg when readyState=${this.readyState}`);if(!("string"==typeof e||e instanceof ArrayBuffer))throw new TypeError("miniapp: socket sendMsg only String/ArrayBuffer supported");this.socketTask.send({data:e})}errorHandler(e){getLogger().error("miniapp::ws: onerror ",e),this.readyState=this.CLOSED,this.onerror&&this.onerror({type:"error",message:e&&(e.errMsg||e.errorMessage)})}}function getSystemInfoFn$2(){var e=getBaseSystemInfo(),t=swan.getSystemInfoSync()||{};return Object.assign(Object.assign({},e),{hostEnv:"Baidu",hostEnvEnum:103,manufactor:"Baidu",userAgent:`NIM/Web/BaiduMiniApp(${t.SDKVersion})/V10.9.71/{{appkey}}`})}function getSystemInfoFn$1(){var e=getBaseSystemInfo(),t=tt.getSystemInfoSync()||{};return Object.assign(Object.assign({},e),{hostEnv:"Tiktok",hostEnvEnum:104,manufactor:"Tiktok",userAgent:`NIM/Web/TiktokMiniApp(${t.SDKVersion})/V10.9.71/{{appkey}}`})}function getSystemInfoFn(){var e=getBaseSystemInfo(),t=wx.getSystemInfoSync()||{};return Object.assign(Object.assign({},e),{hostEnv:"QQ",hostEnvEnum:6,manufactor:"QQ",userAgent:`NIM/Web/QQMiniApp(${t.SDKVersion})/V10.9.71/{{appkey}}`})}!function setAdapters(e){merge(ce,e())}((function getAdapter(){if("undefined"!=typeof qq&&"function"==typeof qq.request)return{setLogger:setLogger,platform:"QQAPP",localStorage:Wr,request:requestFn,WebSocket:WebSocketFn,uploadFile:uploadFileFn,getFileUploadInformation:getFileUploadInformationFn,getSystemInfo:getSystemInfoFn,net:getNetFn(qq),powerMonitor:new PowerMonitor(qq)};if("undefined"!=typeof tt&&"function"==typeof tt.request)return{setLogger:setLogger,platform:"TTAPP",localStorage:Wr,request:requestFn,WebSocket:WebSocketFn,uploadFile:uploadFileFn,getSystemInfo:getSystemInfoFn$1,getFileUploadInformation:getFileUploadInformationFn,net:getNetFn(tt)};if("undefined"!=typeof swan&&"function"==typeof swan.request)return{setLogger:setLogger,platform:"BAIDUAPP",localStorage:Wr,request:requestFn,WebSocket:WebSocketFn,uploadFile:uploadFileFn,getFileUploadInformation:getFileUploadInformationFn,getSystemInfo:getSystemInfoFn$2,net:getNetFn(swan)};if("undefined"!=typeof my&&"function"==typeof my.request)return{setLogger:setLogger,platform:"ALIAPP",localStorage:qr,request:requestFn,WebSocket:WebSocketFn$1,uploadFile:uploadFileFn,getSystemInfo:getSystemInfoFn$4,getFileUploadInformation:getFileUploadInformationFn,net:getNetFn(my),powerMonitor:new PowerMonitor(my),logStorage:LogStorageImpl};if("undefined"!=typeof wx&&"function"==typeof wx.request)return{setLogger:setLogger,platform:"WXAPP",localStorage:Wr,request:requestFn,WebSocket:WebSocketFn,uploadFile:uploadFileFn,getFileUploadInformation:getFileUploadInformationFn,getSystemInfo:getSystemInfoFn$3,net:getNetFn(wx),powerMonitor:new PowerMonitor(wx),logStorage:LogStorageImpl};throw new Error("No adapter found!")})),e.V2NIMChatroomConst=Et,e.default=V2NIMChatroomClient,Object.defineProperty(e,"__esModule",{value:!0})}));