@deepdesk/deepdesk-sdk 17.1.4 → 17.1.5

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.
@@ -79,7 +79,7 @@ Please report this to https://github.com/markedjs/marked.`,t){let o="<p>An error
79
79
  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
80
80
  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 f0=b(R()),M4={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},BR=({className:e,color:t})=>(0,f0.jsx)("svg",{className:e,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:(0,f0.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:M4[t||"pink"]})});var UR={root:"dd-LbeUM",text:"dd-Dpfn1",isLoggedIn:"dd-XvHAn",isLoggedOut:"dd-21y-z",icon:"dd-8rLqS",logo:"dd-slXhD",lock:"dd-ByzlR"};var p0={};pt(p0,{enUS:()=>O4,nlNL:()=>N4});var O4={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Search"}]},N4={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Zoeken"}]};var mi=b(R()),$R=({onLogIn:e})=>{let t=ie(p0),n=te("floatingMenu"),r=te("productName"),o=ve(),s=j(jt),i=_("FloatingMenu",UR);if(s===null||n===!1)return null;let a=()=>{s===!0?o(Fn(!0)):e()};return(0,mi.jsxs)("button",{type:"button",className:(0,VR.default)(i.root,{[i.isLoggedIn]:s,[i.isLoggedOut]:!s}),onClick:a,children:[(0,mi.jsx)("div",{className:i.text,children:t(s?"search":"signin",{productName:r})}),(0,mi.jsxs)("div",{className:i.icon,children:[(0,mi.jsx)(BR,{className:i.logo,color:"pink"}),s===!1&&(0,mi.jsx)(HR,{className:i.lock})]})]})};var Kp=b(Y());function Nr(e){let{showMidSentenceSuggestions:t,showSuggestionsBeforePattern:n,showSuggestionsAfterPattern:r}=e.settings,{text:o,selection:s}=e.input;return 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 _4={showTabHint:!1,inputHasFocus:!1,overlayCollapsed:!1,openOverlayWhenTyping:!1,overlayCollapsedUserOverwrite:!1},$p=({ui:e})=>e.overlayCollapsed,jR=ke({name:"ui",initialState:_4,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:eu,setInputFocus:jp,setOverlayCollapsed:is,setOpenOverlayWhenTyping:WR,setOverlayCollapsedUserOverwrite:KR}=jR.actions,GR=jR.reducer;var JR=b(Y());var as=b(Y());var qR=b(Y());function YR(e,t,n){(0,qR.useEffect)(()=>{let r=e.current;return r?(r.addEventListener(t,n),()=>{r.removeEventListener(t,n)}):()=>{}},[e,t,n])}var XR={root:"dd-1MBCO",actions:"dd--x4cy",closeIconContainer:"dd-1z5NR",closeIcon:"dd-8qMF-",badge:"dd-4Fpkz",formattedText:"dd-EzvTB"};var tu=b(R()),QR=({title:e})=>(0,tu.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"18px",height:"18px",viewBox:"0 0 24 24","aria-labelledby":"closeTitle",children:[(0,tu.jsx)("title",{id:"closeTitle",children:e}),(0,tu.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 m0={};pt(m0,{enUS:()=>D4,nlNL:()=>F4});var D4={assistant:[{type:0,value:"Assistant"}],close:[{type:0,value:"Close"}]},F4={assistant:[{type:0,value:"Assistent"}],close:[{type:0,value:"Sluiten"}]};var _r=b(R()),H4=["search","personal-collection-search","search-autocomplete"];function B4(e,t,n,r={}){var s;let o="";return H4.includes(t)?o=mC(mv(e,n,{stripAgentPart:!0}),(s=r.searchKeywords)!=null?s:[n]):o=mv(e,n,r),r.placeholders===!0&&(o=gC(o)),o}var U4=()=>{},V4=({selected:e,suggestion:t})=>{let n=ie(m0),r=te("inlineSuggestions"),o=j(ca),[s,i]=(0,as.useState)(!1),a=te("enableSuggestionFeedback"),l=j(x=>x.input.text),c=ve(),u=_("TextSuggestion",XR),f=(0,as.useRef)(null),d=t.source==="assistant",p=a&&!d;(0,as.useEffect)(()=>{let x=setTimeout(()=>{c(B1({text:t.text,suggestion:t}))},500);return()=>{clearTimeout(x)}},[t]),YR(f,"click",()=>{c(er({suggestion:t,text:t.text,eventMetrics:{inputType:"mouse"},replace:"until-selection-end"}))});let v=()=>{c(Hs({source:t.source,text:t.text,assistantCode:t.assistantCode}))},g=(0,as.useMemo)(()=>B4(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,_r.jsxs)("div",{className:u.root,onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),children:[(0,_r.jsx)(ge,{ref:f,as:"button","data-testid":"suggestions-overlay-item",selected:e,onClick:U4,children:(0,_r.jsx)(Js,{attributes:t.source==="assistant"?{"data-label":n("assistant")}:void 0,containerTagName:"div",noWrap:!1,tagName:"span",className:u.formattedText,content:g})}),p&&s&&(0,_r.jsx)("div",{className:u.actions,children:(0,_r.jsx)(Hp,{source:"overlay",context:l,suggestion:t})}),d&&s&&(0,_r.jsx)("div",{className:u.closeIconContainer,children:(0,_r.jsx)("button",{type:"button",className:u.closeIcon,onClick:v,title:n("close"),children:(0,_r.jsx)(QR,{title:n("close")})})})]})},ZR=V4;var eP=b(R()),$4=({suggestions:e,selectedIndex:t,reverse:n})=>(0,JR.useMemo)(()=>{let o=e.map((s,i)=>(0,eP.jsx)(ZR,{index:i,selected:i===t,suggestion:s},`${s.text}-${s.source}`));return n?o.reverse():o},[e,t,n]),Wp=$4;var tP={root:"dd-PfvRI",paper:"dd-HYlyY"};var nu=b(R()),j4=()=>{let e=(0,Kp.useRef)(null),t=_("InlineSuggestionsOverlay",tP),n=j(Nr),r=ve(),o=j(jt),s=j(la),i=j($p),a=te("showTextSuggestions"),l=j(zs),c=j(Zl);return ss(()=>{setTimeout(()=>{r(is({collapse:!0,skipWhenInputFocus:!0}))})}),(0,Kp.useEffect)(()=>{let u=e.current;if(!u||!u.parentElement)return;u.parentElement.style.left="0px";let f=u.getBoundingClientRect();u.parentElement.style.left=`${Math.min(window.innerWidth-4-f.right,0)}px`}),i||!n||!a||l.length===0||o!==!0||s===!1?null:(0,nu.jsx)("div",{className:t.root,"data-variant":"inline",children:(0,nu.jsx)("div",{ref:e,className:t.paper,children:(0,nu.jsx)(Ht,{children:(0,nu.jsx)(Wp,{suggestions:l,selectedIndex:c})})})})},nP=j4;var ru=b(R()),W4=({children:e})=>{let n=te("locale").replace("-","");return(0,ru.jsx)(jy.Provider,{value:n,children:e})},K4=({store:e,customStyles:t={},children:n})=>(0,ru.jsx)(m1,{store:e,children:(0,ru.jsx)(W4,{children:(0,ru.jsx)(Qa.Provider,{value:t,children:n})})}),ls=K4;var qp=b(Ne()),Da=b(Y());var rP=b(Y());function oP(e,t){let[n,r]=(0,rP.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 sP=()=>/Mac/i.test(navigator.platform);var aP=b(Ne()),yo=b(Y());var g0={};pt(g0,{enUS:()=>G4,nlNL:()=>q4});var G4={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"}]}]},q4={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 iP={root:"dd-uTPjX",anchor:"dd-C8lsZ",anchorButton:"dd-IoSx9"};var cs=b(R()),h0=(e,t,n)=>r=>(0,cs.jsx)("button",{className:e.anchorButton,type:"button",value:t,onClick:n,children:r},t),Y4=({className:e,loginUrl:t,isEmbedded:n,onSnooze:r,onLogIn:o})=>{let s=ie(g0),i=dn(),a=_("Login",iP),l=te("productName"),c=(0,yo.useCallback)(x=>{x.preventDefault(),r&&r(Number.parseInt(x.target.value,10))},[]),u=(0,yo.useCallback)(x=>{x.preventDefault(),i.send(fa,!0)},[t]),f=(0,yo.useMemo)(()=>x=>(0,cs.jsx)("a",{onClick:h=>{h.preventDefault(),o()},href:t,className:a.anchor,target:"_blank",rel:"noreferrer",children:x},"login"),[t]),d=(0,yo.useCallback)(x=>(0,cs.jsx)("button",{type:"button",className:a.anchorButton,onClick:u,children:x},"prompt"),[u]),{min:p,hour:v,day:g}=(0,yo.useMemo)(()=>({min:h0(a,60*10,c),hour:h0(a,60*60,c),day:h0(a,60*60*12,c)}),[]);return(0,cs.jsxs)("div",{className:(0,aP.default)(e,a.root),children:[s("loginPlease",{login:n?d:f,productName:l}),r&&(0,cs.jsxs)(yo.Fragment,{children:[(0,cs.jsx)("br",{}),s("snooze",{min:p,hour:v,day:g})]})]})},Gp=Y4;var lP={root:"dd-DoQhb",text:"dd-Jwnev"};var ou=b(R()),X4=({title:e})=>{let t=_("SearchTrigger",lP),n=ve(),r=ut();return(0,ou.jsxs)("button",{type:"button",className:t.root,onClick:()=>{n(Fn(!0)),r("open search",{via:"autocomplete-overlay"})},children:[(0,ou.jsx)(Aa,{}),(0,ou.jsx)("span",{className:t.text,children:e})]})},cP=X4;var y0={};pt(y0,{enUS:()=>Q4,nlNL:()=>Z4});var Q4={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"}]},Z4={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"}]};var uP={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"};var Ve=b(R()),J4=({onLogIn:e})=>{let t=_("SuggestionsOverlay",uP),n=ie(y0),r=j(Nr),o=j(H1),s=ve(),i=(0,Da.useRef)(null),a=te("searchTriggerKey"),l=te("productName"),c=j($p),u=j(jt),f=j(la),[d,p]=(0,Da.useState)(null),v=te("showSearch"),g=te("showTextSuggestions"),x=te("adminUrl"),y=te("isEmbedded"),[h,m]=oP("dd-snooze-until-ms",0),w=c||h>Date.now(),E=j(zs),k=j(Zl),C=E.filter(N=>N.source!=="gpt").length,A=()=>{w&&m(0),s(KR(!w))},V=N=>{let L=Date.now()+N*1e3;m(L),Z.info(`Snooze until: ${new Date(L)}`),s(is({collapse:!0}))};return(0,Da.useEffect)(()=>{C===0&&p(null)},[E,C]),ss(()=>{s(is({collapse:!0,skipWhenInputFocus:!0}))}),u===null||f===!1?null:u===!1?(0,Ve.jsxs)("div",{ref:i,className:(0,qp.default)(t.root,{[t.isCollapsed]:w}),children:[!w&&(0,Ve.jsxs)("div",{className:t.triggers,children:[(0,Ve.jsx)("div",{style:{flex:1}}),(0,Ve.jsx)("div",{className:t.triggersRight,children:(0,Ve.jsx)(xs,{className:t.toggleButton,title:n("collapse"),onClick:A,isCollapsed:!1})})]}),(0,Ve.jsx)("div",{className:t.toggleButtonWrapper,children:(0,Ve.jsx)(xs,{className:t.toggleButton,title:n("open",{productName:l}),onClick:A,isCollapsed:!0})}),(0,Ve.jsx)("div",{className:t.collapsible,children:(0,Ve.jsx)(Gp,{loginUrl:x,isEmbedded:y,onLogIn:e,onSnooze:V})})]}):!o||!r?null:(0,Ve.jsxs)("div",{ref:i,className:(0,qp.default)(t.root,{[t.isCollapsed]:w}),children:[!w&&(0,Ve.jsxs)("div",{className:t.triggers,children:[(0,Ve.jsx)("div",{style:{flex:1},children:v&&(0,Ve.jsx)("div",{style:{display:"inline-block"},onFocus:()=>{},onMouseOver:()=>p(n(sP()?"searchHintMac":"searchHintWindows",{searchTriggerKey:a.toUpperCase()})),onMouseLeave:()=>p(null),children:(0,Ve.jsx)(cP,{title:n("search")})})}),(0,Ve.jsxs)("div",{className:t.triggersRight,onFocus:()=>{},children:[(0,Ve.jsx)("div",{className:(0,qp.default)(!d&&t.hintsHidden,t.hints),children:d}),(0,Ve.jsx)(xs,{className:t.toggleButton,title:n("collapse"),onClick:A,isCollapsed:!1})]})]}),(0,Ve.jsx)("div",{className:t.toggleButtonWrapper,children:(0,Ve.jsx)(xs,{className:t.toggleButton,title:n("open",{productName:l}),onClick:A,isCollapsed:!0})}),C>0&&g&&(0,Ve.jsx)("div",{className:t.collapsible,onFocus:()=>{},children:(0,Ve.jsx)(Ht,{children:(0,Ve.jsx)(Wp,{suggestions:E,selectedIndex:k,reverse:!0})})})]})},dP=J4;var im=b(Ne());var wo=b(Y());var Fa=b(Y());function Yp(e){return e.contentEditable==="true"}function eF(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 fP(e){let{selectionStart:t,selectionEnd:n}=Yp(e)?eF(e):e;return[t,n]}function pP(e){let[,t]=(0,Fa.useState)(),n=(0,Fa.useRef)(null);return n.current=fP(e),(0,Fa.useEffect)(()=>{let r=()=>{var a;let[o,s]=(a=n.current)!=null?a:[],i=fP(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 mP(e,t){if(!t)return;let n=e,{value:r}=n,[o,s]=t,i=r.match(_u);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 gP=b(Y()),tF=["div","span","mark","strong","b","i","u","em"];function v0(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(tF.includes(o)){let i=Array.isArray(r.props.children)?r.props.children:[r.props.children];return[...e.slice(0,e.length-1),(0,gP.cloneElement)(r,{children:v0(i,t,n+1)})]}return[...e,...t]}function gi(e){return e.tagName.toLowerCase()==="textarea"}var hP={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 SP=b(Ne());var tm=b(Y());var za=b(Y());function yP(e,t){let n;return[(...r)=>{window.cancelAnimationFrame(n);let o=t?t(...r):r;n=window.requestAnimationFrame(()=>{e(...o)})},()=>window.cancelAnimationFrame(n)]}function Xp(e){let t=(0,za.useRef)(null),[n,r]=(0,za.useState)(!1);return(0,za.useEffect)(()=>{var u;let o=!1,s=Number.parseFloat((u=window.getComputedStyle(document.body).zoom)!=null?u:"1"),[i,a]=yP((f,d)=>{let p=t.current;if(!p)return;let v=f/s,g=d/s,x=p.getBoundingClientRect(),y=v>x.x&&v<x.x+x.width&&g>x.y&&g<x.y+x.height;y&&!o?(o=!0,r(!0)):!y&&o&&(o=!1,r(!1))},({clientX:f,clientY:d})=>[f,d]),[l,c]=yP(()=>{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 vP(e){return e.replace(/[.*+^${}()|[\]\\]/g,"\\$&")}function Qp(e){return t=>{e.forEach(n=>{typeof n=="function"?n(t):n!=null&&(n.current=t)})}}function xP(e){return e!=null}var wP=b(Ne()),Zp=b(Y());var vo={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 x0=b(R()),Jp=(0,Zp.forwardRef)((o,r)=>{var s=o,{className:e,children:t}=s,n=oe(s,["className","children"]);let i=(0,Zp.useRef)(null),a=_("TabCompletion",vo);return(0,x0.jsx)("div",P(S({ref:Qp([i,r]),className:(0,wP.default)(e,a.popoverContentContainer)},n),{children:(0,x0.jsx)("div",{className:a.popoverContent,children:t})}))});var us=b(R()),nF=e=>t=>{let n=l0(t);return"top"in n&&(n.width=e.width-(t.left-e.left)-10),n},rF=({inputElement:e,boundaryRef:t,inputStyle:n,children:r,suggestion:o})=>{let s=_("TabCompletion",vo),i=Dp(),a=(0,tm.useMemo)(()=>nF(e.getBoundingClientRect()),[e]),[l,c]=Xp(e);return(0,tm.useEffect)(()=>{c?i.open():i.close()},[c]),(0,us.jsxs)("span",{children:[(0,us.jsx)("mark",{ref:Qp([l,i.triggerRef]),className:(0,SP.default)(s.matchKeyword,{[s.hover]:c}),"aria-haspopup":"dialog","aria-expanded":i.opened?"true":"false",children:r}),i.opened&&(0,us.jsx)(_a,{className:s.popover,triggerRef:i.triggerRef,boundaryRef:t,position:"below",align:"start",toStyle:a,children:(0,us.jsx)(Jp,{style:n,children:(0,us.jsx)("div",{className:s.hintText,children:o})})})]})},em=class extends ao{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=>P(S({},o),{keywordRegex:new RegExp(`\\b${vP(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(xP);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,us.jsx)(rF,{inputElement:r.inputElement,suggestion:r.suggestion,inputStyle:r.inputStyle,boundaryRef:r.boundaryRef,children:n},`keyword_${r.matchString}_${r.key}`)}asTag(){return"mark"}};var bP=b(Ne());var w0=b(R()),oF=({inputElement:e,children:t})=>{let n=_("TabCompletion",vo),[r,o]=Xp(e);return(0,w0.jsx)("mark",{ref:r,className:(0,bP.default)(n.matchPlaceholder,{[n.hover]:o}),children:t})},nm=class extends ao{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,w0.jsx)(oF,{inputElement:n.inputElement,children:t},`placeholder_${n.matchString}_${n.key}`)}asTag(){return"mark"}};var om=b(Ne());var Jt=b(Y());var S0=b(R()),EP=()=>(0,S0.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,S0.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 Dr=b(Y());var CP=b(Yy());var TP={root:"dd-ky-Bv",content:"dd-kV5e1"};function rm(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 b0(e){return e.replace("https://www.","").replace("https://","")}var Vn=b(R()),sF=3,iF=e=>({image:e.image||"",text:e.text,id:e.id,title:e.title}),aF=({onSelectLink:e,onDismiss:t,placeholder:n,visitUrlText:r,linkCount:o=sF})=>{let s=_("LinkSearch",TP),[i,a]=(0,Dr.useState)(""),l=ve(),c=j(AR("url")),u=j(aT("URL")),f=(0,Dr.useMemo)(()=>u.map(iF),[u]),[d,p]=(0,Dr.useState)(f.length-1),v=te("fallbackImage"),g=m=>{let w=m.target;a(w.value)},x=(m,w)=>{m.stopPropagation(),m.preventDefault(),window.open(w,"_blank")},y=m=>{var k;let w=d-1<0?f.length-1:d-1,E=d+1===f.length?0:d+1;m.code==="Escape"&&(a(""),t()),m.code==="ArrowUp"&&p(w),m.code==="ArrowDown"&&p(E),m.code==="Enter"&&e(((k=f[d])==null?void 0:k.text)||i)},h=(0,Dr.useCallback)((0,CP.default)(m=>{l(Us({query:m,type:"URL",tags:["link-search"]}))},300),[]);return(0,Dr.useEffect)(()=>{i&&h(i)},[i]),(0,Dr.useEffect)(()=>()=>{l(Af())},[]),(0,Vn.jsxs)("div",{className:s.root,children:[(0,Vn.jsx)(Ht,{withDivider:!0,children:(i?f:c).slice(0,o).map((m,w)=>(0,Vn.jsx)(ge,{selected:d===w,onClick:()=>e(m.text),"data-testid":"linksearch-suggestion",children:(0,Vn.jsxs)(Se,{children:[(0,Vn.jsx)(Se.Image,{src:rm(m,"small",v||void 0),title:m.title||m.text}),(0,Vn.jsxs)(Se.Content,{className:s.content,cropText:!0,children:[(0,Vn.jsx)(Se.Title,{children:m.title||b0(m.text)}),m.title&&b0(m.text)]}),(0,Vn.jsx)(ge.Actions,{children:(0,Vn.jsx)(ge.ActionButton,{label:r,onClick:E=>x(E,m.text)})})]})},m.text))}),(0,Vn.jsx)(pc,{value:i,onChange:g,autoFocus:!0,placeholder:n,onKeyUp:y})]})},kP=aF;var E0={};pt(E0,{enUS:()=>lF,nlNL:()=>cF});var lF={insertLink:[{type:0,value:"Insert link"}],linkInputPlaceholder:[{type:0,value:"Search, type or paste link"}],visitUrl:[{type:0,value:"Visit"}]},cF={insertLink:[{type:0,value:"Voeg link toe"}],linkInputPlaceholder:[{type:0,value:"Zoek, typ of plak link"}],visitUrl:[{type:0,value:"Bekijk"}]};var Zt=b(R()),uF=(0,Jt.forwardRef)((e,t)=>{let n=_("TabCompletion",vo);return(0,Zt.jsx)("mark",{ref:t,className:(0,om.default)(n.matchSelection)},"selection-start")}),dF=({startRef:e,boundaryRef:t,inputStyle:n,inputElement:r,children:o})=>{let s=ie(E0),i=_("TabCompletion",vo),a=(0,Jt.useRef)(null),l=(0,Jt.useRef)(null),[c,u]=(0,Jt.useState)(null),f=ve(),d=Dp(document.activeElement===r),[p]=(0,Jt.useState)(()=>document.createRange());d.triggerRef.current=p,(0,Jt.useEffect)(()=>()=>p.detach(),[]),(0,Jt.useEffect)(()=>{let g=e.current,x=a.current;!g||!x||(p.setStart(g,0),p.setEnd(x,0))},[e.current,a.current]),ss(()=>{d.close()});let v=(0,Jt.useCallback)(g=>{let x=p.toString(),y=/^http(s?):\/\//.test(g)?g:`https://${g}`;f(bf({text:`[${x}](${y})`,replace:"selection"}))},[]);return(0,Zt.jsxs)("span",{children:[(0,Zt.jsx)("mark",{ref:a,className:(0,om.default)(i.matchSelection),"aria-haspopup":"dialog","aria-expanded":d.opened?"true":"false",children:o}),d.opened&&(0,Zt.jsx)(_a,{className:i.popoverRoot,triggerRef:d.triggerRef,boundaryRef:t,position:"above",align:"start",children:(0,Zt.jsxs)(Jp,{style:n,ref:l,children:[(0,Zt.jsx)("div",{className:(0,om.default)(i.selectionOptions,{[i.selectionOptionsIsHidden]:c!==null}),children:(0,Zt.jsxs)("button",{type:"button",tabIndex:c===null?-1:void 0,className:i.selectionOptionsButton,onClick:()=>u("insertLink"),children:[(0,Zt.jsx)(EP,{}),(0,Zt.jsx)("span",{children:"\xA0"}),(0,Zt.jsx)("span",{children:s("insertLink")})]})}),c==="insertLink"&&(0,Zt.jsx)(kP,{placeholder:s("linkInputPlaceholder"),visitUrlText:s("visitUrl"),onSelectLink:v,onDismiss:()=>{u(null),d.close()}})]})})]},"selection-end")},sm=class extends ao{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,Jt.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?S({isStart:a},i):null}replaceWith(n,r){return r.isStart?(0,Zt.jsx)(uF,{ref:this.startRef}):(0,Zt.jsx)(dF,{inputElement:r.inputElement,startRef:this.startRef,boundaryRef:r.boundaryRef,inputStyle:r.inputStyle})}asTag(){return"mark"}};var xo=b(R()),fF=({enabled:e,content:t,tabText:n,showTabHint:r,showTabCompletion:o,showStyleSuggestions:s,keywordMatches:i,inputElement:a,source:l})=>{let c=_("TabCompletion",hP),u=te("insertLink"),f=te("showMidSentenceSuggestions"),d=te("inlineSuggestions"),p=pP(a),v=(0,wo.useRef)(null),g=j(jt);(0,wo.useEffect)(()=>{gi(a)&&p&&mP(a,p)},[p]);let x=(0,wo.useCallback)(m=>{if(!o||!n)return m;let w=[(0,xo.jsx)("span",{className:c.resetIndent,children:"\u200B"},"u200B"),(0,xo.jsx)("span",{"data-testid":"tab-completion",className:(0,im.default)(c.tabText,c.resetIndent),"data-source":l,children:n},"tabText")];return r&&w.push((0,xo.jsx)("span",{className:(0,im.default)(c.hint,c.resetIndent),children:(0,xo.jsx)(Mu,{keyCode:"tab"},"tabHint")},"tabHint")),v0(m,w)},[o,n,r]),y=(0,wo.useMemo)(()=>{let m=[];return u&&m.push(new sm("selection")),m.push(new nm("placeholders")),s&&m.push(new em("keywords")),m},[d,u,s]),h=(0,wo.useMemo)(()=>{let m=window.getComputedStyle(a);return{"--dd-color":m.color,"--dd-font-size":m.fontSize,"--dd-font-family":m.fontFamily,"--dd-font-variant":m.fontVariant}},[]);return!e||!g?null:(0,xo.jsxs)("div",{ref:m=>{m!=null&&m.parentElement&&(v.current=m==null?void 0:m.parentElement)},className:c.root,style:h,children:[(0,xo.jsx)(Js,{tagName:"span",containerTagName:"div",className:(0,im.default)(c.container,c.agentText),disableLineBreaks:gi(a),content:t||"\u200B",onAfterParse:x,matchers:y,selection:p,keywordMatches:i,inputElement:a,inputStyle:h,boundaryRef:v,inlineSuggestionsOnlyAtEnd:!f}),(0,xo.jsx)("br",{})]},"tab-completion")},pF=e=>{var x,y,h;let{input:t,ui:n,settings:r,styleSuggestions:o,conversation:s}=e,i=ua({input:t}),a=(i==null?void 0:i.text)||"",l=(i==null?void 0:i.source)||"",c=(x=t.html)!=null?x:ha(t.text),u=a.indexOf(t.text)===0?a.slice(t.text.length):"",{showTabHint:f}=n,{isSupported:d}=s,{showTabCompletion:p,visible:v,showStyleSuggestions:g}=r;return{showTabHint:f,showStyleSuggestions:g,showTabCompletion:p&&Nr(e),content:c,tabText:u,source:l,keywordMatches:(h=(y=o.list)==null?void 0:y.keywordMatches)!=null?h:[],enabled:v&&d!==!1}},RP=p1(pF)(fF);var ds=b(Y());var mF={token:null,interval:null},T0=he("passwordlessToken/getTemporaryPasswordlessToken",(e,t)=>I(void 0,null,function*(){let{deepdeskAPI:n}=t.extra;return{token:yield n.requestPasswordlessToken()}})),C0=he("passwordlessToken/pollPasswordlessToken",(e={},t)=>{let{interval:n=1e3*60*10}=e,{dispatch:r}=t;return r(T0()),setInterval(()=>r(T0()),n)}),PP=ke({name:"passwordlessToken",initialState:mF,reducers:{stopPollPasswordlessToken(e){e.interval&&clearInterval(e.interval),e.interval=null}},extraReducers:e=>{e.addCase(T0.fulfilled,(t,n)=>{t.token=n.payload.token}),e.addCase(C0.fulfilled,(t,n)=>{t.interval=n.payload})}}),{stopPollPasswordlessToken:AP}=PP.actions,IP=PP.reducer;function gF(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return t}var LP=$t([YT],e=>e.map(n=>({text:n.response,title:n.name,callToAction:n.callToAction,isLoading:n.isLoading,specialType:n.specialType,rule:{id:gF(n.code),label:n.code,name:n.name,description:n.name}})));var am=b(Y());var R0=b(Ne());var k0=b(R()),su=()=>(0,k0.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 512 512",xmlns:"http://www.w3.org/2000/svg",children:(0,k0.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 MP={root:"dd-WcEru",entity:"dd-LfP8y",entityText:"dd-L-v0f",iconWrapper:"dd-9Deh1",icon:"dd-tM7E2",iconClicked:"dd-EEdDL"};var Fr=b(R()),hF=({entities:e})=>{let t=_("EntitiesWidgetList",MP),[n,r]=(0,am.useState)(void 0),o=ve(),s=()=>{r(void 0)},i=a=>{e&&(r(e.indexOf(a)),Ir(a.text),o(ro({name:"entity copied",data:{entity:a,type:"copy"}})))};return(0,am.useEffect)(()=>{let a=setTimeout(s,500);return()=>{clearTimeout(a)}},[n]),!e||e.length===0?null:(0,Fr.jsx)("div",{className:t.root,"data-testid":"widget-entities-list",children:e.map((a,l)=>(0,Fr.jsxs)("button",{title:a.text,className:t.entity,type:"button",onClick:()=>i(a),children:[(0,Fr.jsx)("span",{className:t.entityText,children:a.text}),(0,Fr.jsxs)("span",{className:t.iconWrapper,children:[(0,Fr.jsx)("span",{className:(0,R0.default)(t.icon),children:(0,Fr.jsx)(su,{})}),(0,Fr.jsx)("span",{className:(0,R0.default)(t.icon,n===l&&t.iconClicked),children:(0,Fr.jsx)(su,{})})]})]},a.text))})},OP=hF;var P0=b(R()),NP=()=>(0,P0.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:(0,P0.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 UP=b(Y());var _P={root:"dd-ohnXe",trigger:"dd-7i-S3",button:"dd-t53Cg",nav:"dd-qZFnm",item:"dd-FZC0F"};var DP={root:"dd-nazq3",rotation:"dd-3EHTv"};var zP=b(R()),yF=({size:e=12})=>{let t=_("LoadingSpinner",DP);return(0,zP.jsx)("span",{"data-testid":"loading-spinner",style:{width:`${e}px`,height:`${e}px`},className:t.root})},FP=yF;var A0=b(R()),HP=()=>(0,A0.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 0 512 512",fill:"currentColor",children:(0,A0.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 iu=b(R()),BP=e=>(0,iu.jsxs)("svg",P(S({xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 448 512","aria-labelledby":"checkTitle"},e),{children:[(0,iu.jsx)("title",{id:"checkTitle",children:"Check"}),(0,iu.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 I0={};pt(I0,{enUS:()=>vF,nlNL:()=>xF});var vF={error:[{type:0,value:"Something went wrong"}]},xF={error:[{type:0,value:"Er ging iets fout"}]};var Pn=b(R()),wF=3e3,SF=({assistantOptions:e})=>{let t=_("OnDemandAssistants",_P),n=ie(I0),r=(0,UP.useRef)(),o=ai(or),s=ai(so),i=j(eC),a=j(tC),l=ut(),c=a.filter(d=>d.isPinned),u=a.filter(d=>!d.isPinned),f=d=>I(void 0,null,function*(){clearTimeout(r.current),l("trigger on demand assistant",{assistantCode:d}),d===i?yield s.call({transcript:e.transcript}):yield o.call(P(S({},e),{assistantCode:d})),r.current=setTimeout(()=>o.reset(),wF)});return a.length===0?null:(0,Pn.jsxs)("div",{className:t.root,children:[c.map(({assistant:d,assistantName:p})=>(0,Pn.jsx)("button",{type:"button",className:t.button,disabled:o.state==="loading",onClick:()=>f(d),children:p},d)),u.length>0&&(0,Pn.jsxs)(vt,{placement:"top-end",children:[(0,Pn.jsx)(vt.Trigger,{className:t.trigger,disabled:o.state==="loading",children:(0,Pn.jsx)(Fp,{"data-testid":"trigger"})}),(0,Pn.jsx)(vt.Content,{className:t.nav,"data-testid":"popover",children:u.map(({assistant:d,assistantName:p})=>(0,Pn.jsx)(vt.Button,{className:t.item,disabled:o.state==="loading",onClick:()=>f(d),children:p},d))})]}),o.state==="loading"&&(0,Pn.jsx)(FP,{}),o.state==="done"&&(0,Pn.jsx)(BP,{"data-testid":"trigger-done"}),o.state==="error"&&(0,Pn.jsx)(zk,{trigger:(0,Pn.jsx)(HP,{}),children:n("error")})]})},VP=SF;var WP=b(Y());var $P={loadingBar:"dd-6as-V",placeHolderShimmer:"dd-TFYmA"};var jP=b(R()),bF=({width:e})=>{let t=_("LoadingProgressBar",$P);return(0,jP.jsx)("div",{className:t.loadingBar,style:{width:e}})},lm=bF;var So=b(R()),cm=({title:e})=>{let t=(0,WP.useRef)(null);return Ou(t),(0,So.jsx)(ge,{ref:t,children:(0,So.jsx)(Se,{children:(0,So.jsxs)(Se.Content,{children:[(0,So.jsx)(Se.Title,{children:e}),(0,So.jsx)(lm,{width:"60%"}),(0,So.jsx)(lm,{width:"90%"}),(0,So.jsx)(lm,{width:"50%"})]})})})};var au={};pt(au,{enUS:()=>EF,nlNL:()=>TF});var EF={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"}]},TF={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 hi=b(Y());var L0={title:"dd-YBHrC",fadeup:"dd-cRM0K",fadedown:"dd-7D4Pq",selected:"dd-bueui",actions:"dd-9Iqn9",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 Nt=b(R()),CF=500,kF=100,RF=({content:e,onChange:t,onCopy:n})=>{let r=(0,hi.useRef)(null),o=_("WidgetCue",L0);return(0,hi.useEffect)(()=>{let s=r.current;if(!s)return;s.style.setProperty("height","0px");let i=Math.min(Math.max(s.scrollHeight,kF),CF);s.style.setProperty("height",`${i}px`)},[e]),(0,Nt.jsx)("textarea",{ref:r,className:o.editableCue,onCopy:n,onChange:t,value:e})},PF=({cue:e,onCallToAction:t,onRemove:n,onCopy:r,onUse:o})=>{var g;let s=_("WidgetCue",L0),i=ie(au),a=ut(),l=te("hasKeyboardInput"),[c,u]=(0,hi.useState)(e.text),f=()=>{t&&t(e),n(e)},d=x=>{r&&r(x,e)},p=x=>{o&&o(x,e)},v=x=>{x.preventDefault(),x.stopPropagation(),n(e)};return(0,hi.useEffect)(()=>{a("Assistant response displayed",{name:e.rule.name,description:e.rule.description,group:e.rule.label,cueText:e.text})},[]),(0,Nt.jsxs)(ge,{"data-testid":"cue",children:[(0,Nt.jsx)(Se,{children:(0,Nt.jsxs)(Se.Content,{children:[e.title&&(0,Nt.jsx)(Se.Title,{className:s.title,"data-testid":"widget-cue-title",children:e.rule.label.startsWith("__")?i(e.rule.label):e.title}),e.specialType==="summary"?(0,Nt.jsx)(RF,{content:c,onCopy:()=>{let x=document.getSelection();x&&d(x.toString())},onChange:x=>{var y;return u((y=x.target.value)!=null?y:"")}}):(0,Nt.jsx)(ho,{content:e.text,useLabel:i("useCue"),copyLabel:i("copyCue"),onCopy:d,onUse:l?p:void 0})]})}),(0,Nt.jsxs)(ge.ButtonsContainer,{children:[(0,Nt.jsxs)("div",{className:s.actions,children:[e.specialType==="summary"&&(0,Nt.jsx)(ge.Button,{onClick:()=>d(c),children:i("copyCue")}),e.callToAction&&(0,Nt.jsx)(ge.Button,{onClick:f,children:e.callToAction.label}),(0,Nt.jsx)(ge.Button,{onClick:v,children:i("removeCue")})]}),e.specialType==="summary"?(0,Nt.jsx)(li,{eventName:"summary feedback",feedbackText:(g=e.text)!=null?g:"",feedbackType:"summary",eventData:{summary:e.text}}):(0,Nt.jsx)(li,{eventName:"Assistant response feedback",eventData:{name:e.rule.name,group:e.rule.label,description:e.rule.description,cueText:e.text},feedbackText:e.text,feedbackType:"assistant"})]})]})},KP=PF;var Ha=b(R()),AF=({cues:e})=>{let t=ve(),n=dn(),r=ie(au),o=ut(),s=c=>{t(Gf({code:c.rule.label})),o("Assistant response closed",{name:c.rule.name,group:c.rule.label,description:c.rule.description,cueText:c.text})},i=(c,u)=>{switch(Ir(c),u.specialType){case"summary":o("summary copied to clipboard",{originalText:u.text,finalText:c,assistant:u.rule.label});break;default:o("Assistant response copied",{name:u.rule.name,group:u.rule.label,description:u.rule.description,copiedText:c})}},a=c=>{c.callToAction&&(t(Kf(c)),o("Assistant call to action",{name:c.rule.name,group:c.rule.label,description:c.rule.description,eventName:c.callToAction.event,value:c.callToAction.value}))},l=(c,u)=>{var f;n.send(Pr,{text:c,suggestion:{source:"assistant",assistantCode:(f=u.rule)==null?void 0:f.label,sourceText:c}}),o("Assistant response used",{name:u.rule.name,group:u.rule.label,description:u.rule.description,usedText:c})};return(0,Ha.jsx)(Ha.Fragment,{children:e.map(c=>c.isLoading?(0,Ha.jsx)(cm,{title:c.rule.label.startsWith("__")?r(c.rule.label):c.title},c.rule.id):(0,Ha.jsx)(KP,{cue:c,onCallToAction:a,onRemove:s,onCopy:i,onUse:l},c.rule.id))})},GP=AF;var um=b(Y());var qP={root:"dd-cvTAY",label:"dd-QWQxD",value:"dd-WSUHF",copyButton:"dd-67o9H",copyButtonText:"dd-oos-l",isTrue:"dd--1g2O",isFalse:"dd-sz2ir"};var hr=b(R());function IF(e,t){return t.split(".").reduce((n,r)=>!n||typeof n!="object"||!(r in n)?null:n[r],e)}var YP=({data:e,schema:t})=>{let n=_("WidgetCustomData",qP),r=o=>{Ir(o)};return(0,um.useEffect)(()=>{Z.info("Custom data",e,t)},[e]),(0,hr.jsx)("dl",{className:n.root,children:t.map(o=>{let s=IF(e,o.path);return(0,hr.jsxs)(um.Fragment,{children:[(0,hr.jsx)("dt",{className:n.label,children:o.label}),(0,hr.jsx)("dd",{className:n.value,children:o.type==="boolean"&&s?(0,hr.jsx)("span",{className:n.isTrue,children:o.trueValue}):o.type==="boolean"&&!s?(0,hr.jsx)("span",{className:n.isFalse,children:o.falseValue}):typeof s=="string"||typeof s=="number"?(0,hr.jsxs)("button",{type:"button",onClick:()=>r(`${s}`),className:n.copyButton,children:[(0,hr.jsx)("span",{className:n.copyButtonText,children:s}),(0,hr.jsx)(su,{})]}):"-"})]},o.label)})})};var rt=b(Y());var Ba={};pt(Ba,{enUS:()=>LF,nlNL:()=>MF});var LF={inputPlaceholder:[{type:0,value:"What is your question?"}],useCue:[{type:0,value:"Add to message"}],copyCue:[{type:0,value:"Copy"}],removeCue:[{type:0,value:"Close"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}],submitLabel:[{type:0,value:"Submit"}],resetLabel:[{type:0,value:"Reset"}],showMore:[{type:0,value:"Show "},{type:1,value:"amount"},{type:0,value:" more"}]},MF={inputPlaceholder:[{type:0,value:"Wat is je vraag?"}],useCue:[{type:0,value:"Voeg toe aan bericht"}],copyCue:[{type:0,value:"Kopi\xEBren"}],removeCue:[{type:0,value:"Sluiten"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}],submitLabel:[{type:0,value:"Verzend"}],resetLabel:[{type:0,value:"Gesprek wissen"}],showMore:[{type:0,value:"Toon "},{type:1,value:"amount"},{type:0,value:" meer"}]};var dm={form:"dd-pleCH",formInput:"dd-pGJMY",formSubmit:"dd--gkRg",actionButton:"dd-I2NEH",resetContainer:"dd-qKIDX",sources:"dd-xf9c6",source:"dd-a-vyX",tooltip:"dd-EsgcZ",linkContent:"dd-gARDA",showMoreSources:"dd-uDGi-"};var QP=b(Y());var XP={error:"dd-CoAuB"};var M0={};pt(M0,{enUS:()=>OF,nlNL:()=>NF});var OF={errorPrefix:[{type:0,value:"Error:"}]},NF={errorPrefix:[{type:0,value:"Foutmelding:"}]};var lu=b(R()),ZP=({message:e})=>{let t=(0,QP.useRef)(null),n=_("WidgetCardError",XP),r=ie(M0);return Ou(t),(0,lu.jsx)(ge,{ref:t,children:(0,lu.jsx)(Se,{children:(0,lu.jsxs)(Se.Content,{className:n.error,children:[r("errorPrefix")," ",e]})})})};var we=b(R()),_F=3,DF=({sources:e,onClick:t})=>{let n=ie(Ba),r=_("WidgetKnowledgeAssistant",dm),[o,s]=(0,rt.useState)(!1),i=o?e:e.slice(0,_F);return i.length===0?null:(0,we.jsxs)("ul",{className:r.sources,children:[i.map(a=>(0,we.jsx)("li",{className:r.source,"data-testid":"knowledge-assist-source",children:(0,we.jsxs)(vt,{tooltip:!0,placement:"top-start",children:[(0,we.jsx)(vt.Trigger,{as:"a",rel:"noreferrer",target:"_blank",href:a.url,onClick:l=>{l.stopPropagation(),t(a)},children:(0,we.jsx)("span",{className:r.linkContent,children:a.name})}),a.url&&(0,we.jsx)(vt.Content,{className:r.tooltip,children:decodeURIComponent(a.url)})]})},a.name)),i<e&&(0,we.jsx)("button",{type:"button",className:r.showMoreSources,onClick:()=>s(!0),children:n("showMore",{amount:e.length-i.length})})]})},FF=({title:e,description:t})=>(0,we.jsx)(ge,{"data-testid":"knowledge-assist-empty-state",children:(0,we.jsx)(Se,{children:(0,we.jsxs)(Se.Content,{children:[(0,we.jsx)(Se.Title,{children:e}),(0,we.jsx)(ho,{content:t})]})})}),zF=({innerRef:e,item:t,index:n,hasKeyboardInput:r,onCopy:o,onUse:s,onSourceClick:i})=>{var l;let a=ie(Ba);return(0,we.jsxs)(ge,{"data-testid":"knowledge-assist-answer",ref:e,children:[(0,we.jsx)(Se,{children:(0,we.jsxs)(Se.Content,{children:[(0,we.jsx)(Se.Title,{children:t.question}),(0,we.jsx)(ho,{content:t.answer.answer,useLabel:a("useCue"),copyLabel:a("copyCue"),onCopy:o,onUse:r?s:void 0}),(0,we.jsx)(DF,{sources:(l=t.answer.sources)!=null?l:[],onClick:c=>i(c,t.question)})]})}),(0,we.jsxs)(ge.ButtonsContainer,{children:[(0,we.jsx)("div",{}),(0,we.jsx)(li,{eventName:"knowledge assist feedback",eventData:{question:t.question,isFollowUpQuestion:n>0,isAgent:!0,answer:t.answer.answer},feedbackText:t.answer.answer,feedbackType:"assistant"})]})]})},O0=(0,rt.createContext)(null),fm=({assistantCode:e,evaluateKnowledgeAssistFn:t,initialQuestion:n,children:r})=>{let[o,s]=(0,rt.useState)(null),[i,a]=(0,rt.useState)(!1),[l,c]=(0,rt.useState)(null),[u,f]=(0,rt.useState)(!!n),[d,p]=(0,rt.useState)(null),v=ve(),g=ut(),x=ai(m=>{if(!e)throw new Error("No knowledge assistant was defined");return c(null),t({assistantCode:e,input:m,threadId:o,onNewThreadId(w){s(w)}})},{onSuccess(m){var w;g("knowledge assist question answered",{question:m.question,answer:m.answer.answer,sources:(w=m.answer.sources)!=null?w:[],isFollowUpQuestion:m.threadId===o,isAutoInitiated:u}),f(!1)},onError(m){var w;c((w=m.message)!=null?w:"Unknown error")}}),y=m=>I(void 0,null,function*(){a(!0),p(m),yield x.call(m),a(!1),p(null)}),h={isEnabled:!!e,isSubmitting:i,threadId:o,pendingInput:d,errorMessage:l,onSubmit:y,onReset(){o&&v(ga(o)),c(null),s(null)}};return(0,rt.useEffect)(()=>{n&&y(n)},[n]),(0,we.jsx)(O0.Provider,{value:h,children:r})},pm=()=>{let e=ie(Ba),t=_("WidgetKnowledgeAssistant",dm),n=(0,rt.useContext)(O0),r=(0,rt.useRef)(null),[o,s]=(0,rt.useState)(""),i=l=>{s(l.target.value)},a=l=>{l.preventDefault(),n.onSubmit(o).then(()=>{var c;r.current&&((c=r.current)==null||c.focus(),s(""))})};return n.isEnabled?(0,we.jsxs)("form",{className:t.form,onSubmit:a,children:[(0,we.jsx)("input",{ref:r,className:t.formInput,placeholder:e("inputPlaceholder"),type:"text",disabled:n.isSubmitting,value:o,onChange:i}),(0,we.jsx)("button",{type:"submit",disabled:n.isSubmitting||o==="",className:t.formSubmit,children:e("submitLabel")})]}):null},mm=({title:e,emptyState:t})=>{var v,g;let n=ie(Ba),r=ut(),o=_("WidgetKnowledgeAssistant",dm),s=(0,rt.useRef)(null),i=(0,rt.useContext)(O0),a=(g=j(Sc((v=i.threadId)!=null?v:-1)))!=null?g:[],l=te("hasKeyboardInput"),c=dn(),u=x=>{Ir(x),r("Assistant response copied",{name:"Knowledge Assistant",group:"knowlegde-assist",description:"",copiedText:x})},f=(x,y)=>{r("knowledge assist source viewed",{question:y,sourceViewed:x.url||x.name})},d=x=>{var y;x.preventDefault(),i.onReset(),r("knowledge assist reset",{threadId:(y=i.threadId)!=null?y:void 0})},p=x=>{c.send(Pr,{text:x,suggestion:{source:"assistant",sourceText:x}}),r("Assistant response used",{name:"Knowledge Assistant",group:"knowlegde-assist",description:"",usedText:x})};return!i.isEnabled||(a==null?void 0:a.length)===0&&!i.isSubmitting&&!t&&!i.errorMessage?null:(0,we.jsxs)(rt.Fragment,{children:[(0,we.jsx)(wr,{type:"knowledge",title:e,"data-testid":"knowledge",children:(0,we.jsxs)(Ht,{withDivider:!0,children:[t&&a.length===0&&!i.pendingInput&&(0,we.jsx)(FF,S({},t)),a.map((x,y)=>(0,we.jsx)(zF,{innerRef:y===a.length-1?s:void 0,item:x,index:y,hasKeyboardInput:l,onCopy:u,onUse:p,onSourceClick:f},`${x.question}_${x.answer}_${y}`)),i.pendingInput&&(0,we.jsx)(cm,{title:i.pendingInput}),i.errorMessage&&(0,we.jsx)(ZP,{message:i.errorMessage})]})}),a.length>0&&(0,we.jsx)("div",{className:o.resetContainer,children:(0,we.jsx)(ge.Button,{disabled:i.threadId===null||i.isSubmitting,onClick:d,children:n("resetLabel")})})]})};var tA=b(Y());var HF=/(https?:\/\/[^\s]+)/,eA=e=>e.split(" ").find(t=>HF.test(t));var $n=b(R()),BF=({suggestion:e,lines:t,onUse:n})=>{var f;let r=e.text||e.url||e.message,o=eA(r),s=ie(Xc),i=te("showImages"),a=te("fallbackImage"),l=te("hasKeyboardInput"),c=d=>{d.preventDefault(),d.stopPropagation(),l&&n(r)},u=(0,tA.useCallback)(d=>{window.open(o,"_blank"),d.stopPropagation(),d.preventDefault()},[o]);return(0,$n.jsxs)(ge,{onClick:l?c:void 0,"data-testid":"edit-suggestion",children:[(0,$n.jsxs)(Se,{children:[i&&e.image&&(0,$n.jsx)(Se.Image,{src:rm(e,"small",a||void 0),title:e.title}),(0,$n.jsxs)(Se.Content,{children:[e.title&&(0,$n.jsx)(Se.Title,{"data-testid":"widget-suggestion-title",children:e.title}),e.searchKeywords&&((f=e.searchKeywords)==null?void 0:f.length)>0&&(0,$n.jsx)(ge.Labels,{labels:e.searchKeywords}),(0,$n.jsx)(Se.Content,{cropText:t==="single",lineClamp:t==="multiple",children:r})]})]}),(0,$n.jsxs)(ge.Actions,{children:[o&&(0,$n.jsx)(ge.ActionButton,{onClick:u,label:s("visitUrl")}),l&&(0,$n.jsx)(ge.ActionButton,{primary:!0,onClick:c,label:s("useSuggestion")})]})]})},nA=BF;var cu=b(R()),UF=({lines:e,suggestions:t})=>{let n=dn(),r=(o,s)=>{n.send(Pr,{text:o,suggestion:P(S({},s),{source:s.source,sourceText:s.text})})};return(0,cu.jsx)(cu.Fragment,{children:t.map(o=>(0,cu.jsx)(nA,{suggestion:o,lines:e,onUse:s=>r(s,o)},o.text||o.url||o.message))})},rA=UF;var uu={};pt(uu,{enUS:()=>VF,nlNL:()=>$F});var VF={waiting:[{type:0,value:"Loading\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"}]},$F={waiting:[{type:0,value:"Laden\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 Ua={root:"dd-W9VCG",loginText:"dd--dS6t",stateText:"dd-348OC",footer:"dd-tvofr",shortcutList:"dd-MuKK-",shortcut:"dd-5CnK9",footerShortcut:"dd-dH7XJ",link:"dd-DRo0x"};var ue=b(R()),sA=(e,t)=>{let n=j(jt);(0,ds.useEffect)(()=>n?t.every(r=>!!r)?e():()=>{}:()=>{},[...t,n])},jF=({onLogIn:e})=>{let t=_("Widget",Ua),n=te("isEmbedded"),r=te("adminUrl");return(0,ue.jsx)("div",{className:t.loginText,children:(0,ue.jsx)("div",{children:(0,ue.jsx)(Gp,{isEmbedded:n,loginUrl:r,onLogIn:e})})},"login")},oA=({text:e})=>{let t=_("Widget",Ua);return(0,ue.jsx)("div",{className:t.stateText,children:(0,ue.jsx)("div",{children:(0,ue.jsx)("p",{children:e})})},"notification")},WF=()=>{let e=ie(uu),t=ve(),n=_("Widget",Ua),r=te("showSearch"),o=te("isEmbedded"),s=j(Oa("/admin/")),i=dn(),a=te("productName"),l=ut();return sA(()=>{if(o)return t(C0()),()=>{t(AP())}},[t,o]),!r&&!s?null:(0,ue.jsxs)("div",{className:n.shortcutList,children:[r&&(0,ue.jsx)(ge.Button,{"data-testid":"shortcut-search","aria-label":e("linkSearch"),className:n.shortcut,icon:(0,ue.jsx)(Aa,{}),onClick:()=>{i.send("ShowCommandPalette",{isOpen:!0}),l("open search",{via:"widget-shortcut"})},children:e("linkSearch")}),s&&(0,ue.jsx)(ge.Button,{as:"a",target:"_blank",icon:(0,ue.jsx)(NP,{}),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})})]})},KF=({title:e,content:t})=>{let n=ie(uu),[r,o]=(0,ds.useState)(!0);return r?(0,ue.jsx)(wr,{"data-testid":"custom-data-banner",type:"custom-data-banner",title:e,children:(0,ue.jsx)(Ht,{withDivider:!0,children:(0,ue.jsxs)(ge,{children:[(0,ue.jsx)(Se,{children:(0,ue.jsx)(Se.Content,{children:(0,ue.jsx)(ho,{content:t})})}),(0,ue.jsx)(ge.ButtonsContainer,{children:(0,ue.jsx)(ge.Button,{onClick:()=>o(!1),children:n("close")})})]})})}):null},GF=()=>{let e=ve(),t=j(Tc),n=j(rC),r=j(LP),o=j(Z1),s=j(Ap),i=j(Bp),a=j(qs),l=j(Rr);return(0,ds.useEffect)(()=>{!!o&&!n&&Z.warn("Custom data provided, but no schema.")},[o,n]),sA(()=>{t.forEach(({type:c})=>{c==="entities"?e(fr()):Du.includes(c)||e(gr(c))})},[e,l,a]),(0,ds.useEffect)(()=>{r.length>0&&!t.some(c=>c.type==="cues")&&Z.warn("Received cues, but cues are not configured in widget.")},[t,r]),(0,ue.jsx)(ds.Fragment,{children:t.map(({type:c,title:u,amount:f,lines:d,schema:p,property:v})=>{var g,x;switch(c){case"entities":return s&&s.length>0&&(0,ue.jsx)(wr,{type:c,title:u,"data-testid":`type-${c}`,children:(0,ue.jsx)(OP,{entities:s})},c);case"cues":return r&&r.length>0&&(0,ue.jsx)(wr,{type:c,title:u,"data-testid":`type-${c}`,children:(0,ue.jsx)(Ht,{withDivider:!0,children:(0,ue.jsx)(GP,{cues:r})})},c);case"custom-data-banner":return o&&v&&o[v]&&(0,ue.jsx)(KF,{title:u,content:String(o[v])},c);case"custom-data":return o&&p&&(0,ue.jsx)(wr,{type:c,title:u,"data-testid":`type-${c}`,children:(0,ue.jsx)(Ht,{withDivider:!0,children:(0,ue.jsx)(YP,{data:o,schema:p})})},c);default:return((x=(g=i[c])==null?void 0:g.suggestions)==null?void 0:x.length)>0&&(0,ue.jsx)(wr,{type:c,title:u,"data-testid":`type-${c}`,children:(0,ue.jsx)(Ht,{withDivider:!0,children:(0,ue.jsx)(rA,{lines:d,contentType:c,suggestions:i[c].suggestions.slice(0,f)||[]})})},c)}})})},N0=({children:e})=>{let t=_("Widget",Ua);return(0,ue.jsx)("div",{className:t.footer,children:e})},_0=({children:e})=>{let t=_("Widget",Ua);return(0,ue.jsx)("div",{className:t.root,"data-testid":"widget",children:e})},qF=({onLogIn:e,knowledgeAssistOptions:t={},assistantOptions:n={transcript:"in-memory-transcript",expectFormat:"json-schema:cues"}})=>{let r=ie(uu),o=j(la),s=j(jt),i=j(D1),a=j(qs),l=j(nC("knowledge-assist")),c=j(qf),u=j(Yf);return o===!1?(0,ue.jsx)(oA,{text:r("notSupported")}):s===!1?(0,ue.jsx)(jF,{onLogIn:e}):!a||!i||s===null?(0,ue.jsx)(oA,{text:r("waiting")}):(0,ue.jsx)(_0,{children:(0,ue.jsxs)(fm,{initialQuestion:t.initialQuestion,assistantCode:c!=null?c:u,evaluateKnowledgeAssistFn:u?Ks:Gs,children:[(0,ue.jsxs)(Ri,{children:[(0,ue.jsx)(WF,{}),(0,ue.jsx)(GF,{}),l&&(0,ue.jsx)(mm,{title:l.title,emptyState:t.emptyState})]}),(0,ue.jsxs)(N0,{children:[l&&(0,ue.jsx)(pm,{}),(0,ue.jsx)(VP,{assistantOptions:n})]})]})})},iA=qF;function Va(e){let t=new Range;return t.selectNodeContents(e),t}function aA(e,t,n){try{return fs(e,t,n),!0}catch(r){return!1}}function gm(e){return"tagName"in e&&(e.tagName==="DIV"||e.tagName==="P")}function hm(e){return"tagName"in e&&e.tagName==="BR"}var du=/[\u200B-\u200D\uFEFF]/g;function fs(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(du,""),f=o+u.length,d=t>=o&&t<=f,p=n>=o&&n<=f;if(d){let v=i(c,t-o);v===0&&!p?r.setStartBefore(l):r.setStart(l,v)}p&&(r.setEnd(l,i(c,n-o)),s=!0),o=f;break}case Node.ELEMENT_NODE:{if(hm(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;gm(l)&&c&&!gm(c)&&!hm(c)&&o++;break}default:break}}if(a(e),r.startContainer===document)throw new Error("Offsets out of bound");return r}function fu(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,v=f===o;switch(f.nodeType){case Node.TEXT_NODE:{let g=f.textContent;p&&(a=c+g.substring(0,r).replace(du,"").length),v&&(l=c+g.substring(0,s).replace(du,"").length),c+=g.replace(du,"").length;break}case Node.ELEMENT_NODE:{if(hm(f)&&f.nextSibling){c++;break}!d&&gm(f)&&f.previousSibling&&c++;for(let g=0;g<f.childNodes.length;g++){let x=p&&g===r,y=v&&g===s;if(x&&(a=c),y&&(l=c),l!==void 0||((!x||!i)&&u(f.childNodes[g]),v&&g===s-1&&(l=c),l!==void 0))break}v&&(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 pu(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 v=d?r:0,g=p?s:void 0;l+=u.textContent.replace(du,"").substring(v,g);break}case Node.ELEMENT_NODE:{if(!i&&a===1&&hm(u)&&u.nextSibling){l+=`
81
81
  `;break}!f&&!i&&a===1&&gm(u)&&u.previousSibling&&(l+=`
82
- `);let v=d?r:0,g=p?Math.min(s,u.childNodes.length):u.childNodes.length;for(let x=v;x<g&&(c(u.childNodes[x]),a!==2);x++);break}default:break}p&&(a=2)}return c(e),l}var lA=(i=>(i.CUT="Cut",i.BACKSPACE="Backspace",i.DELETE="Delete",i.ERASEEOF="EraseEof",i.UNDO="Undo",i.CLEAR="Clear",i))(lA||{}),bo=class{constructor(t){this.element=t;this.isFocused=!1;this.isActive=!0;this.isDisposed=!1;this.eventListeners={};this.disposeHandlers=[];this.cachedText="";this.cachedCaretPosition=null;this.cachedSelection={start:0,end:0};this.cachedHTML="";this.isSubmitting=!1;this.isPossibleClearInputAction=!1;this.cachedText=this.getText(),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.cachedCaretPosition===null;if(!this.isActive||(t===""&&this.cachedText!==""&&!this.isPossibleClearInputAction&&this.emit("submit"),t!==this.cachedText?(this.cachedText=t,this.cachedHTML=n,o=!0,this.emit("change",{plainText:t,rawHTML:n})):n!==null&&n!==this.cachedHTML&&(this.cachedHTML=n,o=!0,this.emit("change",{plainText:t,rawHTML:n})),(r.start!==this.cachedSelection.start||r.end!==this.cachedSelection.end)&&(this.cachedSelection=r,o=!0,this.emit("selection",r)),!o))return;let s=this.getCaretPosition();Xo(s,this.cachedCaretPosition)||(this.cachedCaretPosition=s,this.emit("caretposition",s))}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(lA).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()})}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 cA(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var yi=class extends bo{constructor(){super(...arguments);this.lastKnownSelection=null}getRootNode(){return this.element.getRootNode()}getText(){let n=new Range;return n.selectNodeContents(this.element),pu(this.element,n)}getHTML(){return this.element.innerHTML||""}getRange(){var i;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="getComposedRanges"in r&&n instanceof ShadowRoot?(i=r.getComposedRanges(n))==null?void 0:i[0]: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!cA(r)&&(n.insertNode(this.element.ownerDocument.createTextNode("\u2060")),r=n.getBoundingClientRect(),n.deleteContents(),!cA(r))?null:{top:r.top+r.height,left:r.left}}getSelection(){let n=this.getRange();if(n)return fu(this.element,n);let r=this.lastKnownSelection;if(r&&aA(this.element,r.start,r.end))return r;let o=Va(this.element);return o.collapse(!1),fu(this.element,o)}getSelectedText(){let{start:n,end:r}=this.getSelection();return pu(this.element,fs(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 YF=["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 uA(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",YF.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 vi=class extends bo{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 uA(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 dA(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 XF(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch(t){return e}}var D0=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()}},F0=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.disposeHandlers=[];this.iframe=dA(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()}},z0=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 F0(t,this.deepdeskUrl,{debug:!0}):new D0(t),r=o=>{var i,a;if(o.origin!==this.deepdeskUrl)return;let s=XF(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(P(S({},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)}},fA=z0;function QF(e){return e.replace(/(_\w)/g,t=>t[1].toUpperCase())}function $e(e){return Array.isArray(e)?e.map($e):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>P(S({},t),{[QF(n)]:$e(e[n])}),{}):e}function ZF(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function _t(e){return Array.isArray(e)?e.map(_t):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>P(S({},t),{[ZF(n)]:_t(e[n])}),{}):e}var $a=class extends Error{constructor(n,r){super(n);this.body=r;this.name="CustomError"}};var H0=e=>new Promise(t=>{setTimeout(t,e)});var ja=class extends $a{constructor(){super(...arguments);this.name="ClientError"}},U0=class extends $a{constructor(){super(...arguments);this.name="ServerError"}},B0=new Map;function JF(e){return I(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 ps=class ps{constructor(t="",n={}){this.baseUrl=t;this.options=n;this.latestRequestByUrl={};this.fetch=window.fetch.bind(window);n.fetch&&(this.fetch=n.fetch)}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",k=n,{useCache:c=!1,abortLatest:u=!1,attempts:f=1,retryDelay:d=500,refreshTokenOn401:p=!0,retryOnError:v=C=>C instanceof TypeError,retryOnResponse:g=C=>C.status>=500,version:x=null}=k,y=oe(k,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]);if(c){if(!l)throw new Error(`Can't use 'useCache' for ${n.method}`);if(B0.has(i)){r(B0.get(i));return}}let h=P(S({credentials:"include"},y),{headers:S({Accept:"application/json","Content-Type":"application/json"},y.headers)});!l&&this.csrfToken&&(h.headers=P(S({},h.headers),{"X-CSRFToken":this.csrfToken})),typeof x=="string"&&(h.headers=P(S({},h.headers),{"X-Deepdesk-API-Version":x}));let m=f,w=!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 E=()=>I(this,null,function*(){return m--,a(i,h).then(C=>I(this,null,function*(){return g(C)&&!s.isAborted&&m>0?(yield H0(d),E()):C.status===401&&p===!0&&w===!1?(w=!0,yield this.refreshToken(),E()):C})).catch(C=>I(this,null,function*(){if(v(C)&&!s.isAborted&&m>0)return yield H0(d),E();throw C}))});E().then(C=>I(this,null,function*(){let A=yield JF(C);if(delete this.latestRequestByUrl[i],C.status>=500){o(new U0("Server Error",A));return}if(C.status===401){o(new ja("Unauthorized",A));return}if(C.status===403){o(new ja("Forbidden",A));return}if(C.status===404){o(new ja("Not Found",A));return}if(C.status>=400){o(new ja("Bad Request",A));return}c&&B0.set(i,A),r(A)})).catch(C=>{o(C)})})}validateToken(){return I(this,null,function*(){let{has_valid_access_token:t}=yield this.get("/auth/validate");if(!t)try{yield this.refreshToken()}catch(r){return!1}let{is_logged_in:n}=yield this.get("/apis/admin/session/validate/");return!!n})}refreshToken(){return ps.refreshingToken||(ps.refreshingToken=this.get("/apis/admin/session/refresh/",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{ps.refreshingToken=null},1e3*60)})),ps.refreshingToken}get(t,n){return this.request(t,n)}post(t,n,r){return this.request(t,S({method:"POST",body:JSON.stringify(n)},r))}patch(t,n,r){return this.request(t,S({method:"PATCH",body:JSON.stringify(n)},r))}put(t,n,r){return this.request(t,S({method:"PUT",body:JSON.stringify(n)},r))}delete(t,n){return this.request(t,S({method:"DELETE"},n))}};ps.refreshingToken=null;var xi=ps;function V0(e){return P(S({},$e(e)),{metadata:e.metadata})}var wi=class wi{constructor(t,n={}){this.options=n;this.latestReceivedDeepdeskVersions={};this.shouldFetchCsrfToken=!0;this.client=new xi(t,{fetch:n.fetch}),this.client.patchFetch(r=>(o,s)=>I(this,null,function*(){let i=yield r(o,s);return this.handleDeepdeskVersionHeaders(i),i}))}preflight(){return I(this,null,function*(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let t=yield this.getCsrfToken();this.client.setCsrfToken(t)}return this.options.token?(wi.exchangeTokenPromise||(wi.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),wi.exchangeTokenPromise):Promise.resolve()})}createConversation(t){return I(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",P(S({chat_start_time:new Date().toISOString()},_t(t)),{metadata:(r=t.metadata)!=null?r:{}}));return V0(n)})}getMe(){return I(this,null,function*(){let t=yield this.client.get("/apis/admin/session/me/");return $e(t)})}postIdentity(t){return I(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/me/identities/",_t(t))})}patchMe(t){return I(this,null,function*(){yield this.preflight();let n=yield this.client.patch("/apis/admin/session/me/",_t(t));return $e(n)})}getProfile(t){return I(this,null,function*(){let n=yield this.client.get(`/apis/admin/profiles/${t}/`,{useCache:!0});return $e(n)})}getKnowledgeAssistant(t){return I(this,null,function*(){let n=yield this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{useCache:!0});return $e(n)})}getContentTypes(){return I(this,null,function*(){let t=yield this.client.get("/apis/admin/content-types/",{useCache:!0});return $e(t)})}getAccount(){return I(this,null,function*(){let t=yield this.client.get("/apis/admin/account/",{useCache:!0});return $e(t)})}getPlatformConfig(t){return I(this,null,function*(){let n=t!==void 0?`/platform/config/${t}/`:"/platform/config/",{config:r}=yield this.client.get(n,{useCache:!0});return $e(r)})}checkUserExists(t){return I(this,null,function*(){let{exists:n}=yield this.client.get(`/apis/admin/users/exists?external_id=${t}`,{version:"v1"});return n})}getConversationByExternalId(r){return I(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}`),V0(i)})}isConversationSupported(r){return I(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 I(this,null,function*(){var s;yield this.preflight();let r=_t(n);n.metadata&&(r.metadata=(s=n.metadata)!=null?s:{});let o=yield this.client.put(`/api/v2/conversations/${t}`,r);return V0(o)})}postMessages(t,n){return I(this,null,function*(){yield this.preflight(),yield this.client.post(`/api/v2/conversations/${t}/messages`,n.map(r=>P(S({},_t(r)),{metadata:r.metadata})))})}sendEvent(t,n){return I(this,null,function*(){yield this.preflight();let i=n,{data:r}=i,o=oe(i,["data"]),s=Object.entries(this.latestReceivedDeepdeskVersions).reduce((a,[l,c])=>P(S({},a),{[l]:c}),{});return this.client.post("/api/v2/events",_t(P(S(S({},s),o),{data:r,name:t})),{version:"v2"})})}getEntities(t){return I(this,null,function*(){return yield this.preflight(),(yield this.client.post("/api/entities",{messages:t.filter(r=>r.text)},{version:"v1"})).entities})}getTemporaryExchangeToken(){return I(this,null,function*(){return(yield this.client.get("/auth/exchange-token")).jwt})}exchangeTokenForAccessCookie(t){return I(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 I(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/api-key/",_t(n),{refreshTokenOn401:!1,headers:{apikey:t}})})}getTextSuggestions(o){return I(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}`,_t(n),{abortLatest:!0})).map(i=>P(S({},$e(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 I(this,null,function*(){return yield this.preflight(),this.client.validateToken()})}getAutocompleteSuggestions(t,n){return I(this,null,function*(){return yield this.preflight(),(yield this.client.post(`/api/v2/conversations/${t}/autocomplete`,_t(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))})}getPinnedMessages(t){return I(this,null,function*(){let n=yield this.client.get(`/api/v2/profiles/${t}/pinned-messages`,{abortLatest:!0});return $e(n).map(r=>P(S({},r),{text:r.message,source:"sticky-messages",type:"pinned-message"}))})}getStyleSuggestions(t){return I(this,null,function*(){let n=yield this.client.post("/api/style-suggestions",_t(t),{abortLatest:!0,version:"v1"});return $e(n)})}search(t){return I(this,null,function*(){let n=yield this.client.post(`/api/profiles/${t.profile}/search`,_t(t),{version:"v2"});return $e(n)})}knowledgeAssist(s,i,a){return I(this,arguments,function*(t,n,r,o={}){yield this.preflight();let l=yield this.client.post(`/api/knowledge-assist/assistants/${r}/search`,_t({question:t.question,doNotKnowAnswer:t.doNotKnowAnswer,customerInstruction:t.customerInstruction,chatHistory:n.map(c=>({question:c.question,answer:c.answer.answer})),agentId:o.agentId,conversationId:o.conversationId}),{version:"v2"});return $e(l)})}requestLoginByEmail(t){return I(this,null,function*(){yield this.preflight();let n=yield this.client.post("/apis/admin/session/passwordless/request/",{email:t});return $e(n)})}requestPasswordlessToken(){return I(this,null,function*(){let t=yield this.client.get("/apis/admin/session/passwordless/request/");return $e(t.token)})}getCsrfToken(){return I(this,null,function*(){let{token:t}=yield this.client.get("/apis/admin/session/csrf/");return t})}verifyLoginToken(t){return I(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/login/",{token:t});return $e(n)})}getSummary(r){return I(this,arguments,function*(t,n={}){yield this.preflight();let o=yield this.client.post("/api/summary",{conversation:{messages:t.filter(s=>s.text&&s.source),agent_id:n.agentId,id:n.externalConversationId},prompt_instruction:n.promptInstruction,model:n.model},{version:"v1"});return $e(o)})}evaluateAssistant(t,n){return I(this,null,function*(){var a;yield this.preflight();let r=new URLSearchParams,{expectFormat:o="text"}=n||{};if(o.startsWith("json-schema:")){let l=o.replace("json-schema:","");r.append("expect_response_format","json-schema"),r.append("expect_response_format_schema",l)}else r.append("expect_response_format",o);n!=null&&n.externalConversationId&&r.append("external_conversation_id",n.externalConversationId);let s=n!=null&&n.threadId?`/api/v2/assistants/${t}/threads/${n==null?void 0:n.threadId}/evaluate?${r.toString()}`:`/api/v2/assistants/${t}/evaluate?${r.toString()}`,i=yield this.client.post(s,{input:(a=n==null?void 0:n.input)!=null?a:{},conversation:n==null?void 0:n.transcript});return $e(i.output)})}createAssistantThread(t){return I(this,null,function*(){yield this.preflight();let{assistantCode:n}=t,r=yield this.client.post(`/apis/admin/assistants/${n}/threads/`,{});return $e(r)})}postMessageToAssistantThread(t){return I(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 $e(s)})}translateMessages(t){return I(this,null,function*(){yield this.preflight();let n=yield this.client.post("/api/translate",_t(t),{version:"v2"});return $e(n)})}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),s=o.match(Zx);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})}};wi.exchangeTokenPromise=null;var Eo=wi;var pA={startTime:null,stopTime:null},mA=e=>e.handlingTime,gA=ke({name:"handlingTime",initialState:pA,reducers:{handlingTimeStart(e){if(e.startTime&&!e.stopTime)throw new Error("Timing already started");e.startTime=new Date,e.stopTime=null},handlingTimeStop(e){if(!e.startTime)throw new Error("Timing not started");e.stopTime=new Date},handlingTimeReset(e){e.startTime=null,e.stopTime=null}},extraReducers:e=>{e.addCase(lt,()=>pA)}}),{handlingTimeStart:hA,handlingTimeStop:ym,handlingTimeReset:yA}=gA.actions,vA=gA.reducer;var xA=(e={})=>{let t=S({onAuthError:aa(!1)},e);return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var vm={list:{keywordMatches:[]},fetchState:"idle"};var Si=he("styleSuggestions/getAll",(n,r)=>I(void 0,[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 vm.list;if(!a)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:a,message:e})})),e5=ke({name:"styleSuggestions",initialState:vm,reducers:{},extraReducers:e=>{e.addCase(Si.pending,t=>{t.fetchState="loading"}).addCase(Si.rejected,t=>{t.fetchState="error"}).addCase(Si.fulfilled,(t,n)=>{t.fetchState="done",Xo(t.list,n.payload)||(t.list=n.payload)}).addCase(Bs,t=>{t.list=vm.list}).addCase(lt,()=>vm)}}),wA=e5.reducer;var SA=(e={})=>{let t,n=!0,r=S({getStyleSuggestions:Si,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 t5(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end}var bA=(e={})=>{let t=S({getTextSuggestions:gr,getAutocompleteSuggestions:Zc,debounce:200,check:Nr},e),n;return r=>o=>s=>{var g;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=(g=l.conversation.current)==null?void 0:g.id,d=s.type===Up.toString();if(!f||!c&&!u)return a;let{input:p}=l;return t5(p,i)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let x=ca(l);x===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(x))},d?0:t.debounce)),a}};var EA=Si.fulfilled.toString();function n5(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 TA=e=>t=>n=>r=>{var c;if(r.type!==EA){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=n5(o,i);r.type===EA&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var r5=of({assistants:QT,auth:k1,conversation:F1,contentTypes:JT,passwordlessToken:IP,entities:Gk,handlingTime:vA,info:rT,input:Y1,settings:x1,profile:oC,search:cT,styleSuggestions:wA,ui:GR,textSuggestions:MR});function CA(e){return KE({reducer:r5,middleware:t=>{var r;let n=t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI}},serializableCheck:!1}).concat(xA()).concat(bA({debounce:200})).concat(SA({debounce:500})).concat(TA(e.deepdeskAPI));return((r=e.middleware)!=null?r:[]).reduce((o,s)=>o.concat(s),n)},preloadedState:e.preloadedState})}var o5=e=>{var t,n;return(n=(t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())!=null?n:"unknown"},s5=e=>t=>n=>r=>{var a,l,c,u,f,d;let o=t.getState(),s=Yl("inlineSuggestions")(o);switch(r.type){case aa.toString():{!r.payload&&e.emit("logout",void 0);break}case fr.fulfilled.toString():r.payload.length>0&&e.sendEvent("entities found",{conversationId:(a=o.conversation.current)==null?void 0:a.id,data:{entities:r.payload}});break;case ro.toString():e.sendEvent(r.payload.name,{conversationId:((l=r.payload.options)==null?void 0:l.includeConversationData)&&((c=o.conversation.current)==null?void 0:c.id),data:r.payload.data});break;case Bs.toString():e.logSendMessage(r.payload);break;case Kf.toString():e.emit("call-to-action",{cue:r.payload});break;case or.fulfilled.toString():r.isBroadcasted||e.broadcast(Ny,r,!1);break;default:break}let i=n(r);switch(r.type){case Bs.toString():e.handleAfterSendMessage(r.payload);break;case eu.toString():e.onUpdateShowTabHint(r.payload);break;case ym.toString():e.logHandlingTime();break;case kf.toString():e.broadcast(If,r);break;case Hs.toString():e.broadcast(If,r);break;case Gf.toString():t.dispatch(Hs({source:"assistant",assistantCode:r.payload.code}));break;case"analytics/logEvent/fulfilled":{e.emit("event",r.meta.arg);break}case bf.toString():{let{start:p,end:v}=o.input.selection;e.emit("replace",P(S({},r.payload),{replace:r.payload.replace==="selection"?{start:p,end:v}:{start:0,end:v}}));break}case er.toString():{let{start:p,end:v}=o.input.selection;e.emit("select-suggestion",P(S({type:o5(r.payload.suggestion)},r.payload),{replace:r.payload.replace==="selection"?{start:p,end:v}:{start:0,end:v}})),s&&t.dispatch(Qo([]));break}case Ef.toString():e.emit("select-image",r.payload),e.sendEvent("Image attached",{conversationId:(u=o.conversation.current)==null?void 0:u.id,data:{path:r.payload.suggestion.image,title:r.payload.suggestion.title}});break;case Qo.toString():{s&&r.payload.length>0&&t.dispatch(Tf(0));break}case so.fulfilled.toString():{e.sendEvent("conversation summarized",{conversationId:(f=o.conversation.current)==null?void 0:f.id,data:{summary:r.payload,assistant:(d=t.getState().profile.data)==null?void 0:d.summarizerAssistantNew}}),e.emit("summary-generated",{summary:r.payload});break}default:break}return i},kA=s5;function $0(e){return e.toISOString().replace("T"," ").replace("Z","")}var i5=(e,t)=>t.version,RA=$t([da,Rr,mA,i5],(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:$0(o),timeStop:$0(s)}});function PA(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}}function j0(e,t){var s;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return j0(r,t);let o=(s=e.ownerDocument.defaultView)==null?void 0:s.frameElement;return o?j0(o,t):null}function W0(e,t){return j0(e,t)}function AA(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function a5(e){return typeof e=="object"&&e!==null&&"tagName"in e}function xm(e){return a5(e)&&(gi(e)||Yp(e))}var LA,zr=new Map,l5=["bottom","height","left","right","top","width"],IA=(e,t)=>!e&&!t?!1:e&&!t||!e&&t?!0:l5.some(n=>e[n]!==t[n]);function MA(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,...MA(t)]:[]}function OA(e,t){return!e||!t?null:P(S({},e),{top:e.top+t.top,left:e.left+t.left})}var wm=!1,NA=()=>{wm=!0;let e=[];if(zr.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),zr.delete(n);return}let r=n.getBoundingClientRect();IA(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{let n=t.parentRects?t.parentRects.reduce(OA,t.rect):t.rect;IA(n,t.totalRect)&&t.callbacks.forEach(r=>r(n)),t.totalRect=n}),zr.size===0){wm=!1;return}LA=window.requestAnimationFrame(NA)};function K0(e,t){let n=MA(e),r=[],o=n.map((s,i)=>K0(s,a=>{r[i]=a;let l=zr.get(e);if(!l)return;let c=r.reduce(OA,l.rect);l.callbacks.forEach(u=>u(c))}));return{observe(s=!0){if(o.forEach(i=>i.observe(!1)),zr.has(e)){let i=zr.get(e);i.callbacks.push(t),i.rect&&t(i.rect)}else zr.set(e,{rect:void 0,callbacks:[t],parentRects:r});s&&!wm&&NA()},unobserve(){o.forEach(i=>i.unobserve());let s=zr.get(e);if(s){let i=s.callbacks.indexOf(t);i>=0&&s.callbacks.splice(i,1),s.callbacks.length||zr.delete(e),zr.size||(cancelAnimationFrame(LA),wm=!1)}}}}var _A,Hr=new Map,DA=()=>{Hr.forEach((e,t)=>{if(!t.isConnected){Hr.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)))}),Hr.size!==0&&(_A=window.requestAnimationFrame(DA))};function FA(e,t){return{observe(){let n=Hr.size===0;Hr.has(e)?Hr.get(e).callbacks.push(t):Hr.set(e,{visible:void 0,callbacks:[t]}),n&&DA()},unobserve(){let n=Hr.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||Hr.delete(e),Hr.size||cancelAnimationFrame(_A)}}}}var G0=["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 q0(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function Wa(e){return Number.parseFloat(e)}function Sm(e){return Math.round(e*1e6)}function zA(e){return e/1e6}function Y0(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=Wa(e.width),s=Wa(e.borderLeftWidth),i=Wa(e.borderRightWidth),a=Wa(e.paddingRight),l=zA(Sm(o)-Sm(s)-Sm(i)),c=zA(Sm(r));if(l-c>2){let u=l-c;n.style.paddingRight=`${a+u}px`}}function mu(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",ui(n);let r=window.getComputedStyle(e),o=!0,s=()=>{n.scrollTop=e.scrollTop};q0(r,n,G0),Y0(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",s));let i=FA(e,()=>{q0(r,n,G0),Y0(r,e,n),s(),setTimeout(s,0)}),a,l=!0,c=K0(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(q0(r,n,G0),Y0(r,e,n),s(),n.style.top=`${d.top}px`,n.style.left=`${d.left}px`,t.closestScrollElement&&t.closestScrollElement!==e){let p=t.closestScrollElement.getBoundingClientRect(),v=window.getComputedStyle(t.closestScrollElement),g=Wa(v.borderTopWidth),x=Wa(v.borderBottomWidth),y=p.top+g-d.top,h=d.top+d.height+-(p.top+p.height-x);n.style.clipPath=`inset(${y}px 0px ${h}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()}]}var HA=(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")}}});function c5(e){return e.offsetParent!==null}function BA(e){if(!c5(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 bm(e,t,n=100){let r=BA(e);t({isVisible:r});let o=setInterval(()=>{let s=BA(e);s!==r&&(r=s,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var gu=class extends Error{};function u5(){let e,t;return{promise:new Promise((r,o)=>{e=r,t=o}),resolve:e,reject:t}}var Em=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 gu("Queued async function is outdated"));let o=u5();return this.queues[t][1]=o,o.promise.then(()=>n().finally(r))}};var d5={accepted:"onConversationAcceptedAssistants","new-message":"onConversationNewMessageAssistants",ended:"onConversationEndedAssistants"},UA=(e,t)=>{let n=e[d5[t]];return n&&n.length>0?n.map(r=>r.code):(Z.warn(`No assistant set in profile for conversation event "${t}"`),[])};var Le=b(R());var VA=HA("showTabHint",!0),Ka=class Ka{constructor({deepdeskUrl:t,version:n=Ka.version||"unknown",locale:r="en-US",token:o,fetch:s,productName:i,createCustomChannel:a}){this.inputMediator=null;this.eventListeners={};this.unmountHandlers=[];this.inlineSuggestions=null;this.aboveSuggestions=null;this.floatingMenu=null;this.widgetElement=null;this.widgetRoot=null;this.dynamicThunkObject={};this.queues=new Em;this.isMounted=!1;this.shouldRender=!0;this.loadProfileConfigPromise=null;let l=t.replace(/\/api$/,"");this.deepdeskApi=new Eo(l,{token:o,fetch:s}),this.version=n,this.instanceId=Ka.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[kA({broadcast:(u,f,d)=>{this.broadcastEvents.send(u,f,d)},emit:(u,f)=>this.emit(u,f),handleAfterSendMessage:u=>this.handleAfterSendMessage(u),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:u=>this.logSendMessage(u),onUpdateShowTabHint:u=>VA.update(u),sendEvent:(u,f)=>this.deepdeskApi.sendEvent(u,f)})]};this.store=CA(c),this.broadcastEvents=new fA({debug:!0,deepdeskUrl:l,eventMap:uT(this.store),createCustomChannel:a}),this.store.dispatch(eu(VA.value())),this.store.dispatch(yf({locale:r,adminUrl:l,productName:i}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){var t;return(t=zs(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)}login(){this.store.dispatch(aa(null)),this.store.dispatch(to());let t=n=>jt(n)&&w1(n)!=="loading";return new Promise(n=>{let r=this.subscribe(t,o=>{o&&(r(),n())});this.unmountHandlers.push(()=>{r()})})}isLoggedIn(){return I(this,null,function*(){return(yield this.store.dispatch(to())).payload})}isConversationSupported(t,n){return I(this,null,function*(){return(yield this.store.dispatch(Ry({externalId:t,options:n}))).payload})}createConversation(t){return I(this,null,function*(){var r;return this.hasConversation()&&this.externalId()!==t.externalId&&this.resetConversation(),(yield this.store.dispatch(xf(P(S({},t),{metadata:(r=t.metadata)!=null?r:{}})))).payload})}getConversationByExternalId(t,n){return I(this,null,function*(){return this.hasConversation()&&this.externalId()!==t&&this.resetConversation(),(yield this.store.dispatch(wf({externalId:t,options:n}))).payload})}upsertConversation(t){return I(this,null,function*(){var r;return this.hasConversation()&&this.externalId()!==t.externalId&&this.resetConversation(),(yield this.store.dispatch(Py(P(S({},t),{metadata:(r=t.metadata)!=null?r:{}})))).payload})}postMessages(t){return I(this,null,function*(){yield this.store.dispatch(Ay(t))})}updateConversation(t){return I(this,null,function*(){return(yield this.store.dispatch(Sf(t))).payload})}resetConversation(){this.store.dispatch(lt()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}configure(t){this.store.dispatch(yf(t))}setVisitorInfo(t){this.store.dispatch(eT(t))}setCustomData(t){this.store.dispatch(tT(t))}setAgentInfo(t,n){return I(this,null,function*(){yield this.store.dispatch(Jl(S(S({},t),n)))})}setAgentSettings(t){return I(this,null,function*(){yield this.store.dispatch(Ly(t))})}getAgentSettings(){return I(this,null,function*(){return(yield this.store.dispatch(My())).payload})}refresh(){return I(this,null,function*(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.store.dispatch(Cf({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()}));let t=[];return this.store.dispatch(Up()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})})}notifyExternalSuggestion(t){this.store.dispatch(er(t))}evaluateAssistant(t,n){return I(this,null,function*(){let u=n||{},{input:r={},transcript:o,showCuesInWidget:s=!0,includeMetadata:i,expectFormat:a}=u,l=oe(u,["input","transcript","showCuesInWidget","includeMetadata","expectFormat"]);Object.assign(r,l);let c=yield this.store.dispatch(or({assistantCode:t,expectFormat:a||"json-schema:cues",transcript:o,includeMetadata:i,input:r,skipState:!s}));if(c.error)throw new Error(c.error.message);return c.payload})}evaluateConversationAssistant(t,n){return I(this,null,function*(){yield this.loadProfileConfig();let r=this.state.profile.data;if(!r){Z.warn("Can't evaluate assistant when profile is not loaded yet.");return}let o=UA(r,t);yield Promise.all(o.map(s=>this.queues.push(s,()=>I(this,null,function*(){yield this.evaluateAssistant(s,S({includeMetadata:!0},n))})).catch(i=>{if(i instanceof gu){Z.warn(`Queued assistant "${s}" was outdated and dropped`);return}throw i})))})}getSummary(){return I(this,arguments,function*(t={}){var r;if(!this.hasConversation())return Z.warn("No conversation to create summary for."),null;(r=this.state.profile.data)!=null&&r.summarizerAssistantNew||Z.warn("No profile loaded yet, or no summarizer assistant set in profile");let n=yield this.store.dispatch(so(t));if(n.error)throw new Error(n.error.message);return n.payload})}handleKeyDown(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui,{textSuggestions:o,selectedSuggestionIndex:s,selection:i}=this.state.input,{inlineSuggestions:a,showTextSuggestions:l}=this.settings,c=a?"below":"above",u=o.length>0;if(this.store.dispatch(V1(Iy(t))),!Nr(this.state)||t.key!=="Tab"&&!l)return;let f=()=>{n||!u||i&&(t.shiftKey||(this.store.dispatch(W1()),t.preventDefault()))},d=()=>{n||!u||a&&s<=0||i&&(t.shiftKey||(this.store.dispatch(K1()),t.preventDefault()))};switch(t.key){case"ArrowUp":c==="below"?d():f();break;case"ArrowDown":{c==="below"?f():d();break}case"Escape":{n||(this.store.dispatch(Tf(-1)),this.store.dispatch(is({collapse:!0})),this.store.dispatch(WR(!0)),t.preventDefault());break}case"Tab":{t.preventDefault();let p=ua(this.state);if(!p)return;this.store.dispatch(eu(!1)),this.store.dispatch(er({text:p.text,suggestion:p,eventMetrics:{inputType:"tab"},replace:"until-selection-end"}));break}case" ":{if(this.settings.inlineSuggestions||this.state.input.selectedSuggestionIndex===-1)return;let p=ua(this.state);if(!p)return;this.store.dispatch(er({text:p.text,suggestion:p,eventMetrics:{inputType:"space"},replace:"until-selection-end"}));break}case"Enter":{if(this.settings.inlineSuggestions||t.shiftKey||this.state.input.selectedSuggestionIndex===-1)return;let p=ua(this.state);if(!p)return;this.store.dispatch(er({text:p.text,suggestion:p,eventMetrics:{inputType:"enter"},replace:"until-selection-end"})),t.preventDefault();break}default:}n&&r&&this.store.dispatch(is({collapse:!1}))}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(Qo([]))}handlingTimeStart(){this.state.handlingTime.startTime||(Z.info("Start handling time"),this.store.dispatch(hA()))}handlingTimeStop(){this.state.handlingTime.startTime&&(Z.info("Stop handling time"),this.store.dispatch(ym()))}logSendMessage(t){let n=PA(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=RA(this.state,{version:this.version});t&&(this.deepdeskApi.sendEvent("Handling Time",{conversationId:this.conversationId(),data:t}),this.store.dispatch(yA()))}notifySubmit(t={}){var n;this.shouldAbort()||(this.store.dispatch(Bs((n=t.text)!=null?n:this.state.input.text)),this.store.dispatch(q1()))}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(nT(t))}whenConversationLoaded(t){let n=o=>{var s;return(s=o.conversation.current)==null?void 0:s.id},r=()=>this.loadProfileConfig().then(()=>t());n(this.state)&&r(),this.subscribe(n,o=>{o&&r()})}overlayContainerFactory(t,n,r,o){let[s,i]=mu(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]=mu(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 ui(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(G1(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(!xm(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=oe(d,["customStyles","closestScrollSelector","floatingMenuParent","appendOverlayTo","inputMediator"]),c={customStyles:r,closestScrollSelector:o,floatingMenuParent:s,appendOverlayTo:i};this.configure(l),this.settings.automaticHandlingTime&&this.setupHandlingTime(t),ui(t),this.inputMediator=a||(gi(t)?new vi(t):new yi(t)),this.inputMediator.on("change",({plainText:p,rawHTML:v})=>{this.store.dispatch(Cf({text:p,html:v}))}),this.inputMediator.on("keyup",p=>{this.store.dispatch($1(Iy(p)))}),this.inputMediator.on("keydown",p=>{this.handleKeyDown(p)}),this.inputMediator.on("paste",({pastedText:p,selectionText:v})=>{this.store.dispatch(j1({text:p,selectionText:v}))}),this.inputMediator.on("cut",({selectionText:p})=>{this.store.dispatch(U1(p))});let u;this.inputMediator.on("selection",p=>{clearTimeout(u),p===null?u=setTimeout(()=>{p!==null&&this.store.dispatch(Rf(p))},500):this.store.dispatch(Rf(p))}),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(jp(!1))}),this.inputMediator.on("focus",()=>{this.store.dispatch(jp(!0))}),this.renderSuggestions(t,c),this.subscribe(Yl("inlineSuggestions"),()=>{this.renderSuggestions(t,c)});let f=this.renderOverlays(n);this.unmountHandlers.push(()=>{f.unmount()}),this.store.dispatch(Cf({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()})),this.store.dispatch(Rf(this.inputMediator.getSelection())),this.store.dispatch(jp(this.inputMediator.isFocused)),this.unmountHandlers.push(()=>{this.state.input.text!==""&&this.storeMetrics()}),this.whenConversationLoaded(()=>{var p;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setExternalId((p=this.state.conversation.current)==null?void 0:p.externalId)}),this.isMounted=!0}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;(t=this.inlineSuggestions)==null||t.unmount(),(n=this.aboveSuggestions)==null||n.unmount(),(r=this.floatingMenu)==null||r.unmount(),this.unmountHandlers.forEach(s=>s()),this.unmountHandlers=[],(o=this.inputMediator)==null||o.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderSuggestions(t,n){var r,o,s;(r=this.floatingMenu)==null||r.unmount(),(o=this.inlineSuggestions)==null||o.unmount(),(s=this.aboveSuggestions)==null||s.unmount(),this.settings.floatingMenu&&(this.floatingMenu=this.renderFloatingMenu(t,n)),this.settings.inlineSuggestions?this.inlineSuggestions=this.renderInlineSuggestions(t,n):this.aboveSuggestions=this.renderAboveSuggestions(t,n)}renderInlineSuggestions(t,n){let{customStyles:r}=n,o=this.createInlineContainer(t,"deepdesk-caret"),s=(0,ms.createRoot)(o);s.render((0,Le.jsx)(ls,{store:this.store,customStyles:r,children:(0,Le.jsx)(Zo,{broadcastEvents:this.broadcastEvents,children:(0,Le.jsx)(nP,{})})}));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()}}}renderAboveSuggestions(t,n){let{customStyles:r,closestScrollSelector:o,appendOverlayTo:s}=n,i=o&&W0(t,o)||void 0,[a,l]=this.overlayContainerFactory("deepdesk-tab-completion",i||t,{appendTo:s,closestScrollElement:i,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),[c,u]=this.overlayContainerFactory("deepdesk-suggestions-overlay",i||t,{appendTo:s},r==null?void 0:r.suggestionsRootNode),f=(0,ms.createRoot)(a);f.render((0,Le.jsx)(ls,{store:this.store,customStyles:r,children:(0,Le.jsx)(Zo,{broadcastEvents:this.broadcastEvents,children:(0,Le.jsx)(RP,{inputElement:t})})}));let d=(0,ms.createRoot)(c);return d.render((0,Le.jsx)(ls,{store:this.store,customStyles:r,children:(0,Le.jsx)(Zo,{broadcastEvents:this.broadcastEvents,children:(0,Le.jsx)(dP,{onLogIn:()=>this.loginViaPopup().catch(p=>Z.warn(p.message))})})})),{unmount(){f.unmount(),d.unmount(),l(),u()}}}renderFloatingMenu(t,n){let{customStyles:r,closestScrollSelector:o,appendOverlayTo:s,floatingMenuParent:i}=n,a=o&&W0(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,ms.createRoot)(l);return u.render((0,Le.jsx)(ls,{store:this.store,customStyles:r,children:(0,Le.jsx)(Zo,{broadcastEvents:this.broadcastEvents,children:(0,Le.jsx)($R,{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,ms.createRoot)(r);return o.render((0,Le.jsx)(ls,{store:this.store,customStyles:n,children:(0,Le.jsx)(Zo,{broadcastEvents:this.broadcastEvents,children:(0,Le.jsx)(zR,{})})})),{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}=n;this.widgetElement=t,this.configure({showImages:o,isEmbedded:s}),this.widgetRoot=(0,ms.createRoot)(t),this.widgetRoot.render((0,Le.jsx)(ls,{store:this.store,customStyles:r,children:(0,Le.jsx)(Zo,{broadcastEvents:this.broadcastEvents,children:(0,Le.jsx)(iA,{assistantOptions:n.assistantOptions,knowledgeAssistOptions:n.knowledgeAssist,onLogIn:()=>this.loginViaPopup().catch(i=>Z.warn(i.message))})})})),this.whenConversationLoaded(()=>{var i;this.broadcastEvents.setExternalId((i=this.state.conversation.current)==null?void 0:i.externalId)})}unmountWidget(){var t,n;(t=this.widgetRoot)==null||t.unmount(),this.widgetRoot=null,(n=this.widgetElement)==null||n.remove(),this.widgetElement=null}renderKnowledgeAssistantWidget(t,n,r={}){let{customStyles:o,initialQuestion:s}=r,i=(0,ms.createRoot)(n);return i.render((0,Le.jsx)(ls,{store:this.store,customStyles:o,children:(0,Le.jsx)(Zo,{broadcastEvents:this.broadcastEvents,children:(0,Le.jsx)(_0,{children:(0,Le.jsxs)(fm,{assistantCode:t,initialQuestion:s,evaluateKnowledgeAssistFn:r.isLegacyKnowledgeAssist?Ks:Gs,children:[(0,Le.jsx)(Ri,{children:(0,Le.jsx)(mm,{title:r.title,emptyState:r.emptyState})}),(0,Le.jsx)(N0,{children:(0,Le.jsx)(pm,{})})]})})})})),{unmount(){i.unmount()}}}setupHandlingTime(t){let n=bm(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){AA(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(()=>I(this,null,function*(){yield this.store.dispatch(Ec());let t=qs(this.state);t&&this.store.dispatch(yf({showSearch:t.search,showImageSearch:t.imageSearch,showEntitiesCommand:t.entitiesCommand,showSummaryCommand:!!t.summarizerAssistantNew,showKnowledgeSearch:!!t.knowledgeAssistantNew||!!t.knowledgeAssistant,recommendTextSuggestions:t.recommendTextSuggestions}))})),this.loadProfileConfigPromise)}loginViaPopup(t){return I(this,null,function*(){return new Promise((n,r)=>{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=>I(this,null,function*(){var v,g;if((v=p.data)!=null&&v.jwt)try{yield this.deepdeskApi.exchangeTokenForAccessCookie((g=p.data)==null?void 0:g.jwt),yield this.isLoggedIn(),this.broadcastEvents.send(tc),l=!0,o.port1.close(),n()}catch(x){console.error(x),r(x)}finally{l=!0,c()}});let u=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");u===null&&r(new Error("Popup blocked by browser"));let f=p=>I(this,null,function*(){var v;if(p.origin===a.origin)switch((v=p.data)==null?void 0:v.type){case"deepdesk-popup-loaded":{try{let g=JSON.stringify({type:"deepdesk-popup-create-channel"});u==null||u.postMessage(g,a.origin,[o.port2])}catch(g){Z.error("Error posting message to popup",g),r(g)}break}case"deepdesk-popup-error":{c(),p.data.message==="Timeout"&&Z.warn("Popup timed out. Check if the account's platform url is configured correctly."),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.unmountHandlers.push(c)})})}translateMessages(t){return this.deepdeskApi.translateMessages(t)}checkForTrialMode(t){return I(this,null,function*(){try{let{account:n}=yield this.deepdeskApi.getPlatformConfig();if(!n.isTrial){this.shouldRender=!0;return}if(Z.info("Trial is active"),!(yield this.deepdeskApi.checkUserExists(t)))throw new Error("User is not in trial");this.shouldRender=!0}catch(n){let{message:r}=n;Z.info(r),this.shouldRender=!1}})}refreshWidgetSuggestions(){return I(this,null,function*(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=Tc(this.state);try{n.forEach(({type:r})=>{r==="entities"?this.store.dispatch(fr()):Du.includes(r)||this.store.dispatch(gr(r))})}catch(r){this.handleError(r)}})}};Ka.version="17.1.4",Ka.count=0;var hu=Ka;function f5(e){return I(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 $A(e,t){return I(this,null,function*(){let n=yield f5(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 jA(e,t,n){return I(this,null,function*(){yield new Eo(e).authenticateWithKey(t,n)})}function WA(e){return e.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}function KA(r,o){return I(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 GA(r,o){return I(this,arguments,function*(e,t,n={}){let s=n.replace?fs(e,n.replace.start,n.replace.end):Va(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(`
82
+ `);let v=d?r:0,g=p?Math.min(s,u.childNodes.length):u.childNodes.length;for(let x=v;x<g&&(c(u.childNodes[x]),a!==2);x++);break}default:break}p&&(a=2)}return c(e),l}var lA=(i=>(i.CUT="Cut",i.BACKSPACE="Backspace",i.DELETE="Delete",i.ERASEEOF="EraseEof",i.UNDO="Undo",i.CLEAR="Clear",i))(lA||{}),bo=class{constructor(t){this.element=t;this.isFocused=!1;this.isActive=!0;this.isDisposed=!1;this.eventListeners={};this.disposeHandlers=[];this.cachedText="";this.cachedCaretPosition=null;this.cachedSelection={start:0,end:0};this.cachedHTML="";this.isSubmitting=!1;this.isPossibleClearInputAction=!1;this.cachedText=this.getText(),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.cachedCaretPosition===null;if(!this.isActive||(t===""&&this.cachedText!==""&&!this.isPossibleClearInputAction&&this.emit("submit"),t!==this.cachedText?(this.cachedText=t,this.cachedHTML=n,o=!0,this.emit("change",{plainText:t,rawHTML:n})):n!==null&&n!==this.cachedHTML&&(this.cachedHTML=n,o=!0,this.emit("change",{plainText:t,rawHTML:n})),(r.start!==this.cachedSelection.start||r.end!==this.cachedSelection.end)&&(this.cachedSelection=r,o=!0,this.emit("selection",r)),!o))return;let s=this.getCaretPosition();Xo(s,this.cachedCaretPosition)||(this.cachedCaretPosition=s,this.emit("caretposition",s))}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(lA).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()})}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 cA(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var yi=class extends bo{constructor(){super(...arguments);this.lastKnownSelection=null}getRootNode(){return this.element.getRootNode()}getText(){let n=new Range;return n.selectNodeContents(this.element),pu(this.element,n)}getHTML(){return this.element.innerHTML||""}getRange(){var i;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="getComposedRanges"in r&&n instanceof ShadowRoot?(i=r.getComposedRanges(n))==null?void 0:i[0]: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!cA(r)&&(n.insertNode(this.element.ownerDocument.createTextNode("\u2060")),r=n.getBoundingClientRect(),n.deleteContents(),!cA(r))?null:{top:r.top+r.height,left:r.left}}getSelection(){let n=this.getRange();if(n)return fu(this.element,n);let r=this.lastKnownSelection;if(r&&aA(this.element,r.start,r.end))return r;let o=Va(this.element);return o.collapse(!1),fu(this.element,o)}getSelectedText(){let{start:n,end:r}=this.getSelection();return pu(this.element,fs(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 YF=["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 uA(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",YF.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 vi=class extends bo{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 uA(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 dA(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 XF(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch(t){return e}}var D0=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()}},F0=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.disposeHandlers=[];this.iframe=dA(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()}},z0=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 F0(t,this.deepdeskUrl,{debug:!0}):new D0(t),r=o=>{var i,a;if(o.origin!==this.deepdeskUrl)return;let s=XF(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(P(S({},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)}},fA=z0;function QF(e){return e.replace(/(_\w)/g,t=>t[1].toUpperCase())}function $e(e){return Array.isArray(e)?e.map($e):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>P(S({},t),{[QF(n)]:$e(e[n])}),{}):e}function ZF(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function _t(e){return Array.isArray(e)?e.map(_t):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>P(S({},t),{[ZF(n)]:_t(e[n])}),{}):e}var $a=class extends Error{constructor(n,r){super(n);this.body=r;this.name="CustomError"}};var H0=e=>new Promise(t=>{setTimeout(t,e)});var ja=class extends $a{constructor(){super(...arguments);this.name="ClientError"}},U0=class extends $a{constructor(){super(...arguments);this.name="ServerError"}},B0=new Map;function JF(e){return I(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 ps=class ps{constructor(t="",n={}){this.baseUrl=t;this.options=n;this.latestRequestByUrl={};this.fetch=window.fetch.bind(window);n.fetch&&(this.fetch=n.fetch)}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",k=n,{useCache:c=!1,abortLatest:u=!1,attempts:f=1,retryDelay:d=500,refreshTokenOn401:p=!0,retryOnError:v=C=>C instanceof TypeError,retryOnResponse:g=C=>C.status>=500,version:x=null}=k,y=oe(k,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]);if(c){if(!l)throw new Error(`Can't use 'useCache' for ${n.method}`);if(B0.has(i)){r(B0.get(i));return}}let h=P(S({credentials:"include"},y),{headers:S({Accept:"application/json","Content-Type":"application/json"},y.headers)});!l&&this.csrfToken&&(h.headers=P(S({},h.headers),{"X-CSRFToken":this.csrfToken})),typeof x=="string"&&(h.headers=P(S({},h.headers),{"X-Deepdesk-API-Version":x}));let m=f,w=!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 E=()=>I(this,null,function*(){return m--,a(i,h).then(C=>I(this,null,function*(){return g(C)&&!s.isAborted&&m>0?(yield H0(d),E()):C.status===401&&p===!0&&w===!1?(w=!0,yield this.refreshToken(),E()):C})).catch(C=>I(this,null,function*(){if(v(C)&&!s.isAborted&&m>0)return yield H0(d),E();throw C}))});E().then(C=>I(this,null,function*(){let A=yield JF(C);if(delete this.latestRequestByUrl[i],C.status>=500){o(new U0("Server Error",A));return}if(C.status===401){o(new ja("Unauthorized",A));return}if(C.status===403){o(new ja("Forbidden",A));return}if(C.status===404){o(new ja("Not Found",A));return}if(C.status>=400){o(new ja("Bad Request",A));return}c&&B0.set(i,A),r(A)})).catch(C=>{o(C)})})}validateToken(){return I(this,null,function*(){let{has_valid_access_token:t}=yield this.get("/auth/validate");if(!t)try{yield this.refreshToken()}catch(r){return!1}let{is_logged_in:n}=yield this.get("/apis/admin/session/validate/");return!!n})}refreshToken(){return ps.refreshingToken||(ps.refreshingToken=this.get("/apis/admin/session/refresh/",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{ps.refreshingToken=null},1e3*60)})),ps.refreshingToken}get(t,n){return this.request(t,n)}post(t,n,r){return this.request(t,S({method:"POST",body:JSON.stringify(n)},r))}patch(t,n,r){return this.request(t,S({method:"PATCH",body:JSON.stringify(n)},r))}put(t,n,r){return this.request(t,S({method:"PUT",body:JSON.stringify(n)},r))}delete(t,n){return this.request(t,S({method:"DELETE"},n))}};ps.refreshingToken=null;var xi=ps;function V0(e){return P(S({},$e(e)),{metadata:e.metadata})}var wi=class wi{constructor(t,n={}){this.options=n;this.latestReceivedDeepdeskVersions={};this.shouldFetchCsrfToken=!0;this.client=new xi(t,{fetch:n.fetch}),this.client.patchFetch(r=>(o,s)=>I(this,null,function*(){let i=yield r(o,s);return this.handleDeepdeskVersionHeaders(i),i}))}preflight(){return I(this,null,function*(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let t=yield this.getCsrfToken();this.client.setCsrfToken(t)}return this.options.token?(wi.exchangeTokenPromise||(wi.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),wi.exchangeTokenPromise):Promise.resolve()})}createConversation(t){return I(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",P(S({chat_start_time:new Date().toISOString()},_t(t)),{metadata:(r=t.metadata)!=null?r:{}}));return V0(n)})}getMe(){return I(this,null,function*(){let t=yield this.client.get("/apis/admin/session/me/");return $e(t)})}postIdentity(t){return I(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/me/identities/",_t(t))})}patchMe(t){return I(this,null,function*(){yield this.preflight();let n=yield this.client.patch("/apis/admin/session/me/",_t(t));return $e(n)})}getProfile(t){return I(this,null,function*(){let n=yield this.client.get(`/apis/admin/profiles/${t}/`,{useCache:!0});return $e(n)})}getKnowledgeAssistant(t){return I(this,null,function*(){let n=yield this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{useCache:!0});return $e(n)})}getContentTypes(){return I(this,null,function*(){let t=yield this.client.get("/apis/admin/content-types/",{useCache:!0});return $e(t)})}getAccount(){return I(this,null,function*(){let t=yield this.client.get("/apis/admin/account/",{useCache:!0});return $e(t)})}getPlatformConfig(t){return I(this,null,function*(){let n=t!==void 0?`/platform/config/${t}/`:"/platform/config/",{config:r}=yield this.client.get(n,{useCache:!0});return $e(r)})}checkUserExists(t){return I(this,null,function*(){let{exists:n}=yield this.client.get(`/apis/admin/users/exists?external_id=${t}`,{version:"v1"});return n})}getConversationByExternalId(r){return I(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}`),V0(i)})}isConversationSupported(r){return I(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 I(this,null,function*(){var s;yield this.preflight();let r=_t(n);n.metadata&&(r.metadata=(s=n.metadata)!=null?s:{});let o=yield this.client.put(`/api/v2/conversations/${t}`,r);return V0(o)})}postMessages(t,n){return I(this,null,function*(){yield this.preflight(),yield this.client.post(`/api/v2/conversations/${t}/messages`,n.map(r=>P(S({},_t(r)),{metadata:r.metadata})))})}sendEvent(t,n){return I(this,null,function*(){yield this.preflight();let i=n,{data:r}=i,o=oe(i,["data"]),s=Object.entries(this.latestReceivedDeepdeskVersions).reduce((a,[l,c])=>P(S({},a),{[l]:c}),{});return this.client.post("/api/v2/events",_t(P(S(S({},s),o),{data:r,name:t})),{version:"v2"})})}getEntities(t){return I(this,null,function*(){return yield this.preflight(),(yield this.client.post("/api/entities",{messages:t.filter(r=>r.text)},{version:"v1"})).entities})}getTemporaryExchangeToken(){return I(this,null,function*(){return(yield this.client.get("/auth/exchange-token")).jwt})}exchangeTokenForAccessCookie(t){return I(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 I(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/api-key/",_t(n),{refreshTokenOn401:!1,headers:{apikey:t}})})}getTextSuggestions(o){return I(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}`,_t(n),{abortLatest:!0})).map(i=>P(S({},$e(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 I(this,null,function*(){return yield this.preflight(),this.client.validateToken()})}getAutocompleteSuggestions(t,n){return I(this,null,function*(){return yield this.preflight(),(yield this.client.post(`/api/v2/conversations/${t}/autocomplete`,_t(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))})}getPinnedMessages(t){return I(this,null,function*(){let n=yield this.client.get(`/api/v2/profiles/${t}/pinned-messages`,{abortLatest:!0});return $e(n).map(r=>P(S({},r),{text:r.message,source:"sticky-messages",type:"pinned-message"}))})}getStyleSuggestions(t){return I(this,null,function*(){let n=yield this.client.post("/api/style-suggestions",_t(t),{abortLatest:!0,version:"v1"});return $e(n)})}search(t){return I(this,null,function*(){let n=yield this.client.post(`/api/profiles/${t.profile}/search`,_t(t),{version:"v2"});return $e(n)})}knowledgeAssist(s,i,a){return I(this,arguments,function*(t,n,r,o={}){yield this.preflight();let l=yield this.client.post(`/api/knowledge-assist/assistants/${r}/search`,_t({question:t.question,doNotKnowAnswer:t.doNotKnowAnswer,customerInstruction:t.customerInstruction,chatHistory:n.map(c=>({question:c.question,answer:c.answer.answer})),agentId:o.agentId,conversationId:o.conversationId}),{version:"v2"});return $e(l)})}requestLoginByEmail(t){return I(this,null,function*(){yield this.preflight();let n=yield this.client.post("/apis/admin/session/passwordless/request/",{email:t});return $e(n)})}requestPasswordlessToken(){return I(this,null,function*(){let t=yield this.client.get("/apis/admin/session/passwordless/request/");return $e(t.token)})}getCsrfToken(){return I(this,null,function*(){let{token:t}=yield this.client.get("/apis/admin/session/csrf/");return t})}verifyLoginToken(t){return I(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/login/",{token:t});return $e(n)})}getSummary(r){return I(this,arguments,function*(t,n={}){yield this.preflight();let o=yield this.client.post("/api/summary",{conversation:{messages:t.filter(s=>s.text&&s.source),agent_id:n.agentId,id:n.externalConversationId},prompt_instruction:n.promptInstruction,model:n.model},{version:"v1"});return $e(o)})}evaluateAssistant(t,n){return I(this,null,function*(){var a;yield this.preflight();let r=new URLSearchParams,{expectFormat:o="text"}=n||{};if(o.startsWith("json-schema:")){let l=o.replace("json-schema:","");r.append("expect_response_format","json-schema"),r.append("expect_response_format_schema",l)}else r.append("expect_response_format",o);n!=null&&n.externalConversationId&&r.append("external_conversation_id",n.externalConversationId);let s=n!=null&&n.threadId?`/api/v2/assistants/${t}/threads/${n==null?void 0:n.threadId}/evaluate?${r.toString()}`:`/api/v2/assistants/${t}/evaluate?${r.toString()}`,i=yield this.client.post(s,{input:(a=n==null?void 0:n.input)!=null?a:{},conversation:n==null?void 0:n.transcript});return $e(i.output)})}createAssistantThread(t){return I(this,null,function*(){yield this.preflight();let{assistantCode:n}=t,r=yield this.client.post(`/apis/admin/assistants/${n}/threads/`,{});return $e(r)})}postMessageToAssistantThread(t){return I(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 $e(s)})}translateMessages(t){return I(this,null,function*(){yield this.preflight();let n=yield this.client.post("/api/translate",_t(t),{version:"v2"});return $e(n)})}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),s=o.match(Zx);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})}};wi.exchangeTokenPromise=null;var Eo=wi;var pA={startTime:null,stopTime:null},mA=e=>e.handlingTime,gA=ke({name:"handlingTime",initialState:pA,reducers:{handlingTimeStart(e){if(e.startTime&&!e.stopTime)throw new Error("Timing already started");e.startTime=new Date,e.stopTime=null},handlingTimeStop(e){if(!e.startTime)throw new Error("Timing not started");e.stopTime=new Date},handlingTimeReset(e){e.startTime=null,e.stopTime=null}},extraReducers:e=>{e.addCase(lt,()=>pA)}}),{handlingTimeStart:hA,handlingTimeStop:ym,handlingTimeReset:yA}=gA.actions,vA=gA.reducer;var xA=(e={})=>{let t=S({onAuthError:aa(!1)},e);return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var vm={list:{keywordMatches:[]},fetchState:"idle"};var Si=he("styleSuggestions/getAll",(n,r)=>I(void 0,[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 vm.list;if(!a)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:a,message:e})})),e5=ke({name:"styleSuggestions",initialState:vm,reducers:{},extraReducers:e=>{e.addCase(Si.pending,t=>{t.fetchState="loading"}).addCase(Si.rejected,t=>{t.fetchState="error"}).addCase(Si.fulfilled,(t,n)=>{t.fetchState="done",Xo(t.list,n.payload)||(t.list=n.payload)}).addCase(Bs,t=>{t.list=vm.list}).addCase(lt,()=>vm)}}),wA=e5.reducer;var SA=(e={})=>{let t,n=!0,r=S({getStyleSuggestions:Si,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 t5(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end}var bA=(e={})=>{let t=S({getTextSuggestions:gr,getAutocompleteSuggestions:Zc,debounce:200,check:Nr},e),n;return r=>o=>s=>{var g;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=(g=l.conversation.current)==null?void 0:g.id,d=s.type===Up.toString();if(!f||!c&&!u)return a;let{input:p}=l;return t5(p,i)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let x=ca(l);x===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(x))},d?0:t.debounce)),a}};var EA=Si.fulfilled.toString();function n5(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 TA=e=>t=>n=>r=>{var c;if(r.type!==EA){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=n5(o,i);r.type===EA&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var r5=of({assistants:QT,auth:k1,conversation:F1,contentTypes:JT,passwordlessToken:IP,entities:Gk,handlingTime:vA,info:rT,input:Y1,settings:x1,profile:oC,search:cT,styleSuggestions:wA,ui:GR,textSuggestions:MR});function CA(e){return KE({reducer:r5,middleware:t=>{var r;let n=t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI}},serializableCheck:!1}).concat(xA()).concat(bA({debounce:200})).concat(SA({debounce:500})).concat(TA(e.deepdeskAPI));return((r=e.middleware)!=null?r:[]).reduce((o,s)=>o.concat(s),n)},preloadedState:e.preloadedState})}var o5=e=>{var t,n;return(n=(t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())!=null?n:"unknown"},s5=e=>t=>n=>r=>{var a,l,c,u,f,d;let o=t.getState(),s=Yl("inlineSuggestions")(o);switch(r.type){case aa.toString():{!r.payload&&e.emit("logout",void 0);break}case fr.fulfilled.toString():r.payload.length>0&&e.sendEvent("entities found",{conversationId:(a=o.conversation.current)==null?void 0:a.id,data:{entities:r.payload}});break;case ro.toString():e.sendEvent(r.payload.name,{conversationId:((l=r.payload.options)==null?void 0:l.includeConversationData)&&((c=o.conversation.current)==null?void 0:c.id),data:r.payload.data});break;case Bs.toString():e.logSendMessage(r.payload);break;case Kf.toString():e.emit("call-to-action",{cue:r.payload});break;case or.fulfilled.toString():r.isBroadcasted||e.broadcast(Ny,r,!1);break;default:break}let i=n(r);switch(r.type){case Bs.toString():e.handleAfterSendMessage(r.payload);break;case eu.toString():e.onUpdateShowTabHint(r.payload);break;case ym.toString():e.logHandlingTime();break;case kf.toString():e.broadcast(If,r);break;case Hs.toString():e.broadcast(If,r);break;case Gf.toString():t.dispatch(Hs({source:"assistant",assistantCode:r.payload.code}));break;case"analytics/logEvent/fulfilled":{e.emit("event",r.meta.arg);break}case bf.toString():{let{start:p,end:v}=o.input.selection;e.emit("replace",P(S({},r.payload),{replace:r.payload.replace==="selection"?{start:p,end:v}:{start:0,end:v}}));break}case er.toString():{let{start:p,end:v}=o.input.selection;e.emit("select-suggestion",P(S({type:o5(r.payload.suggestion)},r.payload),{replace:r.payload.replace==="selection"?{start:p,end:v}:{start:0,end:v}})),s&&t.dispatch(Qo([]));break}case Ef.toString():e.emit("select-image",r.payload),e.sendEvent("Image attached",{conversationId:(u=o.conversation.current)==null?void 0:u.id,data:{path:r.payload.suggestion.image,title:r.payload.suggestion.title}});break;case Qo.toString():{s&&r.payload.length>0&&t.dispatch(Tf(0));break}case so.fulfilled.toString():{e.sendEvent("conversation summarized",{conversationId:(f=o.conversation.current)==null?void 0:f.id,data:{summary:r.payload,assistant:(d=t.getState().profile.data)==null?void 0:d.summarizerAssistantNew}}),e.emit("summary-generated",{summary:r.payload});break}default:break}return i},kA=s5;function $0(e){return e.toISOString().replace("T"," ").replace("Z","")}var i5=(e,t)=>t.version,RA=$t([da,Rr,mA,i5],(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:$0(o),timeStop:$0(s)}});function PA(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}}function j0(e,t){var s;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return j0(r,t);let o=(s=e.ownerDocument.defaultView)==null?void 0:s.frameElement;return o?j0(o,t):null}function W0(e,t){return j0(e,t)}function AA(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function a5(e){return typeof e=="object"&&e!==null&&"tagName"in e}function xm(e){return a5(e)&&(gi(e)||Yp(e))}var LA,zr=new Map,l5=["bottom","height","left","right","top","width"],IA=(e,t)=>!e&&!t?!1:e&&!t||!e&&t?!0:l5.some(n=>e[n]!==t[n]);function MA(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,...MA(t)]:[]}function OA(e,t){return!e||!t?null:P(S({},e),{top:e.top+t.top,left:e.left+t.left})}var wm=!1,NA=()=>{wm=!0;let e=[];if(zr.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),zr.delete(n);return}let r=n.getBoundingClientRect();IA(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{let n=t.parentRects?t.parentRects.reduce(OA,t.rect):t.rect;IA(n,t.totalRect)&&t.callbacks.forEach(r=>r(n)),t.totalRect=n}),zr.size===0){wm=!1;return}LA=window.requestAnimationFrame(NA)};function K0(e,t){let n=MA(e),r=[],o=n.map((s,i)=>K0(s,a=>{r[i]=a;let l=zr.get(e);if(!l)return;let c=r.reduce(OA,l.rect);l.callbacks.forEach(u=>u(c))}));return{observe(s=!0){if(o.forEach(i=>i.observe(!1)),zr.has(e)){let i=zr.get(e);i.callbacks.push(t),i.rect&&t(i.rect)}else zr.set(e,{rect:void 0,callbacks:[t],parentRects:r});s&&!wm&&NA()},unobserve(){o.forEach(i=>i.unobserve());let s=zr.get(e);if(s){let i=s.callbacks.indexOf(t);i>=0&&s.callbacks.splice(i,1),s.callbacks.length||zr.delete(e),zr.size||(cancelAnimationFrame(LA),wm=!1)}}}}var _A,Hr=new Map,DA=()=>{Hr.forEach((e,t)=>{if(!t.isConnected){Hr.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)))}),Hr.size!==0&&(_A=window.requestAnimationFrame(DA))};function FA(e,t){return{observe(){let n=Hr.size===0;Hr.has(e)?Hr.get(e).callbacks.push(t):Hr.set(e,{visible:void 0,callbacks:[t]}),n&&DA()},unobserve(){let n=Hr.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||Hr.delete(e),Hr.size||cancelAnimationFrame(_A)}}}}var G0=["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 q0(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function Wa(e){return Number.parseFloat(e)}function Sm(e){return Math.round(e*1e6)}function zA(e){return e/1e6}function Y0(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=Wa(e.width),s=Wa(e.borderLeftWidth),i=Wa(e.borderRightWidth),a=Wa(e.paddingRight),l=zA(Sm(o)-Sm(s)-Sm(i)),c=zA(Sm(r));if(l-c>2){let u=l-c;n.style.paddingRight=`${a+u}px`}}function mu(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",ui(n);let r=window.getComputedStyle(e),o=!0,s=()=>{n.scrollTop=e.scrollTop};q0(r,n,G0),Y0(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",s));let i=FA(e,()=>{q0(r,n,G0),Y0(r,e,n),s(),setTimeout(s,0)}),a,l=!0,c=K0(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(q0(r,n,G0),Y0(r,e,n),s(),n.style.top=`${d.top}px`,n.style.left=`${d.left}px`,t.closestScrollElement&&t.closestScrollElement!==e){let p=t.closestScrollElement.getBoundingClientRect(),v=window.getComputedStyle(t.closestScrollElement),g=Wa(v.borderTopWidth),x=Wa(v.borderBottomWidth),y=p.top+g-d.top,h=d.top+d.height+-(p.top+p.height-x);n.style.clipPath=`inset(${y}px 0px ${h}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()}]}var HA=(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")}}});function c5(e){return e.offsetParent!==null}function BA(e){if(!c5(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 bm(e,t,n=100){let r=BA(e);t({isVisible:r});let o=setInterval(()=>{let s=BA(e);s!==r&&(r=s,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var gu=class extends Error{};function u5(){let e,t;return{promise:new Promise((r,o)=>{e=r,t=o}),resolve:e,reject:t}}var Em=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 gu("Queued async function is outdated"));let o=u5();return this.queues[t][1]=o,o.promise.then(()=>n().finally(r))}};var d5={accepted:"onConversationAcceptedAssistants","new-message":"onConversationNewMessageAssistants",ended:"onConversationEndedAssistants"},UA=(e,t)=>{let n=e[d5[t]];return n&&n.length>0?n.map(r=>r.code):(Z.warn(`No assistant set in profile for conversation event "${t}"`),[])};var Le=b(R());var VA=HA("showTabHint",!0),Ka=class Ka{constructor({deepdeskUrl:t,version:n=Ka.version||"unknown",locale:r="en-US",token:o,fetch:s,productName:i,createCustomChannel:a}){this.inputMediator=null;this.eventListeners={};this.unmountHandlers=[];this.inlineSuggestions=null;this.aboveSuggestions=null;this.floatingMenu=null;this.widgetElement=null;this.widgetRoot=null;this.dynamicThunkObject={};this.queues=new Em;this.isMounted=!1;this.shouldRender=!0;this.loadProfileConfigPromise=null;let l=t.replace(/\/api$/,"");this.deepdeskApi=new Eo(l,{token:o,fetch:s}),this.version=n,this.instanceId=Ka.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[kA({broadcast:(u,f,d)=>{this.broadcastEvents.send(u,f,d)},emit:(u,f)=>this.emit(u,f),handleAfterSendMessage:u=>this.handleAfterSendMessage(u),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:u=>this.logSendMessage(u),onUpdateShowTabHint:u=>VA.update(u),sendEvent:(u,f)=>this.deepdeskApi.sendEvent(u,f)})]};this.store=CA(c),this.broadcastEvents=new fA({debug:!0,deepdeskUrl:l,eventMap:uT(this.store),createCustomChannel:a}),this.store.dispatch(eu(VA.value())),this.store.dispatch(yf({locale:r,adminUrl:l,productName:i}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){var t;return(t=zs(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)}login(){this.store.dispatch(aa(null)),this.store.dispatch(to());let t=n=>jt(n)&&w1(n)!=="loading";return new Promise(n=>{let r=this.subscribe(t,o=>{o&&(r(),n())});this.unmountHandlers.push(()=>{r()})})}isLoggedIn(){return I(this,null,function*(){return(yield this.store.dispatch(to())).payload})}isConversationSupported(t,n){return I(this,null,function*(){return(yield this.store.dispatch(Ry({externalId:t,options:n}))).payload})}createConversation(t){return I(this,null,function*(){var r;return this.hasConversation()&&this.externalId()!==t.externalId&&this.resetConversation(),(yield this.store.dispatch(xf(P(S({},t),{metadata:(r=t.metadata)!=null?r:{}})))).payload})}getConversationByExternalId(t,n){return I(this,null,function*(){return this.hasConversation()&&this.externalId()!==t&&this.resetConversation(),(yield this.store.dispatch(wf({externalId:t,options:n}))).payload})}upsertConversation(t){return I(this,null,function*(){var r;return this.hasConversation()&&this.externalId()!==t.externalId&&this.resetConversation(),(yield this.store.dispatch(Py(P(S({},t),{metadata:(r=t.metadata)!=null?r:{}})))).payload})}postMessages(t){return I(this,null,function*(){yield this.store.dispatch(Ay(t))})}updateConversation(t){return I(this,null,function*(){return(yield this.store.dispatch(Sf(t))).payload})}resetConversation(){this.store.dispatch(lt()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}configure(t){this.store.dispatch(yf(t))}setVisitorInfo(t){this.store.dispatch(eT(t))}setCustomData(t){this.store.dispatch(tT(t))}setAgentInfo(t,n){return I(this,null,function*(){yield this.store.dispatch(Jl(S(S({},t),n)))})}setAgentSettings(t){return I(this,null,function*(){yield this.store.dispatch(Ly(t))})}getAgentSettings(){return I(this,null,function*(){return(yield this.store.dispatch(My())).payload})}refresh(){return I(this,null,function*(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.store.dispatch(Cf({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()}));let t=[];return this.store.dispatch(Up()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})})}notifyExternalSuggestion(t){this.store.dispatch(er(t))}evaluateAssistant(t,n){return I(this,null,function*(){let u=n||{},{input:r={},transcript:o,showCuesInWidget:s=!0,includeMetadata:i,expectFormat:a}=u,l=oe(u,["input","transcript","showCuesInWidget","includeMetadata","expectFormat"]);Object.assign(r,l);let c=yield this.store.dispatch(or({assistantCode:t,expectFormat:a||"json-schema:cues",transcript:o,includeMetadata:i,input:r,skipState:!s}));if(c.error)throw new Error(c.error.message);return c.payload})}evaluateConversationAssistant(t,n){return I(this,null,function*(){yield this.loadProfileConfig();let r=this.state.profile.data;if(!r){Z.warn("Can't evaluate assistant when profile is not loaded yet.");return}let o=UA(r,t);yield Promise.all(o.map(s=>this.queues.push(s,()=>I(this,null,function*(){yield this.evaluateAssistant(s,S({includeMetadata:!0},n))})).catch(i=>{if(i instanceof gu){Z.warn(`Queued assistant "${s}" was outdated and dropped`);return}throw i})))})}getSummary(){return I(this,arguments,function*(t={}){var r;if(!this.hasConversation())return Z.warn("No conversation to create summary for."),null;(r=this.state.profile.data)!=null&&r.summarizerAssistantNew||Z.warn("No profile loaded yet, or no summarizer assistant set in profile");let n=yield this.store.dispatch(so(t));if(n.error)throw new Error(n.error.message);return n.payload})}handleKeyDown(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui,{textSuggestions:o,selectedSuggestionIndex:s,selection:i}=this.state.input,{inlineSuggestions:a,showTextSuggestions:l}=this.settings,c=a?"below":"above",u=o.length>0;if(this.store.dispatch(V1(Iy(t))),!Nr(this.state)||t.key!=="Tab"&&!l)return;let f=()=>{n||!u||i&&(t.shiftKey||(this.store.dispatch(W1()),t.preventDefault()))},d=()=>{n||!u||a&&s<=0||i&&(t.shiftKey||(this.store.dispatch(K1()),t.preventDefault()))};switch(t.key){case"ArrowUp":c==="below"?d():f();break;case"ArrowDown":{c==="below"?f():d();break}case"Escape":{n||(this.store.dispatch(Tf(-1)),this.store.dispatch(is({collapse:!0})),this.store.dispatch(WR(!0)),t.preventDefault());break}case"Tab":{t.preventDefault();let p=ua(this.state);if(!p)return;this.store.dispatch(eu(!1)),this.store.dispatch(er({text:p.text,suggestion:p,eventMetrics:{inputType:"tab"},replace:"until-selection-end"}));break}case" ":{if(this.settings.inlineSuggestions||this.state.input.selectedSuggestionIndex===-1)return;let p=ua(this.state);if(!p)return;this.store.dispatch(er({text:p.text,suggestion:p,eventMetrics:{inputType:"space"},replace:"until-selection-end"}));break}case"Enter":{if(this.settings.inlineSuggestions||t.shiftKey||this.state.input.selectedSuggestionIndex===-1)return;let p=ua(this.state);if(!p)return;this.store.dispatch(er({text:p.text,suggestion:p,eventMetrics:{inputType:"enter"},replace:"until-selection-end"})),t.preventDefault();break}default:}n&&r&&this.store.dispatch(is({collapse:!1}))}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(Qo([]))}handlingTimeStart(){this.state.handlingTime.startTime||(Z.info("Start handling time"),this.store.dispatch(hA()))}handlingTimeStop(){this.state.handlingTime.startTime&&(Z.info("Stop handling time"),this.store.dispatch(ym()))}logSendMessage(t){let n=PA(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=RA(this.state,{version:this.version});t&&(this.deepdeskApi.sendEvent("Handling Time",{conversationId:this.conversationId(),data:t}),this.store.dispatch(yA()))}notifySubmit(t={}){var n;this.shouldAbort()||(this.store.dispatch(Bs((n=t.text)!=null?n:this.state.input.text)),this.store.dispatch(q1()))}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(nT(t))}whenConversationLoaded(t){let n=o=>{var s;return(s=o.conversation.current)==null?void 0:s.id},r=()=>this.loadProfileConfig().then(()=>t());n(this.state)&&r(),this.subscribe(n,o=>{o&&r()})}overlayContainerFactory(t,n,r,o){let[s,i]=mu(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]=mu(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 ui(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(G1(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(!xm(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=oe(d,["customStyles","closestScrollSelector","floatingMenuParent","appendOverlayTo","inputMediator"]),c={customStyles:r,closestScrollSelector:o,floatingMenuParent:s,appendOverlayTo:i};this.configure(l),this.settings.automaticHandlingTime&&this.setupHandlingTime(t),ui(t),this.inputMediator=a||(gi(t)?new vi(t):new yi(t)),this.inputMediator.on("change",({plainText:p,rawHTML:v})=>{this.store.dispatch(Cf({text:p,html:v}))}),this.inputMediator.on("keyup",p=>{this.store.dispatch($1(Iy(p)))}),this.inputMediator.on("keydown",p=>{this.handleKeyDown(p)}),this.inputMediator.on("paste",({pastedText:p,selectionText:v})=>{this.store.dispatch(j1({text:p,selectionText:v}))}),this.inputMediator.on("cut",({selectionText:p})=>{this.store.dispatch(U1(p))});let u;this.inputMediator.on("selection",p=>{clearTimeout(u),p===null?u=setTimeout(()=>{p!==null&&this.store.dispatch(Rf(p))},500):this.store.dispatch(Rf(p))}),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(jp(!1))}),this.inputMediator.on("focus",()=>{this.store.dispatch(jp(!0))}),this.renderSuggestions(t,c),this.subscribe(Yl("inlineSuggestions"),()=>{this.renderSuggestions(t,c)});let f=this.renderOverlays(n);this.unmountHandlers.push(()=>{f.unmount()}),this.store.dispatch(Cf({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()})),this.store.dispatch(Rf(this.inputMediator.getSelection())),this.store.dispatch(jp(this.inputMediator.isFocused)),this.unmountHandlers.push(()=>{this.state.input.text!==""&&this.storeMetrics()}),this.whenConversationLoaded(()=>{var p;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setExternalId((p=this.state.conversation.current)==null?void 0:p.externalId)}),this.isMounted=!0}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;(t=this.inlineSuggestions)==null||t.unmount(),(n=this.aboveSuggestions)==null||n.unmount(),(r=this.floatingMenu)==null||r.unmount(),this.unmountHandlers.forEach(s=>s()),this.unmountHandlers=[],(o=this.inputMediator)==null||o.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderSuggestions(t,n){var r,o,s;(r=this.floatingMenu)==null||r.unmount(),(o=this.inlineSuggestions)==null||o.unmount(),(s=this.aboveSuggestions)==null||s.unmount(),this.settings.floatingMenu&&(this.floatingMenu=this.renderFloatingMenu(t,n)),this.settings.inlineSuggestions?this.inlineSuggestions=this.renderInlineSuggestions(t,n):this.aboveSuggestions=this.renderAboveSuggestions(t,n)}renderInlineSuggestions(t,n){let{customStyles:r}=n,o=this.createInlineContainer(t,"deepdesk-caret"),s=(0,ms.createRoot)(o);s.render((0,Le.jsx)(ls,{store:this.store,customStyles:r,children:(0,Le.jsx)(Zo,{broadcastEvents:this.broadcastEvents,children:(0,Le.jsx)(nP,{})})}));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()}}}renderAboveSuggestions(t,n){let{customStyles:r,closestScrollSelector:o,appendOverlayTo:s}=n,i=o&&W0(t,o)||void 0,[a,l]=this.overlayContainerFactory("deepdesk-tab-completion",i||t,{appendTo:s,closestScrollElement:i,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),[c,u]=this.overlayContainerFactory("deepdesk-suggestions-overlay",i||t,{appendTo:s},r==null?void 0:r.suggestionsRootNode),f=(0,ms.createRoot)(a);f.render((0,Le.jsx)(ls,{store:this.store,customStyles:r,children:(0,Le.jsx)(Zo,{broadcastEvents:this.broadcastEvents,children:(0,Le.jsx)(RP,{inputElement:t})})}));let d=(0,ms.createRoot)(c);return d.render((0,Le.jsx)(ls,{store:this.store,customStyles:r,children:(0,Le.jsx)(Zo,{broadcastEvents:this.broadcastEvents,children:(0,Le.jsx)(dP,{onLogIn:()=>this.loginViaPopup().catch(p=>Z.warn(p.message))})})})),{unmount(){f.unmount(),d.unmount(),l(),u()}}}renderFloatingMenu(t,n){let{customStyles:r,closestScrollSelector:o,appendOverlayTo:s,floatingMenuParent:i}=n,a=o&&W0(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,ms.createRoot)(l);return u.render((0,Le.jsx)(ls,{store:this.store,customStyles:r,children:(0,Le.jsx)(Zo,{broadcastEvents:this.broadcastEvents,children:(0,Le.jsx)($R,{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,ms.createRoot)(r);return o.render((0,Le.jsx)(ls,{store:this.store,customStyles:n,children:(0,Le.jsx)(Zo,{broadcastEvents:this.broadcastEvents,children:(0,Le.jsx)(zR,{})})})),{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}=n;this.widgetElement=t,this.configure({showImages:o,isEmbedded:s}),this.widgetRoot=(0,ms.createRoot)(t),this.widgetRoot.render((0,Le.jsx)(ls,{store:this.store,customStyles:r,children:(0,Le.jsx)(Zo,{broadcastEvents:this.broadcastEvents,children:(0,Le.jsx)(iA,{assistantOptions:n.assistantOptions,knowledgeAssistOptions:n.knowledgeAssist,onLogIn:()=>this.loginViaPopup().catch(i=>Z.warn(i.message))})})})),this.whenConversationLoaded(()=>{var i;this.broadcastEvents.setExternalId((i=this.state.conversation.current)==null?void 0:i.externalId)})}unmountWidget(){var t,n;(t=this.widgetRoot)==null||t.unmount(),this.widgetRoot=null,(n=this.widgetElement)==null||n.remove(),this.widgetElement=null}renderKnowledgeAssistantWidget(t,n,r={}){let{customStyles:o,initialQuestion:s}=r,i=(0,ms.createRoot)(n);return i.render((0,Le.jsx)(ls,{store:this.store,customStyles:o,children:(0,Le.jsx)(Zo,{broadcastEvents:this.broadcastEvents,children:(0,Le.jsx)(_0,{children:(0,Le.jsxs)(fm,{assistantCode:t,initialQuestion:s,evaluateKnowledgeAssistFn:r.isLegacyKnowledgeAssist?Ks:Gs,children:[(0,Le.jsx)(Ri,{children:(0,Le.jsx)(mm,{title:r.title,emptyState:r.emptyState})}),(0,Le.jsx)(N0,{children:(0,Le.jsx)(pm,{})})]})})})})),{unmount(){i.unmount()}}}setupHandlingTime(t){let n=bm(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){AA(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(()=>I(this,null,function*(){yield this.store.dispatch(Ec());let t=qs(this.state);t&&this.store.dispatch(yf({showSearch:t.search,showImageSearch:t.imageSearch,showEntitiesCommand:t.entitiesCommand,showSummaryCommand:!!t.summarizerAssistantNew,showKnowledgeSearch:!!t.knowledgeAssistantNew||!!t.knowledgeAssistant,recommendTextSuggestions:t.recommendTextSuggestions}))})),this.loadProfileConfigPromise)}loginViaPopup(t){return I(this,null,function*(){return new Promise((n,r)=>{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=>I(this,null,function*(){var v,g;if((v=p.data)!=null&&v.jwt)try{yield this.deepdeskApi.exchangeTokenForAccessCookie((g=p.data)==null?void 0:g.jwt),yield this.isLoggedIn(),this.broadcastEvents.send(tc),l=!0,o.port1.close(),n()}catch(x){console.error(x),r(x)}finally{l=!0,c()}});let u=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");u===null&&r(new Error("Popup blocked by browser"));let f=p=>I(this,null,function*(){var v;if(p.origin===a.origin)switch((v=p.data)==null?void 0:v.type){case"deepdesk-popup-loaded":{try{let g=JSON.stringify({type:"deepdesk-popup-create-channel"});u==null||u.postMessage(g,a.origin,[o.port2])}catch(g){Z.error("Error posting message to popup",g),r(g)}break}case"deepdesk-popup-error":{c(),p.data.message==="Timeout"&&Z.warn("Popup timed out. Check if the account's platform url is configured correctly."),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.unmountHandlers.push(c)})})}translateMessages(t){return this.deepdeskApi.translateMessages(t)}checkForTrialMode(t){return I(this,null,function*(){try{let{account:n}=yield this.deepdeskApi.getPlatformConfig();if(!n.isTrial){this.shouldRender=!0;return}if(Z.info("Trial is active"),!(yield this.deepdeskApi.checkUserExists(t)))throw new Error("User is not in trial");this.shouldRender=!0}catch(n){let{message:r}=n;Z.info(r),this.shouldRender=!1}})}refreshWidgetSuggestions(){return I(this,null,function*(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=Tc(this.state);try{n.forEach(({type:r})=>{r==="entities"?this.store.dispatch(fr()):Du.includes(r)||this.store.dispatch(gr(r))})}catch(r){this.handleError(r)}})}};Ka.version="17.1.5",Ka.count=0;var hu=Ka;function f5(e){return I(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 $A(e,t){return I(this,null,function*(){let n=yield f5(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 jA(e,t,n){return I(this,null,function*(){yield new Eo(e).authenticateWithKey(t,n)})}function WA(e){return e.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}function KA(r,o){return I(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 GA(r,o){return I(this,arguments,function*(e,t,n={}){let s=n.replace?fs(e,n.replace.start,n.replace.end):Va(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(`
83
83
  `).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?fs(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 p5(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 m5(e){let t=document.createDocumentFragment();return e.split(`
84
84
  `).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 qA(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):qA(n,t)}function YA(o,s){return I(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?p5(t):m5(t);n?qA(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 cI(g5);})();
85
85
  /*! Bundled license information:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deepdesk/deepdesk-sdk",
3
- "version": "17.1.4",
3
+ "version": "17.1.5",
4
4
  "description": "Deepdesk SDK",
5
5
  "author": "Lukas Batteau",
6
6
  "license": "ISC",