@webority/chat-elements 0.165.3 → 0.165.5
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/chat-elements.js +1 -1
- package/dist/chat.global.js +18 -18
- package/dist/types/WuiChat.d.ts +3 -1
- package/dist/types/dom.d.ts +2 -0
- package/dist/types/shell-docked.d.ts +1 -0
- package/dist/types/shell-embed.d.ts +1 -0
- package/dist/types/shell-launcher.d.ts +1 -0
- package/dist/types/shell-page.d.ts +1 -0
- package/dist/web-3uVmvlge.js +1 -0
- package/dist/web.js +1 -1
- package/package.json +3 -3
- package/dist/web-D_FBKpuC.js +0 -1
package/dist/chat-elements.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{A as e,D as t,E as n,I as r,M as i,N as a,O as o,P as s,S as c,T as l,_ as u,a as d,b as f,c as p,d as m,f as h,g,j as _,k as v,l as y,m as b,n as x,o as S,p as C,r as w,s as T,w as E,x as D,y as O}from"./web-D_FBKpuC.js";import{CHAT_HANDOFF_REQUEST_ID as k,CHAT_RECENT_ROWS_MAX as A,buildTranscript as ee,createChatClient as te,createChatSession as ne,createConversationList as re,createTurnApi as ie,formatChatDate as j,formatChatDateTime as ae,formatChatDay as oe,formatChatValue as se,formatClipTime as ce,formatFigure as le,formatFileSize as ue,isHandoffTarget as M,isSafeActionHref as de,isSafePrivacyUrl as fe,loaderView as pe,mergeLabels as me,mergeLook as he,messagePlainText as N,resolveNudge as ge,showsCaptchaNote as _e,sniffAudioType as ve,toFigureRuns as ye,toFigureText as be,transcriptToText as xe,voiceClipBars as Se}from"@webority/chat-core";import{linkTarget as Ce,parseInline as we}from"@webority/markdown-core";import{COPY_FEEDBACK_MS as Te,copyTextToClipboard as Ee,emptyValueLabel as De,formatNumber as Oe,glyphNode as ke,isImeSafeEnter as Ae}from"@webority/ui-elements/helpers";import"@webority/ui-elements/elements/lightbox";import"@webority/ui-elements/elements/markdown";import"@webority/ui-elements/elements/code-block";var je=`@webority/chat-elements needs a browser DOM; import @webority/chat-core on the server`;if(typeof HTMLElement>`u`)throw Error(je);var Me=HTMLElement,P=class extends Me{#e=null;#t=null;#n=null;#r=!1;get chatPart(){return this.#e}set chatPart(e){this.#e=e,this.#i()}get message(){return this.#t}set message(e){this.#t=e,this.#i()}get turn(){return this.#n}set turn(e){this.#n=e,this.#i()}get activeTurn(){let e=this.#n;if(e===null)throw Error(`${this.localName} has no turn yet`);return e}connectedCallback(){this.#r=!0,this.#i()}disconnectedCallback(){this.#r=!1,queueMicrotask(()=>{this.isConnected||this.disposePart()})}#i(){this.#r&&this.#e&&this.#t&&this.#n&&this.renderPart(this.#e,this.#t,this.#n)}renderPart(e,t,n){throw Error(`${this.localName} must override renderPart`)}disposePart(){}};function F(e,t){typeof customElements>`u`||customElements.get(e)||customElements.define(e,t)}function I(e,t,n=null,r=null){let i=e.createElement(t);return n&&(i.className=n),r!==null&&(i.textContent=r),i}function L(e,t,n){let r=ke(t,{size:n});return r===null?null:e.adoptNode(r)}var Ne={Confirmed:`actionConfirmed`,Rejected:`actionRejected`,Expired:`actionExpired`,Failed:`actionFailed`},Pe=/^https?:\/\//i,Fe={strong:`strong`,em:`em`,strike:`s`};function R(e,t=null,n=null){let r=document.createElement(e);return t&&(r.className=t),n!=null&&(r.textContent=n),r}function Ie(e,t){return{id:e,label:t,action:`Send`,target:null,navigateAfterMs:null,icon:null,variant:null}}function Le(e){return e.type in Fe}function Re(e,t){for(let n of t)if(n.type===`text`||n.type===`citation`)e.append(document.createTextNode(n.text));else if(n.type===`link`){if(Pe.test(n.href)){let t=R(`a`);t.href=n.href,t.target=`_blank`,t.rel=`noopener noreferrer`,Re(t,n.children),e.append(t)}else Re(e,n.children)}else if(Le(n)){let t=R(Fe[n.type]);Re(t,n.children),e.append(t)}else n.type===`code`&&e.append(R(`code`,null,n.text))}function ze(e){let t=R(`p`,`wui-chat-action-consent`);return Re(t,we(e)),t}function Be(e){let t=R(`ul`,`wui-chat-action-lines`);for(let n of e)t.append(R(`li`,null,n));return t}function Ve(e){let t=R(`dl`,`wui-chat-action-lines`);for(let n of e){let e=R(`div`,`wui-chat-action-line`),r=n.indexOf(`: `);r===-1?e.append(R(`dt`,null,n)):e.append(R(`dt`,null,n.slice(0,r)),R(`dd`,null,n.slice(r+2))),t.append(e)}return t}function He(e){return typeof e!=`object`||!e||!(`message`in e)?``:typeof e.message==`string`?e.message:``}F(`wui-chat-part-action`,class extends P{_part;_turn;_working;_error;_menuOpen;constructor(){super(),this._part=null,this._turn=null,this._working=null,this._error=null,this._menuOpen=!1}renderPart(e,t,n){this._part?.actionId!==e.actionId&&(this._working=null,this._error=null,this._menuOpen=!1),this._part=e,this._turn=n,this._paint()}_paint(e=null){let t=this._part,n=this._turn;t!==null&&n!==null&&(this.replaceChildren(this._view(t,n)),e===`first`?this.querySelector(`[role="menuitem"]`)?.focus():e===`edit`&&this.querySelector(`.wui-chat-action-edit`)?.focus())}async _run(e){let t=this._part,n=this._turn;if(t===null||n===null)return;let r=t.actionId;this._working=e,this._error=null,this._paint();try{e===`confirm`?await n.confirmAction(r):await n.rejectAction(r),this._working=null}catch(e){if(this._part?.actionId!==r)return;this._working=null,this._error=He(e)||n.labels.actionFailed,this._paint()}}_view(e,t){let n=t.labels,r=e.state===`Pending`,i=t.features.LeadRecap===!0&&e.actionKind===`ChatLeadCapture`,a=i&&(e.editFields?.length??0)>0,o=R(`div`,`wui-chat-action wui-chat-action--${e.state.toLowerCase()}`);if(o.append(R(`strong`,`wui-chat-action-title`,e.title)),e.lines.length>0&&o.append(i?Ve(e.lines):Be(e.lines)),i&&e.consentText&&o.append(ze(e.consentText)),e.note&&o.append(R(`p`,`wui-chat-action-note`,e.note)),r||o.append(this._status(e,n)),(r||a)&&o.append(this._buttons(e,n,i,r,a)),e.editFields&&a&&this._menuOpen&&o.append(this._menu(e.editFields,n,t)),this._error){let e=R(`p`,`wui-chat-action-error`,this._error);e.setAttribute(`role`,`alert`),o.append(e)}return o}_status(e,t){let n=R(`p`,`wui-chat-action-status wui-chat-action-status--${e.state.toLowerCase()}`);if(e.state===`Repeat`)n.textContent=e.decidedDateTimeUtc?t.actionRepeat(j(e.decidedDateTimeUtc)):t.actionDone;else if(e.state===`Done`){if(n.append(t.actionDone),e.decidedDateTimeUtc){let t=R(`time`,null,j(e.decidedDateTimeUtc));t.dateTime=e.decidedDateTimeUtc,n.append(` `,t)}}else{let r=Ne[e.state];n.textContent=r===void 0?``:t[r]}return n}_buttons(e,t,n,r,i){let a=R(`div`,`wui-chat-action-buttons`),o=this._working;if(r){let r=n&&e.confirmLabel||t.actionConfirm,i=n&&e.rejectLabel||t.actionDismiss,s=R(`button`,`btn btn-primary btn-sm`,o===`confirm`?t.actionWorking:r);s.type=`button`,s.disabled=o!==null,s.addEventListener(`click`,()=>this._run(`confirm`));let c=R(`button`,`btn btn-soft-primary btn-sm`,i);c.type=`button`,c.disabled=o!==null,c.addEventListener(`click`,()=>this._run(`dismiss`)),a.append(s,c)}if(i){let e=R(`button`,`btn btn-soft-primary btn-sm wui-chat-action-edit`,t.editSomething);e.type=`button`,e.setAttribute(`aria-haspopup`,`menu`),e.setAttribute(`aria-expanded`,String(this._menuOpen)),e.disabled=!r||o!==null,e.addEventListener(`click`,()=>{this._menuOpen=!this._menuOpen,this._paint(this._menuOpen?`first`:`edit`)}),a.append(e)}return a}_menu(e,t,n){let r=R(`ul`,`list-group wui-chat-action-menu`);r.setAttribute(`role`,`menu`),r.setAttribute(`aria-label`,t.editSomething),r.addEventListener(`keydown`,e=>this._onMenuKey(e,r));for(let t of e){let e=R(`li`);e.setAttribute(`role`,`none`);let i=R(`button`,`list-group-item list-group-item-action wui-chat-action-menu-item`,t.label);i.type=`button`,i.setAttribute(`role`,`menuitem`),i.addEventListener(`click`,()=>{this._menuOpen=!1,n.chooseQuickReply(Ie(`lead.edit:${t.id}`,t.label)),this._paint(`edit`)}),e.append(i),r.append(e)}return r}_onMenuKey(e,t){if(e.key===`Escape`){e.preventDefault(),this._menuOpen=!1,this._paint(`edit`);return}let n=[...t.querySelectorAll(`[role="menuitem"]`)],r=document.activeElement,i=r instanceof HTMLElement?n.indexOf(r):-1,a=n.length-1,o=(/* @__PURE__ */ new Map([[`ArrowDown`,i<a?i+1:0],[`ArrowUp`,i>0?i-1:a],[`Home`,0],[`End`,a]])).get(e.key);o!==void 0&&(e.preventDefault(),n[o]?.focus())}});var Ue=null;async function We(){await import(`@webority/ui-elements/chart`),await customElements.whenDefined(`wui-chart`)}async function Ge(){return Ue??=We().catch(e=>{throw Ue=null,e}),Ue}var Ke={sub:`wui-chat-sub`,sup:`wui-chat-sup`};function z(e,t){let n=e.ownerDocument??document;for(let r of t)if(r.kind===`sub`||r.kind===`sup`){let t=n.createElement(r.kind);t.className=Ke[r.kind],t.textContent=r.text,e.append(t)}else e.append(n.createTextNode(r.text))}function B(e,t){e.replaceChildren(),z(e,ye(String(t??``)))}function V(e){return be(String(e??``))}function qe(e){return le(e)}var Je=8,Ye=8,Xe={Bar:`column`,Line:`line`,Donut:`donut`};function Ze(e,t){return e===`Bar`&&t>4?300:240}function Qe(e,t){let n=e.chartType===`Donut`,r=n?e.series.slice(0,1):e.series.slice(0,Je),i=r.map((e,n)=>({key:`s${n}`,label:V(e.name)||t.chart})),a=Object.fromEntries(i.map(e=>[e.key,null])),o=/* @__PURE__ */ new Map;r.forEach((e,t)=>{for(let n of e.points){let e=String(n.label),r=o.get(e);r===void 0&&(r={label:V(e),...a},o.set(e,r)),r[`s${t}`]=n.value}});let s=[...o.values()],c={type:Xe[e.chartType],title:V(e.title)||t.chart,x:{key:`label`,kind:`category`},series:i,data:s,height:Ze(e.chartType,s.length)};return e.chartType===`Bar`&&s.length<=Ye&&(c.x.labelFit=`all`,c.valueLabels=!0),!n&&e.unit&&(c.y={label:V(e.unit)}),s.length===0&&(c.state=`empty`,c.emptyText=t.chartEmpty),c}F(`wui-chat-part-chart`,class extends P{#e=null;#t=0;#n=null;#r=null;#i=null;#a=null;renderPart(e,t,n){let r=JSON.stringify(e);if(r===this.#e)return;this.#e=r,this.#t+=1;let i=this.#t,a=this.ownerDocument??document,o=this.#o(a);if(this.#r?.remove(),this.#r=null,e.title){let t=I(a,`figcaption`,`wui-chat-chart-title`);B(t,e.title),o.figure.prepend(t),this.#r=t}let s=this.#i;if(s!==null){let t=Qe(e,n.labels);Object.assign(s,{spec:t}),this.#s(o,s,t.state!==`empty`,n.labels)}else Ge().then(()=>{if(i!==this.#t||!this.isConnected)return;let t=Qe(e,n.labels),r=a.createElement(`wui-chart`);Object.assign(r,{spec:t}),this.#i=r,o.body.replaceChildren(r),this.#s(o,r,t.state!==`empty`,n.labels)},()=>{i===this.#t&&this.isConnected&&this.#l(o.body,n.labels)})}disposePart(){this.#t+=1,this.#e=null}#o(e){if(this.#n===null){let t=I(e,`figure`,`wui-chat-chart`),n=I(e,`div`,`wui-chat-chart-body`);t.append(n),this.replaceChildren(t),this.#n={figure:t,body:n}}return this.#n}#s(e,t,n,r){if(!n){this.#a?.remove(),this.#a=null;return}if(!this.#a){let n=I(this.ownerDocument??document,`button`,`btn btn-link btn-sm wui-chat-chart-toggle`);n.type=`button`,n.addEventListener(`click`,()=>this.#c(e,t)),e.figure.append(n),this.#a=n}let i=t.getAttribute(`view`)===`table`;this.#a.setAttribute(`aria-pressed`,String(i)),this.#a.textContent=i?r.chartShowChart:r.chartShowTable}#c(e,t){let n=this.activeTurn,r=t.getAttribute(`view`)!==`table`;t.setAttribute(`view`,r?`table`:`chart`),this.#s(e,t,!0,n.labels)}#l(e,t){let n=I(this.ownerDocument??document,`p`,`wui-chat-chart-error`,t.chartLoadFailed);n.setAttribute(`role`,`status`),e.replaceChildren(n),this.#a?.remove(),this.#a=null}});var $e={Positive:`wui-metric-tone-success`,Caution:`wui-metric-tone-warning`,Negative:`wui-metric-tone-danger`},et=/* @__PURE__ */ new Set([`Positive`,`Caution`,`Negative`]),tt=.001;function nt(e,t,n){let r=$e[t.status],i=I(e,`div`,r?`wui-metric ${r}`:`wui-metric`);i.dataset.status=t.status;let a=I(e,`div`,`wui-metric-label`);B(a,t.label);let o=I(e,`div`,`wui-metric-value`);if(z(o,t.value!==0&&Math.abs(t.value)<tt?qe(t.value):[{kind:`text`,text:Oe(t.value)}]),t.unit){let n=I(e,`span`,`wui-chat-figure-unit`);B(n,t.unit),n.prepend(` `),o.append(n)}return et.has(t.status)&&o.append(I(e,`span`,`visually-hidden`,n.figureStatus(t.status))),i.append(a,o),i}F(`wui-chat-part-figures`,class extends P{#e=null;renderPart(e,t,n){let r=JSON.stringify(e);if(r===this.#e)return;if(this.#e=r,!e.figures||e.figures.length===0){this.replaceChildren();return}let i=this.ownerDocument??document,a=I(i,`div`,`wui-chat-figures`),o=I(i,`div`,`wui-metric-strip wui-metric-strip-sm wui-chat-figures-strip`);o.setAttribute(`role`,`group`),o.setAttribute(`aria-label`,n.labels.figures);for(let t of e.figures)o.append(nt(i,t,n.labels));a.append(o),this.replaceChildren(a)}}),F(`wui-chat-part-file`,class extends P{renderPart(e,t,n){let r=n.openAttachment,i=typeof r==`function`,a=document.createElement(i?`button`:`span`);a.className=`wui-chat-file-chip`,i&&(a.setAttribute(`type`,`button`),a.setAttribute(`aria-label`,n.labels.fileOpen(e.fileName)),a.addEventListener(`click`,()=>r(e)));let o=L(document,`document-text`,16),s=document.createElement(`span`);s.className=`wui-chat-file-name`,s.textContent=e.fileName;let c=document.createElement(`span`);c.className=`wui-chat-file-size`,c.textContent=ue(e.length),a.append(...[o,s,c].filter(e=>e!==null));let l=document.createElement(`div`);l.className=`wui-chat-file`,l.append(a),this.replaceChildren(l)}});var rt={Open:`info`,InProgress:`info`,WaitingOnCustomer:`warning`,Resolved:`success`,Closed:`neutral`,Cancelled:`neutral`},it=/^\/[/\\]/,at=/^https?:\/\//i,ot=/[\t\r\n]/g;function st(e){return typeof e==`string`&&e.trim()!==``}function ct(e){return e.replace(ot,``)}function lt(e){if(typeof e!=`string`)return!1;let t=ct(e);return t.startsWith(`/`)?!it.test(t):at.test(t)}function ut(e){if(typeof e!=`string`)return`?`;let t=e.split(/\s+/).filter(Boolean).slice(0,2).map(e=>([...e][0]??``).toUpperCase()).join(``);return t===``?`?`:t}function dt(e,t){let n=e?.displayName,r=ut(st(n)?n:t),i=v(`span`,`wui-chat-avatar`,{"aria-hidden":`true`}),a=e?.avatarUrl,o=typeof a==`string`?ct(a):null;if(lt(o)){let e=v(`img`,null,{alt:``,src:o,loading:`lazy`});e.addEventListener(`error`,()=>{i.textContent=r}),i.append(e)}else i.textContent=r;return i}function ft(e,t){let n=v(`div`,`wui-chat-agent-head`),r=v(`span`,`wui-chat-agent-name`),i=e?.displayName;r.textContent=st(i)?i:t.agent;let a=v(`span`,`wui-chat-agent-role wui-chat-agent-tag`);return a.textContent=t.agent,n.append(dt(e,t.agent),r,a),n}function pt(e,t){let n=e.displayName,r=v(`li`,`wui-chat-message wui-chat-message--agent wui-chat-message--typing`),i=v(`span`,`wui-chat-typing`);for(let e=0;e<3;e+=1)i.append(v(`span`,`wui-chat-typing-dot`,{"aria-hidden":`true`}));let a=v(`span`,`visually-hidden`);return a.textContent=t.agentTyping(st(n)?n:t.agent),r.append(ft({kind:`Agent`,displayName:n,avatarUrl:null},t),i,a),r}function mt(t){return typeof t==`string`&&e(rt,t)?rt[t]??null:null}function ht(e,t){return mt(e)===null?``:t.ticketStatus(e)}var gt=/* @__PURE__ */ new Set([`Requested`,`Waiting`]),_t=/* @__PURE__ */ new Set([`Requested`,`Waiting`,`Joined`]),vt=_t;function yt(e,t){let n=e?.displayName;return typeof n==`string`&&n.trim()!==``?n:t.handoffAgentFallback}function bt(){let e=v(`div`,`wui-chat-handoff-pulses`);for(let t=0;t<3;t+=1)e.append(v(`span`,`wui-chat-handoff-pulse`,{"aria-hidden":`true`}));return e}function H(e,t,n){let r=v(e,t);return r.textContent=n,r}function xt(e,t){let n=v(`div`,`wui-chat-handoff-body`);return n.append(H(`strong`,`wui-chat-handoff-title`,e),H(`p`,`wui-chat-handoff-text`,t)),n}function St(e,t){if(typeof e.queuePosition!=`number`){let e=v(`span`,`wui-chat-system-line-stack`);return e.append(H(`p`,`wui-chat-handoff-text`,t.handoffWaiting),H(`p`,`wui-chat-handoff-text`,t.handoffQueuedText)),[bt(),e]}let n=v(`span`,`wui-chat-handoff-position`,{"aria-hidden":`true`});return n.textContent=String(e.queuePosition),[n,xt(t.handoffQueued(e.queuePosition),t.handoffQueuedText)]}function Ct(e,t){let n=yt(e.agent,t),r=v(`span`,`wui-chat-handoff-agent`);return r.append(dt(e.agent,t.handoffAgentFallback),v(`span`,`wui-chat-handoff-online`,{"aria-hidden":`true`})),[r,xt(t.handoffJoined(n),t.handoffJoinedText(n))]}function wt(e,t){switch(e.state){case`Requested`:return[bt(),H(`p`,`wui-chat-handoff-text`,t.handoffRequested)];case`Waiting`:return St(e,t);case`Joined`:return Ct(e,t);case`Left`:return[xt(t.handoffLeft(yt(e.agent,t)),t.handoffLeftText)];case`Ended`:return[xt(t.handoffEnded,t.handoffEndedText)];default:return null}}F(`wui-chat-part-handoff`,class extends P{_signature;constructor(){super(),this._signature=null}renderPart(e,t,n){let r=n.isLast,i=n.handoffSettled===!0&>.has(e.state),a=JSON.stringify([e.state,e.queuePosition,e.agent,r,n.features.HumanHandoff,n.busy,i]);if(a===this._signature)return;if(this._signature=a,i){this.replaceChildren();return}let o=wt(e,n.labels);if(o===null){this.replaceChildren();return}let s=v(`div`,`wui-chat-handoff wui-chat-handoff--${e.state.toLowerCase()}`);if(r&>.has(e.state)&&s.classList.add(`wui-chat-handoff--live`),r&&_t.has(e.state)&&s.setAttribute(`role`,`status`),vt.has(e.state)){s.classList.add(`wui-chat-system-line`);let e=v(`span`,`wui-chat-system-line-content`);e.append(...o),s.append(e)}else s.append(...o);this.replaceChildren(s)}}),F(`wui-chat-part-image`,class extends P{#e=null;#t=0;#n=null;renderPart(e,t,n){if(e.attachmentId===this.#e)return;this.#e=e.attachmentId;let r=this.ownerDocument??document,i=I(r,`figure`,`wui-chat-image`),a=I(r,`div`,`wui-chat-image-frame`);this.#n=a;let{width:o,height:s}=e;o!==null&&s!==null&&Number.isFinite(o)&&Number.isFinite(s)&&o>0&&s>0&&(a.style.aspectRatio=`${o} / ${s}`),i.append(a),this.replaceChildren(i),this.#r(e,n)}disposePart(){this.#t+=1,this.#e=null}#r(e,t){this.#t+=1;let n=this.#t,r=this.ownerDocument??document,i=this.#n;if(i===null)return;let a=I(r,`div`,`wui-chat-image-skeleton`);a.setAttribute(`aria-hidden`,`true`);let o=I(r,`span`,`visually-hidden`,t.labels.imageLoading);o.setAttribute(`role`,`status`),i.replaceChildren(a,o),typeof t.loadAttachmentUrl==`function`?t.loadAttachmentUrl(e.attachmentId).then(r=>{n===this.#t&&this.isConnected&&this.#i(r,e,t)},()=>{n===this.#t&&this.isConnected&&this.#a(e,t)}):this.#a(e,t)}#i(e,t,n){let r=this.#n;if(r===null)return;let i=this.ownerDocument??document,a=V(t.alt),o=i.createElement(`wui-lightbox`);o.setAttribute(`label`,n.labels.imageViewer),o.setAttribute(`layout`,`single`);let s=I(i,`a`,`wui-lightbox-item`);s.setAttribute(`href`,e),s.dataset.caption=a,s.dataset.name=a;let c=i.createElement(`img`);c.src=e,c.alt=a,c.decoding=`async`,s.append(c),o.append(s),r.replaceChildren(o)}#a(e,t){let n=this.#n;if(n===null)return;let r=this.ownerDocument??document,i=I(r,`p`,`wui-chat-image-error`,t.labels.imageFailed);i.setAttribute(`role`,`status`);let a=I(r,`button`,`btn btn-soft-primary btn-sm`,t.labels.retry);a.type=`button`,a.addEventListener(`click`,()=>this.#r(e,t)),n.replaceChildren(i,a)}});var Tt={Email:{type:`email`,autocomplete:`email`},Phone:{type:`tel`,autocomplete:`tel`},Name:{type:`text`,autocomplete:`name`},Company:{type:`text`,autocomplete:`organization`},Text:{type:`text`,autocomplete:null},LongText:{type:`text`,autocomplete:null}},Et=[`Open`,`Answered`,`Skipped`,`Expired`],Dt=0;function U(e){return Dt+=1,`${e}-${Dt}`}function W(e,t,n){let r=document.createElement(e);return t&&(r.className=t),n!=null&&(r.textContent=n),r}function G(){let e=W(`p`,`wui-chat-field-error`);return e.id=U(`wui-chat-field-error`),e.setAttribute(`role`,`alert`),e.hidden=!0,e}function K(e,t){return e.required?[]:[W(`span`,`wui-chat-field-hint`,t.inputOptional)]}function Ot(e,t,n){let r=U(`wui-chat-field`),i=Tt[t],a=t===`LongText`&&!e.secret,o;if(a){let e=W(`textarea`,`form-control wui-chat-input-control`);e.rows=3,o=e}else{let t=W(`input`,`form-control wui-chat-input-control`);t.type=e.secret?`password`:i.type,e.secret?t.autocomplete=`off`:i.autocomplete&&(t.autocomplete=i.autocomplete),o=t}o.id=r,o.name=e.key,e.placeholder!=null&&(o.placeholder=e.placeholder),e.maxLength!=null&&(o.maxLength=e.maxLength),e.required&&o.setAttribute(`aria-required`,`true`);let s=W(`label`,`form-label`,e.label);s.htmlFor=r;let c=G();o.setAttribute(`aria-describedby`,c.id);let l=W(`div`,`wui-chat-field`);return l.dataset.key=e.key,l.append(s,...K(e,n),o,c),{field:e,element:l,controls:[o],focus:o,invalid:o,error:c,control:o,read:()=>e.secret?o.value:o.value.trim()}}function kt(e,t,n,r,i){let a=e.control,o=W(`button`,`btn btn-soft-primary`,n.inputSendCode);o.type=`button`,o.dataset.wui=`AppButton`;let s=W(`p`,`wui-chat-field-hint`);s.setAttribute(`aria-live`,`polite`);let c=U(`wui-chat-field`),l=W(`label`,`form-label`,n.inputEnterCode);l.htmlFor=c,l.hidden=!0;let u=W(`input`,`form-control wui-chat-input-control`);return u.type=`text`,u.id=c,u.inputMode=`numeric`,u.autocomplete=`one-time-code`,u.hidden=!0,o.addEventListener(`click`,async()=>{o.disabled=!0;try{await r.sendOtp(i,{fieldKey:t.key,value:a.value.trim()}),s.textContent=n.inputCodeSent,l.hidden=!1,u.hidden=!1}catch{s.textContent=n.inputCodeFailed}finally{o.disabled=!1}}),e.element.insertBefore(o,e.error),e.element.insertBefore(s,e.error),e.element.insertBefore(l,e.error),e.element.insertBefore(u,e.error),{...e,controls:[...e.controls,o,u],codeRead:()=>u.value.trim()}}function At(e,t){let n=U(`wui-chat-field-label`),r=W(`span`,`form-label`,e.label);r.id=n;let i=W(`div`);i.setAttribute(`role`,`radiogroup`),i.setAttribute(`aria-labelledby`,n);let a=G();i.setAttribute(`aria-describedby`,a.id);let o=[];for(let t of e.options??[]){let n=W(`div`,`form-check`),r=W(`input`,`form-check-input`);r.type=`radio`,r.name=e.key,r.value=t.id,r.id=U(`wui-chat-option`);let a=W(`label`,`form-check-label`,t.label);a.htmlFor=r.id,n.append(r,a),i.append(n),o.push(r)}o.length===0&&(i.tabIndex=-1);let s=W(`div`,`wui-chat-field`);return s.dataset.key=e.key,s.append(r,...K(e,t),i,a),{field:e,element:s,controls:o,focus:o[0]??i,invalid:i,error:a,read:()=>o.find(e=>e.checked)?.value??``}}function jt(e,t){let n=U(`wui-chat-field-label`),r=W(`span`,`form-label`,e.label);r.id=n;let i=W(`div`,`wui-chat-input-choices`);i.setAttribute(`role`,`group`),i.setAttribute(`aria-labelledby`,n);let a=G();i.setAttribute(`aria-describedby`,a.id);let o=[];for(let t of e.options??[]){let n=W(`div`,`form-check`),r=W(`input`,`form-check-input`);r.type=`checkbox`,r.name=e.key,r.value=t.id,r.id=U(`wui-chat-option`);let a=W(`label`,`form-check-label`,t.label);a.htmlFor=r.id,n.append(r,a),i.append(n),o.push(r)}o.length===0&&(i.tabIndex=-1);let s=W(`div`,`wui-chat-field`);return s.dataset.key=e.key,s.append(r,...K(e,t),i,a),{field:e,element:s,controls:o,focus:o[0]??i,invalid:i,error:a,read:()=>JSON.stringify(o.filter(e=>e.checked).map(e=>e.value))}}function Mt(e,t){let n=U(`wui-chat-field-label`),r=W(`span`,`form-label`,e.label);r.id=n;let i=W(`div`,`wui-chat-input-slots`);i.setAttribute(`role`,`radiogroup`),i.setAttribute(`aria-labelledby`,n);let a=G();i.setAttribute(`aria-describedby`,a.id);let o=new Intl.DateTimeFormat(void 0,{weekday:`short`,day:`numeric`,month:`short`,hour:`numeric`,minute:`2-digit`}),s=[];for(let t of e.slots??[]){let n=W(`input`,`wui-chat-input-slot-radio`);n.type=`radio`,n.name=e.key,n.value=t.id,n.id=U(`wui-chat-slot`);let r=W(`label`,`btn btn-soft-primary wui-chat-input-slot`,o.format(new Date(t.startDateTimeUtc)));r.htmlFor=n.id,i.append(n,r),s.push(n)}s.length===0&&(i.tabIndex=-1);let c=W(`div`,`wui-chat-field`);return c.dataset.key=e.key,c.append(r,...K(e,t),i,a),{field:e,element:c,controls:s,focus:s[0]??i,invalid:i,error:a,read:()=>s.find(e=>e.checked)?.value??``}}function Nt(e,t,n){let r=U(`wui-chat-field-label`),i=W(`span`,`form-label`,e.label);i.id=r;let a=G(),o=W(`input`);o.type=`file`,o.name=e.key,o.id=U(`wui-chat-field`),o.hidden=!0,e.accept?.length&&(o.accept=e.accept.join(`,`));let s=W(`button`,`btn btn-soft-primary`,t.inputChooseFile);s.type=`button`,s.dataset.wui=`AppButton`,s.setAttribute(`aria-describedby`,a.id),s.addEventListener(`click`,()=>o.click());let c=W(`span`,`wui-chat-input-file-status`);c.setAttribute(`aria-live`,`polite`);let l=W(`button`,`btn btn-link-primary`);l.type=`button`,l.dataset.wui=`AppButton`,l.hidden=!0;let u=W(`div`,`wui-chat-input-file`);u.setAttribute(`role`,`group`),u.setAttribute(`aria-labelledby`,r),u.append(s,c,l,o);let d=`empty`,f=``,p=``,m=0,h=()=>{c.textContent=d===`uploading`?`${t.attachmentUploading} ${f}`:f,l.hidden=f===``,l.textContent=f===``?``:t.inputRemoveFile(f);let e=d===`failed`;a.textContent=e?t.attachmentFailed:``,a.hidden=!e,e?u.setAttribute(`aria-invalid`,`true`):u.removeAttribute(`aria-invalid`)},g=async e=>{m+=1;let t=m;d=`uploading`,f=e.name,p=``,h();try{let r=await n.uploadInputFile(e);if(t!==m)return;p=r,d=`ready`}catch{if(t!==m)return;d=`failed`}h()};o.addEventListener(`change`,()=>{let e=o.files?.[0];e&&g(e)}),l.addEventListener(`click`,()=>{m+=1,d=`empty`,f=``,p=``,o.value=``,h()}),h();let _=W(`div`,`wui-chat-field`);return _.dataset.key=e.key,_.append(i,...K(e,t),u,a),{field:e,element:_,controls:[s,l,o],focus:s,invalid:u,error:a,read:()=>d===`ready`?p:``,uploadProblem:()=>d===`uploading`?t.attachmentUploading:d===`failed`?t.attachmentFailed:null}}function Pt(e){let t=W(`input`,`form-check-input`);t.type=`checkbox`,t.name=e.key,t.id=U(`wui-chat-field`);let n=W(`label`,`form-check-label`,e.consentText||e.label);n.htmlFor=t.id;let r=G();t.setAttribute(`aria-describedby`,r.id);let i=W(`div`,`form-check`);i.append(t,n);let a=W(`div`,`wui-chat-field`);return a.dataset.key=e.key,a.append(i,r),{field:e,element:a,controls:[t],focus:t,invalid:t,error:r,read:()=>t.checked?`true`:`false`}}function Ft(e,t,n,r){if(e.type===`Choice`)return At(e,t);if(e.type===`MultiChoice`)return jt(e,t);if(e.type===`TimeSlot`)return Mt(e,t);if(e.type===`File`)return Nt(e,t,n);if(e.type===`Consent`)return Pt(e);let i=Ot(e,e.type,t);return e.verify===`Otp`?kt(i,e,t,n,r):i}function It(e,t,n){let r=e.uploadProblem?.();if(r)return r;let{field:i}=e;return i.required?i.type===`Consent`?t===`true`?null:n.inputConsentRequired:i.type===`MultiChoice`?t===`[]`?n.inputRequired:null:t===``?n.inputRequired:null:null}function Lt(e,t){return e.state===`Answered`?W(`p`,`wui-chat-input-summary`,e.answeredSummary||t.inputAnswered):W(`p`,`wui-chat-input-summary`,e.state===`Skipped`?t.inputSkipped:t.inputExpired)}F(`wui-chat-part-input-request`,class extends P{_signature;_generation;constructor(){super(),this._signature=null,this._generation=0}renderPart(e,t,n){for(let t of Et)this.classList.toggle(`wui-chat-input-request--${t.toLowerCase()}`,e.state===t);let r=JSON.stringify([e.requestId,e.state,e.answeredSummary,e.fields]);r!==this._signature&&(this._signature=r,this._generation+=1,this.replaceChildren(this._content(e,n)))}_content(e,t){return e.state===`Open`?this._form(e,this._generation):Lt(e,t.labels)}_form(e,t){let n=this.activeTurn,r=n.labels,i=n.features,a=W(`form`,`wui-chat-input-form`);a.noValidate=!0,a.setAttribute(`aria-label`,e.title||e.submitLabel),e.title&&a.append(W(`h3`,`wui-chat-input-title`,e.title));let o=e.fields.map(t=>Ft(t,r,n,e.requestId));for(let e of o)a.append(e.element);let s=W(`p`,`wui-chat-input-error`);s.setAttribute(`role`,`status`),s.hidden=!0,a.append(s);let c=W(`button`,`btn btn-primary`,e.submitLabel);c.type=`submit`,c.dataset.wui=`AppButton`;let l=W(`div`,`d-flex flex-wrap gap-2`);l.append(c);let u=[c];if(i.LeadShortcuts&&e.fields.length===1&&!e.fields[0]?.required){let t=W(`button`,`btn btn-soft-primary`,r.skip);t.type=`button`,t.dataset.wui=`AppButton`,t.addEventListener(`click`,()=>this.activeTurn.skipInput(e.requestId)),l.append(t),u.push(t)}if(i.LeadShortcuts&&e.cancellable){let e=W(`button`,`btn btn-link-primary`,r.cancel);e.type=`button`,e.dataset.wui=`AppButton`,e.addEventListener(`click`,()=>this.activeTurn.cancelLead()),l.append(e),u.push(e)}a.append(l),e.allowTyped&&a.append(W(`p`,`wui-chat-input-typed`,r.typeAnswer));let d=!1,f=t=>{for(let e of o)for(let n of e.controls)n.disabled=t;for(let e of u)e.disabled=t;c.textContent=t?r.inputSubmitting:e.submitLabel},p=()=>{for(let e of o)e.error.hidden=!0,e.error.textContent=``,e.invalid.removeAttribute(`aria-invalid`);s.hidden=!0,s.textContent=``},m=(e,t)=>{e.error.textContent=t,e.error.hidden=!1,e.invalid.setAttribute(`aria-invalid`,`true`)};return a.addEventListener(`submit`,async n=>{if(n.preventDefault(),d)return;p();let i={},a={},l=[];for(let e of o){let t=e.read();i[e.field.key]=t,e.codeRead&&(a[e.field.key]=e.codeRead());let n=It(e,t,r);n&&l.push([e,n])}let[u]=l;if(u){for(let[e,t]of l)m(e,t);u[0].focus.focus();return}d=!0,f(!0);let h;try{h=await this.activeTurn.answerInput(e.requestId,i,Object.keys(a).length>0?a:null)}catch{h={ok:!1,errors:{},message:r.errorGeneric}}if(t!==this._generation||h.ok)return;d=!1;let g=null;for(let e of o){let t=h.errors?.[e.field.key];t&&(m(e,t),g??=e)}h.message!=null&&(s.textContent=h.message,s.hidden=!1),f(!1),g?g.focus.focus():o[0]?o[0].focus.focus():c.focus()}),a}});var Rt={ActionLimitReached:`warning`,ConversationTooLong:`warning`,AssistantUnavailable:`danger`},zt={info:`info`,warning:`alert-triangle`,danger:`alert-circle`};function Bt(e,t){let n=I(e,`a`,`wui-chat-notice-row`);if(n.href=t.href,/^https?:/i.test(t.href)&&(n.target=`_blank`,n.rel=`noopener noreferrer`),t.icon){let r=I(e,`span`,`wui-chat-notice-row-icon`);r.setAttribute(`aria-hidden`,`true`);let i=L(e,t.icon,18);i&&r.append(i),n.append(r)}let r=I(e,`span`,`wui-chat-notice-row-text`);r.append(I(e,`strong`,`wui-chat-notice-row-title`,t.title)),t.detail&&r.append(I(e,`span`,`wui-chat-notice-row-detail`,t.detail));let i=I(e,`span`,`wui-chat-notice-row-arrow`);i.setAttribute(`aria-hidden`,`true`);let a=L(e,`arrow-right`,16);return a&&i.append(a),n.append(r,i),n}F(`wui-chat-part-notice`,class extends P{renderPart(e){let t=this.ownerDocument??document,n=Rt[e.code]??`info`,r=I(t,`div`,`wui-chat-notice wui-chat-notice--${n}`);r.setAttribute(`role`,n===`danger`?`alert`:`status`);let i=I(t,`span`,`wui-chat-notice-icon`);i.setAttribute(`aria-hidden`,`true`);let a=L(t,zt[n],16);a&&i.append(a);let o=I(t,`div`,`wui-chat-notice-body`);o.append(I(t,`span`,`wui-chat-notice-text`,e.text));let s=e.action;if(s){let e=I(t,`button`,`wui-chat-notice-action`,s.label);e.type=`button`,e.addEventListener(`click`,()=>s.run()),o.append(e)}let c=(e.actions??[]).filter(e=>de(e.href));if(c.length>0){let e=I(t,`div`,`wui-chat-notice-rows`);for(let n of c)e.append(Bt(t,n));o.append(e)}r.append(i,o),this.replaceChildren(r)}});function Vt(e){switch(e){case`Primary`:return`wui-chat-quick-reply--primary`;case`Cta`:return`wui-chat-quick-reply--cta`;case`Default`:case null:return``}}F(`wui-chat-part-quick-replies`,class extends P{#e=null;renderPart(e,t,n){let r=n.features.SuggestedReplies===!0&&n.isLast===!0&&n.busy===!1&&e.replies.length>0,i=typeof n.openTarget==`function`,a=typeof n.beginHandoff==`function`,o=n.handoffPause===!0,s=JSON.stringify([r,e.replies,e.placement,n.labels.quickReplies,n.labels.handoffMoment,i,a,o,n.handoffHosts??null,n.features.LinkHandoff===!0]);if(s===this.#e)return;this.#e=s;let c=this.querySelector(`:scope > .wui-chat-quick-replies:not(.wui-chat-quick-replies--leaving)`);if(!r&&c){this.#t(c);return}if(this.replaceChildren(),!r)return;let l=this.ownerDocument,u=e.placement===`Composer`,d=I(l,`div`,u?`wui-chat-quick-replies wui-chat-quick-replies--composer`:`wui-chat-quick-replies`);d.setAttribute(`role`,`group`),d.setAttribute(`aria-label`,n.labels.quickReplies);let f=u?null:e.replies.find(e=>e.id===k&&e.action===`Send`),p=0;f&&(d.classList.add(`wui-chat-quick-replies--offer`),d.append(this.#n(l,f,n)),p+=1);for(let t of e.replies){if(t===f||t.action===`Open`&&(!t.target||!i))continue;let e=null;if(t.action===`Navigate`){if(n.features.LinkHandoff!==!0)continue;if(M(t.target,n.handoffHosts))e=t.target;else{let r=t.target===null?null:n.resolveLink?.(t.target);e=typeof r==`string`&&r!==``?r:null}if(e===null){d.append(I(l,`span`,null,t.label));continue}if(!a)continue}d.append(this.#r(l,t,p,n,f?`wui-chat-quick-reply--quiet`:``,e)),p+=1}if(o){let e=I(l,`span`,`visually-hidden`,n.labels.handoffMoment);e.setAttribute(`role`,`status`),d.append(e)}d.childElementCount>0&&this.append(d)}#t(e){e.classList.add(`wui-chat-quick-replies--leaving`);let t=this.ownerDocument.defaultView,n=Number.parseFloat(t?t.getComputedStyle(e).animationDuration:``)*1e3;t===null||!(n>0)?e.remove():t.setTimeout(()=>e.remove(),n)}#n(e,t,n){let r=I(e,`div`,`wui-chat-offer`);return r.style.setProperty(`--wui-chat-i`,`0`),r.append(I(e,`div`,`wui-chat-offer-title`,t.label)),r.append(this.#r(e,{...t,variant:`Primary`},0,n,`wui-chat-offer-action`)),r}#r(e,t,n,r,i=``,a=null){let o=e.createElement(`button`);o.type=`button`,o.className=[`wui-chat-quick-reply`,Vt(t.variant),i].filter(Boolean).join(` `),o.style.setProperty(`--wui-chat-i`,String(n));let s=t.action===`Navigate`,c=s&&r.handoffPause===!0;if(o.disabled=c,t.icon){let n=L(e,t.icon,16);if(n){let t=I(e,`span`,`wui-chat-quick-reply-icon`);t.setAttribute(`aria-hidden`,`true`),t.append(n),o.append(t)}}return o.append(I(e,`span`,`wui-chat-quick-reply-label`,c?r.labels.handoffMoment:t.label)),o.addEventListener(`click`,()=>{if(t.action===`Open`){let{openTarget:e}=this.activeTurn;if(t.target===null||e===void 0)throw Error(`${this.localName} drew an Open chip without a target or openTarget`);e.call(this.activeTurn,t.target)}else if(s){let{beginHandoff:e}=this.activeTurn;if(a===null||e===void 0)throw Error(`${this.localName} drew a Navigate chip without a destination or beginHandoff`);e.call(this.activeTurn,t,()=>this.#i(a))}else this.activeTurn.chooseQuickReply(t),this.closest(`.wui-chat`)?.querySelector(`.wui-chat-input`)?.focus()}),o}#i(e){typeof this.activeTurn.openTarget==`function`?this.activeTurn.openTarget(e):globalThis.location.assign(e)}});var Ht=/* @__PURE__ */ new Set([`Integer`,`Decimal`,`MoneyMinor`,`Percent`]);function Ut(e){return Ht.has(e)}function Wt(e,t,n,r=!0){let i=e=>r?ye(e):[{kind:`text`,text:e}];if(t==null||t===``)return[{kind:`text`,text:De()}];if(e===`Date`||e===`DateTimeUtc`)return[{kind:`text`,text:se(t,e,n)}];if(Ut(e)){let r=Number(t);return i(Number.isFinite(r)?se(r,e,n):String(t))}return i(String(t))}var Gt=0;function Kt(e){return Gt+=1,`${e}-${Gt}`}F(`wui-chat-part-record-card`,class extends P{#e=null;renderPart(e,t,n){let r=!!e.target&&typeof n.openRecord==`function`,i=n.features?.FigureText===!0,a=JSON.stringify([e,r,i]);if(a===this.#e)return;this.#e=a;let o=this.ownerDocument,s=I(o,`article`,`wui-chat-record`),c=Kt(`wui-chat-record-title`);s.setAttribute(`aria-labelledby`,c);let l=I(o,`div`,`wui-chat-record-head`),u=I(o,`strong`,`wui-chat-record-title`);if(u.id=c,u.setAttribute(`role`,`heading`),u.setAttribute(`aria-level`,`3`),i?B(u,e.title):u.textContent=String(e.title??``),l.append(u),e.subtitle){let t=I(o,`span`,`wui-chat-record-subtitle`);i?B(t,e.subtitle):t.textContent=String(e.subtitle??``),l.append(t)}if(s.append(l),e.fields?.length>0){let t=I(o,`dl`,`wui-chat-record-fields`);for(let n of e.fields){let e=I(o,`div`),r=I(o,`dt`);i?B(r,n.label):r.textContent=String(n.label??``);let a=I(o,`dd`);Ut(n.type)&&(a.className=`wui-chat-num`),z(a,Wt(n.type,n.value,null,i)),e.append(r,a),t.append(e)}s.append(t)}if(r){let t=I(o,`button`,`btn btn-soft-primary btn-sm wui-chat-record-open`,n.labels.recordOpen);t.type=`button`,t.setAttribute(`aria-label`,n.labels.recordOpenFor(V(e.title))),t.addEventListener(`click`,()=>{let{openRecord:t}=this.activeTurn;if(t===void 0)throw Error(`${this.localName} lost openRecord after it drew the button`);t.call(this.activeTurn,e)}),s.append(t)}this.replaceChildren(s)}});var qt=/^https?:\/\//i;F(`wui-chat-part-sources`,class extends P{renderPart(e,t,n){if(this.replaceChildren(),!n.features.Sources||e.sources.length===0)return;let r=this.ownerDocument,i=I(r,`div`,`wui-chat-sources`);i.append(I(r,`p`,`wui-chat-sources-label`,n.labels.sources));let a=I(r,`ul`,`wui-chat-sources-list`);a.setAttribute(`aria-label`,n.labels.sources);for(let t of e.sources){let e=r.createElement(`li`);e.append(this.#e(r,t,n)),a.append(e)}i.append(a),this.append(i)}#e(e,t,n){let r;if(typeof t.url==`string`&&qt.test(t.url)){let i=I(e,`a`,`wui-chat-source`);i.setAttribute(`href`,t.url),i.setAttribute(`target`,`_blank`),i.setAttribute(`rel`,`noopener noreferrer`),i.setAttribute(`aria-label`,n.labels.openSource(t.title)),r=i}else r=I(e,`span`,`wui-chat-source`),r.tabIndex=-1;return r.dataset.marker=String(t.marker),r.append(I(e,`span`,`wui-chat-source-marker`,String(t.marker)),I(e,`span`,`wui-chat-source-title`,t.title)),r}});var Jt=25,Yt=0;function Xt(e,t,n){let r=e.createElement(`tr`);for(let i of t.columns){let t=e.createElement(`th`);t.setAttribute(`scope`,`col`),Ut(i.type)&&(t.className=`wui-chat-num`),n?B(t,i.label):t.textContent=String(i.label??``),r.append(t)}return r}function Zt(e,t,n,r){let i=e.createElement(`tr`);return t.columns.forEach((a,o)=>{let s=o===0&&a.type===`Text`,c=e.createElement(s?`th`:`td`);s&&c.setAttribute(`scope`,`row`),Ut(a.type)&&(c.className=`wui-chat-num`);let l=n[o];l==null||l===``?c.append(I(c.ownerDocument,`span`,`wui-chat-null`,De())):z(c,Wt(a.type,l,t.currency,r)),i.append(c)}),i}function Qt(e,t){let n=()=>{let n=t.scrollWidth-t.clientWidth;e.dataset.scroll=n<=1?`none`:t.scrollLeft>=n-1?`end`:t.scrollLeft>0?`middle`:`start`};t.addEventListener(`scroll`,n,{passive:!0}),typeof ResizeObserver<`u`&&new ResizeObserver(n).observe(t),n()}function $t(e,t,n,r,i){let a=e.ownerDocument;for(let o of t.rows.slice(n,r))e.append(Zt(a,t,o,i))}F(`wui-chat-part-table`,class extends P{#e=null;renderPart(e,t,n){let r=n.features?.FigureText===!0,i=JSON.stringify([e,r]);if(i===this.#e)return;if(this.#e=i,!e.columns||e.columns.length===0){this.replaceChildren();return}let a=this.ownerDocument,o=I(a,`figure`,`wui-chat-table`),s=null;if(e.title){Yt+=1,s=`wui-chat-table-${Yt}`;let t=I(a,`figcaption`,`wui-chat-table-title`);t.id=s,r?B(t,e.title):t.textContent=String(e.title??``),o.append(t)}let c=I(a,`div`,`table-wrap wui-chat-table-wrap`);c.tabIndex=0,c.setAttribute(`role`,`region`),s?c.setAttribute(`aria-labelledby`,s):c.setAttribute(`aria-label`,n.labels.table);let l=I(a,`table`,`table table-sm wui-chat-table-grid`),u=a.createElement(`thead`);u.append(Xt(a,e,r));let d=a.createElement(`tbody`);$t(d,e,0,Math.min(e.rows.length,Jt),r),l.append(u,d),c.append(l);let f=I(a,`div`,`wui-chat-table-frame`),p=I(a,`span`,`wui-chat-table-cue`);if(p.setAttribute(`aria-hidden`,`true`),f.append(c,p),o.append(f),Qt(f,c),e.rows.length>Jt){let t=I(a,`button`,`btn btn-soft-primary btn-sm wui-chat-table-more`,n.labels.tableShowAll(e.rows.length));t.type=`button`,t.addEventListener(`click`,()=>{$t(d,e,Jt,e.rows.length,r),t.remove()}),o.append(t)}this.replaceChildren(o)}});var en=/* @__PURE__ */ new Set([`Visitor`,`Customer`]),tn=/^\d+$/;function nn(e,t){return e?.features?.Sources===!0?typeof e?.isCitation==`function`?e.isCitation(t):tn.test(t):!1}function rn(e,t){if(M(e,t?.handoffHosts))return e;let n=t?.resolveLink?.(e);return typeof n==`string`&&n!==``?n:null}function an(e,t){let n=globalThis.location?.origin;for(let r of e.querySelectorAll(`a[href]`)){let e=r.dataset.linkSource??r.getAttribute(`href`)??``;r.dataset.linkSource=e;let i=rn(e,t);i===null?r.replaceWith(r.ownerDocument.createTextNode(r.textContent??``)):(i!==r.getAttribute(`href`)&&r.setAttribute(`href`,i),Ce(i,`web`,void 0,n)?.kind===`web`?(r.setAttribute(`target`,`_blank`),r.setAttribute(`rel`,`noopener noreferrer`)):(r.removeAttribute(`target`),r.removeAttribute(`rel`)))}}function on(e,t){an(e,t)}F(`wui-chat-part-text`,class extends P{#e=null;#t=null;#n=!1;#r=null;constructor(){super(),this.addEventListener(`wui-markdown-citation`,e=>{let t=this.turn;typeof t?.openCitation==`function`&&t.openCitation(Number(e.detail.citation))}),this.addEventListener(`click`,e=>this.#a(e))}renderPart(e,t,n){let r=en.has(t.author.kind)?`plain`:`markdown`,i=this.#e;if((i===null||i.mode!==r)&&(i=r===`plain`?{mode:r,node:this.#s()}:this.#c(e.text),this.#e=i,this.#t=null,this.replaceChildren(i.node)),i.mode===`plain`){let t=this.turn?.features?.FigureText===!0,n=JSON.stringify([e.text,t]);n!==this.#t&&(this.#t=n,i.node.replaceChildren(),t?z(i.node,ye(e.text)):i.node.append(this.ownerDocument.createTextNode(e.text)))}else this.#o(i.node),i.source.textContent!==e.text&&(i.source.textContent=e.text);this.toggleAttribute(`data-streaming`,t.streaming===!0),this.#n||(this.#n=!0,this.closest(`[data-restored]`)||this.classList.add(`wui-chat-part-enter`)),this.#i()}disposePart(){this.#r?.disconnect(),this.#r=null}#i(){this.#r||(this.#r=new MutationObserver(()=>on(this,this.turn)),this.#r.observe(this,{childList:!0,subtree:!0,characterData:!0}),on(this,this.turn))}#a(e){let t=e.target instanceof Element?e.target.closest(`a[href]`):null,n=this.turn;if(!t||!this.contains(t))return;let r=t.getAttribute(`href`)??``;r.startsWith(`#`)||(r.startsWith(`/`)&&typeof n?.onNavigate==`function`?(e.preventDefault(),n.onNavigate(r)):typeof n?.openTarget==`function`&&(e.preventDefault(),n.openTarget(r)))}#o(e){let t=this.turn?.features?.FigureText===!0?ye:void 0;e.figureText!==t&&(e.figureText=t)}#s(){return I(this.ownerDocument,`div`,`wui-chat-bubble`)}#c(e){let t=this.ownerDocument,n=I(t,`wui-markdown`,`wui-markdown wui-chat-text`);n.setAttribute(`links`,`web`),n.setAttribute(`headings`,`text`),n.isCitation=e=>nn(this.turn,e);let r=I(t,`pre`,`wui-markdown-source`,e);return n.append(r),{mode:`markdown`,node:n,source:r}}}),F(`wui-chat-part-ticket`,class extends P{renderPart(e,t,n){let{labels:r}=n,i=v(`article`,`wui-chat-ticket`,{"aria-label":r.ticketAria(e.number)}),a=v(`div`,`wui-chat-ticket-head`),o=v(`span`,`wui-chat-ticket-number`);o.textContent=r.ticketAria(e.number),a.append(o);let s=mt(e.status);if(s!==null){let t=v(`span`,`wui-chat-ticket-badge wui-chat-ticket-badge--${s}`);t.textContent=ht(e.status,r),a.append(t)}let c=v(`strong`,`wui-chat-ticket-title`);if(c.textContent=e.subject,i.append(a,c),typeof n.openTicket==`function`){let t=v(`div`,`wui-chat-ticket-foot`),a=v(`button`,`wui-chat-ticket-link`,{type:`button`});a.textContent=r.ticketView,a.addEventListener(`click`,()=>{let{openTicket:t}=n;if(t===void 0)throw Error(`${this.localName} lost openTicket after it drew the link`);t.call(n,{ticketId:e.ticketId,number:e.number})}),t.append(a),i.append(t)}this.replaceChildren(i)}});var sn=`http://www.w3.org/2000/svg`,cn={mic:`M12 15a3 3 0 0 0 3-3V6a3 3 0 0 0-6 0v6a3 3 0 0 0 3 3zm5-3a5 5 0 0 1-10 0H5a7 7 0 0 0 6 6.92V21h2v-2.08A7 7 0 0 0 19 12z`,stop:`M6 6h12v12H6z`,play:`M8 5v14l11-7z`,pause:`M6 5h4v14H6zm8 0h4v14h-4z`,speaker:`M3 9v6h4l5 5V4L7 9H3zm13.5 3a4.5 4.5 0 0 0-2.5-4v8a4.5 4.5 0 0 0 2.5-4zM14 3.2v2.1a7 7 0 0 1 0 13.4v2.1a9 9 0 0 0 0-17.6z`};function ln(t,n=18){if(!e(cn,t))throw Error(`Unknown voice icon "${t}".`);let r=document.createElementNS(sn,`svg`);r.setAttribute(`viewBox`,`0 0 24 24`),r.setAttribute(`width`,String(n)),r.setAttribute(`height`,String(n)),r.setAttribute(`aria-hidden`,`true`),r.setAttribute(`focusable`,`false`),r.setAttribute(`fill`,`currentColor`);let i=document.createElementNS(sn,`path`);return i.setAttribute(`d`,cn[t]),r.append(i),r}var un=40,q=null;function dn(e){let t=I(document,`span`,`wui-chat-clip-bar`);return t.style.setProperty(`--wui-chat-bar-height`,`${Math.round(e*100)}%`),t}function fn(e,t){e.replaceChildren(...Se(t,un).map(dn))}F(`wui-chat-part-voice-clip`,class extends P{#e=null;#t=!1;#n=0;#r=0;#i=!1;#a=null;#o=null;#s=null;#c=0;#l=!1;renderPart(e,t,n){if(!n.features.VoiceClips){this.#u(e.transcript);return}let r=this.#e??this.#d(e.attachmentId);e.attachmentId!==r.attachmentId&&(this.disposePart(),r.attachmentId=e.attachmentId,this.#r=0,fn(r.wave,e.attachmentId)),this.#n=e.durationMs,this.#f(r,e)}disposePart(){this.#c+=1,this.#a?.pause(),this.#s!==null&&URL.revokeObjectURL(this.#s),q===this&&(q=null),this.#a=null,this.#o=null,this.#s=null,this.#i=!1}#u(e){if(this.disposePart(),this.#e=null,typeof e==`string`&&e!==``){let t=I(document,`p`,`wui-chat-clip-transcript`);t.textContent=e,this.replaceChildren(t)}else this.replaceChildren()}#d(e){let t=I(document,`div`,`wui-chat-clip`);t.setAttribute(`role`,`group`);let n=I(document,`div`,`wui-chat-clip-row`),r=I(document,`button`,`wui-chat-clip-play`);r.type=`button`;let i=I(document,`div`,`wui-chat-clip-wave`);i.setAttribute(`aria-hidden`,`true`);let a=I(document,`span`,`wui-chat-clip-time`);n.append(r,i,a);let o=I(document,`p`,`wui-chat-clip-error`);o.setAttribute(`role`,`status`),o.hidden=!0,t.append(n,o);let s={attachmentId:e,root:t,play:r,wave:i,time:a,error:o,transcript:null};return r.addEventListener(`click`,()=>this.#C(s)),fn(i,e),this.#e=s,this.replaceChildren(t),s}#f(e,t){let n=this.activeTurn.labels;e.root.setAttribute(`aria-label`,n.voiceClip),e.play.disabled=this.#l||typeof this.activeTurn.readAttachment!=`function`,this.#p(e),this.#m(e),this.#h(e,t.transcript)}#p(e){let t=this.activeTurn.labels,n=this.#i?t.voiceClipPause:t.voiceClipPlay;e.play.setAttribute(`aria-label`,n),e.play.title=n,e.play.replaceChildren(ln(this.#i?`pause`:`play`,18))}#m(e){let t=this.#n/1e3,n=t>0?Math.min(1,this.#r/t):0,r=Math.floor(n*un);[...e.wave.children].forEach((e,t)=>{e.classList.toggle(`wui-chat-clip-bar--played`,t<r)});let i=ce(Math.max(1,Math.round(t)));e.time.textContent=this.activeTurn.labels.voiceClipTime(ce(this.#r),i)}#h(e,t){if(typeof t!=`string`||t===``){e.transcript?.toggle.remove(),e.transcript?.text.remove(),e.transcript=null;return}let n=e.transcript??this.#g(e);n.text.textContent=t,this.#_(n)}#g(e){let t=I(document,`button`,`wui-chat-clip-toggle`);t.type=`button`;let n=I(document,`p`,`wui-chat-clip-transcript`);n.hidden=!this.#t;let r={toggle:t,text:n};return t.addEventListener(`click`,()=>{this.#t=!this.#t,n.hidden=!this.#t,this.#_(r)}),e.transcript=r,e.root.append(t,n),r}#_(e){let t=this.activeTurn.labels;e.toggle.setAttribute(`aria-expanded`,String(this.#t)),e.toggle.textContent=this.#t?t.voiceClipHideTranscript:t.voiceClipShowTranscript}#v(e){return this.#o??=this.#y(e).catch(e=>{throw this.#o=null,e}),this.#o}async#y(e){let t=this.#c,{readAttachment:n}=this.activeTurn;if(n===void 0)throw Error(`${this.localName} loaded a clip on a turn without readAttachment`);let r=await n.call(this.activeTurn,e.attachmentId),i=URL.createObjectURL(new Blob([r],{type:ve(r)}));if(t!==this.#c)return URL.revokeObjectURL(i),null;this.#s!==null&&URL.revokeObjectURL(this.#s),this.#s=i;let a=new Audio(this.#s);return a.addEventListener(`timeupdate`,()=>{this.#r=a.currentTime,this.#m(e)}),a.addEventListener(`ended`,()=>{this.#r=0,this.#b(),this.#m(e)}),a.addEventListener(`error`,()=>{this.#b(),this.#o=null,this.#S(e)}),this.#a=a,a}#b(){this.#a?.pause(),this.#x(!1)}#x(e){this.#i=e,e?(q&&q!==this&&q.#b(),q=this):q===this&&(q=null);let t=this.#e;t!==null&&this.#p(t)}#S(e){e.error.textContent=this.activeTurn.labels.voiceClipFailed,e.error.hidden=!1}async#C(e){if(this.#i)this.#b();else{e.error.hidden=!0,this.#l=!0,e.play.disabled=!0,e.play.setAttribute(`aria-busy`,`true`);try{let t=await this.#v(e);if(t===null)return;this.#x(!0),await t.play()}catch{this.#b(),this.#o=null,this.#S(e)}finally{this.#l=!1,e.play.removeAttribute(`aria-busy`),e.play.disabled=typeof this.activeTurn.readAttachment!=`function`}}}});var pn={Text:`wui-chat-part-text`,Sources:`wui-chat-part-sources`,QuickReplies:`wui-chat-part-quick-replies`,InputRequest:`wui-chat-part-input-request`,Action:`wui-chat-part-action`,Notice:`wui-chat-part-notice`,Table:`wui-chat-part-table`,Chart:`wui-chat-part-chart`,Figures:`wui-chat-part-figures`,RecordCard:`wui-chat-part-record-card`,Image:`wui-chat-part-image`,File:`wui-chat-part-file`,Ticket:`wui-chat-part-ticket`,Handoff:`wui-chat-part-handoff`,VoiceClip:`wui-chat-part-voice-clip`},mn=8e3,hn=6e3,gn=/* @__PURE__ */ new Set([`Blocked`,`NoMicrophone`]);function _n(e){let t=e instanceof D?e.code:`Failed`;return{code:t,source:`Dictation`,sticky:gn.has(t)}}function vn(e){let t=N(e.filter(e=>e.kind===`Text`)).replace(/ ?\[\d+\]/g,``).replace(/\s+/g,` `).trim();if(t.length<=6e3)return t;let n=t.slice(0,hn),r=n.lastIndexOf(`. `);return r===-1?n.trim():n.slice(0,r+1)}function yn(e,t){switch(e.code){case`Blocked`:return t.dictationBlocked;case`NoMicrophone`:return t.dictationNoMicrophone;case`NoSpeech`:return t.dictationNotHeard;case`Unavailable`:return t.dictationUnavailable;case`Failed`:return t.dictationFailed;case`SpeakFailed`:return t.readAloudFailed;default:throw Error(`Unknown voice note code "${e.code}".`)}}function bn(e){let t=e.getState,n=e.speech??c({getToken:e.getToken}),r=`Idle`,i=null,a=null,o=null,s=null,l=0,u=null,d=/* @__PURE__ */ new Set,f=()=>({mode:r,messageId:i,startedAtMs:a,note:o});function p(){let e=f();for(let t of[...d])t(e)}function m(e){r=e.mode,i=e.messageId??null,a=e.startedAtMs??null,p()}function h(){u!==null&&clearTimeout(u),u=null}function g(e){h(),o=e,e&&!e.sticky&&(u=setTimeout(()=>{u=null,o=null,p()},mn)),p()}function _(){o!==null&&(h(),o=null,p())}function v(){l+=1;let e={id:l,controller:new AbortController,stopped:!1};return s=e,e}function y(e){s===e&&(s=null,m({mode:`Idle`}))}function b(){let e=s;s=null,e&&(e.stopped=!0,e.controller.abort()),r!==`Idle`&&m({mode:`Idle`})}function x(){let e=t();return!!(e.features.Dictation&&e.profile?.speechAvailable&&n.dictation)}function S(){let e=t();return!!(e.features.ReadAloud&&e.profile?.speechAvailable&&n.readAloud)}async function C(e){if(r===`Dictating`){b();return}if(b(),g(null),!x())return;let t=e.getText(),i=t!==``&&!/\s$/.test(t)?`${t} `:t,a=v();m({mode:`Dictating`});try{await n.startDictation({signal:a.controller.signal,onText:t=>{s===a&&e.setText(i+t)},onEnd:()=>y(a)})}catch(e){if(a.stopped)return;y(a),g(_n(e))}}async function w(e,t){if(r===`Speaking`&&i===e){b();return}b(),g(null);let a=vn(t);if(a===``)return;let o=v();m({mode:`Speaking`,messageId:e});try{await n.speak(a,{signal:o.controller.signal}),y(o)}catch{if(o.stopped)return;y(o),g({code:`SpeakFailed`,source:`ReadAloud`,sticky:!1,messageId:e})}}function T(e){return d.add(e),()=>{d.delete(e)}}function E(){b(),h(),o=null,d.clear()}return{canDictate:x,canSpeak:S,getStatus:f,subscribe:T,toggleDictation:C,toggleSpeak:w,stop:b,dismissNote:_,destroy:E}}var xn=/* @__PURE__ */ new Set([`Shift`,`Control`,`Alt`,`Meta`,`Escape`]);function Sn(e,t){e.isTrusted&&!xn.has(e.key)&&t.getStatus().mode===`Dictating`&&t.stop()}function Cn({voice:e,getLabels:t,textarea:n,onTextChanged:r}){let i=null,a=v(`button`,`wui-chat-tool wui-chat-mic`,{type:`button`});a.append(ln(`mic`,20)),a.hidden=!0,a.addEventListener(`click`,()=>{e.toggleDictation({getText:()=>n.value,setText:e=>{n.value=n.maxLength>0?e.slice(0,n.maxLength):e,r(),n.setSelectionRange(n.value.length,n.value.length)}})});let o=v(`p`,`wui-chat-voice-note`,{role:`status`});o.hidden=!0;let s=v(`span`,`visually-hidden`,{"aria-live":`polite`});function c(e){let n=t(),r=e.note?.source===`ReadAloud`?null:e.note,i=e.mode===`Dictating`,c=i?n.dictateStop:n.dictate;a.setAttribute(`aria-pressed`,String(i)),a.setAttribute(`aria-label`,c),a.title=c;let l=r?.code===`Blocked`||r?.code===`NoMicrophone`;r===null?(o.hidden=!0,o.textContent=``):(o.hidden=!1,o.textContent=yn(r,n),o.setAttribute(`role`,r.sticky?`alert`:`status`)),o.classList.toggle(`wui-chat-voice-note--blocked`,l),s.textContent=i?n.dictateListening:``}function l(t){let{state:n}=t;a.hidden=!e.canDictate();let r=e.getStatus().mode===`Speaking`,i=n.messagesLeftToday===0;a.disabled=i||r||n.handoffPause===!0}function u(e){c(e),i!==null&&l(i)}let d=e.subscribe(u);function f(t){i=t,l(t),c(e.getStatus())}function p(){d()}return{buttons:[a],note:o,announcer:s,paint:f,destroy:p}}var wn=10,Tn=.9,En=0;function Dn(e){for(let t of e.toReversed())for(let e of t.parts.toReversed())if(e.kind===`InputRequest`&&e.state===`Open`)return e.fields[0]?.label??e.title??null;return null}function On(e){En+=1;let t=`wui-chat-composer-hint-${En}`,n=v(`p`,`wui-chat-allowance`,{role:`status`});n.hidden=!0;let r=v(`span`),a=v(`button`,`btn btn-ghost-primary btn-sm wui-chat-action-btn`,{type:`button`});a.addEventListener(`click`,()=>e.onCancelEdit());let o=v(`div`,`wui-chat-editing`);o.hidden=!0,o.append(r,a);let s=v(`div`,`wui-chat-attachments`);s.hidden=!0;let c=v(`button`,`wui-chat-tool`,{type:`button`});c.append(i(`paperclip`,20)),c.hidden=!0;let l=v(`input`,null,{type:`file`,multiple:``,tabindex:`-1`});l.hidden=!0,l.addEventListener(`change`,()=>{let t=[...l.files??[]];l.value=``,t.length>0&&e.onAttach(t)}),c.addEventListener(`click`,()=>l.click());let u=v(`textarea`,`wui-chat-input`,{rows:`1`,"aria-describedby":t}),d=v(`span`,`visually-hidden`,{id:t}),f=v(`span`,`wui-chat-counter`);f.hidden=!0;let p=v(`button`,`wui-chat-send`,{type:`submit`});p.append(i(`arrow-up`,18));let m=v(`button`,`wui-chat-send wui-chat-send--stop`,{type:`button`});m.append(i(`stop`,16)),m.hidden=!0,m.addEventListener(`click`,()=>e.onStop());let h=v(`form`,`wui-chat-composer`);h.append(c,l,u,f,d,m,p);let g=e.mark?.(`input`,`rest`)??null,_=null,y=null,b=null,x=0,S=null;function C(){u.style.height=`auto`,u.style.height=`${u.scrollHeight}px`;let e=getComputedStyle(u),t=u.scrollHeight-parseFloat(e.paddingTop)-parseFloat(e.paddingBottom);h.classList.toggle(`wui-chat-composer--multiline`,t>(parseFloat(e.lineHeight)||22)*1.5)}function w(){return S?.attachments.some(e=>e.status===`Uploading`)??!1}function T(){return S?.attachments.some(e=>e.status===`Ready`)??!1}function E(){let e=u.value.length,t=x>0&&e>x*Tn;f.hidden=!t,t&&b&&(f.textContent=b.counter(e,x))}function D(){let e=S?.messagesLeftToday??null,t=u.value.trim()===``&&!T();p.disabled=!!S?.streaming||e===0||w()||t||S?.handoffPause===!0,h.classList.toggle(`wui-chat-composer--has-text`,!t)}function O(){if(p.disabled)return;let t=u.value.trim();u.value=``,C(),E(),D(),e.voice?.stop(),e.voice?.dismissNote(),e.onSubmit(t)}u.addEventListener(`input`,()=>{C(),E(),D(),u.value!==``&&e.onTyping?.()}),u.addEventListener(`keydown`,e=>{e.key===`Enter`&&!e.shiftKey&&!e.isComposing&&(e.preventDefault(),O())}),h.addEventListener(`submit`,e=>{e.preventDefault(),O()});let k=e.voice,A=k?Cn({voice:k,getLabels:()=>{if(b===null)throw Error(`composer labels are read before the first render`);return b},textarea:u,onTextChanged:()=>{C(),E(),D()}}):null;if(k&&A){let e=A.buttons[0];e&&h.insertBefore(e,p),u.addEventListener(`keydown`,e=>Sn(e,k))}function ee(t,n){let r=t.map(t=>{let r=v(`span`,`wui-chat-chip`),a=v(`span`,null,t.status===`Failed`?{title:t.error??``}:null);a.textContent=t.fileName;let o=v(`button`,`wui-chat-chip-remove`,{type:`button`,"aria-label":n.removeAttachment(t.fileName)});o.append(i(`x`,14)),o.addEventListener(`click`,()=>e.onRemove(t.key));let s=[];if(t.status===`Uploading`){let e=v(`progress`,`wui-chat-chip-progress`,{max:`1`});typeof t.progress==`number`&&(e.value=t.progress);let r=v(`span`,`wui-chat-chip-status`);r.textContent=n.attachmentUploading,s.push(e,r)}if(t.status===`Failed`){let e=v(`span`,`wui-chat-chip-error`,{"aria-live":`polite`});e.textContent=t.error||n.attachmentFailed,s.push(e)}return r.append(a,...s,o),r});s.replaceChildren(...r),s.hidden=r.length===0}function te(t){S=t.state,b=t.labels,x=t.maxLength,t.sendIcon&&p.dataset.icon!==t.sendIcon&&(p.dataset.icon=t.sendIcon,p.replaceChildren(i(t.sendIcon,18)));let s=S.messagesLeftToday;h.setAttribute(`aria-label`,b.composer),d.textContent=b.composerHint,u.setAttribute(`aria-label`,b.composer),u.maxLength=x,u.placeholder=S.handoffPause?b.handoffMoment:Dn(S.messages)??b.placeholder,u.disabled=s===0||S.handoffPause===!0,n.hidden=!(s!==null&&s<=wn),!n.hidden&&s!==null&&(n.textContent=b.allowance(s));let f=S.editing?.messageId??null;if(f!==_){let t=_!==null;_=f,S.editing?(e.voice?.stop(),u.value=S.editing.text,C()):t&&(u.value=``,C())}o.hidden=!S.editing,r.textContent=b.editing,a.textContent=b.cancel;let v=t.draft??null;typeof v==`string`&&v!==``&&v!==y&&(y=v,u.value=v,u.dispatchEvent(new Event(`input`)),u.focus(),e.onDraftApplied?.()),ee(S.attachments,b);let w=S.features.Attachments&&(S.profile?.limits.maxAttachments??0)>0&&S.handoffPause!==!0;c.hidden=!w,c.setAttribute(`aria-label`,b.attach),c.title=b.attachHint,l.accept=t.accept??``;let T=S.streaming&&S.features.Stop===!0;m.hidden=!T,m.setAttribute(`aria-label`,b.stop),p.hidden=T,p.setAttribute(`aria-label`,b.send),E(),D(),g!==null&&(g.dataset.state=t.busy===!0?`busy`:`rest`,t.inputMark===`Avatar`?g.parentNode!==h&&h.insertBefore(g,u):g.remove()),A?.paint({state:S})}function ne(){u.focus()}function re(){A?.destroy();for(let e of ie)e.remove()}let ie=[n,o,s,...A?[A.note,A.announcer]:[],h];return{nodes:ie,paint:te,focus:ne,destroy:re,getDraft:()=>u.value}}var kn=`https://policies.google.com/privacy`,An=`https://policies.google.com/terms`;function jn(e,t){let n=v(`a`,`wui-chat-footer-link`,{href:t,target:`_blank`,rel:`noopener noreferrer`});return n.textContent=e,n}function Mn(){let e=v(`p`,`wui-chat-footer`);e.hidden=!0;function t(t){let{labels:n,profile:r,hideDisclaimer:i}=t,a=[];if(r){if(!i){let e=v(`span`,`wui-chat-footer-text`);e.textContent=r.footer.disclaimer||n.disclaimer,a.push(e)}let{privacyText:e}=r.footer,t=fe(r.footer.privacyUrl)?r.footer.privacyUrl:null;if(t){let r=v(`span`,`wui-chat-footer-privacy`),i=v(`a`,`wui-chat-footer-link`,{href:t});i.textContent=e||n.footerPrivacyFallback,r.append(i),a.push(r)}else if(e){let t=v(`span`,`wui-chat-footer-privacy`);t.textContent=e,a.push(t)}if(r.footer.assuranceText){let e=v(`span`);e.textContent=r.footer.assuranceText,a.push(e)}if(_e(r)){let e=v(`span`,`wui-chat-footer-captcha`),t=v(`span`,`wui-chat-footer-captcha-tail`);t.append(jn(n.captchaPrivacyPolicy,kn),document.createTextNode(n.captchaNoticeAnd),jn(n.captchaTerms,An),document.createTextNode(n.captchaNoticeAfter)),e.append(document.createTextNode(n.captchaNoticeBefore),t),a.push(e)}}e.replaceChildren(...a),e.hidden=a.length===0}return{el:e,paint:t}}function J(e,t,n){e.setAttribute(`aria-label`,t),e.title=t,e.dataset.icon!==n&&(e.dataset.icon=n,e.replaceChildren(i(n,20)))}function Nn(e){let t=e.mark?.(`header`,`rest`)??v(`span`,`wui-chat-orb`,{"aria-hidden":`true`}),n=v(`strong`,`wui-chat-title`);e.titleId&&(n.id=e.titleId);let r=v(`span`,`wui-chat-tagline`),i=v(`span`,`wui-chat-status`),a=v(`div`,`wui-chat-header-text`);a.append(n,r,i);let o=v(`span`,`wui-chat-header-conversation`);o.hidden=!0;let s=_(``,`history`,()=>e.onHistory()),c=_(``,`volume-high`,()=>e.onMute()),l=_(``,`plus`,()=>e.onNew()),u=_(``,`maximize-4`,()=>e.onSwitch());u.classList.add(`wui-chat-switch-btn`,`wui-chat-switch-btn--full`);let d=_(``,`panel-left-open`,()=>e.onSwitch());d.classList.add(`wui-chat-switch-btn`,`wui-chat-switch-btn--side`);let f=_(``,`x`,()=>e.onClose());f.classList.add(`wui-chat-close-btn`);let p=v(`div`,`wui-chat-header-actions`);p.append(o,s,c,l,u,d,f);let m=v(`header`,`wui-chat-header`);m.append(t,a,p);function h(e){let{labels:t}=e;m.hidden=!1,n.textContent=e.title??``,r.textContent=e.tagline??``,r.hidden=!e.tagline,i.textContent=e.status??``,s.hidden=!e.showHistory,e.viewingHistory?J(s,t.backToChat,`arrow-left`):J(s,t.history,`history`),c.hidden=!e.showMute,J(c,e.muted?t.unmuteSounds:t.muteSounds,e.muted?`volume-mute`:`volume-high`),l.hidden=!!e.viewingHistory||e.showNew===!1,l.disabled=!e.canNew,J(l,t.newChat,`plus`),u.hidden=e.switchTo!==`full-page`,u.disabled=!e.canSwitch,J(u,t.openFullScreen,`maximize-4`),d.hidden=e.switchTo!==`docked`,d.disabled=!e.canSwitch,J(d,t.openSidePanel,`panel-left-open`),f.hidden=!e.showClose,J(f,t.close,`x`)}return{el:m,conversation:o,paint:h}}var Pn=120;function Y(e,t,n=`outline`){let r=v(`button`,`${l(n,`sm`)} wui-chat-action-btn`,{type:`button`});return r.textContent=e,r.addEventListener(`click`,t),r}function Fn(e){let t=v(`div`,`wui-chat-history`);t.hidden=!0;let n=null,r=null,i=null,a=null,o=null,s=!1;function c(){return n||(n=re({client:e.getClient()}),r=n.subscribe(()=>y()),n)}function l(e){i={id:e.publicId,kind:`rename`,draft:e.title??``,saving:!1},a=null,o=null,s=!0,y()}function u(e){i={id:e.publicId,kind:`delete`,saving:!1},a=null,o=null,y()}function d(){i=null,a=null,o=null,y()}async function f(){let t=i;if(t?.kind!==`rename`||t.saving)return;let n=t.draft.trim();if(n){t.saving=!0,y();try{await c().rename(t.id,n),i===t&&(i=null),a=null,o=null}catch{if(i!==t)return;t.saving=!1,o=e.getLabels().renameFailed}y()}}async function p(){let t=i;if(!(t?.kind!==`delete`||t.saving)){t.saving=!0,y();try{await c().remove(t.id),i===t&&(i=null),a=null,e.onDeleted(t.id)}catch{if(i!==t)return;t.saving=!1,a=e.getLabels().deleteFailed}y()}}function m(e,t){let n=v(`li`,`wui-chat-history-row wui-chat-history-row--editing`),r=v(`input`,`wui-chat-history-input`,{type:`text`,"aria-label":e.conversationTitle,maxlength:String(Pn)});r.value=t.draft,r.addEventListener(`input`,()=>{t.draft=r.value,i.disabled=t.saving||!t.draft.trim()}),r.addEventListener(`keydown`,e=>{e.key===`Enter`&&!e.isComposing&&e.keyCode!==229?(e.preventDefault(),f()):e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),d())});let i=Y(e.renameSave,()=>f(),`primary`);if(i.disabled=t.saving||!t.draft.trim(),n.append(r,i,Y(e.cancel,()=>d(),`ghost`)),o!==null){let e=v(`p`,`wui-chat-history-error`,{role:`alert`});e.textContent=o,n.append(e)}return s&&(s=!1,queueMicrotask(()=>r.focus())),n}function h(e,t){let n=v(`li`,`wui-chat-history-row wui-chat-history-row--confirm`),r=v(`p`);r.textContent=e.deleteConfirmTitle;let i=v(`p`);i.textContent=e.deleteConfirmMessage;let a=Y(e.deleteConfirm,()=>p(),`danger`);return a.disabled=t.saving,n.append(r,i,a,Y(e.cancel,()=>d(),`ghost`)),n}function g(t,n,r){if(i?.id===t.publicId&&i.kind===`rename`)return m(n,i);if(i?.id===t.publicId&&i.kind===`delete`)return h(n,i);let a=v(`li`,`wui-chat-history-row`),o=v(`button`,`wui-chat-history-open`,{type:`button`}),s=v(`span`,`wui-chat-history-title`);s.textContent=t.title||n.untitled;let c=v(`span`,`wui-chat-history-time`);return c.textContent=j(t.lastActivityDateTimeUtc),o.append(s,c),o.addEventListener(`click`,()=>e.onOpen(t.publicId)),a.append(o),r.Rename&&a.append(_(n.rename,`pencil`,()=>l(t))),r.Delete&&a.append(_(n.deleteChat,`trash`,()=>u(t))),a}function y(){let r=e.getLabels(),i=e.getFeatures(),o=n?n.getState():{items:[],totalCount:null,loading:!1,error:null,hasMore:!1},s=[];if(o.error||a){let e=v(`p`,`wui-chat-history-error`,{role:`alert`});o.error?(e.append(document.createTextNode(r.loadFailed),document.createTextNode(` `)),e.append(Y(r.retry,()=>c().load(),`outline`))):e.textContent=a,s.push(e)}if(o.loading&&o.items.length===0){let e=v(`p`,`wui-chat-history-empty`,{role:`status`});e.textContent=r.loadingConversation,s.push(e)}if(o.items.length===0&&!o.loading&&!o.error){let e=v(`p`,`wui-chat-history-empty`),t=v(`span`);t.textContent=r.historyEmptyTitle;let n=v(`span`);n.textContent=r.historyEmptyText,e.append(t,n),s.push(e)}if(o.items.length>0){let e=v(`ul`,`wui-chat-history-list`,{"aria-label":r.history});e.append(...o.items.map(e=>g(e,r,i))),s.push(e)}o.hasMore&&!o.loading&&s.push(Y(r.loadMore,()=>c().loadMore(),`outline`)),t.replaceChildren(...s)}function b(){t.hidden=!1,Promise.allSettled([c().load()]),y()}function x(){t.hidden=!0}function S(){r?.(),r=null,n?.dispose(),n=null}return{el:t,show:b,hide:x,paint:y,dispose:S}}var In=/* @__PURE__ */ new Set([`GET`,`HEAD`]);function Ln(){let e=document.querySelector(`meta[name="wui-csrf"]`),t=e?.getAttribute(`content`);return t?{token:t,header:e?.getAttribute(`data-header`)||`RequestVerificationToken`}:null}async function Rn(e,{lenient:t=!1}={}){let n=await e.text();if(n){if((e.headers.get(`content-type`)||``).includes(`json`)){if(!t)return JSON.parse(n);try{return JSON.parse(n)}catch{return n}}return n}}async function zn(e,t,n){let r=new TextDecoder,i=e.getReader(),a=``;for(;;){let{done:e,value:o}=await i.read();if(e)break;a+=r.decode(o,{stream:!0}),n({event:{target:{responseText:a,status:t}}})}return a+=r.decode(),a}function Bn({fetch:e=(...e)=>globalThis.fetch(...e)}={}){async function t(t,n,r,i={}){let a={...i.headers},o;if(typeof FormData<`u`&&r instanceof FormData){for(let e of Object.keys(a))e.toLowerCase()===`content-type`&&delete a[e];o=r}else r!==void 0&&(a[`Content-Type`]=`application/json`,o=JSON.stringify(r));if(!In.has(t)){let e=Ln();e&&(a[e.header]=e.token)}let s=i.signal,c=s,l,u,d=()=>l?.abort(s?.reason);(i.timeout??0)>0&&(l=new AbortController,c=l.signal,s?.aborted?l.abort(s.reason):s?.addEventListener(`abort`,d,{once:!0}),u=setTimeout(()=>l?.abort(new DOMException(`The request timed out.`,`TimeoutError`)),i.timeout));try{let r={method:t,headers:a,credentials:`same-origin`};o!==void 0&&(r.body=o),c&&(r.signal=c);let s=await e(n,r);if(!s.ok){let e=/* @__PURE__ */ Error(`Request failed with status ${s.status}`);throw e.response={status:s.status,data:await Rn(s,{lenient:!0})},e}let l;return l=i.responseType===`arraybuffer`?await s.arrayBuffer():typeof i.onDownloadProgress==`function`&&s.body?await zn(s.body,s.status,i.onDownloadProgress):await Rn(s),{data:l,status:s.status}}finally{clearTimeout(u),s?.removeEventListener(`abort`,d)}}return{get:(e,n)=>t(`GET`,e,void 0,n),post:(e,n,r)=>t(`POST`,e,n,r),put:(e,n,r)=>t(`PUT`,e,n,r),delete:(e,n)=>t(`DELETE`,e,void 0,n)}}function Vn(e){let t,n=!1,r=!1,a=v(`div`,`wui-chat-nudge`,{role:`status`});a.hidden=!0;let o=v(`button`,`wui-chat-nudge-text`,{type:`button`}),s=v(`button`,`wui-chat-nudge-close`,{type:`button`});s.append(i(`x`,14)),a.append(o,s);function c(){clearTimeout(t),t=void 0}function l(){c(),r=!0,a.hidden=!0}o.addEventListener(`click`,()=>{a.hidden=!0,e.onActivate()}),s.addEventListener(`click`,()=>{l(),e.onDismiss()});function u(e){c(),r||n||(t=setTimeout(()=>{t=void 0,o.textContent=e.text,s.setAttribute(`aria-label`,e.label),a.hidden=!1,n=!0},e.delaySeconds*1e3))}function d(){c(),a.remove()}return{el:a,schedule:u,cancel:c,dismiss:l,isShown:()=>n,destroy:d}}function Hn(e,t){e.addEventListener(`click`,()=>t()),e.addEventListener(`keydown`,e=>{(Ae(e)||e.key===` `)&&(e.preventDefault(),t())})}function Un(e){let{list:t,getLabels:n,getFeatures:r,onOpen:i}=e,a=v(`div`,`wui-chat-empty-rows wui-chat-empty-rows--past`);a.hidden=!0;let o=!1;function s(e,t){let n=v(`div`,`card card-pad-sm card-clickable wui-chat-empty-row`,{role:`button`,tabindex:`0`}),r=v(`div`,`card-body wui-chat-empty-row-body`),a=v(`span`,`wui-chat-empty-row-title`);a.textContent=e.title||t.earlierChat;let o=v(`span`,`wui-chat-empty-row-time`,{title:ae(e.lastActivityDateTimeUtc)});return o.textContent=j(e.lastActivityDateTimeUtc),r.append(a,o),n.append(r),Hn(n,()=>i(e.publicId)),n}function c(){if(o)return;let e=t.getState().items;if(r().History!==!0||e.length===0){a.replaceChildren(),a.hidden=!0;return}let i=n();a.replaceChildren(...e.slice(0,20).map(e=>s(e,i))),a.hidden=!1}let l=t.subscribe(c);return{el:a,refresh(){r().History===!0&&t.load().catch(e=>globalThis.reportError?.(e))},paint:c,dispose(){o=!0,l()}}}var Wn=`https://www.google.com/recaptcha/api.js?render=`;function Gn(e){return e!==void 0&&typeof e.ready==`function`&&typeof e.execute==`function`}var Kn=/* @__PURE__ */ new Map;function qn(e){let t=Kn.get(e);if(t!==void 0)return t;let n=new Promise((t,n)=>{let r=globalThis.grecaptcha;if(Gn(r)){t(r);return}let i=document.createElement(`script`);i.src=Wn+encodeURIComponent(e),i.async=!0;let a=t=>{Kn.delete(e),n(Object.assign(Error(t),{code:`captcha_unavailable`}))};i.addEventListener(`load`,()=>{let e=globalThis.grecaptcha;e===void 0||typeof e.ready!=`function`?a(`The reCAPTCHA script loaded without grecaptcha.`):e.ready(()=>{let e=globalThis.grecaptcha;Gn(e)?t(e):a(`reCAPTCHA became ready without execute.`)})}),i.addEventListener(`error`,()=>{Kn.delete(e),n(/* @__PURE__ */ Error(`The reCAPTCHA script did not load.`))}),document.head.append(i)});return Kn.set(e,n),n}async function Jn(e,t){let n=await qn(e);await new Promise(e=>n.ready(()=>e()));let r=await n.execute(e,{action:t});if(!r)throw Object.assign(/* @__PURE__ */ Error(`reCAPTCHA returned no token.`),{code:`captcha_unavailable`});return r}var Yn=/* @__PURE__ */ new Set([`Assistant`,`Agent`,`Script`]),Xn=/* @__PURE__ */ new WeakMap;function Zn(e,t,n){let{labels:r,features:i,title:a,busy:o,assistantName:c}=n;if(N(t.parts)!==``){if(i.Share&&g()){let n=s(`ghost`,r.share,`share`,()=>void(async()=>{let e=nr([t],i,r,a,!1,c);e!==``&&await u({title:a,text:e})===`failed`&&or(n.parentElement,r.shareFailed)})());n.disabled=o===!0,e.append(n)}if(i.Print){let t=s(`ghost`,r.print,`printer`,()=>{try{let e=t.closest(`.wui-chat`),n=t.closest(`li.wui-chat-message`);if(!(e instanceof HTMLElement)||!(n instanceof HTMLElement))throw Error(`printReply needs a message inside the wui-chat root`);f(e,n,{title:a,printedOn:ir(r)})}catch{ar(t,r.printFailed)}});e.append(t)}}}function Qn(e,t,n){if(t.streaming||t.thinking||t.loading||t.conversationId===null||t.messages.filter(e=>e.stored&&Yn.has(e.author.kind)&&N(e.parts)!==``).length===0){e.hidden=!0;return}let{labels:r,features:i}=n,a=!!i.Share&&g(),o=!!i.Print;if(!a&&!o){e.hidden=!0;return}let s=[a,o,t.messages.length,r.shareConversation,r.printConversation].join(`|`);e.dataset.sig!==s&&(e.dataset.sig=s,e.replaceChildren(),a&&e.append(er(e,r,i,n)),o&&e.append(tr(e,r,n))),e.hidden=!1}function $n(e,t,n,r){return e.iconOnly?_(t,n,r):s(`ghost`,t,n,r)}function er(e,t,n,r){return $n(r,t.shareConversation,`share`,()=>void(async()=>{let i=r.getState(),a=rr(i,r),o=nr(i.messages.filter(e=>e.stored),n,t,a,!0,i.profile?.assistant.name);await u({title:a,text:o})===`failed`&&or(e,t.shareFailed)})())}function tr(e,t,n){let r=$n(n,t.printConversation,`printer`,()=>{try{let r=e.closest(`.wui-chat`);if(!(r instanceof HTMLElement))throw Error(`printConversation needs the wui-chat root`);O(r,{title:rr(n.getState(),n),printedOn:ir(t)})}catch{n.iconOnly?or(e,t.printFailed):ar(r,t.printFailed)}});return r}function nr(e,t,n,r,i,a){let o=ee(e,{labels:n,title:r,figureText:t.FigureText,...a===void 0?{}:{assistantName:a}});return xe(o,{heading:i,speakers:i})}function rr(e,t){return typeof e.title==`string`&&e.title!==``?e.title:t.title}function ir(e){return e.printedOn(j((/* @__PURE__ */ new Date()).toISOString()))}function ar(e,t){let n=e.lastChild;if(!(n instanceof Text))return;let r=Xn.get(n);r&&clearTimeout(r.timer);let i=r??{original:n.data};n.data=t,i.timer=setTimeout(()=>{n.data=i.original,Xn.delete(n)},Te),Xn.set(n,i)}function or(e,t){if(!e)return;let n=document.createElement(`span`);n.className=`wui-chat-action-notice`,n.setAttribute(`role`,`status`),n.textContent=t,e.append(n),setTimeout(()=>n.remove(),Te)}var sr=`data-wchat-docked`,cr=`--wui-chat-docked-width`,lr=420,ur=/* @__PURE__ */ new Set;function dr(e,t){let n=document.documentElement;n.setAttribute(sr,e),n.style.setProperty(cr,t)}function fr(){let e=document.documentElement;e.removeAttribute(sr),e.style.removeProperty(cr)}function pr(e){let t=o({...e,layout:`docked`,role:`dialog`,launcher:!0}),n={},r=e.position,i=!1,a=null,s=()=>`${Math.round(t.panel.getBoundingClientRect().width)||lr}px`;function c(){ur.add(n),dr(r,s()),typeof ResizeObserver==`function`&&(a=new ResizeObserver(()=>document.documentElement.style.setProperty(cr,s())),a.observe(t.panel))}function l(){a?.disconnect(),a=null,ur.delete(n),ur.size===0&&fr()}function u(e){t.setOpen(e),e&&!i?(i=!0,c()):!e&&i&&(i=!1,l())}function d(e){t.setAppearance(e),e.position!==void 0&&(r=e.position,i&&document.documentElement.setAttribute(sr,r))}function f(){u(!1)}return{...t,setOpen:u,setAppearance:d,destroy:f}}function mr(e){return o({...e,layout:`embedded`,role:`region`,launcher:!1})}var hr=`wchat:peeked`,gr=576,_r=200;function vr(e){let t=o({...e,layout:`launcher`,role:`dialog`,launcher:!0}),{root:n,panel:r,setLauncherState:i}=t;if(!t.nudgeHost||!t.launcherButton)throw Error(`a launcher shell always has its launcher`);let a=t.nudgeHost,s=t.launcherButton,c={peek:!1,peekSeconds:3,hideWhileOpen:!1,expressive:!1};s.dataset.state=`closed`;let l=!1,u=!1,d,f,p=()=>c.hideWhileOpen||c.expressive;function m(){!c.peek||l||u||a.dataset.launcher!==`idle`||globalThis.innerWidth<gr||globalThis.sessionStorage.getItem(hr)!==null||(globalThis.sessionStorage.setItem(hr,`1`),i(`peeking`),d=setTimeout(()=>{d=void 0,a.dataset.launcher===`peeking`&&i(`idle`)},c.peekSeconds*1e3))}a.addEventListener(`animationend`,e=>{e.target===a&&a.dataset.launcher===`idle`&&m()});function h(e){if(e!==u){if(u=e,clearTimeout(d),d=void 0,e)clearTimeout(f),f=void 0,p()?(i(`hidden`),a.toggleAttribute(`inert`,!0)):a.dataset.launcher===`peeking`&&i(`idle`);else if(p()){let e=r.contains(document.activeElement);f=setTimeout(()=>{f=void 0,a.toggleAttribute(`inert`,!1),i(`idle`),e&&s.focus()},_r)}}s.dataset.state=e?`open`:`closed`,t.setOpen(e)}function g(e){e.reduced!==void 0&&(l=!!e.reduced),e.peek!==void 0&&(c.peek=e.peek),e.peekSeconds!==void 0&&(c.peekSeconds=e.peekSeconds),e.hideWhileOpen!==void 0&&(c.hideWhileOpen=e.hideWhileOpen),e.expressive!==void 0&&(c.expressive=e.expressive===!0),e.phoneMode!==void 0&&n.classList.toggle(`wui-chat--sheet`,e.phoneMode===`Sheet`),e.sheetHeightDvh!==void 0&&n.style.setProperty(`--_wui-chat-sheet-height`,`${e.sheetHeightDvh}dvh`),e.sheetMaxHeightPx!==void 0&&n.style.setProperty(`--_wui-chat-sheet-max-height`,`${e.sheetMaxHeightPx}px`),t.setAppearance(e),!p()&&a.dataset.launcher===`hidden`&&!u&&i(`idle`),a.dataset.launcher===`idle`&&m()}return{...t,nudgeHost:a,launcherButton:s,setOpen:h,setAppearance:g}}function yr(e){return o({...e,layout:`full-page`,role:`region`,launcher:!1})}var br=/* @__PURE__ */ new Set([`Agent`,`Customer`]);function xr(){let e=document.createElement(`div`);e.className=`wui-chat-loader-typing`,e.setAttribute(`aria-hidden`,`true`),e.hidden=!0;let t=document.createElement(`span`);t.className=`wui-chat-loader-typing-orb`;let n=document.createElement(`span`);n.className=`wui-chat-loader-typing-dots`;for(let e=0;e<3;e++){let e=document.createElement(`span`);e.className=`wui-chat-loader-typing-dot`,n.append(e)}e.append(t,n);function r({active:n,reduced:r,authorKind:i}){e.hidden=!n,e.classList.toggle(`wui-chat-loader--reduced`,r===!0),t.hidden=br.has(i)}function i(){e.remove()}return{el:e,update:r,destroy:i}}var Sr=3,Cr={Primary:`wui-chat-starter--primary`,Cta:`wui-chat-starter--cta`};function wr(e,t){e.addEventListener(`click`,()=>t()),e.addEventListener(`keydown`,e=>{(Ae(e)||e.key===` `)&&(e.preventDefault(),t())})}function Tr(e){let t=v(`h2`,`wui-chat-greeting`),n=v(`div`,`wui-chat-empty-hero`),r=v(`p`,`wui-chat-empty-intro`);r.hidden=!0;let a=e.mark?.(`greeting`,`rest`)??v(`span`,`wui-chat-orb`,{"aria-hidden":`true`});n.append(a,t,r);let o=v(`div`,`wui-chat-empty-extra`);o.hidden=!0;let s=v(`div`,`wui-chat-starters`,{role:`group`}),c=v(`div`,`wui-chat-empty-rows`),l=v(`div`,`wui-chat-empty-past`),u=v(`div`,`wui-chat-empty`,{role:`group`}),d=xr();u.append(d.el,n,o,s,c,l);let f;function p(t,n){let r=t.variant===null?void 0:Cr[t.variant],a=v(`button`,[`wui-chat-starter`,r??``].filter(Boolean).join(` `),{type:`button`});if(a.style.setProperty(`--wui-chat-i`,String(n)),t.icon){let e=v(`span`,`wui-chat-starter-icon`,{"aria-hidden":`true`});e.append(i(t.icon,16)),a.append(e)}return a.append(document.createTextNode(t.label)),a.addEventListener(`click`,()=>e.onStarter(t)),a}function m(t,n){let r=v(`div`,`card card-pad-sm card-clickable wui-chat-empty-row`,{role:`button`,tabindex:`0`}),i=v(`div`,`card-body wui-chat-empty-row-body`),a=v(`span`,`wui-chat-empty-row-label`);a.textContent=n.resumeLast;let o=v(`span`,`wui-chat-empty-row-title`,{title:t.title||n.untitled});o.textContent=t.title||n.untitled;let s=v(`span`,`wui-chat-empty-row-time`);return s.textContent=j(t.lastActivityDateTimeUtc),i.append(a,o,s),r.append(i),wr(r,()=>e.onResume()),r}function h(t,n){let r=v(`div`,`card card-pad-sm card-clickable wui-chat-empty-row`,{role:`button`,tabindex:`0`}),i=v(`div`,`card-body wui-chat-empty-row-body`),a=v(`span`,`wui-chat-empty-row-title`,{title:t.title||n.untitled});a.textContent=t.title||n.untitled;let o=v(`span`,`wui-chat-empty-row-time`);return o.textContent=j(t.lastActivityDateTimeUtc),i.append(a,o),r.append(i),wr(r,()=>e.onOpenConversation(t.publicId)),r}function g(t,n,r){let i=r?v(`div`,`card card-pad-sm card-clickable wui-chat-empty-row`,{role:`button`,tabindex:`0`}):v(`div`,`card card-pad-sm wui-chat-empty-row`),a=v(`div`,`card-body wui-chat-empty-row-body`),o=v(`span`,`wui-chat-empty-row-label`);o.textContent=n.ticketAria(t.number);let s=v(`span`,`wui-chat-empty-row-title`);s.textContent=t.subject;let c=v(`span`,`wui-chat-empty-row-status`);return c.textContent=ht(t.status,n),a.append(o,s,c),i.append(a),r&&wr(i,()=>e.onTicket(t)),i}function _(e,t){if(e.features?.OpenTickets!==!0||!e.openTickets?.length)return null;let n=v(`div`,`wui-chat-open-tickets`,{role:`group`,"aria-label":t.openTickets});return n.append(...e.openTickets.slice(0,Sr).map(n=>g(n,t,e.ticketsClickable===!0))),n}function y(e){let{labels:n}=e;t.textContent=e.greeting??``;let i=e.intro??``;r.textContent=i,r.hidden=!i,u.setAttribute(`aria-label`,n.emptyTitle);let a=e.starters??[];s.setAttribute(`aria-label`,n.starters),s.hidden=!e.showStarters||a.length===0,s.replaceChildren(...a.map(p));let o=e.resume??null,l=e.recent.length===0?null:v(`div`,`wui-chat-recent`,{role:`group`,"aria-label":n.recentChats});l?.append(...e.recent.map(e=>h(e,n)));let d=_(e,n),f=l??(o===null?null:m(o,n));c.hidden=f===null&&d===null,c.replaceChildren(...[f,d].filter(e=>e!==null))}function b(e){clearTimeout(f),u.classList.remove(`wui-chat-empty--revealed`),u.classList.add(`wui-chat-empty--intro`),d.update({active:!0,reduced:!1,authorKind:`Assistant`}),f=setTimeout(()=>{f=void 0,d.update({active:!1,reduced:!1,authorKind:`Assistant`}),u.classList.replace(`wui-chat-empty--intro`,`wui-chat-empty--revealed`)},e)}return{el:u,paint:y,intro:b,extraHost:o,pastHost:l}}function Er(){let e=document.createElement(`div`);e.className=`wui-chat-loader-orb`;let t=document.createElement(`span`);t.className=`wui-chat-loader-orb-mark`,t.setAttribute(`aria-hidden`,`true`);let n=document.createElement(`span`);n.className=`wui-chat-loader-orb-glow`,n.setAttribute(`aria-hidden`,`true`);let r=document.createElement(`span`);r.className=`wui-chat-loader-orb-disc`,r.setAttribute(`aria-hidden`,`true`),t.append(n,r);let i=document.createElement(`span`);i.className=`wui-chat-loader-orb-label`,e.append(t,i);let a=t;return{el:e,render(n,r=null){i.textContent!==n.label&&(i.textContent=n.label);let o=r??t;o!==a&&(a.parentNode===e?a.replaceWith(o):e.prepend(o),a=o)}}}var Dr=150,Or=1800;function kr(){let e=document.createElement(`div`);e.className=`wui-chat-loader-phrases`;let t=document.createElement(`span`);t.className=`wui-chat-loader-phrases-orb`,t.setAttribute(`aria-hidden`,`true`);let n=document.createElement(`span`);n.className=`wui-chat-loader-phrases-stage`,e.append(t,n);let r=null,i=null;function a(){return e.closest(`.wui-chat-loader`)?.classList.contains(`wui-chat-loader--reduced`)===!0}function o(e){if(e.label===r)return;r=e.label;let t=i,o=document.createElement(`span`);o.className=`wui-chat-loader-phrases-text wui-chat-loader-phrases-text--in`,o.textContent=e.label,o.style.animationDelay=`-${Math.round(performance.now()%Or)}ms, 0s`,n.append(o),i=o,t&&(t.classList.remove(`wui-chat-loader-phrases-text--in`),t.classList.add(`wui-chat-loader-phrases-text--out`),t.style.animationDelay=`-${Math.round(performance.now()%Or)}ms, 0s`,a()?t.remove():setTimeout(()=>t.remove(),Dr))}return{el:e,render:o}}var Ar=3;function jr(){let e=document.createElement(`div`);e.className=`wui-chat-loader-pulse`;let t=document.createElement(`span`);t.className=`wui-chat-loader-pulse-disc`,t.setAttribute(`aria-hidden`,`true`);let n=document.createElement(`span`);n.className=`wui-chat-loader-pulse-label`;let r=document.createElement(`span`);r.className=`wui-chat-loader-pulse-dots`,r.setAttribute(`aria-hidden`,`true`);for(let e=0;e<Ar;e+=1){let e=document.createElement(`span`);e.className=`wui-chat-loader-pulse-dot`,r.append(e)}e.append(t,n,r);let i=t;return{el:e,render(r,a=null){n.textContent!==r.label&&(n.textContent=r.label);let o=a??t;o!==i&&(i.parentNode===e?i.replaceWith(o):e.prepend(o),i=o)}}}var Mr=[`95%`,`80%`,`60%`];function Nr(){let e=document.createElement(`div`);e.className=`wui-chat-loader-skeleton`;let t=document.createElement(`div`);t.className=`wui-chat-loader-skeleton-label`;let n=document.createElement(`div`);n.className=`wui-chat-loader-skeleton-body`;let r=document.createElement(`span`);r.className=`wui-chat-loader-skeleton-avatar`,r.setAttribute(`aria-hidden`,`true`),n.append(r);for(let e of Mr){let t=document.createElement(`span`);t.className=`wui-chat-loader-skeleton-line`,t.setAttribute(`aria-hidden`,`true`),t.style.width=e,n.append(t)}return e.append(t,n),{el:e,render(e){t.textContent!==e.label&&(t.textContent=e.label)}}}var Pr=`http://www.w3.org/2000/svg`;function Fr(e){if(e===`done`){let e=document.createElementNS(Pr,`svg`);e.setAttribute(`viewBox`,`0 0 16 16`),e.setAttribute(`class`,`wui-chat-loader-steps-check`);let t=document.createElementNS(Pr,`path`);return t.setAttribute(`d`,`M3 8.5 6.5 12 13 4.5`),t.setAttribute(`pathLength`,`1`),e.append(t),e}let t=document.createElement(`span`);return t.className=e===`active`?`wui-chat-loader-steps-ring`:`wui-chat-loader-steps-dot`,t}function Ir(){let e=document.createElement(`div`);e.className=`wui-chat-loader-steps`;let t=document.createElement(`span`);t.className=`wui-chat-loader-steps-pill`;let n=document.createElement(`ol`);n.className=`wui-chat-loader-steps-list`,e.append(t,n);let r=[],i=null;function a(){let e=document.createElement(`li`);e.className=`wui-chat-loader-steps-item`;let t=document.createElement(`span`);t.className=`wui-chat-loader-steps-icon`,t.setAttribute(`aria-hidden`,`true`);let i=document.createElement(`span`);i.className=`wui-chat-loader-steps-text`,e.append(t,i);let a={li:e,icon:t,text:i,state:null};return r.push(a),n.append(e),a}function o(o,s=null){s!==i&&(i?.remove(),i=s,s!==null&&e.prepend(s));let c=o.steps.length===0;for(t.hidden=!c,n.hidden=c,c&&t.textContent!==o.label&&(t.textContent=o.label),o.steps.forEach((e,t)=>{let n=r[t]??a();n.text.textContent!==e&&(n.text.textContent=e);let i=t<o.activeIndex?`done`:t===o.activeIndex?`active`:`pending`;n.state!==i&&(n.state=i,n.li.dataset.state=i,n.icon.replaceChildren(Fr(i)))});r.length>o.steps.length;)r.pop()?.li.remove()}return{el:e,render:o}}var Lr={Steps:Ir,Phrases:kr,Orb:Er,Skeleton:Nr,PulseAndDots:jr},Rr=500;function zr(){let t=document.createElement(`div`);t.className=`wui-chat-loader`,t.setAttribute(`role`,`status`),t.hidden=!0;let n=document.createElement(`span`);n.className=`wui-chat-loader-avatar`,n.setAttribute(`aria-hidden`,`true`);let r=document.createElement(`div`);r.className=`wui-chat-loader-body`;let i=document.createElement(`span`);i.className=`visually-hidden`,t.append(n,r,i);let a=null,o=null,s=0,c=null,l=0,u=null,d=!1;function f(){c!==null&&clearInterval(c),c=null}function p(){t.isConnected?(s+=1,m()):f()}function m(){if(!o||!a)return;let e=pe(a.style,a.steps,a.phrases,s);o.render(e,a.mark),t.setAttribute(`aria-label`,e.label)}function h(){u!==null&&clearTimeout(u),u=null,d=!1,i.textContent=``}function g(e){!d&&u===null&&e&&(u=setTimeout(()=>{u=null,d=!0,i.textContent=e},Rr))}function _(n){if(!n.active)a=null,t.hidden=!0,t.removeAttribute(`data-loading`),f(),h();else{if(!e(Lr,n.style))throw Error(`Unknown loader style. Use Steps, Phrases, Orb, Skeleton or PulseAndDots.`);if(!(n.intervalMs>0))throw Error(`Loader intervalMs must be a positive number.`);if(a={...n,steps:n.steps??[],phrases:n.phrases??[],mark:n.mark??null},t.hidden=!1,t.setAttribute(`data-loading`,`true`),t.classList.toggle(`wui-chat-loader--reduced`,n.reduced===!0),!o||o.style!==n.style){let e=Lr[n.style]();r.replaceChildren(e.el),o={style:n.style,render:e.render},t.dataset.style=n.style,s=0}g(n.announce),n.reduced===!0?(f(),s=0):(c===null||l!==n.intervalMs)&&(f(),l=n.intervalMs,c=setInterval(p,l)),m()}}function v(){f(),h(),o=null,a=null,t.remove()}return{el:t,update:_,destroy:v}}function Br({voice:e,getLabels:t,message:n}){if(n.streaming||!e.canSpeak()||vn(n.parts)===``)return null;let r=e.getStatus(),i=r.mode===`Speaking`&&r.messageId===n.id,a=t(),o=i?a.readAloudStop:a.readAloud,s=v(`button`,`wui-chat-action-btn wui-chat-speak`,{type:`button`,"aria-pressed":String(i),"aria-label":o,title:o});return s.append(ln(i?`stop`:`speaker`,16)),s.addEventListener(`click`,()=>{e.toggleSpeak(n.id,n.parts)}),s}function Vr({voice:e,getLabels:t,message:n}){let r=e.getStatus().note;if(r?.code!==`SpeakFailed`||r.messageId!==n.id)return null;let i=v(`span`,`wui-chat-action-notice`,{role:`status`});return i.textContent=yn(r,t()),i}function Hr(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n?.author.kind===`Visitor`&&n.stored)return n}}var Ur=/* @__PURE__ */ new Set([`Assistant`,`Agent`]),Wr=/* @__PURE__ */ new Set([`Assistant`,`Agent`,`Script`]),Gr=/* @__PURE__ */ new Set([`Visitor`,`Customer`]),Kr=48,qr=120,Jr={author:{kind:`Assistant`,displayName:null,avatarUrl:null}},Yr={warning:`alert-triangle`,danger:`alert-circle`};function Xr(e,t,n,r,i){n!==null&&(n.dataset.state=i?`busy`:`rest`,r?n.parentNode!==e&&e.insertBefore(n,t):n.remove())}function Zr(e){return e.scrollHeight-e.scrollTop-e.clientHeight<=Kr}function Qr(e){let{kind:t,displayName:n}=e.author;return t===`Agent`?`Agent:${n??``}`:t===`Script`?`Assistant`:t}function $r(e){for(let t=e?.parentElement;t&&t!==document.body;t=t.parentElement){let{overflowY:e}=getComputedStyle(t);if((e===`auto`||e===`scroll`)&&t.scrollHeight>t.clientHeight)return t}return null}function ei(e){let t=e.textContent?.trim();t&&!e.hasAttribute(`aria-label`)&&(e.setAttribute(`aria-label`,t),e.setAttribute(`title`,t))}function ti(e){return e.reduced===!0}function ni(e,t,n){let r=v(`button`,`${l(`ghost`,`sm`)} wui-chat-action-btn`,{type:`button`,"aria-label":e,title:e}),a=v(`span`);return a.textContent=e,r.append(i(t,14),a),r.addEventListener(`click`,n),{node:r,text:a}}function ri(e,t){return e.profile?.assistant.name||t.assistant}function ii(e,t,n){return e.author.displayName==null?e.author.kind===`Visitor`||e.author.kind===`Customer`?n.you:e.author.kind===`Agent`?n.agent:t.profile?.assistant.name??n.assistant:e.author.displayName}function ai(e){let t=v(`li`,`wui-chat-day`,{role:`presentation`}),n=v(`span`);return n.textContent=e,t.append(n),t}function oi(e){let t=v(`ol`,`wui-chat-thread`),n=v(`div`,`wui-chat-log`,{role:`log`,"aria-live":`polite`});n.append(t);let r=zr(),a=v(`li`,`wui-chat-message wui-chat-message--assistant wui-chat-message--loading`),o=v(`div`,`wui-chat-loader-slot`);o.append(r.el);let s=e.mark?.(`loader`,`busy`)??null;a.append(o);let c=!1,u,d=v(`li`,`wui-chat-message wui-chat-message--assistant wui-chat-message--greeting`,{"data-run-start":``,"data-restored":``}),f=v(`div`,`wui-chat-message-body`),p=v(`p`,`wui-chat-text`);f.append(p),d.append(f);let m=e.mark?.(`reply`,`rest`)??null,h=v(`button`,`wui-chat-jump`,{type:`button`}),g=v(`div`,`wui-chat-jump-slot`);g.hidden=!0,g.append(h);let _=null,y=!0,x=null,S=null,C=/* @__PURE__ */ new Map,w=``,T=null;function E(e,t){return{kind:e.kind,part:e,tag:t[e.kind]}}function D(t,n,r){return Object.assign(document.createElement(t),{message:r,turn:e.makeTurnApi(r.id),chatPart:n})}function O(e){return v(`div`,`wui-chat-part wui-chat-part--${e.toLowerCase()}`)}function k(e,t,n,r){e.parts=[];let i=[],a=e=>{let r=E(e,n),i=O(r.kind);return i.append(D(r.tag,r.part,t)),i};for(let e of r(t))if(Array.isArray(e)){let t=v(`div`,`wui-chat-part-group`);t.append(...e.map(a)),i.push(t)}else i.push(a(e));e.body.replaceChildren(...i)}function A(t,n,r){let i=[];n.parts.forEach((a,o)=>{let s=E(a,r),c=t.parts[o];if(c&&c.kind===s.kind&&c.tag===s.tag){c.part!==s.part&&(c.element.message=n,c.element.turn=e.makeTurnApi(n.id),c.element.chatPart=s.part,c.part=s.part),i.push(c);return}let l=O(s.kind),u=D(s.tag,s.part,n);l.append(u),i.push({kind:s.kind,tag:s.tag,part:s.part,element:u,wrapper:l})}),t.parts=i,ee(t.body,i.map(e=>e.wrapper))}function ee(e,t){let n=new Set(t);for(let t of[...e.children])n.has(t)||t.remove();t.forEach((t,n)=>{e.children[n]!==t&&e.insertBefore(t,e.children[n]??null)})}function te(e,t,n){let r=v(`div`,`wui-chat-rating`,{role:`group`,"aria-label":`${n.rateUp} / ${n.rateDown}`}),a=[[`Up`,n.rateUp,`thumbs-up`],[`Down`,n.rateDown,`thumbs-down`]];for(let[o,s,c]of a){let a=t.rating===o,u=v(`button`,`${l(a?`neutral`:`ghost`,`sm`)} wui-chat-action-btn`,{type:`button`,"aria-pressed":String(a),"data-rating":o,"aria-label":s,title:s}),d=v(`span`);d.textContent=s,u.append(i(c,14),d),u.addEventListener(`click`,()=>ne(e,t,o,n)),r.append(u)}if(e.ratingNote){let t=v(`span`,null,{role:`status`});t.textContent=e.ratingNote,r.append(t)}return r}async function ne(t,n,r,i){try{await e.onRate(n.id,r),t.ratingNote=i.rated}catch{t.ratingNote=i.ratingFailed}T&&he(T.state,T.context)}function re(t,n,r,i,a){let{labels:o}=i,s=r.features,c=n.author.kind,l=N(n.parts),u=[];if(s.Copy&&Wr.has(c)&&l){let e=ni(o.copy,`copy`,()=>void(async()=>{await Ee(l)&&(e.text.textContent=o.copied,e.node.dataset.done=``,e.node.setAttribute(`aria-label`,o.copied),e.node.title=o.copied,clearTimeout(t.copyTimer),t.copyTimer=setTimeout(()=>{e.text.textContent=o.copy,delete e.node.dataset.done,e.node.setAttribute(`aria-label`,o.copy),e.node.title=o.copy},Te))})());u.push(e.node)}let d=e.getVoice?.();if(d&&Wr.has(c)){let e=Br({voice:d,getLabels:()=>o,message:n});e&&u.push(e);let t=Vr({voice:d,getLabels:()=>o,message:n});t&&u.push(t)}if(Wr.has(c)){let e=v(`div`);Zn(e,n,{labels:o,features:s,title:ri(r,o),assistantName:r.profile?.assistant.name,busy:r.streaming||r.thinking});for(let t of e.children)ei(t);u.push(...e.childNodes)}let f=r.messages.some(e=>e.author.kind===`Visitor`&&e.stored);a&&c===`Assistant`&&!r.streaming&&!r.thinking&&s.Regenerate&&f&&u.push(ni(o.regenerate,`refresh`,()=>e.onRegenerate()).node);let p=Hr(r.messages);s.Edit&&p?.id===n.id&&!r.streaming&&!r.thinking&&u.push(ni(o.edit,`pencil`,()=>e.getSession().startEdit(n.id)).node),s.Rating&&n.stored&&Ur.has(c)&&u.push(te(t,n,o)),t.actions.hidden=u.length===0,t.actions.replaceChildren(...u)}function ie(t){let n=C.get(t.id);if(n)return n;let r=v(`li`,`wui-chat-message`),i=v(`span`,`wui-chat-author visually-hidden`),a=v(`div`,`wui-chat-message-body`),o=v(`div`,`wui-chat-message-actions`);r.append(i,a,o);let s={li:r,author:i,body:a,actions:o,head:null,parts:[],copyTimer:void 0,ratingNote:null,mark:t.author.kind===`Assistant`?e.mark?.(`reply`,`rest`)??null:null};return C.set(t.id,s),s}function j(e,t,n,r){let i=n?.author.kind===`Agent`&&t.author.kind===`Agent`&&(n.author.displayName??``)===(t.author.displayName??``);e.head?.remove(),e.head=t.author.kind===`Agent`&&!i?ft(t.author,r):null,e.head&&e.li.insertBefore(e.head,e.body)}function ae(t,n,r,i,a,o){let{labels:s}=i;t.li.className=`wui-chat-message wui-chat-message--${n.author.kind.toLowerCase()}`,t.li.toggleAttribute(`data-restored`,n.restored===!0);let c=!o||Qr(o)!==Qr(n);t.li.toggleAttribute(`data-run-start`,c);let l=i.replyAvatars??`First`,u=n.author.kind===`Assistant`&&(l===`Every`||l===`First`&&c);Xr(t.li,t.body,t.mark,u,n.streaming),n.streaming?t.li.setAttribute(`aria-busy`,`true`):t.li.removeAttribute(`aria-busy`),t.author.textContent=`${ii(n,r,s)}: `,j(t,n,o,s);let d=e.getRenderers(),f=e.getLayoutParts();typeof f==`function`?k(t,n,d,f):A(t,n,d),n.streaming?(t.actions.hidden=!0,t.actions.replaceChildren()):re(t,n,r,i,a)}function se(e,t){let n=v(`li`,`wui-chat-message wui-chat-message--system wui-chat-message--notice`),r=v(`div`,`wui-chat-notice wui-chat-notice--${e}`,{role:e===`danger`?`alert`:`status`}),a=v(`span`,`wui-chat-notice-icon`,{"aria-hidden":`true`});a.append(i(Yr[e],16));let o=v(`div`,`wui-chat-notice-body`),s=v(`span`,`wui-chat-notice-text`);return s.textContent=t,o.append(s),r.append(a,o),n.append(r),n}function ce(e,t){let n=e.resetsDateTimeUtc?` ${t.dailyLimitRefresh(b(e.resetsDateTimeUtc))}`:``;return se(`warning`,`${e.message}${n}`)}function le(t,n){let{labels:r}=n,a=t.turnError,o=a?.code??``;if(a&&o===`daily_limit`)return ce(a,r);if(o.endsWith(`feature_off`))return se(`danger`,t.turnError?.message||r.stopped);let s=v(`li`,`wui-chat-message wui-chat-message--system wui-chat-message--error`),c=v(`p`,`wui-chat-error`,{role:`alert`});c.textContent=t.turnError?.message||r.stopped;let l=i(`alert-circle`,16);if(l.setAttribute(`aria-hidden`,`true`),s.append(l,c),t.features.Retry){let t=v(`div`,`wui-chat-message-actions`);t.append(ni(r.retry,`rotate-ccw`,()=>e.onRetry()).node),s.append(t)}return s}function ue(){return t.closest(`.wui-chat`)}function M(){return t.closest(`.wui-chat-body`)??$r(t)}function de(e){ue()?.classList.toggle(`wui-chat--scrolled`,e.scrollTop>0),Zr(e)&&(g.hidden=!0)}function fe(){_!==null&&(y=Zr(_),de(_))}function pe(e){n.nextElementSibling!==g&&n.parentNode&&n.after(g),e!==_&&(_?.removeEventListener(`scroll`,fe),_=e,e.addEventListener(`scroll`,fe,{passive:!0}),!x&&typeof ResizeObserver==`function`&&(x=new ResizeObserver(()=>{y&&_&&(_.scrollTop=_.scrollHeight)}),x.observe(t)))}h.addEventListener(`click`,()=>{let e=M(),t=T?.context.reduced===!0;e?.scrollTo({top:e.scrollHeight,behavior:t?`auto`:`smooth`}),g.hidden=!0,h.blur()});function me(e,t){let n=e.messages[e.messages.length-1],r=n?`${n.id}|${n.parts.length}|${N(n.parts).length}`:``;if(r===w)return;let i=w===``||e.conversationId!==S;w=r,S=e.conversationId;let a=M();a&&(pe(a),i||t||n!==void 0&&Gr.has(n.author.kind)?(a.scrollTop=a.scrollHeight,g.hidden=!0,y=!0):(g.hidden=!1,y=!1),de(a))}function he(e,i){T={state:e,context:i};let{labels:o}=i;n.setAttribute(`aria-label`,o.thread),h.textContent=o.newMessages??`New messages`;let l=M();l&&pe(l);let g=l===null||l.clientHeight===0||Zr(l),_=[],v=/* @__PURE__ */ new Set,y=e.messages.filter(e=>!(e.streaming&&e.parts.length===0)),b=y[0],x=b!==void 0&&Gr.has(b.author.kind)&&e.greeting?e.greeting:null,S=null,w=e=>{let t=oe(e.createdDateTimeUtc,o);t!==S&&(S=t,_.push(ai(t)))};x&&b&&(w(b),p.textContent=x,Xr(d,f,m,(i.replyAvatars??`First`)!==`None`,!1),_.push(d)),y.forEach((t,n)=>{let r=ie(t);v.add(t.id),w(t);let a=y[n-1]??(x?Jr:null);ae(r,t,e,i,n===y.length-1,a),_.push(r.li)});for(let e of[...C.keys()])v.has(e)||C.delete(e);e.agentTyping&&_.push(pt(e.agentTyping,o)),e.thinking?(clearTimeout(u),u=void 0,a.classList.remove(`wui-chat-message--leaving`),c=!0,r.update({active:!0,mark:s,style:i.loaderStyle,steps:e.steps,phrases:i.phrases,intervalMs:i.intervalMs,reduced:i.reduced,announce:i.assistantName?.trim()?o.preparingAnswer(i.assistantName):void 0}),_.push(a)):c&&u===void 0&&!ti(i)?(a.classList.add(`wui-chat-message--leaving`),u=setTimeout(()=>{u=void 0,c=!1,a.classList.remove(`wui-chat-message--leaving`),r.update({active:!1}),T&&he(T.state,T.context)},qr),_.push(a)):u===void 0?(c=!1,r.update({active:!1})):_.push(a),!e.streaming&&(e.turnError||e.stopped)&&_.push(le(e,i)),ee(t,_),me(e,g)}function ge(e){return C.get(e)?.li??null}function _e(){clearTimeout(u),r.destroy(),_?.removeEventListener(`scroll`,fe),x?.disconnect(),C.clear(),T=null,n.remove()}return{el:n,paint:he,find:ge,destroy:_e}}var si=[`launcher`,`docked`,`full-page`,`embedded`],ci=[`end`,`start`],li={steps:`Steps`,phrases:`Phrases`,orb:`Orb`,skeleton:`Skeleton`,"pulse-and-dots":`PulseAndDots`},ui={on:`On`,reduced:`Reduced`},di={still:`Still`,drift:`Drift`},fi=[`auto`,`light`,`dark`];function pi(e){return fi.find(t=>t===e)??`auto`}var mi=`wchat:muted`,hi=`wchat:open`,gi=6e4,_i=400,vi=[`labels`,`pageContext`,`compact`,`expressive`,`open`,`layoutParts`,`getCaptchaToken`,`attribution`,`openAttachment`,`openCitation`,`openTarget`,`openTicket`,`onNavigate`,`resolveLink`,`emptyContent`,`onPanelSwitch`,`preloadPanelSwitch`],yi={...pn};function bi(e,t){if(!E.includes(e))throw Error(`Unknown part kind "${e}". Use one of ${E.join(`, `)}.`);if(typeof t!=`string`||!t.includes(`-`))throw Error(`Renderer tag "${t}" must be a custom element name containing a hyphen.`)}function X(t,n){return r=>{let i=r.toLowerCase(),a=e(n,i)?n[i]:void 0;if(a===void 0)throw Error(`<wui-chat ${t}> must be one of ${Object.keys(n).join(`, `)}, got "${r}".`);return a}}function Z(e,t){return n=>{let r=Number(n),i=t===void 0?`of pixels`:`from 0 to ${t}`;if(!Number.isInteger(r)||r<0||t!==void 0&&r>t)throw Error(`<wui-chat ${e}> must be a whole number ${i}, got "${n}".`);return r}}function Q(e){return t=>{if(t===``||t===`true`)return!0;if(t===`false`)return!1;throw Error(`<wui-chat ${e}> must be true or false, got "${t}".`)}}var $=e=>e.split(`,`).map(e=>e.trim()).filter(Boolean),xi=[[`launcher-style`,`launcher`,`style`,X(`launcher-style`,{round:`Round`,pill:`Pill`,expanding:`Expanding`})],[`entrance`,`launcher`,`entrance`,X(`entrance`,{"slide-up":`SlideUp`,"bounce-in":`BounceIn`,"fade-in-pulse":`FadeInPulse`,"spin-scale":`SpinScale`,"wiggle-in":`WiggleIn`,"elastic-in":`ElasticIn`,rise:`Rise`,none:`None`})],[`idle`,`launcher`,`idle`,X(`idle`,{"float-and-pulse":`FloatAndPulse`,ring:`Ring`,none:`None`})],[`label-reveal`,`launcher`,`labelReveal`,X(`label-reveal`,{bubble:`Bubble`,expand:`Expand`})],[`compact`,`launcher`,`compact`,Q(`compact`)],[`launcher-mark`,`launcher`,`mark`,X(`launcher-mark`,{icon:`Icon`,avatar:`Avatar`,orb:`Orb`})],[`panel-height`,`panel`,`height`,X(`panel-height`,{fixed:`Fixed`,content:`Content`})],[`panel-placement`,`panel`,`placement`,X(`panel-placement`,{floating:`Floating`,side:`Side`})],[`reply-avatars`,`panel`,`replyAvatars`,X(`reply-avatars`,{none:`None`,first:`First`,every:`Every`})],[`greeting-loader-ms`,`panel`,`greetingLoaderMs`,Z(`greeting-loader-ms`)],[`panel-motion`,`panel`,`motion`,X(`panel-motion`,{spring:`Spring`,gentle:`Gentle`,none:`None`})],[`panel-width`,`panel`,`widthPx`,Z(`panel-width`)],[`panel-max-height`,`panel`,`maxHeightPx`,Z(`panel-max-height`)],[`panel-bottom-gap`,`panel`,`bottomGapPx`,Z(`panel-bottom-gap`)],[`phone-max-width`,`phone`,`maxWidthPx`,Z(`phone-max-width`)],[`phone-mode`,`phone`,`mode`,X(`phone-mode`,{"full-screen":`FullScreen`,sheet:`Sheet`})],[`sheet-height-dvh`,`phone`,`sheetHeightDvh`,Z(`sheet-height-dvh`)],[`sheet-max-height`,`phone`,`sheetMaxHeightPx`,Z(`sheet-max-height`)],[`phone-hide-launcher`,`phone`,`hideLauncher`,Q(`phone-hide-launcher`)],[`input-ring`,`input`,`ring`,Q(`input-ring`)],[`send-reveal`,`input`,`sendReveal`,X(`send-reveal`,{"on-text":`OnText`,always:`Always`})],[`send-icon`,`input`,`sendIcon`,e=>e],[`input-mark`,`input`,`mark`,X(`input-mark`,{none:`None`,avatar:`Avatar`})],[`footer-layout`,`footer`,`layout`,X(`footer-layout`,{stacked:`Stacked`,inline:`Inline`})],[`input-edge`,`input`,`edge`,X(`input-edge`,{none:`None`,gradient:`Gradient`})],[`input-placeholder`,`input`,`placeholder`,X(`input-placeholder`,{plain:`Plain`,gradient:`Gradient`})],[`input-busy-edge`,`input`,`busyEdge`,X(`input-busy-edge`,{off:`Off`,sweep:`Sweep`})],[`starters-style`,`starters`,`style`,X(`starters-style`,{chips:`Chips`,rows:`Rows`})],[`recent-rows`,`starters`,`recentRows`,Z(`recent-rows`,A)],[`footer-disclaimer`,`footer`,`disclaimer`,X(`footer-disclaimer`,{show:`Show`,hide:`Hide`})],[`lift-selectors`,`avoid`,`liftSelectors`,$],[`menu-selectors`,`avoid`,`menuSelectors`,$],[`dark-selectors`,`avoid`,`darkSelectors`,$],[`autoopen-busy-selectors`,`avoid`,`autoOpenBusySelectors`,$],[`autoopen-optout-selector`,`avoid`,`autoOpenOptOutSelector`,e=>e]],Si={layout:`launcher`,position:`end`,"offset-x":`24`,"offset-y":`24`,loader:`steps`,motion:`on`,icon:`chat`},Ci=[`base`,`layout`,`position`,`offset-x`,`offset-y`,`loader`,`screen`,`motion`,`theme`,`icon`,`avatar`,`avatar-motion`,`narrow`,...xi.map(([e])=>e).filter(e=>e!==`compact`)],wi=e=>e.replace(/-([a-z0-9])/g,(e,t)=>t.toUpperCase());function Ti(e){let t={launcher:{},panel:{},phone:{},input:{},avoid:{},footer:{},starters:{}};for(let[n,r,i,a]of xi){let o=e.getAttribute(n);o!=null&&(t[r][i]=a(o))}let n=e.getAttribute(`motion`),r=e.getAttribute(`avatar`),i=e.getAttribute(`avatar-motion`),a=e.getAttribute(`expressive`),o={...t,...n==null?{}:{motion:X(`motion`,ui)(n)},...r?{avatar:r}:{},...i==null?{}:{avatarMotion:X(`avatar-motion`,di)(i)},...a==null?{}:{expressive:Q(`expressive`)(a)}};return he(o)}function Ei(t){let n=t.getAttribute(`loader`)??`steps`,r=e(li,n)?li[n]:void 0;if(r===void 0)throw Error(`<wui-chat loader> must be one of ${Object.keys(li).join(`, `)}, got "${n}".`);return r}function Di(e){let t=e.getAttribute(`narrow`);if(t!=null&&t!==``)return Object.fromEntries($(t).map(e=>[e,!1]))}function Oi(e){return e===mi?globalThis.localStorage:globalThis.sessionStorage}var ki={get:e=>Oi(e).getItem(e),set:(e,t)=>Oi(e).setItem(e,t)};function Ai(e){return globalThis.innerWidth<=e.phone.maxWidthPx}function ji(e){let t=requestAnimationFrame(e);return()=>cancelAnimationFrame(t)}function Mi(e){return e.features.HumanHandoff===!0&&e.conversationState===`Open`&&e.messages.some(e=>e.author.kind===`Visitor`||e.author.kind===`Customer`)&&!e.streaming&&!e.thinking}function Ni(e,t){if(e.conversationState===`WaitingForAgent`)return t.statusWaitingForAgent;if(e.conversationState===`WithAgent`){let n=e.agent?.displayName;return t.statusWithAgent(typeof n==`string`&&n.trim()!==``?n:t.handoffAgentFallback)}return t.headerStatus}function Pi(e,t,n){return t.PanelSwitch!==!0||typeof n!=`function`?null:e===`docked`?`full-page`:e===`full-page`?`docked`:null}function Fi(e){if(!si.some(t=>t===e))throw Error(`<wui-chat layout> must be one of ${si.join(`, `)}, got "${e}".`)}function Ii(e){if(!ci.some(t=>t===e))throw Error(`<wui-chat position> must be one of ${ci.join(`, `)}, got "${e}".`)}function Li(e,t){let n=e[t];delete e[t],e[t]=n}function Ri(e){return e==null?{}:Object(e)}var zi=0,Bi=class extends Me{static get observedAttributes(){return[...Ci,`compact`,`expressive`,`open`,`labels`,`page-context`,`narrow`].filter((e,t,n)=>n.indexOf(e)===t)}constructor(){super(),zi+=1,this._uid=`wui-chat-${zi}`,this._built=!1,this._session=null,this._unsubscribe=null,this._voice=null,this._voiceConversationId=void 0,this._labelsProp=void 0,this._pageContextProp=void 0,this._layoutParts=null,this._renderers={...yi},this._rendererApi={define:(e,t)=>{bi(e,t),this._renderers[e]=t,this._render()},map:this._renderers},this._captchaToken=null,this._attribution=null,this._openAttachmentProp=null,this._openCitationProp=null,this._openTargetProp=null,this._resolveLinkProp=null,this._openTicketProp=void 0,this._emptyContentProp=null,this._onPanelSwitchProp=null,this._preloadPanelSwitchProp=null,this._preloaded=!1,this._pastList=null,this._past=null,this._pastRefreshed=!1,this._historyShown=!1,this._openedConversation=null,this._lastOpen=!1,this._openTrigger=`manual`,this._focusTimer=null,this._nudgeArmed=!1,this._seeded=!1,this._wasLoading=!1,this._seen=/* @__PURE__ */ new Set,this._sound=null,this._behaviour=null,this._autoOpen=null,this._avoid=null,this._motion=null,this._phone=null,this._requesting=!1,this._onKeyDown=e=>{e.key===`Escape`&&this._session?.getState().open&&(e.stopPropagation(),this._session.close(`escape`))}}get session(){return this._session??null}get conversationId(){return this._session?.getState().conversationId??null}get labels(){return me({...Ri(a(this,`labels`)),...this._labelsProp})}set labels(e){this._labelsProp=e??void 0,this._render()}get pageContext(){return this._pageContextProp===void 0?a(this,`page-context`):this._pageContextProp}set pageContext(e){this._pageContextProp=e===null?void 0:e}get compact(){let e=this.getAttribute(`compact`);return e!=null&&Q(`compact`)(e)}set compact(e){this.toggleAttribute(`compact`,e===!0||e===``||e===`true`)}get expressive(){let e=this.getAttribute(`expressive`);return e!=null&&Q(`expressive`)(e)}set expressive(e){this.toggleAttribute(`expressive`,e===!0||e===``||e===`true`)}get open(){return this.hasAttribute(`open`)}set open(e){this.toggleAttribute(`open`,e===!0||e===``||e===`true`)}get renderers(){return this._rendererApi}get layoutParts(){return this._layoutParts}set layoutParts(e){this._layoutParts=typeof e==`function`?e:null,this._render()}get getCaptchaToken(){return this._captchaToken}set getCaptchaToken(e){this._captchaToken=typeof e==`function`?e:null}get attribution(){return this._attribution}set attribution(e){this._attribution=typeof e==`function`?e:null}get openAttachment(){return this._openAttachmentProp??(e=>this._defaultOpenAttachment(e))}set openAttachment(e){this._openAttachmentProp=typeof e==`function`?e:null}get openCitation(){return this._openCitationProp??((e,t)=>this._defaultOpenCitation(e,t))}set openCitation(e){this._openCitationProp=typeof e==`function`?e:null}get openTarget(){return this._openTargetProp??(e=>this._defaultOpenTarget(e))}set openTarget(e){this._openTargetProp=typeof e==`function`?e:null}get openTicket(){return this._openTicketProp}set openTicket(e){this._openTicketProp=typeof e==`function`?e:void 0}get onNavigate(){return this._onNavigateProp}set onNavigate(e){this._onNavigateProp=typeof e==`function`?e:void 0}get resolveLink(){return this._resolveLinkProp}set resolveLink(e){this._resolveLinkProp=typeof e==`function`?e:null}get emptyContent(){return this._emptyContentProp}set emptyContent(e){if(e!==null&&!(e instanceof Node))throw TypeError(`emptyContent must be a Node or null`);this._emptyContentProp=e,this._applyEmptyContent()}get onPanelSwitch(){return this._onPanelSwitchProp}set onPanelSwitch(e){this._onPanelSwitchProp=typeof e==`function`?e:null}get preloadPanelSwitch(){return this._preloadPanelSwitchProp}set preloadPanelSwitch(e){this._preloadPanelSwitchProp=typeof e==`function`?e:null}connectedCallback(){this._adoptEarlyProperties(),!this._built&&this.querySelector(`:scope > [data-wui-chat-placeholder]`)!==null&&(this._launcherPlayed=!0);let e=this._assertLayout();if(this._assertPosition(),this.base.trim()===``)throw TypeError(`<wui-chat> needs a base path, e.g. base="/api/assistant".`);this._built||this._build(),this._shell||this._buildShell(e),this._session||this._createSession(),this._past||this._createPast(),this._unsubscribe||=this.requireSession().subscribe(()=>this._render()),this._render()}_adoptEarlyProperties(){for(let t of vi)e(this,t)&&Li(this,t)}disconnectedCallback(){this._voice?.stop(),this._session?.stop(),this._unsubscribe?.(),this._unsubscribe=null,this._disposePast(),this._shell?.destroy?.(),document.removeEventListener(`keydown`,this._onKeyDown),this._avoid?.destroy(),this._avoid=null,this._autoOpen?.cancel(),this._autoOpen=null,this._motion?.destroy(),this._motion=null}attributeChangedCallback(e,t,n){if(this._built&&t!==n){if(e===`layout`)this._buildShell(this._assertLayout());else if(e===`position`)this._assertPosition();else if(e===`base`||e===`screen`||e===`narrow`)this._resetSession();else if(e===`motion`)this._motion?.destroy(),this._motion=null;else if(e===`open`&&this._session){let e=this._session.getState().open;this.open!==e&&this._setOpen(this.open,`manual`)}this._render()}}toggle(){this._session&&(this._session.getState().open?this._session.close(`button`):this._setOpen(!0,`manual`))}close(){this._voice?.stop(),this._session?.close(`button`)}newConversation(){this._voice?.stop(),this._session?.newConversation(),this._past?.refresh()}reset(){this._voice?.stop(),this._session?.reset()}_setOpen(e,t){this._session&&(e?(this._openTrigger=t,this._session.open({trigger:t})):this._session.close(`button`))}_assertLayout(){let e=this.layout;return Fi(e),e}_assertPosition(){Ii(this.position)}get _position(){let e=this.position;return Ii(e),e}_isLauncherLike(){return this.layout===`launcher`||this.layout===`docked`}requireSession(){if(!this._session)throw TypeError(`wui-chat: _session is not ready; the element is not connected`);return this._session}requireVoice(){if(!this._voice)throw TypeError(`wui-chat: _voice is not ready; the element is not connected`);return this._voice}requireMotion(){if(!this._motion)throw TypeError(`wui-chat: _motion is not ready; the element is not connected`);return this._motion}requirePastList(){if(!this._pastList)throw TypeError(`wui-chat: _pastList is not ready; the element is not connected`);return this._pastList}requireNudgeHost(){if(!this._shell.nudgeHost)throw TypeError(`wui-chat: the launcher shell has no nudge host`);return this._shell.nudgeHost}_build(){this._built=!0,this._markMaker=t(n(this)),this._header=Nn({onNew:()=>this.newConversation(),onHistory:()=>this._toggleHistory(),onClose:()=>this.close(),onMute:()=>{this._session&&this._session.setMuted(!this._session.getState().muted)},onSwitch:()=>this._switchPanel(),titleId:`${this._uid}-title`,mark:this._markMaker}),this._starters=Tr({mark:this._markMaker,onStarter:e=>this.requireSession().submit(e.message),onResume:()=>this.requireSession().resumeLast(),onTicket:e=>{typeof this.openTicket==`function`&&this.openTicket({ticketId:e.ticketId,number:e.number})},onOpenConversation:e=>{Promise.allSettled([this.requireSession().openConversation(e)])}}),this._applyEmptyContent(),this._voice=bn({getState:()=>this.requireSession().getState(),getToken:()=>this.requireSession().client.getSpeechToken()}),this._voice.subscribe(()=>this._render()),this._thread=oi({mark:this._markMaker,getRenderers:()=>this._renderers,getLayoutParts:()=>this._layoutParts,makeTurnApi:e=>this._makeTurnApi(e),onRetry:()=>this.requireSession().retry(),onRegenerate:()=>this.requireSession().regenerate(),onRate:(e,t)=>this.requireSession().rate(e,t),getSession:()=>this.requireSession(),getVoice:()=>this._voice}),this._composer=On({mark:this._markMaker,voice:this._voice,onSubmit:e=>this.requireSession().submit(e),onStop:()=>this.requireSession().stop(),onAttach:e=>this.requireSession().attach(e),onRemove:e=>this.requireSession().removeAttachment(e),onCancelEdit:()=>this.requireSession().cancelEdit(),onTyping:()=>this.requireSession().notifyTyping(),onDraftApplied:()=>this.requireSession().consumeDraft()}),this._footer=Mn(),this._history=Fn({getClient:()=>this.requireSession().client,getLabels:()=>this.labels,getFeatures:()=>this.requireSession().getState().features,onOpen:e=>{Promise.allSettled([this.requireSession().openConversation(e)]),this._toggleHistory(!1)},onDeleted:e=>{e===this.conversationId&&this.requireSession().newConversation()}}),this._nudge=Vn({onActivate:()=>this._setOpen(!0,`manual`),onDismiss:()=>{}}),this._status=v(`p`,null,{role:`status`}),this._status.hidden=!0,this._errorEl=v(`p`,`wui-chat-profile-error`,{role:`alert`}),this._errorEl.hidden=!0,this._liveStatus=v(`p`,`wui-chat-live-status`,{role:`status`}),this._liveStatus.hidden=!0,this._talk=v(`button`,`${l(`outline`,`sm`)} wui-chat-handoff-request`,{type:`button`}),this._talk.addEventListener(`click`,()=>this._requestHandoff()),this._liveRetry=v(`button`,l(`ghost`,`sm`),{type:`button`}),this._liveRetry.addEventListener(`click`,()=>this.requireSession().resumeLive()),this._liveError=v(`p`,`wui-chat-live-error`,{role:`alert`}),this._liveError.hidden=!0,this._live=v(`div`,`wui-chat-live`),this._live.append(this._liveStatus,this._talk,this._liveRetry,this._liveError),this._live.hidden=!0,this._body=v(`div`,`wui-chat-body`),this._body.append(this._starters.el,this._thread.el,this._live,this._history.el,this._status,this._errorEl),this._foot=v(`div`,`wui-chat-foot`),this._foot.append(...this._composer.nodes,this._footer.el)}_buildShell(e){let t={launcher:vr,docked:pr,"full-page":yr,embedded:mr};this._shell?.destroy?.(),this._avoid?.destroy(),this._avoid=null,this._autoOpen?.cancel(),this._autoOpen=null,this._lastOpen=!1,this._launcherPlayed=!1;let n=t[e]({mark:this._markMaker,id:`${this._uid}-panel`,position:this._position,onToggle:()=>this.toggle()});n.panel.append(this._header.el,this._body,this._foot),n.panel.setAttribute(`aria-labelledby`,`${this._uid}-title`),n.panel.addEventListener(`keydown`,e=>{e.key===`Tab`&&y(n.panel,e)}),n.nudgeHost&&n.nudgeHost.prepend(this._nudge.el),this._shell=n,this.replaceChildren(n.root)}_createSession(){let e=te(Bn(),{base:this.base}),t=Di(this);this._session=ne(e,{...this.screen?{screen:this.screen}:{},...t===void 0?{}:{narrow:t},recentConversations:Ti(this).starters.recentRows,pageContext:()=>this.pageContext,attribution:()=>this._attribution?.()??null,behaviour:()=>this._session?.getState().features.BehaviourStarters?this._behaviour?.()??null:null,prefs:ki,reducedMotion:()=>this._motion?.reduced??!1,schedule:ji,getCaptchaToken:e=>{if(this._captchaToken)return this._captchaToken(e);let t=this._session?.getState().profile?.captcha?.siteKey;return t?Jn(t,e):Promise.resolve(null)},onEvent:(e,t)=>{this.dispatchEvent(new CustomEvent(`wui-chat-event`,{bubbles:!0,detail:{name:e,data:t}}))},onError:()=>{},labels:this.labels}),this._unsubscribe=null,this._lastOpen=!1,this._openApplied=!1,this._seeded=!1,this._wasLoading=!1,this._seen=/* @__PURE__ */ new Set,this._pastRefreshed=!1}_createPast(){this._pastList=re({client:this.requireSession().client,pageSize:20}),this._past=Un({list:this._pastList,getLabels:()=>this.labels,getFeatures:()=>this.requireSession().getState().features,onOpen:e=>{Promise.allSettled([this.requireSession().openConversation(e)])}}),this._starters.pastHost.append(this._past.el)}_disposePast(){this._past&&(this._past.el.remove(),this._past.dispose(),this.requirePastList().dispose(),this._past=null,this._pastList=null)}_applyEmptyContent(){if(!this._starters)return;let e=this._starters.extraHost;e.replaceChildren(...this._emptyContentProp?[this._emptyContentProp]:[]),e.hidden=!this._emptyContentProp}_switchPanel(){let e=this.requireSession().getState(),t=this._onPanelSwitchProp,n=Pi(this.layout,e.features,t);if(t===null||n===null)return;n===`full-page`&&this.close();let r={from:this.layout,to:n,conversationId:e.conversationId,draft:this._composer.getDraft()};w(()=>t.call(this,r),{target:n,reduced:this._motion?.reduced===!0}).then(()=>document.querySelector(`.wui-chat--${n} .wui-chat-input`)?.focus()).catch(e=>globalThis.reportError?.(e))}async _requestHandoff(){this._requesting=!0,this._liveError.hidden=!0,this._render();try{await this.requireSession().requestHandoff()}catch(e){let t=typeof e==`object`&&e&&`message`in e?e.message:void 0;this._liveError.textContent=typeof t==`string`&&t||this.labels.errorGeneric,this._liveError.hidden=!1}finally{this._requesting=!1,this._render()}}_paintLive(e,t,n){let r=e.live===`Lost`,i=Mi(e);this._liveStatus.hidden=!r,this._liveStatus.textContent=r?t.liveLost:``,this._liveRetry.hidden=!r,this._liveRetry.textContent=t.retry,this._talk.hidden=!i,this._talk.textContent=t.talkToPerson,this._talk.disabled=this._requesting,this._live.hidden=n||!r&&!i}_resetSession(){this._voice?.stop(),this._unsubscribe?.(),this._unsubscribe=null,this._session?.dispose(),this._session=null,this._disposePast(),this._history.dispose(),this.isConnected&&(this._createSession(),this._createPast(),this._unsubscribe=this.requireSession().subscribe(()=>this._render()))}_toggleHistory(e=!this._historyShown){this._historyShown=e,e?this._history.show():this._history.hide(),this._render()}_makeTurnApi(e){let t=ie(this.requireSession(),{messageId:e,labels:this.labels,openAttachment:e=>this.openAttachment(e),openCitation:t=>this.openCitation(e,t),openTarget:e=>this.openTarget(e),openTicket:this.openTicket,onNavigate:this.onNavigate});return t.resolveLink=this.resolveLink,t}_defaultOpenAttachment(e){this.requireSession().client.getAttachment(e.attachmentId).then(t=>{let n=URL.createObjectURL(new Blob([t],{type:e.contentType}));window.open(n,`_blank`,`noopener`),setTimeout(()=>URL.revokeObjectURL(n),gi)}).catch(e=>globalThis.reportError?.(e))}_defaultOpenCitation(e,t){let n=this._thread.find(e);if(n){for(let e of n.querySelectorAll(`[data-marker]`))if(e.dataset.marker===String(t)){e.focus();return}}}_defaultOpenTarget(e){/^https?:\/\//i.test(e)?window.open(e,`_blank`,`noopener`):window.location.assign(e)}_render(){this._built&&this._session&&this._paint(this._session.getState())}_paint(e){this._shell.root.toggleAttribute(`data-busy`,e.streaming||e.thinking),e.conversationId!==this._voiceConversationId&&(this._voiceConversationId=e.conversationId,this.requireVoice().stop());let t=this.labels,n=e.profile,r=this._isLauncherLike();if(!n){this.hidden=r,this._header.el.hidden=!0,this._starters.el.hidden=!0,this._thread.el.hidden=!0,this._history.el.hidden=!0,this._foot.hidden=!0,this._errorEl.hidden=e.profileError==null,e.profileError&&(this._errorEl.textContent=e.profileError.message),this._status.hidden=e.profileError!=null,this._status.textContent=t.loadingConversation,this._shell.panel.setAttribute(`aria-busy`,String(e.profileError==null));return}if(this._shell.panel.removeAttribute(`aria-busy`),!e.features.VisitorChat){this.hidden=!0,this._status.hidden=!0;return}this.hidden=!1;let i=e.features,a=Ti(this);this._ensureRuntime(e,n,a,t);let o=e.loading,s=e.loadError,c=e.messages.length===0&&!o,l=this._historyShown&&i.History===!0,u=e.messages.some(e=>e.author.kind===`Visitor`||e.author.kind===`Customer`),d=Pi(this.layout,i,this._onPanelSwitchProp),f=e.streaming||e.thinking;this._header.paint({labels:t,title:t.panelTitle||n.assistant.name||t.assistant,tagline:n.assistant.tagline,status:Ni(e,t),canNew:!f,showNew:this.layout===`full-page`||u,showHistory:i.History,showClose:r||this.layout===`full-page`&&d!==null,switchTo:d,canSwitch:!f,viewingHistory:l,showMute:i.Sounds&&n.experience.sound.muteControl,muted:e.muted}),Qn(this._header.conversation,e,{labels:t,features:i,title:n.assistant.name||t.assistant,getState:()=>this.requireSession().getState(),iconOnly:!0}),l&&(this._header.conversation.hidden=!0),this._starters.el.hidden=!c||l,c&&e.open&&!this._introPlayed&&a.panel.greetingLoaderMs>0&&!this.requireMotion().reduced&&(this._introPlayed=!0,this._starters.intro(a.panel.greetingLoaderMs)),c&&this._starters.paint({labels:t,greeting:e.greeting,intro:n.assistant.intro,starters:e.starters,showStarters:i.Starters&&!e.streaming,resume:!i.History&&i.ResumeLast?e.lastConversation:null,recent:e.recentConversations,openTickets:e.openTickets,features:e.features,ticketsClickable:typeof this.openTicket==`function`}),i.History&&!this._pastRefreshed&&(this._pastRefreshed=!0,this._past?.refresh()),this._past?.paint(),this._starters.pastHost.hidden=e.recentConversations.length>0;let p=!c&&!o&&!s&&!l;this._thread.el.hidden=!p,p&&this._thread.paint(e,{labels:t,loaderStyle:Ei(this),reduced:this._motion?.reduced??!1,phrases:n.experience.pacing.thinkingPhrases,intervalMs:n.experience.pacing.phraseIntervalMs,assistantName:n.assistant.name,replyAvatars:a.panel.replyAvatars}),this._paintLive(e,t,l),this._status.hidden=!o||l,this._status.textContent=t.loadingConversation,this._errorEl.hidden=!s||l,s&&(this._errorEl.textContent=s.message),this._foot.hidden=l,this._composer.paint({state:e,labels:t,maxLength:n.limits.maxMessageLength,accept:n.limits.contentTypes.join(`,`),draft:e.draft??null,sendIcon:a.input.sendIcon,inputMark:a.input.mark,busy:e.streaming||e.thinking}),this._footer.paint({labels:t,profile:n,hideDisclaimer:a.footer.disclaimer===`Hide`}),this._history.el.hidden=!l,this._syncOpen(e,n,i,t,r),this._syncConversation(e),this._playSounds(e)}_ensureRuntime(e,t,n,i){let a=e.features;this._motion||(this._motion=r(n,t.experience),this._motion.subscribe(()=>this._render())),a.Sounds&&!this._sound&&(this._sound=d(t.experience.sound,ki)),!a.Sounds&&this._sound&&(this._sound=null),a.BehaviourStarters&&!this._behaviour&&(this._behaviour=m(t.start.behaviour?.servicePathPrefixes??[]));let o=this._isLauncherLike();o&&!this._avoid&&this.layout===`launcher`&&(this._avoid=h(n.avoid,t.experience.launcher,this.requireNudgeHost(),this._shell.setLauncherState)),this.layout===`launcher`&&a.AutoOpen&&!this._autoOpen&&(this._autoOpen=C(t.experience.autoOpen,n,{open:()=>this._setOpen(!0,`auto`),isOpen:()=>this.requireSession().getState().open,panelRect:()=>this._shell.panel.getBoundingClientRect()}));let s=Ai(n);this._shell.setLabels(i),this._shell.setAppearance({position:this._position,offsetX:this.hasAttribute(`offset-x`)?Z(`offset-x`)(this.getAttribute(`offset-x`)??``):void 0,offsetY:this.hasAttribute(`offset-y`)?Z(`offset-y`)(this.getAttribute(`offset-y`)??``):void 0,width:`${n.panel.widthPx}px`,maxHeight:n.panel.maxHeightPx,bottomGap:n.panel.bottomGapPx,reduced:this._motion.reduced,sendReveal:n.input.sendReveal,inputRing:n.input.ring,panelMotion:n.panel.motion,theme:pi(this.getAttribute(`theme`)),icon:this.icon,launcherStyle:n.launcher.style,compact:n.launcher.compact,labelReveal:n.launcher.labelReveal,entrance:n.launcher.entrance,idle:n.launcher.idle,launcherMark:n.launcher.mark,panelHeight:n.panel.height,panelPlacement:n.panel.placement,inputMark:n.input.mark,inputEdge:n.input.edge,inputBusyEdge:n.input.busyEdge,inputPlaceholder:n.input.placeholder,phoneHideLauncher:n.phone.hideLauncher,replyAvatars:n.panel.replyAvatars,footerLayout:n.footer.layout,startersStyle:n.starters.style,avatar:n.avatar,avatarMotion:n.avatarMotion,expressive:n.expressive,phone:s,hoverLabel:t.experience.launcher.hoverLabel,peek:t.experience.launcher.peek,peekSeconds:t.experience.launcher.peekSeconds,hideWhileOpen:t.experience.launcher.hideWhileOpen,phoneMode:n.phone.mode,sheetHeightDvh:n.phone.sheetHeightDvh,sheetMaxHeightPx:n.phone.sheetMaxHeightPx,launcherState:this._launcherPlayed?void 0:`entering`}),this._launcherPlayed=!0,this._shell.root.classList.toggle(`wui-chat--phone`,o&&Ai(n))}_syncOpen(e,t,n,r,i){if(i){if(!this._openApplied&&(this._openApplied=!0,this.hasAttribute(`open`)&&!e.open))this._setOpen(!0,`manual`);else if(this._shell.setOpen(e.open),this.toggleAttribute(`open`,e.open),e.open!==this._lastOpen&&(this._lastOpen=e.open,ki.set(hi,e.open?`1`:`0`),this._onOpenChange(e.open)),e.open)this._nudge.cancel(),this._nudgeArmed=!1,this._autoOpen?.cancel();else if(n.Nudges&&this.layout===`launcher`&&!this._nudgeArmed){let e=ge(t,n);e&&(this._nudge.schedule({text:e.text,delaySeconds:e.delaySeconds,label:r.nudgeDismiss}),this._nudgeArmed=!0)}}}_onOpenChange(e){let t=Ai(Ti(this));if(e){if(document.addEventListener(`keydown`,this._onKeyDown),this._sound?.play(`open`),this._past?.refresh(),this.layout===`docked`&&!this._preloaded&&typeof this._preloadPanelSwitchProp==`function`){this._preloaded=!0;let e=this._preloadPanelSwitchProp;Promise.allSettled([new Promise(t=>t(e.call(this)))]).then(e=>{for(let t of e)t.status===`rejected`&&globalThis.reportError?.(t.reason)})}if(t){let e=Ti(this);this._phone={fit:x(this._shell.panel,e),unlock:S(this._thread.el)}}else this._openTrigger===`manual`&&(this._focusTimer=setTimeout(()=>{this._focusTimer=null,this._composer.focus()},_i))}else document.removeEventListener(`keydown`,this._onKeyDown),clearTimeout(this._focusTimer??void 0),this._focusTimer=null,this._phone?.fit.destroy(),this._phone?.unlock(),this._phone=null,this._historyShown&&(this._historyShown=!1,this._history.hide(),this._render()),p(this._shell.launcherButton)}_syncConversation(e){let t=this.getAttribute(`conversation-id`);t&&t!==this._openedConversation&&!e.loading&&(this._openedConversation=t,e.conversationId!==t&&Promise.allSettled([this.requireSession().openConversation(t)]))}_playSounds(e){if(e.loading){this._wasLoading=!0;for(let t of e.messages)this._seen.add(t.id)}else if(this._wasLoading||!this._seeded){this._wasLoading=!1,this._seeded=!0;for(let t of e.messages)this._seen.add(t.id)}else for(let t of e.messages)this._seen.has(t.id)||(this._seen.add(t.id),this._announce(t))}_announce(e){if(!this._sound||e.restored||e.parts.some(e=>e.kind===`Notice`))return;let t=e.author.kind;if(t===`Visitor`)e.stored||this._sound.play(`sent`);else if(t===`Assistant`||t===`Script`||t===`Agent`){this._sound.play(`reply`);let e=this.requireSession().getState().profile;e?.experience.sound.vibrate&&T(e.experience.sound.vibrateMs,this._sound.isMuted())}}};Object.defineProperty(Bi.prototype,"layout",{get(){return this.getAttribute(`layout`)??Si.layout},set(e){this.setAttribute(`layout`,String(e))}});for(let e of Ci)e!==`layout`&&Object.defineProperty(Bi.prototype,wi(e),{configurable:!0,get(){return this.getAttribute(e)??Si[e]??``},set(t){t==null?this.removeAttribute(e):this.setAttribute(e,String(t))}});function Vi(){typeof customElements<`u`&&!customElements.get(`wui-chat`)&&customElements.define(`wui-chat`,Bi)}Vi();export{Bi as WuiChat,Bn as createFetchChatHttp,pn as defaultRenderers,Vi as defineChat};
|
|
1
|
+
import{A as e,D as t,E as n,F as r,L as i,M as a,N as o,O as s,P as c,S as l,T as u,_ as d,a as f,b as p,c as m,d as h,f as g,g as _,j as v,k as y,l as b,m as x,n as S,o as C,p as w,r as T,s as E,w as D,x as O,y as k}from"./web-3uVmvlge.js";import{CHAT_HANDOFF_REQUEST_ID as A,CHAT_RECENT_ROWS_MAX as ee,buildTranscript as te,createChatClient as ne,createChatSession as re,createConversationList as j,createTurnApi as ie,formatChatDate as M,formatChatDateTime as ae,formatChatDay as oe,formatChatValue as se,formatClipTime as ce,formatFigure as le,formatFileSize as ue,isHandoffTarget as de,isSafeActionHref as fe,isSafePrivacyUrl as pe,loaderView as me,mergeLabels as he,mergeLook as ge,messagePlainText as N,resolveNudge as _e,showsCaptchaNote as ve,sniffAudioType as ye,toFigureRuns as be,toFigureText as xe,transcriptToText as Se,voiceClipBars as Ce}from"@webority/chat-core";import{linkTarget as we,parseInline as Te}from"@webority/markdown-core";import{COPY_FEEDBACK_MS as Ee,copyTextToClipboard as De,emptyValueLabel as Oe,formatNumber as ke,glyphNode as Ae,isImeSafeEnter as je}from"@webority/ui-elements/helpers";import"@webority/ui-elements/elements/lightbox";import"@webority/ui-elements/elements/markdown";import"@webority/ui-elements/elements/code-block";var Me=`@webority/chat-elements needs a browser DOM; import @webority/chat-core on the server`;if(typeof HTMLElement>`u`)throw Error(Me);var Ne=HTMLElement,P=class extends Ne{#e=null;#t=null;#n=null;#r=!1;get chatPart(){return this.#e}set chatPart(e){this.#e=e,this.#i()}get message(){return this.#t}set message(e){this.#t=e,this.#i()}get turn(){return this.#n}set turn(e){this.#n=e,this.#i()}get activeTurn(){let e=this.#n;if(e===null)throw Error(`${this.localName} has no turn yet`);return e}connectedCallback(){this.#r=!0,this.#i()}disconnectedCallback(){this.#r=!1,queueMicrotask(()=>{this.isConnected||this.disposePart()})}#i(){this.#r&&this.#e&&this.#t&&this.#n&&this.renderPart(this.#e,this.#t,this.#n)}renderPart(e,t,n){throw Error(`${this.localName} must override renderPart`)}disposePart(){}};function F(e,t){typeof customElements>`u`||customElements.get(e)||customElements.define(e,t)}function I(e,t,n=null,r=null){let i=e.createElement(t);return n&&(i.className=n),r!==null&&(i.textContent=r),i}function L(e,t,n){let r=Ae(t,{size:n});return r===null?null:e.adoptNode(r)}var Pe={Confirmed:`actionConfirmed`,Rejected:`actionRejected`,Expired:`actionExpired`,Failed:`actionFailed`},Fe=/^https?:\/\//i,Ie={strong:`strong`,em:`em`,strike:`s`};function R(e,t=null,n=null){let r=document.createElement(e);return t&&(r.className=t),n!=null&&(r.textContent=n),r}function Le(e,t){return{id:e,label:t,action:`Send`,target:null,navigateAfterMs:null,icon:null,variant:null}}function Re(e){return e.type in Ie}function ze(e,t){for(let n of t)if(n.type===`text`||n.type===`citation`)e.append(document.createTextNode(n.text));else if(n.type===`link`){if(Fe.test(n.href)){let t=R(`a`);t.href=n.href,t.target=`_blank`,t.rel=`noopener noreferrer`,ze(t,n.children),e.append(t)}else ze(e,n.children)}else if(Re(n)){let t=R(Ie[n.type]);ze(t,n.children),e.append(t)}else n.type===`code`&&e.append(R(`code`,null,n.text))}function Be(e){let t=R(`p`,`wui-chat-action-consent`);return ze(t,Te(e)),t}function Ve(e){let t=R(`ul`,`wui-chat-action-lines`);for(let n of e)t.append(R(`li`,null,n));return t}function He(e){let t=R(`dl`,`wui-chat-action-lines`);for(let n of e){let e=R(`div`,`wui-chat-action-line`),r=n.indexOf(`: `);r===-1?e.append(R(`dt`,null,n)):e.append(R(`dt`,null,n.slice(0,r)),R(`dd`,null,n.slice(r+2))),t.append(e)}return t}function Ue(e){return typeof e!=`object`||!e||!(`message`in e)?``:typeof e.message==`string`?e.message:``}F(`wui-chat-part-action`,class extends P{_part;_turn;_working;_error;_menuOpen;constructor(){super(),this._part=null,this._turn=null,this._working=null,this._error=null,this._menuOpen=!1}renderPart(e,t,n){this._part?.actionId!==e.actionId&&(this._working=null,this._error=null,this._menuOpen=!1),this._part=e,this._turn=n,this._paint()}_paint(e=null){let t=this._part,n=this._turn;t!==null&&n!==null&&(this.replaceChildren(this._view(t,n)),e===`first`?this.querySelector(`[role="menuitem"]`)?.focus():e===`edit`&&this.querySelector(`.wui-chat-action-edit`)?.focus())}async _run(e){let t=this._part,n=this._turn;if(t===null||n===null)return;let r=t.actionId;this._working=e,this._error=null,this._paint();try{e===`confirm`?await n.confirmAction(r):await n.rejectAction(r),this._working=null}catch(e){if(this._part?.actionId!==r)return;this._working=null,this._error=Ue(e)||n.labels.actionFailed,this._paint()}}_view(e,t){let n=t.labels,r=e.state===`Pending`,i=t.features.LeadRecap===!0&&e.actionKind===`ChatLeadCapture`,a=i&&(e.editFields?.length??0)>0,o=R(`div`,`wui-chat-action wui-chat-action--${e.state.toLowerCase()}`);if(o.append(R(`strong`,`wui-chat-action-title`,e.title)),e.lines.length>0&&o.append(i?He(e.lines):Ve(e.lines)),i&&e.consentText&&o.append(Be(e.consentText)),e.note&&o.append(R(`p`,`wui-chat-action-note`,e.note)),r||o.append(this._status(e,n)),(r||a)&&o.append(this._buttons(e,n,i,r,a)),e.editFields&&a&&this._menuOpen&&o.append(this._menu(e.editFields,n,t)),this._error){let e=R(`p`,`wui-chat-action-error`,this._error);e.setAttribute(`role`,`alert`),o.append(e)}return o}_status(e,t){let n=R(`p`,`wui-chat-action-status wui-chat-action-status--${e.state.toLowerCase()}`);if(e.state===`Repeat`)n.textContent=e.decidedDateTimeUtc?t.actionRepeat(M(e.decidedDateTimeUtc)):t.actionDone;else if(e.state===`Done`){if(n.append(t.actionDone),e.decidedDateTimeUtc){let t=R(`time`,null,M(e.decidedDateTimeUtc));t.dateTime=e.decidedDateTimeUtc,n.append(` `,t)}}else{let r=Pe[e.state];n.textContent=r===void 0?``:t[r]}return n}_buttons(e,t,n,r,i){let a=R(`div`,`wui-chat-action-buttons`),o=this._working;if(r){let r=n&&e.confirmLabel||t.actionConfirm,i=n&&e.rejectLabel||t.actionDismiss,s=R(`button`,`btn btn-primary btn-sm`,o===`confirm`?t.actionWorking:r);s.type=`button`,s.disabled=o!==null,s.addEventListener(`click`,()=>this._run(`confirm`));let c=R(`button`,`btn btn-soft-primary btn-sm`,i);c.type=`button`,c.disabled=o!==null,c.addEventListener(`click`,()=>this._run(`dismiss`)),a.append(s,c)}if(i){let e=R(`button`,`btn btn-soft-primary btn-sm wui-chat-action-edit`,t.editSomething);e.type=`button`,e.setAttribute(`aria-haspopup`,`menu`),e.setAttribute(`aria-expanded`,String(this._menuOpen)),e.disabled=!r||o!==null,e.addEventListener(`click`,()=>{this._menuOpen=!this._menuOpen,this._paint(this._menuOpen?`first`:`edit`)}),a.append(e)}return a}_menu(e,t,n){let r=R(`ul`,`list-group wui-chat-action-menu`);r.setAttribute(`role`,`menu`),r.setAttribute(`aria-label`,t.editSomething),r.addEventListener(`keydown`,e=>this._onMenuKey(e,r));for(let t of e){let e=R(`li`);e.setAttribute(`role`,`none`);let i=R(`button`,`list-group-item list-group-item-action wui-chat-action-menu-item`,t.label);i.type=`button`,i.setAttribute(`role`,`menuitem`),i.addEventListener(`click`,()=>{this._menuOpen=!1,n.chooseQuickReply(Le(`lead.edit:${t.id}`,t.label)),this._paint(`edit`)}),e.append(i),r.append(e)}return r}_onMenuKey(e,t){if(e.key===`Escape`){e.preventDefault(),this._menuOpen=!1,this._paint(`edit`);return}let n=[...t.querySelectorAll(`[role="menuitem"]`)],r=document.activeElement,i=r instanceof HTMLElement?n.indexOf(r):-1,a=n.length-1,o=(/* @__PURE__ */ new Map([[`ArrowDown`,i<a?i+1:0],[`ArrowUp`,i>0?i-1:a],[`Home`,0],[`End`,a]])).get(e.key);o!==void 0&&(e.preventDefault(),n[o]?.focus())}});var We=null;async function Ge(){await import(`@webority/ui-elements/chart`),await customElements.whenDefined(`wui-chart`)}async function Ke(){return We??=Ge().catch(e=>{throw We=null,e}),We}var qe={sub:`wui-chat-sub`,sup:`wui-chat-sup`};function z(e,t){let n=e.ownerDocument??document;for(let r of t)if(r.kind===`sub`||r.kind===`sup`){let t=n.createElement(r.kind);t.className=qe[r.kind],t.textContent=r.text,e.append(t)}else e.append(n.createTextNode(r.text))}function B(e,t){e.replaceChildren(),z(e,be(String(t??``)))}function V(e){return xe(String(e??``))}function Je(e){return le(e)}var Ye=8,Xe=8,Ze={Bar:`column`,Line:`line`,Donut:`donut`};function Qe(e,t){return e===`Bar`&&t>4?300:240}function $e(e,t){let n=e.chartType===`Donut`,r=n?e.series.slice(0,1):e.series.slice(0,Ye),i=r.map((e,n)=>({key:`s${n}`,label:V(e.name)||t.chart})),a=Object.fromEntries(i.map(e=>[e.key,null])),o=/* @__PURE__ */ new Map;r.forEach((e,t)=>{for(let n of e.points){let e=String(n.label),r=o.get(e);r===void 0&&(r={label:V(e),...a},o.set(e,r)),r[`s${t}`]=n.value}});let s=[...o.values()],c={type:Ze[e.chartType],title:V(e.title)||t.chart,x:{key:`label`,kind:`category`},series:i,data:s,height:Qe(e.chartType,s.length)};return e.chartType===`Bar`&&s.length<=Xe&&(c.x.labelFit=`all`,c.valueLabels=!0),!n&&e.unit&&(c.y={label:V(e.unit)}),s.length===0&&(c.state=`empty`,c.emptyText=t.chartEmpty),c}F(`wui-chat-part-chart`,class extends P{#e=null;#t=0;#n=null;#r=null;#i=null;#a=null;renderPart(e,t,n){let r=JSON.stringify(e);if(r===this.#e)return;this.#e=r,this.#t+=1;let i=this.#t,a=this.ownerDocument??document,o=this.#o(a);if(this.#r?.remove(),this.#r=null,e.title){let t=I(a,`figcaption`,`wui-chat-chart-title`);B(t,e.title),o.figure.prepend(t),this.#r=t}let s=this.#i;if(s!==null){let t=$e(e,n.labels);Object.assign(s,{spec:t}),this.#s(o,s,t.state!==`empty`,n.labels)}else Ke().then(()=>{if(i!==this.#t||!this.isConnected)return;let t=$e(e,n.labels),r=a.createElement(`wui-chart`);Object.assign(r,{spec:t}),this.#i=r,o.body.replaceChildren(r),this.#s(o,r,t.state!==`empty`,n.labels)},()=>{i===this.#t&&this.isConnected&&this.#l(o.body,n.labels)})}disposePart(){this.#t+=1,this.#e=null}#o(e){if(this.#n===null){let t=I(e,`figure`,`wui-chat-chart`),n=I(e,`div`,`wui-chat-chart-body`);t.append(n),this.replaceChildren(t),this.#n={figure:t,body:n}}return this.#n}#s(e,t,n,r){if(!n){this.#a?.remove(),this.#a=null;return}if(!this.#a){let n=I(this.ownerDocument??document,`button`,`btn btn-link btn-sm wui-chat-chart-toggle`);n.type=`button`,n.addEventListener(`click`,()=>this.#c(e,t)),e.figure.append(n),this.#a=n}let i=t.getAttribute(`view`)===`table`;this.#a.setAttribute(`aria-pressed`,String(i)),this.#a.textContent=i?r.chartShowChart:r.chartShowTable}#c(e,t){let n=this.activeTurn,r=t.getAttribute(`view`)!==`table`;t.setAttribute(`view`,r?`table`:`chart`),this.#s(e,t,!0,n.labels)}#l(e,t){let n=I(this.ownerDocument??document,`p`,`wui-chat-chart-error`,t.chartLoadFailed);n.setAttribute(`role`,`status`),e.replaceChildren(n),this.#a?.remove(),this.#a=null}});var et={Positive:`wui-metric-tone-success`,Caution:`wui-metric-tone-warning`,Negative:`wui-metric-tone-danger`},tt=/* @__PURE__ */ new Set([`Positive`,`Caution`,`Negative`]),nt=.001;function rt(e,t,n){let r=et[t.status],i=I(e,`div`,r?`wui-metric ${r}`:`wui-metric`);i.dataset.status=t.status;let a=I(e,`div`,`wui-metric-label`);B(a,t.label);let o=I(e,`div`,`wui-metric-value`);if(z(o,t.value!==0&&Math.abs(t.value)<nt?Je(t.value):[{kind:`text`,text:ke(t.value)}]),t.unit){let n=I(e,`span`,`wui-chat-figure-unit`);B(n,t.unit),n.prepend(` `),o.append(n)}return tt.has(t.status)&&o.append(I(e,`span`,`visually-hidden`,n.figureStatus(t.status))),i.append(a,o),i}F(`wui-chat-part-figures`,class extends P{#e=null;renderPart(e,t,n){let r=JSON.stringify(e);if(r===this.#e)return;if(this.#e=r,!e.figures||e.figures.length===0){this.replaceChildren();return}let i=this.ownerDocument??document,a=I(i,`div`,`wui-chat-figures`),o=I(i,`div`,`wui-metric-strip wui-metric-strip-sm wui-chat-figures-strip`);o.setAttribute(`role`,`group`),o.setAttribute(`aria-label`,n.labels.figures);for(let t of e.figures)o.append(rt(i,t,n.labels));a.append(o),this.replaceChildren(a)}}),F(`wui-chat-part-file`,class extends P{renderPart(e,t,n){let r=n.openAttachment,i=typeof r==`function`,a=document.createElement(i?`button`:`span`);a.className=`wui-chat-file-chip`,i&&(a.setAttribute(`type`,`button`),a.setAttribute(`aria-label`,n.labels.fileOpen(e.fileName)),a.addEventListener(`click`,()=>r(e)));let o=L(document,`document-text`,16),s=document.createElement(`span`);s.className=`wui-chat-file-name`,s.textContent=e.fileName;let c=document.createElement(`span`);c.className=`wui-chat-file-size`,c.textContent=ue(e.length),a.append(...[o,s,c].filter(e=>e!==null));let l=document.createElement(`div`);l.className=`wui-chat-file`,l.append(a),this.replaceChildren(l)}});var it={Open:`info`,InProgress:`info`,WaitingOnCustomer:`warning`,Resolved:`success`,Closed:`neutral`,Cancelled:`neutral`},at=/^\/[/\\]/,ot=/^https?:\/\//i,st=/[\t\r\n]/g;function ct(e){return typeof e==`string`&&e.trim()!==``}function lt(e){return e.replace(st,``)}function ut(e){if(typeof e!=`string`)return!1;let t=lt(e);return t.startsWith(`/`)?!at.test(t):ot.test(t)}function dt(e){if(typeof e!=`string`)return`?`;let t=e.split(/\s+/).filter(Boolean).slice(0,2).map(e=>([...e][0]??``).toUpperCase()).join(``);return t===``?`?`:t}function ft(e,t){let n=e?.displayName,r=dt(ct(n)?n:t),i=y(`span`,`wui-chat-avatar`,{"aria-hidden":`true`}),a=e?.avatarUrl,o=typeof a==`string`?lt(a):null;if(ut(o)){let e=y(`img`,null,{alt:``,src:o,loading:`lazy`});e.addEventListener(`error`,()=>{i.textContent=r}),i.append(e)}else i.textContent=r;return i}function pt(e,t){let n=y(`div`,`wui-chat-agent-head`),r=y(`span`,`wui-chat-agent-name`),i=e?.displayName;r.textContent=ct(i)?i:t.agent;let a=y(`span`,`wui-chat-agent-role wui-chat-agent-tag`);return a.textContent=t.agent,n.append(ft(e,t.agent),r,a),n}function mt(e,t){let n=e.displayName,r=y(`li`,`wui-chat-message wui-chat-message--agent wui-chat-message--typing`),i=y(`span`,`wui-chat-typing`);for(let e=0;e<3;e+=1)i.append(y(`span`,`wui-chat-typing-dot`,{"aria-hidden":`true`}));let a=y(`span`,`visually-hidden`);return a.textContent=t.agentTyping(ct(n)?n:t.agent),r.append(pt({kind:`Agent`,displayName:n,avatarUrl:null},t),i,a),r}function ht(e){return typeof e==`string`&&v(it,e)?it[e]??null:null}function gt(e,t){return ht(e)===null?``:t.ticketStatus(e)}var _t=/* @__PURE__ */ new Set([`Requested`,`Waiting`]),vt=/* @__PURE__ */ new Set([`Requested`,`Waiting`,`Joined`]),yt=vt;function bt(e,t){let n=e?.displayName;return typeof n==`string`&&n.trim()!==``?n:t.handoffAgentFallback}function xt(){let e=y(`div`,`wui-chat-handoff-pulses`);for(let t=0;t<3;t+=1)e.append(y(`span`,`wui-chat-handoff-pulse`,{"aria-hidden":`true`}));return e}function H(e,t,n){let r=y(e,t);return r.textContent=n,r}function St(e,t){let n=y(`div`,`wui-chat-handoff-body`);return n.append(H(`strong`,`wui-chat-handoff-title`,e),H(`p`,`wui-chat-handoff-text`,t)),n}function Ct(e,t){if(typeof e.queuePosition!=`number`){let e=y(`span`,`wui-chat-system-line-stack`);return e.append(H(`p`,`wui-chat-handoff-text`,t.handoffWaiting),H(`p`,`wui-chat-handoff-text`,t.handoffQueuedText)),[xt(),e]}let n=y(`span`,`wui-chat-handoff-position`,{"aria-hidden":`true`});return n.textContent=String(e.queuePosition),[n,St(t.handoffQueued(e.queuePosition),t.handoffQueuedText)]}function wt(e,t){let n=bt(e.agent,t),r=y(`span`,`wui-chat-handoff-agent`);return r.append(ft(e.agent,t.handoffAgentFallback),y(`span`,`wui-chat-handoff-online`,{"aria-hidden":`true`})),[r,St(t.handoffJoined(n),t.handoffJoinedText(n))]}function Tt(e,t){switch(e.state){case`Requested`:return[xt(),H(`p`,`wui-chat-handoff-text`,t.handoffRequested)];case`Waiting`:return Ct(e,t);case`Joined`:return wt(e,t);case`Left`:return[St(t.handoffLeft(bt(e.agent,t)),t.handoffLeftText)];case`Ended`:return[St(t.handoffEnded,t.handoffEndedText)];default:return null}}F(`wui-chat-part-handoff`,class extends P{_signature;constructor(){super(),this._signature=null}renderPart(e,t,n){let r=n.isLast,i=n.handoffSettled===!0&&_t.has(e.state),a=JSON.stringify([e.state,e.queuePosition,e.agent,r,n.features.HumanHandoff,n.busy,i]);if(a===this._signature)return;if(this._signature=a,i){this.replaceChildren();return}let o=Tt(e,n.labels);if(o===null){this.replaceChildren();return}let s=y(`div`,`wui-chat-handoff wui-chat-handoff--${e.state.toLowerCase()}`);if(r&&_t.has(e.state)&&s.classList.add(`wui-chat-handoff--live`),r&&vt.has(e.state)&&s.setAttribute(`role`,`status`),yt.has(e.state)){s.classList.add(`wui-chat-system-line`);let e=y(`span`,`wui-chat-system-line-content`);e.append(...o),s.append(e)}else s.append(...o);this.replaceChildren(s)}}),F(`wui-chat-part-image`,class extends P{#e=null;#t=0;#n=null;renderPart(e,t,n){if(e.attachmentId===this.#e)return;this.#e=e.attachmentId;let r=this.ownerDocument??document,i=I(r,`figure`,`wui-chat-image`),a=I(r,`div`,`wui-chat-image-frame`);this.#n=a;let{width:o,height:s}=e;o!==null&&s!==null&&Number.isFinite(o)&&Number.isFinite(s)&&o>0&&s>0&&(a.style.aspectRatio=`${o} / ${s}`),i.append(a),this.replaceChildren(i),this.#r(e,n)}disposePart(){this.#t+=1,this.#e=null}#r(e,t){this.#t+=1;let n=this.#t,r=this.ownerDocument??document,i=this.#n;if(i===null)return;let a=I(r,`div`,`wui-chat-image-skeleton`);a.setAttribute(`aria-hidden`,`true`);let o=I(r,`span`,`visually-hidden`,t.labels.imageLoading);o.setAttribute(`role`,`status`),i.replaceChildren(a,o),typeof t.loadAttachmentUrl==`function`?t.loadAttachmentUrl(e.attachmentId).then(r=>{n===this.#t&&this.isConnected&&this.#i(r,e,t)},()=>{n===this.#t&&this.isConnected&&this.#a(e,t)}):this.#a(e,t)}#i(e,t,n){let r=this.#n;if(r===null)return;let i=this.ownerDocument??document,a=V(t.alt),o=i.createElement(`wui-lightbox`);o.setAttribute(`label`,n.labels.imageViewer),o.setAttribute(`layout`,`single`);let s=I(i,`a`,`wui-lightbox-item`);s.setAttribute(`href`,e),s.dataset.caption=a,s.dataset.name=a;let c=i.createElement(`img`);c.src=e,c.alt=a,c.decoding=`async`,s.append(c),o.append(s),r.replaceChildren(o)}#a(e,t){let n=this.#n;if(n===null)return;let r=this.ownerDocument??document,i=I(r,`p`,`wui-chat-image-error`,t.labels.imageFailed);i.setAttribute(`role`,`status`);let a=I(r,`button`,`btn btn-soft-primary btn-sm`,t.labels.retry);a.type=`button`,a.addEventListener(`click`,()=>this.#r(e,t)),n.replaceChildren(i,a)}});var Et={Email:{type:`email`,autocomplete:`email`},Phone:{type:`tel`,autocomplete:`tel`},Name:{type:`text`,autocomplete:`name`},Company:{type:`text`,autocomplete:`organization`},Text:{type:`text`,autocomplete:null},LongText:{type:`text`,autocomplete:null}},Dt=[`Open`,`Answered`,`Skipped`,`Expired`],Ot=0;function U(e){return Ot+=1,`${e}-${Ot}`}function W(e,t,n){let r=document.createElement(e);return t&&(r.className=t),n!=null&&(r.textContent=n),r}function G(){let e=W(`p`,`wui-chat-field-error`);return e.id=U(`wui-chat-field-error`),e.setAttribute(`role`,`alert`),e.hidden=!0,e}function K(e,t){return e.required?[]:[W(`span`,`wui-chat-field-hint`,t.inputOptional)]}function kt(e,t,n){let r=U(`wui-chat-field`),i=Et[t],a=t===`LongText`&&!e.secret,o;if(a){let e=W(`textarea`,`form-control wui-chat-input-control`);e.rows=3,o=e}else{let t=W(`input`,`form-control wui-chat-input-control`);t.type=e.secret?`password`:i.type,e.secret?t.autocomplete=`off`:i.autocomplete&&(t.autocomplete=i.autocomplete),o=t}o.id=r,o.name=e.key,e.placeholder!=null&&(o.placeholder=e.placeholder),e.maxLength!=null&&(o.maxLength=e.maxLength),e.required&&o.setAttribute(`aria-required`,`true`);let s=W(`label`,`form-label`,e.label);s.htmlFor=r;let c=G();o.setAttribute(`aria-describedby`,c.id);let l=W(`div`,`wui-chat-field`);return l.dataset.key=e.key,l.append(s,...K(e,n),o,c),{field:e,element:l,controls:[o],focus:o,invalid:o,error:c,control:o,read:()=>e.secret?o.value:o.value.trim()}}function At(e,t,n,r,i){let a=e.control,o=W(`button`,`btn btn-soft-primary`,n.inputSendCode);o.type=`button`,o.dataset.wui=`AppButton`;let s=W(`p`,`wui-chat-field-hint`);s.setAttribute(`aria-live`,`polite`);let c=U(`wui-chat-field`),l=W(`label`,`form-label`,n.inputEnterCode);l.htmlFor=c,l.hidden=!0;let u=W(`input`,`form-control wui-chat-input-control`);return u.type=`text`,u.id=c,u.inputMode=`numeric`,u.autocomplete=`one-time-code`,u.hidden=!0,o.addEventListener(`click`,async()=>{o.disabled=!0;try{await r.sendOtp(i,{fieldKey:t.key,value:a.value.trim()}),s.textContent=n.inputCodeSent,l.hidden=!1,u.hidden=!1}catch{s.textContent=n.inputCodeFailed}finally{o.disabled=!1}}),e.element.insertBefore(o,e.error),e.element.insertBefore(s,e.error),e.element.insertBefore(l,e.error),e.element.insertBefore(u,e.error),{...e,controls:[...e.controls,o,u],codeRead:()=>u.value.trim()}}function jt(e,t){let n=U(`wui-chat-field-label`),r=W(`span`,`form-label`,e.label);r.id=n;let i=W(`div`);i.setAttribute(`role`,`radiogroup`),i.setAttribute(`aria-labelledby`,n);let a=G();i.setAttribute(`aria-describedby`,a.id);let o=[];for(let t of e.options??[]){let n=W(`div`,`form-check`),r=W(`input`,`form-check-input`);r.type=`radio`,r.name=e.key,r.value=t.id,r.id=U(`wui-chat-option`);let a=W(`label`,`form-check-label`,t.label);a.htmlFor=r.id,n.append(r,a),i.append(n),o.push(r)}o.length===0&&(i.tabIndex=-1);let s=W(`div`,`wui-chat-field`);return s.dataset.key=e.key,s.append(r,...K(e,t),i,a),{field:e,element:s,controls:o,focus:o[0]??i,invalid:i,error:a,read:()=>o.find(e=>e.checked)?.value??``}}function Mt(e,t){let n=U(`wui-chat-field-label`),r=W(`span`,`form-label`,e.label);r.id=n;let i=W(`div`,`wui-chat-input-choices`);i.setAttribute(`role`,`group`),i.setAttribute(`aria-labelledby`,n);let a=G();i.setAttribute(`aria-describedby`,a.id);let o=[];for(let t of e.options??[]){let n=W(`div`,`form-check`),r=W(`input`,`form-check-input`);r.type=`checkbox`,r.name=e.key,r.value=t.id,r.id=U(`wui-chat-option`);let a=W(`label`,`form-check-label`,t.label);a.htmlFor=r.id,n.append(r,a),i.append(n),o.push(r)}o.length===0&&(i.tabIndex=-1);let s=W(`div`,`wui-chat-field`);return s.dataset.key=e.key,s.append(r,...K(e,t),i,a),{field:e,element:s,controls:o,focus:o[0]??i,invalid:i,error:a,read:()=>JSON.stringify(o.filter(e=>e.checked).map(e=>e.value))}}function Nt(e,t){let n=U(`wui-chat-field-label`),r=W(`span`,`form-label`,e.label);r.id=n;let i=W(`div`,`wui-chat-input-slots`);i.setAttribute(`role`,`radiogroup`),i.setAttribute(`aria-labelledby`,n);let a=G();i.setAttribute(`aria-describedby`,a.id);let o=new Intl.DateTimeFormat(void 0,{weekday:`short`,day:`numeric`,month:`short`,hour:`numeric`,minute:`2-digit`}),s=[];for(let t of e.slots??[]){let n=W(`input`,`wui-chat-input-slot-radio`);n.type=`radio`,n.name=e.key,n.value=t.id,n.id=U(`wui-chat-slot`);let r=W(`label`,`btn btn-soft-primary wui-chat-input-slot`,o.format(new Date(t.startDateTimeUtc)));r.htmlFor=n.id,i.append(n,r),s.push(n)}s.length===0&&(i.tabIndex=-1);let c=W(`div`,`wui-chat-field`);return c.dataset.key=e.key,c.append(r,...K(e,t),i,a),{field:e,element:c,controls:s,focus:s[0]??i,invalid:i,error:a,read:()=>s.find(e=>e.checked)?.value??``}}function Pt(e,t,n){let r=U(`wui-chat-field-label`),i=W(`span`,`form-label`,e.label);i.id=r;let a=G(),o=W(`input`);o.type=`file`,o.name=e.key,o.id=U(`wui-chat-field`),o.hidden=!0,e.accept?.length&&(o.accept=e.accept.join(`,`));let s=W(`button`,`btn btn-soft-primary`,t.inputChooseFile);s.type=`button`,s.dataset.wui=`AppButton`,s.setAttribute(`aria-describedby`,a.id),s.addEventListener(`click`,()=>o.click());let c=W(`span`,`wui-chat-input-file-status`);c.setAttribute(`aria-live`,`polite`);let l=W(`button`,`btn btn-link-primary`);l.type=`button`,l.dataset.wui=`AppButton`,l.hidden=!0;let u=W(`div`,`wui-chat-input-file`);u.setAttribute(`role`,`group`),u.setAttribute(`aria-labelledby`,r),u.append(s,c,l,o);let d=`empty`,f=``,p=``,m=0,h=()=>{c.textContent=d===`uploading`?`${t.attachmentUploading} ${f}`:f,l.hidden=f===``,l.textContent=f===``?``:t.inputRemoveFile(f);let e=d===`failed`;a.textContent=e?t.attachmentFailed:``,a.hidden=!e,e?u.setAttribute(`aria-invalid`,`true`):u.removeAttribute(`aria-invalid`)},g=async e=>{m+=1;let t=m;d=`uploading`,f=e.name,p=``,h();try{let r=await n.uploadInputFile(e);if(t!==m)return;p=r,d=`ready`}catch{if(t!==m)return;d=`failed`}h()};o.addEventListener(`change`,()=>{let e=o.files?.[0];e&&g(e)}),l.addEventListener(`click`,()=>{m+=1,d=`empty`,f=``,p=``,o.value=``,h()}),h();let _=W(`div`,`wui-chat-field`);return _.dataset.key=e.key,_.append(i,...K(e,t),u,a),{field:e,element:_,controls:[s,l,o],focus:s,invalid:u,error:a,read:()=>d===`ready`?p:``,uploadProblem:()=>d===`uploading`?t.attachmentUploading:d===`failed`?t.attachmentFailed:null}}function Ft(e){let t=W(`input`,`form-check-input`);t.type=`checkbox`,t.name=e.key,t.id=U(`wui-chat-field`);let n=W(`label`,`form-check-label`,e.consentText||e.label);n.htmlFor=t.id;let r=G();t.setAttribute(`aria-describedby`,r.id);let i=W(`div`,`form-check`);i.append(t,n);let a=W(`div`,`wui-chat-field`);return a.dataset.key=e.key,a.append(i,r),{field:e,element:a,controls:[t],focus:t,invalid:t,error:r,read:()=>t.checked?`true`:`false`}}function It(e,t,n,r){if(e.type===`Choice`)return jt(e,t);if(e.type===`MultiChoice`)return Mt(e,t);if(e.type===`TimeSlot`)return Nt(e,t);if(e.type===`File`)return Pt(e,t,n);if(e.type===`Consent`)return Ft(e);let i=kt(e,e.type,t);return e.verify===`Otp`?At(i,e,t,n,r):i}function Lt(e,t,n){let r=e.uploadProblem?.();if(r)return r;let{field:i}=e;return i.required?i.type===`Consent`?t===`true`?null:n.inputConsentRequired:i.type===`MultiChoice`?t===`[]`?n.inputRequired:null:t===``?n.inputRequired:null:null}function Rt(e,t){return e.state===`Answered`?W(`p`,`wui-chat-input-summary`,e.answeredSummary||t.inputAnswered):W(`p`,`wui-chat-input-summary`,e.state===`Skipped`?t.inputSkipped:t.inputExpired)}F(`wui-chat-part-input-request`,class extends P{_signature;_generation;constructor(){super(),this._signature=null,this._generation=0}renderPart(e,t,n){for(let t of Dt)this.classList.toggle(`wui-chat-input-request--${t.toLowerCase()}`,e.state===t);let r=JSON.stringify([e.requestId,e.state,e.answeredSummary,e.fields]);r!==this._signature&&(this._signature=r,this._generation+=1,this.replaceChildren(this._content(e,n)))}_content(e,t){return e.state===`Open`?this._form(e,this._generation):Rt(e,t.labels)}_form(e,t){let n=this.activeTurn,r=n.labels,i=n.features,a=W(`form`,`wui-chat-input-form`);a.noValidate=!0,a.setAttribute(`aria-label`,e.title||e.submitLabel),e.title&&a.append(W(`h3`,`wui-chat-input-title`,e.title));let o=e.fields.map(t=>It(t,r,n,e.requestId));for(let e of o)a.append(e.element);let s=W(`p`,`wui-chat-input-error`);s.setAttribute(`role`,`status`),s.hidden=!0,a.append(s);let c=W(`button`,`btn btn-primary`,e.submitLabel);c.type=`submit`,c.dataset.wui=`AppButton`;let l=W(`div`,`d-flex flex-wrap gap-2`);l.append(c);let u=[c];if(i.LeadShortcuts&&e.fields.length===1&&!e.fields[0]?.required){let t=W(`button`,`btn btn-soft-primary`,r.skip);t.type=`button`,t.dataset.wui=`AppButton`,t.addEventListener(`click`,()=>this.activeTurn.skipInput(e.requestId)),l.append(t),u.push(t)}if(i.LeadShortcuts&&e.cancellable){let e=W(`button`,`btn btn-link-primary`,r.cancel);e.type=`button`,e.dataset.wui=`AppButton`,e.addEventListener(`click`,()=>this.activeTurn.cancelLead()),l.append(e),u.push(e)}a.append(l),e.allowTyped&&a.append(W(`p`,`wui-chat-input-typed`,r.typeAnswer));let d=!1,f=t=>{for(let e of o)for(let n of e.controls)n.disabled=t;for(let e of u)e.disabled=t;c.textContent=t?r.inputSubmitting:e.submitLabel},p=()=>{for(let e of o)e.error.hidden=!0,e.error.textContent=``,e.invalid.removeAttribute(`aria-invalid`);s.hidden=!0,s.textContent=``},m=(e,t)=>{e.error.textContent=t,e.error.hidden=!1,e.invalid.setAttribute(`aria-invalid`,`true`)};return a.addEventListener(`submit`,async n=>{if(n.preventDefault(),d)return;p();let i={},a={},l=[];for(let e of o){let t=e.read();i[e.field.key]=t,e.codeRead&&(a[e.field.key]=e.codeRead());let n=Lt(e,t,r);n&&l.push([e,n])}let[u]=l;if(u){for(let[e,t]of l)m(e,t);u[0].focus.focus();return}d=!0,f(!0);let h;try{h=await this.activeTurn.answerInput(e.requestId,i,Object.keys(a).length>0?a:null)}catch{h={ok:!1,errors:{},message:r.errorGeneric}}if(t!==this._generation||h.ok)return;d=!1;let g=null;for(let e of o){let t=h.errors?.[e.field.key];t&&(m(e,t),g??=e)}h.message!=null&&(s.textContent=h.message,s.hidden=!1),f(!1),g?g.focus.focus():o[0]?o[0].focus.focus():c.focus()}),a}});var zt={ActionLimitReached:`warning`,ConversationTooLong:`warning`,AssistantUnavailable:`danger`},Bt={info:`info`,warning:`alert-triangle`,danger:`alert-circle`};function Vt(e,t){let n=I(e,`a`,`wui-chat-notice-row`);if(n.href=t.href,/^https?:/i.test(t.href)&&(n.target=`_blank`,n.rel=`noopener noreferrer`),t.icon){let r=I(e,`span`,`wui-chat-notice-row-icon`);r.setAttribute(`aria-hidden`,`true`);let i=L(e,t.icon,18);i&&r.append(i),n.append(r)}let r=I(e,`span`,`wui-chat-notice-row-text`);r.append(I(e,`strong`,`wui-chat-notice-row-title`,t.title)),t.detail&&r.append(I(e,`span`,`wui-chat-notice-row-detail`,t.detail));let i=I(e,`span`,`wui-chat-notice-row-arrow`);i.setAttribute(`aria-hidden`,`true`);let a=L(e,`arrow-right`,16);return a&&i.append(a),n.append(r,i),n}F(`wui-chat-part-notice`,class extends P{renderPart(e){let t=this.ownerDocument??document,n=zt[e.code]??`info`,r=I(t,`div`,`wui-chat-notice wui-chat-notice--${n}`);r.setAttribute(`role`,n===`danger`?`alert`:`status`);let i=I(t,`span`,`wui-chat-notice-icon`);i.setAttribute(`aria-hidden`,`true`);let a=L(t,Bt[n],16);a&&i.append(a);let o=I(t,`div`,`wui-chat-notice-body`);o.append(I(t,`span`,`wui-chat-notice-text`,e.text));let s=e.action;if(s){let e=I(t,`button`,`wui-chat-notice-action`,s.label);e.type=`button`,e.addEventListener(`click`,()=>s.run()),o.append(e)}let c=(e.actions??[]).filter(e=>fe(e.href));if(c.length>0){let e=I(t,`div`,`wui-chat-notice-rows`);for(let n of c)e.append(Vt(t,n));o.append(e)}r.append(i,o),this.replaceChildren(r)}});function Ht(e){switch(e){case`Primary`:return`wui-chat-quick-reply--primary`;case`Cta`:return`wui-chat-quick-reply--cta`;case`Default`:case null:return``}}F(`wui-chat-part-quick-replies`,class extends P{#e=null;renderPart(e,t,n){let r=n.features.SuggestedReplies===!0&&n.isLast===!0&&n.busy===!1&&e.replies.length>0,i=typeof n.openTarget==`function`,a=typeof n.beginHandoff==`function`,o=n.handoffPause===!0,s=JSON.stringify([r,e.replies,e.placement,n.labels.quickReplies,n.labels.handoffMoment,i,a,o,n.handoffHosts??null,n.features.LinkHandoff===!0]);if(s===this.#e)return;this.#e=s;let c=this.querySelector(`:scope > .wui-chat-quick-replies:not(.wui-chat-quick-replies--leaving)`);if(!r&&c){this.#t(c);return}if(this.replaceChildren(),!r)return;let l=this.ownerDocument,u=e.placement===`Composer`,d=I(l,`div`,u?`wui-chat-quick-replies wui-chat-quick-replies--composer`:`wui-chat-quick-replies`);d.setAttribute(`role`,`group`),d.setAttribute(`aria-label`,n.labels.quickReplies);let f=u?null:e.replies.find(e=>e.id===A&&e.action===`Send`),p=0;f&&(d.classList.add(`wui-chat-quick-replies--offer`),d.append(this.#n(l,f,n)),p+=1);for(let t of e.replies){if(t===f||t.action===`Open`&&(!t.target||!i))continue;let e=null;if(t.action===`Navigate`){if(n.features.LinkHandoff!==!0)continue;if(de(t.target,n.handoffHosts))e=t.target;else{let r=t.target===null?null:n.resolveLink?.(t.target);e=typeof r==`string`&&r!==``?r:null}if(e===null){d.append(I(l,`span`,null,t.label));continue}if(!a)continue}d.append(this.#r(l,t,p,n,f?`wui-chat-quick-reply--quiet`:``,e)),p+=1}if(o){let e=I(l,`span`,`visually-hidden`,n.labels.handoffMoment);e.setAttribute(`role`,`status`),d.append(e)}d.childElementCount>0&&this.append(d)}#t(e){e.classList.add(`wui-chat-quick-replies--leaving`);let t=this.ownerDocument.defaultView,n=Number.parseFloat(t?t.getComputedStyle(e).animationDuration:``)*1e3;t===null||!(n>0)?e.remove():t.setTimeout(()=>e.remove(),n)}#n(e,t,n){let r=I(e,`div`,`wui-chat-offer`);return r.style.setProperty(`--wui-chat-i`,`0`),r.append(I(e,`div`,`wui-chat-offer-title`,t.label)),r.append(this.#r(e,{...t,variant:`Primary`},0,n,`wui-chat-offer-action`)),r}#r(e,t,n,r,i=``,a=null){let o=e.createElement(`button`);o.type=`button`,o.className=[`wui-chat-quick-reply`,Ht(t.variant),i].filter(Boolean).join(` `),o.style.setProperty(`--wui-chat-i`,String(n));let s=t.action===`Navigate`,c=s&&r.handoffPause===!0;if(o.disabled=c,t.icon){let n=L(e,t.icon,16);if(n){let t=I(e,`span`,`wui-chat-quick-reply-icon`);t.setAttribute(`aria-hidden`,`true`),t.append(n),o.append(t)}}return o.append(I(e,`span`,`wui-chat-quick-reply-label`,c?r.labels.handoffMoment:t.label)),o.addEventListener(`click`,()=>{if(t.action===`Open`){let{openTarget:e}=this.activeTurn;if(t.target===null||e===void 0)throw Error(`${this.localName} drew an Open chip without a target or openTarget`);e.call(this.activeTurn,t.target)}else if(s){let{beginHandoff:e}=this.activeTurn;if(a===null||e===void 0)throw Error(`${this.localName} drew a Navigate chip without a destination or beginHandoff`);e.call(this.activeTurn,t,()=>this.#i(a))}else this.activeTurn.chooseQuickReply(t),this.closest(`.wui-chat`)?.querySelector(`.wui-chat-input`)?.focus()}),o}#i(e){typeof this.activeTurn.openTarget==`function`?this.activeTurn.openTarget(e):globalThis.location.assign(e)}});var Ut=/* @__PURE__ */ new Set([`Integer`,`Decimal`,`MoneyMinor`,`Percent`]);function Wt(e){return Ut.has(e)}function Gt(e,t,n,r=!0){let i=e=>r?be(e):[{kind:`text`,text:e}];if(t==null||t===``)return[{kind:`text`,text:Oe()}];if(e===`Date`||e===`DateTimeUtc`)return[{kind:`text`,text:se(t,e,n)}];if(Wt(e)){let r=Number(t);return i(Number.isFinite(r)?se(r,e,n):String(t))}return i(String(t))}var Kt=0;function qt(e){return Kt+=1,`${e}-${Kt}`}F(`wui-chat-part-record-card`,class extends P{#e=null;renderPart(e,t,n){let r=!!e.target&&typeof n.openRecord==`function`,i=n.features?.FigureText===!0,a=JSON.stringify([e,r,i]);if(a===this.#e)return;this.#e=a;let o=this.ownerDocument,s=I(o,`article`,`wui-chat-record`),c=qt(`wui-chat-record-title`);s.setAttribute(`aria-labelledby`,c);let l=I(o,`div`,`wui-chat-record-head`),u=I(o,`strong`,`wui-chat-record-title`);if(u.id=c,u.setAttribute(`role`,`heading`),u.setAttribute(`aria-level`,`3`),i?B(u,e.title):u.textContent=String(e.title??``),l.append(u),e.subtitle){let t=I(o,`span`,`wui-chat-record-subtitle`);i?B(t,e.subtitle):t.textContent=String(e.subtitle??``),l.append(t)}if(s.append(l),e.fields?.length>0){let t=I(o,`dl`,`wui-chat-record-fields`);for(let n of e.fields){let e=I(o,`div`),r=I(o,`dt`);i?B(r,n.label):r.textContent=String(n.label??``);let a=I(o,`dd`);Wt(n.type)&&(a.className=`wui-chat-num`),z(a,Gt(n.type,n.value,null,i)),e.append(r,a),t.append(e)}s.append(t)}if(r){let t=I(o,`button`,`btn btn-soft-primary btn-sm wui-chat-record-open`,n.labels.recordOpen);t.type=`button`,t.setAttribute(`aria-label`,n.labels.recordOpenFor(V(e.title))),t.addEventListener(`click`,()=>{let{openRecord:t}=this.activeTurn;if(t===void 0)throw Error(`${this.localName} lost openRecord after it drew the button`);t.call(this.activeTurn,e)}),s.append(t)}this.replaceChildren(s)}});var Jt=/^https?:\/\//i;F(`wui-chat-part-sources`,class extends P{renderPart(e,t,n){if(this.replaceChildren(),!n.features.Sources||e.sources.length===0)return;let r=this.ownerDocument,i=I(r,`div`,`wui-chat-sources`);i.append(I(r,`p`,`wui-chat-sources-label`,n.labels.sources));let a=I(r,`ul`,`wui-chat-sources-list`);a.setAttribute(`aria-label`,n.labels.sources);for(let t of e.sources){let e=r.createElement(`li`);e.append(this.#e(r,t,n)),a.append(e)}i.append(a),this.append(i)}#e(e,t,n){let r;if(typeof t.url==`string`&&Jt.test(t.url)){let i=I(e,`a`,`wui-chat-source`);i.setAttribute(`href`,t.url),i.setAttribute(`target`,`_blank`),i.setAttribute(`rel`,`noopener noreferrer`),i.setAttribute(`aria-label`,n.labels.openSource(t.title)),r=i}else r=I(e,`span`,`wui-chat-source`),r.tabIndex=-1;return r.dataset.marker=String(t.marker),r.append(I(e,`span`,`wui-chat-source-marker`,String(t.marker)),I(e,`span`,`wui-chat-source-title`,t.title)),r}});var Yt=25,Xt=0;function Zt(e,t,n){let r=e.createElement(`tr`);for(let i of t.columns){let t=e.createElement(`th`);t.setAttribute(`scope`,`col`),Wt(i.type)&&(t.className=`wui-chat-num`),n?B(t,i.label):t.textContent=String(i.label??``),r.append(t)}return r}function Qt(e,t,n,r){let i=e.createElement(`tr`);return t.columns.forEach((a,o)=>{let s=o===0&&a.type===`Text`,c=e.createElement(s?`th`:`td`);s&&c.setAttribute(`scope`,`row`),Wt(a.type)&&(c.className=`wui-chat-num`);let l=n[o];l==null||l===``?c.append(I(c.ownerDocument,`span`,`wui-chat-null`,Oe())):z(c,Gt(a.type,l,t.currency,r)),i.append(c)}),i}function $t(e,t){let n=()=>{let n=t.scrollWidth-t.clientWidth;e.dataset.scroll=n<=1?`none`:t.scrollLeft>=n-1?`end`:t.scrollLeft>0?`middle`:`start`};t.addEventListener(`scroll`,n,{passive:!0}),typeof ResizeObserver<`u`&&new ResizeObserver(n).observe(t),n()}function en(e,t,n,r,i){let a=e.ownerDocument;for(let o of t.rows.slice(n,r))e.append(Qt(a,t,o,i))}F(`wui-chat-part-table`,class extends P{#e=null;renderPart(e,t,n){let r=n.features?.FigureText===!0,i=JSON.stringify([e,r]);if(i===this.#e)return;if(this.#e=i,!e.columns||e.columns.length===0){this.replaceChildren();return}let a=this.ownerDocument,o=I(a,`figure`,`wui-chat-table`),s=null;if(e.title){Xt+=1,s=`wui-chat-table-${Xt}`;let t=I(a,`figcaption`,`wui-chat-table-title`);t.id=s,r?B(t,e.title):t.textContent=String(e.title??``),o.append(t)}let c=I(a,`div`,`table-wrap wui-chat-table-wrap`);c.tabIndex=0,c.setAttribute(`role`,`region`),s?c.setAttribute(`aria-labelledby`,s):c.setAttribute(`aria-label`,n.labels.table);let l=I(a,`table`,`table table-sm wui-chat-table-grid`),u=a.createElement(`thead`);u.append(Zt(a,e,r));let d=a.createElement(`tbody`);en(d,e,0,Math.min(e.rows.length,Yt),r),l.append(u,d),c.append(l);let f=I(a,`div`,`wui-chat-table-frame`),p=I(a,`span`,`wui-chat-table-cue`);if(p.setAttribute(`aria-hidden`,`true`),f.append(c,p),o.append(f),$t(f,c),e.rows.length>Yt){let t=I(a,`button`,`btn btn-soft-primary btn-sm wui-chat-table-more`,n.labels.tableShowAll(e.rows.length));t.type=`button`,t.addEventListener(`click`,()=>{en(d,e,Yt,e.rows.length,r),t.remove()}),o.append(t)}this.replaceChildren(o)}});var tn=/* @__PURE__ */ new Set([`Visitor`,`Customer`]),nn=/^\d+$/;function rn(e,t){return e?.features?.Sources===!0?typeof e?.isCitation==`function`?e.isCitation(t):nn.test(t):!1}function an(e,t){if(de(e,t?.handoffHosts))return e;let n=t?.resolveLink?.(e);return typeof n==`string`&&n!==``?n:null}function on(e,t){let n=globalThis.location?.origin;for(let r of e.querySelectorAll(`a[href]`)){let e=r.dataset.linkSource??r.getAttribute(`href`)??``;r.dataset.linkSource=e;let i=an(e,t);i===null?r.replaceWith(r.ownerDocument.createTextNode(r.textContent??``)):(i!==r.getAttribute(`href`)&&r.setAttribute(`href`,i),we(i,`web`,void 0,n)?.kind===`web`?(r.setAttribute(`target`,`_blank`),r.setAttribute(`rel`,`noopener noreferrer`)):(r.removeAttribute(`target`),r.removeAttribute(`rel`)))}}function sn(e,t){on(e,t)}F(`wui-chat-part-text`,class extends P{#e=null;#t=null;#n=!1;#r=null;constructor(){super(),this.addEventListener(`wui-markdown-citation`,e=>{let t=this.turn;typeof t?.openCitation==`function`&&t.openCitation(Number(e.detail.citation))}),this.addEventListener(`click`,e=>this.#a(e))}renderPart(e,t,n){let r=tn.has(t.author.kind)?`plain`:`markdown`,i=this.#e;if((i===null||i.mode!==r)&&(i=r===`plain`?{mode:r,node:this.#s()}:this.#c(e.text),this.#e=i,this.#t=null,this.replaceChildren(i.node)),i.mode===`plain`){let t=this.turn?.features?.FigureText===!0,n=JSON.stringify([e.text,t]);n!==this.#t&&(this.#t=n,i.node.replaceChildren(),t?z(i.node,be(e.text)):i.node.append(this.ownerDocument.createTextNode(e.text)))}else this.#o(i.node),i.source.textContent!==e.text&&(i.source.textContent=e.text);this.toggleAttribute(`data-streaming`,t.streaming===!0),this.#n||(this.#n=!0,this.closest(`[data-restored]`)||this.classList.add(`wui-chat-part-enter`)),this.#i()}disposePart(){this.#r?.disconnect(),this.#r=null}#i(){this.#r||(this.#r=new MutationObserver(()=>sn(this,this.turn)),this.#r.observe(this,{childList:!0,subtree:!0,characterData:!0}),sn(this,this.turn))}#a(e){let t=e.target instanceof Element?e.target.closest(`a[href]`):null,n=this.turn;if(!t||!this.contains(t))return;let r=t.getAttribute(`href`)??``;r.startsWith(`#`)||(r.startsWith(`/`)&&typeof n?.onNavigate==`function`?(e.preventDefault(),n.onNavigate(r)):typeof n?.openTarget==`function`&&(e.preventDefault(),n.openTarget(r)))}#o(e){let t=this.turn?.features?.FigureText===!0?be:void 0;e.figureText!==t&&(e.figureText=t)}#s(){return I(this.ownerDocument,`div`,`wui-chat-bubble`)}#c(e){let t=this.ownerDocument,n=I(t,`wui-markdown`,`wui-markdown wui-chat-text`);n.setAttribute(`links`,`web`),n.setAttribute(`headings`,`text`),n.isCitation=e=>rn(this.turn,e);let r=I(t,`pre`,`wui-markdown-source`,e);return n.append(r),{mode:`markdown`,node:n,source:r}}}),F(`wui-chat-part-ticket`,class extends P{renderPart(e,t,n){let{labels:r}=n,i=y(`article`,`wui-chat-ticket`,{"aria-label":r.ticketAria(e.number)}),a=y(`div`,`wui-chat-ticket-head`),o=y(`span`,`wui-chat-ticket-number`);o.textContent=r.ticketAria(e.number),a.append(o);let s=ht(e.status);if(s!==null){let t=y(`span`,`wui-chat-ticket-badge wui-chat-ticket-badge--${s}`);t.textContent=gt(e.status,r),a.append(t)}let c=y(`strong`,`wui-chat-ticket-title`);if(c.textContent=e.subject,i.append(a,c),typeof n.openTicket==`function`){let t=y(`div`,`wui-chat-ticket-foot`),a=y(`button`,`wui-chat-ticket-link`,{type:`button`});a.textContent=r.ticketView,a.addEventListener(`click`,()=>{let{openTicket:t}=n;if(t===void 0)throw Error(`${this.localName} lost openTicket after it drew the link`);t.call(n,{ticketId:e.ticketId,number:e.number})}),t.append(a),i.append(t)}this.replaceChildren(i)}});var cn=`http://www.w3.org/2000/svg`,ln={mic:`M12 15a3 3 0 0 0 3-3V6a3 3 0 0 0-6 0v6a3 3 0 0 0 3 3zm5-3a5 5 0 0 1-10 0H5a7 7 0 0 0 6 6.92V21h2v-2.08A7 7 0 0 0 19 12z`,stop:`M6 6h12v12H6z`,play:`M8 5v14l11-7z`,pause:`M6 5h4v14H6zm8 0h4v14h-4z`,speaker:`M3 9v6h4l5 5V4L7 9H3zm13.5 3a4.5 4.5 0 0 0-2.5-4v8a4.5 4.5 0 0 0 2.5-4zM14 3.2v2.1a7 7 0 0 1 0 13.4v2.1a9 9 0 0 0 0-17.6z`};function un(e,t=18){if(!v(ln,e))throw Error(`Unknown voice icon "${e}".`);let n=document.createElementNS(cn,`svg`);n.setAttribute(`viewBox`,`0 0 24 24`),n.setAttribute(`width`,String(t)),n.setAttribute(`height`,String(t)),n.setAttribute(`aria-hidden`,`true`),n.setAttribute(`focusable`,`false`),n.setAttribute(`fill`,`currentColor`);let r=document.createElementNS(cn,`path`);return r.setAttribute(`d`,ln[e]),n.append(r),n}var dn=40,q=null;function fn(e){let t=I(document,`span`,`wui-chat-clip-bar`);return t.style.setProperty(`--wui-chat-bar-height`,`${Math.round(e*100)}%`),t}function pn(e,t){e.replaceChildren(...Ce(t,dn).map(fn))}F(`wui-chat-part-voice-clip`,class extends P{#e=null;#t=!1;#n=0;#r=0;#i=!1;#a=null;#o=null;#s=null;#c=0;#l=!1;renderPart(e,t,n){if(!n.features.VoiceClips){this.#u(e.transcript);return}let r=this.#e??this.#d(e.attachmentId);e.attachmentId!==r.attachmentId&&(this.disposePart(),r.attachmentId=e.attachmentId,this.#r=0,pn(r.wave,e.attachmentId)),this.#n=e.durationMs,this.#f(r,e)}disposePart(){this.#c+=1,this.#a?.pause(),this.#s!==null&&URL.revokeObjectURL(this.#s),q===this&&(q=null),this.#a=null,this.#o=null,this.#s=null,this.#i=!1}#u(e){if(this.disposePart(),this.#e=null,typeof e==`string`&&e!==``){let t=I(document,`p`,`wui-chat-clip-transcript`);t.textContent=e,this.replaceChildren(t)}else this.replaceChildren()}#d(e){let t=I(document,`div`,`wui-chat-clip`);t.setAttribute(`role`,`group`);let n=I(document,`div`,`wui-chat-clip-row`),r=I(document,`button`,`wui-chat-clip-play`);r.type=`button`;let i=I(document,`div`,`wui-chat-clip-wave`);i.setAttribute(`aria-hidden`,`true`);let a=I(document,`span`,`wui-chat-clip-time`);n.append(r,i,a);let o=I(document,`p`,`wui-chat-clip-error`);o.setAttribute(`role`,`status`),o.hidden=!0,t.append(n,o);let s={attachmentId:e,root:t,play:r,wave:i,time:a,error:o,transcript:null};return r.addEventListener(`click`,()=>this.#C(s)),pn(i,e),this.#e=s,this.replaceChildren(t),s}#f(e,t){let n=this.activeTurn.labels;e.root.setAttribute(`aria-label`,n.voiceClip),e.play.disabled=this.#l||typeof this.activeTurn.readAttachment!=`function`,this.#p(e),this.#m(e),this.#h(e,t.transcript)}#p(e){let t=this.activeTurn.labels,n=this.#i?t.voiceClipPause:t.voiceClipPlay;e.play.setAttribute(`aria-label`,n),e.play.title=n,e.play.replaceChildren(un(this.#i?`pause`:`play`,18))}#m(e){let t=this.#n/1e3,n=t>0?Math.min(1,this.#r/t):0,r=Math.floor(n*dn);[...e.wave.children].forEach((e,t)=>{e.classList.toggle(`wui-chat-clip-bar--played`,t<r)});let i=ce(Math.max(1,Math.round(t)));e.time.textContent=this.activeTurn.labels.voiceClipTime(ce(this.#r),i)}#h(e,t){if(typeof t!=`string`||t===``){e.transcript?.toggle.remove(),e.transcript?.text.remove(),e.transcript=null;return}let n=e.transcript??this.#g(e);n.text.textContent=t,this.#_(n)}#g(e){let t=I(document,`button`,`wui-chat-clip-toggle`);t.type=`button`;let n=I(document,`p`,`wui-chat-clip-transcript`);n.hidden=!this.#t;let r={toggle:t,text:n};return t.addEventListener(`click`,()=>{this.#t=!this.#t,n.hidden=!this.#t,this.#_(r)}),e.transcript=r,e.root.append(t,n),r}#_(e){let t=this.activeTurn.labels;e.toggle.setAttribute(`aria-expanded`,String(this.#t)),e.toggle.textContent=this.#t?t.voiceClipHideTranscript:t.voiceClipShowTranscript}#v(e){return this.#o??=this.#y(e).catch(e=>{throw this.#o=null,e}),this.#o}async#y(e){let t=this.#c,{readAttachment:n}=this.activeTurn;if(n===void 0)throw Error(`${this.localName} loaded a clip on a turn without readAttachment`);let r=await n.call(this.activeTurn,e.attachmentId),i=URL.createObjectURL(new Blob([r],{type:ye(r)}));if(t!==this.#c)return URL.revokeObjectURL(i),null;this.#s!==null&&URL.revokeObjectURL(this.#s),this.#s=i;let a=new Audio(this.#s);return a.addEventListener(`timeupdate`,()=>{this.#r=a.currentTime,this.#m(e)}),a.addEventListener(`ended`,()=>{this.#r=0,this.#b(),this.#m(e)}),a.addEventListener(`error`,()=>{this.#b(),this.#o=null,this.#S(e)}),this.#a=a,a}#b(){this.#a?.pause(),this.#x(!1)}#x(e){this.#i=e,e?(q&&q!==this&&q.#b(),q=this):q===this&&(q=null);let t=this.#e;t!==null&&this.#p(t)}#S(e){e.error.textContent=this.activeTurn.labels.voiceClipFailed,e.error.hidden=!1}async#C(e){if(this.#i)this.#b();else{e.error.hidden=!0,this.#l=!0,e.play.disabled=!0,e.play.setAttribute(`aria-busy`,`true`);try{let t=await this.#v(e);if(t===null)return;this.#x(!0),await t.play()}catch{this.#b(),this.#o=null,this.#S(e)}finally{this.#l=!1,e.play.removeAttribute(`aria-busy`),e.play.disabled=typeof this.activeTurn.readAttachment!=`function`}}}});var mn={Text:`wui-chat-part-text`,Sources:`wui-chat-part-sources`,QuickReplies:`wui-chat-part-quick-replies`,InputRequest:`wui-chat-part-input-request`,Action:`wui-chat-part-action`,Notice:`wui-chat-part-notice`,Table:`wui-chat-part-table`,Chart:`wui-chat-part-chart`,Figures:`wui-chat-part-figures`,RecordCard:`wui-chat-part-record-card`,Image:`wui-chat-part-image`,File:`wui-chat-part-file`,Ticket:`wui-chat-part-ticket`,Handoff:`wui-chat-part-handoff`,VoiceClip:`wui-chat-part-voice-clip`},hn=8e3,gn=6e3,_n=/* @__PURE__ */ new Set([`Blocked`,`NoMicrophone`]);function vn(e){let t=e instanceof O?e.code:`Failed`;return{code:t,source:`Dictation`,sticky:_n.has(t)}}function yn(e){let t=N(e.filter(e=>e.kind===`Text`)).replace(/ ?\[\d+\]/g,``).replace(/\s+/g,` `).trim();if(t.length<=6e3)return t;let n=t.slice(0,gn),r=n.lastIndexOf(`. `);return r===-1?n.trim():n.slice(0,r+1)}function bn(e,t){switch(e.code){case`Blocked`:return t.dictationBlocked;case`NoMicrophone`:return t.dictationNoMicrophone;case`NoSpeech`:return t.dictationNotHeard;case`Unavailable`:return t.dictationUnavailable;case`Failed`:return t.dictationFailed;case`SpeakFailed`:return t.readAloudFailed;default:throw Error(`Unknown voice note code "${e.code}".`)}}function xn(e){let t=e.getState,n=e.speech??l({getToken:e.getToken}),r=`Idle`,i=null,a=null,o=null,s=null,c=0,u=null,d=/* @__PURE__ */ new Set,f=()=>({mode:r,messageId:i,startedAtMs:a,note:o});function p(){let e=f();for(let t of[...d])t(e)}function m(e){r=e.mode,i=e.messageId??null,a=e.startedAtMs??null,p()}function h(){u!==null&&clearTimeout(u),u=null}function g(e){h(),o=e,e&&!e.sticky&&(u=setTimeout(()=>{u=null,o=null,p()},hn)),p()}function _(){o!==null&&(h(),o=null,p())}function v(){c+=1;let e={id:c,controller:new AbortController,stopped:!1};return s=e,e}function y(e){s===e&&(s=null,m({mode:`Idle`}))}function b(){let e=s;s=null,e&&(e.stopped=!0,e.controller.abort()),r!==`Idle`&&m({mode:`Idle`})}function x(){let e=t();return!!(e.features.Dictation&&e.profile?.speechAvailable&&n.dictation)}function S(){let e=t();return!!(e.features.ReadAloud&&e.profile?.speechAvailable&&n.readAloud)}async function C(e){if(r===`Dictating`){b();return}if(b(),g(null),!x())return;let t=e.getText(),i=t!==``&&!/\s$/.test(t)?`${t} `:t,a=v();m({mode:`Dictating`});try{await n.startDictation({signal:a.controller.signal,onText:t=>{s===a&&e.setText(i+t)},onEnd:()=>y(a)})}catch(e){if(a.stopped)return;y(a),g(vn(e))}}async function w(e,t){if(r===`Speaking`&&i===e){b();return}b(),g(null);let a=yn(t);if(a===``)return;let o=v();m({mode:`Speaking`,messageId:e});try{await n.speak(a,{signal:o.controller.signal}),y(o)}catch{if(o.stopped)return;y(o),g({code:`SpeakFailed`,source:`ReadAloud`,sticky:!1,messageId:e})}}function T(e){return d.add(e),()=>{d.delete(e)}}function E(){b(),h(),o=null,d.clear()}return{canDictate:x,canSpeak:S,getStatus:f,subscribe:T,toggleDictation:C,toggleSpeak:w,stop:b,dismissNote:_,destroy:E}}var Sn=/* @__PURE__ */ new Set([`Shift`,`Control`,`Alt`,`Meta`,`Escape`]);function Cn(e,t){e.isTrusted&&!Sn.has(e.key)&&t.getStatus().mode===`Dictating`&&t.stop()}function wn({voice:e,getLabels:t,textarea:n,onTextChanged:r}){let i=null,a=y(`button`,`wui-chat-tool wui-chat-mic`,{type:`button`});a.append(un(`mic`,20)),a.hidden=!0,a.addEventListener(`click`,()=>{e.toggleDictation({getText:()=>n.value,setText:e=>{n.value=n.maxLength>0?e.slice(0,n.maxLength):e,r(),n.setSelectionRange(n.value.length,n.value.length)}})});let o=y(`p`,`wui-chat-voice-note`,{role:`status`});o.hidden=!0;let s=y(`span`,`visually-hidden`,{"aria-live":`polite`});function c(e){let n=t(),r=e.note?.source===`ReadAloud`?null:e.note,i=e.mode===`Dictating`,c=i?n.dictateStop:n.dictate;a.setAttribute(`aria-pressed`,String(i)),a.setAttribute(`aria-label`,c),a.title=c;let l=r?.code===`Blocked`||r?.code===`NoMicrophone`;r===null?(o.hidden=!0,o.textContent=``):(o.hidden=!1,o.textContent=bn(r,n),o.setAttribute(`role`,r.sticky?`alert`:`status`)),o.classList.toggle(`wui-chat-voice-note--blocked`,l),s.textContent=i?n.dictateListening:``}function l(t){let{state:n}=t;a.hidden=!e.canDictate();let r=e.getStatus().mode===`Speaking`,i=n.messagesLeftToday===0;a.disabled=i||r||n.handoffPause===!0}function u(e){c(e),i!==null&&l(i)}let d=e.subscribe(u);function f(t){i=t,l(t),c(e.getStatus())}function p(){d()}return{buttons:[a],note:o,announcer:s,paint:f,destroy:p}}var Tn=10,En=.9,Dn=0;function On(e){for(let t of e.toReversed())for(let e of t.parts.toReversed())if(e.kind===`InputRequest`&&e.state===`Open`)return e.fields[0]?.label??e.title??null;return null}function kn(e){Dn+=1;let t=`wui-chat-composer-hint-${Dn}`,n=y(`p`,`wui-chat-allowance`,{role:`status`});n.hidden=!0;let r=y(`span`),i=y(`button`,`btn btn-ghost-primary btn-sm wui-chat-action-btn`,{type:`button`});i.addEventListener(`click`,()=>e.onCancelEdit());let a=y(`div`,`wui-chat-editing`);a.hidden=!0,a.append(r,i);let s=y(`div`,`wui-chat-attachments`);s.hidden=!0;let c=y(`button`,`wui-chat-tool`,{type:`button`});c.append(o(`paperclip`,20)),c.hidden=!0;let l=y(`input`,null,{type:`file`,multiple:``,tabindex:`-1`});l.hidden=!0,l.addEventListener(`change`,()=>{let t=[...l.files??[]];l.value=``,t.length>0&&e.onAttach(t)}),c.addEventListener(`click`,()=>l.click());let u=y(`textarea`,`wui-chat-input`,{rows:`1`,"aria-describedby":t}),d=y(`span`,`visually-hidden`,{id:t}),f=y(`span`,`wui-chat-counter`);f.hidden=!0;let p=y(`button`,`wui-chat-send`,{type:`submit`});p.append(o(`arrow-up`,18));let m=y(`button`,`wui-chat-send wui-chat-send--stop`,{type:`button`});m.append(o(`stop`,16)),m.hidden=!0,m.addEventListener(`click`,()=>e.onStop());let h=y(`form`,`wui-chat-composer`);h.append(c,l,u,f,d,m,p);let g=e.mark?.(`input`,`rest`)??null,_=null,v=null,b=null,x=0,S=null;function C(){u.style.height=`auto`,u.style.height=`${u.scrollHeight}px`;let e=getComputedStyle(u),t=u.scrollHeight-parseFloat(e.paddingTop)-parseFloat(e.paddingBottom);h.classList.toggle(`wui-chat-composer--multiline`,t>(parseFloat(e.lineHeight)||22)*1.5)}function w(){return S?.attachments.some(e=>e.status===`Uploading`)??!1}function T(){return S?.attachments.some(e=>e.status===`Ready`)??!1}function E(){let e=u.value.length,t=x>0&&e>x*En;f.hidden=!t,t&&b&&(f.textContent=b.counter(e,x))}function D(){let e=S?.messagesLeftToday??null,t=u.value.trim()===``&&!T();p.disabled=!!S?.streaming||e===0||w()||t||S?.handoffPause===!0,h.classList.toggle(`wui-chat-composer--has-text`,!t)}function O(){if(p.disabled)return;let t=u.value.trim();u.value=``,C(),E(),D(),e.voice?.stop(),e.voice?.dismissNote(),e.onSubmit(t)}u.addEventListener(`input`,()=>{C(),E(),D(),u.value!==``&&e.onTyping?.()}),u.addEventListener(`keydown`,e=>{e.key===`Enter`&&!e.shiftKey&&!e.isComposing&&(e.preventDefault(),O())}),h.addEventListener(`submit`,e=>{e.preventDefault(),O()});let k=e.voice,A=k?wn({voice:k,getLabels:()=>{if(b===null)throw Error(`composer labels are read before the first render`);return b},textarea:u,onTextChanged:()=>{C(),E(),D()}}):null;if(k&&A){let e=A.buttons[0];e&&h.insertBefore(e,p),u.addEventListener(`keydown`,e=>Cn(e,k))}function ee(t,n){let r=t.map(t=>{let r=y(`span`,`wui-chat-chip`),i=y(`span`,null,t.status===`Failed`?{title:t.error??``}:null);i.textContent=t.fileName;let a=y(`button`,`wui-chat-chip-remove`,{type:`button`,"aria-label":n.removeAttachment(t.fileName)});a.append(o(`x`,14)),a.addEventListener(`click`,()=>e.onRemove(t.key));let s=[];if(t.status===`Uploading`){let e=y(`progress`,`wui-chat-chip-progress`,{max:`1`});typeof t.progress==`number`&&(e.value=t.progress);let r=y(`span`,`wui-chat-chip-status`);r.textContent=n.attachmentUploading,s.push(e,r)}if(t.status===`Failed`){let e=y(`span`,`wui-chat-chip-error`,{"aria-live":`polite`});e.textContent=t.error||n.attachmentFailed,s.push(e)}return r.append(i,...s,a),r});s.replaceChildren(...r),s.hidden=r.length===0}function te(t){S=t.state,b=t.labels,x=t.maxLength,t.sendIcon&&p.dataset.icon!==t.sendIcon&&(p.dataset.icon=t.sendIcon,p.replaceChildren(o(t.sendIcon,18)));let s=S.messagesLeftToday;h.setAttribute(`aria-label`,b.composer),d.textContent=b.composerHint,u.setAttribute(`aria-label`,b.composer),u.maxLength=x,u.placeholder=S.handoffPause?b.handoffMoment:On(S.messages)??b.placeholder,u.disabled=s===0||S.handoffPause===!0,n.hidden=!(s!==null&&s<=Tn),!n.hidden&&s!==null&&(n.textContent=b.allowance(s));let f=S.editing?.messageId??null;if(f!==_){let t=_!==null;_=f,S.editing?(e.voice?.stop(),u.value=S.editing.text,C()):t&&(u.value=``,C())}a.hidden=!S.editing,r.textContent=b.editing,i.textContent=b.cancel;let y=t.draft??null;typeof y==`string`&&y!==``&&y!==v&&(v=y,u.value=y,u.dispatchEvent(new Event(`input`)),u.focus(),e.onDraftApplied?.()),ee(S.attachments,b);let w=S.features.Attachments&&(S.profile?.limits.maxAttachments??0)>0&&S.handoffPause!==!0;c.hidden=!w,c.setAttribute(`aria-label`,b.attach),c.title=b.attachHint,l.accept=t.accept??``;let T=S.streaming&&S.features.Stop===!0;m.hidden=!T,m.setAttribute(`aria-label`,b.stop),p.hidden=T,p.setAttribute(`aria-label`,b.send),E(),D(),g!==null&&(g.dataset.state=t.busy===!0?`busy`:`rest`,t.inputMark===`Avatar`?g.parentNode!==h&&h.insertBefore(g,u):g.remove()),A?.paint({state:S})}function ne(){u.focus()}function re(){A?.destroy();for(let e of j)e.remove()}let j=[n,a,s,...A?[A.note,A.announcer]:[],h];return{nodes:j,paint:te,focus:ne,destroy:re,getDraft:()=>u.value}}var An=`https://policies.google.com/privacy`,jn=`https://policies.google.com/terms`;function Mn(e,t){let n=y(`a`,`wui-chat-footer-link`,{href:t,target:`_blank`,rel:`noopener noreferrer`});return n.textContent=e,n}function Nn(){let e=y(`p`,`wui-chat-footer`);e.hidden=!0;function t(t){let{labels:n,profile:r,hideDisclaimer:i}=t,a=[];if(r){if(!i){let e=y(`span`,`wui-chat-footer-text`);e.textContent=r.footer.disclaimer||n.disclaimer,a.push(e)}let{privacyText:e}=r.footer,t=pe(r.footer.privacyUrl)?r.footer.privacyUrl:null;if(t){let r=y(`span`,`wui-chat-footer-privacy`),i=y(`a`,`wui-chat-footer-link`,{href:t});i.textContent=e||n.footerPrivacyFallback,r.append(i),a.push(r)}else if(e){let t=y(`span`,`wui-chat-footer-privacy`);t.textContent=e,a.push(t)}if(r.footer.assuranceText){let e=y(`span`);e.textContent=r.footer.assuranceText,a.push(e)}if(ve(r)){let e=y(`span`,`wui-chat-footer-captcha`),t=y(`span`,`wui-chat-footer-captcha-tail`);t.append(Mn(n.captchaPrivacyPolicy,An),document.createTextNode(n.captchaNoticeAnd),Mn(n.captchaTerms,jn),document.createTextNode(n.captchaNoticeAfter)),e.append(document.createTextNode(n.captchaNoticeBefore),t),a.push(e)}}e.replaceChildren(...a),e.hidden=a.length===0}return{el:e,paint:t}}function J(e,t,n){e.setAttribute(`aria-label`,t),e.title=t,e.dataset.icon!==n&&(e.dataset.icon=n,e.replaceChildren(o(n,20)))}function Pn(e){let t=e.mark?.(`header`,`rest`)??y(`span`,`wui-chat-orb`,{"aria-hidden":`true`}),n=y(`strong`,`wui-chat-title`);e.titleId&&(n.id=e.titleId);let r=y(`span`,`wui-chat-tagline`),i=y(`span`,`wui-chat-status`),o=y(`div`,`wui-chat-header-text`);o.append(n,r,i);let s=y(`span`,`wui-chat-header-conversation`);s.hidden=!0;let c=a(``,`history`,()=>e.onHistory()),l=a(``,`volume-high`,()=>e.onMute()),u=a(``,`plus`,()=>e.onNew()),d=a(``,`maximize-4`,()=>e.onSwitch());d.classList.add(`wui-chat-switch-btn`,`wui-chat-switch-btn--full`);let f=a(``,`panel-left-open`,()=>e.onSwitch());f.classList.add(`wui-chat-switch-btn`,`wui-chat-switch-btn--side`);let p=a(``,`x`,()=>e.onClose());p.classList.add(`wui-chat-close-btn`);let m=y(`div`,`wui-chat-header-actions`);m.append(s,c,l,u,d,f,p);let h=y(`header`,`wui-chat-header`);h.append(t,o,m);function g(e){let{labels:t}=e;h.hidden=!1,n.textContent=e.title??``,r.textContent=e.tagline??``,r.hidden=!e.tagline,i.textContent=e.status??``,c.hidden=!e.showHistory,e.viewingHistory?J(c,t.backToChat,`arrow-left`):J(c,t.history,`history`),l.hidden=!e.showMute,J(l,e.muted?t.unmuteSounds:t.muteSounds,e.muted?`volume-mute`:`volume-high`),u.hidden=!!e.viewingHistory||e.showNew===!1,u.disabled=!e.canNew,J(u,t.newChat,`plus`),d.hidden=e.switchTo!==`full-page`,d.disabled=!e.canSwitch,J(d,t.openFullScreen,`maximize-4`),f.hidden=e.switchTo!==`docked`,f.disabled=!e.canSwitch,J(f,t.openSidePanel,`panel-left-open`),p.hidden=!e.showClose,J(p,t.close,`x`)}return{el:h,conversation:s,paint:g}}var Fn=120;function Y(e,t,n=`outline`){let r=y(`button`,`${u(n,`sm`)} wui-chat-action-btn`,{type:`button`});return r.textContent=e,r.addEventListener(`click`,t),r}function In(e){let t=y(`div`,`wui-chat-history`);t.hidden=!0;let n=null,r=null,i=null,o=null,s=null,c=!1;function l(){return n||(n=j({client:e.getClient()}),r=n.subscribe(()=>v()),n)}function u(e){i={id:e.publicId,kind:`rename`,draft:e.title??``,saving:!1},o=null,s=null,c=!0,v()}function d(e){i={id:e.publicId,kind:`delete`,saving:!1},o=null,s=null,v()}function f(){i=null,o=null,s=null,v()}async function p(){let t=i;if(t?.kind!==`rename`||t.saving)return;let n=t.draft.trim();if(n){t.saving=!0,v();try{await l().rename(t.id,n),i===t&&(i=null),o=null,s=null}catch{if(i!==t)return;t.saving=!1,s=e.getLabels().renameFailed}v()}}async function m(){let t=i;if(!(t?.kind!==`delete`||t.saving)){t.saving=!0,v();try{await l().remove(t.id),i===t&&(i=null),o=null,e.onDeleted(t.id)}catch{if(i!==t)return;t.saving=!1,o=e.getLabels().deleteFailed}v()}}function h(e,t){let n=y(`li`,`wui-chat-history-row wui-chat-history-row--editing`),r=y(`input`,`wui-chat-history-input`,{type:`text`,"aria-label":e.conversationTitle,maxlength:String(Fn)});r.value=t.draft,r.addEventListener(`input`,()=>{t.draft=r.value,i.disabled=t.saving||!t.draft.trim()}),r.addEventListener(`keydown`,e=>{e.key===`Enter`&&!e.isComposing&&e.keyCode!==229?(e.preventDefault(),p()):e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),f())});let i=Y(e.renameSave,()=>p(),`primary`);if(i.disabled=t.saving||!t.draft.trim(),n.append(r,i,Y(e.cancel,()=>f(),`ghost`)),s!==null){let e=y(`p`,`wui-chat-history-error`,{role:`alert`});e.textContent=s,n.append(e)}return c&&(c=!1,queueMicrotask(()=>r.focus())),n}function g(e,t){let n=y(`li`,`wui-chat-history-row wui-chat-history-row--confirm`),r=y(`p`);r.textContent=e.deleteConfirmTitle;let i=y(`p`);i.textContent=e.deleteConfirmMessage;let a=Y(e.deleteConfirm,()=>m(),`danger`);return a.disabled=t.saving,n.append(r,i,a,Y(e.cancel,()=>f(),`ghost`)),n}function _(t,n,r){if(i?.id===t.publicId&&i.kind===`rename`)return h(n,i);if(i?.id===t.publicId&&i.kind===`delete`)return g(n,i);let o=y(`li`,`wui-chat-history-row`),s=y(`button`,`wui-chat-history-open`,{type:`button`}),c=y(`span`,`wui-chat-history-title`);c.textContent=t.title||n.untitled;let l=y(`span`,`wui-chat-history-time`);return l.textContent=M(t.lastActivityDateTimeUtc),s.append(c,l),s.addEventListener(`click`,()=>e.onOpen(t.publicId)),o.append(s),r.Rename&&o.append(a(n.rename,`pencil`,()=>u(t))),r.Delete&&o.append(a(n.deleteChat,`trash`,()=>d(t))),o}function v(){let r=e.getLabels(),i=e.getFeatures(),a=n?n.getState():{items:[],totalCount:null,loading:!1,error:null,hasMore:!1},s=[];if(a.error||o){let e=y(`p`,`wui-chat-history-error`,{role:`alert`});a.error?(e.append(document.createTextNode(r.loadFailed),document.createTextNode(` `)),e.append(Y(r.retry,()=>l().load(),`outline`))):e.textContent=o,s.push(e)}if(a.loading&&a.items.length===0){let e=y(`p`,`wui-chat-history-empty`,{role:`status`});e.textContent=r.loadingConversation,s.push(e)}if(a.items.length===0&&!a.loading&&!a.error){let e=y(`p`,`wui-chat-history-empty`),t=y(`span`);t.textContent=r.historyEmptyTitle;let n=y(`span`);n.textContent=r.historyEmptyText,e.append(t,n),s.push(e)}if(a.items.length>0){let e=y(`ul`,`wui-chat-history-list`,{"aria-label":r.history});e.append(...a.items.map(e=>_(e,r,i))),s.push(e)}a.hasMore&&!a.loading&&s.push(Y(r.loadMore,()=>l().loadMore(),`outline`)),t.replaceChildren(...s)}function b(){t.hidden=!1,Promise.allSettled([l().load()]),v()}function x(){t.hidden=!0}function S(){r?.(),r=null,n?.dispose(),n=null}return{el:t,show:b,hide:x,paint:v,dispose:S}}var Ln=/* @__PURE__ */ new Set([`GET`,`HEAD`]);function Rn(){let e=document.querySelector(`meta[name="wui-csrf"]`),t=e?.getAttribute(`content`);return t?{token:t,header:e?.getAttribute(`data-header`)||`RequestVerificationToken`}:null}async function zn(e,{lenient:t=!1}={}){let n=await e.text();if(n){if((e.headers.get(`content-type`)||``).includes(`json`)){if(!t)return JSON.parse(n);try{return JSON.parse(n)}catch{return n}}return n}}async function Bn(e,t,n){let r=new TextDecoder,i=e.getReader(),a=``;for(;;){let{done:e,value:o}=await i.read();if(e)break;a+=r.decode(o,{stream:!0}),n({event:{target:{responseText:a,status:t}}})}return a+=r.decode(),a}function Vn({fetch:e=(...e)=>globalThis.fetch(...e)}={}){async function t(t,n,r,i={}){let a={...i.headers},o;if(typeof FormData<`u`&&r instanceof FormData){for(let e of Object.keys(a))e.toLowerCase()===`content-type`&&delete a[e];o=r}else r!==void 0&&(a[`Content-Type`]=`application/json`,o=JSON.stringify(r));if(!Ln.has(t)){let e=Rn();e&&(a[e.header]=e.token)}let s=i.signal,c=s,l,u,d=()=>l?.abort(s?.reason);(i.timeout??0)>0&&(l=new AbortController,c=l.signal,s?.aborted?l.abort(s.reason):s?.addEventListener(`abort`,d,{once:!0}),u=setTimeout(()=>l?.abort(new DOMException(`The request timed out.`,`TimeoutError`)),i.timeout));try{let r={method:t,headers:a,credentials:`same-origin`};o!==void 0&&(r.body=o),c&&(r.signal=c);let s=await e(n,r);if(!s.ok){let e=/* @__PURE__ */ Error(`Request failed with status ${s.status}`);throw e.response={status:s.status,data:await zn(s,{lenient:!0})},e}let l;return l=i.responseType===`arraybuffer`?await s.arrayBuffer():typeof i.onDownloadProgress==`function`&&s.body?await Bn(s.body,s.status,i.onDownloadProgress):await zn(s),{data:l,status:s.status}}finally{clearTimeout(u),s?.removeEventListener(`abort`,d)}}return{get:(e,n)=>t(`GET`,e,void 0,n),post:(e,n,r)=>t(`POST`,e,n,r),put:(e,n,r)=>t(`PUT`,e,n,r),delete:(e,n)=>t(`DELETE`,e,void 0,n)}}function Hn(e){let t,n=!1,r=!1,i=y(`div`,`wui-chat-nudge`,{role:`status`});i.hidden=!0;let a=y(`button`,`wui-chat-nudge-text`,{type:`button`}),s=y(`button`,`wui-chat-nudge-close`,{type:`button`});s.append(o(`x`,14)),i.append(a,s);function c(){clearTimeout(t),t=void 0}function l(){c(),r=!0,i.hidden=!0}a.addEventListener(`click`,()=>{i.hidden=!0,e.onActivate()}),s.addEventListener(`click`,()=>{l(),e.onDismiss()});function u(e){c(),r||n||(t=setTimeout(()=>{t=void 0,a.textContent=e.text,s.setAttribute(`aria-label`,e.label),i.hidden=!1,n=!0},e.delaySeconds*1e3))}function d(){c(),i.remove()}return{el:i,schedule:u,cancel:c,dismiss:l,isShown:()=>n,destroy:d}}function Un(e,t){e.addEventListener(`click`,()=>t()),e.addEventListener(`keydown`,e=>{(je(e)||e.key===` `)&&(e.preventDefault(),t())})}function Wn(e){let{list:t,getLabels:n,getFeatures:r,onOpen:i}=e,a=y(`div`,`wui-chat-empty-rows wui-chat-empty-rows--past`);a.hidden=!0;let o=!1;function s(e,t){let n=y(`div`,`card card-pad-sm card-clickable wui-chat-empty-row`,{role:`button`,tabindex:`0`}),r=y(`div`,`card-body wui-chat-empty-row-body`),a=y(`span`,`wui-chat-empty-row-title`);a.textContent=e.title||t.earlierChat;let o=y(`span`,`wui-chat-empty-row-time`,{title:ae(e.lastActivityDateTimeUtc)});return o.textContent=M(e.lastActivityDateTimeUtc),r.append(a,o),n.append(r),Un(n,()=>i(e.publicId)),n}function c(){if(o)return;let e=t.getState().items;if(r().History!==!0||e.length===0){a.replaceChildren(),a.hidden=!0;return}let i=n();a.replaceChildren(...e.slice(0,20).map(e=>s(e,i))),a.hidden=!1}let l=t.subscribe(c);return{el:a,refresh(){r().History===!0&&t.load().catch(e=>globalThis.reportError?.(e))},paint:c,dispose(){o=!0,l()}}}var Gn=`https://www.google.com/recaptcha/api.js?render=`;function Kn(e){return e!==void 0&&typeof e.ready==`function`&&typeof e.execute==`function`}var qn=/* @__PURE__ */ new Map;function Jn(e){let t=qn.get(e);if(t!==void 0)return t;let n=new Promise((t,n)=>{let r=globalThis.grecaptcha;if(Kn(r)){t(r);return}let i=document.createElement(`script`);i.src=Gn+encodeURIComponent(e),i.async=!0;let a=t=>{qn.delete(e),n(Object.assign(Error(t),{code:`captcha_unavailable`}))};i.addEventListener(`load`,()=>{let e=globalThis.grecaptcha;e===void 0||typeof e.ready!=`function`?a(`The reCAPTCHA script loaded without grecaptcha.`):e.ready(()=>{let e=globalThis.grecaptcha;Kn(e)?t(e):a(`reCAPTCHA became ready without execute.`)})}),i.addEventListener(`error`,()=>{qn.delete(e),n(/* @__PURE__ */ Error(`The reCAPTCHA script did not load.`))}),document.head.append(i)});return qn.set(e,n),n}async function Yn(e,t){let n=await Jn(e);await new Promise(e=>n.ready(()=>e()));let r=await n.execute(e,{action:t});if(!r)throw Object.assign(/* @__PURE__ */ Error(`reCAPTCHA returned no token.`),{code:`captcha_unavailable`});return r}var Xn=/* @__PURE__ */ new Set([`Assistant`,`Agent`,`Script`]),Zn=/* @__PURE__ */ new WeakMap;function Qn(e,t,n){let{labels:i,features:a,title:o,busy:s,assistantName:c}=n;if(N(t.parts)!==``){if(a.Share&&_()){let n=r(`ghost`,i.share,`share`,()=>void(async()=>{let e=rr([t],a,i,o,!1,c);e!==``&&await d({title:o,text:e})===`failed`&&sr(n.parentElement,i.shareFailed)})());n.disabled=s===!0,e.append(n)}if(a.Print){let t=r(`ghost`,i.print,`printer`,()=>{try{let e=t.closest(`.wui-chat`),n=t.closest(`li.wui-chat-message`);if(!(e instanceof HTMLElement)||!(n instanceof HTMLElement))throw Error(`printReply needs a message inside the wui-chat root`);p(e,n,{title:o,printedOn:ar(i)})}catch{or(t,i.printFailed)}});e.append(t)}}}function $n(e,t,n){if(t.streaming||t.thinking||t.loading||t.conversationId===null||t.messages.filter(e=>e.stored&&Xn.has(e.author.kind)&&N(e.parts)!==``).length===0){e.hidden=!0;return}let{labels:r,features:i}=n,a=!!i.Share&&_(),o=!!i.Print;if(!a&&!o){e.hidden=!0;return}let s=[a,o,t.messages.length,r.shareConversation,r.printConversation].join(`|`);e.dataset.sig!==s&&(e.dataset.sig=s,e.replaceChildren(),a&&e.append(tr(e,r,i,n)),o&&e.append(nr(e,r,n))),e.hidden=!1}function er(e,t,n,i){return e.iconOnly?a(t,n,i):r(`ghost`,t,n,i)}function tr(e,t,n,r){return er(r,t.shareConversation,`share`,()=>void(async()=>{let i=r.getState(),a=ir(i,r),o=rr(i.messages.filter(e=>e.stored),n,t,a,!0,i.profile?.assistant.name);await d({title:a,text:o})===`failed`&&sr(e,t.shareFailed)})())}function nr(e,t,n){let r=er(n,t.printConversation,`printer`,()=>{try{let r=e.closest(`.wui-chat`);if(!(r instanceof HTMLElement))throw Error(`printConversation needs the wui-chat root`);k(r,{title:ir(n.getState(),n),printedOn:ar(t)})}catch{n.iconOnly?sr(e,t.printFailed):or(r,t.printFailed)}});return r}function rr(e,t,n,r,i,a){let o=te(e,{labels:n,title:r,figureText:t.FigureText,...a===void 0?{}:{assistantName:a}});return Se(o,{heading:i,speakers:i})}function ir(e,t){return typeof e.title==`string`&&e.title!==``?e.title:t.title}function ar(e){return e.printedOn(M((/* @__PURE__ */ new Date()).toISOString()))}function or(e,t){let n=e.lastChild;if(!(n instanceof Text))return;let r=Zn.get(n);r&&clearTimeout(r.timer);let i=r??{original:n.data};n.data=t,i.timer=setTimeout(()=>{n.data=i.original,Zn.delete(n)},Ee),Zn.set(n,i)}function sr(e,t){if(!e)return;let n=document.createElement(`span`);n.className=`wui-chat-action-notice`,n.setAttribute(`role`,`status`),n.textContent=t,e.append(n),setTimeout(()=>n.remove(),Ee)}var cr=`data-wchat-docked`,lr=`--wui-chat-docked-width`,ur=420,dr=/* @__PURE__ */ new Set;function fr(e,t){let n=document.documentElement;n.setAttribute(cr,e),n.style.setProperty(lr,t)}function pr(){let e=document.documentElement;e.removeAttribute(cr),e.style.removeProperty(lr)}function mr(e){let t=s({...e,layout:`docked`,role:`dialog`,launcher:!0}),n={},r=e.position,i=!1,a=null,o=()=>`${Math.round(t.panel.getBoundingClientRect().width)||ur}px`;function c(){dr.add(n),fr(r,o()),typeof ResizeObserver==`function`&&(a=new ResizeObserver(()=>document.documentElement.style.setProperty(lr,o())),a.observe(t.panel))}function l(){a?.disconnect(),a=null,dr.delete(n),dr.size===0&&pr()}function u(e){t.setOpen(e),e&&!i?(i=!0,c()):!e&&i&&(i=!1,l())}function d(e){t.setAppearance(e),e.position!==void 0&&(r=e.position,i&&document.documentElement.setAttribute(cr,r))}function f(){u(!1)}return{...t,setOpen:u,setAppearance:d,destroy:f}}function hr(e){return s({...e,layout:`embedded`,role:`region`,launcher:!1})}var gr=`wchat:peeked`,_r=576,vr=200;function yr(e){let t=s({...e,layout:`launcher`,role:`dialog`,launcher:!0}),{root:n,panel:r,setLauncherState:i}=t;if(!t.nudgeHost||!t.launcherButton)throw Error(`a launcher shell always has its launcher`);let a=t.nudgeHost,o=t.launcherButton,c={peek:!1,peekSeconds:3,hideWhileOpen:!1,expressive:!1};o.dataset.state=`closed`;let l=!1,u=!1,d,f,p=()=>c.hideWhileOpen||c.expressive;function m(){!c.peek||l||u||a.dataset.launcher!==`idle`||globalThis.innerWidth<_r||globalThis.sessionStorage.getItem(gr)!==null||(globalThis.sessionStorage.setItem(gr,`1`),i(`peeking`),d=setTimeout(()=>{d=void 0,a.dataset.launcher===`peeking`&&i(`idle`)},c.peekSeconds*1e3))}a.addEventListener(`animationend`,e=>{e.target===a&&a.dataset.launcher===`idle`&&m()});function h(e){if(e!==u){if(u=e,clearTimeout(d),d=void 0,e)clearTimeout(f),f=void 0,p()?(i(`hidden`),a.toggleAttribute(`inert`,!0)):a.dataset.launcher===`peeking`&&i(`idle`);else if(p()){let e=r.contains(document.activeElement);f=setTimeout(()=>{f=void 0,a.toggleAttribute(`inert`,!1),i(`idle`),e&&o.focus()},vr)}}o.dataset.state=e?`open`:`closed`,t.setOpen(e)}function g(e){e.reduced!==void 0&&(l=!!e.reduced),e.peek!==void 0&&(c.peek=e.peek),e.peekSeconds!==void 0&&(c.peekSeconds=e.peekSeconds),e.hideWhileOpen!==void 0&&(c.hideWhileOpen=e.hideWhileOpen),e.expressive!==void 0&&(c.expressive=e.expressive===!0),e.phoneMode!==void 0&&n.classList.toggle(`wui-chat--sheet`,e.phoneMode===`Sheet`),e.sheetHeightDvh!==void 0&&n.style.setProperty(`--_wui-chat-sheet-height`,`${e.sheetHeightDvh}dvh`),e.sheetMaxHeightPx!==void 0&&n.style.setProperty(`--_wui-chat-sheet-max-height`,`${e.sheetMaxHeightPx}px`),t.setAppearance(e),!p()&&a.dataset.launcher===`hidden`&&!u&&i(`idle`),a.dataset.launcher===`idle`&&m()}return{...t,nudgeHost:a,launcherButton:o,setOpen:h,setAppearance:g}}function br(e){return s({...e,layout:`full-page`,role:`region`,launcher:!1})}var xr=/* @__PURE__ */ new Set([`Agent`,`Customer`]);function Sr(){let e=document.createElement(`div`);e.className=`wui-chat-loader-typing`,e.setAttribute(`aria-hidden`,`true`),e.hidden=!0;let t=document.createElement(`span`);t.className=`wui-chat-loader-typing-orb`;let n=document.createElement(`span`);n.className=`wui-chat-loader-typing-dots`;for(let e=0;e<3;e++){let e=document.createElement(`span`);e.className=`wui-chat-loader-typing-dot`,n.append(e)}e.append(t,n);function r({active:n,reduced:r,authorKind:i}){e.hidden=!n,e.classList.toggle(`wui-chat-loader--reduced`,r===!0),t.hidden=xr.has(i)}function i(){e.remove()}return{el:e,update:r,destroy:i}}var Cr=3,wr={Primary:`wui-chat-starter--primary`,Cta:`wui-chat-starter--cta`};function Tr(e,t){e.addEventListener(`click`,()=>t()),e.addEventListener(`keydown`,e=>{(je(e)||e.key===` `)&&(e.preventDefault(),t())})}function Er(e){let t=y(`h2`,`wui-chat-greeting`),n=y(`div`,`wui-chat-empty-hero`),r=y(`p`,`wui-chat-empty-intro`);r.hidden=!0;let i=e.mark?.(`greeting`,`rest`)??y(`span`,`wui-chat-orb`,{"aria-hidden":`true`});n.append(i,t,r);let a=y(`div`,`wui-chat-empty-extra`);a.hidden=!0;let s=y(`div`,`wui-chat-starters`,{role:`group`}),c=y(`div`,`wui-chat-empty-rows`),l=y(`div`,`wui-chat-empty-past`),u=y(`div`,`wui-chat-empty`,{role:`group`}),d=Sr();u.append(d.el,n,a,s,c,l);let f;function p(t,n){let r=t.variant===null?void 0:wr[t.variant],i=y(`button`,[`wui-chat-starter`,r??``].filter(Boolean).join(` `),{type:`button`});if(i.style.setProperty(`--wui-chat-i`,String(n)),t.icon){let e=y(`span`,`wui-chat-starter-icon`,{"aria-hidden":`true`});e.append(o(t.icon,16)),i.append(e)}return i.append(document.createTextNode(t.label)),i.addEventListener(`click`,()=>e.onStarter(t)),i}function m(t,n){let r=y(`div`,`card card-pad-sm card-clickable wui-chat-empty-row`,{role:`button`,tabindex:`0`}),i=y(`div`,`card-body wui-chat-empty-row-body`),a=y(`span`,`wui-chat-empty-row-label`);a.textContent=n.resumeLast;let o=y(`span`,`wui-chat-empty-row-title`,{title:t.title||n.untitled});o.textContent=t.title||n.untitled;let s=y(`span`,`wui-chat-empty-row-time`);return s.textContent=M(t.lastActivityDateTimeUtc),i.append(a,o,s),r.append(i),Tr(r,()=>e.onResume()),r}function h(t,n){let r=y(`div`,`card card-pad-sm card-clickable wui-chat-empty-row`,{role:`button`,tabindex:`0`}),i=y(`div`,`card-body wui-chat-empty-row-body`),a=y(`span`,`wui-chat-empty-row-title`,{title:t.title||n.untitled});a.textContent=t.title||n.untitled;let o=y(`span`,`wui-chat-empty-row-time`);return o.textContent=M(t.lastActivityDateTimeUtc),i.append(a,o),r.append(i),Tr(r,()=>e.onOpenConversation(t.publicId)),r}function g(t,n,r){let i=r?y(`div`,`card card-pad-sm card-clickable wui-chat-empty-row`,{role:`button`,tabindex:`0`}):y(`div`,`card card-pad-sm wui-chat-empty-row`),a=y(`div`,`card-body wui-chat-empty-row-body`),o=y(`span`,`wui-chat-empty-row-label`);o.textContent=n.ticketAria(t.number);let s=y(`span`,`wui-chat-empty-row-title`);s.textContent=t.subject;let c=y(`span`,`wui-chat-empty-row-status`);return c.textContent=gt(t.status,n),a.append(o,s,c),i.append(a),r&&Tr(i,()=>e.onTicket(t)),i}function _(e,t){if(e.features?.OpenTickets!==!0||!e.openTickets?.length)return null;let n=y(`div`,`wui-chat-open-tickets`,{role:`group`,"aria-label":t.openTickets});return n.append(...e.openTickets.slice(0,Cr).map(n=>g(n,t,e.ticketsClickable===!0))),n}function v(e){let{labels:n}=e;t.textContent=e.greeting??``;let i=e.intro??``;r.textContent=i,r.hidden=!i,u.setAttribute(`aria-label`,n.emptyTitle);let a=e.starters??[];s.setAttribute(`aria-label`,n.starters),s.hidden=!e.showStarters||a.length===0,s.replaceChildren(...a.map(p));let o=e.resume??null,l=e.recent.length===0?null:y(`div`,`wui-chat-recent`,{role:`group`,"aria-label":n.recentChats});l?.append(...e.recent.map(e=>h(e,n)));let d=_(e,n),f=l??(o===null?null:m(o,n));c.hidden=f===null&&d===null,c.replaceChildren(...[f,d].filter(e=>e!==null))}function b(e){clearTimeout(f),u.classList.remove(`wui-chat-empty--revealed`),u.classList.add(`wui-chat-empty--intro`),d.update({active:!0,reduced:!1,authorKind:`Assistant`}),f=setTimeout(()=>{f=void 0,d.update({active:!1,reduced:!1,authorKind:`Assistant`}),u.classList.replace(`wui-chat-empty--intro`,`wui-chat-empty--revealed`)},e)}return{el:u,paint:v,intro:b,extraHost:a,pastHost:l}}function Dr(){let e=document.createElement(`div`);e.className=`wui-chat-loader-orb`;let t=document.createElement(`span`);t.className=`wui-chat-loader-orb-mark`,t.setAttribute(`aria-hidden`,`true`);let n=document.createElement(`span`);n.className=`wui-chat-loader-orb-glow`,n.setAttribute(`aria-hidden`,`true`);let r=document.createElement(`span`);r.className=`wui-chat-loader-orb-disc`,r.setAttribute(`aria-hidden`,`true`),t.append(n,r);let i=document.createElement(`span`);i.className=`wui-chat-loader-orb-label`,e.append(t,i);let a=t;return{el:e,render(n,r=null){i.textContent!==n.label&&(i.textContent=n.label);let o=r??t;o!==a&&(a.parentNode===e?a.replaceWith(o):e.prepend(o),a=o)}}}var Or=150,kr=1800;function Ar(){let e=document.createElement(`div`);e.className=`wui-chat-loader-phrases`;let t=document.createElement(`span`);t.className=`wui-chat-loader-phrases-orb`,t.setAttribute(`aria-hidden`,`true`);let n=document.createElement(`span`);n.className=`wui-chat-loader-phrases-stage`,e.append(t,n);let r=null,i=null;function a(){return e.closest(`.wui-chat-loader`)?.classList.contains(`wui-chat-loader--reduced`)===!0}function o(e){if(e.label===r)return;r=e.label;let t=i,o=document.createElement(`span`);o.className=`wui-chat-loader-phrases-text wui-chat-loader-phrases-text--in`,o.textContent=e.label,o.style.animationDelay=`-${Math.round(performance.now()%kr)}ms, 0s`,n.append(o),i=o,t&&(t.classList.remove(`wui-chat-loader-phrases-text--in`),t.classList.add(`wui-chat-loader-phrases-text--out`),t.style.animationDelay=`-${Math.round(performance.now()%kr)}ms, 0s`,a()?t.remove():setTimeout(()=>t.remove(),Or))}return{el:e,render:o}}var jr=3;function Mr(){let e=document.createElement(`div`);e.className=`wui-chat-loader-pulse`;let t=document.createElement(`span`);t.className=`wui-chat-loader-pulse-disc`,t.setAttribute(`aria-hidden`,`true`);let n=document.createElement(`span`);n.className=`wui-chat-loader-pulse-label`;let r=document.createElement(`span`);r.className=`wui-chat-loader-pulse-dots`,r.setAttribute(`aria-hidden`,`true`);for(let e=0;e<jr;e+=1){let e=document.createElement(`span`);e.className=`wui-chat-loader-pulse-dot`,r.append(e)}e.append(t,n,r);let i=t;return{el:e,render(r,a=null){n.textContent!==r.label&&(n.textContent=r.label);let o=a??t;o!==i&&(i.parentNode===e?i.replaceWith(o):e.prepend(o),i=o)}}}var Nr=[`95%`,`80%`,`60%`];function Pr(){let e=document.createElement(`div`);e.className=`wui-chat-loader-skeleton`;let t=document.createElement(`div`);t.className=`wui-chat-loader-skeleton-label`;let n=document.createElement(`div`);n.className=`wui-chat-loader-skeleton-body`;let r=document.createElement(`span`);r.className=`wui-chat-loader-skeleton-avatar`,r.setAttribute(`aria-hidden`,`true`),n.append(r);for(let e of Nr){let t=document.createElement(`span`);t.className=`wui-chat-loader-skeleton-line`,t.setAttribute(`aria-hidden`,`true`),t.style.width=e,n.append(t)}return e.append(t,n),{el:e,render(e){t.textContent!==e.label&&(t.textContent=e.label)}}}var Fr=`http://www.w3.org/2000/svg`;function Ir(e){if(e===`done`){let e=document.createElementNS(Fr,`svg`);e.setAttribute(`viewBox`,`0 0 16 16`),e.setAttribute(`class`,`wui-chat-loader-steps-check`);let t=document.createElementNS(Fr,`path`);return t.setAttribute(`d`,`M3 8.5 6.5 12 13 4.5`),t.setAttribute(`pathLength`,`1`),e.append(t),e}let t=document.createElement(`span`);return t.className=e===`active`?`wui-chat-loader-steps-ring`:`wui-chat-loader-steps-dot`,t}function Lr(){let e=document.createElement(`div`);e.className=`wui-chat-loader-steps`;let t=document.createElement(`span`);t.className=`wui-chat-loader-steps-pill`;let n=document.createElement(`ol`);n.className=`wui-chat-loader-steps-list`,e.append(t,n);let r=[],i=null;function a(){let e=document.createElement(`li`);e.className=`wui-chat-loader-steps-item`;let t=document.createElement(`span`);t.className=`wui-chat-loader-steps-icon`,t.setAttribute(`aria-hidden`,`true`);let i=document.createElement(`span`);i.className=`wui-chat-loader-steps-text`,e.append(t,i);let a={li:e,icon:t,text:i,state:null};return r.push(a),n.append(e),a}function o(o,s=null){s!==i&&(i?.remove(),i=s,s!==null&&e.prepend(s));let c=o.steps.length===0;for(t.hidden=!c,n.hidden=c,c&&t.textContent!==o.label&&(t.textContent=o.label),o.steps.forEach((e,t)=>{let n=r[t]??a();n.text.textContent!==e&&(n.text.textContent=e);let i=t<o.activeIndex?`done`:t===o.activeIndex?`active`:`pending`;n.state!==i&&(n.state=i,n.li.dataset.state=i,n.icon.replaceChildren(Ir(i)))});r.length>o.steps.length;)r.pop()?.li.remove()}return{el:e,render:o}}var Rr={Steps:Lr,Phrases:Ar,Orb:Dr,Skeleton:Pr,PulseAndDots:Mr},zr=500;function Br(){let e=document.createElement(`div`);e.className=`wui-chat-loader`,e.setAttribute(`role`,`status`),e.hidden=!0;let t=document.createElement(`span`);t.className=`wui-chat-loader-avatar`,t.setAttribute(`aria-hidden`,`true`);let n=document.createElement(`div`);n.className=`wui-chat-loader-body`;let r=document.createElement(`span`);r.className=`visually-hidden`,e.append(t,n,r);let i=null,a=null,o=0,s=null,c=0,l=null,u=!1;function d(){s!==null&&clearInterval(s),s=null}function f(){e.isConnected?(o+=1,p()):d()}function p(){if(!a||!i)return;let t=me(i.style,i.steps,i.phrases,o);a.render(t,i.mark),e.setAttribute(`aria-label`,t.label)}function m(){l!==null&&clearTimeout(l),l=null,u=!1,r.textContent=``}function h(e){!u&&l===null&&e&&(l=setTimeout(()=>{l=null,u=!0,r.textContent=e},zr))}function g(t){if(!t.active)i=null,e.hidden=!0,e.removeAttribute(`data-loading`),d(),m();else{if(!v(Rr,t.style))throw Error(`Unknown loader style. Use Steps, Phrases, Orb, Skeleton or PulseAndDots.`);if(!(t.intervalMs>0))throw Error(`Loader intervalMs must be a positive number.`);if(i={...t,steps:t.steps??[],phrases:t.phrases??[],mark:t.mark??null},e.hidden=!1,e.setAttribute(`data-loading`,`true`),e.classList.toggle(`wui-chat-loader--reduced`,t.reduced===!0),!a||a.style!==t.style){let r=Rr[t.style]();n.replaceChildren(r.el),a={style:t.style,render:r.render},e.dataset.style=t.style,o=0}h(t.announce),t.reduced===!0?(d(),o=0):(s===null||c!==t.intervalMs)&&(d(),c=t.intervalMs,s=setInterval(f,c)),p()}}function _(){d(),m(),a=null,i=null,e.remove()}return{el:e,update:g,destroy:_}}function Vr({voice:e,getLabels:t,message:n}){if(n.streaming||!e.canSpeak()||yn(n.parts)===``)return null;let r=e.getStatus(),i=r.mode===`Speaking`&&r.messageId===n.id,a=t(),o=i?a.readAloudStop:a.readAloud,s=y(`button`,`wui-chat-action-btn wui-chat-speak`,{type:`button`,"aria-pressed":String(i),"aria-label":o,title:o});return s.append(un(i?`stop`:`speaker`,16)),s.addEventListener(`click`,()=>{e.toggleSpeak(n.id,n.parts)}),s}function Hr({voice:e,getLabels:t,message:n}){let r=e.getStatus().note;if(r?.code!==`SpeakFailed`||r.messageId!==n.id)return null;let i=y(`span`,`wui-chat-action-notice`,{role:`status`});return i.textContent=bn(r,t()),i}function Ur(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n?.author.kind===`Visitor`&&n.stored)return n}}var Wr=/* @__PURE__ */ new Set([`Assistant`,`Agent`]),Gr=/* @__PURE__ */ new Set([`Assistant`,`Agent`,`Script`]),Kr=/* @__PURE__ */ new Set([`Visitor`,`Customer`]),qr=48,Jr=120,Yr={author:{kind:`Assistant`,displayName:null,avatarUrl:null}},Xr={warning:`alert-triangle`,danger:`alert-circle`};function Zr(e,t,n,r,i){n!==null&&(n.dataset.state=i?`busy`:`rest`,r?n.parentNode!==e&&e.insertBefore(n,t):n.remove())}function Qr(e){return e.scrollHeight-e.scrollTop-e.clientHeight<=qr}function $r(e){let{kind:t,displayName:n}=e.author;return t===`Agent`?`Agent:${n??``}`:t===`Script`?`Assistant`:t}function ei(e){for(let t=e?.parentElement;t&&t!==document.body;t=t.parentElement){let{overflowY:e}=getComputedStyle(t);if((e===`auto`||e===`scroll`)&&t.scrollHeight>t.clientHeight)return t}return null}function ti(e){let t=e.textContent?.trim();t&&!e.hasAttribute(`aria-label`)&&(e.setAttribute(`aria-label`,t),e.setAttribute(`title`,t))}function ni(e){return e.reduced===!0}function ri(e,t,n){let r=y(`button`,`${u(`ghost`,`sm`)} wui-chat-action-btn`,{type:`button`,"aria-label":e,title:e}),i=y(`span`);return i.textContent=e,r.append(o(t,14),i),r.addEventListener(`click`,n),{node:r,text:i}}function ii(e,t){return e.profile?.assistant.name||t.assistant}function ai(e,t,n){return e.author.displayName==null?e.author.kind===`Visitor`||e.author.kind===`Customer`?n.you:e.author.kind===`Agent`?n.agent:t.profile?.assistant.name??n.assistant:e.author.displayName}function oi(e){let t=y(`li`,`wui-chat-day`,{role:`presentation`}),n=y(`span`);return n.textContent=e,t.append(n),t}function si(e){let t=y(`ol`,`wui-chat-thread`),n=y(`div`,`wui-chat-log`,{role:`log`,"aria-live":`polite`});n.append(t);let r=Br(),i=y(`li`,`wui-chat-message wui-chat-message--assistant wui-chat-message--loading`),a=y(`div`,`wui-chat-loader-slot`);a.append(r.el);let s=e.mark?.(`loader`,`busy`)??null;i.append(a);let c=!1,l,d=y(`li`,`wui-chat-message wui-chat-message--assistant wui-chat-message--greeting`,{"data-run-start":``,"data-restored":``}),f=y(`div`,`wui-chat-message-body`),p=y(`p`,`wui-chat-text`);f.append(p),d.append(f);let m=e.mark?.(`reply`,`rest`)??null,h=y(`button`,`wui-chat-jump`,{type:`button`}),g=y(`div`,`wui-chat-jump-slot`);g.hidden=!0,g.append(h);let _=null,v=!0,b=null,S=null,C=/* @__PURE__ */ new Map,w=``,T=null;function E(e,t){return{kind:e.kind,part:e,tag:t[e.kind]}}function D(t,n,r){return Object.assign(document.createElement(t),{message:r,turn:e.makeTurnApi(r.id),chatPart:n})}function O(e){return y(`div`,`wui-chat-part wui-chat-part--${e.toLowerCase()}`)}function k(e,t,n,r){e.parts=[];let i=[],a=e=>{let r=E(e,n),i=O(r.kind);return i.append(D(r.tag,r.part,t)),i};for(let e of r(t))if(Array.isArray(e)){let t=y(`div`,`wui-chat-part-group`);t.append(...e.map(a)),i.push(t)}else i.push(a(e));e.body.replaceChildren(...i)}function A(t,n,r){let i=[];n.parts.forEach((a,o)=>{let s=E(a,r),c=t.parts[o];if(c&&c.kind===s.kind&&c.tag===s.tag){c.part!==s.part&&(c.element.message=n,c.element.turn=e.makeTurnApi(n.id),c.element.chatPart=s.part,c.part=s.part),i.push(c);return}let l=O(s.kind),u=D(s.tag,s.part,n);l.append(u),i.push({kind:s.kind,tag:s.tag,part:s.part,element:u,wrapper:l})}),t.parts=i,ee(t.body,i.map(e=>e.wrapper))}function ee(e,t){let n=new Set(t);for(let t of[...e.children])n.has(t)||t.remove();t.forEach((t,n)=>{e.children[n]!==t&&e.insertBefore(t,e.children[n]??null)})}function te(e,t,n){let r=y(`div`,`wui-chat-rating`,{role:`group`,"aria-label":`${n.rateUp} / ${n.rateDown}`}),i=[[`Up`,n.rateUp,`thumbs-up`],[`Down`,n.rateDown,`thumbs-down`]];for(let[a,s,c]of i){let i=t.rating===a,l=y(`button`,`${u(i?`neutral`:`ghost`,`sm`)} wui-chat-action-btn`,{type:`button`,"aria-pressed":String(i),"data-rating":a,"aria-label":s,title:s}),d=y(`span`);d.textContent=s,l.append(o(c,14),d),l.addEventListener(`click`,()=>ne(e,t,a,n)),r.append(l)}if(e.ratingNote){let t=y(`span`,null,{role:`status`});t.textContent=e.ratingNote,r.append(t)}return r}async function ne(t,n,r,i){try{await e.onRate(n.id,r),t.ratingNote=i.rated}catch{t.ratingNote=i.ratingFailed}T&&he(T.state,T.context)}function re(t,n,r,i,a){let{labels:o}=i,s=r.features,c=n.author.kind,l=N(n.parts),u=[];if(s.Copy&&Gr.has(c)&&l){let e=ri(o.copy,`copy`,()=>void(async()=>{await De(l)&&(e.text.textContent=o.copied,e.node.dataset.done=``,e.node.setAttribute(`aria-label`,o.copied),e.node.title=o.copied,clearTimeout(t.copyTimer),t.copyTimer=setTimeout(()=>{e.text.textContent=o.copy,delete e.node.dataset.done,e.node.setAttribute(`aria-label`,o.copy),e.node.title=o.copy},Ee))})());u.push(e.node)}let d=e.getVoice?.();if(d&&Gr.has(c)){let e=Vr({voice:d,getLabels:()=>o,message:n});e&&u.push(e);let t=Hr({voice:d,getLabels:()=>o,message:n});t&&u.push(t)}if(Gr.has(c)){let e=y(`div`);Qn(e,n,{labels:o,features:s,title:ii(r,o),assistantName:r.profile?.assistant.name,busy:r.streaming||r.thinking});for(let t of e.children)ti(t);u.push(...e.childNodes)}let f=r.messages.some(e=>e.author.kind===`Visitor`&&e.stored);a&&c===`Assistant`&&!r.streaming&&!r.thinking&&s.Regenerate&&f&&u.push(ri(o.regenerate,`refresh`,()=>e.onRegenerate()).node);let p=Ur(r.messages);s.Edit&&p?.id===n.id&&!r.streaming&&!r.thinking&&u.push(ri(o.edit,`pencil`,()=>e.getSession().startEdit(n.id)).node),s.Rating&&n.stored&&Wr.has(c)&&u.push(te(t,n,o)),t.actions.hidden=u.length===0,t.actions.replaceChildren(...u)}function j(t){let n=C.get(t.id);if(n)return n;let r=y(`li`,`wui-chat-message`),i=y(`span`,`wui-chat-author visually-hidden`),a=y(`div`,`wui-chat-message-body`),o=y(`div`,`wui-chat-message-actions`);r.append(i,a,o);let s={li:r,author:i,body:a,actions:o,head:null,parts:[],copyTimer:void 0,ratingNote:null,mark:t.author.kind===`Assistant`?e.mark?.(`reply`,`rest`)??null:null};return C.set(t.id,s),s}function ie(e,t,n,r){let i=n?.author.kind===`Agent`&&t.author.kind===`Agent`&&(n.author.displayName??``)===(t.author.displayName??``);e.head?.remove(),e.head=t.author.kind===`Agent`&&!i?pt(t.author,r):null,e.head&&e.li.insertBefore(e.head,e.body)}function M(t,n,r,i,a,o){let{labels:s}=i;t.li.className=`wui-chat-message wui-chat-message--${n.author.kind.toLowerCase()}`,t.li.toggleAttribute(`data-restored`,n.restored===!0);let c=!o||$r(o)!==$r(n);t.li.toggleAttribute(`data-run-start`,c);let l=i.replyAvatars??`First`,u=n.author.kind===`Assistant`&&(l===`Every`||l===`First`&&c);Zr(t.li,t.body,t.mark,u,n.streaming),n.streaming?t.li.setAttribute(`aria-busy`,`true`):t.li.removeAttribute(`aria-busy`),t.author.textContent=`${ai(n,r,s)}: `,ie(t,n,o,s);let d=e.getRenderers(),f=e.getLayoutParts();typeof f==`function`?k(t,n,d,f):A(t,n,d),n.streaming?(t.actions.hidden=!0,t.actions.replaceChildren()):re(t,n,r,i,a)}function ae(e,t){let n=y(`li`,`wui-chat-message wui-chat-message--system wui-chat-message--notice`),r=y(`div`,`wui-chat-notice wui-chat-notice--${e}`,{role:e===`danger`?`alert`:`status`}),i=y(`span`,`wui-chat-notice-icon`,{"aria-hidden":`true`});i.append(o(Xr[e],16));let a=y(`div`,`wui-chat-notice-body`),s=y(`span`,`wui-chat-notice-text`);return s.textContent=t,a.append(s),r.append(i,a),n.append(r),n}function se(e,t){let n=e.resetsDateTimeUtc?` ${t.dailyLimitRefresh(x(e.resetsDateTimeUtc))}`:``;return ae(`warning`,`${e.message}${n}`)}function ce(t,n){let{labels:r}=n,i=t.turnError,a=i?.code??``;if(i&&a===`daily_limit`)return se(i,r);if(a.endsWith(`feature_off`))return ae(`danger`,t.turnError?.message||r.stopped);let s=y(`li`,`wui-chat-message wui-chat-message--system wui-chat-message--error`),c=y(`p`,`wui-chat-error`,{role:`alert`});c.textContent=t.turnError?.message||r.stopped;let l=o(`alert-circle`,16);if(l.setAttribute(`aria-hidden`,`true`),s.append(l,c),t.features.Retry){let t=y(`div`,`wui-chat-message-actions`);t.append(ri(r.retry,`rotate-ccw`,()=>e.onRetry()).node),s.append(t)}return s}function le(){return t.closest(`.wui-chat`)}function ue(){return t.closest(`.wui-chat-body`)??ei(t)}function de(e){le()?.classList.toggle(`wui-chat--scrolled`,e.scrollTop>0),Qr(e)&&(g.hidden=!0)}function fe(){_!==null&&(v=Qr(_),de(_))}function pe(e){n.nextElementSibling!==g&&n.parentNode&&n.after(g),e!==_&&(_?.removeEventListener(`scroll`,fe),_=e,e.addEventListener(`scroll`,fe,{passive:!0}),!b&&typeof ResizeObserver==`function`&&(b=new ResizeObserver(()=>{v&&_&&(_.scrollTop=_.scrollHeight)}),b.observe(t)))}h.addEventListener(`click`,()=>{let e=ue(),t=T?.context.reduced===!0;e?.scrollTo({top:e.scrollHeight,behavior:t?`auto`:`smooth`}),g.hidden=!0,h.blur()});function me(e,t){let n=e.messages[e.messages.length-1],r=n?`${n.id}|${n.parts.length}|${N(n.parts).length}`:``;if(r===w)return;let i=w===``||e.conversationId!==S;w=r,S=e.conversationId;let a=ue();a&&(pe(a),i||t||n!==void 0&&Kr.has(n.author.kind)?(a.scrollTop=a.scrollHeight,g.hidden=!0,v=!0):(g.hidden=!1,v=!1),de(a))}function he(e,a){T={state:e,context:a};let{labels:o}=a;n.setAttribute(`aria-label`,o.thread),h.textContent=o.newMessages??`New messages`;let u=ue();u&&pe(u);let g=u===null||u.clientHeight===0||Qr(u),_=[],v=/* @__PURE__ */ new Set,y=e.messages.filter(e=>!(e.streaming&&e.parts.length===0)),b=y[0],x=b!==void 0&&Kr.has(b.author.kind)&&e.greeting?e.greeting:null,S=null,w=e=>{let t=oe(e.createdDateTimeUtc,o);t!==S&&(S=t,_.push(oi(t)))};x&&b&&(w(b),p.textContent=x,Zr(d,f,m,(a.replyAvatars??`First`)!==`None`,!1),_.push(d)),y.forEach((t,n)=>{let r=j(t);v.add(t.id),w(t);let i=y[n-1]??(x?Yr:null);M(r,t,e,a,n===y.length-1,i),_.push(r.li)});for(let e of[...C.keys()])v.has(e)||C.delete(e);e.agentTyping&&_.push(mt(e.agentTyping,o)),e.thinking?(clearTimeout(l),l=void 0,i.classList.remove(`wui-chat-message--leaving`),c=!0,r.update({active:!0,mark:s,style:a.loaderStyle,steps:e.steps,phrases:a.phrases,intervalMs:a.intervalMs,reduced:a.reduced,announce:a.assistantName?.trim()?o.preparingAnswer(a.assistantName):void 0}),_.push(i)):c&&l===void 0&&!ni(a)?(i.classList.add(`wui-chat-message--leaving`),l=setTimeout(()=>{l=void 0,c=!1,i.classList.remove(`wui-chat-message--leaving`),r.update({active:!1}),T&&he(T.state,T.context)},Jr),_.push(i)):l===void 0?(c=!1,r.update({active:!1})):_.push(i),!e.streaming&&(e.turnError||e.stopped)&&_.push(ce(e,a)),ee(t,_),me(e,g)}function ge(e){return C.get(e)?.li??null}function _e(){clearTimeout(l),r.destroy(),_?.removeEventListener(`scroll`,fe),b?.disconnect(),C.clear(),T=null,n.remove()}return{el:n,paint:he,find:ge,destroy:_e}}var ci=[`launcher`,`docked`,`full-page`,`embedded`],li=[`end`,`start`],ui={steps:`Steps`,phrases:`Phrases`,orb:`Orb`,skeleton:`Skeleton`,"pulse-and-dots":`PulseAndDots`},di={on:`On`,reduced:`Reduced`},fi={still:`Still`,drift:`Drift`},pi=[`auto`,`light`,`dark`];function mi(e){return pi.find(t=>t===e)??`auto`}var hi=`wchat:muted`,gi=`wchat:open`,_i=6e4,vi=400,yi=[`labels`,`pageContext`,`compact`,`expressive`,`open`,`layoutParts`,`getCaptchaToken`,`attribution`,`openAttachment`,`openCitation`,`openTarget`,`openTicket`,`onNavigate`,`resolveLink`,`emptyContent`,`onPanelSwitch`,`preloadPanelSwitch`],bi={...mn};function xi(e,t){if(!D.includes(e))throw Error(`Unknown part kind "${e}". Use one of ${D.join(`, `)}.`);if(typeof t!=`string`||!t.includes(`-`))throw Error(`Renderer tag "${t}" must be a custom element name containing a hyphen.`)}function X(e,t){return n=>{let r=n.toLowerCase(),i=v(t,r)?t[r]:void 0;if(i===void 0)throw Error(`<wui-chat ${e}> must be one of ${Object.keys(t).join(`, `)}, got "${n}".`);return i}}function Z(e,t){return n=>{let r=Number(n),i=t===void 0?`of pixels`:`from 0 to ${t}`;if(!Number.isInteger(r)||r<0||t!==void 0&&r>t)throw Error(`<wui-chat ${e}> must be a whole number ${i}, got "${n}".`);return r}}function Q(e){return t=>{if(t===``||t===`true`)return!0;if(t===`false`)return!1;throw Error(`<wui-chat ${e}> must be true or false, got "${t}".`)}}var $=e=>e.split(`,`).map(e=>e.trim()).filter(Boolean),Si=[[`launcher-style`,`launcher`,`style`,X(`launcher-style`,{round:`Round`,pill:`Pill`,expanding:`Expanding`})],[`entrance`,`launcher`,`entrance`,X(`entrance`,{"slide-up":`SlideUp`,"bounce-in":`BounceIn`,"fade-in-pulse":`FadeInPulse`,"spin-scale":`SpinScale`,"wiggle-in":`WiggleIn`,"elastic-in":`ElasticIn`,rise:`Rise`,none:`None`})],[`idle`,`launcher`,`idle`,X(`idle`,{"float-and-pulse":`FloatAndPulse`,ring:`Ring`,none:`None`})],[`label-reveal`,`launcher`,`labelReveal`,X(`label-reveal`,{bubble:`Bubble`,expand:`Expand`})],[`compact`,`launcher`,`compact`,Q(`compact`)],[`launcher-mark`,`launcher`,`mark`,X(`launcher-mark`,{icon:`Icon`,avatar:`Avatar`,orb:`Orb`})],[`panel-height`,`panel`,`height`,X(`panel-height`,{fixed:`Fixed`,content:`Content`})],[`panel-placement`,`panel`,`placement`,X(`panel-placement`,{floating:`Floating`,side:`Side`})],[`reply-avatars`,`panel`,`replyAvatars`,X(`reply-avatars`,{none:`None`,first:`First`,every:`Every`})],[`greeting-loader-ms`,`panel`,`greetingLoaderMs`,Z(`greeting-loader-ms`)],[`panel-motion`,`panel`,`motion`,X(`panel-motion`,{spring:`Spring`,gentle:`Gentle`,none:`None`})],[`panel-width`,`panel`,`widthPx`,Z(`panel-width`)],[`panel-max-height`,`panel`,`maxHeightPx`,Z(`panel-max-height`)],[`panel-bottom-gap`,`panel`,`bottomGapPx`,Z(`panel-bottom-gap`)],[`phone-max-width`,`phone`,`maxWidthPx`,Z(`phone-max-width`)],[`phone-mode`,`phone`,`mode`,X(`phone-mode`,{"full-screen":`FullScreen`,sheet:`Sheet`})],[`sheet-height-dvh`,`phone`,`sheetHeightDvh`,Z(`sheet-height-dvh`)],[`sheet-max-height`,`phone`,`sheetMaxHeightPx`,Z(`sheet-max-height`)],[`phone-hide-launcher`,`phone`,`hideLauncher`,Q(`phone-hide-launcher`)],[`input-ring`,`input`,`ring`,Q(`input-ring`)],[`send-reveal`,`input`,`sendReveal`,X(`send-reveal`,{"on-text":`OnText`,always:`Always`})],[`send-icon`,`input`,`sendIcon`,e=>e],[`input-mark`,`input`,`mark`,X(`input-mark`,{none:`None`,avatar:`Avatar`})],[`footer-layout`,`footer`,`layout`,X(`footer-layout`,{stacked:`Stacked`,inline:`Inline`})],[`input-edge`,`input`,`edge`,X(`input-edge`,{none:`None`,gradient:`Gradient`})],[`input-placeholder`,`input`,`placeholder`,X(`input-placeholder`,{plain:`Plain`,gradient:`Gradient`})],[`input-busy-edge`,`input`,`busyEdge`,X(`input-busy-edge`,{off:`Off`,sweep:`Sweep`})],[`starters-style`,`starters`,`style`,X(`starters-style`,{chips:`Chips`,rows:`Rows`})],[`recent-rows`,`starters`,`recentRows`,Z(`recent-rows`,ee)],[`footer-disclaimer`,`footer`,`disclaimer`,X(`footer-disclaimer`,{show:`Show`,hide:`Hide`})],[`lift-selectors`,`avoid`,`liftSelectors`,$],[`menu-selectors`,`avoid`,`menuSelectors`,$],[`dark-selectors`,`avoid`,`darkSelectors`,$],[`autoopen-busy-selectors`,`avoid`,`autoOpenBusySelectors`,$],[`autoopen-optout-selector`,`avoid`,`autoOpenOptOutSelector`,e=>e]],Ci={layout:`launcher`,position:`end`,"offset-x":`24`,"offset-y":`24`,loader:`steps`,motion:`on`,icon:`chat`},wi=[`base`,`layout`,`position`,`offset-x`,`offset-y`,`loader`,`screen`,`motion`,`theme`,`icon`,`avatar`,`avatar-motion`,`narrow`,...Si.map(([e])=>e).filter(e=>e!==`compact`)],Ti=e=>e.replace(/-([a-z0-9])/g,(e,t)=>t.toUpperCase());function Ei(e){let t={launcher:{},panel:{},phone:{},input:{},avoid:{},footer:{},starters:{}};for(let[n,r,i,a]of Si){let o=e.getAttribute(n);o!=null&&(t[r][i]=a(o))}let n=e.getAttribute(`motion`),r=e.getAttribute(`avatar`),i=e.getAttribute(`avatar-motion`),a=e.getAttribute(`expressive`),o={...t,...n==null?{}:{motion:X(`motion`,di)(n)},...r?{avatar:r}:{},...i==null?{}:{avatarMotion:X(`avatar-motion`,fi)(i)},...a==null?{}:{expressive:Q(`expressive`)(a)}};return ge(o)}function Di(e){let t=e.getAttribute(`loader`)??`steps`,n=v(ui,t)?ui[t]:void 0;if(n===void 0)throw Error(`<wui-chat loader> must be one of ${Object.keys(ui).join(`, `)}, got "${t}".`);return n}function Oi(e){let t=e.getAttribute(`narrow`);if(t!=null&&t!==``)return Object.fromEntries($(t).map(e=>[e,!1]))}function ki(e){return e===hi?globalThis.localStorage:globalThis.sessionStorage}var Ai={get:e=>ki(e).getItem(e),set:(e,t)=>ki(e).setItem(e,t)};function ji(e){return globalThis.innerWidth<=e.phone.maxWidthPx}function Mi(e){let t=requestAnimationFrame(e);return()=>cancelAnimationFrame(t)}function Ni(e){return e.features.HumanHandoff===!0&&e.conversationState===`Open`&&e.messages.some(e=>e.author.kind===`Visitor`||e.author.kind===`Customer`)&&!e.streaming&&!e.thinking}function Pi(e,t){if(e.conversationState===`WaitingForAgent`)return t.statusWaitingForAgent;if(e.conversationState===`WithAgent`){let n=e.agent?.displayName;return t.statusWithAgent(typeof n==`string`&&n.trim()!==``?n:t.handoffAgentFallback)}return t.headerStatus}function Fi(e,t,n){return t.PanelSwitch!==!0||typeof n!=`function`?null:e===`docked`?`full-page`:e===`full-page`?`docked`:null}function Ii(e){if(!ci.some(t=>t===e))throw Error(`<wui-chat layout> must be one of ${ci.join(`, `)}, got "${e}".`)}function Li(e){if(!li.some(t=>t===e))throw Error(`<wui-chat position> must be one of ${li.join(`, `)}, got "${e}".`)}function Ri(e,t){let n=e[t];delete e[t],e[t]=n}function zi(e){return e==null?{}:Object(e)}var Bi=0,Vi=class extends Ne{static get observedAttributes(){return[...wi,`compact`,`expressive`,`open`,`labels`,`page-context`,`narrow`].filter((e,t,n)=>n.indexOf(e)===t)}constructor(){super(),Bi+=1,this._uid=`wui-chat-${Bi}`,this._built=!1,this._session=null,this._unsubscribe=null,this._voice=null,this._voiceConversationId=void 0,this._labelsProp=void 0,this._pageContextProp=void 0,this._layoutParts=null,this._renderers={...bi},this._rendererApi={define:(e,t)=>{xi(e,t),this._renderers[e]=t,this._render()},map:this._renderers},this._captchaToken=null,this._attribution=null,this._openAttachmentProp=null,this._openCitationProp=null,this._openTargetProp=null,this._resolveLinkProp=null,this._openTicketProp=void 0,this._emptyContentProp=null,this._onPanelSwitchProp=null,this._preloadPanelSwitchProp=null,this._preloaded=!1,this._pastList=null,this._past=null,this._pastRefreshed=!1,this._historyShown=!1,this._openedConversation=null,this._lastOpen=!1,this._openTrigger=`manual`,this._focusTimer=null,this._nudgeArmed=!1,this._seeded=!1,this._wasLoading=!1,this._seen=/* @__PURE__ */ new Set,this._sound=null,this._behaviour=null,this._autoOpen=null,this._avoid=null,this._motion=null,this._phone=null,this._requesting=!1,this._onKeyDown=e=>{e.key===`Escape`&&this._session?.getState().open&&(e.stopPropagation(),this._session.close(`escape`))}}get session(){return this._session??null}get conversationId(){return this._session?.getState().conversationId??null}get labels(){return he({...zi(c(this,`labels`)),...this._labelsProp})}set labels(e){this._labelsProp=e??void 0,this._render()}get pageContext(){return this._pageContextProp===void 0?c(this,`page-context`):this._pageContextProp}set pageContext(e){this._pageContextProp=e===null?void 0:e}get compact(){let e=this.getAttribute(`compact`);return e!=null&&Q(`compact`)(e)}set compact(e){this.toggleAttribute(`compact`,e===!0||e===``||e===`true`)}get expressive(){let e=this.getAttribute(`expressive`);return e!=null&&Q(`expressive`)(e)}set expressive(e){this.toggleAttribute(`expressive`,e===!0||e===``||e===`true`)}get open(){return this.hasAttribute(`open`)}set open(e){this.toggleAttribute(`open`,e===!0||e===``||e===`true`)}get renderers(){return this._rendererApi}get layoutParts(){return this._layoutParts}set layoutParts(e){this._layoutParts=typeof e==`function`?e:null,this._render()}get getCaptchaToken(){return this._captchaToken}set getCaptchaToken(e){this._captchaToken=typeof e==`function`?e:null}get attribution(){return this._attribution}set attribution(e){this._attribution=typeof e==`function`?e:null}get openAttachment(){return this._openAttachmentProp??(e=>this._defaultOpenAttachment(e))}set openAttachment(e){this._openAttachmentProp=typeof e==`function`?e:null}get openCitation(){return this._openCitationProp??((e,t)=>this._defaultOpenCitation(e,t))}set openCitation(e){this._openCitationProp=typeof e==`function`?e:null}get openTarget(){return this._openTargetProp??(e=>this._defaultOpenTarget(e))}set openTarget(e){this._openTargetProp=typeof e==`function`?e:null}get openTicket(){return this._openTicketProp}set openTicket(e){this._openTicketProp=typeof e==`function`?e:void 0}get onNavigate(){return this._onNavigateProp}set onNavigate(e){this._onNavigateProp=typeof e==`function`?e:void 0}get resolveLink(){return this._resolveLinkProp}set resolveLink(e){this._resolveLinkProp=typeof e==`function`?e:null}get emptyContent(){return this._emptyContentProp}set emptyContent(e){if(e!==null&&!(e instanceof Node))throw TypeError(`emptyContent must be a Node or null`);this._emptyContentProp=e,this._applyEmptyContent()}get onPanelSwitch(){return this._onPanelSwitchProp}set onPanelSwitch(e){this._onPanelSwitchProp=typeof e==`function`?e:null}get preloadPanelSwitch(){return this._preloadPanelSwitchProp}set preloadPanelSwitch(e){this._preloadPanelSwitchProp=typeof e==`function`?e:null}connectedCallback(){this._adoptEarlyProperties();let e=this._assertLayout();if(this._assertPosition(),this.base.trim()===``)throw TypeError(`<wui-chat> needs a base path, e.g. base="/api/assistant".`);this._built||this._build(),this._shell||this._buildShell(e),this._session||this._createSession(),this._past||this._createPast(),this._unsubscribe||=this.requireSession().subscribe(()=>this._render()),this._render()}_adoptEarlyProperties(){for(let e of yi)v(this,e)&&Ri(this,e)}disconnectedCallback(){this._voice?.stop(),this._session?.stop(),this._unsubscribe?.(),this._unsubscribe=null,this._disposePast(),this._shell?.destroy?.(),document.removeEventListener(`keydown`,this._onKeyDown),this._avoid?.destroy(),this._avoid=null,this._autoOpen?.cancel(),this._autoOpen=null,this._motion?.destroy(),this._motion=null}attributeChangedCallback(e,t,n){if(this._built&&t!==n){if(e===`layout`)this._buildShell(this._assertLayout());else if(e===`position`)this._assertPosition();else if(e===`base`||e===`screen`||e===`narrow`)this._resetSession();else if(e===`motion`)this._motion?.destroy(),this._motion=null;else if(e===`open`&&this._session){let e=this._session.getState().open;this.open!==e&&this._setOpen(this.open,`manual`)}this._render()}}toggle(){this._session&&(this._session.getState().open?this._session.close(`button`):this._setOpen(!0,`manual`))}close(){this._voice?.stop(),this._session?.close(`button`)}newConversation(){this._voice?.stop(),this._session?.newConversation(),this._past?.refresh()}reset(){this._voice?.stop(),this._session?.reset()}_setOpen(e,t){this._session&&(e?(this._openTrigger=t,this._session.open({trigger:t})):this._session.close(`button`))}_assertLayout(){let e=this.layout;return Ii(e),e}_assertPosition(){Li(this.position)}get _position(){let e=this.position;return Li(e),e}_isLauncherLike(){return this.layout===`launcher`||this.layout===`docked`}requireSession(){if(!this._session)throw TypeError(`wui-chat: _session is not ready; the element is not connected`);return this._session}requireVoice(){if(!this._voice)throw TypeError(`wui-chat: _voice is not ready; the element is not connected`);return this._voice}requireMotion(){if(!this._motion)throw TypeError(`wui-chat: _motion is not ready; the element is not connected`);return this._motion}requirePastList(){if(!this._pastList)throw TypeError(`wui-chat: _pastList is not ready; the element is not connected`);return this._pastList}requireNudgeHost(){if(!this._shell.nudgeHost)throw TypeError(`wui-chat: the launcher shell has no nudge host`);return this._shell.nudgeHost}_build(){this._built=!0,this._markMaker=t(n(this)),this._header=Pn({onNew:()=>this.newConversation(),onHistory:()=>this._toggleHistory(),onClose:()=>this.close(),onMute:()=>{this._session&&this._session.setMuted(!this._session.getState().muted)},onSwitch:()=>this._switchPanel(),titleId:`${this._uid}-title`,mark:this._markMaker}),this._starters=Er({mark:this._markMaker,onStarter:e=>this.requireSession().submit(e.message),onResume:()=>this.requireSession().resumeLast(),onTicket:e=>{typeof this.openTicket==`function`&&this.openTicket({ticketId:e.ticketId,number:e.number})},onOpenConversation:e=>{Promise.allSettled([this.requireSession().openConversation(e)])}}),this._applyEmptyContent(),this._voice=xn({getState:()=>this.requireSession().getState(),getToken:()=>this.requireSession().client.getSpeechToken()}),this._voice.subscribe(()=>this._render()),this._thread=si({mark:this._markMaker,getRenderers:()=>this._renderers,getLayoutParts:()=>this._layoutParts,makeTurnApi:e=>this._makeTurnApi(e),onRetry:()=>this.requireSession().retry(),onRegenerate:()=>this.requireSession().regenerate(),onRate:(e,t)=>this.requireSession().rate(e,t),getSession:()=>this.requireSession(),getVoice:()=>this._voice}),this._composer=kn({mark:this._markMaker,voice:this._voice,onSubmit:e=>this.requireSession().submit(e),onStop:()=>this.requireSession().stop(),onAttach:e=>this.requireSession().attach(e),onRemove:e=>this.requireSession().removeAttachment(e),onCancelEdit:()=>this.requireSession().cancelEdit(),onTyping:()=>this.requireSession().notifyTyping(),onDraftApplied:()=>this.requireSession().consumeDraft()}),this._footer=Nn(),this._history=In({getClient:()=>this.requireSession().client,getLabels:()=>this.labels,getFeatures:()=>this.requireSession().getState().features,onOpen:e=>{Promise.allSettled([this.requireSession().openConversation(e)]),this._toggleHistory(!1)},onDeleted:e=>{e===this.conversationId&&this.requireSession().newConversation()}}),this._nudge=Hn({onActivate:()=>this._setOpen(!0,`manual`),onDismiss:()=>{}}),this._status=y(`p`,null,{role:`status`}),this._status.hidden=!0,this._errorEl=y(`p`,`wui-chat-profile-error`,{role:`alert`}),this._errorEl.hidden=!0,this._liveStatus=y(`p`,`wui-chat-live-status`,{role:`status`}),this._liveStatus.hidden=!0,this._talk=y(`button`,`${u(`outline`,`sm`)} wui-chat-handoff-request`,{type:`button`}),this._talk.addEventListener(`click`,()=>this._requestHandoff()),this._liveRetry=y(`button`,u(`ghost`,`sm`),{type:`button`}),this._liveRetry.addEventListener(`click`,()=>this.requireSession().resumeLive()),this._liveError=y(`p`,`wui-chat-live-error`,{role:`alert`}),this._liveError.hidden=!0,this._live=y(`div`,`wui-chat-live`),this._live.append(this._liveStatus,this._talk,this._liveRetry,this._liveError),this._live.hidden=!0,this._body=y(`div`,`wui-chat-body`),this._body.append(this._starters.el,this._thread.el,this._live,this._history.el,this._status,this._errorEl),this._foot=y(`div`,`wui-chat-foot`),this._foot.append(...this._composer.nodes,this._footer.el)}_buildShell(e){let t={launcher:yr,docked:mr,"full-page":br,embedded:hr};this._shell?.destroy?.(),this._avoid?.destroy(),this._avoid=null,this._autoOpen?.cancel(),this._autoOpen=null,this._lastOpen=!1,this._serverLauncher=this.querySelector(`:scope > [data-wui-chat-placeholder]`),this._launcherPlayed=this._serverLauncher!==null;let n=t[e]({mark:this._markMaker,id:`${this._uid}-panel`,position:this._position,onToggle:()=>this.toggle()});if(n.panel.append(this._header.el,this._body,this._foot),n.panel.setAttribute(`aria-labelledby`,`${this._uid}-title`),n.panel.addEventListener(`keydown`,e=>{e.key===`Tab`&&b(n.panel,e)}),n.nudgeHost&&n.nudgeHost.prepend(this._nudge.el),this._shell=n,this._serverLauncher===null)this.replaceChildren(n.root);else{for(let e of[...this.childNodes])e!==this._serverLauncher&&e.remove();n.root.hidden=!0,this.append(n.root)}}_createSession(){let e=ne(Vn(),{base:this.base}),t=Oi(this);this._session=re(e,{...this.screen?{screen:this.screen}:{},...t===void 0?{}:{narrow:t},recentConversations:Ei(this).starters.recentRows,pageContext:()=>this.pageContext,attribution:()=>this._attribution?.()??null,behaviour:()=>this._session?.getState().features.BehaviourStarters?this._behaviour?.()??null:null,prefs:Ai,reducedMotion:()=>this._motion?.reduced??!1,schedule:Mi,getCaptchaToken:e=>{if(this._captchaToken)return this._captchaToken(e);let t=this._session?.getState().profile?.captcha?.siteKey;return t?Yn(t,e):Promise.resolve(null)},onEvent:(e,t)=>{this.dispatchEvent(new CustomEvent(`wui-chat-event`,{bubbles:!0,detail:{name:e,data:t}}))},onError:()=>{},labels:this.labels}),this._unsubscribe=null,this._lastOpen=!1,this._openApplied=!1,this._seeded=!1,this._wasLoading=!1,this._seen=/* @__PURE__ */ new Set,this._pastRefreshed=!1}_createPast(){this._pastList=j({client:this.requireSession().client,pageSize:20}),this._past=Wn({list:this._pastList,getLabels:()=>this.labels,getFeatures:()=>this.requireSession().getState().features,onOpen:e=>{Promise.allSettled([this.requireSession().openConversation(e)])}}),this._starters.pastHost.append(this._past.el)}_disposePast(){this._past&&(this._past.el.remove(),this._past.dispose(),this.requirePastList().dispose(),this._past=null,this._pastList=null)}_applyEmptyContent(){if(!this._starters)return;let e=this._starters.extraHost;e.replaceChildren(...this._emptyContentProp?[this._emptyContentProp]:[]),e.hidden=!this._emptyContentProp}_switchPanel(){let e=this.requireSession().getState(),t=this._onPanelSwitchProp,n=Fi(this.layout,e.features,t);if(t===null||n===null)return;n===`full-page`&&this.close();let r={from:this.layout,to:n,conversationId:e.conversationId,draft:this._composer.getDraft()};T(()=>t.call(this,r),{target:n,reduced:this._motion?.reduced===!0}).then(()=>document.querySelector(`.wui-chat--${n} .wui-chat-input`)?.focus()).catch(e=>globalThis.reportError?.(e))}async _requestHandoff(){this._requesting=!0,this._liveError.hidden=!0,this._render();try{await this.requireSession().requestHandoff()}catch(e){let t=typeof e==`object`&&e&&`message`in e?e.message:void 0;this._liveError.textContent=typeof t==`string`&&t||this.labels.errorGeneric,this._liveError.hidden=!1}finally{this._requesting=!1,this._render()}}_paintLive(e,t,n){let r=e.live===`Lost`,i=Ni(e);this._liveStatus.hidden=!r,this._liveStatus.textContent=r?t.liveLost:``,this._liveRetry.hidden=!r,this._liveRetry.textContent=t.retry,this._talk.hidden=!i,this._talk.textContent=t.talkToPerson,this._talk.disabled=this._requesting,this._live.hidden=n||!r&&!i}_resetSession(){this._voice?.stop(),this._unsubscribe?.(),this._unsubscribe=null,this._session?.dispose(),this._session=null,this._disposePast(),this._history.dispose(),this.isConnected&&(this._createSession(),this._createPast(),this._unsubscribe=this.requireSession().subscribe(()=>this._render()))}_toggleHistory(e=!this._historyShown){this._historyShown=e,e?this._history.show():this._history.hide(),this._render()}_makeTurnApi(e){let t=ie(this.requireSession(),{messageId:e,labels:this.labels,openAttachment:e=>this.openAttachment(e),openCitation:t=>this.openCitation(e,t),openTarget:e=>this.openTarget(e),openTicket:this.openTicket,onNavigate:this.onNavigate});return t.resolveLink=this.resolveLink,t}_defaultOpenAttachment(e){this.requireSession().client.getAttachment(e.attachmentId).then(t=>{let n=URL.createObjectURL(new Blob([t],{type:e.contentType}));window.open(n,`_blank`,`noopener`),setTimeout(()=>URL.revokeObjectURL(n),_i)}).catch(e=>globalThis.reportError?.(e))}_defaultOpenCitation(e,t){let n=this._thread.find(e);if(n){for(let e of n.querySelectorAll(`[data-marker]`))if(e.dataset.marker===String(t)){e.focus();return}}}_defaultOpenTarget(e){/^https?:\/\//i.test(e)?window.open(e,`_blank`,`noopener`):window.location.assign(e)}_render(){this._built&&this._session&&this._paint(this._session.getState())}_paint(e){this._shell.root.toggleAttribute(`data-busy`,e.streaming||e.thinking),e.conversationId!==this._voiceConversationId&&(this._voiceConversationId=e.conversationId,this.requireVoice().stop());let t=this.labels,n=e.profile,r=this._isLauncherLike();if(!n){this.hidden=r&&(this._serverLauncher===null||e.profileError!=null),this._header.el.hidden=!0,this._starters.el.hidden=!0,this._thread.el.hidden=!0,this._history.el.hidden=!0,this._foot.hidden=!0,this._errorEl.hidden=e.profileError==null,e.profileError&&(this._errorEl.textContent=e.profileError.message),this._status.hidden=e.profileError!=null,this._status.textContent=t.loadingConversation,this._shell.panel.setAttribute(`aria-busy`,String(e.profileError==null));return}if(this._shell.panel.removeAttribute(`aria-busy`),!e.features.VisitorChat){this.hidden=!0,this._status.hidden=!0;return}this.hidden=!1;let i=e.features,a=Ei(this);this._ensureRuntime(e,n,a,t);let o=e.loading,s=e.loadError,c=e.messages.length===0&&!o,l=this._historyShown&&i.History===!0,u=e.messages.some(e=>e.author.kind===`Visitor`||e.author.kind===`Customer`),d=Fi(this.layout,i,this._onPanelSwitchProp),f=e.streaming||e.thinking;this._header.paint({labels:t,title:t.panelTitle||n.assistant.name||t.assistant,tagline:n.assistant.tagline,status:Pi(e,t),canNew:!f,showNew:this.layout===`full-page`||u,showHistory:i.History,showClose:r||this.layout===`full-page`&&d!==null,switchTo:d,canSwitch:!f,viewingHistory:l,showMute:i.Sounds&&n.experience.sound.muteControl,muted:e.muted}),$n(this._header.conversation,e,{labels:t,features:i,title:n.assistant.name||t.assistant,getState:()=>this.requireSession().getState(),iconOnly:!0}),l&&(this._header.conversation.hidden=!0),this._starters.el.hidden=!c||l,c&&e.open&&!this._introPlayed&&a.panel.greetingLoaderMs>0&&!this.requireMotion().reduced&&(this._introPlayed=!0,this._starters.intro(a.panel.greetingLoaderMs)),c&&this._starters.paint({labels:t,greeting:e.greeting,intro:n.assistant.intro,starters:e.starters,showStarters:i.Starters&&!e.streaming,resume:!i.History&&i.ResumeLast?e.lastConversation:null,recent:e.recentConversations,openTickets:e.openTickets,features:e.features,ticketsClickable:typeof this.openTicket==`function`}),i.History&&!this._pastRefreshed&&(this._pastRefreshed=!0,this._past?.refresh()),this._past?.paint(),this._starters.pastHost.hidden=e.recentConversations.length>0;let p=!c&&!o&&!s&&!l;this._thread.el.hidden=!p,p&&this._thread.paint(e,{labels:t,loaderStyle:Di(this),reduced:this._motion?.reduced??!1,phrases:n.experience.pacing.thinkingPhrases,intervalMs:n.experience.pacing.phraseIntervalMs,assistantName:n.assistant.name,replyAvatars:a.panel.replyAvatars}),this._paintLive(e,t,l),this._status.hidden=!o||l,this._status.textContent=t.loadingConversation,this._errorEl.hidden=!s||l,s&&(this._errorEl.textContent=s.message),this._foot.hidden=l,this._composer.paint({state:e,labels:t,maxLength:n.limits.maxMessageLength,accept:n.limits.contentTypes.join(`,`),draft:e.draft??null,sendIcon:a.input.sendIcon,inputMark:a.input.mark,busy:e.streaming||e.thinking}),this._footer.paint({labels:t,profile:n,hideDisclaimer:a.footer.disclaimer===`Hide`}),this._history.el.hidden=!l,this._syncOpen(e,n,i,t,r),this._syncConversation(e),this._playSounds(e)}_ensureRuntime(e,t,n,r){let a=e.features;this._motion||(this._motion=i(n,t.experience),this._motion.subscribe(()=>this._render())),a.Sounds&&!this._sound&&(this._sound=f(t.experience.sound,Ai)),!a.Sounds&&this._sound&&(this._sound=null),a.BehaviourStarters&&!this._behaviour&&(this._behaviour=h(t.start.behaviour?.servicePathPrefixes??[]));let o=this._isLauncherLike();o&&!this._avoid&&this.layout===`launcher`&&(this._avoid=g(n.avoid,t.experience.launcher,this.requireNudgeHost(),this._shell.setLauncherState)),this.layout===`launcher`&&a.AutoOpen&&!this._autoOpen&&(this._autoOpen=w(t.experience.autoOpen,n,{open:()=>this._setOpen(!0,`auto`),isOpen:()=>this.requireSession().getState().open,panelRect:()=>this._shell.panel.getBoundingClientRect()}));let s=ji(n);this._shell.setLabels(r),this._shell.setAppearance({position:this._position,offsetX:this.hasAttribute(`offset-x`)?Z(`offset-x`)(this.getAttribute(`offset-x`)??``):void 0,offsetY:this.hasAttribute(`offset-y`)?Z(`offset-y`)(this.getAttribute(`offset-y`)??``):void 0,width:`${n.panel.widthPx}px`,maxHeight:n.panel.maxHeightPx,bottomGap:n.panel.bottomGapPx,reduced:this._motion.reduced,sendReveal:n.input.sendReveal,inputRing:n.input.ring,panelMotion:n.panel.motion,theme:mi(this.getAttribute(`theme`)),icon:this.icon,launcherStyle:n.launcher.style,compact:n.launcher.compact,labelReveal:n.launcher.labelReveal,entrance:n.launcher.entrance,idle:n.launcher.idle,launcherMark:n.launcher.mark,panelHeight:n.panel.height,panelPlacement:n.panel.placement,inputMark:n.input.mark,inputEdge:n.input.edge,inputBusyEdge:n.input.busyEdge,inputPlaceholder:n.input.placeholder,phoneHideLauncher:n.phone.hideLauncher,replyAvatars:n.panel.replyAvatars,footerLayout:n.footer.layout,startersStyle:n.starters.style,avatar:n.avatar,avatarMotion:n.avatarMotion,expressive:n.expressive,phone:s,hoverLabel:t.experience.launcher.hoverLabel,peek:t.experience.launcher.peek,peekSeconds:t.experience.launcher.peekSeconds,hideWhileOpen:t.experience.launcher.hideWhileOpen,phoneMode:n.phone.mode,sheetHeightDvh:n.phone.sheetHeightDvh,sheetMaxHeightPx:n.phone.sheetMaxHeightPx,launcherState:this._launcherPlayed?void 0:`entering`}),this._adoptServerLauncher(),this._launcherPlayed=!0,this._shell.root.classList.toggle(`wui-chat--phone`,o&&ji(n))}_adoptServerLauncher(){let t=this._serverLauncher;if(t===null)return;this._serverLauncher=null;let n=t.querySelector(`.wui-chat-launcher-wrap`),r=n===null?null:e(n);t.remove(),this._shell.root.hidden=!1,r!==null&&this._shell.resumeEntrance(r)}_syncOpen(e,t,n,r,i){if(i){if(!this._openApplied&&(this._openApplied=!0,this.hasAttribute(`open`)&&!e.open))this._setOpen(!0,`manual`);else if(this._shell.setOpen(e.open),this.toggleAttribute(`open`,e.open),e.open!==this._lastOpen&&(this._lastOpen=e.open,Ai.set(gi,e.open?`1`:`0`),this._onOpenChange(e.open)),e.open)this._nudge.cancel(),this._nudgeArmed=!1,this._autoOpen?.cancel();else if(n.Nudges&&this.layout===`launcher`&&!this._nudgeArmed){let e=_e(t,n);e&&(this._nudge.schedule({text:e.text,delaySeconds:e.delaySeconds,label:r.nudgeDismiss}),this._nudgeArmed=!0)}}}_onOpenChange(e){let t=ji(Ei(this));if(e){if(document.addEventListener(`keydown`,this._onKeyDown),this._sound?.play(`open`),this._past?.refresh(),this.layout===`docked`&&!this._preloaded&&typeof this._preloadPanelSwitchProp==`function`){this._preloaded=!0;let e=this._preloadPanelSwitchProp;Promise.allSettled([new Promise(t=>t(e.call(this)))]).then(e=>{for(let t of e)t.status===`rejected`&&globalThis.reportError?.(t.reason)})}if(t){let e=Ei(this);this._phone={fit:S(this._shell.panel,e),unlock:C(this._thread.el)}}else this._openTrigger===`manual`&&(this._focusTimer=setTimeout(()=>{this._focusTimer=null,this._composer.focus()},vi))}else document.removeEventListener(`keydown`,this._onKeyDown),clearTimeout(this._focusTimer??void 0),this._focusTimer=null,this._phone?.fit.destroy(),this._phone?.unlock(),this._phone=null,this._historyShown&&(this._historyShown=!1,this._history.hide(),this._render()),m(this._shell.launcherButton)}_syncConversation(e){let t=this.getAttribute(`conversation-id`);t&&t!==this._openedConversation&&!e.loading&&(this._openedConversation=t,e.conversationId!==t&&Promise.allSettled([this.requireSession().openConversation(t)]))}_playSounds(e){if(e.loading){this._wasLoading=!0;for(let t of e.messages)this._seen.add(t.id)}else if(this._wasLoading||!this._seeded){this._wasLoading=!1,this._seeded=!0;for(let t of e.messages)this._seen.add(t.id)}else for(let t of e.messages)this._seen.has(t.id)||(this._seen.add(t.id),this._announce(t))}_announce(e){if(!this._sound||e.restored||e.parts.some(e=>e.kind===`Notice`))return;let t=e.author.kind;if(t===`Visitor`)e.stored||this._sound.play(`sent`);else if(t===`Assistant`||t===`Script`||t===`Agent`){this._sound.play(`reply`);let e=this.requireSession().getState().profile;e?.experience.sound.vibrate&&E(e.experience.sound.vibrateMs,this._sound.isMuted())}}};Object.defineProperty(Vi.prototype,"layout",{get(){return this.getAttribute(`layout`)??Ci.layout},set(e){this.setAttribute(`layout`,String(e))}});for(let e of wi)e!==`layout`&&Object.defineProperty(Vi.prototype,Ti(e),{configurable:!0,get(){return this.getAttribute(e)??Ci[e]??``},set(t){t==null?this.removeAttribute(e):this.setAttribute(e,String(t))}});function Hi(){typeof customElements<`u`&&!customElements.get(`wui-chat`)&&customElements.define(`wui-chat`,Vi)}Hi();export{Vi as WuiChat,Vn as createFetchChatHttp,mn as defaultRenderers,Hi as defineChat};
|