@deepdesk/deepdesk-sdk 11.5.2 → 11.5.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -20,11 +20,11 @@ Try polyfilling it using "@formatjs/intl-pluralrules"
20
20
  c-17.9,17.9-27.3,40.1-27.3,65.7C163.4,163,163.4,233,163.4,233z M465.5,267.9V477c0,9.4-3.4,17.9-10.2,24.7
21
21
  c-6.8,6.8-15.4,10.2-24.7,10.2h-349c-9.4,0-17.9-3.4-24.7-10.2c-6.8-6.8-10.2-15.4-10.2-24.7V267.9c0-9.4,3.4-17.9,10.2-24.7
22
22
  c6.8-6.8,15.4-10.2,24.7-10.2h11.9v-70c0-44.4,16.2-82.8,47.8-115.2S212.1,0,256.4,0s82.8,16.2,115.2,47.8
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 _h=S(b()),ZO={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},AC=({className:e,color:t})=>(0,_h.jsx)("svg",{className:e,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:(0,_h.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:ZO[t||"pink"]})});var LC={root:"dd-LbeUM",text:"dd-Dpfn1",isLoggedOut:"dd-21y-z",icon:"dd-8rLqS",logo:"dd-slXhD",lock:"dd-ByzlR"};var Dh={};je(Dh,{enUS:()=>JO,nlNL:()=>eM});var JO={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Search"}]},eM={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Zoeken"}]};var zo=S(b()),OC=({onLogIn:e})=>{let t=$(Dh),n=B("floatingMenu"),r=B("productName"),o=Y(),i=O(tt),s=P("FloatingMenu",LC);if(i===null||n===!1)return null;let a=()=>{i===!0?o(wt(!0)):e()};return(0,zo.jsxs)("button",{className:(0,IC.default)(s.root,{[s.isLoggedIn]:i,[s.isLoggedOut]:!i}),onClick:a,children:[(0,zo.jsx)("div",{className:s.text,children:t(i?"search":"signin",{productName:r})}),(0,zo.jsxs)("div",{className:s.icon,children:[(0,zo.jsx)(AC,{className:s.logo,color:"pink"}),i===!1&&(0,zo.jsx)(RC,{className:s.lock})]})]})};var Vd=S(N());var MC=S(N());function $r(e){(0,MC.useEffect)(()=>{let t=n=>{n.isWithinRoot||e(n)};return document.body.addEventListener("mouseup",t),()=>{document.body.removeEventListener("mouseup",t)}},[e])}function Bo(e){e.addEventListener("mouseup",t=>{t.isWithinRoot=!0},!0)}function rs(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 tM={showTabHint:!1,inputHasFocus:!1,overlayCollapsed:!1,openOverlayWhenTyping:!1,overlayCollapsedUserOverwrite:!1};var zd=({ui:e})=>e.overlayCollapsed;var NC=G({name:"ui",initialState:tM,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:nl,setInputHasFocus:Fh,setOverlayCollapsed:qr,setOpenOverlayWhenTyping:_C,setOverlayCollapsedUserOverwrite:DC}=NC.actions,FC=NC.reducer;var Bd=S(N());var os=S(N());var HC=S(N());function UC(e,t,n){(0,HC.useEffect)(()=>{let r=e.current;return r?(r.addEventListener(t,n),()=>{r.removeEventListener(t,n)}):()=>{}},[e,t,n])}var zC={root:"dd-1MBCO",actions:"dd--x4cy",badge:"dd-4Fpkz",formattedText:"dd-EzvTB"};var jo=S(b()),rM=["search","personal-collection-search","search-autocomplete"];function oM(e,t,n,r={}){let o="";return rM.includes(t)?o=PE(xh(e,n,{stripAgentPart:!0}),r.searchKeywords??[n]):o=xh(e,n,r),r.placeholders===!0&&(o=RE(o)),o}var iM=()=>{},sM=({index:e,selected:t,suggestion:n,onFeedback:r})=>{let o=B("inlineSuggestions"),i=O(Gi),s=Y(),a=P("TextSuggestion",zC),l=(0,os.useRef)(null);(0,os.useEffect)(()=>{let c=setTimeout(()=>{s(T1({text:n.text,suggestion:n}))},500);return()=>{clearTimeout(c)}},[n]),UC(l,"click",()=>{s(Br(e)),s(Cn({suggestion:n,text:n.text,eventMetrics:{inputType:"mouse"},replace:"until-selection-end"}))});let u=(0,os.useMemo)(()=>oM(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,jo.jsxs)("div",{className:a.root,onMouseEnter:()=>s(Br(e)),children:[(0,jo.jsx)(ne,{ref:l,as:"button","data-testid":"suggestions-overlay-item",selected:t,onClick:iM,children:(0,jo.jsx)(Xi,{containerTagName:"div",noWrap:!1,tagName:"span",className:a.formattedText,content:u})}),t&&r&&(0,jo.jsx)("div",{className:a.actions,children:(0,jo.jsx)(Ad,{onFeedback:()=>r(n),suggestion:n.text})})]})},BC=sM;var Hh=S(b()),aM=({onFeedback:e,suggestions:t,selectedIndex:n,reverse:r})=>{let o=(0,Bd.useMemo)(()=>{let i=t.map((s,a)=>(0,Hh.jsx)(BC,{index:a,selected:a===n,suggestion:s,onFeedback:e},`${s.text}-${s.source}`));return r?i.reverse():i},[t,n,r]);return(0,Hh.jsx)(Bd.Fragment,{children:o})},jd=aM;var jC={root:"dd-PfvRI",paper:"dd-HYlyY"};var rl=S(b()),lM=({textSuggestions:e,selectedIndex:t})=>{let n=(0,Vd.useRef)(null),r=P("InlineSuggestionsOverlay",jC),o=O(rs),i=Y(),s=O(tt),a=O(qi),l=O(zd),u=B("showTextSuggestions");return $r(()=>{setTimeout(()=>{i(qr({collapse:!0,skipWhenInputFocus:!0}))})}),(0,Vd.useEffect)(()=>{let c=n.current;if(!c||!c.parentElement)return;c.parentElement.style.left="0px";let p=c.getBoundingClientRect();c.parentElement.style.left=`${Math.min(window.innerWidth-4-p.right,0)}px`}),l||!o||!u||e.length===0||s!==!0||a===!1?null:(0,rl.jsx)("div",{className:r.root,"data-variant":"inline",children:(0,rl.jsx)("div",{ref:n,className:r.paper,children:(0,rl.jsx)(ct,{children:(0,rl.jsx)(jd,{suggestions:e,selectedIndex:t})})})})},uM=({input:e})=>({selectedIndex:e.selectedSuggestionIndex,textSuggestions:e.textSuggestions}),VC=Bn(uM)(lM);var ol=S(b()),cM=({children:e})=>{let n=B("locale").replace("-","");return(0,ol.jsx)(ih.Provider,{value:n,children:e})},dM=({store:e,customStyles:t={},children:n})=>(0,ol.jsx)(Hg,{store:e,children:(0,ol.jsx)(cM,{children:(0,ol.jsx)(Ss.Provider,{value:t,children:n})})}),Vo=dM;var Wd=S(te()),is=S(N());var KC=S(N());function WC(e,t){let[n,r]=(0,KC.useState)(()=>{if(typeof window>"u")return t;try{let i=window.localStorage.getItem(e);return i?JSON.parse(i):t}catch(i){return H.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){H.error(s)}}]}var $C=()=>/Mac/i.test(navigator.platform);var GC=S(te()),Jn=S(N());var Uh={};je(Uh,{enUS:()=>fM,nlNL:()=>pM});var fM={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"}]}]},pM={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 qC={root:"dd-uTPjX",anchor:"dd-C8lsZ",anchorButton:"dd-IoSx9"};var Gr=S(b()),zh=(e,t,n)=>r=>(0,Gr.jsx)("button",{className:e.anchorButton,type:"button",value:t,onClick:n,children:r},t),mM=({className:e,loginUrl:t,isEmbedded:n,onSnooze:r,onLogIn:o})=>{let i=$(Uh),s=jt(),a=P("Login",qC),l=B("productName"),u=(0,Jn.useCallback)(f=>{f.preventDefault(),r&&r(parseInt(f.target.value,10))},[]),c=(0,Jn.useCallback)(f=>{f.preventDefault(),s.send(Yi,!0)},[t]),p=(0,Jn.useMemo)(()=>f=>(0,Gr.jsx)("a",{onClick:h=>{h.preventDefault(),o()},href:t,className:a.anchor,target:"_blank",rel:"noreferrer",children:f},"login"),[t]),d=(0,Jn.useCallback)(f=>(0,Gr.jsx)("button",{type:"button",className:a.anchorButton,onClick:c,children:f},"prompt"),[c]),{min:g,hour:y,day:v}=(0,Jn.useMemo)(()=>({min:zh(a,60*10,u),hour:zh(a,60*60,u),day:zh(a,60*60*12,u)}),[]);return(0,Gr.jsxs)("div",{className:(0,GC.default)(e,a.root),children:[i("loginPlease",{login:n?d:p,productName:l}),r&&(0,Gr.jsxs)(Jn.Fragment,{children:[(0,Gr.jsx)("br",{}),i("snooze",{min:g,hour:y,day:v})]})]})},Kd=mM;var YC={root:"dd-DoQhb",text:"dd-Jwnev"};var il=S(b()),gM=({title:e})=>{let t=P("SearchTrigger",YC),n=Y();return(0,il.jsxs)("button",{type:"button",className:t.root,onClick:()=>n(wt(!0)),children:[(0,il.jsx)(Zi,{}),(0,il.jsx)("span",{className:t.text,children:e})]})},XC=gM;var Bh={};je(Bh,{enUS:()=>hM,nlNL:()=>yM});var hM={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"}]},yM={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 QC={root:"dd-oa7Vc",isInline:"dd-bwk31",toggleButton:"dd-MSB8Z",toggleButtonWrapper:"dd-ZkCzT",toggleButtonWrapperHidden:"dd-Sq66c",isCollapsed:"dd-vkrPk",collapsible:"dd-CWQJe",hints:"dd-IOoo3",hintsHidden:"dd-psVuT",triggers:"dd-toIoo",triggersRight:"dd-mc4l2"};var Se=S(b()),vM=({textSuggestions:e,selectedIndex:t,onLogIn:n})=>{let r=P("SuggestionsOverlay",QC),o=$(Bh),i=O(rs),s=w1(),a=Y(),l=(0,is.useRef)(null),u=B("searchTriggerKey"),c=B("productName"),p=O(zd),d=O(tt),g=O(qi),[y,v]=(0,is.useState)(null),f=B("showSearch"),m=B("showTextSuggestions"),h=B("adminUrl"),x=B("isEmbedded"),[w,T]=WC("dd-snooze-until-ms",0),C=p||w>Date.now(),k=O(V=>V.input.text),I=e.filter(V=>V.source!=="gpt").length,L=()=>{C&&T(0),a(DC(!C))},_=V=>{a(Xe({name:"suggestion feedback",data:{text:V.text,source:"overlay",context:k},options:{includeConversationData:!0}}))},W=V=>{let Z=Date.now()+V*1e3;T(Z),H.info(`Snooze until: ${new Date(Z)}`),a(qr({collapse:!0}))};return(0,is.useEffect)(()=>{I===0&&v(null)},[e,I]),$r(()=>{a(qr({collapse:!0,skipWhenInputFocus:!0}))}),d===null||g===!1?null:d===!1?(0,Se.jsxs)("div",{ref:l,className:(0,Wd.default)(r.root,{[r.isCollapsed]:C}),children:[!C&&(0,Se.jsxs)("div",{className:r.triggers,children:[(0,Se.jsx)("div",{style:{flex:1}}),(0,Se.jsx)("div",{className:r.triggersRight,children:(0,Se.jsx)(ao,{className:r.toggleButton,title:o("collapse"),onClick:L,isCollapsed:!1})})]}),(0,Se.jsx)("div",{className:r.toggleButtonWrapper,children:(0,Se.jsx)(ao,{className:r.toggleButton,title:o("open",{productName:c}),onClick:L,isCollapsed:!0})}),(0,Se.jsx)("div",{className:r.collapsible,children:(0,Se.jsx)(Kd,{loginUrl:h,isEmbedded:x,onLogIn:n,onSnooze:W})})]}):!s||!i?null:(0,Se.jsxs)("div",{ref:l,className:(0,Wd.default)(r.root,{[r.isCollapsed]:C}),children:[!C&&(0,Se.jsxs)("div",{className:r.triggers,children:[(0,Se.jsx)("div",{style:{flex:1},children:f&&(0,Se.jsx)("div",{style:{display:"inline-block"},onFocus:()=>{},onMouseOver:()=>v(o($C()?"searchHintMac":"searchHintWindows",{searchTriggerKey:u.toUpperCase()})),onMouseLeave:()=>v(null),children:(0,Se.jsx)(XC,{title:o("search")})})}),(0,Se.jsxs)("div",{className:r.triggersRight,onFocus:()=>{},children:[(0,Se.jsx)("div",{className:(0,Wd.default)(!y&&r.hintsHidden,r.hints),children:y}),(0,Se.jsx)(ao,{className:r.toggleButton,title:o("collapse"),onClick:L,isCollapsed:!1})]})]}),(0,Se.jsx)("div",{className:r.toggleButtonWrapper,children:(0,Se.jsx)(ao,{className:r.toggleButton,title:o("open",{productName:c}),onClick:L,isCollapsed:!0})}),I>0&&m&&(0,Se.jsx)("div",{className:r.collapsible,onFocus:()=>{},children:(0,Se.jsx)(ct,{children:(0,Se.jsx)(jd,{onFeedback:_,suggestions:e,selectedIndex:t,reverse:!0})})})]})},SM=({input:e})=>({selectedIndex:e.selectedSuggestionIndex,textSuggestions:e.textSuggestions}),ZC=Bn(SM)(vM);var af=S(te());var rr=S(N());var ss=S(N());function $d(e){return e.contentEditable==="true"}function xM(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 JC(e){let{selectionStart:t,selectionEnd:n}=$d(e)?xM(e):e;return[t,n]}function eb(e){let[,t]=(0,ss.useState)(),n=(0,ss.useRef)(null);return n.current=JC(e),(0,ss.useEffect)(()=>{let r=()=>{let[o,i]=n.current??[],s=JC(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 tb(e,t){if(!t)return;let n=e,{value:r}=n,[o,i]=t,s=r.match($l);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 nb=S(N()),wM=["div","span","mark","strong","b","i","u","em"];function jh(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(wM.includes(o)){let s=Array.isArray(r.props.children)?r.props.children:[r.props.children];return[...e.slice(0,e.length-1),(0,nb.cloneElement)(r,{children:jh(s,t,n+1)})]}return[...e,...t]}function Yr(e){return e.tagName.toLowerCase()==="textarea"}var rb={agentText:"dd-qnW-V",tabText:"dd-cUHUr",hint:"dd-v7fSg",matchSelection:"dd-8cr8y",focus:"dd-3tr9l",resetIndent:"dd-TvQfZ",matchKeyword:"dd-oJkRD",matchPlaceholder:"dd-QvNoo",hover:"dd--wi0R",hintText:"dd-7gQQh",popover:"dd-xbRu-",popoverRoot:"dd-rA2x8",popoverContentContainer:"dd-JHICl",popoverContent:"dd--mfkC",selectionOptions:"dd-p52wn",selectionOptionsIsHidden:"dd-sSTDp",selectionOptionsButton:"dd-Q6kRY",caret:"dd-jIhc8",popoverSuggestionsRoot:"dd-iFDbL",suggestionsOverlayInputStyles:"dd-zzENA"};var pb=S(te());var tf=S(N());var as=S(N());function ob(e,t){let n;return[(...r)=>{window.cancelAnimationFrame(n);let o=t?t(...r):r;n=window.requestAnimationFrame(()=>{e(...o)})},()=>window.cancelAnimationFrame(n)]}function qd(e){let t=(0,as.useRef)(null),[n,r]=(0,as.useState)(!1);return(0,as.useEffect)(()=>{let o=!1,i=parseFloat(window.getComputedStyle(document.body).zoom??"1"),[s,a]=ob((c,p)=>{let d=t.current;if(!d)return;let g=c/i,y=p/i,v=d.getBoundingClientRect(),f=g>v.x&&g<v.x+v.width&&y>v.y&&y<v.y+v.height;f&&!o?(o=!0,r(!0)):!f&&o&&(o=!1,r(!1))},({clientX:c,clientY:p})=>[c,p]),[l,u]=ob(()=>{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 ib(e){return e.replace(/[.*+^${}()|[\]\\]/g,"\\$&")}function Gd(e){return t=>{e.forEach(n=>{typeof n=="function"?n(t):n!=null&&(n.current=t)})}}function sb(e){return e!=null}var Kh=S(te()),Kt=S(N());var Yd=S(N()),EM=["bottom","height","left","right","top","width"],CM=(e={},t={})=>EM.some(n=>e[n]!==t[n]),er=new Map,ab,lb=()=>{let e=[],t=[];er.forEach((n,r)=>{if(r instanceof Element&&!r.isConnected){t.push(r);return}let o=r.getBoundingClientRect();CM(o,n.rect)&&(n.rect=o,e.push(n))}),t.forEach(n=>{er.delete(n)}),e.forEach(n=>{n.callbacks.forEach(r=>r(n.rect))}),ab=window.requestAnimationFrame(lb)};function bM(e,t){return{observe(){let n=er.size===0;if(er.has(e)){let r=er.get(e);r.callbacks.push(t),r.rect&&t(r.rect)}else er.set(e,{rect:void 0,hasRectChanged:!1,callbacks:[t]});n&&lb()},unobserve(){let n=er.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||er.delete(e),er.size||cancelAnimationFrame(ab)}}}}function Vh(e){let[t,n]=(0,Yd.useState)(null);return(0,Yd.useLayoutEffect)(()=>{if(!e.current)return;let r=bM(e.current,o=>{n(o)});return r.observe(),()=>{r.unobserve()}},[e]),t}var ls=S(N()),cb=S(sc());var ub={root:"dd-r-dgo"};var db=({children:e,parentNode:t})=>{let[n,r]=(0,ls.useState)(null),o=(0,ls.useContext)(Ss);return(0,ls.useLayoutEffect)(()=>{let i=document.createElement("div");return Bo(i),i.classList.add(ub.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,cb.createPortal)(e,n):null};var Tn={ref:"dd-iz-KP",root:"dd-vEMon",positionAbove:"dd-mUCxM",positionBelow:"dd-7oZI7",positionLeft:"dd-BiWvD",positionRight:"dd-JIWea",alignStart:"dd-5ivu6",alignCenter:"dd-rnVkP",alignEnd:"dd-gZBp4"};var Xd=S(b()),Qd=(e=!1)=>{let[t,n]=(0,Kt.useState)(e),r=(0,Kt.useCallback)(()=>n(!0),[]),o=(0,Kt.useCallback)(()=>n(!1),[]),i=(0,Kt.useCallback)(()=>n(a=>!a),[]),s=(0,Kt.useRef)(null);return{opened:t,open:r,close:o,toggle:i,triggerRef:s}};function Wh(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 us=({className:e,triggerRef:t,boundaryRef:n=(0,Kt.createRef)(),position:r="above",align:o="center",children:i,toStyle:s=Wh,parentNode:a,...l})=>{let u=Vh(t),c=Vh(n),p=(0,Kt.useMemo)(()=>s(u,c,0),[u,c]);return(0,Xd.jsx)(db,{parentNode:a,children:(0,Xd.jsx)("div",{className:(0,Kh.default)(Tn.ref,{[Tn.positionAbove]:r==="above",[Tn.positionBelow]:r==="below",[Tn.positionLeft]:r==="left",[Tn.positionRight]:r==="right",[Tn.alignStart]:o==="start",[Tn.alignCenter]:o==="center",[Tn.alignEnd]:o==="end"}),style:p,...l,role:"dialog",children:(0,Xd.jsx)("div",{className:(0,Kh.default)(e,Tn.root),children:i})})})};var fb=S(te()),Zd=S(N());var tr={agentText:"dd-qnW-V",tabText:"dd-cUHUr",hint:"dd-v7fSg",matchSelection:"dd-8cr8y",focus:"dd-3tr9l",resetIndent:"dd-TvQfZ",matchKeyword:"dd-oJkRD",matchPlaceholder:"dd-QvNoo",hover:"dd--wi0R",hintText:"dd-7gQQh",popover:"dd-xbRu-",popoverRoot:"dd-rA2x8",popoverContentContainer:"dd-JHICl",popoverContent:"dd--mfkC",selectionOptions:"dd-p52wn",selectionOptionsIsHidden:"dd-sSTDp",selectionOptionsButton:"dd-Q6kRY",caret:"dd-jIhc8",popoverSuggestionsRoot:"dd-iFDbL",suggestionsOverlayInputStyles:"dd-zzENA"};var $h=S(b()),Jd=(0,Zd.forwardRef)(({className:e,children:t,...n},r)=>{let o=(0,Zd.useRef)(null),i=P("TabCompletion",tr);return(0,$h.jsx)("div",{ref:Gd([o,r]),className:(0,fb.default)(e,i.popoverContentContainer),...n,children:(0,$h.jsx)("div",{className:i.popoverContent,children:t})})});var Xr=S(b()),TM=e=>t=>{let n=Wh(t);return"top"in n&&(n.width=e.width-(t.left-e.left)-10),n},kM=({inputElement:e,boundaryRef:t,inputStyle:n,children:r,suggestion:o})=>{let i=P("TabCompletion",tr),s=Qd(),a=(0,tf.useMemo)(()=>TM(e.getBoundingClientRect()),[e]),[l,u]=qd(e);return(0,tf.useEffect)(()=>{u?s.open():s.close()},[u]),(0,Xr.jsxs)("span",{children:[(0,Xr.jsx)("mark",{ref:Gd([l,s.triggerRef]),className:(0,pb.default)(i.matchKeyword,{[i.hover]:u}),"aria-haspopup":"dialog","aria-expanded":s.opened?"true":"false",children:r}),s.opened&&(0,Xr.jsx)(us,{className:i.popover,triggerRef:s.triggerRef,boundaryRef:t,position:"below",align:"start",toStyle:a,children:(0,Xr.jsx)(Jd,{style:n,children:(0,Xr.jsx)("div",{className:i.hintText,children:o})})})]})},ef=class extends $n{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${ib(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(sb);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,Xr.jsx)(kM,{inputElement:n.inputElement,suggestion:n.suggestion,inputStyle:n.inputStyle,boundaryRef:n.boundaryRef,children:t},`keyword_${n.matchString}_${n.key}`)}asTag(){return"mark"}};var mb=S(te());var qh=S(b()),PM=({inputElement:e,children:t})=>{let n=P("TabCompletion",tr),[r,o]=qd(e);return(0,qh.jsx)("mark",{ref:r,className:(0,mb.default)(n.matchPlaceholder,{[n.hover]:o}),children:t})},nf=class extends $n{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,qh.jsx)(PM,{inputElement:n.inputElement,children:t},`placeholder_${n.matchString}_${n.key}`)}asTag(){return"mark"}};var of=S(te());var ot=S(N());var Gh=S(b()),gb=()=>(0,Gh.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,Gh.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 Qr=S(N());var yb=S(ch());var hb={root:"dd-ky-Bv",content:"dd-kV5e1"};function rf(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 Yh(e){return e.replace("https://www.","").replace("https://","")}var Wt=S(b()),RM=3,AM=e=>({image:e.image||"",text:e.text,id:e.id,title:e.title}),LM=({onSelectLink:e,onDismiss:t,placeholder:n,visitUrlText:r,linkCount:o=RM})=>{let i=P("LinkSearch",hb),[s,a]=(0,Qr.useState)(""),l=Y(),u=O(yC("url")),c=O(K1("URL",AM)),[p,d]=(0,Qr.useState)(c.length-1),g=B("fallbackImage"),y=h=>{let x=h.target;a(x.value)},v=(h,x)=>{h.stopPropagation(),h.preventDefault(),window.open(x,"_blank")},f=h=>{var T;let x=p-1<0?c.length-1:p-1,w=p+1===c.length?0:p+1;h.code==="Escape"&&(a(""),t()),h.code==="ArrowUp"&&d(x),h.code==="ArrowDown"&&d(w),h.code==="Enter"&&e(((T=c[p])==null?void 0:T.text)||s)},m=(0,Qr.useCallback)((0,yb.default)(h=>{l(Po({query:h,type:"URL",tags:["link-search"]}))},300),[]);return(0,Qr.useEffect)(()=>{s&&m(s)},[s]),(0,Qr.useEffect)(()=>()=>{l(td())},[]),(0,Wt.jsxs)("div",{className:i.root,children:[(0,Wt.jsx)(ct,{withDivider:!0,children:(s?c:u).slice(0,o).map((h,x)=>(0,Wt.jsx)(ne,{selected:p===x,onClick:()=>e(h.text),"data-testid":"linksearch-suggestion",children:(0,Wt.jsxs)(fe,{children:[(0,Wt.jsx)(fe.Image,{src:rf(h,"small",g||void 0),title:h.title||h.text}),(0,Wt.jsxs)(fe.Content,{className:i.content,cropText:!0,children:[(0,Wt.jsx)(fe.Title,{children:h.title||Yh(h.text)}),h.title&&Yh(h.text)]}),(0,Wt.jsx)(ne.Actions,{children:(0,Wt.jsx)(ne.ActionButton,{label:r,onClick:w=>v(w,h.text)})})]})},h.text))}),(0,Wt.jsx)(Ha,{value:s,onChange:y,autoFocus:!0,placeholder:n,onKeyUp:f})]})},vb=LM;var Xh={};je(Xh,{enUS:()=>IM,nlNL:()=>OM});var IM={insertLink:[{type:0,value:"Insert link"}],linkInputPlaceholder:[{type:0,value:"Search, type or paste link"}],visitUrl:[{type:0,value:"Visit"}]},OM={insertLink:[{type:0,value:"Voeg link toe"}],linkInputPlaceholder:[{type:0,value:"Zoek, typ of plak link"}],visitUrl:[{type:0,value:"Bekijk"}]};var rt=S(b()),MM=(0,ot.forwardRef)((e,t)=>{let n=P("TabCompletion",tr);return(0,rt.jsx)("mark",{ref:t,className:(0,of.default)(n.matchSelection)},"selection-start")}),NM=({startRef:e,boundaryRef:t,inputStyle:n,inputElement:r,children:o})=>{let i=$(Xh),s=P("TabCompletion",tr),a=(0,ot.useRef)(null),l=(0,ot.useRef)(null),[u,c]=(0,ot.useState)(null),p=Y(),d=Qd(document.activeElement===r),[g]=(0,ot.useState)(()=>document.createRange());d.triggerRef.current=g,(0,ot.useEffect)(()=>()=>g.detach(),[]),(0,ot.useEffect)(()=>{let v=e.current,f=a.current;!v||!f||(g.setStart(v,0),g.setEnd(f,0))},[e.current,a.current]),$r(()=>{d.close()});let y=(0,ot.useCallback)(v=>{let f=g.toString(),m=/^http(s?):\/\//.test(v)?v:`https://${v}`;p(Xc({text:`[${f}](${m})`,replace:"selection"}))},[]);return(0,rt.jsxs)("span",{children:[(0,rt.jsx)("mark",{ref:a,className:(0,of.default)(s.matchSelection),"aria-haspopup":"dialog","aria-expanded":d.opened?"true":"false",children:o}),d.opened&&(0,rt.jsx)(us,{className:s.popoverRoot,triggerRef:d.triggerRef,boundaryRef:t,position:"above",align:"start",children:(0,rt.jsxs)(Jd,{style:n,ref:l,children:[(0,rt.jsx)("div",{className:(0,of.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)(gb,{}),(0,rt.jsx)("span",{children:"\xA0"}),(0,rt.jsx)("span",{children:i("insertLink")})]})}),u==="insertLink"&&(0,rt.jsx)(vb,{placeholder:i("linkInputPlaceholder"),visitUrlText:i("visitUrl"),onSelectLink:y,onDismiss:()=>{c(null),d.close()}})]})})]},"selection-end")},sf=class extends $n{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)(MM,{ref:this.startRef}):(0,rt.jsx)(NM,{inputElement:n.inputElement,startRef:this.startRef,boundaryRef:n.boundaryRef,inputStyle:n.inputStyle})}asTag(){return"mark"}};var nr=S(b()),_M=({enabled:e,content:t,tabText:n,showTabHint:r,showTabCompletion:o,showStyleSuggestions:i,keywordMatches:s,inputElement:a,source:l})=>{let u=P("TabCompletion",rb),c=B("insertLink"),p=B("showMidSentenceSuggestions"),d=B("inlineSuggestions"),g=eb(a),y=(0,rr.useRef)(null),v=O(tt);(0,rr.useEffect)(()=>{Yr(a)&&g&&tb(a,g)},[g]);let f=(0,rr.useCallback)(x=>{if(!o||!n)return x;let w=[(0,nr.jsx)("span",{className:u.resetIndent,children:"\u200B"},"u200B"),(0,nr.jsx)("span",{"data-testid":"tab-completion",className:(0,af.default)(u.tabText,u.resetIndent),"data-source":l,children:n},"tabText")];return r&&w.push((0,nr.jsx)("span",{className:(0,af.default)(u.hint,u.resetIndent),children:(0,nr.jsx)(jl,{keyCode:"tab"},"tabHint")})),jh(x,w)},[o,n,r]),m=(0,rr.useMemo)(()=>{let x=[];return c&&x.push(new sf("selection")),x.push(new nf("placeholders")),i&&x.push(new ef("keywords")),x},[d,c,i]),h=(0,rr.useMemo)(()=>{let x=window.getComputedStyle(a);return{"--dd-color":x.color,"--dd-font-size":x.fontSize,"--dd-font-family":x.fontFamily,"--dd-font-variant":x.fontVariant}},[]);return!e||!v?null:(0,nr.jsxs)("div",{ref:x=>{x!=null&&x.parentElement&&(y.current=x==null?void 0:x.parentElement)},className:u.root,style:h,children:[(0,nr.jsx)(Xi,{tagName:"span",containerTagName:"div",className:(0,af.default)(u.container,u.agentText),disableLineBreaks:Yr(a),content:t||"\u200B",onAfterParse:f,matchers:m,selection:g,keywordMatches:s,inputElement:a,inputStyle:h,boundaryRef:y,inlineSuggestionsOnlyAtEnd:!p}),(0,nr.jsx)("br",{})]})},DM=({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??Qi(e.text),u=s.indexOf(e.text)===0?s.slice(e.text.length):"",{showTabHint:c}=t,{isSupported:p}=o,{showTabCompletion:d,visible:g,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:g&&p!==!1}},Sb=Bn(DM)(_M);var MT=S(te()),vl=S(N());var xb={list:[],fetchState:"idle"},Eb=e=>e.autoflows.list||[],wb=e=>t=>{var n;return(n=t.list)==null?void 0:n.find(r=>r.triggerPayload===e)},or=z("autoflows/getAll",async(e,t)=>{let{deepdeskBrokerAPI:n}=t.extra;if(!n)throw new Error("Deepdesk Broker not initialized");return n.getAutoflows(e)}),Qh=z("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(or(e.platformSessionId))}),Zh=z("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(or(e.platformSessionId))}),FM=G({name:"autoflows",initialState:xb,reducers:{},extraReducers:e=>{e.addCase(Qh.pending,(t,n)=>{let r=wb(n.meta.arg.triggerPayload)(t);r.state="Started",r.isBusy=!0}),e.addCase(Zh.pending,(t,n)=>{let r=wb(n.meta.arg.triggerPayload)(t);r.state="Aborted",r.isBusy=!0}),e.addCase(or.pending,t=>{t.fetchState="loading"}),e.addCase(or.rejected,t=>{t.fetchState="error"}),e.addCase(or.fulfilled,(t,n)=>{t.list=n.payload,t.fetchState="done"}),e.addCase(le,()=>xb)}}),Cb=z("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(or(e))}),o.on("sessionCompleted",()=>{n(or(e))})}),bb=z("autoflows/closeStream",(e,t)=>{let{deepdeskBrokerAPI:n}=t.extra;if(!n)throw new Error("Deepdesk Broker not initialized");n.closeStream(e)}),Tb=FM.reducer;var kb={list:[],fetchState:"idle",sentSuggestions:[],errorSuggestions:[],answeredSuggestions:[]},Pb=e=>e.customMessages.list,Rb=e=>t=>!!t.customMessages.sentSuggestions.find(n=>n===e),Ab=e=>t=>!!t.customMessages.answeredSuggestions.find(n=>n===e),Lb=e=>t=>!!t.customMessages.errorSuggestions.find(n=>n===e),sl=z("customMessages/getAll",async(e,t)=>{let{deepdeskBrokerAPI:n}=t.extra;if(!n)throw new Error("Deepdesk Broker not initialized");return n.getCustomMessages(e)}),lf=z("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)}),uf=z("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)}),Ib=G({name:"customMessages",initialState:kb,reducers:{onCustomMessage(e,t){Array.isArray(t.payload)?e.list=t.payload:e.list=[t.payload]}},extraReducers:e=>{e.addCase(sl.pending,t=>{t.fetchState="loading"}).addCase(sl.rejected,t=>{t.fetchState="error"}).addCase(sl.fulfilled,(t,n)=>{t.fetchState="done",t.list=n.payload||[]}).addCase(lf.pending,(t,n)=>{t.sentSuggestions.push(n.meta.arg.suggestion.text),t.errorSuggestions=t.errorSuggestions.filter(r=>n.meta.arg.suggestion.text!==r)}).addCase(lf.rejected,(t,n)=>{let r=t.sentSuggestions.indexOf(n.meta.arg.suggestion.text);t.errorSuggestions.push(...t.sentSuggestions.splice(r,1))}).addCase(uf.pending,(t,n)=>{t.sentSuggestions.push(n.meta.arg.suggestion.text),t.answeredSuggestions.push(n.meta.arg.suggestion.text)}).addCase(uf.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(le,()=>kb)}}),Ob=z("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(Ib.actions.onCustomMessage(i))})}),Mb=z("customMessages/closeStream",(e,t)=>{let{deepdeskBrokerAPI:n}=t.extra;if(!n)throw new Error("Deepdesk Broker not initialized");n.closeStream(e)}),Nb=Ib.reducer;var _b=e=>t=>{let{passwordlessToken:{token:n},settings:{isEmbedded:r,adminUrl:o}}=t;return o?r?n?`${o}/apis/admin/session/passwordless/login/?token=${n}&redirect=${e}`:null:`${o}${e}`:null};var HM={token:null,interval:null},Jh=z("passwordlessToken/getTemporaryPasswordlessToken",async(e,t)=>{let{deepdeskAPI:n}=t.extra;return{token:await n.requestPasswordlessToken()}}),ey=z("passwordlessToken/pollPasswordlessToken",(e={},t)=>{let{interval:n=1e3*60*10}=e,{dispatch:r}=t;return r(Jh()),setInterval(()=>r(Jh()),n)}),Db=G({name:"passwordlessToken",initialState:HM,reducers:{stopPollPasswordlessToken(e){e.interval&&clearInterval(e.interval),e.interval=null}},extraReducers:e=>{e.addCase(Jh.fulfilled,(t,n)=>{t.token=n.payload.token}),e.addCase(ey.fulfilled,(t,n)=>{t.interval=n.payload})}}),{stopPollPasswordlessToken:Fb}=Db.actions,Hb=Db.reducer;var ty={cues:[],fetchState:"idle"},Ub=e=>{var t;return(t=e.rules)==null?void 0:t.cues},UM=xe("rules/resetCues"),Ko=z("rules/evaluate",async(e,t)=>{var n,r;try{let{deepdeskAPI:o}=t.extra,i=t.getState(),s=(n=i.conversation.current)==null?void 0:n.id;if(!s)throw new Error("No current conversation to evaluate rules");if(!(await o.getAccount()).ruleEngine)throw new Error("Rule engine is not enabled for this account");if(!(await o.getRules()).some(c=>c.label===e.label))throw new Error(`No rules found with label: ${e.label}`);return await o.evaluateRule(e.label,s,{tags:((r=i.conversation.current)==null?void 0:r.tags)||void 0,...e.params})}catch(o){return H.info(o.message),[]}}),zb=G({name:"answer",initialState:ty,reducers:{removeCue(e,t){e.cues=e.cues.filter(n=>n.rule.id!==t.payload.id)}},extraReducers:e=>{e.addCase(Ko.pending,t=>{t.fetchState="loading"}).addCase(Ko.rejected,t=>{t.fetchState="error"}).addCase(Ko.fulfilled,(t,n)=>{let r=n.payload.map(i=>i.rule.id),o=t.cues.filter(i=>!r.includes(i.rule.id));t.fetchState="done",t.cues=[...n.payload,...o]}).addCase(le,()=>ty).addCase(UM.toString(),()=>ty)}}),{removeCue:Bb}=zb.actions,jb=zb.reducer;var Qb=S(N());var Gb=S(te()),Yb=S(N());var Kb=S(te());var Vb={root:"dd-uszkm"};var $b=S(b()),zM=({className:e,children:t})=>{let n=P("Unicode",Vb);return(0,$b.jsx)("span",{className:(0,Kb.default)(e,n.root),children:t})},Wb=zM;var qb={isDisabled:"dd-Sp--t",root:"dd-maqTG",buttonStop:"dd-rcq8w",stateBadge:"dd-zOnkT",isCompleted:"dd-GA-rt",isStarted:"dd-PZwtX",isAborted:"dd-PAXSE"};var ny={};je(ny,{enUS:()=>BM,nlNL:()=>jM});var BM={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"}]},jM={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 bt=S(b()),KM=({disabled:e,state:t,displayName:n,description:r,onStartAutoflow:o,onStopAutoflow:i})=>{let s=P("Autoflow",qb),a=$(ny),l=t==="Started"?"stop":"start",u=l==="start"?"\u25B6":l==="stop"?"\u25FC":"";return(0,bt.jsxs)(ne,{className:(0,Gb.default)(s.root,{[s.isDisabled]:e,[s.isCompleted]:t==="Completed",[s.isAborted]:t==="Aborted",[s.isStarted]:t==="Started"}),children:[(0,bt.jsx)(fe,{children:(0,bt.jsxs)(fe.Content,{children:[(0,bt.jsxs)(fe.Title,{children:[t&&(0,bt.jsx)("span",{className:s.stateBadge,children:a(t)}),n]}),(0,bt.jsx)("span",{children:r})]})}),(0,bt.jsx)(ne.Actions,{fixed:t==="Started",children:(0,bt.jsx)(ne.ActionButton,{primary:!0,className:l==="start"?s.buttonStart:s.buttonStop,onClick:t==="Started"?i:o,disabled:e,label:(0,bt.jsxs)(Yb.Fragment,{children:[(0,bt.jsx)(Wb,{children:u})," ",(0,bt.jsx)("span",{children:a(l)})]})})})]})},Xb=KM;var ry=S(b()),WM=(e,t)=>{let n=t.filter(r=>r.state==="Started");return n.length>0?n.indexOf(e)===-1:!1},$M=({autoflows:e,onStartAutoflow:t,onStopAutoflow:n,platformSessionId:r})=>(0,ry.jsx)(Qb.Fragment,{children:e.map(o=>(0,ry.jsx)(Xb,{displayName:o.displayName,description:o.description,disabled:o.isBusy||WM(o,e),state:o.state,onStartAutoflow:()=>t({platformSessionId:r,triggerPayload:o.triggerPayload}),onStopAutoflow:()=>n({platformSessionId:r,triggerPayload:o.triggerPayload})},o.displayName))}),qM=({autoflows:e,conversation:t})=>{var n;return{autoflows:e.list,platformSessionId:(n=t.current)==null?void 0:n.sessionId}},GM={onStartAutoflow:Qh,onStopAutoflow:Zh},Zb=Bn(qM,GM)($M);var Jb=S(te()),oy=S(N());var ir={root:"dd-ERsBr",title:"dd-b36p6",isUsed:"dd-fp2IX",quickReplies:"dd--VrvP",quickReply:"dd-wFhWh",label:"dd-R9sND",errorIcon:"dd-8cdcH"};var ht=S(b()),YM=({suggestion:e})=>{let t=$(Do),n=Y(),r=O(Rb(e.text)),o=O(Ab(e.text)),i=O(Lb(e.text)),s=O($i),{replyOptions:a}=e,l=(0,oy.useCallback)(c=>{c.preventDefault(),c.stopPropagation(),!(r||!s)&&n(lf({platformSessionId:s,suggestion:e}))},[e,r,n,s]),u=(0,oy.useCallback)(c=>{if(c.preventDefault(),c.stopPropagation(),!s||!a)return;let p=parseInt(c.target.dataset.index,10),d=a[p];n(uf({platformSessionId:s,reply:d,suggestion:e}))},[e,r,n,s]);return(0,ht.jsxs)(ne,{onClick:l,className:(0,Jb.default)(ir.root,{[ir.isUsed]:r,[ir.hasError]:i}),children:[(0,ht.jsx)(fe,{children:(0,ht.jsxs)(fe.Content,{children:[(0,ht.jsxs)(fe.Title,{className:ir.title,children:[e.text," ",(0,ht.jsx)(Vl,{className:ir.label,children:"analyse tool"})," ",i&&(0,ht.jsx)("span",{className:ir.errorIcon,role:"img","aria-label":t("sendingError"),title:t("sendingError"),children:"!"})]}),a&&a.length>0&&(0,ht.jsx)("ul",{className:ir.quickReplies,children:a.map(c=>(0,ht.jsx)("li",{className:ir.quickReply,children:c.title},c.title))})]})}),(0,ht.jsxs)(ne.Actions,{fixed:i||r,children:[a&&a.length>0&&(0,ht.jsx)(ne.DropdownButton,{label:t("answer"),disabled:o,children:a.map((c,p)=>(0,ht.jsx)(ne.DropdownItem,{index:p,label:c.title,onClick:u},c.title))}),(0,ht.jsx)(ne.ActionButton,{primary:!0,disabled:r,onClick:l,label:t(r?"suggestionSent":i?"tryAgain":"sendSuggestion")})]})]})},eT=YM;var cf=S(N());var sy=S(te());var iy=S(b()),al=()=>(0,iy.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 512 512",xmlns:"http://www.w3.org/2000/svg",children:(0,iy.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 tT={root:"dd-WcEru",entity:"dd-LfP8y",entityText:"dd-L-v0f",iconWrapper:"dd-9Deh1",icon:"dd-tM7E2",iconClicked:"dd-EEdDL"};var kn=S(b()),XM=({entities:e})=>{let t=P("EntitiesWidgetList",tT),[n,r]=(0,cf.useState)(void 0),o=Y(),i=()=>{r(void 0)},s=a=>{e&&(r(e.indexOf(a)),Wn(a.text),o(Xe({name:"entity copied",data:{entity:a,type:"copy"}})))};return(0,cf.useEffect)(()=>{let a=setTimeout(i,500);return()=>{clearTimeout(a)}},[n]),!e||e.length===0?null:(0,kn.jsx)("div",{className:t.root,"data-testid":"widget-entities-list",children:e.map((a,l)=>(0,kn.jsxs)("button",{title:a.text,className:t.entity,type:"button",onClick:()=>s(a),children:[(0,kn.jsx)("span",{className:t.entityText,children:a.text}),(0,kn.jsxs)("span",{className:t.iconWrapper,children:[(0,kn.jsx)("span",{className:(0,sy.default)(t.icon),children:(0,kn.jsx)(al,{})}),(0,kn.jsx)("span",{className:(0,sy.default)(t.icon,n===l&&t.iconClicked),children:(0,kn.jsx)(al,{})})]})]},a.text))})},nT=XM;var ay=S(b()),rT=()=>(0,ay.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:(0,ay.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 ly=S(b()),oT=()=>(0,ly.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:(0,ly.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 uy=S(b()),iT=()=>(0,uy.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:(0,uy.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 Sy=S(te()),gf=S(N());var ll=S(b()),sT=({className:e})=>(0,ll.jsxs)("svg",{viewBox:"0 0 12 12",version:"1.1",xmlns:"http://www.w3.org/2000/svg",className:e,children:[(0,ll.jsx)("line",{x1:"2",y1:"10",x2:"10",y2:"2",stroke:"black",strokeWidth:"1"}),(0,ll.jsx)("line",{x1:"2",y1:"2",x2:"10",y2:"10",stroke:"black",strokeWidth:"1"})]});var{entries:mT,setPrototypeOf:aT,isFrozen:QM,getPrototypeOf:ZM,getOwnPropertyDescriptor:JM}=Object,{freeze:it,seal:cn,create:gT}=Object,{apply:gy,construct:hy}=typeof Reflect<"u"&&Reflect;it||(it=function(t){return t});cn||(cn=function(t){return t});gy||(gy=function(t,n,r){return t.apply(n,r)});hy||(hy=function(t,n){return new t(...n)});var df=kt(Array.prototype.forEach),lT=kt(Array.prototype.pop),ul=kt(Array.prototype.push),mf=kt(String.prototype.toLowerCase),cy=kt(String.prototype.toString),eN=kt(String.prototype.match),cl=kt(String.prototype.replace),tN=kt(String.prototype.indexOf),nN=kt(String.prototype.trim),un=kt(Object.prototype.hasOwnProperty),Tt=kt(RegExp.prototype.test),dl=rN(TypeError);function kt(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 gy(e,t,r)}}function rN(e){return function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];return hy(e,n)}}function Q(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:mf;aT&&aT(e,null);let r=t.length;for(;r--;){let o=t[r];if(typeof o=="string"){let i=n(o);i!==o&&(QM(t)||(t[r]=i),o=i)}e[o]=!0}return e}function oN(e){for(let t=0;t<e.length;t++)un(e,t)||(e[t]=null);return e}function Wo(e){let t=gT(null);for(let[n,r]of mT(e))un(e,n)&&(Array.isArray(r)?t[n]=oN(r):r&&typeof r=="object"&&r.constructor===Object?t[n]=Wo(r):t[n]=r);return t}function ff(e,t){for(;e!==null;){let r=JM(e,t);if(r){if(r.get)return kt(r.get);if(typeof r.value=="function")return kt(r.value)}e=ZM(e)}function n(){return null}return n}var uT=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"]),dy=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"]),fy=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"]),iN=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"]),py=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"]),sN=it(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),cT=it(["#text"]),dT=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"]),my=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"]),fT=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"]),pf=it(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),aN=cn(/\{\{[\w\W]*|[\w\W]*\}\}/gm),lN=cn(/<%[\w\W]*|[\w\W]*%>/gm),uN=cn(/\${[\w\W]*}/gm),cN=cn(/^data-[\-\w.\u00B7-\uFFFF]/),dN=cn(/^aria-[\-\w]+$/),hT=cn(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),fN=cn(/^(?:\w+script|data):/i),pN=cn(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),yT=cn(/^html$/i),pT=Object.freeze({__proto__:null,MUSTACHE_EXPR:aN,ERB_EXPR:lN,TMPLIT_EXPR:uN,DATA_ATTR:cN,ARIA_ATTR:dN,IS_ALLOWED_URI:hT,IS_SCRIPT_OR_DATA:fN,ATTR_WHITESPACE:pN,DOCTYPE_NAME:yT}),mN=function(){return typeof window>"u"?null:window},gN=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 vT(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:mN(),t=U=>vT(U);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:p,DOMParser:d,trustedTypes:g}=e,y=l.prototype,v=ff(y,"cloneNode"),f=ff(y,"nextSibling"),m=ff(y,"childNodes"),h=ff(y,"parentNode");if(typeof s=="function"){let U=n.createElement("template");U.content&&U.content.ownerDocument&&(n=U.content.ownerDocument)}let x,w="",{implementation:T,createNodeIterator:C,createDocumentFragment:k,getElementsByTagName:I}=n,{importNode:L}=r,_={};t.isSupported=typeof mT=="function"&&typeof h=="function"&&T&&T.createHTMLDocument!==void 0;let{MUSTACHE_EXPR:W,ERB_EXPR:V,TMPLIT_EXPR:Z,DATA_ATTR:ur,ARIA_ATTR:Rt,IS_SCRIPT_OR_DATA:cr,ATTR_WHITESPACE:At}=pT,{IS_ALLOWED_URI:F}=pT,X=null,dr=Q({},[...uT,...dy,...fy,...py,...cT]),he=null,fr=Q({},[...dT,...my,...fT,...pf]),q=Object.seal(gT(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}})),pr=null,kl=null,Yo=!0,eo=!0,ms=!1,Pl=!0,Gt=!1,Yt=!1,Rl=!1,st=!1,Lt=!1,Al=!1,Ll=!1,Oy=!0,My=!1,Ck="user-content-",Pf=!0,gs=!1,Xo={},Qo=null,Ny=Q({},["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"]),_y=null,Dy=Q({},["audio","video","img","source","image","track"]),Rf=null,Fy=Q({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Il="http://www.w3.org/1998/Math/MathML",Ol="http://www.w3.org/2000/svg",An="http://www.w3.org/1999/xhtml",Zo=An,Af=!1,Lf=null,bk=Q({},[Il,Ol,An],cy),hs=null,Tk=["application/xhtml+xml","text/html"],kk="text/html",Ie=null,Jo=null,Pk=n.createElement("form"),Hy=function(E){return E instanceof RegExp||E instanceof Function},If=function(){let E=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(Jo&&Jo===E)){if((!E||typeof E!="object")&&(E={}),E=Wo(E),hs=Tk.indexOf(E.PARSER_MEDIA_TYPE)===-1?kk:E.PARSER_MEDIA_TYPE,Ie=hs==="application/xhtml+xml"?cy:mf,X=un(E,"ALLOWED_TAGS")?Q({},E.ALLOWED_TAGS,Ie):dr,he=un(E,"ALLOWED_ATTR")?Q({},E.ALLOWED_ATTR,Ie):fr,Lf=un(E,"ALLOWED_NAMESPACES")?Q({},E.ALLOWED_NAMESPACES,cy):bk,Rf=un(E,"ADD_URI_SAFE_ATTR")?Q(Wo(Fy),E.ADD_URI_SAFE_ATTR,Ie):Fy,_y=un(E,"ADD_DATA_URI_TAGS")?Q(Wo(Dy),E.ADD_DATA_URI_TAGS,Ie):Dy,Qo=un(E,"FORBID_CONTENTS")?Q({},E.FORBID_CONTENTS,Ie):Ny,pr=un(E,"FORBID_TAGS")?Q({},E.FORBID_TAGS,Ie):{},kl=un(E,"FORBID_ATTR")?Q({},E.FORBID_ATTR,Ie):{},Xo=un(E,"USE_PROFILES")?E.USE_PROFILES:!1,Yo=E.ALLOW_ARIA_ATTR!==!1,eo=E.ALLOW_DATA_ATTR!==!1,ms=E.ALLOW_UNKNOWN_PROTOCOLS||!1,Pl=E.ALLOW_SELF_CLOSE_IN_ATTR!==!1,Gt=E.SAFE_FOR_TEMPLATES||!1,Yt=E.WHOLE_DOCUMENT||!1,Lt=E.RETURN_DOM||!1,Al=E.RETURN_DOM_FRAGMENT||!1,Ll=E.RETURN_TRUSTED_TYPE||!1,st=E.FORCE_BODY||!1,Oy=E.SANITIZE_DOM!==!1,My=E.SANITIZE_NAMED_PROPS||!1,Pf=E.KEEP_CONTENT!==!1,gs=E.IN_PLACE||!1,F=E.ALLOWED_URI_REGEXP||hT,Zo=E.NAMESPACE||An,q=E.CUSTOM_ELEMENT_HANDLING||{},E.CUSTOM_ELEMENT_HANDLING&&Hy(E.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(q.tagNameCheck=E.CUSTOM_ELEMENT_HANDLING.tagNameCheck),E.CUSTOM_ELEMENT_HANDLING&&Hy(E.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(q.attributeNameCheck=E.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),E.CUSTOM_ELEMENT_HANDLING&&typeof E.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(q.allowCustomizedBuiltInElements=E.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),Gt&&(eo=!1),Al&&(Lt=!0),Xo&&(X=Q({},cT),he=[],Xo.html===!0&&(Q(X,uT),Q(he,dT)),Xo.svg===!0&&(Q(X,dy),Q(he,my),Q(he,pf)),Xo.svgFilters===!0&&(Q(X,fy),Q(he,my),Q(he,pf)),Xo.mathMl===!0&&(Q(X,py),Q(he,fT),Q(he,pf))),E.ADD_TAGS&&(X===dr&&(X=Wo(X)),Q(X,E.ADD_TAGS,Ie)),E.ADD_ATTR&&(he===fr&&(he=Wo(he)),Q(he,E.ADD_ATTR,Ie)),E.ADD_URI_SAFE_ATTR&&Q(Rf,E.ADD_URI_SAFE_ATTR,Ie),E.FORBID_CONTENTS&&(Qo===Ny&&(Qo=Wo(Qo)),Q(Qo,E.FORBID_CONTENTS,Ie)),Pf&&(X["#text"]=!0),Yt&&Q(X,["html","head","body"]),X.table&&(Q(X,["tbody"]),delete pr.tbody),E.TRUSTED_TYPES_POLICY){if(typeof E.TRUSTED_TYPES_POLICY.createHTML!="function")throw dl('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof E.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw dl('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');x=E.TRUSTED_TYPES_POLICY,w=x.createHTML("")}else x===void 0&&(x=gN(g,o)),x!==null&&typeof w=="string"&&(w=x.createHTML(""));it&&it(E),Jo=E}},Uy=Q({},["mi","mo","mn","ms","mtext"]),zy=Q({},["foreignobject","desc","title","annotation-xml"]),Rk=Q({},["title","style","font","a","script"]),By=Q({},[...dy,...fy,...iN]),jy=Q({},[...py,...sN]),Ak=function(E){let A=h(E);(!A||!A.tagName)&&(A={namespaceURI:Zo,tagName:"template"});let D=mf(E.tagName),ce=mf(A.tagName);return Lf[E.namespaceURI]?E.namespaceURI===Ol?A.namespaceURI===An?D==="svg":A.namespaceURI===Il?D==="svg"&&(ce==="annotation-xml"||Uy[ce]):!!By[D]:E.namespaceURI===Il?A.namespaceURI===An?D==="math":A.namespaceURI===Ol?D==="math"&&zy[ce]:!!jy[D]:E.namespaceURI===An?A.namespaceURI===Ol&&!zy[ce]||A.namespaceURI===Il&&!Uy[ce]?!1:!jy[D]&&(Rk[D]||!By[D]):!!(hs==="application/xhtml+xml"&&Lf[E.namespaceURI]):!1},to=function(E){ul(t.removed,{element:E});try{E.parentNode.removeChild(E)}catch{E.remove()}},Of=function(E,A){try{ul(t.removed,{attribute:A.getAttributeNode(E),from:A})}catch{ul(t.removed,{attribute:null,from:A})}if(A.removeAttribute(E),E==="is"&&!he[E])if(Lt||Al)try{to(A)}catch{}else try{A.setAttribute(E,"")}catch{}},Vy=function(E){let A=null,D=null;if(st)E="<remove></remove>"+E;else{let Be=eN(E,/^[\r\n\t ]+/);D=Be&&Be[0]}hs==="application/xhtml+xml"&&Zo===An&&(E='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+E+"</body></html>");let ce=x?x.createHTML(E):E;if(Zo===An)try{A=new d().parseFromString(ce,hs)}catch{}if(!A||!A.documentElement){A=T.createDocument(Zo,"template",null);try{A.documentElement.innerHTML=Af?w:ce}catch{}}let ze=A.body||A.documentElement;return E&&D&&ze.insertBefore(n.createTextNode(D),ze.childNodes[0]||null),Zo===An?I.call(A,Yt?"html":"body")[0]:Yt?A.documentElement:ze},Ky=function(E){return C.call(E.ownerDocument||E,E,u.SHOW_ELEMENT|u.SHOW_COMMENT|u.SHOW_TEXT,null)},Lk=function(E){return E instanceof p&&(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")},Wy=function(E){return typeof a=="function"&&E instanceof a},Ln=function(E,A,D){_[E]&&df(_[E],ce=>{ce.call(t,A,D,Jo)})},$y=function(E){let A=null;if(Ln("beforeSanitizeElements",E,null),Lk(E))return to(E),!0;let D=Ie(E.nodeName);if(Ln("uponSanitizeElement",E,{tagName:D,allowedTags:X}),E.hasChildNodes()&&!Wy(E.firstElementChild)&&Tt(/<[/\w]/g,E.innerHTML)&&Tt(/<[/\w]/g,E.textContent))return to(E),!0;if(!X[D]||pr[D]){if(!pr[D]&&Gy(D)&&(q.tagNameCheck instanceof RegExp&&Tt(q.tagNameCheck,D)||q.tagNameCheck instanceof Function&&q.tagNameCheck(D)))return!1;if(Pf&&!Qo[D]){let ce=h(E)||E.parentNode,ze=m(E)||E.childNodes;if(ze&&ce){let Be=ze.length;for(let at=Be-1;at>=0;--at)ce.insertBefore(v(ze[at],!0),f(E))}}return to(E),!0}return E instanceof l&&!Ak(E)||(D==="noscript"||D==="noembed"||D==="noframes")&&Tt(/<\/no(script|embed|frames)/i,E.innerHTML)?(to(E),!0):(Gt&&E.nodeType===3&&(A=E.textContent,df([W,V,Z],ce=>{A=cl(A,ce," ")}),E.textContent!==A&&(ul(t.removed,{element:E.cloneNode()}),E.textContent=A)),Ln("afterSanitizeElements",E,null),!1)},qy=function(E,A,D){if(Oy&&(A==="id"||A==="name")&&(D in n||D in Pk))return!1;if(!(eo&&!kl[A]&&Tt(ur,A))){if(!(Yo&&Tt(Rt,A))){if(!he[A]||kl[A]){if(!(Gy(E)&&(q.tagNameCheck instanceof RegExp&&Tt(q.tagNameCheck,E)||q.tagNameCheck instanceof Function&&q.tagNameCheck(E))&&(q.attributeNameCheck instanceof RegExp&&Tt(q.attributeNameCheck,A)||q.attributeNameCheck instanceof Function&&q.attributeNameCheck(A))||A==="is"&&q.allowCustomizedBuiltInElements&&(q.tagNameCheck instanceof RegExp&&Tt(q.tagNameCheck,D)||q.tagNameCheck instanceof Function&&q.tagNameCheck(D))))return!1}else if(!Rf[A]){if(!Tt(F,cl(D,At,""))){if(!((A==="src"||A==="xlink:href"||A==="href")&&E!=="script"&&tN(D,"data:")===0&&_y[E])){if(!(ms&&!Tt(cr,cl(D,At,"")))){if(D)return!1}}}}}}return!0},Gy=function(E){return E!=="annotation-xml"&&E.indexOf("-")>0},Yy=function(E){Ln("beforeSanitizeAttributes",E,null);let{attributes:A}=E;if(!A)return;let D={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:he},ce=A.length;for(;ce--;){let ze=A[ce],{name:Be,namespaceURI:at,value:no}=ze,ys=Ie(Be),lt=Be==="value"?no:nN(no);if(D.attrName=ys,D.attrValue=lt,D.keepAttr=!0,D.forceKeepAttr=void 0,Ln("uponSanitizeAttribute",E,D),lt=D.attrValue,D.forceKeepAttr||(Of(Be,E),!D.keepAttr))continue;if(!Pl&&Tt(/\/>/i,lt)){Of(Be,E);continue}Gt&&df([W,V,Z],Qy=>{lt=cl(lt,Qy," ")});let Xy=Ie(E.nodeName);if(qy(Xy,ys,lt)){if(My&&(ys==="id"||ys==="name")&&(Of(Be,E),lt=Ck+lt),x&&typeof g=="object"&&typeof g.getAttributeType=="function"&&!at)switch(g.getAttributeType(Xy,ys)){case"TrustedHTML":{lt=x.createHTML(lt);break}case"TrustedScriptURL":{lt=x.createScriptURL(lt);break}}try{at?E.setAttributeNS(at,Be,lt):E.setAttribute(Be,lt),lT(t.removed)}catch{}}}Ln("afterSanitizeAttributes",E,null)},Ik=function U(E){let A=null,D=Ky(E);for(Ln("beforeSanitizeShadowDOM",E,null);A=D.nextNode();)Ln("uponSanitizeShadowNode",A,null),!$y(A)&&(A.content instanceof i&&U(A.content),Yy(A));Ln("afterSanitizeShadowDOM",E,null)};return t.sanitize=function(U){let E=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},A=null,D=null,ce=null,ze=null;if(Af=!U,Af&&(U="<!-->"),typeof U!="string"&&!Wy(U))if(typeof U.toString=="function"){if(U=U.toString(),typeof U!="string")throw dl("dirty is not a string, aborting")}else throw dl("toString is not a function");if(!t.isSupported)return U;if(Rl||If(E),t.removed=[],typeof U=="string"&&(gs=!1),gs){if(U.nodeName){let no=Ie(U.nodeName);if(!X[no]||pr[no])throw dl("root node is forbidden and cannot be sanitized in-place")}}else if(U instanceof a)A=Vy("<!---->"),D=A.ownerDocument.importNode(U,!0),D.nodeType===1&&D.nodeName==="BODY"||D.nodeName==="HTML"?A=D:A.appendChild(D);else{if(!Lt&&!Gt&&!Yt&&U.indexOf("<")===-1)return x&&Ll?x.createHTML(U):U;if(A=Vy(U),!A)return Lt?null:Ll?w:""}A&&st&&to(A.firstChild);let Be=Ky(gs?U:A);for(;ce=Be.nextNode();)$y(ce)||(ce.content instanceof i&&Ik(ce.content),Yy(ce));if(gs)return U;if(Lt){if(Al)for(ze=k.call(A.ownerDocument);A.firstChild;)ze.appendChild(A.firstChild);else ze=A;return(he.shadowroot||he.shadowrootmode)&&(ze=L.call(r,ze,!0)),ze}let at=Yt?A.outerHTML:A.innerHTML;return Yt&&X["!doctype"]&&A.ownerDocument&&A.ownerDocument.doctype&&A.ownerDocument.doctype.name&&Tt(yT,A.ownerDocument.doctype.name)&&(at="<!DOCTYPE "+A.ownerDocument.doctype.name+`>
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 _h=S(b()),ZO={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},AC=({className:e,color:t})=>(0,_h.jsx)("svg",{className:e,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:(0,_h.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:ZO[t||"pink"]})});var LC={root:"dd-LbeUM",text:"dd-Dpfn1",isLoggedIn:"dd-XvHAn",isLoggedOut:"dd-21y-z",icon:"dd-8rLqS",logo:"dd-slXhD",lock:"dd-ByzlR"};var Dh={};je(Dh,{enUS:()=>JO,nlNL:()=>eM});var JO={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Search"}]},eM={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Zoeken"}]};var zo=S(b()),OC=({onLogIn:e})=>{let t=$(Dh),n=B("floatingMenu"),r=B("productName"),o=Y(),i=O(tt),s=P("FloatingMenu",LC);if(i===null||n===!1)return null;let a=()=>{i===!0?o(wt(!0)):e()};return(0,zo.jsxs)("button",{className:(0,IC.default)(s.root,{[s.isLoggedIn]:i,[s.isLoggedOut]:!i}),onClick:a,children:[(0,zo.jsx)("div",{className:s.text,children:t(i?"search":"signin",{productName:r})}),(0,zo.jsxs)("div",{className:s.icon,children:[(0,zo.jsx)(AC,{className:s.logo,color:"pink"}),i===!1&&(0,zo.jsx)(RC,{className:s.lock})]})]})};var Vd=S(N());var MC=S(N());function $r(e){(0,MC.useEffect)(()=>{let t=n=>{n.isWithinRoot||e(n)};return document.body.addEventListener("mouseup",t),()=>{document.body.removeEventListener("mouseup",t)}},[e])}function Bo(e){e.addEventListener("mouseup",t=>{t.isWithinRoot=!0},!0)}function rs(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 tM={showTabHint:!1,inputHasFocus:!1,overlayCollapsed:!1,openOverlayWhenTyping:!1,overlayCollapsedUserOverwrite:!1};var zd=({ui:e})=>e.overlayCollapsed;var NC=G({name:"ui",initialState:tM,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:nl,setInputHasFocus:Fh,setOverlayCollapsed:qr,setOpenOverlayWhenTyping:_C,setOverlayCollapsedUserOverwrite:DC}=NC.actions,FC=NC.reducer;var Bd=S(N());var os=S(N());var HC=S(N());function UC(e,t,n){(0,HC.useEffect)(()=>{let r=e.current;return r?(r.addEventListener(t,n),()=>{r.removeEventListener(t,n)}):()=>{}},[e,t,n])}var zC={root:"dd-1MBCO",actions:"dd--x4cy",badge:"dd-4Fpkz",formattedText:"dd-EzvTB"};var jo=S(b()),rM=["search","personal-collection-search","search-autocomplete"];function oM(e,t,n,r={}){let o="";return rM.includes(t)?o=PE(xh(e,n,{stripAgentPart:!0}),r.searchKeywords??[n]):o=xh(e,n,r),r.placeholders===!0&&(o=RE(o)),o}var iM=()=>{},sM=({index:e,selected:t,suggestion:n,onFeedback:r})=>{let o=B("inlineSuggestions"),i=O(Gi),s=Y(),a=P("TextSuggestion",zC),l=(0,os.useRef)(null);(0,os.useEffect)(()=>{let c=setTimeout(()=>{s(T1({text:n.text,suggestion:n}))},500);return()=>{clearTimeout(c)}},[n]),UC(l,"click",()=>{s(Br(e)),s(Cn({suggestion:n,text:n.text,eventMetrics:{inputType:"mouse"},replace:"until-selection-end"}))});let u=(0,os.useMemo)(()=>oM(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,jo.jsxs)("div",{className:a.root,onMouseEnter:()=>s(Br(e)),children:[(0,jo.jsx)(ne,{ref:l,as:"button","data-testid":"suggestions-overlay-item",selected:t,onClick:iM,children:(0,jo.jsx)(Xi,{containerTagName:"div",noWrap:!1,tagName:"span",className:a.formattedText,content:u})}),t&&r&&(0,jo.jsx)("div",{className:a.actions,children:(0,jo.jsx)(Ad,{onFeedback:()=>r(n),suggestion:n.text})})]})},BC=sM;var Hh=S(b()),aM=({onFeedback:e,suggestions:t,selectedIndex:n,reverse:r})=>{let o=(0,Bd.useMemo)(()=>{let i=t.map((s,a)=>(0,Hh.jsx)(BC,{index:a,selected:a===n,suggestion:s,onFeedback:e},`${s.text}-${s.source}`));return r?i.reverse():i},[t,n,r]);return(0,Hh.jsx)(Bd.Fragment,{children:o})},jd=aM;var jC={root:"dd-PfvRI",paper:"dd-HYlyY"};var rl=S(b()),lM=({textSuggestions:e,selectedIndex:t})=>{let n=(0,Vd.useRef)(null),r=P("InlineSuggestionsOverlay",jC),o=O(rs),i=Y(),s=O(tt),a=O(qi),l=O(zd),u=B("showTextSuggestions");return $r(()=>{setTimeout(()=>{i(qr({collapse:!0,skipWhenInputFocus:!0}))})}),(0,Vd.useEffect)(()=>{let c=n.current;if(!c||!c.parentElement)return;c.parentElement.style.left="0px";let p=c.getBoundingClientRect();c.parentElement.style.left=`${Math.min(window.innerWidth-4-p.right,0)}px`}),l||!o||!u||e.length===0||s!==!0||a===!1?null:(0,rl.jsx)("div",{className:r.root,"data-variant":"inline",children:(0,rl.jsx)("div",{ref:n,className:r.paper,children:(0,rl.jsx)(ct,{children:(0,rl.jsx)(jd,{suggestions:e,selectedIndex:t})})})})},uM=({input:e})=>({selectedIndex:e.selectedSuggestionIndex,textSuggestions:e.textSuggestions}),VC=Bn(uM)(lM);var ol=S(b()),cM=({children:e})=>{let n=B("locale").replace("-","");return(0,ol.jsx)(ih.Provider,{value:n,children:e})},dM=({store:e,customStyles:t={},children:n})=>(0,ol.jsx)(Hg,{store:e,children:(0,ol.jsx)(cM,{children:(0,ol.jsx)(Ss.Provider,{value:t,children:n})})}),Vo=dM;var Wd=S(te()),is=S(N());var KC=S(N());function WC(e,t){let[n,r]=(0,KC.useState)(()=>{if(typeof window>"u")return t;try{let i=window.localStorage.getItem(e);return i?JSON.parse(i):t}catch(i){return H.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){H.error(s)}}]}var $C=()=>/Mac/i.test(navigator.platform);var GC=S(te()),Jn=S(N());var Uh={};je(Uh,{enUS:()=>fM,nlNL:()=>pM});var fM={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"}]}]},pM={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 qC={root:"dd-uTPjX",anchor:"dd-C8lsZ",anchorButton:"dd-IoSx9"};var Gr=S(b()),zh=(e,t,n)=>r=>(0,Gr.jsx)("button",{className:e.anchorButton,type:"button",value:t,onClick:n,children:r},t),mM=({className:e,loginUrl:t,isEmbedded:n,onSnooze:r,onLogIn:o})=>{let i=$(Uh),s=jt(),a=P("Login",qC),l=B("productName"),u=(0,Jn.useCallback)(f=>{f.preventDefault(),r&&r(parseInt(f.target.value,10))},[]),c=(0,Jn.useCallback)(f=>{f.preventDefault(),s.send(Yi,!0)},[t]),p=(0,Jn.useMemo)(()=>f=>(0,Gr.jsx)("a",{onClick:h=>{h.preventDefault(),o()},href:t,className:a.anchor,target:"_blank",rel:"noreferrer",children:f},"login"),[t]),d=(0,Jn.useCallback)(f=>(0,Gr.jsx)("button",{type:"button",className:a.anchorButton,onClick:c,children:f},"prompt"),[c]),{min:g,hour:y,day:v}=(0,Jn.useMemo)(()=>({min:zh(a,60*10,u),hour:zh(a,60*60,u),day:zh(a,60*60*12,u)}),[]);return(0,Gr.jsxs)("div",{className:(0,GC.default)(e,a.root),children:[i("loginPlease",{login:n?d:p,productName:l}),r&&(0,Gr.jsxs)(Jn.Fragment,{children:[(0,Gr.jsx)("br",{}),i("snooze",{min:g,hour:y,day:v})]})]})},Kd=mM;var YC={root:"dd-DoQhb",text:"dd-Jwnev"};var il=S(b()),gM=({title:e})=>{let t=P("SearchTrigger",YC),n=Y();return(0,il.jsxs)("button",{type:"button",className:t.root,onClick:()=>n(wt(!0)),children:[(0,il.jsx)(Zi,{}),(0,il.jsx)("span",{className:t.text,children:e})]})},XC=gM;var Bh={};je(Bh,{enUS:()=>hM,nlNL:()=>yM});var hM={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"}]},yM={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 QC={root:"dd-oa7Vc",isInline:"dd-bwk31",toggleButton:"dd-MSB8Z",toggleButtonWrapper:"dd-ZkCzT",toggleButtonWrapperHidden:"dd-Sq66c",isCollapsed:"dd-vkrPk",collapsible:"dd-CWQJe",hints:"dd-IOoo3",hintsHidden:"dd-psVuT",triggers:"dd-toIoo",triggersRight:"dd-mc4l2"};var Se=S(b()),vM=({textSuggestions:e,selectedIndex:t,onLogIn:n})=>{let r=P("SuggestionsOverlay",QC),o=$(Bh),i=O(rs),s=w1(),a=Y(),l=(0,is.useRef)(null),u=B("searchTriggerKey"),c=B("productName"),p=O(zd),d=O(tt),g=O(qi),[y,v]=(0,is.useState)(null),f=B("showSearch"),m=B("showTextSuggestions"),h=B("adminUrl"),x=B("isEmbedded"),[w,T]=WC("dd-snooze-until-ms",0),C=p||w>Date.now(),k=O(V=>V.input.text),I=e.filter(V=>V.source!=="gpt").length,L=()=>{C&&T(0),a(DC(!C))},_=V=>{a(Xe({name:"suggestion feedback",data:{text:V.text,source:"overlay",context:k},options:{includeConversationData:!0}}))},W=V=>{let Z=Date.now()+V*1e3;T(Z),H.info(`Snooze until: ${new Date(Z)}`),a(qr({collapse:!0}))};return(0,is.useEffect)(()=>{I===0&&v(null)},[e,I]),$r(()=>{a(qr({collapse:!0,skipWhenInputFocus:!0}))}),d===null||g===!1?null:d===!1?(0,Se.jsxs)("div",{ref:l,className:(0,Wd.default)(r.root,{[r.isCollapsed]:C}),children:[!C&&(0,Se.jsxs)("div",{className:r.triggers,children:[(0,Se.jsx)("div",{style:{flex:1}}),(0,Se.jsx)("div",{className:r.triggersRight,children:(0,Se.jsx)(ao,{className:r.toggleButton,title:o("collapse"),onClick:L,isCollapsed:!1})})]}),(0,Se.jsx)("div",{className:r.toggleButtonWrapper,children:(0,Se.jsx)(ao,{className:r.toggleButton,title:o("open",{productName:c}),onClick:L,isCollapsed:!0})}),(0,Se.jsx)("div",{className:r.collapsible,children:(0,Se.jsx)(Kd,{loginUrl:h,isEmbedded:x,onLogIn:n,onSnooze:W})})]}):!s||!i?null:(0,Se.jsxs)("div",{ref:l,className:(0,Wd.default)(r.root,{[r.isCollapsed]:C}),children:[!C&&(0,Se.jsxs)("div",{className:r.triggers,children:[(0,Se.jsx)("div",{style:{flex:1},children:f&&(0,Se.jsx)("div",{style:{display:"inline-block"},onFocus:()=>{},onMouseOver:()=>v(o($C()?"searchHintMac":"searchHintWindows",{searchTriggerKey:u.toUpperCase()})),onMouseLeave:()=>v(null),children:(0,Se.jsx)(XC,{title:o("search")})})}),(0,Se.jsxs)("div",{className:r.triggersRight,onFocus:()=>{},children:[(0,Se.jsx)("div",{className:(0,Wd.default)(!y&&r.hintsHidden,r.hints),children:y}),(0,Se.jsx)(ao,{className:r.toggleButton,title:o("collapse"),onClick:L,isCollapsed:!1})]})]}),(0,Se.jsx)("div",{className:r.toggleButtonWrapper,children:(0,Se.jsx)(ao,{className:r.toggleButton,title:o("open",{productName:c}),onClick:L,isCollapsed:!0})}),I>0&&m&&(0,Se.jsx)("div",{className:r.collapsible,onFocus:()=>{},children:(0,Se.jsx)(ct,{children:(0,Se.jsx)(jd,{onFeedback:_,suggestions:e,selectedIndex:t,reverse:!0})})})]})},SM=({input:e})=>({selectedIndex:e.selectedSuggestionIndex,textSuggestions:e.textSuggestions}),ZC=Bn(SM)(vM);var af=S(te());var rr=S(N());var ss=S(N());function $d(e){return e.contentEditable==="true"}function xM(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 JC(e){let{selectionStart:t,selectionEnd:n}=$d(e)?xM(e):e;return[t,n]}function eb(e){let[,t]=(0,ss.useState)(),n=(0,ss.useRef)(null);return n.current=JC(e),(0,ss.useEffect)(()=>{let r=()=>{let[o,i]=n.current??[],s=JC(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 tb(e,t){if(!t)return;let n=e,{value:r}=n,[o,i]=t,s=r.match($l);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 nb=S(N()),wM=["div","span","mark","strong","b","i","u","em"];function jh(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(wM.includes(o)){let s=Array.isArray(r.props.children)?r.props.children:[r.props.children];return[...e.slice(0,e.length-1),(0,nb.cloneElement)(r,{children:jh(s,t,n+1)})]}return[...e,...t]}function Yr(e){return e.tagName.toLowerCase()==="textarea"}var rb={root:"dd-7-cgW",container:"dd-PsRQ8",agentText:"dd-qnW-V",tabText:"dd-cUHUr",hint:"dd-v7fSg",matchSelection:"dd-8cr8y",focus:"dd-3tr9l",resetIndent:"dd-TvQfZ",matchKeyword:"dd-oJkRD",matchPlaceholder:"dd-QvNoo",hover:"dd--wi0R",hintText:"dd-7gQQh",popover:"dd-xbRu-",popoverRoot:"dd-rA2x8",popoverContentContainer:"dd-JHICl",popoverContent:"dd--mfkC",selectionOptions:"dd-p52wn",selectionOptionsIsHidden:"dd-sSTDp",selectionOptionsButton:"dd-Q6kRY",caret:"dd-jIhc8",popoverSuggestionsRoot:"dd-iFDbL",suggestionsOverlayInputStyles:"dd-zzENA"};var pb=S(te());var tf=S(N());var as=S(N());function ob(e,t){let n;return[(...r)=>{window.cancelAnimationFrame(n);let o=t?t(...r):r;n=window.requestAnimationFrame(()=>{e(...o)})},()=>window.cancelAnimationFrame(n)]}function qd(e){let t=(0,as.useRef)(null),[n,r]=(0,as.useState)(!1);return(0,as.useEffect)(()=>{let o=!1,i=parseFloat(window.getComputedStyle(document.body).zoom??"1"),[s,a]=ob((c,p)=>{let d=t.current;if(!d)return;let g=c/i,y=p/i,v=d.getBoundingClientRect(),f=g>v.x&&g<v.x+v.width&&y>v.y&&y<v.y+v.height;f&&!o?(o=!0,r(!0)):!f&&o&&(o=!1,r(!1))},({clientX:c,clientY:p})=>[c,p]),[l,u]=ob(()=>{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 ib(e){return e.replace(/[.*+^${}()|[\]\\]/g,"\\$&")}function Gd(e){return t=>{e.forEach(n=>{typeof n=="function"?n(t):n!=null&&(n.current=t)})}}function sb(e){return e!=null}var Kh=S(te()),Kt=S(N());var Yd=S(N()),EM=["bottom","height","left","right","top","width"],CM=(e={},t={})=>EM.some(n=>e[n]!==t[n]),er=new Map,ab,lb=()=>{let e=[],t=[];er.forEach((n,r)=>{if(r instanceof Element&&!r.isConnected){t.push(r);return}let o=r.getBoundingClientRect();CM(o,n.rect)&&(n.rect=o,e.push(n))}),t.forEach(n=>{er.delete(n)}),e.forEach(n=>{n.callbacks.forEach(r=>r(n.rect))}),ab=window.requestAnimationFrame(lb)};function bM(e,t){return{observe(){let n=er.size===0;if(er.has(e)){let r=er.get(e);r.callbacks.push(t),r.rect&&t(r.rect)}else er.set(e,{rect:void 0,hasRectChanged:!1,callbacks:[t]});n&&lb()},unobserve(){let n=er.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||er.delete(e),er.size||cancelAnimationFrame(ab)}}}}function Vh(e){let[t,n]=(0,Yd.useState)(null);return(0,Yd.useLayoutEffect)(()=>{if(!e.current)return;let r=bM(e.current,o=>{n(o)});return r.observe(),()=>{r.unobserve()}},[e]),t}var ls=S(N()),cb=S(sc());var ub={root:"dd-r-dgo"};var db=({children:e,parentNode:t})=>{let[n,r]=(0,ls.useState)(null),o=(0,ls.useContext)(Ss);return(0,ls.useLayoutEffect)(()=>{let i=document.createElement("div");return Bo(i),i.classList.add(ub.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,cb.createPortal)(e,n):null};var Tn={ref:"dd-iz-KP",root:"dd-vEMon",positionAbove:"dd-mUCxM",positionBelow:"dd-7oZI7",positionLeft:"dd-BiWvD",positionRight:"dd-JIWea",alignStart:"dd-5ivu6",alignCenter:"dd-rnVkP",alignEnd:"dd-gZBp4"};var Xd=S(b()),Qd=(e=!1)=>{let[t,n]=(0,Kt.useState)(e),r=(0,Kt.useCallback)(()=>n(!0),[]),o=(0,Kt.useCallback)(()=>n(!1),[]),i=(0,Kt.useCallback)(()=>n(a=>!a),[]),s=(0,Kt.useRef)(null);return{opened:t,open:r,close:o,toggle:i,triggerRef:s}};function Wh(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 us=({className:e,triggerRef:t,boundaryRef:n=(0,Kt.createRef)(),position:r="above",align:o="center",children:i,toStyle:s=Wh,parentNode:a,...l})=>{let u=Vh(t),c=Vh(n),p=(0,Kt.useMemo)(()=>s(u,c,0),[u,c]);return(0,Xd.jsx)(db,{parentNode:a,children:(0,Xd.jsx)("div",{className:(0,Kh.default)(Tn.ref,{[Tn.positionAbove]:r==="above",[Tn.positionBelow]:r==="below",[Tn.positionLeft]:r==="left",[Tn.positionRight]:r==="right",[Tn.alignStart]:o==="start",[Tn.alignCenter]:o==="center",[Tn.alignEnd]:o==="end"}),style:p,...l,role:"dialog",children:(0,Xd.jsx)("div",{className:(0,Kh.default)(e,Tn.root),children:i})})})};var fb=S(te()),Zd=S(N());var tr={root:"dd-7-cgW",container:"dd-PsRQ8",agentText:"dd-qnW-V",tabText:"dd-cUHUr",hint:"dd-v7fSg",matchSelection:"dd-8cr8y",focus:"dd-3tr9l",resetIndent:"dd-TvQfZ",matchKeyword:"dd-oJkRD",matchPlaceholder:"dd-QvNoo",hover:"dd--wi0R",hintText:"dd-7gQQh",popover:"dd-xbRu-",popoverRoot:"dd-rA2x8",popoverContentContainer:"dd-JHICl",popoverContent:"dd--mfkC",selectionOptions:"dd-p52wn",selectionOptionsIsHidden:"dd-sSTDp",selectionOptionsButton:"dd-Q6kRY",caret:"dd-jIhc8",popoverSuggestionsRoot:"dd-iFDbL",suggestionsOverlayInputStyles:"dd-zzENA"};var $h=S(b()),Jd=(0,Zd.forwardRef)(({className:e,children:t,...n},r)=>{let o=(0,Zd.useRef)(null),i=P("TabCompletion",tr);return(0,$h.jsx)("div",{ref:Gd([o,r]),className:(0,fb.default)(e,i.popoverContentContainer),...n,children:(0,$h.jsx)("div",{className:i.popoverContent,children:t})})});var Xr=S(b()),TM=e=>t=>{let n=Wh(t);return"top"in n&&(n.width=e.width-(t.left-e.left)-10),n},kM=({inputElement:e,boundaryRef:t,inputStyle:n,children:r,suggestion:o})=>{let i=P("TabCompletion",tr),s=Qd(),a=(0,tf.useMemo)(()=>TM(e.getBoundingClientRect()),[e]),[l,u]=qd(e);return(0,tf.useEffect)(()=>{u?s.open():s.close()},[u]),(0,Xr.jsxs)("span",{children:[(0,Xr.jsx)("mark",{ref:Gd([l,s.triggerRef]),className:(0,pb.default)(i.matchKeyword,{[i.hover]:u}),"aria-haspopup":"dialog","aria-expanded":s.opened?"true":"false",children:r}),s.opened&&(0,Xr.jsx)(us,{className:i.popover,triggerRef:s.triggerRef,boundaryRef:t,position:"below",align:"start",toStyle:a,children:(0,Xr.jsx)(Jd,{style:n,children:(0,Xr.jsx)("div",{className:i.hintText,children:o})})})]})},ef=class extends $n{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${ib(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(sb);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,Xr.jsx)(kM,{inputElement:n.inputElement,suggestion:n.suggestion,inputStyle:n.inputStyle,boundaryRef:n.boundaryRef,children:t},`keyword_${n.matchString}_${n.key}`)}asTag(){return"mark"}};var mb=S(te());var qh=S(b()),PM=({inputElement:e,children:t})=>{let n=P("TabCompletion",tr),[r,o]=qd(e);return(0,qh.jsx)("mark",{ref:r,className:(0,mb.default)(n.matchPlaceholder,{[n.hover]:o}),children:t})},nf=class extends $n{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,qh.jsx)(PM,{inputElement:n.inputElement,children:t},`placeholder_${n.matchString}_${n.key}`)}asTag(){return"mark"}};var of=S(te());var ot=S(N());var Gh=S(b()),gb=()=>(0,Gh.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,Gh.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 Qr=S(N());var yb=S(ch());var hb={root:"dd-ky-Bv",content:"dd-kV5e1"};function rf(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 Yh(e){return e.replace("https://www.","").replace("https://","")}var Wt=S(b()),RM=3,AM=e=>({image:e.image||"",text:e.text,id:e.id,title:e.title}),LM=({onSelectLink:e,onDismiss:t,placeholder:n,visitUrlText:r,linkCount:o=RM})=>{let i=P("LinkSearch",hb),[s,a]=(0,Qr.useState)(""),l=Y(),u=O(yC("url")),c=O(K1("URL",AM)),[p,d]=(0,Qr.useState)(c.length-1),g=B("fallbackImage"),y=h=>{let x=h.target;a(x.value)},v=(h,x)=>{h.stopPropagation(),h.preventDefault(),window.open(x,"_blank")},f=h=>{var T;let x=p-1<0?c.length-1:p-1,w=p+1===c.length?0:p+1;h.code==="Escape"&&(a(""),t()),h.code==="ArrowUp"&&d(x),h.code==="ArrowDown"&&d(w),h.code==="Enter"&&e(((T=c[p])==null?void 0:T.text)||s)},m=(0,Qr.useCallback)((0,yb.default)(h=>{l(Po({query:h,type:"URL",tags:["link-search"]}))},300),[]);return(0,Qr.useEffect)(()=>{s&&m(s)},[s]),(0,Qr.useEffect)(()=>()=>{l(td())},[]),(0,Wt.jsxs)("div",{className:i.root,children:[(0,Wt.jsx)(ct,{withDivider:!0,children:(s?c:u).slice(0,o).map((h,x)=>(0,Wt.jsx)(ne,{selected:p===x,onClick:()=>e(h.text),"data-testid":"linksearch-suggestion",children:(0,Wt.jsxs)(fe,{children:[(0,Wt.jsx)(fe.Image,{src:rf(h,"small",g||void 0),title:h.title||h.text}),(0,Wt.jsxs)(fe.Content,{className:i.content,cropText:!0,children:[(0,Wt.jsx)(fe.Title,{children:h.title||Yh(h.text)}),h.title&&Yh(h.text)]}),(0,Wt.jsx)(ne.Actions,{children:(0,Wt.jsx)(ne.ActionButton,{label:r,onClick:w=>v(w,h.text)})})]})},h.text))}),(0,Wt.jsx)(Ha,{value:s,onChange:y,autoFocus:!0,placeholder:n,onKeyUp:f})]})},vb=LM;var Xh={};je(Xh,{enUS:()=>IM,nlNL:()=>OM});var IM={insertLink:[{type:0,value:"Insert link"}],linkInputPlaceholder:[{type:0,value:"Search, type or paste link"}],visitUrl:[{type:0,value:"Visit"}]},OM={insertLink:[{type:0,value:"Voeg link toe"}],linkInputPlaceholder:[{type:0,value:"Zoek, typ of plak link"}],visitUrl:[{type:0,value:"Bekijk"}]};var rt=S(b()),MM=(0,ot.forwardRef)((e,t)=>{let n=P("TabCompletion",tr);return(0,rt.jsx)("mark",{ref:t,className:(0,of.default)(n.matchSelection)},"selection-start")}),NM=({startRef:e,boundaryRef:t,inputStyle:n,inputElement:r,children:o})=>{let i=$(Xh),s=P("TabCompletion",tr),a=(0,ot.useRef)(null),l=(0,ot.useRef)(null),[u,c]=(0,ot.useState)(null),p=Y(),d=Qd(document.activeElement===r),[g]=(0,ot.useState)(()=>document.createRange());d.triggerRef.current=g,(0,ot.useEffect)(()=>()=>g.detach(),[]),(0,ot.useEffect)(()=>{let v=e.current,f=a.current;!v||!f||(g.setStart(v,0),g.setEnd(f,0))},[e.current,a.current]),$r(()=>{d.close()});let y=(0,ot.useCallback)(v=>{let f=g.toString(),m=/^http(s?):\/\//.test(v)?v:`https://${v}`;p(Xc({text:`[${f}](${m})`,replace:"selection"}))},[]);return(0,rt.jsxs)("span",{children:[(0,rt.jsx)("mark",{ref:a,className:(0,of.default)(s.matchSelection),"aria-haspopup":"dialog","aria-expanded":d.opened?"true":"false",children:o}),d.opened&&(0,rt.jsx)(us,{className:s.popoverRoot,triggerRef:d.triggerRef,boundaryRef:t,position:"above",align:"start",children:(0,rt.jsxs)(Jd,{style:n,ref:l,children:[(0,rt.jsx)("div",{className:(0,of.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)(gb,{}),(0,rt.jsx)("span",{children:"\xA0"}),(0,rt.jsx)("span",{children:i("insertLink")})]})}),u==="insertLink"&&(0,rt.jsx)(vb,{placeholder:i("linkInputPlaceholder"),visitUrlText:i("visitUrl"),onSelectLink:y,onDismiss:()=>{c(null),d.close()}})]})})]},"selection-end")},sf=class extends $n{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)(MM,{ref:this.startRef}):(0,rt.jsx)(NM,{inputElement:n.inputElement,startRef:this.startRef,boundaryRef:n.boundaryRef,inputStyle:n.inputStyle})}asTag(){return"mark"}};var nr=S(b()),_M=({enabled:e,content:t,tabText:n,showTabHint:r,showTabCompletion:o,showStyleSuggestions:i,keywordMatches:s,inputElement:a,source:l})=>{let u=P("TabCompletion",rb),c=B("insertLink"),p=B("showMidSentenceSuggestions"),d=B("inlineSuggestions"),g=eb(a),y=(0,rr.useRef)(null),v=O(tt);(0,rr.useEffect)(()=>{Yr(a)&&g&&tb(a,g)},[g]);let f=(0,rr.useCallback)(x=>{if(!o||!n)return x;let w=[(0,nr.jsx)("span",{className:u.resetIndent,children:"\u200B"},"u200B"),(0,nr.jsx)("span",{"data-testid":"tab-completion",className:(0,af.default)(u.tabText,u.resetIndent),"data-source":l,children:n},"tabText")];return r&&w.push((0,nr.jsx)("span",{className:(0,af.default)(u.hint,u.resetIndent),children:(0,nr.jsx)(jl,{keyCode:"tab"},"tabHint")})),jh(x,w)},[o,n,r]),m=(0,rr.useMemo)(()=>{let x=[];return c&&x.push(new sf("selection")),x.push(new nf("placeholders")),i&&x.push(new ef("keywords")),x},[d,c,i]),h=(0,rr.useMemo)(()=>{let x=window.getComputedStyle(a);return{"--dd-color":x.color,"--dd-font-size":x.fontSize,"--dd-font-family":x.fontFamily,"--dd-font-variant":x.fontVariant}},[]);return!e||!v?null:(0,nr.jsxs)("div",{ref:x=>{x!=null&&x.parentElement&&(y.current=x==null?void 0:x.parentElement)},className:u.root,style:h,children:[(0,nr.jsx)(Xi,{tagName:"span",containerTagName:"div",className:(0,af.default)(u.container,u.agentText),disableLineBreaks:Yr(a),content:t||"\u200B",onAfterParse:f,matchers:m,selection:g,keywordMatches:s,inputElement:a,inputStyle:h,boundaryRef:y,inlineSuggestionsOnlyAtEnd:!p}),(0,nr.jsx)("br",{})]})},DM=({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??Qi(e.text),u=s.indexOf(e.text)===0?s.slice(e.text.length):"",{showTabHint:c}=t,{isSupported:p}=o,{showTabCompletion:d,visible:g,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:g&&p!==!1}},Sb=Bn(DM)(_M);var MT=S(te()),vl=S(N());var xb={list:[],fetchState:"idle"},Eb=e=>e.autoflows.list||[],wb=e=>t=>{var n;return(n=t.list)==null?void 0:n.find(r=>r.triggerPayload===e)},or=z("autoflows/getAll",async(e,t)=>{let{deepdeskBrokerAPI:n}=t.extra;if(!n)throw new Error("Deepdesk Broker not initialized");return n.getAutoflows(e)}),Qh=z("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(or(e.platformSessionId))}),Zh=z("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(or(e.platformSessionId))}),FM=G({name:"autoflows",initialState:xb,reducers:{},extraReducers:e=>{e.addCase(Qh.pending,(t,n)=>{let r=wb(n.meta.arg.triggerPayload)(t);r.state="Started",r.isBusy=!0}),e.addCase(Zh.pending,(t,n)=>{let r=wb(n.meta.arg.triggerPayload)(t);r.state="Aborted",r.isBusy=!0}),e.addCase(or.pending,t=>{t.fetchState="loading"}),e.addCase(or.rejected,t=>{t.fetchState="error"}),e.addCase(or.fulfilled,(t,n)=>{t.list=n.payload,t.fetchState="done"}),e.addCase(le,()=>xb)}}),Cb=z("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(or(e))}),o.on("sessionCompleted",()=>{n(or(e))})}),bb=z("autoflows/closeStream",(e,t)=>{let{deepdeskBrokerAPI:n}=t.extra;if(!n)throw new Error("Deepdesk Broker not initialized");n.closeStream(e)}),Tb=FM.reducer;var kb={list:[],fetchState:"idle",sentSuggestions:[],errorSuggestions:[],answeredSuggestions:[]},Pb=e=>e.customMessages.list,Rb=e=>t=>!!t.customMessages.sentSuggestions.find(n=>n===e),Ab=e=>t=>!!t.customMessages.answeredSuggestions.find(n=>n===e),Lb=e=>t=>!!t.customMessages.errorSuggestions.find(n=>n===e),sl=z("customMessages/getAll",async(e,t)=>{let{deepdeskBrokerAPI:n}=t.extra;if(!n)throw new Error("Deepdesk Broker not initialized");return n.getCustomMessages(e)}),lf=z("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)}),uf=z("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)}),Ib=G({name:"customMessages",initialState:kb,reducers:{onCustomMessage(e,t){Array.isArray(t.payload)?e.list=t.payload:e.list=[t.payload]}},extraReducers:e=>{e.addCase(sl.pending,t=>{t.fetchState="loading"}).addCase(sl.rejected,t=>{t.fetchState="error"}).addCase(sl.fulfilled,(t,n)=>{t.fetchState="done",t.list=n.payload||[]}).addCase(lf.pending,(t,n)=>{t.sentSuggestions.push(n.meta.arg.suggestion.text),t.errorSuggestions=t.errorSuggestions.filter(r=>n.meta.arg.suggestion.text!==r)}).addCase(lf.rejected,(t,n)=>{let r=t.sentSuggestions.indexOf(n.meta.arg.suggestion.text);t.errorSuggestions.push(...t.sentSuggestions.splice(r,1))}).addCase(uf.pending,(t,n)=>{t.sentSuggestions.push(n.meta.arg.suggestion.text),t.answeredSuggestions.push(n.meta.arg.suggestion.text)}).addCase(uf.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(le,()=>kb)}}),Ob=z("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(Ib.actions.onCustomMessage(i))})}),Mb=z("customMessages/closeStream",(e,t)=>{let{deepdeskBrokerAPI:n}=t.extra;if(!n)throw new Error("Deepdesk Broker not initialized");n.closeStream(e)}),Nb=Ib.reducer;var _b=e=>t=>{let{passwordlessToken:{token:n},settings:{isEmbedded:r,adminUrl:o}}=t;return o?r?n?`${o}/apis/admin/session/passwordless/login/?token=${n}&redirect=${e}`:null:`${o}${e}`:null};var HM={token:null,interval:null},Jh=z("passwordlessToken/getTemporaryPasswordlessToken",async(e,t)=>{let{deepdeskAPI:n}=t.extra;return{token:await n.requestPasswordlessToken()}}),ey=z("passwordlessToken/pollPasswordlessToken",(e={},t)=>{let{interval:n=1e3*60*10}=e,{dispatch:r}=t;return r(Jh()),setInterval(()=>r(Jh()),n)}),Db=G({name:"passwordlessToken",initialState:HM,reducers:{stopPollPasswordlessToken(e){e.interval&&clearInterval(e.interval),e.interval=null}},extraReducers:e=>{e.addCase(Jh.fulfilled,(t,n)=>{t.token=n.payload.token}),e.addCase(ey.fulfilled,(t,n)=>{t.interval=n.payload})}}),{stopPollPasswordlessToken:Fb}=Db.actions,Hb=Db.reducer;var ty={cues:[],fetchState:"idle"},Ub=e=>{var t;return(t=e.rules)==null?void 0:t.cues},UM=xe("rules/resetCues"),Ko=z("rules/evaluate",async(e,t)=>{var n,r;try{let{deepdeskAPI:o}=t.extra,i=t.getState(),s=(n=i.conversation.current)==null?void 0:n.id;if(!s)throw new Error("No current conversation to evaluate rules");if(!(await o.getAccount()).ruleEngine)throw new Error("Rule engine is not enabled for this account");if(!(await o.getRules()).some(c=>c.label===e.label))throw new Error(`No rules found with label: ${e.label}`);return await o.evaluateRule(e.label,s,{tags:((r=i.conversation.current)==null?void 0:r.tags)||void 0,...e.params})}catch(o){return H.info(o.message),[]}}),zb=G({name:"answer",initialState:ty,reducers:{removeCue(e,t){e.cues=e.cues.filter(n=>n.rule.id!==t.payload.id)}},extraReducers:e=>{e.addCase(Ko.pending,t=>{t.fetchState="loading"}).addCase(Ko.rejected,t=>{t.fetchState="error"}).addCase(Ko.fulfilled,(t,n)=>{let r=n.payload.map(i=>i.rule.id),o=t.cues.filter(i=>!r.includes(i.rule.id));t.fetchState="done",t.cues=[...n.payload,...o]}).addCase(le,()=>ty).addCase(UM.toString(),()=>ty)}}),{removeCue:Bb}=zb.actions,jb=zb.reducer;var Qb=S(N());var Gb=S(te()),Yb=S(N());var Kb=S(te());var Vb={root:"dd-uszkm"};var $b=S(b()),zM=({className:e,children:t})=>{let n=P("Unicode",Vb);return(0,$b.jsx)("span",{className:(0,Kb.default)(e,n.root),children:t})},Wb=zM;var qb={isDisabled:"dd-Sp--t",root:"dd-maqTG",buttonStop:"dd-rcq8w",stateBadge:"dd-zOnkT",isCompleted:"dd-GA-rt",isStarted:"dd-PZwtX",isAborted:"dd-PAXSE"};var ny={};je(ny,{enUS:()=>BM,nlNL:()=>jM});var BM={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"}]},jM={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 bt=S(b()),KM=({disabled:e,state:t,displayName:n,description:r,onStartAutoflow:o,onStopAutoflow:i})=>{let s=P("Autoflow",qb),a=$(ny),l=t==="Started"?"stop":"start",u=l==="start"?"\u25B6":l==="stop"?"\u25FC":"";return(0,bt.jsxs)(ne,{className:(0,Gb.default)(s.root,{[s.isDisabled]:e,[s.isCompleted]:t==="Completed",[s.isAborted]:t==="Aborted",[s.isStarted]:t==="Started"}),children:[(0,bt.jsx)(fe,{children:(0,bt.jsxs)(fe.Content,{children:[(0,bt.jsxs)(fe.Title,{children:[t&&(0,bt.jsx)("span",{className:s.stateBadge,children:a(t)}),n]}),(0,bt.jsx)("span",{children:r})]})}),(0,bt.jsx)(ne.Actions,{fixed:t==="Started",children:(0,bt.jsx)(ne.ActionButton,{primary:!0,className:l==="start"?s.buttonStart:s.buttonStop,onClick:t==="Started"?i:o,disabled:e,label:(0,bt.jsxs)(Yb.Fragment,{children:[(0,bt.jsx)(Wb,{children:u})," ",(0,bt.jsx)("span",{children:a(l)})]})})})]})},Xb=KM;var ry=S(b()),WM=(e,t)=>{let n=t.filter(r=>r.state==="Started");return n.length>0?n.indexOf(e)===-1:!1},$M=({autoflows:e,onStartAutoflow:t,onStopAutoflow:n,platformSessionId:r})=>(0,ry.jsx)(Qb.Fragment,{children:e.map(o=>(0,ry.jsx)(Xb,{displayName:o.displayName,description:o.description,disabled:o.isBusy||WM(o,e),state:o.state,onStartAutoflow:()=>t({platformSessionId:r,triggerPayload:o.triggerPayload}),onStopAutoflow:()=>n({platformSessionId:r,triggerPayload:o.triggerPayload})},o.displayName))}),qM=({autoflows:e,conversation:t})=>{var n;return{autoflows:e.list,platformSessionId:(n=t.current)==null?void 0:n.sessionId}},GM={onStartAutoflow:Qh,onStopAutoflow:Zh},Zb=Bn(qM,GM)($M);var Jb=S(te()),oy=S(N());var ir={root:"dd-ERsBr",title:"dd-b36p6",isUsed:"dd-fp2IX",quickReplies:"dd--VrvP",quickReply:"dd-wFhWh",label:"dd-R9sND",errorIcon:"dd-8cdcH"};var ht=S(b()),YM=({suggestion:e})=>{let t=$(Do),n=Y(),r=O(Rb(e.text)),o=O(Ab(e.text)),i=O(Lb(e.text)),s=O($i),{replyOptions:a}=e,l=(0,oy.useCallback)(c=>{c.preventDefault(),c.stopPropagation(),!(r||!s)&&n(lf({platformSessionId:s,suggestion:e}))},[e,r,n,s]),u=(0,oy.useCallback)(c=>{if(c.preventDefault(),c.stopPropagation(),!s||!a)return;let p=parseInt(c.target.dataset.index,10),d=a[p];n(uf({platformSessionId:s,reply:d,suggestion:e}))},[e,r,n,s]);return(0,ht.jsxs)(ne,{onClick:l,className:(0,Jb.default)(ir.root,{[ir.isUsed]:r,[ir.hasError]:i}),children:[(0,ht.jsx)(fe,{children:(0,ht.jsxs)(fe.Content,{children:[(0,ht.jsxs)(fe.Title,{className:ir.title,children:[e.text," ",(0,ht.jsx)(Vl,{className:ir.label,children:"analyse tool"})," ",i&&(0,ht.jsx)("span",{className:ir.errorIcon,role:"img","aria-label":t("sendingError"),title:t("sendingError"),children:"!"})]}),a&&a.length>0&&(0,ht.jsx)("ul",{className:ir.quickReplies,children:a.map(c=>(0,ht.jsx)("li",{className:ir.quickReply,children:c.title},c.title))})]})}),(0,ht.jsxs)(ne.Actions,{fixed:i||r,children:[a&&a.length>0&&(0,ht.jsx)(ne.DropdownButton,{label:t("answer"),disabled:o,children:a.map((c,p)=>(0,ht.jsx)(ne.DropdownItem,{index:p,label:c.title,onClick:u},c.title))}),(0,ht.jsx)(ne.ActionButton,{primary:!0,disabled:r,onClick:l,label:t(r?"suggestionSent":i?"tryAgain":"sendSuggestion")})]})]})},eT=YM;var cf=S(N());var sy=S(te());var iy=S(b()),al=()=>(0,iy.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 512 512",xmlns:"http://www.w3.org/2000/svg",children:(0,iy.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 tT={root:"dd-WcEru",entity:"dd-LfP8y",entityText:"dd-L-v0f",iconWrapper:"dd-9Deh1",icon:"dd-tM7E2",iconClicked:"dd-EEdDL"};var kn=S(b()),XM=({entities:e})=>{let t=P("EntitiesWidgetList",tT),[n,r]=(0,cf.useState)(void 0),o=Y(),i=()=>{r(void 0)},s=a=>{e&&(r(e.indexOf(a)),Wn(a.text),o(Xe({name:"entity copied",data:{entity:a,type:"copy"}})))};return(0,cf.useEffect)(()=>{let a=setTimeout(i,500);return()=>{clearTimeout(a)}},[n]),!e||e.length===0?null:(0,kn.jsx)("div",{className:t.root,"data-testid":"widget-entities-list",children:e.map((a,l)=>(0,kn.jsxs)("button",{title:a.text,className:t.entity,type:"button",onClick:()=>s(a),children:[(0,kn.jsx)("span",{className:t.entityText,children:a.text}),(0,kn.jsxs)("span",{className:t.iconWrapper,children:[(0,kn.jsx)("span",{className:(0,sy.default)(t.icon),children:(0,kn.jsx)(al,{})}),(0,kn.jsx)("span",{className:(0,sy.default)(t.icon,n===l&&t.iconClicked),children:(0,kn.jsx)(al,{})})]})]},a.text))})},nT=XM;var ay=S(b()),rT=()=>(0,ay.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:(0,ay.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 ly=S(b()),oT=()=>(0,ly.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:(0,ly.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 uy=S(b()),iT=()=>(0,uy.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:(0,uy.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 Sy=S(te()),gf=S(N());var ll=S(b()),sT=({className:e})=>(0,ll.jsxs)("svg",{viewBox:"0 0 12 12",version:"1.1",xmlns:"http://www.w3.org/2000/svg",className:e,children:[(0,ll.jsx)("line",{x1:"2",y1:"10",x2:"10",y2:"2",stroke:"black",strokeWidth:"1"}),(0,ll.jsx)("line",{x1:"2",y1:"2",x2:"10",y2:"10",stroke:"black",strokeWidth:"1"})]});var{entries:mT,setPrototypeOf:aT,isFrozen:QM,getPrototypeOf:ZM,getOwnPropertyDescriptor:JM}=Object,{freeze:it,seal:cn,create:gT}=Object,{apply:gy,construct:hy}=typeof Reflect<"u"&&Reflect;it||(it=function(t){return t});cn||(cn=function(t){return t});gy||(gy=function(t,n,r){return t.apply(n,r)});hy||(hy=function(t,n){return new t(...n)});var df=kt(Array.prototype.forEach),lT=kt(Array.prototype.pop),ul=kt(Array.prototype.push),mf=kt(String.prototype.toLowerCase),cy=kt(String.prototype.toString),eN=kt(String.prototype.match),cl=kt(String.prototype.replace),tN=kt(String.prototype.indexOf),nN=kt(String.prototype.trim),un=kt(Object.prototype.hasOwnProperty),Tt=kt(RegExp.prototype.test),dl=rN(TypeError);function kt(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 gy(e,t,r)}}function rN(e){return function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];return hy(e,n)}}function Q(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:mf;aT&&aT(e,null);let r=t.length;for(;r--;){let o=t[r];if(typeof o=="string"){let i=n(o);i!==o&&(QM(t)||(t[r]=i),o=i)}e[o]=!0}return e}function oN(e){for(let t=0;t<e.length;t++)un(e,t)||(e[t]=null);return e}function Wo(e){let t=gT(null);for(let[n,r]of mT(e))un(e,n)&&(Array.isArray(r)?t[n]=oN(r):r&&typeof r=="object"&&r.constructor===Object?t[n]=Wo(r):t[n]=r);return t}function ff(e,t){for(;e!==null;){let r=JM(e,t);if(r){if(r.get)return kt(r.get);if(typeof r.value=="function")return kt(r.value)}e=ZM(e)}function n(){return null}return n}var uT=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"]),dy=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"]),fy=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"]),iN=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"]),py=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"]),sN=it(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),cT=it(["#text"]),dT=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"]),my=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"]),fT=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"]),pf=it(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),aN=cn(/\{\{[\w\W]*|[\w\W]*\}\}/gm),lN=cn(/<%[\w\W]*|[\w\W]*%>/gm),uN=cn(/\${[\w\W]*}/gm),cN=cn(/^data-[\-\w.\u00B7-\uFFFF]/),dN=cn(/^aria-[\-\w]+$/),hT=cn(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),fN=cn(/^(?:\w+script|data):/i),pN=cn(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),yT=cn(/^html$/i),pT=Object.freeze({__proto__:null,MUSTACHE_EXPR:aN,ERB_EXPR:lN,TMPLIT_EXPR:uN,DATA_ATTR:cN,ARIA_ATTR:dN,IS_ALLOWED_URI:hT,IS_SCRIPT_OR_DATA:fN,ATTR_WHITESPACE:pN,DOCTYPE_NAME:yT}),mN=function(){return typeof window>"u"?null:window},gN=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 vT(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:mN(),t=U=>vT(U);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:p,DOMParser:d,trustedTypes:g}=e,y=l.prototype,v=ff(y,"cloneNode"),f=ff(y,"nextSibling"),m=ff(y,"childNodes"),h=ff(y,"parentNode");if(typeof s=="function"){let U=n.createElement("template");U.content&&U.content.ownerDocument&&(n=U.content.ownerDocument)}let x,w="",{implementation:T,createNodeIterator:C,createDocumentFragment:k,getElementsByTagName:I}=n,{importNode:L}=r,_={};t.isSupported=typeof mT=="function"&&typeof h=="function"&&T&&T.createHTMLDocument!==void 0;let{MUSTACHE_EXPR:W,ERB_EXPR:V,TMPLIT_EXPR:Z,DATA_ATTR:ur,ARIA_ATTR:Rt,IS_SCRIPT_OR_DATA:cr,ATTR_WHITESPACE:At}=pT,{IS_ALLOWED_URI:F}=pT,X=null,dr=Q({},[...uT,...dy,...fy,...py,...cT]),he=null,fr=Q({},[...dT,...my,...fT,...pf]),q=Object.seal(gT(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}})),pr=null,kl=null,Yo=!0,eo=!0,ms=!1,Pl=!0,Gt=!1,Yt=!1,Rl=!1,st=!1,Lt=!1,Al=!1,Ll=!1,Oy=!0,My=!1,Ck="user-content-",Pf=!0,gs=!1,Xo={},Qo=null,Ny=Q({},["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"]),_y=null,Dy=Q({},["audio","video","img","source","image","track"]),Rf=null,Fy=Q({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Il="http://www.w3.org/1998/Math/MathML",Ol="http://www.w3.org/2000/svg",An="http://www.w3.org/1999/xhtml",Zo=An,Af=!1,Lf=null,bk=Q({},[Il,Ol,An],cy),hs=null,Tk=["application/xhtml+xml","text/html"],kk="text/html",Ie=null,Jo=null,Pk=n.createElement("form"),Hy=function(E){return E instanceof RegExp||E instanceof Function},If=function(){let E=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(Jo&&Jo===E)){if((!E||typeof E!="object")&&(E={}),E=Wo(E),hs=Tk.indexOf(E.PARSER_MEDIA_TYPE)===-1?kk:E.PARSER_MEDIA_TYPE,Ie=hs==="application/xhtml+xml"?cy:mf,X=un(E,"ALLOWED_TAGS")?Q({},E.ALLOWED_TAGS,Ie):dr,he=un(E,"ALLOWED_ATTR")?Q({},E.ALLOWED_ATTR,Ie):fr,Lf=un(E,"ALLOWED_NAMESPACES")?Q({},E.ALLOWED_NAMESPACES,cy):bk,Rf=un(E,"ADD_URI_SAFE_ATTR")?Q(Wo(Fy),E.ADD_URI_SAFE_ATTR,Ie):Fy,_y=un(E,"ADD_DATA_URI_TAGS")?Q(Wo(Dy),E.ADD_DATA_URI_TAGS,Ie):Dy,Qo=un(E,"FORBID_CONTENTS")?Q({},E.FORBID_CONTENTS,Ie):Ny,pr=un(E,"FORBID_TAGS")?Q({},E.FORBID_TAGS,Ie):{},kl=un(E,"FORBID_ATTR")?Q({},E.FORBID_ATTR,Ie):{},Xo=un(E,"USE_PROFILES")?E.USE_PROFILES:!1,Yo=E.ALLOW_ARIA_ATTR!==!1,eo=E.ALLOW_DATA_ATTR!==!1,ms=E.ALLOW_UNKNOWN_PROTOCOLS||!1,Pl=E.ALLOW_SELF_CLOSE_IN_ATTR!==!1,Gt=E.SAFE_FOR_TEMPLATES||!1,Yt=E.WHOLE_DOCUMENT||!1,Lt=E.RETURN_DOM||!1,Al=E.RETURN_DOM_FRAGMENT||!1,Ll=E.RETURN_TRUSTED_TYPE||!1,st=E.FORCE_BODY||!1,Oy=E.SANITIZE_DOM!==!1,My=E.SANITIZE_NAMED_PROPS||!1,Pf=E.KEEP_CONTENT!==!1,gs=E.IN_PLACE||!1,F=E.ALLOWED_URI_REGEXP||hT,Zo=E.NAMESPACE||An,q=E.CUSTOM_ELEMENT_HANDLING||{},E.CUSTOM_ELEMENT_HANDLING&&Hy(E.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(q.tagNameCheck=E.CUSTOM_ELEMENT_HANDLING.tagNameCheck),E.CUSTOM_ELEMENT_HANDLING&&Hy(E.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(q.attributeNameCheck=E.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),E.CUSTOM_ELEMENT_HANDLING&&typeof E.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(q.allowCustomizedBuiltInElements=E.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),Gt&&(eo=!1),Al&&(Lt=!0),Xo&&(X=Q({},cT),he=[],Xo.html===!0&&(Q(X,uT),Q(he,dT)),Xo.svg===!0&&(Q(X,dy),Q(he,my),Q(he,pf)),Xo.svgFilters===!0&&(Q(X,fy),Q(he,my),Q(he,pf)),Xo.mathMl===!0&&(Q(X,py),Q(he,fT),Q(he,pf))),E.ADD_TAGS&&(X===dr&&(X=Wo(X)),Q(X,E.ADD_TAGS,Ie)),E.ADD_ATTR&&(he===fr&&(he=Wo(he)),Q(he,E.ADD_ATTR,Ie)),E.ADD_URI_SAFE_ATTR&&Q(Rf,E.ADD_URI_SAFE_ATTR,Ie),E.FORBID_CONTENTS&&(Qo===Ny&&(Qo=Wo(Qo)),Q(Qo,E.FORBID_CONTENTS,Ie)),Pf&&(X["#text"]=!0),Yt&&Q(X,["html","head","body"]),X.table&&(Q(X,["tbody"]),delete pr.tbody),E.TRUSTED_TYPES_POLICY){if(typeof E.TRUSTED_TYPES_POLICY.createHTML!="function")throw dl('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof E.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw dl('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');x=E.TRUSTED_TYPES_POLICY,w=x.createHTML("")}else x===void 0&&(x=gN(g,o)),x!==null&&typeof w=="string"&&(w=x.createHTML(""));it&&it(E),Jo=E}},Uy=Q({},["mi","mo","mn","ms","mtext"]),zy=Q({},["foreignobject","desc","title","annotation-xml"]),Rk=Q({},["title","style","font","a","script"]),By=Q({},[...dy,...fy,...iN]),jy=Q({},[...py,...sN]),Ak=function(E){let A=h(E);(!A||!A.tagName)&&(A={namespaceURI:Zo,tagName:"template"});let D=mf(E.tagName),ce=mf(A.tagName);return Lf[E.namespaceURI]?E.namespaceURI===Ol?A.namespaceURI===An?D==="svg":A.namespaceURI===Il?D==="svg"&&(ce==="annotation-xml"||Uy[ce]):!!By[D]:E.namespaceURI===Il?A.namespaceURI===An?D==="math":A.namespaceURI===Ol?D==="math"&&zy[ce]:!!jy[D]:E.namespaceURI===An?A.namespaceURI===Ol&&!zy[ce]||A.namespaceURI===Il&&!Uy[ce]?!1:!jy[D]&&(Rk[D]||!By[D]):!!(hs==="application/xhtml+xml"&&Lf[E.namespaceURI]):!1},to=function(E){ul(t.removed,{element:E});try{E.parentNode.removeChild(E)}catch{E.remove()}},Of=function(E,A){try{ul(t.removed,{attribute:A.getAttributeNode(E),from:A})}catch{ul(t.removed,{attribute:null,from:A})}if(A.removeAttribute(E),E==="is"&&!he[E])if(Lt||Al)try{to(A)}catch{}else try{A.setAttribute(E,"")}catch{}},Vy=function(E){let A=null,D=null;if(st)E="<remove></remove>"+E;else{let Be=eN(E,/^[\r\n\t ]+/);D=Be&&Be[0]}hs==="application/xhtml+xml"&&Zo===An&&(E='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+E+"</body></html>");let ce=x?x.createHTML(E):E;if(Zo===An)try{A=new d().parseFromString(ce,hs)}catch{}if(!A||!A.documentElement){A=T.createDocument(Zo,"template",null);try{A.documentElement.innerHTML=Af?w:ce}catch{}}let ze=A.body||A.documentElement;return E&&D&&ze.insertBefore(n.createTextNode(D),ze.childNodes[0]||null),Zo===An?I.call(A,Yt?"html":"body")[0]:Yt?A.documentElement:ze},Ky=function(E){return C.call(E.ownerDocument||E,E,u.SHOW_ELEMENT|u.SHOW_COMMENT|u.SHOW_TEXT,null)},Lk=function(E){return E instanceof p&&(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")},Wy=function(E){return typeof a=="function"&&E instanceof a},Ln=function(E,A,D){_[E]&&df(_[E],ce=>{ce.call(t,A,D,Jo)})},$y=function(E){let A=null;if(Ln("beforeSanitizeElements",E,null),Lk(E))return to(E),!0;let D=Ie(E.nodeName);if(Ln("uponSanitizeElement",E,{tagName:D,allowedTags:X}),E.hasChildNodes()&&!Wy(E.firstElementChild)&&Tt(/<[/\w]/g,E.innerHTML)&&Tt(/<[/\w]/g,E.textContent))return to(E),!0;if(!X[D]||pr[D]){if(!pr[D]&&Gy(D)&&(q.tagNameCheck instanceof RegExp&&Tt(q.tagNameCheck,D)||q.tagNameCheck instanceof Function&&q.tagNameCheck(D)))return!1;if(Pf&&!Qo[D]){let ce=h(E)||E.parentNode,ze=m(E)||E.childNodes;if(ze&&ce){let Be=ze.length;for(let at=Be-1;at>=0;--at)ce.insertBefore(v(ze[at],!0),f(E))}}return to(E),!0}return E instanceof l&&!Ak(E)||(D==="noscript"||D==="noembed"||D==="noframes")&&Tt(/<\/no(script|embed|frames)/i,E.innerHTML)?(to(E),!0):(Gt&&E.nodeType===3&&(A=E.textContent,df([W,V,Z],ce=>{A=cl(A,ce," ")}),E.textContent!==A&&(ul(t.removed,{element:E.cloneNode()}),E.textContent=A)),Ln("afterSanitizeElements",E,null),!1)},qy=function(E,A,D){if(Oy&&(A==="id"||A==="name")&&(D in n||D in Pk))return!1;if(!(eo&&!kl[A]&&Tt(ur,A))){if(!(Yo&&Tt(Rt,A))){if(!he[A]||kl[A]){if(!(Gy(E)&&(q.tagNameCheck instanceof RegExp&&Tt(q.tagNameCheck,E)||q.tagNameCheck instanceof Function&&q.tagNameCheck(E))&&(q.attributeNameCheck instanceof RegExp&&Tt(q.attributeNameCheck,A)||q.attributeNameCheck instanceof Function&&q.attributeNameCheck(A))||A==="is"&&q.allowCustomizedBuiltInElements&&(q.tagNameCheck instanceof RegExp&&Tt(q.tagNameCheck,D)||q.tagNameCheck instanceof Function&&q.tagNameCheck(D))))return!1}else if(!Rf[A]){if(!Tt(F,cl(D,At,""))){if(!((A==="src"||A==="xlink:href"||A==="href")&&E!=="script"&&tN(D,"data:")===0&&_y[E])){if(!(ms&&!Tt(cr,cl(D,At,"")))){if(D)return!1}}}}}}return!0},Gy=function(E){return E!=="annotation-xml"&&E.indexOf("-")>0},Yy=function(E){Ln("beforeSanitizeAttributes",E,null);let{attributes:A}=E;if(!A)return;let D={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:he},ce=A.length;for(;ce--;){let ze=A[ce],{name:Be,namespaceURI:at,value:no}=ze,ys=Ie(Be),lt=Be==="value"?no:nN(no);if(D.attrName=ys,D.attrValue=lt,D.keepAttr=!0,D.forceKeepAttr=void 0,Ln("uponSanitizeAttribute",E,D),lt=D.attrValue,D.forceKeepAttr||(Of(Be,E),!D.keepAttr))continue;if(!Pl&&Tt(/\/>/i,lt)){Of(Be,E);continue}Gt&&df([W,V,Z],Qy=>{lt=cl(lt,Qy," ")});let Xy=Ie(E.nodeName);if(qy(Xy,ys,lt)){if(My&&(ys==="id"||ys==="name")&&(Of(Be,E),lt=Ck+lt),x&&typeof g=="object"&&typeof g.getAttributeType=="function"&&!at)switch(g.getAttributeType(Xy,ys)){case"TrustedHTML":{lt=x.createHTML(lt);break}case"TrustedScriptURL":{lt=x.createScriptURL(lt);break}}try{at?E.setAttributeNS(at,Be,lt):E.setAttribute(Be,lt),lT(t.removed)}catch{}}}Ln("afterSanitizeAttributes",E,null)},Ik=function U(E){let A=null,D=Ky(E);for(Ln("beforeSanitizeShadowDOM",E,null);A=D.nextNode();)Ln("uponSanitizeShadowNode",A,null),!$y(A)&&(A.content instanceof i&&U(A.content),Yy(A));Ln("afterSanitizeShadowDOM",E,null)};return t.sanitize=function(U){let E=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},A=null,D=null,ce=null,ze=null;if(Af=!U,Af&&(U="<!-->"),typeof U!="string"&&!Wy(U))if(typeof U.toString=="function"){if(U=U.toString(),typeof U!="string")throw dl("dirty is not a string, aborting")}else throw dl("toString is not a function");if(!t.isSupported)return U;if(Rl||If(E),t.removed=[],typeof U=="string"&&(gs=!1),gs){if(U.nodeName){let no=Ie(U.nodeName);if(!X[no]||pr[no])throw dl("root node is forbidden and cannot be sanitized in-place")}}else if(U instanceof a)A=Vy("<!---->"),D=A.ownerDocument.importNode(U,!0),D.nodeType===1&&D.nodeName==="BODY"||D.nodeName==="HTML"?A=D:A.appendChild(D);else{if(!Lt&&!Gt&&!Yt&&U.indexOf("<")===-1)return x&&Ll?x.createHTML(U):U;if(A=Vy(U),!A)return Lt?null:Ll?w:""}A&&st&&to(A.firstChild);let Be=Ky(gs?U:A);for(;ce=Be.nextNode();)$y(ce)||(ce.content instanceof i&&Ik(ce.content),Yy(ce));if(gs)return U;if(Lt){if(Al)for(ze=k.call(A.ownerDocument);A.firstChild;)ze.appendChild(A.firstChild);else ze=A;return(he.shadowroot||he.shadowrootmode)&&(ze=L.call(r,ze,!0)),ze}let at=Yt?A.outerHTML:A.innerHTML;return Yt&&X["!doctype"]&&A.ownerDocument&&A.ownerDocument.doctype&&A.ownerDocument.doctype.name&&Tt(yT,A.ownerDocument.doctype.name)&&(at="<!DOCTYPE "+A.ownerDocument.doctype.name+`>
24
24
  `+at),Gt&&df([W,V,Z],no=>{at=cl(at,no," ")}),x&&Ll?x.createHTML(at):at},t.setConfig=function(){let U=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};If(U),Rl=!0},t.clearConfig=function(){Jo=null,Rl=!1},t.isValidAttribute=function(U,E,A){Jo||If({});let D=Ie(U),ce=Ie(E);return qy(D,ce,A)},t.addHook=function(U,E){typeof E=="function"&&(_[U]=_[U]||[],ul(_[U],E))},t.removeHook=function(U){if(_[U])return lT(_[U])},t.removeHooks=function(U){_[U]&&(_[U]=[])},t.removeAllHooks=function(){_={}},t}var ST=vT();var Zr=S(N());var hN={"":["<em>","</em>"],_:["<strong>","</strong>"],"*":["<strong>","</strong>"],"~":["<s>","</s>"],"\n":["<br />"]," ":["<br />"],"-":["<hr />"]};function xT(e){return e.replace(RegExp("^"+(e.match(/^(\t| )+/)||"")[0],"gm"),"")}function fl(e){return(e+"").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function pl(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||{},p=0;function d(y){var v=hN[y[1]||""],f=l[l.length-1]==y;return v?v[1]?(f?l.pop():l.push(y),v[0|f]):v[0]:y}function g(){for(var y="";l.length;)y+=d(l[l.length-1]);return y}for(e=e.replace(/^\[(.+?)\]:\s*(.+)$/gm,function(y,v,f){return c[v.toLowerCase()]=f,""}).replace(/^\n+|\n+$/g,"");o=a.exec(e);)r=e.substring(p,o.index),p=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()+'"':"")+">"+xT(fl(s).replace(/^\n+|\n+$/g,""))+"</code></pre>":(s=o[6])?(s.match(/\./)&&(o[5]=o[5].replace(/^\d+/gm,"")),i=pl(xT(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="'+fl(o[8])+'" alt="'+fl(o[7])+'">':o[10]?(u=u.replace("<a>",'<a href="'+fl(o[11]||c[r.toLowerCase()])+'">'),n=g()+"</a>"):o[9]?n="<a>":o[12]||o[14]?n="<"+(s="h"+(o[14]?o[14].length:o[13]>"="?1:2))+">"+pl(o[12]||o[15],c)+"</"+s+">":o[16]?n="<code>"+fl(o[16])+"</code>":(o[17]||o[1])&&(n=d(o[17]||"--"))),u+=r,u+=n;return(u+e.substring(p)+g()).replace(/^\n+|\n+$/g,"")}var wT={root:"dd-L7b3z",popover:"dd-OQOTB",options:"dd-Y12RE",copyIcon:"dd-6xOsH",option:"dd-9oFX4",divider:"dd-aiZf8",fadeup:"dd-Jq9pd"};var sr=S(b());function yN(e){return`<button type="button" class=${e}><svg version="1.1" x="0px" y="0px" viewBox="0 0 115.77 122.88" width="10px" height="10px" fill="black"><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></button>`}function yy(e){let t=e.cloneNode(!0);return t.querySelectorAll("div,button").forEach(n=>n.remove()),t.textContent??""}function vN(e){return e.replace(/\r\n/g,`
25
25
  `)}var SN=({content:e,useLabel:t,copyLabel:n,onCopy:r,onUse:o})=>{let i=P("Markdown",wT),s=(0,Zr.useRef)(null),[a,l]=(0,Zr.useState)(null),u=(0,Zr.useMemo)(()=>{let y=pl(vN(e));return ST.sanitize(y).replace(/<\/code>/g,`${yN(i.copyIcon)}</code>`)},[e]),c=y=>{var m;let v=y.target,f=!!((m=s.current)!=null&&m.querySelector("code"));a||f&&v.tagName!=="CODE"||!f&&v!==s.current||(v.addEventListener("mouseleave",()=>l(null),{once:!0}),l(v))},p=()=>{if(!a)return;l(null);let y=a.querySelector("button");y&&(Xn(y,i.fadeup),r(yy(a)))},d=y=>{y.target.tagName.toLowerCase()==="button"&&(Xn(y.target,i.fadeup),r(yy(y.target.parentElement)))},g=()=>{a&&(l(null),o(yy(a)))};return(0,sr.jsxs)(Zr.Fragment,{children:[a&&(0,sr.jsx)(us,{triggerRef:{current:a},parentNode:a,className:i.popover,children:(0,sr.jsxs)("div",{className:i.options,children:[(0,sr.jsx)("button",{type:"button",className:i.option,onClick:p,children:n}),(0,sr.jsx)("div",{className:i.divider}),(0,sr.jsx)("button",{type:"button",className:i.option,onClick:g,children:t})]})}),(0,sr.jsx)("div",{ref:s,className:i.root,dangerouslySetInnerHTML:{__html:u},onMouseOver:c,onClick:d})]})},ET=SN;var vy={};je(vy,{enUS:()=>xN,nlNL:()=>wN});var xN={useCue:[{type:0,value:"Use"}],copyCue:[{type:0,value:"Copy"}],removeCue:[{type:0,value:"Close"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}]},wN={useCue:[{type:0,value:"Gebruik"}],copyCue:[{type:0,value:"Kopieer"}],removeCue:[{type:0,value:"Sluiten"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}]};var CT={title:"dd-YBHrC",fadeup:"dd-cRM0K",fadedown:"dd-7D4Pq",selected:"dd-bueui",thumbsUp:"dd-6QwVx",thumbsDown:"dd-d3E8l"};var Pt=S(b()),EN=({cue:e,onRemove:t,onCopy:n,onUse:r,onThumbsUp:o,onThumbsDown:i})=>{let s=P("WidgetCue",CT),a=$(vy),l=ts(),[u,c]=(0,gf.useState)(null),p=f=>{n&&n(f,e)},d=f=>{r&&r(f,e)},g=f=>{f.preventDefault(),f.stopPropagation(),t(e)},y=f=>{f.preventDefault(),f.stopPropagation(),Xn(f.target,s.fadeup),c("up"),o(e)},v=f=>{f.preventDefault(),f.stopPropagation(),Xn(f.target,s.fadedown),c("down"),i(e)};return(0,gf.useEffect)(()=>{l("Assistant response displayed",{name:e.rule.name,description:e.rule.description,group:e.rule.label,cueText:e.text})},[]),(0,Pt.jsxs)(ne,{"data-testid":"cue",children:[(0,Pt.jsx)(fe,{children:(0,Pt.jsxs)(fe.Content,{children:[e.title&&(0,Pt.jsx)(fe.Title,{className:s.title,"data-testid":"widget-cue-title",children:e.title}),(0,Pt.jsx)(ET,{content:e.text,useLabel:a("useCue"),copyLabel:a("copyCue"),onCopy:p,onUse:d})]})}),(0,Pt.jsx)(ne.IconButton,{title:a("thumbsUp"),onClick:y,icon:(0,Pt.jsx)(Nd,{}),className:(0,Sy.default)(s.thumbsUp,u==="up"&&s.selected),disabled:!!u}),(0,Pt.jsx)(ne.IconButton,{title:a("thumbsDown"),onClick:v,icon:(0,Pt.jsx)(Md,{}),className:(0,Sy.default)(s.thumbsDown,u==="down"&&s.selected),disabled:!!u}),(0,Pt.jsx)(ne.IconButton,{title:a("removeCue"),onClick:g,icon:(0,Pt.jsx)(sT,{})})]})},bT=EN;var ml=S(b()),CN=({cues:e})=>{let t=Y(),n=jt(),r=ts(),o=u=>{t(Bb({id:u.rule.id})),r("Assistant response closed",{name:u.rule.name,group:u.rule.label,description:u.rule.description,cueText:u.text})},i=(u,c)=>{Wn(u),r("Assistant response copied",{name:c.rule.name,group:c.rule.label,description:c.rule.description,copiedText:u})},s=(u,c)=>{n.send(jr,{text:u,suggestion:{source:"cue",sourceText:u}}),r("Assistant response used",{name:c.rule.name,group:c.rule.label,description:c.rule.description,usedText:u})},a=u=>{r("Assistant response feedback",{name:u.rule.name,group:u.rule.label,description:u.rule.description,thumb:"up",cueText:u.text})},l=u=>{r("Assistant response feedback",{name:u.rule.name,group:u.rule.label,description:u.rule.description,thumb:"down",cueText:u.text})};return(0,ml.jsx)(ml.Fragment,{children:e.map(u=>(0,ml.jsx)(bT,{cue:u,onRemove:o,onCopy:i,onUse:s,onThumbsDown:l,onThumbsUp:a},u.rule.id))})},TT=CN;var hf=S(N());var kT={root:"dd-cvTAY",label:"dd-QWQxD",value:"dd-WSUHF",copyButton:"dd-67o9H",isTrue:"dd--1g2O",isFalse:"dd-sz2ir"};var dn=S(b());function bN(e,t){return t.split(".").reduce((n,r)=>!n||typeof n!="object"||!(r in n)?null:n[r],e)}var PT=({data:e,schema:t})=>{let n=P("WidgetCustomData",kT),r=o=>{Wn(o)};return(0,hf.useEffect)(()=>{H.info("Custom data",e,t)},[e]),(0,dn.jsx)("dl",{className:n.root,children:t.map(o=>{let i=bN(e,o.path);return(0,dn.jsxs)(hf.Fragment,{children:[(0,dn.jsx)("dt",{className:n.label,children:o.label}),(0,dn.jsx)("dd",{className:n.value,children:o.type==="boolean"&&i?(0,dn.jsx)("span",{className:n.isTrue,children:o.trueValue}):o.type==="boolean"&&!i?(0,dn.jsx)("span",{className:n.isFalse,children:o.falseValue}):i?(0,dn.jsxs)("button",{type:"button",onClick:()=>r(i),className:n.copyButton,children:[(0,dn.jsx)("span",{children:i}),(0,dn.jsx)(al,{})]}):"-"})]},o.label)})})};var AT=S(N());var TN=/(https?:\/\/[^\s]+)/,RT=e=>e.split(" ").find(t=>TN.test(t));var $t=S(b()),kN=({suggestion:e,lines:t,onUse:n})=>{var c;let r=e.text||e.url||e.message,o=RT(r),i=$(Do),s=B("showImages"),a=B("fallbackImage"),l=p=>{p.preventDefault(),p.stopPropagation(),n(r)},u=(0,AT.useCallback)(p=>{window.open(o,"_blank"),p.stopPropagation(),p.preventDefault()},[o]);return(0,$t.jsxs)(ne,{onClick:l,"data-testid":"edit-suggestion",children:[(0,$t.jsxs)(fe,{children:[s&&e.image&&(0,$t.jsx)(fe.Image,{src:rf(e,"small",a||void 0),title:e.title}),(0,$t.jsxs)(fe.Content,{children:[e.title&&(0,$t.jsx)(fe.Title,{"data-testid":"widget-suggestion-title",children:e.title}),e.searchKeywords&&((c=e.searchKeywords)==null?void 0:c.length)>0&&(0,$t.jsx)(ne.Labels,{labels:e.searchKeywords}),(0,$t.jsx)(fe.Content,{cropText:t==="single",lineClamp:t==="multiple",children:r})]})]}),(0,$t.jsxs)(ne.Actions,{children:[o&&(0,$t.jsx)(ne.ActionButton,{onClick:u,label:i("visitUrl")}),(0,$t.jsx)(ne.ActionButton,{primary:!0,onClick:l,label:i("useSuggestion")})]})]})},LT=kN;var gl=S(b()),PN=({lines:e,suggestions:t})=>{let n=jt(),r=(o,i)=>{n.send(jr,{text:o,suggestion:{...i,source:i.source,sourceText:i.text}})};return(0,gl.jsx)(gl.Fragment,{children:t.map(o=>(0,gl.jsx)(LT,{suggestion:o,lines:e,onUse:i=>r(i,o)},o.text||o.url||o.message))})},IT=PN;var hl={};je(hl,{enUS:()=>RN,nlNL:()=>AN});var RN={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"}]},AN={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 yl={root:"dd-W9VCG",loginText:"dd--dS6t",stateText:"dd-348OC",sectionList:"dd-bF9pF",shortcutList:"dd-MuKK-",shortcut:"dd-5CnK9",link:"dd-DRo0x"};var K=S(b()),yf=(e,t)=>{let n=O(tt);(0,vl.useEffect)(()=>n?t.every(r=>!!r)?e():()=>{}:()=>{},[...t,n])},LN=({onLogIn:e})=>{let t=P("Widget",yl),n=B("isEmbedded"),r=B("adminUrl");return(0,K.jsx)("div",{className:t.loginText,children:(0,K.jsx)("div",{children:(0,K.jsx)(Kd,{isEmbedded:n,loginUrl:r,onLogIn:e})})},"login")},OT=({text:e})=>{let t=P("Widget",yl);return(0,K.jsx)("div",{className:t.stateText,children:(0,K.jsx)("div",{children:(0,K.jsx)("p",{children:e})})},"notification")},IN=()=>{let e=$(hl),t=Y(),n=P("Widget",yl),r=B("showSearch"),o=B("showSummaryCommand"),i=B("showKnowledgeSearch"),s=O(_b("/admin/")),a=jt(),l=B("productName"),u=r||o||i||s;return yf(()=>(t(ey()),()=>{t(Fb())}),[t]),u?(0,K.jsx)(pn,{title:e("actions"),type:"shortcuts",children:(0,K.jsxs)("div",{className:n.shortcutList,children:[r&&(0,K.jsxs)("button",{type:"button",className:n.shortcut,"data-testid":"shortcut-search","aria-label":e("linkSearch"),onClick:()=>a.send("ShowCommandPalette",{isOpen:!0}),children:[(0,K.jsx)(Zi,{}),e("linkSearch")]}),o&&(0,K.jsxs)("button",{type:"button",className:n.shortcut,"data-testid":"shortcut-summary","aria-label":e("linkSummary"),onClick:()=>a.send("ShowCommandPalette",{isOpen:!0,page:"summary"}),children:[(0,K.jsx)(iT,{}),e("linkSummary")]}),i&&(0,K.jsxs)("button",{type:"button",className:n.shortcut,"data-testid":"shortcut-knowledge-assist","aria-label":e("linkKnowledgeSearch"),onClick:()=>a.send("ShowCommandPalette",{isOpen:!0,page:"knowledgeAssist"}),children:[(0,K.jsx)(oT,{}),e("linkKnowledgeSearch")]}),s&&(0,K.jsxs)("a",{className:n.shortcut,target:"_blank",href:s,"data-testid":"shortcut-studio-login","aria-label":e("linkStudioLogin",{productName:l}),rel:"noreferrer",children:[(0,K.jsx)(rT,{}),e("linkStudioLogin",{productName:l})]})]})}):null},ON=()=>{let e=Y(),t=B("showCustomMessages"),n=O(Pb),r=O($i);return yf(()=>(e(sl(r)),e(Ob(r)),()=>{e(Mb(r))}),[e,t,r]),!t||n.length===0?null:(0,K.jsx)(pn,{type:"custom-messages","data-testid":"custom-messages",children:(0,K.jsx)(ct,{withDivider:!0,children:n.map(o=>(0,K.jsx)(eT,{suggestion:o},o.text))})})},MN=()=>{let e=$(hl),t=Y(),n=B("showAutoflows"),r=O(Eb),o=O($i);return yf(()=>(t(or(o)),t(Cb(o)),()=>{t(bb(o))}),[t,n,o]),!n||r.length===0?null:(0,K.jsx)(pn,{type:"autoflows",title:e("titleAutoflows"),"data-testid":"autoflows",children:(0,K.jsx)(ct,{withDivider:!0,children:(0,K.jsx)(Zb,{})})})},NN=()=>{let e=Y(),t=O(Dd),n=O(dC),r=O(Ub),o=O(_1),i=O(Od),s=O(Fd),a=O(Zn),l=O(Kc);return(0,vl.useEffect)(()=>{!!o&&!n&&H.warn("Custom data provided, but no schema.")},[o,n]),yf(()=>{t.forEach(({type:u})=>{u==="entities"?e(sn()):ql.includes(u)||e(ln(u))})},[e,l,a]),(0,K.jsx)(vl.Fragment,{children:t.map(({type:u,title:c,amount:p,lines:d,schema:g})=>{var y,v;switch(u){case"entities":return i&&i.length>0&&(0,K.jsx)(pn,{type:u,title:c,"data-testid":`type-${u}`,children:(0,K.jsx)(nT,{entities:i})},u);case"cues":return r&&r.length>0&&(0,K.jsx)(pn,{type:u,title:c,"data-testid":`type-${u}`,children:(0,K.jsx)(ct,{withDivider:!0,children:(0,K.jsx)(TT,{cues:r})})},u);case"custom-data":return o&&g&&(0,K.jsx)(pn,{type:u,title:c,"data-testid":`type-${u}`,children:(0,K.jsx)(ct,{withDivider:!0,children:(0,K.jsx)(PT,{data:o,schema:g})})},u);default:return((v=(y=s[u])==null?void 0:y.suggestions)==null?void 0:v.length)>0&&(0,K.jsx)(pn,{type:u,title:c,"data-testid":`type-${u}`,children:(0,K.jsx)(ct,{withDivider:!0,children:(0,K.jsx)(IT,{lines:d,contentType:u,suggestions:s[u].suggestions.slice(0,p)||[]})})},u)}})})},_N=({onLogIn:e})=>{let t=$(hl),n=P("Widget",yl),r=O(qi),o=O(tt),i=O($i),s=O(Zn);return r===!1?(0,K.jsx)(OT,{text:t("notSupported")}):o===!1?(0,K.jsx)(LN,{onLogIn:e}):!s||!i||o===null?(0,K.jsx)(OT,{text:t("waiting")}):(0,K.jsx)("div",{className:(0,MT.default)(n.root),"data-testid":"widget",children:(0,K.jsxs)(Kl,{className:n.sectionList,children:[(0,K.jsx)(IN,{}),(0,K.jsx)(ON,{}),(0,K.jsx)(MN,{}),(0,K.jsx)(NN,{})]})})},NT=_N;function cs(e){let t=new Range;return t.selectNodeContents(e),t}function _T(e,t,n){try{return Jr(e,t,n),!0}catch{return!1}}function vf(e){return"tagName"in e&&(e.tagName==="DIV"||e.tagName==="P")}function Sf(e){return"tagName"in e&&e.tagName==="BR"}var Sl=/[\u200B-\u200D\uFEFF]/g;function Jr(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,p=/[\u200B-\u200D\uFEFF]/;if(!p.test(l))return u;for(let d=0;d<=l.length;d++)if(p.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(Sl,""),p=o+c.length,d=t>=o&&t<=p,g=n>=o&&n<=p;if(d){let y=s(u,t-o);y===0&&!g?r.setStartBefore(l):r.setStart(l,y)}g&&(r.setEnd(l,s(u,n-o)),i=!0),o=p;break}case Node.ELEMENT_NODE:{if(Sf(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;vf(l)&&u&&!vf(u)&&!Sf(u)&&o++;break}default:break}}if(a(e),r.startContainer===document)throw new Error("Offsets out of bound");return r}function xl(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(p){let d=p===n,g=p===o;switch(p.nodeType){case Node.TEXT_NODE:{let y=p.textContent;d&&(a=u+y.substring(0,r).replace(Sl,"").length),g&&(l=u+y.substring(0,i).replace(Sl,"").length),u+=y.replace(Sl,"").length;break}case Node.ELEMENT_NODE:{let y=p.nextSibling===null;Sf(p)&&!y&&u++;for(let v=0;v<p.childNodes.length;v++){let f=d&&v===r,m=g&&v===i;if(f&&(a=u),m&&(l=u),l!==void 0||((!f||!s)&&c(p.childNodes[v]),g&&v===i-1&&(l=u),l!==void 0))break}!g&&vf(p)&&!y&&u++,g&&(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 wl(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,p=u===o;switch(c&&s++,u.nodeType){case Node.TEXT_NODE:{if(s!==0)return;let d=c?r:0,g=p?i:void 0,y=u.textContent.replace(Sl,"");d===0&&g===void 0?a+=y:a+=y.substring(d,g);break}case Node.ELEMENT_NODE:{let d=u.nextSibling===null;s===0&&Sf(u)&&!d&&(a+=`
26
26
  `);for(let g=c?r:0;g<(p?Math.min(i,u.childNodes.length):u.childNodes.length)&&(l(u.childNodes[g]),s!==1);g++);!p&&s===0&&vf(u)&&!d&&(a+=`
27
- `);break}default:break}p&&s++}return l(e),a}var DT=(s=>(s.CUT="Cut",s.BACKSPACE="Backspace",s.DELETE="Delete",s.ERASEEOF="EraseEof",s.UNDO="Undo",s.CLEAR="Clear",s))(DT||{}),ar=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();Ur(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(DT).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(t={shouldObserve:!0}){this.addEventListener("keydown",r=>this.handleKeyDown(r)),this.addEventListener("keyup",r=>this.handleKeyUp(r)),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",r=>this.handlePaste(r)),this.addEventListener("click",()=>this.triggerSelection()),document.activeElement===this.element&&setTimeout(()=>{this.handleFocus()},0);let n=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});t!=null&&t.shouldObserve&&n.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{n.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 FT(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var $o=class extends ar{observer;lastKnownSelection=null;getRootNode(){return this.element.getRootNode()}getText(){let t=new Range;return t.selectNodeContents(this.element),wl(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!FT(n)&&(t.insertNode(this.element.ownerDocument.createTextNode("\u2060")),n=t.getBoundingClientRect(),t.deleteContents(),!FT(n))?null:{top:n.top+n.height,left:n.left}}getSelection(){let t=this.getRange();if(t)return xl(this.element,t);let n=this.lastKnownSelection;if(n&&_T(this.element,n.start,n.end))return n;let r=cs(this.element);return r.collapse(!1),xl(this.element,r)}getSelectedText(){let{start:t,end:n}=this.getSelection();return wl(this.element,Jr(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(t={shouldObserve:!0}){super.listen(t),this.observer=new MutationObserver(()=>{setTimeout(()=>{this.triggerChange()},0)}),t!=null&&t.shouldObserve&&this.observer.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0});let n=this.element.isContentEditable,r=new MutationObserver(()=>{this.element.isContentEditable!==n&&(n=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});r.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>r.disconnect())}dispose(){super.dispose(),this.observer&&this.observer.disconnect()}};var qo=class extends ar{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 HT(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 DN(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}var xy=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()}},wy=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.iframe=HT(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()}},Ey=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(),H.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 wy(t,this.deepdeskUrl,{debug:!0}):new xy(t),r=o=>{var s,a;if(o.origin!==this.deepdeskUrl)return;let i=DN(o.data);typeof i!="object"||i.type!=="event"||i.channel!==t||(H.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;H.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)}},UT=Ey;var ds=class extends Error{constructor(n,r){super(n);this.body=r}name="CustomError"};var Cy=e=>new Promise(t=>{setTimeout(t,e)});var fs=class extends ds{name="ClientError"},Ty=class extends ds{name="ServerError"},by=new Map;async function FN(e){if(e.status===204)return e.text().catch(()=>{}),null;let t=e.headers.get("content-type");if(t&&t.includes("application/json"))return e.json();let n=await e.text();return n===""?null:(H.warn("Unexpected response body:",n.slice(0,20)),JSON.parse(n))}var 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,l=n.method===void 0||n.method.toLowerCase()==="get",{useCache:u=!1,abortLatest:c=!1,attempts:p=1,retryDelay:d=500,refreshTokenOn401:g=!0,retryOnError:y=C=>C instanceof TypeError,retryOnResponse:v=C=>C.status>=500,version:f="v1",...m}=n;if(u)if(l){if(by.has(s)){r(by.get(s));return}}else throw new Error(`Can't use 'useCache' for ${n.method}`);let h={credentials:"include",...m,headers:{"Content-Type":"application/json",...m.headers}};!l&&this.csrfToken&&(h.headers={...h.headers,"X-CSRFToken":this.csrfToken}),typeof f=="string"&&(h.headers={...h.headers,"X-Deepdesk-API-Version":f});let x=p,w=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[s]&&c&&(this.latestRequestByUrl[s].isAborted=!0,this.latestRequestByUrl[s].reject(new Error("Aborted"))),this.latestRequestByUrl[s]=i;let T=async()=>(x--,a(s,h).then(async C=>v(C)&&!i.isAborted&&x>0?(await Cy(d),T()):C.status===401&&g===!0&&w===!1?(w=!0,await this.refreshToken(),T()):C).catch(async C=>{if(y(C)&&!i.isAborted&&x>0)return await Cy(d),T();throw C}));T().then(async C=>{let k=await FN(C);if(delete this.latestRequestByUrl[s],C.status>=500){o(new Ty("Server Error",k));return}else if(C.status===401){o(new fs("Unauthorized",k));return}else if(C.status===403){o(new fs("Forbidden",k));return}else if(C.status===404){o(new fs("Not Found",k));return}else if(C.status>=400){o(new fs("Bad Request",k));return}u&&by.set(s,k),r(k)}).catch(C=>{o(C)})})}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 HN;(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||={})})(HN||={});function xf(e){return{...ee(e),tags:e.tags}}var lr=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(),H.info(`Creating conversation for session ${t.sessionId} and agent ${t.agentId}`);let n=await this.client.post("/api/conversations",{...Re(t),tags:t.tags},{version:"v2"});return xf(n)}async getProfile(t){let n=await this.client.get(`/apis/admin/profiles/${t}/`,{version:null,useCache:!0});return ee(n)}async getKnowledgeAssistant(t){let n=await this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{version:null,useCache:!0});return ee(n)}async getContentTypes(){let t=await this.client.get("/apis/admin/content-types/",{version:null,useCache:!0});return ee(t)}async getAccount(){let t=await this.client.get("/apis/admin/account/",{version:null,useCache:!0});return ee(t)}async getPlatformConfig(){let{config:t}=await this.client.get("/platform/config/",{version:null,useCache:!0});return ee(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(),H.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 H.info(`Successfully retrieved conversation ${i.id} for session ${t}`),xf(i)}async isConversationSupported(t,n={}){H.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=Re(n);n.tags&&(r.tags=n.tags);let o=await this.client.put(`/api/conversations/${t}`,r,{version:"v2"});return xf(o)}async postMessages(t,n){return(await this.client.post(`/api/conversations/${t}/messages`,n.map(o=>({...Re(o),tags:o.tags})),{version:"v2"})).map(o=>xf(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",Re({...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:Re({...n,...r})})}async getEntities(t){return(await this.client.post("/api/entities",{messages:t.filter(r=>r.text)})).entities}async getSummary(t,n={}){let r=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});return ee(r)}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 H.warn(`Invalid token '${t}'`),n})}async authenticateWithKey(t,n){await this.preflight(),await this.client.post("/apis/admin/session/api-key/",Re(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}`,Re(n),{abortLatest:!0})).map(i=>({...ee(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`,Re(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 ee(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",Re(t),{abortLatest:!0});return ee(n)}async search(t){let n=await this.client.post(`/api/profiles/${t.profile}/search`,Re(t),{version:"v2"});return ee(n)}async knowledgeAssist(t,n,r,o={}){let i=await this.client.post(`/api/knowledge-assist/assistants/${r}/search`,Re({question:t.question,doNotKnowAnswer:t.doNotKnowAnswer,customerInstruction:t.customerInstruction,chatHistory:n.map(s=>({question:s.question,answer:s.answer.answer})),agentId:o.agentId,conversationId:o.conversationId}),{version:"v2"});return ee(i)}async requestLoginByEmail(t){let n=await this.client.post("/apis/admin/session/passwordless/request/",{email:t},{version:null});return ee(n)}async requestPasswordlessToken(){let t=await this.client.get("/apis/admin/session/passwordless/request/",{version:null});return ee(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 ee(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 ee(s.cues)}async getRules(){let t=new URLSearchParams,n=await this.client.get(`/apis/admin/rule-engine/rules/?${t.toString()}`,{version:null,useCache:!0});return ee(n)}async translateMessages(t){let n=await this.client.post("/api/translate",Re(t),{version:"v2"});return ee(n)}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),i=o.match(Vv);if(!n||!i)return;let s=i[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[s];a&&n&&a!==n&&H.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[s]=n})}};var El=class{constructor(t,n){this.url=t;this.options={timeout:25e3,...n}}eventListeners={};options;timeoutTimer;eventSource;proxyEvent(t){this.eventSource.addEventListener(qg(t),n=>{let{data:r}=n;try{let o=JSON.parse(r);this.emit(t,ee(o))}catch{H.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 UN;(t=>{let e;(i=>(i.Started="Started",i.Aborted="Aborted",i.Completed="Completed"))(e=t.AutoflowSessionState||={})})(UN||={});var Cl=class{constructor(t,n={}){this.apiUrl=t;this.client=new fn(t,n)}client;streams={};logger=H;async getCustomMessages(t){let n=await this.client.get(`/sessions/${t}/suggestions`);return ee(n.suggestions)}async sendCustomMessage(t,n){let r=await this.client.post(`/sessions/${t}/messages`,Re(n));return ee(r)}async answerCustomMessage(t,n){await this.client.post(`/sessions/${t}/answers`,Re(n))}async getAutoflows(t){let n=await this.client.get(`/sessions/${t}/autoflows`);return ee(n.autoflows)}async startAutoflowSession(t){let n=await this.client.post("/autoflow-sessions",Re(t));return ee(n)}async stopAutoflowSession(t){await this.client.delete(`/autoflow-sessions/${t}`)}openStream(t){return this.streams[t]||(this.streams[t]=new El(`${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 zT={startTime:null,stopTime:null},BT=G({name:"handlingTime",initialState:zT,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(le,()=>zT)}}),{handlingTimeStart:jT,handlingTimeStop:wf,handlingTimeReset:VT}=BT.actions,KT=BT.reducer;var WT=(e={})=>{let t={onAuthError:Wi(!1),...e};return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var Ef={list:{keywordMatches:[]},fetchState:"idle"};var Go=z("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 Ef.list;if(!i)throw new Error("No current conversation to fetch pinned messages");return n.getStyleSuggestions({profileCode:i,message:e})}),zN=G({name:"styleSuggestions",initialState:Ef,reducers:{},extraReducers:e=>{e.addCase(Go.pending,t=>{t.fetchState="loading"}).addCase(Go.rejected,t=>{t.fetchState="error"}).addCase(Go.fulfilled,(t,n)=>{t.fetchState="done",Ur(t.list,n.payload)||(t.list=n.payload)}).addCase(ko,t=>{t.list=Ef.list}).addCase(le,()=>Ef)}}),$T=zN.reducer;var qT=(e={})=>{let t,n=!0,r={getStyleSuggestions:Go,debounce:500,...e};return o=>i=>s=>{var g;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(!((g=u.conversation.current)==null?void 0:g.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 BN(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end}var GT=(e={})=>{let t={getTextSuggestions:ln,getAutocompleteSuggestions:el,debounce:200,check:rs,...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,p=(v=l.conversation.current)==null?void 0:v.id,d=i.type===Hd.toString();if(!p||!u&&!c)return a;let{input:{userCommitted:g}}=l;return BN(g,s)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let f=Gi(l);f===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(f))},d?0:t.debounce)),a}};var YT=Go.fulfilled.toString();function jN(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 XT=e=>t=>n=>r=>{var u;if(r.type!==YT){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=jN(o,s);r.type===YT&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var VN=pc({answer:lC,auth:u1,autoflows:Tb,conversation:v1,contentTypes:yE,customMessages:Nb,passwordlessToken:Hb,entities:KE,knowledgeAssistant:iC,handlingTime:KT,info:U1,input:M1,settings:n1,profile:fC,search:$1,summary:QE,styleSuggestions:$T,ui:FC,rules:jb,textSuggestions:xC});function QT(e){return lw({reducer:VN,middleware:t=>[...t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI,deepdeskBrokerAPI:e.deepdeskBrokerAPI}},serializableCheck:!1}),WT(),GT({debounce:200}),qT({debounce:500}),XT(e.deepdeskAPI),...e.middleware?e.middleware:[]],preloadedState:e.preloadedState})}var KN=e=>{var t;return((t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())??"unknown"},WN=e=>t=>n=>r=>{var a,l,u,c,p;let o=t.getState(),i=zg("inlineSuggestions")(o);switch(r.type){case Wi.toString():{!r.payload&&e.emit("logout",void 0);break}case sn.fulfilled.toString():r.payload.length>0&&e.sendEvent("entities found",{conversationId:(a=o.conversation.current)==null?void 0:a.id,data:{entities:r.payload}});break;case Xe.toString():e.sendEvent(r.payload.name,{conversationId:((l=r.payload.options)==null?void 0:l.includeConversationData)&&((u=o.conversation.current)==null?void 0:u.id),data:r.payload.data});break;case Qc.toString():e.handleKeyDown(r.payload);break;case ko.toString():e.logSendMessage(r.payload);break;case Zc.toString():e.handleInputChanged(r.payload);break;case Ko.fulfilled.toString():r.isBroadcasted||e.broadcast(Xg,r,!1),e.emit("cues",r.payload);break;default:break}let s=n(r);switch(r.type){case ko.toString():e.handleAfterSendMessage(r.payload);break;case nl.toString():e.onUpdateShowTabHint(r.payload);break;case wf.toString():e.logHandlingTime();break;case"analytics/logEvent/fulfilled":{e.emit("event",r.meta.arg);break}case Cn.toString():{let{start:d,end:g}=o.input.selection;e.emit("select-suggestion",{type:KN(r.payload.suggestion),...r.payload,replace:r.payload.replace==="selection"?{start:d,end:g}:{start:0,end:g}},{mayApplyChanges:!0}),i&&(t.dispatch(En([])),t.dispatch(Kn()));break}case Xc.toString():{let{start:d,end:g}=o.input.selection;e.emit("replace",{...r.payload,replace:r.payload.replace==="selection"?{start:d,end:g}:{start:0,end:g}},{mayApplyChanges:!0});break}case Aa.toString():{let d=t.getState(),{text:g,selection:y}=d.input.userCommitted;e.emit("reset",{text:g,selectionAfter:y},{mayApplyChanges:!0});break}case Jc.toString():e.emit("select-image",r.payload,{mayApplyChanges:!0}),e.sendEvent("Image attached",{conversationId:(c=o.conversation.current)==null?void 0:c.id,data:{path:r.payload.suggestion.image,title:r.payload.suggestion.title}});break;case En.toString():{i&&r.payload.length>0&&t.dispatch(Br(0));break}case Yn.fulfilled.toString():{e.sendEvent("conversation summarized",{conversationId:(p=o.conversation.current)==null?void 0:p.id,data:{summary:r.payload.summary,model:t.getState().summary.model}});break}default:break}return s},ZT=WN;function ky(e){return e.toISOString().replace("T"," ").replace("Z","")}function JT(e,t){var i,s,a,l;let n=(i=e.conversation.current)==null?void 0:i.id;if(!n)return H.warn("No conversationId for handling time metrics"),null;let{startTime:r,stopTime:o}=e.handlingTime;return!r||!o?(H.warn("No startTime and stopTime for handling time metrics"),null):{conversationId:n,clientVersion:t.version,agentId:(s=e.info.agentInfo)==null?void 0:s.agentId,agentName:(a=e.info.agentInfo)==null?void 0:a.agentName,agentEmail:(l=e.info.agentInfo)==null?void 0:l.agentEmail,timeStart:ky(r),timeStop:ky(o)}}function ek(e,t,n){var I,L,_,W;let r=(I=t.conversation.current)==null?void 0:I.id;if(!r)return H.warn("No conversationId for send message metrics"),null;let{text:o,metrics:{numCharsTyped:i,numCharsPasted:s,numCharsCut:a,numCharsDeleted:l,numPaste:u,agentStartedTypingTimestamp:c,externalTimeTotalSeconds:p,pastes:d,cuts:g,deletions:y,textSuggestions:v,offeredTextSuggestions:f}}=t[e],m=o.length,x=v.reduce((V,{text:Z,searchTerm:ur})=>V+Z.length-(ur?ur.length:0),0),w=c??Date.now(),T=(Date.now()-w)/1e3+(p||0),C=i/T,k=v.reduce((V,{searchTerm:Z})=>V+(Z?Z.length:0),0);return{conversationId:r,source:"agent",text:o,clientVersion:n.version,pastes:d,cuts:g,deletions:y,lenTextTyped:i+k,lenTextTotal:m,lenTextAssisted:x,lenTextPasted:s,lenTextCut:a,lenTextDeleted:l,timeTotalSeconds:T,charsPerSecond:C,numPastes:u,textSuggestionsV2:v,suggestionsCounters:[{source:"gpt",countOffered:f.filter(V=>V.source==="gpt").length}],agentId:(L=t.info.agentInfo)==null?void 0:L.agentId,agentName:(_=t.info.agentInfo)==null?void 0:_.agentName,agentEmail:(W=t.info.agentInfo)==null?void 0:W.agentEmail}}function Py(e,t){var i;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return Py(r,t);let o=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;return o?Py(o,t):null}function tk(e,t){return Py(e,t)}function nk(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function $N(e){return typeof e=="object"&&e!==null&&"tagName"in e}function Cf(e){return $N(e)&&(Yr(e)||$d(e))}var ok,Pn=new Map,qN=["bottom","height","left","right","top","width"],rk=(e,t)=>!e&&!t?!1:e&&!t||!e&&t?!0:qN.some(n=>e[n]!==t[n]);function ik(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,...ik(t)]:[]}function sk(e,t){return!e||!t?null:{...e,top:e.top+t.top,left:e.left+t.left}}var bf=!1,ak=()=>{bf=!0;let e=[];if(Pn.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),Pn.delete(n);return}let r=n.getBoundingClientRect();rk(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{let n=t.parentRects?t.parentRects.reduce(sk,t.rect):t.rect;rk(n,t.totalRect)&&t.callbacks.forEach(r=>r(n)),t.totalRect=n}),Pn.size===0){bf=!1;return}ok=window.requestAnimationFrame(ak)};function Ry(e,t){let n=ik(e),r=[],o=n.map((i,s)=>Ry(i,a=>{r[s]=a;let l=Pn.get(e);if(!l)return;let u=r.reduce(sk,l.rect);l.callbacks.forEach(c=>c(u))}));return{observe(i=!0){if(o.forEach(s=>s.observe(!1)),Pn.has(e)){let s=Pn.get(e);s.callbacks.push(t),s.rect&&t(s.rect)}else Pn.set(e,{rect:void 0,callbacks:[t],parentRects:r});i&&!bf&&ak()},unobserve(){o.forEach(s=>s.unobserve());let i=Pn.get(e);if(i){let s=i.callbacks.indexOf(t);s>=0&&i.callbacks.splice(s,1),i.callbacks.length||Pn.delete(e),Pn.size||(cancelAnimationFrame(ok),bf=!1)}}}}var lk,Rn=new Map,uk=()=>{Rn.forEach((e,t)=>{if(!t.isConnected){Rn.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)))}),Rn.size!==0&&(lk=window.requestAnimationFrame(uk))};function ck(e,t){return{observe(){let n=Rn.size===0;Rn.has(e)?Rn.get(e).callbacks.push(t):Rn.set(e,{visible:void 0,callbacks:[t]}),n&&uk()},unobserve(){let n=Rn.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||Rn.delete(e),Rn.size||cancelAnimationFrame(lk)}}}}var Ay=["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 Ly(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function ps(e){return parseFloat(e)}function Tf(e){return Math.round(e*1e6)}function dk(e){return e/1e6}function Iy(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=ps(e.width),i=ps(e.borderLeftWidth),s=ps(e.borderRightWidth),a=ps(e.paddingRight),l=dk(Tf(o)-Tf(i)-Tf(s)),u=dk(Tf(r));if(l-u>2){let c=l-u;n.style.paddingRight=`${a+c}px`}}function bl(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",Bo(n);let r=window.getComputedStyle(e),o=!0,i=()=>{n.scrollTop=e.scrollTop};Ly(r,n,Ay),Iy(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",i));let s=ck(e,()=>{Ly(r,n,Ay),Iy(r,e,n),i(),setTimeout(i,0)}),a,l=!0,u=Ry(e,p=>{if(p===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),p.height===0&&p.width===0){if(o===!0)return;t.onHide&&t.onHide(),n.style.display="none",o=!0;return}if(Ly(r,n,Ay),Iy(r,e,n),i(),n.style.top=`${p.top}px`,n.style.left=`${p.left}px`,t.closestScrollElement&&t.closestScrollElement!==e){let d=t.closestScrollElement.getBoundingClientRect(),g=window.getComputedStyle(t.closestScrollElement),y=ps(g.borderTopWidth),v=ps(g.borderBottomWidth),f=d.top+y-p.top,m=p.top+p.height+-(d.top+d.height-v);n.style.clipPath=`inset(${f}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 fk=(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{H.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function GN(e){return e.offsetParent!==null}function pk(e){if(!GN(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 kf(e,t,n=100){let r=pk(e);t({isVisible:r});let o=setInterval(()=>{let i=pk(e);i!==r&&(r=i,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var Le=S(b());var mk=fk("showTabHint",!0),Tl=class e{static version="11.5.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 lr(u,{token:i,fetch:s}),this.version=r,this.instanceId=e.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[ZT({broadcast:(p,d,g)=>{this.broadcastEvents.send(p,d,g)},emit:(p,d,g)=>this.emit(p,d,g),handleAfterSendMessage:p=>this.handleAfterSendMessage(p),handleInputChanged:p=>this.handleInputChanged(p),handleKeyDown:p=>this.handleKeyDown(p),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:p=>this.logSendMessage(p),onUpdateShowTabHint:p=>mk.update(p),sendEvent:(p,d)=>this.deepdeskApi.sendEvent(p,d)})]};n&&Object.assign(c,{deepdeskBrokerAPI:new Cl(n)}),this.store=QT(c),this.broadcastEvents=new UT({debug:!0,deepdeskUrl:u,eventMap:q1(this.store),createCustomChannel:l}),this.store.dispatch(nl(mk.value())),this.store.dispatch(jc({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?(H.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(H.warn("Profile has not been loaded (yet)"),!0):(H.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(Wi(null)),this.store.dispatch(jn()),new Promise(t=>{let n=this.store.subscribe(()=>{let r=this.store.getState();tt(r)&&r1(r)!=="loading"&&(n(),t())});this.unmountHandlers.push(()=>{n()})})}async isLoggedIn(){return(await this.store.dispatch(jn())).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){H.warn("Failed to attach user:",n)}}async isConversationSupported(t,n){return(await this.store.dispatch(Kg({sessionId:t,options:n}))).payload}async createConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(Wc(t))).payload}async getConversationBySessionId(t,n){return this.hasConversation()&&this.sessionId()!==t&&this.resetConversation(),(await this.store.dispatch($c({sessionId:t,options:n}))).payload}async upsertConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(Wg(t))).payload}async postMessages(t){return(await this.store.dispatch(Gc(t))).payload}async updateConversation(t){return(await this.store.dispatch(qc(t))).payload}resetConversation(){this.store.dispatch(le()),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(jc(t))}setVisitorInfo(t){this.store.dispatch(F1(t))}setCustomData(t){this.store.dispatch(H1(t))}async setAgentInfo(t){await this.store.dispatch(La(t))}async setAgentSettings(t){await this.store.dispatch(Gg(t))}async getAgentSettings(){return(await this.store.dispatch(Yg())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let t=[];return this.store.dispatch(Hd()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})}notifyInputChanged(t){this.store.dispatch(Zc(t))}notifyKeyDown(t){this.store.dispatch(Qc(t))}notifyPaste(t,n){this.store.dispatch(A1({text:t,selectionText:n}))}notifyCut(t){this.store.dispatch(P1(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(Ko({label:t,params:n}));if(o)throw new Error(o.message);return r}handleInputChanged(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui;n&&r&&this.store.dispatch(qr({collapse:!1})),this.inputMediator&&this.store.dispatch(E1({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(R1(S1(t))),t.key!=="Tab"&&!this.settings.showTextSuggestions)return;let u=()=>{n||!a||i&&(t.shiftKey||(this.store.dispatch(b1()),s||this.stageSelectedSuggestion({inputType:"arrow"}),t.preventDefault()))},c=()=>{n||!a||s&&o<=0||i&&(t.shiftKey||(this.store.dispatch(k1()),t.preventDefault(),!s&&(this.state.input.selectedSuggestionIndex===-1?this.store.dispatch(Aa()):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(Br(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(Br(-1)),this.store.dispatch(Aa()),t.preventDefault()):n||(this.store.dispatch(qr({collapse:!0})),this.store.dispatch(_C(!0)),t.preventDefault());return}case"Tab":{let{userCommitted:p}=this.state.input,d=p.text.substring(0,p.selection.end),{tabCompletionSuggestion:g}=this.state.input;this.store.dispatch(nl(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):!s&&this.settings.showTabCompletion&&g&&g.text.startsWith(d)&&(this.store.dispatch(Cn({text:g.text,suggestion:g,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(L1()),this.store.dispatch(En([]))}handlingTimeStart(){this.state.handlingTime.startTime||(H.info("Start handling time"),this.store.dispatch(jT()))}handlingTimeStop(){this.state.handlingTime.startTime&&(H.info("Stop handling time"),this.store.dispatch(wf()))}logSendMessage(t){let n=ek("input",this.state,{version:this.version});n&&(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=JT(this.state,{version:this.version});t&&(this.deepdeskApi.sendEventV1("Handling Time",t),this.store.dispatch(VT()))}notifySubmit(t={}){this.shouldAbort()||(this.store.dispatch(Kn()),this.store.dispatch(ko(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=()=>{let i=this.eventListeners[t];i&&i.forEach(s=>{try{s(n)}catch(a){H.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),H.error(a)}})};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]=bl(n,r);return i.setAttribute("translate","no"),i.dataset.testid=t,o&&i.classList.add(o),this.unmountHandlers.push(()=>{(0,qt.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]=bl(i,{appendTo:document.body,onMoveStart:()=>{o.style.display="none"}});a.dataset.testid=n,a.style.zIndex="2",a.appendChild(r),this.unmountHandlers.push(()=>{(0,qt.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 Bo(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,qt.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),H.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()?(H.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(O1(r.metrics))):H.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(!Cf(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:p,detectSubmit:d,insertLink:g,inputMediator:y,closestScrollSelector:v,appendOverlayTo:f,inlineSuggestions:m,floatingMenu:h}=n;this.configure({showStyleSuggestions:o,showTabCompletion:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,showTextSuggestions:s,insertLink:g,isEmbedded:p,inlineSuggestions:m,floatingMenu:!!h}),n.automaticHandlingTime&&this.setupHandlingTime(t),Bo(t),this.inputMediator=y||(Yr(t)?new qo(t):new $o(t)),this.inputMediator.on("change",({plainText:T})=>{this.notifyInputChanged(T)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(I1({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()}))}),this.inputMediator.on("keydown",T=>{this.notifyKeyDown(T)}),this.inputMediator.on("paste",({pastedText:T,selectionText:C})=>{this.notifyPaste(T,C)}),this.inputMediator.on("cut",({selectionText:T})=>{this.notifyCut(T)});let x=v&&tk(t,v)||void 0;if(m){let{customStyles:T,appendOverlayTo:C}=n;if(Yr(t))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let k=this.createInlineContainer(t,"deepdesk-caret");(0,qt.render)((0,Le.jsx)(Vo,{store:this.store,customStyles:T,children:(0,Le.jsx)(Ro,{broadcastEvents:this.broadcastEvents,children:(0,Le.jsx)(VC,{})})}),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",x||t,{appendTo:typeof h=="object"&&"appendOverlayTo"in h?h.appendOverlayTo:C},T==null?void 0:T.floatingMenuRootNode);(0,qt.render)((0,Le.jsx)(Vo,{store:this.store,customStyles:T,children:(0,Le.jsx)(Ro,{broadcastEvents:this.broadcastEvents,children:(0,Le.jsx)(OC,{onLogIn:()=>this.loginViaPopup().catch(L=>H.warn(L.message))})})}),I)}else{let T=this.overlayContainerFactory("deepdesk-tab-completion",x||t,{appendTo:f,closestScrollElement:x,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),C=this.overlayContainerFactory("deepdesk-suggestions-overlay",x||t,{appendTo:f},r==null?void 0:r.suggestionsRootNode);(0,qt.render)((0,Le.jsx)(Vo,{store:this.store,customStyles:r,children:(0,Le.jsx)(Ro,{broadcastEvents:this.broadcastEvents,children:(0,Le.jsx)(Sb,{inputElement:t})})}),T),(0,qt.render)((0,Le.jsx)(Vo,{store:this.store,customStyles:r,children:(0,Le.jsx)(Ro,{broadcastEvents:this.broadcastEvents,children:(0,Le.jsx)(ZC,{onLogIn:()=>this.loginViaPopup().catch(k=>H.warn(k.message))})})}),C)}(0,qt.render)((0,Le.jsx)(Vo,{store:this.store,customStyles:r,children:(0,Le.jsx)(Ro,{broadcastEvents:this.broadcastEvents,children:(0,Le.jsx)(PC,{})})}),this.createContainer("deepdesk-overlays"));let w;this.inputMediator.on("selection",T=>{clearTimeout(w),T===null?w=setTimeout(()=>{T!==null&&this.store.dispatch($g(T))},500):this.store.dispatch($g(T))}),this.inputMediator.on("disabled",()=>{var T;(T=this.inputMediator)==null||T.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(Fh(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(Fh(!0))),this.store.dispatch(C1({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 T;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((T=this.state.conversation.current)==null?void 0:T.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&&H.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,qt.render)((0,Le.jsx)(Vo,{store:this.store,customStyles:r,children:(0,Le.jsx)(Ro,{broadcastEvents:this.broadcastEvents,children:(0,Le.jsx)(NT,{onLogIn:()=>this.loginViaPopup().catch(s=>H.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,qt.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(t){let n=kf(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){nk(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(Ja());let t=Zn(this.state);t&&(await this.store.dispatch(Xa()),this.store.dispatch(jc({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",p),clearInterval(d)};i.onmessage=async g=>{var y,v;if((y=g.data)!=null&&y.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((v=g.data)==null?void 0:v.jwt),await this.isLoggedIn(),this.broadcastEvents.send(Oa),l=!0,o.port1.close(),n()}catch(f){console.error(f),r(f)}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 p=async g=>{var y;if(g.origin===a.origin)switch((y=g.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){H.error("Error posting message to popup",v),r(v)}break}case"deepdesk-popup-error":{u(),g.data.message==="Timeout"&&H.warn("Popup timed out. Check if the account's platform url is configured correctly."),r(new Error(g.data.message));break}}};window.addEventListener("message",p);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(H.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;H.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=Dd(this.state);try{n.forEach(({type:r})=>{r==="entities"?this.store.dispatch(sn()):ql.includes(r)||this.store.dispatch(ln(r))})}catch(r){this.handleError(r)}}};async function gk(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 hk(e,t,n={}){let r=n.replace?Jr(e,n.replace.start,n.replace.end):cs(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
+ `);break}default:break}p&&s++}return l(e),a}var DT=(s=>(s.CUT="Cut",s.BACKSPACE="Backspace",s.DELETE="Delete",s.ERASEEOF="EraseEof",s.UNDO="Undo",s.CLEAR="Clear",s))(DT||{}),ar=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();Ur(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(DT).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(t={shouldObserve:!0}){this.addEventListener("keydown",r=>this.handleKeyDown(r)),this.addEventListener("keyup",r=>this.handleKeyUp(r)),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",r=>this.handlePaste(r)),this.addEventListener("click",()=>this.triggerSelection()),document.activeElement===this.element&&setTimeout(()=>{this.handleFocus()},0);let n=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});t!=null&&t.shouldObserve&&n.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{n.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 FT(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var $o=class extends ar{observer;lastKnownSelection=null;getRootNode(){return this.element.getRootNode()}getText(){let t=new Range;return t.selectNodeContents(this.element),wl(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!FT(n)&&(t.insertNode(this.element.ownerDocument.createTextNode("\u2060")),n=t.getBoundingClientRect(),t.deleteContents(),!FT(n))?null:{top:n.top+n.height,left:n.left}}getSelection(){let t=this.getRange();if(t)return xl(this.element,t);let n=this.lastKnownSelection;if(n&&_T(this.element,n.start,n.end))return n;let r=cs(this.element);return r.collapse(!1),xl(this.element,r)}getSelectedText(){let{start:t,end:n}=this.getSelection();return wl(this.element,Jr(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(t={shouldObserve:!0}){super.listen(t),this.observer=new MutationObserver(()=>{setTimeout(()=>{this.triggerChange()},0)}),t!=null&&t.shouldObserve&&this.observer.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0});let n=this.element.isContentEditable,r=new MutationObserver(()=>{this.element.isContentEditable!==n&&(n=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});r.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>r.disconnect())}dispose(){super.dispose(),this.observer&&this.observer.disconnect()}};var qo=class extends ar{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 HT(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 DN(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}var xy=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()}},wy=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.iframe=HT(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()}},Ey=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(),H.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 wy(t,this.deepdeskUrl,{debug:!0}):new xy(t),r=o=>{var s,a;if(o.origin!==this.deepdeskUrl)return;let i=DN(o.data);typeof i!="object"||i.type!=="event"||i.channel!==t||(H.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;H.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)}},UT=Ey;var ds=class extends Error{constructor(n,r){super(n);this.body=r}name="CustomError"};var Cy=e=>new Promise(t=>{setTimeout(t,e)});var fs=class extends ds{name="ClientError"},Ty=class extends ds{name="ServerError"},by=new Map;async function FN(e){if(e.status===204)return e.text().catch(()=>{}),null;let t=e.headers.get("content-type");if(t&&t.includes("application/json"))return e.json();let n=await e.text();return n===""?null:(H.warn("Unexpected response body:",n.slice(0,20)),JSON.parse(n))}var 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,l=n.method===void 0||n.method.toLowerCase()==="get",{useCache:u=!1,abortLatest:c=!1,attempts:p=1,retryDelay:d=500,refreshTokenOn401:g=!0,retryOnError:y=C=>C instanceof TypeError,retryOnResponse:v=C=>C.status>=500,version:f="v1",...m}=n;if(u)if(l){if(by.has(s)){r(by.get(s));return}}else throw new Error(`Can't use 'useCache' for ${n.method}`);let h={credentials:"include",...m,headers:{"Content-Type":"application/json",...m.headers}};!l&&this.csrfToken&&(h.headers={...h.headers,"X-CSRFToken":this.csrfToken}),typeof f=="string"&&(h.headers={...h.headers,"X-Deepdesk-API-Version":f});let x=p,w=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[s]&&c&&(this.latestRequestByUrl[s].isAborted=!0,this.latestRequestByUrl[s].reject(new Error("Aborted"))),this.latestRequestByUrl[s]=i;let T=async()=>(x--,a(s,h).then(async C=>v(C)&&!i.isAborted&&x>0?(await Cy(d),T()):C.status===401&&g===!0&&w===!1?(w=!0,await this.refreshToken(),T()):C).catch(async C=>{if(y(C)&&!i.isAborted&&x>0)return await Cy(d),T();throw C}));T().then(async C=>{let k=await FN(C);if(delete this.latestRequestByUrl[s],C.status>=500){o(new Ty("Server Error",k));return}else if(C.status===401){o(new fs("Unauthorized",k));return}else if(C.status===403){o(new fs("Forbidden",k));return}else if(C.status===404){o(new fs("Not Found",k));return}else if(C.status>=400){o(new fs("Bad Request",k));return}u&&by.set(s,k),r(k)}).catch(C=>{o(C)})})}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 HN;(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||={})})(HN||={});function xf(e){return{...ee(e),tags:e.tags}}var lr=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(),H.info(`Creating conversation for session ${t.sessionId} and agent ${t.agentId}`);let n=await this.client.post("/api/conversations",{...Re(t),tags:t.tags},{version:"v2"});return xf(n)}async getProfile(t){let n=await this.client.get(`/apis/admin/profiles/${t}/`,{version:null,useCache:!0});return ee(n)}async getKnowledgeAssistant(t){let n=await this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{version:null,useCache:!0});return ee(n)}async getContentTypes(){let t=await this.client.get("/apis/admin/content-types/",{version:null,useCache:!0});return ee(t)}async getAccount(){let t=await this.client.get("/apis/admin/account/",{version:null,useCache:!0});return ee(t)}async getPlatformConfig(){let{config:t}=await this.client.get("/platform/config/",{version:null,useCache:!0});return ee(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(),H.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 H.info(`Successfully retrieved conversation ${i.id} for session ${t}`),xf(i)}async isConversationSupported(t,n={}){H.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=Re(n);n.tags&&(r.tags=n.tags);let o=await this.client.put(`/api/conversations/${t}`,r,{version:"v2"});return xf(o)}async postMessages(t,n){return(await this.client.post(`/api/conversations/${t}/messages`,n.map(o=>({...Re(o),tags:o.tags})),{version:"v2"})).map(o=>xf(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",Re({...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:Re({...n,...r})})}async getEntities(t){return(await this.client.post("/api/entities",{messages:t.filter(r=>r.text)})).entities}async getSummary(t,n={}){let r=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});return ee(r)}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 H.warn(`Invalid token '${t}'`),n})}async authenticateWithKey(t,n){await this.preflight(),await this.client.post("/apis/admin/session/api-key/",Re(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}`,Re(n),{abortLatest:!0})).map(i=>({...ee(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`,Re(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 ee(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",Re(t),{abortLatest:!0});return ee(n)}async search(t){let n=await this.client.post(`/api/profiles/${t.profile}/search`,Re(t),{version:"v2"});return ee(n)}async knowledgeAssist(t,n,r,o={}){let i=await this.client.post(`/api/knowledge-assist/assistants/${r}/search`,Re({question:t.question,doNotKnowAnswer:t.doNotKnowAnswer,customerInstruction:t.customerInstruction,chatHistory:n.map(s=>({question:s.question,answer:s.answer.answer})),agentId:o.agentId,conversationId:o.conversationId}),{version:"v2"});return ee(i)}async requestLoginByEmail(t){let n=await this.client.post("/apis/admin/session/passwordless/request/",{email:t},{version:null});return ee(n)}async requestPasswordlessToken(){let t=await this.client.get("/apis/admin/session/passwordless/request/",{version:null});return ee(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 ee(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 ee(s.cues)}async getRules(){let t=new URLSearchParams,n=await this.client.get(`/apis/admin/rule-engine/rules/?${t.toString()}`,{version:null,useCache:!0});return ee(n)}async translateMessages(t){let n=await this.client.post("/api/translate",Re(t),{version:"v2"});return ee(n)}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),i=o.match(Vv);if(!n||!i)return;let s=i[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[s];a&&n&&a!==n&&H.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[s]=n})}};var El=class{constructor(t,n){this.url=t;this.options={timeout:25e3,...n}}eventListeners={};options;timeoutTimer;eventSource;proxyEvent(t){this.eventSource.addEventListener(qg(t),n=>{let{data:r}=n;try{let o=JSON.parse(r);this.emit(t,ee(o))}catch{H.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 UN;(t=>{let e;(i=>(i.Started="Started",i.Aborted="Aborted",i.Completed="Completed"))(e=t.AutoflowSessionState||={})})(UN||={});var Cl=class{constructor(t,n={}){this.apiUrl=t;this.client=new fn(t,n)}client;streams={};logger=H;async getCustomMessages(t){let n=await this.client.get(`/sessions/${t}/suggestions`);return ee(n.suggestions)}async sendCustomMessage(t,n){let r=await this.client.post(`/sessions/${t}/messages`,Re(n));return ee(r)}async answerCustomMessage(t,n){await this.client.post(`/sessions/${t}/answers`,Re(n))}async getAutoflows(t){let n=await this.client.get(`/sessions/${t}/autoflows`);return ee(n.autoflows)}async startAutoflowSession(t){let n=await this.client.post("/autoflow-sessions",Re(t));return ee(n)}async stopAutoflowSession(t){await this.client.delete(`/autoflow-sessions/${t}`)}openStream(t){return this.streams[t]||(this.streams[t]=new El(`${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 zT={startTime:null,stopTime:null},BT=G({name:"handlingTime",initialState:zT,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(le,()=>zT)}}),{handlingTimeStart:jT,handlingTimeStop:wf,handlingTimeReset:VT}=BT.actions,KT=BT.reducer;var WT=(e={})=>{let t={onAuthError:Wi(!1),...e};return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var Ef={list:{keywordMatches:[]},fetchState:"idle"};var Go=z("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 Ef.list;if(!i)throw new Error("No current conversation to fetch pinned messages");return n.getStyleSuggestions({profileCode:i,message:e})}),zN=G({name:"styleSuggestions",initialState:Ef,reducers:{},extraReducers:e=>{e.addCase(Go.pending,t=>{t.fetchState="loading"}).addCase(Go.rejected,t=>{t.fetchState="error"}).addCase(Go.fulfilled,(t,n)=>{t.fetchState="done",Ur(t.list,n.payload)||(t.list=n.payload)}).addCase(ko,t=>{t.list=Ef.list}).addCase(le,()=>Ef)}}),$T=zN.reducer;var qT=(e={})=>{let t,n=!0,r={getStyleSuggestions:Go,debounce:500,...e};return o=>i=>s=>{var g;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(!((g=u.conversation.current)==null?void 0:g.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 BN(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end}var GT=(e={})=>{let t={getTextSuggestions:ln,getAutocompleteSuggestions:el,debounce:200,check:rs,...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,p=(v=l.conversation.current)==null?void 0:v.id,d=i.type===Hd.toString();if(!p||!u&&!c)return a;let{input:{userCommitted:g}}=l;return BN(g,s)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let f=Gi(l);f===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(f))},d?0:t.debounce)),a}};var YT=Go.fulfilled.toString();function jN(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 XT=e=>t=>n=>r=>{var u;if(r.type!==YT){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=jN(o,s);r.type===YT&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var VN=pc({answer:lC,auth:u1,autoflows:Tb,conversation:v1,contentTypes:yE,customMessages:Nb,passwordlessToken:Hb,entities:KE,knowledgeAssistant:iC,handlingTime:KT,info:U1,input:M1,settings:n1,profile:fC,search:$1,summary:QE,styleSuggestions:$T,ui:FC,rules:jb,textSuggestions:xC});function QT(e){return lw({reducer:VN,middleware:t=>[...t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI,deepdeskBrokerAPI:e.deepdeskBrokerAPI}},serializableCheck:!1}),WT(),GT({debounce:200}),qT({debounce:500}),XT(e.deepdeskAPI),...e.middleware?e.middleware:[]],preloadedState:e.preloadedState})}var KN=e=>{var t;return((t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())??"unknown"},WN=e=>t=>n=>r=>{var a,l,u,c,p;let o=t.getState(),i=zg("inlineSuggestions")(o);switch(r.type){case Wi.toString():{!r.payload&&e.emit("logout",void 0);break}case sn.fulfilled.toString():r.payload.length>0&&e.sendEvent("entities found",{conversationId:(a=o.conversation.current)==null?void 0:a.id,data:{entities:r.payload}});break;case Xe.toString():e.sendEvent(r.payload.name,{conversationId:((l=r.payload.options)==null?void 0:l.includeConversationData)&&((u=o.conversation.current)==null?void 0:u.id),data:r.payload.data});break;case Qc.toString():e.handleKeyDown(r.payload);break;case ko.toString():e.logSendMessage(r.payload);break;case Zc.toString():e.handleInputChanged(r.payload);break;case Ko.fulfilled.toString():r.isBroadcasted||e.broadcast(Xg,r,!1),e.emit("cues",r.payload);break;default:break}let s=n(r);switch(r.type){case ko.toString():e.handleAfterSendMessage(r.payload);break;case nl.toString():e.onUpdateShowTabHint(r.payload);break;case wf.toString():e.logHandlingTime();break;case"analytics/logEvent/fulfilled":{e.emit("event",r.meta.arg);break}case Cn.toString():{let{start:d,end:g}=o.input.selection;e.emit("select-suggestion",{type:KN(r.payload.suggestion),...r.payload,replace:r.payload.replace==="selection"?{start:d,end:g}:{start:0,end:g}},{mayApplyChanges:!0}),i&&(t.dispatch(En([])),t.dispatch(Kn()));break}case Xc.toString():{let{start:d,end:g}=o.input.selection;e.emit("replace",{...r.payload,replace:r.payload.replace==="selection"?{start:d,end:g}:{start:0,end:g}},{mayApplyChanges:!0});break}case Aa.toString():{let d=t.getState(),{text:g,selection:y}=d.input.userCommitted;e.emit("reset",{text:g,selectionAfter:y},{mayApplyChanges:!0});break}case Jc.toString():e.emit("select-image",r.payload,{mayApplyChanges:!0}),e.sendEvent("Image attached",{conversationId:(c=o.conversation.current)==null?void 0:c.id,data:{path:r.payload.suggestion.image,title:r.payload.suggestion.title}});break;case En.toString():{i&&r.payload.length>0&&t.dispatch(Br(0));break}case Yn.fulfilled.toString():{e.sendEvent("conversation summarized",{conversationId:(p=o.conversation.current)==null?void 0:p.id,data:{summary:r.payload.summary,model:t.getState().summary.model}});break}default:break}return s},ZT=WN;function ky(e){return e.toISOString().replace("T"," ").replace("Z","")}function JT(e,t){var i,s,a,l;let n=(i=e.conversation.current)==null?void 0:i.id;if(!n)return H.warn("No conversationId for handling time metrics"),null;let{startTime:r,stopTime:o}=e.handlingTime;return!r||!o?(H.warn("No startTime and stopTime for handling time metrics"),null):{conversationId:n,clientVersion:t.version,agentId:(s=e.info.agentInfo)==null?void 0:s.agentId,agentName:(a=e.info.agentInfo)==null?void 0:a.agentName,agentEmail:(l=e.info.agentInfo)==null?void 0:l.agentEmail,timeStart:ky(r),timeStop:ky(o)}}function ek(e,t,n){var I,L,_,W;let r=(I=t.conversation.current)==null?void 0:I.id;if(!r)return H.warn("No conversationId for send message metrics"),null;let{text:o,metrics:{numCharsTyped:i,numCharsPasted:s,numCharsCut:a,numCharsDeleted:l,numPaste:u,agentStartedTypingTimestamp:c,externalTimeTotalSeconds:p,pastes:d,cuts:g,deletions:y,textSuggestions:v,offeredTextSuggestions:f}}=t[e],m=o.length,x=v.reduce((V,{text:Z,searchTerm:ur})=>V+Z.length-(ur?ur.length:0),0),w=c??Date.now(),T=(Date.now()-w)/1e3+(p||0),C=i/T,k=v.reduce((V,{searchTerm:Z})=>V+(Z?Z.length:0),0);return{conversationId:r,source:"agent",text:o,clientVersion:n.version,pastes:d,cuts:g,deletions:y,lenTextTyped:i+k,lenTextTotal:m,lenTextAssisted:x,lenTextPasted:s,lenTextCut:a,lenTextDeleted:l,timeTotalSeconds:T,charsPerSecond:C,numPastes:u,textSuggestionsV2:v,suggestionsCounters:[{source:"gpt",countOffered:f.filter(V=>V.source==="gpt").length}],agentId:(L=t.info.agentInfo)==null?void 0:L.agentId,agentName:(_=t.info.agentInfo)==null?void 0:_.agentName,agentEmail:(W=t.info.agentInfo)==null?void 0:W.agentEmail}}function Py(e,t){var i;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return Py(r,t);let o=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;return o?Py(o,t):null}function tk(e,t){return Py(e,t)}function nk(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function $N(e){return typeof e=="object"&&e!==null&&"tagName"in e}function Cf(e){return $N(e)&&(Yr(e)||$d(e))}var ok,Pn=new Map,qN=["bottom","height","left","right","top","width"],rk=(e,t)=>!e&&!t?!1:e&&!t||!e&&t?!0:qN.some(n=>e[n]!==t[n]);function ik(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,...ik(t)]:[]}function sk(e,t){return!e||!t?null:{...e,top:e.top+t.top,left:e.left+t.left}}var bf=!1,ak=()=>{bf=!0;let e=[];if(Pn.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),Pn.delete(n);return}let r=n.getBoundingClientRect();rk(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{let n=t.parentRects?t.parentRects.reduce(sk,t.rect):t.rect;rk(n,t.totalRect)&&t.callbacks.forEach(r=>r(n)),t.totalRect=n}),Pn.size===0){bf=!1;return}ok=window.requestAnimationFrame(ak)};function Ry(e,t){let n=ik(e),r=[],o=n.map((i,s)=>Ry(i,a=>{r[s]=a;let l=Pn.get(e);if(!l)return;let u=r.reduce(sk,l.rect);l.callbacks.forEach(c=>c(u))}));return{observe(i=!0){if(o.forEach(s=>s.observe(!1)),Pn.has(e)){let s=Pn.get(e);s.callbacks.push(t),s.rect&&t(s.rect)}else Pn.set(e,{rect:void 0,callbacks:[t],parentRects:r});i&&!bf&&ak()},unobserve(){o.forEach(s=>s.unobserve());let i=Pn.get(e);if(i){let s=i.callbacks.indexOf(t);s>=0&&i.callbacks.splice(s,1),i.callbacks.length||Pn.delete(e),Pn.size||(cancelAnimationFrame(ok),bf=!1)}}}}var lk,Rn=new Map,uk=()=>{Rn.forEach((e,t)=>{if(!t.isConnected){Rn.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)))}),Rn.size!==0&&(lk=window.requestAnimationFrame(uk))};function ck(e,t){return{observe(){let n=Rn.size===0;Rn.has(e)?Rn.get(e).callbacks.push(t):Rn.set(e,{visible:void 0,callbacks:[t]}),n&&uk()},unobserve(){let n=Rn.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||Rn.delete(e),Rn.size||cancelAnimationFrame(lk)}}}}var Ay=["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 Ly(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function ps(e){return parseFloat(e)}function Tf(e){return Math.round(e*1e6)}function dk(e){return e/1e6}function Iy(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=ps(e.width),i=ps(e.borderLeftWidth),s=ps(e.borderRightWidth),a=ps(e.paddingRight),l=dk(Tf(o)-Tf(i)-Tf(s)),u=dk(Tf(r));if(l-u>2){let c=l-u;n.style.paddingRight=`${a+c}px`}}function bl(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",Bo(n);let r=window.getComputedStyle(e),o=!0,i=()=>{n.scrollTop=e.scrollTop};Ly(r,n,Ay),Iy(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",i));let s=ck(e,()=>{Ly(r,n,Ay),Iy(r,e,n),i(),setTimeout(i,0)}),a,l=!0,u=Ry(e,p=>{if(p===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),p.height===0&&p.width===0){if(o===!0)return;t.onHide&&t.onHide(),n.style.display="none",o=!0;return}if(Ly(r,n,Ay),Iy(r,e,n),i(),n.style.top=`${p.top}px`,n.style.left=`${p.left}px`,t.closestScrollElement&&t.closestScrollElement!==e){let d=t.closestScrollElement.getBoundingClientRect(),g=window.getComputedStyle(t.closestScrollElement),y=ps(g.borderTopWidth),v=ps(g.borderBottomWidth),f=d.top+y-p.top,m=p.top+p.height+-(d.top+d.height-v);n.style.clipPath=`inset(${f}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 fk=(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{H.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function GN(e){return e.offsetParent!==null}function pk(e){if(!GN(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 kf(e,t,n=100){let r=pk(e);t({isVisible:r});let o=setInterval(()=>{let i=pk(e);i!==r&&(r=i,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var Le=S(b());var mk=fk("showTabHint",!0),Tl=class e{static version="11.5.3";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 lr(u,{token:i,fetch:s}),this.version=r,this.instanceId=e.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[ZT({broadcast:(p,d,g)=>{this.broadcastEvents.send(p,d,g)},emit:(p,d,g)=>this.emit(p,d,g),handleAfterSendMessage:p=>this.handleAfterSendMessage(p),handleInputChanged:p=>this.handleInputChanged(p),handleKeyDown:p=>this.handleKeyDown(p),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:p=>this.logSendMessage(p),onUpdateShowTabHint:p=>mk.update(p),sendEvent:(p,d)=>this.deepdeskApi.sendEvent(p,d)})]};n&&Object.assign(c,{deepdeskBrokerAPI:new Cl(n)}),this.store=QT(c),this.broadcastEvents=new UT({debug:!0,deepdeskUrl:u,eventMap:q1(this.store),createCustomChannel:l}),this.store.dispatch(nl(mk.value())),this.store.dispatch(jc({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?(H.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(H.warn("Profile has not been loaded (yet)"),!0):(H.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(Wi(null)),this.store.dispatch(jn()),new Promise(t=>{let n=this.store.subscribe(()=>{let r=this.store.getState();tt(r)&&r1(r)!=="loading"&&(n(),t())});this.unmountHandlers.push(()=>{n()})})}async isLoggedIn(){return(await this.store.dispatch(jn())).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){H.warn("Failed to attach user:",n)}}async isConversationSupported(t,n){return(await this.store.dispatch(Kg({sessionId:t,options:n}))).payload}async createConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(Wc(t))).payload}async getConversationBySessionId(t,n){return this.hasConversation()&&this.sessionId()!==t&&this.resetConversation(),(await this.store.dispatch($c({sessionId:t,options:n}))).payload}async upsertConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(Wg(t))).payload}async postMessages(t){return(await this.store.dispatch(Gc(t))).payload}async updateConversation(t){return(await this.store.dispatch(qc(t))).payload}resetConversation(){this.store.dispatch(le()),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(jc(t))}setVisitorInfo(t){this.store.dispatch(F1(t))}setCustomData(t){this.store.dispatch(H1(t))}async setAgentInfo(t){await this.store.dispatch(La(t))}async setAgentSettings(t){await this.store.dispatch(Gg(t))}async getAgentSettings(){return(await this.store.dispatch(Yg())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let t=[];return this.store.dispatch(Hd()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})}notifyInputChanged(t){this.store.dispatch(Zc(t))}notifyKeyDown(t){this.store.dispatch(Qc(t))}notifyPaste(t,n){this.store.dispatch(A1({text:t,selectionText:n}))}notifyCut(t){this.store.dispatch(P1(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(Ko({label:t,params:n}));if(o)throw new Error(o.message);return r}handleInputChanged(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui;n&&r&&this.store.dispatch(qr({collapse:!1})),this.inputMediator&&this.store.dispatch(E1({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(R1(S1(t))),t.key!=="Tab"&&!this.settings.showTextSuggestions)return;let u=()=>{n||!a||i&&(t.shiftKey||(this.store.dispatch(b1()),s||this.stageSelectedSuggestion({inputType:"arrow"}),t.preventDefault()))},c=()=>{n||!a||s&&o<=0||i&&(t.shiftKey||(this.store.dispatch(k1()),t.preventDefault(),!s&&(this.state.input.selectedSuggestionIndex===-1?this.store.dispatch(Aa()):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(Br(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(Br(-1)),this.store.dispatch(Aa()),t.preventDefault()):n||(this.store.dispatch(qr({collapse:!0})),this.store.dispatch(_C(!0)),t.preventDefault());return}case"Tab":{let{userCommitted:p}=this.state.input,d=p.text.substring(0,p.selection.end),{tabCompletionSuggestion:g}=this.state.input;this.store.dispatch(nl(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):!s&&this.settings.showTabCompletion&&g&&g.text.startsWith(d)&&(this.store.dispatch(Cn({text:g.text,suggestion:g,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(L1()),this.store.dispatch(En([]))}handlingTimeStart(){this.state.handlingTime.startTime||(H.info("Start handling time"),this.store.dispatch(jT()))}handlingTimeStop(){this.state.handlingTime.startTime&&(H.info("Stop handling time"),this.store.dispatch(wf()))}logSendMessage(t){let n=ek("input",this.state,{version:this.version});n&&(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=JT(this.state,{version:this.version});t&&(this.deepdeskApi.sendEventV1("Handling Time",t),this.store.dispatch(VT()))}notifySubmit(t={}){this.shouldAbort()||(this.store.dispatch(Kn()),this.store.dispatch(ko(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=()=>{let i=this.eventListeners[t];i&&i.forEach(s=>{try{s(n)}catch(a){H.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),H.error(a)}})};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]=bl(n,r);return i.setAttribute("translate","no"),i.dataset.testid=t,o&&i.classList.add(o),this.unmountHandlers.push(()=>{(0,qt.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]=bl(i,{appendTo:document.body,onMoveStart:()=>{o.style.display="none"}});a.dataset.testid=n,a.style.zIndex="2",a.appendChild(r),this.unmountHandlers.push(()=>{(0,qt.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 Bo(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,qt.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),H.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()?(H.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(O1(r.metrics))):H.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(!Cf(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:p,detectSubmit:d,insertLink:g,inputMediator:y,closestScrollSelector:v,appendOverlayTo:f,inlineSuggestions:m,floatingMenu:h}=n;this.configure({showStyleSuggestions:o,showTabCompletion:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,showTextSuggestions:s,insertLink:g,isEmbedded:p,inlineSuggestions:m,floatingMenu:!!h}),n.automaticHandlingTime&&this.setupHandlingTime(t),Bo(t),this.inputMediator=y||(Yr(t)?new qo(t):new $o(t)),this.inputMediator.on("change",({plainText:T})=>{this.notifyInputChanged(T)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(I1({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()}))}),this.inputMediator.on("keydown",T=>{this.notifyKeyDown(T)}),this.inputMediator.on("paste",({pastedText:T,selectionText:C})=>{this.notifyPaste(T,C)}),this.inputMediator.on("cut",({selectionText:T})=>{this.notifyCut(T)});let x=v&&tk(t,v)||void 0;if(m){let{customStyles:T,appendOverlayTo:C}=n;if(Yr(t))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let k=this.createInlineContainer(t,"deepdesk-caret");(0,qt.render)((0,Le.jsx)(Vo,{store:this.store,customStyles:T,children:(0,Le.jsx)(Ro,{broadcastEvents:this.broadcastEvents,children:(0,Le.jsx)(VC,{})})}),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",x||t,{appendTo:typeof h=="object"&&"appendOverlayTo"in h?h.appendOverlayTo:C},T==null?void 0:T.floatingMenuRootNode);(0,qt.render)((0,Le.jsx)(Vo,{store:this.store,customStyles:T,children:(0,Le.jsx)(Ro,{broadcastEvents:this.broadcastEvents,children:(0,Le.jsx)(OC,{onLogIn:()=>this.loginViaPopup().catch(L=>H.warn(L.message))})})}),I)}else{let T=this.overlayContainerFactory("deepdesk-tab-completion",x||t,{appendTo:f,closestScrollElement:x,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),C=this.overlayContainerFactory("deepdesk-suggestions-overlay",x||t,{appendTo:f},r==null?void 0:r.suggestionsRootNode);(0,qt.render)((0,Le.jsx)(Vo,{store:this.store,customStyles:r,children:(0,Le.jsx)(Ro,{broadcastEvents:this.broadcastEvents,children:(0,Le.jsx)(Sb,{inputElement:t})})}),T),(0,qt.render)((0,Le.jsx)(Vo,{store:this.store,customStyles:r,children:(0,Le.jsx)(Ro,{broadcastEvents:this.broadcastEvents,children:(0,Le.jsx)(ZC,{onLogIn:()=>this.loginViaPopup().catch(k=>H.warn(k.message))})})}),C)}(0,qt.render)((0,Le.jsx)(Vo,{store:this.store,customStyles:r,children:(0,Le.jsx)(Ro,{broadcastEvents:this.broadcastEvents,children:(0,Le.jsx)(PC,{})})}),this.createContainer("deepdesk-overlays"));let w;this.inputMediator.on("selection",T=>{clearTimeout(w),T===null?w=setTimeout(()=>{T!==null&&this.store.dispatch($g(T))},500):this.store.dispatch($g(T))}),this.inputMediator.on("disabled",()=>{var T;(T=this.inputMediator)==null||T.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(Fh(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(Fh(!0))),this.store.dispatch(C1({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 T;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((T=this.state.conversation.current)==null?void 0:T.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&&H.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,qt.render)((0,Le.jsx)(Vo,{store:this.store,customStyles:r,children:(0,Le.jsx)(Ro,{broadcastEvents:this.broadcastEvents,children:(0,Le.jsx)(NT,{onLogIn:()=>this.loginViaPopup().catch(s=>H.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,qt.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(t){let n=kf(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){nk(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(Ja());let t=Zn(this.state);t&&(await this.store.dispatch(Xa()),this.store.dispatch(jc({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",p),clearInterval(d)};i.onmessage=async g=>{var y,v;if((y=g.data)!=null&&y.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((v=g.data)==null?void 0:v.jwt),await this.isLoggedIn(),this.broadcastEvents.send(Oa),l=!0,o.port1.close(),n()}catch(f){console.error(f),r(f)}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 p=async g=>{var y;if(g.origin===a.origin)switch((y=g.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){H.error("Error posting message to popup",v),r(v)}break}case"deepdesk-popup-error":{u(),g.data.message==="Timeout"&&H.warn("Popup timed out. Check if the account's platform url is configured correctly."),r(new Error(g.data.message));break}}};window.addEventListener("message",p);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(H.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;H.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=Dd(this.state);try{n.forEach(({type:r})=>{r==="entities"?this.store.dispatch(sn()):ql.includes(r)||this.store.dispatch(ln(r))})}catch(r){this.handleError(r)}}};async function gk(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 hk(e,t,n={}){let r=n.replace?Jr(e,n.replace.start,n.replace.end):cs(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(`
28
28
  `).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?Jr(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 YN(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 XN(e){let t=document.createDocumentFragment();return e.split(`
29
29
  `).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 yk(e,t){let n=e.parentElement;if(!n){console.warn("No insert point found");return}let{display:r}=window.getComputedStyle(n);r.includes("block")||r==="table-cell"?n==null||n.insertBefore(t,e.nextSibling):yk(n,t)}async function vk(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?YN(t):XN(t);n?yk(l.startContainer,u):(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 Sk(e){return e.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}async function xk(e,t,n){await new lr(e).authenticateWithKey(t,n)}async function wk(e){let n=await new fn(e).get("/platform/config/",{version:null,useCache:!0});return ee(n)}async function QN(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 Ek(e,t){let n=await QN(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 Fk(ZN);})();
30
30
  /*! Bundled license information: