@deepdesk/deepdesk-sdk 18.2.1-beta.5 → 18.2.1-beta.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs.js +1 -1
- package/dist/index.esm.js +1 -1
- package/dist/index.iife.js +1 -1
- package/package.json +8 -46
package/dist/index.iife.js
CHANGED
|
@@ -79,7 +79,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let r="<p>An error
|
|
|
79
79
|
`+en),ce&&tm([Q,Y,A],zr=>{en=Zc(en,zr," ")}),S&<?S.createHTML(en):en},t.setConfig=function(){let re=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Em(re),qe=!0},t.clearConfig=function(){yi=null,qe=!1},t.isValidAttribute=function(re,C,H){yi||Em({});let Z=ct(re),He=ct(C);return xx(Z,He,H)},t.addHook=function(re,C){typeof C=="function"&&Qc(M[re],C)},t.removeHook=function(re,C){if(C!==void 0){let H=_F(M[re],C);return H===-1?void 0:NF(M[re],H,1)[0]}return XP(M[re])},t.removeHooks=function(re){M[re]=[]},t.removeAllHooks=function(){M=nI()},t}var aI=iI();var xo=b(X());var lI={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 pr=b(R());function ZF(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 V0(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 JF(e){return e.replace(/\r\n/g,`
|
|
80
80
|
`)}var e5=({content:e,useLabel:t,copyLabel:n,onCopy:r,onUse:o})=>{let s=F("Markdown",lI),i=(0,xo.useRef)(null),[a,c]=(0,xo.useState)(null),l=(0,xo.useMemo)(()=>{let g=Ce.parse(JF(e));return aI.sanitize(g.toString()).replaceAll("</code>",`${ZF(s.copyIcon)}</code>`).replaceAll('<a href="','<a target="_blank" rel="noreferrer noopener" href="')},[e]),u=g=>{var h;let x=g.target,v=!!((h=i.current)!=null&&h.querySelector("code"));if(["A","BUTTON"].includes(x.tagName)){c(null);return}a||v&&x.tagName!=="CODE"||!v&&x!==i.current||(x.addEventListener("mouseleave",()=>c(null),{once:!0}),c(x))},f=()=>{if(!a)return;c(null);let g=a.querySelector("button");g&&(_a(g,s.fadeup),r==null||r(V0(a)))},d=g=>{let x=g.target;if(x.tagName==="A"){g.stopPropagation();return}"copyIcon"in x.dataset&&(_a(x,s.fadeup),r==null||r(V0(x.parentElement)))},p=()=>{!a||!o||(c(null),o(V0(a)))},m=g=>{if(g===null)return;let x=g.getBoundingClientRect();x.left<0?g.style.transform=`translateX(${-x.left+2}px)`:x.right>window.innerWidth&&(g.style.transform=`translateX(${window.innerWidth-x.right-2}px)`)};return(0,pr.jsxs)(xo.Fragment,{children:[a&&(r||o)&&(0,pr.jsxs)(La,{triggerRef:{current:a},className:s.popover,parentNode:a,children:[(0,pr.jsxs)("div",{className:s.options,ref:m,children:[r&&(0,pr.jsx)("button",{type:"button",className:s.option,onClick:f,children:n}),o&&(0,pr.jsxs)(xo.Fragment,{children:[(0,pr.jsx)("div",{className:s.divider}),(0,pr.jsx)("button",{type:"button",className:s.option,onClick:p,children:t})]})]}),(0,pr.jsx)("div",{className:s.arrow})]}),(0,pr.jsx)("div",{ref:i,"data-testid":"widget-markdown-content",className:s.root,dangerouslySetInnerHTML:{__html:l},onMouseOver:u,onClick:d})]})},ai=e5;var W0={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 Jt=b(R()),t5=500,n5=100,r5=({content:e,onChange:t,onCopy:n})=>{let r=(0,li.useRef)(null),o=F("WidgetCue",W0);return(0,li.useEffect)(()=>{let s=r.current;if(!s)return;s.style.setProperty("height","0px");let i=Math.min(Math.max(s.scrollHeight,n5),t5);s.style.setProperty("height",`${i}px`)},[e]),(0,Jt.jsx)("textarea",{ref:r,className:o.editableCue,onCopy:n,onChange:t,value:e})},o5=({cue:e,onCallToAction:t,onRemove:n,onCopy:r,onUse:o})=>{let s=F("WidgetCue",W0),i=ie(Xc),a=Xe(),c=te("hasKeyboardInput"),[l,u]=(0,li.useState)(e.text),f=()=>{t&&t(l,e),n(e)},d=g=>{r&&r(g,e)},p=g=>{o&&o(g,e)},m=g=>{g.preventDefault(),g.stopPropagation(),n(e)};return(0,li.useEffect)(()=>{a("Assistant response displayed",{evaluationId:e.evaluationId,assistantCode:e.rule.label,assistantOutput:e.text})},[]),(0,Jt.jsxs)(de,{"data-testid":"cue",children:[(0,Jt.jsx)(he,{children:(0,Jt.jsxs)(he.Content,{children:[e.title&&(0,Jt.jsx)(he.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,Jt.jsx)(r5,{content:l,onCopy:()=>{let g=document.getSelection();g&&d(g.toString())},onChange:g=>{var x;return u((x=g.target.value)!=null?x:"")}}):(0,Jt.jsx)(ai,{content:e.text,useLabel:i("useCue"),copyLabel:i("copyCue"),onCopy:d,onUse:c?p:void 0})]})}),(0,Jt.jsxs)(de.ButtonsContainer,{children:[(0,Jt.jsxs)("div",{className:s.actions,children:[(e.specialType==="summary"||e.editable)&&(0,Jt.jsx)(de.Button,{onClick:()=>d(l),variant:"primary",children:i("copyCue")}),e.callToAction&&(0,Jt.jsx)(de.Button,{onClick:f,variant:"primary",children:e.callToAction.label}),(0,Jt.jsx)(de.Button,{onClick:m,variant:"secondary",children:i("removeCue")})]}),(0,Jt.jsx)(em,{evaluationId:e.evaluationId,assistantCode:e.rule.label,assistantOutput:e.text,feedbackText:e.text,feedbackType:"assistant"})]})]})},cI=o5;var Na=b(R()),s5=({cues:e})=>{let t=ve(),n=un(),r=ie(Xc),o=Xe(),s=l=>{t(Yp({code:l.rule.label})),o("Assistant response closed",{evaluationId:l.evaluationId,assistantCode:l.rule.label,assistantOutput:l.text})},i=(l,u)=>{Tr(l),o("Assistant response copied",{evaluationId:u.evaluationId,assistantCode:u.rule.label,assistantOutput:u.text,copiedText:l})},a=(l,u)=>{var f;u.callToAction&&(t(qp(u)),o("Assistant call to action",{evaluationId:u.evaluationId,assistantCode:u.rule.label,assistantOutput:u.text,eventName:u.callToAction.event,value:(f=u.callToAction.value)!=null?f:l}))},c=(l,u)=>{var f;n.send(Jr,{text:l,suggestion:{source:"assistant",assistantCode:(f=u.rule)==null?void 0:f.label,sourceText:l}}),o("Assistant response used",{evaluationId:u.evaluationId,assistantCode:u.rule.label,assistantOutput:u.text,usedText:l})};return(0,Na.jsx)(Na.Fragment,{children:e.map(l=>l.isLoading?(0,Na.jsx)(Zp,{title:l.rule.label.startsWith("__")?r(l.rule.label):l.title},l.rule.id):(0,Na.jsx)(cI,{cue:l,onCallToAction:a,onRemove:s,onCopy:i,onUse:c},l.evaluationId))})},uI=s5;var om=b(X());var dI={root:"dd-cvTAY",label:"dd-QWQxD",value:"dd-WSUHF",copyButton:"dd-67o9H",copyButtonText:"dd-oos-l",isTrue:"dd--1g2O",isFalse:"dd-sz2ir"};var gn=b(R());function i5(e,t){return t.split(".").reduce((n,r)=>!n||typeof n!="object"||!(r in n)?null:n[r],e)}var fI=({data:e,schema:t})=>{let n=F("WidgetCustomData",dI),r=o=>{Tr(o)};return(0,om.useEffect)(()=>{J.info("Custom data",e,t)},[e]),(0,gn.jsx)("dl",{className:n.root,children:t.map(o=>{let s=i5(e,o.path);return(0,gn.jsxs)(om.Fragment,{children:[(0,gn.jsx)("dt",{className:n.label,children:o.label}),(0,gn.jsx)("dd",{className:n.value,children:o.type==="boolean"&&s?(0,gn.jsx)("span",{className:n.isTrue,children:o.trueValue}):o.type==="boolean"&&!s?(0,gn.jsx)("span",{className:n.isFalse,children:o.falseValue}):o.type==="array"&&Array.isArray(s)&&s.length>0?(0,gn.jsxs)("button",{type:"button",onClick:()=>r(s.join(", ")),className:n.copyButton,children:[(0,gn.jsx)("span",{className:n.copyButtonText,children:s.join(", ")}),(0,gn.jsx)(Oa,{})]}):typeof s=="string"||typeof s=="number"?(0,gn.jsxs)("button",{type:"button",onClick:()=>r(`${s}`),className:n.copyButton,children:[(0,gn.jsx)("span",{className:n.copyButtonText,children:s}),(0,gn.jsx)(Oa,{})]}):"-"})]},o.label)})})};var Qe=b(X());var Da={};yt(Da,{enUS:()=>a5,nlNL:()=>l5});var a5={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"}]},l5={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 sm={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 mI=b(X());var pI={error:"dd-CoAuB"};var $0={};yt($0,{enUS:()=>c5,nlNL:()=>u5});var c5={errorPrefix:[{type:0,value:"Error:"}]},u5={errorPrefix:[{type:0,value:"Foutmelding:"}]};var nu=b(R()),gI=({message:e})=>{let t=(0,mI.useRef)(null),n=F("WidgetCardError",pI),r=ie($0);return ku(t),(0,nu.jsx)(de,{ref:t,children:(0,nu.jsx)(he,{children:(0,nu.jsxs)(he.Content,{className:n.error,children:[r("errorPrefix")," ",e]})})})};var ge=b(R()),d5=3,f5=({sources:e,onClick:t})=>{let n=ie(Da),r=F("WidgetKnowledgeAssistant",sm),[o,s]=(0,Qe.useState)(!1),i=o?e:e.slice(0,d5);return i.length===0?null:(0,ge.jsxs)("ul",{className:r.sources,children:[i.map(a=>(0,ge.jsx)("li",{className:r.source,"data-testid":"knowledge-assist-source",children:(0,ge.jsxs)(pt,{tooltip:!0,placement:"top-start",children:[(0,ge.jsx)(pt.Trigger,{as:"a",rel:"noreferrer",target:"_blank",href:a.url,onClick:c=>{c.stopPropagation(),t(a)},children:(0,ge.jsx)("span",{className:r.linkContent,children:a.name})}),a.url&&(0,ge.jsx)(pt.Content,{className:r.tooltip,children:decodeURIComponent(a.url)})]})},a.name)),i<e&&(0,ge.jsx)("button",{type:"button",className:r.showMoreSources,onClick:()=>s(!0),children:n("showMore",{amount:e.length-i.length})})]})},p5=({title:e,description:t})=>(0,ge.jsx)(de,{"data-testid":"knowledge-assist-empty-state",children:(0,ge.jsx)(he,{children:(0,ge.jsxs)(he.Content,{children:[(0,ge.jsx)(he.Title,{children:e}),(0,ge.jsx)(ai,{content:t})]})})}),m5=({innerRef:e,item:t,hasKeyboardInput:n,onCopy:r,onUse:o,onSourceClick:s})=>{var c;let i=ie(Da),a=(0,Qe.useContext)(im);return(0,ge.jsxs)(de,{"data-testid":"knowledge-assist-answer",ref:e,children:[(0,ge.jsx)(he,{children:(0,ge.jsxs)(he.Content,{children:[(0,ge.jsx)(he.Title,{children:t.question}),(0,ge.jsx)(ai,{content:t.answer.answer,useLabel:i("useCue"),copyLabel:i("copyCue"),onCopy:r,onUse:n?o:void 0}),(0,ge.jsx)(f5,{sources:(c=t.answer.sources)!=null?c:[],onClick:s})]})}),a.assistantCode&&(0,ge.jsxs)(de.ButtonsContainer,{children:[(0,ge.jsx)("div",{}),(0,ge.jsx)(em,{evaluationId:t.evaluationId,feedbackType:"assistant",assistantCode:a.assistantCode,assistantOutput:t.answer.answer,feedbackText:t.answer.answer})]})]})},im=(0,Qe.createContext)(null),am=({assistantCode:e,evaluateKnowledgeAssistFn:t,initialQuestion:n,children:r})=>{let[o,s]=(0,Qe.useState)(null),[i,a]=(0,Qe.useState)(!1),[c,l]=(0,Qe.useState)(null),[u,f]=(0,Qe.useState)(!!n),[d,p]=(0,Qe.useState)(null),m=ve(),g=Xe(),x=qc(y=>{if(!e)throw new Error("No knowledge assistant was defined");return l(null),t({assistantCode:e,input:y,threadId:o,onNewThreadId(S){s(S)}})},{onSuccess(y){var S;g("Assistant response displayed",{evaluationId:y.evaluationId,assistantCode:e,assistantOutput:y.answer.answer,input:y.question,sources:(S=y.answer.sources)!=null?S:[]}),f(!1)},onError(y){var S;l((S=y.message)!=null?S:"Unknown error")}}),v=y=>L(null,null,function*(){a(!0),p(y),yield x.call(y),a(!1),p(null)}),h={isEnabled:!!e,assistantCode:e,isSubmitting:i,threadId:o,pendingInput:d,errorMessage:c,onSubmit:v,onReset(){o&&m(CP(o)),l(null),s(null),e&&g("Assistant thread reset",{threadId:o!=null?o:void 0,assistantCode:e})}};return(0,Qe.useEffect)(()=>{n&&h.isEnabled&&v(n)},[n]),(0,ge.jsx)(im.Provider,{value:h,children:r})},lm=()=>{let e=ie(Da),t=F("WidgetKnowledgeAssistant",sm),n=(0,Qe.useContext)(im),r=(0,Qe.useRef)(null),[o,s]=(0,Qe.useState)(""),i=c=>{s(c.target.value)},a=c=>{c.preventDefault(),n.onSubmit(o).then(()=>{var l;r.current&&((l=r.current)==null||l.focus(),s(""))})};return n.isEnabled?(0,ge.jsxs)("form",{className:t.form,onSubmit:a,children:[(0,ge.jsx)("input",{ref:r,className:t.formInput,placeholder:e("inputPlaceholder"),type:"text",disabled:n.isSubmitting,value:o,onChange:i}),(0,ge.jsx)("button",{type:"submit",disabled:n.isSubmitting||o==="",className:t.formSubmit,children:e("submitLabel")})]}):null},cm=({title:e,emptyState:t})=>{var m,g;let n=ie(Da),r=Xe(),o=F("WidgetKnowledgeAssistant",sm),s=(0,Qe.useRef)(null),i=(0,Qe.useContext)(im),a=(g=K(w0((m=i.threadId)!=null?m:-1)))!=null?g:[],c=te("hasKeyboardInput"),l=un(),u=(x,v)=>{Tr(x),i.assistantCode&&r("Assistant response copied",{assistantCode:i.assistantCode,assistantOutput:x,copiedText: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)=>{l.send(Jr,{text:x,suggestion:{source:"assistant",sourceText:x}}),i.assistantCode&&r("Assistant response used",{assistantCode:i.assistantCode,evaluationId:v.evaluationId,assistantOutput:v.answer.answer,usedText:x})};return!i.isEnabled||(a==null?void 0:a.length)===0&&!i.isSubmitting&&!t&&!i.errorMessage?null:(0,ge.jsxs)(Qe.Fragment,{children:[(0,ge.jsx)(hr,{type:"knowledge",title:e,"data-testid":"knowledge",children:(0,ge.jsxs)(Dt,{withDivider:!0,children:[t&&a.length===0&&!i.pendingInput&&(0,ge.jsx)(p5,w({},t)),a.map((x,v)=>(0,ge.jsx)(m5,{innerRef:v===a.length-1?s:void 0,item:x,hasKeyboardInput:c,onCopy:h=>u(h,x),onUse:h=>p(h,x),onSourceClick:h=>f(h,x)},`${x.question}_${x.answer}_${v}`)),i.pendingInput&&(0,ge.jsx)(Zp,{title:i.pendingInput}),i.errorMessage&&(0,ge.jsx)(gI,{message:i.errorMessage})]})}),a.length>0&&(0,ge.jsx)("div",{className:o.resetContainer,children:(0,ge.jsx)(de.Button,{disabled:i.threadId===null||i.isSubmitting,onClick:d,children:n("resetLabel")})})]})};var vI=b(X());var g5=/(https?:\/\/[^\s]+)/,yI=e=>e.split(" ").find(t=>g5.test(t));var Un=b(R()),h5=({suggestion:e,lines:t,onUse:n})=>{var f;let r=e.text||e.url||e.message,o=yI(r),s=ie(Mc),i=te("showImages"),a=te("fallbackImage"),c=te("hasKeyboardInput"),l=d=>{d.preventDefault(),d.stopPropagation(),c&&n(r)},u=(0,vI.useCallback)(d=>{window.open(o,"_blank"),d.stopPropagation(),d.preventDefault()},[o]);return(0,Un.jsxs)(de,{onClick:c?l:void 0,"data-testid":"edit-suggestion",children:[(0,Un.jsxs)(he,{children:[i&&e.image&&(0,Un.jsx)(he.Image,{src:Fp(e,"small",a||void 0),title:e.title}),(0,Un.jsxs)(he.Content,{children:[e.title&&(0,Un.jsx)(he.Title,{"data-testid":"widget-suggestion-title",children:e.title}),e.searchKeywords&&((f=e.searchKeywords)==null?void 0:f.length)>0&&(0,Un.jsx)(de.Labels,{labels:e.searchKeywords}),(0,Un.jsx)(he.Content,{cropText:t==="single",lineClamp:t==="multiple",children:r})]})]}),(0,Un.jsxs)(de.Actions,{children:[o&&(0,Un.jsx)(de.ActionButton,{onClick:u,label:s("visitUrl")}),c&&(0,Un.jsx)(de.ActionButton,{primary:!0,onClick:l,label:s("useSuggestion")})]})]})},xI=h5;var ru=b(R()),y5=({lines:e,suggestions:t})=>{let n=un(),r=(o,s)=>{n.send(Jr,{text:o,suggestion:P(w({},s),{source:s.source,sourceText:s.text})})};return(0,ru.jsx)(ru.Fragment,{children:t.map(o=>(0,ru.jsx)(xI,{suggestion:o,lines:e,onUse:s=>r(s,o)},o.text||o.url||o.message))})},SI=y5;var ou={};yt(ou,{enUS:()=>v5,nlNL:()=>x5});var v5={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"}]},x5={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 Fa={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 ae=b(R()),wI=(e,t)=>{let n=K(bt);(0,us.useEffect)(()=>n?t.every(r=>!!r)?e():()=>{}:()=>{},[...t,n])},S5=({onLogIn:e})=>{let t=F("Widget",Fa),n=te("isEmbedded"),r=te("adminUrl");return(0,ae.jsx)("div",{className:t.loginText,children:(0,ae.jsx)("div",{children:(0,ae.jsx)(Cp,{isEmbedded:n,loginUrl:r,onLogIn:e})})},"login")},j0=({text:e})=>{let t=F("Widget",Fa);return(0,ae.jsx)("div",{className:t.stateText,children:(0,ae.jsx)("div",{children:(0,ae.jsx)("p",{children:e})})},"notification")},w5=()=>{let e=ie(ou),t=ve(),n=F("Widget",Fa),r=te("showSearch"),o=te("isEmbedded"),s=K(ka("/admin/")),i=un(),a=te("productName"),c=Xe();return wI(()=>{if(o)return t(E0()),()=>{t(IP())}},[t,o]),!r&&!s?null:(0,ae.jsxs)("div",{className:n.shortcutList,children:[r&&(0,ae.jsx)(de.Button,{"data-testid":"shortcut-search","aria-label":e("linkSearch"),className:n.shortcut,icon:(0,ae.jsx)(Ca,{}),onClick:()=>{i.send("ShowCommandPalette",{isOpen:!0}),c("open search",{via:"widget-shortcut"})},children:e("linkSearch")}),s&&(0,ae.jsx)(de.Button,{as:"a",target:"_blank",icon:(0,ae.jsx)(_P,{}),href:s,"data-testid":"shortcut-studio-login","aria-label":e("linkStudioLogin",{productName:a}),className:n.shortcut,rel:"noreferrer",onClick:()=>{c("open my deepdesk",{via:"widget-shortcut"})},children:e("linkStudioLogin",{productName:a})})]})},b5=({title:e,content:t})=>{let n=ie(ou),[r,o]=(0,us.useState)(!0);return r?(0,ae.jsx)(hr,{"data-testid":"custom-data-banner",type:"custom-data-banner",title:e,children:(0,ae.jsx)(Dt,{withDivider:!0,children:(0,ae.jsxs)(de,{children:[(0,ae.jsx)(he,{children:(0,ae.jsx)(he.Content,{children:(0,ae.jsx)(ai,{content:t})})}),(0,ae.jsx)(de.ButtonsContainer,{children:(0,ae.jsx)(de.Button,{onClick:()=>o(!1),children:n("close")})})]})})}):null},E5=()=>{let e=ve(),t=K(mc),n=K(Y1),r=K(LP),o=K(d1),s=K(fp),i=K(yp),a=K(Us),c=K(Cr);return(0,us.useEffect)(()=>{!!o&&!n&&J.warn("Custom data provided, but no schema.")},[o,n]),wI(()=>{t.forEach(({type:l})=>{l==="entities"?e(cr()):Iu.includes(l)||e(ur(l))})},[e,c,a]),(0,us.useEffect)(()=>{r.length>0&&!t.some(l=>l.type==="cues")&&J.warn("Received cues, but cues are not configured in widget.")},[t,r]),(0,ae.jsx)(us.Fragment,{children:t.map(({type:l,title:u,amount:f,lines:d,schema:p,property:m})=>{var g,x;switch(l){case"entities":return s&&s.length>0&&(0,ae.jsx)(hr,{type:l,title:u,"data-testid":`type-${l}`,children:(0,ae.jsx)(MP,{entities:s})},l);case"cues":return r&&r.length>0&&(0,ae.jsx)(hr,{type:l,title:u,"data-testid":`type-${l}`,children:(0,ae.jsx)(Dt,{withDivider:!0,children:(0,ae.jsx)(uI,{cues:r})})},l);case"custom-data-banner":return o&&m&&o[m]&&(0,ae.jsx)(b5,{title:u,content:String(o[m])},l);case"custom-data":return o&&p&&(0,ae.jsx)(hr,{type:l,title:u,"data-testid":`type-${l}`,children:(0,ae.jsx)(Dt,{withDivider:!0,children:(0,ae.jsx)(fI,{data:o,schema:p})})},l);default:return((x=(g=i[l])==null?void 0:g.suggestions)==null?void 0:x.length)>0&&(0,ae.jsx)(hr,{type:l,title:u,"data-testid":`type-${l}`,children:(0,ae.jsx)(Dt,{withDivider:!0,children:(0,ae.jsx)(SI,{lines:d,contentType:l,suggestions:i[l].suggestions.slice(0,f)||[]})})},l)}})})},K0=({children:e})=>{let t=F("Widget",Fa);return(0,ae.jsx)("div",{className:t.footer,children:e})},G0=({children:e})=>{let t=F("Widget",Fa);return(0,ae.jsx)("div",{className:t.root,"data-testid":"widget",children:e})},C5=({onLogIn:e,knowledgeAssistOptions:t={},assistantOptions:n={transcript:"in-memory-transcript",expectFormat:"json-schema:cues"}})=>{var f;let r=ie(ou),o=K(ta),s=K(bt),i=K(YC),a=K(Us),c=K(q1("knowledge-assist")),l=K(X1),u=K(Q1);return o===!1?(0,ae.jsx)(j0,{text:r("notSupported")}):s===!1?(0,ae.jsx)(S5,{onLogIn:e}):s===null?(0,ae.jsx)(j0,{text:r("waiting")}):!i||!a?(0,ae.jsx)(j0,{text:r("waitingForConversation")}):(0,ae.jsx)(G0,{children:(0,ae.jsxs)(am,{initialQuestion:t.initialQuestion,assistantCode:(f=l!=null?l:u)!=null?f:void 0,evaluateKnowledgeAssistFn:u?Kc:Gc,children:[(0,ae.jsxs)(wi,{children:[(0,ae.jsx)(w5,{}),(0,ae.jsx)(E5,{}),c&&(0,ae.jsx)(cm,{title:c.title,emptyState:t.emptyState})]}),(0,ae.jsxs)(K0,{children:[c&&(0,ae.jsx)(lm,{}),(0,ae.jsx)(VP,{assistantOptions:n})]})]})})},bI=C5;function za(e){let t=new Range;return t.selectNodeContents(e),t}function EI(e,t,n){try{return ds(e,t,n),!0}catch(r){return!1}}function um(e){return"tagName"in e&&(e.tagName==="DIV"||e.tagName==="P")}function dm(e){return"tagName"in e&&e.tagName==="BR"}var su=/[\u200B-\u200D\uFEFF]/g;function ds(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(c,l){let u=-1,f=/[\u200B-\u200D\uFEFF]/;if(!f.test(c))return l;for(let d=0;d<=c.length;d++)if(f.test(c[d])||u++,u===l)return d;throw new Error("Offset out of range")}function a(c){switch(c.nodeType){case Node.TEXT_NODE:{let l=c.textContent,u=l.replace(su,""),f=o+u.length,d=t>=o&&t<=f,p=n>=o&&n<=f;if(d){let m=i(l,t-o);m===0&&!p?r.setStartBefore(c):r.setStart(c,m)}p&&(r.setEnd(c,i(l,n-o)),s=!0),o=f;break}case Node.ELEMENT_NODE:{if(dm(c)&&(o===t&&r.setStartBefore(c),o++,o===n)){r.setEndAfter(c),s=!0;return}for(let u=0;u<c.childNodes.length&&(a(c.childNodes[u]),!s);u++);let l=c.lastChild;um(c)&&l&&!um(l)&&!dm(l)&&o++;break}default:break}}if(a(e),r.startContainer===document)throw new Error("Offsets out of bound");return r}function iu(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,c,l=0;function u(f){let d=f===e,p=f===n,m=f===o;switch(f.nodeType){case Node.TEXT_NODE:{let g=f.textContent;p&&(a=l+g.substring(0,r).replace(su,"").length),m&&(c=l+g.substring(0,s).replace(su,"").length),l+=g.replace(su,"").length;break}case Node.ELEMENT_NODE:{if(dm(f)&&f.nextSibling){l++;break}!d&&um(f)&&f.previousSibling&&l++;for(let g=0;g<f.childNodes.length;g++){let x=p&&g===r,v=m&&g===s;if(x&&(a=l),v&&(c=l),c!==void 0||((!x||!i)&&u(f.childNodes[g]),m&&g===s-1&&(c=l),c!==void 0))break}m&&(c=l);break}default:break}}if(u(e),c===void 0)throw new Error("Could not determine start and end");return{start:a!=null?a:c,end:c}}function au(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,c="";function l(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 m=d?r:0,g=p?s:void 0;c+=u.textContent.replace(su,"").substring(m,g);break}case Node.ELEMENT_NODE:{if(!i&&a===1&&dm(u)&&u.nextSibling){c+=`
|
|
81
81
|
`;break}!f&&!i&&a===1&&um(u)&&u.previousSibling&&(c+=`
|
|
82
|
-
`);let m=d?r:0,g=p?Math.min(s,u.childNodes.length):u.childNodes.length;for(let x=m;x<g&&(l(u.childNodes[x]),a!==2);x++);break}default:break}p&&(a=2)}return l(e),c}var CI=(i=>(i.CUT="Cut",i.BACKSPACE="Backspace",i.DELETE="Delete",i.ERASEEOF="EraseEof",i.UNDO="Undo",i.CLEAR="Clear",i))(CI||{}),So=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();Yo(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(CI).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 TI(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var ci=class extends So{constructor(){super(...arguments);this.lastKnownSelection=null}getRootNode(){return this.element.getRootNode()}getText(){let n=new Range;return n.selectNodeContents(this.element),au(this.element,n)}getHTML(){return this.element.innerHTML||""}getRange(){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=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!TI(r)&&(n.insertNode(this.element.ownerDocument.createTextNode("\u2060")),r=n.getBoundingClientRect(),n.deleteContents(),!TI(r))?null:{top:r.top+r.height,left:r.left}}getSelection(){let n=this.getRange();if(n)return iu(this.element,n);let r=this.lastKnownSelection;if(r&&EI(this.element,r.start,r.end))return r;let o=za(this.element);return o.collapse(!1),iu(this.element,o)}getSelectedText(){let{start:n,end:r}=this.getSelection();return au(this.element,ds(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 T5=["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 kI(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",T5.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 c=e.getBoundingClientRect(),l={top:c.top-e.scrollTop+a.offsetTop+Number.parseInt(s.borderTopWidth)+a.offsetHeight,left:c.left-e.scrollLeft+a.offsetLeft+Number.parseInt(s.borderLeftWidth)};return i.removeChild(r),l}var ui=class extends So{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 kI(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 RI(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,c])=>{i.searchParams.append(a,c)}),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 k5(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch(t){return e}}var q0=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()}},Y0=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.disposeHandlers=[];this.iframe=RI(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()}},X0=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(),J.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 Y0(t,this.deepdeskUrl,{debug:!0}):new q0(t),r=o=>{var i,a;if(o.origin!==this.deepdeskUrl)return;let s=k5(o.data);typeof s!="object"||s.type!=="event"||s.channel!==t||(J.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;J.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)}},PI=X0;function R5(e){return e.replace(/(_\w)/g,t=>t[1].toUpperCase())}function Fe(e){return Array.isArray(e)?e.map(Fe):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>P(w({},t),{[R5(n)]:Fe(e[n])}),{}):e}function P5(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function Mt(e){return Array.isArray(e)?e.map(Mt):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>P(w({},t),{[P5(n)]:Mt(e[n])}),{}):e}var Ha=class extends Error{constructor(n,r){super(n);this.body=r;this.name="CustomError"}};var Q0=e=>new Promise(t=>{setTimeout(t,e)});var Ba=class extends Ha{constructor(){super(...arguments);this.name="ClientError"}},J0=class extends Ha{constructor(){super(...arguments);this.name="ServerError"}},Z0=new Map;function I5(e){return L(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:(J.warn("Unexpected response body:",n.slice(0,20)),JSON.parse(n))})}var fs=class fs{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,c=n.method===void 0||n.method.toLowerCase()==="get",T=n,{useCache:l=!1,abortLatest:u=!1,attempts:f=1,retryDelay:d=500,refreshTokenOn401:p=!0,retryOnError:m=k=>k instanceof TypeError,retryOnResponse:g=k=>k.status>=500,version:x=null}=T,v=oe(T,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]);if(l){if(!c)throw new Error(`Can't use 'useCache' for ${n.method}`);if(Z0.has(i)){r(Z0.get(i));return}}let h=P(w({credentials:"include"},v),{headers:w({Accept:"application/json","Content-Type":"application/json"},v.headers)});!c&&this.csrfToken&&(h.headers=P(w({},h.headers),{"X-CSRFToken":this.csrfToken})),typeof x=="string"&&(h.headers=P(w({},h.headers),{"X-Deepdesk-API-Version":x}));let y=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=()=>L(this,null,function*(){return y--,a(i,h).then(k=>L(this,null,function*(){return g(k)&&!s.isAborted&&y>0?(yield Q0(d),E()):k.status===401&&p===!0&&S===!1?(S=!0,yield this.refreshToken(),E()):k})).catch(k=>L(this,null,function*(){if(m(k)&&!s.isAborted&&y>0)return yield Q0(d),E();throw k}))});E().then(k=>L(this,null,function*(){let I=yield I5(k);if(delete this.latestRequestByUrl[i],k.status>=500){o(new J0("Server Error",I));return}if(k.status===401){o(new Ba("Unauthorized",I));return}if(k.status===403){o(new Ba("Forbidden",I));return}if(k.status===404){o(new Ba("Not Found",I));return}if(k.status>=400){o(new Ba("Bad Request",I));return}l&&Z0.set(i,I),r(I)})).catch(k=>{o(k)})})}validateToken(){return L(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 fs.refreshingToken||(fs.refreshingToken=this.get("/apis/admin/session/refresh/",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{fs.refreshingToken=null},1e3*60)})),fs.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))}};fs.refreshingToken=null;var di=fs;var II;(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={}))})(II||(II={}));function ex(e){return P(w({},Fe(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)=>L(this,null,function*(){let i=yield r(o,s);return this.handleDeepdeskVersionHeaders(i),i}))}preflight(){return L(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 L(this,null,function*(){var r;yield this.preflight(),J.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()},Mt(t)),{metadata:(r=t.metadata)!=null?r:{}}));return ex(n)})}getMe(){return L(this,null,function*(){let t=yield this.client.get("/apis/admin/session/me/");return Fe(t)})}postIdentity(t){return L(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/me/identities/",Mt(t))})}patchMe(t){return L(this,null,function*(){yield this.preflight();let n=yield this.client.patch("/apis/admin/session/me/",Mt(t));return Fe(n)})}getProfile(t){return L(this,null,function*(){let n=yield this.client.get(`/apis/admin/profiles/${t}/`,{useCache:!0});return Fe(n)})}getKnowledgeAssistant(t){return L(this,null,function*(){let n=yield this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{useCache:!0});return Fe(n)})}getContentTypes(){return L(this,null,function*(){let t=yield this.client.get("/apis/admin/content-types/",{useCache:!0});return Fe(t)})}getAccount(){return L(this,null,function*(){let t=yield this.client.get("/apis/admin/account/",{useCache:!0});return Fe(t)})}getPlatformConfig(t){return L(this,null,function*(){let n=t!==void 0?`/platform/config/${t}/`:"/platform/config/",{config:r}=yield this.client.get(n,{useCache:!0});return Fe(r)})}checkUserExists(t){return L(this,null,function*(){let{exists:n}=yield this.client.get(`/apis/admin/users/exists?external_id=${t}`,{version:"v1"});return n})}getConversationByExternalId(r){return L(this,arguments,function*(t,n={}){yield this.preflight(),J.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 J.info(`Successfully retrieved conversation ${i.id} for session ${t}`),ex(i)})}isConversationSupported(r){return L(this,arguments,function*(t,n={}){J.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 L(this,null,function*(){var s;yield this.preflight();let r=Mt(n);n.metadata&&(r.metadata=(s=n.metadata)!=null?s:{});let o=yield this.client.put(`/api/v2/conversations/${t}`,r);return ex(o)})}postMessages(t,n){return L(this,null,function*(){yield this.preflight(),yield this.client.post(`/api/v2/conversations/${t}/messages`,n.map(r=>P(w({},Mt(r)),{metadata:r.metadata})))})}sendEvent(t,n){return L(this,null,function*(){yield this.preflight();let a=n,{data:r}=a,o=oe(a,["data"]),s=Object.entries(this.latestReceivedDeepdeskVersions).reduce((c,[l,u])=>P(w({},c),{[l]:u}),{}),i=["platform","agentId","agentName","agentEmail","conversationId"].reduce((c,l)=>(o[l]&&(c[l]=o[l]),c),{});return this.client.post("/api/v2/events",Mt(P(w(w({},s),i),{data:r,name:t})),{version:"v2"})})}getEntities(t){return L(this,null,function*(){return yield this.preflight(),yield this.client.post("/api/v2/entities",{messages:t.filter(r=>r.text)})})}getTemporaryExchangeToken(){return L(this,null,function*(){return(yield this.client.get("/apis/admin/session/exchange-token/")).jwt})}exchangeTokenForAccessCookie(t){return L(this,null,function*(){return this.client.post("/apis/admin/session/jwt/",{jwt:t}).catch(n=>{throw J.warn(`Invalid token '${t}'`),n})})}authenticateWithKey(t,n){return L(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/api-key/",Mt(n),{refreshTokenOn401:!1,headers:{apikey:t}})})}getTextSuggestions(o){return L(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}`,Mt(n),{abortLatest:!0})).map(i=>P(w({},Fe(i)),{text:i.text||i.url||i.message,source:r,type:r})).filter((i,a,c)=>a===c.findIndex(l=>l.text===i.text))})}isLoggedIn(){return L(this,null,function*(){return yield this.preflight(),this.client.validateToken()})}getAutocompleteSuggestions(t,n){return L(this,null,function*(){return yield this.preflight(),(yield this.client.post(`/api/v2/conversations/${t}/autocomplete`,Mt(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 L(this,null,function*(){let n=yield this.client.get(`/api/v2/profiles/${t}/pinned-messages`,{abortLatest:!0});return Fe(n).map(r=>P(w({},r),{text:r.message,source:"sticky-messages",type:"pinned-message"}))})}getStyleSuggestions(t){return L(this,null,function*(){let n=yield this.client.post("/api/v2/style-suggestions",Mt(t),{abortLatest:!0,version:"v2"});return Fe(n)})}search(t){return L(this,null,function*(){let n=yield this.client.post(`/api/v2/profiles/${t.profile}/search`,Mt(t));return Fe(n)})}knowledgeAssist(s,i,a){return L(this,arguments,function*(t,n,r,o={}){yield this.preflight();let c=yield this.client.post(`/api/knowledge-assist/assistants/${r}/search`,Mt({question:t.question,doNotKnowAnswer:t.doNotKnowAnswer,customerInstruction:t.customerInstruction,chatHistory:n.map(l=>({question:l.question,answer:l.answer.answer})),agentId:o.agentId,conversationId:o.conversationId}),{version:"v2"});return Fe(c)})}requestLoginByEmail(t){return L(this,null,function*(){yield this.preflight();let n=yield this.client.post("/apis/admin/session/passwordless/request/",{email:t});return Fe(n)})}requestPasswordlessToken(){return L(this,null,function*(){let t=yield this.client.get("/apis/admin/session/passwordless/request/");return Fe(t.token)})}getCsrfToken(){return L(this,null,function*(){let{token:t}=yield this.client.get("/apis/admin/session/csrf/");return t})}verifyLoginToken(t){return L(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/login/",{token:t});return Fe(n)})}evaluateAssistant(t,n){return L(this,null,function*(){var a;yield this.preflight();let r=new URLSearchParams,{expectFormat:o="text"}=n||{};if(o.startsWith("json-schema:")){let c=o.replace("json-schema:","");r.append("expect_response_format","json-schema"),r.append("expect_response_format_schema",c)}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 Fe(i)})}createAssistantThread(t){return L(this,null,function*(){yield this.preflight();let{assistantCode:n}=t,r=yield this.client.post(`/apis/admin/assistants/${n}/threads/`,{});return Fe(r)})}postMessageToAssistantThread(t){return L(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 Fe(s)})}translateMessages(t){return L(this,null,function*(){yield this.preflight();let n=yield this.client.post("/api/v2/translate",Mt(t));return Fe(n)})}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),s=o.match(uS);if(!n||!s)return;let i=s[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[i];a&&n&&a!==n&&J.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[i]=n})}};fi.exchangeTokenPromise=null;var wo=fi;var AI={startTime:null,stopTime:null},LI=e=>e.handlingTime,OI=be({name:"handlingTime",initialState:AI,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(it,()=>AI)}}),{handlingTimeStart:MI,handlingTimeStop:fm,handlingTimeReset:_I}=OI.actions,NI=OI.reducer;var DI=(e={})=>{let t=w({onAuthError:ea(!1)},e);return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var pm={list:{keywordMatches:[]},fetchState:"idle"};var pi=fe("styleSuggestions/getAll",(n,r)=>L(null,[n,r],function*({text:e},t){var c;let{deepdeskAPI:o}=t.extra,s=t.getState(),{showStyleSuggestions:i}=s.settings,a=(c=s.conversation.current)==null?void 0:c.profileCode;if(!i)return pm.list;if(!a)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:a,message:e})})),A5=be({name:"styleSuggestions",initialState:pm,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",Yo(t.list,n.payload)||(t.list=n.payload)}).addCase(zs,t=>{t.list=pm.list}).addCase(it,()=>pm)}}),FI=A5.reducer;var zI=(e={})=>{let t,n=!0,r=w({getStyleSuggestions:pi,debounce:500},e);return o=>s=>i=>{var p;let a=o.getState().input.text,c=s(i),l=o.getState();if(l.auth.isLoggedIn!==!0)return c;let{showStyleSuggestions:u}=l.settings;if(!((p=l.conversation.current)==null?void 0:p.id)||!u)return c;let{text:d}=l.input;return d===a&&!n||(clearTimeout(t),d==="")||(t=setTimeout(()=>{n=!1,o.dispatch(r.getStyleSuggestions({text:d}))},e.debounce)),c}};function L5(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end}var HI=(e={})=>{let t=w({getTextSuggestions:ur,getAutocompleteSuggestions:Nc,debounce:200,check:Pr},e),n;return r=>o=>s=>{var g;let{input:i}=r.getState(),a=o(s),c=r.getState();if(c.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:l,showTabCompletion:u}=c.settings,f=(g=c.conversation.current)==null?void 0:g.id,d=s.type===vp.toString();if(!f||!l&&!u)return a;let{input:p}=c;return L5(p,i)&&!d||(clearTimeout(n),!t.check(c))||(n=setTimeout(()=>{let x=na(c);x===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(x))},d?0:t.debounce)),a}};var BI=pi.fulfilled.toString();function O5(e,t){let n=new Set([...t.keywordMatches.map(o=>o.keyword)]),r=[];return n.forEach(o=>{let s=e.keywordMatches.filter(c=>c.keyword===o),i=t.keywordMatches.filter(c=>c.keyword===o),a=i.length-s.length;a<=0||r.push(...i.slice(0,a))}),r}var UI=e=>t=>n=>r=>{var l;if(r.type!==BI){n(r);return}let o=t.getState().styleSuggestions.list;n(r);let s=t.getState(),i=s.styleSuggestions.list,a=(l=s.conversation)==null?void 0:l.current;if(o===i)return;let c=O5(o,i);r.type===BI&&c.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:c}})};var M5=Qd({assistants:RP,auth:HC,conversation:XC,contentTypes:j1,passwordlessToken:AP,entities:Kk,handlingTime:NI,info:h1,input:l1,settings:MC,profile:Z1,search:b1,styleSuggestions:FI,ui:vR,textSuggestions:nR});function VI(e){return iC({reducer:M5,middleware:t=>{var r;let n=t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI}},serializableCheck:!1}).concat(DI()).concat(HI({debounce:200})).concat(zI({debounce:500})).concat(UI(e.deepdeskAPI));return((r=e.middleware)!=null?r:[]).reduce((o,s)=>o.concat(s),n)},preloadedState:e.preloadedState})}var _5=e=>{var t,n;return(n=(t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())!=null?n:"unknown"},N5=e=>t=>n=>r=>{var a,c;let o=t.getState(),s=Ji("inlineSuggestions")(o);switch(r.type){case ea.toString():{!r.payload&&e.emit("logout",void 0);break}case cr.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 zs.toString():e.logSendMessage(r.payload);break;case qp.toString():e.emit("call-to-action",{cue:r.payload});break;case dr.fulfilled.toString():r.isBroadcasted||e.broadcast(Oy,r,!1);break;default:break}let i=n(r);switch(r.type){case zs.toString():e.handleAfterSendMessage(r.payload);break;case Fc.toString():e.onUpdateShowTabHint(r.payload);break;case fm.toString():e.logHandlingTime();break;case oa.toString():e.broadcast(Jl,r);break;case Fs.toString():e.broadcast(Jl,r);break;case Yp.toString():t.dispatch(Fs({source:"assistant",assistantCode:r.payload.code}));break;case"analytics/logEvent/fulfilled":{let l=o.assistants.cues.find(u=>u.code===r.meta.arg.data.assistantCode);e.emit("event",P(w({},r.meta.arg),{cue:l}));break}case gf.toString():{let{start:l,end:u}=o.input.selection;e.emit("replace",P(w({},r.payload),{replace:r.payload.replace==="selection"?{start:l,end:u}:{start:0,end:u}}));break}case er.toString():{let{start:l,end:u}=o.input.selection;e.emit("select-suggestion",P(w({type:_5(r.payload.suggestion)},r.payload),{replace:r.payload.replace==="selection"?{start:l,end:u}:{start:0,end:u}})),s&&t.dispatch(Xo([]));break}case hf.toString():e.emit("select-image",r.payload),e.sendEvent("Image attached",{conversationId:(c=o.conversation.current)==null?void 0:c.id,data:{path:r.payload.suggestion.image,title:r.payload.suggestion.title}});break;case Xo.toString():{s&&r.payload.length>0&&t.dispatch(yf(0));break}case go.fulfilled.toString():{if(r.isBroadcasted)break;e.broadcast(Jl,r,!1),e.emit("summary-generated",{summary:r.payload.output});break}default:break}return i},WI=N5;function tx(e){return e.toISOString().replace("T"," ").replace("Z","")}var D5=(e,t)=>t.version,$I=Bt([sa,Cr,LI,D5],(e,t,n,r)=>{if(!t)return J.warn("No conversationId for handling time metrics"),null;let{startTime:o,stopTime:s}=n;return!o||!s?(J.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:tx(o),timeStop:tx(s)}});function jI(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 nx(e,t){var s;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return nx(r,t);let o=(s=e.ownerDocument.defaultView)==null?void 0:s.frameElement;return o?nx(o,t):null}function rx(e,t){return nx(e,t)}function KI(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function F5(e){return typeof e=="object"&&e!==null&&"tagName"in e}function mm(e){return F5(e)&&(oi(e)||kp(e))}var qI,_r=new Map,z5=["bottom","height","left","right","top","width"],GI=(e,t)=>!e&&!t?!1:e&&!t||!e&&t?!0:z5.some(n=>e[n]!==t[n]);function YI(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,...YI(t)]:[]}function XI(e,t){return!e||!t?null:P(w({},e),{top:e.top+t.top,left:e.left+t.left})}var gm=!1,QI=()=>{gm=!0;let e=[];if(_r.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),_r.delete(n);return}let r=n.getBoundingClientRect();GI(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{let n=t.parentRects?t.parentRects.reduce(XI,t.rect):t.rect;GI(n,t.totalRect)&&t.callbacks.forEach(r=>r(n)),t.totalRect=n}),_r.size===0){gm=!1;return}qI=window.requestAnimationFrame(QI)};function ox(e,t){let n=YI(e),r=[],o=n.map((s,i)=>ox(s,a=>{r[i]=a;let c=_r.get(e);if(!c)return;let l=r.reduce(XI,c.rect);c.callbacks.forEach(u=>u(l))}));return{observe(s=!0){if(o.forEach(i=>i.observe(!1)),_r.has(e)){let i=_r.get(e);i.callbacks.push(t),i.rect&&t(i.rect)}else _r.set(e,{rect:void 0,callbacks:[t],parentRects:r});s&&!gm&&QI()},unobserve(){o.forEach(i=>i.unobserve());let s=_r.get(e);if(s){let i=s.callbacks.indexOf(t);i>=0&&s.callbacks.splice(i,1),s.callbacks.length||_r.delete(e),_r.size||(cancelAnimationFrame(qI),gm=!1)}}}}var ZI,Nr=new Map,JI=()=>{Nr.forEach((e,t)=>{if(!t.isConnected){Nr.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)))}),Nr.size!==0&&(ZI=window.requestAnimationFrame(JI))};function eA(e,t){return{observe(){let n=Nr.size===0;Nr.has(e)?Nr.get(e).callbacks.push(t):Nr.set(e,{visible:void 0,callbacks:[t]}),n&&JI()},unobserve(){let n=Nr.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||Nr.delete(e),Nr.size||cancelAnimationFrame(ZI)}}}}var sx=["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 ix(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function Ua(e){return Number.parseFloat(e)}function hm(e){return Math.round(e*1e6)}function tA(e){return e/1e6}function ax(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=Ua(e.width),s=Ua(e.borderLeftWidth),i=Ua(e.borderRightWidth),a=Ua(e.paddingRight),c=tA(hm(o)-hm(s)-hm(i)),l=tA(hm(r));if(c-l>2){let u=c-l;n.style.paddingRight=`${a+u}px`}}function lu(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",ri(n);let r=window.getComputedStyle(e),o=!0,s=()=>{n.scrollTop=e.scrollTop};ix(r,n,sx),ax(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",s));let i=eA(e,()=>{ix(r,n,sx),ax(r,e,n),s(),setTimeout(s,0)}),a,c=!0,l=ox(e,d=>{if(d===null){t.onRemove&&t.onRemove(),n.remove();return}if(!c&&t.onMoveStart&&(Promise.resolve().then(()=>t.onMoveStart()),c=!0),clearTimeout(a),a=setTimeout(()=>{t.onMoveEnd&&t.onMoveEnd(),c=!1},200),d.height===0&&d.width===0){if(o===!0)return;t.onHide&&t.onHide(),n.style.display="none",o=!0;return}if(ix(r,n,sx),ax(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(),m=window.getComputedStyle(t.closestScrollElement),g=Ua(m.borderTopWidth),x=Ua(m.borderBottomWidth),v=p.top+g-d.top,h=d.top+d.height+-(p.top+p.height-x);n.style.clipPath=`inset(${v}px 0px ${h}px 0px)`}o&&(n.style.display="block",t.onShow&&t.onShow(),o=!1)});return t.appendTo?t.appendTo.appendChild(n):(f=e.parentElement)==null||f.appendChild(n),l.observe(),i.observe(),[n,()=>{e.removeEventListener("scroll",s),l.unobserve(),i.unobserve(),n.remove()}]}var nA=(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){J.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function H5(e){return e.offsetParent!==null}function rA(e){if(!H5(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 ym(e,t,n=100){let r=rA(e);t({isVisible:r});let o=setInterval(()=>{let s=rA(e);s!==r&&(r=s,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var cu=class extends Error{};function B5(){let e,t;return{promise:new Promise((r,o)=>{e=r,t=o}),resolve:e,reject:t}}var vm=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 cu("Queued async function is outdated"));let o=B5();return this.queues[t][1]=o,o.promise.then(()=>n().finally(r))}};var U5={accepted:"onConversationAcceptedAssistants","new-message":"onConversationNewMessageAssistants",ended:"onConversationEndedAssistants"},oA=(e,t)=>{let n=e[U5[t]];return n&&n.length>0?n.map(r=>r.code):(J.warn(`No assistant set in profile for conversation event "${t}"`),[])};var xm=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=Fe(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 sA=nA("showTabHint",!0),Va=class Va{constructor({deepdeskUrl:t,version:n=Va.version||"unknown",locale:r="en-US",token:o,fetch:s,productName:i,createCustomChannel:a,websocketClient:c=xm}){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 vm;this.isMounted=!1;this.shouldRender=!0;this.loadProfileConfigPromise=null;let l=t.replace(/\/api$/,"");this.deepdeskApi=new wo(l,{token:o,fetch:s}),this.version=n,this.instanceId=Va.count++;let u={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[WI({broadcast:(m,g,x)=>{this.broadcastEvents.send(m,g,x)},emit:(m,g)=>this.emit(m,g),handleAfterSendMessage:m=>this.handleAfterSendMessage(m),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:m=>this.logSendMessage(m),onUpdateShowTabHint:m=>sA.update(m),sendEvent:(m,g)=>this.deepdeskApi.sendEvent(m,g)})]};this.store=VI(u),this.broadcastEvents=new PI({debug:!0,deepdeskUrl:l,eventMap:E1(this.store),createCustomChannel:a}),this.disposeHandlers.push(()=>{this.broadcastEvents.cleanup()}),this.ws=new c({url:`${l}/api/v2/me/realtime`.replace("https","wss"),reconnectInterval:25e3,shouldReconnect:()=>L(this,null,function*(){var m;return(m=bt(this.state))!=null?m:!1})}),this.whenLoggedIn(()=>this.ws.connect()),this.store.dispatch(Fc(sA.value())),this.store.dispatch(uf({locale:r,adminUrl:l,productName:i}));let f=[],d=m=>{if(!m.conversationId)return;let g=()=>{this.conversationId()===m.conversationId&&this.store.dispatch(kP(m))};this.hasConversation()?g():f.push(g)};this.ws.on("assistants::direct_response",d),this.ws.on("assistants::user_notification",d),this.ws.on("assistants::response_chunk",m=>{if(!m.conversationId)return;let g=()=>{this.conversationId()===m.conversationId&&this.store.dispatch(TP(m))};this.hasConversation()?g():f.push(g)}),this.ws.on("assistants::suggest_as_reply",m=>{if(!m.conversationId)return;let g=()=>{this.conversationId()===m.conversationId&&this.store.dispatch(oa([{text:m.payload.message,type:"text",source:"assistant",assistantCode:m.code,sourceLabel:m.name}]))};this.hasConversation()?g():f.push(g)});let p=this.whenConversationLoaded(()=>{var m;this.broadcastEvents.setExternalId((m=this.state.conversation.current)==null?void 0:m.externalId),f.forEach(g=>g()),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=Ds(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?(J.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(J.warn("Profile has not been loaded (yet)"),!0):(J.warn("No conversation loaded (yet)"),!0)}whenLoggedIn(t){if(bt(this.state))t();else{let n=this.subscribe(bt,r=>{r&&t()});this.disposeHandlers.push(()=>{n()})}}login(){return this.store.dispatch(ea(null)),this.store.dispatch(Qr()),new Promise(t=>{this.whenLoggedIn(()=>t())})}isLoggedIn(){return L(this,null,function*(){return(yield this.store.dispatch(Qr())).payload})}isConversationSupported(t,n){return L(this,null,function*(){return(yield this.store.dispatch(Ty({externalId:t,options:n}))).payload})}createConversation(t){return L(this,null,function*(){var r;return this.hasConversation()&&this.externalId()!==t.externalId&&this.resetConversation(),(yield this.store.dispatch(ff(P(w({},t),{metadata:(r=t.metadata)!=null?r:{}})))).payload})}getConversationByExternalId(t,n){return L(this,null,function*(){return this.hasConversation()&&this.externalId()!==t&&this.resetConversation(),(yield this.store.dispatch(pf({externalId:t,options:n}))).payload})}upsertConversation(t){return L(this,null,function*(){var r;return this.hasConversation()&&this.externalId()!==t.externalId&&this.resetConversation(),(yield this.store.dispatch(ky(P(w({},t),{metadata:(r=t.metadata)!=null?r:{}})))).payload})}postMessages(t){return L(this,null,function*(){yield this.store.dispatch(Ry(t))})}updateConversation(t){return L(this,null,function*(){return(yield this.store.dispatch(mf(t))).payload})}resetConversation(){this.store.dispatch(it()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}configure(t){this.store.dispatch(uf(t))}setVisitorInfo(t){this.store.dispatch(p1(t))}setCustomData(t){this.store.dispatch(m1(t))}setAgentInfo(t,n){return L(this,null,function*(){yield this.store.dispatch(Xl(w(w({},t),n)))})}setAgentSettings(t){return L(this,null,function*(){yield this.store.dispatch(Iy(t))})}getAgentSettings(){return L(this,null,function*(){return(yield this.store.dispatch(Ay())).payload})}refresh(){return L(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(vf({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()}))}notifyExternalSuggestion(t){this.store.dispatch(er(t))}evaluateAssistant(t,n){return L(this,null,function*(){var f;let u=n||{},{input:r={},transcript:o,showCuesInWidget:s=!0,includeMetadata:i,expectFormat:a}=u,c=oe(u,["input","transcript","showCuesInWidget","includeMetadata","expectFormat"]);Object.assign(r,c);let l=yield this.store.dispatch(dr({assistantCode:t,expectFormat:a||"json-schema:cues",transcript:o,includeMetadata:i,input:r,skipState:!s}));if(l.error)throw new Error(`Assistant evaluation failed: ${(f=l.payload)!=null?f:l.error.message}`);return l.payload.output})}evaluateConversationAssistant(t,n){return L(this,null,function*(){yield this.loadProfileConfig();let r=this.state.profile.data;if(!r){J.warn("Can't evaluate assistant when profile is not loaded yet.");return}let o=oA(r,t);yield Promise.all(o.map(s=>this.queues.push(s,()=>L(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 cu){J.warn(`Queued assistant "${s}" was outdated and dropped`);return}throw i})))})}getSummary(){return L(this,arguments,function*(t={}){if(!this.hasConversation())return J.warn("No conversation to create summary for."),null;if(!this.state.profile.data)return J.warn("No profile loaded yet"),null;let n=this.state.profile.data.summarizerAssistantNew;if(!n)return J.warn("No summarizer assistant set in profile"),null;let r=yield this.store.dispatch(go(P(w({},t),{assistantCode:n})));return r.error?(J.error("Error evaluating summary assistant",r.error),null):r.payload.output})}handleKeyDown(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui,{textSuggestions:o,selectedSuggestionIndex:s,selection:i}=this.state.input,{inlineSuggestions:a,showTextSuggestions:c,suggestionsPlacement:l}=this.settings,u=l==="inline"||l==="below"?"below":"above",f=o.length>0;if(this.store.dispatch(t1(Py(t))),!Pr(this.state)||t.key!=="Tab"&&!c)return;let d=()=>{n||!f||i&&(t.shiftKey||(this.store.dispatch(o1()),t.preventDefault()))},p=()=>{n||!f||a&&s<=0||i&&(t.shiftKey||(this.store.dispatch(s1()),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(yf(-1)),this.store.dispatch(ss({collapse:!0})),this.store.dispatch(hR(!0)),t.preventDefault());break}case"Tab":{t.preventDefault();let m=ra(this.state);if(!m)return;this.store.dispatch(Fc(!1)),this.store.dispatch(er({text:m.text,suggestion:m,eventMetrics:{inputType:"tab"},replace:"until-selection-end"}));break}case" ":{if(this.settings.inlineSuggestions||this.state.input.selectedSuggestionIndex===-1)return;let m=ra(this.state);if(!m)return;this.store.dispatch(er({text:m.text,suggestion:m,eventMetrics:{inputType:"space"},replace:"until-selection-end"}));break}case"Enter":{if(this.settings.inlineSuggestions||t.shiftKey||this.state.input.selectedSuggestionIndex===-1)return;let m=ra(this.state);if(!m)return;this.store.dispatch(er({text:m.text,suggestion:m,eventMetrics:{inputType:"enter"},replace:"until-selection-end"})),t.preventDefault();break}default:}n&&r&&this.store.dispatch(ss({collapse:!1}))}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(Xo([]))}handlingTimeStart(){this.state.handlingTime.startTime||(J.info("Start handling time"),this.store.dispatch(MI()))}handlingTimeStop(){this.state.handlingTime.startTime&&(J.info("Stop handling time"),this.store.dispatch(fm()))}logSendMessage(t){let n=jI(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=$I(this.state,{version:this.version});t&&(this.deepdeskApi.sendEvent("Handling Time",{conversationId:this.conversationId(),data:t}),this.store.dispatch(_I()))}notifySubmit(t={}){var n;this.shouldAbort()||(this.store.dispatch(zs((n=t.text)!=null?n:this.state.input.text)),this.store.dispatch(a1()))}emit(t,n){let r=this.eventListeners[t];r&&r.forEach(o=>{try{o(n)}catch(s){J.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),J.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(g1(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]=lu(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[c,l]=lu(s,{appendTo:document.body,onMoveStart:()=>{o.style.display="none"}});c.dataset.testid=n,c.style.zIndex="2",c.appendChild(r),this.unmountHandlers.push(()=>{l()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return ri(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),J.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()?(J.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(i1(r.metrics))):J.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(!mm(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,c=oe(d,["customStyles","closestScrollSelector","floatingMenuParent","appendOverlayTo","inputMediator"]),l={customStyles:r,closestScrollSelector:o,floatingMenuParent:s,appendOverlayTo:i};this.configure(c),this.settings.automaticHandlingTime&&this.setupHandlingTime(t),ri(t),this.inputMediator=a||(oi(t)?new ui(t):new ci(t)),this.inputMediator.on("change",({plainText:p,rawHTML:m})=>{this.store.dispatch(vf({text:p,html:m}))}),this.inputMediator.on("keyup",p=>{this.store.dispatch(n1(Py(p)))}),this.inputMediator.on("keydown",p=>{this.handleKeyDown(p)}),this.inputMediator.on("paste",({pastedText:p,selectionText:m})=>{this.store.dispatch(r1({text:p,selectionText:m}))}),this.inputMediator.on("cut",({selectionText:p})=>{this.store.dispatch(e1(p))});let u;this.inputMediator.on("selection",p=>{clearTimeout(u),p===null?u=setTimeout(()=>{p!==null&&this.store.dispatch(xf(p))},500):this.store.dispatch(xf(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(wp(!1))}),this.inputMediator.on("focus",()=>{this.store.dispatch(wp(!0))}),this.renderSuggestions(t,l),this.subscribe(Ji("inlineSuggestions"),()=>{this.renderSuggestions(t,l)}),this.subscribe(Ji("suggestionsPlacement"),()=>{this.renderSuggestions(t,l)});let f=this.renderOverlays(n);this.unmountHandlers.push(()=>{f.unmount()}),this.store.dispatch(vf({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()})),this.store.dispatch(xf(this.inputMediator.getSelection())),this.store.dispatch(wp(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,ps.createRoot)(o);s.render((0,Ie.jsx)(as,{store:this.store,customStyles:r,children:(0,Ie.jsx)(Qo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(RR,{})})}));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&&rx(t,s)||void 0,[c,l]=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,ps.createRoot)(c);d.render((0,Ie.jsx)(as,{store:this.store,customStyles:o,children:(0,Ie.jsx)(Qo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(rP,{inputElement:t})})}));let p=(0,ps.createRoot)(u);return p.render((0,Ie.jsx)(as,{store:this.store,customStyles:o,children:(0,Ie.jsx)(Qo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(DR,{onLogIn:()=>this.loginViaPopup().catch(m=>J.warn(m.message))})})})),{unmount(){d.unmount(),p.unmount(),l(),f()}}}renderFloatingMenu(t,n){let{customStyles:r,closestScrollSelector:o,appendOverlayTo:s,floatingMenuParent:i}=n,a=o&&rx(t,o)||void 0,[c,l]=this.overlayContainerFactory("floating-menu",a||t,{appendTo:i!=null?i:s},r==null?void 0:r.floatingMenuParent),u=(0,ps.createRoot)(c);return u.render((0,Ie.jsx)(as,{store:this.store,customStyles:r,children:(0,Ie.jsx)(Qo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(pR,{onLogIn:()=>this.loginViaPopup().catch(f=>J.warn(f.message))})})})),{unmount(){u.unmount(),l()}}}renderOverlays(t){let{customStyles:n}=t,r=this.createContainer("deepdesk-overlays"),o=(0,ps.createRoot)(r);return o.render((0,Ie.jsx)(as,{store:this.store,customStyles:n,children:(0,Ie.jsx)(Qo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(lR,{})})})),{unmount(){o.unmount(),r.remove()}}}renderWidget(t,n={}){if(this.widgetElement&&J.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,isEmbedded:s}=n;this.widgetElement=t,this.configure({showImages:o,isEmbedded:s}),this.widgetRoot=(0,ps.createRoot)(t),this.widgetRoot.render((0,Ie.jsx)(as,{store:this.store,customStyles:r,children:(0,Ie.jsx)(Qo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(bI,{assistantOptions:n.assistantOptions,knowledgeAssistOptions:n.knowledgeAssist,onLogIn:()=>this.loginViaPopup().catch(i=>J.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,ps.createRoot)(n);return i.render((0,Ie.jsx)(as,{store:this.store,customStyles:o,children:(0,Ie.jsx)(Qo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(G0,{children:(0,Ie.jsxs)(am,{assistantCode:t,initialQuestion:s,evaluateKnowledgeAssistFn:r.isLegacyKnowledgeAssist?Kc:Gc,children:[(0,Ie.jsx)(wi,{children:(0,Ie.jsx)(cm,{title:r.title,emptyState:r.emptyState})}),(0,Ie.jsx)(K0,{children:(0,Ie.jsx)(lm,{})})]})})})})),{unmount(){i.unmount()}}}setupHandlingTime(t){let n=ym(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){KI(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(()=>L(this,null,function*(){yield this.store.dispatch(pc());let t=Us(this.state);t&&this.store.dispatch(uf({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 L(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 c=!1,l=()=>{u&&!u.closed&&u.close(),window.removeEventListener("message",f),clearInterval(d)};s.onmessage=p=>L(this,null,function*(){var m,g;if((m=p.data)!=null&&m.jwt)try{yield this.deepdeskApi.exchangeTokenForAccessCookie((g=p.data)==null?void 0:g.jwt),yield this.isLoggedIn(),this.broadcastEvents.send(Zl),c=!0,o.port1.close(),n()}catch(x){console.error(x),r(x)}finally{c=!0,l()}});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=>L(this,null,function*(){var m;if(p.origin===a.origin)switch((m=p.data)==null?void 0:m.type){case"deepdesk-popup-loaded":{try{let g=JSON.stringify({type:"deepdesk-popup-create-channel"});u==null||u.postMessage(g,a.origin,[o.port2])}catch(g){J.error("Error posting message to popup",g),r(g)}break}case"deepdesk-popup-error":{l(),p.data.message==="Timeout"&&J.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||(l(),c||r(new Error("Popup closed by user")))},200);this.disposeHandlers.push(l)})})}translateMessages(t){return this.deepdeskApi.translateMessages(t)}refreshTextSuggestions(){return L(this,null,function*(){this.isMounted&&(yield this.store.dispatch(vp()))})}refreshWidgetSuggestions(){return L(this,null,function*(){if(!this.widgetRoot)return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=mc(this.state);try{n.forEach(({type:r})=>{switch(r){case"entities":this.store.dispatch(cr());break;case"pinned-messages":case"sticky-messages":break;default:Iu.includes(r)||this.store.dispatch(ur(r))}})}catch(r){this.handleError(r)}})}};Va.version="18.2.1-beta.5",Va.count=0;var uu=Va;function V5(e){return L(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 iA(e,t){return L(this,null,function*(){let n=yield V5(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 aA(e,t,n){return L(this,null,function*(){yield new wo(e).authenticateWithKey(t,n)})}function lA(e){return e.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}function cA(r,o){return L(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},c=`${s.slice(0,i)}${t}${s.slice(a)}`,l=(d=n.selectionAfter)!=null?d:{start:i+t.length,end:i+t.length},u=()=>{if(n.setValue)return n.setValue(c);e.value=c};return Promise.resolve(u()).then(()=>{e.selectionStart=l.start,e.selectionEnd=l.end,e.blur(),e.focus()})})}function uA(r,o){return L(this,arguments,function*(e,t,n={}){let s=n.replace?ds(e,n.replace.start,n.replace.end):za(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 m=d?r:0,g=p?Math.min(s,u.childNodes.length):u.childNodes.length;for(let x=m;x<g&&(l(u.childNodes[x]),a!==2);x++);break}default:break}p&&(a=2)}return l(e),c}var CI=(i=>(i.CUT="Cut",i.BACKSPACE="Backspace",i.DELETE="Delete",i.ERASEEOF="EraseEof",i.UNDO="Undo",i.CLEAR="Clear",i))(CI||{}),So=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();Yo(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(CI).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 TI(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var ci=class extends So{constructor(){super(...arguments);this.lastKnownSelection=null}getRootNode(){return this.element.getRootNode()}getText(){let n=new Range;return n.selectNodeContents(this.element),au(this.element,n)}getHTML(){return this.element.innerHTML||""}getRange(){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=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!TI(r)&&(n.insertNode(this.element.ownerDocument.createTextNode("\u2060")),r=n.getBoundingClientRect(),n.deleteContents(),!TI(r))?null:{top:r.top+r.height,left:r.left}}getSelection(){let n=this.getRange();if(n)return iu(this.element,n);let r=this.lastKnownSelection;if(r&&EI(this.element,r.start,r.end))return r;let o=za(this.element);return o.collapse(!1),iu(this.element,o)}getSelectedText(){let{start:n,end:r}=this.getSelection();return au(this.element,ds(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 T5=["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 kI(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",T5.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 c=e.getBoundingClientRect(),l={top:c.top-e.scrollTop+a.offsetTop+Number.parseInt(s.borderTopWidth)+a.offsetHeight,left:c.left-e.scrollLeft+a.offsetLeft+Number.parseInt(s.borderLeftWidth)};return i.removeChild(r),l}var ui=class extends So{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 kI(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 RI(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,c])=>{i.searchParams.append(a,c)}),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 k5(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch(t){return e}}var q0=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()}},Y0=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.disposeHandlers=[];this.iframe=RI(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()}},X0=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(),J.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 Y0(t,this.deepdeskUrl,{debug:!0}):new q0(t),r=o=>{var i,a;if(o.origin!==this.deepdeskUrl)return;let s=k5(o.data);typeof s!="object"||s.type!=="event"||s.channel!==t||(J.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;J.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)}},PI=X0;function R5(e){return e.replace(/(_\w)/g,t=>t[1].toUpperCase())}function Fe(e){return Array.isArray(e)?e.map(Fe):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>P(w({},t),{[R5(n)]:Fe(e[n])}),{}):e}function P5(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function Mt(e){return Array.isArray(e)?e.map(Mt):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>P(w({},t),{[P5(n)]:Mt(e[n])}),{}):e}var Ha=class extends Error{constructor(n,r){super(n);this.body=r;this.name="CustomError"}};var Q0=e=>new Promise(t=>{setTimeout(t,e)});var Ba=class extends Ha{constructor(){super(...arguments);this.name="ClientError"}},J0=class extends Ha{constructor(){super(...arguments);this.name="ServerError"}},Z0=new Map;function I5(e){return L(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:(J.warn("Unexpected response body:",n.slice(0,20)),JSON.parse(n))})}var fs=class fs{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,c=n.method===void 0||n.method.toLowerCase()==="get",T=n,{useCache:l=!1,abortLatest:u=!1,attempts:f=1,retryDelay:d=500,refreshTokenOn401:p=!0,retryOnError:m=k=>k instanceof TypeError,retryOnResponse:g=k=>k.status>=500,version:x=null}=T,v=oe(T,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]);if(l){if(!c)throw new Error(`Can't use 'useCache' for ${n.method}`);if(Z0.has(i)){r(Z0.get(i));return}}let h=P(w({credentials:"include"},v),{headers:w({Accept:"application/json","Content-Type":"application/json"},v.headers)});!c&&this.csrfToken&&(h.headers=P(w({},h.headers),{"X-CSRFToken":this.csrfToken})),typeof x=="string"&&(h.headers=P(w({},h.headers),{"X-Deepdesk-API-Version":x}));let y=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=()=>L(this,null,function*(){return y--,a(i,h).then(k=>L(this,null,function*(){return g(k)&&!s.isAborted&&y>0?(yield Q0(d),E()):k.status===401&&p===!0&&S===!1?(S=!0,yield this.refreshToken(),E()):k})).catch(k=>L(this,null,function*(){if(m(k)&&!s.isAborted&&y>0)return yield Q0(d),E();throw k}))});E().then(k=>L(this,null,function*(){let I=yield I5(k);if(delete this.latestRequestByUrl[i],k.status>=500){o(new J0("Server Error",I));return}if(k.status===401){o(new Ba("Unauthorized",I));return}if(k.status===403){o(new Ba("Forbidden",I));return}if(k.status===404){o(new Ba("Not Found",I));return}if(k.status>=400){o(new Ba("Bad Request",I));return}l&&Z0.set(i,I),r(I)})).catch(k=>{o(k)})})}validateToken(){return L(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 fs.refreshingToken||(fs.refreshingToken=this.get("/apis/admin/session/refresh/",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{fs.refreshingToken=null},1e3*60)})),fs.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))}};fs.refreshingToken=null;var di=fs;var II;(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={}))})(II||(II={}));function ex(e){return P(w({},Fe(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)=>L(this,null,function*(){let i=yield r(o,s);return this.handleDeepdeskVersionHeaders(i),i}))}preflight(){return L(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 L(this,null,function*(){var r;yield this.preflight(),J.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()},Mt(t)),{metadata:(r=t.metadata)!=null?r:{}}));return ex(n)})}getMe(){return L(this,null,function*(){let t=yield this.client.get("/apis/admin/session/me/");return Fe(t)})}postIdentity(t){return L(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/me/identities/",Mt(t))})}patchMe(t){return L(this,null,function*(){yield this.preflight();let n=yield this.client.patch("/apis/admin/session/me/",Mt(t));return Fe(n)})}getProfile(t){return L(this,null,function*(){let n=yield this.client.get(`/apis/admin/profiles/${t}/`,{useCache:!0});return Fe(n)})}getKnowledgeAssistant(t){return L(this,null,function*(){let n=yield this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{useCache:!0});return Fe(n)})}getContentTypes(){return L(this,null,function*(){let t=yield this.client.get("/apis/admin/content-types/",{useCache:!0});return Fe(t)})}getAccount(){return L(this,null,function*(){let t=yield this.client.get("/apis/admin/account/",{useCache:!0});return Fe(t)})}getPlatformConfig(t){return L(this,null,function*(){let n=t!==void 0?`/platform/config/${t}/`:"/platform/config/",{config:r}=yield this.client.get(n,{useCache:!0});return Fe(r)})}checkUserExists(t){return L(this,null,function*(){let{exists:n}=yield this.client.get(`/apis/admin/users/exists?external_id=${t}`,{version:"v1"});return n})}getConversationByExternalId(r){return L(this,arguments,function*(t,n={}){yield this.preflight(),J.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 J.info(`Successfully retrieved conversation ${i.id} for session ${t}`),ex(i)})}isConversationSupported(r){return L(this,arguments,function*(t,n={}){J.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 L(this,null,function*(){var s;yield this.preflight();let r=Mt(n);n.metadata&&(r.metadata=(s=n.metadata)!=null?s:{});let o=yield this.client.put(`/api/v2/conversations/${t}`,r);return ex(o)})}postMessages(t,n){return L(this,null,function*(){yield this.preflight(),yield this.client.post(`/api/v2/conversations/${t}/messages`,n.map(r=>P(w({},Mt(r)),{metadata:r.metadata})))})}sendEvent(t,n){return L(this,null,function*(){yield this.preflight();let a=n,{data:r}=a,o=oe(a,["data"]),s=Object.entries(this.latestReceivedDeepdeskVersions).reduce((c,[l,u])=>P(w({},c),{[l]:u}),{}),i=["platform","agentId","agentName","agentEmail","conversationId"].reduce((c,l)=>(o[l]&&(c[l]=o[l]),c),{});return this.client.post("/api/v2/events",Mt(P(w(w({},s),i),{data:r,name:t})),{version:"v2"})})}getEntities(t){return L(this,null,function*(){return yield this.preflight(),yield this.client.post("/api/v2/entities",{messages:t.filter(r=>r.text)})})}getTemporaryExchangeToken(){return L(this,null,function*(){return(yield this.client.get("/apis/admin/session/exchange-token/")).jwt})}exchangeTokenForAccessCookie(t){return L(this,null,function*(){return this.client.post("/apis/admin/session/jwt/",{jwt:t}).catch(n=>{throw J.warn(`Invalid token '${t}'`),n})})}authenticateWithKey(t,n){return L(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/api-key/",Mt(n),{refreshTokenOn401:!1,headers:{apikey:t}})})}getTextSuggestions(o){return L(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}`,Mt(n),{abortLatest:!0})).map(i=>P(w({},Fe(i)),{text:i.text||i.url||i.message,source:r,type:r})).filter((i,a,c)=>a===c.findIndex(l=>l.text===i.text))})}isLoggedIn(){return L(this,null,function*(){return yield this.preflight(),this.client.validateToken()})}getAutocompleteSuggestions(t,n){return L(this,null,function*(){return yield this.preflight(),(yield this.client.post(`/api/v2/conversations/${t}/autocomplete`,Mt(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 L(this,null,function*(){let n=yield this.client.get(`/api/v2/profiles/${t}/pinned-messages`,{abortLatest:!0});return Fe(n).map(r=>P(w({},r),{text:r.message,source:"sticky-messages",type:"pinned-message"}))})}getStyleSuggestions(t){return L(this,null,function*(){let n=yield this.client.post("/api/v2/style-suggestions",Mt(t),{abortLatest:!0,version:"v2"});return Fe(n)})}search(t){return L(this,null,function*(){let n=yield this.client.post(`/api/v2/profiles/${t.profile}/search`,Mt(t));return Fe(n)})}knowledgeAssist(s,i,a){return L(this,arguments,function*(t,n,r,o={}){yield this.preflight();let c=yield this.client.post(`/api/knowledge-assist/assistants/${r}/search`,Mt({question:t.question,doNotKnowAnswer:t.doNotKnowAnswer,customerInstruction:t.customerInstruction,chatHistory:n.map(l=>({question:l.question,answer:l.answer.answer})),agentId:o.agentId,conversationId:o.conversationId}),{version:"v2"});return Fe(c)})}requestLoginByEmail(t){return L(this,null,function*(){yield this.preflight();let n=yield this.client.post("/apis/admin/session/passwordless/request/",{email:t});return Fe(n)})}requestPasswordlessToken(){return L(this,null,function*(){let t=yield this.client.get("/apis/admin/session/passwordless/request/");return Fe(t.token)})}getCsrfToken(){return L(this,null,function*(){let{token:t}=yield this.client.get("/apis/admin/session/csrf/");return t})}verifyLoginToken(t){return L(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/login/",{token:t});return Fe(n)})}evaluateAssistant(t,n){return L(this,null,function*(){var a;yield this.preflight();let r=new URLSearchParams,{expectFormat:o="text"}=n||{};if(o.startsWith("json-schema:")){let c=o.replace("json-schema:","");r.append("expect_response_format","json-schema"),r.append("expect_response_format_schema",c)}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 Fe(i)})}createAssistantThread(t){return L(this,null,function*(){yield this.preflight();let{assistantCode:n}=t,r=yield this.client.post(`/apis/admin/assistants/${n}/threads/`,{});return Fe(r)})}postMessageToAssistantThread(t){return L(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 Fe(s)})}translateMessages(t){return L(this,null,function*(){yield this.preflight();let n=yield this.client.post("/api/v2/translate",Mt(t));return Fe(n)})}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),s=o.match(uS);if(!n||!s)return;let i=s[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[i];a&&n&&a!==n&&J.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[i]=n})}};fi.exchangeTokenPromise=null;var wo=fi;var AI={startTime:null,stopTime:null},LI=e=>e.handlingTime,OI=be({name:"handlingTime",initialState:AI,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(it,()=>AI)}}),{handlingTimeStart:MI,handlingTimeStop:fm,handlingTimeReset:_I}=OI.actions,NI=OI.reducer;var DI=(e={})=>{let t=w({onAuthError:ea(!1)},e);return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var pm={list:{keywordMatches:[]},fetchState:"idle"};var pi=fe("styleSuggestions/getAll",(n,r)=>L(null,[n,r],function*({text:e},t){var c;let{deepdeskAPI:o}=t.extra,s=t.getState(),{showStyleSuggestions:i}=s.settings,a=(c=s.conversation.current)==null?void 0:c.profileCode;if(!i)return pm.list;if(!a)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:a,message:e})})),A5=be({name:"styleSuggestions",initialState:pm,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",Yo(t.list,n.payload)||(t.list=n.payload)}).addCase(zs,t=>{t.list=pm.list}).addCase(it,()=>pm)}}),FI=A5.reducer;var zI=(e={})=>{let t,n=!0,r=w({getStyleSuggestions:pi,debounce:500},e);return o=>s=>i=>{var p;let a=o.getState().input.text,c=s(i),l=o.getState();if(l.auth.isLoggedIn!==!0)return c;let{showStyleSuggestions:u}=l.settings;if(!((p=l.conversation.current)==null?void 0:p.id)||!u)return c;let{text:d}=l.input;return d===a&&!n||(clearTimeout(t),d==="")||(t=setTimeout(()=>{n=!1,o.dispatch(r.getStyleSuggestions({text:d}))},e.debounce)),c}};function L5(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end}var HI=(e={})=>{let t=w({getTextSuggestions:ur,getAutocompleteSuggestions:Nc,debounce:200,check:Pr},e),n;return r=>o=>s=>{var g;let{input:i}=r.getState(),a=o(s),c=r.getState();if(c.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:l,showTabCompletion:u}=c.settings,f=(g=c.conversation.current)==null?void 0:g.id,d=s.type===vp.toString();if(!f||!l&&!u)return a;let{input:p}=c;return L5(p,i)&&!d||(clearTimeout(n),!t.check(c))||(n=setTimeout(()=>{let x=na(c);x===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(x))},d?0:t.debounce)),a}};var BI=pi.fulfilled.toString();function O5(e,t){let n=new Set([...t.keywordMatches.map(o=>o.keyword)]),r=[];return n.forEach(o=>{let s=e.keywordMatches.filter(c=>c.keyword===o),i=t.keywordMatches.filter(c=>c.keyword===o),a=i.length-s.length;a<=0||r.push(...i.slice(0,a))}),r}var UI=e=>t=>n=>r=>{var l;if(r.type!==BI){n(r);return}let o=t.getState().styleSuggestions.list;n(r);let s=t.getState(),i=s.styleSuggestions.list,a=(l=s.conversation)==null?void 0:l.current;if(o===i)return;let c=O5(o,i);r.type===BI&&c.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:c}})};var M5=Qd({assistants:RP,auth:HC,conversation:XC,contentTypes:j1,passwordlessToken:AP,entities:Kk,handlingTime:NI,info:h1,input:l1,settings:MC,profile:Z1,search:b1,styleSuggestions:FI,ui:vR,textSuggestions:nR});function VI(e){return iC({reducer:M5,middleware:t=>{var r;let n=t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI}},serializableCheck:!1}).concat(DI()).concat(HI({debounce:200})).concat(zI({debounce:500})).concat(UI(e.deepdeskAPI));return((r=e.middleware)!=null?r:[]).reduce((o,s)=>o.concat(s),n)},preloadedState:e.preloadedState})}var _5=e=>{var t,n;return(n=(t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())!=null?n:"unknown"},N5=e=>t=>n=>r=>{var a,c;let o=t.getState(),s=Ji("inlineSuggestions")(o);switch(r.type){case ea.toString():{!r.payload&&e.emit("logout",void 0);break}case cr.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 zs.toString():e.logSendMessage(r.payload);break;case qp.toString():e.emit("call-to-action",{cue:r.payload});break;case dr.fulfilled.toString():r.isBroadcasted||e.broadcast(Oy,r,!1);break;default:break}let i=n(r);switch(r.type){case zs.toString():e.handleAfterSendMessage(r.payload);break;case Fc.toString():e.onUpdateShowTabHint(r.payload);break;case fm.toString():e.logHandlingTime();break;case oa.toString():e.broadcast(Jl,r);break;case Fs.toString():e.broadcast(Jl,r);break;case Yp.toString():t.dispatch(Fs({source:"assistant",assistantCode:r.payload.code}));break;case"analytics/logEvent/fulfilled":{let l=o.assistants.cues.find(u=>u.code===r.meta.arg.data.assistantCode);e.emit("event",P(w({},r.meta.arg),{cue:l}));break}case gf.toString():{let{start:l,end:u}=o.input.selection;e.emit("replace",P(w({},r.payload),{replace:r.payload.replace==="selection"?{start:l,end:u}:{start:0,end:u}}));break}case er.toString():{let{start:l,end:u}=o.input.selection;e.emit("select-suggestion",P(w({type:_5(r.payload.suggestion)},r.payload),{replace:r.payload.replace==="selection"?{start:l,end:u}:{start:0,end:u}})),s&&t.dispatch(Xo([]));break}case hf.toString():e.emit("select-image",r.payload),e.sendEvent("Image attached",{conversationId:(c=o.conversation.current)==null?void 0:c.id,data:{path:r.payload.suggestion.image,title:r.payload.suggestion.title}});break;case Xo.toString():{s&&r.payload.length>0&&t.dispatch(yf(0));break}case go.fulfilled.toString():{if(r.isBroadcasted)break;e.broadcast(Jl,r,!1),e.emit("summary-generated",{summary:r.payload.output});break}default:break}return i},WI=N5;function tx(e){return e.toISOString().replace("T"," ").replace("Z","")}var D5=(e,t)=>t.version,$I=Bt([sa,Cr,LI,D5],(e,t,n,r)=>{if(!t)return J.warn("No conversationId for handling time metrics"),null;let{startTime:o,stopTime:s}=n;return!o||!s?(J.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:tx(o),timeStop:tx(s)}});function jI(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 nx(e,t){var s;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return nx(r,t);let o=(s=e.ownerDocument.defaultView)==null?void 0:s.frameElement;return o?nx(o,t):null}function rx(e,t){return nx(e,t)}function KI(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function F5(e){return typeof e=="object"&&e!==null&&"tagName"in e}function mm(e){return F5(e)&&(oi(e)||kp(e))}var qI,_r=new Map,z5=["bottom","height","left","right","top","width"],GI=(e,t)=>!e&&!t?!1:e&&!t||!e&&t?!0:z5.some(n=>e[n]!==t[n]);function YI(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,...YI(t)]:[]}function XI(e,t){return!e||!t?null:P(w({},e),{top:e.top+t.top,left:e.left+t.left})}var gm=!1,QI=()=>{gm=!0;let e=[];if(_r.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),_r.delete(n);return}let r=n.getBoundingClientRect();GI(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{let n=t.parentRects?t.parentRects.reduce(XI,t.rect):t.rect;GI(n,t.totalRect)&&t.callbacks.forEach(r=>r(n)),t.totalRect=n}),_r.size===0){gm=!1;return}qI=window.requestAnimationFrame(QI)};function ox(e,t){let n=YI(e),r=[],o=n.map((s,i)=>ox(s,a=>{r[i]=a;let c=_r.get(e);if(!c)return;let l=r.reduce(XI,c.rect);c.callbacks.forEach(u=>u(l))}));return{observe(s=!0){if(o.forEach(i=>i.observe(!1)),_r.has(e)){let i=_r.get(e);i.callbacks.push(t),i.rect&&t(i.rect)}else _r.set(e,{rect:void 0,callbacks:[t],parentRects:r});s&&!gm&&QI()},unobserve(){o.forEach(i=>i.unobserve());let s=_r.get(e);if(s){let i=s.callbacks.indexOf(t);i>=0&&s.callbacks.splice(i,1),s.callbacks.length||_r.delete(e),_r.size||(cancelAnimationFrame(qI),gm=!1)}}}}var ZI,Nr=new Map,JI=()=>{Nr.forEach((e,t)=>{if(!t.isConnected){Nr.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)))}),Nr.size!==0&&(ZI=window.requestAnimationFrame(JI))};function eA(e,t){return{observe(){let n=Nr.size===0;Nr.has(e)?Nr.get(e).callbacks.push(t):Nr.set(e,{visible:void 0,callbacks:[t]}),n&&JI()},unobserve(){let n=Nr.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||Nr.delete(e),Nr.size||cancelAnimationFrame(ZI)}}}}var sx=["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 ix(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function Ua(e){return Number.parseFloat(e)}function hm(e){return Math.round(e*1e6)}function tA(e){return e/1e6}function ax(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=Ua(e.width),s=Ua(e.borderLeftWidth),i=Ua(e.borderRightWidth),a=Ua(e.paddingRight),c=tA(hm(o)-hm(s)-hm(i)),l=tA(hm(r));if(c-l>2){let u=c-l;n.style.paddingRight=`${a+u}px`}}function lu(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",ri(n);let r=window.getComputedStyle(e),o=!0,s=()=>{n.scrollTop=e.scrollTop};ix(r,n,sx),ax(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",s));let i=eA(e,()=>{ix(r,n,sx),ax(r,e,n),s(),setTimeout(s,0)}),a,c=!0,l=ox(e,d=>{if(d===null){t.onRemove&&t.onRemove(),n.remove();return}if(!c&&t.onMoveStart&&(Promise.resolve().then(()=>t.onMoveStart()),c=!0),clearTimeout(a),a=setTimeout(()=>{t.onMoveEnd&&t.onMoveEnd(),c=!1},200),d.height===0&&d.width===0){if(o===!0)return;t.onHide&&t.onHide(),n.style.display="none",o=!0;return}if(ix(r,n,sx),ax(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(),m=window.getComputedStyle(t.closestScrollElement),g=Ua(m.borderTopWidth),x=Ua(m.borderBottomWidth),v=p.top+g-d.top,h=d.top+d.height+-(p.top+p.height-x);n.style.clipPath=`inset(${v}px 0px ${h}px 0px)`}o&&(n.style.display="block",t.onShow&&t.onShow(),o=!1)});return t.appendTo?t.appendTo.appendChild(n):(f=e.parentElement)==null||f.appendChild(n),l.observe(),i.observe(),[n,()=>{e.removeEventListener("scroll",s),l.unobserve(),i.unobserve(),n.remove()}]}var nA=(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){J.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function H5(e){return e.offsetParent!==null}function rA(e){if(!H5(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 ym(e,t,n=100){let r=rA(e);t({isVisible:r});let o=setInterval(()=>{let s=rA(e);s!==r&&(r=s,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var cu=class extends Error{};function B5(){let e,t;return{promise:new Promise((r,o)=>{e=r,t=o}),resolve:e,reject:t}}var vm=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 cu("Queued async function is outdated"));let o=B5();return this.queues[t][1]=o,o.promise.then(()=>n().finally(r))}};var U5={accepted:"onConversationAcceptedAssistants","new-message":"onConversationNewMessageAssistants",ended:"onConversationEndedAssistants"},oA=(e,t)=>{let n=e[U5[t]];return n&&n.length>0?n.map(r=>r.code):(J.warn(`No assistant set in profile for conversation event "${t}"`),[])};var xm=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=Fe(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 sA=nA("showTabHint",!0),Va=class Va{constructor({deepdeskUrl:t,version:n=Va.version||"unknown",locale:r="en-US",token:o,fetch:s,productName:i,createCustomChannel:a,websocketClient:c=xm}){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 vm;this.isMounted=!1;this.shouldRender=!0;this.loadProfileConfigPromise=null;let l=t.replace(/\/api$/,"");this.deepdeskApi=new wo(l,{token:o,fetch:s}),this.version=n,this.instanceId=Va.count++;let u={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[WI({broadcast:(m,g,x)=>{this.broadcastEvents.send(m,g,x)},emit:(m,g)=>this.emit(m,g),handleAfterSendMessage:m=>this.handleAfterSendMessage(m),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:m=>this.logSendMessage(m),onUpdateShowTabHint:m=>sA.update(m),sendEvent:(m,g)=>this.deepdeskApi.sendEvent(m,g)})]};this.store=VI(u),this.broadcastEvents=new PI({debug:!0,deepdeskUrl:l,eventMap:E1(this.store),createCustomChannel:a}),this.disposeHandlers.push(()=>{this.broadcastEvents.cleanup()}),this.ws=new c({url:`${l}/api/v2/me/realtime`.replace("https","wss"),reconnectInterval:25e3,shouldReconnect:()=>L(this,null,function*(){var m;return(m=bt(this.state))!=null?m:!1})}),this.whenLoggedIn(()=>this.ws.connect()),this.store.dispatch(Fc(sA.value())),this.store.dispatch(uf({locale:r,adminUrl:l,productName:i}));let f=[],d=m=>{if(!m.conversationId)return;let g=()=>{this.conversationId()===m.conversationId&&this.store.dispatch(kP(m))};this.hasConversation()?g():f.push(g)};this.ws.on("assistants::direct_response",d),this.ws.on("assistants::user_notification",d),this.ws.on("assistants::response_chunk",m=>{if(!m.conversationId)return;let g=()=>{this.conversationId()===m.conversationId&&this.store.dispatch(TP(m))};this.hasConversation()?g():f.push(g)}),this.ws.on("assistants::suggest_as_reply",m=>{if(!m.conversationId)return;let g=()=>{this.conversationId()===m.conversationId&&this.store.dispatch(oa([{text:m.payload.message,type:"text",source:"assistant",assistantCode:m.code,sourceLabel:m.name}]))};this.hasConversation()?g():f.push(g)});let p=this.whenConversationLoaded(()=>{var m;this.broadcastEvents.setExternalId((m=this.state.conversation.current)==null?void 0:m.externalId),f.forEach(g=>g()),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=Ds(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?(J.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(J.warn("Profile has not been loaded (yet)"),!0):(J.warn("No conversation loaded (yet)"),!0)}whenLoggedIn(t){if(bt(this.state))t();else{let n=this.subscribe(bt,r=>{r&&t()});this.disposeHandlers.push(()=>{n()})}}login(){return this.store.dispatch(ea(null)),this.store.dispatch(Qr()),new Promise(t=>{this.whenLoggedIn(()=>t())})}isLoggedIn(){return L(this,null,function*(){return(yield this.store.dispatch(Qr())).payload})}isConversationSupported(t,n){return L(this,null,function*(){return(yield this.store.dispatch(Ty({externalId:t,options:n}))).payload})}createConversation(t){return L(this,null,function*(){var r;return this.hasConversation()&&this.externalId()!==t.externalId&&this.resetConversation(),(yield this.store.dispatch(ff(P(w({},t),{metadata:(r=t.metadata)!=null?r:{}})))).payload})}getConversationByExternalId(t,n){return L(this,null,function*(){return this.hasConversation()&&this.externalId()!==t&&this.resetConversation(),(yield this.store.dispatch(pf({externalId:t,options:n}))).payload})}upsertConversation(t){return L(this,null,function*(){var r;return this.hasConversation()&&this.externalId()!==t.externalId&&this.resetConversation(),(yield this.store.dispatch(ky(P(w({},t),{metadata:(r=t.metadata)!=null?r:{}})))).payload})}postMessages(t){return L(this,null,function*(){yield this.store.dispatch(Ry(t))})}updateConversation(t){return L(this,null,function*(){return(yield this.store.dispatch(mf(t))).payload})}resetConversation(){this.store.dispatch(it()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}configure(t){this.store.dispatch(uf(t))}setVisitorInfo(t){this.store.dispatch(p1(t))}setCustomData(t){this.store.dispatch(m1(t))}setAgentInfo(t,n){return L(this,null,function*(){yield this.store.dispatch(Xl(w(w({},t),n)))})}setAgentSettings(t){return L(this,null,function*(){yield this.store.dispatch(Iy(t))})}getAgentSettings(){return L(this,null,function*(){return(yield this.store.dispatch(Ay())).payload})}refresh(){return L(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(vf({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()}))}notifyExternalSuggestion(t){this.store.dispatch(er(t))}evaluateAssistant(t,n){return L(this,null,function*(){var f;let u=n||{},{input:r={},transcript:o,showCuesInWidget:s=!0,includeMetadata:i,expectFormat:a}=u,c=oe(u,["input","transcript","showCuesInWidget","includeMetadata","expectFormat"]);Object.assign(r,c);let l=yield this.store.dispatch(dr({assistantCode:t,expectFormat:a||"json-schema:cues",transcript:o,includeMetadata:i,input:r,skipState:!s}));if(l.error)throw new Error(`Assistant evaluation failed: ${(f=l.payload)!=null?f:l.error.message}`);return l.payload.output})}evaluateConversationAssistant(t,n){return L(this,null,function*(){yield this.loadProfileConfig();let r=this.state.profile.data;if(!r){J.warn("Can't evaluate assistant when profile is not loaded yet.");return}let o=oA(r,t);yield Promise.all(o.map(s=>this.queues.push(s,()=>L(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 cu){J.warn(`Queued assistant "${s}" was outdated and dropped`);return}throw i})))})}getSummary(){return L(this,arguments,function*(t={}){if(!this.hasConversation())return J.warn("No conversation to create summary for."),null;if(!this.state.profile.data)return J.warn("No profile loaded yet"),null;let n=this.state.profile.data.summarizerAssistantNew;if(!n)return J.warn("No summarizer assistant set in profile"),null;let r=yield this.store.dispatch(go(P(w({},t),{assistantCode:n})));return r.error?(J.error("Error evaluating summary assistant",r.error),null):r.payload.output})}handleKeyDown(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui,{textSuggestions:o,selectedSuggestionIndex:s,selection:i}=this.state.input,{inlineSuggestions:a,showTextSuggestions:c,suggestionsPlacement:l}=this.settings,u=l==="inline"||l==="below"?"below":"above",f=o.length>0;if(this.store.dispatch(t1(Py(t))),!Pr(this.state)||t.key!=="Tab"&&!c)return;let d=()=>{n||!f||i&&(t.shiftKey||(this.store.dispatch(o1()),t.preventDefault()))},p=()=>{n||!f||a&&s<=0||i&&(t.shiftKey||(this.store.dispatch(s1()),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(yf(-1)),this.store.dispatch(ss({collapse:!0})),this.store.dispatch(hR(!0)),t.preventDefault());break}case"Tab":{t.preventDefault();let m=ra(this.state);if(!m)return;this.store.dispatch(Fc(!1)),this.store.dispatch(er({text:m.text,suggestion:m,eventMetrics:{inputType:"tab"},replace:"until-selection-end"}));break}case" ":{if(this.settings.inlineSuggestions||this.state.input.selectedSuggestionIndex===-1)return;let m=ra(this.state);if(!m)return;this.store.dispatch(er({text:m.text,suggestion:m,eventMetrics:{inputType:"space"},replace:"until-selection-end"}));break}case"Enter":{if(this.settings.inlineSuggestions||t.shiftKey||this.state.input.selectedSuggestionIndex===-1)return;let m=ra(this.state);if(!m)return;this.store.dispatch(er({text:m.text,suggestion:m,eventMetrics:{inputType:"enter"},replace:"until-selection-end"})),t.preventDefault();break}default:}n&&r&&this.store.dispatch(ss({collapse:!1}))}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(Xo([]))}handlingTimeStart(){this.state.handlingTime.startTime||(J.info("Start handling time"),this.store.dispatch(MI()))}handlingTimeStop(){this.state.handlingTime.startTime&&(J.info("Stop handling time"),this.store.dispatch(fm()))}logSendMessage(t){let n=jI(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=$I(this.state,{version:this.version});t&&(this.deepdeskApi.sendEvent("Handling Time",{conversationId:this.conversationId(),data:t}),this.store.dispatch(_I()))}notifySubmit(t={}){var n;this.shouldAbort()||(this.store.dispatch(zs((n=t.text)!=null?n:this.state.input.text)),this.store.dispatch(a1()))}emit(t,n){let r=this.eventListeners[t];r&&r.forEach(o=>{try{o(n)}catch(s){J.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),J.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(g1(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]=lu(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[c,l]=lu(s,{appendTo:document.body,onMoveStart:()=>{o.style.display="none"}});c.dataset.testid=n,c.style.zIndex="2",c.appendChild(r),this.unmountHandlers.push(()=>{l()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return ri(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),J.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()?(J.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(i1(r.metrics))):J.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(!mm(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,c=oe(d,["customStyles","closestScrollSelector","floatingMenuParent","appendOverlayTo","inputMediator"]),l={customStyles:r,closestScrollSelector:o,floatingMenuParent:s,appendOverlayTo:i};this.configure(c),this.settings.automaticHandlingTime&&this.setupHandlingTime(t),ri(t),this.inputMediator=a||(oi(t)?new ui(t):new ci(t)),this.inputMediator.on("change",({plainText:p,rawHTML:m})=>{this.store.dispatch(vf({text:p,html:m}))}),this.inputMediator.on("keyup",p=>{this.store.dispatch(n1(Py(p)))}),this.inputMediator.on("keydown",p=>{this.handleKeyDown(p)}),this.inputMediator.on("paste",({pastedText:p,selectionText:m})=>{this.store.dispatch(r1({text:p,selectionText:m}))}),this.inputMediator.on("cut",({selectionText:p})=>{this.store.dispatch(e1(p))});let u;this.inputMediator.on("selection",p=>{clearTimeout(u),p===null?u=setTimeout(()=>{p!==null&&this.store.dispatch(xf(p))},500):this.store.dispatch(xf(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(wp(!1))}),this.inputMediator.on("focus",()=>{this.store.dispatch(wp(!0))}),this.renderSuggestions(t,l),this.subscribe(Ji("inlineSuggestions"),()=>{this.renderSuggestions(t,l)}),this.subscribe(Ji("suggestionsPlacement"),()=>{this.renderSuggestions(t,l)});let f=this.renderOverlays(n);this.unmountHandlers.push(()=>{f.unmount()}),this.store.dispatch(vf({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()})),this.store.dispatch(xf(this.inputMediator.getSelection())),this.store.dispatch(wp(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,ps.createRoot)(o);s.render((0,Ie.jsx)(as,{store:this.store,customStyles:r,children:(0,Ie.jsx)(Qo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(RR,{})})}));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&&rx(t,s)||void 0,[c,l]=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,ps.createRoot)(c);d.render((0,Ie.jsx)(as,{store:this.store,customStyles:o,children:(0,Ie.jsx)(Qo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(rP,{inputElement:t})})}));let p=(0,ps.createRoot)(u);return p.render((0,Ie.jsx)(as,{store:this.store,customStyles:o,children:(0,Ie.jsx)(Qo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(DR,{onLogIn:()=>this.loginViaPopup().catch(m=>J.warn(m.message))})})})),{unmount(){d.unmount(),p.unmount(),l(),f()}}}renderFloatingMenu(t,n){let{customStyles:r,closestScrollSelector:o,appendOverlayTo:s,floatingMenuParent:i}=n,a=o&&rx(t,o)||void 0,[c,l]=this.overlayContainerFactory("floating-menu",a||t,{appendTo:i!=null?i:s},r==null?void 0:r.floatingMenuParent),u=(0,ps.createRoot)(c);return u.render((0,Ie.jsx)(as,{store:this.store,customStyles:r,children:(0,Ie.jsx)(Qo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(pR,{onLogIn:()=>this.loginViaPopup().catch(f=>J.warn(f.message))})})})),{unmount(){u.unmount(),l()}}}renderOverlays(t){let{customStyles:n}=t,r=this.createContainer("deepdesk-overlays"),o=(0,ps.createRoot)(r);return o.render((0,Ie.jsx)(as,{store:this.store,customStyles:n,children:(0,Ie.jsx)(Qo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(lR,{})})})),{unmount(){o.unmount(),r.remove()}}}renderWidget(t,n={}){if(this.widgetElement&&J.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,isEmbedded:s}=n;this.widgetElement=t,this.configure({showImages:o,isEmbedded:s}),this.widgetRoot=(0,ps.createRoot)(t),this.widgetRoot.render((0,Ie.jsx)(as,{store:this.store,customStyles:r,children:(0,Ie.jsx)(Qo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(bI,{assistantOptions:n.assistantOptions,knowledgeAssistOptions:n.knowledgeAssist,onLogIn:()=>this.loginViaPopup().catch(i=>J.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,ps.createRoot)(n);return i.render((0,Ie.jsx)(as,{store:this.store,customStyles:o,children:(0,Ie.jsx)(Qo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(G0,{children:(0,Ie.jsxs)(am,{assistantCode:t,initialQuestion:s,evaluateKnowledgeAssistFn:r.isLegacyKnowledgeAssist?Kc:Gc,children:[(0,Ie.jsx)(wi,{children:(0,Ie.jsx)(cm,{title:r.title,emptyState:r.emptyState})}),(0,Ie.jsx)(K0,{children:(0,Ie.jsx)(lm,{})})]})})})})),{unmount(){i.unmount()}}}setupHandlingTime(t){let n=ym(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){KI(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(()=>L(this,null,function*(){yield this.store.dispatch(pc());let t=Us(this.state);t&&this.store.dispatch(uf({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 L(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 c=!1,l=()=>{u&&!u.closed&&u.close(),window.removeEventListener("message",f),clearInterval(d)};s.onmessage=p=>L(this,null,function*(){var m,g;if((m=p.data)!=null&&m.jwt)try{yield this.deepdeskApi.exchangeTokenForAccessCookie((g=p.data)==null?void 0:g.jwt),yield this.isLoggedIn(),this.broadcastEvents.send(Zl),c=!0,o.port1.close(),n()}catch(x){console.error(x),r(x)}finally{c=!0,l()}});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=>L(this,null,function*(){var m;if(p.origin===a.origin)switch((m=p.data)==null?void 0:m.type){case"deepdesk-popup-loaded":{try{let g=JSON.stringify({type:"deepdesk-popup-create-channel"});u==null||u.postMessage(g,a.origin,[o.port2])}catch(g){J.error("Error posting message to popup",g),r(g)}break}case"deepdesk-popup-error":{l(),p.data.message==="Timeout"&&J.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||(l(),c||r(new Error("Popup closed by user")))},200);this.disposeHandlers.push(l)})})}translateMessages(t){return this.deepdeskApi.translateMessages(t)}refreshTextSuggestions(){return L(this,null,function*(){this.isMounted&&(yield this.store.dispatch(vp()))})}refreshWidgetSuggestions(){return L(this,null,function*(){if(!this.widgetRoot)return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=mc(this.state);try{n.forEach(({type:r})=>{switch(r){case"entities":this.store.dispatch(cr());break;case"pinned-messages":case"sticky-messages":break;default:Iu.includes(r)||this.store.dispatch(ur(r))}})}catch(r){this.handleError(r)}})}};Va.version="18.2.1-beta.6",Va.count=0;var uu=Va;function V5(e){return L(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 iA(e,t){return L(this,null,function*(){let n=yield V5(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 aA(e,t,n){return L(this,null,function*(){yield new wo(e).authenticateWithKey(t,n)})}function lA(e){return e.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}function cA(r,o){return L(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},c=`${s.slice(0,i)}${t}${s.slice(a)}`,l=(d=n.selectionAfter)!=null?d:{start:i+t.length,end:i+t.length},u=()=>{if(n.setValue)return n.setValue(c);e.value=c};return Promise.resolve(u()).then(()=>{e.selectionStart=l.start,e.selectionEnd=l.end,e.blur(),e.focus()})})}function uA(r,o){return L(this,arguments,function*(e,t,n={}){let s=n.replace?ds(e,n.replace.start,n.replace.end):za(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((c,l)=>{l>0&&s.insertNode(document.createElement("br")),s.insertNode(document.createTextNode(c))}):s.insertNode(document.createTextNode(t))};return Promise.resolve(a()).then(()=>{try{if(n.selectionAfter!==!1){e.focus();let c=n.selectionAfter?ds(e,n.selectionAfter.start,n.selectionAfter.end):(s.collapse(!1),s),l=window.getSelection();l==null||l.removeAllRanges(),l==null||l.addRange(c)}if(!i)return;i.scrollIntoView&&i.scrollIntoView({block:"nearest",inline:"nearest"})}finally{i&&i.remove()}})})}function W5(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 $5(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 dA(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):dA(n,t)}function fA(o,s){return L(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 c=(d=e.ownerDocument.defaultView)!=null?d:window,l=c.getSelection();if((!l||l.rangeCount===0)&&(e.focus(),l=c.getSelection()),!l||l.rangeCount===0)return;let u=l.getRangeAt(0);if(!u)return;i=document.createElement("span"),u.insertNode(i);let f=r?W5(t):$5(t);n?dA(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 kA(j5);})();
|
|
85
85
|
/*! Bundled license information:
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@deepdesk/deepdesk-sdk",
|
|
3
|
-
"version": "18.2.1-beta.
|
|
3
|
+
"version": "18.2.1-beta.6",
|
|
4
4
|
"description": "Deepdesk SDK",
|
|
5
5
|
"author": "Lukas Batteau",
|
|
6
6
|
"license": "ISC",
|
|
@@ -40,7 +40,7 @@
|
|
|
40
40
|
"dev:css": "tcm -w -p 'src/**/*.module.css' .",
|
|
41
41
|
"build": "tsup",
|
|
42
42
|
"type-check": "tsc --noEmit",
|
|
43
|
-
"test": "
|
|
43
|
+
"test": "vitest run",
|
|
44
44
|
"snapshot": "./scripts/release.mjs --snapshot",
|
|
45
45
|
"release": "./scripts/release.mjs"
|
|
46
46
|
},
|
|
@@ -66,11 +66,10 @@
|
|
|
66
66
|
"@babel/preset-typescript": "^7.28.5",
|
|
67
67
|
"@deepdesk/esbuild-i18n-plugin": "*",
|
|
68
68
|
"@testing-library/dom": "^10.4.1",
|
|
69
|
-
"@testing-library/jest-dom": "^
|
|
69
|
+
"@testing-library/jest-dom": "^6.6.3",
|
|
70
70
|
"@testing-library/react": "^16.3.0",
|
|
71
71
|
"@testing-library/user-event": "^14.6.1",
|
|
72
72
|
"@types/diff": "^5.2.3",
|
|
73
|
-
"@types/jest": "^29.5.14",
|
|
74
73
|
"@types/lodash.debounce": "^4.0.9",
|
|
75
74
|
"@types/node-fetch": "^2.6.13",
|
|
76
75
|
"@types/react": "^18.3.27",
|
|
@@ -80,11 +79,10 @@
|
|
|
80
79
|
"args": "^5.0.3",
|
|
81
80
|
"esbuild": "^0.27.0",
|
|
82
81
|
"esbuild-plugin-react18-css": "^0.0.4",
|
|
83
|
-
"
|
|
84
|
-
"
|
|
85
|
-
"msw": "^1.3.5",
|
|
82
|
+
"jsdom": "^25.0.1",
|
|
83
|
+
"msw": "^2.12.7",
|
|
86
84
|
"postcss": "^8.5.6",
|
|
87
|
-
"preact": "^10.27.
|
|
85
|
+
"preact": "^10.27.3",
|
|
88
86
|
"react": "^18.3.1",
|
|
89
87
|
"react-dom": "^18.3.1",
|
|
90
88
|
"ts-dedent": "^2.2.0",
|
|
@@ -93,44 +91,8 @@
|
|
|
93
91
|
"typed-css-modules": "^0.9.1",
|
|
94
92
|
"typescript": "^5.9.3",
|
|
95
93
|
"uuid": "^9.0.1",
|
|
94
|
+
"vitest": "^4.0.16",
|
|
96
95
|
"whatwg-fetch": "^3.6.20",
|
|
97
|
-
"zx": "^
|
|
98
|
-
},
|
|
99
|
-
"jest": {
|
|
100
|
-
"roots": [
|
|
101
|
-
"<rootDir>/src"
|
|
102
|
-
],
|
|
103
|
-
"globals": {
|
|
104
|
-
"DEEPDESK_SDK_VERSION": "1.2.3"
|
|
105
|
-
},
|
|
106
|
-
"testEnvironment": "jsdom",
|
|
107
|
-
"setupFilesAfterEnv": [
|
|
108
|
-
"<rootDir>/src/__jest__/testSetup.ts"
|
|
109
|
-
],
|
|
110
|
-
"moduleNameMapper": {
|
|
111
|
-
"\\.(css)$": "<rootDir>/src/__jest__/mockCss.js",
|
|
112
|
-
"\\.(gif|ttf|eot|svg|png|webp)$": "<rootDir>/src/__jest__/mockAsset.js"
|
|
113
|
-
},
|
|
114
|
-
"testPathIgnorePatterns": [
|
|
115
|
-
"/node_modules/",
|
|
116
|
-
"/__helpers__/"
|
|
117
|
-
],
|
|
118
|
-
"collectCoverage": true,
|
|
119
|
-
"coverageThreshold": {
|
|
120
|
-
"global": {
|
|
121
|
-
"statements": 81,
|
|
122
|
-
"branches": 71,
|
|
123
|
-
"functions": 82,
|
|
124
|
-
"lines": 83
|
|
125
|
-
}
|
|
126
|
-
},
|
|
127
|
-
"collectCoverageFrom": [
|
|
128
|
-
"src/**/*.{ts,tsx}",
|
|
129
|
-
"!src/**/*.d.ts",
|
|
130
|
-
"!src/__vite__/**/*",
|
|
131
|
-
"!<rootDir>/node_modules/",
|
|
132
|
-
"!**/__tests__/**/*",
|
|
133
|
-
"!**/__jest__/**/*"
|
|
134
|
-
]
|
|
96
|
+
"zx": "^8.8.5"
|
|
135
97
|
}
|
|
136
98
|
}
|