@deepdesk/deepdesk-sdk 18.1.2-beta.8 → 18.1.2-beta.9

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.
@@ -79,7 +79,7 @@ Please report this to https://github.com/markedjs/marked.`,t){let o="<p>An error
79
79
  `+Jt),X&&em([Q,Z,N],vr=>{Jt=tu(Jt,vr," ")}),S&&Qe?S.createHTML(Jt):Jt},t.setConfig=function(){let ne=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};bm(ne),$e=!0},t.clearConfig=function(){hi=null,$e=!1},t.isValidAttribute=function(ne,T,U){hi||bm({});let J=ut(ne),Be=ut(T);return nx(J,Be,U)},t.addHook=function(ne,T){typeof T=="function"&&eu(L[ne],T)},t.removeHook=function(ne,T){if(T!==void 0){let U=Q4(L[ne],T);return U===-1?void 0:Z4(L[ne],U,1)[0]}return RP(L[ne])},t.removeHooks=function(ne){L[ne]=[]},t.removeAllHooks=function(){L=NP()},t}var BP=HP();var yo=b(Y());var UP={root:"dd-L7b3z",popover:"dd-OQOTB",options:"dd-Y12RE",arrow:"dd-cv33T",copyIcon:"dd-6xOsH",option:"dd-9oFX4",divider:"dd-aiZf8",fadeup:"dd-Jq9pd"};var mr=b(R());function gF(e){return`<button type="button" data-copy-icon class=${e}><svg version="1.1" x="0px" y="0px" viewBox="0 0 115.77 122.88" width="10px" height="10px" fill="black"><g><path d="M89.62,13.96v7.73h12.19h0.01v0.02c3.85,0.01,7.34,1.57,9.86,4.1c2.5,2.51,4.06,5.98,4.07,9.82h0.02v0.02 v73.27v0.01h-0.02c-0.01,3.84-1.57,7.33-4.1,9.86c-2.51,2.5-5.98,4.06-9.82,4.07v0.02h-0.02h-61.7H40.1v-0.02 c-3.84-0.01-7.34-1.57-9.86-4.1c-2.5-2.51-4.06-5.98-4.07-9.82h-0.02v-0.02V92.51H13.96h-0.01v-0.02c-3.84-0.01-7.34-1.57-9.86-4.1 c-2.5-2.51-4.06-5.98-4.07-9.82H0v-0.02V13.96v-0.01h0.02c0.01-3.85,1.58-7.34,4.1-9.86c2.51-2.5,5.98-4.06,9.82-4.07V0h0.02h61.7 h0.01v0.02c3.85,0.01,7.34,1.57,9.86,4.1c2.5,2.51,4.06,5.98,4.07,9.82h0.02V13.96L89.62,13.96z M79.04,21.69v-7.73v-0.02h0.02 c0-0.91-0.39-1.75-1.01-2.37c-0.61-0.61-1.46-1-2.37-1v0.02h-0.01h-61.7h-0.02v-0.02c-0.91,0-1.75,0.39-2.37,1.01 c-0.61,0.61-1,1.46-1,2.37h0.02v0.01v64.59v0.02h-0.02c0,0.91,0.39,1.75,1.01,2.37c0.61,0.61,1.46,1,2.37,1v-0.02h0.01h12.19V35.65 v-0.01h0.02c0.01-3.85,1.58-7.34,4.1-9.86c2.51-2.5,5.98-4.06,9.82-4.07v-0.02h0.02H79.04L79.04,21.69z M105.18,108.92V35.65v-0.02 h0.02c0-0.91-0.39-1.75-1.01-2.37c-0.61-0.61-1.46-1-2.37-1v0.02h-0.01h-61.7h-0.02v-0.02c-0.91,0-1.75,0.39-2.37,1.01 c-0.61,0.61-1,1.46-1,2.37h0.02v0.01v73.27v0.02h-0.02c0,0.91,0.39,1.75,1.01,2.37c0.61,0.61,1.46,1,2.37,1v-0.02h0.01h61.7h0.02 v0.02c0.91,0,1.75-0.39,2.37-1.01c0.61-0.61,1-1.46,1-2.37h-0.02V108.92L105.18,108.92z"/></g></svg></button>`}function C0(e){var n,r;let t=e.cloneNode(!0);return t.querySelectorAll("div,button").forEach(o=>o.remove()),(r=(n=t.textContent)==null?void 0:n.trim())!=null?r:""}function hF(e){return e.replace(/\r\n/g,`
80
80
  `)}var yF=({content:e,useLabel:t,copyLabel:n,onCopy:r,onUse:o})=>{let s=D("Markdown",UP),i=(0,yo.useRef)(null),[a,l]=(0,yo.useState)(null),c=(0,yo.useMemo)(()=>{let m=Ce.parse(hF(e));return BP.sanitize(m.toString()).replaceAll("</code>",`${gF(s.copyIcon)}</code>`).replaceAll('<a href="','<a target="_blank" rel="noreferrer noopener" href="')},[e]),u=m=>{var y;let x=m.target,v=!!((y=i.current)!=null&&y.querySelector("code"));if(["A","BUTTON"].includes(x.tagName)){l(null);return}a||v&&x.tagName!=="CODE"||!v&&x!==i.current||(x.addEventListener("mouseleave",()=>l(null),{once:!0}),l(x))},f=()=>{if(!a)return;l(null);let m=a.querySelector("button");m&&(Ma(m,s.fadeup),r==null||r(C0(a)))},d=m=>{let x=m.target;if(x.tagName==="A"){m.stopPropagation();return}"copyIcon"in x.dataset&&(Ma(x,s.fadeup),r==null||r(C0(x.parentElement)))},p=()=>{!a||!o||(l(null),o(C0(a)))},g=m=>{if(m===null)return;let x=m.getBoundingClientRect();x.left<0?m.style.transform=`translateX(${-x.left+2}px)`:x.right>window.innerWidth&&(m.style.transform=`translateX(${window.innerWidth-x.right-2}px)`)};return(0,mr.jsxs)(yo.Fragment,{children:[a&&(r||o)&&(0,mr.jsxs)(Pa,{triggerRef:{current:a},className:s.popover,parentNode:a,children:[(0,mr.jsxs)("div",{className:s.options,ref:g,children:[r&&(0,mr.jsx)("button",{type:"button",className:s.option,onClick:f,children:n}),o&&(0,mr.jsxs)(yo.Fragment,{children:[(0,mr.jsx)("div",{className:s.divider}),(0,mr.jsx)("button",{type:"button",className:s.option,onClick:p,children:t})]})]}),(0,mr.jsx)("div",{className:s.arrow})]}),(0,mr.jsx)("div",{ref:i,"data-testid":"widget-markdown-content",className:s.root,dangerouslySetInnerHTML:{__html:c},onMouseOver:u,onClick:d})]})},ai=yF;var k0={title:"dd-YBHrC",fadeup:"dd-cRM0K",fadedown:"dd-7D4Pq",selected:"dd-bueui",actions:"dd-9Iqn9",thumbsUp:"dd-6QwVx",thumbsDown:"dd-d3E8l",form:"dd-sPNU2",formInput:"dd-F3E4I",formSubmit:"dd-vw5S0",actionButton:"dd-cCWyJ",editableCue:"dd-nWSD-",inputSpace:"dd-DGYB1"};var Ot=b(R()),vF=500,xF=100,SF=({content:e,onChange:t,onCopy:n})=>{let r=(0,li.useRef)(null),o=D("WidgetCue",k0);return(0,li.useEffect)(()=>{let s=r.current;if(!s)return;s.style.setProperty("height","0px");let i=Math.min(Math.max(s.scrollHeight,xF),vF);s.style.setProperty("height",`${i}px`)},[e]),(0,Ot.jsx)("textarea",{ref:r,className:o.editableCue,onCopy:n,onChange:t,value:e})},wF=({cue:e,onCallToAction:t,onRemove:n,onCopy:r,onUse:o})=>{var m;let s=D("WidgetCue",k0),i=ae(Zc),a=Ct(),l=te("hasKeyboardInput"),[c,u]=(0,li.useState)(e.text),f=()=>{t&&t(c,e),n(e)},d=x=>{r&&r(x,e)},p=x=>{o&&o(x,e)},g=x=>{x.preventDefault(),x.stopPropagation(),n(e)};return(0,li.useEffect)(()=>{a("Assistant response displayed",{evaluationId:e.evaluationId,name:e.rule.name,description:e.rule.description,group:e.rule.label,cueText:e.text})},[]),(0,Ot.jsxs)(de,{"data-testid":"cue",children:[(0,Ot.jsx)(ve,{children:(0,Ot.jsxs)(ve.Content,{children:[e.title&&(0,Ot.jsx)(ve.Title,{className:s.title,"data-testid":"widget-cue-title",children:e.rule.label.startsWith("__")?i(e.rule.label):e.title}),e.specialType==="summary"||e.editable?(0,Ot.jsx)(SF,{content:c,onCopy:()=>{let x=document.getSelection();x&&d(x.toString())},onChange:x=>{var v;return u((v=x.target.value)!=null?v:"")}}):(0,Ot.jsx)(ai,{content:e.text,useLabel:i("useCue"),copyLabel:i("copyCue"),onCopy:d,onUse:l?p:void 0})]})}),(0,Ot.jsxs)(de.ButtonsContainer,{children:[(0,Ot.jsxs)("div",{className:s.actions,children:[(e.specialType==="summary"||e.editable)&&(0,Ot.jsx)(de.Button,{onClick:()=>d(c),children:i("copyCue")}),e.callToAction&&(0,Ot.jsx)(de.Button,{onClick:f,children:e.callToAction.label}),(0,Ot.jsx)(de.Button,{onClick:g,children:i("removeCue")})]}),e.specialType==="summary"?(0,Ot.jsx)(Jc,{eventName:"summary feedback",evaluationId:e.evaluationId,feedbackText:(m=e.text)!=null?m:"",feedbackType:"summary",eventData:{summary:e.text}}):(0,Ot.jsx)(Jc,{eventName:"Assistant response feedback",evaluationId:e.evaluationId,eventData:{name:e.rule.name,group:e.rule.label,description:e.rule.description,cueText:e.text},feedbackText:e.text,feedbackType:"assistant"})]})]})},VP=wF;var Oa=b(R()),bF=({cues:e})=>{let t=ge(),n=cn(),r=ae(Zc),o=Ct(),s=c=>{t(Yp({code:c.rule.label})),o("Assistant response closed",{evaluationId:c.evaluationId,name:c.rule.name,group:c.rule.label,description:c.rule.description,cueText:c.text})},i=(c,u)=>{switch(Rr(c),u.specialType){case"summary":o("summary copied to clipboard",{originalText:u.text,finalText:c,assistant:u.rule.label});break;default:o("Assistant response copied",{evaluationId:u.evaluationId,name:u.rule.name,group:u.rule.label,description:u.rule.description,copiedText:c,originalText:u.text})}},a=(c,u)=>{var f;u.callToAction&&(t(qp(u)),o("Assistant call to action",{evaluationId:u.evaluationId,name:u.rule.name,group:u.rule.label,description:u.rule.description,eventName:u.callToAction.event,value:(f=u.callToAction.value)!=null?f:c,originalText:u.text}))},l=(c,u)=>{var f;n.send(to,{text:c,suggestion:{source:"assistant",assistantCode:(f=u.rule)==null?void 0:f.label,sourceText:c}}),o("Assistant response used",{evaluationId:u.evaluationId,name:u.rule.name,group:u.rule.label,description:u.rule.description,usedText:c,originalText:u.text})};return(0,Oa.jsx)(Oa.Fragment,{children:e.map(c=>c.isLoading?(0,Oa.jsx)(Zp,{title:c.rule.label.startsWith("__")?r(c.rule.label):c.title},c.rule.id):(0,Oa.jsx)(VP,{cue:c,onCallToAction:a,onRemove:s,onCopy:i,onUse:l},c.evaluationId))})},$P=bF;var rm=b(Y());var jP={root:"dd-cvTAY",label:"dd-QWQxD",value:"dd-WSUHF",copyButton:"dd-67o9H",copyButtonText:"dd-oos-l",isTrue:"dd--1g2O",isFalse:"dd-sz2ir"};var gr=b(R());function EF(e,t){return t.split(".").reduce((n,r)=>!n||typeof n!="object"||!(r in n)?null:n[r],e)}var WP=({data:e,schema:t})=>{let n=D("WidgetCustomData",jP),r=o=>{Rr(o)};return(0,rm.useEffect)(()=>{ee.info("Custom data",e,t)},[e]),(0,gr.jsx)("dl",{className:n.root,children:t.map(o=>{let s=EF(e,o.path);return(0,gr.jsxs)(rm.Fragment,{children:[(0,gr.jsx)("dt",{className:n.label,children:o.label}),(0,gr.jsx)("dd",{className:n.value,children:o.type==="boolean"&&s?(0,gr.jsx)("span",{className:n.isTrue,children:o.trueValue}):o.type==="boolean"&&!s?(0,gr.jsx)("span",{className:n.isFalse,children:o.falseValue}):typeof s=="string"||typeof s=="number"?(0,gr.jsxs)("button",{type:"button",onClick:()=>r(`${s}`),className:n.copyButton,children:[(0,gr.jsx)("span",{className:n.copyButtonText,children:s}),(0,gr.jsx)(Yc,{})]}):"-"})]},o.label)})})};var Je=b(Y());var Na={};xt(Na,{enUS:()=>TF,nlNL:()=>CF});var TF={inputPlaceholder:[{type:0,value:"What is your question?"}],useCue:[{type:0,value:"Add to message"}],copyCue:[{type:0,value:"Copy"}],removeCue:[{type:0,value:"Close"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}],submitLabel:[{type:0,value:"Submit"}],resetLabel:[{type:0,value:"Reset"}],showMore:[{type:0,value:"Show "},{type:1,value:"amount"},{type:0,value:" more"}]},CF={inputPlaceholder:[{type:0,value:"Wat is je vraag?"}],useCue:[{type:0,value:"Voeg toe aan bericht"}],copyCue:[{type:0,value:"Kopi\xEBren"}],removeCue:[{type:0,value:"Sluiten"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}],submitLabel:[{type:0,value:"Verzend"}],resetLabel:[{type:0,value:"Gesprek wissen"}],showMore:[{type:0,value:"Toon "},{type:1,value:"amount"},{type:0,value:" meer"}]};var om={form:"dd-pleCH",formInput:"dd-pGJMY",formSubmit:"dd--gkRg",actionButton:"dd-I2NEH",resetContainer:"dd-qKIDX",sources:"dd-xf9c6",source:"dd-a-vyX",tooltip:"dd-EsgcZ",linkContent:"dd-gARDA",showMoreSources:"dd-uDGi-"};var GP=b(Y());var KP={error:"dd-CoAuB"};var R0={};xt(R0,{enUS:()=>kF,nlNL:()=>RF});var kF={errorPrefix:[{type:0,value:"Error:"}]},RF={errorPrefix:[{type:0,value:"Foutmelding:"}]};var su=b(R()),qP=({message:e})=>{let t=(0,GP.useRef)(null),n=D("WidgetCardError",KP),r=ae(R0);return Au(t),(0,su.jsx)(de,{ref:t,children:(0,su.jsx)(ve,{children:(0,su.jsxs)(ve.Content,{className:n.error,children:[r("errorPrefix")," ",e]})})})};var ye=b(R()),PF=3,IF=({sources:e,onClick:t})=>{let n=ae(Na),r=D("WidgetKnowledgeAssistant",om),[o,s]=(0,Je.useState)(!1),i=o?e:e.slice(0,PF);return i.length===0?null:(0,ye.jsxs)("ul",{className:r.sources,children:[i.map(a=>(0,ye.jsx)("li",{className:r.source,"data-testid":"knowledge-assist-source",children:(0,ye.jsxs)(gt,{tooltip:!0,placement:"top-start",children:[(0,ye.jsx)(gt.Trigger,{as:"a",rel:"noreferrer",target:"_blank",href:a.url,onClick:l=>{l.stopPropagation(),t(a)},children:(0,ye.jsx)("span",{className:r.linkContent,children:a.name})}),a.url&&(0,ye.jsx)(gt.Content,{className:r.tooltip,children:decodeURIComponent(a.url)})]})},a.name)),i<e&&(0,ye.jsx)("button",{type:"button",className:r.showMoreSources,onClick:()=>s(!0),children:n("showMore",{amount:e.length-i.length})})]})},AF=({title:e,description:t})=>(0,ye.jsx)(de,{"data-testid":"knowledge-assist-empty-state",children:(0,ye.jsx)(ve,{children:(0,ye.jsxs)(ve.Content,{children:[(0,ye.jsx)(ve.Title,{children:e}),(0,ye.jsx)(ai,{content:t})]})})}),LF=({innerRef:e,item:t,hasKeyboardInput:n,onCopy:r,onUse:o,onSourceClick:s})=>{var l;let i=ae(Na),a=(0,Je.useContext)(sm);return(0,ye.jsxs)(de,{"data-testid":"knowledge-assist-answer",ref:e,children:[(0,ye.jsx)(ve,{children:(0,ye.jsxs)(ve.Content,{children:[(0,ye.jsx)(ve.Title,{children:t.question}),(0,ye.jsx)(ai,{content:t.answer.answer,useLabel:i("useCue"),copyLabel:i("copyCue"),onCopy:r,onUse:n?o:void 0}),(0,ye.jsx)(IF,{sources:(l=t.answer.sources)!=null?l:[],onClick:s})]})}),(0,ye.jsxs)(de.ButtonsContainer,{children:[(0,ye.jsx)("div",{}),(0,ye.jsx)(Jc,{evaluationId:t.evaluationId,eventName:"Assistant response feedback",feedbackType:"assistant",eventData:{group:a.assistantCode,cueText:t.answer.answer},feedbackText:t.answer.answer})]})]})},sm=(0,Je.createContext)(null),im=({assistantCode:e,evaluateKnowledgeAssistFn:t,initialQuestion:n,children:r})=>{let[o,s]=(0,Je.useState)(null),[i,a]=(0,Je.useState)(!1),[l,c]=(0,Je.useState)(null),[u,f]=(0,Je.useState)(!!n),[d,p]=(0,Je.useState)(null),g=ge(),m=Ct(),x=Xc(h=>{if(!e)throw new Error("No knowledge assistant was defined");return c(null),t({assistantCode:e,input:h,threadId:o,onNewThreadId(S){s(S)}})},{onSuccess(h){var S;m("Assistant response displayed",{evaluationId:h.evaluationId,group:e,cueText:h.answer.answer,input:h.question,sources:(S=h.answer.sources)!=null?S:[]}),f(!1)},onError(h){var S;c((S=h.message)!=null?S:"Unknown error")}}),v=h=>A(void 0,null,function*(){a(!0),p(h),yield x.call(h),a(!1),p(null)}),y={isEnabled:!!e,assistantCode:e,isSubmitting:i,threadId:o,pendingInput:d,errorMessage:l,onSubmit:v,onReset(){o&&g(tP(o)),c(null),s(null),e&&m("Assistant thread reset",{threadId:o!=null?o:void 0,assistantCode:e})}};return(0,Je.useEffect)(()=>{n&&y.isEnabled&&v(n)},[n]),(0,ye.jsx)(sm.Provider,{value:y,children:r})},am=()=>{let e=ae(Na),t=D("WidgetKnowledgeAssistant",om),n=(0,Je.useContext)(sm),r=(0,Je.useRef)(null),[o,s]=(0,Je.useState)(""),i=l=>{s(l.target.value)},a=l=>{l.preventDefault(),n.onSubmit(o).then(()=>{var c;r.current&&((c=r.current)==null||c.focus(),s(""))})};return n.isEnabled?(0,ye.jsxs)("form",{className:t.form,onSubmit:a,children:[(0,ye.jsx)("input",{ref:r,className:t.formInput,placeholder:e("inputPlaceholder"),type:"text",disabled:n.isSubmitting,value:o,onChange:i}),(0,ye.jsx)("button",{type:"submit",disabled:n.isSubmitting||o==="",className:t.formSubmit,children:e("submitLabel")})]}):null},lm=({title:e,emptyState:t})=>{var g,m;let n=ae(Na),r=Ct(),o=D("WidgetKnowledgeAssistant",om),s=(0,Je.useRef)(null),i=(0,Je.useContext)(sm),a=(m=K(i0((g=i.threadId)!=null?g:-1)))!=null?m:[],l=te("hasKeyboardInput"),c=cn(),u=(x,v)=>{Rr(x),i.assistantCode&&r("Assistant response copied",{group:i.assistantCode,copiedText:x,originalText:x,evaluationId:v.evaluationId})},f=(x,v)=>{i.assistantCode&&r("Assistant source clicked",{evaluationId:v.evaluationId,assistantCode:i.assistantCode,source:x})},d=x=>{x.preventDefault(),i.onReset()},p=(x,v)=>{c.send(to,{text:x,suggestion:{source:"assistant",sourceText:x}}),i.assistantCode&&r("Assistant response used",{group:i.assistantCode,usedText:x,originalText:x,evaluationId:v.evaluationId})};return!i.isEnabled||(a==null?void 0:a.length)===0&&!i.isSubmitting&&!t&&!i.errorMessage?null:(0,ye.jsxs)(Je.Fragment,{children:[(0,ye.jsx)(xr,{type:"knowledge",title:e,"data-testid":"knowledge",children:(0,ye.jsxs)(zt,{withDivider:!0,children:[t&&a.length===0&&!i.pendingInput&&(0,ye.jsx)(AF,w({},t)),a.map((x,v)=>(0,ye.jsx)(LF,{innerRef:v===a.length-1?s:void 0,item:x,hasKeyboardInput:l,onCopy:y=>u(y,x),onUse:y=>p(y,x),onSourceClick:y=>f(y,x)},`${x.question}_${x.answer}_${v}`)),i.pendingInput&&(0,ye.jsx)(Zp,{title:i.pendingInput}),i.errorMessage&&(0,ye.jsx)(qP,{message:i.errorMessage})]})}),a.length>0&&(0,ye.jsx)("div",{className:o.resetContainer,children:(0,ye.jsx)(de.Button,{disabled:i.threadId===null||i.isSubmitting,onClick:d,children:n("resetLabel")})})]})};var QP=b(Y());var MF=/(https?:\/\/[^\s]+)/,XP=e=>e.split(" ").find(t=>MF.test(t));var Bn=b(R()),OF=({suggestion:e,lines:t,onUse:n})=>{var f;let r=e.text||e.url||e.message,o=XP(r),s=ae(Lc),i=te("showImages"),a=te("fallbackImage"),l=te("hasKeyboardInput"),c=d=>{d.preventDefault(),d.stopPropagation(),l&&n(r)},u=(0,QP.useCallback)(d=>{window.open(o,"_blank"),d.stopPropagation(),d.preventDefault()},[o]);return(0,Bn.jsxs)(de,{onClick:l?c:void 0,"data-testid":"edit-suggestion",children:[(0,Bn.jsxs)(ve,{children:[i&&e.image&&(0,Bn.jsx)(ve.Image,{src:Bp(e,"small",a||void 0),title:e.title}),(0,Bn.jsxs)(ve.Content,{children:[e.title&&(0,Bn.jsx)(ve.Title,{"data-testid":"widget-suggestion-title",children:e.title}),e.searchKeywords&&((f=e.searchKeywords)==null?void 0:f.length)>0&&(0,Bn.jsx)(de.Labels,{labels:e.searchKeywords}),(0,Bn.jsx)(ve.Content,{cropText:t==="single",lineClamp:t==="multiple",children:r})]})]}),(0,Bn.jsxs)(de.Actions,{children:[o&&(0,Bn.jsx)(de.ActionButton,{onClick:u,label:s("visitUrl")}),l&&(0,Bn.jsx)(de.ActionButton,{primary:!0,onClick:c,label:s("useSuggestion")})]})]})},ZP=OF;var iu=b(R()),NF=({lines:e,suggestions:t})=>{let n=cn(),r=(o,s)=>{n.send(to,{text:o,suggestion:P(w({},s),{source:s.source,sourceText:s.text})})};return(0,iu.jsx)(iu.Fragment,{children:t.map(o=>(0,iu.jsx)(ZP,{suggestion:o,lines:e,onUse:s=>r(s,o)},o.text||o.url||o.message))})},JP=NF;var au={};xt(au,{enUS:()=>_F,nlNL:()=>DF});var _F={waiting:[{type:0,value:"Loading\u2026"}],waitingForConversation:[{type:0,value:"Waiting for conversation\u2026"}],notSupported:[{type:0,value:"This conversation is not supported"}],noResults:[{type:0,value:"No results found\u2026"}],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"}],close:[{type:0,value:"Close"}]},DF={waiting:[{type:0,value:"Laden\u2026"}],waitingForConversation:[{type:0,value:"Wachten op gesprek\u2026"}],notSupported:[{type:0,value:"Dit gesprek wordt niet ondersteund"}],noResults:[{type:0,value:"Geen resultaten gevonden\u2026"}],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"}],close:[{type:0,value:"Sluiten"}]};var _a={root:"dd-W9VCG",loginText:"dd--dS6t",stateText:"dd-348OC",footer:"dd-tvofr",shortcutList:"dd-MuKK-",shortcut:"dd-5CnK9",footerShortcut:"dd-dH7XJ",link:"dd-DRo0x"};var le=b(R()),eI=(e,t)=>{let n=K(Tt);(0,as.useEffect)(()=>n?t.every(r=>!!r)?e():()=>{}:()=>{},[...t,n])},FF=({onLogIn:e})=>{let t=D("Widget",_a),n=te("isEmbedded"),r=te("adminUrl");return(0,le.jsx)("div",{className:t.loginText,children:(0,le.jsx)("div",{children:(0,le.jsx)(Rp,{isEmbedded:n,loginUrl:r,onLogIn:e})})},"login")},P0=({text:e})=>{let t=D("Widget",_a);return(0,le.jsx)("div",{className:t.stateText,children:(0,le.jsx)("div",{children:(0,le.jsx)("p",{children:e})})},"notification")},zF=()=>{let e=ae(au),t=ge(),n=D("Widget",_a),r=te("showSearch"),o=te("isEmbedded"),s=K(Ea("/admin/")),i=cn(),a=te("productName"),l=Ct();return eI(()=>{if(o)return t(l0()),()=>{t(iP())}},[t,o]),!r&&!s?null:(0,le.jsxs)("div",{className:n.shortcutList,children:[r&&(0,le.jsx)(de.Button,{"data-testid":"shortcut-search","aria-label":e("linkSearch"),className:n.shortcut,icon:(0,le.jsx)(wa,{}),onClick:()=>{i.send("ShowCommandPalette",{isOpen:!0}),l("open search",{via:"widget-shortcut"})},children:e("linkSearch")}),s&&(0,le.jsx)(de.Button,{as:"a",target:"_blank",icon:(0,le.jsx)(dP,{}),href:s,"data-testid":"shortcut-studio-login","aria-label":e("linkStudioLogin",{productName:a}),className:n.shortcut,rel:"noreferrer",onClick:()=>{l("open my deepdesk",{via:"widget-shortcut"})},children:e("linkStudioLogin",{productName:a})})]})},HF=({title:e,content:t})=>{let n=ae(au),[r,o]=(0,as.useState)(!0);return r?(0,le.jsx)(xr,{"data-testid":"custom-data-banner",type:"custom-data-banner",title:e,children:(0,le.jsx)(zt,{withDivider:!0,children:(0,le.jsxs)(de,{children:[(0,le.jsx)(ve,{children:(0,le.jsx)(ve.Content,{children:(0,le.jsx)(ai,{content:t})})}),(0,le.jsx)(de.ButtonsContainer,{children:(0,le.jsx)(de.Button,{onClick:()=>o(!1),children:n("close")})})]})})}):null},BF=()=>{let e=ge(),t=K(dc),n=K(AT),r=K(lP),o=K(K1),s=K(hp),i=K(Sp),a=K(Hs),l=K(kr);return(0,as.useEffect)(()=>{!!o&&!n&&ee.warn("Custom data provided, but no schema.")},[o,n]),eI(()=>{t.forEach(({type:c})=>{c==="entities"?e(lr()):Ou.includes(c)||e(cr(c))})},[e,l,a]),(0,as.useEffect)(()=>{r.length>0&&!t.some(c=>c.type==="cues")&&ee.warn("Received cues, but cues are not configured in widget.")},[t,r]),(0,le.jsx)(as.Fragment,{children:t.map(({type:c,title:u,amount:f,lines:d,schema:p,property:g})=>{var m,x;switch(c){case"entities":return s&&s.length>0&&(0,le.jsx)(xr,{type:c,title:u,"data-testid":`type-${c}`,children:(0,le.jsx)(uP,{entities:s})},c);case"cues":return r&&r.length>0&&(0,le.jsx)(xr,{type:c,title:u,"data-testid":`type-${c}`,children:(0,le.jsx)(zt,{withDivider:!0,children:(0,le.jsx)($P,{cues:r})})},c);case"custom-data-banner":return o&&g&&o[g]&&(0,le.jsx)(HF,{title:u,content:String(o[g])},c);case"custom-data":return o&&p&&(0,le.jsx)(xr,{type:c,title:u,"data-testid":`type-${c}`,children:(0,le.jsx)(zt,{withDivider:!0,children:(0,le.jsx)(WP,{data:o,schema:p})})},c);default:return((x=(m=i[c])==null?void 0:m.suggestions)==null?void 0:x.length)>0&&(0,le.jsx)(xr,{type:c,title:u,"data-testid":`type-${c}`,children:(0,le.jsx)(zt,{withDivider:!0,children:(0,le.jsx)(JP,{lines:d,contentType:c,suggestions:i[c].suggestions.slice(0,f)||[]})})},c)}})})},I0=({children:e})=>{let t=D("Widget",_a);return(0,le.jsx)("div",{className:t.footer,children:e})},A0=({children:e})=>{let t=D("Widget",_a);return(0,le.jsx)("div",{className:t.root,"data-testid":"widget",children:e})},UF=({onLogIn:e,knowledgeAssistOptions:t={},assistantOptions:n={transcript:"in-memory-transcript",expectFormat:"json-schema:cues"}})=>{var f;let r=ae(au),o=K(ea),s=K(Tt),i=K(A1),a=K(Hs),l=K(IT("knowledge-assist")),c=K(LT),u=K(MT);return o===!1?(0,le.jsx)(P0,{text:r("notSupported")}):s===!1?(0,le.jsx)(FF,{onLogIn:e}):s===null?(0,le.jsx)(P0,{text:r("waiting")}):!i||!a?(0,le.jsx)(P0,{text:r("waitingForConversation")}):(0,le.jsx)(A0,{children:(0,le.jsxs)(im,{initialQuestion:t.initialQuestion,assistantCode:(f=c!=null?c:u)!=null?f:void 0,evaluateKnowledgeAssistFn:u?Gc:qc,children:[(0,le.jsxs)(xi,{children:[(0,le.jsx)(zF,{}),(0,le.jsx)(BF,{}),l&&(0,le.jsx)(lm,{title:l.title,emptyState:t.emptyState})]}),(0,le.jsxs)(I0,{children:[l&&(0,le.jsx)(am,{}),(0,le.jsx)(xP,{assistantOptions:n})]})]})})},tI=UF;function Da(e){let t=new Range;return t.selectNodeContents(e),t}function nI(e,t,n){try{return ls(e,t,n),!0}catch(r){return!1}}function cm(e){return"tagName"in e&&(e.tagName==="DIV"||e.tagName==="P")}function um(e){return"tagName"in e&&e.tagName==="BR"}var lu=/[\u200B-\u200D\uFEFF]/g;function ls(e,t,n){let r=new Range;if(e.firstChild===null&&t===0&&n===0)return r.selectNodeContents(e),r;let o=0,s=!1;function i(l,c){let u=-1,f=/[\u200B-\u200D\uFEFF]/;if(!f.test(l))return c;for(let d=0;d<=l.length;d++)if(f.test(l[d])||u++,u===c)return d;throw new Error("Offset out of range")}function a(l){switch(l.nodeType){case Node.TEXT_NODE:{let c=l.textContent,u=c.replace(lu,""),f=o+u.length,d=t>=o&&t<=f,p=n>=o&&n<=f;if(d){let g=i(c,t-o);g===0&&!p?r.setStartBefore(l):r.setStart(l,g)}p&&(r.setEnd(l,i(c,n-o)),s=!0),o=f;break}case Node.ELEMENT_NODE:{if(um(l)&&(o===t&&r.setStartBefore(l),o++,o===n)){r.setEndAfter(l),s=!0;return}for(let u=0;u<l.childNodes.length&&(a(l.childNodes[u]),!s);u++);let c=l.lastChild;cm(l)&&c&&!cm(c)&&!um(c)&&o++;break}default:break}}if(a(e),r.startContainer===document)throw new Error("Offsets out of bound");return r}function cu(e,t){if(!e.contains(t.startContainer)||!e.contains(t.endContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:r,endContainer:o,endOffset:s,collapsed:i}=t,a,l,c=0;function u(f){let d=f===e,p=f===n,g=f===o;switch(f.nodeType){case Node.TEXT_NODE:{let m=f.textContent;p&&(a=c+m.substring(0,r).replace(lu,"").length),g&&(l=c+m.substring(0,s).replace(lu,"").length),c+=m.replace(lu,"").length;break}case Node.ELEMENT_NODE:{if(um(f)&&f.nextSibling){c++;break}!d&&cm(f)&&f.previousSibling&&c++;for(let m=0;m<f.childNodes.length;m++){let x=p&&m===r,v=g&&m===s;if(x&&(a=c),v&&(l=c),l!==void 0||((!x||!i)&&u(f.childNodes[m]),g&&m===s-1&&(l=c),l!==void 0))break}g&&(l=c);break}default:break}}if(u(e),l===void 0)throw new Error("Could not determine start and end");return{start:a!=null?a:l,end:l}}function uu(e,t){if(!e.contains(t.startContainer)||!e.contains(t.endContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:r,endContainer:o,endOffset:s,collapsed:i}=t,a=0,l="";function c(u){let f=u===e,d=u===n,p=u===o;switch(d&&(a=1),u.nodeType){case Node.TEXT_NODE:{if(a!==1)return;let g=d?r:0,m=p?s:void 0;l+=u.textContent.replace(lu,"").substring(g,m);break}case Node.ELEMENT_NODE:{if(!i&&a===1&&um(u)&&u.nextSibling){l+=`
