@chatsystem/client 1.2.2 → 1.2.3
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 +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.mjs +12 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -144,7 +144,7 @@ For more details see https://formatjs.io/docs/getting-started/message-distributi
|
|
|
144
144
|
transition-colors
|
|
145
145
|
enabled:hover:scale-[1.02] active:scale-[0.98]
|
|
146
146
|
chatsystem-mic-button
|
|
147
|
-
${n??""}`,"data-testid":"mic-button",onClick:e,disabled:t,type:"button","aria-label":"Start voice input",children:x.jsx("span",{"data-state":"closed",children:x.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",width:"24",height:"24","aria-hidden":"true",className:"text-white dark:text-black",children:[x.jsx("path",{d:"M12 14.5c1.66 0 3-1.34 3-3V6.5c0-1.66-1.34-3-3-3s-3 1.34-3 3v5c0 1.66 1.34 3 3 3Z",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinejoin:"round"}),x.jsx("path",{d:"M12 14.5V18",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round"}),x.jsx("path",{d:"M8.5 18h7",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round"}),x.jsx("path",{d:"M7 11.5c0 2.76 2.24 5 5 5s5-2.24 5-5",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round"})]})})})});function F_(){const[e,t]=C.useState("idle"),[n,r]=C.useState(null),[i,a]=C.useState(0),s=C.useRef(null),o=C.useRef(null),u=C.useRef([]),c=C.useRef(null),d=C.useRef(null),f=C.useRef(null),p=C.useRef(null),h=C.useCallback(()=>{p.current!==null&&(cancelAnimationFrame(p.current),p.current=null);try{f.current?.disconnect()}catch{}f.current=null;try{d.current?.disconnect()}catch{}d.current=null;const v=c.current;c.current=null,v&&v.close().catch(()=>{}),a(0)},[]),b=C.useCallback(v=>{try{const k=new AudioContext,L=k.createAnalyser(),A=k.createMediaStreamSource(v);L.fftSize=256,L.smoothingTimeConstant=.85,A.connect(L),c.current=k,d.current=L,f.current=A;const N=new Uint8Array(L.fftSize),Y=()=>{const X=d.current;if(!X)return;X.getByteTimeDomainData(N);let ne=0;for(let z=0;z<N.length;z++){const B=(N[z]-128)/128;ne+=B*B}const I=Math.sqrt(ne/N.length),U=Math.min(1,I*6);a(U),p.current=requestAnimationFrame(Y)};p.current=requestAnimationFrame(Y)}catch{a(0)}},[]),y=C.useCallback(async()=>{r(null),h();try{const v=await navigator.mediaDevices.getUserMedia({audio:!0});o.current=v,b(v);const L=["audio/webm;codecs=opus","audio/webm","audio/ogg;codecs=opus","audio/ogg"].find(N=>MediaRecorder.isTypeSupported(N))||"",A=new MediaRecorder(v,L?{mimeType:L}:void 0);s.current=A,u.current=[],A.ondataavailable=N=>{N.data&&N.data.size>0&&u.current.push(N.data)},A.onerror=()=>{t("error"),r("Recorder error.")},A.onstart=()=>t("recording"),A.onstop=()=>t("stopped"),A.start()}catch(v){h(),t("error"),r(v?.message??"Microphone permission denied.")}},[b,h]),w=C.useCallback(async()=>{const v=s.current,k=o.current;return!v||e!=="recording"?null:new Promise(L=>{v.onstop=()=>{h();const A=v.mimeType||"audio/webm",N=new Blob(u.current,{type:A}),Y=A.includes("ogg")?"ogg":"webm",X=new File([N],`voice-message.${Y}`,{type:A});k?.getTracks().forEach(ne=>ne.stop()),o.current=null,s.current=null,L({blob:N,file:X})},v.stop()})},[e,h]),S=C.useCallback(()=>{const v=s.current,k=o.current;try{v&&e==="recording"&&v.stop()}catch{}h(),k?.getTracks().forEach(L=>L.stop()),o.current=null,s.current=null,u.current=[],t("idle")},[e,h]);return C.useEffect(()=>()=>{h(),o.current?.getTracks().forEach(v=>v.stop())},[h]),{state:e,error:n,audioLevel:i,start:y,stop:w,cancel:S}}const H_=()=>{const e=sn(),t=e.formatMessage({defaultMessage:"Recording...",id:"recordingOverlay.recording"}),n=e.formatMessage({defaultMessage:"Cancel",id:"recordingOverlay.cancel"}),r=e.formatMessage({defaultMessage:"Tap the mic to stop",id:"recordingOverlay.explaination"});return{recordingTranslation:t,cancelTranslation:n,recordingExplainationTranslation:r}},U_=({isOpen:e,onStop:t,onCancel:n,audioLevel:r=0})=>{const{recordingTranslation:i}=H_(),a=C.useMemo(()=>{const s=Math.max(0,Math.min(1,r));return Array.from({length:20},(o,u)=>{const c=Math.sin(u/19*Math.PI*2)*.5+.5,d=u%2===0?.9:.65,f=6+s*(14+c*18)*d;return Math.round(f)})},[r]);return e?x.jsx("div",{className:"relative mt-3 w-full rounded-lg border border-slate-400 bg-white p-1",role:"group","aria-label":"Recording voice message",children:x.jsxs("div",{className:"flex min-h-[48px] items-center gap-3 px-2",children:[x.jsxs("div",{className:"relative flex h-8 w-8 items-center justify-center",children:[x.jsx("span",{className:"absolute h-5 w-5 rounded-full bg-red-100 motion-safe:animate-ping","aria-hidden":!0}),x.jsx("span",{className:"absolute h-5 w-5 rounded-full bg-red-50","aria-hidden":!0}),x.jsx("span",{className:"absolute h-3.5 w-3.5 rounded-full bg-red-200","aria-hidden":!0}),x.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-red-500","aria-hidden":!0})]}),x.jsxs("div",{className:"min-w-0 flex-1",children:[x.jsx("div",{className:"mb-0.5 text-[11px] font-medium leading-3 text-slate-600",children:i}),x.jsx("div",{className:"flex h-5 items-center gap-[3px] overflow-hidden","aria-hidden":"true",children:a.map((s,o)=>x.jsx("span",{className:"block w-1 rounded-full bg-slate-400 transition-[height,background-color] duration-75",style:{height:`${s}px`,backgroundColor:r>.08?"rgb(59 130 246)":"rgb(148 163 184)"}},o))})]}),x.jsx("button",{type:"button",onClick:n,className:"flex h-9 w-9 items-center justify-center rounded-full text-slate-500 hover:bg-slate-100 hover:text-slate-700","aria-label":"Cancel recording",children:x.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",width:"18",height:"18","aria-hidden":"true",children:x.jsx("path",{d:"M6 6l12 12M18 6L6 18",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})})}),x.jsx("button",{type:"button",onClick:t,className:"flex h-9 w-9 items-center justify-center rounded-full bg-violet-600 text-white hover:bg-violet-700","aria-label":"Validate recording",children:x.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",width:"18",height:"18","aria-hidden":"true",children:x.jsx("path",{d:"M5 13l4 4L19 7",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round"})})})]})}):null},j_=e=>/(\[.*|!\[.*)$/.test(e),z_=e=>/\)/.test(e),nu=()=>({rendered:"",markdownTag:"",isWritingTag:!1,lastStreamSourceUuid:null});class $_{buffers=new Map;callbacks;constructor(t){this.callbacks=t}handleStart(t){this.buffers.set(t.messageId,nu()),t.role==="assistant"&&this.callbacks.onAssistantMessageStart?.(),this.callbacks.addEmptyMessage({messageStreamId:t.messageId,role:t.role})}handleDelta(t){this.ensureBufferExists(t.messageId);const n=this.buffers.get(t.messageId);this.appendSourceSeparatorIfNeeded(n,t.streamSourceUuid),this.appendDelta(n,t.delta),this.callbacks.updateMessage({id:t.messageId,newContent:n.rendered})}handleEnd(t){this.buffers.delete(t.messageId)}hasBuffer(t){return this.buffers.has(t)}ensureBufferExists(t){this.buffers.has(t)||(this.buffers.set(t,nu()),this.callbacks.addEmptyMessage({messageStreamId:t,role:"assistant"}))}appendSourceSeparatorIfNeeded(t,n){t.lastStreamSourceUuid&&t.lastStreamSourceUuid!==n&&(t.rendered+='<span style="display:block;height:1rem;"></span>'),t.lastStreamSourceUuid=n??null}appendDelta(t,n){if(z_(n)){t.markdownTag+=n,t.rendered+=t.markdownTag,t.markdownTag="",t.isWritingTag=!1;return}if(t.isWritingTag||j_(n)){t.markdownTag+=n,t.isWritingTag=!0;return}t.rendered+=n}}const Y_=30,G_=e=>{try{const t=e.split(".")[1];if(!t)return null;const n=t.replace(/-/g,"+").replace(/_/g,"/"),r=n.padEnd(n.length+(4-n.length%4)%4,"="),i=JSON.parse(atob(r));return typeof i.exp=="number"?i.exp:null}catch{return null}};class q_{token=null;expiresAt=null;pendingRequest=null;pendingRequestIsInteractive=!1;generation=0;provider;constructor(t){this.provider=t}clear(){this.generation+=1,this.token=null,this.expiresAt=null,this.pendingRequest=null,this.pendingRequestIsInteractive=!1}async getToken(t){if(!this.provider)return null;const n=Math.floor(Date.now()/1e3);if(this.token&&this.expiresAt!=null&&this.expiresAt-Y_>n)return this.token;if(this.pendingRequest){const a=this.pendingRequestIsInteractive,s=await this.pendingRequest;if(s||!t.interactive||a)return s}const r=this.generation;this.pendingRequestIsInteractive=t.interactive;let i;return i=this.provider.getToken(t).then(a=>{if(r!==this.generation)return null;if(!a)return this.clear(),null;const s=G_(a);return s==null||s<=Math.floor(Date.now()/1e3)?(this.clear(),null):(this.token=a,this.expiresAt=s,a)}).finally(()=>{this.pendingRequest===i&&(this.pendingRequest=null,this.pendingRequestIsInteractive=!1)}),this.pendingRequest=i,i}}const ud=C.createContext(void 0),V_=async({apiUrl:e,appToken:t,payload:n,identitySession:r,fetchImplementation:i=fetch})=>{let a=null,s;try{a=await r.getToken({interactive:!0,reason:n.reason,requiredCapabilities:n.requiredCapabilities}),a||(a=await r.getToken({interactive:!1,reason:n.reason,requiredCapabilities:n.requiredCapabilities})),s=a?{status:"success"}:{status:"cancelled"}}catch{r.clear(),s={status:"failed",code:"HOST_IDENTITY_FAILED"}}const o=await i(`${e}/ai/identity-gates/${encodeURIComponent(t)}/${encodeURIComponent(n.gateId)}/result`,{method:"POST",headers:{"Content-Type":"application/json","X-ChatSystem-Identity-Gate-Token":n.resultToken,...a?{Authorization:`Bearer ${a}`}:{}},body:JSON.stringify(s)});if(!o.ok)throw o.status===401&&a&&r.clear(),new Error(`IDENTITY_GATE_RESOLUTION_FAILED:${o.status}`)},W_="chatsystem:pending-turn:",X_=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,rs=e=>`${W_}${encodeURIComponent(e)}`,ld=(e,t=Date.now())=>{if(!e||typeof e!="object"||Array.isArray(e))return null;const n=e;if(typeof n.continuationId!="string"||!X_.test(n.continuationId)||typeof n.expiresAt!="string"||typeof n.discussionId!="number"||!Number.isSafeInteger(n.discussionId)||n.discussionId<=0)return null;const r=Date.parse(n.expiresAt);return!Number.isFinite(r)||r<=t?null:{continuationId:n.continuationId,expiresAt:n.expiresAt,discussionId:n.discussionId}},Q_=(e,t,n,r=sessionStorage)=>{const i=ld({...t,discussionId:n});i&&r.setItem(rs(e),JSON.stringify(i))},K_=(e,t=sessionStorage,n=Date.now())=>{const r=rs(e),i=t.getItem(r);if(!i)return null;try{const a=ld(JSON.parse(i),n);if(a)return a}catch{}return t.removeItem(r),null},ru=(e,t=sessionStorage)=>{t.removeItem(rs(e))},J_=async({apiUrl:e,appToken:t,discussionId:n,continuation:r,identitySession:i,fetchImplementation:a=fetch})=>{if(!Number.isSafeInteger(n)||n<=0)return null;const s=await i.getToken({interactive:!1});if(!s)return null;const o={discussionId:n};return a(`${e}/ai/pending-turns/${encodeURIComponent(t)}/${encodeURIComponent(r.continuationId)}/resume`,{method:"POST",headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"},body:JSON.stringify(o)})},Z_=e=>e>=200&&e<300||e>=400&&e<500&&e!==429||e===503;let gr=new AbortController;const cd=({appToken:e,agentId:t,containerClassName:n})=>{const r=Sn(),i=Kr(),a=C.useContext(ud);e||r.error("App Token missing");const s=C.useRef(null),o=C.useRef(null),u=C.useRef(a),c=C.useRef(new Set),d=C.useRef(null),f=C.useRef(null),p=C.useRef(null),[h,b]=C.useState(0);(!o.current||u.current!==a)&&(u.current=a,o.current=new q_(a)),C.useEffect(()=>{const le=o.current;if(!(!le||!a))return le.getToken({interactive:!1}).catch(()=>le.clear()),a.subscribe?.(()=>{le.clear(),b(Ce=>Ce+1),le.getToken({interactive:!1}).catch(()=>le.clear())})},[a]);const{placeholderTranslation:y,genericErrorTranslation:w,tooManyRequestsTranslation:S,discussionFullErrorTranslation:v,infoBannerExplainationTranslation:k,infoBannerTitleTranslation:L,customerSupportConnectingTranslation:A,customerSupportConnectedTranslation:N,customerSupportConnectionErrorTranslation:Y,customerSupportProviderUnavailableTranslation:X,customerSupportClosedTranslation:ne,customerSupportRestartTranslation:I,customerSupportFallbackTitleTranslation:U,customerSupportFallbackDescriptionTranslation:z,customerSupportFallbackEmailTranslation:B,customerSupportFallbackPhoneTranslation:$,customerSupportFallbackSubmitTranslation:K,customerSupportFallbackSubmittingTranslation:he,customerSupportFallbackSuccessTranslation:pe,customerSupportFallbackErrorTranslation:Se,customerSupportClosedHoursTitleTranslation:Le,customerSupportClosedHoursDescriptionTranslation:m,customerSupportClosedHoursSchedulePrefixTranslation:G,customerSupportClosedHoursReasonTranslation:re,customerSupportClosedHoursSuccessTranslation:T}=Ju(),{currentConversation:W,addEmptyMessageToCurrentConversation:ce,addMessageToCurrentConversation:V,removeEmptyAssistantMessageFromCurrentConversation:oe,resetConversation:ae,setCurrentConversationId:de,updateCurrentConversationMessageById:ie,archivedConversation:ke,chatboxBootState:q,resetConversationRequestId:Ne,setArchivedConversationAsMain:qe}=ns(),[Be,He]=C.useState("notLoading"),{defaultStartingStep:vt,recentMessagesTranslation:je}=sd(),[Dt,kt]=C.useState(null),[be,Ie]=C.useState(vt),[H,J]=C.useState(null),[O,P]=C.useState(!1),{scrollToBottom:Q,showScrollButton:ue,messagesContainerRef:Z,requestScrollToBottomAfterNextRender:_e,messagesContentRef:at}=N_(W.items),{chatTransportMode:et,isCustomerSupportMode:Ve,customerSupportStatusMessage:Pt,isCustomerSupportInputDisabled:Ke,enterCustomerSupportMode:Mt,flushPendingCustomerSupportHandoff:ht,sendToCustomerSupport:yd,fallbackContactCaptureConfig:ss,fallbackContactCaptureStatus:xd,shouldDisplayFallbackContactCapture:_d,submitFallbackContactCapture:Sd,closedHoursContactCaptureConfig:os,closedHoursBusinessHours:Cd,closedHoursContactCaptureStatus:Ad,shouldDisplayClosedHoursContactCapture:wd,submitClosedHoursContactCapture:Id}=S_({appToken:e,currentConversation:W,loadingStatus:Be,labels:{connecting:A,connected:N,connectionError:Y,providerUnavailable:X,closed:ne},logger:r,setCurrentConversationId:de,setLoadingStatus:He,addMessageToCurrentConversation:V,chatboxBootState:q,resetConversationRequestId:Ne}),[us,ti]=C.useState(!1),{start:vd,stop:kd,cancel:Nd,audioLevel:Rd}=F_(),{companySettings:ni}=C.useContext(rn),{appCurrentLang:ls}=C.useContext(td),[Od,Ld]=C.useState(()=>{if(typeof window>"u")return!0;const le=window.matchMedia("(pointer: coarse)"),Ce=window.matchMedia("(hover: none)");return!(le.matches||Ce.matches)}),ri=C.useRef(null);ri.current||(ri.current=new $_({addEmptyMessage:ce,updateMessage:ie,onAssistantMessageStart:()=>He("loadingDisplayedAnswer")}));const ii=ri.current;C.useEffect(()=>{if(typeof window>"u")return;const le=window.matchMedia("(pointer: coarse)"),Ce=window.matchMedia("(hover: none)"),Me=()=>{Ld(!(le.matches||Ce.matches))};return Me(),le.addEventListener?(le.addEventListener("change",Me),Ce.addEventListener("change",Me)):(le.addListener(Me),Ce.addListener(Me)),()=>{le.removeEventListener?(le.removeEventListener("change",Me),Ce.removeEventListener("change",Me)):(le.removeListener(Me),Ce.removeListener(Me))}},[]);const Dd=Be!=="notLoading"||(W?.items?.length??0)>0,[Pd,cs]=C.useState(!0),Md=!!ke&&(ke.items?.length??0)>0,Bd=()=>{qe(),cs(!1)},Fd=!Ve&&(Be!=="notLoading"||O)||Ve&&(Be!=="notLoading"||Ke),Hd={...Dd?{maxHeight:"100vh"}:{height:"250px"}};C.useEffect(()=>{if(Ve){P(!1);return}Bx(W.items)>=ni?.api?.settings?.maxUserMessagesPerDiscussion&&P(!0)},[ni?.api?.settings?.maxUserMessagesPerDiscussion,W.items,Ve]);const ds=C.useRef(Ne);C.useEffect(()=>{ds.current!==Ne&&(ds.current=Ne,He("notLoading"),P(!1))},[Ne]);const Ud=()=>{gr.abort("Cancelling stream on purpose."),r.log("Stream request aborted"),He("notLoading"),oe()},fs=async le=>{const Ce=le?.body?.getReader(),Me=new TextDecoder,Nn=le.headers.get("discussionId"),pt=parseInt(Nn,10);Number.isNaN(pt)||de(pt),await new ReadableStream({start(Nt){return Rn();async function Rn(){if(!le.ok){He("notLoading");let Bt=w;le.status===409?(Bt=v,P(!0)):le.status===429?Bt=S:Bt=w,V({userType:"assistant",content:Bt,metaData:{isErrorMessage:!0},temporaryId:crypto.randomUUID()}),gr=new AbortController;return}return Ce?.read().then(Bt=>{const{done:Gd,value:qd}=Bt,Vd=Me.decode(qd),Wd=Rt.transformNDJSONChunkIntoObjects(Vd);for(const ze of Wd)if(Rt.isObjectOutputstreamMessageStartDTO(ze))ii.handleStart(ze);else if(Rt.isObjectOutputstreamMessageDeltaDTO(ze))ii.handleDelta(ze);else if(Rt.isObjectOutputstreamMessageEndDTO(ze))ii.handleEnd(ze);else if(Rt.isObjectOutputstreamLoadingCurrentStepNumberDTO(ze)){const{content:Pe}=ze;Nt.enqueue(Pe),J(Pe)}else if(Rt.isObjectOutputstreamLoadingCurrentStepNameDTO(ze)){const{content:Pe}=ze;Nt.enqueue(Pe),Ie(Pe)}else if(Rt.isObjectOutputstreamLoadingNumberOfStepsDTO(ze)){const{content:Pe}=ze;Nt.enqueue(Pe),kt(Pe)}else if(Rt.isObjectOutputstreamClientEventDTO(ze)){const Pe=Vx(ze);if(Pe.type==="customer_support_handoff_requested")Mt(Pe.payload);else if(Pe.type==="identity_gate_required"){if(!c.current.has(Pe.payload.gateId)){c.current.add(Pe.payload.gateId);const ps=o.current;ps&&(Pe.payload.protocolVersion===2&&(Q_(e,Pe.payload.continuation,pt),d.current=Pe.payload.continuation.continuationId),V_({apiUrl:i,appToken:e,payload:Pe.payload,identitySession:ps}).then(()=>{Pe.payload.protocolVersion===2&&ru(e)}).catch(Xd=>r.error(Xd)).finally(()=>{Pe.payload.protocolVersion===2&&d.current===Pe.payload.continuation.continuationId&&(d.current=null)}))}}else r.warn(`Client event not handled - ${ze.event}`)}else if(Rt.isObjectOutputstreamErrorDTO(ze)){const{message:Pe}=ze;V({userType:"assistant",metaData:{isErrorMessage:!0},content:Pe,temporaryId:crypto.randomUUID()})}else r.warn(`Packet shape not handled - ${ze}`);if(Gd){Nt.close(),He("notLoading"),Ie(vt),J(null),ht();return}return Rn()})}}}).pipeTo(new WritableStream)};p.current=fs,C.useEffect(()=>{if(!a)return;const le=K_(e);if(!le){f.current=null;return}if(f.current===le.continuationId||d.current===le.continuationId)return;const Ce=o.current;Ce&&(f.current=le.continuationId,J_({apiUrl:i,appToken:e,discussionId:le.discussionId,continuation:le,identitySession:Ce}).then(async Me=>{if(!Me){f.current=null;return}Me.status===401&&Ce.clear(),Z_(Me.status)&&ru(e),He("loadingIntermediaryStates"),await p.current?.(Me)}).catch(Me=>{r.error(Me),He("notLoading")}))},[i,e,a,h,r]);const jd=(le,Ce)=>{const Me=i,Nn=t?`?agentId=${encodeURIComponent(String(t))}`:"",pt=`${Me}/ai/prompt/${e}${Nn}`,ai=gr.signal;if(le.mode==="text"){const Rn={query:le.text,language:ls.locale};W?.discussionId&&(Rn.discussionId=W.discussionId);const Bt=tn.getFetchConfig({httpVerb:"POST",body:Rn,contentType:"application/json",options:{signal:ai,headers:{...tn.getHeaders({contentType:"application/json"}),...a?{[ee.IDENTITY_GATE_VERSION_HEADER]:"2"}:{},...Ce?{Authorization:"Bearer "+Ce}:{}}}});return{url:pt,fetchConfig:Bt}}const Nt=new FormData;return Nt.append("language",ls.locale),W?.discussionId&&Nt.append("discussionId",String(W.discussionId)),Nt.append("audioInput",le.audioFile,le.audioFile.name),{url:pt,fetchConfig:{method:"POST",body:Nt,signal:ai,headers:a||Ce?{...a?{[ee.IDENTITY_GATE_VERSION_HEADER]:"2"}:{},...Ce?{Authorization:"Bearer "+Ce}:{}}:void 0}}},hs=async le=>{He("loadingIntermediaryStates"),Q({smooth:!1,sticky:!0});let Ce=null;try{Ce=await o.current?.getToken({interactive:!1})??null}catch{o.current?.clear()}const{url:Me,fetchConfig:Nn}=jd(le,Ce);fetch(Me,Nn).then(async pt=>{pt.status===401&&Ce&&o.current?.clear(),await fs(pt)}).catch(pt=>{r.error(pt),He("notLoading"),gr=new AbortController})},zd=async()=>{ti(!0),await vd()},$d=async()=>{const le=await kd();ti(!1),le&&hs({mode:"audio",audioFile:le.file})},Yd=()=>{Nd(),ti(!1)};return x.jsxs("div",{className:["chatbox-root relative p-2","flex flex-col min-h-0 overflow-visible","h-auto",n??"mx-auto"].join(" "),ref:s,style:Hd,children:[x.jsx("div",{className:"flex-1 overflow-y-auto min-h-0 messagesContainer",ref:Z,children:x.jsxs("div",{ref:at,children:[W.items.map((le,Ce)=>x.jsx(Cy,{content:le.content,userType:le.userType,metaData:le.metaData,context:{discussionId:W?.discussionId,messageIndex:Ce,appToken:e},seenRootEl:Z.current},le.temporaryId)),x.jsx(A_,{currentStepName:be,currentStepNumber:H,loadingStatus:Be,numberOfSteps:Dt})]})}),ue&&x.jsx(D_,{label:je,onClick:()=>Q({smooth:!0,sticky:!0})}),!Ve&&O&&x.jsx(L_,{onReset:ae}),wd&&os&&x.jsx(M_,{config:os,status:Ad,scheduleLabel:Cd?.todayScheduleLabel,labels:{title:Le,description:m,schedulePrefix:G,email:B,phone:$,reason:re,submit:K,submitting:he,success:T,error:Se},onSubmit:Id}),_d&&ss&&x.jsx(P_,{config:ss,status:xd,labels:{title:U,description:z,email:B,phone:$,submit:K,submitting:he,success:pe,error:Se},onSubmit:Sd}),Pt&&x.jsx(tu,{actionLabel:I,message:Pt,onClick:ae}),Md&&Pd&&x.jsx(tu,{actionLabel:L,message:k,onClick:Bd}),x.jsx("div",{className:"chatbox-input-wrapper flex-shrink-0",children:us?x.jsx(U_,{isOpen:us,onStop:$d,onCancel:Yd,audioLevel:Rd}):x.jsx(Rx,{classNameTextarea:"",classNameContainer:"relative mt-2 border-slate-400 border-[1px] rounded-lg p-1",SubmitComponent:Ox,isDisabled:Fd,shouldDisableIfInputIsEmpty:!0,"aria-label":"TextArea For Bot Conversation",onSubmit:le=>{if(cs(!1),Fx(le)){const Ce=Hx(le,W.discussionId,ae);Ce&&(_e({smooth:!0}),V({userType:"user",content:Ce,temporaryId:crypto.randomUUID()}))}else _e({smooth:!0}),V({userType:"user",content:le,temporaryId:crypto.randomUUID()}),et==="customer_support"?yd(le):hs({mode:"text",text:le})},placeholder:y,autoFocus:Od,isLoadingStream:Be==="loadingDisplayedAnswer"||Be==="loadingIntermediaryStates",LoadingComponent:w_,onPressLoadingButton:Ud,onPressMicButton:()=>{zd()},MicComponent:B_,audioEnabled:ni?.agent?.isAudioAllowed&&!Ve})})]})};function Pr(){return Pr=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},Pr.apply(this,arguments)}function dd(e,t){if(e==null)return{};var n={},r=Object.keys(e),i,a;for(a=0;a<r.length;a++)i=r[a],!(t.indexOf(i)>=0)&&(n[i]=e[i]);return n}function Ta(e,t){return Ta=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(r,i){return r.__proto__=i,r},Ta(e,t)}function fd(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,Ta(e,t)}var br={exports:{}};/*
|
|
147
|
+
${n??""}`,"data-testid":"mic-button",onClick:e,disabled:t,type:"button","aria-label":"Start voice input",children:x.jsx("span",{"data-state":"closed",children:x.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",width:"24",height:"24","aria-hidden":"true",className:"text-white dark:text-black",children:[x.jsx("path",{d:"M12 14.5c1.66 0 3-1.34 3-3V6.5c0-1.66-1.34-3-3-3s-3 1.34-3 3v5c0 1.66 1.34 3 3 3Z",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinejoin:"round"}),x.jsx("path",{d:"M12 14.5V18",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round"}),x.jsx("path",{d:"M8.5 18h7",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round"}),x.jsx("path",{d:"M7 11.5c0 2.76 2.24 5 5 5s5-2.24 5-5",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round"})]})})})});function F_(){const[e,t]=C.useState("idle"),[n,r]=C.useState(null),[i,a]=C.useState(0),s=C.useRef(null),o=C.useRef(null),u=C.useRef([]),c=C.useRef(null),d=C.useRef(null),f=C.useRef(null),p=C.useRef(null),h=C.useCallback(()=>{p.current!==null&&(cancelAnimationFrame(p.current),p.current=null);try{f.current?.disconnect()}catch{}f.current=null;try{d.current?.disconnect()}catch{}d.current=null;const v=c.current;c.current=null,v&&v.close().catch(()=>{}),a(0)},[]),b=C.useCallback(v=>{try{const k=new AudioContext,L=k.createAnalyser(),A=k.createMediaStreamSource(v);L.fftSize=256,L.smoothingTimeConstant=.85,A.connect(L),c.current=k,d.current=L,f.current=A;const N=new Uint8Array(L.fftSize),Y=()=>{const X=d.current;if(!X)return;X.getByteTimeDomainData(N);let ne=0;for(let z=0;z<N.length;z++){const B=(N[z]-128)/128;ne+=B*B}const I=Math.sqrt(ne/N.length),U=Math.min(1,I*6);a(U),p.current=requestAnimationFrame(Y)};p.current=requestAnimationFrame(Y)}catch{a(0)}},[]),y=C.useCallback(async()=>{r(null),h();try{const v=await navigator.mediaDevices.getUserMedia({audio:!0});o.current=v,b(v);const L=["audio/webm;codecs=opus","audio/webm","audio/ogg;codecs=opus","audio/ogg"].find(N=>MediaRecorder.isTypeSupported(N))||"",A=new MediaRecorder(v,L?{mimeType:L}:void 0);s.current=A,u.current=[],A.ondataavailable=N=>{N.data&&N.data.size>0&&u.current.push(N.data)},A.onerror=()=>{t("error"),r("Recorder error.")},A.onstart=()=>t("recording"),A.onstop=()=>t("stopped"),A.start()}catch(v){h(),t("error"),r(v?.message??"Microphone permission denied.")}},[b,h]),w=C.useCallback(async()=>{const v=s.current,k=o.current;return!v||e!=="recording"?null:new Promise(L=>{v.onstop=()=>{h();const A=v.mimeType||"audio/webm",N=new Blob(u.current,{type:A}),Y=A.includes("ogg")?"ogg":"webm",X=new File([N],`voice-message.${Y}`,{type:A});k?.getTracks().forEach(ne=>ne.stop()),o.current=null,s.current=null,L({blob:N,file:X})},v.stop()})},[e,h]),S=C.useCallback(()=>{const v=s.current,k=o.current;try{v&&e==="recording"&&v.stop()}catch{}h(),k?.getTracks().forEach(L=>L.stop()),o.current=null,s.current=null,u.current=[],t("idle")},[e,h]);return C.useEffect(()=>()=>{h(),o.current?.getTracks().forEach(v=>v.stop())},[h]),{state:e,error:n,audioLevel:i,start:y,stop:w,cancel:S}}const H_=()=>{const e=sn(),t=e.formatMessage({defaultMessage:"Recording...",id:"recordingOverlay.recording"}),n=e.formatMessage({defaultMessage:"Cancel",id:"recordingOverlay.cancel"}),r=e.formatMessage({defaultMessage:"Tap the mic to stop",id:"recordingOverlay.explaination"});return{recordingTranslation:t,cancelTranslation:n,recordingExplainationTranslation:r}},U_=({isOpen:e,onStop:t,onCancel:n,audioLevel:r=0})=>{const{recordingTranslation:i}=H_(),a=C.useMemo(()=>{const s=Math.max(0,Math.min(1,r));return Array.from({length:20},(o,u)=>{const c=Math.sin(u/19*Math.PI*2)*.5+.5,d=u%2===0?.9:.65,f=6+s*(14+c*18)*d;return Math.round(f)})},[r]);return e?x.jsx("div",{className:"relative mt-3 w-full rounded-lg border border-slate-400 bg-white p-1",role:"group","aria-label":"Recording voice message",children:x.jsxs("div",{className:"flex min-h-[48px] items-center gap-3 px-2",children:[x.jsxs("div",{className:"relative flex h-8 w-8 items-center justify-center",children:[x.jsx("span",{className:"absolute h-5 w-5 rounded-full bg-red-100 motion-safe:animate-ping","aria-hidden":!0}),x.jsx("span",{className:"absolute h-5 w-5 rounded-full bg-red-50","aria-hidden":!0}),x.jsx("span",{className:"absolute h-3.5 w-3.5 rounded-full bg-red-200","aria-hidden":!0}),x.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-red-500","aria-hidden":!0})]}),x.jsxs("div",{className:"min-w-0 flex-1",children:[x.jsx("div",{className:"mb-0.5 text-[11px] font-medium leading-3 text-slate-600",children:i}),x.jsx("div",{className:"flex h-5 items-center gap-[3px] overflow-hidden","aria-hidden":"true",children:a.map((s,o)=>x.jsx("span",{className:"block w-1 rounded-full bg-slate-400 transition-[height,background-color] duration-75",style:{height:`${s}px`,backgroundColor:r>.08?"rgb(59 130 246)":"rgb(148 163 184)"}},o))})]}),x.jsx("button",{type:"button",onClick:n,className:"flex h-9 w-9 items-center justify-center rounded-full text-slate-500 hover:bg-slate-100 hover:text-slate-700","aria-label":"Cancel recording",children:x.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",width:"18",height:"18","aria-hidden":"true",children:x.jsx("path",{d:"M6 6l12 12M18 6L6 18",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})})}),x.jsx("button",{type:"button",onClick:t,className:"flex h-9 w-9 items-center justify-center rounded-full bg-violet-600 text-white hover:bg-violet-700","aria-label":"Validate recording",children:x.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",width:"18",height:"18","aria-hidden":"true",children:x.jsx("path",{d:"M5 13l4 4L19 7",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round"})})})]})}):null},j_=e=>/(\[.*|!\[.*)$/.test(e),z_=e=>/\)/.test(e),nu=()=>({rendered:"",markdownTag:"",isWritingTag:!1,lastStreamSourceUuid:null});class $_{buffers=new Map;callbacks;constructor(t){this.callbacks=t}handleStart(t){this.buffers.set(t.messageId,nu()),t.role==="assistant"&&this.callbacks.onAssistantMessageStart?.(),this.callbacks.addEmptyMessage({messageStreamId:t.messageId,role:t.role})}handleDelta(t){this.ensureBufferExists(t.messageId);const n=this.buffers.get(t.messageId);this.appendSourceSeparatorIfNeeded(n,t.streamSourceUuid),this.appendDelta(n,t.delta),this.callbacks.updateMessage({id:t.messageId,newContent:n.rendered})}handleEnd(t){this.buffers.delete(t.messageId)}hasBuffer(t){return this.buffers.has(t)}ensureBufferExists(t){this.buffers.has(t)||(this.buffers.set(t,nu()),this.callbacks.addEmptyMessage({messageStreamId:t,role:"assistant"}))}appendSourceSeparatorIfNeeded(t,n){t.lastStreamSourceUuid&&t.lastStreamSourceUuid!==n&&(t.rendered+='<span style="display:block;height:1rem;"></span>'),t.lastStreamSourceUuid=n??null}appendDelta(t,n){if(z_(n)){t.markdownTag+=n,t.rendered+=t.markdownTag,t.markdownTag="",t.isWritingTag=!1;return}if(t.isWritingTag||j_(n)){t.markdownTag+=n,t.isWritingTag=!0;return}t.rendered+=n}}const Y_=30,G_=e=>{try{const t=e.split(".")[1];if(!t)return null;const n=t.replace(/-/g,"+").replace(/_/g,"/"),r=n.padEnd(n.length+(4-n.length%4)%4,"="),i=JSON.parse(atob(r));return typeof i.exp=="number"?i.exp:null}catch{return null}};class q_{token=null;expiresAt=null;pendingRequest=null;pendingRequestIsInteractive=!1;generation=0;provider;constructor(t){this.provider=t}clear(){this.generation+=1,this.token=null,this.expiresAt=null,this.pendingRequest=null,this.pendingRequestIsInteractive=!1}handleIdentityChanged(){this.token=null,this.expiresAt=null,!(this.pendingRequest&&this.pendingRequestIsInteractive)&&(this.generation+=1,this.pendingRequest=null,this.pendingRequestIsInteractive=!1)}async getToken(t){if(!this.provider)return null;const n=Math.floor(Date.now()/1e3);if(this.token&&this.expiresAt!=null&&this.expiresAt-Y_>n)return this.token;if(this.pendingRequest){const a=this.pendingRequestIsInteractive,s=await this.pendingRequest;if(s||!t.interactive||a)return s}const r=this.generation;this.pendingRequestIsInteractive=t.interactive;let i;return i=this.provider.getToken(t).then(a=>{if(r!==this.generation)return null;if(!a)return this.clear(),null;const s=G_(a);return s==null||s<=Math.floor(Date.now()/1e3)?(this.clear(),null):(this.token=a,this.expiresAt=s,a)}).finally(()=>{this.pendingRequest===i&&(this.pendingRequest=null,this.pendingRequestIsInteractive=!1)}),this.pendingRequest=i,i}}const ud=C.createContext(void 0),V_=async({apiUrl:e,appToken:t,payload:n,identitySession:r,fetchImplementation:i=fetch})=>{let a=null,s;try{a=await r.getToken({interactive:!0,reason:n.reason,requiredCapabilities:n.requiredCapabilities}),a||(a=await r.getToken({interactive:!1,reason:n.reason,requiredCapabilities:n.requiredCapabilities})),s=a?{status:"success"}:{status:"cancelled"}}catch{r.clear(),s={status:"failed",code:"HOST_IDENTITY_FAILED"}}const o=await i(`${e}/ai/identity-gates/${encodeURIComponent(t)}/${encodeURIComponent(n.gateId)}/result`,{method:"POST",headers:{"Content-Type":"application/json","X-ChatSystem-Identity-Gate-Token":n.resultToken,...a?{Authorization:`Bearer ${a}`}:{}},body:JSON.stringify(s)});if(!o.ok)throw o.status===401&&a&&r.clear(),new Error(`IDENTITY_GATE_RESOLUTION_FAILED:${o.status}`)},W_="chatsystem:pending-turn:",X_=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,rs=e=>`${W_}${encodeURIComponent(e)}`,ld=(e,t=Date.now())=>{if(!e||typeof e!="object"||Array.isArray(e))return null;const n=e;if(typeof n.continuationId!="string"||!X_.test(n.continuationId)||typeof n.expiresAt!="string"||typeof n.discussionId!="number"||!Number.isSafeInteger(n.discussionId)||n.discussionId<=0)return null;const r=Date.parse(n.expiresAt);return!Number.isFinite(r)||r<=t?null:{continuationId:n.continuationId,expiresAt:n.expiresAt,discussionId:n.discussionId}},Q_=(e,t,n,r=sessionStorage)=>{const i=ld({...t,discussionId:n});i&&r.setItem(rs(e),JSON.stringify(i))},K_=(e,t=sessionStorage,n=Date.now())=>{const r=rs(e),i=t.getItem(r);if(!i)return null;try{const a=ld(JSON.parse(i),n);if(a)return a}catch{}return t.removeItem(r),null},ru=(e,t=sessionStorage)=>{t.removeItem(rs(e))},J_=async({apiUrl:e,appToken:t,discussionId:n,continuation:r,identitySession:i,fetchImplementation:a=fetch})=>{if(!Number.isSafeInteger(n)||n<=0)return null;const s=await i.getToken({interactive:!1});if(!s)return null;const o={discussionId:n};return a(`${e}/ai/pending-turns/${encodeURIComponent(t)}/${encodeURIComponent(r.continuationId)}/resume`,{method:"POST",headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"},body:JSON.stringify(o)})},Z_=e=>e>=200&&e<300||e>=400&&e<500&&e!==429||e===503;let gr=new AbortController;const cd=({appToken:e,agentId:t,containerClassName:n})=>{const r=Sn(),i=Kr(),a=C.useContext(ud);e||r.error("App Token missing");const s=C.useRef(null),o=C.useRef(null),u=C.useRef(a),c=C.useRef(new Set),d=C.useRef(null),f=C.useRef(null),p=C.useRef(null),[h,b]=C.useState(0);(!o.current||u.current!==a)&&(u.current=a,o.current=new q_(a)),C.useEffect(()=>{const le=o.current;if(!(!le||!a))return le.getToken({interactive:!1}).catch(()=>le.clear()),a.subscribe?.(()=>{le.handleIdentityChanged(),b(Ce=>Ce+1),le.getToken({interactive:!1}).catch(()=>le.clear())})},[a]);const{placeholderTranslation:y,genericErrorTranslation:w,tooManyRequestsTranslation:S,discussionFullErrorTranslation:v,infoBannerExplainationTranslation:k,infoBannerTitleTranslation:L,customerSupportConnectingTranslation:A,customerSupportConnectedTranslation:N,customerSupportConnectionErrorTranslation:Y,customerSupportProviderUnavailableTranslation:X,customerSupportClosedTranslation:ne,customerSupportRestartTranslation:I,customerSupportFallbackTitleTranslation:U,customerSupportFallbackDescriptionTranslation:z,customerSupportFallbackEmailTranslation:B,customerSupportFallbackPhoneTranslation:$,customerSupportFallbackSubmitTranslation:K,customerSupportFallbackSubmittingTranslation:he,customerSupportFallbackSuccessTranslation:pe,customerSupportFallbackErrorTranslation:Se,customerSupportClosedHoursTitleTranslation:Le,customerSupportClosedHoursDescriptionTranslation:m,customerSupportClosedHoursSchedulePrefixTranslation:G,customerSupportClosedHoursReasonTranslation:re,customerSupportClosedHoursSuccessTranslation:T}=Ju(),{currentConversation:W,addEmptyMessageToCurrentConversation:ce,addMessageToCurrentConversation:V,removeEmptyAssistantMessageFromCurrentConversation:oe,resetConversation:ae,setCurrentConversationId:de,updateCurrentConversationMessageById:ie,archivedConversation:ke,chatboxBootState:q,resetConversationRequestId:Ne,setArchivedConversationAsMain:qe}=ns(),[Be,He]=C.useState("notLoading"),{defaultStartingStep:vt,recentMessagesTranslation:je}=sd(),[Dt,kt]=C.useState(null),[be,Ie]=C.useState(vt),[H,J]=C.useState(null),[O,P]=C.useState(!1),{scrollToBottom:Q,showScrollButton:ue,messagesContainerRef:Z,requestScrollToBottomAfterNextRender:_e,messagesContentRef:at}=N_(W.items),{chatTransportMode:et,isCustomerSupportMode:Ve,customerSupportStatusMessage:Pt,isCustomerSupportInputDisabled:Ke,enterCustomerSupportMode:Mt,flushPendingCustomerSupportHandoff:ht,sendToCustomerSupport:yd,fallbackContactCaptureConfig:ss,fallbackContactCaptureStatus:xd,shouldDisplayFallbackContactCapture:_d,submitFallbackContactCapture:Sd,closedHoursContactCaptureConfig:os,closedHoursBusinessHours:Cd,closedHoursContactCaptureStatus:Ad,shouldDisplayClosedHoursContactCapture:wd,submitClosedHoursContactCapture:Id}=S_({appToken:e,currentConversation:W,loadingStatus:Be,labels:{connecting:A,connected:N,connectionError:Y,providerUnavailable:X,closed:ne},logger:r,setCurrentConversationId:de,setLoadingStatus:He,addMessageToCurrentConversation:V,chatboxBootState:q,resetConversationRequestId:Ne}),[us,ti]=C.useState(!1),{start:vd,stop:kd,cancel:Nd,audioLevel:Rd}=F_(),{companySettings:ni}=C.useContext(rn),{appCurrentLang:ls}=C.useContext(td),[Od,Ld]=C.useState(()=>{if(typeof window>"u")return!0;const le=window.matchMedia("(pointer: coarse)"),Ce=window.matchMedia("(hover: none)");return!(le.matches||Ce.matches)}),ri=C.useRef(null);ri.current||(ri.current=new $_({addEmptyMessage:ce,updateMessage:ie,onAssistantMessageStart:()=>He("loadingDisplayedAnswer")}));const ii=ri.current;C.useEffect(()=>{if(typeof window>"u")return;const le=window.matchMedia("(pointer: coarse)"),Ce=window.matchMedia("(hover: none)"),Me=()=>{Ld(!(le.matches||Ce.matches))};return Me(),le.addEventListener?(le.addEventListener("change",Me),Ce.addEventListener("change",Me)):(le.addListener(Me),Ce.addListener(Me)),()=>{le.removeEventListener?(le.removeEventListener("change",Me),Ce.removeEventListener("change",Me)):(le.removeListener(Me),Ce.removeListener(Me))}},[]);const Dd=Be!=="notLoading"||(W?.items?.length??0)>0,[Pd,cs]=C.useState(!0),Md=!!ke&&(ke.items?.length??0)>0,Bd=()=>{qe(),cs(!1)},Fd=!Ve&&(Be!=="notLoading"||O)||Ve&&(Be!=="notLoading"||Ke),Hd={...Dd?{maxHeight:"100vh"}:{height:"250px"}};C.useEffect(()=>{if(Ve){P(!1);return}Bx(W.items)>=ni?.api?.settings?.maxUserMessagesPerDiscussion&&P(!0)},[ni?.api?.settings?.maxUserMessagesPerDiscussion,W.items,Ve]);const ds=C.useRef(Ne);C.useEffect(()=>{ds.current!==Ne&&(ds.current=Ne,He("notLoading"),P(!1))},[Ne]);const Ud=()=>{gr.abort("Cancelling stream on purpose."),r.log("Stream request aborted"),He("notLoading"),oe()},fs=async le=>{const Ce=le?.body?.getReader(),Me=new TextDecoder,Nn=le.headers.get("discussionId"),pt=parseInt(Nn,10);Number.isNaN(pt)||de(pt),await new ReadableStream({start(Nt){return Rn();async function Rn(){if(!le.ok){He("notLoading");let Bt=w;le.status===409?(Bt=v,P(!0)):le.status===429?Bt=S:Bt=w,V({userType:"assistant",content:Bt,metaData:{isErrorMessage:!0},temporaryId:crypto.randomUUID()}),gr=new AbortController;return}return Ce?.read().then(Bt=>{const{done:Gd,value:qd}=Bt,Vd=Me.decode(qd),Wd=Rt.transformNDJSONChunkIntoObjects(Vd);for(const ze of Wd)if(Rt.isObjectOutputstreamMessageStartDTO(ze))ii.handleStart(ze);else if(Rt.isObjectOutputstreamMessageDeltaDTO(ze))ii.handleDelta(ze);else if(Rt.isObjectOutputstreamMessageEndDTO(ze))ii.handleEnd(ze);else if(Rt.isObjectOutputstreamLoadingCurrentStepNumberDTO(ze)){const{content:Pe}=ze;Nt.enqueue(Pe),J(Pe)}else if(Rt.isObjectOutputstreamLoadingCurrentStepNameDTO(ze)){const{content:Pe}=ze;Nt.enqueue(Pe),Ie(Pe)}else if(Rt.isObjectOutputstreamLoadingNumberOfStepsDTO(ze)){const{content:Pe}=ze;Nt.enqueue(Pe),kt(Pe)}else if(Rt.isObjectOutputstreamClientEventDTO(ze)){const Pe=Vx(ze);if(Pe.type==="customer_support_handoff_requested")Mt(Pe.payload);else if(Pe.type==="identity_gate_required"){if(!c.current.has(Pe.payload.gateId)){c.current.add(Pe.payload.gateId);const ps=o.current;ps&&(Pe.payload.protocolVersion===2&&(Q_(e,Pe.payload.continuation,pt),d.current=Pe.payload.continuation.continuationId),V_({apiUrl:i,appToken:e,payload:Pe.payload,identitySession:ps}).then(()=>{Pe.payload.protocolVersion===2&&ru(e)}).catch(Xd=>r.error(Xd)).finally(()=>{Pe.payload.protocolVersion===2&&d.current===Pe.payload.continuation.continuationId&&(d.current=null)}))}}else r.warn(`Client event not handled - ${ze.event}`)}else if(Rt.isObjectOutputstreamErrorDTO(ze)){const{message:Pe}=ze;V({userType:"assistant",metaData:{isErrorMessage:!0},content:Pe,temporaryId:crypto.randomUUID()})}else r.warn(`Packet shape not handled - ${ze}`);if(Gd){Nt.close(),He("notLoading"),Ie(vt),J(null),ht();return}return Rn()})}}}).pipeTo(new WritableStream)};p.current=fs,C.useEffect(()=>{if(!a)return;const le=K_(e);if(!le){f.current=null;return}if(f.current===le.continuationId||d.current===le.continuationId)return;const Ce=o.current;Ce&&(f.current=le.continuationId,J_({apiUrl:i,appToken:e,discussionId:le.discussionId,continuation:le,identitySession:Ce}).then(async Me=>{if(!Me){f.current=null;return}Me.status===401&&Ce.clear(),Z_(Me.status)&&ru(e),He("loadingIntermediaryStates"),await p.current?.(Me)}).catch(Me=>{r.error(Me),He("notLoading")}))},[i,e,a,h,r]);const jd=(le,Ce)=>{const Me=i,Nn=t?`?agentId=${encodeURIComponent(String(t))}`:"",pt=`${Me}/ai/prompt/${e}${Nn}`,ai=gr.signal;if(le.mode==="text"){const Rn={query:le.text,language:ls.locale};W?.discussionId&&(Rn.discussionId=W.discussionId);const Bt=tn.getFetchConfig({httpVerb:"POST",body:Rn,contentType:"application/json",options:{signal:ai,headers:{...tn.getHeaders({contentType:"application/json"}),...a?{[ee.IDENTITY_GATE_VERSION_HEADER]:"2"}:{},...Ce?{Authorization:"Bearer "+Ce}:{}}}});return{url:pt,fetchConfig:Bt}}const Nt=new FormData;return Nt.append("language",ls.locale),W?.discussionId&&Nt.append("discussionId",String(W.discussionId)),Nt.append("audioInput",le.audioFile,le.audioFile.name),{url:pt,fetchConfig:{method:"POST",body:Nt,signal:ai,headers:a||Ce?{...a?{[ee.IDENTITY_GATE_VERSION_HEADER]:"2"}:{},...Ce?{Authorization:"Bearer "+Ce}:{}}:void 0}}},hs=async le=>{He("loadingIntermediaryStates"),Q({smooth:!1,sticky:!0});let Ce=null;try{Ce=await o.current?.getToken({interactive:!1})??null}catch{o.current?.clear()}const{url:Me,fetchConfig:Nn}=jd(le,Ce);fetch(Me,Nn).then(async pt=>{pt.status===401&&Ce&&o.current?.clear(),await fs(pt)}).catch(pt=>{r.error(pt),He("notLoading"),gr=new AbortController})},zd=async()=>{ti(!0),await vd()},$d=async()=>{const le=await kd();ti(!1),le&&hs({mode:"audio",audioFile:le.file})},Yd=()=>{Nd(),ti(!1)};return x.jsxs("div",{className:["chatbox-root relative p-2","flex flex-col min-h-0 overflow-visible","h-auto",n??"mx-auto"].join(" "),ref:s,style:Hd,children:[x.jsx("div",{className:"flex-1 overflow-y-auto min-h-0 messagesContainer",ref:Z,children:x.jsxs("div",{ref:at,children:[W.items.map((le,Ce)=>x.jsx(Cy,{content:le.content,userType:le.userType,metaData:le.metaData,context:{discussionId:W?.discussionId,messageIndex:Ce,appToken:e},seenRootEl:Z.current},le.temporaryId)),x.jsx(A_,{currentStepName:be,currentStepNumber:H,loadingStatus:Be,numberOfSteps:Dt})]})}),ue&&x.jsx(D_,{label:je,onClick:()=>Q({smooth:!0,sticky:!0})}),!Ve&&O&&x.jsx(L_,{onReset:ae}),wd&&os&&x.jsx(M_,{config:os,status:Ad,scheduleLabel:Cd?.todayScheduleLabel,labels:{title:Le,description:m,schedulePrefix:G,email:B,phone:$,reason:re,submit:K,submitting:he,success:T,error:Se},onSubmit:Id}),_d&&ss&&x.jsx(P_,{config:ss,status:xd,labels:{title:U,description:z,email:B,phone:$,submit:K,submitting:he,success:pe,error:Se},onSubmit:Sd}),Pt&&x.jsx(tu,{actionLabel:I,message:Pt,onClick:ae}),Md&&Pd&&x.jsx(tu,{actionLabel:L,message:k,onClick:Bd}),x.jsx("div",{className:"chatbox-input-wrapper flex-shrink-0",children:us?x.jsx(U_,{isOpen:us,onStop:$d,onCancel:Yd,audioLevel:Rd}):x.jsx(Rx,{classNameTextarea:"",classNameContainer:"relative mt-2 border-slate-400 border-[1px] rounded-lg p-1",SubmitComponent:Ox,isDisabled:Fd,shouldDisableIfInputIsEmpty:!0,"aria-label":"TextArea For Bot Conversation",onSubmit:le=>{if(cs(!1),Fx(le)){const Ce=Hx(le,W.discussionId,ae);Ce&&(_e({smooth:!0}),V({userType:"user",content:Ce,temporaryId:crypto.randomUUID()}))}else _e({smooth:!0}),V({userType:"user",content:le,temporaryId:crypto.randomUUID()}),et==="customer_support"?yd(le):hs({mode:"text",text:le})},placeholder:y,autoFocus:Od,isLoadingStream:Be==="loadingDisplayedAnswer"||Be==="loadingIntermediaryStates",LoadingComponent:w_,onPressLoadingButton:Ud,onPressMicButton:()=>{zd()},MicComponent:B_,audioEnabled:ni?.agent?.isAudioAllowed&&!Ve})})]})};function Pr(){return Pr=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},Pr.apply(this,arguments)}function dd(e,t){if(e==null)return{};var n={},r=Object.keys(e),i,a;for(a=0;a<r.length;a++)i=r[a],!(t.indexOf(i)>=0)&&(n[i]=e[i]);return n}function Ta(e,t){return Ta=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(r,i){return r.__proto__=i,r},Ta(e,t)}function fd(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,Ta(e,t)}var br={exports:{}};/*
|
|
148
148
|
object-assign
|
|
149
149
|
(c) Sindre Sorhus
|
|
150
150
|
@license MIT
|