vanilla-agent 1.12.0 → 1.14.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/dist/index.cjs +20 -19
- package/dist/index.cjs.map +1 -1
- package/dist/index.global.js +38 -37
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +21 -20
- package/dist/index.js.map +1 -1
- package/dist/widget.css +77 -0
- package/package.json +1 -1
- package/src/client.ts +83 -53
- package/src/styles/widget.css +77 -0
- package/src/ui.ts +13 -4
- package/src/utils/code-generators.ts +5 -1
- package/src/utils/formatting.ts +25 -7
package/dist/index.cjs
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var Ho=Object.create;var hn=Object.defineProperty;var ko=Object.getOwnPropertyDescriptor;var Ro=Object.getOwnPropertyNames;var Io=Object.getPrototypeOf,$o=Object.prototype.hasOwnProperty;var Po=(n,e)=>{for(var o in e)hn(n,o,{get:e[o],enumerable:!0})},co=(n,e,o,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Ro(e))!$o.call(n,r)&&r!==o&&hn(n,r,{get:()=>e[r],enumerable:!(t=ko(e,r))||t.enumerable});return n};var Oo=(n,e,o)=>(o=n!=null?Ho(Io(n)):{},co(e||!n||!n.__esModule?hn(o,"default",{value:n,enumerable:!0}):o,n)),No=n=>co(hn({},"__esModule",{value:!0}),n);var hr={};Po(hr,{AgentWidgetClient:()=>_t,AgentWidgetSession:()=>Yt,DEFAULT_WIDGET_CONFIG:()=>Pe,attachHeaderToContainer:()=>Jt,buildComposer:()=>Kt,buildDefaultHeader:()=>Nn,buildExpandedHeader:()=>Fn,buildHeader:()=>Pt,buildHeaderWithLayout:()=>Sn,buildMinimalHeader:()=>Dn,componentRegistry:()=>Vt,createActionManager:()=>dn,createAgentExperience:()=>Bn,createBubbleWithLayout:()=>vo,createComponentMiddleware:()=>To,createComponentStreamParser:()=>En,createFlexibleJsonStreamParser:()=>mo,createJsonStreamParser:()=>bn,createLocalStorageAdapter:()=>Tn,createPlainTextParser:()=>yn,createRegexJsonParser:()=>vn,createStandardBubble:()=>Xt,createTypingIndicator:()=>rn,createXmlParser:()=>xn,default:()=>gr,defaultActionHandlers:()=>qt,defaultJsonActionParser:()=>ln,directivePostprocessor:()=>po,escapeHtml:()=>mn,extractComponentDirectiveFromMessage:()=>Ln,generateCodeSnippet:()=>Lo,getHeaderLayout:()=>jn,hasComponentDirective:()=>Mn,headerLayouts:()=>Cn,initAgentWidget:()=>Zn,isComponentDirectiveType:()=>Ao,markdownPostprocessor:()=>$n,mergeWithDefaults:()=>An,pluginRegistry:()=>an,renderComponentDirective:()=>Wn});module.exports=No(hr);var In=require("marked");In.marked.setOptions({breaks:!0});var $n=n=>In.marked.parse(n),mn=n=>n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),Do=n=>n.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),uo=n=>`%%FORM_PLACEHOLDER_${n}%%`,Fo=(n,e)=>{let o=n;return o=o.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(t,r)=>{try{let s=JSON.parse(r.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let i=uo(e.length);return e.push({token:i,type:String(s.type)}),i}}catch{return t}return t}),o=o.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(t,r)=>{let s=uo(e.length);return e.push({token:s,type:r}),s}),o},po=n=>{let e=[],o=Fo(n,e),t=$n(o);return e.forEach(({token:r,type:s})=>{let i=new RegExp(r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),u=`<div class="tvw-form-directive" data-tv-form="${Do(s)}"></div>`;t=t.replace(i,u)}),t};var Mt=require("partial-json"),fn=n=>n.replace(/\\n/g,`
|
|
2
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Pn=n=>{if(n===null)return"null";if(n===void 0)return"";if(typeof n=="string")return n;if(typeof n=="number"||typeof n=="boolean")return String(n);try{return JSON.stringify(n,null,2)}catch{return String(n)}},jo=n=>{var i,l;let e=(i=n.completedAt)!=null?i:Date.now(),o=(l=n.startedAt)!=null?l:e,r=(n.durationMs!==void 0?n.durationMs:Math.max(0,e-o))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},go=n=>n.status==="complete"?jo(n):n.status==="pending"?"Waiting":"",_o=n=>{var r,s,i;let o=(typeof n.duration=="number"?n.duration:typeof n.durationMs=="number"?n.durationMs:Math.max(0,((r=n.completedAt)!=null?r:Date.now())-((i=(s=n.startedAt)!=null?s:n.completedAt)!=null?i:Date.now())))/1e3;return o<.1?"Used tool for <0.1 seconds":`Used tool for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`};var ho=n=>n.status==="complete"?_o(n):"Using tool...",qo=()=>{let n=null,e=0,o=t=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=t.match(r);if(s&&s[1])try{return s[1].replace(/\\n/g,`
|
|
2
3
|
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let i=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,l=t.match(i);if(l&&l[1])try{return l[1].replace(/\\n/g,`
|
|
3
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return l[1]}return null};return{getExtractedText:()=>n,processChunk:async t=>{if(t.length<=e)return n!==null?{text:n,raw:t}:null;let r=t.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=o(t);return s!==null&&(n=s),e=t.length,n!==null?{text:n,raw:t}:null},close:async()=>{}}},
|
|
4
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return l[1]}return null};return{getExtractedText:()=>n,processChunk:async t=>{if(t.length<=e)return n!==null?{text:n,raw:t}:null;let r=t.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=o(t);return s!==null&&(n=s),e=t.length,n!==null?{text:n,raw:t}:null},close:async()=>{}}},wn=n=>{try{let e=JSON.parse(n);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},yn=()=>{let n={processChunk:e=>null,getExtractedText:()=>null};return n.__isPlainTextParser=!0,n},vn=()=>{var e;let n=qo();return{processChunk:async o=>{let t=o.trim();return!t.startsWith("{")&&!t.startsWith("[")?null:n.processChunk(o)},getExtractedText:n.getExtractedText.bind(n),close:(e=n.close)==null?void 0:e.bind(n)}},bn=()=>{let n=null,e=0;return{getExtractedText:()=>n,processChunk:o=>{let t=o.trim();if(!t.startsWith("{")&&!t.startsWith("["))return null;if(o.length<=e)return n!==null||n===""?{text:n||"",raw:o}:null;try{let r=(0,Mt.parse)(o,Mt.STR|Mt.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?n=typeof r.text=="string"?fn(r.text):"":r.type==="init"&&r.form?n="":typeof r.text=="string"&&(n=fn(r.text)))}catch{}return e=o.length,n!==null?{text:n,raw:o}:null},close:()=>{}}},mo=n=>{let e=null,o=0,r=n||(s=>{if(!s||typeof s!="object")return null;let i=l=>typeof l=="string"?fn(l):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?fn(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return i(s.on_load_text)||i(s.text)||null;case"message":case"message_and_click":case"checkout":return i(s.text)||null;default:return i(s.text)||i(s.display_text)||i(s.message)||null}return i(s.text)||i(s.display_text)||i(s.message)||i(s.content)||null});return{getExtractedText:()=>e,processChunk:s=>{let i=s.trim();if(!i.startsWith("{")&&!i.startsWith("["))return null;if(s.length<=o)return e!==null?{text:e,raw:s}:null;try{let l=(0,Mt.parse)(s,Mt.STR|Mt.OBJ),u=r(l);u!==null&&(e=u)}catch{}return o=s.length,{text:e||"",raw:s}},close:()=>{}}},xn=()=>{let n=null;return{processChunk:e=>{if(!e.trim().startsWith("<"))return null;let t=e.match(/<text[^>]*>([\s\S]*?)<\/text>/);return t&&t[1]?(n=t[1],{text:n,raw:e}):null},getExtractedText:()=>n}};var Uo="https://api.travrse.ai/v1/dispatch";function zo(n){switch(n){case"json":return bn;case"regex-json":return vn;case"xml":return xn;case"plain":default:return yn}}var _t=class{constructor(e={}){this.config=e;var o,t,r;this.apiUrl=(o=e.apiUrl)!=null?o:Uo,this.headers={"Content-Type":"application/json",...e.headers},this.debug=!!e.debug,this.createStreamParser=(t=e.streamParser)!=null?t:zo(e.parserType),this.contextProviders=(r=e.contextProviders)!=null?r:[],this.requestMiddleware=e.requestMiddleware,this.customFetch=e.customFetch,this.parseSSEEvent=e.parseSSEEvent,this.getHeaders=e.getHeaders}async dispatch(e,o){let t=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>t.abort()),o({type:"status",status:"connecting"});let r=await this.buildPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",r);let s={...this.headers};if(this.getHeaders)try{let l=await this.getHeaders();s={...s,...l}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",l)}let i;if(this.customFetch)try{i=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:t.signal},r)}catch(l){let u=l instanceof Error?l:new Error(String(l));throw o({type:"error",error:u}),u}else i=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:t.signal});if(!i.ok||!i.body){let l=new Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw o({type:"error",error:l}),l}o({type:"status",status:"connected"});try{await this.streamResponse(i.body,o)}finally{o({type:"status",status:"idle"})}}async buildPayload(e){let t={messages:e.slice().sort((r,s)=>{let i=new Date(r.createdAt).getTime(),l=new Date(s.createdAt).getTime();return i-l}).map(r=>({role:r.role,content:r.rawContent||r.content,createdAt:r.createdAt})),...this.config.flowId&&{flowId:this.config.flowId}};if(this.contextProviders.length){let r={};await Promise.all(this.contextProviders.map(async s=>{try{let i=await s({messages:e,config:this.config});i&&typeof i=="object"&&Object.assign(r,i)}catch(i){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",i)}})),Object.keys(r).length&&(t.context=r)}if(this.requestMiddleware)try{let r=await this.requestMiddleware({payload:{...t},config:this.config});if(r&&typeof r=="object")return r}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",r)}return t}async handleCustomSSEEvent(e,o,t,r,s){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(e);if(i===null)return!1;let l=()=>{if(t.current)return t.current;let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s()};return t.current=u,r(u),u};if(i.text!==void 0){let u=l();u.content+=i.text,r(u)}return i.done&&(t.current&&(t.current.streaming=!1,r(t.current)),o({type:"status",status:"idle"})),i.error&&o({type:"error",error:new Error(i.error)}),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(e,o){var se,P,_e,Ye,Qe,vt,bt,D,he,ht,mt,Je,rt,M,Me,it,at,Tt,ft,ke,et,qe,F,lt,Ke,We,je,K,Se,Le,Ue,tt,xt,Lt,pt,Ct,de,Ot,Bt,ve,wt,St,Ht,yt,Et,cn,un,pn,kn,Nt,Dt,nt,Ut,Qt,en,tn;let t=e.getReader(),r=new TextDecoder,s="",i=Date.now(),l=0,u=()=>i+l++,h=y=>{let X=y.reasoning?{...y.reasoning,chunks:[...y.reasoning.chunks]}:void 0,ne=y.toolCall?{...y.toolCall,chunks:y.toolCall.chunks?[...y.toolCall.chunks]:void 0}:void 0,fe=y.tools?y.tools.map(Re=>({...Re,chunks:Re.chunks?[...Re.chunks]:void 0})):void 0;return{...y,reasoning:X,toolCall:ne,tools:fe}},d=y=>{o({type:"message",message:h(y)})},T=null,f={current:null},b=new Map,w=new Map,_={lastId:null,byStep:new Map},j={lastId:null,byCall:new Map},m=y=>{if(y==null)return null;try{return String(y)}catch{return null}},C=y=>{var X,ne,fe,Re,Ie;return m((Ie=(Re=(fe=(ne=(X=y.stepId)!=null?X:y.step_id)!=null?ne:y.step)!=null?fe:y.parentId)!=null?Re:y.flowStepId)!=null?Ie:y.flow_step_id)},$=y=>{var X,ne,fe,Re,Ie,ce,L;return m((L=(ce=(Ie=(Re=(fe=(ne=(X=y.callId)!=null?X:y.call_id)!=null?ne:y.requestId)!=null?fe:y.request_id)!=null?Re:y.toolCallId)!=null?Ie:y.tool_call_id)!=null?ce:y.stepId)!=null?L:y.step_id)},S=()=>T||(T={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u()},d(T),T),Y=(y,X)=>{_.lastId=X,y&&_.byStep.set(y,X)},I=(y,X)=>{var Ie;let ne=(Ie=y.reasoningId)!=null?Ie:y.id,fe=C(y);if(ne){let ce=String(ne);return Y(fe,ce),ce}if(fe){let ce=_.byStep.get(fe);if(ce)return _.lastId=ce,ce}if(_.lastId&&!X)return _.lastId;if(!X)return null;let Re=`reason-${u()}`;return Y(fe,Re),Re},V=y=>{let X=b.get(y);if(X)return X;let ne={id:`reason-${y}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:u(),reasoning:{id:y,status:"streaming",chunks:[]}};return b.set(y,ne),d(ne),ne},te=(y,X)=>{j.lastId=X,y&&j.byCall.set(y,X)},A=(y,X)=>{var Ie;let ne=(Ie=y.toolId)!=null?Ie:y.id,fe=$(y);if(ne){let ce=String(ne);return te(fe,ce),ce}if(fe){let ce=j.byCall.get(fe);if(ce)return j.lastId=ce,ce}if(j.lastId&&!X)return j.lastId;if(!X)return null;let Re=`tool-${u()}`;return te(fe,Re),Re},ie=y=>{let X=w.get(y);if(X)return X;let ne={id:`tool-${y}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:u(),toolCall:{id:y,status:"pending"}};return w.set(y,ne),d(ne),ne},J=y=>{if(typeof y=="number"&&Number.isFinite(y))return y;if(typeof y=="string"){let X=Number(y);if(!Number.isNaN(X)&&Number.isFinite(X))return X;let ne=Date.parse(y);if(!Number.isNaN(ne))return ne}return Date.now()},z=y=>{if(typeof y=="string")return y;if(y==null)return"";try{return JSON.stringify(y)}catch{return String(y)}},G=new Map,le=new Map;for(;;){let{done:y,value:X}=await t.read();if(y)break;s+=r.decode(X,{stream:!0});let ne=s.split(`
|
|
4
5
|
|
|
5
|
-
`);s=(se=
|
|
6
|
-
`),ve="message",Le="";for(let X of Me)X.startsWith("event:")?ve=X.replace("event:","").trim():X.startsWith("data:")&&(Le+=X.replace("data:","").trim());if(!Le)continue;let W;try{W=JSON.parse(Le)}catch(X){o({type:"error",error:X instanceof Error?X:new Error("Failed to parse chat stream payload")});continue}let ut=ve!=="message"?ve:($=W.type)!=null?$:"message";if(this.parseSSEEvent){f.current=E;let X=await this.handleCustomSSEEvent(W,o,f,d,u);if(f.current&&!E&&(E=f.current),X)continue}if(ut==="reason_start"){let X=(qe=R(W,!0))!=null?qe:`reason-${u()}`,w=V(X);w.reasoning=(Je=w.reasoning)!=null?Je:{id:X,status:"streaming",chunks:[]},w.reasoning.startedAt=(wt=w.reasoning.startedAt)!=null?wt:Y((et=W.startedAt)!=null?et:W.timestamp),w.reasoning.completedAt=void 0,w.reasoning.durationMs=void 0,w.streaming=!0,w.reasoning.status="streaming",d(w)}else if(ut==="reason_chunk"){let X=(O=(yt=R(W,!1))!=null?yt:R(W,!0))!=null?O:`reason-${u()}`,w=V(X);w.reasoning=(de=w.reasoning)!=null?de:{id:X,status:"streaming",chunks:[]},w.reasoning.startedAt=(gt=w.reasoning.startedAt)!=null?gt:Y((pt=W.startedAt)!=null?pt:W.timestamp);let g=(B=(rt=(Ke=W.reasoningText)!=null?Ke:W.text)!=null?rt:W.delta)!=null?B:"";if(g&&W.hidden!==!0&&w.reasoning.chunks.push(String(g)),w.reasoning.status=W.done?"complete":"streaming",W.done){w.reasoning.completedAt=Y((ke=W.completedAt)!=null?ke:W.timestamp);let D=(it=w.reasoning.startedAt)!=null?it:Date.now();w.reasoning.durationMs=Math.max(0,((at=w.reasoning.completedAt)!=null?at:Date.now())-D)}w.streaming=w.reasoning.status!=="complete",d(w)}else if(ut==="reason_complete"){let X=(ht=(St=R(W,!1))!=null?St:R(W,!0))!=null?ht:`reason-${u()}`,w=C.get(X);if(w!=null&&w.reasoning){w.reasoning.status="complete",w.reasoning.completedAt=Y((Pe=W.completedAt)!=null?Pe:W.timestamp);let D=(tt=w.reasoning.startedAt)!=null?tt:Date.now();w.reasoning.durationMs=Math.max(0,((Ue=w.reasoning.completedAt)!=null?Ue:Date.now())-D),w.streaming=!1,d(w)}let g=S(W);g&&j.byStep.delete(g)}else if(ut==="tool_start"){let X=(N=T(W,!0))!=null?N:`tool-${u()}`,w=re(X),g=(lt=w.toolCall)!=null?lt:{id:X,status:"pending"};g.name=(Xe=W.toolName)!=null?Xe:g.name,g.status="running",W.args!==void 0&&(g.args=W.args),g.startedAt=(Fe=g.startedAt)!=null?Fe:Y((Ee=W.startedAt)!=null?Ee:W.timestamp),g.completedAt=void 0,g.durationMs=void 0,w.toolCall=g,w.streaming=!0,d(w)}else if(ut==="tool_chunk"){let X=(ye=(J=T(W,!1))!=null?J:T(W,!0))!=null?ye:`tool-${u()}`,w=re(X),g=(Re=w.toolCall)!=null?Re:{id:X,status:"running"};g.startedAt=(nt=g.startedAt)!=null?nt:Y((ze=W.startedAt)!=null?ze:W.timestamp);let D=(ct=(Mt=(vt=W.text)!=null?vt:W.delta)!=null?Mt:W.message)!=null?ct:"";D&&(g.chunks=(bt=g.chunks)!=null?bt:[],g.chunks.push(String(D))),g.status="running",w.toolCall=g,w.streaming=!0,d(w)}else if(ut==="tool_complete"){let X=(Ot=(ie=T(W,!1))!=null?ie:T(W,!0))!=null?Ot:`tool-${u()}`,w=re(X),g=(Lt=w.toolCall)!=null?Lt:{id:X,status:"running"};if(g.status="complete",W.result!==void 0&&(g.result=W.result),typeof W.duration=="number"&&(g.duration=W.duration),g.completedAt=Y((he=W.completedAt)!=null?he:W.timestamp),typeof W.duration=="number")g.durationMs=W.duration;else{let be=(mt=g.startedAt)!=null?mt:Date.now();g.durationMs=Math.max(0,((xt=g.completedAt)!=null?xt:Date.now())-be)}w.toolCall=g,w.streaming=!1,d(w);let D=I(W);D&&F.byCall.delete(D)}else if(ut==="step_chunk"){let X=W.stepType,w=W.executionType;if(X==="tool"||w==="context")continue;let g=A(),D=(cn=(At=(ft=(Bt=W.text)!=null?Bt:W.delta)!=null?ft:W.content)!=null?At:W.chunk)!=null?cn:"";if(D){let xe=((un=ue.get(g.id))!=null?un:"")+D;g.rawContent=xe,ne.has(g.id)||ne.set(g.id,this.createStreamParser());let Ie=ne.get(g.id),Ce=xe.trim().startsWith("{")||xe.trim().startsWith("[");if(Ce&&ue.set(g.id,xe),Ie.__isPlainTextParser===!0){g.content+=D,ue.delete(g.id),ne.delete(g.id),g.rawContent=void 0,d(g);continue}let Se=Ie.processChunk(xe);if(Se instanceof Promise)Se.then(oe=>{var Be;let we=typeof oe=="string"?oe:(Be=oe==null?void 0:oe.text)!=null?Be:null;if(we!==null&&we.trim()!==""){let $e=E;$e&&$e.id===g.id&&($e.content=we,d($e))}else if(!Ce&&!xe.trim().startsWith("<")){let $e=E;$e&&$e.id===g.id&&($e.content+=D,ue.delete($e.id),ne.delete($e.id),$e.rawContent=void 0,d($e))}}).catch(()=>{g.content+=D,ue.delete(g.id),ne.delete(g.id),g.rawContent=void 0,d(g)});else{let oe=typeof Se=="string"?Se:(pn=Se==null?void 0:Se.text)!=null?pn:null;oe!==null&&oe.trim()!==""?(g.content=oe,d(g)):!Ce&&!xe.trim().startsWith("<")&&(g.content+=D,ue.delete(g.id),ne.delete(g.id),g.rawContent=void 0,d(g))}}if(W.isComplete){let be=(Ft=(Nt=W.result)==null?void 0:Nt.response)!=null?Ft:g.content;if(be){let xe=ue.get(g.id),Ie=xe!=null?xe:U(be);g.rawContent=Ie;let Ce=ne.get(g.id),De=null;if(Ce&&(De=Ce.getExtractedText(),De===null&&(De=fn(Ie)),De===null)){let oe=Ce.processChunk(Ie);oe instanceof Promise?oe.then(we=>{var $e;let Be=typeof we=="string"?we:($e=we==null?void 0:we.text)!=null?$e:null;if(Be!==null){let je=E;je&&je.id===g.id&&(je.content=Be,je.streaming=!1,d(je))}}):De=typeof oe=="string"?oe:(st=oe==null?void 0:oe.text)!=null?st:null}De!==null&&De.trim()!==""?g.content=De:ue.has(g.id)||(g.content=U(be));let Se=ne.get(g.id);if(Se){let oe=(Ut=Se.close)==null?void 0:Ut.call(Se);oe instanceof Promise&&oe.catch(()=>{}),ne.delete(g.id)}ue.delete(g.id),g.streaming=!1,d(g)}}}else if(ut==="step_complete"){let X=W.stepType,w=W.executionType;if(X==="tool"||w==="context")continue;let g=(Qt=W.result)==null?void 0:Qt.response,D=A();if(g!=null){let be=ne.get(D.id),xe=!1;if(be){let Ie=be.getExtractedText(),Ce=ue.get(D.id),De=Ce!=null?Ce:U(g);if(D.rawContent=De,Ie!==null&&Ie.trim()!=="")D.content=Ie,xe=!0;else{let Se=fn(De);if(Se!==null)D.content=Se,xe=!0;else{let oe=be.processChunk(De);if(oe instanceof Promise)oe.then(we=>{var $e;let Be=typeof we=="string"?we:($e=we==null?void 0:we.text)!=null?$e:null;if(Be!==null&&Be.trim()!==""){let je=E;je&&je.id===D.id&&(je.content=Be,je.streaming=!1,d(je))}else{let je=be.getExtractedText();if(je===null||je.trim()===""){let Ht=E;Ht&&Ht.id===D.id&&(ue.has(D.id)||(Ht.content=U(g)),Ht.streaming=!1,d(Ht))}}});else{let we=typeof oe=="string"?oe:(en=oe==null?void 0:oe.text)!=null?en:null;if(we!==null&&we.trim()!=="")D.content=we,xe=!0;else{let Be=be.getExtractedText();Be!==null&&Be.trim()!==""&&(D.content=Be,xe=!0)}}}}}if(!D.rawContent){let Ie=ue.get(D.id);D.rawContent=Ie!=null?Ie:U(g)}if(!xe&&!ue.has(D.id)&&(D.content=U(g)),be){let Ie=(tn=be.close)==null?void 0:tn.call(be);Ie instanceof Promise&&Ie.catch(()=>{})}ne.delete(D.id),ue.delete(D.id),D.streaming=!1,d(D)}else ne.delete(D.id),ue.delete(D.id),D.streaming=!1,d(D)}else if(ut==="flow_complete"){let X=(Ve=W.result)==null?void 0:Ve.response;if(X!=null){let w=A(),g=ue.get(w.id),D=g!=null?g:U(X);w.rawContent=D;let be=U(X),xe=ne.get(w.id);if(xe){let Ie=fn(D);if(Ie!==null)be=Ie;else{let Ce=xe.processChunk(D);Ce instanceof Promise&&Ce.then(Se=>{var we;let oe=typeof Se=="string"?Se:(we=Se==null?void 0:Se.text)!=null?we:null;if(oe!==null){let Be=E;Be&&Be.id===w.id&&(Be.content=oe,Be.streaming=!1,d(Be))}});let De=xe.getExtractedText();De!==null&&(be=De)}}ne.delete(w.id),ue.delete(w.id),be!==w.content&&(w.content=be,d(w)),w.streaming=!1,d(w)}else if(E!==null){let w=E;ne.delete(w.id),ue.delete(w.id),w.streaming=!1,d(w)}o({type:"status",status:"idle"})}else ut==="error"&&W.error&&o({type:"error",error:W.error instanceof Error?W.error:new Error(String(W.error))})}}}};var Yt=class{constructor(e={},o){this.config=e;this.callbacks=o;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.handleEvent=e=>{var o,t;e.type==="message"?this.upsertMessage(e.message):e.type==="status"?(this.setStatus(e.status),e.status==="connecting"?this.setStreaming(!0):(e.status==="idle"||e.status==="error")&&(this.setStreaming(!1),this.abortController=null)):e.type==="error"&&(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(t=(o=this.callbacks).onError)==null||t.call(o,e.error))};var t;this.messages=[...(t=e.initialMessages)!=null?t:[]].map(r=>{var s;return{...r,sequence:(s=r.sequence)!=null?s:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new _t(e),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}updateConfig(e){this.config={...this.config,...e},this.client=new _t(this.config)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}async sendMessage(e,o){var l,u,h,d,E;let t=e.trim();if(!t)return;(l=this.abortController)==null||l.abort();let r={id:`user-${Date.now()}`,role:"user",content:t,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(o==null?void 0:o.viaVoice)||!1};this.appendMessage(r),this.setStreaming(!0);let s=new AbortController;this.abortController=s;let i=[...this.messages];try{await this.client.dispatch({messages:i,signal:s.signal},this.handleEvent)}catch(f){let C={id:`assistant-${Date.now()}`,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(C),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,f instanceof Error?(h=(u=this.callbacks).onError)==null||h.call(u,f):(E=(d=this.callbacks).onError)==null||E.call(d,new Error(String(f)))}}cancel(){var e;(e=this.abortController)==null||e.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var e;(e=this.abortController)==null||e.abort(),this.abortController=null,this.messages=[],this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateMessages(e){var o;(o=this.abortController)==null||o.abort(),this.abortController=null,this.messages=this.sortMessages(e.map(t=>{var r;return{...t,streaming:!1,sequence:(r=t.sequence)!=null?r:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}setStreaming(e){this.streaming!==e&&(this.streaming=e,this.callbacks.onStreamingChanged(e))}appendMessage(e){let o=this.ensureSequence(e);this.messages=this.sortMessages([...this.messages,o]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let o=this.ensureSequence(e),t=this.messages.findIndex(r=>r.id===o.id);if(t===-1){this.appendMessage(o);return}this.messages=this.messages.map((r,s)=>s===t?{...r,...o}:r),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(e){return e.sequence!==void 0?{...e}:{...e,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(e){return[...e].sort((o,t)=>{var u,h;let r=new Date(o.createdAt).getTime(),s=new Date(t.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(s)&&r!==s)return r-s;let i=(u=o.sequence)!=null?u:0,l=(h=t.sequence)!=null?h:0;return i!==l?i-l:o.id.localeCompare(t.id)})}};var $n=(n,e)=>{var t;let o=(t=e==null?void 0:e.theme)!=null?t:{};Object.entries(o).forEach(([r,s])=>{if(s==null||s==="")return;let i=r.replace(/[A-Z]/g,l=>`-${l.toLowerCase()}`);n.style.setProperty(`--cw-${i}`,String(s))})};var Uo=$o(require("lucide"),1),ge=(n,e=24,o="currentColor",t=2)=>{try{let r=n.split("-").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(""),s=Uo[r];return s?zo(s,e,o,t):(console.warn(`Lucide icon "${n}" not found (tried "${r}"). Available icons: https://lucide.dev/icons`),null)}catch(r){return console.warn(`Failed to render Lucide icon "${n}":`,r),null}};function zo(n,e,o,t){if(!n||!Array.isArray(n))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(e)),r.setAttribute("height",String(e)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",o),r.setAttribute("stroke-width",String(t)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),n.forEach(s=>{if(Array.isArray(s)&&s.length>=2){let i=s[0],l=s[1];if(l){let u=document.createElementNS("http://www.w3.org/2000/svg",i);Object.entries(l).forEach(([h,d])=>{h!=="stroke"&&u.setAttribute(h,String(d))}),r.appendChild(u)}}}),r}var c=(n,e)=>{let o=document.createElement(n);return e&&(o.className=e),o};var Ye={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var $t={"bottom-right":"tvw-bottom-6 tvw-right-6","bottom-left":"tvw-bottom-6 tvw-left-6","top-right":"tvw-top-6 tvw-right-6","top-left":"tvw-top-6 tvw-left-6"};var on=(n,e)=>{let o=c("button");o.type="button",o.innerHTML=`
|
|
6
|
+
`);s=(se=ne.pop())!=null?se:"";for(let fe of ne){let Re=fe.split(`
|
|
7
|
+
`),Ie="message",ce="";for(let Z of Re)Z.startsWith("event:")?Ie=Z.replace("event:","").trim():Z.startsWith("data:")&&(ce+=Z.replace("data:","").trim());if(!ce)continue;let L;try{L=JSON.parse(ce)}catch(Z){o({type:"error",error:Z instanceof Error?Z:new Error("Failed to parse chat stream payload")});continue}let st=Ie!=="message"?Ie:(P=L.type)!=null?P:"message";if(this.parseSSEEvent){f.current=T;let Z=await this.handleCustomSSEEvent(L,o,f,d,u);if(f.current&&!T&&(T=f.current),Z)continue}if(st==="reason_start"){let Z=(_e=I(L,!0))!=null?_e:`reason-${u()}`,x=V(Z);x.reasoning=(Ye=x.reasoning)!=null?Ye:{id:Z,status:"streaming",chunks:[]},x.reasoning.startedAt=(vt=x.reasoning.startedAt)!=null?vt:J((Qe=L.startedAt)!=null?Qe:L.timestamp),x.reasoning.completedAt=void 0,x.reasoning.durationMs=void 0,x.streaming=!0,x.reasoning.status="streaming",d(x)}else if(st==="reason_chunk"){let Z=(D=(bt=I(L,!1))!=null?bt:I(L,!0))!=null?D:`reason-${u()}`,x=V(Z);x.reasoning=(he=x.reasoning)!=null?he:{id:Z,status:"streaming",chunks:[]},x.reasoning.startedAt=(mt=x.reasoning.startedAt)!=null?mt:J((ht=L.startedAt)!=null?ht:L.timestamp);let g=(M=(rt=(Je=L.reasoningText)!=null?Je:L.text)!=null?rt:L.delta)!=null?M:"";if(g&&L.hidden!==!0&&x.reasoning.chunks.push(String(g)),x.reasoning.status=L.done?"complete":"streaming",L.done){x.reasoning.completedAt=J((Me=L.completedAt)!=null?Me:L.timestamp);let B=(it=x.reasoning.startedAt)!=null?it:Date.now();x.reasoning.durationMs=Math.max(0,((at=x.reasoning.completedAt)!=null?at:Date.now())-B)}x.streaming=x.reasoning.status!=="complete",d(x)}else if(st==="reason_complete"){let Z=(ft=(Tt=I(L,!1))!=null?Tt:I(L,!0))!=null?ft:`reason-${u()}`,x=b.get(Z);if(x!=null&&x.reasoning){x.reasoning.status="complete",x.reasoning.completedAt=J((ke=L.completedAt)!=null?ke:L.timestamp);let B=(et=x.reasoning.startedAt)!=null?et:Date.now();x.reasoning.durationMs=Math.max(0,((qe=x.reasoning.completedAt)!=null?qe:Date.now())-B),x.streaming=!1,d(x)}let g=C(L);g&&_.byStep.delete(g)}else if(st==="tool_start"){let Z=(F=A(L,!0))!=null?F:`tool-${u()}`,x=ie(Z),g=(lt=x.toolCall)!=null?lt:{id:Z,status:"pending"};g.name=(Ke=L.toolName)!=null?Ke:g.name,g.status="running",L.args!==void 0&&(g.args=L.args),g.startedAt=(je=g.startedAt)!=null?je:J((We=L.startedAt)!=null?We:L.timestamp),g.completedAt=void 0,g.durationMs=void 0,x.toolCall=g,x.streaming=!0,d(x)}else if(st==="tool_chunk"){let Z=(Se=(K=A(L,!1))!=null?K:A(L,!0))!=null?Se:`tool-${u()}`,x=ie(Z),g=(Le=x.toolCall)!=null?Le:{id:Z,status:"running"};g.startedAt=(tt=g.startedAt)!=null?tt:J((Ue=L.startedAt)!=null?Ue:L.timestamp);let B=(pt=(Lt=(xt=L.text)!=null?xt:L.delta)!=null?Lt:L.message)!=null?pt:"";B&&(g.chunks=(Ct=g.chunks)!=null?Ct:[],g.chunks.push(String(B))),g.status="running",x.toolCall=g,x.streaming=!0,d(x)}else if(st==="tool_complete"){let Z=(Ot=(de=A(L,!1))!=null?de:A(L,!0))!=null?Ot:`tool-${u()}`,x=ie(Z),g=(Bt=x.toolCall)!=null?Bt:{id:Z,status:"running"};if(g.status="complete",L.result!==void 0&&(g.result=L.result),typeof L.duration=="number"&&(g.duration=L.duration),g.completedAt=J((ve=L.completedAt)!=null?ve:L.timestamp),typeof L.duration=="number")g.durationMs=L.duration;else{let we=(wt=g.startedAt)!=null?wt:Date.now();g.durationMs=Math.max(0,((St=g.completedAt)!=null?St:Date.now())-we)}x.toolCall=g,x.streaming=!1,d(x);let B=$(L);B&&j.byCall.delete(B)}else if(st==="step_chunk"){let Z=L.stepType,x=L.executionType;if(Z==="tool"||x==="context")continue;let g=S(),B=(cn=(Et=(yt=(Ht=L.text)!=null?Ht:L.delta)!=null?yt:L.content)!=null?Et:L.chunk)!=null?cn:"";if(B){let Ae=((un=le.get(g.id))!=null?un:"")+B;g.rawContent=Ae,G.has(g.id)||G.set(g.id,this.createStreamParser());let Xe=G.get(g.id),Be=Ae.trim().startsWith("{")||Ae.trim().startsWith("[");if(Be&&le.set(g.id,Ae),Xe.__isPlainTextParser===!0){g.content+=B,le.delete(g.id),G.delete(g.id),g.rawContent=void 0,d(g);continue}let De=Xe.processChunk(Ae);if(De instanceof Promise)De.then(ae=>{var He;let ue=typeof ae=="string"?ae:(He=ae==null?void 0:ae.text)!=null?He:null;if(ue!==null&&ue.trim()!==""){let pe=T;pe&&pe.id===g.id&&(pe.content=ue,d(pe))}else if(!Be&&!Ae.trim().startsWith("<")){let pe=T;pe&&pe.id===g.id&&(pe.content+=B,le.delete(pe.id),G.delete(pe.id),pe.rawContent=void 0,d(pe))}}).catch(()=>{g.content+=B,le.delete(g.id),G.delete(g.id),g.rawContent=void 0,d(g)});else{let ae=typeof De=="string"?De:(pn=De==null?void 0:De.text)!=null?pn:null;ae!==null&&ae.trim()!==""?(g.content=ae,d(g)):!Be&&!Ae.trim().startsWith("<")&&(g.content+=B,le.delete(g.id),G.delete(g.id),g.rawContent=void 0,d(g))}}if(L.isComplete){let we=(Nt=(kn=L.result)==null?void 0:kn.response)!=null?Nt:g.content;if(we){let Ae=le.get(g.id),Xe=Ae!=null?Ae:z(we);g.rawContent=Xe;let Be=G.get(g.id),be=null,De=!1;if(Be&&(be=Be.getExtractedText(),be===null&&(be=wn(Xe)),be===null)){let ae=Be.processChunk(Xe);ae instanceof Promise?(De=!0,ae.then(ue=>{var pe;let He=typeof ue=="string"?ue:(pe=ue==null?void 0:ue.text)!=null?pe:null;if(He!==null){let Oe=T;Oe&&Oe.id===g.id&&(Oe.content=He,Oe.streaming=!1,G.delete(Oe.id),le.delete(Oe.id),d(Oe))}})):be=typeof ae=="string"?ae:(Dt=ae==null?void 0:ae.text)!=null?Dt:null}if(!De){be!==null&&be.trim()!==""?g.content=be:le.has(g.id)||(g.content=z(we));let ae=G.get(g.id);if(ae){let ue=(nt=ae.close)==null?void 0:nt.call(ae);ue instanceof Promise&&ue.catch(()=>{}),G.delete(g.id)}le.delete(g.id),g.streaming=!1,d(g)}}}}else if(st==="step_complete"){let Z=L.stepType,x=L.executionType;if(Z==="tool"||x==="context")continue;let g=(Ut=L.result)==null?void 0:Ut.response,B=S();if(g!=null){let we=G.get(B.id),Ae=!1,Xe=!1;if(we){let Be=we.getExtractedText(),be=le.get(B.id),De=be!=null?be:z(g);if(B.rawContent=De,Be!==null&&Be.trim()!=="")B.content=Be,Ae=!0;else{let ae=wn(De);if(ae!==null)B.content=ae,Ae=!0;else{let ue=we.processChunk(De);if(ue instanceof Promise)Xe=!0,ue.then(He=>{var Oe;let pe=typeof He=="string"?He:(Oe=He==null?void 0:He.text)!=null?Oe:null;if(pe!==null&&pe.trim()!==""){let ot=T;ot&&ot.id===B.id&&(ot.content=pe,ot.streaming=!1,G.delete(ot.id),le.delete(ot.id),d(ot))}else{let ot=we.getExtractedText(),gt=T;gt&>.id===B.id&&(ot!==null&&ot.trim()!==""?gt.content=ot:le.has(gt.id)||(gt.content=z(g)),gt.streaming=!1,G.delete(gt.id),le.delete(gt.id),d(gt))}});else{let He=typeof ue=="string"?ue:(Qt=ue==null?void 0:ue.text)!=null?Qt:null;if(He!==null&&He.trim()!=="")B.content=He,Ae=!0;else{let pe=we.getExtractedText();pe!==null&&pe.trim()!==""&&(B.content=pe,Ae=!0)}}}}}if(!Xe){if(!B.rawContent){let Be=le.get(B.id);B.rawContent=Be!=null?Be:z(g)}if(!Ae&&!le.has(B.id)&&(B.content=z(g)),we){let Be=(en=we.close)==null?void 0:en.call(we);Be instanceof Promise&&Be.catch(()=>{})}G.delete(B.id),le.delete(B.id),B.streaming=!1,d(B)}}else G.delete(B.id),le.delete(B.id),B.streaming=!1,d(B)}else if(st==="flow_complete"){let Z=(tn=L.result)==null?void 0:tn.response;if(Z!=null){let x=S(),g=le.get(x.id),B=g!=null?g:z(Z);x.rawContent=B;let we=z(Z),Ae=G.get(x.id);if(Ae){let be=wn(B);if(be!==null)we=be;else{let De=Ae.processChunk(B);De instanceof Promise&&De.then(ue=>{var pe;let He=typeof ue=="string"?ue:(pe=ue==null?void 0:ue.text)!=null?pe:null;if(He!==null){let Oe=T;Oe&&Oe.id===x.id&&(Oe.content=He,Oe.streaming=!1,d(Oe))}});let ae=Ae.getExtractedText();ae!==null&&(we=ae)}}G.delete(x.id),le.delete(x.id);let Xe=we!==x.content,Be=x.streaming!==!1;Xe&&(x.content=we),x.streaming=!1,(Xe||Be)&&d(x)}else if(T!==null){let x=T;G.delete(x.id),le.delete(x.id),x.streaming!==!1&&(x.streaming=!1,d(x))}o({type:"status",status:"idle"})}else st==="error"&&L.error&&o({type:"error",error:L.error instanceof Error?L.error:new Error(String(L.error))})}}}};var Yt=class{constructor(e={},o){this.config=e;this.callbacks=o;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.handleEvent=e=>{var o,t;e.type==="message"?this.upsertMessage(e.message):e.type==="status"?(this.setStatus(e.status),e.status==="connecting"?this.setStreaming(!0):(e.status==="idle"||e.status==="error")&&(this.setStreaming(!1),this.abortController=null)):e.type==="error"&&(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(t=(o=this.callbacks).onError)==null||t.call(o,e.error))};var t;this.messages=[...(t=e.initialMessages)!=null?t:[]].map(r=>{var s;return{...r,sequence:(s=r.sequence)!=null?s:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new _t(e),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}updateConfig(e){this.config={...this.config,...e},this.client=new _t(this.config)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}async sendMessage(e,o){var l,u,h,d,T;let t=e.trim();if(!t)return;(l=this.abortController)==null||l.abort();let r={id:`user-${Date.now()}`,role:"user",content:t,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(o==null?void 0:o.viaVoice)||!1};this.appendMessage(r),this.setStreaming(!0);let s=new AbortController;this.abortController=s;let i=[...this.messages];try{await this.client.dispatch({messages:i,signal:s.signal},this.handleEvent)}catch(f){let b={id:`assistant-${Date.now()}`,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(b),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,f instanceof Error?(h=(u=this.callbacks).onError)==null||h.call(u,f):(T=(d=this.callbacks).onError)==null||T.call(d,new Error(String(f)))}}cancel(){var e;(e=this.abortController)==null||e.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var e;(e=this.abortController)==null||e.abort(),this.abortController=null,this.messages=[],this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateMessages(e){var o;(o=this.abortController)==null||o.abort(),this.abortController=null,this.messages=this.sortMessages(e.map(t=>{var r;return{...t,streaming:!1,sequence:(r=t.sequence)!=null?r:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}setStreaming(e){this.streaming!==e&&(this.streaming=e,this.callbacks.onStreamingChanged(e))}appendMessage(e){let o=this.ensureSequence(e);this.messages=this.sortMessages([...this.messages,o]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let o=this.ensureSequence(e),t=this.messages.findIndex(r=>r.id===o.id);if(t===-1){this.appendMessage(o);return}this.messages=this.messages.map((r,s)=>s===t?{...r,...o}:r),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(e){return e.sequence!==void 0?{...e}:{...e,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(e){return[...e].sort((o,t)=>{var u,h;let r=new Date(o.createdAt).getTime(),s=new Date(t.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(s)&&r!==s)return r-s;let i=(u=o.sequence)!=null?u:0,l=(h=t.sequence)!=null?h:0;return i!==l?i-l:o.id.localeCompare(t.id)})}};var On=(n,e)=>{var t;let o=(t=e==null?void 0:e.theme)!=null?t:{};Object.entries(o).forEach(([r,s])=>{if(s==null||s==="")return;let i=r.replace(/[A-Z]/g,l=>`-${l.toLowerCase()}`);n.style.setProperty(`--cw-${i}`,String(s))})};var Yo=Oo(require("lucide"),1),ye=(n,e=24,o="currentColor",t=2)=>{try{let r=n.split("-").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(""),s=Yo[r];return s?Jo(s,e,o,t):(console.warn(`Lucide icon "${n}" not found (tried "${r}"). Available icons: https://lucide.dev/icons`),null)}catch(r){return console.warn(`Failed to render Lucide icon "${n}":`,r),null}};function Jo(n,e,o,t){if(!n||!Array.isArray(n))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(e)),r.setAttribute("height",String(e)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",o),r.setAttribute("stroke-width",String(t)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),n.forEach(s=>{if(Array.isArray(s)&&s.length>=2){let i=s[0],l=s[1];if(l){let u=document.createElementNS("http://www.w3.org/2000/svg",i);Object.entries(l).forEach(([h,d])=>{h!=="stroke"&&u.setAttribute(h,String(d))}),r.appendChild(u)}}}),r}var c=(n,e)=>{let o=document.createElement(n);return e&&(o.className=e),o};var ze={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var $t={"bottom-right":"tvw-bottom-6 tvw-right-6","bottom-left":"tvw-bottom-6 tvw-left-6","top-right":"tvw-top-6 tvw-right-6","top-left":"tvw-top-6 tvw-left-6"};var on=(n,e)=>{let o=c("button");o.type="button",o.innerHTML=`
|
|
7
8
|
<span class="tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-bg-cw-primary tvw-text-white" data-role="launcher-icon">\u{1F4AC}</span>
|
|
8
9
|
<img data-role="launcher-image" class="tvw-rounded-full tvw-object-cover" alt="" style="display:none" />
|
|
9
10
|
<span class="tvw-flex tvw-flex-col tvw-items-start tvw-text-left">
|
|
@@ -11,8 +12,8 @@
|
|
|
11
12
|
<span class="tvw-text-xs tvw-text-cw-muted" data-role="launcher-subtitle"></span>
|
|
12
13
|
</span>
|
|
13
14
|
<span class="tvw-ml-2 tvw-grid tvw-place-items-center tvw-rounded-full tvw-bg-cw-primary tvw-text-cw-call-to-action" data-role="launcher-call-to-action-icon">\u2197</span>
|
|
14
|
-
`,o.addEventListener("click",e);let t=s=>{var j,F,m,S,I,A,z,R,V,te;let i=(j=s.launcher)!=null?j:{},l=o.querySelector("[data-role='launcher-title']");l&&(l.textContent=(F=i.title)!=null?F:"Chat Assistant");let u=o.querySelector("[data-role='launcher-subtitle']");u&&(u.textContent=(m=i.subtitle)!=null?m:"Get answers fast");let h=o.querySelector(".tvw-flex-col");h&&(i.textHidden?h.style.display="none":h.style.display="");let d=o.querySelector("[data-role='launcher-icon']");if(d)if(i.agentIconHidden)d.style.display="none";else{let T=(S=i.agentIconSize)!=null?S:"40px";if(d.style.height=T,d.style.width=T,d.innerHTML="",i.agentIconName){let re=parseFloat(T)||24,Y=ge(i.agentIconName,re*.6,"#ffffff",2);Y?(d.appendChild(Y),d.style.display=""):(d.textContent=(I=i.agentIconText)!=null?I:"\u{1F4AC}",d.style.display="")}else i.iconUrl?d.style.display="none":(d.textContent=(A=i.agentIconText)!=null?A:"\u{1F4AC}",d.style.display="")}let E=o.querySelector("[data-role='launcher-image']");if(E){let T=(z=i.agentIconSize)!=null?z:"40px";E.style.height=T,E.style.width=T,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(E.src=i.iconUrl,E.style.display="block"):E.style.display="none"}let f=o.querySelector("[data-role='launcher-call-to-action-icon']");if(f){let T=(R=i.callToActionIconSize)!=null?R:"32px";f.style.height=T,f.style.width=T,i.callToActionIconBackgroundColor?(f.style.backgroundColor=i.callToActionIconBackgroundColor,f.classList.remove("tvw-bg-cw-primary")):(f.style.backgroundColor="",f.classList.add("tvw-bg-cw-primary"));let re=0;if(i.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=i.callToActionIconPadding,re=(parseFloat(i.callToActionIconPadding)||0)*2):(f.style.boxSizing="",f.style.padding=""),i.callToActionIconHidden)f.style.display="none";else if(f.style.display="",f.innerHTML="",i.callToActionIconName){let Y=parseFloat(T)||24,U=Math.max(Y-re,8),ne=ge(i.callToActionIconName,U,"currentColor",2);ne?f.appendChild(ne):f.textContent=(V=i.callToActionIconText)!=null?V:"\u2197"}else f.textContent=(te=i.callToActionIconText)!=null?te:"\u2197"}let C=i.position&&$t[i.position]?$t[i.position]:$t["bottom-right"],y="tvw-fixed tvw-flex tvw-items-center tvw-gap-3 tvw-rounded-launcher tvw-bg-cw-surface tvw-py-2.5 tvw-pl-3 tvw-pr-3 tvw-shadow-lg tvw-border tvw-border-gray-200 tvw-transition hover:tvw-translate-y-[-2px] tvw-cursor-pointer tvw-z-50";o.className=`${y} ${C}`},r=()=>{o.removeEventListener("click",e),o.remove()};return n&&t(n),{element:o,update:t,destroy:r}};var Pt=n=>{var re,Y,U,ne,ue,se,$,qe,Je,et,wt,yt,O,de,pt,gt,Ke,rt,B,ke,it,at,St,ht,Pe,tt,Ue,N,lt,Xe,Ee,Fe;let{config:e,showClose:o=!0}=n,t=c("div","tvw-flex tvw-items-center tvw-gap-3 tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),r=(re=e==null?void 0:e.launcher)!=null?re:{},s=(Y=r.headerIconSize)!=null?Y:"48px",i=(U=r.closeButtonSize)!=null?U:"32px",l=(ne=r.closeButtonPlacement)!=null?ne:"inline",u=(ue=r.headerIconHidden)!=null?ue:!1,h=r.headerIconName,d=c("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-xl");if(d.style.height=s,d.style.width=s,!u)if(h){let J=parseFloat(s)||24,ye=ge(h,J*.6,"#ffffff",2);ye?d.replaceChildren(ye):d.textContent=($=(se=e==null?void 0:e.launcher)==null?void 0:se.agentIconText)!=null?$:"\u{1F4AC}"}else if((qe=e==null?void 0:e.launcher)!=null&&qe.iconUrl){let J=c("img");J.src=e.launcher.iconUrl,J.alt="",J.className="tvw-rounded-xl tvw-object-cover",J.style.height=s,J.style.width=s,d.replaceChildren(J)}else d.textContent=(et=(Je=e==null?void 0:e.launcher)==null?void 0:Je.agentIconText)!=null?et:"\u{1F4AC}";let E=c("div","tvw-flex tvw-flex-col"),f=c("span","tvw-text-base tvw-font-semibold");f.textContent=(yt=(wt=e==null?void 0:e.launcher)==null?void 0:wt.title)!=null?yt:"Chat Assistant";let C=c("span","tvw-text-xs tvw-text-cw-muted");C.textContent=(de=(O=e==null?void 0:e.launcher)==null?void 0:O.subtitle)!=null?de:"Here to help you get answers fast",E.append(f,C),u?t.append(E):t.append(d,E);let y=(pt=r.clearChat)!=null?pt:{},j=(gt=y.enabled)!=null?gt:!0,F=(Ke=y.placement)!=null?Ke:"inline",m=null,S=null;if(j){let J=(rt=y.size)!=null?rt:"32px",ye=(B=y.iconName)!=null?B:"refresh-cw",Re=(ke=y.iconColor)!=null?ke:"",ze=(it=y.backgroundColor)!=null?it:"",nt=(at=y.borderWidth)!=null?at:"",vt=(St=y.borderColor)!=null?St:"",Mt=(ht=y.borderRadius)!=null?ht:"",ct=(Pe=y.paddingX)!=null?Pe:"",bt=(tt=y.paddingY)!=null?tt:"",ie=(Ue=y.tooltipText)!=null?Ue:"Clear chat",Ot=(N=y.showTooltip)!=null?N:!0;S=c("div",F==="top-right"?"tvw-absolute tvw-top-4 tvw-z-50":"tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper"),F==="top-right"&&(S.style.right="48px"),m=c("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none"),m.style.height=J,m.style.width=J,m.type="button",m.setAttribute("aria-label",ie);let Lt=ge(ye,"20px",Re||"",2);if(Lt&&m.appendChild(Lt),Re&&(m.style.color=Re,m.classList.remove("tvw-text-cw-muted")),ze&&(m.style.backgroundColor=ze,m.classList.remove("hover:tvw-bg-gray-100")),nt||vt){let he=nt||"0px",mt=vt||"transparent";m.style.border=`${he} solid ${mt}`,m.classList.remove("tvw-border-none")}if(Mt&&(m.style.borderRadius=Mt,m.classList.remove("tvw-rounded-full")),ct?(m.style.paddingLeft=ct,m.style.paddingRight=ct):(m.style.paddingLeft="",m.style.paddingRight=""),bt?(m.style.paddingTop=bt,m.style.paddingBottom=bt):(m.style.paddingTop="",m.style.paddingBottom=""),S.appendChild(m),Ot&&ie&&m&&S){let he=null,mt=()=>{if(he||!m)return;he=c("div","tvw-clear-chat-tooltip"),he.textContent=ie;let Bt=c("div");Bt.className="tvw-clear-chat-tooltip-arrow",he.appendChild(Bt);let ft=m.getBoundingClientRect();he.style.position="fixed",he.style.left=`${ft.left+ft.width/2}px`,he.style.top=`${ft.top-8}px`,he.style.transform="translate(-50%, -100%)",document.body.appendChild(he)},xt=()=>{he&&he.parentNode&&(he.parentNode.removeChild(he),he=null)};S.addEventListener("mouseenter",mt),S.addEventListener("mouseleave",xt),m.addEventListener("focus",mt),m.addEventListener("blur",xt),S._cleanupTooltip=()=>{xt(),S&&(S.removeEventListener("mouseenter",mt),S.removeEventListener("mouseleave",xt)),m&&(m.removeEventListener("focus",mt),m.removeEventListener("blur",xt))}}F==="inline"&&t.appendChild(S)}let I=c("div",l==="top-right"?"tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50":j&&F==="inline"?"":"tvw-ml-auto"),A=c("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");A.style.height=i,A.style.width=i,A.type="button";let z=(lt=r.closeButtonTooltipText)!=null?lt:"Close chat",R=(Xe=r.closeButtonShowTooltip)!=null?Xe:!0;A.setAttribute("aria-label",z),A.style.display=o?"":"none";let V=(Ee=r.closeButtonIconName)!=null?Ee:"x",te=(Fe=r.closeButtonIconText)!=null?Fe:"\xD7",T=ge(V,"20px",r.closeButtonColor||"",2);if(T?A.appendChild(T):A.textContent=te,r.closeButtonColor?(A.style.color=r.closeButtonColor,A.classList.remove("tvw-text-cw-muted")):(A.style.color="",A.classList.add("tvw-text-cw-muted")),r.closeButtonBackgroundColor?(A.style.backgroundColor=r.closeButtonBackgroundColor,A.classList.remove("hover:tvw-bg-gray-100")):(A.style.backgroundColor="",A.classList.add("hover:tvw-bg-gray-100")),r.closeButtonBorderWidth||r.closeButtonBorderColor){let J=r.closeButtonBorderWidth||"0px",ye=r.closeButtonBorderColor||"transparent";A.style.border=`${J} solid ${ye}`,A.classList.remove("tvw-border-none")}else A.style.border="",A.classList.add("tvw-border-none");if(r.closeButtonBorderRadius?(A.style.borderRadius=r.closeButtonBorderRadius,A.classList.remove("tvw-rounded-full")):(A.style.borderRadius="",A.classList.add("tvw-rounded-full")),r.closeButtonPaddingX?(A.style.paddingLeft=r.closeButtonPaddingX,A.style.paddingRight=r.closeButtonPaddingX):(A.style.paddingLeft="",A.style.paddingRight=""),r.closeButtonPaddingY?(A.style.paddingTop=r.closeButtonPaddingY,A.style.paddingBottom=r.closeButtonPaddingY):(A.style.paddingTop="",A.style.paddingBottom=""),I.appendChild(A),R&&z){let J=null,ye=()=>{if(J)return;J=c("div","tvw-clear-chat-tooltip"),J.textContent=z;let ze=c("div");ze.className="tvw-clear-chat-tooltip-arrow",J.appendChild(ze);let nt=A.getBoundingClientRect();J.style.position="fixed",J.style.left=`${nt.left+nt.width/2}px`,J.style.top=`${nt.top-8}px`,J.style.transform="translate(-50%, -100%)",document.body.appendChild(J)},Re=()=>{J&&J.parentNode&&(J.parentNode.removeChild(J),J=null)};I.addEventListener("mouseenter",ye),I.addEventListener("mouseleave",Re),A.addEventListener("focus",ye),A.addEventListener("blur",Re),I._cleanupTooltip=()=>{Re(),I.removeEventListener("mouseenter",ye),I.removeEventListener("mouseleave",Re),A.removeEventListener("focus",ye),A.removeEventListener("blur",Re)}}return l!=="top-right"&&t.appendChild(I),{header:t,iconHolder:d,headerTitle:f,headerSubtitle:C,closeButton:A,closeButtonWrapper:I,clearChatButton:m,clearChatButtonWrapper:S}},Jt=(n,e,o)=>{var i,l,u,h;let t=(i=o==null?void 0:o.launcher)!=null?i:{},r=(l=t.closeButtonPlacement)!=null?l:"inline",s=(h=(u=t.clearChat)==null?void 0:u.placement)!=null?h:"inline";n.appendChild(e.header),r==="top-right"&&(n.style.position="relative",n.appendChild(e.closeButtonWrapper)),e.clearChatButtonWrapper&&s==="top-right"&&(n.style.position="relative",n.appendChild(e.clearChatButtonWrapper))};var Pn=n=>Pt({config:n.config,showClose:n.showClose,onClose:n.onClose,onClearChat:n.onClearChat}),On=n=>{var y,j,F,m;let{config:e,showClose:o=!0,onClose:t}=n,r=(y=e==null?void 0:e.launcher)!=null?y:{},s=c("div","tvw-flex tvw-items-center tvw-justify-between tvw-bg-cw-surface tvw-px-6 tvw-py-4 tvw-border-b-cw-divider"),i=c("span","tvw-text-base tvw-font-semibold");i.textContent=(j=r.title)!=null?j:"Chat Assistant",s.appendChild(i);let l=(F=r.closeButtonSize)!=null?F:"32px",u=c("div",""),h=c("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");h.style.height=l,h.style.width=l,h.type="button",h.setAttribute("aria-label","Close chat"),h.style.display=o?"":"none";let d=(m=r.closeButtonIconName)!=null?m:"x",E=ge(d,"20px",r.closeButtonColor||"",2);E?h.appendChild(E):h.textContent="\xD7",t&&h.addEventListener("click",t),u.appendChild(h),s.appendChild(u);let f=c("div");f.style.display="none";let C=c("span");return C.style.display="none",{header:s,iconHolder:f,headerTitle:i,headerSubtitle:C,closeButton:h,closeButtonWrapper:u,clearChatButton:null,clearChatButtonWrapper:null}},Nn=n=>{var A,z,R,V,te,T,re,Y;let{config:e,showClose:o=!0,onClose:t,onClearChat:r}=n,s=(A=e==null?void 0:e.launcher)!=null?A:{},i=c("div","tvw-flex tvw-flex-col tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),l=c("div","tvw-flex tvw-items-center tvw-gap-3"),u=(z=s.headerIconSize)!=null?z:"56px",h=c("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-2xl");h.style.height=u,h.style.width=u;let d=s.headerIconName;if(d){let U=parseFloat(u)||24,ne=ge(d,U*.5,"#ffffff",2);ne?h.replaceChildren(ne):h.textContent=(R=s.agentIconText)!=null?R:"\u{1F4AC}"}else if(s.iconUrl){let U=c("img");U.src=s.iconUrl,U.alt="",U.className="tvw-rounded-xl tvw-object-cover",U.style.height=u,U.style.width=u,h.replaceChildren(U)}else h.textContent=(V=s.agentIconText)!=null?V:"\u{1F4AC}";let E=c("div","tvw-flex tvw-flex-col tvw-flex-1"),f=c("span","tvw-text-lg tvw-font-semibold");f.textContent=(te=s.title)!=null?te:"Chat Assistant";let C=c("span","tvw-text-sm tvw-text-cw-muted");C.textContent=(T=s.subtitle)!=null?T:"Here to help you get answers fast",E.append(f,C),l.append(h,E);let y=(re=s.closeButtonSize)!=null?re:"32px",j=c("div",""),F=c("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");F.style.height=y,F.style.width=y,F.type="button",F.setAttribute("aria-label","Close chat"),F.style.display=o?"":"none";let m=(Y=s.closeButtonIconName)!=null?Y:"x",S=ge(m,"20px",s.closeButtonColor||"",2);S?F.appendChild(S):F.textContent="\xD7",t&&F.addEventListener("click",t),j.appendChild(F),l.appendChild(j),i.appendChild(l);let I=c("div","tvw-mt-3 tvw-pt-3 tvw-border-t tvw-border-gray-100 tvw-text-xs tvw-text-cw-muted");return I.textContent="Online and ready to help",i.appendChild(I),{header:i,iconHolder:h,headerTitle:f,headerSubtitle:C,closeButton:F,closeButtonWrapper:j,clearChatButton:null,clearChatButtonWrapper:null}},xn={default:Pn,minimal:On,expanded:Nn},Fn=n=>{var e;return(e=xn[n])!=null?e:xn.default},Cn=(n,e,o)=>{var i,l,u;if(e!=null&&e.render){let h=e.render({config:n,onClose:o==null?void 0:o.onClose,onClearChat:o==null?void 0:o.onClearChat}),d=c("div");d.style.display="none";let E=c("span"),f=c("span"),C=c("button");C.style.display="none";let y=c("div");return y.style.display="none",{header:h,iconHolder:d,headerTitle:E,headerSubtitle:f,closeButton:C,closeButtonWrapper:y,clearChatButton:null,clearChatButtonWrapper:null}}let t=(i=e==null?void 0:e.layout)!=null?i:"default",s=Fn(t)({config:n,showClose:(u=(l=e==null?void 0:e.showCloseButton)!=null?l:o==null?void 0:o.showClose)!=null?u:!0,onClose:o==null?void 0:o.onClose,onClearChat:o==null?void 0:o.onClearChat});return e&&(e.showIcon===!1&&(s.iconHolder.style.display="none"),e.showTitle===!1&&(s.headerTitle.style.display="none"),e.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),e.showCloseButton===!1&&(s.closeButton.style.display="none"),e.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var Yo=n=>{switch(n){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}},Kt=n=>{var se,$,qe,Je,et,wt,yt,O,de,pt,gt,Ke,rt,B,ke,it,at,St,ht,Pe,tt,Ue,N,lt,Xe;let{config:e}=n,o=c("div","tvw-border-t-cw-divider tvw-bg-cw-surface tvw-px-6 tvw-py-4"),t=c("div","tvw-mb-3 tvw-flex tvw-flex-wrap tvw-gap-2"),r=((se=e==null?void 0:e.voiceRecognition)==null?void 0:se.enabled)===!0,s=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),u=c("form",`tvw-flex tvw-items-end ${r&&s?"tvw-gap-1":"tvw-gap-3"} tvw-rounded-2xl tvw-border tvw-border-gray-200 tvw-bg-cw-input-background tvw-px-4 tvw-py-3`);u.style.outline="none";let h=c("textarea");h.placeholder=(qe=($=e==null?void 0:e.copy)==null?void 0:$.inputPlaceholder)!=null?qe:"Type your message\u2026",h.className="tvw-min-h-[48px] tvw-flex-1 tvw-resize-none tvw-border-none tvw-bg-transparent tvw-text-sm tvw-text-cw-primary focus:tvw-outline-none focus:tvw-border-none",h.rows=1;let d=(et=(Je=e==null?void 0:e.theme)==null?void 0:Je.inputFontFamily)!=null?et:"sans-serif",E=(yt=(wt=e==null?void 0:e.theme)==null?void 0:wt.inputFontWeight)!=null?yt:"400";h.style.fontFamily=Yo(d),h.style.fontWeight=E,h.style.border="none",h.style.outline="none",h.style.borderWidth="0",h.style.borderStyle="none",h.style.borderColor="transparent",h.addEventListener("focus",()=>{h.style.border="none",h.style.outline="none",h.style.borderWidth="0",h.style.borderStyle="none",h.style.borderColor="transparent",h.style.boxShadow="none"}),h.addEventListener("blur",()=>{h.style.border="none",h.style.outline="none"});let f=(O=e==null?void 0:e.sendButton)!=null?O:{},C=(de=f.useIcon)!=null?de:!1,y=(pt=f.iconText)!=null?pt:"\u2191",j=f.iconName,F=(gt=f.tooltipText)!=null?gt:"Send message",m=(Ke=f.showTooltip)!=null?Ke:!1,S=(rt=f.size)!=null?rt:"40px",I=f.backgroundColor,A=f.textColor,z=c("div","tvw-send-button-wrapper"),R=c("button",C?"tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer":"tvw-rounded-button tvw-bg-cw-accent tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold disabled:tvw-opacity-50 tvw-cursor-pointer");if(R.type="submit",C){if(R.style.width=S,R.style.height=S,R.style.minWidth=S,R.style.minHeight=S,R.style.fontSize="18px",R.style.lineHeight="1",R.innerHTML="",j){let Ee=parseFloat(S)||24,Fe=A&&typeof A=="string"&&A.trim()?A.trim():"currentColor",J=ge(j,Ee,Fe,2);J?(R.appendChild(J),R.style.color=Fe):(R.textContent=y,A?R.style.color=A:R.classList.add("tvw-text-white"))}else R.textContent=y,A?R.style.color=A:R.classList.add("tvw-text-white");I?R.style.backgroundColor=I:R.classList.add("tvw-bg-cw-primary")}else R.textContent=(ke=(B=e==null?void 0:e.copy)==null?void 0:B.sendButtonLabel)!=null?ke:"Send",A?R.style.color=A:R.classList.add("tvw-text-white");if(f.borderWidth&&(R.style.borderWidth=f.borderWidth,R.style.borderStyle="solid"),f.borderColor&&(R.style.borderColor=f.borderColor),f.paddingX?(R.style.paddingLeft=f.paddingX,R.style.paddingRight=f.paddingX):(R.style.paddingLeft="",R.style.paddingRight=""),f.paddingY?(R.style.paddingTop=f.paddingY,R.style.paddingBottom=f.paddingY):(R.style.paddingTop="",R.style.paddingBottom=""),m&&F){let Ee=c("div","tvw-send-button-tooltip");Ee.textContent=F,z.appendChild(Ee)}z.appendChild(R);let V=(it=e==null?void 0:e.voiceRecognition)!=null?it:{},te=V.enabled===!0,T=null,re=null,Y=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(te&&Y){re=c("div","tvw-send-button-wrapper"),T=c("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer"),T.type="button",T.setAttribute("aria-label","Start voice recognition");let Ee=(at=V.iconName)!=null?at:"mic",Fe=(St=V.iconSize)!=null?St:S,J=parseFloat(Fe)||24,ye=(ht=V.backgroundColor)!=null?ht:I,Re=(Pe=V.iconColor)!=null?Pe:A;T.style.width=Fe,T.style.height=Fe,T.style.minWidth=Fe,T.style.minHeight=Fe,T.style.fontSize="18px",T.style.lineHeight="1";let ze=Re||"currentColor",nt=ge(Ee,J,ze,1.5);nt?(T.appendChild(nt),T.style.color=ze):(T.textContent="\u{1F3A4}",T.style.color=ze),ye?T.style.backgroundColor=ye:T.classList.add("tvw-bg-cw-primary"),Re?T.style.color=Re:!Re&&!A&&T.classList.add("tvw-text-white"),V.borderWidth&&(T.style.borderWidth=V.borderWidth,T.style.borderStyle="solid"),V.borderColor&&(T.style.borderColor=V.borderColor),V.paddingX&&(T.style.paddingLeft=V.paddingX,T.style.paddingRight=V.paddingX),V.paddingY&&(T.style.paddingTop=V.paddingY,T.style.paddingBottom=V.paddingY),re.appendChild(T);let vt=(tt=V.tooltipText)!=null?tt:"Start voice recognition";if(((Ue=V.showTooltip)!=null?Ue:!1)&&vt){let ct=c("div","tvw-send-button-tooltip");ct.textContent=vt,re.appendChild(ct)}}u.addEventListener("click",Ee=>{Ee.target!==R&&Ee.target!==z&&Ee.target!==T&&Ee.target!==re&&h.focus()}),u.append(h),re&&u.append(re),u.append(z);let U=c("div","tvw-mt-2 tvw-text-right tvw-text-xs tvw-text-cw-muted"),ne=(N=e==null?void 0:e.statusIndicator)!=null?N:{},ue=(lt=ne.visible)!=null?lt:!0;return U.style.display=ue?"":"none",U.textContent=(Xe=ne.idleText)!=null?Xe:"Online",o.append(t,u,U),{footer:o,suggestions:t,composerForm:u,textarea:h,sendButton:R,sendButtonWrapper:z,micButton:T,micButtonWrapper:re,statusText:U}};var ho=n=>{var u,h,d,E,f;if(!((h=(u=n==null?void 0:n.launcher)==null?void 0:u.enabled)!=null?h:!0)){let C=c("div","tvw-relative tvw-w-full tvw-h-full tvw-flex tvw-flex-col tvw-flex-1 tvw-min-h-0"),y=c("div","tvw-relative tvw-w-full tvw-flex-1 tvw-flex tvw-flex-col tvw-min-h-0");return C.appendChild(y),{wrapper:C,panel:y}}let o=(d=n==null?void 0:n.launcher)!=null?d:{},t=o.position&&$t[o.position]?$t[o.position]:$t["bottom-right"],r=c("div",`tvw-fixed ${t} tvw-z-50 tvw-transition`),s=c("div","tvw-relative tvw-min-h-[320px]"),i=(f=(E=n==null?void 0:n.launcher)==null?void 0:E.width)!=null?f:n==null?void 0:n.launcherWidth,l=i!=null?i:"min(400px, calc(100vw - 24px))";return s.style.width=l,s.style.maxWidth=l,r.appendChild(s),{wrapper:r,panel:s}},mo=(n,e=!0)=>{var E,f,C,y,j;let o=c("div","tvw-flex tvw-h-full tvw-w-full tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-bg-cw-surface tvw-text-cw-primary tvw-rounded-2xl tvw-overflow-hidden tvw-shadow-2xl tvw-border tvw-border-cw-border"),t=(E=n==null?void 0:n.layout)==null?void 0:E.header,r=t?Cn(n,t,{showClose:e}):Pt({config:n,showClose:e}),s=c("div","tvw-flex tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-gap-6 tvw-overflow-y-auto tvw-bg-cw-container tvw-px-6 tvw-py-6");s.id="vanilla-agent-scroll-container";let i=c("div","tvw-rounded-2xl tvw-bg-cw-surface tvw-p-6 tvw-shadow-sm"),l=c("h2","tvw-text-lg tvw-font-semibold tvw-text-cw-primary");l.textContent=(C=(f=n==null?void 0:n.copy)==null?void 0:f.welcomeTitle)!=null?C:"Hello \u{1F44B}";let u=c("p","tvw-mt-2 tvw-text-sm tvw-text-cw-muted");u.textContent=(j=(y=n==null?void 0:n.copy)==null?void 0:y.welcomeSubtitle)!=null?j:"Ask anything about your account or products.",i.append(l,u);let h=c("div","tvw-flex tvw-flex-col tvw-gap-3");s.append(i,h);let d=Kt({config:n});return Jt(o,r,n),o.append(s,d.footer),{container:o,body:s,messagesWrapper:h,suggestions:d.suggestions,textarea:d.textarea,sendButton:d.sendButton,sendButtonWrapper:d.sendButtonWrapper,micButton:d.micButton,micButtonWrapper:d.micButtonWrapper,composerForm:d.composerForm,statusText:d.statusText,introTitle:l,introSubtitle:u,closeButton:r.closeButton,closeButtonWrapper:r.closeButtonWrapper,clearChatButton:r.clearChatButton,clearChatButtonWrapper:r.clearChatButtonWrapper,iconHolder:r.iconHolder,headerTitle:r.headerTitle,headerSubtitle:r.headerSubtitle,header:r.header,footer:d.footer}};var rn=()=>{let n=document.createElement("div");n.className="tvw-flex tvw-items-center tvw-space-x-1 tvw-h-5 tvw-mt-2";let e=document.createElement("div");e.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",e.style.animationDelay="0ms";let o=document.createElement("div");o.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",o.style.animationDelay="250ms";let t=document.createElement("div");t.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",t.style.animationDelay="500ms";let r=document.createElement("span");return r.className="tvw-sr-only",r.textContent="Loading",n.appendChild(e),n.appendChild(o),n.appendChild(t),n.appendChild(r),n},Jo=(n,e)=>{let o=c("div","tvw-flex-shrink-0 tvw-w-8 tvw-h-8 tvw-rounded-full tvw-flex tvw-items-center tvw-justify-center tvw-text-sm"),t=e==="user"?n.userAvatar:n.assistantAvatar;if(t)if(t.startsWith("http")||t.startsWith("/")||t.startsWith("data:")){let r=c("img");r.src=t,r.alt=e==="user"?"User":"Assistant",r.className="tvw-w-full tvw-h-full tvw-rounded-full tvw-object-cover",o.appendChild(r)}else o.textContent=t,o.classList.add(e==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");else o.textContent=e==="user"?"U":"A",o.classList.add(e==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");return o},fo=(n,e)=>{let o=c("div","tvw-text-xs tvw-text-cw-muted"),t=new Date(n.createdAt);return e.format?o.textContent=e.format(t):o.textContent=t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},Ko=(n,e="bubble")=>{let o=["vanilla-message-bubble","tvw-max-w-[85%]"];switch(e){case"flat":n==="user"?o.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-text-cw-primary","tvw-py-2"):o.push("vanilla-message-assistant-bubble","tvw-text-cw-primary","tvw-py-2");break;case"minimal":o.push("tvw-text-sm","tvw-leading-relaxed"),n==="user"?o.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-3","tvw-py-2","tvw-rounded-lg"):o.push("vanilla-message-assistant-bubble","tvw-bg-cw-surface","tvw-text-cw-primary","tvw-px-3","tvw-py-2","tvw-rounded-lg");break;case"bubble":default:o.push("tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm"),n==="user"?o.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-5","tvw-py-3"):o.push("vanilla-message-assistant-bubble","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3");break}return o},Xt=(n,e,o)=>{var F,m,S,I,A;let t=o!=null?o:{},r=(F=t.layout)!=null?F:"bubble",s=t.avatar,i=t.timestamp,l=(m=s==null?void 0:s.show)!=null?m:!1,u=(S=i==null?void 0:i.show)!=null?S:!1,h=(I=s==null?void 0:s.position)!=null?I:"left",d=(A=i==null?void 0:i.position)!=null?A:"below",E=Ko(n.role,r),f=c("div",E.join(" ")),C=document.createElement("div");if(C.innerHTML=e({text:n.content,message:n,streaming:!!n.streaming,raw:n.rawContent}),u&&d==="inline"&&n.createdAt){let z=fo(n,i);z.classList.add("tvw-ml-2","tvw-inline"),C.appendChild(z)}if(f.appendChild(C),u&&d==="below"&&n.createdAt){let z=fo(n,i);z.classList.add("tvw-mt-1"),f.appendChild(z)}if(n.streaming&&n.role==="assistant"&&(!n.content||!n.content.trim())){let z=rn();f.appendChild(z)}if(!l||n.role==="system")return f;let y=c("div",`tvw-flex tvw-gap-2 ${n.role==="user"?"tvw-flex-row-reverse":""}`),j=Jo(s,n.role);return h==="right"||h==="left"&&n.role==="user"?y.append(f,j):y.append(j,f),f.classList.remove("tvw-max-w-[85%]"),f.classList.add("tvw-max-w-[calc(85%-2.5rem)]"),y},wo=(n,e,o)=>{let t=o!=null?o:{};return n.role==="user"&&t.renderUserMessage?t.renderUserMessage({message:n,config:{},streaming:!!n.streaming}):n.role==="assistant"&&t.renderAssistantMessage?t.renderAssistantMessage({message:n,config:{},streaming:!!n.streaming}):Xt(n,e,o)};var Dn=new Set,jn=n=>{let e=n.reasoning,o=c("div",["vanilla-message-bubble","vanilla-reasoning-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(!e)return o;let t=Dn.has(n.id),r=c("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");r.type="button",r.setAttribute("aria-expanded",t?"true":"false");let s=c("div","tvw-flex tvw-flex-col tvw-text-left"),i=c("span","tvw-text-xs tvw-text-cw-primary");i.textContent="Thinking...",s.appendChild(i);let l=c("span","tvw-text-xs tvw-text-cw-primary");l.textContent=uo(e),s.appendChild(l),e.status==="complete"?i.style.display="none":i.style.display="";let u=c("div","tvw-flex tvw-items-center"),d=ge(t?"chevron-up":"chevron-down",16,"currentColor",2);d?u.appendChild(d):u.textContent=t?"Hide":"Show";let E=c("div","tvw-flex tvw-items-center tvw-ml-auto");E.append(u),r.append(s,E);let f=c("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-px-4 tvw-py-3");f.style.display=t?"":"none";let C=e.chunks.join(""),y=c("div","tvw-whitespace-pre-wrap tvw-text-xs tvw-leading-snug tvw-text-cw-muted");y.textContent=C||(e.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),f.appendChild(y);let j=()=>{r.setAttribute("aria-expanded",t?"true":"false"),u.innerHTML="";let S=ge(t?"chevron-up":"chevron-down",16,"currentColor",2);S?u.appendChild(S):u.textContent=t?"Hide":"Show",f.style.display=t?"":"none"},F=()=>{t=!t,t?Dn.add(n.id):Dn.delete(n.id),j()};return r.addEventListener("pointerdown",m=>{m.preventDefault(),F()}),r.addEventListener("keydown",m=>{(m.key==="Enter"||m.key===" ")&&(m.preventDefault(),F())}),j(),o.append(r,f),o};var _n=new Set,qn=(n,e)=>{var F;let o=n.toolCall,t=(F=e==null?void 0:e.toolCall)!=null?F:{},r=c("div",["vanilla-message-bubble","vanilla-tool-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(t.backgroundColor&&(r.style.backgroundColor=t.backgroundColor),t.borderColor&&(r.style.borderColor=t.borderColor),t.borderWidth&&(r.style.borderWidth=t.borderWidth),t.borderRadius&&(r.style.borderRadius=t.borderRadius),!o)return r;let s=_n.has(n.id),i=c("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");i.type="button",i.setAttribute("aria-expanded",s?"true":"false"),t.headerBackgroundColor&&(i.style.backgroundColor=t.headerBackgroundColor),t.headerPaddingX&&(i.style.paddingLeft=t.headerPaddingX,i.style.paddingRight=t.headerPaddingX),t.headerPaddingY&&(i.style.paddingTop=t.headerPaddingY,i.style.paddingBottom=t.headerPaddingY);let l=c("div","tvw-flex tvw-flex-col tvw-text-left"),u=c("span","tvw-text-xs tvw-text-cw-primary");t.headerTextColor&&(u.style.color=t.headerTextColor),u.textContent=po(o),l.appendChild(u);let h=c("div","tvw-flex tvw-items-center"),d=t.toggleTextColor||t.headerTextColor||"currentColor",E=ge(s?"chevron-up":"chevron-down",16,d,2);E?h.appendChild(E):h.textContent=s?"Hide":"Show";let f=c("div","tvw-flex tvw-items-center tvw-gap-2 tvw-ml-auto");f.append(h),i.append(l,f);let C=c("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-space-y-3 tvw-px-4 tvw-py-3");if(C.style.display=s?"":"none",t.contentBackgroundColor&&(C.style.backgroundColor=t.contentBackgroundColor),t.contentTextColor&&(C.style.color=t.contentTextColor),t.contentPaddingX&&(C.style.paddingLeft=t.contentPaddingX,C.style.paddingRight=t.contentPaddingX),t.contentPaddingY&&(C.style.paddingTop=t.contentPaddingY,C.style.paddingBottom=t.contentPaddingY),o.name){let m=c("div","tvw-text-xs tvw-text-cw-muted tvw-italic");t.contentTextColor?m.style.color=t.contentTextColor:t.headerTextColor&&(m.style.color=t.headerTextColor),m.textContent=o.name,C.appendChild(m)}if(o.args!==void 0){let m=c("div","tvw-space-y-1"),S=c("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(S.style.color=t.labelTextColor),S.textContent="Arguments";let I=c("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");I.style.fontSize="0.75rem",I.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(I.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(I.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(I.style.color=t.codeBlockTextColor),I.textContent=In(o.args),m.append(S,I),C.appendChild(m)}if(o.chunks&&o.chunks.length){let m=c("div","tvw-space-y-1"),S=c("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(S.style.color=t.labelTextColor),S.textContent="Activity";let I=c("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");I.style.fontSize="0.75rem",I.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(I.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(I.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(I.style.color=t.codeBlockTextColor),I.textContent=o.chunks.join(`
|
|
15
|
-
`),m.append(S,I),C.appendChild(m)}if(o.status==="complete"&&o.result!==void 0){let m=c("div","tvw-space-y-1"),S=c("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(S.style.color=t.labelTextColor),S.textContent="Result";let I=c("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");I.style.fontSize="0.75rem",I.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(I.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(I.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(I.style.color=t.codeBlockTextColor),I.textContent=In(o.result),m.append(S,I),C.appendChild(m)}if(o.status==="complete"&&typeof o.duration=="number"){let m=c("div","tvw-text-xs tvw-text-cw-muted");t.contentTextColor&&(m.style.color=t.contentTextColor),m.textContent=`Duration: ${o.duration}ms`,C.appendChild(m)}let y=()=>{i.setAttribute("aria-expanded",s?"true":"false"),h.innerHTML="";let m=t.toggleTextColor||t.headerTextColor||"currentColor",S=ge(s?"chevron-up":"chevron-down",16,m,2);S?h.appendChild(S):h.textContent=s?"Hide":"Show",C.style.display=s?"":"none"},j=()=>{s=!s,s?_n.add(n.id):_n.delete(n.id),y()};return i.addEventListener("pointerdown",m=>{m.preventDefault(),j()}),i.addEventListener("keydown",m=>{(m.key==="Enter"||m.key===" ")&&(m.preventDefault(),j())}),y(),r.append(i,C),r};var yo=n=>{let e=[];return{buttons:e,render:(t,r,s,i,l)=>{if(n.innerHTML="",e.length=0,!t||!t.length||(i!=null?i:r?r.getMessages():[]).some(C=>C.role==="user"))return;let d=document.createDocumentFragment(),E=r?r.isStreaming():!1,f=C=>{switch(C){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};t.forEach(C=>{let y=c("button","tvw-rounded-button tvw-bg-cw-surface tvw-px-3 tvw-py-1.5 tvw-text-xs tvw-font-medium tvw-text-cw-muted hover:tvw-opacity-90 tvw-cursor-pointer tvw-border tvw-border-gray-200");y.type="button",y.textContent=C,y.disabled=E,l!=null&&l.fontFamily&&(y.style.fontFamily=f(l.fontFamily)),l!=null&&l.fontWeight&&(y.style.fontWeight=l.fontWeight),l!=null&&l.paddingX&&(y.style.paddingLeft=l.paddingX,y.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(y.style.paddingTop=l.paddingY,y.style.paddingBottom=l.paddingY),y.addEventListener("click",()=>{!r||r.isStreaming()||(s.value="",r.sendMessage(C))}),d.appendChild(y),e.push(y)}),n.appendChild(d)}}};var vo={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},Un=(n,e,o,t)=>{let r=n.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{var y,j,F;if(s.dataset.enhanced==="true")return;let i=(y=s.dataset.tvForm)!=null?y:"init";s.dataset.enhanced="true";let l=(j=vo[i])!=null?j:vo.init;s.classList.add("tvw-form-card","tvw-space-y-4");let u=c("div","tvw-space-y-1"),h=c("h3","tvw-text-base tvw-font-semibold tvw-text-cw-primary");if(h.textContent=l.title,u.appendChild(h),l.description){let m=c("p","tvw-text-sm tvw-text-cw-muted");m.textContent=l.description,u.appendChild(m)}let d=document.createElement("form");d.className="tvw-form-grid tvw-space-y-3",l.fields.forEach(m=>{var R,V;let S=c("label","tvw-form-field tvw-flex tvw-flex-col tvw-gap-1");S.htmlFor=`${e.id}-${i}-${m.name}`;let I=c("span","tvw-text-xs tvw-font-medium tvw-text-cw-muted");I.textContent=m.label,S.appendChild(I);let A=(R=m.type)!=null?R:"text",z;A==="textarea"?(z=document.createElement("textarea"),z.rows=3):(z=document.createElement("input"),z.type=A),z.className="tvw-rounded-xl tvw-border tvw-border-gray-200 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-sm tvw-text-cw-primary focus:tvw-outline-none focus:tvw-border-cw-primary",z.id=`${e.id}-${i}-${m.name}`,z.name=m.name,z.placeholder=(V=m.placeholder)!=null?V:"",m.required&&(z.required=!0),S.appendChild(z),d.appendChild(S)});let E=c("div","tvw-flex tvw-items-center tvw-justify-between tvw-gap-2"),f=c("div","tvw-text-xs tvw-text-cw-muted tvw-min-h-[1.5rem]"),C=c("button","tvw-inline-flex tvw-items-center tvw-rounded-full tvw-bg-cw-primary tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold tvw-text-white disabled:tvw-opacity-60 tvw-cursor-pointer");C.type="submit",C.textContent=(F=l.submitLabel)!=null?F:"Submit",E.appendChild(f),E.appendChild(C),d.appendChild(E),s.replaceChildren(u,d),d.addEventListener("submit",async m=>{var z,R;m.preventDefault();let S=(z=o.formEndpoint)!=null?z:"/form",I=new FormData(d),A={};I.forEach((V,te)=>{A[te]=V}),A.type=i,C.disabled=!0,f.textContent="Submitting\u2026";try{let V=await fetch(S,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(A)});if(!V.ok)throw new Error(`Form submission failed (${V.status})`);let te=await V.json();f.textContent=(R=te.message)!=null?R:"Thanks! We'll be in touch soon.",te.success&&te.nextPrompt&&await t.sendMessage(String(te.nextPrompt))}catch(V){f.textContent=V instanceof Error?V.message:"Something went wrong. Please try again."}finally{C.disabled=!1}})})};var zn=class{constructor(){this.plugins=new Map}register(e){var o;this.plugins.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.plugins.set(e.id,e),(o=e.onRegister)==null||o.call(e)}unregister(e){var t;let o=this.plugins.get(e);o&&((t=o.onUnregister)==null||t.call(o),this.plugins.delete(e))}getAll(){return Array.from(this.plugins.values()).sort((e,o)=>{var t,r;return((t=o.priority)!=null?t:0)-((r=e.priority)!=null?r:0)})}getForInstance(e){let o=this.getAll();if(!e||e.length===0)return o;let t=new Set(e.map(s=>s.id));return[...o.filter(s=>!t.has(s.id)),...e].sort((s,i)=>{var l,u;return((l=i.priority)!=null?l:0)-((u=s.priority)!=null?u:0)})}clear(){this.plugins.forEach(e=>{var o;return(o=e.onUnregister)==null?void 0:o.call(e)}),this.plugins.clear()}},an=new zn;var Oe={apiUrl:"http://localhost:43111/api/chat/dispatch",theme:{primary:"#111827",accent:"#1d4ed8",surface:"#ffffff",muted:"#6b7280",container:"#f8fafc",border:"#f1f5f9",divider:"#f1f5f9",messageBorder:"#f1f5f9",inputBackground:"#ffffff",callToAction:"#000000",callToActionBackground:"#ffffff",sendButtonBackgroundColor:"#111827",sendButtonTextColor:"#ffffff",sendButtonBorderColor:"#60a5fa",closeButtonColor:"#6b7280",closeButtonBackgroundColor:"transparent",closeButtonBorderColor:"",clearChatIconColor:"#6b7280",clearChatBackgroundColor:"transparent",clearChatBorderColor:"transparent",micIconColor:"#111827",micBackgroundColor:"transparent",micBorderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",inputFontFamily:"sans-serif",inputFontWeight:"400",radiusSm:"0.75rem",radiusMd:"1rem",radiusLg:"1.5rem",launcherRadius:"9999px",buttonRadius:"9999px"},launcher:{enabled:!0,title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",position:"bottom-right",width:"min(400px, calc(100vw - 24px))",autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:"#000000",callToActionIconBackgroundColor:"#ffffff",closeButtonColor:"#6b7280",closeButtonBackgroundColor:"transparent",clearChat:{iconColor:"#6b7280",backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",backgroundColor:"#111827",textColor:"#ffffff",borderColor:"#60a5fa",useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:"#111827",backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},debug:!1};function Sn(n){var e,o,t,r,s,i,l,u,h,d,E,f,C,y,j,F,m;return n?{...Oe,...n,theme:{...Oe.theme,...n.theme},launcher:{...Oe.launcher,...n.launcher,clearChat:{...(e=Oe.launcher)==null?void 0:e.clearChat,...(o=n.launcher)==null?void 0:o.clearChat}},copy:{...Oe.copy,...n.copy},sendButton:{...Oe.sendButton,...n.sendButton},statusIndicator:{...Oe.statusIndicator,...n.statusIndicator},voiceRecognition:{...Oe.voiceRecognition,...n.voiceRecognition},features:{...Oe.features,...n.features},suggestionChips:(t=n.suggestionChips)!=null?t:Oe.suggestionChips,suggestionChipsConfig:{...Oe.suggestionChipsConfig,...n.suggestionChipsConfig},layout:{...Oe.layout,...n.layout,header:{...(r=Oe.layout)==null?void 0:r.header,...(s=n.layout)==null?void 0:s.header},messages:{...(i=Oe.layout)==null?void 0:i.messages,...(l=n.layout)==null?void 0:l.messages,avatar:{...(h=(u=Oe.layout)==null?void 0:u.messages)==null?void 0:h.avatar,...(E=(d=n.layout)==null?void 0:d.messages)==null?void 0:E.avatar},timestamp:{...(C=(f=Oe.layout)==null?void 0:f.messages)==null?void 0:C.timestamp,...(j=(y=n.layout)==null?void 0:y.messages)==null?void 0:j.timestamp}},slots:{...(F=Oe.layout)==null?void 0:F.slots,...(m=n.layout)==null?void 0:m.slots}}}:Oe}var bo=()=>{let n=new Map,e=(r,s)=>(n.has(r)||n.set(r,new Set),n.get(r).add(s),()=>o(r,s)),o=(r,s)=>{var i;(i=n.get(r))==null||i.delete(s)};return{on:e,off:o,emit:(r,s)=>{var i;(i=n.get(r))==null||i.forEach(l=>{try{l(s)}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",u)}})}}};var Xo=n=>{let e=n.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:n},Vo=n=>{let e=n.trim(),o=e.indexOf("{");if(o===-1)return null;let t=0;for(let r=o;r<e.length;r+=1){let s=e[r];if(s==="{"&&(t+=1),s==="}"&&(t-=1,t===0))return e.slice(o,r+1)}return null},ln=({text:n})=>{if(!n||!n.includes("{"))return null;try{let e=Xo(n),o=Vo(e);if(!o)return null;let t=JSON.parse(o);if(!t||typeof t!="object"||!t.action)return null;let{action:r,...s}=t;return{type:String(r),payload:s,raw:t}}catch{return null}},Yn=n=>typeof n=="string"?n:n==null?"":String(n),qt={message:n=>n.type!=="message"?void 0:{handled:!0,displayText:Yn(n.payload.text)},messageAndClick:(n,e)=>{var r;if(n.type!=="message_and_click")return;let o=n.payload,t=Yn(o.element);if(t&&((r=e.document)!=null&&r.querySelector)){let s=e.document.querySelector(t);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",t)}return{handled:!0,displayText:Yn(o.text)}}},xo=n=>Array.isArray(n)?n.map(e=>String(e)):[],dn=n=>{let e=new Set(xo(n.getMetadata().processedActionMessageIds)),o=()=>{e=new Set(xo(n.getMetadata().processedActionMessageIds))},t=()=>{let s=Array.from(e);n.updateMetadata(i=>({...i,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||e.has(s.message.id))return null;let i=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!i&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let l=i?n.parsers.reduce((h,d)=>h||(d==null?void 0:d({text:i,message:s.message}))||null,null):null;if(!l)return null;e.add(s.message.id),t();let u={action:l,message:s.message};n.emit("action:detected",u);for(let h of n.handlers)if(h)try{let d=h(l,{message:s.message,metadata:n.getMetadata(),updateMetadata:n.updateMetadata,document:n.documentRef});if(!d)continue;if(d.handled){let E=d.persistMessage!==!1;return{text:d.displayText!==void 0?d.displayText:"",persist:E}}}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",d)}return{text:"",persist:!0}},syncFromMetadata:o}};var Go=n=>{if(!n)return null;try{return JSON.parse(n)}catch(e){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",e),null}},Zo=n=>n.map(e=>({...e,streaming:!1})),An=(n="vanilla-agent-state")=>{let e=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let o=e();return o?Go(o.getItem(n)):null},save:o=>{let t=e();if(t)try{let r={...o,messages:o.messages?Zo(o.messages):void 0};t.setItem(n,JSON.stringify(r))}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let o=e();if(o)try{o.removeItem(n)}catch(t){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",t)}}}};var Jn=class{constructor(){this.components=new Map}register(e,o){this.components.has(e)&&console.warn(`[ComponentRegistry] Component "${e}" is already registered. Overwriting.`),this.components.set(e,o)}unregister(e){this.components.delete(e)}get(e){return this.components.get(e)}has(e){return this.components.has(e)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(e){Object.entries(e).forEach(([o,t])=>{this.register(o,t)})}},Vt=new Jn;var Gt=require("partial-json");function Qo(n){if(!n||typeof n!="object"||!("component"in n))return!1;let e=n.component;return typeof e=="string"&&e.length>0}function er(n,e){if(!Qo(n))return null;let o=n.props&&typeof n.props=="object"&&n.props!==null?n.props:{};return{component:n.component,props:o,raw:e}}function Tn(){let n=null,e=0;return{getExtractedDirective:()=>n,processChunk:o=>{let t=o.trim();if(!t.startsWith("{")&&!t.startsWith("["))return null;if(o.length<=e)return n;try{let r=(0,Gt.parse)(o,Gt.STR|Gt.OBJ),s=er(r,o);s&&(n=s)}catch{}return e=o.length,n},reset:()=>{n=null,e=0}}}function Co(n){return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"&&"props"in n&&typeof n.props=="object"}function En(n,e){let{config:o,message:t,onPropsUpdate:r}=e,s=Vt.get(n.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${n.component}" not found in registry. Falling back to default rendering.`),null;let i={message:t,config:o,updateProps:l=>{r&&r(l)}};try{return s(n.props,i)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${n.component}":`,l),null}}function So(){let n=Tn();return{processChunk:e=>n.processChunk(e),getDirective:()=>n.getExtractedDirective(),reset:()=>{n.reset()}}}function Wn(n){if(!n.rawContent)return!1;try{let e=JSON.parse(n.rawContent);return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"}catch{return!1}}function Mn(n){if(!n.rawContent)return null;try{let e=JSON.parse(n.rawContent);if(typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string")return{component:e.component,props:e.props&&typeof e.props=="object"&&e.props!==null?e.props:{},raw:n.rawContent}}catch{}return null}var Zt="vanilla-agent-chat-history",tr=30*1e3,Kn=n=>!n||typeof n!="object"?{}:{...n},Ao=n=>n.map(e=>({...e,streaming:!1})),To=(n,e)=>o=>{var s,i,l;let t=(s=o.text)!=null?s:"",r=(i=o.message.rawContent)!=null?i:null;if(e){let u=e.process({text:t,raw:r!=null?r:t,message:o.message,streaming:o.streaming});u!==null&&(t=u.text,u.persist||(o.message.__skipPersist=!0))}return n!=null&&n.postprocessMessage?n.postprocessMessage({...o,text:t,raw:(l=r!=null?r:o.text)!=null?l:""}):mn(t)},Ln=(n,e,o)=>{var Se,oe,we,Be,$e,je,Ht,Gn,Zn,Qn,es,ts,ns,ss;(!n.id||n.id!=="vanilla-agent-root")&&(n.id="vanilla-agent-root");let t=Sn(e);$n(n,t);let r=an.getForInstance(t.plugins);t.components&&Vt.registerAll(t.components);let s=bo(),i=(Se=t.storageAdapter)!=null?Se:An(),l={},u=null;if(i!=null&&i.load)try{let a=i.load();if(a&&typeof a.then=="function")u=a;else if(a){let p=a;p.metadata&&(l=Kn(p.metadata)),(oe=p.messages)!=null&&oe.length&&(t={...t,initialMessages:p.messages})}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",a)}let h=()=>l,d=a=>{var M;l=(M=a({...l}))!=null?M:{},Bt()},E=t.actionParsers&&t.actionParsers.length?t.actionParsers:[ln],f=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[qt.message,qt.messageAndClick],C=dn({parsers:E,handlers:f,getMetadata:h,updateMetadata:d,emit:s.emit,documentRef:typeof document!="undefined"?document:null});C.syncFromMetadata();let y=(Be=(we=t.launcher)==null?void 0:we.enabled)!=null?Be:!0,j=(je=($e=t.launcher)==null?void 0:$e.autoExpand)!=null?je:!1,F=j,m=y,S=y?j:!0,I=To(t,C),A=(Gn=(Ht=t.features)==null?void 0:Ht.showReasoning)!=null?Gn:!0,z=(Qn=(Zn=t.features)==null?void 0:Zn.showToolCalls)!=null?Qn:!0,R=(es=t.statusIndicator)!=null?es:{},V=a=>{var p,M,P,H;return a==="idle"?(p=R.idleText)!=null?p:Ye.idle:a==="connecting"?(M=R.connectingText)!=null?M:Ye.connecting:a==="connected"?(P=R.connectedText)!=null?P:Ye.connected:a==="error"?(H=R.errorText)!=null?H:Ye.error:Ye[a]},{wrapper:te,panel:T}=ho(t),re=mo(t,y),{container:Y,body:U,messagesWrapper:ne,suggestions:ue,textarea:se,sendButton:$,sendButtonWrapper:qe,composerForm:Je,statusText:et,introTitle:wt,introSubtitle:yt,closeButton:O,iconHolder:de,headerTitle:pt,headerSubtitle:gt,header:Ke,footer:rt}=re,B=re.micButton,ke=re.micButtonWrapper,it=r.find(a=>a.renderHeader);if(it!=null&&it.renderHeader){let a=it.renderHeader({config:t,defaultRenderer:()=>{let p=Pt({config:t,showClose:y});return Jt(Y,p,t),p.header},onClose:()=>st(!1,"user")});if(a){let p=Y.querySelector(".tvw-border-b-cw-divider");p&&(p.replaceWith(a),Ke=a)}}let at=r.find(a=>a.renderComposer);if(at!=null&&at.renderComposer){let a=at.renderComposer({config:t,defaultRenderer:()=>Kt({config:t}).footer,onSubmit:p=>{N&&!N.isStreaming()&&N.sendMessage(p)},disabled:!1});a&&(rt.replaceWith(a),rt=a)}(()=>{var P,H;let a=(H=(P=t.layout)==null?void 0:P.slots)!=null?H:{},p=b=>{switch(b){case"body-top":return Y.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6")||null;case"messages":return ne;case"footer-top":return ue;case"composer":return Je;case"footer-bottom":return et;default:return null}},M=(b,x)=>{var K;switch(b){case"header-left":case"header-center":case"header-right":if(b==="header-left")Ke.insertBefore(x,Ke.firstChild);else if(b==="header-right")Ke.appendChild(x);else{let _=Ke.querySelector(".tvw-flex-col");_?(K=_.parentNode)==null||K.insertBefore(x,_.nextSibling):Ke.appendChild(x)}break;case"body-top":let ae=U.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6");ae?ae.replaceWith(x):U.insertBefore(x,U.firstChild);break;case"body-bottom":U.appendChild(x);break;case"footer-top":ue.replaceWith(x);break;case"footer-bottom":et.replaceWith(x);break;default:break}};for(let[b,x]of Object.entries(a))if(x)try{let K=x({config:t,defaultContent:()=>p(b)});K&&M(b,K)}catch(K){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${b}":`,K)}})(),T.appendChild(Y),n.appendChild(te);let ht=()=>{var q,ee,me,_e,He,ot,pe,Tt,kt,Rt,Et,Dt;let a=(ee=(q=t.launcher)==null?void 0:q.sidebarMode)!=null?ee:!1,p=a||((_e=(me=t.launcher)==null?void 0:me.fullHeight)!=null?_e:!1),M=(He=t.theme)!=null?He:{},P=(pe=(ot=t.launcher)==null?void 0:ot.position)!=null?pe:"bottom-left",H=P==="bottom-left"||P==="top-left",b=a?"none":"1px solid var(--tvw-cw-border)",x=a?H?"2px 0 12px rgba(0, 0, 0, 0.08)":"-2px 0 12px rgba(0, 0, 0, 0.08)":"0 25px 50px -12px rgba(0, 0, 0, 0.25)",K=a?"0":"16px",ae=(Tt=M.panelBorder)!=null?Tt:b,_=(kt=M.panelShadow)!=null?kt:x,k=(Rt=M.panelBorderRadius)!=null?Rt:K;if(Y.style.border=ae,Y.style.boxShadow=_,Y.style.borderRadius=k,p&&(n.style.display="flex",n.style.flexDirection="column",n.style.height="100%",n.style.minHeight="0",te.style.display="flex",te.style.flexDirection="column",te.style.flex="1 1 0%",te.style.minHeight="0",te.style.maxHeight="100%",te.style.height="100%",te.style.overflow="hidden",T.style.display="flex",T.style.flexDirection="column",T.style.flex="1 1 0%",T.style.minHeight="0",T.style.maxHeight="100%",T.style.height="100%",T.style.overflow="hidden",Y.style.display="flex",Y.style.flexDirection="column",Y.style.flex="1 1 0%",Y.style.minHeight="0",Y.style.maxHeight="100%",Y.style.overflow="hidden",U.style.flex="1 1 0%",U.style.minHeight="0",U.style.overflowY="auto",rt.style.flexShrink="0"),a){let jt=(Dt=(Et=t.launcher)==null?void 0:Et.sidebarWidth)!=null?Dt:"420px";te.classList.remove("tvw-bottom-6","tvw-right-6","tvw-left-6","tvw-top-6","tvw-bottom-4","tvw-right-4","tvw-left-4","tvw-top-4"),te.style.cssText=`
|
|
15
|
+
`,o.addEventListener("click",e);let t=s=>{var _,j,m,C,$,S,Y,I,V,te;let i=(_=s.launcher)!=null?_:{},l=o.querySelector("[data-role='launcher-title']");l&&(l.textContent=(j=i.title)!=null?j:"Chat Assistant");let u=o.querySelector("[data-role='launcher-subtitle']");u&&(u.textContent=(m=i.subtitle)!=null?m:"Get answers fast");let h=o.querySelector(".tvw-flex-col");h&&(i.textHidden?h.style.display="none":h.style.display="");let d=o.querySelector("[data-role='launcher-icon']");if(d)if(i.agentIconHidden)d.style.display="none";else{let A=(C=i.agentIconSize)!=null?C:"40px";if(d.style.height=A,d.style.width=A,d.innerHTML="",i.agentIconName){let ie=parseFloat(A)||24,J=ye(i.agentIconName,ie*.6,"#ffffff",2);J?(d.appendChild(J),d.style.display=""):(d.textContent=($=i.agentIconText)!=null?$:"\u{1F4AC}",d.style.display="")}else i.iconUrl?d.style.display="none":(d.textContent=(S=i.agentIconText)!=null?S:"\u{1F4AC}",d.style.display="")}let T=o.querySelector("[data-role='launcher-image']");if(T){let A=(Y=i.agentIconSize)!=null?Y:"40px";T.style.height=A,T.style.width=A,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(T.src=i.iconUrl,T.style.display="block"):T.style.display="none"}let f=o.querySelector("[data-role='launcher-call-to-action-icon']");if(f){let A=(I=i.callToActionIconSize)!=null?I:"32px";f.style.height=A,f.style.width=A,i.callToActionIconBackgroundColor?(f.style.backgroundColor=i.callToActionIconBackgroundColor,f.classList.remove("tvw-bg-cw-primary")):(f.style.backgroundColor="",f.classList.add("tvw-bg-cw-primary"));let ie=0;if(i.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=i.callToActionIconPadding,ie=(parseFloat(i.callToActionIconPadding)||0)*2):(f.style.boxSizing="",f.style.padding=""),i.callToActionIconHidden)f.style.display="none";else if(f.style.display="",f.innerHTML="",i.callToActionIconName){let J=parseFloat(A)||24,z=Math.max(J-ie,8),G=ye(i.callToActionIconName,z,"currentColor",2);G?f.appendChild(G):f.textContent=(V=i.callToActionIconText)!=null?V:"\u2197"}else f.textContent=(te=i.callToActionIconText)!=null?te:"\u2197"}let b=i.position&&$t[i.position]?$t[i.position]:$t["bottom-right"],w="tvw-fixed tvw-flex tvw-items-center tvw-gap-3 tvw-rounded-launcher tvw-bg-cw-surface tvw-py-2.5 tvw-pl-3 tvw-pr-3 tvw-shadow-lg tvw-border tvw-border-gray-200 tvw-transition hover:tvw-translate-y-[-2px] tvw-cursor-pointer tvw-z-50";o.className=`${w} ${b}`},r=()=>{o.removeEventListener("click",e),o.remove()};return n&&t(n),{element:o,update:t,destroy:r}};var Pt=n=>{var ie,J,z,G,le,se,P,_e,Ye,Qe,vt,bt,D,he,ht,mt,Je,rt,M,Me,it,at,Tt,ft,ke,et,qe,F,lt,Ke,We,je;let{config:e,showClose:o=!0}=n,t=c("div","tvw-flex tvw-items-center tvw-gap-3 tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),r=(ie=e==null?void 0:e.launcher)!=null?ie:{},s=(J=r.headerIconSize)!=null?J:"48px",i=(z=r.closeButtonSize)!=null?z:"32px",l=(G=r.closeButtonPlacement)!=null?G:"inline",u=(le=r.headerIconHidden)!=null?le:!1,h=r.headerIconName,d=c("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-xl");if(d.style.height=s,d.style.width=s,!u)if(h){let K=parseFloat(s)||24,Se=ye(h,K*.6,"#ffffff",2);Se?d.replaceChildren(Se):d.textContent=(P=(se=e==null?void 0:e.launcher)==null?void 0:se.agentIconText)!=null?P:"\u{1F4AC}"}else if((_e=e==null?void 0:e.launcher)!=null&&_e.iconUrl){let K=c("img");K.src=e.launcher.iconUrl,K.alt="",K.className="tvw-rounded-xl tvw-object-cover",K.style.height=s,K.style.width=s,d.replaceChildren(K)}else d.textContent=(Qe=(Ye=e==null?void 0:e.launcher)==null?void 0:Ye.agentIconText)!=null?Qe:"\u{1F4AC}";let T=c("div","tvw-flex tvw-flex-col"),f=c("span","tvw-text-base tvw-font-semibold");f.textContent=(bt=(vt=e==null?void 0:e.launcher)==null?void 0:vt.title)!=null?bt:"Chat Assistant";let b=c("span","tvw-text-xs tvw-text-cw-muted");b.textContent=(he=(D=e==null?void 0:e.launcher)==null?void 0:D.subtitle)!=null?he:"Here to help you get answers fast",T.append(f,b),u?t.append(T):t.append(d,T);let w=(ht=r.clearChat)!=null?ht:{},_=(mt=w.enabled)!=null?mt:!0,j=(Je=w.placement)!=null?Je:"inline",m=null,C=null;if(_){let K=(rt=w.size)!=null?rt:"32px",Se=(M=w.iconName)!=null?M:"refresh-cw",Le=(Me=w.iconColor)!=null?Me:"",Ue=(it=w.backgroundColor)!=null?it:"",tt=(at=w.borderWidth)!=null?at:"",xt=(Tt=w.borderColor)!=null?Tt:"",Lt=(ft=w.borderRadius)!=null?ft:"",pt=(ke=w.paddingX)!=null?ke:"",Ct=(et=w.paddingY)!=null?et:"",de=(qe=w.tooltipText)!=null?qe:"Clear chat",Ot=(F=w.showTooltip)!=null?F:!0;C=c("div",j==="top-right"?"tvw-absolute tvw-top-4 tvw-z-50":"tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper"),j==="top-right"&&(C.style.right="48px"),m=c("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none"),m.style.height=K,m.style.width=K,m.type="button",m.setAttribute("aria-label",de);let Bt=ye(Se,"20px",Le||"",2);if(Bt&&m.appendChild(Bt),Le&&(m.style.color=Le,m.classList.remove("tvw-text-cw-muted")),Ue&&(m.style.backgroundColor=Ue,m.classList.remove("hover:tvw-bg-gray-100")),tt||xt){let ve=tt||"0px",wt=xt||"transparent";m.style.border=`${ve} solid ${wt}`,m.classList.remove("tvw-border-none")}if(Lt&&(m.style.borderRadius=Lt,m.classList.remove("tvw-rounded-full")),pt?(m.style.paddingLeft=pt,m.style.paddingRight=pt):(m.style.paddingLeft="",m.style.paddingRight=""),Ct?(m.style.paddingTop=Ct,m.style.paddingBottom=Ct):(m.style.paddingTop="",m.style.paddingBottom=""),C.appendChild(m),Ot&&de&&m&&C){let ve=null,wt=()=>{if(ve||!m)return;ve=c("div","tvw-clear-chat-tooltip"),ve.textContent=de;let Ht=c("div");Ht.className="tvw-clear-chat-tooltip-arrow",ve.appendChild(Ht);let yt=m.getBoundingClientRect();ve.style.position="fixed",ve.style.left=`${yt.left+yt.width/2}px`,ve.style.top=`${yt.top-8}px`,ve.style.transform="translate(-50%, -100%)",document.body.appendChild(ve)},St=()=>{ve&&ve.parentNode&&(ve.parentNode.removeChild(ve),ve=null)};C.addEventListener("mouseenter",wt),C.addEventListener("mouseleave",St),m.addEventListener("focus",wt),m.addEventListener("blur",St),C._cleanupTooltip=()=>{St(),C&&(C.removeEventListener("mouseenter",wt),C.removeEventListener("mouseleave",St)),m&&(m.removeEventListener("focus",wt),m.removeEventListener("blur",St))}}j==="inline"&&t.appendChild(C)}let $=c("div",l==="top-right"?"tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50":_&&j==="inline"?"":"tvw-ml-auto"),S=c("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");S.style.height=i,S.style.width=i,S.type="button";let Y=(lt=r.closeButtonTooltipText)!=null?lt:"Close chat",I=(Ke=r.closeButtonShowTooltip)!=null?Ke:!0;S.setAttribute("aria-label",Y),S.style.display=o?"":"none";let V=(We=r.closeButtonIconName)!=null?We:"x",te=(je=r.closeButtonIconText)!=null?je:"\xD7",A=ye(V,"20px",r.closeButtonColor||"",2);if(A?S.appendChild(A):S.textContent=te,r.closeButtonColor?(S.style.color=r.closeButtonColor,S.classList.remove("tvw-text-cw-muted")):(S.style.color="",S.classList.add("tvw-text-cw-muted")),r.closeButtonBackgroundColor?(S.style.backgroundColor=r.closeButtonBackgroundColor,S.classList.remove("hover:tvw-bg-gray-100")):(S.style.backgroundColor="",S.classList.add("hover:tvw-bg-gray-100")),r.closeButtonBorderWidth||r.closeButtonBorderColor){let K=r.closeButtonBorderWidth||"0px",Se=r.closeButtonBorderColor||"transparent";S.style.border=`${K} solid ${Se}`,S.classList.remove("tvw-border-none")}else S.style.border="",S.classList.add("tvw-border-none");if(r.closeButtonBorderRadius?(S.style.borderRadius=r.closeButtonBorderRadius,S.classList.remove("tvw-rounded-full")):(S.style.borderRadius="",S.classList.add("tvw-rounded-full")),r.closeButtonPaddingX?(S.style.paddingLeft=r.closeButtonPaddingX,S.style.paddingRight=r.closeButtonPaddingX):(S.style.paddingLeft="",S.style.paddingRight=""),r.closeButtonPaddingY?(S.style.paddingTop=r.closeButtonPaddingY,S.style.paddingBottom=r.closeButtonPaddingY):(S.style.paddingTop="",S.style.paddingBottom=""),$.appendChild(S),I&&Y){let K=null,Se=()=>{if(K)return;K=c("div","tvw-clear-chat-tooltip"),K.textContent=Y;let Ue=c("div");Ue.className="tvw-clear-chat-tooltip-arrow",K.appendChild(Ue);let tt=S.getBoundingClientRect();K.style.position="fixed",K.style.left=`${tt.left+tt.width/2}px`,K.style.top=`${tt.top-8}px`,K.style.transform="translate(-50%, -100%)",document.body.appendChild(K)},Le=()=>{K&&K.parentNode&&(K.parentNode.removeChild(K),K=null)};$.addEventListener("mouseenter",Se),$.addEventListener("mouseleave",Le),S.addEventListener("focus",Se),S.addEventListener("blur",Le),$._cleanupTooltip=()=>{Le(),$.removeEventListener("mouseenter",Se),$.removeEventListener("mouseleave",Le),S.removeEventListener("focus",Se),S.removeEventListener("blur",Le)}}return l!=="top-right"&&t.appendChild($),{header:t,iconHolder:d,headerTitle:f,headerSubtitle:b,closeButton:S,closeButtonWrapper:$,clearChatButton:m,clearChatButtonWrapper:C}},Jt=(n,e,o)=>{var i,l,u,h;let t=(i=o==null?void 0:o.launcher)!=null?i:{},r=(l=t.closeButtonPlacement)!=null?l:"inline",s=(h=(u=t.clearChat)==null?void 0:u.placement)!=null?h:"inline";n.appendChild(e.header),r==="top-right"&&(n.style.position="relative",n.appendChild(e.closeButtonWrapper)),e.clearChatButtonWrapper&&s==="top-right"&&(n.style.position="relative",n.appendChild(e.clearChatButtonWrapper))};var Nn=n=>Pt({config:n.config,showClose:n.showClose,onClose:n.onClose,onClearChat:n.onClearChat}),Dn=n=>{var w,_,j,m;let{config:e,showClose:o=!0,onClose:t}=n,r=(w=e==null?void 0:e.launcher)!=null?w:{},s=c("div","tvw-flex tvw-items-center tvw-justify-between tvw-bg-cw-surface tvw-px-6 tvw-py-4 tvw-border-b-cw-divider"),i=c("span","tvw-text-base tvw-font-semibold");i.textContent=(_=r.title)!=null?_:"Chat Assistant",s.appendChild(i);let l=(j=r.closeButtonSize)!=null?j:"32px",u=c("div",""),h=c("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");h.style.height=l,h.style.width=l,h.type="button",h.setAttribute("aria-label","Close chat"),h.style.display=o?"":"none";let d=(m=r.closeButtonIconName)!=null?m:"x",T=ye(d,"20px",r.closeButtonColor||"",2);T?h.appendChild(T):h.textContent="\xD7",t&&h.addEventListener("click",t),u.appendChild(h),s.appendChild(u);let f=c("div");f.style.display="none";let b=c("span");return b.style.display="none",{header:s,iconHolder:f,headerTitle:i,headerSubtitle:b,closeButton:h,closeButtonWrapper:u,clearChatButton:null,clearChatButtonWrapper:null}},Fn=n=>{var S,Y,I,V,te,A,ie,J;let{config:e,showClose:o=!0,onClose:t,onClearChat:r}=n,s=(S=e==null?void 0:e.launcher)!=null?S:{},i=c("div","tvw-flex tvw-flex-col tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),l=c("div","tvw-flex tvw-items-center tvw-gap-3"),u=(Y=s.headerIconSize)!=null?Y:"56px",h=c("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-2xl");h.style.height=u,h.style.width=u;let d=s.headerIconName;if(d){let z=parseFloat(u)||24,G=ye(d,z*.5,"#ffffff",2);G?h.replaceChildren(G):h.textContent=(I=s.agentIconText)!=null?I:"\u{1F4AC}"}else if(s.iconUrl){let z=c("img");z.src=s.iconUrl,z.alt="",z.className="tvw-rounded-xl tvw-object-cover",z.style.height=u,z.style.width=u,h.replaceChildren(z)}else h.textContent=(V=s.agentIconText)!=null?V:"\u{1F4AC}";let T=c("div","tvw-flex tvw-flex-col tvw-flex-1"),f=c("span","tvw-text-lg tvw-font-semibold");f.textContent=(te=s.title)!=null?te:"Chat Assistant";let b=c("span","tvw-text-sm tvw-text-cw-muted");b.textContent=(A=s.subtitle)!=null?A:"Here to help you get answers fast",T.append(f,b),l.append(h,T);let w=(ie=s.closeButtonSize)!=null?ie:"32px",_=c("div",""),j=c("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");j.style.height=w,j.style.width=w,j.type="button",j.setAttribute("aria-label","Close chat"),j.style.display=o?"":"none";let m=(J=s.closeButtonIconName)!=null?J:"x",C=ye(m,"20px",s.closeButtonColor||"",2);C?j.appendChild(C):j.textContent="\xD7",t&&j.addEventListener("click",t),_.appendChild(j),l.appendChild(_),i.appendChild(l);let $=c("div","tvw-mt-3 tvw-pt-3 tvw-border-t tvw-border-gray-100 tvw-text-xs tvw-text-cw-muted");return $.textContent="Online and ready to help",i.appendChild($),{header:i,iconHolder:h,headerTitle:f,headerSubtitle:b,closeButton:j,closeButtonWrapper:_,clearChatButton:null,clearChatButtonWrapper:null}},Cn={default:Nn,minimal:Dn,expanded:Fn},jn=n=>{var e;return(e=Cn[n])!=null?e:Cn.default},Sn=(n,e,o)=>{var i,l,u;if(e!=null&&e.render){let h=e.render({config:n,onClose:o==null?void 0:o.onClose,onClearChat:o==null?void 0:o.onClearChat}),d=c("div");d.style.display="none";let T=c("span"),f=c("span"),b=c("button");b.style.display="none";let w=c("div");return w.style.display="none",{header:h,iconHolder:d,headerTitle:T,headerSubtitle:f,closeButton:b,closeButtonWrapper:w,clearChatButton:null,clearChatButtonWrapper:null}}let t=(i=e==null?void 0:e.layout)!=null?i:"default",s=jn(t)({config:n,showClose:(u=(l=e==null?void 0:e.showCloseButton)!=null?l:o==null?void 0:o.showClose)!=null?u:!0,onClose:o==null?void 0:o.onClose,onClearChat:o==null?void 0:o.onClearChat});return e&&(e.showIcon===!1&&(s.iconHolder.style.display="none"),e.showTitle===!1&&(s.headerTitle.style.display="none"),e.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),e.showCloseButton===!1&&(s.closeButton.style.display="none"),e.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var Ko=n=>{switch(n){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}},Kt=n=>{var se,P,_e,Ye,Qe,vt,bt,D,he,ht,mt,Je,rt,M,Me,it,at,Tt,ft,ke,et,qe,F,lt,Ke;let{config:e}=n,o=c("div","tvw-border-t-cw-divider tvw-bg-cw-surface tvw-px-6 tvw-py-4"),t=c("div","tvw-mb-3 tvw-flex tvw-flex-wrap tvw-gap-2"),r=((se=e==null?void 0:e.voiceRecognition)==null?void 0:se.enabled)===!0,s=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),u=c("form",`tvw-flex tvw-items-end ${r&&s?"tvw-gap-1":"tvw-gap-3"} tvw-rounded-2xl tvw-border tvw-border-gray-200 tvw-bg-cw-input-background tvw-px-4 tvw-py-3`);u.style.outline="none";let h=c("textarea");h.placeholder=(_e=(P=e==null?void 0:e.copy)==null?void 0:P.inputPlaceholder)!=null?_e:"Type your message\u2026",h.className="tvw-min-h-[48px] tvw-flex-1 tvw-resize-none tvw-border-none tvw-bg-transparent tvw-text-sm tvw-text-cw-primary focus:tvw-outline-none focus:tvw-border-none",h.rows=1;let d=(Qe=(Ye=e==null?void 0:e.theme)==null?void 0:Ye.inputFontFamily)!=null?Qe:"sans-serif",T=(bt=(vt=e==null?void 0:e.theme)==null?void 0:vt.inputFontWeight)!=null?bt:"400";h.style.fontFamily=Ko(d),h.style.fontWeight=T,h.style.border="none",h.style.outline="none",h.style.borderWidth="0",h.style.borderStyle="none",h.style.borderColor="transparent",h.addEventListener("focus",()=>{h.style.border="none",h.style.outline="none",h.style.borderWidth="0",h.style.borderStyle="none",h.style.borderColor="transparent",h.style.boxShadow="none"}),h.addEventListener("blur",()=>{h.style.border="none",h.style.outline="none"});let f=(D=e==null?void 0:e.sendButton)!=null?D:{},b=(he=f.useIcon)!=null?he:!1,w=(ht=f.iconText)!=null?ht:"\u2191",_=f.iconName,j=(mt=f.tooltipText)!=null?mt:"Send message",m=(Je=f.showTooltip)!=null?Je:!1,C=(rt=f.size)!=null?rt:"40px",$=f.backgroundColor,S=f.textColor,Y=c("div","tvw-send-button-wrapper"),I=c("button",b?"tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer":"tvw-rounded-button tvw-bg-cw-accent tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold disabled:tvw-opacity-50 tvw-cursor-pointer");if(I.type="submit",b){if(I.style.width=C,I.style.height=C,I.style.minWidth=C,I.style.minHeight=C,I.style.fontSize="18px",I.style.lineHeight="1",I.innerHTML="",_){let We=parseFloat(C)||24,je=S&&typeof S=="string"&&S.trim()?S.trim():"currentColor",K=ye(_,We,je,2);K?(I.appendChild(K),I.style.color=je):(I.textContent=w,S?I.style.color=S:I.classList.add("tvw-text-white"))}else I.textContent=w,S?I.style.color=S:I.classList.add("tvw-text-white");$?I.style.backgroundColor=$:I.classList.add("tvw-bg-cw-primary")}else I.textContent=(Me=(M=e==null?void 0:e.copy)==null?void 0:M.sendButtonLabel)!=null?Me:"Send",S?I.style.color=S:I.classList.add("tvw-text-white");if(f.borderWidth&&(I.style.borderWidth=f.borderWidth,I.style.borderStyle="solid"),f.borderColor&&(I.style.borderColor=f.borderColor),f.paddingX?(I.style.paddingLeft=f.paddingX,I.style.paddingRight=f.paddingX):(I.style.paddingLeft="",I.style.paddingRight=""),f.paddingY?(I.style.paddingTop=f.paddingY,I.style.paddingBottom=f.paddingY):(I.style.paddingTop="",I.style.paddingBottom=""),m&&j){let We=c("div","tvw-send-button-tooltip");We.textContent=j,Y.appendChild(We)}Y.appendChild(I);let V=(it=e==null?void 0:e.voiceRecognition)!=null?it:{},te=V.enabled===!0,A=null,ie=null,J=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(te&&J){ie=c("div","tvw-send-button-wrapper"),A=c("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer"),A.type="button",A.setAttribute("aria-label","Start voice recognition");let We=(at=V.iconName)!=null?at:"mic",je=(Tt=V.iconSize)!=null?Tt:C,K=parseFloat(je)||24,Se=(ft=V.backgroundColor)!=null?ft:$,Le=(ke=V.iconColor)!=null?ke:S;A.style.width=je,A.style.height=je,A.style.minWidth=je,A.style.minHeight=je,A.style.fontSize="18px",A.style.lineHeight="1";let Ue=Le||"currentColor",tt=ye(We,K,Ue,1.5);tt?(A.appendChild(tt),A.style.color=Ue):(A.textContent="\u{1F3A4}",A.style.color=Ue),Se?A.style.backgroundColor=Se:A.classList.add("tvw-bg-cw-primary"),Le?A.style.color=Le:!Le&&!S&&A.classList.add("tvw-text-white"),V.borderWidth&&(A.style.borderWidth=V.borderWidth,A.style.borderStyle="solid"),V.borderColor&&(A.style.borderColor=V.borderColor),V.paddingX&&(A.style.paddingLeft=V.paddingX,A.style.paddingRight=V.paddingX),V.paddingY&&(A.style.paddingTop=V.paddingY,A.style.paddingBottom=V.paddingY),ie.appendChild(A);let xt=(et=V.tooltipText)!=null?et:"Start voice recognition";if(((qe=V.showTooltip)!=null?qe:!1)&&xt){let pt=c("div","tvw-send-button-tooltip");pt.textContent=xt,ie.appendChild(pt)}}u.addEventListener("click",We=>{We.target!==I&&We.target!==Y&&We.target!==A&&We.target!==ie&&h.focus()}),u.append(h),ie&&u.append(ie),u.append(Y);let z=c("div","tvw-mt-2 tvw-text-right tvw-text-xs tvw-text-cw-muted"),G=(F=e==null?void 0:e.statusIndicator)!=null?F:{},le=(lt=G.visible)!=null?lt:!0;return z.style.display=le?"":"none",z.textContent=(Ke=G.idleText)!=null?Ke:"Online",o.append(t,u,z),{footer:o,suggestions:t,composerForm:u,textarea:h,sendButton:I,sendButtonWrapper:Y,micButton:A,micButtonWrapper:ie,statusText:z}};var fo=n=>{var u,h,d,T,f;if(!((h=(u=n==null?void 0:n.launcher)==null?void 0:u.enabled)!=null?h:!0)){let b=c("div","tvw-relative tvw-w-full tvw-h-full tvw-flex tvw-flex-col tvw-flex-1 tvw-min-h-0"),w=c("div","tvw-relative tvw-w-full tvw-flex-1 tvw-flex tvw-flex-col tvw-min-h-0");return b.appendChild(w),{wrapper:b,panel:w}}let o=(d=n==null?void 0:n.launcher)!=null?d:{},t=o.position&&$t[o.position]?$t[o.position]:$t["bottom-right"],r=c("div",`tvw-fixed ${t} tvw-z-50 tvw-transition`),s=c("div","tvw-relative tvw-min-h-[320px]"),i=(f=(T=n==null?void 0:n.launcher)==null?void 0:T.width)!=null?f:n==null?void 0:n.launcherWidth,l=i!=null?i:"min(400px, calc(100vw - 24px))";return s.style.width=l,s.style.maxWidth=l,r.appendChild(s),{wrapper:r,panel:s}},wo=(n,e=!0)=>{var T,f,b,w,_;let o=c("div","tvw-flex tvw-h-full tvw-w-full tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-bg-cw-surface tvw-text-cw-primary tvw-rounded-2xl tvw-overflow-hidden tvw-shadow-2xl tvw-border tvw-border-cw-border"),t=(T=n==null?void 0:n.layout)==null?void 0:T.header,r=t?Sn(n,t,{showClose:e}):Pt({config:n,showClose:e}),s=c("div","tvw-flex tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-gap-6 tvw-overflow-y-auto tvw-bg-cw-container tvw-px-6 tvw-py-6");s.id="vanilla-agent-scroll-container";let i=c("div","tvw-rounded-2xl tvw-bg-cw-surface tvw-p-6 tvw-shadow-sm"),l=c("h2","tvw-text-lg tvw-font-semibold tvw-text-cw-primary");l.textContent=(b=(f=n==null?void 0:n.copy)==null?void 0:f.welcomeTitle)!=null?b:"Hello \u{1F44B}";let u=c("p","tvw-mt-2 tvw-text-sm tvw-text-cw-muted");u.textContent=(_=(w=n==null?void 0:n.copy)==null?void 0:w.welcomeSubtitle)!=null?_:"Ask anything about your account or products.",i.append(l,u);let h=c("div","tvw-flex tvw-flex-col tvw-gap-3");s.append(i,h);let d=Kt({config:n});return Jt(o,r,n),o.append(s,d.footer),{container:o,body:s,messagesWrapper:h,suggestions:d.suggestions,textarea:d.textarea,sendButton:d.sendButton,sendButtonWrapper:d.sendButtonWrapper,micButton:d.micButton,micButtonWrapper:d.micButtonWrapper,composerForm:d.composerForm,statusText:d.statusText,introTitle:l,introSubtitle:u,closeButton:r.closeButton,closeButtonWrapper:r.closeButtonWrapper,clearChatButton:r.clearChatButton,clearChatButtonWrapper:r.clearChatButtonWrapper,iconHolder:r.iconHolder,headerTitle:r.headerTitle,headerSubtitle:r.headerSubtitle,header:r.header,footer:d.footer}};var rn=()=>{let n=document.createElement("div");n.className="tvw-flex tvw-items-center tvw-space-x-1 tvw-h-5 tvw-mt-2";let e=document.createElement("div");e.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",e.style.animationDelay="0ms";let o=document.createElement("div");o.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",o.style.animationDelay="250ms";let t=document.createElement("div");t.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",t.style.animationDelay="500ms";let r=document.createElement("span");return r.className="tvw-sr-only",r.textContent="Loading",n.appendChild(e),n.appendChild(o),n.appendChild(t),n.appendChild(r),n},Xo=(n,e)=>{let o=c("div","tvw-flex-shrink-0 tvw-w-8 tvw-h-8 tvw-rounded-full tvw-flex tvw-items-center tvw-justify-center tvw-text-sm"),t=e==="user"?n.userAvatar:n.assistantAvatar;if(t)if(t.startsWith("http")||t.startsWith("/")||t.startsWith("data:")){let r=c("img");r.src=t,r.alt=e==="user"?"User":"Assistant",r.className="tvw-w-full tvw-h-full tvw-rounded-full tvw-object-cover",o.appendChild(r)}else o.textContent=t,o.classList.add(e==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");else o.textContent=e==="user"?"U":"A",o.classList.add(e==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");return o},yo=(n,e)=>{let o=c("div","tvw-text-xs tvw-text-cw-muted"),t=new Date(n.createdAt);return e.format?o.textContent=e.format(t):o.textContent=t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},Vo=(n,e="bubble")=>{let o=["vanilla-message-bubble","tvw-max-w-[85%]"];switch(e){case"flat":n==="user"?o.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-text-cw-primary","tvw-py-2"):o.push("vanilla-message-assistant-bubble","tvw-text-cw-primary","tvw-py-2");break;case"minimal":o.push("tvw-text-sm","tvw-leading-relaxed"),n==="user"?o.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-3","tvw-py-2","tvw-rounded-lg"):o.push("vanilla-message-assistant-bubble","tvw-bg-cw-surface","tvw-text-cw-primary","tvw-px-3","tvw-py-2","tvw-rounded-lg");break;case"bubble":default:o.push("tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm"),n==="user"?o.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-5","tvw-py-3"):o.push("vanilla-message-assistant-bubble","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3");break}return o},Xt=(n,e,o)=>{var j,m,C,$,S;let t=o!=null?o:{},r=(j=t.layout)!=null?j:"bubble",s=t.avatar,i=t.timestamp,l=(m=s==null?void 0:s.show)!=null?m:!1,u=(C=i==null?void 0:i.show)!=null?C:!1,h=($=s==null?void 0:s.position)!=null?$:"left",d=(S=i==null?void 0:i.position)!=null?S:"below",T=Vo(n.role,r),f=c("div",T.join(" ")),b=document.createElement("div");if(b.innerHTML=e({text:n.content,message:n,streaming:!!n.streaming,raw:n.rawContent}),u&&d==="inline"&&n.createdAt){let Y=yo(n,i);Y.classList.add("tvw-ml-2","tvw-inline"),b.appendChild(Y)}if(f.appendChild(b),u&&d==="below"&&n.createdAt){let Y=yo(n,i);Y.classList.add("tvw-mt-1"),f.appendChild(Y)}if(n.streaming&&n.role==="assistant"&&(!n.content||!n.content.trim())){let Y=rn();f.appendChild(Y)}if(!l||n.role==="system")return f;let w=c("div",`tvw-flex tvw-gap-2 ${n.role==="user"?"tvw-flex-row-reverse":""}`),_=Xo(s,n.role);return h==="right"||h==="left"&&n.role==="user"?w.append(f,_):w.append(_,f),f.classList.remove("tvw-max-w-[85%]"),f.classList.add("tvw-max-w-[calc(85%-2.5rem)]"),w},vo=(n,e,o)=>{let t=o!=null?o:{};return n.role==="user"&&t.renderUserMessage?t.renderUserMessage({message:n,config:{},streaming:!!n.streaming}):n.role==="assistant"&&t.renderAssistantMessage?t.renderAssistantMessage({message:n,config:{},streaming:!!n.streaming}):Xt(n,e,o)};var _n=new Set,qn=n=>{let e=n.reasoning,o=c("div",["vanilla-message-bubble","vanilla-reasoning-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(!e)return o;let t=_n.has(n.id),r=c("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");r.type="button",r.setAttribute("aria-expanded",t?"true":"false");let s=c("div","tvw-flex tvw-flex-col tvw-text-left"),i=c("span","tvw-text-xs tvw-text-cw-primary");i.textContent="Thinking...",s.appendChild(i);let l=c("span","tvw-text-xs tvw-text-cw-primary");l.textContent=go(e),s.appendChild(l),e.status==="complete"?i.style.display="none":i.style.display="";let u=c("div","tvw-flex tvw-items-center"),d=ye(t?"chevron-up":"chevron-down",16,"currentColor",2);d?u.appendChild(d):u.textContent=t?"Hide":"Show";let T=c("div","tvw-flex tvw-items-center tvw-ml-auto");T.append(u),r.append(s,T);let f=c("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-px-4 tvw-py-3");f.style.display=t?"":"none";let b=e.chunks.join(""),w=c("div","tvw-whitespace-pre-wrap tvw-text-xs tvw-leading-snug tvw-text-cw-muted");w.textContent=b||(e.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),f.appendChild(w);let _=()=>{r.setAttribute("aria-expanded",t?"true":"false"),u.innerHTML="";let C=ye(t?"chevron-up":"chevron-down",16,"currentColor",2);C?u.appendChild(C):u.textContent=t?"Hide":"Show",f.style.display=t?"":"none"},j=()=>{t=!t,t?_n.add(n.id):_n.delete(n.id),_()};return r.addEventListener("pointerdown",m=>{m.preventDefault(),j()}),r.addEventListener("keydown",m=>{(m.key==="Enter"||m.key===" ")&&(m.preventDefault(),j())}),_(),o.append(r,f),o};var Un=new Set,zn=(n,e)=>{var j;let o=n.toolCall,t=(j=e==null?void 0:e.toolCall)!=null?j:{},r=c("div",["vanilla-message-bubble","vanilla-tool-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(t.backgroundColor&&(r.style.backgroundColor=t.backgroundColor),t.borderColor&&(r.style.borderColor=t.borderColor),t.borderWidth&&(r.style.borderWidth=t.borderWidth),t.borderRadius&&(r.style.borderRadius=t.borderRadius),!o)return r;let s=Un.has(n.id),i=c("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");i.type="button",i.setAttribute("aria-expanded",s?"true":"false"),t.headerBackgroundColor&&(i.style.backgroundColor=t.headerBackgroundColor),t.headerPaddingX&&(i.style.paddingLeft=t.headerPaddingX,i.style.paddingRight=t.headerPaddingX),t.headerPaddingY&&(i.style.paddingTop=t.headerPaddingY,i.style.paddingBottom=t.headerPaddingY);let l=c("div","tvw-flex tvw-flex-col tvw-text-left"),u=c("span","tvw-text-xs tvw-text-cw-primary");t.headerTextColor&&(u.style.color=t.headerTextColor),u.textContent=ho(o),l.appendChild(u);let h=c("div","tvw-flex tvw-items-center"),d=t.toggleTextColor||t.headerTextColor||"currentColor",T=ye(s?"chevron-up":"chevron-down",16,d,2);T?h.appendChild(T):h.textContent=s?"Hide":"Show";let f=c("div","tvw-flex tvw-items-center tvw-gap-2 tvw-ml-auto");f.append(h),i.append(l,f);let b=c("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-space-y-3 tvw-px-4 tvw-py-3");if(b.style.display=s?"":"none",t.contentBackgroundColor&&(b.style.backgroundColor=t.contentBackgroundColor),t.contentTextColor&&(b.style.color=t.contentTextColor),t.contentPaddingX&&(b.style.paddingLeft=t.contentPaddingX,b.style.paddingRight=t.contentPaddingX),t.contentPaddingY&&(b.style.paddingTop=t.contentPaddingY,b.style.paddingBottom=t.contentPaddingY),o.name){let m=c("div","tvw-text-xs tvw-text-cw-muted tvw-italic");t.contentTextColor?m.style.color=t.contentTextColor:t.headerTextColor&&(m.style.color=t.headerTextColor),m.textContent=o.name,b.appendChild(m)}if(o.args!==void 0){let m=c("div","tvw-space-y-1"),C=c("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(C.style.color=t.labelTextColor),C.textContent="Arguments";let $=c("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");$.style.fontSize="0.75rem",$.style.lineHeight="1rem",t.codeBlockBackgroundColor&&($.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&($.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&($.style.color=t.codeBlockTextColor),$.textContent=Pn(o.args),m.append(C,$),b.appendChild(m)}if(o.chunks&&o.chunks.length){let m=c("div","tvw-space-y-1"),C=c("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(C.style.color=t.labelTextColor),C.textContent="Activity";let $=c("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");$.style.fontSize="0.75rem",$.style.lineHeight="1rem",t.codeBlockBackgroundColor&&($.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&($.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&($.style.color=t.codeBlockTextColor),$.textContent=o.chunks.join(`
|
|
16
|
+
`),m.append(C,$),b.appendChild(m)}if(o.status==="complete"&&o.result!==void 0){let m=c("div","tvw-space-y-1"),C=c("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(C.style.color=t.labelTextColor),C.textContent="Result";let $=c("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");$.style.fontSize="0.75rem",$.style.lineHeight="1rem",t.codeBlockBackgroundColor&&($.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&($.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&($.style.color=t.codeBlockTextColor),$.textContent=Pn(o.result),m.append(C,$),b.appendChild(m)}if(o.status==="complete"&&typeof o.duration=="number"){let m=c("div","tvw-text-xs tvw-text-cw-muted");t.contentTextColor&&(m.style.color=t.contentTextColor),m.textContent=`Duration: ${o.duration}ms`,b.appendChild(m)}let w=()=>{i.setAttribute("aria-expanded",s?"true":"false"),h.innerHTML="";let m=t.toggleTextColor||t.headerTextColor||"currentColor",C=ye(s?"chevron-up":"chevron-down",16,m,2);C?h.appendChild(C):h.textContent=s?"Hide":"Show",b.style.display=s?"":"none"},_=()=>{s=!s,s?Un.add(n.id):Un.delete(n.id),w()};return i.addEventListener("pointerdown",m=>{m.preventDefault(),_()}),i.addEventListener("keydown",m=>{(m.key==="Enter"||m.key===" ")&&(m.preventDefault(),_())}),w(),r.append(i,b),r};var bo=n=>{let e=[];return{buttons:e,render:(t,r,s,i,l)=>{if(n.innerHTML="",e.length=0,!t||!t.length||(i!=null?i:r?r.getMessages():[]).some(b=>b.role==="user"))return;let d=document.createDocumentFragment(),T=r?r.isStreaming():!1,f=b=>{switch(b){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};t.forEach(b=>{let w=c("button","tvw-rounded-button tvw-bg-cw-surface tvw-px-3 tvw-py-1.5 tvw-text-xs tvw-font-medium tvw-text-cw-muted hover:tvw-opacity-90 tvw-cursor-pointer tvw-border tvw-border-gray-200");w.type="button",w.textContent=b,w.disabled=T,l!=null&&l.fontFamily&&(w.style.fontFamily=f(l.fontFamily)),l!=null&&l.fontWeight&&(w.style.fontWeight=l.fontWeight),l!=null&&l.paddingX&&(w.style.paddingLeft=l.paddingX,w.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(w.style.paddingTop=l.paddingY,w.style.paddingBottom=l.paddingY),w.addEventListener("click",()=>{!r||r.isStreaming()||(s.value="",r.sendMessage(b))}),d.appendChild(w),e.push(w)}),n.appendChild(d)}}};var xo={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},Yn=(n,e,o,t)=>{let r=n.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{var w,_,j;if(s.dataset.enhanced==="true")return;let i=(w=s.dataset.tvForm)!=null?w:"init";s.dataset.enhanced="true";let l=(_=xo[i])!=null?_:xo.init;s.classList.add("tvw-form-card","tvw-space-y-4");let u=c("div","tvw-space-y-1"),h=c("h3","tvw-text-base tvw-font-semibold tvw-text-cw-primary");if(h.textContent=l.title,u.appendChild(h),l.description){let m=c("p","tvw-text-sm tvw-text-cw-muted");m.textContent=l.description,u.appendChild(m)}let d=document.createElement("form");d.className="tvw-form-grid tvw-space-y-3",l.fields.forEach(m=>{var I,V;let C=c("label","tvw-form-field tvw-flex tvw-flex-col tvw-gap-1");C.htmlFor=`${e.id}-${i}-${m.name}`;let $=c("span","tvw-text-xs tvw-font-medium tvw-text-cw-muted");$.textContent=m.label,C.appendChild($);let S=(I=m.type)!=null?I:"text",Y;S==="textarea"?(Y=document.createElement("textarea"),Y.rows=3):(Y=document.createElement("input"),Y.type=S),Y.className="tvw-rounded-xl tvw-border tvw-border-gray-200 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-sm tvw-text-cw-primary focus:tvw-outline-none focus:tvw-border-cw-primary",Y.id=`${e.id}-${i}-${m.name}`,Y.name=m.name,Y.placeholder=(V=m.placeholder)!=null?V:"",m.required&&(Y.required=!0),C.appendChild(Y),d.appendChild(C)});let T=c("div","tvw-flex tvw-items-center tvw-justify-between tvw-gap-2"),f=c("div","tvw-text-xs tvw-text-cw-muted tvw-min-h-[1.5rem]"),b=c("button","tvw-inline-flex tvw-items-center tvw-rounded-full tvw-bg-cw-primary tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold tvw-text-white disabled:tvw-opacity-60 tvw-cursor-pointer");b.type="submit",b.textContent=(j=l.submitLabel)!=null?j:"Submit",T.appendChild(f),T.appendChild(b),d.appendChild(T),s.replaceChildren(u,d),d.addEventListener("submit",async m=>{var Y,I;m.preventDefault();let C=(Y=o.formEndpoint)!=null?Y:"/form",$=new FormData(d),S={};$.forEach((V,te)=>{S[te]=V}),S.type=i,b.disabled=!0,f.textContent="Submitting\u2026";try{let V=await fetch(C,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(S)});if(!V.ok)throw new Error(`Form submission failed (${V.status})`);let te=await V.json();f.textContent=(I=te.message)!=null?I:"Thanks! We'll be in touch soon.",te.success&&te.nextPrompt&&await t.sendMessage(String(te.nextPrompt))}catch(V){f.textContent=V instanceof Error?V.message:"Something went wrong. Please try again."}finally{b.disabled=!1}})})};var Jn=class{constructor(){this.plugins=new Map}register(e){var o;this.plugins.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.plugins.set(e.id,e),(o=e.onRegister)==null||o.call(e)}unregister(e){var t;let o=this.plugins.get(e);o&&((t=o.onUnregister)==null||t.call(o),this.plugins.delete(e))}getAll(){return Array.from(this.plugins.values()).sort((e,o)=>{var t,r;return((t=o.priority)!=null?t:0)-((r=e.priority)!=null?r:0)})}getForInstance(e){let o=this.getAll();if(!e||e.length===0)return o;let t=new Set(e.map(s=>s.id));return[...o.filter(s=>!t.has(s.id)),...e].sort((s,i)=>{var l,u;return((l=i.priority)!=null?l:0)-((u=s.priority)!=null?u:0)})}clear(){this.plugins.forEach(e=>{var o;return(o=e.onUnregister)==null?void 0:o.call(e)}),this.plugins.clear()}},an=new Jn;var Pe={apiUrl:"http://localhost:43111/api/chat/dispatch",theme:{primary:"#111827",accent:"#1d4ed8",surface:"#ffffff",muted:"#6b7280",container:"#f8fafc",border:"#f1f5f9",divider:"#f1f5f9",messageBorder:"#f1f5f9",inputBackground:"#ffffff",callToAction:"#000000",callToActionBackground:"#ffffff",sendButtonBackgroundColor:"#111827",sendButtonTextColor:"#ffffff",sendButtonBorderColor:"#60a5fa",closeButtonColor:"#6b7280",closeButtonBackgroundColor:"transparent",closeButtonBorderColor:"",clearChatIconColor:"#6b7280",clearChatBackgroundColor:"transparent",clearChatBorderColor:"transparent",micIconColor:"#111827",micBackgroundColor:"transparent",micBorderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",inputFontFamily:"sans-serif",inputFontWeight:"400",radiusSm:"0.75rem",radiusMd:"1rem",radiusLg:"1.5rem",launcherRadius:"9999px",buttonRadius:"9999px"},launcher:{enabled:!0,title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",position:"bottom-right",width:"min(400px, calc(100vw - 24px))",autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:"#000000",callToActionIconBackgroundColor:"#ffffff",closeButtonColor:"#6b7280",closeButtonBackgroundColor:"transparent",clearChat:{iconColor:"#6b7280",backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",backgroundColor:"#111827",textColor:"#ffffff",borderColor:"#60a5fa",useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:"#111827",backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},debug:!1};function An(n){var e,o,t,r,s,i,l,u,h,d,T,f,b,w,_,j,m;return n?{...Pe,...n,theme:{...Pe.theme,...n.theme},launcher:{...Pe.launcher,...n.launcher,clearChat:{...(e=Pe.launcher)==null?void 0:e.clearChat,...(o=n.launcher)==null?void 0:o.clearChat}},copy:{...Pe.copy,...n.copy},sendButton:{...Pe.sendButton,...n.sendButton},statusIndicator:{...Pe.statusIndicator,...n.statusIndicator},voiceRecognition:{...Pe.voiceRecognition,...n.voiceRecognition},features:{...Pe.features,...n.features},suggestionChips:(t=n.suggestionChips)!=null?t:Pe.suggestionChips,suggestionChipsConfig:{...Pe.suggestionChipsConfig,...n.suggestionChipsConfig},layout:{...Pe.layout,...n.layout,header:{...(r=Pe.layout)==null?void 0:r.header,...(s=n.layout)==null?void 0:s.header},messages:{...(i=Pe.layout)==null?void 0:i.messages,...(l=n.layout)==null?void 0:l.messages,avatar:{...(h=(u=Pe.layout)==null?void 0:u.messages)==null?void 0:h.avatar,...(T=(d=n.layout)==null?void 0:d.messages)==null?void 0:T.avatar},timestamp:{...(b=(f=Pe.layout)==null?void 0:f.messages)==null?void 0:b.timestamp,...(_=(w=n.layout)==null?void 0:w.messages)==null?void 0:_.timestamp}},slots:{...(j=Pe.layout)==null?void 0:j.slots,...(m=n.layout)==null?void 0:m.slots}}}:Pe}var Co=()=>{let n=new Map,e=(r,s)=>(n.has(r)||n.set(r,new Set),n.get(r).add(s),()=>o(r,s)),o=(r,s)=>{var i;(i=n.get(r))==null||i.delete(s)};return{on:e,off:o,emit:(r,s)=>{var i;(i=n.get(r))==null||i.forEach(l=>{try{l(s)}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",u)}})}}};var Go=n=>{let e=n.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:n},Zo=n=>{let e=n.trim(),o=e.indexOf("{");if(o===-1)return null;let t=0;for(let r=o;r<e.length;r+=1){let s=e[r];if(s==="{"&&(t+=1),s==="}"&&(t-=1,t===0))return e.slice(o,r+1)}return null},ln=({text:n})=>{if(!n||!n.includes("{"))return null;try{let e=Go(n),o=Zo(e);if(!o)return null;let t=JSON.parse(o);if(!t||typeof t!="object"||!t.action)return null;let{action:r,...s}=t;return{type:String(r),payload:s,raw:t}}catch{return null}},Kn=n=>typeof n=="string"?n:n==null?"":String(n),qt={message:n=>n.type!=="message"?void 0:{handled:!0,displayText:Kn(n.payload.text)},messageAndClick:(n,e)=>{var r;if(n.type!=="message_and_click")return;let o=n.payload,t=Kn(o.element);if(t&&((r=e.document)!=null&&r.querySelector)){let s=e.document.querySelector(t);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",t)}return{handled:!0,displayText:Kn(o.text)}}},So=n=>Array.isArray(n)?n.map(e=>String(e)):[],dn=n=>{let e=new Set(So(n.getMetadata().processedActionMessageIds)),o=()=>{e=new Set(So(n.getMetadata().processedActionMessageIds))},t=()=>{let s=Array.from(e);n.updateMetadata(i=>({...i,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||e.has(s.message.id))return null;let i=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!i&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let l=i?n.parsers.reduce((h,d)=>h||(d==null?void 0:d({text:i,message:s.message}))||null,null):null;if(!l)return null;e.add(s.message.id),t();let u={action:l,message:s.message};n.emit("action:detected",u);for(let h of n.handlers)if(h)try{let d=h(l,{message:s.message,metadata:n.getMetadata(),updateMetadata:n.updateMetadata,document:n.documentRef});if(!d)continue;if(d.handled){let T=d.persistMessage!==!1;return{text:d.displayText!==void 0?d.displayText:"",persist:T}}}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",d)}return{text:"",persist:!0}},syncFromMetadata:o}};var Qo=n=>{if(!n)return null;try{return JSON.parse(n)}catch(e){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",e),null}},er=n=>n.map(e=>({...e,streaming:!1})),Tn=(n="vanilla-agent-state")=>{let e=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let o=e();return o?Qo(o.getItem(n)):null},save:o=>{let t=e();if(t)try{let r={...o,messages:o.messages?er(o.messages):void 0};t.setItem(n,JSON.stringify(r))}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let o=e();if(o)try{o.removeItem(n)}catch(t){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",t)}}}};var Xn=class{constructor(){this.components=new Map}register(e,o){this.components.has(e)&&console.warn(`[ComponentRegistry] Component "${e}" is already registered. Overwriting.`),this.components.set(e,o)}unregister(e){this.components.delete(e)}get(e){return this.components.get(e)}has(e){return this.components.has(e)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(e){Object.entries(e).forEach(([o,t])=>{this.register(o,t)})}},Vt=new Xn;var Gt=require("partial-json");function tr(n){if(!n||typeof n!="object"||!("component"in n))return!1;let e=n.component;return typeof e=="string"&&e.length>0}function nr(n,e){if(!tr(n))return null;let o=n.props&&typeof n.props=="object"&&n.props!==null?n.props:{};return{component:n.component,props:o,raw:e}}function En(){let n=null,e=0;return{getExtractedDirective:()=>n,processChunk:o=>{let t=o.trim();if(!t.startsWith("{")&&!t.startsWith("["))return null;if(o.length<=e)return n;try{let r=(0,Gt.parse)(o,Gt.STR|Gt.OBJ),s=nr(r,o);s&&(n=s)}catch{}return e=o.length,n},reset:()=>{n=null,e=0}}}function Ao(n){return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"&&"props"in n&&typeof n.props=="object"}function Wn(n,e){let{config:o,message:t,onPropsUpdate:r}=e,s=Vt.get(n.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${n.component}" not found in registry. Falling back to default rendering.`),null;let i={message:t,config:o,updateProps:l=>{r&&r(l)}};try{return s(n.props,i)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${n.component}":`,l),null}}function To(){let n=En();return{processChunk:e=>n.processChunk(e),getDirective:()=>n.getExtractedDirective(),reset:()=>{n.reset()}}}function Mn(n){if(!n.rawContent)return!1;try{let e=JSON.parse(n.rawContent);return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"}catch{return!1}}function Ln(n){if(!n.rawContent)return null;try{let e=JSON.parse(n.rawContent);if(typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string")return{component:e.component,props:e.props&&typeof e.props=="object"&&e.props!==null?e.props:{},raw:n.rawContent}}catch{}return null}var Zt="vanilla-agent-chat-history",sr=30*1e3,Vn=n=>!n||typeof n!="object"?{}:{...n},Eo=n=>n.map(e=>({...e,streaming:!1})),Wo=(n,e)=>o=>{var s,i,l;let t=(s=o.text)!=null?s:"",r=(i=o.message.rawContent)!=null?i:null;if(e){let u=e.process({text:t,raw:r!=null?r:t,message:o.message,streaming:o.streaming});u!==null&&(t=u.text,u.persist||(o.message.__skipPersist=!0))}return n!=null&&n.postprocessMessage?n.postprocessMessage({...o,text:t,raw:(l=r!=null?r:o.text)!=null?l:""}):mn(t)},Bn=(n,e,o)=>{var ae,ue,He,pe,Oe,ot,gt,Qn,es,ts,ns,ss,os,rs;(!n.id||n.id!=="vanilla-agent-root")&&(n.id="vanilla-agent-root");let t=An(e);On(n,t);let r=an.getForInstance(t.plugins);t.components&&Vt.registerAll(t.components);let s=Co(),i=(ae=t.storageAdapter)!=null?ae:Tn(),l={},u=null;if(i!=null&&i.load)try{let a=i.load();if(a&&typeof a.then=="function")u=a;else if(a){let p=a;p.metadata&&(l=Vn(p.metadata)),(ue=p.messages)!=null&&ue.length&&(t={...t,initialMessages:p.messages})}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",a)}let h=()=>l,d=a=>{var E;l=(E=a({...l}))!=null?E:{},Ht()},T=t.actionParsers&&t.actionParsers.length?t.actionParsers:[ln],f=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[qt.message,qt.messageAndClick],b=dn({parsers:T,handlers:f,getMetadata:h,updateMetadata:d,emit:s.emit,documentRef:typeof document!="undefined"?document:null});b.syncFromMetadata();let w=(pe=(He=t.launcher)==null?void 0:He.enabled)!=null?pe:!0,_=(ot=(Oe=t.launcher)==null?void 0:Oe.autoExpand)!=null?ot:!1,j=_,m=w,C=w?_:!0,$=Wo(t,b),S=(Qn=(gt=t.features)==null?void 0:gt.showReasoning)!=null?Qn:!0,Y=(ts=(es=t.features)==null?void 0:es.showToolCalls)!=null?ts:!0,I=(ns=t.statusIndicator)!=null?ns:{},V=a=>{var p,E,N,k;return a==="idle"?(p=I.idleText)!=null?p:ze.idle:a==="connecting"?(E=I.connectingText)!=null?E:ze.connecting:a==="connected"?(N=I.connectedText)!=null?N:ze.connected:a==="error"?(k=I.errorText)!=null?k:ze.error:ze[a]},{wrapper:te,panel:A}=fo(t),ie=wo(t,w),{container:J,body:z,messagesWrapper:G,suggestions:le,textarea:se,sendButton:P,sendButtonWrapper:_e,composerForm:Ye,statusText:Qe,introTitle:vt,introSubtitle:bt,closeButton:D,iconHolder:he,headerTitle:ht,headerSubtitle:mt,header:Je,footer:rt}=ie,M=ie.micButton,Me=ie.micButtonWrapper,it=r.find(a=>a.renderHeader);if(it!=null&&it.renderHeader){let a=it.renderHeader({config:t,defaultRenderer:()=>{let p=Pt({config:t,showClose:w});return Jt(J,p,t),p.header},onClose:()=>nt(!1,"user")});if(a){let p=J.querySelector(".tvw-border-b-cw-divider");p&&(p.replaceWith(a),Je=a)}}let at=r.find(a=>a.renderComposer);if(at!=null&&at.renderComposer){let a=at.renderComposer({config:t,defaultRenderer:()=>Kt({config:t}).footer,onSubmit:p=>{F&&!F.isStreaming()&&F.sendMessage(p)},disabled:!1});a&&(rt.replaceWith(a),rt=a)}(()=>{var N,k;let a=(k=(N=t.layout)==null?void 0:N.slots)!=null?k:{},p=ee=>{switch(ee){case"body-top":return J.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6")||null;case"messages":return G;case"footer-top":return le;case"composer":return Ye;case"footer-bottom":return Qe;default:return null}},E=(ee,H)=>{var v;switch(ee){case"header-left":case"header-center":case"header-right":if(ee==="header-left")Je.insertBefore(H,Je.firstChild);else if(ee==="header-right")Je.appendChild(H);else{let O=Je.querySelector(".tvw-flex-col");O?(v=O.parentNode)==null||v.insertBefore(H,O.nextSibling):Je.appendChild(H)}break;case"body-top":let U=z.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6");U?U.replaceWith(H):z.insertBefore(H,z.firstChild);break;case"body-bottom":z.appendChild(H);break;case"footer-top":le.replaceWith(H);break;case"footer-bottom":Qe.replaceWith(H);break;default:break}};for(let[ee,H]of Object.entries(a))if(H)try{let v=H({config:t,defaultContent:()=>p(ee)});v&&E(ee,v)}catch(v){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${ee}":`,v)}})(),A.appendChild(J),n.appendChild(te);let ft=()=>{var q,$e,xe,re,Ne,dt,oe,ct,kt,Rt,Wt,Ft;let a=($e=(q=t.launcher)==null?void 0:q.sidebarMode)!=null?$e:!1,p=a||((re=(xe=t.launcher)==null?void 0:xe.fullHeight)!=null?re:!1),E=(Ne=t.theme)!=null?Ne:{},N=(oe=(dt=t.launcher)==null?void 0:dt.position)!=null?oe:"bottom-left",k=N==="bottom-left"||N==="top-left",ee=a?"none":"1px solid var(--tvw-cw-border)",H=a?k?"2px 0 12px rgba(0, 0, 0, 0.08)":"-2px 0 12px rgba(0, 0, 0, 0.08)":"0 25px 50px -12px rgba(0, 0, 0, 0.25)",v=a?"0":"16px",U=(ct=E.panelBorder)!=null?ct:ee,O=(kt=E.panelShadow)!=null?kt:H,R=(Rt=E.panelBorderRadius)!=null?Rt:v;if(J.style.border=U,J.style.boxShadow=O,J.style.borderRadius=R,p&&(n.style.display="flex",n.style.flexDirection="column",n.style.height="100%",n.style.minHeight="0",te.style.display="flex",te.style.flexDirection="column",te.style.flex="1 1 0%",te.style.minHeight="0",te.style.maxHeight="100%",te.style.height="100%",te.style.overflow="hidden",A.style.display="flex",A.style.flexDirection="column",A.style.flex="1 1 0%",A.style.minHeight="0",A.style.maxHeight="100%",A.style.height="100%",A.style.overflow="hidden",J.style.display="flex",J.style.flexDirection="column",J.style.flex="1 1 0%",J.style.minHeight="0",J.style.maxHeight="100%",J.style.overflow="hidden",z.style.flex="1 1 0%",z.style.minHeight="0",z.style.overflowY="auto",rt.style.flexShrink="0"),a){let jt=(Ft=(Wt=t.launcher)==null?void 0:Wt.sidebarWidth)!=null?Ft:"420px";te.classList.remove("tvw-bottom-6","tvw-right-6","tvw-left-6","tvw-top-6","tvw-bottom-4","tvw-right-4","tvw-left-4","tvw-top-4"),te.style.cssText=`
|
|
16
17
|
position: fixed !important;
|
|
17
18
|
top: 0 !important;
|
|
18
19
|
bottom: 0 !important;
|
|
@@ -23,8 +24,8 @@
|
|
|
23
24
|
padding: 0 !important;
|
|
24
25
|
display: flex !important;
|
|
25
26
|
flex-direction: column !important;
|
|
26
|
-
${
|
|
27
|
-
`,
|
|
27
|
+
${k?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
|
|
28
|
+
`,A.style.cssText=`
|
|
28
29
|
position: relative !important;
|
|
29
30
|
display: flex !important;
|
|
30
31
|
flex-direction: column !important;
|
|
@@ -35,7 +36,7 @@
|
|
|
35
36
|
min-height: 0 !important;
|
|
36
37
|
margin: 0 !important;
|
|
37
38
|
padding: 0 !important;
|
|
38
|
-
`,
|
|
39
|
+
`,A.style.setProperty("width","100%","important"),A.style.setProperty("max-width","100%","important"),J.style.cssText=`
|
|
39
40
|
display: flex !important;
|
|
40
41
|
flex-direction: column !important;
|
|
41
42
|
flex: 1 1 0% !important;
|
|
@@ -44,18 +45,18 @@
|
|
|
44
45
|
min-height: 0 !important;
|
|
45
46
|
max-height: 100% !important;
|
|
46
47
|
overflow: hidden !important;
|
|
47
|
-
border-radius: ${
|
|
48
|
-
border: ${
|
|
49
|
-
box-shadow: ${
|
|
48
|
+
border-radius: ${R} !important;
|
|
49
|
+
border: ${U} !important;
|
|
50
|
+
box-shadow: ${O} !important;
|
|
50
51
|
`,rt.style.cssText=`
|
|
51
52
|
flex-shrink: 0 !important;
|
|
52
53
|
border-top: none !important;
|
|
53
54
|
padding: 8px 16px 12px 16px !important;
|
|
54
|
-
`}};ht();let Pe=[],tt=yo(ue),Ue=null,N,lt=!1,Xe=!0,Ee=0,Fe=0,J=null,ye=!1,Re=0,ze=!1,nt=125,vt=2e3,Mt=5,ct=50,bt=new Map,ie={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1},Ot=(ns=(ts=t.voiceRecognition)==null?void 0:ts.autoResume)!=null?ns:!1,Lt=a=>{s.emit("voice:state",{active:ie.active,source:a,timestamp:Date.now()})},he=()=>{d(a=>({...a,voiceState:{active:ie.active,timestamp:Date.now(),manuallyDeactivated:ie.manuallyDeactivated}}))},mt=()=>{var P,H;if(((P=t.voiceRecognition)==null?void 0:P.enabled)===!1)return;let a=Kn(l.voiceState),p=!!a.active,M=Number((H=a.timestamp)!=null?H:0);ie.manuallyDeactivated=!!a.manuallyDeactivated,p&&Date.now()-M<tr&&setTimeout(()=>{ie.active||(ie.manuallyDeactivated=!1,Me("restore"))},1e3)},xt=()=>N?Ao(N.getMessages()).filter(a=>!a.__skipPersist):[];function Bt(a){if(!(i!=null&&i.save))return;let M={messages:a?Ao(a):N?xt():[],metadata:l};try{let P=i.save(M);P instanceof Promise&&P.catch(H=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",H)})}catch(P){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",P)}}let ft=(a=!1)=>{if(!Xe)return;let p=Date.now();ye&&p<Re&&!a||(ye&&p>=Re&&(ye=!1),!(!a&&!lt)&&(p-Fe<nt||(Fe=p,J&&cancelAnimationFrame(J),J=requestAnimationFrame(()=>{ye||!Xe||(ze=!0,U.scrollTop=U.scrollHeight,Ee=U.scrollTop,requestAnimationFrame(()=>{ze=!1}),J=null)}))))},At=null,cn=()=>te.querySelector("#vanilla-agent-scroll-container")||U,un=(a,p=500)=>{let M=a.scrollTop,P=a.clientHeight,H=a.scrollHeight,b=H-M;if(M+P>=H-2||Math.abs(b)<5)return;At!==null&&(cancelAnimationFrame(At),At=null);let K=performance.now(),ae=k=>1-Math.pow(1-k,3),_=k=>{let q=a.scrollHeight;q!==H&&(H=q,b=H-M);let ee=k-K,me=Math.min(ee/p,1),_e=ae(me),He=M+b*_e;a.scrollTop=He,me<1?At=requestAnimationFrame(_):(a.scrollTop=a.scrollHeight,At=null)};At=requestAnimationFrame(_)},pn=a=>{let p=new Map;a.forEach(M=>{let P=bt.get(M.id);p.set(M.id,{streaming:M.streaming,role:M.role}),!P&&M.role==="assistant"&&s.emit("assistant:message",M),M.role==="assistant"&&(P!=null&&P.streaming)&&M.streaming===!1&&s.emit("assistant:complete",M)}),bt.clear(),p.forEach((M,P)=>{bt.set(P,M)})},Nt=(a,p,M)=>{a.innerHTML="";let P=document.createDocumentFragment();p.forEach(b=>{var k,q;let x=null,K=r.find(ee=>!!(b.variant==="reasoning"&&ee.renderReasoning||b.variant==="tool"&&ee.renderToolCall||!b.variant&&ee.renderMessage)),ae=(k=t.layout)==null?void 0:k.messages;if(K)if(b.variant==="reasoning"&&b.reasoning&&K.renderReasoning){if(!A)return;x=K.renderReasoning({message:b,defaultRenderer:()=>jn(b),config:t})}else if(b.variant==="tool"&&b.toolCall&&K.renderToolCall){if(!z)return;x=K.renderToolCall({message:b,defaultRenderer:()=>qn(b,t),config:t})}else K.renderMessage&&(x=K.renderMessage({message:b,defaultRenderer:()=>{let ee=Xt(b,M,ae);return b.role!=="user"&&Un(ee,b,t,N),ee},config:t}));if(!x&&b.role==="assistant"&&!b.variant&&t.enableComponentStreaming!==!1&&Wn(b)){let me=Mn(b);if(me){let _e=En(me,{config:t,message:b,transform:M});if(_e){let He=document.createElement("div");if(He.className=["vanilla-message-bubble","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-p-4"].join(" "),He.setAttribute("data-message-id",b.id),b.content&&b.content.trim()){let ot=document.createElement("div");ot.className="tvw-mb-3 tvw-text-sm tvw-leading-relaxed",ot.innerHTML=M({text:b.content,message:b,streaming:!!b.streaming,raw:b.rawContent}),He.appendChild(ot)}He.appendChild(_e),x=He}}}if(!x)if(b.variant==="reasoning"&&b.reasoning){if(!A)return;x=jn(b)}else if(b.variant==="tool"&&b.toolCall){if(!z)return;x=qn(b,t)}else{let ee=(q=t.layout)==null?void 0:q.messages;ee!=null&&ee.renderUserMessage&&b.role==="user"?x=ee.renderUserMessage({message:b,config:t,streaming:!!b.streaming}):ee!=null&&ee.renderAssistantMessage&&b.role==="assistant"?x=ee.renderAssistantMessage({message:b,config:t,streaming:!!b.streaming}):x=Xt(b,M,ee),b.role!=="user"&&x&&Un(x,b,t,N)}let _=document.createElement("div");_.className="tvw-flex",b.role==="user"&&_.classList.add("tvw-justify-end"),_.appendChild(x),P.appendChild(_)});let H=p.some(b=>b.role==="assistant"&&b.streaming);if(lt&&p.some(b=>b.role==="user")&&!H){let b=rn(),x=document.createElement("div");x.className=["tvw-max-w-[85%]","tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3"].join(" "),x.appendChild(b);let K=document.createElement("div");K.className="tvw-flex",K.appendChild(x),P.appendChild(K)}a.appendChild(P),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let b=cn();un(b)})})},Ft=()=>{y&&(S?(te.classList.remove("tvw-pointer-events-none","tvw-opacity-0"),T.classList.remove("tvw-scale-95","tvw-opacity-0"),T.classList.add("tvw-scale-100","tvw-opacity-100"),w?w.element.style.display="none":g&&(g.style.display="none")):(te.classList.add("tvw-pointer-events-none","tvw-opacity-0"),T.classList.remove("tvw-scale-100","tvw-opacity-100"),T.classList.add("tvw-scale-95","tvw-opacity-0"),w?w.element.style.display="":g&&(g.style.display="")))},st=(a,p="user")=>{if(!y||S===a)return;let M=S;S=a,Ft(),S&&(D(),ft(!0));let P={open:S,source:p,timestamp:Date.now()};S&&!M?s.emit("widget:opened",P):!S&&M&&s.emit("widget:closed",P),s.emit("widget:state",{open:S,launcherEnabled:y,voiceActive:ie.active,streaming:N.isStreaming()})},Ut=a=>{se.disabled=a,$.disabled=a,B&&(B.disabled=a),tt.buttons.forEach(p=>{p.disabled=a})},Qt=()=>{var H,b,x,K,ae,_,k,q,ee,me,_e,He,ot,pe;wt.textContent=(b=(H=t.copy)==null?void 0:H.welcomeTitle)!=null?b:"Hello \u{1F44B}",yt.textContent=(K=(x=t.copy)==null?void 0:x.welcomeSubtitle)!=null?K:"Ask anything about your account or products.",se.placeholder=(_=(ae=t.copy)==null?void 0:ae.inputPlaceholder)!=null?_:"How can I help...",((q=(k=t.sendButton)==null?void 0:k.useIcon)!=null?q:!1)||($.textContent=(me=(ee=t.copy)==null?void 0:ee.sendButtonLabel)!=null?me:"Send");let p=(He=(_e=t.theme)==null?void 0:_e.inputFontFamily)!=null?He:"sans-serif",M=(pe=(ot=t.theme)==null?void 0:ot.inputFontWeight)!=null?pe:"400",P=Tt=>{switch(Tt){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};se.style.fontFamily=P(p),se.style.fontWeight=M};N=new Yt(t,{onMessagesChanged(a){Nt(ne,a,I),N&&(a.some(P=>P.role==="user")?tt.render([],N,se,a):tt.render(t.suggestionChips,N,se,a,t.suggestionChipsConfig)),ft(!lt),pn(a);let p=[...a].reverse().find(M=>M.role==="user");ie.lastUserMessageWasVoice=!!(p!=null&&p.viaVoice),Bt(a)},onStatusChanged(a){var P;let p=(P=t.statusIndicator)!=null?P:{},M=H=>{var b,x,K,ae;return H==="idle"?(b=p.idleText)!=null?b:Ye.idle:H==="connecting"?(x=p.connectingText)!=null?x:Ye.connecting:H==="connected"?(K=p.connectedText)!=null?K:Ye.connected:H==="error"?(ae=p.errorText)!=null?ae:Ye.error:Ye[H]};et.textContent=M(a)},onStreamingChanged(a){lt=a,Ut(a),N&&Nt(ne,N.getMessages(),I),a||ft(!0)}}),u&&u.then(a=>{var p;a&&(a.metadata&&(l=Kn(a.metadata),C.syncFromMetadata()),(p=a.messages)!=null&&p.length&&N.hydrateMessages(a.messages))}).catch(a=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",a)});let en=a=>{a.preventDefault();let p=se.value.trim();p&&(se.value="",N.sendMessage(p))},tn=a=>{a.key==="Enter"&&!a.shiftKey&&(a.preventDefault(),$.click())},Ve=null,v=!1,G=null,Q=null,We=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Me=(a="user")=>{var b,x,K,ae;if(v||N.isStreaming())return;let p=We();if(!p)return;Ve=new p;let P=(x=((b=t.voiceRecognition)!=null?b:{}).pauseDuration)!=null?x:2e3;Ve.continuous=!0,Ve.interimResults=!0,Ve.lang="en-US";let H=se.value;Ve.onresult=_=>{let k="",q="";for(let me=0;me<_.results.length;me++){let _e=_.results[me],He=_e[0].transcript;_e.isFinal?k+=He+" ":q=He}let ee=H+k+q;se.value=ee,G&&clearTimeout(G),(k||q)&&(G=window.setTimeout(()=>{let me=se.value.trim();me&&Ve&&v&&(ve(),se.value="",N.sendMessage(me,{viaVoice:!0}))},P))},Ve.onerror=_=>{_.error!=="no-speech"&&ve()},Ve.onend=()=>{if(v){let _=se.value.trim();_&&_!==H.trim()&&(se.value="",N.sendMessage(_,{viaVoice:!0})),ve()}};try{if(Ve.start(),v=!0,ie.active=!0,a!=="system"&&(ie.manuallyDeactivated=!1),Lt(a),he(),B){Q={backgroundColor:B.style.backgroundColor,color:B.style.color,borderColor:B.style.borderColor};let _=(K=t.voiceRecognition)!=null?K:{},k=(ae=_.recordingBackgroundColor)!=null?ae:"#ef4444",q=_.recordingIconColor,ee=_.recordingBorderColor;if(B.classList.add("tvw-voice-recording"),B.style.backgroundColor=k,q){B.style.color=q;let me=B.querySelector("svg");me&&me.setAttribute("stroke",q)}ee&&(B.style.borderColor=ee),B.setAttribute("aria-label","Stop voice recognition")}}catch{ve("system")}},ve=(a="user")=>{if(v){if(v=!1,G&&(clearTimeout(G),G=null),Ve){try{Ve.stop()}catch{}Ve=null}if(ie.active=!1,Lt(a),he(),B){if(B.classList.remove("tvw-voice-recording"),Q){B.style.backgroundColor=Q.backgroundColor,B.style.color=Q.color,B.style.borderColor=Q.borderColor;let p=B.querySelector("svg");p&&p.setAttribute("stroke",Q.color||"currentColor"),Q=null}B.setAttribute("aria-label","Start voice recognition")}}},Le=(a,p)=>{var He,ot,pe,Tt,kt,Rt,Et;if(!(typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined")))return null;let P=c("div","tvw-send-button-wrapper"),H=c("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer");H.type="button",H.setAttribute("aria-label","Start voice recognition");let b=(He=a==null?void 0:a.iconName)!=null?He:"mic",x=(ot=p==null?void 0:p.size)!=null?ot:"40px",K=(pe=a==null?void 0:a.iconSize)!=null?pe:x,ae=parseFloat(K)||24,_=(Tt=a==null?void 0:a.backgroundColor)!=null?Tt:p==null?void 0:p.backgroundColor,k=(kt=a==null?void 0:a.iconColor)!=null?kt:p==null?void 0:p.textColor;H.style.width=K,H.style.height=K,H.style.minWidth=K,H.style.minHeight=K,H.style.fontSize="18px",H.style.lineHeight="1";let q=k||"currentColor",ee=ge(b,ae,q,1.5);ee?(H.appendChild(ee),H.style.color=q):(H.textContent="\u{1F3A4}",H.style.color=q),_?H.style.backgroundColor=_:H.classList.add("tvw-bg-cw-primary"),k?H.style.color=k:!k&&!(p!=null&&p.textColor)&&H.classList.add("tvw-text-white"),a!=null&&a.borderWidth&&(H.style.borderWidth=a.borderWidth,H.style.borderStyle="solid"),a!=null&&a.borderColor&&(H.style.borderColor=a.borderColor),a!=null&&a.paddingX&&(H.style.paddingLeft=a.paddingX,H.style.paddingRight=a.paddingX),a!=null&&a.paddingY&&(H.style.paddingTop=a.paddingY,H.style.paddingBottom=a.paddingY),P.appendChild(H);let me=(Rt=a==null?void 0:a.tooltipText)!=null?Rt:"Start voice recognition";if(((Et=a==null?void 0:a.showTooltip)!=null?Et:!1)&&me){let Dt=c("div","tvw-send-button-tooltip");Dt.textContent=me,P.appendChild(Dt)}return{micButton:H,micButtonWrapper:P}},W=()=>{if(v){let a=se.value.trim();ie.manuallyDeactivated=!0,he(),ve("user"),a&&(se.value="",N.sendMessage(a))}else ie.manuallyDeactivated=!1,he(),Me("user")};B&&(B.addEventListener("click",W),Pe.push(()=>{ve("system"),B&&B.removeEventListener("click",W)}));let ut=s.on("assistant:complete",()=>{Ot&&(ie.active||ie.manuallyDeactivated||Ot==="assistant"&&!ie.lastUserMessageWasVoice||setTimeout(()=>{!ie.active&&!ie.manuallyDeactivated&&Me("auto")},600))});Pe.push(ut);let X=()=>{st(!S,"user")},w=null,g=null;if(y){let a=r.find(p=>p.renderLauncher);if(a!=null&&a.renderLauncher){let p=a.renderLauncher({config:t,defaultRenderer:()=>on(t,X).element,onToggle:X});p&&(g=p)}g||(w=on(t,X))}w?n.appendChild(w.element):g&&n.appendChild(g),Ft(),tt.render(t.suggestionChips,N,se,void 0,t.suggestionChipsConfig),Qt(),Ut(N.isStreaming()),ft(!0),mt();let D=()=>{var M,P,H,b,x,K;let a=(P=(M=t.launcher)==null?void 0:M.sidebarMode)!=null?P:!1,p=a||((b=(H=t.launcher)==null?void 0:H.fullHeight)!=null?b:!1);if(!y){T.style.height="",T.style.width="";return}if(!a){let ae=(K=(x=t==null?void 0:t.launcher)==null?void 0:x.width)!=null?K:t==null?void 0:t.launcherWidth,_=ae!=null?ae:"min(400px, calc(100vw - 24px))";T.style.width=_,T.style.maxWidth=_}if(!p){let ae=window.innerHeight,k=Math.max(200,ae-64),q=Math.min(640,k);T.style.height=`${q}px`}};D(),window.addEventListener("resize",D),Pe.push(()=>window.removeEventListener("resize",D)),Ee=U.scrollTop;let be=()=>{let a=U.scrollTop,p=U.scrollHeight,M=U.clientHeight,P=p-a-M,H=Math.abs(a-Ee);if(Ee=a,!ze&&!(H<=Mt)){if(!Xe&&P<ct){ye=!1,Xe=!0;return}Xe&&P>ct&&(ye=!0,Re=Date.now()+vt,Xe=!1)}};U.addEventListener("scroll",be,{passive:!0}),Pe.push(()=>U.removeEventListener("scroll",be)),Pe.push(()=>{J&&cancelAnimationFrame(J)});let xe=()=>{O&&(Ue&&(O.removeEventListener("click",Ue),Ue=null),y?(O.style.display="",Ue=()=>{S=!1,Ft()},O.addEventListener("click",Ue)):O.style.display="none")};xe(),(()=>{let{clearChatButton:a}=re;a&&a.addEventListener("click",()=>{N.clearMessages();try{localStorage.removeItem(Zt),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Zt}`)}catch(M){console.error("[AgentWidget] Failed to clear default localStorage:",M)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==Zt)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.clearChatHistoryStorageKey}`)}catch(M){console.error("[AgentWidget] Failed to clear custom localStorage:",M)}let p=new CustomEvent("vanilla-agent:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(p),i!=null&&i.clear)try{let M=i.clear();M instanceof Promise&&M.catch(P=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",P)})}catch(M){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",M)}l={},C.syncFromMetadata()})})(),Je.addEventListener("submit",en),se.addEventListener("keydown",tn),Pe.push(()=>{Je.removeEventListener("submit",en),se.removeEventListener("keydown",tn)}),Pe.push(()=>{N.cancel()}),w?Pe.push(()=>{w==null||w.destroy()}):g&&Pe.push(()=>{g==null||g.remove()});let Ce={update(a){var os,rs,is,as,ls,ds,cs,us,ps,gs,hs,ms,fs,ws,ys,vs,bs,xs,Cs,Ss,As,Ts,Es,Ws,Ms,Ls,Bs,Hs,ks,Rs,Is,$s,Ps,Os,Ns,Fs,Ds,js,_s,qs,Us,zs,Ys,Js,Ks,Xs,Vs,Gs,Zs,Qs,eo,to,no,so,oo,ro,io;let p=t.toolCall;t={...t,...a},$n(n,t),ht();let M=an.getForInstance(t.plugins);if(r.length=0,r.push(...M),y=(rs=(os=t.launcher)==null?void 0:os.enabled)!=null?rs:!0,j=(as=(is=t.launcher)==null?void 0:is.autoExpand)!=null?as:!1,A=(ds=(ls=t.features)==null?void 0:ls.showReasoning)!=null?ds:!0,z=(us=(cs=t.features)==null?void 0:cs.showToolCalls)!=null?us:!0,((ps=t.launcher)==null?void 0:ps.enabled)===!1&&w&&(w.destroy(),w=null),((gs=t.launcher)==null?void 0:gs.enabled)===!1&&g&&(g.remove(),g=null),((hs=t.launcher)==null?void 0:hs.enabled)!==!1&&!w&&!g){let L=r.find(ce=>ce.renderLauncher);if(L!=null&&L.renderLauncher){let ce=L.renderLauncher({config:t,defaultRenderer:()=>on(t,X).element,onToggle:X});ce&&(g=ce,n.appendChild(g))}g||(w=on(t,X),n.appendChild(w.element))}w&&w.update(t),pt&&((ms=t.launcher)==null?void 0:ms.title)!==void 0&&(pt.textContent=t.launcher.title),gt&&((fs=t.launcher)==null?void 0:fs.subtitle)!==void 0&&(gt.textContent=t.launcher.subtitle),y!==m?y?st(j,"auto"):(S=!0,Ft()):j!==F&&st(j,"auto"),F=j,m=y,D(),xe(),JSON.stringify(a.toolCall)!==JSON.stringify(p)&&N&&Nt(ne,N.getMessages(),I);let x=(ws=t.launcher)!=null?ws:{},K=(ys=x.headerIconHidden)!=null?ys:!1,ae=x.headerIconName,_=(vs=x.headerIconSize)!=null?vs:"48px";if(de){let L=Y.querySelector(".tvw-border-b-cw-divider"),ce=L==null?void 0:L.querySelector(".tvw-flex-col");if(K)de.style.display="none",L&&ce&&!L.contains(ce)&&L.insertBefore(ce,L.firstChild);else{if(de.style.display="",de.style.height=_,de.style.width=_,L&&ce&&(L.contains(de)?de.nextSibling!==ce&&(de.remove(),L.insertBefore(de,ce)):L.insertBefore(de,ce)),ae){let Te=parseFloat(_)||24,fe=ge(ae,Te*.6,"#ffffff",2);fe?de.replaceChildren(fe):de.textContent=(bs=x.agentIconText)!=null?bs:"\u{1F4AC}"}else if(x.iconUrl){let Te=de.querySelector("img");if(Te)Te.src=x.iconUrl,Te.style.height=_,Te.style.width=_;else{let fe=document.createElement("img");fe.src=x.iconUrl,fe.alt="",fe.className="tvw-rounded-xl tvw-object-cover",fe.style.height=_,fe.style.width=_,de.replaceChildren(fe)}}else{let Te=de.querySelector("svg"),fe=de.querySelector("img");(Te||fe)&&de.replaceChildren(),de.textContent=(xs=x.agentIconText)!=null?xs:"\u{1F4AC}"}let Z=de.querySelector("img");Z&&(Z.style.height=_,Z.style.width=_)}}if(O){let L=(Cs=x.closeButtonSize)!=null?Cs:"32px",ce=(Ss=x.closeButtonPlacement)!=null?Ss:"inline";O.style.height=L,O.style.width=L;let{closeButtonWrapper:Z}=re,Te=ce==="top-right",fe=Z==null?void 0:Z.classList.contains("tvw-absolute");if(Z&&Te!==fe)if(Z.remove(),Te)Z.className="tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50",Y.style.position="relative",Y.appendChild(Z);else{let le=(Ts=(As=x.clearChat)==null?void 0:As.placement)!=null?Ts:"inline",Ze=(Ws=(Es=x.clearChat)==null?void 0:Es.enabled)!=null?Ws:!0;Z.className=Ze&&le==="inline"?"":"tvw-ml-auto";let Qe=Y.querySelector(".tvw-border-b-cw-divider");Qe&&Qe.appendChild(Z)}if(x.closeButtonColor?(O.style.color=x.closeButtonColor,O.classList.remove("tvw-text-cw-muted")):(O.style.color="",O.classList.add("tvw-text-cw-muted")),x.closeButtonBackgroundColor?(O.style.backgroundColor=x.closeButtonBackgroundColor,O.classList.remove("hover:tvw-bg-gray-100")):(O.style.backgroundColor="",O.classList.add("hover:tvw-bg-gray-100")),x.closeButtonBorderWidth||x.closeButtonBorderColor){let le=x.closeButtonBorderWidth||"0px",Ze=x.closeButtonBorderColor||"transparent";O.style.border=`${le} solid ${Ze}`,O.classList.remove("tvw-border-none")}else O.style.border="",O.classList.add("tvw-border-none");x.closeButtonBorderRadius?(O.style.borderRadius=x.closeButtonBorderRadius,O.classList.remove("tvw-rounded-full")):(O.style.borderRadius="",O.classList.add("tvw-rounded-full")),x.closeButtonPaddingX?(O.style.paddingLeft=x.closeButtonPaddingX,O.style.paddingRight=x.closeButtonPaddingX):(O.style.paddingLeft="",O.style.paddingRight=""),x.closeButtonPaddingY?(O.style.paddingTop=x.closeButtonPaddingY,O.style.paddingBottom=x.closeButtonPaddingY):(O.style.paddingTop="",O.style.paddingBottom="");let Ge=(Ms=x.closeButtonIconName)!=null?Ms:"x",Ne=(Ls=x.closeButtonIconText)!=null?Ls:"\xD7";O.innerHTML="";let dt=ge(Ge,"20px",x.closeButtonColor||"",2);dt?O.appendChild(dt):O.textContent=Ne;let It=(Bs=x.closeButtonTooltipText)!=null?Bs:"Close chat",Ae=(Hs=x.closeButtonShowTooltip)!=null?Hs:!0;if(O.setAttribute("aria-label",It),Z&&(Z._cleanupTooltip&&(Z._cleanupTooltip(),delete Z._cleanupTooltip),Ae&&It)){let le=null,Ze=()=>{if(le||!O)return;le=c("div","tvw-clear-chat-tooltip"),le.textContent=It;let zt=c("div");zt.className="tvw-clear-chat-tooltip-arrow",le.appendChild(zt);let Hn=O.getBoundingClientRect();le.style.position="fixed",le.style.left=`${Hn.left+Hn.width/2}px`,le.style.top=`${Hn.top-8}px`,le.style.transform="translate(-50%, -100%)",document.body.appendChild(le)},Qe=()=>{le&&le.parentNode&&(le.parentNode.removeChild(le),le=null)};Z.addEventListener("mouseenter",Ze),Z.addEventListener("mouseleave",Qe),O.addEventListener("focus",Ze),O.addEventListener("blur",Qe),Z._cleanupTooltip=()=>{Qe(),Z&&(Z.removeEventListener("mouseenter",Ze),Z.removeEventListener("mouseleave",Qe)),O&&(O.removeEventListener("focus",Ze),O.removeEventListener("blur",Qe))}}}let{clearChatButton:k,clearChatButtonWrapper:q}=re;if(k){let L=(ks=x.clearChat)!=null?ks:{},ce=(Rs=L.enabled)!=null?Rs:!0,Z=(Is=L.placement)!=null?Is:"inline";if(q){q.style.display=ce?"":"none";let Te=Z==="top-right",fe=q.classList.contains("tvw-absolute");if(Te!==fe&&ce){if(q.remove(),Te)q.className="tvw-absolute tvw-top-4 tvw-z-50",q.style.right="48px",Y.style.position="relative",Y.appendChild(q);else{q.className="tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper",q.style.right="";let Ne=Y.querySelector(".tvw-border-b-cw-divider"),dt=re.closeButtonWrapper;Ne&&dt&&dt.parentElement===Ne?Ne.insertBefore(q,dt):Ne&&Ne.appendChild(q)}let Ge=re.closeButtonWrapper;Ge&&!Ge.classList.contains("tvw-absolute")&&(Te?Ge.classList.add("tvw-ml-auto"):Ge.classList.remove("tvw-ml-auto"))}}if(ce){let Te=($s=L.size)!=null?$s:"32px";k.style.height=Te,k.style.width=Te;let fe=(Ps=L.iconName)!=null?Ps:"refresh-cw",Ge=(Os=L.iconColor)!=null?Os:"";k.innerHTML="";let Ne=ge(fe,"20px",Ge||"",2);if(Ne&&k.appendChild(Ne),Ge?(k.style.color=Ge,k.classList.remove("tvw-text-cw-muted")):(k.style.color="",k.classList.add("tvw-text-cw-muted")),L.backgroundColor?(k.style.backgroundColor=L.backgroundColor,k.classList.remove("hover:tvw-bg-gray-100")):(k.style.backgroundColor="",k.classList.add("hover:tvw-bg-gray-100")),L.borderWidth||L.borderColor){let Ae=L.borderWidth||"0px",le=L.borderColor||"transparent";k.style.border=`${Ae} solid ${le}`,k.classList.remove("tvw-border-none")}else k.style.border="",k.classList.add("tvw-border-none");L.borderRadius?(k.style.borderRadius=L.borderRadius,k.classList.remove("tvw-rounded-full")):(k.style.borderRadius="",k.classList.add("tvw-rounded-full")),L.paddingX?(k.style.paddingLeft=L.paddingX,k.style.paddingRight=L.paddingX):(k.style.paddingLeft="",k.style.paddingRight=""),L.paddingY?(k.style.paddingTop=L.paddingY,k.style.paddingBottom=L.paddingY):(k.style.paddingTop="",k.style.paddingBottom="");let dt=(Ns=L.tooltipText)!=null?Ns:"Clear chat",It=(Fs=L.showTooltip)!=null?Fs:!0;if(k.setAttribute("aria-label",dt),q&&(q._cleanupTooltip&&(q._cleanupTooltip(),delete q._cleanupTooltip),It&&dt)){let Ae=null,le=()=>{if(Ae||!k)return;Ae=c("div","tvw-clear-chat-tooltip"),Ae.textContent=dt;let Qe=c("div");Qe.className="tvw-clear-chat-tooltip-arrow",Ae.appendChild(Qe);let zt=k.getBoundingClientRect();Ae.style.position="fixed",Ae.style.left=`${zt.left+zt.width/2}px`,Ae.style.top=`${zt.top-8}px`,Ae.style.transform="translate(-50%, -100%)",document.body.appendChild(Ae)},Ze=()=>{Ae&&Ae.parentNode&&(Ae.parentNode.removeChild(Ae),Ae=null)};q.addEventListener("mouseenter",le),q.addEventListener("mouseleave",Ze),k.addEventListener("focus",le),k.addEventListener("blur",Ze),q._cleanupTooltip=()=>{Ze(),q&&(q.removeEventListener("mouseenter",le),q.removeEventListener("mouseleave",Ze)),k&&(k.removeEventListener("focus",le),k.removeEventListener("blur",Ze))}}}}let ee=t.actionParsers&&t.actionParsers.length?t.actionParsers:[ln],me=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[qt.message,qt.messageAndClick];C=dn({parsers:ee,handlers:me,getMetadata:h,updateMetadata:d,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),I=To(t,C),N.updateConfig(t),Nt(ne,N.getMessages(),I),tt.render(t.suggestionChips,N,se,void 0,t.suggestionChipsConfig),Qt(),Ut(N.isStreaming());let _e=((Ds=t.voiceRecognition)==null?void 0:Ds.enabled)===!0,He=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),ot=_e&&He;if(Je.classList.remove("tvw-gap-1","tvw-gap-3"),Je.classList.add(ot?"tvw-gap-1":"tvw-gap-3"),_e&&He)if(!B||!ke){let L=Le(t.voiceRecognition,t.sendButton);L&&(B=L.micButton,ke=L.micButtonWrapper,Je.insertBefore(ke,qe),B.addEventListener("click",W),B.disabled=N.isStreaming())}else{let L=(js=t.voiceRecognition)!=null?js:{},ce=(_s=t.sendButton)!=null?_s:{},Z=(qs=L.iconName)!=null?qs:"mic",Te=(Us=ce.size)!=null?Us:"40px",fe=(zs=L.iconSize)!=null?zs:Te,Ge=parseFloat(fe)||24;B.style.width=fe,B.style.height=fe,B.style.minWidth=fe,B.style.minHeight=fe;let Ne=(Js=(Ys=L.iconColor)!=null?Ys:ce.textColor)!=null?Js:"currentColor";B.innerHTML="";let dt=ge(Z,Ge,Ne,2);dt?B.appendChild(dt):B.textContent="\u{1F3A4}";let It=(Ks=L.backgroundColor)!=null?Ks:ce.backgroundColor;It?(B.style.backgroundColor=It,B.classList.remove("tvw-bg-cw-primary")):(B.style.backgroundColor="",B.classList.add("tvw-bg-cw-primary")),Ne?(B.style.color=Ne,B.classList.remove("tvw-text-white")):!Ne&&!ce.textColor&&(B.style.color="",B.classList.add("tvw-text-white")),L.borderWidth?(B.style.borderWidth=L.borderWidth,B.style.borderStyle="solid"):(B.style.borderWidth="",B.style.borderStyle=""),L.borderColor?B.style.borderColor=L.borderColor:B.style.borderColor="",L.paddingX?(B.style.paddingLeft=L.paddingX,B.style.paddingRight=L.paddingX):(B.style.paddingLeft="",B.style.paddingRight=""),L.paddingY?(B.style.paddingTop=L.paddingY,B.style.paddingBottom=L.paddingY):(B.style.paddingTop="",B.style.paddingBottom="");let Ae=ke==null?void 0:ke.querySelector(".tvw-send-button-tooltip"),le=(Xs=L.tooltipText)!=null?Xs:"Start voice recognition";if(((Vs=L.showTooltip)!=null?Vs:!1)&&le)if(Ae)Ae.textContent=le,Ae.style.display="";else{let Qe=document.createElement("div");Qe.className="tvw-send-button-tooltip",Qe.textContent=le,ke==null||ke.insertBefore(Qe,B)}else Ae&&(Ae.style.display="none");ke.style.display="",B.disabled=N.isStreaming()}else B&&ke&&(ke.style.display="none",v&&ve());let pe=(Gs=t.sendButton)!=null?Gs:{},Tt=(Zs=pe.useIcon)!=null?Zs:!1,kt=(Qs=pe.iconText)!=null?Qs:"\u2191",Rt=pe.iconName,Et=(eo=pe.tooltipText)!=null?eo:"Send message",Dt=(to=pe.showTooltip)!=null?to:!1,jt=(no=pe.size)!=null?no:"40px",gn=pe.backgroundColor,Ct=pe.textColor;if(Tt){if($.style.width=jt,$.style.height=jt,$.style.minWidth=jt,$.style.minHeight=jt,$.style.fontSize="18px",$.style.lineHeight="1",$.innerHTML="",Rt){let L=parseFloat(jt)||24,ce=Ct&&typeof Ct=="string"&&Ct.trim()?Ct.trim():"currentColor",Z=ge(Rt,L,ce,2);Z?($.appendChild(Z),$.style.color=ce):($.textContent=kt,Ct?$.style.color=Ct:$.classList.add("tvw-text-white"))}else $.textContent=kt,Ct?$.style.color=Ct:$.classList.add("tvw-text-white");$.className="tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer",gn?($.style.backgroundColor=gn,$.classList.remove("tvw-bg-cw-primary")):$.classList.add("tvw-bg-cw-primary")}else $.textContent=(oo=(so=t.copy)==null?void 0:so.sendButtonLabel)!=null?oo:"Send",$.style.width="",$.style.height="",$.style.minWidth="",$.style.minHeight="",$.style.fontSize="",$.style.lineHeight="",$.className="tvw-rounded-button tvw-bg-cw-accent tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold tvw-text-white disabled:tvw-opacity-50 tvw-cursor-pointer",gn?($.style.backgroundColor=gn,$.classList.remove("tvw-bg-cw-accent")):$.classList.add("tvw-bg-cw-accent"),Ct?$.style.color=Ct:$.classList.add("tvw-text-white");pe.borderWidth?($.style.borderWidth=pe.borderWidth,$.style.borderStyle="solid"):($.style.borderWidth="",$.style.borderStyle=""),pe.borderColor?$.style.borderColor=pe.borderColor:$.style.borderColor="",pe.paddingX?($.style.paddingLeft=pe.paddingX,$.style.paddingRight=pe.paddingX):($.style.paddingLeft="",$.style.paddingRight=""),pe.paddingY?($.style.paddingTop=pe.paddingY,$.style.paddingBottom=pe.paddingY):($.style.paddingTop="",$.style.paddingBottom="");let nn=qe==null?void 0:qe.querySelector(".tvw-send-button-tooltip");if(Dt&&Et)if(nn)nn.textContent=Et,nn.style.display="";else{let L=document.createElement("div");L.className="tvw-send-button-tooltip",L.textContent=Et,qe==null||qe.insertBefore(L,$)}else nn&&(nn.style.display="none");let sn=(ro=t.statusIndicator)!=null?ro:{},Mo=(io=sn.visible)!=null?io:!0;if(et.style.display=Mo?"":"none",N){let L=N.getStatus(),ce=Z=>{var Te,fe,Ge,Ne;return Z==="idle"?(Te=sn.idleText)!=null?Te:Ye.idle:Z==="connecting"?(fe=sn.connectingText)!=null?fe:Ye.connecting:Z==="connected"?(Ge=sn.connectedText)!=null?Ge:Ye.connected:Z==="error"?(Ne=sn.errorText)!=null?Ne:Ye.error:Ye[Z]};et.textContent=ce(L)}},open(){y&&st(!0,"api")},close(){y&&st(!1,"api")},toggle(){y&&st(!S,"api")},clearChat(){N.clearMessages();try{localStorage.removeItem(Zt),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Zt}`)}catch(p){console.error("[AgentWidget] Failed to clear default localStorage:",p)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==Zt)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.clearChatHistoryStorageKey}`)}catch(p){console.error("[AgentWidget] Failed to clear custom localStorage:",p)}let a=new CustomEvent("vanilla-agent:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(a),i!=null&&i.clear)try{let p=i.clear();p instanceof Promise&&p.catch(M=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",M)})}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",p)}l={},C.syncFromMetadata()},setMessage(a){return!se||N.isStreaming()?!1:(!S&&y&&st(!0,"system"),se.value=a,se.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(a){if(N.isStreaming())return!1;let p=(a==null?void 0:a.trim())||se.value.trim();return p?(!S&&y&&st(!0,"system"),se.value="",N.sendMessage(p),!0):!1},startVoiceRecognition(){return v||N.isStreaming()||!We()?!1:(!S&&y&&st(!0,"system"),ie.manuallyDeactivated=!1,he(),Me("user"),!0)},stopVoiceRecognition(){return v?(ie.manuallyDeactivated=!0,he(),ve("user"),!0):!1},injectTestMessage(a){!S&&y&&st(!0,"system"),N.injectTestEvent(a)},getMessages(){return N.getMessages()},getStatus(){return N.getStatus()},getPersistentMetadata(){return{...l}},updatePersistentMetadata(a){d(a)},on(a,p){return s.on(a,p)},off(a,p){s.off(a,p)},isOpen(){return y&&S},isVoiceActive(){return ie.active},getState(){return{open:y&&S,launcherEnabled:y,voiceActive:ie.active,streaming:N.isStreaming()}},destroy(){Pe.forEach(a=>a()),te.remove(),w==null||w.destroy(),g==null||g.remove(),Ue&&O.removeEventListener("click",Ue)}};if((((ss=o==null?void 0:o.debugTools)!=null?ss:!1)||!!t.debug)&&typeof window!="undefined"){let a=window.AgentWidgetBrowser,p={controller:Ce,getMessages:Ce.getMessages,getStatus:Ce.getStatus,getMetadata:Ce.getPersistentMetadata,updateMetadata:Ce.updatePersistentMetadata,clearHistory:()=>Ce.clearChat(),setVoiceActive:M=>M?Ce.startVoiceRecognition():Ce.stopVoiceRecognition()};window.AgentWidgetBrowser=p,Pe.push(()=>{window.AgentWidgetBrowser===p&&(window.AgentWidgetBrowser=a)})}return Ce};var Xn={},nr=n=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof n=="string"){let e=document.querySelector(n);if(!e)throw new Error(`Chat widget target "${n}" was not found`);return e}return n},sr=()=>{try{if(typeof Xn!="undefined"&&Xn.url)return new URL("../widget.css",Xn.url).href}catch{}return null},Eo=n=>{let e=sr(),o=()=>{if(!(n instanceof ShadowRoot)||n.querySelector("link[data-vanilla-agent]"))return;let t=document.head.querySelector("link[data-vanilla-agent]");if(!t)return;let r=t.cloneNode(!0);n.insertBefore(r,n.firstChild)};if(n instanceof ShadowRoot)if(e){let t=document.createElement("link");t.rel="stylesheet",t.href=e,t.setAttribute("data-vanilla-agent","true"),n.insertBefore(t,n.firstChild)}else o();else if(!document.head.querySelector("link[data-vanilla-agent]")&&e){let r=document.createElement("link");r.rel="stylesheet",r.href=e,r.setAttribute("data-vanilla-agent","true"),document.head.appendChild(r)}},Vn=n=>{var h,d,E,f;let e=nr(n.target),o=document.createElement("div");o.className="vanilla-agent-host";let t=(E=(d=(h=n.config)==null?void 0:h.launcher)==null?void 0:d.enabled)!=null?E:!0;t||(o.style.height="100%",o.style.display="flex",o.style.flexDirection="column"),e.appendChild(o);let r=n.useShadowDom===!0,s,i;if(r){let C=o.attachShadow({mode:"open"});i=C,s=document.createElement("div"),s.id="vanilla-agent-root",t||(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0"),C.appendChild(s),Eo(C)}else i=o,s=document.createElement("div"),s.id="vanilla-agent-root",t||(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0"),o.appendChild(s),Eo(o);let l=Ln(s,n.config,{debugTools:n.debugTools});(f=n.onReady)==null||f.call(n);let u={...l,host:o,destroy(){l.destroy(),o.remove(),n.windowKey&&typeof window!="undefined"&&delete window[n.windowKey]}};return n.windowKey&&typeof window!="undefined"&&(window[n.windowKey]=u),u};function or(n){if(!n)return null;let e=n.toString();return e.includes("createJsonStreamParser")||e.includes("partial-json")?"json":e.includes("createRegexJsonParser")||e.includes("regex")?"regex-json":e.includes("createXmlParser")||e.includes("<text>")?"xml":null}function Bn(n){var e,o;return(o=(e=n.parserType)!=null?e:or(n.streamParser))!=null?o:"plain"}function Wo(n,e="esm"){let o={...n};return delete o.postprocessMessage,delete o.initialMessages,e==="esm"?rr(o):e==="script-installer"?lr(o):e==="script-advanced"?cr(o):e==="react-component"?ir(o):e==="react-advanced"?ar(o):dr(o)}function rr(n){let e=Bn(n),o=e!=="plain",t=["import 'vanilla-agent/widget.css';","import { initAgentWidget, markdownPostprocessor } from 'vanilla-agent';","","initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&t.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&t.push(` flowId: "${n.flowId}",`),o&&t.push(` parserType: "${e}",`),n.theme&&(t.push(" theme: {"),Object.entries(n.theme).forEach(([r,s])=>{t.push(` ${r}: "${s}",`)}),t.push(" },")),n.launcher&&(t.push(" launcher: {"),Object.entries(n.launcher).forEach(([r,s])=>{typeof s=="string"?t.push(` ${r}: "${s}",`):typeof s=="boolean"&&t.push(` ${r}: ${s},`)}),t.push(" },")),n.copy&&(t.push(" copy: {"),Object.entries(n.copy).forEach(([r,s])=>{t.push(` ${r}: "${s}",`)}),t.push(" },")),n.sendButton&&(t.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([r,s])=>{typeof s=="string"?t.push(` ${r}: "${s}",`):typeof s=="boolean"&&t.push(` ${r}: ${s},`)}),t.push(" },")),n.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([r,s])=>{typeof s=="string"?t.push(` ${r}: "${s}",`):typeof s=="boolean"?t.push(` ${r}: ${s},`):typeof s=="number"&&t.push(` ${r}: ${s},`)}),t.push(" },")),n.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([r,s])=>{typeof s=="string"?t.push(` ${r}: "${s}",`):typeof s=="boolean"&&t.push(` ${r}: ${s},`)}),t.push(" },")),n.features&&(t.push(" features: {"),Object.entries(n.features).forEach(([r,s])=>{t.push(` ${r}: ${s},`)}),t.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(t.push(" suggestionChips: ["),n.suggestionChips.forEach(r=>{t.push(` "${r}",`)}),t.push(" ],")),n.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),t.push(" },")),n.debug&&t.push(` debug: ${n.debug},`),t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),t.push(" }"),t.push("});"),t.join(`
|
|
55
|
-
`)}function
|
|
56
|
-
`)}function ar(n){let e=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import 'vanilla-agent/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from 'vanilla-agent';","import type { AgentWidgetInitHandle } from 'vanilla-agent';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.vanilla-agent-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&e.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&e.push(` flowId: "${n.flowId}",`),n.theme&&(e.push(" theme: {"),Object.entries(n.theme).forEach(([o,t])=>{e.push(` ${o}: "${t}",`)}),e.push(" },")),n.launcher&&(e.push(" launcher: {"),Object.entries(n.launcher).forEach(([o,t])=>{typeof t=="string"?e.push(` ${o}: "${t}",`):typeof t=="boolean"&&e.push(` ${o}: ${t},`)}),e.push(" },")),n.copy&&(e.push(" copy: {"),Object.entries(n.copy).forEach(([o,t])=>{e.push(` ${o}: "${t}",`)}),e.push(" },")),n.sendButton&&(e.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([o,t])=>{typeof t=="string"?e.push(` ${o}: "${t}",`):typeof t=="boolean"&&e.push(` ${o}: ${t},`)}),e.push(" },")),n.voiceRecognition&&(e.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([o,t])=>{typeof t=="string"?e.push(` ${o}: "${t}",`):typeof t=="boolean"?e.push(` ${o}: ${t},`):typeof t=="number"&&e.push(` ${o}: ${t},`)}),e.push(" },")),n.statusIndicator&&(e.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([o,t])=>{typeof t=="string"?e.push(` ${o}: "${t}",`):typeof t=="boolean"&&e.push(` ${o}: ${t},`)}),e.push(" },")),n.features&&(e.push(" features: {"),Object.entries(n.features).forEach(([o,t])=>{e.push(` ${o}: ${t},`)}),e.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(e.push(" suggestionChips: ["),n.suggestionChips.forEach(o=>{e.push(` "${o}",`)}),e.push(" ],")),n.suggestionChipsConfig&&(e.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&e.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&e.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&e.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&e.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),e.push(" },")),n.debug&&e.push(` debug: ${n.debug},`),e.push(" initialMessages: loadSavedMessages(),"),e.push(" // Flexible JSON stream parser for handling structured actions"),e.push(" streamParser: () => createFlexibleJsonStreamParser((parsed: any) => {"),e.push(" if (!parsed || typeof parsed !== 'object') return null;"),e.push(" // Extract display text based on action type"),e.push(" if (parsed.action === 'nav_then_click') return 'Navigating...';"),e.push(" if (parsed.action === 'message') return parsed.text || '';"),e.push(" if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';"),e.push(" return parsed.text || null;"),e.push(" }),"),e.push(" // Action parsers to detect JSON actions in responses"),e.push(" actionParsers: ["),e.push(" defaultJsonActionParser,"),e.push(" // Custom parser for markdown-wrapped JSON"),e.push(" ({ text, message }: any) => {"),e.push(" const jsonSource = (message as any).rawContent || text || message.content;"),e.push(" if (!jsonSource || typeof jsonSource !== 'string') return null;"),e.push(" // Strip markdown code fences"),e.push(" let cleanJson = jsonSource"),e.push(" .replace(/^```(?:json)?\\s*\\n?/, '')"),e.push(" .replace(/\\n?```\\s*$/, '')"),e.push(" .trim();"),e.push(" if (!cleanJson.startsWith('{') || !cleanJson.endsWith('}')) return null;"),e.push(" try {"),e.push(" const parsed = JSON.parse(cleanJson);"),e.push(" if (parsed.action) return { type: parsed.action, payload: parsed };"),e.push(" } catch (e) { return null; }"),e.push(" return null;"),e.push(" }"),e.push(" ],"),e.push(" // Action handlers for navigation and other actions"),e.push(" actionHandlers: ["),e.push(" defaultActionHandlers.message,"),e.push(" defaultActionHandlers.messageAndClick,"),e.push(" // Handler for nav_then_click action"),e.push(" (action: any, context: any) => {"),e.push(" if (action.type !== 'nav_then_click') return;"),e.push(" const payload = action.payload || action.raw || {};"),e.push(" const url = payload?.page;"),e.push(" const text = payload?.on_load_text || 'Navigating...';"),e.push(" if (!url) return { handled: true, displayText: text };"),e.push(" // Check if already processed"),e.push(" const messageId = context.message?.id;"),e.push(" const processedActions = JSON.parse(localStorage.getItem(PROCESSED_ACTIONS_KEY) || '[]');"),e.push(" const actionKey = `nav_${messageId}_${url}`;"),e.push(" if (processedActions.includes(actionKey)) {"),e.push(" return { handled: true, displayText: text };"),e.push(" }"),e.push(" processedActions.push(actionKey);"),e.push(" localStorage.setItem(PROCESSED_ACTIONS_KEY, JSON.stringify(processedActions));"),e.push(" const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();"),e.push(" window.location.href = targetUrl;"),e.push(" return { handled: true, displayText: text };"),e.push(" }"),e.push(" ],"),e.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),e.push(" requestMiddleware: ({ payload }) => {"),e.push(" return {"),e.push(" ...payload,"),e.push(" metadata: collectDOMContext()"),e.push(" };"),e.push(" }"),e.push(" }"),e.push(" });"),e.push(""),e.push(" // Save state on message events"),e.push(" const handleMessage = () => {"),e.push(" const session = handle?.getSession?.();"),e.push(" if (session) {"),e.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),e.push(" messages: session.messages,"),e.push(" timestamp: new Date().toISOString()"),e.push(" }));"),e.push(" }"),e.push(" };"),e.push(""),e.push(" // Clear state on clear chat"),e.push(" const handleClearChat = () => {"),e.push(" localStorage.removeItem(STORAGE_KEY);"),e.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),e.push(" };"),e.push(""),e.push(" window.addEventListener('vanilla-agent:message', handleMessage);"),e.push(" window.addEventListener('vanilla-agent:clear-chat', handleClearChat);"),e.push(""),e.push(" // Cleanup on unmount"),e.push(" return () => {"),e.push(" window.removeEventListener('vanilla-agent:message', handleMessage);"),e.push(" window.removeEventListener('vanilla-agent:clear-chat', handleClearChat);"),e.push(" if (handle) {"),e.push(" handle.destroy();"),e.push(" }"),e.push(" };"),e.push(" }, []);"),e.push(""),e.push(" return null; // Widget injects itself into the DOM"),e.push("}"),e.push(""),e.push("// Usage: Collects DOM context for AI-powered navigation"),e.push("// Features:"),e.push("// - Extracts page elements (products, buttons, links)"),e.push("// - Persists chat history across page loads"),e.push("// - Handles navigation actions (nav_then_click)"),e.push("// - Processes structured JSON actions from AI"),e.push("//"),e.push("// Example usage in Next.js:"),e.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),e.push("//"),e.push("// export default function RootLayout({ children }) {"),e.push("// return ("),e.push('// <html lang="en">'),e.push("// <body>"),e.push("// {children}"),e.push("// <ChatWidgetAdvanced />"),e.push("// </body>"),e.push("// </html>"),e.push("// );"),e.push("// }"),e.join(`
|
|
57
|
-
`)}function
|
|
58
|
-
`)}function
|
|
59
|
-
`)}function cr(n){let e=["<!-- Load CSS -->",'<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist/widget.css" />',"","<!-- Chat Widget Configuration -->","<script>"," window.ChatWidgetConfig = {"];return n.apiUrl&&e.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&e.push(` flowId: "${n.flowId}",`),n.theme&&(e.push(" theme: {"),Object.entries(n.theme).forEach(([o,t])=>{e.push(` ${o}: "${t}",`)}),e.push(" },")),n.launcher&&(e.push(" launcher: {"),Object.entries(n.launcher).forEach(([o,t])=>{typeof t=="string"?e.push(` ${o}: "${t}",`):typeof t=="boolean"&&e.push(` ${o}: ${t},`)}),e.push(" },")),n.copy&&(e.push(" copy: {"),Object.entries(n.copy).forEach(([o,t])=>{e.push(` ${o}: "${t}",`)}),e.push(" },")),n.sendButton&&(e.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([o,t])=>{typeof t=="string"?e.push(` ${o}: "${t}",`):typeof t=="boolean"&&e.push(` ${o}: ${t},`)}),e.push(" },")),n.voiceRecognition&&(e.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([o,t])=>{typeof t=="string"?e.push(` ${o}: "${t}",`):typeof t=="boolean"?e.push(` ${o}: ${t},`):typeof t=="number"&&e.push(` ${o}: ${t},`)}),e.push(" },")),n.statusIndicator&&(e.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([o,t])=>{typeof t=="string"?e.push(` ${o}: "${t}",`):typeof t=="boolean"&&e.push(` ${o}: ${t},`)}),e.push(" },")),n.features&&(e.push(" features: {"),Object.entries(n.features).forEach(([o,t])=>{e.push(` ${o}: ${t},`)}),e.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(e.push(" suggestionChips: ["),n.suggestionChips.forEach(o=>{e.push(` "${o}",`)}),e.push(" ],")),e.push(" };"),e.push("</script>"),e.push(""),e.push("<!-- Load the widget library -->"),e.push('<script src="https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist/index.global.js"></script>'),e.push(""),e.push("<!-- Chat Widget Script with DOM Helper -->"),e.push("<script>"),e.push(" (function () {"),e.push(" 'use strict';"),e.push(" "),e.push(" const STORAGE_KEY = 'chat-widget-state';"),e.push(" const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';"),e.push(""),e.push(" // DOM context provider - extracts page elements for AI context"),e.push(" const domContextProvider = () => {"),e.push(" const selectors = {"),e.push(` products: '[data-product-id], .product-card, .product-item, [role="article"]',`),e.push(` buttons: 'button, [role="button"], .btn',`),e.push(" links: 'a[href]',"),e.push(" inputs: 'input, textarea, select'"),e.push(" };"),e.push(""),e.push(" const elements = [];"),e.push(" Object.entries(selectors).forEach(([type, selector]) => {"),e.push(" document.querySelectorAll(selector).forEach((element) => {"),e.push(" if (!(element instanceof HTMLElement)) return;"),e.push(" "),e.push(" // Exclude elements within the widget"),e.push(" const widgetHost = element.closest('.vanilla-agent-host');"),e.push(" if (widgetHost) return;"),e.push(" "),e.push(" const text = element.innerText?.trim();"),e.push(" if (!text) return;"),e.push(""),e.push(" const selectorString ="),e.push(" element.id ? `#${element.id}` :"),e.push(" element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"),e.push(" element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"),e.push(" element.tagName.toLowerCase();"),e.push(""),e.push(" const elementData = {"),e.push(" type,"),e.push(" tagName: element.tagName.toLowerCase(),"),e.push(" selector: selectorString,"),e.push(" innerText: text.substring(0, 200)"),e.push(" };"),e.push(""),e.push(" if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"),e.push(" elementData.href = element.href;"),e.push(" }"),e.push(""),e.push(" elements.push(elementData);"),e.push(" });"),e.push(" });"),e.push(""),e.push(" const counts = elements.reduce((acc, el) => {"),e.push(" acc[el.type] = (acc[el.type] || 0) + 1;"),e.push(" return acc;"),e.push(" }, {});"),e.push(""),e.push(" return {"),e.push(" page_elements: elements.slice(0, 50),"),e.push(" page_element_count: elements.length,"),e.push(" element_types: counts,"),e.push(" page_url: window.location.href,"),e.push(" page_title: document.title,"),e.push(" timestamp: new Date().toISOString()"),e.push(" };"),e.push(" };"),e.push(""),e.push(" const createWidgetConfig = (agentWidget) => ({"),e.push(" ...window.ChatWidgetConfig,"),e.push(" // Flexible JSON stream parser for handling structured actions"),e.push(" streamParser: () => agentWidget.createFlexibleJsonStreamParser((parsed) => {"),e.push(" if (!parsed || typeof parsed !== 'object') return null;"),e.push(" "),e.push(" // Extract display text based on action type"),e.push(" if (parsed.action === 'nav_then_click') {"),e.push(" return 'Navigating...';"),e.push(" } else if (parsed.action === 'message') {"),e.push(" return parsed.text || '';"),e.push(" } else if (parsed.action === 'message_and_click') {"),e.push(" return parsed.text || 'Processing...';"),e.push(" }"),e.push(" "),e.push(" return parsed.text || null;"),e.push(" }),"),e.push(" // Action parsers to detect JSON actions in responses"),e.push(" actionParsers: ["),e.push(" agentWidget.defaultJsonActionParser,"),e.push(" // Custom parser for markdown-wrapped JSON"),e.push(" ({ text, message }) => {"),e.push(" const jsonSource = message.rawContent || text || message.content;"),e.push(" if (!jsonSource || typeof jsonSource !== 'string') return null;"),e.push(" "),e.push(" // Strip markdown code fences"),e.push(" let cleanJson = jsonSource"),e.push(" .replace(/^```(?:json)?\\s*\\n?/, '')"),e.push(" .replace(/\\n?```\\s*$/, '')"),e.push(" .trim();"),e.push(" "),e.push(" if (!cleanJson.startsWith('{') || !cleanJson.endsWith('}')) return null;"),e.push(" "),e.push(" try {"),e.push(" const parsed = JSON.parse(cleanJson);"),e.push(" if (parsed.action) {"),e.push(" return { type: parsed.action, payload: parsed };"),e.push(" }"),e.push(" } catch (e) {"),e.push(" return null;"),e.push(" }"),e.push(" return null;"),e.push(" }"),e.push(" ],"),e.push(" // Action handlers for navigation and other actions"),e.push(" actionHandlers: ["),e.push(" agentWidget.defaultActionHandlers.message,"),e.push(" agentWidget.defaultActionHandlers.messageAndClick,"),e.push(" // Handler for nav_then_click action"),e.push(" (action, context) => {"),e.push(" if (action.type !== 'nav_then_click') return;"),e.push(" "),e.push(" const payload = action.payload || action.raw || {};"),e.push(" const url = payload?.page;"),e.push(" const text = payload?.on_load_text || 'Navigating...';"),e.push(" "),e.push(" if (!url) return { handled: true, displayText: text };"),e.push(" "),e.push(" // Check if already processed"),e.push(" const messageId = context.message?.id;"),e.push(" const processedActions = JSON.parse(localStorage.getItem(PROCESSED_ACTIONS_KEY) || '[]');"),e.push(" const actionKey = `nav_${messageId}_${url}`;"),e.push(" "),e.push(" if (processedActions.includes(actionKey)) {"),e.push(" return { handled: true, displayText: text };"),e.push(" }"),e.push(" "),e.push(" processedActions.push(actionKey);"),e.push(" localStorage.setItem(PROCESSED_ACTIONS_KEY, JSON.stringify(processedActions));"),e.push(" "),e.push(" const targetUrl = url.startsWith('http')"),e.push(" ? url"),e.push(" : new URL(url, window.location.origin).toString();"),e.push(" "),e.push(" window.location.href = targetUrl;"),e.push(" "),e.push(" return { handled: true, displayText: text };"),e.push(" }"),e.push(" ],"),e.push(" // Send DOM context with each request"),e.push(" requestMiddleware: ({ payload }) => ({"),e.push(" ...payload,"),e.push(" metadata: domContextProvider()"),e.push(" })"),e.push(" });"),e.push(""),e.push(" // Initialize widget when DOM is loaded"),e.push(" function init() {"),e.push(" const agentWidget = window.AgentWidget;"),e.push(" if (!agentWidget) {"),e.push(" console.error('AgentWidget not loaded');"),e.push(" return;"),e.push(" }"),e.push(""),e.push(" const widgetConfig = createWidgetConfig(agentWidget);"),e.push(""),e.push(" // Load saved state"),e.push(" const savedState = localStorage.getItem(STORAGE_KEY);"),e.push(" if (savedState) {"),e.push(" try {"),e.push(" const { messages } = JSON.parse(savedState);"),e.push(" widgetConfig.initialMessages = messages || [];"),e.push(" } catch (e) {"),e.push(" console.error('Failed to load saved state:', e);"),e.push(" }"),e.push(" }"),e.push(""),e.push(" // Initialize widget with DOM context"),e.push(" const handle = agentWidget.initAgentWidget({"),e.push(" target: 'body',"),e.push(" config: widgetConfig"),e.push(" });"),e.push(""),e.push(" // Save state on message events"),e.push(" window.addEventListener('vanilla-agent:message', (event) => {"),e.push(" const session = handle.getSession?.();"),e.push(" if (session) {"),e.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),e.push(" messages: session.messages,"),e.push(" timestamp: new Date().toISOString()"),e.push(" }));"),e.push(" }"),e.push(" });"),e.push(""),e.push(" // Clear state on clear chat"),e.push(" window.addEventListener('vanilla-agent:clear-chat', () => {"),e.push(" localStorage.removeItem(STORAGE_KEY);"),e.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),e.push(" });"),e.push(" }"),e.push(""),e.push(" // Initialize when DOM is ready"),e.push(" if (document.readyState === 'loading') {"),e.push(" document.addEventListener('DOMContentLoaded', init);"),e.push(" } else {"),e.push(" init();"),e.push(" }"),e.push(" })();"),e.push("</script>"),e.join(`
|
|
60
|
-
`)}var
|
|
55
|
+
`}};ft();let ke=[],et=bo(le),qe=null,F,lt=!1,Ke=!0,We=0,je=0,K=null,Se=!1,Le=0,Ue=!1,tt=125,xt=2e3,Lt=5,pt=50,Ct=new Map,de={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1},Ot=(os=(ss=t.voiceRecognition)==null?void 0:ss.autoResume)!=null?os:!1,Bt=a=>{s.emit("voice:state",{active:de.active,source:a,timestamp:Date.now()})},ve=()=>{d(a=>({...a,voiceState:{active:de.active,timestamp:Date.now(),manuallyDeactivated:de.manuallyDeactivated}}))},wt=()=>{var N,k;if(((N=t.voiceRecognition)==null?void 0:N.enabled)===!1)return;let a=Vn(l.voiceState),p=!!a.active,E=Number((k=a.timestamp)!=null?k:0);de.manuallyDeactivated=!!a.manuallyDeactivated,p&&Date.now()-E<sr&&setTimeout(()=>{de.active||(de.manuallyDeactivated=!1,Ie("restore"))},1e3)},St=()=>F?Eo(F.getMessages()).filter(a=>!a.__skipPersist):[];function Ht(a){if(!(i!=null&&i.save))return;let E={messages:a?Eo(a):F?St():[],metadata:l};try{let N=i.save(E);N instanceof Promise&&N.catch(k=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",k)})}catch(N){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",N)}}let yt=(a=!1)=>{if(!Ke)return;let p=Date.now();Se&&p<Le&&!a||(Se&&p>=Le&&(Se=!1),!(!a&&!lt)&&(p-je<tt||(je=p,K&&cancelAnimationFrame(K),K=requestAnimationFrame(()=>{Se||!Ke||(Ue=!0,z.scrollTop=z.scrollHeight,We=z.scrollTop,requestAnimationFrame(()=>{Ue=!1}),K=null)}))))},Et=null,cn=()=>te.querySelector("#vanilla-agent-scroll-container")||z,un=(a,p=500)=>{let E=a.scrollTop,N=a.clientHeight,k=a.scrollHeight,ee=k-E;if(E+N>=k-2||Math.abs(ee)<5)return;Et!==null&&(cancelAnimationFrame(Et),Et=null);let v=performance.now(),U=R=>1-Math.pow(1-R,3),O=R=>{let q=a.scrollHeight;q!==k&&(k=q,ee=k-E);let $e=R-v,xe=Math.min($e/p,1),re=U(xe),Ne=E+ee*re;a.scrollTop=Ne,xe<1?Et=requestAnimationFrame(O):(a.scrollTop=a.scrollHeight,Et=null)};Et=requestAnimationFrame(O)},pn=a=>{let p=new Map;a.forEach(E=>{let N=Ct.get(E.id);p.set(E.id,{streaming:E.streaming,role:E.role}),!N&&E.role==="assistant"&&s.emit("assistant:message",E),E.role==="assistant"&&(N!=null&&N.streaming)&&E.streaming===!1&&s.emit("assistant:complete",E)}),Ct.clear(),p.forEach((E,N)=>{Ct.set(N,E)})},Nt=(a,p,E)=>{a.innerHTML="";let N=document.createDocumentFragment();p.forEach(v=>{var $e,xe;let U=null,O=r.find(re=>!!(v.variant==="reasoning"&&re.renderReasoning||v.variant==="tool"&&re.renderToolCall||!v.variant&&re.renderMessage)),R=($e=t.layout)==null?void 0:$e.messages;if(O)if(v.variant==="reasoning"&&v.reasoning&&O.renderReasoning){if(!S)return;U=O.renderReasoning({message:v,defaultRenderer:()=>qn(v),config:t})}else if(v.variant==="tool"&&v.toolCall&&O.renderToolCall){if(!Y)return;U=O.renderToolCall({message:v,defaultRenderer:()=>zn(v,t),config:t})}else O.renderMessage&&(U=O.renderMessage({message:v,defaultRenderer:()=>{let re=Xt(v,E,R);return v.role!=="user"&&Yn(re,v,t,F),re},config:t}));if(!U&&v.role==="assistant"&&!v.variant&&t.enableComponentStreaming!==!1&&Mn(v)){let Ne=Ln(v);if(Ne){let dt=Wn(Ne,{config:t,message:v,transform:E});if(dt){let oe=document.createElement("div");if(oe.className=["vanilla-message-bubble","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-p-4"].join(" "),oe.setAttribute("data-message-id",v.id),v.content&&v.content.trim()){let ct=document.createElement("div");ct.className="tvw-mb-3 tvw-text-sm tvw-leading-relaxed",ct.innerHTML=E({text:v.content,message:v,streaming:!!v.streaming,raw:v.rawContent}),oe.appendChild(ct)}oe.appendChild(dt),U=oe}}}if(!U)if(v.variant==="reasoning"&&v.reasoning){if(!S)return;U=qn(v)}else if(v.variant==="tool"&&v.toolCall){if(!Y)return;U=zn(v,t)}else{let re=(xe=t.layout)==null?void 0:xe.messages;re!=null&&re.renderUserMessage&&v.role==="user"?U=re.renderUserMessage({message:v,config:t,streaming:!!v.streaming}):re!=null&&re.renderAssistantMessage&&v.role==="assistant"?U=re.renderAssistantMessage({message:v,config:t,streaming:!!v.streaming}):U=Xt(v,E,re),v.role!=="user"&&U&&Yn(U,v,t,F)}let q=document.createElement("div");q.className="tvw-flex",v.role==="user"&&q.classList.add("tvw-justify-end"),q.appendChild(U),N.appendChild(q)});let k=p.some(v=>v.role==="assistant"&&v.streaming),ee=p[p.length-1],H=(ee==null?void 0:ee.role)==="assistant"&&!ee.streaming;if(lt&&p.some(v=>v.role==="user")&&!k&&!H){let v=rn(),U=document.createElement("div");U.className=["tvw-max-w-[85%]","tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3"].join(" "),U.appendChild(v);let O=document.createElement("div");O.className="tvw-flex",O.appendChild(U),N.appendChild(O)}a.appendChild(N),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let v=cn();un(v)})})},Dt=()=>{w&&(C?(te.classList.remove("tvw-pointer-events-none","tvw-opacity-0"),A.classList.remove("tvw-scale-95","tvw-opacity-0"),A.classList.add("tvw-scale-100","tvw-opacity-100"),g?g.element.style.display="none":B&&(B.style.display="none")):(te.classList.add("tvw-pointer-events-none","tvw-opacity-0"),A.classList.remove("tvw-scale-100","tvw-opacity-100"),A.classList.add("tvw-scale-95","tvw-opacity-0"),g?g.element.style.display="":B&&(B.style.display="")))},nt=(a,p="user")=>{if(!w||C===a)return;let E=C;C=a,Dt(),C&&(we(),yt(!0));let N={open:C,source:p,timestamp:Date.now()};C&&!E?s.emit("widget:opened",N):!C&&E&&s.emit("widget:closed",N),s.emit("widget:state",{open:C,launcherEnabled:w,voiceActive:de.active,streaming:F.isStreaming()})},Ut=a=>{P.disabled=a,M&&(M.disabled=a),et.buttons.forEach(p=>{p.disabled=a})},Qt=()=>{var k,ee,H,v,U,O,R,q,$e,xe,re,Ne,dt,oe;vt.textContent=(ee=(k=t.copy)==null?void 0:k.welcomeTitle)!=null?ee:"Hello \u{1F44B}",bt.textContent=(v=(H=t.copy)==null?void 0:H.welcomeSubtitle)!=null?v:"Ask anything about your account or products.",se.placeholder=(O=(U=t.copy)==null?void 0:U.inputPlaceholder)!=null?O:"How can I help...",((q=(R=t.sendButton)==null?void 0:R.useIcon)!=null?q:!1)||(P.textContent=(xe=($e=t.copy)==null?void 0:$e.sendButtonLabel)!=null?xe:"Send");let p=(Ne=(re=t.theme)==null?void 0:re.inputFontFamily)!=null?Ne:"sans-serif",E=(oe=(dt=t.theme)==null?void 0:dt.inputFontWeight)!=null?oe:"400",N=ct=>{switch(ct){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};se.style.fontFamily=N(p),se.style.fontWeight=E};F=new Yt(t,{onMessagesChanged(a){Nt(G,a,$),F&&(a.some(N=>N.role==="user")?et.render([],F,se,a):et.render(t.suggestionChips,F,se,a,t.suggestionChipsConfig)),yt(!lt),pn(a);let p=[...a].reverse().find(E=>E.role==="user");de.lastUserMessageWasVoice=!!(p!=null&&p.viaVoice),Ht(a)},onStatusChanged(a){var N;let p=(N=t.statusIndicator)!=null?N:{},E=k=>{var ee,H,v,U;return k==="idle"?(ee=p.idleText)!=null?ee:ze.idle:k==="connecting"?(H=p.connectingText)!=null?H:ze.connecting:k==="connected"?(v=p.connectedText)!=null?v:ze.connected:k==="error"?(U=p.errorText)!=null?U:ze.error:ze[k]};Qe.textContent=E(a)},onStreamingChanged(a){lt=a,Ut(a),F&&Nt(G,F.getMessages(),$),a||yt(!0)}}),u&&u.then(a=>{var p;a&&(a.metadata&&(l=Vn(a.metadata),b.syncFromMetadata()),(p=a.messages)!=null&&p.length&&F.hydrateMessages(a.messages))}).catch(a=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",a)});let en=a=>{a.preventDefault();let p=se.value.trim();p&&(se.value="",F.sendMessage(p))},tn=a=>{a.key==="Enter"&&!a.shiftKey&&(a.preventDefault(),P.click())},y=null,X=!1,ne=null,fe=null,Re=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Ie=(a="user")=>{var ee,H,v,U;if(X||F.isStreaming())return;let p=Re();if(!p)return;y=new p;let N=(H=((ee=t.voiceRecognition)!=null?ee:{}).pauseDuration)!=null?H:2e3;y.continuous=!0,y.interimResults=!0,y.lang="en-US";let k=se.value;y.onresult=O=>{let R="",q="";for(let xe=0;xe<O.results.length;xe++){let re=O.results[xe],Ne=re[0].transcript;re.isFinal?R+=Ne+" ":q=Ne}let $e=k+R+q;se.value=$e,ne&&clearTimeout(ne),(R||q)&&(ne=window.setTimeout(()=>{let xe=se.value.trim();xe&&y&&X&&(ce(),se.value="",F.sendMessage(xe,{viaVoice:!0}))},N))},y.onerror=O=>{O.error!=="no-speech"&&ce()},y.onend=()=>{if(X){let O=se.value.trim();O&&O!==k.trim()&&(se.value="",F.sendMessage(O,{viaVoice:!0})),ce()}};try{if(y.start(),X=!0,de.active=!0,a!=="system"&&(de.manuallyDeactivated=!1),Bt(a),ve(),M){fe={backgroundColor:M.style.backgroundColor,color:M.style.color,borderColor:M.style.borderColor};let O=(v=t.voiceRecognition)!=null?v:{},R=(U=O.recordingBackgroundColor)!=null?U:"#ef4444",q=O.recordingIconColor,$e=O.recordingBorderColor;if(M.classList.add("tvw-voice-recording"),M.style.backgroundColor=R,q){M.style.color=q;let xe=M.querySelector("svg");xe&&xe.setAttribute("stroke",q)}$e&&(M.style.borderColor=$e),M.setAttribute("aria-label","Stop voice recognition")}}catch{ce("system")}},ce=(a="user")=>{if(X){if(X=!1,ne&&(clearTimeout(ne),ne=null),y){try{y.stop()}catch{}y=null}if(de.active=!1,Bt(a),ve(),M){if(M.classList.remove("tvw-voice-recording"),fe){M.style.backgroundColor=fe.backgroundColor,M.style.color=fe.color,M.style.borderColor=fe.borderColor;let p=M.querySelector("svg");p&&p.setAttribute("stroke",fe.color||"currentColor"),fe=null}M.setAttribute("aria-label","Start voice recognition")}}},L=(a,p)=>{var Ne,dt,oe,ct,kt,Rt,Wt;if(!(typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined")))return null;let N=c("div","tvw-send-button-wrapper"),k=c("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer");k.type="button",k.setAttribute("aria-label","Start voice recognition");let ee=(Ne=a==null?void 0:a.iconName)!=null?Ne:"mic",H=(dt=p==null?void 0:p.size)!=null?dt:"40px",v=(oe=a==null?void 0:a.iconSize)!=null?oe:H,U=parseFloat(v)||24,O=(ct=a==null?void 0:a.backgroundColor)!=null?ct:p==null?void 0:p.backgroundColor,R=(kt=a==null?void 0:a.iconColor)!=null?kt:p==null?void 0:p.textColor;k.style.width=v,k.style.height=v,k.style.minWidth=v,k.style.minHeight=v,k.style.fontSize="18px",k.style.lineHeight="1";let q=R||"currentColor",$e=ye(ee,U,q,1.5);$e?(k.appendChild($e),k.style.color=q):(k.textContent="\u{1F3A4}",k.style.color=q),O?k.style.backgroundColor=O:k.classList.add("tvw-bg-cw-primary"),R?k.style.color=R:!R&&!(p!=null&&p.textColor)&&k.classList.add("tvw-text-white"),a!=null&&a.borderWidth&&(k.style.borderWidth=a.borderWidth,k.style.borderStyle="solid"),a!=null&&a.borderColor&&(k.style.borderColor=a.borderColor),a!=null&&a.paddingX&&(k.style.paddingLeft=a.paddingX,k.style.paddingRight=a.paddingX),a!=null&&a.paddingY&&(k.style.paddingTop=a.paddingY,k.style.paddingBottom=a.paddingY),N.appendChild(k);let xe=(Rt=a==null?void 0:a.tooltipText)!=null?Rt:"Start voice recognition";if(((Wt=a==null?void 0:a.showTooltip)!=null?Wt:!1)&&xe){let Ft=c("div","tvw-send-button-tooltip");Ft.textContent=xe,N.appendChild(Ft)}return{micButton:k,micButtonWrapper:N}},st=()=>{if(X){let a=se.value.trim();de.manuallyDeactivated=!0,ve(),ce("user"),a&&(se.value="",F.sendMessage(a))}else de.manuallyDeactivated=!1,ve(),Ie("user")};M&&(M.addEventListener("click",st),ke.push(()=>{ce("system"),M&&M.removeEventListener("click",st)}));let Z=s.on("assistant:complete",()=>{Ot&&(de.active||de.manuallyDeactivated||Ot==="assistant"&&!de.lastUserMessageWasVoice||setTimeout(()=>{!de.active&&!de.manuallyDeactivated&&Ie("auto")},600))});ke.push(Z);let x=()=>{nt(!C,"user")},g=null,B=null;if(w){let a=r.find(p=>p.renderLauncher);if(a!=null&&a.renderLauncher){let p=a.renderLauncher({config:t,defaultRenderer:()=>on(t,x).element,onToggle:x});p&&(B=p)}B||(g=on(t,x))}g?n.appendChild(g.element):B&&n.appendChild(B),Dt(),et.render(t.suggestionChips,F,se,void 0,t.suggestionChipsConfig),Qt(),Ut(F.isStreaming()),yt(!0),wt();let we=()=>{var E,N,k,ee,H,v;let a=(N=(E=t.launcher)==null?void 0:E.sidebarMode)!=null?N:!1,p=a||((ee=(k=t.launcher)==null?void 0:k.fullHeight)!=null?ee:!1);if(!w){A.style.height="",A.style.width="";return}if(!a){let U=(v=(H=t==null?void 0:t.launcher)==null?void 0:H.width)!=null?v:t==null?void 0:t.launcherWidth,O=U!=null?U:"min(400px, calc(100vw - 24px))";A.style.width=O,A.style.maxWidth=O}if(!p){let U=window.innerHeight,R=Math.max(200,U-64),q=Math.min(640,R);A.style.height=`${q}px`}};we(),window.addEventListener("resize",we),ke.push(()=>window.removeEventListener("resize",we)),We=z.scrollTop;let Ae=()=>{let a=z.scrollTop,p=z.scrollHeight,E=z.clientHeight,N=p-a-E,k=Math.abs(a-We);if(We=a,!Ue&&!(k<=Lt)){if(!Ke&&N<pt){Se=!1,Ke=!0;return}Ke&&N>pt&&(Se=!0,Le=Date.now()+xt,Ke=!1)}};z.addEventListener("scroll",Ae,{passive:!0}),ke.push(()=>z.removeEventListener("scroll",Ae)),ke.push(()=>{K&&cancelAnimationFrame(K)});let Xe=()=>{D&&(qe&&(D.removeEventListener("click",qe),qe=null),w?(D.style.display="",qe=()=>{C=!1,Dt()},D.addEventListener("click",qe)):D.style.display="none")};Xe(),(()=>{let{clearChatButton:a}=ie;a&&a.addEventListener("click",()=>{F.clearMessages();try{localStorage.removeItem(Zt),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Zt}`)}catch(E){console.error("[AgentWidget] Failed to clear default localStorage:",E)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==Zt)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.clearChatHistoryStorageKey}`)}catch(E){console.error("[AgentWidget] Failed to clear custom localStorage:",E)}let p=new CustomEvent("vanilla-agent:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(p),i!=null&&i.clear)try{let E=i.clear();E instanceof Promise&&E.catch(N=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",N)})}catch(E){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",E)}l={},b.syncFromMetadata()})})(),Ye.addEventListener("submit",en),se.addEventListener("keydown",tn),ke.push(()=>{Ye.removeEventListener("submit",en),se.removeEventListener("keydown",tn)}),ke.push(()=>{F.cancel()}),g?ke.push(()=>{g==null||g.destroy()}):B&&ke.push(()=>{B==null||B.remove()});let be={update(a){var is,as,ls,ds,cs,us,ps,gs,hs,ms,fs,ws,ys,vs,bs,xs,Cs,Ss,As,Ts,Es,Ws,Ms,Ls,Bs,Hs,ks,Rs,Is,$s,Ps,Os,Ns,Ds,Fs,js,_s,qs,Us,zs,Ys,Js,Ks,Xs,Vs,Gs,Zs,Qs,eo,to,no,so,oo,ro,io,ao,lo;let p=t.toolCall;t={...t,...a},On(n,t),ft();let E=an.getForInstance(t.plugins);if(r.length=0,r.push(...E),w=(as=(is=t.launcher)==null?void 0:is.enabled)!=null?as:!0,_=(ds=(ls=t.launcher)==null?void 0:ls.autoExpand)!=null?ds:!1,S=(us=(cs=t.features)==null?void 0:cs.showReasoning)!=null?us:!0,Y=(gs=(ps=t.features)==null?void 0:ps.showToolCalls)!=null?gs:!0,((hs=t.launcher)==null?void 0:hs.enabled)===!1&&g&&(g.destroy(),g=null),((ms=t.launcher)==null?void 0:ms.enabled)===!1&&B&&(B.remove(),B=null),((fs=t.launcher)==null?void 0:fs.enabled)!==!1&&!g&&!B){let W=r.find(me=>me.renderLauncher);if(W!=null&&W.renderLauncher){let me=W.renderLauncher({config:t,defaultRenderer:()=>on(t,x).element,onToggle:x});me&&(B=me,n.appendChild(B))}B||(g=on(t,x),n.appendChild(g.element))}g&&g.update(t),ht&&((ws=t.launcher)==null?void 0:ws.title)!==void 0&&(ht.textContent=t.launcher.title),mt&&((ys=t.launcher)==null?void 0:ys.subtitle)!==void 0&&(mt.textContent=t.launcher.subtitle),w!==m?w?nt(_,"auto"):(C=!0,Dt()):_!==j&&nt(_,"auto"),j=_,m=w,we(),Xe(),JSON.stringify(a.toolCall)!==JSON.stringify(p)&&F&&Nt(G,F.getMessages(),$);let H=(vs=t.launcher)!=null?vs:{},v=(bs=H.headerIconHidden)!=null?bs:!1,U=H.headerIconName,O=(xs=H.headerIconSize)!=null?xs:"48px";if(he){let W=J.querySelector(".tvw-border-b-cw-divider"),me=W==null?void 0:W.querySelector(".tvw-flex-col");if(v)he.style.display="none",W&&me&&!W.contains(me)&&W.insertBefore(me,W.firstChild);else{if(he.style.display="",he.style.height=O,he.style.width=O,W&&me&&(W.contains(he)?he.nextSibling!==me&&(he.remove(),W.insertBefore(he,me)):W.insertBefore(he,me)),U){let Ee=parseFloat(O)||24,Ce=ye(U,Ee*.6,"#ffffff",2);Ce?he.replaceChildren(Ce):he.textContent=(Cs=H.agentIconText)!=null?Cs:"\u{1F4AC}"}else if(H.iconUrl){let Ee=he.querySelector("img");if(Ee)Ee.src=H.iconUrl,Ee.style.height=O,Ee.style.width=O;else{let Ce=document.createElement("img");Ce.src=H.iconUrl,Ce.alt="",Ce.className="tvw-rounded-xl tvw-object-cover",Ce.style.height=O,Ce.style.width=O,he.replaceChildren(Ce)}}else{let Ee=he.querySelector("svg"),Ce=he.querySelector("img");(Ee||Ce)&&he.replaceChildren(),he.textContent=(Ss=H.agentIconText)!=null?Ss:"\u{1F4AC}"}let Q=he.querySelector("img");Q&&(Q.style.height=O,Q.style.width=O)}}if(D){let W=(As=H.closeButtonSize)!=null?As:"32px",me=(Ts=H.closeButtonPlacement)!=null?Ts:"inline";D.style.height=W,D.style.width=W;let{closeButtonWrapper:Q}=ie,Ee=me==="top-right",Ce=Q==null?void 0:Q.classList.contains("tvw-absolute");if(Q&&Ee!==Ce)if(Q.remove(),Ee)Q.className="tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50",J.style.position="relative",J.appendChild(Q);else{let ge=(Ws=(Es=H.clearChat)==null?void 0:Es.placement)!=null?Ws:"inline",Ge=(Ls=(Ms=H.clearChat)==null?void 0:Ms.enabled)!=null?Ls:!0;Q.className=Ge&&ge==="inline"?"":"tvw-ml-auto";let Ze=J.querySelector(".tvw-border-b-cw-divider");Ze&&Ze.appendChild(Q)}if(H.closeButtonColor?(D.style.color=H.closeButtonColor,D.classList.remove("tvw-text-cw-muted")):(D.style.color="",D.classList.add("tvw-text-cw-muted")),H.closeButtonBackgroundColor?(D.style.backgroundColor=H.closeButtonBackgroundColor,D.classList.remove("hover:tvw-bg-gray-100")):(D.style.backgroundColor="",D.classList.add("hover:tvw-bg-gray-100")),H.closeButtonBorderWidth||H.closeButtonBorderColor){let ge=H.closeButtonBorderWidth||"0px",Ge=H.closeButtonBorderColor||"transparent";D.style.border=`${ge} solid ${Ge}`,D.classList.remove("tvw-border-none")}else D.style.border="",D.classList.add("tvw-border-none");H.closeButtonBorderRadius?(D.style.borderRadius=H.closeButtonBorderRadius,D.classList.remove("tvw-rounded-full")):(D.style.borderRadius="",D.classList.add("tvw-rounded-full")),H.closeButtonPaddingX?(D.style.paddingLeft=H.closeButtonPaddingX,D.style.paddingRight=H.closeButtonPaddingX):(D.style.paddingLeft="",D.style.paddingRight=""),H.closeButtonPaddingY?(D.style.paddingTop=H.closeButtonPaddingY,D.style.paddingBottom=H.closeButtonPaddingY):(D.style.paddingTop="",D.style.paddingBottom="");let Ve=(Bs=H.closeButtonIconName)!=null?Bs:"x",Fe=(Hs=H.closeButtonIconText)!=null?Hs:"\xD7";D.innerHTML="";let ut=ye(Ve,"20px",H.closeButtonColor||"",2);ut?D.appendChild(ut):D.textContent=Fe;let It=(ks=H.closeButtonTooltipText)!=null?ks:"Close chat",Te=(Rs=H.closeButtonShowTooltip)!=null?Rs:!0;if(D.setAttribute("aria-label",It),Q&&(Q._cleanupTooltip&&(Q._cleanupTooltip(),delete Q._cleanupTooltip),Te&&It)){let ge=null,Ge=()=>{if(ge||!D)return;ge=c("div","tvw-clear-chat-tooltip"),ge.textContent=It;let zt=c("div");zt.className="tvw-clear-chat-tooltip-arrow",ge.appendChild(zt);let Rn=D.getBoundingClientRect();ge.style.position="fixed",ge.style.left=`${Rn.left+Rn.width/2}px`,ge.style.top=`${Rn.top-8}px`,ge.style.transform="translate(-50%, -100%)",document.body.appendChild(ge)},Ze=()=>{ge&&ge.parentNode&&(ge.parentNode.removeChild(ge),ge=null)};Q.addEventListener("mouseenter",Ge),Q.addEventListener("mouseleave",Ze),D.addEventListener("focus",Ge),D.addEventListener("blur",Ze),Q._cleanupTooltip=()=>{Ze(),Q&&(Q.removeEventListener("mouseenter",Ge),Q.removeEventListener("mouseleave",Ze)),D&&(D.removeEventListener("focus",Ge),D.removeEventListener("blur",Ze))}}}let{clearChatButton:R,clearChatButtonWrapper:q}=ie;if(R){let W=(Is=H.clearChat)!=null?Is:{},me=($s=W.enabled)!=null?$s:!0,Q=(Ps=W.placement)!=null?Ps:"inline";if(q){q.style.display=me?"":"none";let Ee=Q==="top-right",Ce=q.classList.contains("tvw-absolute");if(Ee!==Ce&&me){if(q.remove(),Ee)q.className="tvw-absolute tvw-top-4 tvw-z-50",q.style.right="48px",J.style.position="relative",J.appendChild(q);else{q.className="tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper",q.style.right="";let Fe=J.querySelector(".tvw-border-b-cw-divider"),ut=ie.closeButtonWrapper;Fe&&ut&&ut.parentElement===Fe?Fe.insertBefore(q,ut):Fe&&Fe.appendChild(q)}let Ve=ie.closeButtonWrapper;Ve&&!Ve.classList.contains("tvw-absolute")&&(Ee?Ve.classList.add("tvw-ml-auto"):Ve.classList.remove("tvw-ml-auto"))}}if(me){let Ee=(Os=W.size)!=null?Os:"32px";R.style.height=Ee,R.style.width=Ee;let Ce=(Ns=W.iconName)!=null?Ns:"refresh-cw",Ve=(Ds=W.iconColor)!=null?Ds:"";R.innerHTML="";let Fe=ye(Ce,"20px",Ve||"",2);if(Fe&&R.appendChild(Fe),Ve?(R.style.color=Ve,R.classList.remove("tvw-text-cw-muted")):(R.style.color="",R.classList.add("tvw-text-cw-muted")),W.backgroundColor?(R.style.backgroundColor=W.backgroundColor,R.classList.remove("hover:tvw-bg-gray-100")):(R.style.backgroundColor="",R.classList.add("hover:tvw-bg-gray-100")),W.borderWidth||W.borderColor){let Te=W.borderWidth||"0px",ge=W.borderColor||"transparent";R.style.border=`${Te} solid ${ge}`,R.classList.remove("tvw-border-none")}else R.style.border="",R.classList.add("tvw-border-none");W.borderRadius?(R.style.borderRadius=W.borderRadius,R.classList.remove("tvw-rounded-full")):(R.style.borderRadius="",R.classList.add("tvw-rounded-full")),W.paddingX?(R.style.paddingLeft=W.paddingX,R.style.paddingRight=W.paddingX):(R.style.paddingLeft="",R.style.paddingRight=""),W.paddingY?(R.style.paddingTop=W.paddingY,R.style.paddingBottom=W.paddingY):(R.style.paddingTop="",R.style.paddingBottom="");let ut=(Fs=W.tooltipText)!=null?Fs:"Clear chat",It=(js=W.showTooltip)!=null?js:!0;if(R.setAttribute("aria-label",ut),q&&(q._cleanupTooltip&&(q._cleanupTooltip(),delete q._cleanupTooltip),It&&ut)){let Te=null,ge=()=>{if(Te||!R)return;Te=c("div","tvw-clear-chat-tooltip"),Te.textContent=ut;let Ze=c("div");Ze.className="tvw-clear-chat-tooltip-arrow",Te.appendChild(Ze);let zt=R.getBoundingClientRect();Te.style.position="fixed",Te.style.left=`${zt.left+zt.width/2}px`,Te.style.top=`${zt.top-8}px`,Te.style.transform="translate(-50%, -100%)",document.body.appendChild(Te)},Ge=()=>{Te&&Te.parentNode&&(Te.parentNode.removeChild(Te),Te=null)};q.addEventListener("mouseenter",ge),q.addEventListener("mouseleave",Ge),R.addEventListener("focus",ge),R.addEventListener("blur",Ge),q._cleanupTooltip=()=>{Ge(),q&&(q.removeEventListener("mouseenter",ge),q.removeEventListener("mouseleave",Ge)),R&&(R.removeEventListener("focus",ge),R.removeEventListener("blur",Ge))}}}}let $e=t.actionParsers&&t.actionParsers.length?t.actionParsers:[ln],xe=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[qt.message,qt.messageAndClick];b=dn({parsers:$e,handlers:xe,getMetadata:h,updateMetadata:d,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),$=Wo(t,b),F.updateConfig(t),Nt(G,F.getMessages(),$),et.render(t.suggestionChips,F,se,void 0,t.suggestionChipsConfig),Qt(),Ut(F.isStreaming());let re=((_s=t.voiceRecognition)==null?void 0:_s.enabled)===!0,Ne=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),dt=re&&Ne;if(Ye.classList.remove("tvw-gap-1","tvw-gap-3"),Ye.classList.add(dt?"tvw-gap-1":"tvw-gap-3"),re&&Ne)if(!M||!Me){let W=L(t.voiceRecognition,t.sendButton);W&&(M=W.micButton,Me=W.micButtonWrapper,Ye.insertBefore(Me,_e),M.addEventListener("click",st),M.disabled=F.isStreaming())}else{let W=(qs=t.voiceRecognition)!=null?qs:{},me=(Us=t.sendButton)!=null?Us:{},Q=(zs=W.iconName)!=null?zs:"mic",Ee=(Ys=me.size)!=null?Ys:"40px",Ce=(Js=W.iconSize)!=null?Js:Ee,Ve=parseFloat(Ce)||24;M.style.width=Ce,M.style.height=Ce,M.style.minWidth=Ce,M.style.minHeight=Ce;let Fe=(Xs=(Ks=W.iconColor)!=null?Ks:me.textColor)!=null?Xs:"currentColor";M.innerHTML="";let ut=ye(Q,Ve,Fe,2);ut?M.appendChild(ut):M.textContent="\u{1F3A4}";let It=(Vs=W.backgroundColor)!=null?Vs:me.backgroundColor;It?(M.style.backgroundColor=It,M.classList.remove("tvw-bg-cw-primary")):(M.style.backgroundColor="",M.classList.add("tvw-bg-cw-primary")),Fe?(M.style.color=Fe,M.classList.remove("tvw-text-white")):!Fe&&!me.textColor&&(M.style.color="",M.classList.add("tvw-text-white")),W.borderWidth?(M.style.borderWidth=W.borderWidth,M.style.borderStyle="solid"):(M.style.borderWidth="",M.style.borderStyle=""),W.borderColor?M.style.borderColor=W.borderColor:M.style.borderColor="",W.paddingX?(M.style.paddingLeft=W.paddingX,M.style.paddingRight=W.paddingX):(M.style.paddingLeft="",M.style.paddingRight=""),W.paddingY?(M.style.paddingTop=W.paddingY,M.style.paddingBottom=W.paddingY):(M.style.paddingTop="",M.style.paddingBottom="");let Te=Me==null?void 0:Me.querySelector(".tvw-send-button-tooltip"),ge=(Gs=W.tooltipText)!=null?Gs:"Start voice recognition";if(((Zs=W.showTooltip)!=null?Zs:!1)&&ge)if(Te)Te.textContent=ge,Te.style.display="";else{let Ze=document.createElement("div");Ze.className="tvw-send-button-tooltip",Ze.textContent=ge,Me==null||Me.insertBefore(Ze,M)}else Te&&(Te.style.display="none");Me.style.display="",M.disabled=F.isStreaming()}else M&&Me&&(Me.style.display="none",X&&ce());let oe=(Qs=t.sendButton)!=null?Qs:{},ct=(eo=oe.useIcon)!=null?eo:!1,kt=(to=oe.iconText)!=null?to:"\u2191",Rt=oe.iconName,Wt=(no=oe.tooltipText)!=null?no:"Send message",Ft=(so=oe.showTooltip)!=null?so:!1,jt=(oo=oe.size)!=null?oo:"40px",gn=oe.backgroundColor,At=oe.textColor;if(ct){if(P.style.width=jt,P.style.height=jt,P.style.minWidth=jt,P.style.minHeight=jt,P.style.fontSize="18px",P.style.lineHeight="1",P.innerHTML="",Rt){let W=parseFloat(jt)||24,me=At&&typeof At=="string"&&At.trim()?At.trim():"currentColor",Q=ye(Rt,W,me,2);Q?(P.appendChild(Q),P.style.color=me):(P.textContent=kt,At?P.style.color=At:P.classList.add("tvw-text-white"))}else P.textContent=kt,At?P.style.color=At:P.classList.add("tvw-text-white");P.className="tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer",gn?(P.style.backgroundColor=gn,P.classList.remove("tvw-bg-cw-primary")):P.classList.add("tvw-bg-cw-primary")}else P.textContent=(io=(ro=t.copy)==null?void 0:ro.sendButtonLabel)!=null?io:"Send",P.style.width="",P.style.height="",P.style.minWidth="",P.style.minHeight="",P.style.fontSize="",P.style.lineHeight="",P.className="tvw-rounded-button tvw-bg-cw-accent tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold tvw-text-white disabled:tvw-opacity-50 tvw-cursor-pointer",gn?(P.style.backgroundColor=gn,P.classList.remove("tvw-bg-cw-accent")):P.classList.add("tvw-bg-cw-accent"),At?P.style.color=At:P.classList.add("tvw-text-white");oe.borderWidth?(P.style.borderWidth=oe.borderWidth,P.style.borderStyle="solid"):(P.style.borderWidth="",P.style.borderStyle=""),oe.borderColor?P.style.borderColor=oe.borderColor:P.style.borderColor="",oe.paddingX?(P.style.paddingLeft=oe.paddingX,P.style.paddingRight=oe.paddingX):(P.style.paddingLeft="",P.style.paddingRight=""),oe.paddingY?(P.style.paddingTop=oe.paddingY,P.style.paddingBottom=oe.paddingY):(P.style.paddingTop="",P.style.paddingBottom="");let nn=_e==null?void 0:_e.querySelector(".tvw-send-button-tooltip");if(Ft&&Wt)if(nn)nn.textContent=Wt,nn.style.display="";else{let W=document.createElement("div");W.className="tvw-send-button-tooltip",W.textContent=Wt,_e==null||_e.insertBefore(W,P)}else nn&&(nn.style.display="none");let sn=(ao=t.statusIndicator)!=null?ao:{},Bo=(lo=sn.visible)!=null?lo:!0;if(Qe.style.display=Bo?"":"none",F){let W=F.getStatus(),me=Q=>{var Ee,Ce,Ve,Fe;return Q==="idle"?(Ee=sn.idleText)!=null?Ee:ze.idle:Q==="connecting"?(Ce=sn.connectingText)!=null?Ce:ze.connecting:Q==="connected"?(Ve=sn.connectedText)!=null?Ve:ze.connected:Q==="error"?(Fe=sn.errorText)!=null?Fe:ze.error:ze[Q]};Qe.textContent=me(W)}},open(){w&&nt(!0,"api")},close(){w&&nt(!1,"api")},toggle(){w&&nt(!C,"api")},clearChat(){F.clearMessages();try{localStorage.removeItem(Zt),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Zt}`)}catch(p){console.error("[AgentWidget] Failed to clear default localStorage:",p)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==Zt)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.clearChatHistoryStorageKey}`)}catch(p){console.error("[AgentWidget] Failed to clear custom localStorage:",p)}let a=new CustomEvent("vanilla-agent:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(a),i!=null&&i.clear)try{let p=i.clear();p instanceof Promise&&p.catch(E=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",E)})}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",p)}l={},b.syncFromMetadata()},setMessage(a){return!se||F.isStreaming()?!1:(!C&&w&&nt(!0,"system"),se.value=a,se.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(a){if(F.isStreaming())return!1;let p=(a==null?void 0:a.trim())||se.value.trim();return p?(!C&&w&&nt(!0,"system"),se.value="",F.sendMessage(p),!0):!1},startVoiceRecognition(){return X||F.isStreaming()||!Re()?!1:(!C&&w&&nt(!0,"system"),de.manuallyDeactivated=!1,ve(),Ie("user"),!0)},stopVoiceRecognition(){return X?(de.manuallyDeactivated=!0,ve(),ce("user"),!0):!1},injectTestMessage(a){!C&&w&&nt(!0,"system"),F.injectTestEvent(a)},getMessages(){return F.getMessages()},getStatus(){return F.getStatus()},getPersistentMetadata(){return{...l}},updatePersistentMetadata(a){d(a)},on(a,p){return s.on(a,p)},off(a,p){s.off(a,p)},isOpen(){return w&&C},isVoiceActive(){return de.active},getState(){return{open:w&&C,launcherEnabled:w,voiceActive:de.active,streaming:F.isStreaming()}},destroy(){ke.forEach(a=>a()),te.remove(),g==null||g.destroy(),B==null||B.remove(),qe&&D.removeEventListener("click",qe)}};if((((rs=o==null?void 0:o.debugTools)!=null?rs:!1)||!!t.debug)&&typeof window!="undefined"){let a=window.AgentWidgetBrowser,p={controller:be,getMessages:be.getMessages,getStatus:be.getStatus,getMetadata:be.getPersistentMetadata,updateMetadata:be.updatePersistentMetadata,clearHistory:()=>be.clearChat(),setVoiceActive:E=>E?be.startVoiceRecognition():be.stopVoiceRecognition()};window.AgentWidgetBrowser=p,ke.push(()=>{window.AgentWidgetBrowser===p&&(window.AgentWidgetBrowser=a)})}return be};var Gn={},or=n=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof n=="string"){let e=document.querySelector(n);if(!e)throw new Error(`Chat widget target "${n}" was not found`);return e}return n},rr=()=>{try{if(typeof Gn!="undefined"&&Gn.url)return new URL("../widget.css",Gn.url).href}catch{}return null},Mo=n=>{let e=rr(),o=()=>{if(!(n instanceof ShadowRoot)||n.querySelector("link[data-vanilla-agent]"))return;let t=document.head.querySelector("link[data-vanilla-agent]");if(!t)return;let r=t.cloneNode(!0);n.insertBefore(r,n.firstChild)};if(n instanceof ShadowRoot)if(e){let t=document.createElement("link");t.rel="stylesheet",t.href=e,t.setAttribute("data-vanilla-agent","true"),n.insertBefore(t,n.firstChild)}else o();else if(!document.head.querySelector("link[data-vanilla-agent]")&&e){let r=document.createElement("link");r.rel="stylesheet",r.href=e,r.setAttribute("data-vanilla-agent","true"),document.head.appendChild(r)}},Zn=n=>{var h,d,T,f;let e=or(n.target),o=document.createElement("div");o.className="vanilla-agent-host";let t=(T=(d=(h=n.config)==null?void 0:h.launcher)==null?void 0:d.enabled)!=null?T:!0;t||(o.style.height="100%",o.style.display="flex",o.style.flexDirection="column"),e.appendChild(o);let r=n.useShadowDom===!0,s,i;if(r){let b=o.attachShadow({mode:"open"});i=b,s=document.createElement("div"),s.id="vanilla-agent-root",t||(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0"),b.appendChild(s),Mo(b)}else i=o,s=document.createElement("div"),s.id="vanilla-agent-root",t||(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0"),o.appendChild(s),Mo(o);let l=Bn(s,n.config,{debugTools:n.debugTools});(f=n.onReady)==null||f.call(n);let u={...l,host:o,destroy(){l.destroy(),o.remove(),n.windowKey&&typeof window!="undefined"&&delete window[n.windowKey]}};return n.windowKey&&typeof window!="undefined"&&(window[n.windowKey]=u),u};function ir(n){if(!n)return null;let e=n.toString();return e.includes("createJsonStreamParser")||e.includes("partial-json")?"json":e.includes("createRegexJsonParser")||e.includes("regex")?"regex-json":e.includes("createXmlParser")||e.includes("<text>")?"xml":null}function Hn(n){var e,o;return(o=(e=n.parserType)!=null?e:ir(n.streamParser))!=null?o:"plain"}function Lo(n,e="esm"){let o={...n};return delete o.postprocessMessage,delete o.initialMessages,e==="esm"?ar(o):e==="script-installer"?cr(o):e==="script-advanced"?pr(o):e==="react-component"?lr(o):e==="react-advanced"?dr(o):ur(o)}function ar(n){let e=Hn(n),o=e!=="plain",t=["import 'vanilla-agent/widget.css';","import { initAgentWidget, markdownPostprocessor } from 'vanilla-agent';","","initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&t.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&t.push(` flowId: "${n.flowId}",`),o&&t.push(` parserType: "${e}",`),n.theme&&(t.push(" theme: {"),Object.entries(n.theme).forEach(([r,s])=>{t.push(` ${r}: "${s}",`)}),t.push(" },")),n.launcher&&(t.push(" launcher: {"),Object.entries(n.launcher).forEach(([r,s])=>{typeof s=="string"?t.push(` ${r}: "${s}",`):typeof s=="boolean"&&t.push(` ${r}: ${s},`)}),t.push(" },")),n.copy&&(t.push(" copy: {"),Object.entries(n.copy).forEach(([r,s])=>{t.push(` ${r}: "${s}",`)}),t.push(" },")),n.sendButton&&(t.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([r,s])=>{typeof s=="string"?t.push(` ${r}: "${s}",`):typeof s=="boolean"&&t.push(` ${r}: ${s},`)}),t.push(" },")),n.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([r,s])=>{typeof s=="string"?t.push(` ${r}: "${s}",`):typeof s=="boolean"?t.push(` ${r}: ${s},`):typeof s=="number"&&t.push(` ${r}: ${s},`)}),t.push(" },")),n.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([r,s])=>{typeof s=="string"?t.push(` ${r}: "${s}",`):typeof s=="boolean"&&t.push(` ${r}: ${s},`)}),t.push(" },")),n.features&&(t.push(" features: {"),Object.entries(n.features).forEach(([r,s])=>{t.push(` ${r}: ${s},`)}),t.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(t.push(" suggestionChips: ["),n.suggestionChips.forEach(r=>{t.push(` "${r}",`)}),t.push(" ],")),n.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),t.push(" },")),n.debug&&t.push(` debug: ${n.debug},`),t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),t.push(" }"),t.push("});"),t.join(`
|
|
56
|
+
`)}function lr(n){let e=Hn(n),o=e!=="plain",t=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import 'vanilla-agent/widget.css';","import { initAgentWidget, markdownPostprocessor } from 'vanilla-agent';","import type { AgentWidgetInitHandle } from 'vanilla-agent';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&t.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&t.push(` flowId: "${n.flowId}",`),o&&t.push(` parserType: "${e}",`),n.theme&&(t.push(" theme: {"),Object.entries(n.theme).forEach(([r,s])=>{t.push(` ${r}: "${s}",`)}),t.push(" },")),n.launcher&&(t.push(" launcher: {"),Object.entries(n.launcher).forEach(([r,s])=>{typeof s=="string"?t.push(` ${r}: "${s}",`):typeof s=="boolean"&&t.push(` ${r}: ${s},`)}),t.push(" },")),n.copy&&(t.push(" copy: {"),Object.entries(n.copy).forEach(([r,s])=>{t.push(` ${r}: "${s}",`)}),t.push(" },")),n.sendButton&&(t.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([r,s])=>{typeof s=="string"?t.push(` ${r}: "${s}",`):typeof s=="boolean"&&t.push(` ${r}: ${s},`)}),t.push(" },")),n.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([r,s])=>{typeof s=="string"?t.push(` ${r}: "${s}",`):typeof s=="boolean"?t.push(` ${r}: ${s},`):typeof s=="number"&&t.push(` ${r}: ${s},`)}),t.push(" },")),n.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([r,s])=>{typeof s=="string"?t.push(` ${r}: "${s}",`):typeof s=="boolean"&&t.push(` ${r}: ${s},`)}),t.push(" },")),n.features&&(t.push(" features: {"),Object.entries(n.features).forEach(([r,s])=>{t.push(` ${r}: ${s},`)}),t.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(t.push(" suggestionChips: ["),n.suggestionChips.forEach(r=>{t.push(` "${r}",`)}),t.push(" ],")),n.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),t.push(" },")),n.debug&&t.push(` debug: ${n.debug},`),t.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),t.push(" }"),t.push(" });"),t.push(""),t.push(" // Cleanup on unmount"),t.push(" return () => {"),t.push(" if (handle) {"),t.push(" handle.destroy();"),t.push(" }"),t.push(" };"),t.push(" }, []);"),t.push(""),t.push(" return null; // Widget injects itself into the DOM"),t.push("}"),t.push(""),t.push("// Usage in your app:"),t.push("// import { ChatWidget } from './components/ChatWidget';"),t.push("//"),t.push("// export default function App() {"),t.push("// return ("),t.push("// <div>"),t.push("// {/* Your app content */}"),t.push("// <ChatWidget />"),t.push("// </div>"),t.push("// );"),t.push("// }"),t.join(`
|
|
57
|
+
`)}function dr(n){let e=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import 'vanilla-agent/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from 'vanilla-agent';","import type { AgentWidgetInitHandle } from 'vanilla-agent';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.vanilla-agent-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&e.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&e.push(` flowId: "${n.flowId}",`),n.theme&&(e.push(" theme: {"),Object.entries(n.theme).forEach(([o,t])=>{e.push(` ${o}: "${t}",`)}),e.push(" },")),n.launcher&&(e.push(" launcher: {"),Object.entries(n.launcher).forEach(([o,t])=>{typeof t=="string"?e.push(` ${o}: "${t}",`):typeof t=="boolean"&&e.push(` ${o}: ${t},`)}),e.push(" },")),n.copy&&(e.push(" copy: {"),Object.entries(n.copy).forEach(([o,t])=>{e.push(` ${o}: "${t}",`)}),e.push(" },")),n.sendButton&&(e.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([o,t])=>{typeof t=="string"?e.push(` ${o}: "${t}",`):typeof t=="boolean"&&e.push(` ${o}: ${t},`)}),e.push(" },")),n.voiceRecognition&&(e.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([o,t])=>{typeof t=="string"?e.push(` ${o}: "${t}",`):typeof t=="boolean"?e.push(` ${o}: ${t},`):typeof t=="number"&&e.push(` ${o}: ${t},`)}),e.push(" },")),n.statusIndicator&&(e.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([o,t])=>{typeof t=="string"?e.push(` ${o}: "${t}",`):typeof t=="boolean"&&e.push(` ${o}: ${t},`)}),e.push(" },")),n.features&&(e.push(" features: {"),Object.entries(n.features).forEach(([o,t])=>{e.push(` ${o}: ${t},`)}),e.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(e.push(" suggestionChips: ["),n.suggestionChips.forEach(o=>{e.push(` "${o}",`)}),e.push(" ],")),n.suggestionChipsConfig&&(e.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&e.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&e.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&e.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&e.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),e.push(" },")),n.debug&&e.push(` debug: ${n.debug},`),e.push(" initialMessages: loadSavedMessages(),"),e.push(" // Flexible JSON stream parser for handling structured actions"),e.push(" streamParser: () => createFlexibleJsonStreamParser((parsed: any) => {"),e.push(" if (!parsed || typeof parsed !== 'object') return null;"),e.push(" // Extract display text based on action type"),e.push(" if (parsed.action === 'nav_then_click') return 'Navigating...';"),e.push(" if (parsed.action === 'message') return parsed.text || '';"),e.push(" if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';"),e.push(" return parsed.text || null;"),e.push(" }),"),e.push(" // Action parsers to detect JSON actions in responses"),e.push(" actionParsers: ["),e.push(" defaultJsonActionParser,"),e.push(" // Custom parser for markdown-wrapped JSON"),e.push(" ({ text, message }: any) => {"),e.push(" const jsonSource = (message as any).rawContent || text || message.content;"),e.push(" if (!jsonSource || typeof jsonSource !== 'string') return null;"),e.push(" // Strip markdown code fences"),e.push(" let cleanJson = jsonSource"),e.push(" .replace(/^```(?:json)?\\s*\\n?/, '')"),e.push(" .replace(/\\n?```\\s*$/, '')"),e.push(" .trim();"),e.push(" if (!cleanJson.startsWith('{') || !cleanJson.endsWith('}')) return null;"),e.push(" try {"),e.push(" const parsed = JSON.parse(cleanJson);"),e.push(" if (parsed.action) return { type: parsed.action, payload: parsed };"),e.push(" } catch (e) { return null; }"),e.push(" return null;"),e.push(" }"),e.push(" ],"),e.push(" // Action handlers for navigation and other actions"),e.push(" actionHandlers: ["),e.push(" defaultActionHandlers.message,"),e.push(" defaultActionHandlers.messageAndClick,"),e.push(" // Handler for nav_then_click action"),e.push(" (action: any, context: any) => {"),e.push(" if (action.type !== 'nav_then_click') return;"),e.push(" const payload = action.payload || action.raw || {};"),e.push(" const url = payload?.page;"),e.push(" const text = payload?.on_load_text || 'Navigating...';"),e.push(" if (!url) return { handled: true, displayText: text };"),e.push(" // Check if already processed"),e.push(" const messageId = context.message?.id;"),e.push(" const processedActions = JSON.parse(localStorage.getItem(PROCESSED_ACTIONS_KEY) || '[]');"),e.push(" const actionKey = `nav_${messageId}_${url}`;"),e.push(" if (processedActions.includes(actionKey)) {"),e.push(" return { handled: true, displayText: text };"),e.push(" }"),e.push(" processedActions.push(actionKey);"),e.push(" localStorage.setItem(PROCESSED_ACTIONS_KEY, JSON.stringify(processedActions));"),e.push(" const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();"),e.push(" window.location.href = targetUrl;"),e.push(" return { handled: true, displayText: text };"),e.push(" }"),e.push(" ],"),e.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),e.push(" requestMiddleware: ({ payload }) => {"),e.push(" return {"),e.push(" ...payload,"),e.push(" metadata: collectDOMContext()"),e.push(" };"),e.push(" }"),e.push(" }"),e.push(" });"),e.push(""),e.push(" // Save state on message events"),e.push(" const handleMessage = () => {"),e.push(" const session = handle?.getSession?.();"),e.push(" if (session) {"),e.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),e.push(" messages: session.messages,"),e.push(" timestamp: new Date().toISOString()"),e.push(" }));"),e.push(" }"),e.push(" };"),e.push(""),e.push(" // Clear state on clear chat"),e.push(" const handleClearChat = () => {"),e.push(" localStorage.removeItem(STORAGE_KEY);"),e.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),e.push(" };"),e.push(""),e.push(" window.addEventListener('vanilla-agent:message', handleMessage);"),e.push(" window.addEventListener('vanilla-agent:clear-chat', handleClearChat);"),e.push(""),e.push(" // Cleanup on unmount"),e.push(" return () => {"),e.push(" window.removeEventListener('vanilla-agent:message', handleMessage);"),e.push(" window.removeEventListener('vanilla-agent:clear-chat', handleClearChat);"),e.push(" if (handle) {"),e.push(" handle.destroy();"),e.push(" }"),e.push(" };"),e.push(" }, []);"),e.push(""),e.push(" return null; // Widget injects itself into the DOM"),e.push("}"),e.push(""),e.push("// Usage: Collects DOM context for AI-powered navigation"),e.push("// Features:"),e.push("// - Extracts page elements (products, buttons, links)"),e.push("// - Persists chat history across page loads"),e.push("// - Handles navigation actions (nav_then_click)"),e.push("// - Processes structured JSON actions from AI"),e.push("//"),e.push("// Example usage in Next.js:"),e.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),e.push("//"),e.push("// export default function RootLayout({ children }) {"),e.push("// return ("),e.push('// <html lang="en">'),e.push("// <body>"),e.push("// {children}"),e.push("// <ChatWidgetAdvanced />"),e.push("// </body>"),e.push("// </html>"),e.push("// );"),e.push("// }"),e.join(`
|
|
58
|
+
`)}function cr(n){let e=Hn(n),o=e!=="plain",t=["<script>"," window.siteAgentConfig = {"," target: 'body',"," config: {"];return n.apiUrl&&t.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&t.push(` flowId: "${n.flowId}",`),o&&t.push(` parserType: "${e}",`),n.theme&&(t.push(" theme: {"),Object.entries(n.theme).forEach(([r,s])=>{t.push(` ${r}: "${s}",`)}),t.push(" },")),n.launcher&&(t.push(" launcher: {"),Object.entries(n.launcher).forEach(([r,s])=>{typeof s=="string"?t.push(` ${r}: "${s}",`):typeof s=="boolean"&&t.push(` ${r}: ${s},`)}),t.push(" },")),n.copy&&(t.push(" copy: {"),Object.entries(n.copy).forEach(([r,s])=>{t.push(` ${r}: "${s}",`)}),t.push(" },")),n.sendButton&&(t.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([r,s])=>{typeof s=="string"?t.push(` ${r}: "${s}",`):typeof s=="boolean"&&t.push(` ${r}: ${s},`)}),t.push(" },")),n.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([r,s])=>{typeof s=="string"?t.push(` ${r}: "${s}",`):typeof s=="boolean"?t.push(` ${r}: ${s},`):typeof s=="number"&&t.push(` ${r}: ${s},`)}),t.push(" },")),n.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([r,s])=>{typeof s=="string"?t.push(` ${r}: "${s}",`):typeof s=="boolean"&&t.push(` ${r}: ${s},`)}),t.push(" },")),n.features&&(t.push(" features: {"),Object.entries(n.features).forEach(([r,s])=>{t.push(` ${r}: ${s},`)}),t.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(t.push(" suggestionChips: ["),n.suggestionChips.forEach(r=>{t.push(` "${r}",`)}),t.push(" ],")),n.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),t.push(" },")),n.debug&&t.push(` debug: ${n.debug},`),t.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),t.push(" }"),t.push(" };"),t.push("</script>"),t.push('<script src="https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist/install.global.js"></script>'),t.join(`
|
|
59
|
+
`)}function ur(n){let e=Hn(n),o=e!=="plain",t=["<!-- Load CSS -->",'<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist/widget.css" />',"","<!-- Load JavaScript -->",'<script src="https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist/index.global.js"></script>',"","<!-- Initialize widget -->","<script>"," window.AgentWidget.initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&t.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&t.push(` flowId: "${n.flowId}",`),o&&t.push(` parserType: "${e}",`),n.theme&&(t.push(" theme: {"),Object.entries(n.theme).forEach(([r,s])=>{t.push(` ${r}: "${s}",`)}),t.push(" },")),n.launcher&&(t.push(" launcher: {"),Object.entries(n.launcher).forEach(([r,s])=>{typeof s=="string"?t.push(` ${r}: "${s}",`):typeof s=="boolean"&&t.push(` ${r}: ${s},`)}),t.push(" },")),n.copy&&(t.push(" copy: {"),Object.entries(n.copy).forEach(([r,s])=>{t.push(` ${r}: "${s}",`)}),t.push(" },")),n.sendButton&&(t.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([r,s])=>{typeof s=="string"?t.push(` ${r}: "${s}",`):typeof s=="boolean"&&t.push(` ${r}: ${s},`)}),t.push(" },")),n.voiceRecognition&&(t.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([r,s])=>{typeof s=="string"?t.push(` ${r}: "${s}",`):typeof s=="boolean"?t.push(` ${r}: ${s},`):typeof s=="number"&&t.push(` ${r}: ${s},`)}),t.push(" },")),n.statusIndicator&&(t.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([r,s])=>{typeof s=="string"?t.push(` ${r}: "${s}",`):typeof s=="boolean"&&t.push(` ${r}: ${s},`)}),t.push(" },")),n.features&&(t.push(" features: {"),Object.entries(n.features).forEach(([r,s])=>{t.push(` ${r}: ${s},`)}),t.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(t.push(" suggestionChips: ["),n.suggestionChips.forEach(r=>{t.push(` "${r}",`)}),t.push(" ],")),n.suggestionChipsConfig&&(t.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&t.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&t.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&t.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&t.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),t.push(" },")),n.debug&&t.push(` debug: ${n.debug},`),t.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),t.push(" }"),t.push(" });"),t.push("</script>"),t.join(`
|
|
60
|
+
`)}function pr(n){let e=["<!-- Load CSS -->",'<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist/widget.css" />',"","<!-- Chat Widget Configuration -->","<script>"," window.ChatWidgetConfig = {"];return n.apiUrl&&e.push(` apiUrl: "${n.apiUrl}",`),n.flowId&&e.push(` flowId: "${n.flowId}",`),n.theme&&(e.push(" theme: {"),Object.entries(n.theme).forEach(([o,t])=>{e.push(` ${o}: "${t}",`)}),e.push(" },")),n.launcher&&(e.push(" launcher: {"),Object.entries(n.launcher).forEach(([o,t])=>{typeof t=="string"?e.push(` ${o}: "${t}",`):typeof t=="boolean"&&e.push(` ${o}: ${t},`)}),e.push(" },")),n.copy&&(e.push(" copy: {"),Object.entries(n.copy).forEach(([o,t])=>{e.push(` ${o}: "${t}",`)}),e.push(" },")),n.sendButton&&(e.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([o,t])=>{typeof t=="string"?e.push(` ${o}: "${t}",`):typeof t=="boolean"&&e.push(` ${o}: ${t},`)}),e.push(" },")),n.voiceRecognition&&(e.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([o,t])=>{typeof t=="string"?e.push(` ${o}: "${t}",`):typeof t=="boolean"?e.push(` ${o}: ${t},`):typeof t=="number"&&e.push(` ${o}: ${t},`)}),e.push(" },")),n.statusIndicator&&(e.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([o,t])=>{typeof t=="string"?e.push(` ${o}: "${t}",`):typeof t=="boolean"&&e.push(` ${o}: ${t},`)}),e.push(" },")),n.features&&(e.push(" features: {"),Object.entries(n.features).forEach(([o,t])=>{e.push(` ${o}: ${t},`)}),e.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(e.push(" suggestionChips: ["),n.suggestionChips.forEach(o=>{e.push(` "${o}",`)}),e.push(" ],")),e.push(" };"),e.push("</script>"),e.push(""),e.push("<!-- Load the widget library -->"),e.push('<script src="https://cdn.jsdelivr.net/npm/vanilla-agent@latest/dist/index.global.js"></script>'),e.push(""),e.push("<!-- Chat Widget Script with DOM Helper -->"),e.push("<script>"),e.push(" (function () {"),e.push(" 'use strict';"),e.push(" "),e.push(" const STORAGE_KEY = 'chat-widget-state';"),e.push(" const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';"),e.push(""),e.push(" // DOM context provider - extracts page elements for AI context"),e.push(" const domContextProvider = () => {"),e.push(" const selectors = {"),e.push(` products: '[data-product-id], .product-card, .product-item, [role="article"]',`),e.push(` buttons: 'button, [role="button"], .btn',`),e.push(" links: 'a[href]',"),e.push(" inputs: 'input, textarea, select'"),e.push(" };"),e.push(""),e.push(" const elements = [];"),e.push(" Object.entries(selectors).forEach(([type, selector]) => {"),e.push(" document.querySelectorAll(selector).forEach((element) => {"),e.push(" if (!(element instanceof HTMLElement)) return;"),e.push(" "),e.push(" // Exclude elements within the widget"),e.push(" const widgetHost = element.closest('.vanilla-agent-host');"),e.push(" if (widgetHost) return;"),e.push(" "),e.push(" const text = element.innerText?.trim();"),e.push(" if (!text) return;"),e.push(""),e.push(" const selectorString ="),e.push(" element.id ? `#${element.id}` :"),e.push(" element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"),e.push(" element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"),e.push(" element.tagName.toLowerCase();"),e.push(""),e.push(" const elementData = {"),e.push(" type,"),e.push(" tagName: element.tagName.toLowerCase(),"),e.push(" selector: selectorString,"),e.push(" innerText: text.substring(0, 200)"),e.push(" };"),e.push(""),e.push(" if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"),e.push(" elementData.href = element.href;"),e.push(" }"),e.push(""),e.push(" elements.push(elementData);"),e.push(" });"),e.push(" });"),e.push(""),e.push(" const counts = elements.reduce((acc, el) => {"),e.push(" acc[el.type] = (acc[el.type] || 0) + 1;"),e.push(" return acc;"),e.push(" }, {});"),e.push(""),e.push(" return {"),e.push(" page_elements: elements.slice(0, 50),"),e.push(" page_element_count: elements.length,"),e.push(" element_types: counts,"),e.push(" page_url: window.location.href,"),e.push(" page_title: document.title,"),e.push(" timestamp: new Date().toISOString()"),e.push(" };"),e.push(" };"),e.push(""),e.push(" const createWidgetConfig = (agentWidget) => ({"),e.push(" ...window.ChatWidgetConfig,"),e.push(" // Flexible JSON stream parser for handling structured actions"),e.push(" streamParser: () => agentWidget.createFlexibleJsonStreamParser((parsed) => {"),e.push(" if (!parsed || typeof parsed !== 'object') return null;"),e.push(" "),e.push(" // Extract display text based on action type"),e.push(" if (parsed.action === 'nav_then_click') {"),e.push(" return 'Navigating...';"),e.push(" } else if (parsed.action === 'message') {"),e.push(" return parsed.text || '';"),e.push(" } else if (parsed.action === 'message_and_click') {"),e.push(" return parsed.text || 'Processing...';"),e.push(" }"),e.push(" "),e.push(" return parsed.text || null;"),e.push(" }),"),e.push(" // Action parsers to detect JSON actions in responses"),e.push(" actionParsers: ["),e.push(" agentWidget.defaultJsonActionParser,"),e.push(" // Custom parser for markdown-wrapped JSON"),e.push(" ({ text, message }) => {"),e.push(" const jsonSource = message.rawContent || text || message.content;"),e.push(" if (!jsonSource || typeof jsonSource !== 'string') return null;"),e.push(" "),e.push(" // Strip markdown code fences"),e.push(" let cleanJson = jsonSource"),e.push(" .replace(/^```(?:json)?\\s*\\n?/, '')"),e.push(" .replace(/\\n?```\\s*$/, '')"),e.push(" .trim();"),e.push(" "),e.push(" if (!cleanJson.startsWith('{') || !cleanJson.endsWith('}')) return null;"),e.push(" "),e.push(" try {"),e.push(" const parsed = JSON.parse(cleanJson);"),e.push(" if (parsed.action) {"),e.push(" return { type: parsed.action, payload: parsed };"),e.push(" }"),e.push(" } catch (e) {"),e.push(" return null;"),e.push(" }"),e.push(" return null;"),e.push(" }"),e.push(" ],"),e.push(" // Action handlers for navigation and other actions"),e.push(" actionHandlers: ["),e.push(" agentWidget.defaultActionHandlers.message,"),e.push(" agentWidget.defaultActionHandlers.messageAndClick,"),e.push(" // Handler for nav_then_click action"),e.push(" (action, context) => {"),e.push(" if (action.type !== 'nav_then_click') return;"),e.push(" "),e.push(" const payload = action.payload || action.raw || {};"),e.push(" const url = payload?.page;"),e.push(" const text = payload?.on_load_text || 'Navigating...';"),e.push(" "),e.push(" if (!url) return { handled: true, displayText: text };"),e.push(" "),e.push(" // Check if already processed"),e.push(" const messageId = context.message?.id;"),e.push(" const processedActions = JSON.parse(localStorage.getItem(PROCESSED_ACTIONS_KEY) || '[]');"),e.push(" const actionKey = `nav_${messageId}_${url}`;"),e.push(" "),e.push(" if (processedActions.includes(actionKey)) {"),e.push(" return { handled: true, displayText: text };"),e.push(" }"),e.push(" "),e.push(" processedActions.push(actionKey);"),e.push(" localStorage.setItem(PROCESSED_ACTIONS_KEY, JSON.stringify(processedActions));"),e.push(" "),e.push(" const targetUrl = url.startsWith('http')"),e.push(" ? url"),e.push(" : new URL(url, window.location.origin).toString();"),e.push(" "),e.push(" window.location.href = targetUrl;"),e.push(" "),e.push(" return { handled: true, displayText: text };"),e.push(" }"),e.push(" ],"),e.push(" // Send DOM context with each request"),e.push(" requestMiddleware: ({ payload }) => ({"),e.push(" ...payload,"),e.push(" metadata: domContextProvider()"),e.push(" }),"),e.push(" postprocessMessage: ({ text }) => agentWidget.markdownPostprocessor(text)"),e.push(" });"),e.push(""),e.push(" // Initialize widget when DOM is loaded"),e.push(" function init() {"),e.push(" const agentWidget = window.AgentWidget;"),e.push(" if (!agentWidget) {"),e.push(" console.error('AgentWidget not loaded');"),e.push(" return;"),e.push(" }"),e.push(""),e.push(" const widgetConfig = createWidgetConfig(agentWidget);"),e.push(""),e.push(" // Load saved state"),e.push(" const savedState = localStorage.getItem(STORAGE_KEY);"),e.push(" if (savedState) {"),e.push(" try {"),e.push(" const { messages } = JSON.parse(savedState);"),e.push(" widgetConfig.initialMessages = messages || [];"),e.push(" } catch (e) {"),e.push(" console.error('Failed to load saved state:', e);"),e.push(" }"),e.push(" }"),e.push(""),e.push(" // Initialize widget with DOM context"),e.push(" const handle = agentWidget.initAgentWidget({"),e.push(" target: 'body',"),e.push(" useShadowDom: false,"),e.push(" config: widgetConfig"),e.push(" });"),e.push(""),e.push(" // Save state on message events"),e.push(" window.addEventListener('vanilla-agent:message', (event) => {"),e.push(" const session = handle.getSession?.();"),e.push(" if (session) {"),e.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),e.push(" messages: session.messages,"),e.push(" timestamp: new Date().toISOString()"),e.push(" }));"),e.push(" }"),e.push(" });"),e.push(""),e.push(" // Clear state on clear chat"),e.push(" window.addEventListener('vanilla-agent:clear-chat', () => {"),e.push(" localStorage.removeItem(STORAGE_KEY);"),e.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),e.push(" });"),e.push(" }"),e.push(""),e.push(" // Initialize when DOM is ready"),e.push(" if (document.readyState === 'loading') {"),e.push(" document.addEventListener('DOMContentLoaded', init);"),e.push(" } else {"),e.push(" init();"),e.push(" }"),e.push(" })();"),e.push("</script>"),e.join(`
|
|
61
|
+
`)}var gr=Zn;0&&(module.exports={AgentWidgetClient,AgentWidgetSession,DEFAULT_WIDGET_CONFIG,attachHeaderToContainer,buildComposer,buildDefaultHeader,buildExpandedHeader,buildHeader,buildHeaderWithLayout,buildMinimalHeader,componentRegistry,createActionManager,createAgentExperience,createBubbleWithLayout,createComponentMiddleware,createComponentStreamParser,createFlexibleJsonStreamParser,createJsonStreamParser,createLocalStorageAdapter,createPlainTextParser,createRegexJsonParser,createStandardBubble,createTypingIndicator,createXmlParser,defaultActionHandlers,defaultJsonActionParser,directivePostprocessor,escapeHtml,extractComponentDirectiveFromMessage,generateCodeSnippet,getHeaderLayout,hasComponentDirective,headerLayouts,initAgentWidget,isComponentDirectiveType,markdownPostprocessor,mergeWithDefaults,pluginRegistry,renderComponentDirective});
|
|
61
62
|
//# sourceMappingURL=index.cjs.map
|