@deepdesk/deepdesk-sdk 18.2.1-beta.14 → 18.2.1-beta.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs.js +1 -1
- package/dist/index.esm.js +1 -1
- package/dist/index.iife.js +1 -1
- package/package.json +1 -1
package/dist/index.iife.js
CHANGED
|
@@ -78,7 +78,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let r="<p>An error
|
|
|
78
78
|
`+tn),ce&&Jp([Q,X,A],Hr=>{tn=Xc(tn,Hr," ")}),S&&ct?S.createHTML(tn):tn},t.setConfig=function(){let re=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};wm(re),qe=!0},t.clearConfig=function(){vs=null,qe=!1},t.isValidAttribute=function(re,C,H){vs||wm({});let Z=ut(re),ze=ut(C);return yx(Z,ze,H)},t.addHook=function(re,C){typeof C=="function"&&Yc(L[re],C)},t.removeHook=function(re,C){if(C!==void 0){let H=T5(L[re],C);return H===-1?void 0:k5(L[re],H,1)[0]}return $P(L[re])},t.removeHooks=function(re){L[re]=[]},t.removeAllHooks=function(){L=QP()},t}var nI=tI();var wo=w(Y());var rI={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=w(R());function W5(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 H0(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 j5(e){return e.replace(/\r\n/g,`
|
|
79
79
|
`)}var $5=({content:e,useLabel:t,copyLabel:n,onCopy:r,onUse:o})=>{let i=O("Markdown",rI),s=(0,wo.useRef)(null),[a,c]=(0,wo.useState)(null),l=(0,wo.useMemo)(()=>{let g=Te.parse(j5(e));return nI.sanitize(g.toString()).replaceAll("</code>",`${W5(i.copyIcon)}</code>`).replaceAll('<a href="','<a target="_blank" rel="noreferrer noopener" href="')},[e]),u=g=>{var m;let x=g.target,v=!!((m=s.current)!=null&&m.querySelector("code"));if(["A","BUTTON"].includes(x.tagName)){c(null);return}a||v&&x.tagName!=="CODE"||!v&&x!==s.current||(x.addEventListener("mouseleave",()=>c(null),{once:!0}),c(x))},f=()=>{if(!a)return;c(null);let g=a.querySelector("button");g&&(Oa(g,i.fadeup),r==null||r(H0(a)))},d=g=>{let x=g.target;if(x.tagName==="A"){g.stopPropagation();return}"copyIcon"in x.dataset&&(Oa(x,i.fadeup),r==null||r(H0(x.parentElement)))},p=()=>{!a||!o||(c(null),o(H0(a)))},h=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)(wo.Fragment,{children:[a&&(r||o)&&(0,pr.jsxs)(Ma,{triggerRef:{current:a},className:i.popover,parentNode:a,children:[(0,pr.jsxs)("div",{className:i.options,ref:h,children:[r&&(0,pr.jsx)("button",{type:"button",className:i.option,onClick:f,children:n}),o&&(0,pr.jsxs)(wo.Fragment,{children:[(0,pr.jsx)("div",{className:i.divider}),(0,pr.jsx)("button",{type:"button",className:i.option,onClick:p,children:t})]})]}),(0,pr.jsx)("div",{className:i.arrow})]}),(0,pr.jsx)("div",{ref:s,"data-testid":"widget-markdown-content",className:i.root,dangerouslySetInnerHTML:{__html:l},onMouseOver:u,onClick:d})]})},ls=$5;var B0={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=w(R()),K5=500,G5=100,q5=({content:e,onChange:t,onCopy:n})=>{let r=(0,cs.useRef)(null),o=O("WidgetCue",B0);return(0,cs.useEffect)(()=>{let i=r.current;if(!i)return;i.style.setProperty("height","0px");let s=Math.min(Math.max(i.scrollHeight,G5),K5);i.style.setProperty("height",`${s}px`)},[e]),(0,Jt.jsx)("textarea",{ref:r,className:o.editableCue,onCopy:n,onChange:t,value:e})},Y5=({cue:e,onCallToAction:t,onRemove:n,onCopy:r,onUse:o})=>{let i=O("WidgetCue",B0),s=ie(qc),a=Xe(),c=ee("hasKeyboardInput"),[l,u]=(0,cs.useState)(e.text),f=()=>{t&&t(l,e),n(e)},d=g=>{r&&r(g,e)},p=g=>{o&&o(g,e)},h=g=>{g.preventDefault(),g.stopPropagation(),n(e)};return(0,cs.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:i.title,"data-testid":"widget-cue-title",children:e.rule.label.startsWith("__")?s(e.rule.label):e.title}),e.editable?(0,Jt.jsx)(q5,{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)(ls,{content:e.text,useLabel:s("useCue"),copyLabel:s("copyCue"),onCopy:d,onUse:c?p:void 0})]})}),(0,Jt.jsxs)(de.ButtonsContainer,{children:[(0,Jt.jsxs)("div",{className:i.actions,children:[e.editable&&(0,Jt.jsx)(de.Button,{onClick:()=>d(l),variant:"primary",children:s("copyCue")}),e.callToAction&&(0,Jt.jsx)(de.Button,{onClick:f,variant:"primary",children:e.callToAction.label}),(0,Jt.jsx)(de.Button,{onClick:h,variant:"secondary",children:s("removeCue")})]}),(0,Jt.jsx)(Zp,{evaluationId:e.evaluationId,assistantCode:e.rule.label,assistantOutput:e.text,feedbackText:e.text,feedbackType:"assistant"})]})]})},oI=Y5;var Da=w(R()),X5=({cues:e})=>{let t=ve(),n=un(),r=ie(qc),o=Xe(),i=l=>{t(Kp({code:l.rule.label})),o("Assistant response closed",{evaluationId:l.evaluationId,assistantCode:l.rule.label,assistantOutput:l.text})},s=(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($p(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(eo,{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,Da.jsx)(Da.Fragment,{children:e.map(l=>l.isLoading?(0,Da.jsx)(Xp,{title:l.rule.label.startsWith("__")?r(l.rule.label):l.title},l.rule.id):(0,Da.jsx)(oI,{cue:l,onCallToAction:a,onRemove:i,onCopy:s,onUse:c},l.evaluationId))})},iI=X5;var nm=w(Y());var sI={root:"dd-cvTAY",label:"dd-QWQxD",value:"dd-WSUHF",copyButton:"dd-67o9H",copyButtonText:"dd-oos-l",isTrue:"dd--1g2O",isFalse:"dd-sz2ir"};var gn=w(R());function Q5(e,t){return t.split(".").reduce((n,r)=>!n||typeof n!="object"||!(r in n)?null:n[r],e)}var aI=({data:e,schema:t})=>{let n=O("WidgetCustomData",sI),r=o=>{Tr(o)};return(0,nm.useEffect)(()=>{te.info("Custom data",e,t)},[e]),(0,gn.jsx)("dl",{className:n.root,children:t.map(o=>{let i=Q5(e,o.path);return(0,gn.jsxs)(nm.Fragment,{children:[(0,gn.jsx)("dt",{className:n.label,children:o.label}),(0,gn.jsx)("dd",{className:n.value,children:o.type==="boolean"&&i?(0,gn.jsx)("span",{className:n.isTrue,children:o.trueValue}):o.type==="boolean"&&!i?(0,gn.jsx)("span",{className:n.isFalse,children:o.falseValue}):o.type==="array"&&Array.isArray(i)&&i.length>0?(0,gn.jsxs)("button",{type:"button",onClick:()=>r(i.join(", ")),className:n.copyButton,children:[(0,gn.jsx)("span",{className:n.copyButtonText,children:i.join(", ")}),(0,gn.jsx)(La,{})]}):typeof i=="string"||typeof i=="number"?(0,gn.jsxs)("button",{type:"button",onClick:()=>r(`${i}`),className:n.copyButton,children:[(0,gn.jsx)("span",{className:n.copyButtonText,children:i}),(0,gn.jsx)(La,{})]}):"-"})]},o.label)})})};var Qe=w(Y());var Fa={};dt(Fa,{enUS:()=>Z5,nlNL:()=>J5});var Z5={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"}]},J5={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 rm={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 cI=w(Y());var lI={error:"dd-CoAuB"};var U0={};dt(U0,{enUS:()=>eF,nlNL:()=>tF});var eF={errorPrefix:[{type:0,value:"Error:"}]},tF={errorPrefix:[{type:0,value:"Foutmelding:"}]};var eu=w(R()),uI=({message:e})=>{let t=(0,cI.useRef)(null),n=O("WidgetCardError",lI),r=ie(U0);return Cu(t),(0,eu.jsx)(de,{ref:t,children:(0,eu.jsx)(he,{children:(0,eu.jsxs)(he.Content,{className:n.error,children:[r("errorPrefix")," ",e]})})})};var ge=w(R()),nF=3,rF=({sources:e,onClick:t})=>{let n=ie(Fa),r=O("WidgetKnowledgeAssistant",rm),[o,i]=(0,Qe.useState)(!1),s=o?e:e.slice(0,nF);return s.length===0?null:(0,ge.jsxs)("ul",{className:r.sources,children:[s.map(a=>(0,ge.jsx)("li",{className:r.source,"data-testid":"knowledge-assist-source",children:(0,ge.jsxs)(mt,{tooltip:!0,placement:"top-start",children:[(0,ge.jsx)(mt.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)(mt.Content,{className:r.tooltip,children:decodeURIComponent(a.url)})]})},a.name)),s<e&&(0,ge.jsx)("button",{type:"button",className:r.showMoreSources,onClick:()=>i(!0),children:n("showMore",{amount:e.length-s.length})})]})},oF=({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)(ls,{content:t})]})})}),iF=({innerRef:e,item:t,hasKeyboardInput:n,onCopy:r,onUse:o,onSourceClick:i})=>{var c;let s=ie(Fa),a=(0,Qe.useContext)(om);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)(ls,{content:t.answer.answer,useLabel:s("useCue"),copyLabel:s("copyCue"),onCopy:r,onUse:n?o:void 0}),(0,ge.jsx)(rF,{sources:(c=t.answer.sources)!=null?c:[],onClick:i})]})}),a.assistantCode&&(0,ge.jsxs)(de.ButtonsContainer,{children:[(0,ge.jsx)("div",{}),(0,ge.jsx)(Zp,{evaluationId:t.evaluationId,feedbackType:"assistant",assistantCode:a.assistantCode,assistantOutput:t.answer.answer,feedbackText:t.answer.answer})]})]})},om=(0,Qe.createContext)(null),im=({assistantCode:e,evaluateKnowledgeAssistFn:t,initialQuestion:n,children:r})=>{let[o,i]=(0,Qe.useState)(null),[s,a]=(0,Qe.useState)(!1),[c,l]=(0,Qe.useState)(null),[u,f]=(0,Qe.useState)(!!n),[d,p]=(0,Qe.useState)(null),h=ve(),g=Xe(),x=qp(y=>{if(!e)throw new Error("No knowledge assistant was defined");return l(null),t({assistantCode:e,input:y,threadId:o,onNewThreadId(S){i(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=>_(null,null,function*(){a(!0),p(y),yield x.call(y),a(!1),p(null)}),m={isEnabled:!!e,assistantCode:e,isSubmitting:s,threadId:o,pendingInput:d,errorMessage:c,onSubmit:v,onReset(){o&&h(xP(o)),l(null),i(null),e&&g("Assistant thread reset",{threadId:o!=null?o:void 0,assistantCode:e})}};return(0,Qe.useEffect)(()=>{n&&m.isEnabled&&v(n)},[n]),(0,ge.jsx)(om.Provider,{value:m,children:r})},sm=()=>{let e=ie(Fa),t=O("WidgetKnowledgeAssistant",rm),n=(0,Qe.useContext)(om),r=(0,Qe.useRef)(null),[o,i]=(0,Qe.useState)(""),s=c=>{i(c.target.value)},a=c=>{c.preventDefault(),n.onSubmit(o).then(()=>{var l;r.current&&((l=r.current)==null||l.focus(),i(""))})};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:s}),(0,ge.jsx)("button",{type:"submit",disabled:n.isSubmitting||o==="",className:t.formSubmit,children:e("submitLabel")})]}):null},am=({title:e,emptyState:t})=>{var h,g;let n=ie(Fa),r=Xe(),o=O("WidgetKnowledgeAssistant",rm),i=(0,Qe.useRef)(null),s=(0,Qe.useContext)(om),a=(g=K(yP((h=s.threadId)!=null?h:-1)))!=null?g:[],c=ee("hasKeyboardInput"),l=un(),u=(x,v)=>{Tr(x),s.assistantCode&&r("Assistant response copied",{assistantCode:s.assistantCode,assistantOutput:x,copiedText:x,evaluationId:v.evaluationId})},f=(x,v)=>{s.assistantCode&&r("Assistant source clicked",{evaluationId:v.evaluationId,assistantCode:s.assistantCode,source:x})},d=x=>{x.preventDefault(),s.onReset()},p=(x,v)=>{l.send(eo,{text:x,suggestion:{source:"assistant",sourceText:x}}),s.assistantCode&&r("Assistant response used",{assistantCode:s.assistantCode,evaluationId:v.evaluationId,assistantOutput:v.answer.answer,usedText:x})};return!s.isEnabled||(a==null?void 0:a.length)===0&&!s.isSubmitting&&!t&&!s.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&&!s.pendingInput&&(0,ge.jsx)(oF,b({},t)),a.map((x,v)=>(0,ge.jsx)(iF,{innerRef:v===a.length-1?i:void 0,item:x,hasKeyboardInput:c,onCopy:m=>u(m,x),onUse:m=>p(m,x),onSourceClick:m=>f(m,x)},`${x.question}_${x.answer}_${v}`)),s.pendingInput&&(0,ge.jsx)(Xp,{title:s.pendingInput}),s.errorMessage&&(0,ge.jsx)(uI,{message:s.errorMessage})]})}),a.length>0&&(0,ge.jsx)("div",{className:o.resetContainer,children:(0,ge.jsx)(de.Button,{disabled:s.threadId===null||s.isSubmitting,onClick:d,children:n("resetLabel")})})]})};var pI=w(Y());var sF=/(https?:\/\/[^\s]+)/,fI=e=>e.split(" ").find(t=>sF.test(t));var Vn=w(R()),aF=({suggestion:e,lines:t,onUse:n})=>{var f;let r=e.text||e.url||e.message,o=fI(r),i=ie(Lc),s=ee("showImages"),a=ee("fallbackImage"),c=ee("hasKeyboardInput"),l=d=>{d.preventDefault(),d.stopPropagation(),c&&n(r)},u=(0,pI.useCallback)(d=>{window.open(o,"_blank"),d.stopPropagation(),d.preventDefault()},[o]);return(0,Vn.jsxs)(de,{onClick:c?l:void 0,"data-testid":"edit-suggestion",children:[(0,Vn.jsxs)(he,{children:[s&&e.image&&(0,Vn.jsx)(he.Image,{src:Np(e,"small",a||void 0),title:e.title}),(0,Vn.jsxs)(he.Content,{children:[e.title&&(0,Vn.jsx)(he.Title,{"data-testid":"widget-suggestion-title",children:e.title}),e.searchKeywords&&((f=e.searchKeywords)==null?void 0:f.length)>0&&(0,Vn.jsx)(de.Labels,{labels:e.searchKeywords}),(0,Vn.jsx)(he.Content,{cropText:t==="single",lineClamp:t==="multiple",children:r})]})]}),(0,Vn.jsxs)(de.Actions,{children:[o&&(0,Vn.jsx)(de.ActionButton,{onClick:u,label:i("visitUrl")}),c&&(0,Vn.jsx)(de.ActionButton,{primary:!0,onClick:l,label:i("useSuggestion")})]})]})},mI=aF;var tu=w(R()),lF=({lines:e,suggestions:t})=>{let n=un(),r=(o,i)=>{n.send(eo,{text:o,suggestion:P(b({},i),{source:i.source,sourceText:i.text})})};return(0,tu.jsx)(tu.Fragment,{children:t.map(o=>(0,tu.jsx)(mI,{suggestion:o,lines:e,onUse:i=>r(i,o)},o.text||o.url||o.message))})},gI=lF;var nu={};dt(nu,{enUS:()=>cF,nlNL:()=>uF});var cF={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"}]},uF={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 za={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=w(R()),hI=(e,t)=>{let n=K(Et);(0,ui.useEffect)(()=>n?t.every(r=>!!r)?e():()=>{}:()=>{},[...t,n])},dF=({onLogIn:e})=>{let t=O("Widget",za),n=ee("isEmbedded"),r=ee("adminUrl");return(0,ae.jsx)("div",{className:t.loginText,children:(0,ae.jsx)("div",{children:(0,ae.jsx)(wp,{isEmbedded:n,loginUrl:r,onLogIn:e})})},"login")},V0=({text:e})=>{let t=O("Widget",za);return(0,ae.jsx)("div",{className:t.stateText,children:(0,ae.jsx)("div",{children:(0,ae.jsx)("p",{children:e})})},"notification")},fF=()=>{let e=ie(nu),t=ve(),n=O("Widget",za),r=ee("showSearch"),o=ee("isEmbedded"),i=K(Ra("/admin/")),s=un(),a=ee("productName"),c=Xe();return hI(()=>{if(o)return t(S0()),()=>{t(CP())}},[t,o]),!r&&!i?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)(Ta,{}),onClick:()=>{s.send("ShowCommandPalette",{isOpen:!0}),c("open search",{via:"widget-shortcut"})},children:e("linkSearch")}),i&&(0,ae.jsx)(de.Button,{as:"a",target:"_blank",icon:(0,ae.jsx)(IP,{}),href:i,"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})})]})},pF=({title:e,content:t})=>{let n=ie(nu),[r,o]=(0,ui.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)(ls,{content:t})})}),(0,ae.jsx)(de.ButtonsContainer,{children:(0,ae.jsx)(de.Button,{onClick:()=>o(!1),children:n("close")})})]})})}):null},mF=()=>{let e=ve(),t=K(mc),n=K(j1),r=K(kP),o=K(i1),i=K(cp),s=K(mp),a=K(Vi),c=K(Cr);return(0,ui.useEffect)(()=>{!!o&&!n&&te.warn("Custom data provided, but no schema.")},[o,n]),hI(()=>{t.forEach(({type:l})=>{l==="entities"?e(ur()):Ru.includes(l)||e(dr(l))})},[e,c,a]),(0,ui.useEffect)(()=>{r.length>0&&!t.some(l=>l.type==="cues")&&te.warn("Received cues, but cues are not configured in widget.")},[t,r]),(0,ae.jsx)(ui.Fragment,{children:t.map(({type:l,title:u,amount:f,lines:d,schema:p,property:h})=>{var g,x;switch(l){case"entities":return i&&i.length>0&&(0,ae.jsx)(hr,{type:l,title:u,"data-testid":`type-${l}`,children:(0,ae.jsx)(PP,{entities:i})},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)(iI,{cues:r})})},l);case"custom-data-banner":return o&&h&&o[h]&&(0,ae.jsx)(pF,{title:u,content:String(o[h])},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)(aI,{data:o,schema:p})})},l);default:return((x=(g=s[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)(gI,{lines:d,contentType:l,suggestions:s[l].suggestions.slice(0,f)||[]})})},l)}})})},W0=({children:e})=>{let t=O("Widget",za);return(0,ae.jsx)("div",{className:t.footer,children:e})},j0=({children:e})=>{let t=O("Widget",za);return(0,ae.jsx)("div",{className:t.root,"data-testid":"widget",children:e})},gF=({onLogIn:e,knowledgeAssistOptions:t={},assistantOptions:n={transcript:"in-memory-transcript"}})=>{let r=ie(nu),o=K(ta),i=K(Et),s=K(WC),a=K(Vi),c=K(W1("knowledge-assist")),l=K($1);return o===!1?(0,ae.jsx)(V0,{text:r("notSupported")}):i===!1?(0,ae.jsx)(dF,{onLogIn:e}):i===null?(0,ae.jsx)(V0,{text:r("waiting")}):!s||!a?(0,ae.jsx)(V0,{text:r("waitingForConversation")}):(0,ae.jsx)(j0,{children:(0,ae.jsxs)(im,{initialQuestion:t.initialQuestion,assistantCode:l!=null?l:void 0,evaluateKnowledgeAssistFn:Kc,children:[(0,ae.jsxs)(bs,{children:[(0,ae.jsx)(fF,{}),(0,ae.jsx)(mF,{}),c&&(0,ae.jsx)(am,{title:c.title,emptyState:t.emptyState})]}),(0,ae.jsxs)(W0,{children:[c&&(0,ae.jsx)(sm,{}),(0,ae.jsx)(FP,{assistantOptions:n})]})]})})},yI=gF;function Ha(e){let t=new Range;return t.selectNodeContents(e),t}function vI(e,t,n){try{return di(e,t,n),!0}catch(r){return!1}}function lm(e){return"tagName"in e&&(e.tagName==="DIV"||e.tagName==="P")}function cm(e){return"tagName"in e&&e.tagName==="BR"}var ru=/[\u200B-\u200D\uFEFF]/g;function di(e,t,n){let r=new Range;if(e.firstChild===null&&t===0&&n===0)return r.selectNodeContents(e),r;let o=0,i=!1;function s(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(ru,""),f=o+u.length,d=t>=o&&t<=f,p=n>=o&&n<=f;if(d){let h=s(l,t-o);h===0&&!p?r.setStartBefore(c):r.setStart(c,h)}p&&(r.setEnd(c,s(l,n-o)),i=!0),o=f;break}case Node.ELEMENT_NODE:{if(cm(c)&&(o===t&&r.setStartBefore(c),o++,o===n)){r.setEndAfter(c),i=!0;return}for(let u=0;u<c.childNodes.length&&(a(c.childNodes[u]),!i);u++);let l=c.lastChild;lm(c)&&l&&!lm(l)&&!cm(l)&&o++;break}default:break}}if(a(e),r.startContainer===document)throw new Error("Offsets out of bound");return r}function ou(e,t){if(!e.contains(t.startContainer)||!e.contains(t.endContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:r,endContainer:o,endOffset:i,collapsed:s}=t,a,c,l=0;function u(f){let d=f===e,p=f===n,h=f===o;switch(f.nodeType){case Node.TEXT_NODE:{let g=f.textContent;p&&(a=l+g.substring(0,r).replace(ru,"").length),h&&(c=l+g.substring(0,i).replace(ru,"").length),l+=g.replace(ru,"").length;break}case Node.ELEMENT_NODE:{if(cm(f)&&f.nextSibling){l++;break}!d&&lm(f)&&f.previousSibling&&l++;for(let g=0;g<f.childNodes.length;g++){let x=p&&g===r,v=h&&g===i;if(x&&(a=l),v&&(c=l),c!==void 0||((!x||!s)&&u(f.childNodes[g]),h&&g===i-1&&(c=l),c!==void 0))break}h&&(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 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:i,collapsed:s}=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 h=d?r:0,g=p?i:void 0;c+=u.textContent.replace(ru,"").substring(h,g);break}case Node.ELEMENT_NODE:{if(!s&&a===1&&cm(u)&&u.nextSibling){c+=`
|
|
80
80
|
`;break}!f&&!s&&a===1&&lm(u)&&u.previousSibling&&(c+=`
|
|
81
|
-
`);let h=d?r:0,g=p?Math.min(i,u.childNodes.length):u.childNodes.length;for(let x=h;x<g&&(l(u.childNodes[x]),a!==2);x++);break}default:break}p&&(a=2)}return l(e),c}var xI=(s=>(s.CUT="Cut",s.BACKSPACE="Backspace",s.DELETE="Delete",s.ERASEEOF="EraseEof",s.UNDO="Undo",s.CLEAR="Clear",s))(xI||{}),bo=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 i=this.getCaretPosition();Qo(i,this.cachedCaretPosition)||(this.cachedCaretPosition=i,this.emit("caretposition",i))}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(xI).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 SI(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var us=class extends bo{constructor(){super(...arguments);this.lastKnownSelection=null}getRootNode(){return this.element.getRootNode()}getText(){let n=new Range;return n.selectNodeContents(this.element),iu(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 i=this.element.ownerDocument.createRange();return i.setStart(o==null?void 0:o.startContainer,o==null?void 0:o.startOffset),i.setEnd(o==null?void 0:o.endContainer,o==null?void 0:o.endOffset),!i||!this.element.contains(i.startContainer)||!this.element.contains(i.endContainer)?null:i}getCaretPosition(){let n=this.getRange();if(!n||!n.collapsed||!("getBoundingClientRect"in n))return null;let r=n.getBoundingClientRect();return!SI(r)&&(n.insertNode(this.element.ownerDocument.createTextNode("\u2060")),r=n.getBoundingClientRect(),n.deleteContents(),!SI(r))?null:{top:r.top+r.height,left:r.left}}getSelection(){let n=this.getRange();if(n)return ou(this.element,n);let r=this.lastKnownSelection;if(r&&vI(this.element,r.start,r.end))return r;let o=Ha(this.element);return o.collapse(!1),ou(this.element,o)}getSelectedText(){let{start:n,end:r}=this.getSelection();return iu(this.element,di(this.element,n,r))}listen(){super.listen();let n=new MutationObserver(i=>{var s,a;i.length===2&&i[0].addedNodes.length===1&&((s=i[0].addedNodes[0])==null?void 0:s.textContent)==="\u2060"&&((a=i[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 hF=["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 wI(e,t){let n="mozInnerScreenX"in window,r=document.createElement("div");r.id="input-textarea-caret-position-mirror-div";let o=r.style,i=window.getComputedStyle(e),s=e.ownerDocument.body;o.whiteSpace="pre-wrap",o.wordWrap="break-word",o.position="absolute",o.visibility="hidden",hF.forEach(u=>{o[u]=i[u]}),n?e.scrollHeight>Number.parseInt(i.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),s.appendChild(r);let c=e.getBoundingClientRect(),l={top:c.top-e.scrollTop+a.offsetTop+Number.parseInt(i.borderTopWidth)+a.offsetHeight,left:c.left-e.scrollLeft+a.offsetLeft+Number.parseInt(i.borderLeftWidth)};return s.removeChild(r),l}var ds=class extends bo{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 wI(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 i;return(i=n==null?void 0:n.get)==null?void 0:i.call(this.element)},set:i=>{var s;(s=n==null?void 0:n.set)==null||s.call(this.element,i),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 bI(e,t,n){let r=`deepdesk-iframe-${e}`,o=document.getElementById(r);if(o)return o;let i=document.createElement("iframe"),s=new URL(t);return Object.entries(n).forEach(([a,c])=>{s.searchParams.append(a,c)}),i.style.position="absolute",i.style.left="-999em",i.style.width="0px",i.style.height="0px",i.tabIndex=-1,i.id=r,i.title=`iframe-${e}`,i.src=s.toString(),window.document.body.appendChild(i),i}function yF(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch(t){return e}}var $0=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()}},K0=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.disposeHandlers=[];this.iframe=bI(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()}},G0=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(),te.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 K0(t,this.deepdeskUrl,{debug:!0}):new $0(t),r=o=>{var s,a;if(o.origin!==this.deepdeskUrl)return;let i=yF(o.data);typeof i!="object"||i.type!=="event"||i.channel!==t||(te.info("Received broadcast event",this.externalId,o),(a=(s=this.eventMap)[i.name])==null||a.call(s,i.payload))};return n.onMessage(r),n}send(t,n,r){var s,a;te.info("Broadcast event",{externalId:this.externalId,name:t,payload:n});let o={type:"event",name:t,payload:n};r!==!1&&((a=(s=this.eventMap)[t])==null||a.call(s,n));let i=this.externalId==="deepdesk-general"?this.defaultChannel:this.channel;i==null||i.postMessage(P(b({},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)}},EI=G0;function vF(e){return e.replace(/(_\w)/g,t=>t[1].toUpperCase())}function Ue(e){return Array.isArray(e)?e.map(Ue):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>P(b({},t),{[vF(n)]:Ue(e[n])}),{}):e}function xF(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function en(e){return Array.isArray(e)?e.map(en):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>P(b({},t),{[xF(n)]:en(e[n])}),{}):e}var Ba=class extends Error{constructor(n,r){super(n);this.body=r;this.name="CustomError"}};var q0=e=>new Promise(t=>{setTimeout(t,e)});var Ua=class extends Ba{constructor(){super(...arguments);this.name="ClientError"}},X0=class extends Ba{constructor(){super(...arguments);this.name="ServerError"}},Y0=new Map;function SF(e){return _(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:(te.warn("Unexpected response body:",n.slice(0,20)),JSON.parse(n))})}var fi=class fi{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 i={isAborted:!1,reject:o},s=`${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:h=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(Y0.has(s)){r(Y0.get(s));return}}let m=P(b({credentials:"include"},v),{headers:b({Accept:"application/json","Content-Type":"application/json"},v.headers)});!c&&this.csrfToken&&(m.headers=P(b({},m.headers),{"X-CSRFToken":this.csrfToken})),typeof x=="string"&&(m.headers=P(b({},m.headers),{"X-Deepdesk-API-Version":x}));let y=f,S=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[s]&&u&&(this.latestRequestByUrl[s].isAborted=!0,this.latestRequestByUrl[s].reject(new Error("Aborted"))),this.latestRequestByUrl[s]=i;let E=()=>_(this,null,function*(){return y--,a(s,m).then(k=>_(this,null,function*(){return g(k)&&!i.isAborted&&y>0?(yield q0(d),E()):k.status===401&&p===!0&&S===!1?(S=!0,yield this.refreshToken(),E()):k})).catch(k=>_(this,null,function*(){if(h(k)&&!i.isAborted&&y>0)return yield q0(d),E();throw k}))});E().then(k=>_(this,null,function*(){let I=yield SF(k);if(delete this.latestRequestByUrl[s],k.status>=500){o(new X0("Server Error",I));return}if(k.status===401){o(new Ua("Unauthorized",I));return}if(k.status===403){o(new Ua("Forbidden",I));return}if(k.status===404){o(new Ua("Not Found",I));return}if(k.status>=400){o(new Ua("Bad Request",I));return}l&&Y0.set(s,I),r(I)})).catch(k=>{o(k)})})}validateToken(){return _(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 fi.refreshingToken||(fi.refreshingToken=this.get("/apis/admin/session/refresh/",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{fi.refreshingToken=null},1e3*60)})),fi.refreshingToken}get(t,n){return this.request(t,n)}post(t,n,r){return this.request(t,b({method:"POST",body:JSON.stringify(n)},r))}patch(t,n,r){return this.request(t,b({method:"PATCH",body:JSON.stringify(n)},r))}put(t,n,r){return this.request(t,b({method:"PUT",body:JSON.stringify(n)},r))}delete(t,n){return this.request(t,b({method:"DELETE"},n))}};fi.refreshingToken=null;var fs=fi;var CI;(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={}))})(CI||(CI={}));function Q0(e){return P(b({},Ue(e)),{metadata:e.metadata})}var ps=class ps{constructor(t,n={}){this.options=n;this.latestReceivedDeepdeskVersions={};this.shouldFetchCsrfToken=!0;this.client=new fs(t,{fetch:n.fetch}),this.client.patchFetch(r=>(o,i)=>_(this,null,function*(){let s=yield r(o,i);return this.handleDeepdeskVersionHeaders(s),s}))}preflight(){return _(this,null,function*(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let t=yield this.getCsrfToken();this.client.setCsrfToken(t)}return this.options.token?(ps.exchangeTokenPromise||(ps.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),ps.exchangeTokenPromise):Promise.resolve()})}createConversation(t){return _(this,null,function*(){var r;yield this.preflight(),te.info(`Creating conversation for session ${t.externalId} and agent ${t.agentId}`);let n=yield this.client.post("/api/v2/conversations",P(b({chat_start_time:new Date().toISOString()},en(t)),{metadata:(r=t.metadata)!=null?r:{}}));return Q0(n)})}getMe(){return _(this,null,function*(){let t=yield this.client.get("/apis/admin/session/me/");return Ue(t)})}postIdentity(t){return _(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/me/identities/",en(t))})}patchMe(t){return _(this,null,function*(){yield this.preflight();let n=yield this.client.patch("/apis/admin/session/me/",en(t));return Ue(n)})}getProfile(t){return _(this,null,function*(){let n=yield this.client.get(`/apis/admin/profiles/${t}/`,{useCache:!0});return Ue(n)})}getKnowledgeAssistant(t){return _(this,null,function*(){let n=yield this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{useCache:!0});return Ue(n)})}getContentTypes(){return _(this,null,function*(){let t=yield this.client.get("/apis/admin/content-types/",{useCache:!0});return Ue(t)})}getAccount(){return _(this,null,function*(){let t=yield this.client.get("/apis/admin/account/",{useCache:!0});return Ue(t)})}getPlatformConfig(t){return _(this,null,function*(){let n=t!==void 0?`/platform/config/${t}/`:"/platform/config/",{config:r}=yield this.client.get(n,{useCache:!0});return Ue(r)})}checkUserExists(t){return _(this,null,function*(){let{exists:n}=yield this.client.get(`/apis/admin/users/exists?external_id=${t}`,{version:"v1"});return n})}getConversationByExternalId(r){return _(this,arguments,function*(t,n={}){yield this.preflight(),te.info(`Getting conversation for session ${t}`);let{attempts:o=1,retryDelay:i=1e3}=n,s=yield this.client.get(`/api/v2/conversations/by_external_id/${t}`,{attempts:o,retryDelay:i,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"});return te.info(`Successfully retrieved conversation ${s.id} for session ${t}`),Q0(s)})}isConversationSupported(r){return _(this,arguments,function*(t,n={}){te.info(`Check if conversation for session ${t} is supported`);let{attempts:o=1,retryDelay:i=1e3}=n;return(yield this.client.get(`/api/v2/conversations/by_external_id/${t}/has_active_profile`,{attempts:o,retryDelay:i,retryOnResponse:a=>a.status===404||a.status>=500})).has_active_profile})}updateConversation(t,n){return _(this,null,function*(){var i;yield this.preflight();let r=en(n);n.metadata&&(r.metadata=(i=n.metadata)!=null?i:{});let o=yield this.client.put(`/api/v2/conversations/${t}`,r);return Q0(o)})}postMessages(t,n){return _(this,null,function*(){yield this.preflight(),yield this.client.post(`/api/v2/conversations/${t}/messages`,n.map(r=>P(b({},en(r)),{metadata:r.metadata})))})}sendEvent(t,n){return _(this,null,function*(){yield this.preflight();let a=n,{data:r}=a,o=oe(a,["data"]),i=Object.entries(this.latestReceivedDeepdeskVersions).reduce((c,[l,u])=>P(b({},c),{[l]:u}),{}),s=["platform","agentId","agentName","agentEmail","conversationId"].reduce((c,l)=>(o[l]&&(c[l]=o[l]),c),{});return this.client.post("/api/v2/events",en(P(b(b({},i),s),{data:r,name:t})),{version:"v2"})})}getEntities(t){return _(this,null,function*(){return yield this.preflight(),yield this.client.post("/api/v2/entities",{messages:t.filter(r=>r.text)})})}getTemporaryExchangeToken(){return _(this,null,function*(){return(yield this.client.get("/apis/admin/session/exchange-token/")).jwt})}exchangeTokenForAccessCookie(t){return _(this,null,function*(){return this.client.post("/apis/admin/session/jwt/",{jwt:t}).catch(n=>{throw te.warn(`Invalid token '${t}'`),n})})}authenticateWithKey(t,n){return _(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/api-key/",en(n),{refreshTokenOn401:!1,headers:{apikey:t}})})}getTextSuggestions(o){return _(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}`,en(n),{abortLatest:!0})).map(s=>P(b({},Ue(s)),{text:s.text||s.url||s.message,source:r,type:r})).filter((s,a,c)=>a===c.findIndex(l=>l.text===s.text))})}isLoggedIn(){return _(this,null,function*(){return yield this.preflight(),this.client.validateToken()})}getAutocompleteSuggestions(t,n){return _(this,null,function*(){return yield this.preflight(),(yield this.client.post(`/api/v2/conversations/${t}/autocomplete`,en(n),{abortLatest:!0})).map(o=>({score:1,source:o.source,sourceText:o.source_text,text:o.label,trainingJobs:o.training_jobs,searchKeywords:o.search_keywords,type:o.source})).filter((o,i,s)=>i===s.findIndex(a=>a.text===o.text))})}getPinnedMessages(t){return _(this,null,function*(){let n=yield this.client.get(`/api/v2/profiles/${t}/pinned-messages`,{abortLatest:!0});return Ue(n).map(r=>P(b({},r),{text:r.message,source:"sticky-messages",type:"pinned-message"}))})}getStyleSuggestions(t){return _(this,null,function*(){let n=yield this.client.post("/api/v2/style-suggestions",en(t),{abortLatest:!0,version:"v2"});return Ue(n)})}search(t){return _(this,null,function*(){let n=yield this.client.post(`/api/v2/profiles/${t.profile}/search`,en(t));return Ue(n)})}requestLoginByEmail(t){return _(this,null,function*(){yield this.preflight();let n=yield this.client.post("/apis/admin/session/passwordless/request/",{email:t});return Ue(n)})}requestPasswordlessToken(){return _(this,null,function*(){let t=yield this.client.get("/apis/admin/session/passwordless/request/");return Ue(t.token)})}getCsrfToken(){return _(this,null,function*(){let{token:t}=yield this.client.get("/apis/admin/session/csrf/");return t})}verifyLoginToken(t){return _(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/login/",{token:t});return Ue(n)})}evaluateAssistant(t,n){return _(this,null,function*(){var s;yield this.preflight();let r=new URLSearchParams;n!=null&&n.externalConversationId&&r.append("external_conversation_id",n.externalConversationId);let o=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(o,{input:(s=n==null?void 0:n.input)!=null?s:{},conversation:n==null?void 0:n.transcript});return Ue(i)})}createAssistantThread(t){return _(this,null,function*(){yield this.preflight();let{assistantCode:n}=t,r=yield this.client.post(`/apis/admin/assistants/${n}/threads/`,{});return Ue(r)})}postMessageToAssistantThread(t){return _(this,null,function*(){yield this.preflight();let{assistantCode:n,threadId:r,message:o}=t,i=yield this.client.post(`/apis/admin/assistants/${n}/threads/${r}/messages/`,{content:o,role:"user"});return Ue(i)})}translateMessages(t){return _(this,null,function*(){yield this.preflight();let n=yield this.client.post("/api/v2/translate",en(t));return Ue(n)})}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),i=o.match(lS);if(!n||!i)return;let s=i[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[s];a&&n&&a!==n&&te.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[s]=n})}};ps.exchangeTokenPromise=null;var Eo=ps;var TI={startTime:null,stopTime:null},kI=e=>e.handlingTime,RI=Ee({name:"handlingTime",initialState:TI,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(st,()=>TI)}}),{handlingTimeStart:PI,handlingTimeStop:um,handlingTimeReset:II}=RI.actions,AI=RI.reducer;var _I=(e={})=>{let t=b({onAuthError:ea(!1)},e);return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var dm={list:{keywordMatches:[]},fetchState:"idle"};var ms=fe("styleSuggestions/getAll",(n,r)=>_(null,[n,r],function*({text:e},t){var c;let{deepdeskAPI:o}=t.extra,i=t.getState(),{showStyleSuggestions:s}=i.settings,a=(c=i.conversation.current)==null?void 0:c.profileCode;if(!s)return dm.list;if(!a)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:a,message:e})})),wF=Ee({name:"styleSuggestions",initialState:dm,reducers:{},extraReducers:e=>{e.addCase(ms.pending,t=>{t.fetchState="loading"}).addCase(ms.rejected,t=>{t.fetchState="error"}).addCase(ms.fulfilled,(t,n)=>{t.fetchState="done",Qo(t.list,n.payload)||(t.list=n.payload)}).addCase(Hi,t=>{t.list=dm.list}).addCase(st,()=>dm)}}),MI=wF.reducer;var LI=(e={})=>{let t,n=!0,r=b({getStyleSuggestions:ms,debounce:500},e);return o=>i=>s=>{var p;let a=o.getState().input.text,c=i(s),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 bF(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end}var NI=(e={})=>{let t=b({getTextSuggestions:dr,getAutocompleteSuggestions:Oc,debounce:200,check:Pr},e),n;return r=>o=>i=>{var g;let{input:s}=r.getState(),a=o(i),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=i.type===gp.toString();if(!f||!l&&!u)return a;let{input:p}=c;return bF(p,s)&&!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 OI=ms.fulfilled.toString();function EF(e,t){let n=new Set([...t.keywordMatches.map(o=>o.keyword)]),r=[];return n.forEach(o=>{let i=e.keywordMatches.filter(c=>c.keyword===o),s=t.keywordMatches.filter(c=>c.keyword===o),a=s.length-i.length;a<=0||r.push(...s.slice(0,a))}),r}var DI=e=>t=>n=>r=>{var l;if(r.type!==OI){n(r);return}let o=t.getState().styleSuggestions.list;n(r);let i=t.getState(),s=i.styleSuggestions.list,a=(l=i.conversation)==null?void 0:l.current;if(o===s)return;let c=EF(o,s);r.type===OI&&c.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:c}})};var CF=Yd({assistants:bP,auth:FC,conversation:jC,contentTypes:U1,passwordlessToken:TP,entities:Bk,handlingTime:AI,info:f1,input:n1,settings:_C,profile:K1,search:v1,styleSuggestions:MI,ui:fR,textSuggestions:Xk});function FI(e){return oC({reducer:CF,middleware:t=>{var r;let n=t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI}},serializableCheck:!1}).concat(_I()).concat(NI({debounce:200})).concat(LI({debounce:500})).concat(DI(e.deepdeskAPI));return((r=e.middleware)!=null?r:[]).reduce((o,i)=>o.concat(i),n)},preloadedState:e.preloadedState})}var TF=e=>{var t,n;return(n=(t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())!=null?n:"unknown"},kF=e=>t=>n=>r=>{var a,c;let o=t.getState(),i=Js("inlineSuggestions")(o);switch(r.type){case ea.toString():{!r.payload&&e.emit("logout",void 0);break}case ur.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 Hi.toString():e.logSendMessage(r.payload);break;case $p.toString():e.emit("call-to-action",{cue:r.payload});break;case Lr.fulfilled.toString():r.isBroadcasted||e.broadcast(Ay,r,!1);break;default:break}let s=n(r);switch(r.type){case Hi.toString():e.handleAfterSendMessage(r.payload);break;case Fc.toString():e.onUpdateShowTabHint(r.payload);break;case um.toString():e.logHandlingTime();break;case oa.toString():e.broadcast(xf,r);break;case zi.toString():e.broadcast(xf,r);break;case Kp.toString():t.dispatch(zi({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(b({},r.meta.arg),{cue:l}));break}case En.toString():{let{start:l,end:u}=o.input.selection;e.emit("select-suggestion",P(b({type:TF(r.payload.suggestion)},r.payload),{replace:r.payload.replace==="selection"?{start:l,end:u}:{start:0,end:u}})),i&&t.dispatch(Zo([]));break}case ff.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 Zo.toString():{i&&r.payload.length>0&&t.dispatch(pf(0));break}default:break}return s},zI=kF;function Z0(e){return e.toISOString().replace("T"," ").replace("Z","")}var RF=(e,t)=>t.version,HI=Bt([ia,Cr,kI,RF],(e,t,n,r)=>{if(!t)return te.warn("No conversationId for handling time metrics"),null;let{startTime:o,stopTime:i}=n;return!o||!i?(te.warn("No startTime and stopTime for handling time metrics"),null):{conversationId:t,clientVersion:r,agentId:e==null?void 0:e.agentId,agentName:e==null?void 0:e.agentName,agentEmail:e==null?void 0:e.agentEmail,timeStart:Z0(o),timeStop:Z0(i)}});function BI(e,t){let{text:n,metrics:{numPaste:r,pastes:o,textSuggestions:i}}=e.input,s=n.length;return{source:"agent",clientVersion:t.version,pastes:o,lenTextTotal:s,numPastes:r,suggestions:i}}function J0(e,t){var i;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return J0(r,t);let o=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;return o?J0(o,t):null}function ex(e,t){return J0(e,t)}function UI(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function PF(e){return typeof e=="object"&&e!==null&&"tagName"in e}function fm(e){return PF(e)&&(is(e)||Ep(e))}var WI,Or=new Map,IF=["bottom","height","left","right","top","width"],VI=(e,t)=>!e&&!t?!1:e&&!t||!e&&t?!0:IF.some(n=>e[n]!==t[n]);function jI(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,...jI(t)]:[]}function $I(e,t){return!e||!t?null:P(b({},e),{top:e.top+t.top,left:e.left+t.left})}var pm=!1,KI=()=>{pm=!0;let e=[];if(Or.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),Or.delete(n);return}let r=n.getBoundingClientRect();VI(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{let n=t.parentRects?t.parentRects.reduce($I,t.rect):t.rect;VI(n,t.totalRect)&&t.callbacks.forEach(r=>r(n)),t.totalRect=n}),Or.size===0){pm=!1;return}WI=window.requestAnimationFrame(KI)};function tx(e,t){let n=jI(e),r=[],o=n.map((i,s)=>tx(i,a=>{r[s]=a;let c=Or.get(e);if(!c)return;let l=r.reduce($I,c.rect);c.callbacks.forEach(u=>u(l))}));return{observe(i=!0){if(o.forEach(s=>s.observe(!1)),Or.has(e)){let s=Or.get(e);s.callbacks.push(t),s.rect&&t(s.rect)}else Or.set(e,{rect:void 0,callbacks:[t],parentRects:r});i&&!pm&&KI()},unobserve(){o.forEach(s=>s.unobserve());let i=Or.get(e);if(i){let s=i.callbacks.indexOf(t);s>=0&&i.callbacks.splice(s,1),i.callbacks.length||Or.delete(e),Or.size||(cancelAnimationFrame(WI),pm=!1)}}}}var GI,Dr=new Map,qI=()=>{Dr.forEach((e,t)=>{if(!t.isConnected){Dr.delete(t);return}let{clientHeight:n,scrollHeight:r}=t,o=r>n;e.visible!==o&&(e.visible=o,e.callbacks.forEach(i=>i(e.visible)))}),Dr.size!==0&&(GI=window.requestAnimationFrame(qI))};function YI(e,t){return{observe(){let n=Dr.size===0;Dr.has(e)?Dr.get(e).callbacks.push(t):Dr.set(e,{visible:void 0,callbacks:[t]}),n&&qI()},unobserve(){let n=Dr.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||Dr.delete(e),Dr.size||cancelAnimationFrame(GI)}}}}var nx=["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 rx(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function Va(e){return Number.parseFloat(e)}function mm(e){return Math.round(e*1e6)}function XI(e){return e/1e6}function ox(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=Va(e.width),i=Va(e.borderLeftWidth),s=Va(e.borderRightWidth),a=Va(e.paddingRight),c=XI(mm(o)-mm(i)-mm(s)),l=XI(mm(r));if(c-l>2){let u=c-l;n.style.paddingRight=`${a+u}px`}}function su(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",os(n);let r=window.getComputedStyle(e),o=!0,i=()=>{n.scrollTop=e.scrollTop};rx(r,n,nx),ox(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",i));let s=YI(e,()=>{rx(r,n,nx),ox(r,e,n),i(),setTimeout(i,0)}),a,c=!0,l=tx(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(rx(r,n,nx),ox(r,e,n),i(),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(),h=window.getComputedStyle(t.closestScrollElement),g=Va(h.borderTopWidth),x=Va(h.borderBottomWidth),v=p.top+g-d.top,m=d.top+d.height+-(p.top+p.height-x);n.style.clipPath=`inset(${v}px 0px ${m}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(),s.observe(),[n,()=>{e.removeEventListener("scroll",i),l.unobserve(),s.unobserve(),n.remove()}]}var QI=(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){te.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function AF(e){return e.offsetParent!==null}function ZI(e){if(!AF(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 gm(e,t,n=100){let r=ZI(e);t({isVisible:r});let o=setInterval(()=>{let i=ZI(e);i!==r&&(r=i,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var au=class extends Error{};function _F(){let e,t;return{promise:new Promise((r,o)=>{e=r,t=o}),resolve:e,reject:t}}var hm=class{constructor(){this.queues={}}push(t,n){let r=()=>{let i=this.queues[t][1];i?(this.queues[t]=[i.promise,null],i.resolve()):delete this.queues[t]};if(!this.queues[t]){let i=n().finally(r);return this.queues[t]=[i,null],i}this.queues[t][1]&&this.queues[t][1].reject(new au("Queued async function is outdated"));let o=_F();return this.queues[t][1]=o,o.promise.then(()=>n().finally(r))}};var MF={accepted:"onConversationAcceptedAssistants","new-message":"onConversationNewMessageAssistants",ended:"onConversationEndedAssistants"},JI=(e,t)=>{var o,i,s;if(!((s=(i=(o=e.uiConfig)==null?void 0:o.widget)==null?void 0:i.types.find(a=>a.type==="cues"))==null?void 0:s.isActive))return te.warn("Triggered a conversation assistant, but cues are not configured in widget."),[];let r=e[MF[t]];return r&&r.length>0?r.map(a=>a.code):(te.warn(`No assistant set in profile for conversation event "${t}"`),[])};var ym=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=Ue(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 pi=w(Y());var eA={root:"dd-7zvcP",dialogContent:"dd-4C0lK",continueButton:"dd-YUPQW",buttonContinueWrapper:"dd-IKpYs",nicknameInput:"dd-rxhGp",titleWrapper:"dd-nw3nD",title:"dd-5iof5",closeButtonWrapper:"dd-UUAzA",closeButton:"dd-7rjP5",buttonsWrapper:"dd-5e9Xb",errorMessage:"dd--5VgX",errorLink:"dd-u461n"};var ix={};dt(ix,{enUS:()=>LF,nlNL:()=>NF});var LF={title:[{type:0,value:"Enter your nickname"}],close:[{type:0,value:"Close"}],nicknameDialogTitle:[{type:0,value:"Please enter the name you'd like customers to see during chat conversations. This nickname will be used across your Deepdesk environment.Please enter the name you'd like customers to see during chat conversations. This nickname will be used across your Deepdesk environment."}],nicknameDialogInputPlaceholder:[{type:0,value:"Enter your nickname"}],nicknameDialogContinueButton:[{type:0,value:"Continue"}],nicknameDialogError:[{type:0,value:"Nickname cannot be empty or spaces only"}],nicknameDialogEmojiError:[{type:0,value:"You cannot use emojis in this field."}],nicknameDialogSaveError:[{type:0,value:"We couldn't save your details just now. Please try again, or update it at "},{type:1,value:"account"},{type:0,value:".deepdesk.com/admin/user-settings"}],nicknameDialogSaveErrorWithoutLink:[{type:0,value:"We couldn\u2019t save your details just now. Please try again later, or update them in My Deepdesk \u2192 Settings."}]},NF={title:[{type:0,value:"Voer je bijnaam in"}],close:[{type:0,value:"Sluiten"}],nicknameDialogTitle:[{type:0,value:"Voer de naam in die je wilt dat klanten zien tijdens chatgesprekken. Deze bijnaam wordt gebruikt in je Deepdesk-omgeving."}],nicknameDialogInputPlaceholder:[{type:0,value:"Voer je bijnaam in"}],nicknameDialogContinueButton:[{type:0,value:"Doorgaan"}],nicknameDialogError:[{type:0,value:"Bijnaam mag niet leeg of alleen spaties zijn"}],nicknameDialogEmojiError:[{type:0,value:"Je kunt geen emoji's gebruiken in dit veld."}],nicknameDialogSaveError:[{type:0,value:"We konden je gegevens nu niet opslaan. Probeer het opnieuw of werk het bij op "},{type:1,value:"account"},{type:0,value:".deepdesk.com/admin/user-settings"}],nicknameDialogSaveErrorWithoutLink:[{type:0,value:"We konden je gegevens nu niet opslaan. Probeer het opnieuw later, of werk ze bij in My Deepdesk \u2192 Instellingen."}]};var lt=w(R()),tA=({onClose:e,onSave:t,id:n,error:r})=>{let[o,i]=(0,pi.useState)(""),[s,a]=(0,pi.useState)(!1),[c,l]=(0,pi.useState)(!1),u=O("Nickname",eA),f=pi.default.useRef(null),d=K(v=>v.info.showNicknameDialog),p=ie(ix),h=ee("adminUrl");(0,pi.useEffect)(()=>{r&&a(!0)},[r]);let g=()=>{if(!f.current)return;o.trim()?f.current.setCustomValidity(""):f.current.setCustomValidity(p("nicknameDialogError")),f.current.reportValidity()},x=v=>{v.preventDefault();let m=o.trim(),y=v.currentTarget.querySelector("#nickname-input");if(!m){y.setCustomValidity(p("nicknameDialogError")),y.reportValidity();return}y.setCustomValidity(""),t(m)};return(0,lt.jsxs)(la,{isOpen:d,"datatest-id":n,onClose:e||(()=>{}),onBack:e||(()=>{}),children:[(0,lt.jsx)("div",{className:u.titleWrapper,children:(0,lt.jsx)("h1",{className:u.title,children:p("title")})}),(0,lt.jsxs)("form",{className:u.dialogContent,onSubmit:x,children:[(0,lt.jsx)("p",{children:p("nicknameDialogTitle")}),s&&r&&(0,lt.jsx)("div",{className:u.errorMessage,children:h?(()=>{let v=p("nicknameDialogSaveError",{account:h}),m=`${h}.deepdesk.com/admin/user-settings`,y=v.indexOf(m);if(y!==-1){let S=v.substring(0,y),E=v.substring(y+m.length);return(0,lt.jsxs)(lt.Fragment,{children:[S,(0,lt.jsx)("a",{href:m,target:"_blank",rel:"noopener noreferrer",className:u.errorLink,children:m}),E]})}return v})():p("nicknameDialogSaveErrorWithoutLink")}),(0,lt.jsx)("input",{required:!0,minLength:1,maxLength:20,"data-testid":"nickname-input",id:"nickname-input",className:u.nicknameInput,type:"text",placeholder:p("nicknameDialogInputPlaceholder"),value:o,onChange:v=>{l(new RegExp("\\p{Extended_Pictographic}","u").test(v.target.value)),i(v.target.value)},onBlur:g,ref:f}),c&&(0,lt.jsx)("div",{className:u.errorMessage,role:"alert",children:p("nicknameDialogEmojiError")}),(0,lt.jsxs)("div",{className:u.buttonsWrapper,children:[r?(0,lt.jsx)("div",{className:u.closeButtonWrapper,children:(0,lt.jsx)("button",{type:"button",className:u.closeButton,onClick:()=>e==null?void 0:e(),children:p("close")})}):null,(0,lt.jsx)("div",{className:u.buttonContinueWrapper,children:(0,lt.jsx)("button",{type:"submit",className:u.continueButton,disabled:!o.trim()||new RegExp("\\p{Extended_Pictographic}","u").test(o),children:p("nicknameDialogContinueButton")})})]})]})]})};var we=w(R());var nA=QI("showTabHint",!0),Wa=class Wa{constructor({deepdeskUrl:t,version:n=Wa.version||"unknown",locale:r="en-US",token:o,fetch:i,productName:s,createCustomChannel:a,websocketClient:c=ym}){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.nicknameDialogUnsubscribe=null;this.nicknameDialogFailed=!1;this.dynamicThunkObject={};this.queues=new hm;this.isMounted=!1;this.shouldRender=!0;this.loadProfileConfigPromise=null;let l=t.replace(/\/api$/,"");this.deepdeskApi=new Eo(l,{token:o,fetch:i}),this.version=n,this.instanceId=Wa.count++;let u={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[zI({broadcast:(h,g,x)=>{this.broadcastEvents.send(h,g,x)},emit:(h,g)=>this.emit(h,g),handleAfterSendMessage:h=>this.handleAfterSendMessage(h),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:h=>this.logSendMessage(h),onUpdateShowTabHint:h=>nA.update(h),sendEvent:(h,g)=>this.deepdeskApi.sendEvent(h,g)})]};this.store=FI(u),this.broadcastEvents=new EI({debug:!0,deepdeskUrl:l,eventMap:x1(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:()=>_(this,null,function*(){var h;return(h=Et(this.state))!=null?h:!1})}),this.whenLoggedIn(()=>this.ws.connect()),this.store.dispatch(Fc(nA.value())),this.store.dispatch(lf({locale:r,adminUrl:l,productName:s}));let f=[],d=h=>{if(!h.conversationId)return;let g=()=>{this.conversationId()===h.conversationId&&this.store.dispatch(wP(h))};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",h=>{if(!h.conversationId)return;let g=()=>{this.conversationId()===h.conversationId&&this.store.dispatch(SP(h))};this.hasConversation()?g():f.push(g)}),this.ws.on("assistants::suggest_as_reply",h=>{if(!h.conversationId)return;let g=()=>{this.conversationId()===h.conversationId&&this.store.dispatch(oa([{text:h.payload.message,type:"text",source:"assistant",assistantCode:h.code,sourceLabel:h.name}]))};this.hasConversation()?g():f.push(g)});let p=this.whenConversationLoaded(()=>{var h;this.broadcastEvents.setExternalId((h=this.state.conversation.current)==null?void 0:h.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=Fi(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?(te.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(te.warn("Profile has not been loaded (yet)"),!0):(te.warn("No conversation loaded (yet)"),!0)}whenLoggedIn(t){if(Et(this.state))t();else{let n=this.subscribe(Et,r=>{r&&t()});this.disposeHandlers.push(()=>{n()})}}login(){return this.store.dispatch(ea(null)),this.store.dispatch(Jr()),new Promise(t=>{this.whenLoggedIn(()=>t())})}isLoggedIn(){return _(this,null,function*(){return(yield this.store.dispatch(Jr())).payload})}isConversationSupported(t,n){return _(this,null,function*(){return(yield this.store.dispatch(Ey({externalId:t,options:n}))).payload})}createConversation(t){return _(this,null,function*(){var r;return this.hasConversation()&&this.externalId()!==t.externalId&&this.resetConversation(),(yield this.store.dispatch(cf(P(b({},t),{metadata:(r=t.metadata)!=null?r:{}})))).payload})}getConversationByExternalId(t,n){return _(this,null,function*(){return this.hasConversation()&&this.externalId()!==t&&this.resetConversation(),(yield this.store.dispatch(uf({externalId:t,options:n}))).payload})}upsertConversation(t){return _(this,null,function*(){var r;return this.hasConversation()&&this.externalId()!==t.externalId&&this.resetConversation(),(yield this.store.dispatch(Cy(P(b({},t),{metadata:(r=t.metadata)!=null?r:{}})))).payload})}postMessages(t){return _(this,null,function*(){yield this.store.dispatch(Ty(t))})}updateConversation(t){return _(this,null,function*(){return(yield this.store.dispatch(df(t))).payload})}resetConversation(){this.store.dispatch(st()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}configure(t){this.store.dispatch(lf(t))}setVisitorInfo(t){this.store.dispatch(l1(t))}setCustomData(t){this.store.dispatch(c1(t))}setAgentInfo(t,n){return _(this,null,function*(){var o;yield this.store.dispatch(Ql(b(b({},t),n))),((o=this.state.info.agentInfo)==null?void 0:o.agentNickname)||this.broadcastEvents.send(vf,{showNicknameDialog:!0})})}setAgentSettings(t){return _(this,null,function*(){yield this.store.dispatch(Ry(t))})}getAgentSettings(){return _(this,null,function*(){return(yield this.store.dispatch(Py())).payload})}refresh(){return _(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(mf({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()}))}notifyExternalSuggestion(t){this.store.dispatch(En(t))}evaluateAssistant(t,n){return _(this,null,function*(){var c;let{input:r={},transcript:o,showCuesInWidget:i=!0,includeMetadata:s}=n||{},a=yield this.store.dispatch(Lr({assistantCode:t,transcript:o,includeMetadata:s,input:r,skipState:!i}));if(a.error)throw new Error(`Assistant evaluation failed: ${(c=a.payload)!=null?c:a.error.message}`);return a.payload.output})}evaluateConversationAssistant(t,n){return _(this,null,function*(){yield this.loadProfileConfig();let r=this.state.profile.data;if(!r){te.warn("Can't evaluate assistant when profile is not loaded yet.");return}let o=JI(r,t);yield Promise.all(o.map(i=>this.queues.push(i,()=>_(this,null,function*(){yield this.evaluateAssistant(i,b({includeMetadata:!0},n))})).catch(s=>{if(s instanceof au){te.warn(`Queued assistant "${i}" was outdated and dropped`);return}throw s})))})}handleKeyDown(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui,{textSuggestions:o,selectedSuggestionIndex:i,selection:s}=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(YC(ky(t))),!Pr(this.state)||t.key!=="Tab"&&!c)return;let d=()=>{n||!f||s&&(t.shiftKey||(this.store.dispatch(ZC()),t.preventDefault()))},p=()=>{n||!f||a&&i<=0||s&&(t.shiftKey||(this.store.dispatch(JC()),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(pf(-1)),this.store.dispatch(si({collapse:!0})),this.store.dispatch(uR(!0)),t.preventDefault());break}case"Tab":{t.preventDefault();let h=ra(this.state);if(!h)return;this.store.dispatch(Fc(!1)),this.store.dispatch(En({text:h.text,suggestion:h,eventMetrics:{inputType:"tab"},replace:"until-selection-end"}));break}case" ":{if(this.settings.inlineSuggestions||this.state.input.selectedSuggestionIndex===-1)return;let h=ra(this.state);if(!h)return;this.store.dispatch(En({text:h.text,suggestion:h,eventMetrics:{inputType:"space"},replace:"until-selection-end"}));break}case"Enter":{if(this.settings.inlineSuggestions||t.shiftKey||this.state.input.selectedSuggestionIndex===-1)return;let h=ra(this.state);if(!h)return;this.store.dispatch(En({text:h.text,suggestion:h,eventMetrics:{inputType:"enter"},replace:"until-selection-end"})),t.preventDefault();break}default:}n&&r&&this.store.dispatch(si({collapse:!1}))}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(Zo([]))}handlingTimeStart(){this.state.handlingTime.startTime||(te.info("Start handling time"),this.store.dispatch(PI()))}handlingTimeStop(){this.state.handlingTime.startTime&&(te.info("Stop handling time"),this.store.dispatch(um()))}logSendMessage(t){let n=BI(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=HI(this.state,{version:this.version});t&&(this.deepdeskApi.sendEvent("Handling Time",{conversationId:this.conversationId(),data:t}),this.store.dispatch(II()))}notifySubmit(t={}){var n;this.shouldAbort()||(this.store.dispatch(Hi((n=t.text)!=null?n:this.state.input.text)),this.store.dispatch(t1()))}emit(t,n){let r=this.eventListeners[t];r&&r.forEach(o=>{try{o(n)}catch(i){te.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),te.error(i)}})}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(u1(t))}whenConversationLoaded(t){let n=i=>{var s;return(s=i.conversation.current)==null?void 0:s.id},r=()=>this.loadProfileConfig().then(()=>t());return n(this.state)&&r(),this.subscribe(n,i=>{i&&r()})}overlayContainerFactory(t,n,r,o){let[i,s]=su(n,r);return i.setAttribute("translate","no"),i.dataset.testid=t,o&&i.classList.add(o),[i,s]}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 i=(a=t.ownerDocument.defaultView)==null?void 0:a.frameElement,s=i?i.ownerDocument.defaultView:null;if(i&&(s===window||(s==null?void 0:s.parent)===window)){let[c,l]=su(i,{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 os(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),te.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()?(te.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(e1(r.metrics))):te.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(!fm(t))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let d=n,{customStyles:r,closestScrollSelector:o,floatingMenuParent:i,appendOverlayTo:s,inputMediator:a}=d,c=oe(d,["customStyles","closestScrollSelector","floatingMenuParent","appendOverlayTo","inputMediator"]),l={customStyles:r,closestScrollSelector:o,floatingMenuParent:i,appendOverlayTo:s};this.configure(c),this.settings.automaticHandlingTime&&this.setupHandlingTime(t),os(t),this.inputMediator=a||(is(t)?new ds(t):new us(t)),this.inputMediator.on("change",({plainText:p,rawHTML:h})=>{this.store.dispatch(mf({text:p,html:h}))}),this.inputMediator.on("keyup",p=>{this.store.dispatch(XC(ky(p)))}),this.inputMediator.on("keydown",p=>{this.handleKeyDown(p)}),this.inputMediator.on("paste",({pastedText:p,selectionText:h})=>{this.store.dispatch(QC({text:p,selectionText:h}))}),this.inputMediator.on("cut",({selectionText:p})=>{this.store.dispatch(qC(p))});let u;this.inputMediator.on("selection",p=>{clearTimeout(u),p===null?u=setTimeout(()=>{p!==null&&this.store.dispatch(gf(p))},500):this.store.dispatch(gf(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(vp(!1))}),this.inputMediator.on("focus",()=>{this.store.dispatch(vp(!0))}),this.renderSuggestions(t,l),this.subscribe(Js("inlineSuggestions"),()=>{this.renderSuggestions(t,l)}),this.subscribe(Js("suggestionsPlacement"),()=>{this.renderSuggestions(t,l)});let f=this.renderOverlays(n);this.unmountHandlers.push(()=>{f.unmount()}),this.store.dispatch(mf({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()})),this.store.dispatch(gf(this.inputMediator.getSelection())),this.store.dispatch(vp(this.inputMediator.isFocused)),this.unmountHandlers.push(()=>{this.state.input.text!==""&&this.storeMetrics()}),this.whenConversationLoaded(()=>{this.restoreMetrics(),this.syncInputMediator(),this.refreshTextSuggestions(),this.promptForNickname()}),this.isMounted=!0}promptForNickname(t){if(this.nicknameDialogUnsubscribe||this.nicknameDialogFailed)return;let n=this.createContainer("nickname-dialog",document.body);document.body.appendChild(n);let r=(0,Co.createRoot)(n),o=null,i=a=>{o=a,s()},s=()=>{r==null||r.render((0,we.jsx)(co,{store:this.store,children:(0,we.jsx)(to,{broadcastEvents:this.broadcastEvents,children:(0,we.jsx)(tA,{id:"deepdesk-nickname-dialog",error:o,onSave:a=>_(this,null,function*(){try{yield this.store.dispatch(s1({agentNickname:a})).unwrap(),console.log("setAgentNickname",a),this.broadcastEvents.send(vf,{showNicknameDialog:!1}),this.nicknameDialogUnsubscribe&&this.nicknameDialogUnsubscribe()}catch(c){te.error("Error setting agent nickname",c),i("error"),this.nicknameDialogFailed=!0}})})})}))};s(),this.nicknameDialogUnsubscribe=()=>{r.unmount(),n.remove(),this.nicknameDialogUnsubscribe=null}}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,i;(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(s=>s()),this.unmountHandlers=[],(i=this.inputMediator)==null||i.dispose(),this.nicknameDialogUnsubscribe&&this.nicknameDialogUnsubscribe(),this.isMounted=!1}dispose(){this.unmount(),this.unmountWidget(),this.disposeHandlers.forEach(t=>t()),this.disposeHandlers=[],this.off()}renderSuggestions(t,n){var r,o,i,s;(r=this.floatingMenu)==null||r.unmount(),(o=this.inlineSuggestions)==null||o.unmount(),(i=this.aboveSuggestions)==null||i.unmount(),(s=this.belowSuggestions)==null||s.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"),i=(0,Co.createRoot)(o);i.render((0,we.jsx)(co,{store:this.store,customStyles:r,children:(0,we.jsx)(to,{broadcastEvents:this.broadcastEvents,children:(0,we.jsx)(wR,{})})}));let s=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",s),{unmount:()=>{var a;(a=this.inputMediator)==null||a.off("caretposition",s),i.unmount(),o.remove()}}}renderAboveOrBelowSuggestions(t,n,r){let{customStyles:o,closestScrollSelector:i,appendOverlayTo:s}=n,a=i&&ex(t,i)||void 0,[c,l]=this.overlayContainerFactory("deepdesk-tab-completion",a||t,{appendTo:s,closestScrollElement:a,mirrorOverflow:!0,onRemove:()=>this.unmount()},o==null?void 0:o.rootNode),[u,f]=this.overlayContainerFactory("deepdesk-suggestions-overlay",a||t,{appendTo:s,placement:r},o==null?void 0:o.suggestionsRootNode),d=(0,Co.createRoot)(c);d.render((0,we.jsx)(co,{store:this.store,customStyles:o,children:(0,we.jsx)(to,{broadcastEvents:this.broadcastEvents,children:(0,we.jsx)(QR,{inputElement:t})})}));let p=(0,Co.createRoot)(u);return p.render((0,we.jsx)(co,{store:this.store,customStyles:o,children:(0,we.jsx)(to,{broadcastEvents:this.broadcastEvents,children:(0,we.jsx)(AR,{onLogIn:()=>this.loginViaPopup().catch(h=>te.warn(h.message))})})})),{unmount(){d.unmount(),p.unmount(),l(),f()}}}renderFloatingMenu(t,n){let{customStyles:r,closestScrollSelector:o,appendOverlayTo:i,floatingMenuParent:s}=n,a=o&&ex(t,o)||void 0,[c,l]=this.overlayContainerFactory("floating-menu",a||t,{appendTo:s!=null?s:i},r==null?void 0:r.floatingMenuParent),u=(0,Co.createRoot)(c);return u.render((0,we.jsx)(co,{store:this.store,customStyles:r,children:(0,we.jsx)(to,{broadcastEvents:this.broadcastEvents,children:(0,we.jsx)(aR,{onLogIn:()=>this.loginViaPopup().catch(f=>te.warn(f.message))})})})),{unmount(){u.unmount(),l()}}}renderOverlays(t){let{customStyles:n}=t,r=this.createContainer("deepdesk-overlays"),o=(0,Co.createRoot)(r);return o.render((0,we.jsx)(co,{store:this.store,customStyles:n,children:(0,we.jsx)(to,{broadcastEvents:this.broadcastEvents,children:(0,we.jsx)(nR,{})})})),{unmount(){o.unmount(),r.remove()}}}renderWidget(t,n={}){if(this.widgetElement&&te.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,isEmbedded:i}=n;this.widgetElement=t,this.configure({showImages:o,isEmbedded:i}),this.widgetRoot=(0,Co.createRoot)(t),this.widgetRoot.render((0,we.jsx)(co,{store:this.store,customStyles:r,children:(0,we.jsx)(to,{broadcastEvents:this.broadcastEvents,children:(0,we.jsx)(yI,{assistantOptions:n.assistantOptions,knowledgeAssistOptions:n.knowledgeAssist,onLogIn:()=>this.loginViaPopup().catch(s=>te.warn(s.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:i}=r,s=(0,Co.createRoot)(n);return s.render((0,we.jsx)(co,{store:this.store,customStyles:o,children:(0,we.jsx)(to,{broadcastEvents:this.broadcastEvents,children:(0,we.jsx)(j0,{children:(0,we.jsxs)(im,{assistantCode:t,initialQuestion:i,evaluateKnowledgeAssistFn:Kc,children:[(0,we.jsx)(bs,{children:(0,we.jsx)(am,{title:r.title,emptyState:r.emptyState})}),(0,we.jsx)(W0,{children:(0,we.jsx)(sm,{})})]})})})})),{unmount(){s.unmount()}}}setupHandlingTime(t){let n=gm(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){UI(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(()=>_(this,null,function*(){yield this.store.dispatch(pc());let t=Vi(this.state);t&&this.store.dispatch(lf({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 _(this,null,function*(){return new Promise((n,r)=>{let o=new MessageChannel,i=o.port1,s=this.settings.adminUrl,a=new URL(t!=null&&t.url?t==null?void 0:t.url:`${s}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let c=!1,l=()=>{u&&!u.closed&&u.close(),window.removeEventListener("message",f),clearInterval(d)};i.onmessage=p=>_(this,null,function*(){var h,g;if((h=p.data)!=null&&h.jwt)try{yield this.deepdeskApi.exchangeTokenForAccessCookie((g=p.data)==null?void 0:g.jwt),yield this.isLoggedIn(),this.broadcastEvents.send(Jl),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=>_(this,null,function*(){var h;if(p.origin===a.origin)switch((h=p.data)==null?void 0:h.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){te.error("Error posting message to popup",g),r(g)}break}case"deepdesk-popup-error":{l(),p.data.message==="Timeout"&&te.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 _(this,null,function*(){this.isMounted&&(yield this.store.dispatch(gp()))})}refreshWidgetSuggestions(){return _(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(ur());break;case"pinned-messages":case"sticky-messages":break;default:Ru.includes(r)||this.store.dispatch(dr(r))}})}catch(r){this.handleError(r)}})}};Wa.version="18.2.1-beta.14",Wa.count=0;var lu=Wa;function OF(e){return _(this,null,function*(){var o,i,s;let n=yield((o=e.fetch)!=null?o:window.fetch)(e.url),r=yield n.blob();return new File([r],e.name,{type:(s=(i=e.mimeType)!=null?i:n.headers.get("Content-Type"))!=null?s:"image/jpeg"})})}function rA(e,t){return _(this,null,function*(){let n=yield OF(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 oA(e,t,n){return _(this,null,function*(){yield new Eo(e).authenticateWithKey(t,n)})}function iA(e){return e.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}function sA(r,o){return _(this,arguments,function*(e,t,n={}){var f,d;let{value:i}=e,{start:s,end:a}=(f=n.replace)!=null?f:{start:0,end:i.length},c=`${i.slice(0,s)}${t}${i.slice(a)}`,l=(d=n.selectionAfter)!=null?d:{start:s+t.length,end:s+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 aA(r,o){return _(this,arguments,function*(e,t,n={}){let i=n.replace?di(e,n.replace.start,n.replace.end):Ha(e),s,a=()=>{if(n.setRange)return n.setRange(i.cloneRange());i.deleteContents(),s=document.createElement("span"),i.insertNode(s),n.insertBRs!==!1?t.split(`
|
|
81
|
+
`);let h=d?r:0,g=p?Math.min(i,u.childNodes.length):u.childNodes.length;for(let x=h;x<g&&(l(u.childNodes[x]),a!==2);x++);break}default:break}p&&(a=2)}return l(e),c}var xI=(s=>(s.CUT="Cut",s.BACKSPACE="Backspace",s.DELETE="Delete",s.ERASEEOF="EraseEof",s.UNDO="Undo",s.CLEAR="Clear",s))(xI||{}),bo=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 i=this.getCaretPosition();Qo(i,this.cachedCaretPosition)||(this.cachedCaretPosition=i,this.emit("caretposition",i))}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(xI).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 SI(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var us=class extends bo{constructor(){super(...arguments);this.lastKnownSelection=null}getRootNode(){return this.element.getRootNode()}getText(){let n=new Range;return n.selectNodeContents(this.element),iu(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 i=this.element.ownerDocument.createRange();return i.setStart(o==null?void 0:o.startContainer,o==null?void 0:o.startOffset),i.setEnd(o==null?void 0:o.endContainer,o==null?void 0:o.endOffset),!i||!this.element.contains(i.startContainer)||!this.element.contains(i.endContainer)?null:i}getCaretPosition(){let n=this.getRange();if(!n||!n.collapsed||!("getBoundingClientRect"in n))return null;let r=n.getBoundingClientRect();return!SI(r)&&(n.insertNode(this.element.ownerDocument.createTextNode("\u2060")),r=n.getBoundingClientRect(),n.deleteContents(),!SI(r))?null:{top:r.top+r.height,left:r.left}}getSelection(){let n=this.getRange();if(n)return ou(this.element,n);let r=this.lastKnownSelection;if(r&&vI(this.element,r.start,r.end))return r;let o=Ha(this.element);return o.collapse(!1),ou(this.element,o)}getSelectedText(){let{start:n,end:r}=this.getSelection();return iu(this.element,di(this.element,n,r))}listen(){super.listen();let n=new MutationObserver(i=>{var s,a;i.length===2&&i[0].addedNodes.length===1&&((s=i[0].addedNodes[0])==null?void 0:s.textContent)==="\u2060"&&((a=i[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 hF=["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 wI(e,t){let n="mozInnerScreenX"in window,r=document.createElement("div");r.id="input-textarea-caret-position-mirror-div";let o=r.style,i=window.getComputedStyle(e),s=e.ownerDocument.body;o.whiteSpace="pre-wrap",o.wordWrap="break-word",o.position="absolute",o.visibility="hidden",hF.forEach(u=>{o[u]=i[u]}),n?e.scrollHeight>Number.parseInt(i.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),s.appendChild(r);let c=e.getBoundingClientRect(),l={top:c.top-e.scrollTop+a.offsetTop+Number.parseInt(i.borderTopWidth)+a.offsetHeight,left:c.left-e.scrollLeft+a.offsetLeft+Number.parseInt(i.borderLeftWidth)};return s.removeChild(r),l}var ds=class extends bo{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 wI(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 i;return(i=n==null?void 0:n.get)==null?void 0:i.call(this.element)},set:i=>{var s;(s=n==null?void 0:n.set)==null||s.call(this.element,i),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 bI(e,t,n){let r=`deepdesk-iframe-${e}`,o=document.getElementById(r);if(o)return o;let i=document.createElement("iframe"),s=new URL(t);return Object.entries(n).forEach(([a,c])=>{s.searchParams.append(a,c)}),i.style.position="absolute",i.style.left="-999em",i.style.width="0px",i.style.height="0px",i.tabIndex=-1,i.id=r,i.title=`iframe-${e}`,i.src=s.toString(),window.document.body.appendChild(i),i}function yF(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch(t){return e}}var $0=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()}},K0=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.disposeHandlers=[];this.iframe=bI(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()}},G0=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(),te.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 K0(t,this.deepdeskUrl,{debug:!0}):new $0(t),r=o=>{var s,a;if(o.origin!==this.deepdeskUrl)return;let i=yF(o.data);typeof i!="object"||i.type!=="event"||i.channel!==t||(te.info("Received broadcast event",this.externalId,o),(a=(s=this.eventMap)[i.name])==null||a.call(s,i.payload))};return n.onMessage(r),n}send(t,n,r){var s,a;te.info("Broadcast event",{externalId:this.externalId,name:t,payload:n});let o={type:"event",name:t,payload:n};r!==!1&&((a=(s=this.eventMap)[t])==null||a.call(s,n));let i=this.externalId==="deepdesk-general"?this.defaultChannel:this.channel;i==null||i.postMessage(P(b({},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)}},EI=G0;function vF(e){return e.replace(/(_\w)/g,t=>t[1].toUpperCase())}function Ue(e){return Array.isArray(e)?e.map(Ue):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>P(b({},t),{[vF(n)]:Ue(e[n])}),{}):e}function xF(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function en(e){return Array.isArray(e)?e.map(en):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>P(b({},t),{[xF(n)]:en(e[n])}),{}):e}var Ba=class extends Error{constructor(n,r){super(n);this.body=r;this.name="CustomError"}};var q0=e=>new Promise(t=>{setTimeout(t,e)});var Ua=class extends Ba{constructor(){super(...arguments);this.name="ClientError"}},X0=class extends Ba{constructor(){super(...arguments);this.name="ServerError"}},Y0=new Map;function SF(e){return _(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:(te.warn("Unexpected response body:",n.slice(0,20)),JSON.parse(n))})}var fi=class fi{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 i={isAborted:!1,reject:o},s=`${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:h=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(Y0.has(s)){r(Y0.get(s));return}}let m=P(b({credentials:"include"},v),{headers:b({Accept:"application/json","Content-Type":"application/json"},v.headers)});!c&&this.csrfToken&&(m.headers=P(b({},m.headers),{"X-CSRFToken":this.csrfToken})),typeof x=="string"&&(m.headers=P(b({},m.headers),{"X-Deepdesk-API-Version":x}));let y=f,S=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[s]&&u&&(this.latestRequestByUrl[s].isAborted=!0,this.latestRequestByUrl[s].reject(new Error("Aborted"))),this.latestRequestByUrl[s]=i;let E=()=>_(this,null,function*(){return y--,a(s,m).then(k=>_(this,null,function*(){return g(k)&&!i.isAborted&&y>0?(yield q0(d),E()):k.status===401&&p===!0&&S===!1?(S=!0,yield this.refreshToken(),E()):k})).catch(k=>_(this,null,function*(){if(h(k)&&!i.isAborted&&y>0)return yield q0(d),E();throw k}))});E().then(k=>_(this,null,function*(){let I=yield SF(k);if(delete this.latestRequestByUrl[s],k.status>=500){o(new X0("Server Error",I));return}if(k.status===401){o(new Ua("Unauthorized",I));return}if(k.status===403){o(new Ua("Forbidden",I));return}if(k.status===404){o(new Ua("Not Found",I));return}if(k.status>=400){o(new Ua("Bad Request",I));return}l&&Y0.set(s,I),r(I)})).catch(k=>{o(k)})})}validateToken(){return _(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 fi.refreshingToken||(fi.refreshingToken=this.get("/apis/admin/session/refresh/",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{fi.refreshingToken=null},1e3*60)})),fi.refreshingToken}get(t,n){return this.request(t,n)}post(t,n,r){return this.request(t,b({method:"POST",body:JSON.stringify(n)},r))}patch(t,n,r){return this.request(t,b({method:"PATCH",body:JSON.stringify(n)},r))}put(t,n,r){return this.request(t,b({method:"PUT",body:JSON.stringify(n)},r))}delete(t,n){return this.request(t,b({method:"DELETE"},n))}};fi.refreshingToken=null;var fs=fi;var CI;(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={}))})(CI||(CI={}));function Q0(e){return P(b({},Ue(e)),{metadata:e.metadata})}var ps=class ps{constructor(t,n={}){this.options=n;this.latestReceivedDeepdeskVersions={};this.shouldFetchCsrfToken=!0;this.client=new fs(t,{fetch:n.fetch}),this.client.patchFetch(r=>(o,i)=>_(this,null,function*(){let s=yield r(o,i);return this.handleDeepdeskVersionHeaders(s),s}))}preflight(){return _(this,null,function*(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let t=yield this.getCsrfToken();this.client.setCsrfToken(t)}return this.options.token?(ps.exchangeTokenPromise||(ps.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),ps.exchangeTokenPromise):Promise.resolve()})}createConversation(t){return _(this,null,function*(){var r;yield this.preflight(),te.info(`Creating conversation for session ${t.externalId} and agent ${t.agentId}`);let n=yield this.client.post("/api/v2/conversations",P(b({chat_start_time:new Date().toISOString()},en(t)),{metadata:(r=t.metadata)!=null?r:{}}));return Q0(n)})}getMe(){return _(this,null,function*(){let t=yield this.client.get("/apis/admin/session/me/");return Ue(t)})}postIdentity(t){return _(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/me/identities/",en(t))})}patchMe(t){return _(this,null,function*(){yield this.preflight();let n=yield this.client.patch("/apis/admin/session/me/",en(t));return Ue(n)})}getProfile(t){return _(this,null,function*(){let n=yield this.client.get(`/apis/admin/profiles/${t}/`,{useCache:!0});return Ue(n)})}getKnowledgeAssistant(t){return _(this,null,function*(){let n=yield this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{useCache:!0});return Ue(n)})}getContentTypes(){return _(this,null,function*(){let t=yield this.client.get("/apis/admin/content-types/",{useCache:!0});return Ue(t)})}getAccount(){return _(this,null,function*(){let t=yield this.client.get("/apis/admin/account/",{useCache:!0});return Ue(t)})}getPlatformConfig(t){return _(this,null,function*(){let n=t!==void 0?`/platform/config/${t}/`:"/platform/config/",{config:r}=yield this.client.get(n,{useCache:!0});return Ue(r)})}checkUserExists(t){return _(this,null,function*(){let{exists:n}=yield this.client.get(`/apis/admin/users/exists?external_id=${t}`,{version:"v1"});return n})}getConversationByExternalId(r){return _(this,arguments,function*(t,n={}){yield this.preflight(),te.info(`Getting conversation for session ${t}`);let{attempts:o=1,retryDelay:i=1e3}=n,s=yield this.client.get(`/api/v2/conversations/by_external_id/${t}`,{attempts:o,retryDelay:i,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"});return te.info(`Successfully retrieved conversation ${s.id} for session ${t}`),Q0(s)})}isConversationSupported(r){return _(this,arguments,function*(t,n={}){te.info(`Check if conversation for session ${t} is supported`);let{attempts:o=1,retryDelay:i=1e3}=n;return(yield this.client.get(`/api/v2/conversations/by_external_id/${t}/has_active_profile`,{attempts:o,retryDelay:i,retryOnResponse:a=>a.status===404||a.status>=500})).has_active_profile})}updateConversation(t,n){return _(this,null,function*(){var i;yield this.preflight();let r=en(n);n.metadata&&(r.metadata=(i=n.metadata)!=null?i:{});let o=yield this.client.put(`/api/v2/conversations/${t}`,r);return Q0(o)})}postMessages(t,n){return _(this,null,function*(){yield this.preflight(),yield this.client.post(`/api/v2/conversations/${t}/messages`,n.map(r=>P(b({},en(r)),{metadata:r.metadata})))})}sendEvent(t,n){return _(this,null,function*(){yield this.preflight();let a=n,{data:r}=a,o=oe(a,["data"]),i=Object.entries(this.latestReceivedDeepdeskVersions).reduce((c,[l,u])=>P(b({},c),{[l]:u}),{}),s=["platform","agentId","agentName","agentEmail","conversationId"].reduce((c,l)=>(o[l]&&(c[l]=o[l]),c),{});return this.client.post("/api/v2/events",en(P(b(b({},i),s),{data:r,name:t})),{version:"v2"})})}getEntities(t){return _(this,null,function*(){return yield this.preflight(),yield this.client.post("/api/v2/entities",{messages:t.filter(r=>r.text)})})}getTemporaryExchangeToken(){return _(this,null,function*(){return(yield this.client.get("/apis/admin/session/exchange-token/")).jwt})}exchangeTokenForAccessCookie(t){return _(this,null,function*(){return this.client.post("/apis/admin/session/jwt/",{jwt:t}).catch(n=>{throw te.warn(`Invalid token '${t}'`),n})})}authenticateWithKey(t,n){return _(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/api-key/",en(n),{refreshTokenOn401:!1,headers:{apikey:t}})})}getTextSuggestions(o){return _(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}`,en(n),{abortLatest:!0})).map(s=>P(b({},Ue(s)),{text:s.text||s.url||s.message,source:r,type:r})).filter((s,a,c)=>a===c.findIndex(l=>l.text===s.text))})}isLoggedIn(){return _(this,null,function*(){return yield this.preflight(),this.client.validateToken()})}getAutocompleteSuggestions(t,n){return _(this,null,function*(){return yield this.preflight(),(yield this.client.post(`/api/v2/conversations/${t}/autocomplete`,en(n),{abortLatest:!0})).map(o=>({score:1,source:o.source,sourceText:o.source_text,text:o.label,trainingJobs:o.training_jobs,searchKeywords:o.search_keywords,type:o.source})).filter((o,i,s)=>i===s.findIndex(a=>a.text===o.text))})}getPinnedMessages(t){return _(this,null,function*(){let n=yield this.client.get(`/api/v2/profiles/${t}/pinned-messages`,{abortLatest:!0});return Ue(n).map(r=>P(b({},r),{text:r.message,source:"sticky-messages",type:"pinned-message"}))})}getStyleSuggestions(t){return _(this,null,function*(){let n=yield this.client.post("/api/v2/style-suggestions",en(t),{abortLatest:!0,version:"v2"});return Ue(n)})}search(t){return _(this,null,function*(){let n=yield this.client.post(`/api/v2/profiles/${t.profile}/search`,en(t));return Ue(n)})}requestLoginByEmail(t){return _(this,null,function*(){yield this.preflight();let n=yield this.client.post("/apis/admin/session/passwordless/request/",{email:t});return Ue(n)})}requestPasswordlessToken(){return _(this,null,function*(){let t=yield this.client.get("/apis/admin/session/passwordless/request/");return Ue(t.token)})}getCsrfToken(){return _(this,null,function*(){let{token:t}=yield this.client.get("/apis/admin/session/csrf/");return t})}verifyLoginToken(t){return _(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/login/",{token:t});return Ue(n)})}evaluateAssistant(t,n){return _(this,null,function*(){var s;yield this.preflight();let r=new URLSearchParams;n!=null&&n.externalConversationId&&r.append("external_conversation_id",n.externalConversationId);let o=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(o,{input:(s=n==null?void 0:n.input)!=null?s:{},conversation:n==null?void 0:n.transcript});return Ue(i)})}createAssistantThread(t){return _(this,null,function*(){yield this.preflight();let{assistantCode:n}=t,r=yield this.client.post(`/apis/admin/assistants/${n}/threads/`,{});return Ue(r)})}postMessageToAssistantThread(t){return _(this,null,function*(){yield this.preflight();let{assistantCode:n,threadId:r,message:o}=t,i=yield this.client.post(`/apis/admin/assistants/${n}/threads/${r}/messages/`,{content:o,role:"user"});return Ue(i)})}translateMessages(t){return _(this,null,function*(){yield this.preflight();let n=yield this.client.post("/api/v2/translate",en(t));return Ue(n)})}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),i=o.match(lS);if(!n||!i)return;let s=i[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[s];a&&n&&a!==n&&te.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[s]=n})}};ps.exchangeTokenPromise=null;var Eo=ps;var TI={startTime:null,stopTime:null},kI=e=>e.handlingTime,RI=Ee({name:"handlingTime",initialState:TI,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(st,()=>TI)}}),{handlingTimeStart:PI,handlingTimeStop:um,handlingTimeReset:II}=RI.actions,AI=RI.reducer;var _I=(e={})=>{let t=b({onAuthError:ea(!1)},e);return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var dm={list:{keywordMatches:[]},fetchState:"idle"};var ms=fe("styleSuggestions/getAll",(n,r)=>_(null,[n,r],function*({text:e},t){var c;let{deepdeskAPI:o}=t.extra,i=t.getState(),{showStyleSuggestions:s}=i.settings,a=(c=i.conversation.current)==null?void 0:c.profileCode;if(!s)return dm.list;if(!a)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:a,message:e})})),wF=Ee({name:"styleSuggestions",initialState:dm,reducers:{},extraReducers:e=>{e.addCase(ms.pending,t=>{t.fetchState="loading"}).addCase(ms.rejected,t=>{t.fetchState="error"}).addCase(ms.fulfilled,(t,n)=>{t.fetchState="done",Qo(t.list,n.payload)||(t.list=n.payload)}).addCase(Hi,t=>{t.list=dm.list}).addCase(st,()=>dm)}}),MI=wF.reducer;var LI=(e={})=>{let t,n=!0,r=b({getStyleSuggestions:ms,debounce:500},e);return o=>i=>s=>{var p;let a=o.getState().input.text,c=i(s),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 bF(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end}var NI=(e={})=>{let t=b({getTextSuggestions:dr,getAutocompleteSuggestions:Oc,debounce:200,check:Pr},e),n;return r=>o=>i=>{var g;let{input:s}=r.getState(),a=o(i),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=i.type===gp.toString();if(!f||!l&&!u)return a;let{input:p}=c;return bF(p,s)&&!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 OI=ms.fulfilled.toString();function EF(e,t){let n=new Set([...t.keywordMatches.map(o=>o.keyword)]),r=[];return n.forEach(o=>{let i=e.keywordMatches.filter(c=>c.keyword===o),s=t.keywordMatches.filter(c=>c.keyword===o),a=s.length-i.length;a<=0||r.push(...s.slice(0,a))}),r}var DI=e=>t=>n=>r=>{var l;if(r.type!==OI){n(r);return}let o=t.getState().styleSuggestions.list;n(r);let i=t.getState(),s=i.styleSuggestions.list,a=(l=i.conversation)==null?void 0:l.current;if(o===s)return;let c=EF(o,s);r.type===OI&&c.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:c}})};var CF=Yd({assistants:bP,auth:FC,conversation:jC,contentTypes:U1,passwordlessToken:TP,entities:Bk,handlingTime:AI,info:f1,input:n1,settings:_C,profile:K1,search:v1,styleSuggestions:MI,ui:fR,textSuggestions:Xk});function FI(e){return oC({reducer:CF,middleware:t=>{var r;let n=t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI}},serializableCheck:!1}).concat(_I()).concat(NI({debounce:200})).concat(LI({debounce:500})).concat(DI(e.deepdeskAPI));return((r=e.middleware)!=null?r:[]).reduce((o,i)=>o.concat(i),n)},preloadedState:e.preloadedState})}var TF=e=>{var t,n;return(n=(t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())!=null?n:"unknown"},kF=e=>t=>n=>r=>{var a,c;let o=t.getState(),i=Js("inlineSuggestions")(o);switch(r.type){case ea.toString():{!r.payload&&e.emit("logout",void 0);break}case ur.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 Hi.toString():e.logSendMessage(r.payload);break;case $p.toString():e.emit("call-to-action",{cue:r.payload});break;case Lr.fulfilled.toString():r.isBroadcasted||e.broadcast(Ay,r,!1);break;default:break}let s=n(r);switch(r.type){case Hi.toString():e.handleAfterSendMessage(r.payload);break;case Fc.toString():e.onUpdateShowTabHint(r.payload);break;case um.toString():e.logHandlingTime();break;case oa.toString():e.broadcast(xf,r);break;case zi.toString():e.broadcast(xf,r);break;case Kp.toString():t.dispatch(zi({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(b({},r.meta.arg),{cue:l}));break}case En.toString():{let{start:l,end:u}=o.input.selection;e.emit("select-suggestion",P(b({type:TF(r.payload.suggestion)},r.payload),{replace:r.payload.replace==="selection"?{start:l,end:u}:{start:0,end:u}})),i&&t.dispatch(Zo([]));break}case ff.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 Zo.toString():{i&&r.payload.length>0&&t.dispatch(pf(0));break}default:break}return s},zI=kF;function Z0(e){return e.toISOString().replace("T"," ").replace("Z","")}var RF=(e,t)=>t.version,HI=Bt([ia,Cr,kI,RF],(e,t,n,r)=>{if(!t)return te.warn("No conversationId for handling time metrics"),null;let{startTime:o,stopTime:i}=n;return!o||!i?(te.warn("No startTime and stopTime for handling time metrics"),null):{conversationId:t,clientVersion:r,agentId:e==null?void 0:e.agentId,agentName:e==null?void 0:e.agentName,agentEmail:e==null?void 0:e.agentEmail,timeStart:Z0(o),timeStop:Z0(i)}});function BI(e,t){let{text:n,metrics:{numPaste:r,pastes:o,textSuggestions:i}}=e.input,s=n.length;return{source:"agent",clientVersion:t.version,pastes:o,lenTextTotal:s,numPastes:r,suggestions:i}}function J0(e,t){var i;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return J0(r,t);let o=(i=e.ownerDocument.defaultView)==null?void 0:i.frameElement;return o?J0(o,t):null}function ex(e,t){return J0(e,t)}function UI(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function PF(e){return typeof e=="object"&&e!==null&&"tagName"in e}function fm(e){return PF(e)&&(is(e)||Ep(e))}var WI,Or=new Map,IF=["bottom","height","left","right","top","width"],VI=(e,t)=>!e&&!t?!1:e&&!t||!e&&t?!0:IF.some(n=>e[n]!==t[n]);function jI(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,...jI(t)]:[]}function $I(e,t){return!e||!t?null:P(b({},e),{top:e.top+t.top,left:e.left+t.left})}var pm=!1,KI=()=>{pm=!0;let e=[];if(Or.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),Or.delete(n);return}let r=n.getBoundingClientRect();VI(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{let n=t.parentRects?t.parentRects.reduce($I,t.rect):t.rect;VI(n,t.totalRect)&&t.callbacks.forEach(r=>r(n)),t.totalRect=n}),Or.size===0){pm=!1;return}WI=window.requestAnimationFrame(KI)};function tx(e,t){let n=jI(e),r=[],o=n.map((i,s)=>tx(i,a=>{r[s]=a;let c=Or.get(e);if(!c)return;let l=r.reduce($I,c.rect);c.callbacks.forEach(u=>u(l))}));return{observe(i=!0){if(o.forEach(s=>s.observe(!1)),Or.has(e)){let s=Or.get(e);s.callbacks.push(t),s.rect&&t(s.rect)}else Or.set(e,{rect:void 0,callbacks:[t],parentRects:r});i&&!pm&&KI()},unobserve(){o.forEach(s=>s.unobserve());let i=Or.get(e);if(i){let s=i.callbacks.indexOf(t);s>=0&&i.callbacks.splice(s,1),i.callbacks.length||Or.delete(e),Or.size||(cancelAnimationFrame(WI),pm=!1)}}}}var GI,Dr=new Map,qI=()=>{Dr.forEach((e,t)=>{if(!t.isConnected){Dr.delete(t);return}let{clientHeight:n,scrollHeight:r}=t,o=r>n;e.visible!==o&&(e.visible=o,e.callbacks.forEach(i=>i(e.visible)))}),Dr.size!==0&&(GI=window.requestAnimationFrame(qI))};function YI(e,t){return{observe(){let n=Dr.size===0;Dr.has(e)?Dr.get(e).callbacks.push(t):Dr.set(e,{visible:void 0,callbacks:[t]}),n&&qI()},unobserve(){let n=Dr.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||Dr.delete(e),Dr.size||cancelAnimationFrame(GI)}}}}var nx=["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 rx(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function Va(e){return Number.parseFloat(e)}function mm(e){return Math.round(e*1e6)}function XI(e){return e/1e6}function ox(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=Va(e.width),i=Va(e.borderLeftWidth),s=Va(e.borderRightWidth),a=Va(e.paddingRight),c=XI(mm(o)-mm(i)-mm(s)),l=XI(mm(r));if(c-l>2){let u=c-l;n.style.paddingRight=`${a+u}px`}}function su(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",os(n);let r=window.getComputedStyle(e),o=!0,i=()=>{n.scrollTop=e.scrollTop};rx(r,n,nx),ox(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",i));let s=YI(e,()=>{rx(r,n,nx),ox(r,e,n),i(),setTimeout(i,0)}),a,c=!0,l=tx(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(rx(r,n,nx),ox(r,e,n),i(),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(),h=window.getComputedStyle(t.closestScrollElement),g=Va(h.borderTopWidth),x=Va(h.borderBottomWidth),v=p.top+g-d.top,m=d.top+d.height+-(p.top+p.height-x);n.style.clipPath=`inset(${v}px 0px ${m}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(),s.observe(),[n,()=>{e.removeEventListener("scroll",i),l.unobserve(),s.unobserve(),n.remove()}]}var QI=(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){te.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function AF(e){return e.offsetParent!==null}function ZI(e){if(!AF(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 gm(e,t,n=100){let r=ZI(e);t({isVisible:r});let o=setInterval(()=>{let i=ZI(e);i!==r&&(r=i,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var au=class extends Error{};function _F(){let e,t;return{promise:new Promise((r,o)=>{e=r,t=o}),resolve:e,reject:t}}var hm=class{constructor(){this.queues={}}push(t,n){let r=()=>{let i=this.queues[t][1];i?(this.queues[t]=[i.promise,null],i.resolve()):delete this.queues[t]};if(!this.queues[t]){let i=n().finally(r);return this.queues[t]=[i,null],i}this.queues[t][1]&&this.queues[t][1].reject(new au("Queued async function is outdated"));let o=_F();return this.queues[t][1]=o,o.promise.then(()=>n().finally(r))}};var MF={accepted:"onConversationAcceptedAssistants","new-message":"onConversationNewMessageAssistants",ended:"onConversationEndedAssistants"},JI=(e,t)=>{var o,i,s;if(!((s=(i=(o=e.uiConfig)==null?void 0:o.widget)==null?void 0:i.types.find(a=>a.type==="cues"))==null?void 0:s.isActive))return te.warn("Triggered a conversation assistant, but cues are not configured in widget."),[];let r=e[MF[t]];return r&&r.length>0?r.map(a=>a.code):(te.warn(`No assistant set in profile for conversation event "${t}"`),[])};var ym=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=Ue(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 pi=w(Y());var eA={root:"dd-7zvcP",dialogContent:"dd-4C0lK",continueButton:"dd-YUPQW",buttonContinueWrapper:"dd-IKpYs",nicknameInput:"dd-rxhGp",titleWrapper:"dd-nw3nD",title:"dd-5iof5",closeButtonWrapper:"dd-UUAzA",closeButton:"dd-7rjP5",buttonsWrapper:"dd-5e9Xb",errorMessage:"dd--5VgX",errorLink:"dd-u461n"};var ix={};dt(ix,{enUS:()=>LF,nlNL:()=>NF});var LF={title:[{type:0,value:"Enter your nickname"}],close:[{type:0,value:"Close"}],nicknameDialogTitle:[{type:0,value:"Please enter the name you'd like customers to see during chat conversations. This nickname will be used across your Deepdesk environment.Please enter the name you'd like customers to see during chat conversations. This nickname will be used across your Deepdesk environment."}],nicknameDialogInputPlaceholder:[{type:0,value:"Enter your nickname"}],nicknameDialogContinueButton:[{type:0,value:"Continue"}],nicknameDialogError:[{type:0,value:"Nickname cannot be empty or spaces only"}],nicknameDialogEmojiError:[{type:0,value:"You cannot use emojis in this field."}],nicknameDialogSaveError:[{type:0,value:"We couldn't save your details just now. Please try again, or update it at "},{type:1,value:"account"},{type:0,value:".deepdesk.com/admin/user-settings"}],nicknameDialogSaveErrorWithoutLink:[{type:0,value:"We couldn\u2019t save your details just now. Please try again later, or update them in My Deepdesk \u2192 Settings."}]},NF={title:[{type:0,value:"Voer je bijnaam in"}],close:[{type:0,value:"Sluiten"}],nicknameDialogTitle:[{type:0,value:"Voer de naam in die je wilt dat klanten zien tijdens chatgesprekken. Deze bijnaam wordt gebruikt in je Deepdesk-omgeving."}],nicknameDialogInputPlaceholder:[{type:0,value:"Voer je bijnaam in"}],nicknameDialogContinueButton:[{type:0,value:"Doorgaan"}],nicknameDialogError:[{type:0,value:"Bijnaam mag niet leeg of alleen spaties zijn"}],nicknameDialogEmojiError:[{type:0,value:"Je kunt geen emoji's gebruiken in dit veld."}],nicknameDialogSaveError:[{type:0,value:"We konden je gegevens nu niet opslaan. Probeer het opnieuw of werk het bij op "},{type:1,value:"account"},{type:0,value:".deepdesk.com/admin/user-settings"}],nicknameDialogSaveErrorWithoutLink:[{type:0,value:"We konden je gegevens nu niet opslaan. Probeer het opnieuw later, of werk ze bij in My Deepdesk \u2192 Instellingen."}]};var lt=w(R()),tA=({onClose:e,onSave:t,id:n,error:r})=>{let[o,i]=(0,pi.useState)(""),[s,a]=(0,pi.useState)(!1),[c,l]=(0,pi.useState)(!1),u=O("Nickname",eA),f=pi.default.useRef(null),d=K(v=>v.info.showNicknameDialog),p=ie(ix),h=ee("adminUrl");(0,pi.useEffect)(()=>{r&&a(!0)},[r]);let g=()=>{if(!f.current)return;o.trim()?f.current.setCustomValidity(""):f.current.setCustomValidity(p("nicknameDialogError")),f.current.reportValidity()},x=v=>{v.preventDefault();let m=o.trim(),y=v.currentTarget.querySelector("#nickname-input");if(!m){y.setCustomValidity(p("nicknameDialogError")),y.reportValidity();return}y.setCustomValidity(""),t(m)};return(0,lt.jsxs)(la,{isOpen:d,"datatest-id":n,onClose:e||(()=>{}),onBack:e||(()=>{}),children:[(0,lt.jsx)("div",{className:u.titleWrapper,children:(0,lt.jsx)("h1",{className:u.title,children:p("title")})}),(0,lt.jsxs)("form",{className:u.dialogContent,onSubmit:x,children:[(0,lt.jsx)("p",{children:p("nicknameDialogTitle")}),s&&r&&(0,lt.jsx)("div",{className:u.errorMessage,children:h?(()=>{let v=p("nicknameDialogSaveError",{account:h}),m=`${h}.deepdesk.com/admin/user-settings`,y=v.indexOf(m);if(y!==-1){let S=v.substring(0,y),E=v.substring(y+m.length);return(0,lt.jsxs)(lt.Fragment,{children:[S,(0,lt.jsx)("a",{href:m,target:"_blank",rel:"noopener noreferrer",className:u.errorLink,children:m}),E]})}return v})():p("nicknameDialogSaveErrorWithoutLink")}),(0,lt.jsx)("input",{required:!0,minLength:1,maxLength:20,"data-testid":"nickname-input",id:"nickname-input",className:u.nicknameInput,type:"text",placeholder:p("nicknameDialogInputPlaceholder"),value:o,onChange:v=>{l(new RegExp("\\p{Extended_Pictographic}","u").test(v.target.value)),i(v.target.value)},onBlur:g,ref:f}),c&&(0,lt.jsx)("div",{className:u.errorMessage,role:"alert",children:p("nicknameDialogEmojiError")}),(0,lt.jsxs)("div",{className:u.buttonsWrapper,children:[r?(0,lt.jsx)("div",{className:u.closeButtonWrapper,children:(0,lt.jsx)("button",{type:"button",className:u.closeButton,onClick:()=>e==null?void 0:e(),children:p("close")})}):null,(0,lt.jsx)("div",{className:u.buttonContinueWrapper,children:(0,lt.jsx)("button",{type:"submit",className:u.continueButton,disabled:!o.trim()||new RegExp("\\p{Extended_Pictographic}","u").test(o),children:p("nicknameDialogContinueButton")})})]})]})]})};var we=w(R());var nA=QI("showTabHint",!0),Wa=class Wa{constructor({deepdeskUrl:t,version:n=Wa.version||"unknown",locale:r="en-US",token:o,fetch:i,productName:s,createCustomChannel:a,websocketClient:c=ym}){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.nicknameDialogUnsubscribe=null;this.nicknameDialogFailed=!1;this.dynamicThunkObject={};this.queues=new hm;this.isMounted=!1;this.shouldRender=!0;this.loadProfileConfigPromise=null;let l=t.replace(/\/api$/,"");this.deepdeskApi=new Eo(l,{token:o,fetch:i}),this.version=n,this.instanceId=Wa.count++;let u={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[zI({broadcast:(h,g,x)=>{this.broadcastEvents.send(h,g,x)},emit:(h,g)=>this.emit(h,g),handleAfterSendMessage:h=>this.handleAfterSendMessage(h),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:h=>this.logSendMessage(h),onUpdateShowTabHint:h=>nA.update(h),sendEvent:(h,g)=>this.deepdeskApi.sendEvent(h,g)})]};this.store=FI(u),this.broadcastEvents=new EI({debug:!0,deepdeskUrl:l,eventMap:x1(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:()=>_(this,null,function*(){var h;return(h=Et(this.state))!=null?h:!1})}),this.whenLoggedIn(()=>this.ws.connect()),this.store.dispatch(Fc(nA.value())),this.store.dispatch(lf({locale:r,adminUrl:l,productName:s}));let f=[],d=h=>{if(!h.conversationId)return;let g=()=>{this.conversationId()===h.conversationId&&this.store.dispatch(wP(h))};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",h=>{if(!h.conversationId)return;let g=()=>{this.conversationId()===h.conversationId&&this.store.dispatch(SP(h))};this.hasConversation()?g():f.push(g)}),this.ws.on("assistants::suggest_as_reply",h=>{if(!h.conversationId)return;let g=()=>{this.conversationId()===h.conversationId&&this.store.dispatch(oa([{text:h.payload.message,type:"text",source:"assistant",assistantCode:h.code,sourceLabel:h.name}]))};this.hasConversation()?g():f.push(g)});let p=this.whenConversationLoaded(()=>{var h;this.broadcastEvents.setExternalId((h=this.state.conversation.current)==null?void 0:h.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=Fi(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?(te.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(te.warn("Profile has not been loaded (yet)"),!0):(te.warn("No conversation loaded (yet)"),!0)}whenLoggedIn(t){if(Et(this.state))t();else{let n=this.subscribe(Et,r=>{r&&t()});this.disposeHandlers.push(()=>{n()})}}login(){return this.store.dispatch(ea(null)),this.store.dispatch(Jr()),new Promise(t=>{this.whenLoggedIn(()=>t())})}isLoggedIn(){return _(this,null,function*(){return(yield this.store.dispatch(Jr())).payload})}isConversationSupported(t,n){return _(this,null,function*(){return(yield this.store.dispatch(Ey({externalId:t,options:n}))).payload})}createConversation(t){return _(this,null,function*(){var r;return this.hasConversation()&&this.externalId()!==t.externalId&&this.resetConversation(),(yield this.store.dispatch(cf(P(b({},t),{metadata:(r=t.metadata)!=null?r:{}})))).payload})}getConversationByExternalId(t,n){return _(this,null,function*(){return this.hasConversation()&&this.externalId()!==t&&this.resetConversation(),(yield this.store.dispatch(uf({externalId:t,options:n}))).payload})}upsertConversation(t){return _(this,null,function*(){var r;return this.hasConversation()&&this.externalId()!==t.externalId&&this.resetConversation(),(yield this.store.dispatch(Cy(P(b({},t),{metadata:(r=t.metadata)!=null?r:{}})))).payload})}postMessages(t){return _(this,null,function*(){yield this.store.dispatch(Ty(t))})}updateConversation(t){return _(this,null,function*(){return(yield this.store.dispatch(df(t))).payload})}resetConversation(){this.store.dispatch(st()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}configure(t){this.store.dispatch(lf(t))}setVisitorInfo(t){this.store.dispatch(l1(t))}setCustomData(t){this.store.dispatch(c1(t))}setAgentInfo(t,n){return _(this,null,function*(){var o;yield this.store.dispatch(Ql(b(b({},t),n))),((o=this.state.info.agentInfo)==null?void 0:o.agentNickname)||this.broadcastEvents.send(vf,{showNicknameDialog:!0})})}setAgentSettings(t){return _(this,null,function*(){yield this.store.dispatch(Ry(t))})}getAgentSettings(){return _(this,null,function*(){return(yield this.store.dispatch(Py())).payload})}refresh(){return _(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(mf({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()}))}notifyExternalSuggestion(t){this.store.dispatch(En(t))}evaluateAssistant(t,n){return _(this,null,function*(){var c;let{input:r={},transcript:o,showCuesInWidget:i=!0,includeMetadata:s}=n||{},a=yield this.store.dispatch(Lr({assistantCode:t,transcript:o,includeMetadata:s,input:r,skipState:!i}));if(a.error)throw new Error(`Assistant evaluation failed: ${(c=a.payload)!=null?c:a.error.message}`);return a.payload.output})}evaluateConversationAssistant(t,n){return _(this,null,function*(){yield this.loadProfileConfig();let r=this.state.profile.data;if(!r){te.warn("Can't evaluate assistant when profile is not loaded yet.");return}let o=JI(r,t);yield Promise.all(o.map(i=>this.queues.push(i,()=>_(this,null,function*(){yield this.evaluateAssistant(i,b({includeMetadata:!0},n))})).catch(s=>{if(s instanceof au){te.warn(`Queued assistant "${i}" was outdated and dropped`);return}throw s})))})}handleKeyDown(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui,{textSuggestions:o,selectedSuggestionIndex:i,selection:s}=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(YC(ky(t))),!Pr(this.state)||t.key!=="Tab"&&!c)return;let d=()=>{n||!f||s&&(t.shiftKey||(this.store.dispatch(ZC()),t.preventDefault()))},p=()=>{n||!f||a&&i<=0||s&&(t.shiftKey||(this.store.dispatch(JC()),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(pf(-1)),this.store.dispatch(si({collapse:!0})),this.store.dispatch(uR(!0)),t.preventDefault());break}case"Tab":{t.preventDefault();let h=ra(this.state);if(!h)return;this.store.dispatch(Fc(!1)),this.store.dispatch(En({text:h.text,suggestion:h,eventMetrics:{inputType:"tab"},replace:"until-selection-end"}));break}case" ":{if(this.settings.inlineSuggestions||this.state.input.selectedSuggestionIndex===-1)return;let h=ra(this.state);if(!h)return;this.store.dispatch(En({text:h.text,suggestion:h,eventMetrics:{inputType:"space"},replace:"until-selection-end"}));break}case"Enter":{if(this.settings.inlineSuggestions||t.shiftKey||this.state.input.selectedSuggestionIndex===-1)return;let h=ra(this.state);if(!h)return;this.store.dispatch(En({text:h.text,suggestion:h,eventMetrics:{inputType:"enter"},replace:"until-selection-end"})),t.preventDefault();break}default:}n&&r&&this.store.dispatch(si({collapse:!1}))}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(Zo([]))}handlingTimeStart(){this.state.handlingTime.startTime||(te.info("Start handling time"),this.store.dispatch(PI()))}handlingTimeStop(){this.state.handlingTime.startTime&&(te.info("Stop handling time"),this.store.dispatch(um()))}logSendMessage(t){let n=BI(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=HI(this.state,{version:this.version});t&&(this.deepdeskApi.sendEvent("Handling Time",{conversationId:this.conversationId(),data:t}),this.store.dispatch(II()))}notifySubmit(t={}){var n;this.shouldAbort()||(this.store.dispatch(Hi((n=t.text)!=null?n:this.state.input.text)),this.store.dispatch(t1()))}emit(t,n){let r=this.eventListeners[t];r&&r.forEach(o=>{try{o(n)}catch(i){te.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),te.error(i)}})}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(u1(t))}whenConversationLoaded(t){let n=i=>{var s;return(s=i.conversation.current)==null?void 0:s.id},r=()=>this.loadProfileConfig().then(()=>t());return n(this.state)&&r(),this.subscribe(n,i=>{i&&r()})}overlayContainerFactory(t,n,r,o){let[i,s]=su(n,r);return i.setAttribute("translate","no"),i.dataset.testid=t,o&&i.classList.add(o),[i,s]}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 i=(a=t.ownerDocument.defaultView)==null?void 0:a.frameElement,s=i?i.ownerDocument.defaultView:null;if(i&&(s===window||(s==null?void 0:s.parent)===window)){let[c,l]=su(i,{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 os(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),te.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()?(te.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(e1(r.metrics))):te.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(!fm(t))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let d=n,{customStyles:r,closestScrollSelector:o,floatingMenuParent:i,appendOverlayTo:s,inputMediator:a}=d,c=oe(d,["customStyles","closestScrollSelector","floatingMenuParent","appendOverlayTo","inputMediator"]),l={customStyles:r,closestScrollSelector:o,floatingMenuParent:i,appendOverlayTo:s};this.configure(c),this.settings.automaticHandlingTime&&this.setupHandlingTime(t),os(t),this.inputMediator=a||(is(t)?new ds(t):new us(t)),this.inputMediator.on("change",({plainText:p,rawHTML:h})=>{this.store.dispatch(mf({text:p,html:h}))}),this.inputMediator.on("keyup",p=>{this.store.dispatch(XC(ky(p)))}),this.inputMediator.on("keydown",p=>{this.handleKeyDown(p)}),this.inputMediator.on("paste",({pastedText:p,selectionText:h})=>{this.store.dispatch(QC({text:p,selectionText:h}))}),this.inputMediator.on("cut",({selectionText:p})=>{this.store.dispatch(qC(p))});let u;this.inputMediator.on("selection",p=>{clearTimeout(u),p===null?u=setTimeout(()=>{p!==null&&this.store.dispatch(gf(p))},500):this.store.dispatch(gf(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(vp(!1))}),this.inputMediator.on("focus",()=>{this.store.dispatch(vp(!0))}),this.renderSuggestions(t,l),this.subscribe(Js("inlineSuggestions"),()=>{this.renderSuggestions(t,l)}),this.subscribe(Js("suggestionsPlacement"),()=>{this.renderSuggestions(t,l)});let f=this.renderOverlays(n);this.unmountHandlers.push(()=>{f.unmount()}),this.store.dispatch(mf({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()})),this.store.dispatch(gf(this.inputMediator.getSelection())),this.store.dispatch(vp(this.inputMediator.isFocused)),this.unmountHandlers.push(()=>{this.state.input.text!==""&&this.storeMetrics()}),this.whenConversationLoaded(()=>{this.restoreMetrics(),this.syncInputMediator(),this.refreshTextSuggestions(),this.promptForNickname()}),this.isMounted=!0}promptForNickname(t){if(this.nicknameDialogUnsubscribe||this.nicknameDialogFailed)return;let n=this.createContainer("nickname-dialog",document.body);document.body.appendChild(n);let r=(0,Co.createRoot)(n),o=null,i=a=>{o=a,s()},s=()=>{r==null||r.render((0,we.jsx)(co,{store:this.store,children:(0,we.jsx)(to,{broadcastEvents:this.broadcastEvents,children:(0,we.jsx)(tA,{id:"deepdesk-nickname-dialog",error:o,onSave:a=>_(this,null,function*(){try{yield this.store.dispatch(s1({agentNickname:a})).unwrap(),console.log("setAgentNickname",a),this.broadcastEvents.send(vf,{showNicknameDialog:!1}),this.nicknameDialogUnsubscribe&&this.nicknameDialogUnsubscribe()}catch(c){te.error("Error setting agent nickname",c),i("error"),this.nicknameDialogFailed=!0}})})})}))};s(),this.nicknameDialogUnsubscribe=()=>{r.unmount(),n.remove(),this.nicknameDialogUnsubscribe=null}}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,i;(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(s=>s()),this.unmountHandlers=[],(i=this.inputMediator)==null||i.dispose(),this.nicknameDialogUnsubscribe&&this.nicknameDialogUnsubscribe(),this.isMounted=!1}dispose(){this.unmount(),this.unmountWidget(),this.disposeHandlers.forEach(t=>t()),this.disposeHandlers=[],this.off()}renderSuggestions(t,n){var r,o,i,s;(r=this.floatingMenu)==null||r.unmount(),(o=this.inlineSuggestions)==null||o.unmount(),(i=this.aboveSuggestions)==null||i.unmount(),(s=this.belowSuggestions)==null||s.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"),i=(0,Co.createRoot)(o);i.render((0,we.jsx)(co,{store:this.store,customStyles:r,children:(0,we.jsx)(to,{broadcastEvents:this.broadcastEvents,children:(0,we.jsx)(wR,{})})}));let s=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",s),{unmount:()=>{var a;(a=this.inputMediator)==null||a.off("caretposition",s),i.unmount(),o.remove()}}}renderAboveOrBelowSuggestions(t,n,r){let{customStyles:o,closestScrollSelector:i,appendOverlayTo:s}=n,a=i&&ex(t,i)||void 0,[c,l]=this.overlayContainerFactory("deepdesk-tab-completion",a||t,{appendTo:s,closestScrollElement:a,mirrorOverflow:!0,onRemove:()=>this.unmount()},o==null?void 0:o.rootNode),[u,f]=this.overlayContainerFactory("deepdesk-suggestions-overlay",a||t,{appendTo:s,placement:r},o==null?void 0:o.suggestionsRootNode),d=(0,Co.createRoot)(c);d.render((0,we.jsx)(co,{store:this.store,customStyles:o,children:(0,we.jsx)(to,{broadcastEvents:this.broadcastEvents,children:(0,we.jsx)(QR,{inputElement:t})})}));let p=(0,Co.createRoot)(u);return p.render((0,we.jsx)(co,{store:this.store,customStyles:o,children:(0,we.jsx)(to,{broadcastEvents:this.broadcastEvents,children:(0,we.jsx)(AR,{onLogIn:()=>this.loginViaPopup().catch(h=>te.warn(h.message))})})})),{unmount(){d.unmount(),p.unmount(),l(),f()}}}renderFloatingMenu(t,n){let{customStyles:r,closestScrollSelector:o,appendOverlayTo:i,floatingMenuParent:s}=n,a=o&&ex(t,o)||void 0,[c,l]=this.overlayContainerFactory("floating-menu",a||t,{appendTo:s!=null?s:i},r==null?void 0:r.floatingMenuParent),u=(0,Co.createRoot)(c);return u.render((0,we.jsx)(co,{store:this.store,customStyles:r,children:(0,we.jsx)(to,{broadcastEvents:this.broadcastEvents,children:(0,we.jsx)(aR,{onLogIn:()=>this.loginViaPopup().catch(f=>te.warn(f.message))})})})),{unmount(){u.unmount(),l()}}}renderOverlays(t){let{customStyles:n}=t,r=this.createContainer("deepdesk-overlays"),o=(0,Co.createRoot)(r);return o.render((0,we.jsx)(co,{store:this.store,customStyles:n,children:(0,we.jsx)(to,{broadcastEvents:this.broadcastEvents,children:(0,we.jsx)(nR,{})})})),{unmount(){o.unmount(),r.remove()}}}renderWidget(t,n={}){if(this.widgetElement&&te.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,isEmbedded:i}=n;this.widgetElement=t,this.configure({showImages:o,isEmbedded:i}),this.widgetRoot=(0,Co.createRoot)(t),this.widgetRoot.render((0,we.jsx)(co,{store:this.store,customStyles:r,children:(0,we.jsx)(to,{broadcastEvents:this.broadcastEvents,children:(0,we.jsx)(yI,{assistantOptions:n.assistantOptions,knowledgeAssistOptions:n.knowledgeAssist,onLogIn:()=>this.loginViaPopup().catch(s=>te.warn(s.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:i}=r,s=(0,Co.createRoot)(n);return s.render((0,we.jsx)(co,{store:this.store,customStyles:o,children:(0,we.jsx)(to,{broadcastEvents:this.broadcastEvents,children:(0,we.jsx)(j0,{children:(0,we.jsxs)(im,{assistantCode:t,initialQuestion:i,evaluateKnowledgeAssistFn:Kc,children:[(0,we.jsx)(bs,{children:(0,we.jsx)(am,{title:r.title,emptyState:r.emptyState})}),(0,we.jsx)(W0,{children:(0,we.jsx)(sm,{})})]})})})})),{unmount(){s.unmount()}}}setupHandlingTime(t){let n=gm(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){UI(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(()=>_(this,null,function*(){yield this.store.dispatch(pc());let t=Vi(this.state);t&&this.store.dispatch(lf({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 _(this,null,function*(){return new Promise((n,r)=>{let o=new MessageChannel,i=o.port1,s=this.settings.adminUrl,a=new URL(t!=null&&t.url?t==null?void 0:t.url:`${s}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let c=!1,l=()=>{u&&!u.closed&&u.close(),window.removeEventListener("message",f),clearInterval(d)};i.onmessage=p=>_(this,null,function*(){var h,g;if((h=p.data)!=null&&h.jwt)try{yield this.deepdeskApi.exchangeTokenForAccessCookie((g=p.data)==null?void 0:g.jwt),yield this.isLoggedIn(),this.broadcastEvents.send(Jl),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=>_(this,null,function*(){var h;if(p.origin===a.origin)switch((h=p.data)==null?void 0:h.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){te.error("Error posting message to popup",g),r(g)}break}case"deepdesk-popup-error":{l(),p.data.message==="Timeout"&&te.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 _(this,null,function*(){this.isMounted&&(yield this.store.dispatch(gp()))})}refreshWidgetSuggestions(){return _(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(ur());break;case"pinned-messages":case"sticky-messages":break;default:Ru.includes(r)||this.store.dispatch(dr(r))}})}catch(r){this.handleError(r)}})}};Wa.version="18.2.1-beta.15",Wa.count=0;var lu=Wa;function OF(e){return _(this,null,function*(){var o,i,s;let n=yield((o=e.fetch)!=null?o:window.fetch)(e.url),r=yield n.blob();return new File([r],e.name,{type:(s=(i=e.mimeType)!=null?i:n.headers.get("Content-Type"))!=null?s:"image/jpeg"})})}function rA(e,t){return _(this,null,function*(){let n=yield OF(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 oA(e,t,n){return _(this,null,function*(){yield new Eo(e).authenticateWithKey(t,n)})}function iA(e){return e.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}function sA(r,o){return _(this,arguments,function*(e,t,n={}){var f,d;let{value:i}=e,{start:s,end:a}=(f=n.replace)!=null?f:{start:0,end:i.length},c=`${i.slice(0,s)}${t}${i.slice(a)}`,l=(d=n.selectionAfter)!=null?d:{start:s+t.length,end:s+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 aA(r,o){return _(this,arguments,function*(e,t,n={}){let i=n.replace?di(e,n.replace.start,n.replace.end):Ha(e),s,a=()=>{if(n.setRange)return n.setRange(i.cloneRange());i.deleteContents(),s=document.createElement("span"),i.insertNode(s),n.insertBRs!==!1?t.split(`
|
|
82
82
|
`).reverse().forEach((c,l)=>{l>0&&i.insertNode(document.createElement("br")),i.insertNode(document.createTextNode(c))}):i.insertNode(document.createTextNode(t))};return Promise.resolve(a()).then(()=>{try{if(n.selectionAfter!==!1){e.focus();let c=n.selectionAfter?di(e,n.selectionAfter.start,n.selectionAfter.end):(i.collapse(!1),i),l=window.getSelection();l==null||l.removeAllRanges(),l==null||l.addRange(c)}if(!s)return;s.scrollIntoView&&s.scrollIntoView({block:"nearest",inline:"nearest"})}finally{s&&s.remove()}})})}function DF(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 FF(e){let t=document.createDocumentFragment();return e.split(`
|
|
83
83
|
`).forEach((n,r)=>{r>0&&t.appendChild(document.createElement("br"));let o={index:0},i=0;for(;o=n.slice(i).match(/(\[([^\]]+)])\(([^)]+)\)/);){let s=document.createElement("a");s.href=o[3],s.setAttribute("target","_blank"),s.setAttribute("rel","noopener noreferrer"),s.appendChild(document.createTextNode(o[2])),t.appendChild(document.createTextNode(n.slice(i,i+o.index))),t.appendChild(s),i=i+o.index+o[0].length}t.appendChild(document.createTextNode(n.slice(i)))}),t}function lA(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):lA(n,t)}function cA(o,i){return _(this,arguments,function*(e,t,{isBlock:n,isHTML:r}={}){let s;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;s=document.createElement("span"),u.insertNode(s);let f=r?DF(t):FF(t);n?lA(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(),!!s)try{s.scrollIntoView&&s.scrollIntoView({block:"nearest",inline:"nearest"})}finally{s&&s.remove()}})})}return EA(zF);})();
|
|
84
84
|
/*! Bundled license information:
|