@deepdesk/deepdesk-sdk 19.3.2-beta.6 → 19.4.1

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.
@@ -80,7 +80,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
80
80
  c6.8-6.8,15.4-10.2,24.7-10.2h11.9v-70c0-44.4,16.2-82.8,47.8-115.2S212.1,0,256.4,0s82.8,16.2,115.2,47.8
81
81
  c32.4,32.4,47.8,70,47.8,115.2v70h11.9c9.4,0,17.9,3.4,24.7,10.2C462.1,250,465.5,257.7,465.5,267.9z`})})});var mS=b(I()),z5={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},cI=({className:e,color:t})=>(0,mS.jsx)("svg",{className:e,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:(0,mS.jsx)("path",{d:"M172.03 0.0199966H0V86.03C47.5 86.03 86 124.54 86 172.04C86 124.54 124.51 86.03 172.01 86.03C219.51 86.03 258.03 124.54 258.03 172.04C258.03 219.54 219.52 258.05 172.01 258.05C124.5 258.05 86 219.54 86 172.04C86 219.54 47.5 258.05 0 258.05V344.06H172.03C267.04 344.06 344.06 267.04 344.06 172.03C344.06 77.02 267.04 0 172.03 0V0.0199966Z",fill:z5[t||"pink"]})});var uI={root:"dd-LbeUM",text:"dd-Dpfn1",isLoggedIn:"dd-XvHAn",isLoggedOut:"dd-21y-z",icon:"dd-8rLqS",logo:"dd-slXhD",lock:"dd-ByzlR"};var gS={};ht(gS,{enUS:()=>H5,nlNL:()=>B5});var H5={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Search"}]},B5={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Zoeken"}]};var bs=b(I()),fI=({onLogIn:e})=>{let t=se(gS),n=X("floatingMenu"),r=X("productName"),o=Ee(),i=G(Pt),s=z("FloatingMenu",uI);if(i===null||n===!1)return null;let a=()=>{i===!0?o(ir(!0)):e()};return(0,bs.jsxs)("button",{type:"button",className:(0,dI.default)(s.root,{[s.isLoggedIn]:i,[s.isLoggedOut]:!i}),onClick:a,children:[(0,bs.jsx)("div",{className:s.text,children:t(i?"search":"signin",{productName:r})}),(0,bs.jsxs)("div",{className:s.icon,children:[(0,bs.jsx)(cI,{className:s.logo,color:"pink"}),i===!1&&(0,bs.jsx)(lI,{className:s.lock})]})]})};var Cm=b(Z());function jr(e){let{showMidSentenceSuggestions:t,showSuggestionsBeforePattern:n,showSuggestionsAfterPattern:r}=e.settings,{text:o,selection:i}=e.input;return i.end<e.input.suggestionTextStart||i.start!==i.end?!1:i.end>=o.length?!0:t?n&&new RegExp(n).test(o.substring(i.end))||r&&new RegExp(r).test(o.substring(0,i.end))?!0:n===!1&&r===!1:!1}var U5={showTabHint:!1,inputHasFocus:!1,overlayCollapsed:!1,openOverlayWhenTyping:!1,overlayCollapsedUserOverwrite:!1},ym=({ui:e})=>e.overlayCollapsed,pI=Re({name:"ui",initialState:U5,reducers:{setShowTabHint(e,t){e.showTabHint=t.payload},setInputFocus(e,t){e.overlayCollapsedUserOverwrite!==!0&&(t.payload===!0&&(e.overlayCollapsed=!1),e.inputHasFocus=t.payload)},setOverlayCollapsed(e,t){t.payload.collapse===!1&&(e.openOverlayWhenTyping=!1),!(t.payload.skipWhenInputFocus&&e.inputHasFocus)&&(e.overlayCollapsed=t.payload.collapse)},setOpenOverlayWhenTyping(e,t){e.openOverlayWhenTyping=t.payload},setOverlayCollapsedUserOverwrite(e,t){e.overlayCollapsedUserOverwrite=t.payload,e.overlayCollapsed=t.payload}}}),{setShowTabHint:lu,setInputFocus:vm,setOverlayCollapsed:Si,setOpenOverlayWhenTyping:mI,setOverlayCollapsedUserOverwrite:gI}=pI.actions,hI=pI.reducer;var yI={styleRow:"dd-prYfH",styleSuggestion:"dd-JTmXy"};var cu=b(I()),V5=({match:e,selected:t,styles:n})=>(0,cu.jsx)(pe,{as:"button",selected:t,className:n.styleRow,"data-testid":"style-suggestion-item",title:e.suggestion,children:(0,cu.jsx)("span",{className:n.styleSuggestion,children:e.suggestion})}),W5=({matches:e,selectedIndex:t})=>{let n=z("StyleSuggestionList",yI);return(0,cu.jsx)(Tt,{children:e.map((r,o)=>(0,cu.jsx)(V5,{match:r,selected:t===o,styles:n},`${r.keyword}-${o}`))})},Sm=W5;var EI=b(Z());var xi=b(Z());var vI=b(Z());function SI(e,t,n){(0,vI.useEffect)(()=>{let r=e.current;return r?(r.addEventListener(t,n),()=>{r.removeEventListener(t,n)}):()=>{}},[e,t,n])}var xI={root:"dd-1MBCO",actions:"dd--x4cy",closeIconContainer:"dd-1z5NR",closeIcon:"dd-8qMF-",badge:"dd-4Fpkz",formattedText:"dd-EzvTB",assistantContainer:"dd-j6o8F",formattedTextTruncated:"dd-fv169",assistantBadge:"dd-VD57E"};var uu=b(I()),wI=({title:e})=>(0,uu.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"18px",height:"18px",viewBox:"0 0 24 24","aria-labelledby":"closeTitle",children:[(0,uu.jsx)("title",{id:"closeTitle",children:e}),(0,uu.jsx)("path",{d:"M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"})]});var hS={};ht(hS,{enUS:()=>$5,nlNL:()=>j5});var $5={assistant:[{type:0,value:"Assistant"}],close:[{type:0,value:"Close"}]},j5={assistant:[{type:0,value:"Assistent"}],close:[{type:0,value:"Sluiten"}]};var zn=b(I()),G5=["search","personal-collection-search","search-autocomplete"];function q5(e,t,n,r={}){var i;let o="";return G5.includes(t)?o=MP(sS(e,n,{stripAgentPart:!0}),(i=r.searchKeywords)!=null?i:[n]):o=sS(e,n,r),r.placeholders===!0&&(o=NP(o)),o}var Y5=()=>{},X5=({selected:e,suggestion:t})=>{let n=se(hS),r=X("inlineSuggestions"),o=G(Ni),[i,s]=(0,xi.useState)(!1),a=X("enableSuggestionFeedback"),l=G(v=>v.input.text),c=Ee(),u=z("TextSuggestion",xI),f=(0,xi.useRef)(null),d=t.source==="assistant",p=a&&!d;(0,xi.useEffect)(()=>{let v=setTimeout(()=>{c(Eb({text:t.text,suggestion:t}))},500);return()=>{clearTimeout(v)}},[t]),SI(f,"click",()=>{c(kn({suggestion:t,text:t.text,eventMetrics:{inputType:"mouse"},replace:"until-selection-end"}))});let m=()=>{c(Li({source:t.source,text:t.text,assistantCode:t.assistantCode}))},g=(0,xi.useMemo)(()=>q5(t.text,t.source,o,{stripAgentPart:r,placeholders:!0,searchKeywords:t.searchKeywords}),[r,t.text,t.source,o,t.searchKeywords]);return t.source==="gpt"&&!r?null:(0,zn.jsxs)("div",{className:u.root,onMouseEnter:()=>s(!0),onMouseLeave:()=>s(!1),children:[(0,zn.jsx)(pe,{ref:f,as:"button","data-testid":"suggestions-overlay-item",selected:e,onClick:Y5,children:t.source==="assistant"?(0,zn.jsxs)("div",{className:u.assistantContainer,children:[(0,zn.jsx)(yi,{containerTagName:"div",tagName:"span",className:u.formattedTextTruncated,content:g}),(0,zn.jsx)("span",{className:u.assistantBadge,children:n("assistant")})]}):(0,zn.jsx)(yi,{containerTagName:"div",tagName:"span",className:u.formattedText,content:g})}),p&&i&&(0,zn.jsx)("div",{className:u.actions,children:(0,zn.jsx)(pm,{source:"overlay",context:l,suggestion:t})}),d&&i&&(0,zn.jsx)("div",{className:u.closeIconContainer,children:(0,zn.jsx)("button",{type:"button",className:u.closeIcon,onClick:m,title:n("close"),children:(0,zn.jsx)(wI,{title:n("close")})})})]})},bI=X5;var CI=b(I()),Q5=({suggestions:e,selectedIndex:t,reverse:n})=>(0,EI.useMemo)(()=>{let o=e.map((i,s)=>(0,CI.jsx)(bI,{index:s,selected:s===t,suggestion:i},`${i.text}-${i.source}`));return n?o.reverse():o},[e,t,n]),xm=Q5;var TI={root:"dd-PfvRI",paper:"dd-HYlyY"};var wm={list:{keywordMatches:[]},fetchState:"idle"},bm=e=>e.styleSuggestions.list,Es=ge("styleSuggestions/getAll",(n,r)=>M(null,[n,r],function*({text:e},t){var l;let{deepdeskAPI:o}=t.extra,i=t.getState(),{showStyleSuggestions:s}=i.settings,a=(l=i.conversation.current)==null?void 0:l.profileCode;if(!s)return wm.list;if(!a)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:a,message:e})})),kI=Re({name:"styleSuggestions",initialState:wm,reducers:{commitStyleSuggestion(e,t){let{keyword:n,suggestion:r}=t.payload;e.list.keywordMatches=e.list.keywordMatches.filter(o=>o.keyword.toLowerCase()!==n.toLowerCase()||o.suggestion!==r)}},extraReducers:e=>{e.addCase(Es.pending,t=>{t.fetchState="loading"}).addCase(Es.rejected,t=>{t.fetchState="error"}).addCase(Es.fulfilled,(t,n)=>{t.fetchState="done",zo(t.list,n.payload)||(t.list=n.payload)}).addCase(Di,t=>{t.list=wm.list}).addCase(lt,()=>wm)}}),{commitStyleSuggestion:RI}=kI.actions,PI=kI.reducer;var Em=e=>{let t=new Set;return e.filter(({keyword:n,suggestion:r})=>{let o=JSON.stringify([n.toLowerCase(),r]);return t.has(o)?!1:(t.add(o),!0)})};var Cs=b(I()),Z5=()=>{var v;let e=(0,Cm.useRef)(null),t=z("InlineSuggestionsOverlay",TI),n=G(jr),r=Ee(),o=G(Pt),i=G($s),s=G(ym),a=X("showTextSuggestions"),l=G(Oi),c=G(xl),u=X("showStyleSuggestions"),f=X("showStyleSuggestionList"),d=G(bm),p=u&&f?Em((v=d.keywordMatches)!=null?v:[]):[],m=p.length>0,g=a&&l.length>0;return di(()=>{setTimeout(()=>{r(Si({collapse:!0,skipWhenInputFocus:!0}))})}),(0,Cm.useEffect)(()=>{let h=e.current;if(!h||!h.parentElement)return;h.parentElement.style.left="0px";let y=h.getBoundingClientRect();h.parentElement.style.left=`${Math.min(window.innerWidth-4-y.right,0)}px`}),s||o!==!0||i===!1||!n&&!m||!g&&!m?null:(0,Cs.jsx)("div",{className:t.root,"data-variant":"inline",children:(0,Cs.jsxs)("div",{ref:e,className:t.paper,children:[m&&(0,Cs.jsx)(Sm,{matches:p,selectedIndex:-1}),g&&(0,Cs.jsx)(Tt,{children:(0,Cs.jsx)(xm,{suggestions:l,selectedIndex:c})})]})})},II=Z5;var wi=b(Z());var AI={root:"dd-7zvcP",dialogContent:"dd-4C0lK",continueButton:"dd-YUPQW",buttonContinueWrapper:"dd-IKpYs",nicknameInput:"dd-rxhGp",titleWrapper:"dd-nw3nD",title:"dd-5iof5",closeButtonWrapper:"dd-UUAzA",closeButton:"dd-7rjP5",buttonsWrapper:"dd-5e9Xb",errorMessage:"dd--5VgX",errorLink:"dd-u461n"};var yS={};ht(yS,{enUS:()=>J5,nlNL:()=>e6});var J5={title:[{type:0,value:"Enter your nickname"}],close:[{type:0,value:"Close"}],nicknameDialogTitle:[{type:0,value:"Please enter the name you'd like customers to see during chat conversations. This nickname will be used across your Deepdesk environment."}],nicknameDialogInputPlaceholder:[{type:0,value:"Enter your nickname"}],nicknameDialogContinueButton:[{type:0,value:"Continue"}],nicknameDialogError:[{type:0,value:"Nickname cannot be empty or spaces only"}],nicknameDialogEmojiError:[{type:0,value:"You cannot use emojis in this field."}],nicknameDialogSaveError:[{type:0,value:"We couldn't save your details just now. Please try again, or update it at "},{type:1,value:"account"},{type:0,value:".deepdesk.com/admin/user-settings"}],nicknameDialogSaveErrorWithoutLink:[{type:0,value:"We couldn\u2019t save your details just now. Please try again later, or update them in My Deepdesk \u2192 Settings."}]},e6={title:[{type:0,value:"Voer je bijnaam in"}],close:[{type:0,value:"Sluiten"}],nicknameDialogTitle:[{type:0,value:"Voer de naam in die je wilt dat klanten zien tijdens chatgesprekken. Deze bijnaam wordt gebruikt in je Deepdesk-omgeving."}],nicknameDialogInputPlaceholder:[{type:0,value:"Voer je bijnaam in"}],nicknameDialogContinueButton:[{type:0,value:"Doorgaan"}],nicknameDialogError:[{type:0,value:"Bijnaam mag niet leeg of alleen spaties zijn"}],nicknameDialogEmojiError:[{type:0,value:"Je kunt geen emoji's gebruiken in dit veld."}],nicknameDialogSaveError:[{type:0,value:"We konden je gegevens nu niet opslaan. Probeer het opnieuw of werk het bij op "},{type:1,value:"account"},{type:0,value:".deepdesk.com/admin/user-settings"}],nicknameDialogSaveErrorWithoutLink:[{type:0,value:"We konden je gegevens nu niet opslaan. Probeer het opnieuw later, of werk ze bij in My Deepdesk \u2192 Instellingen."}]};var ft=b(I()),_I=({onClose:e,onSave:t,id:n,error:r})=>{let[o,i]=(0,wi.useState)(""),[s,a]=(0,wi.useState)(!1),[l,c]=(0,wi.useState)(!1),u=z("Nickname",AI),f=wi.default.useRef(null),d=G(h=>h.info.showNicknameDialog),p=se(yS),m=X("adminUrl");(0,wi.useEffect)(()=>{r&&a(!0)},[r]);let g=()=>{if(!f.current)return;o.trim()?f.current.setCustomValidity(""):f.current.setCustomValidity(p("nicknameDialogError")),f.current.reportValidity()},v=h=>{h.preventDefault();let y=o.trim(),S=h.currentTarget.querySelector("#nickname-input");if(!y){S.setCustomValidity(p("nicknameDialogError")),S.reportValidity();return}S.setCustomValidity(""),t(y)};return(0,ft.jsxs)($a,{isOpen:d,"datatest-id":n,onClose:e||(()=>{}),onBack:e||(()=>{}),children:[(0,ft.jsx)("div",{className:u.titleWrapper,children:(0,ft.jsx)("h1",{className:u.title,children:p("title")})}),(0,ft.jsxs)("form",{className:u.dialogContent,onSubmit:v,children:[(0,ft.jsx)("p",{children:p("nicknameDialogTitle")}),s&&r&&(0,ft.jsx)("div",{className:u.errorMessage,children:m?(()=>{let h=p("nicknameDialogSaveError",{account:m}),y=`${m}.deepdesk.com/admin/user-settings`,S=h.indexOf(y);if(S!==-1){let x=h.substring(0,S),T=h.substring(S+y.length);return(0,ft.jsxs)(ft.Fragment,{children:[x,(0,ft.jsx)("a",{href:y,target:"_blank",rel:"noopener noreferrer",className:u.errorLink,children:y}),T]})}return h})():p("nicknameDialogSaveErrorWithoutLink")}),(0,ft.jsx)("input",{required:!0,minLength:1,maxLength:20,"data-testid":"nickname-input",id:"nickname-input",className:u.nicknameInput,type:"text",placeholder:p("nicknameDialogInputPlaceholder"),value:o,onChange:h=>{c(new RegExp("\\p{Extended_Pictographic}","u").test(h.target.value)),i(h.target.value)},onBlur:g,ref:f}),l&&(0,ft.jsx)("div",{className:u.errorMessage,role:"alert",children:p("nicknameDialogEmojiError")}),(0,ft.jsxs)("div",{className:u.buttonsWrapper,children:[r?(0,ft.jsx)("div",{className:u.closeButtonWrapper,children:(0,ft.jsx)("button",{type:"button",className:u.closeButton,onClick:()=>e==null?void 0:e(),children:p("close")})}):null,(0,ft.jsx)("div",{className:u.buttonContinueWrapper,children:(0,ft.jsx)("button",{type:"submit",className:u.continueButton,disabled:!o.trim()||new RegExp("\\p{Extended_Pictographic}","u").test(o),children:p("nicknameDialogContinueButton")})})]})]})]})};var du=b(I()),t6=({children:e})=>{let n=X("locale").replace("-","");return(0,du.jsx)(xh.Provider,{value:n,children:e})},n6=({store:e,customStyles:t={},children:n})=>(0,du.jsx)(vw,{store:e,children:(0,du.jsx)(t6,{children:(0,du.jsx)(cl.Provider,{value:t,children:n})})}),ko=n6;var km=b(De()),Ya=b(Z());var MI=b(Z());function NI(e,t){let[n,r]=(0,MI.useState)(()=>{if(typeof window=="undefined")return t;try{let i=window.localStorage.getItem(e);return i?JSON.parse(i):t}catch(i){return te.error(i),t}});return[n,i=>{try{let s=i instanceof Function?i(n):i;r(s),typeof window!="undefined"&&window.localStorage.setItem(e,JSON.stringify(s))}catch(s){te.error(s)}}]}var OI=()=>/Mac/i.test(navigator.platform);var DI=b(De()),Ro=b(Z());var vS={};ht(vS,{enUS:()=>r6,nlNL:()=>o6});var r6={loginPlease:[{type:8,value:"login",children:[{type:0,value:"Sign in"}]},{type:0,value:" to enable "},{type:1,value:"productName"},{type:0,value:"."}],snooze:[{type:0,value:"Snooze for "},{type:8,value:"min",children:[{type:0,value:"10 minutes"}]},{type:0,value:", "},{type:8,value:"hour",children:[{type:0,value:"1 hour"}]},{type:0,value:" or "},{type:8,value:"day",children:[{type:0,value:"1 day"}]}]},o6={loginPlease:[{type:8,value:"login",children:[{type:0,value:"Log in"}]},{type:0,value:" bij "},{type:1,value:"productName"},{type:0,value:"."}],snooze:[{type:0,value:"Snooze voor "},{type:8,value:"min",children:[{type:0,value:"10 minuten"}]},{type:0,value:", "},{type:8,value:"hour",children:[{type:0,value:"1 uur"}]},{type:0,value:" of "},{type:8,value:"day",children:[{type:0,value:"1 dag"}]}]};var LI={root:"dd-uTPjX",anchor:"dd-C8lsZ",anchorButton:"dd-IoSx9"};var bi=b(I()),SS=(e,t,n)=>r=>(0,bi.jsx)("button",{className:e.anchorButton,type:"button",value:t,onClick:n,children:r},t),i6=({className:e,loginUrl:t,isEmbedded:n,onSnooze:r,onLogIn:o})=>{let i=se(vS),s=pn(),a=z("Login",LI),l=X("productName"),c=(0,Ro.useCallback)(v=>{v.preventDefault(),r&&r(Number.parseInt(v.target.value,10))},[]),u=(0,Ro.useCallback)(v=>{v.preventDefault(),s.send(Ys,!0)},[t]),f=(0,Ro.useMemo)(()=>v=>(0,bi.jsx)("a",{onClick:y=>{y.preventDefault(),o()},href:t,className:a.anchor,target:"_blank",rel:"noreferrer",children:v},"login"),[t]),d=(0,Ro.useCallback)(v=>(0,bi.jsx)("button",{type:"button",className:a.anchorButton,onClick:u,children:v},"prompt"),[u]),{min:p,hour:m,day:g}=(0,Ro.useMemo)(()=>({min:SS(a,600,c),hour:SS(a,3600,c),day:SS(a,3600*12,c)}),[]);return(0,bi.jsxs)("div",{className:(0,DI.default)(e,a.root),children:[i("loginPlease",{login:n?d:f,productName:l}),r&&(0,bi.jsxs)(Ro.Fragment,{children:[(0,bi.jsx)("br",{}),i("snooze",{min:p,hour:m,day:g})]})]})},Tm=i6;var FI={root:"dd-DoQhb",text:"dd-Jwnev"};var fu=b(I()),s6=({title:e})=>{let t=z("SearchTrigger",FI),n=Ee(),r=Ze();return(0,fu.jsxs)("button",{type:"button",className:t.root,onClick:()=>{n(ir(!0)),r("open search",{via:"autocomplete-overlay"})},children:[(0,fu.jsx)(Ga,{}),(0,fu.jsx)("span",{className:t.text,children:e})]})},zI=s6;var xS={};ht(xS,{enUS:()=>a6,nlNL:()=>l6});var a6={arrowHint:[{type:0,value:"Tip: use arrow keys to navigate suggestions"}],searchHintWindows:[{type:0,value:"Press CTRL+"},{type:1,value:"searchTriggerKey"},{type:0,value:" to search"}],searchHintMac:[{type:0,value:"Press CMD+"},{type:1,value:"searchTriggerKey"},{type:0,value:" to search"}],open:[{type:0,value:"Open "},{type:1,value:"productName"}],collapse:[{type:0,value:"Close"}],search:[{type:0,value:"Search"}],dismiss:[{type:0,value:"Dismiss"}],dismissError:[{type:0,value:"Dismiss error"}]},l6={arrowHint:[{type:0,value:"Tip: Selecteer suggesties met pijltoetsen"}],searchHintWindows:[{type:0,value:"Druk CTRL+"},{type:1,value:"searchTriggerKey"},{type:0,value:" om te zoeken"}],searchHintMac:[{type:0,value:"Druk CMD+"},{type:1,value:"searchTriggerKey"},{type:0,value:" om te zoeken"}],open:[{type:0,value:"Open "},{type:1,value:"productName"}],collapse:[{type:0,value:"Sluiten"}],search:[{type:0,value:"Zoeken"}],dismiss:[{type:0,value:"Sluiten"}],dismissError:[{type:0,value:"Foutmelding sluiten"}]};var HI={root:"dd-oa7Vc",isInline:"dd-bwk31",toggleButton:"dd-MSB8Z",toggleButtonWrapper:"dd-ZkCzT",toggleButtonWrapperHidden:"dd-Sq66c",isCollapsed:"dd-vkrPk",collapsible:"dd-CWQJe",hints:"dd-IOoo3",hintsHidden:"dd-psVuT",triggers:"dd-toIoo",triggersRight:"dd-mc4l2",loginError:"dd-KCXeb",loginErrorMessage:"dd-Bv-BG",loginErrorDismiss:"dd-iSCjU"};var Me=b(I()),c6=({onLogIn:e})=>{var W;let t=z("SuggestionsOverlay",HI),n=se(xS),r=G(jr),o=G(bb),i=Ee(),s=(0,Ya.useRef)(null),a=X("searchTriggerKey"),l=X("productName"),c=G(ym),u=G(Pt),f=G(ub),d=G($s),[p,m]=(0,Ya.useState)(null),g=X("showSearch"),v=X("showTextSuggestions"),h=X("adminUrl"),y=X("isEmbedded"),S=X("suggestionsPlacement"),[x,T]=NI("dd-snooze-until-ms",0),C=c||x>Date.now(),k=G(Oi),R=G(xl),F=X("showStyleSuggestions"),O=X("showStyleSuggestionList"),U=G(bm),J=F&&O?Em((W=U.keywordMatches)!=null?W:[]):[],Y=J.length>0,_=k.filter(N=>N.source!=="gpt").length,V=()=>{C&&T(0),i(gI(!C))},B=N=>{let q=Date.now()+N*1e3;T(q),te.info(`Snooze until: ${new Date(q)}`),i(Si({collapse:!0}))};return(0,Ya.useEffect)(()=>{_===0&&m(null)},[k,_]),di(()=>{i(Si({collapse:!0,skipWhenInputFocus:!0}))}),u===null||d===!1?null:u===!1?(0,Me.jsxs)("div",{ref:s,className:(0,km.default)(t.root,{[t.isCollapsed]:C}),children:[!C&&(0,Me.jsxs)("div",{className:t.triggers,children:[(0,Me.jsx)("div",{style:{flex:1}}),(0,Me.jsx)("div",{className:t.triggersRight,children:(0,Me.jsx)(Ii,{className:t.toggleButton,title:n("collapse"),onClick:V,isCollapsed:!1})})]}),(0,Me.jsx)("div",{className:t.toggleButtonWrapper,children:(0,Me.jsx)(Ii,{className:t.toggleButton,title:n("open",{productName:l}),onClick:V,isCollapsed:!0})}),(0,Me.jsxs)("div",{className:t.collapsible,children:[f&&(0,Me.jsxs)("div",{className:t.loginError,children:[(0,Me.jsx)("span",{className:t.loginErrorMessage,children:f}),(0,Me.jsx)("button",{type:"button",className:t.loginErrorDismiss,onClick:()=>i(hd()),"aria-label":n("dismissError"),children:n("dismiss")})]}),(0,Me.jsx)(Tm,{loginUrl:h,isEmbedded:y,onLogIn:e,onSnooze:B})]})]}):!o||!r&&!Y?null:(0,Me.jsxs)("div",{ref:s,className:(0,km.default)(t.root,{[t.isCollapsed]:C}),children:[!C&&(0,Me.jsxs)("div",{className:t.triggers,children:[(0,Me.jsx)("div",{style:{flex:1},children:g&&(0,Me.jsx)("div",{style:{display:"inline-block"},onFocus:()=>{},onMouseOver:()=>m(n(OI()?"searchHintMac":"searchHintWindows",{searchTriggerKey:a.toUpperCase()})),onMouseLeave:()=>m(null),children:(0,Me.jsx)(zI,{title:n("search")})})}),(0,Me.jsxs)("div",{className:t.triggersRight,onFocus:()=>{},children:[(0,Me.jsx)("div",{className:(0,km.default)(!p&&t.hintsHidden,t.hints),children:p}),(0,Me.jsx)(Ii,{className:t.toggleButton,title:n("collapse"),onClick:V,isCollapsed:!1})]})]}),(0,Me.jsx)("div",{className:t.toggleButtonWrapper,children:(0,Me.jsx)(Ii,{className:t.toggleButton,title:n("open",{productName:l}),onClick:V,isCollapsed:!0})}),(Y||_>0&&v)&&(0,Me.jsxs)("div",{className:t.collapsible,onFocus:()=>{},children:[Y&&(0,Me.jsx)(Sm,{matches:J,selectedIndex:-1}),_>0&&v&&(0,Me.jsx)(Tt,{children:(0,Me.jsx)(xm,{suggestions:k,selectedIndex:R,reverse:S==="above"})})]})]})},BI=c6;var Hm=b(De());var Ao=b(Z());var Xa=b(Z());function Rm(e){return e.contentEditable==="true"}function u6(e){let t=0,n=0,r=window.getSelection();if(r.rangeCount!==0){let o=r.getRangeAt(0),i=o.cloneRange();i.selectNodeContents(e),i.setEnd(o.endContainer,o.endOffset),n=i.toString().length,i.selectNodeContents(e),i.setEnd(o.startContainer,o.startOffset),t=i.toString().length}return{selectionStart:t,selectionEnd:n}}function UI(e){let{selectionStart:t,selectionEnd:n}=Rm(e)?u6(e):e;return[t,n]}function VI(e){let[,t]=(0,Xa.useState)(),n=(0,Xa.useRef)(null);return n.current=UI(e),(0,Xa.useEffect)(()=>{let r=()=>{var a;let[o,i]=(a=n.current)!=null?a:[],s=UI(e);(!s||o!==s[0]||i!==s[1])&&(n.current=s,t({}))};return e.addEventListener("keyup",r),e.addEventListener("click",r),e.addEventListener("focus",r),document.addEventListener("selectionchange",r),()=>{e.removeEventListener("keyup",r),e.removeEventListener("click",r),e.removeEventListener("focus",r),document.removeEventListener("selectionchange",r)}},[e]),n.current}function WI(e,t){if(!t)return;let n=e,{value:r}=n,[o,i]=t,s=r.match($u);if(!s||s.length===0)return;let a=0;s.find(l=>{let c=r.indexOf(l,a);return o>c&&i<c+l.length?(n.selectionStart=c,n.selectionEnd=c+l.length,!0):(a=c+l.length,!1)})}var $I=b(Z()),d6=["div","span","mark","strong","b","i","u","em"];function wS(e,t,n=0){var i;let r=e[e.length-1],o=typeof r=="object"&&r!==null?(i=r.props)==null?void 0:i.tagName:void 0;if(o==="br")return e.pop(),[...e,...t,r];if(d6.includes(o)){let s=Array.isArray(r.props.children)?r.props.children:[r.props.children];return[...e.slice(0,e.length-1),(0,$I.cloneElement)(r,{children:wS(s,t,n+1)})]}return[...e,...t]}function Ts(e){return e.tagName.toLowerCase()==="textarea"}var jI={root:"dd-7-cgW",container:"dd-PsRQ8",agentText:"dd-qnW-V",tabText:"dd-cUHUr",hint:"dd-v7fSg",matchSelection:"dd-8cr8y",focus:"dd-3tr9l",resetIndent:"dd-TvQfZ",matchKeyword:"dd-oJkRD",matchPlaceholder:"dd-QvNoo",hover:"dd--wi0R",hintText:"dd-7gQQh",popover:"dd-xbRu-",popoverRoot:"dd-rA2x8",popoverContentContainer:"dd-JHICl",popoverContent:"dd--mfkC",selectionOptions:"dd-p52wn",selectionOptionsIsHidden:"dd-sSTDp",selectionOptionsButton:"dd-Q6kRY",caret:"dd-jIhc8",popoverSuggestionsRoot:"dd-iFDbL",suggestionsOverlayInputStyles:"dd-zzENA"};var YI=b(De());var Om=b(Z());var Qa=b(Z());function KI(e,t){let n;return[(...r)=>{window.cancelAnimationFrame(n);let o=t?t(...r):r;n=window.requestAnimationFrame(()=>{e(...o)})},()=>window.cancelAnimationFrame(n)]}function Pm(e){let t=(0,Qa.useRef)(null),[n,r]=(0,Qa.useState)(!1);return(0,Qa.useEffect)(()=>{var u;let o=!1,i=Number.parseFloat((u=window.getComputedStyle(document.body).zoom)!=null?u:"1"),[s,a]=KI((f,d)=>{let p=t.current;if(!p)return;let m=f/i,g=d/i,v=p.getBoundingClientRect(),h=m>v.x&&m<v.x+v.width&&g>v.y&&g<v.y+v.height;h&&!o?(o=!0,r(!0)):!h&&o&&(o=!1,r(!1))},({clientX:f,clientY:d})=>[f,d]),[l,c]=KI(()=>{o=!1,r(!1)});return e.addEventListener("mousemove",s),e.addEventListener("mouseleave",l),()=>{a(),c(),e.removeEventListener("mousemove",s),e.removeEventListener("mouseleave",l)}},[t]),[t,n]}function Im(e){return e.replace(/[.*+^${}()|[\]\\]/g,"\\$&")}function Am(e){return t=>{e.forEach(n=>{typeof n=="function"?n(t):n!=null&&(n.current=t)})}}function GI(e){return e!=null}var qI=b(De()),_m=b(Z());var Po={root:"dd-7-cgW",container:"dd-PsRQ8",agentText:"dd-qnW-V",tabText:"dd-cUHUr",hint:"dd-v7fSg",matchSelection:"dd-8cr8y",focus:"dd-3tr9l",resetIndent:"dd-TvQfZ",matchKeyword:"dd-oJkRD",matchPlaceholder:"dd-QvNoo",hover:"dd--wi0R",hintText:"dd-7gQQh",popover:"dd-xbRu-",popoverRoot:"dd-rA2x8",popoverContentContainer:"dd-JHICl",popoverContent:"dd--mfkC",selectionOptions:"dd-p52wn",selectionOptionsIsHidden:"dd-sSTDp",selectionOptionsButton:"dd-Q6kRY",caret:"dd-jIhc8",popoverSuggestionsRoot:"dd-iFDbL",suggestionsOverlayInputStyles:"dd-zzENA"};var bS=b(I()),Mm=(0,_m.forwardRef)((o,r)=>{var i=o,{className:e,children:t}=i,n=ie(i,["className","children"]);let s=(0,_m.useRef)(null),a=z("TabCompletion",Po);return(0,bS.jsx)("div",A(E({ref:Am([s,r]),className:(0,qI.default)(e,a.popoverContentContainer)},n),{children:(0,bS.jsx)("div",{className:a.popoverContent,children:t})}))});var Ei=b(I()),f6=e=>t=>{let n=a0(t);return"top"in n&&(n.width=e.width-(t.left-e.left)-10),n},p6=({inputElement:e,boundaryRef:t,inputStyle:n,children:r,suggestion:o})=>{let i=z("TabCompletion",Po),s=wp(),a=(0,Om.useMemo)(()=>f6(e.getBoundingClientRect()),[e]),[l,c]=Pm(e);return(0,Om.useEffect)(()=>{c?s.open():s.close()},[c]),(0,Ei.jsxs)("span",{children:[(0,Ei.jsx)("mark",{ref:Am([l,s.triggerRef]),className:(0,YI.default)(i.matchKeyword,{[i.hover]:c}),"aria-haspopup":"dialog","aria-expanded":s.opened?"true":"false",children:r}),s.opened&&(0,Ei.jsx)(Aa,{className:i.popover,triggerRef:s.triggerRef,boundaryRef:t,position:"below",align:"start",toStyle:a,children:(0,Ei.jsx)(Mm,{style:n,children:(0,Ei.jsx)("div",{className:i.hintText,children:o})})})]})},Nm=class extends Eo{constructor(){super(...arguments);this.keywordMatches=[];this.preparedKeywordMatches=[];this.usedKeywordMatches=new Set}onBeforeParse(n,r){return r.keywordMatches&&r.keywordMatches!==this.keywordMatches&&(this.preparedKeywordMatches=r.keywordMatches.map(o=>A(E({},o),{keywordRegex:new RegExp(`\\b${Im(o.keyword)}\\b`,"i")})),this.keywordMatches=r.keywordMatches),this.usedKeywordMatches.clear(),n}match(n){let r=this.preparedKeywordMatches.map(i=>{if(this.usedKeywordMatches.has(i))return null;let s=n.match(i.keywordRegex);if(!s)return null;let a=n.charAt(s.index-1),l=n.charAt(s.index+i.keyword.length);return a==="{"&&l==="}"?null:{index:s.index,length:s[0].length,match:s[0],matchString:s[0],suggestion:i.suggestion,preparedKeywordMatch:i,valid:!0}}).filter(GI);if(r.length===0)return null;let o=r.reduce((i,s)=>s.index<i.index?s:i);return this.usedKeywordMatches.add(o.preparedKeywordMatch),o}replaceWith(n,r){return(0,Ei.jsx)(p6,{inputElement:r.inputElement,suggestion:r.suggestion,inputStyle:r.inputStyle,boundaryRef:r.boundaryRef,children:n},`keyword_${r.matchString}_${r.key}`)}asTag(){return"mark"}};var XI=b(De());var ES=b(I()),m6=({inputElement:e,children:t})=>{let n=z("TabCompletion",Po),[r,o]=Pm(e);return(0,ES.jsx)("mark",{ref:r,className:(0,XI.default)(n.matchPlaceholder,{[n.hover]:o}),children:t})},Lm=class extends Eo{match(t){let n=t.match(/(((\$!\{)|(\{))[a-zA-Z0-9_.]+\}(?!\}))/);return n?{index:n.index,length:n[0].length,match:n[0],matchString:n[0],valid:!0}:null}replaceWith(t,n){return(0,ES.jsx)(m6,{inputElement:n.inputElement,children:t},`placeholder_${n.matchString}_${n.key}`)}asTag(){return"mark"}};var Fm=b(De());var an=b(Z());var CS=b(I()),QI=()=>(0,CS.jsx)("svg",{width:"1.3em",height:"1.3em",focusable:"false","aria-hidden":"true",viewBox:"0 0 24 24","data-testid":"InsertLinkIcon",tabIndex:-1,children:(0,CS.jsx)("path",{fill:"currentColor",d:"M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76 0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71 0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71 0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76 0 5-2.24 5-5s-2.24-5-5-5z"})});var Kr=b(Z());var JI=b(X0());var ZI={root:"dd-ky-Bv",content:"dd-kV5e1"};function Dm(e,t,n){var o;let r=((o=e.imageSizes)==null?void 0:o[t])||e.image||n;if(!r)return null;try{return new URL(r).toString()}catch(i){return null}}function TS(e){return e.replace("https://www.","").replace("https://","")}var Qn=b(I()),g6=3,h6=e=>({image:e.image||"",text:e.text,id:e.id,title:e.title}),y6=({onSelectLink:e,onDismiss:t,placeholder:n,visitUrlText:r,linkCount:o=g6})=>{let i=z("LinkSearch",ZI),[s,a]=(0,Kr.useState)(""),l=Ee(),c=G(ZP("url")),u=G(Kb("URL")),f=(0,Kr.useMemo)(()=>u.map(h6),[u]),[d,p]=(0,Kr.useState)(f.length-1),m=X("fallbackImage"),g=S=>{let x=S.target;a(x.value)},v=(S,x)=>{S.stopPropagation(),S.preventDefault(),window.open(x,"_blank")},h=S=>{var C;let x=d-1<0?f.length-1:d-1,T=d+1===f.length?0:d+1;S.code==="Escape"&&(a(""),t()),S.code==="ArrowUp"&&p(x),S.code==="ArrowDown"&&p(T),S.code==="Enter"&&e(((C=f[d])==null?void 0:C.text)||s)},y=(0,Kr.useCallback)((0,JI.default)(S=>{l(Fi({query:S,type:"URL",tags:["link-search"]}))},300),[]);return(0,Kr.useEffect)(()=>{s&&y(s)},[s]),(0,Kr.useEffect)(()=>()=>{l(kd())},[]),(0,Qn.jsxs)("div",{className:i.root,children:[(0,Qn.jsx)(Tt,{withDivider:!0,children:(s?f:c).slice(0,o).map((S,x)=>(0,Qn.jsx)(pe,{selected:d===x,onClick:()=>e(S.text),"data-testid":"linksearch-suggestion",children:(0,Qn.jsxs)(we,{children:[(0,Qn.jsx)(we.Image,{src:Dm(S,"small",m||void 0),title:S.title||S.text}),(0,Qn.jsxs)(we.Content,{className:i.content,cropText:!0,children:[(0,Qn.jsx)(we.Title,{children:S.title||TS(S.text)}),S.title&&TS(S.text)]}),(0,Qn.jsx)(pe.Actions,{children:(0,Qn.jsx)(pe.ActionButton,{label:r,onClick:T=>v(T,S.text)})})]})},S.text))}),(0,Qn.jsx)($c,{value:s,onChange:g,autoFocus:!0,placeholder:n,onKeyUp:h})]})},eA=y6;var kS={};ht(kS,{enUS:()=>v6,nlNL:()=>S6});var v6={insertLink:[{type:0,value:"Insert link"}],linkInputPlaceholder:[{type:0,value:"Search, type or paste link"}],visitUrl:[{type:0,value:"Visit"}],addToPersonalCollection:[{type:0,value:"Add to Personal Collection"}]},S6={insertLink:[{type:0,value:"Voeg link toe"}],linkInputPlaceholder:[{type:0,value:"Zoek, typ of plak link"}],visitUrl:[{type:0,value:"Bekijk"}],addToPersonalCollection:[{type:0,value:"Toevoegen aan Personal Collection"}]};var Ot=b(I()),x6=(0,an.forwardRef)((e,t)=>{let n=z("TabCompletion",Po);return(0,Ot.jsx)("mark",{ref:t,className:(0,Fm.default)(n.matchSelection)},"selection-start")}),w6=({startRef:e,boundaryRef:t,inputStyle:n,inputElement:r,children:o})=>{let i=se(kS),s=z("TabCompletion",Po),a=X("addToPersonalCollection"),l=G(Uo("/admin/personal-collection/new")),c=(0,an.useRef)(null),u=(0,an.useRef)(null),[f,d]=(0,an.useState)(null),p=Ee(),m=wp(document.activeElement===r),[g]=(0,an.useState)(()=>document.createRange());m.triggerRef.current=g,(0,an.useEffect)(()=>()=>g.detach(),[]),(0,an.useEffect)(()=>{let h=e.current,y=c.current;!h||!y||(g.setStart(h,0),g.setEnd(y,0))},[e.current,c.current]),di(()=>{m.close()});let v=(0,an.useCallback)(h=>{let y=g.toString(),S=/^http(s?):\/\//.test(h)?h:`https://${h}`,x=`[${y}](${S})`;p(kn({text:x,suggestion:{text:x,source:"search-url",type:"url"},eventMetrics:{inputType:"mouse"},replace:"selection"}))},[]);return(0,Ot.jsxs)("span",{children:[(0,Ot.jsx)("mark",{ref:c,className:(0,Fm.default)(s.matchSelection),"aria-haspopup":"dialog","aria-expanded":m.opened?"true":"false",children:o}),m.opened&&(0,Ot.jsx)(Aa,{className:s.popoverRoot,triggerRef:m.triggerRef,boundaryRef:t,position:"above",align:"start",children:(0,Ot.jsxs)(Mm,{style:n,ref:u,children:[(0,Ot.jsxs)("div",{className:(0,Fm.default)(s.selectionOptions,{[s.selectionOptionsIsHidden]:f!==null}),children:[(0,Ot.jsxs)("button",{type:"button",tabIndex:f===null?-1:void 0,className:s.selectionOptionsButton,onClick:()=>d("insertLink"),children:[(0,Ot.jsx)(QI,{}),(0,Ot.jsx)("span",{children:"\xA0"}),(0,Ot.jsx)("span",{children:i("insertLink")})]}),a&&l&&(0,Ot.jsx)("button",{type:"button",tabIndex:f===null?-1:void 0,className:s.selectionOptionsButton,onClick:()=>{let h=g.toString(),y=`${l}?text=${encodeURIComponent(h)}`;window.open(y,"_blank")},children:(0,Ot.jsx)("span",{children:i("addToPersonalCollection")})})]}),f==="insertLink"&&(0,Ot.jsx)(eA,{placeholder:i("linkInputPlaceholder"),visitUrlText:i("visitUrl"),onSelectLink:v,onDismiss:()=>{d(null),m.close()}})]})})]},"selection-end")},zm=class extends Eo{constructor(){super(...arguments);this.charCount=0;this.foundIndex=0;this.startRef=null}onBeforeParse(n,r){return this.props=r,this.charCount=0,this.startRef=(0,an.createRef)(),this.foundIndex=0,n}match(n){if(!this.props||this.props.selection===null||this.foundIndex===2)return null;let[r,o]=this.props.selection;if(r===o)return null;let i=this.foundIndex===0?r:o,s=i>=this.charCount&&i<=this.charCount+n.length?{index:i-this.charCount,length:0,match:"",valid:!0}:null;s&&this.foundIndex++;let a=this.foundIndex===1;return s&&a?this.charCount+=i-this.charCount:this.charCount+=n.length,s?E({isStart:a},s):null}replaceWith(n,r){return r.isStart?(0,Ot.jsx)(x6,{ref:this.startRef}):(0,Ot.jsx)(w6,{inputElement:r.inputElement,startRef:this.startRef,boundaryRef:r.boundaryRef,inputStyle:r.inputStyle})}asTag(){return"mark"}};var Io=b(I()),b6=({enabled:e,content:t,tabText:n,showTabHint:r,showTabCompletion:o,showStyleSuggestions:i,keywordMatches:s,inputElement:a,source:l})=>{let c=z("TabCompletion",jI),u=X("insertLink"),f=X("addToPersonalCollection"),d=X("showMidSentenceSuggestions"),p=X("inlineSuggestions"),m=VI(a),g=(0,Ao.useRef)(null),v=G(Pt);(0,Ao.useEffect)(()=>{Ts(a)&&m&&WI(a,m)},[m]);let h=(0,Ao.useCallback)(x=>{if(!o||!n)return x;let T=[(0,Io.jsx)("span",{className:c.resetIndent,children:"\u200B"},"u200B"),(0,Io.jsx)("span",{"data-testid":"tab-completion",className:(0,Hm.default)(c.tabText,c.resetIndent),"data-source":l,children:n},"tabText")];return r&&T.push((0,Io.jsx)("span",{className:(0,Hm.default)(c.hint,c.resetIndent),children:(0,Io.jsx)(Uu,{keyCode:"tab"},"tabHint")},"tabHint")),wS(x,T)},[o,n,r]),y=(0,Ao.useMemo)(()=>{let x=[];return(u||f)&&x.push(new zm("selection")),x.push(new Lm("placeholders")),i&&x.push(new Nm("keywords")),x},[p,u,f,i]),S=(0,Ao.useMemo)(()=>{let x=window.getComputedStyle(a);return{"--dd-color":x.color,"--dd-font-size":x.fontSize,"--dd-font-family":x.fontFamily,"--dd-font-variant":x.fontVariant}},[]);return!e||!v?null:(0,Io.jsxs)("div",{ref:x=>{x!=null&&x.parentElement&&(g.current=x==null?void 0:x.parentElement)},className:c.root,style:S,children:[(0,Io.jsx)(yi,{tagName:"span",containerTagName:"div",className:(0,Hm.default)(c.container,c.agentText),disableLineBreaks:Ts(a),content:t||"\u200B",onAfterParse:h,matchers:y,selection:m,keywordMatches:s,inputElement:a,inputStyle:S,boundaryRef:g,inlineSuggestionsOnlyAtEnd:!d}),(0,Io.jsx)("br",{})]},"tab-completion")},E6=e=>{var h,y,S;let{input:t,ui:n,settings:r,styleSuggestions:o,conversation:i}=e,s=js({input:t}),a=(s==null?void 0:s.text)||"",l=(s==null?void 0:s.source)||"",c=(h=t.html)!=null?h:ja(t.text),u=t.text.slice(t.suggestionTextStart,t.selection.end),f=a.indexOf(u)===0?a.slice(u.length):"",{showTabHint:d}=n,{isSupported:p}=i,{showTabCompletion:m,visible:g,showStyleSuggestions:v}=r;return{showTabHint:d,showStyleSuggestions:v,showTabCompletion:m&&jr(e),content:c,tabText:f,source:l,keywordMatches:(S=(y=o.list)==null?void 0:y.keywordMatches)!=null?S:[],enabled:g&&p!==!1}},tA=yw(E6)(b6);var Ci=b(Z());var C6={token:null,interval:null},RS=ge("passwordlessToken/getTemporaryPasswordlessToken",(e,t)=>M(null,null,function*(){let{deepdeskAPI:n}=t.extra;return{token:yield n.requestPasswordlessToken()}})),PS=ge("passwordlessToken/pollPasswordlessToken",(e={},t)=>{let{interval:n=1e3*60*10}=e,{dispatch:r}=t;return r(RS()),setInterval(()=>r(RS()),n)}),nA=Re({name:"passwordlessToken",initialState:C6,reducers:{stopPollPasswordlessToken(e){e.interval&&clearInterval(e.interval),e.interval=null}},extraReducers:e=>{e.addCase(RS.fulfilled,(t,n)=>{t.token=n.payload.token}),e.addCase(PS.fulfilled,(t,n)=>{t.interval=n.payload})}}),{stopPollPasswordlessToken:rA}=nA.actions,oA=nA.reducer;function T6(e){return"buttonText"in e&&"eventName"in e}function iA(e){if(e)return T6(e)?{label:e.buttonText,event:e.eventName,value:e.payload}:e}function k6(e){return e==null?void 0:e.map(t=>iA(t))}function R6(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return t}var sA=fn([bE,yd],(e,t)=>(t?e.filter(o=>!o.externalConversationId||o.externalConversationId===t):e).map(o=>{let i=iA(o.callToAction),s=k6(o.callToActions);return A(E(E(E({text:o.response,title:o.name},i?{callToAction:i}:{}),s!=null&&s.length?{callToActions:s}:{}),o.message!==void 0?{message:o.message}:{}),{editable:o.editable,isLoading:o.isLoading,evaluationId:o.evaluationId,rule:{id:R6(o.code),label:o.code,name:o.name,description:o.name}})}));var Bm=b(Z()),AS=b(De());var IS=b(I()),Za=()=>(0,IS.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 512 512",xmlns:"http://www.w3.org/2000/svg",children:(0,IS.jsx)("path",{d:"M502.6 70.63l-61.25-61.25C435.4 3.371 427.2 0 418.7 0H255.1c-35.35 0-64 28.66-64 64l.0195 256C192 355.4 220.7 384 256 384h192c35.2 0 64-28.8 64-64V93.25C512 84.77 508.6 76.63 502.6 70.63zM464 320c0 8.836-7.164 16-16 16H255.1c-8.838 0-16-7.164-16-16L239.1 64.13c0-8.836 7.164-16 16-16h128L384 96c0 17.67 14.33 32 32 32h47.1V320zM272 448c0 8.836-7.164 16-16 16H63.1c-8.838 0-16-7.164-16-16L47.98 192.1c0-8.836 7.164-16 16-16H160V128H63.99c-35.35 0-64 28.65-64 64l.0098 256C.002 483.3 28.66 512 64 512h192c35.2 0 64-28.8 64-64v-32h-47.1L272 448z"})});var aA={root:"dd-WcEru",entity:"dd-LfP8y",entityText:"dd-L-v0f",iconWrapper:"dd-9Deh1",icon:"dd-tM7E2",iconClicked:"dd-EEdDL"};var Gr=b(I()),P6=({entities:e})=>{let t=z("EntitiesWidgetList",aA),[n,r]=(0,Bm.useState)(void 0),o=Ze(),i=()=>{r(void 0)},s=a=>{e&&(r(e.indexOf(a)),Ar(a.text),o("entity copied",{entity:a,type:"copy"}))};return(0,Bm.useEffect)(()=>{let a=setTimeout(i,500);return()=>{clearTimeout(a)}},[n]),!e||e.length===0?null:(0,Gr.jsx)("div",{className:t.root,"data-testid":"widget-entities-list",children:e.map((a,l)=>(0,Gr.jsxs)("button",{title:a.text,className:t.entity,type:"button",onClick:()=>s(a),children:[(0,Gr.jsx)("span",{className:t.entityText,children:a.text}),(0,Gr.jsxs)("span",{className:t.iconWrapper,children:[(0,Gr.jsx)("span",{className:(0,AS.default)(t.icon),children:(0,Gr.jsx)(Za,{})}),(0,Gr.jsx)("span",{className:(0,AS.default)(t.icon,n===l&&t.iconClicked),children:(0,Gr.jsx)(Za,{})})]})]},a.text))})},lA=P6;var _S=b(I()),cA=()=>(0,_S.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:(0,_S.jsx)("path",{d:"M17 13.5v6H5v-12h6m3-3h6v6m0-6-9 9",stroke:"currentColor",strokeWidth:"1.5",fill:"none",fillRule:"evenodd",strokeLinecap:"round",strokeLinejoin:"round"})});var hA=b(Z());var uA={root:"dd-ohnXe",trigger:"dd-7i-S3",button:"dd-t53Cg",nav:"dd-qZFnm",item:"dd-FZC0F"};var dA={root:"dd-nazq3",rotation:"dd-3EHTv"};var pA=b(I()),I6=({size:e=12})=>{let t=z("LoadingSpinner",dA);return(0,pA.jsx)("span",{"data-testid":"loading-spinner",style:{width:`${e}px`,height:`${e}px`},className:t.root})},fA=I6;var MS=b(I()),mA=()=>(0,MS.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 0 512 512",fill:"currentColor",children:(0,MS.jsx)("path",{d:"M256 32c14.2 0 27.3 7.5 34.5 19.8l216 368c7.3 12.4 7.3 27.7 .2 40.1S486.3 480 472 480H40c-14.3 0-27.6-7.7-34.7-20.1s-7-27.8 .2-40.1l216-368C228.7 39.5 241.8 32 256 32zm0 128c-13.3 0-24 10.7-24 24V296c0 13.3 10.7 24 24 24s24-10.7 24-24V184c0-13.3-10.7-24-24-24zm32 224c0-17.7-14.3-32-32-32s-32 14.3-32 32s14.3 32 32 32s32-14.3 32-32z"})});var pu=b(I()),gA=e=>(0,pu.jsxs)("svg",A(E({xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 448 512","aria-labelledby":"checkTitle"},e),{children:[(0,pu.jsx)("title",{id:"checkTitle",children:"Check"}),(0,pu.jsx)("path",{fill:"#666",d:"M438.6 105.4c12.5 12.5 12.5 32.8 0 45.3l-256 256c-12.5 12.5-32.8 12.5-45.3 0l-128-128c-12.5-12.5-12.5-32.8 0-45.3s32.8-12.5 45.3 0L160 338.7 393.4 105.4c12.5-12.5 32.8-12.5 45.3 0z"})]}));var NS={};ht(NS,{enUS:()=>A6,nlNL:()=>_6});var A6={error:[{type:0,value:"Something went wrong"}]},_6={error:[{type:0,value:"Er ging iets fout"}]};var Hn=b(I()),M6=3e3,N6=({assistantOptions:e})=>{let t=z("OnDemandAssistants",uA),n=se(NS),r=(0,hA.useRef)(),o=Ad(mn),i=G(vP),s=Ze(),a=i.filter(u=>u.isPinned),l=i.filter(u=>!u.isPinned),c=u=>M(null,null,function*(){clearTimeout(r.current),s("trigger on demand assistant",{assistantCode:u}),yield o.call(A(E({},e),{assistantCode:u})),r.current=setTimeout(()=>o.reset(),M6)});return i.length===0?null:(0,Hn.jsxs)("div",{className:t.root,children:[a.map(({assistant:u,assistantName:f,displayName:d})=>(0,Hn.jsx)("button",{type:"button",className:t.button,disabled:o.state==="loading",onClick:()=>c(u),children:d||f},u)),l.length>0&&(0,Hn.jsxs)(wt,{placement:"top-end",children:[(0,Hn.jsx)(wt.Trigger,{className:t.trigger,disabled:o.state==="loading",children:(0,Hn.jsx)(dm,{"data-testid":"trigger"})}),(0,Hn.jsx)(wt.Content,{className:t.nav,"data-testid":"popover",children:l.map(({assistant:u,assistantName:f,displayName:d})=>(0,Hn.jsx)(wt.Button,{className:t.item,disabled:o.state==="loading",onClick:()=>c(u),children:d||f},u))})]}),o.state==="loading"&&(0,Hn.jsx)(fA,{}),o.state==="done"&&(0,Hn.jsx)(gA,{"data-testid":"trigger-done"}),o.state==="error"&&(0,Hn.jsx)(ZR,{trigger:(0,Hn.jsx)(mA,{}),children:n("error")})]})},yA=N6;var mu={};ht(mu,{enUS:()=>O6,nlNL:()=>L6});var O6={useCue:[{type:0,value:"Add to message"}],__summarizerAssistant__:[{type:0,value:"Summary"}],copyCue:[{type:0,value:"Copy"}],removeCue:[{type:0,value:"Close"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}]},L6={useCue:[{type:0,value:"Voeg toe aan bericht"}],__summarizerAssistant__:[{type:0,value:"Samenvatting"}],copyCue:[{type:0,value:"Kopi\xEBren"}],removeCue:[{type:0,value:"Sluiten"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}]};var ks=b(Z());var OS={title:"dd-YBHrC",fadeup:"dd-cRM0K",fadedown:"dd-7D4Pq",selected:"dd-bueui",actions:"dd-9Iqn9",ctaMessage:"dd-ge8nB",thumbsUp:"dd-6QwVx",thumbsDown:"dd-d3E8l",form:"dd-sPNU2",formInput:"dd-F3E4I",formSubmit:"dd-vw5S0",actionButton:"dd-cCWyJ",editableCue:"dd-nWSD-",inputSpace:"dd-DGYB1"};var Lt=b(I()),D6=500,F6=100,z6=({content:e,onChange:t,onCopy:n})=>{let r=(0,ks.useRef)(null),o=z("WidgetCue",OS);return(0,ks.useEffect)(()=>{let i=r.current;if(!i)return;i.style.setProperty("height","0px");let s=Math.min(Math.max(i.scrollHeight,F6),D6);i.style.setProperty("height",`${s}px`)},[e]),(0,Lt.jsx)("textarea",{ref:r,className:o.editableCue,onCopy:n,onChange:t,value:e})},H6=({cue:e,onCallToAction:t,onRemove:n,onCopy:r,onUse:o})=>{var g;let i=z("WidgetCue",OS),s=se(mu),a=Ze(),l=X("hasKeyboardInput"),[c,u]=(0,ks.useState)(e.text),f=v=>{let h=v?A(E({},e),{callToAction:v}):e;t&&t(c,h),n(e)},d=(v,h)=>{r&&r(v,e),h&&Bo(h,i.fadeup)},p=v=>{o&&o(v,e)},m=v=>{v.preventDefault(),v.stopPropagation(),n(e)};return(0,ks.useEffect)(()=>{a("Assistant response displayed",{evaluationId:e.evaluationId,assistantCode:e.rule.label,assistantOutput:e.text})},[]),(0,Lt.jsxs)(pe,{"data-testid":"cue",children:[(0,Lt.jsx)(we,{children:(0,Lt.jsxs)(we.Content,{children:[e.title&&(0,Lt.jsx)(we.Title,{className:i.title,"data-testid":"widget-cue-title",children:e.rule.label.startsWith("__")?s(e.rule.label):e.title}),e.message&&(0,Lt.jsx)("p",{className:i.ctaMessage,children:e.message}),e.editable?(0,Lt.jsx)(z6,{content:c,onCopy:()=>{let v=document.getSelection();v&&d(v.toString())},onChange:v=>{var h;return u((h=v.target.value)!=null?h:"")}}):(0,Lt.jsx)(is,{content:e.text,useLabel:s("useCue"),copyLabel:s("copyCue"),onCopy:d,onUse:l?p:void 0})]})}),(0,Lt.jsxs)(pe.ButtonsContainer,{children:[(0,Lt.jsxs)("div",{className:i.actions,children:[(0,Lt.jsx)(pe.Button,{onClick:v=>{var h;return d((h=Kd(c,"reply")[0])!=null?h:c,v.target)},variant:"primary",children:s("copyCue")}),e.callToAction&&(0,Lt.jsx)(pe.Button,{onClick:()=>f(),variant:"primary",children:e.callToAction.label}),(g=e.callToActions)==null?void 0:g.map((v,h)=>(0,Lt.jsx)(pe.Button,{onClick:()=>f(v),variant:"primary",children:v.label},`${v.event}-${v.label}-${h}`)),(0,Lt.jsx)(pe.Button,{onClick:m,variant:"secondary",children:s("removeCue")})]}),(0,Lt.jsx)(Qd,{evaluationId:e.evaluationId,assistantCode:e.rule.label,assistantOutput:e.text,feedbackText:e.text,feedbackType:"assistant"})]})]})},vA=H6;var Ja=b(I()),B6=({cues:e})=>{let t=Ee(),n=pn(),r=se(mu),o=Ze(),i=c=>{t(qd({code:c.rule.label})),o("Assistant response closed",{evaluationId:c.evaluationId,assistantCode:c.rule.label,assistantOutput:c.text})},s=(c,u)=>{Ar(c),o("Assistant response copied",{evaluationId:u.evaluationId,assistantCode:u.rule.label,assistantOutput:u.text,copiedText:c})},a=(c,u)=>{var f;u.callToAction&&(t(Gd(u)),o("Assistant call to action",{evaluationId:u.evaluationId,assistantCode:u.rule.label,assistantOutput:u.text,eventName:u.callToAction.event,value:(f=u.callToAction.value)!=null?f:c}))},l=(c,u)=>{var f;n.send(eo,{text:c,suggestion:{source:"assistant",assistantCode:(f=u.rule)==null?void 0:f.label,sourceText:c}}),o("Assistant response used",{evaluationId:u.evaluationId,assistantCode:u.rule.label,assistantOutput:u.text,usedText:c})};return(0,Ja.jsx)(Ja.Fragment,{children:e.map(c=>c.isLoading?(0,Ja.jsx)(Ep,{title:c.rule.label.startsWith("__")?r(c.rule.label):c.title},c.rule.id):(0,Ja.jsx)(vA,{cue:c,onCallToAction:a,onRemove:i,onCopy:s,onUse:l},c.evaluationId))})},SA=B6;var Um=b(Z());var xA={root:"dd-cvTAY",label:"dd-QWQxD",value:"dd-WSUHF",copyButton:"dd-67o9H",copyButtonText:"dd-oos-l",isTrue:"dd--1g2O",isFalse:"dd-sz2ir"};var En=b(I());function U6(e,t){return t.split(".").reduce((n,r)=>!n||typeof n!="object"||!(r in n)?null:n[r],e)}var wA=({data:e,schema:t})=>{let n=z("WidgetCustomData",xA),r=o=>{Ar(o)};return(0,Um.useEffect)(()=>{te.info("Custom data",e,t)},[e]),(0,En.jsx)("dl",{className:n.root,children:t.map(o=>{let i=U6(e,o.path);return(0,En.jsxs)(Um.Fragment,{children:[(0,En.jsx)("dt",{className:n.label,children:o.label}),(0,En.jsx)("dd",{className:n.value,children:o.type==="boolean"&&i?(0,En.jsx)("span",{className:n.isTrue,children:o.trueValue}):o.type==="boolean"&&!i?(0,En.jsx)("span",{className:n.isFalse,children:o.falseValue}):o.type==="array"&&Array.isArray(i)&&i.length>0?(0,En.jsxs)("button",{type:"button",onClick:()=>r(i.join(", ")),className:n.copyButton,children:[(0,En.jsx)("span",{className:n.copyButtonText,children:i.join(", ")}),(0,En.jsx)(Za,{})]}):typeof i=="string"||typeof i=="number"?(0,En.jsxs)("button",{type:"button",onClick:()=>r(`${i}`),className:n.copyButton,children:[(0,En.jsx)("span",{className:n.copyButtonText,children:i}),(0,En.jsx)(Za,{})]}):"-"})]},o.label)})})};var EA=b(Z());var V6=/(https?:\/\/[^\s]+)/,bA=e=>e.split(" ").find(t=>V6.test(t));var Zn=b(I()),W6=({suggestion:e,lines:t,onUse:n})=>{var f;let r=e.text||e.url||e.message,o=bA(r),i=se(ou),s=X("showImages"),a=X("fallbackImage"),l=X("hasKeyboardInput"),c=d=>{d.preventDefault(),d.stopPropagation(),l&&n(r)},u=(0,EA.useCallback)(d=>{window.open(o,"_blank"),d.stopPropagation(),d.preventDefault()},[o]);return(0,Zn.jsxs)(pe,{onClick:l?c:void 0,"data-testid":"edit-suggestion",children:[(0,Zn.jsxs)(we,{children:[s&&e.image&&(0,Zn.jsx)(we.Image,{src:Dm(e,"small",a||void 0),title:e.title}),(0,Zn.jsxs)(we.Content,{children:[e.title&&(0,Zn.jsx)(we.Title,{"data-testid":"widget-suggestion-title",children:e.title}),e.searchKeywords&&((f=e.searchKeywords)==null?void 0:f.length)>0&&(0,Zn.jsx)(pe.Labels,{labels:e.searchKeywords}),(0,Zn.jsx)(we.Content,{cropText:t==="single",lineClamp:t==="multiple",children:r})]})]}),(0,Zn.jsxs)(pe.Actions,{children:[o&&(0,Zn.jsx)(pe.ActionButton,{onClick:u,label:i("visitUrl")}),l&&(0,Zn.jsx)(pe.ActionButton,{primary:!0,onClick:c,label:i("useSuggestion")})]})]})},CA=W6;var gu=b(I()),$6=({lines:e,suggestions:t})=>{let n=pn(),r=(o,i)=>{n.send(eo,{text:o,suggestion:A(E({},i),{source:i.source,sourceText:i.text})})};return(0,gu.jsx)(gu.Fragment,{children:t.map(o=>(0,gu.jsx)(CA,{suggestion:o,lines:e,onUse:i=>r(i,o)},o.text||o.url||o.message))})},TA=$6;var hu={};ht(hu,{enUS:()=>j6,nlNL:()=>K6});var j6={waiting:[{type:0,value:"Loading\u2026"}],waitingForConversation:[{type:0,value:"Waiting for conversation\u2026"}],notSupported:[{type:0,value:"This conversation is not supported"}],noResults:[{type:0,value:"No results found\u2026"}],titleCues:[{type:0,value:"Assistant updates"}],actions:[{type:0,value:"Shortcuts"}],linkStudioLogin:[{type:0,value:"My "},{type:1,value:"productName"}],linkSummary:[{type:0,value:"Summarize"}],linkKnowledgeSearch:[{type:0,value:"Knowledge Assist"}],linkSearch:[{type:0,value:"Search"}],close:[{type:0,value:"Close"}]},K6={waiting:[{type:0,value:"Laden\u2026"}],waitingForConversation:[{type:0,value:"Wachten op gesprek\u2026"}],notSupported:[{type:0,value:"Dit gesprek wordt niet ondersteund"}],noResults:[{type:0,value:"Geen resultaten gevonden\u2026"}],titleCues:[{type:0,value:"Assistant updates"}],actions:[{type:0,value:"Shortcuts"}],linkStudioLogin:[{type:0,value:"Mijn "},{type:1,value:"productName"}],linkSummary:[{type:0,value:"Gesprek samenvatten"}],linkKnowledgeSearch:[{type:0,value:"Knowledge assist"}],linkSearch:[{type:0,value:"Zoeken"}],close:[{type:0,value:"Sluiten"}]};var el={root:"dd-W9VCG",loginText:"dd--dS6t",stateText:"dd-348OC",footer:"dd-tvofr",shortcutList:"dd-MuKK-",shortcut:"dd-5CnK9",footerShortcut:"dd-dH7XJ",link:"dd-DRo0x"};var ce=b(I()),kA=(e,t)=>{let n=G(Pt);(0,Ci.useEffect)(()=>n?t.every(r=>!!r)?e():()=>{}:()=>{},[...t,n])},G6=({onLogIn:e})=>{let t=z("Widget",el),n=X("isEmbedded"),r=X("adminUrl");return(0,ce.jsx)("div",{className:t.loginText,children:(0,ce.jsx)("div",{children:(0,ce.jsx)(Tm,{isEmbedded:n,loginUrl:r,onLogIn:e})})},"login")},LS=({text:e})=>{let t=z("Widget",el);return(0,ce.jsx)("div",{className:t.stateText,children:(0,ce.jsx)("div",{children:(0,ce.jsx)("p",{children:e})})},"notification")},q6=()=>{let e=se(hu),t=Ee(),n=z("Widget",el),r=X("showSearch"),o=X("isEmbedded"),i=G(Uo("/admin/")),s=pn(),a=X("productName"),l=Ze();return kA(()=>{if(o)return t(PS()),()=>{t(rA())}},[t,o]),!r&&!i?null:(0,ce.jsxs)("div",{className:n.shortcutList,children:[r&&(0,ce.jsx)(pe.Button,{"data-testid":"shortcut-search","aria-label":e("linkSearch"),className:n.shortcut,icon:(0,ce.jsx)(Ga,{}),onClick:()=>{s.send("ShowCommandPalette",{isOpen:!0}),l("open search",{via:"widget-shortcut"})},children:e("linkSearch")}),i&&(0,ce.jsx)(pe.Button,{as:"a",target:"_blank",icon:(0,ce.jsx)(cA,{}),href:i,"data-testid":"shortcut-studio-login","aria-label":e("linkStudioLogin",{productName:a}),className:n.shortcut,rel:"noreferrer",onClick:()=>{l("open my deepdesk",{via:"widget-shortcut"})},children:e("linkStudioLogin",{productName:a})})]})},Y6=({title:e,content:t})=>{let n=se(hu),[r,o]=(0,Ci.useState)(!0);return r?(0,ce.jsx)(Tr,{"data-testid":"custom-data-banner",type:"custom-data-banner",title:e,children:(0,ce.jsx)(Tt,{withDivider:!0,children:(0,ce.jsxs)(pe,{children:[(0,ce.jsx)(we,{children:(0,ce.jsx)(we.Content,{children:(0,ce.jsx)(is,{content:t})})}),(0,ce.jsx)(pe.ButtonsContainer,{children:(0,ce.jsx)(pe.Button,{onClick:()=>o(!1),children:n("close")})})]})})}):null},X6=()=>{let e=Ee(),t=G(Gc),n=G(xP),r=G(sA),o=G(Lb),i=G(um),s=G(mm),a=G(mi),l=G(Pr);return(0,Ci.useEffect)(()=>{o&&!n&&te.warn("Custom data provided, but no schema.")},[o,n]),kA(()=>{t.forEach(({type:c})=>{c==="entities"?e(vr()):ju.includes(c)||e(Sr(c))})},[e,l,a]),(0,Ci.useEffect)(()=>{r.length>0&&!t.some(c=>c.type==="cues")&&te.warn("Received cues, but cues are not configured in widget.")},[t,r]),(0,ce.jsx)(Ci.Fragment,{children:t.map(({type:c,title:u,amount:f,lines:d,schema:p,property:m})=>{var g,v;switch(c){case"entities":return i&&i.length>0&&(0,ce.jsx)(Tr,{type:c,title:u,"data-testid":`type-${c}`,children:(0,ce.jsx)(lA,{entities:i})},c);case"cues":return r&&r.length>0&&(0,ce.jsx)(Tr,{type:c,title:u,"data-testid":`type-${c}`,children:(0,ce.jsx)(Tt,{withDivider:!0,children:(0,ce.jsx)(SA,{cues:r})})},c);case"custom-data-banner":return o&&m&&o[m]&&(0,ce.jsx)(Y6,{title:u,content:String(o[m])},c);case"custom-data":return o&&p&&(0,ce.jsx)(Tr,{type:c,title:u,"data-testid":`type-${c}`,children:(0,ce.jsx)(Tt,{withDivider:!0,children:(0,ce.jsx)(wA,{data:o,schema:p})})},c);default:return((v=(g=s[c])==null?void 0:g.suggestions)==null?void 0:v.length)>0&&(0,ce.jsx)(Tr,{type:c,title:u,"data-testid":`type-${c}`,children:(0,ce.jsx)(Tt,{withDivider:!0,children:(0,ce.jsx)(TA,{lines:d,contentType:c,suggestions:s[c].suggestions.slice(0,f)||[]})})},c)}})})},DS=({children:e})=>{let t=z("Widget",el);return(0,ce.jsx)("div",{className:t.footer,children:e})},FS=({children:e})=>{let t=z("Widget",el);return(0,ce.jsx)("div",{className:t.root,"data-testid":"widget",children:e})},Q6=({onLogIn:e,knowledgeAssistOptions:t={},assistantOptions:n={transcript:"in-memory-transcript"}})=>{let r=se(hu),o=G($s),i=G(Pt),s=G(yd),a=G(mi),l=G(SP("knowledge-assist")),c=G(wP);return o===!1?(0,ce.jsx)(LS,{text:r("notSupported")}):i===!1?(0,ce.jsx)(G6,{onLogIn:e}):i===null?(0,ce.jsx)(LS,{text:r("waiting")}):!s||!a?(0,ce.jsx)(LS,{text:r("waitingForConversation")}):(0,ce.jsx)(FS,{children:(0,ce.jsxs)(Yp,{initialQuestion:t.initialQuestion,assistantCode:c!=null?c:void 0,evaluateKnowledgeAssistFn:Hl,children:[(0,ce.jsxs)(Hs,{children:[(0,ce.jsx)(q6,{}),(0,ce.jsx)(X6,{}),l&&(0,ce.jsx)(Qp,{title:l.title,emptyState:t.emptyState})]}),(0,ce.jsxs)(DS,{children:[l&&(0,ce.jsx)(Xp,{}),(0,ce.jsx)(yA,{assistantOptions:n})]})]})})},RA=Q6;function tl(e){let t=new Range;return t.selectNodeContents(e),t}function PA(e,t,n){try{return Ti(e,t,n),!0}catch(r){return!1}}function Vm(e){return"tagName"in e&&(e.tagName==="DIV"||e.tagName==="P")}function Wm(e){return"tagName"in e&&e.tagName==="BR"}var yu=/[\u200B-\u200D\uFEFF]/g;function Ti(e,t,n){let r=new Range;if(e.firstChild===null&&t===0&&n===0)return r.selectNodeContents(e),r;let o=0,i=!1;function s(l,c){let u=-1,f=/[\u200B-\u200D\uFEFF]/;if(!f.test(l))return c;for(let d=0;d<=l.length;d++)if(f.test(l[d])||u++,u===c)return d;throw new Error("Offset out of range")}function a(l){switch(l.nodeType){case Node.TEXT_NODE:{let c=l.textContent,u=c.replace(yu,""),f=o+u.length,d=t>=o&&t<=f,p=n>=o&&n<=f;if(d){let m=s(c,t-o);m===0&&!p?r.setStartBefore(l):r.setStart(l,m)}p&&(r.setEnd(l,s(c,n-o)),i=!0),o=f;break}case Node.ELEMENT_NODE:{if(Wm(l)&&(o===t&&r.setStartBefore(l),o++,o===n)){r.setEndAfter(l),i=!0;return}for(let u=0;u<l.childNodes.length&&(a(l.childNodes[u]),!i);u++);let c=l.lastChild;Vm(l)&&c&&!Vm(c)&&!Wm(c)&&o++;break}default:break}}if(a(e),r.startContainer===document)throw new Error("Offsets out of bound");return r}function vu(e,t){if(!e.contains(t.startContainer)||!e.contains(t.endContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:r,endContainer:o,endOffset:i,collapsed:s}=t,a,l,c=0;function u(f){let d=f===e,p=f===n,m=f===o;switch(f.nodeType){case Node.TEXT_NODE:{let g=f.textContent;p&&(a=c+g.substring(0,r).replace(yu,"").length),m&&(l=c+g.substring(0,i).replace(yu,"").length),c+=g.replace(yu,"").length;break}case Node.ELEMENT_NODE:{if(Wm(f)&&f.nextSibling){c++;break}!d&&Vm(f)&&f.previousSibling&&c++;for(let g=0;g<f.childNodes.length;g++){let v=p&&g===r,h=m&&g===i;if(v&&(a=c),h&&(l=c),l!==void 0||((!v||!s)&&u(f.childNodes[g]),m&&g===i-1&&(l=c),l!==void 0))break}m&&(l=c);break}default:break}}if(u(e),l===void 0)throw new Error("Could not determine start and end");return{start:a!=null?a:l,end:l}}function Su(e,t){if(!e.contains(t.startContainer)||!e.contains(t.endContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:r,endContainer:o,endOffset:i,collapsed:s}=t,a=0,l="";function c(u){let f=u===e,d=u===n,p=u===o;switch(d&&(a=1),u.nodeType){case Node.TEXT_NODE:{if(a!==1)return;let m=d?r:0,g=p?i:void 0;l+=u.textContent.replace(yu,"").substring(m,g);break}case Node.ELEMENT_NODE:{if(!s&&a===1&&Wm(u)&&u.nextSibling){l+=`
82
82
  `;break}!f&&!s&&a===1&&Vm(u)&&u.previousSibling&&(l+=`
83
- `);let m=d?r:0,g=p?Math.min(i,u.childNodes.length):u.childNodes.length;for(let v=m;v<g&&(c(u.childNodes[v]),a!==2);v++);break}default:break}p&&(a=2)}return c(e),l}var IA=(s=>(s.CUT="Cut",s.BACKSPACE="Backspace",s.DELETE="Delete",s.ERASEEOF="EraseEof",s.UNDO="Undo",s.CLEAR="Clear",s))(IA||{}),_o=class{constructor(t){this.element=t;this.isFocused=!1;this.isActive=!0;this.isDisposed=!1;this.eventListeners={};this.disposeHandlers=[];this.cachedText="";this.cachedSuggestionTextStart=0;this.cachedCaretPosition=null;this.cachedSelection={start:0,end:0};this.cachedHTML="";this.isSubmitting=!1;this.isPossibleClearInputAction=!1;this.cachedText=this.getText(),this.cachedSuggestionTextStart=this.getSuggestionTextStart(),this.cachedHTML=this.getHTML(),this.cachedSelection=this.getSelection(),this.listen()}addEventListener(t,n){let r=o=>{n(o)};this.element.addEventListener(t,r),this.disposeHandlers.push(()=>{this.element.removeEventListener(t,r)})}removeEventListener(t,n){this.element.removeEventListener(t,n)}handleInteraction(){let t=this.getText(),n=this.getHTML(),r=this.getSelection(),o=this.getSuggestionTextStart(),i=this.cachedCaretPosition===null;if(!this.isActive)return;t===""&&this.cachedText!==""&&!this.isPossibleClearInputAction&&this.emit("submit");let s=t!==this.cachedText,a=n!==null&&n!==this.cachedHTML,l=o!==this.cachedSuggestionTextStart;if((s||a||l)&&(s?(this.cachedText=t,this.cachedHTML=n):a&&(this.cachedHTML=n),this.cachedSuggestionTextStart=o,i=!0,this.emit("change",{plainText:t,rawHTML:n,suggestionTextStart:o})),(r.start!==this.cachedSelection.start||r.end!==this.cachedSelection.end)&&(this.cachedSelection=r,i=!0,this.emit("selection",r)),!i)return;let c=this.getCaretPosition();zo(c,this.cachedCaretPosition)||(this.cachedCaretPosition=c,this.emit("caretposition",c))}handleClick(){this.handleInteraction()}handleFocus(){let t=!this.isFocused;this.isFocused=!0,t&&this.emit("focus"),this.handleInteraction()}handleBlur(){this.isPossibleClearInputAction=!1;let t=this.isFocused;this.isFocused=!1,t&&this.emit("blur")}handleKeyDown(t){let{key:n,ctrlKey:r,metaKey:o}=t;this.isPossibleClearInputAction=Object.values(IA).includes(n)||n.toLowerCase()==="z"&&(r||o),this.emit("keydown",t)}handleKeyUp(t){this.handleInteraction(),this.emit("keyup",t)}handleCut(){this.isPossibleClearInputAction=!0,this.emit("cut",{selectionText:this.getSelectedText()})}handlePaste(t){var r,o;let n=((r=t.clipboardData)==null?void 0:r.getData("text"))||((o=t.clipboardData)==null?void 0:o.getData("text/plain"))||"";this.emit("paste",{pastedText:n,selectionText:this.getSelectedText()})}listen(){this.addEventListener("keydown",n=>this.handleKeyDown(n)),this.addEventListener("keyup",n=>this.handleKeyUp(n)),this.addEventListener("input",()=>this.handleInteraction()),this.addEventListener("change",()=>this.handleInteraction()),this.addEventListener("focus",()=>this.handleFocus()),this.addEventListener("blur",()=>this.handleBlur()),this.addEventListener("cut",()=>this.handleCut()),this.addEventListener("paste",n=>this.handlePaste(n)),this.addEventListener("click",()=>this.handleInteraction()),document.activeElement===this.element&&(this.isFocused=!0);let t=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});t.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{t.disconnect()})}getSuggestionTextStart(){return 0}focus(){this.element.focus()}emit(t,...n){this.isDisposed||this.eventListeners[t]&&this.eventListeners[t].forEach(r=>{r(...n)})}on(t,n){this.isDisposed||(this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n))}off(t,n){if(!this.eventListeners[t])return;let r=this.eventListeners[t].indexOf(n);r!==-1&&this.eventListeners[t].splice(r,1)}activate(){let t=this.isActive===!1;this.isActive=!0,t&&this.handleInteraction()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(t=>t()),this.eventListeners={},this.isDisposed=!0}};function AA(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var Rs=class extends _o{constructor(){super(...arguments);this.lastKnownSelection=null}getRootNode(){return this.element.getRootNode()}getText(){let n=new Range;return n.selectNodeContents(this.element),Su(this.element,n)}getHTML(){return this.element.innerHTML||""}getRange(){let n=this.getRootNode();if(n.activeElement!==this.element)return null;let r="getSelection"in n?n.getSelection():window.getSelection();if(!r)return null;let o=r.rangeCount>0?r.getRangeAt(0):null;if(!o)return null;let i=this.element.ownerDocument.createRange();return i.setStart(o==null?void 0:o.startContainer,o==null?void 0:o.startOffset),i.setEnd(o==null?void 0:o.endContainer,o==null?void 0:o.endOffset),!i||!this.element.contains(i.startContainer)||!this.element.contains(i.endContainer)?null:i}getCaretPosition(){let n=this.getRange();if(!n||!n.collapsed||!("getBoundingClientRect"in n))return null;let r=n.getBoundingClientRect();return!AA(r)&&(n.insertNode(this.element.ownerDocument.createTextNode("\u2060")),r=n.getBoundingClientRect(),n.deleteContents(),!AA(r))?null:{top:r.top+r.height,left:r.left}}getSelection(){let n=this.getRange();if(n)return vu(this.element,n);let r=this.lastKnownSelection;if(r&&PA(this.element,r.start,r.end))return r;let o=tl(this.element);return o.collapse(!1),vu(this.element,o)}getSelectedText(){let{start:n,end:r}=this.getSelection();return Su(this.element,Ti(this.element,n,r))}listen(){super.listen();let n=new MutationObserver(i=>{var s,a;i.length===2&&i[0].addedNodes.length===1&&((s=i[0].addedNodes[0])==null?void 0:s.textContent)==="\u2060"&&((a=i[1].removedNodes[0])==null?void 0:a.textContent)==="\u2060"||setTimeout(()=>{this.handleInteraction()},0)});n.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0}),this.disposeHandlers.push(()=>n.disconnect());let r=this.element.isContentEditable,o=new MutationObserver(()=>{this.element.isContentEditable!==r&&(r=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>o.disconnect())}};var Z6=["direction","boxSizing","width","height","overflowX","overflowY","borderTopWidth","borderRightWidth","borderBottomWidth","borderLeftWidth","borderStyle","paddingTop","paddingRight","paddingBottom","paddingLeft","fontStyle","fontVariant","fontWeight","fontStretch","fontSize","fontSizeAdjust","lineHeight","fontFamily","textAlign","textTransform","textIndent","textDecoration","letterSpacing","wordSpacing","tabSize"];function _A(e,t){let n="mozInnerScreenX"in window,r=document.createElement("div");r.id="input-textarea-caret-position-mirror-div";let o=r.style,i=window.getComputedStyle(e),s=e.ownerDocument.body;o.whiteSpace="pre-wrap",o.wordWrap="break-word",o.position="absolute",o.visibility="hidden",Z6.forEach(u=>{o[u]=i[u]}),n?e.scrollHeight>Number.parseInt(i.height)&&(o.overflowY="scroll"):o.overflow="hidden",r.textContent=e.value.substring(0,t);let a=document.createElement("span");a.textContent=e.value.substring(t)||".",r.appendChild(a),s.appendChild(r);let l=e.getBoundingClientRect(),c={top:l.top-e.scrollTop+a.offsetTop+Number.parseInt(i.borderTopWidth)+a.offsetHeight,left:l.left-e.scrollLeft+a.offsetLeft+Number.parseInt(i.borderLeftWidth)};return s.removeChild(r),c}var Ps=class extends _o{constructor(){super(...arguments);this.lastKnownSelection=null}getText(){return this.element.value}getHTML(){return null}getSelection(){let{selectionStart:n,selectionEnd:r}=this.element;return{start:n,end:r}}getSelectedText(){let n=this.getSelection();return n?this.getText().slice(n.start,n.end):""}getCaretPosition(){return _A(this.element,this.element.selectionEnd)}listen(){super.listen();let n=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var i;return(i=n==null?void 0:n.get)==null?void 0:i.call(this.element)},set:i=>{var s;(s=n==null?void 0:n.set)==null||s.call(this.element,i),this.handleInteraction()}}),this.addEventListener("scroll",()=>{this.emit("caretposition",this.getCaretPosition())});let r=this.element.disabled,o=new MutationObserver(()=>{this.element.disabled!==r&&(r=this.element.disabled,this.emit(r?"disabled":"enabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>o.disconnect())}};function MA(e,t,n){let r=`deepdesk-iframe-${e}`,o=document.getElementById(r);if(o)return o;let i=document.createElement("iframe"),s=new URL(t);return Object.entries(n).forEach(([a,l])=>{s.searchParams.append(a,l)}),i.style.position="absolute",i.style.left="-999em",i.style.width="0px",i.style.height="0px",i.tabIndex=-1,i.id=r,i.title=`iframe-${e}`,i.src=s.toString(),window.document.body.appendChild(i),i}function J6(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch(t){return e}}var zS=class{constructor(t){this.name=t;this.disposeHandlers=[];this.broadcastChannel=new BroadcastChannel(t)}onMessage(t){this.broadcastChannel.addEventListener("message",t),this.disposeHandlers.push(()=>{this.broadcastChannel.removeEventListener("message",t)})}postMessage(t){this.broadcastChannel.postMessage(JSON.stringify(t))}close(){this.disposeHandlers.forEach(t=>t()),this.broadcastChannel.close()}},HS=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.disposeHandlers=[];this.iframe=MA(t,`${this.targetOrigin}/sdk/proxy/proxy.html`,{channel:this.name,host:window.location.origin,debug:"1"}),document.body.appendChild(this.iframe)}onMessage(t){window.addEventListener("message",t),this.disposeHandlers.push(()=>{window.removeEventListener("message",t)})}postMessage(t){var n;(n=this.iframe.contentWindow)==null||n.postMessage(JSON.stringify(t),this.targetOrigin)}close(){var t;this.disposeHandlers.forEach(n=>n()),(t=this.iframe)==null||t.remove()}},BS=class{constructor(t){this.params=t;this.deepdeskUrl=t.deepdeskUrl,this.eventMap=t.eventMap,this.externalId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setExternalId(t){this.externalId!==t&&(this.cleanup(),te.info("Set externalId",t),this.externalId=t,this.channel=this.createChannel(t))}createChannel(t){let n=this.params.createCustomChannel?this.params.createCustomChannel(t):this.isCrossOrigin?new HS(t,this.deepdeskUrl,{debug:!0}):new zS(t),r=o=>{var s,a;if(o.origin!==this.deepdeskUrl)return;let i=J6(o.data);typeof i!="object"||i.type!=="event"||i.channel!==t||(te.info("Received broadcast event",this.externalId,o),(a=(s=this.eventMap)[i.name])==null||a.call(s,i.payload))};return n.onMessage(r),n}send(t,n,r){var s,a;te.info("Broadcast event",{externalId:this.externalId,name:t,payload:n});let o={type:"event",name:t,payload:n};r!==!1&&((a=(s=this.eventMap)[t])==null||a.call(s,n));let i=this.externalId==="deepdesk-general"?this.defaultChannel:this.channel;i==null||i.postMessage(A(E({},o),{channel:this.externalId}))}cleanup(t=!1){var n,r;(n=this.channel)==null||n.close(),this.channel=void 0,t&&((r=this.defaultChannel)==null||r.close(),this.defaultChannel=void 0)}},NA=BS;function ez(e){return e.replace(/(_\w)/g,t=>t[1].toUpperCase())}function Ve(e){return Array.isArray(e)?e.map(Ve):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>A(E({},t),{[ez(n)]:Ve(e[n])}),{}):e}function tz(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function ln(e){return Array.isArray(e)?e.map(ln):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>A(E({},t),{[tz(n)]:ln(e[n])}),{}):e}var nl=class extends Error{constructor(n,r){super(n);this.body=r;this.name="CustomError"}};var US=e=>new Promise(t=>{setTimeout(t,e)});var Is=class extends nl{constructor(){super(...arguments);this.name="ClientError"}},WS=class extends nl{constructor(){super(...arguments);this.name="ServerError"}},VS=new Map;function nz(e){return M(this,null,function*(){if(e.status===204)return e.text().catch(()=>{}),null;let t=e.headers.get("content-type");if(t!=null&&t.includes("application/json"))return e.json();let n=yield e.text();return n===""?null:(te.warn("Unexpected response body:",n.slice(0,20)),JSON.parse(n))})}var As=class{constructor(t="",n={}){this.baseUrl=t;this.options=n;this.latestRequestByUrl={};this.refreshingToken=null;this.lastFailedRefreshAt=null;this.failedRefreshCooldown=1e4;var r;this.fetch=(r=n.fetch)!=null?r:window.fetch.bind(window)}patchFetch(t){this.fetch=t(this.fetch)}setCsrfToken(t){this.csrfToken=t}request(t,n={}){return new Promise((r,o)=>{let i={isAborted:!1,reject:o},s=`${this.baseUrl}${t}`,a=this.fetch,l=n.method===void 0||n.method.toLowerCase()==="get",C=n,{useCache:c=!1,abortLatest:u=!1,attempts:f=1,retryDelay:d=500,refreshTokenOn401:p=!0,retryOnError:m=k=>k instanceof TypeError,retryOnResponse:g=k=>k.status>=500,version:v=null}=C,h=ie(C,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]);if(c){if(!l)throw new Error(`Can't use 'useCache' for ${n.method}`);if(VS.has(s)){r(VS.get(s));return}}let y=A(E({credentials:"include"},h),{headers:E({Accept:"application/json","Content-Type":"application/json"},h.headers)});!l&&this.csrfToken&&(y.headers=A(E({},y.headers),{"X-CSRFToken":this.csrfToken})),typeof v=="string"&&(y.headers=A(E({},y.headers),{"X-Deepdesk-API-Version":v}));let S=f,x=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[s]&&u&&(this.latestRequestByUrl[s].isAborted=!0,this.latestRequestByUrl[s].reject(new Error("Aborted"))),this.latestRequestByUrl[s]=i;let T=()=>M(this,null,function*(){return S--,a(s,y).then(k=>M(this,null,function*(){return g(k)&&!i.isAborted&&S>0?(yield US(d),T()):k.status===401&&p===!0&&x===!1?(x=!0,yield this.refreshToken(),T()):k})).catch(k=>M(this,null,function*(){if(m(k)&&!i.isAborted&&S>0)return yield US(d),T();throw k}))});T().then(k=>M(this,null,function*(){let R=yield nz(k);if(delete this.latestRequestByUrl[s],k.status>=500){o(new WS("Server Error",R));return}if(k.status===401){o(new Is("Unauthorized",R));return}if(k.status===403){o(new Is("Forbidden",R));return}if(k.status===404){o(new Is("Not Found",R));return}if(k.status>=400){o(new Is("Bad Request",R));return}c&&VS.set(s,R),r(R)})).catch(k=>{o(k)})})}validateToken(){return M(this,null,function*(){let t,n,r;try{({has_valid_access_token:t,is_logged_in:n,has_valid_refresh_token:r}=yield this.get("/apis/admin/session/validate/",{refreshTokenOn401:!1}))}catch(o){return!1}if(!t){if(!r)return!1;try{yield this.refreshToken();let{is_logged_in:o}=yield this.get("/apis/admin/session/validate/",{refreshTokenOn401:!1});return o}catch(o){return!1}}return n})}refreshToken(){let t=Date.now();return this.lastFailedRefreshAt&&t-this.lastFailedRefreshAt<this.failedRefreshCooldown?Promise.reject(new Is("Unauthorized","Failed to refresh token")):this.refreshingToken?this.refreshingToken:(this.refreshingToken=this.get("/apis/admin/session/refresh/",{refreshTokenOn401:!1}).catch(n=>{throw(n==null?void 0:n.message)==="Unauthorized"&&(this.lastFailedRefreshAt=Date.now()),n}).finally(()=>{this.refreshingToken=null}),this.refreshingToken)}get(t,n){return this.request(t,n)}post(t,n,r){return this.request(t,E({method:"POST",body:JSON.stringify(n)},r))}patch(t,n,r){return this.request(t,E({method:"PATCH",body:JSON.stringify(n)},r))}put(t,n,r){return this.request(t,E({method:"PUT",body:JSON.stringify(n)},r))}delete(t,n){return this.request(t,E({method:"DELETE"},n))}};var OA;(t=>{let e;(a=>(a.SUCCESS="success",a.FAILURE="failure",a.CONDITIONS_NOT_MET="conditions_not_met",a.MAX_RECURSION_LEVEL="max_recursion_level",a.NO_ACCESS_TO_ASSISTANT="no_access_to_assistant"))(e=t.EvaluationStatus||(t.EvaluationStatus={}))})(OA||(OA={}));function $S(e){return A(E({},Ve(e)),{metadata:e.metadata})}var _s=class _s{constructor(t,n={}){this.options=n;this.latestReceivedDeepdeskVersions={};this.shouldFetchCsrfToken=!0;this.client=new As(t,{fetch:n.fetch}),this.client.patchFetch(r=>(o,i)=>M(this,null,function*(){let s=yield r(o,i);return this.handleDeepdeskVersionHeaders(s),s}))}preflight(){return M(this,null,function*(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let t=yield this.getCsrfToken();this.client.setCsrfToken(t)}return this.options.token?(_s.exchangeTokenPromise||(_s.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),_s.exchangeTokenPromise):Promise.resolve()})}createConversation(t){return M(this,null,function*(){var r;yield this.preflight(),te.info(`Creating conversation for session ${t.externalId} and agent ${t.agentId}`);let n=yield this.client.post("/api/v2/conversations",A(E({chat_start_time:new Date().toISOString()},ln(t)),{metadata:(r=t.metadata)!=null?r:{}}));return $S(n)})}getMe(){return M(this,null,function*(){let t=yield this.client.get("/apis/admin/session/me/");return Ve(t)})}postIdentity(t){return M(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/me/identities/",ln(t))})}patchMe(t){return M(this,null,function*(){yield this.preflight();let n=yield this.client.patch("/apis/admin/session/me/",ln(t));return Ve(n)})}getProfile(t){return M(this,null,function*(){let n=yield this.client.get(`/apis/admin/profiles/${t}/`,{useCache:!0});return Ve(n)})}getKnowledgeAssistant(t){return M(this,null,function*(){let n=yield this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{useCache:!0});return Ve(n)})}getContentTypes(){return M(this,null,function*(){let t=yield this.client.get("/apis/admin/content-types/",{useCache:!0});return Ve(t)})}getAccount(){return M(this,null,function*(){let t=yield this.client.get("/apis/admin/account/",{useCache:!0});return Ve(t)})}getPlatformConfig(t){return M(this,null,function*(){let n=t!==void 0?`/platform/config/${t}/`:"/platform/config/",{config:r}=yield this.client.get(n,{useCache:!0});return Ve(r)})}checkUserExists(t){return M(this,null,function*(){let{exists:n}=yield this.client.get(`/apis/admin/users/exists?external_id=${t}`,{version:"v1"});return n})}getConversationByExternalId(r){return M(this,arguments,function*(t,n={}){yield this.preflight(),te.info(`Getting conversation for session ${t}`);let{attempts:o=1,retryDelay:i=1e3}=n,s=yield this.client.get(`/api/v2/conversations/by_external_id/${t}`,{attempts:o,retryDelay:i,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"});return te.info(`Successfully retrieved conversation ${s.id} for session ${t}`),$S(s)})}isConversationSupported(r){return M(this,arguments,function*(t,n={}){te.info(`Check if conversation for session ${t} is supported`);let{attempts:o=1,retryDelay:i=1e3}=n;return(yield this.client.get(`/api/v2/conversations/by_external_id/${t}/has_active_profile`,{attempts:o,retryDelay:i,retryOnResponse:a=>a.status===404||a.status>=500})).has_active_profile})}updateConversation(t,n){return M(this,null,function*(){var i;yield this.preflight();let r=ln(n);n.metadata&&(r.metadata=(i=n.metadata)!=null?i:{});let o=yield this.client.put(`/api/v2/conversations/${t}`,r);return $S(o)})}postMessages(t,n){return M(this,null,function*(){yield this.preflight(),yield this.client.post(`/api/v2/conversations/${t}/messages`,n.map(r=>A(E({},ln(r)),{metadata:r.metadata})))})}sendEvent(t,n){return M(this,null,function*(){yield this.preflight();let a=n,{data:r}=a,o=ie(a,["data"]),i=Object.entries(this.latestReceivedDeepdeskVersions).reduce((l,[c,u])=>A(E({},l),{[c]:u}),{}),s=["platform","agentId","agentName","agentEmail","conversationId"].reduce((l,c)=>(o[c]&&(l[c]=o[c]),l),{});return this.client.post("/api/v2/events",ln(A(E(E({},i),s),{data:r,name:t})),{version:"v2"})})}getEntities(t){return M(this,null,function*(){return yield this.preflight(),yield this.client.post("/api/v2/entities",{messages:t.filter(r=>r.text)})})}getTemporaryExchangeToken(){return M(this,null,function*(){return(yield this.client.get("/apis/admin/session/exchange-token/")).jwt})}exchangeTokenForAccessCookie(t){return M(this,null,function*(){return this.client.post("/apis/admin/session/jwt/",{jwt:t}).catch(n=>{throw te.warn(`Invalid token '${t}'`),n})})}authenticateWithKey(t,n){return M(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/api-key/",ln(n),{refreshTokenOn401:!1,headers:{apikey:t}})})}getTextSuggestions(o){return M(this,arguments,function*(t,n={},r){if(yield this.preflight(),r==="sticky-messages")throw new Error("Use getPinnedMessages instead");return(yield this.client.post(`/api/v2/conversations/${t}/recommend/${r}`,ln(n),{abortLatest:!0})).map(s=>A(E({},Ve(s)),{text:s.text||s.url||s.message,source:r,type:r})).filter((s,a,l)=>a===l.findIndex(c=>c.text===s.text))})}isLoggedIn(){return M(this,null,function*(){return yield this.preflight(),this.client.validateToken()})}getAutocompleteSuggestions(t,n){return M(this,null,function*(){return yield this.preflight(),(yield this.client.post(`/api/v2/conversations/${t}/autocomplete`,ln(n),{abortLatest:!0})).map(o=>({score:1,source:o.source,sourceText:o.source_text,text:o.label,trainingJobs:o.training_jobs,searchKeywords:o.search_keywords,type:o.source})).filter((o,i,s)=>i===s.findIndex(a=>a.text===o.text))})}getPinnedMessages(t){return M(this,null,function*(){let n=yield this.client.get(`/api/v2/profiles/${t}/pinned-messages`,{abortLatest:!0});return Ve(n).map(r=>A(E({},r),{text:r.message,source:"sticky-messages",type:"pinned-message"}))})}getStyleSuggestions(t){return M(this,null,function*(){let n=yield this.client.post("/api/v2/style-suggestions",ln(t),{abortLatest:!0,version:"v2"});return Ve(n)})}search(t){return M(this,null,function*(){let n=yield this.client.post(`/api/v2/profiles/${t.profile}/search`,ln(t));return Ve(n)})}loginWithPassword(t,n){return M(this,null,function*(){yield this.preflight();let r=yield this.client.post("/apis/admin/session/login/",{username:t,password:n},{refreshTokenOn401:!1});return Ve(r)})}logout(){return M(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/logout/",{},{refreshTokenOn401:!1})})}requestLoginByEmail(t){return M(this,null,function*(){yield this.preflight();let n=yield this.client.post("/apis/admin/session/passwordless/request/",{email:t});return Ve(n)})}requestPasswordlessToken(){return M(this,null,function*(){let t=yield this.client.get("/apis/admin/session/passwordless/request/");return Ve(t.token)})}getCsrfToken(){return M(this,null,function*(){let{token:t}=yield this.client.get("/apis/admin/session/csrf/");return t})}verifyLoginToken(t){return M(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/login/",{token:t});return Ve(n)})}evaluateAssistant(t,n){return M(this,null,function*(){var s;yield this.preflight();let r=new URLSearchParams;n!=null&&n.externalConversationId&&r.append("external_conversation_id",n.externalConversationId);let o=n!=null&&n.threadId?`/api/v2/assistants/${t}/threads/${n==null?void 0:n.threadId}/evaluate?${r.toString()}`:`/api/v2/assistants/${t}/evaluate?${r.toString()}`,i=yield this.client.post(o,{input:(s=n==null?void 0:n.input)!=null?s:{},conversation:n==null?void 0:n.transcript});return Ve(i)})}createAssistantThread(t){return M(this,null,function*(){yield this.preflight();let{assistantCode:n}=t,r=yield this.client.post(`/apis/admin/assistants/${n}/threads/`,{});return Ve(r)})}postMessageToAssistantThread(t){return M(this,null,function*(){yield this.preflight();let{assistantCode:n,threadId:r,message:o}=t,i=yield this.client.post(`/apis/admin/assistants/${n}/threads/${r}/messages/`,{content:o,role:"user"});return Ve(i)})}translateMessages(t){return M(this,null,function*(){yield this.preflight();let n=yield this.client.post("/api/v2/translate",ln(t));return Ve(n)})}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),i=o.match(tw);if(!n||!i)return;let s=i[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[s];a&&n&&a!==n&&te.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[s]=n})}};_s.exchangeTokenPromise=null;var Mo=_s;var $m=class{constructor(t){this.options=t;this.socket=null;this.maxReconnectAttempts=5;this.reconnectInterval=25e3;this.cleanupCallbacks=[];var n,r;this.socket,this.eventListeners=new Map,this.url=t.url,this.maxReconnectAttempts=(n=t.maxReconnectAttempts)!=null?n:this.maxReconnectAttempts,this.reconnectInterval=(r=t.reconnectInterval)!=null?r:this.reconnectInterval,this.shouldReconnect=t.shouldReconnect}connect(){let t=()=>this.cleanup();window.addEventListener("beforeunload",t),this.cleanupCallbacks.push(()=>window.removeEventListener("beforeunload",t)),this.reconnect()}setupListeners(){this.socket&&(this.socket.onmessage=t=>{var n;try{let r=Ve(JSON.parse(t.data));r.event&&this.eventListeners.has(r.event)&&((n=this.eventListeners.get(r.event))==null||n.forEach(o=>o(r.data)))}catch(r){console.error("Error parsing WebSocket message:",r)}},this.socket.onclose=t=>{console.log("WebSocket connection closed:",t),setTimeout(()=>{this.reconnect()},this.reconnectInterval)},this.socket.onerror=t=>{console.error("WebSocket error:",t)})}reconnect(){var t,n;if(this.maxReconnectAttempts<=0){console.error("Max reconnect attempts reached, closing WebSocket connection."),(t=this.socket)==null||t.close();return}if(!this.shouldReconnect()){console.error("Should not reconnect, closing WebSocket connection."),(n=this.socket)==null||n.close();return}this.socket&&(this.socket.onmessage=null,this.socket.onclose=null,this.socket.onerror=null,this.socket.close()),this.socket=new WebSocket(this.url),this.setupListeners(),this.maxReconnectAttempts--}send(t,n){if(!this.socket){console.error("WebSocket connection is not open.");return}this.socket.send(JSON.stringify({event:t,data:n}))}on(t,n){this.eventListeners.has(t)||this.eventListeners.set(t,[]);let r=this.eventListeners.get(t);r&&!r.includes(n)&&r.push(n)}close(){var t;(t=this.socket)==null||t.close()}cleanup(){this.close(),this.cleanupCallbacks.forEach(t=>t()),this.cleanupCallbacks=[]}};var LA={startTime:null,stopTime:null},DA=e=>e.handlingTime,FA=Re({name:"handlingTime",initialState:LA,reducers:{handlingTimeStart(e){if(e.startTime&&!e.stopTime)throw new Error("Timing already started");e.startTime=new Date,e.stopTime=null},handlingTimeStop(e){if(!e.startTime)throw new Error("Timing not started");e.stopTime=new Date},handlingTimeReset(e){e.startTime=null,e.stopTime=null}},extraReducers:e=>{e.addCase(lt,()=>LA)}}),{handlingTimeStart:zA,handlingTimeStop:jm,handlingTimeReset:HA}=FA.actions,BA=FA.reducer;var UA=(e={})=>{let t=E({onAuthError:Ws(!1)},e);return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var VA=(e={})=>{let t,n=!0,r=E({getStyleSuggestions:Es,debounce:500},e);return o=>i=>s=>{var p;let a=o.getState().input.text,l=i(s),c=o.getState();if(c.auth.isLoggedIn!==!0)return l;let{showStyleSuggestions:u}=c.settings;if(!((p=c.conversation.current)==null?void 0:p.id)||!u)return l;let{text:d}=c.input;return d===a&&!n||(clearTimeout(t),d==="")||(t=setTimeout(()=>{n=!1,o.dispatch(r.getStyleSuggestions({text:d}))},e.debounce)),l}};function rz(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end&&e.suggestionTextStart===t.suggestionTextStart}var WA=(e={})=>{let t=E({getTextSuggestions:Sr,getAutocompleteSuggestions:su,debounce:200,check:jr},e),n;return r=>o=>i=>{var g;let{input:s}=r.getState(),a=o(i),l=r.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:c,showTabCompletion:u}=l.settings,f=(g=l.conversation.current)==null?void 0:g.id,d=i.type===gm.toString();if(!f||!c&&!u)return a;let{input:p}=l;return rz(p,s)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let v=Ni(l);v===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(v))},d?0:t.debounce)),a}};var $A=Es.fulfilled.toString();function oz(e,t){let n=new Set([...t.keywordMatches.map(o=>o.keyword)]),r=[];return n.forEach(o=>{let i=e.keywordMatches.filter(l=>l.keyword===o),s=t.keywordMatches.filter(l=>l.keyword===o),a=s.length-i.length;a<=0||r.push(...s.slice(0,a))}),r}var jA=e=>t=>n=>r=>{var c;if(r.type!==$A){n(r);return}let o=t.getState().styleSuggestions.list;n(r);let i=t.getState(),s=i.styleSuggestions.list,a=(c=i.conversation)==null?void 0:c.current;if(o===s)return;let l=oz(o,s);r.type===$A&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var iz=Yu({assistants:IE,auth:mb,conversation:xb,contentTypes:yP,passwordlessToken:oA,entities:jP,handlingTime:BA,info:Vb,input:Mb,settings:_E,profile:bP,search:qb,styleSuggestions:PI,ui:hI,textSuggestions:tI});function KA(e){return tb({reducer:iz,middleware:t=>{var r;let n=t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI}},serializableCheck:!1}).concat(UA()).concat(WA({debounce:200})).concat(VA({debounce:500})).concat(jA(e.deepdeskAPI));return((r=e.middleware)!=null?r:[]).reduce((o,i)=>o.concat(i),n)},preloadedState:e.preloadedState})}function GA(e,t,n){if(t==="")return null;let r=new RegExp(`\\b${Im(t)}\\b`,"gi"),o,i=null;for(;(o=r.exec(e))!==null&&!(o.index>n);)i={start:o.index,end:o.index+o[0].length};return i}var sz=e=>{var t,n;return(n=(t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())!=null?n:"unknown"},az=e=>t=>n=>r=>{var l,c,u,f,d,p;let o=t.getState(),i=Ui("inlineSuggestions")(o),s=Ui("autoSelectSuggestion")(o)||i;switch(r.type){case Ws.toString():{!r.payload&&e.emit("logout",void 0);break}case gd.fulfilled.toString():{e.emit("logout",void 0);break}case vr.fulfilled.toString():r.payload.length>0&&e.sendEvent("entities found",{conversationId:(l=o.conversation.current)==null?void 0:l.id,data:{entities:r.payload}});break;case Di.toString():e.logSendMessage(r.payload);break;case Gd.toString():e.emit("call-to-action",{cue:r.payload});break;case mn.fulfilled.toString():if(!r.isBroadcasted){let{externalConversationId:m,currentExternalIdAtRequest:g}=(c=r.payload)!=null?c:{};(!m||!g||m===g)&&e.broadcast(uh,r,!1)}break;case mn.rejected.toString():break;default:break}let a=n(r);switch(r.type){case Di.toString():e.handleAfterSendMessage(r.payload);break;case lu.toString():e.onUpdateShowTabHint(r.payload);break;case jm.toString():e.logHandlingTime();break;case Ks.toString():e.broadcast(Pd,r);break;case Li.toString():e.broadcast(Pd,r);break;case qd.toString():t.dispatch(Li({source:"assistant",assistantCode:r.payload.code}));break;case"analytics/logEvent/fulfilled":{let m=o.assistants.cues.find(g=>g.code===r.meta.arg.data.assistantCode);e.emit("event",A(E({},r.meta.arg),{cue:m}));break}case kn.toString():{let{start:m,end:g}=o.input.selection;e.emit("select-suggestion",A(E({type:sz(r.payload.suggestion)},r.payload),{replace:r.payload.replace==="selection"?{start:m,end:g}:{start:0,end:g}})),i&&t.dispatch(Ho([]));break}case RI.toString():{let{keyword:m,suggestion:g,eventMetrics:v}=r.payload,{text:h,selection:y}=o.input,S=GA(h,m,(u=y==null?void 0:y.end)!=null?u:h.length);if(!S)break;e.emit("select-suggestion",{text:g,type:"style",replace:S,suggestion:{text:g,source:"style"},eventMetrics:v});break}case wd.toString():e.emit("select-image",r.payload),e.sendEvent("Image attached",{conversationId:(f=o.conversation.current)==null?void 0:f.id,data:{path:r.payload.suggestion.image,title:r.payload.suggestion.title}});break;case Ho.toString():{s&&r.payload.length>0&&t.dispatch(bd(0));break}case mn.fulfilled.toString():{let{evaluationId:m,output:g,externalConversationId:v}=r.payload,h=r.meta.arg.assistantCode;if(e.emit("event",{name:"Assistant evaluation completed",data:{evaluationId:m,assistantCode:h,assistantOutput:CE(g),externalConversationId:v,evaluationStatus:"success"}}),!r.meta.arg.skipState){let y=t.getState().assistants.cues;e.emit("cues",y)}break}case mn.rejected.toString():{let m=r.meta.arg.assistantCode,g=(p=r.meta.arg.externalConversationId)!=null?p:(d=t.getState().conversation.current)==null?void 0:d.externalId;e.emit("event",{name:"Assistant evaluation completed",data:{evaluationId:"",assistantCode:m,assistantOutput:"",externalConversationId:g,evaluationStatus:"failed"}});break}default:break}return a},qA=az;function jS(e){return e.toISOString().replace("T"," ").replace("Z","")}var lz=(e,t)=>t.version,YA=fn([Gs,Pr,DA,lz],(e,t,n,r)=>{if(!t)return te.warn("No conversationId for handling time metrics"),null;let{startTime:o,stopTime:i}=n;return!o||!i?(te.warn("No startTime and stopTime for handling time metrics"),null):{conversationId:t,clientVersion:r,agentId:e==null?void 0:e.agentId,agentName:e==null?void 0:e.agentName,agentEmail:e==null?void 0:e.agentEmail,timeStart:jS(o),timeStop:jS(i)}});function XA(e,t){let{text:n,metrics:{numPaste:r,pastes:o,textSuggestions:i}}=e.input,s=n.length;return{source:"agent",clientVersion:t.version,pastes:o,lenTextTotal:s,numPastes:r,suggestions:i}}var xu=class extends Error{};function cz(){let e,t;return{promise:new Promise((r,o)=>{e=r,t=o}),resolve:e,reject:t}}var Km=class{constructor(){this.queues={}}push(t,n){let r=()=>{let i=this.queues[t][1];i?(this.queues[t]=[i.promise,null],i.resolve()):delete this.queues[t]};if(!this.queues[t]){let i=n().finally(r);return this.queues[t]=[i,null],i}this.queues[t][1]&&this.queues[t][1].reject(new xu("Queued async function is outdated"));let o=cz();return this.queues[t][1]=o,o.promise.then(()=>n().finally(r))}};function KS(e,t){var i;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return KS(r,t);let o=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;return o?KS(o,t):null}function GS(e,t){return KS(e,t)}var uz={accepted:"onConversationAcceptedAssistants","new-message":"onConversationNewMessageAssistants",ended:"onConversationEndedAssistants"},QA=(e,t)=>{var o,i,s;if(!((s=(i=(o=e.uiConfig)==null?void 0:o.widget)==null?void 0:i.types.find(a=>a.type==="cues"))==null?void 0:s.isActive))return te.warn("Triggered a conversation assistant, but cues are not configured in widget."),[];let r=e[uz[t]];return r&&r.length>0?r.map(a=>a.code):(te.warn(`No assistant set in profile for conversation event "${t}"`),[])};function ZA(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function dz(e){return typeof e=="object"&&e!==null&&"tagName"in e}function Gm(e){return dz(e)&&(Ts(e)||Rm(e))}var e_,qr=new Map,fz=["bottom","height","left","right","top","width"],JA=(e,t)=>!e&&!t?!1:e&&!t||!e&&t?!0:fz.some(n=>e[n]!==t[n]);function t_(e){var n,r,o;if(e.ownerDocument===document)return[];let t=(o=(r=(n=e.ownerDocument)==null?void 0:n.defaultView)==null?void 0:r.frameElement)!=null?o:null;return t?[t,...t_(t)]:[]}function n_(e,t){return!e||!t?null:A(E({},e),{top:e.top+t.top,left:e.left+t.left})}var qm=!1,r_=()=>{qm=!0;let e=[];if(qr.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),qr.delete(n);return}let r=n.getBoundingClientRect();JA(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{let n=t.parentRects?t.parentRects.reduce(n_,t.rect):t.rect;JA(n,t.totalRect)&&t.callbacks.forEach(r=>r(n)),t.totalRect=n}),qr.size===0){qm=!1;return}e_=window.requestAnimationFrame(r_)};function qS(e,t){let n=t_(e),r=[],o=n.map((i,s)=>qS(i,a=>{r[s]=a;let l=qr.get(e);if(!l)return;let c=r.reduce(n_,l.rect);l.callbacks.forEach(u=>u(c))}));return{observe(i=!0){if(o.forEach(s=>s.observe(!1)),qr.has(e)){let s=qr.get(e);s.callbacks.push(t),s.rect&&t(s.rect)}else qr.set(e,{rect:void 0,callbacks:[t],parentRects:r});i&&!qm&&r_()},unobserve(){o.forEach(s=>s.unobserve());let i=qr.get(e);if(i){let s=i.callbacks.indexOf(t);s>=0&&i.callbacks.splice(s,1),i.callbacks.length||qr.delete(e),qr.size||(cancelAnimationFrame(e_),qm=!1)}}}}var o_,Yr=new Map,i_=()=>{Yr.forEach((e,t)=>{if(!t.isConnected){Yr.delete(t);return}let{clientHeight:n,scrollHeight:r}=t,o=r>n;e.visible!==o&&(e.visible=o,e.callbacks.forEach(i=>i(e.visible)))}),Yr.size!==0&&(o_=window.requestAnimationFrame(i_))};function s_(e,t){return{observe(){let n=Yr.size===0;Yr.has(e)?Yr.get(e).callbacks.push(t):Yr.set(e,{visible:void 0,callbacks:[t]}),n&&i_()},unobserve(){let n=Yr.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||Yr.delete(e),Yr.size||cancelAnimationFrame(o_)}}}}var YS=["borderLeftWidth","borderRightWidth","borderTopWidth","borderBottomWidth","borderStyle","boxSizing","color","overflowWrap","fontFamily","fontSize","fontSizeAdjust","fontStretch","fontWeight","fontKerning","lineHeight","letterSpacing","paddingLeft","paddingTop","paddingRight","paddingBottom","width","height","textIndent","whiteSpace","wordBreak","wordSpacing","wordWrap"];function XS(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function rl(e){return Number.parseFloat(e)}function Ym(e){return Math.round(e*1e6)}function a_(e){return e/1e6}function QS(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=rl(e.width),i=rl(e.borderLeftWidth),s=rl(e.borderRightWidth),a=rl(e.paddingRight),l=a_(Ym(o)-Ym(i)-Ym(s)),c=a_(Ym(r));if(l-c>2){let u=l-c;n.style.paddingRight=`${a+u}px`}}function wu(e,t={}){var u,f;let n=t.overlayContainer||document.createElement("div");n.style.display="none",n.style.position=(u=t.position)!=null?u:"fixed",n.style.pointerEvents="none",n.style.borderColor="transparent",os(n);let r=window.getComputedStyle(e),o=!0,i=()=>{n.scrollTop=e.scrollTop};XS(r,n,YS),QS(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",i));let s=s_(e,()=>{XS(r,n,YS),QS(r,e,n),i(),setTimeout(i,0)}),a,l=!0,c=qS(e,d=>{if(d===null){t.onRemove&&t.onRemove(),n.remove();return}if(!l&&t.onMoveStart&&(Promise.resolve().then(()=>t.onMoveStart()),l=!0),clearTimeout(a),a=setTimeout(()=>{t.onMoveEnd&&t.onMoveEnd(),l=!1},200),d.height===0&&d.width===0){if(o===!0)return;t.onHide&&t.onHide(),n.style.display="none",o=!0;return}if(XS(r,n,YS),QS(r,e,n),i(),t.placement==="below"&&n.classList.add("below"),n.style.top=`${d.top}px`,n.style.left=`${d.left}px`,t.closestScrollElement&&t.closestScrollElement!==e){let p=t.closestScrollElement.getBoundingClientRect(),m=window.getComputedStyle(t.closestScrollElement),g=rl(m.borderTopWidth),v=rl(m.borderBottomWidth),h=p.top+g-d.top,y=d.top+d.height+-(p.top+p.height-v);n.style.clipPath=`inset(${h}px 0px ${y}px 0px)`}o&&(n.style.display="block",t.onShow&&t.onShow(),o=!1)});return t.appendTo?t.appendTo.appendChild(n):(f=e.parentElement)==null||f.appendChild(n),c.observe(),s.observe(),[n,()=>{e.removeEventListener("scroll",i),c.unobserve(),s.unobserve(),n.remove()}]}function pz(e){return e.offsetParent!==null}function l_(e){if(!pz(e))return!1;let t=e.getBoundingClientRect();return t.top>=0&&t.left>=0&&t.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&t.right<=(window.innerWidth||document.documentElement.clientWidth)}function Xm(e,t,n=100){let r=l_(e);t({isVisible:r});let o=setInterval(()=>{let i=l_(e);i!==r&&(r=i,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var c_=(e,t)=>({value(){try{let n=sessionStorage.getItem(`dd-${e}`);if(!n)return t;try{return JSON.parse(n)}catch(r){return t}}catch(n){return t}},update(n){try{sessionStorage.setItem(`dd-${e}`,JSON.stringify(n))}catch(r){te.warn("[Deepdesk] SessionStorage is blocked by browser")}}});var ke=b(I());var u_=c_("showTabHint",!0),ol=class ol{constructor({deepdeskUrl:t,version:n=ol.version||"unknown",locale:r="en-US",token:o,fetch:i,productName:s,createCustomChannel:a,websocketClient:l=$m}){this.inputMediator=null;this.eventListeners={};this.unmountHandlers=[];this.disposeHandlers=[];this.inlineSuggestions=null;this.aboveSuggestions=null;this.belowSuggestions=null;this.floatingMenu=null;this.widgetElement=null;this.widgetRoot=null;this.nicknameDialogUnsubscribe=null;this.nicknameDialogFailed=!1;this.dynamicThunkObject={};this.queues=new Km;this.isMounted=!1;this.shouldRender=!0;this.loadProfileConfigPromise=null;let c=t.replace(/\/api$/,"");this.deepdeskApi=new Mo(c,{token:o,fetch:i}),this.version=n,this.instanceId=ol.count++;let u={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[qA({broadcast:(m,g,v)=>{this.broadcastEvents.send(m,g,v)},emit:(m,g)=>this.emit(m,g),handleAfterSendMessage:m=>this.handleAfterSendMessage(m),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:m=>this.logSendMessage(m),onUpdateShowTabHint:m=>u_.update(m),sendEvent:(m,g)=>this.deepdeskApi.sendEvent(m,g)})]};this.store=KA(u),this.broadcastEvents=new NA({debug:!0,deepdeskUrl:c,eventMap:Yb(this.store),createCustomChannel:a}),this.disposeHandlers.push(()=>{this.broadcastEvents.cleanup()}),this.ws=new l({url:`${c}/api/v2/me/realtime`.replace("https","wss"),reconnectInterval:25e3,shouldReconnect:()=>M(this,null,function*(){var m;return(m=Pt(this.state))!=null?m:!1})}),this.whenLoggedIn(()=>this.ws.connect()),this.store.dispatch(lu(u_.value())),this.store.dispatch(Yd({locale:r,adminUrl:c,productName:s}));let f=[],d=m=>{if(!m.conversationId)return;let g=()=>{this.conversationId()===m.conversationId&&this.store.dispatch(PE(m))};this.hasConversation()?g():f.push(g)};this.ws.on("assistants::direct_response",d),this.ws.on("assistants::user_notification",d),this.ws.on("assistants::response_chunk",m=>{if(!m.conversationId)return;let g=()=>{this.conversationId()===m.conversationId&&this.store.dispatch(RE(m))};this.hasConversation()?g():f.push(g)}),this.ws.on("assistants::suggest_as_reply",m=>{if(!m.conversationId)return;let g=()=>{this.conversationId()===m.conversationId&&this.store.dispatch(Ks([{text:m.payload.message,type:"text",source:"assistant",assistantCode:m.code,sourceLabel:m.name}]))};this.hasConversation()?g():f.push(g)});let p=this.whenConversationLoaded(()=>{var m;this.broadcastEvents.setExternalId((m=this.state.conversation.current)==null?void 0:m.externalId),f.forEach(g=>g()),f.length=0});this.disposeHandlers.push(()=>{this.ws.cleanup(),f.length=0,p()})}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){var t;return(t=Oi(this.state)[this.state.input.selectedSuggestionIndex])!=null?t:null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}externalId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.externalId}shouldAbort(){return this.state.conversation.isSupported===!1?(te.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(te.warn("Profile has not been loaded (yet)"),!0):(te.warn("No conversation loaded (yet)"),!0)}whenLoggedIn(t){if(Pt(this.state))t();else{let n=this.subscribe(Pt,r=>{r&&t()});this.disposeHandlers.push(()=>{n()})}}login(){return this.store.dispatch(Ws(null)),this.store.dispatch(Jr()),new Promise(t=>{this.whenLoggedIn(()=>t())})}isLoggedIn(){return M(this,null,function*(){return(yield this.store.dispatch(Jr())).payload})}isConversationSupported(t,n){return M(this,null,function*(){return(yield this.store.dispatch(rh({externalId:t,options:n}))).payload})}createConversation(t){return M(this,null,function*(){var r;return this.hasConversation()&&this.externalId()!==t.externalId&&this.resetConversation(),(yield this.store.dispatch(vd(A(E({},t),{metadata:(r=t.metadata)!=null?r:{}})))).payload})}getConversationByExternalId(t,n){return M(this,null,function*(){return this.hasConversation()&&this.externalId()!==t&&this.resetConversation(),(yield this.store.dispatch(Sd({externalId:t,options:n}))).payload})}upsertConversation(t){return M(this,null,function*(){var r;return this.hasConversation()&&this.externalId()!==t.externalId&&this.resetConversation(),(yield this.store.dispatch(oh(A(E({},t),{metadata:(r=t.metadata)!=null?r:{}})))).payload})}postMessages(t){return M(this,null,function*(){yield this.store.dispatch(ih(t))})}updateConversation(t){return M(this,null,function*(){return(yield this.store.dispatch(xd(t))).payload})}resetConversation(){this.store.dispatch(lt()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}configure(t){this.store.dispatch(Yd(t))}setVisitorInfo(t){this.store.dispatch(zb(t))}setCustomData(t){this.store.dispatch(Hb(t))}setAgentInfo(t,n){return M(this,null,function*(){var o;yield this.store.dispatch(wl(E(E({},t),n))),(o=this.state.info.agentInfo)!=null&&o.agentNickname||this.broadcastEvents.send(Rd,{showNicknameDialog:!0})})}setAgentSettings(t){return M(this,null,function*(){yield this.store.dispatch(ah(t))})}getAgentSettings(){return M(this,null,function*(){return(yield this.store.dispatch(lh())).payload})}refresh(){return M(this,null,function*(){if(this.shouldAbort())return Promise.resolve();let t=[];return t.push(this.refreshTextSuggestions()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})})}syncInputMediator(){this.inputMediator&&this.store.dispatch(Ed({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),suggestionTextStart:this.inputMediator.getSuggestionTextStart()}))}notifyExternalSuggestion(t){this.store.dispatch(kn(t))}evaluateAssistant(t,n){return M(this,null,function*(){var c;let{input:r={},transcript:o,showCuesInWidget:i=!0,includeMetadata:s,externalConversationId:a}=n||{},l=yield this.store.dispatch(mn({assistantCode:t,transcript:o,includeMetadata:s,input:r,externalConversationId:a,skipState:!i}));if(l.error)throw new Error(`Assistant evaluation failed: ${(c=l.payload)!=null?c:l.error.message}`);return l.payload.output})}evaluateConversationAssistant(t,n){return M(this,null,function*(){var u,f,p;yield this.loadProfileConfig();let r=this.state.profile.data;if(!r&&((u=this.state.conversation.current)!=null&&u.profileCode)&&(yield this.loadProfileConfig(),r=this.state.profile.data),!r){te.warn("Can't evaluate assistant when profile is not loaded yet.");return}let o=QA(r,t),i=(f=n==null?void 0:n.showCuesInWidget)!=null?f:!0,d=n!=null?n:{},{showCuesInWidget:s}=d,a=ie(d,["showCuesInWidget"]),l=(p=n==null?void 0:n.externalConversationId)!=null?p:this.hasConversation()?this.externalId():"",c=yield Promise.all(o.map(m=>this.queues.push(m,()=>M(this,null,function*(){var v,h;let g=yield this.store.dispatch(mn(A(E({assistantCode:m,includeMetadata:!0},a),{skipState:!i})));if(g.error)throw new Error(`Assistant evaluation failed: ${(v=g.payload)!=null?v:g.error.message}`);return{assistantCode:m,evaluationId:g.payload.evaluationId,output:g.payload.output,externalConversationId:(h=g.payload.externalConversationId)!=null?h:l}})).catch(g=>{if(g instanceof xu)return te.warn(`Queued assistant "${m}" was outdated and dropped`),null;throw g})));if(!i)return c.filter(m=>m!==null)})}handleKeyDown(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui,{textSuggestions:o,selectedSuggestionIndex:i,selection:s}=this.state.input,{inlineSuggestions:a,autoSelectSuggestion:l,showTextSuggestions:c,suggestionsPlacement:u}=this.settings,f=a||l,d=u==="inline"||u==="below"?"below":"above",p=o.length>0;if(this.store.dispatch(Tb(sh(t))),!jr(this.state)||t.key!=="Tab"&&!c)return;let m=()=>{n||!p||s&&(t.shiftKey||(this.store.dispatch(Pb()),t.preventDefault()))},g=()=>{n||!p||f&&i<=0||s&&(t.shiftKey||(this.store.dispatch(Ib()),t.preventDefault()))};switch(t.key){case"ArrowUp":d==="below"?g():m();break;case"ArrowDown":{d==="below"?m():g();break}case"Escape":{n||(this.store.dispatch(bd(-1)),this.store.dispatch(Si({collapse:!0})),this.store.dispatch(mI(!0)),t.preventDefault());break}case"Tab":{t.preventDefault();let v=js(this.state);if(!v)return;this.store.dispatch(lu(!1)),this.store.dispatch(kn({text:v.text,suggestion:v,eventMetrics:{inputType:"tab"},replace:"until-selection-end"}));break}case" ":{if(f||this.state.input.selectedSuggestionIndex===-1)return;let v=js(this.state);if(!v)return;this.store.dispatch(kn({text:v.text,suggestion:v,eventMetrics:{inputType:"space"},replace:"until-selection-end"}));break}case"Enter":{if(f||t.shiftKey||this.state.input.selectedSuggestionIndex===-1)return;let v=js(this.state);if(!v)return;this.store.dispatch(kn({text:v.text,suggestion:v,eventMetrics:{inputType:"enter"},replace:"until-selection-end"})),t.preventDefault();break}default:}n&&r&&this.store.dispatch(Si({collapse:!1}))}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(Ho([]))}handlingTimeStart(){this.state.handlingTime.startTime||(te.info("Start handling time"),this.store.dispatch(zA()))}handlingTimeStop(){this.state.handlingTime.startTime&&(te.info("Stop handling time"),this.store.dispatch(jm()))}logSendMessage(t){let n=XA(this.state,{version:this.version});n&&(t&&(Object.assign(n,{text:t}),Object.assign(n,{lenTextTotal:t.length})),this.deepdeskApi.sendEvent("Send Message",{conversationId:this.conversationId(),data:n}),this.emit("send-message-event",n))}logHandlingTime(){let t=YA(this.state,{version:this.version});t&&(this.deepdeskApi.sendEvent("Handling Time",{conversationId:this.conversationId(),data:t}),this.store.dispatch(HA()))}notifySubmit(t={}){var n;this.shouldAbort()||(this.store.dispatch(Di((n=t.text)!=null?n:this.state.input.text)),this.store.dispatch(_b()))}emit(t,n){let r=this.eventListeners[t];r&&r.forEach(o=>{try{o(n)}catch(i){te.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),te.error(i)}})}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),()=>{this.off(t,n)}}off(t,n){if(!t&&!n){this.eventListeners={};return}let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}setConversationQuery(t){this.dynamicThunkObject.conversationQuery=t}setPlatformVariables(t){this.store.dispatch(Bb(t))}whenConversationLoaded(t){let n=i=>{var s;return(s=i.conversation.current)==null?void 0:s.id},r=()=>this.loadProfileConfig().then(()=>t());return n(this.state)&&r(),this.subscribe(n,i=>{i&&r()})}overlayContainerFactory(t,n,r,o){let[i,s]=wu(n,r);return i.setAttribute("translate","no"),i.dataset.testid=t,o&&i.classList.add(o),[i,s]}createInlineContainer(t,n){var a;let r=document.createElement("div");r.style.position="absolute",r.style.top="0px",r.style.left="0px",r.style.height="0px",r.style.width="0px";let o=document.createElement("div");o.style.display="none",o.style.position="absolute",o.style.height="0px",o.style.width="0px",o.style.backgroundColor="red",r.appendChild(o);let i=(a=t.ownerDocument.defaultView)==null?void 0:a.frameElement,s=i?i.ownerDocument.defaultView:null;if(i&&(s===window||(s==null?void 0:s.parent)===window)){let[l,c]=wu(i,{appendTo:document.body,onMoveStart:()=>{o.style.display="none"}});l.dataset.testid=n,l.style.zIndex="2",l.appendChild(r),this.unmountHandlers.push(()=>{c()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return os(o),o.dataset.testid=t,o.style.color=r.color,o.style.fontSize=r.fontSize,o.style.fontFamily=r.fontFamily,o.style.fontVariant=r.fontVariant,o.setAttribute("translate","no"),n.appendChild(o),o}storeMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(t,n),te.info(`Stored analytics for ${this.conversationId()}`)}catch(t){}}restoreMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=window.sessionStorage.getItem(t);if(!n)return;let r=JSON.parse(n);r.text.trim()===this.state.input.text.trim()?(te.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(Ab(r.metrics))):te.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(t)}catch(t){}}mount(t,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!Gm(t))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let d=n,{customStyles:r,closestScrollSelector:o,floatingMenuParent:i,appendOverlayTo:s,inputMediator:a}=d,l=ie(d,["customStyles","closestScrollSelector","floatingMenuParent","appendOverlayTo","inputMediator"]),c={customStyles:r,closestScrollSelector:o,floatingMenuParent:i,appendOverlayTo:s};this.configure(l),this.settings.automaticHandlingTime&&this.setupHandlingTime(t),os(t),this.inputMediator=a||(Ts(t)?new Ps(t):new Rs(t)),this.inputMediator.on("change",({plainText:p,rawHTML:m,suggestionTextStart:g})=>{this.store.dispatch(Ed({text:p,html:m,suggestionTextStart:g}))}),this.inputMediator.on("keyup",p=>{this.store.dispatch(kb(sh(p)))}),this.inputMediator.on("keydown",p=>{this.handleKeyDown(p)}),this.inputMediator.on("paste",({pastedText:p,selectionText:m})=>{this.store.dispatch(Rb({text:p,selectionText:m}))}),this.inputMediator.on("cut",({selectionText:p})=>{this.store.dispatch(Cb(p))});let u;this.inputMediator.on("selection",p=>{clearTimeout(u),p===null?u=setTimeout(()=>{p!==null&&this.store.dispatch(Cd(p))},500):this.store.dispatch(Cd(p))}),this.unmountHandlers.push(()=>{clearTimeout(u)}),this.inputMediator.on("disabled",()=>{var p;(p=this.inputMediator)==null||p.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{this.settings.detectSubmit&&this.notifySubmit()}),this.inputMediator.on("blur",()=>{this.store.dispatch(vm(!1))}),this.inputMediator.on("focus",()=>{this.store.dispatch(vm(!0))}),this.renderSuggestions(t,c),this.subscribe(Ui("inlineSuggestions"),()=>{this.renderSuggestions(t,c)}),this.subscribe(Ui("suggestionsPlacement"),()=>{this.renderSuggestions(t,c)});let f=this.renderOverlays(n);this.unmountHandlers.push(()=>{f.unmount()}),this.store.dispatch(Ed({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),suggestionTextStart:this.inputMediator.getSuggestionTextStart()})),this.store.dispatch(Cd(this.inputMediator.getSelection())),this.store.dispatch(vm(this.inputMediator.isFocused)),this.unmountHandlers.push(()=>{this.state.input.text!==""&&this.storeMetrics()}),this.whenConversationLoaded(()=>{this.restoreMetrics(),this.syncInputMediator(),this.refreshTextSuggestions(),this.promptForNickname()}),this.isMounted=!0}promptForNickname(t){if(this.nicknameDialogUnsubscribe||this.nicknameDialogFailed)return;let n=this.createContainer("nickname-dialog",document.body);document.body.appendChild(n);let r=(0,No.createRoot)(n),o=null,i=a=>{o=a,s()},s=()=>{r==null||r.render((0,ke.jsx)(ko,{store:this.store,children:(0,ke.jsx)(to,{broadcastEvents:this.broadcastEvents,children:(0,ke.jsx)(_I,{id:"deepdesk-nickname-dialog",error:o,onSave:a=>M(this,null,function*(){try{yield this.store.dispatch(Db({agentNickname:a})).unwrap(),console.log("setAgentNickname",a),this.broadcastEvents.send(Rd,{showNicknameDialog:!1}),this.nicknameDialogUnsubscribe&&this.nicknameDialogUnsubscribe()}catch(l){te.error("Error setting agent nickname",l),i("error"),this.nicknameDialogFailed=!0}})})})}))};s(),this.nicknameDialogUnsubscribe=()=>{r.unmount(),n.remove(),this.nicknameDialogUnsubscribe=null}}subscribe(t,n){let r=t(this.store.getState());return this.store.subscribe(()=>{let o=t(this.store.getState());o!==r&&(r=o,n(r))})}unmount(){var t,n,r,o,i;(t=this.inlineSuggestions)==null||t.unmount(),(n=this.aboveSuggestions)==null||n.unmount(),(r=this.belowSuggestions)==null||r.unmount(),(o=this.floatingMenu)==null||o.unmount(),this.unmountHandlers.forEach(s=>s()),this.unmountHandlers=[],(i=this.inputMediator)==null||i.dispose(),this.nicknameDialogUnsubscribe&&this.nicknameDialogUnsubscribe(),this.isMounted=!1}dispose(){this.unmount(),this.unmountWidget(),this.disposeHandlers.forEach(t=>t()),this.disposeHandlers=[],this.off()}renderSuggestions(t,n){var r,o,i,s;(r=this.floatingMenu)==null||r.unmount(),(o=this.inlineSuggestions)==null||o.unmount(),(i=this.aboveSuggestions)==null||i.unmount(),(s=this.belowSuggestions)==null||s.unmount(),this.settings.floatingMenu&&(this.floatingMenu=this.renderFloatingMenu(t,n)),this.settings.inlineSuggestions||this.settings.suggestionsPlacement==="inline"?this.inlineSuggestions=this.renderInlineSuggestions(t,n):this.settings.suggestionsPlacement==="below"?this.belowSuggestions=this.renderAboveOrBelowSuggestions(t,n,"below"):this.aboveSuggestions=this.renderAboveOrBelowSuggestions(t,n,"above")}renderInlineSuggestions(t,n){let{customStyles:r}=n,o=this.createInlineContainer(t,"deepdesk-caret"),i=(0,No.createRoot)(o);i.render((0,ke.jsx)(ko,{store:this.store,customStyles:r,children:(0,ke.jsx)(to,{broadcastEvents:this.broadcastEvents,children:(0,ke.jsx)(II,{})})}));let s=a=>{a?(o.style.display="block",o.style.top=`${a.top}px`,o.style.left=`${a.left}px`):o.style.display="none"};return this.inputMediator.on("caretposition",s),{unmount:()=>{var a;(a=this.inputMediator)==null||a.off("caretposition",s),i.unmount(),o.remove()}}}renderAboveOrBelowSuggestions(t,n,r){let{customStyles:o,closestScrollSelector:i,appendOverlayTo:s}=n,a=i&&GS(t,i)||void 0,[l,c]=this.overlayContainerFactory("deepdesk-tab-completion",a||t,{appendTo:s,closestScrollElement:a,mirrorOverflow:!0,onRemove:()=>this.unmount()},o==null?void 0:o.rootNode),[u,f]=this.overlayContainerFactory("deepdesk-suggestions-overlay",a||t,{appendTo:s,placement:r},o==null?void 0:o.suggestionsRootNode),d=(0,No.createRoot)(l);d.render((0,ke.jsx)(ko,{store:this.store,customStyles:o,children:(0,ke.jsx)(to,{broadcastEvents:this.broadcastEvents,children:(0,ke.jsx)(tA,{inputElement:t})})}));let p=(0,No.createRoot)(u);return p.render((0,ke.jsx)(ko,{store:this.store,customStyles:o,children:(0,ke.jsx)(to,{broadcastEvents:this.broadcastEvents,children:(0,ke.jsx)(BI,{onLogIn:()=>this.loginViaPopup().catch(m=>te.warn(m.message))})})})),{unmount(){d.unmount(),p.unmount(),c(),f()}}}renderFloatingMenu(t,n){let{customStyles:r,closestScrollSelector:o,appendOverlayTo:i,floatingMenuParent:s}=n,a=o&&GS(t,o)||void 0,[l,c]=this.overlayContainerFactory("floating-menu",a||t,{appendTo:s!=null?s:i},r==null?void 0:r.floatingMenuParent),u=(0,No.createRoot)(l);return u.render((0,ke.jsx)(ko,{store:this.store,customStyles:r,children:(0,ke.jsx)(to,{broadcastEvents:this.broadcastEvents,children:(0,ke.jsx)(fI,{onLogIn:()=>this.loginViaPopup().catch(f=>te.warn(f.message))})})})),{unmount(){u.unmount(),c()}}}renderOverlays(t){let{customStyles:n}=t,r=this.createContainer("deepdesk-overlays"),o=(0,No.createRoot)(r);return o.render((0,ke.jsx)(ko,{store:this.store,customStyles:n,children:(0,ke.jsx)(to,{broadcastEvents:this.broadcastEvents,children:(0,ke.jsx)(aI,{})})})),{unmount(){o.unmount(),r.remove()}}}renderWidget(t,n={}){if(this.widgetElement&&te.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,isEmbedded:i}=n;this.widgetElement=t,this.configure({showImages:o,isEmbedded:i}),this.widgetRoot=(0,No.createRoot)(t),this.widgetRoot.render((0,ke.jsx)(ko,{store:this.store,customStyles:r,children:(0,ke.jsx)(to,{broadcastEvents:this.broadcastEvents,children:(0,ke.jsx)(RA,{assistantOptions:n.assistantOptions,knowledgeAssistOptions:n.knowledgeAssist,onLogIn:()=>this.loginViaPopup().catch(s=>te.warn(s.message))})})}))}unmountWidget(){var t,n;(n=(t=this.widgetRoot)==null?void 0:t.unmount)==null||n.call(t),this.widgetRoot=null,this.widgetElement=null}renderKnowledgeAssistantWidget(t,n,r={}){let{customStyles:o,initialQuestion:i}=r,s=(0,No.createRoot)(n);return s.render((0,ke.jsx)(ko,{store:this.store,customStyles:o,children:(0,ke.jsx)(to,{broadcastEvents:this.broadcastEvents,children:(0,ke.jsx)(FS,{children:(0,ke.jsxs)(Yp,{assistantCode:t,initialQuestion:i,evaluateKnowledgeAssistFn:Hl,children:[(0,ke.jsx)(Hs,{children:(0,ke.jsx)(Qp,{title:r.title,emptyState:r.emptyState})}),(0,ke.jsx)(DS,{children:(0,ke.jsx)(Xp,{})})]})})})})),{unmount(){s.unmount()}}}setupHandlingTime(t){let n=Xm(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){ZA(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfig(){var t;return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(t=this.state.conversation.current)!=null&&t.profileCode?(this.loadProfileConfigPromise=Promise.resolve().then(()=>M(this,null,function*(){yield this.store.dispatch(Kc()).unwrap();let n=mi(this.state);n&&this.store.dispatch(Yd({showSearch:n.search,showImageSearch:n.imageSearch,showEntitiesCommand:n.entitiesCommand,showSummaryCommand:!!n.summarizerAssistantNew,showKnowledgeSearch:!!n.knowledgeAssistantNew||!!n.knowledgeAssistant,recommendTextSuggestions:n.recommendTextSuggestions}))})).finally(()=>{mi(this.state)||(this.loadProfileConfigPromise=null)}),this.loadProfileConfigPromise):Promise.resolve()}loginViaPopup(t){return M(this,null,function*(){return new Promise((n,r)=>{this.store.dispatch(hd());let o=new MessageChannel,i=o.port1,s=this.settings.adminUrl,a=new URL(t!=null&&t.url?t==null?void 0:t.url:`${s}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let l=!1,c=()=>{u&&!u.closed&&u.close(),window.removeEventListener("message",f),clearInterval(d)};i.onmessage=p=>M(this,null,function*(){var m,g;if((m=p.data)!=null&&m.jwt)try{yield this.deepdeskApi.exchangeTokenForAccessCookie((g=p.data)==null?void 0:g.jwt),yield this.isLoggedIn(),this.broadcastEvents.send(El),l=!0,o.port1.close(),n()}catch(v){console.error(v),r(v)}finally{l=!0,c()}});let u=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");u===null&&r(new Error("Popup blocked by browser"));let f=p=>M(this,null,function*(){var m;if(p.origin===a.origin)switch((m=p.data)==null?void 0:m.type){case"deepdesk-popup-request-origin":{try{let g=JSON.stringify({type:"deepdesk-popup-parent-origin"});u==null||u.postMessage(g,a.origin)}catch(g){te.error("Error posting message to popup",g),r(g)}break}case"deepdesk-popup-loaded":{try{let g=JSON.stringify({type:"deepdesk-popup-create-channel"});u==null||u.postMessage(g,a.origin,[o.port2])}catch(g){te.error("Error posting message to popup",g),r(g)}break}case"deepdesk-popup-error":{if(c(),p.data.message==="Platform account url mismatch"){let g=`Please contact your administrator: The platform account url (${p.data.targetOrigin}) is misconfigured as it differs from the origin of the page that opened the popup (${p.data.openerOrigin}).`;te.warn(g),this.store.dispatch(eh(g)),r(new Error(g))}if(p.data.message==="Timeout"){let g="Please contact your administrator: Popup timed out. Check if the account's platform url is configured correctly.";te.warn(g),this.store.dispatch(eh(g)),r(new Error(g))}r(new Error(p.data.message));break}}});window.addEventListener("message",f);let d=setInterval(()=>{u&&!u.closed||(c(),l||r(new Error("Popup closed by user")))},200);this.disposeHandlers.push(c)})})}translateMessages(t){return this.deepdeskApi.translateMessages(t)}refreshTextSuggestions(){return M(this,null,function*(){this.isMounted&&(yield this.store.dispatch(gm()))})}refreshWidgetSuggestions(){return M(this,null,function*(){if(!this.widgetRoot)return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=Gc(this.state);try{n.forEach(({type:r})=>{switch(r){case"entities":this.store.dispatch(vr());break;case"pinned-messages":case"sticky-messages":break;default:ju.includes(r)||this.store.dispatch(Sr(r))}})}catch(r){this.handleError(r)}})}};ol.version="19.3.2-beta.6",ol.count=0;var bu=ol;function mz(e){return M(this,null,function*(){var o,i,s;let n=yield((o=e.fetch)!=null?o:window.fetch)(e.url),r=yield n.blob();return new File([r],e.name,{type:(s=(i=e.mimeType)!=null?i:n.headers.get("Content-Type"))!=null?s:"image/jpeg"})})}function d_(e,t){return M(this,null,function*(){let n=yield mz(t),r=new Event("change",{bubbles:!0,cancelable:!0});try{Object.defineProperty(e,"files",{configurable:!0,get:()=>[n]}),e.dispatchEvent(r)}finally{Object.hasOwn(e,"files")&&delete e.files}})}function f_(e,t,n){return M(this,null,function*(){yield new Mo(e).authenticateWithKey(t,n)})}function p_(e){return e.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}function m_(r,o){return M(this,arguments,function*(e,t,n={}){var f,d;let{value:i}=e,{start:s,end:a}=(f=n.replace)!=null?f:{start:0,end:i.length},l=`${i.slice(0,s)}${t}${i.slice(a)}`,c=(d=n.selectionAfter)!=null?d:{start:s+t.length,end:s+t.length},u=()=>{if(n.setValue)return n.setValue(l);e.value=l};return Promise.resolve(u()).then(()=>{e.selectionStart=c.start,e.selectionEnd=c.end,e.blur(),e.focus()})})}function g_(r,o){return M(this,arguments,function*(e,t,n={}){let i=n.replace?Ti(e,n.replace.start,n.replace.end):tl(e),s,a=()=>{if(n.setRange)return n.setRange(i.cloneRange());i.deleteContents(),s=document.createElement("span"),i.insertNode(s),n.insertBRs!==!1?t.split(`
83
+ `);let m=d?r:0,g=p?Math.min(i,u.childNodes.length):u.childNodes.length;for(let v=m;v<g&&(c(u.childNodes[v]),a!==2);v++);break}default:break}p&&(a=2)}return c(e),l}var IA=(s=>(s.CUT="Cut",s.BACKSPACE="Backspace",s.DELETE="Delete",s.ERASEEOF="EraseEof",s.UNDO="Undo",s.CLEAR="Clear",s))(IA||{}),_o=class{constructor(t){this.element=t;this.isFocused=!1;this.isActive=!0;this.isDisposed=!1;this.eventListeners={};this.disposeHandlers=[];this.cachedText="";this.cachedSuggestionTextStart=0;this.cachedCaretPosition=null;this.cachedSelection={start:0,end:0};this.cachedHTML="";this.isSubmitting=!1;this.isPossibleClearInputAction=!1;this.cachedText=this.getText(),this.cachedSuggestionTextStart=this.getSuggestionTextStart(),this.cachedHTML=this.getHTML(),this.cachedSelection=this.getSelection(),this.listen()}addEventListener(t,n){let r=o=>{n(o)};this.element.addEventListener(t,r),this.disposeHandlers.push(()=>{this.element.removeEventListener(t,r)})}removeEventListener(t,n){this.element.removeEventListener(t,n)}handleInteraction(){let t=this.getText(),n=this.getHTML(),r=this.getSelection(),o=this.getSuggestionTextStart(),i=this.cachedCaretPosition===null;if(!this.isActive)return;t===""&&this.cachedText!==""&&!this.isPossibleClearInputAction&&this.emit("submit");let s=t!==this.cachedText,a=n!==null&&n!==this.cachedHTML,l=o!==this.cachedSuggestionTextStart;if((s||a||l)&&(s?(this.cachedText=t,this.cachedHTML=n):a&&(this.cachedHTML=n),this.cachedSuggestionTextStart=o,i=!0,this.emit("change",{plainText:t,rawHTML:n,suggestionTextStart:o})),(r.start!==this.cachedSelection.start||r.end!==this.cachedSelection.end)&&(this.cachedSelection=r,i=!0,this.emit("selection",r)),!i)return;let c=this.getCaretPosition();zo(c,this.cachedCaretPosition)||(this.cachedCaretPosition=c,this.emit("caretposition",c))}handleClick(){this.handleInteraction()}handleFocus(){let t=!this.isFocused;this.isFocused=!0,t&&this.emit("focus"),this.handleInteraction()}handleBlur(){this.isPossibleClearInputAction=!1;let t=this.isFocused;this.isFocused=!1,t&&this.emit("blur")}handleKeyDown(t){let{key:n,ctrlKey:r,metaKey:o}=t;this.isPossibleClearInputAction=Object.values(IA).includes(n)||n.toLowerCase()==="z"&&(r||o),this.emit("keydown",t)}handleKeyUp(t){this.handleInteraction(),this.emit("keyup",t)}handleCut(){this.isPossibleClearInputAction=!0,this.emit("cut",{selectionText:this.getSelectedText()})}handlePaste(t){var r,o;let n=((r=t.clipboardData)==null?void 0:r.getData("text"))||((o=t.clipboardData)==null?void 0:o.getData("text/plain"))||"";this.emit("paste",{pastedText:n,selectionText:this.getSelectedText()})}listen(){this.addEventListener("keydown",n=>this.handleKeyDown(n)),this.addEventListener("keyup",n=>this.handleKeyUp(n)),this.addEventListener("input",()=>this.handleInteraction()),this.addEventListener("change",()=>this.handleInteraction()),this.addEventListener("focus",()=>this.handleFocus()),this.addEventListener("blur",()=>this.handleBlur()),this.addEventListener("cut",()=>this.handleCut()),this.addEventListener("paste",n=>this.handlePaste(n)),this.addEventListener("click",()=>this.handleInteraction()),document.activeElement===this.element&&(this.isFocused=!0);let t=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});t.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{t.disconnect()})}getSuggestionTextStart(){return 0}focus(){this.element.focus()}emit(t,...n){this.isDisposed||this.eventListeners[t]&&this.eventListeners[t].forEach(r=>{r(...n)})}on(t,n){this.isDisposed||(this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n))}off(t,n){if(!this.eventListeners[t])return;let r=this.eventListeners[t].indexOf(n);r!==-1&&this.eventListeners[t].splice(r,1)}activate(){let t=this.isActive===!1;this.isActive=!0,t&&this.handleInteraction()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(t=>t()),this.eventListeners={},this.isDisposed=!0}};function AA(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var Rs=class extends _o{constructor(){super(...arguments);this.lastKnownSelection=null}getRootNode(){return this.element.getRootNode()}getText(){let n=new Range;return n.selectNodeContents(this.element),Su(this.element,n)}getHTML(){return this.element.innerHTML||""}getRange(){let n=this.getRootNode();if(n.activeElement!==this.element)return null;let r="getSelection"in n?n.getSelection():window.getSelection();if(!r)return null;let o=r.rangeCount>0?r.getRangeAt(0):null;if(!o)return null;let i=this.element.ownerDocument.createRange();return i.setStart(o==null?void 0:o.startContainer,o==null?void 0:o.startOffset),i.setEnd(o==null?void 0:o.endContainer,o==null?void 0:o.endOffset),!i||!this.element.contains(i.startContainer)||!this.element.contains(i.endContainer)?null:i}getCaretPosition(){let n=this.getRange();if(!n||!n.collapsed||!("getBoundingClientRect"in n))return null;let r=n.getBoundingClientRect();return!AA(r)&&(n.insertNode(this.element.ownerDocument.createTextNode("\u2060")),r=n.getBoundingClientRect(),n.deleteContents(),!AA(r))?null:{top:r.top+r.height,left:r.left}}getSelection(){let n=this.getRange();if(n)return vu(this.element,n);let r=this.lastKnownSelection;if(r&&PA(this.element,r.start,r.end))return r;let o=tl(this.element);return o.collapse(!1),vu(this.element,o)}getSelectedText(){let{start:n,end:r}=this.getSelection();return Su(this.element,Ti(this.element,n,r))}listen(){super.listen();let n=new MutationObserver(i=>{var s,a;i.length===2&&i[0].addedNodes.length===1&&((s=i[0].addedNodes[0])==null?void 0:s.textContent)==="\u2060"&&((a=i[1].removedNodes[0])==null?void 0:a.textContent)==="\u2060"||setTimeout(()=>{this.handleInteraction()},0)});n.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0}),this.disposeHandlers.push(()=>n.disconnect());let r=this.element.isContentEditable,o=new MutationObserver(()=>{this.element.isContentEditable!==r&&(r=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>o.disconnect())}};var Z6=["direction","boxSizing","width","height","overflowX","overflowY","borderTopWidth","borderRightWidth","borderBottomWidth","borderLeftWidth","borderStyle","paddingTop","paddingRight","paddingBottom","paddingLeft","fontStyle","fontVariant","fontWeight","fontStretch","fontSize","fontSizeAdjust","lineHeight","fontFamily","textAlign","textTransform","textIndent","textDecoration","letterSpacing","wordSpacing","tabSize"];function _A(e,t){let n="mozInnerScreenX"in window,r=document.createElement("div");r.id="input-textarea-caret-position-mirror-div";let o=r.style,i=window.getComputedStyle(e),s=e.ownerDocument.body;o.whiteSpace="pre-wrap",o.wordWrap="break-word",o.position="absolute",o.visibility="hidden",Z6.forEach(u=>{o[u]=i[u]}),n?e.scrollHeight>Number.parseInt(i.height)&&(o.overflowY="scroll"):o.overflow="hidden",r.textContent=e.value.substring(0,t);let a=document.createElement("span");a.textContent=e.value.substring(t)||".",r.appendChild(a),s.appendChild(r);let l=e.getBoundingClientRect(),c={top:l.top-e.scrollTop+a.offsetTop+Number.parseInt(i.borderTopWidth)+a.offsetHeight,left:l.left-e.scrollLeft+a.offsetLeft+Number.parseInt(i.borderLeftWidth)};return s.removeChild(r),c}var Ps=class extends _o{constructor(){super(...arguments);this.lastKnownSelection=null}getText(){return this.element.value}getHTML(){return null}getSelection(){let{selectionStart:n,selectionEnd:r}=this.element;return{start:n,end:r}}getSelectedText(){let n=this.getSelection();return n?this.getText().slice(n.start,n.end):""}getCaretPosition(){return _A(this.element,this.element.selectionEnd)}listen(){super.listen();let n=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var i;return(i=n==null?void 0:n.get)==null?void 0:i.call(this.element)},set:i=>{var s;(s=n==null?void 0:n.set)==null||s.call(this.element,i),this.handleInteraction()}}),this.addEventListener("scroll",()=>{this.emit("caretposition",this.getCaretPosition())});let r=this.element.disabled,o=new MutationObserver(()=>{this.element.disabled!==r&&(r=this.element.disabled,this.emit(r?"disabled":"enabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>o.disconnect())}};function MA(e,t,n){let r=`deepdesk-iframe-${e}`,o=document.getElementById(r);if(o)return o;let i=document.createElement("iframe"),s=new URL(t);return Object.entries(n).forEach(([a,l])=>{s.searchParams.append(a,l)}),i.style.position="absolute",i.style.left="-999em",i.style.width="0px",i.style.height="0px",i.tabIndex=-1,i.id=r,i.title=`iframe-${e}`,i.src=s.toString(),window.document.body.appendChild(i),i}function J6(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch(t){return e}}var zS=class{constructor(t){this.name=t;this.disposeHandlers=[];this.broadcastChannel=new BroadcastChannel(t)}onMessage(t){this.broadcastChannel.addEventListener("message",t),this.disposeHandlers.push(()=>{this.broadcastChannel.removeEventListener("message",t)})}postMessage(t){this.broadcastChannel.postMessage(JSON.stringify(t))}close(){this.disposeHandlers.forEach(t=>t()),this.broadcastChannel.close()}},HS=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.disposeHandlers=[];this.iframe=MA(t,`${this.targetOrigin}/sdk/proxy/proxy.html`,{channel:this.name,host:window.location.origin,debug:"1"}),document.body.appendChild(this.iframe)}onMessage(t){window.addEventListener("message",t),this.disposeHandlers.push(()=>{window.removeEventListener("message",t)})}postMessage(t){var n;(n=this.iframe.contentWindow)==null||n.postMessage(JSON.stringify(t),this.targetOrigin)}close(){var t;this.disposeHandlers.forEach(n=>n()),(t=this.iframe)==null||t.remove()}},BS=class{constructor(t){this.params=t;this.deepdeskUrl=t.deepdeskUrl,this.eventMap=t.eventMap,this.externalId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setExternalId(t){this.externalId!==t&&(this.cleanup(),te.info("Set externalId",t),this.externalId=t,this.channel=this.createChannel(t))}createChannel(t){let n=this.params.createCustomChannel?this.params.createCustomChannel(t):this.isCrossOrigin?new HS(t,this.deepdeskUrl,{debug:!0}):new zS(t),r=o=>{var s,a;if(o.origin!==this.deepdeskUrl)return;let i=J6(o.data);typeof i!="object"||i.type!=="event"||i.channel!==t||(te.info("Received broadcast event",this.externalId,o),(a=(s=this.eventMap)[i.name])==null||a.call(s,i.payload))};return n.onMessage(r),n}send(t,n,r){var s,a;te.info("Broadcast event",{externalId:this.externalId,name:t,payload:n});let o={type:"event",name:t,payload:n};r!==!1&&((a=(s=this.eventMap)[t])==null||a.call(s,n));let i=this.externalId==="deepdesk-general"?this.defaultChannel:this.channel;i==null||i.postMessage(A(E({},o),{channel:this.externalId}))}cleanup(t=!1){var n,r;(n=this.channel)==null||n.close(),this.channel=void 0,t&&((r=this.defaultChannel)==null||r.close(),this.defaultChannel=void 0)}},NA=BS;function ez(e){return e.replace(/(_\w)/g,t=>t[1].toUpperCase())}function Ve(e){return Array.isArray(e)?e.map(Ve):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>A(E({},t),{[ez(n)]:Ve(e[n])}),{}):e}function tz(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function ln(e){return Array.isArray(e)?e.map(ln):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>A(E({},t),{[tz(n)]:ln(e[n])}),{}):e}var nl=class extends Error{constructor(n,r){super(n);this.body=r;this.name="CustomError"}};var US=e=>new Promise(t=>{setTimeout(t,e)});var Is=class extends nl{constructor(){super(...arguments);this.name="ClientError"}},WS=class extends nl{constructor(){super(...arguments);this.name="ServerError"}},VS=new Map;function nz(e){return M(this,null,function*(){if(e.status===204)return e.text().catch(()=>{}),null;let t=e.headers.get("content-type");if(t!=null&&t.includes("application/json"))return e.json();let n=yield e.text();return n===""?null:(te.warn("Unexpected response body:",n.slice(0,20)),JSON.parse(n))})}var As=class{constructor(t="",n={}){this.baseUrl=t;this.options=n;this.latestRequestByUrl={};this.refreshingToken=null;this.lastFailedRefreshAt=null;this.failedRefreshCooldown=1e4;var r;this.fetch=(r=n.fetch)!=null?r:window.fetch.bind(window)}patchFetch(t){this.fetch=t(this.fetch)}setCsrfToken(t){this.csrfToken=t}request(t,n={}){return new Promise((r,o)=>{let i={isAborted:!1,reject:o},s=`${this.baseUrl}${t}`,a=this.fetch,l=n.method===void 0||n.method.toLowerCase()==="get",C=n,{useCache:c=!1,abortLatest:u=!1,attempts:f=1,retryDelay:d=500,refreshTokenOn401:p=!0,retryOnError:m=k=>k instanceof TypeError,retryOnResponse:g=k=>k.status>=500,version:v=null}=C,h=ie(C,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]);if(c){if(!l)throw new Error(`Can't use 'useCache' for ${n.method}`);if(VS.has(s)){r(VS.get(s));return}}let y=A(E({credentials:"include"},h),{headers:E({Accept:"application/json","Content-Type":"application/json"},h.headers)});!l&&this.csrfToken&&(y.headers=A(E({},y.headers),{"X-CSRFToken":this.csrfToken})),typeof v=="string"&&(y.headers=A(E({},y.headers),{"X-Deepdesk-API-Version":v}));let S=f,x=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[s]&&u&&(this.latestRequestByUrl[s].isAborted=!0,this.latestRequestByUrl[s].reject(new Error("Aborted"))),this.latestRequestByUrl[s]=i;let T=()=>M(this,null,function*(){return S--,a(s,y).then(k=>M(this,null,function*(){return g(k)&&!i.isAborted&&S>0?(yield US(d),T()):k.status===401&&p===!0&&x===!1?(x=!0,yield this.refreshToken(),T()):k})).catch(k=>M(this,null,function*(){if(m(k)&&!i.isAborted&&S>0)return yield US(d),T();throw k}))});T().then(k=>M(this,null,function*(){let R=yield nz(k);if(delete this.latestRequestByUrl[s],k.status>=500){o(new WS("Server Error",R));return}if(k.status===401){o(new Is("Unauthorized",R));return}if(k.status===403){o(new Is("Forbidden",R));return}if(k.status===404){o(new Is("Not Found",R));return}if(k.status>=400){o(new Is("Bad Request",R));return}c&&VS.set(s,R),r(R)})).catch(k=>{o(k)})})}validateToken(){return M(this,null,function*(){let t,n,r;try{({has_valid_access_token:t,is_logged_in:n,has_valid_refresh_token:r}=yield this.get("/apis/admin/session/validate/",{refreshTokenOn401:!1}))}catch(o){return!1}if(!t){if(!r)return!1;try{yield this.refreshToken();let{is_logged_in:o}=yield this.get("/apis/admin/session/validate/",{refreshTokenOn401:!1});return o}catch(o){return!1}}return n})}refreshToken(){let t=Date.now();return this.lastFailedRefreshAt&&t-this.lastFailedRefreshAt<this.failedRefreshCooldown?Promise.reject(new Is("Unauthorized","Failed to refresh token")):this.refreshingToken?this.refreshingToken:(this.refreshingToken=this.get("/apis/admin/session/refresh/",{refreshTokenOn401:!1}).catch(n=>{throw(n==null?void 0:n.message)==="Unauthorized"&&(this.lastFailedRefreshAt=Date.now()),n}).finally(()=>{this.refreshingToken=null}),this.refreshingToken)}get(t,n){return this.request(t,n)}post(t,n,r){return this.request(t,E({method:"POST",body:JSON.stringify(n)},r))}patch(t,n,r){return this.request(t,E({method:"PATCH",body:JSON.stringify(n)},r))}put(t,n,r){return this.request(t,E({method:"PUT",body:JSON.stringify(n)},r))}delete(t,n){return this.request(t,E({method:"DELETE"},n))}};var OA;(t=>{let e;(a=>(a.SUCCESS="success",a.FAILURE="failure",a.CONDITIONS_NOT_MET="conditions_not_met",a.MAX_RECURSION_LEVEL="max_recursion_level",a.NO_ACCESS_TO_ASSISTANT="no_access_to_assistant"))(e=t.EvaluationStatus||(t.EvaluationStatus={}))})(OA||(OA={}));function $S(e){return A(E({},Ve(e)),{metadata:e.metadata})}var _s=class _s{constructor(t,n={}){this.options=n;this.latestReceivedDeepdeskVersions={};this.shouldFetchCsrfToken=!0;this.client=new As(t,{fetch:n.fetch}),this.client.patchFetch(r=>(o,i)=>M(this,null,function*(){let s=yield r(o,i);return this.handleDeepdeskVersionHeaders(s),s}))}preflight(){return M(this,null,function*(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let t=yield this.getCsrfToken();this.client.setCsrfToken(t)}return this.options.token?(_s.exchangeTokenPromise||(_s.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),_s.exchangeTokenPromise):Promise.resolve()})}createConversation(t){return M(this,null,function*(){var r;yield this.preflight(),te.info(`Creating conversation for session ${t.externalId} and agent ${t.agentId}`);let n=yield this.client.post("/api/v2/conversations",A(E({chat_start_time:new Date().toISOString()},ln(t)),{metadata:(r=t.metadata)!=null?r:{}}));return $S(n)})}getMe(){return M(this,null,function*(){let t=yield this.client.get("/apis/admin/session/me/");return Ve(t)})}postIdentity(t){return M(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/me/identities/",ln(t))})}patchMe(t){return M(this,null,function*(){yield this.preflight();let n=yield this.client.patch("/apis/admin/session/me/",ln(t));return Ve(n)})}getProfile(t){return M(this,null,function*(){let n=yield this.client.get(`/apis/admin/profiles/${t}/`,{useCache:!0});return Ve(n)})}getKnowledgeAssistant(t){return M(this,null,function*(){let n=yield this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{useCache:!0});return Ve(n)})}getContentTypes(){return M(this,null,function*(){let t=yield this.client.get("/apis/admin/content-types/",{useCache:!0});return Ve(t)})}getAccount(){return M(this,null,function*(){let t=yield this.client.get("/apis/admin/account/",{useCache:!0});return Ve(t)})}getPlatformConfig(t){return M(this,null,function*(){let n=t!==void 0?`/platform/config/${t}/`:"/platform/config/",{config:r}=yield this.client.get(n,{useCache:!0});return Ve(r)})}checkUserExists(t){return M(this,null,function*(){let{exists:n}=yield this.client.get(`/apis/admin/users/exists?external_id=${t}`,{version:"v1"});return n})}getConversationByExternalId(r){return M(this,arguments,function*(t,n={}){yield this.preflight(),te.info(`Getting conversation for session ${t}`);let{attempts:o=1,retryDelay:i=1e3}=n,s=yield this.client.get(`/api/v2/conversations/by_external_id/${t}`,{attempts:o,retryDelay:i,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"});return te.info(`Successfully retrieved conversation ${s.id} for session ${t}`),$S(s)})}isConversationSupported(r){return M(this,arguments,function*(t,n={}){te.info(`Check if conversation for session ${t} is supported`);let{attempts:o=1,retryDelay:i=1e3}=n;return(yield this.client.get(`/api/v2/conversations/by_external_id/${t}/has_active_profile`,{attempts:o,retryDelay:i,retryOnResponse:a=>a.status===404||a.status>=500})).has_active_profile})}updateConversation(t,n){return M(this,null,function*(){var i;yield this.preflight();let r=ln(n);n.metadata&&(r.metadata=(i=n.metadata)!=null?i:{});let o=yield this.client.put(`/api/v2/conversations/${t}`,r);return $S(o)})}postMessages(t,n){return M(this,null,function*(){yield this.preflight(),yield this.client.post(`/api/v2/conversations/${t}/messages`,n.map(r=>A(E({},ln(r)),{metadata:r.metadata})))})}sendEvent(t,n){return M(this,null,function*(){yield this.preflight();let a=n,{data:r}=a,o=ie(a,["data"]),i=Object.entries(this.latestReceivedDeepdeskVersions).reduce((l,[c,u])=>A(E({},l),{[c]:u}),{}),s=["platform","agentId","agentName","agentEmail","conversationId"].reduce((l,c)=>(o[c]&&(l[c]=o[c]),l),{});return this.client.post("/api/v2/events",ln(A(E(E({},i),s),{data:r,name:t})),{version:"v2"})})}getEntities(t){return M(this,null,function*(){return yield this.preflight(),yield this.client.post("/api/v2/entities",{messages:t.filter(r=>r.text)})})}getTemporaryExchangeToken(){return M(this,null,function*(){return(yield this.client.get("/apis/admin/session/exchange-token/")).jwt})}exchangeTokenForAccessCookie(t){return M(this,null,function*(){return this.client.post("/apis/admin/session/jwt/",{jwt:t}).catch(n=>{throw te.warn(`Invalid token '${t}'`),n})})}authenticateWithKey(t,n){return M(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/api-key/",ln(n),{refreshTokenOn401:!1,headers:{apikey:t}})})}getTextSuggestions(o){return M(this,arguments,function*(t,n={},r){if(yield this.preflight(),r==="sticky-messages")throw new Error("Use getPinnedMessages instead");return(yield this.client.post(`/api/v2/conversations/${t}/recommend/${r}`,ln(n),{abortLatest:!0})).map(s=>A(E({},Ve(s)),{text:s.text||s.url||s.message,source:r,type:r})).filter((s,a,l)=>a===l.findIndex(c=>c.text===s.text))})}isLoggedIn(){return M(this,null,function*(){return yield this.preflight(),this.client.validateToken()})}getAutocompleteSuggestions(t,n){return M(this,null,function*(){return yield this.preflight(),(yield this.client.post(`/api/v2/conversations/${t}/autocomplete`,ln(n),{abortLatest:!0})).map(o=>({score:1,source:o.source,sourceText:o.source_text,text:o.label,trainingJobs:o.training_jobs,searchKeywords:o.search_keywords,type:o.source})).filter((o,i,s)=>i===s.findIndex(a=>a.text===o.text))})}getPinnedMessages(t){return M(this,null,function*(){let n=yield this.client.get(`/api/v2/profiles/${t}/pinned-messages`,{abortLatest:!0});return Ve(n).map(r=>A(E({},r),{text:r.message,source:"sticky-messages",type:"pinned-message"}))})}getStyleSuggestions(t){return M(this,null,function*(){let n=yield this.client.post("/api/v2/style-suggestions",ln(t),{abortLatest:!0,version:"v2"});return Ve(n)})}search(t){return M(this,null,function*(){let n=yield this.client.post(`/api/v2/profiles/${t.profile}/search`,ln(t));return Ve(n)})}loginWithPassword(t,n){return M(this,null,function*(){yield this.preflight();let r=yield this.client.post("/apis/admin/session/login/",{username:t,password:n},{refreshTokenOn401:!1});return Ve(r)})}logout(){return M(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/logout/",{},{refreshTokenOn401:!1})})}requestLoginByEmail(t){return M(this,null,function*(){yield this.preflight();let n=yield this.client.post("/apis/admin/session/passwordless/request/",{email:t});return Ve(n)})}requestPasswordlessToken(){return M(this,null,function*(){let t=yield this.client.get("/apis/admin/session/passwordless/request/");return Ve(t.token)})}getCsrfToken(){return M(this,null,function*(){let{token:t}=yield this.client.get("/apis/admin/session/csrf/");return t})}verifyLoginToken(t){return M(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/login/",{token:t});return Ve(n)})}evaluateAssistant(t,n){return M(this,null,function*(){var s;yield this.preflight();let r=new URLSearchParams;n!=null&&n.externalConversationId&&r.append("external_conversation_id",n.externalConversationId);let o=n!=null&&n.threadId?`/api/v2/assistants/${t}/threads/${n==null?void 0:n.threadId}/evaluate?${r.toString()}`:`/api/v2/assistants/${t}/evaluate?${r.toString()}`,i=yield this.client.post(o,{input:(s=n==null?void 0:n.input)!=null?s:{},conversation:n==null?void 0:n.transcript});return Ve(i)})}createAssistantThread(t){return M(this,null,function*(){yield this.preflight();let{assistantCode:n}=t,r=yield this.client.post(`/apis/admin/assistants/${n}/threads/`,{});return Ve(r)})}postMessageToAssistantThread(t){return M(this,null,function*(){yield this.preflight();let{assistantCode:n,threadId:r,message:o}=t,i=yield this.client.post(`/apis/admin/assistants/${n}/threads/${r}/messages/`,{content:o,role:"user"});return Ve(i)})}translateMessages(t){return M(this,null,function*(){yield this.preflight();let n=yield this.client.post("/api/v2/translate",ln(t));return Ve(n)})}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),i=o.match(tw);if(!n||!i)return;let s=i[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[s];a&&n&&a!==n&&te.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[s]=n})}};_s.exchangeTokenPromise=null;var Mo=_s;var $m=class{constructor(t){this.options=t;this.socket=null;this.maxReconnectAttempts=5;this.reconnectInterval=25e3;this.cleanupCallbacks=[];var n,r;this.socket,this.eventListeners=new Map,this.url=t.url,this.maxReconnectAttempts=(n=t.maxReconnectAttempts)!=null?n:this.maxReconnectAttempts,this.reconnectInterval=(r=t.reconnectInterval)!=null?r:this.reconnectInterval,this.shouldReconnect=t.shouldReconnect}connect(){let t=()=>this.cleanup();window.addEventListener("beforeunload",t),this.cleanupCallbacks.push(()=>window.removeEventListener("beforeunload",t)),this.reconnect()}setupListeners(){this.socket&&(this.socket.onmessage=t=>{var n;try{let r=Ve(JSON.parse(t.data));r.event&&this.eventListeners.has(r.event)&&((n=this.eventListeners.get(r.event))==null||n.forEach(o=>o(r.data)))}catch(r){console.error("Error parsing WebSocket message:",r)}},this.socket.onclose=t=>{console.log("WebSocket connection closed:",t),setTimeout(()=>{this.reconnect()},this.reconnectInterval)},this.socket.onerror=t=>{console.error("WebSocket error:",t)})}reconnect(){var t,n;if(this.maxReconnectAttempts<=0){console.error("Max reconnect attempts reached, closing WebSocket connection."),(t=this.socket)==null||t.close();return}if(!this.shouldReconnect()){console.error("Should not reconnect, closing WebSocket connection."),(n=this.socket)==null||n.close();return}this.socket&&(this.socket.onmessage=null,this.socket.onclose=null,this.socket.onerror=null,this.socket.close()),this.socket=new WebSocket(this.url),this.setupListeners(),this.maxReconnectAttempts--}send(t,n){if(!this.socket){console.error("WebSocket connection is not open.");return}this.socket.send(JSON.stringify({event:t,data:n}))}on(t,n){this.eventListeners.has(t)||this.eventListeners.set(t,[]);let r=this.eventListeners.get(t);r&&!r.includes(n)&&r.push(n)}close(){var t;(t=this.socket)==null||t.close()}cleanup(){this.close(),this.cleanupCallbacks.forEach(t=>t()),this.cleanupCallbacks=[]}};var LA={startTime:null,stopTime:null},DA=e=>e.handlingTime,FA=Re({name:"handlingTime",initialState:LA,reducers:{handlingTimeStart(e){if(e.startTime&&!e.stopTime)throw new Error("Timing already started");e.startTime=new Date,e.stopTime=null},handlingTimeStop(e){if(!e.startTime)throw new Error("Timing not started");e.stopTime=new Date},handlingTimeReset(e){e.startTime=null,e.stopTime=null}},extraReducers:e=>{e.addCase(lt,()=>LA)}}),{handlingTimeStart:zA,handlingTimeStop:jm,handlingTimeReset:HA}=FA.actions,BA=FA.reducer;var UA=(e={})=>{let t=E({onAuthError:Ws(!1)},e);return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var VA=(e={})=>{let t,n=!0,r=E({getStyleSuggestions:Es,debounce:500},e);return o=>i=>s=>{var p;let a=o.getState().input.text,l=i(s),c=o.getState();if(c.auth.isLoggedIn!==!0)return l;let{showStyleSuggestions:u}=c.settings;if(!((p=c.conversation.current)==null?void 0:p.id)||!u)return l;let{text:d}=c.input;return d===a&&!n||(clearTimeout(t),d==="")||(t=setTimeout(()=>{n=!1,o.dispatch(r.getStyleSuggestions({text:d}))},e.debounce)),l}};function rz(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end&&e.suggestionTextStart===t.suggestionTextStart}var WA=(e={})=>{let t=E({getTextSuggestions:Sr,getAutocompleteSuggestions:su,debounce:200,check:jr},e),n;return r=>o=>i=>{var g;let{input:s}=r.getState(),a=o(i),l=r.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:c,showTabCompletion:u}=l.settings,f=(g=l.conversation.current)==null?void 0:g.id,d=i.type===gm.toString();if(!f||!c&&!u)return a;let{input:p}=l;return rz(p,s)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let v=Ni(l);v===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(v))},d?0:t.debounce)),a}};var $A=Es.fulfilled.toString();function oz(e,t){let n=new Set([...t.keywordMatches.map(o=>o.keyword)]),r=[];return n.forEach(o=>{let i=e.keywordMatches.filter(l=>l.keyword===o),s=t.keywordMatches.filter(l=>l.keyword===o),a=s.length-i.length;a<=0||r.push(...s.slice(0,a))}),r}var jA=e=>t=>n=>r=>{var c;if(r.type!==$A){n(r);return}let o=t.getState().styleSuggestions.list;n(r);let i=t.getState(),s=i.styleSuggestions.list,a=(c=i.conversation)==null?void 0:c.current;if(o===s)return;let l=oz(o,s);r.type===$A&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var iz=Yu({assistants:IE,auth:mb,conversation:xb,contentTypes:yP,passwordlessToken:oA,entities:jP,handlingTime:BA,info:Vb,input:Mb,settings:_E,profile:bP,search:qb,styleSuggestions:PI,ui:hI,textSuggestions:tI});function KA(e){return tb({reducer:iz,middleware:t=>{var r;let n=t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI}},serializableCheck:!1}).concat(UA()).concat(WA({debounce:200})).concat(VA({debounce:500})).concat(jA(e.deepdeskAPI));return((r=e.middleware)!=null?r:[]).reduce((o,i)=>o.concat(i),n)},preloadedState:e.preloadedState})}function GA(e,t,n){if(t==="")return null;let r=new RegExp(`\\b${Im(t)}\\b`,"gi"),o,i=null;for(;(o=r.exec(e))!==null&&!(o.index>n);)i={start:o.index,end:o.index+o[0].length};return i}var sz=e=>{var t,n;return(n=(t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())!=null?n:"unknown"},az=e=>t=>n=>r=>{var l,c,u,f,d,p;let o=t.getState(),i=Ui("inlineSuggestions")(o),s=Ui("autoSelectSuggestion")(o)||i;switch(r.type){case Ws.toString():{!r.payload&&e.emit("logout",void 0);break}case gd.fulfilled.toString():{e.emit("logout",void 0);break}case vr.fulfilled.toString():r.payload.length>0&&e.sendEvent("entities found",{conversationId:(l=o.conversation.current)==null?void 0:l.id,data:{entities:r.payload}});break;case Di.toString():e.logSendMessage(r.payload);break;case Gd.toString():e.emit("call-to-action",{cue:r.payload});break;case mn.fulfilled.toString():if(!r.isBroadcasted){let{externalConversationId:m,currentExternalIdAtRequest:g}=(c=r.payload)!=null?c:{};(!m||!g||m===g)&&e.broadcast(uh,r,!1)}break;case mn.rejected.toString():break;default:break}let a=n(r);switch(r.type){case Di.toString():e.handleAfterSendMessage(r.payload);break;case lu.toString():e.onUpdateShowTabHint(r.payload);break;case jm.toString():e.logHandlingTime();break;case Ks.toString():e.broadcast(Pd,r);break;case Li.toString():e.broadcast(Pd,r);break;case qd.toString():t.dispatch(Li({source:"assistant",assistantCode:r.payload.code}));break;case"analytics/logEvent/fulfilled":{let m=o.assistants.cues.find(g=>g.code===r.meta.arg.data.assistantCode);e.emit("event",A(E({},r.meta.arg),{cue:m}));break}case kn.toString():{let{start:m,end:g}=o.input.selection;e.emit("select-suggestion",A(E({type:sz(r.payload.suggestion)},r.payload),{replace:r.payload.replace==="selection"?{start:m,end:g}:{start:0,end:g}})),i&&t.dispatch(Ho([]));break}case RI.toString():{let{keyword:m,suggestion:g,eventMetrics:v}=r.payload,{text:h,selection:y}=o.input,S=GA(h,m,(u=y==null?void 0:y.end)!=null?u:h.length);if(!S)break;e.emit("select-suggestion",{text:g,type:"style",replace:S,suggestion:{text:g,source:"style"},eventMetrics:v});break}case wd.toString():e.emit("select-image",r.payload),e.sendEvent("Image attached",{conversationId:(f=o.conversation.current)==null?void 0:f.id,data:{path:r.payload.suggestion.image,title:r.payload.suggestion.title}});break;case Ho.toString():{s&&r.payload.length>0&&t.dispatch(bd(0));break}case mn.fulfilled.toString():{let{evaluationId:m,output:g,externalConversationId:v}=r.payload,h=r.meta.arg.assistantCode;if(e.emit("event",{name:"Assistant evaluation completed",data:{evaluationId:m,assistantCode:h,assistantOutput:CE(g),externalConversationId:v,evaluationStatus:"success"}}),!r.meta.arg.skipState){let y=t.getState().assistants.cues;e.emit("cues",y)}break}case mn.rejected.toString():{let m=r.meta.arg.assistantCode,g=(p=r.meta.arg.externalConversationId)!=null?p:(d=t.getState().conversation.current)==null?void 0:d.externalId;e.emit("event",{name:"Assistant evaluation completed",data:{evaluationId:"",assistantCode:m,assistantOutput:"",externalConversationId:g,evaluationStatus:"failed"}});break}default:break}return a},qA=az;function jS(e){return e.toISOString().replace("T"," ").replace("Z","")}var lz=(e,t)=>t.version,YA=fn([Gs,Pr,DA,lz],(e,t,n,r)=>{if(!t)return te.warn("No conversationId for handling time metrics"),null;let{startTime:o,stopTime:i}=n;return!o||!i?(te.warn("No startTime and stopTime for handling time metrics"),null):{conversationId:t,clientVersion:r,agentId:e==null?void 0:e.agentId,agentName:e==null?void 0:e.agentName,agentEmail:e==null?void 0:e.agentEmail,timeStart:jS(o),timeStop:jS(i)}});function XA(e,t){let{text:n,metrics:{numPaste:r,pastes:o,textSuggestions:i}}=e.input,s=n.length;return{source:"agent",clientVersion:t.version,pastes:o,lenTextTotal:s,numPastes:r,suggestions:i}}var xu=class extends Error{};function cz(){let e,t;return{promise:new Promise((r,o)=>{e=r,t=o}),resolve:e,reject:t}}var Km=class{constructor(){this.queues={}}push(t,n){let r=()=>{let i=this.queues[t][1];i?(this.queues[t]=[i.promise,null],i.resolve()):delete this.queues[t]};if(!this.queues[t]){let i=n().finally(r);return this.queues[t]=[i,null],i}this.queues[t][1]&&this.queues[t][1].reject(new xu("Queued async function is outdated"));let o=cz();return this.queues[t][1]=o,o.promise.then(()=>n().finally(r))}};function KS(e,t){var i;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return KS(r,t);let o=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;return o?KS(o,t):null}function GS(e,t){return KS(e,t)}var uz={accepted:"onConversationAcceptedAssistants","new-message":"onConversationNewMessageAssistants",ended:"onConversationEndedAssistants"},QA=(e,t)=>{var o,i,s;if(!((s=(i=(o=e.uiConfig)==null?void 0:o.widget)==null?void 0:i.types.find(a=>a.type==="cues"))==null?void 0:s.isActive))return te.warn("Triggered a conversation assistant, but cues are not configured in widget."),[];let r=e[uz[t]];return r&&r.length>0?r.map(a=>a.code):(te.warn(`No assistant set in profile for conversation event "${t}"`),[])};function ZA(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function dz(e){return typeof e=="object"&&e!==null&&"tagName"in e}function Gm(e){return dz(e)&&(Ts(e)||Rm(e))}var e_,qr=new Map,fz=["bottom","height","left","right","top","width"],JA=(e,t)=>!e&&!t?!1:e&&!t||!e&&t?!0:fz.some(n=>e[n]!==t[n]);function t_(e){var n,r,o;if(e.ownerDocument===document)return[];let t=(o=(r=(n=e.ownerDocument)==null?void 0:n.defaultView)==null?void 0:r.frameElement)!=null?o:null;return t?[t,...t_(t)]:[]}function n_(e,t){return!e||!t?null:A(E({},e),{top:e.top+t.top,left:e.left+t.left})}var qm=!1,r_=()=>{qm=!0;let e=[];if(qr.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),qr.delete(n);return}let r=n.getBoundingClientRect();JA(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{let n=t.parentRects?t.parentRects.reduce(n_,t.rect):t.rect;JA(n,t.totalRect)&&t.callbacks.forEach(r=>r(n)),t.totalRect=n}),qr.size===0){qm=!1;return}e_=window.requestAnimationFrame(r_)};function qS(e,t){let n=t_(e),r=[],o=n.map((i,s)=>qS(i,a=>{r[s]=a;let l=qr.get(e);if(!l)return;let c=r.reduce(n_,l.rect);l.callbacks.forEach(u=>u(c))}));return{observe(i=!0){if(o.forEach(s=>s.observe(!1)),qr.has(e)){let s=qr.get(e);s.callbacks.push(t),s.rect&&t(s.rect)}else qr.set(e,{rect:void 0,callbacks:[t],parentRects:r});i&&!qm&&r_()},unobserve(){o.forEach(s=>s.unobserve());let i=qr.get(e);if(i){let s=i.callbacks.indexOf(t);s>=0&&i.callbacks.splice(s,1),i.callbacks.length||qr.delete(e),qr.size||(cancelAnimationFrame(e_),qm=!1)}}}}var o_,Yr=new Map,i_=()=>{Yr.forEach((e,t)=>{if(!t.isConnected){Yr.delete(t);return}let{clientHeight:n,scrollHeight:r}=t,o=r>n;e.visible!==o&&(e.visible=o,e.callbacks.forEach(i=>i(e.visible)))}),Yr.size!==0&&(o_=window.requestAnimationFrame(i_))};function s_(e,t){return{observe(){let n=Yr.size===0;Yr.has(e)?Yr.get(e).callbacks.push(t):Yr.set(e,{visible:void 0,callbacks:[t]}),n&&i_()},unobserve(){let n=Yr.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||Yr.delete(e),Yr.size||cancelAnimationFrame(o_)}}}}var YS=["borderLeftWidth","borderRightWidth","borderTopWidth","borderBottomWidth","borderStyle","boxSizing","color","overflowWrap","fontFamily","fontSize","fontSizeAdjust","fontStretch","fontWeight","fontKerning","lineHeight","letterSpacing","paddingLeft","paddingTop","paddingRight","paddingBottom","width","height","textIndent","whiteSpace","wordBreak","wordSpacing","wordWrap"];function XS(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function rl(e){return Number.parseFloat(e)}function Ym(e){return Math.round(e*1e6)}function a_(e){return e/1e6}function QS(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=rl(e.width),i=rl(e.borderLeftWidth),s=rl(e.borderRightWidth),a=rl(e.paddingRight),l=a_(Ym(o)-Ym(i)-Ym(s)),c=a_(Ym(r));if(l-c>2){let u=l-c;n.style.paddingRight=`${a+u}px`}}function wu(e,t={}){var u,f;let n=t.overlayContainer||document.createElement("div");n.style.display="none",n.style.position=(u=t.position)!=null?u:"fixed",n.style.pointerEvents="none",n.style.borderColor="transparent",os(n);let r=window.getComputedStyle(e),o=!0,i=()=>{n.scrollTop=e.scrollTop};XS(r,n,YS),QS(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",i));let s=s_(e,()=>{XS(r,n,YS),QS(r,e,n),i(),setTimeout(i,0)}),a,l=!0,c=qS(e,d=>{if(d===null){t.onRemove&&t.onRemove(),n.remove();return}if(!l&&t.onMoveStart&&(Promise.resolve().then(()=>t.onMoveStart()),l=!0),clearTimeout(a),a=setTimeout(()=>{t.onMoveEnd&&t.onMoveEnd(),l=!1},200),d.height===0&&d.width===0){if(o===!0)return;t.onHide&&t.onHide(),n.style.display="none",o=!0;return}if(XS(r,n,YS),QS(r,e,n),i(),t.placement==="below"&&n.classList.add("below"),n.style.top=`${d.top}px`,n.style.left=`${d.left}px`,t.closestScrollElement&&t.closestScrollElement!==e){let p=t.closestScrollElement.getBoundingClientRect(),m=window.getComputedStyle(t.closestScrollElement),g=rl(m.borderTopWidth),v=rl(m.borderBottomWidth),h=p.top+g-d.top,y=d.top+d.height+-(p.top+p.height-v);n.style.clipPath=`inset(${h}px 0px ${y}px 0px)`}o&&(n.style.display="block",t.onShow&&t.onShow(),o=!1)});return t.appendTo?t.appendTo.appendChild(n):(f=e.parentElement)==null||f.appendChild(n),c.observe(),s.observe(),[n,()=>{e.removeEventListener("scroll",i),c.unobserve(),s.unobserve(),n.remove()}]}function pz(e){return e.offsetParent!==null}function l_(e){if(!pz(e))return!1;let t=e.getBoundingClientRect();return t.top>=0&&t.left>=0&&t.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&t.right<=(window.innerWidth||document.documentElement.clientWidth)}function Xm(e,t,n=100){let r=l_(e);t({isVisible:r});let o=setInterval(()=>{let i=l_(e);i!==r&&(r=i,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var c_=(e,t)=>({value(){try{let n=sessionStorage.getItem(`dd-${e}`);if(!n)return t;try{return JSON.parse(n)}catch(r){return t}}catch(n){return t}},update(n){try{sessionStorage.setItem(`dd-${e}`,JSON.stringify(n))}catch(r){te.warn("[Deepdesk] SessionStorage is blocked by browser")}}});var ke=b(I());var u_=c_("showTabHint",!0),ol=class ol{constructor({deepdeskUrl:t,version:n=ol.version||"unknown",locale:r="en-US",token:o,fetch:i,productName:s,createCustomChannel:a,websocketClient:l=$m}){this.inputMediator=null;this.eventListeners={};this.unmountHandlers=[];this.disposeHandlers=[];this.inlineSuggestions=null;this.aboveSuggestions=null;this.belowSuggestions=null;this.floatingMenu=null;this.widgetElement=null;this.widgetRoot=null;this.nicknameDialogUnsubscribe=null;this.nicknameDialogFailed=!1;this.dynamicThunkObject={};this.queues=new Km;this.isMounted=!1;this.shouldRender=!0;this.loadProfileConfigPromise=null;let c=t.replace(/\/api$/,"");this.deepdeskApi=new Mo(c,{token:o,fetch:i}),this.version=n,this.instanceId=ol.count++;let u={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[qA({broadcast:(m,g,v)=>{this.broadcastEvents.send(m,g,v)},emit:(m,g)=>this.emit(m,g),handleAfterSendMessage:m=>this.handleAfterSendMessage(m),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:m=>this.logSendMessage(m),onUpdateShowTabHint:m=>u_.update(m),sendEvent:(m,g)=>this.deepdeskApi.sendEvent(m,g)})]};this.store=KA(u),this.broadcastEvents=new NA({debug:!0,deepdeskUrl:c,eventMap:Yb(this.store),createCustomChannel:a}),this.disposeHandlers.push(()=>{this.broadcastEvents.cleanup()}),this.ws=new l({url:`${c}/api/v2/me/realtime`.replace("https","wss"),reconnectInterval:25e3,shouldReconnect:()=>M(this,null,function*(){var m;return(m=Pt(this.state))!=null?m:!1})}),this.whenLoggedIn(()=>this.ws.connect()),this.store.dispatch(lu(u_.value())),this.store.dispatch(Yd({locale:r,adminUrl:c,productName:s}));let f=[],d=m=>{if(!m.conversationId)return;let g=()=>{this.conversationId()===m.conversationId&&this.store.dispatch(PE(m))};this.hasConversation()?g():f.push(g)};this.ws.on("assistants::direct_response",d),this.ws.on("assistants::user_notification",d),this.ws.on("assistants::response_chunk",m=>{if(!m.conversationId)return;let g=()=>{this.conversationId()===m.conversationId&&this.store.dispatch(RE(m))};this.hasConversation()?g():f.push(g)}),this.ws.on("assistants::suggest_as_reply",m=>{if(!m.conversationId)return;let g=()=>{this.conversationId()===m.conversationId&&this.store.dispatch(Ks([{text:m.payload.message,type:"text",source:"assistant",assistantCode:m.code,sourceLabel:m.name}]))};this.hasConversation()?g():f.push(g)});let p=this.whenConversationLoaded(()=>{var m;this.broadcastEvents.setExternalId((m=this.state.conversation.current)==null?void 0:m.externalId),f.forEach(g=>g()),f.length=0});this.disposeHandlers.push(()=>{this.ws.cleanup(),f.length=0,p()})}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){var t;return(t=Oi(this.state)[this.state.input.selectedSuggestionIndex])!=null?t:null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}externalId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.externalId}shouldAbort(){return this.state.conversation.isSupported===!1?(te.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(te.warn("Profile has not been loaded (yet)"),!0):(te.warn("No conversation loaded (yet)"),!0)}whenLoggedIn(t){if(Pt(this.state))t();else{let n=this.subscribe(Pt,r=>{r&&t()});this.disposeHandlers.push(()=>{n()})}}login(){return this.store.dispatch(Ws(null)),this.store.dispatch(Jr()),new Promise(t=>{this.whenLoggedIn(()=>t())})}isLoggedIn(){return M(this,null,function*(){return(yield this.store.dispatch(Jr())).payload})}isConversationSupported(t,n){return M(this,null,function*(){return(yield this.store.dispatch(rh({externalId:t,options:n}))).payload})}createConversation(t){return M(this,null,function*(){var r;return this.hasConversation()&&this.externalId()!==t.externalId&&this.resetConversation(),(yield this.store.dispatch(vd(A(E({},t),{metadata:(r=t.metadata)!=null?r:{}})))).payload})}getConversationByExternalId(t,n){return M(this,null,function*(){return this.hasConversation()&&this.externalId()!==t&&this.resetConversation(),(yield this.store.dispatch(Sd({externalId:t,options:n}))).payload})}upsertConversation(t){return M(this,null,function*(){var r;return this.hasConversation()&&this.externalId()!==t.externalId&&this.resetConversation(),(yield this.store.dispatch(oh(A(E({},t),{metadata:(r=t.metadata)!=null?r:{}})))).payload})}postMessages(t){return M(this,null,function*(){yield this.store.dispatch(ih(t))})}updateConversation(t){return M(this,null,function*(){return(yield this.store.dispatch(xd(t))).payload})}resetConversation(){this.store.dispatch(lt()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}configure(t){this.store.dispatch(Yd(t))}setVisitorInfo(t){this.store.dispatch(zb(t))}setCustomData(t){this.store.dispatch(Hb(t))}setAgentInfo(t,n){return M(this,null,function*(){var o;yield this.store.dispatch(wl(E(E({},t),n))),(o=this.state.info.agentInfo)!=null&&o.agentNickname||this.broadcastEvents.send(Rd,{showNicknameDialog:!0})})}setAgentSettings(t){return M(this,null,function*(){yield this.store.dispatch(ah(t))})}getAgentSettings(){return M(this,null,function*(){return(yield this.store.dispatch(lh())).payload})}refresh(){return M(this,null,function*(){if(this.shouldAbort())return Promise.resolve();let t=[];return t.push(this.refreshTextSuggestions()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})})}syncInputMediator(){this.inputMediator&&this.store.dispatch(Ed({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),suggestionTextStart:this.inputMediator.getSuggestionTextStart()}))}notifyExternalSuggestion(t){this.store.dispatch(kn(t))}evaluateAssistant(t,n){return M(this,null,function*(){var c;let{input:r={},transcript:o,showCuesInWidget:i=!0,includeMetadata:s,externalConversationId:a}=n||{},l=yield this.store.dispatch(mn({assistantCode:t,transcript:o,includeMetadata:s,input:r,externalConversationId:a,skipState:!i}));if(l.error)throw new Error(`Assistant evaluation failed: ${(c=l.payload)!=null?c:l.error.message}`);return l.payload.output})}evaluateConversationAssistant(t,n){return M(this,null,function*(){var u,f,p;yield this.loadProfileConfig();let r=this.state.profile.data;if(!r&&((u=this.state.conversation.current)!=null&&u.profileCode)&&(yield this.loadProfileConfig(),r=this.state.profile.data),!r){te.warn("Can't evaluate assistant when profile is not loaded yet.");return}let o=QA(r,t),i=(f=n==null?void 0:n.showCuesInWidget)!=null?f:!0,d=n!=null?n:{},{showCuesInWidget:s}=d,a=ie(d,["showCuesInWidget"]),l=(p=n==null?void 0:n.externalConversationId)!=null?p:this.hasConversation()?this.externalId():"",c=yield Promise.all(o.map(m=>this.queues.push(m,()=>M(this,null,function*(){var v,h;let g=yield this.store.dispatch(mn(A(E({assistantCode:m,includeMetadata:!0},a),{skipState:!i})));if(g.error)throw new Error(`Assistant evaluation failed: ${(v=g.payload)!=null?v:g.error.message}`);return{assistantCode:m,evaluationId:g.payload.evaluationId,output:g.payload.output,externalConversationId:(h=g.payload.externalConversationId)!=null?h:l}})).catch(g=>{if(g instanceof xu)return te.warn(`Queued assistant "${m}" was outdated and dropped`),null;throw g})));if(!i)return c.filter(m=>m!==null)})}handleKeyDown(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui,{textSuggestions:o,selectedSuggestionIndex:i,selection:s}=this.state.input,{inlineSuggestions:a,autoSelectSuggestion:l,showTextSuggestions:c,suggestionsPlacement:u}=this.settings,f=a||l,d=u==="inline"||u==="below"?"below":"above",p=o.length>0;if(this.store.dispatch(Tb(sh(t))),!jr(this.state)||t.key!=="Tab"&&!c)return;let m=()=>{n||!p||s&&(t.shiftKey||(this.store.dispatch(Pb()),t.preventDefault()))},g=()=>{n||!p||f&&i<=0||s&&(t.shiftKey||(this.store.dispatch(Ib()),t.preventDefault()))};switch(t.key){case"ArrowUp":d==="below"?g():m();break;case"ArrowDown":{d==="below"?m():g();break}case"Escape":{n||(this.store.dispatch(bd(-1)),this.store.dispatch(Si({collapse:!0})),this.store.dispatch(mI(!0)),t.preventDefault());break}case"Tab":{t.preventDefault();let v=js(this.state);if(!v)return;this.store.dispatch(lu(!1)),this.store.dispatch(kn({text:v.text,suggestion:v,eventMetrics:{inputType:"tab"},replace:"until-selection-end"}));break}case" ":{if(f||this.state.input.selectedSuggestionIndex===-1)return;let v=js(this.state);if(!v)return;this.store.dispatch(kn({text:v.text,suggestion:v,eventMetrics:{inputType:"space"},replace:"until-selection-end"}));break}case"Enter":{if(f||t.shiftKey||this.state.input.selectedSuggestionIndex===-1)return;let v=js(this.state);if(!v)return;this.store.dispatch(kn({text:v.text,suggestion:v,eventMetrics:{inputType:"enter"},replace:"until-selection-end"})),t.preventDefault();break}default:}n&&r&&this.store.dispatch(Si({collapse:!1}))}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(Ho([]))}handlingTimeStart(){this.state.handlingTime.startTime||(te.info("Start handling time"),this.store.dispatch(zA()))}handlingTimeStop(){this.state.handlingTime.startTime&&(te.info("Stop handling time"),this.store.dispatch(jm()))}logSendMessage(t){let n=XA(this.state,{version:this.version});n&&(t&&(Object.assign(n,{text:t}),Object.assign(n,{lenTextTotal:t.length})),this.deepdeskApi.sendEvent("Send Message",{conversationId:this.conversationId(),data:n}),this.emit("send-message-event",n))}logHandlingTime(){let t=YA(this.state,{version:this.version});t&&(this.deepdeskApi.sendEvent("Handling Time",{conversationId:this.conversationId(),data:t}),this.store.dispatch(HA()))}notifySubmit(t={}){var n;this.shouldAbort()||(this.store.dispatch(Di((n=t.text)!=null?n:this.state.input.text)),this.store.dispatch(_b()))}emit(t,n){let r=this.eventListeners[t];r&&r.forEach(o=>{try{o(n)}catch(i){te.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),te.error(i)}})}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),()=>{this.off(t,n)}}off(t,n){if(!t&&!n){this.eventListeners={};return}let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}setConversationQuery(t){this.dynamicThunkObject.conversationQuery=t}setPlatformVariables(t){this.store.dispatch(Bb(t))}whenConversationLoaded(t){let n=i=>{var s;return(s=i.conversation.current)==null?void 0:s.id},r=()=>this.loadProfileConfig().then(()=>t());return n(this.state)&&r(),this.subscribe(n,i=>{i&&r()})}overlayContainerFactory(t,n,r,o){let[i,s]=wu(n,r);return i.setAttribute("translate","no"),i.dataset.testid=t,o&&i.classList.add(o),[i,s]}createInlineContainer(t,n){var a;let r=document.createElement("div");r.style.position="absolute",r.style.top="0px",r.style.left="0px",r.style.height="0px",r.style.width="0px";let o=document.createElement("div");o.style.display="none",o.style.position="absolute",o.style.height="0px",o.style.width="0px",o.style.backgroundColor="red",r.appendChild(o);let i=(a=t.ownerDocument.defaultView)==null?void 0:a.frameElement,s=i?i.ownerDocument.defaultView:null;if(i&&(s===window||(s==null?void 0:s.parent)===window)){let[l,c]=wu(i,{appendTo:document.body,onMoveStart:()=>{o.style.display="none"}});l.dataset.testid=n,l.style.zIndex="2",l.appendChild(r),this.unmountHandlers.push(()=>{c()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return os(o),o.dataset.testid=t,o.style.color=r.color,o.style.fontSize=r.fontSize,o.style.fontFamily=r.fontFamily,o.style.fontVariant=r.fontVariant,o.setAttribute("translate","no"),n.appendChild(o),o}storeMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(t,n),te.info(`Stored analytics for ${this.conversationId()}`)}catch(t){}}restoreMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=window.sessionStorage.getItem(t);if(!n)return;let r=JSON.parse(n);r.text.trim()===this.state.input.text.trim()?(te.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(Ab(r.metrics))):te.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(t)}catch(t){}}mount(t,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!Gm(t))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let d=n,{customStyles:r,closestScrollSelector:o,floatingMenuParent:i,appendOverlayTo:s,inputMediator:a}=d,l=ie(d,["customStyles","closestScrollSelector","floatingMenuParent","appendOverlayTo","inputMediator"]),c={customStyles:r,closestScrollSelector:o,floatingMenuParent:i,appendOverlayTo:s};this.configure(l),this.settings.automaticHandlingTime&&this.setupHandlingTime(t),os(t),this.inputMediator=a||(Ts(t)?new Ps(t):new Rs(t)),this.inputMediator.on("change",({plainText:p,rawHTML:m,suggestionTextStart:g})=>{this.store.dispatch(Ed({text:p,html:m,suggestionTextStart:g}))}),this.inputMediator.on("keyup",p=>{this.store.dispatch(kb(sh(p)))}),this.inputMediator.on("keydown",p=>{this.handleKeyDown(p)}),this.inputMediator.on("paste",({pastedText:p,selectionText:m})=>{this.store.dispatch(Rb({text:p,selectionText:m}))}),this.inputMediator.on("cut",({selectionText:p})=>{this.store.dispatch(Cb(p))});let u;this.inputMediator.on("selection",p=>{clearTimeout(u),p===null?u=setTimeout(()=>{p!==null&&this.store.dispatch(Cd(p))},500):this.store.dispatch(Cd(p))}),this.unmountHandlers.push(()=>{clearTimeout(u)}),this.inputMediator.on("disabled",()=>{var p;(p=this.inputMediator)==null||p.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{this.settings.detectSubmit&&this.notifySubmit()}),this.inputMediator.on("blur",()=>{this.store.dispatch(vm(!1))}),this.inputMediator.on("focus",()=>{this.store.dispatch(vm(!0))}),this.renderSuggestions(t,c),this.subscribe(Ui("inlineSuggestions"),()=>{this.renderSuggestions(t,c)}),this.subscribe(Ui("suggestionsPlacement"),()=>{this.renderSuggestions(t,c)});let f=this.renderOverlays(n);this.unmountHandlers.push(()=>{f.unmount()}),this.store.dispatch(Ed({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),suggestionTextStart:this.inputMediator.getSuggestionTextStart()})),this.store.dispatch(Cd(this.inputMediator.getSelection())),this.store.dispatch(vm(this.inputMediator.isFocused)),this.unmountHandlers.push(()=>{this.state.input.text!==""&&this.storeMetrics()}),this.whenConversationLoaded(()=>{this.restoreMetrics(),this.syncInputMediator(),this.refreshTextSuggestions(),this.promptForNickname()}),this.isMounted=!0}promptForNickname(t){if(this.nicknameDialogUnsubscribe||this.nicknameDialogFailed)return;let n=this.createContainer("nickname-dialog",document.body);document.body.appendChild(n);let r=(0,No.createRoot)(n),o=null,i=a=>{o=a,s()},s=()=>{r==null||r.render((0,ke.jsx)(ko,{store:this.store,children:(0,ke.jsx)(to,{broadcastEvents:this.broadcastEvents,children:(0,ke.jsx)(_I,{id:"deepdesk-nickname-dialog",error:o,onSave:a=>M(this,null,function*(){try{yield this.store.dispatch(Db({agentNickname:a})).unwrap(),console.log("setAgentNickname",a),this.broadcastEvents.send(Rd,{showNicknameDialog:!1}),this.nicknameDialogUnsubscribe&&this.nicknameDialogUnsubscribe()}catch(l){te.error("Error setting agent nickname",l),i("error"),this.nicknameDialogFailed=!0}})})})}))};s(),this.nicknameDialogUnsubscribe=()=>{r.unmount(),n.remove(),this.nicknameDialogUnsubscribe=null}}subscribe(t,n){let r=t(this.store.getState());return this.store.subscribe(()=>{let o=t(this.store.getState());o!==r&&(r=o,n(r))})}unmount(){var t,n,r,o,i;(t=this.inlineSuggestions)==null||t.unmount(),(n=this.aboveSuggestions)==null||n.unmount(),(r=this.belowSuggestions)==null||r.unmount(),(o=this.floatingMenu)==null||o.unmount(),this.unmountHandlers.forEach(s=>s()),this.unmountHandlers=[],(i=this.inputMediator)==null||i.dispose(),this.nicknameDialogUnsubscribe&&this.nicknameDialogUnsubscribe(),this.isMounted=!1}dispose(){this.unmount(),this.unmountWidget(),this.disposeHandlers.forEach(t=>t()),this.disposeHandlers=[],this.off()}renderSuggestions(t,n){var r,o,i,s;(r=this.floatingMenu)==null||r.unmount(),(o=this.inlineSuggestions)==null||o.unmount(),(i=this.aboveSuggestions)==null||i.unmount(),(s=this.belowSuggestions)==null||s.unmount(),this.settings.floatingMenu&&(this.floatingMenu=this.renderFloatingMenu(t,n)),this.settings.inlineSuggestions||this.settings.suggestionsPlacement==="inline"?this.inlineSuggestions=this.renderInlineSuggestions(t,n):this.settings.suggestionsPlacement==="below"?this.belowSuggestions=this.renderAboveOrBelowSuggestions(t,n,"below"):this.aboveSuggestions=this.renderAboveOrBelowSuggestions(t,n,"above")}renderInlineSuggestions(t,n){let{customStyles:r}=n,o=this.createInlineContainer(t,"deepdesk-caret"),i=(0,No.createRoot)(o);i.render((0,ke.jsx)(ko,{store:this.store,customStyles:r,children:(0,ke.jsx)(to,{broadcastEvents:this.broadcastEvents,children:(0,ke.jsx)(II,{})})}));let s=a=>{a?(o.style.display="block",o.style.top=`${a.top}px`,o.style.left=`${a.left}px`):o.style.display="none"};return this.inputMediator.on("caretposition",s),{unmount:()=>{var a;(a=this.inputMediator)==null||a.off("caretposition",s),i.unmount(),o.remove()}}}renderAboveOrBelowSuggestions(t,n,r){let{customStyles:o,closestScrollSelector:i,appendOverlayTo:s}=n,a=i&&GS(t,i)||void 0,[l,c]=this.overlayContainerFactory("deepdesk-tab-completion",a||t,{appendTo:s,closestScrollElement:a,mirrorOverflow:!0,onRemove:()=>this.unmount()},o==null?void 0:o.rootNode),[u,f]=this.overlayContainerFactory("deepdesk-suggestions-overlay",a||t,{appendTo:s,placement:r},o==null?void 0:o.suggestionsRootNode),d=(0,No.createRoot)(l);d.render((0,ke.jsx)(ko,{store:this.store,customStyles:o,children:(0,ke.jsx)(to,{broadcastEvents:this.broadcastEvents,children:(0,ke.jsx)(tA,{inputElement:t})})}));let p=(0,No.createRoot)(u);return p.render((0,ke.jsx)(ko,{store:this.store,customStyles:o,children:(0,ke.jsx)(to,{broadcastEvents:this.broadcastEvents,children:(0,ke.jsx)(BI,{onLogIn:()=>this.loginViaPopup().catch(m=>te.warn(m.message))})})})),{unmount(){d.unmount(),p.unmount(),c(),f()}}}renderFloatingMenu(t,n){let{customStyles:r,closestScrollSelector:o,appendOverlayTo:i,floatingMenuParent:s}=n,a=o&&GS(t,o)||void 0,[l,c]=this.overlayContainerFactory("floating-menu",a||t,{appendTo:s!=null?s:i},r==null?void 0:r.floatingMenuParent),u=(0,No.createRoot)(l);return u.render((0,ke.jsx)(ko,{store:this.store,customStyles:r,children:(0,ke.jsx)(to,{broadcastEvents:this.broadcastEvents,children:(0,ke.jsx)(fI,{onLogIn:()=>this.loginViaPopup().catch(f=>te.warn(f.message))})})})),{unmount(){u.unmount(),c()}}}renderOverlays(t){let{customStyles:n}=t,r=this.createContainer("deepdesk-overlays"),o=(0,No.createRoot)(r);return o.render((0,ke.jsx)(ko,{store:this.store,customStyles:n,children:(0,ke.jsx)(to,{broadcastEvents:this.broadcastEvents,children:(0,ke.jsx)(aI,{})})})),{unmount(){o.unmount(),r.remove()}}}renderWidget(t,n={}){if(this.widgetElement&&te.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,isEmbedded:i}=n;this.widgetElement=t,this.configure({showImages:o,isEmbedded:i}),this.widgetRoot=(0,No.createRoot)(t),this.widgetRoot.render((0,ke.jsx)(ko,{store:this.store,customStyles:r,children:(0,ke.jsx)(to,{broadcastEvents:this.broadcastEvents,children:(0,ke.jsx)(RA,{assistantOptions:n.assistantOptions,knowledgeAssistOptions:n.knowledgeAssist,onLogIn:()=>this.loginViaPopup().catch(s=>te.warn(s.message))})})}))}unmountWidget(){var t,n;(n=(t=this.widgetRoot)==null?void 0:t.unmount)==null||n.call(t),this.widgetRoot=null,this.widgetElement=null}renderKnowledgeAssistantWidget(t,n,r={}){let{customStyles:o,initialQuestion:i}=r,s=(0,No.createRoot)(n);return s.render((0,ke.jsx)(ko,{store:this.store,customStyles:o,children:(0,ke.jsx)(to,{broadcastEvents:this.broadcastEvents,children:(0,ke.jsx)(FS,{children:(0,ke.jsxs)(Yp,{assistantCode:t,initialQuestion:i,evaluateKnowledgeAssistFn:Hl,children:[(0,ke.jsx)(Hs,{children:(0,ke.jsx)(Qp,{title:r.title,emptyState:r.emptyState})}),(0,ke.jsx)(DS,{children:(0,ke.jsx)(Xp,{})})]})})})})),{unmount(){s.unmount()}}}setupHandlingTime(t){let n=Xm(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){ZA(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfig(){var t;return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(t=this.state.conversation.current)!=null&&t.profileCode?(this.loadProfileConfigPromise=Promise.resolve().then(()=>M(this,null,function*(){yield this.store.dispatch(Kc()).unwrap();let n=mi(this.state);n&&this.store.dispatch(Yd({showSearch:n.search,showImageSearch:n.imageSearch,showEntitiesCommand:n.entitiesCommand,showSummaryCommand:!!n.summarizerAssistantNew,showKnowledgeSearch:!!n.knowledgeAssistantNew||!!n.knowledgeAssistant,recommendTextSuggestions:n.recommendTextSuggestions}))})).finally(()=>{mi(this.state)||(this.loadProfileConfigPromise=null)}),this.loadProfileConfigPromise):Promise.resolve()}loginViaPopup(t){return M(this,null,function*(){return new Promise((n,r)=>{this.store.dispatch(hd());let o=new MessageChannel,i=o.port1,s=this.settings.adminUrl,a=new URL(t!=null&&t.url?t==null?void 0:t.url:`${s}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let l=!1,c=()=>{u&&!u.closed&&u.close(),window.removeEventListener("message",f),clearInterval(d)};i.onmessage=p=>M(this,null,function*(){var m,g;if((m=p.data)!=null&&m.jwt)try{yield this.deepdeskApi.exchangeTokenForAccessCookie((g=p.data)==null?void 0:g.jwt),yield this.isLoggedIn(),this.broadcastEvents.send(El),l=!0,o.port1.close(),n()}catch(v){console.error(v),r(v)}finally{l=!0,c()}});let u=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");u===null&&r(new Error("Popup blocked by browser"));let f=p=>M(this,null,function*(){var m;if(p.origin===a.origin)switch((m=p.data)==null?void 0:m.type){case"deepdesk-popup-request-origin":{try{let g=JSON.stringify({type:"deepdesk-popup-parent-origin"});u==null||u.postMessage(g,a.origin)}catch(g){te.error("Error posting message to popup",g),r(g)}break}case"deepdesk-popup-loaded":{try{let g=JSON.stringify({type:"deepdesk-popup-create-channel"});u==null||u.postMessage(g,a.origin,[o.port2])}catch(g){te.error("Error posting message to popup",g),r(g)}break}case"deepdesk-popup-error":{if(c(),p.data.message==="Platform account url mismatch"){let g=`Please contact your administrator: The platform account url (${p.data.targetOrigin}) is misconfigured as it differs from the origin of the page that opened the popup (${p.data.openerOrigin}).`;te.warn(g),this.store.dispatch(eh(g)),r(new Error(g))}if(p.data.message==="Timeout"){let g="Please contact your administrator: Popup timed out. Check if the account's platform url is configured correctly.";te.warn(g),this.store.dispatch(eh(g)),r(new Error(g))}r(new Error(p.data.message));break}}});window.addEventListener("message",f);let d=setInterval(()=>{u&&!u.closed||(c(),l||r(new Error("Popup closed by user")))},200);this.disposeHandlers.push(c)})})}translateMessages(t){return this.deepdeskApi.translateMessages(t)}refreshTextSuggestions(){return M(this,null,function*(){this.isMounted&&(yield this.store.dispatch(gm()))})}refreshWidgetSuggestions(){return M(this,null,function*(){if(!this.widgetRoot)return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=Gc(this.state);try{n.forEach(({type:r})=>{switch(r){case"entities":this.store.dispatch(vr());break;case"pinned-messages":case"sticky-messages":break;default:ju.includes(r)||this.store.dispatch(Sr(r))}})}catch(r){this.handleError(r)}})}};ol.version="19.4.1",ol.count=0;var bu=ol;function mz(e){return M(this,null,function*(){var o,i,s;let n=yield((o=e.fetch)!=null?o:window.fetch)(e.url),r=yield n.blob();return new File([r],e.name,{type:(s=(i=e.mimeType)!=null?i:n.headers.get("Content-Type"))!=null?s:"image/jpeg"})})}function d_(e,t){return M(this,null,function*(){let n=yield mz(t),r=new Event("change",{bubbles:!0,cancelable:!0});try{Object.defineProperty(e,"files",{configurable:!0,get:()=>[n]}),e.dispatchEvent(r)}finally{Object.hasOwn(e,"files")&&delete e.files}})}function f_(e,t,n){return M(this,null,function*(){yield new Mo(e).authenticateWithKey(t,n)})}function p_(e){return e.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}function m_(r,o){return M(this,arguments,function*(e,t,n={}){var f,d;let{value:i}=e,{start:s,end:a}=(f=n.replace)!=null?f:{start:0,end:i.length},l=`${i.slice(0,s)}${t}${i.slice(a)}`,c=(d=n.selectionAfter)!=null?d:{start:s+t.length,end:s+t.length},u=()=>{if(n.setValue)return n.setValue(l);e.value=l};return Promise.resolve(u()).then(()=>{e.selectionStart=c.start,e.selectionEnd=c.end,e.blur(),e.focus()})})}function g_(r,o){return M(this,arguments,function*(e,t,n={}){let i=n.replace?Ti(e,n.replace.start,n.replace.end):tl(e),s,a=()=>{if(n.setRange)return n.setRange(i.cloneRange());i.deleteContents(),s=document.createElement("span"),i.insertNode(s),n.insertBRs!==!1?t.split(`
84
84
  `).reverse().forEach((l,c)=>{c>0&&i.insertNode(document.createElement("br")),i.insertNode(document.createTextNode(l))}):i.insertNode(document.createTextNode(t))};return Promise.resolve(a()).then(()=>{try{if(n.selectionAfter!==!1){e.focus();let l=n.selectionAfter?Ti(e,n.selectionAfter.start,n.selectionAfter.end):(i.collapse(!1),i),c=window.getSelection();c==null||c.removeAllRanges(),c==null||c.addRange(l)}if(!s)return;s.scrollIntoView&&s.scrollIntoView({block:"nearest",inline:"nearest"})}finally{s&&s.remove()}})})}function gz(e){let t=document.createElement("template");return t.innerHTML=e.replace(/(\[([^\]]+)])\(([^)]+)\)/g,'<a href="$3" target="_blank" rel="noopener noreferrer">$2</a>'),t.content}function hz(e){let t=document.createDocumentFragment();return e.split(`
85
85
  `).forEach((n,r)=>{r>0&&t.appendChild(document.createElement("br"));let o={index:0},i=0;for(;o=n.slice(i).match(/(\[([^\]]+)])\(([^)]+)\)/);){let s=document.createElement("a");s.href=o[3],s.setAttribute("target","_blank"),s.setAttribute("rel","noopener noreferrer"),s.appendChild(document.createTextNode(o[2])),t.appendChild(document.createTextNode(n.slice(i,i+o.index))),t.appendChild(s),i=i+o.index+o[0].length}t.appendChild(document.createTextNode(n.slice(i)))}),t}function h_(e,t){let n=e.parentElement;if(!n){console.warn("No insert point found");return}let{display:r}=window.getComputedStyle(n);r.includes("block")||r==="table-cell"?n==null||n.insertBefore(t,e.nextSibling):h_(n,t)}function y_(o,i){return M(this,arguments,function*(e,t,{isBlock:n,isHTML:r}={}){let s;e.dispatchEvent(new InputEvent("beforeinput",{inputType:"insertText",data:t,bubbles:!0,cancelable:!0}));let a=()=>{var d;let l=(d=e.ownerDocument.defaultView)!=null?d:window,c=l.getSelection();if((!c||c.rangeCount===0)&&(e.focus(),c=l.getSelection()),!c||c.rangeCount===0)return;let u=c.getRangeAt(0);if(!u)return;s=document.createElement("span"),u.insertNode(s);let f=r?gz(t):hz(t);n?h_(u.startContainer,f):(u.insertNode(f),u.collapse(!1))};return Promise.resolve(a()).then(()=>{if(e.dispatchEvent(new InputEvent("input",{inputType:"insertText",data:t,bubbles:!0,cancelable:!0})),e.focus(),!!s)try{s.scrollIntoView&&s.scrollIntoView({block:"nearest",inline:"nearest"})}finally{s&&s.remove()}})})}return B_(yz);})();
86
86
  /*! Bundled license information:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deepdesk/deepdesk-sdk",
3
- "version": "19.3.2-beta.6",
3
+ "version": "19.4.1",
4
4
  "description": "Deepdesk SDK",
5
5
  "author": "Lukas Batteau",
6
6
  "license": "ISC",