@tarxemo/customer_support 1.0.1 → 1.0.2
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.umd.js
CHANGED
|
@@ -69,5 +69,5 @@ React keys must be passed directly to JSX without using spread:
|
|
|
69
69
|
`)}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,...r){const n=new this(t);return r.forEach(s=>n.set(s)),n}static accessor(t){const n=(this[at]=this[at]={accessors:{}}).accessors,s=this.prototype;function o(i){const a=ce(i);n[a]||(Kr(s,i),n[a]=!0)}return c.isArray(t)?t.forEach(o):o(t),this}};L.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),c.reduceDescriptors(L.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(n){this[r]=n}}}),c.freezeMethods(L);function Fe(e,t){const r=this||ae,n=t||r,s=L.from(n.headers);let o=n.data;return c.forEach(e,function(a){o=a.call(r,o,s.normalize(),t?t.status:void 0)}),s.normalize(),o}function ct(e){return!!(e&&e.__CANCEL__)}let le=class extends b{constructor(t,r,n){super(t??"canceled",b.ERR_CANCELED,r,n),this.name="CanceledError",this.__CANCEL__=!0}};function lt(e,t,r){const n=r.config.validateStatus;!r.status||!n||n(r.status)?e(r):t(new b("Request failed with status code "+r.status,[b.ERR_BAD_REQUEST,b.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}function Yr(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function Xr(e,t){e=e||10;const r=new Array(e),n=new Array(e);let s=0,o=0,i;return t=t!==void 0?t:1e3,function(p){const f=Date.now(),u=n[o];i||(i=f),r[s]=p,n[s]=f;let m=o,g=0;for(;m!==s;)g+=r[m++],m=m%e;if(s=(s+1)%e,s===o&&(o=(o+1)%e),f-i<t)return;const A=u&&f-u;return A?Math.round(g*1e3/A):void 0}}function Gr(e,t){let r=0,n=1e3/t,s,o;const i=(f,u=Date.now())=>{r=u,s=null,o&&(clearTimeout(o),o=null),e(...f)};return[(...f)=>{const u=Date.now(),m=u-r;m>=n?i(f,u):(s=f,o||(o=setTimeout(()=>{o=null,i(s)},n-m)))},()=>s&&i(s)]}const Ee=(e,t,r=3)=>{let n=0;const s=Xr(50,250);return Gr(o=>{const i=o.loaded,a=o.lengthComputable?o.total:void 0,p=i-n,f=s(p),u=i<=a;n=i;const m={loaded:i,total:a,progress:a?i/a:void 0,bytes:p,rate:f||void 0,estimated:f&&a&&u?(a-i)/f:void 0,event:o,lengthComputable:a!=null,[t?"download":"upload"]:!0};e(m)},r)},ut=(e,t)=>{const r=e!=null;return[n=>t[0]({lengthComputable:r,total:e,loaded:n}),t[1]]},ft=e=>(...t)=>c.asap(()=>e(...t)),Zr=F.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,F.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(F.origin),F.navigator&&/(msie|trident)/i.test(F.navigator.userAgent)):()=>!0,Qr=F.hasStandardBrowserEnv?{write(e,t,r,n,s,o,i){if(typeof document>"u")return;const a=[`${e}=${encodeURIComponent(t)}`];c.isNumber(r)&&a.push(`expires=${new Date(r).toUTCString()}`),c.isString(n)&&a.push(`path=${n}`),c.isString(s)&&a.push(`domain=${s}`),o===!0&&a.push("secure"),c.isString(i)&&a.push(`SameSite=${i}`),document.cookie=a.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 en(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function tn(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function dt(e,t,r){let n=!en(t);return e&&(n||r==!1)?tn(e,t):t}const pt=e=>e instanceof L?{...e}:e;function K(e,t){t=t||{};const r={};function n(f,u,m,g){return c.isPlainObject(f)&&c.isPlainObject(u)?c.merge.call({caseless:g},f,u):c.isPlainObject(u)?c.merge({},u):c.isArray(u)?u.slice():u}function s(f,u,m,g){if(c.isUndefined(u)){if(!c.isUndefined(f))return n(void 0,f,m,g)}else return n(f,u,m,g)}function o(f,u){if(!c.isUndefined(u))return n(void 0,u)}function i(f,u){if(c.isUndefined(u)){if(!c.isUndefined(f))return n(void 0,f)}else return n(void 0,u)}function a(f,u,m){if(m in t)return n(f,u);if(m in e)return n(void 0,f)}const p={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:a,headers:(f,u,m)=>s(pt(f),pt(u),m,!0)};return c.forEach(Object.keys({...e,...t}),function(u){const m=p[u]||s,g=m(e[u],t[u],u);c.isUndefined(g)&&m!==a||(r[u]=g)}),r}const ht=e=>{const t=K({},e);let{data:r,withXSRFToken:n,xsrfHeaderName:s,xsrfCookieName:o,headers:i,auth:a}=t;if(t.headers=i=L.from(i),t.url=nt(dt(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),a&&i.set("Authorization","Basic "+btoa((a.username||"")+":"+(a.password?unescape(encodeURIComponent(a.password)):""))),c.isFormData(r)){if(F.hasStandardBrowserEnv||F.hasStandardBrowserWebWorkerEnv)i.setContentType(void 0);else if(c.isFunction(r.getHeaders)){const p=r.getHeaders(),f=["content-type","content-length"];Object.entries(p).forEach(([u,m])=>{f.includes(u.toLowerCase())&&i.set(u,m)})}}if(F.hasStandardBrowserEnv&&(n&&c.isFunction(n)&&(n=n(t)),n||n!==!1&&Zr(t.url))){const p=s&&o&&Qr.read(o);p&&i.set(s,p)}return t},rn=typeof XMLHttpRequest<"u"&&function(e){return new Promise(function(r,n){const s=ht(e);let o=s.data;const i=L.from(s.headers).normalize();let{responseType:a,onUploadProgress:p,onDownloadProgress:f}=s,u,m,g,A,d;function y(){A&&A(),d&&d(),s.cancelToken&&s.cancelToken.unsubscribe(u),s.signal&&s.signal.removeEventListener("abort",u)}let h=new XMLHttpRequest;h.open(s.method.toUpperCase(),s.url,!0),h.timeout=s.timeout;function _(){if(!h)return;const w=L.from("getAllResponseHeaders"in h&&h.getAllResponseHeaders()),j={data:!a||a==="text"||a==="json"?h.responseText:h.response,status:h.status,statusText:h.statusText,headers:w,config:e,request:h};lt(function(U){r(U),y()},function(U){n(U),y()},j),h=null}"onloadend"in h?h.onloadend=_:h.onreadystatechange=function(){!h||h.readyState!==4||h.status===0&&!(h.responseURL&&h.responseURL.indexOf("file:")===0)||setTimeout(_)},h.onabort=function(){h&&(n(new b("Request aborted",b.ECONNABORTED,e,h)),h=null)},h.onerror=function(T){const j=T&&T.message?T.message:"Network Error",B=new b(j,b.ERR_NETWORK,e,h);B.event=T||null,n(B),h=null},h.ontimeout=function(){let T=s.timeout?"timeout of "+s.timeout+"ms exceeded":"timeout exceeded";const j=s.transitional||ot;s.timeoutErrorMessage&&(T=s.timeoutErrorMessage),n(new b(T,j.clarifyTimeoutError?b.ETIMEDOUT:b.ECONNABORTED,e,h)),h=null},o===void 0&&i.setContentType(null),"setRequestHeader"in h&&c.forEach(i.toJSON(),function(T,j){h.setRequestHeader(j,T)}),c.isUndefined(s.withCredentials)||(h.withCredentials=!!s.withCredentials),a&&a!=="json"&&(h.responseType=s.responseType),f&&([g,d]=Ee(f,!0),h.addEventListener("progress",g)),p&&h.upload&&([m,A]=Ee(p),h.upload.addEventListener("progress",m),h.upload.addEventListener("loadend",A)),(s.cancelToken||s.signal)&&(u=w=>{h&&(n(!w||w.type?new le(null,e,h):w),h.abort(),h=null)},s.cancelToken&&s.cancelToken.subscribe(u),s.signal&&(s.signal.aborted?u():s.signal.addEventListener("abort",u)));const C=Yr(s.url);if(C&&F.protocols.indexOf(C)===-1){n(new b("Unsupported protocol "+C+":",b.ERR_BAD_REQUEST,e));return}h.send(o||null)})},nn=(e,t)=>{const{length:r}=e=e?e.filter(Boolean):[];if(t||r){let n=new AbortController,s;const o=function(f){if(!s){s=!0,a();const u=f instanceof Error?f:this.reason;n.abort(u instanceof b?u:new le(u instanceof Error?u.message:u))}};let i=t&&setTimeout(()=>{i=null,o(new b(`timeout of ${t}ms exceeded`,b.ETIMEDOUT))},t);const a=()=>{e&&(i&&clearTimeout(i),i=null,e.forEach(f=>{f.unsubscribe?f.unsubscribe(o):f.removeEventListener("abort",o)}),e=null)};e.forEach(f=>f.addEventListener("abort",o));const{signal:p}=n;return p.unsubscribe=()=>c.asap(a),p}},sn=function*(e,t){let r=e.byteLength;if(r<t){yield e;return}let n=0,s;for(;n<r;)s=n+t,yield e.slice(n,s),n=s},on=async function*(e,t){for await(const r of an(e))yield*sn(r,t)},an=async function*(e){if(e[Symbol.asyncIterator]){yield*e;return}const t=e.getReader();try{for(;;){const{done:r,value:n}=await t.read();if(r)break;yield n}}finally{await t.cancel()}},mt=(e,t,r,n)=>{const s=on(e,t);let o=0,i,a=p=>{i||(i=!0,n&&n(p))};return new ReadableStream({async pull(p){try{const{done:f,value:u}=await s.next();if(f){a(),p.close();return}let m=u.byteLength;if(r){let g=o+=m;r(g)}p.enqueue(new Uint8Array(u))}catch(f){throw a(f),f}},cancel(p){return a(p),s.return()}},{highWaterMark:2})},yt=64*1024,{isFunction:ge}=c,cn=(({Request:e,Response:t})=>({Request:e,Response:t}))(c.global),{ReadableStream:wt,TextEncoder:bt}=c.global,Et=(e,...t)=>{try{return!!e(...t)}catch{return!1}},ln=e=>{e=c.merge.call({skipUndefined:!0},cn,e);const{fetch:t,Request:r,Response:n}=e,s=t?ge(t):typeof fetch=="function",o=ge(r),i=ge(n);if(!s)return!1;const a=s&&ge(wt),p=s&&(typeof bt=="function"?(d=>y=>d.encode(y))(new bt):async d=>new Uint8Array(await new r(d).arrayBuffer())),f=o&&a&&Et(()=>{let d=!1;const y=new r(F.origin,{body:new wt,method:"POST",get duplex(){return d=!0,"half"}}).headers.has("Content-Type");return d&&!y}),u=i&&a&&Et(()=>c.isReadableStream(new n("").body)),m={stream:u&&(d=>d.body)};s&&["text","arrayBuffer","blob","formData","stream"].forEach(d=>{!m[d]&&(m[d]=(y,h)=>{let _=y&&y[d];if(_)return _.call(y);throw new b(`Response type '${d}' is not supported`,b.ERR_NOT_SUPPORT,h)})});const g=async d=>{if(d==null)return 0;if(c.isBlob(d))return d.size;if(c.isSpecCompliantForm(d))return(await new r(F.origin,{method:"POST",body:d}).arrayBuffer()).byteLength;if(c.isArrayBufferView(d)||c.isArrayBuffer(d))return d.byteLength;if(c.isURLSearchParams(d)&&(d=d+""),c.isString(d))return(await p(d)).byteLength},A=async(d,y)=>{const h=c.toFiniteNumber(d.getContentLength());return h??g(y)};return async d=>{let{url:y,method:h,data:_,signal:C,cancelToken:w,timeout:T,onDownloadProgress:j,onUploadProgress:B,responseType:U,headers:ue,withCredentials:$="same-origin",fetchOptions:_e}=ht(d),Te=t||fetch;U=U?(U+"").toLowerCase():"text";let J=nn([C,w&&w.toAbortSignal()],T),V=null;const z=J&&J.unsubscribe&&(()=>{J.unsubscribe()});let Q;try{if(B&&f&&h!=="get"&&h!=="head"&&(Q=await A(ue,_))!==0){let l=new r(y,{method:"POST",body:_,duplex:"half"}),E;if(c.isFormData(_)&&(E=l.headers.get("content-type"))&&ue.setContentType(E),l.body){const[O,x]=ut(Q,Ee(ft(B)));_=mt(l.body,yt,O,x)}}c.isString($)||($=$?"include":"omit");const v=o&&"credentials"in r.prototype,fe={..._e,signal:J,method:h.toUpperCase(),headers:ue.normalize().toJSON(),body:_,duplex:"half",credentials:v?$:void 0};V=o&&new r(y,fe);let M=await(o?Te(V,_e):Te(y,fe));const de=u&&(U==="stream"||U==="response");if(u&&(j||de&&z)){const l={};["status","statusText","headers"].forEach(X=>{l[X]=M[X]});const E=c.toFiniteNumber(M.headers.get("content-length")),[O,x]=j&&ut(E,Ee(ft(j),!0))||[];M=new n(mt(M.body,yt,O,()=>{x&&x(),z&&z()}),l)}U=U||"text";let Oe=await m[c.findKey(m,U)||"text"](M,d);return!de&&z&&z(),await new Promise((l,E)=>{lt(l,E,{data:Oe,headers:L.from(M.headers),status:M.status,statusText:M.statusText,config:d,request:V})})}catch(v){throw z&&z(),v&&v.name==="TypeError"&&/Load failed|fetch/i.test(v.message)?Object.assign(new b("Network Error",b.ERR_NETWORK,d,V),{cause:v.cause||v}):b.from(v,v&&v.code,d,V)}}},un=new Map,gt=e=>{let t=e&&e.env||{};const{fetch:r,Request:n,Response:s}=t,o=[n,s,r];let i=o.length,a=i,p,f,u=un;for(;a--;)p=o[a],f=u.get(p),f===void 0&&u.set(p,f=a?new Map:ln(t)),u=f;return f};gt();const De={http:kr,xhr:rn,fetch:{get:gt}};c.forEach(De,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const Rt=e=>`- ${e}`,fn=e=>c.isFunction(e)||e===null||e===!1;function dn(e,t){e=c.isArray(e)?e:[e];const{length:r}=e;let n,s;const o={};for(let i=0;i<r;i++){n=e[i];let a;if(s=n,!fn(n)&&(s=De[(a=String(n)).toLowerCase()],s===void 0))throw new b(`Unknown adapter '${a}'`);if(s&&(c.isFunction(s)||(s=s.get(t))))break;o[a||"#"+i]=s}if(!s){const i=Object.entries(o).map(([p,f])=>`adapter ${p} `+(f===!1?"is not supported by the environment":"is not available in the build"));let a=r?i.length>1?`since :
|
|
70
70
|
`+i.map(Rt).join(`
|
|
71
71
|
`):" "+Rt(i[0]):"as no adapter specified";throw new b("There is no suitable adapter to dispatch the request "+a,"ERR_NOT_SUPPORT")}return s}const St={getAdapter:dn,adapters:De};function Le(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new le(null,e)}function _t(e){return Le(e),e.headers=L.from(e.headers),e.data=Fe.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),St.getAdapter(e.adapter||ae.adapter,e)(e).then(function(n){return Le(e),n.data=Fe.call(e,e.transformResponse,n),n.headers=L.from(n.headers),n},function(n){return ct(n)||(Le(e),n&&n.response&&(n.response.data=Fe.call(e,e.transformResponse,n.response),n.response.headers=L.from(n.response.headers))),Promise.reject(n)})}const Tt="1.13.4",Re={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{Re[e]=function(n){return typeof n===e||"a"+(t<1?"n ":" ")+e}});const Ot={};Re.transitional=function(t,r,n){function s(o,i){return"[Axios v"+Tt+"] Transitional option '"+o+"'"+i+(n?". "+n:"")}return(o,i,a)=>{if(t===!1)throw new b(s(i," has been removed"+(r?" in "+r:"")),b.ERR_DEPRECATED);return r&&!Ot[i]&&(Ot[i]=!0,console.warn(s(i," has been deprecated since v"+r+" and will be removed in the near future"))),t?t(o,i,a):!0}},Re.spelling=function(t){return(r,n)=>(console.warn(`${n} is likely a misspelling of ${t}`),!0)};function pn(e,t,r){if(typeof e!="object")throw new b("options must be an object",b.ERR_BAD_OPTION_VALUE);const n=Object.keys(e);let s=n.length;for(;s-- >0;){const o=n[s],i=t[o];if(i){const a=e[o],p=a===void 0||i(a,o,e);if(p!==!0)throw new b("option "+o+" must be "+p,b.ERR_BAD_OPTION_VALUE);continue}if(r!==!0)throw new b("Unknown option "+o,b.ERR_BAD_OPTION)}}const Se={assertOptions:pn,validators:Re},H=Se.validators;let Y=class{constructor(t){this.defaults=t||{},this.interceptors={request:new st,response:new st}}async request(t,r){try{return await this._request(t,r)}catch(n){if(n instanceof Error){let s={};Error.captureStackTrace?Error.captureStackTrace(s):s=new Error;const o=s.stack?s.stack.replace(/^.+\n/,""):"";try{n.stack?o&&!String(n.stack).endsWith(o.replace(/^.+\n.+\n/,""))&&(n.stack+=`
|
|
72
|
-
`+o):n.stack=o}catch{}}throw n}}_request(t,r){typeof t=="string"?(r=r||{},r.url=t):r=t||{},r=K(this.defaults,r);const{transitional:n,paramsSerializer:s,headers:o}=r;n!==void 0&&Se.assertOptions(n,{silentJSONParsing:H.transitional(H.boolean),forcedJSONParsing:H.transitional(H.boolean),clarifyTimeoutError:H.transitional(H.boolean)},!1),s!=null&&(c.isFunction(s)?r.paramsSerializer={serialize:s}:Se.assertOptions(s,{encode:H.function,serialize:H.function},!0)),r.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?r.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:r.allowAbsoluteUrls=!0),Se.assertOptions(r,{baseUrl:H.spelling("baseURL"),withXsrfToken:H.spelling("withXSRFToken")},!0),r.method=(r.method||this.defaults.method||"get").toLowerCase();let i=o&&c.merge(o.common,o[r.method]);o&&c.forEach(["delete","get","head","post","put","patch","common"],d=>{delete o[d]}),r.headers=L.concat(i,o);const a=[];let p=!0;this.interceptors.request.forEach(function(y){typeof y.runWhen=="function"&&y.runWhen(r)===!1||(p=p&&y.synchronous,a.unshift(y.fulfilled,y.rejected))});const f=[];this.interceptors.response.forEach(function(y){f.push(y.fulfilled,y.rejected)});let u,m=0,g;if(!p){const d=[_t.bind(this),void 0];for(d.unshift(...a),d.push(...f),g=d.length,u=Promise.resolve(r);m<g;)u=u.then(d[m++],d[m++]);return u}g=a.length;let A=r;for(;m<g;){const d=a[m++],y=a[m++];try{A=d(A)}catch(h){y.call(this,h);break}}try{u=_t.call(this,A)}catch(d){return Promise.reject(d)}for(m=0,g=f.length;m<g;)u=u.then(f[m++],f[m++]);return u}getUri(t){t=K(this.defaults,t);const r=dt(t.baseURL,t.url,t.allowAbsoluteUrls);return nt(r,t.params,t.paramsSerializer)}};c.forEach(["delete","get","head","options"],function(t){Y.prototype[t]=function(r,n){return this.request(K(n||{},{method:t,url:r,data:(n||{}).data}))}}),c.forEach(["post","put","patch"],function(t){function r(n){return function(o,i,a){return this.request(K(a||{},{method:t,headers:n?{"Content-Type":"multipart/form-data"}:{},url:o,data:i}))}}Y.prototype[t]=r(),Y.prototype[t+"Form"]=r(!0)});let hn=class Lt{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let r;this.promise=new Promise(function(o){r=o});const n=this;this.promise.then(s=>{if(!n._listeners)return;let o=n._listeners.length;for(;o-- >0;)n._listeners[o](s);n._listeners=null}),this.promise.then=s=>{let o;const i=new Promise(a=>{n.subscribe(a),o=a}).then(s);return i.cancel=function(){n.unsubscribe(o)},i},t(function(o,i,a){n.reason||(n.reason=new le(o,i,a),r(n.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 r=this._listeners.indexOf(t);r!==-1&&this._listeners.splice(r,1)}toAbortSignal(){const t=new AbortController,r=n=>{t.abort(n)};return this.subscribe(r),t.signal.unsubscribe=()=>this.unsubscribe(r),t.signal}static source(){let t;return{token:new Lt(function(s){t=s}),cancel:t}}};function mn(e){return function(r){return e.apply(null,r)}}function yn(e){return c.isObject(e)&&e.isAxiosError===!0}const Ue={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(Ue).forEach(([e,t])=>{Ue[t]=e});function At(e){const t=new Y(e),r=$e(Y.prototype.request,t);return c.extend(r,Y.prototype,t,{allOwnKeys:!0}),c.extend(r,t,null,{allOwnKeys:!0}),r.create=function(s){return At(K(e,s))},r}const N=At(ae);N.Axios=Y,N.CanceledError=le,N.CancelToken=hn,N.isCancel=ct,N.VERSION=Tt,N.toFormData=we,N.AxiosError=b,N.Cancel=N.CanceledError,N.all=function(t){return Promise.all(t)},N.spread=mn,N.isAxiosError=yn,N.mergeConfig=K,N.AxiosHeaders=L,N.formToJSON=e=>it(c.isHTMLForm(e)?new FormData(e):e),N.getAdapter=St.getAdapter,N.HttpStatusCode=Ue,N.default=N;const{Axios:Pn,AxiosError:kn,CanceledError:jn,isCancel:Fn,CancelToken:Dn,VERSION:Ln,all:Un,Cancel:vn,isAxiosError:In,spread:Bn,toFormData:Mn,AxiosHeaders:Hn,HttpStatusCode:qn,formToJSON:zn,getAdapter:$n,mergeConfig:Jn}=N,wn="http://localhost:8000/api";class xt{constructor(t,r=wn){Ft(this,"client");this.client=N.create({baseURL:r,headers:{"Content-Type":"application/json","X-API-Key":t},timeout:3e4}),this.client.interceptors.response.use(n=>n,n=>{var s,o;if((s=n.response)!=null&&s.data){const a=((o=n.response.data.response)==null?void 0:o.message)||"An unknown error occurred";throw new Error(a)}else throw n.request?new Error("No response from server. Please check your connection."):new Error(n.message||"Request failed")})}async sendMessage(t,r){try{const n=await this.client.post("/chat/",{question:t,session_id:r});if(n.data.response.status!=="success")throw new Error(n.data.response.message);return n.data.data}catch(n){throw n instanceof Error?n:new Error("Failed to send message")}}async getConversationHistory(t){try{const r=await this.client.get(`/chat/history/${t}/`);if(r.data.response.status!=="success")throw new Error(r.data.response.message);return r.data.data}catch(r){throw r instanceof Error?r:new Error("Failed to load conversation history")}}updateApiKey(t){this.client.defaults.headers.common["X-API-Key"]=t}updateBaseUrl(t){this.client.defaults.baseURL=t}}function ve(e,t){const[r,n]=S.useState(()=>{try{const o=window.localStorage.getItem(e);return o?JSON.parse(o):t}catch(o){return console.warn(`Error reading localStorage key "${e}":`,o),t}});return[r,o=>{try{const i=o instanceof Function?o(r):o;n(i),window.localStorage.setItem(e,JSON.stringify(i))}catch(i){console.warn(`Error setting localStorage key "${e}":`,i)}}]}function Ct(){return`session_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}const bn="customer_support_session_id",En="customer_support_messages";function Nt(e){const{apiKey:t,baseUrl:r,onError:n}=e,[s,o]=ve(En,[]),[i,a]=ve(bn,Ct()),[p,f]=S.useState(!1),[u,m]=S.useState(null),g=S.useRef(null);S.useEffect(()=>{g.current=new xt(t,r)},[t,r]);const A=S.useCallback(()=>{m(null)},[]),d=S.useCallback(async _=>{if(!g.current){const w=new Error("API client not initialized");m(w),n==null||n(w);return}if(!_.trim())return;const C={id:`user_${Date.now()}`,role:"USER",content:_,timestamp:new Date};o(w=>[...w,C]),f(!0),m(null);try{const w=await g.current.sendMessage(_,i),T={id:`assistant_${Date.now()}`,role:"ASSISTANT",content:w.answer,timestamp:new Date,sources:w.sources};o(j=>[...j,T]),w.session_id!==i&&a(w.session_id)}catch(w){const T=w instanceof Error?w:new Error("Failed to send message");m(T),n==null||n(T);const j={id:`error_${Date.now()}`,role:"ASSISTANT",content:`Sorry, I encountered an error: ${T.message}`,timestamp:new Date};o(B=>[...B,j])}finally{f(!1)}},[i,n,o,a]),y=S.useCallback(async()=>{if(!(!g.current||!i)){f(!0),m(null);try{const C=(await g.current.getConversationHistory(i)).messages.map((w,T)=>({id:`${w.role.toLowerCase()}_${T}_${Date.now()}`,role:w.role,content:w.content,timestamp:new Date(w.created_at)}));o(C)}catch(_){const C=_ instanceof Error?_:new Error("Failed to load history");m(C),n==null||n(C)}finally{f(!1)}}},[i,n,o]),h=S.useCallback(()=>{o([]),a(Ct())},[o,a]);return{messages:s,sendMessage:d,isLoading:p,error:u,clearError:A,sessionId:i,loadHistory:y,clearHistory:h}}const Pt=({message:e})=>{const t=e.role==="USER";return R.jsxs("div",{className:`cs-message ${t?"cs-message--user":"cs-message--assistant"}`,children:[R.jsxs("div",{className:"cs-message__content",children:[R.jsx("p",{className:"cs-message__text",children:e.content}),e.sources&&e.sources.length>0&&R.jsxs("div",{className:"cs-message__sources",children:[R.jsx("p",{className:"cs-message__sources-title",children:"Sources:"}),R.jsx("ul",{className:"cs-message__sources-list",children:e.sources.map((r,n)=>R.jsxs("li",{className:"cs-message__source-item",children:[R.jsxs("a",{href:r.url,target:"_blank",rel:"noopener noreferrer",className:"cs-message__source-link",children:[R.jsx(qt,{size:12}),R.jsx("span",{children:r.title})]}),R.jsxs("span",{className:"cs-message__source-similarity",children:[Math.round(r.similarity*100),"% match"]})]},n))})]})]}),R.jsx("time",{className:"cs-message__time",children:e.timestamp.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]})},kt=({onSendMessage:e,isLoading:t,placeholder:r="Type your message..."})=>{const[n,s]=S.useState(""),o=a=>{a.preventDefault(),n.trim()&&!t&&(e(n),s(""))},i=a=>{a.key==="Enter"&&!a.shiftKey&&(a.preventDefault(),o(a))};return R.jsxs("form",{className:"cs-input",onSubmit:o,children:[R.jsx("textarea",{className:"cs-input__textarea",value:n,onChange:a=>s(a.target.value),onKeyDown:i,placeholder:r,disabled:t,rows:1,"aria-label":"Message input"}),R.jsx("button",{type:"submit",className:"cs-input__button",disabled:!n.trim()||t,"aria-label":"Send message",children:R.jsx(Jt,{size:20})})]})},jt=({messages:e,onSendMessage:t,onClose:r,isLoading:n,error:s,placeholder:o,welcomeMessage:i="Hi! How can I help you today?"})=>{const a=S.useRef(null);return S.useEffect(()=>{var p;(p=a.current)==null||p.scrollIntoView({behavior:"smooth"})},[e]),R.jsxs("div",{className:"cs-window",children:[R.jsxs("div",{className:"cs-window__header",children:[R.jsx("h3",{className:"cs-window__title",children:"Customer Support"}),R.jsx("button",{className:"cs-window__close",onClick:r,"aria-label":"Close chat",children:R.jsx(Vt,{size:20})})]}),R.jsxs("div",{className:"cs-window__messages",children:[e.length===0&&!n&&R.jsx("div",{className:"cs-window__welcome",children:R.jsx("p",{children:i})}),e.map(p=>R.jsx(Pt,{message:p},p.id)),n&&R.jsxs("div",{className:"cs-window__typing",children:[R.jsx(zt,{size:20,className:"cs-window__typing-icon"}),R.jsx("span",{children:"Thinking..."})]}),s&&R.jsx("div",{className:"cs-window__error",children:R.jsx("p",{children:s.message})}),R.jsx("div",{ref:a})]}),R.jsx("div",{className:"cs-window__input-wrapper",children:R.jsx(kt,{onSendMessage:t,isLoading:n,placeholder:o})})]})},gn=({apiKey:e,baseUrl:t,theme:r,position:n="bottom-right",welcomeMessage:s,placeholder:o,className:i="",onError:a,onMessageSent:p,onMessageReceived:f})=>{const[u,m]=S.useState(!1),{messages:g,sendMessage:A,isLoading:d,error:y,clearError:h}=Nt({apiKey:e,baseUrl:t,onError:a});S.useEffect(()=>{if(r){const w=document.documentElement;r.primaryColor&&w.style.setProperty("--cs-primary-color",r.primaryColor),r.secondaryColor&&w.style.setProperty("--cs-secondary-color",r.secondaryColor),r.backgroundColor&&w.style.setProperty("--cs-bg-color",r.backgroundColor),r.textColor&&w.style.setProperty("--cs-text-color",r.textColor),r.fontFamily&&w.style.setProperty("--cs-font-family",r.fontFamily),r.borderRadius&&w.style.setProperty("--cs-border-radius",r.borderRadius),r.buttonColor&&w.style.setProperty("--cs-button-color",r.buttonColor),r.userMessageColor&&w.style.setProperty("--cs-user-message-color",r.userMessageColor),r.assistantMessageColor&&w.style.setProperty("--cs-assistant-message-color",r.assistantMessageColor)}},[r]);const _=async w=>{if(p==null||p(w),await A(w),!y){const T=g[g.length-1];(T==null?void 0:T.role)==="ASSISTANT"&&(f==null||f(T.content))}},C=()=>{m(!u),y&&h()};return R.jsxs("div",{className:`cs-widget cs-widget--${n} ${i}`,children:[u&&R.jsx(jt,{messages:g,onSendMessage:_,onClose:()=>m(!1),isLoading:d,error:y,placeholder:o,welcomeMessage:s}),R.jsxs("button",{className:`cs-widget__toggle ${u?"cs-widget__toggle--open":""}`,onClick:C,"aria-label":u?"Close chat":"Open chat","aria-expanded":u,children:[R.jsx($t,{size:24}),!u&&g.length>0&&R.jsx("span",{className:"cs-widget__badge",children:g.filter(w=>w.role==="ASSISTANT").length})]})]})};P.ChatInput=kt,P.ChatMessage=Pt,P.ChatWindow=jt,P.CustomerSupportAPIClient=xt,P.CustomerSupportWidget=gn,P.useCustomerSupport=Nt,P.useLocalStorage=ve,Object.defineProperty(P,Symbol.toStringTag,{value:"Module"})}));
|
|
72
|
+
`+o):n.stack=o}catch{}}throw n}}_request(t,r){typeof t=="string"?(r=r||{},r.url=t):r=t||{},r=K(this.defaults,r);const{transitional:n,paramsSerializer:s,headers:o}=r;n!==void 0&&Se.assertOptions(n,{silentJSONParsing:H.transitional(H.boolean),forcedJSONParsing:H.transitional(H.boolean),clarifyTimeoutError:H.transitional(H.boolean)},!1),s!=null&&(c.isFunction(s)?r.paramsSerializer={serialize:s}:Se.assertOptions(s,{encode:H.function,serialize:H.function},!0)),r.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?r.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:r.allowAbsoluteUrls=!0),Se.assertOptions(r,{baseUrl:H.spelling("baseURL"),withXsrfToken:H.spelling("withXSRFToken")},!0),r.method=(r.method||this.defaults.method||"get").toLowerCase();let i=o&&c.merge(o.common,o[r.method]);o&&c.forEach(["delete","get","head","post","put","patch","common"],d=>{delete o[d]}),r.headers=L.concat(i,o);const a=[];let p=!0;this.interceptors.request.forEach(function(y){typeof y.runWhen=="function"&&y.runWhen(r)===!1||(p=p&&y.synchronous,a.unshift(y.fulfilled,y.rejected))});const f=[];this.interceptors.response.forEach(function(y){f.push(y.fulfilled,y.rejected)});let u,m=0,g;if(!p){const d=[_t.bind(this),void 0];for(d.unshift(...a),d.push(...f),g=d.length,u=Promise.resolve(r);m<g;)u=u.then(d[m++],d[m++]);return u}g=a.length;let A=r;for(;m<g;){const d=a[m++],y=a[m++];try{A=d(A)}catch(h){y.call(this,h);break}}try{u=_t.call(this,A)}catch(d){return Promise.reject(d)}for(m=0,g=f.length;m<g;)u=u.then(f[m++],f[m++]);return u}getUri(t){t=K(this.defaults,t);const r=dt(t.baseURL,t.url,t.allowAbsoluteUrls);return nt(r,t.params,t.paramsSerializer)}};c.forEach(["delete","get","head","options"],function(t){Y.prototype[t]=function(r,n){return this.request(K(n||{},{method:t,url:r,data:(n||{}).data}))}}),c.forEach(["post","put","patch"],function(t){function r(n){return function(o,i,a){return this.request(K(a||{},{method:t,headers:n?{"Content-Type":"multipart/form-data"}:{},url:o,data:i}))}}Y.prototype[t]=r(),Y.prototype[t+"Form"]=r(!0)});let hn=class Lt{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let r;this.promise=new Promise(function(o){r=o});const n=this;this.promise.then(s=>{if(!n._listeners)return;let o=n._listeners.length;for(;o-- >0;)n._listeners[o](s);n._listeners=null}),this.promise.then=s=>{let o;const i=new Promise(a=>{n.subscribe(a),o=a}).then(s);return i.cancel=function(){n.unsubscribe(o)},i},t(function(o,i,a){n.reason||(n.reason=new le(o,i,a),r(n.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 r=this._listeners.indexOf(t);r!==-1&&this._listeners.splice(r,1)}toAbortSignal(){const t=new AbortController,r=n=>{t.abort(n)};return this.subscribe(r),t.signal.unsubscribe=()=>this.unsubscribe(r),t.signal}static source(){let t;return{token:new Lt(function(s){t=s}),cancel:t}}};function mn(e){return function(r){return e.apply(null,r)}}function yn(e){return c.isObject(e)&&e.isAxiosError===!0}const Ue={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(Ue).forEach(([e,t])=>{Ue[t]=e});function At(e){const t=new Y(e),r=$e(Y.prototype.request,t);return c.extend(r,Y.prototype,t,{allOwnKeys:!0}),c.extend(r,t,null,{allOwnKeys:!0}),r.create=function(s){return At(K(e,s))},r}const N=At(ae);N.Axios=Y,N.CanceledError=le,N.CancelToken=hn,N.isCancel=ct,N.VERSION=Tt,N.toFormData=we,N.AxiosError=b,N.Cancel=N.CanceledError,N.all=function(t){return Promise.all(t)},N.spread=mn,N.isAxiosError=yn,N.mergeConfig=K,N.AxiosHeaders=L,N.formToJSON=e=>it(c.isHTMLForm(e)?new FormData(e):e),N.getAdapter=St.getAdapter,N.HttpStatusCode=Ue,N.default=N;const{Axios:Pn,AxiosError:kn,CanceledError:jn,isCancel:Fn,CancelToken:Dn,VERSION:Ln,all:Un,Cancel:vn,isAxiosError:In,spread:Bn,toFormData:Mn,AxiosHeaders:Hn,HttpStatusCode:qn,formToJSON:zn,getAdapter:$n,mergeConfig:Jn}=N,wn="http://localhost:8000/api";class xt{constructor(t,r=wn){Ft(this,"client");this.client=N.create({baseURL:r,headers:{"Content-Type":"application/json","X-API-Key":t},timeout:3e4}),this.client.interceptors.response.use(n=>n,n=>{var s,o;if((s=n.response)!=null&&s.data){const a=((o=n.response.data.response)==null?void 0:o.message)||"An unknown error occurred";throw new Error(a)}else throw n.request?new Error("No response from server. Please check your connection."):new Error(n.message||"Request failed")})}async sendMessage(t,r){try{const n=await this.client.post("/chat/",{question:t,session_id:r});if(n.data.response.status!=="success")throw new Error(n.data.response.message);return n.data.data}catch(n){throw n instanceof Error?n:new Error("Failed to send message")}}async getConversationHistory(t){try{const r=await this.client.get(`/chat/history/${t}/`);if(r.data.response.status!=="success")throw new Error(r.data.response.message);return r.data.data}catch(r){throw r instanceof Error?r:new Error("Failed to load conversation history")}}updateApiKey(t){this.client.defaults.headers.common["X-API-Key"]=t}updateBaseUrl(t){this.client.defaults.baseURL=t}}function ve(e,t){const[r,n]=S.useState(()=>{try{const o=window.localStorage.getItem(e);return o?JSON.parse(o):t}catch(o){return console.warn(`Error reading localStorage key "${e}":`,o),t}});return[r,o=>{try{const i=o instanceof Function?o(r):o;n(i),window.localStorage.setItem(e,JSON.stringify(i))}catch(i){console.warn(`Error setting localStorage key "${e}":`,i)}}]}function Ct(){return`session_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}const bn="customer_support_session_id",En="customer_support_messages";function Nt(e){const{apiKey:t,baseUrl:r,onError:n}=e,[s,o]=ve(En,[]),[i,a]=ve(bn,Ct()),[p,f]=S.useState(!1),[u,m]=S.useState(null),g=S.useRef(null);S.useEffect(()=>{g.current=new xt(t,r)},[t,r]);const A=S.useCallback(()=>{m(null)},[]),d=S.useCallback(async _=>{if(!g.current){const w=new Error("API client not initialized");m(w),n==null||n(w);return}if(!_.trim())return;const C={id:`user_${Date.now()}`,role:"USER",content:_,timestamp:new Date};o(w=>[...w,C]),f(!0),m(null);try{const w=await g.current.sendMessage(_,i),T={id:`assistant_${Date.now()}`,role:"ASSISTANT",content:w.answer,timestamp:new Date,sources:w.sources};o(j=>[...j,T]),w.session_id!==i&&a(w.session_id)}catch(w){const T=w instanceof Error?w:new Error("Failed to send message");m(T),n==null||n(T);const j={id:`error_${Date.now()}`,role:"ASSISTANT",content:`Sorry, I encountered an error: ${T.message}`,timestamp:new Date};o(B=>[...B,j])}finally{f(!1)}},[i,n,o,a]),y=S.useCallback(async()=>{if(!(!g.current||!i)){f(!0),m(null);try{const C=(await g.current.getConversationHistory(i)).messages.map((w,T)=>({id:`${w.role.toLowerCase()}_${T}_${Date.now()}`,role:w.role,content:w.content,timestamp:new Date(w.created_at)}));o(C)}catch(_){const C=_ instanceof Error?_:new Error("Failed to load history");m(C),n==null||n(C)}finally{f(!1)}}},[i,n,o]),h=S.useCallback(()=>{o([]),a(Ct())},[o,a]);return{messages:s,sendMessage:d,isLoading:p,error:u,clearError:A,sessionId:i,loadHistory:y,clearHistory:h}}const Pt=({message:e})=>{const t=e.role==="USER",r=e.timestamp instanceof Date?e.timestamp:new Date(e.timestamp);return R.jsxs("div",{className:`cs-message ${t?"cs-message--user":"cs-message--assistant"}`,children:[R.jsxs("div",{className:"cs-message__content",children:[R.jsx("p",{className:"cs-message__text",children:e.content}),e.sources&&e.sources.length>0&&R.jsxs("div",{className:"cs-message__sources",children:[R.jsx("p",{className:"cs-message__sources-title",children:"Sources:"}),R.jsx("ul",{className:"cs-message__sources-list",children:e.sources.map((n,s)=>R.jsxs("li",{className:"cs-message__source-item",children:[R.jsxs("a",{href:n.url,target:"_blank",rel:"noopener noreferrer",className:"cs-message__source-link",children:[R.jsx(qt,{size:12}),R.jsx("span",{children:n.title})]}),R.jsxs("span",{className:"cs-message__source-similarity",children:[Math.round(n.similarity*100),"% match"]})]},s))})]})]}),R.jsx("time",{className:"cs-message__time",dateTime:r.toISOString(),children:r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]})},kt=({onSendMessage:e,isLoading:t,placeholder:r="Type your message..."})=>{const[n,s]=S.useState(""),o=a=>{a.preventDefault(),n.trim()&&!t&&(e(n),s(""))},i=a=>{a.key==="Enter"&&!a.shiftKey&&(a.preventDefault(),o(a))};return R.jsxs("form",{className:"cs-input",onSubmit:o,children:[R.jsx("textarea",{className:"cs-input__textarea",value:n,onChange:a=>s(a.target.value),onKeyDown:i,placeholder:r,disabled:t,rows:1,"aria-label":"Message input"}),R.jsx("button",{type:"submit",className:"cs-input__button",disabled:!n.trim()||t,"aria-label":"Send message",children:R.jsx(Jt,{size:20})})]})},jt=({messages:e,onSendMessage:t,onClose:r,isLoading:n,error:s,placeholder:o,welcomeMessage:i="Hi! How can I help you today?"})=>{const a=S.useRef(null);return S.useEffect(()=>{var p;(p=a.current)==null||p.scrollIntoView({behavior:"smooth"})},[e]),R.jsxs("div",{className:"cs-window",children:[R.jsxs("div",{className:"cs-window__header",children:[R.jsx("h3",{className:"cs-window__title",children:"Customer Support"}),R.jsx("button",{className:"cs-window__close",onClick:r,"aria-label":"Close chat",children:R.jsx(Vt,{size:20})})]}),R.jsxs("div",{className:"cs-window__messages",children:[e.length===0&&!n&&R.jsx("div",{className:"cs-window__welcome",children:R.jsx("p",{children:i})}),e.map(p=>R.jsx(Pt,{message:p},p.id)),n&&R.jsxs("div",{className:"cs-window__typing",children:[R.jsx(zt,{size:20,className:"cs-window__typing-icon"}),R.jsx("span",{children:"Thinking..."})]}),s&&R.jsx("div",{className:"cs-window__error",children:R.jsx("p",{children:s.message})}),R.jsx("div",{ref:a})]}),R.jsx("div",{className:"cs-window__input-wrapper",children:R.jsx(kt,{onSendMessage:t,isLoading:n,placeholder:o})})]})},gn=({apiKey:e,baseUrl:t,theme:r,position:n="bottom-right",welcomeMessage:s,placeholder:o,className:i="",onError:a,onMessageSent:p,onMessageReceived:f})=>{const[u,m]=S.useState(!1),{messages:g,sendMessage:A,isLoading:d,error:y,clearError:h}=Nt({apiKey:e,baseUrl:t,onError:a});S.useEffect(()=>{if(r){const w=document.documentElement;r.primaryColor&&w.style.setProperty("--cs-primary-color",r.primaryColor),r.secondaryColor&&w.style.setProperty("--cs-secondary-color",r.secondaryColor),r.backgroundColor&&w.style.setProperty("--cs-bg-color",r.backgroundColor),r.textColor&&w.style.setProperty("--cs-text-color",r.textColor),r.fontFamily&&w.style.setProperty("--cs-font-family",r.fontFamily),r.borderRadius&&w.style.setProperty("--cs-border-radius",r.borderRadius),r.buttonColor&&w.style.setProperty("--cs-button-color",r.buttonColor),r.userMessageColor&&w.style.setProperty("--cs-user-message-color",r.userMessageColor),r.assistantMessageColor&&w.style.setProperty("--cs-assistant-message-color",r.assistantMessageColor)}},[r]);const _=async w=>{if(p==null||p(w),await A(w),!y){const T=g[g.length-1];(T==null?void 0:T.role)==="ASSISTANT"&&(f==null||f(T.content))}},C=()=>{m(!u),y&&h()};return R.jsxs("div",{className:`cs-widget cs-widget--${n} ${i}`,children:[u&&R.jsx(jt,{messages:g,onSendMessage:_,onClose:()=>m(!1),isLoading:d,error:y,placeholder:o,welcomeMessage:s}),R.jsxs("button",{className:`cs-widget__toggle ${u?"cs-widget__toggle--open":""}`,onClick:C,"aria-label":u?"Close chat":"Open chat","aria-expanded":u,children:[R.jsx($t,{size:24}),!u&&g.length>0&&R.jsx("span",{className:"cs-widget__badge",children:g.filter(w=>w.role==="ASSISTANT").length})]})]})};P.ChatInput=kt,P.ChatMessage=Pt,P.ChatWindow=jt,P.CustomerSupportAPIClient=xt,P.CustomerSupportWidget=gn,P.useCustomerSupport=Nt,P.useLocalStorage=ve,Object.defineProperty(P,Symbol.toStringTag,{value:"Module"})}));
|
|
73
73
|
//# sourceMappingURL=index.umd.js.map
|