@knowbl_ai/nexus-chat 1.10.0 → 1.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/types/store/chatStore.d.ts +2 -0
- package/types/store/chatStore.d.ts.map +1 -1
- package/types/types/index.d.ts +2 -0
- package/types/types/index.d.ts.map +1 -1
- package/widget.js +10 -10
- package/widget.js.map +1 -1
- package/widget.umd.js +1 -1
- package/widget.umd.js.map +1 -1
package/widget.js
CHANGED
|
@@ -22,7 +22,7 @@ return be("div",{class:"ncw:absolute ncw:inset-0 ncw:flex ncw:items-center ncw:j
|
|
|
22
22
|
/* @__PURE__ */be("div",{className:"ncw:h-2 ncw:w-2 ncw:animate-bounce ncw:rounded-full ncw:bg-current",style:{animationDelay:"300ms"}})]})]}):null}var Xi=class extends Error{constructor(e,t,n){super(e),this.actionId=t,this.actionType=n,this.name="ActionHandlerError"}},es=class{constructor(e,t){this.store=e,this.eventEmitter=t}async execute(e,t){const{type:n}=t.action;try{switch(n){case"trigger_handover":await this.handleTriggerHandover(e,t);break;case"trigger_escalation_prompt":await this.handleTriggerEscalationPrompt(e,t);break;case"open_url":await this.handleOpenUrl(e,t);break;case"send_event":await this.handleSendEvent(e,t);break;case"send_query":await this.handleSendQuery(e,t);break;default:throw new Xi(`Unknown action type: ${n}`,e,n)}}catch(r){if(r instanceof Xi)throw r;throw new Xi(r instanceof Error?r.message:"Action execution failed",e,n)}}handleTriggerHandover(e,t){const{payload:n={}}=t.action;if(this.store.events.value.some(e=>"agent_handover"===e.kind))throw new Xi("Already in agent handover session",e,"trigger_handover");const r={kind:"agent_handover",agentInfo:{name:"Support Agent"},reason:n.reason||"user_requested",message:n.message||"Connecting you to a live agent...",timestamp:/* @__PURE__ */new Date};return this.store.addEvent(r),this.eventEmitter&&this.eventEmitter.emit("handover",{timestamp:/* @__PURE__ */(new Date).toISOString(),sessionId:this.store.currentSessionId.value,reason:n.reason||"user_requested",priority:n.priority||"normal",metadata:n.metadata}),Promise.resolve()}handleTriggerEscalationPrompt(e,t){const n=t.action;return this.eventEmitter&&this.eventEmitter.emit("escalationPrompted",{timestamp:/* @__PURE__ */(new Date).toISOString(),sessionId:this.store.currentSessionId.value,reason:n.escalationReason||"consecutive_out_of_scope",metadata:{confidence:n.confidence,actionId:e}}),Promise.resolve()}handleOpenUrl(e,t){const{url:n,target:r="_blank"}=t.action;try{const t=new URL(n);if(!["http:","https:","tel:","mailto:"].includes(t.protocol))throw new Xi(`Protocol not allowed: ${t.protocol}`,e,"open_url")}catch(i){throw new Xi(`Invalid URL: ${n}`,e,"open_url")}const o={kind:"system",type:t.behavior?.postClickBehavior?.systemEventType||"info",message:t.behavior?.postClickBehavior?.systemEventMessage||`Opening URL: ${n}`,timestamp:/* @__PURE__ */new Date,metadata:{actionId:e,actionType:"open_url",visibleToUser:t.behavior?.postClickBehavior?.showSystemEvent||!1,url:n,target:r}};this.store.addEvent(o);try{window.open(n,r,"noopener,noreferrer")||console.warn("[ActionHandler] window.open() returned null - popup may be blocked:",n)}catch(i){throw new Xi(`Failed to open URL: ${i instanceof Error?i.message:"Unknown error"}`,e,"open_url")}return Promise.resolve()}handleSendEvent(e,t){const{eventName:n,eventData:r={}}=t.action;if(!this.eventEmitter)throw new Xi("Event emitter not available",e,"send_event");const o={kind:"system",type:t.behavior?.postClickBehavior?.systemEventType||"info",message:t.behavior?.postClickBehavior?.systemEventMessage||`Custom event triggered: ${n}`,timestamp:/* @__PURE__ */new Date,metadata:{actionId:e,actionType:"send_event",visibleToUser:t.behavior?.postClickBehavior?.showSystemEvent||!1,eventName:n,eventData:r}};return this.store.addEvent(o),this.eventEmitter.emit("customAction",{timestamp:/* @__PURE__ */(new Date).toISOString(),sessionId:this.store.currentSessionId.value,actionId:e,eventName:n,eventData:r}),Promise.resolve()}handleSendQuery(e,t){const{queryText:n,displayText:r}=t.action;if(!this.eventEmitter)throw new Xi("Event emitter not available",e,"send_query");return this.eventEmitter.emit("sendQuery",{timestamp:/* @__PURE__ */(new Date).toISOString(),sessionId:this.store.currentSessionId.value,actionId:e,queryText:n,displayText:r}),Promise.resolve()}},ts={type:"svg",content:'<svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">\n <path d="M8 1.5a6.5 6.5 0 100 13 6.5 6.5 0 000-13zm2.854 4.854l-3.5 3.5a.5.5 0 01-.708 0l-1.5-1.5a.5.5 0 11.708-.708L7 8.793l3.146-3.147a.5.5 0 01.708.708z" />\n </svg>'};function ns({actions:e,messageId:t,messageRole:n,sessionId:r,actionStates:o=[],onActionClick:i,eventEmitter:s,readOnly:a}){const[l,c]=ie(/* @__PURE__ */new Set),d=e=>o.find(t=>t.actionId===e),u=e=>!!a||(!!d(e.id)?.disabled||!!e.behavior?.disabled),p=e.alignment??"center",h=e.spacing??"8px";/* @__PURE__ */
|
|
23
23
|
return be("div",{class:`ncw:flex ncw:flex-wrap ncw:mt-3 ${{left:"ncw:justify-start",center:"ncw:justify-center",right:"ncw:justify-end"}[p]}`,style:{gap:h},children:e.actions.map(e=>{const n=u(e),o=l.has(e.id),p=(e=>{if(a)return"Actions are disabled in read-only mode";const t=d(e.id);return"used"===t?.disabledReason?"This action has already been used":"expired"===t?.disabledReason?"This action has expired":"outdated"===t?.disabledReason?"This action is no longer available":e.behavior?.disabledReason?e.behavior.disabledReason:void 0})(e),h=e.visibility??{},w=h.showIcon??!0,g=h.showLabel??!0,m=h.showTooltip??!0,f=e.style??{},v=f.size??"medium",b=f.backgroundColor??"#0066cc",y=f.disabledBackgroundColor,x=f.iconColor??"#ffffff",k=f.textColor??"#ffffff",_=f.hoverBackgroundColor??"#0052a3",S=f.borderRadius??"8px",C=f.border,I=f.borderWidth,T=f.borderColor,$=f.borderStyle,E=m?n&&p||h.tooltipText||e.label:void 0;/* @__PURE__ */
|
|
24
24
|
return be("button",{type:"button",onClick:()=>{(async e=>{if(!u(e)&&!l.has(e.id)){c(t=>new Set(t).add(e.id));try{s&&s.emit("actionClick",{timestamp:/* @__PURE__ */(new Date).toISOString(),sessionId:r,messageId:t,actionId:e.id,actionType:e.action.type,actionLabel:e.label}),i&&await i(e.id,e)}catch(n){console.error("Action execution error:",n),s&&s.emit("error",{timestamp:/* @__PURE__ */(new Date).toISOString(),sessionId:r,type:"action",message:n instanceof Error?n.message:"Action failed",details:{actionId:e.id,actionType:e.action.type}})}finally{c(t=>{const n=new Set(t);return n.delete(e.id),n})}}})(e)},disabled:n||o,title:E,class:`ncw:inline-flex ncw:items-center ncw:justify-center ncw:font-medium ncw:transition-colors disabled:ncw:opacity-50 ${{small:"ncw:px-3 ncw:py-1.5 ncw:text-xs",medium:"ncw:px-4 ncw:py-2 ncw:text-sm",large:"ncw:px-6 ncw:py-3 ncw:text-base"}[v]} ${n||o?"ncw:cursor-not-allowed":"ncw:cursor-pointer"}`,style:{backgroundColor:n&&y?y:b,color:k,borderRadius:S,border:C||(I||T||$?`${I||"0"} ${$||"solid"} ${T||"transparent"}`:"none"),outline:"none",cursor:n||o?"not-allowed":"pointer"},onMouseEnter:e=>{n||o||(e.currentTarget.style.backgroundColor=_)},onMouseLeave:e=>{n||o||(e.currentTarget.style.backgroundColor=b)},children:[o?/* @__PURE__ */be("span",{class:"ncw:mr-2 ncw:inline-block ncw:w-4 ncw:h-4 ncw:border-2 ncw:border-white ncw:border-t-transparent ncw:rounded-full ncw:animate-spin"}):(()=>{if(!w||!e.icon)return null;const t={width:"small"===v?"14px":"large"===v?"20px":"16px",height:"small"===v?"14px":"large"===v?"20px":"16px",fill:x,color:x};return"emoji"===e.icon.type?/* @__PURE__ */be("span",{class:"ncw:mr-2",style:{fontSize:t.width},children:e.icon.content}):"url"===e.icon.type?/* @__PURE__ */be("img",{src:e.icon.content,alt:"",class:"ncw:mr-2",style:t}):/* @__PURE__ */be("span",{class:"ncw:mr-2 ncw:inline-flex ncw:items-center",style:t,dangerouslySetInnerHTML:{__html:e.icon.content}})})(),g&&/* @__PURE__ */be("span",{children:e.label})]},e.id)})})}function rs({content:e,messageId:t,config:n,sessionId:r,eventEmitter:o,readOnly:i,readOnlyAllowCopy:s=!0}){const[a,l]=ie(!1),{enabled:c=!1,position:d="inline",showLabel:u=!0,showIcon:p=!0,style:h="default",size:w="small",className:g="",iconColor:m,textColor:f,backgroundColor:v,hoverBackgroundColor:b,copyIcon:y,copiedIcon:x,copiedDuration:k=2e3,tooltipText:S="Copy message",copiedText:C="Copied"}=n;if(!c||i&&!s)return null;const I={};v&&(I["--ncw-bg-color"]=v),b&&(I["--ncw-hover-bg-color"]=b),f&&(I["--ncw-text-color"]=f),m&&(I["--ncw-icon-color"]=m);const T=v||b||f||m,$=/* @__PURE__ */be("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"1.5",class:m?"ncw-custom-icon-color":"",children:[/* @__PURE__ */be("rect",{x:"4",y:"4",width:"7",height:"7",rx:"1"}),/* @__PURE__ */be("path",{d:"M3 10V3a1 1 0 011-1h7"})]}),E=(e,t)=>e?e.startsWith("http")?/* @__PURE__ */be("img",{src:e,alt:"",class:"ncw:w-[14px] ncw:h-[14px]"}):e.startsWith("<svg")?/* @__PURE__ */be("div",{dangerouslySetInnerHTML:{__html:e}}):t:t;/* @__PURE__ */
|
|
25
|
-
return be("button",{onClick:()=>{(async()=>{try{if(navigator.clipboard&&window.isSecureContext)await navigator.clipboard.writeText(e);else{const t=document.createElement("textarea");t.value=e,t.style.position="fixed",t.style.left="-999999px",t.style.top="-999999px",document.body.appendChild(t),t.focus(),t.select();try{document.execCommand("copy")}finally{t.remove()}}l(!0),o&&o.emit("copy",{timestamp:/* @__PURE__ */(new Date).toISOString(),sessionId:r,content:e,messageId:t}),setTimeout(()=>l(!1),k)}catch(n){console.error("Failed to copy content:",n)}})()},class:`ncw:inline-flex ncw:items-center ncw:gap-1 ncw:rounded ncw:transition-all ncw:duration-200 ${{small:"ncw:px-2 ncw:py-1 ncw:text-xs",medium:"ncw:px-3 ncw:py-1.5 ncw:text-sm",large:"ncw:px-4 ncw:py-2 ncw:text-base"}[w]} ${T?"ncw-copy-button-custom":{default:"ncw:bg-gray-100 hover:ncw:bg-gray-200 dark:ncw:bg-gray-700 dark:hover:ncw:bg-gray-600",minimal:"hover:ncw:bg-gray-100 dark:hover:ncw:bg-gray-700",outline:"ncw:border ncw:border-gray-300 dark:ncw:border-gray-600 hover:ncw:bg-gray-50 dark:hover:ncw:bg-gray-800",ghost:"hover:ncw:bg-gray-100/50 dark:hover:ncw:bg-gray-700/50"}["top-right"===d&&"default"===h?"ghost":h]} ${{top:"ncw:mb-2",bottom:"ncw:mt-2",inline:"ncw:ml-2 ncw:inline-flex","top-right":"ncw:absolute ncw:top-1 ncw:right-1 ncw:z-10"}[d]} ${"top-right"===d?"ncw:opacity-60 hover:ncw:opacity-100":""} ${g} `,style:I,title:a?C:S,children:/* @__PURE__ */be(_,a?{children:[p&&E(x,/* @__PURE__ */be("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"2",class:"ncw:text-green-600 dark:ncw:text-green-400",children:/* @__PURE__ */be("path",{d:"M2 7l3 3 7-7",strokeLinecap:"round",strokeLinejoin:"round"})})),u&&/* @__PURE__ */be("span",{class:"ncw:text-green-600 dark:ncw:text-green-400",children:C})]}:{children:[p&&E(y,$),u&&/* @__PURE__ */be("span",{class:f?"ncw-custom-text-color":"ncw:text-gray-500 dark:ncw:text-gray-400",children:"Copy"})]})})}function os(e,t){const n={small:"16",medium:"18",large:"20"}[t],r=e.trim();return/^<svg[\s>]/i.test(r)?/* @__PURE__ */be("span",{class:"ncw:inline-flex ncw:items-center ncw:justify-center",dangerouslySetInnerHTML:{__html:/<svg[^>]*(?<!-)width=/i.test(r)?r:r.replace(/^<svg/i,`<svg width="${n}" height="${n}"`)}}):/* @__PURE__ */be("span",{children:e})}function is({message:e,config:t,store:n,eventEmitter:r,onFeedbackChange:o,readOnly:i}){const s=t.features?.feedback,[a,l]=ie(e.feedback?.value??null),[c,d]=ie(!1),[u,p]=ie(!1),[h,w]=ie(!1),[g,m]=ie(!1),[f,v]=ie(null),[b,y]=ie(""),[x,k]=ie(e.feedback?.comment);if(!s?.enabled||i)return null;const S="assistant"===e.role,C="agent"===e.role,I=s.showOnAssistantMessages??!0,T=s.showOnAgentMessages??!0;if(S&&!I||C&&!T)return null;if(e.isStreaming)return null;const $=s.style||"thumbs",E=s.position||"inline",A=s.buttons?.size||"small",z=s.buttons?.showLabels??!1,R=s.buttons?.animation||"scale",M=s.behavior?.allowChange??!0,L=s.commentInput,O={small:"ncw:text-sm ncw:p-1",medium:"ncw:text-base ncw:p-1.5",large:"ncw:text-lg ncw:p-2"},D={none:"",scale:"ncw:transition-transform hover:ncw:scale-110",fade:"ncw:transition-opacity hover:ncw:opacity-80"},B=async(i,c)=>{if(null===a||M){if(s.commentInput&&void 0===c)return v(i),void m(!0);if(m(!1),v(null),d(!0),(await async function(e,t,n,r,o,i){let s;try{const a=n.features?.feedback,l=(a?.api?.endpoint||"/query/feedback").replace(/^\/+/,""),c=a?.api?.includeContext??!1,d={messageId:e,feedbackValue:t,comment:i?.comment,experienceId:n.experienceId,sessionId:r.currentSessionId.value,userId:n.advanced?.userId,timestamp:/* @__PURE__ */(new Date).toISOString(),metadata:{source:"widget",widgetId:n.advanced?.widgetId,messageContent:i?.messageContent,messageRole:i?.messageRole,...n.advanced?.metadata||{},...a?.api?.additionalData||{}},...c&&i?.conversationContext?{conversationContext:i.conversationContext}:{}},u=Ee(n),p=Le(n.apiUrl||""),h=15e3,w=new AbortController;s=setTimeout(()=>w.abort(),h);const g=await fetch(`${p}/${l}`,{method:"POST",headers:u,body:JSON.stringify(d),signal:w.signal,credentials:n.advanced?.credentials});if(clearTimeout(s),!g.ok){const n=await g.text();return console.error("Feedback submission failed:",n),o&&o.emit("error",{timestamp:/* @__PURE__ */(new Date).toISOString(),sessionId:r.currentSessionId.value,type:"feedback",message:`Failed to submit feedback: ${n}`,details:{messageId:e,feedbackValue:t}}),{success:!1,error:`Failed to submit feedback: ${n}`}}return{success:!0}}catch(a){return clearTimeout(s),console.error("Error sending feedback:",a),o&&o.emit("error",{timestamp:/* @__PURE__ */(new Date).toISOString(),sessionId:r.currentSessionId.value,type:"feedback",message:a instanceof Error?a.message:"Unknown error occurred",stack:a instanceof Error?a.stack:void 0,details:{messageId:e,feedbackValue:t}}),{success:!1,error:a instanceof Error?a.message:"Unknown error occurred"}}}(e.metadata?.queryId||e.id,i,t,n,r,{comment:c??(b||void 0),messageContent:e.content,messageRole:e.role,conversationContext:s.api?.includeContext?n.events.value.filter(e=>"message"===e.kind).map(e=>({role:e.role,content:e.content,timestamp:e.timestamp})):void 0})).success){l(i),k(c||b||void 0),r&&r.emit("feedback",{timestamp:/* @__PURE__ */(new Date).toISOString(),sessionId:n.currentSessionId.value,rating:i,messageId:e.id,comment:c||b||void 0});const t={value:i,comment:c||b||void 0,timestamp:/* @__PURE__ */new Date};o&&o(e.id,t),(s.behavior?.showConfirmation??1)&&(w(!0),setTimeout(()=>{w(!1)},s.behavior?.confirmationDuration||2e3))}d(!1),m(!1),v(null),y("")}},P=async()=>{p(!0),(await async function(e,t,n,r){const o=Le(t.apiUrl||""),i=Ee(t),s=new AbortController,a=setTimeout(()=>s.abort(),15e3);try{const r=await fetch(`${o}/query/feedback/${e}`,{method:"DELETE",headers:i,body:JSON.stringify({sessionId:n.currentSessionId.value,experienceId:t.experienceId,userId:t.advanced?.userId}),signal:s.signal,credentials:t.advanced?.credentials});if(clearTimeout(a),!r.ok){const e=await r.text();return console.error("Feedback deletion failed:",e),{success:!1,error:`Failed to delete feedback: ${e}`}}return{success:!0}}catch(l){return clearTimeout(a),console.error("Error deleting feedback:",l),r&&r.emit("error",{timestamp:/* @__PURE__ */(new Date).toISOString(),sessionId:n.currentSessionId.value,type:"feedback",message:l instanceof Error?l.message:"Unknown error occurred",details:{queryId:e}}),{success:!1,error:l instanceof Error?l.message:"Unknown error occurred"}}}(e.metadata?.queryId||e.id,t,n,r)).success&&(l(null),y(""),k(void 0),o&&o(e.id,void 0)),p(!1)};if("thumbs"===$){const e=s.buttons?.positive,n=s.buttons?.negative,r="positive"===a||"positive"===f,o="negative"===a||"negative"===f,i=r?e?.activeIcon??e?.icon??"👍":e?.icon??"👍",l=o?n?.activeIcon??n?.icon??"👎":n?.icon??"👎",d=e?.label||"Helpful",p=n?.label||"Not helpful",w=!!(e?.color||e?.activeColor||e?.backgroundColor||e?.activeBackgroundColor),b=!!(n?.color||n?.activeColor||n?.backgroundColor||n?.activeBackgroundColor),y=null!==f?s.commentPrompts?.[f]:void 0,k=y?.prompt??s.commentPrompt,S=y?.placeholder;/* @__PURE__ */
|
|
25
|
+
return be("button",{onClick:()=>{(async()=>{try{if(navigator.clipboard&&window.isSecureContext)await navigator.clipboard.writeText(e);else{const t=document.createElement("textarea");t.value=e,t.style.position="fixed",t.style.left="-999999px",t.style.top="-999999px",document.body.appendChild(t),t.focus(),t.select();try{document.execCommand("copy")}finally{t.remove()}}l(!0),o&&o.emit("copy",{timestamp:/* @__PURE__ */(new Date).toISOString(),sessionId:r,content:e,messageId:t}),setTimeout(()=>l(!1),k)}catch(n){console.error("Failed to copy content:",n)}})()},class:`ncw:inline-flex ncw:items-center ncw:gap-1 ncw:rounded ncw:transition-all ncw:duration-200 ${{small:"ncw:px-2 ncw:py-1 ncw:text-xs",medium:"ncw:px-3 ncw:py-1.5 ncw:text-sm",large:"ncw:px-4 ncw:py-2 ncw:text-base"}[w]} ${T?"ncw-copy-button-custom":{default:"ncw:bg-gray-100 hover:ncw:bg-gray-200 dark:ncw:bg-gray-700 dark:hover:ncw:bg-gray-600",minimal:"hover:ncw:bg-gray-100 dark:hover:ncw:bg-gray-700",outline:"ncw:border ncw:border-gray-300 dark:ncw:border-gray-600 hover:ncw:bg-gray-50 dark:hover:ncw:bg-gray-800",ghost:"hover:ncw:bg-gray-100/50 dark:hover:ncw:bg-gray-700/50"}["top-right"===d&&"default"===h?"ghost":h]} ${{top:"ncw:mb-2",bottom:"ncw:mt-2",inline:"ncw:ml-2 ncw:inline-flex","top-right":"ncw:absolute ncw:top-1 ncw:right-1 ncw:z-10"}[d]} ${"top-right"===d?"ncw:opacity-60 hover:ncw:opacity-100":""} ${g} `,style:I,title:a?C:S,children:/* @__PURE__ */be(_,a?{children:[p&&E(x,/* @__PURE__ */be("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"2",class:"ncw:text-green-600 dark:ncw:text-green-400",children:/* @__PURE__ */be("path",{d:"M2 7l3 3 7-7",strokeLinecap:"round",strokeLinejoin:"round"})})),u&&/* @__PURE__ */be("span",{class:"ncw:text-green-600 dark:ncw:text-green-400",children:C})]}:{children:[p&&E(y,$),u&&/* @__PURE__ */be("span",{class:f?"ncw-custom-text-color":"ncw:text-gray-500 dark:ncw:text-gray-400",children:"Copy"})]})})}function os(e,t){const n={small:"16",medium:"18",large:"20"}[t],r=e.trim();return/^<svg[\s>]/i.test(r)?/* @__PURE__ */be("span",{class:"ncw:inline-flex ncw:items-center ncw:justify-center",dangerouslySetInnerHTML:{__html:/<svg[^>]*(?<!-)width=/i.test(r)?r:r.replace(/^<svg/i,`<svg width="${n}" height="${n}"`)}}):/* @__PURE__ */be("span",{children:e})}function is({message:e,config:t,store:n,eventEmitter:r,onFeedbackChange:o,readOnly:i}){const s=t.features?.feedback,[a,l]=ie(e.feedback?.value??null),[c,d]=ie(!1),[u,p]=ie(!1),[h,w]=ie(!1),[g,m]=ie(!1),[f,v]=ie(null),[b,y]=ie(""),[x,k]=ie(e.feedback?.comment);if(se(()=>{if(t.features?.feedback?.behavior?.blockInputWhileOpen&&g)return n?.setFeedbackFormOpen(!0),()=>{n?.setFeedbackFormOpen(!1)}},[g]),!s?.enabled||i)return null;const S="assistant"===e.role,C="agent"===e.role,I=s.showOnAssistantMessages??!0,T=s.showOnAgentMessages??!0;if(S&&!I||C&&!T)return null;if(e.isStreaming)return null;const $=s.style||"thumbs",E=s.position||"inline",A=s.buttons?.size||"small",z=s.buttons?.showLabels??!1,R=s.buttons?.animation||"scale",M=s.behavior?.allowChange??!0,L=s.commentInput,O={small:"ncw:text-sm ncw:p-1",medium:"ncw:text-base ncw:p-1.5",large:"ncw:text-lg ncw:p-2"},D={none:"",scale:"ncw:transition-transform hover:ncw:scale-110",fade:"ncw:transition-opacity hover:ncw:opacity-80"},B=async(i,c)=>{if(null===a||M){if(s.commentInput&&void 0===c)return v(i),void m(!0);if(m(!1),v(null),d(!0),(await async function(e,t,n,r,o,i){let s;try{const a=n.features?.feedback,l=(a?.api?.endpoint||"/query/feedback").replace(/^\/+/,""),c=a?.api?.includeContext??!1,d={messageId:e,feedbackValue:t,comment:i?.comment,experienceId:n.experienceId,sessionId:r.currentSessionId.value,userId:n.advanced?.userId,timestamp:/* @__PURE__ */(new Date).toISOString(),metadata:{source:"widget",widgetId:n.advanced?.widgetId,messageContent:i?.messageContent,messageRole:i?.messageRole,...n.advanced?.metadata||{},...a?.api?.additionalData||{}},...c&&i?.conversationContext?{conversationContext:i.conversationContext}:{}},u=Ee(n),p=Le(n.apiUrl||""),h=15e3,w=new AbortController;s=setTimeout(()=>w.abort(),h);const g=await fetch(`${p}/${l}`,{method:"POST",headers:u,body:JSON.stringify(d),signal:w.signal,credentials:n.advanced?.credentials});if(clearTimeout(s),!g.ok){const n=await g.text();return console.error("Feedback submission failed:",n),o&&o.emit("error",{timestamp:/* @__PURE__ */(new Date).toISOString(),sessionId:r.currentSessionId.value,type:"feedback",message:`Failed to submit feedback: ${n}`,details:{messageId:e,feedbackValue:t}}),{success:!1,error:`Failed to submit feedback: ${n}`}}return{success:!0}}catch(a){return clearTimeout(s),console.error("Error sending feedback:",a),o&&o.emit("error",{timestamp:/* @__PURE__ */(new Date).toISOString(),sessionId:r.currentSessionId.value,type:"feedback",message:a instanceof Error?a.message:"Unknown error occurred",stack:a instanceof Error?a.stack:void 0,details:{messageId:e,feedbackValue:t}}),{success:!1,error:a instanceof Error?a.message:"Unknown error occurred"}}}(e.metadata?.queryId||e.id,i,t,n,r,{comment:c??(b||void 0),messageContent:e.content,messageRole:e.role,conversationContext:s.api?.includeContext?n.events.value.filter(e=>"message"===e.kind).map(e=>({role:e.role,content:e.content,timestamp:e.timestamp})):void 0})).success){l(i),k(c||b||void 0),r&&r.emit("feedback",{timestamp:/* @__PURE__ */(new Date).toISOString(),sessionId:n.currentSessionId.value,rating:i,messageId:e.id,comment:c||b||void 0});const t={value:i,comment:c||b||void 0,timestamp:/* @__PURE__ */new Date};o&&o(e.id,t),(s.behavior?.showConfirmation??1)&&(w(!0),setTimeout(()=>{w(!1)},s.behavior?.confirmationDuration||2e3))}d(!1),m(!1),v(null),y("")}},P=async()=>{p(!0),(await async function(e,t,n,r){const o=Le(t.apiUrl||""),i=Ee(t),s=new AbortController,a=setTimeout(()=>s.abort(),15e3);try{const r=await fetch(`${o}/query/feedback/${e}`,{method:"DELETE",headers:i,body:JSON.stringify({sessionId:n.currentSessionId.value,experienceId:t.experienceId,userId:t.advanced?.userId}),signal:s.signal,credentials:t.advanced?.credentials});if(clearTimeout(a),!r.ok){const e=await r.text();return console.error("Feedback deletion failed:",e),{success:!1,error:`Failed to delete feedback: ${e}`}}return{success:!0}}catch(l){return clearTimeout(a),console.error("Error deleting feedback:",l),r&&r.emit("error",{timestamp:/* @__PURE__ */(new Date).toISOString(),sessionId:n.currentSessionId.value,type:"feedback",message:l instanceof Error?l.message:"Unknown error occurred",details:{queryId:e}}),{success:!1,error:l instanceof Error?l.message:"Unknown error occurred"}}}(e.metadata?.queryId||e.id,t,n,r)).success&&(l(null),y(""),k(void 0),o&&o(e.id,void 0)),p(!1)};if("thumbs"===$){const e=s.buttons?.positive,n=s.buttons?.negative,r="positive"===a||"positive"===f,o="negative"===a||"negative"===f,i=r?e?.activeIcon??e?.icon??"👍":e?.icon??"👍",l=o?n?.activeIcon??n?.icon??"👎":n?.icon??"👎",d=e?.label||"Helpful",p=n?.label||"Not helpful",w=!!(e?.color||e?.activeColor||e?.backgroundColor||e?.activeBackgroundColor),b=!!(n?.color||n?.activeColor||n?.backgroundColor||n?.activeBackgroundColor),y=null!==f?s.commentPrompts?.[f]:void 0,k=y?.prompt??s.commentPrompt,S=y?.placeholder;/* @__PURE__ */
|
|
26
26
|
return be(_,{children:[
|
|
27
27
|
/* @__PURE__ */be("div",{class:"ncw:flex ncw:items-center ncw:gap-2 "+("bottom"===E?"ncw:mt-2":"top"===E?"ncw:mb-2":"ncw:ml-2 ncw:inline-flex"),style:{gap:s.buttons?.spacing||"8px"},children:[
|
|
28
28
|
/* @__PURE__ */be("button",{type:"button",disabled:c||u||null!==a&&"positive"!==a&&!M,onClick:()=>{"positive"===a&&s.behavior?.allowRemove?P():B("positive")},class:`ncw:rounded ncw:border ncw:border-transparent ${O[A]} ${D[R]} ${w?"":r?"ncw:bg-green-100 ncw:text-green-700":"ncw:text-gray-500 hover:ncw:text-green-600 hover:ncw:bg-green-50"} ${c||u?"ncw:opacity-50 ncw:cursor-not-allowed":"ncw:cursor-pointer"}`,style:{color:r?e?.activeColor:e?.color,backgroundColor:r?e?.activeBackgroundColor:e?.backgroundColor},"aria-label":"positive"===a?s.behavior?.allowRemove?`${d} — click to remove`:`${d} — click to change`:d,title:"positive"===a?s.behavior?.allowRemove?`${d} — click to remove`:`${d} — click to change`:d,children:/* @__PURE__ */be("span",{class:"ncw:flex ncw:items-center ncw:gap-1",children:[os(i,A),z&&/* @__PURE__ */be("span",{class:"ncw:text-xs",children:d})]})}),
|
|
@@ -47,12 +47,12 @@ return be("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"currentColor",
|
|
|
47
47
|
return be("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",stroke:"currentColor","stroke-width":"1",children:[
|
|
48
48
|
/* @__PURE__ */be("path",{d:"M10 2C5.5 2 2 5.5 2 10v3c0 1.1.9 2 2 2h2V9H4c.5-2.5 2.5-4 6-4s5.5 1.5 6 4h-2v6h2c1.1 0 2-.9 2-2v-3c0-4.5-3.5-8-8-8z"}),
|
|
49
49
|
/* @__PURE__ */be("rect",{x:"2",y:"9",width:"4",height:"6",rx:"1",fill:"currentColor"}),
|
|
50
|
-
/* @__PURE__ */be("rect",{x:"14",y:"9",width:"4",height:"6",rx:"1",fill:"currentColor"})]})}function ds(e){const t=e instanceof Date?e:new Date(e),n=/* @__PURE__ */new Date,r=n.getTime()-t.getTime(),o=Math.floor(r/864e5);return 0===o?t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}):1===o?`Yesterday, ${t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0})}`:t.toLocaleDateString([],{month:"short",day:"numeric",year:t.getFullYear()!==n.getFullYear()?"numeric":void 0})+", "+t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0})}function us({message:e,ttsConfig:t,ttsEnabled:n,onTTSStateChange:r,onMessageSpoken:o,isMessageSpoken:i,readOnly:s,readOnlyAllowCopy:a,bubbleConfig:l,messagesConfig:c,linkConfig:d,apiUrl:u,experienceId:p,sessionId:h,config:w,store:g,eventEmitter:m,onFeedbackChange:f,customProtocolHandlers:v}){if(!(e.content&&e.content.trim().length>0||e.isStreaming||"assistant"!==e.role&&"agent"!==e.role))return null;const
|
|
51
|
-
return be("div",{class:`ncw:flex ncw:w-full ${
|
|
52
|
-
/* @__PURE__ */be("div",{class:`${
|
|
53
|
-
/* @__PURE__ */be(Ni,{content:e.content,format:e.format||w?.features?.format,linkConfig:d,applyTypographySizes:w?.messages?.markdown?.applyTypographySizes,eventEmitter:m,sessionId:h,customProtocolHandlers:v}),e.isStreaming&&!e.content.trim()&&/* @__PURE__ */be(Gi,{type:c?.loadingAnimation||"typing",color:c?.loadingAnimationColor,typingIndicatorText:c?.typingIndicatorText}),!
|
|
54
|
-
return be("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"currentColor",class:"ncw:opacity-70 "+(e?"ncw-custom-icon-color":""),children:[/* @__PURE__ */be("circle",{cx:"5",cy:"5",r:"4",stroke:"currentColor","stroke-width":"0.8",fill:"none"}),/* @__PURE__ */be("path",{d:"M5 2.5v2.5l1.5 0.75",stroke:"currentColor","stroke-width":"0.8","stroke-linecap":"round"})]})}function hs(e){const t=Math.floor(e/1e3),n=Math.floor(t/60),r=Math.floor(n/60);return r>0?`${r}h ${n%60}m`:n>0?`${n}m ${t%60}s`:`${t}s`}function ws({events:e,welcomeMessage:t,ttsConfig:n,ttsEnabled:r,onTTSStateChange:o,onMessageSpoken:i,isMessageSpoken:s,readOnly:a,readOnlyAllowCopy:l,bubbleConfig:c,messagesConfig:d,linkConfig:u,apiUrl:p,experienceId:h,sessionId:w,config:g,store:m,eventEmitter:f,onFeedbackChange:v,onDisclaimerAccept:b,customProtocolHandlers:y}){const x=e.some(e=>"message"===e.kind&&e.metadata?.isPersistentWelcome),k=e.every(e=>"session_start"===e.kind||"agent_handover"===e.kind||"system"===e.kind),_=(0===e.length||k)&&t&&!x;/* @__PURE__ */
|
|
55
|
-
return be("div",{style:{display:"flex",flexDirection:"column",gap:c?.spacing||"16px",..."bottom"===d?.messageAlignment&&{justifyContent:"flex-end"}},children:[_&&(()=>{const e=g?.messages?.welcomeMessageDisplay??"static",l=g?.messages?.welcomeActions;return"bubble"===e?/* @__PURE__ */be(ms,{event:{id:"synthetic-welcome-bubble",kind:"message",role:"assistant",content:t,format:"markdown",timestamp:/* @__PURE__ */new Date,metadata:{isWelcomeBubble:!0,actions:l,actionStates:l?_e.initializeActionStates("synthetic-welcome-bubble",l.actions):void 0}},ttsConfig:n,ttsEnabled:r,onTTSStateChange:o,onMessageSpoken:i,isMessageSpoken:s,readOnly:a,bubbleConfig:c,messagesConfig:d,linkConfig:u,apiUrl:p,experienceId:h,sessionId:w,config:g,store:m,eventEmitter:f,onFeedbackChange:v}):/* @__PURE__ */be("div",{class:"ncw:text-gray-500 dark:ncw:text-gray-400 ncw:text-sm",children:/* @__PURE__ */be(Ni,{content:t,format:"markdown",linkConfig:u,applyTypographySizes:g?.messages?.markdown?.applyTypographySizes})})})(),e.map(e=>/* @__PURE__ */be(gs,{event:e,ttsConfig:n,ttsEnabled:r,onTTSStateChange:o,onMessageSpoken:i,isMessageSpoken:s,readOnly:a,readOnlyAllowCopy:l,bubbleConfig:c,messagesConfig:d,linkConfig:u,apiUrl:p,experienceId:h,sessionId:w,config:g,store:m,eventEmitter:f,onFeedbackChange:v,onDisclaimerAccept:b,customProtocolHandlers:y},e.id))]})}function gs(e){const{event:t,onDisclaimerAccept:n}=e;switch(t.kind){case"message":/* @__PURE__ */return be(ms,{...e,event:t});case"session_start":/* @__PURE__ */return be(vs,{...e,event:t});case"agent_handover":/* @__PURE__ */return be(bs,{event:t,config:e.config,linkConfig:e.linkConfig});case"session_end":/* @__PURE__ */return be(ys,{event:t,config:e.config,linkConfig:e.linkConfig});case"typing":/* @__PURE__ */return be(xs,{event:t,messagesConfig:e.messagesConfig,config:e.config});case"system":/* @__PURE__ */return be(ks,{event:t,config:e.config,linkConfig:e.linkConfig});case"disclaimer":/* @__PURE__ */return be(_s,{event:t,config:e.config,linkConfig:e.linkConfig,readOnly:e.readOnly,onAccept:n});default:return null}}function ms({event:e,...t}){/* @__PURE__ */
|
|
50
|
+
/* @__PURE__ */be("rect",{x:"14",y:"9",width:"4",height:"6",rx:"1",fill:"currentColor"})]})}function ds(e){const t=e instanceof Date?e:new Date(e),n=/* @__PURE__ */new Date,r=n.getTime()-t.getTime(),o=Math.floor(r/864e5);return 0===o?t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0}):1===o?`Yesterday, ${t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0})}`:t.toLocaleDateString([],{month:"short",day:"numeric",year:t.getFullYear()!==n.getFullYear()?"numeric":void 0})+", "+t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",hour12:!0})}function us({message:e,ttsConfig:t,ttsEnabled:n,onTTSStateChange:r,onMessageSpoken:o,isMessageSpoken:i,readOnly:s,readOnlyAllowCopy:a,bubbleConfig:l,messagesConfig:c,linkConfig:d,apiUrl:u,experienceId:p,sessionId:h,config:w,store:g,eventEmitter:m,onFeedbackChange:f,customProtocolHandlers:v,isLatestTurn:b}){if(!(e.content&&e.content.trim().length>0||e.isStreaming||"assistant"!==e.role&&"agent"!==e.role))return null;const y="user"===e.role,x="agent"===e.role,k="assistant"===e.role,_=ae(!1),S=ae(null),C=ae(r),I=ae(o),T=ae(i);C.current=r,I.current=o,T.current=i;const[$,E]=ie(!1),A=g&&m?new es(g,m):null;se(()=>{E(!1)},[l?.assistant?.avatarUrl,l?.agent?.avatarUrl]);const z=l?.user?.alignment||"right",R=y?"left"===z?"ncw:justify-start":"ncw:justify-end":"ncw:justify-start",M={};let L=!1,O=!1;const D=y?l?.user:x?l?.agent:l?.assistant;D&&(D.backgroundColor&&(M["--ncw-bg-color"]=D.backgroundColor,L=!0),D.backgroundColorHover&&(M["--ncw-bg-color-hover"]=D.backgroundColorHover),!1===D.enableHoverEffect&&(M["--ncw-disable-hover"]="true"),D.textColor&&(M["--ncw-text-color"]=D.textColor,O=!0),D.fontFamily&&(M.fontFamily=D.fontFamily),D.fontSize&&(M.fontSize=Be(D.fontSize)),D.borderRadius&&(M.borderRadius=D.borderRadius),D.border?M.border=D.border:(D.borderWidth&&(M.borderWidth=D.borderWidth),D.borderColor&&(M.borderColor=D.borderColor),D.borderStyle&&(M.borderStyle=D.borderStyle)),D.padding&&(M.padding=D.padding),D.maxWidth?M.maxWidth=D.maxWidth:M.maxWidth=l?.defaultMaxWidth?l.defaultMaxWidth:"85%"),e.isStreaming&&!e.content.trim()&&(M.width="fit-content");const B=L?"ncw-custom-bg-color":y?"ncw:bg-blue-600":x?"ncw:bg-green-600":"ncw:bg-gray-100 dark:ncw:bg-gray-800",P=O?"ncw-custom-text-color":y||x?"ncw:text-white":"ncw:text-gray-900 dark:ncw:text-gray-100";se(()=>{if(S.current!==e.id&&(_.current=!1,S.current=e.id),!s){if(!y&&!e.metadata?.isPersistentWelcome&&n&&!e.isStreaming&&C.current){const n=!!T.current&&T.current(e.id);if(_.current||n)return;_.current=!0,I.current&&I.current(e.id);const r=fo(e.content),o={enabled:t?.enabled,defaultOn:t?.defaultOn,synthesisConfig:t?.synthesisConfig,apiUrl:u,experienceId:p,sessionId:h,passthroughHeaders:w?.advanced?.headers,accessToken:w?.accessToken,credentials:w?.advanced?.credentials},i=Date.now(),s=C.current;vo.speak(r,o,s,(t,n)=>{if(m)if("start"===t)m.emit("ttsStart",{timestamp:/* @__PURE__ */(new Date).toISOString(),sessionId:h,text:n.text,messageId:e.id});else if("end"===t){const t=Date.now()-i;m.emit("ttsEnd",{timestamp:/* @__PURE__ */(new Date).toISOString(),sessionId:h,messageId:e.id,duration:t})}}).catch(e=>{"string"!=typeof e?.message||e.message.includes("canceled")||e.message.includes("interrupted")||(console.error("TTS error:",e),_.current=!1)})}return()=>{n||(vo.stop(),_.current=!1)}}},[e.id,e.content,e.isStreaming,y,n,s]);const F=e.metadata?.isWelcomeBubble??!1,U=!y&&(()=>{if(F){return(w?.messages?.welcomeMessageShowAvatar??!0)&&((l?.assistant?.avatar)?.enabled??l?.assistant?.showAvatar??!1)}return k?(l?.assistant?.avatar)?.enabled??l?.assistant?.showAvatar:!!x&&((l?.agent?.avatar)?.enabled??l?.agent?.showAvatar)})(),W=x?l?.agent?.avatar?.url??l?.agent?.avatarUrl:l?.assistant?.avatar?.url??l?.assistant?.avatarUrl,H=W&&!$,N=x?l?.agent?.avatar:l?.assistant?.avatar,q=l?.defaultAvatar,j={};let V=!1,Z=!1;D?.backgroundColor&&(j["--ncw-bg-color"]=D.backgroundColor,V=!0),D?.textColor&&(j["--ncw-text-color"]=D.textColor,Z=!0);const K=Ji(N,q),Q={...j,...K},J=Yi(N,q),Y=V?"ncw-custom-avatar-bg":x?"ncw:bg-green-100 dark:ncw:bg-green-900":"ncw:bg-gray-300 dark:ncw:bg-gray-600",G=Z?"ncw-custom-text-color ncw:opacity-80":x?"ncw:text-green-600 dark:ncw:text-green-400":"ncw:text-gray-600 dark:ncw:text-gray-300";/* @__PURE__ */
|
|
51
|
+
return be("div",{class:`ncw:flex ncw:w-full ${R} ncw-fade-in`,children:[U&&/* @__PURE__ */be("div",{class:"ncw:flex-shrink-0",style:J?{margin:J}:{marginRight:"12px"},children:/* @__PURE__ */be("div",H?{class:`ncw:flex ncw:items-center ncw:justify-center ncw:p-1.5 ${Y} ${K.width&&K.height?"":"ncw:w-8 ncw:h-8"} ${K.borderRadius?"":"ncw:rounded-full"}`,style:Q,children:/* @__PURE__ */be("img",{src:W,alt:x?"Agent":"Assistant",class:"ncw:w-full ncw:h-full ncw:object-contain",onError:()=>{E(!0)}})}:{class:`ncw:flex ncw:items-center ncw:justify-center ${Y} ${G} ${K.width&&K.height?"":"ncw:w-8 ncw:h-8"} ${K.borderRadius?"":"ncw:rounded-full"}`,style:Q,children:/* @__PURE__ */be(x?cs:ls,{})})}),/* @__PURE__ */be("div",{class:`ncw:flex ncw:flex-col ${e.metadata?.confirmationMessage||M.maxWidth?"ncw:w-full":""} ${y&&"right"===z?"ncw:items-end":""} ${!y&&w?.features?.copyButton?.enabled&&"top-right"===w.features.copyButton.position?"ncw:relative":""}`,children:[x&&!0===l?.agent?.showAgentBadge&&/* @__PURE__ */be("div",{class:"ncw:mb-1",children:/* @__PURE__ */be("span",{class:"ncw:inline-block ncw:px-2 ncw:py-0.5 ncw:text-xs ncw:font-semibold ncw:rounded ncw:text-white "+(l?.agent?.badgeColor?"ncw-custom-bg-color":"ncw:bg-green-500"),style:{"--ncw-bg-color":l?.agent?.badgeColor||void 0},children:l?.agent?.badgeText||"Live Agent"})}),!y&&!F&&w?.features?.copyButton?.enabled&&!e.isStreaming&&"top"===w.features.copyButton.position&&/* @__PURE__ */be("div",{class:"ncw:mb-2",children:/* @__PURE__ */be(rs,{content:e.content,messageId:e.id,config:w.features.copyButton,sessionId:h,eventEmitter:m,readOnly:s,readOnlyAllowCopy:a})}),!y&&!F&&!e.metadata?.sessionExpired&&!e.metadata?.error&&w&&g&&"top"===w.features?.feedback?.position&&(!w.features?.feedback?.showOnLatestTurnOnly||b)&&/* @__PURE__ */be(is,{message:e,config:w,store:g,eventEmitter:m,onFeedbackChange:f,readOnly:s}),
|
|
52
|
+
/* @__PURE__ */be("div",{class:`${D?.borderRadius?"":"ncw:rounded-lg"} ncw:break-words ${D?.padding?"":"ncw:px-4 ncw:py-2"} ${B} ${P} ${y||!w?.features?.copyButton?.enabled||w.features.copyButton.position&&"inline"!==w.features.copyButton.position?"":"ncw:flex ncw:items-start ncw:justify-between"} ${!y&&w?.features?.copyButton?.enabled&&"top-right"===w.features.copyButton.position?"ncw:relative ncw:pr-10":""}`,style:M,children:[!y&&!F&&w?.features?.copyButton?.enabled&&!e.isStreaming&&"top-right"===w.features.copyButton.position&&/* @__PURE__ */be(rs,{content:e.content,messageId:e.id,config:w.features.copyButton,sessionId:h,eventEmitter:m,readOnly:s,readOnlyAllowCopy:a}),
|
|
53
|
+
/* @__PURE__ */be(Ni,{content:e.content,format:e.format||w?.features?.format,linkConfig:d,applyTypographySizes:w?.messages?.markdown?.applyTypographySizes,eventEmitter:m,sessionId:h,customProtocolHandlers:v}),e.isStreaming&&!e.content.trim()&&/* @__PURE__ */be(Gi,{type:c?.loadingAnimation||"typing",color:c?.loadingAnimationColor,typingIndicatorText:c?.typingIndicatorText}),!y&&!F&&!e.isStreaming&&w?.features?.copyButton?.enabled&&(!w.features.copyButton.position||"inline"===w.features.copyButton.position)&&/* @__PURE__ */be(rs,{content:e.content,messageId:e.id,config:w.features.copyButton,sessionId:h,eventEmitter:m,readOnly:s,readOnlyAllowCopy:a})]}),!y&&!F&&w?.features?.copyButton?.enabled&&!e.isStreaming&&"bottom"===w.features.copyButton.position&&/* @__PURE__ */be("div",{class:"ncw:mt-2",children:/* @__PURE__ */be(rs,{content:e.content,messageId:e.id,config:w.features.copyButton,sessionId:h,eventEmitter:m,readOnly:s,readOnlyAllowCopy:a})}),!y&&!F&&!e.metadata?.sessionExpired&&!e.metadata?.error&&w&&g&&"top"!==w.features?.feedback?.position&&(!w.features?.feedback?.showOnLatestTurnOnly||b)&&/* @__PURE__ */be(is,{message:e,config:w,store:g,eventEmitter:m,onFeedbackChange:f,readOnly:s}),!y&&!e.isStreaming&&e.metadata?.actions&&e.metadata.actions.actions.length>0&&/* @__PURE__ */be(ns,{actions:e.metadata.actions,messageId:e.id,messageRole:e.role,sessionId:g?.currentSessionId.value||null,actionStates:e.metadata.actionStates,onActionClick:async(t,n)=>{if(A&&g)try{if("send_query"===n.action.type||n.behavior?.oneTimeUse&&n.behavior?.disableAllOnClick){const t=(e.metadata?.actionStates||[]).map(e=>({...e,disabled:!0,disabledReason:"used"}));g.updateEvent(e.id,{metadata:{...e.metadata,actionStates:t}})}if(await A.execute(t,n),n.behavior?.oneTimeUse&&"send_query"!==n.action.type&&!n.behavior?.disableAllOnClick){const n=e.metadata?.actionStates||[],r=_e.markActionUsed(n,t);g.updateEvent(e.id,{metadata:{...e.metadata,actionStates:r}})}const r=n.behavior?.postClickBehavior;if(r){const t={...e.metadata};r.removeOnClick&&(t.actions=void 0,t.actionStates=void 0),r.confirmationMessage&&(t.confirmationMessage=r.confirmationMessage,t.confirmationMessageFormat=r.confirmationMessageFormat||"markdown",t.confirmationMessageAlignment=r.confirmationMessageAlignment||"center",t.confirmationMessageColor=r.confirmationMessageColor,r.confirmationIcon?(t.confirmationIcon=r.confirmationIcon,t.showConfirmationIcon=!1!==r.showIcon):!1!==r.showIcon?(t.confirmationIcon=ts,t.showConfirmationIcon=!0):t.showConfirmationIcon=!1),g.updateEvent(e.id,{metadata:t})}}catch(r){console.error("Action execution failed:",r)}},eventEmitter:m,readOnly:s}),!y&&!e.isStreaming&&e.metadata?.confirmationMessage&&/* @__PURE__ */be("div",{class:`ncw-confirmation-message ncw-fade-in ncw:mt-2 ncw:w-full ncw:flex ncw:items-center ncw:gap-2 ${e.metadata.confirmationMessageColor?"":"ncw:text-green-600 dark:ncw:text-green-400"} ${"left"===e.metadata.confirmationMessageAlignment?"ncw:justify-start":"right"===e.metadata.confirmationMessageAlignment?"ncw:justify-end":"ncw:justify-center"}`,style:{color:e.metadata.confirmationMessageColor||void 0},role:"status","aria-live":"polite",children:[e.metadata.showConfirmationIcon&&e.metadata.confirmationIcon&&/* @__PURE__ */be("span",{class:"ncw:inline-flex ncw:items-center ncw:flex-shrink-0",style:{width:"16px",height:"16px",fill:"currentColor",color:"currentColor"},dangerouslySetInnerHTML:{__html:"svg"===e.metadata.confirmationIcon.type?e.metadata.confirmationIcon.content:"emoji"===e.metadata.confirmationIcon.type?`<span style="font-size: 16px">${e.metadata.confirmationIcon.content}</span>`:`<img src="${e.metadata.confirmationIcon.content}" alt="" style="width: 16px; height: 16px" />`}}),/* @__PURE__ */be("div",{style:{textAlign:"left"===e.metadata.confirmationMessageAlignment?"left":"right"===e.metadata.confirmationMessageAlignment?"right":"center"},children:/* @__PURE__ */be(Ni,{content:e.metadata.confirmationMessage,format:e.metadata.confirmationMessageFormat||"markdown",linkConfig:d,applyTypographySizes:w?.messages?.markdown?.applyTypographySizes,eventEmitter:m,sessionId:h,customProtocolHandlers:v})})]}),l?.showTimestamps&&!F&&e.timestamp&&!e.isStreaming&&/* @__PURE__ */be("div",{class:"ncw:text-xs ncw:text-gray-500 dark:ncw:text-gray-400 ncw:mt-1 "+(y&&"right"===z?"ncw:text-right":""),children:ds(e.timestamp)})]})]})}function ps({hasCustomColor:e}){/* @__PURE__ */
|
|
54
|
+
return be("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"currentColor",class:"ncw:opacity-70 "+(e?"ncw-custom-icon-color":""),children:[/* @__PURE__ */be("circle",{cx:"5",cy:"5",r:"4",stroke:"currentColor","stroke-width":"0.8",fill:"none"}),/* @__PURE__ */be("path",{d:"M5 2.5v2.5l1.5 0.75",stroke:"currentColor","stroke-width":"0.8","stroke-linecap":"round"})]})}function hs(e){const t=Math.floor(e/1e3),n=Math.floor(t/60),r=Math.floor(n/60);return r>0?`${r}h ${n%60}m`:n>0?`${n}m ${t%60}s`:`${t}s`}function ws({events:e,welcomeMessage:t,ttsConfig:n,ttsEnabled:r,onTTSStateChange:o,onMessageSpoken:i,isMessageSpoken:s,readOnly:a,readOnlyAllowCopy:l,bubbleConfig:c,messagesConfig:d,linkConfig:u,apiUrl:p,experienceId:h,sessionId:w,config:g,store:m,eventEmitter:f,onFeedbackChange:v,onDisclaimerAccept:b,customProtocolHandlers:y}){const x=e.some(e=>"message"===e.kind&&e.metadata?.isPersistentWelcome),k=e.every(e=>"session_start"===e.kind||"agent_handover"===e.kind||"system"===e.kind),_=(0===e.length||k)&&t&&!x,S=g?.features?.feedback?.showOnLatestTurnOnly?[...e].reverse().find(e=>"message"===e.kind&&"user"!==e.role&&!e.metadata?.isWelcomeBubble&&!e.metadata?.sessionExpired&&!e.metadata?.error)?.id??null:null;/* @__PURE__ */
|
|
55
|
+
return be("div",{style:{display:"flex",flexDirection:"column",gap:c?.spacing||"16px",..."bottom"===d?.messageAlignment&&{justifyContent:"flex-end"}},children:[_&&(()=>{const e=g?.messages?.welcomeMessageDisplay??"static",l=g?.messages?.welcomeActions;return"bubble"===e?/* @__PURE__ */be(ms,{event:{id:"synthetic-welcome-bubble",kind:"message",role:"assistant",content:t,format:"markdown",timestamp:/* @__PURE__ */new Date,metadata:{isWelcomeBubble:!0,actions:l,actionStates:l?_e.initializeActionStates("synthetic-welcome-bubble",l.actions):void 0}},ttsConfig:n,ttsEnabled:r,onTTSStateChange:o,onMessageSpoken:i,isMessageSpoken:s,readOnly:a,bubbleConfig:c,messagesConfig:d,linkConfig:u,apiUrl:p,experienceId:h,sessionId:w,config:g,store:m,eventEmitter:f,onFeedbackChange:v}):/* @__PURE__ */be("div",{class:"ncw:text-gray-500 dark:ncw:text-gray-400 ncw:text-sm",children:/* @__PURE__ */be(Ni,{content:t,format:"markdown",linkConfig:u,applyTypographySizes:g?.messages?.markdown?.applyTypographySizes})})})(),e.map(e=>/* @__PURE__ */be(gs,{event:e,ttsConfig:n,ttsEnabled:r,onTTSStateChange:o,onMessageSpoken:i,isMessageSpoken:s,readOnly:a,readOnlyAllowCopy:l,bubbleConfig:c,messagesConfig:d,linkConfig:u,apiUrl:p,experienceId:h,sessionId:w,config:g,store:m,eventEmitter:f,onFeedbackChange:v,onDisclaimerAccept:b,customProtocolHandlers:y,isLatestTurn:null!==S&&e.id===S},e.id))]})}function gs(e){const{event:t,onDisclaimerAccept:n}=e;switch(t.kind){case"message":/* @__PURE__ */return be(ms,{...e,event:t});case"session_start":/* @__PURE__ */return be(vs,{...e,event:t});case"agent_handover":/* @__PURE__ */return be(bs,{event:t,config:e.config,linkConfig:e.linkConfig});case"session_end":/* @__PURE__ */return be(ys,{event:t,config:e.config,linkConfig:e.linkConfig});case"typing":/* @__PURE__ */return be(xs,{event:t,messagesConfig:e.messagesConfig,config:e.config});case"system":/* @__PURE__ */return be(ks,{event:t,config:e.config,linkConfig:e.linkConfig});case"disclaimer":/* @__PURE__ */return be(_s,{event:t,config:e.config,linkConfig:e.linkConfig,readOnly:e.readOnly,onAccept:n});default:return null}}function ms({event:e,...t}){/* @__PURE__ */
|
|
56
56
|
return be(us,{message:e,...t})}function fs(e,t){return{...e,...t}}function vs(e){const{event:t,config:n,linkConfig:r}=e,o=n?.events?.sessionStart;if(!1===o?.enabled)return null;const i=!1!==o?.showBadge,s=!1!==o?.showTimestamp,a=o?.layout||"vertical",l=o?.message||t.message,c=o?.messageFormat||"markdown",d=o?.badgeText||"Session started",u={};o?.badgeColor&&(u["--ncw-bg-color"]=o.badgeColor),o?.badgeTextColor&&(u["--ncw-text-color"]=o.badgeTextColor),o?.iconColor&&(u["--ncw-icon-color"]=o.iconColor);const p=o?.badgeColor||o?.badgeTextColor,h=o?.iconColor,w={};void 0!==o?.fontSize&&(w.fontSize=o.fontSize),void 0!==o?.fontFamily&&(w.fontFamily=o.fontFamily),void 0!==o?.fontStyle&&(w.fontStyle=o.fontStyle),void 0!==o?.textColor&&(w.textColor=o.textColor),void 0!==o?.backgroundColor&&(w.backgroundColor=o.backgroundColor),void 0!==o?.borderRadius&&(w.borderRadius=o.borderRadius),void 0!==o?.padding&&(w.padding=o.padding);const g=fs(n?.events?.default,w),m={};let f=!1,v=!1,b=!1;if(g.backgroundColor&&(m["--ncw-event-bg-color"]=g.backgroundColor,f=!0),g.textColor&&(m["--ncw-event-text-color"]=g.textColor,v=!0),g.fontFamily&&(m.fontFamily=g.fontFamily),g.fontStyle&&(m.fontStyle=g.fontStyle),g.fontSize){const e=Be(g.fontSize);e&&(m.fontSize=e,b=!0)}return g.borderRadius&&(m.borderRadius=g.borderRadius),g.padding&&(m.padding=g.padding),/* @__PURE__ */be("div","horizontal"===a?{class:`ncw:flex ncw:flex-col ncw:items-center ncw:my-4 ncw-fade-in ${f?"ncw-custom-event-bg-color":""} ${v?"ncw-custom-event-text-color":""}`,style:m,children:/* @__PURE__ */be("div",{class:"ncw:flex ncw:items-center ncw:justify-between ncw:w-full ncw:max-w-2xl ncw:px-4",children:[/* @__PURE__ */be("div",{class:`ncw:flex-1 ${b?"":"ncw:text-sm"} ${v?"":"ncw:text-gray-600 dark:ncw:text-gray-400"}`,children:l?/* @__PURE__ */be(Ni,{content:l,format:c,linkConfig:r,applyTypographySizes:n?.messages?.markdown?.applyTypographySizes}):/* @__PURE__ */be("span",{children:d})}),s&&/* @__PURE__ */be("div",{class:`${b?"":"ncw:text-xs"} ${v?"":"ncw:text-gray-500 dark:ncw:text-gray-400"} ncw:ml-4 ncw:whitespace-nowrap`,children:ds(t.timestamp)})]})}:{class:`ncw:flex ncw:flex-col ncw:items-center ncw:my-2 ncw-fade-in ncw:gap-1 ${f?"ncw-custom-event-bg-color":""} ${v?"ncw-custom-event-text-color":""}`,style:m,children:[i&&/* @__PURE__ */be("div",{class:"ncw:inline-flex ncw:items-center ncw:gap-1 ncw:px-2 ncw:py-0.5 ncw:rounded-full ncw:text-xs ncw:font-medium "+(p?"ncw-custom-bg-color ncw-custom-text-color":"ncw:bg-blue-100 dark:ncw:bg-blue-900 ncw:text-blue-800 dark:ncw:text-blue-200"),style:u,children:[/* @__PURE__ */be(ps,{hasCustomColor:!!h}),/* @__PURE__ */be("span",{children:d})]}),s&&/* @__PURE__ */be("div",{class:`${b?"":"ncw:text-xs"} ${v?"":"ncw:text-gray-500 dark:ncw:text-gray-400"}`,children:ds(t.timestamp)}),l&&/* @__PURE__ */be("div",{class:`ncw:text-center ${b?"":"ncw:text-sm"} ${v?"":"ncw:text-gray-600 dark:ncw:text-gray-400"} ncw:mt-1 ncw:max-w-md`,children:/* @__PURE__ */be(Ni,{content:l,format:c,linkConfig:r,applyTypographySizes:n?.messages?.markdown?.applyTypographySizes})})]})}function bs({event:e,config:t,linkConfig:n}){const[r,o]=ie(!1),i=t?.events?.agentHandover;if(!1===i?.enabled)return null;const s=!0===i?.showCard,a=i?.avatar?.enabled??i?.showAvatar??!0,l=!1!==i?.showTimestamp,c=i?.layout||"vertical",d=i?.message||e.message,u=i?.messageFormat||"markdown",p={};i?.cardBackgroundColor&&(p.backgroundColor=i.cardBackgroundColor),i?.cardBorderColor&&(p.borderColor=i.cardBorderColor),i?.cardTextColor&&(p.color=i.cardTextColor);const h={};void 0!==i?.fontSize&&(h.fontSize=i.fontSize),void 0!==i?.fontFamily&&(h.fontFamily=i.fontFamily),void 0!==i?.textColor&&(h.textColor=i.textColor),void 0!==i?.backgroundColor&&(h.backgroundColor=i.backgroundColor),void 0!==i?.borderRadius&&(h.borderRadius=i.borderRadius),void 0!==i?.padding&&(h.padding=i.padding);const w=fs(t?.events?.default,h),g={};let m=!1,f=!1,v=!1;if(w.backgroundColor&&(g["--ncw-event-bg-color"]=w.backgroundColor,m=!0),w.textColor&&(g["--ncw-event-text-color"]=w.textColor,f=!0),w.fontFamily&&(g.fontFamily=w.fontFamily),w.fontStyle&&(g.fontStyle=w.fontStyle),w.fontSize){const e=Be(w.fontSize);e&&(g.fontSize=e,v=!0)}return w.borderRadius&&(g.borderRadius=w.borderRadius),w.padding&&(g.padding=w.padding),/* @__PURE__ */be("div","horizontal"===c?{class:`ncw:flex ncw:flex-col ncw:items-center ncw:my-4 ncw-fade-in ${m?"ncw-custom-event-bg-color":""} ${f?"ncw-custom-event-text-color":""}`,style:g,children:/* @__PURE__ */be("div",{class:"ncw:flex ncw:items-center ncw:justify-between ncw:w-full ncw:max-w-2xl ncw:px-4",children:[/* @__PURE__ */be("div",{class:`ncw:flex-1 ${v?"":"ncw:text-sm"} ${f?"":"ncw:text-gray-600 dark:ncw:text-gray-400"}`,children:d||"Connecting you with a live agent..."}),l&&!!e.timestamp&&/* @__PURE__ */be("div",{class:`${v?"":"ncw:text-xs"} ${f?"":"ncw:text-gray-500 dark:ncw:text-gray-400"} ncw:ml-4 ncw:whitespace-nowrap`,children:ds(e.timestamp)})]})}:s?{class:`ncw:flex ncw:justify-center ncw:my-3 ncw-fade-in ${m?"ncw-custom-event-bg-color":""} ${f?"ncw-custom-event-text-color":""}`,style:g,children:/* @__PURE__ */be("div",{class:"ncw:bg-green-50 dark:ncw:bg-green-900/30 ncw:border ncw:border-green-200 dark:ncw:border-green-700 ncw:rounded-lg ncw:p-3 ncw:max-w-sm ncw:w-full",style:p,children:[
|
|
57
57
|
/* @__PURE__ */be("div",{class:"ncw:flex ncw:items-center ncw:gap-3",children:[a&&/* @__PURE__ */be(_,{children:(()=>{const n=t?.events?.agentHandover?.avatar,i=t?.events?.default?.avatar,s=Ji(n,i),a=Yi(n,i),l=n?.url??e.agentInfo?.avatarUrl;/* @__PURE__ */
|
|
58
58
|
return be("div",{class:"ncw:mr-3",style:a?{margin:a}:void 0,children:l&&!r?/* @__PURE__ */be("img",{src:l,alt:"Agent",class:`ncw:object-cover ${s.width&&s.height?"":"ncw:w-10 ncw:h-10"} ${s.borderRadius?"":"ncw:rounded-full"}`,style:s,onError:()=>o(!0)}):/* @__PURE__ */be("div",{class:`ncw:bg-green-100 dark:ncw:bg-green-800 ncw:flex ncw:items-center ncw:justify-center ${s.width&&s.height?"":"ncw:w-10 ncw:h-10"} ${s.borderRadius?"":"ncw:rounded-full"}`,style:s,children:/* @__PURE__ */be(cs,{})})})})()}),/* @__PURE__ */be("div",{class:"ncw:flex-1",children:[/* @__PURE__ */be("div",{class:"ncw:font-medium ncw:text-green-800 dark:ncw:text-green-200",children:e.agentInfo?.name||"Live Agent"}),l&&!!e.timestamp&&/* @__PURE__ */be("div",{class:`${v?"":"ncw:text-xs"} ${f?"":"ncw:text-gray-500 dark:ncw:text-gray-400"}`,children:ds(e.timestamp)})]})]}),d&&/* @__PURE__ */be("div",{class:"ncw:mt-2 ncw:text-sm ncw:text-green-700 dark:ncw:text-green-300",children:/* @__PURE__ */be(Ni,{content:d,format:u,linkConfig:n,applyTypographySizes:t?.messages?.markdown?.applyTypographySizes})}),e.reason&&/* @__PURE__ */be("div",{class:"ncw:mt-1 ncw:text-xs ncw:text-green-600 dark:ncw:text-green-400 ncw:italic",children:["Reason: ",e.reason]})]})}:{class:`ncw:flex ncw:flex-col ncw:items-center ncw:my-2 ncw-fade-in ncw:gap-1 ${m?"ncw-custom-event-bg-color":""} ${f?"ncw-custom-event-text-color":""}`,style:g,children:[d&&/* @__PURE__ */be("div",{class:`ncw:text-center ${v?"":"ncw:text-sm"} ${f?"":"ncw:text-gray-600 dark:ncw:text-gray-400"} ncw:max-w-md`,children:/* @__PURE__ */be(Ni,{content:d,format:u,linkConfig:n,applyTypographySizes:t?.messages?.markdown?.applyTypographySizes})}),l&&!!e.timestamp&&/* @__PURE__ */be("div",{class:`${v?"":"ncw:text-xs"} ${f?"":"ncw:text-gray-500 dark:ncw:text-gray-400"}`,children:ds(e.timestamp)})]})}function ys({event:e,config:t,linkConfig:n}){const r=t?.events?.sessionEnd;if(!1===r?.enabled)return null;const o=!1!==r?.showBadge,i=!1!==r?.showTimestamp,s=!1!==r?.showDuration,a=r?.layout||"vertical",l=r?.message||e.message,c=r?.messageFormat||"markdown",d={user_initiated:"ended by you",agent_initiated:"ended by agent",timeout:"timed out",error:"ended due to error",expired:"ended due to inactivity"},u={};r?.badgeColor&&(u["--ncw-bg-color"]=r.badgeColor),r?.badgeTextColor&&(u["--ncw-text-color"]=r.badgeTextColor),r?.iconColor&&(u["--ncw-icon-color"]=r.iconColor);const p=r?.badgeColor||r?.badgeTextColor,h=r?.iconColor,w={};void 0!==r?.fontSize&&(w.fontSize=r.fontSize),void 0!==r?.fontFamily&&(w.fontFamily=r.fontFamily),void 0!==r?.textColor&&(w.textColor=r.textColor),void 0!==r?.backgroundColor&&(w.backgroundColor=r.backgroundColor),void 0!==r?.borderRadius&&(w.borderRadius=r.borderRadius),void 0!==r?.padding&&(w.padding=r.padding);const g=fs(t?.events?.default,w),m={};let f=!1,v=!1,b=!1;if(g.backgroundColor&&(m["--ncw-event-bg-color"]=g.backgroundColor,f=!0),g.textColor&&(m["--ncw-event-text-color"]=g.textColor,v=!0),g.fontFamily&&(m.fontFamily=g.fontFamily),g.fontStyle&&(m.fontStyle=g.fontStyle),g.fontSize){const e=Be(g.fontSize);e&&(m.fontSize=e,b=!0)}if(g.borderRadius&&(m.borderRadius=g.borderRadius),g.padding&&(m.padding=g.padding),"horizontal"===a){const r=`Session ${e.reason&&d[e.reason]||"ended"}`,o=s&&e.metadata?.duration?` after ${hs(e.metadata.duration)}`:"";/* @__PURE__ */
|
|
@@ -73,11 +73,11 @@ return be(_,{children:[T&&/* @__PURE__ */be("style",{children:T}),
|
|
|
73
73
|
/* @__PURE__ */be("div",{class:k,style:S,"data-ncw-input":"true",children:[
|
|
74
74
|
/* @__PURE__ */be("textarea",{ref:u,value:e,onInput:e=>{const n=e.target;t(n.value),g()},onKeyDown:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),n())},placeholder:r,disabled:o||s?.advanced?.readOnly,rows:p,class:v?"ncw:flex-1 ncw:bg-transparent ncw:text-gray-900 dark:ncw:text-gray-100 focus:ncw:outline-none disabled:ncw:opacity-50 ncw:resize-none ncw:leading-5":["ncw:flex-1",!b&&"ncw:border",!y&&"ncw:rounded-lg",!x&&"ncw:bg-white dark:ncw:bg-gray-800","ncw:text-gray-900 dark:ncw:text-gray-100 focus:ncw:outline-none focus:ncw:ring-2 focus:ncw:ring-blue-500 disabled:ncw:opacity-50 ncw:resize-none ncw:leading-5"].filter(Boolean).join(" "),style:{backgroundColor:v?"transparent":s?.input?.backgroundColor,color:s?.input?.textColor,...s?.input?.textColor&&{WebkitTextFillColor:s.input.textColor},...s?.input?.backgroundColor&&{WebkitBoxShadow:`0 0 0px 1000px ${s.input.backgroundColor} inset`},fontFamily:s?.input?.fontFamily,fontSize:Be(s?.input?.fontSize),fontStyle:"normal",borderRadius:v?"0":s?.input?.borderRadius,...v?{border:"none"}:s?.input?.border?{borderWidth:s.input.border.split(" ")[0],borderStyle:s.input.border.split(" ")[1]||"solid",borderColor:s.input.border.split(" ").slice(2).join(" ")||"currentColor"}:b?{borderStyle:"solid",borderColor:s?.input?.borderColor,borderWidth:s?.input?.borderWidth||"1px"}:{},padding:s?.input?.padding||"6px 12px",minHeight:20*p+12+"px",outline:v?"none":void 0,boxShadow:v?"none":void 0},tabIndex:s?.advanced?.readOnly?-1:0}),m.enabled&&/* @__PURE__ */be(Qs,{config:m,onTranscript:(e,n)=>{n?t(e.trim()):s?.features?.voice?.interimResults&&t(e)},disabled:o||s?.advanced?.readOnly,eventEmitter:a,sessionId:l}),
|
|
75
75
|
/* @__PURE__ */be("button",{onClick:n,disabled:f,class:"ncw:rounded-lg disabled:ncw:cursor-not-allowed ncw:transition-colors ncw:flex ncw:items-center ncw:gap-2",style:(()=>{const e=(e,t,n)=>e??t??n,t=s?.input?.sendButton,n=s?.input,r={display:"flex",alignItems:"center",gap:"8px",padding:e(t?.padding,n?.sendButtonPadding,"8px 16px"),borderRadius:e(t?.borderRadius,n?.borderRadius,"8px"),fontFamily:e(t?.fontFamily,n?.sendButtonFontFamily)||n?.fontFamily,fontSize:Be(e(t?.fontSize,n?.sendButtonFontSize)),fontWeight:Fi(e(t?.fontWeight,n?.sendButtonFontWeight))},o=e(t?.style,n?.sendButtonStyle,"filled"),i=e(t?.color,n?.sendButtonColor),a=e(t?.backgroundColor,n?.sendButtonBackgroundColor),l=e(t?.textColor,n?.sendButtonTextColor),c=e(t?.border,n?.sendButtonBorder,"none"),d=e(t?.disabledOpacity,n?.sendButtonDisabledOpacity,"0.5"),u=e(t?.disabledTextColor,n?.sendButtonDisabledTextColor,"rgba(0, 0, 0, 0.3)");return"text"===o?{...r,backgroundColor:a||"transparent",color:f?u:l||i||"#3B82F6",border:c,opacity:f?d:"1",cursor:f?"not-allowed":"pointer"}:{...r,backgroundColor:a||i||n?.backgroundColor||"#3B82F6",color:l||"#ffffff",border:c,opacity:f?d:"1",cursor:f?"not-allowed":"pointer"}})(),tabIndex:s?.advanced?.readOnly?-1:0,children:i?/* @__PURE__ */be("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"#ffffff",class:"ncw:animate-spin",children:[/* @__PURE__ */be("circle",{cx:"12",cy:"12",r:"10",stroke:"#ffffff","stroke-width":"4",fill:"none",class:"ncw:opacity-25"}),/* @__PURE__ */be("path",{fill:"#ffffff",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z",class:"ncw:opacity-75"})]}):s?.input?.sendButton?.text||s?.input?.sendButtonText?/* @__PURE__ */be("span",{children:s?.input?.sendButton?.text??s?.input?.sendButtonText}):/* @__PURE__ */be("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"#ffffff",children:/* @__PURE__ */be("path",{d:"M10.894 2.553a1 1 0 00-1.788 0l-7 14a1 1 0 001.169 1.409l5-1.429A1 1 0 009 15.571V11a1 1 0 112 0v4.571a1 1 0 00.725.962l5 1.428a1 1 0 001.17-1.408l-7-14z"})})})]})]})});function Ys({config:e,store:t}){const n=e.sessionExpired,r=n?.buttonStyle,o=r?.backgroundColor||e.input?.sendButtonColor||"#2563eb",i=r?.hoverBackgroundColor||"#1d4ed8";/* @__PURE__ */
|
|
76
|
-
return be("button",{onClick:()=>{n?.onAction?n.onAction({timestamp:/* @__PURE__ */(new Date).toISOString(),sessionId:t.currentSessionId.value,startNewConversation:()=>t.resetChat()}):t.resetChat()},class:"ncw:w-full ncw:transition-colors ncw:cursor-pointer",style:{backgroundColor:o,color:r?.textColor||"#ffffff",borderRadius:r?.borderRadius||"8px",border:r?.border||"none",fontWeight:r?.fontWeight||"500",padding:r?.padding||"12px 16px"},onMouseEnter:e=>{e.currentTarget.style.backgroundColor=i},onMouseLeave:e=>{e.currentTarget.style.backgroundColor=o},children:n?.buttonText||"Start New Conversation"})}function Gs({config:e,store:t,eventEmitter:n,widgetContainer:r,isSidenav:o}){const i=ae(null),s=ae(null),a=ae(null),l=ae(!0),c=ae(null),[d,u]=ie(e.disclaimer?.defaultExpanded||!1),[p,h]=ie(!1),[w,g]=ie(()=>!e.disclaimer?.required||ji(e.experienceId)),m=e.messages?.links,f=e.advanced?.customProtocolHandlers,v=e?.input?.topBorder,b=ce(()=>null==v||("boolean"==typeof v?v:!1!==v.show),[v]),y=ce(()=>b&&"object"==typeof v&&null!==v?{borderTopStyle:"solid",borderTopWidth:v.width||"1px",borderTopColor:v.color||"#e5e7eb"}:{},[v,b]),x=ce(()=>b?"object"==typeof v&&null!==v?"":"ncw:border-t ncw:border-gray-200 dark:ncw:border-gray-700":"",[b,v]),k=de(e=>{t.setTTSSpeaking(e)},[t]),S=e.window?.sizing,C=ce(()=>S?.modes&&0!==S.modes.length?S.modes:[{name:"mobile",width:"95vw",height:"85vh"},{name:"normal",width:"384px",height:"600px"},{name:"expanded",width:"600px",height:"700px"}],[S?.modes]),I=ce(()=>{const e=t.windowSizeMode.value;return C.find(t=>t.name===e)||C[0]},[t.windowSizeMode.value,C]);se(()=>{if(S?.rememberSize&&"undefined"!=typeof window)try{const e=window.localStorage.getItem("ncw-window-size-mode");e&&C.some(t=>t.name===e)?t.setWindowSizeMode(e):S.defaultMode&&t.setWindowSizeMode(S.defaultMode)}catch{}else S?.defaultMode&&t.setWindowSizeMode(S.defaultMode);e.advanced?.initialEvents&&t.initializeEvents(e.advanced.initialEvents)},[S,C,t,e.advanced?.initialEvents]),se(()=>{if("event"===e.disclaimer?.displayMode&&e.disclaimer?.content&&!t.events.value.find(e=>"disclaimer"===e.kind&&e.metadata?.isPersistentDisclaimer)){const n=ji(e.experienceId),r=t.createPersistentDisclaimerEvent(e.disclaimer.content,e.disclaimer.contentFormat||"markdown",e.disclaimer.eventRequiresAcceptance||!1,e.disclaimer.acceptButtonText,n,n?/* @__PURE__ */(new Date).toISOString():void 0);t.events.value=[r,...t.events.value]}},[e.disclaimer?.displayMode,e.disclaimer?.content,e.disclaimer?.contentFormat,e.disclaimer?.eventRequiresAcceptance,e.disclaimer?.acceptButtonText,e.experienceId,t]),se(()=>{const n=localStorage.getItem(`nexus-chat-size-mode-${e.experienceId}`);if(e.embedded||S?.rememberSize&&n||S?.modes&&S.modes.length>0)return;const r=Se()?"mobile":"normal";return t.windowSizeMode.value!==r&&(t.windowSizeMode.value=r),Ce(e=>{const n=e?"mobile":"normal";t.windowSizeMode.value!==n&&(t.windowSizeMode.value=n)})},[e.embedded,e.experienceId,S?.rememberSize,S?.modes,t.windowSizeMode]),se(()=>{if(e.features?.tts?.enabled){const n={apiUrl:e.apiUrl,experienceId:e.experienceId},r=vo.checkSupport(n);t.setTTSAvailable(r),r&&e.features?.tts?.defaultOn&&t.setTTSEnabled(!0)}return()=>{t.isTTSSpeaking.value&&(vo.stop(),t.setTTSSpeaking(!1))}},[e.features?.tts,t,e.apiUrl,e.experienceId]),se(()=>{if((e.messages?.autoscroll??1)&&!t.isReadOnly.value){const e=l.current?"instant":"smooth";l.current=!1,setTimeout(()=>{i.current?.scrollIntoView({behavior:e})},50)}},[t.events.value,e.messages?.autoscroll,t.isReadOnly.value]);const T=de(()=>!(!e.disclaimer?.required||w)||!("event"!==e.disclaimer?.displayMode||!e.disclaimer?.eventRequiresAcceptance||t.isDisclaimerEventAccepted()),[e.disclaimer?.required,e.disclaimer?.displayMode,e.disclaimer?.eventRequiresAcceptance,w,t]);se(()=>{const n=e.input?.autofocusAfterResponse??!0;t.isLoading.value||!n||t.isReadOnly.value||t.isTTSSpeaking.value||T()||setTimeout(()=>{s.current?.focus()},100)},[t.isLoading.value,e.input?.autofocusAfterResponse,t.isReadOnly.value,t.isTTSSpeaking.value,T]),se(()=>{!e.input?.autofocusOnLoad||t.isReadOnly.value||t.isTTSSpeaking.value||T()||setTimeout(()=>{s.current?.focus()},100)},[]),se(()=>{if(!n||!1===e.advanced?.analytics?.trackLinkClicks)return;const r=n=>{!function(e,t,n){if(!1!==t.advanced?.analytics?.trackLinkClicks)try{const r=Le(t.apiUrl||""),o=Ee(t),i={sessionId:e.sessionId||n.currentSessionId.value,experienceId:t.experienceId,href:e.href,linkText:e.text,protocol:e.protocol,params:e.params&&Object.keys(e.params).length>0?e.params:void 0,userId:t.advanced?.userId,timestamp:e.timestamp,metadata:{source:"widget",widgetId:t.advanced?.widgetId,...t.advanced?.metadata||{}}},s=new AbortController,a=setTimeout(()=>s.abort(),5e3);fetch(`${r}/analytics/link-clicks`,{method:"POST",headers:o,body:JSON.stringify(i),signal:s.signal,credentials:t.advanced?.credentials}).then(e=>{clearTimeout(a),e.ok||console.warn("[Widget] Link click analytics failed:",e.status)}).catch(e=>{clearTimeout(a),"AbortError"!==e.name&&console.warn("[Widget] Link click analytics error:",e)})}catch(r){console.warn("[Widget] Failed to send link click analytics:",r)}}(n,e,t)};return n.on("linkClick",r),()=>{n.off("linkClick",r)}},[n,e,t]),se(()=>{!e.input?.autofocusOnLoad&&!e.input?.autofocusAfterResponse||t.isReadOnly.value||T()||setTimeout(()=>{s.current?.focus()},100)},[w,t.events.value,e.input?.autofocusOnLoad,e.input?.autofocusAfterResponse,t.isReadOnly.value,T]),se(()=>{if(!n)return;const r=r=>{const{queryText:o,displayText:s}=r,a=s||o;t.addEvent({kind:"message",role:"user",content:a,timestamp:/* @__PURE__ */new Date}),setTimeout(()=>{i.current?.scrollIntoView({behavior:"smooth"})},50),Oe(o,e,t,n,{skipUserMessage:!0,displayText:a})};return n.on("sendQuery",r),()=>{n.off("sendQuery",r)}},[n,e,t]),se(()=>{if(!a.current||!e?.scrollbar)return;const t=setTimeout(()=>{if(a.current){const t=r?r.__shadowRoot:void 0;c.current=function(e,t,n){if(!t)return{destroy:()=>{},update:()=>{}};if(!e.isConnected)return console.warn("[OverlayScrollbars] Element not connected to DOM, skipping initialization"),{destroy:()=>{},update:()=>{}};const r=`ncw-scrollbar-theme-${Math.random().toString(36).substr(2,9)}`,o={scrollbars:{theme:r,visibility:"auto",autoHide:t.autoHide?"move":"never",autoHideDelay:t.autoHideDelay??1e3,autoHideSuspend:!1}},i=mo(t),s=document.createElement("style");let a;s.textContent=`\n .${r} {\n ${i}\n }\n `,(n||document.head).appendChild(s);try{a=go(e,o)}catch(l){return console.error("[OverlayScrollbars] Initialization failed:",l),s.remove(),{destroy:()=>{},update:()=>{}}}return{destroy:()=>{try{a.destroy(),s.remove()}catch(l){console.error("[OverlayScrollbars] Destroy failed:",l)}},update:e=>{if(e)try{const t={scrollbars:{autoHide:e.autoHide?"move":"never",autoHideDelay:e.autoHideDelay??1e3}};a.options(t),s.textContent=`\n .${r} {\n ${mo(e)}\n }\n `}catch(l){console.error("[OverlayScrollbars] Update failed:",l)}}}}(a.current,e.scrollbar,t)}},0);return()=>{clearTimeout(t),c.current&&(c.current.destroy(),c.current=null)}},[]),se(()=>{c.current&&e?.scrollbar&&c.current.update(e.scrollbar)},[e?.scrollbar?.width,e?.scrollbar?.trackColor,e?.scrollbar?.thumbColor,e?.scrollbar?.thumbHoverColor,e?.scrollbar?.borderRadius,e?.scrollbar?.autoHide,e?.scrollbar?.autoHideDelay]);const $=()=>{h(!0),Vi(e.experienceId),n&&n.emit("disclaimerAccept",{timestamp:/* @__PURE__ */(new Date).toISOString(),sessionId:t.currentSessionId.value,experienceId:e.experienceId})},E="event"===e.disclaimer?.displayMode&&e.disclaimer?.eventRequiresAcceptance&&!t.isDisclaimerEventAccepted();se(()=>{if(!o||!r)return;const e=r.__sidenavConfig;return e?(Se()||t.isSidenavMaximized.value?(r.style.width="100%",document.body.style.overflow="hidden"):(r.style.width=e.sideWidth,document.body.style.overflow=""),()=>{document.body.style.overflow=""}):void 0},[t.isSidenavMaximized.value,o,r]),se(()=>{if(e.embedded||o)return;const t="fullscreen"===I?.name||"100vw"===I?.width&&"100vh"===I?.height;return t?function(){if(Fe)return;Fe=!0,Pe=window.scrollY;const e=document.body,t=window.innerWidth-document.documentElement.clientWidth;e.style.position="fixed",e.style.top=`-${Pe}px`,e.style.width="100%",e.style.overflowY="scroll",t>0&&(e.style.paddingRight=`${t}px`)}():Ue(),()=>{t&&Ue()}},[I,e.embedded,o]);const A="dark"===e.theme?"ncw:text-white":"ncw:text-gray-900",z={},R={};o?(z.width="100%",z.height="100%",z.display="flex",z.flexDirection="column",z.position="relative"):e.embedded?(z.width="100%",z.height="100%",z.display="flex",z.flexDirection="column",z.boxSizing="border-box",z.position="relative"):(I?(z.width=I.width,z.height=I.height):(e.window?.width&&(z.width=e.window.width),e.window?.height&&(z.height=e.window.height)),z.display="flex",z.flexDirection="column",z.position="relative");let M=e.window?.backgroundColor||("dark"===e.theme?"#111827":"#ffffff");return e.window?.backgroundTransparent&&(M=function(e,t){const n=e.match(/^#([0-9a-f]{3,8})$/i);if(!n)return e;let r,o,i;const s=n[1];if(3===s.length)r=parseInt(s[0]+s[0],16),o=parseInt(s[1]+s[1],16),i=parseInt(s[2]+s[2],16);else{if(6!==s.length&&8!==s.length)return e;r=parseInt(s.slice(0,2),16),o=parseInt(s.slice(2,4),16),i=parseInt(s.slice(4,6),16)}return`rgba(${r}, ${o}, ${i}, ${t})`}(M,.7)),z.backgroundColor=M,e.window?.backgroundGradient&&(z.background=e.window.backgroundGradientValue||function(e){return`linear-gradient(180deg, rgba(0, 0, 0, 0.3) 0%, ${e} 100%)`}(e.window.backgroundColor||("dark"===e.theme?"#111827":"#ffffff"))),e.window?.backdropBlur&&(z.backdropFilter=`blur(${e.window.backdropBlur})`,z.WebkitBackdropFilter=`blur(${e.window.backdropBlur})`),!e.window?.borderRadius||e.embedded||o?e.embedded||o||(R.borderRadius="8px 8px 0 0",z.borderRadius="8px 8px 0 0"):(R.borderRadius=`${e.window.borderRadius} ${e.window.borderRadius} 0 0`,z.borderRadius=`${e.window.borderRadius} ${e.window.borderRadius} 0 0`),e.window?.boxShadow&&!e.embedded&&(z.boxShadow=e.window.boxShadow),/* @__PURE__ */be(_,{children:/* @__PURE__ */be("div",{class:e.embedded?A:o?`${A} ncw:flex ncw:flex-col`:`${A} ncw:shadow-2xl ncw:flex ncw:flex-col ncw-slide-up`,style:z,children:[e.disclaimer?.required&&!w&&/* @__PURE__ */be(Zi,{config:e,experienceId:e.experienceId,eventEmitter:n,onAccept:()=>{g(!0)}}),e.window?.topAccentColor&&/* @__PURE__ */be("div",{style:{width:"100%",height:e.window?.topAccentHeight||"4px",backgroundColor:e.window?.topAccentColor,flexShrink:0,borderTopLeftRadius:e.window?.borderRadius,borderTopRightRadius:e.window?.borderRadius}}),!1!==e.window?.header?.show&&/* @__PURE__ */be("div",{class:"ncw:flex ncw:items-center ncw:justify-between ncw:gap-2 "+("none"===e.window?.header?.border||e.window?.header?.border||e.window?.header?.borderColor||e.window?.header?.borderWidth?"":"ncw:border-b ncw:border-gray-200 dark:ncw:border-gray-700"),style:{flexShrink:0,backgroundColor:e.window?.header?.backgroundColor,color:e.window?.header?.textColor,fontFamily:e.window?.header?.fontFamily,padding:e.window?.header?.padding||"12px",...e.window?.header?.border&&"none"!==e.window.header.border&&{borderBottom:e.window.header.border},...e.window?.header?.borderColor&&{borderBottomStyle:"solid",borderBottomWidth:e.window?.header?.borderWidth||"1px",borderBottomColor:e.window.header.borderColor},...!e.window?.header?.borderColor&&e.window?.header?.borderWidth&&{borderBottomStyle:"solid",borderBottomWidth:e.window.header.borderWidth,borderBottomColor:"dark"===e.theme?"#374151":"#e5e7eb"},...R},children:[/* @__PURE__ */be("div",{class:"ncw:flex ncw:items-center ncw:gap-2 ncw:min-w-0 ncw:flex-1",children:[e.branding?.logoUrl&&"header"===e.branding?.position&&/* @__PURE__ */be("img",{src:e.branding.logoUrl,alt:e.window?.header?.title||"AI Assistant",class:"ncw:max-h-8 ncw:max-w-[160px] ncw:object-contain ncw:flex-shrink-0"}),
|
|
76
|
+
return be("button",{onClick:()=>{n?.onAction?n.onAction({timestamp:/* @__PURE__ */(new Date).toISOString(),sessionId:t.currentSessionId.value,startNewConversation:()=>t.resetChat()}):t.resetChat()},class:"ncw:w-full ncw:transition-colors ncw:cursor-pointer",style:{backgroundColor:o,color:r?.textColor||"#ffffff",borderRadius:r?.borderRadius||"8px",border:r?.border||"none",fontWeight:r?.fontWeight||"500",padding:r?.padding||"12px 16px"},onMouseEnter:e=>{e.currentTarget.style.backgroundColor=i},onMouseLeave:e=>{e.currentTarget.style.backgroundColor=o},children:n?.buttonText||"Start New Conversation"})}function Gs({config:e,store:t,eventEmitter:n,widgetContainer:r,isSidenav:o}){const i=ae(null),s=ae(null),a=ae(null),l=ae(!0),c=ae(null),[d,u]=ie(e.disclaimer?.defaultExpanded||!1),[p,h]=ie(!1),[w,g]=ie(()=>!e.disclaimer?.required||ji(e.experienceId)),m=e.messages?.links,f=e.advanced?.customProtocolHandlers,v=e?.input?.topBorder,b=ce(()=>null==v||("boolean"==typeof v?v:!1!==v.show),[v]),y=ce(()=>b&&"object"==typeof v&&null!==v?{borderTopStyle:"solid",borderTopWidth:v.width||"1px",borderTopColor:v.color||"#e5e7eb"}:{},[v,b]),x=ce(()=>b?"object"==typeof v&&null!==v?"":"ncw:border-t ncw:border-gray-200 dark:ncw:border-gray-700":"",[b,v]),k=de(e=>{t.setTTSSpeaking(e)},[t]),S=e.window?.sizing,C=ce(()=>S?.modes&&0!==S.modes.length?S.modes:[{name:"mobile",width:"95vw",height:"85vh"},{name:"normal",width:"384px",height:"600px"},{name:"expanded",width:"600px",height:"700px"}],[S?.modes]),I=ce(()=>{const e=t.windowSizeMode.value;return C.find(t=>t.name===e)||C[0]},[t.windowSizeMode.value,C]);se(()=>{if(S?.rememberSize&&"undefined"!=typeof window)try{const e=window.localStorage.getItem("ncw-window-size-mode");e&&C.some(t=>t.name===e)?t.setWindowSizeMode(e):S.defaultMode&&t.setWindowSizeMode(S.defaultMode)}catch{}else S?.defaultMode&&t.setWindowSizeMode(S.defaultMode);e.advanced?.initialEvents&&t.initializeEvents(e.advanced.initialEvents)},[S,C,t,e.advanced?.initialEvents]),se(()=>{if("event"===e.disclaimer?.displayMode&&e.disclaimer?.content&&!t.events.value.find(e=>"disclaimer"===e.kind&&e.metadata?.isPersistentDisclaimer)){const n=ji(e.experienceId),r=t.createPersistentDisclaimerEvent(e.disclaimer.content,e.disclaimer.contentFormat||"markdown",e.disclaimer.eventRequiresAcceptance||!1,e.disclaimer.acceptButtonText,n,n?/* @__PURE__ */(new Date).toISOString():void 0);t.events.value=[r,...t.events.value]}},[e.disclaimer?.displayMode,e.disclaimer?.content,e.disclaimer?.contentFormat,e.disclaimer?.eventRequiresAcceptance,e.disclaimer?.acceptButtonText,e.experienceId,t]),se(()=>{const n=localStorage.getItem(`nexus-chat-size-mode-${e.experienceId}`);if(e.embedded||S?.rememberSize&&n||S?.modes&&S.modes.length>0)return;const r=Se()?"mobile":"normal";return t.windowSizeMode.value!==r&&(t.windowSizeMode.value=r),Ce(e=>{const n=e?"mobile":"normal";t.windowSizeMode.value!==n&&(t.windowSizeMode.value=n)})},[e.embedded,e.experienceId,S?.rememberSize,S?.modes,t.windowSizeMode]),se(()=>{if(e.features?.tts?.enabled){const n={apiUrl:e.apiUrl,experienceId:e.experienceId},r=vo.checkSupport(n);t.setTTSAvailable(r),r&&e.features?.tts?.defaultOn&&t.setTTSEnabled(!0)}return()=>{t.isTTSSpeaking.value&&(vo.stop(),t.setTTSSpeaking(!1))}},[e.features?.tts,t,e.apiUrl,e.experienceId]),se(()=>{if((e.messages?.autoscroll??1)&&!t.isReadOnly.value){const e=l.current?"instant":"smooth";l.current=!1,setTimeout(()=>{i.current?.scrollIntoView({behavior:e})},50)}},[t.events.value,e.messages?.autoscroll,t.isReadOnly.value]);const T=de(()=>!(!e.disclaimer?.required||w)||!("event"!==e.disclaimer?.displayMode||!e.disclaimer?.eventRequiresAcceptance||t.isDisclaimerEventAccepted()),[e.disclaimer?.required,e.disclaimer?.displayMode,e.disclaimer?.eventRequiresAcceptance,w,t]);se(()=>{const n=e.input?.autofocusAfterResponse??!0;t.isLoading.value||!n||t.isReadOnly.value||t.isTTSSpeaking.value||T()||setTimeout(()=>{s.current?.focus()},100)},[t.isLoading.value,e.input?.autofocusAfterResponse,t.isReadOnly.value,t.isTTSSpeaking.value,T]),se(()=>{!e.input?.autofocusOnLoad||t.isReadOnly.value||t.isTTSSpeaking.value||T()||setTimeout(()=>{s.current?.focus()},100)},[]),se(()=>{if(!n||!1===e.advanced?.analytics?.trackLinkClicks)return;const r=n=>{!function(e,t,n){if(!1!==t.advanced?.analytics?.trackLinkClicks)try{const r=Le(t.apiUrl||""),o=Ee(t),i={sessionId:e.sessionId||n.currentSessionId.value,experienceId:t.experienceId,href:e.href,linkText:e.text,protocol:e.protocol,params:e.params&&Object.keys(e.params).length>0?e.params:void 0,userId:t.advanced?.userId,timestamp:e.timestamp,metadata:{source:"widget",widgetId:t.advanced?.widgetId,...t.advanced?.metadata||{}}},s=new AbortController,a=setTimeout(()=>s.abort(),5e3);fetch(`${r}/analytics/link-clicks`,{method:"POST",headers:o,body:JSON.stringify(i),signal:s.signal,credentials:t.advanced?.credentials}).then(e=>{clearTimeout(a),e.ok||console.warn("[Widget] Link click analytics failed:",e.status)}).catch(e=>{clearTimeout(a),"AbortError"!==e.name&&console.warn("[Widget] Link click analytics error:",e)})}catch(r){console.warn("[Widget] Failed to send link click analytics:",r)}}(n,e,t)};return n.on("linkClick",r),()=>{n.off("linkClick",r)}},[n,e,t]),se(()=>{!e.input?.autofocusOnLoad&&!e.input?.autofocusAfterResponse||t.isReadOnly.value||T()||setTimeout(()=>{s.current?.focus()},100)},[w,t.events.value,e.input?.autofocusOnLoad,e.input?.autofocusAfterResponse,t.isReadOnly.value,T]),se(()=>{if(!n)return;const r=r=>{const{queryText:o,displayText:s}=r,a=s||o;t.addEvent({kind:"message",role:"user",content:a,timestamp:/* @__PURE__ */new Date}),setTimeout(()=>{i.current?.scrollIntoView({behavior:"smooth"})},50),Oe(o,e,t,n,{skipUserMessage:!0,displayText:a})};return n.on("sendQuery",r),()=>{n.off("sendQuery",r)}},[n,e,t]),se(()=>{if(!a.current||!e?.scrollbar)return;const t=setTimeout(()=>{if(a.current){const t=r?r.__shadowRoot:void 0;c.current=function(e,t,n){if(!t)return{destroy:()=>{},update:()=>{}};if(!e.isConnected)return console.warn("[OverlayScrollbars] Element not connected to DOM, skipping initialization"),{destroy:()=>{},update:()=>{}};const r=`ncw-scrollbar-theme-${Math.random().toString(36).substr(2,9)}`,o={scrollbars:{theme:r,visibility:"auto",autoHide:t.autoHide?"move":"never",autoHideDelay:t.autoHideDelay??1e3,autoHideSuspend:!1}},i=mo(t),s=document.createElement("style");let a;s.textContent=`\n .${r} {\n ${i}\n }\n `,(n||document.head).appendChild(s);try{a=go(e,o)}catch(l){return console.error("[OverlayScrollbars] Initialization failed:",l),s.remove(),{destroy:()=>{},update:()=>{}}}return{destroy:()=>{try{a.destroy(),s.remove()}catch(l){console.error("[OverlayScrollbars] Destroy failed:",l)}},update:e=>{if(e)try{const t={scrollbars:{autoHide:e.autoHide?"move":"never",autoHideDelay:e.autoHideDelay??1e3}};a.options(t),s.textContent=`\n .${r} {\n ${mo(e)}\n }\n `}catch(l){console.error("[OverlayScrollbars] Update failed:",l)}}}}(a.current,e.scrollbar,t)}},0);return()=>{clearTimeout(t),c.current&&(c.current.destroy(),c.current=null)}},[]),se(()=>{c.current&&e?.scrollbar&&c.current.update(e.scrollbar)},[e?.scrollbar?.width,e?.scrollbar?.trackColor,e?.scrollbar?.thumbColor,e?.scrollbar?.thumbHoverColor,e?.scrollbar?.borderRadius,e?.scrollbar?.autoHide,e?.scrollbar?.autoHideDelay]);const $=()=>{h(!0),Vi(e.experienceId),n&&n.emit("disclaimerAccept",{timestamp:/* @__PURE__ */(new Date).toISOString(),sessionId:t.currentSessionId.value,experienceId:e.experienceId})},E="event"===e.disclaimer?.displayMode&&e.disclaimer?.eventRequiresAcceptance&&!t.isDisclaimerEventAccepted(),A=(e.features?.feedback?.behavior?.blockInputWhileOpen??!1)&&t.openFeedbackFormCount.value>0;se(()=>{if(!o||!r)return;const e=r.__sidenavConfig;return e?(Se()||t.isSidenavMaximized.value?(r.style.width="100%",document.body.style.overflow="hidden"):(r.style.width=e.sideWidth,document.body.style.overflow=""),()=>{document.body.style.overflow=""}):void 0},[t.isSidenavMaximized.value,o,r]),se(()=>{if(e.embedded||o)return;const t="fullscreen"===I?.name||"100vw"===I?.width&&"100vh"===I?.height;return t?function(){if(Fe)return;Fe=!0,Pe=window.scrollY;const e=document.body,t=window.innerWidth-document.documentElement.clientWidth;e.style.position="fixed",e.style.top=`-${Pe}px`,e.style.width="100%",e.style.overflowY="scroll",t>0&&(e.style.paddingRight=`${t}px`)}():Ue(),()=>{t&&Ue()}},[I,e.embedded,o]);const z="dark"===e.theme?"ncw:text-white":"ncw:text-gray-900",R={},M={};o?(R.width="100%",R.height="100%",R.display="flex",R.flexDirection="column",R.position="relative"):e.embedded?(R.width="100%",R.height="100%",R.display="flex",R.flexDirection="column",R.boxSizing="border-box",R.position="relative"):(I?(R.width=I.width,R.height=I.height):(e.window?.width&&(R.width=e.window.width),e.window?.height&&(R.height=e.window.height)),R.display="flex",R.flexDirection="column",R.position="relative");let L=e.window?.backgroundColor||("dark"===e.theme?"#111827":"#ffffff");return e.window?.backgroundTransparent&&(L=function(e,t){const n=e.match(/^#([0-9a-f]{3,8})$/i);if(!n)return e;let r,o,i;const s=n[1];if(3===s.length)r=parseInt(s[0]+s[0],16),o=parseInt(s[1]+s[1],16),i=parseInt(s[2]+s[2],16);else{if(6!==s.length&&8!==s.length)return e;r=parseInt(s.slice(0,2),16),o=parseInt(s.slice(2,4),16),i=parseInt(s.slice(4,6),16)}return`rgba(${r}, ${o}, ${i}, ${t})`}(L,.7)),R.backgroundColor=L,e.window?.backgroundGradient&&(R.background=e.window.backgroundGradientValue||function(e){return`linear-gradient(180deg, rgba(0, 0, 0, 0.3) 0%, ${e} 100%)`}(e.window.backgroundColor||("dark"===e.theme?"#111827":"#ffffff"))),e.window?.backdropBlur&&(R.backdropFilter=`blur(${e.window.backdropBlur})`,R.WebkitBackdropFilter=`blur(${e.window.backdropBlur})`),!e.window?.borderRadius||e.embedded||o?e.embedded||o||(M.borderRadius="8px 8px 0 0",R.borderRadius="8px 8px 0 0"):(M.borderRadius=`${e.window.borderRadius} ${e.window.borderRadius} 0 0`,R.borderRadius=`${e.window.borderRadius} ${e.window.borderRadius} 0 0`),e.window?.boxShadow&&!e.embedded&&(R.boxShadow=e.window.boxShadow),/* @__PURE__ */be(_,{children:/* @__PURE__ */be("div",{class:e.embedded?z:o?`${z} ncw:flex ncw:flex-col`:`${z} ncw:shadow-2xl ncw:flex ncw:flex-col ncw-slide-up`,style:R,children:[e.disclaimer?.required&&!w&&/* @__PURE__ */be(Zi,{config:e,experienceId:e.experienceId,eventEmitter:n,onAccept:()=>{g(!0)}}),e.window?.topAccentColor&&/* @__PURE__ */be("div",{style:{width:"100%",height:e.window?.topAccentHeight||"4px",backgroundColor:e.window?.topAccentColor,flexShrink:0,borderTopLeftRadius:e.window?.borderRadius,borderTopRightRadius:e.window?.borderRadius}}),!1!==e.window?.header?.show&&/* @__PURE__ */be("div",{class:"ncw:flex ncw:items-center ncw:justify-between ncw:gap-2 "+("none"===e.window?.header?.border||e.window?.header?.border||e.window?.header?.borderColor||e.window?.header?.borderWidth?"":"ncw:border-b ncw:border-gray-200 dark:ncw:border-gray-700"),style:{flexShrink:0,backgroundColor:e.window?.header?.backgroundColor,color:e.window?.header?.textColor,fontFamily:e.window?.header?.fontFamily,padding:e.window?.header?.padding||"12px",...e.window?.header?.border&&"none"!==e.window.header.border&&{borderBottom:e.window.header.border},...e.window?.header?.borderColor&&{borderBottomStyle:"solid",borderBottomWidth:e.window?.header?.borderWidth||"1px",borderBottomColor:e.window.header.borderColor},...!e.window?.header?.borderColor&&e.window?.header?.borderWidth&&{borderBottomStyle:"solid",borderBottomWidth:e.window.header.borderWidth,borderBottomColor:"dark"===e.theme?"#374151":"#e5e7eb"},...M},children:[/* @__PURE__ */be("div",{class:"ncw:flex ncw:items-center ncw:gap-2 ncw:min-w-0 ncw:flex-1",children:[e.branding?.logoUrl&&"header"===e.branding?.position&&/* @__PURE__ */be("img",{src:e.branding.logoUrl,alt:e.window?.header?.title||"AI Assistant",class:"ncw:max-h-8 ncw:max-w-[160px] ncw:object-contain ncw:flex-shrink-0"}),
|
|
77
77
|
/* @__PURE__ */be("h3",{class:"ncw:text-base ncw:font-semibold ncw:truncate",title:e.window?.header?.title||"AI Assistant",style:{fontSize:Be(e.window?.header?.fontSize)},children:e.window?.header?.title||"AI Assistant"}),t.isReadOnly.value&&t.readOnlyIndicator.value?.show&&/* @__PURE__ */be("span",{class:"ncw:text-xs ncw:px-2 ncw:py-0.5 ncw:rounded ncw:whitespace-nowrap",style:{backgroundColor:t.readOnlyIndicator.value.backgroundColor||"#f3f4f6",color:t.readOnlyIndicator.value.textColor||"#6b7280"},children:t.readOnlyIndicator.value.text||"Unavailable"})]}),/* @__PURE__ */be("div",{class:"ncw:flex ncw:items-center ncw:gap-1 ncw:flex-shrink-0",children:[!e.embedded&&!o&&!1!==S?.showToggle&&C.length>1&&/* @__PURE__ */be("button",{onClick:()=>t.cycleWindowSize(C.map(e=>e.name)),class:"ncw:p-1.5 hover:ncw:bg-gray-100 dark:hover:ncw:bg-gray-800 ncw:rounded ncw:transition-colors ncw:cursor-pointer "+(e.window?.header?.iconColor||e.window?.header?.textColor?"ncw-custom-icon-color":"ncw:text-gray-500 hover:ncw:text-gray-700 dark:ncw:text-gray-400 dark:hover:ncw:text-gray-200"),style:{"--ncw-icon-color":e.window?.header?.iconColor??e.window?.header?.textColor??void 0},"aria-label":"Toggle window size",title:`Size: ${I.name}`,children:I.icon||/* @__PURE__ */be("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:/* @__PURE__ */be("path",{d:"M2.5 3.5a1 1 0 011-1h2a.5.5 0 010 1H4.707l1.647 1.646a.5.5 0 11-.708.708L4 4.207V5a.5.5 0 01-1 0v-2a1 1 0 01.5-.5zm7 0a.5.5 0 110-1h2a1 1 0 011 1v2a.5.5 0 01-1 0v-.793L9.854 5.354a.5.5 0 11-.708-.708L10.793 3H10a.5.5 0 01-.5-.5zM3 10.5a.5.5 0 011 0v.793l1.646-1.647a.5.5 0 01.708.708L4.707 12H5.5a.5.5 0 010 1h-2a1 1 0 01-1-1v-2a.5.5 0 01.5-.5zm7 1.647a.5.5 0 01.708-.708L12 12.793V12a.5.5 0 011 0v2a1 1 0 01-1 1h-2a.5.5 0 010-1h.793l-1.647-1.646a.5.5 0 010-.708z"})})}),!t.isReadOnly.value&&/* @__PURE__ */be("div",{class:"ncw:contents",children:/* @__PURE__ */be(bo,{onClearChat:()=>t.resetChat(),onEndConversation:()=>{const r=t.currentSessionId.value;(async()=>{let o,i=!0;if(r){const t=await async function(e,t){try{if(!e)return{success:!1,error:"No active session"};const n=t.apiUrl||"";if(!n)return{success:!1,error:"No API URL configured"};const r=n.endsWith("/debug");let o;o=r?`${n}/sessions/${e}/complete`:`${Le(n)}/sessions/${e}/complete?experienceId=${t.experienceId}`;const i=Ee(t),s=new AbortController,a=setTimeout(()=>s.abort(),1e4),l=await fetch(o,{method:"POST",headers:i,body:r?void 0:JSON.stringify({status:"completed"}),signal:s.signal,credentials:t.advanced?.credentials});if(clearTimeout(a),!l.ok){const e=await l.text();return console.warn("[Widget] End conversation API call failed:",e),{success:!1,error:e}}return{success:!0}}catch(n){return n instanceof Error&&"AbortError"===n.name?(console.warn("[Widget] End conversation API call timed out"),{success:!1,error:"Request timed out"}):(console.warn("[Widget] End conversation API error:",n),{success:!1,error:n instanceof Error?n.message:"Unknown error"})}}(r,e);i=t.success,o=t.error}n&&n.emit("sessionComplete",{timestamp:/* @__PURE__ */(new Date).toISOString(),sessionId:r,apiSuccess:i,apiError:o}),t.resetChat()})()},store:t,config:e,disabled:t.isLoading.value})}),o&&/* @__PURE__ */be("button",{onClick:()=>t.toggleSidenavMaximized(),class:"ncw:p-1.5 hover:ncw:bg-gray-100 dark:hover:ncw:bg-gray-800 ncw:rounded ncw:transition-colors ncw:cursor-pointer "+(e.window?.header?.iconColor||e.window?.header?.textColor?"ncw-custom-icon-color":"ncw:text-gray-500 hover:ncw:text-gray-700 dark:ncw:text-gray-400 dark:hover:ncw:text-gray-200"),style:{"--ncw-icon-color":e.window?.header?.iconColor??e.window?.header?.textColor??void 0},"aria-label":t.isSidenavMaximized.value?"Restore side panel":"Maximize",title:t.isSidenavMaximized.value?"Restore":"Maximize",children:t.isSidenavMaximized.value?/* @__PURE__ */be("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:/* @__PURE__ */be("path",{d:"M5.5 2a.5.5 0 010 1H3.707l3.147 3.146a.5.5 0 01-.708.708L3 3.707V5.5a.5.5 0 01-1 0v-3A.5.5 0 012.5 2h3zm5 0a.5.5 0 000 1h1.793L9.146 6.146a.5.5 0 10.708.708L13 3.707V5.5a.5.5 0 001 0v-3a.5.5 0 00-.5-.5h-3zM2.5 10.5a.5.5 0 01.5.5v1.793l3.146-3.147a.5.5 0 01.708.708L3.707 13H5.5a.5.5 0 010 1h-3a.5.5 0 01-.5-.5v-3a.5.5 0 01.5-.5zm11 0a.5.5 0 01.5.5v3a.5.5 0 01-.5.5h-3a.5.5 0 010-1h1.793l-3.147-3.146a.5.5 0 01.708-.708L13 12.293V11a.5.5 0 01.5-.5z"})}):/* @__PURE__ */be("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:/* @__PURE__ */be("path",{d:"M5.828 10.172a.5.5 0 00-.707 0l-2.828 2.829V11.5a.5.5 0 00-1 0v2.999a.5.5 0 00.5.5H4.8a.5.5 0 000-1H3.293l2.828-2.828a.5.5 0 000-.707zM10.172 5.828a.5.5 0 00.707 0l2.829-2.828V4.5a.5.5 0 001 0V1.501a.5.5 0 00-.5-.5H11.2a.5.5 0 100 1h1.507l-2.828 2.828a.5.5 0 000 .707z"})})}),!e.embedded&&!1!==e.window?.header?.showCloseButton&&/* @__PURE__ */be("button",{onClick:t.closeChat,class:"ncw:p-1.5 hover:ncw:bg-gray-100 dark:hover:ncw:bg-gray-800 ncw:rounded ncw:transition-colors ncw:cursor-pointer "+(e.window?.header?.iconColor||e.window?.header?.textColor?"ncw-custom-icon-color":"ncw:text-gray-500 hover:ncw:text-gray-700 dark:ncw:text-gray-400 dark:hover:ncw:text-gray-200"),style:{"--ncw-icon-color":e.window?.header?.iconColor??e.window?.header?.textColor??void 0},"aria-label":"Close chat",title:"Close",children:/* @__PURE__ */be("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor",children:/* @__PURE__ */be("path",{"fill-rule":"evenodd",d:"M3.72 3.72a.5.5 0 01.71 0L8 7.29l3.57-3.57a.5.5 0 01.71.71L8.71 8l3.57 3.57a.5.5 0 01-.71.71L8 8.71l-3.57 3.57a.5.5 0 01-.71-.71L7.29 8 3.72 4.43a.5.5 0 010-.71z","clip-rule":"evenodd"})})})]})]}),
|
|
78
78
|
/* @__PURE__ */be("div",{ref:a,class:"ncw:p-4 ncw:overflow-x-hidden ncw-scrollable-container",style:{flex:1,overflowY:"auto",overflowX:"hidden",minHeight:0},children:/* @__PURE__ */be("div",{style:{...o&&t.isSidenavMaximized.value&&{maxWidth:e.window?.fullWidth||"800px",margin:"0 auto"},..."bottom"===e.messages?.messageAlignment&&{display:"flex",flexDirection:"column",justifyContent:"flex-end",minHeight:"100%"}},children:[/* @__PURE__ */be(ws,{events:t.events.value,welcomeMessage:e.messages?.welcomeMessage,ttsConfig:e.features?.tts,ttsEnabled:t.isTTSEnabled.value,onTTSStateChange:k,onMessageSpoken:t.markMessageAsSpoken,isMessageSpoken:t.isMessageSpoken,readOnly:t.isReadOnly.value,readOnlyAllowCopy:t.readOnlyAllowCopy.value,bubbleConfig:e.bubbles,messagesConfig:e.messages,linkConfig:m,apiUrl:e.apiUrl,experienceId:e.experienceId,sessionId:t.currentSessionId.value,config:e,store:t,eventEmitter:n,onFeedbackChange:(e,n)=>{t.updateEvent(e,{feedback:n})},onDisclaimerAccept:()=>{t.acceptDisclaimer(),Vi(e.experienceId),n&&n.emit("disclaimerAccept",{timestamp:/* @__PURE__ */(new Date).toISOString(),sessionId:t.currentSessionId.value,experienceId:e.experienceId})},customProtocolHandlers:f}),/* @__PURE__ */be("div",{ref:i})]})}),
|
|
79
79
|
/* @__PURE__ */be("div",{style:{flexShrink:0},children:[
|
|
80
|
-
/* @__PURE__ */be("div",{class:x,style:y,children:/* @__PURE__ */be("div",{class:"ncw:p-3",children:t.isSessionExpired.value?!1!==e.sessionExpired?.showButton?/* @__PURE__ */be(Ys,{config:e,store:t}):null:/* @__PURE__ */be(Js,{ref:s,value:t.inputValue.value,onChange:t.setInputValue,onSend:()=>{(async()=>{const r=t.inputValue.value.trim();!r||t.isLoading.value||t.isReadOnly.value||(t.isTTSSpeaking.value&&(vo.stop(),t.setTTSSpeaking(!1)),t.setInputValue(""),await Oe(r,e,t,n))})()},placeholder:e.input?.placeholder||"Type your message...",disabled:t.isLoading.value||t.isReadOnly.value||!w||E,isLoading:t.isLoading.value,config:e,eventEmitter:n,sessionId:t.currentSessionId.value,widgetContainer:r})})}),e.disclaimer?.content&&!e.disclaimer?.required&&"event"!==e.disclaimer?.displayMode&&/* @__PURE__ */be("div",{class:"ncw:border-t ncw:border-gray-200 dark:ncw:border-gray-700",style:{backgroundColor:e.disclaimer.backgroundColor||("dark"===e.theme?"#1a1a1a":"#f9fafb")},children:!1!==e.disclaimer.collapsible?/* @__PURE__ */be("div",{children:[/* @__PURE__ */be("button",{onClick:()=>u(!d),class:"ncw:w-full ncw:px-4 ncw:py-2 ncw:flex ncw:items-center ncw:justify-between ncw:text-xs ncw:text-gray-600 dark:ncw:text-gray-400 hover:ncw:bg-gray-100 dark:hover:ncw:bg-gray-800 ncw:transition-colors","aria-expanded":d,children:[/* @__PURE__ */be("span",{class:"ncw:font-medium",children:"Disclaimer"}),/* @__PURE__ */be("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"currentColor",class:"ncw:transition-transform "+(d?"ncw:rotate-180":""),children:/* @__PURE__ */be("path",{d:"M6 7.5L2.5 4l.7-.7L6 6.1l2.8-2.8.7.7L6 7.5z"})})]}),d&&/* @__PURE__ */be("div",{class:"ncw:px-4 ncw:pb-3 ncw:text-xs",style:{color:e.disclaimer.textColor||("dark"===e.theme?"#9ca3af":"#6b7280")},children:[
|
|
80
|
+
/* @__PURE__ */be("div",{class:x,style:y,children:/* @__PURE__ */be("div",{class:"ncw:p-3",children:t.isSessionExpired.value?!1!==e.sessionExpired?.showButton?/* @__PURE__ */be(Ys,{config:e,store:t}):null:/* @__PURE__ */be(Js,{ref:s,value:t.inputValue.value,onChange:t.setInputValue,onSend:()=>{(async()=>{const r=t.inputValue.value.trim();!r||t.isLoading.value||t.isReadOnly.value||(t.isTTSSpeaking.value&&(vo.stop(),t.setTTSSpeaking(!1)),t.setInputValue(""),await Oe(r,e,t,n))})()},placeholder:e.input?.placeholder||"Type your message...",disabled:t.isLoading.value||t.isReadOnly.value||!w||E||A,isLoading:t.isLoading.value,config:e,eventEmitter:n,sessionId:t.currentSessionId.value,widgetContainer:r})})}),e.disclaimer?.content&&!e.disclaimer?.required&&"event"!==e.disclaimer?.displayMode&&/* @__PURE__ */be("div",{class:"ncw:border-t ncw:border-gray-200 dark:ncw:border-gray-700",style:{backgroundColor:e.disclaimer.backgroundColor||("dark"===e.theme?"#1a1a1a":"#f9fafb")},children:!1!==e.disclaimer.collapsible?/* @__PURE__ */be("div",{children:[/* @__PURE__ */be("button",{onClick:()=>u(!d),class:"ncw:w-full ncw:px-4 ncw:py-2 ncw:flex ncw:items-center ncw:justify-between ncw:text-xs ncw:text-gray-600 dark:ncw:text-gray-400 hover:ncw:bg-gray-100 dark:hover:ncw:bg-gray-800 ncw:transition-colors","aria-expanded":d,children:[/* @__PURE__ */be("span",{class:"ncw:font-medium",children:"Disclaimer"}),/* @__PURE__ */be("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"currentColor",class:"ncw:transition-transform "+(d?"ncw:rotate-180":""),children:/* @__PURE__ */be("path",{d:"M6 7.5L2.5 4l.7-.7L6 6.1l2.8-2.8.7.7L6 7.5z"})})]}),d&&/* @__PURE__ */be("div",{class:"ncw:px-4 ncw:pb-3 ncw:text-xs",style:{color:e.disclaimer.textColor||("dark"===e.theme?"#9ca3af":"#6b7280")},children:[
|
|
81
81
|
/* @__PURE__ */be(Ni,{content:e.disclaimer.content,format:e.disclaimer.contentFormat}),e.disclaimer.acceptButton&&!p&&/* @__PURE__ */be("button",{onClick:$,class:"ncw:mt-2 ncw:px-3 ncw:py-1 ncw:bg-blue-600 hover:ncw:bg-blue-700 ncw:text-white ncw:rounded ncw:text-xs ncw:font-medium ncw:transition-colors",children:e.disclaimer.acceptButtonText||"I understand"}),p&&/* @__PURE__ */be("div",{class:"ncw:mt-2 ncw:text-green-600 dark:ncw:text-green-400 ncw:flex ncw:items-center ncw:gap-1",children:[/* @__PURE__ */be("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"currentColor",children:/* @__PURE__ */be("path",{d:"M5 9L2 6l.7-.7L5 7.6l4.3-4.3.7.7L5 9z"})}),/* @__PURE__ */be("span",{children:"Acknowledged"})]})]})]}):/* @__PURE__ */be("div",{class:"ncw:px-4 ncw:py-3 ncw:text-xs",style:{color:e.disclaimer.textColor||("dark"===e.theme?"#9ca3af":"#6b7280")},children:[
|
|
82
|
-
/* @__PURE__ */be(Ni,{content:e.disclaimer.content,format:e.disclaimer.contentFormat}),e.disclaimer.acceptButton&&!p&&/* @__PURE__ */be("button",{onClick:$,class:"ncw:mt-2 ncw:px-3 ncw:py-1 ncw:bg-blue-600 hover:ncw:bg-blue-700 ncw:text-white ncw:rounded ncw:text-xs ncw:font-medium ncw:transition-colors",children:e.disclaimer.acceptButtonText||"I understand"}),p&&/* @__PURE__ */be("div",{class:"ncw:mt-2 ncw:text-green-600 dark:ncw:text-green-400 ncw:flex ncw:items-center ncw:gap-1",children:[/* @__PURE__ */be("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"currentColor",children:/* @__PURE__ */be("path",{d:"M5 9L2 6l.7-.7L5 7.6l4.3-4.3.7.7L5 9z"})}),/* @__PURE__ */be("span",{children:"Acknowledged"})]})]})}),!1!==e.branding?.show&&/* @__PURE__ */be("div",{class:"ncw:px-4 ncw:pb-3 ncw:pt-2",children:/* @__PURE__ */be("p",{class:"ncw:text-xs ncw:text-gray-500 dark:ncw:text-gray-400 ncw:text-center",children:e.branding?.text||"Powered by Knowbl"})})]})]})})}function Xs({config:e,store:t,eventEmitter:n,widgetContainer:r}){const[o,i]=ie(!1);return se(()=>{const n=r||document.getElementById("nexus-chat-widget-root")||document.querySelector("[data-widget-container]");if(n&&n.setAttribute("data-theme",e.theme||"light"),e.embedded&&(t.isOpen.value=!0),e.advanced?.initialEvents&&(t.initializeEvents(e.advanced.initialEvents),e.messages?.welcomeMessage&&e.messages?.welcomeMessagePersistent&&t.events.value.some(e=>"session_start"===e.kind)&&!t.events.value.some(e=>"message"===e.kind&&"metadata"in e&&e.metadata?.isPersistentWelcome))){const n=t.createPersistentWelcomeEvent(e.messages.welcomeMessage,e.messages.welcomeMessageDisplay);t.insertPersistentWelcomeEvent(n)}},[e.theme,e.embedded,r]),e.embedded?/* @__PURE__ */be(Gs,{config:e,store:t,eventEmitter:n,widgetContainer:r}):"sidenav"===e.layout?(se(()=>{if(!r)return;const n=r.__sidenavConfig,o=n?.sideWidth||e.window?.sideWidth||"500px",i=n?.zIndex??e.window?.zIndex??999999;if(t.isOpen.value){const e=window.innerWidth<=768;r.style.cssText=`\n position: fixed !important;\n top: 0 !important;\n right: 0 !important;\n bottom: 0 !important;\n left: auto !important;\n width: ${e?"100%":o} !important;\n max-width: 100% !important;\n z-index: ${i} !important;\n display: flex !important;\n flex-direction: column !important;\n margin: 0 !important;\n padding: 0 !important;\n transition: width 0.3s ease-in-out !important;\n `}else{const t=window.innerWidth<=768?"8px":"20px",n="bottom-left"===(e.button?.position||"bottom-right")?"left":"right",o=`max(${t}, env(safe-area-inset-${n}))`,s=`max(${t}, env(safe-area-inset-bottom))`;r.style.cssText=`\n position: fixed !important;\n bottom: ${s} !important;\n ${n}: ${o} !important;\n ${"left"===n?"right":"left"}: auto !important;\n z-index: ${i} !important;\n `}},[t.isOpen.value,r]),t.isOpen.value?/* @__PURE__ */be(Gs,{config:e,store:t,eventEmitter:n,widgetContainer:r,isSidenav:!0}):/* @__PURE__ */be("div",{class:"ncw:relative",children:[e.button?.callout&&!o&&/* @__PURE__ */be(ye,{config:e.button.callout,buttonPosition:e.button?.position,buttonBgColor:e.button?.backgroundColor,onDismiss:()=>i(!0)}),/* @__PURE__ */be(ke,{onClick:t.toggleChat,config:e.button})]})):/* @__PURE__ */be(_,{children:t.isOpen.value?/* @__PURE__ */be(Gs,{config:e,store:t,eventEmitter:n,widgetContainer:r}):/* @__PURE__ */be("div",{class:"ncw:relative",children:[e.button?.callout&&!o&&/* @__PURE__ */be(ye,{config:e.button.callout,buttonPosition:e.button?.position,buttonBgColor:e.button?.backgroundColor,onDismiss:()=>i(!0)}),/* @__PURE__ */be(ke,{onClick:t.toggleChat,config:e.button})]})})}var ea=class{experienceId;tabId;channel=null;options;isDestroyed=!1;maxStoredEvents;updateDebounceTimers=/* @__PURE__ */new Map;pendingUpdates=/* @__PURE__ */new Map;visibilityHandler=null;storageHandler=null;constructor(e){this.options=e,this.experienceId=e.experienceId,this.tabId=crypto.randomUUID();const t=e.maxStoredEvents??500;this.maxStoredEvents=Math.min(Math.max(t,10),2e3),this.initBroadcastChannel(),this.initVisibilityListener(),this.initStorageListener()}initBroadcastChannel(){if("undefined"!=typeof BroadcastChannel)try{this.channel=new BroadcastChannel("nexus-chat-sync"),this.channel.onmessage=e=>{this.handleMessage(e.data)}}catch(e){console.warn("[TabCoordinator] Failed to create BroadcastChannel:",e)}else console.warn("[TabCoordinator] BroadcastChannel not supported, using localStorage fallback only")}initVisibilityListener(){"undefined"!=typeof document&&(this.visibilityHandler=()=>{"visible"!==document.visibilityState||this.isDestroyed||this.reconcileFromStorage()},document.addEventListener("visibilitychange",this.visibilityHandler))}initStorageListener(){"undefined"!=typeof window&&(this.storageHandler=e=>{e.key?.startsWith("ncw-")&&!this.isDestroyed&&e.key.includes(this.experienceId)&&this.reconcileFromStorage()},window.addEventListener("storage",this.storageHandler))}handleMessage(e){if(!this.isDestroyed&&e.experienceId===this.experienceId)switch(e.type){case"session_created":this.options.onSessionCreated?.(e.sessionId);break;case"session_cleared":this.options.onSessionCleared?.();break;case"event_added":this.options.onEventAdded?.(e.event);break;case"event_updated":this.options.onEventUpdated?.(e.eventId,e.updates);break;case"state_changed":this.options.onStateChanged?.(e.state);break;case"request_sync":break;case"sync_response":e.targetTabId===this.tabId&&this.options.onFullSync?.(e.state)}}broadcast(e){const t=e;if(this.channel)try{this.channel.postMessage(t)}catch(n){console.warn("[TabCoordinator] Failed to broadcast message:",n)}}getStorageKey(e){return`ncw-${e}-${this.experienceId}`}getFromStorage(e){if("undefined"==typeof localStorage)return null;try{const t=localStorage.getItem(this.getStorageKey(e));return t?JSON.parse(t):null}catch{return null}}setInStorage(e,t){if("undefined"!=typeof localStorage)try{localStorage.setItem(this.getStorageKey(e),JSON.stringify(t))}catch(n){console.warn("[TabCoordinator] Failed to write to localStorage:",n)}}removeFromStorage(e){if("undefined"!=typeof localStorage)try{localStorage.removeItem(this.getStorageKey(e))}catch{}}notifySessionCreated(e){const t=Date.now();this.setInStorage("session",e),this.setInStorage("lastUpdate",t),this.broadcast({type:"session_created",experienceId:this.experienceId,sessionId:e,timestamp:t})}notifySessionCleared(){const e=Date.now();this.removeFromStorage("session"),this.removeFromStorage("events"),this.setInStorage("lastUpdate",e),this.broadcast({type:"session_cleared",experienceId:this.experienceId,timestamp:e})}notifyEventAdded(e){const t=Date.now(),n=[...this.getFromStorage("events")||[],e],r=n.length>this.maxStoredEvents?n.slice(-this.maxStoredEvents):n;this.setInStorage("events",r),this.setInStorage("lastUpdate",t),this.broadcast({type:"event_added",experienceId:this.experienceId,event:e,timestamp:t})}notifyEventUpdated(e,t){const n=this.pendingUpdates.get(e)||{};this.pendingUpdates.set(e,{...n,...t});const r=this.updateDebounceTimers.get(e);void 0!==r&&clearTimeout(r),this.updateDebounceTimers.set(e,setTimeout(()=>{const t=this.pendingUpdates.get(e);if(t){const n=Date.now(),r=(this.getFromStorage("events")||[]).map(n=>n.id===e?{...n,...t}:n);this.setInStorage("events",r),this.setInStorage("lastUpdate",n),this.broadcast({type:"event_updated",experienceId:this.experienceId,eventId:e,updates:t,timestamp:n}),this.pendingUpdates.delete(e)}this.updateDebounceTimers.delete(e)},100))}notifyStateChanged(e){const t=Date.now();this.setInStorage("state",e),this.setInStorage("lastUpdate",t),this.broadcast({type:"state_changed",experienceId:this.experienceId,state:e,timestamp:t})}clearEvents(e){const t=Date.now(),{keepCount:n,beforeDate:r}="number"==typeof e?{keepCount:e}:e??{};if((!n||n<=0)&&!r)return this.removeFromStorage("events"),void this.setInStorage("lastUpdate",t);let o=this.getFromStorage("events")||[];if(r){const e=this.normalizeDate(r);o=o.filter(t=>new Date(t.timestamp)>=e)}n&&n>0&&o.length>n&&(o=o.slice(-n)),0===o.length?this.removeFromStorage("events"):this.setInStorage("events",o),this.setInStorage("lastUpdate",t)}normalizeDate(e){return e instanceof Date?e:new Date(e)}getStoredEventCount(){return(this.getFromStorage("events")||[]).length}reconcileFromStorage(){const e=this.getFromStorage("session"),t=this.getFromStorage("events")||[],n=this.getFromStorage("state")||{isOpen:!1,isLoading:!1,isSessionExpired:!1},r=this.getFromStorage("lastUpdate")||0,o={sessionId:e,events:t.map(e=>({...e,timestamp:new Date(e.timestamp)})),isOpen:n.isOpen,isLoading:n.isLoading,isSessionExpired:n.isSessionExpired,timestamp:r};return this.options.onFullSync&&this.options.onFullSync(o),o}getStoredSessionId(){return this.getFromStorage("session")}getStoredEvents(){return(this.getFromStorage("events")||[]).map(e=>({...e,timestamp:new Date(e.timestamp)}))}updateCallbacks(e){this.options={...this.options,...e}}destroy(){this.isDestroyed=!0,this.updateDebounceTimers.forEach(e=>clearTimeout(e)),this.updateDebounceTimers.clear(),this.pendingUpdates.clear(),this.visibilityHandler&&"undefined"!=typeof document&&document.removeEventListener("visibilitychange",this.visibilityHandler),this.storageHandler&&"undefined"!=typeof window&&window.removeEventListener("storage",this.storageHandler),this.channel&&(this.channel.close(),this.channel=null)}},ta=/* @__PURE__ */new Map;function na(e){const t=ta.get(e);t&&(t.destroy(),ta.delete(e))}var ra=Symbol.for("preact-signals");function oa(){if(la>1)la--;else{var e,t=!1;for(!function(){var e=pa;for(pa=void 0;void 0!==e;)e.S.v===e.v&&(e.S.i=e.i),e=e.o}();void 0!==aa;){var n=aa;for(aa=void 0,ca++;void 0!==n;){var r=n.u;if(n.u=void 0,n.f&=-3,!(8&n.f)&&fa(n))try{n.c()}catch(n){t||(e=n,t=!0)}n=r}}if(ca=0,la--,t)throw e}}var ia=void 0;function sa(e){var t=ia;ia=void 0;try{return e()}finally{ia=t}}var aa=void 0,la=0,ca=0,da=0,ua=0,pa=void 0,ha=0;function wa(e){if(void 0!==ia){var t=e.n;if(void 0===t||t.t!==ia)return t={i:0,S:e,p:ia.s,n:void 0,t:ia,e:void 0,x:void 0,r:t},void 0!==ia.s&&(ia.s.n=t),ia.s=t,e.n=t,32&ia.f&&e.S(t),t;if(-1===t.i)return t.i=0,void 0!==t.n&&(t.n.p=t.p,void 0!==t.p&&(t.p.n=t.n),t.p=ia.s,t.n=void 0,ia.s.n=t,ia.s=t),t}}function ga(e,t){this.v=e,this.i=0,this.n=void 0,this.t=void 0,this.l=0,this.W=null==t?void 0:t.watched,this.Z=null==t?void 0:t.unwatched,this.name=null==t?void 0:t.name}function ma(e,t){return new ga(e,t)}function fa(e){for(var t=e.s;void 0!==t;t=t.n)if(t.S.i!==t.i||!t.S.h()||t.S.i!==t.i)return!0;return!1}function va(e){for(var t=e.s;void 0!==t;t=t.n){var n=t.S.n;if(void 0!==n&&(t.r=n),t.S.n=t,t.i=-1,void 0===t.n){e.s=t;break}}}function ba(e){for(var t=e.s,n=void 0;void 0!==t;){var r=t.p;-1===t.i?(t.S.U(t),void 0!==r&&(r.n=t.n),void 0!==t.n&&(t.n.p=r)):n=t,t.S.n=t.r,void 0!==t.r&&(t.r=void 0),t=r}e.s=n}function ya(e,t){ga.call(this,void 0),this.x=e,this.s=void 0,this.g=ha-1,this.f=4,this.W=null==t?void 0:t.watched,this.Z=null==t?void 0:t.unwatched,this.name=null==t?void 0:t.name}function xa(e,t){return new ya(e,t)}function ka(e){var t=e.m;if(e.m=void 0,"function"==typeof t){la++;var n=ia;ia=void 0;try{t()}catch(oa){throw e.f&=-2,e.f|=8,_a(e),oa}finally{ia=n,oa()}}}function _a(e){for(var t=e.s;void 0!==t;t=t.n)t.S.U(t);e.x=void 0,e.s=void 0,ka(e)}function Sa(e){if(ia!==this)throw new Error("Out-of-order effect");ba(this),ia=e,this.f&=-2,8&this.f&&_a(this),oa()}function Ca(e,t){this.x=e,this.m=void 0,this.s=void 0,this.u=void 0,this.f=32,this.name=null==t?void 0:t.name}function Ia(e,t){var n=new Ca(e,t);try{n.c()}catch(e){throw n.d(),e}var r=n.d.bind(n);return r[Symbol.dispose]=r,r}ga.prototype.brand=ra,ga.prototype.h=function(){return!0},ga.prototype.S=function(e){var t=this,n=this.t;n!==e&&void 0===e.e&&(e.x=n,this.t=e,void 0!==n?n.e=e:sa(function(){var e;null==(e=t.W)||e.call(t)}))},ga.prototype.U=function(e){var t=this;if(void 0!==this.t){var n=e.e,r=e.x;void 0!==n&&(n.x=r,e.e=void 0),void 0!==r&&(r.e=n,e.x=void 0),e===this.t&&(this.t=r,void 0===r&&sa(function(){var e;null==(e=t.Z)||e.call(t)}))}},ga.prototype.subscribe=function(e){var t=this;return Ia(function(){var n=t.value,r=ia;ia=void 0;try{e(n)}finally{ia=r}},{name:"sub"})},ga.prototype.valueOf=function(){return this.value},ga.prototype.toString=function(){return this.value+""},ga.prototype.toJSON=function(){return this.value},ga.prototype.peek=function(){var e=ia;ia=void 0;try{return this.value}finally{ia=e}},Object.defineProperty(ga.prototype,"value",{get:function(){var e=wa(this);return void 0!==e&&(e.i=this.i),this.v},set:function(e){if(e!==this.v){if(ca>100)throw new Error("Cycle detected");!function(e){0!==la&&0===ca&&e.l!==ua&&(e.l=ua,pa={S:e,v:e.v,i:e.i,o:pa})}(this),this.v=e,this.i++,ha++,la++;try{for(var t=this.t;void 0!==t;t=t.x)t.t.N()}finally{oa()}}}}),ya.prototype=new ga,ya.prototype.h=function(){if(this.f&=-3,1&this.f)return!1;if(32==(36&this.f))return!0;if(this.f&=-5,this.g===ha)return!0;if(this.g=ha,this.f|=1,this.i>0&&!fa(this))return this.f&=-2,!0;var e=ia;try{va(this),ia=this;var t=this.x();(16&this.f||this.v!==t||0===this.i)&&(this.v=t,this.f&=-17,this.i++)}catch(e){this.v=e,this.f|=16,this.i++}return ia=e,ba(this),this.f&=-2,!0},ya.prototype.S=function(e){if(void 0===this.t){this.f|=36;for(var t=this.s;void 0!==t;t=t.n)t.S.S(t)}ga.prototype.S.call(this,e)},ya.prototype.U=function(e){if(void 0!==this.t&&(ga.prototype.U.call(this,e),void 0===this.t)){this.f&=-33;for(var t=this.s;void 0!==t;t=t.n)t.S.U(t)}},ya.prototype.N=function(){if(!(2&this.f)){this.f|=6;for(var e=this.t;void 0!==e;e=e.x)e.t.N()}},Object.defineProperty(ya.prototype,"value",{get:function(){if(1&this.f)throw new Error("Cycle detected");var e=wa(this);if(this.h(),void 0!==e&&(e.i=this.i),16&this.f)throw this.v;return this.v}}),Ca.prototype.c=function(){var e=this.S();try{if(8&this.f)return;if(void 0===this.x)return;var t=this.x();"function"==typeof t&&(this.m=t)}finally{e()}},Ca.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,ka(this),va(this),la++;var e=ia;return ia=this,Sa.bind(this,e)},Ca.prototype.N=function(){2&this.f||(this.f|=2,this.u=aa,aa=this)},Ca.prototype.d=function(){this.f|=8,1&this.f||_a(this)},Ca.prototype.dispose=function(){this.d()};var Ta,$a,Ea="undefined"!=typeof window&&!!window.__PREACT_SIGNALS_DEVTOOLS__,Aa=[];function za(e,n){t[e]=n.bind(null,t[e]||function(){})}function Ra(e){if($a){var t=$a;$a=void 0,t()}$a=e&&e.S()}function Ma(e){var t=this,n=e.data,o=function(e,t){return ce(function(){return ma(e,t)},[])}(n);o.value=n;var i=ce(function(){for(var e=t,n=t.__v;n=n.__;)if(n.__c){n.__c.__$f|=4;break}var i=xa(function(){var e=o.value.value;return 0===e?0:!0===e?"":e||""}),s=xa(function(){return!Array.isArray(i.value)&&!r(i.value)}),a=Ia(function(){if(this.N=Ba,s.value){var t=i.value;e.__v&&e.__v.__e&&3===e.__v.__e.nodeType&&(e.__v.__e.data=t)}}),l=t.__$u.d;return t.__$u.d=function(){a(),l.call(this)},[s,i]},[]),s=i[0],a=i[1];return s.value?a.peek():a.value}function La(e,t,n,r){var o=t in e&&void 0===e.ownerSVGElement,i=ma(n),s=n.peek();return{o:function(e,t){i.value=e,s=e.peek()},d:Ia(function(){this.N=Ba;var n=i.value.value;s!==n?(s=void 0,o?e[t]=n:null==n||!1===n&&"-"!==t[4]?e.removeAttribute(t):e.setAttribute(t,n)):s=void 0})}}Ia(function(){Ta=this.N})(),Ma.displayName="ReactiveTextNode",Object.defineProperties(ga.prototype,{constructor:{configurable:!0,value:void 0},type:{configurable:!0,value:Ma},props:{configurable:!0,get:function(){var e=this;return{data:{get value(){return e.value}}}}},__b:{configurable:!0,value:1}}),za("__b",function(e,t){if("string"==typeof t.type){var n,r=t.props;for(var o in r)if("children"!==o){var i=r[o];i instanceof ga&&(n||(t.__np=n={}),n[o]=i,r[o]=i.peek())}}e(t)}),za("__r",function(e,t){if(e(t),t.type!==_){Ra();var n,r=t.__c;r&&(r.__$f&=-2,void 0===(n=r.__$u)&&(r.__$u=n=function(e,t){var n;return Ia(function(){n=this},{name:t}),n.c=e,n}(function(){var e;Ea&&(null==(e=n.y)||e.call(n)),r.__$f|=1,r.setState({})},"function"==typeof t.type?t.type.displayName||t.type.name:""))),Ra(n)}}),za("__e",function(e,t,n,r){Ra(),e(t,n,r)}),za("diffed",function(e,t){var n;if(Ra(),"string"==typeof t.type&&(n=t.__e)){var r=t.__np,o=t.props;if(r){var i=n.U;if(i)for(var s in i){var a=i[s];void 0===a||s in r||(a.d(),i[s]=void 0)}else i={},n.U=i;for(var l in r){var c=i[l],d=r[l];void 0===c?(c=La(n,l,d),i[l]=c):c.o(d,o)}for(var u in r)o[u]=r[u]}}e(t)}),za("unmount",function(e,t){if("string"==typeof t.type){var n=t.__e;if(n){var r=n.U;if(r)for(var o in n.U=void 0,r){var i=r[o];i&&i.d()}}t.__np=void 0}else{var s=t.__c;if(s){var a=s.__$u;a&&(s.__$u=void 0,a.d())}}e(t)}),za("__h",function(e,t,n,r){(r<3||9===r)&&(t.__$f|=2),e(t,n,r)}),S.prototype.shouldComponentUpdate=function(e,t){if(this.__R)return!0;var n=this.__$u,r=n&&void 0!==n.s;for(var o in t)return!0;if(this.__f||"boolean"==typeof this.u&&!0===this.u){var i=2&this.__$f;if(!(r||i||4&this.__$f))return!0;if(1&this.__$f)return!0}else{if(!(r||4&this.__$f))return!0;if(3&this.__$f)return!0}for(var s in e)if("__source"!==s&&e[s]!==this.props[s])return!0;for(var a in this.props)if(!(a in e))return!0;return!1};"undefined"==typeof requestAnimationFrame&&setTimeout;var Oa=function(e){queueMicrotask(function(){queueMicrotask(e)})};function Da(){!function(e){if(la>0)return e();ua=++da,la++;try{return e()}finally{oa()}}(function(){for(var e;e=Aa.shift();)Ta.call(e)})}function Ba(){1===Aa.push(this)&&(t.requestAnimationFrame||Oa)(Da)}var Pa=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Fa(e){return Pa.test(e)}function Ua(e,t){let n=e;const r=ma(!1),o=ma([]),i=ma(!1),s=ma(null),a=ma(null),l=ma(null),c=ma(!1),d=ma(!1),u=ma(""),p=ma(!1),h=ma(!1),w=ma(!1),g=ma(/* @__PURE__ */new Set),m=ma("normal"),f=ma(!1),v=ma(!1),b=ma(null),y=ma(!0),x=ma(!1);let k=null,_=!1;function S(){!_&&t&&t.notifyStateChanged({isOpen:r.value,isLoading:i.value,isSessionExpired:x.value})}const C=xa(()=>o.value.some(e=>"message"===e.kind&&!e.metadata?.isPersistentWelcome));function I(e){const n={...e,id:crypto.randomUUID(),timestamp:e.timestamp||/* @__PURE__ */new Date};return o.value=[...o.value,n],!_&&t&&t.notifyEventAdded(n),n}function T(e,n=!1){const r=s.value;s.value=e,c.value=n,e&&e!==r?(l.value=/* @__PURE__ */new Date,!_&&t&&t.notifySessionCreated(e)):e||(l.value=null)}function $(){const e=s.value,r=l.value;if(n){const t=o.value.filter(e=>"message"===e.kind&&!e.metadata?.isPersistentWelcome).length;n.emit("sessionClear",{timestamp:/* @__PURE__ */(new Date).toISOString(),sessionId:e,messageCount:t})}if(n&&e&&r){const t=/* @__PURE__ */new Date,o=t.getTime()-r.getTime();n.emit("sessionEnd",{timestamp:t.toISOString(),sessionId:e,duration:o})}const a=o.value.filter(e=>"message"===e.kind&&e.metadata?.isPersistentWelcome),d=o.value.filter(e=>"disclaimer"===e.kind&&e.metadata?.isPersistentDisclaimer);if(o.value=[],s.value=null,l.value=null,c.value=!1,x.value=!1,u.value="",i.value=!1,g.value=/* @__PURE__ */new Set,"undefined"!=typeof window&&window.sessionStorage)try{window.sessionStorage.removeItem(`ncw-spoken-messages-${e||"default"}`)}catch{}!_&&t&&t.notifySessionCleared(),S();const p=a.map(e=>"message"===e.kind&&e.metadata?.actions?{...e,metadata:{...e.metadata,actionStates:_e.initializeActionStates(e.id,e.metadata.actions.actions)}}:e);o.value=[...d,...p]}function E(e){w.value=e}function A(e){const t=m.value;if(m.value=e,n&&t!==e){const r="compact"===e||"small"===e||"minimized"===e,o="compact"===t||"small"===t||"minimized"===t;r&&!o?n.emit("minimize",{timestamp:/* @__PURE__ */(new Date).toISOString(),sessionId:s.value,previousMode:t}):!r&&o&&n.emit("maximize",{timestamp:/* @__PURE__ */(new Date).toISOString(),sessionId:s.value,previousMode:t})}if("undefined"!=typeof window&&window.localStorage)try{window.localStorage.setItem("ncw-window-size-mode",e)}catch{}}return{isOpen:r,events:o,isLoading:i,currentSessionId:s,currentUserId:a,sessionStartTime:l,isExplicitSession:c,isExplicitUser:d,inputValue:u,hasMessages:C,isTTSEnabled:p,isTTSAvailable:h,isTTSSpeaking:w,spokenMessageIds:g,windowSizeMode:m,isSidenavMaximized:f,isReadOnly:v,readOnlyIndicator:b,readOnlyAllowCopy:y,isSessionExpired:x,toggleChat:function(){if(r.value=!r.value,S(),n){const e=r.value?"open":"close";n.emit(e,{timestamp:/* @__PURE__ */(new Date).toISOString(),sessionId:s.value})}!r.value&&w.value&&(vo.stop(),E(!1))},openChat:function(){const e=r.value;r.value=!0,e||S(),!e&&n&&n.emit("open",{timestamp:/* @__PURE__ */(new Date).toISOString(),sessionId:s.value})},closeChat:function(){const e=r.value;w.value&&(vo.stop(),E(!1)),r.value=!1,e&&S(),e&&n&&n.emit("close",{timestamp:/* @__PURE__ */(new Date).toISOString(),sessionId:s.value})},addEvent:I,updateEvent:function(e,n){o.value=o.value.map(t=>t.id===e?{...t,...n}:t),!_&&t&&t.notifyEventUpdated(e,n)},removeEvent:function(e){o.value=o.value.filter(t=>t.id!==e)},clearEvents:function(){const e=o.value.filter(e=>"message"===e.kind&&e.metadata?.isPersistentWelcome),t=o.value.filter(e=>"disclaimer"===e.kind&&e.metadata?.isPersistentDisclaimer),n=e.map(e=>"message"===e.kind&&e.metadata?.actions?{...e,metadata:{...e.metadata,actionStates:_e.initializeActionStates(e.id,e.metadata.actions.actions)}}:e);o.value=[...t,...n],s.value=null,l.value=null},clearStoredEvents:function(e){const{keepCount:n,beforeDate:r}="number"==typeof e?{keepCount:e}:e??{};if(n&&!(n<=0)||r){let e=o.value;if(r){const t=(i=r)instanceof Date?i:new Date(i);e=e.filter(e=>e.timestamp>=t)}n&&n>0&&e.length>n&&(e=e.slice(-n)),o.value=e}else{const e=o.value.filter(e=>"message"===e.kind&&e.metadata?.isPersistentWelcome),t=o.value.filter(e=>"disclaimer"===e.kind&&e.metadata?.isPersistentDisclaimer),n=e.map(e=>"message"===e.kind&&e.metadata?.actions?{...e,metadata:{...e.metadata,actionStates:_e.initializeActionStates(e.id,e.metadata.actions.actions)}}:e);o.value=[...t,...n]}var i;t&&t.clearEvents(e)},createPersistentWelcomeEvent:function(e,t,n){const r=crypto.randomUUID();return{id:r,kind:"message",timestamp:/* @__PURE__ */new Date,role:"assistant",content:e,format:"markdown",metadata:{isPersistentWelcome:!0,isWelcomeBubble:"bubble"===t,actions:n,actionStates:n?_e.initializeActionStates(r,n.actions):void 0}}},insertPersistentWelcomeEvent:function(e){const n=[...o.value];let r=0,i=null;for(let t=n.length-1;t>=0;t--)if("session_start"===n[t].kind){r=t+1,i=new Date(n[t].timestamp);break}!i&&n.length>0&&(i=new Date(n[0].timestamp));const s={...e,timestamp:i?new Date(i.getTime()+(r>0?1:-1)):/* @__PURE__ */new Date};n.splice(r,0,s),o.value=n,!_&&t&&t.notifyEventAdded(s)},createPersistentDisclaimerEvent:function(e,t="markdown",n=!1,r,o=!1,i){return{id:crypto.randomUUID(),kind:"disclaimer",timestamp:/* @__PURE__ */new Date,content:e,contentFormat:t,metadata:{isPersistentDisclaimer:!0,requiresAcceptance:n,accepted:o,acceptedAt:i,acceptButtonText:r}}},acceptDisclaimer:function(){const e=o.value.find(e=>"disclaimer"===e.kind&&e.metadata?.isPersistentDisclaimer);if(e&&"disclaimer"===e.kind){const t={...e,metadata:{...e.metadata,isPersistentDisclaimer:!0,accepted:!0,acceptedAt:/* @__PURE__ */(new Date).toISOString()}};o.value=o.value.map(n=>n.id===e.id?t:n)}},isDisclaimerEventAccepted:function(){const e=o.value.find(e=>"disclaimer"===e.kind&&e.metadata?.isPersistentDisclaimer);return!e||"disclaimer"!==e.kind||(!e.metadata?.requiresAcceptance||!0===e.metadata?.accepted)},setSessionId:T,setInputValue:function(e){const t=u.value;u.value=e,n&&(k&&clearTimeout(k),e.length>0?(n.emit("typing",{timestamp:/* @__PURE__ */(new Date).toISOString(),sessionId:s.value,text:e,length:e.length}),k=setTimeout(()=>{n&&n.emit("typingStop",{timestamp:/* @__PURE__ */(new Date).toISOString(),sessionId:s.value}),k=null},1e3)):t.length>0&&n.emit("typingStop",{timestamp:/* @__PURE__ */(new Date).toISOString(),sessionId:s.value}))},clearInput:function(){u.value=""},initializeEvents:function(e){e&&e.length>0&&(o.value=e),function(){if("undefined"!=typeof window&&window.sessionStorage)try{const e=window.sessionStorage.getItem(`ncw-spoken-messages-${s.value||"default"}`);if(e){const t=JSON.parse(e);g.value=new Set(t)}}catch{}}()},resetChat:$,startNewSession:function(e,t){let r=null,a=!1;if(e){if(!Fa(e))throw new Error(`Invalid sessionId: must be a valid UUID format. Got: ${e}`);r=e,a=!0}const c=s.value,d=l.value;if(n&&c&&d){const e=/* @__PURE__ */new Date,t=e.getTime()-d.getTime();n.emit("sessionEnd",{timestamp:e.toISOString(),sessionId:c,duration:t})}const p=o.value.filter(e=>"message"===e.kind&&e.metadata?.isPersistentWelcome),h=o.value.filter(e=>"disclaimer"===e.kind&&e.metadata?.isPersistentDisclaimer);if(o.value=[],u.value="",i.value=!1,g.value=/* @__PURE__ */new Set,"undefined"!=typeof window&&window.sessionStorage)try{window.sessionStorage.removeItem(`ncw-spoken-messages-${c||"default"}`)}catch{}return T(r,a),h.length>0&&(o.value=[...h]),I({kind:"session_start",...r?{sessionId:r}:{},message:t}),p.forEach(e=>{let t={...e,timestamp:/* @__PURE__ */new Date};"message"===e.kind&&e.metadata?.actions&&(t={...t,metadata:{...t.metadata,actionStates:_e.initializeActionStates(e.id,e.metadata.actions.actions)}}),o.value=[...o.value,t]}),n&&r&&n.emit("sessionStart",{timestamp:/* @__PURE__ */(new Date).toISOString(),sessionId:r}),r},toggleTTS:function(){p.value=!p.value},setTTSEnabled:function(e){p.value=e},setTTSAvailable:function(e){h.value=e},setTTSSpeaking:E,markMessageAsSpoken:function(e){g.value=new Set([...g.value,e]),function(){if("undefined"!=typeof window&&window.sessionStorage)try{const e=Array.from(g.value);window.sessionStorage.setItem(`ncw-spoken-messages-${s.value||"default"}`,JSON.stringify(e))}catch{}}()},isMessageSpoken:function(e){return g.value.has(e)},setWindowSizeMode:A,cycleWindowSize:function(e){e&&0!==e.length||(e=["normal","expanded"]);const t=(e.indexOf(m.value)+1)%e.length;A(e[t])},toggleSidenavMaximized:function(){f.value=!f.value},setLoading:function(e){i.value=e,S()},setReadOnly:function(e,t){const r=v.value,o=b.value,i=y.value;v.value=e,void 0!==t?.indicator?b.value=t.indicator:e||(b.value=null),void 0!==t?.allowCopy&&(y.value=t.allowCopy);const a=r!==e,l=JSON.stringify(o)!==JSON.stringify(b.value),c=i!==y.value;(a||l||c)&&n&&n.emit("readOnlyChange",{timestamp:/* @__PURE__ */(new Date).toISOString(),sessionId:s.value,readOnly:e,indicator:b.value})},initializeReadOnly:function(e,t){v.value=e,t&&(b.value=t)},setSessionExpired:function(e){x.value=e,S(),e&&n&&n.emit("sessionExpired",{timestamp:/* @__PURE__ */(new Date).toISOString(),sessionId:s.value,startNewConversation:()=>$()})},applyRemoteSessionCreated:function(e){_=!0;try{s.value&&s.value===e||(s.value=e,l.value=/* @__PURE__ */new Date,c.value=!1)}finally{_=!1}},applyRemoteSessionCleared:function(){_=!0;try{const e=o.value.filter(e=>"message"===e.kind&&e.metadata?.isPersistentWelcome),t=o.value.filter(e=>"disclaimer"===e.kind&&e.metadata?.isPersistentDisclaimer);o.value=[],s.value=null,l.value=null,c.value=!1,u.value="",i.value=!1,g.value=/* @__PURE__ */new Set,o.value=[...t,...e]}finally{_=!1}},applyRemoteEventAdded:function(e){_=!0;try{o.value.some(t=>t.id===e.id)||(o.value=[...o.value,e])}finally{_=!1}},applyRemoteEventUpdated:function(e,t){_=!0;try{o.value=o.value.map(n=>n.id===e?{...n,...t}:n)}finally{_=!1}},applyRemoteStateChanged:function(e){_=!0;try{r.value=e.isOpen,i.value=e.isLoading,void 0!==e.isSessionExpired&&(x.value=e.isSessionExpired)}finally{_=!1}},applyFullSync:function(e){_=!0;try{e.sessionId&&(s.value=e.sessionId,l.value=/* @__PURE__ */new Date);const t=new Map(e.events.map(e=>[e.id,e])),n=o.value.filter(e=>!t.has(e.id)),a=e.events,c=/* @__PURE__ */new Set,d=[];for(const e of a)c.has(e.id)||(c.add(e.id),d.push(e));for(const e of n)c.has(e.id)||(c.add(e.id),d.push(e));d.sort((e,t)=>new Date(e.timestamp).getTime()-new Date(t.timestamp).getTime()),o.value=d,r.value=e.isOpen,i.value=e.isLoading,void 0!==e.isSessionExpired&&(x.value=e.isSessionExpired)}finally{_=!1}},setEventEmitter:e=>{n=e}}}var Wa=new class{stores=/* @__PURE__ */new Map;getStore(e,t,n=!0,r){if(this.stores.has(e))t&&this.stores.get(e).store.setEventEmitter(t);else{let o=null;n&&"undefined"!=typeof window&&(o=function(e,t){let n=ta.get(e);return n?t&&n.updateCallbacks(t):(n=new ea({experienceId:e,maxStoredEvents:t?.maxStoredEvents,...t}),ta.set(e,n)),n}(e,{maxStoredEvents:r}));const i=Ua(t,o||void 0);o&&(this.wireCoordinatorToStore(o,i,e),this.hydrateFromStorage(o,i)),this.stores.set(e,{store:i,coordinator:o})}return this.stores.get(e).store}wireCoordinatorToStore(e,t,n){e.updateCallbacks({onSessionCreated:e=>{t.applyRemoteSessionCreated(e)},onSessionCleared:()=>{t.applyRemoteSessionCleared()},onEventAdded:e=>{t.applyRemoteEventAdded(e)},onEventUpdated:(e,n)=>{t.applyRemoteEventUpdated(e,n)},onStateChanged:e=>{t.applyRemoteStateChanged(e)},onFullSync:e=>{t.applyFullSync(e)}})}hydrateFromStorage(e,t){if(e.getStoredSessionId()&&null===t.currentSessionId.value){const n=e.reconcileFromStorage();n&&t.applyFullSync(n)}}hasStore(e){return this.stores.has(e)}clearStore(e){const t=this.stores.get(e);t&&t.store.resetChat()}removeStore(e){this.stores.get(e)?.coordinator&&na(e),this.stores.delete(e)}clearAll(){this.stores.forEach((e,t)=>{e.store.resetChat(),e.coordinator&&na(t)}),this.stores.clear()}};var Ha=!1;function Na(e,t){let n=window.__nexusChatWidgetCSS;if(!n&&e&&(n=function(){const e=document.head.querySelectorAll("style"),t=[];for(const n of e){const e=n.textContent||"";(n.hasAttribute("data-vite-dev-id")||e.includes("ncw:")||e.includes("ncw-")||e.includes("[data-widget-container]"))&&t.push(e)}return t.length>0?(console.log(`[nexus-chat] Dev mode: collected CSS from ${t.length} style tags`),t.join("\n")):null}()||void 0),!n)return console.warn("[nexus-chat] No compiled CSS found in window.__nexusChatWidgetCSS"),null;if(e&&t){const e=document.createElement("style");return e.setAttribute("data-nexus-chat-styles","true"),e.textContent=n,t.appendChild(e),e}{if(Ha)return null;const e=document.createElement("style");return e.setAttribute("data-nexus-chat-styles","true"),e.textContent=n,document.head.appendChild(e),Ha=!0,e}}var qa=class{listeners=/* @__PURE__ */new Map;onceListeners=/* @__PURE__ */new Map;on(e,t){this.listeners.has(e)||this.listeners.set(e,/* @__PURE__ */new Set),this.listeners.get(e).add(t)}once(e,t){this.onceListeners.has(e)||this.onceListeners.set(e,/* @__PURE__ */new Set),this.onceListeners.get(e).add(t)}off(e,t){const n=this.listeners.get(e);n&&(n.delete(t),0===n.size&&this.listeners.delete(e));const r=this.onceListeners.get(e);r&&(r.delete(t),0===r.size&&this.onceListeners.delete(e))}removeAllListeners(e){e?(this.listeners.delete(e),this.onceListeners.delete(e)):(this.listeners.clear(),this.onceListeners.clear())}emit(e,t){const n=this.listeners.get(e);n&&n.forEach(n=>{try{n(t)}catch(r){console.error(`Error in ${e} event listener:`,r)}});const r=this.onceListeners.get(e);r&&(r.forEach(n=>{try{n(t)}catch(r){console.error(`Error in ${e} once listener:`,r)}}),this.onceListeners.delete(e))}listenerCount(e){const t=this.listeners.get(e),n=this.onceListeners.get(e);return(t?.size||0)+(n?.size||0)}};function ja(e,t){let n,r;"undefined"!=typeof document&&(document.querySelector('meta[name="viewport"]')||console.warn('[Nexus Chat Widget] No viewport meta tag found. Add this to your <head> for proper mobile rendering:\n<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">'));let o=!1;if(t)n=t;else if(e.container)n=e.container;else if(e.containerId){const t=document.getElementById(e.containerId);t?n=t:(n=document.createElement("div"),n.id=e.containerId,o=!0)}else o=!0,n=document.createElement("div"),n.id=e.containerId||"nexus-chat-widget-root";if(n.setAttribute("data-widget-container","true"),e.useShadowDOM){const e=n.attachShadow({mode:"open"});Na(!0,e);const t=document.createElement("div");t.setAttribute("data-widget-container","true"),t.setAttribute("data-shadow-host","true"),e.appendChild(t),t.style.all="initial",t.style.fontFamily="-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif",t.style.fontSize="16px",t.style.fontWeight="400",t.style.fontStyle="normal",t.style.lineHeight="1.5",t.style.color="#111827",t.style.textAlign="left",t.style.visibility="visible",t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.boxSizing="border-box",t.style.letterSpacing="normal",t.style.textTransform="none",t.style.whiteSpace="normal",t.style.wordSpacing="normal",t.style.textIndent="0",t.style.cursor="auto",r=t,n.__shadowRoot=e}else Na(!1),r=n;if(e.typography?.baseFontSize){const t=Be(e.typography.baseFontSize);t&&(r.style.fontSize=t)}if(e.embedded)n.setAttribute("data-embedded","true"),n.style.width="100%",n.style.height="100%",n.style.display="flex",n.style.flexDirection="column";else if("sidenav"===e.layout){n.setAttribute("data-layout","sidenav");const t=e.window?.zIndex??999999,r=e.window?.sideWidth||"500px",o=e.button?.position||"bottom-right",i=Se()?"8px":"20px",s="bottom-left"===o?"left":"right",a=`max(${i}, env(safe-area-inset-${s}))`,l=`max(${i}, env(safe-area-inset-bottom))`;n.style.cssText=`\n position: fixed !important;\n bottom: ${l} !important;\n ${s}: ${a} !important;\n ${"left"===s?"right":"left"}: auto !important;\n z-index: ${t} !important;\n `,n.__sidenavConfig={sideWidth:r,zIndex:t}}else{const t=e.button?.position||"bottom-right",r=e.window?.zIndex??999999,o=Se()?"8px":"20px",i=`max(${o}, env(safe-area-inset-bottom))`,s=`max(${o}, env(safe-area-inset-left))`,a=`max(${o}, env(safe-area-inset-right))`;n.style.cssText="bottom-left"===t?`\n position: fixed !important;\n bottom: ${i} !important;\n left: ${s} !important;\n right: auto !important;\n z-index: ${r} !important;\n `:`\n position: fixed !important;\n bottom: ${i} !important;\n right: ${a} !important;\n left: auto !important;\n z-index: ${r} !important;\n `}o&&n&&null===n.parentNode&&document.body.appendChild(n);const i=new qa;let s;if(e.store)s=e.store,console.warn("Event emissions may not work with externally provided store instances");else if(!1!==e.advanced?.persistStore){const t=e.advanced?.storeKey||e.experienceId,n=!e.disableTabSync;s=Wa.getStore(t,i,n,e.advanced?.maxStoredEvents)}else s=Ua(i),e.disableTabSync||console.warn("[Nexus Chat Widget] persistStore is false but disableTabSync is not true. Tab synchronization has no effect when using isolated stores. Set disableTabSync: true to silence this warning.");if(e.advanced?.userId&&(s.currentUserId.value=e.advanced.userId,s.isExplicitUser.value=!0),e.advanced?.readOnly&&s.initializeReadOnly(e.advanced.readOnly,e.advanced.readOnlyIndicator),e.advanced?.sessionId)try{!function(e){if(!Fa(e))throw new Error(`Invalid sessionId: must be a valid UUID format. Got: ${e}`)}(e.advanced.sessionId),s.setSessionId(e.advanced.sessionId,!0),0===s.events.value.length&&(s.addEvent({kind:"session_start",sessionId:e.advanced.sessionId,message:void 0}),i&&i.emit("sessionStart",{timestamp:/* @__PURE__ */(new Date).toISOString(),sessionId:e.advanced.sessionId}))}catch(a){throw console.error("Failed to set initial sessionId:",a),a}if(e.messages?.welcomeMessage&&e.messages?.welcomeMessagePersistent&&s.currentSessionId.value&&!s.events.value.some(e=>"message"===e.kind&&e.metadata?.isPersistentWelcome)){const t=s.createPersistentWelcomeEvent(e.messages.welcomeMessage,e.messages.welcomeMessageDisplay,e.messages.welcomeActions);s.insertPersistentWelcomeEvent(t)}if(q(x(Xs,{config:e,store:s,eventEmitter:i,widgetContainer:n}),r),e.embedded&&function(e,t){t&&requestAnimationFrame(()=>{const t=e.clientHeight,n=e.scrollHeight;(0===t||t<200&&t===n)&&console.warn(`[Nexus Chat Widget] Container height issue detected.\n\nThe widget is in embedded mode but the container may not have proper height constraints.\nThis can cause the input area to not appear fixed at the bottom.\n\nCurrent container height: ${t}px (appears to be content-based, not constrained)\n\nTo fix this, ensure your container has explicit height:\n\n /* Option 1: Fixed height */\n #your-container { height: 500px; }\n\n /* Option 2: Viewport height */\n #your-container { height: 100vh; }\n\n /* Option 3: Flex child with parent height */\n .parent { height: 100vh; display: flex; }\n #your-container { flex: 1; min-height: 0; }\n\n /* Option 4: Absolute positioning */\n #your-container { position: absolute; top: 0; bottom: 0; left: 0; right: 0; }\n\nFor more information, see: https://docs.nexus.knowbl.com/widget/configuration#container-requirements`)})}(n,!0),!e.embedded&&"sidenav"!==e.layout){const t=()=>{const t=e.button?.position||"bottom-right",r=Se()?"8px":"20px",o=`max(${r}, env(safe-area-inset-bottom))`,i=`max(${r}, env(safe-area-inset-left))`,s=`max(${r}, env(safe-area-inset-right))`;"bottom-left"===t?(n.style.bottom=o,n.style.left=i):(n.style.bottom=o,n.style.right=s)},r=Ce(()=>{t()});n.__viewportCleanup=r}return{destroy:()=>{i.removeAllListeners(),q(null,n),!1!==e.advanced?.persistStore||e.store||s.resetChat(),e.disableTabSync||e.store||na(e.advanced?.storeKey||e.experienceId),!e.container&&n.parentNode&&n.parentNode.removeChild(n)},open:()=>{s.openChat()},close:()=>{s.closeChat()},toggle:()=>{s.toggleChat()},clearChat:()=>{s.resetChat()},startNewSession:e=>s.startNewSession(e,void 0),updateAccessToken:t=>{e.accessToken=t},setReadOnly:(e,t)=>{s.setReadOnly(e,t)},store:s,on:i.on.bind(i),once:i.once.bind(i),off:i.off.bind(i),removeAllListeners:i.removeAllListeners.bind(i)}}function Va(e){if("undefined"==typeof localStorage)return!1;try{const t=function(e){return[`ncw-session-${e}`,`ncw-events-${e}`,`ncw-state-${e}`,`ncw-lastUpdate-${e}`,`nexus-chat-disclaimer-accepted-${e}`]}(e);for(const e of t)localStorage.removeItem(e);return na(e),!0}catch(t){return console.warn("[NexusChatWidget] Failed to clear storage:",t),!1}}if("undefined"!=typeof window){const e=document.currentScript;if(e){const t=e.getAttribute("data-experience-id"),n=e.getAttribute("data-api-url")||"https://api.example.com",r=e.getAttribute("data-theme"),o=e.getAttribute("data-position"),i="true"===e.getAttribute("data-voice-enabled"),s=e.getAttribute("data-voice-language"),a="true"===e.getAttribute("data-streaming-enabled"),l=e.getAttribute("data-input-max-height");if(t){const e={experienceId:t,apiUrl:n,theme:r||"light",button:{position:o||"bottom-right"},...(i||a)&&{features:{...i&&{voice:{enabled:!0,language:s||"en-US",continuous:!1,interimResults:!0}},...a&&{streaming:{enabled:!0}}}},...l&&{input:{maxHeight:l}}};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{ja(e)}):ja(e)}}window.NexusChatWidget={init:ja,storeManager:Wa,clearStorage:Va},window["nexus-chat"]=function(e,t){"init"===e&&ja(t)}}export{Va as clearStorage,ja as initWidget};
|
|
82
|
+
/* @__PURE__ */be(Ni,{content:e.disclaimer.content,format:e.disclaimer.contentFormat}),e.disclaimer.acceptButton&&!p&&/* @__PURE__ */be("button",{onClick:$,class:"ncw:mt-2 ncw:px-3 ncw:py-1 ncw:bg-blue-600 hover:ncw:bg-blue-700 ncw:text-white ncw:rounded ncw:text-xs ncw:font-medium ncw:transition-colors",children:e.disclaimer.acceptButtonText||"I understand"}),p&&/* @__PURE__ */be("div",{class:"ncw:mt-2 ncw:text-green-600 dark:ncw:text-green-400 ncw:flex ncw:items-center ncw:gap-1",children:[/* @__PURE__ */be("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"currentColor",children:/* @__PURE__ */be("path",{d:"M5 9L2 6l.7-.7L5 7.6l4.3-4.3.7.7L5 9z"})}),/* @__PURE__ */be("span",{children:"Acknowledged"})]})]})}),!1!==e.branding?.show&&/* @__PURE__ */be("div",{class:"ncw:px-4 ncw:pb-3 ncw:pt-2",children:/* @__PURE__ */be("p",{class:"ncw:text-xs ncw:text-gray-500 dark:ncw:text-gray-400 ncw:text-center",children:e.branding?.text||"Powered by Knowbl"})})]})]})})}function Xs({config:e,store:t,eventEmitter:n,widgetContainer:r}){const[o,i]=ie(!1);return se(()=>{const n=r||document.getElementById("nexus-chat-widget-root")||document.querySelector("[data-widget-container]");if(n&&n.setAttribute("data-theme",e.theme||"light"),e.embedded&&(t.isOpen.value=!0),e.advanced?.initialEvents&&(t.initializeEvents(e.advanced.initialEvents),e.messages?.welcomeMessage&&e.messages?.welcomeMessagePersistent&&t.events.value.some(e=>"session_start"===e.kind)&&!t.events.value.some(e=>"message"===e.kind&&"metadata"in e&&e.metadata?.isPersistentWelcome))){const n=t.createPersistentWelcomeEvent(e.messages.welcomeMessage,e.messages.welcomeMessageDisplay);t.insertPersistentWelcomeEvent(n)}},[e.theme,e.embedded,r]),e.embedded?/* @__PURE__ */be(Gs,{config:e,store:t,eventEmitter:n,widgetContainer:r}):"sidenav"===e.layout?(se(()=>{if(!r)return;const n=r.__sidenavConfig,o=n?.sideWidth||e.window?.sideWidth||"500px",i=n?.zIndex??e.window?.zIndex??999999;if(t.isOpen.value){const e=window.innerWidth<=768;r.style.cssText=`\n position: fixed !important;\n top: 0 !important;\n right: 0 !important;\n bottom: 0 !important;\n left: auto !important;\n width: ${e?"100%":o} !important;\n max-width: 100% !important;\n z-index: ${i} !important;\n display: flex !important;\n flex-direction: column !important;\n margin: 0 !important;\n padding: 0 !important;\n transition: width 0.3s ease-in-out !important;\n `}else{const t=window.innerWidth<=768?"8px":"20px",n="bottom-left"===(e.button?.position||"bottom-right")?"left":"right",o=`max(${t}, env(safe-area-inset-${n}))`,s=`max(${t}, env(safe-area-inset-bottom))`;r.style.cssText=`\n position: fixed !important;\n bottom: ${s} !important;\n ${n}: ${o} !important;\n ${"left"===n?"right":"left"}: auto !important;\n z-index: ${i} !important;\n `}},[t.isOpen.value,r]),t.isOpen.value?/* @__PURE__ */be(Gs,{config:e,store:t,eventEmitter:n,widgetContainer:r,isSidenav:!0}):/* @__PURE__ */be("div",{class:"ncw:relative",children:[e.button?.callout&&!o&&/* @__PURE__ */be(ye,{config:e.button.callout,buttonPosition:e.button?.position,buttonBgColor:e.button?.backgroundColor,onDismiss:()=>i(!0)}),/* @__PURE__ */be(ke,{onClick:t.toggleChat,config:e.button})]})):/* @__PURE__ */be(_,{children:t.isOpen.value?/* @__PURE__ */be(Gs,{config:e,store:t,eventEmitter:n,widgetContainer:r}):/* @__PURE__ */be("div",{class:"ncw:relative",children:[e.button?.callout&&!o&&/* @__PURE__ */be(ye,{config:e.button.callout,buttonPosition:e.button?.position,buttonBgColor:e.button?.backgroundColor,onDismiss:()=>i(!0)}),/* @__PURE__ */be(ke,{onClick:t.toggleChat,config:e.button})]})})}var ea=class{experienceId;tabId;channel=null;options;isDestroyed=!1;maxStoredEvents;updateDebounceTimers=/* @__PURE__ */new Map;pendingUpdates=/* @__PURE__ */new Map;visibilityHandler=null;storageHandler=null;constructor(e){this.options=e,this.experienceId=e.experienceId,this.tabId=crypto.randomUUID();const t=e.maxStoredEvents??500;this.maxStoredEvents=Math.min(Math.max(t,10),2e3),this.initBroadcastChannel(),this.initVisibilityListener(),this.initStorageListener()}initBroadcastChannel(){if("undefined"!=typeof BroadcastChannel)try{this.channel=new BroadcastChannel("nexus-chat-sync"),this.channel.onmessage=e=>{this.handleMessage(e.data)}}catch(e){console.warn("[TabCoordinator] Failed to create BroadcastChannel:",e)}else console.warn("[TabCoordinator] BroadcastChannel not supported, using localStorage fallback only")}initVisibilityListener(){"undefined"!=typeof document&&(this.visibilityHandler=()=>{"visible"!==document.visibilityState||this.isDestroyed||this.reconcileFromStorage()},document.addEventListener("visibilitychange",this.visibilityHandler))}initStorageListener(){"undefined"!=typeof window&&(this.storageHandler=e=>{e.key?.startsWith("ncw-")&&!this.isDestroyed&&e.key.includes(this.experienceId)&&this.reconcileFromStorage()},window.addEventListener("storage",this.storageHandler))}handleMessage(e){if(!this.isDestroyed&&e.experienceId===this.experienceId)switch(e.type){case"session_created":this.options.onSessionCreated?.(e.sessionId);break;case"session_cleared":this.options.onSessionCleared?.();break;case"event_added":this.options.onEventAdded?.(e.event);break;case"event_updated":this.options.onEventUpdated?.(e.eventId,e.updates);break;case"state_changed":this.options.onStateChanged?.(e.state);break;case"request_sync":break;case"sync_response":e.targetTabId===this.tabId&&this.options.onFullSync?.(e.state)}}broadcast(e){const t=e;if(this.channel)try{this.channel.postMessage(t)}catch(n){console.warn("[TabCoordinator] Failed to broadcast message:",n)}}getStorageKey(e){return`ncw-${e}-${this.experienceId}`}getFromStorage(e){if("undefined"==typeof localStorage)return null;try{const t=localStorage.getItem(this.getStorageKey(e));return t?JSON.parse(t):null}catch{return null}}setInStorage(e,t){if("undefined"!=typeof localStorage)try{localStorage.setItem(this.getStorageKey(e),JSON.stringify(t))}catch(n){console.warn("[TabCoordinator] Failed to write to localStorage:",n)}}removeFromStorage(e){if("undefined"!=typeof localStorage)try{localStorage.removeItem(this.getStorageKey(e))}catch{}}notifySessionCreated(e){const t=Date.now();this.setInStorage("session",e),this.setInStorage("lastUpdate",t),this.broadcast({type:"session_created",experienceId:this.experienceId,sessionId:e,timestamp:t})}notifySessionCleared(){const e=Date.now();this.removeFromStorage("session"),this.removeFromStorage("events"),this.setInStorage("lastUpdate",e),this.broadcast({type:"session_cleared",experienceId:this.experienceId,timestamp:e})}notifyEventAdded(e){const t=Date.now(),n=[...this.getFromStorage("events")||[],e],r=n.length>this.maxStoredEvents?n.slice(-this.maxStoredEvents):n;this.setInStorage("events",r),this.setInStorage("lastUpdate",t),this.broadcast({type:"event_added",experienceId:this.experienceId,event:e,timestamp:t})}notifyEventUpdated(e,t){const n=this.pendingUpdates.get(e)||{};this.pendingUpdates.set(e,{...n,...t});const r=this.updateDebounceTimers.get(e);void 0!==r&&clearTimeout(r),this.updateDebounceTimers.set(e,setTimeout(()=>{const t=this.pendingUpdates.get(e);if(t){const n=Date.now(),r=(this.getFromStorage("events")||[]).map(n=>n.id===e?{...n,...t}:n);this.setInStorage("events",r),this.setInStorage("lastUpdate",n),this.broadcast({type:"event_updated",experienceId:this.experienceId,eventId:e,updates:t,timestamp:n}),this.pendingUpdates.delete(e)}this.updateDebounceTimers.delete(e)},100))}notifyStateChanged(e){const t=Date.now();this.setInStorage("state",e),this.setInStorage("lastUpdate",t),this.broadcast({type:"state_changed",experienceId:this.experienceId,state:e,timestamp:t})}clearEvents(e){const t=Date.now(),{keepCount:n,beforeDate:r}="number"==typeof e?{keepCount:e}:e??{};if((!n||n<=0)&&!r)return this.removeFromStorage("events"),void this.setInStorage("lastUpdate",t);let o=this.getFromStorage("events")||[];if(r){const e=this.normalizeDate(r);o=o.filter(t=>new Date(t.timestamp)>=e)}n&&n>0&&o.length>n&&(o=o.slice(-n)),0===o.length?this.removeFromStorage("events"):this.setInStorage("events",o),this.setInStorage("lastUpdate",t)}normalizeDate(e){return e instanceof Date?e:new Date(e)}getStoredEventCount(){return(this.getFromStorage("events")||[]).length}reconcileFromStorage(){const e=this.getFromStorage("session"),t=this.getFromStorage("events")||[],n=this.getFromStorage("state")||{isOpen:!1,isLoading:!1,isSessionExpired:!1},r=this.getFromStorage("lastUpdate")||0,o={sessionId:e,events:t.map(e=>({...e,timestamp:new Date(e.timestamp)})),isOpen:n.isOpen,isLoading:n.isLoading,isSessionExpired:n.isSessionExpired,timestamp:r};return this.options.onFullSync&&this.options.onFullSync(o),o}getStoredSessionId(){return this.getFromStorage("session")}getStoredEvents(){return(this.getFromStorage("events")||[]).map(e=>({...e,timestamp:new Date(e.timestamp)}))}updateCallbacks(e){this.options={...this.options,...e}}destroy(){this.isDestroyed=!0,this.updateDebounceTimers.forEach(e=>clearTimeout(e)),this.updateDebounceTimers.clear(),this.pendingUpdates.clear(),this.visibilityHandler&&"undefined"!=typeof document&&document.removeEventListener("visibilitychange",this.visibilityHandler),this.storageHandler&&"undefined"!=typeof window&&window.removeEventListener("storage",this.storageHandler),this.channel&&(this.channel.close(),this.channel=null)}},ta=/* @__PURE__ */new Map;function na(e){const t=ta.get(e);t&&(t.destroy(),ta.delete(e))}var ra=Symbol.for("preact-signals");function oa(){if(la>1)la--;else{var e,t=!1;for(!function(){var e=pa;for(pa=void 0;void 0!==e;)e.S.v===e.v&&(e.S.i=e.i),e=e.o}();void 0!==aa;){var n=aa;for(aa=void 0,ca++;void 0!==n;){var r=n.u;if(n.u=void 0,n.f&=-3,!(8&n.f)&&fa(n))try{n.c()}catch(n){t||(e=n,t=!0)}n=r}}if(ca=0,la--,t)throw e}}var ia=void 0;function sa(e){var t=ia;ia=void 0;try{return e()}finally{ia=t}}var aa=void 0,la=0,ca=0,da=0,ua=0,pa=void 0,ha=0;function wa(e){if(void 0!==ia){var t=e.n;if(void 0===t||t.t!==ia)return t={i:0,S:e,p:ia.s,n:void 0,t:ia,e:void 0,x:void 0,r:t},void 0!==ia.s&&(ia.s.n=t),ia.s=t,e.n=t,32&ia.f&&e.S(t),t;if(-1===t.i)return t.i=0,void 0!==t.n&&(t.n.p=t.p,void 0!==t.p&&(t.p.n=t.n),t.p=ia.s,t.n=void 0,ia.s.n=t,ia.s=t),t}}function ga(e,t){this.v=e,this.i=0,this.n=void 0,this.t=void 0,this.l=0,this.W=null==t?void 0:t.watched,this.Z=null==t?void 0:t.unwatched,this.name=null==t?void 0:t.name}function ma(e,t){return new ga(e,t)}function fa(e){for(var t=e.s;void 0!==t;t=t.n)if(t.S.i!==t.i||!t.S.h()||t.S.i!==t.i)return!0;return!1}function va(e){for(var t=e.s;void 0!==t;t=t.n){var n=t.S.n;if(void 0!==n&&(t.r=n),t.S.n=t,t.i=-1,void 0===t.n){e.s=t;break}}}function ba(e){for(var t=e.s,n=void 0;void 0!==t;){var r=t.p;-1===t.i?(t.S.U(t),void 0!==r&&(r.n=t.n),void 0!==t.n&&(t.n.p=r)):n=t,t.S.n=t.r,void 0!==t.r&&(t.r=void 0),t=r}e.s=n}function ya(e,t){ga.call(this,void 0),this.x=e,this.s=void 0,this.g=ha-1,this.f=4,this.W=null==t?void 0:t.watched,this.Z=null==t?void 0:t.unwatched,this.name=null==t?void 0:t.name}function xa(e,t){return new ya(e,t)}function ka(e){var t=e.m;if(e.m=void 0,"function"==typeof t){la++;var n=ia;ia=void 0;try{t()}catch(oa){throw e.f&=-2,e.f|=8,_a(e),oa}finally{ia=n,oa()}}}function _a(e){for(var t=e.s;void 0!==t;t=t.n)t.S.U(t);e.x=void 0,e.s=void 0,ka(e)}function Sa(e){if(ia!==this)throw new Error("Out-of-order effect");ba(this),ia=e,this.f&=-2,8&this.f&&_a(this),oa()}function Ca(e,t){this.x=e,this.m=void 0,this.s=void 0,this.u=void 0,this.f=32,this.name=null==t?void 0:t.name}function Ia(e,t){var n=new Ca(e,t);try{n.c()}catch(e){throw n.d(),e}var r=n.d.bind(n);return r[Symbol.dispose]=r,r}ga.prototype.brand=ra,ga.prototype.h=function(){return!0},ga.prototype.S=function(e){var t=this,n=this.t;n!==e&&void 0===e.e&&(e.x=n,this.t=e,void 0!==n?n.e=e:sa(function(){var e;null==(e=t.W)||e.call(t)}))},ga.prototype.U=function(e){var t=this;if(void 0!==this.t){var n=e.e,r=e.x;void 0!==n&&(n.x=r,e.e=void 0),void 0!==r&&(r.e=n,e.x=void 0),e===this.t&&(this.t=r,void 0===r&&sa(function(){var e;null==(e=t.Z)||e.call(t)}))}},ga.prototype.subscribe=function(e){var t=this;return Ia(function(){var n=t.value,r=ia;ia=void 0;try{e(n)}finally{ia=r}},{name:"sub"})},ga.prototype.valueOf=function(){return this.value},ga.prototype.toString=function(){return this.value+""},ga.prototype.toJSON=function(){return this.value},ga.prototype.peek=function(){var e=ia;ia=void 0;try{return this.value}finally{ia=e}},Object.defineProperty(ga.prototype,"value",{get:function(){var e=wa(this);return void 0!==e&&(e.i=this.i),this.v},set:function(e){if(e!==this.v){if(ca>100)throw new Error("Cycle detected");!function(e){0!==la&&0===ca&&e.l!==ua&&(e.l=ua,pa={S:e,v:e.v,i:e.i,o:pa})}(this),this.v=e,this.i++,ha++,la++;try{for(var t=this.t;void 0!==t;t=t.x)t.t.N()}finally{oa()}}}}),ya.prototype=new ga,ya.prototype.h=function(){if(this.f&=-3,1&this.f)return!1;if(32==(36&this.f))return!0;if(this.f&=-5,this.g===ha)return!0;if(this.g=ha,this.f|=1,this.i>0&&!fa(this))return this.f&=-2,!0;var e=ia;try{va(this),ia=this;var t=this.x();(16&this.f||this.v!==t||0===this.i)&&(this.v=t,this.f&=-17,this.i++)}catch(e){this.v=e,this.f|=16,this.i++}return ia=e,ba(this),this.f&=-2,!0},ya.prototype.S=function(e){if(void 0===this.t){this.f|=36;for(var t=this.s;void 0!==t;t=t.n)t.S.S(t)}ga.prototype.S.call(this,e)},ya.prototype.U=function(e){if(void 0!==this.t&&(ga.prototype.U.call(this,e),void 0===this.t)){this.f&=-33;for(var t=this.s;void 0!==t;t=t.n)t.S.U(t)}},ya.prototype.N=function(){if(!(2&this.f)){this.f|=6;for(var e=this.t;void 0!==e;e=e.x)e.t.N()}},Object.defineProperty(ya.prototype,"value",{get:function(){if(1&this.f)throw new Error("Cycle detected");var e=wa(this);if(this.h(),void 0!==e&&(e.i=this.i),16&this.f)throw this.v;return this.v}}),Ca.prototype.c=function(){var e=this.S();try{if(8&this.f)return;if(void 0===this.x)return;var t=this.x();"function"==typeof t&&(this.m=t)}finally{e()}},Ca.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,ka(this),va(this),la++;var e=ia;return ia=this,Sa.bind(this,e)},Ca.prototype.N=function(){2&this.f||(this.f|=2,this.u=aa,aa=this)},Ca.prototype.d=function(){this.f|=8,1&this.f||_a(this)},Ca.prototype.dispose=function(){this.d()};var Ta,$a,Ea="undefined"!=typeof window&&!!window.__PREACT_SIGNALS_DEVTOOLS__,Aa=[];function za(e,n){t[e]=n.bind(null,t[e]||function(){})}function Ra(e){if($a){var t=$a;$a=void 0,t()}$a=e&&e.S()}function Ma(e){var t=this,n=e.data,o=function(e,t){return ce(function(){return ma(e,t)},[])}(n);o.value=n;var i=ce(function(){for(var e=t,n=t.__v;n=n.__;)if(n.__c){n.__c.__$f|=4;break}var i=xa(function(){var e=o.value.value;return 0===e?0:!0===e?"":e||""}),s=xa(function(){return!Array.isArray(i.value)&&!r(i.value)}),a=Ia(function(){if(this.N=Ba,s.value){var t=i.value;e.__v&&e.__v.__e&&3===e.__v.__e.nodeType&&(e.__v.__e.data=t)}}),l=t.__$u.d;return t.__$u.d=function(){a(),l.call(this)},[s,i]},[]),s=i[0],a=i[1];return s.value?a.peek():a.value}function La(e,t,n,r){var o=t in e&&void 0===e.ownerSVGElement,i=ma(n),s=n.peek();return{o:function(e,t){i.value=e,s=e.peek()},d:Ia(function(){this.N=Ba;var n=i.value.value;s!==n?(s=void 0,o?e[t]=n:null==n||!1===n&&"-"!==t[4]?e.removeAttribute(t):e.setAttribute(t,n)):s=void 0})}}Ia(function(){Ta=this.N})(),Ma.displayName="ReactiveTextNode",Object.defineProperties(ga.prototype,{constructor:{configurable:!0,value:void 0},type:{configurable:!0,value:Ma},props:{configurable:!0,get:function(){var e=this;return{data:{get value(){return e.value}}}}},__b:{configurable:!0,value:1}}),za("__b",function(e,t){if("string"==typeof t.type){var n,r=t.props;for(var o in r)if("children"!==o){var i=r[o];i instanceof ga&&(n||(t.__np=n={}),n[o]=i,r[o]=i.peek())}}e(t)}),za("__r",function(e,t){if(e(t),t.type!==_){Ra();var n,r=t.__c;r&&(r.__$f&=-2,void 0===(n=r.__$u)&&(r.__$u=n=function(e,t){var n;return Ia(function(){n=this},{name:t}),n.c=e,n}(function(){var e;Ea&&(null==(e=n.y)||e.call(n)),r.__$f|=1,r.setState({})},"function"==typeof t.type?t.type.displayName||t.type.name:""))),Ra(n)}}),za("__e",function(e,t,n,r){Ra(),e(t,n,r)}),za("diffed",function(e,t){var n;if(Ra(),"string"==typeof t.type&&(n=t.__e)){var r=t.__np,o=t.props;if(r){var i=n.U;if(i)for(var s in i){var a=i[s];void 0===a||s in r||(a.d(),i[s]=void 0)}else i={},n.U=i;for(var l in r){var c=i[l],d=r[l];void 0===c?(c=La(n,l,d),i[l]=c):c.o(d,o)}for(var u in r)o[u]=r[u]}}e(t)}),za("unmount",function(e,t){if("string"==typeof t.type){var n=t.__e;if(n){var r=n.U;if(r)for(var o in n.U=void 0,r){var i=r[o];i&&i.d()}}t.__np=void 0}else{var s=t.__c;if(s){var a=s.__$u;a&&(s.__$u=void 0,a.d())}}e(t)}),za("__h",function(e,t,n,r){(r<3||9===r)&&(t.__$f|=2),e(t,n,r)}),S.prototype.shouldComponentUpdate=function(e,t){if(this.__R)return!0;var n=this.__$u,r=n&&void 0!==n.s;for(var o in t)return!0;if(this.__f||"boolean"==typeof this.u&&!0===this.u){var i=2&this.__$f;if(!(r||i||4&this.__$f))return!0;if(1&this.__$f)return!0}else{if(!(r||4&this.__$f))return!0;if(3&this.__$f)return!0}for(var s in e)if("__source"!==s&&e[s]!==this.props[s])return!0;for(var a in this.props)if(!(a in e))return!0;return!1};"undefined"==typeof requestAnimationFrame&&setTimeout;var Oa=function(e){queueMicrotask(function(){queueMicrotask(e)})};function Da(){!function(e){if(la>0)return e();ua=++da,la++;try{return e()}finally{oa()}}(function(){for(var e;e=Aa.shift();)Ta.call(e)})}function Ba(){1===Aa.push(this)&&(t.requestAnimationFrame||Oa)(Da)}var Pa=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Fa(e){return Pa.test(e)}function Ua(e,t){let n=e;const r=ma(!1),o=ma([]),i=ma(!1),s=ma(null),a=ma(null),l=ma(null),c=ma(!1),d=ma(!1),u=ma(""),p=ma(!1),h=ma(!1),w=ma(!1),g=ma(/* @__PURE__ */new Set),m=ma("normal"),f=ma(!1),v=ma(!1),b=ma(null),y=ma(!0),x=ma(!1),k=ma(0);let _=null,S=!1;function C(){!S&&t&&t.notifyStateChanged({isOpen:r.value,isLoading:i.value,isSessionExpired:x.value})}const I=xa(()=>o.value.some(e=>"message"===e.kind&&!e.metadata?.isPersistentWelcome));function T(e){const n={...e,id:crypto.randomUUID(),timestamp:e.timestamp||/* @__PURE__ */new Date};return o.value=[...o.value,n],!S&&t&&t.notifyEventAdded(n),n}function $(e,n=!1){const r=s.value;s.value=e,c.value=n,e&&e!==r?(l.value=/* @__PURE__ */new Date,!S&&t&&t.notifySessionCreated(e)):e||(l.value=null)}function E(){const e=s.value,r=l.value;if(n){const t=o.value.filter(e=>"message"===e.kind&&!e.metadata?.isPersistentWelcome).length;n.emit("sessionClear",{timestamp:/* @__PURE__ */(new Date).toISOString(),sessionId:e,messageCount:t})}if(n&&e&&r){const t=/* @__PURE__ */new Date,o=t.getTime()-r.getTime();n.emit("sessionEnd",{timestamp:t.toISOString(),sessionId:e,duration:o})}const a=o.value.filter(e=>"message"===e.kind&&e.metadata?.isPersistentWelcome),d=o.value.filter(e=>"disclaimer"===e.kind&&e.metadata?.isPersistentDisclaimer);if(o.value=[],s.value=null,l.value=null,c.value=!1,x.value=!1,u.value="",i.value=!1,g.value=/* @__PURE__ */new Set,"undefined"!=typeof window&&window.sessionStorage)try{window.sessionStorage.removeItem(`ncw-spoken-messages-${e||"default"}`)}catch{}!S&&t&&t.notifySessionCleared(),C();const p=a.map(e=>"message"===e.kind&&e.metadata?.actions?{...e,metadata:{...e.metadata,actionStates:_e.initializeActionStates(e.id,e.metadata.actions.actions)}}:e);o.value=[...d,...p]}function A(e){w.value=e}function z(e){const t=m.value;if(m.value=e,n&&t!==e){const r="compact"===e||"small"===e||"minimized"===e,o="compact"===t||"small"===t||"minimized"===t;r&&!o?n.emit("minimize",{timestamp:/* @__PURE__ */(new Date).toISOString(),sessionId:s.value,previousMode:t}):!r&&o&&n.emit("maximize",{timestamp:/* @__PURE__ */(new Date).toISOString(),sessionId:s.value,previousMode:t})}if("undefined"!=typeof window&&window.localStorage)try{window.localStorage.setItem("ncw-window-size-mode",e)}catch{}}return{isOpen:r,events:o,isLoading:i,currentSessionId:s,currentUserId:a,sessionStartTime:l,isExplicitSession:c,isExplicitUser:d,inputValue:u,hasMessages:I,isTTSEnabled:p,isTTSAvailable:h,isTTSSpeaking:w,spokenMessageIds:g,windowSizeMode:m,isSidenavMaximized:f,isReadOnly:v,readOnlyIndicator:b,readOnlyAllowCopy:y,isSessionExpired:x,openFeedbackFormCount:k,toggleChat:function(){if(r.value=!r.value,C(),n){const e=r.value?"open":"close";n.emit(e,{timestamp:/* @__PURE__ */(new Date).toISOString(),sessionId:s.value})}!r.value&&w.value&&(vo.stop(),A(!1))},openChat:function(){const e=r.value;r.value=!0,e||C(),!e&&n&&n.emit("open",{timestamp:/* @__PURE__ */(new Date).toISOString(),sessionId:s.value})},closeChat:function(){const e=r.value;w.value&&(vo.stop(),A(!1)),r.value=!1,e&&C(),e&&n&&n.emit("close",{timestamp:/* @__PURE__ */(new Date).toISOString(),sessionId:s.value})},addEvent:T,updateEvent:function(e,n){o.value=o.value.map(t=>t.id===e?{...t,...n}:t),!S&&t&&t.notifyEventUpdated(e,n)},removeEvent:function(e){o.value=o.value.filter(t=>t.id!==e)},clearEvents:function(){const e=o.value.filter(e=>"message"===e.kind&&e.metadata?.isPersistentWelcome),t=o.value.filter(e=>"disclaimer"===e.kind&&e.metadata?.isPersistentDisclaimer),n=e.map(e=>"message"===e.kind&&e.metadata?.actions?{...e,metadata:{...e.metadata,actionStates:_e.initializeActionStates(e.id,e.metadata.actions.actions)}}:e);o.value=[...t,...n],s.value=null,l.value=null},clearStoredEvents:function(e){const{keepCount:n,beforeDate:r}="number"==typeof e?{keepCount:e}:e??{};if(n&&!(n<=0)||r){let e=o.value;if(r){const t=(i=r)instanceof Date?i:new Date(i);e=e.filter(e=>e.timestamp>=t)}n&&n>0&&e.length>n&&(e=e.slice(-n)),o.value=e}else{const e=o.value.filter(e=>"message"===e.kind&&e.metadata?.isPersistentWelcome),t=o.value.filter(e=>"disclaimer"===e.kind&&e.metadata?.isPersistentDisclaimer),n=e.map(e=>"message"===e.kind&&e.metadata?.actions?{...e,metadata:{...e.metadata,actionStates:_e.initializeActionStates(e.id,e.metadata.actions.actions)}}:e);o.value=[...t,...n]}var i;t&&t.clearEvents(e)},createPersistentWelcomeEvent:function(e,t,n){const r=crypto.randomUUID();return{id:r,kind:"message",timestamp:/* @__PURE__ */new Date,role:"assistant",content:e,format:"markdown",metadata:{isPersistentWelcome:!0,isWelcomeBubble:"bubble"===t,actions:n,actionStates:n?_e.initializeActionStates(r,n.actions):void 0}}},insertPersistentWelcomeEvent:function(e){const n=[...o.value];let r=0,i=null;for(let t=n.length-1;t>=0;t--)if("session_start"===n[t].kind){r=t+1,i=new Date(n[t].timestamp);break}!i&&n.length>0&&(i=new Date(n[0].timestamp));const s={...e,timestamp:i?new Date(i.getTime()+(r>0?1:-1)):/* @__PURE__ */new Date};n.splice(r,0,s),o.value=n,!S&&t&&t.notifyEventAdded(s)},createPersistentDisclaimerEvent:function(e,t="markdown",n=!1,r,o=!1,i){return{id:crypto.randomUUID(),kind:"disclaimer",timestamp:/* @__PURE__ */new Date,content:e,contentFormat:t,metadata:{isPersistentDisclaimer:!0,requiresAcceptance:n,accepted:o,acceptedAt:i,acceptButtonText:r}}},acceptDisclaimer:function(){const e=o.value.find(e=>"disclaimer"===e.kind&&e.metadata?.isPersistentDisclaimer);if(e&&"disclaimer"===e.kind){const t={...e,metadata:{...e.metadata,isPersistentDisclaimer:!0,accepted:!0,acceptedAt:/* @__PURE__ */(new Date).toISOString()}};o.value=o.value.map(n=>n.id===e.id?t:n)}},isDisclaimerEventAccepted:function(){const e=o.value.find(e=>"disclaimer"===e.kind&&e.metadata?.isPersistentDisclaimer);return!e||"disclaimer"!==e.kind||(!e.metadata?.requiresAcceptance||!0===e.metadata?.accepted)},setSessionId:$,setInputValue:function(e){const t=u.value;u.value=e,n&&(_&&clearTimeout(_),e.length>0?(n.emit("typing",{timestamp:/* @__PURE__ */(new Date).toISOString(),sessionId:s.value,text:e,length:e.length}),_=setTimeout(()=>{n&&n.emit("typingStop",{timestamp:/* @__PURE__ */(new Date).toISOString(),sessionId:s.value}),_=null},1e3)):t.length>0&&n.emit("typingStop",{timestamp:/* @__PURE__ */(new Date).toISOString(),sessionId:s.value}))},clearInput:function(){u.value=""},initializeEvents:function(e){e&&e.length>0&&(o.value=e),function(){if("undefined"!=typeof window&&window.sessionStorage)try{const e=window.sessionStorage.getItem(`ncw-spoken-messages-${s.value||"default"}`);if(e){const t=JSON.parse(e);g.value=new Set(t)}}catch{}}()},resetChat:E,startNewSession:function(e,t){let r=null,a=!1;if(e){if(!Fa(e))throw new Error(`Invalid sessionId: must be a valid UUID format. Got: ${e}`);r=e,a=!0}const c=s.value,d=l.value;if(n&&c&&d){const e=/* @__PURE__ */new Date,t=e.getTime()-d.getTime();n.emit("sessionEnd",{timestamp:e.toISOString(),sessionId:c,duration:t})}const p=o.value.filter(e=>"message"===e.kind&&e.metadata?.isPersistentWelcome),h=o.value.filter(e=>"disclaimer"===e.kind&&e.metadata?.isPersistentDisclaimer);if(o.value=[],u.value="",i.value=!1,g.value=/* @__PURE__ */new Set,"undefined"!=typeof window&&window.sessionStorage)try{window.sessionStorage.removeItem(`ncw-spoken-messages-${c||"default"}`)}catch{}return $(r,a),h.length>0&&(o.value=[...h]),T({kind:"session_start",...r?{sessionId:r}:{},message:t}),p.forEach(e=>{let t={...e,timestamp:/* @__PURE__ */new Date};"message"===e.kind&&e.metadata?.actions&&(t={...t,metadata:{...t.metadata,actionStates:_e.initializeActionStates(e.id,e.metadata.actions.actions)}}),o.value=[...o.value,t]}),n&&r&&n.emit("sessionStart",{timestamp:/* @__PURE__ */(new Date).toISOString(),sessionId:r}),r},toggleTTS:function(){p.value=!p.value},setTTSEnabled:function(e){p.value=e},setTTSAvailable:function(e){h.value=e},setTTSSpeaking:A,markMessageAsSpoken:function(e){g.value=new Set([...g.value,e]),function(){if("undefined"!=typeof window&&window.sessionStorage)try{const e=Array.from(g.value);window.sessionStorage.setItem(`ncw-spoken-messages-${s.value||"default"}`,JSON.stringify(e))}catch{}}()},isMessageSpoken:function(e){return g.value.has(e)},setWindowSizeMode:z,cycleWindowSize:function(e){e&&0!==e.length||(e=["normal","expanded"]);const t=(e.indexOf(m.value)+1)%e.length;z(e[t])},toggleSidenavMaximized:function(){f.value=!f.value},setLoading:function(e){i.value=e,C()},setReadOnly:function(e,t){const r=v.value,o=b.value,i=y.value;v.value=e,void 0!==t?.indicator?b.value=t.indicator:e||(b.value=null),void 0!==t?.allowCopy&&(y.value=t.allowCopy);const a=r!==e,l=JSON.stringify(o)!==JSON.stringify(b.value),c=i!==y.value;(a||l||c)&&n&&n.emit("readOnlyChange",{timestamp:/* @__PURE__ */(new Date).toISOString(),sessionId:s.value,readOnly:e,indicator:b.value})},setFeedbackFormOpen:function(e){k.value=Math.max(0,k.value+(e?1:-1))},initializeReadOnly:function(e,t){v.value=e,t&&(b.value=t)},setSessionExpired:function(e){x.value=e,C(),e&&n&&n.emit("sessionExpired",{timestamp:/* @__PURE__ */(new Date).toISOString(),sessionId:s.value,startNewConversation:()=>E()})},applyRemoteSessionCreated:function(e){S=!0;try{s.value&&s.value===e||(s.value=e,l.value=/* @__PURE__ */new Date,c.value=!1)}finally{S=!1}},applyRemoteSessionCleared:function(){S=!0;try{const e=o.value.filter(e=>"message"===e.kind&&e.metadata?.isPersistentWelcome),t=o.value.filter(e=>"disclaimer"===e.kind&&e.metadata?.isPersistentDisclaimer);o.value=[],s.value=null,l.value=null,c.value=!1,u.value="",i.value=!1,g.value=/* @__PURE__ */new Set,o.value=[...t,...e]}finally{S=!1}},applyRemoteEventAdded:function(e){S=!0;try{o.value.some(t=>t.id===e.id)||(o.value=[...o.value,e])}finally{S=!1}},applyRemoteEventUpdated:function(e,t){S=!0;try{o.value=o.value.map(n=>n.id===e?{...n,...t}:n)}finally{S=!1}},applyRemoteStateChanged:function(e){S=!0;try{r.value=e.isOpen,i.value=e.isLoading,void 0!==e.isSessionExpired&&(x.value=e.isSessionExpired)}finally{S=!1}},applyFullSync:function(e){S=!0;try{e.sessionId&&(s.value=e.sessionId,l.value=/* @__PURE__ */new Date);const t=new Map(e.events.map(e=>[e.id,e])),n=o.value.filter(e=>!t.has(e.id)),a=e.events,c=/* @__PURE__ */new Set,d=[];for(const e of a)c.has(e.id)||(c.add(e.id),d.push(e));for(const e of n)c.has(e.id)||(c.add(e.id),d.push(e));d.sort((e,t)=>new Date(e.timestamp).getTime()-new Date(t.timestamp).getTime()),o.value=d,r.value=e.isOpen,i.value=e.isLoading,void 0!==e.isSessionExpired&&(x.value=e.isSessionExpired)}finally{S=!1}},setEventEmitter:e=>{n=e}}}var Wa=new class{stores=/* @__PURE__ */new Map;getStore(e,t,n=!0,r){if(this.stores.has(e))t&&this.stores.get(e).store.setEventEmitter(t);else{let o=null;n&&"undefined"!=typeof window&&(o=function(e,t){let n=ta.get(e);return n?t&&n.updateCallbacks(t):(n=new ea({experienceId:e,maxStoredEvents:t?.maxStoredEvents,...t}),ta.set(e,n)),n}(e,{maxStoredEvents:r}));const i=Ua(t,o||void 0);o&&(this.wireCoordinatorToStore(o,i,e),this.hydrateFromStorage(o,i)),this.stores.set(e,{store:i,coordinator:o})}return this.stores.get(e).store}wireCoordinatorToStore(e,t,n){e.updateCallbacks({onSessionCreated:e=>{t.applyRemoteSessionCreated(e)},onSessionCleared:()=>{t.applyRemoteSessionCleared()},onEventAdded:e=>{t.applyRemoteEventAdded(e)},onEventUpdated:(e,n)=>{t.applyRemoteEventUpdated(e,n)},onStateChanged:e=>{t.applyRemoteStateChanged(e)},onFullSync:e=>{t.applyFullSync(e)}})}hydrateFromStorage(e,t){if(e.getStoredSessionId()&&null===t.currentSessionId.value){const n=e.reconcileFromStorage();n&&t.applyFullSync(n)}}hasStore(e){return this.stores.has(e)}clearStore(e){const t=this.stores.get(e);t&&t.store.resetChat()}removeStore(e){this.stores.get(e)?.coordinator&&na(e),this.stores.delete(e)}clearAll(){this.stores.forEach((e,t)=>{e.store.resetChat(),e.coordinator&&na(t)}),this.stores.clear()}};var Ha=!1;function Na(e,t){let n=window.__nexusChatWidgetCSS;if(!n&&e&&(n=function(){const e=document.head.querySelectorAll("style"),t=[];for(const n of e){const e=n.textContent||"";(n.hasAttribute("data-vite-dev-id")||e.includes("ncw:")||e.includes("ncw-")||e.includes("[data-widget-container]"))&&t.push(e)}return t.length>0?(console.log(`[nexus-chat] Dev mode: collected CSS from ${t.length} style tags`),t.join("\n")):null}()||void 0),!n)return console.warn("[nexus-chat] No compiled CSS found in window.__nexusChatWidgetCSS"),null;if(e&&t){const e=document.createElement("style");return e.setAttribute("data-nexus-chat-styles","true"),e.textContent=n,t.appendChild(e),e}{if(Ha)return null;const e=document.createElement("style");return e.setAttribute("data-nexus-chat-styles","true"),e.textContent=n,document.head.appendChild(e),Ha=!0,e}}var qa=class{listeners=/* @__PURE__ */new Map;onceListeners=/* @__PURE__ */new Map;on(e,t){this.listeners.has(e)||this.listeners.set(e,/* @__PURE__ */new Set),this.listeners.get(e).add(t)}once(e,t){this.onceListeners.has(e)||this.onceListeners.set(e,/* @__PURE__ */new Set),this.onceListeners.get(e).add(t)}off(e,t){const n=this.listeners.get(e);n&&(n.delete(t),0===n.size&&this.listeners.delete(e));const r=this.onceListeners.get(e);r&&(r.delete(t),0===r.size&&this.onceListeners.delete(e))}removeAllListeners(e){e?(this.listeners.delete(e),this.onceListeners.delete(e)):(this.listeners.clear(),this.onceListeners.clear())}emit(e,t){const n=this.listeners.get(e);n&&n.forEach(n=>{try{n(t)}catch(r){console.error(`Error in ${e} event listener:`,r)}});const r=this.onceListeners.get(e);r&&(r.forEach(n=>{try{n(t)}catch(r){console.error(`Error in ${e} once listener:`,r)}}),this.onceListeners.delete(e))}listenerCount(e){const t=this.listeners.get(e),n=this.onceListeners.get(e);return(t?.size||0)+(n?.size||0)}};function ja(e,t){let n,r;"undefined"!=typeof document&&(document.querySelector('meta[name="viewport"]')||console.warn('[Nexus Chat Widget] No viewport meta tag found. Add this to your <head> for proper mobile rendering:\n<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">'));let o=!1;if(t)n=t;else if(e.container)n=e.container;else if(e.containerId){const t=document.getElementById(e.containerId);t?n=t:(n=document.createElement("div"),n.id=e.containerId,o=!0)}else o=!0,n=document.createElement("div"),n.id=e.containerId||"nexus-chat-widget-root";if(n.setAttribute("data-widget-container","true"),e.useShadowDOM){const e=n.attachShadow({mode:"open"});Na(!0,e);const t=document.createElement("div");t.setAttribute("data-widget-container","true"),t.setAttribute("data-shadow-host","true"),e.appendChild(t),t.style.all="initial",t.style.fontFamily="-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif",t.style.fontSize="16px",t.style.fontWeight="400",t.style.fontStyle="normal",t.style.lineHeight="1.5",t.style.color="#111827",t.style.textAlign="left",t.style.visibility="visible",t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.boxSizing="border-box",t.style.letterSpacing="normal",t.style.textTransform="none",t.style.whiteSpace="normal",t.style.wordSpacing="normal",t.style.textIndent="0",t.style.cursor="auto",r=t,n.__shadowRoot=e}else Na(!1),r=n;if(e.typography?.baseFontSize){const t=Be(e.typography.baseFontSize);t&&(r.style.fontSize=t)}if(e.embedded)n.setAttribute("data-embedded","true"),n.style.width="100%",n.style.height="100%",n.style.display="flex",n.style.flexDirection="column";else if("sidenav"===e.layout){n.setAttribute("data-layout","sidenav");const t=e.window?.zIndex??999999,r=e.window?.sideWidth||"500px",o=e.button?.position||"bottom-right",i=Se()?"8px":"20px",s="bottom-left"===o?"left":"right",a=`max(${i}, env(safe-area-inset-${s}))`,l=`max(${i}, env(safe-area-inset-bottom))`;n.style.cssText=`\n position: fixed !important;\n bottom: ${l} !important;\n ${s}: ${a} !important;\n ${"left"===s?"right":"left"}: auto !important;\n z-index: ${t} !important;\n `,n.__sidenavConfig={sideWidth:r,zIndex:t}}else{const t=e.button?.position||"bottom-right",r=e.window?.zIndex??999999,o=Se()?"8px":"20px",i=`max(${o}, env(safe-area-inset-bottom))`,s=`max(${o}, env(safe-area-inset-left))`,a=`max(${o}, env(safe-area-inset-right))`;n.style.cssText="bottom-left"===t?`\n position: fixed !important;\n bottom: ${i} !important;\n left: ${s} !important;\n right: auto !important;\n z-index: ${r} !important;\n `:`\n position: fixed !important;\n bottom: ${i} !important;\n right: ${a} !important;\n left: auto !important;\n z-index: ${r} !important;\n `}o&&n&&null===n.parentNode&&document.body.appendChild(n);const i=new qa;let s;if(e.store)s=e.store,console.warn("Event emissions may not work with externally provided store instances");else if(!1!==e.advanced?.persistStore){const t=e.advanced?.storeKey||e.experienceId,n=!e.disableTabSync;s=Wa.getStore(t,i,n,e.advanced?.maxStoredEvents)}else s=Ua(i),e.disableTabSync||console.warn("[Nexus Chat Widget] persistStore is false but disableTabSync is not true. Tab synchronization has no effect when using isolated stores. Set disableTabSync: true to silence this warning.");if(e.advanced?.userId&&(s.currentUserId.value=e.advanced.userId,s.isExplicitUser.value=!0),e.advanced?.readOnly&&s.initializeReadOnly(e.advanced.readOnly,e.advanced.readOnlyIndicator),e.advanced?.sessionId)try{!function(e){if(!Fa(e))throw new Error(`Invalid sessionId: must be a valid UUID format. Got: ${e}`)}(e.advanced.sessionId),s.setSessionId(e.advanced.sessionId,!0),0===s.events.value.length&&(s.addEvent({kind:"session_start",sessionId:e.advanced.sessionId,message:void 0}),i&&i.emit("sessionStart",{timestamp:/* @__PURE__ */(new Date).toISOString(),sessionId:e.advanced.sessionId}))}catch(a){throw console.error("Failed to set initial sessionId:",a),a}if(e.messages?.welcomeMessage&&e.messages?.welcomeMessagePersistent&&s.currentSessionId.value&&!s.events.value.some(e=>"message"===e.kind&&e.metadata?.isPersistentWelcome)){const t=s.createPersistentWelcomeEvent(e.messages.welcomeMessage,e.messages.welcomeMessageDisplay,e.messages.welcomeActions);s.insertPersistentWelcomeEvent(t)}if(q(x(Xs,{config:e,store:s,eventEmitter:i,widgetContainer:n}),r),e.embedded&&function(e,t){t&&requestAnimationFrame(()=>{const t=e.clientHeight,n=e.scrollHeight;(0===t||t<200&&t===n)&&console.warn(`[Nexus Chat Widget] Container height issue detected.\n\nThe widget is in embedded mode but the container may not have proper height constraints.\nThis can cause the input area to not appear fixed at the bottom.\n\nCurrent container height: ${t}px (appears to be content-based, not constrained)\n\nTo fix this, ensure your container has explicit height:\n\n /* Option 1: Fixed height */\n #your-container { height: 500px; }\n\n /* Option 2: Viewport height */\n #your-container { height: 100vh; }\n\n /* Option 3: Flex child with parent height */\n .parent { height: 100vh; display: flex; }\n #your-container { flex: 1; min-height: 0; }\n\n /* Option 4: Absolute positioning */\n #your-container { position: absolute; top: 0; bottom: 0; left: 0; right: 0; }\n\nFor more information, see: https://docs.nexus.knowbl.com/widget/configuration#container-requirements`)})}(n,!0),!e.embedded&&"sidenav"!==e.layout){const t=()=>{const t=e.button?.position||"bottom-right",r=Se()?"8px":"20px",o=`max(${r}, env(safe-area-inset-bottom))`,i=`max(${r}, env(safe-area-inset-left))`,s=`max(${r}, env(safe-area-inset-right))`;"bottom-left"===t?(n.style.bottom=o,n.style.left=i):(n.style.bottom=o,n.style.right=s)},r=Ce(()=>{t()});n.__viewportCleanup=r}return{destroy:()=>{i.removeAllListeners(),q(null,n),!1!==e.advanced?.persistStore||e.store||s.resetChat(),e.disableTabSync||e.store||na(e.advanced?.storeKey||e.experienceId),!e.container&&n.parentNode&&n.parentNode.removeChild(n)},open:()=>{s.openChat()},close:()=>{s.closeChat()},toggle:()=>{s.toggleChat()},clearChat:()=>{s.resetChat()},startNewSession:e=>s.startNewSession(e,void 0),updateAccessToken:t=>{e.accessToken=t},setReadOnly:(e,t)=>{s.setReadOnly(e,t)},store:s,on:i.on.bind(i),once:i.once.bind(i),off:i.off.bind(i),removeAllListeners:i.removeAllListeners.bind(i)}}function Va(e){if("undefined"==typeof localStorage)return!1;try{const t=function(e){return[`ncw-session-${e}`,`ncw-events-${e}`,`ncw-state-${e}`,`ncw-lastUpdate-${e}`,`nexus-chat-disclaimer-accepted-${e}`]}(e);for(const e of t)localStorage.removeItem(e);return na(e),!0}catch(t){return console.warn("[NexusChatWidget] Failed to clear storage:",t),!1}}if("undefined"!=typeof window){const e=document.currentScript;if(e){const t=e.getAttribute("data-experience-id"),n=e.getAttribute("data-api-url")||"https://api.example.com",r=e.getAttribute("data-theme"),o=e.getAttribute("data-position"),i="true"===e.getAttribute("data-voice-enabled"),s=e.getAttribute("data-voice-language"),a="true"===e.getAttribute("data-streaming-enabled"),l=e.getAttribute("data-input-max-height");if(t){const e={experienceId:t,apiUrl:n,theme:r||"light",button:{position:o||"bottom-right"},...(i||a)&&{features:{...i&&{voice:{enabled:!0,language:s||"en-US",continuous:!1,interimResults:!0}},...a&&{streaming:{enabled:!0}}}},...l&&{input:{maxHeight:l}}};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{ja(e)}):ja(e)}}window.NexusChatWidget={init:ja,storeManager:Wa,clearStorage:Va},window["nexus-chat"]=function(e,t){"init"===e&&ja(t)}}export{Va as clearStorage,ja as initWidget};
|
|
83
83
|
//# sourceMappingURL=widget.js.map
|