joytalk 0.0.37 → 0.0.39
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs.js +6 -6
- package/dist/index.es.js +483 -479
- package/dist/index.umd.js +6 -6
- package/dist/utils/index.d.ts +1 -0
- package/package.json +1 -1
package/dist/index.cjs.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});function ot(e,t){return function(){return e.apply(t,arguments)}}const{toString:Dt}=Object.prototype,{getPrototypeOf:Ie}=Object,{iterator:Ee,toStringTag:it}=Symbol,Se=(e=>t=>{const n=Dt.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),x=e=>(e=e.toLowerCase(),t=>Se(t)===e),Te=e=>t=>typeof t===e,{isArray:Q}=Array,Y=Te("undefined");function ne(e){return e!==null&&!Y(e)&&e.constructor!==null&&!Y(e.constructor)&&_(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const at=x("ArrayBuffer");function It(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&at(e.buffer),t}const Lt=Te("string"),_=Te("function"),ct=Te("number"),re=e=>e!==null&&typeof e=="object",Ft=e=>e===!0||e===!1,ue=e=>{if(Se(e)!=="object")return!1;const t=Ie(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(it in e)&&!(Ee in e)},Pt=e=>{if(!re(e)||ne(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},xt=x("Date"),Bt=x("File"),kt=x("Blob"),Ht=x("FileList"),vt=e=>re(e)&&_(e.pipe),jt=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||_(e.append)&&((t=Se(e))==="formdata"||t==="object"&&_(e.toString)&&e.toString()==="[object FormData]"))},Mt=x("URLSearchParams"),[$t,qt,Gt,zt]=["ReadableStream","Request","Response","Headers"].map(x),Jt=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function se(e,t,{allOwnKeys:n=!1}={}){if(e===null||typeof e>"u")return;let r,s;if(typeof e!="object"&&(e=[e]),Q(e))for(r=0,s=e.length;r<s;r++)t.call(null,e[r],r,e);else{if(ne(e))return;const o=n?Object.getOwnPropertyNames(e):Object.keys(e),i=o.length;let c;for(r=0;r<i;r++)c=o[r],t.call(null,e[c],c,e)}}function lt(e,t){if(ne(e))return null;t=t.toLowerCase();const n=Object.keys(e);let r=n.length,s;for(;r-- >0;)if(s=n[r],t===s.toLowerCase())return s;return null}const J=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,ut=e=>!Y(e)&&e!==J;function ge(){const{caseless:e,skipUndefined:t}=ut(this)&&this||{},n={},r=(s,o)=>{const i=e&<(n,o)||o;ue(n[i])&&ue(s)?n[i]=ge(n[i],s):ue(s)?n[i]=ge({},s):Q(s)?n[i]=s.slice():(!t||!Y(s))&&(n[i]=s)};for(let s=0,o=arguments.length;s<o;s++)arguments[s]&&se(arguments[s],r);return n}const Wt=(e,t,n,{allOwnKeys:r}={})=>(se(t,(s,o)=>{n&&_(s)?e[o]=ot(s,n):e[o]=s},{allOwnKeys:r}),e),Vt=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),Kt=(e,t,n,r)=>{e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},Xt=(e,t,n,r)=>{let s,o,i;const c={};if(t=t||{},e==null)return t;do{for(s=Object.getOwnPropertyNames(e),o=s.length;o-- >0;)i=s[o],(!r||r(i,e,t))&&!c[i]&&(t[i]=e[i],c[i]=!0);e=n!==!1&&Ie(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},Yt=(e,t,n)=>{e=String(e),(n===void 0||n>e.length)&&(n=e.length),n-=t.length;const r=e.indexOf(t,n);return r!==-1&&r===n},Qt=e=>{if(!e)return null;if(Q(e))return e;let t=e.length;if(!ct(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},Zt=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&Ie(Uint8Array)),en=(e,t)=>{const r=(e&&e[Ee]).call(e);let s;for(;(s=r.next())&&!s.done;){const o=s.value;t.call(e,o[0],o[1])}},tn=(e,t)=>{let n;const r=[];for(;(n=e.exec(t))!==null;)r.push(n);return r},nn=x("HTMLFormElement"),rn=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,s){return r.toUpperCase()+s}),$e=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),sn=x("RegExp"),ft=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),r={};se(n,(s,o)=>{let i;(i=t(s,o,e))!==!1&&(r[o]=i||s)}),Object.defineProperties(e,r)},on=e=>{ft(e,(t,n)=>{if(_(e)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=e[n];if(_(r)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},an=(e,t)=>{const n={},r=s=>{s.forEach(o=>{n[o]=!0})};return Q(e)?r(e):r(String(e).split(t)),n},cn=()=>{},ln=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function un(e){return!!(e&&_(e.append)&&e[it]==="FormData"&&e[Ee])}const fn=e=>{const t=new Array(10),n=(r,s)=>{if(re(r)){if(t.indexOf(r)>=0)return;if(ne(r))return r;if(!("toJSON"in r)){t[s]=r;const o=Q(r)?[]:{};return se(r,(i,c)=>{const d=n(i,s+1);!Y(d)&&(o[c]=d)}),t[s]=void 0,o}}return r};return n(e,0)},dn=x("AsyncFunction"),hn=e=>e&&(re(e)||_(e))&&_(e.then)&&_(e.catch),dt=((e,t)=>e?setImmediate:t?((n,r)=>(J.addEventListener("message",({source:s,data:o})=>{s===J&&o===n&&r.length&&r.shift()()},!1),s=>{r.push(s),J.postMessage(n,"*")}))(`axios@${Math.random()}`,[]):n=>setTimeout(n))(typeof setImmediate=="function",_(J.postMessage)),pn=typeof queueMicrotask<"u"?queueMicrotask.bind(J):typeof process<"u"&&process.nextTick||dt,mn=e=>e!=null&&_(e[Ee]),a={isArray:Q,isArrayBuffer:at,isBuffer:ne,isFormData:jt,isArrayBufferView:It,isString:Lt,isNumber:ct,isBoolean:Ft,isObject:re,isPlainObject:ue,isEmptyObject:Pt,isReadableStream:$t,isRequest:qt,isResponse:Gt,isHeaders:zt,isUndefined:Y,isDate:xt,isFile:Bt,isBlob:kt,isRegExp:sn,isFunction:_,isStream:vt,isURLSearchParams:Mt,isTypedArray:Zt,isFileList:Ht,forEach:se,merge:ge,extend:Wt,trim:Jt,stripBOM:Vt,inherits:Kt,toFlatObject:Xt,kindOf:Se,kindOfTest:x,endsWith:Yt,toArray:Qt,forEachEntry:en,matchAll:tn,isHTMLForm:nn,hasOwnProperty:$e,hasOwnProp:$e,reduceDescriptors:ft,freezeMethods:on,toObjectSet:an,toCamelCase:rn,noop:cn,toFiniteNumber:ln,findKey:lt,global:J,isContextDefined:ut,isSpecCompliantForm:un,toJSONObject:fn,isAsyncFn:dn,isThenable:hn,setImmediate:dt,asap:pn,isIterable:mn};function E(e,t,n,r,s){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),s&&(this.response=s,this.status=s.status?s.status:null)}a.inherits(E,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:a.toJSONObject(this.config),code:this.code,status:this.status}}});const ht=E.prototype,pt={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{pt[e]={value:e}});Object.defineProperties(E,pt);Object.defineProperty(ht,"isAxiosError",{value:!0});E.from=(e,t,n,r,s,o)=>{const i=Object.create(ht);a.toFlatObject(e,i,function(l){return l!==Error.prototype},u=>u!=="isAxiosError");const c=e&&e.message?e.message:"Error",d=t==null&&e?e.code:t;return E.call(i,c,d,n,r,s),e&&i.cause==null&&Object.defineProperty(i,"cause",{value:e,configurable:!0}),i.name=e&&e.name||"Error",o&&Object.assign(i,o),i};const En=null;function Ce(e){return a.isPlainObject(e)||a.isArray(e)}function mt(e){return a.endsWith(e,"[]")?e.slice(0,-2):e}function qe(e,t,n){return e?e.concat(t).map(function(s,o){return s=mt(s),!n&&o?"["+s+"]":s}).join(n?".":""):t}function Sn(e){return a.isArray(e)&&!e.some(Ce)}const Tn=a.toFlatObject(a,{},null,function(t){return/^is[A-Z]/.test(t)});function we(e,t,n){if(!a.isObject(e))throw new TypeError("target must be an object");t=t||new FormData,n=a.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(m,p){return!a.isUndefined(p[m])});const r=n.metaTokens,s=n.visitor||l,o=n.dots,i=n.indexes,d=(n.Blob||typeof Blob<"u"&&Blob)&&a.isSpecCompliantForm(t);if(!a.isFunction(s))throw new TypeError("visitor must be a function");function u(f){if(f===null)return"";if(a.isDate(f))return f.toISOString();if(a.isBoolean(f))return f.toString();if(!d&&a.isBlob(f))throw new E("Blob is not supported. Use a Buffer instead.");return a.isArrayBuffer(f)||a.isTypedArray(f)?d&&typeof Blob=="function"?new Blob([f]):Buffer.from(f):f}function l(f,m,p){let R=f;if(f&&!p&&typeof f=="object"){if(a.endsWith(m,"{}"))m=r?m:m.slice(0,-2),f=JSON.stringify(f);else if(a.isArray(f)&&Sn(f)||(a.isFileList(f)||a.endsWith(m,"[]"))&&(R=a.toArray(f)))return m=mt(m),R.forEach(function(y,U){!(a.isUndefined(y)||y===null)&&t.append(i===!0?qe([m],U,o):i===null?m:m+"[]",u(y))}),!1}return Ce(f)?!0:(t.append(qe(p,m,o),u(f)),!1)}const h=[],S=Object.assign(Tn,{defaultVisitor:l,convertValue:u,isVisitable:Ce});function w(f,m){if(!a.isUndefined(f)){if(h.indexOf(f)!==-1)throw Error("Circular reference detected in "+m.join("."));h.push(f),a.forEach(f,function(R,I){(!(a.isUndefined(R)||R===null)&&s.call(t,R,a.isString(I)?I.trim():I,m,S))===!0&&w(R,m?m.concat(I):[I])}),h.pop()}}if(!a.isObject(e))throw new TypeError("data must be an object");return w(e),t}function Ge(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(r){return t[r]})}function Le(e,t){this._pairs=[],e&&we(e,this,t)}const Et=Le.prototype;Et.append=function(t,n){this._pairs.push([t,n])};Et.toString=function(t){const n=t?function(r){return t.call(this,r,Ge)}:Ge;return this._pairs.map(function(s){return n(s[0])+"="+n(s[1])},"").join("&")};function wn(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function St(e,t,n){if(!t)return e;const r=n&&n.encode||wn;a.isFunction(n)&&(n={serialize:n});const s=n&&n.serialize;let o;if(s?o=s(t,n):o=a.isURLSearchParams(t)?t.toString():new Le(t,n).toString(r),o){const i=e.indexOf("#");i!==-1&&(e=e.slice(0,i)),e+=(e.indexOf("?")===-1?"?":"&")+o}return e}class ze{constructor(){this.handlers=[]}use(t,n,r){return this.handlers.push({fulfilled:t,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){a.forEach(this.handlers,function(r){r!==null&&t(r)})}}const Tt={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Rn=typeof URLSearchParams<"u"?URLSearchParams:Le,yn=typeof FormData<"u"?FormData:null,An=typeof Blob<"u"?Blob:null,bn={isBrowser:!0,classes:{URLSearchParams:Rn,FormData:yn,Blob:An},protocols:["http","https","file","blob","url","data"]},Fe=typeof window<"u"&&typeof document<"u",Ue=typeof navigator=="object"&&navigator||void 0,Nn=Fe&&(!Ue||["ReactNative","NativeScript","NS"].indexOf(Ue.product)<0),On=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",gn=Fe&&window.location.href||"http://localhost",Cn=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:Fe,hasStandardBrowserEnv:Nn,hasStandardBrowserWebWorkerEnv:On,navigator:Ue,origin:gn},Symbol.toStringTag,{value:"Module"})),g={...Cn,...bn};function Un(e,t){return we(e,new g.classes.URLSearchParams,{visitor:function(n,r,s,o){return g.isNode&&a.isBuffer(n)?(this.append(r,n.toString("base64")),!1):o.defaultVisitor.apply(this,arguments)},...t})}function _n(e){return a.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function Dn(e){const t={},n=Object.keys(e);let r;const s=n.length;let o;for(r=0;r<s;r++)o=n[r],t[o]=e[o];return t}function wt(e){function t(n,r,s,o){let i=n[o++];if(i==="__proto__")return!0;const c=Number.isFinite(+i),d=o>=n.length;return i=!i&&a.isArray(s)?s.length:i,d?(a.hasOwnProp(s,i)?s[i]=[s[i],r]:s[i]=r,!c):((!s[i]||!a.isObject(s[i]))&&(s[i]=[]),t(n,r,s[i],o)&&a.isArray(s[i])&&(s[i]=Dn(s[i])),!c)}if(a.isFormData(e)&&a.isFunction(e.entries)){const n={};return a.forEachEntry(e,(r,s)=>{t(_n(r),s,n,0)}),n}return null}function In(e,t,n){if(a.isString(e))try{return(t||JSON.parse)(e),a.trim(e)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(e)}const oe={transitional:Tt,adapter:["xhr","http","fetch"],transformRequest:[function(t,n){const r=n.getContentType()||"",s=r.indexOf("application/json")>-1,o=a.isObject(t);if(o&&a.isHTMLForm(t)&&(t=new FormData(t)),a.isFormData(t))return s?JSON.stringify(wt(t)):t;if(a.isArrayBuffer(t)||a.isBuffer(t)||a.isStream(t)||a.isFile(t)||a.isBlob(t)||a.isReadableStream(t))return t;if(a.isArrayBufferView(t))return t.buffer;if(a.isURLSearchParams(t))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let c;if(o){if(r.indexOf("application/x-www-form-urlencoded")>-1)return Un(t,this.formSerializer).toString();if((c=a.isFileList(t))||r.indexOf("multipart/form-data")>-1){const d=this.env&&this.env.FormData;return we(c?{"files[]":t}:t,d&&new d,this.formSerializer)}}return o||s?(n.setContentType("application/json",!1),In(t)):t}],transformResponse:[function(t){const n=this.transitional||oe.transitional,r=n&&n.forcedJSONParsing,s=this.responseType==="json";if(a.isResponse(t)||a.isReadableStream(t))return t;if(t&&a.isString(t)&&(r&&!this.responseType||s)){const i=!(n&&n.silentJSONParsing)&&s;try{return JSON.parse(t,this.parseReviver)}catch(c){if(i)throw c.name==="SyntaxError"?E.from(c,E.ERR_BAD_RESPONSE,this,null,this.response):c}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:g.classes.FormData,Blob:g.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};a.forEach(["delete","get","head","post","put","patch"],e=>{oe.headers[e]={}});const Ln=a.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),Fn=e=>{const t={};let n,r,s;return e&&e.split(`
|
|
2
|
-
`).forEach(function(i){s=i.indexOf(":"),n=i.substring(0,s).trim().toLowerCase(),r=i.substring(s+1).trim(),!(!n||t[n]&&
|
|
3
|
-
`)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...n){const r=new this(t);return n.forEach(s=>r.set(s)),r}static accessor(t){const r=(this[Je]=this[Je]={accessors:{}}).accessors,s=this.prototype;function o(i){const c=te(i);r[c]||(kn(s,i),r[c]=!0)}return a.isArray(t)?t.forEach(o):o(t),this}};D.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);a.reduceDescriptors(D.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}});a.freezeMethods(D);function Ne(e,t){const n=this||oe,r=t||n,s=D.from(r.headers);let o=r.data;return a.forEach(e,function(c){o=c.call(n,o,s.normalize(),t?t.status:void 0)}),s.normalize(),o}function Rt(e){return!!(e&&e.__CANCEL__)}function Z(e,t,n){E.call(this,e??"canceled",E.ERR_CANCELED,t,n),this.name="CanceledError"}a.inherits(Z,E,{__CANCEL__:!0});function yt(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new E("Request failed with status code "+n.status,[E.ERR_BAD_REQUEST,E.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function Hn(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function vn(e,t){e=e||10;const n=new Array(e),r=new Array(e);let s=0,o=0,i;return t=t!==void 0?t:1e3,function(d){const u=Date.now(),l=r[o];i||(i=u),n[s]=d,r[s]=u;let h=o,S=0;for(;h!==s;)S+=n[h++],h=h%e;if(s=(s+1)%e,s===o&&(o=(o+1)%e),u-i<t)return;const w=l&&u-l;return w?Math.round(S*1e3/w):void 0}}function jn(e,t){let n=0,r=1e3/t,s,o;const i=(u,l=Date.now())=>{n=l,s=null,o&&(clearTimeout(o),o=null),e(...u)};return[(...u)=>{const l=Date.now(),h=l-n;h>=r?i(u,l):(s=u,o||(o=setTimeout(()=>{o=null,i(s)},r-h)))},()=>s&&i(s)]}const he=(e,t,n=3)=>{let r=0;const s=vn(50,250);return jn(o=>{const i=o.loaded,c=o.lengthComputable?o.total:void 0,d=i-r,u=s(d),l=i<=c;r=i;const h={loaded:i,total:c,progress:c?i/c:void 0,bytes:d,rate:u||void 0,estimated:u&&c&&l?(c-i)/u:void 0,event:o,lengthComputable:c!=null,[t?"download":"upload"]:!0};e(h)},n)},We=(e,t)=>{const n=e!=null;return[r=>t[0]({lengthComputable:n,total:e,loaded:r}),t[1]]},Ve=e=>(...t)=>a.asap(()=>e(...t)),Mn=g.hasStandardBrowserEnv?((e,t)=>n=>(n=new URL(n,g.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new URL(g.origin),g.navigator&&/(msie|trident)/i.test(g.navigator.userAgent)):()=>!0,$n=g.hasStandardBrowserEnv?{write(e,t,n,r,s,o,i){if(typeof document>"u")return;const c=[`${e}=${encodeURIComponent(t)}`];a.isNumber(n)&&c.push(`expires=${new Date(n).toUTCString()}`),a.isString(r)&&c.push(`path=${r}`),a.isString(s)&&c.push(`domain=${s}`),o===!0&&c.push("secure"),a.isString(i)&&c.push(`SameSite=${i}`),document.cookie=c.join("; ")},read(e){if(typeof document>"u")return null;const t=document.cookie.match(new RegExp("(?:^|; )"+e+"=([^;]*)"));return t?decodeURIComponent(t[1]):null},remove(e){this.write(e,"",Date.now()-864e5,"/")}}:{write(){},read(){return null},remove(){}};function qn(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function Gn(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function At(e,t,n){let r=!qn(t);return e&&(r||n==!1)?Gn(e,t):t}const Ke=e=>e instanceof D?{...e}:e;function V(e,t){t=t||{};const n={};function r(u,l,h,S){return a.isPlainObject(u)&&a.isPlainObject(l)?a.merge.call({caseless:S},u,l):a.isPlainObject(l)?a.merge({},l):a.isArray(l)?l.slice():l}function s(u,l,h,S){if(a.isUndefined(l)){if(!a.isUndefined(u))return r(void 0,u,h,S)}else return r(u,l,h,S)}function o(u,l){if(!a.isUndefined(l))return r(void 0,l)}function i(u,l){if(a.isUndefined(l)){if(!a.isUndefined(u))return r(void 0,u)}else return r(void 0,l)}function c(u,l,h){if(h in t)return r(u,l);if(h in e)return r(void 0,u)}const d={url:o,method:o,data:o,baseURL:i,transformRequest:i,transformResponse:i,paramsSerializer:i,timeout:i,timeoutMessage:i,withCredentials:i,withXSRFToken:i,adapter:i,responseType:i,xsrfCookieName:i,xsrfHeaderName:i,onUploadProgress:i,onDownloadProgress:i,decompress:i,maxContentLength:i,maxBodyLength:i,beforeRedirect:i,transport:i,httpAgent:i,httpsAgent:i,cancelToken:i,socketPath:i,responseEncoding:i,validateStatus:c,headers:(u,l,h)=>s(Ke(u),Ke(l),h,!0)};return a.forEach(Object.keys({...e,...t}),function(l){const h=d[l]||s,S=h(e[l],t[l],l);a.isUndefined(S)&&h!==c||(n[l]=S)}),n}const bt=e=>{const t=V({},e);let{data:n,withXSRFToken:r,xsrfHeaderName:s,xsrfCookieName:o,headers:i,auth:c}=t;if(t.headers=i=D.from(i),t.url=St(At(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&i.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),a.isFormData(n)){if(g.hasStandardBrowserEnv||g.hasStandardBrowserWebWorkerEnv)i.setContentType(void 0);else if(a.isFunction(n.getHeaders)){const d=n.getHeaders(),u=["content-type","content-length"];Object.entries(d).forEach(([l,h])=>{u.includes(l.toLowerCase())&&i.set(l,h)})}}if(g.hasStandardBrowserEnv&&(r&&a.isFunction(r)&&(r=r(t)),r||r!==!1&&Mn(t.url))){const d=s&&o&&$n.read(o);d&&i.set(s,d)}return t},zn=typeof XMLHttpRequest<"u",Jn=zn&&function(e){return new Promise(function(n,r){const s=bt(e);let o=s.data;const i=D.from(s.headers).normalize();let{responseType:c,onUploadProgress:d,onDownloadProgress:u}=s,l,h,S,w,f;function m(){w&&w(),f&&f(),s.cancelToken&&s.cancelToken.unsubscribe(l),s.signal&&s.signal.removeEventListener("abort",l)}let p=new XMLHttpRequest;p.open(s.method.toUpperCase(),s.url,!0),p.timeout=s.timeout;function R(){if(!p)return;const y=D.from("getAllResponseHeaders"in p&&p.getAllResponseHeaders()),P={data:!c||c==="text"||c==="json"?p.responseText:p.response,status:p.status,statusText:p.statusText,headers:y,config:e,request:p};yt(function(L){n(L),m()},function(L){r(L),m()},P),p=null}"onloadend"in p?p.onloadend=R:p.onreadystatechange=function(){!p||p.readyState!==4||p.status===0&&!(p.responseURL&&p.responseURL.indexOf("file:")===0)||setTimeout(R)},p.onabort=function(){p&&(r(new E("Request aborted",E.ECONNABORTED,e,p)),p=null)},p.onerror=function(U){const P=U&&U.message?U.message:"Network Error",G=new E(P,E.ERR_NETWORK,e,p);G.event=U||null,r(G),p=null},p.ontimeout=function(){let U=s.timeout?"timeout of "+s.timeout+"ms exceeded":"timeout exceeded";const P=s.transitional||Tt;s.timeoutErrorMessage&&(U=s.timeoutErrorMessage),r(new E(U,P.clarifyTimeoutError?E.ETIMEDOUT:E.ECONNABORTED,e,p)),p=null},o===void 0&&i.setContentType(null),"setRequestHeader"in p&&a.forEach(i.toJSON(),function(U,P){p.setRequestHeader(P,U)}),a.isUndefined(s.withCredentials)||(p.withCredentials=!!s.withCredentials),c&&c!=="json"&&(p.responseType=s.responseType),u&&([S,f]=he(u,!0),p.addEventListener("progress",S)),d&&p.upload&&([h,w]=he(d),p.upload.addEventListener("progress",h),p.upload.addEventListener("loadend",w)),(s.cancelToken||s.signal)&&(l=y=>{p&&(r(!y||y.type?new Z(null,e,p):y),p.abort(),p=null)},s.cancelToken&&s.cancelToken.subscribe(l),s.signal&&(s.signal.aborted?l():s.signal.addEventListener("abort",l)));const I=Hn(s.url);if(I&&g.protocols.indexOf(I)===-1){r(new E("Unsupported protocol "+I+":",E.ERR_BAD_REQUEST,e));return}p.send(o||null)})},Wn=(e,t)=>{const{length:n}=e=e?e.filter(Boolean):[];if(t||n){let r=new AbortController,s;const o=function(u){if(!s){s=!0,c();const l=u instanceof Error?u:this.reason;r.abort(l instanceof E?l:new Z(l instanceof Error?l.message:l))}};let i=t&&setTimeout(()=>{i=null,o(new E(`timeout ${t} of ms exceeded`,E.ETIMEDOUT))},t);const c=()=>{e&&(i&&clearTimeout(i),i=null,e.forEach(u=>{u.unsubscribe?u.unsubscribe(o):u.removeEventListener("abort",o)}),e=null)};e.forEach(u=>u.addEventListener("abort",o));const{signal:d}=r;return d.unsubscribe=()=>a.asap(c),d}},Vn=function*(e,t){let n=e.byteLength;if(n<t){yield e;return}let r=0,s;for(;r<n;)s=r+t,yield e.slice(r,s),r=s},Kn=async function*(e,t){for await(const n of Xn(e))yield*Vn(n,t)},Xn=async function*(e){if(e[Symbol.asyncIterator]){yield*e;return}const t=e.getReader();try{for(;;){const{done:n,value:r}=await t.read();if(n)break;yield r}}finally{await t.cancel()}},Xe=(e,t,n,r)=>{const s=Kn(e,t);let o=0,i,c=d=>{i||(i=!0,r&&r(d))};return new ReadableStream({async pull(d){try{const{done:u,value:l}=await s.next();if(u){c(),d.close();return}let h=l.byteLength;if(n){let S=o+=h;n(S)}d.enqueue(new Uint8Array(l))}catch(u){throw c(u),u}},cancel(d){return c(d),s.return()}},{highWaterMark:2})},Ye=64*1024,{isFunction:le}=a,Yn=(({Request:e,Response:t})=>({Request:e,Response:t}))(a.global),{ReadableStream:Qe,TextEncoder:Ze}=a.global,et=(e,...t)=>{try{return!!e(...t)}catch{return!1}},Qn=e=>{e=a.merge.call({skipUndefined:!0},Yn,e);const{fetch:t,Request:n,Response:r}=e,s=t?le(t):typeof fetch=="function",o=le(n),i=le(r);if(!s)return!1;const c=s&&le(Qe),d=s&&(typeof Ze=="function"?(f=>m=>f.encode(m))(new Ze):async f=>new Uint8Array(await new n(f).arrayBuffer())),u=o&&c&&et(()=>{let f=!1;const m=new n(g.origin,{body:new Qe,method:"POST",get duplex(){return f=!0,"half"}}).headers.has("Content-Type");return f&&!m}),l=i&&c&&et(()=>a.isReadableStream(new r("").body)),h={stream:l&&(f=>f.body)};s&&["text","arrayBuffer","blob","formData","stream"].forEach(f=>{!h[f]&&(h[f]=(m,p)=>{let R=m&&m[f];if(R)return R.call(m);throw new E(`Response type '${f}' is not supported`,E.ERR_NOT_SUPPORT,p)})});const S=async f=>{if(f==null)return 0;if(a.isBlob(f))return f.size;if(a.isSpecCompliantForm(f))return(await new n(g.origin,{method:"POST",body:f}).arrayBuffer()).byteLength;if(a.isArrayBufferView(f)||a.isArrayBuffer(f))return f.byteLength;if(a.isURLSearchParams(f)&&(f=f+""),a.isString(f))return(await d(f)).byteLength},w=async(f,m)=>{const p=a.toFiniteNumber(f.getContentLength());return p??S(m)};return async f=>{let{url:m,method:p,data:R,signal:I,cancelToken:y,timeout:U,onDownloadProgress:P,onUploadProgress:G,responseType:L,headers:ye,withCredentials:ie="same-origin",fetchOptions:Be}=bt(f),ke=t||fetch;L=L?(L+"").toLowerCase():"text";let ae=Wn([I,y&&y.toAbortSignal()],U),ee=null;const z=ae&&ae.unsubscribe&&(()=>{ae.unsubscribe()});let He;try{if(G&&u&&p!=="get"&&p!=="head"&&(He=await w(ye,R))!==0){let M=new n(m,{method:"POST",body:R,duplex:"half"}),K;if(a.isFormData(R)&&(K=M.headers.get("content-type"))&&ye.setContentType(K),M.body){const[Ae,ce]=We(He,he(Ve(G)));R=Xe(M.body,Ye,Ae,ce)}}a.isString(ie)||(ie=ie?"include":"omit");const B=o&&"credentials"in n.prototype,ve={...Be,signal:ae,method:p.toUpperCase(),headers:ye.normalize().toJSON(),body:R,duplex:"half",credentials:B?ie:void 0};ee=o&&new n(m,ve);let j=await(o?ke(ee,Be):ke(m,ve));const je=l&&(L==="stream"||L==="response");if(l&&(P||je&&z)){const M={};["status","statusText","headers"].forEach(Me=>{M[Me]=j[Me]});const K=a.toFiniteNumber(j.headers.get("content-length")),[Ae,ce]=P&&We(K,he(Ve(P),!0))||[];j=new r(Xe(j.body,Ye,Ae,()=>{ce&&ce(),z&&z()}),M)}L=L||"text";let _t=await h[a.findKey(h,L)||"text"](j,f);return!je&&z&&z(),await new Promise((M,K)=>{yt(M,K,{data:_t,headers:D.from(j.headers),status:j.status,statusText:j.statusText,config:f,request:ee})})}catch(B){throw z&&z(),B&&B.name==="TypeError"&&/Load failed|fetch/i.test(B.message)?Object.assign(new E("Network Error",E.ERR_NETWORK,f,ee),{cause:B.cause||B}):E.from(B,B&&B.code,f,ee)}}},Zn=new Map,Nt=e=>{let t=e&&e.env||{};const{fetch:n,Request:r,Response:s}=t,o=[r,s,n];let i=o.length,c=i,d,u,l=Zn;for(;c--;)d=o[c],u=l.get(d),u===void 0&&l.set(d,u=c?new Map:Qn(t)),l=u;return u};Nt();const Pe={http:En,xhr:Jn,fetch:{get:Nt}};a.forEach(Pe,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const tt=e=>`- ${e}`,er=e=>a.isFunction(e)||e===null||e===!1;function tr(e,t){e=a.isArray(e)?e:[e];const{length:n}=e;let r,s;const o={};for(let i=0;i<n;i++){r=e[i];let c;if(s=r,!er(r)&&(s=Pe[(c=String(r)).toLowerCase()],s===void 0))throw new E(`Unknown adapter '${c}'`);if(s&&(a.isFunction(s)||(s=s.get(t))))break;o[c||"#"+i]=s}if(!s){const i=Object.entries(o).map(([d,u])=>`adapter ${d} `+(u===!1?"is not supported by the environment":"is not available in the build"));let c=n?i.length>1?`since :
|
|
4
|
-
`+i.map(
|
|
5
|
-
`):" "+
|
|
6
|
-
`+o):r.stack=o}catch{}}throw r}}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=V(this.defaults,n);const{transitional:r,paramsSerializer:s,headers:o}=n;r!==void 0&&de.assertOptions(r,{silentJSONParsing:k.transitional(k.boolean),forcedJSONParsing:k.transitional(k.boolean),clarifyTimeoutError:k.transitional(k.boolean)},!1),s!=null&&(a.isFunction(s)?n.paramsSerializer={serialize:s}:de.assertOptions(s,{encode:k.function,serialize:k.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),de.assertOptions(n,{baseUrl:k.spelling("baseURL"),withXsrfToken:k.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let i=o&&a.merge(o.common,o[n.method]);o&&a.forEach(["delete","get","head","post","put","patch","common"],f=>{delete o[f]}),n.headers=D.concat(i,o);const c=[];let d=!0;this.interceptors.request.forEach(function(m){typeof m.runWhen=="function"&&m.runWhen(n)===!1||(d=d&&m.synchronous,c.unshift(m.fulfilled,m.rejected))});const u=[];this.interceptors.response.forEach(function(m){u.push(m.fulfilled,m.rejected)});let l,h=0,S;if(!d){const f=[nt.bind(this),void 0];for(f.unshift(...c),f.push(...u),S=f.length,l=Promise.resolve(n);h<S;)l=l.then(f[h++],f[h++]);return l}S=c.length;let w=n;for(;h<S;){const f=c[h++],m=c[h++];try{w=f(w)}catch(p){m.call(this,p);break}}try{l=nt.call(this,w)}catch(f){return Promise.reject(f)}for(h=0,S=u.length;h<S;)l=l.then(u[h++],u[h++]);return l}getUri(t){t=V(this.defaults,t);const n=At(t.baseURL,t.url,t.allowAbsoluteUrls);return St(n,t.params,t.paramsSerializer)}};a.forEach(["delete","get","head","options"],function(t){W.prototype[t]=function(n,r){return this.request(V(r||{},{method:t,url:n,data:(r||{}).data}))}});a.forEach(["post","put","patch"],function(t){function n(r){return function(o,i,c){return this.request(V(c||{},{method:t,headers:r?{"Content-Type":"multipart/form-data"}:{},url:o,data:i}))}}W.prototype[t]=n(),W.prototype[t+"Form"]=n(!0)});let rr=class Ct{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let n;this.promise=new Promise(function(o){n=o});const r=this;this.promise.then(s=>{if(!r._listeners)return;let o=r._listeners.length;for(;o-- >0;)r._listeners[o](s);r._listeners=null}),this.promise.then=s=>{let o;const i=new Promise(c=>{r.subscribe(c),o=c}).then(s);return i.cancel=function(){r.unsubscribe(o)},i},t(function(o,i,c){r.reason||(r.reason=new Z(o,i,c),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const t=new AbortController,n=r=>{t.abort(r)};return this.subscribe(n),t.signal.unsubscribe=()=>this.unsubscribe(n),t.signal}static source(){let t;return{token:new Ct(function(s){t=s}),cancel:t}}};function sr(e){return function(n){return e.apply(null,n)}}function or(e){return a.isObject(e)&&e.isAxiosError===!0}const _e={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(_e).forEach(([e,t])=>{_e[t]=e});function Ut(e){const t=new W(e),n=ot(W.prototype.request,t);return a.extend(n,W.prototype,t,{allOwnKeys:!0}),a.extend(n,t,null,{allOwnKeys:!0}),n.create=function(s){return Ut(V(e,s))},n}const T=Ut(oe);T.Axios=W;T.CanceledError=Z;T.CancelToken=rr;T.isCancel=Rt;T.VERSION=gt;T.toFormData=we;T.AxiosError=E;T.Cancel=T.CanceledError;T.all=function(t){return Promise.all(t)};T.spread=sr;T.isAxiosError=or;T.mergeConfig=V;T.AxiosHeaders=D;T.formToJSON=e=>wt(a.isHTMLForm(e)?new FormData(e):e);T.getAdapter=Ot.getAdapter;T.HttpStatusCode=_e;T.default=T;const{Axios:Dr,AxiosError:Ir,CanceledError:Lr,isCancel:Fr,CancelToken:Pr,VERSION:xr,all:Br,Cancel:kr,isAxiosError:Hr,spread:vr,toFormData:jr,AxiosHeaders:Mr,HttpStatusCode:$r,formToJSON:qr,getAdapter:Gr,mergeConfig:zr}=T,b={UNINITIALIZED:{code:10001,msg:"未初始化"},DISCONNECTED:{code:10002,msg:"未连接"},NO_CUSTOMER_SERVICE:{code:10003,msg:"未分配客服"},MESSAGE_SEND_FAIL:{code:10004,msg:"消息发送失败"},DATA_PARSING_ERROR:{code:10005,msg:"数据解析异常"},FILE_NOT_EXIST:{code:10006,msg:"文件不存在"},FILE_PARSING_ERROR:{code:10007,msg:"文件解析异常"},AUTH_INFO_ERROR:{code:10008,msg:"授权信息错误"},FILE_UPLOAD_FAIL:{code:10009,msg:"文件上传失败"},PARAMETER_ERROR:{code:10010,msg:"参数异常"},EMPTY_DATA:{code:10011,msg:"数据为空"}},ir="/api/customer-service/customer/v1/CustomerService/TestLineLatency",ar="/api/customer-service/customer/v1/CustomerService/ListLines",cr="/pub/logo.png",De={development:{BASE_API_URL:"http://dev-joytalk-api.halaladmin.vip",OBS_URL:"http://dev-joytalk-img.halaladmin.vip"},prodtest:{BASE_API_URL:"https://fat-joytalk-api.halaladmin.vip",OBS_URL:"https://fat-joytalk-img.halaladmin.vip"},production:{BASE_API_URL:"https://fat-joytalk-api.halaladmin.vip",OBS_URL:"https://fat-joytalk-img.halaladmin.vip"}},F={api:"",download:"",ws:""};let X=null;function lr(e){const t=`${e.replace(/\/$/,"")}${ir}`;return T.get(t,{timeout:1e4}).then(n=>n.data?.code!==200?Promise.reject(n):e)}function ur(e){const t=`${e.replace(/\/$/,"")}${cr}`;return T.get(t,{timeout:1e4}).then(()=>e).catch(()=>Promise.reject(new Error("Download latency test failed")))}function fr(e){return e?.length?Promise.any(e.map(t=>lr(t))):Promise.reject(new Error("No urls to test"))}function dr(e){return e?.length?Promise.any(e.map(t=>ur(t))):Promise.reject(new Error("No download urls to test"))}async function xe(e,t){if(F.api&&F.download)return;if(X)return X;const n=De[t].BASE_API_URL||"",r=De[t].OBS_URL||"";F.api=n,F.download=r,F.ws=n.replace(/http/g,"ws"),n||(X=Promise.reject(new Error("环境配置错误")),await X),X=(async()=>{const s=await T.get(`${n.replace(/\/$/,"")}${ar}`,{headers:{Authorization:`Bearer ${e}`},timeout:15e3});if(s.data?.code!==200||!s.data?.data)return Promise.reject(s);const o=(s.data.data.api??[]).map(h=>h.url).filter(Boolean),i=(s.data.data.download??[]).map(h=>h.url).filter(Boolean),c=n,d=r,[u,l]=await Promise.all([o.length?fr(o).catch(()=>c):Promise.resolve(c),i.length?dr(i).catch(()=>d):Promise.resolve(d)]);F.api=u,F.download=l,F.ws=u.replace(/http/g,"ws")})(),await X}const q=T.create({timeout:6e5});q.interceptors.request.use(async e=>{const t=new $,n=t.config.token;return n?(e.headers.Authorization=`Bearer ${n}`,await xe(n,t.config.env),e.baseURL=F.api,e):Promise.reject(b.UNINITIALIZED)},e=>Promise.reject(e));q.interceptors.response.use(e=>e.data?.code!==200?Promise.reject(e):Promise.resolve(e.data),e=>Promise.reject(e));function hr(){return F.api}function pe(){return F.download}function pr(){return F.ws}const mr=e=>q.post("/api/open-auth/obs/v1/ObsService/GetObsAuthInfo",e),Er=async e=>{const t=pe();return T.post(`${t}`,e,{headers:{"Content-Type":"multipart/form-data"}})},Sr=async(e,t)=>T.put(t,e,{headers:{"Content-Type":"application/octet-stream"}}),Tr=e=>q.post("/api/open-auth/open_consultation/v1/OpenConsultationService/GetConsultationList",e),wr=e=>q.get("/api/open-auth/faq/v1/FaqService/GetFaqList",{params:e}),Rr=()=>q.get("/api/open-auth/user/v1/UserService/GetUserInfo"),yr=e=>q.post("/api/open-auth/user/v1/UserService/GetUserHistoryMessages",e),Ar=e=>{const n=new $().config.env,r=hr()||De[n].BASE_API_URL;return T.post(`${r}/api/open-auth/openAuth/v1/OpenAuthService/AnonymousAuth`,e)},br=e=>q.get("/api/chat/chat/v1/Chat/GetMsg",{params:e});var H=(e=>(e.SEND="1",e.WITHDRAW="2",e.EDIT="3",e.SYSTEM_NOTICE="4",e.TRANSFER="5",e.INBOUND="6",e.REPLY="7",e.UNBIND="8",e))(H||{}),v=(e=>(e.TEXT="1",e.IMAGE="2",e.VIDEO="3",e.FILE="4",e.FAQ="5",e))(v||{}),C=(e=>(e[e.CONNECT_SUCCESS=200]="CONNECT_SUCCESS",e[e.CONNECT_FAILED=40001]="CONNECT_FAILED",e[e.TRANSFER_CUSTOMER_SUCCESS=201]="TRANSFER_CUSTOMER_SUCCESS",e[e.TRANSFER_TO_CUSTOMER_SUCCESS=202]="TRANSFER_TO_CUSTOMER_SUCCESS",e[e.TRANSFER_USER_SUCCESS=203]="TRANSFER_USER_SUCCESS",e[e.TRANSFER_FAIL=50001]="TRANSFER_FAIL",e[e.MATCH_FAIL=50002]="MATCH_FAIL",e[e.MATCH_INFO=50005]="MATCH_INFO",e[e.MATCH_SUCCESS=50006]="MATCH_SUCCESS",e[e.RETRACT=204]="RETRACT",e[e.RETRACT_FAIL=50003]="RETRACT_FAIL",e[e.EDIT=205]="EDIT",e[e.EDIT_FAIL=50004]="EDIT_FAIL",e[e.COMMON_FAIL=5e4]="COMMON_FAIL",e[e.SEND_SUCCESS=206]="SEND_SUCCESS",e[e.SEND_CALLBACK=207]="SEND_CALLBACK",e[e.CHANGE_CHAT_STATUS=208]="CHANGE_CHAT_STATUS",e[e.REPLY_FAIL=50008]="REPLY_FAIL",e[e.REPLY_SUCCESS=209]="REPLY_SUCCESS",e[e.UNBIND_SUCCESS=60006]="UNBIND_SUCCESS",e[e.BAN_CUSTOMER=60007]="BAN_CUSTOMER",e[e.BAN_ENTRY=60008]="BAN_ENTRY",e[e.REMATCH=60001]="REMATCH",e))(C||{}),me=(e=>(e.CUSTOMER="1",e.USER="2",e.ANONYMOUS="3",e))(me||{}),A=(e=>(e.CONNECTED="connected",e.DISCONNECTED="disconnected",e.ERROR="error",e.MESSAGE="message",e.STATUS_CHANGE="status_change",e.HEARTBEAT_TIMEOUT="heartbeat_timeout",e))(A||{}),O=(e=>(e.DISCONNECTED="disconnected",e.CONNECTING="connecting",e.CONNECTED="connected",e.RECONNECTING="reconnecting",e.ERROR="error",e))(O||{}),N=(e=>(e.UNMATCHED="1",e.MATCHING="2",e.MATCHED="3",e.UNBIND="4",e))(N||{});class Nr{events=new Map;on(t,n){this.events.has(t)||this.events.set(t,[]),this.events.get(t).push(n)}off(t,n){const r=this.events.get(t);if(r){const s=r.indexOf(n);s>-1&&r.splice(s,1)}}emit(t,n){const r=this.events.get(t);r&&r.forEach(s=>{try{s(n)}catch(o){console.error(`事件回调执行错误 [${t}]:`,o)}})}removeAllListeners(t){t?this.events.delete(t):this.events.clear()}once(t,n){const r=s=>{n(s),this.off(t,r)};this.on(t,r)}}async function Or(e,t){return await xe(e,t),`${await pr()}/api/ws?Authorization=${e}`}function gr(){return"web"+Date.now().toString(36)+Math.random().toString(36).slice(2)}function Cr(e){return typeof e=="object"&&e!==null&&"data"in e&&"msgType"in e&&"toUid"in e&&"chatType"in e&&"code"in e}function st(e){const t=pe()+"/";return e.contentType!==v.TEXT&&(e.content=JSON.parse(e.content),e.content?.fileUrl?.startsWith("http")||(e.content.fileUrl=t+e.content.fileUrl),e.content?.thumbnailUrl?.startsWith("http")||(e.content.thumbnailUrl=t+e.content.thumbnailUrl)),e.replyType&&e.replyType!==v.TEXT&&typeof e.replyContent=="string"&&(e.replyContent=JSON.parse(e.replyContent),e.replyContent?.fileUrl?.startsWith("http")||(e.replyContent.fileUrl=t+e.replyContent.fileUrl),e.replyContent?.thumbnailUrl?.startsWith("http")||(e.replyContent.thumbnailUrl=t+e.replyContent.thumbnailUrl)),e}class $ extends Nr{config={token:"",autoReconnect:!0,reconnectInterval:3e3,maxReconnectAttempts:5,responseTimeout:15e3,env:"production"};ws=null;status=O.DISCONNECTED;reconnectTimer=null;reconnectAttempts=0;heartbeatTimeoutTimer=null;lastHeartbeatTime=0;consultationTypeId="";sessionData=null;userInfo=null;static instance=null;matchStatus=N.UNMATCHED;constructor({env:t="production"}={}){if(super(),$.instance)return $.instance;$.instance=this,this.config.env=t}async init(t){if(!t.token)return Promise.reject(b.PARAMETER_ERROR);await xe(t.token,this.config.env),this.config=Object.assign(this.config,t)}connect(t){return this.consultationTypeId=t,new Promise(async(n,r)=>{if(!this.config.token)return r(b.UNINITIALIZED);if(this.status===O.CONNECTED)return n();if(this.status!==O.CONNECTING){this.setStatus(O.CONNECTING);try{const s=await Or(this.config.token,this.config.env);this.ws=new WebSocket(s),this.ws.onopen=()=>{this.reconnectAttempts=0,this.setStatus(O.CONNECTED),this.emit(A.CONNECTED),n()},this.ws.onmessage=o=>{try{this.handleMessage(o.data)}catch(i){throw console.error("解析消息失败:",i),b.DATA_PARSING_ERROR}},this.ws.onerror=o=>{console.error("连接错误:",o),this.setStatus(O.ERROR),this.emit(A.ERROR,o),r(o)},this.ws.onclose=()=>{this.config.env==="development"&&console.warn("连接断开",new Date().toISOString()),this.setStatus(O.DISCONNECTED),this.emit(A.DISCONNECTED),this.heartbeatTimeoutTimer&&(clearTimeout(this.heartbeatTimeoutTimer),this.heartbeatTimeoutTimer=null),this.config.autoReconnect&&this.reconnectAttempts<this.config.maxReconnectAttempts&&this.scheduleReconnect()}}catch(s){this.setStatus(O.ERROR),this.emit(A.ERROR,s),r(s)}}})}disconnect(){this.config.autoReconnect=!1,this.sessionData=null,this.matchStatus=N.UNMATCHED,this.clearReconnectTimer(),this.heartbeatTimeoutTimer&&(clearTimeout(this.heartbeatTimeoutTimer),this.heartbeatTimeoutTimer=null),this.ws&&(this.ws.close(),this.ws=null),this.setStatus(O.DISCONNECTED)}async sendMessage(t,n,r=H.SEND){const s={msgType:r,data:t,toUid:this.sessionData?.cid,chatType:n,editId:void 0};if(this.status!==O.CONNECTED||!this.ws)if(this.ws&&this.status===O.DISCONNECTED){console.log("连接断开,尝试重新连接");try{await this.connect(this.consultationTypeId)}catch(o){throw console.error("重连失败:",o),b.DISCONNECTED}}else throw console.error(b.DISCONNECTED),b.DISCONNECTED;try{if(!this.ws)throw b.DISCONNECTED;return r===H.SEND?new Promise(async(o,i)=>{const c=gr();s.ext=c;const d=await br({ext:c});d.data?.messageId?(this.ws.send(JSON.stringify(s)),o({messageId:d.data.messageId,data:t})):i(b.MESSAGE_SEND_FAIL)}):(this.ws.send(JSON.stringify(s)),{data:t})}catch(o){throw console.error("发送消息失败:",o),b.MESSAGE_SEND_FAIL}}async checkMatchStatus(){if(this.matchStatus===N.UNBIND&&(await this.sendMessage(this.consultationTypeId,void 0,H.INBOUND),await new Promise((t,n)=>{const r=setTimeout(()=>{clearTimeout(r),n(b.MESSAGE_SEND_FAIL)},this.config.responseTimeout);this.once(A.MESSAGE,s=>{s.code===C.REMATCH&&(clearTimeout(r),t(!0))})})),this.matchStatus!==N.MATCHED)throw console.error(b.NO_CUSTOMER_SERVICE),b.NO_CUSTOMER_SERVICE}async sendText(t){return await this.checkMatchStatus(),this.sendMessage(t,v.TEXT)}async sendFile({file:t,thumbnailFile:n,chatType:r}){try{await this.checkMatchStatus();const[s,o]=await Promise.all([this.handleUploadFile(t),n?this.handleUploadFile(n):Promise.resolve(void 0)]),i={fileName:t.name,fileUrl:s,thumbnailUrl:o,fileSize:t.size},{messageId:c}=await this.sendMessage(JSON.stringify(i),r),d=pe();return{messageId:c,content:{fileName:t.name,fileUrl:`${d}/${s}`,thumbnailUrl:o?`${d}/${o}`:void 0,fileSize:t.size}}}catch(s){throw console.error("上传文件失败:",s),s}}getStatus(){return this.status}isConnected(){return this.status===O.CONNECTED}handleMessage(t){if(t==="ping"){this.lastHeartbeatTime=Date.now(),this.heartbeatTimeoutTimer&&(clearTimeout(this.heartbeatTimeoutTimer),this.heartbeatTimeoutTimer=null),this.sendHeartbeat();return}if(t=JSON.parse(t),!!Cr(t))try{const n=t.data?JSON.parse(t.data):t.data;switch(t.data=n,t.code){case C.CONNECT_SUCCESS:this.matchStatus===N.MATCHED||this.matchStatus===N.MATCHING?this.matchStatus=N.UNBIND:this.matchStatus=N.MATCHING,this.sendMessage(this.consultationTypeId,void 0,H.INBOUND);break;case C.MATCH_INFO:case C.MATCH_SUCCESS:if(this.matchStatus===N.MATCHED)return;this.sessionData=t.data,this.matchStatus===N.UNBIND?(this.matchStatus=N.MATCHED,this.emit(A.MESSAGE,{...t,code:C.REMATCH})):(this.matchStatus=N.MATCHED,this.getFaqList(),this.emit(A.MESSAGE,t));break;case C.TRANSFER_USER_SUCCESS:if(n.oldSessionId!==this.sessionData?.sessionId)return;const r=t.data;this.sessionData={...this.sessionData,cid:String(r.cid),customerAvatar:r.customerAvatar,customerName:r.customerName,groupId:r.groupId,sessionId:r.sessionId},this.emit(A.MESSAGE,t);break;case C.SEND_SUCCESS:case C.EDIT:case C.REPLY_SUCCESS:const s=t.data;if(s.sessionId!==this.sessionData?.sessionId)return;st(s),this.emit(A.MESSAGE,t);break;case C.SEND_CALLBACK:const o=t.ext,c=t.data.messageId;this.emit(o,c);break;case C.UNBIND_SUCCESS:if(n.sessionId!==this.sessionData?.sessionId)return;this.matchStatus=N.UNBIND,this.sessionData=null,this.emit(A.MESSAGE,t);break;default:this.emit(A.MESSAGE,t);break}}catch(n){console.error("解析消息失败:",n)}}setStatus(t){this.status!==t&&(this.status=t,this.emit(A.STATUS_CHANGE,t))}scheduleReconnect(){this.config.env==="development"&&console.warn(`第${this.reconnectAttempts+1}次安排重连`,new Date().toISOString()),this.clearReconnectTimer(),this.reconnectAttempts++,this.setStatus(O.RECONNECTING),this.reconnectTimer=setTimeout(()=>{this.connect(this.consultationTypeId).catch(t=>{console.error("重连失败:",t)})},this.config.reconnectInterval)}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}sendHeartbeat(){if(!(this.status!==O.CONNECTED||!this.ws))try{this.ws.send("pong"),this.lastHeartbeatTime=Date.now(),this.heartbeatTimeoutTimer=setTimeout(()=>{Date.now()-this.lastHeartbeatTime>=this.config.responseTimeout&&(this.emit(A.HEARTBEAT_TIMEOUT),this.config.env==="development"&&console.warn("心跳超时,尝试重连",new Date().toISOString()),this.ws&&this.ws.close())},this.config.responseTimeout)}catch(t){console.error("发送心跳失败:",t)}}async getHistoryMessages({lastMsgId:t,size:n=50}){if(this.matchStatus!==N.MATCHED)return Promise.reject(b.NO_CUSTOMER_SERVICE);const r=await yr({sessionId:this.sessionData?.sessionId,lastMsgId:t,size:n}),s=r.data.list.map(o=>st(o));return{hasMore:r.data.hasMore,list:s}}async getConsultationList(t){return(await Tr({entranceId:t})).data}handleUploadFile(t){return new Promise(async(n,r)=>{const s=t.name.split(".").pop(),o=await mr({ext:s||""}),{accessKeyId:i,signature:c,policy:d,key:u,maxLimit:l,url:h}=o.data;if(t.size>l*1024*1024)return r(`文件大小不能超过${l}MB`);if(h){const S=await Sr(t,h);S.status===200?n(`${u}`):r(S.data)}else{const S=new FormData;S.append("key",u),S.append("AccessKeyId",i),S.append("signature",c),S.append("policy",d),S.append("file",t);const w=await Er(S);w.status===204?n(`${u}`):r(w.data)}})}getVideoThumbnail=t=>new Promise((n,r)=>{const s=document.createElement("video"),o=document.createElement("canvas"),i=o.getContext("2d");if(!i){r(new Error("无法创建 canvas 上下文"));return}const c=URL.createObjectURL(t);s.preload="metadata",s.src=c,s.muted=!0,s.playsInline=!0,s.addEventListener("loadeddata",()=>{o.width=s.videoWidth,o.height=s.videoHeight,s.currentTime=0}),s.addEventListener("seeked",()=>{try{i.drawImage(s,0,0,o.width,o.height),o.toBlob(d=>{if(URL.revokeObjectURL(c),s.remove(),!d){r(b.FILE_PARSING_ERROR);return}const u=t.name.replace(/\.[^/.]+$/,"")+"_thumb.jpg",l=new File([d],u,{type:"image/jpeg",lastModified:Date.now()});n(l)},"image/jpeg",.6)}catch(d){URL.revokeObjectURL(c),s.remove(),r(d)}}),s.addEventListener("error",()=>{URL.revokeObjectURL(c),s.remove(),r(b.FILE_PARSING_ERROR)}),s.load()});async getFaqList(){if(this.matchStatus!==N.MATCHED)return Promise.reject(b.NO_CUSTOMER_SERVICE);const t=await wr({id:this.sessionData?.cid});if(!t.data?.topic?.length)return;const n={guideText:t.data.guideText,list:t.data.topic.map(r=>({...r,question:r.question}))};setTimeout(()=>{const r={code:C.SEND_SUCCESS,data:{content:n,contentType:v.FAQ,sendUserType:me.CUSTOMER,customerServiceAvatar:this.sessionData?.customerAvatar,customerServiceName:this.sessionData?.customerName,createTime:Date.now(),msgType:H.SEND},msgType:H.SEND,chatType:v.FAQ};this.emit(A.MESSAGE,r)},t.data.showDelaySeconds*1e3)}sendFaq(t){const n={code:C.SEND_SUCCESS,data:{sendUserType:me.CUSTOMER,customerServiceAvatar:this.sessionData?.customerAvatar,customerServiceName:this.sessionData?.customerName,createTime:Date.now(),msgType:H.SEND,contentType:v.FAQ,content:{}},msgType:H.SEND,chatType:v.FAQ};if(t.isMulti)n.data.content={list:t.item},this.emit(A.MESSAGE,n);else{const r=t.item?.[0]||t,s=pe();r.imageUrl=r.imageUrl?.map(o=>o?.startsWith("http")?o:`${s}/${o}`),n.data.content={answer:r},this.emit(A.MESSAGE,n)}}async getUserInfo(){if(this.userInfo)return this.userInfo;const t=await Rr();return this.userInfo=t.data,this.userInfo}async anonymousLogin(t,n){return(await Ar({appKey:t,entranceId:n,userSource:"H5"})).data}}exports.ChatType=v;exports.ConnectionStatus=O;exports.EventType=A;exports.JoyTalk=$;exports.MatchStatus=N;exports.MessageCode=C;exports.MessageType=H;exports.SendUserType=me;exports.default=$;
|
|
1
|
+
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});function it(e,t){return function(){return e.apply(t,arguments)}}const{toString:It}=Object.prototype,{getPrototypeOf:Le}=Object,{iterator:Se,toStringTag:at}=Symbol,Te=(e=>t=>{const n=It.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),x=e=>(e=e.toLowerCase(),t=>Te(t)===e),we=e=>t=>typeof t===e,{isArray:Z}=Array,Q=we("undefined");function re(e){return e!==null&&!Q(e)&&e.constructor!==null&&!Q(e.constructor)&&_(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const ct=x("ArrayBuffer");function Lt(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&ct(e.buffer),t}const Ft=we("string"),_=we("function"),lt=we("number"),se=e=>e!==null&&typeof e=="object",Pt=e=>e===!0||e===!1,fe=e=>{if(Te(e)!=="object")return!1;const t=Le(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(at in e)&&!(Se in e)},xt=e=>{if(!se(e)||re(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},Bt=x("Date"),kt=x("File"),vt=x("Blob"),Ht=x("FileList"),jt=e=>se(e)&&_(e.pipe),Mt=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||_(e.append)&&((t=Te(e))==="formdata"||t==="object"&&_(e.toString)&&e.toString()==="[object FormData]"))},$t=x("URLSearchParams"),[qt,Gt,zt,Jt]=["ReadableStream","Request","Response","Headers"].map(x),Vt=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function oe(e,t,{allOwnKeys:n=!1}={}){if(e===null||typeof e>"u")return;let r,s;if(typeof e!="object"&&(e=[e]),Z(e))for(r=0,s=e.length;r<s;r++)t.call(null,e[r],r,e);else{if(re(e))return;const o=n?Object.getOwnPropertyNames(e):Object.keys(e),i=o.length;let c;for(r=0;r<i;r++)c=o[r],t.call(null,e[c],c,e)}}function ut(e,t){if(re(e))return null;t=t.toLowerCase();const n=Object.keys(e);let r=n.length,s;for(;r-- >0;)if(s=n[r],t===s.toLowerCase())return s;return null}const V=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,ft=e=>!Q(e)&&e!==V;function Ce(){const{caseless:e,skipUndefined:t}=ft(this)&&this||{},n={},r=(s,o)=>{const i=e&&ut(n,o)||o;fe(n[i])&&fe(s)?n[i]=Ce(n[i],s):fe(s)?n[i]=Ce({},s):Z(s)?n[i]=s.slice():(!t||!Q(s))&&(n[i]=s)};for(let s=0,o=arguments.length;s<o;s++)arguments[s]&&oe(arguments[s],r);return n}const Wt=(e,t,n,{allOwnKeys:r}={})=>(oe(t,(s,o)=>{n&&_(s)?e[o]=it(s,n):e[o]=s},{allOwnKeys:r}),e),Kt=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),Xt=(e,t,n,r)=>{e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},Yt=(e,t,n,r)=>{let s,o,i;const c={};if(t=t||{},e==null)return t;do{for(s=Object.getOwnPropertyNames(e),o=s.length;o-- >0;)i=s[o],(!r||r(i,e,t))&&!c[i]&&(t[i]=e[i],c[i]=!0);e=n!==!1&&Le(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},Qt=(e,t,n)=>{e=String(e),(n===void 0||n>e.length)&&(n=e.length),n-=t.length;const r=e.indexOf(t,n);return r!==-1&&r===n},Zt=e=>{if(!e)return null;if(Z(e))return e;let t=e.length;if(!lt(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},en=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&Le(Uint8Array)),tn=(e,t)=>{const r=(e&&e[Se]).call(e);let s;for(;(s=r.next())&&!s.done;){const o=s.value;t.call(e,o[0],o[1])}},nn=(e,t)=>{let n;const r=[];for(;(n=e.exec(t))!==null;)r.push(n);return r},rn=x("HTMLFormElement"),sn=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,s){return r.toUpperCase()+s}),qe=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),on=x("RegExp"),dt=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),r={};oe(n,(s,o)=>{let i;(i=t(s,o,e))!==!1&&(r[o]=i||s)}),Object.defineProperties(e,r)},an=e=>{dt(e,(t,n)=>{if(_(e)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=e[n];if(_(r)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},cn=(e,t)=>{const n={},r=s=>{s.forEach(o=>{n[o]=!0})};return Z(e)?r(e):r(String(e).split(t)),n},ln=()=>{},un=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function fn(e){return!!(e&&_(e.append)&&e[at]==="FormData"&&e[Se])}const dn=e=>{const t=new Array(10),n=(r,s)=>{if(se(r)){if(t.indexOf(r)>=0)return;if(re(r))return r;if(!("toJSON"in r)){t[s]=r;const o=Z(r)?[]:{};return oe(r,(i,c)=>{const d=n(i,s+1);!Q(d)&&(o[c]=d)}),t[s]=void 0,o}}return r};return n(e,0)},hn=x("AsyncFunction"),pn=e=>e&&(se(e)||_(e))&&_(e.then)&&_(e.catch),ht=((e,t)=>e?setImmediate:t?((n,r)=>(V.addEventListener("message",({source:s,data:o})=>{s===V&&o===n&&r.length&&r.shift()()},!1),s=>{r.push(s),V.postMessage(n,"*")}))(`axios@${Math.random()}`,[]):n=>setTimeout(n))(typeof setImmediate=="function",_(V.postMessage)),mn=typeof queueMicrotask<"u"?queueMicrotask.bind(V):typeof process<"u"&&process.nextTick||ht,En=e=>e!=null&&_(e[Se]),a={isArray:Z,isArrayBuffer:ct,isBuffer:re,isFormData:Mt,isArrayBufferView:Lt,isString:Ft,isNumber:lt,isBoolean:Pt,isObject:se,isPlainObject:fe,isEmptyObject:xt,isReadableStream:qt,isRequest:Gt,isResponse:zt,isHeaders:Jt,isUndefined:Q,isDate:Bt,isFile:kt,isBlob:vt,isRegExp:on,isFunction:_,isStream:jt,isURLSearchParams:$t,isTypedArray:en,isFileList:Ht,forEach:oe,merge:Ce,extend:Wt,trim:Vt,stripBOM:Kt,inherits:Xt,toFlatObject:Yt,kindOf:Te,kindOfTest:x,endsWith:Qt,toArray:Zt,forEachEntry:tn,matchAll:nn,isHTMLForm:rn,hasOwnProperty:qe,hasOwnProp:qe,reduceDescriptors:dt,freezeMethods:an,toObjectSet:cn,toCamelCase:sn,noop:ln,toFiniteNumber:un,findKey:ut,global:V,isContextDefined:ft,isSpecCompliantForm:fn,toJSONObject:dn,isAsyncFn:hn,isThenable:pn,setImmediate:ht,asap:mn,isIterable:En};function E(e,t,n,r,s){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),s&&(this.response=s,this.status=s.status?s.status:null)}a.inherits(E,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:a.toJSONObject(this.config),code:this.code,status:this.status}}});const pt=E.prototype,mt={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{mt[e]={value:e}});Object.defineProperties(E,mt);Object.defineProperty(pt,"isAxiosError",{value:!0});E.from=(e,t,n,r,s,o)=>{const i=Object.create(pt);a.toFlatObject(e,i,function(l){return l!==Error.prototype},u=>u!=="isAxiosError");const c=e&&e.message?e.message:"Error",d=t==null&&e?e.code:t;return E.call(i,c,d,n,r,s),e&&i.cause==null&&Object.defineProperty(i,"cause",{value:e,configurable:!0}),i.name=e&&e.name||"Error",o&&Object.assign(i,o),i};const Sn=null;function Ue(e){return a.isPlainObject(e)||a.isArray(e)}function Et(e){return a.endsWith(e,"[]")?e.slice(0,-2):e}function Ge(e,t,n){return e?e.concat(t).map(function(s,o){return s=Et(s),!n&&o?"["+s+"]":s}).join(n?".":""):t}function Tn(e){return a.isArray(e)&&!e.some(Ue)}const wn=a.toFlatObject(a,{},null,function(t){return/^is[A-Z]/.test(t)});function Re(e,t,n){if(!a.isObject(e))throw new TypeError("target must be an object");t=t||new FormData,n=a.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(m,p){return!a.isUndefined(p[m])});const r=n.metaTokens,s=n.visitor||l,o=n.dots,i=n.indexes,d=(n.Blob||typeof Blob<"u"&&Blob)&&a.isSpecCompliantForm(t);if(!a.isFunction(s))throw new TypeError("visitor must be a function");function u(f){if(f===null)return"";if(a.isDate(f))return f.toISOString();if(a.isBoolean(f))return f.toString();if(!d&&a.isBlob(f))throw new E("Blob is not supported. Use a Buffer instead.");return a.isArrayBuffer(f)||a.isTypedArray(f)?d&&typeof Blob=="function"?new Blob([f]):Buffer.from(f):f}function l(f,m,p){let R=f;if(f&&!p&&typeof f=="object"){if(a.endsWith(m,"{}"))m=r?m:m.slice(0,-2),f=JSON.stringify(f);else if(a.isArray(f)&&Tn(f)||(a.isFileList(f)||a.endsWith(m,"[]"))&&(R=a.toArray(f)))return m=Et(m),R.forEach(function(y,U){!(a.isUndefined(y)||y===null)&&t.append(i===!0?Ge([m],U,o):i===null?m:m+"[]",u(y))}),!1}return Ue(f)?!0:(t.append(Ge(p,m,o),u(f)),!1)}const h=[],S=Object.assign(wn,{defaultVisitor:l,convertValue:u,isVisitable:Ue});function w(f,m){if(!a.isUndefined(f)){if(h.indexOf(f)!==-1)throw Error("Circular reference detected in "+m.join("."));h.push(f),a.forEach(f,function(R,I){(!(a.isUndefined(R)||R===null)&&s.call(t,R,a.isString(I)?I.trim():I,m,S))===!0&&w(R,m?m.concat(I):[I])}),h.pop()}}if(!a.isObject(e))throw new TypeError("data must be an object");return w(e),t}function ze(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(r){return t[r]})}function Fe(e,t){this._pairs=[],e&&Re(e,this,t)}const St=Fe.prototype;St.append=function(t,n){this._pairs.push([t,n])};St.toString=function(t){const n=t?function(r){return t.call(this,r,ze)}:ze;return this._pairs.map(function(s){return n(s[0])+"="+n(s[1])},"").join("&")};function Rn(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function Tt(e,t,n){if(!t)return e;const r=n&&n.encode||Rn;a.isFunction(n)&&(n={serialize:n});const s=n&&n.serialize;let o;if(s?o=s(t,n):o=a.isURLSearchParams(t)?t.toString():new Fe(t,n).toString(r),o){const i=e.indexOf("#");i!==-1&&(e=e.slice(0,i)),e+=(e.indexOf("?")===-1?"?":"&")+o}return e}class Je{constructor(){this.handlers=[]}use(t,n,r){return this.handlers.push({fulfilled:t,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){a.forEach(this.handlers,function(r){r!==null&&t(r)})}}const wt={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},yn=typeof URLSearchParams<"u"?URLSearchParams:Fe,An=typeof FormData<"u"?FormData:null,bn=typeof Blob<"u"?Blob:null,Nn={isBrowser:!0,classes:{URLSearchParams:yn,FormData:An,Blob:bn},protocols:["http","https","file","blob","url","data"]},Pe=typeof window<"u"&&typeof document<"u",_e=typeof navigator=="object"&&navigator||void 0,On=Pe&&(!_e||["ReactNative","NativeScript","NS"].indexOf(_e.product)<0),gn=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",Cn=Pe&&window.location.href||"http://localhost",Un=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:Pe,hasStandardBrowserEnv:On,hasStandardBrowserWebWorkerEnv:gn,navigator:_e,origin:Cn},Symbol.toStringTag,{value:"Module"})),g={...Un,...Nn};function _n(e,t){return Re(e,new g.classes.URLSearchParams,{visitor:function(n,r,s,o){return g.isNode&&a.isBuffer(n)?(this.append(r,n.toString("base64")),!1):o.defaultVisitor.apply(this,arguments)},...t})}function Dn(e){return a.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function In(e){const t={},n=Object.keys(e);let r;const s=n.length;let o;for(r=0;r<s;r++)o=n[r],t[o]=e[o];return t}function Rt(e){function t(n,r,s,o){let i=n[o++];if(i==="__proto__")return!0;const c=Number.isFinite(+i),d=o>=n.length;return i=!i&&a.isArray(s)?s.length:i,d?(a.hasOwnProp(s,i)?s[i]=[s[i],r]:s[i]=r,!c):((!s[i]||!a.isObject(s[i]))&&(s[i]=[]),t(n,r,s[i],o)&&a.isArray(s[i])&&(s[i]=In(s[i])),!c)}if(a.isFormData(e)&&a.isFunction(e.entries)){const n={};return a.forEachEntry(e,(r,s)=>{t(Dn(r),s,n,0)}),n}return null}function Ln(e,t,n){if(a.isString(e))try{return(t||JSON.parse)(e),a.trim(e)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(e)}const ie={transitional:wt,adapter:["xhr","http","fetch"],transformRequest:[function(t,n){const r=n.getContentType()||"",s=r.indexOf("application/json")>-1,o=a.isObject(t);if(o&&a.isHTMLForm(t)&&(t=new FormData(t)),a.isFormData(t))return s?JSON.stringify(Rt(t)):t;if(a.isArrayBuffer(t)||a.isBuffer(t)||a.isStream(t)||a.isFile(t)||a.isBlob(t)||a.isReadableStream(t))return t;if(a.isArrayBufferView(t))return t.buffer;if(a.isURLSearchParams(t))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let c;if(o){if(r.indexOf("application/x-www-form-urlencoded")>-1)return _n(t,this.formSerializer).toString();if((c=a.isFileList(t))||r.indexOf("multipart/form-data")>-1){const d=this.env&&this.env.FormData;return Re(c?{"files[]":t}:t,d&&new d,this.formSerializer)}}return o||s?(n.setContentType("application/json",!1),Ln(t)):t}],transformResponse:[function(t){const n=this.transitional||ie.transitional,r=n&&n.forcedJSONParsing,s=this.responseType==="json";if(a.isResponse(t)||a.isReadableStream(t))return t;if(t&&a.isString(t)&&(r&&!this.responseType||s)){const i=!(n&&n.silentJSONParsing)&&s;try{return JSON.parse(t,this.parseReviver)}catch(c){if(i)throw c.name==="SyntaxError"?E.from(c,E.ERR_BAD_RESPONSE,this,null,this.response):c}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:g.classes.FormData,Blob:g.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};a.forEach(["delete","get","head","post","put","patch"],e=>{ie.headers[e]={}});const Fn=a.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),Pn=e=>{const t={};let n,r,s;return e&&e.split(`
|
|
2
|
+
`).forEach(function(i){s=i.indexOf(":"),n=i.substring(0,s).trim().toLowerCase(),r=i.substring(s+1).trim(),!(!n||t[n]&&Fn[n])&&(n==="set-cookie"?t[n]?t[n].push(r):t[n]=[r]:t[n]=t[n]?t[n]+", "+r:r)}),t},Ve=Symbol("internals");function ne(e){return e&&String(e).trim().toLowerCase()}function de(e){return e===!1||e==null?e:a.isArray(e)?e.map(de):String(e)}function xn(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(e);)t[r[1]]=r[2];return t}const Bn=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function Ne(e,t,n,r,s){if(a.isFunction(r))return r.call(this,t,n);if(s&&(t=n),!!a.isString(t)){if(a.isString(r))return t.indexOf(r)!==-1;if(a.isRegExp(r))return r.test(t)}}function kn(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,n,r)=>n.toUpperCase()+r)}function vn(e,t){const n=a.toCamelCase(" "+t);["get","set","has"].forEach(r=>{Object.defineProperty(e,r+n,{value:function(s,o,i){return this[r].call(this,t,s,o,i)},configurable:!0})})}let D=class{constructor(t){t&&this.set(t)}set(t,n,r){const s=this;function o(c,d,u){const l=ne(d);if(!l)throw new Error("header name must be a non-empty string");const h=a.findKey(s,l);(!h||s[h]===void 0||u===!0||u===void 0&&s[h]!==!1)&&(s[h||d]=de(c))}const i=(c,d)=>a.forEach(c,(u,l)=>o(u,l,d));if(a.isPlainObject(t)||t instanceof this.constructor)i(t,n);else if(a.isString(t)&&(t=t.trim())&&!Bn(t))i(Pn(t),n);else if(a.isObject(t)&&a.isIterable(t)){let c={},d,u;for(const l of t){if(!a.isArray(l))throw TypeError("Object iterator must return a key-value pair");c[u=l[0]]=(d=c[u])?a.isArray(d)?[...d,l[1]]:[d,l[1]]:l[1]}i(c,n)}else t!=null&&o(n,t,r);return this}get(t,n){if(t=ne(t),t){const r=a.findKey(this,t);if(r){const s=this[r];if(!n)return s;if(n===!0)return xn(s);if(a.isFunction(n))return n.call(this,s,r);if(a.isRegExp(n))return n.exec(s);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,n){if(t=ne(t),t){const r=a.findKey(this,t);return!!(r&&this[r]!==void 0&&(!n||Ne(this,this[r],r,n)))}return!1}delete(t,n){const r=this;let s=!1;function o(i){if(i=ne(i),i){const c=a.findKey(r,i);c&&(!n||Ne(r,r[c],c,n))&&(delete r[c],s=!0)}}return a.isArray(t)?t.forEach(o):o(t),s}clear(t){const n=Object.keys(this);let r=n.length,s=!1;for(;r--;){const o=n[r];(!t||Ne(this,this[o],o,t,!0))&&(delete this[o],s=!0)}return s}normalize(t){const n=this,r={};return a.forEach(this,(s,o)=>{const i=a.findKey(r,o);if(i){n[i]=de(s),delete n[o];return}const c=t?kn(o):String(o).trim();c!==o&&delete n[o],n[c]=de(s),r[c]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){const n=Object.create(null);return a.forEach(this,(r,s)=>{r!=null&&r!==!1&&(n[s]=t&&a.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,n])=>t+": "+n).join(`
|
|
3
|
+
`)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...n){const r=new this(t);return n.forEach(s=>r.set(s)),r}static accessor(t){const r=(this[Ve]=this[Ve]={accessors:{}}).accessors,s=this.prototype;function o(i){const c=ne(i);r[c]||(vn(s,i),r[c]=!0)}return a.isArray(t)?t.forEach(o):o(t),this}};D.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);a.reduceDescriptors(D.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}});a.freezeMethods(D);function Oe(e,t){const n=this||ie,r=t||n,s=D.from(r.headers);let o=r.data;return a.forEach(e,function(c){o=c.call(n,o,s.normalize(),t?t.status:void 0)}),s.normalize(),o}function yt(e){return!!(e&&e.__CANCEL__)}function ee(e,t,n){E.call(this,e??"canceled",E.ERR_CANCELED,t,n),this.name="CanceledError"}a.inherits(ee,E,{__CANCEL__:!0});function At(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new E("Request failed with status code "+n.status,[E.ERR_BAD_REQUEST,E.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function Hn(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function jn(e,t){e=e||10;const n=new Array(e),r=new Array(e);let s=0,o=0,i;return t=t!==void 0?t:1e3,function(d){const u=Date.now(),l=r[o];i||(i=u),n[s]=d,r[s]=u;let h=o,S=0;for(;h!==s;)S+=n[h++],h=h%e;if(s=(s+1)%e,s===o&&(o=(o+1)%e),u-i<t)return;const w=l&&u-l;return w?Math.round(S*1e3/w):void 0}}function Mn(e,t){let n=0,r=1e3/t,s,o;const i=(u,l=Date.now())=>{n=l,s=null,o&&(clearTimeout(o),o=null),e(...u)};return[(...u)=>{const l=Date.now(),h=l-n;h>=r?i(u,l):(s=u,o||(o=setTimeout(()=>{o=null,i(s)},r-h)))},()=>s&&i(s)]}const pe=(e,t,n=3)=>{let r=0;const s=jn(50,250);return Mn(o=>{const i=o.loaded,c=o.lengthComputable?o.total:void 0,d=i-r,u=s(d),l=i<=c;r=i;const h={loaded:i,total:c,progress:c?i/c:void 0,bytes:d,rate:u||void 0,estimated:u&&c&&l?(c-i)/u:void 0,event:o,lengthComputable:c!=null,[t?"download":"upload"]:!0};e(h)},n)},We=(e,t)=>{const n=e!=null;return[r=>t[0]({lengthComputable:n,total:e,loaded:r}),t[1]]},Ke=e=>(...t)=>a.asap(()=>e(...t)),$n=g.hasStandardBrowserEnv?((e,t)=>n=>(n=new URL(n,g.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new URL(g.origin),g.navigator&&/(msie|trident)/i.test(g.navigator.userAgent)):()=>!0,qn=g.hasStandardBrowserEnv?{write(e,t,n,r,s,o,i){if(typeof document>"u")return;const c=[`${e}=${encodeURIComponent(t)}`];a.isNumber(n)&&c.push(`expires=${new Date(n).toUTCString()}`),a.isString(r)&&c.push(`path=${r}`),a.isString(s)&&c.push(`domain=${s}`),o===!0&&c.push("secure"),a.isString(i)&&c.push(`SameSite=${i}`),document.cookie=c.join("; ")},read(e){if(typeof document>"u")return null;const t=document.cookie.match(new RegExp("(?:^|; )"+e+"=([^;]*)"));return t?decodeURIComponent(t[1]):null},remove(e){this.write(e,"",Date.now()-864e5,"/")}}:{write(){},read(){return null},remove(){}};function Gn(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function zn(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function bt(e,t,n){let r=!Gn(t);return e&&(r||n==!1)?zn(e,t):t}const Xe=e=>e instanceof D?{...e}:e;function K(e,t){t=t||{};const n={};function r(u,l,h,S){return a.isPlainObject(u)&&a.isPlainObject(l)?a.merge.call({caseless:S},u,l):a.isPlainObject(l)?a.merge({},l):a.isArray(l)?l.slice():l}function s(u,l,h,S){if(a.isUndefined(l)){if(!a.isUndefined(u))return r(void 0,u,h,S)}else return r(u,l,h,S)}function o(u,l){if(!a.isUndefined(l))return r(void 0,l)}function i(u,l){if(a.isUndefined(l)){if(!a.isUndefined(u))return r(void 0,u)}else return r(void 0,l)}function c(u,l,h){if(h in t)return r(u,l);if(h in e)return r(void 0,u)}const d={url:o,method:o,data:o,baseURL:i,transformRequest:i,transformResponse:i,paramsSerializer:i,timeout:i,timeoutMessage:i,withCredentials:i,withXSRFToken:i,adapter:i,responseType:i,xsrfCookieName:i,xsrfHeaderName:i,onUploadProgress:i,onDownloadProgress:i,decompress:i,maxContentLength:i,maxBodyLength:i,beforeRedirect:i,transport:i,httpAgent:i,httpsAgent:i,cancelToken:i,socketPath:i,responseEncoding:i,validateStatus:c,headers:(u,l,h)=>s(Xe(u),Xe(l),h,!0)};return a.forEach(Object.keys({...e,...t}),function(l){const h=d[l]||s,S=h(e[l],t[l],l);a.isUndefined(S)&&h!==c||(n[l]=S)}),n}const Nt=e=>{const t=K({},e);let{data:n,withXSRFToken:r,xsrfHeaderName:s,xsrfCookieName:o,headers:i,auth:c}=t;if(t.headers=i=D.from(i),t.url=Tt(bt(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&i.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),a.isFormData(n)){if(g.hasStandardBrowserEnv||g.hasStandardBrowserWebWorkerEnv)i.setContentType(void 0);else if(a.isFunction(n.getHeaders)){const d=n.getHeaders(),u=["content-type","content-length"];Object.entries(d).forEach(([l,h])=>{u.includes(l.toLowerCase())&&i.set(l,h)})}}if(g.hasStandardBrowserEnv&&(r&&a.isFunction(r)&&(r=r(t)),r||r!==!1&&$n(t.url))){const d=s&&o&&qn.read(o);d&&i.set(s,d)}return t},Jn=typeof XMLHttpRequest<"u",Vn=Jn&&function(e){return new Promise(function(n,r){const s=Nt(e);let o=s.data;const i=D.from(s.headers).normalize();let{responseType:c,onUploadProgress:d,onDownloadProgress:u}=s,l,h,S,w,f;function m(){w&&w(),f&&f(),s.cancelToken&&s.cancelToken.unsubscribe(l),s.signal&&s.signal.removeEventListener("abort",l)}let p=new XMLHttpRequest;p.open(s.method.toUpperCase(),s.url,!0),p.timeout=s.timeout;function R(){if(!p)return;const y=D.from("getAllResponseHeaders"in p&&p.getAllResponseHeaders()),P={data:!c||c==="text"||c==="json"?p.responseText:p.response,status:p.status,statusText:p.statusText,headers:y,config:e,request:p};At(function(L){n(L),m()},function(L){r(L),m()},P),p=null}"onloadend"in p?p.onloadend=R:p.onreadystatechange=function(){!p||p.readyState!==4||p.status===0&&!(p.responseURL&&p.responseURL.indexOf("file:")===0)||setTimeout(R)},p.onabort=function(){p&&(r(new E("Request aborted",E.ECONNABORTED,e,p)),p=null)},p.onerror=function(U){const P=U&&U.message?U.message:"Network Error",z=new E(P,E.ERR_NETWORK,e,p);z.event=U||null,r(z),p=null},p.ontimeout=function(){let U=s.timeout?"timeout of "+s.timeout+"ms exceeded":"timeout exceeded";const P=s.transitional||wt;s.timeoutErrorMessage&&(U=s.timeoutErrorMessage),r(new E(U,P.clarifyTimeoutError?E.ETIMEDOUT:E.ECONNABORTED,e,p)),p=null},o===void 0&&i.setContentType(null),"setRequestHeader"in p&&a.forEach(i.toJSON(),function(U,P){p.setRequestHeader(P,U)}),a.isUndefined(s.withCredentials)||(p.withCredentials=!!s.withCredentials),c&&c!=="json"&&(p.responseType=s.responseType),u&&([S,f]=pe(u,!0),p.addEventListener("progress",S)),d&&p.upload&&([h,w]=pe(d),p.upload.addEventListener("progress",h),p.upload.addEventListener("loadend",w)),(s.cancelToken||s.signal)&&(l=y=>{p&&(r(!y||y.type?new ee(null,e,p):y),p.abort(),p=null)},s.cancelToken&&s.cancelToken.subscribe(l),s.signal&&(s.signal.aborted?l():s.signal.addEventListener("abort",l)));const I=Hn(s.url);if(I&&g.protocols.indexOf(I)===-1){r(new E("Unsupported protocol "+I+":",E.ERR_BAD_REQUEST,e));return}p.send(o||null)})},Wn=(e,t)=>{const{length:n}=e=e?e.filter(Boolean):[];if(t||n){let r=new AbortController,s;const o=function(u){if(!s){s=!0,c();const l=u instanceof Error?u:this.reason;r.abort(l instanceof E?l:new ee(l instanceof Error?l.message:l))}};let i=t&&setTimeout(()=>{i=null,o(new E(`timeout ${t} of ms exceeded`,E.ETIMEDOUT))},t);const c=()=>{e&&(i&&clearTimeout(i),i=null,e.forEach(u=>{u.unsubscribe?u.unsubscribe(o):u.removeEventListener("abort",o)}),e=null)};e.forEach(u=>u.addEventListener("abort",o));const{signal:d}=r;return d.unsubscribe=()=>a.asap(c),d}},Kn=function*(e,t){let n=e.byteLength;if(n<t){yield e;return}let r=0,s;for(;r<n;)s=r+t,yield e.slice(r,s),r=s},Xn=async function*(e,t){for await(const n of Yn(e))yield*Kn(n,t)},Yn=async function*(e){if(e[Symbol.asyncIterator]){yield*e;return}const t=e.getReader();try{for(;;){const{done:n,value:r}=await t.read();if(n)break;yield r}}finally{await t.cancel()}},Ye=(e,t,n,r)=>{const s=Xn(e,t);let o=0,i,c=d=>{i||(i=!0,r&&r(d))};return new ReadableStream({async pull(d){try{const{done:u,value:l}=await s.next();if(u){c(),d.close();return}let h=l.byteLength;if(n){let S=o+=h;n(S)}d.enqueue(new Uint8Array(l))}catch(u){throw c(u),u}},cancel(d){return c(d),s.return()}},{highWaterMark:2})},Qe=64*1024,{isFunction:ue}=a,Qn=(({Request:e,Response:t})=>({Request:e,Response:t}))(a.global),{ReadableStream:Ze,TextEncoder:et}=a.global,tt=(e,...t)=>{try{return!!e(...t)}catch{return!1}},Zn=e=>{e=a.merge.call({skipUndefined:!0},Qn,e);const{fetch:t,Request:n,Response:r}=e,s=t?ue(t):typeof fetch=="function",o=ue(n),i=ue(r);if(!s)return!1;const c=s&&ue(Ze),d=s&&(typeof et=="function"?(f=>m=>f.encode(m))(new et):async f=>new Uint8Array(await new n(f).arrayBuffer())),u=o&&c&&tt(()=>{let f=!1;const m=new n(g.origin,{body:new Ze,method:"POST",get duplex(){return f=!0,"half"}}).headers.has("Content-Type");return f&&!m}),l=i&&c&&tt(()=>a.isReadableStream(new r("").body)),h={stream:l&&(f=>f.body)};s&&["text","arrayBuffer","blob","formData","stream"].forEach(f=>{!h[f]&&(h[f]=(m,p)=>{let R=m&&m[f];if(R)return R.call(m);throw new E(`Response type '${f}' is not supported`,E.ERR_NOT_SUPPORT,p)})});const S=async f=>{if(f==null)return 0;if(a.isBlob(f))return f.size;if(a.isSpecCompliantForm(f))return(await new n(g.origin,{method:"POST",body:f}).arrayBuffer()).byteLength;if(a.isArrayBufferView(f)||a.isArrayBuffer(f))return f.byteLength;if(a.isURLSearchParams(f)&&(f=f+""),a.isString(f))return(await d(f)).byteLength},w=async(f,m)=>{const p=a.toFiniteNumber(f.getContentLength());return p??S(m)};return async f=>{let{url:m,method:p,data:R,signal:I,cancelToken:y,timeout:U,onDownloadProgress:P,onUploadProgress:z,responseType:L,headers:Ae,withCredentials:ae="same-origin",fetchOptions:ke}=Nt(f),ve=t||fetch;L=L?(L+"").toLowerCase():"text";let ce=Wn([I,y&&y.toAbortSignal()],U),te=null;const J=ce&&ce.unsubscribe&&(()=>{ce.unsubscribe()});let He;try{if(z&&u&&p!=="get"&&p!=="head"&&(He=await w(Ae,R))!==0){let M=new n(m,{method:"POST",body:R,duplex:"half"}),X;if(a.isFormData(R)&&(X=M.headers.get("content-type"))&&Ae.setContentType(X),M.body){const[be,le]=We(He,pe(Ke(z)));R=Ye(M.body,Qe,be,le)}}a.isString(ae)||(ae=ae?"include":"omit");const B=o&&"credentials"in n.prototype,je={...ke,signal:ce,method:p.toUpperCase(),headers:Ae.normalize().toJSON(),body:R,duplex:"half",credentials:B?ae:void 0};te=o&&new n(m,je);let j=await(o?ve(te,ke):ve(m,je));const Me=l&&(L==="stream"||L==="response");if(l&&(P||Me&&J)){const M={};["status","statusText","headers"].forEach($e=>{M[$e]=j[$e]});const X=a.toFiniteNumber(j.headers.get("content-length")),[be,le]=P&&We(X,pe(Ke(P),!0))||[];j=new r(Ye(j.body,Qe,be,()=>{le&&le(),J&&J()}),M)}L=L||"text";let Dt=await h[a.findKey(h,L)||"text"](j,f);return!Me&&J&&J(),await new Promise((M,X)=>{At(M,X,{data:Dt,headers:D.from(j.headers),status:j.status,statusText:j.statusText,config:f,request:te})})}catch(B){throw J&&J(),B&&B.name==="TypeError"&&/Load failed|fetch/i.test(B.message)?Object.assign(new E("Network Error",E.ERR_NETWORK,f,te),{cause:B.cause||B}):E.from(B,B&&B.code,f,te)}}},er=new Map,Ot=e=>{let t=e&&e.env||{};const{fetch:n,Request:r,Response:s}=t,o=[r,s,n];let i=o.length,c=i,d,u,l=er;for(;c--;)d=o[c],u=l.get(d),u===void 0&&l.set(d,u=c?new Map:Zn(t)),l=u;return u};Ot();const xe={http:Sn,xhr:Vn,fetch:{get:Ot}};a.forEach(xe,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const nt=e=>`- ${e}`,tr=e=>a.isFunction(e)||e===null||e===!1;function nr(e,t){e=a.isArray(e)?e:[e];const{length:n}=e;let r,s;const o={};for(let i=0;i<n;i++){r=e[i];let c;if(s=r,!tr(r)&&(s=xe[(c=String(r)).toLowerCase()],s===void 0))throw new E(`Unknown adapter '${c}'`);if(s&&(a.isFunction(s)||(s=s.get(t))))break;o[c||"#"+i]=s}if(!s){const i=Object.entries(o).map(([d,u])=>`adapter ${d} `+(u===!1?"is not supported by the environment":"is not available in the build"));let c=n?i.length>1?`since :
|
|
4
|
+
`+i.map(nt).join(`
|
|
5
|
+
`):" "+nt(i[0]):"as no adapter specified";throw new E("There is no suitable adapter to dispatch the request "+c,"ERR_NOT_SUPPORT")}return s}const gt={getAdapter:nr,adapters:xe};function ge(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new ee(null,e)}function rt(e){return ge(e),e.headers=D.from(e.headers),e.data=Oe.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),gt.getAdapter(e.adapter||ie.adapter,e)(e).then(function(r){return ge(e),r.data=Oe.call(e,e.transformResponse,r),r.headers=D.from(r.headers),r},function(r){return yt(r)||(ge(e),r&&r.response&&(r.response.data=Oe.call(e,e.transformResponse,r.response),r.response.headers=D.from(r.response.headers))),Promise.reject(r)})}const Ct="1.13.2",ye={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{ye[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const st={};ye.transitional=function(t,n,r){function s(o,i){return"[Axios v"+Ct+"] Transitional option '"+o+"'"+i+(r?". "+r:"")}return(o,i,c)=>{if(t===!1)throw new E(s(i," has been removed"+(n?" in "+n:"")),E.ERR_DEPRECATED);return n&&!st[i]&&(st[i]=!0,console.warn(s(i," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(o,i,c):!0}};ye.spelling=function(t){return(n,r)=>(console.warn(`${r} is likely a misspelling of ${t}`),!0)};function rr(e,t,n){if(typeof e!="object")throw new E("options must be an object",E.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let s=r.length;for(;s-- >0;){const o=r[s],i=t[o];if(i){const c=e[o],d=c===void 0||i(c,o,e);if(d!==!0)throw new E("option "+o+" must be "+d,E.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new E("Unknown option "+o,E.ERR_BAD_OPTION)}}const he={assertOptions:rr,validators:ye},k=he.validators;let W=class{constructor(t){this.defaults=t||{},this.interceptors={request:new Je,response:new Je}}async request(t,n){try{return await this._request(t,n)}catch(r){if(r instanceof Error){let s={};Error.captureStackTrace?Error.captureStackTrace(s):s=new Error;const o=s.stack?s.stack.replace(/^.+\n/,""):"";try{r.stack?o&&!String(r.stack).endsWith(o.replace(/^.+\n.+\n/,""))&&(r.stack+=`
|
|
6
|
+
`+o):r.stack=o}catch{}}throw r}}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=K(this.defaults,n);const{transitional:r,paramsSerializer:s,headers:o}=n;r!==void 0&&he.assertOptions(r,{silentJSONParsing:k.transitional(k.boolean),forcedJSONParsing:k.transitional(k.boolean),clarifyTimeoutError:k.transitional(k.boolean)},!1),s!=null&&(a.isFunction(s)?n.paramsSerializer={serialize:s}:he.assertOptions(s,{encode:k.function,serialize:k.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),he.assertOptions(n,{baseUrl:k.spelling("baseURL"),withXsrfToken:k.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let i=o&&a.merge(o.common,o[n.method]);o&&a.forEach(["delete","get","head","post","put","patch","common"],f=>{delete o[f]}),n.headers=D.concat(i,o);const c=[];let d=!0;this.interceptors.request.forEach(function(m){typeof m.runWhen=="function"&&m.runWhen(n)===!1||(d=d&&m.synchronous,c.unshift(m.fulfilled,m.rejected))});const u=[];this.interceptors.response.forEach(function(m){u.push(m.fulfilled,m.rejected)});let l,h=0,S;if(!d){const f=[rt.bind(this),void 0];for(f.unshift(...c),f.push(...u),S=f.length,l=Promise.resolve(n);h<S;)l=l.then(f[h++],f[h++]);return l}S=c.length;let w=n;for(;h<S;){const f=c[h++],m=c[h++];try{w=f(w)}catch(p){m.call(this,p);break}}try{l=rt.call(this,w)}catch(f){return Promise.reject(f)}for(h=0,S=u.length;h<S;)l=l.then(u[h++],u[h++]);return l}getUri(t){t=K(this.defaults,t);const n=bt(t.baseURL,t.url,t.allowAbsoluteUrls);return Tt(n,t.params,t.paramsSerializer)}};a.forEach(["delete","get","head","options"],function(t){W.prototype[t]=function(n,r){return this.request(K(r||{},{method:t,url:n,data:(r||{}).data}))}});a.forEach(["post","put","patch"],function(t){function n(r){return function(o,i,c){return this.request(K(c||{},{method:t,headers:r?{"Content-Type":"multipart/form-data"}:{},url:o,data:i}))}}W.prototype[t]=n(),W.prototype[t+"Form"]=n(!0)});let sr=class Ut{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let n;this.promise=new Promise(function(o){n=o});const r=this;this.promise.then(s=>{if(!r._listeners)return;let o=r._listeners.length;for(;o-- >0;)r._listeners[o](s);r._listeners=null}),this.promise.then=s=>{let o;const i=new Promise(c=>{r.subscribe(c),o=c}).then(s);return i.cancel=function(){r.unsubscribe(o)},i},t(function(o,i,c){r.reason||(r.reason=new ee(o,i,c),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const t=new AbortController,n=r=>{t.abort(r)};return this.subscribe(n),t.signal.unsubscribe=()=>this.unsubscribe(n),t.signal}static source(){let t;return{token:new Ut(function(s){t=s}),cancel:t}}};function or(e){return function(n){return e.apply(null,n)}}function ir(e){return a.isObject(e)&&e.isAxiosError===!0}const De={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(De).forEach(([e,t])=>{De[t]=e});function _t(e){const t=new W(e),n=it(W.prototype.request,t);return a.extend(n,W.prototype,t,{allOwnKeys:!0}),a.extend(n,t,null,{allOwnKeys:!0}),n.create=function(s){return _t(K(e,s))},n}const T=_t(ie);T.Axios=W;T.CanceledError=ee;T.CancelToken=sr;T.isCancel=yt;T.VERSION=Ct;T.toFormData=Re;T.AxiosError=E;T.Cancel=T.CanceledError;T.all=function(t){return Promise.all(t)};T.spread=or;T.isAxiosError=ir;T.mergeConfig=K;T.AxiosHeaders=D;T.formToJSON=e=>Rt(a.isHTMLForm(e)?new FormData(e):e);T.getAdapter=gt.getAdapter;T.HttpStatusCode=De;T.default=T;const{Axios:Ir,AxiosError:Lr,CanceledError:Fr,isCancel:Pr,CancelToken:xr,VERSION:Br,all:kr,Cancel:vr,isAxiosError:Hr,spread:jr,toFormData:Mr,AxiosHeaders:$r,HttpStatusCode:qr,formToJSON:Gr,getAdapter:zr,mergeConfig:Jr}=T,b={UNINITIALIZED:{code:10001,msg:"未初始化"},DISCONNECTED:{code:10002,msg:"未连接"},NO_CUSTOMER_SERVICE:{code:10003,msg:"未分配客服"},MESSAGE_SEND_FAIL:{code:10004,msg:"消息发送失败"},DATA_PARSING_ERROR:{code:10005,msg:"数据解析异常"},FILE_NOT_EXIST:{code:10006,msg:"文件不存在"},FILE_PARSING_ERROR:{code:10007,msg:"文件解析异常"},AUTH_INFO_ERROR:{code:10008,msg:"授权信息错误"},FILE_UPLOAD_FAIL:{code:10009,msg:"文件上传失败"},PARAMETER_ERROR:{code:10010,msg:"参数异常"},EMPTY_DATA:{code:10011,msg:"数据为空"}},ar="/api/customer-service/customer/v1/CustomerService/TestLineLatency",cr="/api/customer-service/customer/v1/CustomerService/ListLines",lr="/pub/logo.png",Ie={development:{BASE_API_URL:"http://dev-joytalk-api.halaladmin.vip",OBS_URL:"http://dev-joytalk-img.halaladmin.vip"},prodtest:{BASE_API_URL:"https://fat-joytalk-api.halaladmin.vip",OBS_URL:"https://fat-joytalk-img.halaladmin.vip"},production:{BASE_API_URL:"https://fat-joytalk-api.halaladmin.vip",OBS_URL:"https://fat-joytalk-img.halaladmin.vip"}},F={api:"",download:"",ws:""};let Y=null;function ur(e){const t=`${e.replace(/\/$/,"")}${ar}`;return T.get(t,{timeout:1e4}).then(n=>n.data?.code!==200?Promise.reject(n):e)}function fr(e){const t=`${e.replace(/\/$/,"")}${lr}`;return T.get(t,{timeout:1e4}).then(()=>e).catch(()=>Promise.reject(new Error("Download latency test failed")))}function dr(e){return e?.length?Promise.any(e.map(t=>ur(t))):Promise.reject(new Error("No urls to test"))}function hr(e){return e?.length?Promise.any(e.map(t=>fr(t))):Promise.reject(new Error("No download urls to test"))}async function Be(e,t){if(F.api&&F.download)return;if(Y)return Y;const n=Ie[t].BASE_API_URL||"",r=Ie[t].OBS_URL||"";F.api=n,F.download=r,F.ws=n.replace(/http/g,"ws"),n||(Y=Promise.reject(new Error("环境配置错误")),await Y),Y=(async()=>{const s=await T.get(`${n.replace(/\/$/,"")}${cr}`,{headers:{Authorization:`Bearer ${e}`},timeout:15e3});if(s.data?.code!==200||!s.data?.data)return Promise.reject(s);const o=(s.data.data.api??[]).map(h=>h.url).filter(Boolean),i=(s.data.data.download??[]).map(h=>h.url).filter(Boolean),c=n,d=r,[u,l]=await Promise.all([o.length?dr(o).catch(()=>c):Promise.resolve(c),i.length?hr(i).catch(()=>d):Promise.resolve(d)]);F.api=u,F.download=l,F.ws=u.replace(/http/g,"ws")})(),await Y}const G=T.create({timeout:6e5});G.interceptors.request.use(async e=>{const t=new q,n=t.config.token;return n?(e.headers.Authorization=`Bearer ${n}`,await Be(n,t.config.env),e.baseURL=F.api,e):Promise.reject(b.UNINITIALIZED)},e=>Promise.reject(e));G.interceptors.response.use(e=>e.data?.code!==200?Promise.reject(e):Promise.resolve(e.data),e=>Promise.reject(e));function pr(){return F.api}function me(){return F.download}function mr(){return F.ws}const Er=e=>G.post("/api/open-auth/obs/v1/ObsService/GetObsAuthInfo",e),Sr=async e=>{const t=me();return T.post(`${t}`,e,{headers:{"Content-Type":"multipart/form-data"}})},Tr=async(e,t)=>T.put(t,e,{headers:{"Content-Type":e.type}}),wr=e=>G.post("/api/open-auth/open_consultation/v1/OpenConsultationService/GetConsultationList",e),Rr=e=>G.get("/api/open-auth/faq/v1/FaqService/GetFaqList",{params:e}),yr=()=>G.get("/api/open-auth/user/v1/UserService/GetUserInfo"),Ar=e=>G.post("/api/open-auth/user/v1/UserService/GetUserHistoryMessages",e),br=e=>{const n=new q().config.env,r=pr()||Ie[n].BASE_API_URL;return T.post(`${r}/api/open-auth/openAuth/v1/OpenAuthService/AnonymousAuth`,e)},Nr=e=>G.get("/api/chat/chat/v1/Chat/GetMsg",{params:e});var v=(e=>(e.SEND="1",e.WITHDRAW="2",e.EDIT="3",e.SYSTEM_NOTICE="4",e.TRANSFER="5",e.INBOUND="6",e.REPLY="7",e.UNBIND="8",e))(v||{}),H=(e=>(e.TEXT="1",e.IMAGE="2",e.VIDEO="3",e.FILE="4",e.FAQ="5",e))(H||{}),C=(e=>(e[e.CONNECT_SUCCESS=200]="CONNECT_SUCCESS",e[e.CONNECT_FAILED=40001]="CONNECT_FAILED",e[e.TRANSFER_CUSTOMER_SUCCESS=201]="TRANSFER_CUSTOMER_SUCCESS",e[e.TRANSFER_TO_CUSTOMER_SUCCESS=202]="TRANSFER_TO_CUSTOMER_SUCCESS",e[e.TRANSFER_USER_SUCCESS=203]="TRANSFER_USER_SUCCESS",e[e.TRANSFER_FAIL=50001]="TRANSFER_FAIL",e[e.MATCH_FAIL=50002]="MATCH_FAIL",e[e.MATCH_INFO=50005]="MATCH_INFO",e[e.MATCH_SUCCESS=50006]="MATCH_SUCCESS",e[e.RETRACT=204]="RETRACT",e[e.RETRACT_FAIL=50003]="RETRACT_FAIL",e[e.EDIT=205]="EDIT",e[e.EDIT_FAIL=50004]="EDIT_FAIL",e[e.COMMON_FAIL=5e4]="COMMON_FAIL",e[e.SEND_SUCCESS=206]="SEND_SUCCESS",e[e.SEND_CALLBACK=207]="SEND_CALLBACK",e[e.CHANGE_CHAT_STATUS=208]="CHANGE_CHAT_STATUS",e[e.REPLY_FAIL=50008]="REPLY_FAIL",e[e.REPLY_SUCCESS=209]="REPLY_SUCCESS",e[e.UNBIND_SUCCESS=60006]="UNBIND_SUCCESS",e[e.BAN_CUSTOMER=60007]="BAN_CUSTOMER",e[e.BAN_ENTRY=60008]="BAN_ENTRY",e[e.REMATCH=60001]="REMATCH",e))(C||{}),Ee=(e=>(e.CUSTOMER="1",e.USER="2",e.ANONYMOUS="3",e))(Ee||{}),A=(e=>(e.CONNECTED="connected",e.DISCONNECTED="disconnected",e.ERROR="error",e.MESSAGE="message",e.STATUS_CHANGE="status_change",e.HEARTBEAT_TIMEOUT="heartbeat_timeout",e))(A||{}),O=(e=>(e.DISCONNECTED="disconnected",e.CONNECTING="connecting",e.CONNECTED="connected",e.RECONNECTING="reconnecting",e.ERROR="error",e))(O||{}),N=(e=>(e.UNMATCHED="1",e.MATCHING="2",e.MATCHED="3",e.UNBIND="4",e))(N||{});class Or{events=new Map;on(t,n){this.events.has(t)||this.events.set(t,[]),this.events.get(t).push(n)}off(t,n){const r=this.events.get(t);if(r){const s=r.indexOf(n);s>-1&&r.splice(s,1)}}emit(t,n){const r=this.events.get(t);r&&r.forEach(s=>{try{s(n)}catch(o){console.error(`事件回调执行错误 [${t}]:`,o)}})}removeAllListeners(t){t?this.events.delete(t):this.events.clear()}once(t,n){const r=s=>{n(s),this.off(t,r)};this.on(t,r)}}async function gr(e,t){return await Be(e,t),`${await mr()}/api/ws?Authorization=${e}`}function Cr(){return"web"+Date.now().toString(36)+Math.random().toString(36).slice(2)}function Ur(e){return typeof e=="object"&&e!==null&&"data"in e&&"msgType"in e&&"toUid"in e&&"chatType"in e&&"code"in e}function ot(e){return e.customerServiceAvatar=$(e.customerServiceAvatar),e.userAvatar=$(e.customerServiceAvatar),e.contentType!==H.TEXT&&(e.content=JSON.parse(e.content),e.content.fileUrl=$(e.content.fileUrl),e.content.thumbnailUrl=$(e.content.thumbnailUrl)),e.replyType&&e.replyType!==H.TEXT&&typeof e.replyContent=="string"&&(e.replyContent=JSON.parse(e.replyContent),e.replyContent.fileUrl=$(e.replyContent.fileUrl),e.replyContent.thumbnailUrl=$(e.replyContent.thumbnailUrl)),e}function $(e=""){return e&&!e.startsWith("http")?me()+"/"+e:e}class q extends Or{config={token:"",autoReconnect:!0,reconnectInterval:3e3,maxReconnectAttempts:5,responseTimeout:15e3,env:"production"};ws=null;status=O.DISCONNECTED;reconnectTimer=null;reconnectAttempts=0;heartbeatTimeoutTimer=null;lastHeartbeatTime=0;consultationTypeId="";sessionData=null;userInfo=null;static instance=null;matchStatus=N.UNMATCHED;constructor({env:t="production"}={}){if(super(),q.instance)return q.instance;q.instance=this,this.config.env=t}async init(t){if(!t.token)return Promise.reject(b.PARAMETER_ERROR);await Be(t.token,this.config.env),this.config=Object.assign(this.config,t)}connect(t){return this.consultationTypeId=t,new Promise(async(n,r)=>{if(!this.config.token)return r(b.UNINITIALIZED);if(this.status===O.CONNECTED)return n();if(this.status!==O.CONNECTING){this.setStatus(O.CONNECTING);try{const s=await gr(this.config.token,this.config.env);this.ws=new WebSocket(s),this.ws.onopen=()=>{this.reconnectAttempts=0,this.setStatus(O.CONNECTED),this.emit(A.CONNECTED),n()},this.ws.onmessage=o=>{try{this.handleMessage(o.data)}catch(i){throw console.error("解析消息失败:",i),b.DATA_PARSING_ERROR}},this.ws.onerror=o=>{console.error("连接错误:",o),this.setStatus(O.ERROR),this.emit(A.ERROR,o),r(o)},this.ws.onclose=()=>{this.config.env==="development"&&console.warn("连接断开",new Date().toISOString()),this.setStatus(O.DISCONNECTED),this.emit(A.DISCONNECTED),this.heartbeatTimeoutTimer&&(clearTimeout(this.heartbeatTimeoutTimer),this.heartbeatTimeoutTimer=null),this.config.autoReconnect&&this.reconnectAttempts<this.config.maxReconnectAttempts&&this.scheduleReconnect()}}catch(s){this.setStatus(O.ERROR),this.emit(A.ERROR,s),r(s)}}})}disconnect(){this.config.autoReconnect=!1,this.sessionData=null,this.matchStatus=N.UNMATCHED,this.clearReconnectTimer(),this.heartbeatTimeoutTimer&&(clearTimeout(this.heartbeatTimeoutTimer),this.heartbeatTimeoutTimer=null),this.ws&&(this.ws.close(),this.ws=null),this.setStatus(O.DISCONNECTED)}async sendMessage(t,n,r=v.SEND){const s={msgType:r,data:t,toUid:this.sessionData?.cid,chatType:n,editId:void 0};if(this.status!==O.CONNECTED||!this.ws)if(this.ws&&this.status===O.DISCONNECTED){console.log("连接断开,尝试重新连接");try{await this.connect(this.consultationTypeId)}catch(o){throw console.error("重连失败:",o),b.DISCONNECTED}}else throw console.error(b.DISCONNECTED),b.DISCONNECTED;try{if(!this.ws)throw b.DISCONNECTED;return r===v.SEND?new Promise(async(o,i)=>{const c=Cr();s.ext=c;const d=await Nr({ext:c});d.data?.messageId?(this.ws.send(JSON.stringify(s)),o({messageId:d.data.messageId,data:t})):i(b.MESSAGE_SEND_FAIL)}):(this.ws.send(JSON.stringify(s)),{data:t})}catch(o){throw console.error("发送消息失败:",o),b.MESSAGE_SEND_FAIL}}async checkMatchStatus(){if(this.matchStatus===N.UNBIND&&(await this.sendMessage(this.consultationTypeId,void 0,v.INBOUND),await new Promise((t,n)=>{const r=setTimeout(()=>{clearTimeout(r),n(b.MESSAGE_SEND_FAIL)},this.config.responseTimeout);this.once(A.MESSAGE,s=>{s.code===C.REMATCH&&(clearTimeout(r),t(!0))})})),this.matchStatus!==N.MATCHED)throw console.error(b.NO_CUSTOMER_SERVICE),b.NO_CUSTOMER_SERVICE}async sendText(t){return await this.checkMatchStatus(),this.sendMessage(t,H.TEXT)}async sendFile({file:t,thumbnailFile:n,chatType:r}){try{await this.checkMatchStatus();const[s,o]=await Promise.all([this.handleUploadFile(t),n?this.handleUploadFile(n):Promise.resolve(void 0)]),i={fileName:t.name,fileUrl:s,thumbnailUrl:o,fileSize:t.size},{messageId:c}=await this.sendMessage(JSON.stringify(i),r),d=me();return{messageId:c,content:{fileName:t.name,fileUrl:`${d}/${s}`,thumbnailUrl:o?`${d}/${o}`:void 0,fileSize:t.size}}}catch(s){throw console.error("上传文件失败:",s),s}}getStatus(){return this.status}isConnected(){return this.status===O.CONNECTED}handleMessage(t){if(t==="ping"){this.lastHeartbeatTime=Date.now(),this.heartbeatTimeoutTimer&&(clearTimeout(this.heartbeatTimeoutTimer),this.heartbeatTimeoutTimer=null),this.sendHeartbeat();return}if(t=JSON.parse(t),!!Ur(t))try{const n=t.data?JSON.parse(t.data):t.data;switch(t.data=n,t.code){case C.CONNECT_SUCCESS:this.matchStatus===N.MATCHED||this.matchStatus===N.MATCHING?this.matchStatus=N.UNBIND:this.matchStatus=N.MATCHING,this.sendMessage(this.consultationTypeId,void 0,v.INBOUND);break;case C.MATCH_INFO:case C.MATCH_SUCCESS:if(this.matchStatus===N.MATCHED)return;t.data.customerAvatar=$(t.data.customerAvatar),this.sessionData=t.data,this.matchStatus===N.UNBIND?(this.matchStatus=N.MATCHED,this.emit(A.MESSAGE,{...t,code:C.REMATCH})):(this.matchStatus=N.MATCHED,this.getFaqList(),this.emit(A.MESSAGE,t));break;case C.TRANSFER_USER_SUCCESS:if(n.oldSessionId!==this.sessionData?.sessionId)return;const r=t.data;this.sessionData={...this.sessionData,cid:String(r.cid),customerAvatar:r.customerAvatar,customerName:r.customerName,groupId:r.groupId,sessionId:r.sessionId},this.emit(A.MESSAGE,t);break;case C.SEND_SUCCESS:case C.EDIT:case C.REPLY_SUCCESS:const s=t.data;if(s.sessionId!==this.sessionData?.sessionId)return;ot(s),this.emit(A.MESSAGE,t);break;case C.SEND_CALLBACK:const o=t.ext,c=t.data.messageId;this.emit(o,c);break;case C.UNBIND_SUCCESS:if(n.sessionId!==this.sessionData?.sessionId)return;this.matchStatus=N.UNBIND,this.sessionData=null,this.emit(A.MESSAGE,t);break;default:this.emit(A.MESSAGE,t);break}}catch(n){console.error("解析消息失败:",n)}}setStatus(t){this.status!==t&&(this.status=t,this.emit(A.STATUS_CHANGE,t))}scheduleReconnect(){this.config.env==="development"&&console.warn(`第${this.reconnectAttempts+1}次安排重连`,new Date().toISOString()),this.clearReconnectTimer(),this.reconnectAttempts++,this.setStatus(O.RECONNECTING),this.reconnectTimer=setTimeout(()=>{this.connect(this.consultationTypeId).catch(t=>{console.error("重连失败:",t)})},this.config.reconnectInterval)}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}sendHeartbeat(){if(!(this.status!==O.CONNECTED||!this.ws))try{this.ws.send("pong"),this.lastHeartbeatTime=Date.now(),this.heartbeatTimeoutTimer=setTimeout(()=>{Date.now()-this.lastHeartbeatTime>=this.config.responseTimeout&&(this.emit(A.HEARTBEAT_TIMEOUT),this.config.env==="development"&&console.warn("心跳超时,尝试重连",new Date().toISOString()),this.ws&&this.ws.close())},this.config.responseTimeout)}catch(t){console.error("发送心跳失败:",t)}}async getHistoryMessages({lastMsgId:t,size:n=50}){if(this.matchStatus!==N.MATCHED)return Promise.reject(b.NO_CUSTOMER_SERVICE);const r=await Ar({sessionId:this.sessionData?.sessionId,lastMsgId:t,size:n}),s=r.data.list.map(o=>ot(o));return{hasMore:r.data.hasMore,list:s}}async getConsultationList(t){return(await wr({entranceId:t})).data}handleUploadFile(t){return new Promise(async(n,r)=>{const s=t.name.split(".").pop(),o=await Er({ext:s||""}),{accessKeyId:i,signature:c,policy:d,key:u,maxLimit:l,url:h}=o.data;if(t.size>l*1024*1024)return r(`文件大小不能超过${l}MB`);if(h){const S=await Tr(t,h);S.status===200?n(`${u}`):r(S.data)}else{const S=new FormData;S.append("key",u),S.append("AccessKeyId",i),S.append("signature",c),S.append("policy",d),S.append("file",t);const w=await Sr(S);w.status===204?n(`${u}`):r(w.data)}})}getVideoThumbnail=t=>new Promise((n,r)=>{const s=document.createElement("video"),o=document.createElement("canvas"),i=o.getContext("2d");if(!i){r(new Error("无法创建 canvas 上下文"));return}const c=URL.createObjectURL(t);s.preload="metadata",s.src=c,s.muted=!0,s.playsInline=!0,s.addEventListener("loadeddata",()=>{o.width=s.videoWidth,o.height=s.videoHeight,s.currentTime=0}),s.addEventListener("seeked",()=>{try{i.drawImage(s,0,0,o.width,o.height),o.toBlob(d=>{if(URL.revokeObjectURL(c),s.remove(),!d){r(b.FILE_PARSING_ERROR);return}const u=t.name.replace(/\.[^/.]+$/,"")+"_thumb.jpg",l=new File([d],u,{type:"image/jpeg",lastModified:Date.now()});n(l)},"image/jpeg",.6)}catch(d){URL.revokeObjectURL(c),s.remove(),r(d)}}),s.addEventListener("error",()=>{URL.revokeObjectURL(c),s.remove(),r(b.FILE_PARSING_ERROR)}),s.load()});async getFaqList(){if(this.matchStatus!==N.MATCHED)return Promise.reject(b.NO_CUSTOMER_SERVICE);const t=await Rr({id:this.sessionData?.cid});if(!t.data?.topic?.length)return;const n={guideText:t.data.guideText,list:t.data.topic.map(r=>({...r,question:r.question}))};setTimeout(()=>{const r={code:C.SEND_SUCCESS,data:{content:n,contentType:H.FAQ,sendUserType:Ee.CUSTOMER,customerServiceAvatar:this.sessionData?.customerAvatar,customerServiceName:this.sessionData?.customerName,createTime:Date.now(),msgType:v.SEND},msgType:v.SEND,chatType:H.FAQ};this.emit(A.MESSAGE,r)},t.data.showDelaySeconds*1e3)}sendFaq(t){const n={code:C.SEND_SUCCESS,data:{sendUserType:Ee.CUSTOMER,customerServiceAvatar:this.sessionData?.customerAvatar,customerServiceName:this.sessionData?.customerName,createTime:Date.now(),msgType:v.SEND,contentType:H.FAQ,content:{}},msgType:v.SEND,chatType:H.FAQ};if(t.isMulti)n.data.content={list:t.item},this.emit(A.MESSAGE,n);else{const r=t.item?.[0]||t,s=me();r.imageUrl=r.imageUrl?.map(o=>o?.startsWith("http")?o:`${s}/${o}`),n.data.content={answer:r},this.emit(A.MESSAGE,n)}}async getUserInfo(){if(this.userInfo)return this.userInfo;const t=await yr();return t.data.avatar=$(t.data.avatar),this.userInfo=t.data,this.userInfo}async anonymousLogin(t,n){return(await br({appKey:t,entranceId:n,userSource:"H5"})).data}}exports.ChatType=H;exports.ConnectionStatus=O;exports.EventType=A;exports.JoyTalk=q;exports.MatchStatus=N;exports.MessageCode=C;exports.MessageType=v;exports.SendUserType=Ee;exports.default=q;
|