nim-web-sdk-ng
Version:
Yunxin IM SDK next generation
16 lines • 200 kB
JavaScript
/**
*
* Version: 10.9.71
*
* Git Hash: f2dd8dce716f63985d0823f710605b924090d68b
*
* Created At: 1/5/2026, 9:46:13 AM
*
* Target: CHATROOM_UNIAPP_SDK.js
*
*/
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).Chatroom=t()}(this,(function(){"use strict";"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 e=createCommonjsModule((function(e){var t=Object.prototype.hasOwnProperty,o="~";function Events(){}function EE(e,t,o){this.fn=e,this.context=t,this.once=o||!1}function addListener(e,t,r,i,n){if("function"!=typeof r)throw new TypeError("The listener must be a function");var s=new EE(r,i||e,n),a=o?o+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__||(o=!1)),EventEmitter.prototype.eventNames=function eventNames(){var e,r,i=[];if(0===this._eventsCount)return i;for(r in e=this._events)t.call(e,r)&&i.push(o?r.slice(1):r);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(e)):i},EventEmitter.prototype.listeners=function listeners(e){var t=o?o+e:e,r=this._events[t];if(!r)return[];if(r.fn)return[r.fn];for(var i=0,n=r.length,s=new Array(n);i<n;i++)s[i]=r[i].fn;return s},EventEmitter.prototype.listenerCount=function listenerCount(e){var t=o?o+e:e,r=this._events[t];return r?r.fn?1:r.length:0},EventEmitter.prototype.emit=function emit(e,t,r,i,n,s){var a=o?o+e:e;if(!this._events[a])return!1;var c,l,_=this._events[a],d=arguments.length;if(_.fn){switch(_.once&&this.removeListener(e,_.fn,void 0,!0),d){case 1:return _.fn.call(_.context),!0;case 2:return _.fn.call(_.context,t),!0;case 3:return _.fn.call(_.context,t,r),!0;case 4:return _.fn.call(_.context,t,r,i),!0;case 5:return _.fn.call(_.context,t,r,i,n),!0;case 6:return _.fn.call(_.context,t,r,i,n,s),!0}for(l=1,c=new Array(d-1);l<d;l++)c[l-1]=arguments[l];_.fn.apply(_.context,c)}else{var E,h=_.length;for(l=0;l<h;l++)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,r);break;case 4:_[l].fn.call(_[l].context,t,r,i);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,o){return addListener(this,e,t,o,!1)},EventEmitter.prototype.once=function once(e,t,o){return addListener(this,e,t,o,!0)},EventEmitter.prototype.removeListener=function removeListener(e,t,r,i){var n=o?o+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||i&&!s.once||r&&s.context!==r||clearEvent(this,n);else{for(var a=0,c=[],l=s.length;a<l;a++)(s[a].fn!==t||i&&!s[a].once||r&&s[a].context!==r)&&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=o?o+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=o,EventEmitter.EventEmitter=EventEmitter,e.exports=EventEmitter})),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,o=t.hasOwnProperty,r="function"==typeof Symbol?Symbol:{},i=r.iterator||"@@iterator",n=r.asyncIterator||"@@asyncIterator",s=r.toStringTag||"@@toStringTag";function define(e,t,o){return Object.defineProperty(e,t,{value:o,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{define({},"")}catch(e){define=function(e,t,o){return e[t]=o}}function wrap(e,t,o,r){var i=t&&t.prototype instanceof Generator?t:Generator,n=Object.create(i.prototype),s=new Context(r||[]);return n._invoke=function(e,t,o){var r="suspendedStart";return function(i,n){if("executing"===r)throw new Error("Generator is already running");if("completed"===r){if("throw"===i)throw n;return doneResult()}for(o.method=i,o.arg=n;;){var s=o.delegate;if(s){var c=maybeInvokeDelegate(s,o);if(c){if(c===a)continue;return c}}if("next"===o.method)o.sent=o._sent=o.arg;else if("throw"===o.method){if("suspendedStart"===r)throw r="completed",o.arg;o.dispatchException(o.arg)}else"return"===o.method&&o.abrupt("return",o.arg);r="executing";var l=tryCatch(e,t,o);if("normal"===l.type){if(r=o.done?"completed":"suspendedYield",l.arg===a)continue;return{value:l.arg,done:o.done}}"throw"===l.type&&(r="completed",o.method="throw",o.arg=l.arg)}}}(e,o,s),n}function tryCatch(e,t,o){try{return{type:"normal",arg:e.call(t,o)}}catch(e){return{type:"throw",arg:e}}}e.wrap=wrap;var a={};function Generator(){}function GeneratorFunction(){}function GeneratorFunctionPrototype(){}var c={};define(c,i,(function(){return this}));var l=Object.getPrototypeOf,_=l&&l(l(values([])));_&&_!==t&&o.call(_,i)&&(c=_);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(r,i,n,s){var a=tryCatch(e[r],e,i);if("throw"!==a.type){var c=a.arg,l=c.value;return l&&"object"==typeof l&&o.call(l,"__await")?t.resolve(l.__await).then((function(e){invoke("next",e,n,s)}),(function(e){invoke("throw",e,n,s)})):t.resolve(l).then((function(e){c.value=e,n(c)}),(function(e){return invoke("throw",e,n,s)}))}s(a.arg)}var r;this._invoke=function(e,o){function callInvokeWithMethodAndArg(){return new t((function(t,r){invoke(e,o,t,r)}))}return r=r?r.then(callInvokeWithMethodAndArg,callInvokeWithMethodAndArg):callInvokeWithMethodAndArg()}}function maybeInvokeDelegate(e,t){var o=e.iterator[t.method];if(void 0===o){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 r=tryCatch(o,e.iterator,t.arg);if("throw"===r.type)return t.method="throw",t.arg=r.arg,t.delegate=null,a;var i=r.arg;return i?i.done?(t[e.resultName]=i.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=void 0),t.delegate=null,a):i:(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[i];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var r=-1,n=function next(){for(;++r<e.length;)if(o.call(e,r))return next.value=e[r],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,o,r,i,n){void 0===n&&(n=Promise);var s=new AsyncIterator(wrap(t,o,r,i),n);return e.isGeneratorFunction(o)?s:s.next().then((function(e){return e.done?e.value:s.next()}))},defineIteratorMethods(d),define(d,s,"Generator"),define(d,i,(function(){return this})),define(d,"toString",(function(){return"[object Generator]"})),e.keys=function(e){var t=[];for(var o in e)t.push(o);return t.reverse(),function next(){for(;t.length;){var o=t.pop();if(o in e)return next.value=o,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)&&o.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(o,r){return n.type="throw",n.arg=e,t.next=o,r&&(t.method="next",t.arg=void 0),!!r}for(var r=this.tryEntries.length-1;r>=0;--r){var i=this.tryEntries[r],n=i.completion;if("root"===i.tryLoc)return handle("end");if(i.tryLoc<=this.prev){var s=o.call(i,"catchLoc"),a=o.call(i,"finallyLoc");if(s&&a){if(this.prev<i.catchLoc)return handle(i.catchLoc,!0);if(this.prev<i.finallyLoc)return handle(i.finallyLoc)}else if(s){if(this.prev<i.catchLoc)return handle(i.catchLoc,!0)}else{if(!a)throw new Error("try statement without catch or finally");if(this.prev<i.finallyLoc)return handle(i.finallyLoc)}}}},abrupt:function(e,t){for(var r=this.tryEntries.length-1;r>=0;--r){var i=this.tryEntries[r];if(i.tryLoc<=this.prev&&o.call(i,"finallyLoc")&&this.prev<i.finallyLoc){var n=i;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 o=this.tryEntries[t];if(o.finallyLoc===e)return this.complete(o.completion,o.afterLoc),resetTryEntry(o),a}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var o=this.tryEntries[t];if(o.tryLoc===e){var r=o.completion;if("throw"===r.type){var i=r.arg;resetTryEntry(o)}return i}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,o){return this.delegate={iterator:values(e),resultName:t,nextLoc:o},"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 o=0;o<t.length;o++){var r=t[o];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function _createClass(e,t,o){return t&&_defineProperties(e.prototype,t),o&&_defineProperties(e,o),Object.defineProperty(e,"prototype",{writable:!1}),e}function __awaiter(e,t,o,r){function adopt(e){return e instanceof o?e:new o((function(t){t(e)}))}return new(o||(o=Promise))((function(o,i){function fulfilled(e){try{step(r.next(e))}catch(e){i(e)}}function rejected(e){try{step(r.throw(e))}catch(e){i(e)}}function step(e){e.done?o(e.value):adopt(e.value).then(fulfilled,rejected)}step((r=r.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,o=8e3,r=function emptyFn(){},i=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 o=this;this.reportConfig.isDataReportEnable&&this.reportConfig.request(e,Object.assign({dataType:"json",method:"POST",timeout:this.reportConfig.timeout},t)).catch((function(e){var t,r;null===(r=null===(t=o.reportConfig)||void 0===t?void 0:t.logger)||void 0===r||r.warn("Reporter immediately upload failed",e)}))}},{key:"report",value:function report(t,o){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(r.priority||(r.priority=this.getEventPriority(t,o)),this.reportConfig.isDataReportEnable&&t){if("login"===t&&!1===o.succeed&&o.process_id){var i=o.extension&&o.extension.find((function(e){return"TCP"===e.operation_type})),n=i&&i.target||"",s=o.process_id+n,a=this.lastFailLogin[s]||0;if(o.start_time-a<e.loginFailIgnoreInterval)return;this.lastFailLogin[s]=o.start_time}var c=Date.now();"HIGH"===r.priority?this.highPriorityMsgList.push({module:t,msg:o,createTime:c}):"NORMAL"===r.priority?this.msgList.push({module:t,msg:o,createTime:c}):"LOW"===r.priority&&this.lowPriorityMsgList.push({module:t,msg:o,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 o=Object.assign(Object.assign({start_time:Date.now()},t),{extension:[]});this.traceMsgCache[e]=o}}},{key:"reportTraceUpdate",value:function reportTraceUpdate(e){}},{key:"reportTraceUpdateV2",value:function reportTraceUpdateV2(e,t,o){var r,i=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==o?void 0:o.asyncParams)&&((r=this.traceMsgCache[e]).asyncPromiseArray||(r.asyncPromiseArray=[]),this.traceMsgCache[e].asyncPromiseArray.push(o.asyncParams.then((function(t){i.traceMsgCache[e]&&i.traceMsgCache[e].extension[c]&&Object.assign(i.traceMsgCache[e].extension[c],t)}))))}}},{key:"reportTraceEnd",value:function reportTraceEnd(e){var t,o=this,r=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(this.reportConfig.isDataReportEnable&&this.traceMsgCache[e])if("nos"!==e||!1===r){"boolean"==typeof r?this.traceMsgCache[e].succeed=!!r:this.traceMsgCache[e].state=r,this.traceMsgCache[e].duration=Date.now()-this.traceMsgCache[e].start_time,this.traceMsgCache[e].extension.forEach((function(e){delete e.end_time}));var i=this.traceMsgCache[e];if(this.traceMsgCache[e]=null,i.asyncPromiseArray){(t=this.endedAsyncMsgByModule)[e]||(t[e]=[]),this.endedAsyncMsgByModule[e].push(i);var n=function asyncCallback(){o.endedAsyncMsgByModule[e]&&o.endedAsyncMsgByModule[e].includes(i)&&(delete i.asyncPromiseArray,o.report(e,i,{priority:o.getEventPriority(e,i)}))};Promise.all(i.asyncPromiseArray).then(n).catch(n)}else this.report(e,i,{priority:this.getEventPriority(e,i)})}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=r,this.report=r,this.reportTraceStart=r,this.reportTraceUpdate=r,this.reportTraceEnd=r,this.pause=r,this.restore=r,this.destroy=r,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,r;return __awaiter(this,void 0,void 0,_regeneratorRuntime().mark((function _callee(){var i,n,s,a,c,l=this;return _regeneratorRuntime().wrap((function _callee$(_){for(;;)switch(_.prev=_.next){case 0:if(!this.loading){_.next=2;break}return _.abrupt("return");case 2:this.loading=!0,i=this.reportConfig.common||{},n=this.reportConfig.compassDataEndpoint.split(",").map((function(e){return"".concat(e,"/").concat(l.configPath)})),s=_regeneratorRuntime().mark((function _loop(s){return _regeneratorRuntime().wrap((function _loop$(a){for(;;)switch(a.prev=a.next){case 0:if(!l.initConfigLoaded&&!l.isDestroyed){a.next=2;break}return a.abrupt("return","break");case 2:return a.prev=2,a.next=5,l.reportConfig.request(n[s],{method:"GET",dataType:"json",params:{deviceId:i.dev_id,sdkVer:i.sdk_ver,platform:i.platform,hostEnv:i.host_env,appkey:i.app_key},timeout:l.reportConfig.timeout}).then((function(e){var t,o;if(!l.isDestroyed){if(200===e.status&&e.data&&200===e.data.code){l.initConfigLoaded=!0;var r=e.data.data||{};l.reportConfig.maxSize=r.maxSize>1e3?1e3:r.maxSize,l.reportConfig.maxInterval=r.maxInterval>1e4?1e4:r.maxInterval,l.reportConfig.maxInterval=r.maxInterval<10?10:r.maxInterval,l.reportConfig.minInterval=r.minInterval<2?2:r.minInterval,l.reportConfig.maxDelay=r.maxDelay||300,l.reportConfig.maxInterval=1e3*l.reportConfig.maxInterval,l.reportConfig.minInterval=1e3*l.reportConfig.minInterval,l.reportConfig.maxDelay=1e3*l.reportConfig.maxDelay,r.endpoint?l.dataReportEndpoint=r.endpoint:l.dataReportEndpoint=n[s],l.serverAllowUpload=!0,l.loading=!1,l.reportHeartBeat()}else 200===e.status&&(l.initConfigLoaded=!0);null===(o=null===(t=l.reportConfig)||void 0===t?void 0:t.logger)||void 0===o||o.log("Get reporter upload config success")}})).catch((function(e){var r,i;l.isDestroyed||(l.loading=!1,null===(i=null===(r=l.reportConfig)||void 0===r?void 0:r.logger)||void 0===i||i.error("Get reporter upload config failed",e),l.reqRetryCount<t&&(l.reqRetryCount++,setTimeout((function(){l.isDestroyed||l.initUploadConfig()}),o)))}));case 5:a.next=14;break;case 7:if(a.prev=7,a.t0=a.catch(2),!l.isDestroyed){a.next=11;break}return a.abrupt("return",{v:void 0});case 11:l.loading=!1,null===(r=null===(e=l.reportConfig)||void 0===e?void 0:e.logger)||void 0===r||r.error("Exec reporter request failed",a.t0),l.reqRetryCount<t&&(l.reqRetryCount++,setTimeout((function(){l.isDestroyed||l.initUploadConfig()}),o));case 14:case"end":return a.stop()}}),_loop,null,[[2,7]])})),a=0;case 7:if(!(a<n.length)){_.next=17;break}return _.delegateYield(s(a),"t0",9);case 9:if("break"!==(c=_.t0)){_.next=12;break}return _.abrupt("break",17);case 12:if("object"!==_typeof(c)){_.next=14;break}return _.abrupt("return",c.v);case 14:a++,_.next=7;break;case 17:case"end":return _.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={},o=Date.now();this.highPriorityMsgList=this.highPriorityMsgList.filter((function(t){return o-t.createTime<e.reportConfig.maxDelay})),this.msgList=this.msgList.filter((function(t){return o-t.createTime<e.reportConfig.maxDelay})),this.lowPriorityMsgList=this.lowPriorityMsgList.filter((function(t){return o-t.createTime<e.reportConfig.maxDelay})),this.cacheMsgList=this.cacheMsgList.filter((function(t){return o-t.createTime<e.reportConfig.maxDelay}));var r=this.highPriorityMsgList.slice(0,this.reportConfig.maxSize);if(this.highPriorityMsgList=this.highPriorityMsgList.slice(r.length),r.length<this.reportConfig.maxSize){var i=this.reportConfig.maxSize-r.length;r=r.concat(this.msgList.slice(0,i)),this.msgList=this.msgList.slice(i)}if(r.length<this.reportConfig.maxSize){var n=this.reportConfig.maxSize-r.length;r=r.concat(this.lowPriorityMsgList.slice(0,n)),this.lowPriorityMsgList=this.lowPriorityMsgList.slice(n)}if(r.length<this.reportConfig.maxSize){var s=this.reportConfig.maxSize-r.length;r=r.concat(this.cacheMsgList.slice(0,s)),this.cacheMsgList=this.cacheMsgList.slice(s)}return r.forEach((function(e){t[e.module]?t[e.module].push(e.msg):t[e.module]=[e.msg]})),{uploadMsgArr:r,uploadMsg:t}}},{key:"upload",value:function upload(){var e,t,o=this;if(this.isUploadEnable&&this.serverAllowUpload&&!(this.lastReportTime&&Date.now()-this.lastReportTime<this.reportConfig.minInterval)){var r=this.getUploadMsg(),i=r.uploadMsgArr,n=r.uploadMsg;if(i.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,r;o.cacheMsgList=o.cacheMsgList.concat(i).slice(0,o.reportConfig.cacheMaxSize),null===(r=null===(t=o.reportConfig)||void 0===t?void 0:t.logger)||void 0===r||r.warn("Reporter upload failed",e)}))}catch(o){null===(t=null===(e=this.reportConfig)||void 0===e?void 0:e.logger)||void 0===t||t.warn("Exec reporter request failed",o)}clearTimeout(this.timer),this.reportHeartBeat()}}}}]),Reporter}();return i}()}));function isPlainObject(e){return null!=e&&"object"==typeof e&&Object.getPrototypeOf(e)==Object.prototype}function merge(e,t){var o=isPlainObject(e)||Array.isArray(e),r=isPlainObject(t)||Array.isArray(t);if(o&&r){for(var i in t){var n=merge(e[i],t[i]);void 0!==n&&(e[i]=n)}return e}return t}var o={getNetworkStatus:()=>Promise.resolve({net_type:0,net_connect:!0}),onNetworkStatusChange(e){},offNetworkStatusChange(){}},r={isActive:()=>!0,getStatus:()=>0,setStatus(e){},destroy(){}};var i,n,s,a,c,l,_,d,E,h,g,m,u,p,T,I,N,f,S,M,A,y,O,v,R,C,P,L,D,V,b,k,w,x,U,F,G,Y,j,B,H,$,K,q,z,W,J,Q,X,Z,ee,te,oe,re,ie,ne,se,ae={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:o,powerMonitor:r,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"}(i||(i={})),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"}(l||(l={})),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"}(_||(_={})),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"}(g||(g={})),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"}(u||(u={})),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"}(T||(T={})),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"}(I||(I={})),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"}(N||(N={})),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"}(f||(f={})),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"}(S||(S={})),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"}(M||(M={})),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"}(A||(A={})),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"}(y||(y={})),function(e){e[e.V2NIM_SEARCH_DIRECTION_BACKWARD=0]="V2NIM_SEARCH_DIRECTION_BACKWARD",e[e.V2NIM_SEARCH_DIRECTION_FORWARD=1]="V2NIM_SEARCH_DIRECTION_FORWARD"}(O||(O={})),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"}(v||(v={})),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"}(R||(R={})),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"}(C||(C={})),function(e){e[e.V2NIM_QUERY_DIRECTION_DESC=0]="V2NIM_QUERY_DIRECTION_DESC",e[e.V2NIM_QUERY_DIRECTION_ASC=1]="V2NIM_QUERY_DIRECTION_ASC"}(P||(P={})),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"}(L||(L={})),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"}(D||(D={})),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"}(V||(V={})),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"}(b||(b={})),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"}(x||(x={})),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"}(U||(U={})),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"}(F||(F={})),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"}(G||(G={})),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"}(Y||(Y={})),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"}(j||(j={})),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"}(B||(B={})),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"}(H||(H={})),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"}($||($={})),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"}(K||(K={})),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"}(q||(q={})),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"}(W||(W={})),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"}(J||(J={})),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"}(Q||(Q={})),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"}(X||(X={})),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"}(Z||(Z={})),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"}(ee||(ee={})),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"}(te||(te={})),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"}(oe||(oe={})),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"}(re||(re={})),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"}(ie||(ie={})),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"}(ne||(ne={})),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"}(se||(se={}));var ce={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(ce),_e=le.reduce((function(e,t){var o=ce[t];return e[t]=o.code,e}),{}),de=le.reduce((function(e,t){var o=ce[t];return e[o.code]=o.message,e}),{});class V2NIMErrorImpl extends Error{constructor(e){super(e.desc),this.name="V2NIMError",this.code=e.code||0,this.desc=e.desc||de[this.code]||Ee[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={},o){super({code:_e.V2NIM_ERROR_CODE_PARAMETER_ERROR,detail:{reason:e,rules:o,data:t}}),this.name="validateError",this.message=this.message+"\n"+JSON.stringify(this.detail,null,2),this.data=t,this.rules=o}}class ValidateErrorV2 extends V2NIMErrorImpl{constructor(e){var t,o,r;super({code:_e.V2NIM_ERROR_CODE_INVALID_PARAMETER,detail:{reason:null===(t=e.detail)||void 0===t?void 0:t.reason,rules:null===(o=e.detail)||void 0===o?void 0:o.rules,data:null===(r=e.detail)||void 0===r?void 0:r.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 Ee={200:null,406:null,808:null,810:null,302:"The user name or password is incorrect.",405:"Parameter length too long",408:"Client request timed out",415:"Client network unavailable",422:"Account disabled",508:"Expiration date",509:"Invalid",7101:"Be pulled black",700:"Partial failure of batch operation",801:"The number of people in the team has reached the upper limit",802:"No permission",803:"The team does not exist or has not changed",804:"The user is not in the team",805:"Team type mismatch",806:"The number of teams created has reached the limit",807:"Team member not valid",809:"Already in the team",811:"The number of accounts in the forced push list exceeds the limit",812:"The team is muted",813:"Due to the limited number of team, some pull people successfully",814:"Disable team message read service",815:"Maximum number of team administrators",816:"Batch operation partial failure",9102:"Channel failure",9103:"This call has been answered / rejected at another end",10201:"Signaling: target NIM client is offline",10202:"Signaling: push is unreachable",10404:"Signaling: channel not exists",10405:"Signaling: channel already exists",10406:"Signaling: member of channel not exists",10407:"Signaling: member of channel already exists",10408:"Signaling: the invitation request does not exist or has expired",10409:"Signaling: the invitation request has been rejected",10410:"Signaling: the invitation request has been accepted",10414:"Signaling: request parameter error",10417:"Signaling: uid conflict",10419:"Signaling: the number of members of channel exceed the limit",10420:"Signaling: member is already in the channel on other client",10700:"Signaling: phased success",13002:"Abnormal chatroom status",13003:"In the blacklist",13004:"In the mute list",13006:"All members are muted, and only the administrator can speak"};function get(e,t){if("object"!=typeof e||null===e)return e;for(var o=(t=t||"").split("."),r=0;r<o.length;r++){var i=o[r],n=e[i],s=i.indexOf("["),a=i.indexOf("]");if(-1!==s&&-1!==a&&s<a){var c=i.slice(0,s),l=parseInt(i.slice(s+1,a));n=e[c],n=Array.isArray(n)?n[l]:void 0}if(null==n)return n;e=n}return e}var he,ge=(he=function(){return(65536*(1+Math.random())|0).toString(16).substring(1)},function(){return he()+he()+he()+he()+he()+he()+he()+he()});function getEnumKeys(e){return Object.keys(e).filter((e=>!(+e>=0)))}function getEnumKeyByEnumValue(e,t){var o=Object.keys(e).filter((o=>e[o]==t));return o.length>0?o[0]:void 0}function assignOptions(e,t){return function assignWith(e,t,o,r){for(var i in e=e||{},o=o||{},r=r||(()=>{}),t=t||{}){var n=r(e[i],t[i]);e[i]=void 0===n?t[i]:n}for(var s in o){var a=r(e[s],o[s]);e[s]=void 0===a?o[s]:a}return e}({},e,t,(function(e,t){return void 0===t?e:t}))}function emptyFuncWithPromise(){return Promise.resolve()}function __rest(e,t){var o={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(o[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(o[r[i]]=e[r[i]])}return o}function __awaiter(e,t,o,r){return new(o||(o=Promise))((function(i,n){function fulfilled(e){try{step(r.next(e))}catch(e){n(e)}}function rejected(e){try{step(r.throw(e))}catch(e){n(e)}}function step(e){e.done?i(e.value):function adopt(e){return e instanceof o?e:new o((function(t){t(e)}))}(e.value).then(fulfilled,rejected)}step((r=r.apply(e,t||[])).next())}))}class PromiseManager{constructor(){this.abortFns=[]}add(e){var t=function getPromiseWithAbort(e){var t={},o=new Promise((function(e,o){t.abort=o}));return t.promise=Promise.race([e,o]),t}(e);return this.abortFns.push(t.abort),t.promise}clear(e){this.abortFns.forEach((t=>t(e||new V2NIMErrorImpl({code:_e.V2NIM_ERROR_CODE_CANCELLED,detail:{reason:"Aborted"}})))),this.abortFns=[]}destroy(){this.clear()}}var me={tolerantRTT:3e3,bestRTT:100,maxChances:5,enable:!0},ue={timestamp:0,rtt:0,baseClock:0,baseTime:0};class TimeOrigin{constructor(e,t,o="getServerTime"){this.serverOrigin=ue,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=o,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=ue,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"),o=get(this.core,"V2NIMLoginService.lifeCycle.loginStatus");if("logined"===e||"logined"===t||1===o){this.isSettingNTP=!0,this.currentChance++,this.timer&&clearTimeout(this.timer),this.timer=0;var r,i="TimeOrigin::setOriginTimetick:",n=Date.now();this.core.logger.debug(`${i} getServerTime start, times ${this.currentChance}`);try{r=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(`${i} Calculate Delay time, getServerTime error`,s),void(s.code!==_e.V2NIM_ERROR_CODE_CANCELLED&&(clearTimeout(this.timer),this.timer=setTimeout(this.setOriginTimetick.bind(this),this.failedDelay)))}if(!r)return this.core.logger.warn(`${i} Calculate Delay time incorrect format`),void(this.config.enable=!1);var a=Date.now()-n;this.doSet(r,a)}}}))}doSet(e,t){var o="TimeOrigin::setOriginTimetick:";t>this.config.tolerantRTT?(this.logger.warn(`${o} 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(`${o} ignore RTT:${t}`):(this.setServerOrigin(t,e),this.logger.log(`${o} accept reluctantly RTT:${t}`)),clearTimeout(this.timer),this.timer=setTimeout(this.setOriginTimetick.bind(this),this.failedDelay)):(this.setServerOrigin(t,e),this.logger.debug(`${o} 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,o=e.time-this.serverOrigin.baseTime;return Math.abs(o-t)<500}return!1}checkPerformance(){return"BROWSER"===ae.platform&&!("undefined"==typeof performance||!performance.now)}static checkPerformance(){return"BROWSER"===ae.platform&&!("undefined"==typeof performance||!performance.now)}getTimeNode(){return{clock:this.checkPerformance()?performance.now():0,time:Date.now()}}static getTimeNode(){return{clock:TimeOrigin.checkPerformance()?performance.now():0,time:Date.now()}}setServerOrigin(e,t){this.serverOrigin={timestamp:t+Math.floor(e/2),rtt:e,baseClock:this.checkPerformance()?performance.now():0,baseTime:Date.now()}}}var pe={},Te={};function parseEachCmd(e,t,o,r,i){var n,s={cmd:o,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:_e.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 o=de[e],r=Ee[e];return null===r?null:new V2NIMErrorImpl({code:e,desc:o||r||e,detail:{cmd:t,timetag:Date.now()}})}(e.code,o);if(s.error=a,s.error){if(s.error.detail.cmd=o,!(null===(n=null==t?void 0:t.ignoreErrCodes)||void 0===n?void 0:n.includes(e.code)))return s;i.warn("parseCmd:: ignore error ",s.error),s.error.detail.ignore=!0}return t.response&&t.response.forEach(((e,t)=>{var o=r[t],i=e.type,n=e.name,a=e.reflectMapper;if(void 0!==o)switch(i){case"Property":s.content[n]=a?deserialize(o,a):o;break;case"PropertyArray":s.content[n]=o.map((e=>a?deserialize(e,a):e));break;case"Int":case"Long":case"Byte":s.content[n]=+o;break;case"Bool":s.content[n]="true"===o||!0===o||1===o;break;default:s.content[n]=o}})),s}function serialize(e,t,o){var r={};for(var i in e=function flattenObjByMapper(e,t){var o={};for(var r in t){var i=t[r],n="number"==typeof i?r:i.access?i.access:r,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&&(o[n]=a)}return o}(e,t),t){var n=t[i],s="number"==typeof n?i:n.access?n.access:i;if(!o||o.includes(i))if(s in e){if("number"==typeof n)r[n]=e[s];else if("object"==typeof n)if(n.converter){var a=n.converter(e[s],e);void 0!==a&&(r[n.id]=a)}else r[n.id]=e[s]}else"object"==typeof n&&n.def&&("function"==typeof n.def?r[n.id]=n.def(e):r[n.id]=n.def)}return r}function deserialize(e,t){var o={};for(var r in e){var i=t[r];if("string"==typeof i)o[i]=e[r];else if("object"==typeof i&&"prop"in i){var n=i.access?i.access:i.prop;if(i.converter){var s=i.converter(e[r],e);void 0!==s&&(o[n]=s)}else i.type&&"number"===i.type?o[n]=+e[r]:i.type&&"boolean"===i.type?o[n]=!("0"===e[r]||!e[r]):o[n]=e[r]}}for(var a in t){var c=t[a];if(c&&void 0!==c.def){var l=c.access?c.access:c.prop;l in o||("function"==typeof c.def?o[l]=c.def(e):o[l]=c.def)}}return o=function unflattenObj(e){var t={},_loop=function(o){var r=o.split(".");r.reduce((function(t,i,n){return t[i]||(t[i]=isNaN(Number(r[n+1]))?r.length-1==n?e[o]:{}:[])}),t)};for(var o in e)_loop(o);return t}(o),o}function registerParser(e){for(var t in Object.assign(pe,e.cmdConfig),e.cmdMap){var o=e.cmdMap[t],r=e.cmdConfig[o];if(r)if(Array.isArray(Te[t])){var i=!1;for(var n of Te[t])if(n.cmd===o&&n.config.service===r.service){i=!0;break}i||Te[t].push({config:r,cmd:o})}else Te[t]=[{config:r,cmd:o}]}}function invertSerializeItem(e){var t={};for(var o in e){var r=e[o];"number"==typeof r?t[r]=o:"object"==typeof r&&(t[r.id]={prop:o,type:r.retType,access:r.retAccess?r.retAccess:r.access?r.access:o,def:r.retDef,converter:r.retConverter})}return t}function replacer(e,t){return t instanceof RegExp?"__REGEXP "+t.toString():t}function validate(e,t={},o,r=!1){var i={};return Object.keys(e).forEach((n=>{var s=e[n].type,a=o?`In ${o}, `:"";if(null==t){var c=`${a}param is null or undefined`;throw r?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(i[n]=t[n]);var l=`${a}param '${n}' is required`;throw r?new ValidateErrorV2({detail:{reason:l,data:{key:n},rules:"required"}}):new ValidateError(l,{key:n},"required")}var _=Ie[s];if(_&&!_(t,n,e[n],r)){var d=`${a}param '${n}' unexpected`,E={key:n,value:t[n]};throw r?new ValidateErrorV2({detail:{reason:d,data:E,rules:JSON.stringify(e[n],replacer)}}):new ValidateError(d,E,JSON.stringify(e[n],replacer))}i[n]=t[n]})),i}var Ie={string:function(e,t,o){var{allowEmpty:r,max:i,min:n,regExp:s}=o,a=e[t];return"string"==typeof a&&((!1!==r||""!==a)&&(!("number"==typeof i&&a.length>i)&&(!("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,o){var{min:r,max:i}=o,n=e[t];return"number"==typeof n&&(!("number"==typeof r&&n<r)&&!("number"==typeof i&&n>i))},boolean:function(e,t){return"boolean"==typeof e[t]},file:function(e,t){return!0},enum:function(e,t,o){var{values:r}=o,i=e[t];return!r||r.indexOf(i)>-1},jsonstr:function(e,t){try{var o=JSON.parse(e[t]);return"object"==typeof o&&null!==o}catch(e){return!1}},func:function(e,t){return"function"==typeof e[t]},array:function(e,t,o,r=!1){var{itemType:i,itemRules:n,rules:s,min:a,max:c,values:l}=o,_=e[t];if(!Array.isArray(_))return!1;if("number"==typeof c&&_.length>c)return!1;if("number"==typeof a&&_.length<a)return!1;if(n)_.forEach(((e,o)=>{validate({[o]:n},{[o]:e},`${t}[${o}]`,r)}));else if(s)_.forEach(((e,o)=>validate(s,e,`${t}[${o}]`,r)));else if("enum"===i){if(l&&function difference(e,t){return t=t||[],(e=e||[]).filter((e=>-1===t.indexOf(e)))}(_,l).length)return!1}else if(i&&!_.every((e=>typeof e===i)))return!1;return!0},object:function(e,t,o,r=!1){var{rules:i,allowEmpty:n}=o,s=e[t];if("object"!=typeof s||null===s)return!1;if(i){var a=Object.keys(i),c=Object.keys(s).filter((e=>a.indexOf(e)>-1));if(!1===n&&0===c.length)return!1;validate(i,s,t,r)}return!0}},Ne=["error","warn","log","debug"],emptyFunc=function(){},fe=["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=fe.indexOf(e)>-1?e:"off",t.debugLevel&&(this.debugLevel=fe.indexOf(t.debugLevel)>-1?t.debugLevel:this.debugLevel),this.logStorage=!1===t.storageEnable?null:new ae.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(),ae.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 o in t){var r=o,i=t[r];i&&(this.strategies[r].func=i)}}}setLogFunc(e,t="log"){var o=Ne.findIndex((t=>t===e)),r=Ne.findIndex((e=>e===t));Ne.forEach(((e,t)=>{this[e]=function(){if(!(t>o&&t>r)){var i=Array.prototype.slice.call(arguments),n=this.strategies[e],s=this.formatArgs(i,n.name);t<=r&&this.logStorage&&this.prepareSaveLog(s,e),t<=o&&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 o=new Date;return`[NIM ${this.iid} ${t} ${`${o.getMonth()+1}-${o.getDate()} ${o.getHours()}:${o.getMinutes()}:${o.getSeconds()}:${o.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()}}class CoreAdapters{constructor(e){this.lastSuccUploadHost="",this.core=e}getFileUploadInformation(e){return ae.getFileUploadInformation(e)}request(e,t,o){var r=(new Date).getTime(),i=(null==o?void 0:o.exception_service)||0;return ae.request(e,t).catch((o=>{var n,s,a,c,l=o;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:r,action:1,exception_service:i}),this.core.reporter.reportTraceUpdateV2("exceptions",{code:"number"==typeof l.code?l.code:0,description:l.message||`${l.code}`,operation_type:0,target:e,context:t?JSON.stringify(t):""},{asyncParams:ae.net.getNetworkStatus()}),this.core.reporter.reportTraceEnd("exceptions",1),o}))}uploadFile(e,t){var o,r,i,n;return __awaiter(this,void 0,void 0,(function*(){for(var s="BROWSER"===ae.platform,a=s?e.chunkUploadHostBackupList:e.commonUploadHostBackupList,c=s?e.chunkUploadHost:e.commonUploadHost,l=a.indexOf(c),_=-1===l?[c,...a]:[c,...a.slice(0,l),...a.slice(l+1)],d=Math.max(_.indexOf(this.lastSuccUploadHost),0),E=null,h=0;h<_.length;h++){var g=(new Date).getTime(),m=_[(h+d)%_.length];null==t||t.update({retry_times:h});try{var u=yield ae.uploadFile(Object.assign(Object.assign({},e),s?{chunkUploadHost:m}:{commonUploadHost:m}));return this.lastSuccUploadHost=m,"string"==typeof u.size&&(u.size=parseInt(u.size)),"string"==typeof u.dur&&(u.dur=parseInt(u.dur)),"string"==typeof u.w&&(u.w=parseInt(u.w)),"string"==typeof u.h&&(u.h=parseInt(u.h)),u}catch(e){this.core.cloudStorage.nos.nosErrorCount--,E=e;var p=e;this.core.reporter.reportTraceStart("exceptions",{user_id:this.core.options.account||(null===(r=null===(o=this.core)||void 0===o?void 0:o.auth)||void 0===r?void 0:r.account),trace_id:null===(n=null===(i=this.core.clientSocket)||void 0===i?void 0:i.socket)||void 0===n?void 0:n.sessionId,start_time:g,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:ae.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}}var Se="https://abt-online.netease.im/v1/api/abt/client/getExperimentInfo",Me="imElite_sdk_abtest_web";class ABTest{constructor(e,t){this.abtInfo={},this.core=e,this.config=assignOptions({isAbtestEnable:!0,abtestUrl:Se,abtestProjectKey:Me},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 o;try{o=yield this.core.adapters.request(this.config.abtestUrl,{method:"POST",dataType:"json",headers:{sdktype:"ABTest"},data:{clientInfo:{projectKey:this.config.abtestProjectKey,appKey:this.core.options.appkey,osType:"Web",sdkVersion:"10.9.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==o?void 0:o.data)||void 0===e?void 0:e.data)||void 0===t?void 0:t.abtInfo)||{}}}))}}class TimerManager{constructor(){this.timerList=[],this.id=1,this.timer=null,this.timeout=0}addTimer(e,t=0,o=1){var r=(new Date).getTime(),i=this.id;return this.timerList.push({id:i,loop:o,count:0,timeout:r+t,interval:t,callback:e}),this.id++,this.checkTimer(r),i}checkTimer(e=(new Date).getTime()){if(this.removeFinished(),0!==this.timerList.length||null==this.timer){var t=0;for(var o of this.timerList)(0===t||t>o.timeout)&&(t=o.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 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 o=get(e,"error.detail.ignore");return e.error&&!o?Promise.reject(e.error):Promise.resolve(e)}}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 o=Math.random(),r=Math.floor(o*this.jitter*e);e=0==(1&Math.floor(10*o))?e-r:e+r,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 Ae,ye,Oe,ve=["disconnect","connect","heartbeat","message","json","event","ack","error","noop"],Re=["transport not supported","client not handshaken","unauthorized"],Ce=["reconnect"];class BaseWebsocket extends e{constructor(e,t,o){super(),this.websocket=null,this.socketConnectTimer=0,this.url="",this.linkSSL=!0,this.core=e,this.url=t,this.linkSSL=o,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,o]=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}"`,o=e.code;o="v2"===get(this.core,"options.apiVersion")?e.code===_e.V2NIM_ERROR_CODE_CONNECT_TIMEOUT?_e.V2NIM_ERROR_CODE_CONNECT_TIMEOUT:_e.V2NIM_ERROR_CODE_CONNECT_FAILED:408===e.code?408:415;var r=new V2NIMErrorImpl({code:o,detail:{reason:t,rawError:e}});this.logger.error(t),this.status="disconnected",this.emit("handshakeFailed",r)}}))):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")?_e.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 ae.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,o=this.decodePacket(e.data);if(o)switch(o.type){case"connect":this.onConnect();break;case"disconnect":this.close(),this.emit("disconnect",{code:0,reason:"MessageEvent type disconnect"});break;case"message":case"json":this.emit("message",o.data);break;case"event":o.name&&this.emit(o.name,o.args);break;case"error":"unauthorized"===o.reason?this.emit("connect_failed",o.reason):this.emit("error",o.reason),this.logger.error("imsocket::Websocket connect failed, onmessage type error. url: ",this.socketUrl),clearTimeout(this.socketConnectTimer),this.emit("handshakeFailed",new V2NIMErrorImpl({code:"v2"===get(this.core,"options.apiVersion")?_e.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",o.type)}}encodePacket(e){var t,o,{type:r,id:i="",endpoint:n="",ack:s}=e,a=null;if(!r)return"";switch(r){case"error":t=e.reason?Re.indexOf(e.reason):"",o=e.advice?Ce.indexOf(e.advice):"",""===t&&""===o||(a=t+(""!==o?"+"+o:""));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=[ve.indexOf(r),i+("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 o,[,r,i,n,s,a]=t,c={type:ve[+r],endpoint:s};switch(i&&(c.id=i,c.ack=!n||"data"),c.type){case"error":o=a.split("+"),c.reason=Re[+o[0]]||"";break;case"message":c.data=a||"";break;case"connect":c.qs=a||"";break;case"event":try{var l=JSON.parse(a);c.name=l.name,c.args=l.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((o=a.match(/^([0-9]+)(\+)?(.*)/))&&(c.ackId=o[1],c.args=[],o[3]))try{c.args=o[3]?JSON.parse(o[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,o={data:e,type:"message",endpoint:""};null===(t=this.websocket)||void 0===t||t.send(this.encodePacket(o))}}!function(e){e[e.ACTIVE=1]="ACTIVE",e[e.KICKED=2]="KICKED",e[e.OFFLINE=3]="OFFLINE"}(Ae||(Ae={}));class V1ClientSocket{constructor(e,t){this.linkUrls=[],this.isAutoReconnect=!1,this.packetTimeout=3e4,this.linkSSL=!0,this.packetSer=1,this.retryCount=0,this.reconnectTimer=0,this.backoff=new Backoff({max:8e3,min:1600,jitter:.01}),this.sendingCmdMap=new Map,this.pingTimer=0,this.hasNetworkListener=!1,this.core=e,t&&(this.auth=t),this.logger=e.logger,this.reporter=e.reporter,this.timerManager=e.timerManager}setSessionId(e){}setLinkSSL(e){this.linkSSL=e}connect(e={},t){return __awaiter(this,void 0,void 0,(function*(){if(validate({linkUrls:{type:"array",itemType:"string",required:!1}},e),!/^(unconnected|waitReconnect)$/.test(this.core.status)){var o=`Core socket status is ${this.core.status}, and would not connect`;return this.logger.warn(o),Promise.reject(o)}this.core.status="connecting",e.linkUrls&&e.linkUrls.length>0&&(this.linkUrls=e.linkUrls.concat(this.linkUrls),this.linkUrls=function uniq(e){e=e||[];for(var t=[],o=0;o<e.length;o++)-1===t.indexOf(e[o])&&t.push(e[o]);return t}(this.linkUrls)),0===this.linkUrls.length&&this.linkUrls.push("weblink.netease.im:443");for(var r=0;r<this.linkUrls.length;r++){var i=this.linkUrls[r],n=(new Date).getTime();try{return yield this.doConnect(i),this.core.status="connected",this.logger.log(`clientsocketV1::connect success with url: ${i}`),i}catch(e){var s=e;t&&t(s,i),this.reporter.reportTraceStart("exceptions",{user_id:this.core.options.account,start_time:n,action:0,exception_service:6}),this.reporter.reportTraceUpdateV2("exceptions",{code:"number"==typeof s.code?s.code:0,description:s.message||`${s.code}`,operation_type:0,target:i},{asyncParams:ae.net.getNetworkStatus()}),this.reporter.reportTraceEnd("exceptions",1),this.logger.warn(`clientsocketV1::connect failed with url: ${i}`,e)}}throw 0===this.retryCount?this.doDisconnect(Ae.ACTIVE,"SocketHandshakeFailed"):this.doDisconnect(Ae.OFFLINE,"ReconnectHadRetryAllLinks"),new Error("clientSocketV1::socket xhr or socket connect failed")}))}doConnect(e){var t=!1;return new Promise(((o,r)=>{this.socket=new BaseWebsocket(this.core,e,this.linkSSL),this.socket.on("connect",(()=>{this.logger.log("clientSocketV1::on connect",e),this.core.reporterHookLinkKeep&&(this.core.reporterHookLinkKeep.start(),this.core.reporterHookLinkKeep.update({code:0,description:"connection begin",operation_type:0,target:e})),t=!0,o()})),this.socket.on("message",this.onMessage.bind(this)),this.socket.on("disconnect",(o=>__awaiter(this,void 0,void 0,(function*(){this.logger.log("clientSocketV1::socket on disconnect",o),this.core.reporterHookLinkKeep&&(yield this.core.reporterHookLinkKeep.update({code:(null==o?void 0:o.code)||0,description:(null==o?void 0:o.reason)||"socket on disconnect",operation_type:1,target:e}),this.core.reporterHookLinkKeep.end(!1)),t=!0,this.doDisconnect(Ae.OFFLINE,"SocketOnDisconnect")})))),this.socket.on("handshakeFailed",(e=>{t?this.ping():(this.logger.error(`clientsocketV1::handshake failed: "${e&&e.message}"`),this.cleanSocket()),t=!0,r(e)}))}))}cleanSocket(){this.socket&&("function"==typeof this.socket.removeAllListeners&&this.socket.removeAllListeners(),"function"==typeof this.socket.close&&this.socket.close(),this.socket=void 0)}beforeConnect(){this.reconnectTimer&&clearTimeout(this.reconnectTimer)}resetConnectStatus(){clearTimeout(this.reconnectTimer),this.backoff.reset(),this.retryCount=0,this.initOnlineListener()}doDisconnect(e,t,o){var r,i,n,s,a;if(this.logger.log(`doDisconnect:type:${e},description:${t}`),"unconnected"!==this.core.status){var c={1:"close",2:"kicked",3:"broken"}[e]||"";this.markAllCmdInvaild(new V2NIMErrorImpl({code:415,desc:"Packet timeout due to instance disconnect",detail:{reason:"Packet timeout due to instance disconnect",disconnect_reason:c}})),this.timerManager.destroy(),clearTimeout(this.pingTimer),this.cleanSocket();var l=!this.core.options.needReconnect||this.retryCount>=this.core.options.reconnectionAttempts;if(e===Ae.ACTIVE||l)this.logger.log("doDisconnect: emit disconnect, type "+e,l),this.core.status="unconnected",this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.core.eventBus.emit("disconnect"),this.core.emit("disconnect"),null===(r=this.auth)||void 0===r||r.emit("disconnect"),this.destroyOnlineListener();else if(e===Ae.KICKED){this.logger.log("doDisconnect: kicked"),this.core.status="unconnected",this.reconnectTimer&&clearTimeout(this.reconnectTimer);var _="string"==typeof t?{reason:"unknow",message:t}:t;this.core.eventBus.emit("kicked",_),this.core.emit("kicked",_),null===(i=this.auth)||void 0===i||i.emit("kicked",_),this.destroyOnlineListener()}else e===Ae.OFFLINE&&this.core.V1NIMLoginService.isManualLoginAttempt?(this.logger.log("doDisconnect: offline in manual login phase. no reconnect"),this.core.status="unconnected",this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.destroyOnlineListener()):e===Ae.OFFLINE&&(null===(s=null===(n=this.auth)||void 0===n?void 0:n.authenticator)||void 0===s?void 0:s.checkLoginTerminalCode(null==o?void 0:o.code))?(this.logger.log(`doDisconnect: login terminal code ${null==o?void 0:o.code}, no reconnect`),this.core.status="unconnected",this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.destroyOnlineListener(),this.core.eventBus.emit("disconnect"),this.core.emit("disconnect"),null===(a=this.auth)||void 0===a||a.emit("disconnect")):e===Ae.OFFLINE?(this.logger.log("doDisconnect: start to reconnect"),this.attempToReconnect()):this.logger.log("doDisconnect: nothing to do")}else this.logger.warn("doDisconnect:already unconnected")}attempToReconnect(){var e,t;if("waitReconnect"!==this.core.status){0===this.retryCount&&(this.core.eventBus.emit("disconnect"),this.core.emit("disconnect"),null===(e=this.auth)||void 0===e||e.emit("disconnect"));var o=this.backoff.duration();this.retryCount++,this.logger.log(`willReconnect ${this.retryCount} ${o}`),this.core.eventBus.emit("willReconnect",{retryCount:this.retryCount,duration:o}),this.core.emit("willReconnect",{retryCount:this.retryCount,duration:o}),null===(t=this.auth)||void 0===t||t.emit("willReconnect",{retryCount:this.retryCount,duration:o}),this.core.status="waitReconnect",this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=setTimeout((()=>__awaiter(this,void 0,void 0,(function*(){"waitReconnect"===this.core.status?!1===(yield ae.net.getNetworkStatus()).net_connect?(this.logger.log("doDisconnect: skip this reconnection attempt because network is offline"),this.core.status="connecting",this.retryCount>=this.core.options.reconnectionAttempts?this.doDisconnect(Ae.OFFLINE,"MaxReconnectionAttemptExceed"):this.attempToReconnect()):this.core.V1NIMLoginService.login({isAutoReconnect:!0}).catch((()=>{this.logger.error(`clientsocketV1::attempToReconnect failed ${this.retryCount}`)})):this.logger.warn(`doDisconnect: reconnectTimer status is ${this.core.status}, would not go on reconnecting`)}))),o)}else this.logger.warn("doDisconnect: already is waiting reconnect")}sendCmd(e,t,o){if("logined"!==this.core.status&&"login"!==e&&"chatroomLogin"!==e&&"qchatLogin"!==e)return this.logger.warn(`instance status is ${this.core.status}, so can not sendCmd ${e}`),Promise.reject({cmd:e,error:{code:"No_connected",message:"Connection not established",timetag:(new Date).getTime()}});if(!this.socket||!this.socket.send)return Promise.reject("No_socket");var r="heartbeat"!==e,i=r?this.packetSer++:0,n=function createCmd(e,t,o,r){var i=pe[e];if(!i)return o.error("createCmd:: can not find cmd config: ",e),null;var n={SER:t,SID:i.sid,CID:i.cid,Q:[]};return i.params&&r&&i.params.forEach((function(e){var t=r[e.name];if(null!=t){var o=e.type,{reflectMapper:i,select:s}=e;switch(e.type){case"PropertyArray":o="ArrayMable",t=t.map((e=>({t:"Property",v:i?serialize(e,i,s):e})));break;case"Property":t=i?serialize(t,i,s):t;break;case"Bool":t=t?"true":"false"}n.Q.push({t:o,v:t})}})),{packet:n,hasPacketResponse:"boolean"!=typeof i.hasPacketResponse||i.hasPacketResponse,hasPacketTimer:"boolean"!=typeof i.hasPacketTimer||i.hasPacketTimer}}(e,i,this.logger,t);if(!n){var s=`SendCmd ${i} ${e} error`;return this.logger.error(s),Promise.reject(new Error(s))}var{packet:a,hasPacketResponse:c,hasPacketTimer:l}=n,_=JSON.stringify(a);r&&(this.logger.getDebugMode()?this.logger.debug("clientsocketV1::sendCmd",e,`ser:${i}`,_):this.logger.log("clientsocketV1::sendCmd",e,`ser:${i}`));var d=(new Date).getTime();return new Promise(((r,n)=>{c&&this.sendingCmdMap.set(i,{cmd:e,params:t,callback:[r,n],timer:l?setTimeout((()=>{var t=new V2NIMErrorImpl({code:408,desc:"Packet Timeout",detail:{reason:"Packet Timeout",cmd:e,ser:i,timetag:Date.now()}});this.markCmdInvalid(i,t,e)}),o&&o.timeout?o.timeout:this.core.config.timeout):null});try{this.socket.send(_),c||r(a)}catch(t){var s=new V2NIMErrorImpl({code:415,detail:{reason:t&&t.message||"Unable to send packet",cmd:e,ser:i,timetag:Date.now(),rawError:t}});this.markCmdInvalid(i,s,e),n(t)}})).catch((e=>{var t;if(![408,415].includes(e.code))return Promise.reject(e);this.reporter.reportTraceStart("exceptions",{user_id:this.core.options.account,trace_id:null===(t=this.socket)||void 0===t?void 0:t.sessionId,start_time:d,action:2,exception_service:6});var o=get(e,"data.disconnect_reason")||"",r=408===e.code?"Send failed due to timeout":"Send failed. Reason unknown";return r=415===e.code?JSON.stringify({disconnect_reason:o}):r,this.reporter.reportTraceUpdateV2("exceptions",{code:e.code||415,description:r,operation_type:1,target:`${a.SID}-${a.CID}`,context:`${a.SER}`},{asyncParams:ae.net.getNetworkStatus()}),this.reporter.reportTraceEnd("exceptions",1),Promise.reject(e)}))}onMessage(e){var t=function parseCmd(e,t){var o;try{o=JSON.parse(e)}catch(o){return void t.error(`Parse command error:"${e}"`)}var r=o.sid+"_"+o.cid,i=o.r;if(["4_1","4_2","4_10","4_11"].includes(r)){var n=o.r[1].headerPacket;r=`${n.sid}_${n.cid}`,o.sid=n.sid,o.cid=n.cid,i=o.r[1].body}var s=Te[r],a=[];if(s&&s.length>0){for(var c of s)a.push(parseEachCmd(o,c.config,c.cmd,i,t));return a}t.error("parseCmd:: mapper not exist",r,o.code)}(e,this.logger);if(t&&t.length>0){var o=t[0],r=o.raw.ser;for(var i of(o.error&&this.logger.error("core:onMessage packet error",`${o.raw.sid}_${o.raw.cid}, ser:${r},`,o.error),"heartbeat"!==o.cmd&&(this.logger.getDebugMode()?this.logger.debug(`imsocket::recvCmd ser:${r}`,o.cmd,o.content):this.logger.log(`imsocket::recvCmd ser:${r}`,o.cmd)),t))this.packetHandler(i)}}packetHandler(e){var t,o,r,i;if(e){var n=e.raw.ser,s=this.sendingCmdMap.get(n);if(s&&s.cmd===e.cmd){var{callback:a,timer:c,params:l}=s;if(clearTimeout(c),e.params=l,this.sendingCmdMap.delete(n),"heartbeat"===e.cmd)return void a[0]();var _=null===(o=null===(t=this.core[e.service])||void 0===t?void 0:t.process)||void 0===o?void 0:o.call(t,e);_&&"function"==typeof _.then?_.then((e=>{a[0](e)})).catch((e=>{a[1](e)})):(this.logger.log("imsocket:: handlerFn without promise",e.service,e.cmd),a[0]())}else{var d=null===(i=null===(r=this.core[e.service])||void 0===r?void 0:r.process)||void 0===i?void 0:i.call(r,e);d&&"function"==typeof d.then&&d.catch((e=>{this.logger.error("imsocket::no obj cache, no process handler",e)}))}}}markCmdInvalid(e,t,o){var r=this.sendingCmdMap.get(e);if(r){var{callback:i,timer:n}=r;n&&clearTimeout(n),this.sendingCmdMap.delete(e),this.logger.warn(`packet ${e}, ${o} is invalid:`,t),i[1](t)}}markAllCmdInvaild(e){this.logger.log("markAllCmdInvaild",e),this.sendingCmdMap.forEach((t=>{var{callback:o,timer:r,cmd:i}=t;this.logger.log(`markAllCmdInvaild:: cmd "${i}"`),r&&clearTimeout(r),o[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(yield this.testHeartBeat5Timeout())return this.core.reporterHookLinkKeep&&(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(Ae.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(`clientsocketV1:: test heartbeat ${e} Timeout`)}return!0}))}initOnlineListener(){this.hasNetworkListener||(this.logger.log("clientsocketV1::onlineListener:init"),this.hasNetworkListener=!0,ae.net.onNetworkStatusChange((e=>{this.logger.log("clientsocketV1::onlineListener:network change",e),e.isConnected&&"logined"===this.core.status?this.ping():e.isConnected&&"waitReconnect"===this.core.status?(this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.core.V1NIMLoginService.login({isAutoReconnect:!0}).catch((()=>{this.logger.error(`clientsocketV1::attempToReconnect failed ${this.retryCount}`)}))):e.isConnected||this.doDisconnect(Ae.OFFLINE,"OfflineListener")})))}destroyOnlineListener(){this.logger.log("clientsocketV1::onlineListener:destroy"),ae.net.offNetworkStatusChange(),this.hasNetworkListener=!1}disconnect(){switch(this.core.status){case"connected":case"logined":case"connecting":case"waitReconnect":return this.doDisconnect(Ae.ACTIVE,"UserActiveDisconnect"),Promise.resolve();default:return Promise.resolve()}}}function formatChatroom(e){var t=Object.assign({},e);return["announcement","broadcastUrl","ext"].forEach((e=>{void 0===t[e]&&(t[e]="")})),["createTime","updateTime","onlineMemberNum"].forEach((e=>{void 0!==t[e]&&(t[e]=parseInt(t[e]))})),["mute"].forEach((e=>{void 0!==t[e]&&(t[e]=1===parseInt(t[e]))})),t}!function(e){e[e.Android=1]="Android",e[e.iOS=2]="iOS",e[e.PC=4]="PC",e[e.WindowsPhone=8]="WindowsPhone",e[e.Web=16]="Web",e[e.Server=32]="Server",e[e.Mac=64]="Mac",e[e.HarmonyOS=65]="HarmonyOS"}(ye||(ye={})),function(e){e[e.text=0]="text",e[e.image=1]="image",e[e.audio=2]="audio",e[e.video=3]="video",e[e.geo=4]="geo",e[e.notification=5]="notification",e[e.file=6]="file",e[e.tip=10]="tip",e[e.robot=11]="robot",e[e.g2=12]="g2",e[e.custom=100]="custom"}(Oe||(Oe={}));var Pe=function invert(e){e=e||{};var t={};for(var o in e)t[e[o]]=o;return t}({unset:"-2",restricted:"-1",common:"0",owner:"1",manager:"2",guest:"3",anonymous:"4"});function formatChatroomMember(e){var t=Object.assign({},e),o={tempMuted:!1,tempMuteDuration:0};return Object.keys(o).forEach((e=>{t[e]=t[e]||o[e]})),["chatroomId"].forEach((e=>{void 0!==t[e]&&(t[e]=t[e].toString())})),["level","enterTime","updateTime","tempMuteDuration"].forEach((e=>{void 0!==t[e]&&(t[e]=parseInt(t[e]))})),["online","guest","blacked","muted","valid","tempMuted"].forEach((e=>{void 0!==t[e]&&(t[e]=1===parseInt(t[e]))})),void 0!==t.type&&(t.type=Pe[t.type]),t.avatar,t.online||delete t.enterTime,t.guest&&(t.type="guest",delete t.valid,delete t.guest),"common"!==t.type&&delete t.level,t}function formatChatroomMembers(e){return e&&e.length>0?e.map((e=>formatChatroomMember(e))):[]}var Le={301:"memberEnter",302:"memberExit",303:"blackMember",304:"unblackMember",305:"gagMember",306:"ungagMember",307:"addManager",308:"removeManager",309:"addCommon",310:"removeCommon",311:"closeChatroom",312:"updateChatroom",313:"kickMember",314:"addTempMute",315:"removeTempMute",316:"updateMemberInfo",317:"updateQueue",318:"muteRoom",319:"unmuteRoom",320:"batchUpdateQueue",321:"addTempMuteTag",322:"removeTempMuteTag",323:"deleteChatroomMsg",325:"updateChatroomTags"};function formatChatroomMsg(e,t){var o=__rest(e,["onUploadDone","onUploadProgress","onUploadStart"]);if(["time","userUpdateTime"].forEach((e=>{void 0!==o[e]&&(o[e]=parseInt(o[e]))})),["resend","needAntiSpam","antiSpamUsingYidun","skipHistory","highPriority","clientAntiSpam"].forEach((e=>{void 0!==o[e]&&(o[e]=1===parseInt(o[e]))})),o.type=getEnumKeyByEnumValue(Oe,o.type),o.fromClientType=getEnumKeyByEnumValue(ye,o.fromClientType),o.flow=o.from===t?"out":"in",o.status=o.status||"success","string"==typeof o.body)try{o.body=JSON.parse(o.body)}catch(e){}return"notification"===o.type&&(o.attach=o.body?function formatNotificationBody(e){var t={};if(t.type=Le[e.id]||e.id,!e.data)return e;t=Object.assign(t,e.data);var o={operator:"from",opeNick:"fromNick",target:"to",tarNick:"toNick"};if(Object.keys(o).forEach((e=>{void 0!==t[e]&&(t[o[e]]=t[e],delete t[e])})),["muteDuration"].forEach((e=>{void 0!==t[e]&&(t[e]=parseInt(t[e]))})),!t.queueChange)return t;var r={};try{r=JSON.parse(t.queueChange)}catch(e){return t}switch(r._e){case"OFFER":r={type:"OFFER",elementKey:r.key,elementValue:r.content};break;case"POLL":r={type:"POLL",elementKey:r.key,elementValue:r.content};break;case"DROP":r={type:"DROP"};break;case"PARTCLEAR":case"BATCH_UPDATE":r={type:r._e,elementKv:r.kvObject}}return t.queueChange=r,t}(o.body):{},o.body=""),o}function formatChatroomMsgs(e,t){return e&&e.length>0?e.map((e=>formatChatroomMsg(e,t))):[]}var De={1:{code:"chatroomClosed",message:"Chatroom is closed"},2:{code:"managerKick",message:"Kicked out by owners or administrators"},3:{code:"samePlatformKick",message:"The same account is not allowed to multiple login at the same time"},4:{code:"silentlyKick",message:"Quietly kicked"},5:{code:"blacked",message:"Was blacklisted"}};class V1AuthAuthenticatorService{constructor(e){this.core=e}verifyAuthentication(e=!1){return __awaiter(this,void 0,void 0,(function*(){var t=this.core.options,o=ae.getSystemInfo(),r=Object.assign(Object.assign({},t),{appLogin:e?0:1,deviceId:this.core.config.deviceId,clientSession:this.core.config.clientSession,clientType:16,protocolVersion:1,sdkVersion:100971,sdkHumanVersion:"10.9.71",os:o.os,browser:o.browser,userAgent:this.core.options.loginSDKTypeParamCompat?"Native/10.9.71":o.userAgent.replace("{{appkey}}",t.appkey).slice(0,299),libEnv:this.core.options.loginSDKTypeParamCompat?void 0:o.libEnv,hostEnv:this.core.options.loginSDKTypeParamCompat?0:o.hostEnvEnum}),i=Object.assign(Object.assign({},t),{appkey:t.appkey,account:t.account,deviceId:this.core.config.deviceId,clientSession:this.core.config.clientSession,appLogin:1});t.isAnonymous&&(i.isAnonymous=1,i.account=i.account||`nimanon_${ge()}`,r.account=i.account,i.chatroomNick=i.account||`nimanon_${ge()}`,i.chatroomAvatar=i.chatroomAvatar||" "),t.tags&&t.tags.length>0&&(i.tags=JSON.stringify(t.tags));var n=yield this.core.clientSocket.sendCmd("chatroomLogin",{type:1,chatroomLogin:i,chatroomIMLogin:r});return this.core.status="logined",{chatroom:formatChatroom(n.content.chatroom),member:formatChatroomMember(n.content.chatroomMember)}}))}}class ChatroomAuthService extends Service{constructor(e){super("chatroomAuth",e),this.account="",this.token="",this.deviceId="",this.isManualLoginAttempt=!1,this.authenticatorService=new V1AuthAuthenticatorService(e)}login(e={}){return __awaiter(this,void 0,void 0,(function*(){e.isAutoReconnect||(this.isManualLoginAttempt=!0);var t=Date.now(),o=yield this._connect(e);this.core.abtest.abtRequest();try{yield this.doLogin(e.isAutoReconnect,o,t),this.isManualLoginAttempt=!1}catch(e){throw this.isManualLoginAttempt=!1,e}}))}_connect(e={}){return __awaiter(this,void 0,void 0,(function*(){if(!/^(unconnected|waitReconnect)$/.test(this.core.status)){var t=`Chatroom status is ${this.core.status}, and would not connect`;return this.logger.warn(t),Promise.reject(t)}this.core.clientSocket.beforeConnect();var o=e.isAutoReconnect||!1;return yield this.core.clientSocket.connect({linkUrls:this.core.options.chatroomAddresses,isAutoReconnect:o})}))}doLogin(e=!1,t,o){var r;return __awaiter(this,void 0,void 0,(function*(){var i;try{i=yield this.authenticatorService.verifyAuthentication(e);var{net_connect:n}=yield ae.net.getNetworkStatus();this.core.status="logined",this.core.reporter.report("chatroomLogin",{accid:this.core.account,roomId:this.core.options.chatroomId,serverIps:this.core.options.chatroomAddresses,currentServerIp:t,rt:Date.now()-o,result:200,failReason:"",time:Date.now(),net_connect:n})}catch(e){this.logger.error("chatroom login error",e);var s=get(e,"error.code")||get(e,"code")||408,a=get(e,"error.message")||get(e,"message")||"login failed",{net_connect:c}=yield ae.net.getNetworkStatus();if(this.core.reporter.report("chatroomLogin",{accid:this.core.account,roomId:this.core.options.chatroomId,serverIps:this.core.options.chatroomAddresses,currentServerIp:t,rt:Date.now()-o,result:s,failReason:a,time:Date.now(),net_connect:c}),this.core.clientSocket.doDisconnect(Ae.OFFLINE,this.isManualLoginAttempt?"FailedToInitializeLogin":"ReconnectLoginFailed"),this.isManualLoginAttempt)throw e;return}try{yield this.core.cloudStorage.init(null===(r=i.member)||void 0===r?void 0:r.enterTime)}catch(e){this.logger.error("NIM:login cloudStorage init failed ",e)}this.core.eventBus.emit("logined",i),this.core.emit("logined",i),this.core.clientSocket.resetConnectStatus(),this.core.clientSocket.ping(),this.core.timeOrigin.setOriginTimetick()}))}beKickedFromChatroomHandler(e){var t=e.content,{reason:o,ext:r}=t,i=function formatKickedReason(e){var t=De[e];return{reason:t?t.code:"unknow",message:t?t.message:"Unknown reason"}}(o);this.logger.warn("beKickedFromChatroomHandler:: ",i.reason,i.message,r),this.core.clientSocket.doDisconnect(Ae.KICKED,i)}}class ChatroomService extends Service{constructor(e){super("chatroom",e)}getInfo(){var e;return __awaiter(this,void 0,void 0,(function*(){var t=yield this.core.sendCmd("getChatroom");return formatChatroom(null===(e=t.content)||void 0===e?void 0:e.chatroom)}))}updateInfo(e){return __awaiter(this,void 0,void 0,(function*(){validate({chatroom:{type:"object",rules:{name:{type:"string",required:!1},announcement:{type:"string",required:!1},broadcastUrl:{type:"string",required:!1},ext:{type:"string",required:!1},queuelevel:{type:"number",min:0,max:1,required:!1}}},needNotify:{type:"boolean"},ext:{type:"string",required:!1}},e),yield this.core.sendCmd("updateChatroom",Object.assign(Object.assign({},e),{ext:e.ext||""}))}))}updateChatroomTagHandler(e){var t,o=e.content;this.logger.log("updateChatroomTagHandler:: ",o);var r=null===(t=null==o?void 0:o.updateTags)||void 0===t?void 0:t.currentTags;try{r=JSON.parse(r)}catch(e){this.logger.error("updateChatroomTagHandler:: ",e)}this.core.emit("tagsUpdate",r)}}var Ve,be,ke={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)"}},we={accessKeyId:"",secretAccessKey:"",sessionToken:"",region:"",maxRetries:0,bucket:"",objectName:"",token:"",shortUrl:""};function getUploadResponseFormat(e="file"){var t=ke[e]||{};return JSON.stringify(t).replace(/"/gi,'\\"')}!function(e){e[e.nos=1]="nos",e[e.s3=2]="s3"}(Ve||(Ve={})),function(e){e[e.dontNeed=-1]="dontNeed",e[e.time=2]="time",e[e.urls=3]="urls"}(be||(be={}));var xe={chunkUploadHost:"https://wannos-web.127.net",chunkUploadHostBackupList:["https://fileup.chatnos.com","https://oss.chatnos.com"],commonUploadHost:"https://fileup.chatnos.com",commonUploadHostBackupList:["https://upload.chatnos.com","https://oss.chatnos.com"],chunkMaxSize:4194304e4,commonMaxSize:104857600,uploadReplaceFormat:"https://{host}/{object}",cdn:{defaultCdnDomain:"nim-nosdn.netease.im",cdnDomain:"",bucket:"nim",objectNamePrefix:""},downloadUrl:"https://{bucket}-nosdn.netease.im/{object}",downloadHostList:["nos.netease.com"],nosCdnEnable:!0,isNeedToGetUploadPolicyFromServer:!0};function pickBy(e,t){e=e||{},t=t||(()=>!0);var o={};for(var r in e)t(e[r])&&(o[r]=e[r]);return o}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"),o=e.url;return{token:t,url:-1!==o.indexOf("?")?o+"&token="+t:o+"?token="+t}}))}deleteNosAccessToken(e){return __awaiter(this,void 0,void 0,(function*(){yield this.core.sendCmd("deleteNosAccessToken",{tag:e})}))}nosUpload(e,t,o){var r,i,n,s,a,c,l,_,d,E;return __awaiter(this,void 0,void 0,(function*(){var h=get(this.core,"config.cdn.bucket"),g={tag:e.nosScenes||h||"nim"};e.nosSurvivalTime&&(g.expireSec=e.nosSurvivalTime);var m,u=this.core.adapters.getFileUploadInformation(e);if(u&&u.complete&&t.destroy(),!o&&!u)try{m=yield this.core.sendCmd("getNosToken",{responseBody:getUploadResponseFormat(e.type),nosToken:g})}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")?_e.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}",u?null===(r=u.uploadInfo)||void 0===r?void 0:r.objectName:o?null==o?void 0:o.objectName:m.content.nosToken.objectName),T="";o&&o.shortUrl&&(T=o.shortUrl),(null===(s=null===(n=null===(i=null==u?void 0:u.uploadInfo)||void 0===i?void 0:i.payload)||void 0===n?void 0:n.mixStoreToken)||void 0===s?void 0:s.shortUrl)&&(T=u.uploadInfo.payload.mixStoreToken.shortUrl);var I,N=T||p;try{var f=u?{token:null===(a=null==u?void 0:u.uploadInfo)||void 0===a?void 0:a.token,bucket:null===(c=null==u?void 0:u.uploadInfo)||void 0===c?void 0:c.bucketName,objectName:null===(l=null==u?void 0:u.uploadInfo)||void 0===l?void 0:l.objectName}:o||m.content.nosToken;this.core.logger.log("uploadFile:: uploadFile params",{nosToken:f,chunkUploadHost:this.config.chunkUploadHost,chunkUploadHostBackupList:this.config.chunkUploadHostBackupList,commonUploadHost:this.config.commonUploadHost,commonUploadHostBackupList:this.config.commonUploadHostBackupList,platform:ae.platform});var S="BROWSER"===ae.platform?this.config.chunkUploadHost:`${this.config.commonUploadHost}/${f&&f.bucket}`,M="UNIAPP"===ae.platform||"MINIAPP"===(null===(_=ae.getSystemInfo())||void 0===_?void 0:_.libEnv)?4:o?2:0,A=e.filePath?e.filePath:"object"==typeof e.file?e.file.name:"";t.update({remote_addr:S,operation_type:M}),A&&t.update({local_file:A}),I=yield this.core.adapters.uploadFile(Object.assign(Object.assign(Object.assign(Object.assign({},e),{nosToken:f,chunkUploadHost:this.config.chunkUploadHost,chunkUploadHostBackupList:this.config.chunkUploadHostBackupList,commonUploadHost:this.config.commonUploadHost,commonUploadHostBackupList:this.config.commonUploadHostBackupList,maxSize:e.maxSize||this.config.chunkMaxSize}),o?{payload:{mixStoreToken:o}}:{}),{onUploadInfo:e=>{t.update(Object.assign({},e))}}),t)}catch(r){this.core.logger.error("uploadFile::nos uploadFile error:",r);var y="v2"===get(this.core,"options.apiVersion");if(r.code===_e.V2NIM_ERROR_CODE_CANCELLED||10499===r.errCode)throw new UploadError({code:y?_e.V2NIM_ERROR_CODE_CANCELLED:400,detail:{reason:get(r,"message")||"Request abort",rawError:r,curProvider:1}});if(y&&r.errCode===_e.V2NIM_ERROR_CODE_FILE_OPEN_FAILED)throw new V2NIMErrorImpl({code:_e.V2NIM_ERROR_CODE_FILE_OPEN_FAILED,detail:{reason:get(r,"message")||"Read file failed",rawError:r,curProvider:1}});var{net_connect:O}=yield ae.net.getNetworkStatus();if(!1===O)throw new UploadError({code:"v2"===get(this.core,"options.apiVersion")?_e.V2NIM_ERROR_CODE_FILE_UPLOAD_FAILED:400,detail:{reason:"No network",rawError:r,curProvider:1}});if(o){if(this.nosErrorCount<=0){try{this.cloudStorage.mixStorage._addCircuitTimer()}catch(t){throw new UploadError({code:"v2"===get(this.core,"options.apiVersion")?_e.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,o)}throw new UploadError({code:"v2"===get(this.core,"options.apiVersion")?_e.V2NIM_ERROR_CODE_FILE_UPLOAD_FAILED:400,detail:{reason:"NOS attempts failed",rawError:r,curProvider:1}})}var v=null==I?void 0:I.type,R=v&&v.indexOf("/")>-1?v.slice(0,v.indexOf("/")):"";R||(R=e.type||"");var C,P={image:"imageInfo",video:"vinfo",audio:"vinfo"};if(!P[R])return Object.assign({url:N},I);if(I.w&&I.h||I.dur)return Object.assign({url:N},I);try{C=yield this.core.adapters.request(`${p}?${P[R]}`,{method:"GET",dataType:"json",timeout:5e3},{exception_service:3})}catch(e){var L=e;return t.update({exception:`Fetch media info failed;url:${p}?${P[R]};errMsg:${(null===(d=L.detail)||void 0===d?void 0:d.reason)||L.message}`,external_code:L.code}),this.core.logger.error("uploadFile:: fetch file info error",e),Object.assign({url:N},I)}if(C){var{data:D}=C,V="imageInfo"===P[R]?D:null===(E=null==D?void 0:D.GetVideoInfo)||void 0===E?void 0:E.VideoInfo;return pickBy({url:N,name:I.name,size:I.size,ext:I.ext,w:null==V?void 0:V.Width,h:null==V?void 0:V.Height,orientation:null==V?void 0:V.Orientation,dur:null==V?void 0:V.Duration,audioCodec:null==V?void 0:V.AudioCodec,videoCodec:null==V?void 0:V.VideoCodec,container:null==V?void 0:V.Container},(function(e){return void 0!==e}))}return Object.assign({url:N},I)}))}_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 o=null===(e=null==t?void 0:t.content)||void 0===e?void 0:e.nosConfigTag,r=parseInt(null==o?void 0:o.expire);0!==r&&o.cdnDomain?-1===r?(this.config.cdn.bucket=o.bucket,this.config.cdn.cdnDomain=o.cdnDomain,this.config.cdn.objectNamePrefix=o.objectNamePrefix):(this.config.cdn.bucket=o.bucket,this.config.cdn.cdnDomain=o.cdnDomain,this.config.cdn.objectNamePrefix=o.objectNamePrefix,this.nosCdnHostTimer=this.core.timerManager.addTimer((()=>{this._getNosCdnHost()}),1e3*r)):(this.config.cdn.bucket="",this.config.cdn.cdnDomain="",this.config.cdn.objectNamePrefix="")}}))}}var Ue={"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"},Fe={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}},Ge={getNosToken:{sid:6,cid:2,service:"cloudStorage",params:[{type:"String",name:"responseBody"},{type:"Property",name:"nosToken",entity:"nosToken",reflectMapper:Fe.nosToken}],response:[{type:"Property",name:"nosToken",reflectMapper:invertSerializeItem(Fe.nosToken)}]},getOriginUrl:{sid:6,cid:22,service:"cloudStorage",params:[{type:"Property",name:"nosSafeUrlTag",reflectMapper:Fe.nosSafeUrlTag}],response:[{type:"Property",name:"nosSafeUrlTag",reflectMapper:invertSerializeItem(Fe.nosSafeUrlTag)}]},getNosCdnHost:{sid:6,cid:26,service:"cloudStorage",response:[{type:"Property",name:"nosConfigTag",reflectMapper:invertSerializeItem(Fe.nosConfigTag)}]},getGrayscaleConfig:{sid:6,cid:27,service:"cloudStorage",params:[{type:"Property",name:"config"}],response:[{type:"Property",name:"grayConfigTag",reflectMapper:invertSerializeItem(Fe.grayConfigTag)}]},getMixStorePolicy:{sid:6,cid:28,service:"cloudStorage",params:[{type:"LongArray",name:"supportType"}],response:[{type:"Property",name:"mixStorePolicyTag",reflectMapper:invertSerializeItem(Fe.mixStorePolicyTag)}]},getMixStoreToken:{sid:6,cid:29,service:"cloudStorage",params:[{type:"Property",name:"mixStoreTokenReqTag",reflectMapper:Fe.mixStoreTokenReqTag}],response:[{type:"Property",name:"mixStoreTokenResTag",reflectMapper:invertSerializeItem(Fe.mixStoreTokenResTag)}]},getFileAuthToken:{sid:6,cid:30,service:"cloudStorage",params:[{type:"Property",name:"mixStoreAuthTokenReqTag",reflectMapper:Fe.mixStoreAuthTokenReqTag}],response:[{type:"Property",name:"mixStoreAuthTokenResTag",reflectMapper:invertSerializeItem(Fe.mixStoreAuthTokenResTag)}]},getNosAccessToken:{sid:6,cid:24,service:"cloudStorage",params:[{type:"Property",name:"tag",reflectMapper:Fe.nosAccessTokenTag}],response:[{type:"Property",name:"tag",reflectMapper:invertSerializeItem(Fe.nosAccessTokenTag)}]},deleteNosAccessToken:{sid:6,cid:25,service:"cloudStorage",params:[{type:"Property",name:"tag",reflectMapper:Fe.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 o;return __awaiter(this,void 0,void 0,(function*(){if(ae.localStorage)try{ae.localStorage.getItem&&ae.localStorage.getItem(this.GRAYKEY)&&(this.grayConfig=JSON.parse(ae.localStorage.getItem(this.GRAYKEY))[e])}catch(e){ae.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 r=yield this.core.sendCmd("getGrayscaleConfig",{config:{}});if(r.content&&r.content.grayConfigTag){this.logger.log("uploadFile::getAppGrayConfigRequest success ");try{this.grayConfig=JSON.parse(r.content.grayConfigTag.config),this.grayConfig.ttl=JSON.parse(r.content.grayConfigTag.ttl)}catch(e){this.logger.error("getGrayscaleConfig error",e)}if(!this.grayConfig)return;var i=ae.localStorage.getItem(this.GRAYKEY)?JSON.parse(ae.localStorage.getItem(this.GRAYKEY)):{};this.grayConfig.timeStamp=(new Date).getTime(),i[e]=this.grayConfig,ae.localStorage.setItem(this.GRAYKEY,JSON.stringify(i))}else this.logger.log("uploadFile:: result grayConfig:",r.content)}(null===(o=this.grayConfig)||void 0===o?void 0:o.mixStoreEnable)&&(yield this._getMixStorePolicy(e))}))}_getMixStorePolicy(e){return __awaiter(this,void 0,void 0,(function*(){var t=(new Date).getTime();if(ae.localStorage)try{if(this.mixStorePolicy=JSON.parse(ae.localStorage.getItem(this.MIXSTOREKEY))[e],this.curProvider=parseInt(this.mixStorePolicy.providers[0]),this.mixStorePolicy.timeStamp&&this.mixStorePolicy.timeStamp+1e3*this.mixStorePolicy.ttl>t){var o=this.mixStorePolicy.timeStamp+1e3*this.mixStorePolicy.ttl-t;this.core.timerManager.addTimer(this._getMixStorePolicy.bind(this,e),o)}}catch(t){ae.localStorage.getItem(this.MIXSTOREKEY)&&JSON.parse(ae.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 r=(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=r.policyVersion,this.mixStorePolicy.ttl=Number(r.ttl),this.mixStorePolicy.providers=r.providers.split(","),this.circuitTimer&&this.core.timerManager.deleteTimer(this.circuitTimer),this.curProvider=parseInt(this.mixStorePolicy.providers[0]),this.mixStorePolicy.nosPolicy=r.nosPolicy?JSON.parse(r.nosPolicy):null,this.mixStorePolicy.s3Policy=r.s3Policy?JSON.parse(r.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 i=ae.localStorage.getItem(this.MIXSTOREKEY)?JSON.parse(ae.localStorage.getItem(this.MIXSTOREKEY)):{};this.mixStorePolicy.timeStamp=(new Date).getTime(),i[e]=this.mixStorePolicy,ae.localStorage.setItem(this.MIXSTOREKEY,JSON.stringify(i))}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 o=this.mixStorePolicy[1===this.curProvider?"nosPolicy":"s3Policy"].uploadConfig.retryPolicy.circuit;if(!o||0===o)throw new Error("uploadFile circuit error");this.circuitTimer=this.core.timerManager.addTimer((()=>{this.logger.log(`uploadFile:: upload policy will change,now policy:${this.curProvider} nextProvider:${parseInt(this.mixStorePolicy.providers[0])}`),this.curProvider=parseInt(this.mixStorePolicy.providers[0]),this.core.timerManager.deleteTimer(this.circuitTimer)}),1e3*o)}throw new Error("uploadFile will not retry again")}getFileAuthToken(e){return __awaiter(this,void 0,void 0,(function*(){return(yield this.core.sendCmd("getFileAuthToken",{mixStoreAuthTokenReqTag:e})).content.mixStoreAuthTokenResTag}))}}var Ye=-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,o){return __awaiter(this,void 0,void 0,(function*(){var r;if(Ye+=1,e.file)r=e.file;else if("string"==typeof e.fileInput){this.logger.warn("fileInput will abandon,Please use file or filepath");var i=document.getElementById(e.fileInput);if(!(i&&i.files&&i.files[0]))throw new Error("Can not get file from fileInput");r=i.files[0]}else{if(!(e.fileInput&&e.fileInput.files&&e.fileInput.files[0]))throw new Error(`Can not get file from fileInput ${e.fileInput}`);r=e.fileInput.files[0]}if(!this.mixStorePolicy.s3Policy)throw new Error("dont get s3 policy");var n={accessKeyId:o.accessKeyId,secretAccessKey:o.secretAccessKey,sessionToken:o.sessionToken,region:o.region,maxRetries:this.mixStorePolicy.s3Policy.uploadConfig.retryPolicy.retry},s=this.s3,a=decodeURIComponent(o.bucket),c=decodeURIComponent(o.objectName),l=r,_=`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;Ye%=h,d.endpoint=E.uploadConfig.uploadUrl[Ye],d.s3ForcePathStyle=!0,_=`${d.endpoint}/${a}/${c}`}t.update({local_file:r.name,remote_addr:_,operation_type:1});var g=new s(d);g.config.update(n);var m={Bucket:a,Key:c,Body:l,Metadata:{token:o.token},ContentType:l.type||"application/octet-stream"};this.core.logger.log("uploadFile:: s3 upload params:",m);var u=g.upload(m);return u.on("httpUploadProgress",(o=>{t.update({index:o.part});var r=parseFloat((o.loaded/o.total).toFixed(2));e.onUploadProgress&&e.onUploadProgress({total:o.total,loaded:o.loaded,percentage:r,percentageText:Math.round(100*r)+"%"})})),new Promise(((r,i)=>{var n=(new Date).getTime();u.send(((s,_)=>__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}),i(new UploadError({code:"v2"===get(this.core,"options.apiVersion")?_e.V2NIM_ERROR_CODE_CANCELLED:400,detail:{reason:"S3RequestAbortedError",rawError:s,curProvider:2}}));else{if(!s){t.update({http_code:200});var g=this.mixStorePolicy.s3Policy.cdnSchema;g=(g=g.replace("{cdnDomain}",this.mixStorePolicy.s3Policy.dlcdn)).replace("{objectName}",_.Key);var m={size:l.size,name:l.name,url:o.shortUrl?o.shortUrl:g,ext:l.name.split(".")[1]||"unknown"},u=e.type||"",p={image:"imageInfo"};return r(p[u]?yield this.getS3FileInfo({url:g,infoSuffix:p[u],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:ae.net.getNetworkStatus()}),this.core.reporter.reportTraceEnd("exceptions",1);var{net_connect:T}=yield ae.net.getNetworkStatus();if(!1===T)return i(new UploadError({code:"v2"===get(this.core,"options.apiVersion")?_e.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 i(new UploadError({code:"v2"===get(this.core,"options.apiVersion")?_e.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}}))}r(this.cloudStorage._uploadFile(e,t))}})))),e.onUploadStart&&e.onUploadStart(u)}))}))}getS3FileInfo(e){var t;return __awaiter(this,void 0,void 0,(function*(){var o,{url:r,infoSuffix:i,s3Result:n}=e;try{o=yield this.core.adapters.request(`${r}?${i}`,{method:"GET",dataType:"text",timeout:5e3},{exception_service:3})}catch(e){return this.core.logger.error("uploadFile:: fetch file info error",e),n}if(o){var{data:s}=o,a="imageInfo"===i?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",`${r}?${i}`),n}))}}var je,Be={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:""},He="ReporterHook::setMonitorForResources:";class ReporterHookCloudStorage{constructor(e,t){this.traceData=Be,this.core=e,this.id=Math.round(1e3*Math.random()),this.traceData=Object.assign({},Be,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}.${He} 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(`${He} 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=Be,this.destroy())}reset(){this.traceData=Object.assign({},Be)}destroy(){this.core=void 0,this.traceData=Be}}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:Ue,cmdConfig:Ge}),this.setOptions(t),this.setListeners()}setOptions(e={}){var t=e.storageKeyPrefix||"NIMClient";this.mixStorage.GRAYKEY=t+"-AllGrayscaleConfig",this.mixStorage.MIXSTOREKEY=t+"-AllMixStorePolicy";var{s3:o}=e,r=__rest(e,["s3"]),i=Object.assign({},xe,this.config);if(r&&Object.prototype.hasOwnProperty.call(r,"cdn")){var n=Object.assign(Object.assign({},i.cdn),r.cdn);this.config=Object.assign({},i,r),this.config.cdn=n}else this.config=Object.assign({},i,r);o&&(this.aws.s3=o)}setListeners(){this.core.eventBus.on("kicked",this._clearUnCompleteTask.bind(this)),this.core.eventBus.on("disconnect",this._clearUnCompleteTask.bind(this)),this.core.eventBus.on("V2NIMLoginService/loginLifeCycleLogout",this._clearUnCompleteTask.bind(this)),this.core.eventBus.on("V2NIMLoginService/loginLifeCycleKicked",this._clearUnCompleteTask.bind(this))}_clearUnCompleteTask(){Object.keys(this.uploadTaskMap).forEach((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,o){var r=e.onUploadProgress,i=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 r?e=>{o.update({transferred_size:e.loaded,full_size:e.total});try{r(e)}catch(e){this.logger.error("CloudStorage::uploadFile:options.onUploadProgress execute error",e)}}:e=>{o.update({transferred_size:e.loaded,full_size:e.total})},onUploadDone:"function"==typeof i?e=>{o.end(0);try{i(e)}catch(e){this.logger.error("CloudStorage::uploadFile:options.onUploadDone execute error",e)}}:()=>{o.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 o=new ReporterHookCloudStorage(this.core);if(o.start(),e.file)o.update({full_size:e.file.size,local_file:e.file.name});else if("string"==typeof e.fileInput){var r=document.getElementById(e.fileInput);r&&r.files&&r.files[0]&&o.update({full_size:r.files[0].size,local_file:r.files[0].name})}else e.fileInput&&e.fileInput.files&&e.fileInput.files[0]&&o.update({full_size:e.fileInput.files[0].size,local_file:e.fileInput.files[0].name});var i=ge(),{onUploadStart:n,onUploadProgress:s,onUploadDone:a}=this.processCallback(e,i,o);e.onUploadStart=n,e.onUploadProgress=s,e.onUploadDone=a;var c=null;try{c=yield this._uploadFile(e,o),e.md5&&(c.md5=e.md5),delete this.uploadTaskMap[i]}catch(e){throw delete this.uploadTaskMap[i],o.end((e&&e.code)===_e.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 o,r;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 i=this.core.adapters.getFileUploadInformation(e),n=!0;i?!1===i.complete&&2===this.mixStorage.curProvider?n=!1:i.complete&&t.destroy():n=!1,this.aws.s3||(this.mixStorage.curProvider=1);var s=we;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")?_e.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===(r=null===(o=null==i?void 0:i.uploadInfo)||void 0===o?void 0:o.payload)||void 0===r?void 0:r.mixStoreToken):2===this.mixStorage.curProvider?this.aws.s3Upload(e,t,s):this.nos.nosUpload(e,t,s)}))}getThumbUrl(e,t){var o,r,i,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,g]=/^(?:([A-Za-z]+):)?(\/{0,3})([0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/.exec(e);if(null===(o=this.grayConfig)||void 0===o?void 0:o.mixStoreEnable){var m=this._getUrlType(e);if(2===m&&this.mixStorePolicy.s3Policy&&get(this.mixStorePolicy,"s3Policy.thumbPolicy.imagethumb"))return(null===(i=null===(r=this.mixStorePolicy.s3Policy)||void 0===r?void 0:r.thumbPolicy)||void 0===i?void 0:i.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 o,r,i,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,g]=/^(?:([A-Za-z]+):)?(\/{0,3})([0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/.exec(e);if(null===(o=this.grayConfig)||void 0===o?void 0:o.mixStoreEnable){var m=this._getUrlType(e);if(2===m&&this.mixStorePolicy.s3Policy&&get(this.mixStorePolicy,"s3Policy.thumbPolicy.vframe"))return(null===(i=null===(r=this.mixStorePolicy.s3Policy)||void 0===r?void 0:r.thumbPolicy)||void 0===i?void 0:i.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[o,r,i,n,s,a,c,l]=/^(?:([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 _=this._getUrlType(e);return 2===_&&this.mixStorePolicy.s3Policy&&(e=this.mixStorePolicy.s3Policy.cdnSchema.replace("{cdnDomain}",this.mixStorePolicy.s3Policy.dlcdn).replace("{objectName}",a)),1===_&&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,g=this.config.cdn.cdnDomain,m=this.config.cdn.objectNamePrefix?decodeURIComponent(this.config.cdn.objectNamePrefix):"",u=decodeURIComponent(a),p=u.indexOf(m);if(g&&p>-1&&h)return`${r}:${i}${g}/${u.slice(p)}`;if(E.includes(n)&&a.includes("/")){var T=a.indexOf("/"),I=a.substring(0,T),N=a.substring(T+1);return d.replace("{bucket}",I).replace("{object}",N)}var f=E.filter((e=>"string"==typeof n&&n.includes(e)))[0],S=f?n.replace(f,"").replace(/\W/g,""):null;return S?d.replace("{bucket}",S).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,o=this.mixStorePolicy.s3Policy?this.mixStorePolicy.s3Policy.authPolicy.policyType:null;if(t===String(-1)&&o===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||o&&o.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 r=[],i=[];if(e.urls.forEach((e=>{var t=this._getUrlType(e);1===t&&i.push(e),2===t&&r.push(e)})),(!o||0!==r.length&&o.indexOf(String(3))<0)&&(this.logger.warn("s3 url don't support url token"),r=[]),(!t||0!==i.length&&t.indexOf(String(3))<0)&&(this.logger.warn("nos url don't support url token"),i=[]),0===r.length&&0===i.length)throw this.logger.error("not support urls"),new Error("not support urls");if(0===r.length||0===i.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)}}class ChatroomMsgService extends Service{constructor(e){super("chatroomMsg",e)}sendTextMsg(e){return validate({body:{type:"string",allowEmpty:!1}},e),this.sendMsg(Object.assign(Object.assign({},e),{type:"text"}))}sendGeoLocationMsg(e){return validate({body:{type:"object",rules:{title:{type:"string",allowEmpty:!1},lat:{type:"number"},lng:{type:"number"}}}},e),this.sendMsg(Object.assign(Object.assign({},e),{type:"geo",body:JSON.stringify(e.body)}))}sendTipMsg(e){return __awaiter(this,void 0,void 0,(function*(){return validate({body:{type:"string",allowEmpty:!1}},e),this.sendMsg(Object.assign(Object.assign({},e),{type:"tip"}))}))}sendCustomMsg(e){return __awaiter(this,void 0,void 0,(function*(){return validate({body:{type:"string",allowEmpty:!1}},e),this.sendMsg(Object.assign(Object.assign({},e),{type:"custom"}))}))}sendImageMsg(e){return this.doSendFile(Object.assign(Object.assign({},e),{type:"image"}))}sendFileMsg(e){return this.doSendFile(Object.assign(Object.assign({},e),{type:"file"}))}sendAudioMsg(e){return this.doSendFile(Object.assign(Object.assign({},e),{type:"audio"}))}sendVideoMsg(e){return this.doSendFile(Object.assign(Object.assign({},e),{type:"video"}))}doSendFile(e){return __awaiter(this,void 0,void 0,(function*(){validate({type:{type:"string",allowEmpty:!1},body:{type:"object",rules:{url:{type:"string",allowEmpty:!1}},required:!1},maxSize:{type:"number",min:1,required:!1}},e);var t=e.body;if(!t){if(!this.core.cloudStorage||!this.core.cloudStorage.uploadFile)throw new Error('Service "cloudStorage" does not exist');try{t=yield this.core.cloudStorage.uploadFile(e)}catch(e){throw this.logger.error("sendFile:: upload File error or abort.",e),e}}return this.sendMsg(Object.assign(Object.assign({},e),{body:JSON.stringify(t),type:e.type}))}))}queryMessageHistory(e){return __awaiter(this,void 0,void 0,(function*(){validate({timetag:{type:"number",required:!1},limit:{type:"number",min:1,max:100,required:!1},reverse:{type:"boolean",required:!1},msgTypes:{type:"array",itemType:"string",required:!1}},e);var t=yield this.core.sendCmd("chatroomQueryMessageHistory",Object.assign(Object.assign({timetag:0,limit:100,reverse:!1},e),{msgTypes:e.msgTypes?e.msgTypes.map((e=>Oe[e])):[]})),{chatroomMsgs:o}=t.content;return formatChatroomMsgs(o,this.core.account)}))}getHistoryMsgsByTags(e){return __awaiter(this,void 0,void 0,(function*(){validate({tags:{type:"array",itemType:"string",required:!0},types:{type:"array",itemType:"string",required:!1},fromTime:{type:"number",min:0,required:!1},toTime:{type:"number",min:0,required:!1},limit:{type:"number",min:0,required:!1},reverse:{type:"number",required:!1}},e);var t=Object.assign(Object.assign({fromTime:0,toTime:0,limit:100,reverse:0},e),{types:e.types?e.types.filter((e=>void 0!==Oe[e])).map((e=>Oe[e])):[]}),o=yield this.core.sendCmd("getHistoryMsgsByTags",{chatRoomTagHistoryMsgRequestTag:Object.assign(t,{tags:JSON.stringify(t.tags),types:JSON.stringify(t.types)})}),{chatroomMsgs:r}=o.content;return formatChatroomMsgs(r,this.core.account)}))}onChatroomMsgHandler(e){var t=e.content,o=formatChatroomMsg(null==t?void 0:t.chatroomMsg,this.core.account);this.logger.getDebugMode()?this.logger.debug("onChatroomMsgHandler::recvMsg",o.type,o.idClient,o):this.logger.log("onChatroomMsgHandler::recvMsg",o.type,o.idClient),this.core.emit("chatroomMsg",o),"out"!==o.flow&&this.doMsgReceiveReport(o,e)}doMsgReceiveReport(e,t){if(e.from!==this.core.account){var o=get(e,"__clientExt.statistics.apiCallingTime")||0,r=get(e,"__clientExt.statistics.sendTime")||0,i=get(e,"__clientExt.statistics.attachUploadDuration")||0,n=this.core.timeOrigin.getNTPTime(),s=e.time,a=this.core.timeOrigin.checkNodeReliable(t.__receiveTimeNode)?this.core.timeOrigin.getNTPTime(t.__receiveTimeNode):n;this.core.reporter.report("msgReceive",{msgId:"",clientId:e.idClient,serverTime:s,receiveTime:a,fromAccid:e.from,toAccid:this.core.account,type:4,roomId:e.chatroomId,apiCallingTime:o,sendTime:r,attachUploadDuration:i,callbackTime:n,preHandleTime:n,result:200,failReason:"",rt:n-s})}}sendMsg(e){return __awaiter(this,void 0,void 0,(function*(){validate({type:{type:"enum",values:getEnumKeys(Oe)},subType:{type:"number",min:1,required:!1}},e);var t=function generatorMsgForCmd(e,t,o){var r=__rest(e,["onSendBefore"]);return e.resend||(r.idClient=ge()),r.type=Oe[e.type],r.from=t,r.fromClientType=16,r.fromDeviceId=o,r.status=r.status||"sending",["resend","needAntiSpam","antiSpamUsingYidun","skipHistory","highPriority","clientAntiSpam"].forEach((t=>{void 0!==e[t]&&(r[t]=e[t]?1:0)})),["subType"].forEach((t=>{void 0!==e[t]&&(r[t]=parseInt(e[t]))})),["body","antiSpamContent","antiSpamBusinessId","ext"].forEach((t=>{void 0!==e[t]&&(r[t]="string"==typeof e[t]?e[t]:JSON.stringify(e[t]))})),r}(e,this.core.account,this.core.config.deviceId),o=formatChatroomMsg(Object.assign(Object.assign({},t),{status:"sending",time:(new Date).getTime()}),this.core.account);try{e.onSendBefore&&e.onSendBefore(o)}catch(e){this.core.logger.error("sendMsg: options.onSendBefore error",e)}try{var r=yield this.core.sendCmd("sendChatroomMsg",{chatroomMsg:t}),i=formatChatroomMsg(Object.assign(Object.assign(Object.assign({},t),r.content.chatroomMsg),{status:"success"}),this.core.account);return this.core.reporter.report("msgSend",{msgId:"",clientId:i.idClient,msgTime:i.time,fromAccid:this.core.account,toAccid:"",type:4,roomId:i.chatroomId,tid:"",result:200,failReason:"",rt:Date.now()-o.time}),i}catch(e){var n=formatChatroomMsg(Object.assign(Object.assign({},t),{status:"fail"}),this.core.account);throw e.msg=n,this.core.reporter.report("msgSend",{msgId:"",clientId:n.idClient,fromAccid:this.core.account,toAccid:"",type:4,roomId:n.chatroomId,tid:"",result:null==e?void 0:e.code,failReason:(null==e?void 0:e.message)||"",rt:Date.now()-t.time}),e}}))}}!function(e){e[e.regular=0]="regular",e[e.temp=1]="temp",e[e.regularOnline=2]="regularOnline",e[e.regularReverse=3]="regularReverse"}(je||(je={}));class ChatroomMemberService extends Service{constructor(e){super("chatroomMember",e)}updateMyRoomRole(e){return __awaiter(this,void 0,void 0,(function*(){validate({member:{type:"object",rules:{nick:{type:"string",required:!1},avatar:{type:"string",required:!1},ext:{type:"string",required:!1}}},needNotify:{type:"boolean"},ext:{type:"string",required:!1},needSave:{type:"boolean",required:!1}},e),yield this.core.sendCmd("chatroomUpdateMyRoomRole",Object.assign(Object.assign({},e),{chatroomMember:e.member,ext:e.ext||""}))}))}setMemberManager(e){return __awaiter(this,void 0,void 0,(function*(){return yield this.markChatroomMember(Object.assign(Object.assign({},e),{type:1}))}))}setMemberNormal(e){return __awaiter(this,void 0,void 0,(function*(){return yield this.markChatroomMember(Object.assign(Object.assign({},e),{type:2}))}))}setMemberMute(e){return __awaiter(this,void 0,void 0,(function*(){return yield this.markChatroomMember(Object.assign(Object.assign({},e),{type:-2}))}))}setMemberBlackList(e){return __awaiter(this,void 0,void 0,(function*(){return yield this.markChatroomMember(Object.assign(Object.assign({},e),{type:-1}))}))}queryMembers(e){var t;return __awaiter(this,void 0,void 0,(function*(){validate({type:{type:"enum",values:getEnumKeys(je)},time:{type:"number",required:!1},limit:{type:"number",required:!1}},e);var o=yield this.core.sendCmd("chatroomQueryMembers",Object.assign(Object.assign({time:0,limit:100},e),{type:je[e.type]}));return formatChatroomMembers(null===(t=o.content)||void 0===t?void 0:t.members)}))}queryMembersByAccounts(e){var t;return __awaiter(this,void 0,void 0,(function*(){validate({accounts:{type:"array",min:1,max:20,itemType:"string"}},e);var o=yield this.core.sendCmd("chatroomQueryMembersByAccounts",e);return formatChatroomMembers(null===(t=o.content)||void 0===t?void 0:t.members)}))}setMemberTempMute(e){return __awaiter(this,void 0,void 0,(function*(){validate({account:{type:"string",allowEmpty:!1},duration:{type:"number",min:0},needNotify:{type:"boolean",required:!1},ext:{type:"string",required:!1}},e),yield this.core.sendCmd("chatroomSetMemberTempMute",Object.assign(Object.assign({},e),{ext:e.ext||""}))}))}kickMember(e){return __awaiter(this,void 0,void 0,(function*(){validate({account:{type:"string",allowEmpty:!1},ext:{type:"string",required:!1}},e),yield this.core.sendCmd("chatroomKickMember",Object.assign(Object.assign({},e),{ext:e.ext||""}))}))}queryMembersCountByTag(e){return __awaiter(this,void 0,void 0,(function*(){return validate({tag:{type:"string",allowEmpty:!1}},e),(yield this.core.sendCmd("chatroomQueryMembersCountByTag",Object.assign({},e))).content.count}))}queryMembersByTag(e){var t;return __awaiter(this,void 0,void 0,(function*(){validate({tag:{type:"string",allowEmpty:!1},time:{type:"number",required:!1},limit:{type:"number",max:100,required:!1}},e);var o=yield this.core.sendCmd("chatroomQueryMembersByTag",{chatroomTagMemberReq:Object.assign({time:0,limit:100},e)});return formatChatroomMembers(null===(t=o.content)||void 0===t?void 0:t.members)}))}setMembersTempMuteByTag(e){return __awaiter(this,void 0,void 0,(function*(){validate({tag:{type:"string",allowEmpty:!1},duration:{type:"number",min:0},needNotify:{type:"boolean"},notifyTargetTags:{type:"string",allowEmpty:!1,required:!1},ext:{type:"string",required:!1}},e),yield this.core.sendCmd("chatroomSetMembersTempMuteByTag",{chatroomTagMuteReq:Object.assign(Object.assign({},e),{needNotify:e.needNotify?1:0,ext:e.ext||""})})}))}markChatroomMember(e){var t;return __awaiter(this,void 0,void 0,(function*(){validate({account:{type:"string"},isAdd:{type:"boolean"},ext:{type:"string",required:!1},level:{type:"number",required:!1}},e);var o=yield this.core.sendCmd("markChatroomMember",Object.assign(Object.assign({level:0},e),{ext:e.ext||""}));return formatChatroomMember(null===(t=o.content)||void 0===t?void 0:t.chatroomMember)}))}}class ChatroomQueueService extends Service{constructor(e){super("chatroomQueue",e)}init(e){return __awaiter(this,void 0,void 0,(function*(){validate({maxItemCount:{type:"number",min:0,max:1e3}},e),yield this.core.sendCmd("chatroomQueueInit",e)}))}update(e){return __awaiter(this,void 0,void 0,(function*(){validate({elementKey:{type:"string",allowEmpty:!1},elementValue:{type:"string",max:4096,allowEmpty:!1},transient:{type:"boolean",required:!1},account:{type:"string",required:!1}},e),yield this.core.sendCmd("chatroomQueueOffer",Object.assign(Object.assign({},e),{transient:!!e.transient}))}))}poll(e){return __awaiter(this,void 0,void 0,(function*(){return validate({key:{type:"string",required:!1}},e),e.key||(e.key=""),(yield this.core.sendCmd("chatroomQueuePoll",e||{})).content}))}batchUpdate(e){return __awaiter(this,void 0,void 0,(function*(){return validate({itemList:{type:"object"},needNotify:{type:"boolean",required:!1},notifyExtension:{type:"string",required:!1}},e),(yield this.core.sendCmd("chatroomQueueChange",Object.assign(Object.assign({},e),{needNotify:!!e.needNotify}))).content.invalidKeyList}))}fetch(){return __awaiter(this,void 0,void 0,(function*(){return(yield this.core.sendCmd("chatroomQueueList")).content.itemList}))}pickHeader(){return __awaiter(this,void 0,void 0,(function*(){var e=yield this.core.sendCmd("chatroomQueuePeak");return{[e.content.elementKey]:e.content.elementValue}}))}clear(){return __awaiter(this,void 0,void 0,(function*(){yield this.core.sendCmd("chatroomQueueDrop")}))}}var $e={"1_2":"heartbeat","6_23":"getServerTime","13_2":"chatroomLogin","13_3":"beKickedFromChatroom","13_4":"chatroomExit","13_6":"sendChatroomMsg","13_7":"onChatroomMsg","13_8":"chatroomQueryMembers","13_9":"chatroomQueryMessageHistory","13_11":"markChatroomMember","13_12":"closeChatroom","13_13":"getChatroom","13_14":"updateChatroom","13_15":"chatroomUpdateMyRoomRole","13_16":"chatroomQueryMembersByAccounts","13_17":"chatroomKickMember","13_19":"chatroomSetMemberTempMute","13_20":"chatroomQueueOffer","13_21":"chatroomQueuePoll","13_22":"chatroomQueueList","13_23":"chatroomQueuePeak","13_24":"chatroomQueueDrop","13_25":"chatroomQueueInit","13_26":"chatroomQueueChange","13_30":"chatroomSetMembersTempMuteByTag","13_31":"chatroomQueryMembersByTag","13_32":"chatroomQueryMembersCountByTag","13_36":"getHistoryMsgsByTags","13_101":"updateChatroomTag"},Ke={chatroomLogin:{appkey:1,account:2,deviceId:3,chatroomId:5,appLogin:8,chatroomNick:20,chatroomAvatar:21,chatroomExt:22,chatroomEnterExt:23,clientSession:26,isAnonymous:38,tags:39,notifyTargetTags:40,authType:41,loginExt:42},chatroomIMLogin:{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,token:1e3,customTag:38,customClientType:39,sdkHumanVersion:40,hostEnv:41,userAgent:42,libEnv:44,isReactNative:112,authType:115,loginExt:116},chatroomMsg:{idClient:1,type:2,body:3,ext:4,resend:5,userUpdateTime:6,fromNick:7,fromAvatar:8,fromExt:9,needAntiSpam:10,antiSpamContent:11,skipHistory:12,messageBody:13,antiSpamBusinessId:14,clientAntiSpam:15,antiSpamUsingYidun:16,time:20,from:21,chatroomId:22,fromClientType:23,highPriority:25,callbackExt:27,subType:28,yidunAntiCheating:29,env:30,notifyTargetTags:31,yidunAntiSpamExt:32,yidunAntiSpamRes:33,__clientExt:{id:39,converter:function objectToJSONString(e){if(e&&"object"==typeof e)try{return JSON.stringify(e)}catch(e){return}},retConverter:function stringToJSONObject(e){if(e&&"string"==typeof e)try{return JSON.parse(e)}catch(e){return}}}},chatroom:{id:1,name:3,announcement:4,broadcastUrl:5,ext:12,createTime:14,updateTime:15,queuelevel:16,creator:100,onlineMemberNum:101,mute:102},chatroomMember:{chatroomId:1,account:2,type:3,level:4,nick:5,avatar:6,ext:7,online:8,guest:9,enterTime:10,blacked:12,muted:13,valid:14,updateTime:15,tempMuted:16,tempMuteDuration:17},chatroomTagMemberReq:{tag:1,time:2,limit:3},chatroomTagMuteReq:{tag:1,duration:2,needNotify:3,ext:4,notifyTargetTags:5},chatroomCdnInfo:{enable:1,cdnUrls:2,timestamp:3,interval:4,decryptType:5,decryptKey:6,timeout:7},chatRoomTagHistoryMsgRequestTag:{tags:1,types:2,fromTime:3,toTime:4,limit:5,reverse:6},updateTags:{currentTags:1}},getDeserializeTag=()=>function invertSerializeMap(e){var t={};return Object.keys(e).forEach((o=>{t[o]=invertSerializeItem(e[o])})),t}(Ke),qe={user_id:"",trace_id:"",action:7,exception_service:6,duration:0,start_time:0,state:1,extension:[]};class ReporterHookLinkKeep{constructor(e,t){this.traceData=qe,this.core=e,this.traceData=Object.assign({},qe,t),this.traceData.extension=[]}reset(){this.traceData=Object.assign({},qe),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:o}=yield ae.net.getNetworkStatus();this.traceData.extension.push(Object.assign({code:0,foreground:!0,foreg_backg_switch:!1,net_type:t,net_connect:o},e))}))}end(e){var t=this.traceData.extension[0],o=this.traceData.extension[1];if(t&&0===t.operation_type&&o&&1===o.operation_type){var r=t.net_type!==o.net_type||t.net_connect!==o.net_connect;if(e||!r)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()}}function getIsDataReportEnable(e){var t,o,r=!0;return"boolean"==typeof(null===(t=null==e?void 0:e.reporterConfig)||void 0===t?void 0:t.enableCompass)?r=e.reporterConfig.enableCompass:"boolean"==typeof(null===(o=null==e?void 0:e.reporterConfig)||void 0===o?void 0:o.isDataReportEnable)&&(r=e.reporterConfig.isDataReportEnable),r}function getCompassDataEndpoint(e,t){var o,r,i=null===(o=null==t?void 0:t.reporterConfig)||void 0===o?void 0:o.compassDataEndpoint,n=null===(r=null==t?void 0:t.reporterConfig)||void 0===r?void 0:r.reportConfigUrl;if(i)return i;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}=ae.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 ze={debugLevel:"off",needReconnect:!0,reconnectionAttempts:Number.MAX_SAFE_INTEGER,autoMarkRead:!0,isAbtestEnable:!0,abtestUrl:Se,abtestProjectKey:Me};class Chatroom extends e{constructor(o,r={}){var i;super(),this.instanceName="Chatroom",this.status="unconnected",this.account="",this.eventBus=new e,this.options={},this.chatroom={},this.chatroomMsg={},this.chatroomMember={},this.chatroomQueue={},this.cloudStorage={},this.logger=new Logger(o.debugLevel,r.loggerConfig),this.setInitOptions(o),registerParser({cmdMap:$e,cmdConfig:(i=getDeserializeTag(),{heartbeat:{sid:1,cid:2,service:"chatroom"},getServerTime:{sid:6,cid:23,service:"chatroom",response:[{type:"Long",name:"time"}]},chatroomLogin:{sid:13,cid:2,service:"chatroom",params:[{type:"Byte",name:"type"},{type:"Property",name:"chatroomLogin",reflectMapper:Ke.chatroomLogin},{type:"Property",name:"chatroomIMLogin",reflectMapper:Ke.chatroomIMLogin}],response:[{type:"Property",name:"chatroom",reflectMapper:i.chatroom},{type:"Property",name:"chatroomMember",reflectMapper:i.chatroomMember},{type:"Property",name:"chatroomCdnInfo",reflectMapper:i.chatroomCdnInfo}]},chatroomExit:{sid:13,cid:4,service:"chatroom"},sendChatroomMsg:{sid:13,cid:6,service:"chatroomMsg",params:[{type:"Property",name:"chatroomMsg",reflectMapper:Ke.chatroomMsg}],response:[{type:"Property",name:"chatroomMsg",reflectMapper:i.chatroomMsg}]},chatroomQueryMessageHistory:{sid:13,cid:9,service:"chatroomMsg",params:[{type:"Long",name:"timetag"},{type:"Int",name:"limit"},{type:"Bool",name:"reverse"},{type:"LongArray",name:"msgTypes"}],response:[{type:"PropertyArray",name:"chatroomMsgs",reflectMapper:i.chatroomMsg}]},getHistoryMsgsByTags:{sid:13,cid:36,service:"chatroomMsg",params:[{type:"Property",name:"chatRoomTagHistoryMsgRequestTag",reflectMapper:Ke.chatRoomTagHistoryMsgRequestTag}],response:[{type:"PropertyArray",name:"chatroomMsgs",reflectMapper:i.chatroomMsg}]},getChatroom:{sid:13,cid:13,service:"chatroom",response:[{type:"Property",name:"chatroom",reflectMapper:i.chatroom}]},updateChatroom:{sid:13,cid:14,service:"chatroom",params:[{type:"Property",name:"chatroom",reflectMapper:Ke.chatroom},{type:"Bool",name:"needNotify"},{type:"String",name:"ext"}]},chatroomUpdateMyRoomRole:{sid:13,cid:15,service:"chatroomMember",params:[{type:"Property",name:"chatroomMember",reflectMapper:Ke.chatroomMember},{type:"Bool",name:"needNotify"},{type:"String",name:"ext"},{type:"Bool",name:"needSave"}]},markChatroomMember:{sid:13,cid:11,service:"chatroomMember",params:[{type:"String",name:"account"},{type:"Int",name:"type"},{type:"Bool",name:"isAdd"},{type:"Int",name:"level"},{type:"String",name:"ext"}],response:[{type:"Property",name:"chatroomMember",reflectMapper:i.chatroomMember}]},chatroomQueryMembers:{sid:13,cid:8,service:"chatroomMember",params:[{type:"Byte",name:"type"},{type:"Long",name:"time"},{type:"Int",name:"limit"}],response:[{type:"PropertyArray",name:"members",reflectMapper:i.chatroomMember}]},chatroomQueryMembersByAccounts:{sid:13,cid:16,service:"chatroomMember",params:[{type:"StrArray",name:"accounts"}],response:[{type:"PropertyArray",name:"members",reflectMapper:i.chatroomMember}]},chatroomKickMember:{sid:13,cid:17,service:"chatroomMember",params:[{type:"String",name:"account"},{type:"String",name:"ext"}]},chatroomSetMemberTempMute:{sid:13,cid:19,service:"chatroomMember",params:[{type:"String",name:"account"},{type:"Long",name:"duration"},{type:"Bool",name:"needNotify"},{type:"String",name:"ext"}]},closeChatroom:{sid:13,cid:12,service:"chatroom",params:[{type:"String",name:"ext"}]},chatroomQueryMembersCountByTag:{sid:13,cid:32,service:"chatroomMember",params:[{type:"String",name:"tag"}],response:[{type:"Long",name:"count"}]},chatroomQueryMembersByTag:{sid:13,cid:31,service:"chatroomMember",params:[{type:"Property",name:"chatroomTagMemberReq",reflectMapper:Ke.chatroomTagMemberReq}],response:[{type:"PropertyArray",name:"members",reflectMapper:i.chatroomMember}]},chatroomSetMembersTempMuteByTag:{sid:13,cid:30,service:"chatroomMember",params:[{type:"Property",name:"chatroomTagMuteReq",reflectMapper:Ke.chatroomTagMuteReq}]},chatroomQueueOffer:{sid:13,cid:20,service:"chatroomQueue",params:[{type:"String",name:"elementKey"},{type:"String",name:"elementValue"},{type:"Bool",name:"transient"},{type:"String",name:"account"}]},chatroomQueuePoll:{sid:13,cid:21,service:"chatroomQueue",params:[{type:"String",name:"key"}],response:[{type:"String",name:"elementKey"},{type:"String",name:"elementValue"}]},chatroomQueueChange:{sid:13,cid:26,service:"chatroomQueue",params:[{type:"StrStrMap",name:"itemList"},{type:"Bool",name:"needNotify"},{type:"String",name:"notifyExtension"}],response:[{type:"StrArray",name:"invalidKeyList"}]},chatroomQueueList:{sid:13,cid:22,service:"chatroomQueue",response:[{type:"KVArray",name:"itemList"}]},chatroomQueuePeak:{sid:13,cid:23,service:"chatroomQueue",response:[{type:"String",name:"elementKey"},{type:"String",name:"elementValue"}]},chatroomQueueDrop:{sid:13,cid:24,service:"chatroomQueue"},chatroomQueueInit:{sid:13,cid:25,service:"chatroomQueue",params:[{type:"Int",name:"maxItemCount"}]},onChatroomMsg:{sid:13,cid:7,service:"chatroomMsg",response:[{type:"Property",name:"chatroomMsg",reflectMapper:i.chatroomMsg}]},beKickedFromChatroom:{sid:13,cid:3,service:"auth",response:[{type:"Int",name:"reason"},{type:"String",name:"ext"}]},updateChatroomTag:{sid:13,cid:101,service:"chatroom",response:[{type:"Property",name:"updateTags",reflectMapper:i.updateTags}]}})}),this.otherOptions=r,this.timerManager=new TimerManager,this.adapters=new CoreAdapters(this),this.timeOrigin=new TimeOrigin(this),this.abtest=new ABTest(this,{isAbtestEnable:this.options.isAbtestEnable,abtestUrl:this.options.abtestUrl,abtestProjectKey:Me});var n="",s="";this.options.isFixedDeviceId?(n=ae.localStorage.getItem("__CHATROOM_DEVC_ID__")||ge(),s=ae.localStorage.getItem("__CHATROOM_CLIENT_SESSION_ID__")||ge(),ae.localStorage.setItem("__CHATROOM_DEVC_ID__",n),ae.localStorage.setItem("__CHATROOM_CLIENT_SESSION_ID__",s)):(n=ge(),s=ge()),this.config={timeout:8e3,deviceId:n,clientSession:s};var a=ae.getSystemInfo(),c=getCompassDataEndpoint(this.logger,this.otherOptions);this.reporter=new t(Object.assign(Object.assign({},c?{compassDataEndpoint:c}:{}),{isDataReportEnable:getIsDataReportEnable(this.otherOptions),common:{app_key:o.appkey,dev_id:this.config.deviceId,platform:"Web",sdk_ver:"10.9.71",env:"online",os_name:a.os,os_ver:a.osVer,lib_env:a.libEnv,host_env:a.hostEnv,host_env_ver:a.hostEnvVer,manufactor:a.manufactor,model:a.model,v2:!1},request:ae.request,logger:this.logger,autoStart:!0})),this.reporterHookLinkKeep=new ReporterHookLinkKeep(this),ae.setLogger(this.logger),this.auth=new ChatroomAuthService(this),this.V1NIMLoginService=this.auth,this.clientSocket=new V1ClientSocket(this),this.chatroom=new ChatroomService(this),this.chatroomMsg=new ChatroomMsgService(this),this.chatroomMember=new ChatroomMemberService(this),this.chatroomQueue=new ChatroomQueueService(this),this.cloudStorage=new CloudStorageService(this,Object.assign({storageKeyPrefix:this.instanceName},r.cloudStorageConfig)),Chatroom.instance=this,this.logger.log("Chatroom init, version ","10.9.71"," sdk version ",100971," appkey ",o.appkey)}static getInstance(e,t){if(!Chatroom.instance){if(e)return new Chatroom(e,t);throw new Error("Instance not exist, please input options")}if(e){if(Chatroom.instance.options.account===e.account&&Chatroom.instance.options.appkey===e.appkey)return Chatroom.instance.setOptions(e),Chatroom.instance;throw new Error("Unexpected login")}return Chatroom.instance}setOptions(e){if("object"==typeof e&&null!==e&&(Object.prototype.hasOwnProperty.call(e,"account")&&e.account!==this.options.account||Object.prototype.hasOwnProperty.call(e,"appkey")&&e.appkey!==this.options.appkey))throw new Error("chatroom::setOptions account and appkey is not allowed to reset");validate({token:{type:"string",required:!1},chatroomId:{type:"string",required:!1},chatroomAddresses:{type:"array",itemType:"string",min:1,required:!1},needReconnect:{type:"boolean",required:!1},reconnectionAttempts:{type:"number",required:!1},isAnonymous:{type:"boolean",required:!1},tags:{type:"array",itemType:"string",required:!1}},e),this.logger.log("chatroom::setOptions options is",e),this.options=Object.assign(Object.assign({},this.options),e)}setInitOptions(e){validate({account:{type:"string"},appkey:{type:"string"},token:{type:"string"},chatroomId:{type:"string"},chatroomAddresses:{type:"array",itemType:"string",min:1},needReconnect:{type:"boolean",required:!1},reconnectionAttempts:{type:"number",required:!1},isAnonymous:{type:"boolean",required:!1},tags:{type:"array",itemType:"string",required:!1}},e),this.logger&&this.logger.log("chatroom::setInitOptions options is",e),this.account=e.account,this.options=Object.assign(Object.assign({},ze),e)}connect(e={}){return this.auth.login(e)}disconnect(){switch(this.status){case"logined":return this.sendCmd("chatroomExit",void 0,{timeout:1e3}).then((()=>{this.clientSocket.doDisconnect(Ae.ACTIVE,"UserActiveDisconnect")})).catch((e=>{this.logger.error("Instance::disconnect sendCmd:logout error",e),this.clientSocket.doDisconnect(Ae.ACTIVE,"UserActiveDisconnect")}));case"connected":case"connecting":case"waitReconnect":return this.clientSocket.doDisconnect(Ae.ACTIVE,"UserActiveDisconnect"),Promise.resolve();case"unconnected":case"destroyed":return Promise.resolve()}}destroy(){return Chatroom.instance=void 0,this.disconnect().then((()=>{this.status="destroyed",this.removeAllListeners(),this.eventBus.removeAllListeners(),this.logger.destroy(),this.reporter.destroy(),this.timerManager.destroy(),this.connect=emptyFuncWithPromise,this.disconnect=emptyFuncWithPromise,this.destroy=emptyFuncWithPromise}))}sendCmd(e,t,o){return this.clientSocket.sendCmd(e,t,o)}emit(e,...t){try{var o=Date.now(),r=super.emit(e,...t),i=Date.now()-o;return i>=10&&this.logger.warn(`Core::emit event: ${e} process takes: ${i}ms`),r}catch(t){return this.logger.error(`Core::emit event: ${e}. Error: ${t}`),setTimeout((()=>{throw this.logger.error(`Core::emit throw error in setTimeout. event: ${e}. Error: ${t}`),t}),0),!1}}}Chatroom.sdkVersion=100971,Chatroom.sdkVersionFormat="10.9.71";var We={debug(...e){},log(...e){},warn(...e){},error(...e){}};function setLogger(e){We=e}function getLogger(){return We}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 o,r="",i=0,n=0,s=0;o=t.charAt(s++);~o&&(n=i%4?64*n+o:o,i++%4)?r+=String.fromCharCode(255&n>>(-2*i&6)):0)o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(o);return r}(e),o=t.length,r=new Uint8Array(o),i=0;i<o;i++)r[i]=t.charCodeAt(i);return r.buffer}function to(e){try{return e.then((e=>[null,e])).catch((e=>[e,void 0]))}catch(e){var t=e;return Promise.resolve([t,void 0])}}var Je={clear(){uni.clearStorageSync()},getItem:e=>uni.getStorageSync(e),setItem:(e,t)=>uni.setStorageSync(e,t),removeItem:e=>uni.removeStorageSync(e)};function formatDateToYYYYMMDD(e){var t=e.getFullYear(),o=e.getMonth()+1,r=e.getDate();return`${t}${o<10?`0${o}`:String(o)}${r<10?`0${r}`:String(r)}`}class LogStorageForAppImpl{constructor(e){this.fileSystem=null,this.dirEntry=null,this.currentLogFile=null,this.isInitialized=!1,this.dirPath="",this.filePath="",this.logRetentionDays=10,this.totalLogSize=209715200,this.maxSingleLogFileSize=10485760,this.lastErrorMsg=void 0,this.logFiles=[],e.logRetentionDays>=1&&e.logRetentionDays<=30&&(this.logRetentionDays=e.logRetentionDays),e.totalLogSizeInMB>=10&&e.totalLogSizeInMB<=500&&(this.totalLogSize=1024*e.totalLogSizeInMB*1024),e.maxLogFileSizeInMB>=1&&e.maxLogFileSizeInMB<=200&&(this.maxSingleLogFileSize=1024*e.maxLogFileSizeInMB*1024),this.dirPath=e.logDirPath||"nim_logs",this.dirPath.endsWith("/")||(this.dirPath+="/");var t=formatDateToYYYYMMDD(new Date);this.filePath=`${this.dirPath}${t}.log`}isPlusAvailable(){return"undefined"!=typeof plus&&void 0!==plus.io&&"function"==typeof plus.io.requestFileSystem}getFileEntry(e,t={}){return new Promise(((o,r)=>{this.dirEntry?this.dirEntry.getFile(e,t,(e=>{o(e)}),(e=>{r(e)})):r(new Error("LogStorage::No directory entry available"))}))}deleteFile(e){return new Promise(((t,o)=>{e.remove((()=>{t()}),(e=>{o(e)}))}))}deleteFileByName(e){return __awaiter(this,void 0,void 0,(function*(){var t=yield this.getFileEntry(e);yield this.deleteFile(t)}))}getFileSize(e){return new Promise(((t,o)=>{e.file((e=>{t(e.size||0)}),(e=>{o(e)}))}))}writeFile(e,t){return new Promise(((o,r)=>{e.createWriter((e=>{e.onwrite=()=>{o()},e.onerror=e=>{r(e)},e.write(t)}),(e=>{r(e)}))}))}appendFile(e,t){return new Promise(((o,r)=>{e.createWriter((e=>{e.onwrite=()=>{o()},e.onerror=e=>{r(e)},e.seek(e.length||0),e.write(t)}),(e=>{r(e)}))}))}getDirectory(e,t={}){var o=getLogger();return new Promise(((r,i)=>{this.fileSystem&&this.fileSystem.root?this.fileSystem.root.getDirectory(e,t,(e=>{r(e)}),(t=>{o.warn(`LogStorage::getDirectory failed: ${e}; ${t&&t.message}`),i(t)})):i(new Error("LogStorage::File system not initialized"))}))}initializeFileSystem(){return __awaiter(this,void 0,void 0,(function*(){var e=getLogger();if(!this.isPlusAvailable())return e.error("LogStorage::plus.io API unavailable"),Promise.reject(new Error("LogStorage::plus.io API unavailable"));try{this.fileSystem=yield new Promise(((t,o)=>{plus.io.requestFileSystem(plus.io.PRIVATE_DOC,(e=>{e.root?t(e):o(new Error("LogStorage::fs.root empty"))}),(t=>{e.error(`LogStorage::requestFileSystem failed;${t&&t.message}`),o(t)}))})),e.log("LogStorage::requestFileSystemOk"),this.dirEntry=yield this.getDirectory(this.dirPath,{create:!0}),e.log("LogStorage::initDirectoryOk"),this.isInitialized=!0}catch(t){return e.error(`LogStorage:initFailed;${t&&t.message}`),Promise.reject(t)}}))}collectFileInfo(e){var t=this,o=getLogger();this.logFiles=[];var r=[],_loop=function(){var e=i,n=e.name;if(!n)return 0;if(!n.endsWith(".log")&&!/\.log\.\d+$/.test(n))return 0;var s=t.getFileSize(e).then((o=>{t.logFiles.push({fileName:n,size:o,fullPath:e.fullPath})})).catch((e=>{o.warn(`LogStorage::collectFileInfo:getFileFailed;${n};${e&&e.message}`)}));r.push(s)};for(var i of e)_loop();return Promise.all(r)}sortLogFiles(){this.logFiles.sort(((e,t)=>{var[o,r,i]=e.fileName.split("."),[n,s,a]=t.fileName.split(".");return o!==n?parseInt(n)-parseInt(o):i&&!a?1:!i&&a?-1:i&&a?parseInt(a)-parseInt(i):0}))}listLogFiles(){var e=getLogger();return this.isInitialized&&this.dirEntry?new Promise(((t,o)=>{this.dirEntry?this.dirEntry.createReader().readEntries((r=>{var i=r;i=i.filter((e=>e.isFile)),this.collectFileInfo(i).then((()=>{this.sortLogFiles(),e.log(`LogStorage::collectFileInfoOk,numbers of files is ${this.logFiles.length}`),t()})).catch((t=>{e.warn(`LogStorage::collectFileInfoFailed;${t&&t.message}`),o(t)}))}),(t=>{e.error(`LogStorage::readEntriesFailed;${t&&t.message}`),o(t)})):o(new Error("LogStorage::dirEntryEmpty"))})):Promise.reject(new Error("LogStorage::uninitialized"))}openCurrentLogFile(){return __awaiter(this,void 0,void 0,(function*(){var e=getLogger(),t=`${formatDateToYYYYMMDD(new Date)}.log`;return this.filePath=`${this.dirPath}${t}`,new Promise(((o,r)=>{if(!this.isInitialized||!this.dirEntry)return r(new Error("LogStorage::uninitialized"));this.dirEntry.getFile(t,{create:!0},(e=>{this.currentLogFile=e,o()}),(t=>{e.error(`LogStorage::openCurrentLogFileFailed:${this.filePath};${t&&t.message}`),r(t)}))}))}))}checkRetentionDays(){return __awaiter(this,void 0,void 0,(function*(){var e=getLogger(),t=new Date,o=this.logRetentionDays,r=new Date(t);r.setDate(t.getDate()-o);var i=+formatDateToYYYYMMDD(r);e.log(`LogStorage:checkRetentionDays;expiryDate:${i}`);var n=[];for(var s of this.logFiles){var a=s.fileName,[c]=a.split(".");if(parseInt(c)<i){e.log(`LogStorage::checkRetentionDays expireFile:${a}`);try{yield this.deleteFileByName(a)}catch(t){e.warn(`LogStorage:checkRetentionDays deleteFailed:${a};${t&&t.message}`)}}else n.push(s)}this.logFiles=n}))}checkTotalLogSize(){return __awaiter(this,void 0,void 0,(function*(){var e=getLogger(),t=this.logFiles.reduce(((e,t)=>e+t.size),0);if(t>this.totalLogSize)for(e.warn(`LogStorage::checkTotalLogSize:overlimit.totalSize(${t}B),limit(${this.totalLogSize}B)`);this.logFiles.length>1&&this.logFiles.reduce(((e,t)=>e+t.size),0)>this.totalLogSize;){var o=this.logFiles[this.logFiles.length-1];if(!o)break;try{yield this.deleteFileByName(o.fileName),this.logFiles.pop(),e.log(`LogStorage::deleteFileOk:${o.fileName}`)}catch(t){e.warn(`LogStorage::deleteFileFailed:${o.fileName};${t&&t.message}`);break}}}))}checkCurrentFileSize(){return __awaiter(this,void 0,void 0,(function*(){var e=getLogger();if(this.currentLogFile)try{var t=yield this.getFileSize(this.currentLogFile);this.logFiles.length>0&&(this.logFiles[0].size=t),t>this.maxSingleLogFileSize&&(e.log(`LogStorage::checkCurrentFileSizeOk:needArchive.currenFileSize(${t}B),limit(${this.maxSingleLogFileSize}B)`),yield this.archiveLog())}catch(t){e.warn(`LogStorage::checkCurrentFileSizeFailed;${t&&t.message}`)}}))}copyFile(e,t,o){return new Promise(((r,i)=>{e.copyTo(t,o,(e=>{r(e)}),(e=>{i(e)}))}))}archiveLog(){return __awaiter(this,void 0,void 0,(function*(){var e=getLogger();if(this.currentLogFile&&this.dirEntry){var t=formatDateToYYYYMMDD(new Date),o=0;for(var r of this.logFiles){var i=r.fileName.split(".");if(i[0]===t&&i.length>=3&&"log"===i[1]){var n=parseInt(i[2],10);!isNaN(n)&&n>o&&(o=n)}}var s=`${t}.log.${o+1}`,[a,c]=yield to(this.copyFile(this.currentLogFile,this.dirEntry,s));if(a||void 0===c)e.error(`LogStorage::archiveLog:copyFailed;${a&&a.message}`);else{var[l,_]=yield to(this.getFileSize(c));if(l||void 0===_)e.error(`LogStorage::archiveLog:getFileSizeFailed;${l&&l.message}`);else{this.logFiles.splice(1,0,{fileName:s,size:_,fullPath:c.fullPath});var[d]=yield to(this.writeFile(this.currentLogFile,"==="));d?e.error(`LogStorage::archiveLog:writeFileFailed;${d&&d.message}`):(this.logFiles.length>0&&(this.logFiles[0].size=3),e.log(`LogStorage::archiveLogOk:${s}`),yield this.checkTotalLogSize())}}}}))}open(){return __awaiter(this,void 0,void 0,(function*(){var e=getLogger();e.log("LogStorage::opening");try{this.isInitialized||(yield this.initializeFileSystem()),yield this.listLogFiles(),yield this.openCurrentLogFile(),yield this.checkRetentionDays(),yield this.checkCurrentFileSize(),yield this.checkTotalLogSize(),e.log("LogStorage::openOK")}catch(t){e.error(`LogStorage:openFailed;${t&&t.message}`)}}))}close(){}addLogs(e){return __awaiter(this,void 0,void 0,(function*(){var t=getLogger();if(this.isInitialized&&this.currentLogFile){var o=e.map((e=>e.text)).concat("").join("\n"),[r]=yield to(this.appendFile(this.currentLogFile,o));if(r){var i=r.message;return this.lastErrorMsg!==i&&t.warn(`LogStorage::addLogFailed:${i}`),void(this.lastErrorMsg=i)}this.logFiles.length>0&&(this.logFiles[0].size+=o.length),this.lastErrorMsg=void 0,yield this.checkCurrentFileSize(),yield this.checkTotalLogSize()}}))}isZipAvailable(){return"undefined"!=typeof plus&&void 0!==plus.zip&&"function"==typeof plus.zip.compress}compressToZip(e,t){return new Promise(((o,r)=>{this.isZipAvailable()?plus.zip.compress(e,t,(()=>{o(t)}),(e=>{r(e)})):r(new Error("LogStorage:plus.zip API unavailable"))}))}extractLogs(){return __awaiter(this,void 0,void 0,(function*(){var e=getLogger();if(this.isInitialized&&this.currentLogFile&&this.dirEntry)if(this.isZipAvailable())if(0!==this.logFiles.length){var t=this.dirEntry.fullPath;if(t){var o="_nim_logs.zip",r=t+o;e.warn(`LogStorage::ready to extract;${t};${r}`);var[i]=yield to(this.deleteFileByName(o));i&&e.warn(`LogStorage::extractLog:deleteTempZipFileFailed;${i&&i.message}`);var[n]=yield to(this.compressToZip(t,r));if(n)throw e.error(`LogStorage::compressToZipFailed:${n&&n.message}`),n;return e.log(`LogStorage::compressToZipOk:${r}`),r}e.warn("LogStorage::fullPath not exist")}else e.warn("LogStorage::no log files to extract");else e.error("LogStorage::LogStorage:plus.zip API unavailable")}))}afterUpload(){return __awaiter(this,void 0,void 0,(function*(){var e=getLogger(),[t]=yield to(this.deleteFileByName("_nim_logs.zip"));t?e.warn(`LogStorage::afterUpload:deleteTempZipFileFailed;${t&&t.message}`):e.log("LogStorage::afterUpload:deleteTempZipFileOk")}))}clearAllFile(){return __awaiter(this,void 0,void 0,(function*(){var e=getLogger();try{for(var t of this.logFiles)yield this.deleteFileByName(t.fileName)}catch(t){e.warn(`LogStorage:clearFailed;${t&&t.message}`)}e.log("LogStorage:clearAllOk")}))}}class LogStorageForMiniAppImpl{constructor(e){this.dirPath="",this.filePath="",this.copyFilePath="",this.enable=!1,this.maxCapacity=26214400,this.remainCapacity=8388608,this.count=0,this.maxCount=100,this.lastErrorMsg=void 0;var t=uni.getSystemInfoSync(),o="mp-weixin"===t.uniPlatform||"mp-alipay"===t.uniPlatform;if(this.enable=o,o){var r=this.getAPIEnv();r&&(this.dirPath=`${r.env.USER_DATA_PATH}/__nim`,this.filePath=`${this.dirPath}/${e.logDirPath}.log`,this.copyFilePath=`${this.dirPath}/${e.logDirPath}_copy.log`)}}getAPIEnv(){if(!("undefined"!=typeof tt&&tt.getSystemInfoSync||"undefined"!=typeof swan&&swan.getSystemInfoSync))return"undefined"!=typeof my&&my.getSystemInfoSync?my:"undefined"!=typeof wx&&wx.getAppBaseInfo?wx:void 0}makeDir(){if(this.enable){var e=this.getAPIEnv();if(e){var t=getLogger(),o=e.getFileSystemManager();try{var r=o.accessSync(this.dirPath);t.log("logStorage::access dir:",r),("object"==typeof r&&null!==r?r.error||r.errno||r.errCode||r.errNo:0)>200&&o.mkdirSync(this.dirPath,!0)}catch(e){o.mkdirSync(this.dirPath,!0)}try{var i=o.accessSync(this.filePath);t.log("logStorage::access file:",i),("object"==typeof i&&null!==i?i.error||i.errno||i.errCode||i.errNo:0)>200&&o.writeFileSync(this.filePath,"===","utf8")}catch(e){o.writeFileSync(this.filePath,"===","utf8")}}}}open(){return __awaiter(this,void 0,void 0,(function*(){if(this.enable){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*(){if(this.enable){var t=this.getAPIEnv();if(t){var o=getLogger(),r=t.getFileSystemManager(),i=this.getSize();if(i>this.maxCapacity){o.log(`logStorage::checksize:exceed,${i} byte`);var n="";try{n=yield this.readLogs(i-e)}catch(e){return void o.log("logStorage::checkCapacity:read failed",e)}o.log(`logStorage::checksize:read success ${i-e} byte`);try{r.unlinkSync(this.filePath)}catch(e){return void o.log("logStorage::checkCapacity:unlink failed",e)}try{r.writeFileSync(this.filePath,n,"utf8")}catch(e){return void o.log("logStorage::checkCapacity:write failed",e)}}else o.log(`logStorage::checkCapacity:not exceeding,${i} byte`)}}}))}getSize(){var e;if(!this.enable)return 0;var t=this.getAPIEnv();if(!t)return 0;var o,r=getLogger(),i=t.getFileSystemManager();try{o=i.statSync(this.filePath,!1)}catch(e){return r.warn("logStorage::stat failed",e),0}return o.size||(null===(e=o.stats)||void 0===e?void 0:e.size)}readLogs(e=0){if(!this.enable)return Promise.resolve("");var t=this.getAPIEnv();if(!t)return Promise.resolve("");var o=getLogger(),r=t.getFileSystemManager();return new Promise(((t,i)=>{r.readFile({filePath:this.filePath,encoding:"utf8",position:e,success:e=>{var r=e.data;"string"==typeof r?(o.warn(`logStorage::readLogs success ${r.length}`),t(r)):(o.warn("logStorage::readLogs empty"),i(new Error("logStorage::readLogs empty")))},fail:e=>{var t=e.errMsg||e.errorMessage||e.message;o.warn(`logStorage::readLogs failed ${t}`);var r={code:e.errCode||0,message:t};i(r)}})}))}close(){}addLogs(e){if(!this.enable)return Promise.resolve();var t=this.getAPIEnv();if(!t)return Promise.resolve();var o=getLogger(),r=e.map((e=>e.text)).concat("").join("\n");try{t.getFileSystemManager().appendFileSync(this.filePath,r,"utf8")}catch(e){var i=e.errMsg||e.errorMessage||e.message;this.lastErrorMsg!==i&&o.warn("logStorage::append failed",e),this.lastErrorMsg=i}return this.count+=1,this.count>this.maxCount&&(this.count=0,this.checkCapacity(this.remainCapacity)),Promise.resolve()}extractLogs(){return __awaiter(this,void 0,void 0,(function*(){if(this.enable){var e=this.getAPIEnv();if(e){var t=getLogger(),o=e.getFileSystemManager();if(this.getSize()>0){try{o.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*(){if(this.enable){var e=this.getAPIEnv();if(e){var t=getLogger(),o=e.getFileSystemManager();try{o.unlinkSync(this.copyFilePath)}catch(e){return void t.log("logStorage::delete copyFilePath failed",e)}}}}))}}var Qe={wifi:2,"2g":3,"3g":4,"4g":5,"5g":6,ethernet:1,unknown:0,none:0,notreachable:0,wwan:0},Xe={__onNetworkStatusChangeFn:null,getNetworkStatus(){var e=uni.getSystemInfoSync()||{};return"app"===e.uniPlatform&&"harmonyos"===e.osName?Promise.resolve({net_type:0,net_connect:!0}):new Promise(((e,t)=>{uni.getNetworkType({success:function(t){var o=!1;o="boolean"==typeof t.networkAvailable?t.networkAvailable:"none"!==t.networkType.toLowerCase(),e({net_type:Qe[t.networkType.toLowerCase()],net_connect:o})},fail:function(){t(new Error("getNetworkType failed"))}})}))},onNetworkStatusChange(e){this.offNetworkStatusChange(),uni.onNetworkStatusChange&&(this.__onNetworkStatusChangeFn=function(t){var o=t.networkType.toLowerCase();e({isConnected:t.isConnected||"none"!==o,networkType:Qe[o]})},uni.onNetworkStatusChange(this.__onNetworkStatusChangeFn))},offNetworkStatusChange(){uni.offNetworkStatusChange&&(this.__onNetworkStatusChangeFn&&uni.offNetworkStatusChange(this.__onNetworkStatusChangeFn),this.__onNetworkStatusChangeFn=null)}},Ze=getLogger();class PowerMonitor extends e{constructor(){super(),this.status=0,this.appShowListener=null,this.appHideListener=null,this.flag=!1,this._initAppLifecycleListener()}isActive(){return 0===this.status}getStatus(){return this.status}setStatus(e){var t=this.status;e!==t&&(this.status=e,0===e&&1===t&&this.emit("onPowerMonitorTurnActive"),Ze.log("Adapter powerMonitor::setStatus: ",e))}destroy(){this.status=0,this.flag=!1,this._canIUse()&&(this.appShowListener&&(uni.offAppShow(this.appShowListener),this.appShowListener=null),this.appHideListener&&(uni.offAppHide(this.appHideListener),this.appHideListener=null))}_initAppLifecycleListener(){this.flag||(!1!==this._canIUse()?(this.appShowListener=()=>{var e=this.status;this.status=0,1===e&&this.emit("onPowerMonitorTurnActive"),Ze.log("Adapter powerMonitor::onAppShow status:",this.status)},this.appHideListener=()=>{this.status=1,Ze.log("Adapter powerMonitor::onAppHide status:",this.status)},uni.onAppShow(this.appShowListener),uni.onAppHide(this.appHideListener),this.flag=!0,Ze.log("Adapter powerMonitor::_initAppLifecycleListener success")):Ze.warn("Adapter powerMonitor::_initAppLifecycleListener env.onAppShow/env.onAppHide not available"))}_canIUse(){return"undefined"!=typeof uni&&"function"==typeof uni.onAppShow&&"function"==typeof uni.onAppHide&&"function"==typeof uni.offAppShow&&"function"==typeof uni.offAppHide}}function requestFn(e,t){return t&&(t.data=t.data||(null==t?void 0:t.params)||{}),new Promise(((o,r)=>{uni.request(Object.assign(Object.assign({method:"GET",url:e},t),{success:function(t){"number"==typeof(t=t||{}).statusCode&&t.statusCode.toString().startsWith("2")?(t={data:t.data,status:t.statusCode,errMsg:t.errMsg,header:t.header},o(t)):r({code:t.statusCode||0,message:t.data||`uniApp request fail. url: ${e}`})},fail:function(t){var o=`uniApp request fail. url: ${e}`;r(t?{code:t.errCode||0,message:t.errMsg||o}:{code:0,message:o})}}))}))}var getUserAgent=function(){var e=uni.getSystemInfoSync()||{};if("mp-weixin"===e.uniPlatform&&"undefined"!=typeof wx&&wx.getAppBaseInfo){var t=wx.getAppBaseInfo();return`NIM/Web/UNIAPP(${e.uniRuntimeVersion})/WeChatMiniApp(${t.SDKVersion})/V10.9.71/{{appkey}}`}if("undefined"!=typeof tt&&tt.getSystemInfoSync){var o=tt.getSystemInfoSync();return`NIM/Web/UNIAPP(${e.uniRuntimeVersion})/TiktokMiniApp(${o.SDKVersion})/V10.9.71/{{appkey}}`}if("undefined"!=typeof swan&&swan.getSystemInfoSync){var r=swan.getSystemInfoSync();return`NIM/Web/UNIAPP(${e.uniRuntimeVersion})/BaiduMiniApp(${r.SDKVersion})/V10.9.71/{{appkey}}`}if("undefined"!=typeof my&&my.getSystemInfoSync){var i=my.getSystemInfoSync();return`NIM/Web/UNIAPP(${e.uniRuntimeVersion})/AliMiniApp(${i.SDKVersion})/V10.9.71/{{appkey}}`}if(navigator&&navigator.userAgent)return navigator.userAgent;if(e.ua)return e.ua;var n=uni.getSystemInfoSync();return`NIM/Web/UNIAPP(${n.uniRuntimeVersion})/${n.osName}(${n.osVersion})/V10.9.71/{{appkey}}`},getHostEnvVer=function(){var e=uni.getSystemInfoSync()||{};if("mp-weixin"===e.uniPlatform&&"undefined"!=typeof wx&&wx.getAppBaseInfo){var t=wx.getAppBaseInfo();return`${e.uniRuntimeVersion}/${t.version}`}if("undefined"!=typeof tt&&tt.getSystemInfoSync){var o=tt.getSystemInfoSync();return`${e.uniRuntimeVersion}/${o.version}`}if("undefined"!=typeof swan&&swan.getSystemInfoSync){var r=swan.getSystemInfoSync();return`${e.uniRuntimeVersion}/${r.version}`}if("undefined"!=typeof my&&my.getSystemInfoSync){var i=my.getSystemInfoSync();return`${e.uniRuntimeVersion}/${i.version}`}return`${e.uniRuntimeVersion}`},getModel=function(){var e=uni.getSystemInfoSync()||{};if("mp-weixin"===e.uniPlatform&&"undefined"!=typeof wx&&wx.getAppBaseInfo){var t=wx.getAppBaseInfo();return`${e.uniRuntimeVersion}/${t.SDKVersion}`}if("undefined"!=typeof tt&&tt.getSystemInfoSync){var o=tt.getSystemInfoSync();return`${e.uniRuntimeVersion}/${o.SDKVersion}`}if("undefined"!=typeof swan&&swan.getSystemInfoSync){var r=swan.getSystemInfoSync();return`${e.uniRuntimeVersion}/${r.SDKVersion}`}return"undefined"!=typeof my&&my.getSystemInfoSync?(my.getSystemInfoSync(),`${e.uniRuntimeVersion}/${my.SDKVersion}`):`${e.uniRuntimeVersion}`};function getSystemInfoFn(){var e,t="app"===(e=(uni.getSystemInfoSync()||{}).uniPlatform)?[110,"APP"]:"web"===e||"h5"===e?[101,"H5"]:"mp-weixin"===e?[6,"WeiXin"]:"mp-alipay"===e?[102,"Ali"]:"mp-baidu"===e?[103,"Baidu"]:"mp-toutiao"===e?[104,"Tiktok"]:0===e.indexOf("mp-")||0===e.indexOf("quickapp")?[105,"OtherMiniProgram"]:[0,"Unset"],o=uni.getSystemInfoSync()||{};return{os:o.osName||"UNIAPP_UNKNOW",osVer:o.osVersion,browser:o.browserName||"",browserVer:o.browserVersion||"",libEnv:"UNIAPP",hostEnv:t[1],hostEnvEnum:t[0],hostEnvVer:getHostEnvVer(),userAgent:getUserAgent(),model:getModel(),manufactor:t[1],pushDeviceInfo:{PRODUCT:o.model,DEVICE:o.model,MANUFACTURER:o.brand}}}function uploadFileFn(e){var t=getLogger(),o=e.headers||{};return e.md5&&(o["Content-MD5"]=e.md5),new Promise(((r,i)=>{var n=uni.uploadFile(Object.assign(Object.assign({url:`${e.commonUploadHost}/${e.nosToken.bucket}`},Object.keys(o).length>0?{header:o}:{}),{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 n={};if("string"==typeof t.data)try{n=JSON.parse(t.data)}catch(o){e.onUploadInfo&&e.onUploadInfo({exception:`JSON parse error:${t.data}`}),i({code:t.statusCode,message:t.errMsg,rawData:t.data})}n.name=e.filePath,n.ext=n.name&&n.name.lastIndexOf(".")>-1?n.name.slice(n.name.lastIndexOf(".")+1).toLowerCase():"",r(n)}else e.onUploadInfo&&e.onUploadInfo({http_code:t.statusCode,exception:t.data,rsp_headers:t.header,req_headers:o}),i({code:t.statusCode,message:t.errMsg,rawData:t.data})},fail(t){e.onUploadInfo&&e.onUploadInfo({http_code:0,exception:t,req_headers:o}),"string"==typeof t.errMsg&&t.errMsg.indexOf("abort")>-1&&(t.code=_e.V2NIM_ERROR_CODE_CANCELLED),t.message=t.errMsg,i(t)}}));try{e.onUploadStart&&e.onUploadStart(n)}catch(e){t.error("Adapter uploadFile: options.onUploadStart error",e&&e.message),n.abort(),i(e)}e.onUploadProgress&&n.onProgressUpdate((function(t){var o=t.totalBytesExpectedToWrite||t.totalBytesExpectedToSend,r=t.totalBytesWritten||t.totalBytesSent;e.onUploadProgress&&e.onUploadProgress({total:o,loaded:r,percentage:parseFloat((r/o).toFixed(2)),percentageText:t.progress+"%"})}))}))}function getFileUploadInformationFn(e){return null}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("Adapter uniapp: sockets on close ",e)},this.onerror=function(e){getLogger().error("Adapter uniapp: 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 o=this.protocol?{protocols:this.protocol}:{};this.socketTask=uni.connectSocket(Object.assign(Object.assign({url:this.url},o),{multiple:!0,fail:e=>{this.errorHandler(e)}})),this.socketTask.onOpen((e=>{getLogger().log("Adapter uniapp:: onOpen. event: ",e),this.readyState=this.OPEN,this.binaryType?this.onopen():this.onmessage&&this.onmessage({type:"open",header:e})})),this.socketTask.onError((e=>{getLogger().log("Adapter uniapp:: onError. event: ",e),this.errorHandler(e)})),this.socketTask.onClose((e=>{(this.readyState=this.CLOSED,"function"==typeof this.onclose)&&(this.onclose&&this.onclose(e),getLogger().log("Adapter uniapp:: onClose. event: ",e));this.socketTask=null})),this.socketTask.onMessage((e=>{var t;t="string"==typeof e.data||e.data instanceof ArrayBuffer?e.data:e.data.isBuffer&&"string"==typeof e.data.data?base64ToArrayBuffer(e.data.data):e.data.data,this.onmessage&&this.onmessage({data:t})}))}close(){getLogger().log("Adapter uniapp:: close uni socket actively"),this.socketTask.close({code:1e3,reason:"user force close websocket",complete:()=>{this.socketTask=null}})}send(e){if(this.readyState!==this.OPEN)throw new Error(`Adapter uniapp:: socket sendMsg when readyState=${this.readyState}`);if(!("string"==typeof e||e instanceof ArrayBuffer))throw new TypeError("Adapter uniapp:: socket sendMsg only String/ArrayBuffer supported");this.socketTask.send({data:e})}errorHandler(e){getLogger().error("Adapter uniapp:: errorHandler. event: ",e),this.readyState=this.CLOSED,this.onerror&&this.onerror({type:"error",message:e&&e.errMsg}),e.errMsg&&"[object Array]"===Object.prototype.toString.call(e.errMsg)&&(e.errMsg.indexOf("断裂管道")>0||e.errMsg.indexOf("broken pipe")>0)&&this.onclose&&this.onclose(e)}}return function setAdapters(e){merge(ae,e())}((()=>{var e=uni.getSystemInfoSync()||{},t="app"===e.uniPlatform,o="mp-weixin"===e.uniPlatform;return Object.assign({setLogger:setLogger,platform:"UNIAPP",localStorage:Je,request:requestFn,WebSocket:WebsocketFn,uploadFile:uploadFileFn,getFileUploadInformation:getFileUploadInformationFn,getSystemInfo:getSystemInfoFn,net:Xe,powerMonitor:new PowerMonitor},t?{logStorage:LogStorageForAppImpl}:o?{logStorage:LogStorageForMiniAppImpl}:{})})),Chatroom}));