@deepdesk/deepdesk-sdk 14.3.1-beta.0 → 14.3.1-beta.1

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.
@@ -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 Jh=w(T()),TN={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},QE=({className:e,color:t})=>(0,Jh.jsx)("svg",{className:e,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:(0,Jh.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:TN[t||"pink"]})});var XE={root:"dd-LbeUM",text:"dd-Dpfn1",isLoggedIn:"dd-XvHAn",isLoggedOut:"dd-21y-z",icon:"dd-8rLqS",logo:"dd-slXhD",lock:"dd-ByzlR"};var ey={};We(ey,{enUS:()=>kN,nlNL:()=>PN});var kN={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Search"}]},PN={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Zoeken"}]};var Go=w(T()),JE=({onLogIn:e})=>{let t=$(ey),n=U("floatingMenu"),r=U("productName"),o=G(),s=M(dt),i=I("FloatingMenu",XE);if(s===null||n===!1)return null;let a=()=>{s===!0?o(_t(!0)):e()};return(0,Go.jsxs)("button",{className:(0,ZE.default)(i.root,{[i.isLoggedIn]:s,[i.isLoggedOut]:!s}),onClick:a,children:[(0,Go.jsx)("div",{className:i.text,children:t(s?"search":"signin",{productName:r})}),(0,Go.jsxs)("div",{className:i.icon,children:[(0,Go.jsx)(QE,{className:i.logo,color:"pink"}),s===!1&&(0,Go.jsx)(YE,{className:i.lock})]})]})};var ap=w(D());var eC=w(D());function so(e){(0,eC.useEffect)(()=>{let t=n=>{n.isWithinRoot||e(n)};return document.body.addEventListener("mouseup",t),()=>{document.body.removeEventListener("mouseup",t)}},[e])}function Yo(e){e.addEventListener("mouseup",t=>{t.isWithinRoot=!0},!0)}function Fn(e){let{showMidSentenceSuggestions:t,showSuggestionsBeforePattern:n,showSuggestionsAfterPattern:r}=e.settings,{text:o,selection:s}=e.input;return s.start!==s.end?!1:s.end>=o.length?!0:t?n&&new RegExp(n).test(o.substring(s.end))||r&&new RegExp(r).test(o.substring(0,s.end))?!0:n===!1&&r===!1:!1}var RN={showTabHint:!1,inputHasFocus:!1,overlayCollapsed:!1,openOverlayWhenTyping:!1,overlayCollapsedUserOverwrite:!1},rp=({ui:e})=>e.overlayCollapsed,tC=J({name:"ui",initialState:RN,reducers:{setShowTabHint(e,t){e.showTabHint=t.payload},setInputFocus(e,t){e.overlayCollapsedUserOverwrite!==!0&&(t.payload===!0&&(e.overlayCollapsed=!1),e.inputHasFocus=t.payload)},setOverlayCollapsed(e,t){t.payload.collapse===!1&&(e.openOverlayWhenTyping=!1),!(t.payload.skipWhenInputFocus&&e.inputHasFocus)&&(e.overlayCollapsed=t.payload.collapse)},setOpenOverlayWhenTyping(e,t){e.openOverlayWhenTyping=t.payload},setOverlayCollapsedUserOverwrite(e,t){e.overlayCollapsedUserOverwrite=t.payload,e.overlayCollapsed=t.payload}}}),{setShowTabHint:bl,setInputFocus:op,setOverlayCollapsed:io,setOpenOverlayWhenTyping:nC,setOverlayCollapsedUserOverwrite:rC}=tC.actions,oC=tC.reducer;var sp=w(D());var xi=w(D());var sC=w(D());function iC(e,t,n){(0,sC.useEffect)(()=>{let r=e.current;return r?(r.addEventListener(t,n),()=>{r.removeEventListener(t,n)}):()=>{}},[e,t,n])}var aC={root:"dd-1MBCO",actions:"dd--x4cy",badge:"dd-4Fpkz",formattedText:"dd-EzvTB"};var Qo=w(T()),IN=["search","personal-collection-search","search-autocomplete"];function LN(e,t,n,r={}){var s;let o="";return IN.includes(t)?o=rE(Hh(e,n,{stripAgentPart:!0}),(s=r.searchKeywords)!=null?s:[n]):o=Hh(e,n,r),r.placeholders===!0&&(o=oE(o)),o}var ON=()=>{},NN=({selected:e,suggestion:t})=>{let n=U("inlineSuggestions"),r=M(ui),o=U("enableSuggestionFeedback"),s=M(c=>c.input.text),i=G(),a=I("TextSuggestion",aC),l=(0,xi.useRef)(null);(0,xi.useEffect)(()=>{let c=setTimeout(()=>{i(V1({text:t.text,suggestion:t}))},500);return()=>{clearTimeout(c)}},[t]),iC(l,"click",()=>{i(fn({suggestion:t,text:t.text,eventMetrics:{inputType:"mouse"},replace:"until-selection-end"}))});let u=(0,xi.useMemo)(()=>LN(t.text,t.source,r,{stripAgentPart:n,placeholders:!0,searchKeywords:t.searchKeywords}),[n,t.text,t.source,r,t.searchKeywords]);return t.source==="gpt"&&!n?null:(0,Qo.jsxs)("div",{className:a.root,children:[(0,Qo.jsx)(ne,{ref:l,as:"button","data-testid":"suggestions-overlay-item",selected:e,onClick:ON,children:(0,Qo.jsx)(mi,{containerTagName:"div",noWrap:!1,tagName:"span",className:a.formattedText,content:u})}),o&&(0,Qo.jsx)("div",{className:a.actions,children:(0,Qo.jsx)(Jd,{source:"overlay",context:s,suggestion:t})})]})},lC=NN;var ty=w(T()),MN=({suggestions:e,selectedIndex:t,reverse:n})=>{let r=(0,sp.useMemo)(()=>{let o=e.map((s,i)=>(0,ty.jsx)(lC,{index:i,selected:i===t,suggestion:s},`${s.text}-${s.source}`));return n?o.reverse():o},[e,t,n]);return(0,ty.jsx)(sp.Fragment,{children:r})},ip=MN;var uC={root:"dd-PfvRI",paper:"dd-HYlyY"};var El=w(T()),_N=({textSuggestions:e,selectedIndex:t})=>{let n=(0,ap.useRef)(null),r=I("InlineSuggestionsOverlay",uC),o=M(Fn),s=G(),i=M(dt),a=M(li),l=M(rp),u=U("showTextSuggestions");return so(()=>{setTimeout(()=>{s(io({collapse:!0,skipWhenInputFocus:!0}))})}),(0,ap.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||i!==!0||a===!1?null:(0,El.jsx)("div",{className:r.root,"data-variant":"inline",children:(0,El.jsx)("div",{ref:n,className:r.paper,children:(0,El.jsx)(Je,{children:(0,El.jsx)(ip,{suggestions:e,selectedIndex:t})})})})},DN=({input:e})=>({selectedIndex:e.selectedSuggestionIndex,textSuggestions:e.textSuggestions}),cC=tr(DN)(_N);var Cl=w(T()),FN=({children:e})=>{let n=U("locale").replace("-","");return(0,Cl.jsx)(Eh.Provider,{value:n,children:e})},HN=({store:e,customStyles:t={},children:n})=>(0,Cl.jsx)(rh,{store:e,children:(0,Cl.jsx)(FN,{children:(0,Cl.jsx)(Hi.Provider,{value:t,children:n})})}),Xo=HN;var up=w(se()),bi=w(D());var dC=w(D());function pC(e,t){let[n,r]=(0,dC.useState)(()=>{if(typeof window=="undefined")return t;try{let s=window.localStorage.getItem(e);return s?JSON.parse(s):t}catch(s){return H.error(s),t}});return[n,s=>{try{let i=s instanceof Function?s(n):s;r(i),typeof window!="undefined"&&window.localStorage.setItem(e,JSON.stringify(i))}catch(i){H.error(i)}}]}var fC=()=>/Mac/i.test(navigator.platform);var gC=w(se()),dr=w(D());var ny={};We(ny,{enUS:()=>UN,nlNL:()=>zN});var UN={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"}]}]},zN={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 mC={root:"dd-uTPjX",anchor:"dd-C8lsZ",anchorButton:"dd-IoSx9"};var ao=w(T()),ry=(e,t,n)=>r=>(0,ao.jsx)("button",{className:e.anchorButton,type:"button",value:t,onClick:n,children:r},t),BN=({className:e,loginUrl:t,isEmbedded:n,onSnooze:r,onLogIn:o})=>{let s=$(ny),i=Rt(),a=I("Login",mC),l=U("productName"),u=(0,dr.useCallback)(f=>{f.preventDefault(),r&&r(parseInt(f.target.value,10))},[]),c=(0,dr.useCallback)(f=>{f.preventDefault(),i.send(di,!0)},[t]),p=(0,dr.useMemo)(()=>f=>(0,ao.jsx)("a",{onClick:h=>{h.preventDefault(),o()},href:t,className:a.anchor,target:"_blank",rel:"noreferrer",children:f},"login"),[t]),d=(0,dr.useCallback)(f=>(0,ao.jsx)("button",{type:"button",className:a.anchorButton,onClick:c,children:f},"prompt"),[c]),{min:g,hour:y,day:v}=(0,dr.useMemo)(()=>({min:ry(a,60*10,u),hour:ry(a,60*60,u),day:ry(a,60*60*12,u)}),[]);return(0,ao.jsxs)("div",{className:(0,gC.default)(e,a.root),children:[s("loginPlease",{login:n?d:p,productName:l}),r&&(0,ao.jsxs)(dr.Fragment,{children:[(0,ao.jsx)("br",{}),s("snooze",{min:g,hour:y,day:v})]})]})},lp=BN;var hC={root:"dd-DoQhb",text:"dd-Jwnev"};var Tl=w(T()),jN=({title:e})=>{let t=I("SearchTrigger",hC),n=G();return(0,Tl.jsxs)("button",{type:"button",className:t.root,onClick:()=>n(_t(!0)),children:[(0,Tl.jsx)(hi,{}),(0,Tl.jsx)("span",{className:t.text,children:e})]})},yC=jN;var oy={};We(oy,{enUS:()=>VN,nlNL:()=>KN});var VN={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"}]},KN={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 vC={root:"dd-oa7Vc",isInline:"dd-bwk31",toggleButton:"dd-MSB8Z",toggleButtonWrapper:"dd-ZkCzT",toggleButtonWrapperHidden:"dd-Sq66c",isCollapsed:"dd-vkrPk",collapsible:"dd-CWQJe",hints:"dd-IOoo3",hintsHidden:"dd-psVuT",triggers:"dd-toIoo",triggersRight:"dd-mc4l2"};var Te=w(T()),WN=({textSuggestions:e,selectedIndex:t,onLogIn:n})=>{let r=I("SuggestionsOverlay",vC),o=$(oy),s=M(Fn),i=j1(),a=G(),l=(0,bi.useRef)(null),u=U("searchTriggerKey"),c=U("productName"),p=M(rp),d=M(dt),g=M(li),[y,v]=(0,bi.useState)(null),f=U("showSearch"),m=U("showTextSuggestions"),h=U("adminUrl"),S=U("isEmbedded"),[x,E]=pC("dd-snooze-until-ms",0),C=p||x>Date.now(),R=e.filter(Q=>Q.source!=="gpt").length,N=()=>{C&&E(0),a(rC(!C))},_=Q=>{let K=Date.now()+Q*1e3;E(K),H.info(`Snooze until: ${new Date(K)}`),a(io({collapse:!0}))};return(0,bi.useEffect)(()=>{R===0&&v(null)},[e,R]),so(()=>{a(io({collapse:!0,skipWhenInputFocus:!0}))}),d===null||g===!1?null:d===!1?(0,Te.jsxs)("div",{ref:l,className:(0,up.default)(r.root,{[r.isCollapsed]:C}),children:[!C&&(0,Te.jsxs)("div",{className:r.triggers,children:[(0,Te.jsx)("div",{style:{flex:1}}),(0,Te.jsx)("div",{className:r.triggersRight,children:(0,Te.jsx)(ho,{className:r.toggleButton,title:o("collapse"),onClick:N,isCollapsed:!1})})]}),(0,Te.jsx)("div",{className:r.toggleButtonWrapper,children:(0,Te.jsx)(ho,{className:r.toggleButton,title:o("open",{productName:c}),onClick:N,isCollapsed:!0})}),(0,Te.jsx)("div",{className:r.collapsible,children:(0,Te.jsx)(lp,{loginUrl:h,isEmbedded:S,onLogIn:n,onSnooze:_})})]}):!i||!s?null:(0,Te.jsxs)("div",{ref:l,className:(0,up.default)(r.root,{[r.isCollapsed]:C}),children:[!C&&(0,Te.jsxs)("div",{className:r.triggers,children:[(0,Te.jsx)("div",{style:{flex:1},children:f&&(0,Te.jsx)("div",{style:{display:"inline-block"},onFocus:()=>{},onMouseOver:()=>v(o(fC()?"searchHintMac":"searchHintWindows",{searchTriggerKey:u.toUpperCase()})),onMouseLeave:()=>v(null),children:(0,Te.jsx)(yC,{title:o("search")})})}),(0,Te.jsxs)("div",{className:r.triggersRight,onFocus:()=>{},children:[(0,Te.jsx)("div",{className:(0,up.default)(!y&&r.hintsHidden,r.hints),children:y}),(0,Te.jsx)(ho,{className:r.toggleButton,title:o("collapse"),onClick:N,isCollapsed:!1})]})]}),(0,Te.jsx)("div",{className:r.toggleButtonWrapper,children:(0,Te.jsx)(ho,{className:r.toggleButton,title:o("open",{productName:c}),onClick:N,isCollapsed:!0})}),R>0&&m&&(0,Te.jsx)("div",{className:r.collapsible,onFocus:()=>{},children:(0,Te.jsx)(Je,{children:(0,Te.jsx)(ip,{suggestions:e,selectedIndex:t,reverse:!0})})})]})},$N=({input:e})=>({selectedIndex:e.selectedSuggestionIndex,textSuggestions:e.textSuggestions}),SC=tr($N)(WN);var Cp=w(se());var gr=w(D());var Ei=w(D());function cp(e){return e.contentEditable==="true"}function qN(e){let t=0,n=0,r=window.getSelection();if(r.rangeCount!==0){let o=r.getRangeAt(0),s=o.cloneRange();s.selectNodeContents(e),s.setEnd(o.endContainer,o.endOffset),n=s.toString().length,s.selectNodeContents(e),s.setEnd(o.startContainer,o.startOffset),t=s.toString().length}return{selectionStart:t,selectionEnd:n}}function wC(e){let{selectionStart:t,selectionEnd:n}=cp(e)?qN(e):e;return[t,n]}function xC(e){let[,t]=(0,Ei.useState)(),n=(0,Ei.useRef)(null);return n.current=wC(e),(0,Ei.useEffect)(()=>{let r=()=>{var a;let[o,s]=(a=n.current)!=null?a:[],i=wC(e);(!i||o!==i[0]||s!==i[1])&&(n.current=i,t({}))};return e.addEventListener("keyup",r),e.addEventListener("click",r),e.addEventListener("focus",r),document.addEventListener("selectionchange",r),()=>{e.removeEventListener("keyup",r),e.removeEventListener("click",r),e.removeEventListener("focus",r),document.removeEventListener("selectionchange",r)}},[e]),n.current}function bC(e,t){if(!t)return;let n=e,{value:r}=n,[o,s]=t,i=r.match(du);if(!i||i.length===0)return;let a=0;i.find(l=>{let u=r.indexOf(l,a);return o>u&&s<u+l.length?(n.selectionStart=u,n.selectionEnd=u+l.length,!0):(a=u+l.length,!1)})}var EC=w(D()),GN=["div","span","mark","strong","b","i","u","em"];function sy(e,t,n=0){var s;let r=e[e.length-1],o=typeof r=="object"&&r!==null?(s=r.props)==null?void 0:s.tagName:void 0;if(o==="br")return e.pop(),[...e,...t,r];if(GN.includes(o)){let i=Array.isArray(r.props.children)?r.props.children:[r.props.children];return[...e.slice(0,e.length-1),(0,EC.cloneElement)(r,{children:sy(i,t,n+1)})]}return[...e,...t]}function Zo(e){return e.tagName.toLowerCase()==="textarea"}var CC={root:"dd-7-cgW",container:"dd-PsRQ8",agentText:"dd-qnW-V",tabText:"dd-cUHUr",hint:"dd-v7fSg",matchSelection:"dd-8cr8y",focus:"dd-3tr9l",resetIndent:"dd-TvQfZ",matchKeyword:"dd-oJkRD",matchPlaceholder:"dd-QvNoo",hover:"dd--wi0R",hintText:"dd-7gQQh",popover:"dd-xbRu-",popoverRoot:"dd-rA2x8",popoverContentContainer:"dd-JHICl",popoverContent:"dd--mfkC",selectionOptions:"dd-p52wn",selectionOptionsIsHidden:"dd-sSTDp",selectionOptionsButton:"dd-Q6kRY",caret:"dd-jIhc8",popoverSuggestionsRoot:"dd-iFDbL",suggestionsOverlayInputStyles:"dd-zzENA"};var MC=w(se());var Sp=w(D());var Ci=w(D());function TC(e,t){let n;return[(...r)=>{window.cancelAnimationFrame(n);let o=t?t(...r):r;n=window.requestAnimationFrame(()=>{e(...o)})},()=>window.cancelAnimationFrame(n)]}function dp(e){let t=(0,Ci.useRef)(null),[n,r]=(0,Ci.useState)(!1);return(0,Ci.useEffect)(()=>{var c;let o=!1,s=parseFloat((c=window.getComputedStyle(document.body).zoom)!=null?c:"1"),[i,a]=TC((p,d)=>{let g=t.current;if(!g)return;let y=p/s,v=d/s,f=g.getBoundingClientRect(),m=y>f.x&&y<f.x+f.width&&v>f.y&&v<f.y+f.height;m&&!o?(o=!0,r(!0)):!m&&o&&(o=!1,r(!1))},({clientX:p,clientY:d})=>[p,d]),[l,u]=TC(()=>{o=!1,r(!1)});return e.addEventListener("mousemove",i),e.addEventListener("mouseleave",l),()=>{a(),u(),e.removeEventListener("mousemove",i),e.removeEventListener("mouseleave",l)}},[t]),[t,n]}function kC(e){return e.replace(/[.*+^${}()|[\]\\]/g,"\\$&")}function pp(e){return t=>{e.forEach(n=>{typeof n=="function"?n(t):n!=null&&(n.current=t)})}}function PC(e){return e!=null}var ay=w(se()),nn=w(D());var fp=w(D()),YN=["bottom","height","left","right","top","width"],QN=(e={},t={})=>YN.some(n=>e[n]!==t[n]),pr=new Map,RC,AC=()=>{let e=[],t=[];pr.forEach((n,r)=>{if(r instanceof Element&&!r.isConnected){t.push(r);return}let o=r.getBoundingClientRect();QN(o,n.rect)&&(n.rect=o,e.push(n))}),t.forEach(n=>{pr.delete(n)}),e.forEach(n=>{n.callbacks.forEach(r=>r(n.rect))}),RC=window.requestAnimationFrame(AC)};function XN(e,t){return{observe(){let n=pr.size===0;if(pr.has(e)){let r=pr.get(e);r.callbacks.push(t),r.rect&&t(r.rect)}else pr.set(e,{rect:void 0,hasRectChanged:!1,callbacks:[t]});n&&AC()},unobserve(){let n=pr.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||pr.delete(e),pr.size||cancelAnimationFrame(RC)}}}}function iy(e){let[t,n]=(0,fp.useState)(null);return(0,fp.useLayoutEffect)(()=>{if(!e.current)return;let r=XN(e.current,o=>{n(o)});return r.observe(),()=>{r.unobserve()}},[e]),t}var Ti=w(D()),LC=w(Tc());var IC={root:"dd-r-dgo"};var OC=({children:e,parentNode:t})=>{let[n,r]=(0,Ti.useState)(null),o=(0,Ti.useContext)(Hi);return(0,Ti.useLayoutEffect)(()=>{let s=document.createElement("div");return Yo(s),s.classList.add(IC.root),o!=null&&o.portalRootNode&&s.classList.add(o==null?void 0:o.portalRootNode),(t||document.body).appendChild(s),r(s),()=>{s.isConnected&&s.remove()}},[]),n?(0,LC.createPortal)(e,n):null};var Hn={ref:"dd-iz-KP",root:"dd-vEMon",positionAbove:"dd-mUCxM",positionBelow:"dd-7oZI7",positionLeft:"dd-BiWvD",positionRight:"dd-JIWea",alignStart:"dd-5ivu6",alignCenter:"dd-rnVkP",alignEnd:"dd-gZBp4"};var mp=w(T()),gp=(e=!1)=>{let[t,n]=(0,nn.useState)(e),r=(0,nn.useCallback)(()=>n(!0),[]),o=(0,nn.useCallback)(()=>n(!1),[]),s=(0,nn.useCallback)(()=>n(a=>!a),[]),i=(0,nn.useRef)(null);return{opened:t,open:r,close:o,toggle:s,triggerRef:i}};function ly(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 ki=u=>{var c=u,{className:e,triggerRef:t,boundaryRef:n=(0,nn.createRef)(),position:r="above",align:o="center",children:s,toStyle:i=ly,parentNode:a}=c,l=ee(c,["className","triggerRef","boundaryRef","position","align","children","toStyle","parentNode"]);let p=iy(t),d=iy(n),g=(0,nn.useMemo)(()=>i(p,d,0),[p,d]);return(0,mp.jsx)(OC,{parentNode:a,children:(0,mp.jsx)("div",L(k({className:(0,ay.default)(Hn.ref,{[Hn.positionAbove]:r==="above",[Hn.positionBelow]:r==="below",[Hn.positionLeft]:r==="left",[Hn.positionRight]:r==="right",[Hn.alignStart]:o==="start",[Hn.alignCenter]:o==="center",[Hn.alignEnd]:o==="end"}),style:g},l),{role:"dialog",children:(0,mp.jsx)("div",{className:(0,ay.default)(e,Hn.root),children:s})}))})};var NC=w(se()),hp=w(D());var fr={root:"dd-7-cgW",container:"dd-PsRQ8",agentText:"dd-qnW-V",tabText:"dd-cUHUr",hint:"dd-v7fSg",matchSelection:"dd-8cr8y",focus:"dd-3tr9l",resetIndent:"dd-TvQfZ",matchKeyword:"dd-oJkRD",matchPlaceholder:"dd-QvNoo",hover:"dd--wi0R",hintText:"dd-7gQQh",popover:"dd-xbRu-",popoverRoot:"dd-rA2x8",popoverContentContainer:"dd-JHICl",popoverContent:"dd--mfkC",selectionOptions:"dd-p52wn",selectionOptionsIsHidden:"dd-sSTDp",selectionOptionsButton:"dd-Q6kRY",caret:"dd-jIhc8",popoverSuggestionsRoot:"dd-iFDbL",suggestionsOverlayInputStyles:"dd-zzENA"};var uy=w(T()),yp=(0,hp.forwardRef)((o,r)=>{var s=o,{className:e,children:t}=s,n=ee(s,["className","children"]);let i=(0,hp.useRef)(null),a=I("TabCompletion",fr);return(0,uy.jsx)("div",L(k({ref:pp([i,r]),className:(0,NC.default)(e,a.popoverContentContainer)},n),{children:(0,uy.jsx)("div",{className:a.popoverContent,children:t})}))});var lo=w(T()),ZN=e=>t=>{let n=ly(t);return"top"in n&&(n.width=e.width-(t.left-e.left)-10),n},JN=({inputElement:e,boundaryRef:t,inputStyle:n,children:r,suggestion:o})=>{let s=I("TabCompletion",fr),i=gp(),a=(0,Sp.useMemo)(()=>ZN(e.getBoundingClientRect()),[e]),[l,u]=dp(e);return(0,Sp.useEffect)(()=>{u?i.open():i.close()},[u]),(0,lo.jsxs)("span",{children:[(0,lo.jsx)("mark",{ref:pp([l,i.triggerRef]),className:(0,MC.default)(s.matchKeyword,{[s.hover]:u}),"aria-haspopup":"dialog","aria-expanded":i.opened?"true":"false",children:r}),i.opened&&(0,lo.jsx)(ki,{className:s.popover,triggerRef:i.triggerRef,boundaryRef:t,position:"below",align:"start",toStyle:a,children:(0,lo.jsx)(yp,{style:n,children:(0,lo.jsx)("div",{className:s.hintText,children:o})})})]})},vp=class extends ar{constructor(){super(...arguments);this.keywordMatches=[];this.preparedKeywordMatches=[];this.usedKeywordMatches=new Set}onBeforeParse(n,r){return r.keywordMatches&&r.keywordMatches!==this.keywordMatches&&(this.preparedKeywordMatches=r.keywordMatches.map(o=>L(k({},o),{keywordRegex:new RegExp(`\\b${kC(o.keyword)}\\b`,"i")})),this.keywordMatches=r.keywordMatches),this.usedKeywordMatches.clear(),n}match(n){let r=this.preparedKeywordMatches.map(s=>{if(this.usedKeywordMatches.has(s))return null;let i=n.match(s.keywordRegex);if(!i)return null;let a=n.charAt(i.index-1),l=n.charAt(i.index+s.keyword.length);return a==="{"&&l==="}"?null:{index:i.index,length:i[0].length,match:i[0],matchString:i[0],suggestion:s.suggestion,preparedKeywordMatch:s,valid:!0}}).filter(PC);if(r.length===0)return null;let o=r.reduce((s,i)=>i.index<s.index?i:s);return this.usedKeywordMatches.add(o.preparedKeywordMatch),o}replaceWith(n,r){return(0,lo.jsx)(JN,{inputElement:r.inputElement,suggestion:r.suggestion,inputStyle:r.inputStyle,boundaryRef:r.boundaryRef,children:n},`keyword_${r.matchString}_${r.key}`)}asTag(){return"mark"}};var _C=w(se());var cy=w(T()),eM=({inputElement:e,children:t})=>{let n=I("TabCompletion",fr),[r,o]=dp(e);return(0,cy.jsx)("mark",{ref:r,className:(0,_C.default)(n.matchPlaceholder,{[n.hover]:o}),children:t})},wp=class extends ar{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,cy.jsx)(eM,{inputElement:n.inputElement,children:t},`placeholder_${n.matchString}_${n.key}`)}asTag(){return"mark"}};var bp=w(se());var ht=w(D());var dy=w(T()),DC=()=>(0,dy.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,dy.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 uo=w(D());var HC=w(Rh());var FC={root:"dd-ky-Bv",content:"dd-kV5e1"};function xp(e,t,n){var o;let r=((o=e.imageSizes)==null?void 0:o[t])||e.image||n;if(!r)return null;try{return new URL(r).toString()}catch(s){return null}}function py(e){return e.replace("https://www.","").replace("https://","")}var rn=w(T()),tM=3,nM=e=>({image:e.image||"",text:e.text,id:e.id,title:e.title}),rM=({onSelectLink:e,onDismiss:t,placeholder:n,visitUrlText:r,linkCount:o=tM})=>{let s=I("LinkSearch",FC),[i,a]=(0,uo.useState)(""),l=G(),u=M(HE("url")),c=M(cb("URL",nM)),[p,d]=(0,uo.useState)(c.length-1),g=U("fallbackImage"),y=h=>{let S=h.target;a(S.value)},v=(h,S)=>{h.stopPropagation(),h.preventDefault(),window.open(S,"_blank")},f=h=>{var E;let S=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(S),h.code==="ArrowDown"&&d(x),h.code==="Enter"&&e(((E=c[p])==null?void 0:E.text)||i)},m=(0,uo.useCallback)((0,HC.default)(h=>{l(_o({query:h,type:"URL",tags:["link-search"]}))},300),[]);return(0,uo.useEffect)(()=>{i&&m(i)},[i]),(0,uo.useEffect)(()=>()=>{l(Sd())},[]),(0,rn.jsxs)("div",{className:s.root,children:[(0,rn.jsx)(Je,{withDivider:!0,children:(i?c:u).slice(0,o).map((h,S)=>(0,rn.jsx)(ne,{selected:p===S,onClick:()=>e(h.text),"data-testid":"linksearch-suggestion",children:(0,rn.jsxs)(le,{children:[(0,rn.jsx)(le.Image,{src:xp(h,"small",g||void 0),title:h.title||h.text}),(0,rn.jsxs)(le.Content,{className:s.content,cropText:!0,children:[(0,rn.jsx)(le.Title,{children:h.title||py(h.text)}),h.title&&py(h.text)]}),(0,rn.jsx)(ne.Actions,{children:(0,rn.jsx)(ne.ActionButton,{label:r,onClick:x=>v(x,h.text)})})]})},h.text))}),(0,rn.jsx)(nl,{value:i,onChange:y,autoFocus:!0,placeholder:n,onKeyUp:f})]})},UC=rM;var fy={};We(fy,{enUS:()=>oM,nlNL:()=>sM});var oM={insertLink:[{type:0,value:"Insert link"}],linkInputPlaceholder:[{type:0,value:"Search, type or paste link"}],visitUrl:[{type:0,value:"Visit"}]},sM={insertLink:[{type:0,value:"Voeg link toe"}],linkInputPlaceholder:[{type:0,value:"Zoek, typ of plak link"}],visitUrl:[{type:0,value:"Bekijk"}]};var gt=w(T()),iM=(0,ht.forwardRef)((e,t)=>{let n=I("TabCompletion",fr);return(0,gt.jsx)("mark",{ref:t,className:(0,bp.default)(n.matchSelection)},"selection-start")}),aM=({startRef:e,boundaryRef:t,inputStyle:n,inputElement:r,children:o})=>{let s=$(fy),i=I("TabCompletion",fr),a=(0,ht.useRef)(null),l=(0,ht.useRef)(null),[u,c]=(0,ht.useState)(null),p=G(),d=gp(document.activeElement===r),[g]=(0,ht.useState)(()=>document.createRange());d.triggerRef.current=g,(0,ht.useEffect)(()=>()=>g.detach(),[]),(0,ht.useEffect)(()=>{let v=e.current,f=a.current;!v||!f||(g.setStart(v,0),g.setEnd(f,0))},[e.current,a.current]),so(()=>{d.close()});let y=(0,ht.useCallback)(v=>{let f=g.toString(),m=/^http(s?):\/\//.test(v)?v:`https://${v}`;p(fd({text:`[${f}](${m})`,replace:"selection"}))},[]);return(0,gt.jsxs)("span",{children:[(0,gt.jsx)("mark",{ref:a,className:(0,bp.default)(i.matchSelection),"aria-haspopup":"dialog","aria-expanded":d.opened?"true":"false",children:o}),d.opened&&(0,gt.jsx)(ki,{className:i.popoverRoot,triggerRef:d.triggerRef,boundaryRef:t,position:"above",align:"start",children:(0,gt.jsxs)(yp,{style:n,ref:l,children:[(0,gt.jsx)("div",{className:(0,bp.default)(i.selectionOptions,{[i.selectionOptionsIsHidden]:u!==null}),children:(0,gt.jsxs)("button",{type:"button",tabIndex:u===null?-1:void 0,className:i.selectionOptionsButton,onClick:()=>c("insertLink"),children:[(0,gt.jsx)(DC,{}),(0,gt.jsx)("span",{children:"\xA0"}),(0,gt.jsx)("span",{children:s("insertLink")})]})}),u==="insertLink"&&(0,gt.jsx)(UC,{placeholder:s("linkInputPlaceholder"),visitUrlText:s("visitUrl"),onSelectLink:y,onDismiss:()=>{c(null),d.close()}})]})})]},"selection-end")},Ep=class extends ar{constructor(){super(...arguments);this.charCount=0;this.foundIndex=0;this.startRef=null}onBeforeParse(n,r){return this.props=r,this.charCount=0,this.startRef=(0,ht.createRef)(),this.foundIndex=0,n}match(n){if(!this.props||this.props.selection===null||this.foundIndex===2)return null;let[r,o]=this.props.selection;if(r===o)return null;let s=this.foundIndex===0?r:o,i=s>=this.charCount&&s<=this.charCount+n.length?{index:s-this.charCount,length:0,match:"",valid:!0}:null;i&&this.foundIndex++;let a=this.foundIndex===1;return i&&a?this.charCount+=s-this.charCount:this.charCount+=n.length,i?k({isStart:a},i):null}replaceWith(n,r){return r.isStart?(0,gt.jsx)(iM,{ref:this.startRef}):(0,gt.jsx)(aM,{inputElement:r.inputElement,startRef:this.startRef,boundaryRef:r.boundaryRef,inputStyle:r.inputStyle})}asTag(){return"mark"}};var mr=w(T()),lM=({enabled:e,content:t,tabText:n,showTabHint:r,showTabCompletion:o,showStyleSuggestions:s,keywordMatches:i,inputElement:a,source:l})=>{let u=I("TabCompletion",CC),c=U("insertLink"),p=U("showMidSentenceSuggestions"),d=U("inlineSuggestions"),g=xC(a),y=(0,gr.useRef)(null),v=M(dt);(0,gr.useEffect)(()=>{Zo(a)&&g&&bC(a,g)},[g]);let f=(0,gr.useCallback)(S=>{if(!o||!n)return S;let x=[(0,mr.jsx)("span",{className:u.resetIndent,children:"\u200B"},"u200B"),(0,mr.jsx)("span",{"data-testid":"tab-completion",className:(0,Cp.default)(u.tabText,u.resetIndent),"data-source":l,children:n},"tabText")];return r&&x.push((0,mr.jsx)("span",{className:(0,Cp.default)(u.hint,u.resetIndent),children:(0,mr.jsx)(au,{keyCode:"tab"},"tabHint")})),sy(S,x)},[o,n,r]),m=(0,gr.useMemo)(()=>{let S=[];return c&&S.push(new Ep("selection")),S.push(new wp("placeholders")),s&&S.push(new vp("keywords")),S},[d,c,s]),h=(0,gr.useMemo)(()=>{let S=window.getComputedStyle(a);return{"--dd-color":S.color,"--dd-font-size":S.fontSize,"--dd-font-family":S.fontFamily,"--dd-font-variant":S.fontVariant}},[]);return!e||!v?null:(0,mr.jsxs)("div",{ref:S=>{S!=null&&S.parentElement&&(y.current=S==null?void 0:S.parentElement)},className:u.root,style:h,children:[(0,mr.jsx)(mi,{tagName:"span",containerTagName:"div",className:(0,Cp.default)(u.container,u.agentText),disableLineBreaks:Zo(a),content:t||"\u200B",onAfterParse:f,matchers:m,selection:g,keywordMatches:i,inputElement:a,inputStyle:h,boundaryRef:y,inlineSuggestionsOnlyAtEnd:!p}),(0,mr.jsx)("br",{})]})},uM=e=>{var f,m,h;let{input:t,ui:n,settings:r,styleSuggestions:o,conversation:s}=e,i=ci({input:t}),a=(i==null?void 0:i.text)||"",l=(i==null?void 0:i.source)||"",u=(f=t.html)!=null?f:gi(t.text),c=a.indexOf(t.text)===0?a.slice(t.text.length):"",{showTabHint:p}=n,{isSupported:d}=s,{showTabCompletion:g,visible:y,showStyleSuggestions:v}=r;return{showTabHint:p,showStyleSuggestions:v,showTabCompletion:g&&Fn(e),content:u,tabText:c,source:l,keywordMatches:(h=(m=o.list)==null?void 0:m.keywordMatches)!=null?h:[],enabled:y&&d!==!1}},zC=tr(uM)(lM);var ok=w(se()),Pi=w(D());var BC={list:[],fetchState:"idle"},VC=e=>e.autoflows.list||[],jC=e=>t=>{var n;return(n=t.list)==null?void 0:n.find(r=>r.triggerPayload===e)},hr=V("autoflows/getAll",(e,t)=>P(void 0,null,function*(){let{deepdeskBrokerAPI:n}=t.extra;if(!n)throw new Error("Deepdesk Broker not initialized");return n.getAutoflows(e)})),my=V("autoflows/start",(e,t)=>P(void 0,null,function*(){let{dispatch:n}=t,{deepdeskBrokerAPI:r}=t.extra;if(!r)throw new Error("Deepdesk Broker not initialized");yield r.startAutoflowSession(e),yield n(hr(e.platformSessionId))})),gy=V("autoflows/stop",(e,t)=>P(void 0,null,function*(){let{dispatch:n}=t,{deepdeskBrokerAPI:r}=t.extra;if(!r)throw new Error("Deepdesk Broker not initialized");yield r.stopAutoflowSession(e.platformSessionId),yield n(hr(e.platformSessionId))})),cM=J({name:"autoflows",initialState:BC,reducers:{},extraReducers:e=>{e.addCase(my.pending,(t,n)=>{let r=jC(n.meta.arg.triggerPayload)(t);r.state="Started",r.isBusy=!0}),e.addCase(gy.pending,(t,n)=>{let r=jC(n.meta.arg.triggerPayload)(t);r.state="Aborted",r.isBusy=!0}),e.addCase(hr.pending,t=>{t.fetchState="loading"}),e.addCase(hr.rejected,t=>{t.fetchState="error"}),e.addCase(hr.fulfilled,(t,n)=>{t.list=n.payload,t.fetchState="done"}),e.addCase(xe,()=>BC)}}),KC=V("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(hr(e))}),o.on("sessionCompleted",()=>{n(hr(e))})}),WC=V("autoflows/closeStream",(e,t)=>{let{deepdeskBrokerAPI:n}=t.extra;if(!n)throw new Error("Deepdesk Broker not initialized");n.closeStream(e)}),$C=cM.reducer;var qC={list:[],fetchState:"idle",sentSuggestions:[],errorSuggestions:[],answeredSuggestions:[]},GC=e=>e.customMessages.list,YC=e=>t=>!!t.customMessages.sentSuggestions.find(n=>n===e),QC=e=>t=>!!t.customMessages.answeredSuggestions.find(n=>n===e),XC=e=>t=>!!t.customMessages.errorSuggestions.find(n=>n===e),kl=V("customMessages/getAll",(e,t)=>P(void 0,null,function*(){let{deepdeskBrokerAPI:n}=t.extra;if(!n)throw new Error("Deepdesk Broker not initialized");return n.getCustomMessages(e)})),Tp=V("customMessages/send",(e,t)=>P(void 0,null,function*(){let{platformSessionId:n,suggestion:r}=e,{deepdeskBrokerAPI:o}=t.extra;if(!o)throw new Error("Deepdesk Broker not initialized");yield o.sendCustomMessage(n,r)})),kp=V("customMessages/answer",(e,t)=>P(void 0,null,function*(){let{platformSessionId:n,reply:r}=e,{deepdeskBrokerAPI:o}=t.extra;if(!o)throw new Error("Deepdesk Broker not initialized");yield o.answerCustomMessage(n,r)})),ZC=J({name:"customMessages",initialState:qC,reducers:{onCustomMessage(e,t){Array.isArray(t.payload)?e.list=t.payload:e.list=[t.payload]}},extraReducers:e=>{e.addCase(kl.pending,t=>{t.fetchState="loading"}).addCase(kl.rejected,t=>{t.fetchState="error"}).addCase(kl.fulfilled,(t,n)=>{t.fetchState="done",t.list=n.payload||[]}).addCase(Tp.pending,(t,n)=>{t.sentSuggestions.push(n.meta.arg.suggestion.text),t.errorSuggestions=t.errorSuggestions.filter(r=>n.meta.arg.suggestion.text!==r)}).addCase(Tp.rejected,(t,n)=>{let r=t.sentSuggestions.indexOf(n.meta.arg.suggestion.text);t.errorSuggestions.push(...t.sentSuggestions.splice(r,1))}).addCase(kp.pending,(t,n)=>{t.sentSuggestions.push(n.meta.arg.suggestion.text),t.answeredSuggestions.push(n.meta.arg.suggestion.text)}).addCase(kp.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(xe,()=>qC)}}),JC=V("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",s=>{n(ZC.actions.onCustomMessage(s))})}),eT=V("customMessages/closeStream",(e,t)=>{let{deepdeskBrokerAPI:n}=t.extra;if(!n)throw new Error("Deepdesk Broker not initialized");n.closeStream(e)}),tT=ZC.reducer;var dM={token:null,interval:null},hy=V("passwordlessToken/getTemporaryPasswordlessToken",(e,t)=>P(void 0,null,function*(){let{deepdeskAPI:n}=t.extra;return{token:yield n.requestPasswordlessToken()}})),yy=V("passwordlessToken/pollPasswordlessToken",(e={},t)=>{let{interval:n=1e3*60*10}=e,{dispatch:r}=t;return r(hy()),setInterval(()=>r(hy()),n)}),nT=J({name:"passwordlessToken",initialState:dM,reducers:{stopPollPasswordlessToken(e){e.interval&&clearInterval(e.interval),e.interval=null}},extraReducers:e=>{e.addCase(hy.fulfilled,(t,n)=>{t.token=n.payload.token}),e.addCase(yy.fulfilled,(t,n)=>{t.interval=n.payload})}}),{stopPollPasswordlessToken:rT}=nT.actions,oT=nT.reducer;var sT={excludeFromWidget:!1},vy={cues:[],fetchState:"idle"},iT=e=>{var t;return(t=e.rules)==null?void 0:t.cues},pM=Le("rules/resetCues"),Jo=V("rules/evaluate",(e,t)=>P(void 0,null,function*(){var n,r;try{let{deepdeskAPI:o}=t.extra,s=t.getState(),{platformVariables:i}=s.info,a=(n=s.conversation.current)==null?void 0:n.id;if(!a)throw new Error("No current conversation to evaluate rules");if(!(yield o.getAccount()).ruleEngine)throw new Error("Rule engine is not enabled for this account");if(!(yield o.getRules()).filter(d=>d.isEnabled).some(d=>d.label===e.label))throw new Error(`No enabled rules found with label: ${e.label}`);let p=yield o.evaluateRule(e.label,a,k({tags:((r=s.conversation.current)==null?void 0:r.tags)||void 0},e.params));return i&&(p=p.map(d=>L(k({},d),{title:Ye(d.title,i),text:Ye(d.text,i)}))),{cues:p,options:e.options}}catch(o){let s=o.message;return H.warn(s),t.rejectWithValue(s)}})),aT=J({name:"answer",initialState:vy,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)=>{var s;if((s=n.payload.options)!=null&&s.excludeFromWidget){t.fetchState="done";return}let r=n.payload.cues.map(i=>i.rule.id),o=t.cues.filter(i=>!r.includes(i.rule.id));t.fetchState="done",t.cues=[...n.payload.cues,...o]}).addCase(xe,()=>vy).addCase(pM.toString(),()=>vy)}}),{removeCue:lT}=aT.actions,uT=aT.reducer;function fM(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return t}var cT=e=>{let t=iT(e),r=Ub(e).map(o=>({text:o.response,title:o.name,callToAction:o.callToAction,rule:{id:fM(o.code),label:o.code,name:o.name,description:o.name}}));return[...t,...r]};var ST=w(D());var hT=w(se()),yT=w(D());var pT=w(se());var dT={root:"dd-uszkm"};var mT=w(T()),mM=({className:e,children:t})=>{let n=I("Unicode",dT);return(0,mT.jsx)("span",{className:(0,pT.default)(e,n.root),children:t})},fT=mM;var gT={isDisabled:"dd-Sp--t",root:"dd-maqTG",buttonStop:"dd-rcq8w",stateBadge:"dd-zOnkT",isCompleted:"dd-GA-rt",isStarted:"dd-PZwtX",isAborted:"dd-PAXSE"};var Sy={};We(Sy,{enUS:()=>gM,nlNL:()=>hM});var gM={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"}]},hM={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 Ht=w(T()),vM=({disabled:e,state:t,displayName:n,description:r,onStartAutoflow:o,onStopAutoflow:s})=>{let i=I("Autoflow",gT),a=$(Sy),l=t==="Started"?"stop":"start",u=l==="start"?"\u25B6":l==="stop"?"\u25FC":"";return(0,Ht.jsxs)(ne,{className:(0,hT.default)(i.root,{[i.isDisabled]:e,[i.isCompleted]:t==="Completed",[i.isAborted]:t==="Aborted",[i.isStarted]:t==="Started"}),children:[(0,Ht.jsx)(le,{children:(0,Ht.jsxs)(le.Content,{children:[(0,Ht.jsxs)(le.Title,{children:[t&&(0,Ht.jsx)("span",{className:i.stateBadge,children:a(t)}),n]}),(0,Ht.jsx)("span",{children:r})]})}),(0,Ht.jsx)(ne.Actions,{fixed:t==="Started",children:(0,Ht.jsx)(ne.ActionButton,{primary:!0,className:l==="start"?i.buttonStart:i.buttonStop,onClick:t==="Started"?s:o,disabled:e,label:(0,Ht.jsxs)(yT.Fragment,{children:[(0,Ht.jsx)(fT,{children:u})," ",(0,Ht.jsx)("span",{children:a(l)})]})})})]})},vT=vM;var wy=w(T()),SM=(e,t)=>{let n=t.filter(r=>r.state==="Started");return n.length>0?n.indexOf(e)===-1:!1},wM=({autoflows:e,onStartAutoflow:t,onStopAutoflow:n,platformSessionId:r})=>(0,wy.jsx)(ST.Fragment,{children:e.map(o=>(0,wy.jsx)(vT,{displayName:o.displayName,description:o.description,disabled:o.isBusy||SM(o,e),state:o.state,onStartAutoflow:()=>t({platformSessionId:r,triggerPayload:o.triggerPayload}),onStopAutoflow:()=>n({platformSessionId:r,triggerPayload:o.triggerPayload})},o.displayName))}),xM=({autoflows:e,conversation:t})=>{var n;return{autoflows:e.list,platformSessionId:(n=t.current)==null?void 0:n.sessionId}},bM={onStartAutoflow:my,onStopAutoflow:gy},wT=tr(xM,bM)(wM);var xT=w(se()),xy=w(D());var yr={root:"dd-ERsBr",title:"dd-b36p6",isUsed:"dd-fp2IX",quickReplies:"dd--VrvP",quickReply:"dd-wFhWh",label:"dd-R9sND",errorIcon:"dd-8cdcH"};var At=w(T()),EM=({suggestion:e})=>{let t=$($o),n=G(),r=M(YC(e.text)),o=M(QC(e.text)),s=M(XC(e.text)),i=M(ai),{replyOptions:a}=e,l=(0,xy.useCallback)(c=>{c.preventDefault(),c.stopPropagation(),!(r||!i)&&n(Tp({platformSessionId:i,suggestion:e}))},[e,r,n,i]),u=(0,xy.useCallback)(c=>{if(c.preventDefault(),c.stopPropagation(),!i||!a)return;let p=parseInt(c.target.dataset.index,10),d=a[p];n(kp({platformSessionId:i,reply:d,suggestion:e}))},[e,r,n,i]);return(0,At.jsxs)(ne,{onClick:l,className:(0,xT.default)(yr.root,{[yr.isUsed]:r,[yr.hasError]:s}),children:[(0,At.jsx)(le,{children:(0,At.jsxs)(le.Content,{children:[(0,At.jsxs)(le.Title,{className:yr.title,children:[e.text," ",(0,At.jsx)(lu,{className:yr.label,children:"analyse tool"})," ",s&&(0,At.jsx)("span",{className:yr.errorIcon,role:"img","aria-label":t("sendingError"),title:t("sendingError"),children:"!"})]}),a&&a.length>0&&(0,At.jsx)("ul",{className:yr.quickReplies,children:a.map(c=>(0,At.jsx)("li",{className:yr.quickReply,children:c.title},c.title))})]})}),(0,At.jsxs)(ne.Actions,{fixed:s||r,children:[a&&a.length>0&&(0,At.jsx)(ne.DropdownButton,{label:t("answer"),disabled:o,children:a.map((c,p)=>(0,At.jsx)(ne.DropdownItem,{index:p,label:c.title,onClick:u},c.title))}),(0,At.jsx)(ne.ActionButton,{primary:!0,disabled:r,onClick:l,label:t(r?"suggestionSent":s?"tryAgain":"sendSuggestion")})]})]})},bT=EM;var Pp=w(D());var Ey=w(se());var by=w(T()),Pl=()=>(0,by.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 512 512",xmlns:"http://www.w3.org/2000/svg",children:(0,by.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 ET={root:"dd-WcEru",entity:"dd-LfP8y",entityText:"dd-L-v0f",iconWrapper:"dd-9Deh1",icon:"dd-tM7E2",iconClicked:"dd-EEdDL"};var Un=w(T()),CM=({entities:e})=>{let t=I("EntitiesWidgetList",ET),[n,r]=(0,Pp.useState)(void 0),o=G(),s=()=>{r(void 0)},i=a=>{e&&(r(e.indexOf(a)),yn(a.text),o(pt({name:"entity copied",data:{entity:a,type:"copy"}})))};return(0,Pp.useEffect)(()=>{let a=setTimeout(s,500);return()=>{clearTimeout(a)}},[n]),!e||e.length===0?null:(0,Un.jsx)("div",{className:t.root,"data-testid":"widget-entities-list",children:e.map((a,l)=>(0,Un.jsxs)("button",{title:a.text,className:t.entity,type:"button",onClick:()=>i(a),children:[(0,Un.jsx)("span",{className:t.entityText,children:a.text}),(0,Un.jsxs)("span",{className:t.iconWrapper,children:[(0,Un.jsx)("span",{className:(0,Ey.default)(t.icon),children:(0,Un.jsx)(Pl,{})}),(0,Un.jsx)("span",{className:(0,Ey.default)(t.icon,n===l&&t.iconClicked),children:(0,Un.jsx)(Pl,{})})]})]},a.text))})},CT=CM;var Cy=w(T()),TT=()=>(0,Cy.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:(0,Cy.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 Ty=w(T()),kT=()=>(0,Ty.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:(0,Ty.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 ky=w(T()),PT=()=>(0,ky.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:(0,ky.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 $T=w(D());var{entries:FT,setPrototypeOf:RT,isFrozen:TM,getPrototypeOf:kM,getOwnPropertyDescriptor:PM}=Object,{freeze:vt,seal:on,create:HT}=Object,{apply:Oy,construct:Ny}=typeof Reflect!="undefined"&&Reflect;vt||(vt=function(t){return t});on||(on=function(t){return t});Oy||(Oy=function(t,n,r){return t.apply(n,r)});Ny||(Ny=function(t,n){return new t(...n)});var Rp=It(Array.prototype.forEach),AT=It(Array.prototype.pop),Rl=It(Array.prototype.push),Lp=It(String.prototype.toLowerCase),Py=It(String.prototype.toString),IT=It(String.prototype.match),Al=It(String.prototype.replace),RM=It(String.prototype.indexOf),AM=It(String.prototype.trim),bn=It(Object.prototype.hasOwnProperty),yt=It(RegExp.prototype.test),Il=IM(TypeError),LT=It(Number.isNaN);function It(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 Oy(e,t,r)}}function IM(e){return function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];return Ny(e,n)}}function te(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Lp;RT&&RT(e,null);let r=t.length;for(;r--;){let o=t[r];if(typeof o=="string"){let s=n(o);s!==o&&(TM(t)||(t[r]=s),o=s)}e[o]=!0}return e}function LM(e){for(let t=0;t<e.length;t++)bn(e,t)||(e[t]=null);return e}function ts(e){let t=HT(null);for(let[n,r]of FT(e))bn(e,n)&&(Array.isArray(r)?t[n]=LM(r):r&&typeof r=="object"&&r.constructor===Object?t[n]=ts(r):t[n]=r);return t}function Ap(e,t){for(;e!==null;){let r=PM(e,t);if(r){if(r.get)return It(r.get);if(typeof r.value=="function")return It(r.value)}e=kM(e)}function n(){return null}return n}var OT=vt(["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"]),Ry=vt(["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"]),Ay=vt(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),OM=vt(["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"]),Iy=vt(["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"]),NM=vt(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),NT=vt(["#text"]),MT=vt(["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","wrap","xmlns","slot"]),Ly=vt(["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"]),_T=vt(["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"]),Ip=vt(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),MM=on(/\{\{[\w\W]*|[\w\W]*\}\}/gm),_M=on(/<%[\w\W]*|[\w\W]*%>/gm),DM=on(/\${[\w\W]*}/gm),FM=on(/^data-[\-\w.\u00B7-\uFFFF]/),HM=on(/^aria-[\-\w]+$/),UT=on(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),UM=on(/^(?:\w+script|data):/i),zM=on(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),zT=on(/^html$/i),BM=on(/^[a-z][.\w]*(-[.\w]+)+$/i),DT=Object.freeze({__proto__:null,MUSTACHE_EXPR:MM,ERB_EXPR:_M,TMPLIT_EXPR:DM,DATA_ATTR:FM,ARIA_ATTR:HM,IS_ALLOWED_URI:UT,IS_SCRIPT_OR_DATA:UM,ATTR_WHITESPACE:zM,DOCTYPE_NAME:zT,CUSTOM_ELEMENT:BM}),es={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,progressingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},jM=function(){return typeof window=="undefined"?null:window},VM=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 s="dompurify"+(r?"#"+r:"");try{return t.createPolicy(s,{createHTML(i){return i},createScriptURL(i){return i}})}catch(i){return console.warn("TrustedTypes policy "+s+" could not be created."),null}};function BT(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:jM(),t=B=>BT(B);if(t.version="3.1.3",t.removed=[],!e||!e.document||e.document.nodeType!==es.document)return t.isSupported=!1,t;let{document:n}=e,r=n,o=r.currentScript,{DocumentFragment:s,HTMLTemplateElement:i,Node:a,Element:l,NodeFilter:u,NamedNodeMap:c=e.NamedNodeMap||e.MozNamedAttrMap,HTMLFormElement:p,DOMParser:d,trustedTypes:g}=e,y=l.prototype,v=Ap(y,"cloneNode"),f=Ap(y,"nextSibling"),m=Ap(y,"childNodes"),h=Ap(y,"parentNode");if(typeof i=="function"){let B=n.createElement("template");B.content&&B.content.ownerDocument&&(n=B.content.ownerDocument)}let S,x="",{implementation:E,createNodeIterator:C,createDocumentFragment:R,getElementsByTagName:N}=n,{importNode:_}=r,Q={};t.isSupported=typeof FT=="function"&&typeof h=="function"&&E&&E.createHTMLDocument!==void 0;let{MUSTACHE_EXPR:K,ERB_EXPR:W,TMPLIT_EXPR:fe,DATA_ATTR:Xe,ARIA_ATTR:Ut,IS_SCRIPT_OR_DATA:is,ATTR_WHITESPACE:zt,CUSTOM_ELEMENT:Tn}=DT,{IS_ALLOWED_URI:Er}=DT,be=null,j=te({},[...OT,...Ry,...Ay,...Iy,...NT]),X=null,St=te({},[...MT,...Ly,..._T,...Ip]),de=Object.seal(HT(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}})),Re=null,me=null,as=!0,ls=!0,Wl=!1,fo=!0,kn=!1,$l=!0,Ue=!1,jn=!1,Kp=!1,us=!1,ql=!1,Gl=!1,Xy=!0,Zy=!1,Qk="user-content-",Wp=!0,Ni=!1,cs={},ds=null,Jy=te({},["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"]),ev=null,tv=te({},["audio","video","img","source","image","track"]),$p=null,nv=te({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Yl="http://www.w3.org/1998/Math/MathML",Ql="http://www.w3.org/2000/svg",Vn="http://www.w3.org/1999/xhtml",ps=Vn,qp=!1,Gp=null,Xk=te({},[Yl,Ql,Vn],Py),Mi=null,Zk=["application/xhtml+xml","text/html"],Jk="text/html",ze=null,fs=null,rv=255,eP=n.createElement("form"),ov=function(b){return b instanceof RegExp||b instanceof Function},Yp=function(){let b=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(fs&&fs===b)){if((!b||typeof b!="object")&&(b={}),b=ts(b),Mi=Zk.indexOf(b.PARSER_MEDIA_TYPE)===-1?Jk:b.PARSER_MEDIA_TYPE,ze=Mi==="application/xhtml+xml"?Py:Lp,be=bn(b,"ALLOWED_TAGS")?te({},b.ALLOWED_TAGS,ze):j,X=bn(b,"ALLOWED_ATTR")?te({},b.ALLOWED_ATTR,ze):St,Gp=bn(b,"ALLOWED_NAMESPACES")?te({},b.ALLOWED_NAMESPACES,Py):Xk,$p=bn(b,"ADD_URI_SAFE_ATTR")?te(ts(nv),b.ADD_URI_SAFE_ATTR,ze):nv,ev=bn(b,"ADD_DATA_URI_TAGS")?te(ts(tv),b.ADD_DATA_URI_TAGS,ze):tv,ds=bn(b,"FORBID_CONTENTS")?te({},b.FORBID_CONTENTS,ze):Jy,Re=bn(b,"FORBID_TAGS")?te({},b.FORBID_TAGS,ze):{},me=bn(b,"FORBID_ATTR")?te({},b.FORBID_ATTR,ze):{},cs=bn(b,"USE_PROFILES")?b.USE_PROFILES:!1,as=b.ALLOW_ARIA_ATTR!==!1,ls=b.ALLOW_DATA_ATTR!==!1,Wl=b.ALLOW_UNKNOWN_PROTOCOLS||!1,fo=b.ALLOW_SELF_CLOSE_IN_ATTR!==!1,kn=b.SAFE_FOR_TEMPLATES||!1,$l=b.SAFE_FOR_XML!==!1,Ue=b.WHOLE_DOCUMENT||!1,us=b.RETURN_DOM||!1,ql=b.RETURN_DOM_FRAGMENT||!1,Gl=b.RETURN_TRUSTED_TYPE||!1,Kp=b.FORCE_BODY||!1,Xy=b.SANITIZE_DOM!==!1,Zy=b.SANITIZE_NAMED_PROPS||!1,Wp=b.KEEP_CONTENT!==!1,Ni=b.IN_PLACE||!1,Er=b.ALLOWED_URI_REGEXP||UT,ps=b.NAMESPACE||Vn,de=b.CUSTOM_ELEMENT_HANDLING||{},b.CUSTOM_ELEMENT_HANDLING&&ov(b.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(de.tagNameCheck=b.CUSTOM_ELEMENT_HANDLING.tagNameCheck),b.CUSTOM_ELEMENT_HANDLING&&ov(b.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(de.attributeNameCheck=b.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),b.CUSTOM_ELEMENT_HANDLING&&typeof b.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(de.allowCustomizedBuiltInElements=b.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),kn&&(ls=!1),ql&&(us=!0),cs&&(be=te({},NT),X=[],cs.html===!0&&(te(be,OT),te(X,MT)),cs.svg===!0&&(te(be,Ry),te(X,Ly),te(X,Ip)),cs.svgFilters===!0&&(te(be,Ay),te(X,Ly),te(X,Ip)),cs.mathMl===!0&&(te(be,Iy),te(X,_T),te(X,Ip))),b.ADD_TAGS&&(be===j&&(be=ts(be)),te(be,b.ADD_TAGS,ze)),b.ADD_ATTR&&(X===St&&(X=ts(X)),te(X,b.ADD_ATTR,ze)),b.ADD_URI_SAFE_ATTR&&te($p,b.ADD_URI_SAFE_ATTR,ze),b.FORBID_CONTENTS&&(ds===Jy&&(ds=ts(ds)),te(ds,b.FORBID_CONTENTS,ze)),Wp&&(be["#text"]=!0),Ue&&te(be,["html","head","body"]),be.table&&(te(be,["tbody"]),delete Re.tbody),b.TRUSTED_TYPES_POLICY){if(typeof b.TRUSTED_TYPES_POLICY.createHTML!="function")throw Il('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof b.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw Il('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');S=b.TRUSTED_TYPES_POLICY,x=S.createHTML("")}else S===void 0&&(S=VM(g,o)),S!==null&&typeof x=="string"&&(x=S.createHTML(""));vt&&vt(b),fs=b}},sv=te({},["mi","mo","mn","ms","mtext"]),iv=te({},["foreignobject","annotation-xml"]),tP=te({},["title","style","font","a","script"]),av=te({},[...Ry,...Ay,...OM]),lv=te({},[...Iy,...NM]),nP=function(b){let A=h(b);(!A||!A.tagName)&&(A={namespaceURI:ps,tagName:"template"});let z=Lp(b.tagName),Z=Lp(A.tagName);return Gp[b.namespaceURI]?b.namespaceURI===Ql?A.namespaceURI===Vn?z==="svg":A.namespaceURI===Yl?z==="svg"&&(Z==="annotation-xml"||sv[Z]):!!av[z]:b.namespaceURI===Yl?A.namespaceURI===Vn?z==="math":A.namespaceURI===Ql?z==="math"&&iv[Z]:!!lv[z]:b.namespaceURI===Vn?A.namespaceURI===Ql&&!iv[Z]||A.namespaceURI===Yl&&!sv[Z]?!1:!lv[z]&&(tP[z]||!av[z]):!!(Mi==="application/xhtml+xml"&&Gp[b.namespaceURI]):!1},Bt=function(b){Rl(t.removed,{element:b});try{b.parentNode.removeChild(b)}catch(A){b.remove()}},Xl=function(b,A){try{Rl(t.removed,{attribute:A.getAttributeNode(b),from:A})}catch(z){Rl(t.removed,{attribute:null,from:A})}if(A.removeAttribute(b),b==="is"&&!X[b])if(us||ql)try{Bt(A)}catch(z){}else try{A.setAttribute(b,"")}catch(z){}},uv=function(b){let A=null,z=null;if(Kp)b="<remove></remove>"+b;else{let Ke=IT(b,/^[\r\n\t ]+/);z=Ke&&Ke[0]}Mi==="application/xhtml+xml"&&ps===Vn&&(b='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+b+"</body></html>");let Z=S?S.createHTML(b):b;if(ps===Vn)try{A=new d().parseFromString(Z,Mi)}catch(Ke){}if(!A||!A.documentElement){A=E.createDocument(ps,"template",null);try{A.documentElement.innerHTML=qp?x:Z}catch(Ke){}}let Ze=A.body||A.documentElement;return b&&z&&Ze.insertBefore(n.createTextNode(z),Ze.childNodes[0]||null),ps===Vn?N.call(A,Ue?"html":"body")[0]:Ue?A.documentElement:Ze},cv=function(b){return C.call(b.ownerDocument||b,b,u.SHOW_ELEMENT|u.SHOW_COMMENT|u.SHOW_TEXT|u.SHOW_PROCESSING_INSTRUCTION|u.SHOW_CDATA_SECTION,null)},dv=function(b){return b instanceof p&&(typeof b.__depth!="undefined"&&typeof b.__depth!="number"||typeof b.__removalCount!="undefined"&&typeof b.__removalCount!="number"||typeof b.nodeName!="string"||typeof b.textContent!="string"||typeof b.removeChild!="function"||!(b.attributes instanceof c)||typeof b.removeAttribute!="function"||typeof b.setAttribute!="function"||typeof b.namespaceURI!="string"||typeof b.insertBefore!="function"||typeof b.hasChildNodes!="function")},pv=function(b){return typeof a=="function"&&b instanceof a},Kn=function(b,A,z){Q[b]&&Rp(Q[b],Z=>{Z.call(t,A,z,fs)})},fv=function(b){let A=null;if(Kn("beforeSanitizeElements",b,null),dv(b))return Bt(b),!0;let z=ze(b.nodeName);if(Kn("uponSanitizeElement",b,{tagName:z,allowedTags:be}),b.hasChildNodes()&&!pv(b.firstElementChild)&&yt(/<[/\w]/g,b.innerHTML)&&yt(/<[/\w]/g,b.textContent)||b.nodeType===es.progressingInstruction||$l&&b.nodeType===es.comment&&yt(/<[/\w]/g,b.data))return Bt(b),!0;if(!be[z]||Re[z]){if(!Re[z]&&gv(z)&&(de.tagNameCheck instanceof RegExp&&yt(de.tagNameCheck,z)||de.tagNameCheck instanceof Function&&de.tagNameCheck(z)))return!1;if(Wp&&!ds[z]){let Z=h(b)||b.parentNode,Ze=m(b)||b.childNodes;if(Ze&&Z){let Ke=Ze.length;for(let wt=Ke-1;wt>=0;--wt){let xt=v(Ze[wt],!0);xt.__removalCount=(b.__removalCount||0)+1,Z.insertBefore(xt,f(b))}}}return Bt(b),!0}return b instanceof l&&!nP(b)||(z==="noscript"||z==="noembed"||z==="noframes")&&yt(/<\/no(script|embed|frames)/i,b.innerHTML)?(Bt(b),!0):(kn&&b.nodeType===es.text&&(A=b.textContent,Rp([K,W,fe],Z=>{A=Al(A,Z," ")}),b.textContent!==A&&(Rl(t.removed,{element:b.cloneNode()}),b.textContent=A)),Kn("afterSanitizeElements",b,null),!1)},mv=function(b,A,z){if(Xy&&(A==="id"||A==="name")&&(z in n||z in eP||z==="__depth"||z==="__removalCount"))return!1;if(!(ls&&!me[A]&&yt(Xe,A))){if(!(as&&yt(Ut,A))){if(!X[A]||me[A]){if(!(gv(b)&&(de.tagNameCheck instanceof RegExp&&yt(de.tagNameCheck,b)||de.tagNameCheck instanceof Function&&de.tagNameCheck(b))&&(de.attributeNameCheck instanceof RegExp&&yt(de.attributeNameCheck,A)||de.attributeNameCheck instanceof Function&&de.attributeNameCheck(A))||A==="is"&&de.allowCustomizedBuiltInElements&&(de.tagNameCheck instanceof RegExp&&yt(de.tagNameCheck,z)||de.tagNameCheck instanceof Function&&de.tagNameCheck(z))))return!1}else if(!$p[A]){if(!yt(Er,Al(z,zt,""))){if(!((A==="src"||A==="xlink:href"||A==="href")&&b!=="script"&&RM(z,"data:")===0&&ev[b])){if(!(Wl&&!yt(is,Al(z,zt,"")))){if(z)return!1}}}}}}return!0},gv=function(b){return b!=="annotation-xml"&&IT(b,Tn)},hv=function(b){Kn("beforeSanitizeAttributes",b,null);let{attributes:A}=b;if(!A)return;let z={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:X},Z=A.length;for(;Z--;){let Ze=A[Z],{name:Ke,namespaceURI:wt,value:xt}=Ze,_i=ze(Ke),lt=Ke==="value"?xt:AM(xt);if(z.attrName=_i,z.attrValue=lt,z.keepAttr=!0,z.forceKeepAttr=void 0,Kn("uponSanitizeAttribute",b,z),lt=z.attrValue,z.forceKeepAttr||(Xl(Ke,b),!z.keepAttr))continue;if(!fo&&yt(/\/>/i,lt)){Xl(Ke,b);continue}if($l&&yt(/((--!?|])>)|<\/(style|title)/i,lt)){Xl(Ke,b);continue}kn&&Rp([K,W,fe],vv=>{lt=Al(lt,vv," ")});let yv=ze(b.nodeName);if(mv(yv,_i,lt)){if(Zy&&(_i==="id"||_i==="name")&&(Xl(Ke,b),lt=Qk+lt),S&&typeof g=="object"&&typeof g.getAttributeType=="function"&&!wt)switch(g.getAttributeType(yv,_i)){case"TrustedHTML":{lt=S.createHTML(lt);break}case"TrustedScriptURL":{lt=S.createScriptURL(lt);break}}try{wt?b.setAttributeNS(wt,Ke,lt):b.setAttribute(Ke,lt),dv(b)?Bt(b):AT(t.removed)}catch(vv){}}}Kn("afterSanitizeAttributes",b,null)},rP=function B(b){let A=null,z=cv(b);for(Kn("beforeSanitizeShadowDOM",b,null);A=z.nextNode();){if(Kn("uponSanitizeShadowNode",A,null),fv(A))continue;let Z=h(A);A.nodeType===es.element&&(Z&&Z.__depth?A.__depth=(A.__removalCount||0)+Z.__depth+1:A.__depth=1),(A.__depth>=rv||A.__depth<0||LT(A.__depth))&&Bt(A),A.content instanceof s&&(A.content.__depth=A.__depth,B(A.content)),hv(A)}Kn("afterSanitizeShadowDOM",b,null)};return t.sanitize=function(B){let b=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},A=null,z=null,Z=null,Ze=null;if(qp=!B,qp&&(B="<!-->"),typeof B!="string"&&!pv(B))if(typeof B.toString=="function"){if(B=B.toString(),typeof B!="string")throw Il("dirty is not a string, aborting")}else throw Il("toString is not a function");if(!t.isSupported)return B;if(jn||Yp(b),t.removed=[],typeof B=="string"&&(Ni=!1),Ni){if(B.nodeName){let xt=ze(B.nodeName);if(!be[xt]||Re[xt])throw Il("root node is forbidden and cannot be sanitized in-place")}}else if(B instanceof a)A=uv("<!---->"),z=A.ownerDocument.importNode(B,!0),z.nodeType===es.element&&z.nodeName==="BODY"||z.nodeName==="HTML"?A=z:A.appendChild(z);else{if(!us&&!kn&&!Ue&&B.indexOf("<")===-1)return S&&Gl?S.createHTML(B):B;if(A=uv(B),!A)return us?null:Gl?x:""}A&&Kp&&Bt(A.firstChild);let Ke=cv(Ni?B:A);for(;Z=Ke.nextNode();){if(fv(Z))continue;let xt=h(Z);Z.nodeType===es.element&&(xt&&xt.__depth?Z.__depth=(Z.__removalCount||0)+xt.__depth+1:Z.__depth=1),(Z.__depth>=rv||Z.__depth<0||LT(Z.__depth))&&Bt(Z),Z.content instanceof s&&(Z.content.__depth=Z.__depth,rP(Z.content)),hv(Z)}if(Ni)return B;if(us){if(ql)for(Ze=R.call(A.ownerDocument);A.firstChild;)Ze.appendChild(A.firstChild);else Ze=A;return(X.shadowroot||X.shadowrootmode)&&(Ze=_.call(r,Ze,!0)),Ze}let wt=Ue?A.outerHTML:A.innerHTML;return Ue&&be["!doctype"]&&A.ownerDocument&&A.ownerDocument.doctype&&A.ownerDocument.doctype.name&&yt(zT,A.ownerDocument.doctype.name)&&(wt="<!DOCTYPE "+A.ownerDocument.doctype.name+`>
24
24
  `+wt),kn&&Rp([K,W,fe],xt=>{wt=Al(wt,xt," ")}),S&&Gl?S.createHTML(wt):wt},t.setConfig=function(){let B=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Yp(B),jn=!0},t.clearConfig=function(){fs=null,jn=!1},t.isValidAttribute=function(B,b,A){fs||Yp({});let z=ze(B),Z=ze(b);return mv(z,Z,A)},t.addHook=function(B,b){typeof b=="function"&&(Q[B]=Q[B]||[],Rl(Q[B],b))},t.removeHook=function(B){if(Q[B])return AT(Q[B])},t.removeHooks=function(B){Q[B]&&(Q[B]=[])},t.removeAllHooks=function(){Q={}},t}var jT=BT();var vr=w(D());var KM={"":["<em>","</em>"],_:["<strong>","</strong>"],"*":["<strong>","</strong>"],"~":["<s>","</s>"],"\n":["<br />"]," ":["<br />"],"-":["<hr />"]};function VT(e){return e.replace(RegExp("^"+(e.match(/^(\t| )+/)||"")[0],"gm"),"")}function Ll(e){return(e+"").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Ol(e,t){var n,r,o,s,i,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=KM[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(/[^\\](\\\\)*\\$/)||((i=o[3]||o[4])?n='<pre class="code '+(o[4]?"poetry":o[2].toLowerCase())+'"><code'+(o[2]?' class="language-'+o[2].toLowerCase()+'"':"")+">"+VT(Ll(i).replace(/^\n+|\n+$/g,""))+"</code></pre>":(i=o[6])?(i.match(/\./)&&(o[5]=o[5].replace(/^\d+/gm,"")),s=Ol(VT(o[5].replace(/^\s*[>*+.-]/gm,""))),i==">"?i="blockquote":(i=i.match(/\./)?"ol":"ul",s=s.replace(/^(.*)(\n|$)/gm,"<li>$1</li>")),n="<"+i+">"+s+"</"+i+">"):o[8]?n='<img src="'+Ll(o[8])+'" alt="'+Ll(o[7])+'">':o[10]?(u=u.replace("<a>",'<a href="'+Ll(o[11]||c[r.toLowerCase()])+'">'),n=g()+"</a>"):o[9]?n="<a>":o[12]||o[14]?n="<"+(i="h"+(o[14]?o[14].length:o[13]>"="?1:2))+">"+Ol(o[12]||o[15],c)+"</"+i+">":o[16]?n="<code>"+Ll(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 KT={root:"dd-L7b3z",popover:"dd-OQOTB",options:"dd-Y12RE",arrow:"dd-cv33T",copyIcon:"dd-6xOsH",option:"dd-9oFX4",divider:"dd-aiZf8",fadeup:"dd-Jq9pd"};var En=w(T());function WM(e){return`<button type="button" data-copy-icon 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){var n;let t=e.cloneNode(!0);return t.querySelectorAll("div,button").forEach(r=>r.remove()),(n=t.textContent)!=null?n:""}function $M(e){return e.replace(/\r\n/g,`
25
- `)}var qM=({content:e,useLabel:t,copyLabel:n,onCopy:r,onUse:o})=>{let s=I("Markdown",KT),i=(0,vr.useRef)(null),[a,l]=(0,vr.useState)(null),u=(0,vr.useMemo)(()=>{let v=Ol($M(e));return jT.sanitize(v).replaceAll("</code>",`${WM(s.copyIcon)}</code>`).replaceAll('<a href="','<a target="_blank" rel="noreferrer noopener" href="')},[e]),c=v=>{var h;let f=v.target,m=!!((h=i.current)!=null&&h.querySelector("code"));if(["A","BUTTON"].includes(f.tagName)){l(null);return}a||m&&f.tagName!=="CODE"||!m&&f!==i.current||(f.addEventListener("mouseleave",()=>l(null),{once:!0}),l(f))},p=()=>{if(!a)return;l(null);let v=a.querySelector("button");v&&(Si(v,s.fadeup),r(My(a)))},d=v=>{let f=v.target;if(f.tagName==="A"){v.stopPropagation();return}"copyIcon"in f.dataset&&(Si(f,s.fadeup),r(My(f.parentElement)))},g=()=>{!a||!o||(l(null),o(My(a)))},y=v=>{if(v===null)return;let f=v.getBoundingClientRect();f.left<0?v.style.transform=`translateX(${-f.left+2}px)`:f.right>window.innerWidth&&(v.style.transform=`translateX(${window.innerWidth-f.right-2}px)`)};return(0,En.jsxs)(vr.Fragment,{children:[a&&(0,En.jsxs)(ki,{triggerRef:{current:a},className:s.popover,parentNode:a,children:[(0,En.jsxs)("div",{className:s.options,ref:y,children:[(0,En.jsx)("button",{type:"button",className:s.option,onClick:p,children:n}),o&&(0,En.jsxs)(vr.Fragment,{children:[(0,En.jsx)("div",{className:s.divider}),(0,En.jsx)("button",{type:"button",className:s.option,onClick:g,children:t})]})]}),(0,En.jsx)("div",{className:s.arrow})]}),(0,En.jsx)("div",{ref:i,className:s.root,dangerouslySetInnerHTML:{__html:u},onMouseOver:c,onClick:d})]})},Op=qM;var _y={};We(_y,{enUS:()=>GM,nlNL:()=>YM});var GM={useCue:[{type:0,value:"Add to message"}],copyCue:[{type:0,value:"Copy"}],removeCue:[{type:0,value:"Close"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}]},YM={useCue:[{type:0,value:"Voeg toe aan bericht"}],copyCue:[{type:0,value:"Kopi\xEBren"}],removeCue:[{type:0,value:"Sluiten"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}]};var WT={title:"dd-YBHrC",fadeup:"dd-cRM0K",fadedown:"dd-7D4Pq",selected:"dd-bueui",actions:"dd-9Iqn9",thumbsUp:"dd-6QwVx",thumbsDown:"dd-d3E8l"};var sn=w(T()),QM=({cue:e,onCallToAction:t,onRemove:n,onCopy:r,onUse:o})=>{let s=I("WidgetCue",WT),i=$(_y),a=ro(),l=U("hasKeyboardInput"),u=()=>{t&&t(e),n(e)},c=g=>{r&&r(g,e)},p=g=>{o&&o(g,e)},d=g=>{g.preventDefault(),g.stopPropagation(),n(e)};return(0,$T.useEffect)(()=>{a("Assistant response displayed",{name:e.rule.name,description:e.rule.description,group:e.rule.label,cueText:e.text})},[]),(0,sn.jsxs)(ne,{"data-testid":"cue",children:[(0,sn.jsx)(le,{children:(0,sn.jsxs)(le.Content,{children:[e.title&&(0,sn.jsx)(le.Title,{className:s.title,"data-testid":"widget-cue-title",children:e.title}),(0,sn.jsx)(Op,{content:e.text,useLabel:i("useCue"),copyLabel:i("copyCue"),onCopy:c,onUse:l?p:void 0})]})}),(0,sn.jsxs)(ne.ButtonsContainer,{children:[(0,sn.jsxs)("div",{className:s.actions,children:[e.callToAction&&(0,sn.jsx)(ne.Button,{onClick:u,children:e.callToAction.label}),(0,sn.jsx)(ne.Button,{onClick:d,children:i("removeCue")})]}),(0,sn.jsx)(oo,{eventName:"Assistant response feedback",eventData:{name:e.rule.name,group:e.rule.label,description:e.rule.description,cueText:e.text},feedbackText:e.text,feedbackType:"assistant"})]})]})},qT=QM;var Nl=w(T()),XM=({cues:e})=>{let t=G(),n=Rt(),r=ro(),o=l=>{t(lT({id:l.rule.id})),t(Bb({code:l.rule.label})),r("Assistant response closed",{name:l.rule.name,group:l.rule.label,description:l.rule.description,cueText:l.text})},s=(l,u)=>{yn(l),r("Assistant response copied",{name:u.rule.name,group:u.rule.label,description:u.rule.description,copiedText:l})},i=l=>{l.callToAction&&(t(Fd(l)),r("Assistant call to action",{name:l.rule.name,group:l.rule.label,description:l.rule.description,eventName:l.callToAction.event,value:l.callToAction.value}))},a=(l,u)=>{n.send(_n,{text:l,suggestion:{source:"cue",sourceText:l}}),r("Assistant response used",{name:u.rule.name,group:u.rule.label,description:u.rule.description,usedText:l})};return(0,Nl.jsx)(Nl.Fragment,{children:e.map(l=>(0,Nl.jsx)(qT,{cue:l,onCallToAction:i,onRemove:o,onCopy:s,onUse:a},l.rule.id))})},GT=XM;var Np=w(D());var YT={root:"dd-cvTAY",label:"dd-QWQxD",value:"dd-WSUHF",copyButton:"dd-67o9H",copyButtonText:"dd-oos-l",isTrue:"dd--1g2O",isFalse:"dd-sz2ir"};var Cn=w(T());function ZM(e,t){return t.split(".").reduce((n,r)=>!n||typeof n!="object"||!(r in n)?null:n[r],e)}var QT=({data:e,schema:t})=>{let n=I("WidgetCustomData",YT),r=o=>{yn(o)};return(0,Np.useEffect)(()=>{H.info("Custom data",e,t)},[e]),(0,Cn.jsx)("dl",{className:n.root,children:t.map(o=>{let s=ZM(e,o.path);return(0,Cn.jsxs)(Np.Fragment,{children:[(0,Cn.jsx)("dt",{className:n.label,children:o.label}),(0,Cn.jsx)("dd",{className:n.value,children:o.type==="boolean"&&s?(0,Cn.jsx)("span",{className:n.isTrue,children:o.trueValue}):o.type==="boolean"&&!s?(0,Cn.jsx)("span",{className:n.isFalse,children:o.falseValue}):s?(0,Cn.jsxs)("button",{type:"button",onClick:()=>r(s),className:n.copyButton,children:[(0,Cn.jsx)("span",{className:n.copyButtonText,children:s}),(0,Cn.jsx)(Pl,{})]}):"-"})]},o.label)})})};var ZT=w(D());var JM=/(https?:\/\/[^\s]+)/,XT=e=>e.split(" ").find(t=>JM.test(t));var an=w(T()),e_=({suggestion:e,lines:t,onUse:n})=>{var p;let r=e.text||e.url||e.message,o=XT(r),s=$($o),i=U("showImages"),a=U("fallbackImage"),l=U("hasKeyboardInput"),u=d=>{d.preventDefault(),d.stopPropagation(),l&&n(r)},c=(0,ZT.useCallback)(d=>{window.open(o,"_blank"),d.stopPropagation(),d.preventDefault()},[o]);return(0,an.jsxs)(ne,{onClick:l?u:void 0,"data-testid":"edit-suggestion",children:[(0,an.jsxs)(le,{children:[i&&e.image&&(0,an.jsx)(le.Image,{src:xp(e,"small",a||void 0),title:e.title}),(0,an.jsxs)(le.Content,{children:[e.title&&(0,an.jsx)(le.Title,{"data-testid":"widget-suggestion-title",children:e.title}),e.searchKeywords&&((p=e.searchKeywords)==null?void 0:p.length)>0&&(0,an.jsx)(ne.Labels,{labels:e.searchKeywords}),(0,an.jsx)(le.Content,{cropText:t==="single",lineClamp:t==="multiple",children:r})]})]}),(0,an.jsxs)(ne.Actions,{children:[o&&(0,an.jsx)(ne.ActionButton,{onClick:c,label:s("visitUrl")}),l&&(0,an.jsx)(ne.ActionButton,{primary:!0,onClick:u,label:s("useSuggestion")})]})]})},JT=e_;var Ml=w(T()),t_=({lines:e,suggestions:t})=>{let n=Rt(),r=(o,s)=>{n.send(_n,{text:o,suggestion:L(k({},s),{source:s.source,sourceText:s.text})})};return(0,Ml.jsx)(Ml.Fragment,{children:t.map(o=>(0,Ml.jsx)(JT,{suggestion:o,lines:e,onUse:s=>r(s,o)},o.text||o.url||o.message))})},ek=t_;var _l={};We(_l,{enUS:()=>n_,nlNL:()=>r_});var n_={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"}]},r_={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 Dl={root:"dd-W9VCG",loginText:"dd--dS6t",stateText:"dd-348OC",sectionList:"dd-bF9pF",shortcutList:"dd-MuKK-",shortcut:"dd-5CnK9",link:"dd-DRo0x"};var Sr=w(D());var Dy=w(T()),tk=()=>(0,Dy.jsx)("svg",{focusable:"false","aria-hidden":"true",viewBox:"0 0 24 24","data-testid":"ReplayIcon",children:(0,Dy.jsx)("path",{d:"M12 5V1L7 6l5 5V7c3.31 0 6 2.69 6 6s-2.69 6-6 6-6-2.69-6-6H4c0 4.42 3.58 8 8 8s8-3.58 8-8-3.58-8-8-8"})});var Fl={};We(Fl,{enUS:()=>o_,nlNL:()=>s_});var o_={titleKnowledgeAssistant:[{type:0,value:"Knowledge Assistant"}],inputPlaceholder:[{type:0,value:"What is your question?"}],useCue:[{type:0,value:"Add to message"}],copyCue:[{type:0,value:"Copy"}],removeCue:[{type:0,value:"Close"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}],submitLabel:[{type:0,value:"Submit"}],resetLabel:[{type:0,value:"Reset"}],showMore:[{type:0,value:"Show "},{type:1,value:"amount"},{type:0,value:" more"}]},s_={titleKnowledgeAssistant:[{type:0,value:"Knowledge Assistant"}],inputPlaceholder:[{type:0,value:"Wat is je vraag?"}],useCue:[{type:0,value:"Voeg toe aan bericht"}],copyCue:[{type:0,value:"Kopi\xEBren"}],removeCue:[{type:0,value:"Sluiten"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}],submitLabel:[{type:0,value:"Verzend"}],resetLabel:[{type:0,value:"Reset"}],showMore:[{type:0,value:"Toon "},{type:1,value:"amount"},{type:0,value:" meer"}]};var Fy={root:"dd-RuLqc",form:"dd-pleCH",formInput:"dd-pGJMY",formSubmit:"dd--gkRg",actionButton:"dd-I2NEH",inputSpace:"dd-mQ6yP",sources:"dd-xf9c6",source:"dd-a-vyX",showMoreSources:"dd-uDGi-"};var pe=w(T()),i_=3,a_=({sources:e,onClick:t})=>{let n=$(Fl),r=I("WidgetKnowledgeAssistant",Fy),[o,s]=(0,Sr.useState)(!1),i=o?e:e.slice(0,i_);return i.length===0?null:(0,pe.jsxs)("ul",{className:r.sources,children:[i.map(a=>(0,pe.jsx)("li",{className:r.source,"data-testid":"knowledge-assist-source",children:(0,pe.jsx)("a",{rel:"noreferrer",target:"_blank",href:a.url,onClick:l=>{l.stopPropagation(),t(a)},"data-tooltip":a.url?decodeURIComponent(a.url):void 0,children:a.name})},a.name)),i<e&&(0,pe.jsx)("button",{type:"button",className:r.showMoreSources,onClick:()=>s(!0),children:n("showMore",{amount:e.length-i.length})})]})},l_=({innerRef:e,item:t,index:n,hasKeyboardInput:r,onCopy:o,onUse:s,onSourceClick:i})=>{var l;let a=$(Fl);return(0,pe.jsxs)(ne,{"data-testid":"knowledge-assist-answer",ref:e,children:[(0,pe.jsx)(le,{children:(0,pe.jsxs)(le.Content,{children:[(0,pe.jsx)(le.Title,{children:t.question}),(0,pe.jsx)(Op,{content:t.answer.answer,useLabel:a("useCue"),copyLabel:a("copyCue"),onCopy:o,onUse:r?s:void 0}),(0,pe.jsx)(a_,{sources:(l=t.answer.sources)!=null?l:[],onClick:u=>i(u,t.question)})]})}),(0,pe.jsxs)(ne.ButtonsContainer,{children:[(0,pe.jsx)("div",{}),(0,pe.jsx)(oo,{eventName:"knowledge assist feedback",eventData:{question:t.question,isFollowUpQuestion:n>0,isAgent:!0,answer:t.answer.answer},feedbackText:t.answer.answer,feedbackType:"assistant"})]})]})},nk=()=>{var x;let e=$(Fl),t=I("WidgetKnowledgeAssistant",Fy),n=ro(),[r,o]=(0,Sr.useState)(""),s=(0,Sr.useRef)(null),i=(0,Sr.useRef)(null),a=G(),[l,u]=(0,Sr.useState)(null),c=(x=M(ol(l!=null?l:-1)))!=null?x:[],p=U("hasKeyboardInput"),d=Rt(),g=Qd(E=>sl({input:E,threadId:l,onNewThreadId(C){u(C)}}),{onSuccess(){var E;s.current&&(o(""),(E=s.current)==null||E.focus())}}),y=E=>{o(E.target.value)},v=E=>{E.preventDefault(),g.call(r)},f=E=>{yn(E),n("Assistant response copied",{name:"Knowledge Assistant",group:"knowlegde-assist",description:"",copiedText:E})},m=(E,C)=>{n("knowledge assist source viewed",{question:C,sourceViewed:E.url||E.name})},h=E=>{d.send(_n,{text:E,suggestion:{source:"cue",sourceText:E}}),n("Assistant response used",{name:"Knowledge Assistant",group:"knowlegde-assist",description:"",usedText:E})},S=()=>{l&&a(fi(l))};return(0,Sr.useEffect)(()=>{c.length>0&&i.current&&i.current.scrollIntoView({behavior:"smooth"})},[c.length]),(0,pe.jsxs)(pe.Fragment,{children:[(c==null?void 0:c.length)>0&&(0,pe.jsx)(Kt,{type:"knowledge",title:e("titleKnowledgeAssistant"),"data-testid":"knowledge",children:(0,pe.jsx)(Je,{withDivider:!0,children:c.map((E,C)=>(0,pe.jsx)(l_,{innerRef:C===c.length-1?i:void 0,item:E,index:C,hasKeyboardInput:p,onCopy:f,onUse:h,onSourceClick:m},`${E.question}_${E.answer}_${C}`))})}),(0,pe.jsx)("div",{className:t.root,children:(0,pe.jsxs)("form",{className:t.form,onSubmit:v,children:[(0,pe.jsx)("input",{ref:s,className:t.formInput,placeholder:e("inputPlaceholder"),type:"text",value:r,onChange:y}),(0,pe.jsx)("button",{type:"submit",disabled:g.state==="loading"||r==="",className:t.formSubmit,children:e("submitLabel")}),(0,pe.jsx)("button",{type:"button",title:e("resetLabel"),disabled:c.length===0||g.state==="loading",onClick:S,className:t.actionButton,children:(0,pe.jsx)(tk,{})})]})}),(0,pe.jsx)("div",{className:t.inputSpace})]})};var Y=w(T()),Mp=(e,t)=>{let n=M(dt);(0,Pi.useEffect)(()=>n?t.every(r=>!!r)?e():()=>{}:()=>{},[...t,n])},u_=({onLogIn:e})=>{let t=I("Widget",Dl),n=U("isEmbedded"),r=U("adminUrl");return(0,Y.jsx)("div",{className:t.loginText,children:(0,Y.jsx)("div",{children:(0,Y.jsx)(lp,{isEmbedded:n,loginUrl:r,onLogIn:e})})},"login")},rk=({text:e})=>{let t=I("Widget",Dl);return(0,Y.jsx)("div",{className:t.stateText,children:(0,Y.jsx)("div",{children:(0,Y.jsx)("p",{children:e})})},"notification")},c_=()=>{let e=$(_l),t=G(),n=I("Widget",Dl),r=U("showSearch"),o=U("showSummaryCommand"),s=U("showKnowledgeSearch"),i=U("isEmbedded"),a=M(wi("/admin/")),l=Rt(),u=U("productName"),c=U("hasKeyboardInput"),p=r||o||s||a;return Mp(()=>{if(i)return t(yy()),()=>{t(rT())}},[t,i]),!p||!c?null:(0,Y.jsx)(Kt,{title:e("actions"),type:"shortcuts",children:(0,Y.jsxs)("div",{className:n.shortcutList,children:[r&&(0,Y.jsxs)("button",{type:"button",className:n.shortcut,"data-testid":"shortcut-search","aria-label":e("linkSearch"),onClick:()=>l.send("ShowCommandPalette",{isOpen:!0}),children:[(0,Y.jsx)(hi,{}),e("linkSearch")]}),o&&(0,Y.jsxs)("button",{type:"button",className:n.shortcut,"data-testid":"shortcut-summary","aria-label":e("linkSummary"),onClick:()=>l.send("ShowCommandPalette",{isOpen:!0,page:"summary"}),children:[(0,Y.jsx)(PT,{}),e("linkSummary")]}),s&&(0,Y.jsxs)("button",{type:"button",className:n.shortcut,"data-testid":"shortcut-knowledge-assist","aria-label":e("linkKnowledgeSearch"),onClick:()=>l.send("ShowCommandPalette",{isOpen:!0,page:"knowledgeAssist"}),children:[(0,Y.jsx)(kT,{}),e("linkKnowledgeSearch")]}),a&&(0,Y.jsxs)("a",{className:n.shortcut,target:"_blank",href:a,"data-testid":"shortcut-studio-login","aria-label":e("linkStudioLogin",{productName:u}),rel:"noreferrer",children:[(0,Y.jsx)(TT,{}),e("linkStudioLogin",{productName:u})]})]})})},d_=()=>{let e=G(),t=U("showCustomMessages"),n=M(GC),r=M(ai);return Mp(()=>(e(kl(r)),e(JC(r)),()=>{e(eT(r))}),[e,t,r]),!t||n.length===0?null:(0,Y.jsx)(Kt,{type:"custom-messages","data-testid":"custom-messages",children:(0,Y.jsx)(Je,{withDivider:!0,children:n.map(o=>(0,Y.jsx)(bT,{suggestion:o},o.text))})})},p_=()=>{let e=$(_l),t=G(),n=U("showAutoflows"),r=M(VC),o=M(ai);return Mp(()=>(t(hr(o)),t(KC(o)),()=>{t(WC(o))}),[t,n,o]),!n||r.length===0?null:(0,Y.jsx)(Kt,{type:"autoflows",title:e("titleAutoflows"),"data-testid":"autoflows",children:(0,Y.jsx)(Je,{withDivider:!0,children:(0,Y.jsx)(wT,{})})})},f_=()=>{let e=G(),t=M(ll),n=M($b),r=M(cT),o=M(eb),s=M(Yd),i=M(ep),a=M(sr),l=M(Zr);return(0,Pi.useEffect)(()=>{!!o&&!n&&H.warn("Custom data provided, but no schema.")},[o,n]),Mp(()=>{t.forEach(({type:u})=>{u==="entities"?e(wn()):pu.includes(u)||e(xn(u))})},[e,l,a]),(0,Pi.useEffect)(()=>{r.length>0&&!t.some(u=>u.type==="cues")&&H.warn("Received cues, but cues are not configured in widget.")},[t,r]),(0,Y.jsx)(Pi.Fragment,{children:t.map(({type:u,title:c,amount:p,lines:d,schema:g})=>{var y,v;switch(u){case"entities":return s&&s.length>0&&(0,Y.jsx)(Kt,{type:u,title:c,"data-testid":`type-${u}`,children:(0,Y.jsx)(CT,{entities:s})},u);case"cues":return r&&r.length>0&&(0,Y.jsx)(Kt,{type:u,title:c,"data-testid":`type-${u}`,children:(0,Y.jsx)(Je,{withDivider:!0,children:(0,Y.jsx)(GT,{cues:r})})},u);case"custom-data":return o&&g&&(0,Y.jsx)(Kt,{type:u,title:c,"data-testid":`type-${u}`,children:(0,Y.jsx)(Je,{withDivider:!0,children:(0,Y.jsx)(QT,{data:o,schema:g})})},u);default:return((v=(y=i[u])==null?void 0:y.suggestions)==null?void 0:v.length)>0&&(0,Y.jsx)(Kt,{type:u,title:c,"data-testid":`type-${u}`,children:(0,Y.jsx)(Je,{withDivider:!0,children:(0,Y.jsx)(ek,{lines:d,contentType:u,suggestions:i[u].suggestions.slice(0,p)||[]})})},u)}})})},m_=({onLogIn:e})=>{let t=$(_l),n=I("Widget",Dl),r=M(li),o=M(dt),s=M(ai),i=M(sr),a=M(Wb("knowledge-assist"));return r===!1?(0,Y.jsx)(rk,{text:t("notSupported")}):o===!1?(0,Y.jsx)(u_,{onLogIn:e}):!i||!s||o===null?(0,Y.jsx)(rk,{text:t("waiting")}):(0,Y.jsx)("div",{className:(0,ok.default)(n.root),"data-testid":"widget",children:(0,Y.jsxs)(uu,{className:n.sectionList,children:[(0,Y.jsx)(c_,{}),(0,Y.jsx)(d_,{}),(0,Y.jsx)(p_,{}),(0,Y.jsx)(f_,{}),a&&(0,Y.jsx)(nk,{})]})})},sk=m_;function Ri(e){let t=new Range;return t.selectNodeContents(e),t}function ik(e,t,n){try{return co(e,t,n),!0}catch(r){return!1}}function _p(e){return"tagName"in e&&(e.tagName==="DIV"||e.tagName==="P")}function Dp(e){return"tagName"in e&&e.tagName==="BR"}var Hl=/[\u200B-\u200D\uFEFF]/g;function co(e,t,n){let r=new Range;if(e.firstChild===null&&t===0&&n===0)return r.selectNodeContents(e),r;let o=0,s=!1;function i(l,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=i(u,t-o);y===0&&!g?r.setStartBefore(l):r.setStart(l,y)}g&&(r.setEnd(l,i(u,n-o)),s=!0),o=p;break}case Node.ELEMENT_NODE:{if(Dp(l)&&(o===t&&r.setStartBefore(l),o++,o===n)){r.setEndAfter(l),s=!0;return}for(let c=0;c<l.childNodes.length&&(a(l.childNodes[c]),!s);c++);let u=l.lastChild;_p(l)&&u&&!_p(u)&&!Dp(u)&&o++;break}default:break}}if(a(e),r.startContainer===document)throw new Error("Offsets out of bound");return r}function Ul(e,t){if(!e.contains(t.startContainer)||!e.contains(t.endContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:r,endContainer:o,endOffset:s,collapsed:i}=t,a,l,u=0;function c(p){let d=p===e,g=p===n,y=p===o;switch(p.nodeType){case Node.TEXT_NODE:{let v=p.textContent;g&&(a=u+v.substring(0,r).replace(Hl,"").length),y&&(l=u+v.substring(0,s).replace(Hl,"").length),u+=v.replace(Hl,"").length;break}case Node.ELEMENT_NODE:{if(Dp(p)&&p.nextSibling){u++;break}!d&&_p(p)&&p.previousSibling&&u++;for(let v=0;v<p.childNodes.length;v++){let f=g&&v===r,m=y&&v===s;if(f&&(a=u),m&&(l=u),l!==void 0||((!f||!i)&&c(p.childNodes[v]),y&&v===s-1&&(l=u),l!==void 0))break}y&&(l=u);break}default:break}}if(c(e),l===void 0)throw new Error("Could not determine start and end");return{start:a!=null?a:l,end:l}}function zl(e,t){if(!e.contains(t.startContainer)||!e.contains(t.endContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:r,endContainer:o,endOffset:s,collapsed:i}=t,a=0,l="";function u(c){let p=c===e,d=c===n,g=c===o;switch(d&&(a=1),c.nodeType){case Node.TEXT_NODE:{if(a!==1)return;let y=d?r:0,v=g?s:void 0;l+=c.textContent.replace(Hl,"").substring(y,v);break}case Node.ELEMENT_NODE:{if(!i&&a===1&&Dp(c)&&c.nextSibling){l+=`
25
+ `)}var qM=({content:e,useLabel:t,copyLabel:n,onCopy:r,onUse:o})=>{let s=I("Markdown",KT),i=(0,vr.useRef)(null),[a,l]=(0,vr.useState)(null),u=(0,vr.useMemo)(()=>{let v=Ol($M(e));return jT.sanitize(v).replaceAll("</code>",`${WM(s.copyIcon)}</code>`).replaceAll('<a href="','<a target="_blank" rel="noreferrer noopener" href="')},[e]),c=v=>{var h;let f=v.target,m=!!((h=i.current)!=null&&h.querySelector("code"));if(["A","BUTTON"].includes(f.tagName)){l(null);return}a||m&&f.tagName!=="CODE"||!m&&f!==i.current||(f.addEventListener("mouseleave",()=>l(null),{once:!0}),l(f))},p=()=>{if(!a)return;l(null);let v=a.querySelector("button");v&&(Si(v,s.fadeup),r(My(a)))},d=v=>{let f=v.target;if(f.tagName==="A"){v.stopPropagation();return}"copyIcon"in f.dataset&&(Si(f,s.fadeup),r(My(f.parentElement)))},g=()=>{!a||!o||(l(null),o(My(a)))},y=v=>{if(v===null)return;let f=v.getBoundingClientRect();f.left<0?v.style.transform=`translateX(${-f.left+2}px)`:f.right>window.innerWidth&&(v.style.transform=`translateX(${window.innerWidth-f.right-2}px)`)};return(0,En.jsxs)(vr.Fragment,{children:[a&&(0,En.jsxs)(ki,{triggerRef:{current:a},className:s.popover,parentNode:a,children:[(0,En.jsxs)("div",{className:s.options,ref:y,children:[(0,En.jsx)("button",{type:"button",className:s.option,onClick:p,children:n}),o&&(0,En.jsxs)(vr.Fragment,{children:[(0,En.jsx)("div",{className:s.divider}),(0,En.jsx)("button",{type:"button",className:s.option,onClick:g,children:t})]})]}),(0,En.jsx)("div",{className:s.arrow})]}),(0,En.jsx)("div",{ref:i,className:s.root,dangerouslySetInnerHTML:{__html:u},onMouseOver:c,onClick:d})]})},Op=qM;var _y={};We(_y,{enUS:()=>GM,nlNL:()=>YM});var GM={useCue:[{type:0,value:"Add to message"}],copyCue:[{type:0,value:"Copy"}],removeCue:[{type:0,value:"Close"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}]},YM={useCue:[{type:0,value:"Voeg toe aan bericht"}],copyCue:[{type:0,value:"Kopi\xEBren"}],removeCue:[{type:0,value:"Sluiten"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}]};var WT={title:"dd-YBHrC",fadeup:"dd-cRM0K",fadedown:"dd-7D4Pq",selected:"dd-bueui",actions:"dd-9Iqn9",thumbsUp:"dd-6QwVx",thumbsDown:"dd-d3E8l"};var sn=w(T()),QM=({cue:e,onCallToAction:t,onRemove:n,onCopy:r,onUse:o})=>{let s=I("WidgetCue",WT),i=$(_y),a=ro(),l=U("hasKeyboardInput"),u=()=>{t&&t(e),n(e)},c=g=>{r&&r(g,e)},p=g=>{o&&o(g,e)},d=g=>{g.preventDefault(),g.stopPropagation(),n(e)};return(0,$T.useEffect)(()=>{a("Assistant response displayed",{name:e.rule.name,description:e.rule.description,group:e.rule.label,cueText:e.text})},[]),(0,sn.jsxs)(ne,{"data-testid":"cue",children:[(0,sn.jsx)(le,{children:(0,sn.jsxs)(le.Content,{children:[e.title&&(0,sn.jsx)(le.Title,{className:s.title,"data-testid":"widget-cue-title",children:e.title}),(0,sn.jsx)(Op,{content:e.text,useLabel:i("useCue"),copyLabel:i("copyCue"),onCopy:c,onUse:l?p:void 0})]})}),(0,sn.jsxs)(ne.ButtonsContainer,{children:[(0,sn.jsxs)("div",{className:s.actions,children:[e.callToAction&&(0,sn.jsx)(ne.Button,{onClick:u,children:e.callToAction.label}),(0,sn.jsx)(ne.Button,{onClick:d,children:i("removeCue")})]}),(0,sn.jsx)(oo,{eventName:"Assistant response feedback",eventData:{name:e.rule.name,group:e.rule.label,description:e.rule.description,cueText:e.text},feedbackText:e.text,feedbackType:"assistant"})]})]})},qT=QM;var Nl=w(T()),XM=({cues:e})=>{let t=G(),n=Rt(),r=ro(),o=l=>{t(lT({id:l.rule.id})),t(Bb({code:l.rule.label})),r("Assistant response closed",{name:l.rule.name,group:l.rule.label,description:l.rule.description,cueText:l.text})},s=(l,u)=>{yn(l),r("Assistant response copied",{name:u.rule.name,group:u.rule.label,description:u.rule.description,copiedText:l})},i=l=>{l.callToAction&&(t(Fd(l)),r("Assistant call to action",{name:l.rule.name,group:l.rule.label,description:l.rule.description,eventName:l.callToAction.event,value:l.callToAction.value}))},a=(l,u)=>{n.send(_n,{text:l,suggestion:{source:"cue",sourceText:l}}),r("Assistant response used",{name:u.rule.name,group:u.rule.label,description:u.rule.description,usedText:l})};return(0,Nl.jsx)(Nl.Fragment,{children:e.map(l=>(0,Nl.jsx)(qT,{cue:l,onCallToAction:i,onRemove:o,onCopy:s,onUse:a},l.rule.id))})},GT=XM;var Np=w(D());var YT={root:"dd-cvTAY",label:"dd-QWQxD",value:"dd-WSUHF",copyButton:"dd-67o9H",copyButtonText:"dd-oos-l",isTrue:"dd--1g2O",isFalse:"dd-sz2ir"};var Cn=w(T());function ZM(e,t){return t.split(".").reduce((n,r)=>!n||typeof n!="object"||!(r in n)?null:n[r],e)}var QT=({data:e,schema:t})=>{let n=I("WidgetCustomData",YT),r=o=>{yn(o)};return(0,Np.useEffect)(()=>{H.info("Custom data",e,t)},[e]),(0,Cn.jsx)("dl",{className:n.root,children:t.map(o=>{let s=ZM(e,o.path);return(0,Cn.jsxs)(Np.Fragment,{children:[(0,Cn.jsx)("dt",{className:n.label,children:o.label}),(0,Cn.jsx)("dd",{className:n.value,children:o.type==="boolean"&&s?(0,Cn.jsx)("span",{className:n.isTrue,children:o.trueValue}):o.type==="boolean"&&!s?(0,Cn.jsx)("span",{className:n.isFalse,children:o.falseValue}):s?(0,Cn.jsxs)("button",{type:"button",onClick:()=>r(s),className:n.copyButton,children:[(0,Cn.jsx)("span",{className:n.copyButtonText,children:s}),(0,Cn.jsx)(Pl,{})]}):"-"})]},o.label)})})};var ZT=w(D());var JM=/(https?:\/\/[^\s]+)/,XT=e=>e.split(" ").find(t=>JM.test(t));var an=w(T()),e_=({suggestion:e,lines:t,onUse:n})=>{var p;let r=e.text||e.url||e.message,o=XT(r),s=$($o),i=U("showImages"),a=U("fallbackImage"),l=U("hasKeyboardInput"),u=d=>{d.preventDefault(),d.stopPropagation(),l&&n(r)},c=(0,ZT.useCallback)(d=>{window.open(o,"_blank"),d.stopPropagation(),d.preventDefault()},[o]);return(0,an.jsxs)(ne,{onClick:l?u:void 0,"data-testid":"edit-suggestion",children:[(0,an.jsxs)(le,{children:[i&&e.image&&(0,an.jsx)(le.Image,{src:xp(e,"small",a||void 0),title:e.title}),(0,an.jsxs)(le.Content,{children:[e.title&&(0,an.jsx)(le.Title,{"data-testid":"widget-suggestion-title",children:e.title}),e.searchKeywords&&((p=e.searchKeywords)==null?void 0:p.length)>0&&(0,an.jsx)(ne.Labels,{labels:e.searchKeywords}),(0,an.jsx)(le.Content,{cropText:t==="single",lineClamp:t==="multiple",children:r})]})]}),(0,an.jsxs)(ne.Actions,{children:[o&&(0,an.jsx)(ne.ActionButton,{onClick:c,label:s("visitUrl")}),l&&(0,an.jsx)(ne.ActionButton,{primary:!0,onClick:u,label:s("useSuggestion")})]})]})},JT=e_;var Ml=w(T()),t_=({lines:e,suggestions:t})=>{let n=Rt(),r=(o,s)=>{n.send(_n,{text:o,suggestion:L(k({},s),{source:s.source,sourceText:s.text})})};return(0,Ml.jsx)(Ml.Fragment,{children:t.map(o=>(0,Ml.jsx)(JT,{suggestion:o,lines:e,onUse:s=>r(s,o)},o.text||o.url||o.message))})},ek=t_;var _l={};We(_l,{enUS:()=>n_,nlNL:()=>r_});var n_={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"}]},r_={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 Dl={root:"dd-W9VCG",loginText:"dd--dS6t",stateText:"dd-348OC",sectionList:"dd-bF9pF",shortcutList:"dd-MuKK-",shortcut:"dd-5CnK9",link:"dd-DRo0x"};var Sr=w(D());var Dy=w(T()),tk=()=>(0,Dy.jsx)("svg",{focusable:"false","aria-hidden":"true",viewBox:"0 0 24 24","data-testid":"ReplayIcon",children:(0,Dy.jsx)("path",{d:"M12 5V1L7 6l5 5V7c3.31 0 6 2.69 6 6s-2.69 6-6 6-6-2.69-6-6H4c0 4.42 3.58 8 8 8s8-3.58 8-8-3.58-8-8-8"})});var Fl={};We(Fl,{enUS:()=>o_,nlNL:()=>s_});var o_={titleKnowledgeAssistant:[{type:0,value:"Knowledge Assistant"}],inputPlaceholder:[{type:0,value:"What is your question?"}],useCue:[{type:0,value:"Add to message"}],copyCue:[{type:0,value:"Copy"}],removeCue:[{type:0,value:"Close"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}],submitLabel:[{type:0,value:"Submit"}],resetLabel:[{type:0,value:"Reset"}],showMore:[{type:0,value:"Show "},{type:1,value:"amount"},{type:0,value:" more"}]},s_={titleKnowledgeAssistant:[{type:0,value:"Knowledge Assistant"}],inputPlaceholder:[{type:0,value:"Wat is je vraag?"}],useCue:[{type:0,value:"Voeg toe aan bericht"}],copyCue:[{type:0,value:"Kopi\xEBren"}],removeCue:[{type:0,value:"Sluiten"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}],submitLabel:[{type:0,value:"Verzend"}],resetLabel:[{type:0,value:"Reset"}],showMore:[{type:0,value:"Toon "},{type:1,value:"amount"},{type:0,value:" meer"}]};var Fy={root:"dd-RuLqc",form:"dd-pleCH",formInput:"dd-pGJMY",formSubmit:"dd--gkRg",actionButton:"dd-I2NEH",inputSpace:"dd-mQ6yP",sources:"dd-xf9c6",source:"dd-a-vyX",showMoreSources:"dd-uDGi-"};var pe=w(T()),i_=3,a_=({sources:e,onClick:t})=>{let n=$(Fl),r=I("WidgetKnowledgeAssistant",Fy),[o,s]=(0,Sr.useState)(!1),i=o?e:e.slice(0,i_);return i.length===0?null:(0,pe.jsxs)("ul",{className:r.sources,children:[i.map(a=>(0,pe.jsx)("li",{className:r.source,"data-testid":"knowledge-assist-source",children:(0,pe.jsx)("a",{rel:"noreferrer",target:"_blank",href:a.url,onClick:l=>{l.stopPropagation(),t(a)},"data-tooltip":a.url?decodeURIComponent(a.url):void 0,children:a.name})},a.name)),i<e&&(0,pe.jsx)("button",{type:"button",className:r.showMoreSources,onClick:()=>s(!0),children:n("showMore",{amount:e.length-i.length})})]})},l_=({innerRef:e,item:t,index:n,hasKeyboardInput:r,onCopy:o,onUse:s,onSourceClick:i})=>{var l;let a=$(Fl);return(0,pe.jsxs)(ne,{"data-testid":"knowledge-assist-answer",ref:e,children:[(0,pe.jsx)(le,{children:(0,pe.jsxs)(le.Content,{children:[(0,pe.jsx)(le.Title,{children:t.question}),(0,pe.jsx)(Op,{content:t.answer.answer,useLabel:a("useCue"),copyLabel:a("copyCue"),onCopy:o,onUse:r?s:void 0}),(0,pe.jsx)(a_,{sources:(l=t.answer.sources)!=null?l:[],onClick:u=>i(u,t.question)})]})}),(0,pe.jsxs)(ne.ButtonsContainer,{children:[(0,pe.jsx)("div",{}),(0,pe.jsx)(oo,{eventName:"knowledge assist feedback",eventData:{question:t.question,isFollowUpQuestion:n>0,isAgent:!0,answer:t.answer.answer},feedbackText:t.answer.answer,feedbackType:"assistant"})]})]})},nk=()=>{var x;let e=$(Fl),t=I("WidgetKnowledgeAssistant",Fy),n=ro(),[r,o]=(0,Sr.useState)(""),s=(0,Sr.useRef)(null),i=(0,Sr.useRef)(null),a=G(),[l,u]=(0,Sr.useState)(null),c=(x=M(ol(l!=null?l:-1)))!=null?x:[],p=U("hasKeyboardInput"),d=Rt(),g=Qd(E=>sl({input:E,threadId:l,onNewThreadId(C){u(C)}}),{onSuccess(){var E;s.current&&(o(""),(E=s.current)==null||E.focus())}}),y=E=>{o(E.target.value)},v=E=>{E.preventDefault(),g.call(r)},f=E=>{yn(E),n("Assistant response copied",{name:"Knowledge Assistant",group:"knowlegde-assist",description:"",copiedText:E})},m=(E,C)=>{n("knowledge assist source viewed",{question:C,sourceViewed:E.url||E.name})},h=E=>{d.send(_n,{text:E,suggestion:{source:"cue",sourceText:E}}),n("Assistant response used",{name:"Knowledge Assistant",group:"knowlegde-assist",description:"",usedText:E})},S=()=>{l&&a(fi(l))};return(0,Sr.useEffect)(()=>{c.length>0&&i.current&&i.current.scrollIntoView({behavior:"smooth"})},[c.length]),(0,pe.jsxs)(pe.Fragment,{children:[(c==null?void 0:c.length)>0&&(0,pe.jsx)(Kt,{type:"knowledge",title:e("titleKnowledgeAssistant"),"data-testid":"knowledge",children:(0,pe.jsx)(Je,{withDivider:!0,children:c.map((E,C)=>(0,pe.jsx)(l_,{innerRef:C===c.length-1?i:void 0,item:E,index:C,hasKeyboardInput:p,onCopy:f,onUse:h,onSourceClick:m},`${E.question}_${E.answer}_${C}`))})}),(0,pe.jsx)("div",{className:t.inputSpace}),(0,pe.jsx)("div",{className:t.root,children:(0,pe.jsxs)("form",{className:t.form,onSubmit:v,children:[(0,pe.jsx)("input",{ref:s,className:t.formInput,placeholder:e("inputPlaceholder"),type:"text",value:r,onChange:y}),(0,pe.jsx)("button",{type:"submit",disabled:g.state==="loading"||r==="",className:t.formSubmit,children:e("submitLabel")}),(0,pe.jsx)("button",{type:"button",title:e("resetLabel"),disabled:c.length===0||g.state==="loading",onClick:S,className:t.actionButton,children:(0,pe.jsx)(tk,{})})]})})]})};var Y=w(T()),Mp=(e,t)=>{let n=M(dt);(0,Pi.useEffect)(()=>n?t.every(r=>!!r)?e():()=>{}:()=>{},[...t,n])},u_=({onLogIn:e})=>{let t=I("Widget",Dl),n=U("isEmbedded"),r=U("adminUrl");return(0,Y.jsx)("div",{className:t.loginText,children:(0,Y.jsx)("div",{children:(0,Y.jsx)(lp,{isEmbedded:n,loginUrl:r,onLogIn:e})})},"login")},rk=({text:e})=>{let t=I("Widget",Dl);return(0,Y.jsx)("div",{className:t.stateText,children:(0,Y.jsx)("div",{children:(0,Y.jsx)("p",{children:e})})},"notification")},c_=()=>{let e=$(_l),t=G(),n=I("Widget",Dl),r=U("showSearch"),o=U("showSummaryCommand"),s=U("showKnowledgeSearch"),i=U("isEmbedded"),a=M(wi("/admin/")),l=Rt(),u=U("productName"),c=U("hasKeyboardInput"),p=r||o||s||a;return Mp(()=>{if(i)return t(yy()),()=>{t(rT())}},[t,i]),!p||!c?null:(0,Y.jsx)(Kt,{title:e("actions"),type:"shortcuts",children:(0,Y.jsxs)("div",{className:n.shortcutList,children:[r&&(0,Y.jsxs)("button",{type:"button",className:n.shortcut,"data-testid":"shortcut-search","aria-label":e("linkSearch"),onClick:()=>l.send("ShowCommandPalette",{isOpen:!0}),children:[(0,Y.jsx)(hi,{}),e("linkSearch")]}),o&&(0,Y.jsxs)("button",{type:"button",className:n.shortcut,"data-testid":"shortcut-summary","aria-label":e("linkSummary"),onClick:()=>l.send("ShowCommandPalette",{isOpen:!0,page:"summary"}),children:[(0,Y.jsx)(PT,{}),e("linkSummary")]}),s&&(0,Y.jsxs)("button",{type:"button",className:n.shortcut,"data-testid":"shortcut-knowledge-assist","aria-label":e("linkKnowledgeSearch"),onClick:()=>l.send("ShowCommandPalette",{isOpen:!0,page:"knowledgeAssist"}),children:[(0,Y.jsx)(kT,{}),e("linkKnowledgeSearch")]}),a&&(0,Y.jsxs)("a",{className:n.shortcut,target:"_blank",href:a,"data-testid":"shortcut-studio-login","aria-label":e("linkStudioLogin",{productName:u}),rel:"noreferrer",children:[(0,Y.jsx)(TT,{}),e("linkStudioLogin",{productName:u})]})]})})},d_=()=>{let e=G(),t=U("showCustomMessages"),n=M(GC),r=M(ai);return Mp(()=>(e(kl(r)),e(JC(r)),()=>{e(eT(r))}),[e,t,r]),!t||n.length===0?null:(0,Y.jsx)(Kt,{type:"custom-messages","data-testid":"custom-messages",children:(0,Y.jsx)(Je,{withDivider:!0,children:n.map(o=>(0,Y.jsx)(bT,{suggestion:o},o.text))})})},p_=()=>{let e=$(_l),t=G(),n=U("showAutoflows"),r=M(VC),o=M(ai);return Mp(()=>(t(hr(o)),t(KC(o)),()=>{t(WC(o))}),[t,n,o]),!n||r.length===0?null:(0,Y.jsx)(Kt,{type:"autoflows",title:e("titleAutoflows"),"data-testid":"autoflows",children:(0,Y.jsx)(Je,{withDivider:!0,children:(0,Y.jsx)(wT,{})})})},f_=()=>{let e=G(),t=M(ll),n=M($b),r=M(cT),o=M(eb),s=M(Yd),i=M(ep),a=M(sr),l=M(Zr);return(0,Pi.useEffect)(()=>{!!o&&!n&&H.warn("Custom data provided, but no schema.")},[o,n]),Mp(()=>{t.forEach(({type:u})=>{u==="entities"?e(wn()):pu.includes(u)||e(xn(u))})},[e,l,a]),(0,Pi.useEffect)(()=>{r.length>0&&!t.some(u=>u.type==="cues")&&H.warn("Received cues, but cues are not configured in widget.")},[t,r]),(0,Y.jsx)(Pi.Fragment,{children:t.map(({type:u,title:c,amount:p,lines:d,schema:g})=>{var y,v;switch(u){case"entities":return s&&s.length>0&&(0,Y.jsx)(Kt,{type:u,title:c,"data-testid":`type-${u}`,children:(0,Y.jsx)(CT,{entities:s})},u);case"cues":return r&&r.length>0&&(0,Y.jsx)(Kt,{type:u,title:c,"data-testid":`type-${u}`,children:(0,Y.jsx)(Je,{withDivider:!0,children:(0,Y.jsx)(GT,{cues:r})})},u);case"custom-data":return o&&g&&(0,Y.jsx)(Kt,{type:u,title:c,"data-testid":`type-${u}`,children:(0,Y.jsx)(Je,{withDivider:!0,children:(0,Y.jsx)(QT,{data:o,schema:g})})},u);default:return((v=(y=i[u])==null?void 0:y.suggestions)==null?void 0:v.length)>0&&(0,Y.jsx)(Kt,{type:u,title:c,"data-testid":`type-${u}`,children:(0,Y.jsx)(Je,{withDivider:!0,children:(0,Y.jsx)(ek,{lines:d,contentType:u,suggestions:i[u].suggestions.slice(0,p)||[]})})},u)}})})},m_=({onLogIn:e})=>{let t=$(_l),n=I("Widget",Dl),r=M(li),o=M(dt),s=M(ai),i=M(sr),a=M(Wb("knowledge-assist"));return r===!1?(0,Y.jsx)(rk,{text:t("notSupported")}):o===!1?(0,Y.jsx)(u_,{onLogIn:e}):!i||!s||o===null?(0,Y.jsx)(rk,{text:t("waiting")}):(0,Y.jsx)("div",{className:(0,ok.default)(n.root),"data-testid":"widget",children:(0,Y.jsxs)(uu,{className:n.sectionList,children:[(0,Y.jsx)(c_,{}),(0,Y.jsx)(d_,{}),(0,Y.jsx)(p_,{}),(0,Y.jsx)(f_,{}),a&&(0,Y.jsx)(nk,{})]})})},sk=m_;function Ri(e){let t=new Range;return t.selectNodeContents(e),t}function ik(e,t,n){try{return co(e,t,n),!0}catch(r){return!1}}function _p(e){return"tagName"in e&&(e.tagName==="DIV"||e.tagName==="P")}function Dp(e){return"tagName"in e&&e.tagName==="BR"}var Hl=/[\u200B-\u200D\uFEFF]/g;function co(e,t,n){let r=new Range;if(e.firstChild===null&&t===0&&n===0)return r.selectNodeContents(e),r;let o=0,s=!1;function i(l,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=i(u,t-o);y===0&&!g?r.setStartBefore(l):r.setStart(l,y)}g&&(r.setEnd(l,i(u,n-o)),s=!0),o=p;break}case Node.ELEMENT_NODE:{if(Dp(l)&&(o===t&&r.setStartBefore(l),o++,o===n)){r.setEndAfter(l),s=!0;return}for(let c=0;c<l.childNodes.length&&(a(l.childNodes[c]),!s);c++);let u=l.lastChild;_p(l)&&u&&!_p(u)&&!Dp(u)&&o++;break}default:break}}if(a(e),r.startContainer===document)throw new Error("Offsets out of bound");return r}function Ul(e,t){if(!e.contains(t.startContainer)||!e.contains(t.endContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:r,endContainer:o,endOffset:s,collapsed:i}=t,a,l,u=0;function c(p){let d=p===e,g=p===n,y=p===o;switch(p.nodeType){case Node.TEXT_NODE:{let v=p.textContent;g&&(a=u+v.substring(0,r).replace(Hl,"").length),y&&(l=u+v.substring(0,s).replace(Hl,"").length),u+=v.replace(Hl,"").length;break}case Node.ELEMENT_NODE:{if(Dp(p)&&p.nextSibling){u++;break}!d&&_p(p)&&p.previousSibling&&u++;for(let v=0;v<p.childNodes.length;v++){let f=g&&v===r,m=y&&v===s;if(f&&(a=u),m&&(l=u),l!==void 0||((!f||!i)&&c(p.childNodes[v]),y&&v===s-1&&(l=u),l!==void 0))break}y&&(l=u);break}default:break}}if(c(e),l===void 0)throw new Error("Could not determine start and end");return{start:a!=null?a:l,end:l}}function zl(e,t){if(!e.contains(t.startContainer)||!e.contains(t.endContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:r,endContainer:o,endOffset:s,collapsed:i}=t,a=0,l="";function u(c){let p=c===e,d=c===n,g=c===o;switch(d&&(a=1),c.nodeType){case Node.TEXT_NODE:{if(a!==1)return;let y=d?r:0,v=g?s:void 0;l+=c.textContent.replace(Hl,"").substring(y,v);break}case Node.ELEMENT_NODE:{if(!i&&a===1&&Dp(c)&&c.nextSibling){l+=`
26
26
  `;break}!p&&!i&&a===1&&_p(c)&&c.previousSibling&&(l+=`
27
- `);let y=d?r:0,v=g?Math.min(s,c.childNodes.length):c.childNodes.length;for(let f=y;f<v&&(u(c.childNodes[f]),a!==2);f++);break}default:break}g&&(a=2)}return u(e),l}var ak=(i=>(i.CUT="Cut",i.BACKSPACE="Backspace",i.DELETE="Delete",i.ERASEEOF="EraseEof",i.UNDO="Undo",i.CLEAR="Clear",i))(ak||{}),wr=class{constructor(t){this.element=t;this.isFocused=!1;this.isActive=!0;this.isDisposed=!1;this.eventListeners={};this.disposeHandlers=[];this.cachedText="";this.cachedCaretPosition=null;this.cachedSelection={start:0,end:0};this.cachedHTML="";this.isSubmitting=!1;this.isPossibleClearInputAction=!1;this.cachedText=this.getText(),this.cachedHTML=this.getHTML(),this.cachedSelection=this.getSelection(),this.listen()}addEventListener(t,n){let r=o=>{n(o)};this.element.addEventListener(t,r),this.disposeHandlers.push(()=>{this.element.removeEventListener(t,r)})}removeEventListener(t,n){this.element.removeEventListener(t,n)}handleInteraction(){let t=this.getText(),n=this.getHTML(),r=this.getSelection(),o=this.cachedCaretPosition===null;if(!this.isActive||(t===""&&this.cachedText!==""&&!this.isPossibleClearInputAction&&this.emit("submit"),t!==this.cachedText?(this.cachedText=t,this.cachedHTML=n,o=!0,this.emit("change",{plainText:t,rawHTML:n})):n!==null&&n!==this.cachedHTML&&(this.cachedHTML=n,o=!0,this.emit("change",{plainText:t,rawHTML:n})),(r.start!==this.cachedSelection.start||r.end!==this.cachedSelection.end)&&(this.cachedSelection=r,o=!0,this.emit("selection",r)),!o))return;let s=this.getCaretPosition();Xr(s,this.cachedCaretPosition)||(this.cachedCaretPosition=s,this.emit("caretposition",s))}handleClick(){this.handleInteraction()}handleFocus(){let t=!this.isFocused;this.isFocused=!0,t&&this.emit("focus"),this.handleInteraction()}handleBlur(){this.isPossibleClearInputAction=!1;let t=this.isFocused;this.isFocused=!1,t&&this.emit("blur")}handleKeyDown(t){let{key:n,ctrlKey:r,metaKey:o}=t;this.isPossibleClearInputAction=Object.values(ak).includes(n)||n.toLowerCase()==="z"&&(r||o),this.emit("keydown",t)}handleKeyUp(t){this.handleInteraction(),this.emit("keyup",t)}handleCut(){this.isPossibleClearInputAction=!0,this.emit("cut",{selectionText:this.getSelectedText()})}handlePaste(t){var r,o;let n=((r=t.clipboardData)==null?void 0:r.getData("text"))||((o=t.clipboardData)==null?void 0:o.getData("text/plain"))||"";this.emit("paste",{pastedText:n,selectionText:this.getSelectedText()})}listen(){this.addEventListener("keydown",n=>this.handleKeyDown(n)),this.addEventListener("keyup",n=>this.handleKeyUp(n)),this.addEventListener("input",()=>this.handleInteraction()),this.addEventListener("change",()=>this.handleInteraction()),this.addEventListener("focus",()=>this.handleFocus()),this.addEventListener("blur",()=>this.handleBlur()),this.addEventListener("cut",()=>this.handleCut()),this.addEventListener("paste",n=>this.handlePaste(n)),this.addEventListener("click",()=>this.handleInteraction()),document.activeElement===this.element&&(this.isFocused=!0);let t=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});t.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{t.disconnect()})}focus(){this.element.focus()}emit(t,...n){this.isDisposed||this.eventListeners[t]&&this.eventListeners[t].forEach(r=>{r(...n)})}on(t,n){this.isDisposed||(this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n))}activate(){let t=this.isActive===!1;this.isActive=!0,t&&this.handleInteraction()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(t=>t()),this.eventListeners={},this.isDisposed=!0}};function lk(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var ns=class extends wr{constructor(){super(...arguments);this.lastKnownSelection=null}getRootNode(){return this.element.getRootNode()}getText(){let n=new Range;return n.selectNodeContents(this.element),zl(this.element,n)}getHTML(){return this.element.innerHTML||""}getRange(){var i;let n=this.getRootNode();if(n.activeElement!==this.element)return null;let r="getSelection"in n?n.getSelection():window.getSelection();if(!r)return null;let o="getComposedRanges"in r&&n instanceof ShadowRoot?(i=r.getComposedRanges(n))==null?void 0:i[0]:r.rangeCount>0?r.getRangeAt(0):null;if(!o)return null;let s=this.element.ownerDocument.createRange();return s.setStart(o==null?void 0:o.startContainer,o==null?void 0:o.startOffset),s.setEnd(o==null?void 0:o.endContainer,o==null?void 0:o.endOffset),!s||!this.element.contains(s.startContainer)||!this.element.contains(s.endContainer)?null:s}getCaretPosition(){let n=this.getRange();if(!n||!n.collapsed||!("getBoundingClientRect"in n))return null;let r=n.getBoundingClientRect();return!lk(r)&&(n.insertNode(this.element.ownerDocument.createTextNode("\u2060")),r=n.getBoundingClientRect(),n.deleteContents(),!lk(r))?null:{top:r.top+r.height,left:r.left}}getSelection(){let n=this.getRange();if(n)return Ul(this.element,n);let r=this.lastKnownSelection;if(r&&ik(this.element,r.start,r.end))return r;let o=Ri(this.element);return o.collapse(!1),Ul(this.element,o)}getSelectedText(){let{start:n,end:r}=this.getSelection();return zl(this.element,co(this.element,n,r))}listen(){super.listen();let n=new MutationObserver(s=>{var i,a;s.length===2&&s[0].addedNodes.length===1&&((i=s[0].addedNodes[0])==null?void 0:i.textContent)==="\u2060"&&((a=s[1].removedNodes[0])==null?void 0:a.textContent)==="\u2060"||setTimeout(()=>{this.handleInteraction()},0)});n.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0}),this.disposeHandlers.push(()=>n.disconnect());let r=this.element.isContentEditable,o=new MutationObserver(()=>{this.element.isContentEditable!==r&&(r=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>o.disconnect())}};var g_=["direction","boxSizing","width","height","overflowX","overflowY","borderTopWidth","borderRightWidth","borderBottomWidth","borderLeftWidth","borderStyle","paddingTop","paddingRight","paddingBottom","paddingLeft","fontStyle","fontVariant","fontWeight","fontStretch","fontSize","fontSizeAdjust","lineHeight","fontFamily","textAlign","textTransform","textIndent","textDecoration","letterSpacing","wordSpacing","tabSize"];function uk(e,t){let n="mozInnerScreenX"in window,r=document.createElement("div");r.id="input-textarea-caret-position-mirror-div";let o=r.style,s=window.getComputedStyle(e),i=e.ownerDocument.body;o.whiteSpace="pre-wrap",o.wordWrap="break-word",o.position="absolute",o.visibility="hidden",g_.forEach(function(c){o[c]=s[c]}),n?e.scrollHeight>parseInt(s.height)&&(o.overflowY="scroll"):o.overflow="hidden",r.textContent=e.value.substring(0,t);let a=document.createElement("span");a.textContent=e.value.substring(t)||".",r.appendChild(a),i.appendChild(r);let l=e.getBoundingClientRect(),u={top:l.top-e.scrollTop+a.offsetTop+parseInt(s.borderTopWidth)+a.offsetHeight,left:l.left-e.scrollLeft+a.offsetLeft+parseInt(s.borderLeftWidth)};return i.removeChild(r),u}var rs=class extends wr{constructor(){super(...arguments);this.lastKnownSelection=null}getText(){return this.element.value}getHTML(){return null}getSelection(){let{selectionStart:n,selectionEnd:r}=this.element;return{start:n,end:r}}getSelectedText(){let n=this.getSelection();return n?this.getText().slice(n.start,n.end):""}getCaretPosition(){return uk(this.element,this.element.selectionEnd)}listen(){super.listen();let n=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var s;return(s=n==null?void 0:n.get)==null?void 0:s.call(this.element)},set:s=>{var i;(i=n==null?void 0:n.set)==null||i.call(this.element,s),this.handleInteraction()}}),this.addEventListener("scroll",()=>{this.emit("caretposition",this.getCaretPosition())});let r=this.element.disabled,o=new MutationObserver(()=>{this.element.disabled!==r&&(r=this.element.disabled,this.emit(r?"disabled":"enabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>o.disconnect())}};function ck(e,t,n){let r=`deepdesk-iframe-${e}`,o=document.getElementById(r);if(o)return o;let s=document.createElement("iframe"),i=new URL(t);return Object.entries(n).forEach(([a,l])=>{i.searchParams.append(a,l)}),s.style.position="absolute",s.style.left="-999em",s.style.width="0px",s.style.height="0px",s.tabIndex=-1,s.id=r,s.title=`iframe-${e}`,s.src=i.toString(),window.document.body.appendChild(s),s}function h_(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch(t){return e}}var Hy=class{constructor(t){this.name=t;this.disposeHandlers=[];this.broadcastChannel=new BroadcastChannel(t)}onMessage(t){this.broadcastChannel.addEventListener("message",t),this.disposeHandlers.push(()=>{this.broadcastChannel.removeEventListener("message",t)})}postMessage(t){this.broadcastChannel.postMessage(JSON.stringify(t))}close(){this.disposeHandlers.forEach(t=>t()),this.broadcastChannel.close()}},Uy=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.disposeHandlers=[];this.iframe=ck(t,`${this.targetOrigin}/sdk/proxy/proxy.html`,{channel:this.name,host:window.location.origin,debug:"1"}),document.body.appendChild(this.iframe)}onMessage(t){window.addEventListener("message",t),this.disposeHandlers.push(()=>{window.removeEventListener("message",t)})}postMessage(t){var n;(n=this.iframe.contentWindow)==null||n.postMessage(JSON.stringify(t),this.targetOrigin)}close(){var t;this.disposeHandlers.forEach(n=>n()),(t=this.iframe)==null||t.remove()}},zy=class{constructor(t){this.params=t;this.deepdeskUrl=t.deepdeskUrl,this.eventMap=t.eventMap,this.sessionId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setSessionId(t){this.sessionId!==t&&(this.cleanup(),H.info("Set sessionId",t),this.sessionId=t,this.channel=this.createChannel(t))}createChannel(t){let n=this.params.createCustomChannel?this.params.createCustomChannel(t):this.isCrossOrigin?new Uy(t,this.deepdeskUrl,{debug:!0}):new Hy(t),r=o=>{var i,a;if(o.origin!==this.deepdeskUrl)return;let s=h_(o.data);typeof s!="object"||s.type!=="event"||s.channel!==t||(H.info("Received broadcast event",this.sessionId,o),(a=(i=this.eventMap)[s.name])==null||a.call(i,s.payload))};return n.onMessage(r),n}send(t,n,r){var i,a;H.info("Broadcast event",{sessionId:this.sessionId,name:t,payload:n});let o={type:"event",name:t,payload:n};r!==!1&&((a=(i=this.eventMap)[t])==null||a.call(i,n));let s=this.sessionId==="deepdesk-general"?this.defaultChannel:this.channel;s==null||s.postMessage(L(k({},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)}},dk=zy;function y_(e){return e.replace(/(_\w)/g,t=>t[1].toUpperCase())}function oe(e){return Array.isArray(e)?e.map(oe):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>L(k({},t),{[y_(n)]:oe(e[n])}),{}):e}function By(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function Oe(e){return Array.isArray(e)?e.map(Oe):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>L(k({},t),{[By(n)]:Oe(e[n])}),{}):e}var Ai=class extends Error{constructor(n,r){super(n);this.body=r;this.name="CustomError"}};var jy=e=>new Promise(t=>{setTimeout(t,e)});var Ii=class extends Ai{constructor(){super(...arguments);this.name="ClientError"}},Ky=class extends Ai{constructor(){super(...arguments);this.name="ServerError"}},Vy=new Map;function v_(e){return P(this,null,function*(){if(e.status===204)return e.text().catch(()=>{}),null;let t=e.headers.get("content-type");if(t&&t.includes("application/json"))return e.json();let n=yield e.text();return n===""?null:(H.warn("Unexpected response body:",n.slice(0,20)),JSON.parse(n))})}var po=class po{constructor(t="",n={}){this.baseUrl=t;this.options=n;this.latestRequestByUrl={};this.fetch=window.fetch.bind(window);n.fetch&&(this.fetch=n.fetch)}patchFetch(t){this.fetch=t(this.fetch)}setCsrfToken(t){this.csrfToken=t}request(t,n={}){return new Promise((r,o)=>{let s={isAborted:!1,reject:o},i=`${this.baseUrl}${t}`,a=this.fetch,l=n.method===void 0||n.method.toLowerCase()==="get",C=n,{useCache:u=!1,abortLatest:c=!1,attempts:p=1,retryDelay:d=500,refreshTokenOn401:g=!0,retryOnError:y=R=>R instanceof TypeError,retryOnResponse:v=R=>R.status>=500,version:f=null}=C,m=ee(C,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]);if(u)if(l){if(Vy.has(i)){r(Vy.get(i));return}}else throw new Error(`Can't use 'useCache' for ${n.method}`);let h=L(k({credentials:"include"},m),{headers:k({Accept:"application/json","Content-Type":"application/json"},m.headers)});!l&&this.csrfToken&&(h.headers=L(k({},h.headers),{"X-CSRFToken":this.csrfToken})),typeof f=="string"&&(h.headers=L(k({},h.headers),{"X-Deepdesk-API-Version":f}));let S=p,x=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[i]&&c&&(this.latestRequestByUrl[i].isAborted=!0,this.latestRequestByUrl[i].reject(new Error("Aborted"))),this.latestRequestByUrl[i]=s;let E=()=>P(this,null,function*(){return S--,a(i,h).then(R=>P(this,null,function*(){return v(R)&&!s.isAborted&&S>0?(yield jy(d),E()):R.status===401&&g===!0&&x===!1?(x=!0,yield this.refreshToken(),E()):R})).catch(R=>P(this,null,function*(){if(y(R)&&!s.isAborted&&S>0)return yield jy(d),E();throw R}))});E().then(R=>P(this,null,function*(){let N=yield v_(R);if(delete this.latestRequestByUrl[i],R.status>=500){o(new Ky("Server Error",N));return}else if(R.status===401){o(new Ii("Unauthorized",N));return}else if(R.status===403){o(new Ii("Forbidden",N));return}else if(R.status===404){o(new Ii("Not Found",N));return}else if(R.status>=400){o(new Ii("Bad Request",N));return}u&&Vy.set(i,N),r(N)})).catch(R=>{o(R)})})}validateToken(){return P(this,null,function*(){let{has_valid_access_token:t}=yield this.get("/auth/validate");if(!t)try{yield this.refreshToken()}catch(r){return!1}let{is_logged_in:n}=yield this.get("/apis/admin/session/validate/");return!!n})}refreshToken(){return po.refreshingToken||(po.refreshingToken=this.get("/auth/refresh",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{po.refreshingToken=null},1e3*60)})),po.refreshingToken}get(t,n){return this.request(t,n)}post(t,n,r){return this.request(t,k({method:"POST",body:JSON.stringify(n)},r))}patch(t,n,r){return this.request(t,k({method:"PATCH",body:JSON.stringify(n)},r))}put(t,n,r){return this.request(t,k({method:"PUT",body:JSON.stringify(n)},r))}delete(t,n){return this.request(t,k({method:"DELETE"},n))}};po.refreshingToken=null;var xr=po;var pk;(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||(t.EventType={}))})(pk||(pk={}));function Fp(e){return L(k({},oe(e)),{tags:e.tags})}var os=class os{constructor(t,n={}){this.options=n;this.latestReceivedDeepdeskVersions={};this.shouldFetchCsrfToken=!0;this.client=new xr(t,{fetch:n.fetch}),this.client.patchFetch(r=>(o,s)=>P(this,null,function*(){let i=yield r(o,s);return this.handleDeepdeskVersionHeaders(i),i}))}preflight(){return P(this,null,function*(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let t=yield this.getCsrfToken();this.client.setCsrfToken(t)}return this.options.token?(os.exchangeTokenPromise||(os.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),os.exchangeTokenPromise):Promise.resolve()})}createConversation(t){return P(this,null,function*(){yield this.preflight(),H.info(`Creating conversation for session ${t.sessionId} and agent ${t.agentId}`);let n=yield this.client.post("/api/conversations",L(k({},Oe(t)),{tags:t.tags}),{version:"v2"});return Fp(n)})}getMe(){return P(this,null,function*(){let t=yield this.client.get("/apis/admin/session/me/");return oe(t)})}postIdentity(t){return P(this,null,function*(){yield this.client.post("/apis/admin/session/me/identities/",Oe(t))})}patchMe(t){return P(this,null,function*(){let n=yield this.client.patch("/apis/admin/session/me/",Oe(t));return oe(n)})}getProfile(t){return P(this,null,function*(){let n=yield this.client.get(`/apis/admin/profiles/${t}/`,{useCache:!0});return oe(n)})}getKnowledgeAssistant(t){return P(this,null,function*(){let n=yield this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{useCache:!0});return oe(n)})}getContentTypes(){return P(this,null,function*(){let t=yield this.client.get("/apis/admin/content-types/",{useCache:!0});return oe(t)})}getAccount(){return P(this,null,function*(){let t=yield this.client.get("/apis/admin/account/",{useCache:!0});return oe(t)})}getPlatformConfig(t){return P(this,null,function*(){let n=t!==void 0?`/platform/config/${t}/`:"/platform/config/",{config:r}=yield this.client.get(n,{useCache:!0});return oe(r)})}checkUserExists(t){return P(this,null,function*(){let{exists:n}=yield this.client.get(`/apis/admin/users/exists?external_id=${t}`,{version:"v1"});return n})}getConversationBySessionId(r){return P(this,arguments,function*(t,n={}){yield this.preflight(),H.info(`Getting conversation for session ${t}`);let{attempts:o=1,retryDelay:s=1e3}=n,i=yield this.client.get(`/api/conversations/by_session_id/${t}`,{attempts:o,retryDelay:s,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"});return H.info(`Successfully retrieved conversation ${i.id} for session ${t}`),Fp(i)})}isConversationSupported(r){return P(this,arguments,function*(t,n={}){H.info(`Check if conversation for session ${t} is supported`);let{attempts:o=1,retryDelay:s=1e3}=n;return(yield this.client.get(`/api/conversations/by_session_id/${t}/active_profile`,{attempts:o,retryDelay:s,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"})).has_active_profile})}updateConversation(t,n){return P(this,null,function*(){let r=Oe(n);n.tags&&(r.tags=n.tags);let o=yield this.client.put(`/api/conversations/${t}`,r,{version:"v2"});return Fp(o)})}postMessages(t,n){return P(this,null,function*(){return(yield this.client.post(`/api/conversations/${t}/messages`,n.map(o=>L(k({},Oe(o)),{tags:o.tags})),{version:"v2"})).map(o=>Fp(o))})}sendEvent(t,n){return P(this,null,function*(){let i=n,{data:r}=i,o=ee(i,["data"]),s=Object.entries(this.latestReceivedDeepdeskVersions).reduce((a,[l,u])=>L(k({},a),{[l]:u}),{});return this.client.post("/api/events",Oe(L(k(k({},s),o),{data:r,name:t})),{version:"v2"})})}sendEventV1(t,n){return P(this,null,function*(){let r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((o,[s,i])=>L(k({},o),{[s]:i}),{});return this.client.post("/api/events",{event:t,data:Oe(k(k({},n),r))},{version:"v1"})})}getEntities(t){return P(this,null,function*(){return(yield this.client.post("/api/entities",{messages:t.filter(r=>r.text)},{version:"v1"})).entities})}getTemporaryExchangeToken(){return P(this,null,function*(){return(yield this.client.get("/auth/exchange-token")).jwt})}exchangeTokenForAccessCookie(t){return P(this,null,function*(){return this.client.post("/apis/admin/session/jwt/",{jwt:t}).catch(n=>{throw H.warn(`Invalid token '${t}'`),n})})}authenticateWithKey(t,n){return P(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/api-key/",Oe(n),{refreshTokenOn401:!1,headers:{apikey:t}})})}getTextSuggestions(o){return P(this,arguments,function*(t,n={},r){return r==="sticky-messages"?this.getPinnedMessages(t):(yield this.client.post(`/api/conversations/${t}/recommend/${r}`,Oe(n),{abortLatest:!0,version:"v1"})).map(i=>L(k({},oe(i)),{text:i.text||i.url||i.message,source:r,type:r})).filter((i,a,l)=>a===l.findIndex(u=>u.text===i.text))})}isLoggedIn(){return P(this,null,function*(){return yield this.preflight(),this.client.validateToken()})}getAutocompleteSuggestions(t,n){return P(this,null,function*(){return(yield this.client.post(`/api/conversations/${t}/autocomplete`,Oe(n),{abortLatest:!0,version:"v1"})).map(o=>({score:1,source:o.source,sourceText:o.source_text,text:o.label,trainingJobs:o.training_jobs,searchKeywords:o.search_keywords,type:o.source})).filter((o,s,i)=>s===i.findIndex(a=>a.text===o.text))})}getPinnedMessages(t){return P(this,null,function*(){let n=yield this.client.get(`/api/conversations/${t}/sticky-messages`,{abortLatest:!0,version:"v1"});return oe(n).map(r=>L(k({},r),{text:r.message,source:"sticky-messages",type:"pinned-message"}))})}getStyleSuggestions(t){return P(this,null,function*(){let n=yield this.client.post("/api/style-suggestions",Oe(t),{abortLatest:!0,version:"v1"});return oe(n)})}search(t){return P(this,null,function*(){let n=yield this.client.post(`/api/profiles/${t.profile}/search`,Oe(t),{version:"v2"});return oe(n)})}knowledgeAssist(s,i,a){return P(this,arguments,function*(t,n,r,o={}){let l=yield this.client.post(`/api/knowledge-assist/assistants/${r}/search`,Oe({question:t.question,doNotKnowAnswer:t.doNotKnowAnswer,customerInstruction:t.customerInstruction,chatHistory:n.map(u=>({question:u.question,answer:u.answer.answer})),agentId:o.agentId,conversationId:o.conversationId}),{version:"v2"});return oe(l)})}requestLoginByEmail(t){return P(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/request/",{email:t});return oe(n)})}requestPasswordlessToken(){return P(this,null,function*(){let t=yield this.client.get("/apis/admin/session/passwordless/request/");return oe(t.token)})}getCsrfToken(){return P(this,null,function*(){let{token:t}=yield this.client.get("/apis/admin/session/csrf/");return t})}verifyLoginToken(t){return P(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/login/",{token:t});return oe(n)})}evaluateRule(s,i,a){return P(this,arguments,function*(t,n,r,o={}){let l=new URLSearchParams;o.raiseForFailingConditions&&l.set("raise_for_failing_conditions","true");let u=yield this.client.post(`/api/conversations/${n}/rules/${t}/evaluate?${l.toString()}`,r,{version:"v2"});return u?oe(u.cues):[]})}getSummary(r){return P(this,arguments,function*(t,n={}){let o=yield this.client.post("/api/summary",{conversation:{messages:t.filter(s=>s.text&&s.source),agent_id:n.agentId,id:n.externalConversationId},prompt_instruction:n.promptInstruction,model:n.model},{version:"v1"});return oe(o)})}evaluateAssistant(t,n){return P(this,null,function*(){var a;let r=new URLSearchParams,{expectFormat:o="text"}=n||{};if(o.startsWith("json-schema:")){let l=o.replace("json-schema:","");r.append("expect_response_format","json-schema"),r.append("expect_response_format_schema",l)}else r.append("expect_response_format",o);n!=null&&n.externalConversationId&&r.append("external_conversation_id",n.externalConversationId);let s=n!=null&&n.threadId?`/api/v2/assistants/${t}/threads/${n==null?void 0:n.threadId}/evaluate?${r.toString()}`:`/api/v2/assistants/${t}/evaluate?${r.toString()}`,i=yield this.client.post(s,{input:(a=n==null?void 0:n.input)!=null?a:{},conversation:n==null?void 0:n.transcript});return oe(i.output)})}createAssistantThread(t){return P(this,null,function*(){let{assistantCode:n}=t,r=yield this.client.post(`/apis/admin/assistants/${n}/threads/`,{});return oe(r)})}postMessageToAssistantThread(t){return P(this,null,function*(){let{assistantCode:n,threadId:r,message:o}=t,s=yield this.client.post(`/apis/admin/assistants/${n}/threads/${r}/messages/`,{content:o,role:"user"});return oe(s)})}getRules(){return P(this,null,function*(){let t=new URLSearchParams,n=yield this.client.get(`/apis/admin/rule-engine/rules/?${t.toString()}`,{useCache:!0});return oe(n)})}translateMessages(t){return P(this,null,function*(){let n=yield this.client.post("/api/translate",Oe(t),{version:"v2"});return oe(n)})}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),s=o.match(c0);if(!n||!s)return;let i=s[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[i];a&&n&&a!==n&&H.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[i]=n})}};os.exchangeTokenPromise=null;var br=os;var Bl=class{constructor(t,n){this.url=t;this.eventListeners={};this.options=k({timeout:25e3},n)}proxyEvent(t){this.eventSource.addEventListener(By(t),n=>{let{data:r}=n;try{let o=JSON.parse(r);this.emit(t,oe(o))}catch(o){H.warn(`Invalid JSON for ${t}: ${r}`)}})}connect(){clearTimeout(this.timeoutTimer);let t=new EventSource(this.url,{withCredentials:!0});this.eventSource=t;let n=!1;t.onopen=()=>{n=!0},t.onerror=()=>{n&&t.readyState===2&&this.connect()},this.timeoutTimer=setTimeout(()=>{t.close(),this.connect()},this.options.timeout),Object.keys(this.eventListeners).forEach(r=>{this.proxyEvent(r)})}disconnect(){var t;clearTimeout(this.timeoutTimer),this.eventListeners={},(t=this.eventSource)==null||t.close()}emit(t,n){this.eventListeners[t]&&this.eventListeners[t].forEach(r=>r(n))}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),this.proxyEvent(t),()=>{this.off(t,n)}}off(t,n){let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}};var fk;(t=>{let e;(s=>(s.Started="Started",s.Aborted="Aborted",s.Completed="Completed"))(e=t.AutoflowSessionState||(t.AutoflowSessionState={}))})(fk||(fk={}));var jl=class{constructor(t,n={}){this.apiUrl=t;this.streams={};this.logger=H;this.client=new xr(t,n)}getCustomMessages(t){return P(this,null,function*(){let n=yield this.client.get(`/sessions/${t}/suggestions`);return oe(n.suggestions)})}sendCustomMessage(t,n){return P(this,null,function*(){let r=yield this.client.post(`/sessions/${t}/messages`,Oe(n));return oe(r)})}answerCustomMessage(t,n){return P(this,null,function*(){yield this.client.post(`/sessions/${t}/answers`,Oe(n))})}getAutoflows(t){return P(this,null,function*(){let n=yield this.client.get(`/sessions/${t}/autoflows`);return oe(n.autoflows)})}startAutoflowSession(t){return P(this,null,function*(){let n=yield this.client.post("/autoflow-sessions",Oe(t));return oe(n)})}stopAutoflowSession(t){return P(this,null,function*(){yield this.client.delete(`/autoflow-sessions/${t}`)})}openStream(t){return this.streams[t]||(this.streams[t]=new Bl(`${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 mk={startTime:null,stopTime:null},gk=J({name:"handlingTime",initialState:mk,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(xe,()=>mk)}}),{handlingTimeStart:hk,handlingTimeStop:Hp,handlingTimeReset:yk}=gk.actions,vk=gk.reducer;var Sk=(e={})=>{let t=k({onAuthError:ii(!1)},e);return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var Up={list:{keywordMatches:[]},fetchState:"idle"};var ss=V("styleSuggestions/getAll",(n,r)=>P(void 0,[n,r],function*({text:e},t){var l;let{deepdeskAPI:o}=t.extra,s=t.getState(),{showStyleSuggestions:i}=s.settings,a=(l=s.conversation.current)==null?void 0:l.profileCode;if(!i)return Up.list;if(!a)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:a,message:e})})),S_=J({name:"styleSuggestions",initialState:Up,reducers:{},extraReducers:e=>{e.addCase(ss.pending,t=>{t.fetchState="loading"}).addCase(ss.rejected,t=>{t.fetchState="error"}).addCase(ss.fulfilled,(t,n)=>{t.fetchState="done",Xr(t.list,n.payload)||(t.list=n.payload)}).addCase(Mo,t=>{t.list=Up.list}).addCase(xe,()=>Up)}}),wk=S_.reducer;var xk=(e={})=>{let t,n=!0,r=k({getStyleSuggestions:ss,debounce:500},e);return o=>s=>i=>{var g;let a=o.getState().input.text,l=s(i),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 w_(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end}var bk=(e={})=>{let t=k({getTextSuggestions:xn,getAutocompleteSuggestions:wl,debounce:200,check:Fn},e),n;return r=>o=>s=>{var v;let{input:i}=r.getState(),a=o(s),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=s.type===tp.toString();if(!p||!u&&!c)return a;let{input:g}=l;return w_(g,i)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let f=ui(l);f===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(f))},d?0:t.debounce)),a}};var Ek=ss.fulfilled.toString();function x_(e,t){let n=new Set([...t.keywordMatches.map(o=>o.keyword)]),r=[];return n.forEach(o=>{let s=e.keywordMatches.filter(l=>l.keyword===o),i=t.keywordMatches.filter(l=>l.keyword===o),a=i.length-s.length;a<=0||r.push(...i.slice(0,a))}),r}var Ck=e=>t=>n=>r=>{var u;if(r.type!==Ek){n(r);return}let o=t.getState().styleSuggestions.list;n(r);let s=t.getState(),i=s.styleSuggestions.list,a=(u=s.conversation)==null?void 0:u.current;if(o===i)return;let l=x_(o,i);r.type===Ek&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var b_=Oc({assistants:jb,auth:I1,autoflows:$C,conversation:z1,contentTypes:Kb,customMessages:tT,passwordlessToken:oT,entities:vE,knowledgeAssistant:Fb,handlingTime:vk,info:sb,input:Z1,settings:E1,profile:qb,search:pb,styleSuggestions:wk,ui:oC,rules:uT,textSuggestions:BE});function Tk(e){return Ax({reducer:b_,middleware:t=>[...t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI,deepdeskBrokerAPI:e.deepdeskBrokerAPI}},serializableCheck:!1}),Sk(),bk({debounce:200}),xk({debounce:500}),Ck(e.deepdeskAPI),...e.middleware?e.middleware:[]],preloadedState:e.preloadedState})}var E_=e=>{var t,n;return(n=(t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())!=null?n:"unknown"},C_=e=>t=>n=>r=>{var a,l,u,c,p,d,g;let o=t.getState(),s=sh("inlineSuggestions")(o);switch(r.type){case ii.toString():{!r.payload&&e.emit("logout",void 0);break}case wn.fulfilled.toString():r.payload.length>0&&e.sendEvent("entities found",{conversationId:(a=o.conversation.current)==null?void 0:a.id,data:{entities:r.payload}});break;case pt.toString():e.sendEvent(r.payload.name,{conversationId:((l=r.payload.options)==null?void 0:l.includeConversationData)&&((u=o.conversation.current)==null?void 0:u.id),data:r.payload.data});break;case Mo.toString():e.logSendMessage(r.payload);break;case Jo.fulfilled.toString():r.isBroadcasted||e.broadcast(fh,r,!1),(c=r.payload.options)!=null&&c.shouldEmit&&e.emit("cues",r.payload.cues);break;case Fd.toString():e.emit("call-to-action",{cue:r.payload});break;case or.fulfilled.toString():r.isBroadcasted||e.broadcast(mh,r,!1);break;default:break}let i=n(r);switch(r.type){case Mo.toString():e.handleAfterSendMessage(r.payload);break;case bl.toString():e.onUpdateShowTabHint(r.payload);break;case Hp.toString():e.logHandlingTime();break;case"analytics/logEvent/fulfilled":{e.emit("event",r.meta.arg);break}case fd.toString():{let{start:y,end:v}=o.input.selection;e.emit("replace",L(k({},r.payload),{replace:r.payload.replace==="selection"?{start:y,end:v}:{start:0,end:v}}));break}case fn.toString():{let{start:y,end:v}=o.input.selection;e.emit("select-suggestion",L(k({type:E_(r.payload.suggestion)},r.payload),{replace:r.payload.replace==="selection"?{start:y,end:v}:{start:0,end:v}})),s&&t.dispatch(Jr([]));break}case md.toString():e.emit("select-image",r.payload),e.sendEvent("Image attached",{conversationId:(p=o.conversation.current)==null?void 0:p.id,data:{path:r.payload.suggestion.image,title:r.payload.suggestion.title}});break;case Jr.toString():{s&&r.payload.length>0&&t.dispatch(gd(0));break}case pi.fulfilled.toString():{e.sendEvent("conversation summarized",{conversationId:(d=o.conversation.current)==null?void 0:d.id,data:{summary:r.payload,assistant:(g=t.getState().profile.data)==null?void 0:g.summarizerAssistantNew}});break}default:break}return i},kk=C_;function Wy(e){return e.toISOString().replace("T"," ").replace("Z","")}function Pk(e,t){var s,i,a,l;let n=(s=e.conversation.current)==null?void 0:s.id;if(!n)return H.warn("No conversationId for handling time metrics"),null;let{startTime:r,stopTime:o}=e.handlingTime;return!r||!o?(H.warn("No startTime and stopTime for handling time metrics"),null):{conversationId:n,clientVersion:t.version,agentId:(i=e.info.agentInfo)==null?void 0:i.agentId,agentName:(a=e.info.agentInfo)==null?void 0:a.agentName,agentEmail:(l=e.info.agentInfo)==null?void 0:l.agentEmail,timeStart:Wy(r),timeStop:Wy(o)}}function Rk(e,t,n){var N,_,Q,K;let r=(N=t.conversation.current)==null?void 0:N.id;if(!r)return H.warn("No conversationId for send message metrics"),null;let{text:o,metrics:{numCharsTyped:s,numCharsPasted:i,numCharsCut:a,numCharsDeleted:l,numPaste:u,agentStartedTypingTimestamp:c,externalTimeTotalSeconds:p,pastes:d,cuts:g,deletions:y,textSuggestions:v,offeredTextSuggestions:f}}=t[e],m=o.length,S=v.reduce((W,{text:fe,searchTerm:Xe})=>W+fe.length-(Xe?Xe.length:0),0),x=c!=null?c:Date.now(),E=(Date.now()-x)/1e3+(p||0),C=s/E,R=v.reduce((W,{searchTerm:fe})=>W+(fe?fe.length:0),0);return{conversationId:r,source:"agent",text:o,clientVersion:n.version,pastes:d,cuts:g,deletions:y,lenTextTyped:s+R,lenTextTotal:m,lenTextAssisted:S,lenTextPasted:i,lenTextCut:a,lenTextDeleted:l,timeTotalSeconds:E,charsPerSecond:C,numPastes:u,textSuggestionsV2:v,suggestionsCounters:[{source:"gpt",countOffered:f.filter(W=>W.source==="gpt").length}],agentId:(_=t.info.agentInfo)==null?void 0:_.agentId,agentName:(Q=t.info.agentInfo)==null?void 0:Q.agentName,agentEmail:(K=t.info.agentInfo)==null?void 0:K.agentEmail}}function $y(e,t){var s;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return $y(r,t);let o=(s=e.ownerDocument.defaultView)==null?void 0:s.frameElement;return o?$y(o,t):null}function Ak(e,t){return $y(e,t)}function Ik(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function T_(e){return typeof e=="object"&&e!==null&&"tagName"in e}function zp(e){return T_(e)&&(Zo(e)||cp(e))}var Ok,zn=new Map,k_=["bottom","height","left","right","top","width"],Lk=(e,t)=>!e&&!t?!1:e&&!t||!e&&t?!0:k_.some(n=>e[n]!==t[n]);function Nk(e){var n,r,o;if(e.ownerDocument===document)return[];let t=(o=(r=(n=e.ownerDocument)==null?void 0:n.defaultView)==null?void 0:r.frameElement)!=null?o:null;return t?[t,...Nk(t)]:[]}function Mk(e,t){return!e||!t?null:L(k({},e),{top:e.top+t.top,left:e.left+t.left})}var Bp=!1,_k=()=>{Bp=!0;let e=[];if(zn.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),zn.delete(n);return}let r=n.getBoundingClientRect();Lk(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{let n=t.parentRects?t.parentRects.reduce(Mk,t.rect):t.rect;Lk(n,t.totalRect)&&t.callbacks.forEach(r=>r(n)),t.totalRect=n}),zn.size===0){Bp=!1;return}Ok=window.requestAnimationFrame(_k)};function qy(e,t){let n=Nk(e),r=[],o=n.map((s,i)=>qy(s,a=>{r[i]=a;let l=zn.get(e);if(!l)return;let u=r.reduce(Mk,l.rect);l.callbacks.forEach(c=>c(u))}));return{observe(s=!0){if(o.forEach(i=>i.observe(!1)),zn.has(e)){let i=zn.get(e);i.callbacks.push(t),i.rect&&t(i.rect)}else zn.set(e,{rect:void 0,callbacks:[t],parentRects:r});s&&!Bp&&_k()},unobserve(){o.forEach(i=>i.unobserve());let s=zn.get(e);if(s){let i=s.callbacks.indexOf(t);i>=0&&s.callbacks.splice(i,1),s.callbacks.length||zn.delete(e),zn.size||(cancelAnimationFrame(Ok),Bp=!1)}}}}var Dk,Bn=new Map,Fk=()=>{Bn.forEach((e,t)=>{if(!t.isConnected){Bn.delete(t);return}let{clientHeight:n,scrollHeight:r}=t,o=r>n;e.visible!==o&&(e.visible=o,e.callbacks.forEach(s=>s(e.visible)))}),Bn.size!==0&&(Dk=window.requestAnimationFrame(Fk))};function Hk(e,t){return{observe(){let n=Bn.size===0;Bn.has(e)?Bn.get(e).callbacks.push(t):Bn.set(e,{visible:void 0,callbacks:[t]}),n&&Fk()},unobserve(){let n=Bn.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||Bn.delete(e),Bn.size||cancelAnimationFrame(Dk)}}}}var Gy=["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 Yy(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function Li(e){return parseFloat(e)}function jp(e){return Math.round(e*1e6)}function Uk(e){return e/1e6}function Qy(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=Li(e.width),s=Li(e.borderLeftWidth),i=Li(e.borderRightWidth),a=Li(e.paddingRight),l=Uk(jp(o)-jp(s)-jp(i)),u=Uk(jp(r));if(l-u>2){let c=l-u;n.style.paddingRight=`${a+c}px`}}function Vl(e,t={}){var c,p;let n=t.overlayContainer||document.createElement("div");n.style.display="none",n.style.position=(c=t.position)!=null?c:"fixed",n.style.pointerEvents="none",n.style.borderColor="transparent",Yo(n);let r=window.getComputedStyle(e),o=!0,s=()=>{n.scrollTop=e.scrollTop};Yy(r,n,Gy),Qy(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",s));let i=Hk(e,()=>{Yy(r,n,Gy),Qy(r,e,n),s(),setTimeout(s,0)}),a,l=!0,u=qy(e,d=>{if(d===null){t.onRemove&&t.onRemove(),n.remove();return}if(!l&&t.onMoveStart&&(Promise.resolve().then(()=>t.onMoveStart()),l=!0),clearTimeout(a),a=setTimeout(()=>{t.onMoveEnd&&t.onMoveEnd(),l=!1},200),d.height===0&&d.width===0){if(o===!0)return;t.onHide&&t.onHide(),n.style.display="none",o=!0;return}if(Yy(r,n,Gy),Qy(r,e,n),s(),n.style.top=`${d.top}px`,n.style.left=`${d.left}px`,t.closestScrollElement&&t.closestScrollElement!==e){let g=t.closestScrollElement.getBoundingClientRect(),y=window.getComputedStyle(t.closestScrollElement),v=Li(y.borderTopWidth),f=Li(y.borderBottomWidth),m=g.top+v-d.top,h=d.top+d.height+-(g.top+g.height-f);n.style.clipPath=`inset(${m}px 0px ${h}px 0px)`}o&&(n.style.display="block",t.onShow&&t.onShow(),o=!1)});return t.appendTo?t.appendTo.appendChild(n):(p=e.parentElement)==null||p.appendChild(n),u.observe(),i.observe(),[n,()=>{e.removeEventListener("scroll",s),u.unobserve(),i.unobserve()}]}var zk=(e,t)=>({value(){try{let n=sessionStorage.getItem(`dd-${e}`);if(!n)return t;try{return JSON.parse(n)}catch(r){return t}}catch(n){return t}},update(n){try{sessionStorage.setItem(`dd-${e}`,JSON.stringify(n))}catch(r){H.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function P_(e){return e.offsetParent!==null}function Bk(e){if(!P_(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 Vp(e,t,n=100){let r=Bk(e);t({isVisible:r});let o=setInterval(()=>{let s=Bk(e);s!==r&&(r=s,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var He=w(T());var jk=zk("showTabHint",!0),Oi=class Oi{constructor({deepdeskUrl:t,brokerUrl:n,version:r=Oi.version||"unknown",locale:o="en-US",token:s,fetch:i,productName:a,createCustomChannel:l}){this.inputMediator=null;this.eventListeners={};this.unmountHandlers=[];this.widgetRoot=null;this.dynamicThunkObject={};this.isMounted=!1;this.shouldRender=!0;this.loadProfileConfigPromise=null;let u=t.replace(/\/api$/,"");this.deepdeskApi=new br(u,{token:s,fetch:i}),this.version=r,this.instanceId=Oi.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[kk({broadcast:(p,d,g)=>{this.broadcastEvents.send(p,d,g)},emit:(p,d)=>this.emit(p,d),handleAfterSendMessage:p=>this.handleAfterSendMessage(p),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:p=>this.logSendMessage(p),onUpdateShowTabHint:p=>jk.update(p),sendEvent:(p,d)=>this.deepdeskApi.sendEvent(p,d)})]};n&&Object.assign(c,{deepdeskBrokerAPI:new jl(n)}),this.store=Tk(c),this.broadcastEvents=new dk({debug:!0,deepdeskUrl:u,eventMap:fb(this.store),createCustomChannel:l}),this.store.dispatch(bl(jk.value())),this.store.dispatch(ad({locale:o,adminUrl:u,productName:a}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){var t;return(t=this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex])!=null?t:null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}sessionId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.sessionId}shouldAbort(){return this.state.conversation.isSupported===!1?(H.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(H.warn("Profile has not been loaded (yet)"),!0):(H.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(ii(null)),this.store.dispatch(nr()),new Promise(t=>{let n=this.store.subscribe(()=>{let r=this.store.getState();dt(r)&&C1(r)!=="loading"&&(n(),t())});this.unmountHandlers.push(()=>{n()})})}isLoggedIn(){return P(this,null,function*(){return(yield this.store.dispatch(nr())).payload})}isConversationSupported(t,n){return P(this,null,function*(){return(yield this.store.dispatch(lh({sessionId:t,options:n}))).payload})}createConversation(t){return P(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(yield this.store.dispatch(ud(t))).payload})}getConversationBySessionId(t,n){return P(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t&&this.resetConversation(),(yield this.store.dispatch(cd({sessionId:t,options:n}))).payload})}upsertConversation(t){return P(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(yield this.store.dispatch(uh(t))).payload})}postMessages(t){return P(this,null,function*(){return(yield this.store.dispatch(pd(t))).payload})}updateConversation(t){return P(this,null,function*(){return(yield this.store.dispatch(dd(t))).payload})}resetConversation(){this.store.dispatch(xe()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}configure(t){this.store.dispatch(ad(t))}setVisitorInfo(t){this.store.dispatch(nb(t))}setCustomData(t){this.store.dispatch(rb(t))}setAgentInfo(t,n){return P(this,null,function*(){yield this.store.dispatch(Ga(k(k({},t),n)))})}setAgentSettings(t){return P(this,null,function*(){yield this.store.dispatch(dh(t))})}getAgentSettings(){return P(this,null,function*(){return(yield this.store.dispatch(ph())).payload})}refresh(){return P(this,null,function*(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.store.dispatch(hd({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()}));let t=[];return this.store.dispatch(tp()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})})}notifyExternalSuggestion(t){this.store.dispatch(fn(t))}evaluateRule(o){return P(this,arguments,function*(t,n={},r=sT){return(yield this.store.dispatch(Jo({label:t,params:n,options:r}))).payload.cues})}evaluateAssistant(t,n){return P(this,null,function*(){let c=n||{},{input:r={},transcript:o,showCuesInWidget:s=!0,includeTags:i,expectFormat:a}=c,l=ee(c,["input","transcript","showCuesInWidget","includeTags","expectFormat"]);Object.assign(r,l);let u=yield this.store.dispatch(or({assistantCode:t,expectFormat:a||"json-schema:cues",transcript:o,includeTags:i,input:r,skipState:!s}));if(u.error)throw new Error(u.error.message);return u.payload})}evaluateConversationAssistant(t,n){return P(this,null,function*(){yield this.loadProfileConfig();let r={accepted:"conversationAcceptedAssistant","new-message":"conversationNewMessageAssistant",ended:"conversationEndedAssistant"},o=this.state.profile.data[r[t]];if(!o){H.warn(`No assistant set in profile for conversation event "${t}"`);return}yield this.evaluateAssistant(o,k({transcript:"stored-transcript",includeTags:!0},n))})}getSummary(){return P(this,null,function*(){var n;if(!this.hasConversation())return H.warn("No conversation to create summary for."),null;(n=this.state.profile.data)!=null&&n.summarizerAssistantNew||H.warn("No profile loaded yet, or no summarizer assistant set in profile");let t=yield this.store.dispatch(pi({}));if(t.error)throw new Error(t.error.message);return t.payload})}handleKeyDown(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui,{textSuggestions:o,selectedSuggestionIndex:s,selection:i}=this.state.input,{inlineSuggestions:a,showTextSuggestions:l}=this.state.settings,u=a?"below":"above",c=o.length>0;if(!Fn(this.state)||(this.store.dispatch(W1(ch(t))),t.key!=="Tab"&&!l))return;let p=()=>{n||!c||i&&(t.shiftKey||(this.store.dispatch(G1()),t.preventDefault()))},d=()=>{n||!c||a&&s<=0||i&&(t.shiftKey||(this.store.dispatch(Y1()),t.preventDefault()))};switch(t.key){case"ArrowUp":u==="below"?d():p();break;case"ArrowDown":{u==="below"?p():d();break}case"Escape":{n||(this.store.dispatch(gd(-1)),this.store.dispatch(io({collapse:!0})),this.store.dispatch(nC(!0)),t.preventDefault());break}case"Tab":{t.preventDefault();let g=ci(this.state);if(!g)return;this.store.dispatch(bl(!1)),this.store.dispatch(fn({text:g.text,suggestion:g,eventMetrics:{inputType:"tab"},replace:"until-selection-end"}));break}case" ":{if(this.state.settings.inlineSuggestions||this.state.input.selectedSuggestionIndex===-1)return;let g=ci(this.state);if(!g)return;this.store.dispatch(fn({text:g.text,suggestion:g,eventMetrics:{inputType:"space"},replace:"until-selection-end"}));break}case"Enter":{if(this.state.settings.inlineSuggestions||t.shiftKey||this.state.input.selectedSuggestionIndex===-1)return;let g=ci(this.state);if(!g)return;this.store.dispatch(fn({text:g.text,suggestion:g,eventMetrics:{inputType:"enter"},replace:"until-selection-end"})),t.preventDefault();break}default:}n&&r&&this.store.dispatch(io({collapse:!1}))}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(Jr([]))}handlingTimeStart(){this.state.handlingTime.startTime||(H.info("Start handling time"),this.store.dispatch(hk()))}handlingTimeStop(){this.state.handlingTime.startTime&&(H.info("Stop handling time"),this.store.dispatch(Hp()))}logSendMessage(t){let n=Rk("input",this.state,{version:this.version});n&&(t&&(Object.assign(n,{text:t}),Object.assign(n,{lenTextTotal:t.length})),this.deepdeskApi.sendEventV1("Send Message",n),this.emit("send-message-event",n))}logHandlingTime(){let t=Pk(this.state,{version:this.version});t&&(this.deepdeskApi.sendEventV1("Handling Time",t),this.store.dispatch(yk()))}notifySubmit(t={}){var n;this.shouldAbort()||(this.store.dispatch(Mo((n=t.text)!=null?n:this.state.input.text)),this.store.dispatch(X1()))}emit(t,n){let r=this.eventListeners[t];r&&r.forEach(o=>{try{o(n)}catch(s){H.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),H.error(s)}})}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),()=>{this.off(t,n)}}off(t,n){if(!t&&!n){this.eventListeners={};return}let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}setConversationQuery(t){this.dynamicThunkObject.conversationQuery=t}setPlatformVariables(t){this.store.dispatch(ob(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[s,i]=Vl(n,r);return s.setAttribute("translate","no"),s.dataset.testid=t,o&&s.classList.add(o),this.unmountHandlers.push(()=>{(0,ln.unmountComponentAtNode)(s),i(),s.remove()}),s}createInlineContainer(t,n){var a;let r=document.createElement("div");r.style.position="absolute",r.style.top="0px",r.style.left="0px",r.style.height="0px",r.style.width="0px";let o=document.createElement("div");o.style.display="none",o.style.position="absolute",o.style.height="0px",o.style.width="0px",o.style.backgroundColor="red",r.appendChild(o);let s=(a=t.ownerDocument.defaultView)==null?void 0:a.frameElement,i=s?s.ownerDocument.defaultView:null;if(s&&(i===window||(i==null?void 0:i.parent)===window)){let[l,u]=Vl(s,{appendTo:document.body,onMoveStart:()=>{o.style.display="none"}});l.dataset.testid=n,l.style.zIndex="2",l.appendChild(r),this.unmountHandlers.push(()=>{(0,ln.unmountComponentAtNode)(o),u()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return Yo(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,ln.unmountComponentAtNode)(o),o.remove()}),o}storeMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(t,n),H.info(`Stored analytics for ${this.conversationId()}`)}catch(t){}}restoreMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=window.sessionStorage.getItem(t);if(!n)return;let r=JSON.parse(n);r.text.trim()===this.state.input.text.trim()?(H.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(Q1(r.metrics))):H.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(t)}catch(t){}}mount(t,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!zp(t))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let{customStyles:r={},showStyleSuggestions:o,showTabCompletion:s,showTextSuggestions:i,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:s,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,showTextSuggestions:i,insertLink:g,isEmbedded:p,inlineSuggestions:m,floatingMenu:!!h}),n.automaticHandlingTime&&this.setupHandlingTime(t),Yo(t),this.inputMediator=y||(Zo(t)?new rs(t):new ns(t)),this.inputMediator.on("change",({plainText:E,rawHTML:C})=>{this.store.dispatch(hd({text:E,html:C}))}),this.inputMediator.on("keyup",E=>{this.store.dispatch($1(ch(E)))}),this.inputMediator.on("keydown",E=>{this.handleKeyDown(E)}),this.inputMediator.on("paste",({pastedText:E,selectionText:C})=>{this.store.dispatch(q1({text:E,selectionText:C}))}),this.inputMediator.on("cut",({selectionText:E})=>{this.store.dispatch(K1(E))});let S;this.inputMediator.on("selection",E=>{clearTimeout(S),E===null?S=setTimeout(()=>{E!==null&&this.store.dispatch(yd(E))},500):this.store.dispatch(yd(E))}),this.inputMediator.on("disabled",()=>{var E;(E=this.inputMediator)==null||E.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(op(!1))}),this.inputMediator.on("focus",()=>{this.store.dispatch(op(!0))});let x=v&&Ak(t,v)||void 0;if(m){let{customStyles:E,appendOverlayTo:C}=n,R=this.createInlineContainer(t,"deepdesk-caret");(0,ln.render)((0,He.jsx)(Xo,{store:this.store,customStyles:E,children:(0,He.jsx)(Do,{broadcastEvents:this.broadcastEvents,children:(0,He.jsx)(cC,{})})}),R),this.inputMediator.on("caretposition",_=>{_?(R.style.display="block",R.style.top=`${_.top}px`,R.style.left=`${_.left}px`):R.style.display="none"});let N=this.overlayContainerFactory("floating-menu",x||t,{appendTo:typeof h=="object"&&"appendOverlayTo"in h?h.appendOverlayTo:C},E==null?void 0:E.floatingMenuRootNode);(0,ln.render)((0,He.jsx)(Xo,{store:this.store,customStyles:E,children:(0,He.jsx)(Do,{broadcastEvents:this.broadcastEvents,children:(0,He.jsx)(JE,{onLogIn:()=>this.loginViaPopup().catch(_=>H.warn(_.message))})})}),N)}else{let E=this.overlayContainerFactory("deepdesk-tab-completion",x||t,{appendTo:f,closestScrollElement:x,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),C=this.overlayContainerFactory("deepdesk-suggestions-overlay",x||t,{appendTo:f},r==null?void 0:r.suggestionsRootNode);(0,ln.render)((0,He.jsx)(Xo,{store:this.store,customStyles:r,children:(0,He.jsx)(Do,{broadcastEvents:this.broadcastEvents,children:(0,He.jsx)(zC,{inputElement:t})})}),E),(0,ln.render)((0,He.jsx)(Xo,{store:this.store,customStyles:r,children:(0,He.jsx)(Do,{broadcastEvents:this.broadcastEvents,children:(0,He.jsx)(SC,{onLogIn:()=>this.loginViaPopup().catch(R=>H.warn(R.message))})})}),C)}(0,ln.render)((0,He.jsx)(Xo,{store:this.store,customStyles:r,children:(0,He.jsx)(Do,{broadcastEvents:this.broadcastEvents,children:(0,He.jsx)(GE,{})})}),this.createContainer("deepdesk-overlays")),this.store.dispatch(hd({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()})),this.store.dispatch(yd(this.inputMediator.getSelection())),this.store.dispatch(op(this.inputMediator.isFocused)),this.unmountHandlers.push(()=>{this.state.input.text!==""&&this.storeMetrics()}),this.whenConversationLoaded(()=>{var E;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((E=this.state.conversation.current)==null?void 0:E.sessionId)}),this.isMounted=!0}unmount(){var t;this.unmountHandlers.forEach(n=>n()),this.unmountHandlers=[],(t=this.inputMediator)==null||t.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(t,n={}){if(this.widgetRoot&&H.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,isEmbedded:s}=n;this.widgetRoot=t,this.configure({showImages:o,isEmbedded:s}),(0,ln.render)((0,He.jsx)(Xo,{store:this.store,customStyles:r,children:(0,He.jsx)(Do,{broadcastEvents:this.broadcastEvents,children:(0,He.jsx)(sk,{onLogIn:()=>this.loginViaPopup().catch(i=>H.warn(i.message))})})}),t),this.whenConversationLoaded(()=>{var i;this.broadcastEvents.setSessionId((i=this.state.conversation.current)==null?void 0:i.sessionId)})}unmountWidget(){this.widgetRoot&&(0,ln.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(t){let n=Vp(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){Ik(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(()=>P(this,null,function*(){yield this.store.dispatch(al());let t=sr(this.state);t&&(yield this.store.dispatch(rl()),this.store.dispatch(ad({showSearch:t.search,showAutoflows:t.autoflows,showCustomMessages:t.customMessages,showImageSearch:t.imageSearch,showEntitiesCommand:t.entitiesCommand,showSummaryCommand:!!t.summarizerAssistantNew||t.summarizer,showKnowledgeSearch:!!t.knowledgeAssistantNew||!!t.knowledgeAssistant,recommendTextSuggestions:t.recommendTextSuggestions})))})),this.loadProfileConfigPromise)}loginViaPopup(t){return P(this,null,function*(){return new Promise((n,r)=>{let o=new MessageChannel,s=o.port1,i=this.state.settings.adminUrl,a=new URL(t!=null&&t.url?t==null?void 0:t.url:`${i}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let l=!1,u=()=>{c&&!c.closed&&c.close(),window.removeEventListener("message",p),clearInterval(d)};s.onmessage=g=>P(this,null,function*(){var y,v;if((y=g.data)!=null&&y.jwt)try{yield this.deepdeskApi.exchangeTokenForAccessCookie((v=g.data)==null?void 0:v.jwt),yield this.isLoggedIn(),this.broadcastEvents.send(Qa),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=g=>P(this,null,function*(){var y;if(g.origin===a.origin)switch((y=g.data)==null?void 0:y.type){case"deepdesk-popup-loaded":{try{let v=JSON.stringify({type:"deepdesk-popup-create-channel"});c==null||c.postMessage(v,a.origin,[o.port2])}catch(v){H.error("Error posting message to popup",v),r(v)}break}case"deepdesk-popup-error":{u(),g.data.message==="Timeout"&&H.warn("Popup timed out. Check if the account's platform url is configured correctly."),r(new Error(g.data.message));break}}});window.addEventListener("message",p);let d=setInterval(()=>{c&&!c.closed||(u(),l||r(new Error("Popup closed by user")))},200);this.unmountHandlers.push(u)})})}translateMessages(t){return this.deepdeskApi.translateMessages(t)}checkForTrialMode(t){return P(this,null,function*(){try{let{account:n}=yield this.deepdeskApi.getPlatformConfig();if(!n.isTrial){this.shouldRender=!0;return}if(H.info("Trial is active"),!(yield this.deepdeskApi.checkUserExists(t)))throw new Error("User is not in trial");this.shouldRender=!0}catch(n){let{message:r}=n;H.info(r),this.shouldRender=!1}})}refreshWidgetSuggestions(){return P(this,null,function*(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=ll(this.state);try{n.forEach(({type:r})=>{r==="entities"?this.store.dispatch(wn()):pu.includes(r)||this.store.dispatch(xn(r))})}catch(r){this.handleError(r)}})}};Oi.version="14.3.1-beta.0",Oi.count=0;var Kl=Oi;function R_(e){return P(this,null,function*(){var o,s,i;let n=yield((o=e.fetch)!=null?o:window.fetch)(e.url),r=yield n.blob();return new File([r],e.name,{type:(i=(s=e.mimeType)!=null?s:n.headers.get("Content-Type"))!=null?i:"image/jpeg"})})}function Vk(e,t){return P(this,null,function*(){let n=yield R_(t),r=new Event("change",{bubbles:!0,cancelable:!0});try{Object.defineProperty(e,"files",{configurable:!0,get:()=>[n]}),e.dispatchEvent(r)}finally{Object.hasOwn(e,"files")&&delete e.files}})}function Kk(e,t,n){return P(this,null,function*(){yield new br(e).authenticateWithKey(t,n)})}function Wk(e){return e.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}function $k(r,o){return P(this,arguments,function*(e,t,n={}){var p,d;let{value:s}=e,{start:i,end:a}=(p=n.replace)!=null?p:{start:0,end:s.length},l=`${s.slice(0,i)}${t}${s.slice(a)}`,u=(d=n.selectionAfter)!=null?d:{start:i+t.length,end:i+t.length},c=()=>{if(n.setValue)return n.setValue(l);e.value=l};return Promise.resolve(c()).then(()=>{e.selectionStart=u.start,e.selectionEnd=u.end,e.blur(),e.focus()})})}function qk(r,o){return P(this,arguments,function*(e,t,n={}){let s=n.replace?co(e,n.replace.start,n.replace.end):Ri(e),i,a=()=>{if(n.setRange)return n.setRange(s.cloneRange());s.deleteContents(),i=document.createElement("span"),s.insertNode(i),n.insertBRs!==!1?t.split(`
27
+ `);let y=d?r:0,v=g?Math.min(s,c.childNodes.length):c.childNodes.length;for(let f=y;f<v&&(u(c.childNodes[f]),a!==2);f++);break}default:break}g&&(a=2)}return u(e),l}var ak=(i=>(i.CUT="Cut",i.BACKSPACE="Backspace",i.DELETE="Delete",i.ERASEEOF="EraseEof",i.UNDO="Undo",i.CLEAR="Clear",i))(ak||{}),wr=class{constructor(t){this.element=t;this.isFocused=!1;this.isActive=!0;this.isDisposed=!1;this.eventListeners={};this.disposeHandlers=[];this.cachedText="";this.cachedCaretPosition=null;this.cachedSelection={start:0,end:0};this.cachedHTML="";this.isSubmitting=!1;this.isPossibleClearInputAction=!1;this.cachedText=this.getText(),this.cachedHTML=this.getHTML(),this.cachedSelection=this.getSelection(),this.listen()}addEventListener(t,n){let r=o=>{n(o)};this.element.addEventListener(t,r),this.disposeHandlers.push(()=>{this.element.removeEventListener(t,r)})}removeEventListener(t,n){this.element.removeEventListener(t,n)}handleInteraction(){let t=this.getText(),n=this.getHTML(),r=this.getSelection(),o=this.cachedCaretPosition===null;if(!this.isActive||(t===""&&this.cachedText!==""&&!this.isPossibleClearInputAction&&this.emit("submit"),t!==this.cachedText?(this.cachedText=t,this.cachedHTML=n,o=!0,this.emit("change",{plainText:t,rawHTML:n})):n!==null&&n!==this.cachedHTML&&(this.cachedHTML=n,o=!0,this.emit("change",{plainText:t,rawHTML:n})),(r.start!==this.cachedSelection.start||r.end!==this.cachedSelection.end)&&(this.cachedSelection=r,o=!0,this.emit("selection",r)),!o))return;let s=this.getCaretPosition();Xr(s,this.cachedCaretPosition)||(this.cachedCaretPosition=s,this.emit("caretposition",s))}handleClick(){this.handleInteraction()}handleFocus(){let t=!this.isFocused;this.isFocused=!0,t&&this.emit("focus"),this.handleInteraction()}handleBlur(){this.isPossibleClearInputAction=!1;let t=this.isFocused;this.isFocused=!1,t&&this.emit("blur")}handleKeyDown(t){let{key:n,ctrlKey:r,metaKey:o}=t;this.isPossibleClearInputAction=Object.values(ak).includes(n)||n.toLowerCase()==="z"&&(r||o),this.emit("keydown",t)}handleKeyUp(t){this.handleInteraction(),this.emit("keyup",t)}handleCut(){this.isPossibleClearInputAction=!0,this.emit("cut",{selectionText:this.getSelectedText()})}handlePaste(t){var r,o;let n=((r=t.clipboardData)==null?void 0:r.getData("text"))||((o=t.clipboardData)==null?void 0:o.getData("text/plain"))||"";this.emit("paste",{pastedText:n,selectionText:this.getSelectedText()})}listen(){this.addEventListener("keydown",n=>this.handleKeyDown(n)),this.addEventListener("keyup",n=>this.handleKeyUp(n)),this.addEventListener("input",()=>this.handleInteraction()),this.addEventListener("change",()=>this.handleInteraction()),this.addEventListener("focus",()=>this.handleFocus()),this.addEventListener("blur",()=>this.handleBlur()),this.addEventListener("cut",()=>this.handleCut()),this.addEventListener("paste",n=>this.handlePaste(n)),this.addEventListener("click",()=>this.handleInteraction()),document.activeElement===this.element&&(this.isFocused=!0);let t=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});t.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{t.disconnect()})}focus(){this.element.focus()}emit(t,...n){this.isDisposed||this.eventListeners[t]&&this.eventListeners[t].forEach(r=>{r(...n)})}on(t,n){this.isDisposed||(this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n))}activate(){let t=this.isActive===!1;this.isActive=!0,t&&this.handleInteraction()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(t=>t()),this.eventListeners={},this.isDisposed=!0}};function lk(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var ns=class extends wr{constructor(){super(...arguments);this.lastKnownSelection=null}getRootNode(){return this.element.getRootNode()}getText(){let n=new Range;return n.selectNodeContents(this.element),zl(this.element,n)}getHTML(){return this.element.innerHTML||""}getRange(){var i;let n=this.getRootNode();if(n.activeElement!==this.element)return null;let r="getSelection"in n?n.getSelection():window.getSelection();if(!r)return null;let o="getComposedRanges"in r&&n instanceof ShadowRoot?(i=r.getComposedRanges(n))==null?void 0:i[0]:r.rangeCount>0?r.getRangeAt(0):null;if(!o)return null;let s=this.element.ownerDocument.createRange();return s.setStart(o==null?void 0:o.startContainer,o==null?void 0:o.startOffset),s.setEnd(o==null?void 0:o.endContainer,o==null?void 0:o.endOffset),!s||!this.element.contains(s.startContainer)||!this.element.contains(s.endContainer)?null:s}getCaretPosition(){let n=this.getRange();if(!n||!n.collapsed||!("getBoundingClientRect"in n))return null;let r=n.getBoundingClientRect();return!lk(r)&&(n.insertNode(this.element.ownerDocument.createTextNode("\u2060")),r=n.getBoundingClientRect(),n.deleteContents(),!lk(r))?null:{top:r.top+r.height,left:r.left}}getSelection(){let n=this.getRange();if(n)return Ul(this.element,n);let r=this.lastKnownSelection;if(r&&ik(this.element,r.start,r.end))return r;let o=Ri(this.element);return o.collapse(!1),Ul(this.element,o)}getSelectedText(){let{start:n,end:r}=this.getSelection();return zl(this.element,co(this.element,n,r))}listen(){super.listen();let n=new MutationObserver(s=>{var i,a;s.length===2&&s[0].addedNodes.length===1&&((i=s[0].addedNodes[0])==null?void 0:i.textContent)==="\u2060"&&((a=s[1].removedNodes[0])==null?void 0:a.textContent)==="\u2060"||setTimeout(()=>{this.handleInteraction()},0)});n.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0}),this.disposeHandlers.push(()=>n.disconnect());let r=this.element.isContentEditable,o=new MutationObserver(()=>{this.element.isContentEditable!==r&&(r=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>o.disconnect())}};var g_=["direction","boxSizing","width","height","overflowX","overflowY","borderTopWidth","borderRightWidth","borderBottomWidth","borderLeftWidth","borderStyle","paddingTop","paddingRight","paddingBottom","paddingLeft","fontStyle","fontVariant","fontWeight","fontStretch","fontSize","fontSizeAdjust","lineHeight","fontFamily","textAlign","textTransform","textIndent","textDecoration","letterSpacing","wordSpacing","tabSize"];function uk(e,t){let n="mozInnerScreenX"in window,r=document.createElement("div");r.id="input-textarea-caret-position-mirror-div";let o=r.style,s=window.getComputedStyle(e),i=e.ownerDocument.body;o.whiteSpace="pre-wrap",o.wordWrap="break-word",o.position="absolute",o.visibility="hidden",g_.forEach(function(c){o[c]=s[c]}),n?e.scrollHeight>parseInt(s.height)&&(o.overflowY="scroll"):o.overflow="hidden",r.textContent=e.value.substring(0,t);let a=document.createElement("span");a.textContent=e.value.substring(t)||".",r.appendChild(a),i.appendChild(r);let l=e.getBoundingClientRect(),u={top:l.top-e.scrollTop+a.offsetTop+parseInt(s.borderTopWidth)+a.offsetHeight,left:l.left-e.scrollLeft+a.offsetLeft+parseInt(s.borderLeftWidth)};return i.removeChild(r),u}var rs=class extends wr{constructor(){super(...arguments);this.lastKnownSelection=null}getText(){return this.element.value}getHTML(){return null}getSelection(){let{selectionStart:n,selectionEnd:r}=this.element;return{start:n,end:r}}getSelectedText(){let n=this.getSelection();return n?this.getText().slice(n.start,n.end):""}getCaretPosition(){return uk(this.element,this.element.selectionEnd)}listen(){super.listen();let n=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var s;return(s=n==null?void 0:n.get)==null?void 0:s.call(this.element)},set:s=>{var i;(i=n==null?void 0:n.set)==null||i.call(this.element,s),this.handleInteraction()}}),this.addEventListener("scroll",()=>{this.emit("caretposition",this.getCaretPosition())});let r=this.element.disabled,o=new MutationObserver(()=>{this.element.disabled!==r&&(r=this.element.disabled,this.emit(r?"disabled":"enabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>o.disconnect())}};function ck(e,t,n){let r=`deepdesk-iframe-${e}`,o=document.getElementById(r);if(o)return o;let s=document.createElement("iframe"),i=new URL(t);return Object.entries(n).forEach(([a,l])=>{i.searchParams.append(a,l)}),s.style.position="absolute",s.style.left="-999em",s.style.width="0px",s.style.height="0px",s.tabIndex=-1,s.id=r,s.title=`iframe-${e}`,s.src=i.toString(),window.document.body.appendChild(s),s}function h_(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch(t){return e}}var Hy=class{constructor(t){this.name=t;this.disposeHandlers=[];this.broadcastChannel=new BroadcastChannel(t)}onMessage(t){this.broadcastChannel.addEventListener("message",t),this.disposeHandlers.push(()=>{this.broadcastChannel.removeEventListener("message",t)})}postMessage(t){this.broadcastChannel.postMessage(JSON.stringify(t))}close(){this.disposeHandlers.forEach(t=>t()),this.broadcastChannel.close()}},Uy=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.disposeHandlers=[];this.iframe=ck(t,`${this.targetOrigin}/sdk/proxy/proxy.html`,{channel:this.name,host:window.location.origin,debug:"1"}),document.body.appendChild(this.iframe)}onMessage(t){window.addEventListener("message",t),this.disposeHandlers.push(()=>{window.removeEventListener("message",t)})}postMessage(t){var n;(n=this.iframe.contentWindow)==null||n.postMessage(JSON.stringify(t),this.targetOrigin)}close(){var t;this.disposeHandlers.forEach(n=>n()),(t=this.iframe)==null||t.remove()}},zy=class{constructor(t){this.params=t;this.deepdeskUrl=t.deepdeskUrl,this.eventMap=t.eventMap,this.sessionId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setSessionId(t){this.sessionId!==t&&(this.cleanup(),H.info("Set sessionId",t),this.sessionId=t,this.channel=this.createChannel(t))}createChannel(t){let n=this.params.createCustomChannel?this.params.createCustomChannel(t):this.isCrossOrigin?new Uy(t,this.deepdeskUrl,{debug:!0}):new Hy(t),r=o=>{var i,a;if(o.origin!==this.deepdeskUrl)return;let s=h_(o.data);typeof s!="object"||s.type!=="event"||s.channel!==t||(H.info("Received broadcast event",this.sessionId,o),(a=(i=this.eventMap)[s.name])==null||a.call(i,s.payload))};return n.onMessage(r),n}send(t,n,r){var i,a;H.info("Broadcast event",{sessionId:this.sessionId,name:t,payload:n});let o={type:"event",name:t,payload:n};r!==!1&&((a=(i=this.eventMap)[t])==null||a.call(i,n));let s=this.sessionId==="deepdesk-general"?this.defaultChannel:this.channel;s==null||s.postMessage(L(k({},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)}},dk=zy;function y_(e){return e.replace(/(_\w)/g,t=>t[1].toUpperCase())}function oe(e){return Array.isArray(e)?e.map(oe):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>L(k({},t),{[y_(n)]:oe(e[n])}),{}):e}function By(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function Oe(e){return Array.isArray(e)?e.map(Oe):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>L(k({},t),{[By(n)]:Oe(e[n])}),{}):e}var Ai=class extends Error{constructor(n,r){super(n);this.body=r;this.name="CustomError"}};var jy=e=>new Promise(t=>{setTimeout(t,e)});var Ii=class extends Ai{constructor(){super(...arguments);this.name="ClientError"}},Ky=class extends Ai{constructor(){super(...arguments);this.name="ServerError"}},Vy=new Map;function v_(e){return P(this,null,function*(){if(e.status===204)return e.text().catch(()=>{}),null;let t=e.headers.get("content-type");if(t&&t.includes("application/json"))return e.json();let n=yield e.text();return n===""?null:(H.warn("Unexpected response body:",n.slice(0,20)),JSON.parse(n))})}var po=class po{constructor(t="",n={}){this.baseUrl=t;this.options=n;this.latestRequestByUrl={};this.fetch=window.fetch.bind(window);n.fetch&&(this.fetch=n.fetch)}patchFetch(t){this.fetch=t(this.fetch)}setCsrfToken(t){this.csrfToken=t}request(t,n={}){return new Promise((r,o)=>{let s={isAborted:!1,reject:o},i=`${this.baseUrl}${t}`,a=this.fetch,l=n.method===void 0||n.method.toLowerCase()==="get",C=n,{useCache:u=!1,abortLatest:c=!1,attempts:p=1,retryDelay:d=500,refreshTokenOn401:g=!0,retryOnError:y=R=>R instanceof TypeError,retryOnResponse:v=R=>R.status>=500,version:f=null}=C,m=ee(C,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]);if(u)if(l){if(Vy.has(i)){r(Vy.get(i));return}}else throw new Error(`Can't use 'useCache' for ${n.method}`);let h=L(k({credentials:"include"},m),{headers:k({Accept:"application/json","Content-Type":"application/json"},m.headers)});!l&&this.csrfToken&&(h.headers=L(k({},h.headers),{"X-CSRFToken":this.csrfToken})),typeof f=="string"&&(h.headers=L(k({},h.headers),{"X-Deepdesk-API-Version":f}));let S=p,x=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[i]&&c&&(this.latestRequestByUrl[i].isAborted=!0,this.latestRequestByUrl[i].reject(new Error("Aborted"))),this.latestRequestByUrl[i]=s;let E=()=>P(this,null,function*(){return S--,a(i,h).then(R=>P(this,null,function*(){return v(R)&&!s.isAborted&&S>0?(yield jy(d),E()):R.status===401&&g===!0&&x===!1?(x=!0,yield this.refreshToken(),E()):R})).catch(R=>P(this,null,function*(){if(y(R)&&!s.isAborted&&S>0)return yield jy(d),E();throw R}))});E().then(R=>P(this,null,function*(){let N=yield v_(R);if(delete this.latestRequestByUrl[i],R.status>=500){o(new Ky("Server Error",N));return}else if(R.status===401){o(new Ii("Unauthorized",N));return}else if(R.status===403){o(new Ii("Forbidden",N));return}else if(R.status===404){o(new Ii("Not Found",N));return}else if(R.status>=400){o(new Ii("Bad Request",N));return}u&&Vy.set(i,N),r(N)})).catch(R=>{o(R)})})}validateToken(){return P(this,null,function*(){let{has_valid_access_token:t}=yield this.get("/auth/validate");if(!t)try{yield this.refreshToken()}catch(r){return!1}let{is_logged_in:n}=yield this.get("/apis/admin/session/validate/");return!!n})}refreshToken(){return po.refreshingToken||(po.refreshingToken=this.get("/auth/refresh",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{po.refreshingToken=null},1e3*60)})),po.refreshingToken}get(t,n){return this.request(t,n)}post(t,n,r){return this.request(t,k({method:"POST",body:JSON.stringify(n)},r))}patch(t,n,r){return this.request(t,k({method:"PATCH",body:JSON.stringify(n)},r))}put(t,n,r){return this.request(t,k({method:"PUT",body:JSON.stringify(n)},r))}delete(t,n){return this.request(t,k({method:"DELETE"},n))}};po.refreshingToken=null;var xr=po;var pk;(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||(t.EventType={}))})(pk||(pk={}));function Fp(e){return L(k({},oe(e)),{tags:e.tags})}var os=class os{constructor(t,n={}){this.options=n;this.latestReceivedDeepdeskVersions={};this.shouldFetchCsrfToken=!0;this.client=new xr(t,{fetch:n.fetch}),this.client.patchFetch(r=>(o,s)=>P(this,null,function*(){let i=yield r(o,s);return this.handleDeepdeskVersionHeaders(i),i}))}preflight(){return P(this,null,function*(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let t=yield this.getCsrfToken();this.client.setCsrfToken(t)}return this.options.token?(os.exchangeTokenPromise||(os.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),os.exchangeTokenPromise):Promise.resolve()})}createConversation(t){return P(this,null,function*(){yield this.preflight(),H.info(`Creating conversation for session ${t.sessionId} and agent ${t.agentId}`);let n=yield this.client.post("/api/conversations",L(k({},Oe(t)),{tags:t.tags}),{version:"v2"});return Fp(n)})}getMe(){return P(this,null,function*(){let t=yield this.client.get("/apis/admin/session/me/");return oe(t)})}postIdentity(t){return P(this,null,function*(){yield this.client.post("/apis/admin/session/me/identities/",Oe(t))})}patchMe(t){return P(this,null,function*(){let n=yield this.client.patch("/apis/admin/session/me/",Oe(t));return oe(n)})}getProfile(t){return P(this,null,function*(){let n=yield this.client.get(`/apis/admin/profiles/${t}/`,{useCache:!0});return oe(n)})}getKnowledgeAssistant(t){return P(this,null,function*(){let n=yield this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{useCache:!0});return oe(n)})}getContentTypes(){return P(this,null,function*(){let t=yield this.client.get("/apis/admin/content-types/",{useCache:!0});return oe(t)})}getAccount(){return P(this,null,function*(){let t=yield this.client.get("/apis/admin/account/",{useCache:!0});return oe(t)})}getPlatformConfig(t){return P(this,null,function*(){let n=t!==void 0?`/platform/config/${t}/`:"/platform/config/",{config:r}=yield this.client.get(n,{useCache:!0});return oe(r)})}checkUserExists(t){return P(this,null,function*(){let{exists:n}=yield this.client.get(`/apis/admin/users/exists?external_id=${t}`,{version:"v1"});return n})}getConversationBySessionId(r){return P(this,arguments,function*(t,n={}){yield this.preflight(),H.info(`Getting conversation for session ${t}`);let{attempts:o=1,retryDelay:s=1e3}=n,i=yield this.client.get(`/api/conversations/by_session_id/${t}`,{attempts:o,retryDelay:s,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"});return H.info(`Successfully retrieved conversation ${i.id} for session ${t}`),Fp(i)})}isConversationSupported(r){return P(this,arguments,function*(t,n={}){H.info(`Check if conversation for session ${t} is supported`);let{attempts:o=1,retryDelay:s=1e3}=n;return(yield this.client.get(`/api/conversations/by_session_id/${t}/active_profile`,{attempts:o,retryDelay:s,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"})).has_active_profile})}updateConversation(t,n){return P(this,null,function*(){let r=Oe(n);n.tags&&(r.tags=n.tags);let o=yield this.client.put(`/api/conversations/${t}`,r,{version:"v2"});return Fp(o)})}postMessages(t,n){return P(this,null,function*(){return(yield this.client.post(`/api/conversations/${t}/messages`,n.map(o=>L(k({},Oe(o)),{tags:o.tags})),{version:"v2"})).map(o=>Fp(o))})}sendEvent(t,n){return P(this,null,function*(){let i=n,{data:r}=i,o=ee(i,["data"]),s=Object.entries(this.latestReceivedDeepdeskVersions).reduce((a,[l,u])=>L(k({},a),{[l]:u}),{});return this.client.post("/api/events",Oe(L(k(k({},s),o),{data:r,name:t})),{version:"v2"})})}sendEventV1(t,n){return P(this,null,function*(){let r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((o,[s,i])=>L(k({},o),{[s]:i}),{});return this.client.post("/api/events",{event:t,data:Oe(k(k({},n),r))},{version:"v1"})})}getEntities(t){return P(this,null,function*(){return(yield this.client.post("/api/entities",{messages:t.filter(r=>r.text)},{version:"v1"})).entities})}getTemporaryExchangeToken(){return P(this,null,function*(){return(yield this.client.get("/auth/exchange-token")).jwt})}exchangeTokenForAccessCookie(t){return P(this,null,function*(){return this.client.post("/apis/admin/session/jwt/",{jwt:t}).catch(n=>{throw H.warn(`Invalid token '${t}'`),n})})}authenticateWithKey(t,n){return P(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/api-key/",Oe(n),{refreshTokenOn401:!1,headers:{apikey:t}})})}getTextSuggestions(o){return P(this,arguments,function*(t,n={},r){return r==="sticky-messages"?this.getPinnedMessages(t):(yield this.client.post(`/api/conversations/${t}/recommend/${r}`,Oe(n),{abortLatest:!0,version:"v1"})).map(i=>L(k({},oe(i)),{text:i.text||i.url||i.message,source:r,type:r})).filter((i,a,l)=>a===l.findIndex(u=>u.text===i.text))})}isLoggedIn(){return P(this,null,function*(){return yield this.preflight(),this.client.validateToken()})}getAutocompleteSuggestions(t,n){return P(this,null,function*(){return(yield this.client.post(`/api/conversations/${t}/autocomplete`,Oe(n),{abortLatest:!0,version:"v1"})).map(o=>({score:1,source:o.source,sourceText:o.source_text,text:o.label,trainingJobs:o.training_jobs,searchKeywords:o.search_keywords,type:o.source})).filter((o,s,i)=>s===i.findIndex(a=>a.text===o.text))})}getPinnedMessages(t){return P(this,null,function*(){let n=yield this.client.get(`/api/conversations/${t}/sticky-messages`,{abortLatest:!0,version:"v1"});return oe(n).map(r=>L(k({},r),{text:r.message,source:"sticky-messages",type:"pinned-message"}))})}getStyleSuggestions(t){return P(this,null,function*(){let n=yield this.client.post("/api/style-suggestions",Oe(t),{abortLatest:!0,version:"v1"});return oe(n)})}search(t){return P(this,null,function*(){let n=yield this.client.post(`/api/profiles/${t.profile}/search`,Oe(t),{version:"v2"});return oe(n)})}knowledgeAssist(s,i,a){return P(this,arguments,function*(t,n,r,o={}){let l=yield this.client.post(`/api/knowledge-assist/assistants/${r}/search`,Oe({question:t.question,doNotKnowAnswer:t.doNotKnowAnswer,customerInstruction:t.customerInstruction,chatHistory:n.map(u=>({question:u.question,answer:u.answer.answer})),agentId:o.agentId,conversationId:o.conversationId}),{version:"v2"});return oe(l)})}requestLoginByEmail(t){return P(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/request/",{email:t});return oe(n)})}requestPasswordlessToken(){return P(this,null,function*(){let t=yield this.client.get("/apis/admin/session/passwordless/request/");return oe(t.token)})}getCsrfToken(){return P(this,null,function*(){let{token:t}=yield this.client.get("/apis/admin/session/csrf/");return t})}verifyLoginToken(t){return P(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/login/",{token:t});return oe(n)})}evaluateRule(s,i,a){return P(this,arguments,function*(t,n,r,o={}){let l=new URLSearchParams;o.raiseForFailingConditions&&l.set("raise_for_failing_conditions","true");let u=yield this.client.post(`/api/conversations/${n}/rules/${t}/evaluate?${l.toString()}`,r,{version:"v2"});return u?oe(u.cues):[]})}getSummary(r){return P(this,arguments,function*(t,n={}){let o=yield this.client.post("/api/summary",{conversation:{messages:t.filter(s=>s.text&&s.source),agent_id:n.agentId,id:n.externalConversationId},prompt_instruction:n.promptInstruction,model:n.model},{version:"v1"});return oe(o)})}evaluateAssistant(t,n){return P(this,null,function*(){var a;let r=new URLSearchParams,{expectFormat:o="text"}=n||{};if(o.startsWith("json-schema:")){let l=o.replace("json-schema:","");r.append("expect_response_format","json-schema"),r.append("expect_response_format_schema",l)}else r.append("expect_response_format",o);n!=null&&n.externalConversationId&&r.append("external_conversation_id",n.externalConversationId);let s=n!=null&&n.threadId?`/api/v2/assistants/${t}/threads/${n==null?void 0:n.threadId}/evaluate?${r.toString()}`:`/api/v2/assistants/${t}/evaluate?${r.toString()}`,i=yield this.client.post(s,{input:(a=n==null?void 0:n.input)!=null?a:{},conversation:n==null?void 0:n.transcript});return oe(i.output)})}createAssistantThread(t){return P(this,null,function*(){let{assistantCode:n}=t,r=yield this.client.post(`/apis/admin/assistants/${n}/threads/`,{});return oe(r)})}postMessageToAssistantThread(t){return P(this,null,function*(){let{assistantCode:n,threadId:r,message:o}=t,s=yield this.client.post(`/apis/admin/assistants/${n}/threads/${r}/messages/`,{content:o,role:"user"});return oe(s)})}getRules(){return P(this,null,function*(){let t=new URLSearchParams,n=yield this.client.get(`/apis/admin/rule-engine/rules/?${t.toString()}`,{useCache:!0});return oe(n)})}translateMessages(t){return P(this,null,function*(){let n=yield this.client.post("/api/translate",Oe(t),{version:"v2"});return oe(n)})}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),s=o.match(c0);if(!n||!s)return;let i=s[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[i];a&&n&&a!==n&&H.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[i]=n})}};os.exchangeTokenPromise=null;var br=os;var Bl=class{constructor(t,n){this.url=t;this.eventListeners={};this.options=k({timeout:25e3},n)}proxyEvent(t){this.eventSource.addEventListener(By(t),n=>{let{data:r}=n;try{let o=JSON.parse(r);this.emit(t,oe(o))}catch(o){H.warn(`Invalid JSON for ${t}: ${r}`)}})}connect(){clearTimeout(this.timeoutTimer);let t=new EventSource(this.url,{withCredentials:!0});this.eventSource=t;let n=!1;t.onopen=()=>{n=!0},t.onerror=()=>{n&&t.readyState===2&&this.connect()},this.timeoutTimer=setTimeout(()=>{t.close(),this.connect()},this.options.timeout),Object.keys(this.eventListeners).forEach(r=>{this.proxyEvent(r)})}disconnect(){var t;clearTimeout(this.timeoutTimer),this.eventListeners={},(t=this.eventSource)==null||t.close()}emit(t,n){this.eventListeners[t]&&this.eventListeners[t].forEach(r=>r(n))}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),this.proxyEvent(t),()=>{this.off(t,n)}}off(t,n){let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}};var fk;(t=>{let e;(s=>(s.Started="Started",s.Aborted="Aborted",s.Completed="Completed"))(e=t.AutoflowSessionState||(t.AutoflowSessionState={}))})(fk||(fk={}));var jl=class{constructor(t,n={}){this.apiUrl=t;this.streams={};this.logger=H;this.client=new xr(t,n)}getCustomMessages(t){return P(this,null,function*(){let n=yield this.client.get(`/sessions/${t}/suggestions`);return oe(n.suggestions)})}sendCustomMessage(t,n){return P(this,null,function*(){let r=yield this.client.post(`/sessions/${t}/messages`,Oe(n));return oe(r)})}answerCustomMessage(t,n){return P(this,null,function*(){yield this.client.post(`/sessions/${t}/answers`,Oe(n))})}getAutoflows(t){return P(this,null,function*(){let n=yield this.client.get(`/sessions/${t}/autoflows`);return oe(n.autoflows)})}startAutoflowSession(t){return P(this,null,function*(){let n=yield this.client.post("/autoflow-sessions",Oe(t));return oe(n)})}stopAutoflowSession(t){return P(this,null,function*(){yield this.client.delete(`/autoflow-sessions/${t}`)})}openStream(t){return this.streams[t]||(this.streams[t]=new Bl(`${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 mk={startTime:null,stopTime:null},gk=J({name:"handlingTime",initialState:mk,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(xe,()=>mk)}}),{handlingTimeStart:hk,handlingTimeStop:Hp,handlingTimeReset:yk}=gk.actions,vk=gk.reducer;var Sk=(e={})=>{let t=k({onAuthError:ii(!1)},e);return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var Up={list:{keywordMatches:[]},fetchState:"idle"};var ss=V("styleSuggestions/getAll",(n,r)=>P(void 0,[n,r],function*({text:e},t){var l;let{deepdeskAPI:o}=t.extra,s=t.getState(),{showStyleSuggestions:i}=s.settings,a=(l=s.conversation.current)==null?void 0:l.profileCode;if(!i)return Up.list;if(!a)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:a,message:e})})),S_=J({name:"styleSuggestions",initialState:Up,reducers:{},extraReducers:e=>{e.addCase(ss.pending,t=>{t.fetchState="loading"}).addCase(ss.rejected,t=>{t.fetchState="error"}).addCase(ss.fulfilled,(t,n)=>{t.fetchState="done",Xr(t.list,n.payload)||(t.list=n.payload)}).addCase(Mo,t=>{t.list=Up.list}).addCase(xe,()=>Up)}}),wk=S_.reducer;var xk=(e={})=>{let t,n=!0,r=k({getStyleSuggestions:ss,debounce:500},e);return o=>s=>i=>{var g;let a=o.getState().input.text,l=s(i),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 w_(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end}var bk=(e={})=>{let t=k({getTextSuggestions:xn,getAutocompleteSuggestions:wl,debounce:200,check:Fn},e),n;return r=>o=>s=>{var v;let{input:i}=r.getState(),a=o(s),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=s.type===tp.toString();if(!p||!u&&!c)return a;let{input:g}=l;return w_(g,i)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let f=ui(l);f===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(f))},d?0:t.debounce)),a}};var Ek=ss.fulfilled.toString();function x_(e,t){let n=new Set([...t.keywordMatches.map(o=>o.keyword)]),r=[];return n.forEach(o=>{let s=e.keywordMatches.filter(l=>l.keyword===o),i=t.keywordMatches.filter(l=>l.keyword===o),a=i.length-s.length;a<=0||r.push(...i.slice(0,a))}),r}var Ck=e=>t=>n=>r=>{var u;if(r.type!==Ek){n(r);return}let o=t.getState().styleSuggestions.list;n(r);let s=t.getState(),i=s.styleSuggestions.list,a=(u=s.conversation)==null?void 0:u.current;if(o===i)return;let l=x_(o,i);r.type===Ek&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var b_=Oc({assistants:jb,auth:I1,autoflows:$C,conversation:z1,contentTypes:Kb,customMessages:tT,passwordlessToken:oT,entities:vE,knowledgeAssistant:Fb,handlingTime:vk,info:sb,input:Z1,settings:E1,profile:qb,search:pb,styleSuggestions:wk,ui:oC,rules:uT,textSuggestions:BE});function Tk(e){return Ax({reducer:b_,middleware:t=>[...t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI,deepdeskBrokerAPI:e.deepdeskBrokerAPI}},serializableCheck:!1}),Sk(),bk({debounce:200}),xk({debounce:500}),Ck(e.deepdeskAPI),...e.middleware?e.middleware:[]],preloadedState:e.preloadedState})}var E_=e=>{var t,n;return(n=(t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())!=null?n:"unknown"},C_=e=>t=>n=>r=>{var a,l,u,c,p,d,g;let o=t.getState(),s=sh("inlineSuggestions")(o);switch(r.type){case ii.toString():{!r.payload&&e.emit("logout",void 0);break}case wn.fulfilled.toString():r.payload.length>0&&e.sendEvent("entities found",{conversationId:(a=o.conversation.current)==null?void 0:a.id,data:{entities:r.payload}});break;case pt.toString():e.sendEvent(r.payload.name,{conversationId:((l=r.payload.options)==null?void 0:l.includeConversationData)&&((u=o.conversation.current)==null?void 0:u.id),data:r.payload.data});break;case Mo.toString():e.logSendMessage(r.payload);break;case Jo.fulfilled.toString():r.isBroadcasted||e.broadcast(fh,r,!1),(c=r.payload.options)!=null&&c.shouldEmit&&e.emit("cues",r.payload.cues);break;case Fd.toString():e.emit("call-to-action",{cue:r.payload});break;case or.fulfilled.toString():r.isBroadcasted||e.broadcast(mh,r,!1);break;default:break}let i=n(r);switch(r.type){case Mo.toString():e.handleAfterSendMessage(r.payload);break;case bl.toString():e.onUpdateShowTabHint(r.payload);break;case Hp.toString():e.logHandlingTime();break;case"analytics/logEvent/fulfilled":{e.emit("event",r.meta.arg);break}case fd.toString():{let{start:y,end:v}=o.input.selection;e.emit("replace",L(k({},r.payload),{replace:r.payload.replace==="selection"?{start:y,end:v}:{start:0,end:v}}));break}case fn.toString():{let{start:y,end:v}=o.input.selection;e.emit("select-suggestion",L(k({type:E_(r.payload.suggestion)},r.payload),{replace:r.payload.replace==="selection"?{start:y,end:v}:{start:0,end:v}})),s&&t.dispatch(Jr([]));break}case md.toString():e.emit("select-image",r.payload),e.sendEvent("Image attached",{conversationId:(p=o.conversation.current)==null?void 0:p.id,data:{path:r.payload.suggestion.image,title:r.payload.suggestion.title}});break;case Jr.toString():{s&&r.payload.length>0&&t.dispatch(gd(0));break}case pi.fulfilled.toString():{e.sendEvent("conversation summarized",{conversationId:(d=o.conversation.current)==null?void 0:d.id,data:{summary:r.payload,assistant:(g=t.getState().profile.data)==null?void 0:g.summarizerAssistantNew}});break}default:break}return i},kk=C_;function Wy(e){return e.toISOString().replace("T"," ").replace("Z","")}function Pk(e,t){var s,i,a,l;let n=(s=e.conversation.current)==null?void 0:s.id;if(!n)return H.warn("No conversationId for handling time metrics"),null;let{startTime:r,stopTime:o}=e.handlingTime;return!r||!o?(H.warn("No startTime and stopTime for handling time metrics"),null):{conversationId:n,clientVersion:t.version,agentId:(i=e.info.agentInfo)==null?void 0:i.agentId,agentName:(a=e.info.agentInfo)==null?void 0:a.agentName,agentEmail:(l=e.info.agentInfo)==null?void 0:l.agentEmail,timeStart:Wy(r),timeStop:Wy(o)}}function Rk(e,t,n){var N,_,Q,K;let r=(N=t.conversation.current)==null?void 0:N.id;if(!r)return H.warn("No conversationId for send message metrics"),null;let{text:o,metrics:{numCharsTyped:s,numCharsPasted:i,numCharsCut:a,numCharsDeleted:l,numPaste:u,agentStartedTypingTimestamp:c,externalTimeTotalSeconds:p,pastes:d,cuts:g,deletions:y,textSuggestions:v,offeredTextSuggestions:f}}=t[e],m=o.length,S=v.reduce((W,{text:fe,searchTerm:Xe})=>W+fe.length-(Xe?Xe.length:0),0),x=c!=null?c:Date.now(),E=(Date.now()-x)/1e3+(p||0),C=s/E,R=v.reduce((W,{searchTerm:fe})=>W+(fe?fe.length:0),0);return{conversationId:r,source:"agent",text:o,clientVersion:n.version,pastes:d,cuts:g,deletions:y,lenTextTyped:s+R,lenTextTotal:m,lenTextAssisted:S,lenTextPasted:i,lenTextCut:a,lenTextDeleted:l,timeTotalSeconds:E,charsPerSecond:C,numPastes:u,textSuggestionsV2:v,suggestionsCounters:[{source:"gpt",countOffered:f.filter(W=>W.source==="gpt").length}],agentId:(_=t.info.agentInfo)==null?void 0:_.agentId,agentName:(Q=t.info.agentInfo)==null?void 0:Q.agentName,agentEmail:(K=t.info.agentInfo)==null?void 0:K.agentEmail}}function $y(e,t){var s;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return $y(r,t);let o=(s=e.ownerDocument.defaultView)==null?void 0:s.frameElement;return o?$y(o,t):null}function Ak(e,t){return $y(e,t)}function Ik(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function T_(e){return typeof e=="object"&&e!==null&&"tagName"in e}function zp(e){return T_(e)&&(Zo(e)||cp(e))}var Ok,zn=new Map,k_=["bottom","height","left","right","top","width"],Lk=(e,t)=>!e&&!t?!1:e&&!t||!e&&t?!0:k_.some(n=>e[n]!==t[n]);function Nk(e){var n,r,o;if(e.ownerDocument===document)return[];let t=(o=(r=(n=e.ownerDocument)==null?void 0:n.defaultView)==null?void 0:r.frameElement)!=null?o:null;return t?[t,...Nk(t)]:[]}function Mk(e,t){return!e||!t?null:L(k({},e),{top:e.top+t.top,left:e.left+t.left})}var Bp=!1,_k=()=>{Bp=!0;let e=[];if(zn.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),zn.delete(n);return}let r=n.getBoundingClientRect();Lk(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{let n=t.parentRects?t.parentRects.reduce(Mk,t.rect):t.rect;Lk(n,t.totalRect)&&t.callbacks.forEach(r=>r(n)),t.totalRect=n}),zn.size===0){Bp=!1;return}Ok=window.requestAnimationFrame(_k)};function qy(e,t){let n=Nk(e),r=[],o=n.map((s,i)=>qy(s,a=>{r[i]=a;let l=zn.get(e);if(!l)return;let u=r.reduce(Mk,l.rect);l.callbacks.forEach(c=>c(u))}));return{observe(s=!0){if(o.forEach(i=>i.observe(!1)),zn.has(e)){let i=zn.get(e);i.callbacks.push(t),i.rect&&t(i.rect)}else zn.set(e,{rect:void 0,callbacks:[t],parentRects:r});s&&!Bp&&_k()},unobserve(){o.forEach(i=>i.unobserve());let s=zn.get(e);if(s){let i=s.callbacks.indexOf(t);i>=0&&s.callbacks.splice(i,1),s.callbacks.length||zn.delete(e),zn.size||(cancelAnimationFrame(Ok),Bp=!1)}}}}var Dk,Bn=new Map,Fk=()=>{Bn.forEach((e,t)=>{if(!t.isConnected){Bn.delete(t);return}let{clientHeight:n,scrollHeight:r}=t,o=r>n;e.visible!==o&&(e.visible=o,e.callbacks.forEach(s=>s(e.visible)))}),Bn.size!==0&&(Dk=window.requestAnimationFrame(Fk))};function Hk(e,t){return{observe(){let n=Bn.size===0;Bn.has(e)?Bn.get(e).callbacks.push(t):Bn.set(e,{visible:void 0,callbacks:[t]}),n&&Fk()},unobserve(){let n=Bn.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||Bn.delete(e),Bn.size||cancelAnimationFrame(Dk)}}}}var Gy=["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 Yy(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function Li(e){return parseFloat(e)}function jp(e){return Math.round(e*1e6)}function Uk(e){return e/1e6}function Qy(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=Li(e.width),s=Li(e.borderLeftWidth),i=Li(e.borderRightWidth),a=Li(e.paddingRight),l=Uk(jp(o)-jp(s)-jp(i)),u=Uk(jp(r));if(l-u>2){let c=l-u;n.style.paddingRight=`${a+c}px`}}function Vl(e,t={}){var c,p;let n=t.overlayContainer||document.createElement("div");n.style.display="none",n.style.position=(c=t.position)!=null?c:"fixed",n.style.pointerEvents="none",n.style.borderColor="transparent",Yo(n);let r=window.getComputedStyle(e),o=!0,s=()=>{n.scrollTop=e.scrollTop};Yy(r,n,Gy),Qy(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",s));let i=Hk(e,()=>{Yy(r,n,Gy),Qy(r,e,n),s(),setTimeout(s,0)}),a,l=!0,u=qy(e,d=>{if(d===null){t.onRemove&&t.onRemove(),n.remove();return}if(!l&&t.onMoveStart&&(Promise.resolve().then(()=>t.onMoveStart()),l=!0),clearTimeout(a),a=setTimeout(()=>{t.onMoveEnd&&t.onMoveEnd(),l=!1},200),d.height===0&&d.width===0){if(o===!0)return;t.onHide&&t.onHide(),n.style.display="none",o=!0;return}if(Yy(r,n,Gy),Qy(r,e,n),s(),n.style.top=`${d.top}px`,n.style.left=`${d.left}px`,t.closestScrollElement&&t.closestScrollElement!==e){let g=t.closestScrollElement.getBoundingClientRect(),y=window.getComputedStyle(t.closestScrollElement),v=Li(y.borderTopWidth),f=Li(y.borderBottomWidth),m=g.top+v-d.top,h=d.top+d.height+-(g.top+g.height-f);n.style.clipPath=`inset(${m}px 0px ${h}px 0px)`}o&&(n.style.display="block",t.onShow&&t.onShow(),o=!1)});return t.appendTo?t.appendTo.appendChild(n):(p=e.parentElement)==null||p.appendChild(n),u.observe(),i.observe(),[n,()=>{e.removeEventListener("scroll",s),u.unobserve(),i.unobserve()}]}var zk=(e,t)=>({value(){try{let n=sessionStorage.getItem(`dd-${e}`);if(!n)return t;try{return JSON.parse(n)}catch(r){return t}}catch(n){return t}},update(n){try{sessionStorage.setItem(`dd-${e}`,JSON.stringify(n))}catch(r){H.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function P_(e){return e.offsetParent!==null}function Bk(e){if(!P_(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 Vp(e,t,n=100){let r=Bk(e);t({isVisible:r});let o=setInterval(()=>{let s=Bk(e);s!==r&&(r=s,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var He=w(T());var jk=zk("showTabHint",!0),Oi=class Oi{constructor({deepdeskUrl:t,brokerUrl:n,version:r=Oi.version||"unknown",locale:o="en-US",token:s,fetch:i,productName:a,createCustomChannel:l}){this.inputMediator=null;this.eventListeners={};this.unmountHandlers=[];this.widgetRoot=null;this.dynamicThunkObject={};this.isMounted=!1;this.shouldRender=!0;this.loadProfileConfigPromise=null;let u=t.replace(/\/api$/,"");this.deepdeskApi=new br(u,{token:s,fetch:i}),this.version=r,this.instanceId=Oi.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[kk({broadcast:(p,d,g)=>{this.broadcastEvents.send(p,d,g)},emit:(p,d)=>this.emit(p,d),handleAfterSendMessage:p=>this.handleAfterSendMessage(p),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:p=>this.logSendMessage(p),onUpdateShowTabHint:p=>jk.update(p),sendEvent:(p,d)=>this.deepdeskApi.sendEvent(p,d)})]};n&&Object.assign(c,{deepdeskBrokerAPI:new jl(n)}),this.store=Tk(c),this.broadcastEvents=new dk({debug:!0,deepdeskUrl:u,eventMap:fb(this.store),createCustomChannel:l}),this.store.dispatch(bl(jk.value())),this.store.dispatch(ad({locale:o,adminUrl:u,productName:a}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){var t;return(t=this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex])!=null?t:null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}sessionId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.sessionId}shouldAbort(){return this.state.conversation.isSupported===!1?(H.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(H.warn("Profile has not been loaded (yet)"),!0):(H.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(ii(null)),this.store.dispatch(nr()),new Promise(t=>{let n=this.store.subscribe(()=>{let r=this.store.getState();dt(r)&&C1(r)!=="loading"&&(n(),t())});this.unmountHandlers.push(()=>{n()})})}isLoggedIn(){return P(this,null,function*(){return(yield this.store.dispatch(nr())).payload})}isConversationSupported(t,n){return P(this,null,function*(){return(yield this.store.dispatch(lh({sessionId:t,options:n}))).payload})}createConversation(t){return P(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(yield this.store.dispatch(ud(t))).payload})}getConversationBySessionId(t,n){return P(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t&&this.resetConversation(),(yield this.store.dispatch(cd({sessionId:t,options:n}))).payload})}upsertConversation(t){return P(this,null,function*(){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(yield this.store.dispatch(uh(t))).payload})}postMessages(t){return P(this,null,function*(){return(yield this.store.dispatch(pd(t))).payload})}updateConversation(t){return P(this,null,function*(){return(yield this.store.dispatch(dd(t))).payload})}resetConversation(){this.store.dispatch(xe()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}configure(t){this.store.dispatch(ad(t))}setVisitorInfo(t){this.store.dispatch(nb(t))}setCustomData(t){this.store.dispatch(rb(t))}setAgentInfo(t,n){return P(this,null,function*(){yield this.store.dispatch(Ga(k(k({},t),n)))})}setAgentSettings(t){return P(this,null,function*(){yield this.store.dispatch(dh(t))})}getAgentSettings(){return P(this,null,function*(){return(yield this.store.dispatch(ph())).payload})}refresh(){return P(this,null,function*(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.store.dispatch(hd({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()}));let t=[];return this.store.dispatch(tp()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})})}notifyExternalSuggestion(t){this.store.dispatch(fn(t))}evaluateRule(o){return P(this,arguments,function*(t,n={},r=sT){return(yield this.store.dispatch(Jo({label:t,params:n,options:r}))).payload.cues})}evaluateAssistant(t,n){return P(this,null,function*(){let c=n||{},{input:r={},transcript:o,showCuesInWidget:s=!0,includeTags:i,expectFormat:a}=c,l=ee(c,["input","transcript","showCuesInWidget","includeTags","expectFormat"]);Object.assign(r,l);let u=yield this.store.dispatch(or({assistantCode:t,expectFormat:a||"json-schema:cues",transcript:o,includeTags:i,input:r,skipState:!s}));if(u.error)throw new Error(u.error.message);return u.payload})}evaluateConversationAssistant(t,n){return P(this,null,function*(){yield this.loadProfileConfig();let r={accepted:"conversationAcceptedAssistant","new-message":"conversationNewMessageAssistant",ended:"conversationEndedAssistant"},o=this.state.profile.data[r[t]];if(!o){H.warn(`No assistant set in profile for conversation event "${t}"`);return}yield this.evaluateAssistant(o,k({transcript:"stored-transcript",includeTags:!0},n))})}getSummary(){return P(this,null,function*(){var n;if(!this.hasConversation())return H.warn("No conversation to create summary for."),null;(n=this.state.profile.data)!=null&&n.summarizerAssistantNew||H.warn("No profile loaded yet, or no summarizer assistant set in profile");let t=yield this.store.dispatch(pi({}));if(t.error)throw new Error(t.error.message);return t.payload})}handleKeyDown(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui,{textSuggestions:o,selectedSuggestionIndex:s,selection:i}=this.state.input,{inlineSuggestions:a,showTextSuggestions:l}=this.state.settings,u=a?"below":"above",c=o.length>0;if(!Fn(this.state)||(this.store.dispatch(W1(ch(t))),t.key!=="Tab"&&!l))return;let p=()=>{n||!c||i&&(t.shiftKey||(this.store.dispatch(G1()),t.preventDefault()))},d=()=>{n||!c||a&&s<=0||i&&(t.shiftKey||(this.store.dispatch(Y1()),t.preventDefault()))};switch(t.key){case"ArrowUp":u==="below"?d():p();break;case"ArrowDown":{u==="below"?p():d();break}case"Escape":{n||(this.store.dispatch(gd(-1)),this.store.dispatch(io({collapse:!0})),this.store.dispatch(nC(!0)),t.preventDefault());break}case"Tab":{t.preventDefault();let g=ci(this.state);if(!g)return;this.store.dispatch(bl(!1)),this.store.dispatch(fn({text:g.text,suggestion:g,eventMetrics:{inputType:"tab"},replace:"until-selection-end"}));break}case" ":{if(this.state.settings.inlineSuggestions||this.state.input.selectedSuggestionIndex===-1)return;let g=ci(this.state);if(!g)return;this.store.dispatch(fn({text:g.text,suggestion:g,eventMetrics:{inputType:"space"},replace:"until-selection-end"}));break}case"Enter":{if(this.state.settings.inlineSuggestions||t.shiftKey||this.state.input.selectedSuggestionIndex===-1)return;let g=ci(this.state);if(!g)return;this.store.dispatch(fn({text:g.text,suggestion:g,eventMetrics:{inputType:"enter"},replace:"until-selection-end"})),t.preventDefault();break}default:}n&&r&&this.store.dispatch(io({collapse:!1}))}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(Jr([]))}handlingTimeStart(){this.state.handlingTime.startTime||(H.info("Start handling time"),this.store.dispatch(hk()))}handlingTimeStop(){this.state.handlingTime.startTime&&(H.info("Stop handling time"),this.store.dispatch(Hp()))}logSendMessage(t){let n=Rk("input",this.state,{version:this.version});n&&(t&&(Object.assign(n,{text:t}),Object.assign(n,{lenTextTotal:t.length})),this.deepdeskApi.sendEventV1("Send Message",n),this.emit("send-message-event",n))}logHandlingTime(){let t=Pk(this.state,{version:this.version});t&&(this.deepdeskApi.sendEventV1("Handling Time",t),this.store.dispatch(yk()))}notifySubmit(t={}){var n;this.shouldAbort()||(this.store.dispatch(Mo((n=t.text)!=null?n:this.state.input.text)),this.store.dispatch(X1()))}emit(t,n){let r=this.eventListeners[t];r&&r.forEach(o=>{try{o(n)}catch(s){H.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),H.error(s)}})}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),()=>{this.off(t,n)}}off(t,n){if(!t&&!n){this.eventListeners={};return}let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}setConversationQuery(t){this.dynamicThunkObject.conversationQuery=t}setPlatformVariables(t){this.store.dispatch(ob(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[s,i]=Vl(n,r);return s.setAttribute("translate","no"),s.dataset.testid=t,o&&s.classList.add(o),this.unmountHandlers.push(()=>{(0,ln.unmountComponentAtNode)(s),i(),s.remove()}),s}createInlineContainer(t,n){var a;let r=document.createElement("div");r.style.position="absolute",r.style.top="0px",r.style.left="0px",r.style.height="0px",r.style.width="0px";let o=document.createElement("div");o.style.display="none",o.style.position="absolute",o.style.height="0px",o.style.width="0px",o.style.backgroundColor="red",r.appendChild(o);let s=(a=t.ownerDocument.defaultView)==null?void 0:a.frameElement,i=s?s.ownerDocument.defaultView:null;if(s&&(i===window||(i==null?void 0:i.parent)===window)){let[l,u]=Vl(s,{appendTo:document.body,onMoveStart:()=>{o.style.display="none"}});l.dataset.testid=n,l.style.zIndex="2",l.appendChild(r),this.unmountHandlers.push(()=>{(0,ln.unmountComponentAtNode)(o),u()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return Yo(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,ln.unmountComponentAtNode)(o),o.remove()}),o}storeMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(t,n),H.info(`Stored analytics for ${this.conversationId()}`)}catch(t){}}restoreMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=window.sessionStorage.getItem(t);if(!n)return;let r=JSON.parse(n);r.text.trim()===this.state.input.text.trim()?(H.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(Q1(r.metrics))):H.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(t)}catch(t){}}mount(t,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!zp(t))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let{customStyles:r={},showStyleSuggestions:o,showTabCompletion:s,showTextSuggestions:i,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:s,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,showTextSuggestions:i,insertLink:g,isEmbedded:p,inlineSuggestions:m,floatingMenu:!!h}),n.automaticHandlingTime&&this.setupHandlingTime(t),Yo(t),this.inputMediator=y||(Zo(t)?new rs(t):new ns(t)),this.inputMediator.on("change",({plainText:E,rawHTML:C})=>{this.store.dispatch(hd({text:E,html:C}))}),this.inputMediator.on("keyup",E=>{this.store.dispatch($1(ch(E)))}),this.inputMediator.on("keydown",E=>{this.handleKeyDown(E)}),this.inputMediator.on("paste",({pastedText:E,selectionText:C})=>{this.store.dispatch(q1({text:E,selectionText:C}))}),this.inputMediator.on("cut",({selectionText:E})=>{this.store.dispatch(K1(E))});let S;this.inputMediator.on("selection",E=>{clearTimeout(S),E===null?S=setTimeout(()=>{E!==null&&this.store.dispatch(yd(E))},500):this.store.dispatch(yd(E))}),this.inputMediator.on("disabled",()=>{var E;(E=this.inputMediator)==null||E.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(op(!1))}),this.inputMediator.on("focus",()=>{this.store.dispatch(op(!0))});let x=v&&Ak(t,v)||void 0;if(m){let{customStyles:E,appendOverlayTo:C}=n,R=this.createInlineContainer(t,"deepdesk-caret");(0,ln.render)((0,He.jsx)(Xo,{store:this.store,customStyles:E,children:(0,He.jsx)(Do,{broadcastEvents:this.broadcastEvents,children:(0,He.jsx)(cC,{})})}),R),this.inputMediator.on("caretposition",_=>{_?(R.style.display="block",R.style.top=`${_.top}px`,R.style.left=`${_.left}px`):R.style.display="none"});let N=this.overlayContainerFactory("floating-menu",x||t,{appendTo:typeof h=="object"&&"appendOverlayTo"in h?h.appendOverlayTo:C},E==null?void 0:E.floatingMenuRootNode);(0,ln.render)((0,He.jsx)(Xo,{store:this.store,customStyles:E,children:(0,He.jsx)(Do,{broadcastEvents:this.broadcastEvents,children:(0,He.jsx)(JE,{onLogIn:()=>this.loginViaPopup().catch(_=>H.warn(_.message))})})}),N)}else{let E=this.overlayContainerFactory("deepdesk-tab-completion",x||t,{appendTo:f,closestScrollElement:x,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),C=this.overlayContainerFactory("deepdesk-suggestions-overlay",x||t,{appendTo:f},r==null?void 0:r.suggestionsRootNode);(0,ln.render)((0,He.jsx)(Xo,{store:this.store,customStyles:r,children:(0,He.jsx)(Do,{broadcastEvents:this.broadcastEvents,children:(0,He.jsx)(zC,{inputElement:t})})}),E),(0,ln.render)((0,He.jsx)(Xo,{store:this.store,customStyles:r,children:(0,He.jsx)(Do,{broadcastEvents:this.broadcastEvents,children:(0,He.jsx)(SC,{onLogIn:()=>this.loginViaPopup().catch(R=>H.warn(R.message))})})}),C)}(0,ln.render)((0,He.jsx)(Xo,{store:this.store,customStyles:r,children:(0,He.jsx)(Do,{broadcastEvents:this.broadcastEvents,children:(0,He.jsx)(GE,{})})}),this.createContainer("deepdesk-overlays")),this.store.dispatch(hd({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()})),this.store.dispatch(yd(this.inputMediator.getSelection())),this.store.dispatch(op(this.inputMediator.isFocused)),this.unmountHandlers.push(()=>{this.state.input.text!==""&&this.storeMetrics()}),this.whenConversationLoaded(()=>{var E;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((E=this.state.conversation.current)==null?void 0:E.sessionId)}),this.isMounted=!0}unmount(){var t;this.unmountHandlers.forEach(n=>n()),this.unmountHandlers=[],(t=this.inputMediator)==null||t.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(t,n={}){if(this.widgetRoot&&H.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,isEmbedded:s}=n;this.widgetRoot=t,this.configure({showImages:o,isEmbedded:s}),(0,ln.render)((0,He.jsx)(Xo,{store:this.store,customStyles:r,children:(0,He.jsx)(Do,{broadcastEvents:this.broadcastEvents,children:(0,He.jsx)(sk,{onLogIn:()=>this.loginViaPopup().catch(i=>H.warn(i.message))})})}),t),this.whenConversationLoaded(()=>{var i;this.broadcastEvents.setSessionId((i=this.state.conversation.current)==null?void 0:i.sessionId)})}unmountWidget(){this.widgetRoot&&(0,ln.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(t){let n=Vp(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){Ik(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(()=>P(this,null,function*(){yield this.store.dispatch(al());let t=sr(this.state);t&&(yield this.store.dispatch(rl()),this.store.dispatch(ad({showSearch:t.search,showAutoflows:t.autoflows,showCustomMessages:t.customMessages,showImageSearch:t.imageSearch,showEntitiesCommand:t.entitiesCommand,showSummaryCommand:!!t.summarizerAssistantNew||t.summarizer,showKnowledgeSearch:!!t.knowledgeAssistantNew||!!t.knowledgeAssistant,recommendTextSuggestions:t.recommendTextSuggestions})))})),this.loadProfileConfigPromise)}loginViaPopup(t){return P(this,null,function*(){return new Promise((n,r)=>{let o=new MessageChannel,s=o.port1,i=this.state.settings.adminUrl,a=new URL(t!=null&&t.url?t==null?void 0:t.url:`${i}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let l=!1,u=()=>{c&&!c.closed&&c.close(),window.removeEventListener("message",p),clearInterval(d)};s.onmessage=g=>P(this,null,function*(){var y,v;if((y=g.data)!=null&&y.jwt)try{yield this.deepdeskApi.exchangeTokenForAccessCookie((v=g.data)==null?void 0:v.jwt),yield this.isLoggedIn(),this.broadcastEvents.send(Qa),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=g=>P(this,null,function*(){var y;if(g.origin===a.origin)switch((y=g.data)==null?void 0:y.type){case"deepdesk-popup-loaded":{try{let v=JSON.stringify({type:"deepdesk-popup-create-channel"});c==null||c.postMessage(v,a.origin,[o.port2])}catch(v){H.error("Error posting message to popup",v),r(v)}break}case"deepdesk-popup-error":{u(),g.data.message==="Timeout"&&H.warn("Popup timed out. Check if the account's platform url is configured correctly."),r(new Error(g.data.message));break}}});window.addEventListener("message",p);let d=setInterval(()=>{c&&!c.closed||(u(),l||r(new Error("Popup closed by user")))},200);this.unmountHandlers.push(u)})})}translateMessages(t){return this.deepdeskApi.translateMessages(t)}checkForTrialMode(t){return P(this,null,function*(){try{let{account:n}=yield this.deepdeskApi.getPlatformConfig();if(!n.isTrial){this.shouldRender=!0;return}if(H.info("Trial is active"),!(yield this.deepdeskApi.checkUserExists(t)))throw new Error("User is not in trial");this.shouldRender=!0}catch(n){let{message:r}=n;H.info(r),this.shouldRender=!1}})}refreshWidgetSuggestions(){return P(this,null,function*(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=ll(this.state);try{n.forEach(({type:r})=>{r==="entities"?this.store.dispatch(wn()):pu.includes(r)||this.store.dispatch(xn(r))})}catch(r){this.handleError(r)}})}};Oi.version="14.3.1-beta.1",Oi.count=0;var Kl=Oi;function R_(e){return P(this,null,function*(){var o,s,i;let n=yield((o=e.fetch)!=null?o:window.fetch)(e.url),r=yield n.blob();return new File([r],e.name,{type:(i=(s=e.mimeType)!=null?s:n.headers.get("Content-Type"))!=null?i:"image/jpeg"})})}function Vk(e,t){return P(this,null,function*(){let n=yield R_(t),r=new Event("change",{bubbles:!0,cancelable:!0});try{Object.defineProperty(e,"files",{configurable:!0,get:()=>[n]}),e.dispatchEvent(r)}finally{Object.hasOwn(e,"files")&&delete e.files}})}function Kk(e,t,n){return P(this,null,function*(){yield new br(e).authenticateWithKey(t,n)})}function Wk(e){return e.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}function $k(r,o){return P(this,arguments,function*(e,t,n={}){var p,d;let{value:s}=e,{start:i,end:a}=(p=n.replace)!=null?p:{start:0,end:s.length},l=`${s.slice(0,i)}${t}${s.slice(a)}`,u=(d=n.selectionAfter)!=null?d:{start:i+t.length,end:i+t.length},c=()=>{if(n.setValue)return n.setValue(l);e.value=l};return Promise.resolve(c()).then(()=>{e.selectionStart=u.start,e.selectionEnd=u.end,e.blur(),e.focus()})})}function qk(r,o){return P(this,arguments,function*(e,t,n={}){let s=n.replace?co(e,n.replace.start,n.replace.end):Ri(e),i,a=()=>{if(n.setRange)return n.setRange(s.cloneRange());s.deleteContents(),i=document.createElement("span"),s.insertNode(i),n.insertBRs!==!1?t.split(`
28
28
  `).reverse().forEach((l,u)=>{u>0&&s.insertNode(document.createElement("br")),s.insertNode(document.createTextNode(l))}):s.insertNode(document.createTextNode(t))};return Promise.resolve(a()).then(()=>{try{if(n.selectionAfter!==!1){e.focus();let l=n.selectionAfter?co(e,n.selectionAfter.start,n.selectionAfter.end):(s.collapse(!1),s),u=window.getSelection();u==null||u.removeAllRanges(),u==null||u.addRange(l)}if(!i)return;i.scrollIntoView&&i.scrollIntoView({block:"nearest",inline:"nearest"})}finally{i&&i.remove()}})})}function A_(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 I_(e){let t=document.createDocumentFragment();return e.split(`
29
29
  `).forEach((n,r)=>{r>0&&t.appendChild(document.createElement("br"));let o={index:0},s=0;for(;o=n.slice(s).match(/(\[([^\]]+)])\(([^)]+)\)/);){let i=document.createElement("a");i.href=o[3],i.setAttribute("target","_blank"),i.setAttribute("rel","noopener noreferrer"),i.appendChild(document.createTextNode(o[2])),t.appendChild(document.createTextNode(n.slice(s,s+o.index))),t.appendChild(i),s=s+o.index+o[0].length}t.appendChild(document.createTextNode(n.slice(s)))}),t}function Gk(e,t){let n=e.parentElement;if(!n){console.warn("No insert point found");return}let{display:r}=window.getComputedStyle(n);r.includes("block")||r==="table-cell"?n==null||n.insertBefore(t,e.nextSibling):Gk(n,t)}function Yk(o,s){return P(this,arguments,function*(e,t,{isBlock:n,isHTML:r}={}){let i;e.dispatchEvent(new InputEvent("beforeinput",{inputType:"insertText",data:t,bubbles:!0,cancelable:!0}));let a=()=>{var d;let l=(d=e.ownerDocument.defaultView)!=null?d:window,u=l.getSelection();if((!u||u.rangeCount===0)&&(e.focus(),u=l.getSelection()),!u||u.rangeCount===0)return;let c=u.getRangeAt(0);if(!c)return;i=document.createElement("span"),c.insertNode(i);let p=r?A_(t):I_(t);n?Gk(c.startContainer,p):(c.insertNode(p),c.collapse(!1))};return Promise.resolve(a()).then(()=>{if(e.dispatchEvent(new InputEvent("input",{inputType:"insertText",data:t,bubbles:!0,cancelable:!0})),e.focus(),!!i)try{i.scrollIntoView&&i.scrollIntoView({block:"nearest",inline:"nearest"})}finally{i&&i.remove()}})})}return cP(L_);})();
30
30
  /*! Bundled license information: