joytalk 0.0.35 → 0.0.36
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 +1 -1
- package/dist/index.es.js +52 -52
- package/dist/index.umd.js +5 -5
- package/package.json +1 -1
package/dist/index.cjs.js
CHANGED
|
@@ -3,4 +3,4 @@
|
|
|
3
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 yt(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 Rt(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=O.hasStandardBrowserEnv?((e,t)=>n=>(n=new URL(n,O.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new URL(O.origin),O.navigator&&/(msie|trident)/i.test(O.navigator.userAgent)):()=>!0,$n=O.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(O.hasStandardBrowserEnv||O.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(O.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 y(){if(!p)return;const R=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:R,config:e,request:p};Rt(function(L){n(L),m()},function(L){r(L),m()},P),p=null}"onloadend"in p?p.onloadend=y:p.onreadystatechange=function(){!p||p.readyState!==4||p.status===0&&!(p.responseURL&&p.responseURL.indexOf("file:")===0)||setTimeout(y)},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=R=>{p&&(r(!R||R.type?new Z(null,e,p):R),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&&O.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(O.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 y=m&&m[f];if(y)return y.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(O.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:y,signal:I,cancelToken:R,timeout:U,onDownloadProgress:P,onUploadProgress:G,responseType:L,headers:Re,withCredentials:ie="same-origin",fetchOptions:Be}=bt(f),ke=t||fetch;L=L?(L+"").toLowerCase():"text";let ae=Wn([I,R&&R.toAbortSignal()],U),ee=null;const z=ae&&ae.unsubscribe&&(()=>{ae.unsubscribe()});let He;try{if(G&&u&&p!=="get"&&p!=="head"&&(He=await w(Re,y))!==0){let M=new n(m,{method:"POST",body:y,duplex:"half"}),K;if(a.isFormData(y)&&(K=M.headers.get("content-type"))&&Re.setContentType(K),M.body){const[Ae,ce]=We(He,he(Ve(G)));y=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:Re.normalize().toJSON(),body:y,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)=>{Rt(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
4
|
`+i.map(tt).join(`
|
|
5
5
|
`):" "+tt(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:tr,adapters:Pe};function ge(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Z(null,e)}function nt(e){return ge(e),e.headers=D.from(e.headers),e.data=Ne.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),gt.getAdapter(e.adapter||oe.adapter,e)(e).then(function(r){return ge(e),r.data=Ne.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=Ne.call(e,e.transformResponse,r.response),r.response.headers=D.from(r.response.headers))),Promise.reject(r)})}const Ot="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 rt={};ye.transitional=function(t,n,r){function s(o,i){return"[Axios v"+Ot+"] 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&&!rt[i]&&(rt[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 nr(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 de={assertOptions:nr,validators:ye},k=de.validators;let W=class{constructor(t){this.defaults=t||{},this.interceptors={request:new ze,response:new ze}}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=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=yt;T.VERSION=Ot;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=gt.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}),yr=()=>q.get("/api/open-auth/user/v1/UserService/GetUserInfo"),Rr=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.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||{}),g=(e=>(e.DISCONNECTED="disconnected",e.CONNECTING="connecting",e.CONNECTED="connected",e.RECONNECTING="reconnecting",e.ERROR="error",e))(g||{}),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 gr(e,t){return await xe(e,t),`${await pr()}/api/ws?Authorization=${e}`}function Or(){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=g.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===g.CONNECTED)return n();if(this.status!==g.CONNECTING){this.setStatus(g.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(g.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(g.ERROR),this.emit(A.ERROR,o),r(o)},this.ws.onclose=()=>{this.config.env==="development"&&console.warn("连接断开",new Date().toISOString()),this.setStatus(g.DISCONNECTED),this.emit(A.DISCONNECTED),this.config.autoReconnect&&this.reconnectAttempts<this.config.maxReconnectAttempts&&this.scheduleReconnect()}}catch(s){this.setStatus(g.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(g.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!==g.CONNECTED||!this.ws)if(this.ws&&this.status===g.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=Or();s.ext=c;const d=await br({ext:c});console.log("🚀 ~ JoyTalk ~ sendMessage ~ res:",d.data.messageId),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===g.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("安排重连",new Date().toISOString()),this.clearReconnectTimer(),this.reconnectAttempts++,this.setStatus(g.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!==g.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 Rr({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 yr();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=g;exports.EventType=A;exports.JoyTalk=$;exports.MatchStatus=N;exports.MessageCode=C;exports.MessageType=H;exports.SendUserType=me;exports.default=$;
|
|
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=yt;T.VERSION=Ot;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=gt.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}),yr=()=>q.get("/api/open-auth/user/v1/UserService/GetUserInfo"),Rr=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.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||{}),g=(e=>(e.DISCONNECTED="disconnected",e.CONNECTING="connecting",e.CONNECTED="connected",e.RECONNECTING="reconnecting",e.ERROR="error",e))(g||{}),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 gr(e,t){return await xe(e,t),`${await pr()}/api/ws?Authorization=${e}`}function Or(){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=g.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===g.CONNECTED)return n();if(this.status!==g.CONNECTING){this.setStatus(g.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(g.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(g.ERROR),this.emit(A.ERROR,o),r(o)},this.ws.onclose=()=>{this.config.env==="development"&&console.warn("连接断开",new Date().toISOString()),this.setStatus(g.DISCONNECTED),this.emit(A.DISCONNECTED),this.config.autoReconnect&&this.reconnectAttempts<this.config.maxReconnectAttempts&&this.scheduleReconnect()}}catch(s){this.setStatus(g.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(g.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!==g.CONNECTED||!this.ws)if(this.ws&&this.status===g.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=Or();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===g.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("安排重连",new Date().toISOString()),this.clearReconnectTimer(),this.reconnectAttempts++,this.setStatus(g.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!==g.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 Rr({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 yr();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=g;exports.EventType=A;exports.JoyTalk=$;exports.MatchStatus=N;exports.MessageCode=C;exports.MessageType=H;exports.SendUserType=me;exports.default=$;
|
package/dist/index.es.js
CHANGED
|
@@ -61,10 +61,10 @@ function lt(e, t) {
|
|
|
61
61
|
return null;
|
|
62
62
|
}
|
|
63
63
|
const z = typeof globalThis < "u" ? globalThis : typeof self < "u" ? self : typeof window < "u" ? window : global, ut = (e) => !Y(e) && e !== z;
|
|
64
|
-
function
|
|
64
|
+
function Oe() {
|
|
65
65
|
const { caseless: e, skipUndefined: t } = ut(this) && this || {}, n = {}, r = (s, o) => {
|
|
66
66
|
const i = e && lt(n, o) || o;
|
|
67
|
-
ue(n[i]) && ue(s) ? n[i] =
|
|
67
|
+
ue(n[i]) && ue(s) ? n[i] = Oe(n[i], s) : ue(s) ? n[i] = Oe({}, s) : Q(s) ? n[i] = s.slice() : (!t || !Y(s)) && (n[i] = s);
|
|
68
68
|
};
|
|
69
69
|
for (let s = 0, o = arguments.length; s < o; s++)
|
|
70
70
|
arguments[s] && se(arguments[s], r);
|
|
@@ -203,7 +203,7 @@ const fn = (e) => {
|
|
|
203
203
|
isTypedArray: Zt,
|
|
204
204
|
isFileList: Ht,
|
|
205
205
|
forEach: se,
|
|
206
|
-
merge:
|
|
206
|
+
merge: Oe,
|
|
207
207
|
extend: Wt,
|
|
208
208
|
trim: Jt,
|
|
209
209
|
stripBOM: Vt,
|
|
@@ -289,7 +289,7 @@ E.from = (e, t, n, r, s, o) => {
|
|
|
289
289
|
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;
|
|
290
290
|
};
|
|
291
291
|
const En = null;
|
|
292
|
-
function
|
|
292
|
+
function ge(e) {
|
|
293
293
|
return a.isPlainObject(e) || a.isArray(e);
|
|
294
294
|
}
|
|
295
295
|
function mt(e) {
|
|
@@ -301,7 +301,7 @@ function qe(e, t, n) {
|
|
|
301
301
|
}).join(n ? "." : "") : t;
|
|
302
302
|
}
|
|
303
303
|
function Sn(e) {
|
|
304
|
-
return a.isArray(e) && !e.some(
|
|
304
|
+
return a.isArray(e) && !e.some(ge);
|
|
305
305
|
}
|
|
306
306
|
const wn = a.toFlatObject(a, {}, null, function(t) {
|
|
307
307
|
return /^is[A-Z]/.test(t);
|
|
@@ -343,12 +343,12 @@ function we(e, t, n) {
|
|
|
343
343
|
);
|
|
344
344
|
}), !1;
|
|
345
345
|
}
|
|
346
|
-
return
|
|
346
|
+
return ge(f) ? !0 : (t.append(qe(p, m, o), u(f)), !1);
|
|
347
347
|
}
|
|
348
348
|
const h = [], S = Object.assign(wn, {
|
|
349
349
|
defaultVisitor: l,
|
|
350
350
|
convertValue: u,
|
|
351
|
-
isVisitable:
|
|
351
|
+
isVisitable: ge
|
|
352
352
|
});
|
|
353
353
|
function T(f, m) {
|
|
354
354
|
if (!a.isUndefined(f)) {
|
|
@@ -482,22 +482,22 @@ const wt = {
|
|
|
482
482
|
Blob: An
|
|
483
483
|
},
|
|
484
484
|
protocols: ["http", "https", "file", "blob", "url", "data"]
|
|
485
|
-
}, Fe = typeof window < "u" && typeof document < "u", Ce = typeof navigator == "object" && navigator || void 0, Nn = Fe && (!Ce || ["ReactNative", "NativeScript", "NS"].indexOf(Ce.product) < 0),
|
|
486
|
-
self instanceof WorkerGlobalScope && typeof self.importScripts == "function",
|
|
485
|
+
}, Fe = typeof window < "u" && typeof document < "u", Ce = typeof navigator == "object" && navigator || void 0, Nn = Fe && (!Ce || ["ReactNative", "NativeScript", "NS"].indexOf(Ce.product) < 0), On = typeof WorkerGlobalScope < "u" && // eslint-disable-next-line no-undef
|
|
486
|
+
self instanceof WorkerGlobalScope && typeof self.importScripts == "function", gn = Fe && window.location.href || "http://localhost", Cn = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
|
|
487
487
|
__proto__: null,
|
|
488
488
|
hasBrowserEnv: Fe,
|
|
489
489
|
hasStandardBrowserEnv: Nn,
|
|
490
|
-
hasStandardBrowserWebWorkerEnv:
|
|
490
|
+
hasStandardBrowserWebWorkerEnv: On,
|
|
491
491
|
navigator: Ce,
|
|
492
|
-
origin:
|
|
493
|
-
}, Symbol.toStringTag, { value: "Module" })),
|
|
492
|
+
origin: gn
|
|
493
|
+
}, Symbol.toStringTag, { value: "Module" })), O = {
|
|
494
494
|
...Cn,
|
|
495
495
|
...bn
|
|
496
496
|
};
|
|
497
497
|
function Un(e, t) {
|
|
498
|
-
return we(e, new
|
|
498
|
+
return we(e, new O.classes.URLSearchParams(), {
|
|
499
499
|
visitor: function(n, r, s, o) {
|
|
500
|
-
return
|
|
500
|
+
return O.isNode && a.isBuffer(n) ? (this.append(r, n.toString("base64")), !1) : o.defaultVisitor.apply(this, arguments);
|
|
501
501
|
},
|
|
502
502
|
...t
|
|
503
503
|
});
|
|
@@ -592,8 +592,8 @@ const oe = {
|
|
|
592
592
|
maxContentLength: -1,
|
|
593
593
|
maxBodyLength: -1,
|
|
594
594
|
env: {
|
|
595
|
-
FormData:
|
|
596
|
-
Blob:
|
|
595
|
+
FormData: O.classes.FormData,
|
|
596
|
+
Blob: O.classes.Blob
|
|
597
597
|
},
|
|
598
598
|
validateStatus: function(t) {
|
|
599
599
|
return t >= 200 && t < 300;
|
|
@@ -893,10 +893,10 @@ const he = (e, t, n = 3) => {
|
|
|
893
893
|
total: e,
|
|
894
894
|
loaded: r
|
|
895
895
|
}), t[1]];
|
|
896
|
-
}, Ve = (e) => (...t) => a.asap(() => e(...t)), Mn =
|
|
897
|
-
new URL(
|
|
898
|
-
|
|
899
|
-
) : () => !0, $n =
|
|
896
|
+
}, Ve = (e) => (...t) => a.asap(() => e(...t)), Mn = O.hasStandardBrowserEnv ? /* @__PURE__ */ ((e, t) => (n) => (n = new URL(n, O.origin), e.protocol === n.protocol && e.host === n.host && (t || e.port === n.port)))(
|
|
897
|
+
new URL(O.origin),
|
|
898
|
+
O.navigator && /(msie|trident)/i.test(O.navigator.userAgent)
|
|
899
|
+
) : () => !0, $n = O.hasStandardBrowserEnv ? (
|
|
900
900
|
// Standard browser envs support document.cookie
|
|
901
901
|
{
|
|
902
902
|
write(e, t, n, r, s, o, i) {
|
|
@@ -1007,7 +1007,7 @@ const bt = (e) => {
|
|
|
1007
1007
|
"Authorization",
|
|
1008
1008
|
"Basic " + btoa((c.username || "") + ":" + (c.password ? unescape(encodeURIComponent(c.password)) : ""))
|
|
1009
1009
|
), a.isFormData(n)) {
|
|
1010
|
-
if (
|
|
1010
|
+
if (O.hasStandardBrowserEnv || O.hasStandardBrowserWebWorkerEnv)
|
|
1011
1011
|
i.setContentType(void 0);
|
|
1012
1012
|
else if (a.isFunction(n.getHeaders)) {
|
|
1013
1013
|
const d = n.getHeaders(), u = ["content-type", "content-length"];
|
|
@@ -1016,7 +1016,7 @@ const bt = (e) => {
|
|
|
1016
1016
|
});
|
|
1017
1017
|
}
|
|
1018
1018
|
}
|
|
1019
|
-
if (
|
|
1019
|
+
if (O.hasStandardBrowserEnv && (r && a.isFunction(r) && (r = r(t)), r || r !== !1 && Mn(t.url))) {
|
|
1020
1020
|
const d = s && o && $n.read(o);
|
|
1021
1021
|
d && i.set(s, d);
|
|
1022
1022
|
}
|
|
@@ -1073,7 +1073,7 @@ const bt = (e) => {
|
|
|
1073
1073
|
p && (r(!y || y.type ? new Z(null, e, p) : y), p.abort(), p = null);
|
|
1074
1074
|
}, s.cancelToken && s.cancelToken.subscribe(l), s.signal && (s.signal.aborted ? l() : s.signal.addEventListener("abort", l)));
|
|
1075
1075
|
const I = Hn(s.url);
|
|
1076
|
-
if (I &&
|
|
1076
|
+
if (I && O.protocols.indexOf(I) === -1) {
|
|
1077
1077
|
r(new E("Unsupported protocol " + I + ":", E.ERR_BAD_REQUEST, e));
|
|
1078
1078
|
return;
|
|
1079
1079
|
}
|
|
@@ -1180,7 +1180,7 @@ const bt = (e) => {
|
|
|
1180
1180
|
return !1;
|
|
1181
1181
|
const c = s && le(Qe), d = s && (typeof Ze == "function" ? /* @__PURE__ */ ((f) => (m) => f.encode(m))(new Ze()) : async (f) => new Uint8Array(await new n(f).arrayBuffer())), u = o && c && et(() => {
|
|
1182
1182
|
let f = !1;
|
|
1183
|
-
const m = new n(
|
|
1183
|
+
const m = new n(O.origin, {
|
|
1184
1184
|
body: new Qe(),
|
|
1185
1185
|
method: "POST",
|
|
1186
1186
|
get duplex() {
|
|
@@ -1205,7 +1205,7 @@ const bt = (e) => {
|
|
|
1205
1205
|
if (a.isBlob(f))
|
|
1206
1206
|
return f.size;
|
|
1207
1207
|
if (a.isSpecCompliantForm(f))
|
|
1208
|
-
return (await new n(
|
|
1208
|
+
return (await new n(O.origin, {
|
|
1209
1209
|
method: "POST",
|
|
1210
1210
|
body: f
|
|
1211
1211
|
}).arrayBuffer()).byteLength;
|
|
@@ -1361,7 +1361,7 @@ function tr(e, t) {
|
|
|
1361
1361
|
}
|
|
1362
1362
|
return s;
|
|
1363
1363
|
}
|
|
1364
|
-
const
|
|
1364
|
+
const Ot = {
|
|
1365
1365
|
/**
|
|
1366
1366
|
* Resolve an adapter from a list of adapter names or functions.
|
|
1367
1367
|
* @type {Function}
|
|
@@ -1381,7 +1381,7 @@ function nt(e) {
|
|
|
1381
1381
|
return Ne(e), e.headers = D.from(e.headers), e.data = be.call(
|
|
1382
1382
|
e,
|
|
1383
1383
|
e.transformRequest
|
|
1384
|
-
), ["post", "put", "patch"].indexOf(e.method) !== -1 && e.headers.setContentType("application/x-www-form-urlencoded", !1),
|
|
1384
|
+
), ["post", "put", "patch"].indexOf(e.method) !== -1 && e.headers.setContentType("application/x-www-form-urlencoded", !1), Ot.getAdapter(e.adapter || oe.adapter, e)(e).then(function(r) {
|
|
1385
1385
|
return Ne(e), r.data = be.call(
|
|
1386
1386
|
e,
|
|
1387
1387
|
e.transformResponse,
|
|
@@ -1395,7 +1395,7 @@ function nt(e) {
|
|
|
1395
1395
|
), r.response.headers = D.from(r.response.headers))), Promise.reject(r);
|
|
1396
1396
|
});
|
|
1397
1397
|
}
|
|
1398
|
-
const
|
|
1398
|
+
const gt = "1.13.2", Te = {};
|
|
1399
1399
|
["object", "boolean", "number", "function", "string", "symbol"].forEach((e, t) => {
|
|
1400
1400
|
Te[e] = function(r) {
|
|
1401
1401
|
return typeof r === e || "a" + (t < 1 ? "n " : " ") + e;
|
|
@@ -1404,7 +1404,7 @@ const Ot = "1.13.2", Te = {};
|
|
|
1404
1404
|
const rt = {};
|
|
1405
1405
|
Te.transitional = function(t, n, r) {
|
|
1406
1406
|
function s(o, i) {
|
|
1407
|
-
return "[Axios v" +
|
|
1407
|
+
return "[Axios v" + gt + "] Transitional option '" + o + "'" + i + (r ? ". " + r : "");
|
|
1408
1408
|
}
|
|
1409
1409
|
return (o, i, c) => {
|
|
1410
1410
|
if (t === !1)
|
|
@@ -1734,7 +1734,7 @@ w.Axios = J;
|
|
|
1734
1734
|
w.CanceledError = Z;
|
|
1735
1735
|
w.CancelToken = rr;
|
|
1736
1736
|
w.isCancel = Rt;
|
|
1737
|
-
w.VERSION =
|
|
1737
|
+
w.VERSION = gt;
|
|
1738
1738
|
w.toFormData = we;
|
|
1739
1739
|
w.AxiosError = E;
|
|
1740
1740
|
w.Cancel = w.CanceledError;
|
|
@@ -1746,7 +1746,7 @@ w.isAxiosError = or;
|
|
|
1746
1746
|
w.mergeConfig = W;
|
|
1747
1747
|
w.AxiosHeaders = D;
|
|
1748
1748
|
w.formToJSON = (e) => Tt(a.isHTMLForm(e) ? new FormData(e) : e);
|
|
1749
|
-
w.getAdapter =
|
|
1749
|
+
w.getAdapter = Ot.getAdapter;
|
|
1750
1750
|
w.HttpStatusCode = Ue;
|
|
1751
1751
|
w.default = w;
|
|
1752
1752
|
const {
|
|
@@ -1939,7 +1939,7 @@ const mr = (e) => $.post(
|
|
|
1939
1939
|
params: e
|
|
1940
1940
|
}
|
|
1941
1941
|
);
|
|
1942
|
-
var H = /* @__PURE__ */ ((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 || {}), M = /* @__PURE__ */ ((e) => (e.TEXT = "1", e.IMAGE = "2", e.VIDEO = "3", e.FILE = "4", e.FAQ = "5", e))(M || {}), U = /* @__PURE__ */ ((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.REMATCH = 60001] = "REMATCH", e))(U || {}), De = /* @__PURE__ */ ((e) => (e.CUSTOMER = "1", e.USER = "2", e.ANONYMOUS = "3", e))(De || {}), b = /* @__PURE__ */ ((e) => (e.CONNECTED = "connected", e.DISCONNECTED = "disconnected", e.ERROR = "error", e.MESSAGE = "message", e.STATUS_CHANGE = "status_change", e.HEARTBEAT_TIMEOUT = "heartbeat_timeout", e))(b || {}),
|
|
1942
|
+
var H = /* @__PURE__ */ ((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 || {}), M = /* @__PURE__ */ ((e) => (e.TEXT = "1", e.IMAGE = "2", e.VIDEO = "3", e.FILE = "4", e.FAQ = "5", e))(M || {}), U = /* @__PURE__ */ ((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.REMATCH = 60001] = "REMATCH", e))(U || {}), De = /* @__PURE__ */ ((e) => (e.CUSTOMER = "1", e.USER = "2", e.ANONYMOUS = "3", e))(De || {}), b = /* @__PURE__ */ ((e) => (e.CONNECTED = "connected", e.DISCONNECTED = "disconnected", e.ERROR = "error", e.MESSAGE = "message", e.STATUS_CHANGE = "status_change", e.HEARTBEAT_TIMEOUT = "heartbeat_timeout", e))(b || {}), g = /* @__PURE__ */ ((e) => (e.DISCONNECTED = "disconnected", e.CONNECTING = "connecting", e.CONNECTED = "connected", e.RECONNECTING = "reconnecting", e.ERROR = "error", e))(g || {}), N = /* @__PURE__ */ ((e) => (e.UNMATCHED = "1", e.MATCHING = "2", e.MATCHED = "3", e.UNBIND = "4", e))(N || {});
|
|
1943
1943
|
class Nr {
|
|
1944
1944
|
events = /* @__PURE__ */ new Map();
|
|
1945
1945
|
/**
|
|
@@ -1996,10 +1996,10 @@ class Nr {
|
|
|
1996
1996
|
this.on(t, r);
|
|
1997
1997
|
}
|
|
1998
1998
|
}
|
|
1999
|
-
async function
|
|
1999
|
+
async function Or(e, t) {
|
|
2000
2000
|
return await xe(e, t), `${await pr()}/api/ws?Authorization=${e}`;
|
|
2001
2001
|
}
|
|
2002
|
-
function
|
|
2002
|
+
function gr() {
|
|
2003
2003
|
return "web" + Date.now().toString(36) + Math.random().toString(36).slice(2);
|
|
2004
2004
|
}
|
|
2005
2005
|
function Cr(e) {
|
|
@@ -2021,7 +2021,7 @@ class X extends Nr {
|
|
|
2021
2021
|
env: "production"
|
|
2022
2022
|
};
|
|
2023
2023
|
ws = null;
|
|
2024
|
-
status =
|
|
2024
|
+
status = g.DISCONNECTED;
|
|
2025
2025
|
reconnectTimer = null;
|
|
2026
2026
|
reconnectAttempts = 0;
|
|
2027
2027
|
/** 心跳超时定时器 */
|
|
@@ -2053,17 +2053,17 @@ class X extends Nr {
|
|
|
2053
2053
|
return this.consultationTypeId = t, new Promise(async (n, r) => {
|
|
2054
2054
|
if (!this.config.token)
|
|
2055
2055
|
return r(A.UNINITIALIZED);
|
|
2056
|
-
if (this.status ===
|
|
2056
|
+
if (this.status === g.CONNECTED)
|
|
2057
2057
|
return n();
|
|
2058
|
-
if (this.status !==
|
|
2059
|
-
this.setStatus(
|
|
2058
|
+
if (this.status !== g.CONNECTING) {
|
|
2059
|
+
this.setStatus(g.CONNECTING);
|
|
2060
2060
|
try {
|
|
2061
|
-
const s = await
|
|
2061
|
+
const s = await Or(
|
|
2062
2062
|
this.config.token,
|
|
2063
2063
|
this.config.env
|
|
2064
2064
|
);
|
|
2065
2065
|
this.ws = new WebSocket(s), this.ws.onopen = () => {
|
|
2066
|
-
this.reconnectAttempts = 0, this.setStatus(
|
|
2066
|
+
this.reconnectAttempts = 0, this.setStatus(g.CONNECTED), this.emit(b.CONNECTED), n();
|
|
2067
2067
|
}, this.ws.onmessage = (o) => {
|
|
2068
2068
|
try {
|
|
2069
2069
|
this.handleMessage(o.data);
|
|
@@ -2071,12 +2071,12 @@ class X extends Nr {
|
|
|
2071
2071
|
throw console.error("解析消息失败:", i), A.DATA_PARSING_ERROR;
|
|
2072
2072
|
}
|
|
2073
2073
|
}, this.ws.onerror = (o) => {
|
|
2074
|
-
console.error("连接错误:", o), this.setStatus(
|
|
2074
|
+
console.error("连接错误:", o), this.setStatus(g.ERROR), this.emit(b.ERROR, o), r(o);
|
|
2075
2075
|
}, this.ws.onclose = () => {
|
|
2076
|
-
this.config.env === "development" && console.warn("连接断开", (/* @__PURE__ */ new Date()).toISOString()), this.setStatus(
|
|
2076
|
+
this.config.env === "development" && console.warn("连接断开", (/* @__PURE__ */ new Date()).toISOString()), this.setStatus(g.DISCONNECTED), this.emit(b.DISCONNECTED), this.config.autoReconnect && this.reconnectAttempts < this.config.maxReconnectAttempts && this.scheduleReconnect();
|
|
2077
2077
|
};
|
|
2078
2078
|
} catch (s) {
|
|
2079
|
-
this.setStatus(
|
|
2079
|
+
this.setStatus(g.ERROR), this.emit(b.ERROR, s), r(s);
|
|
2080
2080
|
}
|
|
2081
2081
|
}
|
|
2082
2082
|
});
|
|
@@ -2086,7 +2086,7 @@ class X extends Nr {
|
|
|
2086
2086
|
* @returns void
|
|
2087
2087
|
*/
|
|
2088
2088
|
disconnect() {
|
|
2089
|
-
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(
|
|
2089
|
+
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(g.DISCONNECTED);
|
|
2090
2090
|
}
|
|
2091
2091
|
/**
|
|
2092
2092
|
* 发送消息
|
|
@@ -2103,8 +2103,8 @@ class X extends Nr {
|
|
|
2103
2103
|
chatType: n,
|
|
2104
2104
|
editId: void 0
|
|
2105
2105
|
};
|
|
2106
|
-
if (this.status !==
|
|
2107
|
-
if (this.ws && this.status ===
|
|
2106
|
+
if (this.status !== g.CONNECTED || !this.ws)
|
|
2107
|
+
if (this.ws && this.status === g.DISCONNECTED) {
|
|
2108
2108
|
console.log("连接断开,尝试重新连接");
|
|
2109
2109
|
try {
|
|
2110
2110
|
await this.connect(this.consultationTypeId);
|
|
@@ -2117,10 +2117,10 @@ class X extends Nr {
|
|
|
2117
2117
|
if (!this.ws)
|
|
2118
2118
|
throw A.DISCONNECTED;
|
|
2119
2119
|
return r === H.SEND ? new Promise(async (o, i) => {
|
|
2120
|
-
const c =
|
|
2120
|
+
const c = gr();
|
|
2121
2121
|
s.ext = c;
|
|
2122
2122
|
const d = await br({ ext: c });
|
|
2123
|
-
|
|
2123
|
+
d.data?.messageId ? (this.ws.send(JSON.stringify(s)), o({ messageId: d.data.messageId, data: t })) : i(A.MESSAGE_SEND_FAIL);
|
|
2124
2124
|
}) : (this.ws.send(JSON.stringify(s)), { data: t });
|
|
2125
2125
|
} catch (o) {
|
|
2126
2126
|
throw console.error("发送消息失败:", o), A.MESSAGE_SEND_FAIL;
|
|
@@ -2203,7 +2203,7 @@ class X extends Nr {
|
|
|
2203
2203
|
* @returns boolean
|
|
2204
2204
|
*/
|
|
2205
2205
|
isConnected() {
|
|
2206
|
-
return this.status ===
|
|
2206
|
+
return this.status === g.CONNECTED;
|
|
2207
2207
|
}
|
|
2208
2208
|
/**
|
|
2209
2209
|
* 处理收到的消息
|
|
@@ -2289,7 +2289,7 @@ class X extends Nr {
|
|
|
2289
2289
|
* @returns void
|
|
2290
2290
|
*/
|
|
2291
2291
|
scheduleReconnect() {
|
|
2292
|
-
this.config.env === "development" && console.warn("安排重连", (/* @__PURE__ */ new Date()).toISOString()), this.clearReconnectTimer(), this.reconnectAttempts++, this.setStatus(
|
|
2292
|
+
this.config.env === "development" && console.warn("安排重连", (/* @__PURE__ */ new Date()).toISOString()), this.clearReconnectTimer(), this.reconnectAttempts++, this.setStatus(g.RECONNECTING), this.reconnectTimer = setTimeout(() => {
|
|
2293
2293
|
this.connect(this.consultationTypeId).catch((t) => {
|
|
2294
2294
|
console.error("重连失败:", t);
|
|
2295
2295
|
});
|
|
@@ -2307,7 +2307,7 @@ class X extends Nr {
|
|
|
2307
2307
|
* @returns void
|
|
2308
2308
|
*/
|
|
2309
2309
|
sendHeartbeat() {
|
|
2310
|
-
if (!(this.status !==
|
|
2310
|
+
if (!(this.status !== g.CONNECTED || !this.ws))
|
|
2311
2311
|
try {
|
|
2312
2312
|
this.ws.send("pong"), this.lastHeartbeatTime = Date.now(), this.heartbeatTimeoutTimer = setTimeout(() => {
|
|
2313
2313
|
Date.now() - this.lastHeartbeatTime >= this.config.responseTimeout && (this.emit(b.HEARTBEAT_TIMEOUT), this.config.env === "development" && console.warn("心跳超时,尝试重连", (/* @__PURE__ */ new Date()).toISOString()), this.ws && this.ws.close());
|
|
@@ -2472,7 +2472,7 @@ class X extends Nr {
|
|
|
2472
2472
|
}
|
|
2473
2473
|
export {
|
|
2474
2474
|
M as ChatType,
|
|
2475
|
-
|
|
2475
|
+
g as ConnectionStatus,
|
|
2476
2476
|
b as EventType,
|
|
2477
2477
|
X as JoyTalk,
|
|
2478
2478
|
N as MatchStatus,
|
package/dist/index.umd.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
(function(U,X){typeof exports=="object"&&typeof module<"u"?X(exports):typeof define=="function"&&define.amd?define(["exports"],X):(U=typeof globalThis<"u"?globalThis:U||self,X(U.JoyTalk={}))})(this,(function(U){"use strict";function X(e,t){return function(){return e.apply(t,arguments)}}const{toString:Dt}=Object.prototype,{getPrototypeOf:be}=Object,{iterator:ce,toStringTag:He}=Symbol,le=(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=>le(t)===e),ue=e=>t=>typeof t===e,{isArray:Y}=Array,Q=ue("undefined");function ne(e){return e!==null&&!Q(e)&&e.constructor!==null&&!Q(e.constructor)&&_(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const ve=x("ArrayBuffer");function It(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&ve(e.buffer),t}const Lt=ue("string"),_=ue("function"),je=ue("number"),se=e=>e!==null&&typeof e=="object",Ft=e=>e===!0||e===!1,fe=e=>{if(le(e)!=="object")return!1;const t=be(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(He in e)&&!(ce in e)},Pt=e=>{if(!se(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=>se(e)&&_(e.pipe),jt=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||_(e.append)&&((t=le(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 re(e,t,{allOwnKeys:n=!1}={}){if(e===null||typeof e>"u")return;let s,r;if(typeof e!="object"&&(e=[e]),Y(e))for(s=0,r=e.length;s<r;s++)t.call(null,e[s],s,e);else{if(ne(e))return;const o=n?Object.getOwnPropertyNames(e):Object.keys(e),i=o.length;let c;for(s=0;s<i;s++)c=o[s],t.call(null,e[c],c,e)}}function Me(e,t){if(ne(e))return null;t=t.toLowerCase();const n=Object.keys(e);let s=n.length,r;for(;s-- >0;)if(r=n[s],t===r.toLowerCase())return r;return null}const z=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,$e=e=>!Q(e)&&e!==z;function Ne(){const{caseless:e,skipUndefined:t}=$e(this)&&this||{},n={},s=(r,o)=>{const i=e&&Me(n,o)||o;fe(n[i])&&fe(r)?n[i]=Ne(n[i],r):fe(r)?n[i]=Ne({},r):Y(r)?n[i]=r.slice():(!t||!Q(r))&&(n[i]=r)};for(let r=0,o=arguments.length;r<o;r++)arguments[r]&&re(arguments[r],s);return n}const Wt=(e,t,n,{allOwnKeys:s}={})=>(re(t,(r,o)=>{n&&_(r)?e[o]=X(r,n):e[o]=r},{allOwnKeys:s}),e),Vt=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),Kt=(e,t,n,s)=>{e.prototype=Object.create(t.prototype,s),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},Xt=(e,t,n,s)=>{let r,o,i;const c={};if(t=t||{},e==null)return t;do{for(r=Object.getOwnPropertyNames(e),o=r.length;o-- >0;)i=r[o],(!s||s(i,e,t))&&!c[i]&&(t[i]=e[i],c[i]=!0);e=n!==!1&&be(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 s=e.indexOf(t,n);return s!==-1&&s===n},Qt=e=>{if(!e)return null;if(Y(e))return e;let t=e.length;if(!je(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"&&be(Uint8Array)),en=(e,t)=>{const s=(e&&e[ce]).call(e);let r;for(;(r=s.next())&&!r.done;){const o=r.value;t.call(e,o[0],o[1])}},tn=(e,t)=>{let n;const s=[];for(;(n=e.exec(t))!==null;)s.push(n);return s},nn=x("HTMLFormElement"),sn=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,s,r){return s.toUpperCase()+r}),qe=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),rn=x("RegExp"),Ge=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),s={};re(n,(r,o)=>{let i;(i=t(r,o,e))!==!1&&(s[o]=i||r)}),Object.defineProperties(e,s)},on=e=>{Ge(e,(t,n)=>{if(_(e)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const s=e[n];if(_(s)){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={},s=r=>{r.forEach(o=>{n[o]=!0})};return Y(e)?s(e):s(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[He]==="FormData"&&e[ce])}const fn=e=>{const t=new Array(10),n=(s,r)=>{if(se(s)){if(t.indexOf(s)>=0)return;if(ne(s))return s;if(!("toJSON"in s)){t[r]=s;const o=Y(s)?[]:{};return re(s,(i,c)=>{const d=n(i,r+1);!Q(d)&&(o[c]=d)}),t[r]=void 0,o}}return s};return n(e,0)},dn=x("AsyncFunction"),hn=e=>e&&(se(e)||_(e))&&_(e.then)&&_(e.catch),ze=((e,t)=>e?setImmediate:t?((n,s)=>(z.addEventListener("message",({source:r,data:o})=>{r===z&&o===n&&s.length&&s.shift()()},!1),r=>{s.push(r),z.postMessage(n,"*")}))(`axios@${Math.random()}`,[]):n=>setTimeout(n))(typeof setImmediate=="function",_(z.postMessage)),pn=typeof queueMicrotask<"u"?queueMicrotask.bind(z):typeof process<"u"&&process.nextTick||ze,a={isArray:Y,isArrayBuffer:ve,isBuffer:ne,isFormData:jt,isArrayBufferView:It,isString:Lt,isNumber:je,isBoolean:Ft,isObject:se,isPlainObject:fe,isEmptyObject:Pt,isReadableStream:$t,isRequest:qt,isResponse:Gt,isHeaders:zt,isUndefined:Q,isDate:xt,isFile:Bt,isBlob:kt,isRegExp:rn,isFunction:_,isStream:vt,isURLSearchParams:Mt,isTypedArray:Zt,isFileList:Ht,forEach:re,merge:Ne,extend:Wt,trim:Jt,stripBOM:Vt,inherits:Kt,toFlatObject:Xt,kindOf:le,kindOfTest:x,endsWith:Yt,toArray:Qt,forEachEntry:en,matchAll:tn,isHTMLForm:nn,hasOwnProperty:qe,hasOwnProp:qe,reduceDescriptors:Ge,freezeMethods:on,toObjectSet:an,toCamelCase:sn,noop:cn,toFiniteNumber:ln,findKey:Me,global:z,isContextDefined:$e,isSpecCompliantForm:un,toJSONObject:fn,isAsyncFn:dn,isThenable:hn,setImmediate:ze,asap:pn,isIterable:e=>e!=null&&_(e[ce])};function E(e,t,n,s,r){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),s&&(this.request=s),r&&(this.response=r,this.status=r.status?r.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 Je=E.prototype,We={};["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=>{We[e]={value:e}}),Object.defineProperties(E,We),Object.defineProperty(Je,"isAxiosError",{value:!0}),E.from=(e,t,n,s,r,o)=>{const i=Object.create(Je);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,s,r),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 mn=null;function ge(e){return a.isPlainObject(e)||a.isArray(e)}function Ve(e){return a.endsWith(e,"[]")?e.slice(0,-2):e}function Ke(e,t,n){return e?e.concat(t).map(function(r,o){return r=Ve(r),!n&&o?"["+r+"]":r}).join(n?".":""):t}function En(e){return a.isArray(e)&&!e.some(ge)}const Sn=a.toFlatObject(a,{},null,function(t){return/^is[A-Z]/.test(t)});function de(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 s=n.metaTokens,r=n.visitor||l,o=n.dots,i=n.indexes,d=(n.Blob||typeof Blob<"u"&&Blob)&&a.isSpecCompliantForm(t);if(!a.isFunction(r))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 y=f;if(f&&!p&&typeof f=="object"){if(a.endsWith(m,"{}"))m=s?m:m.slice(0,-2),f=JSON.stringify(f);else if(a.isArray(f)&&En(f)||(a.isFileList(f)||a.endsWith(m,"[]"))&&(y=a.toArray(f)))return m=Ve(m),y.forEach(function(A,I){!(a.isUndefined(A)||A===null)&&t.append(i===!0?Ke([m],I,o):i===null?m:m+"[]",u(A))}),!1}return ge(f)?!0:(t.append(Ke(p,m,o),u(f)),!1)}const h=[],S=Object.assign(Sn,{defaultVisitor:l,convertValue:u,isVisitable:ge});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(y,F){(!(a.isUndefined(y)||y===null)&&r.call(t,y,a.isString(F)?F.trim():F,m,S))===!0&&w(y,m?m.concat(F):[F])}),h.pop()}}if(!a.isObject(e))throw new TypeError("data must be an object");return w(e),t}function Xe(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(s){return t[s]})}function Oe(e,t){this._pairs=[],e&&de(e,this,t)}const Ye=Oe.prototype;Ye.append=function(t,n){this._pairs.push([t,n])},Ye.toString=function(t){const n=t?function(s){return t.call(this,s,Xe)}:Xe;return this._pairs.map(function(r){return n(r[0])+"="+n(r[1])},"").join("&")};function Tn(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function Qe(e,t,n){if(!t)return e;const s=n&&n.encode||Tn;a.isFunction(n)&&(n={serialize:n});const r=n&&n.serialize;let o;if(r?o=r(t,n):o=a.isURLSearchParams(t)?t.toString():new Oe(t,n).toString(s),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,s){return this.handlers.push({fulfilled:t,rejected:n,synchronous:s?s.synchronous:!1,runWhen:s?s.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(s){s!==null&&t(s)})}}const et={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},wn={isBrowser:!0,classes:{URLSearchParams:typeof URLSearchParams<"u"?URLSearchParams:Oe,FormData:typeof FormData<"u"?FormData:null,Blob:typeof Blob<"u"?Blob:null},protocols:["http","https","file","blob","url","data"]},Ce=typeof window<"u"&&typeof document<"u",Ue=typeof navigator=="object"&&navigator||void 0,yn=Ce&&(!Ue||["ReactNative","NativeScript","NS"].indexOf(Ue.product)<0),Rn=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",An=Ce&&window.location.href||"http://localhost",g={...Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:Ce,hasStandardBrowserEnv:yn,hasStandardBrowserWebWorkerEnv:Rn,navigator:Ue,origin:An},Symbol.toStringTag,{value:"Module"})),...wn};function bn(e,t){return de(e,new g.classes.URLSearchParams,{visitor:function(n,s,r,o){return g.isNode&&a.isBuffer(n)?(this.append(s,n.toString("base64")),!1):o.defaultVisitor.apply(this,arguments)},...t})}function Nn(e){return a.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function gn(e){const t={},n=Object.keys(e);let s;const r=n.length;let o;for(s=0;s<r;s++)o=n[s],t[o]=e[o];return t}function tt(e){function t(n,s,r,o){let i=n[o++];if(i==="__proto__")return!0;const c=Number.isFinite(+i),d=o>=n.length;return i=!i&&a.isArray(r)?r.length:i,d?(a.hasOwnProp(r,i)?r[i]=[r[i],s]:r[i]=s,!c):((!r[i]||!a.isObject(r[i]))&&(r[i]=[]),t(n,s,r[i],o)&&a.isArray(r[i])&&(r[i]=gn(r[i])),!c)}if(a.isFormData(e)&&a.isFunction(e.entries)){const n={};return a.forEachEntry(e,(s,r)=>{t(Nn(s),r,n,0)}),n}return null}function On(e,t,n){if(a.isString(e))try{return(t||JSON.parse)(e),a.trim(e)}catch(s){if(s.name!=="SyntaxError")throw s}return(n||JSON.stringify)(e)}const oe={transitional:et,adapter:["xhr","http","fetch"],transformRequest:[function(t,n){const s=n.getContentType()||"",r=s.indexOf("application/json")>-1,o=a.isObject(t);if(o&&a.isHTMLForm(t)&&(t=new FormData(t)),a.isFormData(t))return r?JSON.stringify(tt(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(s.indexOf("application/x-www-form-urlencoded")>-1)return bn(t,this.formSerializer).toString();if((c=a.isFileList(t))||s.indexOf("multipart/form-data")>-1){const d=this.env&&this.env.FormData;return de(c?{"files[]":t}:t,d&&new d,this.formSerializer)}}return o||r?(n.setContentType("application/json",!1),On(t)):t}],transformResponse:[function(t){const n=this.transitional||oe.transitional,s=n&&n.forcedJSONParsing,r=this.responseType==="json";if(a.isResponse(t)||a.isReadableStream(t))return t;if(t&&a.isString(t)&&(s&&!this.responseType||r)){const i=!(n&&n.silentJSONParsing)&&r;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 Cn=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"]),Un=e=>{const t={};let n,s,r;return e&&e.split(`
|
|
2
|
-
`).forEach(function(i){
|
|
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 s=new this(t);return n.forEach(r=>s.set(r)),s}static accessor(t){const s=(this[nt]=this[nt]={accessors:{}}).accessors,r=this.prototype;function o(i){const c=ie(i);s[c]||(Ln(r,i),s[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(s){this[n]=s}}}),a.freezeMethods(D);function De(e,t){const n=this||oe,s=t||n,r=D.from(s.headers);let o=s.data;return a.forEach(e,function(c){o=c.call(n,o,r.normalize(),t?t.status:void 0)}),r.normalize(),o}function st(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 rt(e,t,n){const s=n.config.validateStatus;!n.status||!s||s(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 Fn(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function Pn(e,t){e=e||10;const n=new Array(e),s=new Array(e);let r=0,o=0,i;return t=t!==void 0?t:1e3,function(d){const u=Date.now(),l=s[o];i||(i=u),n[r]=d,s[r]=u;let h=o,S=0;for(;h!==r;)S+=n[h++],h=h%e;if(r=(r+1)%e,r===o&&(o=(o+1)%e),u-i<t)return;const w=l&&u-l;return w?Math.round(S*1e3/w):void 0}}function xn(e,t){let n=0,s=1e3/t,r,o;const i=(u,l=Date.now())=>{n=l,r=null,o&&(clearTimeout(o),o=null),e(...u)};return[(...u)=>{const l=Date.now(),h=l-n;h>=s?i(u,l):(r=u,o||(o=setTimeout(()=>{o=null,i(r)},s-h)))},()=>r&&i(r)]}const pe=(e,t,n=3)=>{let s=0;const r=Pn(50,250);return xn(o=>{const i=o.loaded,c=o.lengthComputable?o.total:void 0,d=i-s,u=r(d),l=i<=c;s=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)},ot=(e,t)=>{const n=e!=null;return[s=>t[0]({lengthComputable:n,total:e,loaded:s}),t[1]]},it=e=>(...t)=>a.asap(()=>e(...t)),Bn=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,kn=g.hasStandardBrowserEnv?{write(e,t,n,s,r,o,i){if(typeof document>"u")return;const c=[`${e}=${encodeURIComponent(t)}`];a.isNumber(n)&&c.push(`expires=${new Date(n).toUTCString()}`),a.isString(s)&&c.push(`path=${s}`),a.isString(r)&&c.push(`domain=${r}`),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 Hn(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function vn(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function at(e,t,n){let s=!Hn(t);return e&&(s||n==!1)?vn(e,t):t}const ct=e=>e instanceof D?{...e}:e;function J(e,t){t=t||{};const n={};function s(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 r(u,l,h,S){if(a.isUndefined(l)){if(!a.isUndefined(u))return s(void 0,u,h,S)}else return s(u,l,h,S)}function o(u,l){if(!a.isUndefined(l))return s(void 0,l)}function i(u,l){if(a.isUndefined(l)){if(!a.isUndefined(u))return s(void 0,u)}else return s(void 0,l)}function c(u,l,h){if(h in t)return s(u,l);if(h in e)return s(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)=>r(ct(u),ct(l),h,!0)};return a.forEach(Object.keys({...e,...t}),function(l){const h=d[l]||r,S=h(e[l],t[l],l);a.isUndefined(S)&&h!==c||(n[l]=S)}),n}const lt=e=>{const t=J({},e);let{data:n,withXSRFToken:s,xsrfHeaderName:r,xsrfCookieName:o,headers:i,auth:c}=t;if(t.headers=i=D.from(i),t.url=Qe(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&&(s&&a.isFunction(s)&&(s=s(t)),s||s!==!1&&Bn(t.url))){const d=r&&o&&kn.read(o);d&&i.set(r,d)}return t},jn=typeof XMLHttpRequest<"u"&&function(e){return new Promise(function(n,s){const r=lt(e);let o=r.data;const i=D.from(r.headers).normalize();let{responseType:c,onUploadProgress:d,onDownloadProgress:u}=r,l,h,S,w,f;function m(){w&&w(),f&&f(),r.cancelToken&&r.cancelToken.unsubscribe(l),r.signal&&r.signal.removeEventListener("abort",l)}let p=new XMLHttpRequest;p.open(r.method.toUpperCase(),r.url,!0),p.timeout=r.timeout;function y(){if(!p)return;const A=D.from("getAllResponseHeaders"in p&&p.getAllResponseHeaders()),B={data:!c||c==="text"||c==="json"?p.responseText:p.response,status:p.status,statusText:p.statusText,headers:A,config:e,request:p};rt(function(P){n(P),m()},function(P){s(P),m()},B),p=null}"onloadend"in p?p.onloadend=y:p.onreadystatechange=function(){!p||p.readyState!==4||p.status===0&&!(p.responseURL&&p.responseURL.indexOf("file:")===0)||setTimeout(y)},p.onabort=function(){p&&(s(new E("Request aborted",E.ECONNABORTED,e,p)),p=null)},p.onerror=function(I){const B=I&&I.message?I.message:"Network Error",V=new E(B,E.ERR_NETWORK,e,p);V.event=I||null,s(V),p=null},p.ontimeout=function(){let I=r.timeout?"timeout of "+r.timeout+"ms exceeded":"timeout exceeded";const B=r.transitional||et;r.timeoutErrorMessage&&(I=r.timeoutErrorMessage),s(new E(I,B.clarifyTimeoutError?E.ETIMEDOUT:E.ECONNABORTED,e,p)),p=null},o===void 0&&i.setContentType(null),"setRequestHeader"in p&&a.forEach(i.toJSON(),function(I,B){p.setRequestHeader(B,I)}),a.isUndefined(r.withCredentials)||(p.withCredentials=!!r.withCredentials),c&&c!=="json"&&(p.responseType=r.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)),(r.cancelToken||r.signal)&&(l=A=>{p&&(s(!A||A.type?new Z(null,e,p):A),p.abort(),p=null)},r.cancelToken&&r.cancelToken.subscribe(l),r.signal&&(r.signal.aborted?l():r.signal.addEventListener("abort",l)));const F=Fn(r.url);if(F&&g.protocols.indexOf(F)===-1){s(new E("Unsupported protocol "+F+":",E.ERR_BAD_REQUEST,e));return}p.send(o||null)})},Mn=(e,t)=>{const{length:n}=e=e?e.filter(Boolean):[];if(t||n){let s=new AbortController,r;const o=function(u){if(!r){r=!0,c();const l=u instanceof Error?u:this.reason;s.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}=s;return d.unsubscribe=()=>a.asap(c),d}},$n=function*(e,t){let n=e.byteLength;if(n<t){yield e;return}let s=0,r;for(;s<n;)r=s+t,yield e.slice(s,r),s=r},qn=async function*(e,t){for await(const n of Gn(e))yield*$n(n,t)},Gn=async function*(e){if(e[Symbol.asyncIterator]){yield*e;return}const t=e.getReader();try{for(;;){const{done:n,value:s}=await t.read();if(n)break;yield s}}finally{await t.cancel()}},ut=(e,t,n,s)=>{const r=qn(e,t);let o=0,i,c=d=>{i||(i=!0,s&&s(d))};return new ReadableStream({async pull(d){try{const{done:u,value:l}=await r.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),r.return()}},{highWaterMark:2})},ft=64*1024,{isFunction:me}=a,zn=(({Request:e,Response:t})=>({Request:e,Response:t}))(a.global),{ReadableStream:dt,TextEncoder:ht}=a.global,pt=(e,...t)=>{try{return!!e(...t)}catch{return!1}},Jn=e=>{e=a.merge.call({skipUndefined:!0},zn,e);const{fetch:t,Request:n,Response:s}=e,r=t?me(t):typeof fetch=="function",o=me(n),i=me(s);if(!r)return!1;const c=r&&me(dt),d=r&&(typeof ht=="function"?(f=>m=>f.encode(m))(new ht):async f=>new Uint8Array(await new n(f).arrayBuffer())),u=o&&c&&pt(()=>{let f=!1;const m=new n(g.origin,{body:new dt,method:"POST",get duplex(){return f=!0,"half"}}).headers.has("Content-Type");return f&&!m}),l=i&&c&&pt(()=>a.isReadableStream(new s("").body)),h={stream:l&&(f=>f.body)};r&&["text","arrayBuffer","blob","formData","stream"].forEach(f=>{!h[f]&&(h[f]=(m,p)=>{let y=m&&m[f];if(y)return y.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:y,signal:F,cancelToken:A,timeout:I,onDownloadProgress:B,onUploadProgress:V,responseType:P,headers:Be,withCredentials:ye="same-origin",fetchOptions:bt}=lt(f),Nt=t||fetch;P=P?(P+"").toLowerCase():"text";let Re=Mn([F,A&&A.toAbortSignal()],I),ae=null;const K=Re&&Re.unsubscribe&&(()=>{Re.unsubscribe()});let gt;try{if(V&&u&&p!=="get"&&p!=="head"&&(gt=await w(Be,y))!==0){let G=new n(m,{method:"POST",body:y,duplex:"half"}),te;if(a.isFormData(y)&&(te=G.headers.get("content-type"))&&Be.setContentType(te),G.body){const[ke,Ae]=ot(gt,pe(it(V)));y=ut(G.body,ft,ke,Ae)}}a.isString(ye)||(ye=ye?"include":"omit");const v=o&&"credentials"in n.prototype,Ot={...bt,signal:Re,method:p.toUpperCase(),headers:Be.normalize().toJSON(),body:y,duplex:"half",credentials:v?ye:void 0};ae=o&&new n(m,Ot);let q=await(o?Nt(ae,bt):Nt(m,Ot));const Ct=l&&(P==="stream"||P==="response");if(l&&(B||Ct&&K)){const G={};["status","statusText","headers"].forEach(Ut=>{G[Ut]=q[Ut]});const te=a.toFiniteNumber(q.headers.get("content-length")),[ke,Ae]=B&&ot(te,pe(it(B),!0))||[];q=new s(ut(q.body,ft,ke,()=>{Ae&&Ae(),K&&K()}),G)}P=P||"text";let As=await h[a.findKey(h,P)||"text"](q,f);return!Ct&&K&&K(),await new Promise((G,te)=>{rt(G,te,{data:As,headers:D.from(q.headers),status:q.status,statusText:q.statusText,config:f,request:ae})})}catch(v){throw K&&K(),v&&v.name==="TypeError"&&/Load failed|fetch/i.test(v.message)?Object.assign(new E("Network Error",E.ERR_NETWORK,f,ae),{cause:v.cause||v}):E.from(v,v&&v.code,f,ae)}}},Wn=new Map,mt=e=>{let t=e&&e.env||{};const{fetch:n,Request:s,Response:r}=t,o=[s,r,n];let i=o.length,c=i,d,u,l=Wn;for(;c--;)d=o[c],u=l.get(d),u===void 0&&l.set(d,u=c?new Map:Jn(t)),l=u;return u};mt();const Ie={http:mn,xhr:jn,fetch:{get:mt}};a.forEach(Ie,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const Et=e=>`- ${e}`,Vn=e=>a.isFunction(e)||e===null||e===!1;function Kn(e,t){e=a.isArray(e)?e:[e];const{length:n}=e;let s,r;const o={};for(let i=0;i<n;i++){s=e[i];let c;if(r=s,!Vn(s)&&(r=Ie[(c=String(s)).toLowerCase()],r===void 0))throw new E(`Unknown adapter '${c}'`);if(r&&(a.isFunction(r)||(r=r.get(t))))break;o[c||"#"+i]=r}if(!r){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 :
|
|
1
|
+
(function(U,X){typeof exports=="object"&&typeof module<"u"?X(exports):typeof define=="function"&&define.amd?define(["exports"],X):(U=typeof globalThis<"u"?globalThis:U||self,X(U.JoyTalk={}))})(this,(function(U){"use strict";function X(e,t){return function(){return e.apply(t,arguments)}}const{toString:Dt}=Object.prototype,{getPrototypeOf:be}=Object,{iterator:ce,toStringTag:He}=Symbol,le=(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=>le(t)===e),ue=e=>t=>typeof t===e,{isArray:Y}=Array,Q=ue("undefined");function ne(e){return e!==null&&!Q(e)&&e.constructor!==null&&!Q(e.constructor)&&_(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const ve=x("ArrayBuffer");function It(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&ve(e.buffer),t}const Lt=ue("string"),_=ue("function"),je=ue("number"),re=e=>e!==null&&typeof e=="object",Ft=e=>e===!0||e===!1,fe=e=>{if(le(e)!=="object")return!1;const t=be(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(He in e)&&!(ce 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=le(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]),Y(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 Me(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 z=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,$e=e=>!Q(e)&&e!==z;function Ne(){const{caseless:e,skipUndefined:t}=$e(this)&&this||{},n={},r=(s,o)=>{const i=e&&Me(n,o)||o;fe(n[i])&&fe(s)?n[i]=Ne(n[i],s):fe(s)?n[i]=Ne({},s):Y(s)?n[i]=s.slice():(!t||!Q(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]=X(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&&be(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(Y(e))return e;let t=e.length;if(!je(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"&&be(Uint8Array)),en=(e,t)=>{const r=(e&&e[ce]).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}),qe=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),sn=x("RegExp"),Ge=(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=>{Ge(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 Y(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[He]==="FormData"&&e[ce])}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=Y(r)?[]:{};return se(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)},dn=x("AsyncFunction"),hn=e=>e&&(re(e)||_(e))&&_(e.then)&&_(e.catch),ze=((e,t)=>e?setImmediate:t?((n,r)=>(z.addEventListener("message",({source:s,data:o})=>{s===z&&o===n&&r.length&&r.shift()()},!1),s=>{r.push(s),z.postMessage(n,"*")}))(`axios@${Math.random()}`,[]):n=>setTimeout(n))(typeof setImmediate=="function",_(z.postMessage)),pn=typeof queueMicrotask<"u"?queueMicrotask.bind(z):typeof process<"u"&&process.nextTick||ze,a={isArray:Y,isArrayBuffer:ve,isBuffer:ne,isFormData:jt,isArrayBufferView:It,isString:Lt,isNumber:je,isBoolean:Ft,isObject:re,isPlainObject:fe,isEmptyObject:Pt,isReadableStream:$t,isRequest:qt,isResponse:Gt,isHeaders:zt,isUndefined:Q,isDate:xt,isFile:Bt,isBlob:kt,isRegExp:sn,isFunction:_,isStream:vt,isURLSearchParams:Mt,isTypedArray:Zt,isFileList:Ht,forEach:se,merge:Ne,extend:Wt,trim:Jt,stripBOM:Vt,inherits:Kt,toFlatObject:Xt,kindOf:le,kindOfTest:x,endsWith:Yt,toArray:Qt,forEachEntry:en,matchAll:tn,isHTMLForm:nn,hasOwnProperty:qe,hasOwnProp:qe,reduceDescriptors:Ge,freezeMethods:on,toObjectSet:an,toCamelCase:rn,noop:cn,toFiniteNumber:ln,findKey:Me,global:z,isContextDefined:$e,isSpecCompliantForm:un,toJSONObject:fn,isAsyncFn:dn,isThenable:hn,setImmediate:ze,asap:pn,isIterable:e=>e!=null&&_(e[ce])};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 Je=E.prototype,We={};["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=>{We[e]={value:e}}),Object.defineProperties(E,We),Object.defineProperty(Je,"isAxiosError",{value:!0}),E.from=(e,t,n,r,s,o)=>{const i=Object.create(Je);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 mn=null;function ge(e){return a.isPlainObject(e)||a.isArray(e)}function Ve(e){return a.endsWith(e,"[]")?e.slice(0,-2):e}function Ke(e,t,n){return e?e.concat(t).map(function(s,o){return s=Ve(s),!n&&o?"["+s+"]":s}).join(n?".":""):t}function En(e){return a.isArray(e)&&!e.some(ge)}const Sn=a.toFlatObject(a,{},null,function(t){return/^is[A-Z]/.test(t)});function de(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 y=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)&&En(f)||(a.isFileList(f)||a.endsWith(m,"[]"))&&(y=a.toArray(f)))return m=Ve(m),y.forEach(function(A,I){!(a.isUndefined(A)||A===null)&&t.append(i===!0?Ke([m],I,o):i===null?m:m+"[]",u(A))}),!1}return ge(f)?!0:(t.append(Ke(p,m,o),u(f)),!1)}const h=[],S=Object.assign(Sn,{defaultVisitor:l,convertValue:u,isVisitable:ge});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(y,F){(!(a.isUndefined(y)||y===null)&&s.call(t,y,a.isString(F)?F.trim():F,m,S))===!0&&w(y,m?m.concat(F):[F])}),h.pop()}}if(!a.isObject(e))throw new TypeError("data must be an object");return w(e),t}function Xe(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(r){return t[r]})}function Oe(e,t){this._pairs=[],e&&de(e,this,t)}const Ye=Oe.prototype;Ye.append=function(t,n){this._pairs.push([t,n])},Ye.toString=function(t){const n=t?function(r){return t.call(this,r,Xe)}:Xe;return this._pairs.map(function(s){return n(s[0])+"="+n(s[1])},"").join("&")};function Tn(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function Qe(e,t,n){if(!t)return e;const r=n&&n.encode||Tn;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 Oe(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 et={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},wn={isBrowser:!0,classes:{URLSearchParams:typeof URLSearchParams<"u"?URLSearchParams:Oe,FormData:typeof FormData<"u"?FormData:null,Blob:typeof Blob<"u"?Blob:null},protocols:["http","https","file","blob","url","data"]},Ce=typeof window<"u"&&typeof document<"u",Ue=typeof navigator=="object"&&navigator||void 0,yn=Ce&&(!Ue||["ReactNative","NativeScript","NS"].indexOf(Ue.product)<0),Rn=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",An=Ce&&window.location.href||"http://localhost",g={...Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:Ce,hasStandardBrowserEnv:yn,hasStandardBrowserWebWorkerEnv:Rn,navigator:Ue,origin:An},Symbol.toStringTag,{value:"Module"})),...wn};function bn(e,t){return de(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 Nn(e){return a.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function gn(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 tt(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]=gn(s[i])),!c)}if(a.isFormData(e)&&a.isFunction(e.entries)){const n={};return a.forEachEntry(e,(r,s)=>{t(Nn(r),s,n,0)}),n}return null}function On(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:et,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(tt(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 bn(t,this.formSerializer).toString();if((c=a.isFileList(t))||r.indexOf("multipart/form-data")>-1){const d=this.env&&this.env.FormData;return de(c?{"files[]":t}:t,d&&new d,this.formSerializer)}}return o||s?(n.setContentType("application/json",!1),On(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 Cn=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"]),Un=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]&&Cn[n])&&(n==="set-cookie"?t[n]?t[n].push(r):t[n]=[r]:t[n]=t[n]?t[n]+", "+r:r)}),t},nt=Symbol("internals");function ie(e){return e&&String(e).trim().toLowerCase()}function he(e){return e===!1||e==null?e:a.isArray(e)?e.map(he):String(e)}function _n(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 Dn=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function _e(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 In(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,n,r)=>n.toUpperCase()+r)}function Ln(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=ie(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]=he(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())&&!Dn(t))i(Un(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=ie(t),t){const r=a.findKey(this,t);if(r){const s=this[r];if(!n)return s;if(n===!0)return _n(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=ie(t),t){const r=a.findKey(this,t);return!!(r&&this[r]!==void 0&&(!n||_e(this,this[r],r,n)))}return!1}delete(t,n){const r=this;let s=!1;function o(i){if(i=ie(i),i){const c=a.findKey(r,i);c&&(!n||_e(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||_e(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]=he(s),delete n[o];return}const c=t?In(o):String(o).trim();c!==o&&delete n[o],n[c]=he(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[nt]=this[nt]={accessors:{}}).accessors,s=this.prototype;function o(i){const c=ie(i);r[c]||(Ln(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 De(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 st(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 Fn(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function Pn(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 xn(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=Pn(50,250);return xn(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)},ot=(e,t)=>{const n=e!=null;return[r=>t[0]({lengthComputable:n,total:e,loaded:r}),t[1]]},it=e=>(...t)=>a.asap(()=>e(...t)),Bn=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,kn=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 Hn(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function vn(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function at(e,t,n){let r=!Hn(t);return e&&(r||n==!1)?vn(e,t):t}const ct=e=>e instanceof D?{...e}:e;function J(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(ct(u),ct(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 lt=e=>{const t=J({},e);let{data:n,withXSRFToken:r,xsrfHeaderName:s,xsrfCookieName:o,headers:i,auth:c}=t;if(t.headers=i=D.from(i),t.url=Qe(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&&Bn(t.url))){const d=s&&o&&kn.read(o);d&&i.set(s,d)}return t},jn=typeof XMLHttpRequest<"u"&&function(e){return new Promise(function(n,r){const s=lt(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 y(){if(!p)return;const A=D.from("getAllResponseHeaders"in p&&p.getAllResponseHeaders()),B={data:!c||c==="text"||c==="json"?p.responseText:p.response,status:p.status,statusText:p.statusText,headers:A,config:e,request:p};st(function(P){n(P),m()},function(P){r(P),m()},B),p=null}"onloadend"in p?p.onloadend=y:p.onreadystatechange=function(){!p||p.readyState!==4||p.status===0&&!(p.responseURL&&p.responseURL.indexOf("file:")===0)||setTimeout(y)},p.onabort=function(){p&&(r(new E("Request aborted",E.ECONNABORTED,e,p)),p=null)},p.onerror=function(I){const B=I&&I.message?I.message:"Network Error",V=new E(B,E.ERR_NETWORK,e,p);V.event=I||null,r(V),p=null},p.ontimeout=function(){let I=s.timeout?"timeout of "+s.timeout+"ms exceeded":"timeout exceeded";const B=s.transitional||et;s.timeoutErrorMessage&&(I=s.timeoutErrorMessage),r(new E(I,B.clarifyTimeoutError?E.ETIMEDOUT:E.ECONNABORTED,e,p)),p=null},o===void 0&&i.setContentType(null),"setRequestHeader"in p&&a.forEach(i.toJSON(),function(I,B){p.setRequestHeader(B,I)}),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=A=>{p&&(r(!A||A.type?new Z(null,e,p):A),p.abort(),p=null)},s.cancelToken&&s.cancelToken.subscribe(l),s.signal&&(s.signal.aborted?l():s.signal.addEventListener("abort",l)));const F=Fn(s.url);if(F&&g.protocols.indexOf(F)===-1){r(new E("Unsupported protocol "+F+":",E.ERR_BAD_REQUEST,e));return}p.send(o||null)})},Mn=(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}},$n=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},qn=async function*(e,t){for await(const n of Gn(e))yield*$n(n,t)},Gn=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()}},ut=(e,t,n,r)=>{const s=qn(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})},ft=64*1024,{isFunction:me}=a,zn=(({Request:e,Response:t})=>({Request:e,Response:t}))(a.global),{ReadableStream:dt,TextEncoder:ht}=a.global,pt=(e,...t)=>{try{return!!e(...t)}catch{return!1}},Jn=e=>{e=a.merge.call({skipUndefined:!0},zn,e);const{fetch:t,Request:n,Response:r}=e,s=t?me(t):typeof fetch=="function",o=me(n),i=me(r);if(!s)return!1;const c=s&&me(dt),d=s&&(typeof ht=="function"?(f=>m=>f.encode(m))(new ht):async f=>new Uint8Array(await new n(f).arrayBuffer())),u=o&&c&&pt(()=>{let f=!1;const m=new n(g.origin,{body:new dt,method:"POST",get duplex(){return f=!0,"half"}}).headers.has("Content-Type");return f&&!m}),l=i&&c&&pt(()=>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 y=m&&m[f];if(y)return y.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:y,signal:F,cancelToken:A,timeout:I,onDownloadProgress:B,onUploadProgress:V,responseType:P,headers:Be,withCredentials:ye="same-origin",fetchOptions:bt}=lt(f),Nt=t||fetch;P=P?(P+"").toLowerCase():"text";let Re=Mn([F,A&&A.toAbortSignal()],I),ae=null;const K=Re&&Re.unsubscribe&&(()=>{Re.unsubscribe()});let gt;try{if(V&&u&&p!=="get"&&p!=="head"&&(gt=await w(Be,y))!==0){let G=new n(m,{method:"POST",body:y,duplex:"half"}),te;if(a.isFormData(y)&&(te=G.headers.get("content-type"))&&Be.setContentType(te),G.body){const[ke,Ae]=ot(gt,pe(it(V)));y=ut(G.body,ft,ke,Ae)}}a.isString(ye)||(ye=ye?"include":"omit");const v=o&&"credentials"in n.prototype,Ot={...bt,signal:Re,method:p.toUpperCase(),headers:Be.normalize().toJSON(),body:y,duplex:"half",credentials:v?ye:void 0};ae=o&&new n(m,Ot);let q=await(o?Nt(ae,bt):Nt(m,Ot));const Ct=l&&(P==="stream"||P==="response");if(l&&(B||Ct&&K)){const G={};["status","statusText","headers"].forEach(Ut=>{G[Ut]=q[Ut]});const te=a.toFiniteNumber(q.headers.get("content-length")),[ke,Ae]=B&&ot(te,pe(it(B),!0))||[];q=new r(ut(q.body,ft,ke,()=>{Ae&&Ae(),K&&K()}),G)}P=P||"text";let Ar=await h[a.findKey(h,P)||"text"](q,f);return!Ct&&K&&K(),await new Promise((G,te)=>{st(G,te,{data:Ar,headers:D.from(q.headers),status:q.status,statusText:q.statusText,config:f,request:ae})})}catch(v){throw K&&K(),v&&v.name==="TypeError"&&/Load failed|fetch/i.test(v.message)?Object.assign(new E("Network Error",E.ERR_NETWORK,f,ae),{cause:v.cause||v}):E.from(v,v&&v.code,f,ae)}}},Wn=new Map,mt=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=Wn;for(;c--;)d=o[c],u=l.get(d),u===void 0&&l.set(d,u=c?new Map:Jn(t)),l=u;return u};mt();const Ie={http:mn,xhr:jn,fetch:{get:mt}};a.forEach(Ie,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const Et=e=>`- ${e}`,Vn=e=>a.isFunction(e)||e===null||e===!1;function Kn(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,!Vn(r)&&(s=Ie[(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
4
|
`+i.map(Et).join(`
|
|
5
|
-
`):" "+Et(i[0]):"as no adapter specified";throw new E("There is no suitable adapter to dispatch the request "+c,"ERR_NOT_SUPPORT")}return
|
|
6
|
-
`+o):s.stack=o}catch{}}throw s}}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=J(this.defaults,n);const{transitional:s,paramsSerializer:r,headers:o}=n;s!==void 0&&Se.assertOptions(s,{silentJSONParsing:k.transitional(k.boolean),forcedJSONParsing:k.transitional(k.boolean),clarifyTimeoutError:k.transitional(k.boolean)},!1),r!=null&&(a.isFunction(r)?n.paramsSerializer={serialize:r}:Se.assertOptions(r,{encode:k.function,serialize:k.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),Se.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=[Tt.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=Tt.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=J(this.defaults,t);const n=at(t.baseURL,t.url,t.allowAbsoluteUrls);return Qe(n,t.params,t.paramsSerializer)}};a.forEach(["delete","get","head","options"],function(t){W.prototype[t]=function(n,s){return this.request(J(s||{},{method:t,url:n,data:(s||{}).data}))}}),a.forEach(["post","put","patch"],function(t){function n(s){return function(o,i,c){return this.request(J(c||{},{method:t,headers:s?{"Content-Type":"multipart/form-data"}:{},url:o,data:i}))}}W.prototype[t]=n(),W.prototype[t+"Form"]=n(!0)});let Yn=class _t{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 s=this;this.promise.then(r=>{if(!s._listeners)return;let o=s._listeners.length;for(;o-- >0;)s._listeners[o](r);s._listeners=null}),this.promise.then=r=>{let o;const i=new Promise(c=>{s.subscribe(c),o=c}).then(r);return i.cancel=function(){s.unsubscribe(o)},i},t(function(o,i,c){s.reason||(s.reason=new Z(o,i,c),n(s.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=s=>{t.abort(s)};return this.subscribe(n),t.signal.unsubscribe=()=>this.unsubscribe(n),t.signal}static source(){let t;return{token:new _t(function(r){t=r}),cancel:t}}};function Qn(e){return function(n){return e.apply(null,n)}}function Zn(e){return a.isObject(e)&&e.isAxiosError===!0}const Fe={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(Fe).forEach(([e,t])=>{Fe[t]=e});function Rt(e){const t=new W(e),n=X(W.prototype.request,t);return a.extend(n,W.prototype,t,{allOwnKeys:!0}),a.extend(n,t,null,{allOwnKeys:!0}),n.create=function(r){return Rt(J(e,r))},n}const T=Rt(oe);T.Axios=W,T.CanceledError=Z,T.CancelToken=Yn,T.isCancel=st,T.VERSION=wt,T.toFormData=de,T.AxiosError=E,T.Cancel=T.CanceledError,T.all=function(t){return Promise.all(t)},T.spread=Qn,T.isAxiosError=Zn,T.mergeConfig=J,T.AxiosHeaders=D,T.formToJSON=e=>tt(a.isHTMLForm(e)?new FormData(e):e),T.getAdapter=St.getAdapter,T.HttpStatusCode=Fe,T.default=T;const{Axios:_s,AxiosError:Ds,CanceledError:Is,isCancel:Ls,CancelToken:Fs,VERSION:Ps,all:xs,Cancel:Bs,isAxiosError:ks,spread:Hs,toFormData:vs,AxiosHeaders:js,HttpStatusCode:Ms,formToJSON:$s,getAdapter:qs,mergeConfig:Gs}=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:"数据为空"}},es="/api/customer-service/customer/v1/CustomerService/TestLineLatency",ts="/api/customer-service/customer/v1/CustomerService/ListLines",ns="/pub/logo.png",Pe={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"}},L={api:"",download:"",ws:""};let ee=null;function ss(e){const t=`${e.replace(/\/$/,"")}${es}`;return T.get(t,{timeout:1e4}).then(n=>n.data?.code!==200?Promise.reject(n):e)}function rs(e){const t=`${e.replace(/\/$/,"")}${ns}`;return T.get(t,{timeout:1e4}).then(()=>e).catch(()=>Promise.reject(new Error("Download latency test failed")))}function os(e){return e?.length?Promise.any(e.map(t=>ss(t))):Promise.reject(new Error("No urls to test"))}function is(e){return e?.length?Promise.any(e.map(t=>rs(t))):Promise.reject(new Error("No download urls to test"))}async function xe(e,t){if(L.api&&L.download)return;if(ee)return ee;const n=Pe[t].BASE_API_URL||"",s=Pe[t].OBS_URL||"";L.api=n,L.download=s,L.ws=n.replace(/http/g,"ws"),n||(ee=Promise.reject(new Error("环境配置错误")),await ee),ee=(async()=>{const r=await T.get(`${n.replace(/\/$/,"")}${ts}`,{headers:{Authorization:`Bearer ${e}`},timeout:15e3});if(r.data?.code!==200||!r.data?.data)return Promise.reject(r);const o=(r.data.data.api??[]).map(h=>h.url).filter(Boolean),i=(r.data.data.download??[]).map(h=>h.url).filter(Boolean),c=n,d=s,[u,l]=await Promise.all([o.length?os(o).catch(()=>c):Promise.resolve(c),i.length?is(i).catch(()=>d):Promise.resolve(d)]);L.api=u,L.download=l,L.ws=u.replace(/http/g,"ws")})(),await ee}const M=T.create({timeout:6e5});M.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=L.api,e):Promise.reject(b.UNINITIALIZED)},e=>Promise.reject(e)),M.interceptors.response.use(e=>e.data?.code!==200?Promise.reject(e):Promise.resolve(e.data),e=>Promise.reject(e));function as(){return L.api}function Te(){return L.download}function cs(){return L.ws}const ls=e=>M.post("/api/open-auth/obs/v1/ObsService/GetObsAuthInfo",e),us=async e=>{const t=Te();return T.post(`${t}`,e,{headers:{"Content-Type":"multipart/form-data"}})},fs=async(e,t)=>T.put(t,e,{headers:{"Content-Type":"application/octet-stream"}}),ds=e=>M.post("/api/open-auth/open_consultation/v1/OpenConsultationService/GetConsultationList",e),hs=e=>M.get("/api/open-auth/faq/v1/FaqService/GetFaqList",{params:e}),ps=()=>M.get("/api/open-auth/user/v1/UserService/GetUserInfo"),ms=e=>M.post("/api/open-auth/user/v1/UserService/GetUserHistoryMessages",e),Es=e=>{const n=new $().config.env,s=as()||Pe[n].BASE_API_URL;return T.post(`${s}/api/open-auth/openAuth/v1/OpenAuthService/AnonymousAuth`,e)},Ss=e=>M.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||{}),j=(e=>(e.TEXT="1",e.IMAGE="2",e.VIDEO="3",e.FILE="4",e.FAQ="5",e))(j||{}),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.REMATCH=60001]="REMATCH",e))(C||{}),we=(e=>(e.CUSTOMER="1",e.USER="2",e.ANONYMOUS="3",e))(we||{}),R=(e=>(e.CONNECTED="connected",e.DISCONNECTED="disconnected",e.ERROR="error",e.MESSAGE="message",e.STATUS_CHANGE="status_change",e.HEARTBEAT_TIMEOUT="heartbeat_timeout",e))(R||{}),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 Ts{events=new Map;on(t,n){this.events.has(t)||this.events.set(t,[]),this.events.get(t).push(n)}off(t,n){const s=this.events.get(t);if(s){const r=s.indexOf(n);r>-1&&s.splice(r,1)}}emit(t,n){const s=this.events.get(t);s&&s.forEach(r=>{try{r(n)}catch(o){console.error(`事件回调执行错误 [${t}]:`,o)}})}removeAllListeners(t){t?this.events.delete(t):this.events.clear()}once(t,n){const s=r=>{n(r),this.off(t,s)};this.on(t,s)}}async function ws(e,t){return await xe(e,t),`${await cs()}/api/ws?Authorization=${e}`}function ys(){return"web"+Date.now().toString(36)+Math.random().toString(36).slice(2)}function Rs(e){return typeof e=="object"&&e!==null&&"data"in e&&"msgType"in e&&"toUid"in e&&"chatType"in e&&"code"in e}function At(e){const t=Te()+"/";return e.contentType!==j.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!==j.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 Ts{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,s)=>{if(!this.config.token)return s(b.UNINITIALIZED);if(this.status===O.CONNECTED)return n();if(this.status!==O.CONNECTING){this.setStatus(O.CONNECTING);try{const r=await ws(this.config.token,this.config.env);this.ws=new WebSocket(r),this.ws.onopen=()=>{this.reconnectAttempts=0,this.setStatus(O.CONNECTED),this.emit(R.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(R.ERROR,o),s(o)},this.ws.onclose=()=>{this.config.env==="development"&&console.warn("连接断开",new Date().toISOString()),this.setStatus(O.DISCONNECTED),this.emit(R.DISCONNECTED),this.config.autoReconnect&&this.reconnectAttempts<this.config.maxReconnectAttempts&&this.scheduleReconnect()}}catch(r){this.setStatus(O.ERROR),this.emit(R.ERROR,r),s(r)}}})}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,s=H.SEND){const r={msgType:s,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 s===H.SEND?new Promise(async(o,i)=>{const c=ys();r.ext=c;const d=await Ss({ext:c});console.log("🚀 ~ JoyTalk ~ sendMessage ~ res:",d.data.messageId),d.data?.messageId?(this.ws.send(JSON.stringify(r)),o({messageId:d.data.messageId,data:t})):i(b.MESSAGE_SEND_FAIL)}):(this.ws.send(JSON.stringify(r)),{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 s=setTimeout(()=>{clearTimeout(s),n(b.MESSAGE_SEND_FAIL)},this.config.responseTimeout);this.once(R.MESSAGE,r=>{r.code===C.REMATCH&&(clearTimeout(s),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,j.TEXT)}async sendFile({file:t,thumbnailFile:n,chatType:s}){try{await this.checkMatchStatus();const[r,o]=await Promise.all([this.handleUploadFile(t),n?this.handleUploadFile(n):Promise.resolve(void 0)]),i={fileName:t.name,fileUrl:r,thumbnailUrl:o,fileSize:t.size},{messageId:c}=await this.sendMessage(JSON.stringify(i),s),d=Te();return{messageId:c,content:{fileName:t.name,fileUrl:`${d}/${r}`,thumbnailUrl:o?`${d}/${o}`:void 0,fileSize:t.size}}}catch(r){throw console.error("上传文件失败:",r),r}}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),!!Rs(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(R.MESSAGE,{...t,code:C.REMATCH})):(this.matchStatus=N.MATCHED,this.getFaqList(),this.emit(R.MESSAGE,t));break;case C.TRANSFER_USER_SUCCESS:if(n.oldSessionId!==this.sessionData?.sessionId)return;const s=t.data;this.sessionData={...this.sessionData,cid:String(s.cid),customerAvatar:s.customerAvatar,customerName:s.customerName,groupId:s.groupId,sessionId:s.sessionId},this.emit(R.MESSAGE,t);break;case C.SEND_SUCCESS:case C.EDIT:case C.REPLY_SUCCESS:const r=t.data;if(r.sessionId!==this.sessionData?.sessionId)return;At(r),this.emit(R.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(R.MESSAGE,t);break;default:this.emit(R.MESSAGE,t);break}}catch(n){console.error("解析消息失败:",n)}}setStatus(t){this.status!==t&&(this.status=t,this.emit(R.STATUS_CHANGE,t))}scheduleReconnect(){this.config.env==="development"&&console.warn("安排重连",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(R.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 s=await ms({sessionId:this.sessionData?.sessionId,lastMsgId:t,size:n}),r=s.data.list.map(o=>At(o));return{hasMore:s.data.hasMore,list:r}}async getConsultationList(t){return(await ds({entranceId:t})).data}handleUploadFile(t){return new Promise(async(n,s)=>{const r=t.name.split(".").pop(),o=await ls({ext:r||""}),{accessKeyId:i,signature:c,policy:d,key:u,maxLimit:l,url:h}=o.data;if(t.size>l*1024*1024)return s(`文件大小不能超过${l}MB`);if(h){const S=await fs(t,h);S.status===200?n(`${u}`):s(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 us(S);w.status===204?n(`${u}`):s(w.data)}})}getVideoThumbnail=t=>new Promise((n,s)=>{const r=document.createElement("video"),o=document.createElement("canvas"),i=o.getContext("2d");if(!i){s(new Error("无法创建 canvas 上下文"));return}const c=URL.createObjectURL(t);r.preload="metadata",r.src=c,r.muted=!0,r.playsInline=!0,r.addEventListener("loadeddata",()=>{o.width=r.videoWidth,o.height=r.videoHeight,r.currentTime=0}),r.addEventListener("seeked",()=>{try{i.drawImage(r,0,0,o.width,o.height),o.toBlob(d=>{if(URL.revokeObjectURL(c),r.remove(),!d){s(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),r.remove(),s(d)}}),r.addEventListener("error",()=>{URL.revokeObjectURL(c),r.remove(),s(b.FILE_PARSING_ERROR)}),r.load()});async getFaqList(){if(this.matchStatus!==N.MATCHED)return Promise.reject(b.NO_CUSTOMER_SERVICE);const t=await hs({id:this.sessionData?.cid});if(!t.data?.topic?.length)return;const n={guideText:t.data.guideText,list:t.data.topic.map(s=>({...s,question:s.question}))};setTimeout(()=>{const s={code:C.SEND_SUCCESS,data:{content:n,contentType:j.FAQ,sendUserType:we.CUSTOMER,customerServiceAvatar:this.sessionData?.customerAvatar,customerServiceName:this.sessionData?.customerName,createTime:Date.now(),msgType:H.SEND},msgType:H.SEND,chatType:j.FAQ};this.emit(R.MESSAGE,s)},t.data.showDelaySeconds*1e3)}sendFaq(t){const n={code:C.SEND_SUCCESS,data:{sendUserType:we.CUSTOMER,customerServiceAvatar:this.sessionData?.customerAvatar,customerServiceName:this.sessionData?.customerName,createTime:Date.now(),msgType:H.SEND,contentType:j.FAQ,content:{}},msgType:H.SEND,chatType:j.FAQ};if(t.isMulti)n.data.content={list:t.item},this.emit(R.MESSAGE,n);else{const s=t.item?.[0]||t,r=Te();s.imageUrl=s.imageUrl?.map(o=>o?.startsWith("http")?o:`${r}/${o}`),n.data.content={answer:s},this.emit(R.MESSAGE,n)}}async getUserInfo(){if(this.userInfo)return this.userInfo;const t=await ps();return this.userInfo=t.data,this.userInfo}async anonymousLogin(t,n){return(await Es({appKey:t,entranceId:n,userSource:"H5"})).data}}U.ChatType=j,U.ConnectionStatus=O,U.EventType=R,U.JoyTalk=$,U.MatchStatus=N,U.MessageCode=C,U.MessageType=H,U.SendUserType=we,U.default=$,Object.defineProperties(U,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
|
|
5
|
+
`):" "+Et(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 St={getAdapter:Kn,adapters:Ie};function Le(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Z(null,e)}function Tt(e){return Le(e),e.headers=D.from(e.headers),e.data=De.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),St.getAdapter(e.adapter||oe.adapter,e)(e).then(function(r){return Le(e),r.data=De.call(e,e.transformResponse,r),r.headers=D.from(r.headers),r},function(r){return rt(r)||(Le(e),r&&r.response&&(r.response.data=De.call(e,e.transformResponse,r.response),r.response.headers=D.from(r.response.headers))),Promise.reject(r)})}const wt="1.13.2",Ee={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{Ee[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const yt={};Ee.transitional=function(t,n,r){function s(o,i){return"[Axios v"+wt+"] 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&&!yt[i]&&(yt[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}},Ee.spelling=function(t){return(n,r)=>(console.warn(`${r} is likely a misspelling of ${t}`),!0)};function Xn(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 Se={assertOptions:Xn,validators:Ee},k=Se.validators;let W=class{constructor(t){this.defaults=t||{},this.interceptors={request:new Ze,response:new Ze}}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=J(this.defaults,n);const{transitional:r,paramsSerializer:s,headers:o}=n;r!==void 0&&Se.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}:Se.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),Se.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=[Tt.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=Tt.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=J(this.defaults,t);const n=at(t.baseURL,t.url,t.allowAbsoluteUrls);return Qe(n,t.params,t.paramsSerializer)}};a.forEach(["delete","get","head","options"],function(t){W.prototype[t]=function(n,r){return this.request(J(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(J(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 Yn=class _t{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 _t(function(s){t=s}),cancel:t}}};function Qn(e){return function(n){return e.apply(null,n)}}function Zn(e){return a.isObject(e)&&e.isAxiosError===!0}const Fe={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(Fe).forEach(([e,t])=>{Fe[t]=e});function Rt(e){const t=new W(e),n=X(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 Rt(J(e,s))},n}const T=Rt(oe);T.Axios=W,T.CanceledError=Z,T.CancelToken=Yn,T.isCancel=rt,T.VERSION=wt,T.toFormData=de,T.AxiosError=E,T.Cancel=T.CanceledError,T.all=function(t){return Promise.all(t)},T.spread=Qn,T.isAxiosError=Zn,T.mergeConfig=J,T.AxiosHeaders=D,T.formToJSON=e=>tt(a.isHTMLForm(e)?new FormData(e):e),T.getAdapter=St.getAdapter,T.HttpStatusCode=Fe,T.default=T;const{Axios:_r,AxiosError:Dr,CanceledError:Ir,isCancel:Lr,CancelToken:Fr,VERSION:Pr,all:xr,Cancel:Br,isAxiosError:kr,spread:Hr,toFormData:vr,AxiosHeaders:jr,HttpStatusCode:Mr,formToJSON:$r,getAdapter:qr,mergeConfig:Gr}=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:"数据为空"}},er="/api/customer-service/customer/v1/CustomerService/TestLineLatency",tr="/api/customer-service/customer/v1/CustomerService/ListLines",nr="/pub/logo.png",Pe={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"}},L={api:"",download:"",ws:""};let ee=null;function rr(e){const t=`${e.replace(/\/$/,"")}${er}`;return T.get(t,{timeout:1e4}).then(n=>n.data?.code!==200?Promise.reject(n):e)}function sr(e){const t=`${e.replace(/\/$/,"")}${nr}`;return T.get(t,{timeout:1e4}).then(()=>e).catch(()=>Promise.reject(new Error("Download latency test failed")))}function or(e){return e?.length?Promise.any(e.map(t=>rr(t))):Promise.reject(new Error("No urls to test"))}function ir(e){return e?.length?Promise.any(e.map(t=>sr(t))):Promise.reject(new Error("No download urls to test"))}async function xe(e,t){if(L.api&&L.download)return;if(ee)return ee;const n=Pe[t].BASE_API_URL||"",r=Pe[t].OBS_URL||"";L.api=n,L.download=r,L.ws=n.replace(/http/g,"ws"),n||(ee=Promise.reject(new Error("环境配置错误")),await ee),ee=(async()=>{const s=await T.get(`${n.replace(/\/$/,"")}${tr}`,{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?or(o).catch(()=>c):Promise.resolve(c),i.length?ir(i).catch(()=>d):Promise.resolve(d)]);L.api=u,L.download=l,L.ws=u.replace(/http/g,"ws")})(),await ee}const M=T.create({timeout:6e5});M.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=L.api,e):Promise.reject(b.UNINITIALIZED)},e=>Promise.reject(e)),M.interceptors.response.use(e=>e.data?.code!==200?Promise.reject(e):Promise.resolve(e.data),e=>Promise.reject(e));function ar(){return L.api}function Te(){return L.download}function cr(){return L.ws}const lr=e=>M.post("/api/open-auth/obs/v1/ObsService/GetObsAuthInfo",e),ur=async e=>{const t=Te();return T.post(`${t}`,e,{headers:{"Content-Type":"multipart/form-data"}})},fr=async(e,t)=>T.put(t,e,{headers:{"Content-Type":"application/octet-stream"}}),dr=e=>M.post("/api/open-auth/open_consultation/v1/OpenConsultationService/GetConsultationList",e),hr=e=>M.get("/api/open-auth/faq/v1/FaqService/GetFaqList",{params:e}),pr=()=>M.get("/api/open-auth/user/v1/UserService/GetUserInfo"),mr=e=>M.post("/api/open-auth/user/v1/UserService/GetUserHistoryMessages",e),Er=e=>{const n=new $().config.env,r=ar()||Pe[n].BASE_API_URL;return T.post(`${r}/api/open-auth/openAuth/v1/OpenAuthService/AnonymousAuth`,e)},Sr=e=>M.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||{}),j=(e=>(e.TEXT="1",e.IMAGE="2",e.VIDEO="3",e.FILE="4",e.FAQ="5",e))(j||{}),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.REMATCH=60001]="REMATCH",e))(C||{}),we=(e=>(e.CUSTOMER="1",e.USER="2",e.ANONYMOUS="3",e))(we||{}),R=(e=>(e.CONNECTED="connected",e.DISCONNECTED="disconnected",e.ERROR="error",e.MESSAGE="message",e.STATUS_CHANGE="status_change",e.HEARTBEAT_TIMEOUT="heartbeat_timeout",e))(R||{}),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 Tr{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 wr(e,t){return await xe(e,t),`${await cr()}/api/ws?Authorization=${e}`}function yr(){return"web"+Date.now().toString(36)+Math.random().toString(36).slice(2)}function Rr(e){return typeof e=="object"&&e!==null&&"data"in e&&"msgType"in e&&"toUid"in e&&"chatType"in e&&"code"in e}function At(e){const t=Te()+"/";return e.contentType!==j.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!==j.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 Tr{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 wr(this.config.token,this.config.env);this.ws=new WebSocket(s),this.ws.onopen=()=>{this.reconnectAttempts=0,this.setStatus(O.CONNECTED),this.emit(R.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(R.ERROR,o),r(o)},this.ws.onclose=()=>{this.config.env==="development"&&console.warn("连接断开",new Date().toISOString()),this.setStatus(O.DISCONNECTED),this.emit(R.DISCONNECTED),this.config.autoReconnect&&this.reconnectAttempts<this.config.maxReconnectAttempts&&this.scheduleReconnect()}}catch(s){this.setStatus(O.ERROR),this.emit(R.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=yr();s.ext=c;const d=await Sr({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(R.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,j.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=Te();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),!!Rr(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(R.MESSAGE,{...t,code:C.REMATCH})):(this.matchStatus=N.MATCHED,this.getFaqList(),this.emit(R.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(R.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;At(s),this.emit(R.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(R.MESSAGE,t);break;default:this.emit(R.MESSAGE,t);break}}catch(n){console.error("解析消息失败:",n)}}setStatus(t){this.status!==t&&(this.status=t,this.emit(R.STATUS_CHANGE,t))}scheduleReconnect(){this.config.env==="development"&&console.warn("安排重连",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(R.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 mr({sessionId:this.sessionData?.sessionId,lastMsgId:t,size:n}),s=r.data.list.map(o=>At(o));return{hasMore:r.data.hasMore,list:s}}async getConsultationList(t){return(await dr({entranceId:t})).data}handleUploadFile(t){return new Promise(async(n,r)=>{const s=t.name.split(".").pop(),o=await lr({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 fr(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 ur(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 hr({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:j.FAQ,sendUserType:we.CUSTOMER,customerServiceAvatar:this.sessionData?.customerAvatar,customerServiceName:this.sessionData?.customerName,createTime:Date.now(),msgType:H.SEND},msgType:H.SEND,chatType:j.FAQ};this.emit(R.MESSAGE,r)},t.data.showDelaySeconds*1e3)}sendFaq(t){const n={code:C.SEND_SUCCESS,data:{sendUserType:we.CUSTOMER,customerServiceAvatar:this.sessionData?.customerAvatar,customerServiceName:this.sessionData?.customerName,createTime:Date.now(),msgType:H.SEND,contentType:j.FAQ,content:{}},msgType:H.SEND,chatType:j.FAQ};if(t.isMulti)n.data.content={list:t.item},this.emit(R.MESSAGE,n);else{const r=t.item?.[0]||t,s=Te();r.imageUrl=r.imageUrl?.map(o=>o?.startsWith("http")?o:`${s}/${o}`),n.data.content={answer:r},this.emit(R.MESSAGE,n)}}async getUserInfo(){if(this.userInfo)return this.userInfo;const t=await pr();return this.userInfo=t.data,this.userInfo}async anonymousLogin(t,n){return(await Er({appKey:t,entranceId:n,userSource:"H5"})).data}}U.ChatType=j,U.ConnectionStatus=O,U.EventType=R,U.JoyTalk=$,U.MatchStatus=N,U.MessageCode=C,U.MessageType=H,U.SendUserType=we,U.default=$,Object.defineProperties(U,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
|