@deepdesk/deepdesk-sdk 11.0.1-beta.2 → 11.1.0

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.
@@ -23,7 +23,7 @@ Try polyfilling it using "@formatjs/intl-pluralrules"
23
23
  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 vh=w(b()),HO={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},ab=({className:e,color:t})=>(0,vh.jsx)("svg",{className:e,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:(0,vh.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:HO[t||"pink"]})});var lb={root:"j",text:"q",isLoggedIn:"Qe",isLoggedOut:"oo",icon:"Ve",logo:"We",lock:"Ze"};var Sh={};Je(Sh,{enUS:()=>jO,nlNL:()=>zO});var jO={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Search"}]},zO={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Zoeken"}]};var Fo=w(b()),cb=({onLogIn:e})=>{let t=G(Sh),n=U("floatingMenu"),r=U("productName"),o=Z(),i=O(nt),s=A("FloatingMenu",lb);if(i===null||n===!1)return null;let a=()=>{i===!0?o(Ct(!0)):e()};return(0,Fo.jsxs)("button",{className:(0,ub.default)(s.root,{[s.isLoggedIn]:i,[s.isLoggedOut]:!i}),onClick:a,children:[(0,Fo.jsx)("div",{className:s.text,children:t(i?"search":"signin",{productName:r})}),(0,Fo.jsxs)("div",{className:s.icon,children:[(0,Fo.jsx)(ab,{className:s.logo,color:"pink"}),i===!1&&(0,Fo.jsx)(sb,{className:s.lock})]})]})};var Ld=w(F());var db=w(F());function Zi(e){(0,db.useEffect)(()=>{let t=n=>{n.isWithinRoot||e(n)};return document.body.addEventListener("mouseup",t),()=>{document.body.removeEventListener("mouseup",t)}},[e])}function Ho(e){e.addEventListener("mouseup",t=>{t.isWithinRoot=!0},!0)}function Ji(e){let{showMidSentenceSuggestions:t,showSuggestionsBeforePattern:n,showSuggestionsAfterPattern:r}=e.settings,{text:o,selection:i}=e.input.userCommitted;return i.start!==i.end?!1:i.end>=o.length?!0:t?n&&new RegExp(n).test(o.substring(i.end))||r&&new RegExp(r).test(o.substring(0,i.end))?!0:n===!1&&r===!1:!1}var BO={showTabHint:!1,inputHasFocus:!1,overlayCollapsed:!1,openOverlayWhenTyping:!1,overlayCollapsedUserOverwrite:!1};var Rd=({ui:e})=>e.overlayCollapsed;var fb=q({name:"ui",initialState:BO,reducers:{setShowTabHint(e,t){e.showTabHint=t.payload},setInputHasFocus(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:Za,setInputHasFocus:wh,setOverlayCollapsed:Kr,setOpenOverlayWhenTyping:pb,setOverlayCollapsedUserOverwrite:mb}=fb.actions,gb=fb.reducer;var Ad=w(F());var es=w(F());var hb=w(F());function yb(e,t,n){(0,hb.useEffect)(()=>{let r=e.current;return r?(r.addEventListener(t,n),()=>{r.removeEventListener(t,n)}):()=>{}},[e,t,n])}var vb={root:"_e",actions:"oi",badge:"ei",formattedText:"eo"};var Uo=w(b()),$O=["search","personal-collection-search","search-autocomplete"];function WO(e,t,n,r={}){let o="";return $O.includes(t)?o=uC(ah(e,n,{stripAgentPart:!0}),r.searchKeywords??[n]):o=ah(e,n,r),r.placeholders===!0&&(o=cC(o)),o}var qO=()=>{},GO=({index:e,selected:t,suggestion:n,onFeedback:r})=>{let o=U("inlineSuggestions"),i=O(Vi),s=Z(),a=A("TextSuggestion",vb),l=(0,es.useRef)(null);(0,es.useEffect)(()=>{let c=setTimeout(()=>{s(iE({text:n.text,suggestion:n}))},500);return()=>{clearTimeout(c)}},[n]),yb(l,"click",()=>{s(Fr(e)),s(Cn({suggestion:n,text:n.text,eventMetrics:{inputType:"mouse"},replace:"until-selection-end"}))});let u=(0,es.useMemo)(()=>WO(n.text,n.source,i,{stripAgentPart:o,placeholders:!0,searchKeywords:n.searchKeywords}),[o,n.text,n.source,i,n.searchKeywords]);return n.source==="gpt"&&!o?null:(0,Uo.jsxs)("div",{className:a.root,onMouseEnter:()=>s(Fr(e)),children:[(0,Uo.jsx)(ae,{ref:l,as:"button","data-testid":"suggestions-overlay-item",selected:t,onClick:qO,children:(0,Uo.jsx)($i,{containerTagName:"div",noWrap:!1,tagName:"span",className:a.formattedText,content:u})}),t&&r&&(0,Uo.jsx)("div",{className:a.actions,children:(0,Uo.jsx)(wd,{onFeedback:()=>r(n),suggestion:n.text})})]})},Sb=GO;var xh=w(b()),YO=({onFeedback:e,suggestions:t,selectedIndex:n,reverse:r})=>{let o=(0,Ad.useMemo)(()=>{let i=t.map((s,a)=>(0,xh.jsx)(Sb,{index:a,selected:a===n,suggestion:s,onFeedback:e},`${s.text}-${s.source}`));return r?i.reverse():i},[t,n,r]);return(0,xh.jsx)(Ad.Fragment,{children:o})},Id=YO;var wb={root:"ii",paper:"ri"};var Ja=w(b()),QO=({textSuggestions:e,selectedIndex:t})=>{let n=(0,Ld.useRef)(null),r=A("InlineSuggestionsOverlay",wb),o=O(Ji),i=Z(),s=O(nt),a=O(Bi),l=O(Rd),u=U("showTextSuggestions");return Zi(()=>{setTimeout(()=>{i(Kr({collapse:!0,skipWhenInputFocus:!0}))})}),(0,Ld.useEffect)(()=>{let c=n.current;if(!c||!c.parentElement)return;c.parentElement.style.left="0px";let f=c.getBoundingClientRect();c.parentElement.style.left=`${Math.min(window.innerWidth-4-f.right,0)}px`}),l||!o||!u||e.length===0||s!==!0||a===!1?null:(0,Ja.jsx)("div",{className:r.root,"data-variant":"inline",children:(0,Ja.jsx)("div",{ref:n,className:r.paper,children:(0,Ja.jsx)(vt,{children:(0,Ja.jsx)(Id,{suggestions:e,selectedIndex:t})})})})},ZO=({input:e})=>({selectedIndex:e.selectedSuggestionIndex,textSuggestions:e.textSuggestions}),xb=zn(ZO)(QO);var el=w(b()),JO=({children:e})=>{let n=U("locale").replace("-","");return(0,el.jsx)(Wg.Provider,{value:n,children:e})},eN=({store:e,customStyles:t={},children:n})=>(0,el.jsx)(bg,{store:e,children:(0,el.jsx)(JO,{children:(0,el.jsx)(gs.Provider,{value:t,children:n})})}),jo=eN;var Nd=w(ee()),ts=w(F());var Eb=w(F());function Cb(e,t){let[n,r]=(0,Eb.useState)(()=>{if(typeof window>"u")return t;try{let i=window.localStorage.getItem(e);return i?JSON.parse(i):t}catch(i){return V.error(i),t}});return[n,i=>{try{let s=i instanceof Function?i(n):i;r(s),typeof window<"u"&&window.localStorage.setItem(e,JSON.stringify(s))}catch(s){V.error(s)}}]}var bb=()=>/Mac/i.test(navigator.platform);var kb=w(ee()),Qn=w(F());var Eh={};Je(Eh,{enUS:()=>tN,nlNL:()=>nN});var tN={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"}]}]},nN={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 Tb={root:"ti",anchor:"ni",anchorButton:"ai"};var $r=w(b()),Ch=(e,t,n)=>r=>(0,$r.jsx)("button",{className:e.anchorButton,type:"button",value:t,onClick:n,children:r},t),oN=({className:e,loginUrl:t,isEmbedded:n,onSnooze:r,onLogIn:o})=>{let i=G(Eh),s=en(),a=A("Login",Tb),l=U("productName"),u=(0,Qn.useCallback)(g=>{g.preventDefault(),r&&r(parseInt(g.target.value,10))},[]),c=(0,Qn.useCallback)(g=>{g.preventDefault(),s.send(Ki,!0)},[t]),f=(0,Qn.useMemo)(()=>g=>(0,$r.jsx)("a",{onClick:h=>{h.preventDefault(),o()},href:t,className:a.anchor,target:"_blank",rel:"noreferrer",children:g},"login"),[t]),d=(0,Qn.useCallback)(g=>(0,$r.jsx)("button",{type:"button",className:a.anchorButton,onClick:c,children:g},"prompt"),[c]),{min:p,hour:y,day:v}=(0,Qn.useMemo)(()=>({min:Ch(a,60*10,u),hour:Ch(a,60*60,u),day:Ch(a,60*60*12,u)}),[]);return(0,$r.jsxs)("div",{className:(0,kb.default)(e,a.root),children:[i("loginPlease",{login:n?d:f,productName:l}),r&&(0,$r.jsxs)(Qn.Fragment,{children:[(0,$r.jsx)("br",{}),i("snooze",{min:p,hour:y,day:v})]})]})},Od=oN;var Pb={root:"io",text:"di"};var tl=w(b()),sN=({title:e})=>{let t=A("SearchTrigger",Pb),n=Z();return(0,tl.jsxs)("button",{type:"button",className:t.root,onClick:()=>n(Ct(!0)),children:[(0,tl.jsx)(qi,{}),(0,tl.jsx)("span",{className:t.text,children:e})]})},Rb=sN;var bh={};Je(bh,{enUS:()=>aN,nlNL:()=>lN});var aN={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"}]},lN={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 Ab={root:"pi",isInline:"C",toggleButton:"li",toggleButtonWrapper:"S",toggleButtonWrapperHidden:"si",isCollapsed:"ro",collapsible:"xi",hints:"to",hintsHidden:"ci",triggers:"no",triggersRight:"fi"};var we=w(b()),cN=({textSuggestions:e,selectedIndex:t,onLogIn:n})=>{let r=A("SuggestionsOverlay",Ab),o=G(bh),i=O(Ji),s=tE(),a=Z(),l=(0,ts.useRef)(null),u=U("searchTriggerKey"),c=U("productName"),f=O(Rd),d=O(nt),p=O(Bi),[y,v]=(0,ts.useState)(null),g=U("showSearch"),m=U("showTextSuggestions"),h=U("adminUrl"),S=U("isEmbedded"),[x,C]=Cb("dd-snooze-until-ms",0),T=f||x>Date.now(),k=O(K=>K.input.text),I=e.filter(K=>K.source!=="gpt").length,L=()=>{T&&C(0),a(mb(!T))},N=K=>{a(Qe({name:"suggestion feedback",data:{text:K.text,source:"overlay",context:k},options:{includeConversationData:!0}}))},z=K=>{let J=Date.now()+K*1e3;C(J),V.info(`Snooze until: ${new Date(J)}`),a(Kr({collapse:!0}))};return(0,ts.useEffect)(()=>{I===0&&v(null)},[e,I]),Zi(()=>{a(Kr({collapse:!0,skipWhenInputFocus:!0}))}),d===null||p===!1?null:d===!1?(0,we.jsxs)("div",{ref:l,className:(0,Nd.default)(r.root,{[r.isCollapsed]:T}),children:[!T&&(0,we.jsxs)("div",{className:r.triggers,children:[(0,we.jsx)("div",{style:{flex:1}}),(0,we.jsx)("div",{className:r.triggersRight,children:(0,we.jsx)(oo,{className:r.toggleButton,title:o("collapse"),onClick:L,isCollapsed:!1})})]}),(0,we.jsx)("div",{className:r.toggleButtonWrapper,children:(0,we.jsx)(oo,{className:r.toggleButton,title:o("open",{productName:c}),onClick:L,isCollapsed:!0})}),(0,we.jsx)("div",{className:r.collapsible,children:(0,we.jsx)(Od,{loginUrl:h,isEmbedded:S,onLogIn:n,onSnooze:z})})]}):!s||!i?null:(0,we.jsxs)("div",{ref:l,className:(0,Nd.default)(r.root,{[r.isCollapsed]:T}),children:[!T&&(0,we.jsxs)("div",{className:r.triggers,children:[(0,we.jsx)("div",{style:{flex:1},children:g&&(0,we.jsx)("div",{style:{display:"inline-block"},onFocus:()=>{},onMouseOver:()=>v(o(bb()?"searchHintMac":"searchHintWindows",{searchTriggerKey:u.toUpperCase()})),onMouseLeave:()=>v(null),children:(0,we.jsx)(Rb,{title:o("search")})})}),(0,we.jsxs)("div",{className:r.triggersRight,onFocus:()=>{},children:[(0,we.jsx)("div",{className:(0,Nd.default)(!y&&r.hintsHidden,r.hints),children:y}),(0,we.jsx)(oo,{className:r.toggleButton,title:o("collapse"),onClick:L,isCollapsed:!1})]})]}),(0,we.jsx)("div",{className:r.toggleButtonWrapper,children:(0,we.jsx)(oo,{className:r.toggleButton,title:o("open",{productName:c}),onClick:L,isCollapsed:!0})}),I>0&&m&&(0,we.jsx)("div",{className:r.collapsible,onFocus:()=>{},children:(0,we.jsx)(vt,{children:(0,we.jsx)(Id,{onFeedback:N,suggestions:e,selectedIndex:t,reverse:!0})})})]})},dN=({input:e})=>({selectedIndex:e.selectedSuggestionIndex,textSuggestions:e.textSuggestions}),Ib=zn(dN)(cN);var Gd=w(ee());var er=w(F());var ns=w(F());function Md(e){return e.contentEditable==="true"}function fN(e){let t=0,n=0,r=window.getSelection();if(r.rangeCount!==0){let o=r.getRangeAt(0),i=o.cloneRange();i.selectNodeContents(e),i.setEnd(o.endContainer,o.endOffset),n=i.toString().length,i.selectNodeContents(e),i.setEnd(o.startContainer,o.startOffset),t=i.toString().length}return{selectionStart:t,selectionEnd:n}}function Lb(e){let{selectionStart:t,selectionEnd:n}=Md(e)?fN(e):e;return[t,n]}function Ob(e){let[,t]=(0,ns.useState)(),n=(0,ns.useRef)(null);return n.current=Lb(e),(0,ns.useEffect)(()=>{let r=()=>{let[o,i]=n.current??[],s=Lb(e);(!s||o!==s[0]||i!==s[1])&&(n.current=s,t({}))};return e.addEventListener("keyup",r),e.addEventListener("click",r),e.addEventListener("focus",r),document.addEventListener("selectionchange",r),()=>{e.removeEventListener("keyup",r),e.removeEventListener("click",r),e.removeEventListener("focus",r),document.removeEventListener("selectionchange",r)}},[e]),n.current}function Nb(e,t){if(!t)return;let n=e,{value:r}=n,[o,i]=t,s=r.match(Fl);if(!s||s.length===0)return;let a=0;s.find(l=>{let u=r.indexOf(l,a);return o>u&&i<u+l.length?(n.selectionStart=u,n.selectionEnd=u+l.length,!0):(a=u+l.length,!1)})}var Mb=w(F()),pN=["div","span","mark","strong","b","i","u","em"];function Th(e,t,n=0){var i;let r=e[e.length-1],o=typeof r=="object"&&r!==null?(i=r.props)==null?void 0:i.tagName:void 0;if(o==="br")return e.pop(),[...e,...t,r];if(pN.includes(o)){let s=Array.isArray(r.props.children)?r.props.children:[r.props.children];return[...e.slice(0,e.length-1),(0,Mb.cloneElement)(r,{children:Th(s,t,n+1)})]}return[...e,...t]}function Wr(e){return e.tagName.toLowerCase()==="textarea"}var un={root:"gi",container:"bi",agentText:"ao",tabText:"do",hint:"E",matchSelection:"po",focus:"hi",resetIndent:"mi",matchKeyword:"d",matchPlaceholder:"p",hover:"lo",hintText:"ui",popover:"yi",popoverRoot:"wi",popoverContentContainer:"so",popoverContent:"vi",selectionOptions:"ki",selectionOptionsIsHidden:"zi",selectionOptionsButton:"ji",caret:"qi",popoverSuggestionsRoot:"Ci",suggestionsOverlayInputStyles:"Si"};var Kb=w(ee());var Vd=w(F());var rs=w(F());function _b(e,t){let n;return[(...r)=>{window.cancelAnimationFrame(n);let o=t?t(...r):r;n=window.requestAnimationFrame(()=>{e(...o)})},()=>window.cancelAnimationFrame(n)]}function _d(e){let t=(0,rs.useRef)(null),[n,r]=(0,rs.useState)(!1);return(0,rs.useEffect)(()=>{let o=!1,i=parseFloat(window.getComputedStyle(document.body).zoom??"1"),[s,a]=_b((c,f)=>{let d=t.current;if(!d)return;let p=c/i,y=f/i,v=d.getBoundingClientRect(),g=p>v.x&&p<v.x+v.width&&y>v.y&&y<v.y+v.height;g&&!o?(o=!0,r(!0)):!g&&o&&(o=!1,r(!1))},({clientX:c,clientY:f})=>[c,f]),[l,u]=_b(()=>{o=!1,r(!1)});return e.addEventListener("mousemove",s),e.addEventListener("mouseleave",l),()=>{a(),u(),e.removeEventListener("mousemove",s),e.removeEventListener("mouseleave",l)}},[t]),[t,n]}function Db(e){return e.replace(/[.*+^${}()|[\]\\]/g,"\\$&")}function Dd(e){return t=>{e.forEach(n=>{typeof n=="function"?n(t):n!=null&&(n.current=t)})}}function Fb(e){return e!=null}var Ph=w(ee()),Vt=w(F());var Fd=w(F()),gN=["bottom","height","left","right","top","width"],hN=(e={},t={})=>gN.some(n=>e[n]!==t[n]),Zn=new Map,Hb,Ub=()=>{let e=[],t=[];Zn.forEach((n,r)=>{if(r instanceof Element&&!r.isConnected){t.push(r);return}let o=r.getBoundingClientRect();hN(o,n.rect)&&(n.rect=o,e.push(n))}),t.forEach(n=>{Zn.delete(n)}),e.forEach(n=>{n.callbacks.forEach(r=>r(n.rect))}),Hb=window.requestAnimationFrame(Ub)};function yN(e,t){return{observe(){let n=Zn.size===0;if(Zn.has(e)){let r=Zn.get(e);r.callbacks.push(t),r.rect&&t(r.rect)}else Zn.set(e,{rect:void 0,hasRectChanged:!1,callbacks:[t]});n&&Ub()},unobserve(){let n=Zn.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||Zn.delete(e),Zn.size||cancelAnimationFrame(Hb)}}}}function kh(e){let[t,n]=(0,Fd.useState)(null);return(0,Fd.useLayoutEffect)(()=>{if(!e.current)return;let r=yN(e.current,o=>{n(o)});return r.observe(),()=>{r.unobserve()}},[e]),t}var os=w(F()),zb=w(Xu());var jb={root:"Ei"};var Bb=({children:e,parentNode:t})=>{let[n,r]=(0,os.useState)(null),o=(0,os.useContext)(gs);return(0,os.useLayoutEffect)(()=>{let i=document.createElement("div");return Ho(i),i.classList.add(jb.root),o!=null&&o.portalRootNode&&i.classList.add(o==null?void 0:o.portalRootNode),(t||document.body).appendChild(i),r(i),()=>{i.isConnected&&i.remove()}},[]),n?(0,zb.createPortal)(e,n):null};var bn={ref:"Gi",root:"o",positionAbove:"l",positionBelow:"s",positionLeft:"x",positionRight:"c",alignStart:"f",alignCenter:"g",alignEnd:"b"};var Hd=w(b()),Ud=(e=!1)=>{let[t,n]=(0,Vt.useState)(e),r=(0,Vt.useCallback)(()=>n(!0),[]),o=(0,Vt.useCallback)(()=>n(!1),[]),i=(0,Vt.useCallback)(()=>n(a=>!a),[]),s=(0,Vt.useRef)(null);return{opened:t,open:r,close:o,toggle:i,triggerRef:s}};function Rh(e,t=null,n=0){if(!e)return{display:"none"};let r=t?e.top-t.top<0||e.top<t.top-n?t.top-n:e.top+e.height>t.top+t.height+n?t.top+t.height+n-e.height:e.top:e.top,o=t?e.left<t.left-n?t.left-n:e.left+e.width>t.left+t.width+n?t.left+t.width+n-e.width:e.left:e.left;return{top:r,left:o,height:e.height,width:e.width}}var is=({className:e,triggerRef:t,boundaryRef:n=(0,Vt.createRef)(),position:r="above",align:o="center",children:i,toStyle:s=Rh,parentNode:a,...l})=>{let u=kh(t),c=kh(n),f=(0,Vt.useMemo)(()=>s(u,c,0),[u,c]);return(0,Hd.jsx)(Bb,{parentNode:a,children:(0,Hd.jsx)("div",{className:(0,Ph.default)(bn.ref,{[bn.positionAbove]:r==="above",[bn.positionBelow]:r==="below",[bn.positionLeft]:r==="left",[bn.positionRight]:r==="right",[bn.alignStart]:o==="start",[bn.alignCenter]:o==="center",[bn.alignEnd]:o==="end"}),style:f,...l,role:"dialog",children:(0,Hd.jsx)("div",{className:(0,Ph.default)(e,bn.root),children:i})})})};var Vb=w(ee()),jd=w(F());var Ah=w(b()),zd=(0,jd.forwardRef)(({className:e,children:t,...n},r)=>{let o=(0,jd.useRef)(null),i=A("TabCompletion",un);return(0,Ah.jsx)("div",{ref:Dd([o,r]),className:(0,Vb.default)(e,i.popoverContentContainer),...n,children:(0,Ah.jsx)("div",{className:i.popoverContent,children:t})})});var qr=w(b()),wN=e=>t=>{let n=Rh(t);return"top"in n&&(n.width=e.width-(t.left-e.left)-10),n},xN=({inputElement:e,boundaryRef:t,inputStyle:n,children:r,suggestion:o})=>{let i=A("TabCompletion",un),s=Ud(),a=(0,Vd.useMemo)(()=>wN(e.getBoundingClientRect()),[e]),[l,u]=_d(e);return(0,Vd.useEffect)(()=>{u?s.open():s.close()},[u]),(0,qr.jsxs)("span",{children:[(0,qr.jsx)("mark",{ref:Dd([l,s.triggerRef]),className:(0,Kb.default)(i.matchKeyword,{[i.hover]:u}),"aria-haspopup":"dialog","aria-expanded":s.opened?"true":"false",children:r}),s.opened&&(0,qr.jsx)(is,{className:i.popover,triggerRef:s.triggerRef,boundaryRef:t,position:"below",align:"start",toStyle:a,children:(0,qr.jsx)(zd,{style:n,children:(0,qr.jsx)("div",{className:i.hintText,children:o})})})]})},Bd=class extends Wn{keywordMatches=[];preparedKeywordMatches=[];usedKeywordMatches=new Set;onBeforeParse(t,n){return n.keywordMatches&&n.keywordMatches!==this.keywordMatches&&(this.preparedKeywordMatches=n.keywordMatches.map(r=>({...r,keywordRegex:new RegExp(`\\b${Db(r.keyword)}\\b`,"i")})),this.keywordMatches=n.keywordMatches),this.usedKeywordMatches.clear(),t}match(t){let n=this.preparedKeywordMatches.map(o=>{if(this.usedKeywordMatches.has(o))return null;let i=t.match(o.keywordRegex);if(!i)return null;let s=t.charAt(i.index-1),a=t.charAt(i.index+o.keyword.length);return s==="{"&&a==="}"?null:{index:i.index,length:i[0].length,match:i[0],matchString:i[0],suggestion:o.suggestion,preparedKeywordMatch:o,valid:!0}}).filter(Fb);if(n.length===0)return null;let r=n.reduce((o,i)=>i.index<o.index?i:o);return this.usedKeywordMatches.add(r.preparedKeywordMatch),r}replaceWith(t,n){return(0,qr.jsx)(xN,{inputElement:n.inputElement,suggestion:n.suggestion,inputStyle:n.inputStyle,boundaryRef:n.boundaryRef,children:t},`keyword_${n.matchString}_${n.key}`)}asTag(){return"mark"}};var $b=w(ee());var Ih=w(b()),EN=({inputElement:e,children:t})=>{let n=A("TabCompletion",un),[r,o]=_d(e);return(0,Ih.jsx)("mark",{ref:r,className:(0,$b.default)(n.matchPlaceholder,{[n.hover]:o}),children:t})},Kd=class extends Wn{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,Ih.jsx)(EN,{inputElement:n.inputElement,children:t},`placeholder_${n.matchString}_${n.key}`)}asTag(){return"mark"}};var Wd=w(ee());var ot=w(F());var Lh=w(b()),Wb=()=>(0,Lh.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,Lh.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 Gr=w(F());var Gb=w(Qg());var qb={root:"Ni",content:"Yi"};function $d(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{return null}}function Oh(e){return e.replace("https://www.","").replace("https://","")}var Kt=w(b()),bN=3,TN=e=>({image:e.image||"",text:e.text,id:e.id,title:e.title}),kN=({onSelectLink:e,onDismiss:t,placeholder:n,visitUrlText:r,linkCount:o=bN})=>{let i=A("LinkSearch",qb),[s,a]=(0,Gr.useState)(""),l=Z(),u=O(GC("url")),c=O(EE("URL",TN)),[f,d]=(0,Gr.useState)(c.length-1),p=U("fallbackImage"),y=h=>{let S=h.target;a(S.value)},v=(h,S)=>{h.stopPropagation(),h.preventDefault(),window.open(S,"_blank")},g=h=>{var C;let S=f-1<0?c.length-1:f-1,x=f+1===c.length?0:f+1;h.code==="Escape"&&(a(""),t()),h.code==="ArrowUp"&&d(S),h.code==="ArrowDown"&&d(x),h.code==="Enter"&&e(((C=c[f])==null?void 0:C.text)||s)},m=(0,Gr.useCallback)((0,Gb.default)(h=>{l(bo({query:h,type:"URL",tags:["link-search"]}))},300),[]);return(0,Gr.useEffect)(()=>{s&&m(s)},[s]),(0,Gr.useEffect)(()=>()=>{l(Wc())},[]),(0,Kt.jsxs)("div",{className:i.root,children:[(0,Kt.jsx)(vt,{withDivider:!0,children:(s?c:u).slice(0,o).map((h,S)=>(0,Kt.jsx)(ae,{selected:f===S,onClick:()=>e(h.text),"data-testid":"linksearch-suggestion",children:(0,Kt.jsxs)(pe,{children:[(0,Kt.jsx)(pe.Image,{src:$d(h,"small",p||void 0),title:h.title||h.text}),(0,Kt.jsxs)(pe.Content,{className:i.content,cropText:!0,children:[(0,Kt.jsx)(pe.Title,{children:h.title||Oh(h.text)}),h.title&&Oh(h.text)]}),(0,Kt.jsx)(ae.Actions,{children:(0,Kt.jsx)(ae.ActionButton,{label:r,onClick:x=>v(x,h.text)})})]})},h.text))}),(0,Kt.jsx)(_a,{value:s,onChange:y,autoFocus:!0,placeholder:n,onKeyUp:g})]})},Yb=kN;var Nh={};Je(Nh,{enUS:()=>PN,nlNL:()=>RN});var PN={insertLink:[{type:0,value:"Insert link"}],linkInputPlaceholder:[{type:0,value:"Search, type or paste link"}],visitUrl:[{type:0,value:"Visit"}]},RN={insertLink:[{type:0,value:"Voeg link toe"}],linkInputPlaceholder:[{type:0,value:"Zoek, typ of plak link"}],visitUrl:[{type:0,value:"Bekijk"}]};var rt=w(b()),AN=(0,ot.forwardRef)((e,t)=>{let n=A("TabCompletion",un);return(0,rt.jsx)("mark",{ref:t,className:(0,Wd.default)(n.matchSelection)},"selection-start")}),IN=({startRef:e,boundaryRef:t,inputStyle:n,inputElement:r,children:o})=>{let i=G(Nh),s=A("TabCompletion",un),a=(0,ot.useRef)(null),l=(0,ot.useRef)(null),[u,c]=(0,ot.useState)(null),f=Z(),d=Ud(document.activeElement===r),[p]=(0,ot.useState)(()=>document.createRange());d.triggerRef.current=p,(0,ot.useEffect)(()=>()=>p.detach(),[]),(0,ot.useEffect)(()=>{let v=e.current,g=a.current;!v||!g||(p.setStart(v,0),p.setEnd(g,0))},[e.current,a.current]),Zi(()=>{d.close()});let y=(0,ot.useCallback)(v=>{let g=p.toString(),m=/^http(s?):\/\//.test(v)?v:`https://${v}`;f(zc({text:`[${g}](${m})`,replace:"selection"}))},[]);return(0,rt.jsxs)("span",{children:[(0,rt.jsx)("mark",{ref:a,className:(0,Wd.default)(s.matchSelection),"aria-haspopup":"dialog","aria-expanded":d.opened?"true":"false",children:o}),d.opened&&(0,rt.jsx)(is,{className:s.popoverRoot,triggerRef:d.triggerRef,boundaryRef:t,position:"above",align:"start",children:(0,rt.jsxs)(zd,{style:n,ref:l,children:[(0,rt.jsx)("div",{className:(0,Wd.default)(s.selectionOptions,{[s.selectionOptionsIsHidden]:u!==null}),children:(0,rt.jsxs)("button",{type:"button",tabIndex:u===null?-1:void 0,className:s.selectionOptionsButton,onClick:()=>c("insertLink"),children:[(0,rt.jsx)(Wb,{}),(0,rt.jsx)("span",{children:"\xA0"}),(0,rt.jsx)("span",{children:i("insertLink")})]})}),u==="insertLink"&&(0,rt.jsx)(Yb,{placeholder:i("linkInputPlaceholder"),visitUrlText:i("visitUrl"),onSelectLink:y,onDismiss:()=>{c(null),d.close()}})]})})]},"selection-end")},qd=class extends Wn{charCount=0;foundIndex=0;startRef=null;props;onBeforeParse(t,n){return this.props=n,this.charCount=0,this.startRef=(0,ot.createRef)(),this.foundIndex=0,t}match(t){if(!this.props||this.props.selection===null||this.foundIndex===2)return null;let[n,r]=this.props.selection;if(n===r)return null;let o=this.foundIndex===0?n:r,i=o>=this.charCount&&o<=this.charCount+t.length?{index:o-this.charCount,length:0,match:"",valid:!0}:null;i&&this.foundIndex++;let s=this.foundIndex===1;return i&&s?this.charCount+=o-this.charCount:this.charCount+=t.length,i?{isStart:s,...i}:null}replaceWith(t,n){return n.isStart?(0,rt.jsx)(AN,{ref:this.startRef}):(0,rt.jsx)(IN,{inputElement:n.inputElement,startRef:this.startRef,boundaryRef:n.boundaryRef,inputStyle:n.inputStyle})}asTag(){return"mark"}};var Jn=w(b()),LN=({enabled:e,content:t,tabText:n,showTabHint:r,showTabCompletion:o,showStyleSuggestions:i,keywordMatches:s,inputElement:a,source:l})=>{let u=A("TabCompletion",un),c=U("insertLink"),f=U("showMidSentenceSuggestions"),d=U("inlineSuggestions"),p=Ob(a),y=(0,er.useRef)(null),v=O(nt);(0,er.useEffect)(()=>{Wr(a)&&p&&Nb(a,p)},[p]);let g=(0,er.useCallback)(S=>{if(!o||!n)return S;let x=[(0,Jn.jsx)("span",{className:u.resetIndent,children:"\u200B"},"u200B"),(0,Jn.jsx)("span",{"data-testid":"tab-completion",className:(0,Gd.default)(u.tabText,u.resetIndent),"data-source":l,children:n},"tabText")];return r&&x.push((0,Jn.jsx)("span",{className:(0,Gd.default)(u.hint,u.resetIndent),children:(0,Jn.jsx)(Nl,{keyCode:"tab"},"tabHint")})),Th(S,x)},[o,n,r]),m=(0,er.useMemo)(()=>{let S=[];return c&&S.push(new qd("selection")),S.push(new Kd("placeholders")),i&&S.push(new Bd("keywords")),S},[d,c,i]),h=(0,er.useMemo)(()=>{let S=window.getComputedStyle(a);return{"--dd-color":S.color,"--dd-font-size":S.fontSize,"--dd-font-family":S.fontFamily,"--dd-font-variant":S.fontVariant}},[]);return!e||!v?null:(0,Jn.jsxs)("div",{ref:S=>{S!=null&&S.parentElement&&(y.current=S==null?void 0:S.parentElement)},className:u.root,style:h,children:[(0,Jn.jsx)($i,{tagName:"span",containerTagName:"div",className:(0,Gd.default)(u.container,u.agentText),disableLineBreaks:Wr(a),content:t||"\u200B",onAfterParse:g,matchers:m,selection:p,keywordMatches:s,inputElement:a,inputStyle:h,boundaryRef:y,inlineSuggestionsOnlyAtEnd:!f}),(0,Jn.jsx)("br",{})]})},ON=({input:e,ui:t,settings:n,styleSuggestions:r,conversation:o})=>{var v;let{tabCompletionSuggestion:i}=e,s=(i==null?void 0:i.text)||"",a=(i==null?void 0:i.source)||"",l=e.html??Wi(e.text),u=s.indexOf(e.text)===0?s.slice(e.text.length):"",{showTabHint:c}=t,{isSupported:f}=o,{showTabCompletion:d,visible:p,showStyleSuggestions:y}=n;return{showTabHint:c,showStyleSuggestions:y,showTabCompletion:d,content:l,tabText:u,source:a,keywordMatches:((v=r.list)==null?void 0:v.keywordMatches)??[],enabled:p&&f!==!1}},Xb=zn(ON)(LN);var r1=w(ee()),o1=w(F());var Qb={list:[],fetchState:"idle",isInitialRequest:null},Jb=e=>e.autoflows.list||[],Zb=e=>t=>{var n;return(n=t.list)==null?void 0:n.find(r=>r.triggerPayload===e)},tr=j("autoflows/getAll",async(e,t)=>{let{deepdeskBrokerAPI:n}=t.extra;if(!n)throw new Error("Deepdesk Broker not initialized");return n.getAutoflows(e)}),Mh=j("autoflows/start",async(e,t)=>{let{dispatch:n}=t,{deepdeskBrokerAPI:r}=t.extra;if(!r)throw new Error("Deepdesk Broker not initialized");await r.startAutoflowSession(e),await n(tr(e.platformSessionId))}),_h=j("autoflows/stop",async(e,t)=>{let{dispatch:n}=t,{deepdeskBrokerAPI:r}=t.extra;if(!r)throw new Error("Deepdesk Broker not initialized");await r.stopAutoflowSession(e.platformSessionId),await n(tr(e.platformSessionId))}),NN=q({name:"autoflows",initialState:Qb,reducers:{},extraReducers:e=>{e.addCase(Mh.pending,(t,n)=>{let r=Zb(n.meta.arg.triggerPayload)(t);r.state="Started",r.isBusy=!0}),e.addCase(_h.pending,(t,n)=>{let r=Zb(n.meta.arg.triggerPayload)(t);r.state="Aborted",r.isBusy=!0}),e.addCase(tr.pending,t=>{t.isInitialRequest=t.isInitialRequest===null,t.fetchState="loading"}),e.addCase(tr.rejected,t=>{t.fetchState="error"}),e.addCase(tr.fulfilled,(t,n)=>{t.list=n.payload,t.fetchState="done"}),e.addCase(ue,()=>Qb)}}),eT=j("autoflows/openStream",(e,t)=>{let{dispatch:n}=t,{deepdeskBrokerAPI:r}=t.extra;if(!r)throw new Error("Deepdesk Broker not initialized");let o=r.openStream(e);o.on("sessionAborted",()=>{n(tr(e))}),o.on("sessionCompleted",()=>{n(tr(e))})}),tT=j("autoflows/closeStream",(e,t)=>{let{deepdeskBrokerAPI:n}=t.extra;if(!n)throw new Error("Deepdesk Broker not initialized");n.closeStream(e)}),nT=NN.reducer;var rT={list:[],fetchState:"idle",isInitialRequest:null,sentSuggestions:[],errorSuggestions:[],answeredSuggestions:[]},oT=e=>e.customMessages.list,iT=e=>t=>!!t.customMessages.sentSuggestions.find(n=>n===e),sT=e=>t=>!!t.customMessages.answeredSuggestions.find(n=>n===e),aT=e=>t=>!!t.customMessages.errorSuggestions.find(n=>n===e),nl=j("customMessages/getAll",async(e,t)=>{let{deepdeskBrokerAPI:n}=t.extra;if(!n)throw new Error("Deepdesk Broker not initialized");return n.getCustomMessages(e)}),Yd=j("customMessages/send",async(e,t)=>{let{platformSessionId:n,suggestion:r}=e,{deepdeskBrokerAPI:o}=t.extra;if(!o)throw new Error("Deepdesk Broker not initialized");await o.sendCustomMessage(n,r)}),Xd=j("customMessages/answer",async(e,t)=>{let{platformSessionId:n,reply:r}=e,{deepdeskBrokerAPI:o}=t.extra;if(!o)throw new Error("Deepdesk Broker not initialized");await o.answerCustomMessage(n,r)}),lT=q({name:"customMessages",initialState:rT,reducers:{onCustomMessage(e,t){Array.isArray(t.payload)?e.list=t.payload:e.list=[t.payload]}},extraReducers:e=>{e.addCase(nl.pending,t=>{t.isInitialRequest=t.isInitialRequest===null,t.fetchState="loading"}).addCase(nl.rejected,t=>{t.fetchState="error"}).addCase(nl.fulfilled,(t,n)=>{t.fetchState="done",t.list=n.payload||[]}).addCase(Yd.pending,(t,n)=>{t.sentSuggestions.push(n.meta.arg.suggestion.text),t.errorSuggestions=t.errorSuggestions.filter(r=>n.meta.arg.suggestion.text!==r)}).addCase(Yd.rejected,(t,n)=>{let r=t.sentSuggestions.indexOf(n.meta.arg.suggestion.text);t.errorSuggestions.push(...t.sentSuggestions.splice(r,1))}).addCase(Xd.pending,(t,n)=>{t.sentSuggestions.push(n.meta.arg.suggestion.text),t.answeredSuggestions.push(n.meta.arg.suggestion.text)}).addCase(Xd.rejected,(t,n)=>{let r=t.answeredSuggestions.indexOf(n.meta.arg.suggestion.text);t.errorSuggestions.push(...t.sentSuggestions.splice(r,1)),t.answeredSuggestions.splice(r,1)}).addCase(ue,()=>rT)}}),uT=j("customMessages/openStream",(e,t)=>{let{dispatch:n}=t,{deepdeskBrokerAPI:r}=t.extra;if(!r)throw new Error("Deepdesk Broker not initialized");r.openStream(e).on("customMessageSuggestion",i=>{n(lT.actions.onCustomMessage(i))})}),cT=j("customMessages/closeStream",(e,t)=>{let{deepdeskBrokerAPI:n}=t.extra;if(!n)throw new Error("Deepdesk Broker not initialized");n.closeStream(e)}),dT=lT.reducer;var MN={token:null,accountUrl:null,interval:null},fT=e=>t=>{let{passwordlessToken:{token:n,accountUrl:r}}=t;return n&&r?`${r}/apis/admin/session/passwordless/login/?token=${n}&redirect=${e}`:null},Dh=j("passwordlessToken/getTemporaryPasswordlessToken",async(e,t)=>{let{deepdeskAPI:n}=t.extra,r=await n.requestPasswordlessToken();return{accountUrl:n.client.baseUrl,token:r}}),Fh=j("passwordlessToken/pollPasswordlessToken",(e={},t)=>{let{interval:n=1e3*60*10}=e,{dispatch:r}=t;return r(Dh()),setInterval(()=>r(Dh()),n)}),pT=q({name:"passwordlessToken",initialState:MN,reducers:{stopPollPasswordlessToken(e){e.interval&&clearInterval(e.interval),e.interval=null}},extraReducers:e=>{e.addCase(Dh.fulfilled,(t,n)=>{t.token=n.payload.token,t.accountUrl=n.payload.accountUrl}),e.addCase(Fh.fulfilled,(t,n)=>{t.interval=n.payload})}}),{stopPollPasswordlessToken:mT}=pT.actions,gT=pT.reducer;function hT(e){let{customMessages:t,autoflows:n}=e;return n.fetchState==="loading"&&n.isInitialRequest===!0||t.fetchState==="loading"&&t.isInitialRequest===!0}var TT=w(F());var ET=w(ee()),CT=w(F());var vT=w(ee());var yT={root:"Ai"};var wT=w(b()),DN=({className:e,children:t})=>{let n=A("Unicode",yT);return(0,wT.jsx)("span",{className:(0,vT.default)(e,n.root),children:t})},ST=DN;var xT={isDisabled:"Fi",buttonStart:"Hi",root:"Li",buttonStop:"xo",stateBadge:"h",isCompleted:"Mi",isStarted:"Ri",isAborted:"Ti"};var Hh={};Je(Hh,{enUS:()=>HN,nlNL:()=>UN});var HN={start:[{type:0,value:"Start"}],stop:[{type:0,value:"Stop"}],aborted:[{type:0,value:"Stopped"}],completed:[{type:0,value:"Completed"}],Aborted:[{type:0,value:"Stopped"}],Started:[{type:0,value:"Running"}],Completed:[{type:0,value:"Completed"}]},UN={start:[{type:0,value:"Start"}],stop:[{type:0,value:"Stop"}],aborted:[{type:0,value:"Stopped"}],completed:[{type:0,value:"Completed"}],Aborted:[{type:0,value:"Stopped"}],Started:[{type:0,value:"Running"}],Completed:[{type:0,value:"Completed"}]};var Pt=w(b()),zN=({disabled:e,state:t,displayName:n,description:r,onStartAutoflow:o,onStopAutoflow:i})=>{let s=A("Autoflow",xT),a=G(Hh),l=t==="Started"?"stop":"start",u=l==="start"?"\u25B6":l==="stop"?"\u25FC":"";return(0,Pt.jsxs)(ae,{className:(0,ET.default)(s.root,{[s.isDisabled]:e,[s.isCompleted]:t==="Completed",[s.isAborted]:t==="Aborted",[s.isStarted]:t==="Started"}),children:[(0,Pt.jsx)(pe,{children:(0,Pt.jsxs)(pe.Content,{children:[(0,Pt.jsxs)(pe.Title,{children:[t&&(0,Pt.jsx)("span",{className:s.stateBadge,children:a(t)}),n]}),(0,Pt.jsx)("span",{children:r})]})}),(0,Pt.jsx)(ae.Actions,{fixed:t==="Started",children:(0,Pt.jsx)(ae.ActionButton,{primary:!0,className:l==="start"?s.buttonStart:s.buttonStop,onClick:t==="Started"?i:o,disabled:e,label:(0,Pt.jsxs)(CT.Fragment,{children:[(0,Pt.jsx)(ST,{children:u})," ",(0,Pt.jsx)("span",{children:a(l)})]})})})]})},bT=zN;var Uh=w(b()),BN=(e,t)=>{let n=t.filter(r=>r.state==="Started");return n.length>0?n.indexOf(e)===-1:!1},VN=({autoflows:e,onStartAutoflow:t,onStopAutoflow:n,platformSessionId:r})=>(0,Uh.jsx)(TT.Fragment,{children:e.map(o=>(0,Uh.jsx)(bT,{displayName:o.displayName,description:o.description,disabled:o.isBusy||BN(o,e),state:o.state,onStartAutoflow:()=>t({platformSessionId:r,triggerPayload:o.triggerPayload}),onStopAutoflow:()=>n({platformSessionId:r,triggerPayload:o.triggerPayload})},o.displayName))}),KN=({autoflows:e,conversation:t})=>{var n;return{autoflows:e.list,platformSessionId:(n=t.current)==null?void 0:n.sessionId}},$N={onStartAutoflow:Mh,onStopAutoflow:_h},kT=zn(KN,$N)(VN);var PT=w(ee()),jh=w(F());var nr={root:"co",title:"fo",isUsed:"Ui",quickReplies:"Bi",quickReply:"Di",hasError:"Ii",label:"Oi",errorIcon:"Xi"};var ht=w(b()),qN=({suggestion:e})=>{let t=G(Mo),n=Z(),r=O(iT(e.text)),o=O(sT(e.text)),i=O(aT(e.text)),s=O(Mc),{replyOptions:a}=e,l=(0,jh.useCallback)(c=>{c.preventDefault(),c.stopPropagation(),!(r||!s)&&n(Yd({platformSessionId:s,suggestion:e}))},[e,r,n,s]),u=(0,jh.useCallback)(c=>{if(c.preventDefault(),c.stopPropagation(),!s||!a)return;let f=parseInt(c.target.dataset.index,10),d=a[f];n(Xd({platformSessionId:s,reply:d,suggestion:e}))},[e,r,n,s]);return(0,ht.jsxs)(ae,{onClick:l,className:(0,PT.default)(nr.root,{[nr.isUsed]:r,[nr.hasError]:i}),children:[(0,ht.jsx)(pe,{children:(0,ht.jsxs)(pe.Content,{children:[(0,ht.jsxs)(pe.Title,{className:nr.title,children:[e.text," ",(0,ht.jsx)(Ml,{className:nr.label,children:"analyse tool"})," ",i&&(0,ht.jsx)("span",{className:nr.errorIcon,role:"img","aria-label":t("sendingError"),title:t("sendingError"),children:"!"})]}),a&&a.length>0&&(0,ht.jsx)("ul",{className:nr.quickReplies,children:a.map(c=>(0,ht.jsx)("li",{className:nr.quickReply,children:c.title},c.title))})]})}),(0,ht.jsxs)(ae.Actions,{fixed:i||r,children:[a&&a.length>0&&(0,ht.jsx)(ae.DropdownButton,{label:t("answer"),disabled:o,children:a.map((c,f)=>(0,ht.jsx)(ae.DropdownItem,{index:f,label:c.title,onClick:u},c.title))}),(0,ht.jsx)(ae.ActionButton,{primary:!0,disabled:r,onClick:l,label:t(r?"suggestionSent":i?"tryAgain":"sendSuggestion")})]})]})},RT=qN;var Qd=w(F());var Vh=w(ee());var zh=w(b()),Bh=()=>(0,zh.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 512 512",xmlns:"http://www.w3.org/2000/svg",children:(0,zh.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 AT={root:"Ji",entity:"r",entityText:"Ki",iconWrapper:"Pi",icon:"Qi",iconClicked:"Vi"};var Tn=w(b()),YN=({entities:e})=>{let t=A("EntitiesWidgetList",AT),[n,r]=(0,Qd.useState)(void 0),o=Z(),i=()=>{r(void 0)},s=a=>{e&&(r(e.indexOf(a)),Po(a.text),o(Qe({name:"entity copied",data:{entity:a,type:"copy"}})))};return(0,Qd.useEffect)(()=>{let a=setTimeout(i,500);return()=>{clearTimeout(a)}},[n]),!e||e.length===0?null:(0,Tn.jsx)("div",{className:t.root,"data-testid":"widget-entities-list",children:e.map((a,l)=>(0,Tn.jsxs)("button",{title:a.text,className:t.entity,type:"button",onClick:()=>s(a),children:[(0,Tn.jsx)("span",{className:t.entityText,children:a.text}),(0,Tn.jsxs)("span",{className:t.iconWrapper,children:[(0,Tn.jsx)("span",{className:(0,Vh.default)(t.icon),children:(0,Tn.jsx)(Bh,{})}),(0,Tn.jsx)("span",{className:(0,Vh.default)(t.icon,n===l&&t.iconClicked),children:(0,Tn.jsx)(Bh,{})})]})]},a.text))})},IT=YN;var Kh=w(b()),LT=()=>(0,Kh.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:(0,Kh.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 $h=w(b()),OT=()=>(0,$h.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:(0,$h.jsx)("path",{d:"M543-340q16.595 0 28.798-12.202Q584-364.405 584-381t-12.202-28.798Q559.595-422 543-422t-28.798 12.202Q502-397.595 502-381t12.202 28.798Q526.405-340 543-340Zm-25-126h47q2-29 8.5-43t32.5-39q27-26 37.5-45.395Q654-612.79 654-639q0-45.882-31.5-74.941Q591-743 540-743q-38 0-68 20.5T428-665l45 19q11-25 27.5-38t39.5-13q29.778 0 48.389 17Q607-663 607-637q0 20-9 35t-32 32q-32 29-40 46.5t-8 57.5ZM260-200q-24 0-42-18t-18-42v-560q0-24 18-42t42-18h560q24 0 42 18t18 42v560q0 24-18 42t-42 18H260Zm0-60h560v-560H260v560ZM140-80q-24 0-42-18t-18-42v-620h60v620h620v60H140Zm120-740v560-560Z"})});var Wh=w(b()),NT=()=>(0,Wh.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:(0,Wh.jsx)("path",{d:"M319-250h322v-60H319v60Zm0-170h322v-60H319v60ZM220-80q-24 0-42-18t-18-42v-680q0-24 18-42t42-18h361l219 219v521q0 24-18 42t-42 18H220Zm331-554v-186H220v680h520v-494H551ZM220-820v186-186 680-680Z"})});var{entries:zT,setPrototypeOf:MT,isFrozen:XN,getPrototypeOf:QN,getOwnPropertyDescriptor:ZN}=Object,{freeze:it,seal:dn,create:BT}=Object,{apply:Zh,construct:Jh}=typeof Reflect<"u"&&Reflect;it||(it=function(t){return t});dn||(dn=function(t){return t});Zh||(Zh=function(t,n,r){return t.apply(n,r)});Jh||(Jh=function(t,n){return new t(...n)});var Zd=At(Array.prototype.forEach),_T=At(Array.prototype.pop),rl=At(Array.prototype.push),tf=At(String.prototype.toLowerCase),qh=At(String.prototype.toString),JN=At(String.prototype.match),ol=At(String.prototype.replace),eM=At(String.prototype.indexOf),tM=At(String.prototype.trim),cn=At(Object.prototype.hasOwnProperty),Rt=At(RegExp.prototype.test),il=nM(TypeError);function At(e){return function(t){for(var n=arguments.length,r=new Array(n>1?n-1:0),o=1;o<n;o++)r[o-1]=arguments[o];return Zh(e,t,r)}}function nM(e){return function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];return Jh(e,n)}}function Y(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:tf;MT&&MT(e,null);let r=t.length;for(;r--;){let o=t[r];if(typeof o=="string"){let i=n(o);i!==o&&(XN(t)||(t[r]=i),o=i)}e[o]=!0}return e}function rM(e){for(let t=0;t<e.length;t++)cn(e,t)||(e[t]=null);return e}function zo(e){let t=BT(null);for(let[n,r]of zT(e))cn(e,n)&&(Array.isArray(r)?t[n]=rM(r):r&&typeof r=="object"&&r.constructor===Object?t[n]=zo(r):t[n]=r);return t}function Jd(e,t){for(;e!==null;){let r=ZN(e,t);if(r){if(r.get)return At(r.get);if(typeof r.value=="function")return At(r.value)}e=QN(e)}function n(){return null}return n}var DT=it(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","section","select","shadow","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),Gh=it(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","filter","font","g","glyph","glyphref","hkern","image","line","lineargradient","marker","mask","metadata","mpath","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),Yh=it(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),oM=it(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),Xh=it(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),iM=it(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),FT=it(["#text"]),HT=it(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","face","for","headers","height","hidden","high","href","hreflang","id","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","pattern","placeholder","playsinline","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","xmlns","slot"]),Qh=it(["accent-height","accumulate","additive","alignment-baseline","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),UT=it(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),ef=it(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),sM=dn(/\{\{[\w\W]*|[\w\W]*\}\}/gm),aM=dn(/<%[\w\W]*|[\w\W]*%>/gm),lM=dn(/\${[\w\W]*}/gm),uM=dn(/^data-[\-\w.\u00B7-\uFFFF]/),cM=dn(/^aria-[\-\w]+$/),VT=dn(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),dM=dn(/^(?:\w+script|data):/i),fM=dn(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),KT=dn(/^html$/i),jT=Object.freeze({__proto__:null,MUSTACHE_EXPR:sM,ERB_EXPR:aM,TMPLIT_EXPR:lM,DATA_ATTR:uM,ARIA_ATTR:cM,IS_ALLOWED_URI:VT,IS_SCRIPT_OR_DATA:dM,ATTR_WHITESPACE:fM,DOCTYPE_NAME:KT}),pM=function(){return typeof window>"u"?null:window},mM=function(t,n){if(typeof t!="object"||typeof t.createPolicy!="function")return null;let r=null,o="data-tt-policy-suffix";n&&n.hasAttribute(o)&&(r=n.getAttribute(o));let i="dompurify"+(r?"#"+r:"");try{return t.createPolicy(i,{createHTML(s){return s},createScriptURL(s){return s}})}catch{return console.warn("TrustedTypes policy "+i+" could not be created."),null}};function $T(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:pM(),t=H=>$T(H);if(t.version="3.0.9",t.removed=[],!e||!e.document||e.document.nodeType!==9)return t.isSupported=!1,t;let{document:n}=e,r=n,o=r.currentScript,{DocumentFragment:i,HTMLTemplateElement:s,Node:a,Element:l,NodeFilter:u,NamedNodeMap:c=e.NamedNodeMap||e.MozNamedAttrMap,HTMLFormElement:f,DOMParser:d,trustedTypes:p}=e,y=l.prototype,v=Jd(y,"cloneNode"),g=Jd(y,"nextSibling"),m=Jd(y,"childNodes"),h=Jd(y,"parentNode");if(typeof s=="function"){let H=n.createElement("template");H.content&&H.content.ownerDocument&&(n=H.content.ownerDocument)}let S,x="",{implementation:C,createNodeIterator:T,createDocumentFragment:k,getElementsByTagName:I}=n,{importNode:L}=r,N={};t.isSupported=typeof zT=="function"&&typeof h=="function"&&C&&C.createHTMLDocument!==void 0;let{MUSTACHE_EXPR:z,ERB_EXPR:K,TMPLIT_EXPR:J,DATA_ATTR:oe,ARIA_ATTR:ze,IS_SCRIPT_OR_DATA:pn,ATTR_WHITESPACE:st}=jT,{IS_ALLOWED_URI:_}=jT,$=null,ar=Y({},[...DT,...Gh,...Yh,...Xh,...FT]),ye=null,lr=Y({},[...HT,...Qh,...UT,...ef]),W=Object.seal(BT(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),ur=null,yl=null,$o=!0,Qr=!0,cs=!1,vl=!0,qt=!1,Gt=!1,Sl=!1,at=!1,It=!1,wl=!1,xl=!1,py=!0,my=!1,q1="user-content-",pf=!0,ds=!1,Wo={},qo=null,gy=Y({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]),hy=null,yy=Y({},["audio","video","img","source","image","track"]),mf=null,vy=Y({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),El="http://www.w3.org/1998/Math/MathML",Cl="http://www.w3.org/2000/svg",Rn="http://www.w3.org/1999/xhtml",Go=Rn,gf=!1,hf=null,G1=Y({},[El,Cl,Rn],qh),fs=null,Y1=["application/xhtml+xml","text/html"],X1="text/html",Ne=null,Yo=null,Q1=n.createElement("form"),Sy=function(E){return E instanceof RegExp||E instanceof Function},yf=function(){let E=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(Yo&&Yo===E)){if((!E||typeof E!="object")&&(E={}),E=zo(E),fs=Y1.indexOf(E.PARSER_MEDIA_TYPE)===-1?X1:E.PARSER_MEDIA_TYPE,Ne=fs==="application/xhtml+xml"?qh:tf,$=cn(E,"ALLOWED_TAGS")?Y({},E.ALLOWED_TAGS,Ne):ar,ye=cn(E,"ALLOWED_ATTR")?Y({},E.ALLOWED_ATTR,Ne):lr,hf=cn(E,"ALLOWED_NAMESPACES")?Y({},E.ALLOWED_NAMESPACES,qh):G1,mf=cn(E,"ADD_URI_SAFE_ATTR")?Y(zo(vy),E.ADD_URI_SAFE_ATTR,Ne):vy,hy=cn(E,"ADD_DATA_URI_TAGS")?Y(zo(yy),E.ADD_DATA_URI_TAGS,Ne):yy,qo=cn(E,"FORBID_CONTENTS")?Y({},E.FORBID_CONTENTS,Ne):gy,ur=cn(E,"FORBID_TAGS")?Y({},E.FORBID_TAGS,Ne):{},yl=cn(E,"FORBID_ATTR")?Y({},E.FORBID_ATTR,Ne):{},Wo=cn(E,"USE_PROFILES")?E.USE_PROFILES:!1,$o=E.ALLOW_ARIA_ATTR!==!1,Qr=E.ALLOW_DATA_ATTR!==!1,cs=E.ALLOW_UNKNOWN_PROTOCOLS||!1,vl=E.ALLOW_SELF_CLOSE_IN_ATTR!==!1,qt=E.SAFE_FOR_TEMPLATES||!1,Gt=E.WHOLE_DOCUMENT||!1,It=E.RETURN_DOM||!1,wl=E.RETURN_DOM_FRAGMENT||!1,xl=E.RETURN_TRUSTED_TYPE||!1,at=E.FORCE_BODY||!1,py=E.SANITIZE_DOM!==!1,my=E.SANITIZE_NAMED_PROPS||!1,pf=E.KEEP_CONTENT!==!1,ds=E.IN_PLACE||!1,_=E.ALLOWED_URI_REGEXP||VT,Go=E.NAMESPACE||Rn,W=E.CUSTOM_ELEMENT_HANDLING||{},E.CUSTOM_ELEMENT_HANDLING&&Sy(E.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(W.tagNameCheck=E.CUSTOM_ELEMENT_HANDLING.tagNameCheck),E.CUSTOM_ELEMENT_HANDLING&&Sy(E.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(W.attributeNameCheck=E.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),E.CUSTOM_ELEMENT_HANDLING&&typeof E.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(W.allowCustomizedBuiltInElements=E.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),qt&&(Qr=!1),wl&&(It=!0),Wo&&($=Y({},FT),ye=[],Wo.html===!0&&(Y($,DT),Y(ye,HT)),Wo.svg===!0&&(Y($,Gh),Y(ye,Qh),Y(ye,ef)),Wo.svgFilters===!0&&(Y($,Yh),Y(ye,Qh),Y(ye,ef)),Wo.mathMl===!0&&(Y($,Xh),Y(ye,UT),Y(ye,ef))),E.ADD_TAGS&&($===ar&&($=zo($)),Y($,E.ADD_TAGS,Ne)),E.ADD_ATTR&&(ye===lr&&(ye=zo(ye)),Y(ye,E.ADD_ATTR,Ne)),E.ADD_URI_SAFE_ATTR&&Y(mf,E.ADD_URI_SAFE_ATTR,Ne),E.FORBID_CONTENTS&&(qo===gy&&(qo=zo(qo)),Y(qo,E.FORBID_CONTENTS,Ne)),pf&&($["#text"]=!0),Gt&&Y($,["html","head","body"]),$.table&&(Y($,["tbody"]),delete ur.tbody),E.TRUSTED_TYPES_POLICY){if(typeof E.TRUSTED_TYPES_POLICY.createHTML!="function")throw il('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof E.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw il('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');S=E.TRUSTED_TYPES_POLICY,x=S.createHTML("")}else S===void 0&&(S=mM(p,o)),S!==null&&typeof x=="string"&&(x=S.createHTML(""));it&&it(E),Yo=E}},wy=Y({},["mi","mo","mn","ms","mtext"]),xy=Y({},["foreignobject","desc","title","annotation-xml"]),Z1=Y({},["title","style","font","a","script"]),Ey=Y({},[...Gh,...Yh,...oM]),Cy=Y({},[...Xh,...iM]),J1=function(E){let R=h(E);(!R||!R.tagName)&&(R={namespaceURI:Go,tagName:"template"});let D=tf(E.tagName),de=tf(R.tagName);return hf[E.namespaceURI]?E.namespaceURI===Cl?R.namespaceURI===Rn?D==="svg":R.namespaceURI===El?D==="svg"&&(de==="annotation-xml"||wy[de]):!!Ey[D]:E.namespaceURI===El?R.namespaceURI===Rn?D==="math":R.namespaceURI===Cl?D==="math"&&xy[de]:!!Cy[D]:E.namespaceURI===Rn?R.namespaceURI===Cl&&!xy[de]||R.namespaceURI===El&&!wy[de]?!1:!Cy[D]&&(Z1[D]||!Ey[D]):!!(fs==="application/xhtml+xml"&&hf[E.namespaceURI]):!1},Zr=function(E){rl(t.removed,{element:E});try{E.parentNode.removeChild(E)}catch{E.remove()}},vf=function(E,R){try{rl(t.removed,{attribute:R.getAttributeNode(E),from:R})}catch{rl(t.removed,{attribute:null,from:R})}if(R.removeAttribute(E),E==="is"&&!ye[E])if(It||wl)try{Zr(R)}catch{}else try{R.setAttribute(E,"")}catch{}},by=function(E){let R=null,D=null;if(at)E="<remove></remove>"+E;else{let Ve=JN(E,/^[\r\n\t ]+/);D=Ve&&Ve[0]}fs==="application/xhtml+xml"&&Go===Rn&&(E='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+E+"</body></html>");let de=S?S.createHTML(E):E;if(Go===Rn)try{R=new d().parseFromString(de,fs)}catch{}if(!R||!R.documentElement){R=C.createDocument(Go,"template",null);try{R.documentElement.innerHTML=gf?x:de}catch{}}let Be=R.body||R.documentElement;return E&&D&&Be.insertBefore(n.createTextNode(D),Be.childNodes[0]||null),Go===Rn?I.call(R,Gt?"html":"body")[0]:Gt?R.documentElement:Be},Ty=function(E){return T.call(E.ownerDocument||E,E,u.SHOW_ELEMENT|u.SHOW_COMMENT|u.SHOW_TEXT,null)},ek=function(E){return E instanceof f&&(typeof E.nodeName!="string"||typeof E.textContent!="string"||typeof E.removeChild!="function"||!(E.attributes instanceof c)||typeof E.removeAttribute!="function"||typeof E.setAttribute!="function"||typeof E.namespaceURI!="string"||typeof E.insertBefore!="function"||typeof E.hasChildNodes!="function")},ky=function(E){return typeof a=="function"&&E instanceof a},An=function(E,R,D){N[E]&&Zd(N[E],de=>{de.call(t,R,D,Yo)})},Py=function(E){let R=null;if(An("beforeSanitizeElements",E,null),ek(E))return Zr(E),!0;let D=Ne(E.nodeName);if(An("uponSanitizeElement",E,{tagName:D,allowedTags:$}),E.hasChildNodes()&&!ky(E.firstElementChild)&&Rt(/<[/\w]/g,E.innerHTML)&&Rt(/<[/\w]/g,E.textContent))return Zr(E),!0;if(!$[D]||ur[D]){if(!ur[D]&&Ay(D)&&(W.tagNameCheck instanceof RegExp&&Rt(W.tagNameCheck,D)||W.tagNameCheck instanceof Function&&W.tagNameCheck(D)))return!1;if(pf&&!qo[D]){let de=h(E)||E.parentNode,Be=m(E)||E.childNodes;if(Be&&de){let Ve=Be.length;for(let lt=Ve-1;lt>=0;--lt)de.insertBefore(v(Be[lt],!0),g(E))}}return Zr(E),!0}return E instanceof l&&!J1(E)||(D==="noscript"||D==="noembed"||D==="noframes")&&Rt(/<\/no(script|embed|frames)/i,E.innerHTML)?(Zr(E),!0):(qt&&E.nodeType===3&&(R=E.textContent,Zd([z,K,J],de=>{R=ol(R,de," ")}),E.textContent!==R&&(rl(t.removed,{element:E.cloneNode()}),E.textContent=R)),An("afterSanitizeElements",E,null),!1)},Ry=function(E,R,D){if(py&&(R==="id"||R==="name")&&(D in n||D in Q1))return!1;if(!(Qr&&!yl[R]&&Rt(oe,R))){if(!($o&&Rt(ze,R))){if(!ye[R]||yl[R]){if(!(Ay(E)&&(W.tagNameCheck instanceof RegExp&&Rt(W.tagNameCheck,E)||W.tagNameCheck instanceof Function&&W.tagNameCheck(E))&&(W.attributeNameCheck instanceof RegExp&&Rt(W.attributeNameCheck,R)||W.attributeNameCheck instanceof Function&&W.attributeNameCheck(R))||R==="is"&&W.allowCustomizedBuiltInElements&&(W.tagNameCheck instanceof RegExp&&Rt(W.tagNameCheck,D)||W.tagNameCheck instanceof Function&&W.tagNameCheck(D))))return!1}else if(!mf[R]){if(!Rt(_,ol(D,st,""))){if(!((R==="src"||R==="xlink:href"||R==="href")&&E!=="script"&&eM(D,"data:")===0&&hy[E])){if(!(cs&&!Rt(pn,ol(D,st,"")))){if(D)return!1}}}}}}return!0},Ay=function(E){return E!=="annotation-xml"&&E.indexOf("-")>0},Iy=function(E){An("beforeSanitizeAttributes",E,null);let{attributes:R}=E;if(!R)return;let D={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:ye},de=R.length;for(;de--;){let Be=R[de],{name:Ve,namespaceURI:lt,value:Jr}=Be,ps=Ne(Ve),ut=Ve==="value"?Jr:tM(Jr);if(D.attrName=ps,D.attrValue=ut,D.keepAttr=!0,D.forceKeepAttr=void 0,An("uponSanitizeAttribute",E,D),ut=D.attrValue,D.forceKeepAttr||(vf(Ve,E),!D.keepAttr))continue;if(!vl&&Rt(/\/>/i,ut)){vf(Ve,E);continue}qt&&Zd([z,K,J],Oy=>{ut=ol(ut,Oy," ")});let Ly=Ne(E.nodeName);if(Ry(Ly,ps,ut)){if(my&&(ps==="id"||ps==="name")&&(vf(Ve,E),ut=q1+ut),S&&typeof p=="object"&&typeof p.getAttributeType=="function"&&!lt)switch(p.getAttributeType(Ly,ps)){case"TrustedHTML":{ut=S.createHTML(ut);break}case"TrustedScriptURL":{ut=S.createScriptURL(ut);break}}try{lt?E.setAttributeNS(lt,Ve,ut):E.setAttribute(Ve,ut),_T(t.removed)}catch{}}}An("afterSanitizeAttributes",E,null)},tk=function H(E){let R=null,D=Ty(E);for(An("beforeSanitizeShadowDOM",E,null);R=D.nextNode();)An("uponSanitizeShadowNode",R,null),!Py(R)&&(R.content instanceof i&&H(R.content),Iy(R));An("afterSanitizeShadowDOM",E,null)};return t.sanitize=function(H){let E=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},R=null,D=null,de=null,Be=null;if(gf=!H,gf&&(H="<!-->"),typeof H!="string"&&!ky(H))if(typeof H.toString=="function"){if(H=H.toString(),typeof H!="string")throw il("dirty is not a string, aborting")}else throw il("toString is not a function");if(!t.isSupported)return H;if(Sl||yf(E),t.removed=[],typeof H=="string"&&(ds=!1),ds){if(H.nodeName){let Jr=Ne(H.nodeName);if(!$[Jr]||ur[Jr])throw il("root node is forbidden and cannot be sanitized in-place")}}else if(H instanceof a)R=by("<!---->"),D=R.ownerDocument.importNode(H,!0),D.nodeType===1&&D.nodeName==="BODY"||D.nodeName==="HTML"?R=D:R.appendChild(D);else{if(!It&&!qt&&!Gt&&H.indexOf("<")===-1)return S&&xl?S.createHTML(H):H;if(R=by(H),!R)return It?null:xl?x:""}R&&at&&Zr(R.firstChild);let Ve=Ty(ds?H:R);for(;de=Ve.nextNode();)Py(de)||(de.content instanceof i&&tk(de.content),Iy(de));if(ds)return H;if(It){if(wl)for(Be=k.call(R.ownerDocument);R.firstChild;)Be.appendChild(R.firstChild);else Be=R;return(ye.shadowroot||ye.shadowrootmode)&&(Be=L.call(r,Be,!0)),Be}let lt=Gt?R.outerHTML:R.innerHTML;return Gt&&$["!doctype"]&&R.ownerDocument&&R.ownerDocument.doctype&&R.ownerDocument.doctype.name&&Rt(KT,R.ownerDocument.doctype.name)&&(lt="<!DOCTYPE "+R.ownerDocument.doctype.name+`>
24
24
  `+lt),qt&&Zd([z,K,J],Jr=>{lt=ol(lt,Jr," ")}),S&&xl?S.createHTML(lt):lt},t.setConfig=function(){let H=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};yf(H),Sl=!0},t.clearConfig=function(){Yo=null,Sl=!1},t.isValidAttribute=function(H,E,R){Yo||yf({});let D=Ne(H),de=Ne(E);return Ry(D,de,R)},t.addHook=function(H,E){typeof E=="function"&&(N[H]=N[H]||[],rl(N[H],E))},t.removeHook=function(H){if(N[H])return _T(N[H])},t.removeHooks=function(H){N[H]&&(N[H]=[])},t.removeAllHooks=function(){N={}},t}var WT=$T();var or=w(F());var gM={"":["<em>","</em>"],_:["<strong>","</strong>"],"*":["<strong>","</strong>"],"~":["<s>","</s>"],"\n":["<br />"]," ":["<br />"],"-":["<hr />"]};function qT(e){return e.replace(RegExp("^"+(e.match(/^(\t| )+/)||"")[0],"gm"),"")}function sl(e){return(e+"").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function al(e,t){var n,r,o,i,s,a=/((?:^|\n+)(?:\n---+|\* \*(?: \*)+)\n)|(?:^``` *(\w*)\n([\s\S]*?)\n```$)|((?:(?:^|\n+)(?:\t| {2,}).+)+\n*)|((?:(?:^|\n)([>*+-]|\d+\.)\s+.*)+)|(?:!\[([^\]]*?)\]\(([^)]+?)\))|(\[)|(\](?:\(([^)]+?)\))?)|(?:(?:^|\n+)([^\s].*)\n(-{3,}|={3,})(?:\n+|$))|(?:(?:^|\n+)(#{1,6})\s*(.+)(?:\n+|$))|(?:`([^`].*?)`)|( \n\n*|\n{2,}|__|\*\*|[_*]|~~)/gm,l=[],u="",c=t||{},f=0;function d(y){var v=gM[y[1]||""],g=l[l.length-1]==y;return v?v[1]?(g?l.pop():l.push(y),v[0|g]):v[0]:y}function p(){for(var y="";l.length;)y+=d(l[l.length-1]);return y}for(e=e.replace(/^\[(.+?)\]:\s*(.+)$/gm,function(y,v,g){return c[v.toLowerCase()]=g,""}).replace(/^\n+|\n+$/g,"");o=a.exec(e);)r=e.substring(f,o.index),f=a.lastIndex,n=o[0],r.match(/[^\\](\\\\)*\\$/)||((s=o[3]||o[4])?n='<pre class="code '+(o[4]?"poetry":o[2].toLowerCase())+'"><code'+(o[2]?' class="language-'+o[2].toLowerCase()+'"':"")+">"+qT(sl(s).replace(/^\n+|\n+$/g,""))+"</code></pre>":(s=o[6])?(s.match(/\./)&&(o[5]=o[5].replace(/^\d+/gm,"")),i=al(qT(o[5].replace(/^\s*[>*+.-]/gm,""))),s==">"?s="blockquote":(s=s.match(/\./)?"ol":"ul",i=i.replace(/^(.*)(\n|$)/gm,"<li>$1</li>")),n="<"+s+">"+i+"</"+s+">"):o[8]?n='<img src="'+sl(o[8])+'" alt="'+sl(o[7])+'">':o[10]?(u=u.replace("<a>",'<a href="'+sl(o[11]||c[r.toLowerCase()])+'">'),n=p()+"</a>"):o[9]?n="<a>":o[12]||o[14]?n="<"+(s="h"+(o[14]?o[14].length:o[13]>"="?1:2))+">"+al(o[12]||o[15],c)+"</"+s+">":o[16]?n="<code>"+sl(o[16])+"</code>":(o[17]||o[1])&&(n=d(o[17]||"--"))),u+=r,u+=n;return(u+e.substring(f)+p()).replace(/^\n+|\n+$/g,"")}var GT={root:"i",popover:"Wi",options:"go",copyIcon:"Zi",option:"bo",divider:"_i"};var rr=w(b()),yM=e=>`<svg class=${e} version="1.1" x="0px" y="0px" viewBox="0 0 115.77 122.88" width="10px" height="10px" fill="black" fill-opacity="0.5" stroke-opacity="0.8"><g><path d="M89.62,13.96v7.73h12.19h0.01v0.02c3.85,0.01,7.34,1.57,9.86,4.1c2.5,2.51,4.06,5.98,4.07,9.82h0.02v0.02 v73.27v0.01h-0.02c-0.01,3.84-1.57,7.33-4.1,9.86c-2.51,2.5-5.98,4.06-9.82,4.07v0.02h-0.02h-61.7H40.1v-0.02 c-3.84-0.01-7.34-1.57-9.86-4.1c-2.5-2.51-4.06-5.98-4.07-9.82h-0.02v-0.02V92.51H13.96h-0.01v-0.02c-3.84-0.01-7.34-1.57-9.86-4.1 c-2.5-2.51-4.06-5.98-4.07-9.82H0v-0.02V13.96v-0.01h0.02c0.01-3.85,1.58-7.34,4.1-9.86c2.51-2.5,5.98-4.06,9.82-4.07V0h0.02h61.7 h0.01v0.02c3.85,0.01,7.34,1.57,9.86,4.1c2.5,2.51,4.06,5.98,4.07,9.82h0.02V13.96L89.62,13.96z M79.04,21.69v-7.73v-0.02h0.02 c0-0.91-0.39-1.75-1.01-2.37c-0.61-0.61-1.46-1-2.37-1v0.02h-0.01h-61.7h-0.02v-0.02c-0.91,0-1.75,0.39-2.37,1.01 c-0.61,0.61-1,1.46-1,2.37h0.02v0.01v64.59v0.02h-0.02c0,0.91,0.39,1.75,1.01,2.37c0.61,0.61,1.46,1,2.37,1v-0.02h0.01h12.19V35.65 v-0.01h0.02c0.01-3.85,1.58-7.34,4.1-9.86c2.51-2.5,5.98-4.06,9.82-4.07v-0.02h0.02H79.04L79.04,21.69z M105.18,108.92V35.65v-0.02 h0.02c0-0.91-0.39-1.75-1.01-2.37c-0.61-0.61-1.46-1-2.37-1v0.02h-0.01h-61.7h-0.02v-0.02c-0.91,0-1.75,0.39-2.37,1.01 c-0.61,0.61-1,1.46-1,2.37h0.02v0.01v73.27v0.02h-0.02c0,0.91,0.39,1.75,1.01,2.37c0.61,0.61,1.46,1,2.37,1v-0.02h0.01h61.7h0.02 v0.02c0.91,0,1.75-0.39,2.37-1.01c0.61-0.61,1-1.46,1-2.37h-0.02V108.92L105.18,108.92z"/></g></svg>`,vM=({content:e,useLabel:t,copyLabel:n,onCopy:r,onUse:o})=>{let i=A("Markdown",GT),s=(0,or.useRef)(null),[a,l]=(0,or.useState)(null),[u,c]=(0,or.useState)(null),f=(0,or.useMemo)(()=>{let g=al(e);return WT.sanitize(g).replace(/<\/code>/g,`${yM(i.copyIcon)}</code>`)},[e]),d=()=>{l(null),c(null)},p=g=>{var S;let m=g.target,h=!!((S=s.current)!=null&&S.querySelector("code"));a||h&&m.tagName!=="CODE"||!h&&m!==s.current||(m.addEventListener("mouseleave",d,{once:!0}),c(m.textContent),l(m))},y=()=>{u&&r(u),d()},v=()=>{u&&o(u),d()};return(0,rr.jsxs)(or.Fragment,{children:[a&&(0,rr.jsx)(is,{triggerRef:{current:a},parentNode:a,className:i.popover,children:(0,rr.jsxs)("div",{className:i.options,children:[(0,rr.jsx)("button",{type:"button",className:i.option,onClick:y,children:n}),(0,rr.jsx)("div",{className:i.divider}),(0,rr.jsx)("button",{type:"button",className:i.option,onClick:v,children:t})]})}),(0,rr.jsx)("div",{ref:s,className:i.root,dangerouslySetInnerHTML:{__html:f},onMouseOver:p})]})},YT=vM;var ey={};Je(ey,{enUS:()=>SM,nlNL:()=>wM});var SM={useCue:[{type:0,value:"Copy"}],copyCue:[{type:0,value:"Copy"}],removeCue:[{type:0,value:"Close"}]},wM={useCue:[{type:0,value:"Gebruik"}],copyCue:[{type:0,value:"Kopieer"}],removeCue:[{type:0,value:"Sluiten"}]};var Yr=w(b()),xM=({cue:e,onRemove:t,onCopy:n,onUse:r})=>{let o=G(ey),i=l=>{n&&n(l)},s=l=>{r&&r(l)},a=l=>{l.preventDefault(),l.stopPropagation(),t&&t(e.id)};return(0,Yr.jsxs)(ae,{"data-testid":"cue",children:[(0,Yr.jsx)(pe,{children:(0,Yr.jsxs)(pe.Content,{children:[e.title&&(0,Yr.jsx)(pe.Title,{"data-testid":"widget-cue-title",children:e.title}),(0,Yr.jsx)(YT,{content:e.text,useLabel:o("useCue"),copyLabel:o("copyCue"),onCopy:i,onUse:s})]})}),(0,Yr.jsx)(ae.CloseIcon,{title:o("removeCue"),onClick:a})]})},XT=xM;var ll=w(b()),EM=({cues:e,onCopyCue:t,onUseCue:n,onRemoveCue:r})=>(0,ll.jsx)(ll.Fragment,{children:e.map(o=>(0,ll.jsx)(XT,{cue:o,onRemove:r,onCopy:t,onUse:n},`${o.id}_${o.timestamp}`))}),QT=EM;var JT=w(F());var CM=/(https?:\/\/[^\s]+)/,ZT=e=>e.split(" ").find(t=>CM.test(t));var $t=w(b()),bM=({suggestion:e,lines:t,onUse:n})=>{var c;let r=e.text||e.url||e.message,o=ZT(r),i=G(Mo),s=U("showImages"),a=U("fallbackImage"),l=f=>{f.preventDefault(),f.stopPropagation(),n(r)},u=(0,JT.useCallback)(f=>{window.open(o,"_blank"),f.stopPropagation(),f.preventDefault()},[o]);return(0,$t.jsxs)(ae,{onClick:l,"data-testid":"edit-suggestion",children:[(0,$t.jsxs)(pe,{children:[s&&e.image&&(0,$t.jsx)(pe.Image,{src:$d(e,"small",a||void 0),title:e.title}),(0,$t.jsxs)(pe.Content,{children:[e.title&&(0,$t.jsx)(pe.Title,{"data-testid":"widget-suggestion-title",children:e.title}),e.searchKeywords&&((c=e.searchKeywords)==null?void 0:c.length)>0&&(0,$t.jsx)(ae.Labels,{labels:e.searchKeywords}),(0,$t.jsx)(pe.Content,{cropText:t==="single",lineClamp:t==="multiple",children:r})]})]}),(0,$t.jsxs)(ae.Actions,{children:[o&&(0,$t.jsx)(ae.ActionButton,{onClick:u,label:i("visitUrl")}),(0,$t.jsx)(ae.ActionButton,{primary:!0,onClick:l,label:i("useSuggestion")})]})]})},e1=bM;var ul=w(b()),TM=({lines:e,suggestions:t})=>{let n=en(),r=(o,i)=>{n.send(Hr,{text:o,suggestion:{...i,source:i.source,sourceText:i.text}})};return(0,ul.jsx)(ul.Fragment,{children:t.map(o=>(0,ul.jsx)(e1,{suggestion:o,lines:e,onUse:i=>r(i,o)},o.text||o.url||o.message))})},t1=TM;var ty={};Je(ty,{enUS:()=>kM,nlNL:()=>PM});var kM={waiting:[{type:0,value:"Loading\u2026"}],notSupported:[{type:0,value:"This conversation is not supported"}],noResults:[{type:0,value:"No results found\u2026"}],titleAutoflows:[{type:0,value:"Autoflows"}],titleCustomMessages:[{type:0,value:"Quick replies"}],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"}]},PM={waiting:[{type:0,value:"Laden\u2026"}],notSupported:[{type:0,value:"Dit gesprek wordt niet ondersteund"}],noResults:[{type:0,value:"Geen resultaten gevonden\u2026"}],titleAutoflows:[{type:0,value:"Autoflows"}],titleCustomMessages:[{type:0,value:"Quick replies"}],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"}]};var n1={root:"or",loginText:"er",stateText:"ho",sectionList:"ir",shortcutList:"rr",shortcut:"tr",link:"mo"};var X=w(b()),nf=(e,t)=>{let n=O(nt);(0,o1.useEffect)(()=>n?t.every(r=>!!r)?e():()=>{}:()=>{},[...t,n])},AM=({onLogIn:e})=>{let t=G(ty),n=Z(),r=U("isEmbedded"),o=A("Widget",n1),i=U("showAutoflows"),s=U("showCustomMessages"),a=U("showSummaryCommand"),l=U("showKnowledgeSearch"),u=U("showSearch"),c=O(Vr),f=O(bd),d=O(Jb),p=O(TE),y=O(Cd),v=O(oT),g=O(_c),m=O(Bi),h=O(nt),S=O(Mc),x=O(hT),C=O(Td),T=en(),k=O(YC),I=O(fT("/admin/")),L=U("adminUrl"),N=U("productName"),z=en();if(nf(()=>(n(nl(S)),n(uT(S)),()=>{n(cT(S))}),[n,m,s,S]),nf(()=>(n(tr(S)),n(eT(S)),()=>{n(tT(S))}),[n,m,i,S]),nf(()=>{f.forEach(({type:oe})=>{n(oe==="entities"?sn():ln(oe))})},[n,m,g,c]),nf(()=>(n(Fh()),()=>{n(mT())}),[n]),m===!1)return(0,X.jsx)("div",{className:o.stateText,children:(0,X.jsx)("div",{children:(0,X.jsx)("p",{children:t("notSupported")})})},"supported");if(h===!1)return(0,X.jsx)("div",{className:o.loginText,children:(0,X.jsx)("div",{children:(0,X.jsx)(Od,{isEmbedded:r,loginUrl:L,onLogIn:e})})},"login");if(!c||!S||h===null||k||x)return(0,X.jsx)("div",{className:o.stateText,children:(0,X.jsx)("div",{children:(0,X.jsx)("p",{children:t("waiting")})})},"waiting");let K=oe=>{z.send(Hr,{text:oe,suggestion:{source:"cue",sourceText:oe}})},J=u||a||l||I;return(0,X.jsx)("div",{className:(0,r1.default)(o.root),"data-testid":"widget",children:(0,X.jsxs)(_l,{className:o.sectionList,children:[J&&(0,X.jsx)(Ln,{title:t("actions"),type:"shortcuts",children:(0,X.jsxs)("div",{className:o.shortcutList,children:[u&&(0,X.jsxs)("button",{className:o.shortcut,"data-testid":"shortcut-search",onClick:()=>T.send("ShowCommandPalette",{isOpen:!0}),children:[(0,X.jsx)(qi,{}),t("linkSearch")]}),a&&(0,X.jsxs)("button",{className:o.shortcut,"data-testid":"shortcut-summary",onClick:()=>T.send("ShowCommandPalette",{isOpen:!0,page:"summary"}),children:[(0,X.jsx)(NT,{}),t("linkSummary")]}),l&&(0,X.jsxs)("button",{className:o.shortcut,"data-testid":"shortcut-knowledge-assist",onClick:()=>T.send("ShowCommandPalette",{isOpen:!0,page:"knowledgeAssist"}),children:[(0,X.jsx)(OT,{}),t("linkKnowledgeSearch")]}),I&&(0,X.jsxs)("a",{className:o.shortcut,target:"_blank",href:I,"data-testid":"shortcut-studio-login",rel:"noreferrer",children:[(0,X.jsx)(LT,{}),t("linkStudioLogin",{productName:N})]})]})}),s&&v.length>0&&(0,X.jsx)(Ln,{type:"custom-messages","data-testid":"custom-messages",children:(0,X.jsx)(vt,{withDivider:!0,children:v.map(oe=>(0,X.jsx)(RT,{suggestion:oe},oe.text))})}),i&&d.length>0&&(0,X.jsx)(Ln,{type:"autoflows",title:t("titleAutoflows"),"data-testid":"autoflows",children:(0,X.jsx)(vt,{withDivider:!0,children:(0,X.jsx)(kT,{})})}),f.map(({type:oe,title:ze,amount:pn,lines:st})=>{var _;switch(oe){case"entities":return y&&y.length>0&&(0,X.jsx)(Ln,{type:oe,title:ze,"data-testid":`type-${oe}`,children:(0,X.jsx)(IT,{entities:y})},oe);case"cues":return p&&p.length>0&&(0,X.jsx)(Ln,{type:oe,title:ze,"data-testid":`type-${oe}`,children:(0,X.jsx)(vt,{withDivider:!0,children:(0,X.jsx)(QT,{cues:p,onRemoveCue:$=>n(PE({id:$})),onCopyCue:$=>Po($),onUseCue:K})})},oe);default:return((_=C[oe])==null?void 0:_.fetchState)==="done"&&C[oe].suggestions.length>0&&(0,X.jsx)(Ln,{type:oe,title:ze,"data-testid":`type-${oe}`,children:(0,X.jsx)(vt,{withDivider:!0,children:(0,X.jsx)(t1,{lines:st,contentType:oe,suggestions:C[oe].suggestions.slice(0,pn)||[]})})},oe)}})]})})},i1=AM;function ss(e){let t=new Range;return t.selectNodeContents(e),t}function s1(e,t,n){try{return Xr(e,t,n),!0}catch{return!1}}function rf(e){return"tagName"in e&&(e.tagName==="DIV"||e.tagName==="P")}function of(e){return"tagName"in e&&e.tagName==="BR"}var cl=/[\u200B-\u200D\uFEFF]/g;function Xr(e,t,n){let r=new Range;if(e.firstChild===null&&t===0&&n===0)return r.selectNodeContents(e),r;let o=0,i=!1;function s(l,u){let c=-1,f=/[\u200B-\u200D\uFEFF]/;if(!f.test(l))return u;for(let d=0;d<=l.length;d++)if(f.test(l[d])||c++,c===u)return d;throw new Error("Offset out of range")}function a(l){switch(l.nodeType){case Node.TEXT_NODE:{let u=l.textContent,c=u.replace(cl,""),f=o+c.length,d=t>=o&&t<=f,p=n>=o&&n<=f;if(d){let y=s(u,t-o);y===0&&!p?r.setStartBefore(l):r.setStart(l,y)}p&&(r.setEnd(l,s(u,n-o)),i=!0),o=f;break}case Node.ELEMENT_NODE:{if(of(l)&&(o===t&&r.setStartBefore(l),o++,o===n)){r.setEndAfter(l),i=!0;return}for(let c=0;c<l.childNodes.length&&(a(l.childNodes[c]),!i);c++);let u=l.lastChild;rf(l)&&u&&!rf(u)&&!of(u)&&o++;break}default:break}}if(a(e),r.startContainer===document)throw new Error("Offsets out of bound");return r}function dl(e,t){if(!e.contains(t.startContainer)||!e.contains(t.endContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:r,endContainer:o,endOffset:i,collapsed:s}=t,a,l,u=0;function c(f){let d=f===n,p=f===o;switch(f.nodeType){case Node.TEXT_NODE:{let y=f.textContent;d&&(a=u+y.substring(0,r).replace(cl,"").length),p&&(l=u+y.substring(0,i).replace(cl,"").length),u+=y.replace(cl,"").length;break}case Node.ELEMENT_NODE:{let y=f.nextSibling===null;of(f)&&!y&&u++;for(let v=0;v<f.childNodes.length;v++){let g=d&&v===r,m=p&&v===i;if(g&&(a=u),m&&(l=u),l!==void 0||((!g||!s)&&c(f.childNodes[v]),p&&v===i-1&&(l=u),l!==void 0))break}!p&&rf(f)&&!y&&u++,p&&(l=u);break}default:break}}if(c(e),l===void 0)throw new Error("Could not determine start and end");return{start:a??l,end:l}}function fl(e,t){if(!e.contains(t.startContainer)||!e.contains(t.endContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:r,endContainer:o,endOffset:i}=t,s=-1,a="";function l(u){let c=u===n,f=u===o;switch(c&&s++,u.nodeType){case Node.TEXT_NODE:{if(s!==0)return;let d=c?r:0,p=f?i:void 0,y=u.textContent.replace(cl,"");d===0&&p===void 0?a+=y:a+=y.substring(d,p);break}case Node.ELEMENT_NODE:{let d=u.nextSibling===null;s===0&&of(u)&&!d&&(a+=`
25
25
  `);for(let p=c?r:0;p<(f?Math.min(i,u.childNodes.length):u.childNodes.length)&&(l(u.childNodes[p]),s!==1);p++);!f&&s===0&&rf(u)&&!d&&(a+=`
26
- `);break}default:break}f&&s++}return l(e),a}var a1=(s=>(s.CUT="Cut",s.BACKSPACE="Backspace",s.DELETE="Delete",s.ERASEEOF="EraseEof",s.UNDO="Undo",s.CLEAR="Clear",s))(a1||{}),ir=class{constructor(t){this.element=t;this.currentText=this.getText(),this.currentHTML=this.getHTML(),this.listen()}eventListeners={};disposeHandlers=[];currentText="";currentCaret=null;currentSelection={start:0,end:0};currentHTML="";isFocused=!1;isActive=!0;isSettingValue=!1;isSubmitting=!1;isPossibleClearInputAction=!1;isDisposed=!1;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)}triggerChange(){let t=this.getText(),n=this.getHTML(),r=t!==this.currentText;this.isActive&&(t===""&&this.currentText!==""&&!this.isSettingValue&&!this.isPossibleClearInputAction&&(this.isSubmitting=!0,this.emit("submit")),!this.isSettingValue&&r&&!this.isSubmitting&&this.emit("change",{plainText:t}),r&&(this.currentSelection=this.getSelection()),this.currentText=t,this.isSubmitting=!1,(this.currentHTML!==n||n===null&&r)&&(this.emit("updated",{plainText:t}),this.triggerCaretPosition(),this.currentHTML=n))}triggerSelection(){let t=this.getSelection();(t.start!==this.currentSelection.start||t.end!==this.currentSelection.end)&&(this.currentSelection=t,this.emit("selection",t),this.triggerCaretPosition())}triggerCaretPosition(){let t=this.getCaretPosition();_r(t,this.currentCaret)||(this.currentCaret=t,this.emit("caret",t))}handleKeyUp(t){let{key:n,shiftKey:r}=t;(n==="Enter"&&r===!0||n==="Backspace")&&this.triggerChange(),this.triggerSelection()}handleClick(){this.triggerSelection()}handleFocus(){this.isFocused||this.emit("focus"),this.triggerSelection(),this.isFocused=!0}handleBlur(){this.isPossibleClearInputAction=!1,this.isFocused&&this.emit("blur"),this.isFocused=!1}handleKeyDown(t){let{key:n,ctrlKey:r,metaKey:o}=t;this.isPossibleClearInputAction=Object.values(a1).includes(n)||n.toLowerCase()==="z"&&(r||o),this.emit("keydown",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.triggerChange()),this.addEventListener("change",()=>this.triggerChange()),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.triggerSelection()),document.activeElement===this.element&&setTimeout(()=>{this.handleFocus()},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()}),this.currentSelection=this.getSelection()}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))}activate(){let t=this.isActive===!1;this.isActive=!0,t&&this.triggerChange()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(t=>t()),this.eventListeners={},this.isDisposed=!0}};function l1(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var Bo=class extends ir{observer;lastKnownSelection=null;getRootNode(){return this.element.getRootNode()}getText(){let t=new Range;return t.selectNodeContents(this.element),fl(this.element,t)}getHTML(){return this.element.innerHTML||""}getRange(){var i;let t=this.getRootNode();if(t.activeElement!==this.element)return null;let n="getSelection"in t?t.getSelection():window.getSelection();if(!n)return null;let r="getComposedRanges"in n&&t instanceof ShadowRoot?(i=n.getComposedRanges(t))==null?void 0:i[0]:n.rangeCount>0?n.getRangeAt(0):null;if(!r)return null;let o=this.element.ownerDocument.createRange();return o.setStart(r==null?void 0:r.startContainer,r==null?void 0:r.startOffset),o.setEnd(r==null?void 0:r.endContainer,r==null?void 0:r.endOffset),!o||!this.element.contains(o.startContainer)||!this.element.contains(o.endContainer)?null:o}getCaretPosition(){let t=this.getRange();if(!t||!t.collapsed||!("getBoundingClientRect"in t))return null;let n=t.getBoundingClientRect();return!l1(n)&&(t.insertNode(this.element.ownerDocument.createTextNode("\u2060")),n=t.getBoundingClientRect(),t.deleteContents(),!l1(n))?null:{top:n.top+n.height,left:n.left}}getSelection(){let t=this.getRange();if(t)return dl(this.element,t);let n=this.lastKnownSelection;if(n&&s1(this.element,n.start,n.end))return n;let r=ss(this.element);return r.collapse(!1),dl(this.element,r)}getSelectedText(){let{start:t,end:n}=this.getSelection();return fl(this.element,Xr(this.element,t,n))}applyChanges(t){var o;if(!this.isActive)return;this.isSettingValue=!0;let n=this.getText(),r=t(this.element);return(o=this.observer)==null||o.takeRecords(),Promise.resolve(r).then(()=>{this.currentText=this.getText(),n!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(){super.listen(),this.observer=new MutationObserver(()=>{setTimeout(()=>{this.triggerChange()},0)}),this.observer.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0});let t=this.element.isContentEditable,n=new MutationObserver(()=>{this.element.isContentEditable!==t&&(t=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});n.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>n.disconnect())}dispose(){super.dispose(),this.observer&&this.observer.disconnect()}};var Vo=class extends ir{lastKnownSelection=null;getText(){return this.element.value}getHTML(){return null}getSelection(){let{selectionStart:t,selectionEnd:n}=this.element;return{start:t,end:n}}getSelectedText(){let t=this.getSelection();return t?this.getText().slice(t.start,t.end):""}getCaretPosition(){return null}applyChanges(t){if(!this.isActive)return;this.isSettingValue=!0;let n=this.getText(),r=t(this.element);return Promise.resolve(r).then(()=>{this.currentText=this.getText(),n!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(){super.listen();let t=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var o;return(o=t==null?void 0:t.get)==null?void 0:o.call(this.element)},set:o=>{var i;(i=t==null?void 0:t.set)==null||i.call(this.element,o),this.triggerChange()}});let n=this.element.disabled,r=new MutationObserver(()=>{this.element.disabled!==n&&(n=this.element.disabled,this.emit(n?"disabled":"enabled"))});r.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>r.disconnect())}};function u1(e,t,n){let r=`deepdesk-iframe-${e}`,o=document.getElementById(r);if(o)return o;let i=document.createElement("iframe"),s=new URL(t);return Object.entries(n).forEach(([a,l])=>{s.searchParams.append(a,l)}),i.style.position="absolute",i.style.left="-999em",i.style.width="0px",i.style.height="0px",i.tabIndex=-1,i.id=r,i.title=`iframe-${e}`,i.src=s.toString(),window.document.body.appendChild(i),i}function IM(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}var ny=class{constructor(t){this.name=t;this.broadcastChannel=new BroadcastChannel(t)}broadcastChannel;disposeHandlers=[];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()}},ry=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.iframe=u1(t,`${this.targetOrigin}/sdk/proxy/proxy.html`,{channel:this.name,host:window.location.origin,debug:"1"}),document.body.appendChild(this.iframe)}iframe;disposeHandlers=[];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()}},oy=class{constructor(t){this.params=t;this.deepdeskUrl=t.deepdeskUrl,this.eventMap=t.eventMap,this.sessionId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}sessionId;deepdeskUrl;channel;defaultChannel;eventMap;get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setSessionId(t){this.sessionId!==t&&(this.cleanup(),V.info("Set sessionId",t),this.sessionId=t,this.channel=this.createChannel(t))}createChannel(t){let n=this.params.createCustomChannel?this.params.createCustomChannel(t):this.isCrossOrigin?new ry(t,this.deepdeskUrl,{debug:!0}):new ny(t),r=o=>{var s,a;if(o.origin!==this.deepdeskUrl)return;let i=IM(o.data);typeof i!="object"||i.type!=="event"||i.channel!==t||(V.info("Received broadcast event",this.sessionId,o),(a=(s=this.eventMap)[i.name])==null||a.call(s,i.payload))};return n.onMessage(r),n}send(t,n,r){var s,a;V.info("Broadcast event",{sessionId:this.sessionId,name:t,payload:n});let o={type:"event",name:t,payload:n};r!==!1&&((a=(s=this.eventMap)[t])==null||a.call(s,n));let i=this.sessionId==="deepdesk-general"?this.defaultChannel:this.channel;i==null||i.postMessage({...o,channel:this.sessionId})}cleanup(t=!1){var n,r;(n=this.channel)==null||n.close(),delete this.channel,t&&((r=this.defaultChannel)==null||r.close(),delete this.defaultChannel)}},c1=oy;var as=class extends Error{constructor(n,r){super(n);this.body=r}name="CustomError"};var iy=e=>new Promise(t=>{setTimeout(t,e)});var ls=class extends as{name="ClientError"},sy=class extends as{name="ServerError"},fn=class e{constructor(t="",n={}){this.baseUrl=t;this.options=n;n.fetch&&(this.fetch=n.fetch)}latestRequestByUrl={};csrfToken;fetch=window.fetch.bind(window);static refreshingToken=null;patchFetch(t){this.fetch=t(this.fetch)}setCsrfToken(t){this.csrfToken=t}request(t,n={}){return new Promise((r,o)=>{let i={isAborted:!1,reject:o},s=`${this.baseUrl}${t}`,a=this.fetch,{abortLatest:l=!1,attempts:u=1,retryDelay:c=500,refreshTokenOn401:f=!0,retryOnError:d=x=>x instanceof TypeError,retryOnResponse:p=x=>x.status>=500,version:y="v1",...v}=n,g={credentials:"include",...v,headers:{"Content-Type":"application/json",...v.headers}};n.method!==void 0&&n.method!=="GET"&&this.csrfToken&&(g.headers={...g.headers,"X-CSRFToken":this.csrfToken}),typeof y=="string"&&(g.headers={...g.headers,"X-Deepdesk-API-Version":y});let m=u,h=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[s]&&l&&(this.latestRequestByUrl[s].isAborted=!0,this.latestRequestByUrl[s].reject(new Error("Aborted"))),this.latestRequestByUrl[s]=i;let S=async()=>(m--,a(s,g).then(async x=>p(x)&&!i.isAborted&&m>0?(await iy(c),S()):x.status===401&&f===!0&&h===!1?(h=!0,await this.refreshToken(),S()):x).catch(async x=>{if(d(x)&&!i.isAborted&&m>0)return await iy(c),S();throw x}));S().then(x=>x.json().catch(()=>null).then(C=>{x.status>=500?o(new sy("Server Error",C)):x.status===401?o(new ls("Unauthorized",C)):x.status===403?o(new ls("Forbidden",C)):x.status===404?o(new ls("Not Found",C)):x.status>=400&&o(new ls("Bad Request",C)),delete this.latestRequestByUrl[s],r(C)})).catch(x=>{o(x)})})}async validateToken(){let{has_valid_access_token:t}=await this.get("/auth/validate");if(!t)return!1;let{is_logged_in:n}=await this.get("/apis/admin/session/validate/",{version:null});return!!n}refreshToken(){return e.refreshingToken||(e.refreshingToken=this.get("/auth/refresh",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{e.refreshingToken=null},1e3*60)})),e.refreshingToken}get(t,n){return this.request(t,n)}post(t,n,r){return this.request(t,{method:"POST",body:JSON.stringify(n),...r})}patch(t,n,r){return this.request(t,{method:"PATCH",body:JSON.stringify(n),...r})}put(t,n,r){return this.request(t,{method:"PUT",body:JSON.stringify(n),...r})}delete(t,n){return this.request(t,{method:"DELETE",...n})}};var LM;(t=>{let e;(l=>(l.SEND_MESSAGE="Send Message",l.HANDLING_TIME="Handling Time",l.START_AUTOFLOW="Start Autoflow",l.ABORT_AUTOFLOW="Abort Autoflow",l.ADD_TO_PERSONAL_COLLECTION="Add to personal collection",l.DELETE_FROM_PERSONAL_COLLECTION="Delete from personal collection"))(e=t.EventType||={})})(LM||={});function sf(e){return{...ne(e),tags:e.tags}}var sr=class e{constructor(t,n={}){this.options=n;this.client=new fn(t,{fetch:n.fetch}),this.client.patchFetch(r=>async(o,i)=>{let s=await r(o,i);return this.handleDeepdeskVersionHeaders(s),s})}latestReceivedDeepdeskVersions={};client;shouldFetchCsrfToken=!0;static exchangeTokenPromise=null;async preflight(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let t=await this.getCsrfToken();this.client.setCsrfToken(t)}return this.options.token?(e.exchangeTokenPromise||(e.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),e.exchangeTokenPromise):Promise.resolve()}async createConversation(t){await this.preflight(),V.info(`Creating conversation for session ${t.sessionId} and agent ${t.agentId}`);let n=await this.client.post("/api/conversations",{...Ie(t),tags:t.tags},{version:"v2"});return sf(n)}async getProfile(t){let n=await this.client.get(`/apis/admin/profiles/${t}/`,{version:null});return ne(n)}async getKnowledgeAssistant(t){let n=await this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{version:null});return ne(n)}async getContentTypes(){let t=await this.client.get("/apis/admin/content-types/",{version:null});return ne(t)}async getPlatformConfig(){let{config:t}=await this.client.get("/platform/config/",{version:null});return ne(t)}async checkUserExists(t){let{exists:n}=await this.client.get(`/apis/admin/users/exists?external_id=${t}`);return n}async getConversationBySessionId(t,n={}){await this.preflight(),V.info(`Getting conversation for session ${t}`);let{attempts:r=1,retryDelay:o=1e3}=n,i=await this.client.get(`/api/conversations/by_session_id/${t}`,{attempts:r,retryDelay:o,retryOnResponse:s=>s.status===404||s.status>=500,version:"v2"});return V.info(`Successfully retrieved conversation ${i.id} for session ${t}`),sf(i)}async isConversationSupported(t,n={}){V.info(`Check if conversation for session ${t} is supported`);let{attempts:r=1,retryDelay:o=1e3}=n;return(await this.client.get(`/api/conversations/by_session_id/${t}/active_profile`,{attempts:r,retryDelay:o,retryOnResponse:s=>s.status===404||s.status>=500,version:"v2"})).has_active_profile}async updateConversation(t,n){let r=Ie(n);n.tags&&(r.tags=n.tags);let o=await this.client.put(`/api/conversations/${t}`,r,{version:"v2"});return sf(o)}async postMessages(t,n){return(await this.client.post(`/api/conversations/${t}/messages`,n.map(o=>({...Ie(o),tags:o.tags})),{version:"v2"})).map(o=>sf(o))}async sendEvent(t,n){let{data:r,...o}=n,i=Object.entries(this.latestReceivedDeepdeskVersions).reduce((s,[a,l])=>({...s,[a]:l}),{});return this.client.post("/api/events",Ie({...i,...o,data:r,name:t}),{version:"v2"})}async sendEventV1(t,n){let r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((o,[i,s])=>({...o,[i]:s}),{});return this.client.post("/api/events",{event:t,data:Ie({...n,...r})})}async getEntities(t){return(await this.client.post("/api/entities",{messages:t.filter(r=>r.text)})).entities}async getSummary(t,n={}){return(await this.client.post("/api/summary",{conversation:{messages:t.filter(o=>o.text&&o.source),agent_id:n.agentId,id:n.externalConversationId},prompt_instruction:n.promptInstruction,model:n.model})).summary}async getTemporaryExchangeToken(){return(await this.client.get("/auth/exchange-token",{version:null})).jwt}async exchangeTokenForAccessCookie(t){return this.client.post("/apis/admin/session/jwt/",{jwt:t},{version:null}).catch(n=>{throw V.warn(`Invalid token '${t}'`),n})}async authenticateWithKey(t,n){await this.preflight(),await this.client.post("/apis/admin/session/api-key/",Ie(n),{version:null,refreshTokenOn401:!1,headers:{apikey:t}})}async getTextSuggestions(t,n={},r){return r==="sticky-messages"?this.getPinnedMessages(t):(await this.client.post(`/api/conversations/${t}/recommend/${r}`,Ie(n),{abortLatest:!0})).map(i=>({...ne(i),text:i.text||i.url||i.message,source:r,type:r})).filter((i,s,a)=>s===a.findIndex(l=>l.text===i.text))}async isLoggedIn(){return await this.preflight(),this.client.validateToken()}async getAutocompleteSuggestions(t,n){return(await this.client.post(`/api/conversations/${t}/autocomplete`,Ie(n),{abortLatest:!0})).map(o=>({score:1,source:o.source,sourceText:o.source_text,text:o.label,trainingJobs:o.training_jobs,searchKeywords:o.search_keywords,type:o.source})).filter((o,i,s)=>i===s.findIndex(a=>a.text===o.text))}async getPinnedMessages(t){let n=await this.client.get(`/api/conversations/${t}/sticky-messages`,{abortLatest:!0});return ne(n).map(r=>({...r,text:r.message,source:"sticky-messages",type:"pinned-message"}))}async getStyleSuggestions(t){let n=await this.client.post("/api/style-suggestions",Ie(t),{abortLatest:!0});return ne(n)}async search(t){let n=await this.client.post(`/api/profiles/${t.profile}/search`,Ie(t),{version:"v2"});return ne(n)}async knowledgeAssist(t,n,r,o={}){let i=await this.client.post(`/api/knowledge-assist/assistants/${r}/search`,Ie({question:t.question,promptInstruction:t.promptInstruction,chatHistory:n.map(s=>({question:s.question,answer:s.answer.answer})),agentId:o.agentId,conversationId:o.conversationId}),{version:"v2"});return ne(i)}async requestLoginByEmail(t){let n=await this.client.post("/apis/admin/session/passwordless/request/",{email:t},{version:null});return ne(n)}async requestPasswordlessToken(){let t=await this.client.get("/apis/admin/session/passwordless/request/",{version:null});return ne(t.token)}async getCsrfToken(){let{token:t}=await this.client.get("/apis/admin/session/csrf/",{version:null});return t}async verifyLoginToken(t){let n=await this.client.post("/apis/admin/session/passwordless/login/",{token:t},{version:null});return ne(n)}async evaluateRule(t,n,r,o={}){let i=new URLSearchParams;o.raiseForFailingConditions&&i.set("raise_for_failing_conditions","true");let s=await this.client.post(`/api/conversations/${n}/rules/${t}/evaluate?${i.toString()}`,r,{version:"v2"});return ne(s.cues)}async translateMessages(t){let n=await this.client.post("/api/translate",Ie(t),{version:"v2"});return ne(n)}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),i=o.match(Cv);if(!n||!i)return;let s=i[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[s];a&&n&&a!==n&&V.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[s]=n})}};var pl=class{constructor(t,n){this.url=t;this.options={timeout:25e3,...n}}eventListeners={};options;timeoutTimer;eventSource;proxyEvent(t){this.eventSource.addEventListener(Ng(t),n=>{let{data:r}=n;try{let o=JSON.parse(r);this.emit(t,ne(o))}catch{V.warn(`Invalid JSON for ${t}: ${r}`)}})}connect(){clearTimeout(this.timeoutTimer);let t=new EventSource(this.url,{withCredentials:!0});this.eventSource=t;let n=!1;t.onopen=()=>{n=!0},t.onerror=()=>{n&&t.readyState===2&&this.connect()},this.timeoutTimer=setTimeout(()=>{t.close(),this.connect()},this.options.timeout),Object.keys(this.eventListeners).forEach(r=>{this.proxyEvent(r)})}disconnect(){var t;clearTimeout(this.timeoutTimer),this.eventListeners={},(t=this.eventSource)==null||t.close()}emit(t,n){this.eventListeners[t]&&this.eventListeners[t].forEach(r=>r(n))}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),this.proxyEvent(t),()=>{this.off(t,n)}}off(t,n){let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}};var OM;(t=>{let e;(i=>(i.Started="Started",i.Aborted="Aborted",i.Completed="Completed"))(e=t.AutoflowSessionState||={})})(OM||={});var ml=class{constructor(t,n={}){this.apiUrl=t;this.client=new fn(t,n)}client;streams={};logger=V;async getCustomMessages(t){let n=await this.client.get(`/sessions/${t}/suggestions`);return ne(n.suggestions)}async sendCustomMessage(t,n){let r=await this.client.post(`/sessions/${t}/messages`,Ie(n));return ne(r)}async answerCustomMessage(t,n){await this.client.post(`/sessions/${t}/answers`,Ie(n))}async getAutoflows(t){let n=await this.client.get(`/sessions/${t}/autoflows`);return ne(n.autoflows)}async startAutoflowSession(t){let n=await this.client.post("/autoflow-sessions",Ie(t));return ne(n)}async stopAutoflowSession(t){await this.client.delete(`/autoflow-sessions/${t}`)}openStream(t){return this.streams[t]||(this.streams[t]=new pl(`${this.apiUrl}/sessions/${t}/events`),this.streams[t].connect()),this.streams[t]}closeStream(t){this.streams[t]||(this.streams[t].disconnect(),delete this.streams[t])}};var d1={startTime:null,stopTime:null},f1=q({name:"handlingTime",initialState:d1,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(ue,()=>d1)}}),{handlingTimeStart:p1,handlingTimeStop:af,handlingTimeReset:m1}=f1.actions,g1=f1.reducer;var h1=(e={})=>{let t={onAuthError:zi(!1),...e};return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var lf={list:{keywordMatches:[]},fetchState:"idle",isInitialRequest:null};var Ko=j("styleSuggestions/getAll",async({text:e},t)=>{var s;let{deepdeskAPI:n}=t.extra,r=t.getState(),{showStyleSuggestions:o}=r.settings,i=(s=r.conversation.current)==null?void 0:s.profileCode;if(!o)return lf.list;if(!i)throw new Error("No current conversation to fetch pinned messages");return n.getStyleSuggestions({profileCode:i,message:e})}),NM=q({name:"styleSuggestions",initialState:lf,reducers:{},extraReducers:e=>{e.addCase(Ko.pending,t=>{t.isInitialRequest=t.isInitialRequest===null,t.fetchState="loading"}).addCase(Ko.rejected,t=>{t.fetchState="error"}).addCase(Ko.fulfilled,(t,n)=>{t.fetchState="done",_r(t.list,n.payload)||(t.list=n.payload)}).addCase(Co,t=>{t.list=lf.list}).addCase(ue,()=>lf)}}),y1=NM.reducer;var v1=(e={})=>{let t,n=!0,r={getStyleSuggestions:Ko,debounce:500,...e};return o=>i=>s=>{var p;let a=o.getState().input.text,l=i(s),u=o.getState();if(u.auth.isLoggedIn!==!0)return l;let{showStyleSuggestions:c}=u.settings;if(!((p=u.conversation.current)==null?void 0:p.id)||!c)return l;let{text:d}=u.input;return d===a&&!n||(clearTimeout(t),d==="")||(t=setTimeout(()=>{n=!1,o.dispatch(r.getStyleSuggestions({text:d}))},e.debounce)),l}};function MM(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end}var S1=(e={})=>{let t={getTextSuggestions:ln,getAutocompleteSuggestions:Xa,debounce:200,check:Ji,...e},n;return r=>o=>i=>{var v;let{input:{userCommitted:s}}=r.getState(),a=o(i),l=r.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:u,showTabCompletion:c}=l.settings,f=(v=l.conversation.current)==null?void 0:v.id,d=i.type===kd.toString();if(!f||!u&&!c)return a;let{input:{userCommitted:p}}=l;return MM(p,s)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let g=Vi(l);g===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(g))},d?0:t.debounce)),a}};var w1=Ko.fulfilled.toString();function _M(e,t){let n=new Set([...t.keywordMatches.map(o=>o.keyword)]),r=[];return n.forEach(o=>{let i=e.keywordMatches.filter(l=>l.keyword===o),s=t.keywordMatches.filter(l=>l.keyword===o),a=s.length-i.length;a<=0||r.push(...s.slice(0,a))}),r}var x1=e=>t=>n=>r=>{var u;if(r.type!==w1){n(r);return}let o=t.getState().styleSuggestions.list;n(r);let i=t.getState(),s=i.styleSuggestions.list,a=(u=i.conversation)==null?void 0:u.current;if(o===s)return;let l=_M(o,s);r.type===w1&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var DM=rc({answer:jC,auth:Vx,autoflows:nT,conversation:Zx,contentTypes:JE,customMessages:dT,passwordlessToken:gT,entities:kC,knowledgeAssistant:FC,handlingTime:g1,info:yE,input:pE,settings:Dx,profile:VC,search:bE,summary:OC,styleSuggestions:y1,ui:gb,rules:RE,textSuggestions:ZC});function E1(e){return Bw({reducer:DM,middleware:t=>[...t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI,deepdeskBrokerAPI:e.deepdeskBrokerAPI}},serializableCheck:!1}),h1(),S1({debounce:200}),v1({debounce:500}),x1(e.deepdeskAPI),...e.middleware?e.middleware:[]],preloadedState:e.preloadedState})}var FM=e=>{var t;return((t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())??"unknown"},HM=e=>t=>n=>r=>{var a;let o=t.getState(),i=kg("inlineSuggestions")(o);switch(r.type){case zi.toString():{!r.payload&&e.emit("logout",void 0);break}case sn.fulfilled.toString():r.payload.length>0&&e.sendEvent("entities found",{conversationId:o.conversation.current.id,data:{entities:r.payload}});break;case Yn.fulfilled.toString():e.sendEvent("conversation summarized",{conversationId:o.conversation.current.id,data:{summary:r.payload.summary}});break;case Qe.toString():e.sendEvent(r.payload.name,{conversationId:((a=r.payload.options)==null?void 0:a.includeConversationData)&&o.conversation.current.id,data:r.payload.data});break;case Bc.toString():e.handleKeyDown(r.payload);break;case Co.toString():e.logSendMessage(r.payload);break;case Vc.toString():e.handleInputChanged(r.payload);break;case $n.fulfilled.toString():e.broadcast(Fg,r.payload,!1),e.emit("cues",r.payload);break;default:break}let s=n(r);switch(r.type){case Co.toString():e.handleAfterSendMessage(r.payload);break;case Za.toString():e.onUpdateShowTabHint(r.payload);break;case af.toString():e.logHandlingTime();break;case Cn.toString():{let{start:l,end:u}=o.input.selection;e.emit("select-suggestion",{type:FM(r.payload.suggestion),...r.payload,replace:r.payload.replace==="selection"?{start:l,end:u}:{start:0,end:u}},{mayApplyChanges:!0}),i&&(t.dispatch(En([])),t.dispatch(Kn()));break}case zc.toString():{let{start:l,end:u}=o.input.selection;e.emit("replace",{...r.payload,replace:r.payload.replace==="selection"?{start:l,end:u}:{start:0,end:u}},{mayApplyChanges:!0});break}case ka.toString():{let l=t.getState(),{text:u,selection:c}=l.input.userCommitted;e.emit("reset",{text:u,selectionAfter:c},{mayApplyChanges:!0});break}case Kc.toString():e.emit("select-image",r.payload,{mayApplyChanges:!0}),e.sendEvent("Image attached",{conversationId:o.conversation.current.id,data:{path:r.payload.suggestion.image,title:r.payload.suggestion.title}});break;case En.toString():{i&&r.payload.length>0&&t.dispatch(Fr(0));break}default:break}return s},C1=HM;function ay(e){return e.toISOString().replace("T"," ").replace("Z","")}function b1(e,t){var o,i,s;let{startTime:n,stopTime:r}=e.handlingTime;if(!n||!r)throw new Error("No startTime and stopTime for handling time metrics");return{conversationId:e.conversation.current.id,clientVersion:t.version,agentId:(o=e.info.agentInfo)==null?void 0:o.agentId,agentName:(i=e.info.agentInfo)==null?void 0:i.agentName,agentEmail:(s=e.info.agentInfo)==null?void 0:s.agentEmail,timeStart:ay(n),timeStop:ay(r)}}function T1(e,t,n){var k,I,L;let{text:r,metrics:{numCharsTyped:o,numCharsPasted:i,numCharsCut:s,numCharsDeleted:a,numPaste:l,agentStartedTypingTimestamp:u,externalTimeTotalSeconds:c,pastes:f,cuts:d,deletions:p,textSuggestions:y,offeredTextSuggestions:v}}=t[e],g=r.length,h=y.reduce((N,{text:z,searchTerm:K})=>N+z.length-(K?K.length:0),0),S=u??Date.now(),x=(Date.now()-S)/1e3+(c||0),C=o/x,T=y.reduce((N,{searchTerm:z})=>N+(z?z.length:0),0);return{conversationId:t.conversation.current.id,source:"agent",text:r,clientVersion:n.version,pastes:f,cuts:d,deletions:p,lenTextTyped:o+T,lenTextTotal:g,lenTextAssisted:h,lenTextPasted:i,lenTextCut:s,lenTextDeleted:a,timeTotalSeconds:x,charsPerSecond:C,numPastes:l,textSuggestionsV2:y,suggestionsCounters:[{source:"gpt",countOffered:v.filter(N=>N.source==="gpt").length}],agentId:(k=t.info.agentInfo)==null?void 0:k.agentId,agentName:(I=t.info.agentInfo)==null?void 0:I.agentName,agentEmail:(L=t.info.agentInfo)==null?void 0:L.agentEmail}}function ly(e,t){var i;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return ly(r,t);let o=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;return o?ly(o,t):null}function k1(e,t){return ly(e,t)}function P1(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function UM(e){return typeof e=="object"&&e!==null&&"tagName"in e}function uf(e){return UM(e)&&(Wr(e)||Md(e))}var R1,kn=new Map,jM=["bottom","height","left","right","top","width"],zM=(e={},t={})=>jM.some(n=>e[n]!==t[n]);function A1(e){var n,r;if(e.ownerDocument===document)return[];let t=((r=(n=e.ownerDocument)==null?void 0:n.defaultView)==null?void 0:r.frameElement)??null;return t?[t,...A1(t)]:[]}function I1(e,t){return!e||!t?null:{...e,top:e.top+t.top,left:e.left+t.left}}var cf=!1,L1=()=>{cf=!0;let e=[];if(kn.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),kn.delete(n);return}let r=n.getBoundingClientRect();zM(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{let n=t.parentRects?t.parentRects.reduce(I1,t.rect):t.rect;t.callbacks.forEach(r=>r(n))}),kn.size===0){cf=!1;return}R1=window.requestAnimationFrame(L1)};function uy(e,t){let n=A1(e),r=[],o=n.map((i,s)=>uy(i,a=>{r[s]=a;let l=kn.get(e);if(!l)return;let u=r.reduce(I1,l.rect);l.callbacks.forEach(c=>c(u))}));return{observe(i=!0){if(o.forEach(s=>s.observe(!1)),kn.has(e)){let s=kn.get(e);s.callbacks.push(t),s.rect&&t(s.rect)}else kn.set(e,{rect:void 0,callbacks:[t],parentRects:r});i&&!cf&&L1()},unobserve(){o.forEach(s=>s.unobserve());let i=kn.get(e);if(i){let s=i.callbacks.indexOf(t);s>=0&&i.callbacks.splice(s,1),i.callbacks.length||kn.delete(e),kn.size||(cancelAnimationFrame(R1),cf=!1)}}}}var O1,Pn=new Map,N1=()=>{Pn.forEach((e,t)=>{if(!t.isConnected){Pn.delete(t);return}let{clientHeight:n,scrollHeight:r}=t,o=r>n;e.visible!==o&&(e.visible=o,e.callbacks.forEach(i=>i(e.visible)))}),Pn.size!==0&&(O1=window.requestAnimationFrame(N1))};function M1(e,t){return{observe(){let n=Pn.size===0;Pn.has(e)?Pn.get(e).callbacks.push(t):Pn.set(e,{visible:void 0,callbacks:[t]}),n&&N1()},unobserve(){let n=Pn.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||Pn.delete(e),Pn.size||cancelAnimationFrame(O1)}}}}var cy=["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 dy(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function us(e){return parseFloat(e)}function df(e){return Math.round(e*1e6)}function _1(e){return e/1e6}function fy(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=us(e.width),i=us(e.borderLeftWidth),s=us(e.borderRightWidth),a=us(e.paddingRight),l=_1(df(o)-df(i)-df(s)),u=_1(df(r));if(l-u>2){let c=l-u;n.style.paddingRight=`${a+c}px`}}function gl(e,t={}){var c;let n=t.overlayContainer||document.createElement("div");n.style.display="none",n.style.position=t.position??"fixed",n.style.pointerEvents="none",n.style.borderColor="transparent",Ho(n);let r=window.getComputedStyle(e),o=!0,i=()=>{n.scrollTop=e.scrollTop};dy(r,n,cy),fy(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",i));let s=M1(e,()=>{dy(r,n,cy),fy(r,e,n),i(),setTimeout(i,0)}),a,l=!0,u=uy(e,f=>{if(f===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),f.height===0&&f.width===0){if(o===!0)return;t.onHide&&t.onHide(),n.style.display="none",o=!0;return}if(dy(r,n,cy),fy(r,e,n),i(),n.style.top=`${f.top}px`,n.style.left=`${f.left}px`,t.closestScrollElement&&t.closestScrollElement!==e){let d=t.closestScrollElement.getBoundingClientRect(),p=window.getComputedStyle(t.closestScrollElement),y=us(p.borderTopWidth),v=us(p.borderBottomWidth),g=d.top+y-f.top,m=f.top+f.height+-(d.top+d.height-v);n.style.clipPath=`inset(${g}px 0px ${m}px 0px)`}o&&(n.style.display="block",t.onShow&&t.onShow(),o=!1)});return t.appendTo?t.appendTo.appendChild(n):(c=e.parentElement)==null||c.appendChild(n),u.observe(),s.observe(),[n,()=>{e.removeEventListener("scroll",i),u.unobserve(),s.unobserve()}]}var D1=(e,t)=>({value(){try{let n=sessionStorage.getItem(`dd-${e}`);if(!n)return t;try{return JSON.parse(n)}catch{return t}}catch{return t}},update(n){try{sessionStorage.setItem(`dd-${e}`,JSON.stringify(n))}catch{V.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function BM(e){return e.offsetParent!==null}function F1(e){if(!BM(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 ff(e,t,n=100){let r=F1(e);t({isVisible:r});let o=setInterval(()=>{let i=F1(e);i!==r&&(r=i,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var Oe=w(b());var H1=D1("showTabHint",!0),hl=class e{static version="11.0.1-beta.2";static count=0;deepdeskApi;inputMediator=null;version;broadcastEvents;eventListeners={};unmountHandlers=[];widgetRoot=null;dynamicThunkObject={};isMounted=!1;instanceId;shouldRender=!0;store;constructor({deepdeskUrl:t,brokerUrl:n,version:r=e.version||"unknown",locale:o="en-US",token:i,fetch:s,productName:a,createCustomChannel:l}){let u=t.replace(/\/api$/,"");this.deepdeskApi=new sr(u,{token:i,fetch:s}),this.version=r,this.instanceId=e.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[C1({broadcast:(f,d,p)=>{this.broadcastEvents.send(f,d,p)},emit:(f,d,p)=>this.emit(f,d,p),handleAfterSendMessage:f=>this.handleAfterSendMessage(f),handleInputChanged:f=>this.handleInputChanged(f),handleKeyDown:f=>this.handleKeyDown(f),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:f=>this.logSendMessage(f),onUpdateShowTabHint:f=>H1.update(f),sendEvent:(f,d)=>this.deepdeskApi.sendEvent(f,d)})]};n&&Object.assign(c,{deepdeskBrokerAPI:new ml(n)}),this.store=E1(c),this.broadcastEvents=new c1({debug:!0,deepdeskUrl:u,eventMap:AE(this.store),createCustomChannel:l}),this.store.dispatch(Za(H1.value())),this.store.dispatch(Oc({locale:o,adminUrl:u,productName:a}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){return this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex]??null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}sessionId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.sessionId}shouldAbort(){return this.state.conversation.isSupported===!1?(V.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(V.warn("Profile has not been loaded (yet)"),!0):(V.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(zi(null)),this.store.dispatch(Bn()),new Promise(t=>{let n=this.store.subscribe(()=>{let r=this.store.getState();nt(r)&&Fx(r)!=="loading"&&(n(),t())});this.unmountHandlers.push(()=>{n()})})}async isLoggedIn(){return(await this.store.dispatch(Bn())).payload}async setPlatformAgentId(t){try{if((await this.deepdeskApi.client.get("/apis/admin/session/me/",{version:null})).external_id)return;await this.deepdeskApi.client.request("/apis/admin/session/me/",{method:"PATCH",body:JSON.stringify({external_id:t}),version:null})}catch(n){V.warn("Failed to attach user:",n)}}async isConversationSupported(t,n){return(await this.store.dispatch(Ig({sessionId:t,options:n}))).payload}async createConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(Dc(t))).payload}async getConversationBySessionId(t,n){return this.hasConversation()&&this.sessionId()!==t&&this.resetConversation(),(await this.store.dispatch(Fc({sessionId:t,options:n}))).payload}async upsertConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(Lg(t))).payload}async postMessages(t){return(await this.store.dispatch(Uc(t))).payload}async updateConversation(t){return(await this.store.dispatch(Hc(t))).payload}resetConversation(){this.store.dispatch(ue()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}async getSummary(){let t=await this.store.dispatch(Yn());if(t.error)throw new Error(t.error.message);return t.payload.summary}configure(t){this.store.dispatch(Oc(t))}setVisitorInfo(t){this.store.dispatch(hE(t))}async setAgentInfo(t){await this.store.dispatch(Pa(t))}async setAgentSettings(t){await this.store.dispatch(Mg(t))}async getAgentSettings(){return(await this.store.dispatch(_g())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let t=[];return this.store.dispatch(kd()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})}notifyInputChanged(t){this.store.dispatch(Vc(t))}notifyKeyDown(t){this.store.dispatch(Bc(t))}notifyPaste(t,n){this.store.dispatch(uE({text:t,selectionText:n}))}notifyCut(t){this.store.dispatch(aE(t))}notifyExternalSuggestion(t){this.store.dispatch(Cn(t)),this.store.dispatch(Kn())}async evaluateRule(t,n={}){let{payload:r,error:o}=await this.store.dispatch($n({label:t,params:n}));if(o)throw o;return r}handleInputChanged(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui;n&&r&&this.store.dispatch(Kr({collapse:!1})),this.inputMediator&&this.store.dispatch(nE({text:t,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(En([])))}handleKeyDown(t){let{overlayCollapsed:n}=this.state.ui,{textSuggestions:r,selectedSuggestionIndex:o,selection:i}=this.state.input,{inlineSuggestions:s}=this.state.settings,a=r.length>0,l=o!==-1;if(this.store.dispatch(lE(Jx(t))),t.key!=="Tab"&&!this.settings.showTextSuggestions)return;let u=()=>{n||!a||i&&(t.shiftKey||(this.store.dispatch(oE()),s||this.stageSelectedSuggestion({inputType:"arrow"}),t.preventDefault()))},c=()=>{n||!a||s&&o<=0||i&&(t.shiftKey||(this.store.dispatch(sE()),t.preventDefault(),!s&&(this.state.input.selectedSuggestionIndex===-1?this.store.dispatch(ka()):this.stageSelectedSuggestion({inputType:"arrow"}))))};switch(t.key){case"Up":case"ArrowUp":s?c():u();return;case"Down":case"ArrowDown":{s?u():c();return}case"Esc":case"Escape":{s&&l&&this.store.dispatch(Fr(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(Fr(-1)),this.store.dispatch(ka()),t.preventDefault()):n||(this.store.dispatch(Kr({collapse:!0})),this.store.dispatch(pb(!0)),t.preventDefault());return}case"Tab":{let{userCommitted:f}=this.state.input,d=f.text.substring(0,f.selection.end),{tabCompletionSuggestion:p}=this.state.input;this.store.dispatch(Za(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):!s&&this.settings.showTabCompletion&&p&&p.text.startsWith(d)&&(this.store.dispatch(Cn({text:p.text,suggestion:p,eventMetrics:{inputType:"tab"},replace:"until-selection-end"})),this.store.dispatch(Kn())),t.preventDefault();break}default:}}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(cE()),this.store.dispatch(En([]))}handlingTimeStart(){this.state.handlingTime.startTime||(V.info("Start handling time"),this.store.dispatch(p1()))}handlingTimeStop(){this.state.handlingTime.startTime&&(V.info("Stop handling time"),this.store.dispatch(af()))}logSendMessage(t){let n=T1("input",this.state,{version:this.version});t&&(Object.assign(n,{text:t}),Object.assign(n,{lenTextTotal:t.length})),this.deepdeskApi.sendEventV1("Send Message",n),this.emit("send-message-event",n)}logHandlingTime(){let t=b1(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",t),this.store.dispatch(m1())}notifySubmit(t={}){this.shouldAbort()||(this.store.dispatch(Kn()),this.store.dispatch(Co(t.text??this.state.input.text)))}stageSelectedSuggestion(t){let n=this.state.input.selectedSuggestionIndex,{textSuggestions:r}=this.state.input;this.store.dispatch(Cn({text:r[n].text,suggestion:r[n],eventMetrics:t,replace:"until-selection-end"}))}emit(t,n,r={}){let o=()=>{this.eventListeners[t]&&this.eventListeners[t].forEach(i=>{try{i(n)}catch(s){V.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),V.error(s)}})};this.inputMediator&&r.mayApplyChanges?this.inputMediator.applyChanges(o):o()}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}whenConversationLoaded(t){let n=()=>this.loadProfileConfig().then(()=>t());this.hasConversation()&&n();let r=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==r&&(r=this.hasConversation(),r&&n())})}overlayContainerFactory(t,n,r,o){let[i,s]=gl(n,r);return i.setAttribute("translate","no"),i.dataset.testid=t,o&&i.classList.add(o),this.unmountHandlers.push(()=>{(0,Wt.unmountComponentAtNode)(i),s(),i.remove()}),i}createInlineContainer(t,n){var s;let r=document.createElement("div");r.style.position="absolute",r.style.top="0px",r.style.left="0px",r.style.height="0px",r.style.width="0px";let o=document.createElement("div");o.style.display="none",o.style.position="absolute",o.style.height="0px",o.style.width="0px",o.style.backgroundColor="red",r.appendChild(o);let i=(s=t.ownerDocument.defaultView)==null?void 0:s.frameElement;if(i){let[a,l]=gl(i,{appendTo:document.body,onMoveStart:()=>{o.style.display="none"}});a.dataset.testid=n,a.style.zIndex="2",a.appendChild(r),this.unmountHandlers.push(()=>{(0,Wt.unmountComponentAtNode)(o),l()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return Ho(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),this.unmountHandlers.push(()=>{(0,Wt.unmountComponentAtNode)(o),o.remove()}),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),V.info(`Stored analytics for ${this.conversationId()}`)}catch{}}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()?(V.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(fE(r.metrics))):V.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(t)}catch{}}mount(t,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!uf(t))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let{customStyles:r={},showStyleSuggestions:o,showTabCompletion:i,showTextSuggestions:s,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,isEmbedded:f,detectSubmit:d,insertLink:p,inputMediator:y,closestScrollSelector:v,appendOverlayTo:g,inlineSuggestions:m,floatingMenu:h}=n;this.configure({showStyleSuggestions:o,showTabCompletion:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,showTextSuggestions:s,insertLink:p,isEmbedded:f,inlineSuggestions:m,floatingMenu:!!h}),n.automaticHandlingTime&&this.setupHandlingTime(t),Ho(t),this.inputMediator=y||(Wr(t)?new Vo(t):new Bo(t)),this.inputMediator.on("change",({plainText:C})=>{this.notifyInputChanged(C)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(dE({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()}))}),this.inputMediator.on("keydown",C=>{this.notifyKeyDown(C)}),this.inputMediator.on("paste",({pastedText:C,selectionText:T})=>{this.notifyPaste(C,T)}),this.inputMediator.on("cut",({selectionText:C})=>{this.notifyCut(C)});let S=v&&k1(t,v)||void 0;if(m){let{customStyles:C,appendOverlayTo:T}=n;if(Wr(t))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let k=this.createInlineContainer(t,"deepdesk-caret");(0,Wt.render)((0,Oe.jsx)(jo,{store:this.store,customStyles:C,children:(0,Oe.jsx)(To,{broadcastEvents:this.broadcastEvents,children:(0,Oe.jsx)(xb,{})})}),k),this.inputMediator.on("caret",L=>{this.store.dispatch(En([])),L?(k.style.display="block",k.style.top=`${L.top}px`,k.style.left=`${L.left}px`):k.style.display="none"});let I=this.overlayContainerFactory("floating-menu",S||t,{appendTo:typeof h=="object"&&"appendOverlayTo"in h?h.appendOverlayTo:T},C==null?void 0:C.floatingMenuRootNode);(0,Wt.render)((0,Oe.jsx)(jo,{store:this.store,customStyles:C,children:(0,Oe.jsx)(To,{broadcastEvents:this.broadcastEvents,children:(0,Oe.jsx)(cb,{onLogIn:()=>this.loginViaPopup().catch(L=>V.warn(L.message))})})}),I)}else{let C=this.overlayContainerFactory("deepdesk-tab-completion",S||t,{appendTo:g,closestScrollElement:S,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),T=this.overlayContainerFactory("deepdesk-suggestions-overlay",S||t,{appendTo:g},r==null?void 0:r.suggestionsRootNode);(0,Wt.render)((0,Oe.jsx)(jo,{store:this.store,customStyles:r,children:(0,Oe.jsx)(To,{broadcastEvents:this.broadcastEvents,children:(0,Oe.jsx)(Xb,{inputElement:t})})}),C),(0,Wt.render)((0,Oe.jsx)(jo,{store:this.store,customStyles:r,children:(0,Oe.jsx)(To,{broadcastEvents:this.broadcastEvents,children:(0,Oe.jsx)(Ib,{onLogIn:()=>this.loginViaPopup().catch(k=>V.warn(k.message))})})}),T)}(0,Wt.render)((0,Oe.jsx)(jo,{store:this.store,customStyles:r,children:(0,Oe.jsx)(To,{broadcastEvents:this.broadcastEvents,children:(0,Oe.jsx)(ib,{})})}),this.createContainer("deepdesk-overlays"));let x;this.inputMediator.on("selection",C=>{clearTimeout(x),C===null?x=setTimeout(()=>{C!==null&&this.store.dispatch(Og(C))},500):this.store.dispatch(Og(C))}),this.inputMediator.on("disabled",()=>{var C;(C=this.inputMediator)==null||C.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{d&&this.notifySubmit()}),this.inputMediator.on("blur",()=>this.store.dispatch(wh(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(wh(!0))),this.store.dispatch(rE({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.unmountHandlers.push(()=>{this.state.input.text!==""&&(this.store.dispatch(Kn()),this.storeMetrics())}),this.whenConversationLoaded(()=>{var C;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((C=this.state.conversation.current)==null?void 0:C.sessionId)}),this.isMounted=!0}unmount(){var t;this.unmountHandlers.forEach(n=>n()),this.unmountHandlers=[],(t=this.inputMediator)==null||t.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(t,n={}){if(this.widgetRoot&&V.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,isEmbedded:i}=n;this.widgetRoot=t,this.configure({showImages:o,isEmbedded:i}),(0,Wt.render)((0,Oe.jsx)(jo,{store:this.store,customStyles:r,children:(0,Oe.jsx)(To,{broadcastEvents:this.broadcastEvents,children:(0,Oe.jsx)(i1,{onLogIn:()=>this.loginViaPopup().catch(s=>V.warn(s.message))})})}),t),this.whenConversationLoaded(()=>{var s;this.broadcastEvents.setSessionId((s=this.state.conversation.current)==null?void 0:s.sessionId)})}unmountWidget(){this.widgetRoot&&(0,Wt.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(t){let n=ff(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){P1(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(Ya());let t=Vr(this.state);t&&(await this.store.dispatch(qa()),this.store.dispatch(Oc({showSearch:t.search,showAutoflows:t.autoflows,showCustomMessages:t.customMessages,showImageSearch:t.imageSearch,showEntitiesCommand:t.entitiesCommand,showSummaryCommand:t.summarizer,showKnowledgeSearch:!!t.knowledgeAssistant,recommendTextSuggestions:t.recommendTextSuggestions})))}),this.loadProfileConfigPromise)}async loginViaPopup(t){return new Promise((n,r)=>{let o=new MessageChannel,i=o.port1,s=this.state.settings.adminUrl,a=new URL(t!=null&&t.url?t==null?void 0:t.url:`${s}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let l=!1,u=()=>{c&&!c.closed&&c.close(),window.removeEventListener("message",f),clearInterval(d)};i.onmessage=async p=>{var y,v;if((y=p.data)!=null&&y.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((v=p.data)==null?void 0:v.jwt),await this.isLoggedIn(),this.broadcastEvents.send(Aa),l=!0,o.port1.close(),n()}catch(g){console.error(g),r(g)}finally{l=!0,u()}};let c=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");c===null&&r(new Error("Popup blocked by browser"));let f=async p=>{var y;if(p.origin===a.origin)switch((y=p.data)==null?void 0:y.type){case"deepdesk-popup-loaded":{try{let v=JSON.stringify({type:"deepdesk-popup-create-channel"});c==null||c.postMessage(v,a.origin,[o.port2])}catch(v){V.error("Error posting message to popup",v),r(v)}break}case"deepdesk-popup-error":{u(),p.data.message==="Timeout"&&V.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(()=>{c&&!c.closed||(u(),l||r(new Error("Popup closed by user")))},200);this.unmountHandlers.push(u)})}translateMessages(t){return this.deepdeskApi.translateMessages(t)}async checkForTrialMode(t){try{let{account:n}=await this.deepdeskApi.getPlatformConfig();if(!n.isTrial){this.shouldRender=!0;return}if(V.info("Trial is active"),!await this.deepdeskApi.checkUserExists(t))throw new Error("User is not in trial");this.shouldRender=!0}catch(n){let{message:r}=n;V.info(r),this.shouldRender=!1}}async refreshWidgetSuggestions(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=bd(this.state);try{n.forEach(({type:r})=>{r==="entities"?this.store.dispatch(sn()):this.store.dispatch(ln(r))})}catch(r){this.handleError(r)}}};async function U1(e,t,n={}){let{value:r}=e,{start:o,end:i}=n.replace??{start:0,end:r.length},s=`${r.slice(0,o)}${t}${r.slice(i)}`,a=n.selectionAfter??{start:o+t.length,end:o+t.length},l=()=>{if(n.setValue)return n.setValue(s);e.value=s};return Promise.resolve(l()).then(()=>{e.selectionStart=a.start,e.selectionEnd=a.end,e.blur(),e.focus()})}async function j1(e,t,n={}){let r=n.replace?Xr(e,n.replace.start,n.replace.end):ss(e),o,i=()=>{if(n.setRange)return n.setRange(r.cloneRange());r.deleteContents(),o=document.createElement("span"),r.insertNode(o),n.insertBRs!==!1?t.split(`
26
+ `);break}default:break}f&&s++}return l(e),a}var a1=(s=>(s.CUT="Cut",s.BACKSPACE="Backspace",s.DELETE="Delete",s.ERASEEOF="EraseEof",s.UNDO="Undo",s.CLEAR="Clear",s))(a1||{}),ir=class{constructor(t){this.element=t;this.currentText=this.getText(),this.currentHTML=this.getHTML(),this.listen()}eventListeners={};disposeHandlers=[];currentText="";currentCaret=null;currentSelection={start:0,end:0};currentHTML="";isFocused=!1;isActive=!0;isSettingValue=!1;isSubmitting=!1;isPossibleClearInputAction=!1;isDisposed=!1;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)}triggerChange(){let t=this.getText(),n=this.getHTML(),r=t!==this.currentText;this.isActive&&(t===""&&this.currentText!==""&&!this.isSettingValue&&!this.isPossibleClearInputAction&&(this.isSubmitting=!0,this.emit("submit")),!this.isSettingValue&&r&&!this.isSubmitting&&this.emit("change",{plainText:t}),r&&(this.currentSelection=this.getSelection()),this.currentText=t,this.isSubmitting=!1,(this.currentHTML!==n||n===null&&r)&&(this.emit("updated",{plainText:t}),this.triggerCaretPosition(),this.currentHTML=n))}triggerSelection(){let t=this.getSelection();(t.start!==this.currentSelection.start||t.end!==this.currentSelection.end)&&(this.currentSelection=t,this.emit("selection",t),this.triggerCaretPosition())}triggerCaretPosition(){let t=this.getCaretPosition();_r(t,this.currentCaret)||(this.currentCaret=t,this.emit("caret",t))}handleKeyUp(t){let{key:n,shiftKey:r}=t;(n==="Enter"&&r===!0||n==="Backspace")&&this.triggerChange(),this.triggerSelection()}handleClick(){this.triggerSelection()}handleFocus(){this.isFocused||this.emit("focus"),this.triggerSelection(),this.isFocused=!0}handleBlur(){this.isPossibleClearInputAction=!1,this.isFocused&&this.emit("blur"),this.isFocused=!1}handleKeyDown(t){let{key:n,ctrlKey:r,metaKey:o}=t;this.isPossibleClearInputAction=Object.values(a1).includes(n)||n.toLowerCase()==="z"&&(r||o),this.emit("keydown",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.triggerChange()),this.addEventListener("change",()=>this.triggerChange()),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.triggerSelection()),document.activeElement===this.element&&setTimeout(()=>{this.handleFocus()},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()}),this.currentSelection=this.getSelection()}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))}activate(){let t=this.isActive===!1;this.isActive=!0,t&&this.triggerChange()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(t=>t()),this.eventListeners={},this.isDisposed=!0}};function l1(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var Bo=class extends ir{observer;lastKnownSelection=null;getRootNode(){return this.element.getRootNode()}getText(){let t=new Range;return t.selectNodeContents(this.element),fl(this.element,t)}getHTML(){return this.element.innerHTML||""}getRange(){var i;let t=this.getRootNode();if(t.activeElement!==this.element)return null;let n="getSelection"in t?t.getSelection():window.getSelection();if(!n)return null;let r="getComposedRanges"in n&&t instanceof ShadowRoot?(i=n.getComposedRanges(t))==null?void 0:i[0]:n.rangeCount>0?n.getRangeAt(0):null;if(!r)return null;let o=this.element.ownerDocument.createRange();return o.setStart(r==null?void 0:r.startContainer,r==null?void 0:r.startOffset),o.setEnd(r==null?void 0:r.endContainer,r==null?void 0:r.endOffset),!o||!this.element.contains(o.startContainer)||!this.element.contains(o.endContainer)?null:o}getCaretPosition(){let t=this.getRange();if(!t||!t.collapsed||!("getBoundingClientRect"in t))return null;let n=t.getBoundingClientRect();return!l1(n)&&(t.insertNode(this.element.ownerDocument.createTextNode("\u2060")),n=t.getBoundingClientRect(),t.deleteContents(),!l1(n))?null:{top:n.top+n.height,left:n.left}}getSelection(){let t=this.getRange();if(t)return dl(this.element,t);let n=this.lastKnownSelection;if(n&&s1(this.element,n.start,n.end))return n;let r=ss(this.element);return r.collapse(!1),dl(this.element,r)}getSelectedText(){let{start:t,end:n}=this.getSelection();return fl(this.element,Xr(this.element,t,n))}applyChanges(t){var o;if(!this.isActive)return;this.isSettingValue=!0;let n=this.getText(),r=t(this.element);return(o=this.observer)==null||o.takeRecords(),Promise.resolve(r).then(()=>{this.currentText=this.getText(),n!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(){super.listen(),this.observer=new MutationObserver(()=>{setTimeout(()=>{this.triggerChange()},0)}),this.observer.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0});let t=this.element.isContentEditable,n=new MutationObserver(()=>{this.element.isContentEditable!==t&&(t=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});n.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>n.disconnect())}dispose(){super.dispose(),this.observer&&this.observer.disconnect()}};var Vo=class extends ir{lastKnownSelection=null;getText(){return this.element.value}getHTML(){return null}getSelection(){let{selectionStart:t,selectionEnd:n}=this.element;return{start:t,end:n}}getSelectedText(){let t=this.getSelection();return t?this.getText().slice(t.start,t.end):""}getCaretPosition(){return null}applyChanges(t){if(!this.isActive)return;this.isSettingValue=!0;let n=this.getText(),r=t(this.element);return Promise.resolve(r).then(()=>{this.currentText=this.getText(),n!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(){super.listen();let t=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var o;return(o=t==null?void 0:t.get)==null?void 0:o.call(this.element)},set:o=>{var i;(i=t==null?void 0:t.set)==null||i.call(this.element,o),this.triggerChange()}});let n=this.element.disabled,r=new MutationObserver(()=>{this.element.disabled!==n&&(n=this.element.disabled,this.emit(n?"disabled":"enabled"))});r.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>r.disconnect())}};function u1(e,t,n){let r=`deepdesk-iframe-${e}`,o=document.getElementById(r);if(o)return o;let i=document.createElement("iframe"),s=new URL(t);return Object.entries(n).forEach(([a,l])=>{s.searchParams.append(a,l)}),i.style.position="absolute",i.style.left="-999em",i.style.width="0px",i.style.height="0px",i.tabIndex=-1,i.id=r,i.title=`iframe-${e}`,i.src=s.toString(),window.document.body.appendChild(i),i}function IM(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}var ny=class{constructor(t){this.name=t;this.broadcastChannel=new BroadcastChannel(t)}broadcastChannel;disposeHandlers=[];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()}},ry=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.iframe=u1(t,`${this.targetOrigin}/sdk/proxy/proxy.html`,{channel:this.name,host:window.location.origin,debug:"1"}),document.body.appendChild(this.iframe)}iframe;disposeHandlers=[];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()}},oy=class{constructor(t){this.params=t;this.deepdeskUrl=t.deepdeskUrl,this.eventMap=t.eventMap,this.sessionId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}sessionId;deepdeskUrl;channel;defaultChannel;eventMap;get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setSessionId(t){this.sessionId!==t&&(this.cleanup(),V.info("Set sessionId",t),this.sessionId=t,this.channel=this.createChannel(t))}createChannel(t){let n=this.params.createCustomChannel?this.params.createCustomChannel(t):this.isCrossOrigin?new ry(t,this.deepdeskUrl,{debug:!0}):new ny(t),r=o=>{var s,a;if(o.origin!==this.deepdeskUrl)return;let i=IM(o.data);typeof i!="object"||i.type!=="event"||i.channel!==t||(V.info("Received broadcast event",this.sessionId,o),(a=(s=this.eventMap)[i.name])==null||a.call(s,i.payload))};return n.onMessage(r),n}send(t,n,r){var s,a;V.info("Broadcast event",{sessionId:this.sessionId,name:t,payload:n});let o={type:"event",name:t,payload:n};r!==!1&&((a=(s=this.eventMap)[t])==null||a.call(s,n));let i=this.sessionId==="deepdesk-general"?this.defaultChannel:this.channel;i==null||i.postMessage({...o,channel:this.sessionId})}cleanup(t=!1){var n,r;(n=this.channel)==null||n.close(),delete this.channel,t&&((r=this.defaultChannel)==null||r.close(),delete this.defaultChannel)}},c1=oy;var as=class extends Error{constructor(n,r){super(n);this.body=r}name="CustomError"};var iy=e=>new Promise(t=>{setTimeout(t,e)});var ls=class extends as{name="ClientError"},sy=class extends as{name="ServerError"},fn=class e{constructor(t="",n={}){this.baseUrl=t;this.options=n;n.fetch&&(this.fetch=n.fetch)}latestRequestByUrl={};csrfToken;fetch=window.fetch.bind(window);static refreshingToken=null;patchFetch(t){this.fetch=t(this.fetch)}setCsrfToken(t){this.csrfToken=t}request(t,n={}){return new Promise((r,o)=>{let i={isAborted:!1,reject:o},s=`${this.baseUrl}${t}`,a=this.fetch,{abortLatest:l=!1,attempts:u=1,retryDelay:c=500,refreshTokenOn401:f=!0,retryOnError:d=x=>x instanceof TypeError,retryOnResponse:p=x=>x.status>=500,version:y="v1",...v}=n,g={credentials:"include",...v,headers:{"Content-Type":"application/json",...v.headers}};n.method!==void 0&&n.method!=="GET"&&this.csrfToken&&(g.headers={...g.headers,"X-CSRFToken":this.csrfToken}),typeof y=="string"&&(g.headers={...g.headers,"X-Deepdesk-API-Version":y});let m=u,h=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[s]&&l&&(this.latestRequestByUrl[s].isAborted=!0,this.latestRequestByUrl[s].reject(new Error("Aborted"))),this.latestRequestByUrl[s]=i;let S=async()=>(m--,a(s,g).then(async x=>p(x)&&!i.isAborted&&m>0?(await iy(c),S()):x.status===401&&f===!0&&h===!1?(h=!0,await this.refreshToken(),S()):x).catch(async x=>{if(d(x)&&!i.isAborted&&m>0)return await iy(c),S();throw x}));S().then(x=>x.json().catch(()=>null).then(C=>{x.status>=500?o(new sy("Server Error",C)):x.status===401?o(new ls("Unauthorized",C)):x.status===403?o(new ls("Forbidden",C)):x.status===404?o(new ls("Not Found",C)):x.status>=400&&o(new ls("Bad Request",C)),delete this.latestRequestByUrl[s],r(C)})).catch(x=>{o(x)})})}async validateToken(){let{has_valid_access_token:t}=await this.get("/auth/validate");if(!t)return!1;let{is_logged_in:n}=await this.get("/apis/admin/session/validate/",{version:null});return!!n}refreshToken(){return e.refreshingToken||(e.refreshingToken=this.get("/auth/refresh",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{e.refreshingToken=null},1e3*60)})),e.refreshingToken}get(t,n){return this.request(t,n)}post(t,n,r){return this.request(t,{method:"POST",body:JSON.stringify(n),...r})}patch(t,n,r){return this.request(t,{method:"PATCH",body:JSON.stringify(n),...r})}put(t,n,r){return this.request(t,{method:"PUT",body:JSON.stringify(n),...r})}delete(t,n){return this.request(t,{method:"DELETE",...n})}};var LM;(t=>{let e;(l=>(l.SEND_MESSAGE="Send Message",l.HANDLING_TIME="Handling Time",l.START_AUTOFLOW="Start Autoflow",l.ABORT_AUTOFLOW="Abort Autoflow",l.ADD_TO_PERSONAL_COLLECTION="Add to personal collection",l.DELETE_FROM_PERSONAL_COLLECTION="Delete from personal collection"))(e=t.EventType||={})})(LM||={});function sf(e){return{...ne(e),tags:e.tags}}var sr=class e{constructor(t,n={}){this.options=n;this.client=new fn(t,{fetch:n.fetch}),this.client.patchFetch(r=>async(o,i)=>{let s=await r(o,i);return this.handleDeepdeskVersionHeaders(s),s})}latestReceivedDeepdeskVersions={};client;shouldFetchCsrfToken=!0;static exchangeTokenPromise=null;async preflight(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let t=await this.getCsrfToken();this.client.setCsrfToken(t)}return this.options.token?(e.exchangeTokenPromise||(e.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),e.exchangeTokenPromise):Promise.resolve()}async createConversation(t){await this.preflight(),V.info(`Creating conversation for session ${t.sessionId} and agent ${t.agentId}`);let n=await this.client.post("/api/conversations",{...Ie(t),tags:t.tags},{version:"v2"});return sf(n)}async getProfile(t){let n=await this.client.get(`/apis/admin/profiles/${t}/`,{version:null});return ne(n)}async getKnowledgeAssistant(t){let n=await this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{version:null});return ne(n)}async getContentTypes(){let t=await this.client.get("/apis/admin/content-types/",{version:null});return ne(t)}async getPlatformConfig(){let{config:t}=await this.client.get("/platform/config/",{version:null});return ne(t)}async checkUserExists(t){let{exists:n}=await this.client.get(`/apis/admin/users/exists?external_id=${t}`);return n}async getConversationBySessionId(t,n={}){await this.preflight(),V.info(`Getting conversation for session ${t}`);let{attempts:r=1,retryDelay:o=1e3}=n,i=await this.client.get(`/api/conversations/by_session_id/${t}`,{attempts:r,retryDelay:o,retryOnResponse:s=>s.status===404||s.status>=500,version:"v2"});return V.info(`Successfully retrieved conversation ${i.id} for session ${t}`),sf(i)}async isConversationSupported(t,n={}){V.info(`Check if conversation for session ${t} is supported`);let{attempts:r=1,retryDelay:o=1e3}=n;return(await this.client.get(`/api/conversations/by_session_id/${t}/active_profile`,{attempts:r,retryDelay:o,retryOnResponse:s=>s.status===404||s.status>=500,version:"v2"})).has_active_profile}async updateConversation(t,n){let r=Ie(n);n.tags&&(r.tags=n.tags);let o=await this.client.put(`/api/conversations/${t}`,r,{version:"v2"});return sf(o)}async postMessages(t,n){return(await this.client.post(`/api/conversations/${t}/messages`,n.map(o=>({...Ie(o),tags:o.tags})),{version:"v2"})).map(o=>sf(o))}async sendEvent(t,n){let{data:r,...o}=n,i=Object.entries(this.latestReceivedDeepdeskVersions).reduce((s,[a,l])=>({...s,[a]:l}),{});return this.client.post("/api/events",Ie({...i,...o,data:r,name:t}),{version:"v2"})}async sendEventV1(t,n){let r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((o,[i,s])=>({...o,[i]:s}),{});return this.client.post("/api/events",{event:t,data:Ie({...n,...r})})}async getEntities(t){return(await this.client.post("/api/entities",{messages:t.filter(r=>r.text)})).entities}async getSummary(t,n={}){return(await this.client.post("/api/summary",{conversation:{messages:t.filter(o=>o.text&&o.source),agent_id:n.agentId,id:n.externalConversationId},prompt_instruction:n.promptInstruction,model:n.model})).summary}async getTemporaryExchangeToken(){return(await this.client.get("/auth/exchange-token",{version:null})).jwt}async exchangeTokenForAccessCookie(t){return this.client.post("/apis/admin/session/jwt/",{jwt:t},{version:null}).catch(n=>{throw V.warn(`Invalid token '${t}'`),n})}async authenticateWithKey(t,n){await this.preflight(),await this.client.post("/apis/admin/session/api-key/",Ie(n),{version:null,refreshTokenOn401:!1,headers:{apikey:t}})}async getTextSuggestions(t,n={},r){return r==="sticky-messages"?this.getPinnedMessages(t):(await this.client.post(`/api/conversations/${t}/recommend/${r}`,Ie(n),{abortLatest:!0})).map(i=>({...ne(i),text:i.text||i.url||i.message,source:r,type:r})).filter((i,s,a)=>s===a.findIndex(l=>l.text===i.text))}async isLoggedIn(){return await this.preflight(),this.client.validateToken()}async getAutocompleteSuggestions(t,n){return(await this.client.post(`/api/conversations/${t}/autocomplete`,Ie(n),{abortLatest:!0})).map(o=>({score:1,source:o.source,sourceText:o.source_text,text:o.label,trainingJobs:o.training_jobs,searchKeywords:o.search_keywords,type:o.source})).filter((o,i,s)=>i===s.findIndex(a=>a.text===o.text))}async getPinnedMessages(t){let n=await this.client.get(`/api/conversations/${t}/sticky-messages`,{abortLatest:!0});return ne(n).map(r=>({...r,text:r.message,source:"sticky-messages",type:"pinned-message"}))}async getStyleSuggestions(t){let n=await this.client.post("/api/style-suggestions",Ie(t),{abortLatest:!0});return ne(n)}async search(t){let n=await this.client.post(`/api/profiles/${t.profile}/search`,Ie(t),{version:"v2"});return ne(n)}async knowledgeAssist(t,n,r,o={}){let i=await this.client.post(`/api/knowledge-assist/assistants/${r}/search`,Ie({question:t.question,promptInstruction:t.promptInstruction,chatHistory:n.map(s=>({question:s.question,answer:s.answer.answer})),agentId:o.agentId,conversationId:o.conversationId}),{version:"v2"});return ne(i)}async requestLoginByEmail(t){let n=await this.client.post("/apis/admin/session/passwordless/request/",{email:t},{version:null});return ne(n)}async requestPasswordlessToken(){let t=await this.client.get("/apis/admin/session/passwordless/request/",{version:null});return ne(t.token)}async getCsrfToken(){let{token:t}=await this.client.get("/apis/admin/session/csrf/",{version:null});return t}async verifyLoginToken(t){let n=await this.client.post("/apis/admin/session/passwordless/login/",{token:t},{version:null});return ne(n)}async evaluateRule(t,n,r,o={}){let i=new URLSearchParams;o.raiseForFailingConditions&&i.set("raise_for_failing_conditions","true");let s=await this.client.post(`/api/conversations/${n}/rules/${t}/evaluate?${i.toString()}`,r,{version:"v2"});return ne(s.cues)}async translateMessages(t){let n=await this.client.post("/api/translate",Ie(t),{version:"v2"});return ne(n)}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),i=o.match(Cv);if(!n||!i)return;let s=i[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[s];a&&n&&a!==n&&V.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[s]=n})}};var pl=class{constructor(t,n){this.url=t;this.options={timeout:25e3,...n}}eventListeners={};options;timeoutTimer;eventSource;proxyEvent(t){this.eventSource.addEventListener(Ng(t),n=>{let{data:r}=n;try{let o=JSON.parse(r);this.emit(t,ne(o))}catch{V.warn(`Invalid JSON for ${t}: ${r}`)}})}connect(){clearTimeout(this.timeoutTimer);let t=new EventSource(this.url,{withCredentials:!0});this.eventSource=t;let n=!1;t.onopen=()=>{n=!0},t.onerror=()=>{n&&t.readyState===2&&this.connect()},this.timeoutTimer=setTimeout(()=>{t.close(),this.connect()},this.options.timeout),Object.keys(this.eventListeners).forEach(r=>{this.proxyEvent(r)})}disconnect(){var t;clearTimeout(this.timeoutTimer),this.eventListeners={},(t=this.eventSource)==null||t.close()}emit(t,n){this.eventListeners[t]&&this.eventListeners[t].forEach(r=>r(n))}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),this.proxyEvent(t),()=>{this.off(t,n)}}off(t,n){let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}};var OM;(t=>{let e;(i=>(i.Started="Started",i.Aborted="Aborted",i.Completed="Completed"))(e=t.AutoflowSessionState||={})})(OM||={});var ml=class{constructor(t,n={}){this.apiUrl=t;this.client=new fn(t,n)}client;streams={};logger=V;async getCustomMessages(t){let n=await this.client.get(`/sessions/${t}/suggestions`);return ne(n.suggestions)}async sendCustomMessage(t,n){let r=await this.client.post(`/sessions/${t}/messages`,Ie(n));return ne(r)}async answerCustomMessage(t,n){await this.client.post(`/sessions/${t}/answers`,Ie(n))}async getAutoflows(t){let n=await this.client.get(`/sessions/${t}/autoflows`);return ne(n.autoflows)}async startAutoflowSession(t){let n=await this.client.post("/autoflow-sessions",Ie(t));return ne(n)}async stopAutoflowSession(t){await this.client.delete(`/autoflow-sessions/${t}`)}openStream(t){return this.streams[t]||(this.streams[t]=new pl(`${this.apiUrl}/sessions/${t}/events`),this.streams[t].connect()),this.streams[t]}closeStream(t){this.streams[t]||(this.streams[t].disconnect(),delete this.streams[t])}};var d1={startTime:null,stopTime:null},f1=q({name:"handlingTime",initialState:d1,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(ue,()=>d1)}}),{handlingTimeStart:p1,handlingTimeStop:af,handlingTimeReset:m1}=f1.actions,g1=f1.reducer;var h1=(e={})=>{let t={onAuthError:zi(!1),...e};return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var lf={list:{keywordMatches:[]},fetchState:"idle",isInitialRequest:null};var Ko=j("styleSuggestions/getAll",async({text:e},t)=>{var s;let{deepdeskAPI:n}=t.extra,r=t.getState(),{showStyleSuggestions:o}=r.settings,i=(s=r.conversation.current)==null?void 0:s.profileCode;if(!o)return lf.list;if(!i)throw new Error("No current conversation to fetch pinned messages");return n.getStyleSuggestions({profileCode:i,message:e})}),NM=q({name:"styleSuggestions",initialState:lf,reducers:{},extraReducers:e=>{e.addCase(Ko.pending,t=>{t.isInitialRequest=t.isInitialRequest===null,t.fetchState="loading"}).addCase(Ko.rejected,t=>{t.fetchState="error"}).addCase(Ko.fulfilled,(t,n)=>{t.fetchState="done",_r(t.list,n.payload)||(t.list=n.payload)}).addCase(Co,t=>{t.list=lf.list}).addCase(ue,()=>lf)}}),y1=NM.reducer;var v1=(e={})=>{let t,n=!0,r={getStyleSuggestions:Ko,debounce:500,...e};return o=>i=>s=>{var p;let a=o.getState().input.text,l=i(s),u=o.getState();if(u.auth.isLoggedIn!==!0)return l;let{showStyleSuggestions:c}=u.settings;if(!((p=u.conversation.current)==null?void 0:p.id)||!c)return l;let{text:d}=u.input;return d===a&&!n||(clearTimeout(t),d==="")||(t=setTimeout(()=>{n=!1,o.dispatch(r.getStyleSuggestions({text:d}))},e.debounce)),l}};function MM(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end}var S1=(e={})=>{let t={getTextSuggestions:ln,getAutocompleteSuggestions:Xa,debounce:200,check:Ji,...e},n;return r=>o=>i=>{var v;let{input:{userCommitted:s}}=r.getState(),a=o(i),l=r.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:u,showTabCompletion:c}=l.settings,f=(v=l.conversation.current)==null?void 0:v.id,d=i.type===kd.toString();if(!f||!u&&!c)return a;let{input:{userCommitted:p}}=l;return MM(p,s)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let g=Vi(l);g===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(g))},d?0:t.debounce)),a}};var w1=Ko.fulfilled.toString();function _M(e,t){let n=new Set([...t.keywordMatches.map(o=>o.keyword)]),r=[];return n.forEach(o=>{let i=e.keywordMatches.filter(l=>l.keyword===o),s=t.keywordMatches.filter(l=>l.keyword===o),a=s.length-i.length;a<=0||r.push(...s.slice(0,a))}),r}var x1=e=>t=>n=>r=>{var u;if(r.type!==w1){n(r);return}let o=t.getState().styleSuggestions.list;n(r);let i=t.getState(),s=i.styleSuggestions.list,a=(u=i.conversation)==null?void 0:u.current;if(o===s)return;let l=_M(o,s);r.type===w1&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var DM=rc({answer:jC,auth:Vx,autoflows:nT,conversation:Zx,contentTypes:JE,customMessages:dT,passwordlessToken:gT,entities:kC,knowledgeAssistant:FC,handlingTime:g1,info:yE,input:pE,settings:Dx,profile:VC,search:bE,summary:OC,styleSuggestions:y1,ui:gb,rules:RE,textSuggestions:ZC});function E1(e){return Bw({reducer:DM,middleware:t=>[...t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI,deepdeskBrokerAPI:e.deepdeskBrokerAPI}},serializableCheck:!1}),h1(),S1({debounce:200}),v1({debounce:500}),x1(e.deepdeskAPI),...e.middleware?e.middleware:[]],preloadedState:e.preloadedState})}var FM=e=>{var t;return((t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())??"unknown"},HM=e=>t=>n=>r=>{var a;let o=t.getState(),i=kg("inlineSuggestions")(o);switch(r.type){case zi.toString():{!r.payload&&e.emit("logout",void 0);break}case sn.fulfilled.toString():r.payload.length>0&&e.sendEvent("entities found",{conversationId:o.conversation.current.id,data:{entities:r.payload}});break;case Yn.fulfilled.toString():e.sendEvent("conversation summarized",{conversationId:o.conversation.current.id,data:{summary:r.payload.summary}});break;case Qe.toString():e.sendEvent(r.payload.name,{conversationId:((a=r.payload.options)==null?void 0:a.includeConversationData)&&o.conversation.current.id,data:r.payload.data});break;case Bc.toString():e.handleKeyDown(r.payload);break;case Co.toString():e.logSendMessage(r.payload);break;case Vc.toString():e.handleInputChanged(r.payload);break;case $n.fulfilled.toString():e.broadcast(Fg,r.payload,!1),e.emit("cues",r.payload);break;default:break}let s=n(r);switch(r.type){case Co.toString():e.handleAfterSendMessage(r.payload);break;case Za.toString():e.onUpdateShowTabHint(r.payload);break;case af.toString():e.logHandlingTime();break;case Cn.toString():{let{start:l,end:u}=o.input.selection;e.emit("select-suggestion",{type:FM(r.payload.suggestion),...r.payload,replace:r.payload.replace==="selection"?{start:l,end:u}:{start:0,end:u}},{mayApplyChanges:!0}),i&&(t.dispatch(En([])),t.dispatch(Kn()));break}case zc.toString():{let{start:l,end:u}=o.input.selection;e.emit("replace",{...r.payload,replace:r.payload.replace==="selection"?{start:l,end:u}:{start:0,end:u}},{mayApplyChanges:!0});break}case ka.toString():{let l=t.getState(),{text:u,selection:c}=l.input.userCommitted;e.emit("reset",{text:u,selectionAfter:c},{mayApplyChanges:!0});break}case Kc.toString():e.emit("select-image",r.payload,{mayApplyChanges:!0}),e.sendEvent("Image attached",{conversationId:o.conversation.current.id,data:{path:r.payload.suggestion.image,title:r.payload.suggestion.title}});break;case En.toString():{i&&r.payload.length>0&&t.dispatch(Fr(0));break}default:break}return s},C1=HM;function ay(e){return e.toISOString().replace("T"," ").replace("Z","")}function b1(e,t){var o,i,s;let{startTime:n,stopTime:r}=e.handlingTime;if(!n||!r)throw new Error("No startTime and stopTime for handling time metrics");return{conversationId:e.conversation.current.id,clientVersion:t.version,agentId:(o=e.info.agentInfo)==null?void 0:o.agentId,agentName:(i=e.info.agentInfo)==null?void 0:i.agentName,agentEmail:(s=e.info.agentInfo)==null?void 0:s.agentEmail,timeStart:ay(n),timeStop:ay(r)}}function T1(e,t,n){var k,I,L;let{text:r,metrics:{numCharsTyped:o,numCharsPasted:i,numCharsCut:s,numCharsDeleted:a,numPaste:l,agentStartedTypingTimestamp:u,externalTimeTotalSeconds:c,pastes:f,cuts:d,deletions:p,textSuggestions:y,offeredTextSuggestions:v}}=t[e],g=r.length,h=y.reduce((N,{text:z,searchTerm:K})=>N+z.length-(K?K.length:0),0),S=u??Date.now(),x=(Date.now()-S)/1e3+(c||0),C=o/x,T=y.reduce((N,{searchTerm:z})=>N+(z?z.length:0),0);return{conversationId:t.conversation.current.id,source:"agent",text:r,clientVersion:n.version,pastes:f,cuts:d,deletions:p,lenTextTyped:o+T,lenTextTotal:g,lenTextAssisted:h,lenTextPasted:i,lenTextCut:s,lenTextDeleted:a,timeTotalSeconds:x,charsPerSecond:C,numPastes:l,textSuggestionsV2:y,suggestionsCounters:[{source:"gpt",countOffered:v.filter(N=>N.source==="gpt").length}],agentId:(k=t.info.agentInfo)==null?void 0:k.agentId,agentName:(I=t.info.agentInfo)==null?void 0:I.agentName,agentEmail:(L=t.info.agentInfo)==null?void 0:L.agentEmail}}function ly(e,t){var i;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return ly(r,t);let o=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;return o?ly(o,t):null}function k1(e,t){return ly(e,t)}function P1(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function UM(e){return typeof e=="object"&&e!==null&&"tagName"in e}function uf(e){return UM(e)&&(Wr(e)||Md(e))}var R1,kn=new Map,jM=["bottom","height","left","right","top","width"],zM=(e={},t={})=>jM.some(n=>e[n]!==t[n]);function A1(e){var n,r;if(e.ownerDocument===document)return[];let t=((r=(n=e.ownerDocument)==null?void 0:n.defaultView)==null?void 0:r.frameElement)??null;return t?[t,...A1(t)]:[]}function I1(e,t){return!e||!t?null:{...e,top:e.top+t.top,left:e.left+t.left}}var cf=!1,L1=()=>{cf=!0;let e=[];if(kn.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),kn.delete(n);return}let r=n.getBoundingClientRect();zM(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{let n=t.parentRects?t.parentRects.reduce(I1,t.rect):t.rect;t.callbacks.forEach(r=>r(n))}),kn.size===0){cf=!1;return}R1=window.requestAnimationFrame(L1)};function uy(e,t){let n=A1(e),r=[],o=n.map((i,s)=>uy(i,a=>{r[s]=a;let l=kn.get(e);if(!l)return;let u=r.reduce(I1,l.rect);l.callbacks.forEach(c=>c(u))}));return{observe(i=!0){if(o.forEach(s=>s.observe(!1)),kn.has(e)){let s=kn.get(e);s.callbacks.push(t),s.rect&&t(s.rect)}else kn.set(e,{rect:void 0,callbacks:[t],parentRects:r});i&&!cf&&L1()},unobserve(){o.forEach(s=>s.unobserve());let i=kn.get(e);if(i){let s=i.callbacks.indexOf(t);s>=0&&i.callbacks.splice(s,1),i.callbacks.length||kn.delete(e),kn.size||(cancelAnimationFrame(R1),cf=!1)}}}}var O1,Pn=new Map,N1=()=>{Pn.forEach((e,t)=>{if(!t.isConnected){Pn.delete(t);return}let{clientHeight:n,scrollHeight:r}=t,o=r>n;e.visible!==o&&(e.visible=o,e.callbacks.forEach(i=>i(e.visible)))}),Pn.size!==0&&(O1=window.requestAnimationFrame(N1))};function M1(e,t){return{observe(){let n=Pn.size===0;Pn.has(e)?Pn.get(e).callbacks.push(t):Pn.set(e,{visible:void 0,callbacks:[t]}),n&&N1()},unobserve(){let n=Pn.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||Pn.delete(e),Pn.size||cancelAnimationFrame(O1)}}}}var cy=["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 dy(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function us(e){return parseFloat(e)}function df(e){return Math.round(e*1e6)}function _1(e){return e/1e6}function fy(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=us(e.width),i=us(e.borderLeftWidth),s=us(e.borderRightWidth),a=us(e.paddingRight),l=_1(df(o)-df(i)-df(s)),u=_1(df(r));if(l-u>2){let c=l-u;n.style.paddingRight=`${a+c}px`}}function gl(e,t={}){var c;let n=t.overlayContainer||document.createElement("div");n.style.display="none",n.style.position=t.position??"fixed",n.style.pointerEvents="none",n.style.borderColor="transparent",Ho(n);let r=window.getComputedStyle(e),o=!0,i=()=>{n.scrollTop=e.scrollTop};dy(r,n,cy),fy(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",i));let s=M1(e,()=>{dy(r,n,cy),fy(r,e,n),i(),setTimeout(i,0)}),a,l=!0,u=uy(e,f=>{if(f===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),f.height===0&&f.width===0){if(o===!0)return;t.onHide&&t.onHide(),n.style.display="none",o=!0;return}if(dy(r,n,cy),fy(r,e,n),i(),n.style.top=`${f.top}px`,n.style.left=`${f.left}px`,t.closestScrollElement&&t.closestScrollElement!==e){let d=t.closestScrollElement.getBoundingClientRect(),p=window.getComputedStyle(t.closestScrollElement),y=us(p.borderTopWidth),v=us(p.borderBottomWidth),g=d.top+y-f.top,m=f.top+f.height+-(d.top+d.height-v);n.style.clipPath=`inset(${g}px 0px ${m}px 0px)`}o&&(n.style.display="block",t.onShow&&t.onShow(),o=!1)});return t.appendTo?t.appendTo.appendChild(n):(c=e.parentElement)==null||c.appendChild(n),u.observe(),s.observe(),[n,()=>{e.removeEventListener("scroll",i),u.unobserve(),s.unobserve()}]}var D1=(e,t)=>({value(){try{let n=sessionStorage.getItem(`dd-${e}`);if(!n)return t;try{return JSON.parse(n)}catch{return t}}catch{return t}},update(n){try{sessionStorage.setItem(`dd-${e}`,JSON.stringify(n))}catch{V.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function BM(e){return e.offsetParent!==null}function F1(e){if(!BM(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 ff(e,t,n=100){let r=F1(e);t({isVisible:r});let o=setInterval(()=>{let i=F1(e);i!==r&&(r=i,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var Oe=w(b());var H1=D1("showTabHint",!0),hl=class e{static version="11.1.0";static count=0;deepdeskApi;inputMediator=null;version;broadcastEvents;eventListeners={};unmountHandlers=[];widgetRoot=null;dynamicThunkObject={};isMounted=!1;instanceId;shouldRender=!0;store;constructor({deepdeskUrl:t,brokerUrl:n,version:r=e.version||"unknown",locale:o="en-US",token:i,fetch:s,productName:a,createCustomChannel:l}){let u=t.replace(/\/api$/,"");this.deepdeskApi=new sr(u,{token:i,fetch:s}),this.version=r,this.instanceId=e.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[C1({broadcast:(f,d,p)=>{this.broadcastEvents.send(f,d,p)},emit:(f,d,p)=>this.emit(f,d,p),handleAfterSendMessage:f=>this.handleAfterSendMessage(f),handleInputChanged:f=>this.handleInputChanged(f),handleKeyDown:f=>this.handleKeyDown(f),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:f=>this.logSendMessage(f),onUpdateShowTabHint:f=>H1.update(f),sendEvent:(f,d)=>this.deepdeskApi.sendEvent(f,d)})]};n&&Object.assign(c,{deepdeskBrokerAPI:new ml(n)}),this.store=E1(c),this.broadcastEvents=new c1({debug:!0,deepdeskUrl:u,eventMap:AE(this.store),createCustomChannel:l}),this.store.dispatch(Za(H1.value())),this.store.dispatch(Oc({locale:o,adminUrl:u,productName:a}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){return this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex]??null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}sessionId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.sessionId}shouldAbort(){return this.state.conversation.isSupported===!1?(V.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(V.warn("Profile has not been loaded (yet)"),!0):(V.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(zi(null)),this.store.dispatch(Bn()),new Promise(t=>{let n=this.store.subscribe(()=>{let r=this.store.getState();nt(r)&&Fx(r)!=="loading"&&(n(),t())});this.unmountHandlers.push(()=>{n()})})}async isLoggedIn(){return(await this.store.dispatch(Bn())).payload}async setPlatformAgentId(t){try{if((await this.deepdeskApi.client.get("/apis/admin/session/me/",{version:null})).external_id)return;await this.deepdeskApi.client.request("/apis/admin/session/me/",{method:"PATCH",body:JSON.stringify({external_id:t}),version:null})}catch(n){V.warn("Failed to attach user:",n)}}async isConversationSupported(t,n){return(await this.store.dispatch(Ig({sessionId:t,options:n}))).payload}async createConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(Dc(t))).payload}async getConversationBySessionId(t,n){return this.hasConversation()&&this.sessionId()!==t&&this.resetConversation(),(await this.store.dispatch(Fc({sessionId:t,options:n}))).payload}async upsertConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(Lg(t))).payload}async postMessages(t){return(await this.store.dispatch(Uc(t))).payload}async updateConversation(t){return(await this.store.dispatch(Hc(t))).payload}resetConversation(){this.store.dispatch(ue()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}async getSummary(){let t=await this.store.dispatch(Yn());if(t.error)throw new Error(t.error.message);return t.payload.summary}configure(t){this.store.dispatch(Oc(t))}setVisitorInfo(t){this.store.dispatch(hE(t))}async setAgentInfo(t){await this.store.dispatch(Pa(t))}async setAgentSettings(t){await this.store.dispatch(Mg(t))}async getAgentSettings(){return(await this.store.dispatch(_g())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let t=[];return this.store.dispatch(kd()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})}notifyInputChanged(t){this.store.dispatch(Vc(t))}notifyKeyDown(t){this.store.dispatch(Bc(t))}notifyPaste(t,n){this.store.dispatch(uE({text:t,selectionText:n}))}notifyCut(t){this.store.dispatch(aE(t))}notifyExternalSuggestion(t){this.store.dispatch(Cn(t)),this.store.dispatch(Kn())}async evaluateRule(t,n={}){let{payload:r,error:o}=await this.store.dispatch($n({label:t,params:n}));if(o)throw o;return r}handleInputChanged(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui;n&&r&&this.store.dispatch(Kr({collapse:!1})),this.inputMediator&&this.store.dispatch(nE({text:t,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(En([])))}handleKeyDown(t){let{overlayCollapsed:n}=this.state.ui,{textSuggestions:r,selectedSuggestionIndex:o,selection:i}=this.state.input,{inlineSuggestions:s}=this.state.settings,a=r.length>0,l=o!==-1;if(this.store.dispatch(lE(Jx(t))),t.key!=="Tab"&&!this.settings.showTextSuggestions)return;let u=()=>{n||!a||i&&(t.shiftKey||(this.store.dispatch(oE()),s||this.stageSelectedSuggestion({inputType:"arrow"}),t.preventDefault()))},c=()=>{n||!a||s&&o<=0||i&&(t.shiftKey||(this.store.dispatch(sE()),t.preventDefault(),!s&&(this.state.input.selectedSuggestionIndex===-1?this.store.dispatch(ka()):this.stageSelectedSuggestion({inputType:"arrow"}))))};switch(t.key){case"Up":case"ArrowUp":s?c():u();return;case"Down":case"ArrowDown":{s?u():c();return}case"Esc":case"Escape":{s&&l&&this.store.dispatch(Fr(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(Fr(-1)),this.store.dispatch(ka()),t.preventDefault()):n||(this.store.dispatch(Kr({collapse:!0})),this.store.dispatch(pb(!0)),t.preventDefault());return}case"Tab":{let{userCommitted:f}=this.state.input,d=f.text.substring(0,f.selection.end),{tabCompletionSuggestion:p}=this.state.input;this.store.dispatch(Za(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):!s&&this.settings.showTabCompletion&&p&&p.text.startsWith(d)&&(this.store.dispatch(Cn({text:p.text,suggestion:p,eventMetrics:{inputType:"tab"},replace:"until-selection-end"})),this.store.dispatch(Kn())),t.preventDefault();break}default:}}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(cE()),this.store.dispatch(En([]))}handlingTimeStart(){this.state.handlingTime.startTime||(V.info("Start handling time"),this.store.dispatch(p1()))}handlingTimeStop(){this.state.handlingTime.startTime&&(V.info("Stop handling time"),this.store.dispatch(af()))}logSendMessage(t){let n=T1("input",this.state,{version:this.version});t&&(Object.assign(n,{text:t}),Object.assign(n,{lenTextTotal:t.length})),this.deepdeskApi.sendEventV1("Send Message",n),this.emit("send-message-event",n)}logHandlingTime(){let t=b1(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",t),this.store.dispatch(m1())}notifySubmit(t={}){this.shouldAbort()||(this.store.dispatch(Kn()),this.store.dispatch(Co(t.text??this.state.input.text)))}stageSelectedSuggestion(t){let n=this.state.input.selectedSuggestionIndex,{textSuggestions:r}=this.state.input;this.store.dispatch(Cn({text:r[n].text,suggestion:r[n],eventMetrics:t,replace:"until-selection-end"}))}emit(t,n,r={}){let o=()=>{this.eventListeners[t]&&this.eventListeners[t].forEach(i=>{try{i(n)}catch(s){V.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),V.error(s)}})};this.inputMediator&&r.mayApplyChanges?this.inputMediator.applyChanges(o):o()}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}whenConversationLoaded(t){let n=()=>this.loadProfileConfig().then(()=>t());this.hasConversation()&&n();let r=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==r&&(r=this.hasConversation(),r&&n())})}overlayContainerFactory(t,n,r,o){let[i,s]=gl(n,r);return i.setAttribute("translate","no"),i.dataset.testid=t,o&&i.classList.add(o),this.unmountHandlers.push(()=>{(0,Wt.unmountComponentAtNode)(i),s(),i.remove()}),i}createInlineContainer(t,n){var s;let r=document.createElement("div");r.style.position="absolute",r.style.top="0px",r.style.left="0px",r.style.height="0px",r.style.width="0px";let o=document.createElement("div");o.style.display="none",o.style.position="absolute",o.style.height="0px",o.style.width="0px",o.style.backgroundColor="red",r.appendChild(o);let i=(s=t.ownerDocument.defaultView)==null?void 0:s.frameElement;if(i){let[a,l]=gl(i,{appendTo:document.body,onMoveStart:()=>{o.style.display="none"}});a.dataset.testid=n,a.style.zIndex="2",a.appendChild(r),this.unmountHandlers.push(()=>{(0,Wt.unmountComponentAtNode)(o),l()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return Ho(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),this.unmountHandlers.push(()=>{(0,Wt.unmountComponentAtNode)(o),o.remove()}),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),V.info(`Stored analytics for ${this.conversationId()}`)}catch{}}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()?(V.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(fE(r.metrics))):V.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(t)}catch{}}mount(t,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!uf(t))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let{customStyles:r={},showStyleSuggestions:o,showTabCompletion:i,showTextSuggestions:s,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,isEmbedded:f,detectSubmit:d,insertLink:p,inputMediator:y,closestScrollSelector:v,appendOverlayTo:g,inlineSuggestions:m,floatingMenu:h}=n;this.configure({showStyleSuggestions:o,showTabCompletion:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,showTextSuggestions:s,insertLink:p,isEmbedded:f,inlineSuggestions:m,floatingMenu:!!h}),n.automaticHandlingTime&&this.setupHandlingTime(t),Ho(t),this.inputMediator=y||(Wr(t)?new Vo(t):new Bo(t)),this.inputMediator.on("change",({plainText:C})=>{this.notifyInputChanged(C)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(dE({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()}))}),this.inputMediator.on("keydown",C=>{this.notifyKeyDown(C)}),this.inputMediator.on("paste",({pastedText:C,selectionText:T})=>{this.notifyPaste(C,T)}),this.inputMediator.on("cut",({selectionText:C})=>{this.notifyCut(C)});let S=v&&k1(t,v)||void 0;if(m){let{customStyles:C,appendOverlayTo:T}=n;if(Wr(t))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let k=this.createInlineContainer(t,"deepdesk-caret");(0,Wt.render)((0,Oe.jsx)(jo,{store:this.store,customStyles:C,children:(0,Oe.jsx)(To,{broadcastEvents:this.broadcastEvents,children:(0,Oe.jsx)(xb,{})})}),k),this.inputMediator.on("caret",L=>{this.store.dispatch(En([])),L?(k.style.display="block",k.style.top=`${L.top}px`,k.style.left=`${L.left}px`):k.style.display="none"});let I=this.overlayContainerFactory("floating-menu",S||t,{appendTo:typeof h=="object"&&"appendOverlayTo"in h?h.appendOverlayTo:T},C==null?void 0:C.floatingMenuRootNode);(0,Wt.render)((0,Oe.jsx)(jo,{store:this.store,customStyles:C,children:(0,Oe.jsx)(To,{broadcastEvents:this.broadcastEvents,children:(0,Oe.jsx)(cb,{onLogIn:()=>this.loginViaPopup().catch(L=>V.warn(L.message))})})}),I)}else{let C=this.overlayContainerFactory("deepdesk-tab-completion",S||t,{appendTo:g,closestScrollElement:S,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),T=this.overlayContainerFactory("deepdesk-suggestions-overlay",S||t,{appendTo:g},r==null?void 0:r.suggestionsRootNode);(0,Wt.render)((0,Oe.jsx)(jo,{store:this.store,customStyles:r,children:(0,Oe.jsx)(To,{broadcastEvents:this.broadcastEvents,children:(0,Oe.jsx)(Xb,{inputElement:t})})}),C),(0,Wt.render)((0,Oe.jsx)(jo,{store:this.store,customStyles:r,children:(0,Oe.jsx)(To,{broadcastEvents:this.broadcastEvents,children:(0,Oe.jsx)(Ib,{onLogIn:()=>this.loginViaPopup().catch(k=>V.warn(k.message))})})}),T)}(0,Wt.render)((0,Oe.jsx)(jo,{store:this.store,customStyles:r,children:(0,Oe.jsx)(To,{broadcastEvents:this.broadcastEvents,children:(0,Oe.jsx)(ib,{})})}),this.createContainer("deepdesk-overlays"));let x;this.inputMediator.on("selection",C=>{clearTimeout(x),C===null?x=setTimeout(()=>{C!==null&&this.store.dispatch(Og(C))},500):this.store.dispatch(Og(C))}),this.inputMediator.on("disabled",()=>{var C;(C=this.inputMediator)==null||C.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{d&&this.notifySubmit()}),this.inputMediator.on("blur",()=>this.store.dispatch(wh(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(wh(!0))),this.store.dispatch(rE({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.unmountHandlers.push(()=>{this.state.input.text!==""&&(this.store.dispatch(Kn()),this.storeMetrics())}),this.whenConversationLoaded(()=>{var C;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((C=this.state.conversation.current)==null?void 0:C.sessionId)}),this.isMounted=!0}unmount(){var t;this.unmountHandlers.forEach(n=>n()),this.unmountHandlers=[],(t=this.inputMediator)==null||t.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(t,n={}){if(this.widgetRoot&&V.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,isEmbedded:i}=n;this.widgetRoot=t,this.configure({showImages:o,isEmbedded:i}),(0,Wt.render)((0,Oe.jsx)(jo,{store:this.store,customStyles:r,children:(0,Oe.jsx)(To,{broadcastEvents:this.broadcastEvents,children:(0,Oe.jsx)(i1,{onLogIn:()=>this.loginViaPopup().catch(s=>V.warn(s.message))})})}),t),this.whenConversationLoaded(()=>{var s;this.broadcastEvents.setSessionId((s=this.state.conversation.current)==null?void 0:s.sessionId)})}unmountWidget(){this.widgetRoot&&(0,Wt.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(t){let n=ff(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){P1(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(Ya());let t=Vr(this.state);t&&(await this.store.dispatch(qa()),this.store.dispatch(Oc({showSearch:t.search,showAutoflows:t.autoflows,showCustomMessages:t.customMessages,showImageSearch:t.imageSearch,showEntitiesCommand:t.entitiesCommand,showSummaryCommand:t.summarizer,showKnowledgeSearch:!!t.knowledgeAssistant,recommendTextSuggestions:t.recommendTextSuggestions})))}),this.loadProfileConfigPromise)}async loginViaPopup(t){return new Promise((n,r)=>{let o=new MessageChannel,i=o.port1,s=this.state.settings.adminUrl,a=new URL(t!=null&&t.url?t==null?void 0:t.url:`${s}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let l=!1,u=()=>{c&&!c.closed&&c.close(),window.removeEventListener("message",f),clearInterval(d)};i.onmessage=async p=>{var y,v;if((y=p.data)!=null&&y.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((v=p.data)==null?void 0:v.jwt),await this.isLoggedIn(),this.broadcastEvents.send(Aa),l=!0,o.port1.close(),n()}catch(g){console.error(g),r(g)}finally{l=!0,u()}};let c=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");c===null&&r(new Error("Popup blocked by browser"));let f=async p=>{var y;if(p.origin===a.origin)switch((y=p.data)==null?void 0:y.type){case"deepdesk-popup-loaded":{try{let v=JSON.stringify({type:"deepdesk-popup-create-channel"});c==null||c.postMessage(v,a.origin,[o.port2])}catch(v){V.error("Error posting message to popup",v),r(v)}break}case"deepdesk-popup-error":{u(),p.data.message==="Timeout"&&V.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(()=>{c&&!c.closed||(u(),l||r(new Error("Popup closed by user")))},200);this.unmountHandlers.push(u)})}translateMessages(t){return this.deepdeskApi.translateMessages(t)}async checkForTrialMode(t){try{let{account:n}=await this.deepdeskApi.getPlatformConfig();if(!n.isTrial){this.shouldRender=!0;return}if(V.info("Trial is active"),!await this.deepdeskApi.checkUserExists(t))throw new Error("User is not in trial");this.shouldRender=!0}catch(n){let{message:r}=n;V.info(r),this.shouldRender=!1}}async refreshWidgetSuggestions(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=bd(this.state);try{n.forEach(({type:r})=>{r==="entities"?this.store.dispatch(sn()):this.store.dispatch(ln(r))})}catch(r){this.handleError(r)}}};async function U1(e,t,n={}){let{value:r}=e,{start:o,end:i}=n.replace??{start:0,end:r.length},s=`${r.slice(0,o)}${t}${r.slice(i)}`,a=n.selectionAfter??{start:o+t.length,end:o+t.length},l=()=>{if(n.setValue)return n.setValue(s);e.value=s};return Promise.resolve(l()).then(()=>{e.selectionStart=a.start,e.selectionEnd=a.end,e.blur(),e.focus()})}async function j1(e,t,n={}){let r=n.replace?Xr(e,n.replace.start,n.replace.end):ss(e),o,i=()=>{if(n.setRange)return n.setRange(r.cloneRange());r.deleteContents(),o=document.createElement("span"),r.insertNode(o),n.insertBRs!==!1?t.split(`
27
27
  `).reverse().forEach((s,a)=>{a>0&&r.insertNode(document.createElement("br")),r.insertNode(document.createTextNode(s))}):r.insertNode(document.createTextNode(t))};return Promise.resolve(i()).then(()=>{try{if(n.selectionAfter!==!1){e.focus();let s=n.selectionAfter?Xr(e,n.selectionAfter.start,n.selectionAfter.end):(r.collapse(!1),r),a=window.getSelection();a==null||a.removeAllRanges(),a==null||a.addRange(s)}if(!o)return;o.scrollIntoView&&o.scrollIntoView({block:"nearest",inline:"nearest"})}finally{o&&o.remove()}})}function VM(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 KM(e){let t=document.createDocumentFragment();return e.split(`
28
28
  `).forEach((n,r)=>{r>0&&t.appendChild(document.createElement("br"));let o={index:0},i=0;for(;o=n.slice(i).match(/(\[([^\]]+)])\(([^)]+)\)/);){let s=document.createElement("a");s.href=o[3],s.setAttribute("target","_blank"),s.setAttribute("rel","noopener noreferrer"),s.appendChild(document.createTextNode(o[2])),t.appendChild(document.createTextNode(n.slice(i,i+o.index))),t.appendChild(s),i=i+o.index+o[0].length}t.appendChild(document.createTextNode(n.slice(i)))}),t}function z1(e,t){return!e.contains(t)||t===e?null:t.parentNode===e?t:z1(e,t.parentNode)}async function B1(e,t,{isBlock:n,isHTML:r}={}){let o;e.dispatchEvent(new InputEvent("beforeinput",{inputType:"insertText",data:t,bubbles:!0,cancelable:!0}));let i=()=>{let s=e.ownerDocument.defaultView??window,a=s.getSelection();if((!a||a.rangeCount===0)&&(e.focus(),a=s.getSelection()),!a||a.rangeCount===0)return;let l=a.getRangeAt(0);if(!l)return;o=document.createElement("span"),l.insertNode(o);let u=r?VM(t):KM(t);if(n){let c=l.startContainer===e?e.childNodes[l.startOffset]:l.startContainer,f=z1(e,c)??e.firstChild;e.insertBefore(u,(f==null?void 0:f.nextSibling)??null)}else l.insertNode(u),l.collapse(!1)};return Promise.resolve(i()).then(()=>{if(e.dispatchEvent(new InputEvent("input",{inputType:"insertText",data:t,bubbles:!0,cancelable:!0})),e.focus(),!!o)try{o.scrollIntoView&&o.scrollIntoView({block:"nearest",inline:"nearest"})}finally{o&&o.remove()}})}function V1(e){return e.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}async function K1(e,t,n){await new sr(e).authenticateWithKey(t,n)}async function $1(e){let n=await new fn(e).get("/platform/config/",{version:null});return ne(n)}async function $M(e){let n=await(e.fetch??window.fetch)(e.url),r=await n.blob();return new File([r],e.name,{type:e.mimeType??n.headers.get("Content-Type")??"image/jpeg"})}async function W1(e,t){let n=await $M(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}}return ak(WM);})();
29
29
  /*! Bundled license information:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deepdesk/deepdesk-sdk",
3
- "version": "11.0.1-beta.2",
3
+ "version": "11.1.0",
4
4
  "description": "Deepdesk SDK",
5
5
  "author": "Lukas Batteau",
6
6
  "license": "ISC",