@deepdesk/deepdesk-sdk 19.6.2-beta.17 → 19.6.2-beta.18

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.
@@ -81,7 +81,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
81
81
  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
82
82
  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 q0=E(A()),lz={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},gI=({className:e,color:t})=>(0,q0.jsx)("svg",{className:e,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:(0,q0.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:lz[t||"pink"]})});var hI={root:"dd-LbeUM",text:"dd-Dpfn1",isLoggedIn:"dd-XvHAn",isLoggedOut:"dd-21y-z",icon:"dd-8rLqS",logo:"dd-slXhD",lock:"dd-ByzlR"};var Y0={};dt(Y0,{enUS:()=>cz,nlNL:()=>uz});var cz={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Search"}]},uz={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Zoeken"}]};var Ti=E(A()),vI=({onLogIn:e})=>{let t=ae(Y0),n=J("floatingMenu"),r=J("productName"),o=ve(),s=K(kt),i=F("FloatingMenu",hI);if(s===null||n===!1)return null;let a=()=>{s===!0?o(dr(!0)):e()};return(0,Ti.jsxs)("button",{type:"button",className:(0,yI.default)(i.root,{[i.isLoggedIn]:s,[i.isLoggedOut]:!s}),onClick:a,children:[(0,Ti.jsx)("div",{className:i.text,children:t(s?"search":"signin",{productName:r})}),(0,Ti.jsxs)("div",{className:i.icon,children:[(0,Ti.jsx)(gI,{className:i.logo,color:"pink"}),s===!1&&(0,Ti.jsx)(mI,{className:i.lock})]})]})};var Gm=E(Q());function qr(e){let{showMidSentenceSuggestions:t,showSuggestionsBeforePattern:n,showSuggestionsAfterPattern:r}=e.settings,{text:o,selection:s}=e.input;return s.end<e.input.suggestionTextStart||s.start!==s.end?!1:s.end>=o.length?!0:t?n&&new RegExp(n).test(o.substring(s.end))||r&&new RegExp(r).test(o.substring(0,s.end))?!0:n===!1&&r===!1:!1}var dz={showTabHint:!1,inputHasFocus:!1,overlayCollapsed:!1,openOverlayWhenTyping:!1,overlayCollapsedUserOverwrite:!1},Um=({ui:e})=>e.overlayCollapsed,SI=Pe({name:"ui",initialState:dz,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:bu,setInputFocus:Vm,setOverlayCollapsed:bs,setOpenOverlayWhenTyping:xI,setOverlayCollapsedUserOverwrite:wI}=SI.actions,bI=SI.reducer;var EI={styleRow:"dd-prYfH",styleSuggestion:"dd-JTmXy"};var Eu=E(A()),fz=({match:e,selected:t,styles:n})=>(0,Eu.jsx)(fe,{as:"button",selected:t,className:n.styleRow,"data-testid":"style-suggestion-item",title:e.suggestion,children:(0,Eu.jsx)("span",{className:n.styleSuggestion,children:e.suggestion})}),pz=({matches:e,selectedIndex:t})=>{let n=F("StyleSuggestionList",EI);return(0,Eu.jsx)(Ct,{children:e.map((r,o)=>(0,Eu.jsx)(fz,{match:r,selected:t===o,styles:n},`${r.keyword}-${o}`))})},Wm=pz;var AI=E(Q());var Es=E(Q());var CI=E(Q());function TI(e,t,n){(0,CI.useEffect)(()=>{let r=e.current;return r?(r.addEventListener(t,n),()=>{r.removeEventListener(t,n)}):()=>{}},[e,t,n])}var kI={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 Cu=E(A()),RI=({title:e})=>(0,Cu.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"18px",height:"18px",viewBox:"0 0 24 24","aria-labelledby":"closeTitle",children:[(0,Cu.jsx)("title",{id:"closeTitle",children:e}),(0,Cu.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 X0={};dt(X0,{enUS:()=>mz,nlNL:()=>gz});var mz={assistant:[{type:0,value:"Assistant"}],close:[{type:0,value:"Close"}]},gz={assistant:[{type:0,value:"Assistent"}],close:[{type:0,value:"Sluiten"}]};var Hn=E(A()),yz=["search","personal-collection-search","search-autocomplete"];function vz(e,t,n,r={}){var s;let o="";return yz.includes(t)?o=BA(z0(e,n,{stripAgentPart:!0}),(s=r.searchKeywords)!=null?s:[n]):o=z0(e,n,r),r.placeholders===!0&&(o=UA(o)),o}var Sz=()=>{},xz=({selected:e,suggestion:t})=>{let n=ae(X0),r=J("inlineSuggestions"),o=K(Ds),[s,i]=(0,Es.useState)(!1),a=J("enableSuggestionFeedback"),l=K(S=>S.input.text),c=ve(),u=F("TextSuggestion",kI),f=(0,Es.useRef)(null),d=t.source==="assistant",p=a&&!d;(0,Es.useEffect)(()=>{let S=setTimeout(()=>{c(lE({text:t.text,suggestion:t}))},500);return()=>{clearTimeout(S)}},[t]),TI(f,"click",()=>{c(Tn({suggestion:t,text:t.text,eventMetrics:{inputType:"mouse"},replace:"until-selection-end"}))});let h=()=>{c(zs({source:t.source,text:t.text,assistantCode:t.assistantCode}))},y=(0,Es.useMemo)(()=>vz(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,Hn.jsxs)("div",{className:u.root,onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),children:[(0,Hn.jsx)(fe,{ref:f,as:"button","data-testid":"suggestions-overlay-item",selected:e,onClick:Sz,children:t.source==="assistant"?(0,Hn.jsxs)("div",{className:u.assistantContainer,children:[(0,Hn.jsx)(Ss,{containerTagName:"div",tagName:"span",className:u.formattedTextTruncated,content:y}),(0,Hn.jsx)("span",{className:u.assistantBadge,children:n("assistant")})]}):(0,Hn.jsx)(Ss,{containerTagName:"div",tagName:"span",className:u.formattedText,content:y})}),p&&s&&(0,Hn.jsx)("div",{className:u.actions,children:(0,Hn.jsx)(Fm,{source:"overlay",context:l,suggestion:t})}),d&&s&&(0,Hn.jsx)("div",{className:u.closeIconContainer,children:(0,Hn.jsx)("button",{type:"button",className:u.closeIcon,onClick:h,title:n("close"),children:(0,Hn.jsx)(RI,{title:n("close")})})})]})},PI=xz;var II=E(A()),wz=({suggestions:e,selectedIndex:t,reverse:n})=>(0,AI.useMemo)(()=>{let o=e.map((s,i)=>(0,II.jsx)(PI,{index:i,selected:i===t,suggestion:s},`${s.text}-${s.source}`));return n?o.reverse():o},[e,t,n]),$m=wz;var _I={root:"dd-PfvRI",paper:"dd-HYlyY"};var Tu={list:{keywordMatches:[]},fetchState:"idle"},jm=e=>e.styleSuggestions.list,ki=me("styleSuggestions/getAll",(n,r)=>M(null,[n,r],function*({text:e},t){var l;let{deepdeskAPI:o}=t.extra,s=t.getState(),{showStyleSuggestions:i}=s.settings,a=(l=s.conversation.current)==null?void 0:l.profileCode;if(!i)return Tu.list;if(!a)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:a,message:e})})),MI=Pe({name:"styleSuggestions",initialState:Tu,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(ki.pending,t=>{t.fetchState="loading"}).addCase(ki.rejected,t=>{t.fetchState="error"}).addCase(ki.fulfilled,(t,n)=>{t.fetchState="done",Uo(t.list,n.payload)||(t.list=n.payload)}).addCase(Hs,t=>{t.list=Tu.list}).addCase(Ke,()=>Tu).addCase(cn,()=>Tu)}}),{commitStyleSuggestion:LI}=MI.actions,OI=MI.reducer;var Km=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 Ri=E(A()),bz=()=>{var S;let e=(0,Gm.useRef)(null),t=F("InlineSuggestionsOverlay",_I),n=K(qr),r=ve(),o=K(kt),s=K(Xi),i=K(Um),a=J("showTextSuggestions"),l=K(Fs),c=K(Pl),u=J("showStyleSuggestions"),f=J("showStyleSuggestionList"),d=K(jm),p=u&&f?Km((S=d.keywordMatches)!=null?S:[]):[],h=p.length>0,y=a&&l.length>0;return hs(()=>{setTimeout(()=>{r(bs({collapse:!0,skipWhenInputFocus:!0}))})}),(0,Gm.useEffect)(()=>{let g=e.current;if(!g||!g.parentElement)return;g.parentElement.style.left="0px";let m=g.getBoundingClientRect();g.parentElement.style.left=`${Math.min(window.innerWidth-4-m.right,0)}px`}),i||o!==!0||s===!1||!n&&!h||!y&&!h?null:(0,Ri.jsx)("div",{className:t.root,"data-variant":"inline",children:(0,Ri.jsxs)("div",{ref:e,className:t.paper,children:[h&&(0,Ri.jsx)(Wm,{matches:p,selectedIndex:-1}),y&&(0,Ri.jsx)(Ct,{children:(0,Ri.jsx)($m,{suggestions:l,selectedIndex:c})})]})})},NI=bz;var Cs=E(Q());var DI={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 Q0={};dt(Q0,{enUS:()=>Ez,nlNL:()=>Cz});var Ez={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."}]},Cz={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 ht=E(A()),FI=({onClose:e,onSave:t,id:n,error:r})=>{let[o,s]=(0,Cs.useState)(""),[i,a]=(0,Cs.useState)(!1),[l,c]=(0,Cs.useState)(!1),u=F("Nickname",DI),f=Cs.default.useRef(null),d=K(g=>g.info.showNicknameDialog),p=ae(Q0),h=J("adminUrl");(0,Cs.useEffect)(()=>{r&&a(!0)},[r]);let y=()=>{if(!f.current)return;o.trim()?f.current.setCustomValidity(""):f.current.setCustomValidity(p("nicknameDialogError")),f.current.reportValidity()},S=g=>{g.preventDefault();let m=o.trim(),v=g.currentTarget.querySelector("#nickname-input");if(!m){v.setCustomValidity(p("nicknameDialogError")),v.reportValidity();return}v.setCustomValidity(""),t(m)};return(0,ht.jsxs)(Ya,{isOpen:d,"datatest-id":n,onClose:e||(()=>{}),onBack:e||(()=>{}),children:[(0,ht.jsx)("div",{className:u.titleWrapper,children:(0,ht.jsx)("h1",{className:u.title,children:p("title")})}),(0,ht.jsxs)("form",{className:u.dialogContent,onSubmit:S,children:[(0,ht.jsx)("p",{children:p("nicknameDialogTitle")}),i&&r&&(0,ht.jsx)("div",{className:u.errorMessage,children:h?(()=>{let g=p("nicknameDialogSaveError",{account:h}),m=`${h}.deepdesk.com/admin/user-settings`,v=g.indexOf(m);if(v!==-1){let x=g.substring(0,v),T=g.substring(v+m.length);return(0,ht.jsxs)(ht.Fragment,{children:[x,(0,ht.jsx)("a",{href:m,target:"_blank",rel:"noopener noreferrer",className:u.errorLink,children:m}),T]})}return g})():p("nicknameDialogSaveErrorWithoutLink")}),(0,ht.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:g=>{c(new RegExp("\\p{Extended_Pictographic}","u").test(g.target.value)),s(g.target.value)},onBlur:y,ref:f}),l&&(0,ht.jsx)("div",{className:u.errorMessage,role:"alert",children:p("nicknameDialogEmojiError")}),(0,ht.jsxs)("div",{className:u.buttonsWrapper,children:[r?(0,ht.jsx)("div",{className:u.closeButtonWrapper,children:(0,ht.jsx)("button",{type:"button",className:u.closeButton,onClick:()=>e==null?void 0:e(),children:p("close")})}):null,(0,ht.jsx)("div",{className:u.buttonContinueWrapper,children:(0,ht.jsx)("button",{type:"submit",className:u.continueButton,disabled:!o.trim()||new RegExp("\\p{Extended_Pictographic}","u").test(o),children:p("nicknameDialogContinueButton")})})]})]})]})};var ku=E(A()),Tz=({children:e})=>{let n=J("locale").replace("-","");return(0,ku.jsx)(Wh.Provider,{value:n,children:e})},kz=({store:e,customStyles:t={},children:n})=>(0,ku.jsx)(nb,{store:e,children:(0,ku.jsx)(Tz,{children:(0,ku.jsx)(hl.Provider,{value:t,children:n})})}),Po=kz;var Ym=E(De()),nl=E(Q());var zI=E(Q());function HI(e,t){let[n,r]=(0,zI.useState)(()=>{if(typeof window=="undefined")return t;try{let s=window.localStorage.getItem(e);return s?JSON.parse(s):t}catch(s){return Z.error(s),t}});return[n,s=>{try{let i=s instanceof Function?s(n):s;r(i),typeof window!="undefined"&&window.localStorage.setItem(e,JSON.stringify(i))}catch(i){Z.error(i)}}]}var BI=()=>/Mac/i.test(navigator.platform);var VI=E(De()),Ao=E(Q());var Z0={};dt(Z0,{enUS:()=>Rz,nlNL:()=>Pz});var Rz={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"}]}]},Pz={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 UI={root:"dd-uTPjX",anchor:"dd-C8lsZ",anchorButton:"dd-IoSx9"};var Ts=E(A()),J0=(e,t,n)=>r=>(0,Ts.jsx)("button",{className:e.anchorButton,type:"button",value:t,onClick:n,children:r},t),Az=({className:e,loginUrl:t,isEmbedded:n,onSnooze:r,onLogIn:o})=>{let s=ae(Z0),i=un(),a=F("Login",UI),l=J("productName"),c=J("signInViaPopup"),u=n&&!c,f=(0,Ao.useCallback)(m=>{m.preventDefault(),r&&r(Number.parseInt(m.target.value,10))},[]),d=(0,Ao.useCallback)(m=>{m.preventDefault(),i.send(ta,!0)},[t]),p=(0,Ao.useMemo)(()=>m=>(0,Ts.jsx)("a",{onClick:x=>{x.preventDefault(),o()},href:t,className:a.anchor,target:"_blank",rel:"noreferrer",children:m},"login"),[t]),h=(0,Ao.useCallback)(m=>(0,Ts.jsx)("button",{type:"button",className:a.anchorButton,onClick:d,children:m},"prompt"),[d]),{min:y,hour:S,day:g}=(0,Ao.useMemo)(()=>({min:J0(a,600,f),hour:J0(a,3600,f),day:J0(a,3600*12,f)}),[]);return(0,Ts.jsxs)("div",{className:(0,VI.default)(e,a.root),children:[s("loginPlease",{login:u?h:p,productName:l}),r&&(0,Ts.jsxs)(Ao.Fragment,{children:[(0,Ts.jsx)("br",{}),s("snooze",{min:y,hour:S,day:g})]})]})},qm=Az;var WI={root:"dd-DoQhb",text:"dd-Jwnev"};var Ru=E(A()),Iz=({title:e})=>{let t=F("SearchTrigger",WI),n=ve(),r=nt();return(0,Ru.jsxs)("button",{type:"button",className:t.root,onClick:()=>{n(dr(!0)),r("open search",{via:"autocomplete-overlay"})},children:[(0,Ru.jsx)(el,{}),(0,Ru.jsx)("span",{className:t.text,children:e})]})},$I=Iz;var ex={};dt(ex,{enUS:()=>_z,nlNL:()=>Mz});var _z={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"}]},Mz={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 jI={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 Le=E(A()),Lz=({onLogIn:e})=>{var $;let t=F("SuggestionsOverlay",jI),n=ae(ex),r=K(qr),o=K(aE),s=ve(),i=(0,nl.useRef)(null),a=J("searchTriggerKey"),l=J("productName"),c=K(Um),u=K(kt),f=K(qb),d=K(Xi),[p,h]=(0,nl.useState)(null),y=J("showSearch"),S=J("showTextSuggestions"),g=J("adminUrl"),m=J("isEmbedded"),v=J("suggestionsPlacement"),[x,T]=HI("dd-snooze-until-ms",0),C=c||x>Date.now(),k=K(Fs),R=K(Pl),L=J("showStyleSuggestions"),N=J("showStyleSuggestionList"),B=K(jm),Y=L&&N?Km(($=B.keywordMatches)!=null?$:[]):[],X=Y.length>0,I=k.filter(O=>O.source!=="gpt").length,z=()=>{C&&T(0),s(wI(!C))},W=O=>{let q=Date.now()+O*1e3;T(q),Z.info(`Snooze until: ${new Date(q)}`),s(bs({collapse:!0}))};return(0,nl.useEffect)(()=>{I===0&&h(null)},[k,I]),hs(()=>{s(bs({collapse:!0,skipWhenInputFocus:!0}))}),u===null||d===!1?null:u===!1?(0,Le.jsxs)("div",{ref:i,className:(0,Ym.default)(t.root,{[t.isCollapsed]:C}),children:[!C&&(0,Le.jsxs)("div",{className:t.triggers,children:[(0,Le.jsx)("div",{style:{flex:1}}),(0,Le.jsx)("div",{className:t.triggersRight,children:(0,Le.jsx)(Ls,{className:t.toggleButton,title:n("collapse"),onClick:z,isCollapsed:!1})})]}),(0,Le.jsx)("div",{className:t.toggleButtonWrapper,children:(0,Le.jsx)(Ls,{className:t.toggleButton,title:n("open",{productName:l}),onClick:z,isCollapsed:!0})}),(0,Le.jsxs)("div",{className:t.collapsible,children:[f&&(0,Le.jsxs)("div",{className:t.loginError,children:[(0,Le.jsx)("span",{className:t.loginErrorMessage,children:f}),(0,Le.jsx)("button",{type:"button",className:t.loginErrorDismiss,onClick:()=>s(Fd()),"aria-label":n("dismissError"),children:n("dismiss")})]}),(0,Le.jsx)(qm,{loginUrl:g,isEmbedded:m,onLogIn:e,onSnooze:W})]})]}):!o||!r&&!X?null:(0,Le.jsxs)("div",{ref:i,className:(0,Ym.default)(t.root,{[t.isCollapsed]:C}),children:[!C&&(0,Le.jsxs)("div",{className:t.triggers,children:[(0,Le.jsx)("div",{style:{flex:1},children:y&&(0,Le.jsx)("div",{style:{display:"inline-block"},onFocus:()=>{},onMouseOver:()=>h(n(BI()?"searchHintMac":"searchHintWindows",{searchTriggerKey:a.toUpperCase()})),onMouseLeave:()=>h(null),children:(0,Le.jsx)($I,{title:n("search")})})}),(0,Le.jsxs)("div",{className:t.triggersRight,onFocus:()=>{},children:[(0,Le.jsx)("div",{className:(0,Ym.default)(!p&&t.hintsHidden,t.hints),children:p}),(0,Le.jsx)(Ls,{className:t.toggleButton,title:n("collapse"),onClick:z,isCollapsed:!1})]})]}),(0,Le.jsx)("div",{className:t.toggleButtonWrapper,children:(0,Le.jsx)(Ls,{className:t.toggleButton,title:n("open",{productName:l}),onClick:z,isCollapsed:!0})}),(X||I>0&&S)&&(0,Le.jsxs)("div",{className:t.collapsible,onFocus:()=>{},children:[X&&(0,Le.jsx)(Wm,{matches:Y,selectedIndex:-1}),I>0&&S&&(0,Le.jsx)(Ct,{children:(0,Le.jsx)($m,{suggestions:k,selectedIndex:R,reverse:v==="above"})})]})]})},KI=Lz;var lg=E(De());var Mo=E(Q());var rl=E(Q());function Xm(e){return e.contentEditable==="true"}function Oz(e){let t=0,n=0,r=window.getSelection();if(r.rangeCount!==0){let o=r.getRangeAt(0),s=o.cloneRange();s.selectNodeContents(e),s.setEnd(o.endContainer,o.endOffset),n=s.toString().length,s.selectNodeContents(e),s.setEnd(o.startContainer,o.startOffset),t=s.toString().length}return{selectionStart:t,selectionEnd:n}}function GI(e){let{selectionStart:t,selectionEnd:n}=Xm(e)?Oz(e):e;return[t,n]}function qI(e){let[,t]=(0,rl.useState)(),n=(0,rl.useRef)(null);return n.current=GI(e),(0,rl.useEffect)(()=>{let r=()=>{var a;let[o,s]=(a=n.current)!=null?a:[],i=GI(e);(!i||o!==i[0]||s!==i[1])&&(n.current=i,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 YI(e,t){if(!t)return;let n=e,{value:r}=n,[o,s]=t,i=r.match(dd);if(!i||i.length===0)return;let a=0;i.find(l=>{let c=r.indexOf(l,a);return o>c&&s<c+l.length?(n.selectionStart=c,n.selectionEnd=c+l.length,!0):(a=c+l.length,!1)})}var XI=E(Q()),Nz=["div","span","mark","strong","b","i","u","em"];function tx(e,t,n=0){var s;let r=e[e.length-1],o=typeof r=="object"&&r!==null?(s=r.props)==null?void 0:s.tagName:void 0;if(o==="br")return e.pop(),[...e,...t,r];if(Nz.includes(o)){let i=Array.isArray(r.props.children)?r.props.children:[r.props.children];return[...e.slice(0,e.length-1),(0,XI.cloneElement)(r,{children:tx(i,t,n+1)})]}return[...e,...t]}function Pi(e){return e.tagName.toLowerCase()==="textarea"}var QI={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 t_=E(De());var rg=E(Q());var ol=E(Q());function ZI(e,t){let n;return[(...r)=>{window.cancelAnimationFrame(n);let o=t?t(...r):r;n=window.requestAnimationFrame(()=>{e(...o)})},()=>window.cancelAnimationFrame(n)]}function Qm(e){let t=(0,ol.useRef)(null),[n,r]=(0,ol.useState)(!1);return(0,ol.useEffect)(()=>{var u;let o=!1,s=Number.parseFloat((u=window.getComputedStyle(document.body).zoom)!=null?u:"1"),[i,a]=ZI((f,d)=>{let p=t.current;if(!p)return;let h=f/s,y=d/s,S=p.getBoundingClientRect(),g=h>S.x&&h<S.x+S.width&&y>S.y&&y<S.y+S.height;g&&!o?(o=!0,r(!0)):!g&&o&&(o=!1,r(!1))},({clientX:f,clientY:d})=>[f,d]),[l,c]=ZI(()=>{o=!1,r(!1)});return e.addEventListener("mousemove",i),e.addEventListener("mouseleave",l),()=>{a(),c(),e.removeEventListener("mousemove",i),e.removeEventListener("mouseleave",l)}},[t]),[t,n]}function Zm(e){return e.replace(/[.*+^${}()|[\]\\]/g,"\\$&")}function Jm(e){return t=>{e.forEach(n=>{typeof n=="function"?n(t):n!=null&&(n.current=t)})}}function JI(e){return e!=null}var e_=E(De()),eg=E(Q());var Io={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 nx=E(A()),tg=(0,eg.forwardRef)((o,r)=>{var s=o,{className:e,children:t}=s,n=ie(s,["className","children"]);let i=(0,eg.useRef)(null),a=F("TabCompletion",Io);return(0,nx.jsx)("div",_(b({ref:Jm([i,r]),className:(0,e_.default)(e,a.popoverContentContainer)},n),{children:(0,nx.jsx)("div",{className:a.popoverContent,children:t})}))});var ks=E(A()),Dz=e=>t=>{let n=S0(t);return"top"in n&&(n.width=e.width-(t.left-e.left)-10),n},Fz=({inputElement:e,boundaryRef:t,inputStyle:n,children:r,suggestion:o})=>{let s=F("TabCompletion",Io),i=pm(),a=(0,rg.useMemo)(()=>Dz(e.getBoundingClientRect()),[e]),[l,c]=Qm(e);return(0,rg.useEffect)(()=>{c?i.open():i.close()},[c]),(0,ks.jsxs)("span",{children:[(0,ks.jsx)("mark",{ref:Jm([l,i.triggerRef]),className:(0,t_.default)(s.matchKeyword,{[s.hover]:c}),"aria-haspopup":"dialog","aria-expanded":i.opened?"true":"false",children:r}),i.opened&&(0,ks.jsx)(qa,{className:s.popover,triggerRef:i.triggerRef,boundaryRef:t,position:"below",align:"start",toStyle:a,children:(0,ks.jsx)(tg,{style:n,children:(0,ks.jsx)("div",{className:s.hintText,children:o})})})]})},ng=class extends To{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=>_(b({},o),{keywordRegex:new RegExp(`\\b${Zm(o.keyword)}\\b`,"i")})),this.keywordMatches=r.keywordMatches),this.usedKeywordMatches.clear(),n}match(n){let r=this.preparedKeywordMatches.map(s=>{if(this.usedKeywordMatches.has(s))return null;let i=n.match(s.keywordRegex);if(!i)return null;let a=n.charAt(i.index-1),l=n.charAt(i.index+s.keyword.length);return a==="{"&&l==="}"?null:{index:i.index,length:i[0].length,match:i[0],matchString:i[0],suggestion:s.suggestion,preparedKeywordMatch:s,valid:!0}}).filter(JI);if(r.length===0)return null;let o=r.reduce((s,i)=>i.index<s.index?i:s);return this.usedKeywordMatches.add(o.preparedKeywordMatch),o}replaceWith(n,r){return(0,ks.jsx)(Fz,{inputElement:r.inputElement,suggestion:r.suggestion,inputStyle:r.inputStyle,boundaryRef:r.boundaryRef,children:n},`keyword_${r.matchString}_${r.key}`)}asTag(){return"mark"}};var n_=E(De());var rx=E(A()),zz=({inputElement:e,children:t})=>{let n=F("TabCompletion",Io),[r,o]=Qm(e);return(0,rx.jsx)("mark",{ref:r,className:(0,n_.default)(n.matchPlaceholder,{[n.hover]:o}),children:t})},og=class extends To{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,rx.jsx)(zz,{inputElement:n.inputElement,children:t},`placeholder_${n.matchString}_${n.key}`)}asTag(){return"mark"}};var ig=E(De());var sn=E(Q());function r_(e,t){let n=new URL(e),r=n.searchParams.get("redirect");if(r){let o=new URL(r,n.origin);return t.forEach((s,i)=>{o.searchParams.set(i,s)}),n.searchParams.set("redirect",`${o.pathname}${o.search}${o.hash}`),n.toString()}return t.forEach((o,s)=>{n.searchParams.set(s,o)}),n.toString()}var ox=E(A()),o_=()=>(0,ox.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,ox.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 Yr=E(Q());var i_=E(R0());var s_={root:"dd-ky-Bv",content:"dd-kV5e1"};function sg(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(s){return null}}function sx(e){return e.replace("https://www.","").replace("https://","")}var rr=E(A()),Hz=3,Bz=e=>({image:e.image||"",text:e.text,id:e.id,title:e.title}),Uz=({onSelectLink:e,onDismiss:t,placeholder:n,visitUrlText:r,linkCount:o=Hz})=>{let s=F("LinkSearch",s_),[i,a]=(0,Yr.useState)(""),l=ve(),c=K(oI("url")),u=K(_E("URL")),f=(0,Yr.useMemo)(()=>u.map(Bz),[u]),[d,p]=(0,Yr.useState)(f.length-1),h=J("fallbackImage"),y=v=>{let x=v.target;a(x.value)},S=(v,x)=>{v.stopPropagation(),v.preventDefault(),window.open(x,"_blank")},g=v=>{var C;let x=d-1<0?f.length-1:d-1,T=d+1===f.length?0:d+1;v.code==="Escape"&&(a(""),t()),v.code==="ArrowUp"&&p(x),v.code==="ArrowDown"&&p(T),v.code==="Enter"&&e(((C=f[d])==null?void 0:C.text)||i)},m=(0,Yr.useCallback)((0,i_.default)(v=>{l(Bs({query:v,type:"URL",tags:["link-search"]}))},300),[]);return(0,Yr.useEffect)(()=>{i&&m(i)},[i]),(0,Yr.useEffect)(()=>()=>{l(Gd())},[]),(0,rr.jsxs)("div",{className:s.root,children:[(0,rr.jsx)(Ct,{withDivider:!0,children:(i?f:c).slice(0,o).map((v,x)=>(0,rr.jsx)(fe,{selected:d===x,onClick:()=>e(v.text),"data-testid":"linksearch-suggestion",children:(0,rr.jsxs)(Ee,{children:[(0,rr.jsx)(Ee.Image,{src:sg(v,"small",h||void 0),title:v.title||v.text}),(0,rr.jsxs)(Ee.Content,{className:s.content,cropText:!0,children:[(0,rr.jsx)(Ee.Title,{children:v.title||sx(v.text)}),v.title&&sx(v.text)]}),(0,rr.jsx)(fe.Actions,{children:(0,rr.jsx)(fe.ActionButton,{label:r,onClick:T=>S(T,v.text)})})]})},v.text))}),(0,rr.jsx)(ru,{value:i,onChange:y,autoFocus:!0,placeholder:n,onKeyUp:g})]})},a_=Uz;var ix={};dt(ix,{enUS:()=>Vz,nlNL:()=>Wz});var Vz={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"}]},Wz={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 It=E(A()),$z=(0,sn.forwardRef)((e,t)=>{let n=F("TabCompletion",Io);return(0,It.jsx)("mark",{ref:t,className:(0,ig.default)(n.matchSelection)},"selection-start")}),jz=({startRef:e,boundaryRef:t,inputStyle:n,inputElement:r,children:o})=>{let s=ae(ix),i=F("TabCompletion",Io),a=J("addToPersonalCollection"),l=K(ra("/admin/personal-collection/new")),c=K(v=>{var x;return(x=v.conversation.current)==null?void 0:x.profileCode}),u=K(Wn)!==null,f=(0,sn.useRef)(null),d=(0,sn.useRef)(null),[p,h]=(0,sn.useState)(null),y=ve(),S=pm(document.activeElement===r),[g]=(0,sn.useState)(()=>document.createRange());S.triggerRef.current=g,(0,sn.useEffect)(()=>()=>g.detach(),[]),(0,sn.useEffect)(()=>{let v=e.current,x=f.current;!v||!x||(g.setStart(v,0),g.setEnd(x,0))},[e.current,f.current]),hs(()=>{S.close()});let m=(0,sn.useCallback)(v=>{let x=g.toString(),T=/^http(s?):\/\//.test(v)?v:`https://${v}`,C=`[${x}](${T})`;y(Tn({text:C,suggestion:{text:C,source:"search-url",type:"url"},eventMetrics:{inputType:"mouse"},replace:"selection"}))},[]);return(0,It.jsxs)("span",{children:[(0,It.jsx)("mark",{ref:f,className:(0,ig.default)(i.matchSelection),"aria-haspopup":"dialog","aria-expanded":S.opened?"true":"false",children:o}),S.opened&&(0,It.jsx)(qa,{className:i.popoverRoot,triggerRef:S.triggerRef,boundaryRef:t,position:"above",align:"start",children:(0,It.jsxs)(tg,{style:n,ref:d,children:[(0,It.jsxs)("div",{className:(0,ig.default)(i.selectionOptions,{[i.selectionOptionsIsHidden]:p!==null}),children:[(0,It.jsxs)("button",{type:"button",tabIndex:p===null?-1:void 0,className:i.selectionOptionsButton,onClick:()=>h("insertLink"),children:[(0,It.jsx)(o_,{}),(0,It.jsx)("span",{children:"\xA0"}),(0,It.jsx)("span",{children:s("insertLink")})]}),a&&l&&(0,It.jsx)("button",{type:"button",tabIndex:p===null?-1:void 0,className:i.selectionOptionsButton,onClick:()=>{let v=g.toString(),x=new URLSearchParams({text:v});u&&c&&x.set("profile",c);let T=r_(l,x);window.open(T,"_blank")},children:(0,It.jsx)("span",{children:s("addToPersonalCollection")})})]}),p==="insertLink"&&(0,It.jsx)(a_,{placeholder:s("linkInputPlaceholder"),visitUrlText:s("visitUrl"),onSelectLink:m,onDismiss:()=>{h(null),S.close()}})]})})]},"selection-end")},ag=class extends To{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,sn.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 s=this.foundIndex===0?r:o,i=s>=this.charCount&&s<=this.charCount+n.length?{index:s-this.charCount,length:0,match:"",valid:!0}:null;i&&this.foundIndex++;let a=this.foundIndex===1;return i&&a?this.charCount+=s-this.charCount:this.charCount+=n.length,i?b({isStart:a},i):null}replaceWith(n,r){return r.isStart?(0,It.jsx)($z,{ref:this.startRef}):(0,It.jsx)(jz,{inputElement:r.inputElement,startRef:this.startRef,boundaryRef:r.boundaryRef,inputStyle:r.inputStyle})}asTag(){return"mark"}};var _o=E(A()),Kz=({enabled:e,content:t,tabText:n,showTabHint:r,showTabCompletion:o,showStyleSuggestions:s,keywordMatches:i,inputElement:a,source:l})=>{let c=F("TabCompletion",QI),u=J("insertLink"),f=J("addToPersonalCollection"),d=J("showMidSentenceSuggestions"),p=J("inlineSuggestions"),h=qI(a),y=(0,Mo.useRef)(null),S=K(kt);(0,Mo.useEffect)(()=>{Pi(a)&&h&&YI(a,h)},[h]);let g=(0,Mo.useCallback)(x=>{if(!o||!n)return x;let T=[(0,_o.jsx)("span",{className:c.resetIndent,children:"\u200B"},"u200B"),(0,_o.jsx)("span",{"data-testid":"tab-completion",className:(0,lg.default)(c.tabText,c.resetIndent),"data-source":l,children:n},"tabText")];return r&&T.push((0,_o.jsx)("span",{className:(0,lg.default)(c.hint,c.resetIndent),children:(0,_o.jsx)(ld,{keyCode:"tab"},"tabHint")},"tabHint")),tx(x,T)},[o,n,r]),m=(0,Mo.useMemo)(()=>{let x=[];return(u||f)&&x.push(new ag("selection")),x.push(new og("placeholders")),s&&x.push(new ng("keywords")),x},[p,u,f,s]),v=(0,Mo.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||!S?null:(0,_o.jsxs)("div",{ref:x=>{x!=null&&x.parentElement&&(y.current=x==null?void 0:x.parentElement)},className:c.root,style:v,children:[(0,_o.jsx)(Ss,{tagName:"span",containerTagName:"div",className:(0,lg.default)(c.container,c.agentText),disableLineBreaks:Pi(a),content:t||"\u200B",onAfterParse:g,matchers:m,selection:h,keywordMatches:i,inputElement:a,inputStyle:v,boundaryRef:y,inlineSuggestionsOnlyAtEnd:!d}),(0,_o.jsx)("br",{})]},"tab-completion")},Gz=e=>{var g,m,v;let{input:t,ui:n,settings:r,styleSuggestions:o,conversation:s}=e,i=Qi({input:t}),a=(i==null?void 0:i.text)||"",l=(i==null?void 0:i.source)||"",c=(g=t.html)!=null?g:Za(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}=s,{showTabCompletion:h,visible:y,showStyleSuggestions:S}=r;return{showTabHint:d,showStyleSuggestions:S,showTabCompletion:h&&qr(e),content:c,tabText:f,source:l,keywordMatches:(v=(m=o.list)==null?void 0:m.keywordMatches)!=null?v:[],enabled:y&&p!==!1}},l_=tb(Gz)(Kz);var sr=E(Q());var qz={token:null,interval:null},ax=me("passwordlessToken/getTemporaryPasswordlessToken",(e,t)=>M(null,null,function*(){let{deepdeskAPI:n}=t.extra;return{token:yield n.requestPasswordlessToken()}})),lx=me("passwordlessToken/pollPasswordlessToken",(e={},t)=>{let{interval:n=1e3*60*10}=e,{dispatch:r}=t;return r(ax()),setInterval(()=>r(ax()),n)}),c_=Pe({name:"passwordlessToken",initialState:qz,reducers:{stopPollPasswordlessToken(e){e.interval&&clearInterval(e.interval),e.interval=null}},extraReducers:e=>{e.addCase(ax.fulfilled,(t,n)=>{t.token=n.payload.token}),e.addCase(lx.fulfilled,(t,n)=>{t.interval=n.payload})}}),{stopPollPasswordlessToken:u_}=c_.actions,d_=c_.reducer;function Yz(e){return"buttonText"in e&&"eventName"in e}function f_(e){if(e)return Yz(e)?{label:e.buttonText,event:e.eventName,value:e.payload}:e}function Xz(e){return e==null?void 0:e.map(t=>f_(t))}function cg(e){return typeof e!="string"?void 0:e.trim().toLowerCase()||void 0}function Pu(e,t){let n=cg(t);n&&e.add(n)}function Qz(e){var r,o,s;let t=new Set,n=new Set;if(!Array.isArray(e))return{codes:t,names:n};for(let i of e){if(!i||typeof i!="object")continue;let a=i,l=typeof a.assistant=="object"?a.assistant:void 0;((s=(o=(r=a.isSilent)!=null?r:a.is_silent)!=null?o:l==null?void 0:l.isSilent)!=null?s:l!=null&&l.is_silent)&&(Pu(t,typeof a.assistant=="string"?a.assistant:l==null?void 0:l.code),Pu(n,a.assistantName),Pu(n,a.assistant_name),Pu(n,a.displayName),Pu(n,a.display_name))}return{codes:t,names:n}}function cx(e,t){var s,i,a;let{codes:n,names:r}=Qz(t);if(n.size===0&&r.size===0)return!1;let o=(i=cg(e.code))!=null?i:cg((s=e.rule)==null?void 0:s.label);return o?n.has(o):[e.name,e.title,(a=e.rule)==null?void 0:a.name].some(l=>{let c=cg(l);return c!==void 0&&(r.has(c)||n.has(c))})}function Zz(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return t}var p_=Yt([dC,Hd,Qa],(e,t,n)=>(t?e.filter(i=>!i.externalConversationId||i.externalConversationId===t):e).filter(i=>!cx(i,n)).map(i=>{var c;let a=f_(i.callToAction),l=Xz(i.callToActions);return _(b(b(b(b({text:i.response,title:i.name},a?{callToAction:a}:{}),l!=null&&l.length?{callToActions:l}:{}),i.message!==void 0?{message:i.message}:{}),(c=i.sources)!=null&&c.length?{sources:i.sources}:{}),{editable:i.editable,isLoading:i.isLoading,evaluationId:i.evaluationId,rule:{id:Zz(i.code),label:i.code,name:i.name,description:i.name}})}));var ug=E(Q()),dx=E(De());var ux=E(A()),sl=()=>(0,ux.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 512 512",xmlns:"http://www.w3.org/2000/svg",children:(0,ux.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 m_={root:"dd-WcEru",entity:"dd-LfP8y",entityText:"dd-L-v0f",iconWrapper:"dd-9Deh1",icon:"dd-tM7E2",iconClicked:"dd-EEdDL"};var Xr=E(A()),Jz=({entities:e})=>{let t=F("EntitiesWidgetList",m_),[n,r]=(0,ug.useState)(void 0),o=nt(),s=()=>{r(void 0)},i=a=>{e&&(r(e.indexOf(a)),Lr(a.text),o("entity copied",{entity:a,type:"copy"}))};return(0,ug.useEffect)(()=>{let a=setTimeout(s,500);return()=>{clearTimeout(a)}},[n]),!e||e.length===0?null:(0,Xr.jsx)("div",{className:t.root,"data-testid":"widget-entities-list",children:e.map((a,l)=>(0,Xr.jsxs)("button",{title:a.text,className:t.entity,type:"button",onClick:()=>i(a),children:[(0,Xr.jsx)("span",{className:t.entityText,children:a.text}),(0,Xr.jsxs)("span",{className:t.iconWrapper,children:[(0,Xr.jsx)("span",{className:(0,dx.default)(t.icon),children:(0,Xr.jsx)(sl,{})}),(0,Xr.jsx)("span",{className:(0,dx.default)(t.icon,n===l&&t.iconClicked),children:(0,Xr.jsx)(sl,{})})]})]},a.text))})},g_=Jz;var fx=E(A()),h_=()=>(0,fx.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:(0,fx.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 E_=E(Q());var y_={root:"dd-ohnXe",trigger:"dd-7i-S3",button:"dd-t53Cg",nav:"dd-qZFnm",item:"dd-FZC0F"};var v_={root:"dd-nazq3",rotation:"dd-3EHTv"};var x_=E(A()),e9=({size:e=12})=>{let t=F("LoadingSpinner",v_);return(0,x_.jsx)("span",{"data-testid":"loading-spinner",style:{width:`${e}px`,height:`${e}px`},className:t.root})},S_=e9;var px=E(A()),w_=()=>(0,px.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 0 512 512",fill:"currentColor",children:(0,px.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 Au=E(A()),b_=e=>(0,Au.jsxs)("svg",_(b({xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 448 512","aria-labelledby":"checkTitle"},e),{children:[(0,Au.jsx)("title",{id:"checkTitle",children:"Check"}),(0,Au.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 mx={};dt(mx,{enUS:()=>t9,nlNL:()=>n9});var t9={error:[{type:0,value:"Something went wrong"}]},n9={error:[{type:0,value:"Er ging iets fout"}]};var Bn=E(A()),r9=3e3,o9=({assistantOptions:e})=>{let t=F("OnDemandAssistants",y_),n=ae(mx),r=(0,E_.useRef)(),o=ve(),s=Ll(Rn),i=K(Qa),a=nt(),l=i.filter(d=>d.isPinned),c=i.filter(d=>!d.isPinned),u=()=>M(null,null,function*(){return e.attachments&&e.attachments.length>0?e.attachments:o(((d,p,h)=>M(null,null,function*(){let y;if(e.transcript==="in-memory-transcript"){let S=h.dynamicThunkObject.conversationQuery;if(S){let g=yield S();y=Array.isArray(g)?g:void 0}}else Array.isArray(e.transcript)&&(y=e.transcript);return iy({transcript:y})})))}),f=(d,p=!1)=>M(null,null,function*(){clearTimeout(r.current);let h=yield u();a("trigger on demand assistant",{assistantCode:d}),yield s.call(b(_(b({},e),{assistantCode:d,silent:p}),h.length>0?{attachments:h}:{})),r.current=setTimeout(()=>s.reset(),r9)});return i.length===0?null:(0,Bn.jsxs)("div",{className:t.root,children:[l.map(({assistant:d,assistantName:p,displayName:h,isSilent:y})=>(0,Bn.jsx)("button",{type:"button",className:t.button,disabled:s.state==="loading",onClick:()=>f(d,y),children:h||p},d)),c.length>0&&(0,Bn.jsxs)(Xe,{placement:"top-end",children:[(0,Bn.jsx)(Xe.Trigger,{className:t.trigger,disabled:s.state==="loading",children:(0,Bn.jsx)(Dm,{"data-testid":"trigger"})}),(0,Bn.jsx)(Xe.Content,{className:t.nav,"data-testid":"popover",children:c.map(({assistant:d,assistantName:p,displayName:h,isSilent:y})=>(0,Bn.jsx)(Xe.Button,{className:t.item,disabled:s.state==="loading",onClick:()=>f(d,y),children:h||p},d))})]}),s.state==="loading"&&(0,Bn.jsx)(S_,{}),s.state==="done"&&(0,Bn.jsx)(b_,{"data-testid":"trigger-done"}),s.state==="error"&&(0,Bn.jsx)(VP,{trigger:(0,Bn.jsx)(w_,{}),children:n("error")})]})},C_=o9;var Ai=E(Q());var Iu={};dt(Iu,{enUS:()=>s9,nlNL:()=>i9});var s9={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"}]},i9={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 gx={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 _t=E(A()),a9=500,l9=100,c9=({content:e,onChange:t,onCopy:n})=>{let r=(0,Ai.useRef)(null),o=F("WidgetCue",gx);return(0,Ai.useEffect)(()=>{let s=r.current;if(!s)return;s.style.setProperty("height","0px");let i=Math.min(Math.max(s.scrollHeight,l9),a9);s.style.setProperty("height",`${i}px`)},[e]),(0,_t.jsx)("textarea",{ref:r,className:o.editableCue,onCopy:n,onChange:t,value:e})},u9=({cue:e,onCallToAction:t,onRemove:n,onCopy:r,onUse:o,onSourceClick:s})=>{var S;let i=F("WidgetCue",gx),a=ae(Iu),l=nt(),c=J("hasKeyboardInput"),[u,f]=(0,Ai.useState)(e.text),d=g=>{let m=g?_(b({},e),{callToAction:g}):e;t&&t(u,m),n(e)},p=(g,m)=>{r&&r(g,e),m&&$o(m,i.fadeup)},h=g=>{o&&o(g,e)},y=g=>{g.preventDefault(),g.stopPropagation(),n(e)};return(0,Ai.useEffect)(()=>{l("Assistant response displayed",{evaluationId:e.evaluationId,assistantCode:e.rule.label,assistantOutput:e.text})},[]),(0,_t.jsxs)(fe,{"data-testid":"cue",children:[(0,_t.jsx)(Ee,{children:(0,_t.jsxs)(Ee.Content,{children:[e.title&&(0,_t.jsx)(Ee.Title,{className:i.title,"data-testid":"widget-cue-title",children:e.rule.label.startsWith("__")?a(e.rule.label):e.title}),e.message&&(0,_t.jsx)("p",{className:i.ctaMessage,children:e.message}),e.editable?(0,_t.jsx)(c9,{content:u,onCopy:()=>{let g=document.getSelection();g&&p(g.toString())},onChange:g=>{var m;return f((m=g.target.value)!=null?m:"")}}):(0,_t.jsx)(hi,{content:e.text,sources:e.sources,onSourceClick:g=>s==null?void 0:s(g,e),useLabel:a("useCue"),copyLabel:a("copyCue"),onCopy:p,onUse:c?h:void 0})]})}),(0,_t.jsxs)(fe.ButtonsContainer,{children:[(0,_t.jsxs)("div",{className:i.actions,children:[(0,_t.jsx)(fe.Button,{onClick:g=>{var m;return p((m=pf(u,"reply")[0])!=null?m:u,g.target)},variant:"primary",children:a("copyCue")}),e.callToAction&&(0,_t.jsx)(fe.Button,{onClick:()=>d(),variant:"primary",children:e.callToAction.label}),(S=e.callToActions)==null?void 0:S.map((g,m)=>(0,_t.jsx)(fe.Button,{onClick:()=>d(g),variant:"primary",children:g.label},`${g.event}-${g.label}-${m}`)),(0,_t.jsx)(fe.Button,{onClick:y,variant:"secondary",children:a("removeCue")})]}),(0,_t.jsx)(xf,{evaluationId:e.evaluationId,assistantCode:e.rule.label,assistantOutput:e.text,feedbackType:"assistant"})]})]})},T_=u9;var il=E(A()),d9=({cues:e})=>{let t=ve(),n=un(),r=ae(Iu),o=nt(),s=K(Qa),i=d=>{t(gf({code:d.rule.label})),o("Assistant response closed",{evaluationId:d.evaluationId,assistantCode:d.rule.label,assistantOutput:d.text})},a=(d,p)=>{Lr(d),o("Assistant response copied",{evaluationId:p.evaluationId,assistantCode:p.rule.label,assistantOutput:p.text,copiedText:d})},l=(d,p)=>{var h;p.callToAction&&(t(mf(p)),o("Assistant call to action",{evaluationId:p.evaluationId,assistantCode:p.rule.label,assistantOutput:p.text,eventName:p.callToAction.event,value:(h=p.callToAction.value)!=null?h:d}))},c=(d,p)=>{var h;n.send(ro,{text:d,suggestion:{source:"assistant",assistantCode:(h=p.rule)==null?void 0:h.label,sourceText:d}}),o("Assistant response used",{evaluationId:p.evaluationId,assistantCode:p.rule.label,assistantOutput:p.text,usedText:d})},u=(d,p)=>{o("Assistant source clicked",{evaluationId:p.evaluationId,assistantCode:p.rule.label,source:d})},f=e.filter(d=>!cx(d,s));return(0,il.jsx)(il.Fragment,{children:f.map(d=>d.isLoading?(0,il.jsx)(gm,{title:d.rule.label.startsWith("__")?r(d.rule.label):d.title},d.rule.id):(0,il.jsx)(T_,{cue:d,onCallToAction:l,onRemove:i,onCopy:a,onUse:c,onSourceClick:u},d.evaluationId))})},k_=d9;var dg=E(Q());var R_={root:"dd-cvTAY",label:"dd-QWQxD",value:"dd-WSUHF",copyButton:"dd-67o9H",copyButtonText:"dd-oos-l",isTrue:"dd--1g2O",isFalse:"dd-sz2ir"};var xn=E(A());function f9(e,t){return t.split(".").reduce((n,r)=>!n||typeof n!="object"||!(r in n)?null:n[r],e)}var P_=({data:e,schema:t})=>{let n=F("WidgetCustomData",R_),r=o=>{Lr(o)};return(0,dg.useEffect)(()=>{Z.info("Custom data",e,t)},[e]),(0,xn.jsx)("dl",{className:n.root,children:t.map(o=>{let s=f9(e,o.path);return(0,xn.jsxs)(dg.Fragment,{children:[(0,xn.jsx)("dt",{className:n.label,children:o.label}),(0,xn.jsx)("dd",{className:n.value,children:o.type==="boolean"&&s?(0,xn.jsx)("span",{className:n.isTrue,children:o.trueValue}):o.type==="boolean"&&!s?(0,xn.jsx)("span",{className:n.isFalse,children:o.falseValue}):o.type==="array"&&Array.isArray(s)&&s.length>0?(0,xn.jsxs)("button",{type:"button",onClick:()=>r(s.join(", ")),className:n.copyButton,children:[(0,xn.jsx)("span",{className:n.copyButtonText,children:s.join(", ")}),(0,xn.jsx)(sl,{})]}):typeof s=="string"||typeof s=="number"?(0,xn.jsxs)("button",{type:"button",onClick:()=>r(`${s}`),className:n.copyButton,children:[(0,xn.jsx)("span",{className:n.copyButtonText,children:s}),(0,xn.jsx)(sl,{})]}):"-"})]},o.label)})})};var I_=E(Q());var p9=/(https?:\/\/[^\s]+)/,A_=e=>e.split(" ").find(t=>p9.test(t));var or=E(A()),m9=({suggestion:e,lines:t,onUse:n})=>{var f;let r=e.text||e.url||e.message,o=A_(r),s=ae(yu),i=J("showImages"),a=J("fallbackImage"),l=J("hasKeyboardInput"),c=d=>{d.preventDefault(),d.stopPropagation(),l&&n(r)},u=(0,I_.useCallback)(d=>{window.open(o,"_blank"),d.stopPropagation(),d.preventDefault()},[o]);return(0,or.jsxs)(fe,{onClick:l?c:void 0,"data-testid":"edit-suggestion",children:[(0,or.jsxs)(Ee,{children:[i&&e.image&&(0,or.jsx)(Ee.Image,{src:sg(e,"small",a||void 0),title:e.title}),(0,or.jsxs)(Ee.Content,{children:[e.title&&(0,or.jsx)(Ee.Title,{"data-testid":"widget-suggestion-title",children:e.title}),e.searchKeywords&&((f=e.searchKeywords)==null?void 0:f.length)>0&&(0,or.jsx)(fe.Labels,{labels:e.searchKeywords}),(0,or.jsx)(Ee.Content,{cropText:t==="single",lineClamp:t==="multiple",children:r})]})]}),(0,or.jsxs)(fe.Actions,{children:[o&&(0,or.jsx)(fe.ActionButton,{onClick:u,label:s("visitUrl")}),l&&(0,or.jsx)(fe.ActionButton,{primary:!0,onClick:c,label:s("useSuggestion")})]})]})},__=m9;var _u=E(A()),g9=({lines:e,suggestions:t})=>{let n=un(),r=(o,s)=>{n.send(ro,{text:o,suggestion:_(b({},s),{source:s.source,sourceText:s.text})})};return(0,_u.jsx)(_u.Fragment,{children:t.map(o=>(0,_u.jsx)(__,{suggestion:o,lines:e,onUse:s=>r(s,o)},o.text||o.url||o.message))})},M_=g9;var Mu={};dt(Mu,{enUS:()=>h9,nlNL:()=>y9});var h9={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"}]},y9={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 Ii={root:"dd-W9VCG",loginText:"dd--dS6t",stateText:"dd-348OC",footer:"dd-tvofr",shortcutList:"dd-MuKK-",shortcut:"dd-5CnK9",footerShortcut:"dd-dH7XJ",link:"dd-DRo0x",interactiveAssistantTabs:"dd-eSP1-",interactiveAssistantTab:"dd-CwcHD",interactiveAssistantTabActive:"dd-GzRs-"};var le=E(A()),L_=(e,t)=>{let n=K(kt);(0,sr.useEffect)(()=>n?t.every(r=>!!r)?e():()=>{}:()=>{},[...t,n])},v9=({onLogIn:e})=>{let t=F("Widget",Ii),n=J("isEmbedded"),r=J("adminUrl");return(0,le.jsx)("div",{className:t.loginText,children:(0,le.jsx)("div",{children:(0,le.jsx)(qm,{isEmbedded:n,loginUrl:r,onLogIn:e})})},"login")},hx=({text:e})=>{let t=F("Widget",Ii);return(0,le.jsx)("div",{className:t.stateText,children:(0,le.jsx)("div",{children:(0,le.jsx)("p",{children:e})})},"notification")},S9=()=>{let e=ae(Mu),t=ve(),n=F("Widget",Ii),r=J("showSearch"),o=J("isEmbedded"),s=K(ra("/admin/")),i=un(),a=J("productName"),l=nt();return L_(()=>{if(o)return t(lx()),()=>{t(u_())}},[t,o]),!r&&!s?null:(0,le.jsxs)("div",{className:n.shortcutList,children:[r&&(0,le.jsx)(fe.Button,{"data-testid":"shortcut-search","aria-label":e("linkSearch"),className:n.shortcut,icon:(0,le.jsx)(el,{}),onClick:()=>{i.send("ShowCommandPalette",{isOpen:!0}),l("open search",{via:"widget-shortcut"})},children:e("linkSearch")}),s&&(0,le.jsx)(fe.Button,{as:"a",target:"_blank",icon:(0,le.jsx)(h_,{}),href:s,"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})})]})},x9=({title:e,content:t})=>{let n=ae(Mu),[r,o]=(0,sr.useState)(!0);return r?(0,le.jsx)(Ar,{"data-testid":"custom-data-banner",type:"custom-data-banner",title:e,children:(0,le.jsx)(Ct,{withDivider:!0,children:(0,le.jsxs)(fe,{children:[(0,le.jsx)(Ee,{children:(0,le.jsx)(Ee.Content,{children:(0,le.jsx)(hi,{content:t})})}),(0,le.jsx)(fe.ButtonsContainer,{children:(0,le.jsx)(fe.Button,{onClick:()=>o(!1),children:n("close")})})]})})}):null},w9=()=>{let e=ve(),t=K(iu),n=K(PA),r=K(p_),o=K(xE),s=K(Nm),i=K(zm),a=K(nr),l=K(Wn);return(0,sr.useEffect)(()=>{o&&!n&&Z.warn("Custom data provided, but no schema.")},[o,n]),L_(()=>{t.forEach(({type:c})=>{c==="entities"?e(Cr()):fd.includes(c)||e(Tr(c))})},[e,l,a,t]),(0,sr.useEffect)(()=>{r.length>0&&!t.some(c=>c.type==="cues")&&Z.warn("Received cues, but cues are not configured in widget.")},[t,r]),(0,le.jsx)(sr.Fragment,{children:t.map(({type:c,title:u,amount:f,lines:d,schema:p,property:h})=>{var y,S;switch(c){case"entities":return s&&s.length>0&&(0,le.jsx)(Ar,{type:c,title:u,"data-testid":`type-${c}`,children:(0,le.jsx)(g_,{entities:s})},c);case"cues":return r&&r.length>0&&(0,le.jsx)(Ar,{type:c,title:u,"data-testid":`type-${c}`,children:(0,le.jsx)(Ct,{withDivider:!0,children:(0,le.jsx)(k_,{cues:r})})},c);case"custom-data-banner":return o&&h&&o[h]&&(0,le.jsx)(x9,{title:u,content:String(o[h])},c);case"custom-data":return o&&p&&(0,le.jsx)(Ar,{type:c,title:u,"data-testid":`type-${c}`,children:(0,le.jsx)(Ct,{withDivider:!0,children:(0,le.jsx)(P_,{data:o,schema:p})})},c);default:return((S=(y=i[c])==null?void 0:y.suggestions)==null?void 0:S.length)>0&&(0,le.jsx)(Ar,{type:c,title:u,"data-testid":`type-${c}`,children:(0,le.jsx)(Ct,{withDivider:!0,children:(0,le.jsx)(M_,{lines:d,contentType:c,suggestions:i[c].suggestions.slice(0,f)||[]})})},c)}})})},yx=({children:e})=>{let t=F("Widget",Ii);return(0,le.jsx)("div",{className:t.footer,children:e})},vx=({children:e})=>{let t=F("Widget",Ii);return(0,le.jsx)("div",{className:t.root,"data-testid":"widget",children:e})},b9=({onLogIn:e,knowledgeAssistOptions:t={},assistantOptions:n={transcript:"in-memory-transcript"},openAdminFeedback:r})=>{var x;let o=ae(Mu),s=F("Widget",Ii),i=ve(),a=K(Xi),l=K(kt),c=K(Hd),u=K(nr),f=K(RA("knowledge-assist")),d=K(AA),p=K(mC),h=K(pC),y=(x=d.find(T=>T.code===p))!=null?x:d[0],[S,g]=(0,sr.useState)(t.initialQuestion);(0,sr.useEffect)(()=>{g(t.initialQuestion)},[c,t.initialQuestion]),(0,sr.useEffect)(()=>{if(!c)return;let T=Rl(c);T&&i(ly(T))},[i,c]),(0,sr.useEffect)(()=>{if(d.length===0)return;let T=d.some(C=>C.code===p);(!p||!T)&&i(ay(d[0].code))},[d,p,i]);let m=!!f&&d.length>0&&!!y,v=(y==null?void 0:y.displayName)||(y==null?void 0:y.name)||(f==null?void 0:f.title)||"Knowledge Assistant";return a===!1?(0,le.jsx)(hx,{text:o("notSupported")}):l===!1?(0,le.jsx)(v9,{onLogIn:e}):l===null?(0,le.jsx)(hx,{text:o("waiting")}):!c||!u?(0,le.jsx)(hx,{text:o("waitingForConversation")}):(0,le.jsx)(IC,{handler:r,children:(0,le.jsx)(vx,{children:(0,le.jsxs)(vm,{initialQuestion:S,onInitialQuestionConsumed:()=>g(void 0),assistantCode:y==null?void 0:y.code,threadId:h,onThreadIdChange:T=>{y!=null&&y.code&&T!=null&&i(cy({assistantCode:y.code,threadId:T}))},evaluateKnowledgeAssistFn:Yl,children:[(0,le.jsxs)(ji,{children:[(0,le.jsx)(S9,{}),(0,le.jsx)(w9,{}),m&&(0,le.jsx)(xm,{title:v,emptyState:t.emptyState})]}),(0,le.jsxs)(yx,{children:[m&&d.length>1&&(0,le.jsx)("div",{className:s.interactiveAssistantTabs,"data-testid":"widget-interactive-assistant-tabs",children:d.map(T=>{let C=T.code===(y==null?void 0:y.code);return(0,le.jsx)("button",{type:"button","aria-pressed":C,className:C?s.interactiveAssistantTabActive:s.interactiveAssistantTab,onClick:()=>i(ay(T.code)),children:T.displayName||T.name},T.code)})}),m&&(0,le.jsx)(Sm,{}),(0,le.jsx)(C_,{assistantOptions:n})]})]},y==null?void 0:y.code)})})},O_=b9;function al(e){let t=new Range;return t.selectNodeContents(e),t}function N_(e,t,n){try{return Rs(e,t,n),!0}catch(r){return!1}}function fg(e){return"tagName"in e&&(e.tagName==="DIV"||e.tagName==="P")}function pg(e){return"tagName"in e&&e.tagName==="BR"}var Lu=/[\u200B-\u200D\uFEFF]/g;function Rs(e,t,n){let r=new Range;if(e.firstChild===null&&t===0&&n===0)return r.selectNodeContents(e),r;let o=0,s=!1;function i(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(Lu,""),f=o+u.length,d=t>=o&&t<=f,p=n>=o&&n<=f;if(d){let h=i(c,t-o);h===0&&!p?r.setStartBefore(l):r.setStart(l,h)}p&&(r.setEnd(l,i(c,n-o)),s=!0),o=f;break}case Node.ELEMENT_NODE:{if(pg(l)&&(o===t&&r.setStartBefore(l),o++,o===n)){r.setEndAfter(l),s=!0;return}for(let u=0;u<l.childNodes.length&&(a(l.childNodes[u]),!s);u++);let c=l.lastChild;fg(l)&&c&&!fg(c)&&!pg(c)&&o++;break}default:break}}if(a(e),r.startContainer===document)throw new Error("Offsets out of bound");return r}function Ou(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:s,collapsed:i}=t,a,l,c=0;function u(f){let d=f===e,p=f===n,h=f===o;switch(f.nodeType){case Node.TEXT_NODE:{let y=f.textContent;p&&(a=c+y.substring(0,r).replace(Lu,"").length),h&&(l=c+y.substring(0,s).replace(Lu,"").length),c+=y.replace(Lu,"").length;break}case Node.ELEMENT_NODE:{if(pg(f)&&f.nextSibling){c++;break}!d&&fg(f)&&f.previousSibling&&c++;for(let y=0;y<f.childNodes.length;y++){let S=p&&y===r,g=h&&y===s;if(S&&(a=c),g&&(l=c),l!==void 0||((!S||!i)&&u(f.childNodes[y]),h&&y===s-1&&(l=c),l!==void 0))break}h&&(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 Nu(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:s,collapsed:i}=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 h=d?r:0,y=p?s:void 0;l+=u.textContent.replace(Lu,"").substring(h,y);break}case Node.ELEMENT_NODE:{if(!i&&a===1&&pg(u)&&u.nextSibling){l+=`
83
83
  `;break}!f&&!i&&a===1&&fg(u)&&u.previousSibling&&(l+=`
84
- `);let h=d?r:0,y=p?Math.min(s,u.childNodes.length):u.childNodes.length;for(let S=h;S<y&&(c(u.childNodes[S]),a!==2);S++);break}default:break}p&&(a=2)}return c(e),l}var D_=(i=>(i.CUT="Cut",i.BACKSPACE="Backspace",i.DELETE="Delete",i.ERASEEOF="EraseEof",i.UNDO="Undo",i.CLEAR="Clear",i))(D_||{}),Lo=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(),s=this.cachedCaretPosition===null;if(!this.isActive)return;t===""&&this.cachedText!==""&&!this.isPossibleClearInputAction&&this.emit("submit");let i=t!==this.cachedText,a=n!==null&&n!==this.cachedHTML,l=o!==this.cachedSuggestionTextStart;if((i||a||l)&&(i?(this.cachedText=t,this.cachedHTML=n):a&&(this.cachedHTML=n),this.cachedSuggestionTextStart=o,s=!0,this.emit("change",{plainText:t,rawHTML:n,suggestionTextStart:o})),(r.start!==this.cachedSelection.start||r.end!==this.cachedSelection.end)&&(this.cachedSelection=r,s=!0,this.emit("selection",r)),!s)return;let c=this.getCaretPosition();Uo(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(D_).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 F_(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var _i=class extends Lo{constructor(){super(...arguments);this.lastKnownSelection=null}getRootNode(){return this.element.getRootNode()}getText(){let n=new Range;return n.selectNodeContents(this.element),Nu(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 s=this.element.ownerDocument.createRange();return s.setStart(o==null?void 0:o.startContainer,o==null?void 0:o.startOffset),s.setEnd(o==null?void 0:o.endContainer,o==null?void 0:o.endOffset),!s||!this.element.contains(s.startContainer)||!this.element.contains(s.endContainer)?null:s}getCaretPosition(){let n=this.getRange();if(!n||!n.collapsed||!("getBoundingClientRect"in n))return null;let r=n.getBoundingClientRect();return!F_(r)&&(n.insertNode(this.element.ownerDocument.createTextNode("\u2060")),r=n.getBoundingClientRect(),n.deleteContents(),!F_(r))?null:{top:r.top+r.height,left:r.left}}getSelection(){let n=this.getRange();if(n)return Ou(this.element,n);let r=this.lastKnownSelection;if(r&&N_(this.element,r.start,r.end))return r;let o=al(this.element);return o.collapse(!1),Ou(this.element,o)}getSelectedText(){let{start:n,end:r}=this.getSelection();return Nu(this.element,Rs(this.element,n,r))}listen(){super.listen();let n=new MutationObserver(s=>{var i,a;s.length===2&&s[0].addedNodes.length===1&&((i=s[0].addedNodes[0])==null?void 0:i.textContent)==="\u2060"&&((a=s[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 E9=["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 z_(e,t){let n="mozInnerScreenX"in window,r=document.createElement("div");r.id="input-textarea-caret-position-mirror-div";let o=r.style,s=window.getComputedStyle(e),i=e.ownerDocument.body;o.whiteSpace="pre-wrap",o.wordWrap="break-word",o.position="absolute",o.visibility="hidden",E9.forEach(u=>{o[u]=s[u]}),n?e.scrollHeight>Number.parseInt(s.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),i.appendChild(r);let l=e.getBoundingClientRect(),c={top:l.top-e.scrollTop+a.offsetTop+Number.parseInt(s.borderTopWidth)+a.offsetHeight,left:l.left-e.scrollLeft+a.offsetLeft+Number.parseInt(s.borderLeftWidth)};return i.removeChild(r),c}var Mi=class extends Lo{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 z_(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 s;return(s=n==null?void 0:n.get)==null?void 0:s.call(this.element)},set:s=>{var i;(i=n==null?void 0:n.set)==null||i.call(this.element,s),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 H_(e,t,n){let r=`deepdesk-iframe-${e}`,o=document.getElementById(r);if(o)return o;let s=document.createElement("iframe"),i=new URL(t);return Object.entries(n).forEach(([a,l])=>{i.searchParams.append(a,l)}),s.style.position="absolute",s.style.left="-999em",s.style.width="0px",s.style.height="0px",s.tabIndex=-1,s.id=r,s.title=`iframe-${e}`,s.src=i.toString(),window.document.body.appendChild(s),s}function C9(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch(t){return e}}var Sx=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()}},xx=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.disposeHandlers=[];this.iframe=H_(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()}},wx=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(),Z.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 xx(t,this.deepdeskUrl,{debug:!0}):new Sx(t),r=o=>{var i,a;if(o.origin!==this.deepdeskUrl)return;let s=C9(o.data);typeof s!="object"||s.type!=="event"||s.channel!==t||(Z.info("Received broadcast event",this.externalId,o),(a=(i=this.eventMap)[s.name])==null||a.call(i,s.payload))};return n.onMessage(r),n}send(t,n,r){var i,a;Z.info("Broadcast event",{externalId:this.externalId,name:t,payload:n});let o={type:"event",name:t,payload:n};r!==!1&&((a=(i=this.eventMap)[t])==null||a.call(i,n));let s=this.externalId==="deepdesk-general"?this.defaultChannel:this.channel;s==null||s.postMessage(_(b({},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)}},B_=wx;function T9(e){return e.replace(/(_\w)/g,t=>t[1].toUpperCase())}function He(e){return Array.isArray(e)?e.map(He):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>_(b({},t),{[T9(n)]:He(e[n])}),{}):e}function k9(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function Mt(e){return Array.isArray(e)?e.map(Mt):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>_(b({},t),{[k9(n)]:Mt(e[n])}),{}):e}var ll=class extends Error{constructor(n,r){super(n);this.body=r;this.name="CustomError"}};var Du=e=>new Promise(t=>{setTimeout(t,e)});var kr=class extends ll{constructor(){super(...arguments);this.name="ClientError"}},mg=class extends ll{constructor(){super(...arguments);this.name="ServerError"}},bx=new Map;function U_(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:(Z.warn("Unexpected response body:",n.slice(0,20)),JSON.parse(n))})}var Li=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 s={isAborted:!1,reject:o},i=`${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:h=k=>k instanceof TypeError,retryOnResponse:y=k=>k.status>=500,version:S=null}=C,g=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(bx.has(i)){r(bx.get(i));return}}let m=_(b({credentials:"include"},g),{headers:b({Accept:"application/json","Content-Type":"application/json"},g.headers)});!l&&this.csrfToken&&(m.headers=_(b({},m.headers),{"X-CSRFToken":this.csrfToken})),typeof S=="string"&&(m.headers=_(b({},m.headers),{"X-Deepdesk-API-Version":S}));let v=f,x=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[i]&&u&&(this.latestRequestByUrl[i].isAborted=!0,this.latestRequestByUrl[i].reject(new Error("Aborted"))),this.latestRequestByUrl[i]=s;let T=()=>M(this,null,function*(){return v--,a(i,m).then(k=>M(this,null,function*(){return y(k)&&!s.isAborted&&v>0?(yield Du(d),T()):k.status===401&&p===!0&&x===!1?(x=!0,yield this.refreshToken(),T()):k})).catch(k=>M(this,null,function*(){if(h(k)&&!s.isAborted&&v>0)return yield Du(d),T();throw k}))});T().then(k=>M(this,null,function*(){let R=yield U_(k);if(delete this.latestRequestByUrl[i],k.status>=500){o(new mg("Server Error",R));return}if(k.status===401){o(new kr("Unauthorized",R));return}if(k.status===403){o(new kr("Forbidden",R));return}if(k.status===404){o(new kr("Not Found",R));return}if(k.status>=400){o(new kr("Bad Request",R));return}c&&bx.set(i,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 kr("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,b({method:"POST",body:JSON.stringify(n)},r))}postWithStatus(t,n,r){return this.requestWithStatus(t,b({method:"POST",body:JSON.stringify(n)},r))}requestWithStatus(t,n={}){return new Promise((r,o)=>{let s={isAborted:!1,reject:o},i=`${this.baseUrl}${t}`,a=this.fetch,T=n,{useCache:l=!1,abortLatest:c=!1,attempts:u=1,retryDelay:f=500,refreshTokenOn401:d=!0,retryOnError:p=C=>C instanceof TypeError,retryOnResponse:h=C=>C.status>=500,version:y=null}=T,S=ie(T,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]),g=_(b({credentials:"include"},S),{headers:b({Accept:"application/json","Content-Type":"application/json"},S.headers)});this.csrfToken&&(g.headers=_(b({},g.headers),{"X-CSRFToken":this.csrfToken})),typeof y=="string"&&(g.headers=_(b({},g.headers),{"X-Deepdesk-API-Version":y}));let m=u,v=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[i]&&c&&(this.latestRequestByUrl[i].isAborted=!0,this.latestRequestByUrl[i].reject(new Error("Aborted"))),this.latestRequestByUrl[i]=s;let x=()=>M(this,null,function*(){return m--,a(i,g).then(C=>M(this,null,function*(){return h(C)&&!s.isAborted&&m>0?(yield Du(f),x()):C.status===401&&d===!0&&v===!1?(v=!0,yield this.refreshToken(),x()):C})).catch(C=>M(this,null,function*(){if(p(C)&&!s.isAborted&&m>0)return yield Du(f),x();throw C}))});x().then(C=>M(this,null,function*(){let k=yield U_(C);if(delete this.latestRequestByUrl[i],C.status>=500){o(new mg("Server Error",k));return}if(C.status===401){o(new kr("Unauthorized",k));return}if(C.status===403){o(new kr("Forbidden",k));return}if(C.status===404){o(new kr("Not Found",k));return}if(C.status>=400){o(new kr("Bad Request",k));return}r({status:C.status,data:k})})).catch(C=>{delete this.latestRequestByUrl[i],o(C)})})}patch(t,n,r){return this.request(t,b({method:"PATCH",body:JSON.stringify(n)},r))}put(t,n,r){return this.request(t,b({method:"PUT",body:JSON.stringify(n)},r))}delete(t,n){return this.request(t,b({method:"DELETE"},n))}};var V_;(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={}))})(V_||(V_={}));function gg(e){return _(b({},He(e)),{metadata:e.metadata})}var Oi=class Oi{constructor(t,n={}){this.options=n;this.latestReceivedDeepdeskVersions={};this.shouldFetchCsrfToken=!0;this.client=new Li(t,{fetch:n.fetch}),this.client.patchFetch(r=>(o,s)=>M(this,null,function*(){let i=yield r(o,s);return this.handleDeepdeskVersionHeaders(i),i}))}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?(Oi.exchangeTokenPromise||(Oi.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),Oi.exchangeTokenPromise):Promise.resolve()})}createConversation(t){return M(this,null,function*(){var r;yield this.preflight(),Z.info(`Creating conversation for session ${t.externalId} and agent ${t.agentId}`);let n=yield this.client.post("/api/v2/conversations",_(b({chat_start_time:new Date().toISOString()},Mt(t)),{metadata:(r=t.metadata)!=null?r:{}}));return gg(n)})}upsertConversation(t){return M(this,null,function*(){var u;yield this.preflight(),Z.info(`Upserting conversation for session ${t.externalId} and agent ${t.agentId}`);let{status:n,data:r}=yield this.client.postWithStatus("/api/v2/conversations",_(b({chat_start_time:new Date().toISOString()},Mt(t)),{metadata:(u=t.metadata)!=null?u:{}}),{version:"v2"}),o=gg(r);if(n===201)return o;let{agentId:s,agentName:i,agentEmail:a,agentNickname:l,metadata:c}=t;return this.updateConversation(o.id,{agentId:s,agentEmail:a,agentName:i,agentNickname:l,metadata:c})})}getMe(){return M(this,null,function*(){yield this.preflight();let t=yield this.client.get("/apis/admin/session/me/");return He(t)})}postIdentity(t){return M(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/me/identities/",Mt(t))})}patchMe(t){return M(this,null,function*(){yield this.preflight();let n=yield this.client.patch("/apis/admin/session/me/",Mt(t));return He(n)})}getProfile(t){return M(this,null,function*(){let n=yield this.client.get(`/apis/admin/profiles/${t}/`,{useCache:!0});return He(n)})}getKnowledgeAssistant(t){return M(this,null,function*(){let n=yield this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{useCache:!0});return He(n)})}getContentTypes(){return M(this,null,function*(){let t=yield this.client.get("/apis/admin/content-types/",{useCache:!0});return He(t)})}getAccount(){return M(this,null,function*(){let t=yield this.client.get("/apis/admin/account/",{useCache:!0});return He(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 He(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(),Z.info(`Getting conversation for session ${t}`);let{attempts:o=1,retryDelay:s=1e3}=n,i=yield this.client.get(`/api/v2/conversations/by_external_id/${t}`,{attempts:o,retryDelay:s,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"});return Z.info(`Successfully retrieved conversation ${i.id} for session ${t}`),gg(i)})}isConversationSupported(r){return M(this,arguments,function*(t,n={}){Z.info(`Check if conversation for session ${t} is supported`);let{attempts:o=1,retryDelay:s=1e3}=n;return(yield this.client.get(`/api/v2/conversations/by_external_id/${t}/has_active_profile`,{attempts:o,retryDelay:s,retryOnResponse:a=>a.status===404||a.status>=500})).has_active_profile})}updateConversation(t,n){return M(this,null,function*(){var s;yield this.preflight();let r=Mt(n);n.metadata&&(r.metadata=(s=n.metadata)!=null?s:{});let o=yield this.client.put(`/api/v2/conversations/${t}`,r);return gg(o)})}postMessages(t,n){return M(this,null,function*(){yield this.preflight(),yield this.client.post(`/api/v2/conversations/${t}/messages`,n.map(r=>_(b({},Mt(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"]),s=Object.entries(this.latestReceivedDeepdeskVersions).reduce((l,[c,u])=>_(b({},l),{[c]:u}),{}),i=["platform","agentId","agentName","agentEmail","conversationId"].reduce((l,c)=>(o[c]&&(l[c]=o[c]),l),{});return this.client.post("/api/v2/events",Mt(_(b(b({},s),i),{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 Z.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/",Mt(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}`,Mt(n),{abortLatest:!0})).map(i=>_(b({},He(i)),{text:i.text||i.url||i.message,source:r,type:r})).filter((i,a,l)=>a===l.findIndex(c=>c.text===i.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`,Mt(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,s,i)=>s===i.findIndex(a=>a.text===o.text))})}syncPersonalCollection(t){return M(this,null,function*(){yield this.preflight(),yield this.client.post(`/api/v2/conversations/${t}/personal-collection/sync`,{},{version:"v2"})})}getPinnedMessages(t){return M(this,null,function*(){let n=yield this.client.get(`/api/v2/profiles/${t}/pinned-messages`,{abortLatest:!0});return He(n).map(r=>_(b({},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",Mt(t),{abortLatest:!0,version:"v2"});return He(n)})}search(t){return M(this,null,function*(){let n=yield this.client.post(`/api/v2/profiles/${t.profile}/search`,Mt(t));return He(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 He(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 He(n)})}requestPasswordlessToken(){return M(this,null,function*(){let t=yield this.client.get("/apis/admin/session/passwordless/request/");return He(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 He(n)})}evaluateAssistant(t,n){return M(this,null,function*(){var l,c,u;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()}`,s=f=>Mt(f),i=(l=n==null?void 0:n.transcript)==null?void 0:l.map(f=>{var d;return b({source:f.source,text:f.text},(d=f.attachments)!=null&&d.length?{attachments:f.attachments.map(s)}:{})}),a=yield this.client.post(o,b({input:(c=n==null?void 0:n.input)!=null?c:{},conversation:i},(u=n==null?void 0:n.attachments)!=null&&u.length?{attachments:n.attachments.map(s)}:{}));return He(a)})}interactWithAssistant(t){return M(this,null,function*(){yield this.preflight();let n=new URLSearchParams;t.sessionId&&n.append("session_id",t.sessionId),t.externalConversationId&&n.append("external_conversation_id",t.externalConversationId);let r=`/api/v2/assistants/${t.assistantCode}/interact?${n.toString()}`,o=yield this.client.post(r,{message:t.message});return He(o)})}resetAssistantThread(t){return M(this,null,function*(){yield this.preflight();let n=encodeURIComponent(t.assistantCode),r=encodeURIComponent(t.sessionId);yield this.client.delete(`/api/v2/assistants/${n}/sessions/${r}/thread`)})}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 He(r)})}postMessageToAssistantThread(t){return M(this,null,function*(){yield this.preflight();let{assistantCode:n,threadId:r,message:o}=t,s=yield this.client.post(`/apis/admin/assistants/${n}/threads/${r}/messages/`,{content:o,role:"user"});return He(s)})}translateMessages(t){return M(this,null,function*(){yield this.preflight();let n=yield this.client.post("/api/v2/translate",Mt(t));return He(n)})}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),s=o.match(Hw);if(!n||!s)return;let i=s[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[i];a&&n&&a!==n&&Z.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[i]=n})}};Oi.exchangeTokenPromise=null;var Oo=Oi;var hg=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=He(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 W_={startTime:null,stopTime:null},$_=e=>e.handlingTime,j_=Pe({name:"handlingTime",initialState:W_,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(Ke,()=>W_)}}),{handlingTimeStart:K_,handlingTimeStop:yg,handlingTimeReset:G_}=j_.actions,q_=j_.reducer;var Y_=(e={})=>{let t=b({onAuthError:Yi(!1)},e);return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var X_=(e={})=>{let t,n=!0,r=b({getStyleSuggestions:ki,debounce:500},e);return o=>s=>i=>{var p;let a=o.getState().input.text,l=s(i),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 R9(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end&&e.suggestionTextStart===t.suggestionTextStart}var Q_=(e={})=>{let t=b({getTextSuggestions:Tr,getAutocompleteSuggestions:xu,debounce:200,check:qr},e),n;return r=>o=>s=>{var y;let{input:i}=r.getState(),a=o(s),l=r.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:c,showTabCompletion:u}=l.settings,f=(y=l.conversation.current)==null?void 0:y.id,d=s.type===Hm.toString();if(!f||!c&&!u)return a;let{input:p}=l;return R9(p,i)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let S=Ds(l);S===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(S))},d?0:t.debounce)),a}};var Z_=ki.fulfilled.toString();function P9(e,t){let n=new Set([...t.keywordMatches.map(o=>o.keyword)]),r=[];return n.forEach(o=>{let s=e.keywordMatches.filter(l=>l.keyword===o),i=t.keywordMatches.filter(l=>l.keyword===o),a=i.length-s.length;a<=0||r.push(...i.slice(0,a))}),r}var J_=e=>t=>n=>r=>{var c;if(r.type!==Z_){n(r);return}let o=t.getState().styleSuggestions.list;n(r);let s=t.getState(),i=s.styleSuggestions.list,a=(c=s.conversation)==null?void 0:c.current;if(o===i)return;let l=P9(o,i);r.type===Z_&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var A9=hd({assistants:EC,auth:Zb,conversation:sE,contentTypes:CA,passwordlessToken:d_,entities:ZA,handlingTime:q_,info:RE,input:yE,settings:TC,profile:IA,search:LE,styleSuggestions:OI,ui:bI,textSuggestions:aI});function eM(e){return Hb({reducer:A9,middleware:t=>{var r;let n=t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI}},serializableCheck:!1}).concat(Y_()).concat(Q_({debounce:200})).concat(X_({debounce:500})).concat(J_(e.deepdeskAPI));return((r=e.middleware)!=null?r:[]).reduce((o,s)=>o.concat(s),n)},preloadedState:e.preloadedState})}function tM(e,t,n){if(t==="")return null;let r=new RegExp(`\\b${Zm(t)}\\b`,"gi"),o,s=null;for(;(o=r.exec(e))!==null&&!(o.index>n);)s={start:o.index,end:o.index+o[0].length};return s}var I9=e=>{var t,n;return(n=(t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())!=null?n:"unknown"},_9=e=>t=>n=>r=>{var l,c,u,f,d,p;let o=t.getState(),s=$s("inlineSuggestions")(o),i=$s("autoSelectSuggestion")(o)||s;switch(r.type){case Yi.toString():{!r.payload&&e.emit("logout",void 0);break}case Dd.fulfilled.toString():{e.emit("logout",void 0);break}case Cr.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 Hs.toString():e.logSendMessage(r.payload);break;case mf.toString():e.emit("call-to-action",{cue:r.payload});break;case Rn.fulfilled.toString():if(!r.isBroadcasted){let{externalConversationId:h,currentExternalIdAtRequest:y}=(c=r.payload)!=null?c:{};(!h||!y||h===y)&&e.broadcast(Lh,r,!1)}break;case Rn.rejected.toString():break;default:break}let a=n(r);switch(r.type){case Hs.toString():e.handleAfterSendMessage(r.payload);break;case bu.toString():e.onUpdateShowTabHint(r.payload);break;case yg.toString():e.logHandlingTime();break;case Zi.toString():e.broadcast(Yd,r);break;case zs.toString():e.broadcast(Yd,r);break;case gf.toString():t.dispatch(zs({source:"assistant",assistantCode:r.payload.code}));break;case"analytics/logEvent/fulfilled":{let h=o.assistants.cues.find(y=>y.code===r.meta.arg.data.assistantCode);e.emit("event",_(b({},r.meta.arg),{cue:h}));break}case Tn.toString():{let{start:h,end:y}=o.input.selection;e.emit("select-suggestion",_(b({type:I9(r.payload.suggestion)},r.payload),{replace:r.payload.replace==="selection"?{start:h,end:y}:{start:0,end:y}})),s&&t.dispatch(Wo([]));break}case LI.toString():{let{keyword:h,suggestion:y,eventMetrics:S}=r.payload,{text:g,selection:m}=o.input,v=tM(g,h,(u=m==null?void 0:m.end)!=null?u:g.length);if(!v)break;e.emit("select-suggestion",{text:y,type:"style",replace:v,suggestion:{text:y,source:"style"},eventMetrics:S});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 Wo.toString():{i&&r.payload.length>0&&t.dispatch($d(0));break}case Rn.fulfilled.toString():{let{evaluationId:h,output:y,externalConversationId:S}=r.payload,g=r.meta.arg.assistantCode;if(e.emit("event",{name:"Assistant evaluation completed",data:{evaluationId:h,assistantCode:g,assistantOutput:yC(y),externalConversationId:S,evaluationStatus:"success"}}),!r.meta.arg.skipState){let m=t.getState().assistants.cues;e.emit("cues",m)}break}case Rn.rejected.toString():{let h=r.meta.arg.assistantCode,y=(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:h,assistantOutput:"",externalConversationId:y,evaluationStatus:"failed"}});break}default:break}return a},nM=_9;function Ex(e){return e.toISOString().replace("T"," ").replace("Z","")}var M9=(e,t)=>t.version,rM=Yt([Ji,Wn,$_,M9],(e,t,n,r)=>{if(!t)return Z.warn("No conversationId for handling time metrics"),null;let{startTime:o,stopTime:s}=n;return!o||!s?(Z.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:Ex(o),timeStop:Ex(s)}});function oM(e,t){let{text:n,metrics:{numPaste:r,pastes:o,textSuggestions:s}}=e.input,i=n.length;return{source:"agent",clientVersion:t.version,pastes:o,lenTextTotal:i,numPastes:r,suggestions:s}}var Fu=class extends Error{};function L9(){let e,t;return{promise:new Promise((r,o)=>{e=r,t=o}),resolve:e,reject:t}}var vg=class{constructor(){this.queues={}}push(t,n){let r=()=>{let s=this.queues[t][1];s?(this.queues[t]=[s.promise,null],s.resolve()):delete this.queues[t]};if(!this.queues[t]){let s=n().finally(r);return this.queues[t]=[s,null],s}this.queues[t][1]&&this.queues[t][1].reject(new Fu("Queued async function is outdated"));let o=L9();return this.queues[t][1]=o,o.promise.then(()=>n().finally(r))}};function Cx(e,t){var s;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return Cx(r,t);let o=(s=e.ownerDocument.defaultView)==null?void 0:s.frameElement;return o?Cx(o,t):null}function Tx(e,t){return Cx(e,t)}var O9={accepted:"onConversationAcceptedAssistants","new-message":"onConversationNewMessageAssistants",ended:"onConversationEndedAssistants"},sM=(e,t)=>{var o,s,i;if(!((i=(s=(o=e.uiConfig)==null?void 0:o.widget)==null?void 0:s.types.find(a=>a.type==="cues"))==null?void 0:i.isActive))return Z.warn("Triggered a conversation assistant, but cues are not configured in widget."),[];let r=e[O9[t]];if(r&&r.length>0){let a=r.map(l=>l.code);return e.summarizerAssistantNew&&t!=="ended"&&(a=a.filter(l=>l!==e.summarizerAssistantNew)),a}return Z.warn(`No assistant set in profile for conversation event "${t}"`),[]};function N9(e){var t,n,r,o;return(o=(r=(n=(t=e.uiConfig)==null?void 0:t.widget)==null?void 0:n.types)==null?void 0:r.some(s=>s.type==="knowledge-assist"&&s.isActive))!=null?o:!1}function iM(e){var n,r;return((r=(n=e.widgetInteractiveAssistants)==null?void 0:n.length)!=null?r:0)>0&&N9(e)?!0:!!e.knowledgeAssistantNew||!!e.knowledgeAssistant}function D9(e){return typeof e=="object"&&e!==null&&"tagName"in e}function Sg(e){return D9(e)&&(Pi(e)||Xm(e))}var lM,Qr=new Map,F9=["bottom","height","left","right","top","width"],aM=(e,t)=>!e&&!t?!1:e&&!t||!e&&t?!0:F9.some(n=>e[n]!==t[n]);function cM(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,...cM(t)]:[]}function uM(e,t){return!e||!t?null:_(b({},e),{top:e.top+t.top,left:e.left+t.left})}var xg=!1,dM=()=>{xg=!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();aM(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{let n=t.parentRects?t.parentRects.reduce(uM,t.rect):t.rect;aM(n,t.totalRect)&&t.callbacks.forEach(r=>r(n)),t.totalRect=n}),Qr.size===0){xg=!1;return}lM=window.requestAnimationFrame(dM)};function kx(e,t){let n=cM(e),r=[],o=n.map((s,i)=>kx(s,a=>{r[i]=a;let l=Qr.get(e);if(!l)return;let c=r.reduce(uM,l.rect);l.callbacks.forEach(u=>u(c))}));return{observe(s=!0){if(o.forEach(i=>i.observe(!1)),Qr.has(e)){let i=Qr.get(e);i.callbacks.push(t),i.rect&&t(i.rect)}else Qr.set(e,{rect:void 0,callbacks:[t],parentRects:r});s&&!xg&&dM()},unobserve(){o.forEach(i=>i.unobserve());let s=Qr.get(e);if(s){let i=s.callbacks.indexOf(t);i>=0&&s.callbacks.splice(i,1),s.callbacks.length||Qr.delete(e),Qr.size||(cancelAnimationFrame(lM),xg=!1)}}}}var fM,Zr=new Map,pM=()=>{Zr.forEach((e,t)=>{if(!t.isConnected){Zr.delete(t);return}let{clientHeight:n,scrollHeight:r}=t,o=r>n;e.visible!==o&&(e.visible=o,e.callbacks.forEach(s=>s(e.visible)))}),Zr.size!==0&&(fM=window.requestAnimationFrame(pM))};function mM(e,t){return{observe(){let n=Zr.size===0;Zr.has(e)?Zr.get(e).callbacks.push(t):Zr.set(e,{visible:void 0,callbacks:[t]}),n&&pM()},unobserve(){let n=Zr.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||Zr.delete(e),Zr.size||cancelAnimationFrame(fM)}}}}var Rx=["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 Px(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function cl(e){return Number.parseFloat(e)}function wg(e){return Math.round(e*1e6)}function gM(e){return e/1e6}function Ax(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=cl(e.width),s=cl(e.borderLeftWidth),i=cl(e.borderRightWidth),a=cl(e.paddingRight),l=gM(wg(o)-wg(s)-wg(i)),c=gM(wg(r));if(l-c>2){let u=l-c;n.style.paddingRight=`${a+u}px`}}function zu(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",gi(n);let r=window.getComputedStyle(e),o=!0,s=()=>{n.scrollTop=e.scrollTop};Px(r,n,Rx),Ax(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",s));let i=mM(e,()=>{Px(r,n,Rx),Ax(r,e,n),s(),setTimeout(s,0)}),a,l=!0,c=kx(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(Px(r,n,Rx),Ax(r,e,n),s(),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(),h=window.getComputedStyle(t.closestScrollElement),y=cl(h.borderTopWidth),S=cl(h.borderBottomWidth),g=p.top+y-d.top,m=d.top+d.height+-(p.top+p.height-S);n.style.clipPath=`inset(${g}px 0px ${m}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(),i.observe(),[n,()=>{e.removeEventListener("scroll",s),c.unobserve(),i.unobserve(),n.remove()}]}function z9(e){return e.offsetParent!==null}function hM(e){if(!z9(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 bg(e,t,n=100){let r=hM(e);t({isVisible:r});let o=setInterval(()=>{let s=hM(e);s!==r&&(r=s,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var yM=(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){Z.warn("[Deepdesk] SessionStorage is blocked by browser")}}});var Re=E(A());var vM=yM("showTabHint",!0),ul=class ul{constructor({deepdeskUrl:t,version:n=ul.version||"unknown",locale:r="en-US",token:o,fetch:s,productName:i,createCustomChannel:a,websocketClient:l=hg}){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 vg;this.isMounted=!1;this.shouldRender=!0;this.loadProfileConfigPromise=null;this.loadProfileConfigPromiseKey=null;this.personalCollectionSyncPendingKey=null;this.personalCollectionSyncDrainPromise=null;let c=t.replace(/\/api$/,"");this.deepdeskApi=new Oo(c,{token:o,fetch:s}),this.version=n,this.instanceId=ul.count++;let u={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[nM({broadcast:(h,y,S)=>{this.broadcastEvents.send(h,y,S)},emit:(h,y)=>this.emit(h,y),handleAfterSendMessage:h=>this.handleAfterSendMessage(h),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:h=>this.logSendMessage(h),onUpdateShowTabHint:h=>vM.update(h),sendEvent:(h,y)=>this.deepdeskApi.sendEvent(h,y)})]};this.store=eM(u),this.broadcastEvents=new B_({debug:!0,deepdeskUrl:c,eventMap:OE(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 h;return(h=kt(this.state))!=null?h:!1})}),this.whenLoggedIn(()=>this.ws.connect()),this.store.dispatch(bu(vM.value())),this.store.dispatch(Xl({locale:r,adminUrl:c,productName:i}));let f=[],d=h=>{if(!h.conversationId)return;let y=()=>{this.conversationId()===h.conversationId&&this.store.dispatch(wC(h))};this.hasConversation()?y():f.push(y)};this.ws.on("assistants::direct_response",d),this.ws.on("assistants::user_notification",d),this.ws.on("assistants::response_chunk",h=>{if(!h.conversationId)return;let y=()=>{this.conversationId()===h.conversationId&&this.store.dispatch(xC(h))};this.hasConversation()?y():f.push(y)}),this.ws.on("assistants::suggest_as_reply",h=>{if(!h.conversationId)return;let y=()=>{this.conversationId()===h.conversationId&&this.store.dispatch(Zi([{text:h.payload.message,type:"text",source:"assistant",assistantCode:h.code,sourceLabel:h.name}]))};this.hasConversation()?y():f.push(y)});let p=this.whenConversationLoaded(()=>{var h;this.broadcastEvents.setExternalId((h=this.state.conversation.current)==null?void 0:h.externalId),f.forEach(y=>y()),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=Fs(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?(Z.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(Z.warn("Profile has not been loaded (yet)"),!0):(Z.warn("No conversation loaded (yet)"),!0)}whenLoggedIn(t){if(kt(this.state))t();else{let n=this.subscribe(kt,r=>{r&&t()});this.disposeHandlers.push(()=>{n()})}}login(){return this.store.dispatch(Yi(null)),this.store.dispatch(no()),new Promise(t=>{this.whenLoggedIn(()=>t())})}isLoggedIn(){return M(this,null,function*(){return(yield this.store.dispatch(no())).payload})}isConversationSupported(t,n){return M(this,null,function*(){return(yield this.store.dispatch(kh({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(Bd(_(b({},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(Ud({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(Rh(_(b({},t),{metadata:(r=t.metadata)!=null?r:{}})))).payload})}postMessages(t){return M(this,null,function*(){yield this.store.dispatch(Ph(t))})}updateConversation(t){return M(this,null,function*(){return(yield this.store.dispatch(Vd(t))).payload})}resetConversation(){this.store.dispatch(Ke()),this.loadProfileConfigPromise=null,this.loadProfileConfigPromiseKey=null,this.dynamicThunkObject.conversationQuery=null}clearDisplayedAnswers(){var n;let t=this.store.getState().conversation.current;t&&(zd((n=t.externalId)!=null?n:void 0),this.store.dispatch(cn()))}reloadConversationContext(o){return M(this,arguments,function*({conversation:t,visitorInfo:n,clearDisplayedUi:r=!1}){let s=yield this.upsertConversation(t);if(!(s!=null&&s.id))throw new Error("Failed to upsert conversation");r&&this.clearDisplayedAnswers(),n&&this.setVisitorInfo(n)})}publishConversationTranscript(t){return M(this,null,function*(){if(!this.store.getState().conversation.current)return;let r=t.map(o=>({source:o.source,text:o.text}));this.setConversationQuery(()=>Promise.resolve(r)),t.length>0&&(yield this.postMessages(t))})}configure(t){this.store.dispatch(Xl(t))}setVisitorInfo(t){this.store.dispatch(EE(t))}setCustomData(t){this.store.dispatch(CE(t))}setAgentInfo(t,n){return M(this,null,function*(){var o;yield this.store.dispatch(Al(b(b({},t),n))),(o=this.state.info.agentInfo)!=null&&o.agentNickname||this.broadcastEvents.send(qd,{showNicknameDialog:!0})})}setAgentSettings(t){return M(this,null,function*(){yield this.store.dispatch(Ih(t))})}getAgentSettings(){return M(this,null,function*(){return(yield this.store.dispatch(_h())).payload})}getMe(){return M(this,null,function*(){return this.deepdeskApi.getMe()})}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(jd({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),suggestionTextStart:this.inputMediator.getSuggestionTextStart()}))}notifyExternalSuggestion(t){this.store.dispatch(Tn(t))}evaluateAssistant(t,n){return M(this,null,function*(){var u;let{input:r={},attachments:o=[],transcript:s,showCuesInWidget:i=!0,includeMetadata:a,externalConversationId:l}=n||{},c=yield this.store.dispatch(Rn({assistantCode:t,attachments:o,transcript:s,includeMetadata:a,input:r,externalConversationId:l,skipState:!i}));if(c.error)throw new Error(`Assistant evaluation failed: ${(u=c.payload)!=null?u:c.error.message}`);return c.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){Z.warn("Can't evaluate assistant when profile is not loaded yet.");return}let o=sM(r,t),s=(f=n==null?void 0:n.showCuesInWidget)!=null?f:!0,d=n!=null?n:{},{showCuesInWidget:i}=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(h=>this.queues.push(h,()=>M(this,null,function*(){var S,g;let y=yield this.store.dispatch(Rn(b(_(b({assistantCode:h,includeMetadata:!0},a),{skipState:!s}),n!=null&&n.attachments&&(n==null?void 0:n.attachments.length)>0?{attachments:n==null?void 0:n.attachments}:{})));if(y.error)throw new Error(`Assistant evaluation failed: ${(S=y.payload)!=null?S:y.error.message}`);return{assistantCode:h,evaluationId:y.payload.evaluationId,output:y.payload.output,externalConversationId:(g=y.payload.externalConversationId)!=null?g:l}})).catch(y=>{if(y instanceof Fu)return Z.warn(`Queued assistant "${h}" was outdated and dropped`),null;throw y})));if(!s)return c.filter(h=>h!==null)})}handleKeyDown(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui,{textSuggestions:o,selectedSuggestionIndex:s,selection:i}=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(uE(Ah(t))),!qr(this.state)||t.key!=="Tab"&&!c)return;let h=()=>{n||!p||i&&(t.shiftKey||(this.store.dispatch(pE()),t.preventDefault()))},y=()=>{n||!p||f&&s<=0||i&&(t.shiftKey||(this.store.dispatch(mE()),t.preventDefault()))};switch(t.key){case"ArrowUp":d==="below"?y():h();break;case"ArrowDown":{d==="below"?h():y();break}case"Escape":{n||(this.store.dispatch($d(-1)),this.store.dispatch(bs({collapse:!0})),this.store.dispatch(xI(!0)),t.preventDefault());break}case"Tab":{t.preventDefault();let S=Qi(this.state);if(!S)return;this.store.dispatch(bu(!1)),this.store.dispatch(Tn({text:S.text,suggestion:S,eventMetrics:{inputType:"tab"},replace:"until-selection-end"}));break}case" ":{if(f||this.state.input.selectedSuggestionIndex===-1)return;let S=Qi(this.state);if(!S)return;this.store.dispatch(Tn({text:S.text,suggestion:S,eventMetrics:{inputType:"space"},replace:"until-selection-end"}));break}case"Enter":{if(f||t.shiftKey||this.state.input.selectedSuggestionIndex===-1)return;let S=Qi(this.state);if(!S)return;this.store.dispatch(Tn({text:S.text,suggestion:S,eventMetrics:{inputType:"enter"},replace:"until-selection-end"})),t.preventDefault();break}default:}n&&r&&this.store.dispatch(bs({collapse:!1}))}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(Wo([]))}handlingTimeStart(){this.state.handlingTime.startTime||(Z.info("Start handling time"),this.store.dispatch(K_()))}handlingTimeStop(){this.state.handlingTime.startTime&&(Z.info("Stop handling time"),this.store.dispatch(yg()))}logSendMessage(t){let n=oM(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=rM(this.state,{version:this.version});t&&(this.deepdeskApi.sendEvent("Handling Time",{conversationId:this.conversationId(),data:t}),this.store.dispatch(G_()))}notifySubmit(t={}){var n;this.shouldAbort()||(this.store.dispatch(Hs((n=t.text)!=null?n:this.state.input.text)),this.store.dispatch(hE()))}emit(t,n){let r=this.eventListeners[t];r&&r.forEach(o=>{try{o(n)}catch(s){Z.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),Z.error(s)}})}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(TE(t))}whenConversationLoaded(t){let n=()=>this.getConversationLoadedKey(),r=()=>{let s=n();s&&this.loadProfileConfig().then(()=>{if(n()!==s)return;let i=this.state.conversation.current,a=nr(this.state);!(i!=null&&i.id)||i.profileCode&&(a==null?void 0:a.code)!==i.profileCode||t()})};return n()&&r(),this.subscribe(s=>this.getConversationProfileKey(s.conversation.current),s=>{s&&r()})}overlayContainerFactory(t,n,r,o){let[s,i]=zu(n,r);return s.setAttribute("translate","no"),s.dataset.testid=t,o&&s.classList.add(o),[s,i]}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 s=(a=t.ownerDocument.defaultView)==null?void 0:a.frameElement,i=s?s.ownerDocument.defaultView:null;if(s&&(i===window||(i==null?void 0:i.parent)===window)){let[l,c]=zu(s,{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 gi(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),Z.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()?(Z.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(gE(r.metrics))):Z.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(!Sg(t))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let d=n,{customStyles:r,closestScrollSelector:o,floatingMenuParent:s,appendOverlayTo:i,inputMediator:a}=d,l=ie(d,["customStyles","closestScrollSelector","floatingMenuParent","appendOverlayTo","inputMediator"]),c={customStyles:r,closestScrollSelector:o,floatingMenuParent:s,appendOverlayTo:i};this.configure(l),this.settings.automaticHandlingTime&&this.setupHandlingTime(t),gi(t),this.inputMediator=a||(Pi(t)?new Mi(t):new _i(t)),this.inputMediator.on("change",({plainText:p,rawHTML:h,suggestionTextStart:y})=>{this.store.dispatch(jd({text:p,html:h,suggestionTextStart:y}))}),this.inputMediator.on("keyup",p=>{this.store.dispatch(dE(Ah(p)))}),this.inputMediator.on("keydown",p=>{this.handleKeyDown(p)}),this.inputMediator.on("paste",({pastedText:p,selectionText:h})=>{this.store.dispatch(fE({text:p,selectionText:h}))}),this.inputMediator.on("cut",({selectionText:p})=>{this.store.dispatch(cE(p))});let u;this.inputMediator.on("selection",p=>{clearTimeout(u),p===null?u=setTimeout(()=>{p!==null&&this.store.dispatch(Kd(p))},500):this.store.dispatch(Kd(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($s("inlineSuggestions"),()=>{this.renderSuggestions(t,c)}),this.subscribe($s("suggestionsPlacement"),()=>{this.renderSuggestions(t,c)});let f=this.renderOverlays(n);this.unmountHandlers.push(()=>{f.unmount()}),this.store.dispatch(jd({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),suggestionTextStart:this.inputMediator.getSuggestionTextStart()})),this.store.dispatch(Kd(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,s=a=>{o=a,i()},i=()=>{r==null||r.render((0,Re.jsx)(Po,{store:this.store,children:(0,Re.jsx)(oo,{broadcastEvents:this.broadcastEvents,children:(0,Re.jsx)(FI,{id:"deepdesk-nickname-dialog",error:o,onSave:a=>M(this,null,function*(){try{yield this.store.dispatch(wE({agentNickname:a})).unwrap(),console.log("setAgentNickname",a),this.broadcastEvents.send(qd,{showNicknameDialog:!1}),this.nicknameDialogUnsubscribe&&this.nicknameDialogUnsubscribe()}catch(l){Z.error("Error setting agent nickname",l),s("error"),this.nicknameDialogFailed=!0}})})})}))};i(),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,s;(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(i=>i()),this.unmountHandlers=[],(s=this.inputMediator)==null||s.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,s,i;(r=this.floatingMenu)==null||r.unmount(),(o=this.inlineSuggestions)==null||o.unmount(),(s=this.aboveSuggestions)==null||s.unmount(),(i=this.belowSuggestions)==null||i.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"),s=(0,No.createRoot)(o);s.render((0,Re.jsx)(Po,{store:this.store,customStyles:r,children:(0,Re.jsx)(oo,{broadcastEvents:this.broadcastEvents,children:(0,Re.jsx)(NI,{})})}));let i=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",i),{unmount:()=>{var a;(a=this.inputMediator)==null||a.off("caretposition",i),s.unmount(),o.remove()}}}renderAboveOrBelowSuggestions(t,n,r){let{customStyles:o,closestScrollSelector:s,appendOverlayTo:i}=n,a=s&&Tx(t,s)||void 0,[l,c]=this.overlayContainerFactory("deepdesk-tab-completion",a||t,{appendTo:i,closestScrollElement:a,mirrorOverflow:!0,onRemove:()=>this.unmount()},o==null?void 0:o.rootNode),[u,f]=this.overlayContainerFactory("deepdesk-suggestions-overlay",a||t,{appendTo:i,placement:r},o==null?void 0:o.suggestionsRootNode),d=(0,No.createRoot)(l);d.render((0,Re.jsx)(Po,{store:this.store,customStyles:o,children:(0,Re.jsx)(oo,{broadcastEvents:this.broadcastEvents,children:(0,Re.jsx)(l_,{inputElement:t})})}));let p=(0,No.createRoot)(u);return p.render((0,Re.jsx)(Po,{store:this.store,customStyles:o,children:(0,Re.jsx)(oo,{broadcastEvents:this.broadcastEvents,children:(0,Re.jsx)(KI,{onLogIn:()=>this.loginViaPopup().catch(h=>Z.warn(h.message))})})})),{unmount(){d.unmount(),p.unmount(),c(),f()}}}renderFloatingMenu(t,n){let{customStyles:r,closestScrollSelector:o,appendOverlayTo:s,floatingMenuParent:i}=n,a=o&&Tx(t,o)||void 0,[l,c]=this.overlayContainerFactory("floating-menu",a||t,{appendTo:i!=null?i:s},r==null?void 0:r.floatingMenuParent),u=(0,No.createRoot)(l);return u.render((0,Re.jsx)(Po,{store:this.store,customStyles:r,children:(0,Re.jsx)(oo,{broadcastEvents:this.broadcastEvents,children:(0,Re.jsx)(vI,{onLogIn:()=>this.loginViaPopup().catch(f=>Z.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,Re.jsx)(Po,{store:this.store,customStyles:n,children:(0,Re.jsx)(oo,{broadcastEvents:this.broadcastEvents,children:(0,Re.jsx)(pI,{})})})),{unmount(){o.unmount(),r.remove()}}}renderWidget(t,n={}){if(this.widgetElement&&Z.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,isEmbedded:s,signInViaPopup:i,ssoUrl:a,openAdminFeedback:l}=n;this.widgetElement=t,this.configure({showImages:o,isEmbedded:s,signInViaPopup:i});let c;if(a)try{c={url:new URL(a,this.settings.adminUrl).toString()}}catch(u){Z.warn(`Invalid ssoUrl '${a}' passed to renderWidget`)}this.widgetRoot=(0,No.createRoot)(t),this.widgetRoot.render((0,Re.jsx)(Po,{store:this.store,customStyles:r,children:(0,Re.jsx)(oo,{broadcastEvents:this.broadcastEvents,children:(0,Re.jsx)(bm,{report:u=>this.deepdeskApi.sendEvent(cA,{data:u}),children:(0,Re.jsx)(O_,{assistantOptions:n.assistantOptions,knowledgeAssistOptions:n.knowledgeAssist,openAdminFeedback:l,onLogIn:()=>this.loginViaPopup(c).catch(u=>Z.warn(u.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:s}=r,i=(0,No.createRoot)(n);return i.render((0,Re.jsx)(Po,{store:this.store,customStyles:o,children:(0,Re.jsx)(oo,{broadcastEvents:this.broadcastEvents,children:(0,Re.jsx)(vx,{children:(0,Re.jsxs)(vm,{assistantCode:t,initialQuestion:s,evaluateKnowledgeAssistFn:Yl,children:[(0,Re.jsx)(ji,{children:(0,Re.jsx)(xm,{title:r.title,emptyState:r.emptyState})}),(0,Re.jsx)(yx,{children:(0,Re.jsx)(Sm,{})})]})})})})),{unmount(){i.unmount()}}}setupHandlingTime(t){let n=bg(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){wm(t)&&t.message==="Unauthorized"&&this.login()}getConversationProfileKey(t){var n;if(t!=null&&t.id)return`${t.id}:${(n=t.profileCode)!=null?n:""}`}getProfileLoadKey(){var n;let t=this.state.conversation.current;return t!=null&&t.profileCode&&(n=this.getConversationProfileKey(t))!=null?n:null}isCurrentProfileLoadKey(t){return this.getProfileLoadKey()===t}getConversationLoadedKey(){return this.getConversationProfileKey(this.state.conversation.current)}resetProfileDerivedSettings(){this.store.dispatch(P0()),this.store.dispatch(Xl(uy))}syncPersonalCollectionForConversation(t){this.personalCollectionSyncPendingKey=t,this.ensurePersonalCollectionSyncDrain()}ensurePersonalCollectionSyncDrain(){return this.personalCollectionSyncDrainPromise?this.personalCollectionSyncDrainPromise:(this.personalCollectionSyncDrainPromise=this.drainPersonalCollectionSync().finally(()=>{this.personalCollectionSyncDrainPromise=null,this.personalCollectionSyncPendingKey&&this.ensurePersonalCollectionSyncDrain()}),this.personalCollectionSyncDrainPromise)}drainPersonalCollectionSync(){return M(this,null,function*(){for(;this.personalCollectionSyncPendingKey;){let t=this.personalCollectionSyncPendingKey;if(this.personalCollectionSyncPendingKey=null,!this.isCurrentProfileLoadKey(t))continue;let n=this.state.conversation.current,r=n==null?void 0:n.id;if(!(!r||!n.profileCode))try{yield this.deepdeskApi.syncPersonalCollection(r)}catch(o){this.isCurrentProfileLoadKey(t)&&Z.warn("Failed to sync personal collection for profile",o)}}})}loadProfileConfig(t=!0){let n=this.getProfileLoadKey();if(!n)return this.loadProfileConfigPromise=null,this.loadProfileConfigPromiseKey=null,this.resetProfileDerivedSettings(),Promise.resolve();let r=this.state.conversation.current,o=nr(this.state);if(o&&o.code!==(r==null?void 0:r.profileCode)&&(this.loadProfileConfigPromise=null,this.loadProfileConfigPromiseKey=null,this.resetProfileDerivedSettings()),this.loadProfileConfigPromise&&this.loadProfileConfigPromiseKey===n)return this.loadProfileConfigPromise;this.loadProfileConfigPromise=null,this.loadProfileConfigPromiseKey=n;let s=Promise.resolve().then(()=>M(this,null,function*(){try{yield this.store.dispatch(su()).unwrap()}catch(l){if(l===Xa)return this.loadProfileConfigPromise===s&&(this.loadProfileConfigPromise=null,this.loadProfileConfigPromiseKey=null),t&&this.isCurrentProfileLoadKey(n)&&!nr(this.state)?this.loadProfileConfig(!1):void 0;throw l}if(!this.isCurrentProfileLoadKey(n))return;let i=nr(this.state),a=this.state.conversation.current;!i||i.code!==(a==null?void 0:a.profileCode)||(this.store.dispatch(Xl({showSearch:i.search,showImageSearch:i.imageSearch,showEntitiesCommand:i.entitiesCommand,showSummaryCommand:!!i.summarizerAssistantNew,showKnowledgeSearch:iM(i),recommendTextSuggestions:i.recommendTextSuggestions})),this.syncPersonalCollectionForConversation(n))})).finally(()=>{this.loadProfileConfigPromise===s&&(nr(this.state)||(this.loadProfileConfigPromise=null,this.loadProfileConfigPromiseKey=null))});return this.loadProfileConfigPromise=s,s}loginViaPopup(t){return M(this,null,function*(){return new Promise((n,r)=>{this.store.dispatch(Fd());let o=new MessageChannel,s=o.port1,i=this.settings.adminUrl,a=new URL(t!=null&&t.url?t==null?void 0:t.url:`${i}/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)};s.onmessage=p=>M(this,null,function*(){var h,y;if((h=p.data)!=null&&h.jwt)try{yield this.deepdeskApi.exchangeTokenForAccessCookie((y=p.data)==null?void 0:y.jwt),yield this.isLoggedIn(),this.broadcastEvents.send(Ml),l=!0,o.port1.close(),n()}catch(S){console.error(S),r(S)}finally{l=!0,c()}});let u=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");if(u===null){r(new Error("Popup blocked by browser"));return}let f=p=>M(this,null,function*(){var h;if(!(p.origin!==a.origin||p.source!==u))switch((h=p.data)==null?void 0:h.type){case"deepdesk-popup-request-origin":{try{let y=JSON.stringify({type:"deepdesk-popup-parent-origin"});u.postMessage(y,a.origin)}catch(y){Z.error("Error posting message to popup",y),r(y)}break}case"deepdesk-popup-loaded":{try{let y=JSON.stringify({type:"deepdesk-popup-create-channel"});u.postMessage(y,a.origin,[o.port2])}catch(y){Z.error("Error posting message to popup",y),r(y)}break}case"deepdesk-popup-error":{if(c(),p.data.message==="Platform account url mismatch"){let y="Please contact your administrator: The page that opened the popup is not a trusted origin.";Z.warn(y),this.store.dispatch(bh(y)),r(new Error(y));return}if(p.data.message==="Timeout"){let y="Please contact your administrator: Popup timed out. Check if the account's platform.url or account.url is configured correctly.";Z.warn(y),this.store.dispatch(bh(y)),r(new Error(y));return}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(Hm()))})}refreshWidgetSuggestions(){return M(this,null,function*(){if(!this.widgetRoot)return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=iu(this.state);try{n.forEach(({type:r})=>{switch(r){case"entities":this.store.dispatch(Cr());break;case"pinned-messages":case"sticky-messages":break;default:fd.includes(r)||this.store.dispatch(Tr(r))}})}catch(r){this.handleError(r)}})}};ul.version="19.6.2-beta.17",ul.count=0;var Hu=ul;function H9(e){return M(this,null,function*(){var o,s,i;let n=yield((o=e.fetch)!=null?o:window.fetch)(e.url),r=yield n.blob();return new File([r],e.name,{type:(i=(s=e.mimeType)!=null?s:n.headers.get("Content-Type"))!=null?i:"image/jpeg"})})}function SM(e,t){return M(this,null,function*(){let n=yield H9(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 xM(e,t,n){return M(this,null,function*(){yield new Oo(e).authenticateWithKey(t,n)})}function wM(e){return e.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}function bM(r,o){return M(this,arguments,function*(e,t,n={}){var f,d;let{value:s}=e,{start:i,end:a}=(f=n.replace)!=null?f:{start:0,end:s.length},l=`${s.slice(0,i)}${t}${s.slice(a)}`,c=(d=n.selectionAfter)!=null?d:{start:i+t.length,end:i+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 EM(r,o){return M(this,arguments,function*(e,t,n={}){let s=n.replace?Rs(e,n.replace.start,n.replace.end):al(e),i,a=()=>{if(n.setRange)return n.setRange(s.cloneRange());s.deleteContents(),i=document.createElement("span"),s.insertNode(i),n.insertBRs!==!1?t.split(`
84
+ `);let h=d?r:0,y=p?Math.min(s,u.childNodes.length):u.childNodes.length;for(let S=h;S<y&&(c(u.childNodes[S]),a!==2);S++);break}default:break}p&&(a=2)}return c(e),l}var D_=(i=>(i.CUT="Cut",i.BACKSPACE="Backspace",i.DELETE="Delete",i.ERASEEOF="EraseEof",i.UNDO="Undo",i.CLEAR="Clear",i))(D_||{}),Lo=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(),s=this.cachedCaretPosition===null;if(!this.isActive)return;t===""&&this.cachedText!==""&&!this.isPossibleClearInputAction&&this.emit("submit");let i=t!==this.cachedText,a=n!==null&&n!==this.cachedHTML,l=o!==this.cachedSuggestionTextStart;if((i||a||l)&&(i?(this.cachedText=t,this.cachedHTML=n):a&&(this.cachedHTML=n),this.cachedSuggestionTextStart=o,s=!0,this.emit("change",{plainText:t,rawHTML:n,suggestionTextStart:o})),(r.start!==this.cachedSelection.start||r.end!==this.cachedSelection.end)&&(this.cachedSelection=r,s=!0,this.emit("selection",r)),!s)return;let c=this.getCaretPosition();Uo(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(D_).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 F_(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var _i=class extends Lo{constructor(){super(...arguments);this.lastKnownSelection=null}getRootNode(){return this.element.getRootNode()}getText(){let n=new Range;return n.selectNodeContents(this.element),Nu(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 s=this.element.ownerDocument.createRange();return s.setStart(o==null?void 0:o.startContainer,o==null?void 0:o.startOffset),s.setEnd(o==null?void 0:o.endContainer,o==null?void 0:o.endOffset),!s||!this.element.contains(s.startContainer)||!this.element.contains(s.endContainer)?null:s}getCaretPosition(){let n=this.getRange();if(!n||!n.collapsed||!("getBoundingClientRect"in n))return null;let r=n.getBoundingClientRect();return!F_(r)&&(n.insertNode(this.element.ownerDocument.createTextNode("\u2060")),r=n.getBoundingClientRect(),n.deleteContents(),!F_(r))?null:{top:r.top+r.height,left:r.left}}getSelection(){let n=this.getRange();if(n)return Ou(this.element,n);let r=this.lastKnownSelection;if(r&&N_(this.element,r.start,r.end))return r;let o=al(this.element);return o.collapse(!1),Ou(this.element,o)}getSelectedText(){let{start:n,end:r}=this.getSelection();return Nu(this.element,Rs(this.element,n,r))}listen(){super.listen();let n=new MutationObserver(s=>{var i,a;s.length===2&&s[0].addedNodes.length===1&&((i=s[0].addedNodes[0])==null?void 0:i.textContent)==="\u2060"&&((a=s[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 E9=["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 z_(e,t){let n="mozInnerScreenX"in window,r=document.createElement("div");r.id="input-textarea-caret-position-mirror-div";let o=r.style,s=window.getComputedStyle(e),i=e.ownerDocument.body;o.whiteSpace="pre-wrap",o.wordWrap="break-word",o.position="absolute",o.visibility="hidden",E9.forEach(u=>{o[u]=s[u]}),n?e.scrollHeight>Number.parseInt(s.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),i.appendChild(r);let l=e.getBoundingClientRect(),c={top:l.top-e.scrollTop+a.offsetTop+Number.parseInt(s.borderTopWidth)+a.offsetHeight,left:l.left-e.scrollLeft+a.offsetLeft+Number.parseInt(s.borderLeftWidth)};return i.removeChild(r),c}var Mi=class extends Lo{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 z_(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 s;return(s=n==null?void 0:n.get)==null?void 0:s.call(this.element)},set:s=>{var i;(i=n==null?void 0:n.set)==null||i.call(this.element,s),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 H_(e,t,n){let r=`deepdesk-iframe-${e}`,o=document.getElementById(r);if(o)return o;let s=document.createElement("iframe"),i=new URL(t);return Object.entries(n).forEach(([a,l])=>{i.searchParams.append(a,l)}),s.style.position="absolute",s.style.left="-999em",s.style.width="0px",s.style.height="0px",s.tabIndex=-1,s.id=r,s.title=`iframe-${e}`,s.src=i.toString(),window.document.body.appendChild(s),s}function C9(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch(t){return e}}var Sx=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()}},xx=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.disposeHandlers=[];this.iframe=H_(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()}},wx=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(),Z.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 xx(t,this.deepdeskUrl,{debug:!0}):new Sx(t),r=o=>{var i,a;if(o.origin!==this.deepdeskUrl)return;let s=C9(o.data);typeof s!="object"||s.type!=="event"||s.channel!==t||(Z.info("Received broadcast event",this.externalId,o),(a=(i=this.eventMap)[s.name])==null||a.call(i,s.payload))};return n.onMessage(r),n}send(t,n,r){var i,a;Z.info("Broadcast event",{externalId:this.externalId,name:t,payload:n});let o={type:"event",name:t,payload:n};r!==!1&&((a=(i=this.eventMap)[t])==null||a.call(i,n));let s=this.externalId==="deepdesk-general"?this.defaultChannel:this.channel;s==null||s.postMessage(_(b({},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)}},B_=wx;function T9(e){return e.replace(/(_\w)/g,t=>t[1].toUpperCase())}function He(e){return Array.isArray(e)?e.map(He):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>_(b({},t),{[T9(n)]:He(e[n])}),{}):e}function k9(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function Mt(e){return Array.isArray(e)?e.map(Mt):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>_(b({},t),{[k9(n)]:Mt(e[n])}),{}):e}var ll=class extends Error{constructor(n,r){super(n);this.body=r;this.name="CustomError"}};var Du=e=>new Promise(t=>{setTimeout(t,e)});var kr=class extends ll{constructor(){super(...arguments);this.name="ClientError"}},mg=class extends ll{constructor(){super(...arguments);this.name="ServerError"}},bx=new Map;function U_(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:(Z.warn("Unexpected response body:",n.slice(0,20)),JSON.parse(n))})}var Li=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 s={isAborted:!1,reject:o},i=`${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:h=k=>k instanceof TypeError,retryOnResponse:y=k=>k.status>=500,version:S=null}=C,g=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(bx.has(i)){r(bx.get(i));return}}let m=_(b({credentials:"include"},g),{headers:b({Accept:"application/json","Content-Type":"application/json"},g.headers)});!l&&this.csrfToken&&(m.headers=_(b({},m.headers),{"X-CSRFToken":this.csrfToken})),typeof S=="string"&&(m.headers=_(b({},m.headers),{"X-Deepdesk-API-Version":S}));let v=f,x=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[i]&&u&&(this.latestRequestByUrl[i].isAborted=!0,this.latestRequestByUrl[i].reject(new Error("Aborted"))),this.latestRequestByUrl[i]=s;let T=()=>M(this,null,function*(){return v--,a(i,m).then(k=>M(this,null,function*(){return y(k)&&!s.isAborted&&v>0?(yield Du(d),T()):k.status===401&&p===!0&&x===!1?(x=!0,yield this.refreshToken(),T()):k})).catch(k=>M(this,null,function*(){if(h(k)&&!s.isAborted&&v>0)return yield Du(d),T();throw k}))});T().then(k=>M(this,null,function*(){let R=yield U_(k);if(delete this.latestRequestByUrl[i],k.status>=500){o(new mg("Server Error",R));return}if(k.status===401){o(new kr("Unauthorized",R));return}if(k.status===403){o(new kr("Forbidden",R));return}if(k.status===404){o(new kr("Not Found",R));return}if(k.status>=400){o(new kr("Bad Request",R));return}c&&bx.set(i,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 kr("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,b({method:"POST",body:JSON.stringify(n)},r))}postWithStatus(t,n,r){return this.requestWithStatus(t,b({method:"POST",body:JSON.stringify(n)},r))}requestWithStatus(t,n={}){return new Promise((r,o)=>{let s={isAborted:!1,reject:o},i=`${this.baseUrl}${t}`,a=this.fetch,T=n,{useCache:l=!1,abortLatest:c=!1,attempts:u=1,retryDelay:f=500,refreshTokenOn401:d=!0,retryOnError:p=C=>C instanceof TypeError,retryOnResponse:h=C=>C.status>=500,version:y=null}=T,S=ie(T,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]),g=_(b({credentials:"include"},S),{headers:b({Accept:"application/json","Content-Type":"application/json"},S.headers)});this.csrfToken&&(g.headers=_(b({},g.headers),{"X-CSRFToken":this.csrfToken})),typeof y=="string"&&(g.headers=_(b({},g.headers),{"X-Deepdesk-API-Version":y}));let m=u,v=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[i]&&c&&(this.latestRequestByUrl[i].isAborted=!0,this.latestRequestByUrl[i].reject(new Error("Aborted"))),this.latestRequestByUrl[i]=s;let x=()=>M(this,null,function*(){return m--,a(i,g).then(C=>M(this,null,function*(){return h(C)&&!s.isAborted&&m>0?(yield Du(f),x()):C.status===401&&d===!0&&v===!1?(v=!0,yield this.refreshToken(),x()):C})).catch(C=>M(this,null,function*(){if(p(C)&&!s.isAborted&&m>0)return yield Du(f),x();throw C}))});x().then(C=>M(this,null,function*(){let k=yield U_(C);if(delete this.latestRequestByUrl[i],C.status>=500){o(new mg("Server Error",k));return}if(C.status===401){o(new kr("Unauthorized",k));return}if(C.status===403){o(new kr("Forbidden",k));return}if(C.status===404){o(new kr("Not Found",k));return}if(C.status>=400){o(new kr("Bad Request",k));return}r({status:C.status,data:k})})).catch(C=>{delete this.latestRequestByUrl[i],o(C)})})}patch(t,n,r){return this.request(t,b({method:"PATCH",body:JSON.stringify(n)},r))}put(t,n,r){return this.request(t,b({method:"PUT",body:JSON.stringify(n)},r))}delete(t,n){return this.request(t,b({method:"DELETE"},n))}};var V_;(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={}))})(V_||(V_={}));function gg(e){return _(b({},He(e)),{metadata:e.metadata})}var Oi=class Oi{constructor(t,n={}){this.options=n;this.latestReceivedDeepdeskVersions={};this.shouldFetchCsrfToken=!0;this.client=new Li(t,{fetch:n.fetch}),this.client.patchFetch(r=>(o,s)=>M(this,null,function*(){let i=yield r(o,s);return this.handleDeepdeskVersionHeaders(i),i}))}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?(Oi.exchangeTokenPromise||(Oi.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),Oi.exchangeTokenPromise):Promise.resolve()})}createConversation(t){return M(this,null,function*(){var r;yield this.preflight(),Z.info(`Creating conversation for session ${t.externalId} and agent ${t.agentId}`);let n=yield this.client.post("/api/v2/conversations",_(b({chat_start_time:new Date().toISOString()},Mt(t)),{metadata:(r=t.metadata)!=null?r:{}}));return gg(n)})}upsertConversation(t){return M(this,null,function*(){var u;yield this.preflight(),Z.info(`Upserting conversation for session ${t.externalId} and agent ${t.agentId}`);let{status:n,data:r}=yield this.client.postWithStatus("/api/v2/conversations",_(b({chat_start_time:new Date().toISOString()},Mt(t)),{metadata:(u=t.metadata)!=null?u:{}}),{version:"v2"}),o=gg(r);if(n===201)return o;let{agentId:s,agentName:i,agentEmail:a,agentNickname:l,metadata:c}=t;return this.updateConversation(o.id,{agentId:s,agentEmail:a,agentName:i,agentNickname:l,metadata:c})})}getMe(){return M(this,null,function*(){yield this.preflight();let t=yield this.client.get("/apis/admin/session/me/");return He(t)})}postIdentity(t){return M(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/me/identities/",Mt(t))})}patchMe(t){return M(this,null,function*(){yield this.preflight();let n=yield this.client.patch("/apis/admin/session/me/",Mt(t));return He(n)})}getProfile(t){return M(this,null,function*(){let n=yield this.client.get(`/apis/admin/profiles/${t}/`,{useCache:!0});return He(n)})}getKnowledgeAssistant(t){return M(this,null,function*(){let n=yield this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{useCache:!0});return He(n)})}getContentTypes(){return M(this,null,function*(){let t=yield this.client.get("/apis/admin/content-types/",{useCache:!0});return He(t)})}getAccount(){return M(this,null,function*(){let t=yield this.client.get("/apis/admin/account/",{useCache:!0});return He(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 He(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(),Z.info(`Getting conversation for session ${t}`);let{attempts:o=1,retryDelay:s=1e3}=n,i=yield this.client.get(`/api/v2/conversations/by_external_id/${t}`,{attempts:o,retryDelay:s,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"});return Z.info(`Successfully retrieved conversation ${i.id} for session ${t}`),gg(i)})}isConversationSupported(r){return M(this,arguments,function*(t,n={}){Z.info(`Check if conversation for session ${t} is supported`);let{attempts:o=1,retryDelay:s=1e3}=n;return(yield this.client.get(`/api/v2/conversations/by_external_id/${t}/has_active_profile`,{attempts:o,retryDelay:s,retryOnResponse:a=>a.status===404||a.status>=500})).has_active_profile})}updateConversation(t,n){return M(this,null,function*(){var s;yield this.preflight();let r=Mt(n);n.metadata&&(r.metadata=(s=n.metadata)!=null?s:{});let o=yield this.client.put(`/api/v2/conversations/${t}`,r);return gg(o)})}postMessages(t,n){return M(this,null,function*(){yield this.preflight(),yield this.client.post(`/api/v2/conversations/${t}/messages`,n.map(r=>_(b({},Mt(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"]),s=Object.entries(this.latestReceivedDeepdeskVersions).reduce((l,[c,u])=>_(b({},l),{[c]:u}),{}),i=["platform","agentId","agentName","agentEmail","conversationId"].reduce((l,c)=>(o[c]&&(l[c]=o[c]),l),{});return this.client.post("/api/v2/events",Mt(_(b(b({},s),i),{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 Z.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/",Mt(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}`,Mt(n),{abortLatest:!0})).map(i=>_(b({},He(i)),{text:i.text||i.url||i.message,source:r,type:r})).filter((i,a,l)=>a===l.findIndex(c=>c.text===i.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`,Mt(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,s,i)=>s===i.findIndex(a=>a.text===o.text))})}syncPersonalCollection(t){return M(this,null,function*(){yield this.preflight(),yield this.client.post(`/api/v2/conversations/${t}/personal-collection/sync`,{},{version:"v2"})})}getPinnedMessages(t){return M(this,null,function*(){let n=yield this.client.get(`/api/v2/profiles/${t}/pinned-messages`,{abortLatest:!0});return He(n).map(r=>_(b({},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",Mt(t),{abortLatest:!0,version:"v2"});return He(n)})}search(t){return M(this,null,function*(){let n=yield this.client.post(`/api/v2/profiles/${t.profile}/search`,Mt(t));return He(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 He(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 He(n)})}requestPasswordlessToken(){return M(this,null,function*(){let t=yield this.client.get("/apis/admin/session/passwordless/request/");return He(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 He(n)})}evaluateAssistant(t,n){return M(this,null,function*(){var l,c,u;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()}`,s=f=>Mt(f),i=(l=n==null?void 0:n.transcript)==null?void 0:l.map(f=>{var d;return b({source:f.source,text:f.text},(d=f.attachments)!=null&&d.length?{attachments:f.attachments.map(s)}:{})}),a=yield this.client.post(o,b({input:(c=n==null?void 0:n.input)!=null?c:{},conversation:i},(u=n==null?void 0:n.attachments)!=null&&u.length?{attachments:n.attachments.map(s)}:{}));return He(a)})}interactWithAssistant(t){return M(this,null,function*(){yield this.preflight();let n=new URLSearchParams;t.sessionId&&n.append("session_id",t.sessionId),t.externalConversationId&&n.append("external_conversation_id",t.externalConversationId);let r=`/api/v2/assistants/${t.assistantCode}/interact?${n.toString()}`,o=yield this.client.post(r,{message:t.message});return He(o)})}resetAssistantThread(t){return M(this,null,function*(){yield this.preflight();let n=encodeURIComponent(t.assistantCode),r=encodeURIComponent(t.sessionId);yield this.client.delete(`/api/v2/assistants/${n}/sessions/${r}/thread`)})}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 He(r)})}postMessageToAssistantThread(t){return M(this,null,function*(){yield this.preflight();let{assistantCode:n,threadId:r,message:o}=t,s=yield this.client.post(`/apis/admin/assistants/${n}/threads/${r}/messages/`,{content:o,role:"user"});return He(s)})}translateMessages(t){return M(this,null,function*(){yield this.preflight();let n=yield this.client.post("/api/v2/translate",Mt(t));return He(n)})}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),s=o.match(Hw);if(!n||!s)return;let i=s[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[i];a&&n&&a!==n&&Z.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[i]=n})}};Oi.exchangeTokenPromise=null;var Oo=Oi;var hg=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=He(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 W_={startTime:null,stopTime:null},$_=e=>e.handlingTime,j_=Pe({name:"handlingTime",initialState:W_,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(Ke,()=>W_)}}),{handlingTimeStart:K_,handlingTimeStop:yg,handlingTimeReset:G_}=j_.actions,q_=j_.reducer;var Y_=(e={})=>{let t=b({onAuthError:Yi(!1)},e);return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var X_=(e={})=>{let t,n=!0,r=b({getStyleSuggestions:ki,debounce:500},e);return o=>s=>i=>{var p;let a=o.getState().input.text,l=s(i),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 R9(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end&&e.suggestionTextStart===t.suggestionTextStart}var Q_=(e={})=>{let t=b({getTextSuggestions:Tr,getAutocompleteSuggestions:xu,debounce:200,check:qr},e),n;return r=>o=>s=>{var y;let{input:i}=r.getState(),a=o(s),l=r.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:c,showTabCompletion:u}=l.settings,f=(y=l.conversation.current)==null?void 0:y.id,d=s.type===Hm.toString();if(!f||!c&&!u)return a;let{input:p}=l;return R9(p,i)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let S=Ds(l);S===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(S))},d?0:t.debounce)),a}};var Z_=ki.fulfilled.toString();function P9(e,t){let n=new Set([...t.keywordMatches.map(o=>o.keyword)]),r=[];return n.forEach(o=>{let s=e.keywordMatches.filter(l=>l.keyword===o),i=t.keywordMatches.filter(l=>l.keyword===o),a=i.length-s.length;a<=0||r.push(...i.slice(0,a))}),r}var J_=e=>t=>n=>r=>{var c;if(r.type!==Z_){n(r);return}let o=t.getState().styleSuggestions.list;n(r);let s=t.getState(),i=s.styleSuggestions.list,a=(c=s.conversation)==null?void 0:c.current;if(o===i)return;let l=P9(o,i);r.type===Z_&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var A9=hd({assistants:EC,auth:Zb,conversation:sE,contentTypes:CA,passwordlessToken:d_,entities:ZA,handlingTime:q_,info:RE,input:yE,settings:TC,profile:IA,search:LE,styleSuggestions:OI,ui:bI,textSuggestions:aI});function eM(e){return Hb({reducer:A9,middleware:t=>{var r;let n=t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI}},serializableCheck:!1}).concat(Y_()).concat(Q_({debounce:200})).concat(X_({debounce:500})).concat(J_(e.deepdeskAPI));return((r=e.middleware)!=null?r:[]).reduce((o,s)=>o.concat(s),n)},preloadedState:e.preloadedState})}function tM(e,t,n){if(t==="")return null;let r=new RegExp(`\\b${Zm(t)}\\b`,"gi"),o,s=null;for(;(o=r.exec(e))!==null&&!(o.index>n);)s={start:o.index,end:o.index+o[0].length};return s}var I9=e=>{var t,n;return(n=(t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())!=null?n:"unknown"},_9=e=>t=>n=>r=>{var l,c,u,f,d,p;let o=t.getState(),s=$s("inlineSuggestions")(o),i=$s("autoSelectSuggestion")(o)||s;switch(r.type){case Yi.toString():{!r.payload&&e.emit("logout",void 0);break}case Dd.fulfilled.toString():{e.emit("logout",void 0);break}case Cr.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 Hs.toString():e.logSendMessage(r.payload);break;case mf.toString():e.emit("call-to-action",{cue:r.payload});break;case Rn.fulfilled.toString():if(!r.isBroadcasted){let{externalConversationId:h,currentExternalIdAtRequest:y}=(c=r.payload)!=null?c:{};(!h||!y||h===y)&&e.broadcast(Lh,r,!1)}break;case Rn.rejected.toString():break;default:break}let a=n(r);switch(r.type){case Hs.toString():e.handleAfterSendMessage(r.payload);break;case bu.toString():e.onUpdateShowTabHint(r.payload);break;case yg.toString():e.logHandlingTime();break;case Zi.toString():e.broadcast(Yd,r);break;case zs.toString():e.broadcast(Yd,r);break;case gf.toString():t.dispatch(zs({source:"assistant",assistantCode:r.payload.code}));break;case"analytics/logEvent/fulfilled":{let h=o.assistants.cues.find(y=>y.code===r.meta.arg.data.assistantCode);e.emit("event",_(b({},r.meta.arg),{cue:h}));break}case Tn.toString():{let{start:h,end:y}=o.input.selection;e.emit("select-suggestion",_(b({type:I9(r.payload.suggestion)},r.payload),{replace:r.payload.replace==="selection"?{start:h,end:y}:{start:0,end:y}})),s&&t.dispatch(Wo([]));break}case LI.toString():{let{keyword:h,suggestion:y,eventMetrics:S}=r.payload,{text:g,selection:m}=o.input,v=tM(g,h,(u=m==null?void 0:m.end)!=null?u:g.length);if(!v)break;e.emit("select-suggestion",{text:y,type:"style",replace:v,suggestion:{text:y,source:"style"},eventMetrics:S});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 Wo.toString():{i&&r.payload.length>0&&t.dispatch($d(0));break}case Rn.fulfilled.toString():{let{evaluationId:h,output:y,externalConversationId:S}=r.payload,g=r.meta.arg.assistantCode;if(e.emit("event",{name:"Assistant evaluation completed",data:{evaluationId:h,assistantCode:g,assistantOutput:yC(y),externalConversationId:S,evaluationStatus:"success"}}),!r.meta.arg.skipState){let m=t.getState().assistants.cues;e.emit("cues",m)}break}case Rn.rejected.toString():{let h=r.meta.arg.assistantCode,y=(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:h,assistantOutput:"",externalConversationId:y,evaluationStatus:"failed"}});break}default:break}return a},nM=_9;function Ex(e){return e.toISOString().replace("T"," ").replace("Z","")}var M9=(e,t)=>t.version,rM=Yt([Ji,Wn,$_,M9],(e,t,n,r)=>{if(!t)return Z.warn("No conversationId for handling time metrics"),null;let{startTime:o,stopTime:s}=n;return!o||!s?(Z.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:Ex(o),timeStop:Ex(s)}});function oM(e,t){let{text:n,metrics:{numPaste:r,pastes:o,textSuggestions:s}}=e.input,i=n.length;return{source:"agent",clientVersion:t.version,pastes:o,lenTextTotal:i,numPastes:r,suggestions:s}}var Fu=class extends Error{};function L9(){let e,t;return{promise:new Promise((r,o)=>{e=r,t=o}),resolve:e,reject:t}}var vg=class{constructor(){this.queues={}}push(t,n){let r=()=>{let s=this.queues[t][1];s?(this.queues[t]=[s.promise,null],s.resolve()):delete this.queues[t]};if(!this.queues[t]){let s=n().finally(r);return this.queues[t]=[s,null],s}this.queues[t][1]&&this.queues[t][1].reject(new Fu("Queued async function is outdated"));let o=L9();return this.queues[t][1]=o,o.promise.then(()=>n().finally(r))}};function Cx(e,t){var s;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return Cx(r,t);let o=(s=e.ownerDocument.defaultView)==null?void 0:s.frameElement;return o?Cx(o,t):null}function Tx(e,t){return Cx(e,t)}var O9={accepted:"onConversationAcceptedAssistants","new-message":"onConversationNewMessageAssistants",ended:"onConversationEndedAssistants"},sM=(e,t)=>{var o,s,i;if(!((i=(s=(o=e.uiConfig)==null?void 0:o.widget)==null?void 0:s.types.find(a=>a.type==="cues"))==null?void 0:i.isActive))return Z.warn("Triggered a conversation assistant, but cues are not configured in widget."),[];let r=e[O9[t]];if(r&&r.length>0){let a=r.map(l=>l.code);return e.summarizerAssistantNew&&t!=="ended"&&(a=a.filter(l=>l!==e.summarizerAssistantNew)),a}return Z.warn(`No assistant set in profile for conversation event "${t}"`),[]};function N9(e){var t,n,r,o;return(o=(r=(n=(t=e.uiConfig)==null?void 0:t.widget)==null?void 0:n.types)==null?void 0:r.some(s=>s.type==="knowledge-assist"&&s.isActive))!=null?o:!1}function iM(e){var n,r;return((r=(n=e.widgetInteractiveAssistants)==null?void 0:n.length)!=null?r:0)>0&&N9(e)?!0:!!e.knowledgeAssistantNew||!!e.knowledgeAssistant}function D9(e){return typeof e=="object"&&e!==null&&"tagName"in e}function Sg(e){return D9(e)&&(Pi(e)||Xm(e))}var lM,Qr=new Map,F9=["bottom","height","left","right","top","width"],aM=(e,t)=>!e&&!t?!1:e&&!t||!e&&t?!0:F9.some(n=>e[n]!==t[n]);function cM(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,...cM(t)]:[]}function uM(e,t){return!e||!t?null:_(b({},e),{top:e.top+t.top,left:e.left+t.left})}var xg=!1,dM=()=>{xg=!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();aM(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{let n=t.parentRects?t.parentRects.reduce(uM,t.rect):t.rect;aM(n,t.totalRect)&&t.callbacks.forEach(r=>r(n)),t.totalRect=n}),Qr.size===0){xg=!1;return}lM=window.requestAnimationFrame(dM)};function kx(e,t){let n=cM(e),r=[],o=n.map((s,i)=>kx(s,a=>{r[i]=a;let l=Qr.get(e);if(!l)return;let c=r.reduce(uM,l.rect);l.callbacks.forEach(u=>u(c))}));return{observe(s=!0){if(o.forEach(i=>i.observe(!1)),Qr.has(e)){let i=Qr.get(e);i.callbacks.push(t),i.rect&&t(i.rect)}else Qr.set(e,{rect:void 0,callbacks:[t],parentRects:r});s&&!xg&&dM()},unobserve(){o.forEach(i=>i.unobserve());let s=Qr.get(e);if(s){let i=s.callbacks.indexOf(t);i>=0&&s.callbacks.splice(i,1),s.callbacks.length||Qr.delete(e),Qr.size||(cancelAnimationFrame(lM),xg=!1)}}}}var fM,Zr=new Map,pM=()=>{Zr.forEach((e,t)=>{if(!t.isConnected){Zr.delete(t);return}let{clientHeight:n,scrollHeight:r}=t,o=r>n;e.visible!==o&&(e.visible=o,e.callbacks.forEach(s=>s(e.visible)))}),Zr.size!==0&&(fM=window.requestAnimationFrame(pM))};function mM(e,t){return{observe(){let n=Zr.size===0;Zr.has(e)?Zr.get(e).callbacks.push(t):Zr.set(e,{visible:void 0,callbacks:[t]}),n&&pM()},unobserve(){let n=Zr.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||Zr.delete(e),Zr.size||cancelAnimationFrame(fM)}}}}var Rx=["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 Px(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function cl(e){return Number.parseFloat(e)}function wg(e){return Math.round(e*1e6)}function gM(e){return e/1e6}function Ax(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=cl(e.width),s=cl(e.borderLeftWidth),i=cl(e.borderRightWidth),a=cl(e.paddingRight),l=gM(wg(o)-wg(s)-wg(i)),c=gM(wg(r));if(l-c>2){let u=l-c;n.style.paddingRight=`${a+u}px`}}function zu(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",gi(n);let r=window.getComputedStyle(e),o=!0,s=()=>{n.scrollTop=e.scrollTop};Px(r,n,Rx),Ax(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",s));let i=mM(e,()=>{Px(r,n,Rx),Ax(r,e,n),s(),setTimeout(s,0)}),a,l=!0,c=kx(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(Px(r,n,Rx),Ax(r,e,n),s(),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(),h=window.getComputedStyle(t.closestScrollElement),y=cl(h.borderTopWidth),S=cl(h.borderBottomWidth),g=p.top+y-d.top,m=d.top+d.height+-(p.top+p.height-S);n.style.clipPath=`inset(${g}px 0px ${m}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(),i.observe(),[n,()=>{e.removeEventListener("scroll",s),c.unobserve(),i.unobserve(),n.remove()}]}function z9(e){return e.offsetParent!==null}function hM(e){if(!z9(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 bg(e,t,n=100){let r=hM(e);t({isVisible:r});let o=setInterval(()=>{let s=hM(e);s!==r&&(r=s,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var yM=(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){Z.warn("[Deepdesk] SessionStorage is blocked by browser")}}});var Re=E(A());var vM=yM("showTabHint",!0),ul=class ul{constructor({deepdeskUrl:t,version:n=ul.version||"unknown",locale:r="en-US",token:o,fetch:s,productName:i,createCustomChannel:a,websocketClient:l=hg}){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 vg;this.isMounted=!1;this.shouldRender=!0;this.loadProfileConfigPromise=null;this.loadProfileConfigPromiseKey=null;this.personalCollectionSyncPendingKey=null;this.personalCollectionSyncDrainPromise=null;let c=t.replace(/\/api$/,"");this.deepdeskApi=new Oo(c,{token:o,fetch:s}),this.version=n,this.instanceId=ul.count++;let u={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[nM({broadcast:(h,y,S)=>{this.broadcastEvents.send(h,y,S)},emit:(h,y)=>this.emit(h,y),handleAfterSendMessage:h=>this.handleAfterSendMessage(h),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:h=>this.logSendMessage(h),onUpdateShowTabHint:h=>vM.update(h),sendEvent:(h,y)=>this.deepdeskApi.sendEvent(h,y)})]};this.store=eM(u),this.broadcastEvents=new B_({debug:!0,deepdeskUrl:c,eventMap:OE(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 h;return(h=kt(this.state))!=null?h:!1})}),this.whenLoggedIn(()=>this.ws.connect()),this.store.dispatch(bu(vM.value())),this.store.dispatch(Xl({locale:r,adminUrl:c,productName:i}));let f=[],d=h=>{if(!h.conversationId)return;let y=()=>{this.conversationId()===h.conversationId&&this.store.dispatch(wC(h))};this.hasConversation()?y():f.push(y)};this.ws.on("assistants::direct_response",d),this.ws.on("assistants::user_notification",d),this.ws.on("assistants::response_chunk",h=>{if(!h.conversationId)return;let y=()=>{this.conversationId()===h.conversationId&&this.store.dispatch(xC(h))};this.hasConversation()?y():f.push(y)}),this.ws.on("assistants::suggest_as_reply",h=>{if(!h.conversationId)return;let y=()=>{this.conversationId()===h.conversationId&&this.store.dispatch(Zi([{text:h.payload.message,type:"text",source:"assistant",assistantCode:h.code,sourceLabel:h.name}]))};this.hasConversation()?y():f.push(y)});let p=this.whenConversationLoaded(()=>{var h;this.broadcastEvents.setExternalId((h=this.state.conversation.current)==null?void 0:h.externalId),f.forEach(y=>y()),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=Fs(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?(Z.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(Z.warn("Profile has not been loaded (yet)"),!0):(Z.warn("No conversation loaded (yet)"),!0)}whenLoggedIn(t){if(kt(this.state))t();else{let n=this.subscribe(kt,r=>{r&&t()});this.disposeHandlers.push(()=>{n()})}}login(){return this.store.dispatch(Yi(null)),this.store.dispatch(no()),new Promise(t=>{this.whenLoggedIn(()=>t())})}isLoggedIn(){return M(this,null,function*(){return(yield this.store.dispatch(no())).payload})}isConversationSupported(t,n){return M(this,null,function*(){return(yield this.store.dispatch(kh({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(Bd(_(b({},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(Ud({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(Rh(_(b({},t),{metadata:(r=t.metadata)!=null?r:{}})))).payload})}postMessages(t){return M(this,null,function*(){yield this.store.dispatch(Ph(t))})}updateConversation(t){return M(this,null,function*(){return(yield this.store.dispatch(Vd(t))).payload})}resetConversation(){this.store.dispatch(Ke()),this.loadProfileConfigPromise=null,this.loadProfileConfigPromiseKey=null,this.dynamicThunkObject.conversationQuery=null}clearDisplayedAnswers(){var n;let t=this.store.getState().conversation.current;t&&(zd((n=t.externalId)!=null?n:void 0),this.store.dispatch(cn()))}reloadConversationContext(o){return M(this,arguments,function*({conversation:t,visitorInfo:n,clearDisplayedUi:r=!1}){let s=yield this.upsertConversation(t);if(!(s!=null&&s.id))throw new Error("Failed to upsert conversation");r&&this.clearDisplayedAnswers(),n&&this.setVisitorInfo(n)})}publishConversationTranscript(t){return M(this,null,function*(){if(!this.store.getState().conversation.current)return;let r=t.map(o=>({source:o.source,text:o.text}));this.setConversationQuery(()=>Promise.resolve(r)),t.length>0&&(yield this.postMessages(t))})}configure(t){this.store.dispatch(Xl(t))}setVisitorInfo(t){this.store.dispatch(EE(t))}setCustomData(t){this.store.dispatch(CE(t))}setAgentInfo(t,n){return M(this,null,function*(){var o;yield this.store.dispatch(Al(b(b({},t),n))),(o=this.state.info.agentInfo)!=null&&o.agentNickname||this.broadcastEvents.send(qd,{showNicknameDialog:!0})})}setAgentSettings(t){return M(this,null,function*(){yield this.store.dispatch(Ih(t))})}getAgentSettings(){return M(this,null,function*(){return(yield this.store.dispatch(_h())).payload})}getMe(){return M(this,null,function*(){return this.deepdeskApi.getMe()})}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(jd({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),suggestionTextStart:this.inputMediator.getSuggestionTextStart()}))}notifyExternalSuggestion(t){this.store.dispatch(Tn(t))}evaluateAssistant(t,n){return M(this,null,function*(){var u;let{input:r={},attachments:o=[],transcript:s,showCuesInWidget:i=!0,includeMetadata:a,externalConversationId:l}=n||{},c=yield this.store.dispatch(Rn({assistantCode:t,attachments:o,transcript:s,includeMetadata:a,input:r,externalConversationId:l,skipState:!i}));if(c.error)throw new Error(`Assistant evaluation failed: ${(u=c.payload)!=null?u:c.error.message}`);return c.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){Z.warn("Can't evaluate assistant when profile is not loaded yet.");return}let o=sM(r,t),s=(f=n==null?void 0:n.showCuesInWidget)!=null?f:!0,d=n!=null?n:{},{showCuesInWidget:i}=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(h=>this.queues.push(h,()=>M(this,null,function*(){var S,g;let y=yield this.store.dispatch(Rn(b(_(b({assistantCode:h,includeMetadata:!0},a),{skipState:!s}),n!=null&&n.attachments&&(n==null?void 0:n.attachments.length)>0?{attachments:n==null?void 0:n.attachments}:{})));if(y.error)throw new Error(`Assistant evaluation failed: ${(S=y.payload)!=null?S:y.error.message}`);return{assistantCode:h,evaluationId:y.payload.evaluationId,output:y.payload.output,externalConversationId:(g=y.payload.externalConversationId)!=null?g:l}})).catch(y=>{if(y instanceof Fu)return Z.warn(`Queued assistant "${h}" was outdated and dropped`),null;throw y})));if(!s)return c.filter(h=>h!==null)})}handleKeyDown(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui,{textSuggestions:o,selectedSuggestionIndex:s,selection:i}=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(uE(Ah(t))),!qr(this.state)||t.key!=="Tab"&&!c)return;let h=()=>{n||!p||i&&(t.shiftKey||(this.store.dispatch(pE()),t.preventDefault()))},y=()=>{n||!p||f&&s<=0||i&&(t.shiftKey||(this.store.dispatch(mE()),t.preventDefault()))};switch(t.key){case"ArrowUp":d==="below"?y():h();break;case"ArrowDown":{d==="below"?h():y();break}case"Escape":{n||(this.store.dispatch($d(-1)),this.store.dispatch(bs({collapse:!0})),this.store.dispatch(xI(!0)),t.preventDefault());break}case"Tab":{t.preventDefault();let S=Qi(this.state);if(!S)return;this.store.dispatch(bu(!1)),this.store.dispatch(Tn({text:S.text,suggestion:S,eventMetrics:{inputType:"tab"},replace:"until-selection-end"}));break}case" ":{if(f||this.state.input.selectedSuggestionIndex===-1)return;let S=Qi(this.state);if(!S)return;this.store.dispatch(Tn({text:S.text,suggestion:S,eventMetrics:{inputType:"space"},replace:"until-selection-end"}));break}case"Enter":{if(f||t.shiftKey||this.state.input.selectedSuggestionIndex===-1)return;let S=Qi(this.state);if(!S)return;this.store.dispatch(Tn({text:S.text,suggestion:S,eventMetrics:{inputType:"enter"},replace:"until-selection-end"})),t.preventDefault();break}default:}n&&r&&this.store.dispatch(bs({collapse:!1}))}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(Wo([]))}handlingTimeStart(){this.state.handlingTime.startTime||(Z.info("Start handling time"),this.store.dispatch(K_()))}handlingTimeStop(){this.state.handlingTime.startTime&&(Z.info("Stop handling time"),this.store.dispatch(yg()))}logSendMessage(t){let n=oM(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=rM(this.state,{version:this.version});t&&(this.deepdeskApi.sendEvent("Handling Time",{conversationId:this.conversationId(),data:t}),this.store.dispatch(G_()))}notifySubmit(t={}){var n;this.shouldAbort()||(this.store.dispatch(Hs((n=t.text)!=null?n:this.state.input.text)),this.store.dispatch(hE()))}emit(t,n){let r=this.eventListeners[t];r&&r.forEach(o=>{try{o(n)}catch(s){Z.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),Z.error(s)}})}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(TE(t))}whenConversationLoaded(t){let n=()=>this.getConversationLoadedKey(),r=()=>{let s=n();s&&this.loadProfileConfig().then(()=>{if(n()!==s)return;let i=this.state.conversation.current,a=nr(this.state);!(i!=null&&i.id)||i.profileCode&&(a==null?void 0:a.code)!==i.profileCode||t()})};return n()&&r(),this.subscribe(s=>this.getConversationProfileKey(s.conversation.current),s=>{s&&r()})}overlayContainerFactory(t,n,r,o){let[s,i]=zu(n,r);return s.setAttribute("translate","no"),s.dataset.testid=t,o&&s.classList.add(o),[s,i]}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 s=(a=t.ownerDocument.defaultView)==null?void 0:a.frameElement,i=s?s.ownerDocument.defaultView:null;if(s&&(i===window||(i==null?void 0:i.parent)===window)){let[l,c]=zu(s,{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 gi(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),Z.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()?(Z.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(gE(r.metrics))):Z.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(!Sg(t))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let d=n,{customStyles:r,closestScrollSelector:o,floatingMenuParent:s,appendOverlayTo:i,inputMediator:a}=d,l=ie(d,["customStyles","closestScrollSelector","floatingMenuParent","appendOverlayTo","inputMediator"]),c={customStyles:r,closestScrollSelector:o,floatingMenuParent:s,appendOverlayTo:i};this.configure(l),this.settings.automaticHandlingTime&&this.setupHandlingTime(t),gi(t),this.inputMediator=a||(Pi(t)?new Mi(t):new _i(t)),this.inputMediator.on("change",({plainText:p,rawHTML:h,suggestionTextStart:y})=>{this.store.dispatch(jd({text:p,html:h,suggestionTextStart:y}))}),this.inputMediator.on("keyup",p=>{this.store.dispatch(dE(Ah(p)))}),this.inputMediator.on("keydown",p=>{this.handleKeyDown(p)}),this.inputMediator.on("paste",({pastedText:p,selectionText:h})=>{this.store.dispatch(fE({text:p,selectionText:h}))}),this.inputMediator.on("cut",({selectionText:p})=>{this.store.dispatch(cE(p))});let u;this.inputMediator.on("selection",p=>{clearTimeout(u),p===null?u=setTimeout(()=>{p!==null&&this.store.dispatch(Kd(p))},500):this.store.dispatch(Kd(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($s("inlineSuggestions"),()=>{this.renderSuggestions(t,c)}),this.subscribe($s("suggestionsPlacement"),()=>{this.renderSuggestions(t,c)});let f=this.renderOverlays(n);this.unmountHandlers.push(()=>{f.unmount()}),this.store.dispatch(jd({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),suggestionTextStart:this.inputMediator.getSuggestionTextStart()})),this.store.dispatch(Kd(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,s=a=>{o=a,i()},i=()=>{r==null||r.render((0,Re.jsx)(Po,{store:this.store,children:(0,Re.jsx)(oo,{broadcastEvents:this.broadcastEvents,children:(0,Re.jsx)(FI,{id:"deepdesk-nickname-dialog",error:o,onSave:a=>M(this,null,function*(){try{yield this.store.dispatch(wE({agentNickname:a})).unwrap(),console.log("setAgentNickname",a),this.broadcastEvents.send(qd,{showNicknameDialog:!1}),this.nicknameDialogUnsubscribe&&this.nicknameDialogUnsubscribe()}catch(l){Z.error("Error setting agent nickname",l),s("error"),this.nicknameDialogFailed=!0}})})})}))};i(),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,s;(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(i=>i()),this.unmountHandlers=[],(s=this.inputMediator)==null||s.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,s,i;(r=this.floatingMenu)==null||r.unmount(),(o=this.inlineSuggestions)==null||o.unmount(),(s=this.aboveSuggestions)==null||s.unmount(),(i=this.belowSuggestions)==null||i.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"),s=(0,No.createRoot)(o);s.render((0,Re.jsx)(Po,{store:this.store,customStyles:r,children:(0,Re.jsx)(oo,{broadcastEvents:this.broadcastEvents,children:(0,Re.jsx)(NI,{})})}));let i=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",i),{unmount:()=>{var a;(a=this.inputMediator)==null||a.off("caretposition",i),s.unmount(),o.remove()}}}renderAboveOrBelowSuggestions(t,n,r){let{customStyles:o,closestScrollSelector:s,appendOverlayTo:i}=n,a=s&&Tx(t,s)||void 0,[l,c]=this.overlayContainerFactory("deepdesk-tab-completion",a||t,{appendTo:i,closestScrollElement:a,mirrorOverflow:!0,onRemove:()=>this.unmount()},o==null?void 0:o.rootNode),[u,f]=this.overlayContainerFactory("deepdesk-suggestions-overlay",a||t,{appendTo:i,placement:r},o==null?void 0:o.suggestionsRootNode),d=(0,No.createRoot)(l);d.render((0,Re.jsx)(Po,{store:this.store,customStyles:o,children:(0,Re.jsx)(oo,{broadcastEvents:this.broadcastEvents,children:(0,Re.jsx)(l_,{inputElement:t})})}));let p=(0,No.createRoot)(u);return p.render((0,Re.jsx)(Po,{store:this.store,customStyles:o,children:(0,Re.jsx)(oo,{broadcastEvents:this.broadcastEvents,children:(0,Re.jsx)(KI,{onLogIn:()=>this.loginViaPopup().catch(h=>Z.warn(h.message))})})})),{unmount(){d.unmount(),p.unmount(),c(),f()}}}renderFloatingMenu(t,n){let{customStyles:r,closestScrollSelector:o,appendOverlayTo:s,floatingMenuParent:i}=n,a=o&&Tx(t,o)||void 0,[l,c]=this.overlayContainerFactory("floating-menu",a||t,{appendTo:i!=null?i:s},r==null?void 0:r.floatingMenuParent),u=(0,No.createRoot)(l);return u.render((0,Re.jsx)(Po,{store:this.store,customStyles:r,children:(0,Re.jsx)(oo,{broadcastEvents:this.broadcastEvents,children:(0,Re.jsx)(vI,{onLogIn:()=>this.loginViaPopup().catch(f=>Z.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,Re.jsx)(Po,{store:this.store,customStyles:n,children:(0,Re.jsx)(oo,{broadcastEvents:this.broadcastEvents,children:(0,Re.jsx)(pI,{})})})),{unmount(){o.unmount(),r.remove()}}}renderWidget(t,n={}){if(this.widgetElement&&Z.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,isEmbedded:s,signInViaPopup:i,ssoUrl:a,openAdminFeedback:l}=n;this.widgetElement=t,this.configure({showImages:o,isEmbedded:s,signInViaPopup:i});let c;if(a)try{c={url:new URL(a,this.settings.adminUrl).toString()}}catch(u){Z.warn(`Invalid ssoUrl '${a}' passed to renderWidget`)}this.widgetRoot=(0,No.createRoot)(t),this.widgetRoot.render((0,Re.jsx)(Po,{store:this.store,customStyles:r,children:(0,Re.jsx)(oo,{broadcastEvents:this.broadcastEvents,children:(0,Re.jsx)(bm,{report:u=>this.deepdeskApi.sendEvent(cA,{data:u}),children:(0,Re.jsx)(O_,{assistantOptions:n.assistantOptions,knowledgeAssistOptions:n.knowledgeAssist,openAdminFeedback:l,onLogIn:()=>this.loginViaPopup(c).catch(u=>Z.warn(u.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:s}=r,i=(0,No.createRoot)(n);return i.render((0,Re.jsx)(Po,{store:this.store,customStyles:o,children:(0,Re.jsx)(oo,{broadcastEvents:this.broadcastEvents,children:(0,Re.jsx)(vx,{children:(0,Re.jsxs)(vm,{assistantCode:t,initialQuestion:s,evaluateKnowledgeAssistFn:Yl,children:[(0,Re.jsx)(ji,{children:(0,Re.jsx)(xm,{title:r.title,emptyState:r.emptyState})}),(0,Re.jsx)(yx,{children:(0,Re.jsx)(Sm,{})})]})})})})),{unmount(){i.unmount()}}}setupHandlingTime(t){let n=bg(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){wm(t)&&t.message==="Unauthorized"&&this.login()}getConversationProfileKey(t){var n;if(t!=null&&t.id)return`${t.id}:${(n=t.profileCode)!=null?n:""}`}getProfileLoadKey(){var n;let t=this.state.conversation.current;return t!=null&&t.profileCode&&(n=this.getConversationProfileKey(t))!=null?n:null}isCurrentProfileLoadKey(t){return this.getProfileLoadKey()===t}getConversationLoadedKey(){return this.getConversationProfileKey(this.state.conversation.current)}resetProfileDerivedSettings(){this.store.dispatch(P0()),this.store.dispatch(Xl(uy))}syncPersonalCollectionForConversation(t){this.personalCollectionSyncPendingKey=t,this.ensurePersonalCollectionSyncDrain()}ensurePersonalCollectionSyncDrain(){return this.personalCollectionSyncDrainPromise?this.personalCollectionSyncDrainPromise:(this.personalCollectionSyncDrainPromise=this.drainPersonalCollectionSync().finally(()=>{this.personalCollectionSyncDrainPromise=null,this.personalCollectionSyncPendingKey&&this.ensurePersonalCollectionSyncDrain()}),this.personalCollectionSyncDrainPromise)}drainPersonalCollectionSync(){return M(this,null,function*(){for(;this.personalCollectionSyncPendingKey;){let t=this.personalCollectionSyncPendingKey;if(this.personalCollectionSyncPendingKey=null,!this.isCurrentProfileLoadKey(t))continue;let n=this.state.conversation.current,r=n==null?void 0:n.id;if(!(!r||!n.profileCode))try{yield this.deepdeskApi.syncPersonalCollection(r)}catch(o){this.isCurrentProfileLoadKey(t)&&Z.warn("Failed to sync personal collection for profile",o)}}})}loadProfileConfig(t=!0){let n=this.getProfileLoadKey();if(!n)return this.loadProfileConfigPromise=null,this.loadProfileConfigPromiseKey=null,this.resetProfileDerivedSettings(),Promise.resolve();let r=this.state.conversation.current,o=nr(this.state);if(o&&o.code!==(r==null?void 0:r.profileCode)&&(this.loadProfileConfigPromise=null,this.loadProfileConfigPromiseKey=null,this.resetProfileDerivedSettings()),this.loadProfileConfigPromise&&this.loadProfileConfigPromiseKey===n)return this.loadProfileConfigPromise;this.loadProfileConfigPromise=null,this.loadProfileConfigPromiseKey=n;let s=Promise.resolve().then(()=>M(this,null,function*(){try{yield this.store.dispatch(su()).unwrap()}catch(l){if(l===Xa)return this.loadProfileConfigPromise===s&&(this.loadProfileConfigPromise=null,this.loadProfileConfigPromiseKey=null),t&&this.isCurrentProfileLoadKey(n)&&!nr(this.state)?this.loadProfileConfig(!1):void 0;throw l}if(!this.isCurrentProfileLoadKey(n))return;let i=nr(this.state),a=this.state.conversation.current;!i||i.code!==(a==null?void 0:a.profileCode)||(this.store.dispatch(Xl({showSearch:i.search,showImageSearch:i.imageSearch,showEntitiesCommand:i.entitiesCommand,showSummaryCommand:!!i.summarizerAssistantNew,showKnowledgeSearch:iM(i),recommendTextSuggestions:i.recommendTextSuggestions})),this.syncPersonalCollectionForConversation(n))})).finally(()=>{this.loadProfileConfigPromise===s&&(nr(this.state)||(this.loadProfileConfigPromise=null,this.loadProfileConfigPromiseKey=null))});return this.loadProfileConfigPromise=s,s}loginViaPopup(t){return M(this,null,function*(){return new Promise((n,r)=>{this.store.dispatch(Fd());let o=new MessageChannel,s=o.port1,i=this.settings.adminUrl,a=new URL(t!=null&&t.url?t==null?void 0:t.url:`${i}/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)};s.onmessage=p=>M(this,null,function*(){var h,y;if((h=p.data)!=null&&h.jwt)try{yield this.deepdeskApi.exchangeTokenForAccessCookie((y=p.data)==null?void 0:y.jwt),yield this.isLoggedIn(),this.broadcastEvents.send(Ml),l=!0,o.port1.close(),n()}catch(S){console.error(S),r(S)}finally{l=!0,c()}});let u=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");if(u===null){r(new Error("Popup blocked by browser"));return}let f=p=>M(this,null,function*(){var h;if(!(p.origin!==a.origin||p.source!==u))switch((h=p.data)==null?void 0:h.type){case"deepdesk-popup-request-origin":{try{let y=JSON.stringify({type:"deepdesk-popup-parent-origin"});u.postMessage(y,a.origin)}catch(y){Z.error("Error posting message to popup",y),r(y)}break}case"deepdesk-popup-loaded":{try{let y=JSON.stringify({type:"deepdesk-popup-create-channel"});u.postMessage(y,a.origin,[o.port2])}catch(y){Z.error("Error posting message to popup",y),r(y)}break}case"deepdesk-popup-error":{if(c(),p.data.message==="Platform account url mismatch"){let y="Please contact your administrator: The page that opened the popup is not a trusted origin.";Z.warn(y),this.store.dispatch(bh(y)),r(new Error(y));return}if(p.data.message==="Timeout"){let y="Please contact your administrator: Popup timed out. Check if the account's platform.url or account.url is configured correctly.";Z.warn(y),this.store.dispatch(bh(y)),r(new Error(y));return}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(Hm()))})}refreshWidgetSuggestions(){return M(this,null,function*(){if(!this.widgetRoot)return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=iu(this.state);try{n.forEach(({type:r})=>{switch(r){case"entities":this.store.dispatch(Cr());break;case"pinned-messages":case"sticky-messages":break;default:fd.includes(r)||this.store.dispatch(Tr(r))}})}catch(r){this.handleError(r)}})}};ul.version="19.6.2-beta.18",ul.count=0;var Hu=ul;function H9(e){return M(this,null,function*(){var o,s,i;let n=yield((o=e.fetch)!=null?o:window.fetch)(e.url),r=yield n.blob();return new File([r],e.name,{type:(i=(s=e.mimeType)!=null?s:n.headers.get("Content-Type"))!=null?i:"image/jpeg"})})}function SM(e,t){return M(this,null,function*(){let n=yield H9(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 xM(e,t,n){return M(this,null,function*(){yield new Oo(e).authenticateWithKey(t,n)})}function wM(e){return e.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}function bM(r,o){return M(this,arguments,function*(e,t,n={}){var f,d;let{value:s}=e,{start:i,end:a}=(f=n.replace)!=null?f:{start:0,end:s.length},l=`${s.slice(0,i)}${t}${s.slice(a)}`,c=(d=n.selectionAfter)!=null?d:{start:i+t.length,end:i+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 EM(r,o){return M(this,arguments,function*(e,t,n={}){let s=n.replace?Rs(e,n.replace.start,n.replace.end):al(e),i,a=()=>{if(n.setRange)return n.setRange(s.cloneRange());s.deleteContents(),i=document.createElement("span"),s.insertNode(i),n.insertBRs!==!1?t.split(`
85
85
  `).reverse().forEach((l,c)=>{c>0&&s.insertNode(document.createElement("br")),s.insertNode(document.createTextNode(l))}):s.insertNode(document.createTextNode(t))};return Promise.resolve(a()).then(()=>{try{if(n.selectionAfter!==!1){e.focus();let l=n.selectionAfter?Rs(e,n.selectionAfter.start,n.selectionAfter.end):(s.collapse(!1),s),c=window.getSelection();c==null||c.removeAllRanges(),c==null||c.addRange(l)}if(!i)return;i.scrollIntoView&&i.scrollIntoView({block:"nearest",inline:"nearest"})}finally{i&&i.remove()}})})}function B9(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 U9(e){let t=document.createDocumentFragment();return e.split(`
86
86
  `).forEach((n,r)=>{r>0&&t.appendChild(document.createElement("br"));let o={index:0},s=0;for(;o=n.slice(s).match(/(\[([^\]]+)])\(([^)]+)\)/);){let i=document.createElement("a");i.href=o[3],i.setAttribute("target","_blank"),i.setAttribute("rel","noopener noreferrer"),i.appendChild(document.createTextNode(o[2])),t.appendChild(document.createTextNode(n.slice(s,s+o.index))),t.appendChild(i),s=s+o.index+o[0].length}t.appendChild(document.createTextNode(n.slice(s)))}),t}function CM(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):CM(n,t)}function TM(o,s){return M(this,arguments,function*(e,t,{isBlock:n,isHTML:r}={}){let i;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;i=document.createElement("span"),u.insertNode(i);let f=r?B9(t):U9(t);n?CM(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(),!!i)try{i.scrollIntoView&&i.scrollIntoView({block:"nearest",inline:"nearest"})}finally{i&&i.remove()}})})}return qM(V9);})();
87
87
  /*! Bundled license information:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deepdesk/deepdesk-sdk",
3
- "version": "19.6.2-beta.17",
3
+ "version": "19.6.2-beta.18",
4
4
  "description": "Deepdesk SDK",
5
5
  "author": "Lukas Batteau",
6
6
  "license": "ISC",