@deepdesk/deepdesk-sdk 11.2.1-beta.9 → 11.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs.js +2 -2
- package/dist/index.esm.js +2 -2
- package/dist/index.iife.js +2 -2
- package/package.json +1 -1
package/dist/index.iife.js
CHANGED
|
@@ -22,9 +22,9 @@ Try polyfilling it using "@formatjs/intl-pluralrules"
|
|
|
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
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 Ih=S(b()),sO={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},CC=({className:e,color:t})=>(0,Ih.jsx)("svg",{className:e,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:(0,Ih.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:sO[t||"pink"]})});var bC={root:"q",text:"C",isLoggedIn:"di",isLoggedOut:"po",icon:"li",logo:"si",lock:"ci"};var Nh={};ze(Nh,{enUS:()=>lO,nlNL:()=>uO});var lO={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Search"}]},uO={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Zoeken"}]};var Fo=S(b()),kC=({onLogIn:e})=>{let t=W(Nh),n=B("floatingMenu"),r=B("productName"),o=Y(),i=N(tt),s=P("FloatingMenu",bC);if(i===null||n===!1)return null;let a=()=>{i===!0?o(xt(!0)):e()};return(0,Fo.jsxs)("button",{className:(0,TC.default)(s.root,{[s.isLoggedIn]:i,[s.isLoggedOut]:!i}),onClick:a,children:[(0,Fo.jsx)("div",{className:s.text,children:t(i?"search":"signin",{productName:r})}),(0,Fo.jsxs)("div",{className:s.icon,children:[(0,Fo.jsx)(CC,{className:s.logo,color:"pink"}),i===!1&&(0,Fo.jsx)(EC,{className:s.lock})]})]})};var Ud=S(_());var PC=S(_());function ts(e){(0,PC.useEffect)(()=>{let t=n=>{n.isWithinRoot||e(n)};return document.body.addEventListener("mouseup",t),()=>{document.body.removeEventListener("mouseup",t)}},[e])}function Ho(e){e.addEventListener("mouseup",t=>{t.isWithinRoot=!0},!0)}function ns(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 cO={showTabHint:!1,inputHasFocus:!1,overlayCollapsed:!1,openOverlayWhenTyping:!1,overlayCollapsedUserOverwrite:!1};var Dd=({ui:e})=>e.overlayCollapsed;var RC=q({name:"ui",initialState:cO,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:tl,setInputHasFocus:Oh,setOverlayCollapsed:Vr,setOpenOverlayWhenTyping:AC,setOverlayCollapsedUserOverwrite:LC}=RC.actions,IC=RC.reducer;var Fd=S(_());var rs=S(_());var NC=S(_());function OC(e,t,n){(0,NC.useEffect)(()=>{let r=e.current;return r?(r.addEventListener(t,n),()=>{r.removeEventListener(t,n)}):()=>{}},[e,t,n])}var MC={root:"xi",actions:"fi",badge:"gi",formattedText:"do"};var Uo=S(b()),pO=["search","personal-collection-search","search-autocomplete"];function mO(e,t,n,r={}){let o="";return pO.includes(t)?o=EE(hh(e,n,{stripAgentPart:!0}),r.searchKeywords??[n]):o=hh(e,n,r),r.placeholders===!0&&(o=CE(o)),o}var gO=()=>{},hO=({index:e,selected:t,suggestion:n,onFeedback:r})=>{let o=B("inlineSuggestions"),i=N(Wi),s=Y(),a=P("TextSuggestion",MC),l=(0,rs.useRef)(null);(0,rs.useEffect)(()=>{let c=setTimeout(()=>{s(E1({text:n.text,suggestion:n}))},500);return()=>{clearTimeout(c)}},[n]),OC(l,"click",()=>{s(Fr(e)),s(En({suggestion:n,text:n.text,eventMetrics:{inputType:"mouse"},replace:"until-selection-end"}))});let u=(0,rs.useMemo)(()=>mO(n.text,n.source,i,{stripAgentPart:o,placeholders:!0,searchKeywords:n.searchKeywords}),[o,n.text,n.source,i,n.searchKeywords]);return n.source==="gpt"&&!o?null:(0,Uo.jsxs)("div",{className:a.root,onMouseEnter:()=>s(Fr(e)),children:[(0,Uo.jsx)(te,{ref:l,as:"button","data-testid":"suggestions-overlay-item",selected:t,onClick:gO,children:(0,Uo.jsx)(Gi,{containerTagName:"div",noWrap:!1,tagName:"span",className:a.formattedText,content:u})}),t&&r&&(0,Uo.jsx)("div",{className:a.actions,children:(0,Uo.jsx)(Td,{onFeedback:()=>r(n),suggestion:n.text})})]})},_C=hO;var Mh=S(b()),yO=({onFeedback:e,suggestions:t,selectedIndex:n,reverse:r})=>{let o=(0,Fd.useMemo)(()=>{let i=t.map((s,a)=>(0,Mh.jsx)(_C,{index:a,selected:a===n,suggestion:s,onFeedback:e},`${s.text}-${s.source}`));return r?i.reverse():i},[t,n,r]);return(0,Mh.jsx)(Fd.Fragment,{children:o})},Hd=yO;var DC={root:"bi",paper:"hi"};var nl=S(b()),SO=({textSuggestions:e,selectedIndex:t})=>{let n=(0,Ud.useRef)(null),r=P("InlineSuggestionsOverlay",DC),o=N(ns),i=Y(),s=N(tt),a=N(Ki),l=N(Dd),u=B("showTextSuggestions");return ts(()=>{setTimeout(()=>{i(Vr({collapse:!0,skipWhenInputFocus:!0}))})}),(0,Ud.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,nl.jsx)("div",{className:r.root,"data-variant":"inline",children:(0,nl.jsx)("div",{ref:n,className:r.paper,children:(0,nl.jsx)(ht,{children:(0,nl.jsx)(Hd,{suggestions:e,selectedIndex:t})})})})},wO=({input:e})=>({selectedIndex:e.selectedSuggestionIndex,textSuggestions:e.textSuggestions}),FC=jn(wO)(SO);var rl=S(b()),xO=({children:e})=>{let n=B("locale").replace("-","");return(0,rl.jsx)(th.Provider,{value:n,children:e})},EO=({store:e,customStyles:t={},children:n})=>(0,rl.jsx)(Mg,{store:e,children:(0,rl.jsx)(xO,{children:(0,rl.jsx)(Ss.Provider,{value:t,children:n})})}),Bo=EO;var jd=S(ee()),os=S(_());var HC=S(_());function UC(e,t){let[n,r]=(0,HC.useState)(()=>{if(typeof window>"u")return t;try{let i=window.localStorage.getItem(e);return i?JSON.parse(i):t}catch(i){return j.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){j.error(s)}}]}var BC=()=>/Mac/i.test(navigator.platform);var zC=S(ee()),Qn=S(_());var _h={};ze(_h,{enUS:()=>CO,nlNL:()=>bO});var CO={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"}]}]},bO={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 jC={root:"mi",anchor:"ui",anchorButton:"yi"};var Kr=S(b()),Dh=(e,t,n)=>r=>(0,Kr.jsx)("button",{className:e.anchorButton,type:"button",value:t,onClick:n,children:r},t),kO=({className:e,loginUrl:t,isEmbedded:n,onSnooze:r,onLogIn:o})=>{let i=W(_h),s=zt(),a=P("Login",jC),l=B("productName"),u=(0,Qn.useCallback)(f=>{f.preventDefault(),r&&r(parseInt(f.target.value,10))},[]),c=(0,Qn.useCallback)(f=>{f.preventDefault(),s.send($i,!0)},[t]),p=(0,Qn.useMemo)(()=>f=>(0,Kr.jsx)("a",{onClick:h=>{h.preventDefault(),o()},href:t,className:a.anchor,target:"_blank",rel:"noreferrer",children:f},"login"),[t]),d=(0,Qn.useCallback)(f=>(0,Kr.jsx)("button",{type:"button",className:a.anchorButton,onClick:c,children:f},"prompt"),[c]),{min:g,hour:y,day:v}=(0,Qn.useMemo)(()=>({min:Dh(a,60*10,u),hour:Dh(a,60*60,u),day:Dh(a,60*60*12,u)}),[]);return(0,Kr.jsxs)("div",{className:(0,zC.default)(e,a.root),children:[i("loginPlease",{login:n?d:p,productName:l}),r&&(0,Kr.jsxs)(Qn.Fragment,{children:[(0,Kr.jsx)("br",{}),i("snooze",{min:g,hour:y,day:v})]})]})},Bd=kO;var VC={root:"lo",text:"wi"};var ol=S(b()),RO=({title:e})=>{let t=P("SearchTrigger",VC),n=Y();return(0,ol.jsxs)("button",{type:"button",className:t.root,onClick:()=>n(xt(!0)),children:[(0,ol.jsx)(Yi,{}),(0,ol.jsx)("span",{className:t.text,children:e})]})},KC=RO;var Fh={};ze(Fh,{enUS:()=>AO,nlNL:()=>LO});var AO={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"}]},LO={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 WC={root:"vi",isInline:"S",toggleButton:"ki",toggleButtonWrapper:"E",toggleButtonWrapperHidden:"zi",isCollapsed:"so",collapsible:"ji",hints:"co",hintsHidden:"Yi",triggers:"xo",triggersRight:"qi"};var Se=S(b()),NO=({textSuggestions:e,selectedIndex:t,onLogIn:n})=>{let r=P("SuggestionsOverlay",WC),o=W(Fh),i=N(ns),s=v1(),a=Y(),l=(0,os.useRef)(null),u=B("searchTriggerKey"),c=B("productName"),p=N(Dd),d=N(tt),g=N(Ki),[y,v]=(0,os.useState)(null),f=B("showSearch"),m=B("showTextSuggestions"),h=B("adminUrl"),w=B("isEmbedded"),[x,T]=UC("dd-snooze-until-ms",0),C=p||x>Date.now(),k=N(K=>K.input.text),L=e.filter(K=>K.source!=="gpt").length,I=()=>{C&&T(0),a(LC(!C))},O=K=>{a(Xe({name:"suggestion feedback",data:{text:K.text,source:"overlay",context:k},options:{includeConversationData:!0}}))},V=K=>{let se=Date.now()+K*1e3;T(se),j.info(`Snooze until: ${new Date(se)}`),a(Vr({collapse:!0}))};return(0,os.useEffect)(()=>{L===0&&v(null)},[e,L]),ts(()=>{a(Vr({collapse:!0,skipWhenInputFocus:!0}))}),d===null||g===!1?null:d===!1?(0,Se.jsxs)("div",{ref:l,className:(0,jd.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)(ro,{className:r.toggleButton,title:o("collapse"),onClick:I,isCollapsed:!1})})]}),(0,Se.jsx)("div",{className:r.toggleButtonWrapper,children:(0,Se.jsx)(ro,{className:r.toggleButton,title:o("open",{productName:c}),onClick:I,isCollapsed:!0})}),(0,Se.jsx)("div",{className:r.collapsible,children:(0,Se.jsx)(Bd,{loginUrl:h,isEmbedded:w,onLogIn:n,onSnooze:V})})]}):!s||!i?null:(0,Se.jsxs)("div",{ref:l,className:(0,jd.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(BC()?"searchHintMac":"searchHintWindows",{searchTriggerKey:u.toUpperCase()})),onMouseLeave:()=>v(null),children:(0,Se.jsx)(KC,{title:o("search")})})}),(0,Se.jsxs)("div",{className:r.triggersRight,onFocus:()=>{},children:[(0,Se.jsx)("div",{className:(0,jd.default)(!y&&r.hintsHidden,r.hints),children:y}),(0,Se.jsx)(ro,{className:r.toggleButton,title:o("collapse"),onClick:I,isCollapsed:!1})]})]}),(0,Se.jsx)("div",{className:r.toggleButtonWrapper,children:(0,Se.jsx)(ro,{className:r.toggleButton,title:o("open",{productName:c}),onClick:I,isCollapsed:!0})}),L>0&&m&&(0,Se.jsx)("div",{className:r.collapsible,onFocus:()=>{},children:(0,Se.jsx)(ht,{children:(0,Se.jsx)(Hd,{onFeedback:O,suggestions:e,selectedIndex:t,reverse:!0})})})]})},OO=({input:e})=>({selectedIndex:e.selectedSuggestionIndex,textSuggestions:e.textSuggestions}),$C=jn(OO)(NO);var nf=S(ee());var er=S(_());var is=S(_());function zd(e){return e.contentEditable==="true"}function MO(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 GC(e){let{selectionStart:t,selectionEnd:n}=zd(e)?MO(e):e;return[t,n]}function qC(e){let[,t]=(0,is.useState)(),n=(0,is.useRef)(null);return n.current=GC(e),(0,is.useEffect)(()=>{let r=()=>{let[o,i]=n.current??[],s=GC(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 YC(e,t){if(!t)return;let n=e,{value:r}=n,[o,i]=t,s=r.match(Vl);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 XC=S(_()),_O=["div","span","mark","strong","b","i","u","em"];function Hh(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(_O.includes(o)){let s=Array.isArray(r.props.children)?r.props.children:[r.props.children];return[...e.slice(0,e.length-1),(0,XC.cloneElement)(r,{children:Hh(s,t,n+1)})]}return[...e,...t]}function Wr(e){return e.tagName.toLowerCase()==="textarea"}var un={root:"Ci",container:"Si",agentText:"fo",tabText:"go",hint:"G",matchSelection:"bo",focus:"Ei",resetIndent:"Gi",matchKeyword:"p",matchPlaceholder:"d",hover:"ho",hintText:"Ni",popover:"Ai",popoverRoot:"Fi",popoverContentContainer:"mo",popoverContent:"Hi",selectionOptions:"Li",selectionOptionsIsHidden:"Mi",selectionOptionsButton:"Ri",caret:"Ti",popoverSuggestionsRoot:"Ui",suggestionsOverlayInputStyles:"Bi"};var sb=S(ee());var Qd=S(_());var ss=S(_());function QC(e,t){let n;return[(...r)=>{window.cancelAnimationFrame(n);let o=t?t(...r):r;n=window.requestAnimationFrame(()=>{e(...o)})},()=>window.cancelAnimationFrame(n)]}function Vd(e){let t=(0,ss.useRef)(null),[n,r]=(0,ss.useState)(!1);return(0,ss.useEffect)(()=>{let o=!1,i=parseFloat(window.getComputedStyle(document.body).zoom??"1"),[s,a]=QC((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]=QC(()=>{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 ZC(e){return e.replace(/[.*+^${}()|[\]\\]/g,"\\$&")}function Kd(e){return t=>{e.forEach(n=>{typeof n=="function"?n(t):n!=null&&(n.current=t)})}}function JC(e){return e!=null}var Bh=S(ee()),Kt=S(_());var Wd=S(_()),FO=["bottom","height","left","right","top","width"],HO=(e={},t={})=>FO.some(n=>e[n]!==t[n]),Zn=new Map,eb,tb=()=>{let e=[],t=[];Zn.forEach((n,r)=>{if(r instanceof Element&&!r.isConnected){t.push(r);return}let o=r.getBoundingClientRect();HO(o,n.rect)&&(n.rect=o,e.push(n))}),t.forEach(n=>{Zn.delete(n)}),e.forEach(n=>{n.callbacks.forEach(r=>r(n.rect))}),eb=window.requestAnimationFrame(tb)};function UO(e,t){return{observe(){let n=Zn.size===0;if(Zn.has(e)){let r=Zn.get(e);r.callbacks.push(t),r.rect&&t(r.rect)}else Zn.set(e,{rect:void 0,hasRectChanged:!1,callbacks:[t]});n&&tb()},unobserve(){let n=Zn.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||Zn.delete(e),Zn.size||cancelAnimationFrame(eb)}}}}function Uh(e){let[t,n]=(0,Wd.useState)(null);return(0,Wd.useLayoutEffect)(()=>{if(!e.current)return;let r=UO(e.current,o=>{n(o)});return r.observe(),()=>{r.unobserve()}},[e]),t}var as=S(_()),rb=S(nc());var nb={root:"Di"};var ob=({children:e,parentNode:t})=>{let[n,r]=(0,as.useState)(null),o=(0,as.useContext)(Ss);return(0,as.useLayoutEffect)(()=>{let i=document.createElement("div");return Ho(i),i.classList.add(nb.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,rb.createPortal)(e,n):null};var bn={ref:"Ii",root:"o",positionAbove:"l",positionBelow:"s",positionLeft:"c",positionRight:"x",alignStart:"f",alignCenter:"g",alignEnd:"b"};var $d=S(b()),Gd=(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 jh(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 ls=({className:e,triggerRef:t,boundaryRef:n=(0,Kt.createRef)(),position:r="above",align:o="center",children:i,toStyle:s=jh,parentNode:a,...l})=>{let u=Uh(t),c=Uh(n),p=(0,Kt.useMemo)(()=>s(u,c,0),[u,c]);return(0,$d.jsx)(ob,{parentNode:a,children:(0,$d.jsx)("div",{className:(0,Bh.default)(bn.ref,{[bn.positionAbove]:r==="above",[bn.positionBelow]:r==="below",[bn.positionLeft]:r==="left",[bn.positionRight]:r==="right",[bn.alignStart]:o==="start",[bn.alignCenter]:o==="center",[bn.alignEnd]:o==="end"}),style:p,...l,role:"dialog",children:(0,$d.jsx)("div",{className:(0,Bh.default)(e,bn.root),children:i})})})};var ib=S(ee()),qd=S(_());var zh=S(b()),Yd=(0,qd.forwardRef)(({className:e,children:t,...n},r)=>{let o=(0,qd.useRef)(null),i=P("TabCompletion",un);return(0,zh.jsx)("div",{ref:Kd([o,r]),className:(0,ib.default)(e,i.popoverContentContainer),...n,children:(0,zh.jsx)("div",{className:i.popoverContent,children:t})})});var $r=S(b()),zO=e=>t=>{let n=jh(t);return"top"in n&&(n.width=e.width-(t.left-e.left)-10),n},VO=({inputElement:e,boundaryRef:t,inputStyle:n,children:r,suggestion:o})=>{let i=P("TabCompletion",un),s=Gd(),a=(0,Qd.useMemo)(()=>zO(e.getBoundingClientRect()),[e]),[l,u]=Vd(e);return(0,Qd.useEffect)(()=>{u?s.open():s.close()},[u]),(0,$r.jsxs)("span",{children:[(0,$r.jsx)("mark",{ref:Kd([l,s.triggerRef]),className:(0,sb.default)(i.matchKeyword,{[i.hover]:u}),"aria-haspopup":"dialog","aria-expanded":s.opened?"true":"false",children:r}),s.opened&&(0,$r.jsx)(ls,{className:i.popover,triggerRef:s.triggerRef,boundaryRef:t,position:"below",align:"start",toStyle:a,children:(0,$r.jsx)(Yd,{style:n,children:(0,$r.jsx)("div",{className:i.hintText,children:o})})})]})},Xd=class extends Wn{keywordMatches=[];preparedKeywordMatches=[];usedKeywordMatches=new Set;onBeforeParse(t,n){return n.keywordMatches&&n.keywordMatches!==this.keywordMatches&&(this.preparedKeywordMatches=n.keywordMatches.map(r=>({...r,keywordRegex:new RegExp(`\\b${ZC(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(JC);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,$r.jsx)(VO,{inputElement:n.inputElement,suggestion:n.suggestion,inputStyle:n.inputStyle,boundaryRef:n.boundaryRef,children:t},`keyword_${n.matchString}_${n.key}`)}asTag(){return"mark"}};var ab=S(ee());var Vh=S(b()),KO=({inputElement:e,children:t})=>{let n=P("TabCompletion",un),[r,o]=Vd(e);return(0,Vh.jsx)("mark",{ref:r,className:(0,ab.default)(n.matchPlaceholder,{[n.hover]:o}),children:t})},Zd=class extends Wn{match(t){let n=t.match(/(((\$!\{)|(\{))[a-zA-Z0-9_.]+\}(?!\}))/);return n?{index:n.index,length:n[0].length,match:n[0],matchString:n[0],valid:!0}:null}replaceWith(t,n){return(0,Vh.jsx)(KO,{inputElement:n.inputElement,children:t},`placeholder_${n.matchString}_${n.key}`)}asTag(){return"mark"}};var ef=S(ee());var ot=S(_());var Kh=S(b()),lb=()=>(0,Kh.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,Kh.jsx)("path",{fill:"currentColor",d:"M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76 0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71 0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71 0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76 0 5-2.24 5-5s-2.24-5-5-5z"})});var Gr=S(_());var cb=S(sh());var ub={root:"Oi",content:"Xi"};function Jd(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 Wh(e){return e.replace("https://www.","").replace("https://","")}var Wt=S(b()),$O=3,GO=e=>({image:e.image||"",text:e.text,id:e.id,title:e.title}),qO=({onSelectLink:e,onDismiss:t,placeholder:n,visitUrlText:r,linkCount:o=$O})=>{let i=P("LinkSearch",ub),[s,a]=(0,Gr.useState)(""),l=Y(),u=N(dC("url")),c=N(U1("URL",GO)),[p,d]=(0,Gr.useState)(c.length-1),g=B("fallbackImage"),y=h=>{let w=h.target;a(w.value)},v=(h,w)=>{h.stopPropagation(),h.preventDefault(),window.open(w,"_blank")},f=h=>{var T;let w=p-1<0?c.length-1:p-1,x=p+1===c.length?0:p+1;h.code==="Escape"&&(a(""),t()),h.code==="ArrowUp"&&d(w),h.code==="ArrowDown"&&d(x),h.code==="Enter"&&e(((T=c[p])==null?void 0:T.text)||s)},m=(0,Gr.useCallback)((0,cb.default)(h=>{l(Co({query:h,type:"URL",tags:["link-search"]}))},300),[]);return(0,Gr.useEffect)(()=>{s&&m(s)},[s]),(0,Gr.useEffect)(()=>()=>{l(Qc())},[]),(0,Wt.jsxs)("div",{className:i.root,children:[(0,Wt.jsx)(ht,{withDivider:!0,children:(s?c:u).slice(0,o).map((h,w)=>(0,Wt.jsx)(te,{selected:p===w,onClick:()=>e(h.text),"data-testid":"linksearch-suggestion",children:(0,Wt.jsxs)(fe,{children:[(0,Wt.jsx)(fe.Image,{src:Jd(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||Wh(h.text)}),h.title&&Wh(h.text)]}),(0,Wt.jsx)(te.Actions,{children:(0,Wt.jsx)(te.ActionButton,{label:r,onClick:x=>v(x,h.text)})})]})},h.text))}),(0,Wt.jsx)(Ha,{value:s,onChange:y,autoFocus:!0,placeholder:n,onKeyUp:f})]})},db=qO;var $h={};ze($h,{enUS:()=>YO,nlNL:()=>XO});var YO={insertLink:[{type:0,value:"Insert link"}],linkInputPlaceholder:[{type:0,value:"Search, type or paste link"}],visitUrl:[{type:0,value:"Visit"}]},XO={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()),QO=(0,ot.forwardRef)((e,t)=>{let n=P("TabCompletion",un);return(0,rt.jsx)("mark",{ref:t,className:(0,ef.default)(n.matchSelection)},"selection-start")}),ZO=({startRef:e,boundaryRef:t,inputStyle:n,inputElement:r,children:o})=>{let i=W($h),s=P("TabCompletion",un),a=(0,ot.useRef)(null),l=(0,ot.useRef)(null),[u,c]=(0,ot.useState)(null),p=Y(),d=Gd(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]),ts(()=>{d.close()});let y=(0,ot.useCallback)(v=>{let f=g.toString(),m=/^http(s?):\/\//.test(v)?v:`https://${v}`;p($c({text:`[${f}](${m})`,replace:"selection"}))},[]);return(0,rt.jsxs)("span",{children:[(0,rt.jsx)("mark",{ref:a,className:(0,ef.default)(s.matchSelection),"aria-haspopup":"dialog","aria-expanded":d.opened?"true":"false",children:o}),d.opened&&(0,rt.jsx)(ls,{className:s.popoverRoot,triggerRef:d.triggerRef,boundaryRef:t,position:"above",align:"start",children:(0,rt.jsxs)(Yd,{style:n,ref:l,children:[(0,rt.jsx)("div",{className:(0,ef.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)(lb,{}),(0,rt.jsx)("span",{children:"\xA0"}),(0,rt.jsx)("span",{children:i("insertLink")})]})}),u==="insertLink"&&(0,rt.jsx)(db,{placeholder:i("linkInputPlaceholder"),visitUrlText:i("visitUrl"),onSelectLink:y,onDismiss:()=>{c(null),d.close()}})]})})]},"selection-end")},tf=class extends Wn{charCount=0;foundIndex=0;startRef=null;props;onBeforeParse(t,n){return this.props=n,this.charCount=0,this.startRef=(0,ot.createRef)(),this.foundIndex=0,t}match(t){if(!this.props||this.props.selection===null||this.foundIndex===2)return null;let[n,r]=this.props.selection;if(n===r)return null;let o=this.foundIndex===0?n:r,i=o>=this.charCount&&o<=this.charCount+t.length?{index:o-this.charCount,length:0,match:"",valid:!0}:null;i&&this.foundIndex++;let s=this.foundIndex===1;return i&&s?this.charCount+=o-this.charCount:this.charCount+=t.length,i?{isStart:s,...i}:null}replaceWith(t,n){return n.isStart?(0,rt.jsx)(QO,{ref:this.startRef}):(0,rt.jsx)(ZO,{inputElement:n.inputElement,startRef:this.startRef,boundaryRef:n.boundaryRef,inputStyle:n.inputStyle})}asTag(){return"mark"}};var Jn=S(b()),JO=({enabled:e,content:t,tabText:n,showTabHint:r,showTabCompletion:o,showStyleSuggestions:i,keywordMatches:s,inputElement:a,source:l})=>{let u=P("TabCompletion",un),c=B("insertLink"),p=B("showMidSentenceSuggestions"),d=B("inlineSuggestions"),g=qC(a),y=(0,er.useRef)(null),v=N(tt);(0,er.useEffect)(()=>{Wr(a)&&g&&YC(a,g)},[g]);let f=(0,er.useCallback)(w=>{if(!o||!n)return w;let x=[(0,Jn.jsx)("span",{className:u.resetIndent,children:"\u200B"},"u200B"),(0,Jn.jsx)("span",{"data-testid":"tab-completion",className:(0,nf.default)(u.tabText,u.resetIndent),"data-source":l,children:n},"tabText")];return r&&x.push((0,Jn.jsx)("span",{className:(0,nf.default)(u.hint,u.resetIndent),children:(0,Jn.jsx)(Ul,{keyCode:"tab"},"tabHint")})),Hh(w,x)},[o,n,r]),m=(0,er.useMemo)(()=>{let w=[];return c&&w.push(new tf("selection")),w.push(new Zd("placeholders")),i&&w.push(new Xd("keywords")),w},[d,c,i]),h=(0,er.useMemo)(()=>{let w=window.getComputedStyle(a);return{"--dd-color":w.color,"--dd-font-size":w.fontSize,"--dd-font-family":w.fontFamily,"--dd-font-variant":w.fontVariant}},[]);return!e||!v?null:(0,Jn.jsxs)("div",{ref:w=>{w!=null&&w.parentElement&&(y.current=w==null?void 0:w.parentElement)},className:u.root,style:h,children:[(0,Jn.jsx)(Gi,{tagName:"span",containerTagName:"div",className:(0,nf.default)(u.container,u.agentText),disableLineBreaks:Wr(a),content:t||"\u200B",onAfterParse:f,matchers:m,selection:g,keywordMatches:s,inputElement:a,inputStyle:h,boundaryRef:y,inlineSuggestionsOnlyAtEnd:!p}),(0,Jn.jsx)("br",{})]})},eM=({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}},fb=jn(eM)(JO);var bT=S(ee()),ff=S(_());var pb={list:[],fetchState:"idle"},gb=e=>e.autoflows.list||[],mb=e=>t=>{var n;return(n=t.list)==null?void 0:n.find(r=>r.triggerPayload===e)},tr=U("autoflows/getAll",async(e,t)=>{let{deepdeskBrokerAPI:n}=t.extra;if(!n)throw new Error("Deepdesk Broker not initialized");return n.getAutoflows(e)}),Gh=U("autoflows/start",async(e,t)=>{let{dispatch:n}=t,{deepdeskBrokerAPI:r}=t.extra;if(!r)throw new Error("Deepdesk Broker not initialized");await r.startAutoflowSession(e),await n(tr(e.platformSessionId))}),qh=U("autoflows/stop",async(e,t)=>{let{dispatch:n}=t,{deepdeskBrokerAPI:r}=t.extra;if(!r)throw new Error("Deepdesk Broker not initialized");await r.stopAutoflowSession(e.platformSessionId),await n(tr(e.platformSessionId))}),tM=q({name:"autoflows",initialState:pb,reducers:{},extraReducers:e=>{e.addCase(Gh.pending,(t,n)=>{let r=mb(n.meta.arg.triggerPayload)(t);r.state="Started",r.isBusy=!0}),e.addCase(qh.pending,(t,n)=>{let r=mb(n.meta.arg.triggerPayload)(t);r.state="Aborted",r.isBusy=!0}),e.addCase(tr.pending,t=>{t.fetchState="loading"}),e.addCase(tr.rejected,t=>{t.fetchState="error"}),e.addCase(tr.fulfilled,(t,n)=>{t.list=n.payload,t.fetchState="done"}),e.addCase(le,()=>pb)}}),hb=U("autoflows/openStream",(e,t)=>{let{dispatch:n}=t,{deepdeskBrokerAPI:r}=t.extra;if(!r)throw new Error("Deepdesk Broker not initialized");let o=r.openStream(e);o.on("sessionAborted",()=>{n(tr(e))}),o.on("sessionCompleted",()=>{n(tr(e))})}),yb=U("autoflows/closeStream",(e,t)=>{let{deepdeskBrokerAPI:n}=t.extra;if(!n)throw new Error("Deepdesk Broker not initialized");n.closeStream(e)}),vb=tM.reducer;var Sb={list:[],fetchState:"idle",sentSuggestions:[],errorSuggestions:[],answeredSuggestions:[]},wb=e=>e.customMessages.list,xb=e=>t=>!!t.customMessages.sentSuggestions.find(n=>n===e),Eb=e=>t=>!!t.customMessages.answeredSuggestions.find(n=>n===e),Cb=e=>t=>!!t.customMessages.errorSuggestions.find(n=>n===e),il=U("customMessages/getAll",async(e,t)=>{let{deepdeskBrokerAPI:n}=t.extra;if(!n)throw new Error("Deepdesk Broker not initialized");return n.getCustomMessages(e)}),rf=U("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)}),of=U("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)}),bb=q({name:"customMessages",initialState:Sb,reducers:{onCustomMessage(e,t){Array.isArray(t.payload)?e.list=t.payload:e.list=[t.payload]}},extraReducers:e=>{e.addCase(il.pending,t=>{t.fetchState="loading"}).addCase(il.rejected,t=>{t.fetchState="error"}).addCase(il.fulfilled,(t,n)=>{t.fetchState="done",t.list=n.payload||[]}).addCase(rf.pending,(t,n)=>{t.sentSuggestions.push(n.meta.arg.suggestion.text),t.errorSuggestions=t.errorSuggestions.filter(r=>n.meta.arg.suggestion.text!==r)}).addCase(rf.rejected,(t,n)=>{let r=t.sentSuggestions.indexOf(n.meta.arg.suggestion.text);t.errorSuggestions.push(...t.sentSuggestions.splice(r,1))}).addCase(of.pending,(t,n)=>{t.sentSuggestions.push(n.meta.arg.suggestion.text),t.answeredSuggestions.push(n.meta.arg.suggestion.text)}).addCase(of.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,()=>Sb)}}),Tb=U("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(bb.actions.onCustomMessage(i))})}),kb=U("customMessages/closeStream",(e,t)=>{let{deepdeskBrokerAPI:n}=t.extra;if(!n)throw new Error("Deepdesk Broker not initialized");n.closeStream(e)}),Pb=bb.reducer;var nM={token:null,accountUrl:null,interval:null},Rb=e=>t=>{let{passwordlessToken:{token:n,accountUrl:r}}=t;return n&&r?`${r}/apis/admin/session/passwordless/login/?token=${n}&redirect=${e}`:null},Yh=U("passwordlessToken/getTemporaryPasswordlessToken",async(e,t)=>{let{deepdeskAPI:n}=t.extra,r=await n.requestPasswordlessToken();return{accountUrl:n.client.baseUrl,token:r}}),Xh=U("passwordlessToken/pollPasswordlessToken",(e={},t)=>{let{interval:n=1e3*60*10}=e,{dispatch:r}=t;return r(Yh()),setInterval(()=>r(Yh()),n)}),Ab=q({name:"passwordlessToken",initialState:nM,reducers:{stopPollPasswordlessToken(e){e.interval&&clearInterval(e.interval),e.interval=null}},extraReducers:e=>{e.addCase(Yh.fulfilled,(t,n)=>{t.token=n.payload.token,t.accountUrl=n.payload.accountUrl}),e.addCase(Xh.fulfilled,(t,n)=>{t.interval=n.payload})}}),{stopPollPasswordlessToken:Lb}=Ab.actions,Ib=Ab.reducer;var Qh={cues:[],fetchState:"idle"},Nb=e=>{var t;return(t=e.rules)==null?void 0:t.cues},rM=we("rules/resetCues"),jo=U("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 j.info(o.message),[]}}),Ob=q({name:"answer",initialState:Qh,reducers:{removeCue(e,t){e.cues=e.cues.filter(n=>n.rule.id!==t.payload.id)}},extraReducers:e=>{e.addCase(jo.pending,t=>{t.fetchState="loading"}).addCase(jo.rejected,t=>{t.fetchState="error"}).addCase(jo.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,()=>Qh).addCase(rM.toString(),()=>Qh)}}),{removeCue:Mb}=Ob.actions,_b=Ob.reducer;var Kb=S(_());var jb=S(ee()),zb=S(_());var Fb=S(ee());var Db={root:"Ji"};var Ub=S(b()),iM=({className:e,children:t})=>{let n=P("Unicode",Db);return(0,Ub.jsx)("span",{className:(0,Fb.default)(e,n.root),children:t})},Hb=iM;var Bb={isDisabled:"Ki",buttonStart:"Pi",root:"Qi",buttonStop:"uo",stateBadge:"h",isCompleted:"Vi",isStarted:"Wi",isAborted:"Zi"};var Zh={};ze(Zh,{enUS:()=>aM,nlNL:()=>lM});var aM={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"}]},lM={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()),cM=({disabled:e,state:t,displayName:n,description:r,onStartAutoflow:o,onStopAutoflow:i})=>{let s=P("Autoflow",Bb),a=W(Zh),l=t==="Started"?"stop":"start",u=l==="start"?"\u25B6":l==="stop"?"\u25FC":"";return(0,bt.jsxs)(te,{className:(0,jb.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)(te.Actions,{fixed:t==="Started",children:(0,bt.jsx)(te.ActionButton,{primary:!0,className:l==="start"?s.buttonStart:s.buttonStop,onClick:t==="Started"?i:o,disabled:e,label:(0,bt.jsxs)(zb.Fragment,{children:[(0,bt.jsx)(Hb,{children:u})," ",(0,bt.jsx)("span",{children:a(l)})]})})})]})},Vb=cM;var Jh=S(b()),dM=(e,t)=>{let n=t.filter(r=>r.state==="Started");return n.length>0?n.indexOf(e)===-1:!1},fM=({autoflows:e,onStartAutoflow:t,onStopAutoflow:n,platformSessionId:r})=>(0,Jh.jsx)(Kb.Fragment,{children:e.map(o=>(0,Jh.jsx)(Vb,{displayName:o.displayName,description:o.description,disabled:o.isBusy||dM(o,e),state:o.state,onStartAutoflow:()=>t({platformSessionId:r,triggerPayload:o.triggerPayload}),onStopAutoflow:()=>n({platformSessionId:r,triggerPayload:o.triggerPayload})},o.displayName))}),pM=({autoflows:e,conversation:t})=>{var n;return{autoflows:e.list,platformSessionId:(n=t.current)==null?void 0:n.sessionId}},mM={onStartAutoflow:Gh,onStopAutoflow:qh},Wb=jn(pM,mM)(fM);var $b=S(ee()),ey=S(_());var nr={root:"yo",title:"wo",isUsed:"_i",quickReplies:"or",quickReply:"er",hasError:"ir",label:"rr",errorIcon:"tr"};var gt=S(b()),hM=({suggestion:e})=>{let t=W(Oo),n=Y(),r=N(xb(e.text)),o=N(Eb(e.text)),i=N(Cb(e.text)),s=N(Vi),{replyOptions:a}=e,l=(0,ey.useCallback)(c=>{c.preventDefault(),c.stopPropagation(),!(r||!s)&&n(rf({platformSessionId:s,suggestion:e}))},[e,r,n,s]),u=(0,ey.useCallback)(c=>{if(c.preventDefault(),c.stopPropagation(),!s||!a)return;let p=parseInt(c.target.dataset.index,10),d=a[p];n(of({platformSessionId:s,reply:d,suggestion:e}))},[e,r,n,s]);return(0,gt.jsxs)(te,{onClick:l,className:(0,$b.default)(nr.root,{[nr.isUsed]:r,[nr.hasError]:i}),children:[(0,gt.jsx)(fe,{children:(0,gt.jsxs)(fe.Content,{children:[(0,gt.jsxs)(fe.Title,{className:nr.title,children:[e.text," ",(0,gt.jsx)(Bl,{className:nr.label,children:"analyse tool"})," ",i&&(0,gt.jsx)("span",{className:nr.errorIcon,role:"img","aria-label":t("sendingError"),title:t("sendingError"),children:"!"})]}),a&&a.length>0&&(0,gt.jsx)("ul",{className:nr.quickReplies,children:a.map(c=>(0,gt.jsx)("li",{className:nr.quickReply,children:c.title},c.title))})]})}),(0,gt.jsxs)(te.Actions,{fixed:i||r,children:[a&&a.length>0&&(0,gt.jsx)(te.DropdownButton,{label:t("answer"),disabled:o,children:a.map((c,p)=>(0,gt.jsx)(te.DropdownItem,{index:p,label:c.title,onClick:u},c.title))}),(0,gt.jsx)(te.ActionButton,{primary:!0,disabled:r,onClick:l,label:t(r?"suggestionSent":i?"tryAgain":"sendSuggestion")})]})]})},Gb=hM;var sf=S(_());var ry=S(ee());var ty=S(b()),ny=()=>(0,ty.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 512 512",xmlns:"http://www.w3.org/2000/svg",children:(0,ty.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 qb={root:"nr",entity:"r",entityText:"ar",iconWrapper:"pr",icon:"dr",iconClicked:"lr"};var Tn=S(b()),vM=({entities:e})=>{let t=P("EntitiesWidgetList",qb),[n,r]=(0,sf.useState)(void 0),o=Y(),i=()=>{r(void 0)},s=a=>{e&&(r(e.indexOf(a)),ko(a.text),o(Xe({name:"entity copied",data:{entity:a,type:"copy"}})))};return(0,sf.useEffect)(()=>{let a=setTimeout(i,500);return()=>{clearTimeout(a)}},[n]),!e||e.length===0?null:(0,Tn.jsx)("div",{className:t.root,"data-testid":"widget-entities-list",children:e.map((a,l)=>(0,Tn.jsxs)("button",{title:a.text,className:t.entity,type:"button",onClick:()=>s(a),children:[(0,Tn.jsx)("span",{className:t.entityText,children:a.text}),(0,Tn.jsxs)("span",{className:t.iconWrapper,children:[(0,Tn.jsx)("span",{className:(0,ry.default)(t.icon),children:(0,Tn.jsx)(ny,{})}),(0,Tn.jsx)("span",{className:(0,ry.default)(t.icon,n===l&&t.iconClicked),children:(0,Tn.jsx)(ny,{})})]})]},a.text))})},Yb=vM;var oy=S(b()),Xb=()=>(0,oy.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:(0,oy.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 iy=S(b()),Qb=()=>(0,iy.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:(0,iy.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 sy=S(b()),Zb=()=>(0,sy.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:(0,sy.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 hy=S(ee()),df=S(_());var sl=S(b()),Jb=({className:e})=>(0,sl.jsxs)("svg",{viewBox:"0 0 12 12",version:"1.1",xmlns:"http://www.w3.org/2000/svg",className:e,children:[(0,sl.jsx)("line",{x1:"2",y1:"10",x2:"10",y2:"2",stroke:"black",strokeWidth:"1"}),(0,sl.jsx)("line",{x1:"2",y1:"2",x2:"10",y2:"10",stroke:"black",strokeWidth:"1"})]});var{entries:aT,setPrototypeOf:eT,isFrozen:SM,getPrototypeOf:wM,getOwnPropertyDescriptor:xM}=Object,{freeze:it,seal:dn,create:lT}=Object,{apply:fy,construct:py}=typeof Reflect<"u"&&Reflect;it||(it=function(t){return t});dn||(dn=function(t){return t});fy||(fy=function(t,n,r){return t.apply(n,r)});py||(py=function(t,n){return new t(...n)});var af=kt(Array.prototype.forEach),tT=kt(Array.prototype.pop),al=kt(Array.prototype.push),cf=kt(String.prototype.toLowerCase),ay=kt(String.prototype.toString),EM=kt(String.prototype.match),ll=kt(String.prototype.replace),CM=kt(String.prototype.indexOf),bM=kt(String.prototype.trim),cn=kt(Object.prototype.hasOwnProperty),Tt=kt(RegExp.prototype.test),ul=TM(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 fy(e,t,r)}}function TM(e){return function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];return py(e,n)}}function Q(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:cf;eT&&eT(e,null);let r=t.length;for(;r--;){let o=t[r];if(typeof o=="string"){let i=n(o);i!==o&&(SM(t)||(t[r]=i),o=i)}e[o]=!0}return e}function kM(e){for(let t=0;t<e.length;t++)cn(e,t)||(e[t]=null);return e}function zo(e){let t=lT(null);for(let[n,r]of aT(e))cn(e,n)&&(Array.isArray(r)?t[n]=kM(r):r&&typeof r=="object"&&r.constructor===Object?t[n]=zo(r):t[n]=r);return t}function lf(e,t){for(;e!==null;){let r=xM(e,t);if(r){if(r.get)return kt(r.get);if(typeof r.value=="function")return kt(r.value)}e=wM(e)}function n(){return null}return n}var nT=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"]),ly=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"]),uy=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"]),PM=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"]),cy=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"]),RM=it(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),rT=it(["#text"]),oT=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"]),dy=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"]),iT=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"]),uf=it(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),AM=dn(/\{\{[\w\W]*|[\w\W]*\}\}/gm),LM=dn(/<%[\w\W]*|[\w\W]*%>/gm),IM=dn(/\${[\w\W]*}/gm),NM=dn(/^data-[\-\w.\u00B7-\uFFFF]/),OM=dn(/^aria-[\-\w]+$/),uT=dn(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),MM=dn(/^(?:\w+script|data):/i),_M=dn(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),cT=dn(/^html$/i),sT=Object.freeze({__proto__:null,MUSTACHE_EXPR:AM,ERB_EXPR:LM,TMPLIT_EXPR:IM,DATA_ATTR:NM,ARIA_ATTR:OM,IS_ALLOWED_URI:uT,IS_SCRIPT_OR_DATA:MM,ATTR_WHITESPACE:_M,DOCTYPE_NAME:cT}),DM=function(){return typeof window>"u"?null:window},FM=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 dT(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:DM(),t=H=>dT(H);if(t.version="3.0.9",t.removed=[],!e||!e.document||e.document.nodeType!==9)return t.isSupported=!1,t;let{document:n}=e,r=n,o=r.currentScript,{DocumentFragment:i,HTMLTemplateElement:s,Node:a,Element:l,NodeFilter:u,NamedNodeMap:c=e.NamedNodeMap||e.MozNamedAttrMap,HTMLFormElement:p,DOMParser:d,trustedTypes:g}=e,y=l.prototype,v=lf(y,"cloneNode"),f=lf(y,"nextSibling"),m=lf(y,"childNodes"),h=lf(y,"parentNode");if(typeof s=="function"){let H=n.createElement("template");H.content&&H.content.ownerDocument&&(n=H.content.ownerDocument)}let w,x="",{implementation:T,createNodeIterator:C,createDocumentFragment:k,getElementsByTagName:L}=n,{importNode:I}=r,O={};t.isSupported=typeof aT=="function"&&typeof h=="function"&&T&&T.createHTMLDocument!==void 0;let{MUSTACHE_EXPR:V,ERB_EXPR:K,TMPLIT_EXPR:se,DATA_ATTR:ps,ARIA_ATTR:Rt,IS_SCRIPT_OR_DATA:sr,ATTR_WHITESPACE:At}=sT,{IS_ALLOWED_URI:F}=sT,X=null,ar=Q({},[...nT,...ly,...uy,...cy,...rT]),he=null,lr=Q({},[...oT,...dy,...iT,...uf]),G=Object.seal(lT(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),ur=null,Cl=null,$o=!0,Xr=!0,ms=!1,bl=!0,qt=!1,Yt=!1,Tl=!1,st=!1,Lt=!1,kl=!1,Pl=!1,Ay=!0,Ly=!1,pk="user-content-",Cf=!0,gs=!1,Go={},qo=null,Iy=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"]),Ny=null,Oy=Q({},["audio","video","img","source","image","track"]),bf=null,My=Q({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Rl="http://www.w3.org/1998/Math/MathML",Al="http://www.w3.org/2000/svg",Rn="http://www.w3.org/1999/xhtml",Yo=Rn,Tf=!1,kf=null,mk=Q({},[Rl,Al,Rn],ay),hs=null,gk=["application/xhtml+xml","text/html"],hk="text/html",Ie=null,Xo=null,yk=n.createElement("form"),_y=function(E){return E instanceof RegExp||E instanceof Function},Pf=function(){let E=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(Xo&&Xo===E)){if((!E||typeof E!="object")&&(E={}),E=zo(E),hs=gk.indexOf(E.PARSER_MEDIA_TYPE)===-1?hk:E.PARSER_MEDIA_TYPE,Ie=hs==="application/xhtml+xml"?ay:cf,X=cn(E,"ALLOWED_TAGS")?Q({},E.ALLOWED_TAGS,Ie):ar,he=cn(E,"ALLOWED_ATTR")?Q({},E.ALLOWED_ATTR,Ie):lr,kf=cn(E,"ALLOWED_NAMESPACES")?Q({},E.ALLOWED_NAMESPACES,ay):mk,bf=cn(E,"ADD_URI_SAFE_ATTR")?Q(zo(My),E.ADD_URI_SAFE_ATTR,Ie):My,Ny=cn(E,"ADD_DATA_URI_TAGS")?Q(zo(Oy),E.ADD_DATA_URI_TAGS,Ie):Oy,qo=cn(E,"FORBID_CONTENTS")?Q({},E.FORBID_CONTENTS,Ie):Iy,ur=cn(E,"FORBID_TAGS")?Q({},E.FORBID_TAGS,Ie):{},Cl=cn(E,"FORBID_ATTR")?Q({},E.FORBID_ATTR,Ie):{},Go=cn(E,"USE_PROFILES")?E.USE_PROFILES:!1,$o=E.ALLOW_ARIA_ATTR!==!1,Xr=E.ALLOW_DATA_ATTR!==!1,ms=E.ALLOW_UNKNOWN_PROTOCOLS||!1,bl=E.ALLOW_SELF_CLOSE_IN_ATTR!==!1,qt=E.SAFE_FOR_TEMPLATES||!1,Yt=E.WHOLE_DOCUMENT||!1,Lt=E.RETURN_DOM||!1,kl=E.RETURN_DOM_FRAGMENT||!1,Pl=E.RETURN_TRUSTED_TYPE||!1,st=E.FORCE_BODY||!1,Ay=E.SANITIZE_DOM!==!1,Ly=E.SANITIZE_NAMED_PROPS||!1,Cf=E.KEEP_CONTENT!==!1,gs=E.IN_PLACE||!1,F=E.ALLOWED_URI_REGEXP||uT,Yo=E.NAMESPACE||Rn,G=E.CUSTOM_ELEMENT_HANDLING||{},E.CUSTOM_ELEMENT_HANDLING&&_y(E.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(G.tagNameCheck=E.CUSTOM_ELEMENT_HANDLING.tagNameCheck),E.CUSTOM_ELEMENT_HANDLING&&_y(E.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(G.attributeNameCheck=E.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),E.CUSTOM_ELEMENT_HANDLING&&typeof E.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(G.allowCustomizedBuiltInElements=E.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),qt&&(Xr=!1),kl&&(Lt=!0),Go&&(X=Q({},rT),he=[],Go.html===!0&&(Q(X,nT),Q(he,oT)),Go.svg===!0&&(Q(X,ly),Q(he,dy),Q(he,uf)),Go.svgFilters===!0&&(Q(X,uy),Q(he,dy),Q(he,uf)),Go.mathMl===!0&&(Q(X,cy),Q(he,iT),Q(he,uf))),E.ADD_TAGS&&(X===ar&&(X=zo(X)),Q(X,E.ADD_TAGS,Ie)),E.ADD_ATTR&&(he===lr&&(he=zo(he)),Q(he,E.ADD_ATTR,Ie)),E.ADD_URI_SAFE_ATTR&&Q(bf,E.ADD_URI_SAFE_ATTR,Ie),E.FORBID_CONTENTS&&(qo===Iy&&(qo=zo(qo)),Q(qo,E.FORBID_CONTENTS,Ie)),Cf&&(X["#text"]=!0),Yt&&Q(X,["html","head","body"]),X.table&&(Q(X,["tbody"]),delete ur.tbody),E.TRUSTED_TYPES_POLICY){if(typeof E.TRUSTED_TYPES_POLICY.createHTML!="function")throw ul('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof E.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw ul('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');w=E.TRUSTED_TYPES_POLICY,x=w.createHTML("")}else w===void 0&&(w=FM(g,o)),w!==null&&typeof x=="string"&&(x=w.createHTML(""));it&&it(E),Xo=E}},Dy=Q({},["mi","mo","mn","ms","mtext"]),Fy=Q({},["foreignobject","desc","title","annotation-xml"]),vk=Q({},["title","style","font","a","script"]),Hy=Q({},[...ly,...uy,...PM]),Uy=Q({},[...cy,...RM]),Sk=function(E){let A=h(E);(!A||!A.tagName)&&(A={namespaceURI:Yo,tagName:"template"});let D=cf(E.tagName),ce=cf(A.tagName);return kf[E.namespaceURI]?E.namespaceURI===Al?A.namespaceURI===Rn?D==="svg":A.namespaceURI===Rl?D==="svg"&&(ce==="annotation-xml"||Dy[ce]):!!Hy[D]:E.namespaceURI===Rl?A.namespaceURI===Rn?D==="math":A.namespaceURI===Al?D==="math"&&Fy[ce]:!!Uy[D]:E.namespaceURI===Rn?A.namespaceURI===Al&&!Fy[ce]||A.namespaceURI===Rl&&!Dy[ce]?!1:!Uy[D]&&(vk[D]||!Hy[D]):!!(hs==="application/xhtml+xml"&&kf[E.namespaceURI]):!1},Qr=function(E){al(t.removed,{element:E});try{E.parentNode.removeChild(E)}catch{E.remove()}},Rf=function(E,A){try{al(t.removed,{attribute:A.getAttributeNode(E),from:A})}catch{al(t.removed,{attribute:null,from:A})}if(A.removeAttribute(E),E==="is"&&!he[E])if(Lt||kl)try{Qr(A)}catch{}else try{A.setAttribute(E,"")}catch{}},By=function(E){let A=null,D=null;if(st)E="<remove></remove>"+E;else{let je=EM(E,/^[\r\n\t ]+/);D=je&&je[0]}hs==="application/xhtml+xml"&&Yo===Rn&&(E='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+E+"</body></html>");let ce=w?w.createHTML(E):E;if(Yo===Rn)try{A=new d().parseFromString(ce,hs)}catch{}if(!A||!A.documentElement){A=T.createDocument(Yo,"template",null);try{A.documentElement.innerHTML=Tf?x:ce}catch{}}let Be=A.body||A.documentElement;return E&&D&&Be.insertBefore(n.createTextNode(D),Be.childNodes[0]||null),Yo===Rn?L.call(A,Yt?"html":"body")[0]:Yt?A.documentElement:Be},jy=function(E){return C.call(E.ownerDocument||E,E,u.SHOW_ELEMENT|u.SHOW_COMMENT|u.SHOW_TEXT,null)},wk=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")},zy=function(E){return typeof a=="function"&&E instanceof a},An=function(E,A,D){O[E]&&af(O[E],ce=>{ce.call(t,A,D,Xo)})},Vy=function(E){let A=null;if(An("beforeSanitizeElements",E,null),wk(E))return Qr(E),!0;let D=Ie(E.nodeName);if(An("uponSanitizeElement",E,{tagName:D,allowedTags:X}),E.hasChildNodes()&&!zy(E.firstElementChild)&&Tt(/<[/\w]/g,E.innerHTML)&&Tt(/<[/\w]/g,E.textContent))return Qr(E),!0;if(!X[D]||ur[D]){if(!ur[D]&&Wy(D)&&(G.tagNameCheck instanceof RegExp&&Tt(G.tagNameCheck,D)||G.tagNameCheck instanceof Function&&G.tagNameCheck(D)))return!1;if(Cf&&!qo[D]){let ce=h(E)||E.parentNode,Be=m(E)||E.childNodes;if(Be&&ce){let je=Be.length;for(let at=je-1;at>=0;--at)ce.insertBefore(v(Be[at],!0),f(E))}}return Qr(E),!0}return E instanceof l&&!Sk(E)||(D==="noscript"||D==="noembed"||D==="noframes")&&Tt(/<\/no(script|embed|frames)/i,E.innerHTML)?(Qr(E),!0):(qt&&E.nodeType===3&&(A=E.textContent,af([V,K,se],ce=>{A=ll(A,ce," ")}),E.textContent!==A&&(al(t.removed,{element:E.cloneNode()}),E.textContent=A)),An("afterSanitizeElements",E,null),!1)},Ky=function(E,A,D){if(Ay&&(A==="id"||A==="name")&&(D in n||D in yk))return!1;if(!(Xr&&!Cl[A]&&Tt(ps,A))){if(!($o&&Tt(Rt,A))){if(!he[A]||Cl[A]){if(!(Wy(E)&&(G.tagNameCheck instanceof RegExp&&Tt(G.tagNameCheck,E)||G.tagNameCheck instanceof Function&&G.tagNameCheck(E))&&(G.attributeNameCheck instanceof RegExp&&Tt(G.attributeNameCheck,A)||G.attributeNameCheck instanceof Function&&G.attributeNameCheck(A))||A==="is"&&G.allowCustomizedBuiltInElements&&(G.tagNameCheck instanceof RegExp&&Tt(G.tagNameCheck,D)||G.tagNameCheck instanceof Function&&G.tagNameCheck(D))))return!1}else if(!bf[A]){if(!Tt(F,ll(D,At,""))){if(!((A==="src"||A==="xlink:href"||A==="href")&&E!=="script"&&CM(D,"data:")===0&&Ny[E])){if(!(ms&&!Tt(sr,ll(D,At,"")))){if(D)return!1}}}}}}return!0},Wy=function(E){return E!=="annotation-xml"&&E.indexOf("-")>0},$y=function(E){An("beforeSanitizeAttributes",E,null);let{attributes:A}=E;if(!A)return;let D={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:he},ce=A.length;for(;ce--;){let Be=A[ce],{name:je,namespaceURI:at,value:Zr}=Be,ys=Ie(je),lt=je==="value"?Zr:bM(Zr);if(D.attrName=ys,D.attrValue=lt,D.keepAttr=!0,D.forceKeepAttr=void 0,An("uponSanitizeAttribute",E,D),lt=D.attrValue,D.forceKeepAttr||(Rf(je,E),!D.keepAttr))continue;if(!bl&&Tt(/\/>/i,lt)){Rf(je,E);continue}qt&&af([V,K,se],qy=>{lt=ll(lt,qy," ")});let Gy=Ie(E.nodeName);if(Ky(Gy,ys,lt)){if(Ly&&(ys==="id"||ys==="name")&&(Rf(je,E),lt=pk+lt),w&&typeof g=="object"&&typeof g.getAttributeType=="function"&&!at)switch(g.getAttributeType(Gy,ys)){case"TrustedHTML":{lt=w.createHTML(lt);break}case"TrustedScriptURL":{lt=w.createScriptURL(lt);break}}try{at?E.setAttributeNS(at,je,lt):E.setAttribute(je,lt),tT(t.removed)}catch{}}}An("afterSanitizeAttributes",E,null)},xk=function H(E){let A=null,D=jy(E);for(An("beforeSanitizeShadowDOM",E,null);A=D.nextNode();)An("uponSanitizeShadowNode",A,null),!Vy(A)&&(A.content instanceof i&&H(A.content),$y(A));An("afterSanitizeShadowDOM",E,null)};return t.sanitize=function(H){let E=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},A=null,D=null,ce=null,Be=null;if(Tf=!H,Tf&&(H="<!-->"),typeof H!="string"&&!zy(H))if(typeof H.toString=="function"){if(H=H.toString(),typeof H!="string")throw ul("dirty is not a string, aborting")}else throw ul("toString is not a function");if(!t.isSupported)return H;if(Tl||Pf(E),t.removed=[],typeof H=="string"&&(gs=!1),gs){if(H.nodeName){let Zr=Ie(H.nodeName);if(!X[Zr]||ur[Zr])throw ul("root node is forbidden and cannot be sanitized in-place")}}else if(H instanceof a)A=By("<!---->"),D=A.ownerDocument.importNode(H,!0),D.nodeType===1&&D.nodeName==="BODY"||D.nodeName==="HTML"?A=D:A.appendChild(D);else{if(!Lt&&!qt&&!Yt&&H.indexOf("<")===-1)return w&&Pl?w.createHTML(H):H;if(A=By(H),!A)return Lt?null:Pl?x:""}A&&st&&Qr(A.firstChild);let je=jy(gs?H:A);for(;ce=je.nextNode();)Vy(ce)||(ce.content instanceof i&&xk(ce.content),$y(ce));if(gs)return H;if(Lt){if(kl)for(Be=k.call(A.ownerDocument);A.firstChild;)Be.appendChild(A.firstChild);else Be=A;return(he.shadowroot||he.shadowrootmode)&&(Be=I.call(r,Be,!0)),Be}let at=Yt?A.outerHTML:A.innerHTML;return Yt&&X["!doctype"]&&A.ownerDocument&&A.ownerDocument.doctype&&A.ownerDocument.doctype.name&&Tt(cT,A.ownerDocument.doctype.name)&&(at="<!DOCTYPE "+A.ownerDocument.doctype.name+`>
|
|
24
24
|
`+at),qt&&af([V,K,se],Zr=>{at=ll(at,Zr," ")}),w&&Pl?w.createHTML(at):at},t.setConfig=function(){let H=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Pf(H),Tl=!0},t.clearConfig=function(){Xo=null,Tl=!1},t.isValidAttribute=function(H,E,A){Xo||Pf({});let D=Ie(H),ce=Ie(E);return Ky(D,ce,A)},t.addHook=function(H,E){typeof E=="function"&&(O[H]=O[H]||[],al(O[H],E))},t.removeHook=function(H){if(O[H])return tT(O[H])},t.removeHooks=function(H){O[H]&&(O[H]=[])},t.removeAllHooks=function(){O={}},t}var fT=dT();var qr=S(_());var HM={"":["<em>","</em>"],_:["<strong>","</strong>"],"*":["<strong>","</strong>"],"~":["<s>","</s>"],"\n":["<br />"]," ":["<br />"],"-":["<hr />"]};function pT(e){return e.replace(RegExp("^"+(e.match(/^(\t| )+/)||"")[0],"gm"),"")}function cl(e){return(e+"").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function dl(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=HM[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()+'"':"")+">"+pT(cl(s).replace(/^\n+|\n+$/g,""))+"</code></pre>":(s=o[6])?(s.match(/\./)&&(o[5]=o[5].replace(/^\d+/gm,"")),i=dl(pT(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="'+cl(o[8])+'" alt="'+cl(o[7])+'">':o[10]?(u=u.replace("<a>",'<a href="'+cl(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))+">"+dl(o[12]||o[15],c)+"</"+s+">":o[16]?n="<code>"+cl(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 mT={fadeup:"N",root:"i",popover:"sr",options:"vo",copyIcon:"A",option:"ko",divider:"cr"};var rr=S(b());function BM(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 my(e){let t=e.cloneNode(!0);return t.querySelectorAll("div,button").forEach(n=>n.remove()),t.textContent??""}function jM(e){return e.replace(/\r\n/g,`
|
|
25
|
-
`)}var zM=({content:e,useLabel:t,copyLabel:n,onCopy:r,onUse:o})=>{let i=P("Markdown",mT),s=(0,qr.useRef)(null),[a,l]=(0,qr.useState)(null),u=(0,qr.useMemo)(()=>{let y=dl(jM(e));return fT.sanitize(y).replace(/<\/code>/g,`${BM(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&&(Yn(y,i.fadeup),r(my(a)))},d=y=>{y.target.tagName.toLowerCase()==="button"&&(Yn(y.target,i.fadeup),r(my(y.target.parentElement)))},g=()=>{a&&(l(null),o(my(a)))};return(0,rr.jsxs)(qr.Fragment,{children:[a&&(0,rr.jsx)(ls,{triggerRef:{current:a},parentNode:a,className:i.popover,children:(0,rr.jsxs)("div",{className:i.options,children:[(0,rr.jsx)("button",{type:"button",className:i.option,onClick:p,children:n}),(0,rr.jsx)("div",{className:i.divider}),(0,rr.jsx)("button",{type:"button",className:i.option,onClick:g,children:t})]})}),(0,rr.jsx)("div",{ref:s,className:i.root,dangerouslySetInnerHTML:{__html:u},onMouseOver:c,onClick:d})]})},gT=zM;var gy={};ze(gy,{enUS:()=>VM,nlNL:()=>KM});var VM={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"}]},KM={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 hT={fadeup:"F",fadedown:"H",selected:"zo",thumbsUp:"xr",thumbsDown:"fr"};var Pt=S(b()),$M=({cue:e,onRemove:t,onCopy:n,onUse:r,onThumbsUp:o,onThumbsDown:i})=>{let s=P("WidgetCue",hT),a=W(gy),l=Zi(),[u,c]=(0,df.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(),Yn(f.target,s.fadeup),c("up"),o(e)},v=f=>{f.preventDefault(),f.stopPropagation(),Yn(f.target,s.fadedown),c("down"),i(e)};return(0,df.useEffect)(()=>{l("Assistant response displayed",{name:e.rule.name,description:e.rule.description,group:e.rule.label})},[]),(0,Pt.jsxs)(te,{"data-testid":"cue",children:[(0,Pt.jsx)(fe,{children:(0,Pt.jsxs)(fe.Content,{children:[e.title&&(0,Pt.jsx)(fe.Title,{"data-testid":"widget-cue-title",children:e.title}),(0,Pt.jsx)(gT,{content:e.text,useLabel:a("useCue"),copyLabel:a("copyCue"),onCopy:p,onUse:d})]})}),(0,Pt.jsx)(te.IconButton,{title:a("thumbsUp"),onClick:y,icon:(0,Pt.jsx)(Ld,{}),className:(0,hy.default)(s.thumbsUp,u==="up"&&s.selected),disabled:!!u}),(0,Pt.jsx)(te.IconButton,{title:a("thumbsDown"),onClick:v,icon:(0,Pt.jsx)(Ad,{}),className:(0,hy.default)(s.thumbsDown,u==="down"&&s.selected),disabled:!!u}),(0,Pt.jsx)(te.IconButton,{title:a("removeCue"),onClick:g,icon:(0,Pt.jsx)(Jb,{})})]})},yT=$M;var fl=S(b()),GM=({cues:e})=>{let t=Y(),n=zt(),r=Zi(),o=u=>{t(Mb({id:u.rule.id})),r("Assistant response closed",{name:u.rule.name,group:u.rule.label,description:u.rule.description})},i=(u,c)=>{ko(u),r("Assistant response copied",{name:c.rule.name,group:c.rule.label,description:c.rule.description,copiedText:u})},s=(u,c)=>{n.send(Hr,{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"})},l=u=>{r("Assistant response feedback",{name:u.rule.name,group:u.rule.label,description:u.rule.description,thumb:"down"})};return(0,fl.jsx)(fl.Fragment,{children:e.map(u=>(0,fl.jsx)(yT,{cue:u,onRemove:o,onCopy:i,onUse:s,onThumbsDown:l,onThumbsUp:a},u.rule.id))})},vT=GM;var wT=S(_());var qM=/(https?:\/\/[^\s]+)/,ST=e=>e.split(" ").find(t=>qM.test(t));var $t=S(b()),YM=({suggestion:e,lines:t,onUse:n})=>{var c;let r=e.text||e.url||e.message,o=ST(r),i=W(Oo),s=B("showImages"),a=B("fallbackImage"),l=p=>{p.preventDefault(),p.stopPropagation(),n(r)},u=(0,wT.useCallback)(p=>{window.open(o,"_blank"),p.stopPropagation(),p.preventDefault()},[o]);return(0,$t.jsxs)(te,{onClick:l,"data-testid":"edit-suggestion",children:[(0,$t.jsxs)(fe,{children:[s&&e.image&&(0,$t.jsx)(fe.Image,{src:Jd(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)(te.Labels,{labels:e.searchKeywords}),(0,$t.jsx)(fe.Content,{cropText:t==="single",lineClamp:t==="multiple",children:r})]})]}),(0,$t.jsxs)(te.Actions,{children:[o&&(0,$t.jsx)(te.ActionButton,{onClick:u,label:i("visitUrl")}),(0,$t.jsx)(te.ActionButton,{primary:!0,onClick:l,label:i("useSuggestion")})]})]})},xT=YM;var pl=S(b()),XM=({lines:e,suggestions:t})=>{let n=zt(),r=(o,i)=>{n.send(Hr,{text:o,suggestion:{...i,source:i.source,sourceText:i.text}})};return(0,pl.jsx)(pl.Fragment,{children:t.map(o=>(0,pl.jsx)(xT,{suggestion:o,lines:e,onUse:i=>r(i,o)},o.text||o.url||o.message))})},ET=XM;var ml={};ze(ml,{enUS:()=>QM,nlNL:()=>ZM});var QM={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"}]},ZM={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 gl={root:"gr",loginText:"br",stateText:"jo",sectionList:"hr",shortcutList:"mr",shortcut:"ur",link:"Yo"};var $=S(b()),pf=(e,t)=>{let n=N(tt);(0,ff.useEffect)(()=>n?t.every(r=>!!r)?e():()=>{}:()=>{},[...t,n])},e2=({onLogIn:e})=>{let t=P("Widget",gl),n=B("isEmbedded"),r=B("adminUrl");return(0,$.jsx)("div",{className:t.loginText,children:(0,$.jsx)("div",{children:(0,$.jsx)(Bd,{isEmbedded:n,loginUrl:r,onLogIn:e})})},"login")},CT=({text:e})=>{let t=P("Widget",gl);return(0,$.jsx)("div",{className:t.stateText,children:(0,$.jsx)("div",{children:(0,$.jsx)("p",{children:e})})},"notification")},t2=()=>{let e=W(ml),t=Y(),n=P("Widget",gl),r=B("showSearch"),o=B("showSummaryCommand"),i=B("showKnowledgeSearch"),s=N(Rb("/admin/")),a=zt(),l=B("productName"),u=r||o||i||s;return pf(()=>(t(Xh()),()=>{t(Lb())}),[t]),u?(0,$.jsx)(In,{title:e("actions"),type:"shortcuts",children:(0,$.jsxs)("div",{className:n.shortcutList,children:[r&&(0,$.jsxs)("button",{className:n.shortcut,"data-testid":"shortcut-search",onClick:()=>a.send("ShowCommandPalette",{isOpen:!0}),children:[(0,$.jsx)(Yi,{}),e("linkSearch")]}),o&&(0,$.jsxs)("button",{className:n.shortcut,"data-testid":"shortcut-summary",onClick:()=>a.send("ShowCommandPalette",{isOpen:!0,page:"summary"}),children:[(0,$.jsx)(Zb,{}),e("linkSummary")]}),i&&(0,$.jsxs)("button",{className:n.shortcut,"data-testid":"shortcut-knowledge-assist",onClick:()=>a.send("ShowCommandPalette",{isOpen:!0,page:"knowledgeAssist"}),children:[(0,$.jsx)(Qb,{}),e("linkKnowledgeSearch")]}),s&&(0,$.jsxs)("a",{className:n.shortcut,target:"_blank",href:s,"data-testid":"shortcut-studio-login",rel:"noreferrer",children:[(0,$.jsx)(Xb,{}),e("linkStudioLogin",{productName:l})]})]})}):null},n2=()=>{let e=Y(),t=B("showCustomMessages"),n=N(wb),r=N(Vi);return pf(()=>(e(il(r)),e(Tb(r)),()=>{e(kb(r))}),[e,t,r]),!t||n.length===0?null:(0,$.jsx)(In,{type:"custom-messages","data-testid":"custom-messages",children:(0,$.jsx)(ht,{withDivider:!0,children:n.map(o=>(0,$.jsx)(Gb,{suggestion:o},o.text))})})},r2=()=>{let e=W(ml),t=Y(),n=B("showAutoflows"),r=N(gb),o=N(Vi);return pf(()=>(t(tr(o)),t(hb(o)),()=>{t(yb(o))}),[t,n,o]),!n||r.length===0?null:(0,$.jsx)(In,{type:"autoflows",title:e("titleAutoflows"),"data-testid":"autoflows",children:(0,$.jsx)(ht,{withDivider:!0,children:(0,$.jsx)(Wb,{})})})},o2=()=>{let e=Y(),t=N(Nd),n=N(Nb),r=N(Rd),o=N(Od),i=N(Xn),s=N(Bc);return pf(()=>{t.forEach(({type:a})=>{a==="entities"?e(sn()):["cues"].includes(a)||e(ln(a))})},[e,s,i]),(0,$.jsx)(ff.Fragment,{children:t.map(({type:a,title:l,amount:u,lines:c})=>{var p,d;switch(a){case"entities":return r&&r.length>0&&(0,$.jsx)(In,{type:a,title:l,"data-testid":`type-${a}`,children:(0,$.jsx)(Yb,{entities:r})},a);case"cues":return n&&n.length>0&&(0,$.jsx)(In,{type:a,title:l,"data-testid":`type-${a}`,children:(0,$.jsx)(ht,{withDivider:!0,children:(0,$.jsx)(vT,{cues:n})})},a);default:return((d=(p=o[a])==null?void 0:p.suggestions)==null?void 0:d.length)>0&&(0,$.jsx)(In,{type:a,title:l,"data-testid":`type-${a}`,children:(0,$.jsx)(ht,{withDivider:!0,children:(0,$.jsx)(ET,{lines:c,contentType:a,suggestions:o[a].suggestions.slice(0,u)||[]})})},a)}})})},i2=({onLogIn:e})=>{let t=W(ml),n=P("Widget",gl),r=N(Ki),o=N(tt),i=N(Vi),s=N(Xn);return r===!1?(0,$.jsx)(CT,{text:t("notSupported")}):o===!1?(0,$.jsx)(e2,{onLogIn:e}):!s||!i||o===null?(0,$.jsx)(CT,{text:t("waiting")}):(0,$.jsx)("div",{className:(0,bT.default)(n.root),"data-testid":"widget",children:(0,$.jsxs)(jl,{className:n.sectionList,children:[(0,$.jsx)(t2,{}),(0,$.jsx)(n2,{}),(0,$.jsx)(r2,{}),(0,$.jsx)(o2,{})]})})},TT=i2;function us(e){let t=new Range;return t.selectNodeContents(e),t}function kT(e,t,n){try{return Yr(e,t,n),!0}catch{return!1}}function mf(e){return"tagName"in e&&(e.tagName==="DIV"||e.tagName==="P")}function gf(e){return"tagName"in e&&e.tagName==="BR"}var hl=/[\u200B-\u200D\uFEFF]/g;function Yr(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(hl,""),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(gf(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;mf(l)&&u&&!mf(u)&&!gf(u)&&o++;break}default:break}}if(a(e),r.startContainer===document)throw new Error("Offsets out of bound");return r}function yl(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(hl,"").length),g&&(l=u+y.substring(0,i).replace(hl,"").length),u+=y.replace(hl,"").length;break}case Node.ELEMENT_NODE:{let y=p.nextSibling===null;gf(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&&mf(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 vl(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(hl,"");d===0&&g===void 0?a+=y:a+=y.substring(d,g);break}case Node.ELEMENT_NODE:{let d=u.nextSibling===null;s===0&&gf(u)&&!d&&(a+=`
|
|
25
|
+
`)}var zM=({content:e,useLabel:t,copyLabel:n,onCopy:r,onUse:o})=>{let i=P("Markdown",mT),s=(0,qr.useRef)(null),[a,l]=(0,qr.useState)(null),u=(0,qr.useMemo)(()=>{let y=dl(jM(e));return fT.sanitize(y).replace(/<\/code>/g,`${BM(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&&(Yn(y,i.fadeup),r(my(a)))},d=y=>{y.target.tagName.toLowerCase()==="button"&&(Yn(y.target,i.fadeup),r(my(y.target.parentElement)))},g=()=>{a&&(l(null),o(my(a)))};return(0,rr.jsxs)(qr.Fragment,{children:[a&&(0,rr.jsx)(ls,{triggerRef:{current:a},parentNode:a,className:i.popover,children:(0,rr.jsxs)("div",{className:i.options,children:[(0,rr.jsx)("button",{type:"button",className:i.option,onClick:p,children:n}),(0,rr.jsx)("div",{className:i.divider}),(0,rr.jsx)("button",{type:"button",className:i.option,onClick:g,children:t})]})}),(0,rr.jsx)("div",{ref:s,className:i.root,dangerouslySetInnerHTML:{__html:u},onMouseOver:c,onClick:d})]})},gT=zM;var gy={};ze(gy,{enUS:()=>VM,nlNL:()=>KM});var VM={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"}]},KM={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 hT={fadeup:"F",fadedown:"H",selected:"zo",thumbsUp:"xr",thumbsDown:"fr"};var Pt=S(b()),$M=({cue:e,onRemove:t,onCopy:n,onUse:r,onThumbsUp:o,onThumbsDown:i})=>{let s=P("WidgetCue",hT),a=W(gy),l=Zi(),[u,c]=(0,df.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(),Yn(f.target,s.fadeup),c("up"),o(e)},v=f=>{f.preventDefault(),f.stopPropagation(),Yn(f.target,s.fadedown),c("down"),i(e)};return(0,df.useEffect)(()=>{l("Assistant response displayed",{name:e.rule.name,description:e.rule.description,group:e.rule.label})},[]),(0,Pt.jsxs)(te,{"data-testid":"cue",children:[(0,Pt.jsx)(fe,{children:(0,Pt.jsxs)(fe.Content,{children:[e.title&&(0,Pt.jsx)(fe.Title,{"data-testid":"widget-cue-title",children:e.title}),(0,Pt.jsx)(gT,{content:e.text,useLabel:a("useCue"),copyLabel:a("copyCue"),onCopy:p,onUse:d})]})}),(0,Pt.jsx)(te.IconButton,{title:a("thumbsUp"),onClick:y,icon:(0,Pt.jsx)(Ld,{}),className:(0,hy.default)(s.thumbsUp,u==="up"&&s.selected),disabled:!!u}),(0,Pt.jsx)(te.IconButton,{title:a("thumbsDown"),onClick:v,icon:(0,Pt.jsx)(Ad,{}),className:(0,hy.default)(s.thumbsDown,u==="down"&&s.selected),disabled:!!u}),(0,Pt.jsx)(te.IconButton,{title:a("removeCue"),onClick:g,icon:(0,Pt.jsx)(Jb,{})})]})},yT=$M;var fl=S(b()),GM=({cues:e})=>{let t=Y(),n=zt(),r=Zi(),o=u=>{t(Mb({id:u.rule.id})),r("Assistant response closed",{name:u.rule.name,group:u.rule.label,description:u.rule.description})},i=(u,c)=>{ko(u),r("Assistant response copied",{name:c.rule.name,group:c.rule.label,description:c.rule.description,copiedText:u})},s=(u,c)=>{n.send(Hr,{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"})},l=u=>{r("Assistant response feedback",{name:u.rule.name,group:u.rule.label,description:u.rule.description,thumb:"down"})};return(0,fl.jsx)(fl.Fragment,{children:e.map(u=>(0,fl.jsx)(yT,{cue:u,onRemove:o,onCopy:i,onUse:s,onThumbsDown:l,onThumbsUp:a},u.rule.id))})},vT=GM;var wT=S(_());var qM=/(https?:\/\/[^\s]+)/,ST=e=>e.split(" ").find(t=>qM.test(t));var $t=S(b()),YM=({suggestion:e,lines:t,onUse:n})=>{var c;let r=e.text||e.url||e.message,o=ST(r),i=W(Oo),s=B("showImages"),a=B("fallbackImage"),l=p=>{p.preventDefault(),p.stopPropagation(),n(r)},u=(0,wT.useCallback)(p=>{window.open(o,"_blank"),p.stopPropagation(),p.preventDefault()},[o]);return(0,$t.jsxs)(te,{onClick:l,"data-testid":"edit-suggestion",children:[(0,$t.jsxs)(fe,{children:[s&&e.image&&(0,$t.jsx)(fe.Image,{src:Jd(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)(te.Labels,{labels:e.searchKeywords}),(0,$t.jsx)(fe.Content,{cropText:t==="single",lineClamp:t==="multiple",children:r})]})]}),(0,$t.jsxs)(te.Actions,{children:[o&&(0,$t.jsx)(te.ActionButton,{onClick:u,label:i("visitUrl")}),(0,$t.jsx)(te.ActionButton,{primary:!0,onClick:l,label:i("useSuggestion")})]})]})},xT=YM;var pl=S(b()),XM=({lines:e,suggestions:t})=>{let n=zt(),r=(o,i)=>{n.send(Hr,{text:o,suggestion:{...i,source:i.source,sourceText:i.text}})};return(0,pl.jsx)(pl.Fragment,{children:t.map(o=>(0,pl.jsx)(xT,{suggestion:o,lines:e,onUse:i=>r(i,o)},o.text||o.url||o.message))})},ET=XM;var ml={};ze(ml,{enUS:()=>QM,nlNL:()=>ZM});var QM={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"}]},ZM={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 gl={root:"gr",loginText:"br",stateText:"jo",sectionList:"hr",shortcutList:"mr",shortcut:"ur",link:"Yo"};var $=S(b()),pf=(e,t)=>{let n=N(tt);(0,ff.useEffect)(()=>n?t.every(r=>!!r)?e():()=>{}:()=>{},[...t,n])},e2=({onLogIn:e})=>{let t=P("Widget",gl),n=B("isEmbedded"),r=B("adminUrl");return(0,$.jsx)("div",{className:t.loginText,children:(0,$.jsx)("div",{children:(0,$.jsx)(Bd,{isEmbedded:n,loginUrl:r,onLogIn:e})})},"login")},CT=({text:e})=>{let t=P("Widget",gl);return(0,$.jsx)("div",{className:t.stateText,children:(0,$.jsx)("div",{children:(0,$.jsx)("p",{children:e})})},"notification")},t2=()=>{let e=W(ml),t=Y(),n=P("Widget",gl),r=B("showSearch"),o=B("showSummaryCommand"),i=B("showKnowledgeSearch"),s=N(Rb("/admin/")),a=zt(),l=B("productName"),u=r||o||i||s;return pf(()=>(t(Xh()),()=>{t(Lb())}),[t]),u?(0,$.jsx)(In,{title:e("actions"),type:"shortcuts",children:(0,$.jsxs)("div",{className:n.shortcutList,children:[r&&(0,$.jsxs)("button",{type:"button",className:n.shortcut,"data-testid":"shortcut-search",title:e("linkSearch"),onClick:()=>a.send("ShowCommandPalette",{isOpen:!0}),children:[(0,$.jsx)(Yi,{}),e("linkSearch")]}),o&&(0,$.jsxs)("button",{type:"button",className:n.shortcut,"data-testid":"shortcut-summary",title:e("linkSummary"),onClick:()=>a.send("ShowCommandPalette",{isOpen:!0,page:"summary"}),children:[(0,$.jsx)(Zb,{}),e("linkSummary")]}),i&&(0,$.jsxs)("button",{type:"button",className:n.shortcut,"data-testid":"shortcut-knowledge-assist",title:e("linkKnowledgeSearch"),onClick:()=>a.send("ShowCommandPalette",{isOpen:!0,page:"knowledgeAssist"}),children:[(0,$.jsx)(Qb,{}),e("linkKnowledgeSearch")]}),s&&(0,$.jsxs)("a",{className:n.shortcut,target:"_blank",href:s,"data-testid":"shortcut-studio-login",title:e("linkStudioLogin",{productName:l}),rel:"noreferrer",children:[(0,$.jsx)(Xb,{}),e("linkStudioLogin",{productName:l})]})]})}):null},n2=()=>{let e=Y(),t=B("showCustomMessages"),n=N(wb),r=N(Vi);return pf(()=>(e(il(r)),e(Tb(r)),()=>{e(kb(r))}),[e,t,r]),!t||n.length===0?null:(0,$.jsx)(In,{type:"custom-messages","data-testid":"custom-messages",children:(0,$.jsx)(ht,{withDivider:!0,children:n.map(o=>(0,$.jsx)(Gb,{suggestion:o},o.text))})})},r2=()=>{let e=W(ml),t=Y(),n=B("showAutoflows"),r=N(gb),o=N(Vi);return pf(()=>(t(tr(o)),t(hb(o)),()=>{t(yb(o))}),[t,n,o]),!n||r.length===0?null:(0,$.jsx)(In,{type:"autoflows",title:e("titleAutoflows"),"data-testid":"autoflows",children:(0,$.jsx)(ht,{withDivider:!0,children:(0,$.jsx)(Wb,{})})})},o2=()=>{let e=Y(),t=N(Nd),n=N(Nb),r=N(Rd),o=N(Od),i=N(Xn),s=N(Bc);return pf(()=>{t.forEach(({type:a})=>{a==="entities"?e(sn()):["cues"].includes(a)||e(ln(a))})},[e,s,i]),(0,$.jsx)(ff.Fragment,{children:t.map(({type:a,title:l,amount:u,lines:c})=>{var p,d;switch(a){case"entities":return r&&r.length>0&&(0,$.jsx)(In,{type:a,title:l,"data-testid":`type-${a}`,children:(0,$.jsx)(Yb,{entities:r})},a);case"cues":return n&&n.length>0&&(0,$.jsx)(In,{type:a,title:l,"data-testid":`type-${a}`,children:(0,$.jsx)(ht,{withDivider:!0,children:(0,$.jsx)(vT,{cues:n})})},a);default:return((d=(p=o[a])==null?void 0:p.suggestions)==null?void 0:d.length)>0&&(0,$.jsx)(In,{type:a,title:l,"data-testid":`type-${a}`,children:(0,$.jsx)(ht,{withDivider:!0,children:(0,$.jsx)(ET,{lines:c,contentType:a,suggestions:o[a].suggestions.slice(0,u)||[]})})},a)}})})},i2=({onLogIn:e})=>{let t=W(ml),n=P("Widget",gl),r=N(Ki),o=N(tt),i=N(Vi),s=N(Xn);return r===!1?(0,$.jsx)(CT,{text:t("notSupported")}):o===!1?(0,$.jsx)(e2,{onLogIn:e}):!s||!i||o===null?(0,$.jsx)(CT,{text:t("waiting")}):(0,$.jsx)("div",{className:(0,bT.default)(n.root),"data-testid":"widget",children:(0,$.jsxs)(jl,{className:n.sectionList,children:[(0,$.jsx)(t2,{}),(0,$.jsx)(n2,{}),(0,$.jsx)(r2,{}),(0,$.jsx)(o2,{})]})})},TT=i2;function us(e){let t=new Range;return t.selectNodeContents(e),t}function kT(e,t,n){try{return Yr(e,t,n),!0}catch{return!1}}function mf(e){return"tagName"in e&&(e.tagName==="DIV"||e.tagName==="P")}function gf(e){return"tagName"in e&&e.tagName==="BR"}var hl=/[\u200B-\u200D\uFEFF]/g;function Yr(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(hl,""),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(gf(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;mf(l)&&u&&!mf(u)&&!gf(u)&&o++;break}default:break}}if(a(e),r.startContainer===document)throw new Error("Offsets out of bound");return r}function yl(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(hl,"").length),g&&(l=u+y.substring(0,i).replace(hl,"").length),u+=y.replace(hl,"").length;break}case Node.ELEMENT_NODE:{let y=p.nextSibling===null;gf(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&&mf(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 vl(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(hl,"");d===0&&g===void 0?a+=y:a+=y.substring(d,g);break}case Node.ELEMENT_NODE:{let d=u.nextSibling===null;s===0&&gf(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&&mf(u)&&!d&&(a+=`
|
|
27
|
-
`);break}default:break}p&&s++}return l(e),a}var PT=(s=>(s.CUT="Cut",s.BACKSPACE="Backspace",s.DELETE="Delete",s.ERASEEOF="EraseEof",s.UNDO="Undo",s.CLEAR="Clear",s))(PT||{}),or=class{constructor(t){this.element=t;this.currentText=this.getText(),this.currentHTML=this.getHTML(),this.listen()}eventListeners={};disposeHandlers=[];currentText="";currentCaret=null;currentSelection={start:0,end:0};currentHTML="";isFocused=!1;isActive=!0;isSettingValue=!1;isSubmitting=!1;isPossibleClearInputAction=!1;isDisposed=!1;addEventListener(t,n){let r=o=>{n(o)};this.element.addEventListener(t,r),this.disposeHandlers.push(()=>{this.element.removeEventListener(t,r)})}removeEventListener(t,n){this.element.removeEventListener(t,n)}triggerChange(){let t=this.getText(),n=this.getHTML(),r=t!==this.currentText;this.isActive&&(t===""&&this.currentText!==""&&!this.isSettingValue&&!this.isPossibleClearInputAction&&(this.isSubmitting=!0,this.emit("submit")),!this.isSettingValue&&r&&!this.isSubmitting&&this.emit("change",{plainText:t}),r&&(this.currentSelection=this.getSelection()),this.currentText=t,this.isSubmitting=!1,(this.currentHTML!==n||n===null&&r)&&(this.emit("updated",{plainText:t}),this.triggerCaretPosition(),this.currentHTML=n))}triggerSelection(){let t=this.getSelection();(t.start!==this.currentSelection.start||t.end!==this.currentSelection.end)&&(this.currentSelection=t,this.emit("selection",t),this.triggerCaretPosition())}triggerCaretPosition(){let t=this.getCaretPosition();_r(t,this.currentCaret)||(this.currentCaret=t,this.emit("caret",t))}handleKeyUp(t){let{key:n,shiftKey:r}=t;(n==="Enter"&&r===!0||n==="Backspace")&&this.triggerChange(),this.triggerSelection()}handleClick(){this.triggerSelection()}handleFocus(){this.isFocused||this.emit("focus"),this.triggerSelection(),this.isFocused=!0}handleBlur(){this.isPossibleClearInputAction=!1,this.isFocused&&this.emit("blur"),this.isFocused=!1}handleKeyDown(t){let{key:n,ctrlKey:r,metaKey:o}=t;this.isPossibleClearInputAction=Object.values(PT).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 RT(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var Vo=class extends or{observer;lastKnownSelection=null;getRootNode(){return this.element.getRootNode()}getText(){let t=new Range;return t.selectNodeContents(this.element),vl(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!RT(n)&&(t.insertNode(this.element.ownerDocument.createTextNode("\u2060")),n=t.getBoundingClientRect(),t.deleteContents(),!RT(n))?null:{top:n.top+n.height,left:n.left}}getSelection(){let t=this.getRange();if(t)return yl(this.element,t);let n=this.lastKnownSelection;if(n&&kT(this.element,n.start,n.end))return n;let r=us(this.element);return r.collapse(!1),yl(this.element,r)}getSelectedText(){let{start:t,end:n}=this.getSelection();return vl(this.element,Yr(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 Ko=class extends or{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 AT(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 s2(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}var yy=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()}},vy=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.iframe=AT(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()}},Sy=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(),j.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 vy(t,this.deepdeskUrl,{debug:!0}):new yy(t),r=o=>{var s,a;if(o.origin!==this.deepdeskUrl)return;let i=s2(o.data);typeof i!="object"||i.type!=="event"||i.channel!==t||(j.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;j.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)}},LT=Sy;var cs=class extends Error{constructor(n,r){super(n);this.body=r}name="CustomError"};var wy=e=>new Promise(t=>{setTimeout(t,e)});var ds=class extends cs{name="ClientError"},Ey=class extends cs{name="ServerError"},xy=new Map;function a2(e){return e.status===204||["0",null].includes(e.headers.get("content-length"))}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(xy.has(s)){r(xy.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 w=p,x=!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()=>(w--,a(s,h).then(async C=>v(C)&&!i.isAborted&&w>0?(await wy(d),T()):C.status===401&&g===!0&&x===!1?(x=!0,await this.refreshToken(),T()):C).catch(async C=>{if(y(C)&&!i.isAborted&&w>0)return await wy(d),T();throw C}));T().then(async C=>{let k=await C.json().catch(L=>{if(a2(C))return null;throw L});if(delete this.latestRequestByUrl[s],C.status>=500){o(new Ey("Server Error",k));return}else if(C.status===401){o(new ds("Unauthorized",k));return}else if(C.status===403){o(new ds("Forbidden",k));return}else if(C.status===404){o(new ds("Not Found",k));return}else if(C.status>=400){o(new ds("Bad Request",k));return}u&&xy.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 l2;(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||={})})(l2||={});function hf(e){return{...J(e),tags:e.tags}}var ir=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(),j.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 hf(n)}async getProfile(t){let n=await this.client.get(`/apis/admin/profiles/${t}/`,{version:null,useCache:!0});return J(n)}async getKnowledgeAssistant(t){let n=await this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{version:null,useCache:!0});return J(n)}async getContentTypes(){let t=await this.client.get("/apis/admin/content-types/",{version:null,useCache:!0});return J(t)}async getAccount(){let t=await this.client.get("/apis/admin/account/",{version:null,useCache:!0});return J(t)}async getPlatformConfig(){let{config:t}=await this.client.get("/platform/config/",{version:null,useCache:!0});return J(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(),j.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 j.info(`Successfully retrieved conversation ${i.id} for session ${t}`),hf(i)}async isConversationSupported(t,n={}){j.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 hf(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=>hf(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 J(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 j.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=>({...J(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 J(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 J(n)}async search(t){let n=await this.client.post(`/api/profiles/${t.profile}/search`,Re(t),{version:"v2"});return J(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 J(i)}async requestLoginByEmail(t){let n=await this.client.post("/apis/admin/session/passwordless/request/",{email:t},{version:null});return J(n)}async requestPasswordlessToken(){let t=await this.client.get("/apis/admin/session/passwordless/request/",{version:null});return J(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 J(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 J(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 J(n)}async translateMessages(t){let n=await this.client.post("/api/translate",Re(t),{version:"v2"});return J(n)}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),i=o.match(Bv);if(!n||!i)return;let s=i[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[s];a&&n&&a!==n&&j.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[s]=n})}};var Sl=class{constructor(t,n){this.url=t;this.options={timeout:25e3,...n}}eventListeners={};options;timeoutTimer;eventSource;proxyEvent(t){this.eventSource.addEventListener(Vg(t),n=>{let{data:r}=n;try{let o=JSON.parse(r);this.emit(t,J(o))}catch{j.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 u2;(t=>{let e;(i=>(i.Started="Started",i.Aborted="Aborted",i.Completed="Completed"))(e=t.AutoflowSessionState||={})})(u2||={});var wl=class{constructor(t,n={}){this.apiUrl=t;this.client=new fn(t,n)}client;streams={};logger=j;async getCustomMessages(t){let n=await this.client.get(`/sessions/${t}/suggestions`);return J(n.suggestions)}async sendCustomMessage(t,n){let r=await this.client.post(`/sessions/${t}/messages`,Re(n));return J(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 J(n.autoflows)}async startAutoflowSession(t){let n=await this.client.post("/autoflow-sessions",Re(t));return J(n)}async stopAutoflowSession(t){await this.client.delete(`/autoflow-sessions/${t}`)}openStream(t){return this.streams[t]||(this.streams[t]=new Sl(`${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 IT={startTime:null,stopTime:null},NT=q({name:"handlingTime",initialState:IT,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,()=>IT)}}),{handlingTimeStart:OT,handlingTimeStop:yf,handlingTimeReset:MT}=NT.actions,_T=NT.reducer;var DT=(e={})=>{let t={onAuthError:zi(!1),...e};return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var vf={list:{keywordMatches:[]},fetchState:"idle"};var Wo=U("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 vf.list;if(!i)throw new Error("No current conversation to fetch pinned messages");return n.getStyleSuggestions({profileCode:i,message:e})}),c2=q({name:"styleSuggestions",initialState:vf,reducers:{},extraReducers:e=>{e.addCase(Wo.pending,t=>{t.fetchState="loading"}).addCase(Wo.rejected,t=>{t.fetchState="error"}).addCase(Wo.fulfilled,(t,n)=>{t.fetchState="done",_r(t.list,n.payload)||(t.list=n.payload)}).addCase(Eo,t=>{t.list=vf.list}).addCase(le,()=>vf)}}),FT=c2.reducer;var HT=(e={})=>{let t,n=!0,r={getStyleSuggestions:Wo,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 d2(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end}var UT=(e={})=>{let t={getTextSuggestions:ln,getAutocompleteSuggestions:Ja,debounce:200,check:ns,...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===Md.toString();if(!p||!u&&!c)return a;let{input:{userCommitted:g}}=l;return d2(g,s)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let f=Wi(l);f===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(f))},d?0:t.debounce)),a}};var BT=Wo.fulfilled.toString();function f2(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 jT=e=>t=>n=>r=>{var u;if(r.type!==BT){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=f2(o,s);r.type===BT&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var p2=uc({answer:rC,auth:s1,autoflows:vb,conversation:g1,contentTypes:fE,customMessages:Pb,passwordlessToken:Ib,entities:UE,knowledgeAssistant:eC,handlingTime:_T,info:M1,input:L1,settings:Jx,profile:sC,search:j1,summary:$E,styleSuggestions:FT,ui:IC,rules:_b,textSuggestions:mC});function zT(e){return ix({reducer:p2,middleware:t=>[...t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI,deepdeskBrokerAPI:e.deepdeskBrokerAPI}},serializableCheck:!1}),DT(),UT({debounce:200}),HT({debounce:500}),jT(e.deepdeskAPI),...e.middleware?e.middleware:[]],preloadedState:e.preloadedState})}var m2=e=>{var t;return((t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())??"unknown"},g2=e=>t=>n=>r=>{var a;let o=t.getState(),i=Dg("inlineSuggestions")(o);switch(r.type){case zi.toString():{!r.payload&&e.emit("logout",void 0);break}case sn.fulfilled.toString():r.payload.length>0&&e.sendEvent("entities found",{conversationId:o.conversation.current.id,data:{entities:r.payload}});break;case Xe.toString():e.sendEvent(r.payload.name,{conversationId:((a=r.payload.options)==null?void 0:a.includeConversationData)&&o.conversation.current.id,data:r.payload.data});break;case Gc.toString():e.handleKeyDown(r.payload);break;case Eo.toString():e.logSendMessage(r.payload);break;case qc.toString():e.handleInputChanged(r.payload);break;case jo.fulfilled.toString():r.isBroadcasted||e.broadcast($g,r,!1),e.emit("cues",r.payload);break;default:break}let s=n(r);switch(r.type){case Eo.toString():e.handleAfterSendMessage(r.payload);break;case tl.toString():e.onUpdateShowTabHint(r.payload);break;case yf.toString():e.logHandlingTime();break;case"analytics/logEvent/fulfilled":{e.emit("event",r.meta.arg);break}case En.toString():{let{start:l,end:u}=o.input.selection;e.emit("select-suggestion",{type:m2(r.payload.suggestion),...r.payload,replace:r.payload.replace==="selection"?{start:l,end:u}:{start:0,end:u}},{mayApplyChanges:!0}),i&&(t.dispatch(xn([])),t.dispatch(Kn()));break}case $c.toString():{let{start:l,end:u}=o.input.selection;e.emit("replace",{...r.payload,replace:r.payload.replace==="selection"?{start:l,end:u}:{start:0,end:u}},{mayApplyChanges:!0});break}case Aa.toString():{let l=t.getState(),{text:u,selection:c}=l.input.userCommitted;e.emit("reset",{text:u,selectionAfter:c},{mayApplyChanges:!0});break}case Yc.toString():e.emit("select-image",r.payload,{mayApplyChanges:!0}),e.sendEvent("Image attached",{conversationId:o.conversation.current.id,data:{path:r.payload.suggestion.image,title:r.payload.suggestion.title}});break;case xn.toString():{i&&r.payload.length>0&&t.dispatch(Fr(0));break}case qn.fulfilled.toString():{e.sendEvent("conversation summarized",{conversationId:o.conversation.current.id,data:{summary:r.payload.summary,model:t.getState().summary.model}});break}default:break}return s},VT=g2;function Cy(e){return e.toISOString().replace("T"," ").replace("Z","")}function KT(e,t){var o,i,s;let{startTime:n,stopTime:r}=e.handlingTime;if(!n||!r)throw new Error("No startTime and stopTime for handling time metrics");return{conversationId:e.conversation.current.id,clientVersion:t.version,agentId:(o=e.info.agentInfo)==null?void 0:o.agentId,agentName:(i=e.info.agentInfo)==null?void 0:i.agentName,agentEmail:(s=e.info.agentInfo)==null?void 0:s.agentEmail,timeStart:Cy(n),timeStop:Cy(r)}}function WT(e,t,n){var k,L,I;let{text:r,metrics:{numCharsTyped:o,numCharsPasted:i,numCharsCut:s,numCharsDeleted:a,numPaste:l,agentStartedTypingTimestamp:u,externalTimeTotalSeconds:c,pastes:p,cuts:d,deletions:g,textSuggestions:y,offeredTextSuggestions:v}}=t[e],f=r.length,h=y.reduce((O,{text:V,searchTerm:K})=>O+V.length-(K?K.length:0),0),w=u??Date.now(),x=(Date.now()-w)/1e3+(c||0),T=o/x,C=y.reduce((O,{searchTerm:V})=>O+(V?V.length:0),0);return{conversationId:t.conversation.current.id,source:"agent",text:r,clientVersion:n.version,pastes:p,cuts:d,deletions:g,lenTextTyped:o+C,lenTextTotal:f,lenTextAssisted:h,lenTextPasted:i,lenTextCut:s,lenTextDeleted:a,timeTotalSeconds:x,charsPerSecond:T,numPastes:l,textSuggestionsV2:y,suggestionsCounters:[{source:"gpt",countOffered:v.filter(O=>O.source==="gpt").length}],agentId:(k=t.info.agentInfo)==null?void 0:k.agentId,agentName:(L=t.info.agentInfo)==null?void 0:L.agentName,agentEmail:(I=t.info.agentInfo)==null?void 0:I.agentEmail}}function by(e,t){var i;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return by(r,t);let o=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;return o?by(o,t):null}function $T(e,t){return by(e,t)}function GT(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function h2(e){return typeof e=="object"&&e!==null&&"tagName"in e}function Sf(e){return h2(e)&&(Wr(e)||zd(e))}var qT,kn=new Map,y2=["bottom","height","left","right","top","width"],v2=(e={},t={})=>y2.some(n=>e[n]!==t[n]);function YT(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,...YT(t)]:[]}function XT(e,t){return!e||!t?null:{...e,top:e.top+t.top,left:e.left+t.left}}var wf=!1,QT=()=>{wf=!0;let e=[];if(kn.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),kn.delete(n);return}let r=n.getBoundingClientRect();v2(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{let n=t.parentRects?t.parentRects.reduce(XT,t.rect):t.rect;t.callbacks.forEach(r=>r(n))}),kn.size===0){wf=!1;return}qT=window.requestAnimationFrame(QT)};function Ty(e,t){let n=YT(e),r=[],o=n.map((i,s)=>Ty(i,a=>{r[s]=a;let l=kn.get(e);if(!l)return;let u=r.reduce(XT,l.rect);l.callbacks.forEach(c=>c(u))}));return{observe(i=!0){if(o.forEach(s=>s.observe(!1)),kn.has(e)){let s=kn.get(e);s.callbacks.push(t),s.rect&&t(s.rect)}else kn.set(e,{rect:void 0,callbacks:[t],parentRects:r});i&&!wf&&QT()},unobserve(){o.forEach(s=>s.unobserve());let i=kn.get(e);if(i){let s=i.callbacks.indexOf(t);s>=0&&i.callbacks.splice(s,1),i.callbacks.length||kn.delete(e),kn.size||(cancelAnimationFrame(qT),wf=!1)}}}}var ZT,Pn=new Map,JT=()=>{Pn.forEach((e,t)=>{if(!t.isConnected){Pn.delete(t);return}let{clientHeight:n,scrollHeight:r}=t,o=r>n;e.visible!==o&&(e.visible=o,e.callbacks.forEach(i=>i(e.visible)))}),Pn.size!==0&&(ZT=window.requestAnimationFrame(JT))};function ek(e,t){return{observe(){let n=Pn.size===0;Pn.has(e)?Pn.get(e).callbacks.push(t):Pn.set(e,{visible:void 0,callbacks:[t]}),n&&JT()},unobserve(){let n=Pn.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||Pn.delete(e),Pn.size||cancelAnimationFrame(ZT)}}}}var ky=["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 Py(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function fs(e){return parseFloat(e)}function xf(e){return Math.round(e*1e6)}function tk(e){return e/1e6}function Ry(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=fs(e.width),i=fs(e.borderLeftWidth),s=fs(e.borderRightWidth),a=fs(e.paddingRight),l=tk(xf(o)-xf(i)-xf(s)),u=tk(xf(r));if(l-u>2){let c=l-u;n.style.paddingRight=`${a+c}px`}}function xl(e,t={}){var c;let n=t.overlayContainer||document.createElement("div");n.style.display="none",n.style.position=t.position??"fixed",n.style.pointerEvents="none",n.style.borderColor="transparent",Ho(n);let r=window.getComputedStyle(e),o=!0,i=()=>{n.scrollTop=e.scrollTop};Py(r,n,ky),Ry(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",i));let s=ek(e,()=>{Py(r,n,ky),Ry(r,e,n),i(),setTimeout(i,0)}),a,l=!0,u=Ty(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(Py(r,n,ky),Ry(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=fs(g.borderTopWidth),v=fs(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 nk=(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{j.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function S2(e){return e.offsetParent!==null}function rk(e){if(!S2(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 Ef(e,t,n=100){let r=rk(e);t({isVisible:r});let o=setInterval(()=>{let i=rk(e);i!==r&&(r=i,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var Le=S(b());var ok=nk("showTabHint",!0),El=class e{static version="11.2.1-beta.9";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 ir(u,{token:i,fetch:s}),this.version=r,this.instanceId=e.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[VT({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=>ok.update(p),sendEvent:(p,d)=>this.deepdeskApi.sendEvent(p,d)})]};n&&Object.assign(c,{deepdeskBrokerAPI:new wl(n)}),this.store=zT(c),this.broadcastEvents=new LT({debug:!0,deepdeskUrl:u,eventMap:z1(this.store),createCustomChannel:l}),this.store.dispatch(tl(ok.value())),this.store.dispatch(Hc({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?(j.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(j.warn("Profile has not been loaded (yet)"),!0):(j.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(zi(null)),this.store.dispatch(zn()),new Promise(t=>{let n=this.store.subscribe(()=>{let r=this.store.getState();tt(r)&&e1(r)!=="loading"&&(n(),t())});this.unmountHandlers.push(()=>{n()})})}async isLoggedIn(){return(await this.store.dispatch(zn())).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){j.warn("Failed to attach user:",n)}}async isConversationSupported(t,n){return(await this.store.dispatch(Bg({sessionId:t,options:n}))).payload}async createConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(jc(t))).payload}async getConversationBySessionId(t,n){return this.hasConversation()&&this.sessionId()!==t&&this.resetConversation(),(await this.store.dispatch(zc({sessionId:t,options:n}))).payload}async upsertConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(jg(t))).payload}async postMessages(t){return(await this.store.dispatch(Kc(t))).payload}async updateConversation(t){return(await this.store.dispatch(Vc(t))).payload}resetConversation(){this.store.dispatch(le()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}async getSummary(){let t=await this.store.dispatch(qn());if(t.error)throw new Error(t.error.message);return t.payload.summary}configure(t){this.store.dispatch(Hc(t))}setVisitorInfo(t){this.store.dispatch(O1(t))}async setAgentInfo(t){await this.store.dispatch(La(t))}async setAgentSettings(t){await this.store.dispatch(Kg(t))}async getAgentSettings(){return(await this.store.dispatch(Wg())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let t=[];return this.store.dispatch(Md()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})}notifyInputChanged(t){this.store.dispatch(qc(t))}notifyKeyDown(t){this.store.dispatch(Gc(t))}notifyPaste(t,n){this.store.dispatch(k1({text:t,selectionText:n}))}notifyCut(t){this.store.dispatch(b1(t))}notifyExternalSuggestion(t){this.store.dispatch(En(t)),this.store.dispatch(Kn())}async evaluateRule(t,n={}){let{payload:r,error:o}=await this.store.dispatch(jo({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(Vr({collapse:!1})),this.inputMediator&&this.store.dispatch(S1({text:t,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(xn([])))}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(T1(h1(t))),t.key!=="Tab"&&!this.settings.showTextSuggestions)return;let u=()=>{n||!a||i&&(t.shiftKey||(this.store.dispatch(x1()),s||this.stageSelectedSuggestion({inputType:"arrow"}),t.preventDefault()))},c=()=>{n||!a||s&&o<=0||i&&(t.shiftKey||(this.store.dispatch(C1()),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(Fr(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(Fr(-1)),this.store.dispatch(Aa()),t.preventDefault()):n||(this.store.dispatch(Vr({collapse:!0})),this.store.dispatch(AC(!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(tl(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):!s&&this.settings.showTabCompletion&&g&&g.text.startsWith(d)&&(this.store.dispatch(En({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(P1()),this.store.dispatch(xn([]))}handlingTimeStart(){this.state.handlingTime.startTime||(j.info("Start handling time"),this.store.dispatch(OT()))}handlingTimeStop(){this.state.handlingTime.startTime&&(j.info("Stop handling time"),this.store.dispatch(yf()))}logSendMessage(t){let n=WT("input",this.state,{version:this.version});t&&(Object.assign(n,{text:t}),Object.assign(n,{lenTextTotal:t.length})),this.deepdeskApi.sendEventV1("Send Message",n),this.emit("send-message-event",n)}logHandlingTime(){let t=KT(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",t),this.store.dispatch(MT())}notifySubmit(t={}){this.shouldAbort()||(this.store.dispatch(Kn()),this.store.dispatch(Eo(t.text??this.state.input.text)))}stageSelectedSuggestion(t){let n=this.state.input.selectedSuggestionIndex,{textSuggestions:r}=this.state.input;this.store.dispatch(En({text:r[n].text,suggestion:r[n],eventMetrics:t,replace:"until-selection-end"}))}emit(t,n,r={}){let o=()=>{this.eventListeners[t]&&this.eventListeners[t].forEach(i=>{try{i(n)}catch(s){j.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),j.error(s)}})};this.inputMediator&&r.mayApplyChanges?this.inputMediator.applyChanges(o):o()}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),()=>{this.off(t,n)}}off(t,n){if(!t&&!n){this.eventListeners={};return}let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}setConversationQuery(t){this.dynamicThunkObject.conversationQuery=t}whenConversationLoaded(t){let n=()=>this.loadProfileConfig().then(()=>t());this.hasConversation()&&n();let r=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==r&&(r=this.hasConversation(),r&&n())})}overlayContainerFactory(t,n,r,o){let[i,s]=xl(n,r);return i.setAttribute("translate","no"),i.dataset.testid=t,o&&i.classList.add(o),this.unmountHandlers.push(()=>{(0,Gt.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]=xl(i,{appendTo:document.body,onMoveStart:()=>{o.style.display="none"}});a.dataset.testid=n,a.style.zIndex="2",a.appendChild(r),this.unmountHandlers.push(()=>{(0,Gt.unmountComponentAtNode)(o),l()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return Ho(o),o.dataset.testid=t,o.style.color=r.color,o.style.fontSize=r.fontSize,o.style.fontFamily=r.fontFamily,o.style.fontVariant=r.fontVariant,o.setAttribute("translate","no"),n.appendChild(o),this.unmountHandlers.push(()=>{(0,Gt.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),j.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()?(j.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(A1(r.metrics))):j.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(!Sf(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),Ho(t),this.inputMediator=y||(Wr(t)?new Ko(t):new Vo(t)),this.inputMediator.on("change",({plainText:T})=>{this.notifyInputChanged(T)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(R1({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 w=v&&$T(t,v)||void 0;if(m){let{customStyles:T,appendOverlayTo:C}=n;if(Wr(t))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let k=this.createInlineContainer(t,"deepdesk-caret");(0,Gt.render)((0,Le.jsx)(Bo,{store:this.store,customStyles:T,children:(0,Le.jsx)(bo,{broadcastEvents:this.broadcastEvents,children:(0,Le.jsx)(FC,{})})}),k),this.inputMediator.on("caret",I=>{this.store.dispatch(xn([])),I?(k.style.display="block",k.style.top=`${I.top}px`,k.style.left=`${I.left}px`):k.style.display="none"});let L=this.overlayContainerFactory("floating-menu",w||t,{appendTo:typeof h=="object"&&"appendOverlayTo"in h?h.appendOverlayTo:C},T==null?void 0:T.floatingMenuRootNode);(0,Gt.render)((0,Le.jsx)(Bo,{store:this.store,customStyles:T,children:(0,Le.jsx)(bo,{broadcastEvents:this.broadcastEvents,children:(0,Le.jsx)(kC,{onLogIn:()=>this.loginViaPopup().catch(I=>j.warn(I.message))})})}),L)}else{let T=this.overlayContainerFactory("deepdesk-tab-completion",w||t,{appendTo:f,closestScrollElement:w,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),C=this.overlayContainerFactory("deepdesk-suggestions-overlay",w||t,{appendTo:f},r==null?void 0:r.suggestionsRootNode);(0,Gt.render)((0,Le.jsx)(Bo,{store:this.store,customStyles:r,children:(0,Le.jsx)(bo,{broadcastEvents:this.broadcastEvents,children:(0,Le.jsx)(fb,{inputElement:t})})}),T),(0,Gt.render)((0,Le.jsx)(Bo,{store:this.store,customStyles:r,children:(0,Le.jsx)(bo,{broadcastEvents:this.broadcastEvents,children:(0,Le.jsx)($C,{onLogIn:()=>this.loginViaPopup().catch(k=>j.warn(k.message))})})}),C)}(0,Gt.render)((0,Le.jsx)(Bo,{store:this.store,customStyles:r,children:(0,Le.jsx)(bo,{broadcastEvents:this.broadcastEvents,children:(0,Le.jsx)(xC,{})})}),this.createContainer("deepdesk-overlays"));let x;this.inputMediator.on("selection",T=>{clearTimeout(x),T===null?x=setTimeout(()=>{T!==null&&this.store.dispatch(zg(T))},500):this.store.dispatch(zg(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(Oh(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(Oh(!0))),this.store.dispatch(w1({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&&j.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,Gt.render)((0,Le.jsx)(Bo,{store:this.store,customStyles:r,children:(0,Le.jsx)(bo,{broadcastEvents:this.broadcastEvents,children:(0,Le.jsx)(TT,{onLogIn:()=>this.loginViaPopup().catch(s=>j.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,Gt.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(t){let n=Ef(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){GT(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(Za());let t=Xn(this.state);t&&(await this.store.dispatch(Xa()),this.store.dispatch(Hc({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(Na),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){j.error("Error posting message to popup",v),r(v)}break}case"deepdesk-popup-error":{u(),g.data.message==="Timeout"&&j.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(j.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;j.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=Nd(this.state);try{n.forEach(({type:r})=>{r==="entities"?this.store.dispatch(sn()):["cues"].includes(r)||this.store.dispatch(ln(r))})}catch(r){this.handleError(r)}}};async function ik(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 sk(e,t,n={}){let r=n.replace?Yr(e,n.replace.start,n.replace.end):us(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 PT=(s=>(s.CUT="Cut",s.BACKSPACE="Backspace",s.DELETE="Delete",s.ERASEEOF="EraseEof",s.UNDO="Undo",s.CLEAR="Clear",s))(PT||{}),or=class{constructor(t){this.element=t;this.currentText=this.getText(),this.currentHTML=this.getHTML(),this.listen()}eventListeners={};disposeHandlers=[];currentText="";currentCaret=null;currentSelection={start:0,end:0};currentHTML="";isFocused=!1;isActive=!0;isSettingValue=!1;isSubmitting=!1;isPossibleClearInputAction=!1;isDisposed=!1;addEventListener(t,n){let r=o=>{n(o)};this.element.addEventListener(t,r),this.disposeHandlers.push(()=>{this.element.removeEventListener(t,r)})}removeEventListener(t,n){this.element.removeEventListener(t,n)}triggerChange(){let t=this.getText(),n=this.getHTML(),r=t!==this.currentText;this.isActive&&(t===""&&this.currentText!==""&&!this.isSettingValue&&!this.isPossibleClearInputAction&&(this.isSubmitting=!0,this.emit("submit")),!this.isSettingValue&&r&&!this.isSubmitting&&this.emit("change",{plainText:t}),r&&(this.currentSelection=this.getSelection()),this.currentText=t,this.isSubmitting=!1,(this.currentHTML!==n||n===null&&r)&&(this.emit("updated",{plainText:t}),this.triggerCaretPosition(),this.currentHTML=n))}triggerSelection(){let t=this.getSelection();(t.start!==this.currentSelection.start||t.end!==this.currentSelection.end)&&(this.currentSelection=t,this.emit("selection",t),this.triggerCaretPosition())}triggerCaretPosition(){let t=this.getCaretPosition();_r(t,this.currentCaret)||(this.currentCaret=t,this.emit("caret",t))}handleKeyUp(t){let{key:n,shiftKey:r}=t;(n==="Enter"&&r===!0||n==="Backspace")&&this.triggerChange(),this.triggerSelection()}handleClick(){this.triggerSelection()}handleFocus(){this.isFocused||this.emit("focus"),this.triggerSelection(),this.isFocused=!0}handleBlur(){this.isPossibleClearInputAction=!1,this.isFocused&&this.emit("blur"),this.isFocused=!1}handleKeyDown(t){let{key:n,ctrlKey:r,metaKey:o}=t;this.isPossibleClearInputAction=Object.values(PT).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 RT(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var Vo=class extends or{observer;lastKnownSelection=null;getRootNode(){return this.element.getRootNode()}getText(){let t=new Range;return t.selectNodeContents(this.element),vl(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!RT(n)&&(t.insertNode(this.element.ownerDocument.createTextNode("\u2060")),n=t.getBoundingClientRect(),t.deleteContents(),!RT(n))?null:{top:n.top+n.height,left:n.left}}getSelection(){let t=this.getRange();if(t)return yl(this.element,t);let n=this.lastKnownSelection;if(n&&kT(this.element,n.start,n.end))return n;let r=us(this.element);return r.collapse(!1),yl(this.element,r)}getSelectedText(){let{start:t,end:n}=this.getSelection();return vl(this.element,Yr(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 Ko=class extends or{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 AT(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 s2(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}var yy=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()}},vy=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.iframe=AT(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()}},Sy=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(),j.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 vy(t,this.deepdeskUrl,{debug:!0}):new yy(t),r=o=>{var s,a;if(o.origin!==this.deepdeskUrl)return;let i=s2(o.data);typeof i!="object"||i.type!=="event"||i.channel!==t||(j.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;j.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)}},LT=Sy;var cs=class extends Error{constructor(n,r){super(n);this.body=r}name="CustomError"};var wy=e=>new Promise(t=>{setTimeout(t,e)});var ds=class extends cs{name="ClientError"},Ey=class extends cs{name="ServerError"},xy=new Map;function a2(e){return e.status===204||["0",null].includes(e.headers.get("content-length"))}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(xy.has(s)){r(xy.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 w=p,x=!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()=>(w--,a(s,h).then(async C=>v(C)&&!i.isAborted&&w>0?(await wy(d),T()):C.status===401&&g===!0&&x===!1?(x=!0,await this.refreshToken(),T()):C).catch(async C=>{if(y(C)&&!i.isAborted&&w>0)return await wy(d),T();throw C}));T().then(async C=>{let k=await C.json().catch(L=>{if(a2(C))return null;throw L});if(delete this.latestRequestByUrl[s],C.status>=500){o(new Ey("Server Error",k));return}else if(C.status===401){o(new ds("Unauthorized",k));return}else if(C.status===403){o(new ds("Forbidden",k));return}else if(C.status===404){o(new ds("Not Found",k));return}else if(C.status>=400){o(new ds("Bad Request",k));return}u&&xy.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 l2;(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||={})})(l2||={});function hf(e){return{...J(e),tags:e.tags}}var ir=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(),j.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 hf(n)}async getProfile(t){let n=await this.client.get(`/apis/admin/profiles/${t}/`,{version:null,useCache:!0});return J(n)}async getKnowledgeAssistant(t){let n=await this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{version:null,useCache:!0});return J(n)}async getContentTypes(){let t=await this.client.get("/apis/admin/content-types/",{version:null,useCache:!0});return J(t)}async getAccount(){let t=await this.client.get("/apis/admin/account/",{version:null,useCache:!0});return J(t)}async getPlatformConfig(){let{config:t}=await this.client.get("/platform/config/",{version:null,useCache:!0});return J(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(),j.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 j.info(`Successfully retrieved conversation ${i.id} for session ${t}`),hf(i)}async isConversationSupported(t,n={}){j.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 hf(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=>hf(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 J(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 j.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=>({...J(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 J(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 J(n)}async search(t){let n=await this.client.post(`/api/profiles/${t.profile}/search`,Re(t),{version:"v2"});return J(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 J(i)}async requestLoginByEmail(t){let n=await this.client.post("/apis/admin/session/passwordless/request/",{email:t},{version:null});return J(n)}async requestPasswordlessToken(){let t=await this.client.get("/apis/admin/session/passwordless/request/",{version:null});return J(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 J(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 J(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 J(n)}async translateMessages(t){let n=await this.client.post("/api/translate",Re(t),{version:"v2"});return J(n)}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),i=o.match(Bv);if(!n||!i)return;let s=i[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[s];a&&n&&a!==n&&j.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[s]=n})}};var Sl=class{constructor(t,n){this.url=t;this.options={timeout:25e3,...n}}eventListeners={};options;timeoutTimer;eventSource;proxyEvent(t){this.eventSource.addEventListener(Vg(t),n=>{let{data:r}=n;try{let o=JSON.parse(r);this.emit(t,J(o))}catch{j.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 u2;(t=>{let e;(i=>(i.Started="Started",i.Aborted="Aborted",i.Completed="Completed"))(e=t.AutoflowSessionState||={})})(u2||={});var wl=class{constructor(t,n={}){this.apiUrl=t;this.client=new fn(t,n)}client;streams={};logger=j;async getCustomMessages(t){let n=await this.client.get(`/sessions/${t}/suggestions`);return J(n.suggestions)}async sendCustomMessage(t,n){let r=await this.client.post(`/sessions/${t}/messages`,Re(n));return J(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 J(n.autoflows)}async startAutoflowSession(t){let n=await this.client.post("/autoflow-sessions",Re(t));return J(n)}async stopAutoflowSession(t){await this.client.delete(`/autoflow-sessions/${t}`)}openStream(t){return this.streams[t]||(this.streams[t]=new Sl(`${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 IT={startTime:null,stopTime:null},NT=q({name:"handlingTime",initialState:IT,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,()=>IT)}}),{handlingTimeStart:OT,handlingTimeStop:yf,handlingTimeReset:MT}=NT.actions,_T=NT.reducer;var DT=(e={})=>{let t={onAuthError:zi(!1),...e};return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var vf={list:{keywordMatches:[]},fetchState:"idle"};var Wo=U("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 vf.list;if(!i)throw new Error("No current conversation to fetch pinned messages");return n.getStyleSuggestions({profileCode:i,message:e})}),c2=q({name:"styleSuggestions",initialState:vf,reducers:{},extraReducers:e=>{e.addCase(Wo.pending,t=>{t.fetchState="loading"}).addCase(Wo.rejected,t=>{t.fetchState="error"}).addCase(Wo.fulfilled,(t,n)=>{t.fetchState="done",_r(t.list,n.payload)||(t.list=n.payload)}).addCase(Eo,t=>{t.list=vf.list}).addCase(le,()=>vf)}}),FT=c2.reducer;var HT=(e={})=>{let t,n=!0,r={getStyleSuggestions:Wo,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 d2(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end}var UT=(e={})=>{let t={getTextSuggestions:ln,getAutocompleteSuggestions:Ja,debounce:200,check:ns,...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===Md.toString();if(!p||!u&&!c)return a;let{input:{userCommitted:g}}=l;return d2(g,s)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let f=Wi(l);f===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(f))},d?0:t.debounce)),a}};var BT=Wo.fulfilled.toString();function f2(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 jT=e=>t=>n=>r=>{var u;if(r.type!==BT){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=f2(o,s);r.type===BT&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var p2=uc({answer:rC,auth:s1,autoflows:vb,conversation:g1,contentTypes:fE,customMessages:Pb,passwordlessToken:Ib,entities:UE,knowledgeAssistant:eC,handlingTime:_T,info:M1,input:L1,settings:Jx,profile:sC,search:j1,summary:$E,styleSuggestions:FT,ui:IC,rules:_b,textSuggestions:mC});function zT(e){return ix({reducer:p2,middleware:t=>[...t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI,deepdeskBrokerAPI:e.deepdeskBrokerAPI}},serializableCheck:!1}),DT(),UT({debounce:200}),HT({debounce:500}),jT(e.deepdeskAPI),...e.middleware?e.middleware:[]],preloadedState:e.preloadedState})}var m2=e=>{var t;return((t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())??"unknown"},g2=e=>t=>n=>r=>{var a;let o=t.getState(),i=Dg("inlineSuggestions")(o);switch(r.type){case zi.toString():{!r.payload&&e.emit("logout",void 0);break}case sn.fulfilled.toString():r.payload.length>0&&e.sendEvent("entities found",{conversationId:o.conversation.current.id,data:{entities:r.payload}});break;case Xe.toString():e.sendEvent(r.payload.name,{conversationId:((a=r.payload.options)==null?void 0:a.includeConversationData)&&o.conversation.current.id,data:r.payload.data});break;case Gc.toString():e.handleKeyDown(r.payload);break;case Eo.toString():e.logSendMessage(r.payload);break;case qc.toString():e.handleInputChanged(r.payload);break;case jo.fulfilled.toString():r.isBroadcasted||e.broadcast($g,r,!1),e.emit("cues",r.payload);break;default:break}let s=n(r);switch(r.type){case Eo.toString():e.handleAfterSendMessage(r.payload);break;case tl.toString():e.onUpdateShowTabHint(r.payload);break;case yf.toString():e.logHandlingTime();break;case"analytics/logEvent/fulfilled":{e.emit("event",r.meta.arg);break}case En.toString():{let{start:l,end:u}=o.input.selection;e.emit("select-suggestion",{type:m2(r.payload.suggestion),...r.payload,replace:r.payload.replace==="selection"?{start:l,end:u}:{start:0,end:u}},{mayApplyChanges:!0}),i&&(t.dispatch(xn([])),t.dispatch(Kn()));break}case $c.toString():{let{start:l,end:u}=o.input.selection;e.emit("replace",{...r.payload,replace:r.payload.replace==="selection"?{start:l,end:u}:{start:0,end:u}},{mayApplyChanges:!0});break}case Aa.toString():{let l=t.getState(),{text:u,selection:c}=l.input.userCommitted;e.emit("reset",{text:u,selectionAfter:c},{mayApplyChanges:!0});break}case Yc.toString():e.emit("select-image",r.payload,{mayApplyChanges:!0}),e.sendEvent("Image attached",{conversationId:o.conversation.current.id,data:{path:r.payload.suggestion.image,title:r.payload.suggestion.title}});break;case xn.toString():{i&&r.payload.length>0&&t.dispatch(Fr(0));break}case qn.fulfilled.toString():{e.sendEvent("conversation summarized",{conversationId:o.conversation.current.id,data:{summary:r.payload.summary,model:t.getState().summary.model}});break}default:break}return s},VT=g2;function Cy(e){return e.toISOString().replace("T"," ").replace("Z","")}function KT(e,t){var o,i,s;let{startTime:n,stopTime:r}=e.handlingTime;if(!n||!r)throw new Error("No startTime and stopTime for handling time metrics");return{conversationId:e.conversation.current.id,clientVersion:t.version,agentId:(o=e.info.agentInfo)==null?void 0:o.agentId,agentName:(i=e.info.agentInfo)==null?void 0:i.agentName,agentEmail:(s=e.info.agentInfo)==null?void 0:s.agentEmail,timeStart:Cy(n),timeStop:Cy(r)}}function WT(e,t,n){var k,L,I;let{text:r,metrics:{numCharsTyped:o,numCharsPasted:i,numCharsCut:s,numCharsDeleted:a,numPaste:l,agentStartedTypingTimestamp:u,externalTimeTotalSeconds:c,pastes:p,cuts:d,deletions:g,textSuggestions:y,offeredTextSuggestions:v}}=t[e],f=r.length,h=y.reduce((O,{text:V,searchTerm:K})=>O+V.length-(K?K.length:0),0),w=u??Date.now(),x=(Date.now()-w)/1e3+(c||0),T=o/x,C=y.reduce((O,{searchTerm:V})=>O+(V?V.length:0),0);return{conversationId:t.conversation.current.id,source:"agent",text:r,clientVersion:n.version,pastes:p,cuts:d,deletions:g,lenTextTyped:o+C,lenTextTotal:f,lenTextAssisted:h,lenTextPasted:i,lenTextCut:s,lenTextDeleted:a,timeTotalSeconds:x,charsPerSecond:T,numPastes:l,textSuggestionsV2:y,suggestionsCounters:[{source:"gpt",countOffered:v.filter(O=>O.source==="gpt").length}],agentId:(k=t.info.agentInfo)==null?void 0:k.agentId,agentName:(L=t.info.agentInfo)==null?void 0:L.agentName,agentEmail:(I=t.info.agentInfo)==null?void 0:I.agentEmail}}function by(e,t){var i;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return by(r,t);let o=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;return o?by(o,t):null}function $T(e,t){return by(e,t)}function GT(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function h2(e){return typeof e=="object"&&e!==null&&"tagName"in e}function Sf(e){return h2(e)&&(Wr(e)||zd(e))}var qT,kn=new Map,y2=["bottom","height","left","right","top","width"],v2=(e={},t={})=>y2.some(n=>e[n]!==t[n]);function YT(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,...YT(t)]:[]}function XT(e,t){return!e||!t?null:{...e,top:e.top+t.top,left:e.left+t.left}}var wf=!1,QT=()=>{wf=!0;let e=[];if(kn.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),kn.delete(n);return}let r=n.getBoundingClientRect();v2(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{let n=t.parentRects?t.parentRects.reduce(XT,t.rect):t.rect;t.callbacks.forEach(r=>r(n))}),kn.size===0){wf=!1;return}qT=window.requestAnimationFrame(QT)};function Ty(e,t){let n=YT(e),r=[],o=n.map((i,s)=>Ty(i,a=>{r[s]=a;let l=kn.get(e);if(!l)return;let u=r.reduce(XT,l.rect);l.callbacks.forEach(c=>c(u))}));return{observe(i=!0){if(o.forEach(s=>s.observe(!1)),kn.has(e)){let s=kn.get(e);s.callbacks.push(t),s.rect&&t(s.rect)}else kn.set(e,{rect:void 0,callbacks:[t],parentRects:r});i&&!wf&&QT()},unobserve(){o.forEach(s=>s.unobserve());let i=kn.get(e);if(i){let s=i.callbacks.indexOf(t);s>=0&&i.callbacks.splice(s,1),i.callbacks.length||kn.delete(e),kn.size||(cancelAnimationFrame(qT),wf=!1)}}}}var ZT,Pn=new Map,JT=()=>{Pn.forEach((e,t)=>{if(!t.isConnected){Pn.delete(t);return}let{clientHeight:n,scrollHeight:r}=t,o=r>n;e.visible!==o&&(e.visible=o,e.callbacks.forEach(i=>i(e.visible)))}),Pn.size!==0&&(ZT=window.requestAnimationFrame(JT))};function ek(e,t){return{observe(){let n=Pn.size===0;Pn.has(e)?Pn.get(e).callbacks.push(t):Pn.set(e,{visible:void 0,callbacks:[t]}),n&&JT()},unobserve(){let n=Pn.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||Pn.delete(e),Pn.size||cancelAnimationFrame(ZT)}}}}var ky=["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 Py(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function fs(e){return parseFloat(e)}function xf(e){return Math.round(e*1e6)}function tk(e){return e/1e6}function Ry(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=fs(e.width),i=fs(e.borderLeftWidth),s=fs(e.borderRightWidth),a=fs(e.paddingRight),l=tk(xf(o)-xf(i)-xf(s)),u=tk(xf(r));if(l-u>2){let c=l-u;n.style.paddingRight=`${a+c}px`}}function xl(e,t={}){var c;let n=t.overlayContainer||document.createElement("div");n.style.display="none",n.style.position=t.position??"fixed",n.style.pointerEvents="none",n.style.borderColor="transparent",Ho(n);let r=window.getComputedStyle(e),o=!0,i=()=>{n.scrollTop=e.scrollTop};Py(r,n,ky),Ry(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",i));let s=ek(e,()=>{Py(r,n,ky),Ry(r,e,n),i(),setTimeout(i,0)}),a,l=!0,u=Ty(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(Py(r,n,ky),Ry(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=fs(g.borderTopWidth),v=fs(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 nk=(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{j.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function S2(e){return e.offsetParent!==null}function rk(e){if(!S2(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 Ef(e,t,n=100){let r=rk(e);t({isVisible:r});let o=setInterval(()=>{let i=rk(e);i!==r&&(r=i,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var Le=S(b());var ok=nk("showTabHint",!0),El=class e{static version="11.3.0";static count=0;deepdeskApi;inputMediator=null;version;broadcastEvents;eventListeners={};unmountHandlers=[];widgetRoot=null;dynamicThunkObject={};isMounted=!1;instanceId;shouldRender=!0;store;constructor({deepdeskUrl:t,brokerUrl:n,version:r=e.version||"unknown",locale:o="en-US",token:i,fetch:s,productName:a,createCustomChannel:l}){let u=t.replace(/\/api$/,"");this.deepdeskApi=new ir(u,{token:i,fetch:s}),this.version=r,this.instanceId=e.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[VT({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=>ok.update(p),sendEvent:(p,d)=>this.deepdeskApi.sendEvent(p,d)})]};n&&Object.assign(c,{deepdeskBrokerAPI:new wl(n)}),this.store=zT(c),this.broadcastEvents=new LT({debug:!0,deepdeskUrl:u,eventMap:z1(this.store),createCustomChannel:l}),this.store.dispatch(tl(ok.value())),this.store.dispatch(Hc({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?(j.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(j.warn("Profile has not been loaded (yet)"),!0):(j.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(zi(null)),this.store.dispatch(zn()),new Promise(t=>{let n=this.store.subscribe(()=>{let r=this.store.getState();tt(r)&&e1(r)!=="loading"&&(n(),t())});this.unmountHandlers.push(()=>{n()})})}async isLoggedIn(){return(await this.store.dispatch(zn())).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){j.warn("Failed to attach user:",n)}}async isConversationSupported(t,n){return(await this.store.dispatch(Bg({sessionId:t,options:n}))).payload}async createConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(jc(t))).payload}async getConversationBySessionId(t,n){return this.hasConversation()&&this.sessionId()!==t&&this.resetConversation(),(await this.store.dispatch(zc({sessionId:t,options:n}))).payload}async upsertConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(jg(t))).payload}async postMessages(t){return(await this.store.dispatch(Kc(t))).payload}async updateConversation(t){return(await this.store.dispatch(Vc(t))).payload}resetConversation(){this.store.dispatch(le()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}async getSummary(){let t=await this.store.dispatch(qn());if(t.error)throw new Error(t.error.message);return t.payload.summary}configure(t){this.store.dispatch(Hc(t))}setVisitorInfo(t){this.store.dispatch(O1(t))}async setAgentInfo(t){await this.store.dispatch(La(t))}async setAgentSettings(t){await this.store.dispatch(Kg(t))}async getAgentSettings(){return(await this.store.dispatch(Wg())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let t=[];return this.store.dispatch(Md()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})}notifyInputChanged(t){this.store.dispatch(qc(t))}notifyKeyDown(t){this.store.dispatch(Gc(t))}notifyPaste(t,n){this.store.dispatch(k1({text:t,selectionText:n}))}notifyCut(t){this.store.dispatch(b1(t))}notifyExternalSuggestion(t){this.store.dispatch(En(t)),this.store.dispatch(Kn())}async evaluateRule(t,n={}){let{payload:r,error:o}=await this.store.dispatch(jo({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(Vr({collapse:!1})),this.inputMediator&&this.store.dispatch(S1({text:t,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(xn([])))}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(T1(h1(t))),t.key!=="Tab"&&!this.settings.showTextSuggestions)return;let u=()=>{n||!a||i&&(t.shiftKey||(this.store.dispatch(x1()),s||this.stageSelectedSuggestion({inputType:"arrow"}),t.preventDefault()))},c=()=>{n||!a||s&&o<=0||i&&(t.shiftKey||(this.store.dispatch(C1()),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(Fr(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(Fr(-1)),this.store.dispatch(Aa()),t.preventDefault()):n||(this.store.dispatch(Vr({collapse:!0})),this.store.dispatch(AC(!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(tl(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):!s&&this.settings.showTabCompletion&&g&&g.text.startsWith(d)&&(this.store.dispatch(En({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(P1()),this.store.dispatch(xn([]))}handlingTimeStart(){this.state.handlingTime.startTime||(j.info("Start handling time"),this.store.dispatch(OT()))}handlingTimeStop(){this.state.handlingTime.startTime&&(j.info("Stop handling time"),this.store.dispatch(yf()))}logSendMessage(t){let n=WT("input",this.state,{version:this.version});t&&(Object.assign(n,{text:t}),Object.assign(n,{lenTextTotal:t.length})),this.deepdeskApi.sendEventV1("Send Message",n),this.emit("send-message-event",n)}logHandlingTime(){let t=KT(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",t),this.store.dispatch(MT())}notifySubmit(t={}){this.shouldAbort()||(this.store.dispatch(Kn()),this.store.dispatch(Eo(t.text??this.state.input.text)))}stageSelectedSuggestion(t){let n=this.state.input.selectedSuggestionIndex,{textSuggestions:r}=this.state.input;this.store.dispatch(En({text:r[n].text,suggestion:r[n],eventMetrics:t,replace:"until-selection-end"}))}emit(t,n,r={}){let o=()=>{this.eventListeners[t]&&this.eventListeners[t].forEach(i=>{try{i(n)}catch(s){j.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),j.error(s)}})};this.inputMediator&&r.mayApplyChanges?this.inputMediator.applyChanges(o):o()}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),()=>{this.off(t,n)}}off(t,n){if(!t&&!n){this.eventListeners={};return}let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}setConversationQuery(t){this.dynamicThunkObject.conversationQuery=t}whenConversationLoaded(t){let n=()=>this.loadProfileConfig().then(()=>t());this.hasConversation()&&n();let r=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==r&&(r=this.hasConversation(),r&&n())})}overlayContainerFactory(t,n,r,o){let[i,s]=xl(n,r);return i.setAttribute("translate","no"),i.dataset.testid=t,o&&i.classList.add(o),this.unmountHandlers.push(()=>{(0,Gt.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]=xl(i,{appendTo:document.body,onMoveStart:()=>{o.style.display="none"}});a.dataset.testid=n,a.style.zIndex="2",a.appendChild(r),this.unmountHandlers.push(()=>{(0,Gt.unmountComponentAtNode)(o),l()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return Ho(o),o.dataset.testid=t,o.style.color=r.color,o.style.fontSize=r.fontSize,o.style.fontFamily=r.fontFamily,o.style.fontVariant=r.fontVariant,o.setAttribute("translate","no"),n.appendChild(o),this.unmountHandlers.push(()=>{(0,Gt.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),j.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()?(j.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(A1(r.metrics))):j.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(!Sf(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),Ho(t),this.inputMediator=y||(Wr(t)?new Ko(t):new Vo(t)),this.inputMediator.on("change",({plainText:T})=>{this.notifyInputChanged(T)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(R1({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 w=v&&$T(t,v)||void 0;if(m){let{customStyles:T,appendOverlayTo:C}=n;if(Wr(t))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let k=this.createInlineContainer(t,"deepdesk-caret");(0,Gt.render)((0,Le.jsx)(Bo,{store:this.store,customStyles:T,children:(0,Le.jsx)(bo,{broadcastEvents:this.broadcastEvents,children:(0,Le.jsx)(FC,{})})}),k),this.inputMediator.on("caret",I=>{this.store.dispatch(xn([])),I?(k.style.display="block",k.style.top=`${I.top}px`,k.style.left=`${I.left}px`):k.style.display="none"});let L=this.overlayContainerFactory("floating-menu",w||t,{appendTo:typeof h=="object"&&"appendOverlayTo"in h?h.appendOverlayTo:C},T==null?void 0:T.floatingMenuRootNode);(0,Gt.render)((0,Le.jsx)(Bo,{store:this.store,customStyles:T,children:(0,Le.jsx)(bo,{broadcastEvents:this.broadcastEvents,children:(0,Le.jsx)(kC,{onLogIn:()=>this.loginViaPopup().catch(I=>j.warn(I.message))})})}),L)}else{let T=this.overlayContainerFactory("deepdesk-tab-completion",w||t,{appendTo:f,closestScrollElement:w,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),C=this.overlayContainerFactory("deepdesk-suggestions-overlay",w||t,{appendTo:f},r==null?void 0:r.suggestionsRootNode);(0,Gt.render)((0,Le.jsx)(Bo,{store:this.store,customStyles:r,children:(0,Le.jsx)(bo,{broadcastEvents:this.broadcastEvents,children:(0,Le.jsx)(fb,{inputElement:t})})}),T),(0,Gt.render)((0,Le.jsx)(Bo,{store:this.store,customStyles:r,children:(0,Le.jsx)(bo,{broadcastEvents:this.broadcastEvents,children:(0,Le.jsx)($C,{onLogIn:()=>this.loginViaPopup().catch(k=>j.warn(k.message))})})}),C)}(0,Gt.render)((0,Le.jsx)(Bo,{store:this.store,customStyles:r,children:(0,Le.jsx)(bo,{broadcastEvents:this.broadcastEvents,children:(0,Le.jsx)(xC,{})})}),this.createContainer("deepdesk-overlays"));let x;this.inputMediator.on("selection",T=>{clearTimeout(x),T===null?x=setTimeout(()=>{T!==null&&this.store.dispatch(zg(T))},500):this.store.dispatch(zg(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(Oh(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(Oh(!0))),this.store.dispatch(w1({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&&j.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,Gt.render)((0,Le.jsx)(Bo,{store:this.store,customStyles:r,children:(0,Le.jsx)(bo,{broadcastEvents:this.broadcastEvents,children:(0,Le.jsx)(TT,{onLogIn:()=>this.loginViaPopup().catch(s=>j.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,Gt.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(t){let n=Ef(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){GT(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(Za());let t=Xn(this.state);t&&(await this.store.dispatch(Xa()),this.store.dispatch(Hc({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(Na),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){j.error("Error posting message to popup",v),r(v)}break}case"deepdesk-popup-error":{u(),g.data.message==="Timeout"&&j.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(j.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;j.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=Nd(this.state);try{n.forEach(({type:r})=>{r==="entities"?this.store.dispatch(sn()):["cues"].includes(r)||this.store.dispatch(ln(r))})}catch(r){this.handleError(r)}}};async function ik(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 sk(e,t,n={}){let r=n.replace?Yr(e,n.replace.start,n.replace.end):us(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?Yr(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 w2(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 x2(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 ak(e,t){return!e.contains(t)||t===e?null:t.parentNode===e?t:ak(e,t.parentNode)}async function lk(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?w2(t):x2(t);if(n){let c=l.startContainer===e?e.childNodes[l.startOffset]:l.startContainer,p=ak(e,c)??e.firstChild;e.insertBefore(u,(p==null?void 0:p.nextSibling)??null)}else l.insertNode(u),l.collapse(!1)};return Promise.resolve(i()).then(()=>{if(e.dispatchEvent(new InputEvent("input",{inputType:"insertText",data:t,bubbles:!0,cancelable:!0})),e.focus(),!!o)try{o.scrollIntoView&&o.scrollIntoView({block:"nearest",inline:"nearest"})}finally{o&&o.remove()}})}function uk(e){return e.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}async function ck(e,t,n){await new ir(e).authenticateWithKey(t,n)}async function dk(e){let n=await new fn(e).get("/platform/config/",{version:null,useCache:!0});return J(n)}async function E2(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 fk(e,t){let n=await E2(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 Pk(C2);})();
|
|
30
30
|
/*! Bundled license information:
|