@deepdesk/deepdesk-sdk 10.1.7 → 10.1.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs.js +1 -1
- package/dist/index.esm.js +1 -1
- package/dist/index.iife.js +1 -1
- package/package.json +1 -1
package/dist/index.iife.js
CHANGED
|
@@ -18,7 +18,7 @@ ${$.current.stack}
|
|
|
18
18
|
|
|
19
19
|
`),o=o.replace(/\n/g,"<br/>"),o}createContainer(t){var n;let o=(typeof global<"u"&&global.INTERWEAVE_SSR_POLYFILL||qP)();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(KP)||(s.innerHTML=this.convertLineBreaks(this.props.escapeHtml?(0,l_.default)(t):t)),s}extractAttributes(t){let{allowAttributes:n}=this.props,r={},o=0;return t.nodeType!==a_||!t.attributes||([...t.attributes].forEach(i=>{let{name:s,value:a}=i,l=s.toLowerCase(),u=Ic[l]||Ic[s];if(!this.isSafe(t)||!l.match(WP)&&(!n&&(!u||u===tg)||l.startsWith("on")||a.replace(/(\s|\0|�([9AD]);)/,"").match(/(javascript|vbscript|livescript|xss):/i)))return;let c=l==="style"?this.extractStyleAttribute(t):a;u===yr?c=!0:u===Zr?c=Number.parseFloat(String(c)):u!==Rc&&(c=String(c)),r[ng[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 la[t]?{...n,...la[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===a_){let d=c.nodeName.toLowerCase(),y=this.getTagConfig(d);u&&(l.push(u),u="");let v=this.applyNodeFilters(d,c);if(!v)return;let h;if(s&&!(a&&!this.isTagAllowed(d))){this.keyIndex+=1;let g=this.keyIndex;h=this.parseNode(v,y);let m=s(v,h,y);if(m===null)return;if(typeof m<"u"){l.push(eo.default.cloneElement(m,{key:g}));return}this.keyIndex=g-1}if(this.banned.has(d))return;if(!(r||o&&d!=="br")&&this.isTagAllowed(d)&&(i||this.canRenderChild(n,y))){var f;this.keyIndex+=1;let g=this.extractAttributes(v),m={tagName:d};g&&(m.attributes=g),y.void&&(m.selfClose=y.void),l.push(eo.default.createElement(Lc,{...m,key:this.keyIndex},(f=h)!==null&&f!==void 0?f:this.parseNode(v,y)))}else l=[...l,...this.parseNode(v,y.tagName?y:n)]}else if(c.nodeType===VP){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($P);){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:f,props:d}=n[a],y;if(u)y=s.length,r.push(f.createElement(c,d));else{let v=o.match(new RegExp(`{{{/${a}}}}`));y=v.index+v[0].length,r.push(f.createElement(this.replaceTokens(o.slice(s.length,v.index),n),d))}o=o.slice(y)}return o.length>0&&r.push(o),r.length===0?"":r.length===1&&typeof r[0]=="string"?r[0]:r}};function GP(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",f=c==="fragment"?!0:u,d;if(a)d=a;else{let y=new Ac(i??"",e).parse();y.length>0&&(d=y)}return d||(d=s),f?eo.default.createElement(eo.default.Fragment,null,d):eo.default.createElement(Lc,{attributes:n,className:r,tagName:c},d)}function ai(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:f="span",noWrap:d=!1,...y}=e,v=i?[]:l,h=o?[]:a,g=c?[c]:[],m=u?[u]:[];v.forEach(C=>{C.onBeforeParse&&g.push(C.onBeforeParse.bind(C)),C.onAfterParse&&m.push(C.onAfterParse.bind(C))});let p=g.reduce((C,w)=>w(C,e),r??""),x=new Ac(p,y,v,h),_=m.reduce((C,w)=>w(C,e),x.parse());return eo.default.createElement(GP,{attributes:t,className:n,containerTagName:e.containerTagName,emptyContent:s,noWrap:d,parsedContent:_.length===0?void 0:_,tagName:f})}var dg=S(X());var og={root:"_root_kxnai_1",agentText:"_agentText_kxnai_3",textInput:"_textInput_kxnai_8",textInputWrapper:"_textInputWrapper_kxnai_27",alert:"_alert_kxnai_31",alertText:"_alertText_kxnai_50",warning:"_warning_kxnai_60",success:"_success_kxnai_69"};var c_=S(X());var li=S(O());function u_(e,t){let n;return[(...r)=>{window.cancelAnimationFrame(n);let o=t?t(...r):r;n=window.requestAnimationFrame(()=>{e(...o)})},()=>window.cancelAnimationFrame(n)]}function Oc(e){let t=(0,li.useRef)(null),[n,r]=(0,li.useState)(!1);return(0,li.useEffect)(()=>{let o=!1,i=parseFloat(window.getComputedStyle(document.body).zoom??"1"),[s,a]=u_((c,f)=>{let d=t.current;if(!d)return;let y=c/i,v=f/i,h=d.getBoundingClientRect(),g=y>h.x&&y<h.x+h.width&&v>h.y&&v<h.y+h.height;g&&!o?(o=!0,r(!0)):!g&&o&&(o=!1,r(!1))},({clientX:c,clientY:f})=>[c,f]),[l,u]=u_(()=>{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 bt={root:"_root_1l8n5_1",container:"_container_1l8n5_4",agentText:"_agentText_1l8n5_7",tabText:"_tabText_1l8n5_8",hint:"_hint_1l8n5_8",matchSelection:"_matchSelection_1l8n5_12",focus:"_focus_1l8n5_18",resetIndent:"_resetIndent_1l8n5_22",matchKeyword:"_matchKeyword_1l8n5_26",matchPlaceholder:"_matchPlaceholder_1l8n5_27",hover:"_hover_1l8n5_33",hintText:"_hintText_1l8n5_66",popover:"_popover_1l8n5_74",popoverRoot:"_popoverRoot_1l8n5_79",popoverContentContainer:"_popoverContentContainer_1l8n5_83",popoverContent:"_popoverContent_1l8n5_83",selectionOptions:"_selectionOptions_1l8n5_109",selectionOptionsIsHidden:"_selectionOptionsIsHidden_1l8n5_114",selectionOptionsButton:"_selectionOptionsButton_1l8n5_118",caret:"_caret_1l8n5_134",popoverSuggestionsRoot:"_popoverSuggestionsRoot_1l8n5_138",suggestionsOverlayInputStyles:"_suggestionsOverlayInputStyles_1l8n5_143"};var ig=S(E()),XP=({inputElement:e,children:t})=>{let n=k("TabCompletion",bt),[r,o]=Oc(e);return(0,ig.jsx)("mark",{ref:r,className:(0,c_.default)(n.matchPlaceholder,{[n.hover]:o}),children:t})},ui=class extends Ht{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,ig.jsx)(XP,{inputElement:n.inputElement,children:t},`placeholder_${n.matchString}_${n.key}`)}asTag(){return"mark"}};var ci=S(O());function Nc(e){return e.contentEditable==="true"}function QP(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 d_(e){let{selectionStart:t,selectionEnd:n}=Nc(e)?QP(e):e;return[t,n]}function Mc(e){let[,t]=(0,ci.useState)(),n=(0,ci.useRef)(null);return n.current=d_(e),(0,ci.useEffect)(()=>{let r=()=>{let[o,i]=n.current??[],s=d_(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 Dc(e,t){if(!t)return;let n=e,{value:r}=n,[o,i]=t,s=r.match(ho);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 f_=S(O());function di(e){(0,f_.useEffect)(()=>{let t=n=>{n.isWithinRoot||e(n)};return document.body.addEventListener("mouseup",t),()=>{document.body.removeEventListener("mouseup",t)}},[e])}function to(e){e.addEventListener("mouseup",t=>{t.isWithinRoot=!0},!0)}var p_,nn=new Map,YP=["bottom","height","left","right","top","width"],ZP=(e={},t={})=>YP.some(n=>e[n]!==t[n]),m_=()=>{let e=[];nn.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),nn.delete(n);return}let r=n.getBoundingClientRect();ZP(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{t.callbacks.forEach(n=>n(t.rect))}),nn.size!==0&&(p_=window.requestAnimationFrame(m_))};function g_(e,t){return{observe(){let n=nn.size===0;if(nn.has(e)){let r=nn.get(e);r.callbacks.push(t),r.rect&&t(r.rect)}else nn.set(e,{rect:void 0,callbacks:[t]});n&&m_()},unobserve(){let n=nn.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||nn.delete(e),nn.size||cancelAnimationFrame(p_)}}}}var h_,rn=new Map,y_=()=>{rn.forEach((e,t)=>{if(!t.isConnected){rn.delete(t);return}let{clientHeight:n,scrollHeight:r}=t,o=r>n;e.visible!==o&&(e.visible=o,e.callbacks.forEach(i=>i(e.visible)))}),rn.size!==0&&(h_=window.requestAnimationFrame(y_))};function v_(e,t){return{observe(){let n=rn.size===0;rn.has(e)?rn.get(e).callbacks.push(t):rn.set(e,{visible:void 0,callbacks:[t]}),n&&y_()},unobserve(){let n=rn.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||rn.delete(e),rn.size||cancelAnimationFrame(h_)}}}}var sg=["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 ag(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function fi(e){return parseFloat(e)}function Fc(e){return Math.round(e*1e6)}function S_(e){return e/1e6}function lg(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=fi(e.width),i=fi(e.borderLeftWidth),s=fi(e.borderRightWidth),a=fi(e.paddingRight),l=S_(Fc(o)-Fc(i)-Fc(s)),u=S_(Fc(r));if(l-u>2){let c=l-u;n.style.paddingRight=`${a+c}px`}}function pi(e,t={}){var l;let n=t.overlayContainer||document.createElement("div");n.style.display="none",n.style.position="fixed",n.style.pointerEvents="none",n.style.borderColor="transparent",to(n);let r=window.getComputedStyle(e),o=!0,i=()=>{n.scrollTop=e.scrollTop};ag(r,n,sg),lg(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",i));let s=v_(e,()=>{ag(r,n,sg),lg(r,e,n),i(),setTimeout(i,0)}),a=g_(e,u=>{if(u===null){t.onRemove&&t.onRemove(),n.remove();return}if(u.height===0&&u.width===0){if(o===!0)return;t.onHide&&t.onHide(),n.style.display="none",o=!0;return}if(ag(r,n,sg),lg(r,e,n),i(),n.style.top=`${u.top}px`,n.style.left=`${u.left}px`,t.closestScrollElement&&t.closestScrollElement!==e){let c=t.closestScrollElement.getBoundingClientRect(),f=window.getComputedStyle(t.closestScrollElement),d=fi(f.borderTopWidth),y=fi(f.borderBottomWidth),v=c.top+d-u.top,h=u.top+u.height+-(c.top+c.height-y);n.style.clipPath=`inset(${v}px 0px ${h}px 0px)`}o&&(n.style.display="block",t.onShow&&t.onShow(),o=!1)});return t.appendTo?t.appendTo.appendChild(n):(l=e.parentElement)==null||l.appendChild(n),a.observe(),s.observe(),[n,()=>{e.removeEventListener("scroll",i),a.unobserve(),s.unobserve()}]}var ug={};Ce(ug,{enUS:()=>JP,nlNL:()=>eR});var JP={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"}]},eR={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 ua=S(E()),x_=()=>(0,ua.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 512 512","aria-labelledby":"circleCheckTitle",children:[(0,ua.jsx)("title",{id:"circleCheckTitle",children:"Check"}),(0,ua.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 cg=S(E()),__=()=>(0,cg.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 512 512",fill:"currentColor",children:(0,cg.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 w_=(s=>(s.CUT="Cut",s.BACKSPACE="Backspace",s.DELETE="Delete",s.ERASEEOF="EraseEof",s.UNDO="Undo",s.CLEAR="Clear",s))(w_||{}),_n=class{constructor(t){this.element=t;this.currentText=this.getText(),this.currentHTML=this.getHTML(),this.listen()}eventListeners={};disposeHandlers=[];currentText="";currentHTML="";currentSelection=null;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,rawHtml:n}),this.currentText=t,this.isSubmitting=!1,(this.currentHTML!==n||n===null&&r)&&(this.emit("updated",{plainText:t,rawHtml:n}),this.currentHTML=n))}handleKeyUp(t){let{key:n,shiftKey:r}=t;(n==="Enter"&&r===!0||n==="Backspace")&&this.triggerChange()}handleFocus(){this.isFocused||this.emit("focus"),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(w_).includes(n)||n.toLowerCase()==="z"&&(r||o),this.emit("keydown",t)}handleCut(){let t=this.currentSelection;this.isPossibleClearInputAction=!0,t&&this.emit("cut",{selectionText:this.getSelectedText()})}handlePaste(t){let n=(t.clipboardData||window.clipboardData).getData("text");this.emit("paste",{pastedText:n,selectionText:this.getSelectedText()})}listen(){let t=()=>{let r=document.activeElement===this.element?this.getSelection():null;pr(this.currentSelection,r)||(this.currentSelection=r,this.emit("selection",r))};document.addEventListener("selectionchange",t),this.disposeHandlers.push(()=>{window.document&&document.removeEventListener("selectionchange",t)}),this.addEventListener("keydown",r=>this.handleKeyDown(r)),this.addEventListener("keyup",r=>this.handleKeyUp(r)),this.addEventListener("input",()=>this.triggerChange()),this.addEventListener("change",()=>this.triggerChange()),this.addEventListener("focus",()=>this.handleFocus()),this.addEventListener("blur",()=>this.handleBlur()),this.addEventListener("cut",()=>this.handleCut()),this.addEventListener("paste",r=>this.handlePaste(r)),document.activeElement===this.element&&setTimeout(()=>{this.handleFocus()},0);let n=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});n.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{n.disconnect()})}focus(){this.element.focus()}emit(t,...n){this.isDisposed||this.eventListeners[t]&&this.eventListeners[t].forEach(r=>{r(...n)})}on(t,n){this.isDisposed||(this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n))}activate(){let t=this.isActive===!1;this.isActive=!0,t&&this.triggerChange()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(t=>t()),this.eventListeners={},this.isDisposed=!0}};var wn=class extends _n{getText(){return this.element.value}getHTML(){return null}getSelection(){let{selectionStart:t,selectionEnd:n}=this.element;return{start:t,end:n}}getSelectedText(){return this.currentSelection?this.getText().slice(this.currentSelection.start,this.currentSelection.end):""}applyChanges(t){if(!this.isActive)return;this.isSettingValue=!0;let n=this.getText(),r=t(this.element);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 Xe=S(E()),tR=({value:e,onUse:t,...n})=>{var c;let r=j(ug),o=W(),i=k("EditSuggestionTextInput",og),[s,a]=(0,Tt.useState)(null),l=(0,Tt.useRef)(null),u=((c=e.match(ho))==null?void 0:c.length)||0;return(0,Tt.useEffect)(()=>{let f;return l.current&&(a(l.current),f=new wn(l.current),f.on("change",({plainText:d})=>{o(Ge.actions.userInput({text:d,selection:f.getSelection()}))}),f.on("keydown",d=>{o(Ge.actions.registerKeyDown(vc(d))),d.code==="Enter"&&d.shiftKey&&t(f.getText())}),f.on("paste",({pastedText:d,selectionText:y})=>{o(Ge.actions.registerPaste({text:d,selectionText:y}))}),f.on("cut",({selectionText:d})=>{o(Ge.actions.registerCut(d))})),()=>{o(Ge.actions.reset()),f.dispose(),f.deactivate()}},[l]),(0,Tt.useEffect)(()=>{e&&l.current&&(l.current.value=e)},[e,l]),(0,Tt.useEffect)(()=>{l.current&&setTimeout(()=>{if(!l.current)return;let f=l.current.value.length;l.current.setSelectionRange(f,f),l.current.focus()},0)},[l]),(0,Xe.jsxs)("div",{className:i.textInputWrapper,children:[(0,Xe.jsx)("textarea",{...n,ref:l,"data-testid":"edit-suggestion-dialog-textarea",className:i.textInput,defaultValue:e,onChange:()=>{}}),s&&(0,Xe.jsx)(nR,{inputElement:l.current,value:e}),(0,Xe.jsxs)("div",{className:(0,dg.default)(i.alert,u===0?i.success:i.warning),children:[(0,Xe.jsx)("div",{className:i.alertText,children:r("placeholders",{placeholderSize:u})}),u===0?(0,Xe.jsx)(x_,{}):(0,Xe.jsx)(__,{})]})]})},nR=({inputElement:e,value:t})=>{let n=k("EditSuggestionTextInput",og),r=(0,Tt.useRef)(null),o=Mc(e);return(0,Tt.useEffect)(()=>{Dc(e,o)},[o,e]),(0,Xe.jsx)(rR,{inputElement:e,children:(0,Xe.jsxs)("div",{ref:r,className:(0,dg.default)(n.root,n.agentText),children:[(0,Xe.jsx)(ai,{tagName:"span",disableLineBreaks:!0,content:t,matchers:[new ui("placeholders")],inputElement:e,boundaryRef:r}),(0,Xe.jsx)("br",{})]})})},rR=({inputElement:e,children:t})=>{let n=(0,Tt.useRef)(null);return(0,Tt.useEffect)(()=>{if(!n.current)return()=>{};let[r,o]=pi(e,{overlayContainer:n.current,mirrorOverflow:!0});return()=>{o()}},[n.current]),(0,Xe.jsx)("div",{ref:n,children:t})},E_=tR;var hi=S(O());var C_=S(O()),jc=S(X());var Qe={root:"_root_185k9_1",list:"_list_185k9_2",listWrapper:"_listWrapper_185k9_6",listHorizontal:"_listHorizontal_185k9_10",page:"_page_185k9_19",search:"_search_185k9_25",pageNav:"_pageNav_185k9_33",pageTitle:"_pageTitle_185k9_41",pageBackButton:"_pageBackButton_185k9_48",listHeading:"_listHeading_185k9_62",listItem:"_listItem_185k9_70",listItemContent:"_listItemContent_185k9_79",listItemText:"_listItemText_185k9_97",listItemDescription:"_listItemDescription_185k9_105",truncate:"_truncate_185k9_112",lineClamp:"_lineClamp_185k9_118",listItemTitle:"_listItemTitle_185k9_125",listItemAction:"_listItemAction_185k9_132",listItemPrimaryAction:"_listItemPrimaryAction_185k9_146",listItemSelected:"_listItemSelected_185k9_151",sources:"_sources_185k9_155",sourcesTitle:"_sourcesTitle_185k9_162",source:"_source_185k9_155",icon:"_icon_185k9_177",searchIcon:"_searchIcon_185k9_194",searchInputWrapper:"_searchInputWrapper_185k9_199",searchInput:"_searchInput_185k9_199",select:"_select_185k9_220",selectType:"_selectType_185k9_237",selectWrapper:"_selectWrapper_185k9_241",image:"_image_185k9_271",imageSrc:"_imageSrc_185k9_278",imageSrcHidden:"_imageSrcHidden_185k9_289",imageSrcStatus:"_imageSrcStatus_185k9_293",imageTitle:"_imageTitle_185k9_303",actions:"_actions_185k9_308",actionsWrapper:"_actionsWrapper_185k9_312",actionsBar:"_actionsBar_185k9_318",actionButton:"_actionButton_185k9_327",actionShortcut:"_actionShortcut_185k9_345",actionShortcutFixKerning:"_actionShortcutFixKerning_185k9_352"};var no={};Ce(no,{enUS:()=>oR,nlNL:()=>iR});var oR={visitUrl:[{type:0,value:"Visit"}],back:[{type:0,value:"Back"}],loading:[{type:0,value:"Loading..."}],imageError:[{type:0,value:"Could not load image"}]},iR={visitUrl:[{type:0,value:"Bekijk"}],back:[{type:0,value:"Terug"}],loading:[{type:0,value:"Laden..."}],imageError:[{type:0,value:"Kan afbeelding niet laden"}]};var vr=S(E()),sR=({src:e,title:t})=>{let n=k("CommandPalette",Qe),[r,o]=(0,C_.useState)("loading"),i=j(no);return(0,vr.jsxs)("div",{className:n.image,children:[(0,vr.jsx)("img",{src:e,alt:t,onLoad:()=>o("done"),onError:()=>o("error"),className:(0,jc.default)(n.imageSrc,{[n.imageSrcHidden]:["loading","error"].includes(r)})}),r==="loading"&&(0,vr.jsx)("span",{className:(0,jc.default)(n.imageSrc,n.imageSrcStatus),children:i("loading")}),r==="error"&&(0,vr.jsx)("span",{className:(0,jc.default)(n.imageSrc,n.imageSrcStatus),children:(0,vr.jsx)($a,{})}),t&&(0,vr.jsx)("span",{className:n.imageTitle,children:t})]})},b_=sR;var T_=S(O()),k_=S(X());var ca=S(E());function fg({children:e,heading:t,orientation:n}){let r=k("CommandPalette",Qe);return T_.default.Children.count(e)===0?null:(0,ca.jsxs)("div",{"data-testid":"commandpalette-list",className:r.list,children:[t&&(0,ca.jsx)("h4",{className:r.listHeading,children:t}),(0,ca.jsx)("div",{className:(0,k_.default)(r.listWrapper,n==="horizontal"&&r.listHorizontal),children:e})]})}var da=S(X());var Hc=S(O()),I_=S(E()),P_=Hc.default.createContext(void 0);function Sr(){let e=Hc.default.useContext(P_);if(e===void 0)throw new Error("useCommandPalette must be used within the CommandPalette component");return e}var R_=({children:e,page:t,isOpen:n,onChangeOpen:r,selected:o,setSelected:i})=>{let s=Hc.default.useMemo(()=>({page:t,isOpen:n,onChangeOpen:r,selected:o,setSelected:i}),[n,t,o]);return(0,I_.jsx)(P_.Provider,{value:s,children:e})};var kt=S(E());function pg({closeOnSelect:e=!0,lineClamp:t,children:n,onClick:r,onSourceClick:o,index:i,isExperimental:s,description:a,sources:l,styles:u,...c}){let{selected:f,onChangeOpen:d}=Sr(),y=k("CommandPalette",Qe);function v(h){r(h),e&&d(!1)}return(0,kt.jsxs)("div",{className:(0,da.default)(y.listItem,f===i&&y.listItemSelected),children:[(0,kt.jsxs)("button",{type:"button",className:(0,da.default)("command-palette-list-item",y.listItemAction,y.listItemPrimaryAction),"aria-disabled":c.disabled??!1,onClick:v,...c,children:[(0,kt.jsxs)("div",{className:y.listItemContent,children:[typeof n=="string"?(0,kt.jsx)("p",{className:(0,da.default)(y.listItemText,y.truncate,u==null?void 0:u.title),children:n}):n,a&&(0,kt.jsx)("p",{className:(0,da.default)(y.listItemDescription,u==null?void 0:u.description,t?y.lineClamp:y.truncate),children:a})]}),s&&(0,kt.jsx)(cl,{})]}),l&&(0,kt.jsxs)("div",{className:y.sources,children:[(0,kt.jsx)("span",{className:y.sourcesTitle,children:"Sources"}),l.map(h=>h.url?(0,kt.jsx)("a",{className:y.source,href:h.url,target:"_blank",title:h.url,rel:"noopener noreferrer",onClick:()=>o&&o(h),children:h.name},h.url):(0,kt.jsx)("span",{className:y.source,children:h.name},h.name))]})]})}var xr=S(E());function mg({children:e,title:t,id:n,onDismiss:r,isExperimental:o}){let i=j(no),s=k("CommandPalette",Qe),{page:a}=Sr();return a!==n?null:(0,xr.jsxs)("div",{className:s.page,id:`page_${n}`,tabIndex:-1,children:[r&&(0,xr.jsxs)("div",{className:s.pageNav,children:[(0,xr.jsxs)("button",{className:s.pageBackButton,type:"button",onClick:r,children:[(0,xr.jsx)(bc,{}),i("back")]}),t&&(0,xr.jsx)("h3",{className:s.pageTitle,children:t}),o&&(0,xr.jsx)(cl,{})]}),e]})}var _r=S(O());var Bc=()=>/Mac/i.test(navigator.platform);var aR={info(...e){console.info("[Deepdesk]",...e)},warn(...e){console.warn("[Deepdesk]",...e)},error(...e){console.error("[Deepdesk]",...e)}},U=aR;function lR(e){return e.replace(/(_\w)/g,t=>t[1].toUpperCase())}function re(e){return Array.isArray(e)?e.map(re):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>({...t,[lR(n)]:re(e[n])}),{}):e}function gg(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function we(e){return Array.isArray(e)?e.map(we):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>({...t,[gg(n)]:we(e[n])}),{}):e}var uR={agentInfo:void 0,agentSettings:{},visitorInfo:void 0,fetchState:"idle"},pa=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)||""}},fa=M("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?re(r):(await n.client.patch("/apis/admin/session/me/",o,{version:null}),re(r))}),hg=M("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}),yg=M("info/getAgentSettings",async(e,t)=>{let{deepdeskAPI:n}=t.extra;return(await n.client.get("/apis/admin/session/me/",{version:null})).ui_config}),L_=e=>e.info.agentInfo,A_=H({name:"info",initialState:uR,reducers:{setVisitorInfo(e,t){e.visitorInfo={...e.visitorInfo,...t.payload}}},extraReducers:e=>{e.addCase(fa.pending,(t,n)=>{t.fetchState="loading",t.agentInfo={...t.agentInfo,...n.meta.arg}}).addCase(fa.rejected,t=>{t.fetchState="error"}).addCase(fa.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(hg.fulfilled,(t,n)=>{t.agentSettings=n.payload}).addCase(yg.fulfilled,(t,n)=>{t.agentSettings=n.payload}).addCase(J,t=>{t.visitorInfo=void 0})}}),{setVisitorInfo:O_}=A_.actions,N_=A_.reducer;var Uc={list:[],fetchState:"idle",isOpen:!1,page:"search"},M_=e=>e.search.isOpen,D_=e=>e.search.page,F_=e=>e.search.list;function j_(e,t=n=>n){return n=>n.search.list.filter(r=>r.type===e).map(t)}var ro=M("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:pa(r),tags:e.tags});return i.map(a=>({...a,source:a.type==="URL"?"search-url":"search-overlay",searchTerm:e.query}))}),H_=H({name:"search",initialState:Uc,reducers:{setIsOpen(e,t){e.isOpen=t.payload},setPage(e,t){e.page=t.payload},resetSearch(e){e.fetchState=Uc.fetchState,e.list=Uc.list}},extraReducers:e=>{e.addCase(ro.pending,t=>{t.fetchState="loading"}).addCase(ro.rejected,(t,n)=>{t.fetchState="error",U.error(n.error)}).addCase(ro.fulfilled,(t,n)=>{t.fetchState="done",t.list=n.payload}).addCase(J,()=>Uc)}}),{resetSearch:zc,setIsOpen:st,setPage:Ue}=H_.actions,B_=H_.reducer;var cR=/(https?:\/\/[^\s]+)/,Vc=e=>e.split(" ").find(t=>cR.test(t));var vg=S(X());var Kc=S(E()),dR=({onClick:e,shortKeys:t,children:n,...r})=>{let o=k("CommandPalette",Qe);return(0,Kc.jsxs)("button",{type:"button",...r,onClick:e,className:(0,vg.default)(o.actionButton,r.className),children:[n,t&&t.map(i=>(0,Kc.jsx)("span",{className:(0,vg.default)(o.actionShortcut,i===8629&&o.actionShortcutFixKerning),children:typeof i=="number"?String.fromCharCode(i):i},i))]})},mi=dR;var En=S(E()),fR=({children:e,primaryLabel:t,secondaryLabel:n,onPrimary:r,onSecondary:o,list:i})=>{let s=k("CommandPalette",Qe),a=j(no),{selected:l,setSelected:u}=Sr(),c=i[l],f=c&&typeof c.text=="string"&&Vc(c.text),d=(0,_r.useRef)(null);function y(x){if(!d.current)return;let _=d.current.querySelectorAll(".command-palette-list-item"),C=0,w=0;x==="down"?(_.forEach((R,P)=>{P===l&&(C=P)}),w=C===_.length-1?0:C+1):x==="up"?(_.forEach((R,P)=>{P===l&&(C=P)}),w=C?C-1:_.length-1):u(0);let b=_[w];b&&typeof w=="number"&&(u(w),b.scrollIntoView&&b.scrollIntoView({behavior:"smooth",block:w?"center":"end"}))}function v(){if(!d.current)return;let x=d.current.querySelectorAll(".command-palette-list-item"),_=0;x.forEach((w,b)=>{b===l&&(_=b)});let C=x[_];C&&C.click()}let h=()=>{f&&window.open(f,"_blank")},g=()=>{c&&r(c,l)},m=()=>{!c.type||["IMAGE","command"].includes(c.type)||o&&o(c,l)},p=(0,_r.useCallback)(x=>{if(x.key==="Enter"&&x.altKey&&f){h();return}if(x.key==="Enter"&&x.shiftKey){m();return}if(x.key==="ArrowDown"){x.preventDefault(),x.stopPropagation(),y("down");return}if(x.key==="ArrowUp"){x.preventDefault(),x.stopPropagation(),y("up");return}x.key==="Enter"&&l!==-1&&(x.preventDefault(),x.stopPropagation(),v())},[l]);return(0,_r.useEffect)(()=>(window.addEventListener("keyup",p),()=>{window.removeEventListener("keyup",p)}),[p]),(0,En.jsxs)("div",{className:s.actions,children:[(0,En.jsx)("div",{className:s.actionsWrapper,ref:d,children:e}),(0,En.jsxs)("div",{className:s.actionsBar,children:[f&&(0,En.jsx)(mi,{onClick:h,shortKeys:[Bc()?8997:"ALT",8629],children:a("visitUrl")}),c&&(0,En.jsxs)(_r.Fragment,{children:[o&&c.type&&!["command","image"].includes(c.type.toLowerCase())&&(0,En.jsx)(mi,{onClick:m,shortKeys:[8679,8629],children:n}),(0,En.jsx)(mi,{onClick:g,shortKeys:[8629],children:t})]})]})]})},z_=fR;var V_=S(O());var ma=S(E()),gi=()=>(0,ma.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 0 24 24",width:"1em",fill:"currentColor",children:[(0,ma.jsx)("path",{d:"M0 0h24v24H0z",fill:"none"}),(0,ma.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 Bt=S(E());function pR({onChange:e,onChangeType:t,placeholder:n,typePlaceholder:r,types:o,value:i,selectedType:s},a){let l=k("CommandPalette",Qe);return(0,Bt.jsxs)("div",{className:l.search,children:[(0,Bt.jsx)("div",{className:l.searchIcon,children:(0,Bt.jsx)(gi,{})}),(0,Bt.jsxs)("div",{className:l.searchInputWrapper,children:[(0,Bt.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,Bt.jsx)("div",{className:l.selectWrapper,children:(0,Bt.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,Bt.jsx)("option",{children:r}),o.map(u=>(0,Bt.jsx)("option",{value:u.value,children:u.label},u.value))]})})]})]})}var K_=(0,V_.forwardRef)(pR);var ga=S(E());function oo({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:f,search:d}){let[y,v]=(0,hi.useState)(0),h=(0,hi.useRef)(null),g=()=>{o&&o(n),s(void 0),i(""),a(!1)},m=()=>{var p;if(r!==n&&o){o(n);return}if(l&&s){s(void 0),(p=h.current)==null||p.focus();return}if(d.length>0){i("");return}a(!1)};return(0,hi.useEffect)(()=>{v(0)},[d,r]),(0,ga.jsx)(si,{autoFocus:!0,contentAriaLabel:"Search Results",overlayAriaLabel:"Command Palette",isOpen:f,onBack:m,onClose:g,children:(0,ga.jsxs)(R_,{selected:y,setSelected:v,isOpen:f,onChangeOpen:a,page:r,children:[r===n&&(0,ga.jsx)(K_,{ref:h,onChange:i,onChangeType:s,placeholder:e,value:d,selectedType:l,types:u,typePlaceholder:t}),c]})})}oo.Page=mg;oo.List=fg;oo.Image=b_;oo.ListItem=pg;oo.ActionsBar=z_;oo.Button=mi;var te=oo;var Fe=S(E()),mR=({suggestion:e,onUse:t,onDismiss:n,onTouched:r,onNext:o,onPrevious:i})=>{let s=e.text||e.url||e.message,a=k("EditSuggestionForm",n_),l=W(),u=j(Xm),c=A(v=>v.overlayInput.text);(0,Sg.useEffect)(()=>{e&&(l(Ge.actions.reset()),l(Ge.actions.stageSuggestion({text:s,suggestion:{...e,source:"search-preview"},eventMetrics:{inputType:"mouse"},replace:"until-selection-end"})),l(Ge.actions.commitSuggestion()))},[e]);let f=v=>{v.preventDefault(),d(c)},d=v=>{l(_c(v)),t(v)},y=v=>h=>{c!==s?window.confirm(u("warning"))&&v(h):v(h)};return(0,Sg.useEffect)(()=>{r&&r(c!==s)},[r,e,c]),(0,Fe.jsxs)("div",{className:a.root,children:[(0,Fe.jsxs)("div",{className:a.content,children:[e.title&&(0,Fe.jsx)("h3",{className:a.title,children:e.title}),e.searchKeywords&&e.searchKeywords.length>0&&(0,Fe.jsx)(Ud,{labels:e.searchKeywords}),(0,Fe.jsx)(E_,{onUse:d,value:c})]}),(0,Fe.jsxs)("form",{className:a.actions,onSubmit:f,children:[(0,Fe.jsxs)("div",{children:[(0,Fe.jsx)("button",{disabled:!i,className:a.pagination,type:"button",onClick:i&&y(i),children:(0,Fe.jsx)(bc,{})}),(0,Fe.jsx)("button",{disabled:!o,className:a.pagination,type:"button",onClick:o&&y(o),children:(0,Fe.jsx)(r_,{})})]}),(0,Fe.jsxs)("div",{className:a.primaryButtons,children:[(0,Fe.jsx)(te.Button,{onClick:y(n),shortKeys:["esc"],children:u("dismiss")}),(0,Fe.jsx)(te.Button,{shortKeys:[8679,8629],type:"submit",children:u("add")})]})]})]})},Wc=mR;var gR=["{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}"],hR=new RegExp(gR.map(e=>`(?:${e.replace("{","\\{").replace("}","\\}")})`).join("|"));function W_(e,t){let n=e.split(hR),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 f=a.charAt(0),d=0;do u=f?t.indexOf(f,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 $_(e,t){return typeof t=="boolean"?e:e.slice(0,t)}var G_={suggestions:[],fetchState:"idle",isInitialRequest:null},q_={default:G_},X_=e=>t=>{var n;return((n=t.textSuggestions[e])==null?void 0:n.suggestions)||[]},Q_=e=>t=>{var n;return((n=t.textSuggestions[e])==null?void 0:n.suggestions)??[]},Y_=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")},yi=e=>e.textSuggestions,Z_=e=>t=>t.text.startsWith(e),$c=fe("textSuggestions/refresh"),Cn=M("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=oi(r);if(!o)throw new Error("No current conversation to fetch text suggestions");let l=await n.getTextSuggestions(o,pa(r),e);if(e==="default"){let c=s?l.filter(Z_(a)):l;t.dispatch(gr(c.slice(0,i)))}return l}),ha=M("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,{...pa(r),input:e});if(!t.getState().input.text)throw new Error("Abort");return a&&(l=l.filter(Z_(e))),s&&(l=l.map(c=>({...c,text:c.source!=="trie-with-typos"?W_(c.text,e):c.text}))),l=$_(l,i),t.dispatch(gr(l)),l}),J_=H({name:"textSuggestions",initialState:q_,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(Cn.pending,(t,n)=>{let r=n.meta.arg,o=t[r]||G_;return{...t,[r]:{...o,fetchState:"loading",isInitialRequest:o.isInitialRequest===null}}}).addCase(Cn.rejected,(t,n)=>{let r=n.meta.arg;t[r].fetchState="error"}).addCase(Cn.fulfilled,(t,n)=>{let r=n.meta.arg;t[r].fetchState="done",t[r].suggestions=n.payload}).addCase(ha.pending,t=>{t.default.fetchState="loading"}).addCase(ha.rejected,t=>{t.default.fetchState="error"}).addCase(ha.fulfilled,(t,n)=>{t.default.fetchState="done",t.default.suggestions=n.payload}).addCase(J,()=>q_)}}),{setTextSuggestions:ew,setSuggestionState:tw}=J_.actions,nw=J_.reducer;var rw={contentType:null,suggestion:null},ow=e=>e.activeSuggestion.suggestion,iw=e=>e.activeSuggestion.contentType,sw=H({name:"activeSuggestion",initialState:rw,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(J,()=>rw)}}),{setActiveSuggestion:bn,resetActiveSuggestion:xg}=sw.actions,aw=sw.reducer;var _g={};Ce(_g,{enUS:()=>yR,nlNL:()=>vR});var yR={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"}]},vR={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 SR={showTabHint:!1,inputHasFocus:!1,overlayCollapsed:!1,openOverlayWhenTyping:!1,overlayCollapsedUserOverwrite:!1};var lw=({ui:e})=>e.overlayCollapsed;var uw=H({name:"ui",initialState:SR,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:ya,setInputHasFocus:vi,setOverlayCollapsed:Si,setOpenOverlayWhenTyping:cw,setOverlayCollapsedUserOverwrite:dw}=uw.actions,fw=uw.reducer;var va=S(O()),mw=S(E()),pw=va.default.createContext(null),Sa=({broadcastEvents:e,children:t})=>{let n=va.default.useMemo(()=>e,[]);return(0,mw.jsx)(pw.Provider,{value:n,children:t})},Pt=()=>{let e=(0,va.useContext)(pw);if(!e)throw new Error("You should use the useBroadcastEvents within a BroadcastEventsProvider");return e};var xR={isLoggedIn:!0,loginFetchState:"idle",verifyFetchState:"idle",showLoginOverlay:!1},Tn=e=>e.auth.isLoggedIn,gw=e=>e.auth.loginFetchState,hw=e=>e.auth.verifyFetchState,yw=e=>e.auth.showLoginOverlay,wr=M("auth/validate",async(e,t)=>t.extra.deepdeskAPI.isLoggedIn()),vw=M("auth/requestLogin",async({email:e},t)=>{let{deepdeskAPI:n}=t.extra;return n.requestLoginByEmail(e)}),xa=M("auth/verifyLoginToken",async({token:e},t)=>{let{deepdeskAPI:n}=t.extra;return n.verifyLoginToken(e)}),Sw=H({name:"auth",initialState:xR,reducers:{setIsLoggedIn(e,t){e.isLoggedIn=t.payload},setShowLoginOverlay(e,t){e.showLoginOverlay=t.payload}},extraReducers:e=>{e.addCase(wr.pending,t=>{t.loginFetchState="loading"}),e.addCase(wr.fulfilled,(t,{payload:n})=>{t.isLoggedIn=n,t.loginFetchState="done"}),e.addCase(wr.rejected,t=>{t.loginFetchState="error",t.isLoggedIn=!1}),e.addCase(xa.pending,t=>{t.verifyFetchState="loading"}),e.addCase(xa.rejected,t=>{t.verifyFetchState="error"}),e.addCase(xa.fulfilled,(t,n)=>{n.payload.isLoggedIn?t.verifyFetchState="done":t.verifyFetchState="error"})}}),{setIsLoggedIn:xi,setShowLoginOverlay:xw}=Sw.actions,_w=Sw.reducer;var wg="SetActiveSuggestion",_i="ShowLoginOverlay",Eg="UserLoggedIn",_R="UserLoggedOut",kn="ApplySuggestion",Cg="ApplyImageSuggestion",wR="ShowCommandPalette",ER=e=>({[wg]:t=>{e.dispatch(tw(t.state)),e.dispatch(bn({contentType:t.contentType,suggestion:t.suggestion}))},[wR]:t=>{e.dispatch(st(t.isOpen)),t.page&&e.dispatch(Ue(t.page))},[_i]:t=>{e.dispatch(xw(t))},[Eg]:()=>{e.dispatch(wr())},[_R]:()=>{e.dispatch(wr())},[Cg]:t=>{e.dispatch(Ec({suggestion:t.suggestion}))},[kn]:t=>{e.dispatch(Ft({...t,eventMetrics:{inputType:"mouse"},replace:"selection"})),e.dispatch(hr())}}),ww=ER;var bg=S(E()),CR=()=>{var v;let[e,t]=(0,Ew.useState)(!1),n=A(ow),r=A(iw),o=A(yi),i=W(),s=Pt(),a=j(_g),l=()=>{n!==null&&e?window.confirm(a("warning"))&&u():u()},u=()=>{i(xg()),i(vi(!0)),i(Ge.actions.reset())},c=(h,g)=>{i(xg()),i(vi(!0)),s.send(kn,{text:h,suggestion:g})};if(n===null||r===null)return null;let f=(v=o[r])==null?void 0:v.suggestions.indexOf(n),d=f===0||f===null?void 0:()=>i(bn({contentType:r,suggestion:o[r].suggestions[f-1]})),y=f===o[r].suggestions.length-1||f===null?void 0:()=>i(bn({contentType:r,suggestion:o[r].suggestions[f+1]}));return(0,bg.jsx)(si,{autoFocus:!0,isOpen:f!==null,onClose:l,onBack:l,contentAriaLabel:a("editContentLabel"),overlayAriaLabel:a("overlayLabel"),children:(0,bg.jsx)(Wc,{onTouched:t,onDismiss:u,onUse:h=>c(h,n),suggestion:n,onNext:y,onPrevious:d})})},Cw=CR;var qc=S(X()),Ut=S(O());var Tw=S(X());var bw={root:"_root_1ukx5_1"};var kw=S(E()),bR=({className:e,value:t,...n})=>{let r=k("TextInput",bw);return(0,kw.jsx)("input",{className:(0,Tw.default)(e,r.root),type:"text",value:t,...n})},_a=bR;var Tg={};Ce(Tg,{enUS:()=>TR,nlNL:()=>kR});var TR={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"}]},kR={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 Pw={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 he=S(E());var PR=e=>{try{let t=new URL(e);return new URLSearchParams(t.search).get("token")||void 0}catch{return e}},RR=({agentEmail:e,isOpen:t,origin:n="",onSuccess:r,onDismiss:o})=>{let i=j(Tg),s=k("LoginTokenDialog",Pw),a=A(hw),l=W(),u=F("productName"),[c,f]=(0,Ut.useState)(e||""),[d,y]=(0,Ut.useState)(0),[v,h]=(0,Ut.useState)(""),g=(0,Ut.useCallback)(async _=>{_.preventDefault(),l(vw({email:c})),y(1)},[n,c]),m=()=>{h(""),y(0)},p=(0,Ut.useCallback)(async _=>{_.preventDefault();let C=PR(_.target.elements.token.value);if(!C){h(i("verifyCodeError",{login:x}));return}l(xa({token:C}))},[n]),x=(0,Ut.useMemo)(()=>_=>(0,he.jsx)("button",{type:"button","data-testid":"login-token-dialog-back-button",className:s.anchorButton,onClick:m,children:_},"back-button"),[]);return(0,Ut.useEffect)(()=>{a==="error"&&h(i("verifyCodeError",{login:x})),a==="done"&&r()},[a]),(0,he.jsx)(si,{autoFocus:!0,isOpen:t,contentAriaLabel:i("promptTitle",{productName:u}),overlayAriaLabel:i("promptTitle",{productName:u}),onClose:o,onBack:o,children:(0,he.jsxs)("div",{className:s.root,children:[(0,he.jsx)("h1",{className:s.title,children:i("promptTitle",{productName:u})}),d===0&&(0,he.jsxs)("form",{onSubmit:g,children:[(0,he.jsx)("h2",{className:s.subtitle,children:i("requestCodeTitle")}),(0,he.jsx)("p",{className:s.text,children:i("requestCodeBody",{productName:u})}),(0,he.jsx)(_a,{className:s.input,name:"email",placeholder:i("requestCodeInputPlaceholder"),value:c,onChange:_=>f(_.target.value)}),(0,he.jsx)("div",{className:s.actions,children:(0,he.jsx)("button",{type:"submit",className:(0,qc.default)(s.button,s.primaryButton),children:i("requestCodeSubmitLabel")})})]}),d===1&&(0,he.jsxs)("form",{onSubmit:p,children:[(0,he.jsx)("h2",{className:s.subtitle,children:i("verifyCodeTitle")}),(0,he.jsx)("p",{className:s.text,children:i("verifyCodeBody")}),(0,he.jsx)(_a,{className:s.input,name:"token",placeholder:i("verifyCodeInputPlaceholder"),disabled:["loading","done"].includes(a)}),v&&(0,he.jsx)("div",{className:s.errorMessage,children:v}),(0,he.jsxs)("div",{className:s.actions,children:[(0,he.jsx)("button",{type:"button",className:(0,qc.default)(s.button),onClick:m,children:i("back")}),(0,he.jsx)("button",{type:"submit",className:(0,qc.default)(s.button,s.primaryButton),disabled:["loading","done"].includes(a),children:i("verifyCodeSubmitLabel")})]})]})]})})},Rw=RR;var Lw=S(E()),IR=()=>{let e=A(yw),t=A(L_),n=F("adminUrl"),r=Pt(),o=()=>r.send(_i,!1),i=()=>{r.send(_i,!1),r.send(Eg)};return(0,Lw.jsx)(Rw,{isOpen:e,agentEmail:t==null?void 0:t.agentEmail,origin:n,onDismiss:o,onSuccess:i})},Iw=IR;var r1=S(Rg()),Ze=S(O());var GR={data:null,fetchState:"idle"},Mw=e=>e.contentTypes.data,wa=M("contentTypes/getContentTypes",async(e,t)=>t.extra.deepdeskAPI.getContentTypes()),XR=H({name:"contentTypes",initialState:GR,reducers:{},extraReducers:e=>{e.addCase(wa.pending,t=>{t.fetchState="loading"}).addCase(wa.rejected,t=>{t.fetchState="error"}).addCase(wa.fulfilled,(t,n)=>{t.fetchState="done",t.data=n.payload})}}),Dw=XR.reducer;function Ea(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 Fw=S(O());function jw(e,t){(0,Fw.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 Ca=S(O());var Hw={data:null,fetchState:"idle"},Gc=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},zt=M("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)}),QR=e=>e.filter((t,n)=>n===e.findIndex(r=>r.text===t.text)),YR=H({name:"entities",initialState:Hw,reducers:{},extraReducers:e=>{e.addCase(zt.pending,t=>{t.fetchState="loading"}).addCase(zt.rejected,t=>{t.fetchState="error"}).addCase(zt.fulfilled,(t,n)=>{t.fetchState="done",t.data=QR(t.data?[...t.data,...n.payload]:n.payload)}).addCase(J,()=>Hw)}}),Bw=YR.reducer;var Ig={};Ce(Ig,{enUS:()=>ZR,nlNL:()=>JR});var ZR={noResults:[{type:0,value:"No entities have been found"}],copy:[{type:0,value:"Copy"}],use:[{type:0,value:"Use"}]},JR={noResults:[{type:0,value:"Er zijn geen entiteiten gevonden"}],copy:[{type:0,value:"Kopieer"}],use:[{type:0,value:"Gebruik"}]};var Uw={root:"_root_17kae_1",empty:"_empty_17kae_5"};var io=S(E()),eI=({onCopy:e,onUse:t})=>{let n=(0,Ca.useRef)(null),r=k("EntitiesList",Uw),o=j(Ig),i=A(Gc),s=W();return(0,Ca.useEffect)(()=>{s(zt())},[]),(0,Ca.useEffect)(()=>{n.current&&n.current.focus()},[n]),(0,io.jsxs)("div",{className:r.root,ref:n,tabIndex:-1,children:[i&&i.length>0&&(0,io.jsx)(te.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,io.jsx)(te.List,{children:i.map((a,l)=>(0,io.jsx)(te.ListItem,{index:l,closeOnSelect:!0,onClick:()=>e(a),children:a.text},a.text))},"entities")}),i&&i.length===0&&(0,io.jsx)("p",{className:r.empty,children:o("noResults")})]})},zw=eI;var Vt=S(O());var Vw={data:null,fetchState:"idle"},Kw=e=>e.summary.data,Ww=e=>e.summary.fetchState==="error",Pn=M("summary/getSummary",async(e,t)=>{let n=t.getState().profile.data;if(!n)throw new Error("Profile is not defined");let{deepdeskAPI:r,dynamicThunkObject:o}=t.extra;if(!o.conversationQuery)return Promise.reject(new Error("setConversationQuery method is not defined"));let i=o.conversationQuery,s=await i();if(s.length===0)return Promise.reject(new Error("No messages are included"));let a=await r.getSummary(s,{promptInstruction:n.summarizerPromptInstruction,model:n.summarizerModel});return{original:s,summary:a}}),tI=H({name:"summary",initialState:Vw,reducers:{},extraReducers:e=>{e.addCase(Pn.pending,t=>{t.data=null,t.fetchState="loading"}).addCase(Pn.rejected,t=>{t.data=null,t.fetchState="error"}).addCase(Pn.fulfilled,(t,n)=>{t.fetchState="done",n.payload&&(t.data=n.payload.summary)}).addCase(J,()=>Vw)}}),$w=tI.reducer;var Lg={};Ce(Lg,{enUS:()=>nI,nlNL:()=>rI});var nI={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."}]},rI={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 qw={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 Rn=S(E()),oI=({onCopy:e})=>{let t=(0,Vt.useRef)(null),n=k("SummaryForm",qw),[r,o]=(0,Vt.useState)(""),i=j(Lg),s=A(Kw),a=A(Ww),l=W(),u=()=>{l(it({name:"summary copied to clipboard",data:{originalText:s,finalText:r},options:{includeConversationData:!0}})),e(r)},c=()=>{let f=document.getSelection();f&&l(it({name:"summary copied to clipboard",data:{originalText:s,finalText:f==null?void 0:f.toString()},options:{includeConversationData:!0}}))};return(0,Vt.useEffect)(()=>{l(Pn())},[]),(0,Vt.useEffect)(()=>{o(s||"")},[s]),(0,Vt.useEffect)(()=>{t.current&&s&&t.current.focus()},[t,s]),(0,Vt.useEffect)(()=>{let f=d=>{d.key==="Enter"&&d.shiftKey&&u()};return document.addEventListener("keydown",f),()=>{document.removeEventListener("keydown",f)}},[r]),(0,Rn.jsx)("div",{className:n.root,tabIndex:-1,children:a?(0,Rn.jsx)("p",{className:n.error,children:i("error")}):(0,Rn.jsxs)(Vt.Fragment,{children:[(0,Rn.jsx)("div",{className:n.main,children:(0,Rn.jsx)("textarea",{placeholder:s?void 0:i("loading"),disabled:!s,className:n.textInput,ref:t,value:r,onCopy:c,onChange:f=>o(f.target.value)})}),(0,Rn.jsx)("div",{className:n.actions,children:(0,Rn.jsx)(te.Button,{shortKeys:[8679,8629],onClick:u,children:i("copy")})})]})})},Gw=oI;var Ag={};Ce(Ag,{enUS:()=>iI,nlNL:()=>sI});var iI={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"}],knowledgeSearch:[{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?"}]},sI={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:"Vat gesprek samen"}],summaryTitle:[{type:0,value:"Gesprek samenvatting"}],knowledgeSearch:[{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 Er=S(O());var Og={};Ce(Og,{enUS:()=>aI,nlNL:()=>lI});var aI={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"}]},lI={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 Xw={root:"_root_cnaw4_1",title:"_title_cnaw4_9",empty:"_empty_cnaw4_20",status:"_status_cnaw4_24",form:"_form_cnaw4_30",input:"_input_cnaw4_43",submit:"_submit_cnaw4_55",question:"_question_cnaw4_63",answer:"_answer_cnaw4_67",alignRight:"_alignRight_cnaw4_73"};var Ng={data:[],fetchState:"idle"},Qw=e=>{var t;return(t=e.answer)==null?void 0:t.data},Yw=e=>e.answer.fetchState,Ei=fe("answer/resetKnowledgeSearch"),wi=M("answer/getAnswer",async(e,t)=>{var s;let{deepdeskAPI:n}=t.extra,r=t.getState().answer.data,o=(s=t.getState().conversation.current)==null?void 0:s.profileCode;if(!o)throw new Error("Profile is not defined");let i=await n.knowledgeSearch({promptInstruction:e.promptInstruction,question:e.question},r,o);return{question:e.question,answer:i}}),uI=H({name:"answer",initialState:Ng,reducers:{},extraReducers:e=>{e.addCase(wi.pending,t=>{t.fetchState="loading"}).addCase(wi.rejected,t=>{t.fetchState="error"}).addCase(wi.fulfilled,(t,n)=>{t.fetchState="done",t.data=[...t.data,n.payload]}).addCase(J,()=>Ng).addCase(Ei,()=>Ng)}}),Zw=uI.reducer;var ba=S(E()),Jw=()=>(0,ba.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 512 512","aria-labelledby":"paperPlaneTitle",children:[(0,ba.jsx)("title",{id:"paperPlaneTitle",children:"PaperPlane"}),(0,ba.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 Ye=S(E()),cI=({onUse:e,onResetQuestion:t,question:n,promptInstruction:r})=>{let[o,i]=Er.default.useState(""),{setSelected:s}=Sr(),a=(0,Er.useRef)(null),l=k("EntitiesList",Xw),u=j(Og),c=W(),f=A(Qw),d=A(Yw),y=async h=>{h.preventDefault(),h.stopPropagation(),o!==""&&c(wi({question:o,promptInstruction:r}))},v=(h,g)=>{c(it({name:"knowledge assist source viewed",data:{question:g,sourceViewed:h.url||h.name},options:{includeConversationData:!0}}))};return(0,Er.useEffect)(()=>{var h;n&&d==="idle"?c(wi({question:n,promptInstruction:r})):(h=a.current)==null||h.focus()},[a,d]),(0,Er.useEffect)(()=>{d==="done"&&(c(it({name:"knowledge assist question answered",data:{question:o||n,sources:f[f.length-1].answer.sources,isFollowUpQuestion:f.length>1},options:{includeConversationData:!0}})),s(f.length-1),i(""))},[d,f]),(0,Er.useEffect)(()=>{a.current&&a.current.scrollIntoView({behavior:"smooth"})},[a,f]),(0,Ye.jsxs)("div",{className:l.root,children:[f.length>0&&(0,Ye.jsx)("div",{className:l.alignRight,children:(0,Ye.jsx)(te.Button,{onClick:t,children:u("reset")})}),(0,Ye.jsxs)(te.ActionsBar,{list:f.map(({answer:h})=>({text:h.answer,type:"answer"})),primaryLabel:u("use"),onPrimary:h=>e(h.text),children:[f.map(({question:h,answer:g},m)=>(0,Ye.jsx)(te.List,{children:(0,Ye.jsx)(te.ListItem,{"data-testid":"knowledge-search-answer",index:m,description:g.answer,closeOnSelect:!0,onClick:()=>e(g.answer),onSourceClick:p=>v(p,h),sources:g.sources,styles:{title:l.question,description:l.answer},children:h})},`${g.answer}_${m}`)),d==="loading"&&(0,Ye.jsx)("p",{className:l.status,children:u("loading")}),d==="error"&&(0,Ye.jsx)("p",{className:l.status,children:u("error")}),(0,Ye.jsxs)("form",{className:l.form,onSubmit:y,children:[(0,Ye.jsx)("input",{ref:a,placeholder:u("anotherQuestion"),className:l.input,type:"text",value:o,onFocus:()=>{s(-1)},onChange:h=>{s(-1),i(h.target.value)}}),(0,Ye.jsx)("button",{type:"submit",className:l.submit,children:(0,Ye.jsx)(Jw,{})})]})]})]})},e1=cI;var dI={data:null,fetchState:"idle"},Ci=e=>e.profile.data,Xc=e=>e.profile.data?e.profile.data.uiConfig.widget.types.filter(t=>t.isActive):[],Ta=M("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)}),fI=H({name:"profile",initialState:dI,reducers:{},extraReducers:e=>{e.addCase(Ta.pending,t=>{t.fetchState="loading"}).addCase(Ta.rejected,t=>{t.fetchState="error"}).addCase(Ta.fulfilled,(t,n)=>{t.fetchState="done",t.data=n.payload})}}),t1=fI.reducer;var Ee=S(E()),pI=200,mI=5,gI=4,hI=e=>e.reduce((t,n)=>[...t,...n.list.map(r=>({...r,type:n.value}))],[]),n1=(e,t)=>!t||e.toLowerCase().includes(t.toLowerCase()),yI=()=>{let e=W(),t=Pt(),n=j(Ag),[r,o]=(0,Ze.useState)(!1),[i,s]=(0,Ze.useState)(""),a=A(D_),l=A(Ci),[u,c]=(0,Ze.useState)(null),[f,d]=(0,Ze.useState)([]),[y,v]=(0,Ze.useState)(),h=A(Tn),g=F("showSearch"),m=F("showEntitiesCommand"),p=F("showSummaryCommand"),x=F("showKnowledgeSearch"),_=F("showImageSearch"),C=F("searchTriggerKey"),w=A(Mw),b=A(F_),R=A(M_),P=I=>ln(b.filter($=>$.type===I.toUpperCase()),I),N=[{value:"PERSONAL",label:n("personalSuggestions"),list:P("PERSONAL"),lineClamp:!1,listOrientation:"vertical",shouldShow:!0},{value:"URL",label:n("urlSuggestions"),list:P("URL"),lineClamp:!1,listOrientation:"vertical",shouldShow:!0},{value:"STICKYMESSAGE",label:n("pinnedMessages"),list:P("STICKYMESSAGE"),lineClamp:!1,listOrientation:"vertical",shouldShow:!0},{value:"IMAGE",label:n("imageSuggestions"),lineClamp:!1,list:P("IMAGE"),listOrientation:"horizontal",shouldShow:_}].filter(I=>I.shouldShow),V=[{label:n("entitiesClipboard"),onClick:()=>e(Ue("entities")),shouldShow:m&&n1(n("entitiesClipboard"),i),experimental:!0},{label:n("summaryClipboard"),onClick:()=>e(Ue("summary")),shouldShow:p&&n1(n("summaryClipboard"),i),experimental:!0},{label:i?`${n("knowledgeSearch")}: ${i}`:n("knowledgeSearch"),onClick:()=>e(Ue("knowledgeSearch")),shouldShow:x,experimental:!0}].filter(I=>I.shouldShow),B=(w==null?void 0:w.map(I=>({value:I.code.toUpperCase(),label:`${I.name}s`,list:P(I.code.toUpperCase()),listOrientation:"vertical",lineClamp:!0})))||[],je=(0,Ze.useCallback)((0,r1.default)((I,$)=>{e(ro({query:I,type:$,tags:["search-overlay"]}))},pI),[]),an=hI([...B,...N]),Wt=(0,Ze.useCallback)((I,$)=>{if(!$)return;let Lt=[...N,...B].find(({value:Hn})=>Hn===$);Lt&&(e(Ue("edit")),c({...I,searchTerm:void 0}),d(Lt.list))},[e,u,B]),uo=(0,Ze.useCallback)((I,$)=>{switch($.type){case"IMAGE":t.send(Cg,{suggestion:$});break;default:t.send(kn,{text:I,suggestion:$})}e(st(!1))},[e]),Ni=I=>{Ea(I.text),e(it({name:"entity copied",data:{entity:I,type:"copy"}})),e(st(!1))},Pr=I=>{t.send(kn,{text:I,suggestion:{source:"knowledge-assist",text:I}}),e(it({name:"answer used",data:{originalText:I},options:{includeConversationData:!0}})),s(""),e(Ue("search")),e(Ei()),e(st(!1))},ja=I=>{Ea(I),e(st(!1))},Ha=I=>{t.send(kn,{text:I.text,suggestion:{source:"entity",text:I.text}}),e(st(!1))},Mi=u===null||f.indexOf(u)-1<0?void 0:()=>c(f[f.indexOf(u)-1]),Di=u===null||f.indexOf(u)===f.length-1?void 0:()=>c(f[f.indexOf(u)+1]);function ln(I,$){return I.slice(0,y?10:$.toLowerCase()==="image"?gI:mI)}function Fi(I,$,Lt){return $.reduce((Hn,un)=>Lt&&y===Lt?un.length+Hn:ln(un,Lt).length+Hn,I)}function Rr(I){return $=>{r?window.confirm(n("warning"))&&(I($),o(!1)):I($)}}return(0,Ze.useEffect)(()=>{i?je(i,y):e(zc())},[i,y]),(0,Ze.useEffect)(()=>{a==="search"&&e(Ei())},[a]),(0,Ze.useEffect)(()=>{h&&e(wa())},[h]),jw(C,()=>e(st(!0))),!g||!l?null:(0,Ee.jsxs)(te,{placeholder:n("searchPlaceholder"),typePlaceholder:n("typePlaceholder"),onChangeSearch:s,onChangeOpen:Rr(I=>e(st(I))),onChangeType:I=>v(I),onChangePage:Rr(I=>e(Ue(I))),selectedType:y,search:i,page:a,isOpen:R,types:[...B,...N],children:[(0,Ee.jsx)(te.Page,{id:"search",children:(0,Ee.jsxs)(te.ActionsBar,{list:[...V.map(I=>({text:I.label,type:"command"})),...an.map(I=>({text:I.text||I.url||I.message,type:I.type}))],primaryLabel:n("use"),secondaryLabel:n("preview"),onPrimary:({text:I},$)=>uo(I,an[$]),onSecondary:(I,$)=>{Wt(an[$-V.length],an[$-V.length].type)},children:[V.length>0&&(0,Ee.jsx)(te.List,{heading:n("commands"),children:V.map((I,$)=>(0,Ee.jsx)(te.ListItem,{index:Fi($,[],"commands"),closeOnSelect:!1,onClick:I.onClick,isExperimental:I.experimental,children:I.label},I.label))}),[...B,...N].map(({value:I,label:$,list:Lt,lineClamp:Hn,listOrientation:un},ji)=>(0,Ee.jsx)(te.List,{heading:$,orientation:un==="horizontal"?"horizontal":"vertical",children:ln(Lt,I).map((ct,dt)=>(0,Ee.jsx)(te.ListItem,{index:Fi(V.length+dt,[...B,...N].slice(0,ji).map(({list:Ir})=>Ir),I),closeOnSelect:!1,lineClamp:Hn,onClick:()=>uo(ct.text,ct),description:I!=="IMAGE"?ct.title&&ct.text:void 0,children:I==="IMAGE"?(0,Ee.jsx)(te.Image,{title:ct.title||ct.text,src:ct.image}):ct.title||ct.text},`${ct.id}-${ct.text}`))},I))]})}),(0,Ee.jsx)(te.Page,{id:"edit",onDismiss:Rr(()=>{e(Ue("search")),c(null)}),children:u&&(0,Ee.jsx)(Wc,{suggestion:u,onTouched:o,onDismiss:()=>{o(!1),e(Ue("search")),c(null),d([])},onNext:Di,onPrevious:Mi,onUse:I=>{e(Ue("search")),uo(I,u),e(st(!1)),d([]),c(null)}})}),(0,Ee.jsx)(te.Page,{id:"entities",title:n("entitiesTitle"),isExperimental:!0,onDismiss:Rr(()=>{e(Ue("search"))}),children:(0,Ee.jsx)(zw,{onUse:Ha,onCopy:Ni})}),(0,Ee.jsx)(te.Page,{id:"summary",title:n("summaryTitle"),isExperimental:!0,onDismiss:Rr(()=>{e(Ue("search"))}),children:(0,Ee.jsx)(Gw,{onCopy:ja})}),(0,Ee.jsx)(te.Page,{id:"knowledgeSearch",title:n("knowledgeSearch"),isExperimental:!0,onDismiss:Rr(()=>{e(Ei()),e(Ue("search"))}),children:(0,Ee.jsx)(e1,{promptInstruction:l.knowledgeSearchPromptInstruction,question:i,onUse:Pr,onResetQuestion:()=>{e(Ei()),s("")}})})]})},o1=yI;var bi=S(E()),vI=()=>{let e=F("showSearch"),t=F("isEmbedded");return(0,bi.jsxs)(i1.Fragment,{children:[e&&(0,bi.jsx)(o1,{}),(0,bi.jsx)(Cw,{}),t&&(0,bi.jsx)(Iw,{})]})},s1=vI;var ka=S(E()),SI=({children:e})=>{let n=F("locale").replace("-","");return(0,ka.jsx)(Fd.Provider,{value:n,children:e})},xI=({store:e,customStyles:t={},children:n})=>(0,ka.jsx)(jm,{store:e,children:(0,ka.jsx)(SI,{children:(0,ka.jsx)(Bi.Provider,{value:t,children:n})})}),Pa=xI;var Zc=S(X()),Pi=S(O());var a1=S(O());function l1(e,t){let[n,r]=(0,a1.useState)(()=>{if(typeof window>"u")return t;try{let i=window.localStorage.getItem(e);return i?JSON.parse(i):t}catch(i){return U.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){U.error(s)}}]}function Qc(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 c1=S(X()),In=S(O());var Mg={};Ce(Mg,{enUS:()=>_I,nlNL:()=>wI});var _I={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"}]}]},wI={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 u1={root:"_root_1vfca_1",anchor:"_anchor_1vfca_6",anchorButton:"_anchorButton_1vfca_11"};var Cr=S(E()),Dg=(e,t,n)=>r=>(0,Cr.jsx)("button",{className:e.anchorButton,type:"button",value:t,onClick:n,children:r},t),EI=({className:e,loginUrl:t,isEmbedded:n,onSnooze:r})=>{let o=j(Mg),i=Pt(),s=k("Login",u1),a=F("productName"),l=(0,In.useCallback)(h=>{h.preventDefault(),r&&r(parseInt(h.target.value,10))},[]),u=(0,In.useCallback)(h=>{h.preventDefault(),i.send(_i,!0)},[t]),c=(0,In.useMemo)(()=>h=>(0,Cr.jsx)("a",{href:t,className:s.anchor,target:"_blank",rel:"noreferrer",children:h},"login"),[t]),f=(0,In.useCallback)(h=>(0,Cr.jsx)("button",{type:"button",className:s.anchorButton,onClick:u,children:h},"prompt"),[u]),{min:d,hour:y,day:v}=(0,In.useMemo)(()=>({min:Dg(s,60*10,l),hour:Dg(s,60*60,l),day:Dg(s,60*60*12,l)}),[]);return(0,Cr.jsxs)("div",{className:(0,c1.default)(e,s.root),children:[o("loginPlease",{login:n?f:c,productName:a}),r&&(0,Cr.jsxs)(In.Fragment,{children:[(0,Cr.jsx)("br",{}),o("snooze",{min:d,hour:y,day:v})]})]})},Yc=EI;var d1={root:"_root_1g8fi_1",text:"_text_1g8fi_19"};var Ra=S(E()),CI=({title:e})=>{let t=k("SearchTrigger",d1),n=W();return(0,Ra.jsxs)("button",{type:"button",className:t.root,onClick:()=>n(st(!0)),children:[(0,Ra.jsx)(gi,{}),(0,Ra.jsx)("span",{className:t.text,children:e})]})},f1=CI;var S1=S(O());var ki=S(O());var p1=S(O());function m1(e,t,n){(0,p1.useEffect)(()=>{let r=e.current;return r?(r.addEventListener(t,n),()=>{r.removeEventListener(t,n)}):()=>{}},[e,t,n])}var bI=/[.*+?^${}()|[\]\\]/g,TI=/[^0-9A-Za-zÀ-ÖØ-öø-ÿ](?=[0-9A-Za-zÀ-ÖØ-öø-ÿ]*$)/;function kI(e){return e.replace(bI,"\\$&")}function PI(e,t){let n=e.split("").findIndex((r,o)=>r!==t[o]);return n>-1?n:Math.min(e.length,t.length)}function Fg(e){return e.search(TI)}function g1(e,t=[]){let n=e;return t.forEach(r=>{if(!r)return;let o=new RegExp(`\\b(${kI(r)})\\b`,"gi");n=n.replace(o,"<strong>$1</strong>")}),n}function h1(e){return e.replace(ho,'<mark data-type="placeholder">$1</mark>')}function Ti(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function RI(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 jg(e,t,n={}){if(t){let r=PI(t.toLowerCase(),e.toLowerCase()),o=Ti(e.substring(r,e.length));if(n.stripAgentPart){let l=e.substring(0,r),u=Fg(l);return`<span style="opacity: 0.5">${l.substring(u+1)}</span>${o}`}let s=t.split(vy).length>3||t.length>30?RI(t.trim(),r):0;return`${`${s>0?"\u2026":""}${Ti(e.substring(s,r))}`}<strong>${o}</strong>`}return e}var y1={badge:"_badge_8rv7b_1",formattedText:"_formattedText_8rv7b_5"};var Hg=S(E()),LI=["search","personal-collection-search","search-autocomplete"];function AI(e,t,n,r={}){let o="";return LI.includes(t)?o=g1(jg(e,n,{stripAgentPart:!0}),r.searchKeywords??[n]):o=jg(e,n,r),r.placeholders===!0&&(o=h1(o)),o}var OI=()=>{},NI=({index:e,selected:t,suggestion:n})=>{let r=F("inlineSuggestions"),o=A(oi),i=W(),s=k("TextSuggestion",y1),a=(0,ki.useRef)(null);(0,ki.useEffect)(()=>{let u=setTimeout(()=>{i(Gx({text:n.text,suggestion:n}))},500);return()=>{clearTimeout(u)}},[n]),m1(a,"click",()=>{i(Cc(e)),i(Ft({suggestion:n,text:n.text,eventMetrics:{inputType:"mouse"},replace:"until-selection-end"}))});let l=(0,ki.useMemo)(()=>AI(n.text,n.source,o,{stripAgentPart:r,placeholders:!0,searchKeywords:n.searchKeywords}),[r,n.text,n.source,o,n.searchKeywords]);return n.source==="gpt"?null:(0,Hg.jsx)(oe,{ref:a,as:"button",selected:t,onClick:OI,children:(0,Hg.jsx)(ai,{containerTagName:"div",noWrap:!1,tagName:"span",className:s.formattedText,content:l})})},v1=NI;var Bg=S(E()),MI=({suggestions:e,selectedIndex:t})=>(0,Bg.jsx)(S1.Fragment,{children:e.slice().map((n,r)=>(0,Bg.jsx)(v1,{index:r,selected:r===t,suggestion:n},`${n.text}-${n.source}`)).reverse()}),x1=MI;var Ug={};Ce(Ug,{enUS:()=>DI,nlNL:()=>FI});var DI={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"}]},FI={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 _1={root:"_root_4kcme_1",isInline:"_isInline_4kcme_14",toggleButton:"_toggleButton_4kcme_18",toggleButtonWrapper:"_toggleButtonWrapper_4kcme_22",toggleButtonWrapperHidden:"_toggleButtonWrapperHidden_4kcme_29",isCollapsed:"_isCollapsed_4kcme_33",collapsible:"_collapsible_4kcme_33",hints:"_hints_4kcme_41",hintsHidden:"_hintsHidden_4kcme_48",triggers:"_triggers_4kcme_53",triggersRight:"_triggersRight_4kcme_68"};var ue=S(E()),jI=({inline:e=!1,textSuggestions:t,selectedIndex:n})=>{let r=k("SuggestionsOverlay",_1),o=j(Ug),i=F("inlineSuggestions"),s=A(Qc),a=Vx(),l=W(),u=(0,Pi.useRef)(null),c=F("searchTriggerKey"),f=F("productName"),d=A(lw),y=A(Tn),v=A(fc),[h,g]=(0,Pi.useState)(null),m=F("showSearch"),p=F("showTextSuggestions"),x=F("adminUrl"),_=F("isEmbedded"),[C,w]=l1("dd-snooze-until-ms",0),b=d||C>Date.now(),R=t.filter(V=>V.source!=="gpt").length,P=()=>{b&&w(0),l(dw(!b))},N=V=>{let B=Date.now()+V*1e3;w(B),U.info(`Snooze until: ${new Date(B)}`),l(Si({collapse:!0}))};return(0,Pi.useEffect)(()=>{R===0&&g(null)},[t,R]),di(()=>{l(Si({collapse:!0,skipWhenInputFocus:!0}))}),i!==e||y===null||v===!1?null:y===!1?(0,ue.jsxs)("div",{ref:u,className:(0,Zc.default)(r.root,{[r.isCollapsed]:b,[r.isInline]:e}),"data-inline":e,children:[!b&&(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)(Nr,{className:r.toggleButton,title:o("collapse"),onClick:P,isCollapsed:!1})})]}),(0,ue.jsx)("div",{className:r.toggleButtonWrapper,children:(0,ue.jsx)(Nr,{className:r.toggleButton,title:o("open",{productName:f}),onClick:P,isCollapsed:!0})}),(0,ue.jsx)("div",{className:r.collapsible,children:(0,ue.jsx)(Yc,{loginUrl:x,isEmbedded:_,onSnooze:N})})]}):!a||!s?null:(0,ue.jsxs)("div",{ref:u,className:(0,Zc.default)(r.root,{[r.isCollapsed]:b,[r.isInline]:e}),"data-inline":e,children:[!b&&(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:()=>g(o(Bc()?"searchHintMac":"searchHintWindows",{searchTriggerKey:c.toUpperCase()})),onMouseLeave:()=>g(null),children:(0,ue.jsx)(f1,{title:o("search")})})}),(0,ue.jsxs)("div",{className:r.triggersRight,onFocus:()=>{},children:[(0,ue.jsx)("div",{className:(0,Zc.default)(!h&&r.hintsHidden,r.hints),children:h}),(0,ue.jsx)(Nr,{className:r.toggleButton,title:o("collapse"),onClick:P,isCollapsed:!1})]})]}),(0,ue.jsx)("div",{className:r.toggleButtonWrapper,children:(0,ue.jsx)(Nr,{className:r.toggleButton,title:o("open",{productName:f}),onClick:P,isCollapsed:!0})}),R>0&&p&&(0,ue.jsx)("div",{className:r.collapsible,onFocus:()=>{},children:(0,ue.jsx)($t,{children:(0,ue.jsx)(x1,{suggestions:t,selectedIndex:n})})})]})},HI=({input:e})=>({selectedIndex:e.selectedSuggestionIndex,textSuggestions:e.textSuggestions}),Jc=Yr(HI)(jI);var fd=S(X());var Nn=S(O());var w1=S(O()),BI=["div","span","mark","strong","b","i","u","em"];function zg(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(BI.includes(o)){let s=Array.isArray(r.props.children)?r.props.children:[r.props.children];return[...e.slice(0,e.length-1),(0,w1.cloneElement)(r,{children:zg(s,t,n+1)})]}return[...e,...t]}function Ln(e){return e.tagName.toLowerCase()==="textarea"}var E1={root:"_root_1l8n5_1",container:"_container_1l8n5_4",agentText:"_agentText_1l8n5_7",tabText:"_tabText_1l8n5_8",hint:"_hint_1l8n5_8",matchSelection:"_matchSelection_1l8n5_12",focus:"_focus_1l8n5_18",resetIndent:"_resetIndent_1l8n5_22",matchKeyword:"_matchKeyword_1l8n5_26",matchPlaceholder:"_matchPlaceholder_1l8n5_27",hover:"_hover_1l8n5_33",hintText:"_hintText_1l8n5_66",popover:"_popover_1l8n5_74",popoverRoot:"_popoverRoot_1l8n5_79",popoverContentContainer:"_popoverContentContainer_1l8n5_83",popoverContent:"_popoverContent_1l8n5_83",selectionOptions:"_selectionOptions_1l8n5_109",selectionOptionsIsHidden:"_selectionOptionsIsHidden_1l8n5_114",selectionOptionsButton:"_selectionOptionsButton_1l8n5_118",caret:"_caret_1l8n5_134",popoverSuggestionsRoot:"_popoverSuggestionsRoot_1l8n5_138",suggestionsOverlayInputStyles:"_suggestionsOverlayInputStyles_1l8n5_143"};var rd=S(O());var Kg=S(X()),Rt=S(O());var ed=S(O()),UI=["bottom","height","left","right","top","width"],zI=(e={},t={})=>UI.some(n=>e[n]!==t[n]),An=new Map,C1,b1=()=>{let e=[],t=[];An.forEach((n,r)=>{if(r instanceof Element&&!r.isConnected){t.push(r);return}let o=r.getBoundingClientRect();zI(o,n.rect)&&(n.rect=o,e.push(n))}),t.forEach(n=>{An.delete(n)}),e.forEach(n=>{n.callbacks.forEach(r=>r(n.rect))}),C1=window.requestAnimationFrame(b1)};function VI(e,t){return{observe(){let n=An.size===0;if(An.has(e)){let r=An.get(e);r.callbacks.push(t),r.rect&&t(r.rect)}else An.set(e,{rect:void 0,hasRectChanged:!1,callbacks:[t]});n&&b1()},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(C1)}}}}function Vg(e){let[t,n]=(0,ed.useState)(null);return(0,ed.useLayoutEffect)(()=>{if(!e.current)return;let r=VI(e.current,o=>{n(o)});return r.observe(),()=>{r.unobserve()}},[e]),t}var Ri=S(O()),k1=S(ku());var T1={root:"_root_1jq08_1"};var P1=({children:e})=>{let[t,n]=(0,Ri.useState)(null),r=(0,Ri.useContext)(Bi);return(0,Ri.useLayoutEffect)(()=>{let o=document.createElement("div");return to(o),o.classList.add(T1.root),r!=null&&r.rootNode&&o.classList.add(r==null?void 0:r.rootNode),document.body.appendChild(o),n(o),()=>{o.isConnected&&document.body.removeChild(o)}},[]),t?(0,k1.createPortal)(e,t):null};var on={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 td=S(E()),Ii=(e=!1)=>{let[t,n]=(0,Rt.useState)(e),r=(0,Rt.useCallback)(()=>n(!0),[]),o=(0,Rt.useCallback)(()=>n(!1),[]),i=(0,Rt.useCallback)(()=>n(a=>!a),[]),s=(0,Rt.useRef)(null);return{opened:t,open:r,close:o,toggle:i,triggerRef:s}};function Wg(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 Li=({className:e,triggerRef:t,boundaryRef:n=(0,Rt.createRef)(),position:r="above",align:o="center",children:i,toStyle:s=Wg,...a})=>{let l=Vg(t),u=Vg(n),c=(0,Rt.useMemo)(()=>s(l,u,0),[l,u]);return(0,td.jsx)(P1,{children:(0,td.jsx)("div",{className:(0,Kg.default)(on.ref,{[on.positionAbove]:r==="above",[on.positionBelow]:r==="below",[on.positionLeft]:r==="left",[on.positionRight]:r==="right",[on.alignStart]:o==="start",[on.alignCenter]:o==="center",[on.alignEnd]:o==="end"}),style:c,...a,role:"dialog",children:(0,td.jsx)("div",{className:(0,Kg.default)(e,on.root),children:i})})})};var br=S(E()),KI=({inputStyle:e,inputElement:t})=>{let n=k("TabCompletion",bt),r=Ii(document.activeElement===t);return di(()=>r.close()),(0,rd.useEffect)(()=>{let o=()=>r.open();return t.addEventListener("focus",o),()=>{t.removeEventListener("focus",o)}},[]),(0,br.jsxs)(rd.Fragment,{children:[(0,br.jsx)("mark",{className:bt.caret,ref:r.triggerRef}),r.opened&&(0,br.jsx)(Li,{className:n.popoverSuggestionsRoot,triggerRef:r.triggerRef,position:"above",align:"start",children:(0,br.jsx)("div",{style:e,className:n.suggestionsOverlayInputStyles,children:(0,br.jsx)(Jc,{inline:!0})})})]})},nd=class extends Ht{charCounter=0;charLength=0;found=!1;onlyAtEnd=!1;props;onBeforeParse(t,n){var r;return this.props=n,this.charCounter=0,this.onlyAtEnd=n.inlineSuggestionsOnlyAtEnd??!1,this.charLength=(Ln(n.inputElement)?n.inputElement.value.length:(r=n.inputElement.textContent)==null?void 0:r.length)??0,this.found=!1,t}match(t){if(this.found||!this.props||this.props.selection===null)return null;let[n,r]=this.props.selection;if(n!==r||this.onlyAtEnd&&n!==this.charLength)return null;let o=n,s=o>=this.charCounter&&o<=this.charCounter+t.length?{index:Fg(t.slice(0,o))+1-this.charCounter,length:0,match:"",valid:!0}:null;return s&&(this.found=!0),this.charCounter+=t.length,s??null}replaceWith(t,n){return(0,br.jsx)(KI,{inputStyle:n.inputStyle,inputElement:n.inputElement},"caret")}asTag(){return"mark"}};var A1=S(X());var ld=S(O());function R1(e){return e.replace(/[.*+^${}()|[\]\\]/g,"\\$&")}function od(e){return t=>{e.forEach(n=>{typeof n=="function"?n(t):n!=null&&(n.current=t)})}}function I1(e){return e!=null}var L1=S(X()),id=S(O());var $g=S(E()),sd=(0,id.forwardRef)(({className:e,children:t,...n},r)=>{let o=(0,id.useRef)(null),i=k("TabCompletion",bt);return(0,$g.jsx)("div",{ref:od([o,r]),className:(0,L1.default)(e,i.popoverContentContainer),...n,children:(0,$g.jsx)("div",{className:i.popoverContent,children:t})})});var Tr=S(E()),WI=e=>t=>{let n=Wg(t);return"top"in n&&(n.width=e.width-(t.left-e.left)-10),n},$I=({inputElement:e,boundaryRef:t,inputStyle:n,children:r,suggestion:o})=>{let i=k("TabCompletion",bt),s=Ii(),a=(0,ld.useMemo)(()=>WI(e.getBoundingClientRect()),[e]),[l,u]=Oc(e);return(0,ld.useEffect)(()=>{u?s.open():s.close()},[u]),(0,Tr.jsxs)("span",{children:[(0,Tr.jsx)("mark",{ref:od([l,s.triggerRef]),className:(0,A1.default)(i.matchKeyword,{[i.hover]:u}),"aria-haspopup":"dialog","aria-expanded":s.opened?"true":"false",children:r}),s.opened&&(0,Tr.jsx)(Li,{className:i.popover,triggerRef:s.triggerRef,boundaryRef:t,position:"below",align:"start",toStyle:a,children:(0,Tr.jsx)(sd,{style:n,children:(0,Tr.jsx)("div",{className:i.hintText,children:o})})})]})},ad=class extends Ht{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${R1(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(I1);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,Tr.jsx)($I,{inputElement:n.inputElement,suggestion:n.suggestion,inputStyle:n.inputStyle,boundaryRef:n.boundaryRef,children:t},`keyword_${n.matchString}_${n.key}`)}asTag(){return"mark"}};var cd=S(X());var Ve=S(O());var qg=S(E()),O1=()=>(0,qg.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,qg.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 kr=S(O());var M1=S(Rg());var N1={root:"_root_1muu8_1",content:"_content_1muu8_7"};function ud(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 Gg(e){return e.replace("https://www.","").replace("https://","")}var It=S(E()),qI=3,GI=e=>({image:e.image||"",text:e.text,id:e.id,title:e.title}),XI=({onSelectLink:e,onDismiss:t,placeholder:n,visitUrlText:r,linkCount:o=qI})=>{let i=k("LinkSearch",N1),[s,a]=(0,kr.useState)(""),l=W(),u=A(X_("url")),c=A(j_("URL",GI)),[f,d]=(0,kr.useState)(c.length-1),y=F("fallbackImage"),v=p=>{let x=p.target;a(x.value)},h=(p,x)=>{p.stopPropagation(),p.preventDefault(),window.open(x,"_blank")},g=p=>{var C;let x=f-1<0?c.length-1:f-1,_=f+1===c.length?0:f+1;p.code==="Escape"&&(a(""),t()),p.code==="ArrowUp"&&d(x),p.code==="ArrowDown"&&d(_),p.code==="Enter"&&e(((C=c[f])==null?void 0:C.text)||s)},m=(0,kr.useCallback)((0,M1.default)(p=>{l(ro({query:p,type:"URL",tags:["link-search"]}))},300),[]);return(0,kr.useEffect)(()=>{s&&m(s)},[s]),(0,kr.useEffect)(()=>()=>{l(zc())},[]),(0,It.jsxs)("div",{className:i.root,children:[(0,It.jsx)($t,{withDivider:!0,children:(s?c:u).slice(0,o).map((p,x)=>(0,It.jsx)(oe,{selected:f===x,onClick:()=>e(p.text),"data-testid":"linksearch-suggestion",children:(0,It.jsxs)(me,{children:[(0,It.jsx)(me.Image,{src:ud(p,"small",y||void 0),title:p.title||p.text}),(0,It.jsxs)(me.Content,{className:i.content,cropText:!0,children:[(0,It.jsx)(me.Title,{children:p.title||Gg(p.text)}),p.title&&Gg(p.text)]}),(0,It.jsx)(oe.Actions,{children:(0,It.jsx)(oe.ActionButton,{label:r,onClick:_=>h(_,p.text)})})]})},p.text))}),(0,It.jsx)(_a,{value:s,onChange:v,autoFocus:!0,placeholder:n,onKeyUp:g})]})},D1=XI;var Xg={};Ce(Xg,{enUS:()=>QI,nlNL:()=>YI});var QI={insertLink:[{type:0,value:"Insert link"}],linkInputPlaceholder:[{type:0,value:"Search, type or paste link"}],visitUrl:[{type:0,value:"Visit"}]},YI={insertLink:[{type:0,value:"Voeg link toe"}],linkInputPlaceholder:[{type:0,value:"Zoek, typ of plak link"}],visitUrl:[{type:0,value:"Bekijk"}]};var ze=S(E()),ZI=(0,Ve.forwardRef)((e,t)=>{let n=k("TabCompletion",bt);return(0,ze.jsx)("mark",{ref:t,className:(0,cd.default)(n.matchSelection)},"selection-start")}),JI=({startRef:e,boundaryRef:t,inputStyle:n,inputElement:r,children:o})=>{let i=j(Xg),s=k("TabCompletion",bt),a=(0,Ve.useRef)(null),l=(0,Ve.useRef)(null),[u,c]=(0,Ve.useState)(null),f=W(),d=Ii(document.activeElement===r),[y]=(0,Ve.useState)(()=>document.createRange());d.triggerRef.current=y,(0,Ve.useEffect)(()=>()=>y.detach(),[]),(0,Ve.useEffect)(()=>{let h=e.current,g=a.current;!h||!g||(y.setStart(h,0),y.setEnd(g,0))},[e.current,a.current]),di(()=>{d.close()});let v=(0,Ve.useCallback)(h=>{let g=y.toString(),m=/^http(s?):\/\//.test(h)?h:`https://${h}`;f(Sc({text:`[${g}](${m})`,replace:"selection"}))},[]);return(0,ze.jsxs)("span",{children:[(0,ze.jsx)("mark",{ref:a,className:(0,cd.default)(s.matchSelection),"aria-haspopup":"dialog","aria-expanded":d.opened?"true":"false",children:o}),d.opened&&(0,ze.jsx)(Li,{className:s.popoverRoot,triggerRef:d.triggerRef,boundaryRef:t,position:"above",align:"start",children:(0,ze.jsxs)(sd,{style:n,ref:l,children:[(0,ze.jsx)("div",{className:(0,cd.default)(s.selectionOptions,{[s.selectionOptionsIsHidden]:u!==null}),children:(0,ze.jsxs)("button",{type:"button",tabIndex:u===null?-1:void 0,className:s.selectionOptionsButton,onClick:()=>c("insertLink"),children:[(0,ze.jsx)(O1,{}),(0,ze.jsx)("span",{children:"\xA0"}),(0,ze.jsx)("span",{children:i("insertLink")})]})}),u==="insertLink"&&(0,ze.jsx)(D1,{placeholder:i("linkInputPlaceholder"),visitUrlText:i("visitUrl"),onSelectLink:v,onDismiss:()=>{c(null),d.close()}})]})})]},"selection-end")},dd=class extends Ht{charCount=0;foundIndex=0;startRef=null;props;onBeforeParse(t,n){return this.props=n,this.charCount=0,this.startRef=(0,Ve.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,ze.jsx)(ZI,{ref:this.startRef}):(0,ze.jsx)(JI,{inputElement:n.inputElement,startRef:this.startRef,boundaryRef:n.boundaryRef,inputStyle:n.inputStyle})}asTag(){return"mark"}};var On=S(E()),eL=({enabled:e,content:t,tabText:n,showTabHint:r,showTabCompletion:o,showStyleSuggestions:i,keywordMatches:s,inputElement:a,source:l})=>{let u=k("TabCompletion",E1),c=F("insertLink"),f=F("showMidSentenceSuggestions"),d=F("inlineSuggestions"),y=Mc(a),v=(0,Nn.useRef)(null);(0,Nn.useEffect)(()=>{Ln(a)&&y&&Dc(a,y)},[y]);let h=(0,Nn.useCallback)(p=>{if(!o||!n)return p;let x=[(0,On.jsx)("span",{className:u.resetIndent,children:"\u200B"},"u200B"),(0,On.jsx)("span",{className:(0,fd.default)(u.tabText,u.resetIndent),"data-source":l,children:n},"tabText")];return r&&x.push((0,On.jsx)("span",{className:(0,fd.default)(u.hint,u.resetIndent),children:(0,On.jsx)(dl,{keyCode:"tab"},"tabHint")})),zg(p,x)},[o,n,r]),g=(0,Nn.useMemo)(()=>{let p=[];return d&&p.push(new nd("inline")),c&&p.push(new dd("selection")),p.push(new ui("placeholders")),i&&p.push(new ad("keywords")),p},[d,c,i]),m=(0,Nn.useMemo)(()=>{let p=window.getComputedStyle(a);return{"--dd-color":p.color,"--dd-font-size":p.fontSize,"--dd-font-family":p.fontFamily,"--dd-font-variant":p.fontVariant}},[]);return e?(0,On.jsxs)("div",{ref:p=>{p!=null&&p.parentElement&&(v.current=p==null?void 0:p.parentElement)},className:u.root,style:m,children:[(0,On.jsx)(ai,{tagName:"span",containerTagName:"div",className:(0,fd.default)(u.container,u.agentText),disableLineBreaks:Ln(a),content:t||"\u200B",onAfterParse:h,matchers:g,selection:y,keywordMatches:s,inputElement:a,inputStyle:m,boundaryRef:v,inlineSuggestionsOnlyAtEnd:!f}),(0,On.jsx)("br",{})]}):null},tL=({input:e,ui:t,settings:n,styleSuggestions:r,conversation:o})=>{var h;let{tabCompletionSuggestion:i}=e,s=(i==null?void 0:i.text)||"",a=(i==null?void 0:i.source)||"",l=e.html??Ti(e.text),u=s.indexOf(e.text)===0?s.slice(e.text.length):"",{showTabHint:c}=t,{isSupported:f}=o,{showTabCompletion:d,visible:y,showStyleSuggestions:v}=n;return{showTabHint:c,showStyleSuggestions:v,showTabCompletion:d,content:l,tabText:u,source:a,keywordMatches:((h=r.list)==null?void 0:h.keywordMatches)??[],enabled:y&&f!==!1}},F1=Yr(tL)(eL);var bE=S(X()),TE=S(O());var j1={list:[],fetchState:"idle",isInitialRequest:null},B1=e=>e.autoflows.list||[],H1=e=>t=>{var n;return(n=t.list)==null?void 0:n.find(r=>r.triggerPayload===e)},Mn=M("autoflows/getAll",async(e,t)=>{let{deepdeskBrokerAPI:n}=t.extra;if(!n)throw new Error("Deepdesk Broker not initialized");return n.getAutoflows(e)}),Qg=M("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(Mn(e.platformSessionId))}),Yg=M("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(Mn(e.platformSessionId))}),nL=H({name:"autoflows",initialState:j1,reducers:{},extraReducers:e=>{e.addCase(Qg.pending,(t,n)=>{let r=H1(n.meta.arg.triggerPayload)(t);r.state="Started",r.isBusy=!0}),e.addCase(Yg.pending,(t,n)=>{let r=H1(n.meta.arg.triggerPayload)(t);r.state="Aborted",r.isBusy=!0}),e.addCase(Mn.pending,t=>{t.isInitialRequest=t.isInitialRequest===null,t.fetchState="loading"}),e.addCase(Mn.rejected,t=>{t.fetchState="error"}),e.addCase(Mn.fulfilled,(t,n)=>{t.list=n.payload,t.fetchState="done"}),e.addCase(J,()=>j1)}}),U1=M("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(Mn(e))}),o.on("sessionCompleted",()=>{n(Mn(e))})}),z1=M("autoflows/closeStream",(e,t)=>{let{deepdeskBrokerAPI:n}=t.extra;if(!n)throw new Error("Deepdesk Broker not initialized");n.closeStream(e)}),V1=nL.reducer;var K1={list:[],fetchState:"idle",isInitialRequest:null,sentSuggestions:[],errorSuggestions:[],answeredSuggestions:[]},W1=e=>e.customMessages.list,$1=e=>t=>!!t.customMessages.sentSuggestions.find(n=>n===e),q1=e=>t=>!!t.customMessages.answeredSuggestions.find(n=>n===e),G1=e=>t=>!!t.customMessages.errorSuggestions.find(n=>n===e),Ia=M("customMessages/getAll",async(e,t)=>{let{deepdeskBrokerAPI:n}=t.extra;if(!n)throw new Error("Deepdesk Broker not initialized");return n.getCustomMessages(e)}),pd=M("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)}),md=M("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)}),X1=H({name:"customMessages",initialState:K1,reducers:{onCustomMessage(e,t){Array.isArray(t.payload)?e.list=t.payload:e.list=[t.payload]}},extraReducers:e=>{e.addCase(Ia.pending,t=>{t.isInitialRequest=t.isInitialRequest===null,t.fetchState="loading"}).addCase(Ia.rejected,t=>{t.fetchState="error"}).addCase(Ia.fulfilled,(t,n)=>{t.fetchState="done",t.list=n.payload||[]}).addCase(pd.pending,(t,n)=>{t.sentSuggestions.push(n.meta.arg.suggestion.text),t.errorSuggestions=t.errorSuggestions.filter(r=>n.meta.arg.suggestion.text!==r)}).addCase(pd.rejected,(t,n)=>{let r=t.sentSuggestions.indexOf(n.meta.arg.suggestion.text);t.errorSuggestions.push(...t.sentSuggestions.splice(r,1))}).addCase(md.pending,(t,n)=>{t.sentSuggestions.push(n.meta.arg.suggestion.text),t.answeredSuggestions.push(n.meta.arg.suggestion.text)}).addCase(md.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(J,()=>K1)}}),Q1=M("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(X1.actions.onCustomMessage(i))})}),Y1=M("customMessages/closeStream",(e,t)=>{let{deepdeskBrokerAPI:n}=t.extra;if(!n)throw new Error("Deepdesk Broker not initialized");n.closeStream(e)}),Z1=X1.reducer;var rL={jwt:null,accountUrl:null,interval:null},J1=e=>t=>{let{exchangeToken:{jwt:n,accountUrl:r}}=t;return n&&r?`${r}/apis/admin/session/jwt/?jwt=${n}&redirect=${e}`:null},Zg=M("exchangeToken/getTemporaryExchangeToken",async(e,t)=>{let{deepdeskAPI:n}=t.extra,r=await n.getTemporaryExchangeToken();return{accountUrl:n.client.baseUrl,jwt:r}}),Jg=M("exchangeToken/pollExchangeToken",(e={},t)=>{let{interval:n=1e3*60*30}=e,{dispatch:r}=t;return r(Zg()),setInterval(()=>r(Zg()),n)}),eE=H({name:"exchangeToken",initialState:rL,reducers:{stopPollExchangeToken(e){e.interval&&clearInterval(e.interval),e.interval=null}},extraReducers:e=>{e.addCase(Zg.fulfilled,(t,n)=>{t.jwt=n.payload.jwt,t.accountUrl=n.payload.accountUrl}),e.addCase(Jg.fulfilled,(t,n)=>{t.interval=n.payload})}}),{stopPollExchangeToken:tE}=eE.actions,nE=eE.reducer;function rE(e){let{customMessages:t,autoflows:n}=e;return n.fetchState==="loading"&&n.isInitialRequest===!0||t.fetchState==="loading"&&t.isInitialRequest===!0}var fE=S(O());var uE=S(X()),cE=S(O());var iE=S(X());var oE={root:"_root_838fd_1"};var aE=S(E()),oL=({className:e,children:t})=>{let n=k("Unicode",oE);return(0,aE.jsx)("span",{className:(0,iE.default)(e,n.root),children:t})},sE=oL;var lE={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 eh={};Ce(eh,{enUS:()=>iL,nlNL:()=>sL});var iL={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"}]},sL={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 at=S(E()),lL=({disabled:e,state:t,displayName:n,description:r,onStartAutoflow:o,onStopAutoflow:i})=>{let s=k("Autoflow",lE),a=j(eh),l=t==="Started"?"stop":"start",u=l==="start"?"\u25B6":l==="stop"?"\u25FC":"";return(0,at.jsxs)(oe,{className:(0,uE.default)(s.root,{[s.isDisabled]:e,[s.isCompleted]:t==="Completed",[s.isAborted]:t==="Aborted",[s.isStarted]:t==="Started"}),children:[(0,at.jsx)(me,{children:(0,at.jsxs)(me.Content,{children:[(0,at.jsxs)(me.Title,{children:[t&&(0,at.jsx)("span",{className:s.stateBadge,children:a(t)}),n]}),(0,at.jsx)("span",{children:r})]})}),(0,at.jsx)(oe.Actions,{fixed:t==="Started",children:(0,at.jsx)(oe.ActionButton,{primary:!0,className:l==="start"?s.buttonStart:s.buttonStop,onClick:t==="Started"?i:o,disabled:e,label:(0,at.jsxs)(cE.Fragment,{children:[(0,at.jsx)(sE,{children:u})," ",(0,at.jsx)("span",{children:a(l)})]})})})]})},dE=lL;var th=S(E()),uL=(e,t)=>{let n=t.filter(r=>r.state==="Started");return n.length>0?n.indexOf(e)===-1:!1},cL=({autoflows:e,onStartAutoflow:t,onStopAutoflow:n,platformSessionId:r})=>(0,th.jsx)(fE.Fragment,{children:e.map(o=>(0,th.jsx)(dE,{displayName:o.displayName,description:o.description,disabled:o.isBusy||uL(o,e),state:o.state,onStartAutoflow:()=>t({platformSessionId:r,triggerPayload:o.triggerPayload}),onStopAutoflow:()=>n({platformSessionId:r,triggerPayload:o.triggerPayload})},o.displayName))}),dL=({autoflows:e,conversation:t})=>{var n;return{autoflows:e.list,platformSessionId:(n=t.current)==null?void 0:n.sessionId}},fL={onStartAutoflow:Qg,onStopAutoflow:Yg},pE=Yr(dL,fL)(cL);var gd=S(O());var oh=S(X());var nh=S(E()),rh=()=>(0,nh.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 512 512",xmlns:"http://www.w3.org/2000/svg",children:(0,nh.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 mE={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 sn=S(E()),pL=({entities:e})=>{let t=k("EntitiesWidgetList",mE),[n,r]=(0,gd.useState)(void 0),o=W(),i=()=>{r(void 0)},s=a=>{e&&(r(e.indexOf(a)),Ea(a.text),o(it({name:"entity copied",data:{entity:a,type:"copy"}})))};return(0,gd.useEffect)(()=>{let a=setTimeout(i,500);return()=>{clearTimeout(a)}},[n]),!e||e.length===0?null:(0,sn.jsx)("div",{className:t.root,"data-testid":"widget-entities-list",children:e.map((a,l)=>(0,sn.jsxs)("button",{title:a.text,className:t.entity,type:"button",onClick:()=>s(a),children:[(0,sn.jsx)("span",{className:t.entityText,children:a.text}),(0,sn.jsxs)("span",{className:t.iconWrapper,children:[(0,sn.jsx)("span",{className:(0,oh.default)(t.icon),children:(0,sn.jsx)(rh,{})}),(0,sn.jsx)("span",{className:(0,oh.default)(t.icon,n===l&&t.iconClicked),children:(0,sn.jsx)(rh,{})})]})]},a.text))})},gE=pL;var hE=S(X()),ih=S(O());var La={};Ce(La,{enUS:()=>mL,nlNL:()=>gL});var mL={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"}],answer:[{type:0,value:"Answer"}]},gL={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"}],answer:[{type:0,value:"Antwoord"}]};var Dn={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 Je=S(E()),hL=({suggestion:e})=>{let t=j(La),n=W(),r=A($1(e.text)),o=A(q1(e.text)),i=A(G1(e.text)),s=A(cc),{replyOptions:a}=e,l=(0,ih.useCallback)(c=>{c.preventDefault(),c.stopPropagation(),!(r||!s)&&n(pd({platformSessionId:s,suggestion:e}))},[e,r,n,s]),u=(0,ih.useCallback)(c=>{if(c.preventDefault(),c.stopPropagation(),!s||!a)return;let f=parseInt(c.target.dataset.index,10),d=a[f];n(md({platformSessionId:s,reply:d,suggestion:e}))},[e,r,n,s]);return(0,Je.jsxs)(oe,{onClick:l,className:(0,hE.default)(Dn.root,{[Dn.isUsed]:r,[Dn.hasError]:i}),children:[(0,Je.jsx)(me,{children:(0,Je.jsxs)(me.Content,{children:[(0,Je.jsxs)(me.Title,{className:Dn.title,children:[e.text," ",(0,Je.jsx)(fl,{className:Dn.label,children:"analyse tool"})," ",i&&(0,Je.jsx)("span",{className:Dn.errorIcon,role:"img","aria-label":t("sendingError"),title:t("sendingError"),children:"!"})]}),a&&a.length>0&&(0,Je.jsx)("ul",{className:Dn.quickReplies,children:a.map(c=>(0,Je.jsx)("li",{className:Dn.quickReply,children:c.title},c.title))})]})}),(0,Je.jsxs)(oe.Actions,{fixed:i||r,children:[a&&a.length>0&&(0,Je.jsx)(oe.DropdownButton,{label:t("answer"),disabled:o,children:a.map((c,f)=>(0,Je.jsx)(oe.DropdownItem,{index:f,label:c.title,onClick:u},c.title))}),(0,Je.jsx)(oe.ActionButton,{primary:!0,disabled:r,onClick:l,label:t(r?"suggestionSent":i?"tryAgain":"sendSuggestion")})]})]})},yE=hL;var sh=S(E()),vE=()=>(0,sh.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:(0,sh.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 SE=S(O());var lt=S(E()),yL=({suggestion:e,lines:t,onEdit:n,onUse:r})=>{var d;let o=e.text||e.url||e.message,i=Vc(o),s=j(La),a=F("showImages"),l=F("fallbackImage"),u=y=>{y.preventDefault(),y.stopPropagation(),r(o)},c=y=>{y.preventDefault(),y.stopPropagation(),n(e)},f=(0,SE.useCallback)(y=>{window.open(i,"_blank"),y.stopPropagation(),y.preventDefault()},[i]);return(0,lt.jsxs)(oe,{onClick:u,"data-testid":"edit-suggestion",children:[(0,lt.jsxs)(me,{children:[a&&e.image&&(0,lt.jsx)(me.Image,{src:ud(e,"small",l||void 0),title:e.title}),(0,lt.jsxs)(me.Content,{children:[e.title&&(0,lt.jsx)(me.Title,{children:e.title}),e.searchKeywords&&((d=e.searchKeywords)==null?void 0:d.length)>0&&(0,lt.jsx)(oe.Labels,{labels:e.searchKeywords}),(0,lt.jsx)(me.Content,{cropText:t==="single",lineClamp:t==="multiple",children:o})]})]}),(0,lt.jsxs)(oe.Actions,{children:[i&&(0,lt.jsx)(oe.ActionButton,{onClick:f,label:s("visitUrl")}),(0,lt.jsx)(oe.ActionButton,{primary:!0,onClick:c,label:s("preview")}),(0,lt.jsx)(oe.ActionButton,{primary:!0,onClick:u,label:s("useSuggestion")})]})]})},xE=yL;var Aa=S(E()),vL=({contentType:e,lines:t,suggestions:n})=>{let r=Pt(),o=A(yi),i=a=>{r.send(wg,{state:o,suggestion:a,contentType:e})},s=(a,l)=>{r.send(kn,{text:a,suggestion:{...l,source:l.source,sourceText:l.text}})};return(0,Aa.jsx)(Aa.Fragment,{children:n.map(a=>(0,Aa.jsx)(xE,{suggestion:a,lines:t,onEdit:l=>i(l),onUse:l=>s(l,a)},a.text||a.url||a.message))})},_E=vL;var ah={};Ce(ah,{enUS:()=>SL,nlNL:()=>xL});var SL={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"}],linkPersonalcollection:[{type:0,value:"Personal Collection"}],linkSummary:[{type:0,value:"Summarize"}],linkKnowledgeSearch:[{type:0,value:"Knowledge Assist"}],linkSearch:[{type:0,value:"Search"}]},xL={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"}],linkPersonalcollection:[{type:0,value:"Personal Collection"}],linkSummary:[{type:0,value:"Vat gesprek samen"}],linkKnowledgeSearch:[{type:0,value:"Knowledge assist"}],linkSearch:[{type:0,value:"Zoeken"}]};var wE={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 lh=S(E()),EE=()=>(0,lh.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:(0,lh.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 uh=S(E()),CE=()=>(0,uh.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 -960 960 960",width:"1em",children:(0,uh.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 z=S(E()),hd=(e,t)=>{let n=A(Tn);(0,TE.useEffect)(()=>n?t.every(r=>!!r)?e():()=>{}:()=>{},[...t,n])},_L=()=>{let e=j(ah),t=W(),n=F("isEmbedded"),r=k("Widget",wE),o=F("showAutoflows"),i=F("showCustomMessages"),s=F("showPersonalCollectionLink"),a=F("showSummaryCommand"),l=F("showKnowledgeSearch"),u=F("showSearch"),c=A(Ci),f=A(Xc),d=A(B1),y=A(Gc),v=A(W1),h=A(dc),g=A(fc),m=A(Tn),p=A(cc),x=A(rE),_=A(yi),C=Pt(),w=A(Y_),b=A(J1("/admin/personal-collection")),R=F("adminUrl");if(hd(()=>(t(Ia(p)),t(Q1(p)),()=>{t(Y1(p))}),[t,g,i,p]),hd(()=>(t(Mn(p)),t(U1(p)),()=>{t(z1(p))}),[t,g,o,p]),hd(()=>{f.forEach(({type:N})=>{t(N==="entities"?zt():Cn(N))})},[t,g,h,c]),hd(()=>(t(Jg()),()=>{t(tE())}),[t,g,s,h]),g===!1)return(0,z.jsx)("div",{className:r.stateText,children:(0,z.jsx)("div",{children:(0,z.jsx)("p",{children:e("notSupported")})})},"supported");if(m===!1)return(0,z.jsx)("div",{className:r.loginText,children:(0,z.jsx)("div",{children:(0,z.jsx)(Yc,{isEmbedded:n,loginUrl:R})})},"login");if(!c||!p||m===null||w||x)return(0,z.jsx)("div",{className:r.stateText,children:(0,z.jsx)("div",{children:(0,z.jsx)("p",{children:e("waiting")})})},"waiting");let P=u||a||l||b;return(0,z.jsx)("div",{className:(0,bE.default)(r.root),"data-testid":"widget",children:(0,z.jsxs)(pl,{className:r.sectionList,children:[P&&(0,z.jsx)(Bn,{title:e("actions"),type:"shortcuts",children:(0,z.jsxs)("div",{className:r.shortcutList,children:[u&&(0,z.jsxs)("button",{className:r.shortcut,onClick:()=>C.send("ShowCommandPalette",{isOpen:!0}),children:[(0,z.jsx)(gi,{}),e("linkSearch")]}),a&&(0,z.jsxs)("button",{className:r.shortcut,onClick:()=>C.send("ShowCommandPalette",{isOpen:!0,page:"summary"}),children:[(0,z.jsx)(CE,{}),e("linkSummary")]}),l&&(0,z.jsxs)("button",{className:r.shortcut,onClick:()=>C.send("ShowCommandPalette",{isOpen:!0,page:"knowledgeSearch"}),children:[(0,z.jsx)(EE,{}),e("linkKnowledgeSearch")]}),b&&(0,z.jsxs)("a",{className:r.shortcut,target:"_blank",href:b,rel:"noreferrer",children:[(0,z.jsx)(vE,{}),e("linkPersonalcollection")]})]})}),i&&v.length>0&&(0,z.jsx)(Bn,{type:"custom-messages","data-testid":"custom-messages",children:(0,z.jsx)($t,{withDivider:!0,children:v.map(N=>(0,z.jsx)(yE,{suggestion:N},N.text))})}),o&&d.length>0&&(0,z.jsx)(Bn,{type:"autoflows",title:e("titleAutoflows"),"data-testid":"autoflows",children:(0,z.jsx)($t,{withDivider:!0,children:(0,z.jsx)(pE,{})})}),f.map(({type:N,title:V,amount:B,lines:je})=>{var an;switch(N){case"entities":return y&&y.length>0&&(0,z.jsx)(Bn,{type:N,title:V,"data-testid":`type-${N}`,children:(0,z.jsx)(gE,{entities:y})},N);default:return((an=_[N])==null?void 0:an.fetchState)==="done"&&_[N].suggestions.length>0&&(0,z.jsx)(Bn,{type:N,title:V,"data-testid":`type-${N}`,children:(0,z.jsx)($t,{withDivider:!0,children:(0,z.jsx)(_E,{lines:je,contentType:N,suggestions:_[N].suggestions.slice(0,B)||[]})})},N)}})]})})},kE=_L;function PE(e){let t=new Range;return t.selectNodeContents(e),t}var Oa=/[\u200B-\u200D\uFEFF]/g;function so(e,t,n){let r=new Range;if(e.firstChild===null&&t===0&&n===0)return r.selectNodeContents(e),r;let o=0,i=!1;function s(l,u){let c=-1,f=/[\u200B-\u200D\uFEFF]/;if(!f.test(l))return u;for(let d=0;d<=l.length;d++)if(f.test(l[d])||c++,c===u)return d;throw new Error("Offset out of range")}function a(l){var u;switch(l.nodeType){case Node.TEXT_NODE:{let c=l.textContent,f=c.replace(Oa,""),d=o+f.length,y=t>=o&&t<=d,v=n>=o&&n<=d;if(y){let h=s(c,t-o);h===0&&!v?r.setStartBefore(l):r.setStart(l,h)}v&&(r.setEnd(l,s(c,n-o)),i=!0),o=d;break}case Node.ELEMENT_NODE:{if(l.tagName==="BR"&&(o===t&&r.setStartBefore(l),o++,o===n)){r.setEndAfter(l),i=!0;return}for(let f=0;f<l.childNodes.length&&(a(l.childNodes[f]),!i);f++);let c=(u=l.lastChild)==null?void 0:u.tagName;l.tagName==="DIV"&&c!=="DIV"&&c!=="BR"&&o++;break}default:break}}if(a(e),r.startContainer===document)throw new Error("Offsets out of bound");return r}function yd(e,t){if(!e.contains(t.commonAncestorContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:r,endContainer:o,endOffset:i}=t,s,a,l=0;function u(c){let f=c===n,d=c===o;switch(c.nodeType){case Node.TEXT_NODE:{let y=c.textContent;f&&(s=l+y.substring(0,r).replace(Oa,"").length),d&&(a=l+y.substring(0,i).replace(Oa,"").length),l+=y.replace(Oa,"").length;break}case Node.ELEMENT_NODE:{let{tagName:y}=c,v=c.nextSibling===null;y==="BR"&&!v&&l++;for(let h=0;h<c.childNodes.length&&(f&&h===r&&(s=l),u(c.childNodes[h]),d&&h===i-1&&(a=l),a===void 0);h++);!d&&y==="DIV"&&!v&&l++,d&&(a=l);break}default:break}}if(u(e),a===void 0)throw new Error("Could not determine start and end");return{start:s??a,end:a}}function Na(e,t){if(!e.contains(t.commonAncestorContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:r,endContainer:o,endOffset:i}=t,s=-1,a="";function l(u){let c=u===n,f=u===o;switch(c&&s++,u.nodeType){case Node.TEXT_NODE:{if(s!==0)return;let d=c?r:0,y=f?i:void 0,v=u.textContent.replace(Oa,"");d===0&&y===void 0?a+=v:a+=v.substring(d,y);break}case Node.ELEMENT_NODE:{let{tagName:d}=u,y=u.nextSibling===null;s===0&&d==="BR"&&!y&&(a+=`
|
|
20
20
|
`);for(let v=c?r:0;v<(f?Math.min(i,u.childNodes.length):u.childNodes.length)&&(l(u.childNodes[v]),s!==1);v++);!f&&s===0&&d==="DIV"&&!y&&(a+=`
|
|
21
|
-
`);break}default:break}f&&s++}return l(e),a}var ao=class extends _n{observer;getText(){let t=new Range;return t.selectNodeContents(this.element),Na(this.element,t)}getHTML(){return this.element.innerHTML||""}getSelection(){if(document.activeElement!==this.element)return null;let t=window.getSelection();if(!t||t.rangeCount===0)return null;let n=t.getRangeAt(0);return!n||!this.element.contains(n.commonAncestorContainer)?null:yd(this.element,n)}getSelectedText(){if(!this.currentSelection)return"";let{start:t,end:n}=this.currentSelection;return Na(this.element,so(this.element,t,n))}applyChanges(t){var o;if(!this.isActive)return;this.isSettingValue=!0;let n=this.getText(),r=t(this.element);(o=this.observer)==null||o.takeRecords(),Promise.resolve(r).then(()=>{this.currentText=this.getText(),n!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(){super.listen(),this.observer=new MutationObserver(()=>{setTimeout(()=>{this.triggerChange()},0)}),this.observer.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0});let t=this.element.isContentEditable,n=new MutationObserver(()=>{this.element.isContentEditable!==t&&(t=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});n.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>n.disconnect())}dispose(){super.dispose(),this.observer&&this.observer.disconnect()}};var ch=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(t)}close(){this.disposeHandlers.forEach(t=>t()),this.broadcastChannel.close()}},dh=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.iframe=this.createIframe(),document.body.appendChild(this.iframe)}iframe;disposeHandlers=[];createIframe(){let t=`deepdesk-iframe-${this.name}`,n=document.getElementById(t);if(n)return n;let r=document.createElement("iframe"),o=`${this.targetOrigin}/v2/widget/liveengage/channel.html`,i=new URLSearchParams({channel:this.name,host:window.location.origin});return this.options.debug&&i.set("debug","1"),r.style.position="absolute",r.style.left="-999em",r.style.width="0px",r.style.height="0px",r.tabIndex=-1,r.id=t,r.title=`iframe-${this.name}`,r.src=`${o}?${i.toString()}`,r}onMessage(t){window.addEventListener("message",t),this.disposeHandlers.push(()=>{window.removeEventListener("message",t)})}postMessage(t){var n;(n=this.iframe.contentWindow)==null||n.postMessage(t,this.targetOrigin)}close(){var t;this.disposeHandlers.forEach(n=>n()),(t=this.iframe)==null||t.remove()}},fh=class{constructor(t){this.params=t;this.deepdeskUrl=t.deepdeskUrl,this.eventMap=t.eventMap,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(),U.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 dh(t,this.deepdeskUrl,{debug:!0}):new ch(t),r=o=>{var i,s;o.origin===this.deepdeskUrl&&o.data.type==="event"&&o.data.channel===t&&(U.info("Received broadcast event",this.sessionId,o),(s=(i=this.eventMap)[o.data.name])==null||s.call(i,o.data.payload))};return n.onMessage(r),n}send(t,n){var o,i,s;if(!this.sessionId)return;U.info("broadcast event",{sessionId:this.sessionId,name:t,payload:n});let r={type:"event",name:t,payload:n};(i=(o=this.eventMap)[t])==null||i.call(o,n),(s=this.channel)==null||s.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)}},RE=fh;var Ai=class extends Error{constructor(n,r){super(n);this.body=r}name="CustomError"};var ph=e=>new Promise(t=>{setTimeout(t,e)});var Oi=class extends Ai{name="ClientError"},mh=class extends Ai{name="ServerError"},Kt=class e{constructor(t="",n={}){this.baseUrl=t;this.options=n;n.fetch&&(this.fetch=n.fetch)}latestRequestByUrl={};csrfToken;fetch=window.fetch.bind(window);static refreshingToken=null;patchFetch(t){this.fetch=t(this.fetch)}setCsrfToken(t){this.csrfToken=t}request(t,n={}){return new Promise((r,o)=>{let i={isAborted:!1,reject:o},s=`${this.baseUrl}${t}`,a=this.fetch,{abortLatest:l=!1,attempts:u=1,retryDelay:c=500,refreshTokenOn401:f=!0,retryOnError:d=_=>_ instanceof TypeError,retryOnResponse:y=_=>_.status>=500,version:v="v1",...h}=n,g={credentials:"include",...h,headers:{"Content-Type":"application/json",...h.headers}};n.method!==void 0&&n.method!=="GET"&&this.csrfToken&&(g.headers={...g.headers,"X-CSRFToken":this.csrfToken}),typeof v=="string"&&(g.headers={...g.headers,"X-Deepdesk-API-Version":v});let m=u,p=!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()=>(m--,a(s,g).then(async _=>y(_)&&!i.isAborted&&m>0?(await ph(c),x()):_.status===401&&f===!0&&p===!1?(p=!0,await this.refreshToken(),x()):_).catch(async _=>{if(d(_)&&!i.isAborted&&m>0)return await ph(c),x();throw _}));x().then(_=>_.json().catch(()=>null).then(C=>{_.status>=500?o(new mh("Server Error",C)):_.status===401?o(new Oi("Unauthorized",C)):_.status===403?o(new Oi("Forbidden",C)):_.status===404?o(new Oi("Not Found",C)):_.status>=400&&o(new Oi("Bad Request",C)),delete this.latestRequestByUrl[s],r(C)})).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 wL;(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||={})})(wL||={});function vd(e){return{...re(e),tags:e.tags}}var Fn=class e{constructor(t,n={}){this.options=n;this.client=new Kt(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(),U.info(`Creating conversation for session ${t.sessionId} and agent ${t.agentId}`);let n=await this.client.post("/api/conversations",{...we(t),tags:t.tags},{version:"v2"});return vd(n)}async getProfile(t){let n=await this.client.get(`/apis/admin/profiles/${t}/`,{version:null});return re(n)}async getContentTypes(){let t=await this.client.get("/apis/admin/content-types/",{version:null});return re(t)}async getPlatformConfig(){let{config:t}=await this.client.get("/platform/config/",{version:null});return re(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(),U.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 vd(i)}async isConversationSupported(t,n={}){U.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=we(n);n.tags&&(r.tags=n.tags);let o=await this.client.put(`/api/conversations/${t}`,r,{version:"v2"});return vd(o)}async postMessages(t,n){return(await this.client.post(`/api/conversations/${t}/messages`,n.map(o=>({...we(o),tags:o.tags})),{version:"v2"})).map(o=>vd(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",we({...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:we({...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)},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 U.warn(`Invalid token '${t}'`),n})}async authenticateWithKey(t,n){await this.client.post("/apis/admin/session/api-key/",we(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}`,we(n),{abortLatest:!0})).map(i=>({...re(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`,we(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 re(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",we(t),{abortLatest:!0});return re(n)}async search(t){let n=await this.client.post(`/api/profiles/${t.profile}/search`,we(t),{version:"v2"});return re(n)}async knowledgeSearch(t,n,r){let o=await this.client.post("/api/knowledge-search/search",we({question:t.question,promptInstruction:t.promptInstruction,profile:r,chatHistory:n.map(i=>({question:i.question,answer:i.answer.answer}))}),{version:"v2"});return re(o)}async requestLoginByEmail(t){let n=await this.client.post("/apis/admin/session/passwordless/request/",{email:t},{version:null});return re(n)}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 re(n)}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),i=o.match(Sy);if(!n||!i)return;let s=i[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[s];a&&n&&a!==n&&U.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[s]=n})}};var Ma=class{constructor(t,n){this.url=t;this.options={timeout:25e3,...n}}eventListeners={};options;timeoutTimer;eventSource;proxyEvent(t){this.eventSource.addEventListener(gg(t),n=>{let{data:r}=n;try{let o=JSON.parse(r);this.emit(t,re(o))}catch{U.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 EL;(t=>{let e;(i=>(i.Started="Started",i.Aborted="Aborted",i.Completed="Completed"))(e=t.AutoflowSessionState||={})})(EL||={});var Da=class{constructor(t,n={}){this.apiUrl=t;this.client=new Kt(t,n)}client;streams={};logger=U;async getCustomMessages(t){let n=await this.client.get(`/sessions/${t}/suggestions`);return re(n.suggestions)}async sendCustomMessage(t,n){let r=await this.client.post(`/sessions/${t}/messages`,we(n));return re(r)}async answerCustomMessage(t,n){await this.client.post(`/sessions/${t}/answers`,we(n))}async getAutoflows(t){let n=await this.client.get(`/sessions/${t}/autoflows`);return re(n.autoflows)}async startAutoflowSession(t){let n=await this.client.post("/autoflow-sessions",we(t));return re(n)}async stopAutoflowSession(t){await this.client.delete(`/autoflow-sessions/${t}`)}openStream(t){return this.streams[t]||(this.streams[t]=new Ma(`${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 IE={startTime:null,stopTime:null},LE=H({name:"handlingTime",initialState:IE,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(J,()=>IE)}}),{handlingTimeStart:AE,handlingTimeStop:Sd,handlingTimeReset:OE}=LE.actions,NE=LE.reducer;var ME=(e={})=>{let t={onAuthError:xi(!1),...e};return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var gh={list:{keywordMatches:[]},fetchState:"idle",isInitialRequest:null};var lo=M("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 gh.list;if(!i)throw new Error("No current conversation to fetch pinned messages");return n.getStyleSuggestions({profileCode:i,message:e})}),CL=H({name:"styleSuggestions",initialState:gh,reducers:{},extraReducers:e=>{e.addCase(lo.pending,t=>{t.isInitialRequest=t.isInitialRequest===null,t.fetchState="loading"}).addCase(lo.rejected,t=>{t.fetchState="error"}).addCase(lo.fulfilled,(t,n)=>{t.fetchState="done",pr(t.list,n.payload)||(t.list=n.payload)}).addCase(J,()=>gh)}}),DE=CL.reducer;var FE=(e={})=>{let t,n=!0,r={getStyleSuggestions:lo,debounce:500,...e};return o=>i=>s=>{var y;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(!((y=u.conversation.current)==null?void 0:y.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 bL(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end}var jE=(e={})=>{let t={getTextSuggestions:Cn,getAutocompleteSuggestions:ha,debounce:200,check:Qc,...e},n;return r=>o=>i=>{var h;let{input:{userCommitted:s}}=r.getState(),a=o(i),l=r.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:u,showTabCompletion:c}=l.settings,f=(h=l.conversation.current)==null?void 0:h.id,d=i.type===$c.toString();if(!f||!u&&!c)return a;let{input:{userCommitted:y}}=l;return bL(y,s)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let g=oi(l);g===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(g))},d?0:t.debounce)),a}};var HE=lo.fulfilled.toString();function TL(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 BE=e=>t=>n=>r=>{var c;if(r.type!==HE){n(r);return}let o=t.getState().styleSuggestions.list;n(r);let i=t.getState(),s=i.styleSuggestions.list,a=(c=i.conversation)==null?void 0:c.current,{agentInfo:l}=i.info;if(o===s)return;let u=TL(o,s);r.type===HE&&u.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,agentId:l.agentId??(a==null?void 0:a.agentId),agentName:l.agentName??(a==null?void 0:a.agentName),agentEmail:l.agentEmail??(a==null?void 0:a.agentEmail),data:{keywordMatches:u}})};var kL=Nu({activeSuggestion:aw,answer:Zw,auth:_w,autoflows:V1,conversation:Ux,contentTypes:Dw,customMessages:Z1,exchangeToken:nE,entities:Bw,handlingTime:NE,info:N_,input:$m.reducer,overlayInput:Ge.reducer,settings:Ax,profile:t1,search:B_,summary:$w,styleSuggestions:DE,ui:fw,textSuggestions:nw});function UE(e){return j0({reducer:kL,middleware:t=>[...t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI,deepdeskBrokerAPI:e.deepdeskBrokerAPI}},serializableCheck:!1}),ME(),jE({debounce:200}),FE({debounce:500}),BE(e.deepdeskAPI),...e.middleware?e.middleware:[]],preloadedState:e.preloadedState})}var PL=e=>{var t;return((t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())??"unknown"},RL=e=>t=>n=>r=>{var a;let o=t.getState(),i=Bm("inlineSuggestions")(o);switch(r.type){case bn.toString():{let l=Q_(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 xi.toString():{!r.payload&&e.emit("logout",void 0);break}case Ft.toString():{let{start:l,end:u}=o.input.selection;e.emit("select-suggestion",{type:PL(r.payload.suggestion),...r.payload,replace:r.payload.replace==="selection"?{start:l,end:u}:{start:0,end:u}},{mayApplyChanges:!0});break}case Sc.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 na.toString():{let l=t.getState(),{text:u,selection:c}=l.input.userCommitted;e.emit("reset",{text:u,selectionAfter:c},{mayApplyChanges:!0});break}case Ec.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 zt.fulfilled.toString():r.payload.length>0&&e.sendEvent("entities found",{conversationId:o.conversation.current.id,data:{entities:r.payload}});break;case Pn.fulfilled.toString():e.sendEvent("conversation summarized",{conversationId:o.conversation.current.id,data:{inputText:JSON.stringify(r.payload.original),summary:r.payload.summary}});break;case it.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 xc.toString():e.handleKeyDown(r.payload);break;case ta.toString():e.logSendMessage(r.payload);break;case _c.toString():e.logSendEditSuggestionMessage(r.payload);break;case wc.toString():e.handleInputChanged(r.payload);break;default:break}let s=n(r);switch(r.type){case ta.toString():e.handleAfterSendMessage(r.payload);break;case ya.toString():e.onUpdateShowTabHint(r.payload);break;case Sd.toString():e.logHandlingTime();break;case Ft.toString():{i&&(t.dispatch(gr([])),t.dispatch(hr()));break}default:break}return s},zE=RL;function hh(e){return e.toISOString().replace("T"," ").replace("Z","")}function VE(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:hh(n),timeStop:hh(r)}}function yh(e,t,n){var b,R,P;let{text:r,metrics:{numCharsTyped:o,numCharsPasted:i,numCharsCut:s,numCharsDeleted:a,numPaste:l,agentStartedTypingTimestamp:u,externalTimeTotalSeconds:c,pastes:f,cuts:d,deletions:y,textSuggestions:v,offeredTextSuggestions:h}}=t[e],g=r.length,p=v.reduce((N,{text:V,searchTerm:B})=>N+V.length-(B?B.length:0),0),x=u??Date.now(),_=(Date.now()-x)/1e3+(c||0),C=o/_,w=v.reduce((N,{searchTerm:V})=>N+(V?V.length:0),0);return{conversationId:t.conversation.current.id,source:"agent",text:r,clientVersion:n.version,pastes:f,cuts:d,deletions:y,lenTextTyped:o+w,lenTextTotal:g,lenTextAssisted:p,lenTextPasted:i,lenTextCut:s,lenTextDeleted:a,timeTotalSeconds:_,charsPerSecond:C,numPastes:l,textSuggestionsV2:v,suggestionsCounters:[{source:"gpt",countOffered:h.filter(N=>N.source==="gpt").length}],agentId:(b=t.info.agentInfo)==null?void 0:b.agentId,agentName:(R=t.info.agentInfo)==null?void 0:R.agentName,agentEmail:(P=t.info.agentInfo)==null?void 0:P.agentEmail}}function KE(e,t){let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;return r instanceof HTMLElement?KE(r,t):null}function WE(e,t){return KE(e,t)}function $E(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function xd(e){return e instanceof HTMLElement&&(Ln(e)||Nc(e))}var qE=(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{U.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function IL(e){return e.offsetParent!==null}function GE(e){if(!IL(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 _d(e,t,n=100){let r=GE(e);t({isVisible:r});let o=setInterval(()=>{let i=GE(e);i!==r&&(r=i,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var ut=S(E()),XE=qE("showTabHint",!0),Fa=class e{static version="10.1.7";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 Fn(u,{token:i,fetch:s}),this.version=r,this.instanceId=e.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[zE({emit:(f,d,y)=>this.emit(f,d,y),handleAfterSendMessage:f=>this.handleAfterSendMessage(f),handleInputChanged:f=>this.handleInputChanged(f),handleKeyDown:f=>this.handleKeyDown(f),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:f=>this.logSendMessage(f),logSendEditSuggestionMessage:f=>this.logSendEditMessage(f),onUpdateShowTabHint:f=>XE.update(f),sendEvent:(f,d)=>this.deepdeskApi.sendEvent(f,d)})]};n&&Object.assign(c,{deepdeskBrokerAPI:new Da(n)}),this.store=UE(c),this.broadcastEvents=new RE({debug:!0,deepdeskUrl:u,eventMap:ww(this.store),createCustomChannel:l}),this.store.dispatch(Js),this.store.dispatch(ya(XE.value())),this.store.dispatch(Js({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?(U.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(U.warn("Profile has not been loaded (yet)"),!0):(U.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(xi(null)),this.store.dispatch(wr()),new Promise(t=>{let n=this.store.subscribe(()=>{let r=this.store.getState();Tn(r)&&gw(r)!=="loading"&&t()});this.unmountHandlers.push(()=>{n()})})}isLoggedIn(){return this.deepdeskApi.isLoggedIn()}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){U.warn("Failed to attach user:",n)}}async isConversationSupported(t,n){return(await this.store.dispatch(Km({sessionId:t,options:n}))).payload}async createConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(pc(t))).payload}async getConversationBySessionId(t,n){return this.hasConversation()&&this.sessionId()!==t&&this.resetConversation(),(await this.store.dispatch(mc({sessionId:t,options:n}))).payload}async upsertConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(Wm(t))).payload}async postMessages(t){return(await this.store.dispatch(hc(t))).payload}async updateConversation(t){return(await this.store.dispatch(gc(t))).payload}resetConversation(){this.store.dispatch(J()),this.dynamicThunkObject.conversationQuery=null}async getSummary(){let t=await this.store.dispatch(Pn());if(t.error)throw new Error(t.error.message);return t.payload.summary}configure(t){this.store.dispatch(Js(t))}setVisitorInfo(t){this.store.dispatch(O_(t))}async setAgentInfo(t){await this.store.dispatch(fa(t))}async setAgentSettings(t){await this.store.dispatch(hg(t))}async getAgentSettings(){return(await this.store.dispatch(yg())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();let t=[];return this.store.dispatch($c()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})}notifyInputChanged(t){this.store.dispatch(wc(t))}syncInputHtml(t){this.store.dispatch(e_(t))}notifyKeyDown(t){this.store.dispatch(xc(t))}notifyPaste(t,n){this.store.dispatch(Zx({text:t,selectionText:n}))}notifyCut(t){this.store.dispatch(Qx(t))}notifyExternalSuggestion(t){this.store.dispatch(Ft(t)),this.store.dispatch(hr())}notifyEditSuggestion(t){this.store.dispatch(ew(t.contentType,t.suggestions)),this.store.dispatch(bn({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(Si({collapse:!1})),this.inputMediator&&this.store.dispatch(Kx({text:t,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(gr([])))}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(Yx(vc(t))),!(t.key!=="Tab"&&!this.settings.showTextSuggestions))switch(t.key){case"Up":case"ArrowUp":if(n||!a||!i||t.shiftKey)return;this.store.dispatch(qx()),s||this.stageSelectedSuggestion({inputType:"arrow"}),t.preventDefault();return;case"Down":case"ArrowDown":{if(n||!a||!i||t.shiftKey)return;this.store.dispatch(Xx());let{selectedSuggestionIndex:u}=this.state.input;u===-1?this.store.dispatch(na()):s||this.stageSelectedSuggestion({inputType:"arrow"}),t.preventDefault();return}case"Esc":case"Escape":{l?(this.store.dispatch(Cc(-1)),this.store.dispatch(na()),t.preventDefault()):n||(this.store.dispatch(Si({collapse:!0})),this.store.dispatch(cw(!0)),t.preventDefault());return}case"Tab":{let{userCommitted:u}=this.state.input,c=u.text.substring(0,u.selection.end),{tabCompletionSuggestion:f}=this.state.input;this.store.dispatch(ya(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):this.settings.showTabCompletion&&f&&f.text.startsWith(c)&&(this.store.dispatch(Ft({text:f.text,suggestion:f,eventMetrics:{inputType:"tab"},replace:"until-selection-end"})),this.store.dispatch(hr())),t.preventDefault();break}default:}}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(Jx()),this.store.dispatch(gr([]))}handlingTimeStart(){this.state.handlingTime.startTime||(U.info("Start handling time"),this.store.dispatch(AE()))}handlingTimeStop(){this.state.handlingTime.startTime&&(U.info("Stop handling time"),this.store.dispatch(Sd()))}logSendMessage(t){let n=yh("input",this.state,{version:this.version});t&&Object.assign(n,{text:t}),this.deepdeskApi.sendEventV1("Send Message",n),this.emit("send-message-event",n)}logSendEditMessage(t){let n=yh("overlayInput",this.state,{version:this.version});t&&Object.assign(n,{text:t}),this.store.dispatch($x(this.state.overlayInput.metrics))}logHandlingTime(){let t=VE(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",t),this.store.dispatch(OE())}notifySubmit(t={}){this.shouldAbort()||(this.store.dispatch(hr()),this.store.dispatch(ta(t.text??this.state.input.text)))}stageSelectedSuggestion(t){let n=this.state.input.selectedSuggestionIndex,{textSuggestions:r}=this.state.input;this.store.dispatch(Ft({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){U.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),U.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]=pi(r,o);return i.dataset.testid=t,n!=null&&n.rootNode&&i.classList.add(n.rootNode),this.unmountHandlers.push(()=>{(0,jn.unmountComponentAtNode)(i),s(),i.remove()}),i}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return to(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,n.appendChild(o),this.unmountHandlers.push(()=>{(0,jn.unmountComponentAtNode)(o),o.remove()}),o}mount(t,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!xd(t))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let{customStyles:r={},showStyleSuggestions:o,showTabCompletion:i,showTextSuggestions:s,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,isEmbedded:f,detectSubmit:d,insertLink:y,inputMediator:v,closestScrollSelector:h,appendOverlayTo:g,inlineSuggestions:m}=n;this.configure({showStyleSuggestions:o,showTabCompletion:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,showTextSuggestions:s,insertLink:y,isEmbedded:f,inlineSuggestions:m});let p=h&&WE(t,h)||void 0,x=this.overlayContainerFactory("deepdesk-tab-completion",r,t,{appendTo:g,closestScrollElement:p,mirrorOverflow:!0,onRemove:()=>this.unmount()}),_=this.overlayContainerFactory("deepdesk-suggestions-overlay",r,p||t,{appendTo:g});n.automaticHandlingTime&&this.setupHandlingTime(t),(0,jn.render)((0,ut.jsx)(Pa,{store:this.store,customStyles:r,children:(0,ut.jsx)(Sa,{broadcastEvents:this.broadcastEvents,children:(0,ut.jsx)(F1,{inputElement:t})})}),x),(0,jn.render)((0,ut.jsx)(Pa,{store:this.store,customStyles:r,children:(0,ut.jsx)(Sa,{broadcastEvents:this.broadcastEvents,children:(0,ut.jsx)(Jc,{})})}),_),(0,jn.render)((0,ut.jsx)(Pa,{store:this.store,customStyles:r,children:(0,ut.jsx)(Sa,{broadcastEvents:this.broadcastEvents,children:(0,ut.jsx)(s1,{})})}),this.createContainer("deepdesk-overlays")),to(t),this.inputMediator=v||(Ln(t)?new wn(t):new ao(t)),this.inputMediator.on("change",({plainText:w})=>{this.notifyInputChanged(w)}),this.inputMediator.on("updated",({rawHtml:w})=>{w!=null&&this.syncInputHtml(w)}),this.inputMediator.on("keydown",w=>{this.notifyKeyDown(w)}),this.inputMediator.on("paste",({pastedText:w,selectionText:b})=>{this.notifyPaste(w,b)}),this.inputMediator.on("cut",({selectionText:w})=>{this.notifyCut(w)});let C;this.inputMediator.on("selection",w=>{clearTimeout(C),w===null?C=setTimeout(()=>{w!==null&&this.store.dispatch(qm(w))},500):this.store.dispatch(qm(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(vi(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(vi(!0))),this.store.dispatch(Wx({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.whenConversationLoaded(()=>{var w;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&&U.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,showPersonalCollectionLink:i,isEmbedded:s}=n;this.widgetRoot=t,this.configure({showImages:o,showPersonalCollectionLink:i,isEmbedded:s}),(0,jn.render)((0,ut.jsx)(Pa,{store:this.store,customStyles:r,children:(0,ut.jsx)(Sa,{broadcastEvents:this.broadcastEvents,children:(0,ut.jsx)(kE,{})})}),t),this.whenConversationLoaded(()=>{var a;this.broadcastEvents.setSessionId((a=this.state.conversation.current)==null?void 0:a.sessionId)})}unmountWidget(){this.widgetRoot&&(0,jn.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(t){let n=_d(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){$E(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(Ta());let t=Ci(this.state);t&&this.store.dispatch(Js({showSearch:t.search,showAutoflows:t.autoflows,showCustomMessages:t.customMessages,showImageSearch:t.imageSearch,showEntitiesCommand:t.entitiesCommand,showSummaryCommand:t.summarizer,showKnowledgeSearch:t.knowledgeSearch,recommendTextSuggestions:t.recommendTextSuggestions}))}),this.loadProfileConfigPromise)}async checkForTrialMode(t){try{let{account:n}=await this.deepdeskApi.getPlatformConfig();if(!n.isTrial){this.shouldRender=!0;return}if(U.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;U.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=Xc(this.state);try{n.forEach(({type:r})=>{r==="entities"?this.store.dispatch(zt()):this.store.dispatch(Cn(r))})}catch(r){this.handleError(r)}}};async function QE(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 YE(e,t,n={}){let r=n.replace?so(e,n.replace.start,n.replace.end):PE(e),o,i=()=>{if(n.setRange)return n.setRange(r.cloneRange());r.deleteContents(),o=document.createElement("span"),r.insertNode(o),t.split(`
|
|
21
|
+
`);break}default:break}f&&s++}return l(e),a}var ao=class extends _n{observer;getText(){let t=new Range;return t.selectNodeContents(this.element),Na(this.element,t)}getHTML(){return this.element.innerHTML||""}getSelection(){if(document.activeElement!==this.element)return null;let t=window.getSelection();if(!t||t.rangeCount===0)return null;let n=t.getRangeAt(0);return!n||!this.element.contains(n.commonAncestorContainer)?null:yd(this.element,n)}getSelectedText(){if(!this.currentSelection)return"";let{start:t,end:n}=this.currentSelection;return Na(this.element,so(this.element,t,n))}applyChanges(t){var o;if(!this.isActive)return;this.isSettingValue=!0;let n=this.getText(),r=t(this.element);(o=this.observer)==null||o.takeRecords(),Promise.resolve(r).then(()=>{this.currentText=this.getText(),n!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(){super.listen(),this.observer=new MutationObserver(()=>{setTimeout(()=>{this.triggerChange()},0)}),this.observer.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0});let t=this.element.isContentEditable,n=new MutationObserver(()=>{this.element.isContentEditable!==t&&(t=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});n.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>n.disconnect())}dispose(){super.dispose(),this.observer&&this.observer.disconnect()}};var ch=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(t)}close(){this.disposeHandlers.forEach(t=>t()),this.broadcastChannel.close()}},dh=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.iframe=this.createIframe(),document.body.appendChild(this.iframe)}iframe;disposeHandlers=[];createIframe(){let t=`deepdesk-iframe-${this.name}`,n=document.getElementById(t);if(n)return n;let r=document.createElement("iframe"),o=`${this.targetOrigin}/v2/widget/liveengage/channel.html`,i=new URLSearchParams({channel:this.name,host:window.location.origin});return this.options.debug&&i.set("debug","1"),r.style.position="absolute",r.style.left="-999em",r.style.width="0px",r.style.height="0px",r.tabIndex=-1,r.id=t,r.title=`iframe-${this.name}`,r.src=`${o}?${i.toString()}`,r}onMessage(t){window.addEventListener("message",t),this.disposeHandlers.push(()=>{window.removeEventListener("message",t)})}postMessage(t){var n;(n=this.iframe.contentWindow)==null||n.postMessage(t,this.targetOrigin)}close(){var t;this.disposeHandlers.forEach(n=>n()),(t=this.iframe)==null||t.remove()}},fh=class{constructor(t){this.params=t;this.deepdeskUrl=t.deepdeskUrl,this.eventMap=t.eventMap,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(),U.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 dh(t,this.deepdeskUrl,{debug:!0}):new ch(t),r=o=>{var i,s;o.origin===this.deepdeskUrl&&o.data.type==="event"&&o.data.channel===t&&(U.info("Received broadcast event",this.sessionId,o),(s=(i=this.eventMap)[o.data.name])==null||s.call(i,o.data.payload))};return n.onMessage(r),n}send(t,n){var o,i,s;if(!this.sessionId)return;U.info("broadcast event",{sessionId:this.sessionId,name:t,payload:n});let r={type:"event",name:t,payload:n};(i=(o=this.eventMap)[t])==null||i.call(o,n),(s=this.channel)==null||s.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)}},RE=fh;var Ai=class extends Error{constructor(n,r){super(n);this.body=r}name="CustomError"};var ph=e=>new Promise(t=>{setTimeout(t,e)});var Oi=class extends Ai{name="ClientError"},mh=class extends Ai{name="ServerError"},Kt=class e{constructor(t="",n={}){this.baseUrl=t;this.options=n;n.fetch&&(this.fetch=n.fetch)}latestRequestByUrl={};csrfToken;fetch=window.fetch.bind(window);static refreshingToken=null;patchFetch(t){this.fetch=t(this.fetch)}setCsrfToken(t){this.csrfToken=t}request(t,n={}){return new Promise((r,o)=>{let i={isAborted:!1,reject:o},s=`${this.baseUrl}${t}`,a=this.fetch,{abortLatest:l=!1,attempts:u=1,retryDelay:c=500,refreshTokenOn401:f=!0,retryOnError:d=_=>_ instanceof TypeError,retryOnResponse:y=_=>_.status>=500,version:v="v1",...h}=n,g={credentials:"include",...h,headers:{"Content-Type":"application/json",...h.headers}};n.method!==void 0&&n.method!=="GET"&&this.csrfToken&&(g.headers={...g.headers,"X-CSRFToken":this.csrfToken}),typeof v=="string"&&(g.headers={...g.headers,"X-Deepdesk-API-Version":v});let m=u,p=!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()=>(m--,a(s,g).then(async _=>y(_)&&!i.isAborted&&m>0?(await ph(c),x()):_.status===401&&f===!0&&p===!1?(p=!0,await this.refreshToken(),x()):_).catch(async _=>{if(d(_)&&!i.isAborted&&m>0)return await ph(c),x();throw _}));x().then(_=>_.json().catch(()=>null).then(C=>{_.status>=500?o(new mh("Server Error",C)):_.status===401?o(new Oi("Unauthorized",C)):_.status===403?o(new Oi("Forbidden",C)):_.status===404?o(new Oi("Not Found",C)):_.status>=400&&o(new Oi("Bad Request",C)),delete this.latestRequestByUrl[s],r(C)})).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 wL;(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||={})})(wL||={});function vd(e){return{...re(e),tags:e.tags}}var Fn=class e{constructor(t,n={}){this.options=n;this.client=new Kt(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(),U.info(`Creating conversation for session ${t.sessionId} and agent ${t.agentId}`);let n=await this.client.post("/api/conversations",{...we(t),tags:t.tags},{version:"v2"});return vd(n)}async getProfile(t){let n=await this.client.get(`/apis/admin/profiles/${t}/`,{version:null});return re(n)}async getContentTypes(){let t=await this.client.get("/apis/admin/content-types/",{version:null});return re(t)}async getPlatformConfig(){let{config:t}=await this.client.get("/platform/config/",{version:null});return re(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(),U.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 vd(i)}async isConversationSupported(t,n={}){U.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=we(n);n.tags&&(r.tags=n.tags);let o=await this.client.put(`/api/conversations/${t}`,r,{version:"v2"});return vd(o)}async postMessages(t,n){return(await this.client.post(`/api/conversations/${t}/messages`,n.map(o=>({...we(o),tags:o.tags})),{version:"v2"})).map(o=>vd(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",we({...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:we({...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)},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 U.warn(`Invalid token '${t}'`),n})}async authenticateWithKey(t,n){await this.client.post("/apis/admin/session/api-key/",we(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}`,we(n),{abortLatest:!0})).map(i=>({...re(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`,we(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 re(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",we(t),{abortLatest:!0});return re(n)}async search(t){let n=await this.client.post(`/api/profiles/${t.profile}/search`,we(t),{version:"v2"});return re(n)}async knowledgeSearch(t,n,r){let o=await this.client.post("/api/knowledge-search/search",we({question:t.question,promptInstruction:t.promptInstruction,profile:r,chatHistory:n.map(i=>({question:i.question,answer:i.answer.answer}))}),{version:"v2"});return re(o)}async requestLoginByEmail(t){let n=await this.client.post("/apis/admin/session/passwordless/request/",{email:t},{version:null});return re(n)}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 re(n)}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),i=o.match(Sy);if(!n||!i)return;let s=i[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[s];a&&n&&a!==n&&U.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[s]=n})}};var Ma=class{constructor(t,n){this.url=t;this.options={timeout:25e3,...n}}eventListeners={};options;timeoutTimer;eventSource;proxyEvent(t){this.eventSource.addEventListener(gg(t),n=>{let{data:r}=n;try{let o=JSON.parse(r);this.emit(t,re(o))}catch{U.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 EL;(t=>{let e;(i=>(i.Started="Started",i.Aborted="Aborted",i.Completed="Completed"))(e=t.AutoflowSessionState||={})})(EL||={});var Da=class{constructor(t,n={}){this.apiUrl=t;this.client=new Kt(t,n)}client;streams={};logger=U;async getCustomMessages(t){let n=await this.client.get(`/sessions/${t}/suggestions`);return re(n.suggestions)}async sendCustomMessage(t,n){let r=await this.client.post(`/sessions/${t}/messages`,we(n));return re(r)}async answerCustomMessage(t,n){await this.client.post(`/sessions/${t}/answers`,we(n))}async getAutoflows(t){let n=await this.client.get(`/sessions/${t}/autoflows`);return re(n.autoflows)}async startAutoflowSession(t){let n=await this.client.post("/autoflow-sessions",we(t));return re(n)}async stopAutoflowSession(t){await this.client.delete(`/autoflow-sessions/${t}`)}openStream(t){return this.streams[t]||(this.streams[t]=new Ma(`${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 IE={startTime:null,stopTime:null},LE=H({name:"handlingTime",initialState:IE,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(J,()=>IE)}}),{handlingTimeStart:AE,handlingTimeStop:Sd,handlingTimeReset:OE}=LE.actions,NE=LE.reducer;var ME=(e={})=>{let t={onAuthError:xi(!1),...e};return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var gh={list:{keywordMatches:[]},fetchState:"idle",isInitialRequest:null};var lo=M("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 gh.list;if(!i)throw new Error("No current conversation to fetch pinned messages");return n.getStyleSuggestions({profileCode:i,message:e})}),CL=H({name:"styleSuggestions",initialState:gh,reducers:{},extraReducers:e=>{e.addCase(lo.pending,t=>{t.isInitialRequest=t.isInitialRequest===null,t.fetchState="loading"}).addCase(lo.rejected,t=>{t.fetchState="error"}).addCase(lo.fulfilled,(t,n)=>{t.fetchState="done",pr(t.list,n.payload)||(t.list=n.payload)}).addCase(J,()=>gh)}}),DE=CL.reducer;var FE=(e={})=>{let t,n=!0,r={getStyleSuggestions:lo,debounce:500,...e};return o=>i=>s=>{var y;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(!((y=u.conversation.current)==null?void 0:y.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 bL(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end}var jE=(e={})=>{let t={getTextSuggestions:Cn,getAutocompleteSuggestions:ha,debounce:200,check:Qc,...e},n;return r=>o=>i=>{var h;let{input:{userCommitted:s}}=r.getState(),a=o(i),l=r.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:u,showTabCompletion:c}=l.settings,f=(h=l.conversation.current)==null?void 0:h.id,d=i.type===$c.toString();if(!f||!u&&!c)return a;let{input:{userCommitted:y}}=l;return bL(y,s)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let g=oi(l);g===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(g))},d?0:t.debounce)),a}};var HE=lo.fulfilled.toString();function TL(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 BE=e=>t=>n=>r=>{var c;if(r.type!==HE){n(r);return}let o=t.getState().styleSuggestions.list;n(r);let i=t.getState(),s=i.styleSuggestions.list,a=(c=i.conversation)==null?void 0:c.current,{agentInfo:l}=i.info;if(o===s)return;let u=TL(o,s);r.type===HE&&u.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,agentId:l.agentId??(a==null?void 0:a.agentId),agentName:l.agentName??(a==null?void 0:a.agentName),agentEmail:l.agentEmail??(a==null?void 0:a.agentEmail),data:{keywordMatches:u}})};var kL=Nu({activeSuggestion:aw,answer:Zw,auth:_w,autoflows:V1,conversation:Ux,contentTypes:Dw,customMessages:Z1,exchangeToken:nE,entities:Bw,handlingTime:NE,info:N_,input:$m.reducer,overlayInput:Ge.reducer,settings:Ax,profile:t1,search:B_,summary:$w,styleSuggestions:DE,ui:fw,textSuggestions:nw});function UE(e){return j0({reducer:kL,middleware:t=>[...t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI,deepdeskBrokerAPI:e.deepdeskBrokerAPI}},serializableCheck:!1}),ME(),jE({debounce:200}),FE({debounce:500}),BE(e.deepdeskAPI),...e.middleware?e.middleware:[]],preloadedState:e.preloadedState})}var PL=e=>{var t;return((t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())??"unknown"},RL=e=>t=>n=>r=>{var a;let o=t.getState(),i=Bm("inlineSuggestions")(o);switch(r.type){case bn.toString():{let l=Q_(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 xi.toString():{!r.payload&&e.emit("logout",void 0);break}case Ft.toString():{let{start:l,end:u}=o.input.selection;e.emit("select-suggestion",{type:PL(r.payload.suggestion),...r.payload,replace:r.payload.replace==="selection"?{start:l,end:u}:{start:0,end:u}},{mayApplyChanges:!0});break}case Sc.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 na.toString():{let l=t.getState(),{text:u,selection:c}=l.input.userCommitted;e.emit("reset",{text:u,selectionAfter:c},{mayApplyChanges:!0});break}case Ec.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 zt.fulfilled.toString():r.payload.length>0&&e.sendEvent("entities found",{conversationId:o.conversation.current.id,data:{entities:r.payload}});break;case Pn.fulfilled.toString():e.sendEvent("conversation summarized",{conversationId:o.conversation.current.id,data:{inputText:JSON.stringify(r.payload.original),summary:r.payload.summary}});break;case it.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 xc.toString():e.handleKeyDown(r.payload);break;case ta.toString():e.logSendMessage(r.payload);break;case _c.toString():e.logSendEditSuggestionMessage(r.payload);break;case wc.toString():e.handleInputChanged(r.payload);break;default:break}let s=n(r);switch(r.type){case ta.toString():e.handleAfterSendMessage(r.payload);break;case ya.toString():e.onUpdateShowTabHint(r.payload);break;case Sd.toString():e.logHandlingTime();break;case Ft.toString():{i&&(t.dispatch(gr([])),t.dispatch(hr()));break}default:break}return s},zE=RL;function hh(e){return e.toISOString().replace("T"," ").replace("Z","")}function VE(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:hh(n),timeStop:hh(r)}}function yh(e,t,n){var b,R,P;let{text:r,metrics:{numCharsTyped:o,numCharsPasted:i,numCharsCut:s,numCharsDeleted:a,numPaste:l,agentStartedTypingTimestamp:u,externalTimeTotalSeconds:c,pastes:f,cuts:d,deletions:y,textSuggestions:v,offeredTextSuggestions:h}}=t[e],g=r.length,p=v.reduce((N,{text:V,searchTerm:B})=>N+V.length-(B?B.length:0),0),x=u??Date.now(),_=(Date.now()-x)/1e3+(c||0),C=o/_,w=v.reduce((N,{searchTerm:V})=>N+(V?V.length:0),0);return{conversationId:t.conversation.current.id,source:"agent",text:r,clientVersion:n.version,pastes:f,cuts:d,deletions:y,lenTextTyped:o+w,lenTextTotal:g,lenTextAssisted:p,lenTextPasted:i,lenTextCut:s,lenTextDeleted:a,timeTotalSeconds:_,charsPerSecond:C,numPastes:l,textSuggestionsV2:v,suggestionsCounters:[{source:"gpt",countOffered:h.filter(N=>N.source==="gpt").length}],agentId:(b=t.info.agentInfo)==null?void 0:b.agentId,agentName:(R=t.info.agentInfo)==null?void 0:R.agentName,agentEmail:(P=t.info.agentInfo)==null?void 0:P.agentEmail}}function KE(e,t){let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;return r instanceof HTMLElement?KE(r,t):null}function WE(e,t){return KE(e,t)}function $E(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function xd(e){return e instanceof HTMLElement&&(Ln(e)||Nc(e))}var qE=(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{U.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function IL(e){return e.offsetParent!==null}function GE(e){if(!IL(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 _d(e,t,n=100){let r=GE(e);t({isVisible:r});let o=setInterval(()=>{let i=GE(e);i!==r&&(r=i,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var ut=S(E()),XE=qE("showTabHint",!0),Fa=class e{static version="10.1.8";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 Fn(u,{token:i,fetch:s}),this.version=r,this.instanceId=e.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[zE({emit:(f,d,y)=>this.emit(f,d,y),handleAfterSendMessage:f=>this.handleAfterSendMessage(f),handleInputChanged:f=>this.handleInputChanged(f),handleKeyDown:f=>this.handleKeyDown(f),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:f=>this.logSendMessage(f),logSendEditSuggestionMessage:f=>this.logSendEditMessage(f),onUpdateShowTabHint:f=>XE.update(f),sendEvent:(f,d)=>this.deepdeskApi.sendEvent(f,d)})]};n&&Object.assign(c,{deepdeskBrokerAPI:new Da(n)}),this.store=UE(c),this.broadcastEvents=new RE({debug:!0,deepdeskUrl:u,eventMap:ww(this.store),createCustomChannel:l}),this.store.dispatch(Js),this.store.dispatch(ya(XE.value())),this.store.dispatch(Js({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?(U.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(U.warn("Profile has not been loaded (yet)"),!0):(U.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(xi(null)),this.store.dispatch(wr()),new Promise(t=>{let n=this.store.subscribe(()=>{let r=this.store.getState();Tn(r)&&gw(r)!=="loading"&&t()});this.unmountHandlers.push(()=>{n()})})}isLoggedIn(){return this.deepdeskApi.isLoggedIn()}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){U.warn("Failed to attach user:",n)}}async isConversationSupported(t,n){return(await this.store.dispatch(Km({sessionId:t,options:n}))).payload}async createConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(pc(t))).payload}async getConversationBySessionId(t,n){return this.hasConversation()&&this.sessionId()!==t&&this.resetConversation(),(await this.store.dispatch(mc({sessionId:t,options:n}))).payload}async upsertConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(Wm(t))).payload}async postMessages(t){return(await this.store.dispatch(hc(t))).payload}async updateConversation(t){return(await this.store.dispatch(gc(t))).payload}resetConversation(){this.store.dispatch(J()),this.dynamicThunkObject.conversationQuery=null}async getSummary(){let t=await this.store.dispatch(Pn());if(t.error)throw new Error(t.error.message);return t.payload.summary}configure(t){this.store.dispatch(Js(t))}setVisitorInfo(t){this.store.dispatch(O_(t))}async setAgentInfo(t){await this.store.dispatch(fa(t))}async setAgentSettings(t){await this.store.dispatch(hg(t))}async getAgentSettings(){return(await this.store.dispatch(yg())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();let t=[];return this.store.dispatch($c()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})}notifyInputChanged(t){this.store.dispatch(wc(t))}syncInputHtml(t){this.store.dispatch(e_(t))}notifyKeyDown(t){this.store.dispatch(xc(t))}notifyPaste(t,n){this.store.dispatch(Zx({text:t,selectionText:n}))}notifyCut(t){this.store.dispatch(Qx(t))}notifyExternalSuggestion(t){this.store.dispatch(Ft(t)),this.store.dispatch(hr())}notifyEditSuggestion(t){this.store.dispatch(ew(t.contentType,t.suggestions)),this.store.dispatch(bn({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(Si({collapse:!1})),this.inputMediator&&this.store.dispatch(Kx({text:t,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(gr([])))}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(Yx(vc(t))),!(t.key!=="Tab"&&!this.settings.showTextSuggestions))switch(t.key){case"Up":case"ArrowUp":if(n||!a||!i||t.shiftKey)return;this.store.dispatch(qx()),s||this.stageSelectedSuggestion({inputType:"arrow"}),t.preventDefault();return;case"Down":case"ArrowDown":{if(n||!a||!i||t.shiftKey)return;this.store.dispatch(Xx());let{selectedSuggestionIndex:u}=this.state.input;u===-1?this.store.dispatch(na()):s||this.stageSelectedSuggestion({inputType:"arrow"}),t.preventDefault();return}case"Esc":case"Escape":{l?(this.store.dispatch(Cc(-1)),this.store.dispatch(na()),t.preventDefault()):n||(this.store.dispatch(Si({collapse:!0})),this.store.dispatch(cw(!0)),t.preventDefault());return}case"Tab":{let{userCommitted:u}=this.state.input,c=u.text.substring(0,u.selection.end),{tabCompletionSuggestion:f}=this.state.input;this.store.dispatch(ya(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):this.settings.showTabCompletion&&f&&f.text.startsWith(c)&&(this.store.dispatch(Ft({text:f.text,suggestion:f,eventMetrics:{inputType:"tab"},replace:"until-selection-end"})),this.store.dispatch(hr())),t.preventDefault();break}default:}}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(Jx()),this.store.dispatch(gr([]))}handlingTimeStart(){this.state.handlingTime.startTime||(U.info("Start handling time"),this.store.dispatch(AE()))}handlingTimeStop(){this.state.handlingTime.startTime&&(U.info("Stop handling time"),this.store.dispatch(Sd()))}logSendMessage(t){let n=yh("input",this.state,{version:this.version});t&&Object.assign(n,{text:t}),this.deepdeskApi.sendEventV1("Send Message",n),this.emit("send-message-event",n)}logSendEditMessage(t){let n=yh("overlayInput",this.state,{version:this.version});t&&Object.assign(n,{text:t}),this.store.dispatch($x(this.state.overlayInput.metrics))}logHandlingTime(){let t=VE(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",t),this.store.dispatch(OE())}notifySubmit(t={}){this.shouldAbort()||(this.store.dispatch(hr()),this.store.dispatch(ta(t.text??this.state.input.text)))}stageSelectedSuggestion(t){let n=this.state.input.selectedSuggestionIndex,{textSuggestions:r}=this.state.input;this.store.dispatch(Ft({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){U.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),U.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]=pi(r,o);return i.dataset.testid=t,n!=null&&n.rootNode&&i.classList.add(n.rootNode),this.unmountHandlers.push(()=>{(0,jn.unmountComponentAtNode)(i),s(),i.remove()}),i}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return to(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,n.appendChild(o),this.unmountHandlers.push(()=>{(0,jn.unmountComponentAtNode)(o),o.remove()}),o}mount(t,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!xd(t))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let{customStyles:r={},showStyleSuggestions:o,showTabCompletion:i,showTextSuggestions:s,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,isEmbedded:f,detectSubmit:d,insertLink:y,inputMediator:v,closestScrollSelector:h,appendOverlayTo:g,inlineSuggestions:m}=n;this.configure({showStyleSuggestions:o,showTabCompletion:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,showTextSuggestions:s,insertLink:y,isEmbedded:f,inlineSuggestions:m});let p=h&&WE(t,h)||void 0,x=this.overlayContainerFactory("deepdesk-tab-completion",r,p||t,{appendTo:g,closestScrollElement:p,mirrorOverflow:!0,onRemove:()=>this.unmount()}),_=this.overlayContainerFactory("deepdesk-suggestions-overlay",r,p||t,{appendTo:g});n.automaticHandlingTime&&this.setupHandlingTime(t),(0,jn.render)((0,ut.jsx)(Pa,{store:this.store,customStyles:r,children:(0,ut.jsx)(Sa,{broadcastEvents:this.broadcastEvents,children:(0,ut.jsx)(F1,{inputElement:t})})}),x),(0,jn.render)((0,ut.jsx)(Pa,{store:this.store,customStyles:r,children:(0,ut.jsx)(Sa,{broadcastEvents:this.broadcastEvents,children:(0,ut.jsx)(Jc,{})})}),_),(0,jn.render)((0,ut.jsx)(Pa,{store:this.store,customStyles:r,children:(0,ut.jsx)(Sa,{broadcastEvents:this.broadcastEvents,children:(0,ut.jsx)(s1,{})})}),this.createContainer("deepdesk-overlays")),to(t),this.inputMediator=v||(Ln(t)?new wn(t):new ao(t)),this.inputMediator.on("change",({plainText:w})=>{this.notifyInputChanged(w)}),this.inputMediator.on("updated",({rawHtml:w})=>{w!=null&&this.syncInputHtml(w)}),this.inputMediator.on("keydown",w=>{this.notifyKeyDown(w)}),this.inputMediator.on("paste",({pastedText:w,selectionText:b})=>{this.notifyPaste(w,b)}),this.inputMediator.on("cut",({selectionText:w})=>{this.notifyCut(w)});let C;this.inputMediator.on("selection",w=>{clearTimeout(C),w===null?C=setTimeout(()=>{w!==null&&this.store.dispatch(qm(w))},500):this.store.dispatch(qm(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(vi(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(vi(!0))),this.store.dispatch(Wx({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.whenConversationLoaded(()=>{var w;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&&U.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,showPersonalCollectionLink:i,isEmbedded:s}=n;this.widgetRoot=t,this.configure({showImages:o,showPersonalCollectionLink:i,isEmbedded:s}),(0,jn.render)((0,ut.jsx)(Pa,{store:this.store,customStyles:r,children:(0,ut.jsx)(Sa,{broadcastEvents:this.broadcastEvents,children:(0,ut.jsx)(kE,{})})}),t),this.whenConversationLoaded(()=>{var a;this.broadcastEvents.setSessionId((a=this.state.conversation.current)==null?void 0:a.sessionId)})}unmountWidget(){this.widgetRoot&&(0,jn.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(t){let n=_d(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){$E(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(Ta());let t=Ci(this.state);t&&this.store.dispatch(Js({showSearch:t.search,showAutoflows:t.autoflows,showCustomMessages:t.customMessages,showImageSearch:t.imageSearch,showEntitiesCommand:t.entitiesCommand,showSummaryCommand:t.summarizer,showKnowledgeSearch:t.knowledgeSearch,recommendTextSuggestions:t.recommendTextSuggestions}))}),this.loadProfileConfigPromise)}async checkForTrialMode(t){try{let{account:n}=await this.deepdeskApi.getPlatformConfig();if(!n.isTrial){this.shouldRender=!0;return}if(U.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;U.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=Xc(this.state);try{n.forEach(({type:r})=>{r==="entities"?this.store.dispatch(zt()):this.store.dispatch(Cn(r))})}catch(r){this.handleError(r)}}};async function QE(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 YE(e,t,n={}){let r=n.replace?so(e,n.replace.start,n.replace.end):PE(e),o,i=()=>{if(n.setRange)return n.setRange(r.cloneRange());r.deleteContents(),o=document.createElement("span"),r.insertNode(o),t.split(`
|
|
22
22
|
`).reverse().forEach((s,a)=>{a>0&&r.insertNode(document.createElement("br")),r.insertNode(document.createTextNode(s))}),r.commonAncestorContainer===e&&r.surroundContents(document.createElement("div"))};return Promise.resolve(i()).then(()=>{try{if(n.selectionAfter!==!1){e.focus();let s=n.selectionAfter?so(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 ZE(e){return e.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}async function JE(e,t,n){await new Fn(e).authenticateWithKey(t,n)}async function eC(e){let n=await new Kt(e).get("/platform/config/",{version:null});return re(n)}async function LL(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 tC(e,t){let n=await LL(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 aC(AL);})();
|
|
23
23
|
/*! Bundled license information:
|
|
24
24
|
|