@deepdesk/deepdesk-sdk 10.10.3 → 10.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -16,13 +16,13 @@ Try polyfilling it using "@formatjs/intl-pluralrules"
16
16
  `);return o=o.replace(/\n{3,}/g,`
17
17
 
18
18
 
19
- `),o=o.replace(/\n/g,"<br/>"),o}createContainer(t){var n;let o=(typeof global<"u"&&global.INTERWEAVE_SSR_POLYFILL||CI)();if(!o)return;let i=(n=this.props.containerTagName)!==null&&n!==void 0?n:"body",s=i==="body"||i==="fragment"?o.body:o.createElement(i);return t.match(wI)||(s.innerHTML=this.convertLineBreaks(this.props.escapeHtml?(0,E_.default)(t):t)),s}extractAttributes(t){let{allowAttributes:n}=this.props,r={},o=0;return t.nodeType!==b_||!t.attributes||([...t.attributes].forEach(i=>{let{name:s,value:a}=i,l=s.toLowerCase(),u=Fc[l]||Fc[s];if(!this.isSafe(t)||!l.match(bI)&&(!n&&(!u||u===hg)||l.startsWith("on")||a.replace(/(\s|\0|&#x0([9AD]);)/,"").match(/(javascript|vbscript|livescript|xss):/i)))return;let c=l==="style"?this.extractStyleAttribute(t):a;u===Sr?c=!0:u===oo?c=Number.parseFloat(String(c)):u!==Dc&&(c=String(c)),r[yg[l]||l]=this.applyAttributeFilters(l,c),o+=1}),o===0)?null:r}extractStyleAttribute(t){let n={};return Array.from(t.style).forEach(r=>{let o=t.style[r];(typeof o=="string"||typeof o=="number")&&(n[r.replace(/-([a-z])/g,(i,s)=>String(s).toUpperCase())]=o)}),n}getTagConfig(t){let n={children:[],content:0,invalid:[],parent:[],self:!0,tagName:"",type:0,void:!1};return ha[t]?{...n,...ha[t],tagName:t}:n}isSafe(t){if(typeof HTMLAnchorElement<"u"&&t instanceof HTMLAnchorElement){let n=t.getAttribute("href");if(n!=null&&n.startsWith("#"))return!0;let r=t.protocol.toLowerCase();return r===":"||r==="http:"||r==="https:"||r==="mailto:"||r==="tel:"}return!0}isTagAllowed(t){return this.banned.has(t)||this.blocked.has(t)?!1:this.props.allowElements||this.allowed.has(t)}parse(){return this.container?this.parseNode(this.container,this.getTagConfig(this.container.nodeName.toLowerCase())):[]}parseNode(t,n){let{noHtml:r,noHtmlExceptMatchers:o,allowElements:i,transform:s,transformOnlyAllowList:a}=this.props,l=[],u="";return[...t.childNodes].forEach(c=>{if(c.nodeType===b_){let d=c.nodeName.toLowerCase(),f=this.getTagConfig(d);u&&(l.push(u),u="");let y=this.applyNodeFilters(d,c);if(!y)return;let v;if(s&&!(a&&!this.isTagAllowed(d))){this.keyIndex+=1;let m=this.keyIndex;v=this.parseNode(y,f);let h=s(y,v,f);if(h===null)return;if(typeof h<"u"){l.push(so.default.cloneElement(h,{key:m}));return}this.keyIndex=m-1}if(this.banned.has(d))return;if(!(r||o&&d!=="br")&&this.isTagAllowed(d)&&(i||this.canRenderChild(n,f))){var p;this.keyIndex+=1;let m=this.extractAttributes(y),h={tagName:d};m&&(h.attributes=m),f.void&&(h.selfClose=f.void),l.push(so.default.createElement(jc,{...h,key:this.keyIndex},(p=v)!==null&&p!==void 0?p:this.parseNode(y,f)))}else l=[...l,...this.parseNode(y,f.tagName?f:n)]}else if(c.nodeType===_I){let d=r&&!o?c.textContent:this.applyMatchers(c.textContent||"",n);Array.isArray(d)?l=[...l,...d]:u+=d}}),u&&l.push(u),l}replaceTokens(t,n){if(!t.includes("{{{"))return t;let r=[],o=t,i=null;for(;i=o.match(EI);){let[s,a]=i,l=i.index,u=s.includes("/");l>0&&(r.push(o.slice(0,l)),o=o.slice(l));let{children:c,matcher:p,props:d}=n[a],f;if(u)f=s.length,r.push(p.createElement(c,d));else{let y=o.match(new RegExp(`{{{/${a}}}}`));f=y.index+y[0].length,r.push(p.createElement(this.replaceTokens(o.slice(s.length,y.index),n),d))}o=o.slice(f)}return o.length>0&&r.push(o),r.length===0?"":r.length===1&&typeof r[0]=="string"?r[0]:r}};function TI(e){var t;let{attributes:n,className:r,containerTagName:o,content:i,emptyContent:s,parsedContent:a,tagName:l,noWrap:u}=e,c=(t=o??l)!==null&&t!==void 0?t:"span",p=c==="fragment"?!0:u,d;if(a)d=a;else{let f=new Hc(i??"",e).parse();f.length>0&&(d=f)}return d||(d=s),p?so.default.createElement(so.default.Fragment,null,d):so.default.createElement(jc,{attributes:n,className:r,tagName:c},d)}function Cn(e){let{attributes:t,className:n,content:r="",disableFilters:o=!1,disableMatchers:i=!1,emptyContent:s=null,filters:a=[],matchers:l=[],onAfterParse:u=null,onBeforeParse:c=null,tagName:p="span",noWrap:d=!1,...f}=e,y=i?[]:l,v=o?[]:a,m=c?[c]:[],h=u?[u]:[];y.forEach(w=>{w.onBeforeParse&&m.push(w.onBeforeParse.bind(w)),w.onAfterParse&&h.push(w.onAfterParse.bind(w))});let g=m.reduce((w,E)=>E(w,e),r??""),x=new Hc(g,f,y,v),_=h.reduce((w,E)=>E(w,e),x.parse());return so.default.createElement(TI,{attributes:t,className:n,containerTagName:e.containerTagName,emptyContent:s,noWrap:d,parsedContent:_.length===0?void 0:_,tagName:p})}var Pg=S(q());var Sg={root:"_root_smoda_1",agentText:"_agentText_smoda_3",textInput:"_textInput_smoda_8",textInputWrapper:"_textInputWrapper_smoda_27",alert:"_alert_smoda_31",alertText:"_alertText_smoda_50",warning:"_warning_smoda_60",success:"_success_smoda_69"};var T_=S(q());var bi=S(O());function C_(e,t){let n;return[(...r)=>{window.cancelAnimationFrame(n);let o=t?t(...r):r;n=window.requestAnimationFrame(()=>{e(...o)})},()=>window.cancelAnimationFrame(n)]}function Bc(e){let t=(0,bi.useRef)(null),[n,r]=(0,bi.useState)(!1);return(0,bi.useEffect)(()=>{let o=!1,i=parseFloat(window.getComputedStyle(document.body).zoom??"1"),[s,a]=C_((c,p)=>{let d=t.current;if(!d)return;let f=c/i,y=p/i,v=d.getBoundingClientRect(),m=f>v.x&&f<v.x+v.width&&y>v.y&&y<v.y+v.height;m&&!o?(o=!0,r(!0)):!m&&o&&(o=!1,r(!1))},({clientX:c,clientY:p})=>[c,p]),[l,u]=C_(()=>{o=!1,r(!1)});return e.addEventListener("mousemove",s),e.addEventListener("mouseleave",l),()=>{a(),u(),e.removeEventListener("mousemove",s),e.removeEventListener("mouseleave",l)}},[t]),[t,n]}var Tn={root:"_root_81non_1",container:"_container_81non_3",agentText:"_agentText_81non_5",tabText:"_tabText_81non_6",hint:"_hint_81non_6",matchSelection:"_matchSelection_81non_10",focus:"_focus_81non_16",resetIndent:"_resetIndent_81non_20",matchKeyword:"_matchKeyword_81non_24",matchPlaceholder:"_matchPlaceholder_81non_25",hover:"_hover_81non_31",hintText:"_hintText_81non_64",popover:"_popover_81non_72",popoverRoot:"_popoverRoot_81non_77",popoverContentContainer:"_popoverContentContainer_81non_81",popoverContent:"_popoverContent_81non_81",selectionOptions:"_selectionOptions_81non_107",selectionOptionsIsHidden:"_selectionOptionsIsHidden_81non_112",selectionOptionsButton:"_selectionOptionsButton_81non_116",caret:"_caret_81non_132",popoverSuggestionsRoot:"_popoverSuggestionsRoot_81non_136",suggestionsOverlayInputStyles:"_suggestionsOverlayInputStyles_81non_141"};var xg=S(b()),kI=({inputElement:e,children:t})=>{let n=P("TabCompletion",Tn),[r,o]=Bc(e);return(0,xg.jsx)("mark",{ref:r,className:(0,T_.default)(n.matchPlaceholder,{[n.hover]:o}),children:t})},Ei=class extends bn{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,xg.jsx)(kI,{inputElement:n.inputElement,children:t},`placeholder_${n.matchString}_${n.key}`)}asTag(){return"mark"}};var Ci=S(O());function zc(e){return e.contentEditable==="true"}function PI(e){let t=0,n=0,r=window.getSelection();if(r.rangeCount!==0){let o=r.getRangeAt(0),i=o.cloneRange();i.selectNodeContents(e),i.setEnd(o.endContainer,o.endOffset),n=i.toString().length,i.selectNodeContents(e),i.setEnd(o.startContainer,o.startOffset),t=i.toString().length}return{selectionStart:t,selectionEnd:n}}function k_(e){let{selectionStart:t,selectionEnd:n}=zc(e)?PI(e):e;return[t,n]}function Uc(e){let[,t]=(0,Ci.useState)(),n=(0,Ci.useRef)(null);return n.current=k_(e),(0,Ci.useEffect)(()=>{let r=()=>{let[o,i]=n.current??[],s=k_(e);(!s||o!==s[0]||i!==s[1])&&(n.current=s,t({}))};return e.addEventListener("keyup",r),e.addEventListener("click",r),e.addEventListener("focus",r),document.addEventListener("selectionchange",r),()=>{e.removeEventListener("keyup",r),e.removeEventListener("click",r),e.removeEventListener("focus",r),document.removeEventListener("selectionchange",r)}},[e]),n.current}function Kc(e,t){if(!t)return;let n=e,{value:r}=n,[o,i]=t,s=r.match(Lo);if(!s||s.length===0)return;let a=0;s.find(l=>{let u=r.indexOf(l,a);return o>u&&i<u+l.length?(n.selectionStart=u,n.selectionEnd=u+l.length,!0):(a=u+l.length,!1)})}var P_=S(O());function Ti(e){(0,P_.useEffect)(()=>{let t=n=>{n.isWithinRoot||e(n)};return document.body.addEventListener("mouseup",t),()=>{document.body.removeEventListener("mouseup",t)}},[e])}function ao(e){e.addEventListener("mouseup",t=>{t.isWithinRoot=!0},!0)}var I_,sn=new Map,II=["bottom","height","left","right","top","width"],RI=(e={},t={})=>II.some(n=>e[n]!==t[n]);function R_(e){var n,r;if(e.ownerDocument===document)return[];let t=((r=(n=e.ownerDocument)==null?void 0:n.defaultView)==null?void 0:r.frameElement)??null;return t?[t,...R_(t)]:[]}function L_(e,t){return!e||!t?null:{...e,top:e.top+t.top,left:e.left+t.left}}var Vc=!1,A_=()=>{Vc=!0;let e=[];if(sn.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),sn.delete(n);return}let r=n.getBoundingClientRect();RI(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{let n=t.parentRects?t.parentRects.reduce(L_,t.rect):t.rect;t.callbacks.forEach(r=>r(n))}),sn.size===0){Vc=!1;return}I_=window.requestAnimationFrame(A_)};function _g(e,t){let n=R_(e),r=[],o=n.map((i,s)=>_g(i,a=>{r[s]=a;let l=sn.get(e);if(!l)return;let u=r.reduce(L_,l.rect);l.callbacks.forEach(c=>c(u))}));return{observe(i=!0){if(o.forEach(s=>s.observe(!1)),sn.has(e)){let s=sn.get(e);s.callbacks.push(t),s.rect&&t(s.rect)}else sn.set(e,{rect:void 0,callbacks:[t],parentRects:r});i&&!Vc&&A_()},unobserve(){o.forEach(s=>s.unobserve());let i=sn.get(e);if(i){let s=i.callbacks.indexOf(t);s>=0&&i.callbacks.splice(s,1),i.callbacks.length||sn.delete(e),sn.size||(cancelAnimationFrame(I_),Vc=!1)}}}}var O_,an=new Map,N_=()=>{an.forEach((e,t)=>{if(!t.isConnected){an.delete(t);return}let{clientHeight:n,scrollHeight:r}=t,o=r>n;e.visible!==o&&(e.visible=o,e.callbacks.forEach(i=>i(e.visible)))}),an.size!==0&&(O_=window.requestAnimationFrame(N_))};function M_(e,t){return{observe(){let n=an.size===0;an.has(e)?an.get(e).callbacks.push(t):an.set(e,{visible:void 0,callbacks:[t]}),n&&N_()},unobserve(){let n=an.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||an.delete(e),an.size||cancelAnimationFrame(O_)}}}}var wg=["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 bg(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function ki(e){return parseFloat(e)}function Wc(e){return Math.round(e*1e6)}function D_(e){return e/1e6}function Eg(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=ki(e.width),i=ki(e.borderLeftWidth),s=ki(e.borderRightWidth),a=ki(e.paddingRight),l=D_(Wc(o)-Wc(i)-Wc(s)),u=D_(Wc(r));if(l-u>2){let c=l-u;n.style.paddingRight=`${a+c}px`}}function lo(e,t={}){var c;let n=t.overlayContainer||document.createElement("div");n.style.display="none",n.style.position=t.position??"fixed",n.style.pointerEvents="none",n.style.borderColor="transparent",ao(n);let r=window.getComputedStyle(e),o=!0,i=()=>{n.scrollTop=e.scrollTop};bg(r,n,wg),Eg(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",i));let s=M_(e,()=>{bg(r,n,wg),Eg(r,e,n),i(),setTimeout(i,0)}),a,l=!0,u=_g(e,p=>{if(p===null){t.onRemove&&t.onRemove(),n.remove();return}if(!l&&t.onMoveStart&&(Promise.resolve().then(()=>t.onMoveStart()),l=!0),clearTimeout(a),a=setTimeout(()=>{t.onMoveEnd&&t.onMoveEnd(),l=!1},200),p.height===0&&p.width===0){if(o===!0)return;t.onHide&&t.onHide(),n.style.display="none",o=!0;return}if(bg(r,n,wg),Eg(r,e,n),i(),n.style.top=`${p.top}px`,n.style.left=`${p.left}px`,t.closestScrollElement&&t.closestScrollElement!==e){let d=t.closestScrollElement.getBoundingClientRect(),f=window.getComputedStyle(t.closestScrollElement),y=ki(f.borderTopWidth),v=ki(f.borderBottomWidth),m=d.top+y-p.top,h=p.top+p.height+-(d.top+d.height-v);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):(c=e.parentElement)==null||c.appendChild(n),u.observe(),s.observe(),[n,()=>{e.removeEventListener("scroll",i),u.unobserve(),s.unobserve()}]}var Cg={};Pe(Cg,{enUS:()=>LI,nlNL:()=>AI});var LI={placeholders:[{type:6,value:"placeholderSize",options:{"=0":{value:[{type:0,value:"No placeholders found"}]},one:{value:[{type:0,value:"There is one placeholder in your message"}]},other:{value:[{type:0,value:"There are "},{type:7},{type:0,value:" placeholders in your message"}]}},offset:0,pluralType:"cardinal"}]},AI={placeholders:[{type:6,value:"placeholderSize",options:{"=0":{value:[{type:0,value:"Alle placeholders zijn uit je bericht"}]},one:{value:[{type:0,value:"Er is 1 placeholder in jouw bericht"}]},other:{value:[{type:0,value:"Er zijn "},{type:7},{type:0,value:" placeholders in jouw bericht"}]}},offset:0,pluralType:"cardinal"}]};var ya=S(b()),F_=()=>(0,ya.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 512 512","aria-labelledby":"circleCheckTitle",children:[(0,ya.jsx)("title",{id:"circleCheckTitle",children:"Check"}),(0,ya.jsx)("path",{d:"M243.8 339.8C232.9 350.7 215.1 350.7 204.2 339.8L140.2 275.8C129.3 264.9 129.3 247.1 140.2 236.2C151.1 225.3 168.9 225.3 179.8 236.2L224 280.4L332.2 172.2C343.1 161.3 360.9 161.3 371.8 172.2C382.7 183.1 382.7 200.9 371.8 211.8L243.8 339.8zM512 256C512 397.4 397.4 512 256 512C114.6 512 0 397.4 0 256C0 114.6 114.6 0 256 0C397.4 0 512 114.6 512 256zM256 48C141.1 48 48 141.1 48 256C48 370.9 141.1 464 256 464C370.9 464 464 370.9 464 256C464 141.1 370.9 48 256 48z"})]});var Tg=S(b()),j_=()=>(0,Tg.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",fill:"currentColor",children:(0,Tg.jsx)("path",{d:"M256 32c14.2 0 27.3 7.5 34.5 19.8l216 368c7.3 12.4 7.3 27.7 .2 40.1S486.3 480 472 480H40c-14.3 0-27.6-7.7-34.7-20.1s-7-27.8 .2-40.1l216-368C228.7 39.5 241.8 32 256 32zm0 128c-13.3 0-24 10.7-24 24V296c0 13.3 10.7 24 24 24s24-10.7 24-24V184c0-13.3-10.7-24-24-24zm32 224c0-17.7-14.3-32-32-32s-32 14.3-32 32s14.3 32 32 32s32-14.3 32-32z"})});var H_=(s=>(s.CUT="Cut",s.BACKSPACE="Backspace",s.DELETE="Delete",s.ERASEEOF="EraseEof",s.UNDO="Undo",s.CLEAR="Clear",s))(H_||{}),kn=class{constructor(t){this.element=t;this.currentText=this.getText(),this.currentHTML=this.getHTML(),this.listen()}eventListeners={};disposeHandlers=[];currentText="";currentCaret=null;currentSelection={start:0,end:0};currentHTML="";isFocused=!1;isActive=!0;isSettingValue=!1;isSubmitting=!1;isPossibleClearInputAction=!1;isDisposed=!1;addEventListener(t,n){let r=o=>{n(o)};this.element.addEventListener(t,r),this.disposeHandlers.push(()=>{this.element.removeEventListener(t,r)})}removeEventListener(t,n){this.element.removeEventListener(t,n)}triggerChange(){let t=this.getText(),n=this.getHTML(),r=t!==this.currentText;this.isActive&&(t===""&&this.currentText!==""&&!this.isSettingValue&&!this.isPossibleClearInputAction&&(this.isSubmitting=!0,this.emit("submit")),!this.isSettingValue&&r&&!this.isSubmitting&&this.emit("change",{plainText:t}),r&&(this.currentSelection=this.getSelection()),this.currentText=t,this.isSubmitting=!1,(this.currentHTML!==n||n===null&&r)&&(this.emit("updated",{plainText:t}),this.triggerCaretPosition(),this.currentHTML=n))}triggerSelection(){let t=this.getSelection();(t.start!==this.currentSelection.start||t.end!==this.currentSelection.end)&&(this.currentSelection=t,this.emit("selection",t),this.triggerCaretPosition())}triggerCaretPosition(){let t=this.getCaretPosition();hr(t,this.currentCaret)||(this.currentCaret=t,this.emit("caret",t))}handleKeyUp(t){let{key:n,shiftKey:r}=t;(n==="Enter"&&r===!0||n==="Backspace")&&this.triggerChange(),this.triggerSelection()}handleClick(){this.triggerSelection()}handleFocus(){this.isFocused||this.emit("focus"),this.triggerSelection(),this.isFocused=!0}handleBlur(){this.isPossibleClearInputAction=!1,this.isFocused&&this.emit("blur"),this.isFocused=!1}handleKeyDown(t){let{key:n,ctrlKey:r,metaKey:o}=t;this.isPossibleClearInputAction=Object.values(H_).includes(n)||n.toLowerCase()==="z"&&(r||o),this.emit("keydown",t)}handleCut(){this.isPossibleClearInputAction=!0,this.emit("cut",{selectionText:this.getSelectedText()})}handlePaste(t){var r,o;let n=((r=t.clipboardData)==null?void 0:r.getData("text"))||((o=t.clipboardData)==null?void 0:o.getData("text/plain"))||"";this.emit("paste",{pastedText:n,selectionText:this.getSelectedText()})}listen(){this.addEventListener("keydown",n=>this.handleKeyDown(n)),this.addEventListener("keyup",n=>this.handleKeyUp(n)),this.addEventListener("input",()=>this.triggerChange()),this.addEventListener("change",()=>this.triggerChange()),this.addEventListener("focus",()=>this.handleFocus()),this.addEventListener("blur",()=>this.handleBlur()),this.addEventListener("cut",()=>this.handleCut()),this.addEventListener("paste",n=>this.handlePaste(n)),this.addEventListener("click",()=>this.triggerSelection()),document.activeElement===this.element&&setTimeout(()=>{this.handleFocus()},0);let t=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});t.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{t.disconnect()}),this.currentSelection=this.getSelection()}focus(){this.element.focus()}emit(t,...n){this.isDisposed||this.eventListeners[t]&&this.eventListeners[t].forEach(r=>{r(...n)})}on(t,n){this.isDisposed||(this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n))}activate(){let t=this.isActive===!1;this.isActive=!0,t&&this.triggerChange()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(t=>t()),this.eventListeners={},this.isDisposed=!0}};var Pn=class extends kn{lastKnownSelection=null;getText(){return this.element.value}getHTML(){return null}getSelection(){let{selectionStart:t,selectionEnd:n}=this.element;return{start:t,end:n}}getSelectedText(){let t=this.getSelection();return t?this.getText().slice(t.start,t.end):""}getCaretPosition(){return null}applyChanges(t){if(!this.isActive)return;this.isSettingValue=!0;let n=this.getText(),r=t(this.element);return Promise.resolve(r).then(()=>{this.currentText=this.getText(),n!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(){super.listen();let t=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var o;return(o=t==null?void 0:t.get)==null?void 0:o.call(this.element)},set:o=>{var i;(i=t==null?void 0:t.set)==null||i.call(this.element,o),this.triggerChange()}});let n=this.element.disabled,r=new MutationObserver(()=>{this.element.disabled!==n&&(n=this.element.disabled,this.emit(n?"disabled":"enabled"))});r.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>r.disconnect())}};var OI=/[.*+?^${}()|[\]\\]/g,NI=/[^0-9A-Za-zÀ-ÖØ-öø-ÿ](?=[0-9A-Za-zÀ-ÖØ-öø-ÿ]*$)/;function MI(e){return e.replace(OI,"\\$&")}function DI(e,t){let n=e.split("").findIndex((r,o)=>r!==t[o]);return n>-1?n:Math.min(e.length,t.length)}function FI(e){return e.search(NI)}function B_(e,t=[]){let n=e;return t.forEach(r=>{if(!r)return;let o=new RegExp(`\\b(${MI(r)})\\b`,"gi");n=n.replace(o,"<strong>$1</strong>")}),n}function z_(e){return e.replace(Lo,'<mark data-type="placeholder">$1</mark>')}function Pi(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}function jI(e,t){return e.split("").map((s,a)=>({char:s,index:a})).filter(({char:s,index:a})=>/\s/.test(s)&&a<=t).map(({index:s})=>s).reverse()[0]}function kg(e,t,n={}){if(t){let r=DI(t.toLowerCase(),e.toLowerCase()),o=Pi(e.substring(r,e.length));if(n.stripAgentPart){let l=e.substring(0,r),u=FI(l);return`<span style="opacity: 0.5">${l.substring(u+1)}</span>${o}`}let s=t.split(Ey).length>3||t.length>30?jI(t.trim(),r):0;return`${`${s>0?"\u2026":""}${Pi(e.substring(s,r))}`}<strong>${o}</strong>`}return e}var HI=/(<\/[a-zA-Z]+[0-9]?>|<[a-zA-Z]+\s?\/>|<br>)/i;function uo(e){return HI.test(e)}function U_(e){if(uo(e)){let n=/<body[^>]*>([\s\S]*)<\/body>/gi.exec(e);return n?n[1]:""}return e}function K_(e){let t=document.createElement("template");return t.innerHTML=e,t.content.textContent??""}var Ue=S(b()),BI=({value:e,onUse:t,...n})=>{var p;let r=H(Cg),o=U(),i=uo(e),s=P("EditSuggestionTextInput",Sg),[a,l]=(0,Rt.useState)(null),u=(0,Rt.useRef)(null),c=((p=e.match(Lo))==null?void 0:p.length)||0;return(0,Rt.useEffect)(()=>{let d;return u.current&&(l(u.current),d=new Pn(u.current),d.on("change",({plainText:f})=>{o(rt.actions.userInput({text:f,selection:d.getSelection()}))}),d.on("keydown",f=>{o(rt.actions.registerKeyDown(pc(f))),f.code==="Enter"&&f.shiftKey&&t(d.getText())}),d.on("paste",({pastedText:f,selectionText:y})=>{o(rt.actions.registerPaste({text:f,selectionText:y}))}),d.on("cut",({selectionText:f})=>{o(rt.actions.registerCut(f))})),()=>{o(rt.actions.reset()),d.dispose(),d.deactivate()}},[u]),(0,Rt.useEffect)(()=>{e&&u.current&&(u.current.value=e)},[e,u]),(0,Rt.useEffect)(()=>{u.current&&setTimeout(()=>{if(!u.current)return;let d=u.current.value.length;u.current.setSelectionRange(d,d),u.current.focus()},0)},[u]),i?(0,Ue.jsx)("div",{className:s.textInputWrapper,children:(0,Ue.jsx)(Cn,{className:s.textInput,tagName:"div",content:e})}):(0,Ue.jsxs)("div",{className:s.textInputWrapper,children:[(0,Ue.jsx)("textarea",{...n,ref:u,"data-testid":"edit-suggestion-dialog-textarea",className:s.textInput,defaultValue:e,onChange:()=>{}}),a&&(0,Ue.jsx)(zI,{inputElement:u.current,value:e}),(0,Ue.jsxs)("div",{className:(0,Pg.default)(s.alert,c===0?s.success:s.warning),children:[(0,Ue.jsx)("div",{className:s.alertText,children:r("placeholders",{placeholderSize:c})}),c===0?(0,Ue.jsx)(F_,{}):(0,Ue.jsx)(j_,{})]})]})},zI=({inputElement:e,value:t})=>{let n=P("EditSuggestionTextInput",Sg),r=(0,Rt.useRef)(null),o=Uc(e);return(0,Rt.useEffect)(()=>{Kc(e,o)},[o,e]),(0,Ue.jsx)(UI,{inputElement:e,children:(0,Ue.jsxs)("div",{ref:r,className:(0,Pg.default)(n.root,n.agentText),children:[(0,Ue.jsx)(Cn,{tagName:"span",disableLineBreaks:!0,content:t,matchers:[new Ei("placeholders")],inputElement:e,boundaryRef:r}),(0,Ue.jsx)("br",{})]})})},UI=({inputElement:e,children:t})=>{let n=(0,Rt.useRef)(null);return(0,Rt.useEffect)(()=>{if(!n.current)return()=>{};let[r,o]=lo(e,{overlayContainer:n.current,mirrorOverflow:!0});return r.setAttribute("translate","no"),()=>{o()}},[n.current]),(0,Ue.jsx)("div",{ref:n,children:t})},V_=BI;var Li=S(O());var W_=S(O()),$c=S(q());var ot={root:"_root_1mc8f_1",list:"_list_1mc8f_2",listWrapper:"_listWrapper_1mc8f_6",listHorizontal:"_listHorizontal_1mc8f_10",page:"_page_1mc8f_19",search:"_search_1mc8f_25",pageNav:"_pageNav_1mc8f_33",pageTitle:"_pageTitle_1mc8f_41",pageBackButton:"_pageBackButton_1mc8f_48",listHeading:"_listHeading_1mc8f_62",listItem:"_listItem_1mc8f_70",listItemContent:"_listItemContent_1mc8f_79",listItemText:"_listItemText_1mc8f_97",listItemDescription:"_listItemDescription_1mc8f_105",listItemActions:"_listItemActions_1mc8f_112",truncate:"_truncate_1mc8f_123",lineClamp:"_lineClamp_1mc8f_129",listItemTitle:"_listItemTitle_1mc8f_136",listItemAction:"_listItemAction_1mc8f_112",listItemPrimaryAction:"_listItemPrimaryAction_1mc8f_157",listItemSelected:"_listItemSelected_1mc8f_162",sources:"_sources_1mc8f_166",sourcesTitle:"_sourcesTitle_1mc8f_173",source:"_source_1mc8f_166",icon:"_icon_1mc8f_188",searchIcon:"_searchIcon_1mc8f_205",searchInputWrapper:"_searchInputWrapper_1mc8f_210",searchInput:"_searchInput_1mc8f_210",select:"_select_1mc8f_231",selectType:"_selectType_1mc8f_248",selectWrapper:"_selectWrapper_1mc8f_252",image:"_image_1mc8f_282",imageSrc:"_imageSrc_1mc8f_289",imageSrcHidden:"_imageSrcHidden_1mc8f_300",imageSrcStatus:"_imageSrcStatus_1mc8f_304",imageTitle:"_imageTitle_1mc8f_314",actions:"_actions_1mc8f_319",actionsWrapper:"_actionsWrapper_1mc8f_323",actionsBar:"_actionsBar_1mc8f_329",actionButton:"_actionButton_1mc8f_338",hasShortKeys:"_hasShortKeys_1mc8f_351",actionShortcut:"_actionShortcut_1mc8f_360",actionShortcutFixKerning:"_actionShortcutFixKerning_1mc8f_367"};var co={};Pe(co,{enUS:()=>KI,nlNL:()=>VI});var KI={visitUrl:[{type:0,value:"Visit"}],back:[{type:0,value:"Back"}],loading:[{type:0,value:"Loading..."}],imageError:[{type:0,value:"Could not load image"}]},VI={visitUrl:[{type:0,value:"Bekijk"}],back:[{type:0,value:"Terug"}],loading:[{type:0,value:"Laden..."}],imageError:[{type:0,value:"Kan afbeelding niet laden"}]};var xr=S(b()),WI=({src:e,title:t})=>{let n=P("CommandPalette",ot),[r,o]=(0,W_.useState)("loading"),i=H(co);return(0,xr.jsxs)("div",{className:n.image,children:[(0,xr.jsx)("img",{src:e,alt:t,onLoad:()=>o("done"),onError:()=>o("error"),className:(0,$c.default)(n.imageSrc,{[n.imageSrcHidden]:["loading","error"].includes(r)})}),r==="loading"&&(0,xr.jsx)("span",{className:(0,$c.default)(n.imageSrc,n.imageSrcStatus),children:i("loading")}),r==="error"&&(0,xr.jsx)("span",{className:(0,$c.default)(n.imageSrc,n.imageSrcStatus),children:(0,xr.jsx)(nl,{})}),t&&(0,xr.jsx)("span",{className:n.imageTitle,children:t})]})},$_=WI;var q_=S(O()),G_=S(q());var va=S(b());function Ig({children:e,heading:t,orientation:n}){let r=P("CommandPalette",ot);return q_.default.Children.count(e)===0?null:(0,va.jsxs)("div",{"data-testid":"commandpalette-list",className:r.list,children:[t&&(0,va.jsx)("h4",{className:r.listHeading,children:t}),(0,va.jsx)("div",{className:(0,G_.default)(r.listWrapper,n==="horizontal"&&r.listHorizontal),children:e})]})}var Sa=S(q());var Ae=S(O()),X_=S(q());var Rg={root:"_root_1oh4w_1",trigger:"_trigger_1oh4w_5",content:"_content_1oh4w_19",contentOpen:"_contentOpen_1oh4w_33",contentTop:"_contentTop_1oh4w_37",contentBottom:"_contentBottom_1oh4w_41",item:"_item_1oh4w_45"};var po=S(b()),$I=0,Q_=Ae.default.createContext(null),qI=()=>{let e=(0,Ae.useContext)(Q_);if(!e)throw new Error("Invalid DropdownContext");return e},Y_=({trigger:e,children:t,position:n="bottom"})=>{let r=(0,Ae.useMemo)(()=>++$I,[]),o=(0,Ae.useRef)(null),i=(0,Ae.useRef)(null),s=P("Dropdown",Rg),[a,l]=(0,Ae.useState)(!1),[u,c]=(0,Ae.useState)(n),p=f=>{f.preventDefault(),f.stopPropagation(),l(!a)},d=(0,Ae.useCallback)(([f])=>{!f.isIntersecting&&a&&c(u==="top"?"bottom":"top")},[a]);return(0,Ae.useEffect)(()=>{let f=y=>{o.current&&!o.current.contains(y.target)&&l(!1)};return document.addEventListener("click",f),()=>{document.removeEventListener("click",f)}},[]),(0,Ae.useEffect)(()=>{if(!i.current&&!a)return()=>{};let f=new IntersectionObserver(d,{root:null,rootMargin:"0px",threshold:1});return i.current&&f.observe(i.current),()=>{i.current&&f.unobserve(i.current)}},[i,a]),(0,po.jsx)(Q_.Provider,{value:{setIsOpen:l},children:(0,po.jsxs)("div",{ref:o,className:s.root,children:[(0,po.jsx)("button",{id:`dropdown-${r}`,"data-testid":"dropdown-trigger","aria-haspopup":"true","aria-expanded":a,"aria-label":"Dropdown trigger",type:"button",className:s.trigger,onClick:p,children:e}),(0,po.jsx)("div",{"data-testid":"dropdown-content",ref:i,"aria-hidden":!a,"aria-labelledby":`dropdown-${r}`,className:(0,X_.default)(s.content,{[s.contentOpen]:a,[s.contentTop]:u==="top",[s.contentBottom]:u==="bottom"}),children:t})]})})};function GI({as:e,children:t,onClick:n,...r}){let o=e||"button",i=P("Dropdown",Rg),{setIsOpen:s}=qI(),a=l=>{s(!1),n(l),l.stopPropagation()};return(0,po.jsx)(o,{type:"button",className:i.item,onClick:a,...r,children:t})}Y_.Item=GI;var Lg=Y_;var Ag=S(b()),Z_=e=>(0,Ag.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"16",width:"14",viewBox:"0 0 448 512",...e,children:(0,Ag.jsx)("path",{fill:"currentColor",d:"M8 256a56 56 0 1 1 112 0A56 56 0 1 1 8 256zm160 0a56 56 0 1 1 112 0 56 56 0 1 1 -112 0zm216-56a56 56 0 1 1 0 112 56 56 0 1 1 0-112z"})});var fo={};Pe(fo,{enUS:()=>XI,nlNL:()=>QI});var XI={preview:[{type:0,value:"Preview"}],useSuggestion:[{type:0,value:"Add"}],sendSuggestion:[{type:0,value:"Send"}],suggestionSent:[{type:0,value:"Sent"}],sendingError:[{type:0,value:"Sending failed"}],tryAgain:[{type:0,value:"Try again"}],editSuggestion:[{type:0,value:"Edit"}],visitUrl:[{type:0,value:"Visit"}],giveFeedback:[{type:0,value:"Give feedback"}],answer:[{type:0,value:"Answer"}]},QI={preview:[{type:0,value:"Preview"}],useSuggestion:[{type:0,value:"Gebruik"}],sendSuggestion:[{type:0,value:"Verzenden"}],suggestionSent:[{type:0,value:"Verzonden"}],sendingError:[{type:0,value:"Verzenden mislukt"}],tryAgain:[{type:0,value:"Probeer opnieuw"}],editSuggestion:[{type:0,value:"Bewerken"}],visitUrl:[{type:0,value:"Bekijk"}],giveFeedback:[{type:0,value:"Geef feedback"}],answer:[{type:0,value:"Antwoord"}]};var qc=S(b()),YI="%0d%0a%0d%0a%0d%0a",ZI=(e,t)=>{let n=[`Suggestie: ${encodeURIComponent(t)}`,"Beschrijf je feedback:"];return`mailto:${e.join(",")}?subject=Suggestie feedback&body=${n.join(YI)}`},JI=({suggestion:e,onFeedback:t})=>{let n=H(fo),r=M("suggestionFeedbackEmailAddresses");return!r||r.length===0?null:(0,qc.jsx)(Lg,{trigger:(0,qc.jsx)(Z_,{"data-testid":"feedback-dropdown-trigger"}),children:(0,qc.jsx)(Lg.Item,{as:"a",href:ZI(r,e),onClick:t,children:n("giveFeedback")})})},Gc=JI;var Xc=S(O()),tw=S(b()),J_=Xc.default.createContext(void 0);function _r(){let e=Xc.default.useContext(J_);if(e===void 0)throw new Error("useCommandPalette must be used within the CommandPalette component");return e}var ew=({children:e,page:t,isOpen:n,onChangeOpen:r,selected:o,setSelected:i})=>{let s=Xc.default.useMemo(()=>({page:t,isOpen:n,onChangeOpen:r,selected:o,setSelected:i}),[n,t,o]);return(0,tw.jsx)(J_.Provider,{value:s,children:e})};var pt=S(b());function Og({closeOnSelect:e=!0,lineClamp:t,children:n,onClick:r,onFeedback:o,onSourceClick:i,index:s,description:a,sources:l,styles:u,...c}){let{selected:p,setSelected:d,onChangeOpen:f}=_r(),y=P("CommandPalette",ot);function v(m){r(m),e&&f(!1)}return(0,pt.jsxs)("div",{className:(0,Sa.default)(y.listItem,p===s&&y.listItemSelected),children:[(0,pt.jsx)("button",{onMouseEnter:()=>d(s),type:"button",className:(0,Sa.default)("command-palette-list-item",y.listItemAction,y.listItemPrimaryAction),"aria-disabled":c.disabled??!1,onClick:v,...c,children:(0,pt.jsxs)("div",{className:y.listItemContent,children:[typeof n=="string"?(0,pt.jsx)("p",{className:(0,Sa.default)(y.listItemText,y.truncate,u==null?void 0:u.title),children:n}):n,a&&(0,pt.jsx)(Cn,{tagName:"p",allowList:[],content:uo(a)?K_(a):a,className:(0,Sa.default)(y.listItemDescription,u==null?void 0:u.description,t?y.lineClamp:y.truncate)})]})}),o&&p===s&&(0,pt.jsx)("div",{className:y.listItemActions,children:(0,pt.jsx)(Gc,{suggestion:String(n),onFeedback:o})}),l&&(0,pt.jsxs)("div",{className:y.sources,children:[(0,pt.jsx)("span",{className:y.sourcesTitle,children:"Sources"}),l.map(m=>m.url?(0,pt.jsx)("a",{className:y.source,href:m.url,target:"_blank",title:m.url,rel:"noopener noreferrer",onClick:()=>i&&i(m),children:m.name},m.url):(0,pt.jsx)("span",{className:y.source,children:m.name},m.name))]})]})}var mo=S(b());function Ng({children:e,title:t,id:n,onDismiss:r}){let o=H(co),i=P("CommandPalette",ot),{page:s}=_r();return s!==n?null:(0,mo.jsxs)("div",{className:i.page,id:`page_${n}`,tabIndex:-1,children:[r&&(0,mo.jsxs)("div",{className:i.pageNav,children:[(0,mo.jsxs)("button",{className:i.pageBackButton,type:"button",onClick:r,children:[(0,mo.jsx)(Ac,{}),o("back")]}),t&&(0,mo.jsx)("h3",{className:i.pageTitle,children:t})]}),e]})}var wr=S(O());var eR={info(...e){console.info("[Deepdesk]",...e)},warn(...e){console.warn("[Deepdesk]",...e)},error(...e){console.error("[Deepdesk]",...e)}},j=eR;function tR(e){return e.replace(/(_\w)/g,t=>t[1].toUpperCase())}function Z(e){return Array.isArray(e)?e.map(Z):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>({...t,[tR(n)]:Z(e[n])}),{}):e}function Mg(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function ke(e){return Array.isArray(e)?e.map(ke):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>({...t,[Mg(n)]:ke(e[n])}),{}):e}var nR={agentInfo:void 0,agentSettings:{},visitorInfo:void 0,fetchState:"idle"},_a=e=>{var t,n,r;return{timezone:((t=e.info.visitorInfo)==null?void 0:t.visitorTimeZone)||Intl.DateTimeFormat().resolvedOptions().timeZone,agentName:((n=e.info.agentInfo)==null?void 0:n.agentNickname)||"",visitorName:((r=e.info.visitorInfo)==null?void 0:r.visitorName)||""}},xa=D("info/setAgentInfo",async(e,t)=>{let{deepdeskAPI:n}=t.extra;if(!e.agentId&&!e.agentNickname)throw new Error("At least provide agentId or agentNickname");let r=await n.client.get("/apis/admin/session/me/",{version:null}),o={};return r.external_id||(o.external_id=e.agentId),r.nickname||(o.nickname=e.agentNickname),!o.external_id&&!o.nickname?Z(r):(await n.client.patch("/apis/admin/session/me/",o,{version:null}),Z(r))}),Dg=D("info/setAgentSettings",async(e,t)=>{let{deepdeskAPI:n}=t.extra,r=await n.client.get("/apis/admin/session/me/",{version:null}),o={...typeof r.ui_config=="object"?r.ui_config:{},...e};return await n.client.patch("/apis/admin/session/me/",{ui_config:o}),o}),Fg=D("info/getAgentSettings",async(e,t)=>{let{deepdeskAPI:n}=t.extra;return(await n.client.get("/apis/admin/session/me/",{version:null})).ui_config}),nw=e=>e.info.agentInfo,rw=z({name:"info",initialState:nR,reducers:{setVisitorInfo(e,t){e.visitorInfo={...e.visitorInfo,...t.payload}}},extraReducers:e=>{e.addCase(xa.pending,(t,n)=>{t.fetchState="loading",t.agentInfo={...t.agentInfo,...n.meta.arg}}).addCase(xa.rejected,t=>{t.fetchState="error"}).addCase(xa.fulfilled,(t,n)=>{t.fetchState="done",t.agentInfo={...t.agentInfo,...n.meta.arg,agentId:n.payload.externalId||n.meta.arg.agentId||"",agentNickname:n.payload.nickname||n.meta.arg.agentNickname||""}}).addCase(Dg.fulfilled,(t,n)=>{t.agentSettings=n.payload}).addCase(Fg.fulfilled,(t,n)=>{t.agentSettings=n.payload}).addCase(te,t=>{t.visitorInfo=void 0})}}),{setVisitorInfo:ow}=rw.actions,iw=rw.reducer;var Qc={list:[],fetchState:"idle",isOpen:!1,page:"search"},sw=e=>e.search.isOpen,aw=e=>e.search.page,lw=e=>e.search.list;function uw(e,t=n=>n){return n=>n.search.list.filter(r=>r.type===e).map(t)}var go=D("search/getAll",async(e,t)=>{var s;let{deepdeskAPI:n}=t.extra,r=t.getState(),o=(s=r.conversation.current)==null?void 0:s.profileCode;if(!o)throw new Error("Profile should be provided in order to be able to search");let{results:i}=await n.search({profile:o,query:e.query,filters:{type:e.type},params:_a(r),tags:e.tags});return i.map(a=>({...a,source:`search-${a.type.toLowerCase()}`,searchTerm:e.query}))}),cw=z({name:"search",initialState:Qc,reducers:{setIsOpen(e,t){e.isOpen=t.payload},setPage(e,t){e.page=t.payload},resetSearch(e){e.fetchState=Qc.fetchState,e.list=Qc.list}},extraReducers:e=>{e.addCase(go.pending,t=>{t.fetchState="loading"}).addCase(go.rejected,(t,n)=>{t.fetchState="error",j.error(n.error)}).addCase(go.fulfilled,(t,n)=>{t.fetchState="done",t.list=n.payload}).addCase(te,()=>Qc)}}),{resetSearch:Yc,setIsOpen:$e,setPage:qe}=cw.actions,dw=cw.reducer;var rR=/(https?:\/\/[^\s]+)/,Zc=e=>e.split(" ").find(t=>rR.test(t));var Jc=()=>/Mac/i.test(navigator.platform);var jg=S(q());var ed=S(b()),oR=({onClick:e,shortKeys:t,children:n,...r})=>{let o=P("CommandPalette",ot);return(0,ed.jsxs)("button",{type:"button",...r,onClick:e,className:(0,jg.default)(o.actionButton,r.className,{[o.hasShortKeys]:t&&t.length>0}),children:[n,t&&t.map(i=>(0,ed.jsx)("span",{className:(0,jg.default)(o.actionShortcut,i===8629&&o.actionShortcutFixKerning),children:typeof i=="number"?String.fromCharCode(i):i},i))]})},Ii=oR;var In=S(b()),iR=["url","URL"],sR=["default","pinned-message","DEFAULT","STICKYMESSAGE"],aR=({children:e,primaryLabel:t,secondaryLabel:n,onPrimary:r,onSecondary:o,list:i})=>{let s=P("CommandPalette",ot),a=H(co),{selected:l,setSelected:u}=_r(),c=i[l],p=c&&c.type&&iR.includes(c.type),d=c&&c.type&&sR.includes(c.type)||c&&"secondaryAction"in c,f=p?Zc(c.text):null,y=(0,wr.useRef)(null);function v(w){if(!y.current)return;let E=y.current.querySelectorAll(".command-palette-list-item"),C=0,I=0;w==="down"?(E.forEach((K,N)=>{N===l&&(C=N)}),I=C===E.length-1?0:C+1):w==="up"?(E.forEach((K,N)=>{N===l&&(C=N)}),I=C?C-1:E.length-1):u(0);let k=E[I];k&&typeof I=="number"&&(u(I),k.scrollIntoView&&k.scrollIntoView({behavior:"smooth",block:I?"center":"end"}))}function m(){if(!y.current)return;let w=y.current.querySelectorAll(".command-palette-list-item"),E=0;w.forEach((I,k)=>{k===l&&(E=k)});let C=w[E];C&&C.click()}let h=()=>{f&&window.open(f,"_blank")},g=()=>{c&&r(c,l)},x=()=>{!o||!d||o(c,l)},_=(0,wr.useCallback)(w=>{if(w.key==="Enter"&&w.altKey&&f){h();return}if(w.key==="Enter"&&w.shiftKey){x();return}if(w.key==="ArrowDown"){w.preventDefault(),w.stopPropagation(),v("down");return}if(w.key==="ArrowUp"){w.preventDefault(),w.stopPropagation(),v("up");return}w.key==="Enter"&&l!==-1&&(w.preventDefault(),w.stopPropagation(),m())},[l]);return(0,wr.useEffect)(()=>(window.addEventListener("keyup",_),()=>{window.removeEventListener("keyup",_)}),[_]),(0,In.jsxs)("div",{className:s.actions,children:[(0,In.jsx)("div",{className:s.actionsWrapper,ref:y,children:e}),(0,In.jsxs)("div",{className:s.actionsBar,children:[f&&(0,In.jsx)(Ii,{onClick:h,shortKeys:[Jc()?8997:"ALT",8629],children:a("visitUrl")}),c&&(0,In.jsxs)(wr.Fragment,{children:[o&&d&&(0,In.jsx)(Ii,{onClick:x,shortKeys:[8679,8629],children:n}),(0,In.jsx)(Ii,{onClick:g,shortKeys:[8629],children:t})]})]})]})},fw=aR;var mw=S(O());var wa=S(b()),Ri=()=>(0,wa.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 0 24 24",width:"1em",fill:"currentColor",children:[(0,wa.jsx)("path",{d:"M0 0h24v24H0z",fill:"none"}),(0,wa.jsx)("path",{d:"M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"})]});var Kt=S(b());function lR({onChange:e,onChangeType:t,placeholder:n,typePlaceholder:r,types:o,value:i,selectedType:s},a){let l=P("CommandPalette",ot);return(0,Kt.jsxs)("div",{className:l.search,children:[(0,Kt.jsx)("div",{className:l.searchIcon,children:(0,Kt.jsx)(Ri,{})}),(0,Kt.jsxs)("div",{className:l.searchInputWrapper,children:[(0,Kt.jsx)("input",{ref:a,spellCheck:!1,autoComplete:"off",onChange:u=>{e(u.currentTarget.value)},onFocus:u=>{u.currentTarget.select()},className:l.searchInput,placeholder:n,value:i,type:"text",id:"command-palette-search-input",autoFocus:!0}),o&&o.length>0&&(0,Kt.jsx)("div",{className:l.selectWrapper,children:(0,Kt.jsxs)("select",{"data-testid":"command-palette-type-select",className:l.select,onChange:u=>t(u.target.value===r?void 0:u.target.value),value:s||r,children:[r&&(0,Kt.jsx)("option",{children:r}),o.map(u=>(0,Kt.jsx)("option",{value:u.value,children:u.label},u.value))]})})]})]})}var gw=(0,mw.forwardRef)(lR);var ba=S(b());function ho({placeholder:e="Start typing to search...",typePlaceholder:t="All types",defaultPage:n="search",page:r,onChangePage:o,onChangeSearch:i,onChangeType:s,onChangeOpen:a,selectedType:l,types:u,children:c,isOpen:p,search:d}){let[f,y]=(0,Li.useState)(0),v=(0,Li.useRef)(null),m=()=>{o&&o(n),s(void 0),i(""),a(!1)},h=()=>{var g;if(r!==n&&o){o(n);return}if(l&&s){s(void 0),(g=v.current)==null||g.focus();return}if(d.length>0){i("");return}a(!1)};return(0,Li.useEffect)(()=>{y(0)},[d,r]),(0,ba.jsx)(wi,{autoFocus:!0,contentAriaLabel:"Search Results",overlayAriaLabel:"Command Palette",isOpen:p,onBack:h,onClose:m,children:(0,ba.jsxs)(ew,{selected:f,setSelected:y,isOpen:p,onChangeOpen:a,page:r,children:[r===n&&(0,ba.jsx)(gw,{ref:v,onChange:i,onChangeType:s,placeholder:e,value:d,selectedType:l,types:u,typePlaceholder:t}),c]})})}ho.Page=Ng;ho.List=Ig;ho.Image=$_;ho.ListItem=Og;ho.ActionsBar=fw;ho.Button=Ii;var $=ho;var Ke=S(b()),uR=({suggestion:e,onUse:t,onDismiss:n,onTouched:r,onNext:o,onPrevious:i})=>{let s=e.text||e.url||e.message,a=P("EditSuggestionForm",u_),l=U(),u=H(ng),c=R(y=>y.overlayInput.text);(0,Hg.useEffect)(()=>{e&&(l(rt.actions.reset()),l(rt.actions.stageSuggestion({text:s,suggestion:e,eventMetrics:{inputType:"mouse"},replace:"until-selection-end"})),l(rt.actions.commitSuggestion()))},[e]);let p=y=>{y.preventDefault(),d(c)},d=y=>{l(gc(y)),t(y)},f=y=>v=>{c!==s?window.confirm(u("warning"))&&y(v):y(v)};return(0,Hg.useEffect)(()=>{r&&r(c!==s)},[r,e,c]),(0,Ke.jsxs)("div",{className:a.root,children:[(0,Ke.jsxs)("div",{className:a.content,children:[e.title&&(0,Ke.jsx)("h3",{className:a.title,children:e.title}),e.searchKeywords&&e.searchKeywords.length>0&&(0,Ke.jsx)(Gd,{labels:e.searchKeywords}),(0,Ke.jsx)(V_,{onUse:d,value:U_(c)})]}),(0,Ke.jsxs)("form",{className:a.actions,onSubmit:p,children:[(0,Ke.jsxs)("div",{children:[(0,Ke.jsx)("button",{disabled:!i,className:a.pagination,type:"button",onClick:i&&f(i),children:(0,Ke.jsx)(Ac,{})}),(0,Ke.jsx)("button",{disabled:!o,className:a.pagination,type:"button",onClick:o&&f(o),children:(0,Ke.jsx)(S_,{})})]}),(0,Ke.jsxs)("div",{className:a.primaryButtons,children:[(0,Ke.jsx)($.Button,{onClick:f(n),shortKeys:["esc"],children:u("dismiss")}),(0,Ke.jsx)($.Button,{shortKeys:[8679,8629],type:"submit",children:u("add")})]})]})]})},td=uR;var cR=["{amount}"," {amount}","{date}","{email}","{iban}","{name}","{postal_code}","{street}","{tarif}","{usage}","{3_digits}","{4_digits}","{5_digits}","{6_digits}","{7_digits}","{8_digits}","{9_digits}","{10_digits}"],dR=new RegExp(cR.map(e=>`(?:${e.replace("{","\\{").replace("}","\\}")})`).join("|"));function hw(e,t){let n=e.split(dR),r=0,o=[];for(let i=0;i<n.length;i++){let s=n[i];if(o.push(s),i===n.length-1)break;if(t.indexOf(s)===-1)return e;let a=n[i+1],l=i===n.length-2;r+=s.length;let u=r;if(l){let p=a.charAt(0),d=0;do u=p?t.indexOf(p,u+1):-1,d+=1;while(u!==-1&&a.indexOf(t.slice(u))!==0);if(u===-1&&d>2)return e}else u=a&&a!==""?t.indexOf(a,r):-1;let c=u===-1?t.slice(r):t.slice(r,u);o.push(c),r=u}return o.join("")}function yw(e,t){return typeof t=="boolean"?e:e.slice(0,t)}var Sw={suggestions:[],fetchState:"idle",isInitialRequest:null},vw={default:Sw},nd=e=>t=>{var n;return((n=t.textSuggestions[e])==null?void 0:n.suggestions)??[]},xw=e=>{let t=Object.keys(e.textSuggestions).map(n=>{var r;return(r=e.textSuggestions[n])==null?void 0:r.fetchState});return t.length===0?!0:t.every(n=>n!=="done")},br=e=>e.textSuggestions,_w=e=>{let t=e.toLowerCase();return n=>{let r=n.text.toLowerCase();return r.startsWith(t)&&r.length>t.length}},rd=fe("textSuggestions/refresh"),Vt=D("textSuggestions/recommendations",async(e,t)=>{var u;let{deepdeskAPI:n}=t.extra,r=t.getState(),o=(u=r.conversation.current)==null?void 0:u.id,{textSuggestionsCount:i,inlineSuggestions:s}=r.settings,a=xi(r);if(!o)throw new Error("No current conversation to fetch text suggestions");let l=await n.getTextSuggestions(o,_a(r),e);if(e==="default"){let c=s?l.filter(_w(a)):l;t.dispatch(on(c.slice(0,i)))}return l}),Ea=D("textSuggestions/autocompletions",async(e,t)=>{var u;let{deepdeskAPI:n}=t.extra,r=t.getState(),o=(u=r.conversation.current)==null?void 0:u.id,{textSuggestionsCount:i,deanonymize:s,inlineSuggestions:a}=r.settings;if(!o)throw new Error("No current conversation to fetch text suggestions");let l=await n.getAutocompleteSuggestions(o,{..._a(r),input:e});if(!t.getState().input.text)throw new Error("Abort");return a&&(l=l.filter(_w(e))),s&&(l=l.map(c=>({...c,text:c.source!=="trie-with-typos"?hw(c.text,e):c.text}))),l=yw(l,i),t.dispatch(on(l)),l}),ww=z({name:"textSuggestions",initialState:vw,reducers:{setTextSuggestions:{reducer(e,t){let{contentType:n}=t.payload;e[n].fetchState="done",e[n].suggestions=t.payload.suggestions},prepare(e,t){return{payload:{contentType:e,suggestions:t}}}},setSuggestionState(e,t){return t.payload}},extraReducers:e=>{e.addCase(Vt.pending,(t,n)=>{let r=n.meta.arg,o=t[r]||Sw;return{...t,[r]:{...o,fetchState:"loading",isInitialRequest:o.isInitialRequest===null}}}).addCase(Vt.rejected,(t,n)=>{let r=n.meta.arg;t[r]&&(t[r].fetchState="error")}).addCase(Vt.fulfilled,(t,n)=>{let r=n.meta.arg;t[r]&&(t[r].fetchState="done",t[r].suggestions=n.payload)}).addCase(Ea.pending,t=>{t.default.fetchState="loading"}).addCase(Ea.rejected,t=>{t.default.fetchState="error"}).addCase(Ea.fulfilled,(t,n)=>{t.default.fetchState="done",t.default.suggestions=n.payload}).addCase(te,()=>vw)}}),{setTextSuggestions:bw,setSuggestionState:Ew}=ww.actions,Cw=ww.reducer;var Tw={contentType:null,suggestion:null},kw=e=>e.activeSuggestion.suggestion,Pw=e=>e.activeSuggestion.contentType,Iw=z({name:"activeSuggestion",initialState:Tw,reducers:{setActiveSuggestion(e,t){let{contentType:n,suggestion:r}=t.payload;e.contentType=n,e.suggestion=r},resetActiveSuggestion(e){e.contentType=null,e.suggestion=null}},extraReducers:e=>{e.addCase(te,()=>Tw)}}),{setActiveSuggestion:Rn,resetActiveSuggestion:Bg}=Iw.actions,Rw=Iw.reducer;var zg={};Pe(zg,{enUS:()=>pR,nlNL:()=>fR});var pR={warning:[{type:0,value:"Are you sure you want to discard the message?"}],editContentLabel:[{type:0,value:"Edit and view suggestion"}],overlayLabel:[{type:0,value:"Close dialog"}]},fR={warning:[{type:0,value:"Weet je zeker dat je de wijzigingen wilt weggooien?"}],editContentLabel:[{type:0,value:"Bewerk en bekijk suggestie"}],overlayLabel:[{type:0,value:"Sluit"}]};var mR={showTabHint:!1,inputHasFocus:!1,overlayCollapsed:!1,openOverlayWhenTyping:!1,overlayCollapsedUserOverwrite:!1};var od=({ui:e})=>e.overlayCollapsed;var Lw=z({name:"ui",initialState:mR,reducers:{setShowTabHint(e,t){e.showTabHint=t.payload},setInputHasFocus(e,t){e.overlayCollapsedUserOverwrite!==!0&&(t.payload===!0&&(e.overlayCollapsed=!1),e.inputHasFocus=t.payload)},setOverlayCollapsed(e,t){t.payload.collapse===!1&&(e.openOverlayWhenTyping=!1),!(t.payload.skipWhenInputFocus&&e.inputHasFocus)&&(e.overlayCollapsed=t.payload.collapse)},setOpenOverlayWhenTyping(e,t){e.openOverlayWhenTyping=t.payload},setOverlayCollapsedUserOverwrite(e,t){e.overlayCollapsedUserOverwrite=t.payload,e.overlayCollapsed=t.payload}}}),{setShowTabHint:Ca,setInputHasFocus:Ai,setOverlayCollapsed:Er,setOpenOverlayWhenTyping:Aw,setOverlayCollapsedUserOverwrite:Ow}=Lw.actions,Nw=Lw.reducer;var Ta=S(O()),Dw=S(b()),Mw=Ta.default.createContext(null),yo=({broadcastEvents:e,children:t})=>{let n=Ta.default.useMemo(()=>e,[]);return(0,Dw.jsx)(Mw.Provider,{value:n,children:t})},Lt=()=>{let e=(0,Ta.useContext)(Mw);if(!e)throw new Error("You should use the useBroadcastEvents within a BroadcastEventsProvider");return e};var gR={isLoggedIn:!0,loginFetchState:"idle",verifyFetchState:"idle",showLoginOverlay:!1},Ge=e=>e.auth.isLoggedIn,Fw=e=>e.auth.loginFetchState,jw=e=>e.auth.verifyFetchState,Hw=e=>e.auth.showLoginOverlay,Ln=D("auth/validate",async(e,t)=>t.extra.deepdeskAPI.isLoggedIn()),Bw=D("auth/requestLogin",async({email:e},t)=>{let{deepdeskAPI:n}=t.extra;return n.requestLoginByEmail(e)}),ka=D("auth/verifyLoginToken",async({token:e},t)=>{let{deepdeskAPI:n}=t.extra;return n.verifyLoginToken(e)}),zw=z({name:"auth",initialState:gR,reducers:{setIsLoggedIn(e,t){e.isLoggedIn=t.payload},setShowLoginOverlay(e,t){e.showLoginOverlay=t.payload}},extraReducers:e=>{e.addCase(Ln.pending,t=>{t.loginFetchState="loading"}),e.addCase(Ln.fulfilled,(t,{payload:n})=>{t.isLoggedIn=n,t.loginFetchState="done"}),e.addCase(Ln.rejected,t=>{t.loginFetchState="error",t.isLoggedIn=!1}),e.addCase(ka.pending,t=>{t.verifyFetchState="loading"}),e.addCase(ka.rejected,t=>{t.verifyFetchState="error"}),e.addCase(ka.fulfilled,(t,n)=>{n.payload.isLoggedIn?t.verifyFetchState="done":t.verifyFetchState="error"})}}),{setIsLoggedIn:Oi,setShowLoginOverlay:Uw}=zw.actions,Kw=zw.reducer;var Ug="SetActiveSuggestion",Ni="ShowLoginOverlay",Pa="UserLoggedIn",hR="UserLoggedOut",An="ApplySuggestion",Kg="ApplyImageSuggestion",yR="ShowCommandPalette",vR=e=>({[Ug]:t=>{e.dispatch(Ew(t.state)),e.dispatch(Rn({contentType:t.contentType,suggestion:t.suggestion}))},[yR]:t=>{e.dispatch($e(t.isOpen)),t.page&&e.dispatch(qe(t.page))},[Ni]:t=>{e.dispatch(Uw(t))},[Pa]:()=>{e.dispatch(Ln())},[hR]:()=>{e.dispatch(Ln())},[Kg]:t=>{e.dispatch(yc({suggestion:t.suggestion}))},[An]:t=>{e.dispatch(Bt({...t,eventMetrics:{inputType:"mouse"},replace:"selection"})),e.dispatch(wn())}}),Vw=vR;var Vg=S(b()),SR=()=>{var y;let[e,t]=(0,Ww.useState)(!1),n=R(kw),r=R(Pw),o=R(br),i=U(),s=Lt(),a=H(zg),l=()=>{n!==null&&e?window.confirm(a("warning"))&&u():u()},u=()=>{i(Bg()),i(Ai(!0)),i(rt.actions.reset())},c=(v,m)=>{i(Bg()),i(Ai(!0)),s.send(An,{text:v,suggestion:{...m,source:`${m.source||"text_recommendation"}-preview`}})};if(n===null||r===null)return null;let p=(y=o[r])==null?void 0:y.suggestions.indexOf(n),d=p===0||p===null?void 0:()=>i(Rn({contentType:r,suggestion:o[r].suggestions[p-1]})),f=p===o[r].suggestions.length-1||p===null?void 0:()=>i(Rn({contentType:r,suggestion:o[r].suggestions[p+1]}));return(0,Vg.jsx)(wi,{autoFocus:!0,isOpen:p!==null,onClose:l,onBack:l,contentAriaLabel:a("editContentLabel"),overlayAriaLabel:a("overlayLabel"),children:(0,Vg.jsx)(td,{onTouched:t,onDismiss:u,onUse:v=>c(v,n),suggestion:n,onNext:f,onPrevious:d})})},$w=SR;var id=S(q()),Wt=S(O());var Gw=S(q());var qw={root:"_root_1ukx5_1"};var Xw=S(b()),xR=({className:e,value:t,...n})=>{let r=P("TextInput",qw);return(0,Xw.jsx)("input",{className:(0,Gw.default)(e,r.root),type:"text",value:t,...n})},Ia=xR;var Wg={};Pe(Wg,{enUS:()=>_R,nlNL:()=>wR});var _R={back:[{type:0,value:"Back"}],promptTitle:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],verifyCodeTitle:[{type:0,value:"Paste the code from your email"}],verifyCodeBody:[{type:0,value:"Copy the code from the email you just received and paste it here."}],verifyCodeInputPlaceholder:[{type:0,value:"Paste link or code here"}],verifyCodeSubmitLabel:[{type:0,value:"Sign in"}],verifyCodeError:[{type:0,value:"Sign in failed. The code is probably no longer valid. Please "},{type:8,value:"login",children:[{type:0,value:"request new code"}]},{type:0,value:"."}],requestCodeTitle:[{type:0,value:"Have a code sent to your email"}],requestCodeBody:[{type:0,value:"Enter your email and request a code. If you are an existing "},{type:1,value:"productName"},{type:0,value:" user you will receive an email with a code. If you are a new user you will receive an email asking to request access to "},{type:1,value:"productName"},{type:0,value:" first."}],requestCodeInputPlaceholder:[{type:0,value:"Enter your email"}],requestCodeSubmitLabel:[{type:0,value:"Request code"}]},wR={back:[{type:0,value:"Terug"}],promptTitle:[{type:0,value:"Login bij "},{type:1,value:"productName"}],verifyCodeTitle:[{type:0,value:"Plak de code uit je email"}],verifyCodeBody:[{type:0,value:"Kopieer de code uit de email en plak deze hier."}],verifyCodeInputPlaceholder:[{type:0,value:"Plak hier de code"}],verifyCodeSubmitLabel:[{type:0,value:"Inloggen"}],verifyCodeError:[{type:0,value:"Inloggen is niet gelukt. De code is waarschijnlijk niet meer geldig. "},{type:8,value:"login",children:[{type:0,value:"Vraag een nieuwe code aan"}]},{type:0,value:"."}],requestCodeTitle:[{type:0,value:"Verstuur een login code naar je email"}],requestCodeBody:[{type:0,value:"Voer je e-mailadres in en krijg een login code. Als je een bestaande "},{type:1,value:"productName"},{type:0,value:" gebruiker bent krijg je een email met een code. Als je een nieuwe gebruiker bent wordt er een email verstuurd met een toegangsverzoek voor "},{type:1,value:"productName"},{type:0,value:"."}],requestCodeInputPlaceholder:[{type:0,value:"Typ hier je e-mailadres"}],requestCodeSubmitLabel:[{type:0,value:"Code aanvragen"}]};var Qw={root:"_root_1edpl_1",anchorButton:"_anchorButton_1edpl_5",errorMessage:"_errorMessage_1edpl_19",title:"_title_1edpl_25",subtitle:"_subtitle_1edpl_31",text:"_text_1edpl_38",input:"_input_1edpl_43",actions:"_actions_1edpl_48",button:"_button_1edpl_55",primaryButton:"_primaryButton_1edpl_70"};var ye=S(b());var bR=e=>{try{let t=new URL(e);return new URLSearchParams(t.search).get("token")||void 0}catch{return e}},ER=({agentEmail:e,isOpen:t,origin:n="",onSuccess:r,onDismiss:o})=>{let i=H(Wg),s=P("LoginTokenDialog",Qw),a=R(jw),l=U(),u=M("productName"),[c,p]=(0,Wt.useState)(e||""),[d,f]=(0,Wt.useState)(0),[y,v]=(0,Wt.useState)(""),m=(0,Wt.useCallback)(async _=>{_.preventDefault(),l(Bw({email:c})),f(1)},[n,c]),h=()=>{v(""),f(0)},g=(0,Wt.useCallback)(async _=>{_.preventDefault();let w=bR(_.target.elements.token.value);if(!w){v(i("verifyCodeError",{login:x}));return}l(ka({token:w}))},[n]),x=(0,Wt.useMemo)(()=>_=>(0,ye.jsx)("button",{type:"button","data-testid":"login-token-dialog-back-button",className:s.anchorButton,onClick:h,children:_},"back-button"),[]);return(0,Wt.useEffect)(()=>{a==="error"&&v(i("verifyCodeError",{login:x})),a==="done"&&r()},[a]),(0,ye.jsx)(wi,{autoFocus:!0,isOpen:t,contentAriaLabel:i("promptTitle",{productName:u}),overlayAriaLabel:i("promptTitle",{productName:u}),onClose:o,onBack:o,children:(0,ye.jsxs)("div",{className:s.root,children:[(0,ye.jsx)("h1",{className:s.title,children:i("promptTitle",{productName:u})}),d===0&&(0,ye.jsxs)("form",{onSubmit:m,children:[(0,ye.jsx)("h2",{className:s.subtitle,children:i("requestCodeTitle")}),(0,ye.jsx)("p",{className:s.text,children:i("requestCodeBody",{productName:u})}),(0,ye.jsx)(Ia,{className:s.input,name:"email",placeholder:i("requestCodeInputPlaceholder"),value:c,onChange:_=>p(_.target.value)}),(0,ye.jsx)("div",{className:s.actions,children:(0,ye.jsx)("button",{type:"submit",className:(0,id.default)(s.button,s.primaryButton),children:i("requestCodeSubmitLabel")})})]}),d===1&&(0,ye.jsxs)("form",{onSubmit:g,children:[(0,ye.jsx)("h2",{className:s.subtitle,children:i("verifyCodeTitle")}),(0,ye.jsx)("p",{className:s.text,children:i("verifyCodeBody")}),(0,ye.jsx)(Ia,{className:s.input,name:"token",placeholder:i("verifyCodeInputPlaceholder"),disabled:["loading","done"].includes(a)}),y&&(0,ye.jsx)("div",{className:s.errorMessage,children:y}),(0,ye.jsxs)("div",{className:s.actions,children:[(0,ye.jsx)("button",{type:"button",className:(0,id.default)(s.button),onClick:h,children:i("back")}),(0,ye.jsx)("button",{type:"submit",className:(0,id.default)(s.button,s.primaryButton),disabled:["loading","done"].includes(a),children:i("verifyCodeSubmitLabel")})]})]})]})})},Yw=ER;var Jw=S(b()),CR=()=>{let e=R(Hw),t=R(nw),n=M("adminUrl"),r=Lt(),o=()=>r.send(Ni,!1),i=()=>{r.send(Ni,!1),r.send(Pa)};return(0,Jw.jsx)(Yw,{isOpen:e,agentEmail:t==null?void 0:t.agentEmail,origin:n,onDismiss:o,onSuccess:i})},Zw=CR;var I1=S(Gg()),Xe=S(O());var KR={data:null,fetchState:"idle"},r1=e=>e.contentTypes.data,Ra=D("contentTypes/getContentTypes",async(e,t)=>t.extra.deepdeskAPI.getContentTypes()),VR=z({name:"contentTypes",initialState:KR,reducers:{},extraReducers:e=>{e.addCase(Ra.pending,t=>{t.fetchState="loading"}).addCase(Ra.rejected,t=>{t.fetchState="error"}).addCase(Ra.fulfilled,(t,n)=>{t.fetchState="done",t.data=n.payload})}}),o1=VR.reducer;function La(e){let t=document.createElement("textarea");t.value=e,t.style.position="fixed",t.style.left="-999999px",t.style.top="-999999px",document.body.appendChild(t),t.focus(),t.select(),document.execCommand("copy"),t.remove()}var i1=S(O());function s1(e,t){(0,i1.useEffect)(()=>{let n=r=>{var o;((o=navigator==null?void 0:navigator.platform)!=null&&o.toLowerCase().includes("mac")?r.metaKey:r.ctrlKey)&&r.key===e&&(r.preventDefault(),r.stopPropagation(),t())};return document.addEventListener("keydown",n),()=>{document.removeEventListener("keydown",n)}},[])}var Aa=S(O());var a1={data:null,fetchState:"idle"},sd=e=>{var i;let t=[],{visitorName:n}=e.info.visitorInfo??{},{agentName:r,agentNickname:o}=e.info.agentInfo??{};return r&&r!==n&&t.push(r),o&&o!==n&&t.push(o),((i=e.entities.data)==null?void 0:i.filter(s=>!t.includes(s.text)))??null},$t=D("entities/getEntities",async(e,t)=>{let{deepdeskAPI:n,dynamicThunkObject:r}=t.extra;if(!r.conversationQuery)return Promise.resolve([]);let o=r.conversationQuery,i=await o();return i.length===0?Promise.resolve([]):n.getEntities(i)}),WR=e=>e.filter((t,n)=>n===e.findIndex(r=>r.text===t.text)),$R=z({name:"entities",initialState:a1,reducers:{},extraReducers:e=>{e.addCase($t.pending,t=>{t.fetchState="loading"}).addCase($t.rejected,t=>{t.fetchState="error"}).addCase($t.fulfilled,(t,n)=>{t.fetchState="done",t.data=WR(t.data?[...t.data,...n.payload]:n.payload)}).addCase(te,()=>a1)}}),l1=$R.reducer;var Xg={};Pe(Xg,{enUS:()=>qR,nlNL:()=>GR});var qR={noResults:[{type:0,value:"No entities have been found"}],copy:[{type:0,value:"Copy"}],use:[{type:0,value:"Use"}]},GR={noResults:[{type:0,value:"Er zijn geen entiteiten gevonden"}],copy:[{type:0,value:"Kopieer"}],use:[{type:0,value:"Gebruik"}]};var u1={root:"_root_17kae_1",empty:"_empty_17kae_5"};var vo=S(b()),XR=({onCopy:e,onUse:t})=>{let n=(0,Aa.useRef)(null),r=P("EntitiesList",u1),o=H(Xg),i=R(sd),s=U();return(0,Aa.useEffect)(()=>{s($t())},[]),(0,Aa.useEffect)(()=>{n.current&&n.current.focus()},[n]),(0,vo.jsxs)("div",{className:r.root,ref:n,tabIndex:-1,children:[i&&i.length>0&&(0,vo.jsx)($.ActionsBar,{primaryLabel:o("copy"),secondaryLabel:o("use"),onPrimary:(a,l)=>e(i[l]),onSecondary:(a,l)=>t(i[l]),list:i.map(a=>({text:a.text,type:a.label,primaryAction:"copy",secondaryAction:"use"})),children:(0,vo.jsx)($.List,{children:i.map((a,l)=>(0,vo.jsx)($.ListItem,{index:l,closeOnSelect:!0,onClick:()=>e(a),children:a.text},a.text))},"entities")}),i&&i.length===0&&(0,vo.jsx)("p",{className:r.empty,children:o("noResults")})]})},c1=XR;var qt=S(O());var d1={data:null,fetchState:"idle"},p1=e=>e.summary.data,f1=e=>e.summary.fetchState==="error",On=D("summary/getSummary",async(e,t)=>{var c,p,d;let n=t.getState().profile.data,r=(c=t.getState().conversation.current)==null?void 0:c.id,o=(d=(p=t.getState().info)==null?void 0:p.agentInfo)==null?void 0:d.agentId;if(!n)throw new Error("Profile is not defined");let{deepdeskAPI:i,dynamicThunkObject:s}=t.extra;if(!s.conversationQuery)return Promise.reject(new Error("setConversationQuery method is not defined"));let a=s.conversationQuery,l=await a();if(l.length===0)return Promise.reject(new Error("No messages are included"));let u=await i.getSummary(l,{externalConversationId:r,agentId:o,promptInstruction:n.summarizerPromptInstruction,model:n.summarizerModel});return u?{summary:u}:Promise.reject(new Error("Summary is not provided"))}),QR=z({name:"summary",initialState:d1,reducers:{},extraReducers:e=>{e.addCase(On.pending,t=>{t.data=null,t.fetchState="loading"}).addCase(On.rejected,t=>{t.data=null,t.fetchState="error"}).addCase(On.fulfilled,(t,n)=>{t.fetchState="done",n.payload&&(t.data=n.payload.summary)}).addCase(te,()=>d1)}}),m1=QR.reducer;var Qg={};Pe(Qg,{enUS:()=>YR,nlNL:()=>ZR});var YR={copy:[{type:0,value:"Copy"}],error:[{type:0,value:"Could not generate a summary"}],loading:[{type:0,value:"Generating summary, this may take a few moments."}]},ZR={copy:[{type:0,value:"Kopieer"}],error:[{type:0,value:"Kon helaas geen samenvatting genereren."}],loading:[{type:0,value:"Samenvatting wordt gemaakt, dit kan even duren."}]};var g1={root:"_root_6ahh3_1",actions:"_actions_6ahh3_5",main:"_main_6ahh3_11",textInput:"_textInput_6ahh3_15",loading:"_loading_6ahh3_34",error:"_error_6ahh3_38"};var Nn=S(b()),JR=({onCopy:e})=>{let t=(0,qt.useRef)(null),n=P("SummaryForm",g1),[r,o]=(0,qt.useState)(""),i=H(Qg),s=R(p1),a=R(f1),l=U(),u=()=>{l(Be({name:"summary copied to clipboard",data:{originalText:s,finalText:r},options:{includeConversationData:!0}})),e(r)},c=()=>{let p=document.getSelection();p&&l(Be({name:"summary copied to clipboard",data:{originalText:s,finalText:p==null?void 0:p.toString()},options:{includeConversationData:!0}}))};return(0,qt.useEffect)(()=>{l(On())},[]),(0,qt.useEffect)(()=>{o(s||"")},[s]),(0,qt.useEffect)(()=>{t.current&&s&&t.current.focus()},[t,s]),(0,qt.useEffect)(()=>{let p=d=>{d.key==="Enter"&&d.shiftKey&&u()};return document.addEventListener("keydown",p),()=>{document.removeEventListener("keydown",p)}},[r]),(0,Nn.jsx)("div",{className:n.root,tabIndex:-1,children:a?(0,Nn.jsx)("p",{className:n.error,children:i("error")}):(0,Nn.jsxs)(qt.Fragment,{children:[(0,Nn.jsx)("div",{className:n.main,children:(0,Nn.jsx)("textarea",{placeholder:s?void 0:i("loading"),disabled:!s,className:n.textInput,ref:t,value:r,onCopy:c,onChange:p=>o(p.target.value)})}),(0,Nn.jsx)("div",{className:n.actions,children:(0,Nn.jsx)($.Button,{shortKeys:[8679,8629],onClick:u,children:i("copy")})})]})})},h1=JR;var Oa={};Pe(Oa,{enUS:()=>eL,nlNL:()=>tL});var eL={personalCollectionLink:[{type:0,value:"Go to Personal Collection"}],searchPlaceholder:[{type:0,value:"Start typing to search..."}],urlSuggestions:[{type:0,value:"Link suggestions"}],personalSuggestions:[{type:0,value:"Personal suggestions"}],pinnedMessages:[{type:0,value:"Pinned messages"}],imageSuggestions:[{type:0,value:"Images"}],typePlaceholder:[{type:0,value:"All types"}],navigation:[{type:0,value:"Navigation"}],entitiesClipboard:[{type:0,value:"Conversation clipper"}],entitiesTitle:[{type:0,value:"Copy to your clipboard"}],summaryClipboard:[{type:0,value:"Summarize conversation"}],summaryTitle:[{type:0,value:"Conversation summary"}],knowledgeAssist:[{type:0,value:"Knowledge assist"}],commands:[{type:0,value:"Commands"}],use:[{type:0,value:"Use"}],preview:[{type:0,value:"Preview"}],warning:[{type:0,value:"Are you sure you want to discard the message?"}]},tL={personalCollectionLink:[{type:0,value:"Ga naar persoonlijke collectie"}],searchPlaceholder:[{type:0,value:"Begin met typen om te zoeken..."}],personalSuggestions:[{type:0,value:"Persoonlijke suggesties"}],urlSuggestions:[{type:0,value:"Link suggesties"}],imageSuggestions:[{type:0,value:"Afbeeldingen"}],navigation:[{type:0,value:"Navigatie"}],typePlaceholder:[{type:0,value:"Alle types"}],pinnedMessages:[{type:0,value:"Actueel"}],entitiesClipboard:[{type:0,value:"Klembord"}],entitiesTitle:[{type:0,value:"Kopieer naar klembord"}],summaryClipboard:[{type:0,value:"Gesprek samenvatten"}],summaryTitle:[{type:0,value:"Gesprek samenvatting"}],knowledgeAssist:[{type:0,value:"Knowledge assist"}],commands:[{type:0,value:"Acties"}],use:[{type:0,value:"Gebruik"}],preview:[{type:0,value:"Bewerk"}],warning:[{type:0,value:"Weet je zeker dat je de wijzigingen wilt weggooien?"}]};var Cr=S(O());var Yg={};Pe(Yg,{enUS:()=>nL,nlNL:()=>rL});var nL={use:[{type:0,value:"Use"}],loading:[{type:0,value:"Loading..."}],error:[{type:0,value:"Something went wrong, please try again later."}],anotherQuestion:[{type:0,value:"Send a message..."}],reset:[{type:0,value:"Reset conversation"}]},rL={use:[{type:0,value:"Gebruik"}],loading:[{type:0,value:"Laden..."}],error:[{type:0,value:"Er ging iets mis, probeer het later opnieuw."}],anotherQuestion:[{type:0,value:"Stuur een bericht..."}],reset:[{type:0,value:"Reset gesprek"}]};var y1={root:"_root_1g4pq_1",title:"_title_1g4pq_9",empty:"_empty_1g4pq_20",status:"_status_1g4pq_24",form:"_form_1g4pq_30",input:"_input_1g4pq_43",submit:"_submit_1g4pq_55",question:"_question_1g4pq_63",answer:"_answer_1g4pq_67",alignRight:"_alignRight_1g4pq_73"};var oL={data:null,fetchState:"idle"},v1=e=>{var t;return(t=e.knowledgeAssistant)==null?void 0:t.data},Na=D("knowledgeAssistant/getKnoeledgeAssistant",async(e,t)=>{var s;let{deepdeskAPI:n}=t.extra,r=t.getState(),o=r.conversation.current;if(!o||!o.profileCode)throw new Error("No conversation of conversation profileCode found");let i=(s=r.profile.data)==null?void 0:s.knowledgeAssistant;return i?n.getKnowledgeAssistant(i):null}),iL=z({name:"knowledgeAssistant",initialState:oL,reducers:{},extraReducers:e=>{e.addCase(Na.pending,t=>{t.fetchState="loading"}).addCase(Na.rejected,t=>{t.fetchState="error"}).addCase(Na.fulfilled,(t,n)=>{t.fetchState="done",t.data=n.payload})}}),S1=iL.reducer;var Zg={data:[],fetchState:"idle"},x1=e=>{var t;return(t=e.answer)==null?void 0:t.data},_1=e=>e.answer.fetchState,Di=fe("answer/resetKnowledgeSearch"),Mi=D("answer/getAnswer",async(e,t)=>{let{deepdeskAPI:n}=t.extra,r=t.getState().answer.data,o=v1(t.getState());if(!o)throw new Error("KnowledgeAssistant is not defined");let i=await n.knowledgeAssist({promptInstruction:o.prompt,question:e},r,o.code);return{question:e,answer:i}}),sL=z({name:"answer",initialState:Zg,reducers:{},extraReducers:e=>{e.addCase(Mi.pending,t=>{t.fetchState="loading"}).addCase(Mi.rejected,t=>{t.fetchState="error"}).addCase(Mi.fulfilled,(t,n)=>{t.fetchState="done",t.data=[...t.data,n.payload]}).addCase(te,()=>Zg).addCase(Di,()=>Zg)}}),w1=sL.reducer;var Ma=S(b()),b1=()=>(0,Ma.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 512 512","aria-labelledby":"paperPlaneTitle",children:[(0,Ma.jsx)("title",{id:"paperPlaneTitle",children:"PaperPlane"}),(0,Ma.jsx)("path",{d:"M498.1 5.6c10.1 7 15.4 19.1 13.5 31.2l-64 416c-1.5 9.7-7.4 18.2-16 23s-18.9 5.4-28 1.6L284 427.7l-68.5 74.1c-8.9 9.7-22.9 12.9-35.2 8.1S160 493.2 160 480V396.4c0-4 1.5-7.8 4.2-10.7L331.8 202.8c5.8-6.3 5.6-16-.4-22s-15.7-6.4-22-.7L106 360.8 17.7 316.6C7.1 311.3 .3 300.7 0 288.9s5.9-22.8 16.1-28.7l448-256c10.7-6.1 23.9-5.5 34 1.4z"})]});var it=S(b()),aL=({onUse:e,onResetQuestion:t,question:n})=>{let[r,o]=Cr.default.useState(""),{setSelected:i}=_r(),s=(0,Cr.useRef)(null),a=P("EntitiesList",y1),l=H(Yg),u=U(),c=R(x1),p=R(_1),d=async y=>{y.preventDefault(),y.stopPropagation(),r!==""&&u(Mi(r))},f=(y,v)=>{u(Be({name:"knowledge assist source viewed",data:{question:v,sourceViewed:y.url||y.name},options:{includeConversationData:!0}}))};return(0,Cr.useEffect)(()=>{var y;n&&p==="idle"?u(Mi(n)):(y=s.current)==null||y.focus()},[s,p]),(0,Cr.useEffect)(()=>{p==="done"&&(u(Be({name:"knowledge assist question answered",data:{question:r||n,sources:c[c.length-1].answer.sources,answer:c[c.length-1].answer.answer,isFollowUpQuestion:c.length>1},options:{includeConversationData:!0}})),i(c.length-1),o(""))},[p,c]),(0,Cr.useEffect)(()=>{s.current&&s.current.scrollIntoView({behavior:"smooth"})},[s,c]),(0,it.jsxs)("div",{className:a.root,children:[c.length>0&&(0,it.jsx)("div",{className:a.alignRight,children:(0,it.jsx)($.Button,{onClick:t,children:l("reset")})}),(0,it.jsxs)($.ActionsBar,{list:c.map(({answer:y})=>({text:y.answer,type:"answer"})),primaryLabel:l("use"),onPrimary:y=>e(y.text),children:[c.map(({question:y,answer:v},m)=>(0,it.jsx)($.List,{children:(0,it.jsx)($.ListItem,{"data-testid":"knowledge-search-answer",index:m,description:v.answer,closeOnSelect:!0,onClick:()=>e(v.answer),onSourceClick:h=>f(h,y),sources:v.sources,styles:{title:a.question,description:a.answer},children:y})},`${v.answer}_${m}`)),p==="loading"&&(0,it.jsx)("p",{className:a.status,children:l("loading")}),p==="error"&&(0,it.jsx)("p",{className:a.status,children:l("error")}),(0,it.jsxs)("form",{className:a.form,onSubmit:d,children:[(0,it.jsx)("input",{ref:s,placeholder:l("anotherQuestion"),className:a.input,type:"text",value:r,onFocus:()=>{i(-1)},onChange:y=>{i(-1),o(y.target.value)}}),(0,it.jsx)("button",{type:"submit",className:a.submit,children:(0,it.jsx)(b1,{})})]})]})]})},E1=aL;var lL={data:null,fetchState:"idle"},Tr=e=>e.profile.data,ad=e=>e.profile.data?e.profile.data.uiConfig.widget.types.filter(t=>t.isActive):[],Da=D("profile/getProfile",async(e,t)=>{var i;let{deepdeskAPI:n}=t.extra,r=t.getState(),o=r.conversation.current;if(!o||!o.profileCode)throw new Error("No conversation of conversation profileCode found");return((i=r.profile.data)==null?void 0:i.code)===o.profileCode?r.profile.data:n.getProfile(o.profileCode)}),uL=z({name:"profile",initialState:lL,reducers:{},extraReducers:e=>{e.addCase(Da.pending,t=>{t.fetchState="loading"}).addCase(Da.rejected,t=>{t.fetchState="error"}).addCase(Da.fulfilled,(t,n)=>{t.fetchState="done",t.data=n.payload})}}),C1=uL.reducer;var T1=S(O());var So=S(b()),cL=({commands:e,onClick:t,onEdit:n})=>{var c,p,d;let r=U(),o=H(Oa),i=R(Tr),s=R(br),a=((d=(p=(c=i==null?void 0:i.uiConfig)==null?void 0:c.search)==null?void 0:p.initialTypes)==null?void 0:d.filter(({isActive:f})=>f))||[],l=0,u=a.map(({type:f})=>{var y;return(y=s[f])==null?void 0:y.suggestions.map(v=>({text:v.text||v.url||v.message,type:f}))}).flat(1);return(0,T1.useEffect)(()=>{a.forEach(({type:f})=>{(!s[f]||s[f].suggestions.length===0)&&r(Vt(f))})},[]),(0,So.jsxs)($.ActionsBar,{list:[...e.map(f=>({text:f.label,type:"command"})),...u],primaryLabel:o("use"),secondaryLabel:o("preview"),onPrimary:({text:f},y)=>t(f,u[y]),onSecondary:(f,y)=>{let v=y-e.length;n(u[v],s[u[v].type].suggestions)},children:[e.length>0&&(0,So.jsx)($.List,{heading:o("commands"),children:e.map((f,y)=>(0,So.jsx)($.ListItem,{index:y,closeOnSelect:!1,onClick:f.onClick,children:f.label},f.label))}),a.map(({type:f,title:y})=>{var v;return(0,So.jsx)($.List,{heading:y,orientation:"vertical",children:(v=s[f])==null?void 0:v.suggestions.map(m=>(l++,(0,So.jsx)($.ListItem,{index:l+e.length-1,closeOnSelect:!1,description:m.text,onClick:()=>t(m.text,m),"data-testid":"search-overlay-suggestion",children:m.title},`${m.id}-${m.text}`)))},f)})]})},k1=cL;var _e=S(b()),dL=200,pL=5,fL=4,mL=e=>e.reduce((t,n)=>[...t,...n.list.map(r=>({...r,type:n.value}))],[]),P1=(e,t)=>!t||e.toLowerCase().includes(t.toLowerCase()),gL=()=>{let e=U(),t=Lt(),n=H(Oa),[r,o]=(0,Xe.useState)(!1),[i,s]=(0,Xe.useState)(""),a=R(aw),l=R(Tr),[u,c]=(0,Xe.useState)(null),[p,d]=(0,Xe.useState)([]),[f,y]=(0,Xe.useState)(),v=R(Ge),m=M("showSearch"),h=M("showEntitiesCommand"),g=M("showSummaryCommand"),x=M("showKnowledgeSearch"),_=M("showImageSearch"),w=M("searchTriggerKey"),E=R(r1),C=R(lw),I=R(sw),k=L=>Co(C.filter(J=>J.type===L.toUpperCase()),L),K=[{value:"PERSONAL",label:n("personalSuggestions"),list:k("PERSONAL"),lineClamp:!1,listOrientation:"vertical",shouldShow:!0},{value:"URL",label:n("urlSuggestions"),list:k("URL"),lineClamp:!1,listOrientation:"vertical",shouldShow:!0},{value:"STICKYMESSAGE",label:n("pinnedMessages"),list:k("STICKYMESSAGE"),lineClamp:!1,listOrientation:"vertical",shouldShow:!0},{value:"IMAGE",label:n("imageSuggestions"),lineClamp:!1,list:k("IMAGE"),listOrientation:"horizontal",shouldShow:_}].filter(L=>L.shouldShow),N=[{label:n("entitiesClipboard"),onClick:()=>e(qe("entities")),shouldShow:h&&P1(n("entitiesClipboard"),i)},{label:n("summaryClipboard"),onClick:()=>e(qe("summary")),shouldShow:g&&P1(n("summaryClipboard"),i)},{label:i?`${n("knowledgeAssist")}: ${i}`:n("knowledgeAssist"),onClick:()=>e(qe("knowledgeAssist")),shouldShow:x}].filter(L=>L.shouldShow),B=(E==null?void 0:E.map(L=>({value:L.code.toUpperCase(),label:`${L.name}s`,list:k(L.code.toUpperCase()),listOrientation:"vertical",lineClamp:!0})))||[],be=(0,Xe.useCallback)((0,I1.default)((L,J)=>{e(go({query:L,type:J,tags:["search-overlay"]}))},dL),[]),Ar=mL([...B,...K]),Ze=(0,Xe.useCallback)((L,J)=>{e(qe("edit")),c({...L,searchTerm:void 0}),d(J)},[e,u,B]),Or=(0,Xe.useCallback)((L,J)=>{switch(J.type){case"IMAGE":t.send(Kg,{suggestion:J});break;default:t.send(An,{text:L,suggestion:J})}e($e(!1))},[e]),Wi=L=>{La(L.text),e(Be({name:"entity copied",data:{entity:L,type:"copy"}})),e($e(!1))},Nr=(0,Xe.useCallback)(L=>{e(Be({name:"suggestion feedback",data:{text:L.text,source:"search",context:i},options:{includeConversationData:!0}}))},[i]),Ga=L=>{t.send(An,{text:L,suggestion:{source:"knowledge-assist",text:L}}),e(Be({name:"answer used",data:{originalText:L},options:{includeConversationData:!0}})),s(""),e(qe("search")),e(Di()),e($e(!1))},Xa=L=>{La(L),e($e(!1))},$i=L=>{t.send(An,{text:L.text,suggestion:{source:"entity",text:L.text}}),e($e(!1))},qi=u===null||p.indexOf(u)-1<0?void 0:()=>c(p[p.indexOf(u)-1]),Mr=u===null||p.indexOf(u)===p.length-1?void 0:()=>c(p[p.indexOf(u)+1]);function Co(L,J){return L.slice(0,f?10:J.toLowerCase()==="image"?fL:pL)}function jd(L,J,gt){return J.reduce((cn,Un)=>gt&&f===gt?Un.length+cn:Co(Un,gt).length+cn,L)}function Xt(L){return J=>{r?window.confirm(n("warning"))&&(L(J),o(!1)):L(J)}}return(0,Xe.useEffect)(()=>{i?be(i,f):e(Yc())},[i,f]),(0,Xe.useEffect)(()=>{a==="search"&&e(Di())},[a]),(0,Xe.useEffect)(()=>{v&&e(Ra())},[v]),s1(w,()=>e($e(!0))),!m||!l?null:(0,_e.jsxs)($,{placeholder:n("searchPlaceholder"),typePlaceholder:n("typePlaceholder"),onChangeSearch:s,onChangeOpen:Xt(L=>e($e(L))),onChangeType:L=>y(L),onChangePage:Xt(L=>e(qe(L))),selectedType:f,search:i,page:a,isOpen:I,types:[...B,...K],children:[(0,_e.jsxs)($.Page,{id:"search",children:[i.length===0&&(0,_e.jsx)(k1,{commands:N,onClick:Or,onEdit:Ze}),i.length>0&&(0,_e.jsxs)($.ActionsBar,{list:[...N.map(L=>({text:L.label,type:"command"})),...Ar.map(L=>({text:L.text||L.url||L.message,type:L.type}))],primaryLabel:n("use"),secondaryLabel:n("preview"),onPrimary:({text:L},J)=>Or(L,Ar[J]),onSecondary:(L,J)=>{let gt=Ar[J-N.length];!gt||!gt.type||Ze(gt,k(gt.type))},children:[N.length>0&&(0,_e.jsx)($.List,{heading:n("commands"),children:N.map((L,J)=>(0,_e.jsx)($.ListItem,{index:jd(J,[],"commands"),closeOnSelect:!1,onClick:L.onClick,children:L.label},L.label))}),[...B,...K].map(({value:L,label:J,list:gt,lineClamp:cn,listOrientation:Un},Mh)=>(0,_e.jsx)($.List,{heading:J,orientation:Un==="horizontal"?"horizontal":"vertical",children:Co(gt,L).map((ce,Dr)=>(0,_e.jsx)($.ListItem,{index:jd(N.length+Dr,[...B,...K].slice(0,Mh).map(({list:ME})=>ME),L),closeOnSelect:!1,lineClamp:cn,onClick:()=>Or(ce.text,ce),description:L!=="IMAGE"?ce.title&&ce.text:void 0,onFeedback:L!=="IMAGE"?()=>Nr(ce):void 0,children:L==="IMAGE"?(0,_e.jsx)($.Image,{title:ce.title||ce.text,src:ce.image}):ce.title||ce.text},`${ce.id}-${ce.text}`))},L))]})]}),(0,_e.jsx)($.Page,{id:"edit",onDismiss:Xt(()=>{e(qe("search")),c(null)}),children:u&&(0,_e.jsx)(td,{suggestion:u,onTouched:o,onDismiss:()=>{o(!1),e(qe("search")),c(null),d([])},onNext:Mr,onPrevious:qi,onUse:L=>{e(qe("search")),Or(L,{...u,source:`${u.source||"text_recommendation"}-preview`}),e($e(!1)),d([]),c(null)}})}),(0,_e.jsx)($.Page,{id:"entities",title:n("entitiesTitle"),onDismiss:Xt(()=>{e(qe("search"))}),children:(0,_e.jsx)(c1,{onUse:$i,onCopy:Wi})}),(0,_e.jsx)($.Page,{id:"summary",title:n("summaryTitle"),onDismiss:Xt(()=>{e(qe("search"))}),children:(0,_e.jsx)(h1,{onCopy:Xa})}),(0,_e.jsx)($.Page,{id:"knowledgeAssist",title:n("knowledgeAssist"),onDismiss:Xt(()=>{e(Di()),e(qe("search"))}),children:(0,_e.jsx)(E1,{question:i,onUse:Ga,onResetQuestion:()=>{e(Di()),s("")}})})]})},R1=gL;var Fi=S(b()),hL=()=>{let e=M("showSearch"),t=M("isEmbedded");return(0,Fi.jsxs)(L1.Fragment,{children:[e&&(0,Fi.jsx)(R1,{}),(0,Fi.jsx)($w,{}),t&&(0,Fi.jsx)(Zw,{})]})},A1=hL;var D1=S(q());var ld=S(b()),O1=({className:e})=>(0,ld.jsx)("svg",{version:"1.1",xmlns:"http://www.w3.org/2000/svg",xmlnsXlink:"http://www.w3.org/1999/xlink",x:"0px",y:"0px",viewBox:"0 0 512 512",xmlSpace:"preserve",className:e,children:(0,ld.jsx)("g",{children:(0,ld.jsx)("path",{d:`M163.4,233h186v-70c0-25.6-9.4-47.8-27.3-65.7C304.2,79.4,282,70,256.4,70s-47.8,9.4-65.7,27.3
19
+ `),o=o.replace(/\n/g,"<br/>"),o}createContainer(t){var n;let o=(typeof global<"u"&&global.INTERWEAVE_SSR_POLYFILL||CI)();if(!o)return;let i=(n=this.props.containerTagName)!==null&&n!==void 0?n:"body",s=i==="body"||i==="fragment"?o.body:o.createElement(i);return t.match(wI)||(s.innerHTML=this.convertLineBreaks(this.props.escapeHtml?(0,E_.default)(t):t)),s}extractAttributes(t){let{allowAttributes:n}=this.props,r={},o=0;return t.nodeType!==b_||!t.attributes||([...t.attributes].forEach(i=>{let{name:s,value:a}=i,l=s.toLowerCase(),u=Fc[l]||Fc[s];if(!this.isSafe(t)||!l.match(bI)&&(!n&&(!u||u===hg)||l.startsWith("on")||a.replace(/(\s|\0|&#x0([9AD]);)/,"").match(/(javascript|vbscript|livescript|xss):/i)))return;let c=l==="style"?this.extractStyleAttribute(t):a;u===Sr?c=!0:u===oo?c=Number.parseFloat(String(c)):u!==Dc&&(c=String(c)),r[yg[l]||l]=this.applyAttributeFilters(l,c),o+=1}),o===0)?null:r}extractStyleAttribute(t){let n={};return Array.from(t.style).forEach(r=>{let o=t.style[r];(typeof o=="string"||typeof o=="number")&&(n[r.replace(/-([a-z])/g,(i,s)=>String(s).toUpperCase())]=o)}),n}getTagConfig(t){let n={children:[],content:0,invalid:[],parent:[],self:!0,tagName:"",type:0,void:!1};return ha[t]?{...n,...ha[t],tagName:t}:n}isSafe(t){if(typeof HTMLAnchorElement<"u"&&t instanceof HTMLAnchorElement){let n=t.getAttribute("href");if(n!=null&&n.startsWith("#"))return!0;let r=t.protocol.toLowerCase();return r===":"||r==="http:"||r==="https:"||r==="mailto:"||r==="tel:"}return!0}isTagAllowed(t){return this.banned.has(t)||this.blocked.has(t)?!1:this.props.allowElements||this.allowed.has(t)}parse(){return this.container?this.parseNode(this.container,this.getTagConfig(this.container.nodeName.toLowerCase())):[]}parseNode(t,n){let{noHtml:r,noHtmlExceptMatchers:o,allowElements:i,transform:s,transformOnlyAllowList:a}=this.props,l=[],u="";return[...t.childNodes].forEach(c=>{if(c.nodeType===b_){let d=c.nodeName.toLowerCase(),f=this.getTagConfig(d);u&&(l.push(u),u="");let y=this.applyNodeFilters(d,c);if(!y)return;let v;if(s&&!(a&&!this.isTagAllowed(d))){this.keyIndex+=1;let m=this.keyIndex;v=this.parseNode(y,f);let h=s(y,v,f);if(h===null)return;if(typeof h<"u"){l.push(so.default.cloneElement(h,{key:m}));return}this.keyIndex=m-1}if(this.banned.has(d))return;if(!(r||o&&d!=="br")&&this.isTagAllowed(d)&&(i||this.canRenderChild(n,f))){var p;this.keyIndex+=1;let m=this.extractAttributes(y),h={tagName:d};m&&(h.attributes=m),f.void&&(h.selfClose=f.void),l.push(so.default.createElement(jc,{...h,key:this.keyIndex},(p=v)!==null&&p!==void 0?p:this.parseNode(y,f)))}else l=[...l,...this.parseNode(y,f.tagName?f:n)]}else if(c.nodeType===_I){let d=r&&!o?c.textContent:this.applyMatchers(c.textContent||"",n);Array.isArray(d)?l=[...l,...d]:u+=d}}),u&&l.push(u),l}replaceTokens(t,n){if(!t.includes("{{{"))return t;let r=[],o=t,i=null;for(;i=o.match(EI);){let[s,a]=i,l=i.index,u=s.includes("/");l>0&&(r.push(o.slice(0,l)),o=o.slice(l));let{children:c,matcher:p,props:d}=n[a],f;if(u)f=s.length,r.push(p.createElement(c,d));else{let y=o.match(new RegExp(`{{{/${a}}}}`));f=y.index+y[0].length,r.push(p.createElement(this.replaceTokens(o.slice(s.length,y.index),n),d))}o=o.slice(f)}return o.length>0&&r.push(o),r.length===0?"":r.length===1&&typeof r[0]=="string"?r[0]:r}};function TI(e){var t;let{attributes:n,className:r,containerTagName:o,content:i,emptyContent:s,parsedContent:a,tagName:l,noWrap:u}=e,c=(t=o??l)!==null&&t!==void 0?t:"span",p=c==="fragment"?!0:u,d;if(a)d=a;else{let f=new Hc(i??"",e).parse();f.length>0&&(d=f)}return d||(d=s),p?so.default.createElement(so.default.Fragment,null,d):so.default.createElement(jc,{attributes:n,className:r,tagName:c},d)}function Cn(e){let{attributes:t,className:n,content:r="",disableFilters:o=!1,disableMatchers:i=!1,emptyContent:s=null,filters:a=[],matchers:l=[],onAfterParse:u=null,onBeforeParse:c=null,tagName:p="span",noWrap:d=!1,...f}=e,y=i?[]:l,v=o?[]:a,m=c?[c]:[],h=u?[u]:[];y.forEach(w=>{w.onBeforeParse&&m.push(w.onBeforeParse.bind(w)),w.onAfterParse&&h.push(w.onAfterParse.bind(w))});let g=m.reduce((w,E)=>E(w,e),r??""),x=new Hc(g,f,y,v),_=h.reduce((w,E)=>E(w,e),x.parse());return so.default.createElement(TI,{attributes:t,className:n,containerTagName:e.containerTagName,emptyContent:s,noWrap:d,parsedContent:_.length===0?void 0:_,tagName:p})}var Pg=S(q());var Sg={root:"_root_smoda_1",agentText:"_agentText_smoda_3",textInput:"_textInput_smoda_8",textInputWrapper:"_textInputWrapper_smoda_27",alert:"_alert_smoda_31",alertText:"_alertText_smoda_50",warning:"_warning_smoda_60",success:"_success_smoda_69"};var T_=S(q());var bi=S(O());function C_(e,t){let n;return[(...r)=>{window.cancelAnimationFrame(n);let o=t?t(...r):r;n=window.requestAnimationFrame(()=>{e(...o)})},()=>window.cancelAnimationFrame(n)]}function Bc(e){let t=(0,bi.useRef)(null),[n,r]=(0,bi.useState)(!1);return(0,bi.useEffect)(()=>{let o=!1,i=parseFloat(window.getComputedStyle(document.body).zoom??"1"),[s,a]=C_((c,p)=>{let d=t.current;if(!d)return;let f=c/i,y=p/i,v=d.getBoundingClientRect(),m=f>v.x&&f<v.x+v.width&&y>v.y&&y<v.y+v.height;m&&!o?(o=!0,r(!0)):!m&&o&&(o=!1,r(!1))},({clientX:c,clientY:p})=>[c,p]),[l,u]=C_(()=>{o=!1,r(!1)});return e.addEventListener("mousemove",s),e.addEventListener("mouseleave",l),()=>{a(),u(),e.removeEventListener("mousemove",s),e.removeEventListener("mouseleave",l)}},[t]),[t,n]}var Tn={root:"_root_81non_1",container:"_container_81non_3",agentText:"_agentText_81non_5",tabText:"_tabText_81non_6",hint:"_hint_81non_6",matchSelection:"_matchSelection_81non_10",focus:"_focus_81non_16",resetIndent:"_resetIndent_81non_20",matchKeyword:"_matchKeyword_81non_24",matchPlaceholder:"_matchPlaceholder_81non_25",hover:"_hover_81non_31",hintText:"_hintText_81non_64",popover:"_popover_81non_72",popoverRoot:"_popoverRoot_81non_77",popoverContentContainer:"_popoverContentContainer_81non_81",popoverContent:"_popoverContent_81non_81",selectionOptions:"_selectionOptions_81non_107",selectionOptionsIsHidden:"_selectionOptionsIsHidden_81non_112",selectionOptionsButton:"_selectionOptionsButton_81non_116",caret:"_caret_81non_132",popoverSuggestionsRoot:"_popoverSuggestionsRoot_81non_136",suggestionsOverlayInputStyles:"_suggestionsOverlayInputStyles_81non_141"};var xg=S(b()),kI=({inputElement:e,children:t})=>{let n=P("TabCompletion",Tn),[r,o]=Bc(e);return(0,xg.jsx)("mark",{ref:r,className:(0,T_.default)(n.matchPlaceholder,{[n.hover]:o}),children:t})},Ei=class extends bn{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,xg.jsx)(kI,{inputElement:n.inputElement,children:t},`placeholder_${n.matchString}_${n.key}`)}asTag(){return"mark"}};var Ci=S(O());function zc(e){return e.contentEditable==="true"}function PI(e){let t=0,n=0,r=window.getSelection();if(r.rangeCount!==0){let o=r.getRangeAt(0),i=o.cloneRange();i.selectNodeContents(e),i.setEnd(o.endContainer,o.endOffset),n=i.toString().length,i.selectNodeContents(e),i.setEnd(o.startContainer,o.startOffset),t=i.toString().length}return{selectionStart:t,selectionEnd:n}}function k_(e){let{selectionStart:t,selectionEnd:n}=zc(e)?PI(e):e;return[t,n]}function Uc(e){let[,t]=(0,Ci.useState)(),n=(0,Ci.useRef)(null);return n.current=k_(e),(0,Ci.useEffect)(()=>{let r=()=>{let[o,i]=n.current??[],s=k_(e);(!s||o!==s[0]||i!==s[1])&&(n.current=s,t({}))};return e.addEventListener("keyup",r),e.addEventListener("click",r),e.addEventListener("focus",r),document.addEventListener("selectionchange",r),()=>{e.removeEventListener("keyup",r),e.removeEventListener("click",r),e.removeEventListener("focus",r),document.removeEventListener("selectionchange",r)}},[e]),n.current}function Kc(e,t){if(!t)return;let n=e,{value:r}=n,[o,i]=t,s=r.match(Lo);if(!s||s.length===0)return;let a=0;s.find(l=>{let u=r.indexOf(l,a);return o>u&&i<u+l.length?(n.selectionStart=u,n.selectionEnd=u+l.length,!0):(a=u+l.length,!1)})}var P_=S(O());function Ti(e){(0,P_.useEffect)(()=>{let t=n=>{n.isWithinRoot||e(n)};return document.body.addEventListener("mouseup",t),()=>{document.body.removeEventListener("mouseup",t)}},[e])}function ao(e){e.addEventListener("mouseup",t=>{t.isWithinRoot=!0},!0)}var I_,sn=new Map,II=["bottom","height","left","right","top","width"],RI=(e={},t={})=>II.some(n=>e[n]!==t[n]);function R_(e){var n,r;if(e.ownerDocument===document)return[];let t=((r=(n=e.ownerDocument)==null?void 0:n.defaultView)==null?void 0:r.frameElement)??null;return t?[t,...R_(t)]:[]}function L_(e,t){return!e||!t?null:{...e,top:e.top+t.top,left:e.left+t.left}}var Vc=!1,A_=()=>{Vc=!0;let e=[];if(sn.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),sn.delete(n);return}let r=n.getBoundingClientRect();RI(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{let n=t.parentRects?t.parentRects.reduce(L_,t.rect):t.rect;t.callbacks.forEach(r=>r(n))}),sn.size===0){Vc=!1;return}I_=window.requestAnimationFrame(A_)};function _g(e,t){let n=R_(e),r=[],o=n.map((i,s)=>_g(i,a=>{r[s]=a;let l=sn.get(e);if(!l)return;let u=r.reduce(L_,l.rect);l.callbacks.forEach(c=>c(u))}));return{observe(i=!0){if(o.forEach(s=>s.observe(!1)),sn.has(e)){let s=sn.get(e);s.callbacks.push(t),s.rect&&t(s.rect)}else sn.set(e,{rect:void 0,callbacks:[t],parentRects:r});i&&!Vc&&A_()},unobserve(){o.forEach(s=>s.unobserve());let i=sn.get(e);if(i){let s=i.callbacks.indexOf(t);s>=0&&i.callbacks.splice(s,1),i.callbacks.length||sn.delete(e),sn.size||(cancelAnimationFrame(I_),Vc=!1)}}}}var O_,an=new Map,N_=()=>{an.forEach((e,t)=>{if(!t.isConnected){an.delete(t);return}let{clientHeight:n,scrollHeight:r}=t,o=r>n;e.visible!==o&&(e.visible=o,e.callbacks.forEach(i=>i(e.visible)))}),an.size!==0&&(O_=window.requestAnimationFrame(N_))};function M_(e,t){return{observe(){let n=an.size===0;an.has(e)?an.get(e).callbacks.push(t):an.set(e,{visible:void 0,callbacks:[t]}),n&&N_()},unobserve(){let n=an.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||an.delete(e),an.size||cancelAnimationFrame(O_)}}}}var wg=["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 bg(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function ki(e){return parseFloat(e)}function Wc(e){return Math.round(e*1e6)}function D_(e){return e/1e6}function Eg(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=ki(e.width),i=ki(e.borderLeftWidth),s=ki(e.borderRightWidth),a=ki(e.paddingRight),l=D_(Wc(o)-Wc(i)-Wc(s)),u=D_(Wc(r));if(l-u>2){let c=l-u;n.style.paddingRight=`${a+c}px`}}function lo(e,t={}){var c;let n=t.overlayContainer||document.createElement("div");n.style.display="none",n.style.position=t.position??"fixed",n.style.pointerEvents="none",n.style.borderColor="transparent",ao(n);let r=window.getComputedStyle(e),o=!0,i=()=>{n.scrollTop=e.scrollTop};bg(r,n,wg),Eg(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",i));let s=M_(e,()=>{bg(r,n,wg),Eg(r,e,n),i(),setTimeout(i,0)}),a,l=!0,u=_g(e,p=>{if(p===null){t.onRemove&&t.onRemove(),n.remove();return}if(!l&&t.onMoveStart&&(Promise.resolve().then(()=>t.onMoveStart()),l=!0),clearTimeout(a),a=setTimeout(()=>{t.onMoveEnd&&t.onMoveEnd(),l=!1},200),p.height===0&&p.width===0){if(o===!0)return;t.onHide&&t.onHide(),n.style.display="none",o=!0;return}if(bg(r,n,wg),Eg(r,e,n),i(),n.style.top=`${p.top}px`,n.style.left=`${p.left}px`,t.closestScrollElement&&t.closestScrollElement!==e){let d=t.closestScrollElement.getBoundingClientRect(),f=window.getComputedStyle(t.closestScrollElement),y=ki(f.borderTopWidth),v=ki(f.borderBottomWidth),m=d.top+y-p.top,h=p.top+p.height+-(d.top+d.height-v);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):(c=e.parentElement)==null||c.appendChild(n),u.observe(),s.observe(),[n,()=>{e.removeEventListener("scroll",i),u.unobserve(),s.unobserve()}]}var Cg={};Pe(Cg,{enUS:()=>LI,nlNL:()=>AI});var LI={placeholders:[{type:6,value:"placeholderSize",options:{"=0":{value:[{type:0,value:"No placeholders found"}]},one:{value:[{type:0,value:"There is one placeholder in your message"}]},other:{value:[{type:0,value:"There are "},{type:7},{type:0,value:" placeholders in your message"}]}},offset:0,pluralType:"cardinal"}]},AI={placeholders:[{type:6,value:"placeholderSize",options:{"=0":{value:[{type:0,value:"Alle placeholders zijn uit je bericht"}]},one:{value:[{type:0,value:"Er is 1 placeholder in jouw bericht"}]},other:{value:[{type:0,value:"Er zijn "},{type:7},{type:0,value:" placeholders in jouw bericht"}]}},offset:0,pluralType:"cardinal"}]};var ya=S(b()),F_=()=>(0,ya.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 512 512","aria-labelledby":"circleCheckTitle",children:[(0,ya.jsx)("title",{id:"circleCheckTitle",children:"Check"}),(0,ya.jsx)("path",{d:"M243.8 339.8C232.9 350.7 215.1 350.7 204.2 339.8L140.2 275.8C129.3 264.9 129.3 247.1 140.2 236.2C151.1 225.3 168.9 225.3 179.8 236.2L224 280.4L332.2 172.2C343.1 161.3 360.9 161.3 371.8 172.2C382.7 183.1 382.7 200.9 371.8 211.8L243.8 339.8zM512 256C512 397.4 397.4 512 256 512C114.6 512 0 397.4 0 256C0 114.6 114.6 0 256 0C397.4 0 512 114.6 512 256zM256 48C141.1 48 48 141.1 48 256C48 370.9 141.1 464 256 464C370.9 464 464 370.9 464 256C464 141.1 370.9 48 256 48z"})]});var Tg=S(b()),j_=()=>(0,Tg.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",fill:"currentColor",children:(0,Tg.jsx)("path",{d:"M256 32c14.2 0 27.3 7.5 34.5 19.8l216 368c7.3 12.4 7.3 27.7 .2 40.1S486.3 480 472 480H40c-14.3 0-27.6-7.7-34.7-20.1s-7-27.8 .2-40.1l216-368C228.7 39.5 241.8 32 256 32zm0 128c-13.3 0-24 10.7-24 24V296c0 13.3 10.7 24 24 24s24-10.7 24-24V184c0-13.3-10.7-24-24-24zm32 224c0-17.7-14.3-32-32-32s-32 14.3-32 32s14.3 32 32 32s32-14.3 32-32z"})});var H_=(s=>(s.CUT="Cut",s.BACKSPACE="Backspace",s.DELETE="Delete",s.ERASEEOF="EraseEof",s.UNDO="Undo",s.CLEAR="Clear",s))(H_||{}),kn=class{constructor(t){this.element=t;this.currentText=this.getText(),this.currentHTML=this.getHTML(),this.listen()}eventListeners={};disposeHandlers=[];currentText="";currentCaret=null;currentSelection={start:0,end:0};currentHTML="";isFocused=!1;isActive=!0;isSettingValue=!1;isSubmitting=!1;isPossibleClearInputAction=!1;isDisposed=!1;addEventListener(t,n){let r=o=>{n(o)};this.element.addEventListener(t,r),this.disposeHandlers.push(()=>{this.element.removeEventListener(t,r)})}removeEventListener(t,n){this.element.removeEventListener(t,n)}triggerChange(){let t=this.getText(),n=this.getHTML(),r=t!==this.currentText;this.isActive&&(t===""&&this.currentText!==""&&!this.isSettingValue&&!this.isPossibleClearInputAction&&(this.isSubmitting=!0,this.emit("submit")),!this.isSettingValue&&r&&!this.isSubmitting&&this.emit("change",{plainText:t}),r&&(this.currentSelection=this.getSelection()),this.currentText=t,this.isSubmitting=!1,(this.currentHTML!==n||n===null&&r)&&(this.emit("updated",{plainText:t}),this.triggerCaretPosition(),this.currentHTML=n))}triggerSelection(){let t=this.getSelection();(t.start!==this.currentSelection.start||t.end!==this.currentSelection.end)&&(this.currentSelection=t,this.emit("selection",t),this.triggerCaretPosition())}triggerCaretPosition(){let t=this.getCaretPosition();hr(t,this.currentCaret)||(this.currentCaret=t,this.emit("caret",t))}handleKeyUp(t){let{key:n,shiftKey:r}=t;(n==="Enter"&&r===!0||n==="Backspace")&&this.triggerChange(),this.triggerSelection()}handleClick(){this.triggerSelection()}handleFocus(){this.isFocused||this.emit("focus"),this.triggerSelection(),this.isFocused=!0}handleBlur(){this.isPossibleClearInputAction=!1,this.isFocused&&this.emit("blur"),this.isFocused=!1}handleKeyDown(t){let{key:n,ctrlKey:r,metaKey:o}=t;this.isPossibleClearInputAction=Object.values(H_).includes(n)||n.toLowerCase()==="z"&&(r||o),this.emit("keydown",t)}handleCut(){this.isPossibleClearInputAction=!0,this.emit("cut",{selectionText:this.getSelectedText()})}handlePaste(t){var r,o;let n=((r=t.clipboardData)==null?void 0:r.getData("text"))||((o=t.clipboardData)==null?void 0:o.getData("text/plain"))||"";this.emit("paste",{pastedText:n,selectionText:this.getSelectedText()})}listen(){this.addEventListener("keydown",n=>this.handleKeyDown(n)),this.addEventListener("keyup",n=>this.handleKeyUp(n)),this.addEventListener("input",()=>this.triggerChange()),this.addEventListener("change",()=>this.triggerChange()),this.addEventListener("focus",()=>this.handleFocus()),this.addEventListener("blur",()=>this.handleBlur()),this.addEventListener("cut",()=>this.handleCut()),this.addEventListener("paste",n=>this.handlePaste(n)),this.addEventListener("click",()=>this.triggerSelection()),document.activeElement===this.element&&setTimeout(()=>{this.handleFocus()},0);let t=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});t.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{t.disconnect()}),this.currentSelection=this.getSelection()}focus(){this.element.focus()}emit(t,...n){this.isDisposed||this.eventListeners[t]&&this.eventListeners[t].forEach(r=>{r(...n)})}on(t,n){this.isDisposed||(this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n))}activate(){let t=this.isActive===!1;this.isActive=!0,t&&this.triggerChange()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(t=>t()),this.eventListeners={},this.isDisposed=!0}};var Pn=class extends kn{lastKnownSelection=null;getText(){return this.element.value}getHTML(){return null}getSelection(){let{selectionStart:t,selectionEnd:n}=this.element;return{start:t,end:n}}getSelectedText(){let t=this.getSelection();return t?this.getText().slice(t.start,t.end):""}getCaretPosition(){return null}applyChanges(t){if(!this.isActive)return;this.isSettingValue=!0;let n=this.getText(),r=t(this.element);return Promise.resolve(r).then(()=>{this.currentText=this.getText(),n!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(){super.listen();let t=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var o;return(o=t==null?void 0:t.get)==null?void 0:o.call(this.element)},set:o=>{var i;(i=t==null?void 0:t.set)==null||i.call(this.element,o),this.triggerChange()}});let n=this.element.disabled,r=new MutationObserver(()=>{this.element.disabled!==n&&(n=this.element.disabled,this.emit(n?"disabled":"enabled"))});r.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>r.disconnect())}};var OI=/[.*+?^${}()|[\]\\]/g,NI=/[^0-9A-Za-zÀ-ÖØ-öø-ÿ](?=[0-9A-Za-zÀ-ÖØ-öø-ÿ]*$)/;function MI(e){return e.replace(OI,"\\$&")}function DI(e,t){let n=e.split("").findIndex((r,o)=>r!==t[o]);return n>-1?n:Math.min(e.length,t.length)}function FI(e){return e.search(NI)}function B_(e,t=[]){let n=e;return t.forEach(r=>{if(!r)return;let o=new RegExp(`\\b(${MI(r)})\\b`,"gi");n=n.replace(o,"<strong>$1</strong>")}),n}function z_(e){return e.replace(Lo,'<mark data-type="placeholder">$1</mark>')}function Pi(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}function jI(e,t){return e.split("").map((s,a)=>({char:s,index:a})).filter(({char:s,index:a})=>/\s/.test(s)&&a<=t).map(({index:s})=>s).reverse()[0]}function kg(e,t,n={}){if(t){let r=DI(t.toLowerCase(),e.toLowerCase()),o=Pi(e.substring(r,e.length));if(n.stripAgentPart){let l=e.substring(0,r),u=FI(l);return`<span style="opacity: 0.5">${l.substring(u+1)}</span>${o}`}let s=t.split(Ey).length>3||t.length>30?jI(t.trim(),r):0;return`${`${s>0?"\u2026":""}${Pi(e.substring(s,r))}`}<strong>${o}</strong>`}return e}var HI=/(<\/[a-zA-Z]+[0-9]?>|<[a-zA-Z]+\s?\/>|<br>)/i;function uo(e){return HI.test(e)}function U_(e){if(uo(e)){let n=/<body[^>]*>([\s\S]*)<\/body>/gi.exec(e);return n?n[1]:""}return e}function K_(e){let t=document.createElement("template");return t.innerHTML=e,t.content.textContent??""}var Ue=S(b()),BI=({value:e,onUse:t,...n})=>{var p;let r=H(Cg),o=U(),i=uo(e),s=P("EditSuggestionTextInput",Sg),[a,l]=(0,Rt.useState)(null),u=(0,Rt.useRef)(null),c=((p=e.match(Lo))==null?void 0:p.length)||0;return(0,Rt.useEffect)(()=>{let d;return u.current&&(l(u.current),d=new Pn(u.current),d.on("change",({plainText:f})=>{o(rt.actions.userInput({text:f,selection:d.getSelection()}))}),d.on("keydown",f=>{o(rt.actions.registerKeyDown(pc(f))),f.code==="Enter"&&f.shiftKey&&t(d.getText())}),d.on("paste",({pastedText:f,selectionText:y})=>{o(rt.actions.registerPaste({text:f,selectionText:y}))}),d.on("cut",({selectionText:f})=>{o(rt.actions.registerCut(f))})),()=>{o(rt.actions.reset()),d.dispose(),d.deactivate()}},[u]),(0,Rt.useEffect)(()=>{e&&u.current&&(u.current.value=e)},[e,u]),(0,Rt.useEffect)(()=>{u.current&&setTimeout(()=>{if(!u.current)return;let d=u.current.value.length;u.current.setSelectionRange(d,d),u.current.focus()},0)},[u]),i?(0,Ue.jsx)("div",{className:s.textInputWrapper,children:(0,Ue.jsx)(Cn,{className:s.textInput,tagName:"div",content:e})}):(0,Ue.jsxs)("div",{className:s.textInputWrapper,children:[(0,Ue.jsx)("textarea",{...n,ref:u,"data-testid":"edit-suggestion-dialog-textarea",className:s.textInput,defaultValue:e,onChange:()=>{}}),a&&(0,Ue.jsx)(zI,{inputElement:u.current,value:e}),(0,Ue.jsxs)("div",{className:(0,Pg.default)(s.alert,c===0?s.success:s.warning),children:[(0,Ue.jsx)("div",{className:s.alertText,children:r("placeholders",{placeholderSize:c})}),c===0?(0,Ue.jsx)(F_,{}):(0,Ue.jsx)(j_,{})]})]})},zI=({inputElement:e,value:t})=>{let n=P("EditSuggestionTextInput",Sg),r=(0,Rt.useRef)(null),o=Uc(e);return(0,Rt.useEffect)(()=>{Kc(e,o)},[o,e]),(0,Ue.jsx)(UI,{inputElement:e,children:(0,Ue.jsxs)("div",{ref:r,className:(0,Pg.default)(n.root,n.agentText),children:[(0,Ue.jsx)(Cn,{tagName:"span",disableLineBreaks:!0,content:t,matchers:[new Ei("placeholders")],inputElement:e,boundaryRef:r}),(0,Ue.jsx)("br",{})]})})},UI=({inputElement:e,children:t})=>{let n=(0,Rt.useRef)(null);return(0,Rt.useEffect)(()=>{if(!n.current)return()=>{};let[r,o]=lo(e,{overlayContainer:n.current,mirrorOverflow:!0});return r.setAttribute("translate","no"),()=>{o()}},[n.current]),(0,Ue.jsx)("div",{ref:n,children:t})},V_=BI;var Li=S(O());var W_=S(O()),$c=S(q());var ot={root:"_root_1mc8f_1",list:"_list_1mc8f_2",listWrapper:"_listWrapper_1mc8f_6",listHorizontal:"_listHorizontal_1mc8f_10",page:"_page_1mc8f_19",search:"_search_1mc8f_25",pageNav:"_pageNav_1mc8f_33",pageTitle:"_pageTitle_1mc8f_41",pageBackButton:"_pageBackButton_1mc8f_48",listHeading:"_listHeading_1mc8f_62",listItem:"_listItem_1mc8f_70",listItemContent:"_listItemContent_1mc8f_79",listItemText:"_listItemText_1mc8f_97",listItemDescription:"_listItemDescription_1mc8f_105",listItemActions:"_listItemActions_1mc8f_112",truncate:"_truncate_1mc8f_123",lineClamp:"_lineClamp_1mc8f_129",listItemTitle:"_listItemTitle_1mc8f_136",listItemAction:"_listItemAction_1mc8f_112",listItemPrimaryAction:"_listItemPrimaryAction_1mc8f_157",listItemSelected:"_listItemSelected_1mc8f_162",sources:"_sources_1mc8f_166",sourcesTitle:"_sourcesTitle_1mc8f_173",source:"_source_1mc8f_166",icon:"_icon_1mc8f_188",searchIcon:"_searchIcon_1mc8f_205",searchInputWrapper:"_searchInputWrapper_1mc8f_210",searchInput:"_searchInput_1mc8f_210",select:"_select_1mc8f_231",selectType:"_selectType_1mc8f_248",selectWrapper:"_selectWrapper_1mc8f_252",image:"_image_1mc8f_282",imageSrc:"_imageSrc_1mc8f_289",imageSrcHidden:"_imageSrcHidden_1mc8f_300",imageSrcStatus:"_imageSrcStatus_1mc8f_304",imageTitle:"_imageTitle_1mc8f_314",actions:"_actions_1mc8f_319",actionsWrapper:"_actionsWrapper_1mc8f_323",actionsBar:"_actionsBar_1mc8f_329",actionButton:"_actionButton_1mc8f_338",hasShortKeys:"_hasShortKeys_1mc8f_351",actionShortcut:"_actionShortcut_1mc8f_360",actionShortcutFixKerning:"_actionShortcutFixKerning_1mc8f_367"};var co={};Pe(co,{enUS:()=>KI,nlNL:()=>VI});var KI={visitUrl:[{type:0,value:"Visit"}],back:[{type:0,value:"Back"}],loading:[{type:0,value:"Loading..."}],imageError:[{type:0,value:"Could not load image"}]},VI={visitUrl:[{type:0,value:"Bekijk"}],back:[{type:0,value:"Terug"}],loading:[{type:0,value:"Laden..."}],imageError:[{type:0,value:"Kan afbeelding niet laden"}]};var xr=S(b()),WI=({src:e,title:t})=>{let n=P("CommandPalette",ot),[r,o]=(0,W_.useState)("loading"),i=H(co);return(0,xr.jsxs)("div",{className:n.image,children:[(0,xr.jsx)("img",{src:e,alt:t,onLoad:()=>o("done"),onError:()=>o("error"),className:(0,$c.default)(n.imageSrc,{[n.imageSrcHidden]:["loading","error"].includes(r)})}),r==="loading"&&(0,xr.jsx)("span",{className:(0,$c.default)(n.imageSrc,n.imageSrcStatus),children:i("loading")}),r==="error"&&(0,xr.jsx)("span",{className:(0,$c.default)(n.imageSrc,n.imageSrcStatus),children:(0,xr.jsx)(nl,{})}),t&&(0,xr.jsx)("span",{className:n.imageTitle,children:t})]})},$_=WI;var q_=S(O()),G_=S(q());var va=S(b());function Ig({children:e,heading:t,orientation:n}){let r=P("CommandPalette",ot);return q_.default.Children.count(e)===0?null:(0,va.jsxs)("div",{"data-testid":"commandpalette-list",className:r.list,children:[t&&(0,va.jsx)("h4",{className:r.listHeading,children:t}),(0,va.jsx)("div",{className:(0,G_.default)(r.listWrapper,n==="horizontal"&&r.listHorizontal),children:e})]})}var Sa=S(q());var Ae=S(O()),X_=S(q());var Rg={root:"_root_1oh4w_1",trigger:"_trigger_1oh4w_5",content:"_content_1oh4w_19",contentOpen:"_contentOpen_1oh4w_33",contentTop:"_contentTop_1oh4w_37",contentBottom:"_contentBottom_1oh4w_41",item:"_item_1oh4w_45"};var po=S(b()),$I=0,Q_=Ae.default.createContext(null),qI=()=>{let e=(0,Ae.useContext)(Q_);if(!e)throw new Error("Invalid DropdownContext");return e},Y_=({trigger:e,children:t,position:n="bottom"})=>{let r=(0,Ae.useMemo)(()=>++$I,[]),o=(0,Ae.useRef)(null),i=(0,Ae.useRef)(null),s=P("Dropdown",Rg),[a,l]=(0,Ae.useState)(!1),[u,c]=(0,Ae.useState)(n),p=f=>{f.preventDefault(),f.stopPropagation(),l(!a)},d=(0,Ae.useCallback)(([f])=>{!f.isIntersecting&&a&&c(u==="top"?"bottom":"top")},[a]);return(0,Ae.useEffect)(()=>{let f=y=>{o.current&&!o.current.contains(y.target)&&l(!1)};return document.addEventListener("click",f),()=>{document.removeEventListener("click",f)}},[]),(0,Ae.useEffect)(()=>{if(!i.current&&!a)return()=>{};let f=new IntersectionObserver(d,{root:null,rootMargin:"0px",threshold:1});return i.current&&f.observe(i.current),()=>{i.current&&f.unobserve(i.current)}},[i,a]),(0,po.jsx)(Q_.Provider,{value:{setIsOpen:l},children:(0,po.jsxs)("div",{ref:o,className:s.root,children:[(0,po.jsx)("button",{id:`dropdown-${r}`,"data-testid":"dropdown-trigger","aria-haspopup":"true","aria-expanded":a,"aria-label":"Dropdown trigger",type:"button",className:s.trigger,onClick:p,children:e}),(0,po.jsx)("div",{"data-testid":"dropdown-content",ref:i,"aria-hidden":!a,"aria-labelledby":`dropdown-${r}`,className:(0,X_.default)(s.content,{[s.contentOpen]:a,[s.contentTop]:u==="top",[s.contentBottom]:u==="bottom"}),children:t})]})})};function GI({as:e,children:t,onClick:n,...r}){let o=e||"button",i=P("Dropdown",Rg),{setIsOpen:s}=qI(),a=l=>{s(!1),n(l),l.stopPropagation()};return(0,po.jsx)(o,{type:"button",className:i.item,onClick:a,...r,children:t})}Y_.Item=GI;var Lg=Y_;var Ag=S(b()),Z_=e=>(0,Ag.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"16",width:"14",viewBox:"0 0 448 512",...e,children:(0,Ag.jsx)("path",{fill:"currentColor",d:"M8 256a56 56 0 1 1 112 0A56 56 0 1 1 8 256zm160 0a56 56 0 1 1 112 0 56 56 0 1 1 -112 0zm216-56a56 56 0 1 1 0 112 56 56 0 1 1 0-112z"})});var fo={};Pe(fo,{enUS:()=>XI,nlNL:()=>QI});var XI={preview:[{type:0,value:"Preview"}],useSuggestion:[{type:0,value:"Add"}],sendSuggestion:[{type:0,value:"Send"}],suggestionSent:[{type:0,value:"Sent"}],sendingError:[{type:0,value:"Sending failed"}],tryAgain:[{type:0,value:"Try again"}],editSuggestion:[{type:0,value:"Edit"}],visitUrl:[{type:0,value:"Visit"}],giveFeedback:[{type:0,value:"Give feedback"}],answer:[{type:0,value:"Answer"}]},QI={preview:[{type:0,value:"Preview"}],useSuggestion:[{type:0,value:"Gebruik"}],sendSuggestion:[{type:0,value:"Verzenden"}],suggestionSent:[{type:0,value:"Verzonden"}],sendingError:[{type:0,value:"Verzenden mislukt"}],tryAgain:[{type:0,value:"Probeer opnieuw"}],editSuggestion:[{type:0,value:"Bewerken"}],visitUrl:[{type:0,value:"Bekijk"}],giveFeedback:[{type:0,value:"Geef feedback"}],answer:[{type:0,value:"Antwoord"}]};var qc=S(b()),YI="%0d%0a%0d%0a%0d%0a",ZI=(e,t)=>{let n=[`Suggestie: ${encodeURIComponent(t)}`,"Beschrijf je feedback:"];return`mailto:${e.join(",")}?subject=Suggestie feedback&body=${n.join(YI)}`},JI=({suggestion:e,onFeedback:t})=>{let n=H(fo),r=M("suggestionFeedbackEmailAddresses");return!r||r.length===0?null:(0,qc.jsx)(Lg,{trigger:(0,qc.jsx)(Z_,{"data-testid":"feedback-dropdown-trigger"}),children:(0,qc.jsx)(Lg.Item,{as:"a",href:ZI(r,e),onClick:t,children:n("giveFeedback")})})},Gc=JI;var Xc=S(O()),tw=S(b()),J_=Xc.default.createContext(void 0);function _r(){let e=Xc.default.useContext(J_);if(e===void 0)throw new Error("useCommandPalette must be used within the CommandPalette component");return e}var ew=({children:e,page:t,isOpen:n,onChangeOpen:r,selected:o,setSelected:i})=>{let s=Xc.default.useMemo(()=>({page:t,isOpen:n,onChangeOpen:r,selected:o,setSelected:i}),[n,t,o]);return(0,tw.jsx)(J_.Provider,{value:s,children:e})};var pt=S(b());function Og({closeOnSelect:e=!0,lineClamp:t,children:n,onClick:r,onFeedback:o,onSourceClick:i,index:s,description:a,sources:l,styles:u,...c}){let{selected:p,setSelected:d,onChangeOpen:f}=_r(),y=P("CommandPalette",ot);function v(m){r(m),e&&f(!1)}return(0,pt.jsxs)("div",{className:(0,Sa.default)(y.listItem,p===s&&y.listItemSelected),children:[(0,pt.jsx)("button",{onMouseEnter:()=>d(s),type:"button",className:(0,Sa.default)("command-palette-list-item",y.listItemAction,y.listItemPrimaryAction),"aria-disabled":c.disabled??!1,onClick:v,...c,children:(0,pt.jsxs)("div",{className:y.listItemContent,children:[typeof n=="string"?(0,pt.jsx)("p",{className:(0,Sa.default)(y.listItemText,y.truncate,u==null?void 0:u.title),children:n}):n,a&&(0,pt.jsx)(Cn,{tagName:"p",allowList:[],content:uo(a)?K_(a):a,className:(0,Sa.default)(y.listItemDescription,u==null?void 0:u.description,t?y.lineClamp:y.truncate)})]})}),o&&p===s&&(0,pt.jsx)("div",{className:y.listItemActions,children:(0,pt.jsx)(Gc,{suggestion:String(n),onFeedback:o})}),l&&(0,pt.jsxs)("div",{className:y.sources,children:[(0,pt.jsx)("span",{className:y.sourcesTitle,children:"Sources"}),l.map(m=>m.url?(0,pt.jsx)("a",{className:y.source,href:m.url,target:"_blank",title:m.url,rel:"noopener noreferrer",onClick:()=>i&&i(m),children:m.name},m.url):(0,pt.jsx)("span",{className:y.source,children:m.name},m.name))]})]})}var mo=S(b());function Ng({children:e,title:t,id:n,onDismiss:r}){let o=H(co),i=P("CommandPalette",ot),{page:s}=_r();return s!==n?null:(0,mo.jsxs)("div",{className:i.page,id:`page_${n}`,tabIndex:-1,children:[r&&(0,mo.jsxs)("div",{className:i.pageNav,children:[(0,mo.jsxs)("button",{className:i.pageBackButton,type:"button",onClick:r,children:[(0,mo.jsx)(Ac,{}),o("back")]}),t&&(0,mo.jsx)("h3",{className:i.pageTitle,children:t})]}),e]})}var wr=S(O());var eR={info(...e){console.info("[Deepdesk]",...e)},warn(...e){console.warn("[Deepdesk]",...e)},error(...e){console.error("[Deepdesk]",...e)}},j=eR;function tR(e){return e.replace(/(_\w)/g,t=>t[1].toUpperCase())}function Z(e){return Array.isArray(e)?e.map(Z):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>({...t,[tR(n)]:Z(e[n])}),{}):e}function Mg(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function ke(e){return Array.isArray(e)?e.map(ke):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>({...t,[Mg(n)]:ke(e[n])}),{}):e}var nR={agentInfo:void 0,agentSettings:{},visitorInfo:void 0,fetchState:"idle"},_a=e=>{var t,n,r;return{timezone:((t=e.info.visitorInfo)==null?void 0:t.visitorTimeZone)||Intl.DateTimeFormat().resolvedOptions().timeZone,agentName:((n=e.info.agentInfo)==null?void 0:n.agentNickname)||"",visitorName:((r=e.info.visitorInfo)==null?void 0:r.visitorName)||""}},xa=D("info/setAgentInfo",async(e,t)=>{let{deepdeskAPI:n}=t.extra;if(!e.agentId&&!e.agentNickname)throw new Error("At least provide agentId or agentNickname");let r=await n.client.get("/apis/admin/session/me/",{version:null}),o={};return r.external_id||(o.external_id=e.agentId),r.nickname||(o.nickname=e.agentNickname),!o.external_id&&!o.nickname?Z(r):(await n.client.patch("/apis/admin/session/me/",o,{version:null}),Z(r))}),Dg=D("info/setAgentSettings",async(e,t)=>{let{deepdeskAPI:n}=t.extra,r=await n.client.get("/apis/admin/session/me/",{version:null}),o={...typeof r.ui_config=="object"?r.ui_config:{},...e};return await n.client.patch("/apis/admin/session/me/",{ui_config:o}),o}),Fg=D("info/getAgentSettings",async(e,t)=>{let{deepdeskAPI:n}=t.extra;return(await n.client.get("/apis/admin/session/me/",{version:null})).ui_config}),nw=e=>e.info.agentInfo,rw=z({name:"info",initialState:nR,reducers:{setVisitorInfo(e,t){e.visitorInfo={...e.visitorInfo,...t.payload}}},extraReducers:e=>{e.addCase(xa.pending,(t,n)=>{t.fetchState="loading",t.agentInfo={...t.agentInfo,...n.meta.arg}}).addCase(xa.rejected,t=>{t.fetchState="error"}).addCase(xa.fulfilled,(t,n)=>{t.fetchState="done",t.agentInfo={...t.agentInfo,...n.meta.arg,agentId:n.payload.externalId||n.meta.arg.agentId||"",agentNickname:n.payload.nickname||n.meta.arg.agentNickname||""}}).addCase(Dg.fulfilled,(t,n)=>{t.agentSettings=n.payload}).addCase(Fg.fulfilled,(t,n)=>{t.agentSettings=n.payload}).addCase(te,t=>{t.visitorInfo=void 0})}}),{setVisitorInfo:ow}=rw.actions,iw=rw.reducer;var Qc={list:[],fetchState:"idle",isOpen:!1,page:"search"},sw=e=>e.search.isOpen,aw=e=>e.search.page,lw=e=>e.search.list;function uw(e,t=n=>n){return n=>n.search.list.filter(r=>r.type===e).map(t)}var go=D("search/getAll",async(e,t)=>{var s;let{deepdeskAPI:n}=t.extra,r=t.getState(),o=(s=r.conversation.current)==null?void 0:s.profileCode;if(!o)throw new Error("Profile should be provided in order to be able to search");let{results:i}=await n.search({profile:o,query:e.query,filters:{type:e.type},params:_a(r),tags:e.tags});return i.map(a=>({...a,source:`search-${a.type.toLowerCase()}`,searchTerm:e.query}))}),cw=z({name:"search",initialState:Qc,reducers:{setIsOpen(e,t){e.isOpen=t.payload},setPage(e,t){e.page=t.payload},resetSearch(e){e.fetchState=Qc.fetchState,e.list=Qc.list}},extraReducers:e=>{e.addCase(go.pending,t=>{t.fetchState="loading"}).addCase(go.rejected,(t,n)=>{t.fetchState="error",j.error(n.error)}).addCase(go.fulfilled,(t,n)=>{t.fetchState="done",t.list=n.payload}).addCase(te,()=>Qc)}}),{resetSearch:Yc,setIsOpen:$e,setPage:qe}=cw.actions,dw=cw.reducer;var rR=/(https?:\/\/[^\s]+)/,Zc=e=>e.split(" ").find(t=>rR.test(t));var Jc=()=>/Mac/i.test(navigator.platform);var jg=S(q());var ed=S(b()),oR=({onClick:e,shortKeys:t,children:n,...r})=>{let o=P("CommandPalette",ot);return(0,ed.jsxs)("button",{type:"button",...r,onClick:e,className:(0,jg.default)(o.actionButton,r.className,{[o.hasShortKeys]:t&&t.length>0}),children:[n,t&&t.map(i=>(0,ed.jsx)("span",{className:(0,jg.default)(o.actionShortcut,i===8629&&o.actionShortcutFixKerning),children:typeof i=="number"?String.fromCharCode(i):i},i))]})},Ii=oR;var In=S(b()),iR=["url","URL"],sR=["default","pinned-message","DEFAULT","STICKYMESSAGE"],aR=({children:e,primaryLabel:t,secondaryLabel:n,onPrimary:r,onSecondary:o,list:i})=>{let s=P("CommandPalette",ot),a=H(co),{selected:l,setSelected:u}=_r(),c=i[l],p=c&&c.type&&iR.includes(c.type),d=c&&c.type&&sR.includes(c.type)||c&&"secondaryAction"in c,f=p?Zc(c.text):null,y=(0,wr.useRef)(null);function v(w){if(!y.current)return;let E=y.current.querySelectorAll(".command-palette-list-item"),C=0,I=0;w==="down"?(E.forEach((K,N)=>{N===l&&(C=N)}),I=C===E.length-1?0:C+1):w==="up"?(E.forEach((K,N)=>{N===l&&(C=N)}),I=C?C-1:E.length-1):u(0);let k=E[I];k&&typeof I=="number"&&(u(I),k.scrollIntoView&&k.scrollIntoView({behavior:"smooth",block:I?"center":"end"}))}function m(){if(!y.current)return;let w=y.current.querySelectorAll(".command-palette-list-item"),E=0;w.forEach((I,k)=>{k===l&&(E=k)});let C=w[E];C&&C.click()}let h=()=>{f&&window.open(f,"_blank")},g=()=>{c&&r(c,l)},x=()=>{!o||!d||o(c,l)},_=(0,wr.useCallback)(w=>{if(w.key==="Enter"&&w.altKey&&f){h();return}if(w.key==="Enter"&&w.shiftKey){x();return}if(w.key==="ArrowDown"){w.preventDefault(),w.stopPropagation(),v("down");return}if(w.key==="ArrowUp"){w.preventDefault(),w.stopPropagation(),v("up");return}w.key==="Enter"&&l!==-1&&(w.preventDefault(),w.stopPropagation(),m())},[l]);return(0,wr.useEffect)(()=>(window.addEventListener("keyup",_),()=>{window.removeEventListener("keyup",_)}),[_]),(0,In.jsxs)("div",{className:s.actions,children:[(0,In.jsx)("div",{className:s.actionsWrapper,ref:y,children:e}),(0,In.jsxs)("div",{className:s.actionsBar,children:[f&&(0,In.jsx)(Ii,{onClick:h,shortKeys:[Jc()?8997:"ALT",8629],children:a("visitUrl")}),c&&(0,In.jsxs)(wr.Fragment,{children:[o&&d&&(0,In.jsx)(Ii,{onClick:x,shortKeys:[8679,8629],children:n}),(0,In.jsx)(Ii,{onClick:g,shortKeys:[8629],children:t})]})]})]})},fw=aR;var mw=S(O());var wa=S(b()),Ri=()=>(0,wa.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 0 24 24",width:"1em",fill:"currentColor",children:[(0,wa.jsx)("path",{d:"M0 0h24v24H0z",fill:"none"}),(0,wa.jsx)("path",{d:"M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"})]});var Kt=S(b());function lR({onChange:e,onChangeType:t,placeholder:n,typePlaceholder:r,types:o,value:i,selectedType:s},a){let l=P("CommandPalette",ot);return(0,Kt.jsxs)("div",{className:l.search,children:[(0,Kt.jsx)("div",{className:l.searchIcon,children:(0,Kt.jsx)(Ri,{})}),(0,Kt.jsxs)("div",{className:l.searchInputWrapper,children:[(0,Kt.jsx)("input",{ref:a,spellCheck:!1,autoComplete:"off",onChange:u=>{e(u.currentTarget.value)},onFocus:u=>{u.currentTarget.select()},className:l.searchInput,placeholder:n,value:i,type:"text",id:"command-palette-search-input",autoFocus:!0}),o&&o.length>0&&(0,Kt.jsx)("div",{className:l.selectWrapper,children:(0,Kt.jsxs)("select",{"data-testid":"command-palette-type-select",className:l.select,onChange:u=>t(u.target.value===r?void 0:u.target.value),value:s||r,children:[r&&(0,Kt.jsx)("option",{children:r}),o.map(u=>(0,Kt.jsx)("option",{value:u.value,children:u.label},u.value))]})})]})]})}var gw=(0,mw.forwardRef)(lR);var ba=S(b());function ho({placeholder:e="Start typing to search...",typePlaceholder:t="All types",defaultPage:n="search",page:r,onChangePage:o,onChangeSearch:i,onChangeType:s,onChangeOpen:a,selectedType:l,types:u,children:c,isOpen:p,search:d}){let[f,y]=(0,Li.useState)(0),v=(0,Li.useRef)(null),m=()=>{o&&o(n),s(void 0),i(""),a(!1)},h=()=>{var g;if(r!==n&&o){o(n);return}if(l&&s){s(void 0),(g=v.current)==null||g.focus();return}if(d.length>0){i("");return}a(!1)};return(0,Li.useEffect)(()=>{y(0)},[d,r]),(0,ba.jsx)(wi,{autoFocus:!0,contentAriaLabel:"Search Results",overlayAriaLabel:"Command Palette",isOpen:p,onBack:h,onClose:m,children:(0,ba.jsxs)(ew,{selected:f,setSelected:y,isOpen:p,onChangeOpen:a,page:r,children:[r===n&&(0,ba.jsx)(gw,{ref:v,onChange:i,onChangeType:s,placeholder:e,value:d,selectedType:l,types:u,typePlaceholder:t}),c]})})}ho.Page=Ng;ho.List=Ig;ho.Image=$_;ho.ListItem=Og;ho.ActionsBar=fw;ho.Button=Ii;var $=ho;var Ke=S(b()),uR=({suggestion:e,onUse:t,onDismiss:n,onTouched:r,onNext:o,onPrevious:i})=>{let s=e.text||e.url||e.message,a=P("EditSuggestionForm",u_),l=U(),u=H(ng),c=R(y=>y.overlayInput.text);(0,Hg.useEffect)(()=>{e&&(l(rt.actions.reset()),l(rt.actions.stageSuggestion({text:s,suggestion:e,eventMetrics:{inputType:"mouse"},replace:"until-selection-end"})),l(rt.actions.commitSuggestion()))},[e]);let p=y=>{y.preventDefault(),d(c)},d=y=>{l(gc(y)),t(y)},f=y=>v=>{c!==s?window.confirm(u("warning"))&&y(v):y(v)};return(0,Hg.useEffect)(()=>{r&&r(c!==s)},[r,e,c]),(0,Ke.jsxs)("div",{className:a.root,children:[(0,Ke.jsxs)("div",{className:a.content,children:[e.title&&(0,Ke.jsx)("h3",{className:a.title,children:e.title}),e.searchKeywords&&e.searchKeywords.length>0&&(0,Ke.jsx)(Gd,{labels:e.searchKeywords}),(0,Ke.jsx)(V_,{onUse:d,value:U_(c)})]}),(0,Ke.jsxs)("form",{className:a.actions,onSubmit:p,children:[(0,Ke.jsxs)("div",{children:[(0,Ke.jsx)("button",{disabled:!i,className:a.pagination,type:"button",onClick:i&&f(i),children:(0,Ke.jsx)(Ac,{})}),(0,Ke.jsx)("button",{disabled:!o,className:a.pagination,type:"button",onClick:o&&f(o),children:(0,Ke.jsx)(S_,{})})]}),(0,Ke.jsxs)("div",{className:a.primaryButtons,children:[(0,Ke.jsx)($.Button,{onClick:f(n),shortKeys:["esc"],children:u("dismiss")}),(0,Ke.jsx)($.Button,{shortKeys:[8679,8629],type:"submit",children:u("add")})]})]})]})},td=uR;var cR=["{amount}"," {amount}","{date}","{email}","{iban}","{name}","{postal_code}","{street}","{tarif}","{usage}","{3_digits}","{4_digits}","{5_digits}","{6_digits}","{7_digits}","{8_digits}","{9_digits}","{10_digits}"],dR=new RegExp(cR.map(e=>`(?:${e.replace("{","\\{").replace("}","\\}")})`).join("|"));function hw(e,t){let n=e.split(dR),r=0,o=[];for(let i=0;i<n.length;i++){let s=n[i];if(o.push(s),i===n.length-1)break;if(t.indexOf(s)===-1)return e;let a=n[i+1],l=i===n.length-2;r+=s.length;let u=r;if(l){let p=a.charAt(0),d=0;do u=p?t.indexOf(p,u+1):-1,d+=1;while(u!==-1&&a.indexOf(t.slice(u))!==0);if(u===-1&&d>2)return e}else u=a&&a!==""?t.indexOf(a,r):-1;let c=u===-1?t.slice(r):t.slice(r,u);o.push(c),r=u}return o.join("")}function yw(e,t){return typeof t=="boolean"?e:e.slice(0,t)}var Sw={suggestions:[],fetchState:"idle",isInitialRequest:null},vw={default:Sw},nd=e=>t=>{var n;return((n=t.textSuggestions[e])==null?void 0:n.suggestions)??[]},xw=e=>{let t=Object.keys(e.textSuggestions).map(n=>{var r;return(r=e.textSuggestions[n])==null?void 0:r.fetchState});return t.length===0?!0:t.every(n=>n!=="done")},br=e=>e.textSuggestions,_w=e=>{let t=e.toLowerCase();return n=>{let r=n.text.toLowerCase();return r.startsWith(t)&&r.length>t.length}},rd=fe("textSuggestions/refresh"),Vt=D("textSuggestions/recommendations",async(e,t)=>{var u;let{deepdeskAPI:n}=t.extra,r=t.getState(),o=(u=r.conversation.current)==null?void 0:u.id,{textSuggestionsCount:i,inlineSuggestions:s}=r.settings,a=xi(r);if(!o)throw new Error("No current conversation to fetch text suggestions");let l=await n.getTextSuggestions(o,_a(r),e);if(e==="default"){let c=s?l.filter(_w(a)):l;t.dispatch(on(c.slice(0,i)))}return l}),Ea=D("textSuggestions/autocompletions",async(e,t)=>{var u;let{deepdeskAPI:n}=t.extra,r=t.getState(),o=(u=r.conversation.current)==null?void 0:u.id,{textSuggestionsCount:i,deanonymize:s,inlineSuggestions:a}=r.settings;if(!o)throw new Error("No current conversation to fetch text suggestions");let l=await n.getAutocompleteSuggestions(o,{..._a(r),input:e});if(!t.getState().input.text)throw new Error("Abort");return a&&(l=l.filter(_w(e))),s&&(l=l.map(c=>({...c,text:c.source!=="trie-with-typos"?hw(c.text,e):c.text}))),l=yw(l,i),t.dispatch(on(l)),l}),ww=z({name:"textSuggestions",initialState:vw,reducers:{setTextSuggestions:{reducer(e,t){let{contentType:n}=t.payload;e[n].fetchState="done",e[n].suggestions=t.payload.suggestions},prepare(e,t){return{payload:{contentType:e,suggestions:t}}}},setSuggestionState(e,t){return t.payload}},extraReducers:e=>{e.addCase(Vt.pending,(t,n)=>{let r=n.meta.arg,o=t[r]||Sw;return{...t,[r]:{...o,fetchState:"loading",isInitialRequest:o.isInitialRequest===null}}}).addCase(Vt.rejected,(t,n)=>{let r=n.meta.arg;t[r]&&(t[r].fetchState="error")}).addCase(Vt.fulfilled,(t,n)=>{let r=n.meta.arg;t[r]&&(t[r].fetchState="done",t[r].suggestions=n.payload)}).addCase(Ea.pending,t=>{t.default.fetchState="loading"}).addCase(Ea.rejected,t=>{t.default.fetchState="error"}).addCase(Ea.fulfilled,(t,n)=>{t.default.fetchState="done",t.default.suggestions=n.payload}).addCase(te,()=>vw)}}),{setTextSuggestions:bw,setSuggestionState:Ew}=ww.actions,Cw=ww.reducer;var Tw={contentType:null,suggestion:null},kw=e=>e.activeSuggestion.suggestion,Pw=e=>e.activeSuggestion.contentType,Iw=z({name:"activeSuggestion",initialState:Tw,reducers:{setActiveSuggestion(e,t){let{contentType:n,suggestion:r}=t.payload;e.contentType=n,e.suggestion=r},resetActiveSuggestion(e){e.contentType=null,e.suggestion=null}},extraReducers:e=>{e.addCase(te,()=>Tw)}}),{setActiveSuggestion:Rn,resetActiveSuggestion:Bg}=Iw.actions,Rw=Iw.reducer;var zg={};Pe(zg,{enUS:()=>pR,nlNL:()=>fR});var pR={warning:[{type:0,value:"Are you sure you want to discard the message?"}],editContentLabel:[{type:0,value:"Edit and view suggestion"}],overlayLabel:[{type:0,value:"Close dialog"}]},fR={warning:[{type:0,value:"Weet je zeker dat je de wijzigingen wilt weggooien?"}],editContentLabel:[{type:0,value:"Bewerk en bekijk suggestie"}],overlayLabel:[{type:0,value:"Sluit"}]};var mR={showTabHint:!1,inputHasFocus:!1,overlayCollapsed:!1,openOverlayWhenTyping:!1,overlayCollapsedUserOverwrite:!1};var od=({ui:e})=>e.overlayCollapsed;var Lw=z({name:"ui",initialState:mR,reducers:{setShowTabHint(e,t){e.showTabHint=t.payload},setInputHasFocus(e,t){e.overlayCollapsedUserOverwrite!==!0&&(t.payload===!0&&(e.overlayCollapsed=!1),e.inputHasFocus=t.payload)},setOverlayCollapsed(e,t){t.payload.collapse===!1&&(e.openOverlayWhenTyping=!1),!(t.payload.skipWhenInputFocus&&e.inputHasFocus)&&(e.overlayCollapsed=t.payload.collapse)},setOpenOverlayWhenTyping(e,t){e.openOverlayWhenTyping=t.payload},setOverlayCollapsedUserOverwrite(e,t){e.overlayCollapsedUserOverwrite=t.payload,e.overlayCollapsed=t.payload}}}),{setShowTabHint:Ca,setInputHasFocus:Ai,setOverlayCollapsed:Er,setOpenOverlayWhenTyping:Aw,setOverlayCollapsedUserOverwrite:Ow}=Lw.actions,Nw=Lw.reducer;var Ta=S(O()),Dw=S(b()),Mw=Ta.default.createContext(null),yo=({broadcastEvents:e,children:t})=>{let n=Ta.default.useMemo(()=>e,[]);return(0,Dw.jsx)(Mw.Provider,{value:n,children:t})},Lt=()=>{let e=(0,Ta.useContext)(Mw);if(!e)throw new Error("You should use the useBroadcastEvents within a BroadcastEventsProvider");return e};var gR={isLoggedIn:!0,loginFetchState:"idle",verifyFetchState:"idle",showLoginOverlay:!1},Ge=e=>e.auth.isLoggedIn,Fw=e=>e.auth.loginFetchState,jw=e=>e.auth.verifyFetchState,Hw=e=>e.auth.showLoginOverlay,Ln=D("auth/validate",async(e,t)=>t.extra.deepdeskAPI.isLoggedIn()),Bw=D("auth/requestLogin",async({email:e},t)=>{let{deepdeskAPI:n}=t.extra;return n.requestLoginByEmail(e)}),ka=D("auth/verifyLoginToken",async({token:e},t)=>{let{deepdeskAPI:n}=t.extra;return n.verifyLoginToken(e)}),zw=z({name:"auth",initialState:gR,reducers:{setIsLoggedIn(e,t){e.isLoggedIn=t.payload},setShowLoginOverlay(e,t){e.showLoginOverlay=t.payload}},extraReducers:e=>{e.addCase(Ln.pending,t=>{t.loginFetchState="loading"}),e.addCase(Ln.fulfilled,(t,{payload:n})=>{t.isLoggedIn=n,t.loginFetchState="done"}),e.addCase(Ln.rejected,t=>{t.loginFetchState="error",t.isLoggedIn=!1}),e.addCase(ka.pending,t=>{t.verifyFetchState="loading"}),e.addCase(ka.rejected,t=>{t.verifyFetchState="error"}),e.addCase(ka.fulfilled,(t,n)=>{n.payload.isLoggedIn?t.verifyFetchState="done":t.verifyFetchState="error"})}}),{setIsLoggedIn:Oi,setShowLoginOverlay:Uw}=zw.actions,Kw=zw.reducer;var Ug="SetActiveSuggestion",Ni="ShowLoginOverlay",Pa="UserLoggedIn",hR="UserLoggedOut",An="ApplySuggestion",Kg="ApplyImageSuggestion",yR="ShowCommandPalette",vR=e=>({[Ug]:t=>{e.dispatch(Ew(t.state)),e.dispatch(Rn({contentType:t.contentType,suggestion:t.suggestion}))},[yR]:t=>{e.dispatch($e(t.isOpen)),t.page&&e.dispatch(qe(t.page))},[Ni]:t=>{e.dispatch(Uw(t))},[Pa]:()=>{e.dispatch(Ln())},[hR]:()=>{e.dispatch(Ln())},[Kg]:t=>{e.dispatch(yc({suggestion:t.suggestion}))},[An]:t=>{e.dispatch(Bt({...t,eventMetrics:{inputType:"mouse"},replace:"selection"})),e.dispatch(wn())}}),Vw=vR;var Vg=S(b()),SR=()=>{var y;let[e,t]=(0,Ww.useState)(!1),n=R(kw),r=R(Pw),o=R(br),i=U(),s=Lt(),a=H(zg),l=()=>{n!==null&&e?window.confirm(a("warning"))&&u():u()},u=()=>{i(Bg()),i(Ai(!0)),i(rt.actions.reset())},c=(v,m)=>{i(Bg()),i(Ai(!0)),s.send(An,{text:v,suggestion:{...m,source:`${m.source||"text_recommendation"}-preview`}})};if(n===null||r===null)return null;let p=(y=o[r])==null?void 0:y.suggestions.indexOf(n),d=p===0||p===null?void 0:()=>i(Rn({contentType:r,suggestion:o[r].suggestions[p-1]})),f=p===o[r].suggestions.length-1||p===null?void 0:()=>i(Rn({contentType:r,suggestion:o[r].suggestions[p+1]}));return(0,Vg.jsx)(wi,{autoFocus:!0,isOpen:p!==null,onClose:l,onBack:l,contentAriaLabel:a("editContentLabel"),overlayAriaLabel:a("overlayLabel"),children:(0,Vg.jsx)(td,{onTouched:t,onDismiss:u,onUse:v=>c(v,n),suggestion:n,onNext:f,onPrevious:d})})},$w=SR;var id=S(q()),Wt=S(O());var Gw=S(q());var qw={root:"_root_1ukx5_1"};var Xw=S(b()),xR=({className:e,value:t,...n})=>{let r=P("TextInput",qw);return(0,Xw.jsx)("input",{className:(0,Gw.default)(e,r.root),type:"text",value:t,...n})},Ia=xR;var Wg={};Pe(Wg,{enUS:()=>_R,nlNL:()=>wR});var _R={back:[{type:0,value:"Back"}],promptTitle:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],verifyCodeTitle:[{type:0,value:"Paste the code from your email"}],verifyCodeBody:[{type:0,value:"Copy the code from the email you just received and paste it here."}],verifyCodeInputPlaceholder:[{type:0,value:"Paste link or code here"}],verifyCodeSubmitLabel:[{type:0,value:"Sign in"}],verifyCodeError:[{type:0,value:"Sign in failed. The code is probably no longer valid. Please "},{type:8,value:"login",children:[{type:0,value:"request new code"}]},{type:0,value:"."}],requestCodeTitle:[{type:0,value:"Have a code sent to your email"}],requestCodeBody:[{type:0,value:"Enter your email and request a code. If you are an existing "},{type:1,value:"productName"},{type:0,value:" user you will receive an email with a code. If you are a new user you will receive an email asking to request access to "},{type:1,value:"productName"},{type:0,value:" first."}],requestCodeInputPlaceholder:[{type:0,value:"Enter your email"}],requestCodeSubmitLabel:[{type:0,value:"Request code"}]},wR={back:[{type:0,value:"Terug"}],promptTitle:[{type:0,value:"Login bij "},{type:1,value:"productName"}],verifyCodeTitle:[{type:0,value:"Plak de code uit je email"}],verifyCodeBody:[{type:0,value:"Kopieer de code uit de email en plak deze hier."}],verifyCodeInputPlaceholder:[{type:0,value:"Plak hier de code"}],verifyCodeSubmitLabel:[{type:0,value:"Inloggen"}],verifyCodeError:[{type:0,value:"Inloggen is niet gelukt. De code is waarschijnlijk niet meer geldig. "},{type:8,value:"login",children:[{type:0,value:"Vraag een nieuwe code aan"}]},{type:0,value:"."}],requestCodeTitle:[{type:0,value:"Verstuur een login code naar je email"}],requestCodeBody:[{type:0,value:"Voer je e-mailadres in en krijg een login code. Als je een bestaande "},{type:1,value:"productName"},{type:0,value:" gebruiker bent krijg je een email met een code. Als je een nieuwe gebruiker bent wordt er een email verstuurd met een toegangsverzoek voor "},{type:1,value:"productName"},{type:0,value:"."}],requestCodeInputPlaceholder:[{type:0,value:"Typ hier je e-mailadres"}],requestCodeSubmitLabel:[{type:0,value:"Code aanvragen"}]};var Qw={root:"_root_1edpl_1",anchorButton:"_anchorButton_1edpl_5",errorMessage:"_errorMessage_1edpl_19",title:"_title_1edpl_25",subtitle:"_subtitle_1edpl_31",text:"_text_1edpl_38",input:"_input_1edpl_43",actions:"_actions_1edpl_48",button:"_button_1edpl_55",primaryButton:"_primaryButton_1edpl_70"};var ye=S(b());var bR=e=>{try{let t=new URL(e);return new URLSearchParams(t.search).get("token")||void 0}catch{return e}},ER=({agentEmail:e,isOpen:t,origin:n="",onSuccess:r,onDismiss:o})=>{let i=H(Wg),s=P("LoginTokenDialog",Qw),a=R(jw),l=U(),u=M("productName"),[c,p]=(0,Wt.useState)(e||""),[d,f]=(0,Wt.useState)(0),[y,v]=(0,Wt.useState)(""),m=(0,Wt.useCallback)(async _=>{_.preventDefault(),l(Bw({email:c})),f(1)},[n,c]),h=()=>{v(""),f(0)},g=(0,Wt.useCallback)(async _=>{_.preventDefault();let w=bR(_.target.elements.token.value);if(!w){v(i("verifyCodeError",{login:x}));return}l(ka({token:w}))},[n]),x=(0,Wt.useMemo)(()=>_=>(0,ye.jsx)("button",{type:"button","data-testid":"login-token-dialog-back-button",className:s.anchorButton,onClick:h,children:_},"back-button"),[]);return(0,Wt.useEffect)(()=>{a==="error"&&v(i("verifyCodeError",{login:x})),a==="done"&&r()},[a]),(0,ye.jsx)(wi,{autoFocus:!0,isOpen:t,contentAriaLabel:i("promptTitle",{productName:u}),overlayAriaLabel:i("promptTitle",{productName:u}),onClose:o,onBack:o,children:(0,ye.jsxs)("div",{className:s.root,children:[(0,ye.jsx)("h1",{className:s.title,children:i("promptTitle",{productName:u})}),d===0&&(0,ye.jsxs)("form",{onSubmit:m,children:[(0,ye.jsx)("h2",{className:s.subtitle,children:i("requestCodeTitle")}),(0,ye.jsx)("p",{className:s.text,children:i("requestCodeBody",{productName:u})}),(0,ye.jsx)(Ia,{className:s.input,name:"email",placeholder:i("requestCodeInputPlaceholder"),value:c,onChange:_=>p(_.target.value)}),(0,ye.jsx)("div",{className:s.actions,children:(0,ye.jsx)("button",{type:"submit",className:(0,id.default)(s.button,s.primaryButton),children:i("requestCodeSubmitLabel")})})]}),d===1&&(0,ye.jsxs)("form",{onSubmit:g,children:[(0,ye.jsx)("h2",{className:s.subtitle,children:i("verifyCodeTitle")}),(0,ye.jsx)("p",{className:s.text,children:i("verifyCodeBody")}),(0,ye.jsx)(Ia,{className:s.input,name:"token",placeholder:i("verifyCodeInputPlaceholder"),disabled:["loading","done"].includes(a)}),y&&(0,ye.jsx)("div",{className:s.errorMessage,children:y}),(0,ye.jsxs)("div",{className:s.actions,children:[(0,ye.jsx)("button",{type:"button",className:(0,id.default)(s.button),onClick:h,children:i("back")}),(0,ye.jsx)("button",{type:"submit",className:(0,id.default)(s.button,s.primaryButton),disabled:["loading","done"].includes(a),children:i("verifyCodeSubmitLabel")})]})]})]})})},Yw=ER;var Jw=S(b()),CR=()=>{let e=R(Hw),t=R(nw),n=M("adminUrl"),r=Lt(),o=()=>r.send(Ni,!1),i=()=>{r.send(Ni,!1),r.send(Pa)};return(0,Jw.jsx)(Yw,{isOpen:e,agentEmail:t==null?void 0:t.agentEmail,origin:n,onDismiss:o,onSuccess:i})},Zw=CR;var I1=S(Gg()),Xe=S(O());var KR={data:null,fetchState:"idle"},r1=e=>e.contentTypes.data,Ra=D("contentTypes/getContentTypes",async(e,t)=>t.extra.deepdeskAPI.getContentTypes()),VR=z({name:"contentTypes",initialState:KR,reducers:{},extraReducers:e=>{e.addCase(Ra.pending,t=>{t.fetchState="loading"}).addCase(Ra.rejected,t=>{t.fetchState="error"}).addCase(Ra.fulfilled,(t,n)=>{t.fetchState="done",t.data=n.payload})}}),o1=VR.reducer;function La(e){let t=document.createElement("textarea");t.value=e,t.style.position="fixed",t.style.left="-999999px",t.style.top="-999999px",document.body.appendChild(t),t.focus(),t.select(),document.execCommand("copy"),t.remove()}var i1=S(O());function s1(e,t){(0,i1.useEffect)(()=>{let n=r=>{var o;((o=navigator==null?void 0:navigator.platform)!=null&&o.toLowerCase().includes("mac")?r.metaKey:r.ctrlKey)&&r.key===e&&(r.preventDefault(),r.stopPropagation(),t())};return document.addEventListener("keydown",n),()=>{document.removeEventListener("keydown",n)}},[])}var Aa=S(O());var a1={data:null,fetchState:"idle"},sd=e=>{var i;let t=[],{visitorName:n}=e.info.visitorInfo??{},{agentName:r,agentNickname:o}=e.info.agentInfo??{};return r&&r!==n&&t.push(r),o&&o!==n&&t.push(o),((i=e.entities.data)==null?void 0:i.filter(s=>!t.includes(s.text)))??null},$t=D("entities/getEntities",async(e,t)=>{let{deepdeskAPI:n,dynamicThunkObject:r}=t.extra;if(!r.conversationQuery)return Promise.resolve([]);let o=r.conversationQuery,i=await o();return i.length===0?Promise.resolve([]):n.getEntities(i)}),WR=e=>e.filter((t,n)=>n===e.findIndex(r=>r.text===t.text)),$R=z({name:"entities",initialState:a1,reducers:{},extraReducers:e=>{e.addCase($t.pending,t=>{t.fetchState="loading"}).addCase($t.rejected,t=>{t.fetchState="error"}).addCase($t.fulfilled,(t,n)=>{t.fetchState="done",t.data=WR(t.data?[...t.data,...n.payload]:n.payload)}).addCase(te,()=>a1)}}),l1=$R.reducer;var Xg={};Pe(Xg,{enUS:()=>qR,nlNL:()=>GR});var qR={noResults:[{type:0,value:"No entities have been found"}],copy:[{type:0,value:"Copy"}],use:[{type:0,value:"Use"}]},GR={noResults:[{type:0,value:"Er zijn geen entiteiten gevonden"}],copy:[{type:0,value:"Kopieer"}],use:[{type:0,value:"Gebruik"}]};var u1={root:"_root_17kae_1",empty:"_empty_17kae_5"};var vo=S(b()),XR=({onCopy:e,onUse:t})=>{let n=(0,Aa.useRef)(null),r=P("EntitiesList",u1),o=H(Xg),i=R(sd),s=U();return(0,Aa.useEffect)(()=>{s($t())},[]),(0,Aa.useEffect)(()=>{n.current&&n.current.focus()},[n]),(0,vo.jsxs)("div",{className:r.root,ref:n,tabIndex:-1,children:[i&&i.length>0&&(0,vo.jsx)($.ActionsBar,{primaryLabel:o("copy"),secondaryLabel:o("use"),onPrimary:(a,l)=>e(i[l]),onSecondary:(a,l)=>t(i[l]),list:i.map(a=>({text:a.text,type:a.label,primaryAction:"copy",secondaryAction:"use"})),children:(0,vo.jsx)($.List,{children:i.map((a,l)=>(0,vo.jsx)($.ListItem,{index:l,closeOnSelect:!0,onClick:()=>e(a),children:a.text},a.text))},"entities")}),i&&i.length===0&&(0,vo.jsx)("p",{className:r.empty,children:o("noResults")})]})},c1=XR;var qt=S(O());var d1={data:null,fetchState:"idle"},p1=e=>e.summary.data,f1=e=>e.summary.fetchState==="error",On=D("summary/getSummary",async(e,t)=>{var c,p,d;let n=t.getState().profile.data,r=(c=t.getState().conversation.current)==null?void 0:c.sessionId,o=(d=(p=t.getState().info)==null?void 0:p.agentInfo)==null?void 0:d.agentId;if(!n)throw new Error("Profile is not defined");let{deepdeskAPI:i,dynamicThunkObject:s}=t.extra;if(!s.conversationQuery)return Promise.reject(new Error("setConversationQuery method is not defined"));let a=s.conversationQuery,l=await a();if(l.length===0)return Promise.reject(new Error("No messages are included"));let u=await i.getSummary(l,{externalConversationId:r,agentId:o,promptInstruction:n.summarizerPromptInstruction,model:n.summarizerModel});return u?{summary:u}:Promise.reject(new Error("Summary is not provided"))}),QR=z({name:"summary",initialState:d1,reducers:{},extraReducers:e=>{e.addCase(On.pending,t=>{t.data=null,t.fetchState="loading"}).addCase(On.rejected,t=>{t.data=null,t.fetchState="error"}).addCase(On.fulfilled,(t,n)=>{t.fetchState="done",n.payload&&(t.data=n.payload.summary)}).addCase(te,()=>d1)}}),m1=QR.reducer;var Qg={};Pe(Qg,{enUS:()=>YR,nlNL:()=>ZR});var YR={copy:[{type:0,value:"Copy"}],error:[{type:0,value:"Could not generate a summary"}],loading:[{type:0,value:"Generating summary, this may take a few moments."}]},ZR={copy:[{type:0,value:"Kopieer"}],error:[{type:0,value:"Kon helaas geen samenvatting genereren."}],loading:[{type:0,value:"Samenvatting wordt gemaakt, dit kan even duren."}]};var g1={root:"_root_6ahh3_1",actions:"_actions_6ahh3_5",main:"_main_6ahh3_11",textInput:"_textInput_6ahh3_15",loading:"_loading_6ahh3_34",error:"_error_6ahh3_38"};var Nn=S(b()),JR=({onCopy:e})=>{let t=(0,qt.useRef)(null),n=P("SummaryForm",g1),[r,o]=(0,qt.useState)(""),i=H(Qg),s=R(p1),a=R(f1),l=U(),u=()=>{l(Be({name:"summary copied to clipboard",data:{originalText:s,finalText:r},options:{includeConversationData:!0}})),e(r)},c=()=>{let p=document.getSelection();p&&l(Be({name:"summary copied to clipboard",data:{originalText:s,finalText:p==null?void 0:p.toString()},options:{includeConversationData:!0}}))};return(0,qt.useEffect)(()=>{l(On())},[]),(0,qt.useEffect)(()=>{o(s||"")},[s]),(0,qt.useEffect)(()=>{t.current&&s&&t.current.focus()},[t,s]),(0,qt.useEffect)(()=>{let p=d=>{d.key==="Enter"&&d.shiftKey&&u()};return document.addEventListener("keydown",p),()=>{document.removeEventListener("keydown",p)}},[r]),(0,Nn.jsx)("div",{className:n.root,tabIndex:-1,children:a?(0,Nn.jsx)("p",{className:n.error,children:i("error")}):(0,Nn.jsxs)(qt.Fragment,{children:[(0,Nn.jsx)("div",{className:n.main,children:(0,Nn.jsx)("textarea",{placeholder:s?void 0:i("loading"),disabled:!s,className:n.textInput,ref:t,value:r,onCopy:c,onChange:p=>o(p.target.value)})}),(0,Nn.jsx)("div",{className:n.actions,children:(0,Nn.jsx)($.Button,{shortKeys:[8679,8629],onClick:u,children:i("copy")})})]})})},h1=JR;var Oa={};Pe(Oa,{enUS:()=>eL,nlNL:()=>tL});var eL={personalCollectionLink:[{type:0,value:"Go to Personal Collection"}],searchPlaceholder:[{type:0,value:"Start typing to search..."}],urlSuggestions:[{type:0,value:"Link suggestions"}],personalSuggestions:[{type:0,value:"Personal suggestions"}],pinnedMessages:[{type:0,value:"Pinned messages"}],imageSuggestions:[{type:0,value:"Images"}],typePlaceholder:[{type:0,value:"All types"}],navigation:[{type:0,value:"Navigation"}],entitiesClipboard:[{type:0,value:"Conversation clipper"}],entitiesTitle:[{type:0,value:"Copy to your clipboard"}],summaryClipboard:[{type:0,value:"Summarize conversation"}],summaryTitle:[{type:0,value:"Conversation summary"}],knowledgeAssist:[{type:0,value:"Knowledge assist"}],commands:[{type:0,value:"Commands"}],use:[{type:0,value:"Use"}],preview:[{type:0,value:"Preview"}],warning:[{type:0,value:"Are you sure you want to discard the message?"}]},tL={personalCollectionLink:[{type:0,value:"Ga naar persoonlijke collectie"}],searchPlaceholder:[{type:0,value:"Begin met typen om te zoeken..."}],personalSuggestions:[{type:0,value:"Persoonlijke suggesties"}],urlSuggestions:[{type:0,value:"Link suggesties"}],imageSuggestions:[{type:0,value:"Afbeeldingen"}],navigation:[{type:0,value:"Navigatie"}],typePlaceholder:[{type:0,value:"Alle types"}],pinnedMessages:[{type:0,value:"Actueel"}],entitiesClipboard:[{type:0,value:"Klembord"}],entitiesTitle:[{type:0,value:"Kopieer naar klembord"}],summaryClipboard:[{type:0,value:"Gesprek samenvatten"}],summaryTitle:[{type:0,value:"Gesprek samenvatting"}],knowledgeAssist:[{type:0,value:"Knowledge assist"}],commands:[{type:0,value:"Acties"}],use:[{type:0,value:"Gebruik"}],preview:[{type:0,value:"Bewerk"}],warning:[{type:0,value:"Weet je zeker dat je de wijzigingen wilt weggooien?"}]};var Cr=S(O());var Yg={};Pe(Yg,{enUS:()=>nL,nlNL:()=>rL});var nL={use:[{type:0,value:"Use"}],loading:[{type:0,value:"Loading..."}],error:[{type:0,value:"Something went wrong, please try again later."}],anotherQuestion:[{type:0,value:"Send a message..."}],reset:[{type:0,value:"Reset conversation"}]},rL={use:[{type:0,value:"Gebruik"}],loading:[{type:0,value:"Laden..."}],error:[{type:0,value:"Er ging iets mis, probeer het later opnieuw."}],anotherQuestion:[{type:0,value:"Stuur een bericht..."}],reset:[{type:0,value:"Reset gesprek"}]};var y1={root:"_root_1g4pq_1",title:"_title_1g4pq_9",empty:"_empty_1g4pq_20",status:"_status_1g4pq_24",form:"_form_1g4pq_30",input:"_input_1g4pq_43",submit:"_submit_1g4pq_55",question:"_question_1g4pq_63",answer:"_answer_1g4pq_67",alignRight:"_alignRight_1g4pq_73"};var oL={data:null,fetchState:"idle"},v1=e=>{var t;return(t=e.knowledgeAssistant)==null?void 0:t.data},Na=D("knowledgeAssistant/getKnowledgeAssistant",async(e,t)=>{var s;let{deepdeskAPI:n}=t.extra,r=t.getState(),o=r.conversation.current;if(!o||!o.profileCode)throw new Error("No conversation of conversation profileCode found");let i=(s=r.profile.data)==null?void 0:s.knowledgeAssistant;return i?n.getKnowledgeAssistant(i):null}),iL=z({name:"knowledgeAssistant",initialState:oL,reducers:{},extraReducers:e=>{e.addCase(Na.pending,t=>{t.fetchState="loading"}).addCase(Na.rejected,t=>{t.fetchState="error"}).addCase(Na.fulfilled,(t,n)=>{t.fetchState="done",t.data=n.payload})}}),S1=iL.reducer;var Zg={data:[],fetchState:"idle"},x1=e=>{var t;return(t=e.answer)==null?void 0:t.data},_1=e=>e.answer.fetchState,Di=fe("answer/resetKnowledgeSearch"),Mi=D("answer/getAnswer",async(e,t)=>{var l,u,c;let{deepdeskAPI:n}=t.extra,r=t.getState().answer.data,o=v1(t.getState()),i=(l=t.getState().conversation.current)==null?void 0:l.sessionId,s=(c=(u=t.getState().info)==null?void 0:u.agentInfo)==null?void 0:c.agentId;if(!o)throw new Error("KnowledgeAssistant is not defined");let a=await n.knowledgeAssist({promptInstruction:o.prompt,question:e},r,o.code,{agentId:s,conversationId:i});return{question:e,answer:a}}),sL=z({name:"answer",initialState:Zg,reducers:{},extraReducers:e=>{e.addCase(Mi.pending,t=>{t.fetchState="loading"}).addCase(Mi.rejected,t=>{t.fetchState="error"}).addCase(Mi.fulfilled,(t,n)=>{t.fetchState="done",t.data=[...t.data,n.payload]}).addCase(te,()=>Zg).addCase(Di,()=>Zg)}}),w1=sL.reducer;var Ma=S(b()),b1=()=>(0,Ma.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 512 512","aria-labelledby":"paperPlaneTitle",children:[(0,Ma.jsx)("title",{id:"paperPlaneTitle",children:"PaperPlane"}),(0,Ma.jsx)("path",{d:"M498.1 5.6c10.1 7 15.4 19.1 13.5 31.2l-64 416c-1.5 9.7-7.4 18.2-16 23s-18.9 5.4-28 1.6L284 427.7l-68.5 74.1c-8.9 9.7-22.9 12.9-35.2 8.1S160 493.2 160 480V396.4c0-4 1.5-7.8 4.2-10.7L331.8 202.8c5.8-6.3 5.6-16-.4-22s-15.7-6.4-22-.7L106 360.8 17.7 316.6C7.1 311.3 .3 300.7 0 288.9s5.9-22.8 16.1-28.7l448-256c10.7-6.1 23.9-5.5 34 1.4z"})]});var it=S(b()),aL=({onUse:e,onResetQuestion:t,question:n})=>{let[r,o]=Cr.default.useState(""),{setSelected:i}=_r(),s=(0,Cr.useRef)(null),a=P("EntitiesList",y1),l=H(Yg),u=U(),c=R(x1),p=R(_1),d=async y=>{y.preventDefault(),y.stopPropagation(),r!==""&&u(Mi(r))},f=(y,v)=>{u(Be({name:"knowledge assist source viewed",data:{question:v,sourceViewed:y.url||y.name},options:{includeConversationData:!0}}))};return(0,Cr.useEffect)(()=>{var y;n&&p==="idle"?u(Mi(n)):(y=s.current)==null||y.focus()},[s,p]),(0,Cr.useEffect)(()=>{p==="done"&&(u(Be({name:"knowledge assist question answered",data:{question:r||n,sources:c[c.length-1].answer.sources,answer:c[c.length-1].answer.answer,isFollowUpQuestion:c.length>1},options:{includeConversationData:!0}})),i(c.length-1),o(""))},[p,c]),(0,Cr.useEffect)(()=>{s.current&&s.current.scrollIntoView({behavior:"smooth"})},[s,c]),(0,it.jsxs)("div",{className:a.root,children:[c.length>0&&(0,it.jsx)("div",{className:a.alignRight,children:(0,it.jsx)($.Button,{onClick:t,children:l("reset")})}),(0,it.jsxs)($.ActionsBar,{list:c.map(({answer:y})=>({text:y.answer,type:"answer"})),primaryLabel:l("use"),onPrimary:y=>e(y.text),children:[c.map(({question:y,answer:v},m)=>(0,it.jsx)($.List,{children:(0,it.jsx)($.ListItem,{"data-testid":"knowledge-search-answer",index:m,description:v.answer,closeOnSelect:!0,onClick:()=>e(v.answer),onSourceClick:h=>f(h,y),sources:v.sources,styles:{title:a.question,description:a.answer},children:y})},`${v.answer}_${m}`)),p==="loading"&&(0,it.jsx)("p",{className:a.status,children:l("loading")}),p==="error"&&(0,it.jsx)("p",{className:a.status,children:l("error")}),(0,it.jsxs)("form",{className:a.form,onSubmit:d,children:[(0,it.jsx)("input",{ref:s,placeholder:l("anotherQuestion"),className:a.input,type:"text",value:r,onFocus:()=>{i(-1)},onChange:y=>{i(-1),o(y.target.value)}}),(0,it.jsx)("button",{type:"submit",className:a.submit,children:(0,it.jsx)(b1,{})})]})]})]})},E1=aL;var lL={data:null,fetchState:"idle"},Tr=e=>e.profile.data,ad=e=>e.profile.data?e.profile.data.uiConfig.widget.types.filter(t=>t.isActive):[],Da=D("profile/getProfile",async(e,t)=>{var i;let{deepdeskAPI:n}=t.extra,r=t.getState(),o=r.conversation.current;if(!o||!o.profileCode)throw new Error("No conversation of conversation profileCode found");return((i=r.profile.data)==null?void 0:i.code)===o.profileCode?r.profile.data:n.getProfile(o.profileCode)}),uL=z({name:"profile",initialState:lL,reducers:{},extraReducers:e=>{e.addCase(Da.pending,t=>{t.fetchState="loading"}).addCase(Da.rejected,t=>{t.fetchState="error"}).addCase(Da.fulfilled,(t,n)=>{t.fetchState="done",t.data=n.payload})}}),C1=uL.reducer;var T1=S(O());var So=S(b()),cL=({commands:e,onClick:t,onEdit:n})=>{var c,p,d;let r=U(),o=H(Oa),i=R(Tr),s=R(br),a=((d=(p=(c=i==null?void 0:i.uiConfig)==null?void 0:c.search)==null?void 0:p.initialTypes)==null?void 0:d.filter(({isActive:f})=>f))||[],l=0,u=a.map(({type:f})=>{var y;return(y=s[f])==null?void 0:y.suggestions.map(v=>({text:v.text||v.url||v.message,type:f}))}).flat(1);return(0,T1.useEffect)(()=>{a.forEach(({type:f})=>{(!s[f]||s[f].suggestions.length===0)&&r(Vt(f))})},[]),(0,So.jsxs)($.ActionsBar,{list:[...e.map(f=>({text:f.label,type:"command"})),...u],primaryLabel:o("use"),secondaryLabel:o("preview"),onPrimary:({text:f},y)=>t(f,u[y]),onSecondary:(f,y)=>{let v=y-e.length;n(u[v],s[u[v].type].suggestions)},children:[e.length>0&&(0,So.jsx)($.List,{heading:o("commands"),children:e.map((f,y)=>(0,So.jsx)($.ListItem,{index:y,closeOnSelect:!1,onClick:f.onClick,children:f.label},f.label))}),a.map(({type:f,title:y})=>{var v;return(0,So.jsx)($.List,{heading:y,orientation:"vertical",children:(v=s[f])==null?void 0:v.suggestions.map(m=>(l++,(0,So.jsx)($.ListItem,{index:l+e.length-1,closeOnSelect:!1,description:m.text,onClick:()=>t(m.text,m),"data-testid":"search-overlay-suggestion",children:m.title},`${m.id}-${m.text}`)))},f)})]})},k1=cL;var _e=S(b()),dL=200,pL=5,fL=4,mL=e=>e.reduce((t,n)=>[...t,...n.list.map(r=>({...r,type:n.value}))],[]),P1=(e,t)=>!t||e.toLowerCase().includes(t.toLowerCase()),gL=()=>{let e=U(),t=Lt(),n=H(Oa),[r,o]=(0,Xe.useState)(!1),[i,s]=(0,Xe.useState)(""),a=R(aw),l=R(Tr),[u,c]=(0,Xe.useState)(null),[p,d]=(0,Xe.useState)([]),[f,y]=(0,Xe.useState)(),v=R(Ge),m=M("showSearch"),h=M("showEntitiesCommand"),g=M("showSummaryCommand"),x=M("showKnowledgeSearch"),_=M("showImageSearch"),w=M("searchTriggerKey"),E=R(r1),C=R(lw),I=R(sw),k=L=>Co(C.filter(J=>J.type===L.toUpperCase()),L),K=[{value:"PERSONAL",label:n("personalSuggestions"),list:k("PERSONAL"),lineClamp:!1,listOrientation:"vertical",shouldShow:!0},{value:"URL",label:n("urlSuggestions"),list:k("URL"),lineClamp:!1,listOrientation:"vertical",shouldShow:!0},{value:"STICKYMESSAGE",label:n("pinnedMessages"),list:k("STICKYMESSAGE"),lineClamp:!1,listOrientation:"vertical",shouldShow:!0},{value:"IMAGE",label:n("imageSuggestions"),lineClamp:!1,list:k("IMAGE"),listOrientation:"horizontal",shouldShow:_}].filter(L=>L.shouldShow),N=[{label:n("entitiesClipboard"),onClick:()=>e(qe("entities")),shouldShow:h&&P1(n("entitiesClipboard"),i)},{label:n("summaryClipboard"),onClick:()=>e(qe("summary")),shouldShow:g&&P1(n("summaryClipboard"),i)},{label:i?`${n("knowledgeAssist")}: ${i}`:n("knowledgeAssist"),onClick:()=>e(qe("knowledgeAssist")),shouldShow:x}].filter(L=>L.shouldShow),B=(E==null?void 0:E.map(L=>({value:L.code.toUpperCase(),label:`${L.name}s`,list:k(L.code.toUpperCase()),listOrientation:"vertical",lineClamp:!0})))||[],be=(0,Xe.useCallback)((0,I1.default)((L,J)=>{e(go({query:L,type:J,tags:["search-overlay"]}))},dL),[]),Ar=mL([...B,...K]),Ze=(0,Xe.useCallback)((L,J)=>{e(qe("edit")),c({...L,searchTerm:void 0}),d(J)},[e,u,B]),Or=(0,Xe.useCallback)((L,J)=>{switch(J.type){case"IMAGE":t.send(Kg,{suggestion:J});break;default:t.send(An,{text:L,suggestion:J})}e($e(!1))},[e]),Wi=L=>{La(L.text),e(Be({name:"entity copied",data:{entity:L,type:"copy"}})),e($e(!1))},Nr=(0,Xe.useCallback)(L=>{e(Be({name:"suggestion feedback",data:{text:L.text,source:"search",context:i},options:{includeConversationData:!0}}))},[i]),Ga=L=>{t.send(An,{text:L,suggestion:{source:"knowledge-assist",text:L}}),e(Be({name:"answer used",data:{originalText:L},options:{includeConversationData:!0}})),s(""),e(qe("search")),e(Di()),e($e(!1))},Xa=L=>{La(L),e($e(!1))},$i=L=>{t.send(An,{text:L.text,suggestion:{source:"entity",text:L.text}}),e($e(!1))},qi=u===null||p.indexOf(u)-1<0?void 0:()=>c(p[p.indexOf(u)-1]),Mr=u===null||p.indexOf(u)===p.length-1?void 0:()=>c(p[p.indexOf(u)+1]);function Co(L,J){return L.slice(0,f?10:J.toLowerCase()==="image"?fL:pL)}function jd(L,J,gt){return J.reduce((cn,Un)=>gt&&f===gt?Un.length+cn:Co(Un,gt).length+cn,L)}function Xt(L){return J=>{r?window.confirm(n("warning"))&&(L(J),o(!1)):L(J)}}return(0,Xe.useEffect)(()=>{i?be(i,f):e(Yc())},[i,f]),(0,Xe.useEffect)(()=>{a==="search"&&e(Di())},[a]),(0,Xe.useEffect)(()=>{v&&e(Ra())},[v]),s1(w,()=>e($e(!0))),!m||!l?null:(0,_e.jsxs)($,{placeholder:n("searchPlaceholder"),typePlaceholder:n("typePlaceholder"),onChangeSearch:s,onChangeOpen:Xt(L=>e($e(L))),onChangeType:L=>y(L),onChangePage:Xt(L=>e(qe(L))),selectedType:f,search:i,page:a,isOpen:I,types:[...B,...K],children:[(0,_e.jsxs)($.Page,{id:"search",children:[i.length===0&&(0,_e.jsx)(k1,{commands:N,onClick:Or,onEdit:Ze}),i.length>0&&(0,_e.jsxs)($.ActionsBar,{list:[...N.map(L=>({text:L.label,type:"command"})),...Ar.map(L=>({text:L.text||L.url||L.message,type:L.type}))],primaryLabel:n("use"),secondaryLabel:n("preview"),onPrimary:({text:L},J)=>Or(L,Ar[J]),onSecondary:(L,J)=>{let gt=Ar[J-N.length];!gt||!gt.type||Ze(gt,k(gt.type))},children:[N.length>0&&(0,_e.jsx)($.List,{heading:n("commands"),children:N.map((L,J)=>(0,_e.jsx)($.ListItem,{index:jd(J,[],"commands"),closeOnSelect:!1,onClick:L.onClick,children:L.label},L.label))}),[...B,...K].map(({value:L,label:J,list:gt,lineClamp:cn,listOrientation:Un},Mh)=>(0,_e.jsx)($.List,{heading:J,orientation:Un==="horizontal"?"horizontal":"vertical",children:Co(gt,L).map((ce,Dr)=>(0,_e.jsx)($.ListItem,{index:jd(N.length+Dr,[...B,...K].slice(0,Mh).map(({list:ME})=>ME),L),closeOnSelect:!1,lineClamp:cn,onClick:()=>Or(ce.text,ce),description:L!=="IMAGE"?ce.title&&ce.text:void 0,onFeedback:L!=="IMAGE"?()=>Nr(ce):void 0,children:L==="IMAGE"?(0,_e.jsx)($.Image,{title:ce.title||ce.text,src:ce.image}):ce.title||ce.text},`${ce.id}-${ce.text}`))},L))]})]}),(0,_e.jsx)($.Page,{id:"edit",onDismiss:Xt(()=>{e(qe("search")),c(null)}),children:u&&(0,_e.jsx)(td,{suggestion:u,onTouched:o,onDismiss:()=>{o(!1),e(qe("search")),c(null),d([])},onNext:Mr,onPrevious:qi,onUse:L=>{e(qe("search")),Or(L,{...u,source:`${u.source||"text_recommendation"}-preview`}),e($e(!1)),d([]),c(null)}})}),(0,_e.jsx)($.Page,{id:"entities",title:n("entitiesTitle"),onDismiss:Xt(()=>{e(qe("search"))}),children:(0,_e.jsx)(c1,{onUse:$i,onCopy:Wi})}),(0,_e.jsx)($.Page,{id:"summary",title:n("summaryTitle"),onDismiss:Xt(()=>{e(qe("search"))}),children:(0,_e.jsx)(h1,{onCopy:Xa})}),(0,_e.jsx)($.Page,{id:"knowledgeAssist",title:n("knowledgeAssist"),onDismiss:Xt(()=>{e(Di()),e(qe("search"))}),children:(0,_e.jsx)(E1,{question:i,onUse:Ga,onResetQuestion:()=>{e(Di()),s("")}})})]})},R1=gL;var Fi=S(b()),hL=()=>{let e=M("showSearch"),t=M("isEmbedded");return(0,Fi.jsxs)(L1.Fragment,{children:[e&&(0,Fi.jsx)(R1,{}),(0,Fi.jsx)($w,{}),t&&(0,Fi.jsx)(Zw,{})]})},A1=hL;var D1=S(q());var ld=S(b()),O1=({className:e})=>(0,ld.jsx)("svg",{version:"1.1",xmlns:"http://www.w3.org/2000/svg",xmlnsXlink:"http://www.w3.org/1999/xlink",x:"0px",y:"0px",viewBox:"0 0 512 512",xmlSpace:"preserve",className:e,children:(0,ld.jsx)("g",{children:(0,ld.jsx)("path",{d:`M163.4,233h186v-70c0-25.6-9.4-47.8-27.3-65.7C304.2,79.4,282,70,256.4,70s-47.8,9.4-65.7,27.3
20
20
  c-17.9,17.9-27.3,40.1-27.3,65.7C163.4,163,163.4,233,163.4,233z M465.5,267.9V477c0,9.4-3.4,17.9-10.2,24.7
21
21
  c-6.8,6.8-15.4,10.2-24.7,10.2h-349c-9.4,0-17.9-3.4-24.7-10.2c-6.8-6.8-10.2-15.4-10.2-24.7V267.9c0-9.4,3.4-17.9,10.2-24.7
22
22
  c6.8-6.8,15.4-10.2,24.7-10.2h11.9v-70c0-44.4,16.2-82.8,47.8-115.2S212.1,0,256.4,0s82.8,16.2,115.2,47.8
23
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 Jg=S(b()),yL={green:"#0A5E52",pink:"#CD8EF2",red:"#DF341D",yellow:"#DEBD00"},N1=({className:e,color:t})=>(0,Jg.jsx)("svg",{className:e,viewBox:"0 0 345 345",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:(0,Jg.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:yL[t||"pink"]})});var M1={root:"_root_1tvv4_1",text:"_text_1tvv4_18",isLoggedIn:"_isLoggedIn_1tvv4_25",isLoggedOut:"_isLoggedOut_1tvv4_29",icon:"_icon_1tvv4_39",logo:"_logo_1tvv4_44",lock:"_lock_1tvv4_49"};var eh={};Pe(eh,{enUS:()=>vL,nlNL:()=>SL});var vL={signin:[{type:0,value:"Sign in to "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Search"}]},SL={signin:[{type:0,value:"Log in bij "},{type:1,value:"productName"}],search:[{type:1,value:"productName"},{type:0,value:" Zoeken"}]};var xo=S(b()),F1=({onLogIn:e})=>{let t=H(eh),n=M("floatingMenu"),r=M("productName"),o=U(),i=R(Ge),s=P("FloatingMenu",M1);if(i===null||n===!1)return null;let a=()=>{i===!0?o($e(!0)):e()};return(0,xo.jsxs)("button",{className:(0,D1.default)(s.root,{[s.isLoggedIn]:i,[s.isLoggedOut]:!i}),onClick:a,children:[(0,xo.jsx)("div",{className:s.text,children:t(i?"search":"signin",{productName:r})}),(0,xo.jsxs)("div",{className:s.icon,children:[(0,xo.jsx)(N1,{className:s.logo,color:"pink"}),i===!1&&(0,xo.jsx)(O1,{className:s.lock})]})]})};var dd=S(O());function ji(e){let{showMidSentenceSuggestions:t,showSuggestionsBeforePattern:n,showSuggestionsAfterPattern:r}=e.settings,{text:o,selection:i}=e.input.userCommitted;return i.start!==i.end?!1:i.end>=o.length?!0:t?n&&new RegExp(n).test(o.substring(i.end))||r&&new RegExp(r).test(o.substring(0,i.end))?!0:n===!1&&r===!1:!1}var ud=S(O());var Hi=S(O());var j1=S(O());function H1(e,t,n){(0,j1.useEffect)(()=>{let r=e.current;return r?(r.addEventListener(t,n),()=>{r.removeEventListener(t,n)}):()=>{}},[e,t,n])}var B1={root:"_root_4u430_1",actions:"_actions_4u430_8",badge:"_badge_4u430_15",formattedText:"_formattedText_4u430_19"};var _o=S(b()),_L=["search","personal-collection-search","search-autocomplete"];function wL(e,t,n,r={}){let o="";return _L.includes(t)?o=B_(kg(e,n,{stripAgentPart:!0}),r.searchKeywords??[n]):o=kg(e,n,r),r.placeholders===!0&&(o=z_(o)),o}var bL=()=>{},EL=({index:e,selected:t,suggestion:n,onFeedback:r})=>{let o=M("inlineSuggestions"),i=R(xi),s=U(),a=P("TextSuggestion",B1),l=(0,Hi.useRef)(null);(0,Hi.useEffect)(()=>{let c=setTimeout(()=>{s(e_({text:n.text,suggestion:n}))},500);return()=>{clearTimeout(c)}},[n]),H1(l,"click",()=>{s(vr(e)),s(Bt({suggestion:n,text:n.text,eventMetrics:{inputType:"mouse"},replace:"until-selection-end"}))});let u=(0,Hi.useMemo)(()=>wL(n.text,n.source,i,{stripAgentPart:o,placeholders:!0,searchKeywords:n.searchKeywords}),[o,n.text,n.source,i,n.searchKeywords]);return n.source==="gpt"&&!o?null:(0,_o.jsxs)("div",{className:a.root,onMouseEnter:()=>s(vr(e)),children:[(0,_o.jsx)(oe,{ref:l,as:"button","data-testid":"suggestions-overlay-item",selected:t,onClick:bL,children:(0,_o.jsx)(Cn,{containerTagName:"div",noWrap:!1,tagName:"span",className:a.formattedText,content:u})}),t&&r&&(0,_o.jsx)("div",{className:a.actions,children:(0,_o.jsx)(Gc,{onFeedback:()=>r(n),suggestion:n.text})})]})},z1=EL;var th=S(b()),CL=({onFeedback:e,suggestions:t,selectedIndex:n,reverse:r})=>{let o=(0,ud.useMemo)(()=>{let i=t.map((s,a)=>(0,th.jsx)(z1,{index:a,selected:a===n,suggestion:s,onFeedback:e},`${s.text}-${s.source}`));return r?i.reverse():i},[t,n,r]);return(0,th.jsx)(ud.Fragment,{children:o})},cd=CL;var U1={root:"_root_otdbu_1",paper:"_paper_otdbu_11"};var Fa=S(b()),TL=({textSuggestions:e,selectedIndex:t})=>{let n=(0,dd.useRef)(null),r=P("InlineSuggestionsOverlay",U1),o=R(ji),i=U(),s=R(Ge),a=R(Si),l=R(od),u=M("showTextSuggestions");return Ti(()=>{i(Er({collapse:!0,skipWhenInputFocus:!0}))}),(0,dd.useEffect)(()=>{let c=n.current;if(!c||!c.parentElement)return;c.parentElement.style.left="0px";let p=c.getBoundingClientRect();c.parentElement.style.left=`${Math.min(window.innerWidth-4-p.right,0)}px`}),l||!o||!u||e.length===0||s!==!0||a===!1?null:(0,Fa.jsx)("div",{className:r.root,"data-variant":"inline",children:(0,Fa.jsx)("div",{ref:n,className:r.paper,children:(0,Fa.jsx)(xt,{children:(0,Fa.jsx)(cd,{suggestions:e,selectedIndex:t})})})})},kL=({input:e})=>({selectedIndex:e.selectedSuggestionIndex,textSuggestions:e.textSuggestions}),K1=xn(kL)(TL);var ja=S(b()),PL=({children:e})=>{let n=M("locale").replace("-","");return(0,ja.jsx)(cg.Provider,{value:n,children:e})},IL=({store:e,customStyles:t={},children:n})=>(0,ja.jsx)(Wm,{store:e,children:(0,ja.jsx)(PL,{children:(0,ja.jsx)(Xi.Provider,{value:t,children:n})})}),wo=IL;var fd=S(q()),Bi=S(O());var V1=S(O());function W1(e,t){let[n,r]=(0,V1.useState)(()=>{if(typeof window>"u")return t;try{let i=window.localStorage.getItem(e);return i?JSON.parse(i):t}catch(i){return j.error(i),t}});return[n,i=>{try{let s=i instanceof Function?i(n):i;r(s),typeof window<"u"&&window.localStorage.setItem(e,JSON.stringify(s))}catch(s){j.error(s)}}]}var q1=S(q()),Mn=S(O());var nh={};Pe(nh,{enUS:()=>RL,nlNL:()=>LL});var RL={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"}]}]},LL={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 $1={root:"_root_1vfca_1",anchor:"_anchor_1vfca_6",anchorButton:"_anchorButton_1vfca_11"};var kr=S(b()),rh=(e,t,n)=>r=>(0,kr.jsx)("button",{className:e.anchorButton,type:"button",value:t,onClick:n,children:r},t),AL=({className:e,loginUrl:t,isEmbedded:n,onSnooze:r,onLogIn:o})=>{let i=H(nh),s=Lt(),a=P("Login",$1),l=M("productName"),u=(0,Mn.useCallback)(m=>{m.preventDefault(),r&&r(parseInt(m.target.value,10))},[]),c=(0,Mn.useCallback)(m=>{m.preventDefault(),s.send(Ni,!0)},[t]),p=(0,Mn.useMemo)(()=>m=>(0,kr.jsx)("a",{onClick:g=>{g.preventDefault(),o()},href:t,className:a.anchor,target:"_blank",rel:"noreferrer",children:m},"login"),[t]),d=(0,Mn.useCallback)(m=>(0,kr.jsx)("button",{type:"button",className:a.anchorButton,onClick:c,children:m},"prompt"),[c]),{min:f,hour:y,day:v}=(0,Mn.useMemo)(()=>({min:rh(a,60*10,u),hour:rh(a,60*60,u),day:rh(a,60*60*12,u)}),[]);return(0,kr.jsxs)("div",{className:(0,q1.default)(e,a.root),children:[i("loginPlease",{login:n?d:p,productName:l}),r&&(0,kr.jsxs)(Mn.Fragment,{children:[(0,kr.jsx)("br",{}),i("snooze",{min:f,hour:y,day:v})]})]})},pd=AL;var G1={root:"_root_1g8fi_1",text:"_text_1g8fi_19"};var Ha=S(b()),OL=({title:e})=>{let t=P("SearchTrigger",G1),n=U();return(0,Ha.jsxs)("button",{type:"button",className:t.root,onClick:()=>n($e(!0)),children:[(0,Ha.jsx)(Ri,{}),(0,Ha.jsx)("span",{className:t.text,children:e})]})},X1=OL;var oh={};Pe(oh,{enUS:()=>NL,nlNL:()=>ML});var NL={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"}]},ML={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 Q1={root:"_root_onpov_1",isInline:"_isInline_onpov_14",toggleButton:"_toggleButton_onpov_21",toggleButtonWrapper:"_toggleButtonWrapper_onpov_25",toggleButtonWrapperHidden:"_toggleButtonWrapperHidden_onpov_32",isCollapsed:"_isCollapsed_onpov_36",collapsible:"_collapsible_onpov_36",hints:"_hints_onpov_44",hintsHidden:"_hintsHidden_onpov_51",triggers:"_triggers_onpov_56",triggersRight:"_triggersRight_onpov_71"};var ue=S(b()),DL=({textSuggestions:e,selectedIndex:t,onLogIn:n})=>{let r=P("SuggestionsOverlay",Q1),o=H(oh),i=R(ji),s=Xx(),a=U(),l=(0,Bi.useRef)(null),u=M("searchTriggerKey"),c=M("productName"),p=R(od),d=R(Ge),f=R(Si),[y,v]=(0,Bi.useState)(null),m=M("showSearch"),h=M("showTextSuggestions"),g=M("adminUrl"),x=M("isEmbedded"),[_,w]=W1("dd-snooze-until-ms",0),E=p||_>Date.now(),C=R(B=>B.input.text),I=e.filter(B=>B.source!=="gpt").length,k=()=>{E&&w(0),a(Ow(!E))},K=B=>{a(Be({name:"suggestion feedback",data:{text:B.text,source:"overlay",context:C},options:{includeConversationData:!0}}))},N=B=>{let be=Date.now()+B*1e3;w(be),j.info(`Snooze until: ${new Date(be)}`),a(Er({collapse:!0}))};return(0,Bi.useEffect)(()=>{I===0&&v(null)},[e,I]),Ti(()=>{a(Er({collapse:!0,skipWhenInputFocus:!0}))}),d===null||f===!1?null:d===!1?(0,ue.jsxs)("div",{ref:l,className:(0,fd.default)(r.root,{[r.isCollapsed]:E}),children:[!E&&(0,ue.jsxs)("div",{className:r.triggers,children:[(0,ue.jsx)("div",{style:{flex:1}}),(0,ue.jsx)("div",{className:r.triggersRight,children:(0,ue.jsx)(Hr,{className:r.toggleButton,title:o("collapse"),onClick:k,isCollapsed:!1})})]}),(0,ue.jsx)("div",{className:r.toggleButtonWrapper,children:(0,ue.jsx)(Hr,{className:r.toggleButton,title:o("open",{productName:c}),onClick:k,isCollapsed:!0})}),(0,ue.jsx)("div",{className:r.collapsible,children:(0,ue.jsx)(pd,{loginUrl:g,isEmbedded:x,onLogIn:n,onSnooze:N})})]}):!s||!i?null:(0,ue.jsxs)("div",{ref:l,className:(0,fd.default)(r.root,{[r.isCollapsed]:E}),children:[!E&&(0,ue.jsxs)("div",{className:r.triggers,children:[(0,ue.jsx)("div",{style:{flex:1},children:m&&(0,ue.jsx)("div",{style:{display:"inline-block"},onFocus:()=>{},onMouseOver:()=>v(o(Jc()?"searchHintMac":"searchHintWindows",{searchTriggerKey:u.toUpperCase()})),onMouseLeave:()=>v(null),children:(0,ue.jsx)(X1,{title:o("search")})})}),(0,ue.jsxs)("div",{className:r.triggersRight,onFocus:()=>{},children:[(0,ue.jsx)("div",{className:(0,fd.default)(!y&&r.hintsHidden,r.hints),children:y}),(0,ue.jsx)(Hr,{className:r.toggleButton,title:o("collapse"),onClick:k,isCollapsed:!1})]})]}),(0,ue.jsx)("div",{className:r.toggleButtonWrapper,children:(0,ue.jsx)(Hr,{className:r.toggleButton,title:o("open",{productName:c}),onClick:k,isCollapsed:!0})}),I>0&&h&&(0,ue.jsx)("div",{className:r.collapsible,onFocus:()=>{},children:(0,ue.jsx)(xt,{children:(0,ue.jsx)(cd,{onFeedback:K,suggestions:e,selectedIndex:t,reverse:!0})})})]})},FL=({input:e})=>({selectedIndex:e.selectedSuggestionIndex,textSuggestions:e.textSuggestions}),Y1=xn(FL)(DL);var Td=S(q());var jn=S(O());var Z1=S(O()),jL=["div","span","mark","strong","b","i","u","em"];function ih(e,t,n=0){var i;let r=e[e.length-1],o=typeof r=="object"&&r!==null?(i=r.props)==null?void 0:i.tagName:void 0;if(o==="br")return e.pop(),[...e,...t,r];if(jL.includes(o)){let s=Array.isArray(r.props.children)?r.props.children:[r.props.children];return[...e.slice(0,e.length-1),(0,Z1.cloneElement)(r,{children:ih(s,t,n+1)})]}return[...e,...t]}function Pr(e){return e.tagName.toLowerCase()==="textarea"}var J1={root:"_root_81non_1",container:"_container_81non_3",agentText:"_agentText_81non_5",tabText:"_tabText_81non_6",hint:"_hint_81non_6",matchSelection:"_matchSelection_81non_10",focus:"_focus_81non_16",resetIndent:"_resetIndent_81non_20",matchKeyword:"_matchKeyword_81non_24",matchPlaceholder:"_matchPlaceholder_81non_25",hover:"_hover_81non_31",hintText:"_hintText_81non_64",popover:"_popover_81non_72",popoverRoot:"_popoverRoot_81non_77",popoverContentContainer:"_popoverContentContainer_81non_81",popoverContent:"_popoverContent_81non_81",selectionOptions:"_selectionOptions_81non_107",selectionOptionsIsHidden:"_selectionOptionsIsHidden_81non_112",selectionOptionsButton:"_selectionOptionsButton_81non_116",caret:"_caret_81non_132",popoverSuggestionsRoot:"_popoverSuggestionsRoot_81non_136",suggestionsOverlayInputStyles:"_suggestionsOverlayInputStyles_81non_141"};var lb=S(q());var wd=S(O());function eb(e){return e.replace(/[.*+^${}()|[\]\\]/g,"\\$&")}function md(e){return t=>{e.forEach(n=>{typeof n=="function"?n(t):n!=null&&(n.current=t)})}}function tb(e){return e!=null}var ah=S(q()),At=S(O());var gd=S(O()),HL=["bottom","height","left","right","top","width"],BL=(e={},t={})=>HL.some(n=>e[n]!==t[n]),Dn=new Map,nb,rb=()=>{let e=[],t=[];Dn.forEach((n,r)=>{if(r instanceof Element&&!r.isConnected){t.push(r);return}let o=r.getBoundingClientRect();BL(o,n.rect)&&(n.rect=o,e.push(n))}),t.forEach(n=>{Dn.delete(n)}),e.forEach(n=>{n.callbacks.forEach(r=>r(n.rect))}),nb=window.requestAnimationFrame(rb)};function zL(e,t){return{observe(){let n=Dn.size===0;if(Dn.has(e)){let r=Dn.get(e);r.callbacks.push(t),r.rect&&t(r.rect)}else Dn.set(e,{rect:void 0,hasRectChanged:!1,callbacks:[t]});n&&rb()},unobserve(){let n=Dn.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||Dn.delete(e),Dn.size||cancelAnimationFrame(nb)}}}}function sh(e){let[t,n]=(0,gd.useState)(null);return(0,gd.useLayoutEffect)(()=>{if(!e.current)return;let r=zL(e.current,o=>{n(o)});return r.observe(),()=>{r.unobserve()}},[e]),t}var zi=S(O()),ib=S(wu());var ob={root:"_root_1jq08_1"};var sb=({children:e})=>{let[t,n]=(0,zi.useState)(null),r=(0,zi.useContext)(Xi);return(0,zi.useLayoutEffect)(()=>{let o=document.createElement("div");return ao(o),o.classList.add(ob.root),r!=null&&r.portalRootNode&&o.classList.add(r==null?void 0:r.portalRootNode),document.body.appendChild(o),n(o),()=>{o.isConnected&&document.body.removeChild(o)}},[]),t?(0,ib.createPortal)(e,t):null};var ln={ref:"_ref_1rcyi_1",root:"_root_1rcyi_7",positionAbove:"_positionAbove_1rcyi_13",positionBelow:"_positionBelow_1rcyi_17",positionLeft:"_positionLeft_1rcyi_21",positionRight:"_positionRight_1rcyi_25",alignStart:"_alignStart_1rcyi_29",alignCenter:"_alignCenter_1rcyi_34",alignEnd:"_alignEnd_1rcyi_40"};var hd=S(b()),yd=(e=!1)=>{let[t,n]=(0,At.useState)(e),r=(0,At.useCallback)(()=>n(!0),[]),o=(0,At.useCallback)(()=>n(!1),[]),i=(0,At.useCallback)(()=>n(a=>!a),[]),s=(0,At.useRef)(null);return{opened:t,open:r,close:o,toggle:i,triggerRef:s}};function lh(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 vd=({className:e,triggerRef:t,boundaryRef:n=(0,At.createRef)(),position:r="above",align:o="center",children:i,toStyle:s=lh,...a})=>{let l=sh(t),u=sh(n),c=(0,At.useMemo)(()=>s(l,u,0),[l,u]);return(0,hd.jsx)(sb,{children:(0,hd.jsx)("div",{className:(0,ah.default)(ln.ref,{[ln.positionAbove]:r==="above",[ln.positionBelow]:r==="below",[ln.positionLeft]:r==="left",[ln.positionRight]:r==="right",[ln.alignStart]:o==="start",[ln.alignCenter]:o==="center",[ln.alignEnd]:o==="end"}),style:c,...a,role:"dialog",children:(0,hd.jsx)("div",{className:(0,ah.default)(e,ln.root),children:i})})})};var ab=S(q()),Sd=S(O());var uh=S(b()),xd=(0,Sd.forwardRef)(({className:e,children:t,...n},r)=>{let o=(0,Sd.useRef)(null),i=P("TabCompletion",Tn);return(0,uh.jsx)("div",{ref:md([o,r]),className:(0,ab.default)(e,i.popoverContentContainer),...n,children:(0,uh.jsx)("div",{className:i.popoverContent,children:t})})});var Ir=S(b()),UL=e=>t=>{let n=lh(t);return"top"in n&&(n.width=e.width-(t.left-e.left)-10),n},KL=({inputElement:e,boundaryRef:t,inputStyle:n,children:r,suggestion:o})=>{let i=P("TabCompletion",Tn),s=yd(),a=(0,wd.useMemo)(()=>UL(e.getBoundingClientRect()),[e]),[l,u]=Bc(e);return(0,wd.useEffect)(()=>{u?s.open():s.close()},[u]),(0,Ir.jsxs)("span",{children:[(0,Ir.jsx)("mark",{ref:md([l,s.triggerRef]),className:(0,lb.default)(i.matchKeyword,{[i.hover]:u}),"aria-haspopup":"dialog","aria-expanded":s.opened?"true":"false",children:r}),s.opened&&(0,Ir.jsx)(vd,{className:i.popover,triggerRef:s.triggerRef,boundaryRef:t,position:"below",align:"start",toStyle:a,children:(0,Ir.jsx)(xd,{style:n,children:(0,Ir.jsx)("div",{className:i.hintText,children:o})})})]})},_d=class extends bn{keywordMatches=[];preparedKeywordMatches=[];usedKeywordMatches=new Set;onBeforeParse(t,n){return n.keywordMatches&&n.keywordMatches!==this.keywordMatches&&(this.preparedKeywordMatches=n.keywordMatches.map(r=>({...r,keywordRegex:new RegExp(`\\b${eb(r.keyword)}\\b`,"i")})),this.keywordMatches=n.keywordMatches),this.usedKeywordMatches.clear(),t}match(t){let n=this.preparedKeywordMatches.map(o=>{if(this.usedKeywordMatches.has(o))return null;let i=t.match(o.keywordRegex);if(!i)return null;let s=t.charAt(i.index-1),a=t.charAt(i.index+o.keyword.length);return s==="{"&&a==="}"?null:{index:i.index,length:i[0].length,match:i[0],matchString:i[0],suggestion:o.suggestion,preparedKeywordMatch:o,valid:!0}}).filter(tb);if(n.length===0)return null;let r=n.reduce((o,i)=>i.index<o.index?i:o);return this.usedKeywordMatches.add(r.preparedKeywordMatch),r}replaceWith(t,n){return(0,Ir.jsx)(KL,{inputElement:n.inputElement,suggestion:n.suggestion,inputStyle:n.inputStyle,boundaryRef:n.boundaryRef,children:t},`keyword_${n.matchString}_${n.key}`)}asTag(){return"mark"}};var Ed=S(q());var Ye=S(O());var ch=S(b()),ub=()=>(0,ch.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,ch.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 Rr=S(O());var db=S(Gg());var cb={root:"_root_1muu8_1",content:"_content_1muu8_7"};function bd(e,t,n){var o;let r=((o=e.imageSizes)==null?void 0:o[t])||e.image||n;if(!r)return null;try{return new URL(r).toString()}catch{return null}}function dh(e){return e.replace("https://www.","").replace("https://","")}var Ot=S(b()),VL=3,WL=e=>({image:e.image||"",text:e.text,id:e.id,title:e.title}),$L=({onSelectLink:e,onDismiss:t,placeholder:n,visitUrlText:r,linkCount:o=VL})=>{let i=P("LinkSearch",cb),[s,a]=(0,Rr.useState)(""),l=U(),u=R(nd("url")),c=R(uw("URL",WL)),[p,d]=(0,Rr.useState)(c.length-1),f=M("fallbackImage"),y=g=>{let x=g.target;a(x.value)},v=(g,x)=>{g.stopPropagation(),g.preventDefault(),window.open(x,"_blank")},m=g=>{var w;let x=p-1<0?c.length-1:p-1,_=p+1===c.length?0:p+1;g.code==="Escape"&&(a(""),t()),g.code==="ArrowUp"&&d(x),g.code==="ArrowDown"&&d(_),g.code==="Enter"&&e(((w=c[p])==null?void 0:w.text)||s)},h=(0,Rr.useCallback)((0,db.default)(g=>{l(go({query:g,type:"URL",tags:["link-search"]}))},300),[]);return(0,Rr.useEffect)(()=>{s&&h(s)},[s]),(0,Rr.useEffect)(()=>()=>{l(Yc())},[]),(0,Ot.jsxs)("div",{className:i.root,children:[(0,Ot.jsx)(xt,{withDivider:!0,children:(s?c:u).slice(0,o).map((g,x)=>(0,Ot.jsx)(oe,{selected:p===x,onClick:()=>e(g.text),"data-testid":"linksearch-suggestion",children:(0,Ot.jsxs)(ge,{children:[(0,Ot.jsx)(ge.Image,{src:bd(g,"small",f||void 0),title:g.title||g.text}),(0,Ot.jsxs)(ge.Content,{className:i.content,cropText:!0,children:[(0,Ot.jsx)(ge.Title,{children:g.title||dh(g.text)}),g.title&&dh(g.text)]}),(0,Ot.jsx)(oe.Actions,{children:(0,Ot.jsx)(oe.ActionButton,{label:r,onClick:_=>v(_,g.text)})})]})},g.text))}),(0,Ot.jsx)(Ia,{value:s,onChange:y,autoFocus:!0,placeholder:n,onKeyUp:m})]})},pb=$L;var ph={};Pe(ph,{enUS:()=>qL,nlNL:()=>GL});var qL={insertLink:[{type:0,value:"Insert link"}],linkInputPlaceholder:[{type:0,value:"Search, type or paste link"}],visitUrl:[{type:0,value:"Visit"}]},GL={insertLink:[{type:0,value:"Voeg link toe"}],linkInputPlaceholder:[{type:0,value:"Zoek, typ of plak link"}],visitUrl:[{type:0,value:"Bekijk"}]};var Qe=S(b()),XL=(0,Ye.forwardRef)((e,t)=>{let n=P("TabCompletion",Tn);return(0,Qe.jsx)("mark",{ref:t,className:(0,Ed.default)(n.matchSelection)},"selection-start")}),QL=({startRef:e,boundaryRef:t,inputStyle:n,inputElement:r,children:o})=>{let i=H(ph),s=P("TabCompletion",Tn),a=(0,Ye.useRef)(null),l=(0,Ye.useRef)(null),[u,c]=(0,Ye.useState)(null),p=U(),d=yd(document.activeElement===r),[f]=(0,Ye.useState)(()=>document.createRange());d.triggerRef.current=f,(0,Ye.useEffect)(()=>()=>f.detach(),[]),(0,Ye.useEffect)(()=>{let v=e.current,m=a.current;!v||!m||(f.setStart(v,0),f.setEnd(m,0))},[e.current,a.current]),Ti(()=>{d.close()});let y=(0,Ye.useCallback)(v=>{let m=f.toString(),h=/^http(s?):\/\//.test(v)?v:`https://${v}`;p(fc({text:`[${m}](${h})`,replace:"selection"}))},[]);return(0,Qe.jsxs)("span",{children:[(0,Qe.jsx)("mark",{ref:a,className:(0,Ed.default)(s.matchSelection),"aria-haspopup":"dialog","aria-expanded":d.opened?"true":"false",children:o}),d.opened&&(0,Qe.jsx)(vd,{className:s.popoverRoot,triggerRef:d.triggerRef,boundaryRef:t,position:"above",align:"start",children:(0,Qe.jsxs)(xd,{style:n,ref:l,children:[(0,Qe.jsx)("div",{className:(0,Ed.default)(s.selectionOptions,{[s.selectionOptionsIsHidden]:u!==null}),children:(0,Qe.jsxs)("button",{type:"button",tabIndex:u===null?-1:void 0,className:s.selectionOptionsButton,onClick:()=>c("insertLink"),children:[(0,Qe.jsx)(ub,{}),(0,Qe.jsx)("span",{children:"\xA0"}),(0,Qe.jsx)("span",{children:i("insertLink")})]})}),u==="insertLink"&&(0,Qe.jsx)(pb,{placeholder:i("linkInputPlaceholder"),visitUrlText:i("visitUrl"),onSelectLink:y,onDismiss:()=>{c(null),d.close()}})]})})]},"selection-end")},Cd=class extends bn{charCount=0;foundIndex=0;startRef=null;props;onBeforeParse(t,n){return this.props=n,this.charCount=0,this.startRef=(0,Ye.createRef)(),this.foundIndex=0,t}match(t){if(!this.props||this.props.selection===null||this.foundIndex===2)return null;let[n,r]=this.props.selection;if(n===r)return null;let o=this.foundIndex===0?n:r,i=o>=this.charCount&&o<=this.charCount+t.length?{index:o-this.charCount,length:0,match:"",valid:!0}:null;i&&this.foundIndex++;let s=this.foundIndex===1;return i&&s?this.charCount+=o-this.charCount:this.charCount+=t.length,i?{isStart:s,...i}:null}replaceWith(t,n){return n.isStart?(0,Qe.jsx)(XL,{ref:this.startRef}):(0,Qe.jsx)(QL,{inputElement:n.inputElement,startRef:this.startRef,boundaryRef:n.boundaryRef,inputStyle:n.inputStyle})}asTag(){return"mark"}};var Fn=S(b()),YL=({enabled:e,content:t,tabText:n,showTabHint:r,showTabCompletion:o,showStyleSuggestions:i,keywordMatches:s,inputElement:a,source:l})=>{let u=P("TabCompletion",J1),c=M("insertLink"),p=M("showMidSentenceSuggestions"),d=M("inlineSuggestions"),f=Uc(a),y=(0,jn.useRef)(null),v=R(Ge);(0,jn.useEffect)(()=>{Pr(a)&&f&&Kc(a,f)},[f]);let m=(0,jn.useCallback)(x=>{if(!o||!n)return x;let _=[(0,Fn.jsx)("span",{className:u.resetIndent,children:"\u200B"},"u200B"),(0,Fn.jsx)("span",{"data-testid":"tab-completion",className:(0,Td.default)(u.tabText,u.resetIndent),"data-source":l,children:n},"tabText")];return r&&_.push((0,Fn.jsx)("span",{className:(0,Td.default)(u.hint,u.resetIndent),children:(0,Fn.jsx)(sl,{keyCode:"tab"},"tabHint")})),ih(x,_)},[o,n,r]),h=(0,jn.useMemo)(()=>{let x=[];return c&&x.push(new Cd("selection")),x.push(new Ei("placeholders")),i&&x.push(new _d("keywords")),x},[d,c,i]),g=(0,jn.useMemo)(()=>{let x=window.getComputedStyle(a);return{"--dd-color":x.color,"--dd-font-size":x.fontSize,"--dd-font-family":x.fontFamily,"--dd-font-variant":x.fontVariant}},[]);return!e||!v?null:(0,Fn.jsxs)("div",{ref:x=>{x!=null&&x.parentElement&&(y.current=x==null?void 0:x.parentElement)},className:u.root,style:g,children:[(0,Fn.jsx)(Cn,{tagName:"span",containerTagName:"div",className:(0,Td.default)(u.container,u.agentText),disableLineBreaks:Pr(a),content:t||"\u200B",onAfterParse:m,matchers:h,selection:f,keywordMatches:s,inputElement:a,inputStyle:g,boundaryRef:y,inlineSuggestionsOnlyAtEnd:!p}),(0,Fn.jsx)("br",{})]})},ZL=({input:e,ui:t,settings:n,styleSuggestions:r,conversation:o})=>{var v;let{tabCompletionSuggestion:i}=e,s=(i==null?void 0:i.text)||"",a=(i==null?void 0:i.source)||"",l=e.html??Pi(e.text),u=s.indexOf(e.text)===0?s.slice(e.text.length):"",{showTabHint:c}=t,{isSupported:p}=o,{showTabCompletion:d,visible:f,showStyleSuggestions:y}=n;return{showTabHint:c,showStyleSuggestions:y,showTabCompletion:d,content:l,tabText:u,source:a,keywordMatches:((v=r.list)==null?void 0:v.keywordMatches)??[],enabled:f&&p!==!1}},fb=xn(ZL)(YL);var tE=S(q()),nE=S(O());var mb={list:[],fetchState:"idle",isInitialRequest:null},hb=e=>e.autoflows.list||[],gb=e=>t=>{var n;return(n=t.list)==null?void 0:n.find(r=>r.triggerPayload===e)},Hn=D("autoflows/getAll",async(e,t)=>{let{deepdeskBrokerAPI:n}=t.extra;if(!n)throw new Error("Deepdesk Broker not initialized");return n.getAutoflows(e)}),fh=D("autoflows/start",async(e,t)=>{let{dispatch:n}=t,{deepdeskBrokerAPI:r}=t.extra;if(!r)throw new Error("Deepdesk Broker not initialized");await r.startAutoflowSession(e),await n(Hn(e.platformSessionId))}),mh=D("autoflows/stop",async(e,t)=>{let{dispatch:n}=t,{deepdeskBrokerAPI:r}=t.extra;if(!r)throw new Error("Deepdesk Broker not initialized");await r.stopAutoflowSession(e.platformSessionId),await n(Hn(e.platformSessionId))}),JL=z({name:"autoflows",initialState:mb,reducers:{},extraReducers:e=>{e.addCase(fh.pending,(t,n)=>{let r=gb(n.meta.arg.triggerPayload)(t);r.state="Started",r.isBusy=!0}),e.addCase(mh.pending,(t,n)=>{let r=gb(n.meta.arg.triggerPayload)(t);r.state="Aborted",r.isBusy=!0}),e.addCase(Hn.pending,t=>{t.isInitialRequest=t.isInitialRequest===null,t.fetchState="loading"}),e.addCase(Hn.rejected,t=>{t.fetchState="error"}),e.addCase(Hn.fulfilled,(t,n)=>{t.list=n.payload,t.fetchState="done"}),e.addCase(te,()=>mb)}}),yb=D("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(Hn(e))}),o.on("sessionCompleted",()=>{n(Hn(e))})}),vb=D("autoflows/closeStream",(e,t)=>{let{deepdeskBrokerAPI:n}=t.extra;if(!n)throw new Error("Deepdesk Broker not initialized");n.closeStream(e)}),Sb=JL.reducer;var xb={list:[],fetchState:"idle",isInitialRequest:null,sentSuggestions:[],errorSuggestions:[],answeredSuggestions:[]},_b=e=>e.customMessages.list,wb=e=>t=>!!t.customMessages.sentSuggestions.find(n=>n===e),bb=e=>t=>!!t.customMessages.answeredSuggestions.find(n=>n===e),Eb=e=>t=>!!t.customMessages.errorSuggestions.find(n=>n===e),Ba=D("customMessages/getAll",async(e,t)=>{let{deepdeskBrokerAPI:n}=t.extra;if(!n)throw new Error("Deepdesk Broker not initialized");return n.getCustomMessages(e)}),kd=D("customMessages/send",async(e,t)=>{let{platformSessionId:n,suggestion:r}=e,{deepdeskBrokerAPI:o}=t.extra;if(!o)throw new Error("Deepdesk Broker not initialized");await o.sendCustomMessage(n,r)}),Pd=D("customMessages/answer",async(e,t)=>{let{platformSessionId:n,reply:r}=e,{deepdeskBrokerAPI:o}=t.extra;if(!o)throw new Error("Deepdesk Broker not initialized");await o.answerCustomMessage(n,r)}),Cb=z({name:"customMessages",initialState:xb,reducers:{onCustomMessage(e,t){Array.isArray(t.payload)?e.list=t.payload:e.list=[t.payload]}},extraReducers:e=>{e.addCase(Ba.pending,t=>{t.isInitialRequest=t.isInitialRequest===null,t.fetchState="loading"}).addCase(Ba.rejected,t=>{t.fetchState="error"}).addCase(Ba.fulfilled,(t,n)=>{t.fetchState="done",t.list=n.payload||[]}).addCase(kd.pending,(t,n)=>{t.sentSuggestions.push(n.meta.arg.suggestion.text),t.errorSuggestions=t.errorSuggestions.filter(r=>n.meta.arg.suggestion.text!==r)}).addCase(kd.rejected,(t,n)=>{let r=t.sentSuggestions.indexOf(n.meta.arg.suggestion.text);t.errorSuggestions.push(...t.sentSuggestions.splice(r,1))}).addCase(Pd.pending,(t,n)=>{t.sentSuggestions.push(n.meta.arg.suggestion.text),t.answeredSuggestions.push(n.meta.arg.suggestion.text)}).addCase(Pd.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(te,()=>xb)}}),Tb=D("customMessages/openStream",(e,t)=>{let{dispatch:n}=t,{deepdeskBrokerAPI:r}=t.extra;if(!r)throw new Error("Deepdesk Broker not initialized");r.openStream(e).on("customMessageSuggestion",i=>{n(Cb.actions.onCustomMessage(i))})}),kb=D("customMessages/closeStream",(e,t)=>{let{deepdeskBrokerAPI:n}=t.extra;if(!n)throw new Error("Deepdesk Broker not initialized");n.closeStream(e)}),Pb=Cb.reducer;var eA={token:null,accountUrl:null,interval:null},Ib=e=>t=>{let{passwordlessToken:{token:n,accountUrl:r}}=t;return n&&r?`${r}/apis/admin/session/passwordless/login/?token=${n}&redirect=${e}`:null},gh=D("passwordlessToken/getTemporaryPasswordlessToken",async(e,t)=>{let{deepdeskAPI:n}=t.extra,r=await n.requestPasswordlessToken();return{accountUrl:n.client.baseUrl,token:r}}),hh=D("passwordlessToken/pollPasswordlessToken",(e={},t)=>{let{interval:n=1e3*60*10}=e,{dispatch:r}=t;return r(gh()),setInterval(()=>r(gh()),n)}),Rb=z({name:"passwordlessToken",initialState:eA,reducers:{stopPollPasswordlessToken(e){e.interval&&clearInterval(e.interval),e.interval=null}},extraReducers:e=>{e.addCase(gh.fulfilled,(t,n)=>{t.token=n.payload.token,t.accountUrl=n.payload.accountUrl}),e.addCase(hh.fulfilled,(t,n)=>{t.interval=n.payload})}}),{stopPollPasswordlessToken:Lb}=Rb.actions,Ab=Rb.reducer;function Ob(e){let{customMessages:t,autoflows:n}=e;return n.fetchState==="loading"&&n.isInitialRequest===!0||t.fetchState==="loading"&&t.isInitialRequest===!0}var Ub=S(O());var Hb=S(q()),Bb=S(O());var Mb=S(q());var Nb={root:"_root_838fd_1"};var Fb=S(b()),tA=({className:e,children:t})=>{let n=P("Unicode",Nb);return(0,Fb.jsx)("span",{className:(0,Mb.default)(e,n.root),children:t})},Db=tA;var jb={isDisabled:"_isDisabled_1rmfm_1",buttonStart:"_buttonStart_1rmfm_5",root:"_root_1rmfm_8",buttonStop:"_buttonStop_1rmfm_8",stateBadge:"_stateBadge_1rmfm_19",isCompleted:"_isCompleted_1rmfm_26",isStarted:"_isStarted_1rmfm_30",isAborted:"_isAborted_1rmfm_34"};var yh={};Pe(yh,{enUS:()=>nA,nlNL:()=>rA});var nA={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"}]},rA={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 ft=S(b()),iA=({disabled:e,state:t,displayName:n,description:r,onStartAutoflow:o,onStopAutoflow:i})=>{let s=P("Autoflow",jb),a=H(yh),l=t==="Started"?"stop":"start",u=l==="start"?"\u25B6":l==="stop"?"\u25FC":"";return(0,ft.jsxs)(oe,{className:(0,Hb.default)(s.root,{[s.isDisabled]:e,[s.isCompleted]:t==="Completed",[s.isAborted]:t==="Aborted",[s.isStarted]:t==="Started"}),children:[(0,ft.jsx)(ge,{children:(0,ft.jsxs)(ge.Content,{children:[(0,ft.jsxs)(ge.Title,{children:[t&&(0,ft.jsx)("span",{className:s.stateBadge,children:a(t)}),n]}),(0,ft.jsx)("span",{children:r})]})}),(0,ft.jsx)(oe.Actions,{fixed:t==="Started",children:(0,ft.jsx)(oe.ActionButton,{primary:!0,className:l==="start"?s.buttonStart:s.buttonStop,onClick:t==="Started"?i:o,disabled:e,label:(0,ft.jsxs)(Bb.Fragment,{children:[(0,ft.jsx)(Db,{children:u})," ",(0,ft.jsx)("span",{children:a(l)})]})})})]})},zb=iA;var vh=S(b()),sA=(e,t)=>{let n=t.filter(r=>r.state==="Started");return n.length>0?n.indexOf(e)===-1:!1},aA=({autoflows:e,onStartAutoflow:t,onStopAutoflow:n,platformSessionId:r})=>(0,vh.jsx)(Ub.Fragment,{children:e.map(o=>(0,vh.jsx)(zb,{displayName:o.displayName,description:o.description,disabled:o.isBusy||sA(o,e),state:o.state,onStartAutoflow:()=>t({platformSessionId:r,triggerPayload:o.triggerPayload}),onStopAutoflow:()=>n({platformSessionId:r,triggerPayload:o.triggerPayload})},o.displayName))}),lA=({autoflows:e,conversation:t})=>{var n;return{autoflows:e.list,platformSessionId:(n=t.current)==null?void 0:n.sessionId}},uA={onStartAutoflow:fh,onStopAutoflow:mh},Kb=xn(lA,uA)(aA);var Id=S(O());var _h=S(q());var Sh=S(b()),xh=()=>(0,Sh.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 512 512",xmlns:"http://www.w3.org/2000/svg",children:(0,Sh.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 Vb={root:"_root_rjdyr_1",entity:"_entity_rjdyr_10",entityText:"_entityText_rjdyr_46",iconWrapper:"_iconWrapper_rjdyr_53",icon:"_icon_rjdyr_53",iconClicked:"_iconClicked_rjdyr_67"};var un=S(b()),cA=({entities:e})=>{let t=P("EntitiesWidgetList",Vb),[n,r]=(0,Id.useState)(void 0),o=U(),i=()=>{r(void 0)},s=a=>{e&&(r(e.indexOf(a)),La(a.text),o(Be({name:"entity copied",data:{entity:a,type:"copy"}})))};return(0,Id.useEffect)(()=>{let a=setTimeout(i,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:()=>s(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,_h.default)(t.icon),children:(0,un.jsx)(xh,{})}),(0,un.jsx)("span",{className:(0,_h.default)(t.icon,n===l&&t.iconClicked),children:(0,un.jsx)(xh,{})})]})]},a.text))})},Wb=cA;var $b=S(q()),wh=S(O());var Bn={root:"_root_1e6ej_1",title:"_title_1e6ej_8",isUsed:"_isUsed_1e6ej_13",quickReplies:"_quickReplies_1e6ej_22",quickReply:"_quickReply_1e6ej_29",hasError:"_hasError_1e6ej_39",label:"_label_1e6ej_43",errorIcon:"_errorIcon_1e6ej_48"};var st=S(b()),dA=({suggestion:e})=>{let t=H(fo),n=U(),r=R(wb(e.text)),o=R(bb(e.text)),i=R(Eb(e.text)),s=R(ic),{replyOptions:a}=e,l=(0,wh.useCallback)(c=>{c.preventDefault(),c.stopPropagation(),!(r||!s)&&n(kd({platformSessionId:s,suggestion:e}))},[e,r,n,s]),u=(0,wh.useCallback)(c=>{if(c.preventDefault(),c.stopPropagation(),!s||!a)return;let p=parseInt(c.target.dataset.index,10),d=a[p];n(Pd({platformSessionId:s,reply:d,suggestion:e}))},[e,r,n,s]);return(0,st.jsxs)(oe,{onClick:l,className:(0,$b.default)(Bn.root,{[Bn.isUsed]:r,[Bn.hasError]:i}),children:[(0,st.jsx)(ge,{children:(0,st.jsxs)(ge.Content,{children:[(0,st.jsxs)(ge.Title,{className:Bn.title,children:[e.text," ",(0,st.jsx)(al,{className:Bn.label,children:"analyse tool"})," ",i&&(0,st.jsx)("span",{className:Bn.errorIcon,role:"img","aria-label":t("sendingError"),title:t("sendingError"),children:"!"})]}),a&&a.length>0&&(0,st.jsx)("ul",{className:Bn.quickReplies,children:a.map(c=>(0,st.jsx)("li",{className:Bn.quickReply,children:c.title},c.title))})]})}),(0,st.jsxs)(oe.Actions,{fixed:i||r,children:[a&&a.length>0&&(0,st.jsx)(oe.DropdownButton,{label:t("answer"),disabled:o,children:a.map((c,p)=>(0,st.jsx)(oe.DropdownItem,{index:p,label:c.title,onClick:u},c.title))}),(0,st.jsx)(oe.ActionButton,{primary:!0,disabled:r,onClick:l,label:t(r?"suggestionSent":i?"tryAgain":"sendSuggestion")})]})]})},qb=dA;var bh=S(b()),Gb=()=>(0,bh.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:(0,bh.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 Xb=S(O());var mt=S(b()),pA=({suggestion:e,lines:t,onEdit:n,onUse:r})=>{var d;let o=e.text||e.url||e.message,i=Zc(o),s=H(fo),a=M("showImages"),l=M("fallbackImage"),u=f=>{f.preventDefault(),f.stopPropagation(),r(o)},c=f=>{f.preventDefault(),f.stopPropagation(),n(e)},p=(0,Xb.useCallback)(f=>{window.open(i,"_blank"),f.stopPropagation(),f.preventDefault()},[i]);return(0,mt.jsxs)(oe,{onClick:u,"data-testid":"edit-suggestion",children:[(0,mt.jsxs)(ge,{children:[a&&e.image&&(0,mt.jsx)(ge.Image,{src:bd(e,"small",l||void 0),title:e.title}),(0,mt.jsxs)(ge.Content,{children:[e.title&&(0,mt.jsx)(ge.Title,{"data-testid":"widget-suggestion-title",children:e.title}),e.searchKeywords&&((d=e.searchKeywords)==null?void 0:d.length)>0&&(0,mt.jsx)(oe.Labels,{labels:e.searchKeywords}),(0,mt.jsx)(ge.Content,{cropText:t==="single",lineClamp:t==="multiple",children:o})]})]}),(0,mt.jsxs)(oe.Actions,{children:[i&&(0,mt.jsx)(oe.ActionButton,{onClick:p,label:s("visitUrl")}),(0,mt.jsx)(oe.ActionButton,{primary:!0,onClick:c,label:s("preview")}),(0,mt.jsx)(oe.ActionButton,{primary:!0,onClick:u,label:s("useSuggestion")})]})]})},Qb=pA;var za=S(b()),fA=({contentType:e,lines:t,suggestions:n})=>{let r=Lt(),o=R(br),i=a=>{r.send(Ug,{state:o,suggestion:a,contentType:e})},s=(a,l)=>{r.send(An,{text:a,suggestion:{...l,source:l.source,sourceText:l.text}})};return(0,za.jsx)(za.Fragment,{children:n.map(a=>(0,za.jsx)(Qb,{suggestion:a,lines:t,onEdit:l=>i(l),onUse:l=>s(l,a)},a.text||a.url||a.message))})},Yb=fA;var Eh={};Pe(Eh,{enUS:()=>mA,nlNL:()=>gA});var mA={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"}],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"}]},gA={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"}],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 Zb={root:"_root_x0pwe_1",loginText:"_loginText_x0pwe_7",stateText:"_stateText_x0pwe_8",sectionList:"_sectionList_x0pwe_20",shortcutList:"_shortcutList_x0pwe_24",shortcut:"_shortcut_x0pwe_24",link:"_link_x0pwe_52"};var Ch=S(b()),Jb=()=>(0,Ch.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:(0,Ch.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 Th=S(b()),eE=()=>(0,Th.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:(0,Th.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 V=S(b()),Rd=(e,t)=>{let n=R(Ge);(0,nE.useEffect)(()=>n?t.every(r=>!!r)?e():()=>{}:()=>{},[...t,n])},hA=({onLogIn:e})=>{let t=H(Eh),n=U(),r=M("isEmbedded"),o=P("Widget",Zb),i=M("showAutoflows"),s=M("showCustomMessages"),a=M("showSummaryCommand"),l=M("showKnowledgeSearch"),u=M("showSearch"),c=R(Tr),p=R(ad),d=R(hb),f=R(sd),y=R(_b),v=R(sc),m=R(Si),h=R(Ge),g=R(ic),x=R(Ob),_=R(br),w=Lt(),E=R(xw),C=R(Ib("/admin/")),I=M("adminUrl"),k=M("productName");if(Rd(()=>(n(Ba(g)),n(Tb(g)),()=>{n(kb(g))}),[n,m,s,g]),Rd(()=>(n(Hn(g)),n(yb(g)),()=>{n(vb(g))}),[n,m,i,g]),Rd(()=>{p.forEach(({type:N})=>{n(N==="entities"?$t():Vt(N))})},[n,m,v,c]),Rd(()=>(n(hh()),()=>{n(Lb())}),[n]),m===!1)return(0,V.jsx)("div",{className:o.stateText,children:(0,V.jsx)("div",{children:(0,V.jsx)("p",{children:t("notSupported")})})},"supported");if(h===!1)return(0,V.jsx)("div",{className:o.loginText,children:(0,V.jsx)("div",{children:(0,V.jsx)(pd,{isEmbedded:r,loginUrl:I,onLogIn:e})})},"login");if(!c||!g||h===null||E||x)return(0,V.jsx)("div",{className:o.stateText,children:(0,V.jsx)("div",{children:(0,V.jsx)("p",{children:t("waiting")})})},"waiting");let K=u||a||l||C;return(0,V.jsx)("div",{className:(0,tE.default)(o.root),"data-testid":"widget",children:(0,V.jsxs)(ll,{className:o.sectionList,children:[K&&(0,V.jsx)(Kn,{title:t("actions"),type:"shortcuts",children:(0,V.jsxs)("div",{className:o.shortcutList,children:[u&&(0,V.jsxs)("button",{className:o.shortcut,"data-testid":"shortcut-search",onClick:()=>w.send("ShowCommandPalette",{isOpen:!0}),children:[(0,V.jsx)(Ri,{}),t("linkSearch")]}),a&&(0,V.jsxs)("button",{className:o.shortcut,"data-testid":"shortcut-summary",onClick:()=>w.send("ShowCommandPalette",{isOpen:!0,page:"summary"}),children:[(0,V.jsx)(eE,{}),t("linkSummary")]}),l&&(0,V.jsxs)("button",{className:o.shortcut,"data-testid":"shortcut-knowledge-assist",onClick:()=>w.send("ShowCommandPalette",{isOpen:!0,page:"knowledgeAssist"}),children:[(0,V.jsx)(Jb,{}),t("linkKnowledgeSearch")]}),C&&(0,V.jsxs)("a",{className:o.shortcut,target:"_blank",href:C,"data-testid":"shortcut-studio-login",rel:"noreferrer",children:[(0,V.jsx)(Gb,{}),t("linkStudioLogin",{productName:k})]})]})}),s&&y.length>0&&(0,V.jsx)(Kn,{type:"custom-messages","data-testid":"custom-messages",children:(0,V.jsx)(xt,{withDivider:!0,children:y.map(N=>(0,V.jsx)(qb,{suggestion:N},N.text))})}),i&&d.length>0&&(0,V.jsx)(Kn,{type:"autoflows",title:t("titleAutoflows"),"data-testid":"autoflows",children:(0,V.jsx)(xt,{withDivider:!0,children:(0,V.jsx)(Kb,{})})}),p.map(({type:N,title:B,amount:be,lines:Ar})=>{var Ze;switch(N){case"entities":return f&&f.length>0&&(0,V.jsx)(Kn,{type:N,title:B,"data-testid":`type-${N}`,children:(0,V.jsx)(Wb,{entities:f})},N);default:return((Ze=_[N])==null?void 0:Ze.fetchState)==="done"&&_[N].suggestions.length>0&&(0,V.jsx)(Kn,{type:N,title:B,"data-testid":`type-${N}`,children:(0,V.jsx)(xt,{withDivider:!0,children:(0,V.jsx)(Yb,{lines:Ar,contentType:N,suggestions:_[N].suggestions.slice(0,be)||[]})})},N)}})]})})},rE=hA;function Ui(e){let t=new Range;return t.selectNodeContents(e),t}function oE(e,t,n){try{return Lr(e,t,n),!0}catch{return!1}}function Ld(e){return"tagName"in e&&(e.tagName==="DIV"||e.tagName==="P")}function Ad(e){return"tagName"in e&&e.tagName==="BR"}var Ua=/[\u200B-\u200D\uFEFF]/g;function Lr(e,t,n){let r=new Range;if(e.firstChild===null&&t===0&&n===0)return r.selectNodeContents(e),r;let o=0,i=!1;function s(l,u){let c=-1,p=/[\u200B-\u200D\uFEFF]/;if(!p.test(l))return u;for(let d=0;d<=l.length;d++)if(p.test(l[d])||c++,c===u)return d;throw new Error("Offset out of range")}function a(l){switch(l.nodeType){case Node.TEXT_NODE:{let u=l.textContent,c=u.replace(Ua,""),p=o+c.length,d=t>=o&&t<=p,f=n>=o&&n<=p;if(d){let y=s(u,t-o);y===0&&!f?r.setStartBefore(l):r.setStart(l,y)}f&&(r.setEnd(l,s(u,n-o)),i=!0),o=p;break}case Node.ELEMENT_NODE:{if(Ad(l)&&(o===t&&r.setStartBefore(l),o++,o===n)){r.setEndAfter(l),i=!0;return}for(let c=0;c<l.childNodes.length&&(a(l.childNodes[c]),!i);c++);let u=l.lastChild;Ld(l)&&u&&!Ld(u)&&!Ad(u)&&o++;break}default:break}}if(a(e),r.startContainer===document)throw new Error("Offsets out of bound");return r}function Ka(e,t){if(!e.contains(t.startContainer)||!e.contains(t.endContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:r,endContainer:o,endOffset:i,collapsed:s}=t,a,l,u=0;function c(p){let d=p===n,f=p===o;switch(p.nodeType){case Node.TEXT_NODE:{let y=p.textContent;d&&(a=u+y.substring(0,r).replace(Ua,"").length),f&&(l=u+y.substring(0,i).replace(Ua,"").length),u+=y.replace(Ua,"").length;break}case Node.ELEMENT_NODE:{let y=p.nextSibling===null;Ad(p)&&!y&&u++;for(let v=0;v<p.childNodes.length;v++){let m=d&&v===r,h=f&&v===i;if(m&&(a=u),h&&(l=u),l!==void 0||((!m||!s)&&c(p.childNodes[v]),f&&v===i-1&&(l=u),l!==void 0))break}!f&&Ld(p)&&!y&&u++,f&&(l=u);break}default:break}}if(c(e),l===void 0)throw new Error("Could not determine start and end");return{start:a??l,end:l}}function Va(e,t){if(!e.contains(t.startContainer)||!e.contains(t.endContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:r,endContainer:o,endOffset:i}=t,s=-1,a="";function l(u){let c=u===n,p=u===o;switch(c&&s++,u.nodeType){case Node.TEXT_NODE:{if(s!==0)return;let d=c?r:0,f=p?i:void 0,y=u.textContent.replace(Ua,"");d===0&&f===void 0?a+=y:a+=y.substring(d,f);break}case Node.ELEMENT_NODE:{let d=u.nextSibling===null;s===0&&Ad(u)&&!d&&(a+=`
24
24
  `);for(let f=c?r:0;f<(p?Math.min(i,u.childNodes.length):u.childNodes.length)&&(l(u.childNodes[f]),s!==1);f++);!p&&s===0&&Ld(u)&&!d&&(a+=`
25
- `);break}default:break}p&&s++}return l(e),a}function iE(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var bo=class extends kn{observer;lastKnownSelection=null;getRootNode(){return this.element.getRootNode()}getText(){let t=new Range;return t.selectNodeContents(this.element),Va(this.element,t)}getHTML(){return this.element.innerHTML||""}getRange(){var i;let t=this.getRootNode();if(t.activeElement!==this.element)return null;let n="getSelection"in t?t.getSelection():window.getSelection();if(!n)return null;let r="getComposedRanges"in n&&t instanceof ShadowRoot?(i=n.getComposedRanges(t))==null?void 0:i[0]:n.rangeCount>0?n.getRangeAt(0):null;if(!r)return null;let o=this.element.ownerDocument.createRange();return o.setStart(r==null?void 0:r.startContainer,r==null?void 0:r.startOffset),o.setEnd(r==null?void 0:r.endContainer,r==null?void 0:r.endOffset),!o||!this.element.contains(o.startContainer)||!this.element.contains(o.endContainer)?null:o}getCaretPosition(){let t=this.getRange();if(!t||!t.collapsed||!("getBoundingClientRect"in t))return null;let n=t.getBoundingClientRect();return!iE(n)&&(t.insertNode(this.element.ownerDocument.createTextNode("\u2060")),n=t.getBoundingClientRect(),t.deleteContents(),!iE(n))?null:{top:n.top+n.height,left:n.left}}getSelection(){let t=this.getRange();if(t)return Ka(this.element,t);let n=this.lastKnownSelection;if(n&&oE(this.element,n.start,n.end))return n;let r=Ui(this.element);return r.collapse(!1),Ka(this.element,r)}getSelectedText(){let{start:t,end:n}=this.getSelection();return Va(this.element,Lr(this.element,t,n))}applyChanges(t){var o;if(!this.isActive)return;this.isSettingValue=!0;let n=this.getText(),r=t(this.element);return(o=this.observer)==null||o.takeRecords(),Promise.resolve(r).then(()=>{this.currentText=this.getText(),n!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(){super.listen(),this.observer=new MutationObserver(()=>{setTimeout(()=>{this.triggerChange()},0)}),this.observer.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0});let t=this.element.isContentEditable,n=new MutationObserver(()=>{this.element.isContentEditable!==t&&(t=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});n.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>n.disconnect())}dispose(){super.dispose(),this.observer&&this.observer.disconnect()}};function sE(e,t,n){let r=`deepdesk-iframe-${e}`,o=document.getElementById(r);if(o)return o;let i=document.createElement("iframe"),s=new URL(t);return Object.entries(n).forEach(([a,l])=>{s.searchParams.append(a,l)}),i.style.position="absolute",i.style.left="-999em",i.style.width="0px",i.style.height="0px",i.tabIndex=-1,i.id=r,i.title=`iframe-${e}`,i.src=s.toString(),window.document.body.appendChild(i),i}var kh=class{constructor(t){this.name=t;this.broadcastChannel=new BroadcastChannel(t)}broadcastChannel;disposeHandlers=[];onMessage(t){this.broadcastChannel.addEventListener("message",t),this.disposeHandlers.push(()=>{this.broadcastChannel.removeEventListener("message",t)})}postMessage(t){this.broadcastChannel.postMessage(JSON.stringify(t))}close(){this.disposeHandlers.forEach(t=>t()),this.broadcastChannel.close()}},Ph=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.iframe=sE(t,`${this.targetOrigin}/sdk/proxy/proxy.html`,{channel:this.name,host:window.location.origin,debug:"1"}),document.body.appendChild(this.iframe)}iframe;disposeHandlers=[];onMessage(t){window.addEventListener("message",t),this.disposeHandlers.push(()=>{window.removeEventListener("message",t)})}postMessage(t){var n;(n=this.iframe.contentWindow)==null||n.postMessage(JSON.stringify(t),this.targetOrigin)}close(){var t;this.disposeHandlers.forEach(n=>n()),(t=this.iframe)==null||t.remove()}},Ih=class{constructor(t){this.params=t;this.deepdeskUrl=t.deepdeskUrl,this.eventMap=t.eventMap,this.sessionId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}sessionId;deepdeskUrl;channel;defaultChannel;eventMap;get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setSessionId(t){this.sessionId!==t&&(this.cleanup(),j.info("Set sessionId",t),this.sessionId=t,this.channel=this.createChannel(t))}createChannel(t){let n=this.params.createCustomChannel?this.params.createCustomChannel(t):this.isCrossOrigin?new Ph(t,this.deepdeskUrl,{debug:!0}):new kh(t),r=o=>{var s,a;if(o.origin!==this.deepdeskUrl)return;let i=typeof o.data=="string"?JSON.parse(o.data):o.data;i.type==="event"&&i.channel===t&&(j.info("Received broadcast event",this.sessionId,o),(a=(s=this.eventMap)[i.name])==null||a.call(s,i.payload))};return n.onMessage(r),n}send(t,n){var i,s;j.info("Broadcast event",{sessionId:this.sessionId,name:t,payload:n});let r={type:"event",name:t,payload:n};(s=(i=this.eventMap)[t])==null||s.call(i,n);let o=this.sessionId==="deepdesk-general"?this.defaultChannel:this.channel;o==null||o.postMessage({...r,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)}},aE=Ih;var Ki=class extends Error{constructor(n,r){super(n);this.body=r}name="CustomError"};var Rh=e=>new Promise(t=>{setTimeout(t,e)});var Vi=class extends Ki{name="ClientError"},Lh=class extends Ki{name="ServerError"},Gt=class e{constructor(t="",n={}){this.baseUrl=t;this.options=n;n.fetch&&(this.fetch=n.fetch)}latestRequestByUrl={};csrfToken;fetch=window.fetch.bind(window);static refreshingToken=null;patchFetch(t){this.fetch=t(this.fetch)}setCsrfToken(t){this.csrfToken=t}request(t,n={}){return new Promise((r,o)=>{let i={isAborted:!1,reject:o},s=`${this.baseUrl}${t}`,a=this.fetch,{abortLatest:l=!1,attempts:u=1,retryDelay:c=500,refreshTokenOn401:p=!0,retryOnError:d=_=>_ instanceof TypeError,retryOnResponse:f=_=>_.status>=500,version:y="v1",...v}=n,m={credentials:"include",...v,headers:{"Content-Type":"application/json",...v.headers}};n.method!==void 0&&n.method!=="GET"&&this.csrfToken&&(m.headers={...m.headers,"X-CSRFToken":this.csrfToken}),typeof y=="string"&&(m.headers={...m.headers,"X-Deepdesk-API-Version":y});let h=u,g=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[s]&&l&&(this.latestRequestByUrl[s].isAborted=!0,this.latestRequestByUrl[s].reject(new Error("Aborted"))),this.latestRequestByUrl[s]=i;let x=async()=>(h--,a(s,m).then(async _=>f(_)&&!i.isAborted&&h>0?(await Rh(c),x()):_.status===401&&p===!0&&g===!1?(g=!0,await this.refreshToken(),x()):_).catch(async _=>{if(d(_)&&!i.isAborted&&h>0)return await Rh(c),x();throw _}));x().then(_=>_.json().catch(()=>null).then(w=>{_.status>=500?o(new Lh("Server Error",w)):_.status===401?o(new Vi("Unauthorized",w)):_.status===403?o(new Vi("Forbidden",w)):_.status===404?o(new Vi("Not Found",w)):_.status>=400&&o(new Vi("Bad Request",w)),delete this.latestRequestByUrl[s],r(w)})).catch(_=>{o(_)})})}async validateToken(){let{has_valid_access_token:t}=await this.get("/auth/validate");if(!t)return!1;let{is_logged_in:n}=await this.get("/apis/admin/session/validate/",{version:null});return!!n}refreshToken(){return e.refreshingToken||(e.refreshingToken=this.get("/auth/refresh",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{e.refreshingToken=null},1e3*60)})),e.refreshingToken}get(t,n){return this.request(t,n)}post(t,n,r){return this.request(t,{method:"POST",body:JSON.stringify(n),...r})}patch(t,n,r){return this.request(t,{method:"PATCH",body:JSON.stringify(n),...r})}put(t,n,r){return this.request(t,{method:"PUT",body:JSON.stringify(n),...r})}delete(t,n){return this.request(t,{method:"DELETE",...n})}};var yA;(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||={})})(yA||={});function Od(e){return{...Z(e),tags:e.tags}}var zn=class e{constructor(t,n={}){this.options=n;this.client=new Gt(t,{fetch:n.fetch}),this.client.patchFetch(r=>async(o,i)=>{let s=await r(o,i);return this.handleDeepdeskVersionHeaders(s),s})}latestReceivedDeepdeskVersions={};client;shouldFetchCsrfToken=!0;static exchangeTokenPromise=null;async preflight(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let t=await this.getCsrfToken();this.client.setCsrfToken(t)}return this.options.token?(e.exchangeTokenPromise||(e.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),e.exchangeTokenPromise):Promise.resolve()}async createConversation(t){await this.preflight(),j.info(`Creating conversation for session ${t.sessionId} and agent ${t.agentId}`);let n=await this.client.post("/api/conversations",{...ke(t),tags:t.tags},{version:"v2"});return Od(n)}async getProfile(t){let n=await this.client.get(`/apis/admin/profiles/${t}/`,{version:null});return Z(n)}async getKnowledgeAssistant(t){let n=await this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{version:null});return Z(n)}async getContentTypes(){let t=await this.client.get("/apis/admin/content-types/",{version:null});return Z(t)}async getPlatformConfig(){let{config:t}=await this.client.get("/platform/config/",{version:null});return Z(t)}async checkUserExists(t){let{exists:n}=await this.client.get(`/apis/admin/users/exists?external_id=${t}`);return n}async getConversationBySessionId(t,n={}){await this.preflight(),j.info(`Getting conversation for session ${t}`);let{attempts:r=1,retryDelay:o=1e3}=n,i=await this.client.get(`/api/conversations/by_session_id/${t}`,{attempts:r,retryDelay:o,retryOnResponse:s=>s.status===404||s.status>=500,version:"v2"});return Od(i)}async isConversationSupported(t,n={}){j.info(`Check if conversation for session ${t} is supported`);let{attempts:r=1,retryDelay:o=1e3}=n;return(await this.client.get(`/api/conversations/by_session_id/${t}/active_profile`,{attempts:r,retryDelay:o,retryOnResponse:s=>s.status===404||s.status>=500,version:"v2"})).has_active_profile}async updateConversation(t,n){let r=ke(n);n.tags&&(r.tags=n.tags);let o=await this.client.put(`/api/conversations/${t}`,r,{version:"v2"});return Od(o)}async postMessages(t,n){return(await this.client.post(`/api/conversations/${t}/messages`,n.map(o=>({...ke(o),tags:o.tags})),{version:"v2"})).map(o=>Od(o))}async sendEvent(t,n){let{data:r,...o}=n,i=Object.entries(this.latestReceivedDeepdeskVersions).reduce((s,[a,l])=>({...s,[a]:l}),{});return this.client.post("/api/events",ke({...i,...o,data:r,name:t}),{version:"v2"})}async sendEventV1(t,n){let r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((o,[i,s])=>({...o,[i]:s}),{});return this.client.post("/api/events",{event:t,data:ke({...n,...r})})}async getEntities(t){return(await this.client.post("/api/entities",{messages:t.filter(r=>r.text)})).entities}async getSummary(t,n={}){return(await this.client.post("/api/summary",{conversation:{messages:t.filter(o=>o.text&&o.source),agent_id:n.agentId,id:n.externalConversationId},prompt_instruction:n.promptInstruction,model:n.model})).summary}async getTemporaryExchangeToken(){return(await this.client.get("/auth/exchange-token",{version:null})).jwt}async exchangeTokenForAccessCookie(t){return this.client.post("/apis/admin/session/jwt/",{jwt:t},{version:null}).catch(n=>{throw j.warn(`Invalid token '${t}'`),n})}async authenticateWithKey(t,n){await this.client.post("/apis/admin/session/api-key/",ke(n),{version:null,refreshTokenOn401:!1,headers:{apikey:t}})}async getTextSuggestions(t,n={},r){return r==="sticky-messages"?this.getPinnedMessages(t):(await this.client.post(`/api/conversations/${t}/recommend/${r}`,ke(n),{abortLatest:!0})).map(i=>({...Z(i),text:i.text||i.url||i.message,source:r,type:r})).filter((i,s,a)=>s===a.findIndex(l=>l.text===i.text))}async isLoggedIn(){return await this.preflight(),this.client.validateToken()}async getAutocompleteSuggestions(t,n){return(await this.client.post(`/api/conversations/${t}/autocomplete`,ke(n),{abortLatest:!0})).map(o=>({score:1,source:o.source,sourceText:o.source_text,text:o.label,trainingJobs:o.training_jobs,searchKeywords:o.search_keywords,type:o.source})).filter((o,i,s)=>i===s.findIndex(a=>a.text===o.text))}async getPinnedMessages(t){let n=await this.client.get(`/api/conversations/${t}/sticky-messages`,{abortLatest:!0});return Z(n).map(r=>({...r,text:r.message,source:"sticky-messages",type:"pinned-message"}))}async getStyleSuggestions(t){let n=await this.client.post("/api/style-suggestions",ke(t),{abortLatest:!0});return Z(n)}async search(t){let n=await this.client.post(`/api/profiles/${t.profile}/search`,ke(t),{version:"v2"});return Z(n)}async knowledgeAssist(t,n,r){let o=await this.client.post(`/api/knowledge-assist/assistants/${r}/search`,ke({question:t.question,promptInstruction:t.promptInstruction,chatHistory:n.map(i=>({question:i.question,answer:i.answer.answer}))}),{version:"v2"});return Z(o)}async requestLoginByEmail(t){let n=await this.client.post("/apis/admin/session/passwordless/request/",{email:t},{version:null});return Z(n)}async requestPasswordlessToken(){let t=await this.client.get("/apis/admin/session/passwordless/request/",{version:null});return Z(t.token)}async getCsrfToken(){let{token:t}=await this.client.get("/apis/admin/session/csrf/",{version:null});return t}async verifyLoginToken(t){let n=await this.client.post("/apis/admin/session/passwordless/login/",{token:t},{version:null});return Z(n)}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),i=o.match(Cy);if(!n||!i)return;let s=i[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[s];a&&n&&a!==n&&j.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[s]=n})}};var Wa=class{constructor(t,n){this.url=t;this.options={timeout:25e3,...n}}eventListeners={};options;timeoutTimer;eventSource;proxyEvent(t){this.eventSource.addEventListener(Mg(t),n=>{let{data:r}=n;try{let o=JSON.parse(r);this.emit(t,Z(o))}catch{j.warn(`Invalid JSON for ${t}: ${r}`)}})}connect(){clearTimeout(this.timeoutTimer);let t=new EventSource(this.url,{withCredentials:!0});this.eventSource=t;let n=!1;t.onopen=()=>{n=!0},t.onerror=()=>{n&&t.readyState===2&&this.connect()},this.timeoutTimer=setTimeout(()=>{t.close(),this.connect()},this.options.timeout),Object.keys(this.eventListeners).forEach(r=>{this.proxyEvent(r)})}disconnect(){var t;clearTimeout(this.timeoutTimer),this.eventListeners={},(t=this.eventSource)==null||t.close()}emit(t,n){this.eventListeners[t]&&this.eventListeners[t].forEach(r=>r(n))}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),this.proxyEvent(t),()=>{this.off(t,n)}}off(t,n){let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}};var vA;(t=>{let e;(i=>(i.Started="Started",i.Aborted="Aborted",i.Completed="Completed"))(e=t.AutoflowSessionState||={})})(vA||={});var $a=class{constructor(t,n={}){this.apiUrl=t;this.client=new Gt(t,n)}client;streams={};logger=j;async getCustomMessages(t){let n=await this.client.get(`/sessions/${t}/suggestions`);return Z(n.suggestions)}async sendCustomMessage(t,n){let r=await this.client.post(`/sessions/${t}/messages`,ke(n));return Z(r)}async answerCustomMessage(t,n){await this.client.post(`/sessions/${t}/answers`,ke(n))}async getAutoflows(t){let n=await this.client.get(`/sessions/${t}/autoflows`);return Z(n.autoflows)}async startAutoflowSession(t){let n=await this.client.post("/autoflow-sessions",ke(t));return Z(n)}async stopAutoflowSession(t){await this.client.delete(`/autoflow-sessions/${t}`)}openStream(t){return this.streams[t]||(this.streams[t]=new Wa(`${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 lE={startTime:null,stopTime:null},uE=z({name:"handlingTime",initialState:lE,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(te,()=>lE)}}),{handlingTimeStart:cE,handlingTimeStop:Nd,handlingTimeReset:dE}=uE.actions,pE=uE.reducer;var fE=(e={})=>{let t={onAuthError:Oi(!1),...e};return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var Md={list:{keywordMatches:[]},fetchState:"idle",isInitialRequest:null};var Eo=D("styleSuggestions/getAll",async({text:e},t)=>{var s;let{deepdeskAPI:n}=t.extra,r=t.getState(),{showStyleSuggestions:o}=r.settings,i=(s=r.conversation.current)==null?void 0:s.profileCode;if(!o)return Md.list;if(!i)throw new Error("No current conversation to fetch pinned messages");return n.getStyleSuggestions({profileCode:i,message:e})}),SA=z({name:"styleSuggestions",initialState:Md,reducers:{},extraReducers:e=>{e.addCase(Eo.pending,t=>{t.isInitialRequest=t.isInitialRequest===null,t.fetchState="loading"}).addCase(Eo.rejected,t=>{t.fetchState="error"}).addCase(Eo.fulfilled,(t,n)=>{t.fetchState="done",hr(t.list,n.payload)||(t.list=n.payload)}).addCase(no,t=>{t.list=Md.list}).addCase(te,()=>Md)}}),mE=SA.reducer;var gE=(e={})=>{let t,n=!0,r={getStyleSuggestions:Eo,debounce:500,...e};return o=>i=>s=>{var f;let a=o.getState().input.text,l=i(s),u=o.getState();if(u.auth.isLoggedIn!==!0)return l;let{showStyleSuggestions:c}=u.settings;if(!((f=u.conversation.current)==null?void 0:f.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 xA(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end}var hE=(e={})=>{let t={getTextSuggestions:Vt,getAutocompleteSuggestions:Ea,debounce:200,check:ji,...e},n;return r=>o=>i=>{var v;let{input:{userCommitted:s}}=r.getState(),a=o(i),l=r.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:u,showTabCompletion:c}=l.settings,p=(v=l.conversation.current)==null?void 0:v.id,d=i.type===rd.toString();if(!p||!u&&!c)return a;let{input:{userCommitted:f}}=l;return xA(f,s)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let m=xi(l);m===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(m))},d?0:t.debounce)),a}};var yE=Eo.fulfilled.toString();function _A(e,t){let n=new Set([...t.keywordMatches.map(o=>o.keyword)]),r=[];return n.forEach(o=>{let i=e.keywordMatches.filter(l=>l.keyword===o),s=t.keywordMatches.filter(l=>l.keyword===o),a=s.length-i.length;a<=0||r.push(...s.slice(0,a))}),r}var vE=e=>t=>n=>r=>{var u;if(r.type!==yE){n(r);return}let o=t.getState().styleSuggestions.list;n(r);let i=t.getState(),s=i.styleSuggestions.list,a=(u=i.conversation)==null?void 0:u.current;if(o===s)return;let l=_A(o,s);r.type===yE&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var wA=Iu({activeSuggestion:Rw,answer:w1,auth:Kw,autoflows:Sb,conversation:qx,contentTypes:o1,customMessages:Pb,passwordlessToken:Ab,entities:l1,knowledgeAssistant:S1,handlingTime:pE,info:iw,input:Jm.reducer,overlayInput:rt.reducer,settings:jx,profile:C1,search:dw,summary:m1,styleSuggestions:mE,ui:Nw,textSuggestions:Cw});function SE(e){return V0({reducer:wA,middleware:t=>[...t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI,deepdeskBrokerAPI:e.deepdeskBrokerAPI}},serializableCheck:!1}),fE(),hE({debounce:200}),gE({debounce:500}),vE(e.deepdeskAPI),...e.middleware?e.middleware:[]],preloadedState:e.preloadedState})}var bA=e=>{var t;return((t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())??"unknown"},EA=e=>t=>n=>r=>{var a;let o=t.getState(),i=qm("inlineSuggestions")(o);switch(r.type){case Rn.toString():{let l=nd(r.payload.contentType)(t.getState()),u=l.indexOf(r.payload.suggestion);e.emit("edit-suggestion",{contentType:r.payload.contentType,index:u,suggestions:l});break}case Oi.toString():{!r.payload&&e.emit("logout",void 0);break}case Bt.toString():{let{start:l,end:u}=o.input.selection;e.emit("select-suggestion",{type:bA(r.payload.suggestion),...r.payload,replace:r.payload.replace==="selection"?{start:l,end:u}:{start:0,end:u}},{mayApplyChanges:!0});break}case fc.toString():{let{start:l,end:u}=o.input.selection;e.emit("replace",{...r.payload,replace:r.payload.replace==="selection"?{start:l,end:u}:{start:0,end:u}},{mayApplyChanges:!0});break}case sa.toString():{let l=t.getState(),{text:u,selection:c}=l.input.userCommitted;e.emit("reset",{text:u,selectionAfter:c},{mayApplyChanges:!0});break}case yc.toString():e.emit("select-image",r.payload,{mayApplyChanges:!0}),e.sendEvent("Image attached",{conversationId:o.conversation.current.id,data:{path:r.payload.suggestion.image,title:r.payload.suggestion.title}});break;case $t.fulfilled.toString():r.payload.length>0&&e.sendEvent("entities found",{conversationId:o.conversation.current.id,data:{entities:r.payload}});break;case On.fulfilled.toString():e.sendEvent("conversation summarized",{conversationId:o.conversation.current.id,data:{summary:r.payload.summary}});break;case Be.toString():e.sendEvent(r.payload.name,{conversationId:((a=r.payload.options)==null?void 0:a.includeConversationData)&&o.conversation.current.id,data:r.payload.data});break;case mc.toString():e.handleKeyDown(r.payload);break;case no.toString():e.logSendMessage(r.payload);break;case gc.toString():e.logSendEditSuggestionMessage(r.payload);break;case hc.toString():e.handleInputChanged(r.payload);break;default:break}let s=n(r);switch(r.type){case no.toString():e.handleAfterSendMessage(r.payload);break;case Ca.toString():e.onUpdateShowTabHint(r.payload);break;case Nd.toString():e.logHandlingTime();break;case Bt.toString():{i&&(t.dispatch(on([])),t.dispatch(wn()));break}case on.toString():{i&&r.payload.length>0&&t.dispatch(vr(0));break}default:break}return s},xE=EA;function Ah(e){return e.toISOString().replace("T"," ").replace("Z","")}function _E(e,t){var o,i,s;let{startTime:n,stopTime:r}=e.handlingTime;if(!n||!r)throw new Error("No startTime and stopTime for handling time metrics");return{conversationId:e.conversation.current.id,clientVersion:t.version,agentId:(o=e.info.agentInfo)==null?void 0:o.agentId,agentName:(i=e.info.agentInfo)==null?void 0:i.agentName,agentEmail:(s=e.info.agentInfo)==null?void 0:s.agentEmail,timeStart:Ah(n),timeStop:Ah(r)}}function Oh(e,t,n){var C,I,k;let{text:r,metrics:{numCharsTyped:o,numCharsPasted:i,numCharsCut:s,numCharsDeleted:a,numPaste:l,agentStartedTypingTimestamp:u,externalTimeTotalSeconds:c,pastes:p,cuts:d,deletions:f,textSuggestions:y,offeredTextSuggestions:v}}=t[e],m=r.length,g=y.reduce((K,{text:N,searchTerm:B})=>K+N.length-(B?B.length:0),0),x=u??Date.now(),_=(Date.now()-x)/1e3+(c||0),w=o/_,E=y.reduce((K,{searchTerm:N})=>K+(N?N.length:0),0);return{conversationId:t.conversation.current.id,source:"agent",text:r,clientVersion:n.version,pastes:p,cuts:d,deletions:f,lenTextTyped:o+E,lenTextTotal:m,lenTextAssisted:g,lenTextPasted:i,lenTextCut:s,lenTextDeleted:a,timeTotalSeconds:_,charsPerSecond:w,numPastes:l,textSuggestionsV2:y,suggestionsCounters:[{source:"gpt",countOffered:v.filter(K=>K.source==="gpt").length}],agentId:(C=t.info.agentInfo)==null?void 0:C.agentId,agentName:(I=t.info.agentInfo)==null?void 0:I.agentName,agentEmail:(k=t.info.agentInfo)==null?void 0:k.agentEmail}}function Nh(e,t){var i;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return Nh(r,t);let o=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;return o?Nh(o,t):null}function wE(e,t){return Nh(e,t)}function bE(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function CA(e){return typeof e=="object"&&e!==null&&"tagName"in e}function Dd(e){return CA(e)&&(Pr(e)||zc(e))}var EE=(e,t)=>({value(){try{let n=sessionStorage.getItem(`dd-${e}`);if(!n)return t;try{return JSON.parse(n)}catch{return t}}catch{return t}},update(n){try{sessionStorage.setItem(`dd-${e}`,JSON.stringify(n))}catch{j.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function TA(e){return e.offsetParent!==null}function CE(e){if(!TA(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 Fd(e,t,n=100){let r=CE(e);t({isVisible:r});let o=setInterval(()=>{let i=CE(e);i!==r&&(r=i,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var we=S(b());var TE=EE("showTabHint",!0),qa=class e{static version="10.10.3";static count=0;deepdeskApi;inputMediator=null;version;broadcastEvents;eventListeners={};unmountHandlers=[];widgetRoot=null;dynamicThunkObject={};isMounted=!1;instanceId;shouldRender=!0;store;constructor({deepdeskUrl:t,brokerUrl:n,version:r=e.version||"unknown",locale:o="en-US",token:i,fetch:s,productName:a,createCustomChannel:l}){let u=t.replace(/\/api$/,"");this.deepdeskApi=new zn(u,{token:i,fetch:s}),this.version=r,this.instanceId=e.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[xE({emit:(p,d,f)=>this.emit(p,d,f),handleAfterSendMessage:p=>this.handleAfterSendMessage(p),handleInputChanged:p=>this.handleInputChanged(p),handleKeyDown:p=>this.handleKeyDown(p),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:p=>this.logSendMessage(p),logSendEditSuggestionMessage:p=>this.logSendEditMessage(p),onUpdateShowTabHint:p=>TE.update(p),sendEvent:(p,d)=>this.deepdeskApi.sendEvent(p,d)})]};n&&Object.assign(c,{deepdeskBrokerAPI:new $a(n)}),this.store=SE(c),this.broadcastEvents=new aE({debug:!0,deepdeskUrl:u,eventMap:Vw(this.store),createCustomChannel:l}),this.store.dispatch(oa),this.store.dispatch(Ca(TE.value())),this.store.dispatch(oa({locale:o,adminUrl:u,productName:a}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){return this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex]??null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}sessionId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.sessionId}shouldAbort(){return this.state.conversation.isSupported===!1?(j.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(j.warn("Profile has not been loaded (yet)"),!0):(j.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(Oi(null)),this.store.dispatch(Ln()),new Promise(t=>{let n=this.store.subscribe(()=>{let r=this.store.getState();Ge(r)&&Fw(r)!=="loading"&&(n(),t())});this.unmountHandlers.push(()=>{n()})})}async isLoggedIn(){return(await this.store.dispatch(Ln())).payload}async setPlatformAgentId(t){try{if((await this.deepdeskApi.client.get("/apis/admin/session/me/",{version:null})).external_id)return;await this.deepdeskApi.client.request("/apis/admin/session/me/",{method:"PATCH",body:JSON.stringify({external_id:t}),version:null})}catch(n){j.warn("Failed to attach user:",n)}}async isConversationSupported(t,n){return(await this.store.dispatch(Ym({sessionId:t,options:n}))).payload}async createConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(ac(t))).payload}async getConversationBySessionId(t,n){return this.hasConversation()&&this.sessionId()!==t&&this.resetConversation(),(await this.store.dispatch(lc({sessionId:t,options:n}))).payload}async upsertConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(Zm(t))).payload}async postMessages(t){return(await this.store.dispatch(cc(t))).payload}async updateConversation(t){return(await this.store.dispatch(uc(t))).payload}resetConversation(){this.store.dispatch(te()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}async getSummary(){let t=await this.store.dispatch(On());if(t.error)throw new Error(t.error.message);return t.payload.summary}configure(t){this.store.dispatch(oa(t))}setVisitorInfo(t){this.store.dispatch(ow(t))}async setAgentInfo(t){await this.store.dispatch(xa(t))}async setAgentSettings(t){await this.store.dispatch(Dg(t))}async getAgentSettings(){return(await this.store.dispatch(Fg())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let t=[];return this.store.dispatch(rd()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})}notifyInputChanged(t){this.store.dispatch(hc(t))}notifyKeyDown(t){this.store.dispatch(mc(t))}notifyPaste(t,n){this.store.dispatch(o_({text:t,selectionText:n}))}notifyCut(t){this.store.dispatch(n_(t))}notifyExternalSuggestion(t){this.store.dispatch(Bt(t)),this.store.dispatch(wn())}notifyEditSuggestion(t){this.store.dispatch(bw(t.contentType,t.suggestions)),this.store.dispatch(Rn({contentType:t.contentType,suggestion:typeof t.index=="number"?t.suggestions[t.index]:null}))}handleInputChanged(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui;n&&r&&this.store.dispatch(Er({collapse:!1})),this.inputMediator&&this.store.dispatch(Qx({text:t,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(on([])))}handleKeyDown(t){let{overlayCollapsed:n}=this.state.ui,{textSuggestions:r,selectedSuggestionIndex:o,selection:i}=this.state.input,{inlineSuggestions:s}=this.state.settings,a=r.length>0,l=o!==-1;if(this.store.dispatch(r_(pc(t))),t.key!=="Tab"&&!this.settings.showTextSuggestions)return;let u=()=>{n||!a||i&&(t.shiftKey||(this.store.dispatch(Jx()),s||this.stageSelectedSuggestion({inputType:"arrow"}),t.preventDefault()))},c=()=>{n||!a||s&&o<=0||i&&(t.shiftKey||(this.store.dispatch(t_()),t.preventDefault(),!s&&(this.state.input.selectedSuggestionIndex===-1?this.store.dispatch(sa()):this.stageSelectedSuggestion({inputType:"arrow"}))))};switch(t.key){case"Up":case"ArrowUp":s?c():u();return;case"Down":case"ArrowDown":{s?u():c();return}case"Esc":case"Escape":{s&&l&&this.store.dispatch(vr(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(vr(-1)),this.store.dispatch(sa()),t.preventDefault()):n||(this.store.dispatch(Er({collapse:!0})),this.store.dispatch(Aw(!0)),t.preventDefault());return}case"Tab":{let{userCommitted:p}=this.state.input,d=p.text.substring(0,p.selection.end),{tabCompletionSuggestion:f}=this.state.input;this.store.dispatch(Ca(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):!s&&this.settings.showTabCompletion&&f&&f.text.startsWith(d)&&(this.store.dispatch(Bt({text:f.text,suggestion:f,eventMetrics:{inputType:"tab"},replace:"until-selection-end"})),this.store.dispatch(wn())),t.preventDefault();break}default:}}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(i_()),this.store.dispatch(on([]))}handlingTimeStart(){this.state.handlingTime.startTime||(j.info("Start handling time"),this.store.dispatch(cE()))}handlingTimeStop(){this.state.handlingTime.startTime&&(j.info("Stop handling time"),this.store.dispatch(Nd()))}logSendMessage(t){let n=Oh("input",this.state,{version:this.version});t&&(Object.assign(n,{text:t}),Object.assign(n,{lenTextTotal:t.length})),this.deepdeskApi.sendEventV1("Send Message",n),this.emit("send-message-event",n)}logSendEditMessage(t){let n=Oh("overlayInput",this.state,{version:this.version});t&&Object.assign(n,{text:t}),this.store.dispatch(Zx(this.state.overlayInput.metrics))}logHandlingTime(){let t=_E(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",t),this.store.dispatch(dE())}notifySubmit(t={}){this.shouldAbort()||(this.store.dispatch(wn()),this.store.dispatch(no(t.text??this.state.input.text)))}stageSelectedSuggestion(t){let n=this.state.input.selectedSuggestionIndex,{textSuggestions:r}=this.state.input;this.store.dispatch(Bt({text:r[n].text,suggestion:r[n],eventMetrics:t,replace:"until-selection-end"}))}emit(t,n,r={}){let o=()=>{this.eventListeners[t]&&this.eventListeners[t].forEach(i=>{try{i(n)}catch(s){j.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),j.error(s)}})};this.inputMediator&&r.mayApplyChanges?this.inputMediator.applyChanges(o):o()}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),()=>{this.off(t,n)}}off(t,n){if(!t&&!n){this.eventListeners={};return}let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}setConversationQuery(t){this.dynamicThunkObject.conversationQuery=t}whenConversationLoaded(t){let n=()=>this.loadProfileConfig().then(()=>t());this.hasConversation()&&n();let r=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==r&&(r=this.hasConversation(),r&&n())})}overlayContainerFactory(t,n,r,o){let[i,s]=lo(n,r);return i.setAttribute("translate","no"),i.dataset.testid=t,o&&i.classList.add(o),this.unmountHandlers.push(()=>{(0,Nt.unmountComponentAtNode)(i),s(),i.remove()}),i}createInlineContainer(t,n){var s;let r=document.createElement("div");r.style.position="absolute",r.style.top="0px",r.style.left="0px",r.style.height="0px",r.style.width="0px";let o=document.createElement("div");o.style.display="none",o.style.position="absolute",o.style.height="0px",o.style.width="0px",o.style.backgroundColor="red",r.appendChild(o);let i=(s=t.ownerDocument.defaultView)==null?void 0:s.frameElement;if(i){let[a,l]=lo(i,{appendTo:document.body,onMoveStart:()=>{o.style.display="none"}});a.dataset.testid=n,a.style.zIndex="2",a.appendChild(r),this.unmountHandlers.push(()=>{(0,Nt.unmountComponentAtNode)(o),l()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return ao(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,Nt.unmountComponentAtNode)(o),o.remove()}),o}storeMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(t,n),j.info(`Stored analytics for ${this.conversationId()}`)}catch{}}restoreMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=window.sessionStorage.getItem(t);if(!n)return;let r=JSON.parse(n);r.text.trim()===this.state.input.text.trim()?(j.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(a_(r.metrics))):j.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(t)}catch{}}mount(t,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!Dd(t))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let{customStyles:r={},showStyleSuggestions:o,showTabCompletion:i,showTextSuggestions:s,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,isEmbedded:p,detectSubmit:d,insertLink:f,inputMediator:y,closestScrollSelector:v,appendOverlayTo:m,inlineSuggestions:h,floatingMenu:g}=n;this.configure({showStyleSuggestions:o,showTabCompletion:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,showTextSuggestions:s,insertLink:f,isEmbedded:p,inlineSuggestions:h,floatingMenu:!!g}),n.automaticHandlingTime&&this.setupHandlingTime(t),ao(t),this.inputMediator=y||(Pr(t)?new Pn(t):new bo(t)),this.inputMediator.on("change",({plainText:w})=>{this.notifyInputChanged(w)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(s_({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()}))}),this.inputMediator.on("keydown",w=>{this.notifyKeyDown(w)}),this.inputMediator.on("paste",({pastedText:w,selectionText:E})=>{this.notifyPaste(w,E)}),this.inputMediator.on("cut",({selectionText:w})=>{this.notifyCut(w)});let x=v&&wE(t,v)||void 0;if(h){let{customStyles:w,appendOverlayTo:E}=n;if(Pr(t))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let C=this.createInlineContainer(t,"deepdesk-caret");(0,Nt.render)((0,we.jsx)(wo,{store:this.store,customStyles:w,children:(0,we.jsx)(yo,{broadcastEvents:this.broadcastEvents,children:(0,we.jsx)(K1,{})})}),C),this.inputMediator.on("caret",k=>{this.store.dispatch(on([])),k?(C.style.display="block",C.style.top=`${k.top}px`,C.style.left=`${k.left}px`):C.style.display="none"});let I=this.overlayContainerFactory("floating-menu",x||t,{appendTo:typeof g=="object"&&"appendOverlayTo"in g?g.appendOverlayTo:E},w==null?void 0:w.floatingMenuRootNode);(0,Nt.render)((0,we.jsx)(wo,{store:this.store,customStyles:w,children:(0,we.jsx)(yo,{broadcastEvents:this.broadcastEvents,children:(0,we.jsx)(F1,{onLogIn:()=>this.loginViaPopup().catch(k=>j.warn(k.message))})})}),I)}else{let w=this.overlayContainerFactory("deepdesk-tab-completion",x||t,{appendTo:m,closestScrollElement:x,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),E=this.overlayContainerFactory("deepdesk-suggestions-overlay",x||t,{appendTo:m},r==null?void 0:r.suggestionsRootNode);(0,Nt.render)((0,we.jsx)(wo,{store:this.store,customStyles:r,children:(0,we.jsx)(yo,{broadcastEvents:this.broadcastEvents,children:(0,we.jsx)(fb,{inputElement:t})})}),w),(0,Nt.render)((0,we.jsx)(wo,{store:this.store,customStyles:r,children:(0,we.jsx)(yo,{broadcastEvents:this.broadcastEvents,children:(0,we.jsx)(Y1,{onLogIn:()=>this.loginViaPopup().catch(C=>j.warn(C.message))})})}),E)}(0,Nt.render)((0,we.jsx)(wo,{store:this.store,customStyles:r,children:(0,we.jsx)(yo,{broadcastEvents:this.broadcastEvents,children:(0,we.jsx)(A1,{})})}),this.createContainer("deepdesk-overlays"));let _;this.inputMediator.on("selection",w=>{clearTimeout(_),w===null?_=setTimeout(()=>{w!==null&&this.store.dispatch(eg(w))},500):this.store.dispatch(eg(w))}),this.inputMediator.on("disabled",()=>{var w;(w=this.inputMediator)==null||w.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(Ai(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(Ai(!0))),this.store.dispatch(Yx({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.unmountHandlers.push(()=>{this.state.input.text!==""&&(this.store.dispatch(wn()),this.storeMetrics())}),this.whenConversationLoaded(()=>{var w;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((w=this.state.conversation.current)==null?void 0:w.sessionId)}),this.isMounted=!0}unmount(){var t;this.unmountHandlers.forEach(n=>n()),this.unmountHandlers=[],(t=this.inputMediator)==null||t.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(t,n={}){if(this.widgetRoot&&j.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,isEmbedded:i}=n;this.widgetRoot=t,this.configure({showImages:o,isEmbedded:i}),(0,Nt.render)((0,we.jsx)(wo,{store:this.store,customStyles:r,children:(0,we.jsx)(yo,{broadcastEvents:this.broadcastEvents,children:(0,we.jsx)(rE,{onLogIn:()=>this.loginViaPopup().catch(s=>j.warn(s.message))})})}),t),this.whenConversationLoaded(()=>{var s;this.broadcastEvents.setSessionId((s=this.state.conversation.current)==null?void 0:s.sessionId)})}unmountWidget(){this.widgetRoot&&(0,Nt.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(t){let n=Fd(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){bE(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(Da());let t=Tr(this.state);t&&(await this.store.dispatch(Na()),this.store.dispatch(oa({showSearch:t.search,showAutoflows:t.autoflows,showCustomMessages:t.customMessages,showImageSearch:t.imageSearch,showEntitiesCommand:t.entitiesCommand,showSummaryCommand:t.summarizer,showKnowledgeSearch:!!t.knowledgeAssistant,recommendTextSuggestions:t.recommendTextSuggestions})))}),this.loadProfileConfigPromise)}async loginViaPopup(t){return new Promise((n,r)=>{let o=new MessageChannel,i=o.port1,s=this.state.settings.adminUrl,a=new URL(t!=null&&t.url?t==null?void 0:t.url:`${s}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let l=!1,u=()=>{c&&!c.closed&&c.close(),window.removeEventListener("message",p),clearInterval(d)};i.onmessage=async f=>{var y,v;if((y=f.data)!=null&&y.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((v=f.data)==null?void 0:v.jwt),await this.isLoggedIn(),this.broadcastEvents.send(Pa),l=!0,o.port1.close(),n()}catch(m){console.error(m),r(m)}finally{l=!0,u()}};let c=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");c===null&&r(new Error("Popup blocked by browser"));let p=async f=>{var y;if(f.origin===a.origin)switch((y=f.data)==null?void 0:y.type){case"deepdesk-popup-loaded":{try{let v=JSON.stringify({type:"deepdesk-popup-create-channel"});c==null||c.postMessage(v,a.origin,[o.port2])}catch(v){j.error("Error posting message to popup",v),r(v)}break}case"deepdesk-popup-error":{u(),f.data.message==="Timeout"&&j.warn("Popup timed out. Check if the account's platform url is configured correctly."),r(new Error(f.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)})}async checkForTrialMode(t){try{let{account:n}=await this.deepdeskApi.getPlatformConfig();if(!n.isTrial){this.shouldRender=!0;return}if(j.info("Trial is active"),!await this.deepdeskApi.checkUserExists(t))throw new Error("User is not in trial");this.shouldRender=!0}catch(n){let{message:r}=n;j.info(r),this.shouldRender=!1}}async refreshWidgetSuggestions(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=ad(this.state);try{n.forEach(({type:r})=>{r==="entities"?this.store.dispatch($t()):this.store.dispatch(Vt(r))})}catch(r){this.handleError(r)}}};async function kE(e,t,n={}){let{value:r}=e,{start:o,end:i}=n.replace??{start:0,end:r.length},s=`${r.slice(0,o)}${t}${r.slice(i)}`,a=n.selectionAfter??{start:o+t.length,end:o+t.length},l=()=>{if(n.setValue)return n.setValue(s);e.value=s};return Promise.resolve(l()).then(()=>{e.selectionStart=a.start,e.selectionEnd=a.end,e.blur(),e.focus()})}async function PE(e,t,n={}){let r=n.replace?Lr(e,n.replace.start,n.replace.end):Ui(e),o,i=()=>{if(n.setRange)return n.setRange(r.cloneRange());r.deleteContents(),o=document.createElement("span"),r.insertNode(o),n.insertBRs!==!1?t.split(`
25
+ `);break}default:break}p&&s++}return l(e),a}function iE(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var bo=class extends kn{observer;lastKnownSelection=null;getRootNode(){return this.element.getRootNode()}getText(){let t=new Range;return t.selectNodeContents(this.element),Va(this.element,t)}getHTML(){return this.element.innerHTML||""}getRange(){var i;let t=this.getRootNode();if(t.activeElement!==this.element)return null;let n="getSelection"in t?t.getSelection():window.getSelection();if(!n)return null;let r="getComposedRanges"in n&&t instanceof ShadowRoot?(i=n.getComposedRanges(t))==null?void 0:i[0]:n.rangeCount>0?n.getRangeAt(0):null;if(!r)return null;let o=this.element.ownerDocument.createRange();return o.setStart(r==null?void 0:r.startContainer,r==null?void 0:r.startOffset),o.setEnd(r==null?void 0:r.endContainer,r==null?void 0:r.endOffset),!o||!this.element.contains(o.startContainer)||!this.element.contains(o.endContainer)?null:o}getCaretPosition(){let t=this.getRange();if(!t||!t.collapsed||!("getBoundingClientRect"in t))return null;let n=t.getBoundingClientRect();return!iE(n)&&(t.insertNode(this.element.ownerDocument.createTextNode("\u2060")),n=t.getBoundingClientRect(),t.deleteContents(),!iE(n))?null:{top:n.top+n.height,left:n.left}}getSelection(){let t=this.getRange();if(t)return Ka(this.element,t);let n=this.lastKnownSelection;if(n&&oE(this.element,n.start,n.end))return n;let r=Ui(this.element);return r.collapse(!1),Ka(this.element,r)}getSelectedText(){let{start:t,end:n}=this.getSelection();return Va(this.element,Lr(this.element,t,n))}applyChanges(t){var o;if(!this.isActive)return;this.isSettingValue=!0;let n=this.getText(),r=t(this.element);return(o=this.observer)==null||o.takeRecords(),Promise.resolve(r).then(()=>{this.currentText=this.getText(),n!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(){super.listen(),this.observer=new MutationObserver(()=>{setTimeout(()=>{this.triggerChange()},0)}),this.observer.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0});let t=this.element.isContentEditable,n=new MutationObserver(()=>{this.element.isContentEditable!==t&&(t=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});n.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>n.disconnect())}dispose(){super.dispose(),this.observer&&this.observer.disconnect()}};function sE(e,t,n){let r=`deepdesk-iframe-${e}`,o=document.getElementById(r);if(o)return o;let i=document.createElement("iframe"),s=new URL(t);return Object.entries(n).forEach(([a,l])=>{s.searchParams.append(a,l)}),i.style.position="absolute",i.style.left="-999em",i.style.width="0px",i.style.height="0px",i.tabIndex=-1,i.id=r,i.title=`iframe-${e}`,i.src=s.toString(),window.document.body.appendChild(i),i}var kh=class{constructor(t){this.name=t;this.broadcastChannel=new BroadcastChannel(t)}broadcastChannel;disposeHandlers=[];onMessage(t){this.broadcastChannel.addEventListener("message",t),this.disposeHandlers.push(()=>{this.broadcastChannel.removeEventListener("message",t)})}postMessage(t){this.broadcastChannel.postMessage(JSON.stringify(t))}close(){this.disposeHandlers.forEach(t=>t()),this.broadcastChannel.close()}},Ph=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.iframe=sE(t,`${this.targetOrigin}/sdk/proxy/proxy.html`,{channel:this.name,host:window.location.origin,debug:"1"}),document.body.appendChild(this.iframe)}iframe;disposeHandlers=[];onMessage(t){window.addEventListener("message",t),this.disposeHandlers.push(()=>{window.removeEventListener("message",t)})}postMessage(t){var n;(n=this.iframe.contentWindow)==null||n.postMessage(JSON.stringify(t),this.targetOrigin)}close(){var t;this.disposeHandlers.forEach(n=>n()),(t=this.iframe)==null||t.remove()}},Ih=class{constructor(t){this.params=t;this.deepdeskUrl=t.deepdeskUrl,this.eventMap=t.eventMap,this.sessionId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}sessionId;deepdeskUrl;channel;defaultChannel;eventMap;get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setSessionId(t){this.sessionId!==t&&(this.cleanup(),j.info("Set sessionId",t),this.sessionId=t,this.channel=this.createChannel(t))}createChannel(t){let n=this.params.createCustomChannel?this.params.createCustomChannel(t):this.isCrossOrigin?new Ph(t,this.deepdeskUrl,{debug:!0}):new kh(t),r=o=>{var s,a;if(o.origin!==this.deepdeskUrl)return;let i=typeof o.data=="string"?JSON.parse(o.data):o.data;i.type==="event"&&i.channel===t&&(j.info("Received broadcast event",this.sessionId,o),(a=(s=this.eventMap)[i.name])==null||a.call(s,i.payload))};return n.onMessage(r),n}send(t,n){var i,s;j.info("Broadcast event",{sessionId:this.sessionId,name:t,payload:n});let r={type:"event",name:t,payload:n};(s=(i=this.eventMap)[t])==null||s.call(i,n);let o=this.sessionId==="deepdesk-general"?this.defaultChannel:this.channel;o==null||o.postMessage({...r,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)}},aE=Ih;var Ki=class extends Error{constructor(n,r){super(n);this.body=r}name="CustomError"};var Rh=e=>new Promise(t=>{setTimeout(t,e)});var Vi=class extends Ki{name="ClientError"},Lh=class extends Ki{name="ServerError"},Gt=class e{constructor(t="",n={}){this.baseUrl=t;this.options=n;n.fetch&&(this.fetch=n.fetch)}latestRequestByUrl={};csrfToken;fetch=window.fetch.bind(window);static refreshingToken=null;patchFetch(t){this.fetch=t(this.fetch)}setCsrfToken(t){this.csrfToken=t}request(t,n={}){return new Promise((r,o)=>{let i={isAborted:!1,reject:o},s=`${this.baseUrl}${t}`,a=this.fetch,{abortLatest:l=!1,attempts:u=1,retryDelay:c=500,refreshTokenOn401:p=!0,retryOnError:d=_=>_ instanceof TypeError,retryOnResponse:f=_=>_.status>=500,version:y="v1",...v}=n,m={credentials:"include",...v,headers:{"Content-Type":"application/json",...v.headers}};n.method!==void 0&&n.method!=="GET"&&this.csrfToken&&(m.headers={...m.headers,"X-CSRFToken":this.csrfToken}),typeof y=="string"&&(m.headers={...m.headers,"X-Deepdesk-API-Version":y});let h=u,g=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[s]&&l&&(this.latestRequestByUrl[s].isAborted=!0,this.latestRequestByUrl[s].reject(new Error("Aborted"))),this.latestRequestByUrl[s]=i;let x=async()=>(h--,a(s,m).then(async _=>f(_)&&!i.isAborted&&h>0?(await Rh(c),x()):_.status===401&&p===!0&&g===!1?(g=!0,await this.refreshToken(),x()):_).catch(async _=>{if(d(_)&&!i.isAborted&&h>0)return await Rh(c),x();throw _}));x().then(_=>_.json().catch(()=>null).then(w=>{_.status>=500?o(new Lh("Server Error",w)):_.status===401?o(new Vi("Unauthorized",w)):_.status===403?o(new Vi("Forbidden",w)):_.status===404?o(new Vi("Not Found",w)):_.status>=400&&o(new Vi("Bad Request",w)),delete this.latestRequestByUrl[s],r(w)})).catch(_=>{o(_)})})}async validateToken(){let{has_valid_access_token:t}=await this.get("/auth/validate");if(!t)return!1;let{is_logged_in:n}=await this.get("/apis/admin/session/validate/",{version:null});return!!n}refreshToken(){return e.refreshingToken||(e.refreshingToken=this.get("/auth/refresh",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{e.refreshingToken=null},1e3*60)})),e.refreshingToken}get(t,n){return this.request(t,n)}post(t,n,r){return this.request(t,{method:"POST",body:JSON.stringify(n),...r})}patch(t,n,r){return this.request(t,{method:"PATCH",body:JSON.stringify(n),...r})}put(t,n,r){return this.request(t,{method:"PUT",body:JSON.stringify(n),...r})}delete(t,n){return this.request(t,{method:"DELETE",...n})}};var yA;(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||={})})(yA||={});function Od(e){return{...Z(e),tags:e.tags}}var zn=class e{constructor(t,n={}){this.options=n;this.client=new Gt(t,{fetch:n.fetch}),this.client.patchFetch(r=>async(o,i)=>{let s=await r(o,i);return this.handleDeepdeskVersionHeaders(s),s})}latestReceivedDeepdeskVersions={};client;shouldFetchCsrfToken=!0;static exchangeTokenPromise=null;async preflight(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let t=await this.getCsrfToken();this.client.setCsrfToken(t)}return this.options.token?(e.exchangeTokenPromise||(e.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),e.exchangeTokenPromise):Promise.resolve()}async createConversation(t){await this.preflight(),j.info(`Creating conversation for session ${t.sessionId} and agent ${t.agentId}`);let n=await this.client.post("/api/conversations",{...ke(t),tags:t.tags},{version:"v2"});return Od(n)}async getProfile(t){let n=await this.client.get(`/apis/admin/profiles/${t}/`,{version:null});return Z(n)}async getKnowledgeAssistant(t){let n=await this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{version:null});return Z(n)}async getContentTypes(){let t=await this.client.get("/apis/admin/content-types/",{version:null});return Z(t)}async getPlatformConfig(){let{config:t}=await this.client.get("/platform/config/",{version:null});return Z(t)}async checkUserExists(t){let{exists:n}=await this.client.get(`/apis/admin/users/exists?external_id=${t}`);return n}async getConversationBySessionId(t,n={}){await this.preflight(),j.info(`Getting conversation for session ${t}`);let{attempts:r=1,retryDelay:o=1e3}=n,i=await this.client.get(`/api/conversations/by_session_id/${t}`,{attempts:r,retryDelay:o,retryOnResponse:s=>s.status===404||s.status>=500,version:"v2"});return Od(i)}async isConversationSupported(t,n={}){j.info(`Check if conversation for session ${t} is supported`);let{attempts:r=1,retryDelay:o=1e3}=n;return(await this.client.get(`/api/conversations/by_session_id/${t}/active_profile`,{attempts:r,retryDelay:o,retryOnResponse:s=>s.status===404||s.status>=500,version:"v2"})).has_active_profile}async updateConversation(t,n){let r=ke(n);n.tags&&(r.tags=n.tags);let o=await this.client.put(`/api/conversations/${t}`,r,{version:"v2"});return Od(o)}async postMessages(t,n){return(await this.client.post(`/api/conversations/${t}/messages`,n.map(o=>({...ke(o),tags:o.tags})),{version:"v2"})).map(o=>Od(o))}async sendEvent(t,n){let{data:r,...o}=n,i=Object.entries(this.latestReceivedDeepdeskVersions).reduce((s,[a,l])=>({...s,[a]:l}),{});return this.client.post("/api/events",ke({...i,...o,data:r,name:t}),{version:"v2"})}async sendEventV1(t,n){let r=Object.entries(this.latestReceivedDeepdeskVersions).reduce((o,[i,s])=>({...o,[i]:s}),{});return this.client.post("/api/events",{event:t,data:ke({...n,...r})})}async getEntities(t){return(await this.client.post("/api/entities",{messages:t.filter(r=>r.text)})).entities}async getSummary(t,n={}){return(await this.client.post("/api/summary",{conversation:{messages:t.filter(o=>o.text&&o.source),agent_id:n.agentId,id:n.externalConversationId},prompt_instruction:n.promptInstruction,model:n.model})).summary}async getTemporaryExchangeToken(){return(await this.client.get("/auth/exchange-token",{version:null})).jwt}async exchangeTokenForAccessCookie(t){return this.client.post("/apis/admin/session/jwt/",{jwt:t},{version:null}).catch(n=>{throw j.warn(`Invalid token '${t}'`),n})}async authenticateWithKey(t,n){await this.client.post("/apis/admin/session/api-key/",ke(n),{version:null,refreshTokenOn401:!1,headers:{apikey:t}})}async getTextSuggestions(t,n={},r){return r==="sticky-messages"?this.getPinnedMessages(t):(await this.client.post(`/api/conversations/${t}/recommend/${r}`,ke(n),{abortLatest:!0})).map(i=>({...Z(i),text:i.text||i.url||i.message,source:r,type:r})).filter((i,s,a)=>s===a.findIndex(l=>l.text===i.text))}async isLoggedIn(){return await this.preflight(),this.client.validateToken()}async getAutocompleteSuggestions(t,n){return(await this.client.post(`/api/conversations/${t}/autocomplete`,ke(n),{abortLatest:!0})).map(o=>({score:1,source:o.source,sourceText:o.source_text,text:o.label,trainingJobs:o.training_jobs,searchKeywords:o.search_keywords,type:o.source})).filter((o,i,s)=>i===s.findIndex(a=>a.text===o.text))}async getPinnedMessages(t){let n=await this.client.get(`/api/conversations/${t}/sticky-messages`,{abortLatest:!0});return Z(n).map(r=>({...r,text:r.message,source:"sticky-messages",type:"pinned-message"}))}async getStyleSuggestions(t){let n=await this.client.post("/api/style-suggestions",ke(t),{abortLatest:!0});return Z(n)}async search(t){let n=await this.client.post(`/api/profiles/${t.profile}/search`,ke(t),{version:"v2"});return Z(n)}async knowledgeAssist(t,n,r,o={}){let i=await this.client.post(`/api/knowledge-assist/assistants/${r}/search`,ke({question:t.question,promptInstruction:t.promptInstruction,chatHistory:n.map(s=>({question:s.question,answer:s.answer.answer})),agentId:o.agentId,conversationId:o.conversationId}),{version:"v2"});return Z(i)}async requestLoginByEmail(t){let n=await this.client.post("/apis/admin/session/passwordless/request/",{email:t},{version:null});return Z(n)}async requestPasswordlessToken(){let t=await this.client.get("/apis/admin/session/passwordless/request/",{version:null});return Z(t.token)}async getCsrfToken(){let{token:t}=await this.client.get("/apis/admin/session/csrf/",{version:null});return t}async verifyLoginToken(t){let n=await this.client.post("/apis/admin/session/passwordless/login/",{token:t},{version:null});return Z(n)}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),i=o.match(Cy);if(!n||!i)return;let s=i[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[s];a&&n&&a!==n&&j.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[s]=n})}};var Wa=class{constructor(t,n){this.url=t;this.options={timeout:25e3,...n}}eventListeners={};options;timeoutTimer;eventSource;proxyEvent(t){this.eventSource.addEventListener(Mg(t),n=>{let{data:r}=n;try{let o=JSON.parse(r);this.emit(t,Z(o))}catch{j.warn(`Invalid JSON for ${t}: ${r}`)}})}connect(){clearTimeout(this.timeoutTimer);let t=new EventSource(this.url,{withCredentials:!0});this.eventSource=t;let n=!1;t.onopen=()=>{n=!0},t.onerror=()=>{n&&t.readyState===2&&this.connect()},this.timeoutTimer=setTimeout(()=>{t.close(),this.connect()},this.options.timeout),Object.keys(this.eventListeners).forEach(r=>{this.proxyEvent(r)})}disconnect(){var t;clearTimeout(this.timeoutTimer),this.eventListeners={},(t=this.eventSource)==null||t.close()}emit(t,n){this.eventListeners[t]&&this.eventListeners[t].forEach(r=>r(n))}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),this.proxyEvent(t),()=>{this.off(t,n)}}off(t,n){let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}};var vA;(t=>{let e;(i=>(i.Started="Started",i.Aborted="Aborted",i.Completed="Completed"))(e=t.AutoflowSessionState||={})})(vA||={});var $a=class{constructor(t,n={}){this.apiUrl=t;this.client=new Gt(t,n)}client;streams={};logger=j;async getCustomMessages(t){let n=await this.client.get(`/sessions/${t}/suggestions`);return Z(n.suggestions)}async sendCustomMessage(t,n){let r=await this.client.post(`/sessions/${t}/messages`,ke(n));return Z(r)}async answerCustomMessage(t,n){await this.client.post(`/sessions/${t}/answers`,ke(n))}async getAutoflows(t){let n=await this.client.get(`/sessions/${t}/autoflows`);return Z(n.autoflows)}async startAutoflowSession(t){let n=await this.client.post("/autoflow-sessions",ke(t));return Z(n)}async stopAutoflowSession(t){await this.client.delete(`/autoflow-sessions/${t}`)}openStream(t){return this.streams[t]||(this.streams[t]=new Wa(`${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 lE={startTime:null,stopTime:null},uE=z({name:"handlingTime",initialState:lE,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(te,()=>lE)}}),{handlingTimeStart:cE,handlingTimeStop:Nd,handlingTimeReset:dE}=uE.actions,pE=uE.reducer;var fE=(e={})=>{let t={onAuthError:Oi(!1),...e};return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var Md={list:{keywordMatches:[]},fetchState:"idle",isInitialRequest:null};var Eo=D("styleSuggestions/getAll",async({text:e},t)=>{var s;let{deepdeskAPI:n}=t.extra,r=t.getState(),{showStyleSuggestions:o}=r.settings,i=(s=r.conversation.current)==null?void 0:s.profileCode;if(!o)return Md.list;if(!i)throw new Error("No current conversation to fetch pinned messages");return n.getStyleSuggestions({profileCode:i,message:e})}),SA=z({name:"styleSuggestions",initialState:Md,reducers:{},extraReducers:e=>{e.addCase(Eo.pending,t=>{t.isInitialRequest=t.isInitialRequest===null,t.fetchState="loading"}).addCase(Eo.rejected,t=>{t.fetchState="error"}).addCase(Eo.fulfilled,(t,n)=>{t.fetchState="done",hr(t.list,n.payload)||(t.list=n.payload)}).addCase(no,t=>{t.list=Md.list}).addCase(te,()=>Md)}}),mE=SA.reducer;var gE=(e={})=>{let t,n=!0,r={getStyleSuggestions:Eo,debounce:500,...e};return o=>i=>s=>{var f;let a=o.getState().input.text,l=i(s),u=o.getState();if(u.auth.isLoggedIn!==!0)return l;let{showStyleSuggestions:c}=u.settings;if(!((f=u.conversation.current)==null?void 0:f.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 xA(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end}var hE=(e={})=>{let t={getTextSuggestions:Vt,getAutocompleteSuggestions:Ea,debounce:200,check:ji,...e},n;return r=>o=>i=>{var v;let{input:{userCommitted:s}}=r.getState(),a=o(i),l=r.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:u,showTabCompletion:c}=l.settings,p=(v=l.conversation.current)==null?void 0:v.id,d=i.type===rd.toString();if(!p||!u&&!c)return a;let{input:{userCommitted:f}}=l;return xA(f,s)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let m=xi(l);m===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(m))},d?0:t.debounce)),a}};var yE=Eo.fulfilled.toString();function _A(e,t){let n=new Set([...t.keywordMatches.map(o=>o.keyword)]),r=[];return n.forEach(o=>{let i=e.keywordMatches.filter(l=>l.keyword===o),s=t.keywordMatches.filter(l=>l.keyword===o),a=s.length-i.length;a<=0||r.push(...s.slice(0,a))}),r}var vE=e=>t=>n=>r=>{var u;if(r.type!==yE){n(r);return}let o=t.getState().styleSuggestions.list;n(r);let i=t.getState(),s=i.styleSuggestions.list,a=(u=i.conversation)==null?void 0:u.current;if(o===s)return;let l=_A(o,s);r.type===yE&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var wA=Iu({activeSuggestion:Rw,answer:w1,auth:Kw,autoflows:Sb,conversation:qx,contentTypes:o1,customMessages:Pb,passwordlessToken:Ab,entities:l1,knowledgeAssistant:S1,handlingTime:pE,info:iw,input:Jm.reducer,overlayInput:rt.reducer,settings:jx,profile:C1,search:dw,summary:m1,styleSuggestions:mE,ui:Nw,textSuggestions:Cw});function SE(e){return V0({reducer:wA,middleware:t=>[...t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI,deepdeskBrokerAPI:e.deepdeskBrokerAPI}},serializableCheck:!1}),fE(),hE({debounce:200}),gE({debounce:500}),vE(e.deepdeskAPI),...e.middleware?e.middleware:[]],preloadedState:e.preloadedState})}var bA=e=>{var t;return((t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())??"unknown"},EA=e=>t=>n=>r=>{var a;let o=t.getState(),i=qm("inlineSuggestions")(o);switch(r.type){case Rn.toString():{let l=nd(r.payload.contentType)(t.getState()),u=l.indexOf(r.payload.suggestion);e.emit("edit-suggestion",{contentType:r.payload.contentType,index:u,suggestions:l});break}case Oi.toString():{!r.payload&&e.emit("logout",void 0);break}case Bt.toString():{let{start:l,end:u}=o.input.selection;e.emit("select-suggestion",{type:bA(r.payload.suggestion),...r.payload,replace:r.payload.replace==="selection"?{start:l,end:u}:{start:0,end:u}},{mayApplyChanges:!0});break}case fc.toString():{let{start:l,end:u}=o.input.selection;e.emit("replace",{...r.payload,replace:r.payload.replace==="selection"?{start:l,end:u}:{start:0,end:u}},{mayApplyChanges:!0});break}case sa.toString():{let l=t.getState(),{text:u,selection:c}=l.input.userCommitted;e.emit("reset",{text:u,selectionAfter:c},{mayApplyChanges:!0});break}case yc.toString():e.emit("select-image",r.payload,{mayApplyChanges:!0}),e.sendEvent("Image attached",{conversationId:o.conversation.current.id,data:{path:r.payload.suggestion.image,title:r.payload.suggestion.title}});break;case $t.fulfilled.toString():r.payload.length>0&&e.sendEvent("entities found",{conversationId:o.conversation.current.id,data:{entities:r.payload}});break;case On.fulfilled.toString():e.sendEvent("conversation summarized",{conversationId:o.conversation.current.id,data:{summary:r.payload.summary}});break;case Be.toString():e.sendEvent(r.payload.name,{conversationId:((a=r.payload.options)==null?void 0:a.includeConversationData)&&o.conversation.current.id,data:r.payload.data});break;case mc.toString():e.handleKeyDown(r.payload);break;case no.toString():e.logSendMessage(r.payload);break;case gc.toString():e.logSendEditSuggestionMessage(r.payload);break;case hc.toString():e.handleInputChanged(r.payload);break;default:break}let s=n(r);switch(r.type){case no.toString():e.handleAfterSendMessage(r.payload);break;case Ca.toString():e.onUpdateShowTabHint(r.payload);break;case Nd.toString():e.logHandlingTime();break;case Bt.toString():{i&&(t.dispatch(on([])),t.dispatch(wn()));break}case on.toString():{i&&r.payload.length>0&&t.dispatch(vr(0));break}default:break}return s},xE=EA;function Ah(e){return e.toISOString().replace("T"," ").replace("Z","")}function _E(e,t){var o,i,s;let{startTime:n,stopTime:r}=e.handlingTime;if(!n||!r)throw new Error("No startTime and stopTime for handling time metrics");return{conversationId:e.conversation.current.id,clientVersion:t.version,agentId:(o=e.info.agentInfo)==null?void 0:o.agentId,agentName:(i=e.info.agentInfo)==null?void 0:i.agentName,agentEmail:(s=e.info.agentInfo)==null?void 0:s.agentEmail,timeStart:Ah(n),timeStop:Ah(r)}}function Oh(e,t,n){var C,I,k;let{text:r,metrics:{numCharsTyped:o,numCharsPasted:i,numCharsCut:s,numCharsDeleted:a,numPaste:l,agentStartedTypingTimestamp:u,externalTimeTotalSeconds:c,pastes:p,cuts:d,deletions:f,textSuggestions:y,offeredTextSuggestions:v}}=t[e],m=r.length,g=y.reduce((K,{text:N,searchTerm:B})=>K+N.length-(B?B.length:0),0),x=u??Date.now(),_=(Date.now()-x)/1e3+(c||0),w=o/_,E=y.reduce((K,{searchTerm:N})=>K+(N?N.length:0),0);return{conversationId:t.conversation.current.id,source:"agent",text:r,clientVersion:n.version,pastes:p,cuts:d,deletions:f,lenTextTyped:o+E,lenTextTotal:m,lenTextAssisted:g,lenTextPasted:i,lenTextCut:s,lenTextDeleted:a,timeTotalSeconds:_,charsPerSecond:w,numPastes:l,textSuggestionsV2:y,suggestionsCounters:[{source:"gpt",countOffered:v.filter(K=>K.source==="gpt").length}],agentId:(C=t.info.agentInfo)==null?void 0:C.agentId,agentName:(I=t.info.agentInfo)==null?void 0:I.agentName,agentEmail:(k=t.info.agentInfo)==null?void 0:k.agentEmail}}function Nh(e,t){var i;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return Nh(r,t);let o=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;return o?Nh(o,t):null}function wE(e,t){return Nh(e,t)}function bE(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function CA(e){return typeof e=="object"&&e!==null&&"tagName"in e}function Dd(e){return CA(e)&&(Pr(e)||zc(e))}var EE=(e,t)=>({value(){try{let n=sessionStorage.getItem(`dd-${e}`);if(!n)return t;try{return JSON.parse(n)}catch{return t}}catch{return t}},update(n){try{sessionStorage.setItem(`dd-${e}`,JSON.stringify(n))}catch{j.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function TA(e){return e.offsetParent!==null}function CE(e){if(!TA(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 Fd(e,t,n=100){let r=CE(e);t({isVisible:r});let o=setInterval(()=>{let i=CE(e);i!==r&&(r=i,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var we=S(b());var TE=EE("showTabHint",!0),qa=class e{static version="10.11.0";static count=0;deepdeskApi;inputMediator=null;version;broadcastEvents;eventListeners={};unmountHandlers=[];widgetRoot=null;dynamicThunkObject={};isMounted=!1;instanceId;shouldRender=!0;store;constructor({deepdeskUrl:t,brokerUrl:n,version:r=e.version||"unknown",locale:o="en-US",token:i,fetch:s,productName:a,createCustomChannel:l}){let u=t.replace(/\/api$/,"");this.deepdeskApi=new zn(u,{token:i,fetch:s}),this.version=r,this.instanceId=e.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[xE({emit:(p,d,f)=>this.emit(p,d,f),handleAfterSendMessage:p=>this.handleAfterSendMessage(p),handleInputChanged:p=>this.handleInputChanged(p),handleKeyDown:p=>this.handleKeyDown(p),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:p=>this.logSendMessage(p),logSendEditSuggestionMessage:p=>this.logSendEditMessage(p),onUpdateShowTabHint:p=>TE.update(p),sendEvent:(p,d)=>this.deepdeskApi.sendEvent(p,d)})]};n&&Object.assign(c,{deepdeskBrokerAPI:new $a(n)}),this.store=SE(c),this.broadcastEvents=new aE({debug:!0,deepdeskUrl:u,eventMap:Vw(this.store),createCustomChannel:l}),this.store.dispatch(oa),this.store.dispatch(Ca(TE.value())),this.store.dispatch(oa({locale:o,adminUrl:u,productName:a}))}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){return this.state.input.textSuggestions[this.state.input.selectedSuggestionIndex]??null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}sessionId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.sessionId}shouldAbort(){return this.state.conversation.isSupported===!1?(j.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(j.warn("Profile has not been loaded (yet)"),!0):(j.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(Oi(null)),this.store.dispatch(Ln()),new Promise(t=>{let n=this.store.subscribe(()=>{let r=this.store.getState();Ge(r)&&Fw(r)!=="loading"&&(n(),t())});this.unmountHandlers.push(()=>{n()})})}async isLoggedIn(){return(await this.store.dispatch(Ln())).payload}async setPlatformAgentId(t){try{if((await this.deepdeskApi.client.get("/apis/admin/session/me/",{version:null})).external_id)return;await this.deepdeskApi.client.request("/apis/admin/session/me/",{method:"PATCH",body:JSON.stringify({external_id:t}),version:null})}catch(n){j.warn("Failed to attach user:",n)}}async isConversationSupported(t,n){return(await this.store.dispatch(Ym({sessionId:t,options:n}))).payload}async createConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(ac(t))).payload}async getConversationBySessionId(t,n){return this.hasConversation()&&this.sessionId()!==t&&this.resetConversation(),(await this.store.dispatch(lc({sessionId:t,options:n}))).payload}async upsertConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(Zm(t))).payload}async postMessages(t){return(await this.store.dispatch(cc(t))).payload}async updateConversation(t){return(await this.store.dispatch(uc(t))).payload}resetConversation(){this.store.dispatch(te()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}async getSummary(){let t=await this.store.dispatch(On());if(t.error)throw new Error(t.error.message);return t.payload.summary}configure(t){this.store.dispatch(oa(t))}setVisitorInfo(t){this.store.dispatch(ow(t))}async setAgentInfo(t){await this.store.dispatch(xa(t))}async setAgentSettings(t){await this.store.dispatch(Dg(t))}async getAgentSettings(){return(await this.store.dispatch(Fg())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let t=[];return this.store.dispatch(rd()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})}notifyInputChanged(t){this.store.dispatch(hc(t))}notifyKeyDown(t){this.store.dispatch(mc(t))}notifyPaste(t,n){this.store.dispatch(o_({text:t,selectionText:n}))}notifyCut(t){this.store.dispatch(n_(t))}notifyExternalSuggestion(t){this.store.dispatch(Bt(t)),this.store.dispatch(wn())}notifyEditSuggestion(t){this.store.dispatch(bw(t.contentType,t.suggestions)),this.store.dispatch(Rn({contentType:t.contentType,suggestion:typeof t.index=="number"?t.suggestions[t.index]:null}))}handleInputChanged(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui;n&&r&&this.store.dispatch(Er({collapse:!1})),this.inputMediator&&this.store.dispatch(Qx({text:t,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(on([])))}handleKeyDown(t){let{overlayCollapsed:n}=this.state.ui,{textSuggestions:r,selectedSuggestionIndex:o,selection:i}=this.state.input,{inlineSuggestions:s}=this.state.settings,a=r.length>0,l=o!==-1;if(this.store.dispatch(r_(pc(t))),t.key!=="Tab"&&!this.settings.showTextSuggestions)return;let u=()=>{n||!a||i&&(t.shiftKey||(this.store.dispatch(Jx()),s||this.stageSelectedSuggestion({inputType:"arrow"}),t.preventDefault()))},c=()=>{n||!a||s&&o<=0||i&&(t.shiftKey||(this.store.dispatch(t_()),t.preventDefault(),!s&&(this.state.input.selectedSuggestionIndex===-1?this.store.dispatch(sa()):this.stageSelectedSuggestion({inputType:"arrow"}))))};switch(t.key){case"Up":case"ArrowUp":s?c():u();return;case"Down":case"ArrowDown":{s?u():c();return}case"Esc":case"Escape":{s&&l&&this.store.dispatch(vr(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(vr(-1)),this.store.dispatch(sa()),t.preventDefault()):n||(this.store.dispatch(Er({collapse:!0})),this.store.dispatch(Aw(!0)),t.preventDefault());return}case"Tab":{let{userCommitted:p}=this.state.input,d=p.text.substring(0,p.selection.end),{tabCompletionSuggestion:f}=this.state.input;this.store.dispatch(Ca(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):!s&&this.settings.showTabCompletion&&f&&f.text.startsWith(d)&&(this.store.dispatch(Bt({text:f.text,suggestion:f,eventMetrics:{inputType:"tab"},replace:"until-selection-end"})),this.store.dispatch(wn())),t.preventDefault();break}default:}}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(i_()),this.store.dispatch(on([]))}handlingTimeStart(){this.state.handlingTime.startTime||(j.info("Start handling time"),this.store.dispatch(cE()))}handlingTimeStop(){this.state.handlingTime.startTime&&(j.info("Stop handling time"),this.store.dispatch(Nd()))}logSendMessage(t){let n=Oh("input",this.state,{version:this.version});t&&(Object.assign(n,{text:t}),Object.assign(n,{lenTextTotal:t.length})),this.deepdeskApi.sendEventV1("Send Message",n),this.emit("send-message-event",n)}logSendEditMessage(t){let n=Oh("overlayInput",this.state,{version:this.version});t&&Object.assign(n,{text:t}),this.store.dispatch(Zx(this.state.overlayInput.metrics))}logHandlingTime(){let t=_E(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",t),this.store.dispatch(dE())}notifySubmit(t={}){this.shouldAbort()||(this.store.dispatch(wn()),this.store.dispatch(no(t.text??this.state.input.text)))}stageSelectedSuggestion(t){let n=this.state.input.selectedSuggestionIndex,{textSuggestions:r}=this.state.input;this.store.dispatch(Bt({text:r[n].text,suggestion:r[n],eventMetrics:t,replace:"until-selection-end"}))}emit(t,n,r={}){let o=()=>{this.eventListeners[t]&&this.eventListeners[t].forEach(i=>{try{i(n)}catch(s){j.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),j.error(s)}})};this.inputMediator&&r.mayApplyChanges?this.inputMediator.applyChanges(o):o()}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),()=>{this.off(t,n)}}off(t,n){if(!t&&!n){this.eventListeners={};return}let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}setConversationQuery(t){this.dynamicThunkObject.conversationQuery=t}whenConversationLoaded(t){let n=()=>this.loadProfileConfig().then(()=>t());this.hasConversation()&&n();let r=this.hasConversation();this.store.subscribe(()=>{this.hasConversation()!==r&&(r=this.hasConversation(),r&&n())})}overlayContainerFactory(t,n,r,o){let[i,s]=lo(n,r);return i.setAttribute("translate","no"),i.dataset.testid=t,o&&i.classList.add(o),this.unmountHandlers.push(()=>{(0,Nt.unmountComponentAtNode)(i),s(),i.remove()}),i}createInlineContainer(t,n){var s;let r=document.createElement("div");r.style.position="absolute",r.style.top="0px",r.style.left="0px",r.style.height="0px",r.style.width="0px";let o=document.createElement("div");o.style.display="none",o.style.position="absolute",o.style.height="0px",o.style.width="0px",o.style.backgroundColor="red",r.appendChild(o);let i=(s=t.ownerDocument.defaultView)==null?void 0:s.frameElement;if(i){let[a,l]=lo(i,{appendTo:document.body,onMoveStart:()=>{o.style.display="none"}});a.dataset.testid=n,a.style.zIndex="2",a.appendChild(r),this.unmountHandlers.push(()=>{(0,Nt.unmountComponentAtNode)(o),l()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return ao(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,Nt.unmountComponentAtNode)(o),o.remove()}),o}storeMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(t,n),j.info(`Stored analytics for ${this.conversationId()}`)}catch{}}restoreMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=window.sessionStorage.getItem(t);if(!n)return;let r=JSON.parse(n);r.text.trim()===this.state.input.text.trim()?(j.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(a_(r.metrics))):j.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(t)}catch{}}mount(t,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!Dd(t))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let{customStyles:r={},showStyleSuggestions:o,showTabCompletion:i,showTextSuggestions:s,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,isEmbedded:p,detectSubmit:d,insertLink:f,inputMediator:y,closestScrollSelector:v,appendOverlayTo:m,inlineSuggestions:h,floatingMenu:g}=n;this.configure({showStyleSuggestions:o,showTabCompletion:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,showTextSuggestions:s,insertLink:f,isEmbedded:p,inlineSuggestions:h,floatingMenu:!!g}),n.automaticHandlingTime&&this.setupHandlingTime(t),ao(t),this.inputMediator=y||(Pr(t)?new Pn(t):new bo(t)),this.inputMediator.on("change",({plainText:w})=>{this.notifyInputChanged(w)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(s_({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()}))}),this.inputMediator.on("keydown",w=>{this.notifyKeyDown(w)}),this.inputMediator.on("paste",({pastedText:w,selectionText:E})=>{this.notifyPaste(w,E)}),this.inputMediator.on("cut",({selectionText:w})=>{this.notifyCut(w)});let x=v&&wE(t,v)||void 0;if(h){let{customStyles:w,appendOverlayTo:E}=n;if(Pr(t))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let C=this.createInlineContainer(t,"deepdesk-caret");(0,Nt.render)((0,we.jsx)(wo,{store:this.store,customStyles:w,children:(0,we.jsx)(yo,{broadcastEvents:this.broadcastEvents,children:(0,we.jsx)(K1,{})})}),C),this.inputMediator.on("caret",k=>{this.store.dispatch(on([])),k?(C.style.display="block",C.style.top=`${k.top}px`,C.style.left=`${k.left}px`):C.style.display="none"});let I=this.overlayContainerFactory("floating-menu",x||t,{appendTo:typeof g=="object"&&"appendOverlayTo"in g?g.appendOverlayTo:E},w==null?void 0:w.floatingMenuRootNode);(0,Nt.render)((0,we.jsx)(wo,{store:this.store,customStyles:w,children:(0,we.jsx)(yo,{broadcastEvents:this.broadcastEvents,children:(0,we.jsx)(F1,{onLogIn:()=>this.loginViaPopup().catch(k=>j.warn(k.message))})})}),I)}else{let w=this.overlayContainerFactory("deepdesk-tab-completion",x||t,{appendTo:m,closestScrollElement:x,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),E=this.overlayContainerFactory("deepdesk-suggestions-overlay",x||t,{appendTo:m},r==null?void 0:r.suggestionsRootNode);(0,Nt.render)((0,we.jsx)(wo,{store:this.store,customStyles:r,children:(0,we.jsx)(yo,{broadcastEvents:this.broadcastEvents,children:(0,we.jsx)(fb,{inputElement:t})})}),w),(0,Nt.render)((0,we.jsx)(wo,{store:this.store,customStyles:r,children:(0,we.jsx)(yo,{broadcastEvents:this.broadcastEvents,children:(0,we.jsx)(Y1,{onLogIn:()=>this.loginViaPopup().catch(C=>j.warn(C.message))})})}),E)}(0,Nt.render)((0,we.jsx)(wo,{store:this.store,customStyles:r,children:(0,we.jsx)(yo,{broadcastEvents:this.broadcastEvents,children:(0,we.jsx)(A1,{})})}),this.createContainer("deepdesk-overlays"));let _;this.inputMediator.on("selection",w=>{clearTimeout(_),w===null?_=setTimeout(()=>{w!==null&&this.store.dispatch(eg(w))},500):this.store.dispatch(eg(w))}),this.inputMediator.on("disabled",()=>{var w;(w=this.inputMediator)==null||w.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(Ai(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(Ai(!0))),this.store.dispatch(Yx({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.unmountHandlers.push(()=>{this.state.input.text!==""&&(this.store.dispatch(wn()),this.storeMetrics())}),this.whenConversationLoaded(()=>{var w;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((w=this.state.conversation.current)==null?void 0:w.sessionId)}),this.isMounted=!0}unmount(){var t;this.unmountHandlers.forEach(n=>n()),this.unmountHandlers=[],(t=this.inputMediator)==null||t.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(t,n={}){if(this.widgetRoot&&j.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,isEmbedded:i}=n;this.widgetRoot=t,this.configure({showImages:o,isEmbedded:i}),(0,Nt.render)((0,we.jsx)(wo,{store:this.store,customStyles:r,children:(0,we.jsx)(yo,{broadcastEvents:this.broadcastEvents,children:(0,we.jsx)(rE,{onLogIn:()=>this.loginViaPopup().catch(s=>j.warn(s.message))})})}),t),this.whenConversationLoaded(()=>{var s;this.broadcastEvents.setSessionId((s=this.state.conversation.current)==null?void 0:s.sessionId)})}unmountWidget(){this.widgetRoot&&(0,Nt.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(t){let n=Fd(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){bE(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(Da());let t=Tr(this.state);t&&(await this.store.dispatch(Na()),this.store.dispatch(oa({showSearch:t.search,showAutoflows:t.autoflows,showCustomMessages:t.customMessages,showImageSearch:t.imageSearch,showEntitiesCommand:t.entitiesCommand,showSummaryCommand:t.summarizer,showKnowledgeSearch:!!t.knowledgeAssistant,recommendTextSuggestions:t.recommendTextSuggestions})))}),this.loadProfileConfigPromise)}async loginViaPopup(t){return new Promise((n,r)=>{let o=new MessageChannel,i=o.port1,s=this.state.settings.adminUrl,a=new URL(t!=null&&t.url?t==null?void 0:t.url:`${s}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let l=!1,u=()=>{c&&!c.closed&&c.close(),window.removeEventListener("message",p),clearInterval(d)};i.onmessage=async f=>{var y,v;if((y=f.data)!=null&&y.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((v=f.data)==null?void 0:v.jwt),await this.isLoggedIn(),this.broadcastEvents.send(Pa),l=!0,o.port1.close(),n()}catch(m){console.error(m),r(m)}finally{l=!0,u()}};let c=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");c===null&&r(new Error("Popup blocked by browser"));let p=async f=>{var y;if(f.origin===a.origin)switch((y=f.data)==null?void 0:y.type){case"deepdesk-popup-loaded":{try{let v=JSON.stringify({type:"deepdesk-popup-create-channel"});c==null||c.postMessage(v,a.origin,[o.port2])}catch(v){j.error("Error posting message to popup",v),r(v)}break}case"deepdesk-popup-error":{u(),f.data.message==="Timeout"&&j.warn("Popup timed out. Check if the account's platform url is configured correctly."),r(new Error(f.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)})}async checkForTrialMode(t){try{let{account:n}=await this.deepdeskApi.getPlatformConfig();if(!n.isTrial){this.shouldRender=!0;return}if(j.info("Trial is active"),!await this.deepdeskApi.checkUserExists(t))throw new Error("User is not in trial");this.shouldRender=!0}catch(n){let{message:r}=n;j.info(r),this.shouldRender=!1}}async refreshWidgetSuggestions(){if(!this.widgetRoot||this.shouldAbort())return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=ad(this.state);try{n.forEach(({type:r})=>{r==="entities"?this.store.dispatch($t()):this.store.dispatch(Vt(r))})}catch(r){this.handleError(r)}}};async function kE(e,t,n={}){let{value:r}=e,{start:o,end:i}=n.replace??{start:0,end:r.length},s=`${r.slice(0,o)}${t}${r.slice(i)}`,a=n.selectionAfter??{start:o+t.length,end:o+t.length},l=()=>{if(n.setValue)return n.setValue(s);e.value=s};return Promise.resolve(l()).then(()=>{e.selectionStart=a.start,e.selectionEnd=a.end,e.blur(),e.focus()})}async function PE(e,t,n={}){let r=n.replace?Lr(e,n.replace.start,n.replace.end):Ui(e),o,i=()=>{if(n.setRange)return n.setRange(r.cloneRange());r.deleteContents(),o=document.createElement("span"),r.insertNode(o),n.insertBRs!==!1?t.split(`
26
26
  `).reverse().forEach((s,a)=>{a>0&&r.insertNode(document.createElement("br")),r.insertNode(document.createTextNode(s))}):r.insertNode(document.createTextNode(t))};return Promise.resolve(i()).then(()=>{try{if(n.selectionAfter!==!1){e.focus();let s=n.selectionAfter?Lr(e,n.selectionAfter.start,n.selectionAfter.end):(r.collapse(!1),r),a=window.getSelection();a==null||a.removeAllRanges(),a==null||a.addRange(s)}if(!o)return;o.scrollIntoView&&o.scrollIntoView({block:"nearest",inline:"nearest"})}finally{o&&o.remove()}})}function kA(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 PA(e){let t=document.createDocumentFragment();return e.split(`
27
27
  `).forEach((n,r)=>{r>0&&t.appendChild(document.createElement("br"));let o={index:0},i=0;for(;o=n.slice(i).match(/(\[([^\]]+)])\(([^)]+)\)/);){let s=document.createElement("a");s.href=o[3],s.setAttribute("target","_blank"),s.setAttribute("rel","noopener noreferrer"),s.appendChild(document.createTextNode(o[2])),t.appendChild(document.createTextNode(n.slice(i,i+o.index))),t.appendChild(s),i=i+o.index+o[0].length}t.appendChild(document.createTextNode(n.slice(i)))}),t}function IE(e,t){return!e.contains(t)||t===e?null:t.parentNode===e?t:IE(e,t.parentNode)}async function RE(e,t,{isBlock:n,isHTML:r}={}){let o;e.dispatchEvent(new InputEvent("beforeinput",{inputType:"insertText",data:t,bubbles:!0,cancelable:!0}));let i=()=>{let s=e.ownerDocument.defaultView??window,a=s.getSelection();if((!a||a.rangeCount===0)&&(e.focus(),a=s.getSelection()),!a||a.rangeCount===0)return;let l=a.getRangeAt(0);if(!l)return;o=document.createElement("span"),l.insertNode(o);let u=r?kA(t):PA(t);if(n){let c=l.startContainer===e?e.childNodes[l.startOffset]:l.startContainer,p=IE(e,c)??e.firstChild;e.insertBefore(u,(p==null?void 0:p.nextSibling)??null)}else l.insertNode(u),l.collapse(!1)};return Promise.resolve(i()).then(()=>{if(e.dispatchEvent(new InputEvent("input",{inputType:"insertText",data:t,bubbles:!0,cancelable:!0})),e.focus(),!!o)try{o.scrollIntoView&&o.scrollIntoView({block:"nearest",inline:"nearest"})}finally{o&&o.remove()}})}function LE(e){return e.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}async function AE(e,t,n){await new zn(e).authenticateWithKey(t,n)}async function OE(e){let n=await new Gt(e).get("/platform/config/",{version:null});return Z(n)}async function IA(e){let n=await(e.fetch??window.fetch)(e.url),r=await n.blob();return new File([r],e.name,{type:e.mimeType??n.headers.get("Content-Type")??"image/jpeg"})}async function NE(e,t){let n=await IA(t),r=new Event("change",{bubbles:!0,cancelable:!0});try{Object.defineProperty(e,"files",{configurable:!0,get:()=>[n]}),e.dispatchEvent(r)}finally{Object.hasOwn(e,"files")&&delete e.files}}return zE(RA);})();
28
28
  /*! Bundled license information: