@deepdesk/deepdesk-sdk 18.1.2-beta.1 → 18.1.2-beta.2

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.
@@ -75,11 +75,11 @@ ${t}</tr>
75
75
  `}tablecell(t){let n=this.parser.parseInline(t.tokens),r=t.header?"th":"td";return(t.align?`<${r} align="${t.align}">`:`<${r}>`)+n+`</${r}>
76
76
  `}strong({tokens:t}){return`<strong>${this.parser.parseInline(t)}</strong>`}em({tokens:t}){return`<em>${this.parser.parseInline(t)}</em>`}codespan({text:t}){return`<code>${Nr(t,!0)}</code>`}br(t){return"<br>"}del({tokens:t}){return`<del>${this.parser.parseInline(t)}</del>`}link({href:t,title:n,tokens:r}){let o=this.parser.parseInline(r),s=FR(t);if(s===null)return o;t=s;let i='<a href="'+t+'"';return n&&(i+=' title="'+Nr(n)+'"'),i+=">"+o+"</a>",i}image({href:t,title:n,text:r}){let o=FR(t);if(o===null)return Nr(r);t=o;let s=`<img src="${t}" alt="${r}"`;return n&&(s+=` title="${Nr(n)}"`),s+=">",s}text(t){return"tokens"in t&&t.tokens?this.parser.parseInline(t.tokens):"escaped"in t&&t.escaped?t.text:Nr(t.text)}},Vc=class{strong({text:t}){return t}em({text:t}){return t}codespan({text:t}){return t}del({text:t}){return t}html({text:t}){return t}text({text:t}){return t}link({text:t}){return""+t}image({text:t}){return""+t}br(){return""}},dr=class e{constructor(t){we(this,"options");we(this,"renderer");we(this,"textRenderer");this.options=t||si,this.options.renderer=this.options.renderer||new Ia,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Vc}static parse(t,n){return new e(n).parse(t)}static parseInline(t,n){return new e(n).parseInline(t)}parse(t,n=!0){var o,s;let r="";for(let i=0;i<t.length;i++){let a=t[i];if((s=(o=this.options.extensions)==null?void 0:o.renderers)!=null&&s[a.type]){let c=a,u=this.options.extensions.renderers[c.type].call({parser:this},c);if(u!==!1||!["space","hr","heading","code","table","blockquote","list","html","paragraph","text"].includes(c.type)){r+=u||"";continue}}let l=a;switch(l.type){case"space":{r+=this.renderer.space(l);continue}case"hr":{r+=this.renderer.hr(l);continue}case"heading":{r+=this.renderer.heading(l);continue}case"code":{r+=this.renderer.code(l);continue}case"table":{r+=this.renderer.table(l);continue}case"blockquote":{r+=this.renderer.blockquote(l);continue}case"list":{r+=this.renderer.list(l);continue}case"html":{r+=this.renderer.html(l);continue}case"paragraph":{r+=this.renderer.paragraph(l);continue}case"text":{let c=l,u=this.renderer.text(c);for(;i+1<t.length&&t[i+1].type==="text";)c=t[++i],u+=`
77
77
  `+this.renderer.text(c);n?r+=this.renderer.paragraph({type:"paragraph",raw:u,text:u,tokens:[{type:"text",raw:u,text:u,escaped:!0}]}):r+=u;continue}default:{let c='Token with "'+l.type+'" type was not found.';if(this.options.silent)return console.error(c),"";throw new Error(c)}}}return r}parseInline(t,n=this.renderer){var o,s;let r="";for(let i=0;i<t.length;i++){let a=t[i];if((s=(o=this.options.extensions)==null?void 0:o.renderers)!=null&&s[a.type]){let c=this.options.extensions.renderers[a.type].call({parser:this},a);if(c!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(a.type)){r+=c||"";continue}}let l=a;switch(l.type){case"escape":{r+=n.text(l);break}case"html":{r+=n.html(l);break}case"link":{r+=n.link(l);break}case"image":{r+=n.image(l);break}case"strong":{r+=n.strong(l);break}case"em":{r+=n.em(l);break}case"codespan":{r+=n.codespan(l);break}case"br":{r+=n.br(l);break}case"del":{r+=n.del(l);break}case"text":{r+=n.text(l);break}default:{let c='Token with "'+l.type+'" type was not found.';if(this.options.silent)return console.error(c),"";throw new Error(c)}}}return r}},ri=class{constructor(t){we(this,"options");we(this,"block");this.options=t||si}preprocess(t){return t}postprocess(t){return t}processAllTokens(t){return t}provideLexer(){return this.block?ur.lex:ur.lexInline}provideParser(){return this.block?dr.parse:dr.parseInline}};we(ri,"passThroughHooks",new Set(["preprocess","postprocess","processAllTokens"]));var $c=class{constructor(...t){we(this,"defaults",Zv());we(this,"options",this.setOptions);we(this,"parse",this.parseMarkdown(!0));we(this,"parseInline",this.parseMarkdown(!1));we(this,"Parser",dr);we(this,"Renderer",Ia);we(this,"TextRenderer",Vc);we(this,"Lexer",ur);we(this,"Tokenizer",Pa);we(this,"Hooks",ri);this.use(...t)}walkTokens(t,n){var o,s;let r=[];for(let i of t)switch(r=r.concat(n.call(this,i)),i.type){case"table":{let a=i;for(let l of a.header)r=r.concat(this.walkTokens(l.tokens,n));for(let l of a.rows)for(let c of l)r=r.concat(this.walkTokens(c.tokens,n));break}case"list":{let a=i;r=r.concat(this.walkTokens(a.items,n));break}default:{let a=i;(s=(o=this.defaults.extensions)==null?void 0:o.childTokens)!=null&&s[a.type]?this.defaults.extensions.childTokens[a.type].forEach(l=>{let c=a[l].flat(1/0);r=r.concat(this.walkTokens(c,n))}):a.tokens&&(r=r.concat(this.walkTokens(a.tokens,n)))}}return r}use(...t){let n=this.defaults.extensions||{renderers:{},childTokens:{}};return t.forEach(r=>{let o=w({},r);if(o.async=this.defaults.async||o.async||!1,r.extensions&&(r.extensions.forEach(s=>{if(!s.name)throw new Error("extension name required");if("renderer"in s){let i=n.renderers[s.name];i?n.renderers[s.name]=function(...a){let l=s.renderer.apply(this,a);return l===!1&&(l=i.apply(this,a)),l}:n.renderers[s.name]=s.renderer}if("tokenizer"in s){if(!s.level||s.level!=="block"&&s.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let i=n[s.level];i?i.unshift(s.tokenizer):n[s.level]=[s.tokenizer],s.start&&(s.level==="block"?n.startBlock?n.startBlock.push(s.start):n.startBlock=[s.start]:s.level==="inline"&&(n.startInline?n.startInline.push(s.start):n.startInline=[s.start]))}"childTokens"in s&&s.childTokens&&(n.childTokens[s.name]=s.childTokens)}),o.extensions=n),r.renderer){let s=this.defaults.renderer||new Ia(this.defaults);for(let i in r.renderer){if(!(i in s))throw new Error(`renderer '${i}' does not exist`);if(["options","parser"].includes(i))continue;let a=i,l=r.renderer[a],c=s[a];s[a]=(...u)=>{let f=l.apply(s,u);return f===!1&&(f=c.apply(s,u)),f||""}}o.renderer=s}if(r.tokenizer){let s=this.defaults.tokenizer||new Pa(this.defaults);for(let i in r.tokenizer){if(!(i in s))throw new Error(`tokenizer '${i}' does not exist`);if(["options","rules","lexer"].includes(i))continue;let a=i,l=r.tokenizer[a],c=s[a];s[a]=(...u)=>{let f=l.apply(s,u);return f===!1&&(f=c.apply(s,u)),f}}o.tokenizer=s}if(r.hooks){let s=this.defaults.hooks||new ri;for(let i in r.hooks){if(!(i in s))throw new Error(`hook '${i}' does not exist`);if(["options","block"].includes(i))continue;let a=i,l=r.hooks[a],c=s[a];ri.passThroughHooks.has(i)?s[a]=u=>{if(this.defaults.async)return Promise.resolve(l.call(s,u)).then(d=>c.call(s,d));let f=l.call(s,u);return c.call(s,f)}:s[a]=(...u)=>{let f=l.apply(s,u);return f===!1&&(f=c.apply(s,u)),f}}o.hooks=s}if(r.walkTokens){let s=this.defaults.walkTokens,i=r.walkTokens;o.walkTokens=function(a){let l=[];return l.push(i.call(this,a)),s&&(l=l.concat(s.call(this,a))),l}}this.defaults=w(w({},this.defaults),o)}),this}setOptions(t){return this.defaults=w(w({},this.defaults),t),this}lexer(t,n){return ur.lex(t,n!=null?n:this.defaults)}parser(t,n){return dr.parse(t,n!=null?n:this.defaults)}parseMarkdown(t){return(r,o)=>{let s=w({},o),i=w(w({},this.defaults),s),a=this.onError(!!i.silent,!!i.async);if(this.defaults.async===!0&&s.async===!1)return a(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof r=="undefined"||r===null)return a(new Error("marked(): input parameter is undefined or null"));if(typeof r!="string")return a(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(r)+", string expected"));i.hooks&&(i.hooks.options=i,i.hooks.block=t);let l=i.hooks?i.hooks.provideLexer():t?ur.lex:ur.lexInline,c=i.hooks?i.hooks.provideParser():t?dr.parse:dr.parseInline;if(i.async)return Promise.resolve(i.hooks?i.hooks.preprocess(r):r).then(u=>l(u,i)).then(u=>i.hooks?i.hooks.processAllTokens(u):u).then(u=>i.walkTokens?Promise.all(this.walkTokens(u,i.walkTokens)).then(()=>u):u).then(u=>c(u,i)).then(u=>i.hooks?i.hooks.postprocess(u):u).catch(a);try{i.hooks&&(r=i.hooks.preprocess(r));let u=l(r,i);i.hooks&&(u=i.hooks.processAllTokens(u)),i.walkTokens&&this.walkTokens(u,i.walkTokens);let f=c(u,i);return i.hooks&&(f=i.hooks.postprocess(f)),f}catch(u){return a(u)}}}onError(t,n){return r=>{if(r.message+=`
78
- Please report this to https://github.com/markedjs/marked.`,t){let o="<p>An error occurred:</p><pre>"+Nr(r.message+"",!0)+"</pre>";return n?Promise.resolve(o):o}if(n)return Promise.reject(r);throw r}}},oi=new $c;function Ce(e,t){return oi.parse(e,t)}Ce.options=Ce.setOptions=function(e){return oi.setOptions(e),Ce.defaults=oi.defaults,BR(Ce.defaults),Ce};Ce.getDefaults=Zv;Ce.defaults=si;Ce.use=function(...e){return oi.use(...e),Ce.defaults=oi.defaults,BR(Ce.defaults),Ce};Ce.walkTokens=function(e,t){return oi.walkTokens(e,t)};Ce.parseInline=oi.parseInline;Ce.Parser=dr;Ce.parser=dr.parse;Ce.Renderer=Ia;Ce.TextRenderer=Vc;Ce.Lexer=ur;Ce.lexer=ur.lex;Ce.Tokenizer=Pa;Ce.Hooks=ri;Ce.parse=Ce;var fG=Ce.options,pG=Ce.setOptions,mG=Ce.use,gG=Ce.walkTokens,hG=Ce.parseInline;var yG=dr.parse,vG=ur.lex;var QR=(e,t)=>{let n=[],r=new $c,o=s=>{s.type==="code"&&s.lang===t&&n.push(s.text)};return r.use({walkTokens:o}),r.parse(e),n};var Wc="__summarizerAssistant__",ZR={cues:[],threads:{},pending:[]},JR=e=>{var t;return(t=e.assistants)==null?void 0:t.cues};var i0=e=>t=>{var n,r;return(r=(n=t.assistants)==null?void 0:n.threads[e])!=null?r:null},qp=it("assistants/callToAction"),mo=fe("assistants/evaluateSummaryAssistant",(e,t)=>A(void 0,null,function*(){let r=t.getState().profile.data;if(!r)throw new Error("No Profile is loaded");let{summarizerAssistantNew:o}=r;if(!o)throw new Error("No Summarizer Assistant set in Profile");let s=yield t.dispatch(fr(w({assistantCode:o,expectFormat:"text",transcript:"in-memory-transcript",skipState:!0},e)));if(s.error)throw new Error(s.error.message);if(typeof s.payload.output!="string")throw ee.warn("Unexpected summary output",s),new Error("Unexpected summary output");return{output:s.payload.output,evaluationId:s.payload.evaluationId}})),O4=1,Kc=fe("assistants/evaluateKnowledgeAssistantLegacy",(e,t)=>A(void 0,null,function*(){var p,h,m,x;let{threadId:n}=e,{onNewThreadId:r,input:o}=e,{deepdeskAPI:s}=t.extra,i=t.getState(),{platformVariables:a}=i.info;n||(n=O4++,r&&r(n));let l=(p=i0(n)(i))!=null?p:[],c=yield s.getKnowledgeAssistant(e.assistantCode),u=(h=i.conversation.current)==null?void 0:h.externalId,f=(x=(m=i.info)==null?void 0:m.agentInfo)==null?void 0:x.agentId;if(!c)throw new Error("KnowledgeAssistant is not found");let d=yield s.knowledgeAssist({customerInstruction:c.customerInstruction,doNotKnowAnswer:c.doNotKnowAnswer,question:o},l,c.code,{agentId:f,conversationId:u});return a&&(d.answer=ln(d.answer,a)),{threadId:n,question:o,answer:d,evaluationId:"??"}})),Gc=fe("assistants/evaluateKnowledgeAssistant",(e,t)=>A(void 0,null,function*(){let{threadId:n}=e,{onNewThreadId:r}=e,{deepdeskAPI:o}=t.extra,s=t.getState(),{platformVariables:i}=s.info;n||(n=(yield o.createAssistantThread({assistantCode:e.assistantCode})).id,r&&r(n)),yield o.postMessageToAssistantThread({assistantCode:e.assistantCode,threadId:n,message:e.input});let a=yield t.dispatch(fr(P(w({expectFormat:"json-schema:knowledge-assist",skipState:!0},e),{input:{},threadId:n})));if(a.error)throw new Error(a.error.message);let l=a.payload.output;return{threadId:n,question:e.input,evaluationId:a.payload.evaluationId,answer:{answer:ln(l.response,i!=null?i:{}),sources:l.sources}}})),LG=it("assistants/extractedTextSuggestions"),fr=fe("assistants/evaluate",(e,t)=>A(void 0,null,function*(){var p;let{deepdeskAPI:n,dynamicThunkObject:r}=t.extra,{transcript:o,input:s={},expectFormat:i,threadId:a}=e,l=t.getState(),{platformVariables:c}=l.info,u=(p=l.conversation.current)==null?void 0:p.externalId,f;if(o==="in-memory-transcript"){if(!r.conversationQuery)throw new Error("Can't include in-memory-transcript, setConversationQuery is not defined");f=yield r.conversationQuery()}else Array.isArray(o)&&(f=o);if(e.includeMetadata){if(!l.conversation.current)throw new Error("Can't include metadata, no current conversation");let{metadata:h}=l.conversation.current;Object.assign(s,{metadata:h})}let d=yield n.evaluateAssistant(e.assistantCode,{expectFormat:i,input:s,transcript:f,externalConversationId:u,threadId:a});if(d.evaluationStatus!=="success")throw new Error(`Assistant ${e.assistantCode} evaluation failed: ${d.evaluationStatus}`);switch(i){case"text":return{evaluationId:d.evaluationId,output:ln(d.output,c)};case"json-schema:cues":{if(!Array.isArray(d.output))return P(w({},d),{output:[]});let h=d.output.map(x=>P(w({},x),{name:ln(x.name,c),response:ln(x.response,c)})),m=[];return h.forEach(x=>{let v=QR(x.response,"reply");m.push(...v.map(y=>({text:y,type:"text",source:"assistant",assistantCode:x.code,sourceLabel:x.name})))}),m.length>0&&t.dispatch(bf(m)),P(w({},d),{output:h})}case"json-schema:knowledge-assist":{let h=d.output;if(d.output==="")throw new Error("No output from assistant");return{output:h,evaluationId:d.evaluationId,answer:ln(h.response,c)}}default:return d}})),eP=Ee({name:"assistants",initialState:ZR,reducers:{resetCues(e){e.cues=[]},removeCueByCode(e,t){e.cues=e.cues.filter(n=>n.code!==t.payload.code)},removeThreadById(e,t){delete e.threads[t.payload]},receiveChunk(e,t){let{code:n,name:r,payload:o,evaluationId:s}=t.payload,i=e.cues.findIndex(a=>a.code===n);i!==-1?e.cues[i].response+=o.text:e.cues.push({code:n,name:r,evaluationId:s,response:o.text})},userNotification(e,t){let n=e.cues.filter(l=>l.code!==t.payload.code),{code:r,name:o,evaluationId:s,payload:i}=t.payload,{callToAction:a}=i;e.cues=[...n,{code:r,name:o,evaluationId:s,response:i.message,editable:i.editableMessage,callToAction:a&&{label:a.displayName,event:a.onClickEvent,value:a.eventPayload}}]}},extraReducers:e=>{e.addCase(fr.pending,(t,n)=>{t.pending.includes(n.meta.arg.assistantCode)&&ee.warn(`Assistant ${n.meta.arg.assistantCode} already evaluating`),t.pending.push(n.meta.arg.assistantCode)}).addCase(fr.rejected,(t,n)=>{var o;ee.warn((o=n.error)==null?void 0:o.message);let r=t.pending.indexOf(n.meta.arg.assistantCode);r!==-1&&t.pending.splice(r,1)}).addCase(fr.fulfilled,(t,n)=>{let r=t.pending.indexOf(n.meta.arg.assistantCode);if(r!==-1&&t.pending.splice(r,1),!n.meta.arg.skipState)switch(n.meta.arg.expectFormat){case"json-schema:cues":{let{evaluationId:o,output:s}=n.payload,i=s.map(c=>c.code),a=t.cues.filter(c=>!i.includes(c.code)),l=s.map(c=>P(w({},c),{evaluationId:o}));t.cues=[...a,...l];break}}}).addCase(Gc.fulfilled,(t,n)=>{let s=n.payload,{threadId:r}=s,o=re(s,["threadId"]);t.threads[r]=[...t.threads[r]||[],o]}).addCase(Kc.fulfilled,(t,n)=>{let s=n.payload,{threadId:r}=s,o=re(s,["threadId"]);t.threads[r]=[...t.threads[r]||[],o]}).addCase(mo.pending,t=>{let n={code:Wc,name:"Summary",response:"",isLoading:!0,evaluationId:""},r=t.cues.filter(o=>o.code!==Wc);t.cues=[...r,n]}).addCase(mo.rejected,t=>{let n=t.cues.filter(r=>r.code!==Wc);t.cues=n}).addCase(mo.fulfilled,(t,n)=>{let r={code:Wc,name:"Summary",response:n.payload.output,specialType:"summary",evaluationId:n.payload.evaluationId},o=t.cues.filter(s=>s.code!==Wc);t.cues=[...o,r]}).addCase(at,()=>ZR)}}),{removeCueByCode:Yp,resetCues:MG,removeThreadById:tP,receiveChunk:nP,userNotification:rP}=eP.actions,oP=eP.reducer;var N4={token:null,interval:null},a0=fe("passwordlessToken/getTemporaryPasswordlessToken",(e,t)=>A(void 0,null,function*(){let{deepdeskAPI:n}=t.extra;return{token:yield n.requestPasswordlessToken()}})),l0=fe("passwordlessToken/pollPasswordlessToken",(e={},t)=>{let{interval:n=1e3*60*10}=e,{dispatch:r}=t;return r(a0()),setInterval(()=>r(a0()),n)}),sP=Ee({name:"passwordlessToken",initialState:N4,reducers:{stopPollPasswordlessToken(e){e.interval&&clearInterval(e.interval),e.interval=null}},extraReducers:e=>{e.addCase(a0.fulfilled,(t,n)=>{t.token=n.payload.token}),e.addCase(l0.fulfilled,(t,n)=>{t.interval=n.payload})}}),{stopPollPasswordlessToken:iP}=sP.actions,aP=sP.reducer;function _4(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return t}var lP=Vt([JR],e=>e.map(n=>({text:n.response,title:n.name,callToAction:n.callToAction,editable:n.editable,isLoading:n.isLoading,specialType:n.specialType,evaluationId:n.evaluationId,rule:{id:_4(n.code),label:n.code,name:n.name,description:n.name}})));var Xp=b(Y());var u0=b(Me());var c0=b(R()),qc=()=>(0,c0.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 512 512",xmlns:"http://www.w3.org/2000/svg",children:(0,c0.jsx)("path",{d:"M502.6 70.63l-61.25-61.25C435.4 3.371 427.2 0 418.7 0H255.1c-35.35 0-64 28.66-64 64l.0195 256C192 355.4 220.7 384 256 384h192c35.2 0 64-28.8 64-64V93.25C512 84.77 508.6 76.63 502.6 70.63zM464 320c0 8.836-7.164 16-16 16H255.1c-8.838 0-16-7.164-16-16L239.1 64.13c0-8.836 7.164-16 16-16h128L384 96c0 17.67 14.33 32 32 32h47.1V320zM272 448c0 8.836-7.164 16-16 16H63.1c-8.838 0-16-7.164-16-16L47.98 192.1c0-8.836 7.164-16 16-16H160V128H63.99c-35.35 0-64 28.65-64 64l.0098 256C.002 483.3 28.66 512 64 512h192c35.2 0 64-28.8 64-64v-32h-47.1L272 448z"})});var cP={root:"dd-WcEru",entity:"dd-LfP8y",entityText:"dd-L-v0f",iconWrapper:"dd-9Deh1",icon:"dd-tM7E2",iconClicked:"dd-EEdDL"};var _r=b(R()),D4=({entities:e})=>{let t=D("EntitiesWidgetList",cP),[n,r]=(0,Xp.useState)(void 0),o=ge(),s=()=>{r(void 0)},i=a=>{e&&(r(e.indexOf(a)),Rr(a.text),o(Go({name:"entity copied",data:{entity:a,type:"copy"}})))};return(0,Xp.useEffect)(()=>{let a=setTimeout(s,500);return()=>{clearTimeout(a)}},[n]),!e||e.length===0?null:(0,_r.jsx)("div",{className:t.root,"data-testid":"widget-entities-list",children:e.map((a,l)=>(0,_r.jsxs)("button",{title:a.text,className:t.entity,type:"button",onClick:()=>i(a),children:[(0,_r.jsx)("span",{className:t.entityText,children:a.text}),(0,_r.jsxs)("span",{className:t.iconWrapper,children:[(0,_r.jsx)("span",{className:(0,u0.default)(t.icon),children:(0,_r.jsx)(qc,{})}),(0,_r.jsx)("span",{className:(0,u0.default)(t.icon,n===l&&t.iconClicked),children:(0,_r.jsx)(qc,{})})]})]},a.text))})},uP=D4;var d0=b(R()),dP=()=>(0,d0.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:(0,d0.jsx)("path",{d:"M17 13.5v6H5v-12h6m3-3h6v6m0-6-9 9",stroke:"currentColor",strokeWidth:"1.5",fill:"none",fillRule:"evenodd",strokeLinecap:"round",strokeLinejoin:"round"})});var vP=b(Y());var Aa=b(Y());function Yc(e,t){let n=(0,Aa.useRef)(e);n.current=e;let[r,o]=(0,Aa.useState)(void 0),[s,i]=(0,Aa.useState)(void 0),[a,l]=(0,Aa.useState)("idle"),c=ge();return{error:s,state:a,data:r,call:d=>A(this,null,function*(){l("loading"),yield c(n.current(d)).unwrap().then(p=>{o(p),l("done"),t!=null&&t.onSuccess&&(t==null||t.onSuccess(p))}).catch(p=>{i(p),l("error"),t!=null&&t.onError&&(t==null||t.onError(p))})}),reset:()=>{l("idle"),o(void 0),i(void 0)}}}var fP={root:"dd-ohnXe",trigger:"dd-7i-S3",button:"dd-t53Cg",nav:"dd-qZFnm",item:"dd-FZC0F"};var pP={root:"dd-nazq3",rotation:"dd-3EHTv"};var gP=b(R()),F4=({size:e=12})=>{let t=D("LoadingSpinner",pP);return(0,gP.jsx)("span",{"data-testid":"loading-spinner",style:{width:`${e}px`,height:`${e}px`},className:t.root})},mP=F4;var f0=b(R()),hP=()=>(0,f0.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 0 512 512",fill:"currentColor",children:(0,f0.jsx)("path",{d:"M256 32c14.2 0 27.3 7.5 34.5 19.8l216 368c7.3 12.4 7.3 27.7 .2 40.1S486.3 480 472 480H40c-14.3 0-27.6-7.7-34.7-20.1s-7-27.8 .2-40.1l216-368C228.7 39.5 241.8 32 256 32zm0 128c-13.3 0-24 10.7-24 24V296c0 13.3 10.7 24 24 24s24-10.7 24-24V184c0-13.3-10.7-24-24-24zm32 224c0-17.7-14.3-32-32-32s-32 14.3-32 32s14.3 32 32 32s32-14.3 32-32z"})});var Xc=b(R()),yP=e=>(0,Xc.jsxs)("svg",P(w({xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 448 512","aria-labelledby":"checkTitle"},e),{children:[(0,Xc.jsx)("title",{id:"checkTitle",children:"Check"}),(0,Xc.jsx)("path",{fill:"#666",d:"M438.6 105.4c12.5 12.5 12.5 32.8 0 45.3l-256 256c-12.5 12.5-32.8 12.5-45.3 0l-128-128c-12.5-12.5-12.5-32.8 0-45.3s32.8-12.5 45.3 0L160 338.7 393.4 105.4c12.5-12.5 32.8-12.5 45.3 0z"})]}));var p0={};xt(p0,{enUS:()=>z4,nlNL:()=>H4});var z4={error:[{type:0,value:"Something went wrong"}]},H4={error:[{type:0,value:"Er ging iets fout"}]};var kn=b(R()),B4=3e3,U4=({assistantOptions:e})=>{let t=D("OnDemandAssistants",fP),n=ae(p0),r=(0,vP.useRef)(),o=Yc(fr),s=Yc(mo),i=K(RT),a=K(PT),l=Ct(),c=a.filter(d=>d.isPinned),u=a.filter(d=>!d.isPinned),f=d=>A(void 0,null,function*(){clearTimeout(r.current),l("trigger on demand assistant",{assistantCode:d}),d===i?yield s.call({transcript:e.transcript}):yield o.call(P(w({},e),{assistantCode:d})),r.current=setTimeout(()=>o.reset(),B4)});return a.length===0?null:(0,kn.jsxs)("div",{className:t.root,children:[c.map(({assistant:d,assistantName:p,displayName:h})=>(0,kn.jsx)("button",{type:"button",className:t.button,disabled:o.state==="loading",onClick:()=>f(d),children:h||p},d)),u.length>0&&(0,kn.jsxs)(gt,{placement:"top-end",children:[(0,kn.jsx)(gt.Trigger,{className:t.trigger,disabled:o.state==="loading",children:(0,kn.jsx)(yp,{"data-testid":"trigger"})}),(0,kn.jsx)(gt.Content,{className:t.nav,"data-testid":"popover",children:u.map(({assistant:d,assistantName:p,displayName:h})=>(0,kn.jsx)(gt.Button,{className:t.item,disabled:o.state==="loading",onClick:()=>f(d),children:h||p},d))})]}),o.state==="loading"&&(0,kn.jsx)(mP,{}),o.state==="done"&&(0,kn.jsx)(yP,{"data-testid":"trigger-done"}),o.state==="error"&&(0,kn.jsx)(pk,{trigger:(0,kn.jsx)(hP,{}),children:n("error")})]})},xP=U4;var bP=b(Y());var SP={loadingBar:"dd-6as-V",placeHolderShimmer:"dd-TFYmA"};var wP=b(R()),V4=({width:e})=>{let t=D("LoadingProgressBar",SP);return(0,wP.jsx)("div",{className:t.loadingBar,style:{width:e}})},Qp=V4;var go=b(R()),Zp=({title:e})=>{let t=(0,bP.useRef)(null);return Iu(t),(0,go.jsx)(de,{ref:t,children:(0,go.jsx)(ve,{children:(0,go.jsxs)(ve.Content,{children:[(0,go.jsx)(ve.Title,{children:e}),(0,go.jsx)(Qp,{width:"60%"}),(0,go.jsx)(Qp,{width:"90%"}),(0,go.jsx)(Qp,{width:"50%"})]})})})};var Qc={};xt(Qc,{enUS:()=>$4,nlNL:()=>j4});var $4={useCue:[{type:0,value:"Add to message"}],__summarizerAssistant__:[{type:0,value:"Summary"}],copyCue:[{type:0,value:"Copy"}],removeCue:[{type:0,value:"Close"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}]},j4={useCue:[{type:0,value:"Voeg toe aan bericht"}],__summarizerAssistant__:[{type:0,value:"Samenvatting"}],copyCue:[{type:0,value:"Kopi\xEBren"}],removeCue:[{type:0,value:"Sluiten"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}]};var li=b(Y());var Jp=b(Me()),CP=b(Y());var m0=b(R()),g0=e=>(0,m0.jsx)("svg",P(w({width:"16",height:"16",fill:"#000000"},e),{viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:(0,m0.jsx)("path",{fillRule:"evenodd",d:"M6.57086468,14.9173453 C6.38997052,14.9711236 6.19835748,15 6,15 L4,15 C2.8954305,15 2,14.1045695 2,13 L2,4 C2,2.8954305 2.8954305,2 4,2 L6,2 C6.68685475,2 7.29284112,2.34623869 7.65294381,2.87370078 C7.95642355,2.67736738 8.29504785,2.51351337 8.66312366,2.3818197 C9.50544052,2.08044754 10.3408482,1.9879107 10.9989281,1.99971266 C11.0150698,2.00005426 13.3487605,2.00015005 18,2 C20.7551411,2 22,6.05643086 22,12 C22,13.6824804 20.8695981,15 19,15 L15.9269768,15 C15.9359266,15.0245465 15.9451954,15.0497804 15.9547911,15.0757271 C16.007193,15.2174219 16.2391583,15.8256341 16.2970775,15.9810953 C16.4872151,16.4914441 16.6259612,16.9026411 16.7382242,17.3098712 C16.9079007,17.9253665 17,18.4798886 17,19 C17,20.4720069 16.091867,21.3862822 14.748281,21.777514 C14.1422801,21.9539723 13.6147967,22.0000922 13.0076976,22.0000008 L12.5204954,22 L12.2202699,21.6261158 C11.2556275,20.4248034 7.64562469,16.4822788 6.57086468,14.9173453 Z M8,13 C8,13.2401953 8.04443154,13.4528921 8.14171093,13.6800176 C8.40663864,14.2985643 11.914268,18.1371493 13.4599624,19.9848695 C13.7113931,19.9660111 13.9483736,19.9273712 14.1891338,19.8572655 C14.7621788,19.6904035 15,19.4509737 15,19 C15,18.6834183 14.9359344,18.2976852 14.8101464,17.8413935 C14.7161494,17.500423 14.5944107,17.1396301 14.4229225,16.6793379 C14.3689242,16.5344009 14.1358033,15.923159 14.0789589,15.7694517 C13.9489218,15.4178313 13.8632547,15.1589343 13.8046536,14.9236885 C13.5555377,13.9236468 13.8054549,13 15,13 L19,13 C19.6912225,13 20,12.6401099 20,12 C20,7.20925475 19.015127,4 18,4 C15.9322103,4 15.9322103,4 10.9655994,3.99940813 C10.5253746,3.99154158 9.91062406,4.05963657 9.33687634,4.2649175 C8.45196659,4.58152894 8,5.09776992 8,6 L8,13 Z M4,4 L4,13 L6,13 L6,4 L4,4 Z"})}));var h0=b(R()),EP=e=>(0,h0.jsx)("svg",P(w({width:"16",height:"16",fill:"#000000"},e),{viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:(0,h0.jsx)("path",{fillRule:"evenodd",d:"M7.65336736,21.1256786 C7.2933164,21.6534897 6.68712411,22 6,22 L4,22 C2.8954305,22 2,21.1045695 2,20 L2,11 C2,9.8954305 2.8954305,9 4,9 L6,9 C6.198171,9 6.38961023,9.02882212 6.57035446,9.08250314 C7.6444817,7.51807482 11.2554748,3.57449216 12.2202699,2.37298955 L12.5204954,1.99910538 L13,1.99910538 C13.6147967,1.99901314 14.1422801,2.04513312 14.748281,2.22159137 C16.091867,2.61282321 17,3.52709845 17,4.99910538 C17,5.51921677 16.9079007,6.07373891 16.7382242,6.68923415 C16.6259612,7.09646424 16.4872151,7.50766133 16.2970775,8.01801005 C16.2391583,8.17347129 16.007193,8.78168345 15.9547911,8.92337824 C15.9451954,8.94932503 15.9359266,8.9745589 15.9269768,8.99910538 L19,8.99910538 C20.8695981,8.99910538 22,10.316625 22,11.9991054 C22,17.9426745 20.7551411,21.9991054 18,21.9991054 L11.0344006,21.9985135 C10.3408482,22.0111947 9.50544052,21.9186578 8.66312366,21.6172857 C8.29521907,21.4856533 7.9567386,21.3218904 7.65336736,21.1256786 Z M8,17.9991054 C8,18.9013355 8.45196659,19.4175764 9.33687634,19.7341879 C9.91062406,19.9394688 10.5253746,20.0075638 10.963066,19.9997143 C10.9703499,19.9995545 10.9703499,19.9995545 11,19.9991054 L18,19.9991054 C19.015127,19.9991054 20,16.7898506 20,11.9991054 C20,11.3589955 19.6912225,10.9991054 19,10.9991054 L15,10.9991054 C13.8054549,10.9991054 13.5555377,10.0754586 13.8046536,9.07541689 C13.8632547,8.84017106 13.9489218,8.5812741 14.0789589,8.22965366 C14.1358033,8.07594642 14.3689242,7.46470447 14.4229225,7.31976744 C14.5944107,6.85947528 14.7161494,6.4986824 14.8101464,6.1577119 C14.9359344,5.70142019 15,5.31568707 15,4.99910538 C15,4.54813166 14.7621788,4.30870189 14.1891338,4.1418399 C13.9483736,4.07173418 13.7113931,4.0330943 13.4599624,4.01423587 C11.914268,5.86195611 8.40663864,9.70054105 8.14171093,10.3190878 C8.04443154,10.5462133 8,10.7589101 8,10.9991054 L8,17.9991054 Z M4,11 L4,20 L6,20 L6,11 L4,11 Z"})}));function La(e,t){var o;let n=e.cloneNode(!0);n.style.top=`${e.offsetTop}px`,n.style.left=`${e.offsetLeft}px`,n.style.position="absolute",t.split(" ").forEach(s=>{n.classList.add(s)}),n.addEventListener("animationend",()=>n.remove()),(o=e.parentElement)==null||o.appendChild(n)}var y0={};xt(y0,{enUS:()=>W4,nlNL:()=>K4});var W4={thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}]},K4={thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}]};var TP={thumbs:"dd-5F1zq",fadeup:"dd-eTmY-",fadedown:"dd-sS85z",selected:"dd-rid-f",thumbsUp:"dd-4poEf",thumbsDown:"dd-3KozS"};var ho=b(R()),G4=({eventName:e,eventData:t,evaluationId:n,feedbackType:r,feedbackText:o})=>{let s=D("FeedbackThumbs",TP),i=te("enableFeedbackForm"),a=K(kr),l=K(ba(`/admin/feedback?conversationId=${a}&evaluationId=${n}&type=${r}&text=${o}&data=${JSON.stringify(t)}`)),c=ae(y0),u=Ct(),[f,d]=(0,CP.useState)(null),p=m=>{m.stopPropagation(),La(m.target,s.fadeup),d("up"),u(e,P(w({},t),{evaluationId:n,rating:"up"}))},h=m=>{m.stopPropagation(),La(m.target,s.fadedown),d("down"),u(e,P(w({},t),{evaluationId:n,rating:"down"}))};return(0,ho.jsxs)("div",{className:s.thumbs,children:[(0,ho.jsx)(de.Button,{title:c("thumbsUp"),onClick:p,icon:(0,ho.jsx)(EP,{}),className:(0,Jp.default)(s.thumbsUp,f==="up"&&s.selected),disabled:!!f}),i&&l?(0,ho.jsx)(de.Button,{as:"a",title:c("thumbsDown"),href:l,target:"_blank",rel:"noreferrer",onClick:h,icon:(0,ho.jsx)(g0,{}),className:(0,Jp.default)(s.thumbsDown,f==="down"&&s.selected),disabled:!!f}):(0,ho.jsx)(de.Button,{title:c("thumbsDown"),onClick:h,icon:(0,ho.jsx)(g0,{}),className:(0,Jp.default)(s.thumbsDown,f==="down"&&s.selected),disabled:!!f})]})},Zc=G4;var{entries:_P,setPrototypeOf:kP,isFrozen:q4,getPrototypeOf:Y4,getOwnPropertyDescriptor:X4}=Object,{freeze:Xt,seal:Hn,create:DP}=Object,{apply:E0,construct:T0}=typeof Reflect!="undefined"&&Reflect;Xt||(Xt=function(t){return t});Hn||(Hn=function(t){return t});E0||(E0=function(t,n,r){return t.apply(n,r)});T0||(T0=function(t,n){return new t(...n)});var em=Qt(Array.prototype.forEach),Q4=Qt(Array.prototype.lastIndexOf),RP=Qt(Array.prototype.pop),Jc=Qt(Array.prototype.push),Z4=Qt(Array.prototype.splice),nm=Qt(String.prototype.toLowerCase),v0=Qt(String.prototype.toString),PP=Qt(String.prototype.match),eu=Qt(String.prototype.replace),J4=Qt(String.prototype.indexOf),eF=Qt(String.prototype.trim),pr=Qt(Object.prototype.hasOwnProperty),Yt=Qt(RegExp.prototype.test),tu=tF(TypeError);function Qt(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);for(var n=arguments.length,r=new Array(n>1?n-1:0),o=1;o<n;o++)r[o-1]=arguments[o];return E0(e,t,r)}}function tF(e){return function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];return T0(e,n)}}function he(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:nm;kP&&kP(e,null);let r=t.length;for(;r--;){let o=t[r];if(typeof o=="string"){let s=n(o);s!==o&&(q4(t)||(t[r]=s),o=s)}e[o]=!0}return e}function nF(e){for(let t=0;t<e.length;t++)pr(e,t)||(e[t]=null);return e}function ii(e){let t=DP(null);for(let[n,r]of _P(e))pr(e,n)&&(Array.isArray(r)?t[n]=nF(r):r&&typeof r=="object"&&r.constructor===Object?t[n]=ii(r):t[n]=r);return t}function nu(e,t){for(;e!==null;){let r=X4(e,t);if(r){if(r.get)return Qt(r.get);if(typeof r.value=="function")return Qt(r.value)}e=Y4(e)}function n(){return null}return n}var IP=Xt(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","section","select","shadow","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),x0=Xt(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","filter","font","g","glyph","glyphref","hkern","image","line","lineargradient","marker","mask","metadata","mpath","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),S0=Xt(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),rF=Xt(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),w0=Xt(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),oF=Xt(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),AP=Xt(["#text"]),LP=Xt(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","face","for","headers","height","hidden","high","href","hreflang","id","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),b0=Xt(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),MP=Xt(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),tm=Xt(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),sF=Hn(/\{\{[\w\W]*|[\w\W]*\}\}/gm),iF=Hn(/<%[\w\W]*|[\w\W]*%>/gm),aF=Hn(/\$\{[\w\W]*/gm),lF=Hn(/^data-[\-\w.\u00B7-\uFFFF]+$/),cF=Hn(/^aria-[\-\w]+$/),FP=Hn(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),uF=Hn(/^(?:\w+script|data):/i),dF=Hn(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),zP=Hn(/^html$/i),fF=Hn(/^[a-z][.\w]*(-[.\w]+)+$/i),OP=Object.freeze({__proto__:null,ARIA_ATTR:cF,ATTR_WHITESPACE:dF,CUSTOM_ELEMENT:fF,DATA_ATTR:lF,DOCTYPE_NAME:zP,ERB_EXPR:iF,IS_ALLOWED_URI:FP,IS_SCRIPT_OR_DATA:uF,MUSTACHE_EXPR:sF,TMPLIT_EXPR:aF}),ru={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,progressingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},pF=function(){return typeof window=="undefined"?null:window},mF=function(t,n){if(typeof t!="object"||typeof t.createPolicy!="function")return null;let r=null,o="data-tt-policy-suffix";n&&n.hasAttribute(o)&&(r=n.getAttribute(o));let s="dompurify"+(r?"#"+r:"");try{return t.createPolicy(s,{createHTML(i){return i},createScriptURL(i){return i}})}catch(i){return console.warn("TrustedTypes policy "+s+" could not be created."),null}},NP=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function HP(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:pF(),t=ne=>HP(ne);if(t.version="3.2.5",t.removed=[],!e||!e.document||e.document.nodeType!==ru.document||!e.Element)return t.isSupported=!1,t;let{document:n}=e,r=n,o=r.currentScript,{DocumentFragment:s,HTMLTemplateElement:i,Node:a,Element:l,NodeFilter:c,NamedNodeMap:u=e.NamedNodeMap||e.MozNamedAttrMap,HTMLFormElement:f,DOMParser:d,trustedTypes:p}=e,h=l.prototype,m=nu(h,"cloneNode"),x=nu(h,"remove"),v=nu(h,"nextSibling"),y=nu(h,"childNodes"),g=nu(h,"parentNode");if(typeof i=="function"){let ne=n.createElement("template");ne.content&&ne.content.ownerDocument&&(n=ne.content.ownerDocument)}let S,E="",{implementation:k,createNodeIterator:C,createDocumentFragment:I,getElementsByTagName:$}=n,{importNode:_}=r,L=NP();t.isSupported=typeof _P=="function"&&typeof g=="function"&&k&&k.createHTMLDocument!==void 0;let{MUSTACHE_EXPR:Q,ERB_EXPR:Z,TMPLIT_EXPR:N,DATA_ATTR:z,ARIA_ATTR:B,IS_SCRIPT_OR_DATA:j,ATTR_WHITESPACE:H,CUSTOM_ELEMENT:V}=OP,{IS_ALLOWED_URI:W}=OP,O=null,q=he({},[...IP,...x0,...S0,...w0,...AP]),ce=null,Ge=he({},[...LP,...b0,...MP,...tm]),pe=Object.seal(DP(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),Pe=null,De=null,xe=!0,be=!0,rt=!1,oe=!0,X=!1,se=!0,ue=!1,$e=!1,yt=!1,Xe=!1,He=!1,Qe=!1,ct=!0,ds=!1,fs="user-content-",Zt=!0,hr=!1,zr={},mi=null,W0=he({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]),K0=null,G0=he({},["audio","video","img","source","image","track"]),xm=null,q0=he({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),pu="http://www.w3.org/1998/Math/MathML",mu="http://www.w3.org/2000/svg",Hr="http://www.w3.org/1999/xhtml",gi=Hr,Sm=!1,wm=null,KI=he({},[pu,mu,Hr],v0),gu=he({},["mi","mo","mn","ms","mtext"]),hu=he({},["annotation-xml"]),GI=he({},["title","style","font","a","script"]),Ba=null,qI=["application/xhtml+xml","text/html"],YI="text/html",ut=null,hi=null,XI=n.createElement("form"),Y0=function(T){return T instanceof RegExp||T instanceof Function},bm=function(){let T=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(hi&&hi===T)){if((!T||typeof T!="object")&&(T={}),T=ii(T),Ba=qI.indexOf(T.PARSER_MEDIA_TYPE)===-1?YI:T.PARSER_MEDIA_TYPE,ut=Ba==="application/xhtml+xml"?v0:nm,O=pr(T,"ALLOWED_TAGS")?he({},T.ALLOWED_TAGS,ut):q,ce=pr(T,"ALLOWED_ATTR")?he({},T.ALLOWED_ATTR,ut):Ge,wm=pr(T,"ALLOWED_NAMESPACES")?he({},T.ALLOWED_NAMESPACES,v0):KI,xm=pr(T,"ADD_URI_SAFE_ATTR")?he(ii(q0),T.ADD_URI_SAFE_ATTR,ut):q0,K0=pr(T,"ADD_DATA_URI_TAGS")?he(ii(G0),T.ADD_DATA_URI_TAGS,ut):G0,mi=pr(T,"FORBID_CONTENTS")?he({},T.FORBID_CONTENTS,ut):W0,Pe=pr(T,"FORBID_TAGS")?he({},T.FORBID_TAGS,ut):{},De=pr(T,"FORBID_ATTR")?he({},T.FORBID_ATTR,ut):{},zr=pr(T,"USE_PROFILES")?T.USE_PROFILES:!1,xe=T.ALLOW_ARIA_ATTR!==!1,be=T.ALLOW_DATA_ATTR!==!1,rt=T.ALLOW_UNKNOWN_PROTOCOLS||!1,oe=T.ALLOW_SELF_CLOSE_IN_ATTR!==!1,X=T.SAFE_FOR_TEMPLATES||!1,se=T.SAFE_FOR_XML!==!1,ue=T.WHOLE_DOCUMENT||!1,Xe=T.RETURN_DOM||!1,He=T.RETURN_DOM_FRAGMENT||!1,Qe=T.RETURN_TRUSTED_TYPE||!1,yt=T.FORCE_BODY||!1,ct=T.SANITIZE_DOM!==!1,ds=T.SANITIZE_NAMED_PROPS||!1,Zt=T.KEEP_CONTENT!==!1,hr=T.IN_PLACE||!1,W=T.ALLOWED_URI_REGEXP||FP,gi=T.NAMESPACE||Hr,gu=T.MATHML_TEXT_INTEGRATION_POINTS||gu,hu=T.HTML_INTEGRATION_POINTS||hu,pe=T.CUSTOM_ELEMENT_HANDLING||{},T.CUSTOM_ELEMENT_HANDLING&&Y0(T.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(pe.tagNameCheck=T.CUSTOM_ELEMENT_HANDLING.tagNameCheck),T.CUSTOM_ELEMENT_HANDLING&&Y0(T.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(pe.attributeNameCheck=T.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),T.CUSTOM_ELEMENT_HANDLING&&typeof T.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(pe.allowCustomizedBuiltInElements=T.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),X&&(be=!1),He&&(Xe=!0),zr&&(O=he({},AP),ce=[],zr.html===!0&&(he(O,IP),he(ce,LP)),zr.svg===!0&&(he(O,x0),he(ce,b0),he(ce,tm)),zr.svgFilters===!0&&(he(O,S0),he(ce,b0),he(ce,tm)),zr.mathMl===!0&&(he(O,w0),he(ce,MP),he(ce,tm))),T.ADD_TAGS&&(O===q&&(O=ii(O)),he(O,T.ADD_TAGS,ut)),T.ADD_ATTR&&(ce===Ge&&(ce=ii(ce)),he(ce,T.ADD_ATTR,ut)),T.ADD_URI_SAFE_ATTR&&he(xm,T.ADD_URI_SAFE_ATTR,ut),T.FORBID_CONTENTS&&(mi===W0&&(mi=ii(mi)),he(mi,T.FORBID_CONTENTS,ut)),Zt&&(O["#text"]=!0),ue&&he(O,["html","head","body"]),O.table&&(he(O,["tbody"]),delete Pe.tbody),T.TRUSTED_TYPES_POLICY){if(typeof T.TRUSTED_TYPES_POLICY.createHTML!="function")throw tu('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof T.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw tu('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');S=T.TRUSTED_TYPES_POLICY,E=S.createHTML("")}else S===void 0&&(S=mF(p,o)),S!==null&&typeof E=="string"&&(E=S.createHTML(""));Xt&&Xt(T),hi=T}},X0=he({},[...x0,...S0,...rF]),Q0=he({},[...w0,...oF]),QI=function(T){let U=g(T);(!U||!U.tagName)&&(U={namespaceURI:gi,tagName:"template"});let J=nm(T.tagName),Be=nm(U.tagName);return wm[T.namespaceURI]?T.namespaceURI===mu?U.namespaceURI===Hr?J==="svg":U.namespaceURI===pu?J==="svg"&&(Be==="annotation-xml"||gu[Be]):!!X0[J]:T.namespaceURI===pu?U.namespaceURI===Hr?J==="math":U.namespaceURI===mu?J==="math"&&hu[Be]:!!Q0[J]:T.namespaceURI===Hr?U.namespaceURI===mu&&!hu[Be]||U.namespaceURI===pu&&!gu[Be]?!1:!Q0[J]&&(GI[J]||!X0[J]):!!(Ba==="application/xhtml+xml"&&wm[T.namespaceURI]):!1},yr=function(T){Jc(t.removed,{element:T});try{g(T).removeChild(T)}catch(U){x(T)}},yu=function(T,U){try{Jc(t.removed,{attribute:U.getAttributeNode(T),from:U})}catch(J){Jc(t.removed,{attribute:null,from:U})}if(U.removeAttribute(T),T==="is")if(Xe||He)try{yr(U)}catch(J){}else try{U.setAttribute(T,"")}catch(J){}},Z0=function(T){let U=null,J=null;if(yt)T="<remove></remove>"+T;else{let vt=PP(T,/^[\r\n\t ]+/);J=vt&&vt[0]}Ba==="application/xhtml+xml"&&gi===Hr&&(T='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+T+"</body></html>");let Be=S?S.createHTML(T):T;if(gi===Hr)try{U=new d().parseFromString(Be,Ba)}catch(vt){}if(!U||!U.documentElement){U=k.createDocument(gi,"template",null);try{U.documentElement.innerHTML=Sm?E:Be}catch(vt){}}let kt=U.body||U.documentElement;return T&&J&&kt.insertBefore(n.createTextNode(J),kt.childNodes[0]||null),gi===Hr?$.call(U,ue?"html":"body")[0]:ue?U.documentElement:kt},J0=function(T){return C.call(T.ownerDocument||T,T,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT|c.SHOW_PROCESSING_INSTRUCTION|c.SHOW_CDATA_SECTION,null)},Em=function(T){return T instanceof f&&(typeof T.nodeName!="string"||typeof T.textContent!="string"||typeof T.removeChild!="function"||!(T.attributes instanceof u)||typeof T.removeAttribute!="function"||typeof T.setAttribute!="function"||typeof T.namespaceURI!="string"||typeof T.insertBefore!="function"||typeof T.hasChildNodes!="function")},ex=function(T){return typeof a=="function"&&T instanceof a};function Br(ne,T,U){em(ne,J=>{J.call(t,T,U,hi)})}let tx=function(T){let U=null;if(Br(L.beforeSanitizeElements,T,null),Em(T))return yr(T),!0;let J=ut(T.nodeName);if(Br(L.uponSanitizeElement,T,{tagName:J,allowedTags:O}),T.hasChildNodes()&&!ex(T.firstElementChild)&&Yt(/<[/\w!]/g,T.innerHTML)&&Yt(/<[/\w!]/g,T.textContent)||T.nodeType===ru.progressingInstruction||se&&T.nodeType===ru.comment&&Yt(/<[/\w]/g,T.data))return yr(T),!0;if(!O[J]||Pe[J]){if(!Pe[J]&&rx(J)&&(pe.tagNameCheck instanceof RegExp&&Yt(pe.tagNameCheck,J)||pe.tagNameCheck instanceof Function&&pe.tagNameCheck(J)))return!1;if(Zt&&!mi[J]){let Be=g(T)||T.parentNode,kt=y(T)||T.childNodes;if(kt&&Be){let vt=kt.length;for(let Jt=vt-1;Jt>=0;--Jt){let vr=m(kt[Jt],!0);vr.__removalCount=(T.__removalCount||0)+1,Be.insertBefore(vr,v(T))}}}return yr(T),!0}return T instanceof l&&!QI(T)||(J==="noscript"||J==="noembed"||J==="noframes")&&Yt(/<\/no(script|embed|frames)/i,T.innerHTML)?(yr(T),!0):(X&&T.nodeType===ru.text&&(U=T.textContent,em([Q,Z,N],Be=>{U=eu(U,Be," ")}),T.textContent!==U&&(Jc(t.removed,{element:T.cloneNode()}),T.textContent=U)),Br(L.afterSanitizeElements,T,null),!1)},nx=function(T,U,J){if(ct&&(U==="id"||U==="name")&&(J in n||J in XI))return!1;if(!(be&&!De[U]&&Yt(z,U))){if(!(xe&&Yt(B,U))){if(!ce[U]||De[U]){if(!(rx(T)&&(pe.tagNameCheck instanceof RegExp&&Yt(pe.tagNameCheck,T)||pe.tagNameCheck instanceof Function&&pe.tagNameCheck(T))&&(pe.attributeNameCheck instanceof RegExp&&Yt(pe.attributeNameCheck,U)||pe.attributeNameCheck instanceof Function&&pe.attributeNameCheck(U))||U==="is"&&pe.allowCustomizedBuiltInElements&&(pe.tagNameCheck instanceof RegExp&&Yt(pe.tagNameCheck,J)||pe.tagNameCheck instanceof Function&&pe.tagNameCheck(J))))return!1}else if(!xm[U]){if(!Yt(W,eu(J,H,""))){if(!((U==="src"||U==="xlink:href"||U==="href")&&T!=="script"&&J4(J,"data:")===0&&K0[T])){if(!(rt&&!Yt(j,eu(J,H,"")))){if(J)return!1}}}}}}return!0},rx=function(T){return T!=="annotation-xml"&&PP(T,V)},ox=function(T){Br(L.beforeSanitizeAttributes,T,null);let{attributes:U}=T;if(!U||Em(T))return;let J={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:ce,forceKeepAttr:void 0},Be=U.length;for(;Be--;){let kt=U[Be],{name:vt,namespaceURI:Jt,value:vr}=kt,Ua=ut(vt),_t=vt==="value"?vr:eF(vr);if(J.attrName=Ua,J.attrValue=_t,J.keepAttr=!0,J.forceKeepAttr=void 0,Br(L.uponSanitizeAttribute,T,J),_t=J.attrValue,ds&&(Ua==="id"||Ua==="name")&&(yu(vt,T),_t=fs+_t),se&&Yt(/((--!?|])>)|<\/(style|title)/i,_t)){yu(vt,T);continue}if(J.forceKeepAttr||(yu(vt,T),!J.keepAttr))continue;if(!oe&&Yt(/\/>/i,_t)){yu(vt,T);continue}X&&em([Q,Z,N],ix=>{_t=eu(_t,ix," ")});let sx=ut(T.nodeName);if(nx(sx,Ua,_t)){if(S&&typeof p=="object"&&typeof p.getAttributeType=="function"&&!Jt)switch(p.getAttributeType(sx,Ua)){case"TrustedHTML":{_t=S.createHTML(_t);break}case"TrustedScriptURL":{_t=S.createScriptURL(_t);break}}try{Jt?T.setAttributeNS(Jt,vt,_t):T.setAttribute(vt,_t),Em(T)?yr(T):RP(t.removed)}catch(ix){}}}Br(L.afterSanitizeAttributes,T,null)},ZI=function ne(T){let U=null,J=J0(T);for(Br(L.beforeSanitizeShadowDOM,T,null);U=J.nextNode();)Br(L.uponSanitizeShadowNode,U,null),tx(U),ox(U),U.content instanceof s&&ne(U.content);Br(L.afterSanitizeShadowDOM,T,null)};return t.sanitize=function(ne){let T=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},U=null,J=null,Be=null,kt=null;if(Sm=!ne,Sm&&(ne="<!-->"),typeof ne!="string"&&!ex(ne))if(typeof ne.toString=="function"){if(ne=ne.toString(),typeof ne!="string")throw tu("dirty is not a string, aborting")}else throw tu("toString is not a function");if(!t.isSupported)return ne;if($e||bm(T),t.removed=[],typeof ne=="string"&&(hr=!1),hr){if(ne.nodeName){let vr=ut(ne.nodeName);if(!O[vr]||Pe[vr])throw tu("root node is forbidden and cannot be sanitized in-place")}}else if(ne instanceof a)U=Z0("<!---->"),J=U.ownerDocument.importNode(ne,!0),J.nodeType===ru.element&&J.nodeName==="BODY"||J.nodeName==="HTML"?U=J:U.appendChild(J);else{if(!Xe&&!X&&!ue&&ne.indexOf("<")===-1)return S&&Qe?S.createHTML(ne):ne;if(U=Z0(ne),!U)return Xe?null:Qe?E:""}U&&yt&&yr(U.firstChild);let vt=J0(hr?ne:U);for(;Be=vt.nextNode();)tx(Be),ox(Be),Be.content instanceof s&&ZI(Be.content);if(hr)return ne;if(Xe){if(He)for(kt=I.call(U.ownerDocument);U.firstChild;)kt.appendChild(U.firstChild);else kt=U;return(ce.shadowroot||ce.shadowrootmode)&&(kt=_.call(r,kt,!0)),kt}let Jt=ue?U.outerHTML:U.innerHTML;return ue&&O["!doctype"]&&U.ownerDocument&&U.ownerDocument.doctype&&U.ownerDocument.doctype.name&&Yt(zP,U.ownerDocument.doctype.name)&&(Jt="<!DOCTYPE "+U.ownerDocument.doctype.name+`>
78
+ Please report this to https://github.com/markedjs/marked.`,t){let o="<p>An error occurred:</p><pre>"+Nr(r.message+"",!0)+"</pre>";return n?Promise.resolve(o):o}if(n)return Promise.reject(r);throw r}}},oi=new $c;function Ce(e,t){return oi.parse(e,t)}Ce.options=Ce.setOptions=function(e){return oi.setOptions(e),Ce.defaults=oi.defaults,BR(Ce.defaults),Ce};Ce.getDefaults=Zv;Ce.defaults=si;Ce.use=function(...e){return oi.use(...e),Ce.defaults=oi.defaults,BR(Ce.defaults),Ce};Ce.walkTokens=function(e,t){return oi.walkTokens(e,t)};Ce.parseInline=oi.parseInline;Ce.Parser=dr;Ce.parser=dr.parse;Ce.Renderer=Ia;Ce.TextRenderer=Vc;Ce.Lexer=ur;Ce.lexer=ur.lex;Ce.Tokenizer=Pa;Ce.Hooks=ri;Ce.parse=Ce;var fG=Ce.options,pG=Ce.setOptions,mG=Ce.use,gG=Ce.walkTokens,hG=Ce.parseInline;var yG=dr.parse,vG=ur.lex;var QR=(e,t)=>{let n=[],r=new $c,o=s=>{s.type==="code"&&s.lang===t&&n.push(s.text)};return r.use({walkTokens:o}),r.parse(e),n};var Wc="__summarizerAssistant__",ZR={cues:[],threads:{},pending:[]},JR=e=>{var t;return(t=e.assistants)==null?void 0:t.cues};var i0=e=>t=>{var n,r;return(r=(n=t.assistants)==null?void 0:n.threads[e])!=null?r:null},qp=it("assistants/callToAction"),mo=fe("assistants/evaluateSummaryAssistant",(e,t)=>A(void 0,null,function*(){try{let r=t.getState().profile.data;if(!r)throw new Error("No Profile is loaded");let{summarizerAssistantNew:o}=r;if(!o)throw new Error("No Summarizer Assistant set in Profile");let s=yield t.dispatch(fr(w({assistantCode:o,expectFormat:"text",transcript:"in-memory-transcript",skipState:!0},e)));if(s.error)throw new Error(s.error.message);if(typeof s.payload.output!="string")throw ee.warn("Unexpected summary output",s),new Error("Unexpected summary output");return{output:s.payload.output,evaluationId:s.payload.evaluationId}}catch(n){return n instanceof Error?t.rejectWithValue(n.message):t.rejectWithValue("Unknown error")}})),O4=1,Kc=fe("assistants/evaluateKnowledgeAssistantLegacy",(e,t)=>A(void 0,null,function*(){var p,h,m,x;let{threadId:n}=e,{onNewThreadId:r,input:o}=e,{deepdeskAPI:s}=t.extra,i=t.getState(),{platformVariables:a}=i.info;n||(n=O4++,r&&r(n));let l=(p=i0(n)(i))!=null?p:[],c=yield s.getKnowledgeAssistant(e.assistantCode),u=(h=i.conversation.current)==null?void 0:h.externalId,f=(x=(m=i.info)==null?void 0:m.agentInfo)==null?void 0:x.agentId;if(!c)throw new Error("KnowledgeAssistant is not found");let d=yield s.knowledgeAssist({customerInstruction:c.customerInstruction,doNotKnowAnswer:c.doNotKnowAnswer,question:o},l,c.code,{agentId:f,conversationId:u});return a&&(d.answer=ln(d.answer,a)),{threadId:n,question:o,answer:d,evaluationId:"??"}})),Gc=fe("assistants/evaluateKnowledgeAssistant",(e,t)=>A(void 0,null,function*(){let{threadId:n}=e,{onNewThreadId:r}=e,{deepdeskAPI:o}=t.extra,s=t.getState(),{platformVariables:i}=s.info;n||(n=(yield o.createAssistantThread({assistantCode:e.assistantCode})).id,r&&r(n)),yield o.postMessageToAssistantThread({assistantCode:e.assistantCode,threadId:n,message:e.input});let a=yield t.dispatch(fr(P(w({expectFormat:"json-schema:knowledge-assist",skipState:!0},e),{input:{},threadId:n})));if(a.error)throw new Error(a.error.message);let l=a.payload.output;return{threadId:n,question:e.input,evaluationId:a.payload.evaluationId,answer:{answer:ln(l.response,i!=null?i:{}),sources:l.sources}}})),LG=it("assistants/extractedTextSuggestions"),fr=fe("assistants/evaluate",(e,t)=>A(void 0,null,function*(){var p;let{deepdeskAPI:n,dynamicThunkObject:r}=t.extra,{transcript:o,input:s={},expectFormat:i,threadId:a}=e,l=t.getState(),{platformVariables:c}=l.info,u=(p=l.conversation.current)==null?void 0:p.externalId,f;if(o==="in-memory-transcript"){if(!r.conversationQuery)throw new Error("Can't include in-memory-transcript, setConversationQuery is not defined");f=yield r.conversationQuery()}else Array.isArray(o)&&(f=o);if(e.includeMetadata){if(!l.conversation.current)throw new Error("Can't include metadata, no current conversation");let{metadata:h}=l.conversation.current;Object.assign(s,{metadata:h})}let d=yield n.evaluateAssistant(e.assistantCode,{expectFormat:i,input:s,transcript:f,externalConversationId:u,threadId:a});if(d.evaluationStatus!=="success")throw new Error(`Assistant ${e.assistantCode} evaluation failed: ${d.evaluationStatus}`);switch(i){case"text":return{evaluationId:d.evaluationId,output:ln(d.output,c)};case"json-schema:cues":{if(!Array.isArray(d.output))return P(w({},d),{output:[]});let h=d.output.map(x=>P(w({},x),{name:ln(x.name,c),response:ln(x.response,c)})),m=[];return h.forEach(x=>{let v=QR(x.response,"reply");m.push(...v.map(y=>({text:y,type:"text",source:"assistant",assistantCode:x.code,sourceLabel:x.name})))}),m.length>0&&t.dispatch(bf(m)),P(w({},d),{output:h})}case"json-schema:knowledge-assist":{let h=d.output;if(d.output==="")throw new Error("No output from assistant");return{output:h,evaluationId:d.evaluationId,answer:ln(h.response,c)}}default:return d}})),eP=Ee({name:"assistants",initialState:ZR,reducers:{resetCues(e){e.cues=[]},removeCueByCode(e,t){e.cues=e.cues.filter(n=>n.code!==t.payload.code)},removeThreadById(e,t){delete e.threads[t.payload]},receiveChunk(e,t){let{code:n,name:r,payload:o,evaluationId:s}=t.payload,i=e.cues.findIndex(a=>a.code===n);i!==-1?e.cues[i].response+=o.text:e.cues.push({code:n,name:r,evaluationId:s,response:o.text})},userNotification(e,t){let n=e.cues.filter(l=>l.code!==t.payload.code),{code:r,name:o,evaluationId:s,payload:i}=t.payload,{callToAction:a}=i;e.cues=[...n,{code:r,name:o,evaluationId:s,response:i.message,editable:i.editableMessage,callToAction:a&&{label:a.displayName,event:a.onClickEvent,value:a.eventPayload}}]}},extraReducers:e=>{e.addCase(fr.pending,(t,n)=>{t.pending.includes(n.meta.arg.assistantCode)&&ee.warn(`Assistant ${n.meta.arg.assistantCode} already evaluating`),t.pending.push(n.meta.arg.assistantCode)}).addCase(fr.rejected,(t,n)=>{var o;ee.warn((o=n.error)==null?void 0:o.message);let r=t.pending.indexOf(n.meta.arg.assistantCode);r!==-1&&t.pending.splice(r,1)}).addCase(fr.fulfilled,(t,n)=>{let r=t.pending.indexOf(n.meta.arg.assistantCode);if(r!==-1&&t.pending.splice(r,1),!n.meta.arg.skipState)switch(n.meta.arg.expectFormat){case"json-schema:cues":{let{evaluationId:o,output:s}=n.payload,i=s.map(c=>c.code),a=t.cues.filter(c=>!i.includes(c.code)),l=s.map(c=>P(w({},c),{evaluationId:o}));t.cues=[...a,...l];break}}}).addCase(Gc.fulfilled,(t,n)=>{let s=n.payload,{threadId:r}=s,o=re(s,["threadId"]);t.threads[r]=[...t.threads[r]||[],o]}).addCase(Kc.fulfilled,(t,n)=>{let s=n.payload,{threadId:r}=s,o=re(s,["threadId"]);t.threads[r]=[...t.threads[r]||[],o]}).addCase(mo.pending,t=>{let n={code:Wc,name:"Summary",response:"",isLoading:!0,evaluationId:""},r=t.cues.filter(o=>o.code!==Wc);t.cues=[...r,n]}).addCase(mo.rejected,t=>{let n=t.cues.filter(r=>r.code!==Wc);t.cues=n}).addCase(mo.fulfilled,(t,n)=>{let r={code:Wc,name:"Summary",response:n.payload.output,specialType:"summary",evaluationId:n.payload.evaluationId},o=t.cues.filter(s=>s.code!==Wc);t.cues=[...o,r]}).addCase(at,()=>ZR)}}),{removeCueByCode:Yp,resetCues:MG,removeThreadById:tP,receiveChunk:nP,userNotification:rP}=eP.actions,oP=eP.reducer;var N4={token:null,interval:null},a0=fe("passwordlessToken/getTemporaryPasswordlessToken",(e,t)=>A(void 0,null,function*(){let{deepdeskAPI:n}=t.extra;return{token:yield n.requestPasswordlessToken()}})),l0=fe("passwordlessToken/pollPasswordlessToken",(e={},t)=>{let{interval:n=1e3*60*10}=e,{dispatch:r}=t;return r(a0()),setInterval(()=>r(a0()),n)}),sP=Ee({name:"passwordlessToken",initialState:N4,reducers:{stopPollPasswordlessToken(e){e.interval&&clearInterval(e.interval),e.interval=null}},extraReducers:e=>{e.addCase(a0.fulfilled,(t,n)=>{t.token=n.payload.token}),e.addCase(l0.fulfilled,(t,n)=>{t.interval=n.payload})}}),{stopPollPasswordlessToken:iP}=sP.actions,aP=sP.reducer;function _4(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return t}var lP=Vt([JR],e=>e.map(n=>({text:n.response,title:n.name,callToAction:n.callToAction,editable:n.editable,isLoading:n.isLoading,specialType:n.specialType,evaluationId:n.evaluationId,rule:{id:_4(n.code),label:n.code,name:n.name,description:n.name}})));var Xp=b(Y());var u0=b(Me());var c0=b(R()),qc=()=>(0,c0.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 512 512",xmlns:"http://www.w3.org/2000/svg",children:(0,c0.jsx)("path",{d:"M502.6 70.63l-61.25-61.25C435.4 3.371 427.2 0 418.7 0H255.1c-35.35 0-64 28.66-64 64l.0195 256C192 355.4 220.7 384 256 384h192c35.2 0 64-28.8 64-64V93.25C512 84.77 508.6 76.63 502.6 70.63zM464 320c0 8.836-7.164 16-16 16H255.1c-8.838 0-16-7.164-16-16L239.1 64.13c0-8.836 7.164-16 16-16h128L384 96c0 17.67 14.33 32 32 32h47.1V320zM272 448c0 8.836-7.164 16-16 16H63.1c-8.838 0-16-7.164-16-16L47.98 192.1c0-8.836 7.164-16 16-16H160V128H63.99c-35.35 0-64 28.65-64 64l.0098 256C.002 483.3 28.66 512 64 512h192c35.2 0 64-28.8 64-64v-32h-47.1L272 448z"})});var cP={root:"dd-WcEru",entity:"dd-LfP8y",entityText:"dd-L-v0f",iconWrapper:"dd-9Deh1",icon:"dd-tM7E2",iconClicked:"dd-EEdDL"};var _r=b(R()),D4=({entities:e})=>{let t=D("EntitiesWidgetList",cP),[n,r]=(0,Xp.useState)(void 0),o=ge(),s=()=>{r(void 0)},i=a=>{e&&(r(e.indexOf(a)),Rr(a.text),o(Go({name:"entity copied",data:{entity:a,type:"copy"}})))};return(0,Xp.useEffect)(()=>{let a=setTimeout(s,500);return()=>{clearTimeout(a)}},[n]),!e||e.length===0?null:(0,_r.jsx)("div",{className:t.root,"data-testid":"widget-entities-list",children:e.map((a,l)=>(0,_r.jsxs)("button",{title:a.text,className:t.entity,type:"button",onClick:()=>i(a),children:[(0,_r.jsx)("span",{className:t.entityText,children:a.text}),(0,_r.jsxs)("span",{className:t.iconWrapper,children:[(0,_r.jsx)("span",{className:(0,u0.default)(t.icon),children:(0,_r.jsx)(qc,{})}),(0,_r.jsx)("span",{className:(0,u0.default)(t.icon,n===l&&t.iconClicked),children:(0,_r.jsx)(qc,{})})]})]},a.text))})},uP=D4;var d0=b(R()),dP=()=>(0,d0.jsx)("svg",{width:"1em",height:"1em",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:(0,d0.jsx)("path",{d:"M17 13.5v6H5v-12h6m3-3h6v6m0-6-9 9",stroke:"currentColor",strokeWidth:"1.5",fill:"none",fillRule:"evenodd",strokeLinecap:"round",strokeLinejoin:"round"})});var vP=b(Y());var Aa=b(Y());function Yc(e,t){let n=(0,Aa.useRef)(e);n.current=e;let[r,o]=(0,Aa.useState)(void 0),[s,i]=(0,Aa.useState)(void 0),[a,l]=(0,Aa.useState)("idle"),c=ge();return{error:s,state:a,data:r,call:d=>A(this,null,function*(){l("loading"),yield c(n.current(d)).unwrap().then(p=>{o(p),l("done"),t!=null&&t.onSuccess&&(t==null||t.onSuccess(p))}).catch(p=>{i(p),l("error"),t!=null&&t.onError&&(t==null||t.onError(p))})}),reset:()=>{l("idle"),o(void 0),i(void 0)}}}var fP={root:"dd-ohnXe",trigger:"dd-7i-S3",button:"dd-t53Cg",nav:"dd-qZFnm",item:"dd-FZC0F"};var pP={root:"dd-nazq3",rotation:"dd-3EHTv"};var gP=b(R()),F4=({size:e=12})=>{let t=D("LoadingSpinner",pP);return(0,gP.jsx)("span",{"data-testid":"loading-spinner",style:{width:`${e}px`,height:`${e}px`},className:t.root})},mP=F4;var f0=b(R()),hP=()=>(0,f0.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",height:"1em",viewBox:"0 0 512 512",fill:"currentColor",children:(0,f0.jsx)("path",{d:"M256 32c14.2 0 27.3 7.5 34.5 19.8l216 368c7.3 12.4 7.3 27.7 .2 40.1S486.3 480 472 480H40c-14.3 0-27.6-7.7-34.7-20.1s-7-27.8 .2-40.1l216-368C228.7 39.5 241.8 32 256 32zm0 128c-13.3 0-24 10.7-24 24V296c0 13.3 10.7 24 24 24s24-10.7 24-24V184c0-13.3-10.7-24-24-24zm32 224c0-17.7-14.3-32-32-32s-32 14.3-32 32s14.3 32 32 32s32-14.3 32-32z"})});var Xc=b(R()),yP=e=>(0,Xc.jsxs)("svg",P(w({xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 448 512","aria-labelledby":"checkTitle"},e),{children:[(0,Xc.jsx)("title",{id:"checkTitle",children:"Check"}),(0,Xc.jsx)("path",{fill:"#666",d:"M438.6 105.4c12.5 12.5 12.5 32.8 0 45.3l-256 256c-12.5 12.5-32.8 12.5-45.3 0l-128-128c-12.5-12.5-12.5-32.8 0-45.3s32.8-12.5 45.3 0L160 338.7 393.4 105.4c12.5-12.5 32.8-12.5 45.3 0z"})]}));var p0={};xt(p0,{enUS:()=>z4,nlNL:()=>H4});var z4={error:[{type:0,value:"Something went wrong"}]},H4={error:[{type:0,value:"Er ging iets fout"}]};var kn=b(R()),B4=3e3,U4=({assistantOptions:e})=>{let t=D("OnDemandAssistants",fP),n=ae(p0),r=(0,vP.useRef)(),o=Yc(fr),s=Yc(mo),i=K(RT),a=K(PT),l=Ct(),c=a.filter(d=>d.isPinned),u=a.filter(d=>!d.isPinned),f=d=>A(void 0,null,function*(){clearTimeout(r.current),l("trigger on demand assistant",{assistantCode:d}),d===i?yield s.call({transcript:e.transcript}):yield o.call(P(w({},e),{assistantCode:d})),r.current=setTimeout(()=>o.reset(),B4)});return a.length===0?null:(0,kn.jsxs)("div",{className:t.root,children:[c.map(({assistant:d,assistantName:p,displayName:h})=>(0,kn.jsx)("button",{type:"button",className:t.button,disabled:o.state==="loading",onClick:()=>f(d),children:h||p},d)),u.length>0&&(0,kn.jsxs)(gt,{placement:"top-end",children:[(0,kn.jsx)(gt.Trigger,{className:t.trigger,disabled:o.state==="loading",children:(0,kn.jsx)(yp,{"data-testid":"trigger"})}),(0,kn.jsx)(gt.Content,{className:t.nav,"data-testid":"popover",children:u.map(({assistant:d,assistantName:p,displayName:h})=>(0,kn.jsx)(gt.Button,{className:t.item,disabled:o.state==="loading",onClick:()=>f(d),children:h||p},d))})]}),o.state==="loading"&&(0,kn.jsx)(mP,{}),o.state==="done"&&(0,kn.jsx)(yP,{"data-testid":"trigger-done"}),o.state==="error"&&(0,kn.jsx)(pk,{trigger:(0,kn.jsx)(hP,{}),children:n("error")})]})},xP=U4;var bP=b(Y());var SP={loadingBar:"dd-6as-V",placeHolderShimmer:"dd-TFYmA"};var wP=b(R()),V4=({width:e})=>{let t=D("LoadingProgressBar",SP);return(0,wP.jsx)("div",{className:t.loadingBar,style:{width:e}})},Qp=V4;var go=b(R()),Zp=({title:e})=>{let t=(0,bP.useRef)(null);return Iu(t),(0,go.jsx)(de,{ref:t,children:(0,go.jsx)(ve,{children:(0,go.jsxs)(ve.Content,{children:[(0,go.jsx)(ve.Title,{children:e}),(0,go.jsx)(Qp,{width:"60%"}),(0,go.jsx)(Qp,{width:"90%"}),(0,go.jsx)(Qp,{width:"50%"})]})})})};var Qc={};xt(Qc,{enUS:()=>$4,nlNL:()=>j4});var $4={useCue:[{type:0,value:"Add to message"}],__summarizerAssistant__:[{type:0,value:"Summary"}],copyCue:[{type:0,value:"Copy"}],removeCue:[{type:0,value:"Close"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}]},j4={useCue:[{type:0,value:"Voeg toe aan bericht"}],__summarizerAssistant__:[{type:0,value:"Samenvatting"}],copyCue:[{type:0,value:"Kopi\xEBren"}],removeCue:[{type:0,value:"Sluiten"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}]};var li=b(Y());var Jp=b(Me()),CP=b(Y());var m0=b(R()),g0=e=>(0,m0.jsx)("svg",P(w({width:"16",height:"16",fill:"#000000"},e),{viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:(0,m0.jsx)("path",{fillRule:"evenodd",d:"M6.57086468,14.9173453 C6.38997052,14.9711236 6.19835748,15 6,15 L4,15 C2.8954305,15 2,14.1045695 2,13 L2,4 C2,2.8954305 2.8954305,2 4,2 L6,2 C6.68685475,2 7.29284112,2.34623869 7.65294381,2.87370078 C7.95642355,2.67736738 8.29504785,2.51351337 8.66312366,2.3818197 C9.50544052,2.08044754 10.3408482,1.9879107 10.9989281,1.99971266 C11.0150698,2.00005426 13.3487605,2.00015005 18,2 C20.7551411,2 22,6.05643086 22,12 C22,13.6824804 20.8695981,15 19,15 L15.9269768,15 C15.9359266,15.0245465 15.9451954,15.0497804 15.9547911,15.0757271 C16.007193,15.2174219 16.2391583,15.8256341 16.2970775,15.9810953 C16.4872151,16.4914441 16.6259612,16.9026411 16.7382242,17.3098712 C16.9079007,17.9253665 17,18.4798886 17,19 C17,20.4720069 16.091867,21.3862822 14.748281,21.777514 C14.1422801,21.9539723 13.6147967,22.0000922 13.0076976,22.0000008 L12.5204954,22 L12.2202699,21.6261158 C11.2556275,20.4248034 7.64562469,16.4822788 6.57086468,14.9173453 Z M8,13 C8,13.2401953 8.04443154,13.4528921 8.14171093,13.6800176 C8.40663864,14.2985643 11.914268,18.1371493 13.4599624,19.9848695 C13.7113931,19.9660111 13.9483736,19.9273712 14.1891338,19.8572655 C14.7621788,19.6904035 15,19.4509737 15,19 C15,18.6834183 14.9359344,18.2976852 14.8101464,17.8413935 C14.7161494,17.500423 14.5944107,17.1396301 14.4229225,16.6793379 C14.3689242,16.5344009 14.1358033,15.923159 14.0789589,15.7694517 C13.9489218,15.4178313 13.8632547,15.1589343 13.8046536,14.9236885 C13.5555377,13.9236468 13.8054549,13 15,13 L19,13 C19.6912225,13 20,12.6401099 20,12 C20,7.20925475 19.015127,4 18,4 C15.9322103,4 15.9322103,4 10.9655994,3.99940813 C10.5253746,3.99154158 9.91062406,4.05963657 9.33687634,4.2649175 C8.45196659,4.58152894 8,5.09776992 8,6 L8,13 Z M4,4 L4,13 L6,13 L6,4 L4,4 Z"})}));var h0=b(R()),EP=e=>(0,h0.jsx)("svg",P(w({width:"16",height:"16",fill:"#000000"},e),{viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:(0,h0.jsx)("path",{fillRule:"evenodd",d:"M7.65336736,21.1256786 C7.2933164,21.6534897 6.68712411,22 6,22 L4,22 C2.8954305,22 2,21.1045695 2,20 L2,11 C2,9.8954305 2.8954305,9 4,9 L6,9 C6.198171,9 6.38961023,9.02882212 6.57035446,9.08250314 C7.6444817,7.51807482 11.2554748,3.57449216 12.2202699,2.37298955 L12.5204954,1.99910538 L13,1.99910538 C13.6147967,1.99901314 14.1422801,2.04513312 14.748281,2.22159137 C16.091867,2.61282321 17,3.52709845 17,4.99910538 C17,5.51921677 16.9079007,6.07373891 16.7382242,6.68923415 C16.6259612,7.09646424 16.4872151,7.50766133 16.2970775,8.01801005 C16.2391583,8.17347129 16.007193,8.78168345 15.9547911,8.92337824 C15.9451954,8.94932503 15.9359266,8.9745589 15.9269768,8.99910538 L19,8.99910538 C20.8695981,8.99910538 22,10.316625 22,11.9991054 C22,17.9426745 20.7551411,21.9991054 18,21.9991054 L11.0344006,21.9985135 C10.3408482,22.0111947 9.50544052,21.9186578 8.66312366,21.6172857 C8.29521907,21.4856533 7.9567386,21.3218904 7.65336736,21.1256786 Z M8,17.9991054 C8,18.9013355 8.45196659,19.4175764 9.33687634,19.7341879 C9.91062406,19.9394688 10.5253746,20.0075638 10.963066,19.9997143 C10.9703499,19.9995545 10.9703499,19.9995545 11,19.9991054 L18,19.9991054 C19.015127,19.9991054 20,16.7898506 20,11.9991054 C20,11.3589955 19.6912225,10.9991054 19,10.9991054 L15,10.9991054 C13.8054549,10.9991054 13.5555377,10.0754586 13.8046536,9.07541689 C13.8632547,8.84017106 13.9489218,8.5812741 14.0789589,8.22965366 C14.1358033,8.07594642 14.3689242,7.46470447 14.4229225,7.31976744 C14.5944107,6.85947528 14.7161494,6.4986824 14.8101464,6.1577119 C14.9359344,5.70142019 15,5.31568707 15,4.99910538 C15,4.54813166 14.7621788,4.30870189 14.1891338,4.1418399 C13.9483736,4.07173418 13.7113931,4.0330943 13.4599624,4.01423587 C11.914268,5.86195611 8.40663864,9.70054105 8.14171093,10.3190878 C8.04443154,10.5462133 8,10.7589101 8,10.9991054 L8,17.9991054 Z M4,11 L4,20 L6,20 L6,11 L4,11 Z"})}));function La(e,t){var o;let n=e.cloneNode(!0);n.style.top=`${e.offsetTop}px`,n.style.left=`${e.offsetLeft}px`,n.style.position="absolute",t.split(" ").forEach(s=>{n.classList.add(s)}),n.addEventListener("animationend",()=>n.remove()),(o=e.parentElement)==null||o.appendChild(n)}var y0={};xt(y0,{enUS:()=>W4,nlNL:()=>K4});var W4={thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}]},K4={thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}]};var TP={thumbs:"dd-5F1zq",fadeup:"dd-eTmY-",fadedown:"dd-sS85z",selected:"dd-rid-f",thumbsUp:"dd-4poEf",thumbsDown:"dd-3KozS"};var ho=b(R()),G4=({eventName:e,eventData:t,evaluationId:n,feedbackType:r,feedbackText:o})=>{let s=D("FeedbackThumbs",TP),i=te("enableFeedbackForm"),a=K(kr),l=K(ba(`/admin/feedback?conversationId=${a}&evaluationId=${n}&type=${r}&text=${o}&data=${JSON.stringify(t)}`)),c=ae(y0),u=Ct(),[f,d]=(0,CP.useState)(null),p=m=>{m.stopPropagation(),La(m.target,s.fadeup),d("up"),u(e,P(w({},t),{evaluationId:n,rating:"up"}))},h=m=>{m.stopPropagation(),La(m.target,s.fadedown),d("down"),u(e,P(w({},t),{evaluationId:n,rating:"down"}))};return(0,ho.jsxs)("div",{className:s.thumbs,children:[(0,ho.jsx)(de.Button,{title:c("thumbsUp"),onClick:p,icon:(0,ho.jsx)(EP,{}),className:(0,Jp.default)(s.thumbsUp,f==="up"&&s.selected),disabled:!!f}),i&&l?(0,ho.jsx)(de.Button,{as:"a",title:c("thumbsDown"),href:l,target:"_blank",rel:"noreferrer",onClick:h,icon:(0,ho.jsx)(g0,{}),className:(0,Jp.default)(s.thumbsDown,f==="down"&&s.selected),disabled:!!f}):(0,ho.jsx)(de.Button,{title:c("thumbsDown"),onClick:h,icon:(0,ho.jsx)(g0,{}),className:(0,Jp.default)(s.thumbsDown,f==="down"&&s.selected),disabled:!!f})]})},Zc=G4;var{entries:_P,setPrototypeOf:kP,isFrozen:q4,getPrototypeOf:Y4,getOwnPropertyDescriptor:X4}=Object,{freeze:Xt,seal:Hn,create:DP}=Object,{apply:E0,construct:T0}=typeof Reflect!="undefined"&&Reflect;Xt||(Xt=function(t){return t});Hn||(Hn=function(t){return t});E0||(E0=function(t,n,r){return t.apply(n,r)});T0||(T0=function(t,n){return new t(...n)});var em=Qt(Array.prototype.forEach),Q4=Qt(Array.prototype.lastIndexOf),RP=Qt(Array.prototype.pop),Jc=Qt(Array.prototype.push),Z4=Qt(Array.prototype.splice),nm=Qt(String.prototype.toLowerCase),v0=Qt(String.prototype.toString),PP=Qt(String.prototype.match),eu=Qt(String.prototype.replace),J4=Qt(String.prototype.indexOf),eF=Qt(String.prototype.trim),pr=Qt(Object.prototype.hasOwnProperty),Yt=Qt(RegExp.prototype.test),tu=tF(TypeError);function Qt(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);for(var n=arguments.length,r=new Array(n>1?n-1:0),o=1;o<n;o++)r[o-1]=arguments[o];return E0(e,t,r)}}function tF(e){return function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];return T0(e,n)}}function he(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:nm;kP&&kP(e,null);let r=t.length;for(;r--;){let o=t[r];if(typeof o=="string"){let s=n(o);s!==o&&(q4(t)||(t[r]=s),o=s)}e[o]=!0}return e}function nF(e){for(let t=0;t<e.length;t++)pr(e,t)||(e[t]=null);return e}function ii(e){let t=DP(null);for(let[n,r]of _P(e))pr(e,n)&&(Array.isArray(r)?t[n]=nF(r):r&&typeof r=="object"&&r.constructor===Object?t[n]=ii(r):t[n]=r);return t}function nu(e,t){for(;e!==null;){let r=X4(e,t);if(r){if(r.get)return Qt(r.get);if(typeof r.value=="function")return Qt(r.value)}e=Y4(e)}function n(){return null}return n}var IP=Xt(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","section","select","shadow","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),x0=Xt(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","filter","font","g","glyph","glyphref","hkern","image","line","lineargradient","marker","mask","metadata","mpath","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),S0=Xt(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),rF=Xt(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),w0=Xt(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),oF=Xt(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),AP=Xt(["#text"]),LP=Xt(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","face","for","headers","height","hidden","high","href","hreflang","id","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),b0=Xt(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),MP=Xt(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),tm=Xt(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),sF=Hn(/\{\{[\w\W]*|[\w\W]*\}\}/gm),iF=Hn(/<%[\w\W]*|[\w\W]*%>/gm),aF=Hn(/\$\{[\w\W]*/gm),lF=Hn(/^data-[\-\w.\u00B7-\uFFFF]+$/),cF=Hn(/^aria-[\-\w]+$/),FP=Hn(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),uF=Hn(/^(?:\w+script|data):/i),dF=Hn(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),zP=Hn(/^html$/i),fF=Hn(/^[a-z][.\w]*(-[.\w]+)+$/i),OP=Object.freeze({__proto__:null,ARIA_ATTR:cF,ATTR_WHITESPACE:dF,CUSTOM_ELEMENT:fF,DATA_ATTR:lF,DOCTYPE_NAME:zP,ERB_EXPR:iF,IS_ALLOWED_URI:FP,IS_SCRIPT_OR_DATA:uF,MUSTACHE_EXPR:sF,TMPLIT_EXPR:aF}),ru={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,progressingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},pF=function(){return typeof window=="undefined"?null:window},mF=function(t,n){if(typeof t!="object"||typeof t.createPolicy!="function")return null;let r=null,o="data-tt-policy-suffix";n&&n.hasAttribute(o)&&(r=n.getAttribute(o));let s="dompurify"+(r?"#"+r:"");try{return t.createPolicy(s,{createHTML(i){return i},createScriptURL(i){return i}})}catch(i){return console.warn("TrustedTypes policy "+s+" could not be created."),null}},NP=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function HP(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:pF(),t=ne=>HP(ne);if(t.version="3.2.5",t.removed=[],!e||!e.document||e.document.nodeType!==ru.document||!e.Element)return t.isSupported=!1,t;let{document:n}=e,r=n,o=r.currentScript,{DocumentFragment:s,HTMLTemplateElement:i,Node:a,Element:l,NodeFilter:c,NamedNodeMap:u=e.NamedNodeMap||e.MozNamedAttrMap,HTMLFormElement:f,DOMParser:d,trustedTypes:p}=e,h=l.prototype,m=nu(h,"cloneNode"),x=nu(h,"remove"),v=nu(h,"nextSibling"),y=nu(h,"childNodes"),g=nu(h,"parentNode");if(typeof i=="function"){let ne=n.createElement("template");ne.content&&ne.content.ownerDocument&&(n=ne.content.ownerDocument)}let S,E="",{implementation:k,createNodeIterator:C,createDocumentFragment:I,getElementsByTagName:$}=n,{importNode:_}=r,L=NP();t.isSupported=typeof _P=="function"&&typeof g=="function"&&k&&k.createHTMLDocument!==void 0;let{MUSTACHE_EXPR:Q,ERB_EXPR:Z,TMPLIT_EXPR:N,DATA_ATTR:z,ARIA_ATTR:B,IS_SCRIPT_OR_DATA:j,ATTR_WHITESPACE:H,CUSTOM_ELEMENT:V}=OP,{IS_ALLOWED_URI:W}=OP,O=null,q=he({},[...IP,...x0,...S0,...w0,...AP]),ce=null,Ge=he({},[...LP,...b0,...MP,...tm]),pe=Object.seal(DP(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),Pe=null,De=null,xe=!0,be=!0,rt=!1,oe=!0,X=!1,se=!0,ue=!1,$e=!1,yt=!1,Xe=!1,He=!1,Qe=!1,ct=!0,ds=!1,fs="user-content-",Zt=!0,hr=!1,zr={},mi=null,W0=he({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]),K0=null,G0=he({},["audio","video","img","source","image","track"]),xm=null,q0=he({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),pu="http://www.w3.org/1998/Math/MathML",mu="http://www.w3.org/2000/svg",Hr="http://www.w3.org/1999/xhtml",gi=Hr,Sm=!1,wm=null,KI=he({},[pu,mu,Hr],v0),gu=he({},["mi","mo","mn","ms","mtext"]),hu=he({},["annotation-xml"]),GI=he({},["title","style","font","a","script"]),Ba=null,qI=["application/xhtml+xml","text/html"],YI="text/html",ut=null,hi=null,XI=n.createElement("form"),Y0=function(T){return T instanceof RegExp||T instanceof Function},bm=function(){let T=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(hi&&hi===T)){if((!T||typeof T!="object")&&(T={}),T=ii(T),Ba=qI.indexOf(T.PARSER_MEDIA_TYPE)===-1?YI:T.PARSER_MEDIA_TYPE,ut=Ba==="application/xhtml+xml"?v0:nm,O=pr(T,"ALLOWED_TAGS")?he({},T.ALLOWED_TAGS,ut):q,ce=pr(T,"ALLOWED_ATTR")?he({},T.ALLOWED_ATTR,ut):Ge,wm=pr(T,"ALLOWED_NAMESPACES")?he({},T.ALLOWED_NAMESPACES,v0):KI,xm=pr(T,"ADD_URI_SAFE_ATTR")?he(ii(q0),T.ADD_URI_SAFE_ATTR,ut):q0,K0=pr(T,"ADD_DATA_URI_TAGS")?he(ii(G0),T.ADD_DATA_URI_TAGS,ut):G0,mi=pr(T,"FORBID_CONTENTS")?he({},T.FORBID_CONTENTS,ut):W0,Pe=pr(T,"FORBID_TAGS")?he({},T.FORBID_TAGS,ut):{},De=pr(T,"FORBID_ATTR")?he({},T.FORBID_ATTR,ut):{},zr=pr(T,"USE_PROFILES")?T.USE_PROFILES:!1,xe=T.ALLOW_ARIA_ATTR!==!1,be=T.ALLOW_DATA_ATTR!==!1,rt=T.ALLOW_UNKNOWN_PROTOCOLS||!1,oe=T.ALLOW_SELF_CLOSE_IN_ATTR!==!1,X=T.SAFE_FOR_TEMPLATES||!1,se=T.SAFE_FOR_XML!==!1,ue=T.WHOLE_DOCUMENT||!1,Xe=T.RETURN_DOM||!1,He=T.RETURN_DOM_FRAGMENT||!1,Qe=T.RETURN_TRUSTED_TYPE||!1,yt=T.FORCE_BODY||!1,ct=T.SANITIZE_DOM!==!1,ds=T.SANITIZE_NAMED_PROPS||!1,Zt=T.KEEP_CONTENT!==!1,hr=T.IN_PLACE||!1,W=T.ALLOWED_URI_REGEXP||FP,gi=T.NAMESPACE||Hr,gu=T.MATHML_TEXT_INTEGRATION_POINTS||gu,hu=T.HTML_INTEGRATION_POINTS||hu,pe=T.CUSTOM_ELEMENT_HANDLING||{},T.CUSTOM_ELEMENT_HANDLING&&Y0(T.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(pe.tagNameCheck=T.CUSTOM_ELEMENT_HANDLING.tagNameCheck),T.CUSTOM_ELEMENT_HANDLING&&Y0(T.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(pe.attributeNameCheck=T.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),T.CUSTOM_ELEMENT_HANDLING&&typeof T.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(pe.allowCustomizedBuiltInElements=T.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),X&&(be=!1),He&&(Xe=!0),zr&&(O=he({},AP),ce=[],zr.html===!0&&(he(O,IP),he(ce,LP)),zr.svg===!0&&(he(O,x0),he(ce,b0),he(ce,tm)),zr.svgFilters===!0&&(he(O,S0),he(ce,b0),he(ce,tm)),zr.mathMl===!0&&(he(O,w0),he(ce,MP),he(ce,tm))),T.ADD_TAGS&&(O===q&&(O=ii(O)),he(O,T.ADD_TAGS,ut)),T.ADD_ATTR&&(ce===Ge&&(ce=ii(ce)),he(ce,T.ADD_ATTR,ut)),T.ADD_URI_SAFE_ATTR&&he(xm,T.ADD_URI_SAFE_ATTR,ut),T.FORBID_CONTENTS&&(mi===W0&&(mi=ii(mi)),he(mi,T.FORBID_CONTENTS,ut)),Zt&&(O["#text"]=!0),ue&&he(O,["html","head","body"]),O.table&&(he(O,["tbody"]),delete Pe.tbody),T.TRUSTED_TYPES_POLICY){if(typeof T.TRUSTED_TYPES_POLICY.createHTML!="function")throw tu('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof T.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw tu('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');S=T.TRUSTED_TYPES_POLICY,E=S.createHTML("")}else S===void 0&&(S=mF(p,o)),S!==null&&typeof E=="string"&&(E=S.createHTML(""));Xt&&Xt(T),hi=T}},X0=he({},[...x0,...S0,...rF]),Q0=he({},[...w0,...oF]),QI=function(T){let U=g(T);(!U||!U.tagName)&&(U={namespaceURI:gi,tagName:"template"});let J=nm(T.tagName),Be=nm(U.tagName);return wm[T.namespaceURI]?T.namespaceURI===mu?U.namespaceURI===Hr?J==="svg":U.namespaceURI===pu?J==="svg"&&(Be==="annotation-xml"||gu[Be]):!!X0[J]:T.namespaceURI===pu?U.namespaceURI===Hr?J==="math":U.namespaceURI===mu?J==="math"&&hu[Be]:!!Q0[J]:T.namespaceURI===Hr?U.namespaceURI===mu&&!hu[Be]||U.namespaceURI===pu&&!gu[Be]?!1:!Q0[J]&&(GI[J]||!X0[J]):!!(Ba==="application/xhtml+xml"&&wm[T.namespaceURI]):!1},yr=function(T){Jc(t.removed,{element:T});try{g(T).removeChild(T)}catch(U){x(T)}},yu=function(T,U){try{Jc(t.removed,{attribute:U.getAttributeNode(T),from:U})}catch(J){Jc(t.removed,{attribute:null,from:U})}if(U.removeAttribute(T),T==="is")if(Xe||He)try{yr(U)}catch(J){}else try{U.setAttribute(T,"")}catch(J){}},Z0=function(T){let U=null,J=null;if(yt)T="<remove></remove>"+T;else{let vt=PP(T,/^[\r\n\t ]+/);J=vt&&vt[0]}Ba==="application/xhtml+xml"&&gi===Hr&&(T='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+T+"</body></html>");let Be=S?S.createHTML(T):T;if(gi===Hr)try{U=new d().parseFromString(Be,Ba)}catch(vt){}if(!U||!U.documentElement){U=k.createDocument(gi,"template",null);try{U.documentElement.innerHTML=Sm?E:Be}catch(vt){}}let kt=U.body||U.documentElement;return T&&J&&kt.insertBefore(n.createTextNode(J),kt.childNodes[0]||null),gi===Hr?$.call(U,ue?"html":"body")[0]:ue?U.documentElement:kt},J0=function(T){return C.call(T.ownerDocument||T,T,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT|c.SHOW_PROCESSING_INSTRUCTION|c.SHOW_CDATA_SECTION,null)},Em=function(T){return T instanceof f&&(typeof T.nodeName!="string"||typeof T.textContent!="string"||typeof T.removeChild!="function"||!(T.attributes instanceof u)||typeof T.removeAttribute!="function"||typeof T.setAttribute!="function"||typeof T.namespaceURI!="string"||typeof T.insertBefore!="function"||typeof T.hasChildNodes!="function")},ex=function(T){return typeof a=="function"&&T instanceof a};function Br(ne,T,U){em(ne,J=>{J.call(t,T,U,hi)})}let tx=function(T){let U=null;if(Br(L.beforeSanitizeElements,T,null),Em(T))return yr(T),!0;let J=ut(T.nodeName);if(Br(L.uponSanitizeElement,T,{tagName:J,allowedTags:O}),T.hasChildNodes()&&!ex(T.firstElementChild)&&Yt(/<[/\w!]/g,T.innerHTML)&&Yt(/<[/\w!]/g,T.textContent)||T.nodeType===ru.progressingInstruction||se&&T.nodeType===ru.comment&&Yt(/<[/\w]/g,T.data))return yr(T),!0;if(!O[J]||Pe[J]){if(!Pe[J]&&rx(J)&&(pe.tagNameCheck instanceof RegExp&&Yt(pe.tagNameCheck,J)||pe.tagNameCheck instanceof Function&&pe.tagNameCheck(J)))return!1;if(Zt&&!mi[J]){let Be=g(T)||T.parentNode,kt=y(T)||T.childNodes;if(kt&&Be){let vt=kt.length;for(let Jt=vt-1;Jt>=0;--Jt){let vr=m(kt[Jt],!0);vr.__removalCount=(T.__removalCount||0)+1,Be.insertBefore(vr,v(T))}}}return yr(T),!0}return T instanceof l&&!QI(T)||(J==="noscript"||J==="noembed"||J==="noframes")&&Yt(/<\/no(script|embed|frames)/i,T.innerHTML)?(yr(T),!0):(X&&T.nodeType===ru.text&&(U=T.textContent,em([Q,Z,N],Be=>{U=eu(U,Be," ")}),T.textContent!==U&&(Jc(t.removed,{element:T.cloneNode()}),T.textContent=U)),Br(L.afterSanitizeElements,T,null),!1)},nx=function(T,U,J){if(ct&&(U==="id"||U==="name")&&(J in n||J in XI))return!1;if(!(be&&!De[U]&&Yt(z,U))){if(!(xe&&Yt(B,U))){if(!ce[U]||De[U]){if(!(rx(T)&&(pe.tagNameCheck instanceof RegExp&&Yt(pe.tagNameCheck,T)||pe.tagNameCheck instanceof Function&&pe.tagNameCheck(T))&&(pe.attributeNameCheck instanceof RegExp&&Yt(pe.attributeNameCheck,U)||pe.attributeNameCheck instanceof Function&&pe.attributeNameCheck(U))||U==="is"&&pe.allowCustomizedBuiltInElements&&(pe.tagNameCheck instanceof RegExp&&Yt(pe.tagNameCheck,J)||pe.tagNameCheck instanceof Function&&pe.tagNameCheck(J))))return!1}else if(!xm[U]){if(!Yt(W,eu(J,H,""))){if(!((U==="src"||U==="xlink:href"||U==="href")&&T!=="script"&&J4(J,"data:")===0&&K0[T])){if(!(rt&&!Yt(j,eu(J,H,"")))){if(J)return!1}}}}}}return!0},rx=function(T){return T!=="annotation-xml"&&PP(T,V)},ox=function(T){Br(L.beforeSanitizeAttributes,T,null);let{attributes:U}=T;if(!U||Em(T))return;let J={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:ce,forceKeepAttr:void 0},Be=U.length;for(;Be--;){let kt=U[Be],{name:vt,namespaceURI:Jt,value:vr}=kt,Ua=ut(vt),_t=vt==="value"?vr:eF(vr);if(J.attrName=Ua,J.attrValue=_t,J.keepAttr=!0,J.forceKeepAttr=void 0,Br(L.uponSanitizeAttribute,T,J),_t=J.attrValue,ds&&(Ua==="id"||Ua==="name")&&(yu(vt,T),_t=fs+_t),se&&Yt(/((--!?|])>)|<\/(style|title)/i,_t)){yu(vt,T);continue}if(J.forceKeepAttr||(yu(vt,T),!J.keepAttr))continue;if(!oe&&Yt(/\/>/i,_t)){yu(vt,T);continue}X&&em([Q,Z,N],ix=>{_t=eu(_t,ix," ")});let sx=ut(T.nodeName);if(nx(sx,Ua,_t)){if(S&&typeof p=="object"&&typeof p.getAttributeType=="function"&&!Jt)switch(p.getAttributeType(sx,Ua)){case"TrustedHTML":{_t=S.createHTML(_t);break}case"TrustedScriptURL":{_t=S.createScriptURL(_t);break}}try{Jt?T.setAttributeNS(Jt,vt,_t):T.setAttribute(vt,_t),Em(T)?yr(T):RP(t.removed)}catch(ix){}}}Br(L.afterSanitizeAttributes,T,null)},ZI=function ne(T){let U=null,J=J0(T);for(Br(L.beforeSanitizeShadowDOM,T,null);U=J.nextNode();)Br(L.uponSanitizeShadowNode,U,null),tx(U),ox(U),U.content instanceof s&&ne(U.content);Br(L.afterSanitizeShadowDOM,T,null)};return t.sanitize=function(ne){let T=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},U=null,J=null,Be=null,kt=null;if(Sm=!ne,Sm&&(ne="<!-->"),typeof ne!="string"&&!ex(ne))if(typeof ne.toString=="function"){if(ne=ne.toString(),typeof ne!="string")throw tu("dirty is not a string, aborting")}else throw tu("toString is not a function");if(!t.isSupported)return ne;if($e||bm(T),t.removed=[],typeof ne=="string"&&(hr=!1),hr){if(ne.nodeName){let vr=ut(ne.nodeName);if(!O[vr]||Pe[vr])throw tu("root node is forbidden and cannot be sanitized in-place")}}else if(ne instanceof a)U=Z0("<!---->"),J=U.ownerDocument.importNode(ne,!0),J.nodeType===ru.element&&J.nodeName==="BODY"||J.nodeName==="HTML"?U=J:U.appendChild(J);else{if(!Xe&&!X&&!ue&&ne.indexOf("<")===-1)return S&&Qe?S.createHTML(ne):ne;if(U=Z0(ne),!U)return Xe?null:Qe?E:""}U&&yt&&yr(U.firstChild);let vt=J0(hr?ne:U);for(;Be=vt.nextNode();)tx(Be),ox(Be),Be.content instanceof s&&ZI(Be.content);if(hr)return ne;if(Xe){if(He)for(kt=I.call(U.ownerDocument);U.firstChild;)kt.appendChild(U.firstChild);else kt=U;return(ce.shadowroot||ce.shadowrootmode)&&(kt=_.call(r,kt,!0)),kt}let Jt=ue?U.outerHTML:U.innerHTML;return ue&&O["!doctype"]&&U.ownerDocument&&U.ownerDocument.doctype&&U.ownerDocument.doctype.name&&Yt(zP,U.ownerDocument.doctype.name)&&(Jt="<!DOCTYPE "+U.ownerDocument.doctype.name+`>
79
79
  `+Jt),X&&em([Q,Z,N],vr=>{Jt=eu(Jt,vr," ")}),S&&Qe?S.createHTML(Jt):Jt},t.setConfig=function(){let ne=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};bm(ne),$e=!0},t.clearConfig=function(){hi=null,$e=!1},t.isValidAttribute=function(ne,T,U){hi||bm({});let J=ut(ne),Be=ut(T);return nx(J,Be,U)},t.addHook=function(ne,T){typeof T=="function"&&Jc(L[ne],T)},t.removeHook=function(ne,T){if(T!==void 0){let U=Q4(L[ne],T);return U===-1?void 0:Z4(L[ne],U,1)[0]}return RP(L[ne])},t.removeHooks=function(ne){L[ne]=[]},t.removeAllHooks=function(){L=NP()},t}var BP=HP();var yo=b(Y());var UP={root:"dd-L7b3z",popover:"dd-OQOTB",options:"dd-Y12RE",arrow:"dd-cv33T",copyIcon:"dd-6xOsH",option:"dd-9oFX4",divider:"dd-aiZf8",fadeup:"dd-Jq9pd"};var mr=b(R());function gF(e){return`<button type="button" data-copy-icon class=${e}><svg version="1.1" x="0px" y="0px" viewBox="0 0 115.77 122.88" width="10px" height="10px" fill="black"><g><path d="M89.62,13.96v7.73h12.19h0.01v0.02c3.85,0.01,7.34,1.57,9.86,4.1c2.5,2.51,4.06,5.98,4.07,9.82h0.02v0.02 v73.27v0.01h-0.02c-0.01,3.84-1.57,7.33-4.1,9.86c-2.51,2.5-5.98,4.06-9.82,4.07v0.02h-0.02h-61.7H40.1v-0.02 c-3.84-0.01-7.34-1.57-9.86-4.1c-2.5-2.51-4.06-5.98-4.07-9.82h-0.02v-0.02V92.51H13.96h-0.01v-0.02c-3.84-0.01-7.34-1.57-9.86-4.1 c-2.5-2.51-4.06-5.98-4.07-9.82H0v-0.02V13.96v-0.01h0.02c0.01-3.85,1.58-7.34,4.1-9.86c2.51-2.5,5.98-4.06,9.82-4.07V0h0.02h61.7 h0.01v0.02c3.85,0.01,7.34,1.57,9.86,4.1c2.5,2.51,4.06,5.98,4.07,9.82h0.02V13.96L89.62,13.96z M79.04,21.69v-7.73v-0.02h0.02 c0-0.91-0.39-1.75-1.01-2.37c-0.61-0.61-1.46-1-2.37-1v0.02h-0.01h-61.7h-0.02v-0.02c-0.91,0-1.75,0.39-2.37,1.01 c-0.61,0.61-1,1.46-1,2.37h0.02v0.01v64.59v0.02h-0.02c0,0.91,0.39,1.75,1.01,2.37c0.61,0.61,1.46,1,2.37,1v-0.02h0.01h12.19V35.65 v-0.01h0.02c0.01-3.85,1.58-7.34,4.1-9.86c2.51-2.5,5.98-4.06,9.82-4.07v-0.02h0.02H79.04L79.04,21.69z M105.18,108.92V35.65v-0.02 h0.02c0-0.91-0.39-1.75-1.01-2.37c-0.61-0.61-1.46-1-2.37-1v0.02h-0.01h-61.7h-0.02v-0.02c-0.91,0-1.75,0.39-2.37,1.01 c-0.61,0.61-1,1.46-1,2.37h0.02v0.01v73.27v0.02h-0.02c0,0.91,0.39,1.75,1.01,2.37c0.61,0.61,1.46,1,2.37,1v-0.02h0.01h61.7h0.02 v0.02c0.91,0,1.75-0.39,2.37-1.01c0.61-0.61,1-1.46,1-2.37h-0.02V108.92L105.18,108.92z"/></g></svg></button>`}function C0(e){var n,r;let t=e.cloneNode(!0);return t.querySelectorAll("div,button").forEach(o=>o.remove()),(r=(n=t.textContent)==null?void 0:n.trim())!=null?r:""}function hF(e){return e.replace(/\r\n/g,`
80
80
  `)}var yF=({content:e,useLabel:t,copyLabel:n,onCopy:r,onUse:o})=>{let s=D("Markdown",UP),i=(0,yo.useRef)(null),[a,l]=(0,yo.useState)(null),c=(0,yo.useMemo)(()=>{let m=Ce.parse(hF(e));return BP.sanitize(m.toString()).replaceAll("</code>",`${gF(s.copyIcon)}</code>`).replaceAll('<a href="','<a target="_blank" rel="noreferrer noopener" href="')},[e]),u=m=>{var y;let x=m.target,v=!!((y=i.current)!=null&&y.querySelector("code"));if(["A","BUTTON"].includes(x.tagName)){l(null);return}a||v&&x.tagName!=="CODE"||!v&&x!==i.current||(x.addEventListener("mouseleave",()=>l(null),{once:!0}),l(x))},f=()=>{if(!a)return;l(null);let m=a.querySelector("button");m&&(La(m,s.fadeup),r==null||r(C0(a)))},d=m=>{let x=m.target;if(x.tagName==="A"){m.stopPropagation();return}"copyIcon"in x.dataset&&(La(x,s.fadeup),r==null||r(C0(x.parentElement)))},p=()=>{!a||!o||(l(null),o(C0(a)))},h=m=>{if(m===null)return;let x=m.getBoundingClientRect();x.left<0?m.style.transform=`translateX(${-x.left+2}px)`:x.right>window.innerWidth&&(m.style.transform=`translateX(${window.innerWidth-x.right-2}px)`)};return(0,mr.jsxs)(yo.Fragment,{children:[a&&(r||o)&&(0,mr.jsxs)(Ra,{triggerRef:{current:a},className:s.popover,parentNode:a,children:[(0,mr.jsxs)("div",{className:s.options,ref:h,children:[r&&(0,mr.jsx)("button",{type:"button",className:s.option,onClick:f,children:n}),o&&(0,mr.jsxs)(yo.Fragment,{children:[(0,mr.jsx)("div",{className:s.divider}),(0,mr.jsx)("button",{type:"button",className:s.option,onClick:p,children:t})]})]}),(0,mr.jsx)("div",{className:s.arrow})]}),(0,mr.jsx)("div",{ref:i,"data-testid":"widget-markdown-content",className:s.root,dangerouslySetInnerHTML:{__html:c},onMouseOver:u,onClick:d})]})},ai=yF;var k0={title:"dd-YBHrC",fadeup:"dd-cRM0K",fadedown:"dd-7D4Pq",selected:"dd-bueui",actions:"dd-9Iqn9",thumbsUp:"dd-6QwVx",thumbsDown:"dd-d3E8l",form:"dd-sPNU2",formInput:"dd-F3E4I",formSubmit:"dd-vw5S0",actionButton:"dd-cCWyJ",editableCue:"dd-nWSD-",inputSpace:"dd-DGYB1"};var Ot=b(R()),vF=500,xF=100,SF=({content:e,onChange:t,onCopy:n})=>{let r=(0,li.useRef)(null),o=D("WidgetCue",k0);return(0,li.useEffect)(()=>{let s=r.current;if(!s)return;s.style.setProperty("height","0px");let i=Math.min(Math.max(s.scrollHeight,xF),vF);s.style.setProperty("height",`${i}px`)},[e]),(0,Ot.jsx)("textarea",{ref:r,className:o.editableCue,onCopy:n,onChange:t,value:e})},wF=({cue:e,onCallToAction:t,onRemove:n,onCopy:r,onUse:o})=>{var m;let s=D("WidgetCue",k0),i=ae(Qc),a=Ct(),l=te("hasKeyboardInput"),[c,u]=(0,li.useState)(e.text),f=()=>{t&&t(c,e),n(e)},d=x=>{r&&r(x,e)},p=x=>{o&&o(x,e)},h=x=>{x.preventDefault(),x.stopPropagation(),n(e)};return(0,li.useEffect)(()=>{a("Assistant response displayed",{evaluationId:e.evaluationId,name:e.rule.name,description:e.rule.description,group:e.rule.label,cueText:e.text})},[]),(0,Ot.jsxs)(de,{"data-testid":"cue",children:[(0,Ot.jsx)(ve,{children:(0,Ot.jsxs)(ve.Content,{children:[e.title&&(0,Ot.jsx)(ve.Title,{className:s.title,"data-testid":"widget-cue-title",children:e.rule.label.startsWith("__")?i(e.rule.label):e.title}),e.specialType==="summary"||e.editable?(0,Ot.jsx)(SF,{content:c,onCopy:()=>{let x=document.getSelection();x&&d(x.toString())},onChange:x=>{var v;return u((v=x.target.value)!=null?v:"")}}):(0,Ot.jsx)(ai,{content:e.text,useLabel:i("useCue"),copyLabel:i("copyCue"),onCopy:d,onUse:l?p:void 0})]})}),(0,Ot.jsxs)(de.ButtonsContainer,{children:[(0,Ot.jsxs)("div",{className:s.actions,children:[(e.specialType==="summary"||e.editable)&&(0,Ot.jsx)(de.Button,{onClick:()=>d(c),children:i("copyCue")}),e.callToAction&&(0,Ot.jsx)(de.Button,{onClick:f,children:e.callToAction.label}),(0,Ot.jsx)(de.Button,{onClick:h,children:i("removeCue")})]}),e.specialType==="summary"?(0,Ot.jsx)(Zc,{eventName:"summary feedback",evaluationId:e.evaluationId,feedbackText:(m=e.text)!=null?m:"",feedbackType:"summary",eventData:{summary:e.text}}):(0,Ot.jsx)(Zc,{eventName:"Assistant response feedback",evaluationId:e.evaluationId,eventData:{name:e.rule.name,group:e.rule.label,description:e.rule.description,cueText:e.text},feedbackText:e.text,feedbackType:"assistant"})]})]})},VP=wF;var Ma=b(R()),bF=({cues:e})=>{let t=ge(),n=cn(),r=ae(Qc),o=Ct(),s=c=>{t(Yp({code:c.rule.label})),o("Assistant response closed",{evaluationId:c.evaluationId,name:c.rule.name,group:c.rule.label,description:c.rule.description,cueText:c.text})},i=(c,u)=>{switch(Rr(c),u.specialType){case"summary":o("summary copied to clipboard",{originalText:u.text,finalText:c,assistant:u.rule.label});break;default:o("Assistant response copied",{evaluationId:u.evaluationId,name:u.rule.name,group:u.rule.label,description:u.rule.description,copiedText:c,originalText:u.text})}},a=(c,u)=>{var f;u.callToAction&&(t(qp(u)),o("Assistant call to action",{evaluationId:u.evaluationId,name:u.rule.name,group:u.rule.label,description:u.rule.description,eventName:u.callToAction.event,value:(f=u.callToAction.value)!=null?f:c,originalText:u.text}))},l=(c,u)=>{var f;n.send(to,{text:c,suggestion:{source:"assistant",assistantCode:(f=u.rule)==null?void 0:f.label,sourceText:c}}),o("Assistant response used",{evaluationId:u.evaluationId,name:u.rule.name,group:u.rule.label,description:u.rule.description,usedText:c,originalText:u.text})};return(0,Ma.jsx)(Ma.Fragment,{children:e.map(c=>c.isLoading?(0,Ma.jsx)(Zp,{title:c.rule.label.startsWith("__")?r(c.rule.label):c.title},c.rule.id):(0,Ma.jsx)(VP,{cue:c,onCallToAction:a,onRemove:s,onCopy:i,onUse:l},c.evaluationId))})},$P=bF;var rm=b(Y());var jP={root:"dd-cvTAY",label:"dd-QWQxD",value:"dd-WSUHF",copyButton:"dd-67o9H",copyButtonText:"dd-oos-l",isTrue:"dd--1g2O",isFalse:"dd-sz2ir"};var gr=b(R());function EF(e,t){return t.split(".").reduce((n,r)=>!n||typeof n!="object"||!(r in n)?null:n[r],e)}var WP=({data:e,schema:t})=>{let n=D("WidgetCustomData",jP),r=o=>{Rr(o)};return(0,rm.useEffect)(()=>{ee.info("Custom data",e,t)},[e]),(0,gr.jsx)("dl",{className:n.root,children:t.map(o=>{let s=EF(e,o.path);return(0,gr.jsxs)(rm.Fragment,{children:[(0,gr.jsx)("dt",{className:n.label,children:o.label}),(0,gr.jsx)("dd",{className:n.value,children:o.type==="boolean"&&s?(0,gr.jsx)("span",{className:n.isTrue,children:o.trueValue}):o.type==="boolean"&&!s?(0,gr.jsx)("span",{className:n.isFalse,children:o.falseValue}):typeof s=="string"||typeof s=="number"?(0,gr.jsxs)("button",{type:"button",onClick:()=>r(`${s}`),className:n.copyButton,children:[(0,gr.jsx)("span",{className:n.copyButtonText,children:s}),(0,gr.jsx)(qc,{})]}):"-"})]},o.label)})})};var Je=b(Y());var Oa={};xt(Oa,{enUS:()=>TF,nlNL:()=>CF});var TF={inputPlaceholder:[{type:0,value:"What is your question?"}],useCue:[{type:0,value:"Add to message"}],copyCue:[{type:0,value:"Copy"}],removeCue:[{type:0,value:"Close"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}],submitLabel:[{type:0,value:"Submit"}],resetLabel:[{type:0,value:"Reset"}],showMore:[{type:0,value:"Show "},{type:1,value:"amount"},{type:0,value:" more"}]},CF={inputPlaceholder:[{type:0,value:"Wat is je vraag?"}],useCue:[{type:0,value:"Voeg toe aan bericht"}],copyCue:[{type:0,value:"Kopi\xEBren"}],removeCue:[{type:0,value:"Sluiten"}],thumbsUp:[{type:0,value:"Thumbs up"}],thumbsDown:[{type:0,value:"Thumbs down"}],submitLabel:[{type:0,value:"Verzend"}],resetLabel:[{type:0,value:"Gesprek wissen"}],showMore:[{type:0,value:"Toon "},{type:1,value:"amount"},{type:0,value:" meer"}]};var om={form:"dd-pleCH",formInput:"dd-pGJMY",formSubmit:"dd--gkRg",actionButton:"dd-I2NEH",resetContainer:"dd-qKIDX",sources:"dd-xf9c6",source:"dd-a-vyX",tooltip:"dd-EsgcZ",linkContent:"dd-gARDA",showMoreSources:"dd-uDGi-"};var GP=b(Y());var KP={error:"dd-CoAuB"};var R0={};xt(R0,{enUS:()=>kF,nlNL:()=>RF});var kF={errorPrefix:[{type:0,value:"Error:"}]},RF={errorPrefix:[{type:0,value:"Foutmelding:"}]};var ou=b(R()),qP=({message:e})=>{let t=(0,GP.useRef)(null),n=D("WidgetCardError",KP),r=ae(R0);return Iu(t),(0,ou.jsx)(de,{ref:t,children:(0,ou.jsx)(ve,{children:(0,ou.jsxs)(ve.Content,{className:n.error,children:[r("errorPrefix")," ",e]})})})};var ye=b(R()),PF=3,IF=({sources:e,onClick:t})=>{let n=ae(Oa),r=D("WidgetKnowledgeAssistant",om),[o,s]=(0,Je.useState)(!1),i=o?e:e.slice(0,PF);return i.length===0?null:(0,ye.jsxs)("ul",{className:r.sources,children:[i.map(a=>(0,ye.jsx)("li",{className:r.source,"data-testid":"knowledge-assist-source",children:(0,ye.jsxs)(gt,{tooltip:!0,placement:"top-start",children:[(0,ye.jsx)(gt.Trigger,{as:"a",rel:"noreferrer",target:"_blank",href:a.url,onClick:l=>{l.stopPropagation(),t(a)},children:(0,ye.jsx)("span",{className:r.linkContent,children:a.name})}),a.url&&(0,ye.jsx)(gt.Content,{className:r.tooltip,children:decodeURIComponent(a.url)})]})},a.name)),i<e&&(0,ye.jsx)("button",{type:"button",className:r.showMoreSources,onClick:()=>s(!0),children:n("showMore",{amount:e.length-i.length})})]})},AF=({title:e,description:t})=>(0,ye.jsx)(de,{"data-testid":"knowledge-assist-empty-state",children:(0,ye.jsx)(ve,{children:(0,ye.jsxs)(ve.Content,{children:[(0,ye.jsx)(ve.Title,{children:e}),(0,ye.jsx)(ai,{content:t})]})})}),LF=({innerRef:e,item:t,hasKeyboardInput:n,onCopy:r,onUse:o,onSourceClick:s})=>{var l;let i=ae(Oa),a=(0,Je.useContext)(sm);return(0,ye.jsxs)(de,{"data-testid":"knowledge-assist-answer",ref:e,children:[(0,ye.jsx)(ve,{children:(0,ye.jsxs)(ve.Content,{children:[(0,ye.jsx)(ve.Title,{children:t.question}),(0,ye.jsx)(ai,{content:t.answer.answer,useLabel:i("useCue"),copyLabel:i("copyCue"),onCopy:r,onUse:n?o:void 0}),(0,ye.jsx)(IF,{sources:(l=t.answer.sources)!=null?l:[],onClick:s})]})}),(0,ye.jsxs)(de.ButtonsContainer,{children:[(0,ye.jsx)("div",{}),(0,ye.jsx)(Zc,{evaluationId:t.evaluationId,eventName:"Assistant response feedback",feedbackType:"assistant",eventData:{group:a.assistantCode,cueText:t.answer.answer},feedbackText:t.answer.answer})]})]})},sm=(0,Je.createContext)(null),im=({assistantCode:e,evaluateKnowledgeAssistFn:t,initialQuestion:n,children:r})=>{let[o,s]=(0,Je.useState)(null),[i,a]=(0,Je.useState)(!1),[l,c]=(0,Je.useState)(null),[u,f]=(0,Je.useState)(!!n),[d,p]=(0,Je.useState)(null),h=ge(),m=Ct(),x=Yc(g=>{if(!e)throw new Error("No knowledge assistant was defined");return c(null),t({assistantCode:e,input:g,threadId:o,onNewThreadId(S){s(S)}})},{onSuccess(g){var S;m("Assistant response displayed",{evaluationId:g.evaluationId,group:e,cueText:g.answer.answer,input:g.question,sources:(S=g.answer.sources)!=null?S:[]}),f(!1)},onError(g){var S;c((S=g.message)!=null?S:"Unknown error")}}),v=g=>A(void 0,null,function*(){a(!0),p(g),yield x.call(g),a(!1),p(null)}),y={isEnabled:!!e,assistantCode:e,isSubmitting:i,threadId:o,pendingInput:d,errorMessage:l,onSubmit:v,onReset(){o&&h(tP(o)),c(null),s(null),e&&m("Assistant thread reset",{threadId:o!=null?o:void 0,assistantCode:e})}};return(0,Je.useEffect)(()=>{n&&y.isEnabled&&v(n)},[n]),(0,ye.jsx)(sm.Provider,{value:y,children:r})},am=()=>{let e=ae(Oa),t=D("WidgetKnowledgeAssistant",om),n=(0,Je.useContext)(sm),r=(0,Je.useRef)(null),[o,s]=(0,Je.useState)(""),i=l=>{s(l.target.value)},a=l=>{l.preventDefault(),n.onSubmit(o).then(()=>{var c;r.current&&((c=r.current)==null||c.focus(),s(""))})};return n.isEnabled?(0,ye.jsxs)("form",{className:t.form,onSubmit:a,children:[(0,ye.jsx)("input",{ref:r,className:t.formInput,placeholder:e("inputPlaceholder"),type:"text",disabled:n.isSubmitting,value:o,onChange:i}),(0,ye.jsx)("button",{type:"submit",disabled:n.isSubmitting||o==="",className:t.formSubmit,children:e("submitLabel")})]}):null},lm=({title:e,emptyState:t})=>{var h,m;let n=ae(Oa),r=Ct(),o=D("WidgetKnowledgeAssistant",om),s=(0,Je.useRef)(null),i=(0,Je.useContext)(sm),a=(m=K(i0((h=i.threadId)!=null?h:-1)))!=null?m:[],l=te("hasKeyboardInput"),c=cn(),u=(x,v)=>{Rr(x),i.assistantCode&&r("Assistant response copied",{group:i.assistantCode,copiedText:x,originalText:x,evaluationId:v.evaluationId})},f=(x,v)=>{i.assistantCode&&r("Assistant source clicked",{evaluationId:v.evaluationId,assistantCode:i.assistantCode,source:x})},d=x=>{x.preventDefault(),i.onReset()},p=(x,v)=>{c.send(to,{text:x,suggestion:{source:"assistant",sourceText:x}}),i.assistantCode&&r("Assistant response used",{group:i.assistantCode,usedText:x,originalText:x,evaluationId:v.evaluationId})};return!i.isEnabled||(a==null?void 0:a.length)===0&&!i.isSubmitting&&!t&&!i.errorMessage?null:(0,ye.jsxs)(Je.Fragment,{children:[(0,ye.jsx)(xr,{type:"knowledge",title:e,"data-testid":"knowledge",children:(0,ye.jsxs)(zt,{withDivider:!0,children:[t&&a.length===0&&!i.pendingInput&&(0,ye.jsx)(AF,w({},t)),a.map((x,v)=>(0,ye.jsx)(LF,{innerRef:v===a.length-1?s:void 0,item:x,hasKeyboardInput:l,onCopy:y=>u(y,x),onUse:y=>p(y,x),onSourceClick:y=>f(y,x)},`${x.question}_${x.answer}_${v}`)),i.pendingInput&&(0,ye.jsx)(Zp,{title:i.pendingInput}),i.errorMessage&&(0,ye.jsx)(qP,{message:i.errorMessage})]})}),a.length>0&&(0,ye.jsx)("div",{className:o.resetContainer,children:(0,ye.jsx)(de.Button,{disabled:i.threadId===null||i.isSubmitting,onClick:d,children:n("resetLabel")})})]})};var QP=b(Y());var MF=/(https?:\/\/[^\s]+)/,XP=e=>e.split(" ").find(t=>MF.test(t));var Bn=b(R()),OF=({suggestion:e,lines:t,onUse:n})=>{var f;let r=e.text||e.url||e.message,o=XP(r),s=ae(Ac),i=te("showImages"),a=te("fallbackImage"),l=te("hasKeyboardInput"),c=d=>{d.preventDefault(),d.stopPropagation(),l&&n(r)},u=(0,QP.useCallback)(d=>{window.open(o,"_blank"),d.stopPropagation(),d.preventDefault()},[o]);return(0,Bn.jsxs)(de,{onClick:l?c:void 0,"data-testid":"edit-suggestion",children:[(0,Bn.jsxs)(ve,{children:[i&&e.image&&(0,Bn.jsx)(ve.Image,{src:Bp(e,"small",a||void 0),title:e.title}),(0,Bn.jsxs)(ve.Content,{children:[e.title&&(0,Bn.jsx)(ve.Title,{"data-testid":"widget-suggestion-title",children:e.title}),e.searchKeywords&&((f=e.searchKeywords)==null?void 0:f.length)>0&&(0,Bn.jsx)(de.Labels,{labels:e.searchKeywords}),(0,Bn.jsx)(ve.Content,{cropText:t==="single",lineClamp:t==="multiple",children:r})]})]}),(0,Bn.jsxs)(de.Actions,{children:[o&&(0,Bn.jsx)(de.ActionButton,{onClick:u,label:s("visitUrl")}),l&&(0,Bn.jsx)(de.ActionButton,{primary:!0,onClick:c,label:s("useSuggestion")})]})]})},ZP=OF;var su=b(R()),NF=({lines:e,suggestions:t})=>{let n=cn(),r=(o,s)=>{n.send(to,{text:o,suggestion:P(w({},s),{source:s.source,sourceText:s.text})})};return(0,su.jsx)(su.Fragment,{children:t.map(o=>(0,su.jsx)(ZP,{suggestion:o,lines:e,onUse:s=>r(s,o)},o.text||o.url||o.message))})},JP=NF;var iu={};xt(iu,{enUS:()=>_F,nlNL:()=>DF});var _F={waiting:[{type:0,value:"Loading\u2026"}],waitingForConversation:[{type:0,value:"Waiting for conversation\u2026"}],notSupported:[{type:0,value:"This conversation is not supported"}],noResults:[{type:0,value:"No results found\u2026"}],titleCues:[{type:0,value:"Assistant updates"}],actions:[{type:0,value:"Shortcuts"}],linkStudioLogin:[{type:0,value:"My "},{type:1,value:"productName"}],linkSummary:[{type:0,value:"Summarize"}],linkKnowledgeSearch:[{type:0,value:"Knowledge Assist"}],linkSearch:[{type:0,value:"Search"}],close:[{type:0,value:"Close"}]},DF={waiting:[{type:0,value:"Laden\u2026"}],waitingForConversation:[{type:0,value:"Wachten op gesprek\u2026"}],notSupported:[{type:0,value:"Dit gesprek wordt niet ondersteund"}],noResults:[{type:0,value:"Geen resultaten gevonden\u2026"}],titleCues:[{type:0,value:"Assistant updates"}],actions:[{type:0,value:"Shortcuts"}],linkStudioLogin:[{type:0,value:"Mijn "},{type:1,value:"productName"}],linkSummary:[{type:0,value:"Gesprek samenvatten"}],linkKnowledgeSearch:[{type:0,value:"Knowledge assist"}],linkSearch:[{type:0,value:"Zoeken"}],close:[{type:0,value:"Sluiten"}]};var Na={root:"dd-W9VCG",loginText:"dd--dS6t",stateText:"dd-348OC",footer:"dd-tvofr",shortcutList:"dd-MuKK-",shortcut:"dd-5CnK9",footerShortcut:"dd-dH7XJ",link:"dd-DRo0x"};var le=b(R()),eI=(e,t)=>{let n=K(Tt);(0,as.useEffect)(()=>n?t.every(r=>!!r)?e():()=>{}:()=>{},[...t,n])},FF=({onLogIn:e})=>{let t=D("Widget",Na),n=te("isEmbedded"),r=te("adminUrl");return(0,le.jsx)("div",{className:t.loginText,children:(0,le.jsx)("div",{children:(0,le.jsx)(Rp,{isEmbedded:n,loginUrl:r,onLogIn:e})})},"login")},P0=({text:e})=>{let t=D("Widget",Na);return(0,le.jsx)("div",{className:t.stateText,children:(0,le.jsx)("div",{children:(0,le.jsx)("p",{children:e})})},"notification")},zF=()=>{let e=ae(iu),t=ge(),n=D("Widget",Na),r=te("showSearch"),o=te("isEmbedded"),s=K(ba("/admin/")),i=cn(),a=te("productName"),l=Ct();return eI(()=>{if(o)return t(l0()),()=>{t(iP())}},[t,o]),!r&&!s?null:(0,le.jsxs)("div",{className:n.shortcutList,children:[r&&(0,le.jsx)(de.Button,{"data-testid":"shortcut-search","aria-label":e("linkSearch"),className:n.shortcut,icon:(0,le.jsx)(Sa,{}),onClick:()=>{i.send("ShowCommandPalette",{isOpen:!0}),l("open search",{via:"widget-shortcut"})},children:e("linkSearch")}),s&&(0,le.jsx)(de.Button,{as:"a",target:"_blank",icon:(0,le.jsx)(dP,{}),href:s,"data-testid":"shortcut-studio-login","aria-label":e("linkStudioLogin",{productName:a}),className:n.shortcut,rel:"noreferrer",onClick:()=>{l("open my deepdesk",{via:"widget-shortcut"})},children:e("linkStudioLogin",{productName:a})})]})},HF=({title:e,content:t})=>{let n=ae(iu),[r,o]=(0,as.useState)(!0);return r?(0,le.jsx)(xr,{"data-testid":"custom-data-banner",type:"custom-data-banner",title:e,children:(0,le.jsx)(zt,{withDivider:!0,children:(0,le.jsxs)(de,{children:[(0,le.jsx)(ve,{children:(0,le.jsx)(ve.Content,{children:(0,le.jsx)(ai,{content:t})})}),(0,le.jsx)(de.ButtonsContainer,{children:(0,le.jsx)(de.Button,{onClick:()=>o(!1),children:n("close")})})]})})}):null},BF=()=>{let e=ge(),t=K(uc),n=K(AT),r=K(lP),o=K(K1),s=K(hp),i=K(Sp),a=K(Hs),l=K(kr);return(0,as.useEffect)(()=>{!!o&&!n&&ee.warn("Custom data provided, but no schema.")},[o,n]),eI(()=>{t.forEach(({type:c})=>{c==="entities"?e(lr()):Mu.includes(c)||e(cr(c))})},[e,l,a]),(0,as.useEffect)(()=>{r.length>0&&!t.some(c=>c.type==="cues")&&ee.warn("Received cues, but cues are not configured in widget.")},[t,r]),(0,le.jsx)(as.Fragment,{children:t.map(({type:c,title:u,amount:f,lines:d,schema:p,property:h})=>{var m,x;switch(c){case"entities":return s&&s.length>0&&(0,le.jsx)(xr,{type:c,title:u,"data-testid":`type-${c}`,children:(0,le.jsx)(uP,{entities:s})},c);case"cues":return r&&r.length>0&&(0,le.jsx)(xr,{type:c,title:u,"data-testid":`type-${c}`,children:(0,le.jsx)(zt,{withDivider:!0,children:(0,le.jsx)($P,{cues:r})})},c);case"custom-data-banner":return o&&h&&o[h]&&(0,le.jsx)(HF,{title:u,content:String(o[h])},c);case"custom-data":return o&&p&&(0,le.jsx)(xr,{type:c,title:u,"data-testid":`type-${c}`,children:(0,le.jsx)(zt,{withDivider:!0,children:(0,le.jsx)(WP,{data:o,schema:p})})},c);default:return((x=(m=i[c])==null?void 0:m.suggestions)==null?void 0:x.length)>0&&(0,le.jsx)(xr,{type:c,title:u,"data-testid":`type-${c}`,children:(0,le.jsx)(zt,{withDivider:!0,children:(0,le.jsx)(JP,{lines:d,contentType:c,suggestions:i[c].suggestions.slice(0,f)||[]})})},c)}})})},I0=({children:e})=>{let t=D("Widget",Na);return(0,le.jsx)("div",{className:t.footer,children:e})},A0=({children:e})=>{let t=D("Widget",Na);return(0,le.jsx)("div",{className:t.root,"data-testid":"widget",children:e})},UF=({onLogIn:e,knowledgeAssistOptions:t={},assistantOptions:n={transcript:"in-memory-transcript",expectFormat:"json-schema:cues"}})=>{var f;let r=ae(iu),o=K(ea),s=K(Tt),i=K(A1),a=K(Hs),l=K(IT("knowledge-assist")),c=K(LT),u=K(MT);return o===!1?(0,le.jsx)(P0,{text:r("notSupported")}):s===!1?(0,le.jsx)(FF,{onLogIn:e}):s===null?(0,le.jsx)(P0,{text:r("waiting")}):!i||!a?(0,le.jsx)(P0,{text:r("waitingForConversation")}):(0,le.jsx)(A0,{children:(0,le.jsxs)(im,{initialQuestion:t.initialQuestion,assistantCode:(f=c!=null?c:u)!=null?f:void 0,evaluateKnowledgeAssistFn:u?Kc:Gc,children:[(0,le.jsxs)(xi,{children:[(0,le.jsx)(zF,{}),(0,le.jsx)(BF,{}),l&&(0,le.jsx)(lm,{title:l.title,emptyState:t.emptyState})]}),(0,le.jsxs)(I0,{children:[l&&(0,le.jsx)(am,{}),(0,le.jsx)(xP,{assistantOptions:n})]})]})})},tI=UF;function _a(e){let t=new Range;return t.selectNodeContents(e),t}function nI(e,t,n){try{return ls(e,t,n),!0}catch(r){return!1}}function cm(e){return"tagName"in e&&(e.tagName==="DIV"||e.tagName==="P")}function um(e){return"tagName"in e&&e.tagName==="BR"}var au=/[\u200B-\u200D\uFEFF]/g;function ls(e,t,n){let r=new Range;if(e.firstChild===null&&t===0&&n===0)return r.selectNodeContents(e),r;let o=0,s=!1;function i(l,c){let u=-1,f=/[\u200B-\u200D\uFEFF]/;if(!f.test(l))return c;for(let d=0;d<=l.length;d++)if(f.test(l[d])||u++,u===c)return d;throw new Error("Offset out of range")}function a(l){switch(l.nodeType){case Node.TEXT_NODE:{let c=l.textContent,u=c.replace(au,""),f=o+u.length,d=t>=o&&t<=f,p=n>=o&&n<=f;if(d){let h=i(c,t-o);h===0&&!p?r.setStartBefore(l):r.setStart(l,h)}p&&(r.setEnd(l,i(c,n-o)),s=!0),o=f;break}case Node.ELEMENT_NODE:{if(um(l)&&(o===t&&r.setStartBefore(l),o++,o===n)){r.setEndAfter(l),s=!0;return}for(let u=0;u<l.childNodes.length&&(a(l.childNodes[u]),!s);u++);let c=l.lastChild;cm(l)&&c&&!cm(c)&&!um(c)&&o++;break}default:break}}if(a(e),r.startContainer===document)throw new Error("Offsets out of bound");return r}function lu(e,t){if(!e.contains(t.startContainer)||!e.contains(t.endContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:r,endContainer:o,endOffset:s,collapsed:i}=t,a,l,c=0;function u(f){let d=f===e,p=f===n,h=f===o;switch(f.nodeType){case Node.TEXT_NODE:{let m=f.textContent;p&&(a=c+m.substring(0,r).replace(au,"").length),h&&(l=c+m.substring(0,s).replace(au,"").length),c+=m.replace(au,"").length;break}case Node.ELEMENT_NODE:{if(um(f)&&f.nextSibling){c++;break}!d&&cm(f)&&f.previousSibling&&c++;for(let m=0;m<f.childNodes.length;m++){let x=p&&m===r,v=h&&m===s;if(x&&(a=c),v&&(l=c),l!==void 0||((!x||!i)&&u(f.childNodes[m]),h&&m===s-1&&(l=c),l!==void 0))break}h&&(l=c);break}default:break}}if(u(e),l===void 0)throw new Error("Could not determine start and end");return{start:a!=null?a:l,end:l}}function cu(e,t){if(!e.contains(t.startContainer)||!e.contains(t.endContainer))throw new Error("Range not within root element");let{startContainer:n,startOffset:r,endContainer:o,endOffset:s,collapsed:i}=t,a=0,l="";function c(u){let f=u===e,d=u===n,p=u===o;switch(d&&(a=1),u.nodeType){case Node.TEXT_NODE:{if(a!==1)return;let h=d?r:0,m=p?s:void 0;l+=u.textContent.replace(au,"").substring(h,m);break}case Node.ELEMENT_NODE:{if(!i&&a===1&&um(u)&&u.nextSibling){l+=`
81
81
  `;break}!f&&!i&&a===1&&cm(u)&&u.previousSibling&&(l+=`
82
- `);let h=d?r:0,m=p?Math.min(s,u.childNodes.length):u.childNodes.length;for(let x=h;x<m&&(c(u.childNodes[x]),a!==2);x++);break}default:break}p&&(a=2)}return c(e),l}var rI=(i=>(i.CUT="Cut",i.BACKSPACE="Backspace",i.DELETE="Delete",i.ERASEEOF="EraseEof",i.UNDO="Undo",i.CLEAR="Clear",i))(rI||{}),vo=class{constructor(t){this.element=t;this.isFocused=!1;this.isActive=!0;this.isDisposed=!1;this.eventListeners={};this.disposeHandlers=[];this.cachedText="";this.cachedCaretPosition=null;this.cachedSelection={start:0,end:0};this.cachedHTML="";this.isSubmitting=!1;this.isPossibleClearInputAction=!1;this.cachedText=this.getText(),this.cachedHTML=this.getHTML(),this.cachedSelection=this.getSelection(),this.listen()}addEventListener(t,n){let r=o=>{n(o)};this.element.addEventListener(t,r),this.disposeHandlers.push(()=>{this.element.removeEventListener(t,r)})}removeEventListener(t,n){this.element.removeEventListener(t,n)}handleInteraction(){let t=this.getText(),n=this.getHTML(),r=this.getSelection(),o=this.cachedCaretPosition===null;if(!this.isActive||(t===""&&this.cachedText!==""&&!this.isPossibleClearInputAction&&this.emit("submit"),t!==this.cachedText?(this.cachedText=t,this.cachedHTML=n,o=!0,this.emit("change",{plainText:t,rawHTML:n})):n!==null&&n!==this.cachedHTML&&(this.cachedHTML=n,o=!0,this.emit("change",{plainText:t,rawHTML:n})),(r.start!==this.cachedSelection.start||r.end!==this.cachedSelection.end)&&(this.cachedSelection=r,o=!0,this.emit("selection",r)),!o))return;let s=this.getCaretPosition();Ko(s,this.cachedCaretPosition)||(this.cachedCaretPosition=s,this.emit("caretposition",s))}handleClick(){this.handleInteraction()}handleFocus(){let t=!this.isFocused;this.isFocused=!0,t&&this.emit("focus"),this.handleInteraction()}handleBlur(){this.isPossibleClearInputAction=!1;let t=this.isFocused;this.isFocused=!1,t&&this.emit("blur")}handleKeyDown(t){let{key:n,ctrlKey:r,metaKey:o}=t;this.isPossibleClearInputAction=Object.values(rI).includes(n)||n.toLowerCase()==="z"&&(r||o),this.emit("keydown",t)}handleKeyUp(t){this.handleInteraction(),this.emit("keyup",t)}handleCut(){this.isPossibleClearInputAction=!0,this.emit("cut",{selectionText:this.getSelectedText()})}handlePaste(t){var r,o;let n=((r=t.clipboardData)==null?void 0:r.getData("text"))||((o=t.clipboardData)==null?void 0:o.getData("text/plain"))||"";this.emit("paste",{pastedText:n,selectionText:this.getSelectedText()})}listen(){this.addEventListener("keydown",n=>this.handleKeyDown(n)),this.addEventListener("keyup",n=>this.handleKeyUp(n)),this.addEventListener("input",()=>this.handleInteraction()),this.addEventListener("change",()=>this.handleInteraction()),this.addEventListener("focus",()=>this.handleFocus()),this.addEventListener("blur",()=>this.handleBlur()),this.addEventListener("cut",()=>this.handleCut()),this.addEventListener("paste",n=>this.handlePaste(n)),this.addEventListener("click",()=>this.handleInteraction()),document.activeElement===this.element&&(this.isFocused=!0);let t=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});t.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{t.disconnect()})}focus(){this.element.focus()}emit(t,...n){this.isDisposed||this.eventListeners[t]&&this.eventListeners[t].forEach(r=>{r(...n)})}on(t,n){this.isDisposed||(this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n))}off(t,n){if(!this.eventListeners[t])return;let r=this.eventListeners[t].indexOf(n);r!==-1&&this.eventListeners[t].splice(r,1)}activate(){let t=this.isActive===!1;this.isActive=!0,t&&this.handleInteraction()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(t=>t()),this.eventListeners={},this.isDisposed=!0}};function oI(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var ci=class extends vo{constructor(){super(...arguments);this.lastKnownSelection=null}getRootNode(){return this.element.getRootNode()}getText(){let n=new Range;return n.selectNodeContents(this.element),cu(this.element,n)}getHTML(){return this.element.innerHTML||""}getRange(){var i;let n=this.getRootNode();if(n.activeElement!==this.element)return null;let r="getSelection"in n?n.getSelection():window.getSelection();if(!r)return null;let o="getComposedRanges"in r&&n instanceof ShadowRoot?(i=r.getComposedRanges(n))==null?void 0:i[0]:r.rangeCount>0?r.getRangeAt(0):null;if(!o)return null;let s=this.element.ownerDocument.createRange();return s.setStart(o==null?void 0:o.startContainer,o==null?void 0:o.startOffset),s.setEnd(o==null?void 0:o.endContainer,o==null?void 0:o.endOffset),!s||!this.element.contains(s.startContainer)||!this.element.contains(s.endContainer)?null:s}getCaretPosition(){let n=this.getRange();if(!n||!n.collapsed||!("getBoundingClientRect"in n))return null;let r=n.getBoundingClientRect();return!oI(r)&&(n.insertNode(this.element.ownerDocument.createTextNode("\u2060")),r=n.getBoundingClientRect(),n.deleteContents(),!oI(r))?null:{top:r.top+r.height,left:r.left}}getSelection(){let n=this.getRange();if(n)return lu(this.element,n);let r=this.lastKnownSelection;if(r&&nI(this.element,r.start,r.end))return r;let o=_a(this.element);return o.collapse(!1),lu(this.element,o)}getSelectedText(){let{start:n,end:r}=this.getSelection();return cu(this.element,ls(this.element,n,r))}listen(){super.listen();let n=new MutationObserver(s=>{var i,a;s.length===2&&s[0].addedNodes.length===1&&((i=s[0].addedNodes[0])==null?void 0:i.textContent)==="\u2060"&&((a=s[1].removedNodes[0])==null?void 0:a.textContent)==="\u2060"||setTimeout(()=>{this.handleInteraction()},0)});n.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0}),this.disposeHandlers.push(()=>n.disconnect());let r=this.element.isContentEditable,o=new MutationObserver(()=>{this.element.isContentEditable!==r&&(r=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>o.disconnect())}};var VF=["direction","boxSizing","width","height","overflowX","overflowY","borderTopWidth","borderRightWidth","borderBottomWidth","borderLeftWidth","borderStyle","paddingTop","paddingRight","paddingBottom","paddingLeft","fontStyle","fontVariant","fontWeight","fontStretch","fontSize","fontSizeAdjust","lineHeight","fontFamily","textAlign","textTransform","textIndent","textDecoration","letterSpacing","wordSpacing","tabSize"];function sI(e,t){let n="mozInnerScreenX"in window,r=document.createElement("div");r.id="input-textarea-caret-position-mirror-div";let o=r.style,s=window.getComputedStyle(e),i=e.ownerDocument.body;o.whiteSpace="pre-wrap",o.wordWrap="break-word",o.position="absolute",o.visibility="hidden",VF.forEach(u=>{o[u]=s[u]}),n?e.scrollHeight>Number.parseInt(s.height)&&(o.overflowY="scroll"):o.overflow="hidden",r.textContent=e.value.substring(0,t);let a=document.createElement("span");a.textContent=e.value.substring(t)||".",r.appendChild(a),i.appendChild(r);let l=e.getBoundingClientRect(),c={top:l.top-e.scrollTop+a.offsetTop+Number.parseInt(s.borderTopWidth)+a.offsetHeight,left:l.left-e.scrollLeft+a.offsetLeft+Number.parseInt(s.borderLeftWidth)};return i.removeChild(r),c}var ui=class extends vo{constructor(){super(...arguments);this.lastKnownSelection=null}getText(){return this.element.value}getHTML(){return null}getSelection(){let{selectionStart:n,selectionEnd:r}=this.element;return{start:n,end:r}}getSelectedText(){let n=this.getSelection();return n?this.getText().slice(n.start,n.end):""}getCaretPosition(){return sI(this.element,this.element.selectionEnd)}listen(){super.listen();let n=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var s;return(s=n==null?void 0:n.get)==null?void 0:s.call(this.element)},set:s=>{var i;(i=n==null?void 0:n.set)==null||i.call(this.element,s),this.handleInteraction()}}),this.addEventListener("scroll",()=>{this.emit("caretposition",this.getCaretPosition())});let r=this.element.disabled,o=new MutationObserver(()=>{this.element.disabled!==r&&(r=this.element.disabled,this.emit(r?"disabled":"enabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>o.disconnect())}};function iI(e,t,n){let r=`deepdesk-iframe-${e}`,o=document.getElementById(r);if(o)return o;let s=document.createElement("iframe"),i=new URL(t);return Object.entries(n).forEach(([a,l])=>{i.searchParams.append(a,l)}),s.style.position="absolute",s.style.left="-999em",s.style.width="0px",s.style.height="0px",s.tabIndex=-1,s.id=r,s.title=`iframe-${e}`,s.src=i.toString(),window.document.body.appendChild(s),s}function $F(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch(t){return e}}var L0=class{constructor(t){this.name=t;this.disposeHandlers=[];this.broadcastChannel=new BroadcastChannel(t)}onMessage(t){this.broadcastChannel.addEventListener("message",t),this.disposeHandlers.push(()=>{this.broadcastChannel.removeEventListener("message",t)})}postMessage(t){this.broadcastChannel.postMessage(JSON.stringify(t))}close(){this.disposeHandlers.forEach(t=>t()),this.broadcastChannel.close()}},M0=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.disposeHandlers=[];this.iframe=iI(t,`${this.targetOrigin}/sdk/proxy/proxy.html`,{channel:this.name,host:window.location.origin,debug:"1"}),document.body.appendChild(this.iframe)}onMessage(t){window.addEventListener("message",t),this.disposeHandlers.push(()=>{window.removeEventListener("message",t)})}postMessage(t){var n;(n=this.iframe.contentWindow)==null||n.postMessage(JSON.stringify(t),this.targetOrigin)}close(){var t;this.disposeHandlers.forEach(n=>n()),(t=this.iframe)==null||t.remove()}},O0=class{constructor(t){this.params=t;this.deepdeskUrl=t.deepdeskUrl,this.eventMap=t.eventMap,this.externalId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setExternalId(t){this.externalId!==t&&(this.cleanup(),ee.info("Set externalId",t),this.externalId=t,this.channel=this.createChannel(t))}createChannel(t){let n=this.params.createCustomChannel?this.params.createCustomChannel(t):this.isCrossOrigin?new M0(t,this.deepdeskUrl,{debug:!0}):new L0(t),r=o=>{var i,a;if(o.origin!==this.deepdeskUrl)return;let s=$F(o.data);typeof s!="object"||s.type!=="event"||s.channel!==t||(ee.info("Received broadcast event",this.externalId,o),(a=(i=this.eventMap)[s.name])==null||a.call(i,s.payload))};return n.onMessage(r),n}send(t,n,r){var i,a;ee.info("Broadcast event",{externalId:this.externalId,name:t,payload:n});let o={type:"event",name:t,payload:n};r!==!1&&((a=(i=this.eventMap)[t])==null||a.call(i,n));let s=this.externalId==="deepdesk-general"?this.defaultChannel:this.channel;s==null||s.postMessage(P(w({},o),{channel:this.externalId}))}cleanup(t=!1){var n,r;(n=this.channel)==null||n.close(),this.channel=void 0,t&&((r=this.defaultChannel)==null||r.close(),this.defaultChannel=void 0)}},aI=O0;function jF(e){return e.replace(/(_\w)/g,t=>t[1].toUpperCase())}function _e(e){return Array.isArray(e)?e.map(_e):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>P(w({},t),{[jF(n)]:_e(e[n])}),{}):e}function WF(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function Nt(e){return Array.isArray(e)?e.map(Nt):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>P(w({},t),{[WF(n)]:Nt(e[n])}),{}):e}var Da=class extends Error{constructor(n,r){super(n);this.body=r;this.name="CustomError"}};var N0=e=>new Promise(t=>{setTimeout(t,e)});var Fa=class extends Da{constructor(){super(...arguments);this.name="ClientError"}},D0=class extends Da{constructor(){super(...arguments);this.name="ServerError"}},_0=new Map;function KF(e){return A(this,null,function*(){if(e.status===204)return e.text().catch(()=>{}),null;let t=e.headers.get("content-type");if(t!=null&&t.includes("application/json"))return e.json();let n=yield e.text();return n===""?null:(ee.warn("Unexpected response body:",n.slice(0,20)),JSON.parse(n))})}var cs=class cs{constructor(t="",n={}){this.baseUrl=t;this.options=n;this.latestRequestByUrl={};var r;this.fetch=(r=n.fetch)!=null?r:window.fetch.bind(window)}patchFetch(t){this.fetch=t(this.fetch)}setCsrfToken(t){this.csrfToken=t}request(t,n={}){return new Promise((r,o)=>{let s={isAborted:!1,reject:o},i=`${this.baseUrl}${t}`,a=this.fetch,l=n.method===void 0||n.method.toLowerCase()==="get",k=n,{useCache:c=!1,abortLatest:u=!1,attempts:f=1,retryDelay:d=500,refreshTokenOn401:p=!0,retryOnError:h=C=>C instanceof TypeError,retryOnResponse:m=C=>C.status>=500,version:x=null}=k,v=re(k,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]);if(c){if(!l)throw new Error(`Can't use 'useCache' for ${n.method}`);if(_0.has(i)){r(_0.get(i));return}}let y=P(w({credentials:"include"},v),{headers:w({Accept:"application/json","Content-Type":"application/json"},v.headers)});!l&&this.csrfToken&&(y.headers=P(w({},y.headers),{"X-CSRFToken":this.csrfToken})),typeof x=="string"&&(y.headers=P(w({},y.headers),{"X-Deepdesk-API-Version":x}));let g=f,S=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[i]&&u&&(this.latestRequestByUrl[i].isAborted=!0,this.latestRequestByUrl[i].reject(new Error("Aborted"))),this.latestRequestByUrl[i]=s;let E=()=>A(this,null,function*(){return g--,a(i,y).then(C=>A(this,null,function*(){return m(C)&&!s.isAborted&&g>0?(yield N0(d),E()):C.status===401&&p===!0&&S===!1?(S=!0,yield this.refreshToken(),E()):C})).catch(C=>A(this,null,function*(){if(h(C)&&!s.isAborted&&g>0)return yield N0(d),E();throw C}))});E().then(C=>A(this,null,function*(){let I=yield KF(C);if(delete this.latestRequestByUrl[i],C.status>=500){o(new D0("Server Error",I));return}if(C.status===401){o(new Fa("Unauthorized",I));return}if(C.status===403){o(new Fa("Forbidden",I));return}if(C.status===404){o(new Fa("Not Found",I));return}if(C.status>=400){o(new Fa("Bad Request",I));return}c&&_0.set(i,I),r(I)})).catch(C=>{o(C)})})}validateToken(){return A(this,null,function*(){let{has_valid_access_token:t,is_logged_in:n}=yield this.get("/apis/admin/session/validate/");if(!t)try{yield this.refreshToken();let{is_logged_in:r}=yield this.get("/apis/admin/session/validate/");return r}catch(r){return!1}return n})}refreshToken(){return cs.refreshingToken||(cs.refreshingToken=this.get("/apis/admin/session/refresh/",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{cs.refreshingToken=null},1e3*60)})),cs.refreshingToken}get(t,n){return this.request(t,n)}post(t,n,r){return this.request(t,w({method:"POST",body:JSON.stringify(n)},r))}patch(t,n,r){return this.request(t,w({method:"PATCH",body:JSON.stringify(n)},r))}put(t,n,r){return this.request(t,w({method:"PUT",body:JSON.stringify(n)},r))}delete(t,n){return this.request(t,w({method:"DELETE"},n))}};cs.refreshingToken=null;var di=cs;var lI;(t=>{let e;(a=>(a.SUCCESS="success",a.FAILURE="failure",a.CONDITIONS_NOT_MET="conditions_not_met",a.MAX_RECURSION_LEVEL="max_recursion_level",a.NO_ACCESS_TO_ASSISTANT="no_access_to_assistant"))(e=t.EvaluationStatus||(t.EvaluationStatus={}))})(lI||(lI={}));function F0(e){return P(w({},_e(e)),{metadata:e.metadata})}var fi=class fi{constructor(t,n={}){this.options=n;this.latestReceivedDeepdeskVersions={};this.shouldFetchCsrfToken=!0;this.client=new di(t,{fetch:n.fetch}),this.client.patchFetch(r=>(o,s)=>A(this,null,function*(){let i=yield r(o,s);return this.handleDeepdeskVersionHeaders(i),i}))}preflight(){return A(this,null,function*(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let t=yield this.getCsrfToken();this.client.setCsrfToken(t)}return this.options.token?(fi.exchangeTokenPromise||(fi.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),fi.exchangeTokenPromise):Promise.resolve()})}createConversation(t){return A(this,null,function*(){var r;yield this.preflight(),ee.info(`Creating conversation for session ${t.externalId} and agent ${t.agentId}`);let n=yield this.client.post("/api/v2/conversations",P(w({chat_start_time:new Date().toISOString()},Nt(t)),{metadata:(r=t.metadata)!=null?r:{}}));return F0(n)})}getMe(){return A(this,null,function*(){let t=yield this.client.get("/apis/admin/session/me/");return _e(t)})}postIdentity(t){return A(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/me/identities/",Nt(t))})}patchMe(t){return A(this,null,function*(){yield this.preflight();let n=yield this.client.patch("/apis/admin/session/me/",Nt(t));return _e(n)})}getProfile(t){return A(this,null,function*(){let n=yield this.client.get(`/apis/admin/profiles/${t}/`,{useCache:!0});return _e(n)})}getKnowledgeAssistant(t){return A(this,null,function*(){let n=yield this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{useCache:!0});return _e(n)})}getContentTypes(){return A(this,null,function*(){let t=yield this.client.get("/apis/admin/content-types/",{useCache:!0});return _e(t)})}getAccount(){return A(this,null,function*(){let t=yield this.client.get("/apis/admin/account/",{useCache:!0});return _e(t)})}getPlatformConfig(t){return A(this,null,function*(){let n=t!==void 0?`/platform/config/${t}/`:"/platform/config/",{config:r}=yield this.client.get(n,{useCache:!0});return _e(r)})}checkUserExists(t){return A(this,null,function*(){let{exists:n}=yield this.client.get(`/apis/admin/users/exists?external_id=${t}`,{version:"v1"});return n})}getConversationByExternalId(r){return A(this,arguments,function*(t,n={}){yield this.preflight(),ee.info(`Getting conversation for session ${t}`);let{attempts:o=1,retryDelay:s=1e3}=n,i=yield this.client.get(`/api/v2/conversations/by_external_id/${t}`,{attempts:o,retryDelay:s,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"});return ee.info(`Successfully retrieved conversation ${i.id} for session ${t}`),F0(i)})}isConversationSupported(r){return A(this,arguments,function*(t,n={}){ee.info(`Check if conversation for session ${t} is supported`);let{attempts:o=1,retryDelay:s=1e3}=n;return(yield this.client.get(`/api/v2/conversations/by_external_id/${t}/has_active_profile`,{attempts:o,retryDelay:s,retryOnResponse:a=>a.status===404||a.status>=500})).has_active_profile})}updateConversation(t,n){return A(this,null,function*(){var s;yield this.preflight();let r=Nt(n);n.metadata&&(r.metadata=(s=n.metadata)!=null?s:{});let o=yield this.client.put(`/api/v2/conversations/${t}`,r);return F0(o)})}postMessages(t,n){return A(this,null,function*(){yield this.preflight(),yield this.client.post(`/api/v2/conversations/${t}/messages`,n.map(r=>P(w({},Nt(r)),{metadata:r.metadata})))})}sendEvent(t,n){return A(this,null,function*(){yield this.preflight();let a=n,{data:r}=a,o=re(a,["data"]),s=Object.entries(this.latestReceivedDeepdeskVersions).reduce((l,[c,u])=>P(w({},l),{[c]:u}),{}),i=["platform","agentId","agentName","agentEmail","conversationId"].reduce((l,c)=>(o[c]&&(l[c]=o[c]),l),{});return this.client.post("/api/v2/events",Nt(P(w(w({},s),i),{data:r,name:t})),{version:"v2"})})}getEntities(t){return A(this,null,function*(){return yield this.preflight(),yield this.client.post("/api/v2/entities",{messages:t.filter(r=>r.text)})})}getTemporaryExchangeToken(){return A(this,null,function*(){return(yield this.client.get("/apis/admin/session/exchange-token/")).jwt})}exchangeTokenForAccessCookie(t){return A(this,null,function*(){return this.client.post("/apis/admin/session/jwt/",{jwt:t}).catch(n=>{throw ee.warn(`Invalid token '${t}'`),n})})}authenticateWithKey(t,n){return A(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/api-key/",Nt(n),{refreshTokenOn401:!1,headers:{apikey:t}})})}getTextSuggestions(o){return A(this,arguments,function*(t,n={},r){if(yield this.preflight(),r==="sticky-messages")throw new Error("Use getPinnedMessages instead");return(yield this.client.post(`/api/v2/conversations/${t}/recommend/${r}`,Nt(n),{abortLatest:!0})).map(i=>P(w({},_e(i)),{text:i.text||i.url||i.message,source:r,type:r})).filter((i,a,l)=>a===l.findIndex(c=>c.text===i.text))})}isLoggedIn(){return A(this,null,function*(){return yield this.preflight(),this.client.validateToken()})}getAutocompleteSuggestions(t,n){return A(this,null,function*(){return yield this.preflight(),(yield this.client.post(`/api/v2/conversations/${t}/autocomplete`,Nt(n),{abortLatest:!0})).map(o=>({score:1,source:o.source,sourceText:o.source_text,text:o.label,trainingJobs:o.training_jobs,searchKeywords:o.search_keywords,type:o.source})).filter((o,s,i)=>s===i.findIndex(a=>a.text===o.text))})}getPinnedMessages(t){return A(this,null,function*(){let n=yield this.client.get(`/api/v2/profiles/${t}/pinned-messages`,{abortLatest:!0});return _e(n).map(r=>P(w({},r),{text:r.message,source:"sticky-messages",type:"pinned-message"}))})}getStyleSuggestions(t){return A(this,null,function*(){let n=yield this.client.post("/api/v2/style-suggestions",Nt(t),{abortLatest:!0,version:"v2"});return _e(n)})}search(t){return A(this,null,function*(){let n=yield this.client.post(`/api/v2/profiles/${t.profile}/search`,Nt(t));return _e(n)})}knowledgeAssist(s,i,a){return A(this,arguments,function*(t,n,r,o={}){yield this.preflight();let l=yield this.client.post(`/api/knowledge-assist/assistants/${r}/search`,Nt({question:t.question,doNotKnowAnswer:t.doNotKnowAnswer,customerInstruction:t.customerInstruction,chatHistory:n.map(c=>({question:c.question,answer:c.answer.answer})),agentId:o.agentId,conversationId:o.conversationId}),{version:"v2"});return _e(l)})}requestLoginByEmail(t){return A(this,null,function*(){yield this.preflight();let n=yield this.client.post("/apis/admin/session/passwordless/request/",{email:t});return _e(n)})}requestPasswordlessToken(){return A(this,null,function*(){let t=yield this.client.get("/apis/admin/session/passwordless/request/");return _e(t.token)})}getCsrfToken(){return A(this,null,function*(){let{token:t}=yield this.client.get("/apis/admin/session/csrf/");return t})}verifyLoginToken(t){return A(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/login/",{token:t});return _e(n)})}getSummary(r){return A(this,arguments,function*(t,n={}){yield this.preflight();let o=yield this.client.post("/api/summary",{conversation:{messages:t.filter(s=>s.text&&s.source),agent_id:n.agentId,id:n.externalConversationId},prompt_instruction:n.promptInstruction,model:n.model},{version:"v1"});return _e(o)})}evaluateAssistant(t,n){return A(this,null,function*(){var a;yield this.preflight();let r=new URLSearchParams,{expectFormat:o="text"}=n||{};if(o.startsWith("json-schema:")){let l=o.replace("json-schema:","");r.append("expect_response_format","json-schema"),r.append("expect_response_format_schema",l)}else r.append("expect_response_format",o);n!=null&&n.externalConversationId&&r.append("external_conversation_id",n.externalConversationId);let s=n!=null&&n.threadId?`/api/v2/assistants/${t}/threads/${n==null?void 0:n.threadId}/evaluate?${r.toString()}`:`/api/v2/assistants/${t}/evaluate?${r.toString()}`,i=yield this.client.post(s,{input:(a=n==null?void 0:n.input)!=null?a:{},conversation:n==null?void 0:n.transcript});return _e(i)})}createAssistantThread(t){return A(this,null,function*(){yield this.preflight();let{assistantCode:n}=t,r=yield this.client.post(`/apis/admin/assistants/${n}/threads/`,{});return _e(r)})}postMessageToAssistantThread(t){return A(this,null,function*(){yield this.preflight();let{assistantCode:n,threadId:r,message:o}=t,s=yield this.client.post(`/apis/admin/assistants/${n}/threads/${r}/messages/`,{content:o,role:"user"});return _e(s)})}translateMessages(t){return A(this,null,function*(){yield this.preflight();let n=yield this.client.post("/api/v2/translate",Nt(t));return _e(n)})}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),s=o.match(Gx);if(!n||!s)return;let i=s[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[i];a&&n&&a!==n&&ee.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[i]=n})}};fi.exchangeTokenPromise=null;var xo=fi;var cI={startTime:null,stopTime:null},uI=e=>e.handlingTime,dI=Ee({name:"handlingTime",initialState:cI,reducers:{handlingTimeStart(e){if(e.startTime&&!e.stopTime)throw new Error("Timing already started");e.startTime=new Date,e.stopTime=null},handlingTimeStop(e){if(!e.startTime)throw new Error("Timing not started");e.stopTime=new Date},handlingTimeReset(e){e.startTime=null,e.stopTime=null}},extraReducers:e=>{e.addCase(at,()=>cI)}}),{handlingTimeStart:fI,handlingTimeStop:dm,handlingTimeReset:pI}=dI.actions,mI=dI.reducer;var gI=(e={})=>{let t=w({onAuthError:Ji(!1)},e);return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var fm={list:{keywordMatches:[]},fetchState:"idle"};var pi=fe("styleSuggestions/getAll",(n,r)=>A(void 0,[n,r],function*({text:e},t){var l;let{deepdeskAPI:o}=t.extra,s=t.getState(),{showStyleSuggestions:i}=s.settings,a=(l=s.conversation.current)==null?void 0:l.profileCode;if(!i)return fm.list;if(!a)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:a,message:e})})),GF=Ee({name:"styleSuggestions",initialState:fm,reducers:{},extraReducers:e=>{e.addCase(pi.pending,t=>{t.fetchState="loading"}).addCase(pi.rejected,t=>{t.fetchState="error"}).addCase(pi.fulfilled,(t,n)=>{t.fetchState="done",Ko(t.list,n.payload)||(t.list=n.payload)}).addCase(Ds,t=>{t.list=fm.list}).addCase(at,()=>fm)}}),hI=GF.reducer;var yI=(e={})=>{let t,n=!0,r=w({getStyleSuggestions:pi,debounce:500},e);return o=>s=>i=>{var p;let a=o.getState().input.text,l=s(i),c=o.getState();if(c.auth.isLoggedIn!==!0)return l;let{showStyleSuggestions:u}=c.settings;if(!((p=c.conversation.current)==null?void 0:p.id)||!u)return l;let{text:d}=c.input;return d===a&&!n||(clearTimeout(t),d==="")||(t=setTimeout(()=>{n=!1,o.dispatch(r.getStyleSuggestions({text:d}))},e.debounce)),l}};function qF(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end}var vI=(e={})=>{let t=w({getTextSuggestions:cr,getAutocompleteSuggestions:Mc,debounce:200,check:Ar},e),n;return r=>o=>s=>{var m;let{input:i}=r.getState(),a=o(s),l=r.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:c,showTabCompletion:u}=l.settings,f=(m=l.conversation.current)==null?void 0:m.id,d=s.type===wp.toString();if(!f||!c&&!u)return a;let{input:p}=l;return qF(p,i)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let x=ta(l);x===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(x))},d?0:t.debounce)),a}};var xI=pi.fulfilled.toString();function YF(e,t){let n=new Set([...t.keywordMatches.map(o=>o.keyword)]),r=[];return n.forEach(o=>{let s=e.keywordMatches.filter(l=>l.keyword===o),i=t.keywordMatches.filter(l=>l.keyword===o),a=i.length-s.length;a<=0||r.push(...i.slice(0,a))}),r}var SI=e=>t=>n=>r=>{var c;if(r.type!==xI){n(r);return}let o=t.getState().styleSuggestions.list;n(r);let s=t.getState(),i=s.styleSuggestions.list,a=(c=s.conversation)==null?void 0:c.current;if(o===i)return;let l=YF(o,i);r.type===xI&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var XF=ef({assistants:oP,auth:S1,conversation:L1,contentTypes:kT,passwordlessToken:aP,entities:bk,handlingTime:mI,info:Q1,input:$1,settings:m1,profile:OT,search:rT,styleSuggestions:hI,ui:Yk,textSuggestions:Mk});function wI(e){return UE({reducer:XF,middleware:t=>{var r;let n=t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI}},serializableCheck:!1}).concat(gI()).concat(vI({debounce:200})).concat(yI({debounce:500})).concat(SI(e.deepdeskAPI));return((r=e.middleware)!=null?r:[]).reduce((o,s)=>o.concat(s),n)},preloadedState:e.preloadedState})}var QF=e=>{var t,n;return(n=(t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())!=null?n:"unknown"},ZF=e=>t=>n=>r=>{var a,l,c,u,f,d,p;let o=t.getState(),s=Vl("inlineSuggestions")(o);switch(r.type){case Ji.toString():{!r.payload&&e.emit("logout",void 0);break}case lr.fulfilled.toString():r.payload.length>0&&e.sendEvent("entities found",{conversationId:(a=o.conversation.current)==null?void 0:a.id,data:{entities:r.payload}});break;case Go.toString():e.sendEvent(r.payload.name,{conversationId:((l=r.payload.options)==null?void 0:l.includeConversationData)&&((c=o.conversation.current)==null?void 0:c.id),data:r.payload.data});break;case Ds.toString():e.logSendMessage(r.payload);break;case qp.toString():e.emit("call-to-action",{cue:r.payload});break;case fr.fulfilled.toString():r.isBroadcasted||e.broadcast(Iy,r,!1);break;default:break}let i=n(r);switch(r.type){case Ds.toString():e.handleAfterSendMessage(r.payload);break;case Nc.toString():e.onUpdateShowTabHint(r.payload);break;case dm.toString():e.logHandlingTime();break;case bf.toString():e.broadcast(Yl,r);break;case _s.toString():e.broadcast(Yl,r);break;case Yp.toString():t.dispatch(_s({source:"assistant",assistantCode:r.payload.code}));break;case"analytics/logEvent/fulfilled":{e.emit("event",r.meta.arg);break}case vf.toString():{let{start:h,end:m}=o.input.selection;e.emit("replace",P(w({},r.payload),{replace:r.payload.replace==="selection"?{start:h,end:m}:{start:0,end:m}}));break}case Zn.toString():{let{start:h,end:m}=o.input.selection;e.emit("select-suggestion",P(w({type:QF(r.payload.suggestion)},r.payload),{replace:r.payload.replace==="selection"?{start:h,end:m}:{start:0,end:m}})),s&&t.dispatch(qo([]));break}case xf.toString():e.emit("select-image",r.payload),e.sendEvent("Image attached",{conversationId:(u=o.conversation.current)==null?void 0:u.id,data:{path:r.payload.suggestion.image,title:r.payload.suggestion.title}});break;case qo.toString():{s&&r.payload.length>0&&t.dispatch(Sf(0));break}case mo.fulfilled.toString():{if(r.isBroadcasted)break;e.broadcast(Yl,r,!1),e.sendEvent("conversation summarized",{conversationId:(f=o.conversation.current)==null?void 0:f.id,data:{summary:r.payload.output,assistant:(p=(d=t.getState().profile.data)==null?void 0:d.summarizerAssistantNew)!=null?p:void 0}}),e.emit("summary-generated",{summary:r.payload.output});break}default:break}return i},bI=ZF;function z0(e){return e.toISOString().replace("T"," ").replace("Z","")}var JF=(e,t)=>t.version,EI=Vt([ra,kr,uI,JF],(e,t,n,r)=>{if(!t)return ee.warn("No conversationId for handling time metrics"),null;let{startTime:o,stopTime:s}=n;return!o||!s?(ee.warn("No startTime and stopTime for handling time metrics"),null):{conversationId:t,clientVersion:r,agentId:e==null?void 0:e.agentId,agentName:e==null?void 0:e.agentName,agentEmail:e==null?void 0:e.agentEmail,timeStart:z0(o),timeStop:z0(s)}});function TI(e,t){let{text:n,metrics:{numPaste:r,pastes:o,textSuggestions:s}}=e.input,i=n.length;return{source:"agent",clientVersion:t.version,pastes:o,lenTextTotal:i,numPastes:r,suggestions:s}}function H0(e,t){var s;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return H0(r,t);let o=(s=e.ownerDocument.defaultView)==null?void 0:s.frameElement;return o?H0(o,t):null}function B0(e,t){return H0(e,t)}function CI(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function e5(e){return typeof e=="object"&&e!==null&&"tagName"in e}function pm(e){return e5(e)&&(ni(e)||Ip(e))}var RI,Dr=new Map,t5=["bottom","height","left","right","top","width"],kI=(e,t)=>!e&&!t?!1:e&&!t||!e&&t?!0:t5.some(n=>e[n]!==t[n]);function PI(e){var n,r,o;if(e.ownerDocument===document)return[];let t=(o=(r=(n=e.ownerDocument)==null?void 0:n.defaultView)==null?void 0:r.frameElement)!=null?o:null;return t?[t,...PI(t)]:[]}function II(e,t){return!e||!t?null:P(w({},e),{top:e.top+t.top,left:e.left+t.left})}var mm=!1,AI=()=>{mm=!0;let e=[];if(Dr.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),Dr.delete(n);return}let r=n.getBoundingClientRect();kI(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{let n=t.parentRects?t.parentRects.reduce(II,t.rect):t.rect;kI(n,t.totalRect)&&t.callbacks.forEach(r=>r(n)),t.totalRect=n}),Dr.size===0){mm=!1;return}RI=window.requestAnimationFrame(AI)};function U0(e,t){let n=PI(e),r=[],o=n.map((s,i)=>U0(s,a=>{r[i]=a;let l=Dr.get(e);if(!l)return;let c=r.reduce(II,l.rect);l.callbacks.forEach(u=>u(c))}));return{observe(s=!0){if(o.forEach(i=>i.observe(!1)),Dr.has(e)){let i=Dr.get(e);i.callbacks.push(t),i.rect&&t(i.rect)}else Dr.set(e,{rect:void 0,callbacks:[t],parentRects:r});s&&!mm&&AI()},unobserve(){o.forEach(i=>i.unobserve());let s=Dr.get(e);if(s){let i=s.callbacks.indexOf(t);i>=0&&s.callbacks.splice(i,1),s.callbacks.length||Dr.delete(e),Dr.size||(cancelAnimationFrame(RI),mm=!1)}}}}var LI,Fr=new Map,MI=()=>{Fr.forEach((e,t)=>{if(!t.isConnected){Fr.delete(t);return}let{clientHeight:n,scrollHeight:r}=t,o=r>n;e.visible!==o&&(e.visible=o,e.callbacks.forEach(s=>s(e.visible)))}),Fr.size!==0&&(LI=window.requestAnimationFrame(MI))};function OI(e,t){return{observe(){let n=Fr.size===0;Fr.has(e)?Fr.get(e).callbacks.push(t):Fr.set(e,{visible:void 0,callbacks:[t]}),n&&MI()},unobserve(){let n=Fr.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||Fr.delete(e),Fr.size||cancelAnimationFrame(LI)}}}}var V0=["borderLeftWidth","borderRightWidth","borderTopWidth","borderBottomWidth","borderStyle","boxSizing","color","overflowWrap","fontFamily","fontSize","fontSizeAdjust","fontStretch","fontWeight","fontKerning","lineHeight","letterSpacing","paddingLeft","paddingTop","paddingRight","paddingBottom","width","height","textIndent","whiteSpace","wordBreak","wordSpacing","wordWrap"];function $0(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function za(e){return Number.parseFloat(e)}function gm(e){return Math.round(e*1e6)}function NI(e){return e/1e6}function j0(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=za(e.width),s=za(e.borderLeftWidth),i=za(e.borderRightWidth),a=za(e.paddingRight),l=NI(gm(o)-gm(s)-gm(i)),c=NI(gm(r));if(l-c>2){let u=l-c;n.style.paddingRight=`${a+u}px`}}function uu(e,t={}){var u,f;let n=t.overlayContainer||document.createElement("div");n.style.display="none",n.style.position=(u=t.position)!=null?u:"fixed",n.style.pointerEvents="none",n.style.borderColor="transparent",ti(n);let r=window.getComputedStyle(e),o=!0,s=()=>{n.scrollTop=e.scrollTop};$0(r,n,V0),j0(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",s));let i=OI(e,()=>{$0(r,n,V0),j0(r,e,n),s(),setTimeout(s,0)}),a,l=!0,c=U0(e,d=>{if(d===null){t.onRemove&&t.onRemove(),n.remove();return}if(!l&&t.onMoveStart&&(Promise.resolve().then(()=>t.onMoveStart()),l=!0),clearTimeout(a),a=setTimeout(()=>{t.onMoveEnd&&t.onMoveEnd(),l=!1},200),d.height===0&&d.width===0){if(o===!0)return;t.onHide&&t.onHide(),n.style.display="none",o=!0;return}if($0(r,n,V0),j0(r,e,n),s(),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),m=za(h.borderTopWidth),x=za(h.borderBottomWidth),v=p.top+m-d.top,y=d.top+d.height+-(p.top+p.height-x);n.style.clipPath=`inset(${v}px 0px ${y}px 0px)`}o&&(n.style.display="block",t.onShow&&t.onShow(),o=!1)});return t.appendTo?t.appendTo.appendChild(n):(f=e.parentElement)==null||f.appendChild(n),c.observe(),i.observe(),[n,()=>{e.removeEventListener("scroll",s),c.unobserve(),i.unobserve(),n.remove()}]}var _I=(e,t)=>({value(){try{let n=sessionStorage.getItem(`dd-${e}`);if(!n)return t;try{return JSON.parse(n)}catch(r){return t}}catch(n){return t}},update(n){try{sessionStorage.setItem(`dd-${e}`,JSON.stringify(n))}catch(r){ee.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function n5(e){return e.offsetParent!==null}function DI(e){if(!n5(e))return!1;let t=e.getBoundingClientRect();return t.top>=0&&t.left>=0&&t.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&t.right<=(window.innerWidth||document.documentElement.clientWidth)}function hm(e,t,n=100){let r=DI(e);t({isVisible:r});let o=setInterval(()=>{let s=DI(e);s!==r&&(r=s,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var du=class extends Error{};function r5(){let e,t;return{promise:new Promise((r,o)=>{e=r,t=o}),resolve:e,reject:t}}var ym=class{constructor(){this.queues={}}push(t,n){let r=()=>{let s=this.queues[t][1];s?(this.queues[t]=[s.promise,null],s.resolve()):delete this.queues[t]};if(!this.queues[t]){let s=n().finally(r);return this.queues[t]=[s,null],s}this.queues[t][1]&&this.queues[t][1].reject(new du("Queued async function is outdated"));let o=r5();return this.queues[t][1]=o,o.promise.then(()=>n().finally(r))}};var o5={accepted:"onConversationAcceptedAssistants","new-message":"onConversationNewMessageAssistants",ended:"onConversationEndedAssistants"},FI=(e,t)=>{let n=e[o5[t]];return n&&n.length>0?n.map(r=>r.code):(ee.warn(`No assistant set in profile for conversation event "${t}"`),[])};var vm=class{constructor(t){this.options=t;this.socket=null;this.maxReconnectAttempts=5;this.reconnectInterval=25e3;this.cleanupCallbacks=[];var n,r;this.socket,this.eventListeners=new Map,this.url=t.url,this.maxReconnectAttempts=(n=t.maxReconnectAttempts)!=null?n:this.maxReconnectAttempts,this.reconnectInterval=(r=t.reconnectInterval)!=null?r:this.reconnectInterval,this.shouldReconnect=t.shouldReconnect}connect(){let t=()=>this.cleanup();window.addEventListener("beforeunload",t),this.cleanupCallbacks.push(()=>window.removeEventListener("beforeunload",t)),this.reconnect()}setupListeners(){this.socket&&(this.socket.onmessage=t=>{var n;try{let r=_e(JSON.parse(t.data));r.event&&this.eventListeners.has(r.event)&&((n=this.eventListeners.get(r.event))==null||n.forEach(o=>o(r.data)))}catch(r){console.error("Error parsing WebSocket message:",r)}},this.socket.onclose=t=>{console.log("WebSocket connection closed:",t),setTimeout(()=>{this.reconnect()},this.reconnectInterval)},this.socket.onerror=t=>{console.error("WebSocket error:",t)})}reconnect(){var t,n;if(this.maxReconnectAttempts<=0){console.error("Max reconnect attempts reached, closing WebSocket connection."),(t=this.socket)==null||t.close();return}if(!this.shouldReconnect()){console.error("Should not reconnect, closing WebSocket connection."),(n=this.socket)==null||n.close();return}this.socket&&(this.socket.onmessage=null,this.socket.onclose=null,this.socket.onerror=null,this.socket.close()),this.socket=new WebSocket(this.url),this.setupListeners(),this.maxReconnectAttempts--}send(t,n){if(!this.socket){console.error("WebSocket connection is not open.");return}this.socket.send(JSON.stringify({event:t,data:n}))}on(t,n){this.eventListeners.has(t)||this.eventListeners.set(t,[]);let r=this.eventListeners.get(t);r&&!r.includes(n)&&r.push(n)}close(){var t;(t=this.socket)==null||t.close()}cleanup(){this.close(),this.cleanupCallbacks.forEach(t=>t()),this.cleanupCallbacks=[]}};var Ie=b(R());var zI=_I("showTabHint",!0),Ha=class Ha{constructor({deepdeskUrl:t,version:n=Ha.version||"unknown",locale:r="en-US",token:o,fetch:s,productName:i,createCustomChannel:a,websocketClient:l=vm}){this.inputMediator=null;this.eventListeners={};this.unmountHandlers=[];this.disposeHandlers=[];this.inlineSuggestions=null;this.aboveSuggestions=null;this.floatingMenu=null;this.widgetElement=null;this.widgetRoot=null;this.dynamicThunkObject={};this.queues=new ym;this.isMounted=!1;this.shouldRender=!0;this.loadProfileConfigPromise=null;let c=t.replace(/\/api$/,"");this.deepdeskApi=new xo(c,{token:o,fetch:s}),this.version=n,this.instanceId=Ha.count++;let u={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[bI({broadcast:(p,h,m)=>{this.broadcastEvents.send(p,h,m)},emit:(p,h)=>this.emit(p,h),handleAfterSendMessage:p=>this.handleAfterSendMessage(p),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:p=>this.logSendMessage(p),onUpdateShowTabHint:p=>zI.update(p),sendEvent:(p,h)=>this.deepdeskApi.sendEvent(p,h)})]};this.store=wI(u),this.broadcastEvents=new aI({debug:!0,deepdeskUrl:c,eventMap:oT(this.store),createCustomChannel:a}),this.disposeHandlers.push(()=>{this.broadcastEvents.cleanup()}),this.ws=new l({url:`${c}/api/v2/me/realtime`.replace("https","wss"),reconnectInterval:25e3,shouldReconnect:()=>A(this,null,function*(){var p;return(p=Tt(this.state))!=null?p:!1})}),this.whenLoggedIn(()=>this.ws.connect()),this.store.dispatch(Nc(zI.value())),this.store.dispatch(pf({locale:r,adminUrl:c,productName:i}));let f=[];this.ws.on("assistants::user_notification",p=>{if(!p.conversationId)return;let h=()=>{this.conversationId()===p.conversationId&&this.store.dispatch(rP(p))};this.hasConversation()?h():f.push(h)}),this.ws.on("assistants::response_chunk",p=>{if(!p.conversationId)return;let h=()=>{this.conversationId()===p.conversationId&&this.store.dispatch(nP(p))};this.hasConversation()?h():f.push(h)});let d=this.whenConversationLoaded(()=>{var p;this.broadcastEvents.setExternalId((p=this.state.conversation.current)==null?void 0:p.externalId),f.forEach(h=>h()),f.length=0});this.disposeHandlers.push(()=>{this.ws.cleanup(),f.length=0,d()})}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){var t;return(t=Ns(this.state)[this.state.input.selectedSuggestionIndex])!=null?t:null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}externalId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.externalId}shouldAbort(){return this.state.conversation.isSupported===!1?(ee.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(ee.warn("Profile has not been loaded (yet)"),!0):(ee.warn("No conversation loaded (yet)"),!0)}whenLoggedIn(t){if(Tt(this.state))t();else{let n=this.subscribe(Tt,r=>{r&&t()});this.disposeHandlers.push(()=>{n()})}}login(){return this.store.dispatch(Ji(null)),this.store.dispatch(Jr()),new Promise(t=>{this.whenLoggedIn(()=>t())})}isLoggedIn(){return A(this,null,function*(){return(yield this.store.dispatch(Jr())).payload})}isConversationSupported(t,n){return A(this,null,function*(){return(yield this.store.dispatch(by({externalId:t,options:n}))).payload})}createConversation(t){return A(this,null,function*(){var r;return this.hasConversation()&&this.externalId()!==t.externalId&&this.resetConversation(),(yield this.store.dispatch(gf(P(w({},t),{metadata:(r=t.metadata)!=null?r:{}})))).payload})}getConversationByExternalId(t,n){return A(this,null,function*(){return this.hasConversation()&&this.externalId()!==t&&this.resetConversation(),(yield this.store.dispatch(hf({externalId:t,options:n}))).payload})}upsertConversation(t){return A(this,null,function*(){var r;return this.hasConversation()&&this.externalId()!==t.externalId&&this.resetConversation(),(yield this.store.dispatch(Ey(P(w({},t),{metadata:(r=t.metadata)!=null?r:{}})))).payload})}postMessages(t){return A(this,null,function*(){yield this.store.dispatch(Ty(t))})}updateConversation(t){return A(this,null,function*(){return(yield this.store.dispatch(yf(t))).payload})}resetConversation(){this.store.dispatch(at()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}configure(t){this.store.dispatch(pf(t))}setVisitorInfo(t){this.store.dispatch(q1(t))}setCustomData(t){this.store.dispatch(Y1(t))}setAgentInfo(t,n){return A(this,null,function*(){yield this.store.dispatch(Kl(w(w({},t),n)))})}setAgentSettings(t){return A(this,null,function*(){yield this.store.dispatch(ky(t))})}getAgentSettings(){return A(this,null,function*(){return(yield this.store.dispatch(Ry())).payload})}refresh(){return A(this,null,function*(){if(this.shouldAbort())return Promise.resolve();let t=[];return t.push(this.refreshTextSuggestions()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})})}syncInputMediator(){this.inputMediator&&this.store.dispatch(wf({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()}))}notifyExternalSuggestion(t){this.store.dispatch(Zn(t))}evaluateAssistant(t,n){return A(this,null,function*(){let u=n||{},{input:r={},transcript:o,showCuesInWidget:s=!0,includeMetadata:i,expectFormat:a}=u,l=re(u,["input","transcript","showCuesInWidget","includeMetadata","expectFormat"]);Object.assign(r,l);let c=yield this.store.dispatch(fr({assistantCode:t,expectFormat:a||"json-schema:cues",transcript:o,includeMetadata:i,input:r,skipState:!s}));if(c.error)throw new Error(c.error.message);return c.payload.output})}evaluateConversationAssistant(t,n){return A(this,null,function*(){yield this.loadProfileConfig();let r=this.state.profile.data;if(!r){ee.warn("Can't evaluate assistant when profile is not loaded yet.");return}let o=FI(r,t);yield Promise.all(o.map(s=>this.queues.push(s,()=>A(this,null,function*(){if(s===r.summarizerAssistantNew)return this.getSummary(w({includeMetadata:!0},n));yield this.evaluateAssistant(s,w({includeMetadata:!0},n))})).catch(i=>{if(i instanceof du){ee.warn(`Queued assistant "${s}" was outdated and dropped`);return}throw i})))})}getSummary(){return A(this,arguments,function*(t={}){var r;if(!this.hasConversation())return ee.warn("No conversation to create summary for."),null;(r=this.state.profile.data)!=null&&r.summarizerAssistantNew||ee.warn("No profile loaded yet, or no summarizer assistant set in profile");let n=yield this.store.dispatch(mo(t));if(n.error)throw new Error(n.error.message);return n.payload.output})}handleKeyDown(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui,{textSuggestions:o,selectedSuggestionIndex:s,selection:i}=this.state.input,{inlineSuggestions:a,showTextSuggestions:l}=this.settings,c=a?"below":"above",u=o.length>0;if(this.store.dispatch(D1(Cy(t))),!Ar(this.state)||t.key!=="Tab"&&!l)return;let f=()=>{n||!u||i&&(t.shiftKey||(this.store.dispatch(H1()),t.preventDefault()))},d=()=>{n||!u||a&&s<=0||i&&(t.shiftKey||(this.store.dispatch(B1()),t.preventDefault()))};switch(t.key){case"ArrowUp":c==="below"?d():f();break;case"ArrowDown":{c==="below"?f():d();break}case"Escape":{n||(this.store.dispatch(Sf(-1)),this.store.dispatch(ns({collapse:!0})),this.store.dispatch(Gk(!0)),t.preventDefault());break}case"Tab":{t.preventDefault();let p=na(this.state);if(!p)return;this.store.dispatch(Nc(!1)),this.store.dispatch(Zn({text:p.text,suggestion:p,eventMetrics:{inputType:"tab"},replace:"until-selection-end"}));break}case" ":{if(this.settings.inlineSuggestions||this.state.input.selectedSuggestionIndex===-1)return;let p=na(this.state);if(!p)return;this.store.dispatch(Zn({text:p.text,suggestion:p,eventMetrics:{inputType:"space"},replace:"until-selection-end"}));break}case"Enter":{if(this.settings.inlineSuggestions||t.shiftKey||this.state.input.selectedSuggestionIndex===-1)return;let p=na(this.state);if(!p)return;this.store.dispatch(Zn({text:p.text,suggestion:p,eventMetrics:{inputType:"enter"},replace:"until-selection-end"})),t.preventDefault();break}default:}n&&r&&this.store.dispatch(ns({collapse:!1}))}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(qo([]))}handlingTimeStart(){this.state.handlingTime.startTime||(ee.info("Start handling time"),this.store.dispatch(fI()))}handlingTimeStop(){this.state.handlingTime.startTime&&(ee.info("Stop handling time"),this.store.dispatch(dm()))}logSendMessage(t){let n=TI(this.state,{version:this.version});n&&(t&&(Object.assign(n,{text:t}),Object.assign(n,{lenTextTotal:t.length})),this.deepdeskApi.sendEvent("Send Message",{conversationId:this.conversationId(),data:n}),this.emit("send-message-event",n))}logHandlingTime(){let t=EI(this.state,{version:this.version});t&&(this.deepdeskApi.sendEvent("Handling Time",{conversationId:this.conversationId(),data:t}),this.store.dispatch(pI()))}notifySubmit(t={}){var n;this.shouldAbort()||(this.store.dispatch(Ds((n=t.text)!=null?n:this.state.input.text)),this.store.dispatch(V1()))}emit(t,n){let r=this.eventListeners[t];r&&r.forEach(o=>{try{o(n)}catch(s){ee.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),ee.error(s)}})}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),()=>{this.off(t,n)}}off(t,n){if(!t&&!n){this.eventListeners={};return}let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}setConversationQuery(t){this.dynamicThunkObject.conversationQuery=t}setPlatformVariables(t){this.store.dispatch(X1(t))}whenConversationLoaded(t){let n=s=>{var i;return(i=s.conversation.current)==null?void 0:i.id},r=()=>this.loadProfileConfig().then(()=>t());return n(this.state)&&r(),this.subscribe(n,s=>{s&&r()})}overlayContainerFactory(t,n,r,o){let[s,i]=uu(n,r);return s.setAttribute("translate","no"),s.dataset.testid=t,o&&s.classList.add(o),[s,i]}createInlineContainer(t,n){var a;let r=document.createElement("div");r.style.position="absolute",r.style.top="0px",r.style.left="0px",r.style.height="0px",r.style.width="0px";let o=document.createElement("div");o.style.display="none",o.style.position="absolute",o.style.height="0px",o.style.width="0px",o.style.backgroundColor="red",r.appendChild(o);let s=(a=t.ownerDocument.defaultView)==null?void 0:a.frameElement,i=s?s.ownerDocument.defaultView:null;if(s&&(i===window||(i==null?void 0:i.parent)===window)){let[l,c]=uu(s,{appendTo:document.body,onMoveStart:()=>{o.style.display="none"}});l.dataset.testid=n,l.style.zIndex="2",l.appendChild(r),this.unmountHandlers.push(()=>{c()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return ti(o),o.dataset.testid=t,o.style.color=r.color,o.style.fontSize=r.fontSize,o.style.fontFamily=r.fontFamily,o.style.fontVariant=r.fontVariant,o.setAttribute("translate","no"),n.appendChild(o),o}storeMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(t,n),ee.info(`Stored analytics for ${this.conversationId()}`)}catch(t){}}restoreMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=window.sessionStorage.getItem(t);if(!n)return;let r=JSON.parse(n);r.text.trim()===this.state.input.text.trim()?(ee.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(U1(r.metrics))):ee.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(t)}catch(t){}}mount(t,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!pm(t))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let d=n,{customStyles:r,closestScrollSelector:o,floatingMenuParent:s,appendOverlayTo:i,inputMediator:a}=d,l=re(d,["customStyles","closestScrollSelector","floatingMenuParent","appendOverlayTo","inputMediator"]),c={customStyles:r,closestScrollSelector:o,floatingMenuParent:s,appendOverlayTo:i};this.configure(l),this.settings.automaticHandlingTime&&this.setupHandlingTime(t),ti(t),this.inputMediator=a||(ni(t)?new ui(t):new ci(t)),this.inputMediator.on("change",({plainText:p,rawHTML:h})=>{this.store.dispatch(wf({text:p,html:h}))}),this.inputMediator.on("keyup",p=>{this.store.dispatch(F1(Cy(p)))}),this.inputMediator.on("keydown",p=>{this.handleKeyDown(p)}),this.inputMediator.on("paste",({pastedText:p,selectionText:h})=>{this.store.dispatch(z1({text:p,selectionText:h}))}),this.inputMediator.on("cut",({selectionText:p})=>{this.store.dispatch(_1(p))});let u;this.inputMediator.on("selection",p=>{clearTimeout(u),p===null?u=setTimeout(()=>{p!==null&&this.store.dispatch(Ef(p))},500):this.store.dispatch(Ef(p))}),this.unmountHandlers.push(()=>{clearTimeout(u)}),this.inputMediator.on("disabled",()=>{var p;(p=this.inputMediator)==null||p.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{this.settings.detectSubmit&&this.notifySubmit()}),this.inputMediator.on("blur",()=>{this.store.dispatch(Tp(!1))}),this.inputMediator.on("focus",()=>{this.store.dispatch(Tp(!0))}),this.renderSuggestions(t,c),this.subscribe(Vl("inlineSuggestions"),()=>{this.renderSuggestions(t,c)});let f=this.renderOverlays(n);this.unmountHandlers.push(()=>{f.unmount()}),this.store.dispatch(wf({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()})),this.store.dispatch(Ef(this.inputMediator.getSelection())),this.store.dispatch(Tp(this.inputMediator.isFocused)),this.unmountHandlers.push(()=>{this.state.input.text!==""&&this.storeMetrics()}),this.whenConversationLoaded(()=>{this.restoreMetrics(),this.syncInputMediator(),this.refreshTextSuggestions()}),this.isMounted=!0}subscribe(t,n){let r=t(this.store.getState());return this.store.subscribe(()=>{let o=t(this.store.getState());o!==r&&(r=o,n(r))})}unmount(){var t,n,r,o;(t=this.inlineSuggestions)==null||t.unmount(),(n=this.aboveSuggestions)==null||n.unmount(),(r=this.floatingMenu)==null||r.unmount(),this.unmountHandlers.forEach(s=>s()),this.unmountHandlers=[],(o=this.inputMediator)==null||o.dispose(),this.isMounted=!1}dispose(){this.unmount(),this.unmountWidget(),this.disposeHandlers.forEach(t=>t()),this.disposeHandlers=[],this.off()}renderSuggestions(t,n){var r,o,s;(r=this.floatingMenu)==null||r.unmount(),(o=this.inlineSuggestions)==null||o.unmount(),(s=this.aboveSuggestions)==null||s.unmount(),this.settings.floatingMenu&&(this.floatingMenu=this.renderFloatingMenu(t,n)),this.settings.inlineSuggestions?this.inlineSuggestions=this.renderInlineSuggestions(t,n):this.aboveSuggestions=this.renderAboveSuggestions(t,n)}renderInlineSuggestions(t,n){let{customStyles:r}=n,o=this.createInlineContainer(t,"deepdesk-caret"),s=(0,us.createRoot)(o);s.render((0,Ie.jsx)(os,{store:this.store,customStyles:r,children:(0,Ie.jsx)(Yo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(oR,{})})}));let i=a=>{a?(o.style.display="block",o.style.top=`${a.top}px`,o.style.left=`${a.left}px`):o.style.display="none"};return this.inputMediator.on("caretposition",i),{unmount:()=>{var a;(a=this.inputMediator)==null||a.off("caretposition",i),s.unmount(),o.remove()}}}renderAboveSuggestions(t,n){let{customStyles:r,closestScrollSelector:o,appendOverlayTo:s}=n,i=o&&B0(t,o)||void 0,[a,l]=this.overlayContainerFactory("deepdesk-tab-completion",i||t,{appendTo:s,closestScrollElement:i,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),[c,u]=this.overlayContainerFactory("deepdesk-suggestions-overlay",i||t,{appendTo:s},r==null?void 0:r.suggestionsRootNode),f=(0,us.createRoot)(a);f.render((0,Ie.jsx)(os,{store:this.store,customStyles:r,children:(0,Ie.jsx)(Yo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(NR,{inputElement:t})})}));let d=(0,us.createRoot)(c);return d.render((0,Ie.jsx)(os,{store:this.store,customStyles:r,children:(0,Ie.jsx)(Yo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(pR,{onLogIn:()=>this.loginViaPopup().catch(p=>ee.warn(p.message))})})})),{unmount(){f.unmount(),d.unmount(),l(),u()}}}renderFloatingMenu(t,n){let{customStyles:r,closestScrollSelector:o,appendOverlayTo:s,floatingMenuParent:i}=n,a=o&&B0(t,o)||void 0,[l,c]=this.overlayContainerFactory("floating-menu",a||t,{appendTo:i!=null?i:s},r==null?void 0:r.floatingMenuParent),u=(0,us.createRoot)(l);return u.render((0,Ie.jsx)(os,{store:this.store,customStyles:r,children:(0,Ie.jsx)(Yo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(jk,{onLogIn:()=>this.loginViaPopup().catch(f=>ee.warn(f.message))})})})),{unmount(){u.unmount(),c()}}}renderOverlays(t){let{customStyles:n}=t,r=this.createContainer("deepdesk-overlays"),o=(0,us.createRoot)(r);return o.render((0,Ie.jsx)(os,{store:this.store,customStyles:n,children:(0,Ie.jsx)(Yo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(Hk,{})})})),{unmount(){o.unmount(),r.remove()}}}renderWidget(t,n={}){if(this.widgetElement&&ee.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,isEmbedded:s}=n;this.widgetElement=t,this.configure({showImages:o,isEmbedded:s}),this.widgetRoot=(0,us.createRoot)(t),this.widgetRoot.render((0,Ie.jsx)(os,{store:this.store,customStyles:r,children:(0,Ie.jsx)(Yo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(tI,{assistantOptions:n.assistantOptions,knowledgeAssistOptions:n.knowledgeAssist,onLogIn:()=>this.loginViaPopup().catch(i=>ee.warn(i.message))})})}))}unmountWidget(){var t,n;(n=(t=this.widgetRoot)==null?void 0:t.unmount)==null||n.call(t),this.widgetRoot=null,this.widgetElement=null}renderKnowledgeAssistantWidget(t,n,r={}){let{customStyles:o,initialQuestion:s}=r,i=(0,us.createRoot)(n);return i.render((0,Ie.jsx)(os,{store:this.store,customStyles:o,children:(0,Ie.jsx)(Yo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(A0,{children:(0,Ie.jsxs)(im,{assistantCode:t,initialQuestion:s,evaluateKnowledgeAssistFn:r.isLegacyKnowledgeAssist?Kc:Gc,children:[(0,Ie.jsx)(xi,{children:(0,Ie.jsx)(lm,{title:r.title,emptyState:r.emptyState})}),(0,Ie.jsx)(I0,{children:(0,Ie.jsx)(am,{})})]})})})})),{unmount(){i.unmount()}}}setupHandlingTime(t){let n=hm(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){CI(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(()=>A(this,null,function*(){yield this.store.dispatch(cc());let t=Hs(this.state);t&&this.store.dispatch(pf({showSearch:t.search,showImageSearch:t.imageSearch,showEntitiesCommand:t.entitiesCommand,showSummaryCommand:!!t.summarizerAssistantNew,showKnowledgeSearch:!!t.knowledgeAssistantNew||!!t.knowledgeAssistant,recommendTextSuggestions:t.recommendTextSuggestions}))})),this.loadProfileConfigPromise)}loginViaPopup(t){return A(this,null,function*(){return new Promise((n,r)=>{let o=new MessageChannel,s=o.port1,i=this.settings.adminUrl,a=new URL(t!=null&&t.url?t==null?void 0:t.url:`${i}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let l=!1,c=()=>{u&&!u.closed&&u.close(),window.removeEventListener("message",f),clearInterval(d)};s.onmessage=p=>A(this,null,function*(){var h,m;if((h=p.data)!=null&&h.jwt)try{yield this.deepdeskApi.exchangeTokenForAccessCookie((m=p.data)==null?void 0:m.jwt),yield this.isLoggedIn(),this.broadcastEvents.send(ql),l=!0,o.port1.close(),n()}catch(x){console.error(x),r(x)}finally{l=!0,c()}});let u=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");u===null&&r(new Error("Popup blocked by browser"));let f=p=>A(this,null,function*(){var h;if(p.origin===a.origin)switch((h=p.data)==null?void 0:h.type){case"deepdesk-popup-loaded":{try{let m=JSON.stringify({type:"deepdesk-popup-create-channel"});u==null||u.postMessage(m,a.origin,[o.port2])}catch(m){ee.error("Error posting message to popup",m),r(m)}break}case"deepdesk-popup-error":{c(),p.data.message==="Timeout"&&ee.warn("Popup timed out. Check if the account's platform url is configured correctly."),r(new Error(p.data.message));break}}});window.addEventListener("message",f);let d=setInterval(()=>{u&&!u.closed||(c(),l||r(new Error("Popup closed by user")))},200);this.disposeHandlers.push(c)})})}translateMessages(t){return this.deepdeskApi.translateMessages(t)}refreshTextSuggestions(){return A(this,null,function*(){this.isMounted&&(yield this.store.dispatch(wp()))})}refreshWidgetSuggestions(){return A(this,null,function*(){if(!this.widgetRoot)return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=uc(this.state);try{n.forEach(({type:r})=>{switch(r){case"entities":this.store.dispatch(lr());break;case"pinned-messages":case"sticky-messages":break;default:Mu.includes(r)||this.store.dispatch(cr(r))}})}catch(r){this.handleError(r)}})}};Ha.version="18.1.2-beta.1",Ha.count=0;var fu=Ha;function s5(e){return A(this,null,function*(){var o,s,i;let n=yield((o=e.fetch)!=null?o:window.fetch)(e.url),r=yield n.blob();return new File([r],e.name,{type:(i=(s=e.mimeType)!=null?s:n.headers.get("Content-Type"))!=null?i:"image/jpeg"})})}function HI(e,t){return A(this,null,function*(){let n=yield s5(t),r=new Event("change",{bubbles:!0,cancelable:!0});try{Object.defineProperty(e,"files",{configurable:!0,get:()=>[n]}),e.dispatchEvent(r)}finally{Object.hasOwn(e,"files")&&delete e.files}})}function BI(e,t,n){return A(this,null,function*(){yield new xo(e).authenticateWithKey(t,n)})}function UI(e){return e.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}function VI(r,o){return A(this,arguments,function*(e,t,n={}){var f,d;let{value:s}=e,{start:i,end:a}=(f=n.replace)!=null?f:{start:0,end:s.length},l=`${s.slice(0,i)}${t}${s.slice(a)}`,c=(d=n.selectionAfter)!=null?d:{start:i+t.length,end:i+t.length},u=()=>{if(n.setValue)return n.setValue(l);e.value=l};return Promise.resolve(u()).then(()=>{e.selectionStart=c.start,e.selectionEnd=c.end,e.blur(),e.focus()})})}function $I(r,o){return A(this,arguments,function*(e,t,n={}){let s=n.replace?ls(e,n.replace.start,n.replace.end):_a(e),i,a=()=>{if(n.setRange)return n.setRange(s.cloneRange());s.deleteContents(),i=document.createElement("span"),s.insertNode(i),n.insertBRs!==!1?t.split(`
82
+ `);let h=d?r:0,m=p?Math.min(s,u.childNodes.length):u.childNodes.length;for(let x=h;x<m&&(c(u.childNodes[x]),a!==2);x++);break}default:break}p&&(a=2)}return c(e),l}var rI=(i=>(i.CUT="Cut",i.BACKSPACE="Backspace",i.DELETE="Delete",i.ERASEEOF="EraseEof",i.UNDO="Undo",i.CLEAR="Clear",i))(rI||{}),vo=class{constructor(t){this.element=t;this.isFocused=!1;this.isActive=!0;this.isDisposed=!1;this.eventListeners={};this.disposeHandlers=[];this.cachedText="";this.cachedCaretPosition=null;this.cachedSelection={start:0,end:0};this.cachedHTML="";this.isSubmitting=!1;this.isPossibleClearInputAction=!1;this.cachedText=this.getText(),this.cachedHTML=this.getHTML(),this.cachedSelection=this.getSelection(),this.listen()}addEventListener(t,n){let r=o=>{n(o)};this.element.addEventListener(t,r),this.disposeHandlers.push(()=>{this.element.removeEventListener(t,r)})}removeEventListener(t,n){this.element.removeEventListener(t,n)}handleInteraction(){let t=this.getText(),n=this.getHTML(),r=this.getSelection(),o=this.cachedCaretPosition===null;if(!this.isActive||(t===""&&this.cachedText!==""&&!this.isPossibleClearInputAction&&this.emit("submit"),t!==this.cachedText?(this.cachedText=t,this.cachedHTML=n,o=!0,this.emit("change",{plainText:t,rawHTML:n})):n!==null&&n!==this.cachedHTML&&(this.cachedHTML=n,o=!0,this.emit("change",{plainText:t,rawHTML:n})),(r.start!==this.cachedSelection.start||r.end!==this.cachedSelection.end)&&(this.cachedSelection=r,o=!0,this.emit("selection",r)),!o))return;let s=this.getCaretPosition();Ko(s,this.cachedCaretPosition)||(this.cachedCaretPosition=s,this.emit("caretposition",s))}handleClick(){this.handleInteraction()}handleFocus(){let t=!this.isFocused;this.isFocused=!0,t&&this.emit("focus"),this.handleInteraction()}handleBlur(){this.isPossibleClearInputAction=!1;let t=this.isFocused;this.isFocused=!1,t&&this.emit("blur")}handleKeyDown(t){let{key:n,ctrlKey:r,metaKey:o}=t;this.isPossibleClearInputAction=Object.values(rI).includes(n)||n.toLowerCase()==="z"&&(r||o),this.emit("keydown",t)}handleKeyUp(t){this.handleInteraction(),this.emit("keyup",t)}handleCut(){this.isPossibleClearInputAction=!0,this.emit("cut",{selectionText:this.getSelectedText()})}handlePaste(t){var r,o;let n=((r=t.clipboardData)==null?void 0:r.getData("text"))||((o=t.clipboardData)==null?void 0:o.getData("text/plain"))||"";this.emit("paste",{pastedText:n,selectionText:this.getSelectedText()})}listen(){this.addEventListener("keydown",n=>this.handleKeyDown(n)),this.addEventListener("keyup",n=>this.handleKeyUp(n)),this.addEventListener("input",()=>this.handleInteraction()),this.addEventListener("change",()=>this.handleInteraction()),this.addEventListener("focus",()=>this.handleFocus()),this.addEventListener("blur",()=>this.handleBlur()),this.addEventListener("cut",()=>this.handleCut()),this.addEventListener("paste",n=>this.handlePaste(n)),this.addEventListener("click",()=>this.handleInteraction()),document.activeElement===this.element&&(this.isFocused=!0);let t=new MutationObserver(()=>{this.element.isConnected||(this.emit("unmounted"),this.dispose())});t.observe(document.body,{subtree:!0,childList:!0}),this.disposeHandlers.push(()=>{t.disconnect()})}focus(){this.element.focus()}emit(t,...n){this.isDisposed||this.eventListeners[t]&&this.eventListeners[t].forEach(r=>{r(...n)})}on(t,n){this.isDisposed||(this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n))}off(t,n){if(!this.eventListeners[t])return;let r=this.eventListeners[t].indexOf(n);r!==-1&&this.eventListeners[t].splice(r,1)}activate(){let t=this.isActive===!1;this.isActive=!0,t&&this.handleInteraction()}deactivate(){this.isActive=!1}dispose(){this.disposeHandlers.forEach(t=>t()),this.eventListeners={},this.isDisposed=!0}};function oI(e){return e.top!==0||e.left!==0||e.height!==0||e.width!==0}var ci=class extends vo{constructor(){super(...arguments);this.lastKnownSelection=null}getRootNode(){return this.element.getRootNode()}getText(){let n=new Range;return n.selectNodeContents(this.element),cu(this.element,n)}getHTML(){return this.element.innerHTML||""}getRange(){var i;let n=this.getRootNode();if(n.activeElement!==this.element)return null;let r="getSelection"in n?n.getSelection():window.getSelection();if(!r)return null;let o="getComposedRanges"in r&&n instanceof ShadowRoot?(i=r.getComposedRanges(n))==null?void 0:i[0]:r.rangeCount>0?r.getRangeAt(0):null;if(!o)return null;let s=this.element.ownerDocument.createRange();return s.setStart(o==null?void 0:o.startContainer,o==null?void 0:o.startOffset),s.setEnd(o==null?void 0:o.endContainer,o==null?void 0:o.endOffset),!s||!this.element.contains(s.startContainer)||!this.element.contains(s.endContainer)?null:s}getCaretPosition(){let n=this.getRange();if(!n||!n.collapsed||!("getBoundingClientRect"in n))return null;let r=n.getBoundingClientRect();return!oI(r)&&(n.insertNode(this.element.ownerDocument.createTextNode("\u2060")),r=n.getBoundingClientRect(),n.deleteContents(),!oI(r))?null:{top:r.top+r.height,left:r.left}}getSelection(){let n=this.getRange();if(n)return lu(this.element,n);let r=this.lastKnownSelection;if(r&&nI(this.element,r.start,r.end))return r;let o=_a(this.element);return o.collapse(!1),lu(this.element,o)}getSelectedText(){let{start:n,end:r}=this.getSelection();return cu(this.element,ls(this.element,n,r))}listen(){super.listen();let n=new MutationObserver(s=>{var i,a;s.length===2&&s[0].addedNodes.length===1&&((i=s[0].addedNodes[0])==null?void 0:i.textContent)==="\u2060"&&((a=s[1].removedNodes[0])==null?void 0:a.textContent)==="\u2060"||setTimeout(()=>{this.handleInteraction()},0)});n.observe(this.element,{attributes:!0,characterData:!0,childList:!0,subtree:!0}),this.disposeHandlers.push(()=>n.disconnect());let r=this.element.isContentEditable,o=new MutationObserver(()=>{this.element.isContentEditable!==r&&(r=this.element.isContentEditable,this.emit(this.element.isContentEditable?"enabled":"disabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["contenteditable"]}),this.disposeHandlers.push(()=>o.disconnect())}};var VF=["direction","boxSizing","width","height","overflowX","overflowY","borderTopWidth","borderRightWidth","borderBottomWidth","borderLeftWidth","borderStyle","paddingTop","paddingRight","paddingBottom","paddingLeft","fontStyle","fontVariant","fontWeight","fontStretch","fontSize","fontSizeAdjust","lineHeight","fontFamily","textAlign","textTransform","textIndent","textDecoration","letterSpacing","wordSpacing","tabSize"];function sI(e,t){let n="mozInnerScreenX"in window,r=document.createElement("div");r.id="input-textarea-caret-position-mirror-div";let o=r.style,s=window.getComputedStyle(e),i=e.ownerDocument.body;o.whiteSpace="pre-wrap",o.wordWrap="break-word",o.position="absolute",o.visibility="hidden",VF.forEach(u=>{o[u]=s[u]}),n?e.scrollHeight>Number.parseInt(s.height)&&(o.overflowY="scroll"):o.overflow="hidden",r.textContent=e.value.substring(0,t);let a=document.createElement("span");a.textContent=e.value.substring(t)||".",r.appendChild(a),i.appendChild(r);let l=e.getBoundingClientRect(),c={top:l.top-e.scrollTop+a.offsetTop+Number.parseInt(s.borderTopWidth)+a.offsetHeight,left:l.left-e.scrollLeft+a.offsetLeft+Number.parseInt(s.borderLeftWidth)};return i.removeChild(r),c}var ui=class extends vo{constructor(){super(...arguments);this.lastKnownSelection=null}getText(){return this.element.value}getHTML(){return null}getSelection(){let{selectionStart:n,selectionEnd:r}=this.element;return{start:n,end:r}}getSelectedText(){let n=this.getSelection();return n?this.getText().slice(n.start,n.end):""}getCaretPosition(){return sI(this.element,this.element.selectionEnd)}listen(){super.listen();let n=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value");Object.defineProperty(this.element,"value",{configurable:!0,get:()=>{var s;return(s=n==null?void 0:n.get)==null?void 0:s.call(this.element)},set:s=>{var i;(i=n==null?void 0:n.set)==null||i.call(this.element,s),this.handleInteraction()}}),this.addEventListener("scroll",()=>{this.emit("caretposition",this.getCaretPosition())});let r=this.element.disabled,o=new MutationObserver(()=>{this.element.disabled!==r&&(r=this.element.disabled,this.emit(r?"disabled":"enabled"))});o.observe(this.element,{attributes:!0,attributeFilter:["disabled"]}),this.disposeHandlers.push(()=>o.disconnect())}};function iI(e,t,n){let r=`deepdesk-iframe-${e}`,o=document.getElementById(r);if(o)return o;let s=document.createElement("iframe"),i=new URL(t);return Object.entries(n).forEach(([a,l])=>{i.searchParams.append(a,l)}),s.style.position="absolute",s.style.left="-999em",s.style.width="0px",s.style.height="0px",s.tabIndex=-1,s.id=r,s.title=`iframe-${e}`,s.src=i.toString(),window.document.body.appendChild(s),s}function $F(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch(t){return e}}var L0=class{constructor(t){this.name=t;this.disposeHandlers=[];this.broadcastChannel=new BroadcastChannel(t)}onMessage(t){this.broadcastChannel.addEventListener("message",t),this.disposeHandlers.push(()=>{this.broadcastChannel.removeEventListener("message",t)})}postMessage(t){this.broadcastChannel.postMessage(JSON.stringify(t))}close(){this.disposeHandlers.forEach(t=>t()),this.broadcastChannel.close()}},M0=class{constructor(t,n,r){this.name=t;this.targetOrigin=n;this.options=r;this.disposeHandlers=[];this.iframe=iI(t,`${this.targetOrigin}/sdk/proxy/proxy.html`,{channel:this.name,host:window.location.origin,debug:"1"}),document.body.appendChild(this.iframe)}onMessage(t){window.addEventListener("message",t),this.disposeHandlers.push(()=>{window.removeEventListener("message",t)})}postMessage(t){var n;(n=this.iframe.contentWindow)==null||n.postMessage(JSON.stringify(t),this.targetOrigin)}close(){var t;this.disposeHandlers.forEach(n=>n()),(t=this.iframe)==null||t.remove()}},O0=class{constructor(t){this.params=t;this.deepdeskUrl=t.deepdeskUrl,this.eventMap=t.eventMap,this.externalId="deepdesk-general",this.defaultChannel=this.createChannel("deepdesk-general")}get isCrossOrigin(){return this.params.deepdeskUrl!==(this.params.origin||window.location.origin)}setExternalId(t){this.externalId!==t&&(this.cleanup(),ee.info("Set externalId",t),this.externalId=t,this.channel=this.createChannel(t))}createChannel(t){let n=this.params.createCustomChannel?this.params.createCustomChannel(t):this.isCrossOrigin?new M0(t,this.deepdeskUrl,{debug:!0}):new L0(t),r=o=>{var i,a;if(o.origin!==this.deepdeskUrl)return;let s=$F(o.data);typeof s!="object"||s.type!=="event"||s.channel!==t||(ee.info("Received broadcast event",this.externalId,o),(a=(i=this.eventMap)[s.name])==null||a.call(i,s.payload))};return n.onMessage(r),n}send(t,n,r){var i,a;ee.info("Broadcast event",{externalId:this.externalId,name:t,payload:n});let o={type:"event",name:t,payload:n};r!==!1&&((a=(i=this.eventMap)[t])==null||a.call(i,n));let s=this.externalId==="deepdesk-general"?this.defaultChannel:this.channel;s==null||s.postMessage(P(w({},o),{channel:this.externalId}))}cleanup(t=!1){var n,r;(n=this.channel)==null||n.close(),this.channel=void 0,t&&((r=this.defaultChannel)==null||r.close(),this.defaultChannel=void 0)}},aI=O0;function jF(e){return e.replace(/(_\w)/g,t=>t[1].toUpperCase())}function _e(e){return Array.isArray(e)?e.map(_e):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>P(w({},t),{[jF(n)]:_e(e[n])}),{}):e}function WF(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function Nt(e){return Array.isArray(e)?e.map(Nt):typeof e=="object"&&e!==null?Object.keys(e).reduce((t,n)=>P(w({},t),{[WF(n)]:Nt(e[n])}),{}):e}var Da=class extends Error{constructor(n,r){super(n);this.body=r;this.name="CustomError"}};var N0=e=>new Promise(t=>{setTimeout(t,e)});var Fa=class extends Da{constructor(){super(...arguments);this.name="ClientError"}},D0=class extends Da{constructor(){super(...arguments);this.name="ServerError"}},_0=new Map;function KF(e){return A(this,null,function*(){if(e.status===204)return e.text().catch(()=>{}),null;let t=e.headers.get("content-type");if(t!=null&&t.includes("application/json"))return e.json();let n=yield e.text();return n===""?null:(ee.warn("Unexpected response body:",n.slice(0,20)),JSON.parse(n))})}var cs=class cs{constructor(t="",n={}){this.baseUrl=t;this.options=n;this.latestRequestByUrl={};var r;this.fetch=(r=n.fetch)!=null?r:window.fetch.bind(window)}patchFetch(t){this.fetch=t(this.fetch)}setCsrfToken(t){this.csrfToken=t}request(t,n={}){return new Promise((r,o)=>{let s={isAborted:!1,reject:o},i=`${this.baseUrl}${t}`,a=this.fetch,l=n.method===void 0||n.method.toLowerCase()==="get",k=n,{useCache:c=!1,abortLatest:u=!1,attempts:f=1,retryDelay:d=500,refreshTokenOn401:p=!0,retryOnError:h=C=>C instanceof TypeError,retryOnResponse:m=C=>C.status>=500,version:x=null}=k,v=re(k,["useCache","abortLatest","attempts","retryDelay","refreshTokenOn401","retryOnError","retryOnResponse","version"]);if(c){if(!l)throw new Error(`Can't use 'useCache' for ${n.method}`);if(_0.has(i)){r(_0.get(i));return}}let y=P(w({credentials:"include"},v),{headers:w({Accept:"application/json","Content-Type":"application/json"},v.headers)});!l&&this.csrfToken&&(y.headers=P(w({},y.headers),{"X-CSRFToken":this.csrfToken})),typeof x=="string"&&(y.headers=P(w({},y.headers),{"X-Deepdesk-API-Version":x}));let g=f,S=!1;if(!a)throw new Error("fetch is not set");this.latestRequestByUrl[i]&&u&&(this.latestRequestByUrl[i].isAborted=!0,this.latestRequestByUrl[i].reject(new Error("Aborted"))),this.latestRequestByUrl[i]=s;let E=()=>A(this,null,function*(){return g--,a(i,y).then(C=>A(this,null,function*(){return m(C)&&!s.isAborted&&g>0?(yield N0(d),E()):C.status===401&&p===!0&&S===!1?(S=!0,yield this.refreshToken(),E()):C})).catch(C=>A(this,null,function*(){if(h(C)&&!s.isAborted&&g>0)return yield N0(d),E();throw C}))});E().then(C=>A(this,null,function*(){let I=yield KF(C);if(delete this.latestRequestByUrl[i],C.status>=500){o(new D0("Server Error",I));return}if(C.status===401){o(new Fa("Unauthorized",I));return}if(C.status===403){o(new Fa("Forbidden",I));return}if(C.status===404){o(new Fa("Not Found",I));return}if(C.status>=400){o(new Fa("Bad Request",I));return}c&&_0.set(i,I),r(I)})).catch(C=>{o(C)})})}validateToken(){return A(this,null,function*(){let{has_valid_access_token:t,is_logged_in:n}=yield this.get("/apis/admin/session/validate/");if(!t)try{yield this.refreshToken();let{is_logged_in:r}=yield this.get("/apis/admin/session/validate/");return r}catch(r){return!1}return n})}refreshToken(){return cs.refreshingToken||(cs.refreshingToken=this.get("/apis/admin/session/refresh/",{refreshTokenOn401:!1}).finally(()=>{setTimeout(()=>{cs.refreshingToken=null},1e3*60)})),cs.refreshingToken}get(t,n){return this.request(t,n)}post(t,n,r){return this.request(t,w({method:"POST",body:JSON.stringify(n)},r))}patch(t,n,r){return this.request(t,w({method:"PATCH",body:JSON.stringify(n)},r))}put(t,n,r){return this.request(t,w({method:"PUT",body:JSON.stringify(n)},r))}delete(t,n){return this.request(t,w({method:"DELETE"},n))}};cs.refreshingToken=null;var di=cs;var lI;(t=>{let e;(a=>(a.SUCCESS="success",a.FAILURE="failure",a.CONDITIONS_NOT_MET="conditions_not_met",a.MAX_RECURSION_LEVEL="max_recursion_level",a.NO_ACCESS_TO_ASSISTANT="no_access_to_assistant"))(e=t.EvaluationStatus||(t.EvaluationStatus={}))})(lI||(lI={}));function F0(e){return P(w({},_e(e)),{metadata:e.metadata})}var fi=class fi{constructor(t,n={}){this.options=n;this.latestReceivedDeepdeskVersions={};this.shouldFetchCsrfToken=!0;this.client=new di(t,{fetch:n.fetch}),this.client.patchFetch(r=>(o,s)=>A(this,null,function*(){let i=yield r(o,s);return this.handleDeepdeskVersionHeaders(i),i}))}preflight(){return A(this,null,function*(){if(this.shouldFetchCsrfToken){this.shouldFetchCsrfToken=!1;let t=yield this.getCsrfToken();this.client.setCsrfToken(t)}return this.options.token?(fi.exchangeTokenPromise||(fi.exchangeTokenPromise=this.exchangeTokenForAccessCookie(this.options.token)),fi.exchangeTokenPromise):Promise.resolve()})}createConversation(t){return A(this,null,function*(){var r;yield this.preflight(),ee.info(`Creating conversation for session ${t.externalId} and agent ${t.agentId}`);let n=yield this.client.post("/api/v2/conversations",P(w({chat_start_time:new Date().toISOString()},Nt(t)),{metadata:(r=t.metadata)!=null?r:{}}));return F0(n)})}getMe(){return A(this,null,function*(){let t=yield this.client.get("/apis/admin/session/me/");return _e(t)})}postIdentity(t){return A(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/me/identities/",Nt(t))})}patchMe(t){return A(this,null,function*(){yield this.preflight();let n=yield this.client.patch("/apis/admin/session/me/",Nt(t));return _e(n)})}getProfile(t){return A(this,null,function*(){let n=yield this.client.get(`/apis/admin/profiles/${t}/`,{useCache:!0});return _e(n)})}getKnowledgeAssistant(t){return A(this,null,function*(){let n=yield this.client.get(`/apis/admin/knowledge-assist/assistants/${t}/`,{useCache:!0});return _e(n)})}getContentTypes(){return A(this,null,function*(){let t=yield this.client.get("/apis/admin/content-types/",{useCache:!0});return _e(t)})}getAccount(){return A(this,null,function*(){let t=yield this.client.get("/apis/admin/account/",{useCache:!0});return _e(t)})}getPlatformConfig(t){return A(this,null,function*(){let n=t!==void 0?`/platform/config/${t}/`:"/platform/config/",{config:r}=yield this.client.get(n,{useCache:!0});return _e(r)})}checkUserExists(t){return A(this,null,function*(){let{exists:n}=yield this.client.get(`/apis/admin/users/exists?external_id=${t}`,{version:"v1"});return n})}getConversationByExternalId(r){return A(this,arguments,function*(t,n={}){yield this.preflight(),ee.info(`Getting conversation for session ${t}`);let{attempts:o=1,retryDelay:s=1e3}=n,i=yield this.client.get(`/api/v2/conversations/by_external_id/${t}`,{attempts:o,retryDelay:s,retryOnResponse:a=>a.status===404||a.status>=500,version:"v2"});return ee.info(`Successfully retrieved conversation ${i.id} for session ${t}`),F0(i)})}isConversationSupported(r){return A(this,arguments,function*(t,n={}){ee.info(`Check if conversation for session ${t} is supported`);let{attempts:o=1,retryDelay:s=1e3}=n;return(yield this.client.get(`/api/v2/conversations/by_external_id/${t}/has_active_profile`,{attempts:o,retryDelay:s,retryOnResponse:a=>a.status===404||a.status>=500})).has_active_profile})}updateConversation(t,n){return A(this,null,function*(){var s;yield this.preflight();let r=Nt(n);n.metadata&&(r.metadata=(s=n.metadata)!=null?s:{});let o=yield this.client.put(`/api/v2/conversations/${t}`,r);return F0(o)})}postMessages(t,n){return A(this,null,function*(){yield this.preflight(),yield this.client.post(`/api/v2/conversations/${t}/messages`,n.map(r=>P(w({},Nt(r)),{metadata:r.metadata})))})}sendEvent(t,n){return A(this,null,function*(){yield this.preflight();let a=n,{data:r}=a,o=re(a,["data"]),s=Object.entries(this.latestReceivedDeepdeskVersions).reduce((l,[c,u])=>P(w({},l),{[c]:u}),{}),i=["platform","agentId","agentName","agentEmail","conversationId"].reduce((l,c)=>(o[c]&&(l[c]=o[c]),l),{});return this.client.post("/api/v2/events",Nt(P(w(w({},s),i),{data:r,name:t})),{version:"v2"})})}getEntities(t){return A(this,null,function*(){return yield this.preflight(),yield this.client.post("/api/v2/entities",{messages:t.filter(r=>r.text)})})}getTemporaryExchangeToken(){return A(this,null,function*(){return(yield this.client.get("/apis/admin/session/exchange-token/")).jwt})}exchangeTokenForAccessCookie(t){return A(this,null,function*(){return this.client.post("/apis/admin/session/jwt/",{jwt:t}).catch(n=>{throw ee.warn(`Invalid token '${t}'`),n})})}authenticateWithKey(t,n){return A(this,null,function*(){yield this.preflight(),yield this.client.post("/apis/admin/session/api-key/",Nt(n),{refreshTokenOn401:!1,headers:{apikey:t}})})}getTextSuggestions(o){return A(this,arguments,function*(t,n={},r){if(yield this.preflight(),r==="sticky-messages")throw new Error("Use getPinnedMessages instead");return(yield this.client.post(`/api/v2/conversations/${t}/recommend/${r}`,Nt(n),{abortLatest:!0})).map(i=>P(w({},_e(i)),{text:i.text||i.url||i.message,source:r,type:r})).filter((i,a,l)=>a===l.findIndex(c=>c.text===i.text))})}isLoggedIn(){return A(this,null,function*(){return yield this.preflight(),this.client.validateToken()})}getAutocompleteSuggestions(t,n){return A(this,null,function*(){return yield this.preflight(),(yield this.client.post(`/api/v2/conversations/${t}/autocomplete`,Nt(n),{abortLatest:!0})).map(o=>({score:1,source:o.source,sourceText:o.source_text,text:o.label,trainingJobs:o.training_jobs,searchKeywords:o.search_keywords,type:o.source})).filter((o,s,i)=>s===i.findIndex(a=>a.text===o.text))})}getPinnedMessages(t){return A(this,null,function*(){let n=yield this.client.get(`/api/v2/profiles/${t}/pinned-messages`,{abortLatest:!0});return _e(n).map(r=>P(w({},r),{text:r.message,source:"sticky-messages",type:"pinned-message"}))})}getStyleSuggestions(t){return A(this,null,function*(){let n=yield this.client.post("/api/v2/style-suggestions",Nt(t),{abortLatest:!0,version:"v2"});return _e(n)})}search(t){return A(this,null,function*(){let n=yield this.client.post(`/api/v2/profiles/${t.profile}/search`,Nt(t));return _e(n)})}knowledgeAssist(s,i,a){return A(this,arguments,function*(t,n,r,o={}){yield this.preflight();let l=yield this.client.post(`/api/knowledge-assist/assistants/${r}/search`,Nt({question:t.question,doNotKnowAnswer:t.doNotKnowAnswer,customerInstruction:t.customerInstruction,chatHistory:n.map(c=>({question:c.question,answer:c.answer.answer})),agentId:o.agentId,conversationId:o.conversationId}),{version:"v2"});return _e(l)})}requestLoginByEmail(t){return A(this,null,function*(){yield this.preflight();let n=yield this.client.post("/apis/admin/session/passwordless/request/",{email:t});return _e(n)})}requestPasswordlessToken(){return A(this,null,function*(){let t=yield this.client.get("/apis/admin/session/passwordless/request/");return _e(t.token)})}getCsrfToken(){return A(this,null,function*(){let{token:t}=yield this.client.get("/apis/admin/session/csrf/");return t})}verifyLoginToken(t){return A(this,null,function*(){let n=yield this.client.post("/apis/admin/session/passwordless/login/",{token:t});return _e(n)})}getSummary(r){return A(this,arguments,function*(t,n={}){yield this.preflight();let o=yield this.client.post("/api/summary",{conversation:{messages:t.filter(s=>s.text&&s.source),agent_id:n.agentId,id:n.externalConversationId},prompt_instruction:n.promptInstruction,model:n.model},{version:"v1"});return _e(o)})}evaluateAssistant(t,n){return A(this,null,function*(){var a;yield this.preflight();let r=new URLSearchParams,{expectFormat:o="text"}=n||{};if(o.startsWith("json-schema:")){let l=o.replace("json-schema:","");r.append("expect_response_format","json-schema"),r.append("expect_response_format_schema",l)}else r.append("expect_response_format",o);n!=null&&n.externalConversationId&&r.append("external_conversation_id",n.externalConversationId);let s=n!=null&&n.threadId?`/api/v2/assistants/${t}/threads/${n==null?void 0:n.threadId}/evaluate?${r.toString()}`:`/api/v2/assistants/${t}/evaluate?${r.toString()}`,i=yield this.client.post(s,{input:(a=n==null?void 0:n.input)!=null?a:{},conversation:n==null?void 0:n.transcript});return _e(i)})}createAssistantThread(t){return A(this,null,function*(){yield this.preflight();let{assistantCode:n}=t,r=yield this.client.post(`/apis/admin/assistants/${n}/threads/`,{});return _e(r)})}postMessageToAssistantThread(t){return A(this,null,function*(){yield this.preflight();let{assistantCode:n,threadId:r,message:o}=t,s=yield this.client.post(`/apis/admin/assistants/${n}/threads/${r}/messages/`,{content:o,role:"user"});return _e(s)})}translateMessages(t){return A(this,null,function*(){yield this.preflight();let n=yield this.client.post("/api/v2/translate",Nt(t));return _e(n)})}handleDeepdeskVersionHeaders(t){t.headers.forEach((n,r)=>{let o=r.toLowerCase(),s=o.match(Gx);if(!n||!s)return;let i=s[1].replace("-","_"),a=this.latestReceivedDeepdeskVersions[i];a&&n&&a!==n&&ee.warn(`Overwritten Version header ${o}: ${JSON.stringify(a)} -> ${JSON.stringify(n)}`),this.latestReceivedDeepdeskVersions[i]=n})}};fi.exchangeTokenPromise=null;var xo=fi;var cI={startTime:null,stopTime:null},uI=e=>e.handlingTime,dI=Ee({name:"handlingTime",initialState:cI,reducers:{handlingTimeStart(e){if(e.startTime&&!e.stopTime)throw new Error("Timing already started");e.startTime=new Date,e.stopTime=null},handlingTimeStop(e){if(!e.startTime)throw new Error("Timing not started");e.stopTime=new Date},handlingTimeReset(e){e.startTime=null,e.stopTime=null}},extraReducers:e=>{e.addCase(at,()=>cI)}}),{handlingTimeStart:fI,handlingTimeStop:dm,handlingTimeReset:pI}=dI.actions,mI=dI.reducer;var gI=(e={})=>{let t=w({onAuthError:Ji(!1)},e);return n=>r=>o=>("error"in o&&o.error.message==="Unauthorized"&&n.dispatch(t.onAuthError),r(o))};var fm={list:{keywordMatches:[]},fetchState:"idle"};var pi=fe("styleSuggestions/getAll",(n,r)=>A(void 0,[n,r],function*({text:e},t){var l;let{deepdeskAPI:o}=t.extra,s=t.getState(),{showStyleSuggestions:i}=s.settings,a=(l=s.conversation.current)==null?void 0:l.profileCode;if(!i)return fm.list;if(!a)throw new Error("No current conversation to fetch pinned messages");return o.getStyleSuggestions({profileCode:a,message:e})})),GF=Ee({name:"styleSuggestions",initialState:fm,reducers:{},extraReducers:e=>{e.addCase(pi.pending,t=>{t.fetchState="loading"}).addCase(pi.rejected,t=>{t.fetchState="error"}).addCase(pi.fulfilled,(t,n)=>{t.fetchState="done",Ko(t.list,n.payload)||(t.list=n.payload)}).addCase(Ds,t=>{t.list=fm.list}).addCase(at,()=>fm)}}),hI=GF.reducer;var yI=(e={})=>{let t,n=!0,r=w({getStyleSuggestions:pi,debounce:500},e);return o=>s=>i=>{var p;let a=o.getState().input.text,l=s(i),c=o.getState();if(c.auth.isLoggedIn!==!0)return l;let{showStyleSuggestions:u}=c.settings;if(!((p=c.conversation.current)==null?void 0:p.id)||!u)return l;let{text:d}=c.input;return d===a&&!n||(clearTimeout(t),d==="")||(t=setTimeout(()=>{n=!1,o.dispatch(r.getStyleSuggestions({text:d}))},e.debounce)),l}};function qF(e,t){return e.text===t.text&&e.selection.start===t.selection.start&&e.selection.end===t.selection.end}var vI=(e={})=>{let t=w({getTextSuggestions:cr,getAutocompleteSuggestions:Mc,debounce:200,check:Ar},e),n;return r=>o=>s=>{var m;let{input:i}=r.getState(),a=o(s),l=r.getState();if(l.auth.isLoggedIn!==!0)return a;let{recommendTextSuggestions:c,showTabCompletion:u}=l.settings,f=(m=l.conversation.current)==null?void 0:m.id,d=s.type===wp.toString();if(!f||!c&&!u)return a;let{input:p}=l;return qF(p,i)&&!d||(clearTimeout(n),!t.check(l))||(n=setTimeout(()=>{let x=ta(l);x===""?r.dispatch(t.getTextSuggestions("default")):r.dispatch(t.getAutocompleteSuggestions(x))},d?0:t.debounce)),a}};var xI=pi.fulfilled.toString();function YF(e,t){let n=new Set([...t.keywordMatches.map(o=>o.keyword)]),r=[];return n.forEach(o=>{let s=e.keywordMatches.filter(l=>l.keyword===o),i=t.keywordMatches.filter(l=>l.keyword===o),a=i.length-s.length;a<=0||r.push(...i.slice(0,a))}),r}var SI=e=>t=>n=>r=>{var c;if(r.type!==xI){n(r);return}let o=t.getState().styleSuggestions.list;n(r);let s=t.getState(),i=s.styleSuggestions.list,a=(c=s.conversation)==null?void 0:c.current;if(o===i)return;let l=YF(o,i);r.type===xI&&l.length>0&&e.sendEvent("style suggested",{conversationId:a==null?void 0:a.id,data:{keywordMatches:l}})};var XF=ef({assistants:oP,auth:S1,conversation:L1,contentTypes:kT,passwordlessToken:aP,entities:bk,handlingTime:mI,info:Q1,input:$1,settings:m1,profile:OT,search:rT,styleSuggestions:hI,ui:Yk,textSuggestions:Mk});function wI(e){return UE({reducer:XF,middleware:t=>{var r;let n=t({thunk:{extraArgument:{dynamicThunkObject:e.dynamicThunkObject,deepdeskAPI:e.deepdeskAPI}},serializableCheck:!1}).concat(gI()).concat(vI({debounce:200})).concat(yI({debounce:500})).concat(SI(e.deepdeskAPI));return((r=e.middleware)!=null?r:[]).reduce((o,s)=>o.concat(s),n)},preloadedState:e.preloadedState})}var QF=e=>{var t,n;return(n=(t=e==null?void 0:e.type)==null?void 0:t.toLowerCase())!=null?n:"unknown"},ZF=e=>t=>n=>r=>{var a,l,c,u,f,d,p;let o=t.getState(),s=Vl("inlineSuggestions")(o);switch(r.type){case Ji.toString():{!r.payload&&e.emit("logout",void 0);break}case lr.fulfilled.toString():r.payload.length>0&&e.sendEvent("entities found",{conversationId:(a=o.conversation.current)==null?void 0:a.id,data:{entities:r.payload}});break;case Go.toString():e.sendEvent(r.payload.name,{conversationId:((l=r.payload.options)==null?void 0:l.includeConversationData)&&((c=o.conversation.current)==null?void 0:c.id),data:r.payload.data});break;case Ds.toString():e.logSendMessage(r.payload);break;case qp.toString():e.emit("call-to-action",{cue:r.payload});break;case fr.fulfilled.toString():r.isBroadcasted||e.broadcast(Iy,r,!1);break;default:break}let i=n(r);switch(r.type){case Ds.toString():e.handleAfterSendMessage(r.payload);break;case Nc.toString():e.onUpdateShowTabHint(r.payload);break;case dm.toString():e.logHandlingTime();break;case bf.toString():e.broadcast(Yl,r);break;case _s.toString():e.broadcast(Yl,r);break;case Yp.toString():t.dispatch(_s({source:"assistant",assistantCode:r.payload.code}));break;case"analytics/logEvent/fulfilled":{e.emit("event",r.meta.arg);break}case vf.toString():{let{start:h,end:m}=o.input.selection;e.emit("replace",P(w({},r.payload),{replace:r.payload.replace==="selection"?{start:h,end:m}:{start:0,end:m}}));break}case Zn.toString():{let{start:h,end:m}=o.input.selection;e.emit("select-suggestion",P(w({type:QF(r.payload.suggestion)},r.payload),{replace:r.payload.replace==="selection"?{start:h,end:m}:{start:0,end:m}})),s&&t.dispatch(qo([]));break}case xf.toString():e.emit("select-image",r.payload),e.sendEvent("Image attached",{conversationId:(u=o.conversation.current)==null?void 0:u.id,data:{path:r.payload.suggestion.image,title:r.payload.suggestion.title}});break;case qo.toString():{s&&r.payload.length>0&&t.dispatch(Sf(0));break}case mo.fulfilled.toString():{if(r.isBroadcasted)break;e.broadcast(Yl,r,!1),e.sendEvent("conversation summarized",{conversationId:(f=o.conversation.current)==null?void 0:f.id,data:{summary:r.payload.output,assistant:(p=(d=t.getState().profile.data)==null?void 0:d.summarizerAssistantNew)!=null?p:void 0}}),e.emit("summary-generated",{summary:r.payload.output});break}default:break}return i},bI=ZF;function z0(e){return e.toISOString().replace("T"," ").replace("Z","")}var JF=(e,t)=>t.version,EI=Vt([ra,kr,uI,JF],(e,t,n,r)=>{if(!t)return ee.warn("No conversationId for handling time metrics"),null;let{startTime:o,stopTime:s}=n;return!o||!s?(ee.warn("No startTime and stopTime for handling time metrics"),null):{conversationId:t,clientVersion:r,agentId:e==null?void 0:e.agentId,agentName:e==null?void 0:e.agentName,agentEmail:e==null?void 0:e.agentEmail,timeStart:z0(o),timeStop:z0(s)}});function TI(e,t){let{text:n,metrics:{numPaste:r,pastes:o,textSuggestions:s}}=e.input,i=n.length;return{source:"agent",clientVersion:t.version,pastes:o,lenTextTotal:i,numPastes:r,suggestions:s}}function H0(e,t){var s;let n=e.closest(t);if(n)return n;let r=e.getRootNode().host;if(r instanceof HTMLElement)return H0(r,t);let o=(s=e.ownerDocument.defaultView)==null?void 0:s.frameElement;return o?H0(o,t):null}function B0(e,t){return H0(e,t)}function CI(e){return typeof e=="object"&&e!==null&&"name"in e&&"message"in e}function e5(e){return typeof e=="object"&&e!==null&&"tagName"in e}function pm(e){return e5(e)&&(ni(e)||Ip(e))}var RI,Dr=new Map,t5=["bottom","height","left","right","top","width"],kI=(e,t)=>!e&&!t?!1:e&&!t||!e&&t?!0:t5.some(n=>e[n]!==t[n]);function PI(e){var n,r,o;if(e.ownerDocument===document)return[];let t=(o=(r=(n=e.ownerDocument)==null?void 0:n.defaultView)==null?void 0:r.frameElement)!=null?o:null;return t?[t,...PI(t)]:[]}function II(e,t){return!e||!t?null:P(w({},e),{top:e.top+t.top,left:e.left+t.left})}var mm=!1,AI=()=>{mm=!0;let e=[];if(Dr.forEach((t,n)=>{if(!n.isConnected){t.rect=null,e.push(t),Dr.delete(n);return}let r=n.getBoundingClientRect();kI(r,t.rect)&&(t.rect=r,e.push(t))}),e.forEach(t=>{let n=t.parentRects?t.parentRects.reduce(II,t.rect):t.rect;kI(n,t.totalRect)&&t.callbacks.forEach(r=>r(n)),t.totalRect=n}),Dr.size===0){mm=!1;return}RI=window.requestAnimationFrame(AI)};function U0(e,t){let n=PI(e),r=[],o=n.map((s,i)=>U0(s,a=>{r[i]=a;let l=Dr.get(e);if(!l)return;let c=r.reduce(II,l.rect);l.callbacks.forEach(u=>u(c))}));return{observe(s=!0){if(o.forEach(i=>i.observe(!1)),Dr.has(e)){let i=Dr.get(e);i.callbacks.push(t),i.rect&&t(i.rect)}else Dr.set(e,{rect:void 0,callbacks:[t],parentRects:r});s&&!mm&&AI()},unobserve(){o.forEach(i=>i.unobserve());let s=Dr.get(e);if(s){let i=s.callbacks.indexOf(t);i>=0&&s.callbacks.splice(i,1),s.callbacks.length||Dr.delete(e),Dr.size||(cancelAnimationFrame(RI),mm=!1)}}}}var LI,Fr=new Map,MI=()=>{Fr.forEach((e,t)=>{if(!t.isConnected){Fr.delete(t);return}let{clientHeight:n,scrollHeight:r}=t,o=r>n;e.visible!==o&&(e.visible=o,e.callbacks.forEach(s=>s(e.visible)))}),Fr.size!==0&&(LI=window.requestAnimationFrame(MI))};function OI(e,t){return{observe(){let n=Fr.size===0;Fr.has(e)?Fr.get(e).callbacks.push(t):Fr.set(e,{visible:void 0,callbacks:[t]}),n&&MI()},unobserve(){let n=Fr.get(e);if(n){let r=n.callbacks.indexOf(t);r>=0&&n.callbacks.splice(r,1),n.callbacks.length||Fr.delete(e),Fr.size||cancelAnimationFrame(LI)}}}}var V0=["borderLeftWidth","borderRightWidth","borderTopWidth","borderBottomWidth","borderStyle","boxSizing","color","overflowWrap","fontFamily","fontSize","fontSizeAdjust","fontStretch","fontWeight","fontKerning","lineHeight","letterSpacing","paddingLeft","paddingTop","paddingRight","paddingBottom","width","height","textIndent","whiteSpace","wordBreak","wordSpacing","wordWrap"];function $0(e,t,n){return n.forEach(r=>{t.style[r]=e[r]})}function za(e){return Number.parseFloat(e)}function gm(e){return Math.round(e*1e6)}function NI(e){return e/1e6}function j0(e,t,n){if(e.boxSizing==="content-box")return;let{clientWidth:r}=t,o=za(e.width),s=za(e.borderLeftWidth),i=za(e.borderRightWidth),a=za(e.paddingRight),l=NI(gm(o)-gm(s)-gm(i)),c=NI(gm(r));if(l-c>2){let u=l-c;n.style.paddingRight=`${a+u}px`}}function uu(e,t={}){var u,f;let n=t.overlayContainer||document.createElement("div");n.style.display="none",n.style.position=(u=t.position)!=null?u:"fixed",n.style.pointerEvents="none",n.style.borderColor="transparent",ti(n);let r=window.getComputedStyle(e),o=!0,s=()=>{n.scrollTop=e.scrollTop};$0(r,n,V0),j0(r,e,n),t.mirrorOverflow&&(n.style.overflow="hidden",e.addEventListener("scroll",s));let i=OI(e,()=>{$0(r,n,V0),j0(r,e,n),s(),setTimeout(s,0)}),a,l=!0,c=U0(e,d=>{if(d===null){t.onRemove&&t.onRemove(),n.remove();return}if(!l&&t.onMoveStart&&(Promise.resolve().then(()=>t.onMoveStart()),l=!0),clearTimeout(a),a=setTimeout(()=>{t.onMoveEnd&&t.onMoveEnd(),l=!1},200),d.height===0&&d.width===0){if(o===!0)return;t.onHide&&t.onHide(),n.style.display="none",o=!0;return}if($0(r,n,V0),j0(r,e,n),s(),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),m=za(h.borderTopWidth),x=za(h.borderBottomWidth),v=p.top+m-d.top,y=d.top+d.height+-(p.top+p.height-x);n.style.clipPath=`inset(${v}px 0px ${y}px 0px)`}o&&(n.style.display="block",t.onShow&&t.onShow(),o=!1)});return t.appendTo?t.appendTo.appendChild(n):(f=e.parentElement)==null||f.appendChild(n),c.observe(),i.observe(),[n,()=>{e.removeEventListener("scroll",s),c.unobserve(),i.unobserve(),n.remove()}]}var _I=(e,t)=>({value(){try{let n=sessionStorage.getItem(`dd-${e}`);if(!n)return t;try{return JSON.parse(n)}catch(r){return t}}catch(n){return t}},update(n){try{sessionStorage.setItem(`dd-${e}`,JSON.stringify(n))}catch(r){ee.warn("[Deepdesk] SessionStorage is blocked by browser")}}});function n5(e){return e.offsetParent!==null}function DI(e){if(!n5(e))return!1;let t=e.getBoundingClientRect();return t.top>=0&&t.left>=0&&t.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&t.right<=(window.innerWidth||document.documentElement.clientWidth)}function hm(e,t,n=100){let r=DI(e);t({isVisible:r});let o=setInterval(()=>{let s=DI(e);s!==r&&(r=s,t({isVisible:r}))},n);return()=>{clearTimeout(o)}}var du=class extends Error{};function r5(){let e,t;return{promise:new Promise((r,o)=>{e=r,t=o}),resolve:e,reject:t}}var ym=class{constructor(){this.queues={}}push(t,n){let r=()=>{let s=this.queues[t][1];s?(this.queues[t]=[s.promise,null],s.resolve()):delete this.queues[t]};if(!this.queues[t]){let s=n().finally(r);return this.queues[t]=[s,null],s}this.queues[t][1]&&this.queues[t][1].reject(new du("Queued async function is outdated"));let o=r5();return this.queues[t][1]=o,o.promise.then(()=>n().finally(r))}};var o5={accepted:"onConversationAcceptedAssistants","new-message":"onConversationNewMessageAssistants",ended:"onConversationEndedAssistants"},FI=(e,t)=>{let n=e[o5[t]];return n&&n.length>0?n.map(r=>r.code):(ee.warn(`No assistant set in profile for conversation event "${t}"`),[])};var vm=class{constructor(t){this.options=t;this.socket=null;this.maxReconnectAttempts=5;this.reconnectInterval=25e3;this.cleanupCallbacks=[];var n,r;this.socket,this.eventListeners=new Map,this.url=t.url,this.maxReconnectAttempts=(n=t.maxReconnectAttempts)!=null?n:this.maxReconnectAttempts,this.reconnectInterval=(r=t.reconnectInterval)!=null?r:this.reconnectInterval,this.shouldReconnect=t.shouldReconnect}connect(){let t=()=>this.cleanup();window.addEventListener("beforeunload",t),this.cleanupCallbacks.push(()=>window.removeEventListener("beforeunload",t)),this.reconnect()}setupListeners(){this.socket&&(this.socket.onmessage=t=>{var n;try{let r=_e(JSON.parse(t.data));r.event&&this.eventListeners.has(r.event)&&((n=this.eventListeners.get(r.event))==null||n.forEach(o=>o(r.data)))}catch(r){console.error("Error parsing WebSocket message:",r)}},this.socket.onclose=t=>{console.log("WebSocket connection closed:",t),setTimeout(()=>{this.reconnect()},this.reconnectInterval)},this.socket.onerror=t=>{console.error("WebSocket error:",t)})}reconnect(){var t,n;if(this.maxReconnectAttempts<=0){console.error("Max reconnect attempts reached, closing WebSocket connection."),(t=this.socket)==null||t.close();return}if(!this.shouldReconnect()){console.error("Should not reconnect, closing WebSocket connection."),(n=this.socket)==null||n.close();return}this.socket&&(this.socket.onmessage=null,this.socket.onclose=null,this.socket.onerror=null,this.socket.close()),this.socket=new WebSocket(this.url),this.setupListeners(),this.maxReconnectAttempts--}send(t,n){if(!this.socket){console.error("WebSocket connection is not open.");return}this.socket.send(JSON.stringify({event:t,data:n}))}on(t,n){this.eventListeners.has(t)||this.eventListeners.set(t,[]);let r=this.eventListeners.get(t);r&&!r.includes(n)&&r.push(n)}close(){var t;(t=this.socket)==null||t.close()}cleanup(){this.close(),this.cleanupCallbacks.forEach(t=>t()),this.cleanupCallbacks=[]}};var Ie=b(R());var zI=_I("showTabHint",!0),Ha=class Ha{constructor({deepdeskUrl:t,version:n=Ha.version||"unknown",locale:r="en-US",token:o,fetch:s,productName:i,createCustomChannel:a,websocketClient:l=vm}){this.inputMediator=null;this.eventListeners={};this.unmountHandlers=[];this.disposeHandlers=[];this.inlineSuggestions=null;this.aboveSuggestions=null;this.floatingMenu=null;this.widgetElement=null;this.widgetRoot=null;this.dynamicThunkObject={};this.queues=new ym;this.isMounted=!1;this.shouldRender=!0;this.loadProfileConfigPromise=null;let c=t.replace(/\/api$/,"");this.deepdeskApi=new xo(c,{token:o,fetch:s}),this.version=n,this.instanceId=Ha.count++;let u={deepdeskAPI:this.deepdeskApi,dynamicThunkObject:this.dynamicThunkObject,middleware:[bI({broadcast:(p,h,m)=>{this.broadcastEvents.send(p,h,m)},emit:(p,h)=>this.emit(p,h),handleAfterSendMessage:p=>this.handleAfterSendMessage(p),logHandlingTime:()=>this.logHandlingTime(),logSendMessage:p=>this.logSendMessage(p),onUpdateShowTabHint:p=>zI.update(p),sendEvent:(p,h)=>this.deepdeskApi.sendEvent(p,h)})]};this.store=wI(u),this.broadcastEvents=new aI({debug:!0,deepdeskUrl:c,eventMap:oT(this.store),createCustomChannel:a}),this.disposeHandlers.push(()=>{this.broadcastEvents.cleanup()}),this.ws=new l({url:`${c}/api/v2/me/realtime`.replace("https","wss"),reconnectInterval:25e3,shouldReconnect:()=>A(this,null,function*(){var p;return(p=Tt(this.state))!=null?p:!1})}),this.whenLoggedIn(()=>this.ws.connect()),this.store.dispatch(Nc(zI.value())),this.store.dispatch(pf({locale:r,adminUrl:c,productName:i}));let f=[];this.ws.on("assistants::user_notification",p=>{if(!p.conversationId)return;let h=()=>{this.conversationId()===p.conversationId&&this.store.dispatch(rP(p))};this.hasConversation()?h():f.push(h)}),this.ws.on("assistants::response_chunk",p=>{if(!p.conversationId)return;let h=()=>{this.conversationId()===p.conversationId&&this.store.dispatch(nP(p))};this.hasConversation()?h():f.push(h)});let d=this.whenConversationLoaded(()=>{var p;this.broadcastEvents.setExternalId((p=this.state.conversation.current)==null?void 0:p.externalId),f.forEach(h=>h()),f.length=0});this.disposeHandlers.push(()=>{this.ws.cleanup(),f.length=0,d()})}get state(){return this.store.getState()}get settings(){return this.state.settings}get selectedTextSuggestion(){var t;return(t=Ns(this.state)[this.state.input.selectedSuggestionIndex])!=null?t:null}hasConversation(){return!!this.state.conversation.current}conversationId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.id}externalId(){if(!this.hasConversation())throw new Error("No conversation loaded");return this.state.conversation.current.externalId}shouldAbort(){return this.state.conversation.isSupported===!1?(ee.warn("Conversation is not supported"),!0):this.hasConversation()?this.state.profile.data?!1:(ee.warn("Profile has not been loaded (yet)"),!0):(ee.warn("No conversation loaded (yet)"),!0)}whenLoggedIn(t){if(Tt(this.state))t();else{let n=this.subscribe(Tt,r=>{r&&t()});this.disposeHandlers.push(()=>{n()})}}login(){return this.store.dispatch(Ji(null)),this.store.dispatch(Jr()),new Promise(t=>{this.whenLoggedIn(()=>t())})}isLoggedIn(){return A(this,null,function*(){return(yield this.store.dispatch(Jr())).payload})}isConversationSupported(t,n){return A(this,null,function*(){return(yield this.store.dispatch(by({externalId:t,options:n}))).payload})}createConversation(t){return A(this,null,function*(){var r;return this.hasConversation()&&this.externalId()!==t.externalId&&this.resetConversation(),(yield this.store.dispatch(gf(P(w({},t),{metadata:(r=t.metadata)!=null?r:{}})))).payload})}getConversationByExternalId(t,n){return A(this,null,function*(){return this.hasConversation()&&this.externalId()!==t&&this.resetConversation(),(yield this.store.dispatch(hf({externalId:t,options:n}))).payload})}upsertConversation(t){return A(this,null,function*(){var r;return this.hasConversation()&&this.externalId()!==t.externalId&&this.resetConversation(),(yield this.store.dispatch(Ey(P(w({},t),{metadata:(r=t.metadata)!=null?r:{}})))).payload})}postMessages(t){return A(this,null,function*(){yield this.store.dispatch(Ty(t))})}updateConversation(t){return A(this,null,function*(){return(yield this.store.dispatch(yf(t))).payload})}resetConversation(){this.store.dispatch(at()),this.loadProfileConfigPromise=null,this.dynamicThunkObject.conversationQuery=null}configure(t){this.store.dispatch(pf(t))}setVisitorInfo(t){this.store.dispatch(q1(t))}setCustomData(t){this.store.dispatch(Y1(t))}setAgentInfo(t,n){return A(this,null,function*(){yield this.store.dispatch(Kl(w(w({},t),n)))})}setAgentSettings(t){return A(this,null,function*(){yield this.store.dispatch(ky(t))})}getAgentSettings(){return A(this,null,function*(){return(yield this.store.dispatch(Ry())).payload})}refresh(){return A(this,null,function*(){if(this.shouldAbort())return Promise.resolve();let t=[];return t.push(this.refreshTextSuggestions()),t.push(this.refreshWidgetSuggestions()),Promise.all(t).then(()=>{})})}syncInputMediator(){this.inputMediator&&this.store.dispatch(wf({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()}))}notifyExternalSuggestion(t){this.store.dispatch(Zn(t))}evaluateAssistant(t,n){return A(this,null,function*(){let u=n||{},{input:r={},transcript:o,showCuesInWidget:s=!0,includeMetadata:i,expectFormat:a}=u,l=re(u,["input","transcript","showCuesInWidget","includeMetadata","expectFormat"]);Object.assign(r,l);let c=yield this.store.dispatch(fr({assistantCode:t,expectFormat:a||"json-schema:cues",transcript:o,includeMetadata:i,input:r,skipState:!s}));if(c.error)throw new Error(c.error.message);return c.payload.output})}evaluateConversationAssistant(t,n){return A(this,null,function*(){yield this.loadProfileConfig();let r=this.state.profile.data;if(!r){ee.warn("Can't evaluate assistant when profile is not loaded yet.");return}let o=FI(r,t);yield Promise.all(o.map(s=>this.queues.push(s,()=>A(this,null,function*(){if(s===r.summarizerAssistantNew)return this.getSummary(w({includeMetadata:!0},n));yield this.evaluateAssistant(s,w({includeMetadata:!0},n))})).catch(i=>{if(i instanceof du){ee.warn(`Queued assistant "${s}" was outdated and dropped`);return}throw i})))})}getSummary(){return A(this,arguments,function*(t={}){var r;if(!this.hasConversation())return ee.warn("No conversation to create summary for."),null;(r=this.state.profile.data)!=null&&r.summarizerAssistantNew||ee.warn("No profile loaded yet, or no summarizer assistant set in profile");let n=yield this.store.dispatch(mo(t));return n.error?(ee.error("Error evaluating summary assistant",n.error),null):n.payload.output})}handleKeyDown(t){let{overlayCollapsed:n,openOverlayWhenTyping:r}=this.state.ui,{textSuggestions:o,selectedSuggestionIndex:s,selection:i}=this.state.input,{inlineSuggestions:a,showTextSuggestions:l}=this.settings,c=a?"below":"above",u=o.length>0;if(this.store.dispatch(D1(Cy(t))),!Ar(this.state)||t.key!=="Tab"&&!l)return;let f=()=>{n||!u||i&&(t.shiftKey||(this.store.dispatch(H1()),t.preventDefault()))},d=()=>{n||!u||a&&s<=0||i&&(t.shiftKey||(this.store.dispatch(B1()),t.preventDefault()))};switch(t.key){case"ArrowUp":c==="below"?d():f();break;case"ArrowDown":{c==="below"?f():d();break}case"Escape":{n||(this.store.dispatch(Sf(-1)),this.store.dispatch(ns({collapse:!0})),this.store.dispatch(Gk(!0)),t.preventDefault());break}case"Tab":{t.preventDefault();let p=na(this.state);if(!p)return;this.store.dispatch(Nc(!1)),this.store.dispatch(Zn({text:p.text,suggestion:p,eventMetrics:{inputType:"tab"},replace:"until-selection-end"}));break}case" ":{if(this.settings.inlineSuggestions||this.state.input.selectedSuggestionIndex===-1)return;let p=na(this.state);if(!p)return;this.store.dispatch(Zn({text:p.text,suggestion:p,eventMetrics:{inputType:"space"},replace:"until-selection-end"}));break}case"Enter":{if(this.settings.inlineSuggestions||t.shiftKey||this.state.input.selectedSuggestionIndex===-1)return;let p=na(this.state);if(!p)return;this.store.dispatch(Zn({text:p.text,suggestion:p,eventMetrics:{inputType:"enter"},replace:"until-selection-end"})),t.preventDefault();break}default:}n&&r&&this.store.dispatch(ns({collapse:!1}))}handleAfterSendMessage(t){this.emit("send-message",t),this.store.dispatch(qo([]))}handlingTimeStart(){this.state.handlingTime.startTime||(ee.info("Start handling time"),this.store.dispatch(fI()))}handlingTimeStop(){this.state.handlingTime.startTime&&(ee.info("Stop handling time"),this.store.dispatch(dm()))}logSendMessage(t){let n=TI(this.state,{version:this.version});n&&(t&&(Object.assign(n,{text:t}),Object.assign(n,{lenTextTotal:t.length})),this.deepdeskApi.sendEvent("Send Message",{conversationId:this.conversationId(),data:n}),this.emit("send-message-event",n))}logHandlingTime(){let t=EI(this.state,{version:this.version});t&&(this.deepdeskApi.sendEvent("Handling Time",{conversationId:this.conversationId(),data:t}),this.store.dispatch(pI()))}notifySubmit(t={}){var n;this.shouldAbort()||(this.store.dispatch(Ds((n=t.text)!=null?n:this.state.input.text)),this.store.dispatch(V1()))}emit(t,n){let r=this.eventListeners[t];r&&r.forEach(o=>{try{o(n)}catch(s){ee.warn(`The following error occurred in deepdeskSDK.on('${t}', handler)`),ee.error(s)}})}on(t,n){return this.eventListeners[t]||(this.eventListeners[t]=[]),this.eventListeners[t].push(n),()=>{this.off(t,n)}}off(t,n){if(!t&&!n){this.eventListeners={};return}let r;this.eventListeners[t]&&(r=this.eventListeners[t].indexOf(n),r>-1&&this.eventListeners[t].splice(r,1))}setConversationQuery(t){this.dynamicThunkObject.conversationQuery=t}setPlatformVariables(t){this.store.dispatch(X1(t))}whenConversationLoaded(t){let n=s=>{var i;return(i=s.conversation.current)==null?void 0:i.id},r=()=>this.loadProfileConfig().then(()=>t());return n(this.state)&&r(),this.subscribe(n,s=>{s&&r()})}overlayContainerFactory(t,n,r,o){let[s,i]=uu(n,r);return s.setAttribute("translate","no"),s.dataset.testid=t,o&&s.classList.add(o),[s,i]}createInlineContainer(t,n){var a;let r=document.createElement("div");r.style.position="absolute",r.style.top="0px",r.style.left="0px",r.style.height="0px",r.style.width="0px";let o=document.createElement("div");o.style.display="none",o.style.position="absolute",o.style.height="0px",o.style.width="0px",o.style.backgroundColor="red",r.appendChild(o);let s=(a=t.ownerDocument.defaultView)==null?void 0:a.frameElement,i=s?s.ownerDocument.defaultView:null;if(s&&(i===window||(i==null?void 0:i.parent)===window)){let[l,c]=uu(s,{appendTo:document.body,onMoveStart:()=>{o.style.display="none"}});l.dataset.testid=n,l.style.zIndex="2",l.appendChild(r),this.unmountHandlers.push(()=>{c()})}else document.body.appendChild(r);return o}createContainer(t,n=document.body){let r=window.getComputedStyle(n),o=document.createElement("div");return ti(o),o.dataset.testid=t,o.style.color=r.color,o.style.fontSize=r.fontSize,o.style.fontFamily=r.fontFamily,o.style.fontVariant=r.fontVariant,o.setAttribute("translate","no"),n.appendChild(o),o}storeMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=JSON.stringify({text:this.state.input.text,metrics:this.state.input.metrics});window.sessionStorage.setItem(t,n),ee.info(`Stored analytics for ${this.conversationId()}`)}catch(t){}}restoreMetrics(){try{let t=`dd-metrics-${this.conversationId()}`,n=window.sessionStorage.getItem(t);if(!n)return;let r=JSON.parse(n);r.text.trim()===this.state.input.text.trim()?(ee.info(`Restored metrics for ${this.conversationId()}`),this.store.dispatch(U1(r.metrics))):ee.warn(`Metrics mismatch, disregarding stored metrics for ${this.conversationId()}`),window.sessionStorage.removeItem(t)}catch(t){}}mount(t,n={}){if(this.isMounted)throw new Error("[Deepdesk] This instance was already mounted. Make sure to unmount before you remount.");if(!pm(t))throw new Error("[Deepdesk] Only mount on textarea or contentEditable div.");if(!this.shouldRender)return;let d=n,{customStyles:r,closestScrollSelector:o,floatingMenuParent:s,appendOverlayTo:i,inputMediator:a}=d,l=re(d,["customStyles","closestScrollSelector","floatingMenuParent","appendOverlayTo","inputMediator"]),c={customStyles:r,closestScrollSelector:o,floatingMenuParent:s,appendOverlayTo:i};this.configure(l),this.settings.automaticHandlingTime&&this.setupHandlingTime(t),ti(t),this.inputMediator=a||(ni(t)?new ui(t):new ci(t)),this.inputMediator.on("change",({plainText:p,rawHTML:h})=>{this.store.dispatch(wf({text:p,html:h}))}),this.inputMediator.on("keyup",p=>{this.store.dispatch(F1(Cy(p)))}),this.inputMediator.on("keydown",p=>{this.handleKeyDown(p)}),this.inputMediator.on("paste",({pastedText:p,selectionText:h})=>{this.store.dispatch(z1({text:p,selectionText:h}))}),this.inputMediator.on("cut",({selectionText:p})=>{this.store.dispatch(_1(p))});let u;this.inputMediator.on("selection",p=>{clearTimeout(u),p===null?u=setTimeout(()=>{p!==null&&this.store.dispatch(Ef(p))},500):this.store.dispatch(Ef(p))}),this.unmountHandlers.push(()=>{clearTimeout(u)}),this.inputMediator.on("disabled",()=>{var p;(p=this.inputMediator)==null||p.deactivate(),this.configure({visible:!1})}),this.inputMediator.on("enabled",()=>{this.inputMediator&&(this.configure({visible:!0}),this.inputMediator.activate())}),this.inputMediator.on("submit",()=>{this.settings.detectSubmit&&this.notifySubmit()}),this.inputMediator.on("blur",()=>{this.store.dispatch(Tp(!1))}),this.inputMediator.on("focus",()=>{this.store.dispatch(Tp(!0))}),this.renderSuggestions(t,c),this.subscribe(Vl("inlineSuggestions"),()=>{this.renderSuggestions(t,c)});let f=this.renderOverlays(n);this.unmountHandlers.push(()=>{f.unmount()}),this.store.dispatch(wf({text:this.inputMediator.getText(),html:this.inputMediator.getHTML()})),this.store.dispatch(Ef(this.inputMediator.getSelection())),this.store.dispatch(Tp(this.inputMediator.isFocused)),this.unmountHandlers.push(()=>{this.state.input.text!==""&&this.storeMetrics()}),this.whenConversationLoaded(()=>{this.restoreMetrics(),this.syncInputMediator(),this.refreshTextSuggestions()}),this.isMounted=!0}subscribe(t,n){let r=t(this.store.getState());return this.store.subscribe(()=>{let o=t(this.store.getState());o!==r&&(r=o,n(r))})}unmount(){var t,n,r,o;(t=this.inlineSuggestions)==null||t.unmount(),(n=this.aboveSuggestions)==null||n.unmount(),(r=this.floatingMenu)==null||r.unmount(),this.unmountHandlers.forEach(s=>s()),this.unmountHandlers=[],(o=this.inputMediator)==null||o.dispose(),this.isMounted=!1}dispose(){this.unmount(),this.unmountWidget(),this.disposeHandlers.forEach(t=>t()),this.disposeHandlers=[],this.off()}renderSuggestions(t,n){var r,o,s;(r=this.floatingMenu)==null||r.unmount(),(o=this.inlineSuggestions)==null||o.unmount(),(s=this.aboveSuggestions)==null||s.unmount(),this.settings.floatingMenu&&(this.floatingMenu=this.renderFloatingMenu(t,n)),this.settings.inlineSuggestions?this.inlineSuggestions=this.renderInlineSuggestions(t,n):this.aboveSuggestions=this.renderAboveSuggestions(t,n)}renderInlineSuggestions(t,n){let{customStyles:r}=n,o=this.createInlineContainer(t,"deepdesk-caret"),s=(0,us.createRoot)(o);s.render((0,Ie.jsx)(os,{store:this.store,customStyles:r,children:(0,Ie.jsx)(Yo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(oR,{})})}));let i=a=>{a?(o.style.display="block",o.style.top=`${a.top}px`,o.style.left=`${a.left}px`):o.style.display="none"};return this.inputMediator.on("caretposition",i),{unmount:()=>{var a;(a=this.inputMediator)==null||a.off("caretposition",i),s.unmount(),o.remove()}}}renderAboveSuggestions(t,n){let{customStyles:r,closestScrollSelector:o,appendOverlayTo:s}=n,i=o&&B0(t,o)||void 0,[a,l]=this.overlayContainerFactory("deepdesk-tab-completion",i||t,{appendTo:s,closestScrollElement:i,mirrorOverflow:!0,onRemove:()=>this.unmount()},r==null?void 0:r.rootNode),[c,u]=this.overlayContainerFactory("deepdesk-suggestions-overlay",i||t,{appendTo:s},r==null?void 0:r.suggestionsRootNode),f=(0,us.createRoot)(a);f.render((0,Ie.jsx)(os,{store:this.store,customStyles:r,children:(0,Ie.jsx)(Yo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(NR,{inputElement:t})})}));let d=(0,us.createRoot)(c);return d.render((0,Ie.jsx)(os,{store:this.store,customStyles:r,children:(0,Ie.jsx)(Yo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(pR,{onLogIn:()=>this.loginViaPopup().catch(p=>ee.warn(p.message))})})})),{unmount(){f.unmount(),d.unmount(),l(),u()}}}renderFloatingMenu(t,n){let{customStyles:r,closestScrollSelector:o,appendOverlayTo:s,floatingMenuParent:i}=n,a=o&&B0(t,o)||void 0,[l,c]=this.overlayContainerFactory("floating-menu",a||t,{appendTo:i!=null?i:s},r==null?void 0:r.floatingMenuParent),u=(0,us.createRoot)(l);return u.render((0,Ie.jsx)(os,{store:this.store,customStyles:r,children:(0,Ie.jsx)(Yo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(jk,{onLogIn:()=>this.loginViaPopup().catch(f=>ee.warn(f.message))})})})),{unmount(){u.unmount(),c()}}}renderOverlays(t){let{customStyles:n}=t,r=this.createContainer("deepdesk-overlays"),o=(0,us.createRoot)(r);return o.render((0,Ie.jsx)(os,{store:this.store,customStyles:n,children:(0,Ie.jsx)(Yo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(Hk,{})})})),{unmount(){o.unmount(),r.remove()}}}renderWidget(t,n={}){if(this.widgetElement&&ee.warn("A widget was already rendered for this instance. Make sure to unmountWidget before rerendering"),!this.shouldRender)return;let{customStyles:r,showImages:o,isEmbedded:s}=n;this.widgetElement=t,this.configure({showImages:o,isEmbedded:s}),this.widgetRoot=(0,us.createRoot)(t),this.widgetRoot.render((0,Ie.jsx)(os,{store:this.store,customStyles:r,children:(0,Ie.jsx)(Yo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(tI,{assistantOptions:n.assistantOptions,knowledgeAssistOptions:n.knowledgeAssist,onLogIn:()=>this.loginViaPopup().catch(i=>ee.warn(i.message))})})}))}unmountWidget(){var t,n;(n=(t=this.widgetRoot)==null?void 0:t.unmount)==null||n.call(t),this.widgetRoot=null,this.widgetElement=null}renderKnowledgeAssistantWidget(t,n,r={}){let{customStyles:o,initialQuestion:s}=r,i=(0,us.createRoot)(n);return i.render((0,Ie.jsx)(os,{store:this.store,customStyles:o,children:(0,Ie.jsx)(Yo,{broadcastEvents:this.broadcastEvents,children:(0,Ie.jsx)(A0,{children:(0,Ie.jsxs)(im,{assistantCode:t,initialQuestion:s,evaluateKnowledgeAssistFn:r.isLegacyKnowledgeAssist?Kc:Gc,children:[(0,Ie.jsx)(xi,{children:(0,Ie.jsx)(lm,{title:r.title,emptyState:r.emptyState})}),(0,Ie.jsx)(I0,{children:(0,Ie.jsx)(am,{})})]})})})})),{unmount(){i.unmount()}}}setupHandlingTime(t){let n=hm(t,({isVisible:r})=>{r?this.handlingTimeStart():this.handlingTimeStop()});this.unmountHandlers.push(()=>{this.handlingTimeStop(),n()}),this.whenConversationLoaded(()=>{this.handlingTimeStart()})}handleError(t){CI(t)&&t.message==="Unauthorized"&&this.login()}loadProfileConfig(){return this.loadProfileConfigPromise?this.loadProfileConfigPromise:(this.loadProfileConfigPromise=Promise.resolve().then(()=>A(this,null,function*(){yield this.store.dispatch(cc());let t=Hs(this.state);t&&this.store.dispatch(pf({showSearch:t.search,showImageSearch:t.imageSearch,showEntitiesCommand:t.entitiesCommand,showSummaryCommand:!!t.summarizerAssistantNew,showKnowledgeSearch:!!t.knowledgeAssistantNew||!!t.knowledgeAssistant,recommendTextSuggestions:t.recommendTextSuggestions}))})),this.loadProfileConfigPromise)}loginViaPopup(t){return A(this,null,function*(){return new Promise((n,r)=>{let o=new MessageChannel,s=o.port1,i=this.settings.adminUrl,a=new URL(t!=null&&t.url?t==null?void 0:t.url:`${i}/platform/sso/`);a.searchParams.append("redirect","/sdk/popup/close.html");let l=!1,c=()=>{u&&!u.closed&&u.close(),window.removeEventListener("message",f),clearInterval(d)};s.onmessage=p=>A(this,null,function*(){var h,m;if((h=p.data)!=null&&h.jwt)try{yield this.deepdeskApi.exchangeTokenForAccessCookie((m=p.data)==null?void 0:m.jwt),yield this.isLoggedIn(),this.broadcastEvents.send(ql),l=!0,o.port1.close(),n()}catch(x){console.error(x),r(x)}finally{l=!0,c()}});let u=window.open(a.toString(),"deepdesk-login","scrollbars=no,left=100,top=150,width=500,height=500");u===null&&r(new Error("Popup blocked by browser"));let f=p=>A(this,null,function*(){var h;if(p.origin===a.origin)switch((h=p.data)==null?void 0:h.type){case"deepdesk-popup-loaded":{try{let m=JSON.stringify({type:"deepdesk-popup-create-channel"});u==null||u.postMessage(m,a.origin,[o.port2])}catch(m){ee.error("Error posting message to popup",m),r(m)}break}case"deepdesk-popup-error":{c(),p.data.message==="Timeout"&&ee.warn("Popup timed out. Check if the account's platform url is configured correctly."),r(new Error(p.data.message));break}}});window.addEventListener("message",f);let d=setInterval(()=>{u&&!u.closed||(c(),l||r(new Error("Popup closed by user")))},200);this.disposeHandlers.push(c)})})}translateMessages(t){return this.deepdeskApi.translateMessages(t)}refreshTextSuggestions(){return A(this,null,function*(){this.isMounted&&(yield this.store.dispatch(wp()))})}refreshWidgetSuggestions(){return A(this,null,function*(){if(!this.widgetRoot)return;let{uiConfig:t}=this.state.profile.data;if(!t.widget)return;let n=uc(this.state);try{n.forEach(({type:r})=>{switch(r){case"entities":this.store.dispatch(lr());break;case"pinned-messages":case"sticky-messages":break;default:Mu.includes(r)||this.store.dispatch(cr(r))}})}catch(r){this.handleError(r)}})}};Ha.version="18.1.2-beta.2",Ha.count=0;var fu=Ha;function s5(e){return A(this,null,function*(){var o,s,i;let n=yield((o=e.fetch)!=null?o:window.fetch)(e.url),r=yield n.blob();return new File([r],e.name,{type:(i=(s=e.mimeType)!=null?s:n.headers.get("Content-Type"))!=null?i:"image/jpeg"})})}function HI(e,t){return A(this,null,function*(){let n=yield s5(t),r=new Event("change",{bubbles:!0,cancelable:!0});try{Object.defineProperty(e,"files",{configurable:!0,get:()=>[n]}),e.dispatchEvent(r)}finally{Object.hasOwn(e,"files")&&delete e.files}})}function BI(e,t,n){return A(this,null,function*(){yield new xo(e).authenticateWithKey(t,n)})}function UI(e){return e.replace(/\[([\w\s\d]+)\]\((https?:\/\/[^\s]+)\)/g,'<a href="$2" target="_blank" rel="noreferrer">$1</a>')}function VI(r,o){return A(this,arguments,function*(e,t,n={}){var f,d;let{value:s}=e,{start:i,end:a}=(f=n.replace)!=null?f:{start:0,end:s.length},l=`${s.slice(0,i)}${t}${s.slice(a)}`,c=(d=n.selectionAfter)!=null?d:{start:i+t.length,end:i+t.length},u=()=>{if(n.setValue)return n.setValue(l);e.value=l};return Promise.resolve(u()).then(()=>{e.selectionStart=c.start,e.selectionEnd=c.end,e.blur(),e.focus()})})}function $I(r,o){return A(this,arguments,function*(e,t,n={}){let s=n.replace?ls(e,n.replace.start,n.replace.end):_a(e),i,a=()=>{if(n.setRange)return n.setRange(s.cloneRange());s.deleteContents(),i=document.createElement("span"),s.insertNode(i),n.insertBRs!==!1?t.split(`
83
83
  `).reverse().forEach((l,c)=>{c>0&&s.insertNode(document.createElement("br")),s.insertNode(document.createTextNode(l))}):s.insertNode(document.createTextNode(t))};return Promise.resolve(a()).then(()=>{try{if(n.selectionAfter!==!1){e.focus();let l=n.selectionAfter?ls(e,n.selectionAfter.start,n.selectionAfter.end):(s.collapse(!1),s),c=window.getSelection();c==null||c.removeAllRanges(),c==null||c.addRange(l)}if(!i)return;i.scrollIntoView&&i.scrollIntoView({block:"nearest",inline:"nearest"})}finally{i&&i.remove()}})})}function i5(e){let t=document.createElement("template");return t.innerHTML=e.replace(/(\[([^\]]+)])\(([^)]+)\)/g,'<a href="$3" target="_blank" rel="noopener noreferrer">$2</a>'),t.content}function a5(e){let t=document.createDocumentFragment();return e.split(`
84
84
  `).forEach((n,r)=>{r>0&&t.appendChild(document.createElement("br"));let o={index:0},s=0;for(;o=n.slice(s).match(/(\[([^\]]+)])\(([^)]+)\)/);){let i=document.createElement("a");i.href=o[3],i.setAttribute("target","_blank"),i.setAttribute("rel","noopener noreferrer"),i.appendChild(document.createTextNode(o[2])),t.appendChild(document.createTextNode(n.slice(s,s+o.index))),t.appendChild(i),s=s+o.index+o[0].length}t.appendChild(document.createTextNode(n.slice(s)))}),t}function jI(e,t){let n=e.parentElement;if(!n){console.warn("No insert point found");return}let{display:r}=window.getComputedStyle(n);r.includes("block")||r==="table-cell"?n==null||n.insertBefore(t,e.nextSibling):jI(n,t)}function WI(o,s){return A(this,arguments,function*(e,t,{isBlock:n,isHTML:r}={}){let i;e.dispatchEvent(new InputEvent("beforeinput",{inputType:"insertText",data:t,bubbles:!0,cancelable:!0}));let a=()=>{var d;let l=(d=e.ownerDocument.defaultView)!=null?d:window,c=l.getSelection();if((!c||c.rangeCount===0)&&(e.focus(),c=l.getSelection()),!c||c.rangeCount===0)return;let u=c.getRangeAt(0);if(!u)return;i=document.createElement("span"),u.insertNode(i);let f=r?i5(t):a5(t);n?jI(u.startContainer,f):(u.insertNode(f),u.collapse(!1))};return Promise.resolve(a()).then(()=>{if(e.dispatchEvent(new InputEvent("input",{inputType:"insertText",data:t,bubbles:!0,cancelable:!0})),e.focus(),!!i)try{i.scrollIntoView&&i.scrollIntoView({block:"nearest",inline:"nearest"})}finally{i&&i.remove()}})})}return sA(l5);})();
85
85
  /*! Bundled license information: