@deepdesk/deepdesk-sdk 11.2.1-beta.2 → 11.2.1-beta.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs.js +2 -2
- package/dist/index.d.mts +2 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.esm.js +2 -2
- package/dist/index.iife.js +2 -2
- package/package.json +1 -1
package/dist/index.iife.js
CHANGED
|
@@ -16,7 +16,7 @@ Try polyfilling it using "@formatjs/intl-pluralrules"
|
|
|
16
16
|
`);return o=o.replace(/\n{3,}/g,`
|
|
17
17
|
|
|
18
18
|
|
|
19
|
-
`),o=o.replace(/\n/g,"<br/>"),o}createContainer(t){var n;let o=(typeof global<"u"&&global.INTERWEAVE_SSR_POLYFILL||JI)();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(XI)||(s.innerHTML=this.convertLineBreaks(this.props.escapeHtml?(0,pE.default)(t):t)),s}extractAttributes(t){let{allowAttributes:n}=this.props,r={},o=0;return t.nodeType!==fE||!t.attributes||([...t.attributes].forEach(i=>{let{name:s,value:a}=i,l=s.toLowerCase(),u=hd[l]||hd[s];if(!this.isSafe(t)||!l.match(QI)&&(!n&&(!u||u===sh)||l.startsWith("on")||a.replace(/(\s|\0|�([9AD]);)/,"").match(/(javascript|vbscript|livescript|xss):/i)))return;let c=l==="style"?this.extractStyleAttribute(t):a;u===Hr?c=!0:u===Ao?c=Number.parseFloat(String(c)):u!==gd&&(c=String(c)),r[ah[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 Ba[t]?{...n,...Ba[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===fE){let d=c.nodeName.toLowerCase(),m=this.getTagConfig(d);u&&(l.push(u),u="");let y=this.applyNodeFilters(d,c);if(!y)return;let v;if(s&&!(a&&!this.isTagAllowed(d))){this.keyIndex+=1;let p=this.keyIndex;v=this.parseNode(y,m);let g=s(y,v,m);if(g===null)return;if(typeof g<"u"){l.push(Io.default.cloneElement(g,{key:p}));return}this.keyIndex=p-1}if(this.banned.has(d))return;if(!(r||o&&d!=="br")&&this.isTagAllowed(d)&&(i||this.canRenderChild(n,m))){var f;this.keyIndex+=1;let p=this.extractAttributes(y),g={tagName:d};p&&(g.attributes=p),m.void&&(g.selfClose=m.void),l.push(Io.default.createElement(yd,{...g,key:this.keyIndex},(f=v)!==null&&f!==void 0?f:this.parseNode(y,m)))}else l=[...l,...this.parseNode(y,m.tagName?m:n)]}else if(c.nodeType===YI){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(ZI);){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],m;if(u)m=s.length,r.push(f.createElement(c,d));else{let y=o.match(new RegExp(`{{{/${a}}}}`));m=y.index+y[0].length,r.push(f.createElement(this.replaceTokens(o.slice(s.length,y.index),n),d))}o=o.slice(m)}return o.length>0&&r.push(o),r.length===0?"":r.length===1&&typeof r[0]=="string"?r[0]:r}};function eO(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 m=new vd(i??"",e).parse();m.length>0&&(d=m)}return d||(d=s),f?Io.default.createElement(Io.default.Fragment,null,d):Io.default.createElement(yd,{attributes:n,className:r,tagName:c},d)}function $i(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,...m}=e,y=i?[]:l,v=o?[]:a,p=c?[c]:[],g=u?[u]:[];y.forEach(T=>{T.onBeforeParse&&p.push(T.onBeforeParse.bind(T)),T.onAfterParse&&g.push(T.onAfterParse.bind(T))});let h=p.reduce((T,C)=>C(T,e),r??""),S=new vd(h,m,y,v),x=g.reduce((T,C)=>C(T,e),S.parse());return Io.default.createElement(eO,{attributes:t,className:n,containerTagName:e.containerTagName,emptyContent:s,noWrap:d,parsedContent:x.length===0?void 0:x,tagName:f})}var tO=/[.*+?^${}()|[\]\\]/g,nO=/[^0-9A-Za-zÀ-ÖØ-öø-ÿ](?=[0-9A-Za-zÀ-ÖØ-öø-ÿ]*$)/;function rO(e){return e.replace(tO,"\\$&")}function oO(e,t){let n=e.split("").findIndex((r,o)=>r!==t[o]);return n>-1?n:Math.min(e.length,t.length)}function iO(e){return e.search(nO)}function mE(e,t=[]){let n=e;return t.forEach(r=>{if(!r)return;let o=new RegExp(`\\b(${rO(r)})\\b`,"gi");n=n.replace(o,"<strong>$1</strong>")}),n}function gE(e){return e.replace(Hl,'<mark data-type="placeholder">$1</mark>')}function Wi(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function sO(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 uh(e,t,n={}){if(t){let r=oO(t.toLowerCase(),e.toLowerCase()),o=Wi(e.substring(r,e.length));if(n.stripAgentPart){let l=e.substring(0,r),u=iO(l);return`<span style="opacity: 0.5">${l.substring(u+1)}</span>${o}`}let s=t.split(Iv).length>3||t.length>30?sO(t.trim(),r):0;return`${`${s>0?"\u2026":""}${Wi(e.substring(s,r))}`}<strong>${o}</strong>`}return e}var aO=/(<\/[a-zA-Z]+[0-9]?>|<[a-zA-Z]+\s?\/>|<br>)/i;function Sd(e){return aO.test(e)}function hE(e){let t=document.createElement("template");return t.innerHTML=e,t.content.textContent??""}var He=w(D()),yE=w(te());var ch={root:"Le",trigger:"_",content:"Me",contentOpen:"Re",contentTop:"Te",contentBottom:"Ue",item:"oo"};var Oo=w(b()),uO=0,vE=He.default.createContext(null),cO=()=>{let e=(0,He.useContext)(vE);if(!e)throw new Error("Invalid DropdownContext");return e},SE=({trigger:e,children:t,position:n="bottom"})=>{let r=(0,He.useMemo)(()=>++uO,[]),o=(0,He.useRef)(null),i=(0,He.useRef)(null),s=A("Dropdown",ch),[a,l]=(0,He.useState)(!1),[u,c]=(0,He.useState)(n),f=m=>{m.preventDefault(),m.stopPropagation(),l(!a)},d=(0,He.useCallback)(([m])=>{!m.isIntersecting&&a&&c(u==="top"?"bottom":"top")},[a]);return(0,He.useEffect)(()=>{let m=y=>{o.current&&!o.current.contains(y.target)&&l(!1)};return document.addEventListener("click",m),()=>{document.removeEventListener("click",m)}},[]),(0,He.useEffect)(()=>{if(!i.current&&!a)return()=>{};let m=new IntersectionObserver(d,{root:null,rootMargin:"0px",threshold:1});return i.current&&m.observe(i.current),()=>{i.current&&m.unobserve(i.current)}},[i,a]),(0,Oo.jsx)(vE.Provider,{value:{setIsOpen:l},children:(0,Oo.jsxs)("div",{ref:o,className:s.root,children:[(0,Oo.jsx)("button",{id:`dropdown-${r}`,"data-testid":"dropdown-trigger","aria-haspopup":"true","aria-expanded":a,"aria-label":"Dropdown trigger",type:"button",className:s.trigger,onClick:f,children:e}),(0,Oo.jsx)("div",{"data-testid":"dropdown-content",ref:i,"aria-hidden":!a,"aria-labelledby":`dropdown-${r}`,className:(0,yE.default)(s.content,{[s.contentOpen]:a,[s.contentTop]:u==="top",[s.contentBottom]:u==="bottom"}),children:t})]})})};function dO({as:e,children:t,onClick:n,...r}){let o=e||"button",i=A("Dropdown",ch),{setIsOpen:s}=cO(),a=l=>{s(!1),n(l),l.stopPropagation()};return(0,Oo.jsx)(o,{type:"button",className:i.item,onClick:a,...r,children:t})}SE.Item=dO;var dh=SE;var fh=w(b()),wE=e=>(0,fh.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"16",width:"14",viewBox:"0 0 448 512",...e,children:(0,fh.jsx)("path",{fill:"currentColor",d:"M8 256a56 56 0 1 1 112 0A56 56 0 1 1 8 256zm160 0a56 56 0 1 1 112 0 56 56 0 1 1 -112 0zm216-56a56 56 0 1 1 0 112 56 56 0 1 1 0-112z"})});var No={};Qe(No,{enUS:()=>fO,nlNL:()=>pO});var fO={preview:[{type:0,value:"Preview"}],useSuggestion:[{type:0,value:"Add"}],sendSuggestion:[{type:0,value:"Send"}],suggestionSent:[{type:0,value:"Sent"}],sendingError:[{type:0,value:"Sending failed"}],tryAgain:[{type:0,value:"Try again"}],editSuggestion:[{type:0,value:"Edit"}],visitUrl:[{type:0,value:"Visit"}],giveFeedback:[{type:0,value:"Give feedback"}],answer:[{type:0,value:"Answer"}]},pO={preview:[{type:0,value:"Preview"}],useSuggestion:[{type:0,value:"Gebruik"}],sendSuggestion:[{type:0,value:"Verzenden"}],suggestionSent:[{type:0,value:"Verzonden"}],sendingError:[{type:0,value:"Verzenden mislukt"}],tryAgain:[{type:0,value:"Probeer opnieuw"}],editSuggestion:[{type:0,value:"Bewerken"}],visitUrl:[{type:0,value:"Bekijk"}],giveFeedback:[{type:0,value:"Geef feedback"}],answer:[{type:0,value:"Antwoord"}]};var wd=w(b()),mO="%0d%0a%0d%0a%0d%0a",gO=(e,t)=>{let n=[`Suggestie: ${encodeURIComponent(t)}`,"Beschrijf je feedback:"];return`mailto:${e.join(",")}?subject=Suggestie feedback&body=${n.join(mO)}`},hO=({suggestion:e,onFeedback:t})=>{let n=G(No),r=j("suggestionFeedbackEmailAddresses");return!r||r.length===0?null:(0,wd.jsx)(dh,{trigger:(0,wd.jsx)(wE,{"data-testid":"feedback-dropdown-trigger"}),children:(0,wd.jsx)(dh.Item,{as:"a",href:gO(r,e),onClick:t,children:n("giveFeedback")})})},xd=hO;var Ed=w(D()),CE=w(b()),xE=Ed.default.createContext(void 0);function Ur(){let e=Ed.default.useContext(xE);if(e===void 0)throw new Error("useCommandPalette must be used within the CommandPalette component");return e}var EE=({children:e,page:t,isOpen:n,onChangeOpen:r,selected:o,setSelected:i})=>{let s=Ed.default.useMemo(()=>({page:t,isOpen:n,onChangeOpen:r,selected:o,setSelected:i}),[n,t,o]);return(0,CE.jsx)(xE.Provider,{value:s,children:e})};var Ct=w(b());function ph({closeOnSelect:e=!0,lineClamp:t,children:n,onClick:r,onFeedback:o,onSourceClick:i,description:s,sources:a,id:l,styles:u,...c}){let{selected:f,onChangeOpen:d}=Ur(),m=A("CommandPalette",Vt);function y(v){r(v),e&&d(!1)}return(0,Ct.jsxs)("div",{className:(0,ja.default)(m.listItem,l===f&&m.listItemSelected),children:[(0,Ct.jsx)("button",{type:"button",className:(0,ja.default)(m.listItemAction,m.listItemPrimaryAction),"aria-disabled":c.disabled??!1,onClick:y,"data-command-palette-item":!0,"data-item-id":l,...c,children:(0,Ct.jsxs)("div",{className:m.listItemContent,children:[typeof n=="string"?(0,Ct.jsx)("p",{className:(0,ja.default)(m.listItemText,m.truncate,u==null?void 0:u.title),children:n}):n,s&&(0,Ct.jsx)($i,{tagName:"p",allowList:[],content:Sd(s)?hE(s):s,className:(0,ja.default)(m.listItemDescription,u==null?void 0:u.description,t?m.lineClamp:m.truncate)})]})}),o&&(0,Ct.jsx)("div",{className:m.listItemActions,children:(0,Ct.jsx)(xd,{suggestion:String(n),onFeedback:o})}),a&&(0,Ct.jsxs)("div",{className:m.sources,children:[(0,Ct.jsx)("span",{className:m.sourcesTitle,children:"Sources"}),a.map(v=>v.url?(0,Ct.jsx)("a",{className:m.source,href:v.url,target:"_blank",title:v.url,rel:"noopener noreferrer",onClick:()=>i&&i(v),children:v.name},v.url):(0,Ct.jsx)("span",{className:m.source,children:v.name},v.name))]})]})}var za=w(b()),bE=()=>(0,za.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 256 512","aria-labelledby":"angleLeftTitle",children:[(0,za.jsx)("title",{id:"angleLeftTitle",children:"AngleLeft"}),(0,za.jsx)("path",{d:"M192 448c-8.188 0-16.38-3.125-22.62-9.375l-160-160c-12.5-12.5-12.5-32.75 0-45.25l160-160c12.5-12.5 32.75-12.5 45.25 0s12.5 32.75 0 45.25L77.25 256l137.4 137.4c12.5 12.5 12.5 32.75 0 45.25C208.4 444.9 200.2 448 192 448z"})]});var Mo=w(b());function mh({children:e,title:t,id:n,onDismiss:r}){let o=G(Po),i=A("CommandPalette",Vt),{page:s}=Ur();return s!==n?null:(0,Mo.jsxs)("div",{className:i.page,id:`page_${n}`,tabIndex:-1,children:[r&&(0,Mo.jsxs)("div",{className:i.pageNav,children:[(0,Mo.jsxs)("button",{className:i.pageBackButton,type:"button",onClick:r,children:[(0,Mo.jsx)(bE,{}),o("back")]}),t&&(0,Mo.jsx)("h3",{className:i.pageTitle,children:t})]}),e]})}var TE=w(D());var Va=w(b()),qi=()=>(0,Va.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 0 24 24",width:"1em",fill:"currentColor",children:[(0,Va.jsx)("path",{d:"M0 0h24v24H0z",fill:"none"}),(0,Va.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 sn=w(b());function yO({onChange:e,onChangeType:t,placeholder:n,typePlaceholder:r,types:o,value:i,selectedType:s},a){let l=A("CommandPalette",Vt);return(0,sn.jsxs)("div",{className:l.search,children:[(0,sn.jsx)("div",{className:l.searchIcon,children:(0,sn.jsx)(qi,{})}),(0,sn.jsxs)("div",{className:l.searchInputWrapper,children:[(0,sn.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,sn.jsx)("div",{className:l.selectWrapper,children:(0,sn.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,sn.jsx)("option",{children:r}),o.map(u=>(0,sn.jsx)("option",{value:u.value,children:u.label},u.value))]})})]})]})}var kE=(0,TE.forwardRef)(yO);var gh=w(te());var Cd=w(b()),vO=({onClick:e,shortKeys:t,children:n,...r})=>{let o=A("CommandPalette",Vt);return(0,Cd.jsxs)("button",{type:"button",...r,onClick:e,className:(0,gh.default)(o.actionButton,r.className,{[o.hasShortKeys]:t&&t.length>0}),children:[n,t&&t.map(i=>(0,Cd.jsx)("span",{className:(0,gh.default)(o.actionShortcut,i===8629&&o.actionShortcutFixKerning),children:typeof i=="number"?String.fromCharCode(i):i},i))]})},PE=vO;var Ka=w(b()),SO="[data-command-palette-item]";function Gi({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[m,y]=(0,qn.useState)(),v=(0,qn.useRef)(null),p=()=>{o&&o(n),s(void 0),i(""),a(!1)},g=()=>{var N;if(r!==n&&o){o(n);return}if(l&&s){s(void 0),(N=v.current)==null||N.focus();return}if(d.length>0){i("");return}a(!1)},h=()=>{let N=S();N.length!==0&&y(N[0].dataset.itemId)},S=()=>Array.from(document.querySelectorAll(SO)||[]),x=N=>document.querySelector(`[data-item-id=${N}]`),T=N=>{let V=x(N);V&&y(V.dataset.itemId)},C=N=>{let V=x(N);V&&V.scrollIntoView({behavior:"smooth"})},k=()=>{if(!m)return;let N=S(),V=x(m);if(!V)return;let _=N.indexOf(V),ee=N[_+1];ee&&ee.dataset.itemId?T(ee.dataset.itemId):h()},L=()=>{if(!m)return;let N=S(),V=x(m);if(!V)return;let _=N.indexOf(V),ee=N[_-1];ee&&ee.dataset.itemId?T(ee.dataset.itemId):T(N[N.length-1].dataset.itemId)},I=(0,qn.useCallback)(N=>{switch(N.key){case"ArrowDown":{N.preventDefault(),k();break}case"ArrowUp":{N.preventDefault(),L();break}case"Enter":{if(m){let V=x(m);V==null||V.click()}break}}},[m]);return(0,qn.useEffect)(()=>{h()},[d,r,l,f]),(0,qn.useEffect)(()=>{m&&C(m)},[m]),(0,Ka.jsx)(ud,{autoFocus:!0,contentAriaLabel:"Search Results",overlayAriaLabel:"Command Palette",isOpen:f,onBack:g,onClose:p,onKeyDown:I,children:(0,Ka.jsxs)(EE,{selected:m,setSelected:y,isOpen:f,onChangeOpen:a,page:r,children:[r===n&&(0,Ka.jsx)(kE,{ref:v,onChange:i,onChangeType:s,placeholder:e,value:d,selectedType:l,types:u,typePlaceholder:t}),c]})})}Gi.Page=mh;Gi.List=eh;Gi.Image=sE;Gi.ListItem=ph;Gi.Button=PE;var ge=Gi;var RE=w(D());function AE(e,t){(0,RE.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 $a=w(D());var LE={data:null,fetchState:"idle"},bd=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},an=B("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)}),wO=e=>e.filter((t,n)=>n===e.findIndex(r=>r.text===t.text)),xO=W({name:"entities",initialState:LE,reducers:{},extraReducers:e=>{e.addCase(an.pending,t=>{t.fetchState="loading"}).addCase(an.rejected,t=>{t.fetchState="error"}).addCase(an.fulfilled,(t,n)=>{t.fetchState="done",t.data=wO(t.data?[...t.data,...n.payload]:n.payload)}).addCase(le,()=>LE)}}),IE=xO.reducer;var hh={};Qe(hh,{enUS:()=>EO,nlNL:()=>CO});var EO={noResults:[{type:0,value:"No entities have been found"}],copy:[{type:0,value:"Copy"}],use:[{type:0,value:"Use"}]},CO={noResults:[{type:0,value:"Er zijn geen entiteiten gevonden"}],copy:[{type:0,value:"Kopieer"}],use:[{type:0,value:"Gebruik"}]};var OE={root:"Be",empty:"De"};var Yi=w(b()),TO=({onCopy:e})=>{let t=(0,$a.useRef)(null),n=A("EntitiesList",OE),r=O(bd),{setSelected:o}=Ur(),i=G(hh),s=Y();return(0,$a.useEffect)(()=>{s(an())},[]),(0,$a.useEffect)(()=>{t.current&&(t.current.focus(),o("entity-0"))},[t]),(0,Yi.jsxs)("div",{className:n.root,ref:t,tabIndex:-1,children:[r&&r.length>0&&(0,Yi.jsx)(ge.List,{children:r.map((a,l)=>(0,Yi.jsx)(ge.ListItem,{id:`entity-${l}`,closeOnSelect:!0,onClick:()=>e(a),children:a.text},a.text))},"entities"),r&&r.length===0&&(0,Yi.jsx)("p",{className:n.empty,children:i("noResults")})]})},NE=TO;var ln=w(D());var ME={data:null,fetchState:"idle"},_E=e=>e.summary.data,DE=e=>e.summary.fetchState==="error",FE=e=>e.summary.model,Gn=B("summary/getSummary",async(e,t)=>{var c,f,d;let n=t.getState().profile.data,r=(c=t.getState().conversation.current)==null?void 0:c.sessionId,o=(d=(f=t.getState().info)==null?void 0:f.agentInfo)==null?void 0:d.agentId;if(!n)throw new Error("Profile is not defined");let{deepdeskAPI:i,dynamicThunkObject:s}=t.extra;if(!s.conversationQuery)return Promise.reject(new Error("setConversationQuery method is not defined"));let a=s.conversationQuery,l=await a();if(l.length===0)return Promise.reject(new Error("No messages are included"));let u=await i.getSummary(l,{externalConversationId:r,agentId:o,promptInstruction:n.summarizerPromptInstruction,model:n.summarizerModel});return u.summary?u:Promise.reject(new Error("Summary is not provided"))}),kO=W({name:"summary",initialState:ME,reducers:{},extraReducers:e=>{e.addCase(Gn.pending,t=>{t.data=null,t.fetchState="loading"}).addCase(Gn.rejected,t=>{t.data=null,t.fetchState="error"}).addCase(Gn.fulfilled,(t,n)=>{t.fetchState="done",n.payload&&(t.data=n.payload.summary,t.model=n.payload.model)}).addCase(le,()=>ME)}}),HE=kO.reducer;var yh={};Qe(yh,{enUS:()=>PO,nlNL:()=>RO});var PO={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."}]},RO={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 UE={root:"Ie",actions:"Oe",main:"Xe",textInput:"eo",loading:"Je",error:"Ke"};var Yn=w(b()),LO=({onCopy:e})=>{let t=(0,ln.useRef)(null),n=A("SummaryForm",UE),[r,o]=(0,ln.useState)(""),i=G(yh),s=O(FE),a=O(_E),l=O(DE),u=Y(),c=()=>{u(Ye({name:"summary copied to clipboard",data:{originalText:a,finalText:r,model:s},options:{includeConversationData:!0}})),e(r)},f=()=>{let d=document.getSelection();d&&u(Ye({name:"summary copied to clipboard",data:{originalText:a,finalText:d==null?void 0:d.toString(),model:s},options:{includeConversationData:!0}}))};return(0,ln.useEffect)(()=>{u(Gn())},[]),(0,ln.useEffect)(()=>{o(a||"")},[a]),(0,ln.useEffect)(()=>{t.current&&a&&t.current.focus()},[t,a]),(0,ln.useEffect)(()=>{let d=m=>{m.key==="Enter"&&m.shiftKey&&c()};return document.addEventListener("keydown",d),()=>{document.removeEventListener("keydown",d)}},[r]),(0,Yn.jsx)("div",{className:n.root,tabIndex:-1,children:l?(0,Yn.jsx)("p",{className:n.error,children:i("error")}):(0,Yn.jsxs)(ln.Fragment,{children:[(0,Yn.jsx)("div",{className:n.main,children:(0,Yn.jsx)("textarea",{placeholder:a?void 0:i("loading"),disabled:!a,className:n.textInput,ref:t,value:r,onCopy:f,onChange:d=>o(d.target.value)})}),(0,Yn.jsx)("div",{className:n.actions,children:(0,Yn.jsx)(ge.Button,{shortKeys:[8679,8629],onClick:c,children:i("copy")})})]})})},BE=LO;var Wa={};Qe(Wa,{enUS:()=>IO,nlNL:()=>OO});var IO={personalCollectionLink:[{type:0,value:"Go to Personal Collection"}],searchPlaceholder:[{type:0,value:"Start typing to search..."}],urlSuggestions:[{type:0,value:"Link suggestions"}],personalSuggestions:[{type:0,value:"Personal suggestions"}],pinnedMessages:[{type:0,value:"Pinned messages"}],imageSuggestions:[{type:0,value:"Images"}],typePlaceholder:[{type:0,value:"All types"}],navigation:[{type:0,value:"Navigation"}],entitiesClipboard:[{type:0,value:"Conversation clipper"}],entitiesTitle:[{type:0,value:"Copy to your clipboard"}],summaryClipboard:[{type:0,value:"Summarize conversation"}],summaryTitle:[{type:0,value:"Conversation summary"}],knowledgeAssist:[{type:0,value:"Knowledge assist"}],commands:[{type:0,value:"Commands"}],use:[{type:0,value:"Use"}],preview:[{type:0,value:"Preview"}],warning:[{type:0,value:"Are you sure you want to discard the message?"}]},OO={personalCollectionLink:[{type:0,value:"Ga naar persoonlijke collectie"}],searchPlaceholder:[{type:0,value:"Begin met typen om te zoeken..."}],personalSuggestions:[{type:0,value:"Persoonlijke suggesties"}],urlSuggestions:[{type:0,value:"Link suggesties"}],imageSuggestions:[{type:0,value:"Afbeeldingen"}],navigation:[{type:0,value:"Navigatie"}],typePlaceholder:[{type:0,value:"Alle types"}],pinnedMessages:[{type:0,value:"Actueel"}],entitiesClipboard:[{type:0,value:"Klembord"}],entitiesTitle:[{type:0,value:"Kopieer naar klembord"}],summaryClipboard:[{type:0,value:"Gesprek samenvatten"}],summaryTitle:[{type:0,value:"Gesprek samenvatting"}],knowledgeAssist:[{type:0,value:"Knowledge assist"}],commands:[{type:0,value:"Acties"}],use:[{type:0,value:"Gebruik"}],preview:[{type:0,value:"Bewerk"}],warning:[{type:0,value:"Weet je zeker dat je de wijzigingen wilt weggooien?"}]};var Br=w(D());var vh={};Qe(vh,{enUS:()=>NO,nlNL:()=>MO});var NO={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"}]},MO={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 jE={root:"io",title:"Pe",empty:"Qe",status:"Ve",form:"ro",input:"to",submit:"We",question:"Ze",answer:"_e",alignRight:"oi"};var DO={data:null,fetchState:"idle"},zE=e=>{var t;return(t=e.knowledgeAssistant)==null?void 0:t.data},qa=B("knowledgeAssistant/getKnowledgeAssistant",async(e,t)=>{var s;let{deepdeskAPI:n}=t.extra,r=t.getState(),o=r.conversation.current;if(!o||!o.profileCode)throw new Error("No conversation of conversation profileCode found");let i=(s=r.profile.data)==null?void 0:s.knowledgeAssistant;return i?n.getKnowledgeAssistant(i):null}),FO=W({name:"knowledgeAssistant",initialState:DO,reducers:{},extraReducers:e=>{e.addCase(qa.pending,t=>{t.fetchState="loading"}).addCase(qa.rejected,t=>{t.fetchState="error"}).addCase(qa.fulfilled,(t,n)=>{t.fetchState="done",t.data=n.payload})}}),VE=FO.reducer;var Sh={data:[],fetchState:"idle"},KE=e=>{var t;return(t=e.answer)==null?void 0:t.data},$E=e=>e.answer.fetchState,Qi=we("answer/resetKnowledgeSearch"),Xi=B("answer/getAnswer",async(e,t)=>{var l,u,c;let{deepdeskAPI:n}=t.extra,r=t.getState().answer.data,o=zE(t.getState()),i=(l=t.getState().conversation.current)==null?void 0:l.sessionId,s=(c=(u=t.getState().info)==null?void 0:u.agentInfo)==null?void 0:c.agentId;if(!o)throw new Error("KnowledgeAssistant is not defined");let a=await n.knowledgeAssist({promptInstruction:o.prompt,question:e},r,o.code,{agentId:s,conversationId:i});return{question:e,answer:a}}),HO=W({name:"answer",initialState:Sh,reducers:{},extraReducers:e=>{e.addCase(Xi.pending,t=>{t.fetchState="loading"}).addCase(Xi.rejected,t=>{t.fetchState="error"}).addCase(Xi.fulfilled,(t,n)=>{t.fetchState="done",t.data=[...t.data,n.payload]}).addCase(le,()=>Sh).addCase(Qi,()=>Sh)}}),WE=HO.reducer;var Ga=w(b()),qE=()=>(0,Ga.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 512 512","aria-labelledby":"paperPlaneTitle",children:[(0,Ga.jsx)("title",{id:"paperPlaneTitle",children:"PaperPlane"}),(0,Ga.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 bt=w(b()),UO=({onUse:e,onResetQuestion:t,question:n})=>{let[r,o]=Br.default.useState(""),{setSelected:i}=Ur(),s=(0,Br.useRef)(null),a=A("EntitiesList",jE),l=G(vh),u=Y(),c=O(KE),f=O($E),d=async y=>{y.preventDefault(),y.stopPropagation(),r!==""&&u(Xi(r))},m=(y,v)=>{u(Ye({name:"knowledge assist source viewed",data:{question:v,sourceViewed:y.url||y.name},options:{includeConversationData:!0}}))};return(0,Br.useEffect)(()=>{var y;n&&f==="idle"?u(Xi(n)):(y=s.current)==null||y.focus()},[s,f]),(0,Br.useEffect)(()=>{f==="done"&&(u(Ye({name:"knowledge assist question answered",data:{question:r||n,sources:c[c.length-1].answer.sources,answer:c[c.length-1].answer.answer,isFollowUpQuestion:c.length>1},options:{includeConversationData:!0}})),i(`knowledge-assist-${c.length-1}`),o(""))},[f,c]),(0,Br.useEffect)(()=>{s.current&&s.current.scrollIntoView({behavior:"smooth"})},[s,c]),(0,bt.jsxs)("div",{className:a.root,children:[c.length>0&&(0,bt.jsx)("div",{className:a.alignRight,children:(0,bt.jsx)(ge.Button,{onClick:t,children:l("reset")})}),c.map(({question:y,answer:v},p)=>(0,bt.jsx)(ge.List,{children:(0,bt.jsx)(ge.ListItem,{id:`knowledge-assist-${p}`,"data-testid":"knowledge-search-answer",description:v.answer,closeOnSelect:!0,onClick:()=>e(v.answer),onSourceClick:g=>m(g,y),sources:v.sources,styles:{title:a.question,description:a.answer},children:y})},`${v.answer}_${p}`)),f==="loading"&&(0,bt.jsx)("p",{className:a.status,children:l("loading")}),f==="error"&&(0,bt.jsx)("p",{className:a.status,children:l("error")}),(0,bt.jsxs)("form",{className:a.form,onSubmit:d,children:[(0,bt.jsx)("input",{ref:s,placeholder:l("anotherQuestion"),className:a.input,type:"text",value:r,onFocus:()=>{i(void 0)},onChange:y=>{i(void 0),o(y.target.value)}}),(0,bt.jsx)("button",{type:"submit",className:a.submit,children:(0,bt.jsx)(qE,{})})]})]})},GE=UO;var BO={data:null,fetchState:"idle"},jr=e=>e.profile.data,Td=e=>e.profile.data?e.profile.data.uiConfig.widget.types.filter(t=>t.isActive):[],Ya=B("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)}),jO=W({name:"profile",initialState:BO,reducers:{},extraReducers:e=>{e.addCase(Ya.pending,t=>{t.fetchState="loading"}).addCase(Ya.rejected,t=>{t.fetchState="error"}).addCase(Ya.fulfilled,(t,n)=>{t.fetchState="done",t.data=n.payload})}}),YE=jO.reducer;var iC=w(D());var zO=["{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}"],VO=new RegExp(zO.map(e=>`(?:${e.replace("{","\\{").replace("}","\\}")})`).join("|"));function XE(e,t){let n=e.split(VO),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 QE(e,t){return typeof t=="boolean"?e:e.slice(0,t)}var JE={suggestions:[],fetchState:"idle",isInitialRequest:null},ZE={default:JE},eC=e=>t=>{var n;return((n=t.textSuggestions[e])==null?void 0:n.suggestions)??[]},tC=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")},kd=e=>e.textSuggestions,nC=e=>{let t=e.toLowerCase();return n=>{let r=n.text.toLowerCase();return r.startsWith(t)&&r.length>t.length}},Pd=we("textSuggestions/refresh"),un=B("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=Vi(r);if(!o)throw new Error("No current conversation to fetch text suggestions");let l=await n.getTextSuggestions(o,Ra(r),e);if(e==="default"){let c=s?l.filter(nC(a)):l;t.dispatch(En(c.slice(0,i)))}return l}),Xa=B("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,{...Ra(r),input:e});if(!t.getState().input.text)throw new Error("Abort");return a&&(l=l.filter(nC(e))),s&&(l=l.map(c=>({...c,text:c.source!=="trie-with-typos"?XE(c.text,e):c.text}))),l=QE(l,i),t.dispatch(En(l)),l}),rC=W({name:"textSuggestions",initialState:ZE,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(un.pending,(t,n)=>{let r=n.meta.arg,o=t[r]||JE;return{...t,[r]:{...o,fetchState:"loading",isInitialRequest:o.isInitialRequest===null}}}).addCase(un.rejected,(t,n)=>{let r=n.meta.arg;t[r]&&(t[r].fetchState="error")}).addCase(un.fulfilled,(t,n)=>{let r=n.meta.arg;t[r]&&(t[r].fetchState="done",t[r].suggestions=n.payload)}).addCase(Xa.pending,t=>{t.default.fetchState="loading"}).addCase(Xa.rejected,t=>{t.default.fetchState="error"}).addCase(Xa.fulfilled,(t,n)=>{t.default.fetchState="done",t.default.suggestions=n.payload}).addCase(le,()=>ZE)}}),{setTextSuggestions:fF,setSuggestionState:pF}=rC.actions,oC=rC.reducer;var _o=w(b()),KO=({commands:e,onClick:t})=>{var a,l,u;let n=Y(),r=G(Wa),o=O(jr),i=O(kd),s=((u=(l=(a=o==null?void 0:o.uiConfig)==null?void 0:a.search)==null?void 0:l.initialTypes)==null?void 0:u.filter(({isActive:c})=>c))||[];return(0,iC.useEffect)(()=>{s.forEach(({type:c})=>{(!i[c]||i[c].suggestions.length===0)&&n(un(c))})},[]),(0,_o.jsxs)("div",{children:[e.length>0&&(0,_o.jsx)(ge.List,{heading:r("commands"),children:e.map((c,f)=>(0,_o.jsx)(ge.ListItem,{id:`command-${f}`,closeOnSelect:!1,onClick:c.onClick,children:c.label},c.label))}),s.map(({type:c,title:f})=>{var d;return(0,_o.jsx)(ge.List,{heading:f,orientation:"vertical",children:(d=i[c])==null?void 0:d.suggestions.map((m,y)=>(0,_o.jsx)(ge.ListItem,{id:`${c}-${y}`,closeOnSelect:!1,description:m.text,onClick:()=>t(m.text,m),"data-testid":"search-overlay-suggestion",children:m.title},`${m.id}-${m.text}`))},c)})]})},sC=KO;var Ue=w(b()),WO=200,qO=5,GO=4,aC=(e,t)=>!t||e.toLowerCase().includes(t.toLowerCase()),YO=()=>{let e=Y(),t=zt(),n=G(Wa),[r,o]=(0,mt.useState)(!1),[i,s]=(0,mt.useState)(""),a=O(R1),l=O(jr),[u,c]=(0,mt.useState)(),f=O(tt),d=j("showSearch"),m=j("showEntitiesCommand"),y=j("showSummaryCommand"),v=j("showKnowledgeSearch"),p=j("showImageSearch"),g=j("searchTriggerKey"),h=O(rE),S=O(A1),x=O(L1),T=O(P1),C=H=>Gt(S.filter(q=>q.type===H.toUpperCase()),H),k=[{value:"PERSONAL",label:n("personalSuggestions"),list:C("PERSONAL"),lineClamp:!1,listOrientation:"vertical",shouldShow:!0},{value:"URL",label:n("urlSuggestions"),list:C("URL"),lineClamp:!1,listOrientation:"vertical",shouldShow:!0},{value:"STICKYMESSAGE",label:n("pinnedMessages"),list:C("STICKYMESSAGE"),lineClamp:!1,listOrientation:"vertical",shouldShow:!0},{value:"IMAGE",label:n("imageSuggestions"),lineClamp:!1,list:C("IMAGE"),listOrientation:"horizontal",shouldShow:p}].filter(H=>H.shouldShow),L=[{label:n("entitiesClipboard"),onClick:()=>e(tn("entities")),shouldShow:m&&aC(n("entitiesClipboard"),i)},{label:n("summaryClipboard"),onClick:()=>e(tn("summary")),shouldShow:y&&aC(n("summaryClipboard"),i)},{label:i?`${n("knowledgeAssist")}: ${i}`:n("knowledgeAssist"),onClick:()=>e(tn("knowledgeAssist")),shouldShow:v}].filter(H=>H.shouldShow),I=(h==null?void 0:h.map(H=>({value:H.code.toUpperCase(),label:`${H.name}s`,list:C(H.code.toUpperCase()),listOrientation:"vertical",lineClamp:!0})))||[],N=(0,mt.useCallback)((0,lC.default)((H,q)=>{e(Co({query:H,type:q,tags:["search-overlay"],size:u?50:20}))},WO),[u]),V=(0,mt.useCallback)((H,q)=>{switch(q.type){case"IMAGE":t.send(Bg,{suggestion:q});break;default:t.send(Dr,{text:H,suggestion:q})}e(xt(!1))},[e]),_=H=>{ko(H.text),e(Ye({name:"entity copied",data:{entity:H,type:"copy"}})),e(xt(!1))},ee=(0,mt.useCallback)(H=>{e(Ye({name:"suggestion feedback",data:{text:H.text,source:"search",context:i},options:{includeConversationData:!0}}))},[i]),Yr=H=>{t.send(Dr,{text:H,suggestion:{source:"knowledge-assist",text:H}}),e(Ye({name:"answer used",data:{originalText:H},options:{includeConversationData:!0}})),s(""),e(tn("search")),e(Qi()),e(xt(!1))},it=H=>{ko(H),e(xt(!1))};function Gt(H,q){return H.slice(0,u?10:q.toLowerCase()==="image"?GO:qO)}function At(H){return q=>{r?window.confirm(n("warning"))&&(H(q),o(!1)):H(q)}}return(0,mt.useEffect)(()=>{i?N(i,u):e(qc())},[i,u]),(0,mt.useEffect)(()=>{a==="search"&&e(Qi())},[a]),(0,mt.useEffect)(()=>{f&&e(Da())},[f]),AE(g,()=>e(xt(!0))),!d||!l?null:(0,Ue.jsxs)(ge,{placeholder:n("searchPlaceholder"),typePlaceholder:n("typePlaceholder"),onChangeSearch:s,onChangeOpen:At(H=>e(xt(H))),onChangeType:H=>c(H),onChangePage:At(H=>e(tn(H))),selectedType:u,search:i,page:a,isOpen:T,types:[...I,...k],children:[(0,Ue.jsxs)(ge.Page,{id:"search",children:[i.length===0&&(0,Ue.jsx)(sC,{commands:L,onClick:V}),i.length>0&&(0,Ue.jsxs)(mt.Fragment,{children:[L.length>0&&(0,Ue.jsx)(ge.List,{heading:n("commands"),children:L.map((H,q)=>(0,Ue.jsx)(ge.ListItem,{closeOnSelect:!1,onClick:H.onClick,id:`commands-${q}`,children:H.label},H.label))}),[...I,...k].map(({value:H,label:q,list:ir,lineClamp:he,listOrientation:sr})=>(0,Ue.jsx)(ge.List,{heading:q,orientation:sr==="horizontal"?"horizontal":"vertical",onShowAll:()=>c(H),hasMore:!u&&x[H.toLowerCase()]>Gt(ir,H).length,children:Gt(ir,H).map($=>(0,Ue.jsx)(ge.ListItem,{id:`${H}-${$.id}`,closeOnSelect:!1,lineClamp:he,onClick:()=>V($.text,$),description:H!=="IMAGE"?$.title&&$.text:void 0,onFeedback:H!=="IMAGE"?()=>ee($):void 0,children:H==="IMAGE"?(0,Ue.jsx)(ge.Image,{title:$.title||$.text,src:$.image}):$.title||$.text},`${$.id}-${$.text}`))},H))]})]}),(0,Ue.jsx)(ge.Page,{id:"entities",title:n("entitiesTitle"),onDismiss:At(()=>{e(tn("search"))}),children:(0,Ue.jsx)(NE,{onCopy:_})}),(0,Ue.jsx)(ge.Page,{id:"summary",title:n("summaryTitle"),onDismiss:At(()=>{e(tn("search"))}),children:(0,Ue.jsx)(BE,{onCopy:it})}),(0,Ue.jsx)(ge.Page,{id:"knowledgeAssist",title:n("knowledgeAssist"),onDismiss:At(()=>{e(Qi()),e(tn("search"))}),children:(0,Ue.jsx)(GE,{question:i,onUse:Yr,onResetQuestion:()=>{e(Qi()),s("")}})})]})},uC=YO;var Qa=w(b()),XO=()=>{let e=j("showSearch"),t=j("isEmbedded");return(0,Qa.jsxs)(cC.Fragment,{children:[e&&(0,Qa.jsx)(uC,{}),t&&(0,Qa.jsx)(Z1,{})]})},dC=XO;var gC=w(te());var Rd=w(b()),fC=({className:e})=>(0,Rd.jsx)("svg",{version:"1.1",xmlns:"http://www.w3.org/2000/svg",xmlnsXlink:"http://www.w3.org/1999/xlink",x:"0px",y:"0px",viewBox:"0 0 512 512",xmlSpace:"preserve",className:e,children:(0,Rd.jsx)("g",{children:(0,Rd.jsx)("path",{d:`M163.4,233h186v-70c0-25.6-9.4-47.8-27.3-65.7C304.2,79.4,282,70,256.4,70s-47.8,9.4-65.7,27.3
|
|
19
|
+
`),o=o.replace(/\n/g,"<br/>"),o}createContainer(t){var n;let o=(typeof global<"u"&&global.INTERWEAVE_SSR_POLYFILL||JI)();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(XI)||(s.innerHTML=this.convertLineBreaks(this.props.escapeHtml?(0,pE.default)(t):t)),s}extractAttributes(t){let{allowAttributes:n}=this.props,r={},o=0;return t.nodeType!==fE||!t.attributes||([...t.attributes].forEach(i=>{let{name:s,value:a}=i,l=s.toLowerCase(),u=hd[l]||hd[s];if(!this.isSafe(t)||!l.match(QI)&&(!n&&(!u||u===sh)||l.startsWith("on")||a.replace(/(\s|\0|�([9AD]);)/,"").match(/(javascript|vbscript|livescript|xss):/i)))return;let c=l==="style"?this.extractStyleAttribute(t):a;u===Hr?c=!0:u===Ao?c=Number.parseFloat(String(c)):u!==gd&&(c=String(c)),r[ah[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 Ba[t]?{...n,...Ba[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===fE){let d=c.nodeName.toLowerCase(),m=this.getTagConfig(d);u&&(l.push(u),u="");let y=this.applyNodeFilters(d,c);if(!y)return;let v;if(s&&!(a&&!this.isTagAllowed(d))){this.keyIndex+=1;let p=this.keyIndex;v=this.parseNode(y,m);let g=s(y,v,m);if(g===null)return;if(typeof g<"u"){l.push(Io.default.cloneElement(g,{key:p}));return}this.keyIndex=p-1}if(this.banned.has(d))return;if(!(r||o&&d!=="br")&&this.isTagAllowed(d)&&(i||this.canRenderChild(n,m))){var f;this.keyIndex+=1;let p=this.extractAttributes(y),g={tagName:d};p&&(g.attributes=p),m.void&&(g.selfClose=m.void),l.push(Io.default.createElement(yd,{...g,key:this.keyIndex},(f=v)!==null&&f!==void 0?f:this.parseNode(y,m)))}else l=[...l,...this.parseNode(y,m.tagName?m:n)]}else if(c.nodeType===YI){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(ZI);){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],m;if(u)m=s.length,r.push(f.createElement(c,d));else{let y=o.match(new RegExp(`{{{/${a}}}}`));m=y.index+y[0].length,r.push(f.createElement(this.replaceTokens(o.slice(s.length,y.index),n),d))}o=o.slice(m)}return o.length>0&&r.push(o),r.length===0?"":r.length===1&&typeof r[0]=="string"?r[0]:r}};function eO(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 m=new vd(i??"",e).parse();m.length>0&&(d=m)}return d||(d=s),f?Io.default.createElement(Io.default.Fragment,null,d):Io.default.createElement(yd,{attributes:n,className:r,tagName:c},d)}function $i(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,...m}=e,y=i?[]:l,v=o?[]:a,p=c?[c]:[],g=u?[u]:[];y.forEach(T=>{T.onBeforeParse&&p.push(T.onBeforeParse.bind(T)),T.onAfterParse&&g.push(T.onAfterParse.bind(T))});let h=p.reduce((T,C)=>C(T,e),r??""),S=new vd(h,m,y,v),x=g.reduce((T,C)=>C(T,e),S.parse());return Io.default.createElement(eO,{attributes:t,className:n,containerTagName:e.containerTagName,emptyContent:s,noWrap:d,parsedContent:x.length===0?void 0:x,tagName:f})}var tO=/[.*+?^${}()|[\]\\]/g,nO=/[^0-9A-Za-zÀ-ÖØ-öø-ÿ](?=[0-9A-Za-zÀ-ÖØ-öø-ÿ]*$)/;function rO(e){return e.replace(tO,"\\$&")}function oO(e,t){let n=e.split("").findIndex((r,o)=>r!==t[o]);return n>-1?n:Math.min(e.length,t.length)}function iO(e){return e.search(nO)}function mE(e,t=[]){let n=e;return t.forEach(r=>{if(!r)return;let o=new RegExp(`\\b(${rO(r)})\\b`,"gi");n=n.replace(o,"<strong>$1</strong>")}),n}function gE(e){return e.replace(Hl,'<mark data-type="placeholder">$1</mark>')}function Wi(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function sO(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 uh(e,t,n={}){if(t){let r=oO(t.toLowerCase(),e.toLowerCase()),o=Wi(e.substring(r,e.length));if(n.stripAgentPart){let l=e.substring(0,r),u=iO(l);return`<span style="opacity: 0.5">${l.substring(u+1)}</span>${o}`}let s=t.split(Iv).length>3||t.length>30?sO(t.trim(),r):0;return`${`${s>0?"\u2026":""}${Wi(e.substring(s,r))}`}<strong>${o}</strong>`}return e}var aO=/(<\/[a-zA-Z]+[0-9]?>|<[a-zA-Z]+\s?\/>|<br>)/i;function Sd(e){return aO.test(e)}function hE(e){let t=document.createElement("template");return t.innerHTML=e,t.content.textContent??""}var He=w(D()),yE=w(te());var ch={root:"Le",trigger:"_",content:"Me",contentOpen:"Re",contentTop:"Te",contentBottom:"Ue",item:"oo"};var Oo=w(b()),uO=0,vE=He.default.createContext(null),cO=()=>{let e=(0,He.useContext)(vE);if(!e)throw new Error("Invalid DropdownContext");return e},SE=({trigger:e,children:t,position:n="bottom"})=>{let r=(0,He.useMemo)(()=>++uO,[]),o=(0,He.useRef)(null),i=(0,He.useRef)(null),s=A("Dropdown",ch),[a,l]=(0,He.useState)(!1),[u,c]=(0,He.useState)(n),f=m=>{m.preventDefault(),m.stopPropagation(),l(!a)},d=(0,He.useCallback)(([m])=>{!m.isIntersecting&&a&&c(u==="top"?"bottom":"top")},[a]);return(0,He.useEffect)(()=>{let m=y=>{o.current&&!o.current.contains(y.target)&&l(!1)};return document.addEventListener("click",m),()=>{document.removeEventListener("click",m)}},[]),(0,He.useEffect)(()=>{if(!i.current&&!a)return()=>{};let m=new IntersectionObserver(d,{root:null,rootMargin:"0px",threshold:1});return i.current&&m.observe(i.current),()=>{i.current&&m.unobserve(i.current)}},[i,a]),(0,Oo.jsx)(vE.Provider,{value:{setIsOpen:l},children:(0,Oo.jsxs)("div",{ref:o,className:s.root,children:[(0,Oo.jsx)("button",{id:`dropdown-${r}`,"data-testid":"dropdown-trigger","aria-haspopup":"true","aria-expanded":a,"aria-label":"Dropdown trigger",type:"button",className:s.trigger,onClick:f,children:e}),(0,Oo.jsx)("div",{"data-testid":"dropdown-content",ref:i,"aria-hidden":!a,"aria-labelledby":`dropdown-${r}`,className:(0,yE.default)(s.content,{[s.contentOpen]:a,[s.contentTop]:u==="top",[s.contentBottom]:u==="bottom"}),children:t})]})})};function dO({as:e,children:t,onClick:n,...r}){let o=e||"button",i=A("Dropdown",ch),{setIsOpen:s}=cO(),a=l=>{s(!1),n(l),l.stopPropagation()};return(0,Oo.jsx)(o,{type:"button",className:i.item,onClick:a,...r,children:t})}SE.Item=dO;var dh=SE;var fh=w(b()),wE=e=>(0,fh.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"16",width:"14",viewBox:"0 0 448 512",...e,children:(0,fh.jsx)("path",{fill:"currentColor",d:"M8 256a56 56 0 1 1 112 0A56 56 0 1 1 8 256zm160 0a56 56 0 1 1 112 0 56 56 0 1 1 -112 0zm216-56a56 56 0 1 1 0 112 56 56 0 1 1 0-112z"})});var No={};Qe(No,{enUS:()=>fO,nlNL:()=>pO});var fO={preview:[{type:0,value:"Preview"}],useSuggestion:[{type:0,value:"Add"}],sendSuggestion:[{type:0,value:"Send"}],suggestionSent:[{type:0,value:"Sent"}],sendingError:[{type:0,value:"Sending failed"}],tryAgain:[{type:0,value:"Try again"}],editSuggestion:[{type:0,value:"Edit"}],visitUrl:[{type:0,value:"Visit"}],giveFeedback:[{type:0,value:"Give feedback"}],answer:[{type:0,value:"Answer"}]},pO={preview:[{type:0,value:"Preview"}],useSuggestion:[{type:0,value:"Gebruik"}],sendSuggestion:[{type:0,value:"Verzenden"}],suggestionSent:[{type:0,value:"Verzonden"}],sendingError:[{type:0,value:"Verzenden mislukt"}],tryAgain:[{type:0,value:"Probeer opnieuw"}],editSuggestion:[{type:0,value:"Bewerken"}],visitUrl:[{type:0,value:"Bekijk"}],giveFeedback:[{type:0,value:"Geef feedback"}],answer:[{type:0,value:"Antwoord"}]};var wd=w(b()),mO="%0d%0a%0d%0a%0d%0a",gO=(e,t)=>{let n=[`Suggestie: ${encodeURIComponent(t)}`,"Beschrijf je feedback:"];return`mailto:${e.join(",")}?subject=Suggestie feedback&body=${n.join(mO)}`},hO=({suggestion:e,onFeedback:t})=>{let n=G(No),r=j("suggestionFeedbackEmailAddresses");return!r||r.length===0?null:(0,wd.jsx)(dh,{trigger:(0,wd.jsx)(wE,{"data-testid":"feedback-dropdown-trigger"}),children:(0,wd.jsx)(dh.Item,{as:"a",href:gO(r,e),onClick:t,children:n("giveFeedback")})})},xd=hO;var Ed=w(D()),CE=w(b()),xE=Ed.default.createContext(void 0);function Ur(){let e=Ed.default.useContext(xE);if(e===void 0)throw new Error("useCommandPalette must be used within the CommandPalette component");return e}var EE=({children:e,page:t,isOpen:n,onChangeOpen:r,selected:o,setSelected:i})=>{let s=Ed.default.useMemo(()=>({page:t,isOpen:n,onChangeOpen:r,selected:o,setSelected:i}),[n,t,o]);return(0,CE.jsx)(xE.Provider,{value:s,children:e})};var Ct=w(b());function ph({closeOnSelect:e=!0,lineClamp:t,children:n,onClick:r,onFeedback:o,onSourceClick:i,description:s,sources:a,id:l,styles:u,...c}){let{selected:f,onChangeOpen:d}=Ur(),m=A("CommandPalette",Vt);function y(v){r(v),e&&d(!1)}return(0,Ct.jsxs)("div",{className:(0,ja.default)(m.listItem,l===f&&m.listItemSelected),children:[(0,Ct.jsx)("button",{type:"button",className:(0,ja.default)(m.listItemAction,m.listItemPrimaryAction),"aria-disabled":c.disabled??!1,onClick:y,"data-command-palette-item":!0,"data-item-id":l,...c,children:(0,Ct.jsxs)("div",{className:m.listItemContent,children:[typeof n=="string"?(0,Ct.jsx)("p",{className:(0,ja.default)(m.listItemText,m.truncate,u==null?void 0:u.title),children:n}):n,s&&(0,Ct.jsx)($i,{tagName:"p",allowList:[],content:Sd(s)?hE(s):s,className:(0,ja.default)(m.listItemDescription,u==null?void 0:u.description,t?m.lineClamp:m.truncate)})]})}),o&&(0,Ct.jsx)("div",{className:m.listItemActions,children:(0,Ct.jsx)(xd,{suggestion:String(n),onFeedback:o})}),a&&(0,Ct.jsxs)("div",{className:m.sources,children:[(0,Ct.jsx)("span",{className:m.sourcesTitle,children:"Sources"}),a.map(v=>v.url?(0,Ct.jsx)("a",{className:m.source,href:v.url,target:"_blank",title:v.url,rel:"noopener noreferrer",onClick:()=>i&&i(v),children:v.name},v.url):(0,Ct.jsx)("span",{className:m.source,children:v.name},v.name))]})]})}var za=w(b()),bE=()=>(0,za.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 256 512","aria-labelledby":"angleLeftTitle",children:[(0,za.jsx)("title",{id:"angleLeftTitle",children:"AngleLeft"}),(0,za.jsx)("path",{d:"M192 448c-8.188 0-16.38-3.125-22.62-9.375l-160-160c-12.5-12.5-12.5-32.75 0-45.25l160-160c12.5-12.5 32.75-12.5 45.25 0s12.5 32.75 0 45.25L77.25 256l137.4 137.4c12.5 12.5 12.5 32.75 0 45.25C208.4 444.9 200.2 448 192 448z"})]});var Mo=w(b());function mh({children:e,title:t,id:n,onDismiss:r}){let o=G(Po),i=A("CommandPalette",Vt),{page:s}=Ur();return s!==n?null:(0,Mo.jsxs)("div",{className:i.page,id:`page_${n}`,tabIndex:-1,children:[r&&(0,Mo.jsxs)("div",{className:i.pageNav,children:[(0,Mo.jsxs)("button",{className:i.pageBackButton,type:"button",onClick:r,children:[(0,Mo.jsx)(bE,{}),o("back")]}),t&&(0,Mo.jsx)("h3",{className:i.pageTitle,children:t})]}),e]})}var TE=w(D());var Va=w(b()),qi=()=>(0,Va.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 0 24 24",width:"1em",fill:"currentColor",children:[(0,Va.jsx)("path",{d:"M0 0h24v24H0z",fill:"none"}),(0,Va.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 sn=w(b());function yO({onChange:e,onChangeType:t,placeholder:n,typePlaceholder:r,types:o,value:i,selectedType:s},a){let l=A("CommandPalette",Vt);return(0,sn.jsxs)("div",{className:l.search,children:[(0,sn.jsx)("div",{className:l.searchIcon,children:(0,sn.jsx)(qi,{})}),(0,sn.jsxs)("div",{className:l.searchInputWrapper,children:[(0,sn.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,sn.jsx)("div",{className:l.selectWrapper,children:(0,sn.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,sn.jsx)("option",{children:r}),o.map(u=>(0,sn.jsx)("option",{value:u.value,children:u.label},u.value))]})})]})]})}var kE=(0,TE.forwardRef)(yO);var gh=w(te());var Cd=w(b()),vO=({onClick:e,shortKeys:t,children:n,...r})=>{let o=A("CommandPalette",Vt);return(0,Cd.jsxs)("button",{type:"button",...r,onClick:e,className:(0,gh.default)(o.actionButton,r.className,{[o.hasShortKeys]:t&&t.length>0}),children:[n,t&&t.map(i=>(0,Cd.jsx)("span",{className:(0,gh.default)(o.actionShortcut,i===8629&&o.actionShortcutFixKerning),children:typeof i=="number"?String.fromCharCode(i):i},i))]})},PE=vO;var Ka=w(b()),SO="[data-command-palette-item]";function Gi({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[m,y]=(0,qn.useState)(),v=(0,qn.useRef)(null),p=()=>{o&&o(n),s(void 0),i(""),a(!1)},g=()=>{var N;if(r!==n&&o){o(n);return}if(l&&s){s(void 0),(N=v.current)==null||N.focus();return}if(d.length>0){i("");return}a(!1)},h=()=>{let N=S();N.length!==0&&y(N[0].dataset.itemId)},S=()=>Array.from(document.querySelectorAll(SO)||[]),x=N=>document.querySelector(`[data-item-id=${N}]`),T=N=>{let V=x(N);V&&y(V.dataset.itemId)},C=N=>{let V=x(N);V&&V.scrollIntoView({behavior:"smooth"})},k=()=>{if(!m)return;let N=S(),V=x(m);if(!V)return;let _=N.indexOf(V),ee=N[_+1];ee&&ee.dataset.itemId?T(ee.dataset.itemId):h()},L=()=>{if(!m)return;let N=S(),V=x(m);if(!V)return;let _=N.indexOf(V),ee=N[_-1];ee&&ee.dataset.itemId?T(ee.dataset.itemId):T(N[N.length-1].dataset.itemId)},I=(0,qn.useCallback)(N=>{switch(N.key){case"ArrowDown":{N.preventDefault(),k();break}case"ArrowUp":{N.preventDefault(),L();break}case"Enter":{if(m){let V=x(m);V==null||V.click()}break}}},[m]);return(0,qn.useEffect)(()=>{h()},[d,r,l,f]),(0,qn.useEffect)(()=>{m&&C(m)},[m]),(0,Ka.jsx)(ud,{autoFocus:!0,contentAriaLabel:"Search Results",overlayAriaLabel:"Command Palette",isOpen:f,onBack:g,onClose:p,onKeyDown:I,children:(0,Ka.jsxs)(EE,{selected:m,setSelected:y,isOpen:f,onChangeOpen:a,page:r,children:[r===n&&(0,Ka.jsx)(kE,{ref:v,onChange:i,onChangeType:s,placeholder:e,value:d,selectedType:l,types:u,typePlaceholder:t}),c]})})}Gi.Page=mh;Gi.List=eh;Gi.Image=sE;Gi.ListItem=ph;Gi.Button=PE;var ge=Gi;var RE=w(D());function AE(e,t){(0,RE.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 $a=w(D());var LE={data:null,fetchState:"idle"},bd=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},an=B("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)}),wO=e=>e.filter((t,n)=>n===e.findIndex(r=>r.text===t.text)),xO=W({name:"entities",initialState:LE,reducers:{},extraReducers:e=>{e.addCase(an.pending,t=>{t.fetchState="loading"}).addCase(an.rejected,t=>{t.fetchState="error"}).addCase(an.fulfilled,(t,n)=>{t.fetchState="done",t.data=wO(t.data?[...t.data,...n.payload]:n.payload)}).addCase(le,()=>LE)}}),IE=xO.reducer;var hh={};Qe(hh,{enUS:()=>EO,nlNL:()=>CO});var EO={noResults:[{type:0,value:"No entities have been found"}],copy:[{type:0,value:"Copy"}],use:[{type:0,value:"Use"}]},CO={noResults:[{type:0,value:"Er zijn geen entiteiten gevonden"}],copy:[{type:0,value:"Kopieer"}],use:[{type:0,value:"Gebruik"}]};var OE={root:"Be",empty:"De"};var Yi=w(b()),TO=({onCopy:e})=>{let t=(0,$a.useRef)(null),n=A("EntitiesList",OE),r=O(bd),{setSelected:o}=Ur(),i=G(hh),s=Y();return(0,$a.useEffect)(()=>{s(an())},[]),(0,$a.useEffect)(()=>{t.current&&(t.current.focus(),o("entity-0"))},[t]),(0,Yi.jsxs)("div",{className:n.root,ref:t,tabIndex:-1,children:[r&&r.length>0&&(0,Yi.jsx)(ge.List,{children:r.map((a,l)=>(0,Yi.jsx)(ge.ListItem,{id:`entity-${l}`,closeOnSelect:!0,onClick:()=>e(a),children:a.text},a.text))},"entities"),r&&r.length===0&&(0,Yi.jsx)("p",{className:n.empty,children:i("noResults")})]})},NE=TO;var ln=w(D());var ME={data:null,fetchState:"idle"},_E=e=>e.summary.data,DE=e=>e.summary.fetchState==="error",FE=e=>e.summary.model,Gn=B("summary/getSummary",async(e,t)=>{var c,f,d;let n=t.getState().profile.data,r=(c=t.getState().conversation.current)==null?void 0:c.sessionId,o=(d=(f=t.getState().info)==null?void 0:f.agentInfo)==null?void 0:d.agentId;if(!n)throw new Error("Profile is not defined");let{deepdeskAPI:i,dynamicThunkObject:s}=t.extra;if(!s.conversationQuery)return Promise.reject(new Error("setConversationQuery method is not defined"));let a=s.conversationQuery,l=await a();if(l.length===0)return Promise.reject(new Error("No messages are included"));let u=await i.getSummary(l,{externalConversationId:r,agentId:o,promptInstruction:n.summarizerPromptInstruction,model:n.summarizerModel});return u.summary?u:Promise.reject(new Error("Summary is not provided"))}),kO=W({name:"summary",initialState:ME,reducers:{},extraReducers:e=>{e.addCase(Gn.pending,t=>{t.data=null,t.fetchState="loading"}).addCase(Gn.rejected,t=>{t.data=null,t.fetchState="error"}).addCase(Gn.fulfilled,(t,n)=>{t.fetchState="done",n.payload&&(t.data=n.payload.summary,t.model=n.payload.model)}).addCase(le,()=>ME)}}),HE=kO.reducer;var yh={};Qe(yh,{enUS:()=>PO,nlNL:()=>RO});var PO={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."}]},RO={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 UE={root:"Ie",actions:"Oe",main:"Xe",textInput:"eo",loading:"Je",error:"Ke"};var Yn=w(b()),LO=({onCopy:e})=>{let t=(0,ln.useRef)(null),n=A("SummaryForm",UE),[r,o]=(0,ln.useState)(""),i=G(yh),s=O(FE),a=O(_E),l=O(DE),u=Y(),c=()=>{u(Ye({name:"summary copied to clipboard",data:{originalText:a,finalText:r,model:s},options:{includeConversationData:!0}})),e(r)},f=()=>{let d=document.getSelection();d&&u(Ye({name:"summary copied to clipboard",data:{originalText:a,finalText:d==null?void 0:d.toString(),model:s},options:{includeConversationData:!0}}))};return(0,ln.useEffect)(()=>{u(Gn())},[]),(0,ln.useEffect)(()=>{o(a||"")},[a]),(0,ln.useEffect)(()=>{t.current&&a&&t.current.focus()},[t,a]),(0,ln.useEffect)(()=>{let d=m=>{m.key==="Enter"&&m.shiftKey&&c()};return document.addEventListener("keydown",d),()=>{document.removeEventListener("keydown",d)}},[r]),(0,Yn.jsx)("div",{className:n.root,tabIndex:-1,children:l?(0,Yn.jsx)("p",{className:n.error,children:i("error")}):(0,Yn.jsxs)(ln.Fragment,{children:[(0,Yn.jsx)("div",{className:n.main,children:(0,Yn.jsx)("textarea",{placeholder:a?void 0:i("loading"),disabled:!a,className:n.textInput,ref:t,value:r,onCopy:f,onChange:d=>o(d.target.value)})}),(0,Yn.jsx)("div",{className:n.actions,children:(0,Yn.jsx)(ge.Button,{shortKeys:[8679,8629],onClick:c,children:i("copy")})})]})})},BE=LO;var Wa={};Qe(Wa,{enUS:()=>IO,nlNL:()=>OO});var IO={personalCollectionLink:[{type:0,value:"Go to Personal Collection"}],searchPlaceholder:[{type:0,value:"Start typing to search..."}],urlSuggestions:[{type:0,value:"Link suggestions"}],personalSuggestions:[{type:0,value:"Personal suggestions"}],pinnedMessages:[{type:0,value:"Pinned messages"}],imageSuggestions:[{type:0,value:"Images"}],typePlaceholder:[{type:0,value:"All types"}],navigation:[{type:0,value:"Navigation"}],entitiesClipboard:[{type:0,value:"Conversation clipper"}],entitiesTitle:[{type:0,value:"Copy to your clipboard"}],summaryClipboard:[{type:0,value:"Summarize conversation"}],summaryTitle:[{type:0,value:"Conversation summary"}],knowledgeAssist:[{type:0,value:"Knowledge assist"}],commands:[{type:0,value:"Commands"}],use:[{type:0,value:"Use"}],preview:[{type:0,value:"Preview"}],warning:[{type:0,value:"Are you sure you want to discard the message?"}]},OO={personalCollectionLink:[{type:0,value:"Ga naar persoonlijke collectie"}],searchPlaceholder:[{type:0,value:"Begin met typen om te zoeken..."}],personalSuggestions:[{type:0,value:"Persoonlijke suggesties"}],urlSuggestions:[{type:0,value:"Link suggesties"}],imageSuggestions:[{type:0,value:"Afbeeldingen"}],navigation:[{type:0,value:"Navigatie"}],typePlaceholder:[{type:0,value:"Alle types"}],pinnedMessages:[{type:0,value:"Actueel"}],entitiesClipboard:[{type:0,value:"Klembord"}],entitiesTitle:[{type:0,value:"Kopieer naar klembord"}],summaryClipboard:[{type:0,value:"Gesprek samenvatten"}],summaryTitle:[{type:0,value:"Gesprek samenvatting"}],knowledgeAssist:[{type:0,value:"Knowledge assist"}],commands:[{type:0,value:"Acties"}],use:[{type:0,value:"Gebruik"}],preview:[{type:0,value:"Bewerk"}],warning:[{type:0,value:"Weet je zeker dat je de wijzigingen wilt weggooien?"}]};var Br=w(D());var vh={};Qe(vh,{enUS:()=>NO,nlNL:()=>MO});var NO={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"}]},MO={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 jE={root:"io",title:"Pe",empty:"Qe",status:"Ve",form:"ro",input:"to",submit:"We",question:"Ze",answer:"_e",alignRight:"oi"};var DO={data:null,fetchState:"idle"},zE=e=>{var t;return(t=e.knowledgeAssistant)==null?void 0:t.data},qa=B("knowledgeAssistant/getKnowledgeAssistant",async(e,t)=>{var s;let{deepdeskAPI:n}=t.extra,r=t.getState(),o=r.conversation.current;if(!o||!o.profileCode)throw new Error("No conversation of conversation profileCode found");let i=(s=r.profile.data)==null?void 0:s.knowledgeAssistant;return i?n.getKnowledgeAssistant(i):null}),FO=W({name:"knowledgeAssistant",initialState:DO,reducers:{},extraReducers:e=>{e.addCase(qa.pending,t=>{t.fetchState="loading"}).addCase(qa.rejected,t=>{t.fetchState="error"}).addCase(qa.fulfilled,(t,n)=>{t.fetchState="done",t.data=n.payload})}}),VE=FO.reducer;var Sh={data:[],fetchState:"idle"},KE=e=>{var t;return(t=e.answer)==null?void 0:t.data},$E=e=>e.answer.fetchState,Qi=we("answer/resetKnowledgeSearch"),Xi=B("answer/getAnswer",async(e,t)=>{var l,u,c;let{deepdeskAPI:n}=t.extra,r=t.getState().answer.data,o=zE(t.getState()),i=(l=t.getState().conversation.current)==null?void 0:l.sessionId,s=(c=(u=t.getState().info)==null?void 0:u.agentInfo)==null?void 0:c.agentId;if(!o)throw new Error("KnowledgeAssistant is not defined");let a=await n.knowledgeAssist({promptInstruction:o.customerInstruction,question:e},r,o.code,{agentId:s,conversationId:i});return{question:e,answer:a}}),HO=W({name:"answer",initialState:Sh,reducers:{},extraReducers:e=>{e.addCase(Xi.pending,t=>{t.fetchState="loading"}).addCase(Xi.rejected,t=>{t.fetchState="error"}).addCase(Xi.fulfilled,(t,n)=>{t.fetchState="done",t.data=[...t.data,n.payload]}).addCase(le,()=>Sh).addCase(Qi,()=>Sh)}}),WE=HO.reducer;var Ga=w(b()),qE=()=>(0,Ga.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 512 512","aria-labelledby":"paperPlaneTitle",children:[(0,Ga.jsx)("title",{id:"paperPlaneTitle",children:"PaperPlane"}),(0,Ga.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 bt=w(b()),UO=({onUse:e,onResetQuestion:t,question:n})=>{let[r,o]=Br.default.useState(""),{setSelected:i}=Ur(),s=(0,Br.useRef)(null),a=A("EntitiesList",jE),l=G(vh),u=Y(),c=O(KE),f=O($E),d=async y=>{y.preventDefault(),y.stopPropagation(),r!==""&&u(Xi(r))},m=(y,v)=>{u(Ye({name:"knowledge assist source viewed",data:{question:v,sourceViewed:y.url||y.name},options:{includeConversationData:!0}}))};return(0,Br.useEffect)(()=>{var y;n&&f==="idle"?u(Xi(n)):(y=s.current)==null||y.focus()},[s,f]),(0,Br.useEffect)(()=>{f==="done"&&(u(Ye({name:"knowledge assist question answered",data:{question:r||n,sources:c[c.length-1].answer.sources,answer:c[c.length-1].answer.answer,isFollowUpQuestion:c.length>1},options:{includeConversationData:!0}})),i(`knowledge-assist-${c.length-1}`),o(""))},[f,c]),(0,Br.useEffect)(()=>{s.current&&s.current.scrollIntoView({behavior:"smooth"})},[s,c]),(0,bt.jsxs)("div",{className:a.root,children:[c.length>0&&(0,bt.jsx)("div",{className:a.alignRight,children:(0,bt.jsx)(ge.Button,{onClick:t,children:l("reset")})}),c.map(({question:y,answer:v},p)=>(0,bt.jsx)(ge.List,{children:(0,bt.jsx)(ge.ListItem,{id:`knowledge-assist-${p}`,"data-testid":"knowledge-search-answer",description:v.answer,closeOnSelect:!0,onClick:()=>e(v.answer),onSourceClick:g=>m(g,y),sources:v.sources,styles:{title:a.question,description:a.answer},children:y})},`${v.answer}_${p}`)),f==="loading"&&(0,bt.jsx)("p",{className:a.status,children:l("loading")}),f==="error"&&(0,bt.jsx)("p",{className:a.status,children:l("error")}),(0,bt.jsxs)("form",{className:a.form,onSubmit:d,children:[(0,bt.jsx)("input",{ref:s,placeholder:l("anotherQuestion"),className:a.input,type:"text",value:r,onFocus:()=>{i(void 0)},onChange:y=>{i(void 0),o(y.target.value)}}),(0,bt.jsx)("button",{type:"submit",className:a.submit,children:(0,bt.jsx)(qE,{})})]})]})},GE=UO;var BO={data:null,fetchState:"idle"},jr=e=>e.profile.data,Td=e=>e.profile.data?e.profile.data.uiConfig.widget.types.filter(t=>t.isActive):[],Ya=B("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)}),jO=W({name:"profile",initialState:BO,reducers:{},extraReducers:e=>{e.addCase(Ya.pending,t=>{t.fetchState="loading"}).addCase(Ya.rejected,t=>{t.fetchState="error"}).addCase(Ya.fulfilled,(t,n)=>{t.fetchState="done",t.data=n.payload})}}),YE=jO.reducer;var iC=w(D());var zO=["{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}"],VO=new RegExp(zO.map(e=>`(?:${e.replace("{","\\{").replace("}","\\}")})`).join("|"));function XE(e,t){let n=e.split(VO),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 QE(e,t){return typeof t=="boolean"?e:e.slice(0,t)}var JE={suggestions:[],fetchState:"idle",isInitialRequest:null},ZE={default:JE},eC=e=>t=>{var n;return((n=t.textSuggestions[e])==null?void 0:n.suggestions)??[]},tC=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")},kd=e=>e.textSuggestions,nC=e=>{let t=e.toLowerCase();return n=>{let r=n.text.toLowerCase();return r.startsWith(t)&&r.length>t.length}},Pd=we("textSuggestions/refresh"),un=B("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=Vi(r);if(!o)throw new Error("No current conversation to fetch text suggestions");let l=await n.getTextSuggestions(o,Ra(r),e);if(e==="default"){let c=s?l.filter(nC(a)):l;t.dispatch(En(c.slice(0,i)))}return l}),Xa=B("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,{...Ra(r),input:e});if(!t.getState().input.text)throw new Error("Abort");return a&&(l=l.filter(nC(e))),s&&(l=l.map(c=>({...c,text:c.source!=="trie-with-typos"?XE(c.text,e):c.text}))),l=QE(l,i),t.dispatch(En(l)),l}),rC=W({name:"textSuggestions",initialState:ZE,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(un.pending,(t,n)=>{let r=n.meta.arg,o=t[r]||JE;return{...t,[r]:{...o,fetchState:"loading",isInitialRequest:o.isInitialRequest===null}}}).addCase(un.rejected,(t,n)=>{let r=n.meta.arg;t[r]&&(t[r].fetchState="error")}).addCase(un.fulfilled,(t,n)=>{let r=n.meta.arg;t[r]&&(t[r].fetchState="done",t[r].suggestions=n.payload)}).addCase(Xa.pending,t=>{t.default.fetchState="loading"}).addCase(Xa.rejected,t=>{t.default.fetchState="error"}).addCase(Xa.fulfilled,(t,n)=>{t.default.fetchState="done",t.default.suggestions=n.payload}).addCase(le,()=>ZE)}}),{setTextSuggestions:fF,setSuggestionState:pF}=rC.actions,oC=rC.reducer;var _o=w(b()),KO=({commands:e,onClick:t})=>{var a,l,u;let n=Y(),r=G(Wa),o=O(jr),i=O(kd),s=((u=(l=(a=o==null?void 0:o.uiConfig)==null?void 0:a.search)==null?void 0:l.initialTypes)==null?void 0:u.filter(({isActive:c})=>c))||[];return(0,iC.useEffect)(()=>{s.forEach(({type:c})=>{(!i[c]||i[c].suggestions.length===0)&&n(un(c))})},[]),(0,_o.jsxs)("div",{children:[e.length>0&&(0,_o.jsx)(ge.List,{heading:r("commands"),children:e.map((c,f)=>(0,_o.jsx)(ge.ListItem,{id:`command-${f}`,closeOnSelect:!1,onClick:c.onClick,children:c.label},c.label))}),s.map(({type:c,title:f})=>{var d;return(0,_o.jsx)(ge.List,{heading:f,orientation:"vertical",children:(d=i[c])==null?void 0:d.suggestions.map((m,y)=>(0,_o.jsx)(ge.ListItem,{id:`${c}-${y}`,closeOnSelect:!1,description:m.text,onClick:()=>t(m.text,m),"data-testid":"search-overlay-suggestion",children:m.title},`${m.id}-${m.text}`))},c)})]})},sC=KO;var Ue=w(b()),WO=200,qO=5,GO=4,aC=(e,t)=>!t||e.toLowerCase().includes(t.toLowerCase()),YO=()=>{let e=Y(),t=zt(),n=G(Wa),[r,o]=(0,mt.useState)(!1),[i,s]=(0,mt.useState)(""),a=O(R1),l=O(jr),[u,c]=(0,mt.useState)(),f=O(tt),d=j("showSearch"),m=j("showEntitiesCommand"),y=j("showSummaryCommand"),v=j("showKnowledgeSearch"),p=j("showImageSearch"),g=j("searchTriggerKey"),h=O(rE),S=O(A1),x=O(L1),T=O(P1),C=H=>Gt(S.filter(q=>q.type===H.toUpperCase()),H),k=[{value:"PERSONAL",label:n("personalSuggestions"),list:C("PERSONAL"),lineClamp:!1,listOrientation:"vertical",shouldShow:!0},{value:"URL",label:n("urlSuggestions"),list:C("URL"),lineClamp:!1,listOrientation:"vertical",shouldShow:!0},{value:"STICKYMESSAGE",label:n("pinnedMessages"),list:C("STICKYMESSAGE"),lineClamp:!1,listOrientation:"vertical",shouldShow:!0},{value:"IMAGE",label:n("imageSuggestions"),lineClamp:!1,list:C("IMAGE"),listOrientation:"horizontal",shouldShow:p}].filter(H=>H.shouldShow),L=[{label:n("entitiesClipboard"),onClick:()=>e(tn("entities")),shouldShow:m&&aC(n("entitiesClipboard"),i)},{label:n("summaryClipboard"),onClick:()=>e(tn("summary")),shouldShow:y&&aC(n("summaryClipboard"),i)},{label:i?`${n("knowledgeAssist")}: ${i}`:n("knowledgeAssist"),onClick:()=>e(tn("knowledgeAssist")),shouldShow:v}].filter(H=>H.shouldShow),I=(h==null?void 0:h.map(H=>({value:H.code.toUpperCase(),label:`${H.name}s`,list:C(H.code.toUpperCase()),listOrientation:"vertical",lineClamp:!0})))||[],N=(0,mt.useCallback)((0,lC.default)((H,q)=>{e(Co({query:H,type:q,tags:["search-overlay"],size:u?50:20}))},WO),[u]),V=(0,mt.useCallback)((H,q)=>{switch(q.type){case"IMAGE":t.send(Bg,{suggestion:q});break;default:t.send(Dr,{text:H,suggestion:q})}e(xt(!1))},[e]),_=H=>{ko(H.text),e(Ye({name:"entity copied",data:{entity:H,type:"copy"}})),e(xt(!1))},ee=(0,mt.useCallback)(H=>{e(Ye({name:"suggestion feedback",data:{text:H.text,source:"search",context:i},options:{includeConversationData:!0}}))},[i]),Yr=H=>{t.send(Dr,{text:H,suggestion:{source:"knowledge-assist",text:H}}),e(Ye({name:"answer used",data:{originalText:H},options:{includeConversationData:!0}})),s(""),e(tn("search")),e(Qi()),e(xt(!1))},it=H=>{ko(H),e(xt(!1))};function Gt(H,q){return H.slice(0,u?10:q.toLowerCase()==="image"?GO:qO)}function At(H){return q=>{r?window.confirm(n("warning"))&&(H(q),o(!1)):H(q)}}return(0,mt.useEffect)(()=>{i?N(i,u):e(qc())},[i,u]),(0,mt.useEffect)(()=>{a==="search"&&e(Qi())},[a]),(0,mt.useEffect)(()=>{f&&e(Da())},[f]),AE(g,()=>e(xt(!0))),!d||!l?null:(0,Ue.jsxs)(ge,{placeholder:n("searchPlaceholder"),typePlaceholder:n("typePlaceholder"),onChangeSearch:s,onChangeOpen:At(H=>e(xt(H))),onChangeType:H=>c(H),onChangePage:At(H=>e(tn(H))),selectedType:u,search:i,page:a,isOpen:T,types:[...I,...k],children:[(0,Ue.jsxs)(ge.Page,{id:"search",children:[i.length===0&&(0,Ue.jsx)(sC,{commands:L,onClick:V}),i.length>0&&(0,Ue.jsxs)(mt.Fragment,{children:[L.length>0&&(0,Ue.jsx)(ge.List,{heading:n("commands"),children:L.map((H,q)=>(0,Ue.jsx)(ge.ListItem,{closeOnSelect:!1,onClick:H.onClick,id:`commands-${q}`,children:H.label},H.label))}),[...I,...k].map(({value:H,label:q,list:ir,lineClamp:he,listOrientation:sr})=>(0,Ue.jsx)(ge.List,{heading:q,orientation:sr==="horizontal"?"horizontal":"vertical",onShowAll:()=>c(H),hasMore:!u&&x[H.toLowerCase()]>Gt(ir,H).length,children:Gt(ir,H).map($=>(0,Ue.jsx)(ge.ListItem,{id:`${H}-${$.id}`,closeOnSelect:!1,lineClamp:he,onClick:()=>V($.text,$),description:H!=="IMAGE"?$.title&&$.text:void 0,onFeedback:H!=="IMAGE"?()=>ee($):void 0,children:H==="IMAGE"?(0,Ue.jsx)(ge.Image,{title:$.title||$.text,src:$.image}):$.title||$.text},`${$.id}-${$.text}`))},H))]})]}),(0,Ue.jsx)(ge.Page,{id:"entities",title:n("entitiesTitle"),onDismiss:At(()=>{e(tn("search"))}),children:(0,Ue.jsx)(NE,{onCopy:_})}),(0,Ue.jsx)(ge.Page,{id:"summary",title:n("summaryTitle"),onDismiss:At(()=>{e(tn("search"))}),children:(0,Ue.jsx)(BE,{onCopy:it})}),(0,Ue.jsx)(ge.Page,{id:"knowledgeAssist",title:n("knowledgeAssist"),onDismiss:At(()=>{e(Qi()),e(tn("search"))}),children:(0,Ue.jsx)(GE,{question:i,onUse:Yr,onResetQuestion:()=>{e(Qi()),s("")}})})]})},uC=YO;var Qa=w(b()),XO=()=>{let e=j("showSearch"),t=j("isEmbedded");return(0,Qa.jsxs)(cC.Fragment,{children:[e&&(0,Qa.jsx)(uC,{}),t&&(0,Qa.jsx)(Z1,{})]})},dC=XO;var gC=w(te());var Rd=w(b()),fC=({className:e})=>(0,Rd.jsx)("svg",{version:"1.1",xmlns:"http://www.w3.org/2000/svg",xmlnsXlink:"http://www.w3.org/1999/xlink",x:"0px",y:"0px",viewBox:"0 0 512 512",xmlSpace:"preserve",className:e,children:(0,Rd.jsx)("g",{children:(0,Rd.jsx)("path",{d:`M163.4,233h186v-70c0-25.6-9.4-47.8-27.3-65.7C304.2,79.4,282,70,256.4,70s-47.8,9.4-65.7,27.3
|
|
20
20
|
c-17.9,17.9-27.3,40.1-27.3,65.7C163.4,163,163.4,233,163.4,233z M465.5,267.9V477c0,9.4-3.4,17.9-10.2,24.7
|
|
21
21
|
c-6.8,6.8-15.4,10.2-24.7,10.2h-349c-9.4,0-17.9-3.4-24.7-10.2c-6.8-6.8-10.2-15.4-10.2-24.7V267.9c0-9.4,3.4-17.9,10.2-24.7
|
|
22
22
|
c6.8-6.8,15.4-10.2,24.7-10.2h11.9v-70c0-44.4,16.2-82.8,47.8-115.2S212.1,0,256.4,0s82.8,16.2,115.2,47.8
|
|
@@ -24,7 +24,7 @@ Try polyfilling it using "@formatjs/intl-pluralrules"
|
|
|
24
24
|
`+at),Yt&&ef([V,_,ee],Zr=>{at=il(at,Zr," ")}),S&&El?S.createHTML(at):at},t.setConfig=function(){let U=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};wf(U),wl=!0},t.clearConfig=function(){Yo=null,wl=!1},t.isValidAttribute=function(U,E,R){Yo||wf({});let F=Oe(U),ce=Oe(E);return Dy(F,ce,R)},t.addHook=function(U,E){typeof E=="function"&&(N[U]=N[U]||[],ol(N[U],E))},t.removeHook=function(U){if(N[U])return Yb(N[U])},t.removeHooks=function(U){N[U]&&(N[U]=[])},t.removeAllHooks=function(){N={}},t}var sT=iT();var qr=w(D());var AM={"":["<em>","</em>"],_:["<strong>","</strong>"],"*":["<strong>","</strong>"],"~":["<s>","</s>"],"\n":["<br />"]," ":["<br />"],"-":["<hr />"]};function aT(e){return e.replace(RegExp("^"+(e.match(/^(\t| )+/)||"")[0],"gm"),"")}function al(e){return(e+"").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function ll(e,t){var n,r,o,i,s,a=/((?:^|\n+)(?:\n---+|\* \*(?: \*)+)\n)|(?:^``` *(\w*)\n([\s\S]*?)\n```$)|((?:(?:^|\n+)(?:\t| {2,}).+)+\n*)|((?:(?:^|\n)([>*+-]|\d+\.)\s+.*)+)|(?:!\[([^\]]*?)\]\(([^)]+?)\))|(\[)|(\](?:\(([^)]+?)\))?)|(?:(?:^|\n+)([^\s].*)\n(-{3,}|={3,})(?:\n+|$))|(?:(?:^|\n+)(#{1,6})\s*(.+)(?:\n+|$))|(?:`([^`].*?)`)|( \n\n*|\n{2,}|__|\*\*|[_*]|~~)/gm,l=[],u="",c=t||{},f=0;function d(y){var v=AM[y[1]||""],p=l[l.length-1]==y;return v?v[1]?(p?l.pop():l.push(y),v[0|p]):v[0]:y}function m(){for(var y="";l.length;)y+=d(l[l.length-1]);return y}for(e=e.replace(/^\[(.+?)\]:\s*(.+)$/gm,function(y,v,p){return c[v.toLowerCase()]=p,""}).replace(/^\n+|\n+$/g,"");o=a.exec(e);)r=e.substring(f,o.index),f=a.lastIndex,n=o[0],r.match(/[^\\](\\\\)*\\$/)||((s=o[3]||o[4])?n='<pre class="code '+(o[4]?"poetry":o[2].toLowerCase())+'"><code'+(o[2]?' class="language-'+o[2].toLowerCase()+'"':"")+">"+aT(al(s).replace(/^\n+|\n+$/g,""))+"</code></pre>":(s=o[6])?(s.match(/\./)&&(o[5]=o[5].replace(/^\d+/gm,"")),i=ll(aT(o[5].replace(/^\s*[>*+.-]/gm,""))),s==">"?s="blockquote":(s=s.match(/\./)?"ol":"ul",i=i.replace(/^(.*)(\n|$)/gm,"<li>$1</li>")),n="<"+s+">"+i+"</"+s+">"):o[8]?n='<img src="'+al(o[8])+'" alt="'+al(o[7])+'">':o[10]?(u=u.replace("<a>",'<a href="'+al(o[11]||c[r.toLowerCase()])+'">'),n=m()+"</a>"):o[9]?n="<a>":o[12]||o[14]?n="<"+(s="h"+(o[14]?o[14].length:o[13]>"="?1:2))+">"+ll(o[12]||o[15],c)+"</"+s+">":o[16]?n="<code>"+al(o[16])+"</code>":(o[17]||o[1])&&(n=d(o[17]||"--"))),u+=r,u+=n;return(u+e.substring(f)+m()).replace(/^\n+|\n+$/g,"")}var lT={fadeup:"E",root:"i",popover:"rr",options:"yo",copyIcon:"G",option:"wo",divider:"tr"};var nr=w(b());function IM(e){return`<button type="button" class=${e}><svg version="1.1" x="0px" y="0px" viewBox="0 0 115.77 122.88" width="10px" height="10px" fill="black"><g><path d="M89.62,13.96v7.73h12.19h0.01v0.02c3.85,0.01,7.34,1.57,9.86,4.1c2.5,2.51,4.06,5.98,4.07,9.82h0.02v0.02 v73.27v0.01h-0.02c-0.01,3.84-1.57,7.33-4.1,9.86c-2.51,2.5-5.98,4.06-9.82,4.07v0.02h-0.02h-61.7H40.1v-0.02 c-3.84-0.01-7.34-1.57-9.86-4.1c-2.5-2.51-4.06-5.98-4.07-9.82h-0.02v-0.02V92.51H13.96h-0.01v-0.02c-3.84-0.01-7.34-1.57-9.86-4.1 c-2.5-2.51-4.06-5.98-4.07-9.82H0v-0.02V13.96v-0.01h0.02c0.01-3.85,1.58-7.34,4.1-9.86c2.51-2.5,5.98-4.06,9.82-4.07V0h0.02h61.7 h0.01v0.02c3.85,0.01,7.34,1.57,9.86,4.1c2.5,2.51,4.06,5.98,4.07,9.82h0.02V13.96L89.62,13.96z M79.04,21.69v-7.73v-0.02h0.02 c0-0.91-0.39-1.75-1.01-2.37c-0.61-0.61-1.46-1-2.37-1v0.02h-0.01h-61.7h-0.02v-0.02c-0.91,0-1.75,0.39-2.37,1.01 c-0.61,0.61-1,1.46-1,2.37h0.02v0.01v64.59v0.02h-0.02c0,0.91,0.39,1.75,1.01,2.37c0.61,0.61,1.46,1,2.37,1v-0.02h0.01h12.19V35.65 v-0.01h0.02c0.01-3.85,1.58-7.34,4.1-9.86c2.51-2.5,5.98-4.06,9.82-4.07v-0.02h0.02H79.04L79.04,21.69z M105.18,108.92V35.65v-0.02 h0.02c0-0.91-0.39-1.75-1.01-2.37c-0.61-0.61-1.46-1-2.37-1v0.02h-0.01h-61.7h-0.02v-0.02c-0.91,0-1.75,0.39-2.37,1.01 c-0.61,0.61-1,1.46-1,2.37h0.02v0.01v73.27v0.02h-0.02c0,0.91,0.39,1.75,1.01,2.37c0.61,0.61,1.46,1,2.37,1v-0.02h0.01h61.7h0.02 v0.02c0.91,0,1.75-0.39,2.37-1.01c0.61-0.61,1-1.46,1-2.37h-0.02V108.92L105.18,108.92z"/></g></svg></button>`}function iy(e){let t=e.cloneNode(!0);return t.querySelectorAll("div,button").forEach(n=>n.remove()),t.textContent??""}function OM(e){return e.replace(/\r\n/g,`
|
|
25
25
|
`)}var NM=({content:e,useLabel:t,copyLabel:n,onCopy:r,onUse:o})=>{let i=A("Markdown",lT),s=(0,qr.useRef)(null),[a,l]=(0,qr.useState)(null),u=(0,qr.useMemo)(()=>{let y=ll(OM(e));return sT.sanitize(y).replace(/<\/code>/g,`${IM(i.copyIcon)}</code>`)},[e]),c=y=>{var g;let v=y.target,p=!!((g=s.current)!=null&&g.querySelector("code"));a||p&&v.tagName!=="CODE"||!p&&v!==s.current||(v.addEventListener("mouseleave",()=>l(null),{once:!0}),l(v))},f=()=>{if(!a)return;l(null);let y=a.querySelector("button");y&&(ss(y,i.fadeup),r(iy(a)))},d=y=>{y.target.tagName.toLowerCase()==="button"&&(ss(y.target,i.fadeup),r(iy(y.target.parentElement)))},m=()=>{a&&(l(null),o(iy(a)))};return(0,nr.jsxs)(qr.Fragment,{children:[a&&(0,nr.jsx)(is,{triggerRef:{current:a},parentNode:a,className:i.popover,children:(0,nr.jsxs)("div",{className:i.options,children:[(0,nr.jsx)("button",{type:"button",className:i.option,onClick:f,children:n}),(0,nr.jsx)("div",{className:i.divider}),(0,nr.jsx)("button",{type:"button",className:i.option,onClick:m,children:t})]})}),(0,nr.jsx)("div",{ref:s,className:i.root,dangerouslySetInnerHTML:{__html:u},onMouseOver:c,onClick:d})]})},uT=NM;var sy={};Qe(sy,{enUS:()=>MM,nlNL:()=>_M});var MM={useCue:[{type:0,value:"Use"}],copyCue:[{type:0,value:"Copy"}],removeCue:[{type:0,value:"Close"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}]},_M={useCue:[{type:0,value:"Gebruik"}],copyCue:[{type:0,value:"Kopieer"}],removeCue:[{type:0,value:"Sluiten"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}]};var cT={fadeup:"N",fadedown:"A",selected:"vo",thumbsUp:"nr",thumbsDown:"ar"};var Rt=w(b()),FM=({cue:e,onRemove:t,onCopy:n,onUse:r,onThumbsUp:o,onThumbsDown:i})=>{let s=A("WidgetCue",cT),a=G(sy),l=Jd(),[u,c]=(0,of.useState)(null),f=p=>{n&&n(p,e)},d=p=>{r&&r(p,e)},m=p=>{p.preventDefault(),p.stopPropagation(),t(e)},y=p=>{p.preventDefault(),p.stopPropagation(),ss(p.target,s.fadeup),c("up"),o(e)},v=p=>{p.preventDefault(),p.stopPropagation(),ss(p.target,s.fadedown),c("down"),i(e)};return(0,of.useEffect)(()=>{l("Assistant response displayed",{name:e.rule.name,description:e.rule.description,group:e.rule.label})},[]),(0,Rt.jsxs)(oe,{"data-testid":"cue",children:[(0,Rt.jsx)(fe,{children:(0,Rt.jsxs)(fe.Content,{children:[e.title&&(0,Rt.jsx)(fe.Title,{"data-testid":"widget-cue-title",children:e.title}),(0,Rt.jsx)(uT,{content:e.text,useLabel:a("useCue"),copyLabel:a("copyCue"),onCopy:f,onUse:d})]})}),(0,Rt.jsx)(oe.IconButton,{title:a("thumbsUp"),onClick:y,icon:(0,Rt.jsx)(qb,{}),className:(0,ay.default)(s.thumbsUp,u==="up"&&s.selected),disabled:!!u}),(0,Rt.jsx)(oe.IconButton,{title:a("thumbsDown"),onClick:v,icon:(0,Rt.jsx)(Wb,{}),className:(0,ay.default)(s.thumbsDown,u==="down"&&s.selected),disabled:!!u}),(0,Rt.jsx)(oe.IconButton,{title:a("removeCue"),onClick:m,icon:(0,Rt.jsx)($b,{})})]})},dT=FM;var ul=w(b()),HM=({cues:e})=>{let t=Y(),n=zt(),r=Jd(),o=u=>{t(bb({id:u.rule.id})),r("Assistant response closed",{name:u.rule.name,group:u.rule.label,description:u.rule.description})},i=(u,c)=>{ko(u),r("Assistant response copied",{name:c.rule.name,group:c.rule.label,description:c.rule.description,copiedText:u})},s=(u,c)=>{n.send(Dr,{text:u,suggestion:{source:"cue",sourceText:u}}),r("Assistant response used",{name:c.rule.name,group:c.rule.label,description:c.rule.description,usedText:u})},a=u=>{r("Assistant response feedback",{name:u.rule.name,group:u.rule.label,description:u.rule.description,thumb:"up"})},l=u=>{r("Assistant response feedback",{name:u.rule.name,group:u.rule.label,description:u.rule.description,thumb:"down"})};return(0,ul.jsx)(ul.Fragment,{children:e.map(u=>(0,ul.jsx)(dT,{cue:u,onRemove:o,onCopy:i,onUse:s,onThumbsDown:l,onThumbsUp:a},u.rule.id))})},fT=HM;var mT=w(D());var UM=/(https?:\/\/[^\s]+)/,pT=e=>e.split(" ").find(t=>UM.test(t));var Wt=w(b()),BM=({suggestion:e,lines:t,onUse:n})=>{var c;let r=e.text||e.url||e.message,o=pT(r),i=G(No),s=j("showImages"),a=j("fallbackImage"),l=f=>{f.preventDefault(),f.stopPropagation(),n(r)},u=(0,mT.useCallback)(f=>{window.open(o,"_blank"),f.stopPropagation(),f.preventDefault()},[o]);return(0,Wt.jsxs)(oe,{onClick:l,"data-testid":"edit-suggestion",children:[(0,Wt.jsxs)(fe,{children:[s&&e.image&&(0,Wt.jsx)(fe.Image,{src:Wd(e,"small",a||void 0),title:e.title}),(0,Wt.jsxs)(fe.Content,{children:[e.title&&(0,Wt.jsx)(fe.Title,{"data-testid":"widget-suggestion-title",children:e.title}),e.searchKeywords&&((c=e.searchKeywords)==null?void 0:c.length)>0&&(0,Wt.jsx)(oe.Labels,{labels:e.searchKeywords}),(0,Wt.jsx)(fe.Content,{cropText:t==="single",lineClamp:t==="multiple",children:r})]})]}),(0,Wt.jsxs)(oe.Actions,{children:[o&&(0,Wt.jsx)(oe.ActionButton,{onClick:u,label:i("visitUrl")}),(0,Wt.jsx)(oe.ActionButton,{primary:!0,onClick:l,label:i("useSuggestion")})]})]})},gT=BM;var cl=w(b()),jM=({lines:e,suggestions:t})=>{let n=zt(),r=(o,i)=>{n.send(Dr,{text:o,suggestion:{...i,source:i.source,sourceText:i.text}})};return(0,cl.jsx)(cl.Fragment,{children:t.map(o=>(0,cl.jsx)(gT,{suggestion:o,lines:e,onUse:i=>r(i,o)},o.text||o.url||o.message))})},hT=jM;var ly={};Qe(ly,{enUS:()=>zM,nlNL:()=>VM});var zM={waiting:[{type:0,value:"Loading\u2026"}],notSupported:[{type:0,value:"This conversation is not supported"}],noResults:[{type:0,value:"No results found\u2026"}],titleAutoflows:[{type:0,value:"Autoflows"}],titleCustomMessages:[{type:0,value:"Quick replies"}],titleCues:[{type:0,value:"Assistant updates"}],actions:[{type:0,value:"Shortcuts"}],linkStudioLogin:[{type:0,value:"My "},{type:1,value:"productName"}],linkSummary:[{type:0,value:"Summarize"}],linkKnowledgeSearch:[{type:0,value:"Knowledge Assist"}],linkSearch:[{type:0,value:"Search"}]},VM={waiting:[{type:0,value:"Laden\u2026"}],notSupported:[{type:0,value:"Dit gesprek wordt niet ondersteund"}],noResults:[{type:0,value:"Geen resultaten gevonden\u2026"}],titleAutoflows:[{type:0,value:"Autoflows"}],titleCustomMessages:[{type:0,value:"Quick replies"}],titleCues:[{type:0,value:"Assistant updates"}],actions:[{type:0,value:"Shortcuts"}],linkStudioLogin:[{type:0,value:"Mijn "},{type:1,value:"productName"}],linkSummary:[{type:0,value:"Gesprek samenvatten"}],linkKnowledgeSearch:[{type:0,value:"Knowledge assist"}],linkSearch:[{type:0,value:"Zoeken"}]};var yT={root:"pr",loginText:"dr",stateText:"ko",sectionList:"lr",shortcutList:"sr",shortcut:"cr",link:"zo"};var Q=w(b()),sf=(e,t)=>{let n=O(tt);(0,ST.useEffect)(()=>n?t.every(r=>!!r)?e():()=>{}:()=>{},[...t,n])},$M=({onLogIn:e})=>{let t=G(ly),n=Y(),r=j("isEmbedded"),o=A("Widget",yT),i=j("showAutoflows"),s=j("showCustomMessages"),a=j("showSummaryCommand"),l=j("showKnowledgeSearch"),u=j("showSearch"),c=O(jr),f=O(Td),d=O(ib),m=O(Eb),y=O(bd),v=O(cb),p=O(Dc),g=O(zi),h=O(tt),S=O(_c),x=O(kb),T=O(kd),C=zt(),k=O(tC),L=O(vb("/admin/")),I=j("adminUrl"),N=j("productName");if(sf(()=>(n(nl(S)),n(gb(S)),()=>{n(hb(S))}),[n,g,s,S]),sf(()=>(n(er(S)),n(sb(S)),()=>{n(ab(S))}),[n,g,i,S]),sf(()=>{f.forEach(({type:_})=>{n(_==="entities"?an():un(_))})},[n,g,p,c]),sf(()=>(n(Uh()),()=>{n(wb())}),[n]),g===!1)return(0,Q.jsx)("div",{className:o.stateText,children:(0,Q.jsx)("div",{children:(0,Q.jsx)("p",{children:t("notSupported")})})},"supported");if(h===!1)return(0,Q.jsx)("div",{className:o.loginText,children:(0,Q.jsx)("div",{children:(0,Q.jsx)(Nd,{isEmbedded:r,loginUrl:I,onLogIn:e})})},"login");if(!c||!S||h===null||k||x)return(0,Q.jsx)("div",{className:o.stateText,children:(0,Q.jsx)("div",{children:(0,Q.jsx)("p",{children:t("waiting")})})},"waiting");let V=u||a||l||L;return(0,Q.jsx)("div",{className:(0,vT.default)(o.root),"data-testid":"widget",children:(0,Q.jsxs)(Dl,{className:o.sectionList,children:[V&&(0,Q.jsx)(In,{title:t("actions"),type:"shortcuts",children:(0,Q.jsxs)("div",{className:o.shortcutList,children:[u&&(0,Q.jsxs)("button",{className:o.shortcut,"data-testid":"shortcut-search",onClick:()=>C.send("ShowCommandPalette",{isOpen:!0}),children:[(0,Q.jsx)(qi,{}),t("linkSearch")]}),a&&(0,Q.jsxs)("button",{className:o.shortcut,"data-testid":"shortcut-summary",onClick:()=>C.send("ShowCommandPalette",{isOpen:!0,page:"summary"}),children:[(0,Q.jsx)(Vb,{}),t("linkSummary")]}),l&&(0,Q.jsxs)("button",{className:o.shortcut,"data-testid":"shortcut-knowledge-assist",onClick:()=>C.send("ShowCommandPalette",{isOpen:!0,page:"knowledgeAssist"}),children:[(0,Q.jsx)(zb,{}),t("linkKnowledgeSearch")]}),L&&(0,Q.jsxs)("a",{className:o.shortcut,target:"_blank",href:L,"data-testid":"shortcut-studio-login",rel:"noreferrer",children:[(0,Q.jsx)(jb,{}),t("linkStudioLogin",{productName:N})]})]})}),s&&v.length>0&&(0,Q.jsx)(In,{type:"custom-messages","data-testid":"custom-messages",children:(0,Q.jsx)(ht,{withDivider:!0,children:v.map(_=>(0,Q.jsx)(Hb,{suggestion:_},_.text))})}),i&&d.length>0&&(0,Q.jsx)(In,{type:"autoflows",title:t("titleAutoflows"),"data-testid":"autoflows",children:(0,Q.jsx)(ht,{withDivider:!0,children:(0,Q.jsx)(Db,{})})}),f.map(({type:_,title:ee,amount:Yr,lines:it})=>{var Gt;switch(_){case"entities":return y&&y.length>0&&(0,Q.jsx)(In,{type:_,title:ee,"data-testid":`type-${_}`,children:(0,Q.jsx)(Bb,{entities:y})},_);case"cues":return m&&m.length>0&&(0,Q.jsx)(In,{type:_,title:ee,"data-testid":`type-${_}`,children:(0,Q.jsx)(ht,{withDivider:!0,children:(0,Q.jsx)(fT,{cues:m})})},_);default:return((Gt=T[_])==null?void 0:Gt.fetchState)==="done"&&T[_].suggestions.length>0&&(0,Q.jsx)(In,{type:_,title:ee,"data-testid":`type-${_}`,children:(0,Q.jsx)(ht,{withDivider:!0,children:(0,Q.jsx)(hT,{lines:it,contentType:_,suggestions:T[_].suggestions.slice(0,Yr)||[]})})},_)}})]})})},wT=$M;function as(e){let t=new Range;return t.selectNodeContents(e),t}function xT(e,t,n){try{return Gr(e,t,n),!0}catch{return!1}}function af(e){return"tagName"in e&&(e.tagName==="DIV"||e.tagName==="P")}function lf(e){return"tagName"in e&&e.tagName==="BR"}var dl=/[\u200B-\u200D\uFEFF]/g;function Gr(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){switch(l.nodeType){case Node.TEXT_NODE:{let u=l.textContent,c=u.replace(dl,""),f=o+c.length,d=t>=o&&t<=f,m=n>=o&&n<=f;if(d){let y=s(u,t-o);y===0&&!m?r.setStartBefore(l):r.setStart(l,y)}m&&(r.setEnd(l,s(u,n-o)),i=!0),o=f;break}case Node.ELEMENT_NODE:{if(lf(l)&&(o===t&&r.setStartBefore(l),o++,o===n)){r.setEndAfter(l),i=!0;return}for(let c=0;c<l.childNodes.length&&(a(l.childNodes[c]),!i);c++);let u=l.lastChild;af(l)&&u&&!af(u)&&!lf(u)&&o++;break}default:break}}if(a(e),r.startContainer===document)throw new Error("Offsets out of bound");return r}function fl(e,t){if(!e.contains(t.startContainer)||!e.contains(t.endContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:r,endContainer:o,endOffset:i,collapsed:s}=t,a,l,u=0;function c(f){let d=f===n,m=f===o;switch(f.nodeType){case Node.TEXT_NODE:{let y=f.textContent;d&&(a=u+y.substring(0,r).replace(dl,"").length),m&&(l=u+y.substring(0,i).replace(dl,"").length),u+=y.replace(dl,"").length;break}case Node.ELEMENT_NODE:{let y=f.nextSibling===null;lf(f)&&!y&&u++;for(let v=0;v<f.childNodes.length;v++){let p=d&&v===r,g=m&&v===i;if(p&&(a=u),g&&(l=u),l!==void 0||((!p||!s)&&c(f.childNodes[v]),m&&v===i-1&&(l=u),l!==void 0))break}!m&&af(f)&&!y&&u++,m&&(l=u);break}default:break}}if(c(e),l===void 0)throw new Error("Could not determine start and end");return{start:a??l,end:l}}function pl(e,t){if(!e.contains(t.startContainer)||!e.contains(t.endContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:r,endContainer:o,endOffset:i}=t,s=-1,a="";function l(u){let c=u===n,f=u===o;switch(c&&s++,u.nodeType){case Node.TEXT_NODE:{if(s!==0)return;let d=c?r:0,m=f?i:void 0,y=u.textContent.replace(dl,"");d===0&&m===void 0?a+=y:a+=y.substring(d,m);break}case Node.ELEMENT_NODE:{let d=u.nextSibling===null;s===0&&lf(u)&&!d&&(a+=`
|
|
26
26
|
`);for(let m=c?r:0;m<(f?Math.min(i,u.childNodes.length):u.childNodes.length)&&(l(u.childNodes[m]),s!==1);m++);!f&&s===0&&af(u)&&!d&&(a+=`
|
|
27
|
-
`);break}default:break}f&&s++}return l(e),a}var ET=(s=>(s.CUT="Cut",s.BACKSPACE="Backspace",s.DELETE="Delete",s.ERASEEOF="EraseEof",s.UNDO="Undo",s.CLEAR="Clear",s))(ET||{}),rr=class{constructor(t){this.element=t;this.currentText=this.getText(),this.currentHTML=this.getHTML(),this.listen()}eventListeners={};disposeHandlers=[];currentText="";currentCaret=null;currentSelection={start:0,end:0};currentHTML="";isFocused=!1;isActive=!0;isSettingValue=!1;isSubmitting=!1;isPossibleClearInputAction=!1;isDisposed=!1;addEventListener(t,n){let r=o=>{n(o)};this.element.addEventListener(t,r),this.disposeHandlers.push(()=>{this.element.removeEventListener(t,r)})}removeEventListener(t,n){this.element.removeEventListener(t,n)}triggerChange(){let t=this.getText(),n=this.getHTML(),r=t!==this.currentText;this.isActive&&(t===""&&this.currentText!==""&&!this.isSettingValue&&!this.isPossibleClearInputAction&&(this.isSubmitting=!0,this.emit("submit")),!this.isSettingValue&&r&&!this.isSubmitting&&this.emit("change",{plainText:t}),r&&(this.currentSelection=this.getSelection()),this.currentText=t,this.isSubmitting=!1,(this.currentHTML!==n||n===null&&r)&&(this.emit("updated",{plainText:t}),this.triggerCaretPosition(),this.currentHTML=n))}triggerSelection(){let t=this.getSelection();(t.start!==this.currentSelection.start||t.end!==this.currentSelection.end)&&(this.currentSelection=t,this.emit("selection",t),this.triggerCaretPosition())}triggerCaretPosition(){let t=this.getCaretPosition();Nr(t,this.currentCaret)||(this.currentCaret=t,this.emit("caret",t))}handleKeyUp(t){let{key:n,shiftKey:r}=t;(n==="Enter"&&r===!0||n==="Backspace")&&this.triggerChange(),this.triggerSelection()}handleClick(){this.triggerSelection()}handleFocus(){this.isFocused||this.emit("focus"),this.triggerSelection(),this.isFocused=!0}handleBlur(){this.isPossibleClearInputAction=!1,this.isFocused&&this.emit("blur"),this.isFocused=!1}handleKeyDown(t){let{key:n,ctrlKey:r,metaKey:o}=t;this.isPossibleClearInputAction=Object.values(ET).includes(n)||n.toLowerCase()==="z"&&(r||o),this.emit("keydown",t)}handleCut(){this.isPossibleClearInputAction=!0,this.emit("cut",{selectionText:this.getSelectedText()})}handlePaste(t){var r,o;let n=((r=t.clipboardData)==null?void 0:r.getData("text"))||((o=t.clipboardData)==null?void 0:o.getData("text/plain"))||"";this.emit("paste",{pastedText:n,selectionText:this.getSelectedText()})}listen(t={shouldObserve:!0}){this.addEventListener("keydown",r=>this.handleKeyDown(r)),this.addEventListener("keyup",r=>this.handleKeyUp(r)),this.addEventListener("input",()=>this.triggerChange()),this.addEventListener("change",()=>this.triggerChange()),this.addEventListener("focus",()=>this.handleFocus()),this.addEventListener("blur",()=>this.handleBlur()),this.addEventListener("cut",()=>this.handleCut()),this.addEventListener("paste",r=>this.handlePaste(r)),this.addEventListener("click",()=>this.triggerSelection()),document.activeElement===this.element&&setTimeout(()=>{this.handleFocus()},0);let n=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});t!=null&&t.shouldObserve&&n.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{n.disconnect()}),this.currentSelection=this.getSelection()}focus(){this.element.focus()}emit(t,...n){this.isDisposed||this.eventListeners[t]&&this.eventListeners[t].forEach(r=>{r(...n)})}on(t,n){this.isDisposed||(this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n))}activate(){let t=this.isActive===!1;this.isActive=!0,t&&this.triggerChange()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(t=>t()),this.eventListeners={},this.isDisposed=!0}};function CT(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var zo=class extends rr{observer;lastKnownSelection=null;getRootNode(){return this.element.getRootNode()}getText(){let t=new Range;return t.selectNodeContents(this.element),pl(this.element,t)}getHTML(){return this.element.innerHTML||""}getRange(){var i;let t=this.getRootNode();if(t.activeElement!==this.element)return null;let n="getSelection"in t?t.getSelection():window.getSelection();if(!n)return null;let r="getComposedRanges"in n&&t instanceof ShadowRoot?(i=n.getComposedRanges(t))==null?void 0:i[0]:n.rangeCount>0?n.getRangeAt(0):null;if(!r)return null;let o=this.element.ownerDocument.createRange();return o.setStart(r==null?void 0:r.startContainer,r==null?void 0:r.startOffset),o.setEnd(r==null?void 0:r.endContainer,r==null?void 0:r.endOffset),!o||!this.element.contains(o.startContainer)||!this.element.contains(o.endContainer)?null:o}getCaretPosition(){let t=this.getRange();if(!t||!t.collapsed||!("getBoundingClientRect"in t))return null;let n=t.getBoundingClientRect();return!CT(n)&&(t.insertNode(this.element.ownerDocument.createTextNode("\u2060")),n=t.getBoundingClientRect(),t.deleteContents(),!CT(n))?null:{top:n.top+n.height,left:n.left}}getSelection(){let t=this.getRange();if(t)return fl(this.element,t);let n=this.lastKnownSelection;if(n&&xT(this.element,n.start,n.end))return n;let r=as(this.element);return r.collapse(!1),fl(this.element,r)}getSelectedText(){let{start:t,end:n}=this.getSelection();return pl(this.element,Gr(this.element,t,n))}applyChanges(t){var o;if(!this.isActive)return;this.isSettingValue=!0;let n=this.getText(),r=t(this.element);return(o=this.observer)==null||o.takeRecords(),Promise.resolve(r).then(()=>{this.currentText=this.getText(),n!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(t={shouldObserve:!0}){super.listen(t),this.observer=new MutationObserver(()=>{setTimeout(()=>{this.triggerChange()},0)}),t!=null&&t.shouldObserve&&this.observer.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0});let n=this.element.isContentEditable,r=new MutationObserver(()=>{this.element.isContentEditable!==n&&(n=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});r.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>r.disconnect())}dispose(){super.dispose(),this.observer&&this.observer.disconnect()}};var Vo=class extends rr{lastKnownSelection=null;getText(){return this.element.value}getHTML(){return null}getSelection(){let{selectionStart:t,selectionEnd:n}=this.element;return{start:t,end:n}}getSelectedText(){let t=this.getSelection();return t?this.getText().slice(t.start,t.end):""}getCaretPosition(){return null}applyChanges(t){if(!this.isActive)return;this.isSettingValue=!0;let n=this.getText(),r=t(this.element);return Promise.resolve(r).then(()=>{this.currentText=this.getText(),n!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(){super.listen();let t=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var o;return(o=t==null?void 0:t.get)==null?void 0:o.call(this.element)},set:o=>{var i;(i=t==null?void 0:t.set)==null||i.call(this.element,o),this.triggerChange()}});let n=this.element.disabled,r=new MutationObserver(()=>{this.element.disabled!==n&&(n=this.element.disabled,this.emit(n?"disabled":"enabled"))});r.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>r.disconnect())}};function bT(e,t,n){let r=`deepdesk-iframe-${e}`,o=document.getElementById(r);if(o)return o;let i=document.createElement("iframe"),s=new URL(t);return Object.entries(n).forEach(([a,l])=>{s.searchParams.append(a,l)}),i.style.position="absolute",i.style.left="-999em",i.style.width="0px",i.style.height="0px",i.tabIndex=-1,i.id=r,i.title=`iframe-${e}`,i.src=s.toString(),window.document.body.appendChild(i),i}function WM(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}var uy=class{constructor(t){this.name=t;this.broadcastChannel=new BroadcastChannel(t)}broadcastChannel;disposeHandlers=[];onMessage(t){this.broadcastChannel.addEventListener("message",t),this.disposeHandlers.push(()=>{this.broadcastChannel.removeEventListener("message",t)})}postMessage(t){this.broadcastChannel.postMessage(JSON.stringify(t))}close(){this.disposeHandlers.forEach(t=>t()),this.broadcastChannel.close()}},cy=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.iframe=bT(t,`${this.targetOrigin}/sdk/proxy/proxy.html`,{channel:this.name,host:window.location.origin,debug:"1"}),document.body.appendChild(this.iframe)}iframe;disposeHandlers=[];onMessage(t){window.addEventListener("message",t),this.disposeHandlers.push(()=>{window.removeEventListener("message",t)})}postMessage(t){var n;(n=this.iframe.contentWindow)==null||n.postMessage(JSON.stringify(t),this.targetOrigin)}close(){var t;this.disposeHandlers.forEach(n=>n()),(t=this.iframe)==null||t.remove()}},dy=class{constructor(t){this.params=t;this.deepdeskUrl=t.deepdeskUrl,this.eventMap=t.eventMap,this.sessionId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}sessionId;deepdeskUrl;channel;defaultChannel;eventMap;get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setSessionId(t){this.sessionId!==t&&(this.cleanup(),z.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 cy(t,this.deepdeskUrl,{debug:!0}):new uy(t),r=o=>{var s,a;if(o.origin!==this.deepdeskUrl)return;let i=WM(o.data);typeof i!="object"||i.type!=="event"||i.channel!==t||(z.info("Received broadcast event",this.sessionId,o),(a=(s=this.eventMap)[i.name])==null||a.call(s,i.payload))};return n.onMessage(r),n}send(t,n,r){var s,a;z.info("Broadcast event",{sessionId:this.sessionId,name:t,payload:n});let o={type:"event",name:t,payload:n};r!==!1&&((a=(s=this.eventMap)[t])==null||a.call(s,n));let i=this.sessionId==="deepdesk-general"?this.defaultChannel:this.channel;i==null||i.postMessage({...o,channel:this.sessionId})}cleanup(t=!1){var n,r;(n=this.channel)==null||n.close(),delete this.channel,t&&((r=this.defaultChannel)==null||r.close(),delete this.defaultChannel)}},TT=dy;var ls=class extends Error{constructor(n,r){super(n);this.body=r}name="CustomError"};var fy=e=>new Promise(t=>{setTimeout(t,e)});var us=class extends ls{name="ClientError"},my=class extends ls{name="ServerError"},py=new Map,pn=class e{constructor(t="",n={}){this.baseUrl=t;this.options=n;n.fetch&&(this.fetch=n.fetch)}latestRequestByUrl={};csrfToken;fetch=window.fetch.bind(window);static refreshingToken=null;patchFetch(t){this.fetch=t(this.fetch)}setCsrfToken(t){this.csrfToken=t}request(t,n={}){return new Promise((r,o)=>{let i={isAborted:!1,reject:o},s=`${this.baseUrl}${t}`,a=this.fetch,l=n.method===void 0||n.method.toLowerCase()==="get",{useCache:u=!1,abortLatest:c=!1,attempts:f=1,retryDelay:d=500,refreshTokenOn401:m=!0,retryOnError:y=C=>C instanceof TypeError,retryOnResponse:v=C=>C.status>=500,version:p="v1",...g}=n;if(u)if(l){if(py.has(s)){r(py.get(s));return}}else throw new Error(`Can't use 'useCache' for ${n.method}`);let h={credentials:"include",...g,headers:{"Content-Type":"application/json",...g.headers}};!l&&this.csrfToken&&(h.headers={...h.headers,"X-CSRFToken":this.csrfToken}),typeof p=="string"&&(h.headers={...h.headers,"X-Deepdesk-API-Version":p});let S=f,x=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[s]&&c&&(this.latestRequestByUrl[s].isAborted=!0,this.latestRequestByUrl[s].reject(new Error("Aborted"))),this.latestRequestByUrl[s]=i;let T=async()=>(S--,a(s,h).then(async C=>v(C)&&!i.isAborted&&S>0?(await fy(d),T()):C.status===401&&m===!0&&x===!1?(x=!0,await this.refreshToken(),T()):C).catch(async C=>{if(y(C)&&!i.isAborted&&S>0)return await fy(d),T();throw C}));T().then(C=>C.json().catch(()=>null).then(k=>{C.status>=500?o(new my("Server Error",k)):C.status===401?o(new us("Unauthorized",k)):C.status===403?o(new us("Forbidden",k)):C.status===404?o(new us("Not Found",k)):C.status>=400&&o(new us("Bad Request",k)),delete this.latestRequestByUrl[s],u&&py.set(s,k),r(k)})).catch(C=>{o(C)})})}async validateToken(){let{has_valid_access_token:t}=await this.get("/auth/validate");if(!t)return!1;let{is_logged_in:n}=await this.get("/apis/admin/session/validate/",{version:null});return!!n}refreshToken(){return e.refreshingToken||(e.refreshingToken=this.get("/auth/refresh",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{e.refreshingToken=null},1e3*60)})),e.refreshingToken}get(t,n){return this.request(t,n)}post(t,n,r){return this.request(t,{method:"POST",body:JSON.stringify(n),...r})}patch(t,n,r){return this.request(t,{method:"PATCH",body:JSON.stringify(n),...r})}put(t,n,r){return this.request(t,{method:"PUT",body:JSON.stringify(n),...r})}delete(t,n){return this.request(t,{method:"DELETE",...n})}};var qM;(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||={})})(qM||={});function uf(e){return{...J(e),tags:e.tags}}var or=class e{constructor(t,n={}){this.options=n;this.client=new pn(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(),z.info(`Creating conversation for session ${t.sessionId} and agent ${t.agentId}`);let n=await this.client.post("/api/conversations",{...Ae(t),tags:t.tags},{version:"v2"});return uf(n)}async getProfile(t){let n=await this.client.get(`/apis/admin/profiles/${t}/`,{version:null,useCache:!0});return J(n)}async getKnowledgeAssistant(t){let n=await this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{version:null,useCache:!0});return J(n)}async getContentTypes(){let t=await this.client.get("/apis/admin/content-types/",{version:null,useCache:!0});return J(t)}async getAccount(){let t=await this.client.get("/apis/admin/account/",{version:null,useCache:!0});return J(t)}async getPlatformConfig(){let{config:t}=await this.client.get("/platform/config/",{version:null,useCache:!0});return J(t)}async checkUserExists(t){let{exists:n}=await this.client.get(`/apis/admin/users/exists?external_id=${t}`);return n}async getConversationBySessionId(t,n={}){await this.preflight(),z.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 z.info(`Successfully retrieved conversation ${i.id} for session ${t}`),uf(i)}async isConversationSupported(t,n={}){z.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=Ae(n);n.tags&&(r.tags=n.tags);let o=await this.client.put(`/api/conversations/${t}`,r,{version:"v2"});return uf(o)}async postMessages(t,n){return(await this.client.post(`/api/conversations/${t}/messages`,n.map(o=>({...Ae(o),tags:o.tags})),{version:"v2"})).map(o=>uf(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",Ae({...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:Ae({...n,...r})})}async getEntities(t){return(await this.client.post("/api/entities",{messages:t.filter(r=>r.text)})).entities}async getSummary(t,n={}){let r=await this.client.post("/api/summary",{conversation:{messages:t.filter(o=>o.text&&o.source),agent_id:n.agentId,id:n.externalConversationId},prompt_instruction:n.promptInstruction,model:n.model});return J(r)}async getTemporaryExchangeToken(){return(await this.client.get("/auth/exchange-token",{version:null})).jwt}async exchangeTokenForAccessCookie(t){return this.client.post("/apis/admin/session/jwt/",{jwt:t},{version:null}).catch(n=>{throw z.warn(`Invalid token '${t}'`),n})}async authenticateWithKey(t,n){await this.preflight(),await this.client.post("/apis/admin/session/api-key/",Ae(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}`,Ae(n),{abortLatest:!0})).map(i=>({...J(i),text:i.text||i.url||i.message,source:r,type:r})).filter((i,s,a)=>s===a.findIndex(l=>l.text===i.text))}async isLoggedIn(){return await this.preflight(),this.client.validateToken()}async getAutocompleteSuggestions(t,n){return(await this.client.post(`/api/conversations/${t}/autocomplete`,Ae(n),{abortLatest:!0})).map(o=>({score:1,source:o.source,sourceText:o.source_text,text:o.label,trainingJobs:o.training_jobs,searchKeywords:o.search_keywords,type:o.source})).filter((o,i,s)=>i===s.findIndex(a=>a.text===o.text))}async getPinnedMessages(t){let n=await this.client.get(`/api/conversations/${t}/sticky-messages`,{abortLatest:!0});return J(n).map(r=>({...r,text:r.message,source:"sticky-messages",type:"pinned-message"}))}async getStyleSuggestions(t){let n=await this.client.post("/api/style-suggestions",Ae(t),{abortLatest:!0});return J(n)}async search(t){let n=await this.client.post(`/api/profiles/${t.profile}/search`,Ae(t),{version:"v2"});return J(n)}async knowledgeAssist(t,n,r,o={}){let i=await this.client.post(`/api/knowledge-assist/assistants/${r}/search`,Ae({question:t.question,promptInstruction:t.promptInstruction,chatHistory:n.map(s=>({question:s.question,answer:s.answer.answer})),agentId:o.agentId,conversationId:o.conversationId}),{version:"v2"});return J(i)}async requestLoginByEmail(t){let n=await this.client.post("/apis/admin/session/passwordless/request/",{email:t},{version:null});return J(n)}async requestPasswordlessToken(){let t=await this.client.get("/apis/admin/session/passwordless/request/",{version:null});return J(t.token)}async getCsrfToken(){let{token:t}=await this.client.get("/apis/admin/session/csrf/",{version:null});return t}async verifyLoginToken(t){let n=await this.client.post("/apis/admin/session/passwordless/login/",{token:t},{version:null});return J(n)}async evaluateRule(t,n,r,o={}){let i=new URLSearchParams;o.raiseForFailingConditions&&i.set("raise_for_failing_conditions","true");let s=await this.client.post(`/api/conversations/${n}/rules/${t}/evaluate?${i.toString()}`,r,{version:"v2"});return J(s.cues)}async getRules(){let t=new URLSearchParams,n=await this.client.get(`/apis/admin/rule-engine/rules/?${t.toString()}`,{version:null,useCache:!0});return J(n)}async translateMessages(t){let n=await this.client.post("/api/translate",Ae(t),{version:"v2"});return J(n)}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),i=o.match(Ov);if(!n||!i)return;let s=i[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[s];a&&n&&a!==n&&z.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[s]=n})}};var ml=class{constructor(t,n){this.url=t;this.options={timeout:25e3,...n}}eventListeners={};options;timeoutTimer;eventSource;proxyEvent(t){this.eventSource.addEventListener(Dg(t),n=>{let{data:r}=n;try{let o=JSON.parse(r);this.emit(t,J(o))}catch{z.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 GM;(t=>{let e;(i=>(i.Started="Started",i.Aborted="Aborted",i.Completed="Completed"))(e=t.AutoflowSessionState||={})})(GM||={});var gl=class{constructor(t,n={}){this.apiUrl=t;this.client=new pn(t,n)}client;streams={};logger=z;async getCustomMessages(t){let n=await this.client.get(`/sessions/${t}/suggestions`);return J(n.suggestions)}async sendCustomMessage(t,n){let r=await this.client.post(`/sessions/${t}/messages`,Ae(n));return J(r)}async answerCustomMessage(t,n){await this.client.post(`/sessions/${t}/answers`,Ae(n))}async getAutoflows(t){let n=await this.client.get(`/sessions/${t}/autoflows`);return J(n.autoflows)}async startAutoflowSession(t){let n=await this.client.post("/autoflow-sessions",Ae(t));return J(n)}async stopAutoflowSession(t){await this.client.delete(`/autoflow-sessions/${t}`)}openStream(t){return this.streams[t]||(this.streams[t]=new ml(`${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 kT={startTime:null,stopTime:null},PT=W({name:"handlingTime",initialState:kT,reducers:{handlingTimeStart(e){if(e.startTime&&!e.stopTime)throw new Error("Timing already started");e.startTime=new Date,e.stopTime=null},handlingTimeStop(e){if(!e.startTime)throw new Error("Timing not started");e.stopTime=new Date},handlingTimeReset(e){e.startTime=null,e.stopTime=null}},extraReducers:e=>{e.addCase(le,()=>kT)}}),{handlingTimeStart:RT,handlingTimeStop:cf,handlingTimeReset:AT}=PT.actions,LT=PT.reducer;var IT=(e={})=>{let t={onAuthError:ji(!1),...e};return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var df={list:{keywordMatches:[]},fetchState:"idle",isInitialRequest:null};var Ko=B("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 df.list;if(!i)throw new Error("No current conversation to fetch pinned messages");return n.getStyleSuggestions({profileCode:i,message:e})}),YM=W({name:"styleSuggestions",initialState:df,reducers:{},extraReducers:e=>{e.addCase(Ko.pending,t=>{t.isInitialRequest=t.isInitialRequest===null,t.fetchState="loading"}).addCase(Ko.rejected,t=>{t.fetchState="error"}).addCase(Ko.fulfilled,(t,n)=>{t.fetchState="done",Nr(t.list,n.payload)||(t.list=n.payload)}).addCase(Eo,t=>{t.list=df.list}).addCase(le,()=>df)}}),OT=YM.reducer;var NT=(e={})=>{let t,n=!0,r={getStyleSuggestions:Ko,debounce:500,...e};return o=>i=>s=>{var m;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(!((m=u.conversation.current)==null?void 0:m.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 XM(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end}var MT=(e={})=>{let t={getTextSuggestions:un,getAutocompleteSuggestions:Xa,debounce:200,check:Ji,...e},n;return r=>o=>i=>{var v;let{input:{userCommitted:s}}=r.getState(),a=o(i),l=r.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:u,showTabCompletion:c}=l.settings,f=(v=l.conversation.current)==null?void 0:v.id,d=i.type===Pd.toString();if(!f||!u&&!c)return a;let{input:{userCommitted:m}}=l;return XM(m,s)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let p=Vi(l);p===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(p))},d?0:t.debounce)),a}};var _T=Ko.fulfilled.toString();function QM(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 DT=e=>t=>n=>r=>{var u;if(r.type!==_T){n(r);return}let o=t.getState().styleSuggestions.list;n(r);let i=t.getState(),s=i.styleSuggestions.list,a=(u=i.conversation)==null?void 0:u.current;if(o===s)return;let l=QM(o,s);r.type===_T&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var ZM=oc({answer:WE,auth:Zx,autoflows:lb,conversation:a1,contentTypes:oE,customMessages:yb,passwordlessToken:xb,entities:IE,knowledgeAssistant:VE,handlingTime:LT,info:k1,input:E1,settings:$x,profile:YE,search:N1,summary:HE,styleSuggestions:OT,ui:xC,rules:Tb,textSuggestions:oC});function FT(e){return Qw({reducer:ZM,middleware:t=>[...t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI,deepdeskBrokerAPI:e.deepdeskBrokerAPI}},serializableCheck:!1}),IT(),MT({debounce:200}),NT({debounce:500}),DT(e.deepdeskAPI),...e.middleware?e.middleware:[]],preloadedState:e.preloadedState})}var JM=e=>{var t;return((t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())??"unknown"},e2=e=>t=>n=>r=>{var a;let o=t.getState(),i=Ag("inlineSuggestions")(o);switch(r.type){case ji.toString():{!r.payload&&e.emit("logout",void 0);break}case an.fulfilled.toString():r.payload.length>0&&e.sendEvent("entities found",{conversationId:o.conversation.current.id,data:{entities:r.payload}});break;case Ye.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 Vc.toString():e.handleKeyDown(r.payload);break;case Eo.toString():e.logSendMessage(r.payload);break;case Kc.toString():e.handleInputChanged(r.payload);break;case Bo.fulfilled.toString():r.isBroadcasted||e.broadcast(Ug,r,!1),e.emit("cues",r.payload);break;default:break}let s=n(r);switch(r.type){case Eo.toString():e.handleAfterSendMessage(r.payload);break;case Za.toString():e.onUpdateShowTabHint(r.payload);break;case cf.toString():e.logHandlingTime();break;case Cn.toString():{let{start:l,end:u}=o.input.selection;e.emit("select-suggestion",{type:JM(r.payload.suggestion),...r.payload,replace:r.payload.replace==="selection"?{start:l,end:u}:{start:0,end:u}},{mayApplyChanges:!0}),i&&(t.dispatch(En([])),t.dispatch(Kn()));break}case zc.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 ka.toString():{let l=t.getState(),{text:u,selection:c}=l.input.userCommitted;e.emit("reset",{text:u,selectionAfter:c},{mayApplyChanges:!0});break}case $c.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 En.toString():{i&&r.payload.length>0&&t.dispatch(_r(0));break}case Gn.fulfilled.toString():{e.sendEvent("conversation summarized",{conversationId:o.conversation.current.id,data:{summary:r.payload.summary,model:t.getState().summary.model}});break}default:break}return s},HT=e2;function gy(e){return e.toISOString().replace("T"," ").replace("Z","")}function UT(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:gy(n),timeStop:gy(r)}}function BT(e,t,n){var k,L,I;let{text:r,metrics:{numCharsTyped:o,numCharsPasted:i,numCharsCut:s,numCharsDeleted:a,numPaste:l,agentStartedTypingTimestamp:u,externalTimeTotalSeconds:c,pastes:f,cuts:d,deletions:m,textSuggestions:y,offeredTextSuggestions:v}}=t[e],p=r.length,h=y.reduce((N,{text:V,searchTerm:_})=>N+V.length-(_?_.length:0),0),S=u??Date.now(),x=(Date.now()-S)/1e3+(c||0),T=o/x,C=y.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:m,lenTextTyped:o+C,lenTextTotal:p,lenTextAssisted:h,lenTextPasted:i,lenTextCut:s,lenTextDeleted:a,timeTotalSeconds:x,charsPerSecond:T,numPastes:l,textSuggestionsV2:y,suggestionsCounters:[{source:"gpt",countOffered:v.filter(N=>N.source==="gpt").length}],agentId:(k=t.info.agentInfo)==null?void 0:k.agentId,agentName:(L=t.info.agentInfo)==null?void 0:L.agentName,agentEmail:(I=t.info.agentInfo)==null?void 0:I.agentEmail}}function hy(e,t){var i;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return hy(r,t);let o=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;return o?hy(o,t):null}function jT(e,t){return hy(e,t)}function zT(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function t2(e){return typeof e=="object"&&e!==null&&"tagName"in e}function ff(e){return t2(e)&&(Kr(e)||_d(e))}var VT,kn=new Map,n2=["bottom","height","left","right","top","width"],r2=(e={},t={})=>n2.some(n=>e[n]!==t[n]);function KT(e){var n,r;if(e.ownerDocument===document)return[];let t=((r=(n=e.ownerDocument)==null?void 0:n.defaultView)==null?void 0:r.frameElement)??null;return t?[t,...KT(t)]:[]}function $T(e,t){return!e||!t?null:{...e,top:e.top+t.top,left:e.left+t.left}}var pf=!1,WT=()=>{pf=!0;let e=[];if(kn.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),kn.delete(n);return}let r=n.getBoundingClientRect();r2(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{let n=t.parentRects?t.parentRects.reduce($T,t.rect):t.rect;t.callbacks.forEach(r=>r(n))}),kn.size===0){pf=!1;return}VT=window.requestAnimationFrame(WT)};function yy(e,t){let n=KT(e),r=[],o=n.map((i,s)=>yy(i,a=>{r[s]=a;let l=kn.get(e);if(!l)return;let u=r.reduce($T,l.rect);l.callbacks.forEach(c=>c(u))}));return{observe(i=!0){if(o.forEach(s=>s.observe(!1)),kn.has(e)){let s=kn.get(e);s.callbacks.push(t),s.rect&&t(s.rect)}else kn.set(e,{rect:void 0,callbacks:[t],parentRects:r});i&&!pf&&WT()},unobserve(){o.forEach(s=>s.unobserve());let i=kn.get(e);if(i){let s=i.callbacks.indexOf(t);s>=0&&i.callbacks.splice(s,1),i.callbacks.length||kn.delete(e),kn.size||(cancelAnimationFrame(VT),pf=!1)}}}}var qT,Pn=new Map,GT=()=>{Pn.forEach((e,t)=>{if(!t.isConnected){Pn.delete(t);return}let{clientHeight:n,scrollHeight:r}=t,o=r>n;e.visible!==o&&(e.visible=o,e.callbacks.forEach(i=>i(e.visible)))}),Pn.size!==0&&(qT=window.requestAnimationFrame(GT))};function YT(e,t){return{observe(){let n=Pn.size===0;Pn.has(e)?Pn.get(e).callbacks.push(t):Pn.set(e,{visible:void 0,callbacks:[t]}),n&>()},unobserve(){let n=Pn.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||Pn.delete(e),Pn.size||cancelAnimationFrame(qT)}}}}var vy=["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 Sy(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function cs(e){return parseFloat(e)}function mf(e){return Math.round(e*1e6)}function XT(e){return e/1e6}function wy(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=cs(e.width),i=cs(e.borderLeftWidth),s=cs(e.borderRightWidth),a=cs(e.paddingRight),l=XT(mf(o)-mf(i)-mf(s)),u=XT(mf(r));if(l-u>2){let c=l-u;n.style.paddingRight=`${a+c}px`}}function hl(e,t={}){var c;let n=t.overlayContainer||document.createElement("div");n.style.display="none",n.style.position=t.position??"fixed",n.style.pointerEvents="none",n.style.borderColor="transparent",Fo(n);let r=window.getComputedStyle(e),o=!0,i=()=>{n.scrollTop=e.scrollTop};Sy(r,n,vy),wy(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",i));let s=YT(e,()=>{Sy(r,n,vy),wy(r,e,n),i(),setTimeout(i,0)}),a,l=!0,u=yy(e,f=>{if(f===null){t.onRemove&&t.onRemove(),n.remove();return}if(!l&&t.onMoveStart&&(Promise.resolve().then(()=>t.onMoveStart()),l=!0),clearTimeout(a),a=setTimeout(()=>{t.onMoveEnd&&t.onMoveEnd(),l=!1},200),f.height===0&&f.width===0){if(o===!0)return;t.onHide&&t.onHide(),n.style.display="none",o=!0;return}if(Sy(r,n,vy),wy(r,e,n),i(),n.style.top=`${f.top}px`,n.style.left=`${f.left}px`,t.closestScrollElement&&t.closestScrollElement!==e){let d=t.closestScrollElement.getBoundingClientRect(),m=window.getComputedStyle(t.closestScrollElement),y=cs(m.borderTopWidth),v=cs(m.borderBottomWidth),p=d.top+y-f.top,g=f.top+f.height+-(d.top+d.height-v);n.style.clipPath=`inset(${p}px 0px ${g}px 0px)`}o&&(n.style.display="block",t.onShow&&t.onShow(),o=!1)});return t.appendTo?t.appendTo.appendChild(n):(c=e.parentElement)==null||c.appendChild(n),u.observe(),s.observe(),[n,()=>{e.removeEventListener("scroll",i),u.unobserve(),s.unobserve()}]}var QT=(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{z.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function o2(e){return e.offsetParent!==null}function ZT(e){if(!o2(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 gf(e,t,n=100){let r=ZT(e);t({isVisible:r});let o=setInterval(()=>{let i=ZT(e);i!==r&&(r=i,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var Ie=w(b());var JT=QT("showTabHint",!0),yl=class e{static version="11.2.1-beta.2";static count=0;deepdeskApi;inputMediator=null;version;broadcastEvents;eventListeners={};unmountHandlers=[];widgetRoot=null;dynamicThunkObject={};isMounted=!1;instanceId;shouldRender=!0;store;constructor({deepdeskUrl:t,brokerUrl:n,version:r=e.version||"unknown",locale:o="en-US",token:i,fetch:s,productName:a,createCustomChannel:l}){let u=t.replace(/\/api$/,"");this.deepdeskApi=new or(u,{token:i,fetch:s}),this.version=r,this.instanceId=e.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[HT({broadcast:(f,d,m)=>{this.broadcastEvents.send(f,d,m)},emit:(f,d,m)=>this.emit(f,d,m),handleAfterSendMessage:f=>this.handleAfterSendMessage(f),handleInputChanged:f=>this.handleInputChanged(f),handleKeyDown:f=>this.handleKeyDown(f),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:f=>this.logSendMessage(f),onUpdateShowTabHint:f=>JT.update(f),sendEvent:(f,d)=>this.deepdeskApi.sendEvent(f,d)})]};n&&Object.assign(c,{deepdeskBrokerAPI:new gl(n)}),this.store=FT(c),this.broadcastEvents=new TT({debug:!0,deepdeskUrl:u,eventMap:M1(this.store),createCustomChannel:l}),this.store.dispatch(Za(JT.value())),this.store.dispatch(Nc({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?(z.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(z.warn("Profile has not been loaded (yet)"),!0):(z.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(ji(null)),this.store.dispatch(zn()),new Promise(t=>{let n=this.store.subscribe(()=>{let r=this.store.getState();tt(r)&&Wx(r)!=="loading"&&(n(),t())});this.unmountHandlers.push(()=>{n()})})}async isLoggedIn(){return(await this.store.dispatch(zn())).payload}async setPlatformAgentId(t){try{if((await this.deepdeskApi.client.get("/apis/admin/session/me/",{version:null})).external_id)return;await this.deepdeskApi.client.request("/apis/admin/session/me/",{method:"PATCH",body:JSON.stringify({external_id:t}),version:null})}catch(n){z.warn("Failed to attach user:",n)}}async isConversationSupported(t,n){return(await this.store.dispatch(Ng({sessionId:t,options:n}))).payload}async createConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(Fc(t))).payload}async getConversationBySessionId(t,n){return this.hasConversation()&&this.sessionId()!==t&&this.resetConversation(),(await this.store.dispatch(Hc({sessionId:t,options:n}))).payload}async upsertConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(Mg(t))).payload}async postMessages(t){return(await this.store.dispatch(Bc(t))).payload}async updateConversation(t){return(await this.store.dispatch(Uc(t))).payload}resetConversation(){this.store.dispatch(le()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}async getSummary(){let t=await this.store.dispatch(Gn());if(t.error)throw new Error(t.error.message);return t.payload.summary}configure(t){this.store.dispatch(Nc(t))}setVisitorInfo(t){this.store.dispatch(T1(t))}async setAgentInfo(t){await this.store.dispatch(Pa(t))}async setAgentSettings(t){await this.store.dispatch(Fg(t))}async getAgentSettings(){return(await this.store.dispatch(Hg())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let t=[];return this.store.dispatch(Pd()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})}notifyInputChanged(t){this.store.dispatch(Kc(t))}notifyKeyDown(t){this.store.dispatch(Vc(t))}notifyPaste(t,n){this.store.dispatch(v1({text:t,selectionText:n}))}notifyCut(t){this.store.dispatch(h1(t))}notifyExternalSuggestion(t){this.store.dispatch(Cn(t)),this.store.dispatch(Kn())}async evaluateRule(t,n={}){let{payload:r,error:o}=await this.store.dispatch(Bo({label:t,params:n}));if(o)throw new Error(o.message);return r}handleInputChanged(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui;n&&r&&this.store.dispatch(zr({collapse:!1})),this.inputMediator&&this.store.dispatch(d1({text:t,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(En([])))}handleKeyDown(t){let{overlayCollapsed:n}=this.state.ui,{textSuggestions:r,selectedSuggestionIndex:o,selection:i}=this.state.input,{inlineSuggestions:s}=this.state.settings,a=r.length>0,l=o!==-1;if(this.store.dispatch(y1(l1(t))),t.key!=="Tab"&&!this.settings.showTextSuggestions)return;let u=()=>{n||!a||i&&(t.shiftKey||(this.store.dispatch(p1()),s||this.stageSelectedSuggestion({inputType:"arrow"}),t.preventDefault()))},c=()=>{n||!a||s&&o<=0||i&&(t.shiftKey||(this.store.dispatch(g1()),t.preventDefault(),!s&&(this.state.input.selectedSuggestionIndex===-1?this.store.dispatch(ka()):this.stageSelectedSuggestion({inputType:"arrow"}))))};switch(t.key){case"Up":case"ArrowUp":s?c():u();return;case"Down":case"ArrowDown":{s?u():c();return}case"Esc":case"Escape":{s&&l&&this.store.dispatch(_r(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(_r(-1)),this.store.dispatch(ka()),t.preventDefault()):n||(this.store.dispatch(zr({collapse:!0})),this.store.dispatch(SC(!0)),t.preventDefault());return}case"Tab":{let{userCommitted:f}=this.state.input,d=f.text.substring(0,f.selection.end),{tabCompletionSuggestion:m}=this.state.input;this.store.dispatch(Za(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):!s&&this.settings.showTabCompletion&&m&&m.text.startsWith(d)&&(this.store.dispatch(Cn({text:m.text,suggestion:m,eventMetrics:{inputType:"tab"},replace:"until-selection-end"})),this.store.dispatch(Kn())),t.preventDefault();break}default:}}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(S1()),this.store.dispatch(En([]))}handlingTimeStart(){this.state.handlingTime.startTime||(z.info("Start handling time"),this.store.dispatch(RT()))}handlingTimeStop(){this.state.handlingTime.startTime&&(z.info("Stop handling time"),this.store.dispatch(cf()))}logSendMessage(t){let n=BT("input",this.state,{version:this.version});t&&(Object.assign(n,{text:t}),Object.assign(n,{lenTextTotal:t.length})),this.deepdeskApi.sendEventV1("Send Message",n),this.emit("send-message-event",n)}logHandlingTime(){let t=UT(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",t),this.store.dispatch(AT())}notifySubmit(t={}){this.shouldAbort()||(this.store.dispatch(Kn()),this.store.dispatch(Eo(t.text??this.state.input.text)))}stageSelectedSuggestion(t){let n=this.state.input.selectedSuggestionIndex,{textSuggestions:r}=this.state.input;this.store.dispatch(Cn({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){z.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),z.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]=hl(n,r);return i.setAttribute("translate","no"),i.dataset.testid=t,o&&i.classList.add(o),this.unmountHandlers.push(()=>{(0,qt.unmountComponentAtNode)(i),s(),i.remove()}),i}createInlineContainer(t,n){var s;let r=document.createElement("div");r.style.position="absolute",r.style.top="0px",r.style.left="0px",r.style.height="0px",r.style.width="0px";let o=document.createElement("div");o.style.display="none",o.style.position="absolute",o.style.height="0px",o.style.width="0px",o.style.backgroundColor="red",r.appendChild(o);let i=(s=t.ownerDocument.defaultView)==null?void 0:s.frameElement;if(i){let[a,l]=hl(i,{appendTo:document.body,onMoveStart:()=>{o.style.display="none"}});a.dataset.testid=n,a.style.zIndex="2",a.appendChild(r),this.unmountHandlers.push(()=>{(0,qt.unmountComponentAtNode)(o),l()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return Fo(o),o.dataset.testid=t,o.style.color=r.color,o.style.fontSize=r.fontSize,o.style.fontFamily=r.fontFamily,o.style.fontVariant=r.fontVariant,o.setAttribute("translate","no"),n.appendChild(o),this.unmountHandlers.push(()=>{(0,qt.unmountComponentAtNode)(o),o.remove()}),o}storeMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(t,n),z.info(`Stored analytics for ${this.conversationId()}`)}catch{}}restoreMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=window.sessionStorage.getItem(t);if(!n)return;let r=JSON.parse(n);r.text.trim()===this.state.input.text.trim()?(z.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(x1(r.metrics))):z.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(t)}catch{}}mount(t,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!ff(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:m,inputMediator:y,closestScrollSelector:v,appendOverlayTo:p,inlineSuggestions:g,floatingMenu:h}=n;this.configure({showStyleSuggestions:o,showTabCompletion:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,showTextSuggestions:s,insertLink:m,isEmbedded:f,inlineSuggestions:g,floatingMenu:!!h}),n.automaticHandlingTime&&this.setupHandlingTime(t),Fo(t),this.inputMediator=y||(Kr(t)?new Vo(t):new zo(t)),this.inputMediator.on("change",({plainText:T})=>{this.notifyInputChanged(T)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(w1({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()}))}),this.inputMediator.on("keydown",T=>{this.notifyKeyDown(T)}),this.inputMediator.on("paste",({pastedText:T,selectionText:C})=>{this.notifyPaste(T,C)}),this.inputMediator.on("cut",({selectionText:T})=>{this.notifyCut(T)});let S=v&&jT(t,v)||void 0;if(g){let{customStyles:T,appendOverlayTo:C}=n;if(Kr(t))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let k=this.createInlineContainer(t,"deepdesk-caret");(0,qt.render)((0,Ie.jsx)(Uo,{store:this.store,customStyles:T,children:(0,Ie.jsx)(bo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(PC,{})})}),k),this.inputMediator.on("caret",I=>{this.store.dispatch(En([])),I?(k.style.display="block",k.style.top=`${I.top}px`,k.style.left=`${I.left}px`):k.style.display="none"});let L=this.overlayContainerFactory("floating-menu",S||t,{appendTo:typeof h=="object"&&"appendOverlayTo"in h?h.appendOverlayTo:C},T==null?void 0:T.floatingMenuRootNode);(0,qt.render)((0,Ie.jsx)(Uo,{store:this.store,customStyles:T,children:(0,Ie.jsx)(bo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(hC,{onLogIn:()=>this.loginViaPopup().catch(I=>z.warn(I.message))})})}),L)}else{let T=this.overlayContainerFactory("deepdesk-tab-completion",S||t,{appendTo:p,closestScrollElement:S,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),C=this.overlayContainerFactory("deepdesk-suggestions-overlay",S||t,{appendTo:p},r==null?void 0:r.suggestionsRootNode);(0,qt.render)((0,Ie.jsx)(Uo,{store:this.store,customStyles:r,children:(0,Ie.jsx)(bo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(nb,{inputElement:t})})}),T),(0,qt.render)((0,Ie.jsx)(Uo,{store:this.store,customStyles:r,children:(0,Ie.jsx)(bo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(DC,{onLogIn:()=>this.loginViaPopup().catch(k=>z.warn(k.message))})})}),C)}(0,qt.render)((0,Ie.jsx)(Uo,{store:this.store,customStyles:r,children:(0,Ie.jsx)(bo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(dC,{})})}),this.createContainer("deepdesk-overlays"));let x;this.inputMediator.on("selection",T=>{clearTimeout(x),T===null?x=setTimeout(()=>{T!==null&&this.store.dispatch(_g(T))},500):this.store.dispatch(_g(T))}),this.inputMediator.on("disabled",()=>{var T;(T=this.inputMediator)==null||T.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{d&&this.notifySubmit()}),this.inputMediator.on("blur",()=>this.store.dispatch(Eh(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(Eh(!0))),this.store.dispatch(f1({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.unmountHandlers.push(()=>{this.state.input.text!==""&&(this.store.dispatch(Kn()),this.storeMetrics())}),this.whenConversationLoaded(()=>{var T;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((T=this.state.conversation.current)==null?void 0:T.sessionId)}),this.isMounted=!0}unmount(){var t;this.unmountHandlers.forEach(n=>n()),this.unmountHandlers=[],(t=this.inputMediator)==null||t.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(t,n={}){if(this.widgetRoot&&z.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,isEmbedded:i}=n;this.widgetRoot=t,this.configure({showImages:o,isEmbedded:i}),(0,qt.render)((0,Ie.jsx)(Uo,{store:this.store,customStyles:r,children:(0,Ie.jsx)(bo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(wT,{onLogIn:()=>this.loginViaPopup().catch(s=>z.warn(s.message))})})}),t),this.whenConversationLoaded(()=>{var s;this.broadcastEvents.setSessionId((s=this.state.conversation.current)==null?void 0:s.sessionId)})}unmountWidget(){this.widgetRoot&&(0,qt.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(t){let n=gf(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){zT(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(Ya());let t=jr(this.state);t&&(await this.store.dispatch(qa()),this.store.dispatch(Nc({showSearch:t.search,showAutoflows:t.autoflows,showCustomMessages:t.customMessages,showImageSearch:t.imageSearch,showEntitiesCommand:t.entitiesCommand,showSummaryCommand:t.summarizer,showKnowledgeSearch:!!t.knowledgeAssistant,recommendTextSuggestions:t.recommendTextSuggestions})))}),this.loadProfileConfigPromise)}async loginViaPopup(t){return new Promise((n,r)=>{let o=new MessageChannel,i=o.port1,s=this.state.settings.adminUrl,a=new URL(t!=null&&t.url?t==null?void 0:t.url:`${s}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let l=!1,u=()=>{c&&!c.closed&&c.close(),window.removeEventListener("message",f),clearInterval(d)};i.onmessage=async m=>{var y,v;if((y=m.data)!=null&&y.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((v=m.data)==null?void 0:v.jwt),await this.isLoggedIn(),this.broadcastEvents.send(Aa),l=!0,o.port1.close(),n()}catch(p){console.error(p),r(p)}finally{l=!0,u()}};let c=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");c===null&&r(new Error("Popup blocked by browser"));let f=async m=>{var y;if(m.origin===a.origin)switch((y=m.data)==null?void 0:y.type){case"deepdesk-popup-loaded":{try{let v=JSON.stringify({type:"deepdesk-popup-create-channel"});c==null||c.postMessage(v,a.origin,[o.port2])}catch(v){z.error("Error posting message to popup",v),r(v)}break}case"deepdesk-popup-error":{u(),m.data.message==="Timeout"&&z.warn("Popup timed out. Check if the account's platform url is configured correctly."),r(new Error(m.data.message));break}}};window.addEventListener("message",f);let d=setInterval(()=>{c&&!c.closed||(u(),l||r(new Error("Popup closed by user")))},200);this.unmountHandlers.push(u)})}translateMessages(t){return this.deepdeskApi.translateMessages(t)}async checkForTrialMode(t){try{let{account:n}=await this.deepdeskApi.getPlatformConfig();if(!n.isTrial){this.shouldRender=!0;return}if(z.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;z.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=Td(this.state);try{n.forEach(({type:r})=>{r==="entities"?this.store.dispatch(an()):this.store.dispatch(un(r))})}catch(r){this.handleError(r)}}};async function ek(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 tk(e,t,n={}){let r=n.replace?Gr(e,n.replace.start,n.replace.end):as(e),o,i=()=>{if(n.setRange)return n.setRange(r.cloneRange());r.deleteContents(),o=document.createElement("span"),r.insertNode(o),n.insertBRs!==!1?t.split(`
|
|
27
|
+
`);break}default:break}f&&s++}return l(e),a}var ET=(s=>(s.CUT="Cut",s.BACKSPACE="Backspace",s.DELETE="Delete",s.ERASEEOF="EraseEof",s.UNDO="Undo",s.CLEAR="Clear",s))(ET||{}),rr=class{constructor(t){this.element=t;this.currentText=this.getText(),this.currentHTML=this.getHTML(),this.listen()}eventListeners={};disposeHandlers=[];currentText="";currentCaret=null;currentSelection={start:0,end:0};currentHTML="";isFocused=!1;isActive=!0;isSettingValue=!1;isSubmitting=!1;isPossibleClearInputAction=!1;isDisposed=!1;addEventListener(t,n){let r=o=>{n(o)};this.element.addEventListener(t,r),this.disposeHandlers.push(()=>{this.element.removeEventListener(t,r)})}removeEventListener(t,n){this.element.removeEventListener(t,n)}triggerChange(){let t=this.getText(),n=this.getHTML(),r=t!==this.currentText;this.isActive&&(t===""&&this.currentText!==""&&!this.isSettingValue&&!this.isPossibleClearInputAction&&(this.isSubmitting=!0,this.emit("submit")),!this.isSettingValue&&r&&!this.isSubmitting&&this.emit("change",{plainText:t}),r&&(this.currentSelection=this.getSelection()),this.currentText=t,this.isSubmitting=!1,(this.currentHTML!==n||n===null&&r)&&(this.emit("updated",{plainText:t}),this.triggerCaretPosition(),this.currentHTML=n))}triggerSelection(){let t=this.getSelection();(t.start!==this.currentSelection.start||t.end!==this.currentSelection.end)&&(this.currentSelection=t,this.emit("selection",t),this.triggerCaretPosition())}triggerCaretPosition(){let t=this.getCaretPosition();Nr(t,this.currentCaret)||(this.currentCaret=t,this.emit("caret",t))}handleKeyUp(t){let{key:n,shiftKey:r}=t;(n==="Enter"&&r===!0||n==="Backspace")&&this.triggerChange(),this.triggerSelection()}handleClick(){this.triggerSelection()}handleFocus(){this.isFocused||this.emit("focus"),this.triggerSelection(),this.isFocused=!0}handleBlur(){this.isPossibleClearInputAction=!1,this.isFocused&&this.emit("blur"),this.isFocused=!1}handleKeyDown(t){let{key:n,ctrlKey:r,metaKey:o}=t;this.isPossibleClearInputAction=Object.values(ET).includes(n)||n.toLowerCase()==="z"&&(r||o),this.emit("keydown",t)}handleCut(){this.isPossibleClearInputAction=!0,this.emit("cut",{selectionText:this.getSelectedText()})}handlePaste(t){var r,o;let n=((r=t.clipboardData)==null?void 0:r.getData("text"))||((o=t.clipboardData)==null?void 0:o.getData("text/plain"))||"";this.emit("paste",{pastedText:n,selectionText:this.getSelectedText()})}listen(t={shouldObserve:!0}){this.addEventListener("keydown",r=>this.handleKeyDown(r)),this.addEventListener("keyup",r=>this.handleKeyUp(r)),this.addEventListener("input",()=>this.triggerChange()),this.addEventListener("change",()=>this.triggerChange()),this.addEventListener("focus",()=>this.handleFocus()),this.addEventListener("blur",()=>this.handleBlur()),this.addEventListener("cut",()=>this.handleCut()),this.addEventListener("paste",r=>this.handlePaste(r)),this.addEventListener("click",()=>this.triggerSelection()),document.activeElement===this.element&&setTimeout(()=>{this.handleFocus()},0);let n=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});t!=null&&t.shouldObserve&&n.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{n.disconnect()}),this.currentSelection=this.getSelection()}focus(){this.element.focus()}emit(t,...n){this.isDisposed||this.eventListeners[t]&&this.eventListeners[t].forEach(r=>{r(...n)})}on(t,n){this.isDisposed||(this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n))}activate(){let t=this.isActive===!1;this.isActive=!0,t&&this.triggerChange()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(t=>t()),this.eventListeners={},this.isDisposed=!0}};function CT(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var zo=class extends rr{observer;lastKnownSelection=null;getRootNode(){return this.element.getRootNode()}getText(){let t=new Range;return t.selectNodeContents(this.element),pl(this.element,t)}getHTML(){return this.element.innerHTML||""}getRange(){var i;let t=this.getRootNode();if(t.activeElement!==this.element)return null;let n="getSelection"in t?t.getSelection():window.getSelection();if(!n)return null;let r="getComposedRanges"in n&&t instanceof ShadowRoot?(i=n.getComposedRanges(t))==null?void 0:i[0]:n.rangeCount>0?n.getRangeAt(0):null;if(!r)return null;let o=this.element.ownerDocument.createRange();return o.setStart(r==null?void 0:r.startContainer,r==null?void 0:r.startOffset),o.setEnd(r==null?void 0:r.endContainer,r==null?void 0:r.endOffset),!o||!this.element.contains(o.startContainer)||!this.element.contains(o.endContainer)?null:o}getCaretPosition(){let t=this.getRange();if(!t||!t.collapsed||!("getBoundingClientRect"in t))return null;let n=t.getBoundingClientRect();return!CT(n)&&(t.insertNode(this.element.ownerDocument.createTextNode("\u2060")),n=t.getBoundingClientRect(),t.deleteContents(),!CT(n))?null:{top:n.top+n.height,left:n.left}}getSelection(){let t=this.getRange();if(t)return fl(this.element,t);let n=this.lastKnownSelection;if(n&&xT(this.element,n.start,n.end))return n;let r=as(this.element);return r.collapse(!1),fl(this.element,r)}getSelectedText(){let{start:t,end:n}=this.getSelection();return pl(this.element,Gr(this.element,t,n))}applyChanges(t){var o;if(!this.isActive)return;this.isSettingValue=!0;let n=this.getText(),r=t(this.element);return(o=this.observer)==null||o.takeRecords(),Promise.resolve(r).then(()=>{this.currentText=this.getText(),n!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(t={shouldObserve:!0}){super.listen(t),this.observer=new MutationObserver(()=>{setTimeout(()=>{this.triggerChange()},0)}),t!=null&&t.shouldObserve&&this.observer.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0});let n=this.element.isContentEditable,r=new MutationObserver(()=>{this.element.isContentEditable!==n&&(n=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});r.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>r.disconnect())}dispose(){super.dispose(),this.observer&&this.observer.disconnect()}};var Vo=class extends rr{lastKnownSelection=null;getText(){return this.element.value}getHTML(){return null}getSelection(){let{selectionStart:t,selectionEnd:n}=this.element;return{start:t,end:n}}getSelectedText(){let t=this.getSelection();return t?this.getText().slice(t.start,t.end):""}getCaretPosition(){return null}applyChanges(t){if(!this.isActive)return;this.isSettingValue=!0;let n=this.getText(),r=t(this.element);return Promise.resolve(r).then(()=>{this.currentText=this.getText(),n!==this.currentText&&this.triggerChange(),this.isSettingValue=!1})}listen(){super.listen();let t=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var o;return(o=t==null?void 0:t.get)==null?void 0:o.call(this.element)},set:o=>{var i;(i=t==null?void 0:t.set)==null||i.call(this.element,o),this.triggerChange()}});let n=this.element.disabled,r=new MutationObserver(()=>{this.element.disabled!==n&&(n=this.element.disabled,this.emit(n?"disabled":"enabled"))});r.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>r.disconnect())}};function bT(e,t,n){let r=`deepdesk-iframe-${e}`,o=document.getElementById(r);if(o)return o;let i=document.createElement("iframe"),s=new URL(t);return Object.entries(n).forEach(([a,l])=>{s.searchParams.append(a,l)}),i.style.position="absolute",i.style.left="-999em",i.style.width="0px",i.style.height="0px",i.tabIndex=-1,i.id=r,i.title=`iframe-${e}`,i.src=s.toString(),window.document.body.appendChild(i),i}function WM(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}var uy=class{constructor(t){this.name=t;this.broadcastChannel=new BroadcastChannel(t)}broadcastChannel;disposeHandlers=[];onMessage(t){this.broadcastChannel.addEventListener("message",t),this.disposeHandlers.push(()=>{this.broadcastChannel.removeEventListener("message",t)})}postMessage(t){this.broadcastChannel.postMessage(JSON.stringify(t))}close(){this.disposeHandlers.forEach(t=>t()),this.broadcastChannel.close()}},cy=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.iframe=bT(t,`${this.targetOrigin}/sdk/proxy/proxy.html`,{channel:this.name,host:window.location.origin,debug:"1"}),document.body.appendChild(this.iframe)}iframe;disposeHandlers=[];onMessage(t){window.addEventListener("message",t),this.disposeHandlers.push(()=>{window.removeEventListener("message",t)})}postMessage(t){var n;(n=this.iframe.contentWindow)==null||n.postMessage(JSON.stringify(t),this.targetOrigin)}close(){var t;this.disposeHandlers.forEach(n=>n()),(t=this.iframe)==null||t.remove()}},dy=class{constructor(t){this.params=t;this.deepdeskUrl=t.deepdeskUrl,this.eventMap=t.eventMap,this.sessionId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}sessionId;deepdeskUrl;channel;defaultChannel;eventMap;get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setSessionId(t){this.sessionId!==t&&(this.cleanup(),z.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 cy(t,this.deepdeskUrl,{debug:!0}):new uy(t),r=o=>{var s,a;if(o.origin!==this.deepdeskUrl)return;let i=WM(o.data);typeof i!="object"||i.type!=="event"||i.channel!==t||(z.info("Received broadcast event",this.sessionId,o),(a=(s=this.eventMap)[i.name])==null||a.call(s,i.payload))};return n.onMessage(r),n}send(t,n,r){var s,a;z.info("Broadcast event",{sessionId:this.sessionId,name:t,payload:n});let o={type:"event",name:t,payload:n};r!==!1&&((a=(s=this.eventMap)[t])==null||a.call(s,n));let i=this.sessionId==="deepdesk-general"?this.defaultChannel:this.channel;i==null||i.postMessage({...o,channel:this.sessionId})}cleanup(t=!1){var n,r;(n=this.channel)==null||n.close(),delete this.channel,t&&((r=this.defaultChannel)==null||r.close(),delete this.defaultChannel)}},TT=dy;var ls=class extends Error{constructor(n,r){super(n);this.body=r}name="CustomError"};var fy=e=>new Promise(t=>{setTimeout(t,e)});var us=class extends ls{name="ClientError"},my=class extends ls{name="ServerError"},py=new Map,pn=class e{constructor(t="",n={}){this.baseUrl=t;this.options=n;n.fetch&&(this.fetch=n.fetch)}latestRequestByUrl={};csrfToken;fetch=window.fetch.bind(window);static refreshingToken=null;patchFetch(t){this.fetch=t(this.fetch)}setCsrfToken(t){this.csrfToken=t}request(t,n={}){return new Promise((r,o)=>{let i={isAborted:!1,reject:o},s=`${this.baseUrl}${t}`,a=this.fetch,l=n.method===void 0||n.method.toLowerCase()==="get",{useCache:u=!1,abortLatest:c=!1,attempts:f=1,retryDelay:d=500,refreshTokenOn401:m=!0,retryOnError:y=C=>C instanceof TypeError,retryOnResponse:v=C=>C.status>=500,version:p="v1",...g}=n;if(u)if(l){if(py.has(s)){r(py.get(s));return}}else throw new Error(`Can't use 'useCache' for ${n.method}`);let h={credentials:"include",...g,headers:{"Content-Type":"application/json",...g.headers}};!l&&this.csrfToken&&(h.headers={...h.headers,"X-CSRFToken":this.csrfToken}),typeof p=="string"&&(h.headers={...h.headers,"X-Deepdesk-API-Version":p});let S=f,x=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[s]&&c&&(this.latestRequestByUrl[s].isAborted=!0,this.latestRequestByUrl[s].reject(new Error("Aborted"))),this.latestRequestByUrl[s]=i;let T=async()=>(S--,a(s,h).then(async C=>v(C)&&!i.isAborted&&S>0?(await fy(d),T()):C.status===401&&m===!0&&x===!1?(x=!0,await this.refreshToken(),T()):C).catch(async C=>{if(y(C)&&!i.isAborted&&S>0)return await fy(d),T();throw C}));T().then(C=>C.json().catch(()=>null).then(k=>{C.status>=500?o(new my("Server Error",k)):C.status===401?o(new us("Unauthorized",k)):C.status===403?o(new us("Forbidden",k)):C.status===404?o(new us("Not Found",k)):C.status>=400&&o(new us("Bad Request",k)),delete this.latestRequestByUrl[s],u&&py.set(s,k),r(k)})).catch(C=>{o(C)})})}async validateToken(){let{has_valid_access_token:t}=await this.get("/auth/validate");if(!t)return!1;let{is_logged_in:n}=await this.get("/apis/admin/session/validate/",{version:null});return!!n}refreshToken(){return e.refreshingToken||(e.refreshingToken=this.get("/auth/refresh",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{e.refreshingToken=null},1e3*60)})),e.refreshingToken}get(t,n){return this.request(t,n)}post(t,n,r){return this.request(t,{method:"POST",body:JSON.stringify(n),...r})}patch(t,n,r){return this.request(t,{method:"PATCH",body:JSON.stringify(n),...r})}put(t,n,r){return this.request(t,{method:"PUT",body:JSON.stringify(n),...r})}delete(t,n){return this.request(t,{method:"DELETE",...n})}};var qM;(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||={})})(qM||={});function uf(e){return{...J(e),tags:e.tags}}var or=class e{constructor(t,n={}){this.options=n;this.client=new pn(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(),z.info(`Creating conversation for session ${t.sessionId} and agent ${t.agentId}`);let n=await this.client.post("/api/conversations",{...Ae(t),tags:t.tags},{version:"v2"});return uf(n)}async getProfile(t){let n=await this.client.get(`/apis/admin/profiles/${t}/`,{version:null,useCache:!0});return J(n)}async getKnowledgeAssistant(t){let n=await this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{version:null,useCache:!0});return J(n)}async getContentTypes(){let t=await this.client.get("/apis/admin/content-types/",{version:null,useCache:!0});return J(t)}async getAccount(){let t=await this.client.get("/apis/admin/account/",{version:null,useCache:!0});return J(t)}async getPlatformConfig(){let{config:t}=await this.client.get("/platform/config/",{version:null,useCache:!0});return J(t)}async checkUserExists(t){let{exists:n}=await this.client.get(`/apis/admin/users/exists?external_id=${t}`);return n}async getConversationBySessionId(t,n={}){await this.preflight(),z.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 z.info(`Successfully retrieved conversation ${i.id} for session ${t}`),uf(i)}async isConversationSupported(t,n={}){z.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=Ae(n);n.tags&&(r.tags=n.tags);let o=await this.client.put(`/api/conversations/${t}`,r,{version:"v2"});return uf(o)}async postMessages(t,n){return(await this.client.post(`/api/conversations/${t}/messages`,n.map(o=>({...Ae(o),tags:o.tags})),{version:"v2"})).map(o=>uf(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",Ae({...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:Ae({...n,...r})})}async getEntities(t){return(await this.client.post("/api/entities",{messages:t.filter(r=>r.text)})).entities}async getSummary(t,n={}){let r=await this.client.post("/api/summary",{conversation:{messages:t.filter(o=>o.text&&o.source),agent_id:n.agentId,id:n.externalConversationId},prompt_instruction:n.promptInstruction,model:n.model});return J(r)}async getTemporaryExchangeToken(){return(await this.client.get("/auth/exchange-token",{version:null})).jwt}async exchangeTokenForAccessCookie(t){return this.client.post("/apis/admin/session/jwt/",{jwt:t},{version:null}).catch(n=>{throw z.warn(`Invalid token '${t}'`),n})}async authenticateWithKey(t,n){await this.preflight(),await this.client.post("/apis/admin/session/api-key/",Ae(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}`,Ae(n),{abortLatest:!0})).map(i=>({...J(i),text:i.text||i.url||i.message,source:r,type:r})).filter((i,s,a)=>s===a.findIndex(l=>l.text===i.text))}async isLoggedIn(){return await this.preflight(),this.client.validateToken()}async getAutocompleteSuggestions(t,n){return(await this.client.post(`/api/conversations/${t}/autocomplete`,Ae(n),{abortLatest:!0})).map(o=>({score:1,source:o.source,sourceText:o.source_text,text:o.label,trainingJobs:o.training_jobs,searchKeywords:o.search_keywords,type:o.source})).filter((o,i,s)=>i===s.findIndex(a=>a.text===o.text))}async getPinnedMessages(t){let n=await this.client.get(`/api/conversations/${t}/sticky-messages`,{abortLatest:!0});return J(n).map(r=>({...r,text:r.message,source:"sticky-messages",type:"pinned-message"}))}async getStyleSuggestions(t){let n=await this.client.post("/api/style-suggestions",Ae(t),{abortLatest:!0});return J(n)}async search(t){let n=await this.client.post(`/api/profiles/${t.profile}/search`,Ae(t),{version:"v2"});return J(n)}async knowledgeAssist(t,n,r,o={}){let i=await this.client.post(`/api/knowledge-assist/assistants/${r}/search`,Ae({question:t.question,promptInstruction:t.promptInstruction,chatHistory:n.map(s=>({question:s.question,answer:s.answer.answer})),agentId:o.agentId,conversationId:o.conversationId}),{version:"v2"});return J(i)}async requestLoginByEmail(t){let n=await this.client.post("/apis/admin/session/passwordless/request/",{email:t},{version:null});return J(n)}async requestPasswordlessToken(){let t=await this.client.get("/apis/admin/session/passwordless/request/",{version:null});return J(t.token)}async getCsrfToken(){let{token:t}=await this.client.get("/apis/admin/session/csrf/",{version:null});return t}async verifyLoginToken(t){let n=await this.client.post("/apis/admin/session/passwordless/login/",{token:t},{version:null});return J(n)}async evaluateRule(t,n,r,o={}){let i=new URLSearchParams;o.raiseForFailingConditions&&i.set("raise_for_failing_conditions","true");let s=await this.client.post(`/api/conversations/${n}/rules/${t}/evaluate?${i.toString()}`,r,{version:"v2"});return J(s.cues)}async getRules(){let t=new URLSearchParams,n=await this.client.get(`/apis/admin/rule-engine/rules/?${t.toString()}`,{version:null,useCache:!0});return J(n)}async translateMessages(t){let n=await this.client.post("/api/translate",Ae(t),{version:"v2"});return J(n)}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),i=o.match(Ov);if(!n||!i)return;let s=i[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[s];a&&n&&a!==n&&z.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[s]=n})}};var ml=class{constructor(t,n){this.url=t;this.options={timeout:25e3,...n}}eventListeners={};options;timeoutTimer;eventSource;proxyEvent(t){this.eventSource.addEventListener(Dg(t),n=>{let{data:r}=n;try{let o=JSON.parse(r);this.emit(t,J(o))}catch{z.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 GM;(t=>{let e;(i=>(i.Started="Started",i.Aborted="Aborted",i.Completed="Completed"))(e=t.AutoflowSessionState||={})})(GM||={});var gl=class{constructor(t,n={}){this.apiUrl=t;this.client=new pn(t,n)}client;streams={};logger=z;async getCustomMessages(t){let n=await this.client.get(`/sessions/${t}/suggestions`);return J(n.suggestions)}async sendCustomMessage(t,n){let r=await this.client.post(`/sessions/${t}/messages`,Ae(n));return J(r)}async answerCustomMessage(t,n){await this.client.post(`/sessions/${t}/answers`,Ae(n))}async getAutoflows(t){let n=await this.client.get(`/sessions/${t}/autoflows`);return J(n.autoflows)}async startAutoflowSession(t){let n=await this.client.post("/autoflow-sessions",Ae(t));return J(n)}async stopAutoflowSession(t){await this.client.delete(`/autoflow-sessions/${t}`)}openStream(t){return this.streams[t]||(this.streams[t]=new ml(`${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 kT={startTime:null,stopTime:null},PT=W({name:"handlingTime",initialState:kT,reducers:{handlingTimeStart(e){if(e.startTime&&!e.stopTime)throw new Error("Timing already started");e.startTime=new Date,e.stopTime=null},handlingTimeStop(e){if(!e.startTime)throw new Error("Timing not started");e.stopTime=new Date},handlingTimeReset(e){e.startTime=null,e.stopTime=null}},extraReducers:e=>{e.addCase(le,()=>kT)}}),{handlingTimeStart:RT,handlingTimeStop:cf,handlingTimeReset:AT}=PT.actions,LT=PT.reducer;var IT=(e={})=>{let t={onAuthError:ji(!1),...e};return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var df={list:{keywordMatches:[]},fetchState:"idle",isInitialRequest:null};var Ko=B("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 df.list;if(!i)throw new Error("No current conversation to fetch pinned messages");return n.getStyleSuggestions({profileCode:i,message:e})}),YM=W({name:"styleSuggestions",initialState:df,reducers:{},extraReducers:e=>{e.addCase(Ko.pending,t=>{t.isInitialRequest=t.isInitialRequest===null,t.fetchState="loading"}).addCase(Ko.rejected,t=>{t.fetchState="error"}).addCase(Ko.fulfilled,(t,n)=>{t.fetchState="done",Nr(t.list,n.payload)||(t.list=n.payload)}).addCase(Eo,t=>{t.list=df.list}).addCase(le,()=>df)}}),OT=YM.reducer;var NT=(e={})=>{let t,n=!0,r={getStyleSuggestions:Ko,debounce:500,...e};return o=>i=>s=>{var m;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(!((m=u.conversation.current)==null?void 0:m.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 XM(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end}var MT=(e={})=>{let t={getTextSuggestions:un,getAutocompleteSuggestions:Xa,debounce:200,check:Ji,...e},n;return r=>o=>i=>{var v;let{input:{userCommitted:s}}=r.getState(),a=o(i),l=r.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:u,showTabCompletion:c}=l.settings,f=(v=l.conversation.current)==null?void 0:v.id,d=i.type===Pd.toString();if(!f||!u&&!c)return a;let{input:{userCommitted:m}}=l;return XM(m,s)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let p=Vi(l);p===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(p))},d?0:t.debounce)),a}};var _T=Ko.fulfilled.toString();function QM(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 DT=e=>t=>n=>r=>{var u;if(r.type!==_T){n(r);return}let o=t.getState().styleSuggestions.list;n(r);let i=t.getState(),s=i.styleSuggestions.list,a=(u=i.conversation)==null?void 0:u.current;if(o===s)return;let l=QM(o,s);r.type===_T&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var ZM=oc({answer:WE,auth:Zx,autoflows:lb,conversation:a1,contentTypes:oE,customMessages:yb,passwordlessToken:xb,entities:IE,knowledgeAssistant:VE,handlingTime:LT,info:k1,input:E1,settings:$x,profile:YE,search:N1,summary:HE,styleSuggestions:OT,ui:xC,rules:Tb,textSuggestions:oC});function FT(e){return Qw({reducer:ZM,middleware:t=>[...t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI,deepdeskBrokerAPI:e.deepdeskBrokerAPI}},serializableCheck:!1}),IT(),MT({debounce:200}),NT({debounce:500}),DT(e.deepdeskAPI),...e.middleware?e.middleware:[]],preloadedState:e.preloadedState})}var JM=e=>{var t;return((t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())??"unknown"},e2=e=>t=>n=>r=>{var a;let o=t.getState(),i=Ag("inlineSuggestions")(o);switch(r.type){case ji.toString():{!r.payload&&e.emit("logout",void 0);break}case an.fulfilled.toString():r.payload.length>0&&e.sendEvent("entities found",{conversationId:o.conversation.current.id,data:{entities:r.payload}});break;case Ye.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 Vc.toString():e.handleKeyDown(r.payload);break;case Eo.toString():e.logSendMessage(r.payload);break;case Kc.toString():e.handleInputChanged(r.payload);break;case Bo.fulfilled.toString():r.isBroadcasted||e.broadcast(Ug,r,!1),e.emit("cues",r.payload);break;default:break}let s=n(r);switch(r.type){case Eo.toString():e.handleAfterSendMessage(r.payload);break;case Za.toString():e.onUpdateShowTabHint(r.payload);break;case cf.toString():e.logHandlingTime();break;case Cn.toString():{let{start:l,end:u}=o.input.selection;e.emit("select-suggestion",{type:JM(r.payload.suggestion),...r.payload,replace:r.payload.replace==="selection"?{start:l,end:u}:{start:0,end:u}},{mayApplyChanges:!0}),i&&(t.dispatch(En([])),t.dispatch(Kn()));break}case zc.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 ka.toString():{let l=t.getState(),{text:u,selection:c}=l.input.userCommitted;e.emit("reset",{text:u,selectionAfter:c},{mayApplyChanges:!0});break}case $c.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 En.toString():{i&&r.payload.length>0&&t.dispatch(_r(0));break}case Gn.fulfilled.toString():{e.sendEvent("conversation summarized",{conversationId:o.conversation.current.id,data:{summary:r.payload.summary,model:t.getState().summary.model}});break}default:break}return s},HT=e2;function gy(e){return e.toISOString().replace("T"," ").replace("Z","")}function UT(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:gy(n),timeStop:gy(r)}}function BT(e,t,n){var k,L,I;let{text:r,metrics:{numCharsTyped:o,numCharsPasted:i,numCharsCut:s,numCharsDeleted:a,numPaste:l,agentStartedTypingTimestamp:u,externalTimeTotalSeconds:c,pastes:f,cuts:d,deletions:m,textSuggestions:y,offeredTextSuggestions:v}}=t[e],p=r.length,h=y.reduce((N,{text:V,searchTerm:_})=>N+V.length-(_?_.length:0),0),S=u??Date.now(),x=(Date.now()-S)/1e3+(c||0),T=o/x,C=y.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:m,lenTextTyped:o+C,lenTextTotal:p,lenTextAssisted:h,lenTextPasted:i,lenTextCut:s,lenTextDeleted:a,timeTotalSeconds:x,charsPerSecond:T,numPastes:l,textSuggestionsV2:y,suggestionsCounters:[{source:"gpt",countOffered:v.filter(N=>N.source==="gpt").length}],agentId:(k=t.info.agentInfo)==null?void 0:k.agentId,agentName:(L=t.info.agentInfo)==null?void 0:L.agentName,agentEmail:(I=t.info.agentInfo)==null?void 0:I.agentEmail}}function hy(e,t){var i;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return hy(r,t);let o=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;return o?hy(o,t):null}function jT(e,t){return hy(e,t)}function zT(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function t2(e){return typeof e=="object"&&e!==null&&"tagName"in e}function ff(e){return t2(e)&&(Kr(e)||_d(e))}var VT,kn=new Map,n2=["bottom","height","left","right","top","width"],r2=(e={},t={})=>n2.some(n=>e[n]!==t[n]);function KT(e){var n,r;if(e.ownerDocument===document)return[];let t=((r=(n=e.ownerDocument)==null?void 0:n.defaultView)==null?void 0:r.frameElement)??null;return t?[t,...KT(t)]:[]}function $T(e,t){return!e||!t?null:{...e,top:e.top+t.top,left:e.left+t.left}}var pf=!1,WT=()=>{pf=!0;let e=[];if(kn.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),kn.delete(n);return}let r=n.getBoundingClientRect();r2(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{let n=t.parentRects?t.parentRects.reduce($T,t.rect):t.rect;t.callbacks.forEach(r=>r(n))}),kn.size===0){pf=!1;return}VT=window.requestAnimationFrame(WT)};function yy(e,t){let n=KT(e),r=[],o=n.map((i,s)=>yy(i,a=>{r[s]=a;let l=kn.get(e);if(!l)return;let u=r.reduce($T,l.rect);l.callbacks.forEach(c=>c(u))}));return{observe(i=!0){if(o.forEach(s=>s.observe(!1)),kn.has(e)){let s=kn.get(e);s.callbacks.push(t),s.rect&&t(s.rect)}else kn.set(e,{rect:void 0,callbacks:[t],parentRects:r});i&&!pf&&WT()},unobserve(){o.forEach(s=>s.unobserve());let i=kn.get(e);if(i){let s=i.callbacks.indexOf(t);s>=0&&i.callbacks.splice(s,1),i.callbacks.length||kn.delete(e),kn.size||(cancelAnimationFrame(VT),pf=!1)}}}}var qT,Pn=new Map,GT=()=>{Pn.forEach((e,t)=>{if(!t.isConnected){Pn.delete(t);return}let{clientHeight:n,scrollHeight:r}=t,o=r>n;e.visible!==o&&(e.visible=o,e.callbacks.forEach(i=>i(e.visible)))}),Pn.size!==0&&(qT=window.requestAnimationFrame(GT))};function YT(e,t){return{observe(){let n=Pn.size===0;Pn.has(e)?Pn.get(e).callbacks.push(t):Pn.set(e,{visible:void 0,callbacks:[t]}),n&>()},unobserve(){let n=Pn.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||Pn.delete(e),Pn.size||cancelAnimationFrame(qT)}}}}var vy=["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 Sy(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function cs(e){return parseFloat(e)}function mf(e){return Math.round(e*1e6)}function XT(e){return e/1e6}function wy(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=cs(e.width),i=cs(e.borderLeftWidth),s=cs(e.borderRightWidth),a=cs(e.paddingRight),l=XT(mf(o)-mf(i)-mf(s)),u=XT(mf(r));if(l-u>2){let c=l-u;n.style.paddingRight=`${a+c}px`}}function hl(e,t={}){var c;let n=t.overlayContainer||document.createElement("div");n.style.display="none",n.style.position=t.position??"fixed",n.style.pointerEvents="none",n.style.borderColor="transparent",Fo(n);let r=window.getComputedStyle(e),o=!0,i=()=>{n.scrollTop=e.scrollTop};Sy(r,n,vy),wy(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",i));let s=YT(e,()=>{Sy(r,n,vy),wy(r,e,n),i(),setTimeout(i,0)}),a,l=!0,u=yy(e,f=>{if(f===null){t.onRemove&&t.onRemove(),n.remove();return}if(!l&&t.onMoveStart&&(Promise.resolve().then(()=>t.onMoveStart()),l=!0),clearTimeout(a),a=setTimeout(()=>{t.onMoveEnd&&t.onMoveEnd(),l=!1},200),f.height===0&&f.width===0){if(o===!0)return;t.onHide&&t.onHide(),n.style.display="none",o=!0;return}if(Sy(r,n,vy),wy(r,e,n),i(),n.style.top=`${f.top}px`,n.style.left=`${f.left}px`,t.closestScrollElement&&t.closestScrollElement!==e){let d=t.closestScrollElement.getBoundingClientRect(),m=window.getComputedStyle(t.closestScrollElement),y=cs(m.borderTopWidth),v=cs(m.borderBottomWidth),p=d.top+y-f.top,g=f.top+f.height+-(d.top+d.height-v);n.style.clipPath=`inset(${p}px 0px ${g}px 0px)`}o&&(n.style.display="block",t.onShow&&t.onShow(),o=!1)});return t.appendTo?t.appendTo.appendChild(n):(c=e.parentElement)==null||c.appendChild(n),u.observe(),s.observe(),[n,()=>{e.removeEventListener("scroll",i),u.unobserve(),s.unobserve()}]}var QT=(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{z.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function o2(e){return e.offsetParent!==null}function ZT(e){if(!o2(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 gf(e,t,n=100){let r=ZT(e);t({isVisible:r});let o=setInterval(()=>{let i=ZT(e);i!==r&&(r=i,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var Ie=w(b());var JT=QT("showTabHint",!0),yl=class e{static version="11.2.1-beta.3";static count=0;deepdeskApi;inputMediator=null;version;broadcastEvents;eventListeners={};unmountHandlers=[];widgetRoot=null;dynamicThunkObject={};isMounted=!1;instanceId;shouldRender=!0;store;constructor({deepdeskUrl:t,brokerUrl:n,version:r=e.version||"unknown",locale:o="en-US",token:i,fetch:s,productName:a,createCustomChannel:l}){let u=t.replace(/\/api$/,"");this.deepdeskApi=new or(u,{token:i,fetch:s}),this.version=r,this.instanceId=e.count++;let c={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[HT({broadcast:(f,d,m)=>{this.broadcastEvents.send(f,d,m)},emit:(f,d,m)=>this.emit(f,d,m),handleAfterSendMessage:f=>this.handleAfterSendMessage(f),handleInputChanged:f=>this.handleInputChanged(f),handleKeyDown:f=>this.handleKeyDown(f),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:f=>this.logSendMessage(f),onUpdateShowTabHint:f=>JT.update(f),sendEvent:(f,d)=>this.deepdeskApi.sendEvent(f,d)})]};n&&Object.assign(c,{deepdeskBrokerAPI:new gl(n)}),this.store=FT(c),this.broadcastEvents=new TT({debug:!0,deepdeskUrl:u,eventMap:M1(this.store),createCustomChannel:l}),this.store.dispatch(Za(JT.value())),this.store.dispatch(Nc({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?(z.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(z.warn("Profile has not been loaded (yet)"),!0):(z.warn("No conversation loaded (yet)"),!0)}login(){return this.store.dispatch(ji(null)),this.store.dispatch(zn()),new Promise(t=>{let n=this.store.subscribe(()=>{let r=this.store.getState();tt(r)&&Wx(r)!=="loading"&&(n(),t())});this.unmountHandlers.push(()=>{n()})})}async isLoggedIn(){return(await this.store.dispatch(zn())).payload}async setPlatformAgentId(t){try{if((await this.deepdeskApi.client.get("/apis/admin/session/me/",{version:null})).external_id)return;await this.deepdeskApi.client.request("/apis/admin/session/me/",{method:"PATCH",body:JSON.stringify({external_id:t}),version:null})}catch(n){z.warn("Failed to attach user:",n)}}async isConversationSupported(t,n){return(await this.store.dispatch(Ng({sessionId:t,options:n}))).payload}async createConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(Fc(t))).payload}async getConversationBySessionId(t,n){return this.hasConversation()&&this.sessionId()!==t&&this.resetConversation(),(await this.store.dispatch(Hc({sessionId:t,options:n}))).payload}async upsertConversation(t){return this.hasConversation()&&this.sessionId()!==t.sessionId&&this.resetConversation(),(await this.store.dispatch(Mg(t))).payload}async postMessages(t){return(await this.store.dispatch(Bc(t))).payload}async updateConversation(t){return(await this.store.dispatch(Uc(t))).payload}resetConversation(){this.store.dispatch(le()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}async getSummary(){let t=await this.store.dispatch(Gn());if(t.error)throw new Error(t.error.message);return t.payload.summary}configure(t){this.store.dispatch(Nc(t))}setVisitorInfo(t){this.store.dispatch(T1(t))}async setAgentInfo(t){await this.store.dispatch(Pa(t))}async setAgentSettings(t){await this.store.dispatch(Fg(t))}async getAgentSettings(){return(await this.store.dispatch(Hg())).payload}async refresh(){if(this.shouldAbort())return Promise.resolve();this.inputMediator&&this.handleInputChanged(this.inputMediator.getText());let t=[];return this.store.dispatch(Pd()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})}notifyInputChanged(t){this.store.dispatch(Kc(t))}notifyKeyDown(t){this.store.dispatch(Vc(t))}notifyPaste(t,n){this.store.dispatch(v1({text:t,selectionText:n}))}notifyCut(t){this.store.dispatch(h1(t))}notifyExternalSuggestion(t){this.store.dispatch(Cn(t)),this.store.dispatch(Kn())}async evaluateRule(t,n={}){let{payload:r,error:o}=await this.store.dispatch(Bo({label:t,params:n}));if(o)throw new Error(o.message);return r}handleInputChanged(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui;n&&r&&this.store.dispatch(zr({collapse:!1})),this.inputMediator&&this.store.dispatch(d1({text:t,html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),!this.shouldAbort()&&(this.isMounted||this.store.dispatch(En([])))}handleKeyDown(t){let{overlayCollapsed:n}=this.state.ui,{textSuggestions:r,selectedSuggestionIndex:o,selection:i}=this.state.input,{inlineSuggestions:s}=this.state.settings,a=r.length>0,l=o!==-1;if(this.store.dispatch(y1(l1(t))),t.key!=="Tab"&&!this.settings.showTextSuggestions)return;let u=()=>{n||!a||i&&(t.shiftKey||(this.store.dispatch(p1()),s||this.stageSelectedSuggestion({inputType:"arrow"}),t.preventDefault()))},c=()=>{n||!a||s&&o<=0||i&&(t.shiftKey||(this.store.dispatch(g1()),t.preventDefault(),!s&&(this.state.input.selectedSuggestionIndex===-1?this.store.dispatch(ka()):this.stageSelectedSuggestion({inputType:"arrow"}))))};switch(t.key){case"Up":case"ArrowUp":s?c():u();return;case"Down":case"ArrowDown":{s?u():c();return}case"Esc":case"Escape":{s&&l&&this.store.dispatch(_r(-1)),this.state.input.selectedSuggestionIndex!==-1?(this.store.dispatch(_r(-1)),this.store.dispatch(ka()),t.preventDefault()):n||(this.store.dispatch(zr({collapse:!0})),this.store.dispatch(SC(!0)),t.preventDefault());return}case"Tab":{let{userCommitted:f}=this.state.input,d=f.text.substring(0,f.selection.end),{tabCompletionSuggestion:m}=this.state.input;this.store.dispatch(Za(!1)),this.state.input.selectedSuggestionIndex>-1?this.stageSelectedSuggestion({inputType:"tab"}):!s&&this.settings.showTabCompletion&&m&&m.text.startsWith(d)&&(this.store.dispatch(Cn({text:m.text,suggestion:m,eventMetrics:{inputType:"tab"},replace:"until-selection-end"})),this.store.dispatch(Kn())),t.preventDefault();break}default:}}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(S1()),this.store.dispatch(En([]))}handlingTimeStart(){this.state.handlingTime.startTime||(z.info("Start handling time"),this.store.dispatch(RT()))}handlingTimeStop(){this.state.handlingTime.startTime&&(z.info("Stop handling time"),this.store.dispatch(cf()))}logSendMessage(t){let n=BT("input",this.state,{version:this.version});t&&(Object.assign(n,{text:t}),Object.assign(n,{lenTextTotal:t.length})),this.deepdeskApi.sendEventV1("Send Message",n),this.emit("send-message-event",n)}logHandlingTime(){let t=UT(this.state,{version:this.version});this.deepdeskApi.sendEventV1("Handling Time",t),this.store.dispatch(AT())}notifySubmit(t={}){this.shouldAbort()||(this.store.dispatch(Kn()),this.store.dispatch(Eo(t.text??this.state.input.text)))}stageSelectedSuggestion(t){let n=this.state.input.selectedSuggestionIndex,{textSuggestions:r}=this.state.input;this.store.dispatch(Cn({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){z.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),z.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]=hl(n,r);return i.setAttribute("translate","no"),i.dataset.testid=t,o&&i.classList.add(o),this.unmountHandlers.push(()=>{(0,qt.unmountComponentAtNode)(i),s(),i.remove()}),i}createInlineContainer(t,n){var s;let r=document.createElement("div");r.style.position="absolute",r.style.top="0px",r.style.left="0px",r.style.height="0px",r.style.width="0px";let o=document.createElement("div");o.style.display="none",o.style.position="absolute",o.style.height="0px",o.style.width="0px",o.style.backgroundColor="red",r.appendChild(o);let i=(s=t.ownerDocument.defaultView)==null?void 0:s.frameElement;if(i){let[a,l]=hl(i,{appendTo:document.body,onMoveStart:()=>{o.style.display="none"}});a.dataset.testid=n,a.style.zIndex="2",a.appendChild(r),this.unmountHandlers.push(()=>{(0,qt.unmountComponentAtNode)(o),l()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return Fo(o),o.dataset.testid=t,o.style.color=r.color,o.style.fontSize=r.fontSize,o.style.fontFamily=r.fontFamily,o.style.fontVariant=r.fontVariant,o.setAttribute("translate","no"),n.appendChild(o),this.unmountHandlers.push(()=>{(0,qt.unmountComponentAtNode)(o),o.remove()}),o}storeMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(t,n),z.info(`Stored analytics for ${this.conversationId()}`)}catch{}}restoreMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=window.sessionStorage.getItem(t);if(!n)return;let r=JSON.parse(n);r.text.trim()===this.state.input.text.trim()?(z.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(x1(r.metrics))):z.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(t)}catch{}}mount(t,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!ff(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:m,inputMediator:y,closestScrollSelector:v,appendOverlayTo:p,inlineSuggestions:g,floatingMenu:h}=n;this.configure({showStyleSuggestions:o,showTabCompletion:i,textSuggestionsCount:a,showMidSentenceSuggestions:l,showSuggestionsBeforePattern:u,showSuggestionsAfterPattern:c,showTextSuggestions:s,insertLink:m,isEmbedded:f,inlineSuggestions:g,floatingMenu:!!h}),n.automaticHandlingTime&&this.setupHandlingTime(t),Fo(t),this.inputMediator=y||(Kr(t)?new Vo(t):new zo(t)),this.inputMediator.on("change",({plainText:T})=>{this.notifyInputChanged(T)}),this.inputMediator.on("updated",()=>{this.inputMediator&&this.store.dispatch(w1({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()}))}),this.inputMediator.on("keydown",T=>{this.notifyKeyDown(T)}),this.inputMediator.on("paste",({pastedText:T,selectionText:C})=>{this.notifyPaste(T,C)}),this.inputMediator.on("cut",({selectionText:T})=>{this.notifyCut(T)});let S=v&&jT(t,v)||void 0;if(g){let{customStyles:T,appendOverlayTo:C}=n;if(Kr(t))throw new Error("[Deepdesk] Inline suggestion is not supported for textarea yet.");let k=this.createInlineContainer(t,"deepdesk-caret");(0,qt.render)((0,Ie.jsx)(Uo,{store:this.store,customStyles:T,children:(0,Ie.jsx)(bo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(PC,{})})}),k),this.inputMediator.on("caret",I=>{this.store.dispatch(En([])),I?(k.style.display="block",k.style.top=`${I.top}px`,k.style.left=`${I.left}px`):k.style.display="none"});let L=this.overlayContainerFactory("floating-menu",S||t,{appendTo:typeof h=="object"&&"appendOverlayTo"in h?h.appendOverlayTo:C},T==null?void 0:T.floatingMenuRootNode);(0,qt.render)((0,Ie.jsx)(Uo,{store:this.store,customStyles:T,children:(0,Ie.jsx)(bo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(hC,{onLogIn:()=>this.loginViaPopup().catch(I=>z.warn(I.message))})})}),L)}else{let T=this.overlayContainerFactory("deepdesk-tab-completion",S||t,{appendTo:p,closestScrollElement:S,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),C=this.overlayContainerFactory("deepdesk-suggestions-overlay",S||t,{appendTo:p},r==null?void 0:r.suggestionsRootNode);(0,qt.render)((0,Ie.jsx)(Uo,{store:this.store,customStyles:r,children:(0,Ie.jsx)(bo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(nb,{inputElement:t})})}),T),(0,qt.render)((0,Ie.jsx)(Uo,{store:this.store,customStyles:r,children:(0,Ie.jsx)(bo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(DC,{onLogIn:()=>this.loginViaPopup().catch(k=>z.warn(k.message))})})}),C)}(0,qt.render)((0,Ie.jsx)(Uo,{store:this.store,customStyles:r,children:(0,Ie.jsx)(bo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(dC,{})})}),this.createContainer("deepdesk-overlays"));let x;this.inputMediator.on("selection",T=>{clearTimeout(x),T===null?x=setTimeout(()=>{T!==null&&this.store.dispatch(_g(T))},500):this.store.dispatch(_g(T))}),this.inputMediator.on("disabled",()=>{var T;(T=this.inputMediator)==null||T.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{d&&this.notifySubmit()}),this.inputMediator.on("blur",()=>this.store.dispatch(Eh(!1))),this.inputMediator.on("focus",()=>this.store.dispatch(Eh(!0))),this.store.dispatch(f1({text:this.inputMediator.getText(),html:this.inputMediator.getHTML(),selection:this.inputMediator.getSelection()})),this.unmountHandlers.push(()=>{this.state.input.text!==""&&(this.store.dispatch(Kn()),this.storeMetrics())}),this.whenConversationLoaded(()=>{var T;this.restoreMetrics(),this.refresh(),this.broadcastEvents.setSessionId((T=this.state.conversation.current)==null?void 0:T.sessionId)}),this.isMounted=!0}unmount(){var t;this.unmountHandlers.forEach(n=>n()),this.unmountHandlers=[],(t=this.inputMediator)==null||t.dispose(),this.broadcastEvents.cleanup(),this.isMounted=!1}renderWidget(t,n={}){if(this.widgetRoot&&z.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,isEmbedded:i}=n;this.widgetRoot=t,this.configure({showImages:o,isEmbedded:i}),(0,qt.render)((0,Ie.jsx)(Uo,{store:this.store,customStyles:r,children:(0,Ie.jsx)(bo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(wT,{onLogIn:()=>this.loginViaPopup().catch(s=>z.warn(s.message))})})}),t),this.whenConversationLoaded(()=>{var s;this.broadcastEvents.setSessionId((s=this.state.conversation.current)==null?void 0:s.sessionId)})}unmountWidget(){this.widgetRoot&&(0,qt.unmountComponentAtNode)(this.widgetRoot),this.widgetRoot=null}setupHandlingTime(t){let n=gf(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){zT(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfigPromise=null;loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(async()=>{await this.store.dispatch(Ya());let t=jr(this.state);t&&(await this.store.dispatch(qa()),this.store.dispatch(Nc({showSearch:t.search,showAutoflows:t.autoflows,showCustomMessages:t.customMessages,showImageSearch:t.imageSearch,showEntitiesCommand:t.entitiesCommand,showSummaryCommand:t.summarizer,showKnowledgeSearch:!!t.knowledgeAssistant,recommendTextSuggestions:t.recommendTextSuggestions})))}),this.loadProfileConfigPromise)}async loginViaPopup(t){return new Promise((n,r)=>{let o=new MessageChannel,i=o.port1,s=this.state.settings.adminUrl,a=new URL(t!=null&&t.url?t==null?void 0:t.url:`${s}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let l=!1,u=()=>{c&&!c.closed&&c.close(),window.removeEventListener("message",f),clearInterval(d)};i.onmessage=async m=>{var y,v;if((y=m.data)!=null&&y.jwt)try{await this.deepdeskApi.exchangeTokenForAccessCookie((v=m.data)==null?void 0:v.jwt),await this.isLoggedIn(),this.broadcastEvents.send(Aa),l=!0,o.port1.close(),n()}catch(p){console.error(p),r(p)}finally{l=!0,u()}};let c=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");c===null&&r(new Error("Popup blocked by browser"));let f=async m=>{var y;if(m.origin===a.origin)switch((y=m.data)==null?void 0:y.type){case"deepdesk-popup-loaded":{try{let v=JSON.stringify({type:"deepdesk-popup-create-channel"});c==null||c.postMessage(v,a.origin,[o.port2])}catch(v){z.error("Error posting message to popup",v),r(v)}break}case"deepdesk-popup-error":{u(),m.data.message==="Timeout"&&z.warn("Popup timed out. Check if the account's platform url is configured correctly."),r(new Error(m.data.message));break}}};window.addEventListener("message",f);let d=setInterval(()=>{c&&!c.closed||(u(),l||r(new Error("Popup closed by user")))},200);this.unmountHandlers.push(u)})}translateMessages(t){return this.deepdeskApi.translateMessages(t)}async checkForTrialMode(t){try{let{account:n}=await this.deepdeskApi.getPlatformConfig();if(!n.isTrial){this.shouldRender=!0;return}if(z.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;z.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=Td(this.state);try{n.forEach(({type:r})=>{r==="entities"?this.store.dispatch(an()):this.store.dispatch(un(r))})}catch(r){this.handleError(r)}}};async function ek(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 tk(e,t,n={}){let r=n.replace?Gr(e,n.replace.start,n.replace.end):as(e),o,i=()=>{if(n.setRange)return n.setRange(r.cloneRange());r.deleteContents(),o=document.createElement("span"),r.insertNode(o),n.insertBRs!==!1?t.split(`
|
|
28
28
|
`).reverse().forEach((s,a)=>{a>0&&r.insertNode(document.createElement("br")),r.insertNode(document.createTextNode(s))}):r.insertNode(document.createTextNode(t))};return Promise.resolve(i()).then(()=>{try{if(n.selectionAfter!==!1){e.focus();let s=n.selectionAfter?Gr(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 i2(e){let t=document.createElement("template");return t.innerHTML=e.replace(/(\[([^\]]+)])\(([^)]+)\)/g,'<a href="$3" target="_blank" rel="noopener noreferrer">$2</a>'),t.content}function s2(e){let t=document.createDocumentFragment();return e.split(`
|
|
29
29
|
`).forEach((n,r)=>{r>0&&t.appendChild(document.createElement("br"));let o={index:0},i=0;for(;o=n.slice(i).match(/(\[([^\]]+)])\(([^)]+)\)/);){let s=document.createElement("a");s.href=o[3],s.setAttribute("target","_blank"),s.setAttribute("rel","noopener noreferrer"),s.appendChild(document.createTextNode(o[2])),t.appendChild(document.createTextNode(n.slice(i,i+o.index))),t.appendChild(s),i=i+o.index+o[0].length}t.appendChild(document.createTextNode(n.slice(i)))}),t}function nk(e,t){return!e.contains(t)||t===e?null:t.parentNode===e?t:nk(e,t.parentNode)}async function rk(e,t,{isBlock:n,isHTML:r}={}){let o;e.dispatchEvent(new InputEvent("beforeinput",{inputType:"insertText",data:t,bubbles:!0,cancelable:!0}));let i=()=>{let s=e.ownerDocument.defaultView??window,a=s.getSelection();if((!a||a.rangeCount===0)&&(e.focus(),a=s.getSelection()),!a||a.rangeCount===0)return;let l=a.getRangeAt(0);if(!l)return;o=document.createElement("span"),l.insertNode(o);let u=r?i2(t):s2(t);if(n){let c=l.startContainer===e?e.childNodes[l.startOffset]:l.startContainer,f=nk(e,c)??e.firstChild;e.insertBefore(u,(f==null?void 0:f.nextSibling)??null)}else l.insertNode(u),l.collapse(!1)};return Promise.resolve(i()).then(()=>{if(e.dispatchEvent(new InputEvent("input",{inputType:"insertText",data:t,bubbles:!0,cancelable:!0})),e.focus(),!!o)try{o.scrollIntoView&&o.scrollIntoView({block:"nearest",inline:"nearest"})}finally{o&&o.remove()}})}function ok(e){return e.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}async function ik(e,t,n){await new or(e).authenticateWithKey(t,n)}async function sk(e){let n=await new pn(e).get("/platform/config/",{version:null,useCache:!0});return J(n)}async function a2(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 ak(e,t){let n=await a2(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 Ek(l2);})();
|
|
30
30
|
/*! Bundled license information:
|