81
81
  `;break}!f&&!i&&a===1&&cm(u)&&u.previousSibling&&(l+=`
82
- `);let g=d?r:0,m=p?Math.min(s,u.childNodes.length):u.childNodes.length;for(let x=g;x<m&&(c(u.childNodes[x]),a!==2);x++);break}default:break}p&&(a=2)}return c(e),l}var rI=(i=>(i.CUT="Cut",i.BACKSPACE="Backspace",i.DELETE="Delete",i.ERASEEOF="EraseEof",i.UNDO="Undo",i.CLEAR="Clear",i))(rI||{}),vo=class{constructor(t){this.element=t;this.isFocused=!1;this.isActive=!0;this.isDisposed=!1;this.eventListeners={};this.disposeHandlers=[];this.cachedText="";this.cachedCaretPosition=null;this.cachedSelection={start:0,end:0};this.cachedHTML="";this.isSubmitting=!1;this.isPossibleClearInputAction=!1;this.cachedText=this.getText(),this.cachedHTML=this.getHTML(),this.cachedSelection=this.getSelection(),this.listen()}addEventListener(t,n){let r=o=>{n(o)};this.element.addEventListener(t,r),this.disposeHandlers.push(()=>{this.element.removeEventListener(t,r)})}removeEventListener(t,n){this.element.removeEventListener(t,n)}handleInteraction(){let t=this.getText(),n=this.getHTML(),r=this.getSelection(),o=this.cachedCaretPosition===null;if(!this.isActive||(t===""&&this.cachedText!==""&&!this.isPossibleClearInputAction&&this.emit("submit"),t!==this.cachedText?(this.cachedText=t,this.cachedHTML=n,o=!0,this.emit("change",{plainText:t,rawHTML:n})):n!==null&&n!==this.cachedHTML&&(this.cachedHTML=n,o=!0,this.emit("change",{plainText:t,rawHTML:n})),(r.start!==this.cachedSelection.start||r.end!==this.cachedSelection.end)&&(this.cachedSelection=r,o=!0,this.emit("selection",r)),!o))return;let s=this.getCaretPosition();Ko(s,this.cachedCaretPosition)||(this.cachedCaretPosition=s,this.emit("caretposition",s))}handleClick(){this.handleInteraction()}handleFocus(){let t=!this.isFocused;this.isFocused=!0,t&&this.emit("focus"),this.handleInteraction()}handleBlur(){this.isPossibleClearInputAction=!1;let t=this.isFocused;this.isFocused=!1,t&&this.emit("blur")}handleKeyDown(t){let{key:n,ctrlKey:r,metaKey:o}=t;this.isPossibleClearInputAction=Object.values(rI).includes(n)||n.toLowerCase()==="z"&&(r||o),this.emit("keydown",t)}handleKeyUp(t){this.handleInteraction(),this.emit("keyup",t)}handleCut(){this.isPossibleClearInputAction=!0,this.emit("cut",{selectionText:this.getSelectedText()})}handlePaste(t){var r,o;let n=((r=t.clipboardData)==null?void 0:r.getData("text"))||((o=t.clipboardData)==null?void 0:o.getData("text/plain"))||"";this.emit("paste",{pastedText:n,selectionText:this.getSelectedText()})}listen(){this.addEventListener("keydown",n=>this.handleKeyDown(n)),this.addEventListener("keyup",n=>this.handleKeyUp(n)),this.addEventListener("input",()=>this.handleInteraction()),this.addEventListener("change",()=>this.handleInteraction()),this.addEventListener("focus",()=>this.handleFocus()),this.addEventListener("blur",()=>this.handleBlur()),this.addEventListener("cut",()=>this.handleCut()),this.addEventListener("paste",n=>this.handlePaste(n)),this.addEventListener("click",()=>this.handleInteraction()),document.activeElement===this.element&&(this.isFocused=!0);let t=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});t.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{t.disconnect()})}focus(){this.element.focus()}emit(t,...n){this.isDisposed||this.eventListeners[t]&&this.eventListeners[t].forEach(r=>{r(...n)})}on(t,n){this.isDisposed||(this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n))}off(t,n){if(!this.eventListeners[t])return;let r=this.eventListeners[t].indexOf(n);r!==-1&&this.eventListeners[t].splice(r,1)}activate(){let t=this.isActive===!1;this.isActive=!0,t&&this.handleInteraction()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(t=>t()),this.eventListeners={},this.isDisposed=!0}};function oI(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var ci=class extends vo{constructor(){super(...arguments);this.lastKnownSelection=null}getRootNode(){return this.element.getRootNode()}getText(){let n=new Range;return n.selectNodeContents(this.element),uu(this.element,n)}getHTML(){return this.element.innerHTML||""}getRange(){var i;let n=this.getRootNode();if(n.activeElement!==this.element)return null;let r="getSelection"in n?n.getSelection():window.getSelection();if(!r)return null;let o="getComposedRanges"in r&&n instanceof ShadowRoot?(i=r.getComposedRanges(n))==null?void 0:i[0]:r.rangeCount>0?r.getRangeAt(0):null;if(!o)return null;let s=this.element.ownerDocument.createRange();return s.setStart(o==null?void 0:o.startContainer,o==null?void 0:o.startOffset),s.setEnd(o==null?void 0:o.endContainer,o==null?void 0:o.endOffset),!s||!this.element.contains(s.startContainer)||!this.element.contains(s.endContainer)?null:s}getCaretPosition(){let n=this.getRange();if(!n||!n.collapsed||!("getBoundingClientRect"in n))return null;let r=n.getBoundingClientRect();return!oI(r)&&(n.insertNode(this.element.ownerDocument.createTextNode("\u2060")),r=n.getBoundingClientRect(),n.deleteContents(),!oI(r))?null:{top:r.top+r.height,left:r.left}}getSelection(){let n=this.getRange();if(n)return cu(this.element,n);let r=this.lastKnownSelection;if(r&&nI(this.element,r.start,r.end))return r;let o=Da(this.element);return o.collapse(!1),cu(this.element,o)}getSelectedText(){let{start:n,end:r}=this.getSelection();return uu(this.element,ls(this.element,n,r))}listen(){super.listen();let n=new MutationObserver(s=>{var i,a;s.length===2&&s[0].addedNodes.length===1&&((i=s[0].addedNodes[0])==null?void 0:i.textContent)==="\u2060"&&((a=s[1].removedNodes[0])==null?void 0:a.textContent)==="\u2060"||setTimeout(()=>{this.handleInteraction()},0)});n.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0}),this.disposeHandlers.push(()=>n.disconnect());let r=this.element.isContentEditable,o=new MutationObserver(()=>{this.element.isContentEditable!==r&&(r=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>o.disconnect())}};var VF=["direction","boxSizing","width","height","overflowX","overflowY","borderTopWidth","borderRightWidth","borderBottomWidth","borderLeftWidth","borderStyle","paddingTop","paddingRight","paddingBottom","paddingLeft","fontStyle","fontVariant","fontWeight","fontStretch","fontSize","fontSizeAdjust","lineHeight","fontFamily","textAlign","textTransform","textIndent","textDecoration","letterSpacing","wordSpacing","tabSize"];function sI(e,t){let n="mozInnerScreenX"in window,r=document.createElement("div");r.id="input-textarea-caret-position-mirror-div";let o=r.style,s=window.getComputedStyle(e),i=e.ownerDocument.body;o.whiteSpace="pre-wrap",o.wordWrap="break-word",o.position="absolute",o.visibility="hidden",VF.forEach(u=>{o[u]=s[u]}),n?e.scrollHeight>Number.parseInt(s.height)&&(o.overflowY="scroll"):o.overflow="hidden",r.textContent=e.value.substring(0,t);let a=document.createElement("span");a.textContent=e.value.substring(t)||".",r.appendChild(a),i.appendChild(r);let l=e.getBoundingClientRect(),c={top:l.top-e.scrollTop+a.offsetTop+Number.parseInt(s.borderTopWidth)+a.offsetHeight,left:l.left-e.scrollLeft+a.offsetLeft+Number.parseInt(s.borderLeftWidth)};return i.removeChild(r),c}var ui=class extends vo{constructor(){super(...arguments);this.lastKnownSelection=null}getText(){return this.element.value}getHTML(){return null}getSelection(){let{selectionStart:n,selectionEnd:r}=this.element;return{start:n,end:r}}getSelectedText(){let n=this.getSelection();return n?this.getText().slice(n.start,n.end):""}getCaretPosition(){return sI(this.element,this.element.selectionEnd)}listen(){super.listen();let n=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var s;return(s=n==null?void 0:n.get)==null?void 0:s.call(this.element)},set:s=>{var i;(i=n==null?void 0:n.set)==null||i.call(this.element,s),this.handleInteraction()}}),this.addEventListener("scroll",()=>{this.emit("caretposition",this.getCaretPosition())});let r=this.element.disabled,o=new MutationObserver(()=>{this.element.disabled!==r&&(r=this.element.disabled,this.emit(r?"disabled":"enabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>o.disconnect())}};function iI(e,t,n){let r=`deepdesk-iframe-${e}`,o=document.getElementById(r);if(o)return o;let s=document.createElement("iframe"),i=new URL(t);return Object.entries(n).forEach(([a,l])=>{i.searchParams.append(a,l)}),s.style.position="absolute",s.style.left="-999em",s.style.width="0px",s.style.height="0px",s.tabIndex=-1,s.id=r,s.title=`iframe-${e}`,s.src=i.toString(),window.document.body.appendChild(s),s}function $F(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch(t){return e}}var L0=class{constructor(t){this.name=t;this.disposeHandlers=[];this.broadcastChannel=new BroadcastChannel(t)}onMessage(t){this.broadcastChannel.addEventListener("message",t),this.disposeHandlers.push(()=>{this.broadcastChannel.removeEventListener("message",t)})}postMessage(t){this.broadcastChannel.postMessage(JSON.stringify(t))}close(){this.disposeHandlers.forEach(t=>t()),this.broadcastChannel.close()}},M0=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.disposeHandlers=[];this.iframe=iI(t,`${this.targetOrigin}/sdk/proxy/proxy.html`,{channel:this.name,host:window.location.origin,debug:"1"}),document.body.appendChild(this.iframe)}onMessage(t){window.addEventListener("message",t),this.disposeHandlers.push(()=>{window.removeEventListener("message",t)})}postMessage(t){var n;(n=this.iframe.contentWindow)==null||n.postMessage(JSON.stringify(t),this.targetOrigin)}close(){var t;this.disposeHandlers.forEach(n=>n()),(t=this.iframe)==null||t.remove()}},O0=class{constructor(t){this.params=t;this.deepdeskUrl=t.deepdeskUrl,this.eventMap=t.eventMap,this.externalId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setExternalId(t){this.externalId!==t&&(this.cleanup(),ee.info("Set externalId",t),this.externalId=t,this.channel=this.createChannel(t))}createChannel(t){let n=this.params.createCustomChannel?this.params.createCustomChannel(t):this.isCrossOrigin?new M0(t,this.deepdeskUrl,{debug:!0}):new L0(t),r=o=>{var i,a;if(o.origin!==this.deepdeskUrl)return;let s=$F(o.data);typeof s!="object"||s.type!=="event"||s.channel!==t||(ee.info("Received broadcast event",this.externalId,o),(a=(i=this.eventMap)[s.name])==null||a.call(i,s.payload))};return n.onMessage(r),n}send(t,n,r){var i,a;ee.info("Broadcast event",{externalId:this.externalId,name:t,payload:n});let o={type:"event",name:t,payload:n};r!==!1&&((a=(i=this.eventMap)[t])==null||a.call(i,n));let s=this.externalId==="deepdesk-general"?this.defaultChannel:this.channel;s==null||s.postMessage(P(w({},o),{channel:this.externalId}))}cleanup(t=!1){var n,r;(n=this.channel)==null||n.close(),this.channel=void 0,t&&((r=this.defaultChannel)==null||r.close(),this.defaultChannel=void 0)}},aI=O0;function jF(e){return e.replace(/(_\w)/g,t=>t[1].toUpperCase())}function _e(e){return Array.isArray(e)?e.map(_e):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>P(w({},t),{[jF(n)]:_e(e[n])}),{}):e}function WF(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function Nt(e){return Array.isArray(e)?e.map(Nt):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>P(w({},t),{[WF(n)]:Nt(e[n])}),{}):e}var Fa=class extends Error{constructor(n,r){super(n);this.body=r;this.name="CustomError"}};var N0=e=>new Promise(t=>{setTimeout(t,e)});var za=class extends Fa{constructor(){super(...arguments);this.name="ClientError"}},D0=class extends Fa{constructor(){super(...arguments);this.name="ServerError"}},_0=new Map;function KF(e){return A(this,null,function*(){if(e.status===204)return e.text().catch(()=>{}),null;let t=e.headers.get("content-type");if(t!=null&&t.includes("application/json"))return e.json();let n=yield e.text();return n===""?null:(ee.warn("Unexpected response body:",n.slice(0,20)),JSON.parse(n))})}var cs=class cs{constructor(t="",n={}){this.baseUrl=t;this.options=n;this.latestRequestByUrl={};var r;this.fetch=(r=n.fetch)!=null?r:window.fetch.bind(window)}patchFetch(t){this.fetch=t(this.fetch)}setCsrfToken(t){this.csrfToken=t}request(t,n={}){return new Promise((r,o)=>{let s={isAborted:!1,reject:o},i=`${this.baseUrl}${t}`,a=this.fetch,l=n.method===void 0||n.method.toLowerCase()==="get",k=n,{useCache:c=!1,abortLatest:u=!1,attempts:f=1,retryDelay:d=500,refreshTokenOn401:p=!0,retryOnError:g=C=>C instanceof TypeError,retryOnResponse:m=C=>C.status>=500,version:x=null}=k,v=re(k,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]);if(c){if(!l)throw new Error(`Can't use 'useCache' for ${n.method}`);if(_0.has(i)){r(_0.get(i));return}}let y=P(w({credentials:"include"},v),{headers:w({Accept:"application/json","Content-Type":"application/json"},v.headers)});!l&&this.csrfToken&&(y.headers=P(w({},y.headers),{"X-CSRFToken":this.csrfToken})),typeof x=="string"&&(y.headers=P(w({},y.headers),{"X-Deepdesk-API-Version":x}));let h=f,S=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[i]&&u&&(this.latestRequestByUrl[i].isAborted=!0,this.latestRequestByUrl[i].reject(new Error("Aborted"))),this.latestRequestByUrl[i]=s;let E=()=>A(this,null,function*(){return h--,a(i,y).then(C=>A(this,null,function*(){return m(C)&&!s.isAborted&&h>0?(yield N0(d),E()):C.status===401&&p===!0&&S===!1?(S=!0,yield this.refreshToken(),E()):C})).catch(C=>A(this,null,function*(){if(g(C)&&!s.isAborted&&h>0)return yield N0(d),E();throw C}))});E().then(C=>A(this,null,function*(){let I=yield KF(C);if(delete this.latestRequestByUrl[i],C.status>=500){o(new D0("Server Error",I));return}if(C.status===401){o(new za("Unauthorized",I));return}if(C.status===403){o(new za("Forbidden",I));return}if(C.status===404){o(new za("Not Found",I));return}if(C.status>=400){o(new za("Bad Request",I));return}c&&_0.set(i,I),r(I)})).catch(C=>{o(C)})})}validateToken(){return A(this,null,function*(){let{has_valid_access_token:t,is_logged_in:n}=yield this.get("/apis/admin/session/validate/");if(!t)try{yield this.refreshToken();let{is_logged_in:r}=yield this.get("/apis/admin/session/validate/");return r}catch(r){return!1}return n})}refreshToken(){return cs.refreshingToken||(cs.refreshingToken=this.get("/apis/admin/session/refresh/",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{cs.refreshingToken=null},1e3*60)})),cs.refreshingToken}get(t,n){return this.request(t,n)}post(t,n,r){return this.request(t,w({method:"POST",body:JSON.stringify(n)},r))}patch(t,n,r){return this.request(t,w({method:"PATCH",body:JSON.stringify(n)},r))}put(t,n,r){return this.request(t,w({method:"PUT",body:JSON.stringify(n)},r))}delete(t,n){return this.request(t,w({method:"DELETE"},n))}};cs.refreshingToken=null;var di=cs;var lI;(t=>{let e;(a=>(a.SUCCESS="success",a.FAILURE="failure",a.CONDITIONS_NOT_MET="conditions_not_met",a.MAX_RECURSION_LEVEL="max_recursion_level",a.NO_ACCESS_TO_ASSISTANT="no_access_to_assistant"))(e=t.EvaluationStatus||(t.EvaluationStatus={}))})(lI||(lI={}));function F0(e){return P(w({},_e(e)),{metadata:e.metadata})}var fi=class fi{constructor(t,n={}){this.options=n;this.latestReceivedDeepdeskVersions={};this.shouldFetchCsrfToken=!0;this.client=new di(t,{fetch:n.fetch}),this.client.patchFetch(r=>(o,s)=>A(this,null,function*(){let i=yield r(o,s);return this.handleDeepdeskVersionHeaders(i),i}))}preflight(){return A(this,null,function*(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let t=yield this.getCsrfToken();this.client.setCsrfToken(t)}return this.options.token?(fi.exchangeTokenPromise||(fi.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),fi.exchangeTokenPromise):Promise.resolve()})}createConversation(t){return A(this,null,function*(){var r;yield this.preflight(),ee.info(`Creating conversation for session ${t.externalId} and agent ${t.agentId}`);let n=yield this.client.post("/api/v2/conversations",P(w({chat_start_time:new Date().toISOString()},Nt(t)),{metadata:(r=t.metadata)!=null?r:{}}));return F0(n)})}getMe(){return A(this,null,function*(){let t=yield this.client.get("/apis/admin/session/me/");return _e(t)})}postIdentity(t){return A(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/me/identities/",Nt(t))})}patchMe(t){return A(this,null,function*(){yield this.preflight();let n=yield this.client.patch("/apis/admin/session/me/",Nt(t));return _e(n)})}getProfile(t){return A(this,null,function*(){let n=yield this.client.get(`/apis/admin/profiles/${t}/`,{useCache:!0});return _e(n)})}getKnowledgeAssistant(t){return A(this,null,function*(){let n=yield this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{useCache:!0});return _e(n)})}getContentTypes(){return A(this,null,function*(){let t=yield this.client.get("/apis/admin/content-types/",{useCache:!0});return _e(t)})}getAccount(){return A(this,null,function*(){let t=yield this.client.get("/apis/admin/account/",{useCache:!0});return _e(t)})}getPlatformConfig(t){return A(this,null,function*(){let n=t!==void 0?`/platform/config/${t}/`:"/platform/config/",{config:r}=yield this.client.get(n,{useCache:!0});return _e(r)})}checkUserExists(t){return A(this,null,function*(){let{exists:n}=yield this.client.get(`/apis/admin/users/exists?external_id=${t}`,{version:"v1"});return n})}getConversationByExternalId(r){return A(this,arguments,function*(t,n={}){yield this.preflight(),ee.info(`Getting conversation for session ${t}`);let{attempts:o=1,retryDelay:s=1e3}=n,i=yield this.client.get(`/api/v2/conversations/by_external_id/${t}`,{attempts:o,retryDelay:s,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"});return ee.info(`Successfully retrieved conversation ${i.id} for session ${t}`),F0(i)})}isConversationSupported(r){return A(this,arguments,function*(t,n={}){ee.info(`Check if conversation for session ${t} is supported`);let{attempts:o=1,retryDelay:s=1e3}=n;return(yield this.client.get(`/api/v2/conversations/by_external_id/${t}/has_active_profile`,{attempts:o,retryDelay:s,retryOnResponse:a=>a.status===404||a.status>=500})).has_active_profile})}updateConversation(t,n){return A(this,null,function*(){var s;yield this.preflight();let r=Nt(n);n.metadata&&(r.metadata=(s=n.metadata)!=null?s:{});let o=yield this.client.put(`/api/v2/conversations/${t}`,r);return F0(o)})}postMessages(t,n){return A(this,null,function*(){yield this.preflight(),yield this.client.post(`/api/v2/conversations/${t}/messages`,n.map(r=>P(w({},Nt(r)),{metadata:r.metadata})))})}sendEvent(t,n){return A(this,null,function*(){yield this.preflight();let a=n,{data:r}=a,o=re(a,["data"]),s=Object.entries(this.latestReceivedDeepdeskVersions).reduce((l,[c,u])=>P(w({},l),{[c]:u}),{}),i=["platform","agentId","agentName","agentEmail","conversationId"].reduce((l,c)=>(o[c]&&(l[c]=o[c]),l),{});return this.client.post("/api/v2/events",Nt(P(w(w({},s),i),{data:r,name:t})),{version:"v2"})})}getEntities(t){return A(this,null,function*(){return yield this.preflight(),yield this.client.post("/api/v2/entities",{messages:t.filter(r=>r.text)})})}getTemporaryExchangeToken(){return A(this,null,function*(){return(yield this.client.get("/apis/admin/session/exchange-token/")).jwt})}exchangeTokenForAccessCookie(t){return A(this,null,function*(){return this.client.post("/apis/admin/session/jwt/",{jwt:t}).catch(n=>{throw ee.warn(`Invalid token '${t}'`),n})})}authenticateWithKey(t,n){return A(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/api-key/",Nt(n),{refreshTokenOn401:!1,headers:{apikey:t}})})}getTextSuggestions(o){return A(this,arguments,function*(t,n={},r){if(yield this.preflight(),r==="sticky-messages")throw new Error("Use getPinnedMessages instead");return(yield this.client.post(`/api/v2/conversations/${t}/recommend/${r}`,Nt(n),{abortLatest:!0})).map(i=>P(w({},_e(i)),{text:i.text||i.url||i.message,source:r,type:r})).filter((i,a,l)=>a===l.findIndex(c=>c.text===i.text))})}isLoggedIn(){return A(this,null,function*(){return yield this.preflight(),this.client.validateToken()})}getAutocompleteSuggestions(t,n){return A(this,null,function*(){return yield this.preflight(),(yield this.client.post(`/api/v2/conversations/${t}/autocomplete`,Nt(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,s,i)=>s===i.findIndex(a=>a.text===o.text))})}getPinnedMessages(t){return A(this,null,function*(){let n=yield this.client.get(`/api/v2/profiles/${t}/pinned-messages`,{abortLatest:!0});return _e(n).map(r=>P(w({},r),{text:r.message,source:"sticky-messages",type:"pinned-message"}))})}getStyleSuggestions(t){return A(this,null,function*(){let n=yield this.client.post("/api/v2/style-suggestions",Nt(t),{abortLatest:!0,version:"v2"});return _e(n)})}search(t){return A(this,null,function*(){let n=yield this.client.post(`/api/v2/profiles/${t.profile}/search`,Nt(t));return _e(n)})}knowledgeAssist(s,i,a){return A(this,arguments,function*(t,n,r,o={}){yield this.preflight();let l=yield this.client.post(`/api/knowledge-assist/assistants/${r}/search`,Nt({question:t.question,doNotKnowAnswer:t.doNotKnowAnswer,customerInstruction:t.customerInstruction,chatHistory:n.map(c=>({question:c.question,answer:c.answer.answer})),agentId:o.agentId,conversationId:o.conversationId}),{version:"v2"});return _e(l)})}requestLoginByEmail(t){return A(this,null,function*(){yield this.preflight();let n=yield this.client.post("/apis/admin/session/passwordless/request/",{email:t});return _e(n)})}requestPasswordlessToken(){return A(this,null,function*(){let t=yield this.client.get("/apis/admin/session/passwordless/request/");return _e(t.token)})}getCsrfToken(){return A(this,null,function*(){let{token:t}=yield this.client.get("/apis/admin/session/csrf/");return t})}verifyLoginToken(t){return A(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/login/",{token:t});return _e(n)})}getSummary(r){return A(this,arguments,function*(t,n={}){yield this.preflight();let o=yield this.client.post("/api/summary",{conversation:{messages:t.filter(s=>s.text&&s.source),agent_id:n.agentId,id:n.externalConversationId},prompt_instruction:n.promptInstruction,model:n.model},{version:"v1"});return _e(o)})}evaluateAssistant(t,n){return A(this,null,function*(){var a;yield this.preflight();let r=new URLSearchParams,{expectFormat:o="text"}=n||{};if(o.startsWith("json-schema:")){let l=o.replace("json-schema:","");r.append("expect_response_format","json-schema"),r.append("expect_response_format_schema",l)}else r.append("expect_response_format",o);n!=null&&n.externalConversationId&&r.append("external_conversation_id",n.externalConversationId);let s=n!=null&&n.threadId?`/api/v2/assistants/${t}/threads/${n==null?void 0:n.threadId}/evaluate?${r.toString()}`:`/api/v2/assistants/${t}/evaluate?${r.toString()}`,i=yield this.client.post(s,{input:(a=n==null?void 0:n.input)!=null?a:{},conversation:n==null?void 0:n.transcript});return _e(i)})}createAssistantThread(t){return A(this,null,function*(){yield this.preflight();let{assistantCode:n}=t,r=yield this.client.post(`/apis/admin/assistants/${n}/threads/`,{});return _e(r)})}postMessageToAssistantThread(t){return A(this,null,function*(){yield this.preflight();let{assistantCode:n,threadId:r,message:o}=t,s=yield this.client.post(`/apis/admin/assistants/${n}/threads/${r}/messages/`,{content:o,role:"user"});return _e(s)})}translateMessages(t){return A(this,null,function*(){yield this.preflight();let n=yield this.client.post("/api/v2/translate",Nt(t));return _e(n)})}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),s=o.match(Gx);if(!n||!s)return;let i=s[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[i];a&&n&&a!==n&&ee.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[i]=n})}};fi.exchangeTokenPromise=null;var xo=fi;var cI={startTime:null,stopTime:null},uI=e=>e.handlingTime,dI=Ee({name:"handlingTime",initialState:cI,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(at,()=>cI)}}),{handlingTimeStart:fI,handlingTimeStop:dm,handlingTimeReset:pI}=dI.actions,mI=dI.reducer;var gI=(e={})=>{let t=w({onAuthError:Ji(!1)},e);return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var fm={list:{keywordMatches:[]},fetchState:"idle"};var pi=fe("styleSuggestions/getAll",(n,r)=>A(void 0,[n,r],function*({text:e},t){var l;let{deepdeskAPI:o}=t.extra,s=t.getState(),{showStyleSuggestions:i}=s.settings,a=(l=s.conversation.current)==null?void 0:l.profileCode;if(!i)return fm.list;if(!a)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:a,message:e})})),GF=Ee({name:"styleSuggestions",initialState:fm,reducers:{},extraReducers:e=>{e.addCase(pi.pending,t=>{t.fetchState="loading"}).addCase(pi.rejected,t=>{t.fetchState="error"}).addCase(pi.fulfilled,(t,n)=>{t.fetchState="done",Ko(t.list,n.payload)||(t.list=n.payload)}).addCase(Ds,t=>{t.list=fm.list}).addCase(at,()=>fm)}}),hI=GF.reducer;var yI=(e={})=>{let t,n=!0,r=w({getStyleSuggestions:pi,debounce:500},e);return o=>s=>i=>{var p;let a=o.getState().input.text,l=s(i),c=o.getState();if(c.auth.isLoggedIn!==!0)return l;let{showStyleSuggestions:u}=c.settings;if(!((p=c.conversation.current)==null?void 0:p.id)||!u)return l;let{text:d}=c.input;return d===a&&!n||(clearTimeout(t),d==="")||(t=setTimeout(()=>{n=!1,o.dispatch(r.getStyleSuggestions({text:d}))},e.debounce)),l}};function qF(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end}var vI=(e={})=>{let t=w({getTextSuggestions:cr,getAutocompleteSuggestions:Oc,debounce:200,check:Ar},e),n;return r=>o=>s=>{var m;let{input:i}=r.getState(),a=o(s),l=r.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:c,showTabCompletion:u}=l.settings,f=(m=l.conversation.current)==null?void 0:m.id,d=s.type===wp.toString();if(!f||!c&&!u)return a;let{input:p}=l;return qF(p,i)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let x=ta(l);x===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(x))},d?0:t.debounce)),a}};var xI=pi.fulfilled.toString();function YF(e,t){let n=new Set([...t.keywordMatches.map(o=>o.keyword)]),r=[];return n.forEach(o=>{let s=e.keywordMatches.filter(l=>l.keyword===o),i=t.keywordMatches.filter(l=>l.keyword===o),a=i.length-s.length;a<=0||r.push(...i.slice(0,a))}),r}var SI=e=>t=>n=>r=>{var c;if(r.type!==xI){n(r);return}let o=t.getState().styleSuggestions.list;n(r);let s=t.getState(),i=s.styleSuggestions.list,a=(c=s.conversation)==null?void 0:c.current;if(o===i)return;let l=YF(o,i);r.type===xI&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var XF=tf({assistants:oP,auth:S1,conversation:L1,contentTypes:kT,passwordlessToken:aP,entities:bk,handlingTime:mI,info:Q1,input:$1,settings:m1,profile:OT,search:rT,styleSuggestions:hI,ui:Yk,textSuggestions:Mk});function wI(e){return UE({reducer:XF,middleware:t=>{var r;let n=t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI}},serializableCheck:!1}).concat(gI()).concat(vI({debounce:200})).concat(yI({debounce:500})).concat(SI(e.deepdeskAPI));return((r=e.middleware)!=null?r:[]).reduce((o,s)=>o.concat(s),n)},preloadedState:e.preloadedState})}var QF=e=>{var t,n;return(n=(t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())!=null?n:"unknown"},ZF=e=>t=>n=>r=>{var a,l,c,u,f,d,p;let o=t.getState(),s=$l("inlineSuggestions")(o);switch(r.type){case Ji.toString():{!r.payload&&e.emit("logout",void 0);break}case lr.fulfilled.toString():r.payload.length>0&&e.sendEvent("entities found",{conversationId:(a=o.conversation.current)==null?void 0:a.id,data:{entities:r.payload}});break;case Go.toString():e.sendEvent(r.payload.name,{conversationId:((l=r.payload.options)==null?void 0:l.includeConversationData)&&((c=o.conversation.current)==null?void 0:c.id),data:r.payload.data});break;case Ds.toString():e.logSendMessage(r.payload);break;case qp.toString():e.emit("call-to-action",{cue:r.payload});break;case fr.fulfilled.toString():r.isBroadcasted||e.broadcast(Iy,r,!1);break;default:break}let i=n(r);switch(r.type){case Ds.toString():e.handleAfterSendMessage(r.payload);break;case _c.toString():e.onUpdateShowTabHint(r.payload);break;case dm.toString():e.logHandlingTime();break;case ra.toString():e.broadcast(Xl,r);break;case _s.toString():e.broadcast(Xl,r);break;case Yp.toString():t.dispatch(_s({source:"assistant",assistantCode:r.payload.code}));break;case"analytics/logEvent/fulfilled":{e.emit("event",r.meta.arg);break}case xf.toString():{let{start:g,end:m}=o.input.selection;e.emit("replace",P(w({},r.payload),{replace:r.payload.replace==="selection"?{start:g,end:m}:{start:0,end:m}}));break}case Zn.toString():{let{start:g,end:m}=o.input.selection;e.emit("select-suggestion",P(w({type:QF(r.payload.suggestion)},r.payload),{replace:r.payload.replace==="selection"?{start:g,end:m}:{start:0,end:m}})),s&&t.dispatch(qo([]));break}case Sf.toString():e.emit("select-image",r.payload),e.sendEvent("Image attached",{conversationId:(u=o.conversation.current)==null?void 0:u.id,data:{path:r.payload.suggestion.image,title:r.payload.suggestion.title}});break;case qo.toString():{s&&r.payload.length>0&&t.dispatch(wf(0));break}case mo.fulfilled.toString():{if(r.isBroadcasted)break;e.broadcast(Xl,r,!1),e.sendEvent("conversation summarized",{conversationId:(f=o.conversation.current)==null?void 0:f.id,data:{summary:r.payload.output,assistant:(p=(d=t.getState().profile.data)==null?void 0:d.summarizerAssistantNew)!=null?p:void 0}}),e.emit("summary-generated",{summary:r.payload.output});break}default:break}return i},bI=ZF;function z0(e){return e.toISOString().replace("T"," ").replace("Z","")}var JF=(e,t)=>t.version,EI=Vt([oa,kr,uI,JF],(e,t,n,r)=>{if(!t)return ee.warn("No conversationId for handling time metrics"),null;let{startTime:o,stopTime:s}=n;return!o||!s?(ee.warn("No startTime and stopTime for handling time metrics"),null):{conversationId:t,clientVersion:r,agentId:e==null?void 0:e.agentId,agentName:e==null?void 0:e.agentName,agentEmail:e==null?void 0:e.agentEmail,timeStart:z0(o),timeStop:z0(s)}});function TI(e,t){let{text:n,metrics:{numPaste:r,pastes:o,textSuggestions:s}}=e.input,i=n.length;return{source:"agent",clientVersion:t.version,pastes:o,lenTextTotal:i,numPastes:r,suggestions:s}}function H0(e,t){var s;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return H0(r,t);let o=(s=e.ownerDocument.defaultView)==null?void 0:s.frameElement;return o?H0(o,t):null}function B0(e,t){return H0(e,t)}function CI(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function e5(e){return typeof e=="object"&&e!==null&&"tagName"in e}function pm(e){return e5(e)&&(ni(e)||Ip(e))}var RI,Dr=new Map,t5=["bottom","height","left","right","top","width"],kI=(e,t)=>!e&&!t?!1:e&&!t||!e&&t?!0:t5.some(n=>e[n]!==t[n]);function PI(e){var n,r,o;if(e.ownerDocument===document)return[];let t=(o=(r=(n=e.ownerDocument)==null?void 0:n.defaultView)==null?void 0:r.frameElement)!=null?o:null;return t?[t,...PI(t)]:[]}function II(e,t){return!e||!t?null:P(w({},e),{top:e.top+t.top,left:e.left+t.left})}var mm=!1,AI=()=>{mm=!0;let e=[];if(Dr.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),Dr.delete(n);return}let r=n.getBoundingClientRect();kI(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{let n=t.parentRects?t.parentRects.reduce(II,t.rect):t.rect;kI(n,t.totalRect)&&t.callbacks.forEach(r=>r(n)),t.totalRect=n}),Dr.size===0){mm=!1;return}RI=window.requestAnimationFrame(AI)};function U0(e,t){let n=PI(e),r=[],o=n.map((s,i)=>U0(s,a=>{r[i]=a;let l=Dr.get(e);if(!l)return;let c=r.reduce(II,l.rect);l.callbacks.forEach(u=>u(c))}));return{observe(s=!0){if(o.forEach(i=>i.observe(!1)),Dr.has(e)){let i=Dr.get(e);i.callbacks.push(t),i.rect&&t(i.rect)}else Dr.set(e,{rect:void 0,callbacks:[t],parentRects:r});s&&!mm&&AI()},unobserve(){o.forEach(i=>i.unobserve());let s=Dr.get(e);if(s){let i=s.callbacks.indexOf(t);i>=0&&s.callbacks.splice(i,1),s.callbacks.length||Dr.delete(e),Dr.size||(cancelAnimationFrame(RI),mm=!1)}}}}var LI,Fr=new Map,MI=()=>{Fr.forEach((e,t)=>{if(!t.isConnected){Fr.delete(t);return}let{clientHeight:n,scrollHeight:r}=t,o=r>n;e.visible!==o&&(e.visible=o,e.callbacks.forEach(s=>s(e.visible)))}),Fr.size!==0&&(LI=window.requestAnimationFrame(MI))};function OI(e,t){return{observe(){let n=Fr.size===0;Fr.has(e)?Fr.get(e).callbacks.push(t):Fr.set(e,{visible:void 0,callbacks:[t]}),n&&MI()},unobserve(){let n=Fr.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||Fr.delete(e),Fr.size||cancelAnimationFrame(LI)}}}}var V0=["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 $0(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function Ha(e){return Number.parseFloat(e)}function gm(e){return Math.round(e*1e6)}function NI(e){return e/1e6}function j0(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=Ha(e.width),s=Ha(e.borderLeftWidth),i=Ha(e.borderRightWidth),a=Ha(e.paddingRight),l=NI(gm(o)-gm(s)-gm(i)),c=NI(gm(r));if(l-c>2){let u=l-c;n.style.paddingRight=`${a+u}px`}}function du(e,t={}){var u,f;let n=t.overlayContainer||document.createElement("div");n.style.display="none",n.style.position=(u=t.position)!=null?u:"fixed",n.style.pointerEvents="none",n.style.borderColor="transparent",ti(n);let r=window.getComputedStyle(e),o=!0,s=()=>{n.scrollTop=e.scrollTop};$0(r,n,V0),j0(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",s));let i=OI(e,()=>{$0(r,n,V0),j0(r,e,n),s(),setTimeout(s,0)}),a,l=!0,c=U0(e,d=>{if(d===null){t.onRemove&&t.onRemove(),n.remove();return}if(!l&&t.onMoveStart&&(Promise.resolve().then(()=>t.onMoveStart()),l=!0),clearTimeout(a),a=setTimeout(()=>{t.onMoveEnd&&t.onMoveEnd(),l=!1},200),d.height===0&&d.width===0){if(o===!0)return;t.onHide&&t.onHide(),n.style.display="none",o=!0;return}if($0(r,n,V0),j0(r,e,n),s(),t.placement==="below"&&n.classList.add("below"),n.style.top=`${d.top}px`,n.style.left=`${d.left}px`,t.closestScrollElement&&t.closestScrollElement!==e){let p=t.closestScrollElement.getBoundingClientRect(),g=window.getComputedStyle(t.closestScrollElement),m=Ha(g.borderTopWidth),x=Ha(g.borderBottomWidth),v=p.top+m-d.top,y=d.top+d.height+-(p.top+p.height-x);n.style.clipPath=`inset(${v}px 0px ${y}px 0px)`}o&&(n.style.display="block",t.onShow&&t.onShow(),o=!1)});return t.appendTo?t.appendTo.appendChild(n):(f=e.parentElement)==null||f.appendChild(n),c.observe(),i.observe(),[n,()=>{e.removeEventListener("scroll",s),c.unobserve(),i.unobserve(),n.remove()}]}var _I=(e,t)=>({value(){try{let n=sessionStorage.getItem(`dd-${e}`);if(!n)return t;try{return JSON.parse(n)}catch(r){return t}}catch(n){return t}},update(n){try{sessionStorage.setItem(`dd-${e}`,JSON.stringify(n))}catch(r){ee.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function n5(e){return e.offsetParent!==null}function DI(e){if(!n5(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 hm(e,t,n=100){let r=DI(e);t({isVisible:r});let o=setInterval(()=>{let s=DI(e);s!==r&&(r=s,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var fu=class extends Error{};function r5(){let e,t;return{promise:new Promise((r,o)=>{e=r,t=o}),resolve:e,reject:t}}var ym=class{constructor(){this.queues={}}push(t,n){let r=()=>{let s=this.queues[t][1];s?(this.queues[t]=[s.promise,null],s.resolve()):delete this.queues[t]};if(!this.queues[t]){let s=n().finally(r);return this.queues[t]=[s,null],s}this.queues[t][1]&&this.queues[t][1].reject(new fu("Queued async function is outdated"));let o=r5();return this.queues[t][1]=o,o.promise.then(()=>n().finally(r))}};var o5={accepted:"onConversationAcceptedAssistants","new-message":"onConversationNewMessageAssistants",ended:"onConversationEndedAssistants"},FI=(e,t)=>{let n=e[o5[t]];return n&&n.length>0?n.map(r=>r.code):(ee.warn(`No assistant set in profile for conversation event "${t}"`),[])};var vm=class{constructor(t){this.options=t;this.socket=null;this.maxReconnectAttempts=5;this.reconnectInterval=25e3;this.cleanupCallbacks=[];var n,r;this.socket,this.eventListeners=new Map,this.url=t.url,this.maxReconnectAttempts=(n=t.maxReconnectAttempts)!=null?n:this.maxReconnectAttempts,this.reconnectInterval=(r=t.reconnectInterval)!=null?r:this.reconnectInterval,this.shouldReconnect=t.shouldReconnect}connect(){let t=()=>this.cleanup();window.addEventListener("beforeunload",t),this.cleanupCallbacks.push(()=>window.removeEventListener("beforeunload",t)),this.reconnect()}setupListeners(){this.socket&&(this.socket.onmessage=t=>{var n;try{let r=_e(JSON.parse(t.data));r.event&&this.eventListeners.has(r.event)&&((n=this.eventListeners.get(r.event))==null||n.forEach(o=>o(r.data)))}catch(r){console.error("Error parsing WebSocket message:",r)}},this.socket.onclose=t=>{console.log("WebSocket connection closed:",t),setTimeout(()=>{this.reconnect()},this.reconnectInterval)},this.socket.onerror=t=>{console.error("WebSocket error:",t)})}reconnect(){var t,n;if(this.maxReconnectAttempts<=0){console.error("Max reconnect attempts reached, closing WebSocket connection."),(t=this.socket)==null||t.close();return}if(!this.shouldReconnect()){console.error("Should not reconnect, closing WebSocket connection."),(n=this.socket)==null||n.close();return}this.socket&&(this.socket.onmessage=null,this.socket.onclose=null,this.socket.onerror=null,this.socket.close()),this.socket=new WebSocket(this.url),this.setupListeners(),this.maxReconnectAttempts--}send(t,n){if(!this.socket){console.error("WebSocket connection is not open.");return}this.socket.send(JSON.stringify({event:t,data:n}))}on(t,n){this.eventListeners.has(t)||this.eventListeners.set(t,[]);let r=this.eventListeners.get(t);r&&!r.includes(n)&&r.push(n)}close(){var t;(t=this.socket)==null||t.close()}cleanup(){this.close(),this.cleanupCallbacks.forEach(t=>t()),this.cleanupCallbacks=[]}};var Ie=b(R());var zI=_I("showTabHint",!0),Ba=class Ba{constructor({deepdeskUrl:t,version:n=Ba.version||"unknown",locale:r="en-US",token:o,fetch:s,productName:i,createCustomChannel:a,websocketClient:l=vm}){this.inputMediator=null;this.eventListeners={};this.unmountHandlers=[];this.disposeHandlers=[];this.inlineSuggestions=null;this.aboveSuggestions=null;this.belowSuggestions=null;this.floatingMenu=null;this.widgetElement=null;this.widgetRoot=null;this.dynamicThunkObject={};this.queues=new ym;this.isMounted=!1;this.shouldRender=!0;this.loadProfileConfigPromise=null;let c=t.replace(/\/api$/,"");this.deepdeskApi=new xo(c,{token:o,fetch:s}),this.version=n,this.instanceId=Ba.count++;let u={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[bI({broadcast:(p,g,m)=>{this.broadcastEvents.send(p,g,m)},emit:(p,g)=>this.emit(p,g),handleAfterSendMessage:p=>this.handleAfterSendMessage(p),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:p=>this.logSendMessage(p),onUpdateShowTabHint:p=>zI.update(p),sendEvent:(p,g)=>this.deepdeskApi.sendEvent(p,g)})]};this.store=wI(u),this.broadcastEvents=new aI({debug:!0,deepdeskUrl:c,eventMap:oT(this.store),createCustomChannel:a}),this.disposeHandlers.push(()=>{this.broadcastEvents.cleanup()}),this.ws=new l({url:`${c}/api/v2/me/realtime`.replace("https","wss"),reconnectInterval:25e3,shouldReconnect:()=>A(this,null,function*(){var p;return(p=Tt(this.state))!=null?p:!1})}),this.whenLoggedIn(()=>this.ws.connect()),this.store.dispatch(_c(zI.value())),this.store.dispatch(mf({locale:r,adminUrl:c,productName:i}));let f=[];this.ws.on("assistants::user_notification",p=>{if(!p.conversationId)return;let g=()=>{this.conversationId()===p.conversationId&&this.store.dispatch(rP(p))};this.hasConversation()?g():f.push(g)}),this.ws.on("assistants::response_chunk",p=>{if(!p.conversationId)return;let g=()=>{this.conversationId()===p.conversationId&&this.store.dispatch(nP(p))};this.hasConversation()?g():f.push(g)}),this.ws.on("assistants::suggest_as_reply",p=>{if(!p.conversationId)return;let g=()=>{this.conversationId()===p.conversationId&&this.store.dispatch(ra([{text:p.payload.message,type:"text",source:"assistant",assistantCode:p.code,sourceLabel:p.name}]))};this.hasConversation()?g():f.push(g)});let d=this.whenConversationLoaded(()=>{var p;this.broadcastEvents.setExternalId((p=this.state.conversation.current)==null?void 0:p.externalId),f.forEach(g=>g()),f.length=0});this.disposeHandlers.push(()=>{this.ws.cleanup(),f.length=0,d()})}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){var t;return(t=Ns(this.state)[this.state.input.selectedSuggestionIndex])!=null?t:null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}externalId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.externalId}shouldAbort(){return this.state.conversation.isSupported===!1?(ee.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(ee.warn("Profile has not been loaded (yet)"),!0):(ee.warn("No conversation loaded (yet)"),!0)}whenLoggedIn(t){if(Tt(this.state))t();else{let n=this.subscribe(Tt,r=>{r&&t()});this.disposeHandlers.push(()=>{n()})}}login(){return this.store.dispatch(Ji(null)),this.store.dispatch(Jr()),new Promise(t=>{this.whenLoggedIn(()=>t())})}isLoggedIn(){return A(this,null,function*(){return(yield this.store.dispatch(Jr())).payload})}isConversationSupported(t,n){return A(this,null,function*(){return(yield this.store.dispatch(by({externalId:t,options:n}))).payload})}createConversation(t){return A(this,null,function*(){var r;return this.hasConversation()&&this.externalId()!==t.externalId&&this.resetConversation(),(yield this.store.dispatch(hf(P(w({},t),{metadata:(r=t.metadata)!=null?r:{}})))).payload})}getConversationByExternalId(t,n){return A(this,null,function*(){return this.hasConversation()&&this.externalId()!==t&&this.resetConversation(),(yield this.store.dispatch(yf({externalId:t,options:n}))).payload})}upsertConversation(t){return A(this,null,function*(){var r;return this.hasConversation()&&this.externalId()!==t.externalId&&this.resetConversation(),(yield this.store.dispatch(Ey(P(w({},t),{metadata:(r=t.metadata)!=null?r:{}})))).payload})}postMessages(t){return A(this,null,function*(){yield this.store.dispatch(Ty(t))})}updateConversation(t){return A(this,null,function*(){return(yield this.store.dispatch(vf(t))).payload})}resetConversation(){this.store.dispatch(at()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}configure(t){this.store.dispatch(mf(t))}setVisitorInfo(t){this.store.dispatch(q1(t))}setCustomData(t){this.store.dispatch(Y1(t))}setAgentInfo(t,n){return A(this,null,function*(){yield this.store.dispatch(Gl(w(w({},t),n)))})}setAgentSettings(t){return A(this,null,function*(){yield this.store.dispatch(ky(t))})}getAgentSettings(){return A(this,null,function*(){return(yield this.store.dispatch(Ry())).payload})}refresh(){return A(this,null,function*(){if(this.shouldAbort())return Promise.resolve();let t=[];return t.push(this.refreshTextSuggestions()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})})}syncInputMediator(){this.inputMediator&&this.store.dispatch(bf({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()}))}notifyExternalSuggestion(t){this.store.dispatch(Zn(t))}evaluateAssistant(t,n){return A(this,null,function*(){var f;let u=n||{},{input:r={},transcript:o,showCuesInWidget:s=!0,includeMetadata:i,expectFormat:a}=u,l=re(u,["input","transcript","showCuesInWidget","includeMetadata","expectFormat"]);Object.assign(r,l);let c=yield this.store.dispatch(fr({assistantCode:t,expectFormat:a||"json-schema:cues",transcript:o,includeMetadata:i,input:r,skipState:!s}));if(c.error)throw new Error(`Assistant evaluation failed: ${(f=c.payload)!=null?f:c.error.message}`);return c.payload.output})}evaluateConversationAssistant(t,n){return A(this,null,function*(){yield this.loadProfileConfig();let r=this.state.profile.data;if(!r){ee.warn("Can't evaluate assistant when profile is not loaded yet.");return}let o=FI(r,t);yield Promise.all(o.map(s=>this.queues.push(s,()=>A(this,null,function*(){if(s===r.summarizerAssistantNew)return this.getSummary(w({includeMetadata:!0},n));yield this.evaluateAssistant(s,w({includeMetadata:!0},n))})).catch(i=>{if(i instanceof fu){ee.warn(`Queued assistant "${s}" was outdated and dropped`);return}throw i})))})}getSummary(){return A(this,arguments,function*(t={}){var r;if(!this.hasConversation())return ee.warn("No conversation to create summary for."),null;(r=this.state.profile.data)!=null&&r.summarizerAssistantNew||ee.warn("No profile loaded yet, or no summarizer assistant set in profile");let n=yield this.store.dispatch(mo(t));return n.error?(ee.error("Error evaluating summary assistant",n.error),null):n.payload.output})}handleKeyDown(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui,{textSuggestions:o,selectedSuggestionIndex:s,selection:i}=this.state.input,{inlineSuggestions:a,showTextSuggestions:l,suggestionsPlacement:c}=this.settings,u=c==="inline"||c==="below"?"below":"above",f=o.length>0;if(this.store.dispatch(D1(Cy(t))),!Ar(this.state)||t.key!=="Tab"&&!l)return;let d=()=>{n||!f||i&&(t.shiftKey||(this.store.dispatch(H1()),t.preventDefault()))},p=()=>{n||!f||a&&s<=0||i&&(t.shiftKey||(this.store.dispatch(B1()),t.preventDefault()))};switch(t.key){case"ArrowUp":u==="below"?p():d();break;case"ArrowDown":{u==="below"?d():p();break}case"Escape":{n||(this.store.dispatch(wf(-1)),this.store.dispatch(ns({collapse:!0})),this.store.dispatch(Gk(!0)),t.preventDefault());break}case"Tab":{t.preventDefault();let g=na(this.state);if(!g)return;this.store.dispatch(_c(!1)),this.store.dispatch(Zn({text:g.text,suggestion:g,eventMetrics:{inputType:"tab"},replace:"until-selection-end"}));break}case" ":{if(this.settings.inlineSuggestions||this.state.input.selectedSuggestionIndex===-1)return;let g=na(this.state);if(!g)return;this.store.dispatch(Zn({text:g.text,suggestion:g,eventMetrics:{inputType:"space"},replace:"until-selection-end"}));break}case"Enter":{if(this.settings.inlineSuggestions||t.shiftKey||this.state.input.selectedSuggestionIndex===-1)return;let g=na(this.state);if(!g)return;this.store.dispatch(Zn({text:g.text,suggestion:g,eventMetrics:{inputType:"enter"},replace:"until-selection-end"})),t.preventDefault();break}default:}n&&r&&this.store.dispatch(ns({collapse:!1}))}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(qo([]))}handlingTimeStart(){this.state.handlingTime.startTime||(ee.info("Start handling time"),this.store.dispatch(fI()))}handlingTimeStop(){this.state.handlingTime.startTime&&(ee.info("Stop handling time"),this.store.dispatch(dm()))}logSendMessage(t){let n=TI(this.state,{version:this.version});n&&(t&&(Object.assign(n,{text:t}),Object.assign(n,{lenTextTotal:t.length})),this.deepdeskApi.sendEvent("Send Message",{conversationId:this.conversationId(),data:n}),this.emit("send-message-event",n))}logHandlingTime(){let t=EI(this.state,{version:this.version});t&&(this.deepdeskApi.sendEvent("Handling Time",{conversationId:this.conversationId(),data:t}),this.store.dispatch(pI()))}notifySubmit(t={}){var n;this.shouldAbort()||(this.store.dispatch(Ds((n=t.text)!=null?n:this.state.input.text)),this.store.dispatch(V1()))}emit(t,n){let r=this.eventListeners[t];r&&r.forEach(o=>{try{o(n)}catch(s){ee.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),ee.error(s)}})}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),()=>{this.off(t,n)}}off(t,n){if(!t&&!n){this.eventListeners={};return}let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}setConversationQuery(t){this.dynamicThunkObject.conversationQuery=t}setPlatformVariables(t){this.store.dispatch(X1(t))}whenConversationLoaded(t){let n=s=>{var i;return(i=s.conversation.current)==null?void 0:i.id},r=()=>this.loadProfileConfig().then(()=>t());return n(this.state)&&r(),this.subscribe(n,s=>{s&&r()})}overlayContainerFactory(t,n,r,o){let[s,i]=du(n,r);return s.setAttribute("translate","no"),s.dataset.testid=t,o&&s.classList.add(o),[s,i]}createInlineContainer(t,n){var a;let r=document.createElement("div");r.style.position="absolute",r.style.top="0px",r.style.left="0px",r.style.height="0px",r.style.width="0px";let o=document.createElement("div");o.style.display="none",o.style.position="absolute",o.style.height="0px",o.style.width="0px",o.style.backgroundColor="red",r.appendChild(o);let s=(a=t.ownerDocument.defaultView)==null?void 0:a.frameElement,i=s?s.ownerDocument.defaultView:null;if(s&&(i===window||(i==null?void 0:i.parent)===window)){let[l,c]=du(s,{appendTo:document.body,onMoveStart:()=>{o.style.display="none"}});l.dataset.testid=n,l.style.zIndex="2",l.appendChild(r),this.unmountHandlers.push(()=>{c()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return ti(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),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),ee.info(`Stored analytics for ${this.conversationId()}`)}catch(t){}}restoreMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=window.sessionStorage.getItem(t);if(!n)return;let r=JSON.parse(n);r.text.trim()===this.state.input.text.trim()?(ee.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(U1(r.metrics))):ee.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(t)}catch(t){}}mount(t,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!pm(t))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let d=n,{customStyles:r,closestScrollSelector:o,floatingMenuParent:s,appendOverlayTo:i,inputMediator:a}=d,l=re(d,["customStyles","closestScrollSelector","floatingMenuParent","appendOverlayTo","inputMediator"]),c={customStyles:r,closestScrollSelector:o,floatingMenuParent:s,appendOverlayTo:i};this.configure(l),this.settings.automaticHandlingTime&&this.setupHandlingTime(t),ti(t),this.inputMediator=a||(ni(t)?new ui(t):new ci(t)),this.inputMediator.on("change",({plainText:p,rawHTML:g})=>{this.store.dispatch(bf({text:p,html:g}))}),this.inputMediator.on("keyup",p=>{this.store.dispatch(F1(Cy(p)))}),this.inputMediator.on("keydown",p=>{this.handleKeyDown(p)}),this.inputMediator.on("paste",({pastedText:p,selectionText:g})=>{this.store.dispatch(z1({text:p,selectionText:g}))}),this.inputMediator.on("cut",({selectionText:p})=>{this.store.dispatch(_1(p))});let u;this.inputMediator.on("selection",p=>{clearTimeout(u),p===null?u=setTimeout(()=>{p!==null&&this.store.dispatch(Ef(p))},500):this.store.dispatch(Ef(p))}),this.unmountHandlers.push(()=>{clearTimeout(u)}),this.inputMediator.on("disabled",()=>{var p;(p=this.inputMediator)==null||p.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{this.settings.detectSubmit&&this.notifySubmit()}),this.inputMediator.on("blur",()=>{this.store.dispatch(Tp(!1))}),this.inputMediator.on("focus",()=>{this.store.dispatch(Tp(!0))}),this.renderSuggestions(t,c),this.subscribe($l("inlineSuggestions"),()=>{this.renderSuggestions(t,c)});let f=this.renderOverlays(n);this.unmountHandlers.push(()=>{f.unmount()}),this.store.dispatch(bf({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()})),this.store.dispatch(Ef(this.inputMediator.getSelection())),this.store.dispatch(Tp(this.inputMediator.isFocused)),this.unmountHandlers.push(()=>{this.state.input.text!==""&&this.storeMetrics()}),this.whenConversationLoaded(()=>{this.restoreMetrics(),this.syncInputMediator(),this.refreshTextSuggestions()}),this.isMounted=!0}subscribe(t,n){let r=t(this.store.getState());return this.store.subscribe(()=>{let o=t(this.store.getState());o!==r&&(r=o,n(r))})}unmount(){var t,n,r,o,s;(t=this.inlineSuggestions)==null||t.unmount(),(n=this.aboveSuggestions)==null||n.unmount(),(r=this.belowSuggestions)==null||r.unmount(),(o=this.floatingMenu)==null||o.unmount(),this.unmountHandlers.forEach(i=>i()),this.unmountHandlers=[],(s=this.inputMediator)==null||s.dispose(),this.isMounted=!1}dispose(){this.unmount(),this.unmountWidget(),this.disposeHandlers.forEach(t=>t()),this.disposeHandlers=[],this.off()}renderSuggestions(t,n){var r,o,s,i;(r=this.floatingMenu)==null||r.unmount(),(o=this.inlineSuggestions)==null||o.unmount(),(s=this.aboveSuggestions)==null||s.unmount(),(i=this.belowSuggestions)==null||i.unmount(),this.settings.floatingMenu&&(this.floatingMenu=this.renderFloatingMenu(t,n)),this.settings.inlineSuggestions||this.settings.suggestionsPlacement==="inline"?this.inlineSuggestions=this.renderInlineSuggestions(t,n):this.settings.suggestionsPlacement==="below"?this.belowSuggestions=this.renderAboveOrBelowSuggestions(t,n,"below"):this.aboveSuggestions=this.renderAboveOrBelowSuggestions(t,n,"above")}renderInlineSuggestions(t,n){let{customStyles:r}=n,o=this.createInlineContainer(t,"deepdesk-caret"),s=(0,us.createRoot)(o);s.render((0,Ie.jsx)(os,{store:this.store,customStyles:r,children:(0,Ie.jsx)(Yo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(oR,{})})}));let i=a=>{a?(o.style.display="block",o.style.top=`${a.top}px`,o.style.left=`${a.left}px`):o.style.display="none"};return this.inputMediator.on("caretposition",i),{unmount:()=>{var a;(a=this.inputMediator)==null||a.off("caretposition",i),s.unmount(),o.remove()}}}renderAboveOrBelowSuggestions(t,n,r){let{customStyles:o,closestScrollSelector:s,appendOverlayTo:i}=n,a=s&&B0(t,s)||void 0,[l,c]=this.overlayContainerFactory("deepdesk-tab-completion",a||t,{appendTo:i,closestScrollElement:a,mirrorOverflow:!0,onRemove:()=>this.unmount()},o==null?void 0:o.rootNode),[u,f]=this.overlayContainerFactory("deepdesk-suggestions-overlay",a||t,{appendTo:i,placement:r},o==null?void 0:o.suggestionsRootNode),d=(0,us.createRoot)(l);d.render((0,Ie.jsx)(os,{store:this.store,customStyles:o,children:(0,Ie.jsx)(Yo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(NR,{inputElement:t})})}));let p=(0,us.createRoot)(u);return p.render((0,Ie.jsx)(os,{store:this.store,customStyles:o,children:(0,Ie.jsx)(Yo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(pR,{onLogIn:()=>this.loginViaPopup().catch(g=>ee.warn(g.message))})})})),{unmount(){d.unmount(),p.unmount(),c(),f()}}}renderFloatingMenu(t,n){let{customStyles:r,closestScrollSelector:o,appendOverlayTo:s,floatingMenuParent:i}=n,a=o&&B0(t,o)||void 0,[l,c]=this.overlayContainerFactory("floating-menu",a||t,{appendTo:i!=null?i:s},r==null?void 0:r.floatingMenuParent),u=(0,us.createRoot)(l);return u.render((0,Ie.jsx)(os,{store:this.store,customStyles:r,children:(0,Ie.jsx)(Yo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(jk,{onLogIn:()=>this.loginViaPopup().catch(f=>ee.warn(f.message))})})})),{unmount(){u.unmount(),c()}}}renderOverlays(t){let{customStyles:n}=t,r=this.createContainer("deepdesk-overlays"),o=(0,us.createRoot)(r);return o.render((0,Ie.jsx)(os,{store:this.store,customStyles:n,children:(0,Ie.jsx)(Yo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(Hk,{})})})),{unmount(){o.unmount(),r.remove()}}}renderWidget(t,n={}){if(this.widgetElement&&ee.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,isEmbedded:s}=n;this.widgetElement=t,this.configure({showImages:o,isEmbedded:s}),this.widgetRoot=(0,us.createRoot)(t),this.widgetRoot.render((0,Ie.jsx)(os,{store:this.store,customStyles:r,children:(0,Ie.jsx)(Yo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(tI,{assistantOptions:n.assistantOptions,knowledgeAssistOptions:n.knowledgeAssist,onLogIn:()=>this.loginViaPopup().catch(i=>ee.warn(i.message))})})}))}unmountWidget(){var t,n;(n=(t=this.widgetRoot)==null?void 0:t.unmount)==null||n.call(t),this.widgetRoot=null,this.widgetElement=null}renderKnowledgeAssistantWidget(t,n,r={}){let{customStyles:o,initialQuestion:s}=r,i=(0,us.createRoot)(n);return i.render((0,Ie.jsx)(os,{store:this.store,customStyles:o,children:(0,Ie.jsx)(Yo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(A0,{children:(0,Ie.jsxs)(im,{assistantCode:t,initialQuestion:s,evaluateKnowledgeAssistFn:r.isLegacyKnowledgeAssist?Gc:qc,children:[(0,Ie.jsx)(xi,{children:(0,Ie.jsx)(lm,{title:r.title,emptyState:r.emptyState})}),(0,Ie.jsx)(I0,{children:(0,Ie.jsx)(am,{})})]})})})})),{unmount(){i.unmount()}}}setupHandlingTime(t){let n=hm(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){CI(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(()=>A(this,null,function*(){yield this.store.dispatch(uc());let t=Hs(this.state);t&&this.store.dispatch(mf({showSearch:t.search,showImageSearch:t.imageSearch,showEntitiesCommand:t.entitiesCommand,showSummaryCommand:!!t.summarizerAssistantNew,showKnowledgeSearch:!!t.knowledgeAssistantNew||!!t.knowledgeAssistant,recommendTextSuggestions:t.recommendTextSuggestions}))})),this.loadProfileConfigPromise)}loginViaPopup(t){return A(this,null,function*(){return new Promise((n,r)=>{let o=new MessageChannel,s=o.port1,i=this.settings.adminUrl,a=new URL(t!=null&&t.url?t==null?void 0:t.url:`${i}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let l=!1,c=()=>{u&&!u.closed&&u.close(),window.removeEventListener("message",f),clearInterval(d)};s.onmessage=p=>A(this,null,function*(){var g,m;if((g=p.data)!=null&&g.jwt)try{yield this.deepdeskApi.exchangeTokenForAccessCookie((m=p.data)==null?void 0:m.jwt),yield this.isLoggedIn(),this.broadcastEvents.send(Yl),l=!0,o.port1.close(),n()}catch(x){console.error(x),r(x)}finally{l=!0,c()}});let u=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");u===null&&r(new Error("Popup blocked by browser"));let f=p=>A(this,null,function*(){var g;if(p.origin===a.origin)switch((g=p.data)==null?void 0:g.type){case"deepdesk-popup-loaded":{try{let m=JSON.stringify({type:"deepdesk-popup-create-channel"});u==null||u.postMessage(m,a.origin,[o.port2])}catch(m){ee.error("Error posting message to popup",m),r(m)}break}case"deepdesk-popup-error":{c(),p.data.message==="Timeout"&&ee.warn("Popup timed out. Check if the account's platform url is configured correctly."),r(new Error(p.data.message));break}}});window.addEventListener("message",f);let d=setInterval(()=>{u&&!u.closed||(c(),l||r(new Error("Popup closed by user")))},200);this.disposeHandlers.push(c)})})}translateMessages(t){return this.deepdeskApi.translateMessages(t)}refreshTextSuggestions(){return A(this,null,function*(){this.isMounted&&(yield this.store.dispatch(wp()))})}refreshWidgetSuggestions(){return A(this,null,function*(){if(!this.widgetRoot)return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=dc(this.state);try{n.forEach(({type:r})=>{switch(r){case"entities":this.store.dispatch(lr());break;case"pinned-messages":case"sticky-messages":break;default:Ou.includes(r)||this.store.dispatch(cr(r))}})}catch(r){this.handleError(r)}})}};Ba.version="18.1.2-beta.8",Ba.count=0;var pu=Ba;function s5(e){return A(this,null,function*(){var o,s,i;let n=yield((o=e.fetch)!=null?o:window.fetch)(e.url),r=yield n.blob();return new File([r],e.name,{type:(i=(s=e.mimeType)!=null?s:n.headers.get("Content-Type"))!=null?i:"image/jpeg"})})}function HI(e,t){return A(this,null,function*(){let n=yield s5(t),r=new Event("change",{bubbles:!0,cancelable:!0});try{Object.defineProperty(e,"files",{configurable:!0,get:()=>[n]}),e.dispatchEvent(r)}finally{Object.hasOwn(e,"files")&&delete e.files}})}function BI(e,t,n){return A(this,null,function*(){yield new xo(e).authenticateWithKey(t,n)})}function UI(e){return e.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}function VI(r,o){return A(this,arguments,function*(e,t,n={}){var f,d;let{value:s}=e,{start:i,end:a}=(f=n.replace)!=null?f:{start:0,end:s.length},l=`${s.slice(0,i)}${t}${s.slice(a)}`,c=(d=n.selectionAfter)!=null?d:{start:i+t.length,end:i+t.length},u=()=>{if(n.setValue)return n.setValue(l);e.value=l};return Promise.resolve(u()).then(()=>{e.selectionStart=c.start,e.selectionEnd=c.end,e.blur(),e.focus()})})}function $I(r,o){return A(this,arguments,function*(e,t,n={}){let s=n.replace?ls(e,n.replace.start,n.replace.end):Da(e),i,a=()=>{if(n.setRange)return n.setRange(s.cloneRange());s.deleteContents(),i=document.createElement("span"),s.insertNode(i),n.insertBRs!==!1?t.split(`
82
+ `);let g=d?r:0,m=p?Math.min(s,u.childNodes.length):u.childNodes.length;for(let x=g;x<m&&(c(u.childNodes[x]),a!==2);x++);break}default:break}p&&(a=2)}return c(e),l}var rI=(i=>(i.CUT="Cut",i.BACKSPACE="Backspace",i.DELETE="Delete",i.ERASEEOF="EraseEof",i.UNDO="Undo",i.CLEAR="Clear",i))(rI||{}),vo=class{constructor(t){this.element=t;this.isFocused=!1;this.isActive=!0;this.isDisposed=!1;this.eventListeners={};this.disposeHandlers=[];this.cachedText="";this.cachedCaretPosition=null;this.cachedSelection={start:0,end:0};this.cachedHTML="";this.isSubmitting=!1;this.isPossibleClearInputAction=!1;this.cachedText=this.getText(),this.cachedHTML=this.getHTML(),this.cachedSelection=this.getSelection(),this.listen()}addEventListener(t,n){let r=o=>{n(o)};this.element.addEventListener(t,r),this.disposeHandlers.push(()=>{this.element.removeEventListener(t,r)})}removeEventListener(t,n){this.element.removeEventListener(t,n)}handleInteraction(){let t=this.getText(),n=this.getHTML(),r=this.getSelection(),o=this.cachedCaretPosition===null;if(!this.isActive||(t===""&&this.cachedText!==""&&!this.isPossibleClearInputAction&&this.emit("submit"),t!==this.cachedText?(this.cachedText=t,this.cachedHTML=n,o=!0,this.emit("change",{plainText:t,rawHTML:n})):n!==null&&n!==this.cachedHTML&&(this.cachedHTML=n,o=!0,this.emit("change",{plainText:t,rawHTML:n})),(r.start!==this.cachedSelection.start||r.end!==this.cachedSelection.end)&&(this.cachedSelection=r,o=!0,this.emit("selection",r)),!o))return;let s=this.getCaretPosition();Ko(s,this.cachedCaretPosition)||(this.cachedCaretPosition=s,this.emit("caretposition",s))}handleClick(){this.handleInteraction()}handleFocus(){let t=!this.isFocused;this.isFocused=!0,t&&this.emit("focus"),this.handleInteraction()}handleBlur(){this.isPossibleClearInputAction=!1;let t=this.isFocused;this.isFocused=!1,t&&this.emit("blur")}handleKeyDown(t){let{key:n,ctrlKey:r,metaKey:o}=t;this.isPossibleClearInputAction=Object.values(rI).includes(n)||n.toLowerCase()==="z"&&(r||o),this.emit("keydown",t)}handleKeyUp(t){this.handleInteraction(),this.emit("keyup",t)}handleCut(){this.isPossibleClearInputAction=!0,this.emit("cut",{selectionText:this.getSelectedText()})}handlePaste(t){var r,o;let n=((r=t.clipboardData)==null?void 0:r.getData("text"))||((o=t.clipboardData)==null?void 0:o.getData("text/plain"))||"";this.emit("paste",{pastedText:n,selectionText:this.getSelectedText()})}listen(){this.addEventListener("keydown",n=>this.handleKeyDown(n)),this.addEventListener("keyup",n=>this.handleKeyUp(n)),this.addEventListener("input",()=>this.handleInteraction()),this.addEventListener("change",()=>this.handleInteraction()),this.addEventListener("focus",()=>this.handleFocus()),this.addEventListener("blur",()=>this.handleBlur()),this.addEventListener("cut",()=>this.handleCut()),this.addEventListener("paste",n=>this.handlePaste(n)),this.addEventListener("click",()=>this.handleInteraction()),document.activeElement===this.element&&(this.isFocused=!0);let t=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});t.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{t.disconnect()})}focus(){this.element.focus()}emit(t,...n){this.isDisposed||this.eventListeners[t]&&this.eventListeners[t].forEach(r=>{r(...n)})}on(t,n){this.isDisposed||(this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n))}off(t,n){if(!this.eventListeners[t])return;let r=this.eventListeners[t].indexOf(n);r!==-1&&this.eventListeners[t].splice(r,1)}activate(){let t=this.isActive===!1;this.isActive=!0,t&&this.handleInteraction()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(t=>t()),this.eventListeners={},this.isDisposed=!0}};function oI(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var ci=class extends vo{constructor(){super(...arguments);this.lastKnownSelection=null}getRootNode(){return this.element.getRootNode()}getText(){let n=new Range;return n.selectNodeContents(this.element),uu(this.element,n)}getHTML(){return this.element.innerHTML||""}getRange(){var i;let n=this.getRootNode();if(n.activeElement!==this.element)return null;let r="getSelection"in n?n.getSelection():window.getSelection();if(!r)return null;let o="getComposedRanges"in r&&n instanceof ShadowRoot?(i=r.getComposedRanges(n))==null?void 0:i[0]:r.rangeCount>0?r.getRangeAt(0):null;if(!o)return null;let s=this.element.ownerDocument.createRange();return s.setStart(o==null?void 0:o.startContainer,o==null?void 0:o.startOffset),s.setEnd(o==null?void 0:o.endContainer,o==null?void 0:o.endOffset),!s||!this.element.contains(s.startContainer)||!this.element.contains(s.endContainer)?null:s}getCaretPosition(){let n=this.getRange();if(!n||!n.collapsed||!("getBoundingClientRect"in n))return null;let r=n.getBoundingClientRect();return!oI(r)&&(n.insertNode(this.element.ownerDocument.createTextNode("\u2060")),r=n.getBoundingClientRect(),n.deleteContents(),!oI(r))?null:{top:r.top+r.height,left:r.left}}getSelection(){let n=this.getRange();if(n)return cu(this.element,n);let r=this.lastKnownSelection;if(r&&nI(this.element,r.start,r.end))return r;let o=Da(this.element);return o.collapse(!1),cu(this.element,o)}getSelectedText(){let{start:n,end:r}=this.getSelection();return uu(this.element,ls(this.element,n,r))}listen(){super.listen();let n=new MutationObserver(s=>{var i,a;s.length===2&&s[0].addedNodes.length===1&&((i=s[0].addedNodes[0])==null?void 0:i.textContent)==="\u2060"&&((a=s[1].removedNodes[0])==null?void 0:a.textContent)==="\u2060"||setTimeout(()=>{this.handleInteraction()},0)});n.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0}),this.disposeHandlers.push(()=>n.disconnect());let r=this.element.isContentEditable,o=new MutationObserver(()=>{this.element.isContentEditable!==r&&(r=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>o.disconnect())}};var VF=["direction","boxSizing","width","height","overflowX","overflowY","borderTopWidth","borderRightWidth","borderBottomWidth","borderLeftWidth","borderStyle","paddingTop","paddingRight","paddingBottom","paddingLeft","fontStyle","fontVariant","fontWeight","fontStretch","fontSize","fontSizeAdjust","lineHeight","fontFamily","textAlign","textTransform","textIndent","textDecoration","letterSpacing","wordSpacing","tabSize"];function sI(e,t){let n="mozInnerScreenX"in window,r=document.createElement("div");r.id="input-textarea-caret-position-mirror-div";let o=r.style,s=window.getComputedStyle(e),i=e.ownerDocument.body;o.whiteSpace="pre-wrap",o.wordWrap="break-word",o.position="absolute",o.visibility="hidden",VF.forEach(u=>{o[u]=s[u]}),n?e.scrollHeight>Number.parseInt(s.height)&&(o.overflowY="scroll"):o.overflow="hidden",r.textContent=e.value.substring(0,t);let a=document.createElement("span");a.textContent=e.value.substring(t)||".",r.appendChild(a),i.appendChild(r);let l=e.getBoundingClientRect(),c={top:l.top-e.scrollTop+a.offsetTop+Number.parseInt(s.borderTopWidth)+a.offsetHeight,left:l.left-e.scrollLeft+a.offsetLeft+Number.parseInt(s.borderLeftWidth)};return i.removeChild(r),c}var ui=class extends vo{constructor(){super(...arguments);this.lastKnownSelection=null}getText(){return this.element.value}getHTML(){return null}getSelection(){let{selectionStart:n,selectionEnd:r}=this.element;return{start:n,end:r}}getSelectedText(){let n=this.getSelection();return n?this.getText().slice(n.start,n.end):""}getCaretPosition(){return sI(this.element,this.element.selectionEnd)}listen(){super.listen();let n=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var s;return(s=n==null?void 0:n.get)==null?void 0:s.call(this.element)},set:s=>{var i;(i=n==null?void 0:n.set)==null||i.call(this.element,s),this.handleInteraction()}}),this.addEventListener("scroll",()=>{this.emit("caretposition",this.getCaretPosition())});let r=this.element.disabled,o=new MutationObserver(()=>{this.element.disabled!==r&&(r=this.element.disabled,this.emit(r?"disabled":"enabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>o.disconnect())}};function iI(e,t,n){let r=`deepdesk-iframe-${e}`,o=document.getElementById(r);if(o)return o;let s=document.createElement("iframe"),i=new URL(t);return Object.entries(n).forEach(([a,l])=>{i.searchParams.append(a,l)}),s.style.position="absolute",s.style.left="-999em",s.style.width="0px",s.style.height="0px",s.tabIndex=-1,s.id=r,s.title=`iframe-${e}`,s.src=i.toString(),window.document.body.appendChild(s),s}function $F(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch(t){return e}}var L0=class{constructor(t){this.name=t;this.disposeHandlers=[];this.broadcastChannel=new BroadcastChannel(t)}onMessage(t){this.broadcastChannel.addEventListener("message",t),this.disposeHandlers.push(()=>{this.broadcastChannel.removeEventListener("message",t)})}postMessage(t){this.broadcastChannel.postMessage(JSON.stringify(t))}close(){this.disposeHandlers.forEach(t=>t()),this.broadcastChannel.close()}},M0=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.disposeHandlers=[];this.iframe=iI(t,`${this.targetOrigin}/sdk/proxy/proxy.html`,{channel:this.name,host:window.location.origin,debug:"1"}),document.body.appendChild(this.iframe)}onMessage(t){window.addEventListener("message",t),this.disposeHandlers.push(()=>{window.removeEventListener("message",t)})}postMessage(t){var n;(n=this.iframe.contentWindow)==null||n.postMessage(JSON.stringify(t),this.targetOrigin)}close(){var t;this.disposeHandlers.forEach(n=>n()),(t=this.iframe)==null||t.remove()}},O0=class{constructor(t){this.params=t;this.deepdeskUrl=t.deepdeskUrl,this.eventMap=t.eventMap,this.externalId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setExternalId(t){this.externalId!==t&&(this.cleanup(),ee.info("Set externalId",t),this.externalId=t,this.channel=this.createChannel(t))}createChannel(t){let n=this.params.createCustomChannel?this.params.createCustomChannel(t):this.isCrossOrigin?new M0(t,this.deepdeskUrl,{debug:!0}):new L0(t),r=o=>{var i,a;if(o.origin!==this.deepdeskUrl)return;let s=$F(o.data);typeof s!="object"||s.type!=="event"||s.channel!==t||(ee.info("Received broadcast event",this.externalId,o),(a=(i=this.eventMap)[s.name])==null||a.call(i,s.payload))};return n.onMessage(r),n}send(t,n,r){var i,a;ee.info("Broadcast event",{externalId:this.externalId,name:t,payload:n});let o={type:"event",name:t,payload:n};r!==!1&&((a=(i=this.eventMap)[t])==null||a.call(i,n));let s=this.externalId==="deepdesk-general"?this.defaultChannel:this.channel;s==null||s.postMessage(P(w({},o),{channel:this.externalId}))}cleanup(t=!1){var n,r;(n=this.channel)==null||n.close(),this.channel=void 0,t&&((r=this.defaultChannel)==null||r.close(),this.defaultChannel=void 0)}},aI=O0;function jF(e){return e.replace(/(_\w)/g,t=>t[1].toUpperCase())}function _e(e){return Array.isArray(e)?e.map(_e):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>P(w({},t),{[jF(n)]:_e(e[n])}),{}):e}function WF(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function Nt(e){return Array.isArray(e)?e.map(Nt):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>P(w({},t),{[WF(n)]:Nt(e[n])}),{}):e}var Fa=class extends Error{constructor(n,r){super(n);this.body=r;this.name="CustomError"}};var N0=e=>new Promise(t=>{setTimeout(t,e)});var za=class extends Fa{constructor(){super(...arguments);this.name="ClientError"}},D0=class extends Fa{constructor(){super(...arguments);this.name="ServerError"}},_0=new Map;function KF(e){return A(this,null,function*(){if(e.status===204)return e.text().catch(()=>{}),null;let t=e.headers.get("content-type");if(t!=null&&t.includes("application/json"))return e.json();let n=yield e.text();return n===""?null:(ee.warn("Unexpected response body:",n.slice(0,20)),JSON.parse(n))})}var cs=class cs{constructor(t="",n={}){this.baseUrl=t;this.options=n;this.latestRequestByUrl={};var r;this.fetch=(r=n.fetch)!=null?r:window.fetch.bind(window)}patchFetch(t){this.fetch=t(this.fetch)}setCsrfToken(t){this.csrfToken=t}request(t,n={}){return new Promise((r,o)=>{let s={isAborted:!1,reject:o},i=`${this.baseUrl}${t}`,a=this.fetch,l=n.method===void 0||n.method.toLowerCase()==="get",k=n,{useCache:c=!1,abortLatest:u=!1,attempts:f=1,retryDelay:d=500,refreshTokenOn401:p=!0,retryOnError:g=C=>C instanceof TypeError,retryOnResponse:m=C=>C.status>=500,version:x=null}=k,v=re(k,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]);if(c){if(!l)throw new Error(`Can't use 'useCache' for ${n.method}`);if(_0.has(i)){r(_0.get(i));return}}let y=P(w({credentials:"include"},v),{headers:w({Accept:"application/json","Content-Type":"application/json"},v.headers)});!l&&this.csrfToken&&(y.headers=P(w({},y.headers),{"X-CSRFToken":this.csrfToken})),typeof x=="string"&&(y.headers=P(w({},y.headers),{"X-Deepdesk-API-Version":x}));let h=f,S=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[i]&&u&&(this.latestRequestByUrl[i].isAborted=!0,this.latestRequestByUrl[i].reject(new Error("Aborted"))),this.latestRequestByUrl[i]=s;let E=()=>A(this,null,function*(){return h--,a(i,y).then(C=>A(this,null,function*(){return m(C)&&!s.isAborted&&h>0?(yield N0(d),E()):C.status===401&&p===!0&&S===!1?(S=!0,yield this.refreshToken(),E()):C})).catch(C=>A(this,null,function*(){if(g(C)&&!s.isAborted&&h>0)return yield N0(d),E();throw C}))});E().then(C=>A(this,null,function*(){let I=yield KF(C);if(delete this.latestRequestByUrl[i],C.status>=500){o(new D0("Server Error",I));return}if(C.status===401){o(new za("Unauthorized",I));return}if(C.status===403){o(new za("Forbidden",I));return}if(C.status===404){o(new za("Not Found",I));return}if(C.status>=400){o(new za("Bad Request",I));return}c&&_0.set(i,I),r(I)})).catch(C=>{o(C)})})}validateToken(){return A(this,null,function*(){let{has_valid_access_token:t,is_logged_in:n}=yield this.get("/apis/admin/session/validate/");if(!t)try{yield this.refreshToken();let{is_logged_in:r}=yield this.get("/apis/admin/session/validate/");return r}catch(r){return!1}return n})}refreshToken(){return cs.refreshingToken||(cs.refreshingToken=this.get("/apis/admin/session/refresh/",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{cs.refreshingToken=null},1e3*60)})),cs.refreshingToken}get(t,n){return this.request(t,n)}post(t,n,r){return this.request(t,w({method:"POST",body:JSON.stringify(n)},r))}patch(t,n,r){return this.request(t,w({method:"PATCH",body:JSON.stringify(n)},r))}put(t,n,r){return this.request(t,w({method:"PUT",body:JSON.stringify(n)},r))}delete(t,n){return this.request(t,w({method:"DELETE"},n))}};cs.refreshingToken=null;var di=cs;var lI;(t=>{let e;(a=>(a.SUCCESS="success",a.FAILURE="failure",a.CONDITIONS_NOT_MET="conditions_not_met",a.MAX_RECURSION_LEVEL="max_recursion_level",a.NO_ACCESS_TO_ASSISTANT="no_access_to_assistant"))(e=t.EvaluationStatus||(t.EvaluationStatus={}))})(lI||(lI={}));function F0(e){return P(w({},_e(e)),{metadata:e.metadata})}var fi=class fi{constructor(t,n={}){this.options=n;this.latestReceivedDeepdeskVersions={};this.shouldFetchCsrfToken=!0;this.client=new di(t,{fetch:n.fetch}),this.client.patchFetch(r=>(o,s)=>A(this,null,function*(){let i=yield r(o,s);return this.handleDeepdeskVersionHeaders(i),i}))}preflight(){return A(this,null,function*(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let t=yield this.getCsrfToken();this.client.setCsrfToken(t)}return this.options.token?(fi.exchangeTokenPromise||(fi.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),fi.exchangeTokenPromise):Promise.resolve()})}createConversation(t){return A(this,null,function*(){var r;yield this.preflight(),ee.info(`Creating conversation for session ${t.externalId} and agent ${t.agentId}`);let n=yield this.client.post("/api/v2/conversations",P(w({chat_start_time:new Date().toISOString()},Nt(t)),{metadata:(r=t.metadata)!=null?r:{}}));return F0(n)})}getMe(){return A(this,null,function*(){let t=yield this.client.get("/apis/admin/session/me/");return _e(t)})}postIdentity(t){return A(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/me/identities/",Nt(t))})}patchMe(t){return A(this,null,function*(){yield this.preflight();let n=yield this.client.patch("/apis/admin/session/me/",Nt(t));return _e(n)})}getProfile(t){return A(this,null,function*(){let n=yield this.client.get(`/apis/admin/profiles/${t}/`,{useCache:!0});return _e(n)})}getKnowledgeAssistant(t){return A(this,null,function*(){let n=yield this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{useCache:!0});return _e(n)})}getContentTypes(){return A(this,null,function*(){let t=yield this.client.get("/apis/admin/content-types/",{useCache:!0});return _e(t)})}getAccount(){return A(this,null,function*(){let t=yield this.client.get("/apis/admin/account/",{useCache:!0});return _e(t)})}getPlatformConfig(t){return A(this,null,function*(){let n=t!==void 0?`/platform/config/${t}/`:"/platform/config/",{config:r}=yield this.client.get(n,{useCache:!0});return _e(r)})}checkUserExists(t){return A(this,null,function*(){let{exists:n}=yield this.client.get(`/apis/admin/users/exists?external_id=${t}`,{version:"v1"});return n})}getConversationByExternalId(r){return A(this,arguments,function*(t,n={}){yield this.preflight(),ee.info(`Getting conversation for session ${t}`);let{attempts:o=1,retryDelay:s=1e3}=n,i=yield this.client.get(`/api/v2/conversations/by_external_id/${t}`,{attempts:o,retryDelay:s,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"});return ee.info(`Successfully retrieved conversation ${i.id} for session ${t}`),F0(i)})}isConversationSupported(r){return A(this,arguments,function*(t,n={}){ee.info(`Check if conversation for session ${t} is supported`);let{attempts:o=1,retryDelay:s=1e3}=n;return(yield this.client.get(`/api/v2/conversations/by_external_id/${t}/has_active_profile`,{attempts:o,retryDelay:s,retryOnResponse:a=>a.status===404||a.status>=500})).has_active_profile})}updateConversation(t,n){return A(this,null,function*(){var s;yield this.preflight();let r=Nt(n);n.metadata&&(r.metadata=(s=n.metadata)!=null?s:{});let o=yield this.client.put(`/api/v2/conversations/${t}`,r);return F0(o)})}postMessages(t,n){return A(this,null,function*(){yield this.preflight(),yield this.client.post(`/api/v2/conversations/${t}/messages`,n.map(r=>P(w({},Nt(r)),{metadata:r.metadata})))})}sendEvent(t,n){return A(this,null,function*(){yield this.preflight();let a=n,{data:r}=a,o=re(a,["data"]),s=Object.entries(this.latestReceivedDeepdeskVersions).reduce((l,[c,u])=>P(w({},l),{[c]:u}),{}),i=["platform","agentId","agentName","agentEmail","conversationId"].reduce((l,c)=>(o[c]&&(l[c]=o[c]),l),{});return this.client.post("/api/v2/events",Nt(P(w(w({},s),i),{data:r,name:t})),{version:"v2"})})}getEntities(t){return A(this,null,function*(){return yield this.preflight(),yield this.client.post("/api/v2/entities",{messages:t.filter(r=>r.text)})})}getTemporaryExchangeToken(){return A(this,null,function*(){return(yield this.client.get("/apis/admin/session/exchange-token/")).jwt})}exchangeTokenForAccessCookie(t){return A(this,null,function*(){return this.client.post("/apis/admin/session/jwt/",{jwt:t}).catch(n=>{throw ee.warn(`Invalid token '${t}'`),n})})}authenticateWithKey(t,n){return A(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/api-key/",Nt(n),{refreshTokenOn401:!1,headers:{apikey:t}})})}getTextSuggestions(o){return A(this,arguments,function*(t,n={},r){if(yield this.preflight(),r==="sticky-messages")throw new Error("Use getPinnedMessages instead");return(yield this.client.post(`/api/v2/conversations/${t}/recommend/${r}`,Nt(n),{abortLatest:!0})).map(i=>P(w({},_e(i)),{text:i.text||i.url||i.message,source:r,type:r})).filter((i,a,l)=>a===l.findIndex(c=>c.text===i.text))})}isLoggedIn(){return A(this,null,function*(){return yield this.preflight(),this.client.validateToken()})}getAutocompleteSuggestions(t,n){return A(this,null,function*(){return yield this.preflight(),(yield this.client.post(`/api/v2/conversations/${t}/autocomplete`,Nt(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,s,i)=>s===i.findIndex(a=>a.text===o.text))})}getPinnedMessages(t){return A(this,null,function*(){let n=yield this.client.get(`/api/v2/profiles/${t}/pinned-messages`,{abortLatest:!0});return _e(n).map(r=>P(w({},r),{text:r.message,source:"sticky-messages",type:"pinned-message"}))})}getStyleSuggestions(t){return A(this,null,function*(){let n=yield this.client.post("/api/v2/style-suggestions",Nt(t),{abortLatest:!0,version:"v2"});return _e(n)})}search(t){return A(this,null,function*(){let n=yield this.client.post(`/api/v2/profiles/${t.profile}/search`,Nt(t));return _e(n)})}knowledgeAssist(s,i,a){return A(this,arguments,function*(t,n,r,o={}){yield this.preflight();let l=yield this.client.post(`/api/knowledge-assist/assistants/${r}/search`,Nt({question:t.question,doNotKnowAnswer:t.doNotKnowAnswer,customerInstruction:t.customerInstruction,chatHistory:n.map(c=>({question:c.question,answer:c.answer.answer})),agentId:o.agentId,conversationId:o.conversationId}),{version:"v2"});return _e(l)})}requestLoginByEmail(t){return A(this,null,function*(){yield this.preflight();let n=yield this.client.post("/apis/admin/session/passwordless/request/",{email:t});return _e(n)})}requestPasswordlessToken(){return A(this,null,function*(){let t=yield this.client.get("/apis/admin/session/passwordless/request/");return _e(t.token)})}getCsrfToken(){return A(this,null,function*(){let{token:t}=yield this.client.get("/apis/admin/session/csrf/");return t})}verifyLoginToken(t){return A(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/login/",{token:t});return _e(n)})}getSummary(r){return A(this,arguments,function*(t,n={}){yield this.preflight();let o=yield this.client.post("/api/summary",{conversation:{messages:t.filter(s=>s.text&&s.source),agent_id:n.agentId,id:n.externalConversationId},prompt_instruction:n.promptInstruction,model:n.model},{version:"v1"});return _e(o)})}evaluateAssistant(t,n){return A(this,null,function*(){var a;yield this.preflight();let r=new URLSearchParams,{expectFormat:o="text"}=n||{};if(o.startsWith("json-schema:")){let l=o.replace("json-schema:","");r.append("expect_response_format","json-schema"),r.append("expect_response_format_schema",l)}else r.append("expect_response_format",o);n!=null&&n.externalConversationId&&r.append("external_conversation_id",n.externalConversationId);let s=n!=null&&n.threadId?`/api/v2/assistants/${t}/threads/${n==null?void 0:n.threadId}/evaluate?${r.toString()}`:`/api/v2/assistants/${t}/evaluate?${r.toString()}`,i=yield this.client.post(s,{input:(a=n==null?void 0:n.input)!=null?a:{},conversation:n==null?void 0:n.transcript});return _e(i)})}createAssistantThread(t){return A(this,null,function*(){yield this.preflight();let{assistantCode:n}=t,r=yield this.client.post(`/apis/admin/assistants/${n}/threads/`,{});return _e(r)})}postMessageToAssistantThread(t){return A(this,null,function*(){yield this.preflight();let{assistantCode:n,threadId:r,message:o}=t,s=yield this.client.post(`/apis/admin/assistants/${n}/threads/${r}/messages/`,{content:o,role:"user"});return _e(s)})}translateMessages(t){return A(this,null,function*(){yield this.preflight();let n=yield this.client.post("/api/v2/translate",Nt(t));return _e(n)})}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),s=o.match(Gx);if(!n||!s)return;let i=s[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[i];a&&n&&a!==n&&ee.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[i]=n})}};fi.exchangeTokenPromise=null;var xo=fi;var cI={startTime:null,stopTime:null},uI=e=>e.handlingTime,dI=Ee({name:"handlingTime",initialState:cI,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(at,()=>cI)}}),{handlingTimeStart:fI,handlingTimeStop:dm,handlingTimeReset:pI}=dI.actions,mI=dI.reducer;var gI=(e={})=>{let t=w({onAuthError:Ji(!1)},e);return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var fm={list:{keywordMatches:[]},fetchState:"idle"};var pi=fe("styleSuggestions/getAll",(n,r)=>A(void 0,[n,r],function*({text:e},t){var l;let{deepdeskAPI:o}=t.extra,s=t.getState(),{showStyleSuggestions:i}=s.settings,a=(l=s.conversation.current)==null?void 0:l.profileCode;if(!i)return fm.list;if(!a)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:a,message:e})})),GF=Ee({name:"styleSuggestions",initialState:fm,reducers:{},extraReducers:e=>{e.addCase(pi.pending,t=>{t.fetchState="loading"}).addCase(pi.rejected,t=>{t.fetchState="error"}).addCase(pi.fulfilled,(t,n)=>{t.fetchState="done",Ko(t.list,n.payload)||(t.list=n.payload)}).addCase(Ds,t=>{t.list=fm.list}).addCase(at,()=>fm)}}),hI=GF.reducer;var yI=(e={})=>{let t,n=!0,r=w({getStyleSuggestions:pi,debounce:500},e);return o=>s=>i=>{var p;let a=o.getState().input.text,l=s(i),c=o.getState();if(c.auth.isLoggedIn!==!0)return l;let{showStyleSuggestions:u}=c.settings;if(!((p=c.conversation.current)==null?void 0:p.id)||!u)return l;let{text:d}=c.input;return d===a&&!n||(clearTimeout(t),d==="")||(t=setTimeout(()=>{n=!1,o.dispatch(r.getStyleSuggestions({text:d}))},e.debounce)),l}};function qF(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end}var vI=(e={})=>{let t=w({getTextSuggestions:cr,getAutocompleteSuggestions:Oc,debounce:200,check:Ar},e),n;return r=>o=>s=>{var m;let{input:i}=r.getState(),a=o(s),l=r.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:c,showTabCompletion:u}=l.settings,f=(m=l.conversation.current)==null?void 0:m.id,d=s.type===wp.toString();if(!f||!c&&!u)return a;let{input:p}=l;return qF(p,i)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let x=ta(l);x===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(x))},d?0:t.debounce)),a}};var xI=pi.fulfilled.toString();function YF(e,t){let n=new Set([...t.keywordMatches.map(o=>o.keyword)]),r=[];return n.forEach(o=>{let s=e.keywordMatches.filter(l=>l.keyword===o),i=t.keywordMatches.filter(l=>l.keyword===o),a=i.length-s.length;a<=0||r.push(...i.slice(0,a))}),r}var SI=e=>t=>n=>r=>{var c;if(r.type!==xI){n(r);return}let o=t.getState().styleSuggestions.list;n(r);let s=t.getState(),i=s.styleSuggestions.list,a=(c=s.conversation)==null?void 0:c.current;if(o===i)return;let l=YF(o,i);r.type===xI&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var XF=tf({assistants:oP,auth:S1,conversation:L1,contentTypes:kT,passwordlessToken:aP,entities:bk,handlingTime:mI,info:Q1,input:$1,settings:m1,profile:OT,search:rT,styleSuggestions:hI,ui:Yk,textSuggestions:Mk});function wI(e){return UE({reducer:XF,middleware:t=>{var r;let n=t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI}},serializableCheck:!1}).concat(gI()).concat(vI({debounce:200})).concat(yI({debounce:500})).concat(SI(e.deepdeskAPI));return((r=e.middleware)!=null?r:[]).reduce((o,s)=>o.concat(s),n)},preloadedState:e.preloadedState})}var QF=e=>{var t,n;return(n=(t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())!=null?n:"unknown"},ZF=e=>t=>n=>r=>{var a,l,c,u,f,d,p;let o=t.getState(),s=$l("inlineSuggestions")(o);switch(r.type){case Ji.toString():{!r.payload&&e.emit("logout",void 0);break}case lr.fulfilled.toString():r.payload.length>0&&e.sendEvent("entities found",{conversationId:(a=o.conversation.current)==null?void 0:a.id,data:{entities:r.payload}});break;case Go.toString():e.sendEvent(r.payload.name,{conversationId:((l=r.payload.options)==null?void 0:l.includeConversationData)&&((c=o.conversation.current)==null?void 0:c.id),data:r.payload.data});break;case Ds.toString():e.logSendMessage(r.payload);break;case qp.toString():e.emit("call-to-action",{cue:r.payload});break;case fr.fulfilled.toString():r.isBroadcasted||e.broadcast(Iy,r,!1);break;default:break}let i=n(r);switch(r.type){case Ds.toString():e.handleAfterSendMessage(r.payload);break;case _c.toString():e.onUpdateShowTabHint(r.payload);break;case dm.toString():e.logHandlingTime();break;case ra.toString():e.broadcast(Xl,r);break;case _s.toString():e.broadcast(Xl,r);break;case Yp.toString():t.dispatch(_s({source:"assistant",assistantCode:r.payload.code}));break;case"analytics/logEvent/fulfilled":{e.emit("event",r.meta.arg);break}case xf.toString():{let{start:g,end:m}=o.input.selection;e.emit("replace",P(w({},r.payload),{replace:r.payload.replace==="selection"?{start:g,end:m}:{start:0,end:m}}));break}case Zn.toString():{let{start:g,end:m}=o.input.selection;e.emit("select-suggestion",P(w({type:QF(r.payload.suggestion)},r.payload),{replace:r.payload.replace==="selection"?{start:g,end:m}:{start:0,end:m}})),s&&t.dispatch(qo([]));break}case Sf.toString():e.emit("select-image",r.payload),e.sendEvent("Image attached",{conversationId:(u=o.conversation.current)==null?void 0:u.id,data:{path:r.payload.suggestion.image,title:r.payload.suggestion.title}});break;case qo.toString():{s&&r.payload.length>0&&t.dispatch(wf(0));break}case mo.fulfilled.toString():{if(r.isBroadcasted)break;e.broadcast(Xl,r,!1),e.sendEvent("conversation summarized",{conversationId:(f=o.conversation.current)==null?void 0:f.id,data:{summary:r.payload.output,assistant:(p=(d=t.getState().profile.data)==null?void 0:d.summarizerAssistantNew)!=null?p:void 0}}),e.emit("summary-generated",{summary:r.payload.output});break}default:break}return i},bI=ZF;function z0(e){return e.toISOString().replace("T"," ").replace("Z","")}var JF=(e,t)=>t.version,EI=Vt([oa,kr,uI,JF],(e,t,n,r)=>{if(!t)return ee.warn("No conversationId for handling time metrics"),null;let{startTime:o,stopTime:s}=n;return!o||!s?(ee.warn("No startTime and stopTime for handling time metrics"),null):{conversationId:t,clientVersion:r,agentId:e==null?void 0:e.agentId,agentName:e==null?void 0:e.agentName,agentEmail:e==null?void 0:e.agentEmail,timeStart:z0(o),timeStop:z0(s)}});function TI(e,t){let{text:n,metrics:{numPaste:r,pastes:o,textSuggestions:s}}=e.input,i=n.length;return{source:"agent",clientVersion:t.version,pastes:o,lenTextTotal:i,numPastes:r,suggestions:s}}function H0(e,t){var s;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return H0(r,t);let o=(s=e.ownerDocument.defaultView)==null?void 0:s.frameElement;return o?H0(o,t):null}function B0(e,t){return H0(e,t)}function CI(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function e5(e){return typeof e=="object"&&e!==null&&"tagName"in e}function pm(e){return e5(e)&&(ni(e)||Ip(e))}var RI,Dr=new Map,t5=["bottom","height","left","right","top","width"],kI=(e,t)=>!e&&!t?!1:e&&!t||!e&&t?!0:t5.some(n=>e[n]!==t[n]);function PI(e){var n,r,o;if(e.ownerDocument===document)return[];let t=(o=(r=(n=e.ownerDocument)==null?void 0:n.defaultView)==null?void 0:r.frameElement)!=null?o:null;return t?[t,...PI(t)]:[]}function II(e,t){return!e||!t?null:P(w({},e),{top:e.top+t.top,left:e.left+t.left})}var mm=!1,AI=()=>{mm=!0;let e=[];if(Dr.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),Dr.delete(n);return}let r=n.getBoundingClientRect();kI(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{let n=t.parentRects?t.parentRects.reduce(II,t.rect):t.rect;kI(n,t.totalRect)&&t.callbacks.forEach(r=>r(n)),t.totalRect=n}),Dr.size===0){mm=!1;return}RI=window.requestAnimationFrame(AI)};function U0(e,t){let n=PI(e),r=[],o=n.map((s,i)=>U0(s,a=>{r[i]=a;let l=Dr.get(e);if(!l)return;let c=r.reduce(II,l.rect);l.callbacks.forEach(u=>u(c))}));return{observe(s=!0){if(o.forEach(i=>i.observe(!1)),Dr.has(e)){let i=Dr.get(e);i.callbacks.push(t),i.rect&&t(i.rect)}else Dr.set(e,{rect:void 0,callbacks:[t],parentRects:r});s&&!mm&&AI()},unobserve(){o.forEach(i=>i.unobserve());let s=Dr.get(e);if(s){let i=s.callbacks.indexOf(t);i>=0&&s.callbacks.splice(i,1),s.callbacks.length||Dr.delete(e),Dr.size||(cancelAnimationFrame(RI),mm=!1)}}}}var LI,Fr=new Map,MI=()=>{Fr.forEach((e,t)=>{if(!t.isConnected){Fr.delete(t);return}let{clientHeight:n,scrollHeight:r}=t,o=r>n;e.visible!==o&&(e.visible=o,e.callbacks.forEach(s=>s(e.visible)))}),Fr.size!==0&&(LI=window.requestAnimationFrame(MI))};function OI(e,t){return{observe(){let n=Fr.size===0;Fr.has(e)?Fr.get(e).callbacks.push(t):Fr.set(e,{visible:void 0,callbacks:[t]}),n&&MI()},unobserve(){let n=Fr.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||Fr.delete(e),Fr.size||cancelAnimationFrame(LI)}}}}var V0=["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 $0(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function Ha(e){return Number.parseFloat(e)}function gm(e){return Math.round(e*1e6)}function NI(e){return e/1e6}function j0(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=Ha(e.width),s=Ha(e.borderLeftWidth),i=Ha(e.borderRightWidth),a=Ha(e.paddingRight),l=NI(gm(o)-gm(s)-gm(i)),c=NI(gm(r));if(l-c>2){let u=l-c;n.style.paddingRight=`${a+u}px`}}function du(e,t={}){var u,f;let n=t.overlayContainer||document.createElement("div");n.style.display="none",n.style.position=(u=t.position)!=null?u:"fixed",n.style.pointerEvents="none",n.style.borderColor="transparent",ti(n);let r=window.getComputedStyle(e),o=!0,s=()=>{n.scrollTop=e.scrollTop};$0(r,n,V0),j0(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",s));let i=OI(e,()=>{$0(r,n,V0),j0(r,e,n),s(),setTimeout(s,0)}),a,l=!0,c=U0(e,d=>{if(d===null){t.onRemove&&t.onRemove(),n.remove();return}if(!l&&t.onMoveStart&&(Promise.resolve().then(()=>t.onMoveStart()),l=!0),clearTimeout(a),a=setTimeout(()=>{t.onMoveEnd&&t.onMoveEnd(),l=!1},200),d.height===0&&d.width===0){if(o===!0)return;t.onHide&&t.onHide(),n.style.display="none",o=!0;return}if($0(r,n,V0),j0(r,e,n),s(),t.placement==="below"&&n.classList.add("below"),n.style.top=`${d.top}px`,n.style.left=`${d.left}px`,t.closestScrollElement&&t.closestScrollElement!==e){let p=t.closestScrollElement.getBoundingClientRect(),g=window.getComputedStyle(t.closestScrollElement),m=Ha(g.borderTopWidth),x=Ha(g.borderBottomWidth),v=p.top+m-d.top,y=d.top+d.height+-(p.top+p.height-x);n.style.clipPath=`inset(${v}px 0px ${y}px 0px)`}o&&(n.style.display="block",t.onShow&&t.onShow(),o=!1)});return t.appendTo?t.appendTo.appendChild(n):(f=e.parentElement)==null||f.appendChild(n),c.observe(),i.observe(),[n,()=>{e.removeEventListener("scroll",s),c.unobserve(),i.unobserve(),n.remove()}]}var _I=(e,t)=>({value(){try{let n=sessionStorage.getItem(`dd-${e}`);if(!n)return t;try{return JSON.parse(n)}catch(r){return t}}catch(n){return t}},update(n){try{sessionStorage.setItem(`dd-${e}`,JSON.stringify(n))}catch(r){ee.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function n5(e){return e.offsetParent!==null}function DI(e){if(!n5(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 hm(e,t,n=100){let r=DI(e);t({isVisible:r});let o=setInterval(()=>{let s=DI(e);s!==r&&(r=s,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var fu=class extends Error{};function r5(){let e,t;return{promise:new Promise((r,o)=>{e=r,t=o}),resolve:e,reject:t}}var ym=class{constructor(){this.queues={}}push(t,n){let r=()=>{let s=this.queues[t][1];s?(this.queues[t]=[s.promise,null],s.resolve()):delete this.queues[t]};if(!this.queues[t]){let s=n().finally(r);return this.queues[t]=[s,null],s}this.queues[t][1]&&this.queues[t][1].reject(new fu("Queued async function is outdated"));let o=r5();return this.queues[t][1]=o,o.promise.then(()=>n().finally(r))}};var o5={accepted:"onConversationAcceptedAssistants","new-message":"onConversationNewMessageAssistants",ended:"onConversationEndedAssistants"},FI=(e,t)=>{let n=e[o5[t]];return n&&n.length>0?n.map(r=>r.code):(ee.warn(`No assistant set in profile for conversation event "${t}"`),[])};var vm=class{constructor(t){this.options=t;this.socket=null;this.maxReconnectAttempts=5;this.reconnectInterval=25e3;this.cleanupCallbacks=[];var n,r;this.socket,this.eventListeners=new Map,this.url=t.url,this.maxReconnectAttempts=(n=t.maxReconnectAttempts)!=null?n:this.maxReconnectAttempts,this.reconnectInterval=(r=t.reconnectInterval)!=null?r:this.reconnectInterval,this.shouldReconnect=t.shouldReconnect}connect(){let t=()=>this.cleanup();window.addEventListener("beforeunload",t),this.cleanupCallbacks.push(()=>window.removeEventListener("beforeunload",t)),this.reconnect()}setupListeners(){this.socket&&(this.socket.onmessage=t=>{var n;try{let r=_e(JSON.parse(t.data));r.event&&this.eventListeners.has(r.event)&&((n=this.eventListeners.get(r.event))==null||n.forEach(o=>o(r.data)))}catch(r){console.error("Error parsing WebSocket message:",r)}},this.socket.onclose=t=>{console.log("WebSocket connection closed:",t),setTimeout(()=>{this.reconnect()},this.reconnectInterval)},this.socket.onerror=t=>{console.error("WebSocket error:",t)})}reconnect(){var t,n;if(this.maxReconnectAttempts<=0){console.error("Max reconnect attempts reached, closing WebSocket connection."),(t=this.socket)==null||t.close();return}if(!this.shouldReconnect()){console.error("Should not reconnect, closing WebSocket connection."),(n=this.socket)==null||n.close();return}this.socket&&(this.socket.onmessage=null,this.socket.onclose=null,this.socket.onerror=null,this.socket.close()),this.socket=new WebSocket(this.url),this.setupListeners(),this.maxReconnectAttempts--}send(t,n){if(!this.socket){console.error("WebSocket connection is not open.");return}this.socket.send(JSON.stringify({event:t,data:n}))}on(t,n){this.eventListeners.has(t)||this.eventListeners.set(t,[]);let r=this.eventListeners.get(t);r&&!r.includes(n)&&r.push(n)}close(){var t;(t=this.socket)==null||t.close()}cleanup(){this.close(),this.cleanupCallbacks.forEach(t=>t()),this.cleanupCallbacks=[]}};var Ie=b(R());var zI=_I("showTabHint",!0),Ba=class Ba{constructor({deepdeskUrl:t,version:n=Ba.version||"unknown",locale:r="en-US",token:o,fetch:s,productName:i,createCustomChannel:a,websocketClient:l=vm}){this.inputMediator=null;this.eventListeners={};this.unmountHandlers=[];this.disposeHandlers=[];this.inlineSuggestions=null;this.aboveSuggestions=null;this.belowSuggestions=null;this.floatingMenu=null;this.widgetElement=null;this.widgetRoot=null;this.dynamicThunkObject={};this.queues=new ym;this.isMounted=!1;this.shouldRender=!0;this.loadProfileConfigPromise=null;let c=t.replace(/\/api$/,"");this.deepdeskApi=new xo(c,{token:o,fetch:s}),this.version=n,this.instanceId=Ba.count++;let u={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[bI({broadcast:(g,m,x)=>{this.broadcastEvents.send(g,m,x)},emit:(g,m)=>this.emit(g,m),handleAfterSendMessage:g=>this.handleAfterSendMessage(g),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:g=>this.logSendMessage(g),onUpdateShowTabHint:g=>zI.update(g),sendEvent:(g,m)=>this.deepdeskApi.sendEvent(g,m)})]};this.store=wI(u),this.broadcastEvents=new aI({debug:!0,deepdeskUrl:c,eventMap:oT(this.store),createCustomChannel:a}),this.disposeHandlers.push(()=>{this.broadcastEvents.cleanup()}),this.ws=new l({url:`${c}/api/v2/me/realtime`.replace("https","wss"),reconnectInterval:25e3,shouldReconnect:()=>A(this,null,function*(){var g;return(g=Tt(this.state))!=null?g:!1})}),this.whenLoggedIn(()=>this.ws.connect()),this.store.dispatch(_c(zI.value())),this.store.dispatch(mf({locale:r,adminUrl:c,productName:i}));let f=[],d=g=>{if(!g.conversationId)return;let m=()=>{this.conversationId()===g.conversationId&&this.store.dispatch(rP(g))};this.hasConversation()?m():f.push(m)};this.ws.on("assistants::direct_response",d),this.ws.on("assistants::user_notification",d),this.ws.on("assistants::response_chunk",g=>{if(!g.conversationId)return;let m=()=>{this.conversationId()===g.conversationId&&this.store.dispatch(nP(g))};this.hasConversation()?m():f.push(m)}),this.ws.on("assistants::suggest_as_reply",g=>{if(!g.conversationId)return;let m=()=>{this.conversationId()===g.conversationId&&this.store.dispatch(ra([{text:g.payload.message,type:"text",source:"assistant",assistantCode:g.code,sourceLabel:g.name}]))};this.hasConversation()?m():f.push(m)});let p=this.whenConversationLoaded(()=>{var g;this.broadcastEvents.setExternalId((g=this.state.conversation.current)==null?void 0:g.externalId),f.forEach(m=>m()),f.length=0});this.disposeHandlers.push(()=>{this.ws.cleanup(),f.length=0,p()})}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){var t;return(t=Ns(this.state)[this.state.input.selectedSuggestionIndex])!=null?t:null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}externalId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.externalId}shouldAbort(){return this.state.conversation.isSupported===!1?(ee.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(ee.warn("Profile has not been loaded (yet)"),!0):(ee.warn("No conversation loaded (yet)"),!0)}whenLoggedIn(t){if(Tt(this.state))t();else{let n=this.subscribe(Tt,r=>{r&&t()});this.disposeHandlers.push(()=>{n()})}}login(){return this.store.dispatch(Ji(null)),this.store.dispatch(Jr()),new Promise(t=>{this.whenLoggedIn(()=>t())})}isLoggedIn(){return A(this,null,function*(){return(yield this.store.dispatch(Jr())).payload})}isConversationSupported(t,n){return A(this,null,function*(){return(yield this.store.dispatch(by({externalId:t,options:n}))).payload})}createConversation(t){return A(this,null,function*(){var r;return this.hasConversation()&&this.externalId()!==t.externalId&&this.resetConversation(),(yield this.store.dispatch(hf(P(w({},t),{metadata:(r=t.metadata)!=null?r:{}})))).payload})}getConversationByExternalId(t,n){return A(this,null,function*(){return this.hasConversation()&&this.externalId()!==t&&this.resetConversation(),(yield this.store.dispatch(yf({externalId:t,options:n}))).payload})}upsertConversation(t){return A(this,null,function*(){var r;return this.hasConversation()&&this.externalId()!==t.externalId&&this.resetConversation(),(yield this.store.dispatch(Ey(P(w({},t),{metadata:(r=t.metadata)!=null?r:{}})))).payload})}postMessages(t){return A(this,null,function*(){yield this.store.dispatch(Ty(t))})}updateConversation(t){return A(this,null,function*(){return(yield this.store.dispatch(vf(t))).payload})}resetConversation(){this.store.dispatch(at()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}configure(t){this.store.dispatch(mf(t))}setVisitorInfo(t){this.store.dispatch(q1(t))}setCustomData(t){this.store.dispatch(Y1(t))}setAgentInfo(t,n){return A(this,null,function*(){yield this.store.dispatch(Gl(w(w({},t),n)))})}setAgentSettings(t){return A(this,null,function*(){yield this.store.dispatch(ky(t))})}getAgentSettings(){return A(this,null,function*(){return(yield this.store.dispatch(Ry())).payload})}refresh(){return A(this,null,function*(){if(this.shouldAbort())return Promise.resolve();let t=[];return t.push(this.refreshTextSuggestions()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})})}syncInputMediator(){this.inputMediator&&this.store.dispatch(bf({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()}))}notifyExternalSuggestion(t){this.store.dispatch(Zn(t))}evaluateAssistant(t,n){return A(this,null,function*(){var f;let u=n||{},{input:r={},transcript:o,showCuesInWidget:s=!0,includeMetadata:i,expectFormat:a}=u,l=re(u,["input","transcript","showCuesInWidget","includeMetadata","expectFormat"]);Object.assign(r,l);let c=yield this.store.dispatch(fr({assistantCode:t,expectFormat:a||"json-schema:cues",transcript:o,includeMetadata:i,input:r,skipState:!s}));if(c.error)throw new Error(`Assistant evaluation failed: ${(f=c.payload)!=null?f:c.error.message}`);return c.payload.output})}evaluateConversationAssistant(t,n){return A(this,null,function*(){yield this.loadProfileConfig();let r=this.state.profile.data;if(!r){ee.warn("Can't evaluate assistant when profile is not loaded yet.");return}let o=FI(r,t);yield Promise.all(o.map(s=>this.queues.push(s,()=>A(this,null,function*(){if(s===r.summarizerAssistantNew)return this.getSummary(w({includeMetadata:!0},n));yield this.evaluateAssistant(s,w({includeMetadata:!0},n))})).catch(i=>{if(i instanceof fu){ee.warn(`Queued assistant "${s}" was outdated and dropped`);return}throw i})))})}getSummary(){return A(this,arguments,function*(t={}){var r;if(!this.hasConversation())return ee.warn("No conversation to create summary for."),null;(r=this.state.profile.data)!=null&&r.summarizerAssistantNew||ee.warn("No profile loaded yet, or no summarizer assistant set in profile");let n=yield this.store.dispatch(mo(t));return n.error?(ee.error("Error evaluating summary assistant",n.error),null):n.payload.output})}handleKeyDown(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui,{textSuggestions:o,selectedSuggestionIndex:s,selection:i}=this.state.input,{inlineSuggestions:a,showTextSuggestions:l,suggestionsPlacement:c}=this.settings,u=c==="inline"||c==="below"?"below":"above",f=o.length>0;if(this.store.dispatch(D1(Cy(t))),!Ar(this.state)||t.key!=="Tab"&&!l)return;let d=()=>{n||!f||i&&(t.shiftKey||(this.store.dispatch(H1()),t.preventDefault()))},p=()=>{n||!f||a&&s<=0||i&&(t.shiftKey||(this.store.dispatch(B1()),t.preventDefault()))};switch(t.key){case"ArrowUp":u==="below"?p():d();break;case"ArrowDown":{u==="below"?d():p();break}case"Escape":{n||(this.store.dispatch(wf(-1)),this.store.dispatch(ns({collapse:!0})),this.store.dispatch(Gk(!0)),t.preventDefault());break}case"Tab":{t.preventDefault();let g=na(this.state);if(!g)return;this.store.dispatch(_c(!1)),this.store.dispatch(Zn({text:g.text,suggestion:g,eventMetrics:{inputType:"tab"},replace:"until-selection-end"}));break}case" ":{if(this.settings.inlineSuggestions||this.state.input.selectedSuggestionIndex===-1)return;let g=na(this.state);if(!g)return;this.store.dispatch(Zn({text:g.text,suggestion:g,eventMetrics:{inputType:"space"},replace:"until-selection-end"}));break}case"Enter":{if(this.settings.inlineSuggestions||t.shiftKey||this.state.input.selectedSuggestionIndex===-1)return;let g=na(this.state);if(!g)return;this.store.dispatch(Zn({text:g.text,suggestion:g,eventMetrics:{inputType:"enter"},replace:"until-selection-end"})),t.preventDefault();break}default:}n&&r&&this.store.dispatch(ns({collapse:!1}))}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(qo([]))}handlingTimeStart(){this.state.handlingTime.startTime||(ee.info("Start handling time"),this.store.dispatch(fI()))}handlingTimeStop(){this.state.handlingTime.startTime&&(ee.info("Stop handling time"),this.store.dispatch(dm()))}logSendMessage(t){let n=TI(this.state,{version:this.version});n&&(t&&(Object.assign(n,{text:t}),Object.assign(n,{lenTextTotal:t.length})),this.deepdeskApi.sendEvent("Send Message",{conversationId:this.conversationId(),data:n}),this.emit("send-message-event",n))}logHandlingTime(){let t=EI(this.state,{version:this.version});t&&(this.deepdeskApi.sendEvent("Handling Time",{conversationId:this.conversationId(),data:t}),this.store.dispatch(pI()))}notifySubmit(t={}){var n;this.shouldAbort()||(this.store.dispatch(Ds((n=t.text)!=null?n:this.state.input.text)),this.store.dispatch(V1()))}emit(t,n){let r=this.eventListeners[t];r&&r.forEach(o=>{try{o(n)}catch(s){ee.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),ee.error(s)}})}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),()=>{this.off(t,n)}}off(t,n){if(!t&&!n){this.eventListeners={};return}let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}setConversationQuery(t){this.dynamicThunkObject.conversationQuery=t}setPlatformVariables(t){this.store.dispatch(X1(t))}whenConversationLoaded(t){let n=s=>{var i;return(i=s.conversation.current)==null?void 0:i.id},r=()=>this.loadProfileConfig().then(()=>t());return n(this.state)&&r(),this.subscribe(n,s=>{s&&r()})}overlayContainerFactory(t,n,r,o){let[s,i]=du(n,r);return s.setAttribute("translate","no"),s.dataset.testid=t,o&&s.classList.add(o),[s,i]}createInlineContainer(t,n){var a;let r=document.createElement("div");r.style.position="absolute",r.style.top="0px",r.style.left="0px",r.style.height="0px",r.style.width="0px";let o=document.createElement("div");o.style.display="none",o.style.position="absolute",o.style.height="0px",o.style.width="0px",o.style.backgroundColor="red",r.appendChild(o);let s=(a=t.ownerDocument.defaultView)==null?void 0:a.frameElement,i=s?s.ownerDocument.defaultView:null;if(s&&(i===window||(i==null?void 0:i.parent)===window)){let[l,c]=du(s,{appendTo:document.body,onMoveStart:()=>{o.style.display="none"}});l.dataset.testid=n,l.style.zIndex="2",l.appendChild(r),this.unmountHandlers.push(()=>{c()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return ti(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),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),ee.info(`Stored analytics for ${this.conversationId()}`)}catch(t){}}restoreMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=window.sessionStorage.getItem(t);if(!n)return;let r=JSON.parse(n);r.text.trim()===this.state.input.text.trim()?(ee.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(U1(r.metrics))):ee.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(t)}catch(t){}}mount(t,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!pm(t))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let d=n,{customStyles:r,closestScrollSelector:o,floatingMenuParent:s,appendOverlayTo:i,inputMediator:a}=d,l=re(d,["customStyles","closestScrollSelector","floatingMenuParent","appendOverlayTo","inputMediator"]),c={customStyles:r,closestScrollSelector:o,floatingMenuParent:s,appendOverlayTo:i};this.configure(l),this.settings.automaticHandlingTime&&this.setupHandlingTime(t),ti(t),this.inputMediator=a||(ni(t)?new ui(t):new ci(t)),this.inputMediator.on("change",({plainText:p,rawHTML:g})=>{this.store.dispatch(bf({text:p,html:g}))}),this.inputMediator.on("keyup",p=>{this.store.dispatch(F1(Cy(p)))}),this.inputMediator.on("keydown",p=>{this.handleKeyDown(p)}),this.inputMediator.on("paste",({pastedText:p,selectionText:g})=>{this.store.dispatch(z1({text:p,selectionText:g}))}),this.inputMediator.on("cut",({selectionText:p})=>{this.store.dispatch(_1(p))});let u;this.inputMediator.on("selection",p=>{clearTimeout(u),p===null?u=setTimeout(()=>{p!==null&&this.store.dispatch(Ef(p))},500):this.store.dispatch(Ef(p))}),this.unmountHandlers.push(()=>{clearTimeout(u)}),this.inputMediator.on("disabled",()=>{var p;(p=this.inputMediator)==null||p.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{this.settings.detectSubmit&&this.notifySubmit()}),this.inputMediator.on("blur",()=>{this.store.dispatch(Tp(!1))}),this.inputMediator.on("focus",()=>{this.store.dispatch(Tp(!0))}),this.renderSuggestions(t,c),this.subscribe($l("inlineSuggestions"),()=>{this.renderSuggestions(t,c)});let f=this.renderOverlays(n);this.unmountHandlers.push(()=>{f.unmount()}),this.store.dispatch(bf({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()})),this.store.dispatch(Ef(this.inputMediator.getSelection())),this.store.dispatch(Tp(this.inputMediator.isFocused)),this.unmountHandlers.push(()=>{this.state.input.text!==""&&this.storeMetrics()}),this.whenConversationLoaded(()=>{this.restoreMetrics(),this.syncInputMediator(),this.refreshTextSuggestions()}),this.isMounted=!0}subscribe(t,n){let r=t(this.store.getState());return this.store.subscribe(()=>{let o=t(this.store.getState());o!==r&&(r=o,n(r))})}unmount(){var t,n,r,o,s;(t=this.inlineSuggestions)==null||t.unmount(),(n=this.aboveSuggestions)==null||n.unmount(),(r=this.belowSuggestions)==null||r.unmount(),(o=this.floatingMenu)==null||o.unmount(),this.unmountHandlers.forEach(i=>i()),this.unmountHandlers=[],(s=this.inputMediator)==null||s.dispose(),this.isMounted=!1}dispose(){this.unmount(),this.unmountWidget(),this.disposeHandlers.forEach(t=>t()),this.disposeHandlers=[],this.off()}renderSuggestions(t,n){var r,o,s,i;(r=this.floatingMenu)==null||r.unmount(),(o=this.inlineSuggestions)==null||o.unmount(),(s=this.aboveSuggestions)==null||s.unmount(),(i=this.belowSuggestions)==null||i.unmount(),this.settings.floatingMenu&&(this.floatingMenu=this.renderFloatingMenu(t,n)),this.settings.inlineSuggestions||this.settings.suggestionsPlacement==="inline"?this.inlineSuggestions=this.renderInlineSuggestions(t,n):this.settings.suggestionsPlacement==="below"?this.belowSuggestions=this.renderAboveOrBelowSuggestions(t,n,"below"):this.aboveSuggestions=this.renderAboveOrBelowSuggestions(t,n,"above")}renderInlineSuggestions(t,n){let{customStyles:r}=n,o=this.createInlineContainer(t,"deepdesk-caret"),s=(0,us.createRoot)(o);s.render((0,Ie.jsx)(os,{store:this.store,customStyles:r,children:(0,Ie.jsx)(Yo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(oR,{})})}));let i=a=>{a?(o.style.display="block",o.style.top=`${a.top}px`,o.style.left=`${a.left}px`):o.style.display="none"};return this.inputMediator.on("caretposition",i),{unmount:()=>{var a;(a=this.inputMediator)==null||a.off("caretposition",i),s.unmount(),o.remove()}}}renderAboveOrBelowSuggestions(t,n,r){let{customStyles:o,closestScrollSelector:s,appendOverlayTo:i}=n,a=s&&B0(t,s)||void 0,[l,c]=this.overlayContainerFactory("deepdesk-tab-completion",a||t,{appendTo:i,closestScrollElement:a,mirrorOverflow:!0,onRemove:()=>this.unmount()},o==null?void 0:o.rootNode),[u,f]=this.overlayContainerFactory("deepdesk-suggestions-overlay",a||t,{appendTo:i,placement:r},o==null?void 0:o.suggestionsRootNode),d=(0,us.createRoot)(l);d.render((0,Ie.jsx)(os,{store:this.store,customStyles:o,children:(0,Ie.jsx)(Yo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(NR,{inputElement:t})})}));let p=(0,us.createRoot)(u);return p.render((0,Ie.jsx)(os,{store:this.store,customStyles:o,children:(0,Ie.jsx)(Yo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(pR,{onLogIn:()=>this.loginViaPopup().catch(g=>ee.warn(g.message))})})})),{unmount(){d.unmount(),p.unmount(),c(),f()}}}renderFloatingMenu(t,n){let{customStyles:r,closestScrollSelector:o,appendOverlayTo:s,floatingMenuParent:i}=n,a=o&&B0(t,o)||void 0,[l,c]=this.overlayContainerFactory("floating-menu",a||t,{appendTo:i!=null?i:s},r==null?void 0:r.floatingMenuParent),u=(0,us.createRoot)(l);return u.render((0,Ie.jsx)(os,{store:this.store,customStyles:r,children:(0,Ie.jsx)(Yo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(jk,{onLogIn:()=>this.loginViaPopup().catch(f=>ee.warn(f.message))})})})),{unmount(){u.unmount(),c()}}}renderOverlays(t){let{customStyles:n}=t,r=this.createContainer("deepdesk-overlays"),o=(0,us.createRoot)(r);return o.render((0,Ie.jsx)(os,{store:this.store,customStyles:n,children:(0,Ie.jsx)(Yo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(Hk,{})})})),{unmount(){o.unmount(),r.remove()}}}renderWidget(t,n={}){if(this.widgetElement&&ee.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,isEmbedded:s}=n;this.widgetElement=t,this.configure({showImages:o,isEmbedded:s}),this.widgetRoot=(0,us.createRoot)(t),this.widgetRoot.render((0,Ie.jsx)(os,{store:this.store,customStyles:r,children:(0,Ie.jsx)(Yo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(tI,{assistantOptions:n.assistantOptions,knowledgeAssistOptions:n.knowledgeAssist,onLogIn:()=>this.loginViaPopup().catch(i=>ee.warn(i.message))})})}))}unmountWidget(){var t,n;(n=(t=this.widgetRoot)==null?void 0:t.unmount)==null||n.call(t),this.widgetRoot=null,this.widgetElement=null}renderKnowledgeAssistantWidget(t,n,r={}){let{customStyles:o,initialQuestion:s}=r,i=(0,us.createRoot)(n);return i.render((0,Ie.jsx)(os,{store:this.store,customStyles:o,children:(0,Ie.jsx)(Yo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(A0,{children:(0,Ie.jsxs)(im,{assistantCode:t,initialQuestion:s,evaluateKnowledgeAssistFn:r.isLegacyKnowledgeAssist?Gc:qc,children:[(0,Ie.jsx)(xi,{children:(0,Ie.jsx)(lm,{title:r.title,emptyState:r.emptyState})}),(0,Ie.jsx)(I0,{children:(0,Ie.jsx)(am,{})})]})})})})),{unmount(){i.unmount()}}}setupHandlingTime(t){let n=hm(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){CI(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(()=>A(this,null,function*(){yield this.store.dispatch(uc());let t=Hs(this.state);t&&this.store.dispatch(mf({showSearch:t.search,showImageSearch:t.imageSearch,showEntitiesCommand:t.entitiesCommand,showSummaryCommand:!!t.summarizerAssistantNew,showKnowledgeSearch:!!t.knowledgeAssistantNew||!!t.knowledgeAssistant,recommendTextSuggestions:t.recommendTextSuggestions}))})),this.loadProfileConfigPromise)}loginViaPopup(t){return A(this,null,function*(){return new Promise((n,r)=>{let o=new MessageChannel,s=o.port1,i=this.settings.adminUrl,a=new URL(t!=null&&t.url?t==null?void 0:t.url:`${i}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let l=!1,c=()=>{u&&!u.closed&&u.close(),window.removeEventListener("message",f),clearInterval(d)};s.onmessage=p=>A(this,null,function*(){var g,m;if((g=p.data)!=null&&g.jwt)try{yield this.deepdeskApi.exchangeTokenForAccessCookie((m=p.data)==null?void 0:m.jwt),yield this.isLoggedIn(),this.broadcastEvents.send(Yl),l=!0,o.port1.close(),n()}catch(x){console.error(x),r(x)}finally{l=!0,c()}});let u=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");u===null&&r(new Error("Popup blocked by browser"));let f=p=>A(this,null,function*(){var g;if(p.origin===a.origin)switch((g=p.data)==null?void 0:g.type){case"deepdesk-popup-loaded":{try{let m=JSON.stringify({type:"deepdesk-popup-create-channel"});u==null||u.postMessage(m,a.origin,[o.port2])}catch(m){ee.error("Error posting message to popup",m),r(m)}break}case"deepdesk-popup-error":{c(),p.data.message==="Timeout"&&ee.warn("Popup timed out. Check if the account's platform url is configured correctly."),r(new Error(p.data.message));break}}});window.addEventListener("message",f);let d=setInterval(()=>{u&&!u.closed||(c(),l||r(new Error("Popup closed by user")))},200);this.disposeHandlers.push(c)})})}translateMessages(t){return this.deepdeskApi.translateMessages(t)}refreshTextSuggestions(){return A(this,null,function*(){this.isMounted&&(yield this.store.dispatch(wp()))})}refreshWidgetSuggestions(){return A(this,null,function*(){if(!this.widgetRoot)return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=dc(this.state);try{n.forEach(({type:r})=>{switch(r){case"entities":this.store.dispatch(lr());break;case"pinned-messages":case"sticky-messages":break;default:Ou.includes(r)||this.store.dispatch(cr(r))}})}catch(r){this.handleError(r)}})}};Ba.version="18.1.2-beta.9",Ba.count=0;var pu=Ba;function s5(e){return A(this,null,function*(){var o,s,i;let n=yield((o=e.fetch)!=null?o:window.fetch)(e.url),r=yield n.blob();return new File([r],e.name,{type:(i=(s=e.mimeType)!=null?s:n.headers.get("Content-Type"))!=null?i:"image/jpeg"})})}function HI(e,t){return A(this,null,function*(){let n=yield s5(t),r=new Event("change",{bubbles:!0,cancelable:!0});try{Object.defineProperty(e,"files",{configurable:!0,get:()=>[n]}),e.dispatchEvent(r)}finally{Object.hasOwn(e,"files")&&delete e.files}})}function BI(e,t,n){return A(this,null,function*(){yield new xo(e).authenticateWithKey(t,n)})}function UI(e){return e.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}function VI(r,o){return A(this,arguments,function*(e,t,n={}){var f,d;let{value:s}=e,{start:i,end:a}=(f=n.replace)!=null?f:{start:0,end:s.length},l=`${s.slice(0,i)}${t}${s.slice(a)}`,c=(d=n.selectionAfter)!=null?d:{start:i+t.length,end:i+t.length},u=()=>{if(n.setValue)return n.setValue(l);e.value=l};return Promise.resolve(u()).then(()=>{e.selectionStart=c.start,e.selectionEnd=c.end,e.blur(),e.focus()})})}function $I(r,o){return A(this,arguments,function*(e,t,n={}){let s=n.replace?ls(e,n.replace.start,n.replace.end):Da(e),i,a=()=>{if(n.setRange)return n.setRange(s.cloneRange());s.deleteContents(),i=document.createElement("span"),s.insertNode(i),n.insertBRs!==!1?t.split(`
83
83
  `).reverse().forEach((l,c)=>{c>0&&s.insertNode(document.createElement("br")),s.insertNode(document.createTextNode(l))}):s.insertNode(document.createTextNode(t))};return Promise.resolve(a()).then(()=>{try{if(n.selectionAfter!==!1){e.focus();let l=n.selectionAfter?ls(e,n.selectionAfter.start,n.selectionAfter.end):(s.collapse(!1),s),c=window.getSelection();c==null||c.removeAllRanges(),c==null||c.addRange(l)}if(!i)return;i.scrollIntoView&&i.scrollIntoView({block:"nearest",inline:"nearest"})}finally{i&&i.remove()}})})}function i5(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 a5(e){let t=document.createDocumentFragment();return e.split(`
84
84
  `).forEach((n,r)=>{r>0&&t.appendChild(document.createElement("br"));let o={index:0},s=0;for(;o=n.slice(s).match(/(\[([^\]]+)])\(([^)]+)\)/);){let i=document.createElement("a");i.href=o[3],i.setAttribute("target","_blank"),i.setAttribute("rel","noopener noreferrer"),i.appendChild(document.createTextNode(o[2])),t.appendChild(document.createTextNode(n.slice(s,s+o.index))),t.appendChild(i),s=s+o.index+o[0].length}t.appendChild(document.createTextNode(n.slice(s)))}),t}function jI(e,t){let n=e.parentElement;if(!n){console.warn("No insert point found");return}let{display:r}=window.getComputedStyle(n);r.includes("block")||r==="table-cell"?n==null||n.insertBefore(t,e.nextSibling):jI(n,t)}function WI(o,s){return A(this,arguments,function*(e,t,{isBlock:n,isHTML:r}={}){let i;e.dispatchEvent(new InputEvent("beforeinput",{inputType:"insertText",data:t,bubbles:!0,cancelable:!0}));let a=()=>{var d;let l=(d=e.ownerDocument.defaultView)!=null?d:window,c=l.getSelection();if((!c||c.rangeCount===0)&&(e.focus(),c=l.getSelection()),!c||c.rangeCount===0)return;let u=c.getRangeAt(0);if(!u)return;i=document.createElement("span"),u.insertNode(i);let f=r?i5(t):a5(t);n?jI(u.startContainer,f):(u.insertNode(f),u.collapse(!1))};return Promise.resolve(a()).then(()=>{if(e.dispatchEvent(new InputEvent("input",{inputType:"insertText",data:t,bubbles:!0,cancelable:!0})),e.focus(),!!i)try{i.scrollIntoView&&i.scrollIntoView({block:"nearest",inline:"nearest"})}finally{i&&i.remove()}})})}return sA(l5);})();
85
85
  /*! Bundled license information:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deepdesk/deepdesk-sdk",
3
- "version": "18.1.2-beta.8",
3
+ "version": "18.1.2-beta.9",
4
4
  "description": "Deepdesk SDK",
5
5
  "author": "Lukas Batteau",
6
6
  "license": "ISC",