@sendbird/ai-agent-messenger-react 1.37.0 → 1.38.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +104 -104
- package/dist/index.d.ts +101 -5
- package/dist/index.js +4312 -4216
- package/package.json +2 -2
package/dist/index.cjs
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
"use strict";var cc=Object.defineProperty;var lc=(e,t,n)=>t in e?cc(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var v=(e,t,n)=>lc(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Ce=require("@sendbird/chat"),l=require("react"),B=require("styled-components"),it=require("date-fns"),uc=require("date-fns/locale/en-US"),De=require("@sendbird/chat/message"),ge=require("@sendbird/chat/aiAgent"),dc=require("react-dom"),je=require("@sendbird/chat/groupChannel"),mc=require("date-fns/isSameDay"),hc=require("dompurify"),Ir=e=>e&&e.__esModule?e:{default:e};function fc(e){if(e&&e.__esModule)return e;const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const gc=Ir(Ce),a=fc(l),_=Ir(B),Vo=Ir(hc),qo=e=>{try{return JSON.parse(e===""?"{}":e)}catch{return{}}},pc=e=>{const t=qo(e);return typeof t=="object"&&t!==null?t:{}},Ko=e=>typeof e=="string"?pc(e):e??{},_c=e=>!!Ko(e).stream,ms=e=>{if(typeof e=="number"&&Number.isSafeInteger(e)&&e>0)return e;if(typeof e!="string"||e.trim().length===0)return;const t=Number(e);return Number.isSafeInteger(t)&&t>0?t:void 0},Yo=e=>{const t=Ko(e),n=ms(t.user_message_id)??ms(t.respond_mesg_id);return{isStreaming:!!t.stream,hasResponseMetadata:Object.prototype.hasOwnProperty.call(t,"stream")||n!==void 0,...n!==void 0&&{userMessageId:n}}},Ct="sb-agent",Wo="KEY_IMG_ASPECT_RATIO",cr="*/*",se={BODY_MAX_WIDTH:244,WIDE_BODY_MAX_WIDTH:640,AVATAR_SIZE:26,BODY_TIME_GAP:4,HORIZONTAL_PADDING:12,GAP_GROUPED:2,GAP_UNGROUPED:16};var _n=(e=>(e.IN_PROGRESS="IN_PROGRESS",e.COMPLETED="COMPLETED",e.CANCELED="CANCELED",e))(_n||{}),Bt=(e=>(e.IN_PROGRESS="IN_PROGRESS",e.COMPLETED="COMPLETED",e.CANCELED="CANCELED",e))(Bt||{});const Ec=e=>!!(e!=null&&e.cta_button),Cc=e=>{var t;return!!((t=e==null?void 0:e.citations)!=null&&t.length)},jo=e=>!!(e!=null&&e.form)&&!e.form.canceled_at,bc=e=>{var t;return jo(e)&&!((t=e==null?void 0:e.form)!=null&&t.submitted_at)},vc=e=>{var t;return!!((t=e==null?void 0:e.suggested_replies)!=null&&t.length)},ze=e=>{let t;return{enumerable:!0,get:()=>(t??(t=e()),t)}},qt=e=>Object.defineProperties({},{hasMessageTemplate:ze(()=>!!(e!=null&&e.message_template)),hasCTAButton:ze(()=>Ec(e)),hasChallenge:ze(()=>!!(e!=null&&e.challenge)),isThinking:ze(()=>!!(e!=null&&e.is_thinking)),hasCSAT:ze(()=>!!(e!=null&&e.csat)),hasSuggestedReplies:ze(()=>vc(e)),hasCustomMessageTemplates:ze(()=>{var t;return!!((t=e==null?void 0:e.custom_message_templates)!=null&&t.length)}),hasForm:ze(()=>jo(e)),hasActiveForm:ze(()=>bc(e)),hasSteward:ze(()=>!!(e!=null&&e.steward)),hasCitations:ze(()=>Cc(e))}),Sc=e=>{const t=qt(e);return t.hasMessageTemplate||t.hasCTAButton||t.hasCSAT||t.hasSuggestedReplies||t.hasForm||t.hasSteward||t.hasCitations},Xo=e=>{var t;return!!((t=e==null?void 0:e.extendedMessagePayload)!=null&&t.steward)},yc=e=>e===Bt.COMPLETED||e===Bt.CANCELED?e:Bt.IN_PROGRESS,Vn=e=>Ze(e)&&!Xo(e),Ze=e=>!!e&&"sender"in e,Ac=e=>Ze(e)?e.sendingStatus==="succeeded"?String(e.messageId):e.reqId:String(e.messageId),Tc=(e,t,n,r=!0)=>{if(!r||!Vn(e))return"single";const s=()=>{if(!Vn(t))return!1;const u=t.sender.userId===e.sender.userId,d=it.isSameMinute(t.createdAt,e.createdAt);return u&&d},o=()=>{if(!Vn(n))return!1;const u=n.sender.userId===e.sender.userId,d=it.isSameMinute(n.createdAt,e.createdAt);return u&&d},i=s(),c=o();return i&&c?"middle":i?"bottom":c?"top":"single"},rt=(e,t)=>(()=>{var r;return Ze(e)?e.sender.userId:((r=e==null?void 0:e.sender)==null?void 0:r.userId)??void 0})()===t,Oe={isAdmin:e=>e.isAdminMessage(),isCSAT:e=>{var t;return e.isAdminMessage()&&!!((t=e.extendedMessagePayload)!=null&&t.csat)},isSteward:e=>Xo(e),isIncoming:(e,t)=>Ze(e)&&e.sender.userId!==t,isOutgoing:(e,t)=>Ze(e)&&(e.sender.userId===t||e.sendingStatus===De.SendingStatus.PENDING)},Ve=e=>e.startsWith("image/"),Kt=e=>e.startsWith("video/"),Ic=e=>e.startsWith("audio/"),Zo=({name:e="",mimeType:t=""})=>t==="application/pdf"||/\.pdf$/i.test(e.trim()),xr=(e,t)=>{if(e&&!e.startsWith(".")){const n=e.split(".").pop();if(n&&n!==e)return n.toUpperCase()}if(t){const[,n]=t.split("/");if(n)return n.toUpperCase()}return"FILE"},Jo=e=>{var t;return e.messageType==="file"?e.message.length>0&&e.file.name!==e.message:e.messageType==="multipleFiles"?e.message.length>0&&((t=e.files[0])==null?void 0:t.name)!==e.message:e.message.length>0},xc=e=>{if(e.message&&e.message.trim().length>0)return!0;const t=e.extendedMessagePayload;return Sc(t)},xn=e=>{switch(e){case"top":case"middle":return se.GAP_GROUPED;default:return se.GAP_UNGROUPED}},Rc=(e,t)=>{const n=/```(\w+)?\n([\s\S]*?)```/g,r=[];let s=0;return e.replace(n,(o,...i)=>{const[c,u,d]=i;return s<d&&r.push({type:"text",value:e.slice(s,d).trim()}),r.push({type:"code",value:u.trim(),language:c?c.trim():"plaintext"}),s=d+o.length,o}),s<e.length&&r.push({type:"text",value:e.slice(s).trim()}),t?r.map(o=>o.type!=="text"?o:{...o,value:t(o.value)}):r},Mc=e=>e.replace(/\[([^\]]+)\](?!\()/g,"\\[$1\\]"),wc=e=>e.replace(/([a-zA-Z0-9])_(?=[a-zA-Z0-9])/g,"$1\\_"),kc=e=>e.replace(/~~/g,"\\~\\~"),Lc=e=>{let t=e;return t=Mc(t),t=wc(t),t=kc(t),t},Oc=typeof navigator<"u"&&navigator.product==="ReactNative",hs=(e,t)=>{const n=r=>!t||t.length===0?!0:Ze(r)&&t.includes(r.sendingStatus);return Oc?e.find(n):e.findLast(n)},xe=e=>{requestAnimationFrame(()=>{requestAnimationFrame(e)})};function fe(){}function Nc(){const e=typeof navigator<"u"?navigator.userAgent:"",t=/iPad|iPhone|iPod/.test(e),n=/Android/.test(e);return t||n}function Dc(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return t.toString(16)}const we={isStreaming(e){return _c(e.data)},isExplicitWelcomeMessage(e){var t;return((t=e.extendedMessagePayload)==null?void 0:t.bot_message_type)==="welcome"},isWelcomeMessage(e,t){var r;if(we.isExplicitWelcomeMessage(e))return!0;if(((r=e.extendedMessagePayload)==null?void 0:r.bot_message_type)!==void 0||!rt(e,t))return!1;const n=Yo(e.data);return!n.isStreaming&&!n.hasResponseMetadata},isGeneratedMessage(e){var t;return((t=e.extendedMessagePayload)==null?void 0:t.bot_message_type)==="generated"},hasFeedback(e){var t;return!!((t=e.extendedMessagePayload)!=null&&t.feedback)}},qn=`@${Ct}`,$c=({appId:e,aiAgentId:t,storage:n})=>{const r={templateBase:`${qn}-template`,template:s=>`${r.templateBase}/templates/${s}`,templateToken:()=>`${r.templateBase}/tokens`,messengerSession:s=>{const o=Dc(`${e}/${t}/${s}`);return`${qn}-udata/${o}`},anonUserSession:()=>`${qn}-session/${e}/${t}`};return{template:{set:(s,o)=>n.set(r.template(s),o),get:s=>n.get(r.template(s)),setCachedToken:s=>n.set(r.templateToken(),s),getCachedToken:()=>n.get(r.templateToken()),clear:()=>{n.getKeys(r.templateBase).forEach(n.delete)}},messenger:{getSettings:s=>{try{const o=n.get(r.messengerSession(s));return o?JSON.parse(o):null}catch{return null}},setSettings:(s,o)=>{try{delete o.auto_created_user;const i=JSON.stringify(o);n.set(r.messengerSession(s),i)}catch{return}},getAnonUser:()=>{try{const s=n.get(r.anonUserSession());return s?JSON.parse(s):null}catch{return null}},setAnonUser:s=>{try{const o=JSON.stringify(s);n.set(r.anonUserSession(),o)}catch{return}},clear:s=>{try{s&&n.delete(r.messengerSession(s)),n.delete(r.anonUserSession())}catch{return}}}}},Qo=(e,t,n={})=>{let r=null,s=null,o=null;const{leading:i=!0,trailing:c=!0}=n,u=(...d)=>{const m=Date.now();if(o===null||m-o>=t)i?(e(...d),o=m):(s=d,o=m);else if(s=d,c&&!r){const h=t-(m-o);r=setTimeout(()=>{s&&c&&(e(...s),o=Date.now()),r=null,s=null},h)}};return u.cancel=()=>{r&&(clearTimeout(r),r=null),s=null,o=null},u},Pc=()=>{let e=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const n=(e+Math.random()*16)%16|0;return e=Math.floor(e/16),(t==="x"?n:n&3|8).toString(16)})};class Fc{constructor(t){v(this,"_params");this._params={aiAgentChannelFilter:(t==null?void 0:t.aiAgentChannelFilter)??ge.AIAgentChannelFilter.INCLUDE,aiAgentConversationStatusFilter:(t==null?void 0:t.aiAgentConversationStatusFilter)??[ge.ConversationStatus.OPEN,ge.ConversationStatus.CLOSED],aiAgentIds:(t==null?void 0:t.aiAgentIds)??[],deskChannelFilter:(t==null?void 0:t.deskChannelFilter)??ge.DeskChannelFilter.INCLUDE,pinnedChannelUrls:(t==null?void 0:t.pinnedChannelUrls)??[],copilotConversationOnly:(t==null?void 0:t.copilotConversationOnly)??!1,copilotSupportChannelUrl:t==null?void 0:t.copilotSupportChannelUrl}}get params(){return{...this._params}}match(t,n){const{pinnedChannelUrls:r,aiAgentChannelFilter:s,aiAgentConversationStatusFilter:o,aiAgentIds:i,deskChannelFilter:c}=this._params;return r!=null&&r.includes(t.url)?!0:t.isAIAgent?!(!t.conversation||s===ge.AIAgentChannelFilter.EXCLUDE||i&&i.length>0&&!i.includes(t.conversation.aiAgentId)||o&&o.length>0&&!o.some(d=>{var m;return((m=t.conversation)==null?void 0:m.status)===d})):t.isDesk?c!==ge.DeskChannelFilter.EXCLUDE:!1}}class ei extends je.BaseChannelCollection{constructor(n,r){const s=new Fc(r.filter),o=n,i=o.aiAgent._manager,c=r.limit??20,u=je.GroupChannelListOrder.LATEST_LAST_MESSAGE,d={getRemoteChannels:(m,h,f,g)=>i.getMyGroupChannels(m,h.params,g),changeLogSync:m=>{const{aiAgentChannelFilter:h,aiAgentIds:f,deskChannelFilter:g,pinnedChannelUrls:C,copilotConversationOnly:b,copilotSupportChannelUrl:S}=s.params,p={aiAgentChannelFilter:h,aiAgentIds:f,deskChannelFilter:g,pinnedChannelUrls:C,copilotConversationOnly:b,copilotSupportChannelUrl:S};return i.getMyGroupChannelChangeLogs(m,p,je.GroupChannelEventSource.SYNC_CHANNEL_CHANGELOGS)}};super(o.aiAgent._iid,{filter:s,order:u,limit:c,syncKeyPrefix:"aiAgent",fetcher:d});v(this,"_params");v(this,"_sdk");v(this,"_throttledOnChannelChanged");v(this,"_key");v(this,"_pendingChannels",[]);this._sdk=n,this._params=r,this._key=`clc-${Pc()}`,this._throttledOnChannelChanged=Qo(()=>{var g;const m=[...this._pendingChannels];this._pendingChannels=[];const h=new Map;for(const{channel:C,context:b}of m)h.delete(C.url),h.set(C.url,{channel:C,context:b});const f=new Map;for(const{channel:C,context:b}of h.values())f.has(b)||f.set(b,new Map),f.get(b).set(C.url,C);for(const[C,b]of f){const S=Array.from(b.values()),p=(g=this._sdk.currentUser)==null?void 0:g.userId,A=S.filter(T=>this.filter.match(T,p)),y=S.filter(T=>!this.filter.match(T,p)).map(T=>T.url);A.length>0&&this._base._addChannelsToView(A,C,!1),y.length>0&&this._removeChannels(y,C)}},250,{trailing:!0,leading:!0}),this._base._subscribeChannelEvent(this._key,{onUpdate:(m,h)=>{for(const f of m)this._pendingChannels.push({channel:f,context:h});this._throttledOnChannelChanged()},onRemove:(m,h)=>{this._removeChannels(m,h)}})}get _base(){return this}_removeChannels(n,r){const s=new Set(n);this._pendingChannels=this._pendingChannels.filter(({channel:o})=>!s.has(o.url)),this._base._removeChannelsFromView(n,r)}get channels(){var c;const n=((c=this._params.filter)==null?void 0:c.pinnedChannelUrls)??[],r=[],s=new Map(super.channels.map(u=>[u.url,u])),o=new Set;for(const u of n){const d=s.get(u);d&&!o.has(u)&&(r.push(d),o.add(u))}const i=super.channels.filter(u=>!o.has(u.url));return[...r,...i]}setConversationListCollectionHandler(n){super.setGroupChannelCollectionHandler(n)}dispose(){super.dispose(),this._throttledOnChannelChanged.cancel(),this._base._unsubscribeChannelEvent(this._key)}}class ti{constructor(t){v(this,"subscribers",{});this.logger=t}async send(t){const n=Uc(),r=this.subscribers[t.type];if(r){this.logger.debug(`messenger.dispatcher: dispatching command: ${t.type}`,t.payload);const s=r.map(o=>o(t.payload));await Promise.all(s).catch(o=>{this.logger.error(`messenger.dispatcher: error in callback for command: ${t.type}`,o)})}return n.resolve(),n.promise}subscribe(t,n){this.subscribers[t]||(this.subscribers[t]=[]),this.subscribers[t].push(n)}unsubscribe(t,n){const r=this.subscribers[t];r&&(this.subscribers[t]=r.filter(s=>s!==n))}}const Uc=()=>{let e=fe,t=fe;return{promise:new Promise((r,s)=>{e=r,t=s}),resolve:e,reject:t}};var Ue=(e=>(e.ConversationClose="conv.close",e.MessengerSettingsUpdated="messenger.settings.updated",e.ActiveChannelUpdated="active.channel.updated",e.AnonymousSessionTokenExpired="anon.token.expired",e.AuthTokenRefreshed="auth.token.refreshed",e.NudgeMessageReceived="nudge.message.received",e))(Ue||{});class xt{constructor(t={}){v(this,"payload");this.payload=t}toJSON(){return JSON.stringify({type:this.type,payload:this.payload})}}const tt={CloseConversation:e=>new Bc(e),MessengerSettingsUpdated:e=>new Hc(e),ActiveChannelUpdated:e=>new Gc(e),AnonymousSessionTokenExpired:()=>new zc,AuthTokenRefreshed:()=>new Vc,NudgeMessageReceived:e=>new qc(e)};class Bc extends xt{constructor(){super(...arguments);v(this,"type","conv.close")}}class Hc extends xt{constructor(){super(...arguments);v(this,"type","messenger.settings.updated")}}class Gc extends xt{constructor(){super(...arguments);v(this,"type","active.channel.updated")}}class zc extends xt{constructor(){super(...arguments);v(this,"type","anon.token.expired")}}class Vc extends xt{constructor(){super(...arguments);v(this,"type","auth.token.refreshed")}}class qc extends xt{constructor(){super(...arguments);v(this,"type","nudge.message.received")}}const Yt=e=>{const t={};for(const n of Object.keys(e)){const r=e[n];r!==void 0&&(t[n]=String(r))}return t};class Wt{constructor(t){v(this,"category","connection");this.userId=t}get data(){return Yt({user_id:this.userId})}}class Kc extends Wt{constructor(){super(...arguments);v(this,"metricKey","connection_connected")}}class Yc extends Wt{constructor(){super(...arguments);v(this,"metricKey","connection_reconnect_started")}}class Wc extends Wt{constructor(){super(...arguments);v(this,"metricKey","connection_reconnect_succeeded")}}class jc extends Wt{constructor(){super(...arguments);v(this,"metricKey","connection_reconnect_failed")}}class Xc extends Wt{constructor(){super(...arguments);v(this,"metricKey","connection_disconnected")}}class Zc{constructor(t){v(this,"lastKey",null);this.dispatch=t}handleEvent({detail:t,userId:n}){const r=`${t}:${n}`;if(this.shouldEmit(r)){this.lastKey=r;const s=t==="connected"?new Kc(n):t==="reconnectStarted"?new Yc(n):t==="reconnectSucceeded"?new Wc(n):t==="reconnectFailed"?new jc(n):new Xc(n);this.dispatch(s)}}shouldEmit(t){return t!==this.lastKey}}class Rr{constructor(t,n){v(this,"category","conversation");this.channelUrl=t,this.conversationId=n}get data(){return Yt({channel_url:this.channelUrl,conversation_id:this.conversationId})}}class Jc extends Rr{constructor(){super(...arguments);v(this,"metricKey","conversation_initialized")}}class Qc extends Rr{constructor(){super(...arguments);v(this,"metricKey","conversation_open")}}class el extends Rr{constructor(){super(...arguments);v(this,"metricKey","conversation_closed")}}class tl{constructor(t){v(this,"statusByChannel",new Map);this.dispatch=t}handleEvent({channel:t}){const{conversation:n}=t;if(!n)return;const r=this.statusByChannel.get(t.url),s=n.status;if(this.statusByChannel.set(t.url,s),this.shouldEmit(r,s)){const o=s===ge.ConversationStatus.INITIALIZED?new Jc(t.url,n.id):s===ge.ConversationStatus.OPEN?new Qc(t.url,n.id):new el(t.url,n.id);this.dispatch(o)}}shouldEmit(t,n){return n===ge.ConversationStatus.INITIALIZED?t===void 0:n===ge.ConversationStatus.OPEN?t===ge.ConversationStatus.INITIALIZED:t===ge.ConversationStatus.OPEN}}const ni=(e,t)=>{if(e)return e.members.filter(n=>n.userId!==t).sort((n,r)=>r.joinedAt-n.joinedAt)[0]},Fe=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===ge.ConversationStatus.CLOSED||e!=null&&e.isDesk&&((n=e==null?void 0:e.helpdeskInfo)==null?void 0:n.ticketStatus)==="closed")},Mr=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===ge.ConversationStatus.OPEN||e!=null&&e.isDesk&&((n=e==null?void 0:e.helpdeskInfo)==null?void 0:n.ticketStatus)==="open")};function nt(e){var n,r,s;return typeof(((n=e==null?void 0:e.conversation)==null?void 0:n.handedOverAt)??((s=(r=e==null?void 0:e.conversation)==null?void 0:r.handoff)==null?void 0:s.timestamp))=="number"}function nl(e){var r;const t=(r=e==null?void 0:e.conversation)==null?void 0:r.handoff;return t?typeof t.requestedAt=="number"&&!nt(e):!1}function rl(e){var t;if(((t=e==null?void 0:e.resolution)==null?void 0:t.determinedBy)==="user")return e.resolution.isResolved}function ri(e){return!!e&&e<=Date.now()}function sl(e){return!e.title}function ol(e,t){var n;if(e)return sl(e)?{...e,title:t.title,csat_question:t.question,csat_scores:[{label:"",image_url:"https://static.dashboard.sendbird.com/assets/ai-agent/angry-active.png"},{label:"",image_url:"https://static.dashboard.sendbird.com/assets/ai-agent/suspicious-active.png"},{label:"",image_url:"https://static.dashboard.sendbird.com/assets/ai-agent/neutral-active.png"},{label:"",image_url:"https://static.dashboard.sendbird.com/assets/ai-agent/smile-active.png"},{label:"",image_url:"https://static.dashboard.sendbird.com/assets/ai-agent/happy-active.png"}],cre:{required:((n=e.cre)==null?void 0:n.required)??!0,question:t.cre.question,positive_label:t.cre.positive_label,negative_label:t.cre.negative_label},follow_up:[{response_type:"free_text",scores:[1,2,3,4,5],question:t.followUp.question,always_visible:!1}],csat_submit_label:t.submit_label,csat_submitted_label:t.submitted_label}:e}class wr{constructor(t,n){v(this,"category","handoff");this.channelUrl=t,this.conversationId=n}get data(){return Yt({channel_url:this.channelUrl,conversation_id:this.conversationId})}}class il extends wr{constructor(){super(...arguments);v(this,"metricKey","handoff_started")}}class al extends wr{constructor(){super(...arguments);v(this,"metricKey","handoff_succeeded")}}class cl extends wr{constructor(){super(...arguments);v(this,"metricKey","handoff_failed")}}class ll{constructor(t){v(this,"statusByChannel",new Map);this.dispatch=t}handleEvent({channel:t}){const n=!this.statusByChannel.has(t.url);n&&this.statusByChannel.set(t.url,void 0);const r=t.conversation;if(!r||!r.handoff||n)return;const s=this.statusByChannel.get(t.url),o=this.resolveStatus(t,r);if(o!==void 0&&this.shouldEmit(s,o)){this.statusByChannel.set(t.url,o);const i=o==="started"?new il(t.url,r.id):o==="succeeded"?new al(t.url,r.id):new cl(t.url,r.id);this.dispatch(i)}}resolveStatus(t,n){if(Fe(t))return"failed";const{members:r}=t;if(r.length===1)return"started";if(r.length===2&&n.aiAgentId&&!r.some(s=>s.userId===n.aiAgentId))return"succeeded"}shouldEmit(t,n){return n==="started"?t===void 0:t==="started"}}class ul{constructor(t){v(this,"category","message");v(this,"metricKey","incoming_message_received");v(this,"channelUrl");v(this,"messageId");v(this,"senderType");v(this,"createdAt");v(this,"conversationId");this.channelUrl=t.channelUrl,this.messageId=t.messageId,this.senderType=t.senderType,this.createdAt=t.createdAt,this.conversationId=t.conversationId}get data(){return Yt({channel_url:this.channelUrl,message_id:this.messageId,sender_type:this.senderType,created_at:this.createdAt,conversation_id:this.conversationId})}}const dl=(e,t)=>{const n=Ze(e)?e.sender.userId:void 0;return n===void 0?"system":n===t?"ai_agent":"human_agent"};class ml{constructor(t,n){this.dispatch=t,this.getCurrentUserId=n}handleEvent({channel:t,message:n}){const{conversation:r}=t;this.shouldEmit(n,r)&&this.dispatch(new ul({channelUrl:t.url,messageId:n.messageId,senderType:dl(n,r.aiAgentId),createdAt:n.createdAt,conversationId:r.id}))}shouldEmit(t,n){return!rt(t,this.getCurrentUserId())&&n!==null}}class hl{constructor(t){v(this,"category","message");v(this,"metricKey");v(this,"channelUrl");v(this,"requestId");v(this,"messageId");v(this,"target");v(this,"sendingStatus");v(this,"createdAt");v(this,"conversationId");this.channelUrl=t.channelUrl,this.requestId=t.requestId,this.messageId=t.messageId,this.target=t.target,this.sendingStatus=t.sendingStatus,this.createdAt=t.createdAt,this.conversationId=t.conversationId,this.metricKey=`outgoing_message_${t.sendingStatus}`}get data(){return Yt({channel_url:this.channelUrl,request_id:this.requestId,message_id:this.messageId,target:this.target,created_at:this.createdAt,conversation_id:this.conversationId})}}const fl=e=>{switch(e){case De.SendingStatus.PENDING:return"pending";case De.SendingStatus.SUCCEEDED:return"succeeded";case De.SendingStatus.FAILED:return"failed";case De.SendingStatus.SCHEDULED:return"scheduled";default:return}};class gl{constructor(t,n){v(this,"statusByReqId",new Map);this.dispatch=t,this.getCurrentUserId=n}handleEvent({channel:t,message:n}){var o;if(!rt(n,this.getCurrentUserId()))return;const r=fl(n.sendingStatus);if(r===void 0)return;const s=this.statusByReqId.get(n.reqId);this.statusByReqId.set(n.reqId,r),r!=="scheduled"&&this.shouldEmit(s,r)&&this.dispatch(new hl({channelUrl:t.url,requestId:n.reqId,messageId:r==="succeeded"?n.messageId:void 0,target:nt(t)?"human_agent":"ai_agent",sendingStatus:r,createdAt:n.createdAt,conversationId:(o=t.conversation)==null?void 0:o.id}))}shouldEmit(t,n){return n==="pending"?t!=="pending"&&t!=="succeeded":n==="succeeded"?t==="pending"||t==="scheduled":t!=="failed"}}class pl{constructor(t){v(this,"id","aiagent_livemetric");v(this,"dispatch");v(this,"emit",({category:t,metricKey:n,data:r})=>{var s;(s=this.dispatch)==null||s.call(this,{category:t,metricKey:n,data:r})});v(this,"emitters");this.chatSDK=t;const n=()=>{var r;return(r=this.chatSDK.currentUser)==null?void 0:r.userId};this.emitters={connection:new Zc(this.emit),conversation:new tl(this.emit),handoff:new ll(this.emit),incomingMessage:new ml(this.emit,n),outgoingMessage:new gl(this.emit,n)}}start(){const t=new Ce.ConnectionHandler({onConnected:r=>this.trackConnection("connected",r),onDisconnected:r=>this.trackConnection("disconnected",r),onReconnectStarted:()=>this.trackConnection("reconnectStarted"),onReconnectSucceeded:()=>this.trackConnection("reconnectSucceeded"),onReconnectFailed:()=>this.trackConnection("reconnectFailed")}),n=new je.GroupChannelHandler({onMessageReceived:(r,s)=>{r.isGroupChannel()&&this.track({type:"incomingMessage",channel:r,message:s})},onChannelChanged:r=>{r.isGroupChannel()&&(this.track({type:"handoff",channel:r}),this.track({type:"conversation",channel:r}))},onUserJoined:r=>this.track({type:"handoff",channel:r}),onUserLeft:r=>this.track({type:"handoff",channel:r})});this.chatSDK.addConnectionHandler(this.id,t),this.chatSDK.groupChannel.addGroupChannelHandler(this.id,n)}track(t){try{this.emitters[t.type].handleEvent(t)}catch{}}dispose(){this.chatSDK.removeConnectionHandler(this.id),this.chatSDK.groupChannel.removeGroupChannelHandler(this.id)}trackConnection(t,n=(r=>(r=this.chatSDK.currentUser)==null?void 0:r.userId)()){n&&this.track({type:"connection",detail:t,userId:n})}}var kr=(e=>(e[e.VERBOSE=0]="VERBOSE",e[e.DEBUG=1]="DEBUG",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e[e.NONE=5]="NONE",e))(kr||{});class si{constructor(t){v(this,"level");this.level=t}verbose(...t){this.level<=0&&console.log(`[${Ct}/verbose]`,...t)}debug(...t){this.level<=1&&console.log(`[${Ct}/debug]`,...t)}info(...t){this.level<=2&&console.log(`[${Ct}/info]`,...t)}warn(...t){this.level<=3&&console.warn(`[${Ct}/warn]`,...t)}error(...t){this.level<=4&&console.error(`[${Ct}/error]`,...t)}}class oi{constructor({userId:t,authToken:n,sessionHandler:r}){v(this,"userId");v(this,"authToken");v(this,"sessionHandler");this.userId=t,this.authToken=n,this.sessionHandler=r}}class lr{constructor(){v(this,"userId");v(this,"authToken");v(this,"sessionHandler")}}const _l=e=>({onSessionTokenRequired:t=>{t(null),e.send(tt.AnonymousSessionTokenExpired())}}),Lr=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!=null)),El="ai_agent:stats",Cl="conversation_initial_render",bl="conversation_not_interactive_timeout",vl="recovery_not_interactive_timeout",Sl="conversation_list_initial_render",yl="message_pending_stuck",Al="aiev_auth_expired_unhandled",Tl="user_perceived_response_time",Il="stream_stalled",xl="ai_typing_indicator_absent_timeout",Rl="rendered_content_unusable",Ml=800220;var V=(e=>(e.ACK_TO_FIRST_CHUNK="ack_to_first_chunk_ms",e.AFTER_TPEN_ABSENT="after_tpen_absent_ms",e.AUTH="auth_duration_ms",e.BEFORE_TPST_ABSENT="before_tpst_absent_ms",e.FIRST_CHUNK_TO_RENDER="first_chunk_to_render_ms",e.GET_CHANNEL="get_channel_duration_ms",e.GET_LIST="get_list_duration_ms",e.GET_MESSAGES="get_messages_duration_ms",e.PAGE_RENDER="page_render_duration_ms",e.PAGE_RENDER_FROM_CACHE="total_duration_from_cache_ms",e.SEND_TO_ACK="send_to_ack_ms",e.TIMEOUT="timeout_ms",e))(V||{});const ur=(e,t)=>e.startAt===null||e.endedAt===null||t.startAt===null||t.endedAt===null?0:Math.max(0,Math.min(e.endedAt,t.endedAt)-Math.max(e.startAt,t.startAt)),ii=e=>typeof e=="object"&&e!==null,wl=e=>{if(ii(e))return typeof e.code=="number"?e.code:void 0},kl=e=>e instanceof Error?e.message:typeof e=="string"?e:ii(e)&&typeof e.message=="string"?e.message:"";class Je{constructor(){v(this,"timers",new Map);v(this,"committed",!1);v(this,"commitCallback",null);v(this,"conversationId",null);v(this,"errorCode",null);v(this,"errorDescription",null);v(this,"extraData",{})}setCommitCallback(t){return this.commitCallback=t,this}setConversationId(t){return t&&(this.conversationId=t),this}setError(t){return t==null?this:(this.errorCode=wl(t)??Ml,this.errorDescription=kl(t),this)}setExtra(t,n){return n!=null&&(this.extraData[t]=n),this}startTimer(t){if(this.committed)return this;const n=this.timers.get(t);return(n==null?void 0:n.startTime)!==null&&(n==null?void 0:n.startTime)!==void 0?this:(this.timers.set(t,{startTime:performance.now(),endTime:null}),this)}stopTimer(t){if(this.committed)return this;const n=this.timers.get(t);return!n||n.startTime===null||n.endTime!==null?this:(this.timers.set(t,{...n,endTime:performance.now()}),this)}getTimer(t){const n=this.timers.get(t);return!n||n.startTime===null?{startAt:null,endedAt:null,duration:null}:{startAt:n.startTime,endedAt:n.endTime,duration:n.endTime===null?null:n.endTime-n.startTime}}createPayload(t,n){const r={key:this.getMetricKey(),value:String(t)},s=(n==null?void 0:n.conversationId)??this.conversationId??void 0;s!==void 0&&(r.conversation_id=s),this.errorCode!==null&&(r.error_code=this.errorCode,r.error_description=this.errorDescription??"");const o=Lr({...this.extraData,...n==null?void 0:n.extra});return Object.keys(o).length>0&&(r.extra=o),r}isCommitted(){return this.committed}discard(){this.committed=!0}commit(){if(this.committed||!this.commitCallback)return!1;const t=this.buildPayload();return t?(this.committed=!0,this.commitCallback(El,t)):!1}}class fs extends Je{constructor(){super(...arguments);v(this,"reason");v(this,"aiAgentId")}setReason(n){return this.reason=n,this}setAIAgentId(n){return this.aiAgentId=n,this}getMetricKey(){return Al}buildPayload(){return this.reason===void 0||this.aiAgentId===void 0?null:this.createPayload(this.reason,{extra:{agent_id:this.aiAgentId}})}}class Rn{constructor(t){v(this,"commitCallback");this.commitCallback=t}}class Rt extends Rn{constructor(){super(...arguments);v(this,"records",new Map)}}class ai extends Rn{constructor(){super(...arguments);v(this,"activeSpan",null);v(this,"visible",!0)}setVisible(n){var r;this.visible=n,(r=this.activeSpan)==null||r.onVisibilityChanged(n)}}class ci{constructor(t,n){v(this,"stats");v(this,"visible");v(this,"completedHidden",!1);this.stats=t,this.visible=n}get isRecording(){return this.stats!==null&&!this.stats.isCommitted()}onVisibilityChanged(t){this.stats&&(this.visible=t,t&&this.completedHidden&&(this.stats.commit(),this.stats=null))}commitOrDefer(){if(this.stats){if(!this.visible){this.completedHidden=!0;return}this.stats.commit(),this.stats=null}}cancel(){this.stats=null}}const mt=(e,t)=>!(e&&t&&e!==t),dr=(e,t)=>{for(const n of e)if(n.measure.userMessageId===void 0&&mt(n.measure.channelUrl,t))return!0;return!1},Mn=(e,t)=>{if(e.size<t)return;const n=e.keys().next();n.done||e.delete(n.value)};class Ll extends Rn{onPayloadParseFailed(t){new fs().setReason("payload_parse_failed").setAIAgentId(t.aiAgentId).setCommitCallback(this.commitCallback).commit()}onCallbackNotFound(t){new fs().setReason("callback_not_found").setAIAgentId(t.aiAgentId).setCommitCallback(this.commitCallback).commit()}clear(){}}class Ol extends Je{constructor(){super(...arguments);v(this,"channelUrl",null);v(this,"presentMethod","direct_present")}setChannelUrl(n){return this.channelUrl=n,this}setPresentMethod(n){return this.presentMethod=n,this}resetPageRenderSpan(){return this.timers.delete(V.PAGE_RENDER),this.timers.delete(V.PAGE_RENDER_FROM_CACHE),this.timers.delete(V.GET_CHANNEL),this.timers.delete(V.GET_MESSAGES),this.conversationId=null,this.channelUrl=null,this.errorCode=null,this.errorDescription=null,this}getMetricKey(){return Cl}buildPayload(){const n=this.getTimer(V.AUTH),r=this.getTimer(V.PAGE_RENDER),s=this.getTimer(V.PAGE_RENDER_FROM_CACHE);if(r.duration===null&&(this.errorCode===null||n.duration===null))return null;const o=r.duration===null?0:r.duration-ur(n,r),i=s.duration===null?null:s.duration-ur(n,s);return this.createPayload((n.duration??0)+o,{extra:{channel_url:this.channelUrl,present_method:this.presentMethod,[V.AUTH]:n.duration,[V.GET_CHANNEL]:this.getTimer(V.GET_CHANNEL).duration,[V.GET_MESSAGES]:this.getTimer(V.GET_MESSAGES).duration,[V.PAGE_RENDER_FROM_CACHE]:i}})}}class Nl extends ci{constructor(n,r,s){var o;super(n,s);v(this,"measure");this.measure={channelUrl:r,pageRenderState:"initialized"},(o=this.stats)==null||o.setChannelUrl(r).startTimer(V.PAGE_RENDER).startTimer(V.PAGE_RENDER_FROM_CACHE)}onGetChannelStart(n){!this.stats||n!==this.measure.channelUrl||this.measure.pageRenderState!=="initialized"||(this.stats.startTimer(V.GET_CHANNEL),this.measure.pageRenderState="channel_fetching")}onGetChannelComplete(n,r){!this.stats||n!==this.measure.channelUrl||this.measure.pageRenderState!=="channel_fetching"||(this.stats.stopTimer(V.GET_CHANNEL).setConversationId(r),this.measure.pageRenderState="channel_fetched")}onGetChannelError(n,r){!this.stats||n!==this.measure.channelUrl||this.measure.pageRenderState!=="channel_fetching"||(this.stats.stopTimer(V.GET_CHANNEL).setError(r).stopTimer(V.PAGE_RENDER),this.measure.pageRenderState="channel_failed",this.tryFinalize())}onGetMessagesStart(){!this.stats||this.measure.pageRenderState!=="channel_fetched"||(this.stats.startTimer(V.GET_MESSAGES),this.measure.pageRenderState="messages_fetching")}onGetMessagesCacheComplete(n,r){!this.stats||n!==this.measure.channelUrl||r||this.measure.pageRenderState!=="messages_fetching"||this.stats.stopTimer(V.PAGE_RENDER_FROM_CACHE)}onGetMessagesComplete(n,r){!this.stats||n!==this.measure.channelUrl||this.measure.pageRenderState!=="messages_fetching"||(this.stats.stopTimer(V.GET_MESSAGES).setError(r),this.measure.pageRenderState="messages_fetching_completed")}onRendered(){!this.stats||this.measure.pageRenderState!=="messages_fetching_completed"||(this.stats.stopTimer(V.PAGE_RENDER),this.tryFinalize())}onRenderDiscarded(){!this.stats||this.measure.pageRenderState!=="messages_fetching_completed"||(this.stats.discard(),this.stats=null)}onAuthSettled(){this.tryFinalize()}tryFinalize(){if(!this.stats||this.stats.getTimer(V.PAGE_RENDER).endedAt===null)return;const n=this.stats.getTimer(V.AUTH);if(!(n.startAt!==null&&n.endedAt===null)){if(this.measure.pageRenderState==="channel_failed"){this.stats.commit(),this.stats=null;return}this.commitOrDefer()}}}class Dl extends ai{constructor(){super(...arguments);v(this,"stats",null);v(this,"authState","idle");v(this,"presentMethod","direct_present")}getOrCreateStats(){var n;return(n=this.stats)!=null&&n.isCommitted()?null:(this.stats||(this.stats=new Ol().setCommitCallback(this.commitCallback).setPresentMethod(this.presentMethod)),this.stats)}getActiveStats(){return!this.stats||this.stats.isCommitted()?null:this.stats}setPresentMethod(n){var r;this.presentMethod=n,(r=this.getActiveStats())==null||r.setPresentMethod(n)}onAuthStart(){var n,r;if((n=this.stats)!=null&&n.isCommitted()){if(this.authState!=="failed"||this.activeSpan!==null)return;this.stats=null,this.authState="idle"}this.authState==="idle"&&(this.authState="in_progress",(r=this.getOrCreateStats())==null||r.startTimer(V.AUTH))}onAuthComplete(){var n,r;this.authState==="in_progress"&&(this.authState="completed",(n=this.getActiveStats())==null||n.stopTimer(V.AUTH)),(r=this.activeSpan)==null||r.onAuthSettled()}onAuthError(n){var r,s;this.authState==="in_progress"&&(this.authState="failed",(r=this.getActiveStats())==null||r.stopTimer(V.AUTH).setError(n).commit(),(s=this.activeSpan)==null||s.cancel())}startSpan(n){const r=this.activeSpan;r==null||r.cancel();const s=this.getOrCreateStats();return s&&r&&s.resetPageRenderSpan(),this.activeSpan=new Nl(s,n,this.visible),this.activeSpan}clear(){var n;(n=this.activeSpan)==null||n.cancel(),this.activeSpan=null,this.stats=null,this.authState="idle"}}class $l extends Je{constructor(){super(...arguments);v(this,"presentMethod","direct_present")}setPresentMethod(n){return this.presentMethod=n,this}resetPageRenderSpan(){return this.timers.delete(V.PAGE_RENDER),this.timers.delete(V.GET_LIST),this.errorCode=null,this.errorDescription=null,this}getMetricKey(){return Sl}buildPayload(){const n=this.getTimer(V.AUTH),r=this.getTimer(V.PAGE_RENDER),s=this.getTimer(V.GET_LIST).duration;if(r.duration===null&&(this.errorCode===null||n.duration===null))return null;const o=r.duration===null?0:r.duration-ur(n,r),i=(n.duration??0)+o;return this.createPayload(i,{extra:{present_method:this.presentMethod,[V.AUTH]:n.duration,[V.GET_LIST]:s}})}}class Pl extends ci{constructor(n,r){var s;super(n,r);v(this,"measure",{listStarted:!1,listCompleted:!1});(s=this.stats)==null||s.startTimer(V.PAGE_RENDER)}onListRequestStart(){!this.stats||this.measure.listStarted||(this.stats.startTimer(V.PAGE_RENDER),this.stats.startTimer(V.GET_LIST),this.measure.listStarted=!0)}onListRequestComplete(n){if(!(!this.stats||!this.measure.listStarted||this.measure.listCompleted)){if(n){this.stats.resetPageRenderSpan(),this.measure.listStarted=!1;return}this.stats.stopTimer(V.GET_LIST),this.measure.listCompleted=!0}}onRendered(){!this.stats||!this.measure.listCompleted||(this.stats.stopTimer(V.PAGE_RENDER),this.tryFinalize())}onRenderDiscarded(){!this.stats||!this.measure.listCompleted||(this.stats.discard(),this.stats=null)}onAuthSettled(){this.tryFinalize()}tryFinalize(){if(!this.stats||this.stats.getTimer(V.PAGE_RENDER).endedAt===null)return;const n=this.stats.getTimer(V.AUTH);n.startAt!==null&&n.endedAt===null||this.commitOrDefer()}}class Fl extends ai{constructor(){super(...arguments);v(this,"stats",null);v(this,"authState","idle");v(this,"presentMethod","direct_present")}getOrCreateStats(){var n;return(n=this.stats)!=null&&n.isCommitted()?null:(this.stats||(this.stats=new $l().setCommitCallback(this.commitCallback).setPresentMethod(this.presentMethod)),this.stats)}getActiveStats(){return!this.stats||this.stats.isCommitted()?null:this.stats}setPresentMethod(n){var r;this.presentMethod=n,(r=this.getActiveStats())==null||r.setPresentMethod(n)}onAuthStart(){var n;this.authState="in_progress",(n=this.getOrCreateStats())==null||n.startTimer(V.AUTH)}onAuthComplete(){var r,s;const n=this.authState==="in_progress";this.authState="completed",n&&((r=this.getActiveStats())==null||r.stopTimer(V.AUTH)),(s=this.activeSpan)==null||s.onAuthSettled()}onAuthError(n){var o;const r=this.authState==="in_progress";this.authState="failed";const s=this.getActiveStats();if(s){if(!((o=this.activeSpan)!=null&&o.isRecording)){this.stats=null;return}r&&s.stopTimer(V.AUTH),s.setError(n).commit(),this.activeSpan.cancel()}}startSpan(){const n=this.activeSpan;n==null||n.cancel();const r=this.getOrCreateStats();return r&&n&&r.resetPageRenderSpan(),r&&this.authState==="in_progress"&&r.startTimer(V.AUTH),this.activeSpan=new Pl(r,this.visible),this.activeSpan}clear(){var n;(n=this.activeSpan)==null||n.cancel(),this.activeSpan=null,this.stats=null,this.authState="idle"}}class Ul extends Je{constructor(){super(...arguments);v(this,"phaseReached","auth");v(this,"historyLoadResult","pending")}setHistoryLoadResult(n){return this.historyLoadResult=n,this}setPhaseReached(n){return this.phaseReached=n,this}getMetricKey(){return bl}buildPayload(){const n=this.getTimer(V.TIMEOUT).duration;return n===null?null:this.createPayload(n,{extra:{outcome:"timeout",phase_reached:this.phaseReached,history_load_result:this.historyLoadResult}})}}class Bl extends Rt{start(t){const n=this.getKey(t==null?void 0:t.channelUrl);this.clearKey(n);const r={stats:new Ul().setCommitCallback(this.commitCallback).startTimer(V.TIMEOUT),measure:{channelUrl:t==null?void 0:t.channelUrl,historyLoadResult:"pending",inputEnabled:!1,timer:null}};(t==null?void 0:t.conversationId)!==void 0&&r.stats.setConversationId(t.conversationId),r.measure.timer=setTimeout(()=>this.commitTimeout(n),1e4),this.records.set(n,r)}markChannelJoined(t,n){const r=this.getRecord(n);r&&(r.stats.setPhaseReached("channel_join"),t!==void 0&&r.stats.setConversationId(t))}markHistoryLoaded(t,n){const r=this.getRecord(n);r&&(r.measure.historyLoadResult=t,r.stats.setHistoryLoadResult(t).setPhaseReached("history_load"),this.cancelIfReady(n))}markInputReady(t){const n=this.getRecord(t);n&&(n.measure.inputEnabled=!0,n.stats.setPhaseReached("input_enable"),this.cancelIfReady(t))}markRendered(t){const n=this.getRecord(t);n&&n.stats.setPhaseReached("render")}clear(){this.records.forEach(t=>{t.measure.timer!==null&&clearTimeout(t.measure.timer)}),this.records.clear()}clearChannel(t){t!==void 0&&this.clearKey(this.getKey(t))}clearKey(t){const n=this.records.get(t);n&&(n.measure.timer!==null&&clearTimeout(n.measure.timer),this.records.delete(t))}cancelIfReady(t){const n=this.getRecord(t);!n||!n.measure.inputEnabled||n.measure.historyLoadResult==="pending"||this.clearKey(this.getKey(n.measure.channelUrl))}commitTimeout(t){const n=this.records.get(t);n&&(n.measure.timer=null,this.records.delete(t),n.stats.stopTimer(V.TIMEOUT).commit())}getRecord(t){return t!==void 0?this.records.get(this.getKey(t)):this.records.size===1?this.records.values().next().value:this.records.get(this.getKey())}getKey(t){return t??"__default__"}}class Hl extends Je{constructor(){super(...arguments);v(this,"requestId");v(this,"messageType");v(this,"stuckReason")}setRequestId(n){return this.requestId=n,this}setMessageType(n){return this.messageType=n,this}setStuckReason(n){return this.stuckReason=n,this}getMetricKey(){return yl}buildPayload(){return this.requestId===void 0||this.messageType===void 0||this.stuckReason===void 0?null:this.createPayload(this.stuckReason,{extra:{message_type:this.messageType,request_id:this.requestId}})}}const Gl=5e3,gs=1e4;class zl extends Rt{start(t){if(!t.requestId||this.records.has(t.requestId))return;const n=t.messageType!=="text"&&t.tracksUploadProgress===!0,s={stats:new Hl().setRequestId(t.requestId).setMessageType(t.messageType).setStuckReason(n?"upload_no_progress":"pending_too_long").setCommitCallback(this.commitCallback),measure:{channelUrl:t.channelUrl,timer:null,usesUploadProgress:n}},o=n?gs:Gl;s.measure.timer=setTimeout(()=>this.detect(t.requestId),o),this.records.set(t.requestId,s)}resolve(t){this.cancel(t.requestId)}disappear(t){this.cancel(t.requestId)}cancel(t){const n=this.records.get(t);n&&(n.measure.timer!==null&&clearTimeout(n.measure.timer),this.records.delete(t))}markUploadProgress(t){const n=this.records.get(t);n&&n.measure.usesUploadProgress&&(n.measure.timer!==null&&clearTimeout(n.measure.timer),n.measure.timer=setTimeout(()=>this.detect(t),gs))}clear(){this.records.forEach(t=>{t.measure.timer!==null&&clearTimeout(t.measure.timer)}),this.records.clear()}clearChannel(t){t&&this.records.forEach((n,r)=>{n.measure.channelUrl===t&&(n.measure.timer!==null&&clearTimeout(n.measure.timer),this.records.delete(r))})}detect(t){const n=this.records.get(t);n&&(this.records.delete(t),n.stats.commit())}}class Kn extends Je{constructor(){super(...arguments);v(this,"triggerType")}setTriggerType(n){return this.triggerType=n,this}getMetricKey(){return vl}buildPayload(){const n=this.getTimer(V.TIMEOUT).duration;return n===null||this.triggerType===void 0?null:this.createPayload(n,{extra:{trigger_type:this.triggerType}})}}class Vl extends Rt{start(t,n){const r=this.getKey(n);let s=this.records.get(r);s!=null&&s.measure.started||s!=null&&s.measure.inputEnabled||(s||(s=this.createRecord(!1)),s.measure.started=!0,s.stats=new Kn().setTriggerType(t).setCommitCallback(this.commitCallback).startTimer(V.TIMEOUT),s.measure.timer=setTimeout(()=>this.commitTimeout(r),1e4),this.records.set(r,s))}setInputEnabled(t,n){const r=this.getKey(n);let s=this.records.get(r);if(!s){if(!t)return;s=this.createRecord(t),this.records.set(r,s);return}s.measure.inputEnabled=t,t?this.cancelRecord(s):s.measure.started||this.records.delete(r)}cancelPending(t){const n=this.getKey(t),r=this.records.get(n);r&&(this.cancelRecord(r),r.measure.inputEnabled||this.records.delete(n))}clear(){this.records.forEach(t=>{t.measure.timer!==null&&clearTimeout(t.measure.timer)}),this.records.clear()}clearChannel(t){t!==void 0&&this.clearKey(this.getKey(t))}clearKey(t){const n=this.records.get(t);n&&(n.measure.timer!==null&&clearTimeout(n.measure.timer),this.records.delete(t))}commitTimeout(t){const n=this.records.get(t);if(!(!n||!n.measure.started)){if(n.measure.inputEnabled){this.cancelRecord(n);return}n.stats.stopTimer(V.TIMEOUT),this.records.delete(t),n.stats.commit()}}cancelRecord(t){t.measure.timer!==null&&clearTimeout(t.measure.timer),t.measure.timer=null,t.measure.started=!1,t.stats=new Kn().setCommitCallback(this.commitCallback)}createRecord(t){return{stats:new Kn().setCommitCallback(this.commitCallback),measure:{inputEnabled:t,started:!1,timer:null}}}getKey(t){return t??"__default__"}}class ql extends Je{constructor(){super(...arguments);v(this,"messageId");v(this,"contentKind");v(this,"errorDomain")}setMessageId(n){return this.messageId=n,this}setContentKind(n){return this.contentKind=n,this}setErrorDomain(n){return this.errorDomain=n,this}getMetricKey(){return Rl}buildPayload(){return this.messageId===void 0||this.contentKind===void 0||this.errorDomain===void 0?null:this.createPayload(this.errorDomain,{extra:{content_kind:this.contentKind,message_id:String(this.messageId)}})}}const Kl=500;class Yl extends Rn{constructor(){super(...arguments);v(this,"measure",{committed:new Set})}commit(n){const r=`${n.messageId}:${n.contentKind}:${n.errorDomain}`;if(this.measure.committed.has(r))return;Mn(this.measure.committed,Kl),this.measure.committed.add(r),new ql().setMessageId(n.messageId).setContentKind(n.contentKind).setErrorDomain(n.errorDomain).setError(n.error?{code:n.error.code,message:n.errorDomain}:void 0).setCommitCallback(this.commitCallback).commit()}clear(){this.measure.committed.clear()}}class Wl extends Je{constructor(){super(...arguments);v(this,"durationMs");v(this,"messageId");v(this,"stallKind")}setMessageId(n){return this.messageId=n,this}setStall(n){return this.durationMs=n.durationMs,this.stallKind=n.stallKind,this}getMetricKey(){return Il}buildPayload(){return this.durationMs===void 0||this.messageId===void 0||this.stallKind===void 0?null:this.createPayload(this.durationMs,{extra:{message_id:String(this.messageId),stall_kind:this.stallKind}})}}const ps=1e4,Et=5e3,jl=500;class Xl extends Rt{constructor(){super(...arguments);v(this,"emittedMessageChannels",new Map)}markRawProgress(n){if(!n.aiResponse.isStreaming){this.completeDelivery(n.messageId,n.textLength);return}if(this.emittedMessageChannels.has(n.messageId))return;const r=this.getOrCreate(n.messageId,n.channelUrl),s=r.measure;this.markRawProgressForRecord(r,n.textLength,performance.now())?(s.deliveryTimer!==null&&clearTimeout(s.deliveryTimer),s.deliveryTimer=null,this.scheduleDeliveryStallCheck(n.messageId,r)):this.scheduleDeliveryStallCheck(n.messageId,r),this.isRenderPending(r)&&s.renderTimer===null&&(s.lastRenderAt=performance.now(),this.scheduleRenderStallCheck(n.messageId,r,Et))}markRenderedProgress(n){const r=this.records.get(n.messageId);if(!r)return;const s=r.measure;if(this.markRenderedProgressForRecord(r,n.displayedLength,performance.now())){if(!this.isRenderPending(r)){if(s.deliveryTimer===null){this.clearRecord(n.messageId,r);return}s.renderTimer!==null&&clearTimeout(s.renderTimer),s.renderTimer=null;return}this.scheduleRenderStallCheck(n.messageId,r,Et)}}hasPendingStream(n){return this.records.has(n)}complete(n){const r=this.records.get(n);r&&this.clearRecord(n,r)}completeDelivery(n,r){const s=this.records.get(n);if(!s)return;const o=s.measure;if(r>o.lastRawLength&&(o.lastRawLength=r,o.lastRawAt=performance.now()),o.deliveryTimer!==null&&clearTimeout(o.deliveryTimer),o.deliveryTimer=null,!this.isRenderPending(s)){this.clearRecord(n,s);return}o.renderTimer===null&&(o.lastRenderAt=performance.now(),this.scheduleRenderStallCheck(n,s,Et))}clearMessage(n){const r=this.records.get(n);r&&this.clearRecord(n,r),this.emittedMessageChannels.delete(n)}clear(){this.records.forEach(n=>{n.measure.deliveryTimer!==null&&clearTimeout(n.measure.deliveryTimer),n.measure.renderTimer!==null&&clearTimeout(n.measure.renderTimer)}),this.records.clear(),this.emittedMessageChannels.clear()}clearChannel(n){n&&(this.records.forEach((r,s)=>{r.measure.channelUrl!==n&&r.measure.channelUrl!==void 0||this.clearRecord(s,r)}),this.emittedMessageChannels.forEach((r,s)=>{(r===n||r===void 0)&&this.emittedMessageChannels.delete(s)}))}detectDelivery(n){const r=this.records.get(n);if(!r)return;const s=r.measure;s.deliveryTimer=null,s.renderTimer!==null&&clearTimeout(s.renderTimer),s.renderTimer=null,this.emit(n,r,"delivery")}detectRender(n){const r=this.records.get(n);if(!r)return;const s=r.measure;if(s.renderTimer=null,!this.isRenderPending(r))return;const o=performance.now()-s.lastRenderAt;if(o<Et){this.scheduleRenderStallCheck(n,r,Et-o);return}const i=performance.now()-s.lastRawAt;if(i>=Et&&s.deliveryTimer!==null){const c=ps-i;if(c>0){this.scheduleRenderStallCheck(n,r,c);return}}this.emit(n,r,"render")}scheduleRenderStallCheck(n,r,s){r.measure.renderTimer===null&&(r.measure.renderTimer=setTimeout(()=>this.detectRender(n),s))}scheduleDeliveryStallCheck(n,r){r.measure.deliveryTimer===null&&(r.measure.deliveryTimer=setTimeout(()=>this.detectDelivery(n),ps))}emit(n,r,s){if(this.emittedMessageChannels.has(n))return;const o=performance.now(),i=s==="delivery"?r.measure.lastRawAt:r.measure.lastRenderAt;r.stats.setStall({stallKind:s,durationMs:o-i}).commit(),this.rememberEmitted(n,r.measure.channelUrl),this.clearRecord(n,r)}getOrCreate(n,r){const s=this.records.get(n);if(s)return s;const o=performance.now(),i={stats:new Wl().setMessageId(n).setCommitCallback(this.commitCallback),measure:{channelUrl:r,deliveryTimer:null,lastRawAt:o,lastRawLength:0,lastRenderAt:o,lastRenderedLength:0,renderTimer:null}};return this.records.set(n,i),i}rememberEmitted(n,r){this.emittedMessageChannels.has(n)||Mn(this.emittedMessageChannels,jl),this.emittedMessageChannels.set(n,r)}clearRecord(n,r){r.measure.deliveryTimer!==null&&clearTimeout(r.measure.deliveryTimer),r.measure.renderTimer!==null&&clearTimeout(r.measure.renderTimer),this.records.delete(n)}isRenderPending(n){return n.measure.lastRenderedLength<n.measure.lastRawLength}markRawProgressForRecord(n,r,s){return r<=n.measure.lastRawLength?!1:(n.measure.lastRawLength=r,n.measure.lastRawAt=s,!0)}markRenderedProgressForRecord(n,r,s){return r<=n.measure.lastRenderedLength?!1:(n.measure.lastRenderedLength=r,n.measure.lastRenderAt=s,!0)}}class Zl extends Je{constructor(){super(...arguments);v(this,"beforeTpstAbsentMs");v(this,"afterTpenAbsentMs")}setBeforeTpstAbsentMs(n){return this.beforeTpstAbsentMs=n,this}setAfterTpenAbsentMs(n){return this.afterTpenAbsentMs=n,this}getMetricKey(){return xl}buildPayload(){return this.beforeTpstAbsentMs===void 0&&this.afterTpenAbsentMs===void 0?null:this.createPayload((this.beforeTpstAbsentMs??0)+(this.afterTpenAbsentMs??0),{extra:{[V.BEFORE_TPST_ABSENT]:this.beforeTpstAbsentMs,[V.AFTER_TPEN_ABSENT]:this.afterTpenAbsentMs}})}}const _s=3e3,Jl=3e4;class Ql extends Rt{constructor(){super(...arguments);v(this,"pendingAIResponseStartsByUserMessageId",new Map)}startTurn(n){this.cancelTurn(n.requestId);const r={stats:new Zl().setCommitCallback(this.commitCallback),measure:{afterTpenStartedAt:null,beforeTpstStartedAt:performance.now(),channelUrl:n.channelUrl,requestId:n.requestId,timer:null}};r.measure.timer=setTimeout(()=>this.commitTimeout(r.measure.requestId),Jl),this.records.set(n.requestId,r)}markUserMessageAck(n){const r=this.records.get(n.requestId);if(!r)return;r.measure.userMessageId=n.messageId;const s=this.pendingAIResponseStartsByUserMessageId.get(n.messageId);s&&(this.pendingAIResponseStartsByUserMessageId.delete(n.messageId),this.applyAIResponseStarted({channelUrl:s.channelUrl,matchesUserMessage:!0,userMessageId:n.messageId},s.startedAt))}replaceTurnRequestId(n,r){if(n===r)return;const s=this.records.get(n);s&&(this.records.delete(n),s.measure.requestId=r,this.records.set(r,s))}cancelTurn(n){this.cleanupTurn(n)}markTypingStarted(n){const r=performance.now();this.records.forEach(s=>{mt(s.measure.channelUrl,n)&&(this.recordAfterTpen(s,r),this.recordBeforeTpst(s,r))})}markTypingEnded(n){const r=performance.now();this.records.forEach(s=>{mt(s.measure.channelUrl,n)&&(this.recordBeforeTpst(s,r),s.measure.afterTpenStartedAt=r)})}markAIResponseStarted(n={}){const r=n.channelUrl,s=n.userMessageId,o=s!==void 0,i=performance.now();this.applyAIResponseStarted({channelUrl:r,matchesUserMessage:o,userMessageId:s},i)||!o||s===void 0||!dr(this.records.values(),r)||this.pendingAIResponseStartsByUserMessageId.has(s)||(Mn(this.pendingAIResponseStartsByUserMessageId,100),this.pendingAIResponseStartsByUserMessageId.set(s,{channelUrl:r,startedAt:i}))}applyAIResponseStarted(n,r){if(!n.matchesUserMessage){const o=this.findSingleTurn(n.channelUrl);return o?(this.completeTurn(o.requestId,o.record,r),!0):!1}let s=!1;return this.records.forEach(o=>{mt(o.measure.channelUrl,n.channelUrl)&&(n.matchesUserMessage&&o.measure.userMessageId!==n.userMessageId||(s=!0,this.completeTurn(o.measure.requestId,o,r)))}),s}findSingleTurn(n){let r,s=0;return this.records.forEach(o=>{mt(o.measure.channelUrl,n)&&(s+=1,!(s>1)&&(r={requestId:o.measure.requestId,record:o}))}),s===1?r:void 0}completeTurn(n,r,s){this.recordBeforeTpst(r,s),this.recordAfterTpen(r,s),this.commitIfAbsent(n,r)}clear(){this.records.forEach(n=>{n.measure.timer!==null&&clearTimeout(n.measure.timer)}),this.records.clear(),this.pendingAIResponseStartsByUserMessageId.clear()}clearChannel(n){n&&(this.records.forEach(r=>{r.measure.channelUrl===n&&this.cleanupTurn(r.measure.requestId)}),this.pendingAIResponseStartsByUserMessageId.forEach((r,s)=>{r.channelUrl===n&&this.pendingAIResponseStartsByUserMessageId.delete(s)}))}commitTimeout(n){const r=this.records.get(n);if(!r)return;const s=performance.now();this.recordBeforeTpst(r,s),this.recordAfterTpen(r,s),this.commitIfAbsent(n,r)}commitIfAbsent(n,r){r.stats.commit(),this.cleanupTurn(n)}cleanupTurn(n){const r=this.records.get(n);r&&(r.measure.timer!==null&&clearTimeout(r.measure.timer),this.records.delete(n))}recordBeforeTpst(n,r){if(n.measure.beforeTpstStartedAt===null)return;const s=r-n.measure.beforeTpstStartedAt;s>=_s&&n.stats.setBeforeTpstAbsentMs(s),n.measure.beforeTpstStartedAt=null}recordAfterTpen(n,r){if(n.measure.afterTpenStartedAt===null)return;const s=r-n.measure.afterTpenStartedAt;s>=_s&&n.stats.setAfterTpenAbsentMs(s),n.measure.afterTpenStartedAt=null}}class eu extends Je{constructor(){super(...arguments);v(this,"ackToFirstChunkMs");v(this,"firstChunkToRenderMs");v(this,"isStreaming");v(this,"sendToAckMs");v(this,"totalDurationMs")}setDurations(n){return this.ackToFirstChunkMs=n.ackToFirstChunkMs,this.firstChunkToRenderMs=n.firstChunkToRenderMs,this.isStreaming=n.isStreaming,this.sendToAckMs=n.sendToAckMs,this.totalDurationMs=n.totalDurationMs,this}getMetricKey(){return Tl}buildPayload(){return this.ackToFirstChunkMs===void 0||this.firstChunkToRenderMs===void 0||this.isStreaming===void 0||this.sendToAckMs===void 0||this.totalDurationMs===void 0?null:this.createPayload(this.totalDurationMs,{extra:{is_streaming:this.isStreaming,[V.ACK_TO_FIRST_CHUNK]:this.ackToFirstChunkMs,[V.FIRST_CHUNK_TO_RENDER]:this.firstChunkToRenderMs,[V.SEND_TO_ACK]:this.sendToAckMs}})}}const tu=.15,nu=10,ru=e=>e<=0?!1:e>=1?!0:Math.random()<e;class su extends Rt{constructor(n,r){super(n);v(this,"samplingRate");v(this,"pendingAIResponseByUserMessageId",new Map);v(this,"collectedCount",0);this.samplingRate=(r==null?void 0:r.samplingRate)??tu}startTurn(n){if(this.collectedCount>=nu||!ru(this.samplingRate))return;this.collectedCount+=1;const r={stats:new eu().setCommitCallback(this.commitCallback),measure:{channelUrl:n.channelUrl,requestId:n.requestId,startedAt:performance.now()}};this.records.set(n.requestId,r)}markUserMessageAck(n){const r=this.records.get(n.requestId);if(!r)return;r.measure.ackAt=performance.now(),r.measure.userMessageId=n.messageId;const s=this.pendingAIResponseByUserMessageId.get(n.messageId);s&&(this.pendingAIResponseByUserMessageId.delete(n.messageId),this.applyAIResponseRaw(r,s))}replaceTurnRequestId(n,r){if(n===r)return;const s=this.records.get(n);s&&(this.records.delete(n),s.measure.requestId=r,this.records.set(r,s))}cancelTurn(n){const r=this.records.get(n);r&&(this.deleteRecord(r),this.collectedCount>0&&(this.collectedCount-=1))}markAIResponseRaw(n){const r=performance.now(),s=n.aiResponse.userMessageId;if(s===void 0&&dr(this.records.values(),n.channelUrl))return;const o=this.findPendingRecord(n.channelUrl,s);if(o){this.applyAIResponseRaw(o,{...n,firstChunkAt:r});return}s===void 0||!dr(this.records.values(),n.channelUrl)||this.bufferAIResponseRaw({messageId:n.messageId,...n.channelUrl!==void 0&&{channelUrl:n.channelUrl},aiResponse:n.aiResponse,firstChunkAt:r},s)}markAIResponseVisible(n){const r=this.findRecordByAIMessageId(n);if(!r)return!1;const s=r.measure;if(s.ackAt===void 0||s.firstChunkAt===void 0||s.userMessageId===void 0)return!1;const o=performance.now();return r.stats.setDurations({ackToFirstChunkMs:s.firstChunkAt-s.ackAt,firstChunkToRenderMs:o-s.firstChunkAt,isStreaming:!!s.isStreaming,sendToAckMs:s.ackAt-s.startedAt,totalDurationMs:o-s.startedAt}).commit(),this.deleteRecord(r),!0}hasPendingAIResponse(n){return this.findRecordByAIMessageId(n)!==void 0}clearMessage(n){this.pendingAIResponseByUserMessageId.forEach((s,o)=>{s.messageId===n&&this.pendingAIResponseByUserMessageId.delete(o)});const r=this.findRecordByAIMessageId(n);r&&(this.deleteRecord(r),this.collectedCount>0&&(this.collectedCount-=1))}clearChannel(n){n&&(this.records.forEach(r=>{r.measure.channelUrl===n&&(this.deleteRecord(r),this.collectedCount>0&&(this.collectedCount-=1))}),this.pendingAIResponseByUserMessageId.forEach((r,s)=>{r.channelUrl===n&&this.pendingAIResponseByUserMessageId.delete(s)}))}clear(){this.records.clear(),this.pendingAIResponseByUserMessageId.clear(),this.collectedCount=0}findRecordByAIMessageId(n){for(const r of this.records.values())if(r.measure.aiMessageId===n)return r}findPendingRecord(n,r){if(r!==void 0){for(const o of this.records.values())if(!(o.measure.ackAt===void 0||o.measure.firstChunkAt!==void 0)&&mt(o.measure.channelUrl,n)&&o.measure.userMessageId===r)return o;return}let s;for(const o of this.records.values())if(!(o.measure.ackAt===void 0||o.measure.firstChunkAt!==void 0)&&mt(o.measure.channelUrl,n)){if(s)return;s=o}return s}applyAIResponseRaw(n,r){n.measure.firstChunkAt===void 0&&(n.measure.firstChunkAt=n.measure.ackAt===void 0?r.firstChunkAt:Math.max(r.firstChunkAt,n.measure.ackAt),n.measure.aiMessageId=r.messageId,n.measure.channelUrl=n.measure.channelUrl??r.channelUrl,n.measure.isStreaming=r.aiResponse.isStreaming)}bufferAIResponseRaw(n,r){this.pendingAIResponseByUserMessageId.has(r)||(Mn(this.pendingAIResponseByUserMessageId,100),this.pendingAIResponseByUserMessageId.set(r,n))}deleteRecord(n){this.records.delete(n.measure.requestId),n.measure.userMessageId!==void 0&&this.pendingAIResponseByUserMessageId.delete(n.measure.userMessageId)}}function ou(){let e=null,t=0;const n=(r,s)=>{if((e==null?void 0:e.key)===r)return e.promise;const o=++t,c=(e?e.promise.catch(()=>{}).then(()=>s()):s()).finally(()=>{(e==null?void 0:e.id)===o&&(e=null)});return e={key:r,id:o,promise:c},c};return n.isPending=()=>e!==null,n}const Es={isTalkToAgentViewEnabled:!0,scrollMode:"auto",newMessageIndicatorEnabled:!0,senderAvatarEnabled:!0},Or={conversation:{...Es,messageAlertSoundEnabled:!1,list:{...Es,deferredMarkdownElements:[]},header:{avatarEnabled:!0},input:{camera:{photoEnabled:!0},gallery:{photoEnabled:!0},fileEnabled:!0},fileViewer:{downloadEnabled:!0}},launcher:{unreadBadgeEnabled:!1}},Cs=e=>e?{conversation:cu(e.conversation),launcher:iu(e.launcher)}:Or,iu=e=>bt(Or.launcher,e),au=e=>{if(e.deferredMarkdownElements)return[...e.deferredMarkdownElements];const t=[];return e.markdownImageRenderMode==="complete-only"&&t.push("image"),e.markdownLinkRenderMode==="complete-only"&&t.push("link"),t},cu=e=>{const t=Or.conversation;if(!e)return t;const{list:n={},header:r={},input:s,fileViewer:o={},messageAlertSoundEnabled:i=t.messageAlertSoundEnabled,...c}=e,{camera:u={},gallery:d={},fileEnabled:m=t.input.fileEnabled}=s??{},h={...bt(t.list,c,n),deferredMarkdownElements:au(n)};return{...h,messageAlertSoundEnabled:i,list:h,header:bt(t.header,r),input:{camera:bt(t.input.camera,u),gallery:bt(t.input.gallery,d),fileEnabled:m},fileViewer:bt(t.fileViewer,o)}},bt=(e,...t)=>{const n={...e};for(const r of t)r&&Object.assign(n,Lr(r));return n},lu=e=>({userId:e.bot_userid,profileUrl:e.bot_profile_url,nickname:e.bot_nickname,replyToFile:e.reply_to_file,specialNotice:e.special_notice,specialNoticeEnabled:e.is_special_notice_enabled,showHandoffButton:e.show_handoff_button??!0,isMultipleActiveConversationsEnabled:e.is_multiple_active_conversations_enabled??!0,isUserFeedbackEnabled:e.is_user_feedback_enabled??!1,isUserFeedbackCommentOptionEnabled:e.is_user_feedback_comment_option_enabled??!1}),uu=e=>({type:e.image_type||"default_icon",imageUrl:e.image_url}),mr=e=>({enabled:e.enabled,showIndicator:e.show_indicator,toggleAllowed:e.toggle_allowed,deleteOnOff:e.delete_on_off,consentDialog:e.consent_dialog});class du{constructor(){v(this,"_channelHandlerId",null);v(this,"_connectionHandlerId",null);v(this,"_initConversationRequests",new Map);v(this,"_handleActiveChannelChangedThrottled",null);v(this,"_setupChannelHandler",()=>{const t=Date.now();this._channelHandlerId=`aiagent_channel_${t}`,this._connectionHandlerId=`aiagent_connection_${t}`,this._handleActiveChannelChangedThrottled=Qo(s=>{var o,i;(i=this._session)==null||i._updateActiveChannel({url:s.url,status:Fe(s)?"closed":"open",conversationStatus:(o=s.conversation)==null?void 0:o.status}),this._logger.debug("AIAgentEventManager: activeChannel updated",s.url)},250,{leading:!0,trailing:!1});const n=new je.GroupChannelHandler({onChannelChanged:s=>{var o,i;s.isGroupChannel()&&s.url===((o=this._session)==null?void 0:o.activeChannel.url)&&((i=this._handleActiveChannelChangedThrottled)==null||i.call(this,s))}}),r=new Ce.ConnectionHandler({onReconnectSucceeded:async()=>{await this._syncActiveChannelOnReconnect()}});this._chatClient.chatSDK.groupChannel.addGroupChannelHandler(this._channelHandlerId,n),this._chatClient.chatSDK.addConnectionHandler(this._connectionHandlerId,r),this._logger.debug("AIAgentEventManager: handlers registered",{channelHandlerId:this._channelHandlerId,connectionHandlerId:this._connectionHandlerId})});v(this,"_removeChannelHandler",()=>{this._channelHandlerId&&(this._chatClient.chatSDK.groupChannel.removeGroupChannelHandler(this._channelHandlerId),this._channelHandlerId=null),this._connectionHandlerId&&(this._chatClient.chatSDK.removeConnectionHandler(this._connectionHandlerId),this._connectionHandlerId=null),this._handleActiveChannelChangedThrottled&&(this._handleActiveChannelChangedThrottled.cancel(),this._handleActiveChannelChangedThrottled=null),this._logger.debug("AIAgentEventManager: handlers removed")});v(this,"_syncActiveChannelOnReconnect",async()=>{var n,r,s;const t=(n=this._session)==null?void 0:n.activeChannel.url;if(t)try{const i=await(await this._chatClient.chatSDK.groupChannel.getChannel(t)).refresh();i.url===t&&((s=this._session)==null||s._updateActiveChannel({url:i.url,status:Fe(i)?"closed":"open",conversationStatus:(r=i.conversation)==null?void 0:r.status}),this._logger.debug("AIAgentEventManager: activeChannel synced on reconnect",i.url))}catch(o){this._logger.error("AIAgentEventManager: failed to sync activeChannel on reconnect",o)}});v(this,"_initConversationIfNeeded",(t,n)=>{if(!t.isAIAgent||t.conversation)return Promise.resolve();const r=this._initConversationRequests.get(t.url);if(r)return r;const s=t.initConversation({aiAgentId:this.aiAgentId,initialUserMessage:n==null?void 0:n.initialUserMessage}).then(()=>{}).catch(o=>{this._logger.warn("AIAgentEventManager: initConversation failed",o)}).finally(()=>{this._initConversationRequests.delete(t.url)});return this._initConversationRequests.set(t.url,s),s});v(this,"onMessengerSettingsUpdated",t=>(this._dispatcher.subscribe(Ue.MessengerSettingsUpdated,t),()=>{this._dispatcher.unsubscribe(Ue.MessengerSettingsUpdated,t)}));v(this,"onActiveChannelUpdated",t=>(this._dispatcher.subscribe(Ue.ActiveChannelUpdated,t),()=>{this._dispatcher.unsubscribe(Ue.ActiveChannelUpdated,t)}));v(this,"onAuthTokenRefreshed",t=>(this._dispatcher.subscribe(Ue.AuthTokenRefreshed,t),()=>{this._dispatcher.unsubscribe(Ue.AuthTokenRefreshed,t)}));v(this,"onNudgeMessageReceived",t=>(this._dispatcher.subscribe(Ue.NudgeMessageReceived,t),()=>{this._dispatcher.unsubscribe(Ue.NudgeMessageReceived,t)}))}}class mu{constructor(t){v(this,"_sdkUser");v(this,"_userSession");v(this,"_dispatcher");v(this,"_activeChannel");v(this,"_updateActiveChannel",t=>{this._activeChannel=t,this._dispatcher.send(tt.ActiveChannelUpdated({channelUrl:t.url,status:t.status,conversationStatus:t.conversationStatus}))});v(this,"_updateAuthToken",t=>{this._userSession.authToken=t,this._dispatcher.send(tt.AuthTokenRefreshed())});this._sdkUser=t.sdkUser,this._userSession=t.userSession,this._dispatcher=t.dispatcher,this._activeChannel=t.activeChannel}get sdkUser(){return this._sdkUser}get userSession(){return this._userSession}get activeChannel(){return this._activeChannel}}const li=e=>{try{const t=JSON.parse(e);return typeof t=="string"?JSON.stringify(t).slice(1,-1):e.trim()}catch{return JSON.stringify(e).slice(1,-1)}},ui=e=>JSON.parse(e),hu=e=>JSON.parse(e);function fu(e,t){const[n,r]=t.split(",").map(s=>s.trim());return e==="dark"&&r||n}function gu(e){const t={};function n(r,s=""){for(const[o,i]of Object.entries(r)){const c=s?`${s}.${o}`:o;i&&typeof i=="object"&&!Array.isArray(i)?n(i,c):t[c]=i}}return n(e),t}function pu({template:e,variables:t,variableKeyPattern:n,variableValueTransformer:r}){return Object.entries(t).reduce((s,[o,i])=>{if(!r&&!["number","boolean","string"].includes(typeof i))throw new Error(`If transformer is not provided, value(${o}:${i}) must be a {string, number, or boolean}`);const c=r?r(i):String(i),u=n(o);return s.replace(u,li(c))},e)}async function _u({template:e,variables:t,variableKeyPattern:n,variableValueTransformer:r}){return(await Promise.all(Object.entries(t).map(async([o,i])=>{const c=await r(i);return{regex:n(o),transformedValue:c}}))).reduce((o,{regex:i,transformedValue:c})=>o.replace(i,li(c)),e)}var Nr=(e=>(e[e.EXTERNAL_AUTH_TOKEN_EXPIRED=1]="EXTERNAL_AUTH_TOKEN_EXPIRED",e))(Nr||{});const di=e=>typeof e=="object"&&e!==null,bs=(e,t)=>t in e&&typeof e[t]=="string"&&e[t]!=="",Eu=e=>!di(e)||!bs(e,"channel_url")||!bs(e,"ai_agent_id")?null:{channelUrl:e.channel_url,aiAgentId:e.ai_agent_id},Cu={1:Eu};function bu(e){if(!di(e)||!("cat"in e)||typeof e.cat!="number"||!("data"in e))return null;const t=e.cat,n=Cu[t];if(!n)return null;const r=n(e.data);return r?{category:t,data:r}:null}function vu(e,t,n,r){const s=gc.default.init({appId:e,modules:[new je.GroupChannelModule,new ge.AIAgentModule],localCacheEnabled:!0,options:new Ce.SendbirdChatOptions({typingIndicatorInvalidateTime:2e4}),...r,customApiHost:(r==null?void 0:r.customApiHost)??`https://api-${e}.app.delight.ai`,customWebSocketHost:(r==null?void 0:r.customWebSocketHost)??`wss://ws-${e}.app.delight.ai`});return s.addSendbirdExtensions([{version:n,product:Ce.SendbirdProduct.AI_AGENT,platform:t.platform}],{platform:t.deviceOSPlatform,version:t.deviceOSVersion},t.customData)||console.warn("Invalid Sendbird Extensions",t),s}function Su(e){const t=n=>{throw new Error(`Please initialize chat sdk with ${n}`)};typeof e.groupChannel!="object"&&t("GroupChannelModule"),typeof e.aiAgent!="object"&&t("AIAgentModule")}const yu=[400300,400301,400302,400310],Au=Nr.EXTERNAL_AUTH_TOKEN_EXPIRED.toString(),Tu=e=>`${Au}:${e}`;class Dr{constructor(t,n,r,s,o){v(this,"chatSDK");v(this,"_aiAgentId");v(this,"_externalAuthTokenExpiredEventHandlerKey");v(this,"_logger");v(this,"_cache");v(this,"_statsTrackers");v(this,"_sessionHandler");v(this,"_aiEventHandlerRegistered",!1);v(this,"connect",async(t,n,r,s)=>{if(this._logger.debug("ChatClient.connect: start",t.userId),n){this._sessionHandler=n;const o=new Ce.SessionHandler({...n,onSessionTokenRequired:this._interceptTokenRefresh(n.onSessionTokenRequired,r,s)});this.chatSDK.setSessionHandler(o)}this._registerAIEventHandler();try{return await this.chatSDK.connect(t.userId,t.authToken),await this._syncTemplatesIfNeeded(),this._logger.debug("ChatClient.connect: end",this.chatSDK.currentUser),this.chatSDK.currentUser}catch(o){const i=o;if(this.chatSDK.isCacheEnabled){if(this._isCacheRestrictedError(i))this._logger.warn("ChatClient.connect","offline connect restricted",i.message,i.code),this._logger.warn("ChatClient.connect","clear cached-data"),await this.chatSDK.clearCachedData().catch(c=>this._logger.warn("ChatClient.connect","clear cached-data failure",c));else if(this.chatSDK.currentUser)return this._logger.debug("ChatClient.connect: end (offline)",this.chatSDK.currentUser),this.chatSDK.currentUser}throw this._logger.warn("ChatClient.connect","connect failure",i.message,i.code),this.dispose(),i}});v(this,"_registerAIEventHandler",()=>{this._aiEventHandlerRegistered||(this._aiEventHandlerRegistered=!0,this.chatSDK.aiAgent.addEventHandler(this._externalAuthTokenExpiredEventHandlerKey,this._handleAIEvent))});v(this,"_handleAIEvent",t=>{var o;this._logger.debug("ChatClient.connect: EXTERNAL_AUTH_TOKEN_EXPIRED event received",t);const n=bu(t),r=typeof t.cat=="number"?t.cat:void 0;if(r!==void 0&&r!==Nr.EXTERNAL_AUTH_TOKEN_EXPIRED)return;if(!n){this._statsTrackers.aievAuthExpiredUnhandled.onPayloadParseFailed({aiAgentId:this._aiAgentId});return}if(n.data.aiAgentId!==this._aiAgentId){this._logger.debug("ChatClient.connect: ignore EXTERNAL_AUTH_TOKEN_EXPIRED for another agent",n.data);return}const s=(o=this._sessionHandler)==null?void 0:o.onExternalAuthTokenExpired;if(!s){this._statsTrackers.aievAuthExpiredUnhandled.onCallbackNotFound(n.data);return}this._logger.debug("ChatClient.connect: calling onExternalAuthTokenExpired handler",n.data),s(n.data)});v(this,"dispose",()=>{this._aiEventHandlerRegistered&&(this.chatSDK.aiAgent.removeEventHandler(this._externalAuthTokenExpiredEventHandlerKey),this._aiEventHandlerRegistered=!1),this._sessionHandler=void 0});v(this,"disconnect",async()=>{this._logger.debug("ChatClient.disconnect: start"),this.dispose(),await this.chatSDK.disconnect(),this._cache.template.clear(),this._logger.debug("ChatClient.disconnect: end")});v(this,"getChannel",async t=>this.chatSDK.groupChannel.getChannel(t));v(this,"patchContext",async(t,n,r)=>this.chatSDK.aiAgent.patchContext(t,n,r));v(this,"updateContext",async(t,n,r)=>this.chatSDK.aiAgent.updateContext(t,n,r));v(this,"requestNudgeMessage",async t=>this.chatSDK.aiAgent.requestNudgeMessage(t));v(this,"requestMessengerSettings",async t=>{var s;if(t.userId===""){const o=new Error("userId cannot be empty string for messenger settings request");throw this._logger.error("ChatClient.requestMessengerSettings: invalid userId",o),o}const n={...t,shouldSendFirstMessage:!1};this._logger.debug("ChatClient.requestMessengerSettings: requesting",n);const r=await this.chatSDK.aiAgent.requestMessengerSettings(n);return this._logger.debug("ChatClient.requestMessengerSettings: received",(s=r.active_channel)==null?void 0:s.channel_url),r});v(this,"setUserMemoryState",async t=>{this._logger.debug("ChatClient.setUserMemoryState: requesting",t);const n=await this.chatSDK.aiAgent.setUserMemoryState(t);return this._logger.debug("ChatClient.setUserMemoryState: received",n.enabled),n});v(this,"clearUserMemories",async(t={})=>{this._logger.debug("ChatClient.clearUserMemories: requesting",t),await this.chatSDK.aiAgent.clearUserMemories(t),this._logger.debug("ChatClient.clearUserMemories: completed")});v(this,"_interceptTokenRefresh",(t,n,r)=>{if(t)return async(s,o)=>{new Promise((i,c)=>t==null?void 0:t(i,c)).then(i=>{i?n==null||n(i):r==null||r(),s(i)}).catch(i=>{r==null||r(),o(i)})}});v(this,"_isCacheRestrictedError",t=>yu.some(n=>t.code===n));v(this,"_syncTemplatesIfNeeded",async()=>{var r,s;const t=(s=(r=this.chatSDK.appInfo)==null?void 0:r.aiAgentInfo)==null?void 0:s.templateListToken;if(!t)return;const n=this._cache.template.getCachedToken();if(!(n&&n===t)){this._logger.debug("ChatClient._syncTemplatesIfNeeded: syncing templates");try{const{templates:o,token:i}=await this.chatSDK.aiAgent.getMessageTemplates({limit:20});for(const{template:c}of o){const{key:u}=ui(c);this._cache.template.set(u,c)}this._cache.template.setCachedToken(i),this._logger.debug("ChatClient._syncTemplatesIfNeeded: sync completed")}catch(o){this._logger.error("ChatClient._syncTemplatesIfNeeded: error",o)}}});this.chatSDK=t,this._aiAgentId=n,this._externalAuthTokenExpiredEventHandlerKey=Tu(n),this._logger=r,this._cache=s,this._statsTrackers=o}static init(t){let n;return t.chatSDK?(Su(t.chatSDK),n=t.chatSDK):n=vu(t.appId,t.extensions,t.messengerVersion,t.chatParams),new Dr(n,t.aiAgentId,t.logger,t.cache,t.statsTrackers)}}const Iu=e=>t=>{if(!e||e.getState()==="foregrounded"){t();return}const n=e.subscribe(r=>{r==="foregrounded"&&(n(),t())});return n},xu=e=>()=>{let t=e.getState()==="backgrounded";const n=e.subscribe(r=>{r==="backgrounded"&&(t=!0)});return()=>(n(),t)},nn=new Map,mi={set:(e,t)=>{nn.set(e,t)},get:e=>{if(nn.size===0)throw new Error("AIAgent platform not configured. Ensure you are using the correct package (@sendbird/ai-agent-messenger-react or @sendbird/ai-agent-messenger-react-native).");if(e){const n=nn.get(e);if(!n)throw new Error(`AIAgent platform "${e}" is not configured.`);return{platform:e,...n}}const t=nn.entries().next().value;return{platform:t[0],...t[1]}}};class vs extends Error{constructor(n,r){const s=(r==null?void 0:r.detail)??"";super(s||`Desk API error (${n})`);v(this,"status");v(this,"code");v(this,"detail");this.name="DeskApiError",this.status=n,this.code=(r==null?void 0:r.code)??"",this.detail=s}}var $r=(e=>(e.INITIALIZED="INITIALIZED",e.PROACTIVE="PROACTIVE",e.PENDING="PENDING",e.ACTIVE="ACTIVE",e.CLOSED="CLOSED",e.WORK_IN_PROGRESS="WORK_IN_PROGRESS",e.IDLE="IDLE",e))($r||{}),Pr=(e=>(e.URGENT="URGENT",e.HIGH="HIGH",e.MEDIUM="MEDIUM",e.LOW="LOW",e))(Pr||{}),hi=(e=>(e.ERR_CREDENTIALS_NOT_PROVIDED="desk401100",e.ERR_NON_AUTHORIZED="desk401103",e.ERR_SESSION_KEY_EXPIRED="desk401106",e.ERR_SESSION_TOKEN_REVOKED="desk401107",e.ERR_USER_DEACTIVATED="desk401108",e.ERR_USER_NOT_EXIST="desk401109",e))(hi||{});const Ru=e=>e==="desk401103"||e==="desk401106"||e==="desk401107"||e==="desk401108"||e==="desk401109";class Mu{constructor(t){v(this,"_appId");v(this,"_apiHost");v(this,"_logger");v(this,"_credential",null);v(this,"_authRefreshPromise",null);v(this,"_onDeskTokenRefreshRequired",async()=>!1);v(this,"request",async(t,n)=>{const r=n.authRequired??!0,s=`${this._apiHost}${t}`;r&&this._authRefreshPromise&&(this._logger.debug("DeskApiClient: waiting for in-flight recovery..."),await this._authRefreshPromise);const o=await this._fetch(s,n);return r&&o.status===401?this._handleUnauthorized(o,s,n):this._toResult(o)});v(this,"setCredential",(t,n=async()=>!1)=>{this._authRefreshPromise=null,this._onDeskTokenRefreshRequired=n,this._credential=t});v(this,"clearCredential",()=>{this._authRefreshPromise=null,this._credential=null,this._onDeskTokenRefreshRequired=async()=>!1});v(this,"_handleUnauthorized",async(t,n,r)=>{const s=await this._parseErrorCode(t);if(!Ru(s))return this._toResult(t);if(!await this._refresh(s)||this._credential===null)return this._toResult(t);const i=await this._fetch(n,r);return this._toResult(i)});v(this,"_refresh",async t=>{if(this._authRefreshPromise)return this._logger.debug("DeskApiClient: refresh already in progress, joining..."),this._authRefreshPromise;try{return this._authRefreshPromise=this._onDeskTokenRefreshRequired({reason:t}).catch(n=>(this._logger.error("DeskApiClient: delegated recovery failed",n),!1)),await this._authRefreshPromise}finally{this._authRefreshPromise=null}});v(this,"_fetch",(t,n)=>fetch(`${t}?${this._buildParams(n.params)}`,{method:n.method,headers:this._buildHeaders(n.authRequired??!0,n.headers),...n.body?{body:JSON.stringify(this._buildBody(n.body))}:{}}));v(this,"_buildParams",t=>new URLSearchParams({sendbirdAppId:this._appId,...t}));v(this,"_buildBody",t=>({sendbirdAppId:this._appId,...t}));v(this,"_buildHeaders",(t,n)=>({"content-type":"application/json",...t&&this._credential?{sendbirdDeskToken:this._credential.deskToken}:{},...n}));v(this,"_toResult",async t=>{if(!t.ok){const r=await t.json().catch(()=>({}));throw new vs(t.status,r)}const n=await t.text();if(n)try{return JSON.parse(n)}catch{throw new vs(t.status,{})}});v(this,"_parseErrorCode",async t=>{const n=await t.clone().json().catch(()=>({}));return n==null?void 0:n.code});this._appId=t.appId,this._apiHost=t.customApiHost??`https://desk-api-${t.appId}.app.delight.ai/sapi`,this._logger=t.logger}get credential(){return this._credential}}class En{constructor(t,n){v(this,"id");v(this,"title");v(this,"status");v(this,"agent");v(this,"priority");v(this,"group");v(this,"firstResponseTime");v(this,"issuedAt");v(this,"customFields");v(this,"_client");v(this,"refresh",async()=>this._client.getTicket(this.id));this.id=t.id,this.title=t.title,this.status=t.status,this.agent=t.agent,this.priority=t.priority,this.group=t.group,this.firstResponseTime=t.firstResponseTime,this.issuedAt=t.issuedAt,this.customFields=t.customFields,this._client=n}static _fromResponse(t,n){var r;return new En({id:t.id,title:t.channelName??null,status:t.status2??$r.INITIALIZED,agent:(()=>{var o;const s=(o=t.recentAssignment)==null?void 0:o.agent;return s?{userId:s.sendbirdId??"",name:s.displayName??"",profileUrl:s.photoThumbnailUrl??""}:null})(),priority:t.priority??Pr.MEDIUM,group:t.group??0,firstResponseTime:t.firstResponseTime??-1,issuedAt:t.issuedAt??null,customFields:Object.fromEntries(((r=t.customFields)==null?void 0:r.map(s=>[s.key,s.value]))??[])},n)}}class Fr{constructor(t){v(this,"_logger");v(this,"_apiClient");v(this,"_onDeskTokenRefreshRequired");v(this,"refreshDeskAuthToken",async t=>this._apiClient.credential?this.authenticate({userId:this._apiClient.credential.userId,accessToken:t,onDeskTokenRefreshRequired:this._onDeskTokenRefreshRequired}):!1);v(this,"authenticate",async t=>{this._logger.debug("DeskClient.authenticate: start",t.userId);try{const{token:n}=await this._apiClient.request("/customers/auth/",{method:"POST",headers:{sendbirdAccessToken:t.accessToken},body:{sendbirdId:t.userId},authRequired:!1});return t.onDeskTokenRefreshRequired!==void 0&&(this._onDeskTokenRefreshRequired=t.onDeskTokenRefreshRequired),this._apiClient.setCredential({userId:t.userId,deskToken:n,chatToken:t.accessToken},this._onDeskTokenRefreshRequired),this._logger.debug("DeskClient.authenticate: end"),!0}catch(n){return this._apiClient.clearCredential(),this._logger.debug("DeskClient.authenticate: failed",n),!1}});v(this,"deauthenticate",()=>{this._apiClient.clearCredential(),this._onDeskTokenRefreshRequired=void 0,this._logger.debug("DeskClient.deauthenticate: token cleared")});v(this,"setCustomerLanguage",async t=>{this._assertAuthenticated(this._apiClient),this._logger.debug("DeskClient.setCustomerLanguage: start",t),await this._apiClient.request("/customers/language/",{method:"PATCH",body:{language:t}}),this._logger.debug("DeskClient.setCustomerLanguage: end")});v(this,"getTicket",async t=>{this._assertAuthenticated(this._apiClient);const n=await this._apiClient.request(`/tickets/${encodeURIComponent(t)}/`,{method:"GET"});return En._fromResponse(n,this)});v(this,"createTicket",async t=>{this._assertAuthenticated(this._apiClient);const n=await this._apiClient.request("/tickets/",{method:"POST",body:Lr({channelName:t.title,channelType:"SENDBIRD_JAVASCRIPT",customFields:t.customFields?JSON.stringify(t.customFields):void 0,info:JSON.stringify({ticket:{subject:t.title,requester:{name:t.name,email:this._apiClient.credential.userId}}}),priority:t.priority,groupKey:t.groupKey})});return En._fromResponse(n,this)});this._logger=t.logger,this._apiClient=new Mu(t)}static init(t){return new Fr(t)}_assertAuthenticated(t){if(t.credential==null)throw new Error("DeskClient is not authenticated")}}class Ur{constructor(){v(this,"authenticate",async t=>!1);v(this,"deauthenticate",()=>{});v(this,"refreshDeskAuthToken",async()=>!1);v(this,"setCustomerLanguage",async()=>{});v(this,"getTicket",async()=>{throw new Error("DeskClient is disabled via __SBA_USE_DESK_CLIENT__")})}static init(){return new Ur}}function wu(e){return{get:t=>e.getString(t)??null,set:(t,n)=>{e.set(t,n)},delete:t=>{e.delete?e.delete(t):e.remove&&e.remove(t)},getKeys:t=>e.getAllKeys().filter(n=>n.startsWith(t))}}const ku=1440*60*1e3,Lu=typeof __SBA_USE_DESK_CLIENT__>"u"||__SBA_USE_DESK_CLIENT__;function Ye(e){if(!e)throw new Error("Not authenticated. Call authenticate() first.")}function Ou(e,t){return Object.entries(t).every(([n,r])=>e[n]===r)}const Nu=e=>{const t={conversationInitialRender:new Dl(e),conversationNotInteractiveTimeout:new Bl(e),recoveryNotInteractiveTimeout:new Vl(e),conversationListInitialRender:new Fl(e),aievAuthExpiredUnhandled:new Ll(e),messagePendingStuck:new zl(e),userPerceivedResponseTime:new su(e),streamStalled:new Xl(e),typingIndicatorAbsentTimeout:new Ql(e),renderedContentUnusable:new Yl(e)};return{...t,clear:()=>{Object.values(t).forEach(n=>n.clear())}}};class Cn extends du{constructor(n){super();v(this,"appId");v(this,"aiAgentId");v(this,"_chatClient");v(this,"_deskClient");v(this,"_cache");v(this,"_logger");v(this,"_dispatcher");v(this,"_session",null);v(this,"language");v(this,"countryCode");v(this,"context");v(this,"queryParams");v(this,"_config");v(this,"_networkStateAdapter");v(this,"_scheduleForegroundTask");v(this,"_watchBackgrounded");v(this,"_forceCreateChannel");v(this,"_agentVersion");v(this,"_statsTrackers");v(this,"_liveMetricManager");v(this,"_operationQueue",ou());v(this,"dispose",()=>{this._operationQueue.isPending()||(this._logger.debug("AIAgent.dispose: start"),this._chatClient.dispose(),this._chatClient.chatSDK.connectionState==="OPEN"&&this._chatClient.chatSDK.disconnectWebSocket(),this._removeChannelHandler(),this._session=null,this._deskClient.deauthenticate(),this._statsTrackers.clear(),this._liveMetricManager.dispose(),this._logger.debug("AIAgent.dispose: end"))});v(this,"initConversationIfNeeded",(n,r)=>this._initConversationIfNeeded(n,r));v(this,"authenticate",n=>{if(!this.appId)return Promise.reject(new Error("appId is required"));if(!this.aiAgentId)return Promise.reject(new Error("aiAgentId is required"));const r=n&&"userId"in n?`auth:${n.userId}`:"auth:anon";return this._operationQueue(r,async()=>{var i,c,u,d,m;this._logger.debug("AIAgent.authenticate: start"),this._statsTrackers.conversationInitialRender.onAuthStart(),this._statsTrackers.conversationListInitialRender.onAuthStart();const s=this._getSessionCandidate(n),o=(i=s.userSessionCandidate)!=null&&i.userId?this._cache.messenger.getSettings(s.userSessionCandidate.userId):null;o!=null&&o.bot&&this._dispatcher.send(tt.MessengerSettingsUpdated({settings:o,source:"cache"}));try{const h=await this._chatClient.requestMessengerSettings({aiAgentId:this.aiAgentId,userId:(c=s.userSessionCandidate)==null?void 0:c.userId,language:this.language,country:this.countryCode,context:this.context,knownActiveChannelUrl:(u=o==null?void 0:o.active_channel)==null?void 0:u.channel_url,forceCreateChannel:this._forceCreateChannel,agentVersion:this._agentVersion});let f;if(h.auto_created_user)if(s.type==="manual")this._logger.warn("Received auto created user info but current session is manual. Ignoring auto created user info."),f={userId:s.userSessionCandidate.userId,authToken:s.userSessionCandidate.authToken};else{const{user_id:b,session_token:S,expire_at:p}=h.auto_created_user;this._cache.messenger.setAnonUser({userId:b,authToken:S,expireAt:p}),f={userId:b,authToken:S},this._logger.debug("AIAgent.authenticate: anonymous user created",b)}else f={userId:((d=s.userSessionCandidate)==null?void 0:d.userId)??"",authToken:((m=s.userSessionCandidate)==null?void 0:m.authToken)??""};this._cache.messenger.setSettings(f.userId,h),this._dispatcher.send(tt.MessengerSettingsUpdated({settings:h,source:"server"}));const g=(()=>{var b;return s.type==="anonymous"?_l(this._dispatcher):(b=s.userSessionCandidate)==null?void 0:b.sessionHandler})(),C=await this._chatClient.connect(f,g,b=>{var S;this._logger.debug("AIAgent: session token refreshed"),(S=this._session)==null||S._updateAuthToken(b),this._deskClient.refreshDeskAuthToken(b)},()=>{this._logger.debug("AIAgent: session token unavailable, deauthenticating desk"),this._deskClient.deauthenticate()});return await this._deskClient.authenticate({userId:f.userId,accessToken:f.authToken,onDeskTokenRefreshRequired:async({reason:b})=>{var S;if(b===hi.ERR_SESSION_KEY_EXPIRED){await new Promise(A=>setTimeout(A,2e3));const p=(S=this._session)==null?void 0:S.userSession.authToken;return p?await this._deskClient.refreshDeskAuthToken(p):!1}return!1}}),(o==null?void 0:o.language)!==h.language&&this._deskClient.setCustomerLanguage(this.language).catch(()=>{}),this._statsTrackers.conversationInitialRender.onAuthComplete(),this._statsTrackers.conversationListInitialRender.onAuthComplete(),this._session=new mu({sdkUser:C,userSession:f,activeChannel:{url:h.active_channel.channel_url,status:"open"},dispatcher:this._dispatcher}),this._setupChannelHandler(),this._logger.debug("AIAgent.authenticate: end",{userId:f.userId}),h}catch(h){throw this._statsTrackers.conversationInitialRender.onAuthError(h),this._statsTrackers.conversationListInitialRender.onAuthError(h),h}})});v(this,"deauthenticate",()=>this._operationQueue("deauth",async()=>{var r;this._logger.debug("AIAgent.deauthenticate: start");const n=(r=this._session)==null?void 0:r.userSession.userId;this._statsTrackers.clear();try{await this._chatClient.disconnect()}finally{this._deskClient.deauthenticate(),this._cache.messenger.clear(n),this._session=null,this._removeChannelHandler(),this._statsTrackers.clear()}this._logger.debug("AIAgent.deauthenticate: end")}));v(this,"createConversation",async n=>{Ye(this._session),this._logger.debug("AIAgent.createConversation: start",n);const r=await this._chatClient.requestMessengerSettings({...n,userId:this._session.userSession.userId,knownActiveChannelUrl:void 0,agentVersion:this._agentVersion}),s=r.active_channel.channel_url;return this._cache.messenger.setSettings(this._session.userSession.userId,r),this._logger.debug("AIAgent.createConversation: end",s),s});v(this,"searchConversation",async n=>{if(Ye(this._session),this._logger.debug("AIAgent.searchConversation: start",n),Object.entries(n.context).length===0)return this._logger.debug("AIAgent.searchConversation: empty context, returning empty array"),[];const r=this.chatSDK.aiAgent.createConversationListQuery({aiAgentId:n.aiAgentId,status:ge.ConversationStatus.OPEN,limit:100}),s=[];for(;r.hasNext;){const o=await r.next();for(const i of o)Ou(i.context??{},n.context)&&s.push(i.channelInfo.url)}return this._logger.debug("AIAgent.searchConversation: end",{count:s.length}),s});v(this,"closeConversation",async n=>{var s;Ye(this._session),this._logger.debug("AIAgent.closeConversation: start",n);const r=await this._chatClient.getChannel(n);((s=r.conversation)==null?void 0:s.status)===ge.ConversationStatus.OPEN?(await r.closeConversation(),this._session.activeChannel.url===n&&this._session._updateActiveChannel({url:n,status:"closed",conversationStatus:ge.ConversationStatus.CLOSED}),this._logger.debug("AIAgent.closeConversation: end")):this._logger.debug("AIAgent.closeConversation: already closed or not an AI agent conversation")});v(this,"createConversationListCollection",n=>new ei(this.chatSDK,n??{}));v(this,"patchContext",async(n,r)=>{Ye(this._session),this._logger.debug("AIAgent.patchContext: start",{channelUrl:n,context:r});const s=await this._chatClient.patchContext(this.aiAgentId,n,r);return this._logger.debug("AIAgent.patchContext: end",s),{...s,context:s.context??{}}});v(this,"updateContext",async(n,r)=>{Ye(this._session),this._logger.debug("AIAgent.updateContext: start",{channelUrl:n,context:r});const s=await this._chatClient.updateContext(this.aiAgentId,n,r);return this._logger.debug("AIAgent.updateContext: end",s),{...s,context:s.context??{}}});v(this,"getContextObject",async n=>{Ye(this._session),this._logger.debug("AIAgent.getContextObject: start",n);const s=await(await this._chatClient.getChannel(n)).getContextObject(this.aiAgentId);return this._logger.debug("AIAgent.getContextObject: end",s),{...s,context:s.context??{}}});v(this,"requestNudgeMessage",async n=>{Ye(this._session);const r=this._session;this._logger.debug("AIAgent.requestNudgeMessage: start",n);const s=await this._chatClient.requestNudgeMessage({aiAgentId:this.aiAgentId,key:n.key,context:n.context,language:this.language});if(this._logger.debug("AIAgent.requestNudgeMessage: end",s),this._session!==r){this._logger.debug("AIAgent.requestNudgeMessage: session changed during request, discarding stale nudge");return}s.status!=="ok"||!s.payload.message||this._dispatcher.send(tt.NudgeMessageReceived({message:s.payload.message,callbackUserMessage:s.payload.callback_user_message??void 0}))});v(this,"clearUserMemories",async(n={})=>{Ye(this._session);const r={...n,contextAiAgentId:n.contextAiAgentId??this.aiAgentId};this._logger.debug("AIAgent.clearUserMemories: start",r),await this._chatClient.clearUserMemories(r),this._logger.debug("AIAgent.clearUserMemories: end")});v(this,"setUserMemoryState",async n=>{Ye(this._session);const r=this._session;this._logger.debug("AIAgent.setUserMemoryState: start",n.enabled);const s={...n,contextAiAgentId:n.contextAiAgentId??this.aiAgentId},o=r.userSession.userId,i=await this._chatClient.setUserMemoryState(s);if(this._session!==r)return this._logger.debug("AIAgent.setUserMemoryState: session changed during request, discarding stale result"),mr(i);const c=this._cache.messenger.getSettings(o);if(c){const u={...c,memory:i};this._cache.messenger.setSettings(o,u),this._dispatcher.send(tt.MessengerSettingsUpdated({settings:u,source:"cache"}))}return this._logger.debug("AIAgent.setUserMemoryState: end",i.enabled),mr(i)});v(this,"refreshActiveChannel",async n=>{var c,u,d;Ye(this._session);const r=this._session,s=(n==null?void 0:n.useKnownActiveChannelUrl)??!0;this._logger.debug("AIAgent.refreshActiveChannel: start",{useKnownActiveChannelUrl:s});const o=await this._chatClient.requestMessengerSettings({aiAgentId:this.aiAgentId,userId:r.userSession.userId,language:this.language,country:this.countryCode,context:this.context,knownActiveChannelUrl:s?(u=(c=this._cache.messenger.getSettings(r.userSession.userId))==null?void 0:c.active_channel)==null?void 0:u.channel_url:void 0,forceCreateChannel:this._forceCreateChannel,agentVersion:this._agentVersion});if(this._session!==r)return this._logger.debug("AIAgent.refreshActiveChannel: session changed during refresh, discarding stale result"),((d=this._session)==null?void 0:d.activeChannel.url)??o.active_channel.channel_url;const i=o.active_channel.channel_url;return this._cache.messenger.setSettings(this._session.userSession.userId,o),this._session._updateActiveChannel({url:i,status:"open"}),this._logger.debug("AIAgent.refreshActiveChannel: end",i),i});v(this,"_getSessionCandidate",n=>n instanceof oi?{type:"manual",userSessionCandidate:this._getManualSessionInfo(n)}:n instanceof lr?{type:"anonymous",userSessionCandidate:this._getAnonymousSessionInfo()}:n&&typeof n=="object"?(this._logger.warn("Please use ManualSessionInfo instead of the old userSessionInfo format."),{type:"manual",userSessionCandidate:this._getManualSessionInfo(n)}):n===void 0?(this._logger.warn("Please use AnonymousSessionInfo instead of undefined userSessionInfo."),{type:"anonymous",userSessionCandidate:this._getAnonymousSessionInfo()}):{type:"anonymous",userSessionCandidate:null});v(this,"_getAnonymousSessionInfo",()=>{const n=this._cache.messenger.getAnonUser();return n?n.expireAt-ku<=Date.now()?(this._logger.debug("_getAnonymousSessionInfo: auto session expired, clear cache"),this._cache.messenger.clear(n.userId),null):(this._logger.debug("_getAnonymousSessionInfo: auto session info detected"),{userId:n.userId,authToken:n.authToken}):null});v(this,"_getManualSessionInfo",n=>{if(!n||n instanceof lr)throw new Error("userSessionInfo must be an instance of ManualSessionInfo");if(typeof n.userId!="string")throw new Error("userSessionInfo.userId must be a string");const r=["userId","authToken","sessionHandler"].filter(s=>!(s in n));return r.length>0&&this._logger.error(`_getManualSessionInfo: missing required keys in userSessionInfo: ${r.join(", ")}`),this._logger.debug("_getManualSessionInfo: manual session info detected"),{userId:n.userId,authToken:n.authToken,sessionHandler:n.sessionHandler}});this.appId=n.appId,this.aiAgentId=n.aiAgentId,this.language=n.language??"en",this.countryCode=n.countryCode,this.context=n.context,this._config=Cs(n.config),this.queryParams=n.queryParams,this._networkStateAdapter=n.networkStateAdapter,this._scheduleForegroundTask=Iu(n.foregroundStateAdapter),this._watchBackgrounded=n.foregroundStateAdapter&&xu(n.foregroundStateAdapter),this._forceCreateChannel=n.forceCreateChannel,this._agentVersion=n.agentVersion,this._chatClient=n.chatClient,this._deskClient=n.deskClient,this._cache=n.cache,this._logger=n.logger,this._dispatcher=n.dispatcher,this._statsTrackers=n.statsTrackers,this._liveMetricManager=new pl(this._chatClient.chatSDK),this._liveMetricManager.start()}static init(n){var g;const r=mi.get(n.platform),s=n.logger??new si(n.logLevel??kr.WARN),o=n.dispatcher??new ti(s),i=n.useMMKVStorage?wu(n.useMMKVStorage):r.keyValueStorage,c=n.useMMKVStorage?{...n.chatParams,useMMKVStorageStore:n.useMMKVStorage}:n.chatParams,u=$c({appId:n.appId,aiAgentId:n.aiAgentId,storage:i});let d;const h=Nu((C,b)=>{if(!d)throw new Error("ChatClient is not initialized.");return d.chatSDK.aiAgent.appendStat(C,b)});d=Dr.init({appId:n.appId,aiAgentId:n.aiAgentId,messengerVersion:r.messengerVersion,extensions:{platform:r.platform,deviceOSPlatform:r.deviceOSPlatform,deviceOSVersion:r.deviceOSVersion},chatParams:c,chatSDK:n.chatSDK,logger:s,cache:u,statsTrackers:h});const f=Lu?Fr.init({appId:n.appId,logger:s,customApiHost:(g=n.deskParams)==null?void 0:g.customApiHost}):Ur.init();return s.debug("AIAgent.init: created",{appId:n.appId,aiAgentId:n.aiAgentId}),new Cn({appId:n.appId,aiAgentId:n.aiAgentId,language:n.language,countryCode:n.countryCode,context:n.context,config:n.config,queryParams:n.queryParams,networkStateAdapter:r.networkStateAdapter,foregroundStateAdapter:r.foregroundStateAdapter,forceCreateChannel:n._forceCreateChannel,agentVersion:n._agentVersion,chatClient:d,deskClient:f,cache:u,logger:s,dispatcher:o,statsTrackers:h})}get chatSDK(){return this._chatClient.chatSDK}get deskClient(){return this._deskClient}get session(){return this._session}get config(){return this._config}set config(n){this._config=Cs(n)}get agentVersion(){return this._agentVersion}set agentVersion(n){this._agentVersion=n}get statsTrackers(){return this._statsTrackers}get liveMetricManager(){return this._liveMetricManager}get onLiveMetric(){return this._liveMetricManager.dispatch}set onLiveMetric(n){this._liveMetricManager.dispatch=n}get networkStateAdapter(){return this._networkStateAdapter}get logger(){return this._logger}get dispatcher(){return this._dispatcher}get cache(){return this._cache}get scheduleForegroundTask(){return this._scheduleForegroundTask}get watchBackgrounded(){return this._watchBackgrounded}}const ve=(e,t)=>{const n=l.createContext(t??null),r=({children:i,value:c})=>a.createElement(n.Provider,{value:c},typeof i=="function"?i(c):i),s=({children:i})=>a.createElement(n.Consumer,null,c=>c?typeof i=="function"?i(c):i:null),o=()=>{const i=l.useContext(n);if(!i)throw new Error(`use${e}Context must be used within a ${e}Provider`);return i};return n.displayName=`${e}Context`,r.displayName=`${e}Provider`,s.displayName=`${e}Consumer`,o.displayName=`use${e}Context`,{Context:n,Provider:r,Consumer:s,useContext:o}};function qe(e){const t=l.createContext({Template:e.template,updateTemplate:()=>{},components:e.components,updateComponent:()=>{}});function n({children:o}){const[i,c]=l.useState(()=>e.template),[u,d]=l.useState(e.components),m={Template:i,updateTemplate:h=>c(()=>h),components:u,updateComponent:(h,f)=>d(g=>({...g,[h]:f}))};return a.createElement(t.Provider,{value:m},o)}function r({template:o,children:i}){const{updateTemplate:c}=l.useContext(t);return l.useLayoutEffect(()=>{o&&c(o)},[o]),a.createElement(a.Fragment,null,i)}function s({children:o}){return a.createElement(n,null,o)}return s.defaults=e,s.useContext=()=>l.useContext(t),s.Context=t,s.Template=r,Object.keys(e.components).forEach(o=>{s[o]=function({component:c}){const{updateComponent:u}=l.useContext(t);return l.useLayoutEffect(()=>{c&&u(o,c)},[c]),null}}),s}function Du(...e){return function({children:n}){return e.reduce((r,s)=>a.createElement(s,null,r),n)}}function $u(e,t){const n=e.lastMessage;return n!=null&&n.isAdminMessage()?n.message??"":Pu(e,t)}function Pu(e,t){var r;const n=e.lastMessage;if(n!=null&&n.isUserMessage())return n.message||"";if(n!=null&&n.isAdminMessage())return n.message??"";if(n!=null&&n.isFileMessage())return n.message||n.name||"FILE";if(n!=null&&n.isMultipleFilesMessage()){if(n.message)return n.message;const s=n.fileInfoList.length;return((r=t==null?void 0:t.formatMultipleFilesCount)==null?void 0:r.call(t,s))??`${s} photos`}return e.name}function Fu(e,t,n){var i;const r=new Date,s=new Date(((i=e.lastMessage)==null?void 0:i.createdAt)||e.createdAt),o=it.differenceInMinutes(r,s);return o<1?n.justNow:o<60?n.minutesAgo(o):it.isToday(s)?n.hoursAgo(it.differenceInHours(r,s)):t(s,n.dateShortFormat)}const Uu=e=>{const t=e.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null},rn=e=>Math.max(0,Math.min(255,e)).toString(16).padStart(2,"0"),Ss=(e,t)=>{const n=rn(Math.round(t*255));if(e.startsWith("#")){const s=e.slice(1);return s.length===3||s.length===4?`#${s[0]}${s[0]}${s[1]}${s[1]}${s[2]}${s[2]}${n}`:`#${s.slice(0,6)}${n}`}const r=Uu(e);return r?`#${rn(r[0])}${rn(r[1])}${rn(r[2])}${n}`:e},Bu=(e,t)=>{if(!t)return e;const n={...e};for(const[r,s]of Object.entries(t))s&&(n[r]=s);return n},Hu=e=>e.consentDialog?"consent":e.toggleAllowed?e.enabled?"on":"off":"readonly",Gu=e=>e.length>0,zu=e=>{const t=e[0];if(!t)return e;const n=e.some(s=>Ve(s.type)),r=e.some(s=>!Ve(s.type));return n&&r?Ve(t.type)?e.filter(s=>Ve(s.type)):[t]:r?[t]:e},ys=e=>e.length===0?"empty":e.every(t=>Ve(t.type))?"images":"non_images",Vu=({currentFiles:e,incomingFiles:t,maxAttachmentCount:n})=>{const r=zu(t),s=ys(e),o=ys(r),c=s==="images"&&o==="images"?{type:"append",files:r,nextFiles:[...e,...r]}:{type:"replace",files:r,nextFiles:r};return c.nextFiles.length>n?{type:"reject",reason:"count_limit",maxAttachmentCount:n,nextFileCount:c.nextFiles.length}:c.type==="replace"&&s!=="empty"&&s!==o?{type:"confirm_replace",action:c}:{type:"apply",action:c}},yt=3,fi=6,qu=e=>e%yt===0?yt:fi,Ku=({index:e,itemCount:t})=>{const n=t%yt,r=n>0,s=r?t-n:t,o=r&&e>=s,i=o?n:yt,c=o?e-s:e%yt,u=!r&&e>=t-yt;return{columnSpan:r?fi/i:1,rowItemCount:i,isLastInRow:c===i-1,isLastRow:o||u}},gi=ve("AIAgent"),Yu=gi.Provider,Te=gi.useContext;function Wu(e){const t=ju(e);return a.createElement(Yu,{value:{_aiAgentSDK:t,chatSDK:t.chatSDK,deskClient:t.deskClient,appId:t.appId,aiAgentId:t.aiAgentId,language:t.language,countryCode:t.countryCode,context:t.context,logger:t.logger,dispatcher:t.dispatcher,cache:t.cache,networkStateAdapter:t.networkStateAdapter,queryParams:t.queryParams,config:t.config,handlers:e.handlers}},e.children)}function ju(e){var s;const t=l.useRef(null),n=l.useRef(null);if(!t.current||!n.current)t.current=Cn.init(e);else{const o=Xu(n.current,e);(o.appId||o.aiAgentId||o.chatSDK)&&(t.current.dispose(),t.current=Cn.init({...e,chatParams:o.appId?{...e.chatParams,newInstance:!0}:e.chatParams}))}n.current=e,l.useEffect(()=>()=>{var o;(o=t.current)==null||o.dispose()},[]);const r=t.current;return r.language=e.language??"en",r.countryCode=e.countryCode,r.context=e.context,r.queryParams=e.queryParams,r.config=e.config,r.agentVersion=e._agentVersion,r.onLiveMetric=(s=e.handlers)==null?void 0:s.onLiveMetric,r}function Xu(e,t){const n=t.chatSDK!==void 0&&t.chatSDK!==null;return{appId:!n&&e.appId!==t.appId,aiAgentId:e.aiAgentId!==t.aiAgentId,chatSDK:!!e.chatSDK!==n||n&&t.chatSDK!==e.chatSDK}}function le(e){const t=l.useRef(e);return t.current=e,l.useCallback((...n)=>t.current(...n),[t])}const wn=()=>{const[,e]=l.useState(0);return l.useCallback(()=>e(t=>t+1),[])};let Zu=0;function Ju(){return l.useState(()=>`${Zu++}`)[0]}const ht=(e,t,n)=>{const r=l.useRef(t),o=Ju();r.current=t,l.useEffect(()=>{var c;const i=u=>{const d=u;return Object.keys(d).forEach(h=>{d[h]=(...f)=>{var C;const g=r.current;(C=g[h])==null||C.call(g,...f)}}),d};return(c=e==null?void 0:e.groupChannel)==null||c.addGroupChannelHandler(o,i(new je.GroupChannelHandler)),()=>{var u;(u=e==null?void 0:e.groupChannel)==null||u.removeGroupChannelHandler(o)}},[e==null?void 0:e.groupChannel,o])};function Qu(e,t){return!e||!t?!0:e.url!==t.url}function Ge(e){return e!=null&&"sendingStatus"in e}function ed(e,t="##__USER_ID_IS_NOT_PROVIDED__##"){var n;return Ge(e)?((n=e.sender)==null?void 0:n.userId)===t:!1}function td(e,t){return ed(e,t)||e.isAdminMessage()?!1:e.updatedAt===0}function As(e){return"sendingStatus"in e?e.sendingStatus==="succeeded"?String(e.messageId):e.reqId:String(e.messageId)}const bn={collection:{groupChannel:{defaultOrder:je.GroupChannelListOrder.LATEST_LAST_MESSAGE},message:{defaultLimit:{next:25,prev:25},searchLimit:{next:10,prev:10}}}};function Ts(e){return!e||!Array.isArray(e)?!1:e.length!==0}function Is(e,t){return e.reduce((n,r)=>{const s=t(r);return n[s]=r,n},{})}const nd=({...e},t)=>{switch(t.type){case"update_initialized":return e.initialized=t.value.status,e;case"update_refreshing":return e.refreshing=t.value.status,e;case"update_loading":return e.loading=t.value.status,e;case"update_messages":{if(t.value.clearBeforeAction)e.messageMap=rd(t.value.messages);else{const n={...e.messageMap},r=[],s=[];t.value.messages.forEach(o=>{const i=Ge(o)?o.reqId:void 0,c=o.messageId||void 0;[i,c].forEach(u=>{if(!u)return;const d=n[u];sd(d,o,t.value.strictStreamingOrder)&&(d&&r.push(d),o.parentMessageId>0&&(d!=null&&d.parentMessage)&&o.applyParentMessage(d.parentMessage),s.push(o))})}),r.forEach(o=>{Ge(o)&&delete n[o.reqId],delete n[o.messageId]}),s.forEach(o=>{Ge(o)&&(n[o.reqId]=o),o.messageId!==0&&(n[o.messageId]=o)}),e.messageMap=n}return e}case"update_new_messages":{const n=t.value.currentUserId,r=t.value.messages.filter(s=>td(s,n));return t.value.clearBeforeAction?e.newMessageMap=Is(r,As):(r.map(o=>o.messageId).forEach(o=>delete e.newMessageMap[o]),e.newMessageMap={...e.newMessageMap,...Is(r,As)}),e}case"delete_messages":case"delete_new_messages":{const n=t.type==="delete_messages"?"messageMap":"newMessageMap";return e[n]={...e[n]},t.value.messageIds.forEach(r=>{if(r===0)return;const s=e[n][r];s&&(Ge(s)&&delete e[n][s.reqId],delete e[n][s.messageId])}),t.value.reqIds.forEach(r=>{const s=e[n][r];s&&(Ge(s)&&delete e[n][s.reqId],delete e[n][s.messageId])}),e}}},rd=e=>e.reduce((t,n)=>(Ge(n)?(t[n.reqId]=n,n.sendingStatus===De.SendingStatus.SUCCEEDED&&(t[n.messageId]=n)):t[n.messageId]=n,t),{}),sd=(e,t,n=!1)=>{var r,s;if(!Ge(e)||!Ge(t))return!0;if(n&&e&&we.isStreaming(e)&&we.isStreaming(t)){const o=((r=e.message)==null?void 0:r.length)||0,i=((s=t.message)==null?void 0:s.length)||0;if(o>i)return!1}return e.sendingStatus===De.SendingStatus.SUCCEEDED?t.sendingStatus===De.SendingStatus.SUCCEEDED:e.sendingStatus!==t.sendingStatus},od=(e=id)=>{const[{initialized:t,loading:n,refreshing:r,messageMap:s,newMessageMap:o},i]=l.useReducer(nd,{initialized:!1,loading:!0,refreshing:!1,messageMap:{},newMessageMap:{}}),c=(S,p,A,y)=>{i({type:"update_messages",value:{messages:S,clearBeforeAction:p,currentUserId:A,strictStreamingOrder:y}})},u=(S,p)=>{i({type:"delete_messages",value:{messageIds:S,reqIds:p}})},d=(S,p,A)=>{i({type:"update_new_messages",value:{messages:S,clearBeforeAction:p,currentUserId:A}})},m=(S,p)=>{i({type:"delete_new_messages",value:{messageIds:S,reqIds:p}})},h=S=>{i({type:"update_initialized",value:{status:S}})},f=S=>{i({type:"update_loading",value:{status:S}})},g=S=>{i({type:"update_refreshing",value:{status:S}})},C=Object.values(o),b=l.useMemo(()=>Array.from(new Set(Object.values(s))).sort(e),[s]);return{updateInitialized:h,updateLoading:f,updateRefreshing:g,updateMessages:c,deleteMessages:u,initialized:t,loading:n,refreshing:r,messages:b,newMessages:C,updateNewMessages:d,deleteNewMessages:m}},xs=Math.floor(Number.MAX_SAFE_INTEGER/10);function id(e,t){let n=0,r=0;return Ge(e)&&e.sendingStatus!=="succeeded"&&(n=xs),Ge(t)&&t.sendingStatus!=="succeeded"&&(r=xs),e.createdAt+n-(t.createdAt+r)}const ad=(e,t,n)=>{var o;const r={prevResultLimit:t.prev,nextResultLimit:t.next,startingPoint:n==null?void 0:n.startingPoint,replyType:n==null?void 0:n.replyType},s=(o=n==null?void 0:n.collectionCreator)==null?void 0:o.call(n,r);return s||e.createMessageCollection({...r,filter:new je.MessageFilter(r)})};function Rs(e){return e<Date.now()?bn.collection.message.searchLimit:bn.collection.message.defaultLimit}const cd=(e,t,n={})=>{var ke,P;const r=l.useRef(n);r.current=n;const s=l.useRef(t);s.current=t;const o=r.current.logger,i=r.current.startingPoint??Number.MAX_SAFE_INTEGER,c=Rs(i),u=r.current.strictStreamingOrder??!1,d=l.useRef({prev:!1,next:!1}),m=wn(),h=l.useRef({initialized:!1,apiInitialized:!1,instance:null}),{initialized:f,loading:g,refreshing:C,messages:b,newMessages:S,updateMessages:p,updateNewMessages:A,deleteNewMessages:y,deleteMessages:T,updateInitialized:I,updateLoading:L,updateRefreshing:N}=od(n==null?void 0:n.sortComparator),k=le(R=>{var x,O,U,j;if(!s.current||!s.current.url)return(x=o==null?void 0:o.error)==null?void 0:x.call(o,"[useGroupChannelMessages] channel is required");try{switch(R){case Ce.CollectionEventSource.EVENT_MESSAGE_RECEIVED:case Ce.CollectionEventSource.EVENT_MESSAGE_SENT_SUCCESS:case Ce.CollectionEventSource.SYNC_MESSAGE_FILL:case void 0:(U=(O=r.current).markAsRead)==null||U.call(O,[s.current]);break}}catch(re){(j=o==null?void 0:o.warn)==null||j.call(o,"[useGroupChannelMessages/markAsReadBySource]",re)}}),w=le((R,x)=>{var O,U,j,re,Z;if(x.length>0)switch(R){case Ce.CollectionEventSource.EVENT_MESSAGE_RECEIVED:case Ce.CollectionEventSource.SYNC_MESSAGE_FILL:{(U=(O=r.current).shouldCountNewMessages)!=null&&U.call(O)&&A(x,!1,(j=e.currentUser)==null?void 0:j.userId),(Z=(re=r.current).onMessagesReceived)==null||Z.call(re,x);break}}}),z=le(R=>{var x,O;(O=(x=r.current).onCollectionEvent)==null||O.call(x,R)}),$=le(async(R,x,O)=>new Promise((U,j)=>{var Ke,dt,ot;h.current.instance&&h.current.instance.dispose(),k(),A([],!0,(Ke=e.currentUser)==null?void 0:Ke.userId);const re=()=>{var ne,ce;const{pendingMessages:me,failedMessages:be}=h.current.instance??{};Ts(me)&&p(me,!1,(ne=e.currentUser)==null?void 0:ne.userId),Ts(be)&&p(be,!1,(ce=e.currentUser)==null?void 0:ce.userId)},Z=ad(R,O,{...r.current,startingPoint:x});h.current={apiInitialized:!1,initialized:!1,instance:Z},Z.setMessageCollectionHandler({onMessagesAdded:(me,be,ne)=>{var ce;k(me.source),w(me.source,ne),p(ne,!1,(ce=e.currentUser)==null?void 0:ce.userId,u),z({kind:"messagesAdded",source:me.source,channelUrl:R.url,messages:ne})},onMessagesUpdated:(me,be,ne)=>{var ce,_e,Ee;k(me.source),w(me.source,ne),p(ne,!1,(ce=e.currentUser)==null?void 0:ce.userId,u),me.source===Ce.CollectionEventSource.EVENT_MESSAGE_UPDATED&&((Ee=(_e=r.current).onMessagesUpdated)==null||Ee.call(_e,ne)),z({kind:"messagesUpdated",source:me.source,channelUrl:R.url,messages:ne})},onMessagesDeleted:(me,be,ne,ce)=>{const _e=ce.map(Ae=>Ae.messageId),Ee=ce.filter(Ge).map(Ae=>Ae.reqId);T(_e,Ee),y(_e,Ee),z({kind:"messagesDeleted",source:me.source,channelUrl:R.url,messages:ce})},onChannelDeleted:(me,be)=>{var ne,ce;(ce=(ne=r.current).onChannelDeleted)==null||ce.call(ne,be)},onChannelUpdated:(me,be)=>{var ne,ce;m(),(ce=(ne=r.current).onChannelUpdated)==null||ce.call(ne,be,me)},onHugeGapDetected:()=>{$(R,Number.MAX_SAFE_INTEGER,bn.collection.message.defaultLimit)}});let pe=!1;(ot=(dt=r.current).onCollectionInitializeStart)==null||ot.call(dt),Z.initialize(je.MessageCollectionInitPolicy.CACHE_AND_REPLACE_BY_API).onCacheResult((me,be)=>{var ne,ce,_e,Ee,Ae;(ce=(ne=r.current).onCacheResult)==null||ce.call(ne,me,be??[],R.url),me?(e.isCacheEnabled&&((_e=o==null?void 0:o.error)==null||_e.call(o,"[useGroupChannelMessages/onCacheResult]",me)),pe=!0):be&&((Ee=o==null?void 0:o.debug)==null||Ee.call(o,"[useGroupChannelMessages/onCacheResult]","message length:",be.length),p(Z.succeededMessages,!0,(Ae=e.currentUser)==null?void 0:Ae.userId),re(),be.length>0&&(h.current.initialized=!0,U())),z({kind:"initialized",source:"cache",channelUrl:R.url,messages:be??[],error:me})}).onApiResult((me,be)=>{var ne,ce,_e,Ee,Ae,ue,Me;(ce=(ne=r.current).onApiResult)==null||ce.call(ne,me,be??[],R.url),h.current.initialized=!0,h.current.apiInitialized=!0,me?((_e=o==null?void 0:o.warn)==null||_e.call(o,"[useGroupChannelMessages/onApiResult]",me),pe?j(me):U()):be&&((Ee=o==null?void 0:o.debug)==null||Ee.call(o,"[useGroupChannelMessages/onApiResult]","message length:",be.length),p(Z.succeededMessages,!0,(Ae=e.currentUser)==null?void 0:Ae.userId),r.current.startingPoint||(Me=(ue=r.current).onMessagesReceived)==null||Me.call(ue,be),e.isCacheEnabled&&re(),U()),z({kind:"initialized",source:"api",channelUrl:R.url,messages:be??[],error:me})})}));ht(e,{onUserBanned(R,x){var O,U,j;R.isGroupChannel()&&!Qu(R,s.current)&&(x.userId===((O=e.currentUser)==null?void 0:O.userId)?(j=(U=r.current).onCurrentUserBanned)==null||j.call(U):m())}}),l.useLayoutEffect(()=>{const R=setTimeout(async()=>{e.currentUser&&s.current&&(I(!1),L(!0),await $(s.current,i,c),L(!1),I(!0))});return()=>clearTimeout(R)},[e,(ke=e.currentUser)==null?void 0:ke.userId,(P=s.current)==null?void 0:P.url,r.current.replyType]),l.useEffect(()=>()=>{h.current.instance&&h.current.instance.dispose()},[]);const q=le(async()=>{e.currentUser&&s.current&&(N(!0),await $(s.current,Number.MAX_SAFE_INTEGER,bn.collection.message.defaultLimit),N(!1))}),Q=le(async()=>{var x;const R=h.current.instance;if(R!=null&&R.hasPrevious&&!d.current.prev)try{d.current.prev=!0;const O=await R.loadPrevious();p(O,!1,(x=e.currentUser)==null?void 0:x.userId)}catch{}finally{d.current.prev=!1}}),D=le(()=>{const{initialized:R,instance:x}=h.current;return R&&x?x.hasPrevious:!1}),G=le(async()=>{var x;const R=h.current.instance;if(R!=null&&R.hasNext&&!d.current.next)try{d.current.next=!0;const O=await R.loadNext();p(O,!1,(x=e.currentUser)==null?void 0:x.userId)}catch{}finally{d.current.next=!1}}),F=le(()=>{const{initialized:R,apiInitialized:x,instance:O}=h.current;return x&&R&&O?O.hasNext:!1}),K=R=>{var x,O,U,j;!R||R.channelUrl!==((x=s.current)==null?void 0:x.url)||(p([R],!1,(O=e.currentUser)==null?void 0:O.userId),(j=(U=r.current).onOutgoingMessageStatusChanged)==null||j.call(U,R))},he=le((R,x)=>{var O;if(!s.current||!s.current.url)throw(O=o==null?void 0:o.error)==null||O.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((U,j)=>{s.current.sendUserMessage(R).onPending(re=>{K(re),x==null||x(re)}).onSucceeded(re=>{K(re),U(re)}).onFailed((re,Z)=>{K(Z),j(re)})})}),W=le((R,x)=>{var O;if(!s.current||!s.current.url)throw(O=o==null?void 0:o.error)==null||O.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((U,j)=>{s.current.sendFileMessage(R).onPending(re=>{K(re),x==null||x(re)}).onSucceeded(re=>{K(re),U(re)}).onFailed((re,Z)=>{K(Z),j(re)})})}),Y=le((R,x,O)=>{var U;if(!s.current||!s.current.url)throw(U=o==null?void 0:o.error)==null||U.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((j,re)=>{s.current.sendMultipleFilesMessage(R).onPending(Z=>{K(Z),x==null||x(Z)}).onFileUploaded(Z=>{O==null||O(Z),m()}).onSucceeded(Z=>{K(Z),j(Z)}).onFailed((Z,pe)=>{K(pe),re(Z)})})}),X=le(async(R,x)=>{var U,j;if(!s.current||!s.current.url)throw(U=o==null?void 0:o.error)==null||U.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");const O=await s.current.updateUserMessage(R,x);return O.channelUrl===s.current.url&&p([O],!1,(j=e.currentUser)==null?void 0:j.userId),O}),M=le(async(R,x)=>{var U,j;if(!s.current||!s.current.url)throw(U=o==null?void 0:o.error)==null||U.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");const O=await s.current.updateFileMessage(R,x);return O.channelUrl===s.current.url&&p([O],!1,(j=e.currentUser)==null?void 0:j.userId),O}),J=le(async(R,x,O)=>{var U;if(!s.current||!s.current.url)throw(U=o==null?void 0:o.error)==null||U.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((j,re)=>{let Z;R.isUserMessage()&&(Z=s.current.resendMessage(R)),R.isFileMessage()&&(Z=s.current.resendMessage(R)),R.isMultipleFilesMessage()&&(Z=s.current.resendMessage(R)),Z&&("onPending"in Z&&Z.onPending(pe=>{K(pe),x==null||x(pe)}),"onFileUploaded"in Z&&Z.onFileUploaded(pe=>{O==null||O(pe),m()}),"onSucceeded"in Z&&Z.onSucceeded(pe=>{K(pe),j(pe)}),"onFailed"in Z&&Z.onFailed((pe,Ke)=>{K(Ke),re(pe)}))})}),ae=le(async R=>{var x,O,U,j;if(!s.current||!s.current.url)throw(x=o==null?void 0:o.error)==null||x.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");if(R.sendingStatus==="succeeded")R.isUserMessage()&&await s.current.deleteMessage(R),R.isFileMessage()&&await s.current.deleteMessage(R),R.isMultipleFilesMessage()&&await s.current.deleteMessage(R);else try{await((O=h.current.instance)==null?void 0:O.removeFailedMessage(R.reqId))}finally{T([],[R.reqId]),(j=(U=r.current).onLocalMessageDeleted)==null||j.call(U,R)}}),ye=le(()=>{var R;A([],!0,(R=e.currentUser)==null?void 0:R.userId)}),$e=le(async R=>{var x;if(e.currentUser&&s.current){const O=Rs(R);L(!0),p([],!0,(x=e.currentUser)==null?void 0:x.userId),await $(s.current,R,O),L(!1)}});return{initialized:f,loading:g,refreshing:C,messages:b,newMessages:S,resetNewMessages:ye,refresh:q,loadPrevious:Q,hasPrevious:D,loadNext:G,hasNext:F,sendUserMessage:he,sendFileMessage:W,sendMultipleFilesMessage:Y,updateUserMessage:X,updateFileMessage:M,resendMessage:J,deleteMessage:ae,resetWithStartingPoint:$e,_dangerous_reducer_updateMessages:p,_dangerous_reducer_deleteMessages:T}},ld=e=>e.customType==="SENDBIRD_DESK_ADMIN_MESSAGE_CUSTOM_TYPE"?!0:e.isAdminMessage()?e.message==="The channel's custom_type was updated.":!1,ud=(e,t,n)=>{const r=cd(e,t,{...n,strictStreamingOrder:!0}),s=l.useMemo(()=>r.messages.filter(o=>!ld(o)),[r.messages]);return{...r,messages:s}},dd=()=>{const e=new Set;return{publish:t=>{e.size!==0&&[...e].forEach(n=>{n(t)})},subscribe:t=>{let n=!0;return e.add(t),()=>{n&&(n=!1,e.delete(t))}}}},pi=dd(),md=({channelUrl:e,enabled:t=!0,statsTracker:n})=>{const r=l.useRef(e),s=l.useRef(t),o=l.useRef(null),i=l.useRef(!1);s.current=t;const c=l.useCallback(C=>r.current===C,[]),u=l.useCallback(()=>{i.current&&(n.clearChannel(r.current),i.current=!1)},[n]),d=l.useCallback(C=>{c(C)&&s.current&&(i.current=!0)},[c]),m=l.useCallback(({channelUrl:C,conversationId:b})=>{i.current=!0,n.markChannelJoined(b,C)},[n]),h=l.useCallback(({channelUrl:C})=>{n.clearChannel(C),i.current=!1},[n]),f=l.useCallback(C=>{if(c(C.channelUrl)){if(!s.current){o.current=C;return}o.current=null,m(C)}},[c,m]),g=l.useCallback(C=>{if(c(C.channelUrl)){if(!s.current){o.current=C;return}o.current=null,h(C)}},[c,h]);return l.useEffect(()=>{if(t){const C=o.current;if(!C||(o.current=null,C.channelUrl!==e))return;"error"in C?h(C):m(C);return}u()},[e,u,t,h,m]),l.useEffect(()=>(r.current=e,o.current=null,i.current=!1,()=>{u(),o.current=null,i.current=!1}),[e,u]),{onFetchStart:d,onFetchSuccess:f,onFetchError:g}},hd=({channelUrl:e,enabled:t=!0,scheduleForegroundTask:n,statsTracker:r})=>{const s=l.useRef(e),o=l.useRef(null),i=l.useRef(t),c=l.useRef(0),u=l.useRef(null);i.current=t;const d=l.useCallback((h=!0)=>{var g;(g=o.current)==null||g.call(o),o.current=null;const f=u.current;h&&(u.current=null),h&&f&&r.clearChannel(f)},[r]),m=l.useCallback(h=>{if(!i.current){d(),r.clearChannel(h);return}d(!1),u.current=h;const f=c.current,g=()=>{if(!i.current||f!==c.current||s.current!==h){r.clearChannel(h),u.current===h&&(u.current=null);return}r.start("ws_reconnected",h)};o.current=(n==null?void 0:n(g))??null,n||g()},[d,n,r]);return l.useEffect(()=>{t||d()},[d,t]),l.useEffect(()=>(s.current=e,c.current+=1,()=>{c.current+=1,d()}),[e,d]),{onReconnectSucceeded:m}},Gt={DEFAULT_PRIMARY:"#000000",DEFAULT_BOT_MSG_BG:"#ECECEC",WHITE:"#ffffff",BLACK:"#000000"};function _i(e){return e.length===4?`#${[...e.slice(1)].map(t=>t+t).join("")}`:e}function fd(e){const t=_i(e);return[parseInt(t.slice(1,3),16),parseInt(t.slice(3,5),16),parseInt(t.slice(5,7),16)]}function gd(e){return`#${e.map(t=>t.toString(16).padStart(2,"0")).join("")}`}function pd(e,t,n){e/=255,t/=255,n/=255;const r=Math.max(e,t,n),s=Math.min(e,t,n),o=r-s;let i=0,c=0;const u=(r+s)/2;return r!==s&&(c=u>.5?o/(2-r-s):o/(r+s)),r===e?i=(t-n)/o+(t<n?6:0):r===t?i=(n-e)/o+2:r===n&&(i=(e-t)/o+4),i/=6,[i,c,u]}function _d(e,t,n){let r,s,o;if(t===0)r=s=o=n;else{const i=function(m,h,f){return f<0&&(f+=1),f>1&&(f-=1),f<.16666666666666666?m+(h-m)*6*f:f<.5?h:f<.6666666666666666?m+(h-m)*(.6666666666666666-f)*6:m},c=n<.5?n*(1+t):n+t-n*t,u=2*n-c;r=i(u,c,e+1/3),s=i(u,c,e),o=i(u,c,e-1/3)}return[Math.round(r*255),Math.round(s*255),Math.round(o*255)]}function sn(e,t,n){const[r,s,o]=fd(e),[i,c,u]=pd(r,s,o),d=Math.max(0,Math.min(1,u*t)),m=Math.max(0,Math.min(1,c*n)),[h,f,g]=_d(i,m,d);return gd([Math.round(h),Math.round(f),Math.round(g)])}function Ed(e,t="light"){return{extraDark:sn(e,.6,1.2),dark:sn(e,.85,1.1),main:e,light:sn(e,t==="dark"?1.1:1.5,t==="dark"?.95:.9),extraLight:sn(e,t==="dark"?1.2:1.75,t==="dark"?.9:.8)}}function hr(e){const t=_i(e),n=149,r=+`0x${t[1]}${t[2]}`,s=+`0x${t[3]}${t[4]}`,o=+`0x${t[5]}${t[6]}`;return r*.299+s*.587+o*.114>n?Gt.BLACK:Gt.WHITE}function Cd(e,t,n,r,s){return{base:{primary:t,primaryContrastContent:n,background:e.background50,headerBackground:e.background50,modalContentBackground:e.background50},messageInput:{text:e.onlight.textHighEmphasis,placeholderText:e.onlight.textLowEmphasis,background:e.background100},messageIncoming:{text:s,background:r},messageOutgoing:{text:n,background:t},csat:{background:e.background100},conversation:{headerProfileSkeleton:e.background100},memoryDialog:{titleText:e.onlight.textHighEmphasis,markdownBodyText:e.onlight.textLowEmphasis,markdownLinkText:e.onlight.textHighEmphasis,positiveBackground:e.onlight.textHighEmphasis,positiveText:e.ondark.textHighEmphasis,positiveBorderColor:"transparent",negativeBackground:"transparent",negativeText:e.onlight.textHighEmphasis,negativeBorderColor:"transparent"}}}const bd=(e,t,n,r,s)=>({base:{primary:t,primaryContrastContent:n,background:e.background600,headerBackground:e.background500,modalContentBackground:e.background500},messageInput:{text:e.ondark.textHighEmphasis,placeholderText:e.ondark.textLowEmphasis,background:e.background400},messageIncoming:{text:s,background:r},messageOutgoing:{text:n,background:t},csat:{background:e.background400},conversation:{headerProfileSkeleton:e.background400},memoryDialog:{titleText:e.ondark.textHighEmphasis,markdownBodyText:e.ondark.textLowEmphasis,markdownLinkText:e.ondark.textHighEmphasis,positiveBackground:e.ondark.textHighEmphasis,positiveText:e.onlight.textHighEmphasis,positiveBorderColor:"transparent",negativeBackground:"transparent",negativeText:e.ondark.textHighEmphasis,negativeBorderColor:"transparent"}}),on={primary:{extraDark:"#491389",dark:"#6211c8",main:"#742ddd",light:"#c2a9fa",extraLight:"#dbd1ff"},secondary:{extraDark:"#066858",dark:"#027d69",main:"#259c72",light:"#69c085",extraLight:"#a8e2ab"},error:{extraDark:"#9d091e",dark:"#bf0711",main:"#de360b",light:"#f66161",extraLight:"#fdaaaa"},information:{extraDark:"#241389",dark:"#362ca9",main:"#4a48cd",light:"#a9bbfa",extraLight:"#d1dbff"},background700:"#000000",background600:"#161616",background500:"#2c2c2c",background400:"#393939",background300:"#bdbdbd",background200:"#e0e0e0",background100:"#eeeeee",background50:"#ffffff",onlight:{textHighEmphasis:"rgba(0, 0, 0, 1)",textMidEmphasis:"rgba(0, 0, 0, 0.75)",textLowEmphasis:"rgba(0, 0, 0, 0.55)",textDisabled:"rgba(0, 0, 0, 0.12)"},ondark:{textHighEmphasis:"rgba(255, 255, 255, 1)",textMidEmphasis:"rgba(255, 255, 255, 0.75)",textLowEmphasis:"rgba(255, 255, 255, 0.58)",textDisabled:"rgba(255, 255, 255, 0.12)"},overlay:{dark:"rgba(0, 0, 0, 0.55)",light:"rgba(22, 22, 22, 0.32)"}},Yn={h1:{fontSize:18,fontWeight:700},h2:{fontSize:16,fontWeight:700},subtitle1:{fontSize:16,fontWeight:500},subtitle2:{fontSize:16,fontWeight:400},body1:{fontSize:16,fontWeight:400},body2:{fontSize:14,fontWeight:500},body3:{fontSize:14,fontWeight:400},button:{fontSize:14,fontWeight:700},caption1:{fontSize:12,fontWeight:700},caption2:{fontSize:12,fontWeight:400},caption3:{fontSize:11,fontWeight:700},caption4:{fontSize:11,fontWeight:400}};function Ms(e){const t=vd(e),n=Sd(e,t),r=Ad(n,e.colors,e.selectedTheme),s=Id(e);return{selectedTheme:e.selectedTheme,palette:t,colors:r,aiAgentColorVariables:{primary_color:r.base.primary,primary_contrast_color:r.base.primaryContrastContent,bot_message_bg_color:r.messageIncoming.background,bot_message_bg_contrast_color:r.messageIncoming.text},typography:s}}function vd({selectedTheme:e,palette:t,primary:n}){const r=t!=null&&t.primary?t.primary:n?n===on.primary.main?on.primary:Ed(n,e):on.primary;return{...on,primary:r,...t}}function Sd({selectedTheme:e,primaryContrast:t,botMessageBackground:n,botMessageBackgroundContrast:r},s){const o=s.primary.main,i=t??hr(o),c=n??Gt.DEFAULT_BOT_MSG_BG,u=r??hr(c);return(e==="light"?Cd:bd)(s,o,i,c,u)}function yd(e,t,n){return typeof e=="string"?e:e[t]??n}function Ad(e,t,n){var i;if(!t||Object.keys(t).length===0)return e;const r={...e},s=r,o=e;for(const c of Object.keys(t)){const u=t[c];if(u){s[c]={...s[c]};for(const[d,m]of Object.entries(u))if(m!==void 0){const h=((i=o[c])==null?void 0:i[d])??"";s[c][d]=yd(m,n,h)}}}return r}function Td(e,t,n){const r={...e};return n.forEach(s=>{const o=t[s];o!=null&&(r[s]=o)}),r}function Id({typography:e}){if(!e)return Yn;const t={...Yn};return Object.keys(e).forEach(n=>{const r=e[n];if(r&&typeof r=="object"){const s=Yn[n],o=["fontSize","fontWeight","fontFamily","lineHeight"];t[n]=Td(s,r,o)}}),t}const{Provider:xd,useContext:Br}=ve("AIAgentTheme");function Rd({logger:e,palette:t,typography:n,colors:r,appearance:s,children:o}){const i=l.useRef(null),[c,u]=l.useState(()=>Ms({selectedTheme:(s==null?void 0:s.theme)??"light",palette:t,typography:n,colors:r,primary:s==null?void 0:s.primaryColor,botMessageBackground:s==null?void 0:s.botMessageBackgroundColor})),d=l.useCallback((m,h)=>{h&&(i.current=h);const f=(s==null?void 0:s.theme)??m,g=i.current?i.current.themes[f]:null,C={primary:s==null?void 0:s.primaryColor,primaryContrast:void 0,botMessageBackground:s==null?void 0:s.botMessageBackgroundColor,botMessageBackgroundContrast:void 0};!C.primary&&(g!=null&&g.primary_color)&&(C.primary=g.primary_color,C.primaryContrast=g.primary_contrast_color),!C.botMessageBackground&&(g!=null&&g.bot_message_bg_color)&&(C.botMessageBackground=g.bot_message_bg_color,C.botMessageBackgroundContrast=g.bot_message_bg_contrast_color);const b=Ms({selectedTheme:f,palette:t,typography:n,colors:r,...C});u(b),e==null||e.info("theme.update:",f)},[s==null?void 0:s.theme,s==null?void 0:s.primaryColor,s==null?void 0:s.botMessageBackgroundColor,t,n,r,e]);return l.useEffect(()=>{(s!=null&&s.theme||s!=null&&s.primaryColor||s!=null&&s.botMessageBackgroundColor)&&d(c.selectedTheme)},[s==null?void 0:s.theme,s==null?void 0:s.primaryColor,s==null?void 0:s.botMessageBackgroundColor]),a.createElement(xd,{value:{theme:c,updateTheme:d}},o)}const Wn=25*1024*1024,ws=1,ks=new Set(["image/png","image/jpeg","image/jpg"]),Ls=new Set(["application/pdf"]),Md={off:"off",always:"always",handed_off_only:"handed_off_only"},wd=()=>{const[e,t]=l.useState(()=>({maxAttachmentCount:ws,attachmentMode:"handed_off_only",defaultUploadSizeLimit:Wn,uploadSizeLimitPerType:new Map,supportedImageMimeTypes:ks,supportedFileMimeTypes:Ls})),n=l.useCallback(({active_channel:s,upload_restriction:o})=>{t({maxAttachmentCount:(o==null?void 0:o.max_attachment_count)??ws,attachmentMode:Md[s.attachment_mode]??"handed_off_only",defaultUploadSizeLimit:(o==null?void 0:o.default_upload_size_limit)??Wn,uploadSizeLimitPerType:new Map(Object.entries((o==null?void 0:o.upload_size_limit_per_type)??[])),supportedImageMimeTypes:new Set((o==null?void 0:o.supported_image_mime_types)??ks),supportedFileMimeTypes:new Set((o==null?void 0:o.supported_file_mime_types)??Ls)})},[]),r=l.useCallback(s=>{const{channel:o,uploadSizeLimit:i=Wn}=s,c=(d=!0)=>o!=null&&o.isAIAgent?d?nt(o):!1:!0,u=d=>{if(c())return e.defaultUploadSizeLimit??i;const m=e.defaultUploadSizeLimit??i,h=e.uploadSizeLimitPerType.get(d)??m;return Math.min(m,h)};return{maxAttachmentCount:e.maxAttachmentCount,isEnabled:()=>{if(c(!1))return!0;switch(e.attachmentMode){case"off":return!1;case"always":return!0;case"handed_off_only":return nt(o);default:return!0}},get supportedMimeTypes(){return c()?[cr]:[...e.supportedImageMimeTypes,...e.supportedFileMimeTypes]},isSupportedMimeType:d=>c()?!0:e.supportedImageMimeTypes.has(d)||e.supportedFileMimeTypes.has(d),getUploadSizeLimit:u,getUploadSizeLimitInMB:d=>u(d)/(1024*1024)}},[e]);return{updateBaseAttachmentRules:n,createAttachmentRules:r}},Os=(...e)=>{const[t,n,r]=e;if(e.length===1&&typeof t=="object"&&t!==null)return{type:"active",context:t};if(e.length===3&&typeof t=="string"&&typeof n=="string"&&typeof r=="object"&&r!==null)return{type:"specific",aiAgentId:t,channelUrl:n,context:r};throw new Error("Invalid arguments: expected (context) or (aiAgentId, channelUrl, context)")},Ot=e=>({...e,context:e.context??{}}),{Provider:kd,useContext:lt}=ve("AIAgentMessengerSession"),Ld=l.forwardRef(function({userSessionInfo:e,children:t},n){const{_aiAgentSDK:r,chatSDK:s,aiAgentId:o,logger:i}=Te(),{updateTheme:c}=Br(),[u,d]=l.useState(void 0),[m,h]=l.useState(void 0),[f,g]=l.useState(null),[C,b]=l.useState(null),[S,p]=l.useState(null),[A,y]=l.useState(null),[T,I]=l.useState(null),{updateBaseAttachmentRules:L,createAttachmentRules:N}=wd();l.useEffect(()=>{const $=r.onMessengerSettingsUpdated(({settings:D})=>{const{appearance:G,bot:F,launcher:K,memory:he}=D;c(G.selected_theme,G),p(lu(F)),y(uu(K)),I(he?mr(he):null),L(D)}),q=r.onActiveChannelUpdated(({channelUrl:D,status:G,conversationStatus:F})=>{h({url:D,status:G,conversationStatus:F})}),Q=r.onAuthTokenRefreshed(()=>{var G;const D=(G=r.session)==null?void 0:G.userSession.authToken;D&&b(F=>F?{...F,authToken:D}:null)});return()=>{$(),q(),Q()}},[r,c,L]);const k=l.useCallback(async()=>{try{const $=await r.authenticate(e),q=r.session;return g(q.sdkUser),b(q.userSession),h(q.activeChannel),d(void 0),$}catch($){throw g(null),b(null),h(void 0),d($),$}},[r,e]),w=l.useCallback(async()=>{await r.deauthenticate(),g(null),h(void 0),b(null),p(null),y(null),I(null)},[r]),z=l.useCallback(async()=>{if(!r.session){if(C)return i.debug("agentMessengerSession.refreshActiveChannel: stale call after deauthenticate, skipping"),"";throw i.error("agentMessengerSession.refreshActiveChannel: userSession is not ready"),new Error("userSession is not ready")}return r.session.userSession.userId!==(C==null?void 0:C.userId)?(i.debug("agentMessengerSession.refreshActiveChannel: stale call from previous session, skipping"),r.session.activeChannel.url):(h(void 0),await r.refreshActiveChannel())},[r,i,C]);return l.useImperativeHandle(n,()=>{const $=async()=>{if(!m)throw new Error("No active conversation. Please start a conversation first.");return await s.groupChannel.getChannel(m.url)};return{activeChannel:m,chatSDK:s,authenticate:k,deauthenticate:w,updateContext:async(...q)=>{const Q=Os(...q);if(Q.type==="active"){const F=await(await $()).updateContext(o,Q.context);return Ot(F)}const D=await s.aiAgent.updateContext(Q.aiAgentId,Q.channelUrl,Q.context);return Ot(D)},patchContext:async(...q)=>{const Q=Os(...q);if(Q.type==="active"){const F=await(await $()).patchContext(o,Q.context);return Ot(F)}const D=await s.aiAgent.patchContext(Q.aiAgentId,Q.channelUrl,Q.context);return Ot(D)},getContextObject:async()=>{const Q=await(await $()).getContextObject(o);return Ot(Q)},requestNudgeMessage:q=>r.requestNudgeMessage(q)}},[k,w,m,s,o,i,r]),a.createElement(kd,{value:{sdkUser:f,userSessionInfo:e,userSession:C,activeChannel:m,setActiveChannel:h,refreshActiveChannel:z,createConversation:r.createConversation,searchConversation:r.searchConversation,connectionError:u,aiAgentInfo:S,launcherInfo:A,memoryInfo:T,authenticate:k,deauthenticate:w,createAttachmentRules:N}},t)}),Od={ai_responding:"not_ready",conversation_closed:"ready",form_active:"ready",handoff_pending:"ready",reconnecting:"not_ready",steward:"ready",suggested_replies:"ready",system:"ready",unavailable:"not_ready"},Nd=e=>e.disabled?Od[e.disabledBy]==="ready":!0,Dd=e=>{var n,r,s,o,i;if(e.isUserMessage())return"text";const t=e.isFileMessage()?e.type:((r=(n=e.fileInfoList)==null?void 0:n[0])==null?void 0:r.mimeType)??((i=(o=(s=e.messageParams)==null?void 0:s.fileInfoList)==null?void 0:o[0])==null?void 0:i.mimeType);return t&&Ve(t)?"file_image":t&&Kt(t)?"file_video":t&&Ic(t)?"file_audio":"file_document"};let Ns=0;const $d=e=>(Ns+=1,`${e??"unknown"}:${Ns}`),vt=(e,t)=>e===void 0||t===e,Ei=(e,t)=>{!t.error&&t.messages.length>0&&e.conversationNotInteractiveTimeout.markHistoryLoaded("success",t.channelUrl)},Ci=(e,t)=>{t.error?e.conversationNotInteractiveTimeout.markHistoryLoaded("failed",t.channelUrl):e.conversationNotInteractiveTimeout.markHistoryLoaded(t.messages.length>0?"success":"verified_empty",t.channelUrl)},Pd=(e,t)=>{Ei(e,t)},Fd=(e,t)=>{Ci(e,t)},Ud=(e,t,n)=>{var o;if(!rt(e,n))return;const{hasResponseMetadata:r,...s}=Yo(e.data);r&&(t.typingIndicatorAbsentTimeout.markAIResponseStarted({channelUrl:e.channelUrl,userMessageId:s.userMessageId}),t.userPerceivedResponseTime.markAIResponseRaw({messageId:e.messageId,channelUrl:e.channelUrl,aiResponse:s}),t.streamStalled.markRawProgress({messageId:e.messageId,channelUrl:e.channelUrl,textLength:((o=e.message)==null?void 0:o.length)??0,aiResponse:s}))},Ds=(e,t)=>{t.streamStalled.clearMessage(e.messageId),t.userPerceivedResponseTime.clearMessage(e.messageId);const n=Ze(e)?e.reqId:void 0;n&&(t.messagePendingStuck.disappear({requestId:n}),t.userPerceivedResponseTime.cancelTurn(n),t.typingIndicatorAbsentTimeout.cancelTurn(n))},jn=(e,t)=>{t&&(e.conversationNotInteractiveTimeout.clearChannel(t),e.recoveryNotInteractiveTimeout.clearChannel(t),e.messagePendingStuck.clearChannel(t),e.userPerceivedResponseTime.clearChannel(t),e.typingIndicatorAbsentTimeout.clearChannel(t),e.streamStalled.clearChannel(t))},Bd=({activeChannelUrl:e,statsTrackers:t})=>{const{chatSDK:n}=Te(),{aiAgentInfo:r}=lt(),s=l.useRef(!1),o=r==null?void 0:r.userId;ht(!!e&&!!o?n:void 0,{onTypingStatusUpdated(c){if(c.url!==e)return;const u=c.getTypingUsers().some(m=>m.userId===o),d=s.current;u&&!d?t.typingIndicatorAbsentTimeout.markTypingStarted(c.url):!u&&d&&t.typingIndicatorAbsentTimeout.markTypingEnded(c.url),s.current=u}}),l.useEffect(()=>{s.current=!1},[e,o])},Hd=({enabled:e=!0,requestedChannelUrl:t,statsTrackers:n})=>{const r=l.useRef(void 0);l.useLayoutEffect(()=>{const s=r.current;if(!e){s&&(jn(n,s),r.current=void 0);return}s&&s!==t&&(jn(n,s),r.current=void 0),t&&s!==t&&(n.conversationNotInteractiveTimeout.start({channelUrl:t}),r.current=t)},[e,t,n]),l.useLayoutEffect(()=>()=>{const s=r.current;s&&(jn(n,s),r.current=void 0)},[n])},Gd=({aiAgentUserId:e,statsEnabled:t=!0,requestedChannelUrl:n,statsTrackers:r})=>{const s=l.useRef(null),o=l.useRef(null),i=l.useRef(!1),c=l.useRef(0),u=l.useRef(0),d=l.useRef(t),m=l.useMemo(()=>c.current+1,[n]);l.useLayoutEffect(()=>(i.current=!0,c.current=m,()=>{i.current=!1,c.current+=1}),[m]);const h=l.useCallback(g=>i.current&&c.current===g,[]);l.useLayoutEffect(()=>{u.current+=1,s.current=null,o.current=null},[n]),l.useLayoutEffect(()=>{const g=d.current;d.current=t,!(g||!t)&&(s.current&&(s.current.tracked=!1),o.current&&(o.current.tracked=!1))},[t]);const f=l.useCallback(g=>g.lifecycleGeneration===u.current&&vt(n,g.channelUrl),[n]);return l.useEffect(()=>{if(!t)return;const g=s.current;g&&f(g)&&(g.tracked||(Ei(r,g),g.tracked=!0));const C=o.current;C&&f(C)&&(C.tracked||(Ci(r,C),C.tracked=!0))},[t,f,r]),l.useMemo(()=>({onCollectionEvent:g=>{if(h(m)&&vt(n,g.channelUrl)){if(g.kind==="messagesDeleted"){g.messages.forEach(C=>Ds(C,r));return}t&&g.messages.forEach(C=>Ud(C,r,e))}},onCacheResult:(g,C,b)=>{if(!h(m)||!vt(n,b))return;const S={error:g,messages:C,channelUrl:b,lifecycleGeneration:u.current,tracked:!1};s.current=S,t&&(Pd(r,S),S.tracked=!0)},onApiResult:(g,C,b)=>{if(!h(m)||!vt(n,b))return;const S={error:g,messages:C,channelUrl:b,lifecycleGeneration:u.current,tracked:!1};o.current=S,t&&(Fd(r,S),S.tracked=!0)},onLocalMessageDeleted:g=>{h(m)&&vt(n,g.channelUrl)&&Ds(g,r)}}),[e,m,t,h,n,r])},zd=({enabled:e=!0,channelUrl:t,initialized:n,inputReady:r,renderedSignal:s,statsTrackers:o})=>{const i=l.useRef(!1),c=l.useRef(0);l.useEffect(()=>{c.current+=1,i.current=!1},[t,e]),l.useEffect(()=>{e&&(o.recoveryNotInteractiveTimeout.setInputEnabled(r,t),r&&o.conversationNotInteractiveTimeout.markInputReady(t))},[t,e,r,o]),l.useEffect(()=>{if(!e||!n||i.current)return;const u=c.current,d=setTimeout(()=>{c.current===u&&(o.conversationNotInteractiveTimeout.markRendered(t),i.current=!0)});return()=>clearTimeout(d)},[t,e,n,s,o])},Vd=({channelUrl:e,enabled:t=!0,statsTrackers:n})=>{const r=l.useRef(!1),s=l.useRef(e),o=l.useRef(t),i=l.useRef(0);return l.useLayoutEffect(()=>(r.current=!0,s.current=e,o.current=t,i.current+=1,()=>{r.current=!1,i.current+=1}),[e,t]),l.useCallback(async(c,u,d={})=>{if(!r.current||!o.current)return c(b=>u==null?void 0:u(b),()=>{});let m;const h=i.current,f=s.current,g=()=>r.current&&o.current&&i.current===h&&s.current===f,C=b=>g()&&vt(f,b);try{const b=await c(S=>{if(!C(S.channelUrl)){u==null||u(S);return}m=S.reqId,n.messagePendingStuck.start({requestId:S.reqId,channelUrl:S.channelUrl,messageType:Dd(S),tracksUploadProgress:d.tracksUploadProgress??!1}),u==null||u(S)},S=>{!g()||m!==S||n.messagePendingStuck.markUploadProgress(S)});return m&&(g()?n.messagePendingStuck.resolve({requestId:m}):n.messagePendingStuck.disappear({requestId:m})),b}catch(b){throw m&&(g()?n.messagePendingStuck.resolve({requestId:m}):n.messagePendingStuck.disappear({requestId:m})),b}},[n])},qd=({channelUrl:e,enabled:t=!0,statsTrackers:n})=>{const r=l.useRef(!1),s=l.useRef(e),o=l.useRef(t),i=l.useRef(0);return l.useLayoutEffect(()=>(r.current=!0,s.current=e,o.current=t,i.current+=1,()=>{r.current=!1,i.current+=1}),[e,t]),l.useCallback(async c=>{if(!r.current||!o.current)return c(()=>{});const u=i.current,d=s.current,m=()=>r.current&&o.current&&i.current===u&&s.current===d;let h=$d(d);n.userPerceivedResponseTime.startTurn({requestId:h,channelUrl:d}),n.typingIndicatorAbsentTimeout.startTurn({requestId:h,channelUrl:d});try{const f=await c(g=>{m()&&(n.userPerceivedResponseTime.replaceTurnRequestId(h,g),n.typingIndicatorAbsentTimeout.replaceTurnRequestId(h,g),h=g)});return m()?(n.userPerceivedResponseTime.markUserMessageAck({requestId:h,messageId:f.messageId}),n.typingIndicatorAbsentTimeout.markUserMessageAck({requestId:h,messageId:f.messageId})):(n.userPerceivedResponseTime.cancelTurn(h),n.typingIndicatorAbsentTimeout.cancelTurn(h)),f}catch(f){throw n.userPerceivedResponseTime.cancelTurn(h),n.typingIndicatorAbsentTimeout.cancelTurn(h),f}},[e,n])},Kd=({requestedChannelUrl:e,activeChannelUrl:t,statsEnabled:n=!0,statsTrackers:r})=>{const{aiAgentInfo:s}=lt();Bd({activeChannelUrl:t,statsTrackers:r}),Hd({enabled:n,requestedChannelUrl:e,statsTrackers:r});const o=Gd({aiAgentUserId:s==null?void 0:s.userId,statsEnabled:n,requestedChannelUrl:e,statsTrackers:r}),i=Vd({channelUrl:t,enabled:n,statsTrackers:r}),c=qd({channelUrl:t,enabled:n,statsTrackers:r});return l.useMemo(()=>({messageCallbacks:o,runWithPendingStuckStats:i,runWithUserTurnStats:c}),[o,i,c])},Mt=()=>Te()._aiAgentSDK.statsTrackers,Yd=({enabled:e=!0,channelUrl:t}={})=>{const{conversationInitialRender:n}=Mt(),{watchBackgrounded:r}=Te()._aiAgentSDK,s=l.useRef(null);return l.useLayoutEffect(()=>{n.setVisible(e)},[e,n]),l.useLayoutEffect(()=>{if(!t)return;const o=n.startSpan(t);return s.current=o,()=>{o.cancel(),s.current===o&&(s.current=null)}},[t,n]),l.useMemo(()=>({onGetChannelStart:o=>{var i;(i=s.current)==null||i.onGetChannelStart(o)},onGetChannelComplete:({channelUrl:o,conversationId:i})=>{var c;(c=s.current)==null||c.onGetChannelComplete(o,i)},onGetChannelError:({channelUrl:o,error:i})=>{var c;(c=s.current)==null||c.onGetChannelError(o,i)},onCollectionInitializeStart:()=>{var o;(o=s.current)==null||o.onGetMessagesStart()},onCollectionCacheResult:(o,i)=>{var c;(c=s.current)==null||c.onGetMessagesCacheComplete(i,o)},onCollectionApiResult:(o,i)=>{const c=s.current;if(!c)return;c.onGetMessagesComplete(i,o);const u=r==null?void 0:r();xe(()=>{u!=null&&u()?c.onRenderDiscarded():c.onRendered()})}}),[r])},jt=(e,t)=>{const n=l.useId(),r=l.useRef(t);l.useLayoutEffect(()=>{r.current=t}),l.useLayoutEffect(()=>{const s=new Ce.ConnectionHandler({onDisconnected:o=>{var i,c;return(c=(i=r.current).onDisconnected)==null?void 0:c.call(i,o)},onConnected:o=>{var i,c;return(c=(i=r.current).onConnected)==null?void 0:c.call(i,o)},onReconnectStarted:()=>{var o,i;return(i=(o=r.current).onReconnectStarted)==null?void 0:i.call(o)},onReconnectSucceeded:()=>{var o,i;return(i=(o=r.current).onReconnectSucceeded)==null?void 0:i.call(o)},onReconnectFailed:()=>{var o,i;return(i=(o=r.current).onReconnectFailed)==null?void 0:i.call(o)},onConnectionLost:()=>{var o,i;return(i=(o=r.current).onConnectionLost)==null?void 0:i.call(o)},onConnectionDelayed:o=>{var i,c;return(c=(i=r.current).onConnectionDelayed)==null?void 0:c.call(i,o)}});return e.addConnectionHandler(n,s),()=>{e.removeConnectionHandler(n)}},[e,n])},$s=()=>{const e=l.useRef(0);return{next:()=>(e.current+=1,e.current),current:()=>e.current,invalidate:()=>{e.current+=1},isCurrent:t=>t===e.current}};function Wd(e,t={}){const{shouldInitializeConversation:n=!0,initialUserMessage:r}=t,{chatSDK:s,logger:o,aiAgentId:i,_aiAgentSDK:c}=Te(),{sdkUser:u}=lt(),d=$s(),m=$s(),h=wn(),[f,g]=l.useState(void 0),[C,b]=l.useState(void 0),[S,p]=l.useState(!1),A=le(T=>{if(n&&T.isAIAgent&&!T.conversation){const I=m.next();p(!0),c.initConversationIfNeeded(T,{initialUserMessage:r}).finally(()=>{m.isCurrent(I)&&p(!1)})}});async function y(){var I,L,N,k,w,z;const T=d.next();if(!u){o.debug("useChannel.getChannel: no sdk user, skip fetching channel");return}if(o.debug("useChannel.getChannel: start"),g(void 0),b(void 0),m.invalidate(),p(!1),e){(I=t.onFetchStart)==null||I.call(t,e);try{o.debug("useChannel.getChannel: get channel",e);const $=await s.groupChannel.getChannel(e);if(!d.isCurrent(T))return;A($),g($),(N=t.onFetchSuccess)==null||N.call(t,{channelUrl:$.url,conversationId:(L=$.conversation)==null?void 0:L.id}),$.url===((k=c.session)==null?void 0:k.activeChannel.url)&&c.session._updateActiveChannel({url:$.url,status:Fe($)?"closed":"open",conversationStatus:(w=$.conversation)==null?void 0:w.status}),o.debug("useChannel.getChannel: fetched channel",$)}catch($){if(!d.isCurrent(T))return;(z=t.onFetchError)==null||z.call(t,{channelUrl:e,error:$}),$ instanceof Ce.SendbirdError&&b($),o.error("useChannel.getChannel: error",$)}}}return l.useEffect(()=>(y(),()=>{d.invalidate()}),[s,u,e,i]),l.useEffect(()=>{n&&f&&A(f)},[n]),jt(s,{async onReconnectSucceeded(){var L;if(!f){C&&await y();return}const T=d.current(),I=await f.refresh();!d.isCurrent(T)||f.url!==e||((L=t.onReconnectSucceeded)==null||L.call(t,f.url),A(I),g(I))}}),ht(s,{onChannelChanged:T=>{T.isGroupChannel()&&T.url===e&&(o.debug("useChannel.onChannelChanged: channel changed",T.url),g(T),h())}}),{channel:f,channelFetchError:C,getChannel:y,isInitializingConversation:S}}const jd=e=>{const t=e==null?void 0:e.lastMessage,n=t==null?void 0:t.extendedMessagePayload,r=n==null?void 0:n.user_input_disabled_by;if(!r)return;const s=qt(n);switch(r){case"suggested_replies":return s.hasSuggestedReplies?r:void 0;case"steward":return s.hasSteward?r:void 0;case"system":return r;default:return}},Xd=e=>{var o;const t=e==null?void 0:e.lastMessage;if(!t||!e)return!1;const n=t.extendedMessagePayload,r=qt(n).hasActiveForm,s=e.isAIAgent&&!!((o=e.conversation)!=null&&o.handedOverAt);return r&&!s},Zd=()=>{const{chatSDK:e,networkStateAdapter:t}=Te(),[n,r]=l.useState(()=>t?t.isOnline()?"connected":"reconnecting":"connected");return jt(e,{onConnected:()=>r("connected"),onDisconnected:()=>r("disconnected"),onReconnectStarted:()=>r("reconnecting"),onReconnectSucceeded:()=>r("connected"),onReconnectFailed:()=>r("disconnected"),onConnectionLost:()=>r("reconnecting")}),l.useEffect(()=>{if(t)return t.subscribe(s=>{if(!s){r("reconnecting");return}r(o=>o==="reconnecting"&&e.connectionState===Ce.ConnectionState.OPEN?"connected":o)})},[t,e]),n},Jd=3e4,Qd=({shouldApply:e,lastMessage:t,isBlockedWhileAIResponding:n,currentUserId:r})=>{const[s,o]=l.useState(!1),i=l.useRef(null),c=t&&rt(t,r)?t.createdAt:0;return l.useEffect(()=>{const u=()=>{i.current&&(clearTimeout(i.current),i.current=null),o(!1)},d=f=>{i.current&&clearTimeout(i.current),o(!0),i.current=setTimeout(()=>{o(!1),i.current=null},f)},m=Date.now()-c,h=Jd-m;return n||h<=0?u():d(h),()=>{i.current&&clearTimeout(i.current)}},[n,c]),s&&e},bi=e=>{const{chatSDK:t}=Te(),[n,r]=l.useState([]);return ht(t,{onTypingStatusUpdated(s){if(s.url===(e==null?void 0:e.url)){const o=s.getTypingUsers();r(o)}}}),n},em=({channel:e,lastMessage:t,aiAgentUserId:n,isStreamAnimating:r})=>{const[s,o]=l.useState(!1),i=bi(e);return l.useEffect(()=>{if(!t)return;const c=i.some(d=>d.userId===n),u=rt(t,n)&&(we.isStreaming(t)||r);o(u||c)},[i,t,n,r]),s},tm=({channel:e,messages:t,isStreamAnimating:n,isInitializingConversation:r})=>{const{aiAgentInfo:s,userSession:o}=lt(),i=Zd(),c=em({channel:e,lastMessage:hs(t,[De.SendingStatus.SUCCEEDED]),aiAgentUserId:(s==null?void 0:s.userId)??"",isStreamAnimating:n}),u=Qd({shouldApply:!!(e!=null&&e.isAIAgent)&&!nt(e),isBlockedWhileAIResponding:c,lastMessage:hs(t,[De.SendingStatus.PENDING,De.SendingStatus.SUCCEEDED]),currentUserId:(o==null?void 0:o.userId)??""}),d=h=>h===""?{disabled:!1,disabledBy:"",focusPolicy:"auto"}:h==="ai_responding"?{disabled:!0,disabledBy:h,focusPolicy:"preserve"}:{disabled:!0,disabledBy:h,focusPolicy:"release"};if(!e||i==="disconnected")return d("unavailable");if(i==="reconnecting")return d("reconnecting");if(Fe(e))return d("conversation_closed");if(nl(e))return d("handoff_pending");if(Xd(e))return d("form_active");const m=jd(e);return d(m||(c||u||r?"ai_responding":""))},nm=()=>{const[e,t]=l.useState(new Set),n=l.useCallback(s=>{t(o=>{if(o.has(s))return o;const i=new Set(o);return i.add(s),i})},[]),r=l.useCallback(s=>{t(o=>{if(!o.has(s))return o;const i=new Set(o);return i.delete(s),i})},[]);return{isAnimating:e.size>0,start:n,stop:r}},{Provider:rm}=ve("AIAgentConversation");function sm({children:e,channelUrl:t,onChannelDeleted:n,onMessagesReceived:r,onMessagesUpdated:s,onConversationStatusChanged:o,onConversationClosedViaDispatcher:i,onBeforeSendMessage:c,onAfterSendMessage:u=fe,shouldMarkAsRead:d=!0,conversationStatsEnabled:m=!0,shouldInitializeConversation:h=!0,initialUserMessage:f,shouldCountNewMessages:g=()=>!1,sortComparator:C}){var P,R;const b=()=>d&&(w==null?void 0:w.markAsRead()),{_aiAgentSDK:S,chatSDK:p,logger:A,dispatcher:y}=Te(),T=Mt(),I={channelUrl:t,enabled:m},L=md({...I,statsTracker:T.conversationNotInteractiveTimeout}),N=hd({...I,scheduleForegroundTask:S.scheduleForegroundTask,statsTracker:T.recoveryNotInteractiveTimeout}),k=Yd(I),{channel:w,channelFetchError:z,getChannel:$,isInitializingConversation:q}=Wd(t,{shouldInitializeConversation:h,initialUserMessage:f,onFetchStart:x=>{L.onFetchStart(x),k.onGetChannelStart(x)},onFetchSuccess:x=>{L.onFetchSuccess(x),k.onGetChannelComplete(x)},onFetchError:x=>{L.onFetchError(x),k.onGetChannelError(x)},onReconnectSucceeded:N.onReconnectSucceeded}),Q=w==null?void 0:w.url,D=Kd({requestedChannelUrl:t,activeChannelUrl:Q,statsEnabled:m,statsTrackers:T}),G=ud(p,w,{replyType:De.ReplyType.ONLY_REPLY_TO_CHANNEL,shouldCountNewMessages:g,logger:A,markAsRead:b,sortComparator:C,onChannelDeleted:n,onMessagesReceived:x=>r==null?void 0:r(x),onMessagesUpdated:x=>s==null?void 0:s(x),onCollectionInitializeStart:()=>{k.onCollectionInitializeStart()},onApiResult:(x,O,U)=>{k.onCollectionApiResult(x,U),D.messageCallbacks.onApiResult(x,O,U)},onCacheResult:(x,O,U)=>{k.onCollectionCacheResult(x,U),D.messageCallbacks.onCacheResult(x,O,U)},onCollectionEvent:x=>{D.messageCallbacks.onCollectionEvent(x),pi.publish(x)},onLocalMessageDeleted:x=>{D.messageCallbacks.onLocalMessageDeleted(x)},onOutgoingMessageStatusChanged:x=>{w&&S.liveMetricManager.track({type:"outgoingMessage",channel:w,message:x})}}),F=nm(),K=tm({channel:w,messages:G.messages,isStreamAnimating:F.isAnimating,isInitializingConversation:q});zd({enabled:m,channelUrl:Q,initialized:G.initialized,inputReady:Nd(K),renderedSignal:G.messages,statsTrackers:T}),l.useEffect(()=>{b()},[d,w]);const he=(P=w==null?void 0:w.conversation)==null?void 0:P.status;l.useEffect(()=>{he&&(o==null||o(he))},[he,o]),l.useEffect(()=>{const x=async O=>{const U=typeof(O==null?void 0:O.channelUrl)=="string";w&&U&&O.channelUrl!==w.url||(A.debug("conversation.dispatcher: try to close conversation",w),w!=null&&w.conversation&&w.conversation.status===ge.ConversationStatus.OPEN&&(await w.closeConversation(),i==null||i()))};return y.subscribe(Ue.ConversationClose,x),()=>{y.unsubscribe(Ue.ConversationClose,x)}},[y,w,A,(R=w==null?void 0:w.conversation)==null?void 0:R.status,i]);const W=le(()=>G.loadPrevious()),Y=le(()=>G.loadNext()),X=le(async x=>{try{await G.deleteMessage(x)}finally{x.sendingStatus!=="succeeded"&&D.messageCallbacks.onLocalMessageDeleted(x)}}),M=le(x=>x.isUserMessage()?D.runWithUserTurnStats(O=>D.runWithPendingStuckStats(U=>G.resendMessage(x,j=>{O(j.reqId),U(j)}),void 0)):D.runWithPendingStuckStats((O,U)=>G.resendMessage(x,O,U),void 0,{tracksUploadProgress:x.isMultipleFilesMessage()})),J=le(()=>G.resetNewMessages()),ae=le(async x=>{var U;if(((U=w==null?void 0:w.conversation)==null?void 0:U.status)===ge.ConversationStatus.CLOSED)throw new Error("Conversation is closed");c&&(x=await c(x));const O=await D.runWithUserTurnStats(j=>D.runWithPendingStuckStats(re=>G.sendUserMessage(x,Z=>{j(Z.reqId),re(Z)}),u));return u==null||u(O),O}),ye=le(async x=>{var U;if(((U=w==null?void 0:w.conversation)==null?void 0:U.status)===ge.ConversationStatus.CLOSED)throw new Error("Conversation is closed");c&&(x=await c(x));const O=await D.runWithPendingStuckStats(j=>G.sendFileMessage(x,j),u);return u==null||u(O),O}),$e=le(async x=>{var U;if(((U=w==null?void 0:w.conversation)==null?void 0:U.status)===ge.ConversationStatus.CLOSED)throw new Error("Conversation is closed");c&&(x=await c(x));const O=await D.runWithPendingStuckStats((j,re)=>G.sendMultipleFilesMessage(x,j,re),u,{tracksUploadProgress:!0});return u==null||u(O),O}),ke={_statsEnabled:m,conversation:(w==null?void 0:w.conversation)??void 0,actions:{setUserMemoryState:S.setUserMemoryState},channelSource:{channel:w,error:z,refetch:()=>$(),closeConversation:async()=>{Fe(w)||await(w==null?void 0:w.closeConversation())}},messageSource:{messages:G.messages,newMessages:G.newMessages,initialized:G.initialized,loadPrevious:W,loadNext:Y,deleteMessage:X,resendMessage:M,resetNewMessages:J,sendUserMessage:ae,sendFileMessage:ye,sendMultipleFilesMessage:$e},state:{streamAnimation:F,input:K}};return a.createElement(rm,{value:ke},e)}function om(e,t,n){var p,A,y,T,I,L,N,k,w,z;const[r,s]=l.useState(!1),[o,i]=l.useState(null),[c,u]=l.useState([]),[d,m]=l.useState(null),h=l.useRef(!1),f=le(()=>{var $;return($=n==null?void 0:n.onListRequestStart)==null?void 0:$.call(n)}),g=le($=>{var q;return(q=n==null?void 0:n.onListRequestComplete)==null?void 0:q.call(n,$)}),C=l.useCallback(async $=>{f();try{await $.loadMore(),g()}catch(q){throw g(q),q}},[f,g]),b=l.useCallback(async()=>{if(!h.current&&e.currentUser){h.current=!0,s(!1),i(null),u([]);try{d==null||d.dispose();const $=new ei(e,t);$.setConversationListCollectionHandler({onChannelsAdded:()=>{u($.channels)},onChannelsUpdated:()=>{u($.channels)},onChannelsDeleted:()=>{u($.channels)}}),await C($),u($.channels),m($),i(null)}catch($){m(null),i($)}finally{s(!0),h.current=!1}}},[e,e.currentUser,(p=t.filter)==null?void 0:p.aiAgentChannelFilter,(y=(A=t.filter)==null?void 0:A.aiAgentConversationStatusFilter)==null?void 0:y.join(),(I=(T=t.filter)==null?void 0:T.aiAgentIds)==null?void 0:I.join(),(L=t.filter)==null?void 0:L.deskChannelFilter,(k=(N=t.filter)==null?void 0:N.pinnedChannelUrls)==null?void 0:k.join(),(w=t.filter)==null?void 0:w.copilotConversationOnly,(z=t.filter)==null?void 0:z.copilotSupportChannelUrl,t.limit,C]),S=l.useCallback(async()=>{if(d)try{await d.loadMore(),u(d.channels)}catch($){i($)}},[d]);return jt(e,{onConnected:()=>b()}),l.useEffect(()=>{b()},[b]),l.useEffect(()=>()=>{h.current=!1,d==null||d.dispose()},[d]),{initialized:r,error:o,channels:c,loadMore:S}}const vi=e=>{var s;const{aiAgentId:t,queryParams:n}=Te(),r=(s=n==null?void 0:n.conversationListParams)==null?void 0:s.filter;return{aiAgentIds:[t],aiAgentConversationStatusFilter:[ge.ConversationStatus.CLOSED,ge.ConversationStatus.OPEN],...r,...e}},im=({enabled:e=!0}={})=>{const{conversationListInitialRender:t}=Mt(),{watchBackgrounded:n}=Te()._aiAgentSDK,r=l.useRef(null);return l.useLayoutEffect(()=>{t.setVisible(e)},[e,t]),l.useLayoutEffect(()=>{const s=t.startSpan();return r.current=s,()=>{s.cancel(),r.current===s&&(r.current=null)}},[t]),l.useMemo(()=>({onListRequestStart:()=>{var s;(s=r.current)==null||s.onListRequestStart()},onListRequestComplete:s=>{const o=r.current;if(!o||(o.onListRequestComplete(s),s))return;const i=n==null?void 0:n();xe(()=>{i!=null&&i()?o.onRenderDiscarded():o.onRendered()})}}),[n])},{Provider:am}=ve("AIAgentConversationList");function cm({conversationListLimit:e,conversationListFilter:t,conversationListStatsEnabled:n=!0,children:r}){var h;const{chatSDK:s,queryParams:o}=Te(),i=e??((h=o==null?void 0:o.conversationListParams)==null?void 0:h.limit),c=vi(t),u=im({enabled:n}),d=om(s,{limit:i,filter:c},{onListRequestStart:()=>{u.onListRequestStart()},onListRequestComplete:f=>{u.onListRequestComplete(f)}}),m={listSource:{initialized:d.initialized,error:d.error??void 0,channels:d.channels,loadMore:()=>d.loadMore()}};return a.createElement(am,{value:m},r)}function lm(e){let t="pending",n=e.then(r=>{t="resolved",n=r}).catch(r=>{t="rejected",n=r});return{get value(){if(t==="resolved")return n;throw n}}}const{Provider:um,useContext:dm}=ve("MessageTemplateFetching");function mm({children:e,internalVariables:t}){const n=l.useRef({}),r=l.useRef({}),[s,o]=l.useState({}),i=l.useCallback((d,m)=>{o(h=>({...h,[d]:{fetching:!1,error:!1,...h[d],...m}}))},[]),c=l.useCallback(async({onRequestTemplate:d,onGetCachedTemplate:m,templateKey:h,suspense:f=!1})=>{const g=m(h);if(g)return g;const C=r.current[h];if(C)return C;f||i(h,{fetching:!0});const b=d(h).catch(S=>{throw f||i(h,{error:!0}),S}).finally(()=>{f||i(h,{fetching:!1}),delete r.current[h]});return r.current[h]=b,b},[i]),u={internalVariables:t,fetchTemplate:c,suspend:(d,m)=>{if(n.current[d])return n.current[d];const h=lm(m());return n.current[d]=h,h},getIsFetching:d=>{var m;return((m=s[d])==null?void 0:m.fetching)??!1},getHasError:d=>{var m;return((m=s[d])==null?void 0:m.error)??!1}};return a.createElement(um,{value:u},e)}const hm="remove_powered_by",Hr=(e,t)=>{var s,o;const{chatSDK:n}=Te(),{aiAgentInfo:r}=lt();if(e==="handoff-button"){const i=!!((s=t==null?void 0:t.conversation)!=null&&s.handoff);return!!(t!=null&&t.isAIAgent)&&!!(r!=null&&r.showHandoffButton)&&i&&Mr(t)}if(e==="special-notice")return!!(t!=null&&t.isAIAgent)&&!!(r!=null&&r.specialNoticeEnabled)&&!!(r!=null&&r.specialNotice);if(e==="powered-by"){const i=(o=n==null?void 0:n.appInfo)==null?void 0:o.applicationAttributes;return l.useMemo(()=>!(Array.isArray(i)&&i.includes(hm)),[i])}throw new Error("Unsupported feature")},fm={required:"This question is required",minLength:e=>`Minimum ${e} characters required`,maxLength:e=>`Maximum ${e} characters allowed`,min:e=>`Minimum value is ${e}`,max:e=>`Maximum value is ${e}`,minSelect:e=>`Select at least ${e} options`,maxSelect:e=>`Select at most ${e} options`,regex:"Invalid format",invalidSelection:"Invalid selection"},gm={getValueOrDefault:e=>e.value??e.default_value??null,validate:(e,t,n)=>{const r=t;if(e.required&&(!r||r.trim()===""))return{isValid:!1,error:n.required};if(!r)return{isValid:!0};const{rules:s}=e;if(s){if(s.min_length!==void 0&&r.length<s.min_length)return{isValid:!1,error:typeof n.minLength=="function"?n.minLength(s.min_length):n.minLength};if(s.max_length!==void 0&&r.length>s.max_length)return{isValid:!1,error:typeof n.maxLength=="function"?n.maxLength(s.max_length):n.maxLength};if(s.regex&&!new RegExp(s.regex).test(r))return{isValid:!1,error:n.regex}}return{isValid:!0}}},pm={getValueOrDefault:e=>e.value??e.default_value??null,validate:(e,t,n)=>{const r=t;if(e.required&&r===null)return{isValid:!1,error:n.required};if(r===null)return{isValid:!0};const{rules:s}=e;if(s){if(s.min!==void 0&&r<s.min)return{isValid:!1,error:typeof n.min=="function"?n.min(s.min):n.min};if(s.max!==void 0&&r>s.max)return{isValid:!1,error:typeof n.max=="function"?n.max(s.max):n.max}}return{isValid:!0}}},_m={getValueOrDefault:e=>e.value??e.default_value??null,validate:(e,t,n)=>{const r=t;return e.required&&!r?{isValid:!1,error:n.required}:r&&!e.options.includes(r)?{isValid:!1,error:n.invalidSelection}:{isValid:!0}}},Em={getValueOrDefault:e=>e.values??e.default_values??null,validate:(e,t,n)=>{const r=t;if(e.required&&(!r||r.length===0))return{isValid:!1,error:n.required};if(!r||r.length===0)return{isValid:!0};if(r.filter(i=>!e.options.includes(i)).length>0)return{isValid:!1,error:n.invalidSelection};const{rules:o}=e;if(o){if(o.min_select!==void 0&&r.length<o.min_select)return{isValid:!1,error:typeof n.minSelect=="function"?n.minSelect(o.min_select):n.minSelect};if(o.max_select!==void 0&&r.length>o.max_select)return{isValid:!1,error:typeof n.maxSelect=="function"?n.maxSelect(o.max_select):n.maxSelect}}return{isValid:!0}}},Cm={text:gm,number:pm,"single-select":_m,"multi-select":Em},bm={getValueOrDefault:()=>null,validate:()=>({isValid:!1})};function Si(e){return Cm[e.type]||bm}function Ps(e){return Si(e).getValueOrDefault(e)}function vm(e,t,n={}){const r={...fm,...n};return Si(e).validate(e,t,r)}const Sm=(e,t={})=>{const{labels:n={},onSubmit:r,onCancel:s}=t,[o,i]=l.useState({}),[c,u]=l.useState(()=>{const b={};return e.fields.forEach(S=>{b[S.key]=Ps(S)}),b}),d=l.useMemo(()=>e.submitted_at?"submitted":e.canceled_at?"canceled":"draft",[e.submitted_at,e.canceled_at]);l.useEffect(()=>{if(d==="submitted"||d==="canceled"){const b={};let S=!1;e.fields.forEach(p=>{const A=Ps(p);JSON.stringify(c[p.key])!==JSON.stringify(A)&&(S=!0),b[p.key]=A}),S&&u(b)}},[d]);const m=(b,S)=>{u(p=>({...p,[b]:S})),i(p=>({...p,[b]:void 0}))},h=e.fields.map(b=>{var A,y,T;const S=c[b.key]??null,p={key:b.key,label:b.label,error:o[b.key],required:b.required};return b.type==="text"?{...p,type:"text",layout:b.layout,value:S,...b.placeholder&&{placeholder:b.placeholder},...((A=b.rules)==null?void 0:A.max_length)&&{maxLength:b.rules.max_length}}:b.type==="number"?{...p,type:"number",layout:b.layout,value:S,...b.placeholder&&{placeholder:b.placeholder},...((y=b.rules)==null?void 0:y.max)&&{max:b.rules.max}}:b.type==="single-select"?{...p,type:"single-select",layout:b.layout,value:S,options:b.options}:b.type==="multi-select"?{...p,type:"multi-select",layout:b.layout,value:S,options:b.options,...((T=b.rules)==null?void 0:T.max_select)&&{maxSelect:b.rules.max_select}}:{...p,type:"unknown",layout:"default",value:null}});return{state:d,fields:h,getField:b=>h.find(S=>S.key===b),updateFieldValue:m,submit:async()=>{const b={};let S=!1;for(const p of e.fields){const A=c[p.key]??null,y=vm(p,A,n);y.isValid||(b[p.key]=y.error,S=!0)}if(i(b),!S&&r){const p={};e.fields.forEach(A=>{p[A.key]=c[A.key]??null}),await r(p)}},cancel:async()=>{await(s==null?void 0:s())}}},ym=({isMessengerOpened:e,onConversationStarted:t})=>{const{_aiAgentSDK:n,aiAgentId:r,language:s,countryCode:o,context:i}=Te(),{createConversation:c,userSession:u}=lt(),[d,m]=l.useState(null),h=u==null?void 0:u.userId;l.useEffect(()=>{if(m(null),!(e||!h))return n.onNudgeMessageReceived(b=>m(S=>({seq:((S==null?void 0:S.seq)??0)+1,response:b})))},[n,e,h]);const f=()=>m(null),g=l.useRef(!1),C=async()=>{var S;if(!d||g.current)return;g.current=!0,m(null);const b=n.session;try{const p=await c({aiAgentId:r,language:s,country:o,context:i});if(n.session!==b)return;(S=n.session)==null||S._updateActiveChannel({url:p,status:"open"}),t({channelUrl:p,initialUserMessage:d.response.callbackUserMessage})}finally{g.current=!1}};return{nudgeMessage:e?null:(d==null?void 0:d.response)??null,nudgeMessageKey:(d==null?void 0:d.seq)??0,dismissNudgeMessage:f,startNudgeConversation:C}},Am=e=>{const{chatSDK:t,handlers:n,logger:r}=Te(),{aiAgentInfo:s}=lt(),o=l.useRef(new Set),i=l.useRef(new Set),c=(m,h)=>{if(!(n!=null&&n.onCustomEvent)||!(s!=null&&s.userId)||!rt(m,s.userId))return;const f=m.messageId;if(we.isStreaming(m)){i.current.add(f);return}h==="updated"&&!i.current.has(f)||(r.debug("useCustomEventForMessageReceive: bot-message-received",m),n.onCustomEvent({type:"bot-message-received",data:{message:m}}),i.current.delete(f))},u=l.useCallback(m=>{if(n!=null&&n.onCustomEvent&&m.isAdminMessage()&&m.customType==="user_action_required"&&!o.current.has(m.messageId)){const h=qo(m.data);Array.isArray(h.history)&&h.history.length===0&&(r.debug("useCustomEventForMessageReceive: user_action_required",h),n.onCustomEvent({type:"user-action-requested",data:h}),o.current.add(m.messageId))}},[n,r]),d=(m,h,f)=>{m.url===e&&(c(h,f),u(h))};return ht(t,{onMessageReceived:(m,h)=>d(m,h,"received"),onMessageUpdated:(m,h)=>d(m,h,"updated")}),{checkForUserActionRequired:u}},Tm=e=>{if(e==null||typeof e!="object")return;const t="thinking_message"in e?e.thinking_message:void 0;return typeof t=="string"&&t?t:void 0},yi=e=>{const{aiAgentInfo:t}=lt(),n=bi(e);if(Fe(e))return null;const r=n[0];if(!r)return null;const s=r.userId===(t==null?void 0:t.userId),o=s?Tm(r.metaData):void 0;return{user:s?t:r,isBot:s,thinkingMessage:o}},Im=(e,t,{enabled:n=!0,idleMs:r=1e3}={})=>{const s=l.useRef(null),o=l.useRef(t),i=l.useRef(t),c=l.useRef(!1);o.current=t,l.useEffect(()=>{if(s.current&&(clearTimeout(s.current),s.current=null),!n||!e){(c.current?i.current:o.current)(!1),c.current=!1,i.current=o.current;return}c.current=!0,i.current=o.current,i.current(!0),s.current=setTimeout(()=>{s.current=null,i.current(!1),c.current=!1,i.current=o.current},r)},[n,r,e]),l.useEffect(()=>()=>{s.current&&(clearTimeout(s.current),s.current=null),(c.current?i.current:o.current)(!1),c.current=!1,i.current=o.current},[])},xm=(e=1e4)=>{const t=new Map;let n=e;return{shouldAnnounce:c=>{const u=Date.now(),d=t.get(c);return d!==void 0&&u-d<n?!1:(t.set(c,u),!0)},setInterval:c=>{n=c},reset:()=>{t.clear()}}},Rm=(e,t,n=1e4,r=!0)=>{const s=l.useRef(null),o=l.useRef(null),i=l.useRef(!1);s.current||(s.current=xm(n));const c=(e==null?void 0:e.nickname.trim())||null,u=(e==null?void 0:e.userId)??c;l.useEffect(()=>{var d;(d=s.current)==null||d.setInterval(n)},[n]),l.useEffect(()=>{var h;if(!r){i.current=!1,o.current=u;return}if(!u||!c){i.current=!1,o.current=null;return}const d=!i.current,m=o.current!==u;i.current=!0,o.current=u,!(!d&&!m)&&(h=s.current)!=null&&h.shouldAnnounce(u)&&t(c)},[u,c,r,t])},Mm=({csat:e,csatPayload:t,isRenderableCSAT:n,isExpiredNow:r,announceStatus:s,onSubmittedAnnounced:o})=>{const i=(t==null?void 0:t.csat_submitted_label)??"",c=l.useRef(n&&typeof e=="number"),u=l.useRef(n&&r);l.useEffect(()=>{n&&i&&(typeof e!="number"||c.current||(c.current=!0,s&&(s({event:"csatSubmitted",submittedLabel:i}),o==null||o())))},[s,e,n,o,i]),l.useEffect(()=>{n&&r&&(u.current||(u.current=!0,s==null||s({event:"csatExpired"})))},[s,r,n])},Gr=({channel:e,userSession:t,aiAgentInfo:n})=>{if(!t||!n||!e)return{fallbackIcon:void 0,url:void 0,title:""};const r=ni(e,t.userId),s={ai(o){return{fallbackIcon:o,url:n.profileUrl,title:n.nickname}},human(o){return{fallbackIcon:o,url:r==null?void 0:r.profileUrl,title:(r==null?void 0:r.nickname)||n.nickname}},channel(o){return{fallbackIcon:o,url:e==null?void 0:e.coverUrl,title:(e==null?void 0:e.name)??""}}};return e.isAIAgent?nt(e)?s.human("agent"):s.ai("delight"):e.isDesk?s.human("agent"):s.channel("user")},Fs=e=>l.useReducer((t,n)=>({...t,...n}),e);var Xe=(e=>(e.AI_AGENT_CSAT_5="AI_AGENT_CSAT_5",e.AI_AGENT_CSAT_5_WITH_CRE="AI_AGENT_CSAT_5_WITH_CRE",e.HELPDESK_CSAT_5="HELPDESK_CSAT_5",e))(Xe||{});const wm=new Set(["free_text","single_choice"]),km=({csatPayload:e,type:t,initialCsat:n,initialCsatReason:r,initialIsResolved:s})=>{const[o,i]=Fs({csatType:t,csat:n,csatReason:r,isResolved:s}),[c,u]=Fs({followUpItem:!1}),d=l.useMemo(()=>{var S;const g=o.csat,C=typeof g=="number",b=(S=e.follow_up)==null?void 0:S.find(p=>C?p.scores.includes(g):p.always_visible??!1);if(wm.has(b==null?void 0:b.response_type))return b},[o.csat,e.follow_up]),m=(()=>{var g;if(typeof n=="number")return"submitted";if((t===Xe.AI_AGENT_CSAT_5||t===Xe.HELPDESK_CSAT_5)&&typeof o.csat=="number")return"submittable";if(t===Xe.AI_AGENT_CSAT_5_WITH_CRE){const C=typeof o.csat=="number",b=!((g=e.cre)!=null&&g.required)||typeof o.isResolved=="boolean";if(C&&b)return"submittable"}return"unsubmittable"})(),h=l.useCallback(()=>typeof o.csat>"u"?!1:d!=null&&d.required&&!o.csatReason?(u({followUpItem:!0}),!1):!0,[o,d,u]);return l.useEffect(()=>{r||(i({csatReason:""}),u({followUpItem:!1}))},[r,d,i,u]),{params:o,setParams:i,error:c,setError:u,followUpItem:d,state:m,validateParams:h,itemProps:{csatPayload:e,state:m,submitted:m==="submitted"}}},Lm=({csat:e,csatExpireAt:t,csatPayload:n,isSubmitInFlight:r=!1})=>{const s=!!n&&n.visibility&&!!Xe[n.type],o=!r&&typeof e!="number"&&ri(t),i=wn();return l.useEffect(()=>{if(!s||typeof e=="number"||t==null||o)return;const c=t-Date.now();if(c<=0&&r)return;const u=setTimeout(i,Math.max(0,c));return()=>clearTimeout(u)},[i,e,t,o,s,r]),{isRenderableCSAT:s,isExpiredNow:o}},Xn=5,$t=250,Om=50,Us=e=>Math.max(0,e-Om),hn=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():0,Nm=e=>e<1e3?{speed:Xn*.5,chunkSize:2}:e<2e3?{speed:Xn*.8,chunkSize:2}:{speed:Xn*.6,chunkSize:3},fn=(e,t)=>{let n=0;for(let r=t-1;r>=0&&e[r]==="\\";r--)n++;return n%2===1},Bs=(e,t,n,r)=>{let s=1,o=t;for(;o<e.length&&s>0;){if(fn(e,o)){o++;continue}e[o]===n?s++:e[o]===r&&s--,o++}return s>0?-1:o},Ai=(e,{hideImages:t,hideLinks:n})=>{let r="",s=0,o=0;for(;s<e.length;){if(e[s]==="`"&&!fn(e,s)){let h=1;for(;e[s+h]==="`";)h++;o===0?o=h:h===o&&(o=0),r+=e.slice(s,s+h),s+=h;continue}const i=e[s]==="!"&&e[s+1]==="["&&!fn(e,s),c=e[s]==="["&&!fn(e,s);if(o>0||!i&&!c){r+=e[s],s++;continue}if(i?!t:!n){const h=i?"![":"[";r+=h,s+=h.length;continue}const u=s,d=Bs(e,s+(i?2:1),"[","]");if(d===-1)return r;if(s=d,e[s]!=="("){r+=e.slice(u,s);continue}const m=Bs(e,s+1,"(",")");if(m===-1)return r;s=m,r+=e.slice(u,s)}return r},Dm=({trackedRef:e,onVisibleTextProgress:t,onRenderedTextProgress:n})=>{const r=l.useRef(t),s=l.useRef(n),o=l.useRef(null),i=l.useRef({lastLength:0,lastReportedAt:0}).current,c=l.useRef({lastLength:0,lastReportedAt:0,lastCheckedAt:0}).current,u=l.useRef(null);l.useLayoutEffect(()=>{r.current=t,s.current=n});const d=l.useCallback(A=>{var y;(y=r.current)==null||y.call(r,A)},[]),m=l.useCallback(A=>{const y=e.initialEnabled&&(e.enabled||A<e.textLength),T=y&&e.deferImages,I=y&&e.deferLinks;return!T&&!I?A:Ai(e.text.slice(0,A),{hideImages:T,hideLinks:I}).length},[e]),h=l.useCallback((A,y,T=!1)=>{r.current&&(A<=c.lastLength||!T&&y-c.lastReportedAt<$t||(c.lastLength=A,c.lastReportedAt=y,d(A)))},[d,c]),f=l.useCallback((A,y,T=!1)=>{if(!r.current)return;const I=Math.max(c.lastReportedAt,c.lastCheckedAt);!T&&y-I<$t||(c.lastCheckedAt=y,h(m(A),y,!0))},[m,h,c]),g=l.useCallback((A,y,T=!1)=>{s.current&&(A<=i.lastLength||!T&&y-i.lastReportedAt<$t||(i.lastLength=A,i.lastReportedAt=y,s.current(A)))},[i]),C=l.useCallback((A,y,T)=>{const I=A>=y,L=T-i.lastReportedAt>=$t;if(!I&&!L)return;const N=m(A);g(N,T,I)},[m,i,g]),b=l.useCallback(()=>{c.lastLength=0,c.lastReportedAt=0,c.lastCheckedAt=0,i.lastLength=0,i.lastReportedAt=0},[i,c]),S=l.useCallback(A=>{r.current&&(o.current!==null&&A<=o.current||(o.current=A,d(A)))},[d]),p=l.useCallback(({displayedLength:A,streamTextLength:y})=>{const T=u.current;if(u.current={displayedLength:A,streamTextLength:y},!e.initialEnabled||!T||A>T.displayedLength||y<=T.streamTextLength)return;const I=hn();h(y,I,!0),g(y,I,!0)},[u,g,h,e]);return{resetProgress:b,reportVisibleTextProgress:f,reportRenderedTextProgress:C,reportNonStreamingVisibleTextProgress:S,reportMarkdownRevealProgress:p}},$m=e=>{const{text:t,enabled:n=!1,snapOnDisable:r=!1,deferredMarkdownElements:s=[],onAnimationStart:o,onAnimationProgress:i,onAnimationComplete:c,onVisibleTextProgress:u,onRenderedTextProgress:d}=e,m=s.includes("image"),h=s.includes("link"),[f,g]=l.useState(()=>Us(t.length)),C=l.useRef(null),b=l.useRef({startTime:0,lastUpdate:0,lastProgressCall:0}).current,S=l.useRef({startCalled:!1,completeCalled:!1}).current,p=l.useRef({initialEnabled:n,textLength:t.length,enabled:n,text:t,deferImages:m,deferLinks:h,snapOnDisable:r}).current,A=le(()=>o==null?void 0:o()),y=le(()=>i==null?void 0:i()),T=le(()=>c==null?void 0:c()),{resetProgress:I,reportVisibleTextProgress:L,reportRenderedTextProgress:N,reportNonStreamingVisibleTextProgress:k,reportMarkdownRevealProgress:w}=Dm({trackedRef:p,onVisibleTextProgress:u,onRenderedTextProgress:d}),z=n,$=f<t.length,q=p.initialEnabled&&(z||$);l.useLayoutEffect(()=>{p.textLength=t.length,p.enabled=n,p.text=t,p.deferImages=m,p.deferLinks=h,p.snapOnDisable=r}),l.useLayoutEffect(()=>{if(p.initialEnabled){if(S.startCalled||(S.startCalled=!0,A()),!p.enabled&&p.snapOnDisable){g(t.length);const D=hn();L(t.length,D,!0),N(t.length,t.length,D);return}g(D=>t.length<D?t.length:D)}},[A,N,L,t]),l.useEffect(()=>{if(!p.initialEnabled)return;let D=Us(t.length);b.lastUpdate=0,b.startTime=0,b.lastProgressCall=0,I();const G=F=>{b.lastUpdate===0&&(b.lastUpdate=F,b.startTime=F,b.lastProgressCall=F,D>0&&L(D,F,!0));const K=p.textLength;!p.enabled&&p.snapOnDisable&&D<K&&(D=K,g(D),L(D,F,!0),N(D,K,F));const he=F-b.lastUpdate,W=F-b.startTime,{speed:Y,chunkSize:X}=Nm(W),M=Y*X;he>=M&&D<K&&(D=Math.min(D+X,K),g(D),L(D,F,D>=K),N(D,K,F),b.lastUpdate=F),F-b.lastProgressCall>=$t&&(b.lastProgressCall=F,y()),(D<K||p.enabled)&&(C.current=requestAnimationFrame(G))};return C.current=requestAnimationFrame(G),()=>{C.current&&cancelAnimationFrame(C.current),S.startCalled&&!S.completeCalled&&(S.completeCalled=!0,T())}},[T,y,N,L,I]),l.useEffect(()=>{p.initialEnabled&&(n||t.length>0)||(k(t.length),N(t.length,t.length,hn()))},[n,d,u,k,N,t.length,p]),l.useEffect(()=>{const D=p.initialEnabled&&S.startCalled,G=!n,F=f>=t.length;D&&G&&F&&!S.completeCalled&&(S.completeCalled=!0,T())},[n,f,T,t.length]);const Q=l.useMemo(()=>{const D=p.initialEnabled?t.slice(0,f):t,G=q&&m,F=q&&h;return!G&&!F?D:Ai(D,{hideImages:G,hideLinks:F})},[t,f,m,h,q]);return l.useEffect(()=>{!p.initialEnabled||q||L(f,hn(),!0)},[f,q,L]),l.useEffect(()=>{w({displayedLength:f,streamTextLength:Q.length})},[f,w,Q.length]),{streamText:Q,isAnimating:q}},Hs={visible:!1,remainingTime:0,showDescription:!1,targetTimeMs:null},Pm=e=>({visible:!0,remainingTime:e,showDescription:!0,targetTimeMs:Date.now()+e*1e3}),Fm=(e,t=Date.now())=>{if(!e.visible||e.targetTimeMs==null)return e;const n=Math.max(Math.ceil((e.targetTimeMs-t)/1e3),0);return n<=0?{...e,remainingTime:0,showDescription:!1,targetTimeMs:null}:e.remainingTime===n&&e.showDescription?e:{...e,remainingTime:n,showDescription:!0}},Um=()=>{const{chatSDK:e}=Te(),[t,n]=l.useState(Hs),r=()=>n(Hs);return jt(e,{onConnectionDelayed:s=>{s>0?n(Pm(s)):r()},onReconnectSucceeded:r,onConnected:r}),l.useEffect(()=>{if(!t.visible||!t.showDescription||t.targetTimeMs==null)return;const s=setTimeout(()=>{n(o=>Fm(o))},1e3);return()=>clearTimeout(s)},[t.visible,t.showDescription,t.targetTimeMs,t.remainingTime]),{visible:t.visible,remainingTime:t.remainingTime,showDescription:t.showDescription}},Bm=e=>{const t=Math.floor(e/60),n=e%60;return`${String(t).padStart(2,"0")}:${String(n).padStart(2,"0")}`},Hm=(e,t)=>{if(!t)return{beforeText:e,highlightedText:"",afterText:""};const n=e.indexOf(t);return n<0?{beforeText:e,highlightedText:"",afterText:""}:{beforeText:e.slice(0,n),highlightedText:t,afterText:e.slice(n+t.length)}},Gm=({enabled:e=!0}={})=>{const t=Mt();return l.useCallback(({message:n,isBotMessage:r,aiAgentUserId:s})=>{if(!e)return;const o=n.messageId,i=we.isStreaming(n),c=qt(n.extendedMessagePayload),u=c.hasMessageTemplate,d=c.hasForm,m=r&&n.isUserMessage()&&!i&&!xc(n)&&!we.isWelcomeMessage(n,s),h=i||t.streamStalled.hasPendingStream(o),f=t.userPerceivedResponseTime.hasPendingAIResponse(o);if(!h&&!f&&!m&&!u&&!d)return;let g=!1,C=!1;const b={};return(f||m)&&(b.onVisibleTextProgress=()=>{f&&!g&&(g=t.userPerceivedResponseTime.markAIResponseVisible(o)),m&&!C&&(C=!0,t.renderedContentUnusable.commit({messageId:o,contentKind:"text",errorDomain:"empty_render"}))}),h&&(b.onRenderedTextProgress=S=>{t.streamStalled.markRenderedProgress({messageId:o,displayedLength:S})}),u&&(b.onMessageTemplateError=S=>{t.renderedContentUnusable.commit({messageId:o,contentKind:"template",errorDomain:"template_error",error:S})}),d&&(b.onFormRenderError=S=>{t.renderedContentUnusable.commit({messageId:o,contentKind:"form",errorDomain:"form_error",error:S})}),b},[e,t])},zm=e=>{const t=l.useRef(!1);l.useEffect(()=>{t.current||e!=null&&e.onVisibleTextProgress&&(t.current=!0,e.onVisibleTextProgress(0))},[e])},Zn=5e3,Vm=({channelUrl:e,enabled:t=!0,isInitiallyBackgrounded:n,isForegrounded:r,subscribeToForegroundState:s})=>{const o=Mt(),i=l.useRef(t),c=l.useRef(n),u=l.useRef(t&&n()?performance.now()-Zn:null),d=l.useRef(!1);i.current=t,c.current=n;const m=l.useCallback((h=r())=>{if(!i.current){d.current=!1;return}if(!h){d.current=!1;return}if(u.current===null){d.current=!1;return}if(performance.now()-u.current<Zn){u.current=null,d.current=!1;return}if(!e){d.current=!0;return}u.current=null,d.current=!1,o.recoveryNotInteractiveTimeout.start("foreground_resume",e)},[e,r,o]);l.useEffect(()=>{t||(u.current=null,d.current=!1,e&&o.recoveryNotInteractiveTimeout.cancelPending(e))},[e,t,o]),l.useEffect(()=>{if(!t)return;d.current&&!!e&&r()&&m()},[e,t,r,m]),l.useEffect(()=>{if(t)return c.current()?u.current??(u.current=performance.now()-Zn):u.current=null,s(h=>{if(h==="backgrounded"){u.current??(u.current=performance.now()),d.current=!1,e&&o.recoveryNotInteractiveTimeout.cancelPending(e);return}m(!0)})},[e,t,m,o,s])},qm=e=>{const{conversationInitialRender:t,conversationListInitialRender:n}=Mt();l.useLayoutEffect(()=>{t.setPresentMethod(e),n.setPresentMethod(e)},[t,n,e])},Km=(e,{enabled:t=!0,opened:n=!1,filter:r}={})=>{var u,d,m;const[s,o]=l.useState(!1),i=l.useRef(0),c=()=>{if(!t)return;const h=++i.current;e.aiAgent.getUnreadMessageCount(r).then(f=>{h===i.current&&o(f.total>0)}).catch(()=>{})};return l.useEffect(()=>{if(!t){o(!1),i.current++;return}e.connectionState===Ce.ConnectionState.OPEN&&c()},[t,e,r==null?void 0:r.aiAgentChannelFilter,(u=r==null?void 0:r.aiAgentConversationStatusFilter)==null?void 0:u.join(),(d=r==null?void 0:r.aiAgentIds)==null?void 0:d.join(),r==null?void 0:r.deskChannelFilter,(m=r==null?void 0:r.pinnedChannelUrls)==null?void 0:m.join(),r==null?void 0:r.copilotConversationOnly,r==null?void 0:r.copilotSupportChannelUrl]),l.useEffect(()=>{n&&(o(!1),i.current++)},[n]),jt(e,{onConnected:c,onReconnectSucceeded:c}),s},Tt=e=>e.replace(/\s+/g," ").trim(),Ym="Code block",Ti=e=>`A11Y_INLINE_CODE_${e}`,Ii=e=>{let t="",n=e;for(;;){const r=n.match(/^([ \t]{0,3}>\s?)(.*)$/);if(r){t+=r[1],n=r[2];continue}break}return{blockquotePrefix:t,content:n}},xi=e=>{const t=e.match(/^([ \t]{0,3}[-+*]\s+)(.*)$/);if(t)return{content:t[2],hasListPrefix:!0};const n=e.match(/^([ \t]{0,3}\d+[.)]\s+)(.*)$/);return n?{content:n[2],hasListPrefix:!0}:{content:e,hasListPrefix:!1}},Wm=e=>{const{blockquotePrefix:t,content:n}=Ii(e),{content:r}=xi(n),s=r.match(/^[ \t]{0,3}([`~]{3,})(.*)$/);if(!s)return;const o=s[1],i=s[2],c=o[0];if(!(c!=="`"&&c!=="~"||!o.split("").every(u=>u===c))&&!(c==="`"&&i.includes("`")))return{char:c,blockquotePrefix:t,length:o.length}},jm=(e,t)=>{const{blockquotePrefix:n,content:r}=Ii(e);if(n!==t.blockquotePrefix)return!1;const{content:s,hasListPrefix:o}=xi(r);if(o)return!1;const i=s.match(/^[ \t]{0,3}([`~]{3,})[ \t]*$/);if(!i)return!1;const c=i[1];return c[0]===t.char&&c.length>=t.length&&c.split("").every(u=>u===t.char)},Xm=(e,t,n)=>{let r=n;for(;r<e.length;){const s=e[r];if(s==="\\"&&r+1<e.length){r+=2;continue}if(s===t)return r;r+=1}return-1},Zm=(e,t)=>{let n=1,r=t;for(;r<e.length;){const s=e[r];if(s==="\\"&&r+1<e.length){r+=2;continue}if(s==="["){n+=1,r+=1;continue}if(s==="]"&&(n-=1,n===0))return r;r+=1}return-1},Jm=(e,t)=>{let n=t,r=1,s,o=!1,i=!1;for(;n<e.length&&r>0;){const c=e[n];if(c==="\\"&&n+1<e.length){n+=2;continue}if(s){c===s&&(s=void 0),n+=1;continue}if(r===1&&o&&/\s/.test(c)){i=!0,n+=1;continue}if(r===1&&i&&(c==='"'||c==="'")){s=c,n+=1;continue}if(c==="("){r+=1,o=!0,n+=1;continue}if(c===")"){r-=1,n+=1;continue}/\s/.test(c)||(o=!0),n+=1}return r===0?n:-1},Qm=e=>{let t=0,n="";for(;t<e.length;){const r=Xm(e,"[",t);if(r===-1){n+=e.slice(t);break}const s=Zm(e,r+1);if(s===-1){n+=e.slice(t);break}if(r>0&&e[r-1]==="!"&&vn(e,r-1)){n+=e.slice(t,s+1),t=s+1;continue}if(e[s+1]!=="("){n+=e.slice(t,s+1),t=s+1;continue}const o=r>0&&e[r-1]==="!"&&!vn(e,r-1)?r-1:r;n+=e.slice(t,o);const i=e.slice(r+1,s),c=Jm(e,s+2);if(c===-1){n+=e.slice(o);break}n+=i,t=c}return n},Ri=(e,t,n)=>{if(!/^\d+$/.test(t))return!1;const r=e.slice(-1);return/\d/.test(r)&&/\d/.test(n)},eh=e=>e.replace(/(^|[^*\\])\*\*([^\s*](?:[\s\S]*?[^\s*])?)\*\*(?!\*)/g,(t,n,r,s,o)=>{const i=o[s+t.length]??"";return Ri(n,r,i)?t:`${n}${r}`}),th=e=>e.replace(/(^|[^_\\])__([^\s_](?:[\s\S]*?[^\s_])?)__(?!_)/g,"$1$2"),nh=e=>e.replace(/(^|[^~\\])~~([^\s~](?:[\s\S]*?[^\s~])?)~~(?!~)/g,"$1$2"),rh=e=>{let t=e;return t=t.replace(/(^|[^*\\])\*([^\s*](?:[\s\S]*?[^\s*])?)\*(?!\*)/g,(n,r,s,o,i)=>{const c=i[o+n.length]??"";return Ri(r,s,c)?n:`${r}${s}`}),t=t.replace(/(^|[\s([{"'])_([^_\s](?:[\s\S]*?[^_\s])?)_(?=$|[\s)\]}"'.,!?:;])/g,"$1$2"),t},sh=e=>e.replace(/\\([\\`*_[\]()#+.!~|-])/g,"$1"),oh=e=>{let t=e;return t=t.replace(/^\s{0,3}#{1,6}\s+/gm,""),t=t.replace(/^\s{0,3}>\s?/gm,""),t=t.replace(/^\s{0,3}(?!([-*_])(?:\s*\1){2,}\s*$)[-*+]\s+/gm,""),t=t.replace(/^\s{0,3}\d+[.)]\s+/gm,""),t},Gs=e=>{const t=e.trim();if(!t.includes("|"))return!1;const n=t.split("|").map(r=>r.trim()).filter(Boolean);return n.length===0?!1:n.every(r=>/^:?-{3,}:?$/.test(r))},zs=e=>{const t=[];let n="",r=!1;for(const o of e.trim()){if(r){n+=o==="|"?"|":`\\${o}`,r=!1;continue}if(o==="\\"){r=!0;continue}if(o==="|"){const i=n.trim();i&&t.push(i),n="";continue}n+=o}r&&(n+="\\");const s=n.trim();return s&&t.push(s),t},ih=e=>{const t=e.split(`
|
|
2
|
-
`),n=[];let r=0;for(;r<t.length;){const s=t[r],o=t[r+1],i=
|
|
3
|
-
`)},
|
|
4
|
-
`),r=[];let s=0;for(;s<n.length;){const o=n[s],i=
|
|
5
|
-
`)},
|
|
6
|
-
`;){if(e[c]==="`"&&!
|
|
7
|
-
`);if(!n)return;const r=[];let s=n;s=ch(s,t),s=oh(s);const o=lh(s);s=o.text,r.push(...o.inlineCodes),s=Qm(s),s=eh(s),s=th(s),s=nh(s),s=rh(s),s=ih(s),s=ah(s),s=sh(s);for(let c=0;c<r.length;c++)s=s.replaceAll(Ti(c),r[c]);return Tt(s)||void 0},uh=(e,t)=>{var s;const n=((s=e.name)==null?void 0:s.trim())||"",r=e.mimeType??"";return Ve(r)?t.image:Kt(r)?t.video:Zo({name:n,mimeType:r})?t.pdf(n):t.document(n)},Sn=e=>(e==null?void 0:e.trim())||"",dh=e=>(e?Tt(e):void 0)||void 0,Vs=30,mh=e=>e.length>Vs?`${e.slice(0,Vs)}…`:e,hh=({agent:e,status:t,lastMessage:n,time:r,unreadCount:s},o)=>{const i=mh(Tt(n)),c=[t,i].filter(Boolean).join(", ");return o(Tt(e),Tt(c),r,s)},wi=e=>({text:Sn(e),format:"plain"}),fh=e=>({text:Sn(e),format:"markdown"}),Jn=({markdownText:e,plainText:t,comparisonText:n})=>{const r=Sn(e);return r&&r!==Sn(n)?fh(r):wi(t)},Pt=({sender:e,message:t,messageFormat:n="plain",time:r,codeBlockPlaceholder:s})=>{const o=[],i=n==="markdown"?Mi(t,{codeBlockPlaceholder:s}):dh(t);if(r&&o.push(r),e&&o.push(e),i&&o.push(i),o.length!==0)return o.join(", ")},ki=(e,t)=>Mi(e==null?void 0:e.trim(),t!==void 0?{codeBlockPlaceholder:t}:void 0),gh=(...e)=>Tt(e.filter(Boolean).join(", "))||void 0,qs=(e,t,n,r)=>{if(!t||t===n)return e;const s=ki(t,r);return s?gh(e,s):e},ph=(e,t)=>{var r,s,o,i;const n=(r=e.message)==null?void 0:r.trim();if(e.isFileMessage()){const c=((s=e.name)==null?void 0:s.trim())||"",u=uh({name:c,mimeType:e.type},t);return qs(u,n,c,t.codeBlockPlaceholder)}if(e.isMultipleFilesMessage()){const c=e.fileInfoList??[],u=c.length;if(u===0)return;const d=((i=(o=c[0])==null?void 0:o.fileName)==null?void 0:i.trim())||"",h=c.every(f=>{var g;return(g=f.mimeType)==null?void 0:g.startsWith("image")})?t.receivedFilesImageCount(u):t.multipleFilesCount(u);return qs(h,n,d,t.codeBlockPlaceholder)}return ki(n,t.codeBlockPlaceholder)},_h=(e,t={})=>{const{throttleMs:n=1e3,isSuppressed:r,maxOrderedQueueSize:s=10}=t,o=Math.max(1,s);let i=null;const c=[];let u=null,d=null,m=null,h=!1,f=0;const g=(k,w,z)=>({text:k,ignoreSuppression:w,queueOrder:f++,dedupeKey:z}),C=()=>{const k=c[0]??null,w=i;return k&&w?w.queueOrder<k.queueOrder?(i=null,w):c.shift()??null:k?c.shift()??null:w!==null?(i=null,w):null},b=()=>{for(;;){const k=C();if(!k)return null;if(!(!k.ignoreSuppression&&(r!=null&&r())))return k}},S=k=>{u=k.text,d=k.dedupeKey??null,h=!0,e(k.text),m=setTimeout(()=>{m=null,h=!1;const w=b();w&&S(w)},n)},p=k=>{u=k.text,d=k.dedupeKey??null,e(k.text)},A=(k,w,z,$)=>w!=null&&$!=null?w===$:w==null&&$==null?k!=null&&k===z:!1,y=(k,w,z)=>{if(!k||!w&&(r!=null&&r()))return;const $=z==null?void 0:z.dedupeKey;if(!(h&&A(k,$,u,d)))if(h){if(((z==null?void 0:z.mode)??"latestOnly")==="ordered"){const Q=c[c.length-1];if(Q&&A(k,$,Q.text,Q.dedupeKey))return;c.push(g(k,w,$)),c.length>o&&c.shift();return}i=g(k,w,$)}else i=null,S(g(k,w,$))};return{announce:(k,w)=>{y(k,!1,w)},announceIgnoringSuppression:(k,w)=>{y(k,!0,w)},flush:()=>{const k=[];let w=C();for(;w!==null;)k.push(w),w=C();if(m!==null&&(clearTimeout(m),m=null),h=!1,k.length!==0)for(const z of k)p(z)},destroy:()=>{m!==null&&(clearTimeout(m),m=null),i=null,c.length=0,u=null,d=null,h=!1}}},Eh=e=>{switch(e){case"newMessage":case"conversationClosed":case"csatDisplayed":case"csatSubmitted":case"csatExpired":return"ordered";default:return"latestOnly"}},Ch=(e,t)=>e.screen==="conversationList"?typeof e.conversationCount=="number"?t.screenConversationListWithCount(e.conversationCount):t.screenConversationListNoCount:[e.agentName?t.screenConversationWithAgent(e.agentName):t.screenConversation,e.isClosed?t.conversationClosed:null,e.isClosed&&e.hasCSAT?t.csatDisplayed:null,e.isEmpty?t.emptyState:null].filter(r=>!!r).join(". "),bh=(e,t)=>{switch(e.event){case"newMessage":return e.body!==void 0||e.time!==void 0?[t.newMessage(1),e.time,e.senderName,e.body].filter(r=>!!r).join(", "):e.senderName?t.newMessageFromSender(e.senderName,1):t.newMessage(1);case"typing":return t.typing(e.agentName??"");case"sendFailed":return t.sendFailed;case"agentConnected":return t.agentConnected(e.agentName??"");case"conversationClosed":return t.conversationClosed;case"csatDisplayed":return t.csatDisplayed;case"csatSubmitted":return e.submittedLabel;case"csatExpired":return t.csatExpired;case"emptyState":return t.emptyState;case"inputDisabled":return t.inputDisabled}},vh=(e,t)=>{switch(e.type){case"fileSizeExceeded":return t.fileSizeExceeded(e.maxSizeMB??25);case"sendFailed":return t.sendFailed;case"csatFormError":return t.csatFormError;case"generic":return e.message}},Sh=(e,t)=>!t||!Ze(e)||e.sender.userId!==t?null:e.reqId||(e.messageId>0?String(e.messageId):null),yh=(e,t)=>Oe.isAdmin(e)?Oe.isCSAT(e):"sender"in e?e.sender.userId!==t:!1,Ah=e=>"messageId"in e&&e.messageId>0?String(e.messageId):"reqId"in e&&typeof e.reqId=="string"&&e.reqId.length>0?e.reqId:null,Th=e=>e===Ce.CollectionEventSource.EVENT_MESSAGE_RECEIVED||e===Ce.CollectionEventSource.EVENT_MESSAGE_UPDATED,Ih=({isOpened:e,opensConversationList:t})=>e?t?"closeConversationList":"closeConversation":t?"openConversationList":"openConversation",xh=(e,t)=>{switch(e){case"closeConversationList":return t.closeConversationList;case"closeConversation":return t.closeConversation;case"openConversationList":return t.openConversationList;case"openConversation":return t.openConversation}},Rh=(e,t)=>{switch(e){case"closeConversation":return t.hintCloseConversation;case"openConversationList":return t.hintOpenConversationList;case"openConversation":return t.hintOpenConversation;default:return}},Mh=({intent:e,strings:t})=>({label:xh(e,t),hint:Rh(e,t)}),wh="1.37.0",Be="sb-agent",Se={ENTRY:`${Be}-entry`,MODAL_ROOT:`${Be}-modal-root`,WINDOW:`${Be}-window`,LAUNCHER:`${Be}-launcher`,WINDOW_TITLE:`${Be}-window-title`},Li="data-sb-initial-focus",Oi="true",kh=`[${Li}="${Oi}"]`,Ni={[Li]:Oi},zr="data-sb-focus-trap-sentinel",Lh="true",Di="data-sb-initial-focus-header",$i="true",Oh=`[${Di}="${$i}"]`,Pi={[Di]:$i},Fi="data-sb-message-input",Ui="true",Nh=`textarea[${Fi}="${Ui}"]:not(:disabled)`,Dh={[Fi]:Ui},Bi=1e3,an=2147483647,ft={MODAL:an-1,TOOLTIP:an-2,WINDOW:an-3,LAUNCHER:an-4},Hi=36,$h=100,Ph=wh,Vr="noopener noreferrer nofollow",Fh=()=>typeof document>"u"||document.visibilityState==="visible",fr=()=>typeof document<"u"&&document.visibilityState==="hidden",Ks=()=>fr()?"backgrounded":"foregrounded",Uh={getState:Ks,subscribe:e=>{if(typeof document>"u")return()=>{};const t=()=>e(Ks());return document.addEventListener("visibilitychange",t),()=>document.removeEventListener("visibilitychange",t)}};function Bh(){return{isOnline:()=>navigator.onLine,subscribe:e=>{const t=()=>e(!0),n=()=>e(!1);return window.addEventListener("online",t),window.addEventListener("offline",n),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",n)}}}}const cn={};function Hh(){return{get:e=>{try{return localStorage.getItem(e)}catch{return cn[e]??null}},set:(e,t)=>{try{localStorage.setItem(e,t)}catch{cn[e]=t}},delete:e=>{try{localStorage.removeItem(e)}catch{delete cn[e]}},getKeys:e=>{try{const t=[];for(let n=0;n<localStorage.length;n++){const r=localStorage.key(n);r&&r.startsWith(e)&&t.push(r)}return t}catch{return Object.keys(cn).filter(t=>t.startsWith(e))}}}}const Gh={conversation:{input_placeholder:"Ask a question",input_placeholder_disabled:"Chat is unavailable in this channel",input_placeholder_steward:"Processing your request...",input_placeholder_wait_ai_agent_response:"Waiting for the agent's reply...",input_placeholder_active_form:"Please fill out the form to move forward.",input_placeholder_reconnecting:"Trying to reconnect. Refresh if persists.",unknown_message_type:"(Unknown message type)",powered_by:"Powered by",citation_title:"Source",start_new_conversation_label:"Start a conversation",scroll_to_new_messages_label:()=>"New message",failed_message_resend:"Retry",failed_message_remove:"Remove",file_upload_no_supported_files:"No supported file types available.",file_upload_replace_alert_title:"Replace attachment?",file_upload_replace_alert_description:"Uploading a different file type will replace the current one.",a11y_message_list:"Chat messages",a11y_scroll_to_bottom:"Scroll to bottom",a11y_scroll_to_new_messages:"Scroll to new messages",a11y_open_conversation_list:"Open conversation list",a11y_open_conversation:"Open conversation with Support",a11y_open_conversations:"Open conversations",a11y_close_conversation:"Close conversation",a11y_close_conversations:"Close conversations",a11y_menu:"Menu",a11y_message_input:"Message",a11y_send_message:"Send message",a11y_attach_file:"Attach file",a11y_close_messenger:"Close messenger",a11y_dismiss_nudge_message:"Dismiss message",a11y_expand_messenger:"Expand messenger",a11y_collapse_messenger:"Collapse messenger",a11y_connect_agent:"Talk to human agent",a11y_message_sender_you:"You",a11y_suggested_reply:"Suggested reply",a11y_typing_indicator:"Typing",a11y_code_block_placeholder:"Code block",a11y_typing_format:e=>`${e} is typing`,a11y_message_failed:"Message send failed",a11y_new_messages_received:e=>`${e} new ${e===1?"message":"messages"} received`,a11y_new_messages_received_from_sender:(e,t)=>`${e}: ${t} new ${t===1?"message":"messages"} received`,a11y_agent_connected:e=>"Connected to human agent",a11y_conversation_closed:"Conversation has ended",a11y_file_image:e=>`Image file: ${e}`,a11y_file_video:e=>`Video file: ${e}`,a11y_file_pdf:e=>`PDF file: ${e}`,a11y_file_document:e=>`Document file: ${e}`,a11y_received_file_image:"Image file",a11y_received_file_video:"Video file",a11y_received_file_pdf:e=>`PDF file: ${e}`,a11y_received_files_image_count:e=>`${e} ${e===1?"image":"images"}`,a11y_screen_conversation:"Conversation",a11y_screen_conversation_with_agent:e=>`Conversation with ${e}`,a11y_screen_conversation_list_no_count:"Conversation list",a11y_screen_conversation_list_with_count:e=>`Conversations, ${e} total`,a11y_csat_displayed:"Satisfaction survey displayed",a11y_empty_conversation:"No messages in this conversation",a11y_input_disabled:"Message input is disabled",a11y_file_size_exceeded:e=>`File exceeds size limit of ${e}MB`,a11y_csat_form_error:"Please complete the required fields",a11y_hint_send_message:"Sends the message",a11y_hint_open_conversation:"Opens the conversation",a11y_hint_open_conversations:"Opens conversations",a11y_hint_close_conversation:"Closes the conversation",a11y_hint_close_messenger:"Closes the messenger",a11y_hint_open_menu:"Opens the menu",a11y_hint_connect_to_agent:"Escalates to a human agent",a11y_hint_attach_file:"Opens file attachment options",a11y_hint_view_new_messages:"Scrolls to new messages",a11y_hint_open_file:"Opens the file",a11y_hint_open_image:"Opens the image",a11y_hint_send_reply:"Sends this reply",image_viewer_default_title:"Image",a11y_image_viewer_close:"Close image viewer",a11y_image_viewer_previous:"Previous image",a11y_image_viewer_next:"Next image",a11y_image_viewer_download:"Download image",attachment_document:"Files"},conversation_list:{header_title:"Conversations",ended:"Ended",system_message:"System message",footer_title:"Start a conversation",multiple_files_count:e=>`${e} ${e===1?"file":"files"}`,a11y_conversation_item:(e,t,n,r)=>`${e}, ${t}, ${n}${r>0?`, ${r} unread ${r===1?"message":"messages"}`:""}`},date_format:{just_now:"Just now",minutes_ago:e=>`${e} minutes ago`,hours_ago:e=>`${e} hours ago`,date_short:"MM/dd/yyyy",date_separator:"MMMM dd, yyyy",message_timestamp:"p"},csat:{title:"Your feedback matters to us",submitted_label:"Successfully submitted!",cre_question:"Was your issue resolved?",cre_positive_label:"Yes, thank you! 👍",cre_negative_label:"No, that didn't help.",reason_placeholder:"Share your feedback",question:"How would you rate your experience?",submit_label:"Submit",submission_expired:"We're sorry, the survey period has ended.",a11y_csat_rating_label:(e,t)=>`${e} out of 5 — ${t}`,a11y_hint_select_rating:"Selects this rating"},form:{optional_label:"optional",validation_required:"This question is required"},common:{placeholder_something_went_wrong:"Something went wrong",placeholder_no_messages:"No messages",placeholder_no_conversations:"No conversations yet",placeholder_something_went_wrong_retry_label:"Retry",button_ok:"OK",button_cancel:"Cancel"},feedback:{title:"Submit feedback",good:"Good",bad:"Bad",comment_label:"Comment (optional)",comment_placeholder:"Leave a comment",cancel:"Cancel",submit:"Submit",save:"Save",edit:"Edit feedback",remove:"Remove feedback"},handoff:{confirm_title:"Request handoff?",confirm_description:"You'll be transferred to a human agent. Your conversation history will be shared.",confirm_cancel:"Cancel",confirm_handoff:"Handoff"},memory:{dialog_title:"Memory",desc_on:"Memory is **turned on**. It remembers your conversation history to provide personalized responses tailored to your previous questions and preferences.",desc_off:"Memory is **turned off**. If turned on, it will remember your conversation history to provide personalized responses tailored to your previous questions and preferences.",button_use:"Use",button_dont_use:"Don't use",button_keep_using:"Keep using",button_disable:"Disable",button_disable_and_delete:"Disable & Delete memory",button_keep_off:"Keep off",button_enable:"Enable memory",button_cancel:"Cancel",error_message:"Failed to update memory state. Please try again.",a11y_indicator_manage:"Manage memory",a11y_indicator_on:"Memory is on",a11y_indicator_off:"Memory is off"},connection_delay:{title:"Something went wrong. You'll be reconnected shortly.",description:e=>`Estimated waiting time: ${e}`}},gr={language:"en",strings:Gh,dateLocale:uc.enUS},Gi=e=>({MESSAGE_INPUT__PLACE_HOLDER:e.conversation.input_placeholder,MESSAGE_INPUT__PLACE_HOLDER__DISABLED:e.conversation.input_placeholder_disabled,MESSAGE_INPUT__PLACE_HOLDER__STEWARD:e.conversation.input_placeholder_steward,MESSAGE_INPUT__PLACE_HOLDER__WAIT_AI_AGENT_RESPONSE:e.conversation.input_placeholder_wait_ai_agent_response,MESSAGE_INPUT__PLACE_HOLDER__RECONNECTING:e.conversation.input_placeholder_reconnecting,UNKNOWN__UNKNOWN_MESSAGE_TYPE:e.conversation.unknown_message_type,POWERED_BY:e.conversation.powered_by,CSAT_TITLE_UNSUBMITTED:e.csat.title,CSAT_TITLE_SUBMITTED:e.csat.submitted_label,CSAT_CRE_TITLE:e.csat.cre_question,CSAT_CRE_SOLVED:e.csat.cre_positive_label,CSAT_CRE_NOT_SOLVED:e.csat.cre_negative_label,CSAT_REASON_PLACEHOLDER:e.csat.reason_placeholder,CSAT_RATING_TITLE:e.csat.question,CSAT_SUBMIT_LABEL:e.csat.submit_label,CSAT_SUBMISSION_EXPIRED:e.csat.submission_expired,DATE_FORMAT__JUST_NOW:e.date_format.just_now,DATE_FORMAT__MINUTES_AGO:e.date_format.minutes_ago,DATE_FORMAT__HOURS_AGO:e.date_format.hours_ago,DATE_FORMAT__DATE_SHORT:e.date_format.date_short,DATE_FORMAT__MESSAGE_LIST__DATE_SEPARATOR:e.date_format.date_separator,DATE_FORMAT__MESSAGE_TIMESTAMP:e.date_format.message_timestamp,CONVERSATION_LIST__HEADER_TITLE:e.conversation_list.header_title,CONVERSATION_LIST__ENDED:e.conversation_list.ended,CONVERSATION_LIST__SYSTEM_MESSAGE:e.conversation_list.system_message,CONVERSATION_LIST__NO_CONVERSATIONS:e.common.placeholder_no_conversations,CONVERSATION_LIST__MULTIPLE_FILES_COUNT:e.conversation_list.multiple_files_count,TALK_TO_AGENT:e.conversation.start_new_conversation_label,CITATION_SOURCE_TITLE:e.conversation.citation_title,FORM_PLACEHOLDER:e.conversation.input_placeholder_active_form,FORM_VALIDATION_REQUIRED:e.form.validation_required,OPTIONAL:e.form.optional_label,PLACE_HOLDER__WRONG:e.common.placeholder_something_went_wrong,PLACE_HOLDER__NO_MESSAGES:e.common.placeholder_no_messages,RETRY:e.common.placeholder_something_went_wrong_retry_label,BUTTON__OK:e.common.button_ok,BUTTON__CANCEL:e.common.button_cancel,FAILED_MESSAGE_RESEND:e.conversation.failed_message_resend,FAILED_MESSAGE_REMOVE:e.conversation.failed_message_remove,FILE_UPLOAD_NO_SUPPORTED_FILES:e.conversation.file_upload_no_supported_files,FILE_UPLOAD_REPLACE_ALERT__TITLE:e.conversation.file_upload_replace_alert_title,FILE_UPLOAD_REPLACE_ALERT__DESCRIPTION:e.conversation.file_upload_replace_alert_description,FILE_UPLOAD_FILES:e.conversation.attachment_document,FEEDBACK_TITLE:e.feedback.title,FEEDBACK_GOOD:e.feedback.good,FEEDBACK_BAD:e.feedback.bad,FEEDBACK_COMMENT_LABEL:e.feedback.comment_label,FEEDBACK_COMMENT_PLACEHOLDER:e.feedback.comment_placeholder,FEEDBACK_CANCEL:e.feedback.cancel,FEEDBACK_SUBMIT:e.feedback.submit,FEEDBACK_SAVE:e.feedback.save,FEEDBACK_EDIT:e.feedback.edit,FEEDBACK_REMOVE:e.feedback.remove,A11Y_MESSAGE_LIST:e.conversation.a11y_message_list,A11Y_SCROLL_TO_BOTTOM:e.conversation.a11y_scroll_to_bottom,A11Y_SCROLL_TO_NEW_MESSAGES:e.conversation.a11y_scroll_to_new_messages,A11Y_OPEN_CONVERSATION_LIST:e.conversation.a11y_open_conversation_list,A11Y_OPEN_CONVERSATION:e.conversation.a11y_open_conversation,A11Y_OPEN_CONVERSATIONS:e.conversation.a11y_open_conversations,A11Y_CLOSE_CONVERSATION:e.conversation.a11y_close_conversation,A11Y_CLOSE_CONVERSATIONS:e.conversation.a11y_close_conversations,A11Y_MENU:e.conversation.a11y_menu,A11Y_MESSAGE_INPUT:e.conversation.a11y_message_input,A11Y_SEND_MESSAGE:e.conversation.a11y_send_message,A11Y_ATTACH_FILE:e.conversation.a11y_attach_file,A11Y_CONNECT_AGENT:e.conversation.a11y_connect_agent,A11Y_CLOSE_MESSENGER:e.conversation.a11y_close_messenger,A11Y_DISMISS_NUDGE_MESSAGE:e.conversation.a11y_dismiss_nudge_message,A11Y_EXPAND_MESSENGER:e.conversation.a11y_expand_messenger,A11Y_COLLAPSE_MESSENGER:e.conversation.a11y_collapse_messenger,A11Y_MESSAGE_SENDER_YOU:e.conversation.a11y_message_sender_you,A11Y_SUGGESTED_REPLY:e.conversation.a11y_suggested_reply,A11Y_TYPING_INDICATOR:e.conversation.a11y_typing_indicator,A11Y_CODE_BLOCK_PLACEHOLDER:e.conversation.a11y_code_block_placeholder,A11Y_TYPING_FORMAT:e.conversation.a11y_typing_format,A11Y_MESSAGE_FAILED:e.conversation.a11y_message_failed,A11Y_NEW_MESSAGES_RECEIVED:e.conversation.a11y_new_messages_received,A11Y_NEW_MESSAGES_RECEIVED_FROM_SENDER:e.conversation.a11y_new_messages_received_from_sender,A11Y_AGENT_CONNECTED:e.conversation.a11y_agent_connected,A11Y_CONVERSATION_CLOSED:e.conversation.a11y_conversation_closed,A11Y_FILE_IMAGE:e.conversation.a11y_file_image,A11Y_FILE_VIDEO:e.conversation.a11y_file_video,A11Y_FILE_PDF:e.conversation.a11y_file_pdf,A11Y_FILE_DOCUMENT:e.conversation.a11y_file_document,A11Y_RECEIVED_FILE_IMAGE:e.conversation.a11y_received_file_image,A11Y_RECEIVED_FILE_VIDEO:e.conversation.a11y_received_file_video,A11Y_RECEIVED_FILE_PDF:e.conversation.a11y_received_file_pdf,A11Y_RECEIVED_FILES_IMAGE_COUNT:e.conversation.a11y_received_files_image_count,A11Y_SCREEN_CONVERSATION:e.conversation.a11y_screen_conversation,A11Y_SCREEN_CONVERSATION_WITH_AGENT:e.conversation.a11y_screen_conversation_with_agent,A11Y_SCREEN_CONVERSATION_LIST_NO_COUNT:e.conversation.a11y_screen_conversation_list_no_count,A11Y_SCREEN_CONVERSATION_LIST_WITH_COUNT:e.conversation.a11y_screen_conversation_list_with_count,A11Y_CSAT_DISPLAYED:e.conversation.a11y_csat_displayed,A11Y_EMPTY_CONVERSATION:e.conversation.a11y_empty_conversation,A11Y_INPUT_DISABLED:e.conversation.a11y_input_disabled,A11Y_FILE_SIZE_EXCEEDED:e.conversation.a11y_file_size_exceeded,A11Y_CSAT_FORM_ERROR:e.conversation.a11y_csat_form_error,A11Y_HINT_SEND_MESSAGE:e.conversation.a11y_hint_send_message,A11Y_HINT_OPEN_CONVERSATION:e.conversation.a11y_hint_open_conversation,A11Y_HINT_OPEN_CONVERSATIONS:e.conversation.a11y_hint_open_conversations,A11Y_HINT_CLOSE_CONVERSATION:e.conversation.a11y_hint_close_conversation,A11Y_HINT_OPEN_MENU:e.conversation.a11y_hint_open_menu,A11Y_HINT_CONNECT_TO_AGENT:e.conversation.a11y_hint_connect_to_agent,A11Y_HINT_ATTACH_FILE:e.conversation.a11y_hint_attach_file,A11Y_HINT_VIEW_NEW_MESSAGES:e.conversation.a11y_hint_view_new_messages,A11Y_HINT_OPEN_FILE:e.conversation.a11y_hint_open_file,A11Y_HINT_OPEN_IMAGE:e.conversation.a11y_hint_open_image,A11Y_HINT_SEND_REPLY:e.conversation.a11y_hint_send_reply,A11Y_CONVERSATION_ITEM:e.conversation_list.a11y_conversation_item,A11Y_CSAT_RATING_LABEL:e.csat.a11y_csat_rating_label,A11Y_HINT_SELECT_RATING:e.csat.a11y_hint_select_rating,IMAGE_VIEWER__DEFAULT_TITLE:e.conversation.image_viewer_default_title,A11Y_IMAGE_VIEWER_CLOSE:e.conversation.a11y_image_viewer_close,A11Y_IMAGE_VIEWER_PREVIOUS:e.conversation.a11y_image_viewer_previous,A11Y_IMAGE_VIEWER_NEXT:e.conversation.a11y_image_viewer_next,A11Y_IMAGE_VIEWER_DOWNLOAD:e.conversation.a11y_image_viewer_download,SCROLL_TO_NEW_MESSAGES_LABEL:e.conversation.scroll_to_new_messages_label,HANDOFF_CONFIRM__TITLE:e.handoff.confirm_title,HANDOFF_CONFIRM__DESCRIPTION:e.handoff.confirm_description,HANDOFF_CONFIRM__CANCEL:e.handoff.confirm_cancel,HANDOFF_CONFIRM__HANDOFF:e.handoff.confirm_handoff,MEMORY__DIALOG_TITLE:e.memory.dialog_title,MEMORY__DESC_ON:e.memory.desc_on,MEMORY__DESC_OFF:e.memory.desc_off,MEMORY__BUTTON_USE:e.memory.button_use,MEMORY__BUTTON_DONT_USE:e.memory.button_dont_use,MEMORY__BUTTON_KEEP_USING:e.memory.button_keep_using,MEMORY__BUTTON_DISABLE:e.memory.button_disable,MEMORY__BUTTON_DISABLE_AND_DELETE:e.memory.button_disable_and_delete,MEMORY__BUTTON_KEEP_OFF:e.memory.button_keep_off,MEMORY__BUTTON_ENABLE:e.memory.button_enable,MEMORY__BUTTON_CANCEL:e.memory.button_cancel,MEMORY__ERROR_MESSAGE:e.memory.error_message,A11Y_MEMORY_INDICATOR_MANAGE:e.memory.a11y_indicator_manage,A11Y_MEMORY_INDICATOR_ON:e.memory.a11y_indicator_on,A11Y_MEMORY_INDICATOR_OFF:e.memory.a11y_indicator_off,CONNECTION_DELAY__TITLE:e.connection_delay.title,CONNECTION_DELAY__DESCRIPTION:e.connection_delay.description}),zi=e=>{var t;return((t=e.split("-"))==null?void 0:t[0])??Xt},Xt="en",Vi=new Set([Xt,"ko","es","pt","fr","hi","it","de","tr","ja"]),zh='@import"https://fonts.googleapis.com/css?family=Roboto:400,500,600,700&display=swap";.sb-message-template__border{position:relative}.sb-message-template__border:after{content:"";position:absolute;top:0;right:0;bottom:0;left:0;z-index:1;box-shadow:inset 0 0 0 var(--border-width) var(--border-color);border-radius:var(--border-radius);pointer-events:none}.sb-message-template__action{cursor:pointer}.sb-message-template__parent{font-family:Roboto,serif}.sb-message-template__text{font-family:inherit;font-size:14px;font-weight:400;font-stretch:normal;font-style:normal;letter-spacing:normal;text-align:left}.sb-message-template__text-button{font-family:inherit;background-color:#e0e0e0;text-align:center;padding:10px;border-radius:6px;font-size:14px;font-weight:600;font-stretch:normal;font-style:normal;letter-spacing:normal}.sendbird-theme--light .sb-message-template__text-button{color:#742ddd}.sendbird-theme--dark .sb-message-template__text-button{color:#c2a9fa}.sb-message-template__text-button:hover{opacity:1;box-shadow:#0000001a 0 1px 3px,#0000000f 0 1px 2px}.sb-message-template__text-button,.sb-message-template__image-button{cursor:pointer;border-style:none}.sb-message-template__parent{border-radius:unset;background-color:transparent;overflow:hidden}.sb-message-template__parent *{box-sizing:border-box;line-height:1.3}.sb-message-template__carousel{display:flex;width:100%;box-sizing:border-box;touch-action:pan-y}',{Provider:Vh,useContext:qr}=ve("AgentUIElementResolver"),qh=({entryElement:e,modalRootElement:t,rootElement:n,children:r})=>{const s=l.useMemo(()=>{const o=n??document.body,i=e??o,c=t??o,u=d=>d===Se.MODAL_ROOT?c:i.querySelector(`#${d}`);return{resolveElement:u,resolvePortalContainer:d=>u(d)??c}},[e,t,n]);return a.createElement(Vh,{value:s},r)};function ct(e,t){const n=e.getRootNode({composed:t});return n instanceof ShadowRoot||n instanceof Document?n:document}const Ys=()=>{const e=[];let t=0;const n=new Set,r=()=>n.forEach(s=>s());return{register:s=>{const o=++t;return e.push({id:o,handler:s}),r(),()=>{const i=e.findIndex(c=>c.id===o);i>=0&&(e.splice(i,1),r())}},dismissTopmost:()=>{const s=e[e.length-1];return s?(s.handler(),!0):!1},subscribe:s=>(n.add(s),()=>{n.delete(s)}),getOpenCount:()=>e.length}},{Provider:Kh,useContext:Kr}=ve("EscapeDismissStack"),Ws=e=>{e.stopPropagation(),e.stopImmediatePropagation()},Yh=({rootElement:e=document.body,boundaryElement:t,children:n})=>{const r=l.useRef(null),s=l.useRef(null);r.current||(r.current=Ys()),s.current||(s.current=Ys());const o=r.current,i=s.current;l.useLayoutEffect(()=>{const u=t??ct(e),d=m=>{if(m.key==="Escape"){if(o.dismissTopmost()){Ws(m);return}i.dismissTopmost()&&Ws(m)}};return u.addEventListener("keydown",d),()=>u.removeEventListener("keydown",d)},[t,e,i,o]);const c=l.useMemo(()=>({register:o.register,dismissTopmost:o.dismissTopmost,registerShellDismissHandler:i.register,subscribe:o.subscribe,getOpenCount:o.getOpenCount}),[i,o]);return a.createElement(Kh,{value:c},n)},qi=(e,t,n)=>{const r=l.useRef(t);l.useLayoutEffect(()=>{r.current=t},[t]),l.useLayoutEffect(()=>{if(e)return n(()=>r.current())},[e,n])},Wh=(e,t)=>{const{register:n}=Kr();qi(e,t,n)},jh=(e,t)=>{const{registerShellDismissHandler:n}=Kr();qi(e,t,n)},Ki=()=>{const{subscribe:e,getOpenCount:t}=Kr();return l.useSyncExternalStore(e,()=>t()>0,()=>!1)},Xh=(e,t,n)=>{const r=e[t];return r?typeof r=="function"?r():Promise.resolve(r):new Promise((s,o)=>{(typeof queueMicrotask=="function"?queueMicrotask:setTimeout)(o.bind(null,new Error("Unknown variable dynamic import: "+t+(t.split("/").length!==n?". Note that variables only represent file names one level deep.":""))))})},js=Gi(gr.strings),Zh={...js,HEADER_BUTTON__AGENT_HANDOFF:"Talk to human agent",MESSAGE_INPUT__PLACE_HOLDER__SUGGESTED_REPLIES:"Select an option to continue",BUTTON__SUBMIT:"Submit",SUBMITTED:"Submitted",TRY_AGAIN:"Please try again.",FILE_UPLOAD_NOTIFICATION__COUNT_LIMIT:"Up to %d files can be attached.",FILE_UPLOAD_NOTIFICATION__SIZE_LIMIT:"The maximum size per file is %d MB.",FILE_UPLOAD_NOTIFICATION__FILES_EXCLUDED_BY_VALIDATION:"%d files were excluded due to limits. Please select files individually.",FILE_UPLOAD_PHOTOS:"Photos",FILE_VIEWER__UNSUPPORT:"Unsupported message",A11Y_FILE_SELECTED:e=>`${e}, selected`,A11Y_FILE_REMOVE_BUTTON:e=>`Remove file: ${e}`,A11Y_FILE_UPLOAD_OPTIONS:"File upload options",A11Y_FAILED_MESSAGE_OPTIONS:"Failed message options",A11Y_FEEDBACK_OPTIONS:"Feedback options",A11Y_CSAT_TEXT_INPUT_LABEL:"Enter answer",FORM_UNAVAILABLE:"Form is no longer available.",FORM_NOT_SUPPORTED:"This form is not supported in the current version.",FORM_VALIDATION_MIN_LENGTH:e=>`Minimum ${e} characters required`,FORM_VALIDATION_MAX_LENGTH:e=>`Maximum ${e} characters allowed`,FORM_VALIDATION_MIN:e=>`Minimum value is ${e}`,FORM_VALIDATION_MAX:e=>`Maximum value is ${e}`,FORM_VALIDATION_MIN_SELECT:e=>`Select at least ${e} options`,FORM_VALIDATION_MAX_SELECT:e=>`Select at most ${e} options`,FORM_VALIDATION_REGEX_FAILED:"Invalid format",DATE_FORMAT__CONVERSATION_LIST__LIST_ITEM_TITLE:js.DATE_FORMAT__DATE_SHORT,DATE_FORMAT__CONVERSATION_LIST__LIST_ITEM_TITLE_CAPTION:"h:mma",CONVERSATION_LIST__TOPICS_FALLBACK:"No category",CONVERSATION_CLOSED_FOOTER_LABEL:"Your conversation has ended",START_NEW_CONVERSATION:"💬 Start a new conversation",RETURN_TO_CONVERSATION:"💬 Return to conversation",BUTTON__SAVE:"Save",NO_NAME:"(No name)",CHANNEL_FROZEN:"Channel frozen"},yn={language:gr.language,dateLocale:gr.dateLocale,stringSet:Zh},Jh=Object.freeze(Object.defineProperty({__proto__:null,default:yn},Symbol.toStringTag,{value:"Module"})),pr=new Map([[Xt,yn]]);async function Qh(e){const t=pr.get(e);if(t)return t;try{if(Vi.has(e)){const{default:n}=await Xh(Object.assign({"./languages/de.ts":()=>Promise.resolve().then(()=>require("./cjs/CIjjIGUs.cjs")),"./languages/en.ts":()=>Promise.resolve().then(()=>Jh),"./languages/es.ts":()=>Promise.resolve().then(()=>require("./cjs/B9JzuCyz.cjs")),"./languages/fr.ts":()=>Promise.resolve().then(()=>require("./cjs/BQ8EaWkc.cjs")),"./languages/hi.ts":()=>Promise.resolve().then(()=>require("./cjs/Cr2LxvlJ.cjs")),"./languages/it.ts":()=>Promise.resolve().then(()=>require("./cjs/C2Oi-KA4.cjs")),"./languages/ja.ts":()=>Promise.resolve().then(()=>require("./cjs/LFX2h7v2.cjs")),"./languages/ko.ts":()=>Promise.resolve().then(()=>require("./cjs/CKr98WbE.cjs")),"./languages/pt.ts":()=>Promise.resolve().then(()=>require("./cjs/C3VEshQr.cjs")),"./languages/tr.ts":()=>Promise.resolve().then(()=>require("./cjs/C116E0pr.cjs"))}),`./languages/${e}.ts`,3);return pr.set(e,n),n}return yn}catch{return yn}}const{Provider:ef,useContext:oe}=ve("Localization"),tf=({language:e=navigator.language,languageCode:t,logger:n,stringSet:r,children:s})=>{const[o,i]=l.useState(pr.get(Xt));return l.useEffect(()=>{const c=t??zi(e);o.language!==c&&(n==null||n.debug("localization.useEffect: update language",{from:o.language,to:c}),Qh(c).then(i))},[e,t,n]),a.createElement(ef,{value:{language:o.language,defaultStringSet:o.stringSet,stringSet:{...o.stringSet,...r},dateLocale:o.dateLocale,format:(c,u,d)=>it.format(c,u,{locale:o.dateLocale,...d})}},s)},An="data-sb-agent-theme",Xs=e=>(t,...n)=>{let r="";return t.forEach((s,o)=>{r+=s+(n[o]??"")}),`[${An}='${e}'] & { ${r} }`},te={light:Xs("light"),dark:Xs("dark")},nf=B.css(({theme:e})=>{const{palette:t}=e;return`
|
|
1
|
+
"use strict";var hc=Object.defineProperty;var fc=(e,t,n)=>t in e?hc(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var b=(e,t,n)=>fc(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Ce=require("@sendbird/chat"),l=require("react"),U=require("styled-components"),ut=require("date-fns"),gc=require("date-fns/locale/en-US"),Le=require("@sendbird/chat/message"),he=require("@sendbird/chat/aiAgent"),pc=require("react-dom"),Qe=require("@sendbird/chat/groupChannel"),_c=require("date-fns/isSameDay"),Ec=require("dompurify"),Or=e=>e&&e.__esModule?e:{default:e};function Cc(e){if(e&&e.__esModule)return e;const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const bc=Or(Ce),a=Cc(l),_=Or(U),Wo=Or(Ec),jo=e=>{try{return JSON.parse(e===""?"{}":e)}catch{return{}}},vc=e=>{const t=jo(e);return typeof t=="object"&&t!==null?t:{}},Xo=e=>typeof e=="string"?vc(e):e??{},Sc=e=>!!Xo(e).stream,Cs=e=>{if(typeof e=="number"&&Number.isSafeInteger(e)&&e>0)return e;if(typeof e!="string"||e.trim().length===0)return;const t=Number(e);return Number.isSafeInteger(t)&&t>0?t:void 0},Zo=e=>{const t=Xo(e),n=Cs(t.user_message_id)??Cs(t.respond_mesg_id);return{isStreaming:!!t.stream,hasResponseMetadata:Object.prototype.hasOwnProperty.call(t,"stream")||n!==void 0,...n!==void 0&&{userMessageId:n}}},St="sb-agent",Jo="KEY_IMG_ASPECT_RATIO",fr="*/*",oe={BODY_MAX_WIDTH:244,WIDE_BODY_MAX_WIDTH:640,AVATAR_SIZE:26,BODY_TIME_GAP:4,HORIZONTAL_PADDING:12,GAP_GROUPED:2,GAP_UNGROUPED:16};var vn=(e=>(e.IN_PROGRESS="IN_PROGRESS",e.COMPLETED="COMPLETED",e.CANCELED="CANCELED",e))(vn||{}),Gt=(e=>(e.IN_PROGRESS="IN_PROGRESS",e.COMPLETED="COMPLETED",e.CANCELED="CANCELED",e))(Gt||{});const yc=e=>!!(e!=null&&e.cta_button),Ac=e=>{var t;return!!((t=e==null?void 0:e.citations)!=null&&t.length)},Qo=e=>!!(e!=null&&e.form)&&!e.form.canceled_at,Tc=e=>{var t;return Qo(e)&&!((t=e==null?void 0:e.form)!=null&&t.submitted_at)},Ic=e=>{var t;return!!((t=e==null?void 0:e.suggested_replies)!=null&&t.length)},Ke=e=>{let t;return{enumerable:!0,get:()=>(t??(t=e()),t)}},Wt=e=>Object.defineProperties({},{hasMessageTemplate:Ke(()=>!!(e!=null&&e.message_template)),hasCTAButton:Ke(()=>yc(e)),hasChallenge:Ke(()=>!!(e!=null&&e.challenge)),isThinking:Ke(()=>!!(e!=null&&e.is_thinking)),hasCSAT:Ke(()=>!!(e!=null&&e.csat)),hasSuggestedReplies:Ke(()=>Ic(e)),hasCustomMessageTemplates:Ke(()=>{var t;return!!((t=e==null?void 0:e.custom_message_templates)!=null&&t.length)}),hasForm:Ke(()=>Qo(e)),hasActiveForm:Ke(()=>Tc(e)),hasSteward:Ke(()=>!!(e!=null&&e.steward)),hasCitations:Ke(()=>Ac(e))}),xc=e=>{const t=Wt(e);return t.hasMessageTemplate||t.hasCTAButton||t.hasCSAT||t.hasSuggestedReplies||t.hasForm||t.hasSteward||t.hasCitations},ei=e=>{var t;return!!((t=e==null?void 0:e.extendedMessagePayload)!=null&&t.steward)},Rc=e=>e===Gt.COMPLETED||e===Gt.CANCELED?e:Gt.IN_PROGRESS,Wn=e=>tt(e)&&!ei(e),tt=e=>!!e&&"sender"in e,Mc=(e,{aiAgentInfo:t,members:n})=>t&&nt(e,t.userId)?t:(n==null?void 0:n.find(r=>r.userId===e.sender.userId))??e.sender,wc=e=>tt(e)?e.sendingStatus==="succeeded"?String(e.messageId):e.reqId:String(e.messageId),kc=(e,t,n,r=!0)=>{if(!r||!Wn(e))return"single";const s=()=>{if(!Wn(t))return!1;const u=t.sender.userId===e.sender.userId,d=ut.isSameMinute(t.createdAt,e.createdAt);return u&&d},o=()=>{if(!Wn(n))return!1;const u=n.sender.userId===e.sender.userId,d=ut.isSameMinute(n.createdAt,e.createdAt);return u&&d},i=s(),c=o();return i&&c?"middle":i?"bottom":c?"top":"single"},nt=(e,t)=>(()=>{var r;return tt(e)?e.sender.userId:((r=e==null?void 0:e.sender)==null?void 0:r.userId)??void 0})()===t,Me={isAdmin:e=>e.isAdminMessage(),isCSAT:e=>{var t;return e.isAdminMessage()&&!!((t=e.extendedMessagePayload)!=null&&t.csat)},isSteward:e=>ei(e),isIncoming:(e,t)=>tt(e)&&e.sender.userId!==t,isOutgoing:(e,t)=>tt(e)&&(e.sender.userId===t||e.sendingStatus===Le.SendingStatus.PENDING)},We=e=>e.startsWith("image/"),jt=e=>e.startsWith("video/"),Lc=e=>e.startsWith("audio/"),ti=({name:e="",mimeType:t=""})=>t==="application/pdf"||/\.pdf$/i.test(e.trim()),Nr=(e,t)=>{if(e&&!e.startsWith(".")){const n=e.split(".").pop();if(n&&n!==e)return n.toUpperCase()}if(t){const[,n]=t.split("/");if(n)return n.toUpperCase()}return"FILE"},ni=e=>{var t;return e.messageType==="file"?e.message.length>0&&e.file.name!==e.message:e.messageType==="multipleFiles"?e.message.length>0&&((t=e.files[0])==null?void 0:t.name)!==e.message:e.message.length>0},Oc=e=>{if(e.message&&e.message.trim().length>0)return!0;const t=e.extendedMessagePayload;return xc(t)},kn=e=>{switch(e){case"top":case"middle":return oe.GAP_GROUPED;default:return oe.GAP_UNGROUPED}},Nc=(e,t)=>{const n=/```(\w+)?\n([\s\S]*?)```/g,r=[];let s=0;return e.replace(n,(o,...i)=>{const[c,u,d]=i;return s<d&&r.push({type:"text",value:e.slice(s,d).trim()}),r.push({type:"code",value:u.trim(),language:c?c.trim():"plaintext"}),s=d+o.length,o}),s<e.length&&r.push({type:"text",value:e.slice(s).trim()}),t?r.map(o=>o.type!=="text"?o:{...o,value:t(o.value)}):r},Dc=e=>e.replace(/\[([^\]]+)\](?!\()/g,"\\[$1\\]"),$c=e=>e.replace(/([a-zA-Z0-9])_(?=[a-zA-Z0-9])/g,"$1\\_"),Pc=e=>e.replace(/~~/g,"\\~\\~"),Fc=e=>{let t=e;return t=Dc(t),t=$c(t),t=Pc(t),t},Uc=typeof navigator<"u"&&navigator.product==="ReactNative",gr=(e,t)=>{const n=r=>!t||t.length===0?!0:tt(r)&&t.includes(r.sendingStatus);return Uc?e.find(n):e.findLast(n)},Bc=(e,t)=>{const n=gr(e,[Le.SendingStatus.SUCCEEDED]);return n&&Me.isIncoming(n,t)?n:void 0},Ie=e=>{requestAnimationFrame(()=>{requestAnimationFrame(e)})};function me(){}function Hc(){const e=typeof navigator<"u"?navigator.userAgent:"",t=/iPad|iPhone|iPod/.test(e),n=/Android/.test(e);return t||n}function Gc(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return t.toString(16)}const we={isStreaming(e){return Sc(e.data)},isExplicitWelcomeMessage(e){var t;return((t=e.extendedMessagePayload)==null?void 0:t.bot_message_type)==="welcome"},isWelcomeMessage(e,t){var r;if(we.isExplicitWelcomeMessage(e))return!0;if(((r=e.extendedMessagePayload)==null?void 0:r.bot_message_type)!==void 0||!nt(e,t))return!1;const n=Zo(e.data);return!n.isStreaming&&!n.hasResponseMetadata},isGeneratedMessage(e){var t;return((t=e.extendedMessagePayload)==null?void 0:t.bot_message_type)==="generated"},hasFeedback(e){var t;return!!((t=e.extendedMessagePayload)!=null&&t.feedback)}},jn=`@${St}`,zc=({appId:e,aiAgentId:t,storage:n})=>{const r={templateBase:`${jn}-template`,template:s=>`${r.templateBase}/templates/${s}`,templateToken:()=>`${r.templateBase}/tokens`,messengerSession:s=>{const o=Gc(`${e}/${t}/${s}`);return`${jn}-udata/${o}`},anonUserSession:()=>`${jn}-session/${e}/${t}`};return{template:{set:(s,o)=>n.set(r.template(s),o),get:s=>n.get(r.template(s)),setCachedToken:s=>n.set(r.templateToken(),s),getCachedToken:()=>n.get(r.templateToken()),clear:()=>{n.getKeys(r.templateBase).forEach(n.delete)}},messenger:{getSettings:s=>{try{const o=n.get(r.messengerSession(s));return o?JSON.parse(o):null}catch{return null}},setSettings:(s,o)=>{try{delete o.auto_created_user;const i=JSON.stringify(o);n.set(r.messengerSession(s),i)}catch{return}},getAnonUser:()=>{try{const s=n.get(r.anonUserSession());return s?JSON.parse(s):null}catch{return null}},setAnonUser:s=>{try{const o=JSON.stringify(s);n.set(r.anonUserSession(),o)}catch{return}},clear:s=>{try{s&&n.delete(r.messengerSession(s)),n.delete(r.anonUserSession())}catch{return}}}}},ri=(e,t,n={})=>{let r=null,s=null,o=null;const{leading:i=!0,trailing:c=!0}=n,u=(...d)=>{const m=Date.now();if(o===null||m-o>=t)i?(e(...d),o=m):(s=d,o=m);else if(s=d,c&&!r){const h=t-(m-o);r=setTimeout(()=>{s&&c&&(e(...s),o=Date.now()),r=null,s=null},h)}};return u.cancel=()=>{r&&(clearTimeout(r),r=null),s=null,o=null},u},Vc=()=>{let e=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const n=(e+Math.random()*16)%16|0;return e=Math.floor(e/16),(t==="x"?n:n&3|8).toString(16)})};class qc{constructor(t){b(this,"_params");this._params={aiAgentChannelFilter:(t==null?void 0:t.aiAgentChannelFilter)??he.AIAgentChannelFilter.INCLUDE,aiAgentConversationStatusFilter:(t==null?void 0:t.aiAgentConversationStatusFilter)??[he.ConversationStatus.OPEN,he.ConversationStatus.CLOSED],aiAgentIds:(t==null?void 0:t.aiAgentIds)??[],deskChannelFilter:(t==null?void 0:t.deskChannelFilter)??he.DeskChannelFilter.INCLUDE,pinnedChannelUrls:(t==null?void 0:t.pinnedChannelUrls)??[],copilotConversationOnly:(t==null?void 0:t.copilotConversationOnly)??!1,copilotSupportChannelUrl:t==null?void 0:t.copilotSupportChannelUrl}}get params(){return{...this._params}}match(t,n){const{pinnedChannelUrls:r,aiAgentChannelFilter:s,aiAgentConversationStatusFilter:o,aiAgentIds:i,deskChannelFilter:c}=this._params;return r!=null&&r.includes(t.url)?!0:t.isAIAgent?!(!t.conversation||s===he.AIAgentChannelFilter.EXCLUDE||i&&i.length>0&&!i.includes(t.conversation.aiAgentId)||o&&o.length>0&&!o.some(d=>{var m;return((m=t.conversation)==null?void 0:m.status)===d})):t.isDesk?c!==he.DeskChannelFilter.EXCLUDE:!1}}class si extends Qe.BaseChannelCollection{constructor(n,r){const s=new qc(r.filter),o=n,i=o.aiAgent._manager,c=r.limit??20,u=Qe.GroupChannelListOrder.LATEST_LAST_MESSAGE,d={getRemoteChannels:(m,h,f,g)=>i.getMyGroupChannels(m,h.params,g),changeLogSync:m=>{const{aiAgentChannelFilter:h,aiAgentIds:f,deskChannelFilter:g,pinnedChannelUrls:p,copilotConversationOnly:v,copilotSupportChannelUrl:S}=s.params,C={aiAgentChannelFilter:h,aiAgentIds:f,deskChannelFilter:g,pinnedChannelUrls:p,copilotConversationOnly:v,copilotSupportChannelUrl:S};return i.getMyGroupChannelChangeLogs(m,C,Qe.GroupChannelEventSource.SYNC_CHANNEL_CHANGELOGS)}};super(o.aiAgent._iid,{filter:s,order:u,limit:c,syncKeyPrefix:"aiAgent",fetcher:d});b(this,"_params");b(this,"_sdk");b(this,"_throttledOnChannelChanged");b(this,"_key");b(this,"_pendingChannels",[]);this._sdk=n,this._params=r,this._key=`clc-${Vc()}`,this._throttledOnChannelChanged=ri(()=>{var g;const m=[...this._pendingChannels];this._pendingChannels=[];const h=new Map;for(const{channel:p,context:v}of m)h.delete(p.url),h.set(p.url,{channel:p,context:v});const f=new Map;for(const{channel:p,context:v}of h.values())f.has(v)||f.set(v,new Map),f.get(v).set(p.url,p);for(const[p,v]of f){const S=Array.from(v.values()),C=(g=this._sdk.currentUser)==null?void 0:g.userId,A=S.filter(T=>this.filter.match(T,C)),y=S.filter(T=>!this.filter.match(T,C)).map(T=>T.url);A.length>0&&this._base._addChannelsToView(A,p,!1),y.length>0&&this._removeChannels(y,p)}},250,{trailing:!0,leading:!0}),this._base._subscribeChannelEvent(this._key,{onUpdate:(m,h)=>{for(const f of m)this._pendingChannels.push({channel:f,context:h});this._throttledOnChannelChanged()},onRemove:(m,h)=>{this._removeChannels(m,h)}})}get _base(){return this}_removeChannels(n,r){const s=new Set(n);this._pendingChannels=this._pendingChannels.filter(({channel:o})=>!s.has(o.url)),this._base._removeChannelsFromView(n,r)}get channels(){var c;const n=((c=this._params.filter)==null?void 0:c.pinnedChannelUrls)??[],r=[],s=new Map(super.channels.map(u=>[u.url,u])),o=new Set;for(const u of n){const d=s.get(u);d&&!o.has(u)&&(r.push(d),o.add(u))}const i=super.channels.filter(u=>!o.has(u.url));return[...r,...i]}setConversationListCollectionHandler(n){super.setGroupChannelCollectionHandler(n)}dispose(){super.dispose(),this._throttledOnChannelChanged.cancel(),this._base._unsubscribeChannelEvent(this._key)}}class oi{constructor(t){b(this,"subscribers",{});this.logger=t}async send(t){const n=Kc(),r=this.subscribers[t.type];if(r){this.logger.debug(`messenger.dispatcher: dispatching command: ${t.type}`,t.payload);const s=r.map(o=>o(t.payload));await Promise.all(s).catch(o=>{this.logger.error(`messenger.dispatcher: error in callback for command: ${t.type}`,o)})}return n.resolve(),n.promise}subscribe(t,n){this.subscribers[t]||(this.subscribers[t]=[]),this.subscribers[t].push(n)}unsubscribe(t,n){const r=this.subscribers[t];r&&(this.subscribers[t]=r.filter(s=>s!==n))}}const Kc=()=>{let e=me,t=me;return{promise:new Promise((r,s)=>{e=r,t=s}),resolve:e,reject:t}};var Be=(e=>(e.ConversationClose="conv.close",e.MessengerSettingsUpdated="messenger.settings.updated",e.ActiveChannelUpdated="active.channel.updated",e.AnonymousSessionTokenExpired="anon.token.expired",e.AuthTokenRefreshed="auth.token.refreshed",e.NudgeMessageReceived="nudge.message.received",e))(Be||{});class wt{constructor(t={}){b(this,"payload");this.payload=t}toJSON(){return JSON.stringify({type:this.type,payload:this.payload})}}const at={CloseConversation:e=>new Yc(e),MessengerSettingsUpdated:e=>new Wc(e),ActiveChannelUpdated:e=>new jc(e),AnonymousSessionTokenExpired:()=>new Xc,AuthTokenRefreshed:()=>new Zc,NudgeMessageReceived:e=>new Jc(e)};class Yc extends wt{constructor(){super(...arguments);b(this,"type","conv.close")}}class Wc extends wt{constructor(){super(...arguments);b(this,"type","messenger.settings.updated")}}class jc extends wt{constructor(){super(...arguments);b(this,"type","active.channel.updated")}}class Xc extends wt{constructor(){super(...arguments);b(this,"type","anon.token.expired")}}class Zc extends wt{constructor(){super(...arguments);b(this,"type","auth.token.refreshed")}}class Jc extends wt{constructor(){super(...arguments);b(this,"type","nudge.message.received")}}const Xt=e=>{const t={};for(const n of Object.keys(e)){const r=e[n];r!==void 0&&(t[n]=String(r))}return t};class Zt{constructor(t){b(this,"category","connection");this.userId=t}get data(){return Xt({user_id:this.userId})}}class Qc extends Zt{constructor(){super(...arguments);b(this,"metricKey","connection_connected")}}class el extends Zt{constructor(){super(...arguments);b(this,"metricKey","connection_reconnect_started")}}class tl extends Zt{constructor(){super(...arguments);b(this,"metricKey","connection_reconnect_succeeded")}}class nl extends Zt{constructor(){super(...arguments);b(this,"metricKey","connection_reconnect_failed")}}class rl extends Zt{constructor(){super(...arguments);b(this,"metricKey","connection_disconnected")}}class sl{constructor(t){b(this,"lastKey",null);this.dispatch=t}handleEvent({detail:t,userId:n}){const r=`${t}:${n}`;if(this.shouldEmit(r)){this.lastKey=r;const s=t==="connected"?new Qc(n):t==="reconnectStarted"?new el(n):t==="reconnectSucceeded"?new tl(n):t==="reconnectFailed"?new nl(n):new rl(n);this.dispatch(s)}}shouldEmit(t){return t!==this.lastKey}}class Dr{constructor(t,n){b(this,"category","conversation");this.channelUrl=t,this.conversationId=n}get data(){return Xt({channel_url:this.channelUrl,conversation_id:this.conversationId})}}class ol extends Dr{constructor(){super(...arguments);b(this,"metricKey","conversation_initialized")}}class il extends Dr{constructor(){super(...arguments);b(this,"metricKey","conversation_open")}}class al extends Dr{constructor(){super(...arguments);b(this,"metricKey","conversation_closed")}}class cl{constructor(t){b(this,"statusByChannel",new Map);this.dispatch=t}handleEvent({channel:t}){const{conversation:n}=t;if(!n)return;const r=this.statusByChannel.get(t.url),s=n.status;if(this.statusByChannel.set(t.url,s),this.shouldEmit(r,s)){const o=s===he.ConversationStatus.INITIALIZED?new ol(t.url,n.id):s===he.ConversationStatus.OPEN?new il(t.url,n.id):new al(t.url,n.id);this.dispatch(o)}}shouldEmit(t,n){return n===he.ConversationStatus.INITIALIZED?t===void 0:n===he.ConversationStatus.OPEN?t===he.ConversationStatus.INITIALIZED:t===he.ConversationStatus.OPEN}}const ii=(e,t)=>{if(e)return e.members.filter(n=>n.userId!==t).sort((n,r)=>r.joinedAt-n.joinedAt)[0]},De=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===he.ConversationStatus.CLOSED||e!=null&&e.isDesk&&((n=e==null?void 0:e.helpdeskInfo)==null?void 0:n.ticketStatus)==="closed")},$r=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===he.ConversationStatus.OPEN||e!=null&&e.isDesk&&((n=e==null?void 0:e.helpdeskInfo)==null?void 0:n.ticketStatus)==="open")};function ct(e){var n,r,s;return typeof(((n=e==null?void 0:e.conversation)==null?void 0:n.handedOverAt)??((s=(r=e==null?void 0:e.conversation)==null?void 0:r.handoff)==null?void 0:s.timestamp))=="number"}function ll(e){var r;const t=(r=e==null?void 0:e.conversation)==null?void 0:r.handoff;return t?typeof t.requestedAt=="number"&&!ct(e):!1}function ul(e){var t;if(((t=e==null?void 0:e.resolution)==null?void 0:t.determinedBy)==="user")return e.resolution.isResolved}function ai(e){return!!e&&e<=Date.now()}function dl(e){return!e.title}function ml(e,t){var n;if(e)return dl(e)?{...e,title:t.title,csat_question:t.question,csat_scores:[{label:"",image_url:"https://static.dashboard.sendbird.com/assets/ai-agent/angry-active.png"},{label:"",image_url:"https://static.dashboard.sendbird.com/assets/ai-agent/suspicious-active.png"},{label:"",image_url:"https://static.dashboard.sendbird.com/assets/ai-agent/neutral-active.png"},{label:"",image_url:"https://static.dashboard.sendbird.com/assets/ai-agent/smile-active.png"},{label:"",image_url:"https://static.dashboard.sendbird.com/assets/ai-agent/happy-active.png"}],cre:{required:((n=e.cre)==null?void 0:n.required)??!0,question:t.cre.question,positive_label:t.cre.positive_label,negative_label:t.cre.negative_label},follow_up:[{response_type:"free_text",scores:[1,2,3,4,5],question:t.followUp.question,always_visible:!1}],csat_submit_label:t.submit_label,csat_submitted_label:t.submitted_label}:e}class Pr{constructor(t,n){b(this,"category","handoff");this.channelUrl=t,this.conversationId=n}get data(){return Xt({channel_url:this.channelUrl,conversation_id:this.conversationId})}}class hl extends Pr{constructor(){super(...arguments);b(this,"metricKey","handoff_started")}}class fl extends Pr{constructor(){super(...arguments);b(this,"metricKey","handoff_succeeded")}}class gl extends Pr{constructor(){super(...arguments);b(this,"metricKey","handoff_failed")}}class pl{constructor(t){b(this,"statusByChannel",new Map);this.dispatch=t}handleEvent({channel:t}){const n=!this.statusByChannel.has(t.url);n&&this.statusByChannel.set(t.url,void 0);const r=t.conversation;if(!r||!r.handoff||n)return;const s=this.statusByChannel.get(t.url),o=this.resolveStatus(t,r);if(o!==void 0&&this.shouldEmit(s,o)){this.statusByChannel.set(t.url,o);const i=o==="started"?new hl(t.url,r.id):o==="succeeded"?new fl(t.url,r.id):new gl(t.url,r.id);this.dispatch(i)}}resolveStatus(t,n){if(De(t))return"failed";const{members:r}=t;if(r.length===1)return"started";if(r.length===2&&n.aiAgentId&&!r.some(s=>s.userId===n.aiAgentId))return"succeeded"}shouldEmit(t,n){return n==="started"?t===void 0:t==="started"}}class _l{constructor(t){b(this,"category","message");b(this,"metricKey","incoming_message_received");b(this,"channelUrl");b(this,"messageId");b(this,"senderType");b(this,"createdAt");b(this,"conversationId");this.channelUrl=t.channelUrl,this.messageId=t.messageId,this.senderType=t.senderType,this.createdAt=t.createdAt,this.conversationId=t.conversationId}get data(){return Xt({channel_url:this.channelUrl,message_id:this.messageId,sender_type:this.senderType,created_at:this.createdAt,conversation_id:this.conversationId})}}const El=(e,t)=>{const n=tt(e)?e.sender.userId:void 0;return n===void 0?"system":n===t?"ai_agent":"human_agent"};class Cl{constructor(t,n){this.dispatch=t,this.getCurrentUserId=n}handleEvent({channel:t,message:n}){const{conversation:r}=t;this.shouldEmit(n,r)&&this.dispatch(new _l({channelUrl:t.url,messageId:n.messageId,senderType:El(n,r.aiAgentId),createdAt:n.createdAt,conversationId:r.id}))}shouldEmit(t,n){return!nt(t,this.getCurrentUserId())&&n!==null}}class bl{constructor(t){b(this,"category","message");b(this,"metricKey");b(this,"channelUrl");b(this,"requestId");b(this,"messageId");b(this,"target");b(this,"sendingStatus");b(this,"createdAt");b(this,"conversationId");this.channelUrl=t.channelUrl,this.requestId=t.requestId,this.messageId=t.messageId,this.target=t.target,this.sendingStatus=t.sendingStatus,this.createdAt=t.createdAt,this.conversationId=t.conversationId,this.metricKey=`outgoing_message_${t.sendingStatus}`}get data(){return Xt({channel_url:this.channelUrl,request_id:this.requestId,message_id:this.messageId,target:this.target,created_at:this.createdAt,conversation_id:this.conversationId})}}const vl=e=>{switch(e){case Le.SendingStatus.PENDING:return"pending";case Le.SendingStatus.SUCCEEDED:return"succeeded";case Le.SendingStatus.FAILED:return"failed";case Le.SendingStatus.SCHEDULED:return"scheduled";default:return}};class Sl{constructor(t,n){b(this,"statusByReqId",new Map);this.dispatch=t,this.getCurrentUserId=n}handleEvent({channel:t,message:n}){var o;if(!nt(n,this.getCurrentUserId()))return;const r=vl(n.sendingStatus);if(r===void 0)return;const s=this.statusByReqId.get(n.reqId);this.statusByReqId.set(n.reqId,r),r!=="scheduled"&&this.shouldEmit(s,r)&&this.dispatch(new bl({channelUrl:t.url,requestId:n.reqId,messageId:r==="succeeded"?n.messageId:void 0,target:ct(t)?"human_agent":"ai_agent",sendingStatus:r,createdAt:n.createdAt,conversationId:(o=t.conversation)==null?void 0:o.id}))}shouldEmit(t,n){return n==="pending"?t!=="pending"&&t!=="succeeded":n==="succeeded"?t==="pending"||t==="scheduled":t!=="failed"}}class yl{constructor(t){b(this,"id","aiagent_livemetric");b(this,"dispatch");b(this,"emit",({category:t,metricKey:n,data:r})=>{var s;(s=this.dispatch)==null||s.call(this,{category:t,metricKey:n,data:r})});b(this,"emitters");this.chatSDK=t;const n=()=>{var r;return(r=this.chatSDK.currentUser)==null?void 0:r.userId};this.emitters={connection:new sl(this.emit),conversation:new cl(this.emit),handoff:new pl(this.emit),incomingMessage:new Cl(this.emit,n),outgoingMessage:new Sl(this.emit,n)}}start(){const t=new Ce.ConnectionHandler({onConnected:r=>this.trackConnection("connected",r),onDisconnected:r=>this.trackConnection("disconnected",r),onReconnectStarted:()=>this.trackConnection("reconnectStarted"),onReconnectSucceeded:()=>this.trackConnection("reconnectSucceeded"),onReconnectFailed:()=>this.trackConnection("reconnectFailed")}),n=new Qe.GroupChannelHandler({onMessageReceived:(r,s)=>{r.isGroupChannel()&&this.track({type:"incomingMessage",channel:r,message:s})},onChannelChanged:r=>{r.isGroupChannel()&&(this.track({type:"handoff",channel:r}),this.track({type:"conversation",channel:r}))},onUserJoined:r=>this.track({type:"handoff",channel:r}),onUserLeft:r=>this.track({type:"handoff",channel:r})});this.chatSDK.addConnectionHandler(this.id,t),this.chatSDK.groupChannel.addGroupChannelHandler(this.id,n)}track(t){try{this.emitters[t.type].handleEvent(t)}catch{}}dispose(){this.chatSDK.removeConnectionHandler(this.id),this.chatSDK.groupChannel.removeGroupChannelHandler(this.id)}trackConnection(t,n=(r=>(r=this.chatSDK.currentUser)==null?void 0:r.userId)()){n&&this.track({type:"connection",detail:t,userId:n})}}var Fr=(e=>(e[e.VERBOSE=0]="VERBOSE",e[e.DEBUG=1]="DEBUG",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e[e.NONE=5]="NONE",e))(Fr||{});class ci{constructor(t){b(this,"level");this.level=t}verbose(...t){this.level<=0&&console.log(`[${St}/verbose]`,...t)}debug(...t){this.level<=1&&console.log(`[${St}/debug]`,...t)}info(...t){this.level<=2&&console.log(`[${St}/info]`,...t)}warn(...t){this.level<=3&&console.warn(`[${St}/warn]`,...t)}error(...t){this.level<=4&&console.error(`[${St}/error]`,...t)}}class li{constructor({userId:t,authToken:n,sessionHandler:r}){b(this,"userId");b(this,"authToken");b(this,"sessionHandler");this.userId=t,this.authToken=n,this.sessionHandler=r}}class pr{constructor(){b(this,"userId");b(this,"authToken");b(this,"sessionHandler")}}const Al=e=>({onSessionTokenRequired:t=>{t(null),e.send(at.AnonymousSessionTokenExpired())}}),Ur=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!=null)),Tl="ai_agent:stats",Il="conversation_initial_render",xl="conversation_not_interactive_timeout",Rl="recovery_not_interactive_timeout",Ml="conversation_list_initial_render",wl="message_pending_stuck",kl="aiev_auth_expired_unhandled",Ll="user_perceived_response_time",Ol="stream_stalled",Nl="ai_typing_indicator_absent_timeout",Dl="rendered_content_unusable",$l=800220;var j=(e=>(e.ACK_TO_FIRST_CHUNK="ack_to_first_chunk_ms",e.AFTER_TPEN_ABSENT="after_tpen_absent_ms",e.AUTH="auth_duration_ms",e.BEFORE_TPST_ABSENT="before_tpst_absent_ms",e.FIRST_CHUNK_TO_RENDER="first_chunk_to_render_ms",e.GET_CHANNEL="get_channel_duration_ms",e.GET_LIST="get_list_duration_ms",e.GET_MESSAGES="get_messages_duration_ms",e.PAGE_RENDER="page_render_duration_ms",e.PAGE_RENDER_FROM_CACHE="total_duration_from_cache_ms",e.SEND_TO_ACK="send_to_ack_ms",e.TIMEOUT="timeout_ms",e))(j||{});const _r=(e,t)=>e.startAt===null||e.endedAt===null||t.startAt===null||t.endedAt===null?0:Math.max(0,Math.min(e.endedAt,t.endedAt)-Math.max(e.startAt,t.startAt)),ui=e=>typeof e=="object"&&e!==null,Pl=e=>{if(ui(e))return typeof e.code=="number"?e.code:void 0},Fl=e=>e instanceof Error?e.message:typeof e=="string"?e:ui(e)&&typeof e.message=="string"?e.message:"";class rt{constructor(){b(this,"timers",new Map);b(this,"committed",!1);b(this,"commitCallback",null);b(this,"conversationId",null);b(this,"errorCode",null);b(this,"errorDescription",null);b(this,"extraData",{})}setCommitCallback(t){return this.commitCallback=t,this}setConversationId(t){return t&&(this.conversationId=t),this}setError(t){return t==null?this:(this.errorCode=Pl(t)??$l,this.errorDescription=Fl(t),this)}setExtra(t,n){return n!=null&&(this.extraData[t]=n),this}startTimer(t){if(this.committed)return this;const n=this.timers.get(t);return(n==null?void 0:n.startTime)!==null&&(n==null?void 0:n.startTime)!==void 0?this:(this.timers.set(t,{startTime:performance.now(),endTime:null}),this)}stopTimer(t){if(this.committed)return this;const n=this.timers.get(t);return!n||n.startTime===null||n.endTime!==null?this:(this.timers.set(t,{...n,endTime:performance.now()}),this)}getTimer(t){const n=this.timers.get(t);return!n||n.startTime===null?{startAt:null,endedAt:null,duration:null}:{startAt:n.startTime,endedAt:n.endTime,duration:n.endTime===null?null:n.endTime-n.startTime}}createPayload(t,n){const r={key:this.getMetricKey(),value:String(t)},s=(n==null?void 0:n.conversationId)??this.conversationId??void 0;s!==void 0&&(r.conversation_id=s),this.errorCode!==null&&(r.error_code=this.errorCode,r.error_description=this.errorDescription??"");const o=Ur({...this.extraData,...n==null?void 0:n.extra});return Object.keys(o).length>0&&(r.extra=o),r}isCommitted(){return this.committed}discard(){this.committed=!0}commit(){if(this.committed||!this.commitCallback)return!1;const t=this.buildPayload();return t?(this.committed=!0,this.commitCallback(Tl,t)):!1}}class bs extends rt{constructor(){super(...arguments);b(this,"reason");b(this,"aiAgentId")}setReason(n){return this.reason=n,this}setAIAgentId(n){return this.aiAgentId=n,this}getMetricKey(){return kl}buildPayload(){return this.reason===void 0||this.aiAgentId===void 0?null:this.createPayload(this.reason,{extra:{agent_id:this.aiAgentId}})}}class Ln{constructor(t){b(this,"commitCallback");this.commitCallback=t}}class kt extends Ln{constructor(){super(...arguments);b(this,"records",new Map)}}class di extends Ln{constructor(){super(...arguments);b(this,"activeSpan",null);b(this,"visible",!0)}setVisible(n){var r;this.visible=n,(r=this.activeSpan)==null||r.onVisibilityChanged(n)}}class mi{constructor(t,n){b(this,"stats");b(this,"visible");b(this,"completedHidden",!1);this.stats=t,this.visible=n}get isRecording(){return this.stats!==null&&!this.stats.isCommitted()}onVisibilityChanged(t){this.stats&&(this.visible=t,t&&this.completedHidden&&(this.stats.commit(),this.stats=null))}commitOrDefer(){if(this.stats){if(!this.visible){this.completedHidden=!0;return}this.stats.commit(),this.stats=null}}cancel(){this.stats=null}}const gt=(e,t)=>!(e&&t&&e!==t),Er=(e,t)=>{for(const n of e)if(n.measure.userMessageId===void 0&>(n.measure.channelUrl,t))return!0;return!1},On=(e,t)=>{if(e.size<t)return;const n=e.keys().next();n.done||e.delete(n.value)};class Ul extends Ln{onPayloadParseFailed(t){new bs().setReason("payload_parse_failed").setAIAgentId(t.aiAgentId).setCommitCallback(this.commitCallback).commit()}onCallbackNotFound(t){new bs().setReason("callback_not_found").setAIAgentId(t.aiAgentId).setCommitCallback(this.commitCallback).commit()}clear(){}}class Bl extends rt{constructor(){super(...arguments);b(this,"channelUrl",null);b(this,"presentMethod","direct_present")}setChannelUrl(n){return this.channelUrl=n,this}setPresentMethod(n){return this.presentMethod=n,this}resetPageRenderSpan(){return this.timers.delete(j.PAGE_RENDER),this.timers.delete(j.PAGE_RENDER_FROM_CACHE),this.timers.delete(j.GET_CHANNEL),this.timers.delete(j.GET_MESSAGES),this.conversationId=null,this.channelUrl=null,this.errorCode=null,this.errorDescription=null,this}getMetricKey(){return Il}buildPayload(){const n=this.getTimer(j.AUTH),r=this.getTimer(j.PAGE_RENDER),s=this.getTimer(j.PAGE_RENDER_FROM_CACHE);if(r.duration===null&&(this.errorCode===null||n.duration===null))return null;const o=r.duration===null?0:r.duration-_r(n,r),i=s.duration===null?null:s.duration-_r(n,s);return this.createPayload((n.duration??0)+o,{extra:{channel_url:this.channelUrl,present_method:this.presentMethod,[j.AUTH]:n.duration,[j.GET_CHANNEL]:this.getTimer(j.GET_CHANNEL).duration,[j.GET_MESSAGES]:this.getTimer(j.GET_MESSAGES).duration,[j.PAGE_RENDER_FROM_CACHE]:i}})}}class Hl extends mi{constructor(n,r,s){var o;super(n,s);b(this,"measure");this.measure={channelUrl:r,pageRenderState:"initialized"},(o=this.stats)==null||o.setChannelUrl(r).startTimer(j.PAGE_RENDER).startTimer(j.PAGE_RENDER_FROM_CACHE)}onGetChannelStart(n){!this.stats||n!==this.measure.channelUrl||this.measure.pageRenderState!=="initialized"||(this.stats.startTimer(j.GET_CHANNEL),this.measure.pageRenderState="channel_fetching")}onGetChannelComplete(n,r){!this.stats||n!==this.measure.channelUrl||this.measure.pageRenderState!=="channel_fetching"||(this.stats.stopTimer(j.GET_CHANNEL).setConversationId(r),this.measure.pageRenderState="channel_fetched")}onGetChannelError(n,r){!this.stats||n!==this.measure.channelUrl||this.measure.pageRenderState!=="channel_fetching"||(this.stats.stopTimer(j.GET_CHANNEL).setError(r).stopTimer(j.PAGE_RENDER),this.measure.pageRenderState="channel_failed",this.tryFinalize())}onGetMessagesStart(){!this.stats||this.measure.pageRenderState!=="channel_fetched"||(this.stats.startTimer(j.GET_MESSAGES),this.measure.pageRenderState="messages_fetching")}onGetMessagesCacheComplete(n,r){!this.stats||n!==this.measure.channelUrl||r||this.measure.pageRenderState!=="messages_fetching"||this.stats.stopTimer(j.PAGE_RENDER_FROM_CACHE)}onGetMessagesComplete(n,r){!this.stats||n!==this.measure.channelUrl||this.measure.pageRenderState!=="messages_fetching"||(this.stats.stopTimer(j.GET_MESSAGES).setError(r),this.measure.pageRenderState="messages_fetching_completed")}onRendered(){!this.stats||this.measure.pageRenderState!=="messages_fetching_completed"||(this.stats.stopTimer(j.PAGE_RENDER),this.tryFinalize())}onRenderDiscarded(){!this.stats||this.measure.pageRenderState!=="messages_fetching_completed"||(this.stats.discard(),this.stats=null)}onAuthSettled(){this.tryFinalize()}tryFinalize(){if(!this.stats||this.stats.getTimer(j.PAGE_RENDER).endedAt===null)return;const n=this.stats.getTimer(j.AUTH);if(!(n.startAt!==null&&n.endedAt===null)){if(this.measure.pageRenderState==="channel_failed"){this.stats.commit(),this.stats=null;return}this.commitOrDefer()}}}class Gl extends di{constructor(){super(...arguments);b(this,"stats",null);b(this,"authState","idle");b(this,"presentMethod","direct_present")}getOrCreateStats(){var n;return(n=this.stats)!=null&&n.isCommitted()?null:(this.stats||(this.stats=new Bl().setCommitCallback(this.commitCallback).setPresentMethod(this.presentMethod)),this.stats)}getActiveStats(){return!this.stats||this.stats.isCommitted()?null:this.stats}setPresentMethod(n){var r;this.presentMethod=n,(r=this.getActiveStats())==null||r.setPresentMethod(n)}onAuthStart(){var n,r;if((n=this.stats)!=null&&n.isCommitted()){if(this.authState!=="failed"||this.activeSpan!==null)return;this.stats=null,this.authState="idle"}this.authState==="idle"&&(this.authState="in_progress",(r=this.getOrCreateStats())==null||r.startTimer(j.AUTH))}onAuthComplete(){var n,r;this.authState==="in_progress"&&(this.authState="completed",(n=this.getActiveStats())==null||n.stopTimer(j.AUTH)),(r=this.activeSpan)==null||r.onAuthSettled()}onAuthError(n){var r,s;this.authState==="in_progress"&&(this.authState="failed",(r=this.getActiveStats())==null||r.stopTimer(j.AUTH).setError(n).commit(),(s=this.activeSpan)==null||s.cancel())}startSpan(n){const r=this.activeSpan;r==null||r.cancel();const s=this.getOrCreateStats();return s&&r&&s.resetPageRenderSpan(),this.activeSpan=new Hl(s,n,this.visible),this.activeSpan}clear(){var n;(n=this.activeSpan)==null||n.cancel(),this.activeSpan=null,this.stats=null,this.authState="idle"}}class zl extends rt{constructor(){super(...arguments);b(this,"presentMethod","direct_present")}setPresentMethod(n){return this.presentMethod=n,this}resetPageRenderSpan(){return this.timers.delete(j.PAGE_RENDER),this.timers.delete(j.GET_LIST),this.errorCode=null,this.errorDescription=null,this}getMetricKey(){return Ml}buildPayload(){const n=this.getTimer(j.AUTH),r=this.getTimer(j.PAGE_RENDER),s=this.getTimer(j.GET_LIST).duration;if(r.duration===null&&(this.errorCode===null||n.duration===null))return null;const o=r.duration===null?0:r.duration-_r(n,r),i=(n.duration??0)+o;return this.createPayload(i,{extra:{present_method:this.presentMethod,[j.AUTH]:n.duration,[j.GET_LIST]:s}})}}class Vl extends mi{constructor(n,r){var s;super(n,r);b(this,"measure",{listStarted:!1,listCompleted:!1});(s=this.stats)==null||s.startTimer(j.PAGE_RENDER)}onListRequestStart(){!this.stats||this.measure.listStarted||(this.stats.startTimer(j.PAGE_RENDER),this.stats.startTimer(j.GET_LIST),this.measure.listStarted=!0)}onListRequestComplete(n){if(!(!this.stats||!this.measure.listStarted||this.measure.listCompleted)){if(n){this.stats.resetPageRenderSpan(),this.measure.listStarted=!1;return}this.stats.stopTimer(j.GET_LIST),this.measure.listCompleted=!0}}onRendered(){!this.stats||!this.measure.listCompleted||(this.stats.stopTimer(j.PAGE_RENDER),this.tryFinalize())}onRenderDiscarded(){!this.stats||!this.measure.listCompleted||(this.stats.discard(),this.stats=null)}onAuthSettled(){this.tryFinalize()}tryFinalize(){if(!this.stats||this.stats.getTimer(j.PAGE_RENDER).endedAt===null)return;const n=this.stats.getTimer(j.AUTH);n.startAt!==null&&n.endedAt===null||this.commitOrDefer()}}class ql extends di{constructor(){super(...arguments);b(this,"stats",null);b(this,"authState","idle");b(this,"presentMethod","direct_present")}getOrCreateStats(){var n;return(n=this.stats)!=null&&n.isCommitted()?null:(this.stats||(this.stats=new zl().setCommitCallback(this.commitCallback).setPresentMethod(this.presentMethod)),this.stats)}getActiveStats(){return!this.stats||this.stats.isCommitted()?null:this.stats}setPresentMethod(n){var r;this.presentMethod=n,(r=this.getActiveStats())==null||r.setPresentMethod(n)}onAuthStart(){var n;this.authState="in_progress",(n=this.getOrCreateStats())==null||n.startTimer(j.AUTH)}onAuthComplete(){var r,s;const n=this.authState==="in_progress";this.authState="completed",n&&((r=this.getActiveStats())==null||r.stopTimer(j.AUTH)),(s=this.activeSpan)==null||s.onAuthSettled()}onAuthError(n){var o;const r=this.authState==="in_progress";this.authState="failed";const s=this.getActiveStats();if(s){if(!((o=this.activeSpan)!=null&&o.isRecording)){this.stats=null;return}r&&s.stopTimer(j.AUTH),s.setError(n).commit(),this.activeSpan.cancel()}}startSpan(){const n=this.activeSpan;n==null||n.cancel();const r=this.getOrCreateStats();return r&&n&&r.resetPageRenderSpan(),r&&this.authState==="in_progress"&&r.startTimer(j.AUTH),this.activeSpan=new Vl(r,this.visible),this.activeSpan}clear(){var n;(n=this.activeSpan)==null||n.cancel(),this.activeSpan=null,this.stats=null,this.authState="idle"}}class Kl extends rt{constructor(){super(...arguments);b(this,"phaseReached","auth");b(this,"historyLoadResult","pending")}setHistoryLoadResult(n){return this.historyLoadResult=n,this}setPhaseReached(n){return this.phaseReached=n,this}getMetricKey(){return xl}buildPayload(){const n=this.getTimer(j.TIMEOUT).duration;return n===null?null:this.createPayload(n,{extra:{outcome:"timeout",phase_reached:this.phaseReached,history_load_result:this.historyLoadResult}})}}class Yl extends kt{start(t){const n=this.getKey(t==null?void 0:t.channelUrl);this.clearKey(n);const r={stats:new Kl().setCommitCallback(this.commitCallback).startTimer(j.TIMEOUT),measure:{channelUrl:t==null?void 0:t.channelUrl,historyLoadResult:"pending",inputEnabled:!1,timer:null}};(t==null?void 0:t.conversationId)!==void 0&&r.stats.setConversationId(t.conversationId),r.measure.timer=setTimeout(()=>this.commitTimeout(n),1e4),this.records.set(n,r)}markChannelJoined(t,n){const r=this.getRecord(n);r&&(r.stats.setPhaseReached("channel_join"),t!==void 0&&r.stats.setConversationId(t))}markHistoryLoaded(t,n){const r=this.getRecord(n);r&&(r.measure.historyLoadResult=t,r.stats.setHistoryLoadResult(t).setPhaseReached("history_load"),this.cancelIfReady(n))}markInputReady(t){const n=this.getRecord(t);n&&(n.measure.inputEnabled=!0,n.stats.setPhaseReached("input_enable"),this.cancelIfReady(t))}markRendered(t){const n=this.getRecord(t);n&&n.stats.setPhaseReached("render")}clear(){this.records.forEach(t=>{t.measure.timer!==null&&clearTimeout(t.measure.timer)}),this.records.clear()}clearChannel(t){t!==void 0&&this.clearKey(this.getKey(t))}clearKey(t){const n=this.records.get(t);n&&(n.measure.timer!==null&&clearTimeout(n.measure.timer),this.records.delete(t))}cancelIfReady(t){const n=this.getRecord(t);!n||!n.measure.inputEnabled||n.measure.historyLoadResult==="pending"||this.clearKey(this.getKey(n.measure.channelUrl))}commitTimeout(t){const n=this.records.get(t);n&&(n.measure.timer=null,this.records.delete(t),n.stats.stopTimer(j.TIMEOUT).commit())}getRecord(t){return t!==void 0?this.records.get(this.getKey(t)):this.records.size===1?this.records.values().next().value:this.records.get(this.getKey())}getKey(t){return t??"__default__"}}class Wl extends rt{constructor(){super(...arguments);b(this,"requestId");b(this,"messageType");b(this,"stuckReason")}setRequestId(n){return this.requestId=n,this}setMessageType(n){return this.messageType=n,this}setStuckReason(n){return this.stuckReason=n,this}getMetricKey(){return wl}buildPayload(){return this.requestId===void 0||this.messageType===void 0||this.stuckReason===void 0?null:this.createPayload(this.stuckReason,{extra:{message_type:this.messageType,request_id:this.requestId}})}}const jl=5e3,vs=1e4;class Xl extends kt{start(t){if(!t.requestId||this.records.has(t.requestId))return;const n=t.messageType!=="text"&&t.tracksUploadProgress===!0,s={stats:new Wl().setRequestId(t.requestId).setMessageType(t.messageType).setStuckReason(n?"upload_no_progress":"pending_too_long").setCommitCallback(this.commitCallback),measure:{channelUrl:t.channelUrl,timer:null,usesUploadProgress:n}},o=n?vs:jl;s.measure.timer=setTimeout(()=>this.detect(t.requestId),o),this.records.set(t.requestId,s)}resolve(t){this.cancel(t.requestId)}disappear(t){this.cancel(t.requestId)}cancel(t){const n=this.records.get(t);n&&(n.measure.timer!==null&&clearTimeout(n.measure.timer),this.records.delete(t))}markUploadProgress(t){const n=this.records.get(t);n&&n.measure.usesUploadProgress&&(n.measure.timer!==null&&clearTimeout(n.measure.timer),n.measure.timer=setTimeout(()=>this.detect(t),vs))}clear(){this.records.forEach(t=>{t.measure.timer!==null&&clearTimeout(t.measure.timer)}),this.records.clear()}clearChannel(t){t&&this.records.forEach((n,r)=>{n.measure.channelUrl===t&&(n.measure.timer!==null&&clearTimeout(n.measure.timer),this.records.delete(r))})}detect(t){const n=this.records.get(t);n&&(this.records.delete(t),n.stats.commit())}}class Xn extends rt{constructor(){super(...arguments);b(this,"triggerType")}setTriggerType(n){return this.triggerType=n,this}getMetricKey(){return Rl}buildPayload(){const n=this.getTimer(j.TIMEOUT).duration;return n===null||this.triggerType===void 0?null:this.createPayload(n,{extra:{trigger_type:this.triggerType}})}}class Zl extends kt{start(t,n){const r=this.getKey(n);let s=this.records.get(r);s!=null&&s.measure.started||s!=null&&s.measure.inputEnabled||(s||(s=this.createRecord(!1)),s.measure.started=!0,s.stats=new Xn().setTriggerType(t).setCommitCallback(this.commitCallback).startTimer(j.TIMEOUT),s.measure.timer=setTimeout(()=>this.commitTimeout(r),1e4),this.records.set(r,s))}setInputEnabled(t,n){const r=this.getKey(n);let s=this.records.get(r);if(!s){if(!t)return;s=this.createRecord(t),this.records.set(r,s);return}s.measure.inputEnabled=t,t?this.cancelRecord(s):s.measure.started||this.records.delete(r)}cancelPending(t){const n=this.getKey(t),r=this.records.get(n);r&&(this.cancelRecord(r),r.measure.inputEnabled||this.records.delete(n))}clear(){this.records.forEach(t=>{t.measure.timer!==null&&clearTimeout(t.measure.timer)}),this.records.clear()}clearChannel(t){t!==void 0&&this.clearKey(this.getKey(t))}clearKey(t){const n=this.records.get(t);n&&(n.measure.timer!==null&&clearTimeout(n.measure.timer),this.records.delete(t))}commitTimeout(t){const n=this.records.get(t);if(!(!n||!n.measure.started)){if(n.measure.inputEnabled){this.cancelRecord(n);return}n.stats.stopTimer(j.TIMEOUT),this.records.delete(t),n.stats.commit()}}cancelRecord(t){t.measure.timer!==null&&clearTimeout(t.measure.timer),t.measure.timer=null,t.measure.started=!1,t.stats=new Xn().setCommitCallback(this.commitCallback)}createRecord(t){return{stats:new Xn().setCommitCallback(this.commitCallback),measure:{inputEnabled:t,started:!1,timer:null}}}getKey(t){return t??"__default__"}}class Jl extends rt{constructor(){super(...arguments);b(this,"messageId");b(this,"contentKind");b(this,"errorDomain")}setMessageId(n){return this.messageId=n,this}setContentKind(n){return this.contentKind=n,this}setErrorDomain(n){return this.errorDomain=n,this}getMetricKey(){return Dl}buildPayload(){return this.messageId===void 0||this.contentKind===void 0||this.errorDomain===void 0?null:this.createPayload(this.errorDomain,{extra:{content_kind:this.contentKind,message_id:String(this.messageId)}})}}const Ql=500;class eu extends Ln{constructor(){super(...arguments);b(this,"measure",{committed:new Set})}commit(n){const r=`${n.messageId}:${n.contentKind}:${n.errorDomain}`;if(this.measure.committed.has(r))return;On(this.measure.committed,Ql),this.measure.committed.add(r),new Jl().setMessageId(n.messageId).setContentKind(n.contentKind).setErrorDomain(n.errorDomain).setError(n.error?{code:n.error.code,message:n.errorDomain}:void 0).setCommitCallback(this.commitCallback).commit()}clear(){this.measure.committed.clear()}}class tu extends rt{constructor(){super(...arguments);b(this,"durationMs");b(this,"messageId");b(this,"stallKind")}setMessageId(n){return this.messageId=n,this}setStall(n){return this.durationMs=n.durationMs,this.stallKind=n.stallKind,this}getMetricKey(){return Ol}buildPayload(){return this.durationMs===void 0||this.messageId===void 0||this.stallKind===void 0?null:this.createPayload(this.durationMs,{extra:{message_id:String(this.messageId),stall_kind:this.stallKind}})}}const Ss=1e4,vt=5e3,nu=500;class ru extends kt{constructor(){super(...arguments);b(this,"emittedMessageChannels",new Map)}markRawProgress(n){if(!n.aiResponse.isStreaming){this.completeDelivery(n.messageId,n.textLength);return}if(this.emittedMessageChannels.has(n.messageId))return;const r=this.getOrCreate(n.messageId,n.channelUrl),s=r.measure;this.markRawProgressForRecord(r,n.textLength,performance.now())?(s.deliveryTimer!==null&&clearTimeout(s.deliveryTimer),s.deliveryTimer=null,this.scheduleDeliveryStallCheck(n.messageId,r)):this.scheduleDeliveryStallCheck(n.messageId,r),this.isRenderPending(r)&&s.renderTimer===null&&(s.lastRenderAt=performance.now(),this.scheduleRenderStallCheck(n.messageId,r,vt))}markRenderedProgress(n){const r=this.records.get(n.messageId);if(!r)return;const s=r.measure;if(this.markRenderedProgressForRecord(r,n.displayedLength,performance.now())){if(!this.isRenderPending(r)){if(s.deliveryTimer===null){this.clearRecord(n.messageId,r);return}s.renderTimer!==null&&clearTimeout(s.renderTimer),s.renderTimer=null;return}this.scheduleRenderStallCheck(n.messageId,r,vt)}}hasPendingStream(n){return this.records.has(n)}complete(n){const r=this.records.get(n);r&&this.clearRecord(n,r)}completeDelivery(n,r){const s=this.records.get(n);if(!s)return;const o=s.measure;if(r>o.lastRawLength&&(o.lastRawLength=r,o.lastRawAt=performance.now()),o.deliveryTimer!==null&&clearTimeout(o.deliveryTimer),o.deliveryTimer=null,!this.isRenderPending(s)){this.clearRecord(n,s);return}o.renderTimer===null&&(o.lastRenderAt=performance.now(),this.scheduleRenderStallCheck(n,s,vt))}clearMessage(n){const r=this.records.get(n);r&&this.clearRecord(n,r),this.emittedMessageChannels.delete(n)}clear(){this.records.forEach(n=>{n.measure.deliveryTimer!==null&&clearTimeout(n.measure.deliveryTimer),n.measure.renderTimer!==null&&clearTimeout(n.measure.renderTimer)}),this.records.clear(),this.emittedMessageChannels.clear()}clearChannel(n){n&&(this.records.forEach((r,s)=>{r.measure.channelUrl!==n&&r.measure.channelUrl!==void 0||this.clearRecord(s,r)}),this.emittedMessageChannels.forEach((r,s)=>{(r===n||r===void 0)&&this.emittedMessageChannels.delete(s)}))}detectDelivery(n){const r=this.records.get(n);if(!r)return;const s=r.measure;s.deliveryTimer=null,s.renderTimer!==null&&clearTimeout(s.renderTimer),s.renderTimer=null,this.emit(n,r,"delivery")}detectRender(n){const r=this.records.get(n);if(!r)return;const s=r.measure;if(s.renderTimer=null,!this.isRenderPending(r))return;const o=performance.now()-s.lastRenderAt;if(o<vt){this.scheduleRenderStallCheck(n,r,vt-o);return}const i=performance.now()-s.lastRawAt;if(i>=vt&&s.deliveryTimer!==null){const c=Ss-i;if(c>0){this.scheduleRenderStallCheck(n,r,c);return}}this.emit(n,r,"render")}scheduleRenderStallCheck(n,r,s){r.measure.renderTimer===null&&(r.measure.renderTimer=setTimeout(()=>this.detectRender(n),s))}scheduleDeliveryStallCheck(n,r){r.measure.deliveryTimer===null&&(r.measure.deliveryTimer=setTimeout(()=>this.detectDelivery(n),Ss))}emit(n,r,s){if(this.emittedMessageChannels.has(n))return;const o=performance.now(),i=s==="delivery"?r.measure.lastRawAt:r.measure.lastRenderAt;r.stats.setStall({stallKind:s,durationMs:o-i}).commit(),this.rememberEmitted(n,r.measure.channelUrl),this.clearRecord(n,r)}getOrCreate(n,r){const s=this.records.get(n);if(s)return s;const o=performance.now(),i={stats:new tu().setMessageId(n).setCommitCallback(this.commitCallback),measure:{channelUrl:r,deliveryTimer:null,lastRawAt:o,lastRawLength:0,lastRenderAt:o,lastRenderedLength:0,renderTimer:null}};return this.records.set(n,i),i}rememberEmitted(n,r){this.emittedMessageChannels.has(n)||On(this.emittedMessageChannels,nu),this.emittedMessageChannels.set(n,r)}clearRecord(n,r){r.measure.deliveryTimer!==null&&clearTimeout(r.measure.deliveryTimer),r.measure.renderTimer!==null&&clearTimeout(r.measure.renderTimer),this.records.delete(n)}isRenderPending(n){return n.measure.lastRenderedLength<n.measure.lastRawLength}markRawProgressForRecord(n,r,s){return r<=n.measure.lastRawLength?!1:(n.measure.lastRawLength=r,n.measure.lastRawAt=s,!0)}markRenderedProgressForRecord(n,r,s){return r<=n.measure.lastRenderedLength?!1:(n.measure.lastRenderedLength=r,n.measure.lastRenderAt=s,!0)}}class su extends rt{constructor(){super(...arguments);b(this,"beforeTpstAbsentMs");b(this,"afterTpenAbsentMs")}setBeforeTpstAbsentMs(n){return this.beforeTpstAbsentMs=n,this}setAfterTpenAbsentMs(n){return this.afterTpenAbsentMs=n,this}getMetricKey(){return Nl}buildPayload(){return this.beforeTpstAbsentMs===void 0&&this.afterTpenAbsentMs===void 0?null:this.createPayload((this.beforeTpstAbsentMs??0)+(this.afterTpenAbsentMs??0),{extra:{[j.BEFORE_TPST_ABSENT]:this.beforeTpstAbsentMs,[j.AFTER_TPEN_ABSENT]:this.afterTpenAbsentMs}})}}const ys=3e3,ou=3e4;class iu extends kt{constructor(){super(...arguments);b(this,"pendingAIResponseStartsByUserMessageId",new Map)}startTurn(n){this.cancelTurn(n.requestId);const r={stats:new su().setCommitCallback(this.commitCallback),measure:{afterTpenStartedAt:null,beforeTpstStartedAt:performance.now(),channelUrl:n.channelUrl,requestId:n.requestId,timer:null}};r.measure.timer=setTimeout(()=>this.commitTimeout(r.measure.requestId),ou),this.records.set(n.requestId,r)}markUserMessageAck(n){const r=this.records.get(n.requestId);if(!r)return;r.measure.userMessageId=n.messageId;const s=this.pendingAIResponseStartsByUserMessageId.get(n.messageId);s&&(this.pendingAIResponseStartsByUserMessageId.delete(n.messageId),this.applyAIResponseStarted({channelUrl:s.channelUrl,matchesUserMessage:!0,userMessageId:n.messageId},s.startedAt))}replaceTurnRequestId(n,r){if(n===r)return;const s=this.records.get(n);s&&(this.records.delete(n),s.measure.requestId=r,this.records.set(r,s))}cancelTurn(n){this.cleanupTurn(n)}markTypingStarted(n){const r=performance.now();this.records.forEach(s=>{gt(s.measure.channelUrl,n)&&(this.recordAfterTpen(s,r),this.recordBeforeTpst(s,r))})}markTypingEnded(n){const r=performance.now();this.records.forEach(s=>{gt(s.measure.channelUrl,n)&&(this.recordBeforeTpst(s,r),s.measure.afterTpenStartedAt=r)})}markAIResponseStarted(n={}){const r=n.channelUrl,s=n.userMessageId,o=s!==void 0,i=performance.now();this.applyAIResponseStarted({channelUrl:r,matchesUserMessage:o,userMessageId:s},i)||!o||s===void 0||!Er(this.records.values(),r)||this.pendingAIResponseStartsByUserMessageId.has(s)||(On(this.pendingAIResponseStartsByUserMessageId,100),this.pendingAIResponseStartsByUserMessageId.set(s,{channelUrl:r,startedAt:i}))}applyAIResponseStarted(n,r){if(!n.matchesUserMessage){const o=this.findSingleTurn(n.channelUrl);return o?(this.completeTurn(o.requestId,o.record,r),!0):!1}let s=!1;return this.records.forEach(o=>{gt(o.measure.channelUrl,n.channelUrl)&&(n.matchesUserMessage&&o.measure.userMessageId!==n.userMessageId||(s=!0,this.completeTurn(o.measure.requestId,o,r)))}),s}findSingleTurn(n){let r,s=0;return this.records.forEach(o=>{gt(o.measure.channelUrl,n)&&(s+=1,!(s>1)&&(r={requestId:o.measure.requestId,record:o}))}),s===1?r:void 0}completeTurn(n,r,s){this.recordBeforeTpst(r,s),this.recordAfterTpen(r,s),this.commitIfAbsent(n,r)}clear(){this.records.forEach(n=>{n.measure.timer!==null&&clearTimeout(n.measure.timer)}),this.records.clear(),this.pendingAIResponseStartsByUserMessageId.clear()}clearChannel(n){n&&(this.records.forEach(r=>{r.measure.channelUrl===n&&this.cleanupTurn(r.measure.requestId)}),this.pendingAIResponseStartsByUserMessageId.forEach((r,s)=>{r.channelUrl===n&&this.pendingAIResponseStartsByUserMessageId.delete(s)}))}commitTimeout(n){const r=this.records.get(n);if(!r)return;const s=performance.now();this.recordBeforeTpst(r,s),this.recordAfterTpen(r,s),this.commitIfAbsent(n,r)}commitIfAbsent(n,r){r.stats.commit(),this.cleanupTurn(n)}cleanupTurn(n){const r=this.records.get(n);r&&(r.measure.timer!==null&&clearTimeout(r.measure.timer),this.records.delete(n))}recordBeforeTpst(n,r){if(n.measure.beforeTpstStartedAt===null)return;const s=r-n.measure.beforeTpstStartedAt;s>=ys&&n.stats.setBeforeTpstAbsentMs(s),n.measure.beforeTpstStartedAt=null}recordAfterTpen(n,r){if(n.measure.afterTpenStartedAt===null)return;const s=r-n.measure.afterTpenStartedAt;s>=ys&&n.stats.setAfterTpenAbsentMs(s),n.measure.afterTpenStartedAt=null}}class au extends rt{constructor(){super(...arguments);b(this,"ackToFirstChunkMs");b(this,"firstChunkToRenderMs");b(this,"isStreaming");b(this,"sendToAckMs");b(this,"totalDurationMs")}setDurations(n){return this.ackToFirstChunkMs=n.ackToFirstChunkMs,this.firstChunkToRenderMs=n.firstChunkToRenderMs,this.isStreaming=n.isStreaming,this.sendToAckMs=n.sendToAckMs,this.totalDurationMs=n.totalDurationMs,this}getMetricKey(){return Ll}buildPayload(){return this.ackToFirstChunkMs===void 0||this.firstChunkToRenderMs===void 0||this.isStreaming===void 0||this.sendToAckMs===void 0||this.totalDurationMs===void 0?null:this.createPayload(this.totalDurationMs,{extra:{is_streaming:this.isStreaming,[j.ACK_TO_FIRST_CHUNK]:this.ackToFirstChunkMs,[j.FIRST_CHUNK_TO_RENDER]:this.firstChunkToRenderMs,[j.SEND_TO_ACK]:this.sendToAckMs}})}}const cu=.15,lu=10,uu=e=>e<=0?!1:e>=1?!0:Math.random()<e;class du extends kt{constructor(n,r){super(n);b(this,"samplingRate");b(this,"pendingAIResponseByUserMessageId",new Map);b(this,"collectedCount",0);this.samplingRate=(r==null?void 0:r.samplingRate)??cu}startTurn(n){if(this.collectedCount>=lu||!uu(this.samplingRate))return;this.collectedCount+=1;const r={stats:new au().setCommitCallback(this.commitCallback),measure:{channelUrl:n.channelUrl,requestId:n.requestId,startedAt:performance.now()}};this.records.set(n.requestId,r)}markUserMessageAck(n){const r=this.records.get(n.requestId);if(!r)return;r.measure.ackAt=performance.now(),r.measure.userMessageId=n.messageId;const s=this.pendingAIResponseByUserMessageId.get(n.messageId);s&&(this.pendingAIResponseByUserMessageId.delete(n.messageId),this.applyAIResponseRaw(r,s))}replaceTurnRequestId(n,r){if(n===r)return;const s=this.records.get(n);s&&(this.records.delete(n),s.measure.requestId=r,this.records.set(r,s))}cancelTurn(n){const r=this.records.get(n);r&&(this.deleteRecord(r),this.collectedCount>0&&(this.collectedCount-=1))}markAIResponseRaw(n){const r=performance.now(),s=n.aiResponse.userMessageId;if(s===void 0&&Er(this.records.values(),n.channelUrl))return;const o=this.findPendingRecord(n.channelUrl,s);if(o){this.applyAIResponseRaw(o,{...n,firstChunkAt:r});return}s===void 0||!Er(this.records.values(),n.channelUrl)||this.bufferAIResponseRaw({messageId:n.messageId,...n.channelUrl!==void 0&&{channelUrl:n.channelUrl},aiResponse:n.aiResponse,firstChunkAt:r},s)}markAIResponseVisible(n){const r=this.findRecordByAIMessageId(n);if(!r)return!1;const s=r.measure;if(s.ackAt===void 0||s.firstChunkAt===void 0||s.userMessageId===void 0)return!1;const o=performance.now();return r.stats.setDurations({ackToFirstChunkMs:s.firstChunkAt-s.ackAt,firstChunkToRenderMs:o-s.firstChunkAt,isStreaming:!!s.isStreaming,sendToAckMs:s.ackAt-s.startedAt,totalDurationMs:o-s.startedAt}).commit(),this.deleteRecord(r),!0}hasPendingAIResponse(n){return this.findRecordByAIMessageId(n)!==void 0}clearMessage(n){this.pendingAIResponseByUserMessageId.forEach((s,o)=>{s.messageId===n&&this.pendingAIResponseByUserMessageId.delete(o)});const r=this.findRecordByAIMessageId(n);r&&(this.deleteRecord(r),this.collectedCount>0&&(this.collectedCount-=1))}clearChannel(n){n&&(this.records.forEach(r=>{r.measure.channelUrl===n&&(this.deleteRecord(r),this.collectedCount>0&&(this.collectedCount-=1))}),this.pendingAIResponseByUserMessageId.forEach((r,s)=>{r.channelUrl===n&&this.pendingAIResponseByUserMessageId.delete(s)}))}clear(){this.records.clear(),this.pendingAIResponseByUserMessageId.clear(),this.collectedCount=0}findRecordByAIMessageId(n){for(const r of this.records.values())if(r.measure.aiMessageId===n)return r}findPendingRecord(n,r){if(r!==void 0){for(const o of this.records.values())if(!(o.measure.ackAt===void 0||o.measure.firstChunkAt!==void 0)&>(o.measure.channelUrl,n)&&o.measure.userMessageId===r)return o;return}let s;for(const o of this.records.values())if(!(o.measure.ackAt===void 0||o.measure.firstChunkAt!==void 0)&>(o.measure.channelUrl,n)){if(s)return;s=o}return s}applyAIResponseRaw(n,r){n.measure.firstChunkAt===void 0&&(n.measure.firstChunkAt=n.measure.ackAt===void 0?r.firstChunkAt:Math.max(r.firstChunkAt,n.measure.ackAt),n.measure.aiMessageId=r.messageId,n.measure.channelUrl=n.measure.channelUrl??r.channelUrl,n.measure.isStreaming=r.aiResponse.isStreaming)}bufferAIResponseRaw(n,r){this.pendingAIResponseByUserMessageId.has(r)||(On(this.pendingAIResponseByUserMessageId,100),this.pendingAIResponseByUserMessageId.set(r,n))}deleteRecord(n){this.records.delete(n.measure.requestId),n.measure.userMessageId!==void 0&&this.pendingAIResponseByUserMessageId.delete(n.measure.userMessageId)}}function mu(){let e=null,t=0;const n=(r,s)=>{if((e==null?void 0:e.key)===r)return e.promise;const o=++t,c=(e?e.promise.catch(()=>{}).then(()=>s()):s()).finally(()=>{(e==null?void 0:e.id)===o&&(e=null)});return e={key:r,id:o,promise:c},c};return n.isPending=()=>e!==null,n}const As={isTalkToAgentViewEnabled:!0,scrollMode:"auto",newMessageIndicatorEnabled:!0,senderAvatarEnabled:!0},Br={conversation:{...As,messageAlertSoundEnabled:!1,list:{...As,deferredMarkdownElements:[]},header:{avatarEnabled:!0},input:{camera:{photoEnabled:!0},gallery:{photoEnabled:!0},fileEnabled:!0},fileViewer:{downloadEnabled:!0}},launcher:{unreadBadgeEnabled:!1}},Ts=e=>e?{conversation:gu(e.conversation),launcher:hu(e.launcher)}:Br,hu=e=>yt(Br.launcher,e),fu=e=>{if(e.deferredMarkdownElements)return[...e.deferredMarkdownElements];const t=[];return e.markdownImageRenderMode==="complete-only"&&t.push("image"),e.markdownLinkRenderMode==="complete-only"&&t.push("link"),t},gu=e=>{const t=Br.conversation;if(!e)return t;const{list:n={},header:r={},input:s,fileViewer:o={},messageAlertSoundEnabled:i=t.messageAlertSoundEnabled,...c}=e,{camera:u={},gallery:d={},fileEnabled:m=t.input.fileEnabled}=s??{},h={...yt(t.list,c,n),deferredMarkdownElements:fu(n)};return{...h,messageAlertSoundEnabled:i,list:h,header:yt(t.header,r),input:{camera:yt(t.input.camera,u),gallery:yt(t.input.gallery,d),fileEnabled:m},fileViewer:yt(t.fileViewer,o)}},yt=(e,...t)=>{const n={...e};for(const r of t)r&&Object.assign(n,Ur(r));return n},pu=e=>({userId:e.bot_userid,profileUrl:e.bot_profile_url,nickname:e.bot_nickname,replyToFile:e.reply_to_file,specialNotice:e.special_notice,specialNoticeEnabled:e.is_special_notice_enabled,showHandoffButton:e.show_handoff_button??!0,isMultipleActiveConversationsEnabled:e.is_multiple_active_conversations_enabled??!0,isUserFeedbackEnabled:e.is_user_feedback_enabled??!1,isUserFeedbackCommentOptionEnabled:e.is_user_feedback_comment_option_enabled??!1}),_u=e=>({type:e.image_type||"default_icon",imageUrl:e.image_url}),Cr=e=>({enabled:e.enabled,showIndicator:e.show_indicator,toggleAllowed:e.toggle_allowed,deleteOnOff:e.delete_on_off,consentDialog:e.consent_dialog});class Eu{constructor(){b(this,"_channelHandlerId",null);b(this,"_connectionHandlerId",null);b(this,"_initConversationRequests",new Map);b(this,"_handleActiveChannelChangedThrottled",null);b(this,"_setupChannelHandler",()=>{const t=Date.now();this._channelHandlerId=`aiagent_channel_${t}`,this._connectionHandlerId=`aiagent_connection_${t}`,this._handleActiveChannelChangedThrottled=ri(s=>{var o,i;(i=this._session)==null||i._updateActiveChannel({url:s.url,status:De(s)?"closed":"open",conversationStatus:(o=s.conversation)==null?void 0:o.status}),this._logger.debug("AIAgentEventManager: activeChannel updated",s.url)},250,{leading:!0,trailing:!1});const n=new Qe.GroupChannelHandler({onChannelChanged:s=>{var o,i;s.isGroupChannel()&&s.url===((o=this._session)==null?void 0:o.activeChannel.url)&&((i=this._handleActiveChannelChangedThrottled)==null||i.call(this,s))}}),r=new Ce.ConnectionHandler({onReconnectSucceeded:async()=>{await this._syncActiveChannelOnReconnect()}});this._chatClient.chatSDK.groupChannel.addGroupChannelHandler(this._channelHandlerId,n),this._chatClient.chatSDK.addConnectionHandler(this._connectionHandlerId,r),this._logger.debug("AIAgentEventManager: handlers registered",{channelHandlerId:this._channelHandlerId,connectionHandlerId:this._connectionHandlerId})});b(this,"_removeChannelHandler",()=>{this._channelHandlerId&&(this._chatClient.chatSDK.groupChannel.removeGroupChannelHandler(this._channelHandlerId),this._channelHandlerId=null),this._connectionHandlerId&&(this._chatClient.chatSDK.removeConnectionHandler(this._connectionHandlerId),this._connectionHandlerId=null),this._handleActiveChannelChangedThrottled&&(this._handleActiveChannelChangedThrottled.cancel(),this._handleActiveChannelChangedThrottled=null),this._logger.debug("AIAgentEventManager: handlers removed")});b(this,"_syncActiveChannelOnReconnect",async()=>{var n,r,s;const t=(n=this._session)==null?void 0:n.activeChannel.url;if(t)try{const i=await(await this._chatClient.chatSDK.groupChannel.getChannel(t)).refresh();i.url===t&&((s=this._session)==null||s._updateActiveChannel({url:i.url,status:De(i)?"closed":"open",conversationStatus:(r=i.conversation)==null?void 0:r.status}),this._logger.debug("AIAgentEventManager: activeChannel synced on reconnect",i.url))}catch(o){this._logger.error("AIAgentEventManager: failed to sync activeChannel on reconnect",o)}});b(this,"_initConversationIfNeeded",(t,n)=>{if(!t.isAIAgent||t.conversation)return Promise.resolve();const r=this._initConversationRequests.get(t.url);if(r)return r;const s=t.initConversation({aiAgentId:this.aiAgentId,initialUserMessage:n==null?void 0:n.initialUserMessage}).then(()=>{}).catch(o=>{this._logger.warn("AIAgentEventManager: initConversation failed",o)}).finally(()=>{this._initConversationRequests.delete(t.url)});return this._initConversationRequests.set(t.url,s),s});b(this,"onMessengerSettingsUpdated",t=>(this._dispatcher.subscribe(Be.MessengerSettingsUpdated,t),()=>{this._dispatcher.unsubscribe(Be.MessengerSettingsUpdated,t)}));b(this,"onActiveChannelUpdated",t=>(this._dispatcher.subscribe(Be.ActiveChannelUpdated,t),()=>{this._dispatcher.unsubscribe(Be.ActiveChannelUpdated,t)}));b(this,"onAuthTokenRefreshed",t=>(this._dispatcher.subscribe(Be.AuthTokenRefreshed,t),()=>{this._dispatcher.unsubscribe(Be.AuthTokenRefreshed,t)}));b(this,"onNudgeMessageReceived",t=>(this._dispatcher.subscribe(Be.NudgeMessageReceived,t),()=>{this._dispatcher.unsubscribe(Be.NudgeMessageReceived,t)}))}}class Cu{constructor(t){b(this,"_sdkUser");b(this,"_userSession");b(this,"_dispatcher");b(this,"_activeChannel");b(this,"_updateActiveChannel",t=>{this._activeChannel=t,this._dispatcher.send(at.ActiveChannelUpdated({channelUrl:t.url,status:t.status,conversationStatus:t.conversationStatus}))});b(this,"_updateAuthToken",t=>{this._userSession.authToken=t,this._dispatcher.send(at.AuthTokenRefreshed())});this._sdkUser=t.sdkUser,this._userSession=t.userSession,this._dispatcher=t.dispatcher,this._activeChannel=t.activeChannel}get sdkUser(){return this._sdkUser}get userSession(){return this._userSession}get activeChannel(){return this._activeChannel}}const hi=e=>{try{const t=JSON.parse(e);return typeof t=="string"?JSON.stringify(t).slice(1,-1):e.trim()}catch{return JSON.stringify(e).slice(1,-1)}},fi=e=>JSON.parse(e),bu=e=>JSON.parse(e);function vu(e,t){const[n,r]=t.split(",").map(s=>s.trim());return e==="dark"&&r||n}function Su(e){const t={};function n(r,s=""){for(const[o,i]of Object.entries(r)){const c=s?`${s}.${o}`:o;i&&typeof i=="object"&&!Array.isArray(i)?n(i,c):t[c]=i}}return n(e),t}function yu({template:e,variables:t,variableKeyPattern:n,variableValueTransformer:r}){return Object.entries(t).reduce((s,[o,i])=>{if(!r&&!["number","boolean","string"].includes(typeof i))throw new Error(`If transformer is not provided, value(${o}:${i}) must be a {string, number, or boolean}`);const c=r?r(i):String(i),u=n(o);return s.replace(u,hi(c))},e)}async function Au({template:e,variables:t,variableKeyPattern:n,variableValueTransformer:r}){return(await Promise.all(Object.entries(t).map(async([o,i])=>{const c=await r(i);return{regex:n(o),transformedValue:c}}))).reduce((o,{regex:i,transformedValue:c})=>o.replace(i,hi(c)),e)}var Hr=(e=>(e[e.EXTERNAL_AUTH_TOKEN_EXPIRED=1]="EXTERNAL_AUTH_TOKEN_EXPIRED",e))(Hr||{});const gi=e=>typeof e=="object"&&e!==null,Zn=(e,t)=>t in e&&typeof e[t]=="string"&&e[t]!=="",Tu=e=>!gi(e)||!Zn(e,"channel_url")||!Zn(e,"ai_agent_id")||!Zn(e,"cpa_key")?null:{channelUrl:e.channel_url,aiAgentId:e.ai_agent_id,cpaKey:e.cpa_key},Iu={1:Tu};function xu(e){if(!gi(e)||!("cat"in e)||typeof e.cat!="number"||!("data"in e))return null;const t=e.cat,n=Iu[t];if(!n)return null;const r=n(e.data);return r?{category:t,data:r}:null}function Ru(e,t,n,r){const s=bc.default.init({appId:e,modules:[new Qe.GroupChannelModule,new he.AIAgentModule],localCacheEnabled:!0,options:new Ce.SendbirdChatOptions({typingIndicatorInvalidateTime:2e4}),...r,customApiHost:(r==null?void 0:r.customApiHost)??`https://api-${e}.app.delight.ai`,customWebSocketHost:(r==null?void 0:r.customWebSocketHost)??`wss://ws-${e}.app.delight.ai`});return s.addSendbirdExtensions([{version:n,product:Ce.SendbirdProduct.AI_AGENT,platform:t.platform}],{platform:t.deviceOSPlatform,version:t.deviceOSVersion},t.customData)||console.warn("Invalid Sendbird Extensions",t),s}function Mu(e){const t=n=>{throw new Error(`Please initialize chat sdk with ${n}`)};typeof e.groupChannel!="object"&&t("GroupChannelModule"),typeof e.aiAgent!="object"&&t("AIAgentModule")}const wu=[400300,400301,400302,400310],ku=Hr.EXTERNAL_AUTH_TOKEN_EXPIRED.toString(),Lu=e=>`${ku}:${e}`;class Gr{constructor(t,n,r,s,o){b(this,"chatSDK");b(this,"_aiAgentId");b(this,"_externalAuthTokenExpiredEventHandlerKey");b(this,"_logger");b(this,"_cache");b(this,"_statsTrackers");b(this,"_sessionHandler");b(this,"_aiEventHandlerRegistered",!1);b(this,"connect",async(t,n,r,s,o)=>{if(this._logger.debug("ChatClient.connect: start",t.userId),n){this._sessionHandler=n;const i=new Ce.SessionHandler({...n,onSessionTokenRequired:this._interceptTokenRefresh(n.onSessionTokenRequired,r,s)});this.chatSDK.setSessionHandler(i)}this._registerAIEventHandler();try{await this.chatSDK.connect(t.userId,t.authToken);const[,i]=await Promise.allSettled([this._syncTemplatesIfNeeded(),o?this.submitCPAAuthorizationCodes(o):Promise.resolve()]);return o&&(i.status==="fulfilled"?this._logger.debug("ChatClient.connect: CPA authorization codes submitted",i.value):this._logger.error("ChatClient.connect: CPA authorization code submission failed",i.reason)),this._logger.debug("ChatClient.connect: end",this.chatSDK.currentUser),this.chatSDK.currentUser}catch(i){const c=i;if(this.chatSDK.isCacheEnabled){if(this._isCacheRestrictedError(c))this._logger.warn("ChatClient.connect","offline connect restricted",c.message,c.code),this._logger.warn("ChatClient.connect","clear cached-data"),await this.chatSDK.clearCachedData().catch(u=>this._logger.warn("ChatClient.connect","clear cached-data failure",u));else if(this.chatSDK.currentUser)return this._logger.debug("ChatClient.connect: end (offline)",this.chatSDK.currentUser),this.chatSDK.currentUser}throw this._logger.warn("ChatClient.connect","connect failure",c.message,c.code),this.dispose(),c}});b(this,"_registerAIEventHandler",()=>{this._aiEventHandlerRegistered||(this._aiEventHandlerRegistered=!0,this.chatSDK.aiAgent.addEventHandler(this._externalAuthTokenExpiredEventHandlerKey,this._handleAIEvent))});b(this,"_handleAIEvent",t=>{var o;this._logger.debug("ChatClient.connect: EXTERNAL_AUTH_TOKEN_EXPIRED event received",t);const n=xu(t),r=typeof t.cat=="number"?t.cat:void 0;if(r!==void 0&&r!==Hr.EXTERNAL_AUTH_TOKEN_EXPIRED)return;if(!n){this._statsTrackers.aievAuthExpiredUnhandled.onPayloadParseFailed({aiAgentId:this._aiAgentId});return}if(n.data.aiAgentId!==this._aiAgentId){this._logger.debug("ChatClient.connect: ignore EXTERNAL_AUTH_TOKEN_EXPIRED for another agent",n.data);return}const s=(o=this._sessionHandler)==null?void 0:o.onExternalAuthTokenExpired;if(!s){this._statsTrackers.aievAuthExpiredUnhandled.onCallbackNotFound(n.data);return}this._logger.debug("ChatClient.connect: calling onExternalAuthTokenExpired handler",n.data),s(n.data)});b(this,"dispose",()=>{this._aiEventHandlerRegistered&&(this.chatSDK.aiAgent.removeEventHandler(this._externalAuthTokenExpiredEventHandlerKey),this._aiEventHandlerRegistered=!1),this._sessionHandler=void 0});b(this,"disconnect",async()=>{this._logger.debug("ChatClient.disconnect: start"),this.dispose(),await this.chatSDK.disconnect(),this._cache.template.clear(),this._logger.debug("ChatClient.disconnect: end")});b(this,"getChannel",async t=>this.chatSDK.groupChannel.getChannel(t));b(this,"patchContext",async(t,n,r)=>this.chatSDK.aiAgent.patchContext(t,n,r));b(this,"updateContext",async(t,n,r)=>this.chatSDK.aiAgent.updateContext(t,n,r));b(this,"requestNudgeMessage",async t=>this.chatSDK.aiAgent.requestNudgeMessage(t));b(this,"submitCPAAuthorizationCodes",async({aiAgentId:t,authCodes:n})=>this.chatSDK.aiAgent.submitCustomerProvidedAuthCodes({aiAgentId:t,authorizationCodes:n}));b(this,"requestMessengerSettings",async t=>{var s;if(t.userId===""){const o=new Error("userId cannot be empty string for messenger settings request");throw this._logger.error("ChatClient.requestMessengerSettings: invalid userId",o),o}const n={...t,shouldSendFirstMessage:!1};this._logger.debug("ChatClient.requestMessengerSettings: requesting",n);const r=await this.chatSDK.aiAgent.requestMessengerSettings(n);return this._logger.debug("ChatClient.requestMessengerSettings: received",(s=r.active_channel)==null?void 0:s.channel_url),r});b(this,"setUserMemoryState",async t=>{this._logger.debug("ChatClient.setUserMemoryState: requesting",t);const n=await this.chatSDK.aiAgent.setUserMemoryState(t);return this._logger.debug("ChatClient.setUserMemoryState: received",n.enabled),n});b(this,"clearUserMemories",async(t={})=>{this._logger.debug("ChatClient.clearUserMemories: requesting",t),await this.chatSDK.aiAgent.clearUserMemories(t),this._logger.debug("ChatClient.clearUserMemories: completed")});b(this,"_interceptTokenRefresh",(t,n,r)=>{if(t)return async(s,o)=>{new Promise((i,c)=>t==null?void 0:t(i,c)).then(i=>{i?n==null||n(i):r==null||r(),s(i)}).catch(i=>{r==null||r(),o(i)})}});b(this,"_isCacheRestrictedError",t=>wu.some(n=>t.code===n));b(this,"_syncTemplatesIfNeeded",async()=>{var r,s;const t=(s=(r=this.chatSDK.appInfo)==null?void 0:r.aiAgentInfo)==null?void 0:s.templateListToken;if(!t)return;const n=this._cache.template.getCachedToken();if(!(n&&n===t)){this._logger.debug("ChatClient._syncTemplatesIfNeeded: syncing templates");try{const{templates:o,token:i}=await this.chatSDK.aiAgent.getMessageTemplates({limit:20});for(const{template:c}of o){const{key:u}=fi(c);this._cache.template.set(u,c)}this._cache.template.setCachedToken(i),this._logger.debug("ChatClient._syncTemplatesIfNeeded: sync completed")}catch(o){this._logger.error("ChatClient._syncTemplatesIfNeeded: error",o)}}});this.chatSDK=t,this._aiAgentId=n,this._externalAuthTokenExpiredEventHandlerKey=Lu(n),this._logger=r,this._cache=s,this._statsTrackers=o}static init(t){let n;return t.chatSDK?(Mu(t.chatSDK),n=t.chatSDK):n=Ru(t.appId,t.extensions,t.messengerVersion,t.chatParams),new Gr(n,t.aiAgentId,t.logger,t.cache,t.statsTrackers)}}const Ou=e=>t=>{if(!e||e.getState()==="foregrounded"){t();return}const n=e.subscribe(r=>{r==="foregrounded"&&(n(),t())});return n},Nu=e=>()=>{let t=e.getState()==="backgrounded";const n=e.subscribe(r=>{r==="backgrounded"&&(t=!0)});return()=>(n(),t)},an=new Map,pi={set:(e,t)=>{an.set(e,t)},get:e=>{if(an.size===0)throw new Error("AIAgent platform not configured. Ensure you are using the correct package (@sendbird/ai-agent-messenger-react or @sendbird/ai-agent-messenger-react-native).");if(e){const n=an.get(e);if(!n)throw new Error(`AIAgent platform "${e}" is not configured.`);return{platform:e,...n}}const t=an.entries().next().value;return{platform:t[0],...t[1]}}};class Is extends Error{constructor(n,r){const s=(r==null?void 0:r.detail)??"";super(s||`Desk API error (${n})`);b(this,"status");b(this,"code");b(this,"detail");this.name="DeskApiError",this.status=n,this.code=(r==null?void 0:r.code)??"",this.detail=s}}var zr=(e=>(e.INITIALIZED="INITIALIZED",e.PROACTIVE="PROACTIVE",e.PENDING="PENDING",e.ACTIVE="ACTIVE",e.CLOSED="CLOSED",e.WORK_IN_PROGRESS="WORK_IN_PROGRESS",e.IDLE="IDLE",e))(zr||{}),Vr=(e=>(e.URGENT="URGENT",e.HIGH="HIGH",e.MEDIUM="MEDIUM",e.LOW="LOW",e))(Vr||{}),_i=(e=>(e.ERR_CREDENTIALS_NOT_PROVIDED="desk401100",e.ERR_NON_AUTHORIZED="desk401103",e.ERR_SESSION_KEY_EXPIRED="desk401106",e.ERR_SESSION_TOKEN_REVOKED="desk401107",e.ERR_USER_DEACTIVATED="desk401108",e.ERR_USER_NOT_EXIST="desk401109",e))(_i||{});const Du=e=>e==="desk401103"||e==="desk401106"||e==="desk401107"||e==="desk401108"||e==="desk401109";class $u{constructor(t){b(this,"_appId");b(this,"_apiHost");b(this,"_logger");b(this,"_credential",null);b(this,"_authRefreshPromise",null);b(this,"_onDeskTokenRefreshRequired",async()=>!1);b(this,"request",async(t,n)=>{const r=n.authRequired??!0,s=`${this._apiHost}${t}`;r&&this._authRefreshPromise&&(this._logger.debug("DeskApiClient: waiting for in-flight recovery..."),await this._authRefreshPromise);const o=await this._fetch(s,n);return r&&o.status===401?this._handleUnauthorized(o,s,n):this._toResult(o)});b(this,"setCredential",(t,n=async()=>!1)=>{this._authRefreshPromise=null,this._onDeskTokenRefreshRequired=n,this._credential=t});b(this,"clearCredential",()=>{this._authRefreshPromise=null,this._credential=null,this._onDeskTokenRefreshRequired=async()=>!1});b(this,"_handleUnauthorized",async(t,n,r)=>{const s=await this._parseErrorCode(t);if(!Du(s))return this._toResult(t);if(!await this._refresh(s)||this._credential===null)return this._toResult(t);const i=await this._fetch(n,r);return this._toResult(i)});b(this,"_refresh",async t=>{if(this._authRefreshPromise)return this._logger.debug("DeskApiClient: refresh already in progress, joining..."),this._authRefreshPromise;try{return this._authRefreshPromise=this._onDeskTokenRefreshRequired({reason:t}).catch(n=>(this._logger.error("DeskApiClient: delegated recovery failed",n),!1)),await this._authRefreshPromise}finally{this._authRefreshPromise=null}});b(this,"_fetch",(t,n)=>fetch(`${t}?${this._buildParams(n.params)}`,{method:n.method,headers:this._buildHeaders(n.authRequired??!0,n.headers),...n.body?{body:JSON.stringify(this._buildBody(n.body))}:{}}));b(this,"_buildParams",t=>new URLSearchParams({sendbirdAppId:this._appId,...t}));b(this,"_buildBody",t=>({sendbirdAppId:this._appId,...t}));b(this,"_buildHeaders",(t,n)=>({"content-type":"application/json",...t&&this._credential?{sendbirdDeskToken:this._credential.deskToken}:{},...n}));b(this,"_toResult",async t=>{if(!t.ok){const r=await t.json().catch(()=>({}));throw new Is(t.status,r)}const n=await t.text();if(n)try{return JSON.parse(n)}catch{throw new Is(t.status,{})}});b(this,"_parseErrorCode",async t=>{const n=await t.clone().json().catch(()=>({}));return n==null?void 0:n.code});this._appId=t.appId,this._apiHost=t.customApiHost??`https://desk-api-${t.appId}.app.delight.ai/sapi`,this._logger=t.logger}get credential(){return this._credential}}class Sn{constructor(t,n){b(this,"id");b(this,"title");b(this,"status");b(this,"agent");b(this,"priority");b(this,"group");b(this,"firstResponseTime");b(this,"issuedAt");b(this,"customFields");b(this,"_client");b(this,"refresh",async()=>this._client.getTicket(this.id));this.id=t.id,this.title=t.title,this.status=t.status,this.agent=t.agent,this.priority=t.priority,this.group=t.group,this.firstResponseTime=t.firstResponseTime,this.issuedAt=t.issuedAt,this.customFields=t.customFields,this._client=n}static _fromResponse(t,n){var r;return new Sn({id:t.id,title:t.channelName??null,status:t.status2??zr.INITIALIZED,agent:(()=>{var o;const s=(o=t.recentAssignment)==null?void 0:o.agent;return s?{userId:s.sendbirdId??"",name:s.displayName??"",profileUrl:s.photoThumbnailUrl??""}:null})(),priority:t.priority??Vr.MEDIUM,group:t.group??0,firstResponseTime:t.firstResponseTime??-1,issuedAt:t.issuedAt??null,customFields:Object.fromEntries(((r=t.customFields)==null?void 0:r.map(s=>[s.key,s.value]))??[])},n)}}class qr{constructor(t){b(this,"_logger");b(this,"_apiClient");b(this,"_onDeskTokenRefreshRequired");b(this,"refreshDeskAuthToken",async t=>this._apiClient.credential?this.authenticate({userId:this._apiClient.credential.userId,accessToken:t,onDeskTokenRefreshRequired:this._onDeskTokenRefreshRequired}):!1);b(this,"authenticate",async t=>{this._logger.debug("DeskClient.authenticate: start",t.userId);try{const{token:n}=await this._apiClient.request("/customers/auth/",{method:"POST",headers:{sendbirdAccessToken:t.accessToken},body:{sendbirdId:t.userId},authRequired:!1});return t.onDeskTokenRefreshRequired!==void 0&&(this._onDeskTokenRefreshRequired=t.onDeskTokenRefreshRequired),this._apiClient.setCredential({userId:t.userId,deskToken:n,chatToken:t.accessToken},this._onDeskTokenRefreshRequired),this._logger.debug("DeskClient.authenticate: end"),!0}catch(n){return this._apiClient.clearCredential(),this._logger.debug("DeskClient.authenticate: failed",n),!1}});b(this,"deauthenticate",()=>{this._apiClient.clearCredential(),this._onDeskTokenRefreshRequired=void 0,this._logger.debug("DeskClient.deauthenticate: token cleared")});b(this,"setCustomerLanguage",async t=>{this._assertAuthenticated(this._apiClient),this._logger.debug("DeskClient.setCustomerLanguage: start",t),await this._apiClient.request("/customers/language/",{method:"PATCH",body:{language:t}}),this._logger.debug("DeskClient.setCustomerLanguage: end")});b(this,"getTicket",async t=>{this._assertAuthenticated(this._apiClient);const n=await this._apiClient.request(`/tickets/${encodeURIComponent(t)}/`,{method:"GET"});return Sn._fromResponse(n,this)});b(this,"createTicket",async t=>{this._assertAuthenticated(this._apiClient);const n=await this._apiClient.request("/tickets/",{method:"POST",body:Ur({channelName:t.title,channelType:"SENDBIRD_JAVASCRIPT",customFields:t.customFields?JSON.stringify(t.customFields):void 0,info:JSON.stringify({ticket:{subject:t.title,requester:{name:t.name,email:this._apiClient.credential.userId}}}),priority:t.priority,groupKey:t.groupKey})});return Sn._fromResponse(n,this)});this._logger=t.logger,this._apiClient=new $u(t)}static init(t){return new qr(t)}_assertAuthenticated(t){if(t.credential==null)throw new Error("DeskClient is not authenticated")}}class Kr{constructor(){b(this,"authenticate",async t=>!1);b(this,"deauthenticate",()=>{});b(this,"refreshDeskAuthToken",async()=>!1);b(this,"setCustomerLanguage",async()=>{});b(this,"getTicket",async()=>{throw new Error("DeskClient is disabled via __SBA_USE_DESK_CLIENT__")})}static init(){return new Kr}}function Pu(e){return{get:t=>e.getString(t)??null,set:(t,n)=>{e.set(t,n)},delete:t=>{e.delete?e.delete(t):e.remove&&e.remove(t)},getKeys:t=>e.getAllKeys().filter(n=>n.startsWith(t))}}const Fu=1440*60*1e3,Uu=typeof __SBA_USE_DESK_CLIENT__>"u"||__SBA_USE_DESK_CLIENT__;function Ye(e){if(!e)throw new Error("Not authenticated. Call authenticate() first.")}function Bu(e,t){return Object.entries(t).every(([n,r])=>e[n]===r)}const Hu=e=>{const t={conversationInitialRender:new Gl(e),conversationNotInteractiveTimeout:new Yl(e),recoveryNotInteractiveTimeout:new Zl(e),conversationListInitialRender:new ql(e),aievAuthExpiredUnhandled:new Ul(e),messagePendingStuck:new Xl(e),userPerceivedResponseTime:new du(e),streamStalled:new ru(e),typingIndicatorAbsentTimeout:new iu(e),renderedContentUnusable:new eu(e)};return{...t,clear:()=>{Object.values(t).forEach(n=>n.clear())}}};class yn extends Eu{constructor(n){super();b(this,"appId");b(this,"aiAgentId");b(this,"_chatClient");b(this,"_deskClient");b(this,"_cache");b(this,"_logger");b(this,"_dispatcher");b(this,"_session",null);b(this,"language");b(this,"countryCode");b(this,"context");b(this,"cpaAuthorizationCodes");b(this,"queryParams");b(this,"_config");b(this,"_networkStateAdapter");b(this,"_scheduleForegroundTask");b(this,"_watchBackgrounded");b(this,"_forceCreateChannel");b(this,"_agentVersion");b(this,"_statsTrackers");b(this,"_liveMetricManager");b(this,"_operationQueue",mu());b(this,"dispose",()=>{this._operationQueue.isPending()||(this._logger.debug("AIAgent.dispose: start"),this._chatClient.dispose(),this._chatClient.chatSDK.connectionState==="OPEN"&&this._chatClient.chatSDK.disconnectWebSocket(),this._removeChannelHandler(),this._session=null,this._deskClient.deauthenticate(),this._statsTrackers.clear(),this._liveMetricManager.dispose(),this._logger.debug("AIAgent.dispose: end"))});b(this,"initConversationIfNeeded",(n,r)=>this._initConversationIfNeeded(n,r));b(this,"authenticate",n=>{if(!this.appId)return Promise.reject(new Error("appId is required"));if(!this.aiAgentId)return Promise.reject(new Error("aiAgentId is required"));const r=n&&"userId"in n?`auth:${n.userId}`:"auth:anon";return this._operationQueue(r,async()=>{var i,c,u,d,m;this._logger.debug("AIAgent.authenticate: start"),this._statsTrackers.conversationInitialRender.onAuthStart(),this._statsTrackers.conversationListInitialRender.onAuthStart();const s=this._getSessionCandidate(n),o=(i=s.userSessionCandidate)!=null&&i.userId?this._cache.messenger.getSettings(s.userSessionCandidate.userId):null;o!=null&&o.bot&&this._dispatcher.send(at.MessengerSettingsUpdated({settings:o,source:"cache"}));try{const h=await this._chatClient.requestMessengerSettings({aiAgentId:this.aiAgentId,userId:(c=s.userSessionCandidate)==null?void 0:c.userId,language:this.language,country:this.countryCode,context:this.context,knownActiveChannelUrl:(u=o==null?void 0:o.active_channel)==null?void 0:u.channel_url,forceCreateChannel:this._forceCreateChannel,agentVersion:this._agentVersion});let f;if(h.auto_created_user)if(s.type==="manual")this._logger.warn("Received auto created user info but current session is manual. Ignoring auto created user info."),f={userId:s.userSessionCandidate.userId,authToken:s.userSessionCandidate.authToken};else{const{user_id:v,session_token:S,expire_at:C}=h.auto_created_user;this._cache.messenger.setAnonUser({userId:v,authToken:S,expireAt:C}),f={userId:v,authToken:S},this._logger.debug("AIAgent.authenticate: anonymous user created",v)}else f={userId:((d=s.userSessionCandidate)==null?void 0:d.userId)??"",authToken:((m=s.userSessionCandidate)==null?void 0:m.authToken)??""};this._cache.messenger.setSettings(f.userId,h),this._dispatcher.send(at.MessengerSettingsUpdated({settings:h,source:"server"}));const g=(()=>{var v;return s.type==="anonymous"?Al(this._dispatcher):(v=s.userSessionCandidate)==null?void 0:v.sessionHandler})(),p=await this._chatClient.connect(f,g,v=>{var S;this._logger.debug("AIAgent: session token refreshed"),(S=this._session)==null||S._updateAuthToken(v),this._deskClient.refreshDeskAuthToken(v)},()=>{this._logger.debug("AIAgent: session token unavailable, deauthenticating desk"),this._deskClient.deauthenticate()},this.cpaAuthorizationCodes?{aiAgentId:this.aiAgentId,authCodes:this.cpaAuthorizationCodes}:void 0);return await this._deskClient.authenticate({userId:f.userId,accessToken:f.authToken,onDeskTokenRefreshRequired:async({reason:v})=>{var S;if(v===_i.ERR_SESSION_KEY_EXPIRED){await new Promise(A=>setTimeout(A,2e3));const C=(S=this._session)==null?void 0:S.userSession.authToken;return C?await this._deskClient.refreshDeskAuthToken(C):!1}return!1}}),(o==null?void 0:o.language)!==h.language&&this._deskClient.setCustomerLanguage(this.language).catch(()=>{}),this._statsTrackers.conversationInitialRender.onAuthComplete(),this._statsTrackers.conversationListInitialRender.onAuthComplete(),this._session=new Cu({sdkUser:p,userSession:f,activeChannel:{url:h.active_channel.channel_url,status:"open"},dispatcher:this._dispatcher}),this._setupChannelHandler(),this._logger.debug("AIAgent.authenticate: end",{userId:f.userId}),h}catch(h){throw this._statsTrackers.conversationInitialRender.onAuthError(h),this._statsTrackers.conversationListInitialRender.onAuthError(h),h}})});b(this,"submitCPAAuthorizationCodes",async n=>{Ye(this._session),this._logger.debug("AIAgent.submitCPAAuthorizationCodes: start");const r=await this._chatClient.submitCPAAuthorizationCodes({aiAgentId:this.aiAgentId,authCodes:n});return this._logger.debug("AIAgent.submitCPAAuthorizationCodes: end",r),r});b(this,"deauthenticate",()=>this._operationQueue("deauth",async()=>{var r;this._logger.debug("AIAgent.deauthenticate: start");const n=(r=this._session)==null?void 0:r.userSession.userId;this._statsTrackers.clear();try{await this._chatClient.disconnect()}finally{this._deskClient.deauthenticate(),this._cache.messenger.clear(n),this._session=null,this._removeChannelHandler(),this._statsTrackers.clear()}this._logger.debug("AIAgent.deauthenticate: end")}));b(this,"createConversation",async n=>{Ye(this._session),this._logger.debug("AIAgent.createConversation: start",n);const r=await this._chatClient.requestMessengerSettings({...n,userId:this._session.userSession.userId,knownActiveChannelUrl:void 0,agentVersion:this._agentVersion}),s=r.active_channel.channel_url;return this._cache.messenger.setSettings(this._session.userSession.userId,r),this._logger.debug("AIAgent.createConversation: end",s),s});b(this,"searchConversation",async n=>{if(Ye(this._session),this._logger.debug("AIAgent.searchConversation: start",n),Object.entries(n.context).length===0)return this._logger.debug("AIAgent.searchConversation: empty context, returning empty array"),[];const r=this.chatSDK.aiAgent.createConversationListQuery({aiAgentId:n.aiAgentId,status:he.ConversationStatus.OPEN,limit:100}),s=[];for(;r.hasNext;){const o=await r.next();for(const i of o)Bu(i.context??{},n.context)&&s.push(i.channelInfo.url)}return this._logger.debug("AIAgent.searchConversation: end",{count:s.length}),s});b(this,"closeConversation",async n=>{var s;Ye(this._session),this._logger.debug("AIAgent.closeConversation: start",n);const r=await this._chatClient.getChannel(n);((s=r.conversation)==null?void 0:s.status)===he.ConversationStatus.OPEN?(await r.closeConversation(),this._session.activeChannel.url===n&&this._session._updateActiveChannel({url:n,status:"closed",conversationStatus:he.ConversationStatus.CLOSED}),this._logger.debug("AIAgent.closeConversation: end")):this._logger.debug("AIAgent.closeConversation: already closed or not an AI agent conversation")});b(this,"createConversationListCollection",n=>new si(this.chatSDK,n??{}));b(this,"patchContext",async(n,r)=>{Ye(this._session),this._logger.debug("AIAgent.patchContext: start",{channelUrl:n,context:r});const s=await this._chatClient.patchContext(this.aiAgentId,n,r);return this._logger.debug("AIAgent.patchContext: end",s),{...s,context:s.context??{}}});b(this,"updateContext",async(n,r)=>{Ye(this._session),this._logger.debug("AIAgent.updateContext: start",{channelUrl:n,context:r});const s=await this._chatClient.updateContext(this.aiAgentId,n,r);return this._logger.debug("AIAgent.updateContext: end",s),{...s,context:s.context??{}}});b(this,"getContextObject",async n=>{Ye(this._session),this._logger.debug("AIAgent.getContextObject: start",n);const s=await(await this._chatClient.getChannel(n)).getContextObject(this.aiAgentId);return this._logger.debug("AIAgent.getContextObject: end",s),{...s,context:s.context??{}}});b(this,"requestNudgeMessage",async n=>{Ye(this._session);const r=this._session;this._logger.debug("AIAgent.requestNudgeMessage: start",n);const s=await this._chatClient.requestNudgeMessage({aiAgentId:this.aiAgentId,key:n.key,context:n.context,language:this.language});if(this._logger.debug("AIAgent.requestNudgeMessage: end",s),this._session!==r){this._logger.debug("AIAgent.requestNudgeMessage: session changed during request, discarding stale nudge");return}s.status!=="ok"||!s.payload.message||this._dispatcher.send(at.NudgeMessageReceived({message:s.payload.message,callbackUserMessage:s.payload.callback_user_message??void 0}))});b(this,"clearUserMemories",async(n={})=>{Ye(this._session);const r={...n,contextAiAgentId:n.contextAiAgentId??this.aiAgentId};this._logger.debug("AIAgent.clearUserMemories: start",r),await this._chatClient.clearUserMemories(r),this._logger.debug("AIAgent.clearUserMemories: end")});b(this,"setUserMemoryState",async n=>{Ye(this._session);const r=this._session;this._logger.debug("AIAgent.setUserMemoryState: start",n.enabled);const s={...n,contextAiAgentId:n.contextAiAgentId??this.aiAgentId},o=r.userSession.userId,i=await this._chatClient.setUserMemoryState(s);if(this._session!==r)return this._logger.debug("AIAgent.setUserMemoryState: session changed during request, discarding stale result"),Cr(i);const c=this._cache.messenger.getSettings(o);if(c){const u={...c,memory:i};this._cache.messenger.setSettings(o,u),this._dispatcher.send(at.MessengerSettingsUpdated({settings:u,source:"cache"}))}return this._logger.debug("AIAgent.setUserMemoryState: end",i.enabled),Cr(i)});b(this,"refreshActiveChannel",async n=>{var c,u,d;Ye(this._session);const r=this._session,s=(n==null?void 0:n.useKnownActiveChannelUrl)??!0;this._logger.debug("AIAgent.refreshActiveChannel: start",{useKnownActiveChannelUrl:s});const o=await this._chatClient.requestMessengerSettings({aiAgentId:this.aiAgentId,userId:r.userSession.userId,language:this.language,country:this.countryCode,context:this.context,knownActiveChannelUrl:s?(u=(c=this._cache.messenger.getSettings(r.userSession.userId))==null?void 0:c.active_channel)==null?void 0:u.channel_url:void 0,forceCreateChannel:this._forceCreateChannel,agentVersion:this._agentVersion});if(this._session!==r)return this._logger.debug("AIAgent.refreshActiveChannel: session changed during refresh, discarding stale result"),((d=this._session)==null?void 0:d.activeChannel.url)??o.active_channel.channel_url;const i=o.active_channel.channel_url;return this._cache.messenger.setSettings(this._session.userSession.userId,o),this._session._updateActiveChannel({url:i,status:"open"}),this._logger.debug("AIAgent.refreshActiveChannel: end",i),i});b(this,"_getSessionCandidate",n=>n instanceof li?{type:"manual",userSessionCandidate:this._getManualSessionInfo(n)}:n instanceof pr?{type:"anonymous",userSessionCandidate:this._getAnonymousSessionInfo()}:n&&typeof n=="object"?(this._logger.warn("Please use ManualSessionInfo instead of the old userSessionInfo format."),{type:"manual",userSessionCandidate:this._getManualSessionInfo(n)}):n===void 0?(this._logger.warn("Please use AnonymousSessionInfo instead of undefined userSessionInfo."),{type:"anonymous",userSessionCandidate:this._getAnonymousSessionInfo()}):{type:"anonymous",userSessionCandidate:null});b(this,"_getAnonymousSessionInfo",()=>{const n=this._cache.messenger.getAnonUser();return n?n.expireAt-Fu<=Date.now()?(this._logger.debug("_getAnonymousSessionInfo: auto session expired, clear cache"),this._cache.messenger.clear(n.userId),null):(this._logger.debug("_getAnonymousSessionInfo: auto session info detected"),{userId:n.userId,authToken:n.authToken}):null});b(this,"_getManualSessionInfo",n=>{if(!n||n instanceof pr)throw new Error("userSessionInfo must be an instance of ManualSessionInfo");if(typeof n.userId!="string")throw new Error("userSessionInfo.userId must be a string");const r=["userId","authToken","sessionHandler"].filter(s=>!(s in n));return r.length>0&&this._logger.error(`_getManualSessionInfo: missing required keys in userSessionInfo: ${r.join(", ")}`),this._logger.debug("_getManualSessionInfo: manual session info detected"),{userId:n.userId,authToken:n.authToken,sessionHandler:n.sessionHandler}});this.appId=n.appId,this.aiAgentId=n.aiAgentId,this.language=n.language??"en",this.countryCode=n.countryCode,this.context=n.context,this.cpaAuthorizationCodes=n.cpaAuthorizationCodes,this._config=Ts(n.config),this.queryParams=n.queryParams,this._networkStateAdapter=n.networkStateAdapter,this._scheduleForegroundTask=Ou(n.foregroundStateAdapter),this._watchBackgrounded=n.foregroundStateAdapter&&Nu(n.foregroundStateAdapter),this._forceCreateChannel=n.forceCreateChannel,this._agentVersion=n.agentVersion,this._chatClient=n.chatClient,this._deskClient=n.deskClient,this._cache=n.cache,this._logger=n.logger,this._dispatcher=n.dispatcher,this._statsTrackers=n.statsTrackers,this._liveMetricManager=new yl(this._chatClient.chatSDK),this._liveMetricManager.start()}static init(n){var g;const r=pi.get(n.platform),s=n.logger??new ci(n.logLevel??Fr.WARN),o=n.dispatcher??new oi(s),i=n.useMMKVStorage?Pu(n.useMMKVStorage):r.keyValueStorage,c=n.useMMKVStorage?{...n.chatParams,useMMKVStorageStore:n.useMMKVStorage}:n.chatParams,u=zc({appId:n.appId,aiAgentId:n.aiAgentId,storage:i});let d;const h=Hu((p,v)=>{if(!d)throw new Error("ChatClient is not initialized.");return d.chatSDK.aiAgent.appendStat(p,v)});d=Gr.init({appId:n.appId,aiAgentId:n.aiAgentId,messengerVersion:r.messengerVersion,extensions:{platform:r.platform,deviceOSPlatform:r.deviceOSPlatform,deviceOSVersion:r.deviceOSVersion},chatParams:c,chatSDK:n.chatSDK,logger:s,cache:u,statsTrackers:h});const f=Uu?qr.init({appId:n.appId,logger:s,customApiHost:(g=n.deskParams)==null?void 0:g.customApiHost}):Kr.init();return s.debug("AIAgent.init: created",{appId:n.appId,aiAgentId:n.aiAgentId}),new yn({appId:n.appId,aiAgentId:n.aiAgentId,language:n.language,countryCode:n.countryCode,context:n.context,cpaAuthorizationCodes:n.cpaAuthorizationCodes,config:n.config,queryParams:n.queryParams,networkStateAdapter:r.networkStateAdapter,foregroundStateAdapter:r.foregroundStateAdapter,forceCreateChannel:n._forceCreateChannel,agentVersion:n._agentVersion,chatClient:d,deskClient:f,cache:u,logger:s,dispatcher:o,statsTrackers:h})}get chatSDK(){return this._chatClient.chatSDK}get deskClient(){return this._deskClient}get session(){return this._session}get config(){return this._config}set config(n){this._config=Ts(n)}get agentVersion(){return this._agentVersion}set agentVersion(n){this._agentVersion=n}get statsTrackers(){return this._statsTrackers}get liveMetricManager(){return this._liveMetricManager}get onLiveMetric(){return this._liveMetricManager.dispatch}set onLiveMetric(n){this._liveMetricManager.dispatch=n}get networkStateAdapter(){return this._networkStateAdapter}get logger(){return this._logger}get dispatcher(){return this._dispatcher}get cache(){return this._cache}get scheduleForegroundTask(){return this._scheduleForegroundTask}get watchBackgrounded(){return this._watchBackgrounded}}const ve=(e,t)=>{const n=l.createContext(t??null),r=({children:i,value:c})=>a.createElement(n.Provider,{value:c},typeof i=="function"?i(c):i),s=({children:i})=>a.createElement(n.Consumer,null,c=>c?typeof i=="function"?i(c):i:null),o=()=>{const i=l.useContext(n);if(!i)throw new Error(`use${e}Context must be used within a ${e}Provider`);return i};return n.displayName=`${e}Context`,r.displayName=`${e}Provider`,s.displayName=`${e}Consumer`,o.displayName=`use${e}Context`,{Context:n,Provider:r,Consumer:s,useContext:o}};function je(e){const t=l.createContext({Template:e.template,updateTemplate:()=>{},components:e.components,updateComponent:()=>{}});function n({children:o}){const[i,c]=l.useState(()=>e.template),[u,d]=l.useState(e.components),m={Template:i,updateTemplate:h=>c(()=>h),components:u,updateComponent:(h,f)=>d(g=>({...g,[h]:f}))};return a.createElement(t.Provider,{value:m},o)}function r({template:o,children:i}){const{updateTemplate:c}=l.useContext(t);return l.useLayoutEffect(()=>{o&&c(o)},[o]),a.createElement(a.Fragment,null,i)}function s({children:o}){return a.createElement(n,null,o)}return s.defaults=e,s.useContext=()=>l.useContext(t),s.Context=t,s.Template=r,Object.keys(e.components).forEach(o=>{s[o]=function({component:c}){const{updateComponent:u}=l.useContext(t);return l.useLayoutEffect(()=>{c&&u(o,c)},[c]),null}}),s}function Gu(...e){return function({children:n}){return e.reduce((r,s)=>a.createElement(s,null,r),n)}}function zu(e,t){const n=e.lastMessage;return n!=null&&n.isAdminMessage()?n.message??"":Vu(e,t)}function Vu(e,t){var r;const n=e.lastMessage;if(n!=null&&n.isUserMessage())return n.message||"";if(n!=null&&n.isAdminMessage())return n.message??"";if(n!=null&&n.isFileMessage())return n.message||n.name||"FILE";if(n!=null&&n.isMultipleFilesMessage()){if(n.message)return n.message;const s=n.fileInfoList.length;return((r=t==null?void 0:t.formatMultipleFilesCount)==null?void 0:r.call(t,s))??`${s} photos`}return e.name}function qu(e,t,n){var i;const r=new Date,s=new Date(((i=e.lastMessage)==null?void 0:i.createdAt)||e.createdAt),o=ut.differenceInMinutes(r,s);return o<1?n.justNow:o<60?n.minutesAgo(o):ut.isToday(s)?n.hoursAgo(ut.differenceInHours(r,s)):t(s,n.dateShortFormat)}const Ku=e=>{const t=e.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null},cn=e=>Math.max(0,Math.min(255,e)).toString(16).padStart(2,"0"),xs=(e,t)=>{const n=cn(Math.round(t*255));if(e.startsWith("#")){const s=e.slice(1);return s.length===3||s.length===4?`#${s[0]}${s[0]}${s[1]}${s[1]}${s[2]}${s[2]}${n}`:`#${s.slice(0,6)}${n}`}const r=Ku(e);return r?`#${cn(r[0])}${cn(r[1])}${cn(r[2])}${n}`:e},Yu=(e,t)=>{if(!t)return e;const n={...e};for(const[r,s]of Object.entries(t))s&&(n[r]=s);return n},Wu=e=>e.consentDialog?"consent":e.toggleAllowed?e.enabled?"on":"off":"readonly",ju=e=>e.length>0,Xu=e=>{const t=e[0];if(!t)return e;const n=e.some(s=>We(s.type)),r=e.some(s=>!We(s.type));return n&&r?We(t.type)?e.filter(s=>We(s.type)):[t]:r?[t]:e},Rs=e=>e.length===0?"empty":e.every(t=>We(t.type))?"images":"non_images",Zu=({currentFiles:e,incomingFiles:t,maxAttachmentCount:n})=>{const r=Xu(t),s=Rs(e),o=Rs(r),c=s==="images"&&o==="images"?{type:"append",files:r,nextFiles:[...e,...r]}:{type:"replace",files:r,nextFiles:r};return c.nextFiles.length>n?{type:"reject",reason:"count_limit",maxAttachmentCount:n,nextFileCount:c.nextFiles.length}:c.type==="replace"&&s!=="empty"&&s!==o?{type:"confirm_replace",action:c}:{type:"apply",action:c}},It=3,Ei=6,Ju=e=>e%It===0?It:Ei,Qu=({index:e,itemCount:t})=>{const n=t%It,r=n>0,s=r?t-n:t,o=r&&e>=s,i=o?n:It,c=o?e-s:e%It,u=!r&&e>=t-It;return{columnSpan:r?Ei/i:1,rowItemCount:i,isLastInRow:c===i-1,isLastRow:o||u}},Ci=ve("AIAgent"),ed=Ci.Provider,ye=Ci.useContext;function td(e){const t=nd(e);return a.createElement(ed,{value:{_aiAgentSDK:t,chatSDK:t.chatSDK,deskClient:t.deskClient,appId:t.appId,aiAgentId:t.aiAgentId,language:t.language,countryCode:t.countryCode,context:t.context,cpaAuthorizationCodes:t.cpaAuthorizationCodes,logger:t.logger,dispatcher:t.dispatcher,cache:t.cache,networkStateAdapter:t.networkStateAdapter,queryParams:t.queryParams,config:t.config,handlers:e.handlers}},e.children)}function nd(e){var s;const t=l.useRef(null),n=l.useRef(null);if(!t.current||!n.current)t.current=yn.init(e);else{const o=rd(n.current,e);(o.appId||o.aiAgentId||o.chatSDK)&&(t.current.dispose(),t.current=yn.init({...e,chatParams:o.appId?{...e.chatParams,newInstance:!0}:e.chatParams}))}n.current=e,l.useEffect(()=>()=>{var o;(o=t.current)==null||o.dispose()},[]);const r=t.current;return r.language=e.language??"en",r.countryCode=e.countryCode,r.context=e.context,r.cpaAuthorizationCodes=e.cpaAuthorizationCodes,r.queryParams=e.queryParams,r.config=e.config,r.agentVersion=e._agentVersion,r.onLiveMetric=(s=e.handlers)==null?void 0:s.onLiveMetric,r}function rd(e,t){const n=t.chatSDK!==void 0&&t.chatSDK!==null;return{appId:!n&&e.appId!==t.appId,aiAgentId:e.aiAgentId!==t.aiAgentId,chatSDK:!!e.chatSDK!==n||n&&t.chatSDK!==e.chatSDK}}function ce(e){const t=l.useRef(e);return t.current=e,l.useCallback((...n)=>t.current(...n),[t])}const Nn=()=>{const[,e]=l.useState(0);return l.useCallback(()=>e(t=>t+1),[])};let sd=0;function od(){return l.useState(()=>`${sd++}`)[0]}const pt=(e,t,n)=>{const r=l.useRef(t),o=od();r.current=t,l.useEffect(()=>{var c;const i=u=>{const d=u;return Object.keys(d).forEach(h=>{d[h]=(...f)=>{var p;const g=r.current;(p=g[h])==null||p.call(g,...f)}}),d};return(c=e==null?void 0:e.groupChannel)==null||c.addGroupChannelHandler(o,i(new Qe.GroupChannelHandler)),()=>{var u;(u=e==null?void 0:e.groupChannel)==null||u.removeGroupChannelHandler(o)}},[e==null?void 0:e.groupChannel,o])};function id(e,t){return!e||!t?!0:e.url!==t.url}function Ve(e){return e!=null&&"sendingStatus"in e}function ad(e,t="##__USER_ID_IS_NOT_PROVIDED__##"){var n;return Ve(e)?((n=e.sender)==null?void 0:n.userId)===t:!1}function cd(e,t){return ad(e,t)||e.isAdminMessage()?!1:e.updatedAt===0}function Ms(e){return"sendingStatus"in e?e.sendingStatus==="succeeded"?String(e.messageId):e.reqId:String(e.messageId)}const An={collection:{groupChannel:{defaultOrder:Qe.GroupChannelListOrder.LATEST_LAST_MESSAGE},message:{defaultLimit:{next:25,prev:25},searchLimit:{next:10,prev:10}}}};function ws(e){return!e||!Array.isArray(e)?!1:e.length!==0}function ks(e,t){return e.reduce((n,r)=>{const s=t(r);return n[s]=r,n},{})}const ld=({...e},t)=>{switch(t.type){case"update_initialized":return e.initialized=t.value.status,e;case"update_refreshing":return e.refreshing=t.value.status,e;case"update_loading":return e.loading=t.value.status,e;case"update_messages":{if(t.value.clearBeforeAction)e.messageMap=ud(t.value.messages);else{const n={...e.messageMap},r=[],s=[];t.value.messages.forEach(o=>{const i=Ve(o)?o.reqId:void 0,c=o.messageId||void 0;[i,c].forEach(u=>{if(!u)return;const d=n[u];dd(d,o,t.value.strictStreamingOrder)&&(d&&r.push(d),o.parentMessageId>0&&(d!=null&&d.parentMessage)&&o.applyParentMessage(d.parentMessage),s.push(o))})}),r.forEach(o=>{Ve(o)&&delete n[o.reqId],delete n[o.messageId]}),s.forEach(o=>{Ve(o)&&(n[o.reqId]=o),o.messageId!==0&&(n[o.messageId]=o)}),e.messageMap=n}return e}case"update_new_messages":{const n=t.value.currentUserId,r=t.value.messages.filter(s=>cd(s,n));return t.value.clearBeforeAction?e.newMessageMap=ks(r,Ms):(r.map(o=>o.messageId).forEach(o=>delete e.newMessageMap[o]),e.newMessageMap={...e.newMessageMap,...ks(r,Ms)}),e}case"delete_messages":case"delete_new_messages":{const n=t.type==="delete_messages"?"messageMap":"newMessageMap";return e[n]={...e[n]},t.value.messageIds.forEach(r=>{if(r===0)return;const s=e[n][r];s&&(Ve(s)&&delete e[n][s.reqId],delete e[n][s.messageId])}),t.value.reqIds.forEach(r=>{const s=e[n][r];s&&(Ve(s)&&delete e[n][s.reqId],delete e[n][s.messageId])}),e}}},ud=e=>e.reduce((t,n)=>(Ve(n)?(t[n.reqId]=n,n.sendingStatus===Le.SendingStatus.SUCCEEDED&&(t[n.messageId]=n)):t[n.messageId]=n,t),{}),dd=(e,t,n=!1)=>{var r,s;if(!Ve(e)||!Ve(t))return!0;if(n&&e&&we.isStreaming(e)&&we.isStreaming(t)){const o=((r=e.message)==null?void 0:r.length)||0,i=((s=t.message)==null?void 0:s.length)||0;if(o>i)return!1}return e.sendingStatus===Le.SendingStatus.SUCCEEDED?t.sendingStatus===Le.SendingStatus.SUCCEEDED:e.sendingStatus!==t.sendingStatus},md=(e=hd)=>{const[{initialized:t,loading:n,refreshing:r,messageMap:s,newMessageMap:o},i]=l.useReducer(ld,{initialized:!1,loading:!0,refreshing:!1,messageMap:{},newMessageMap:{}}),c=(S,C,A,y)=>{i({type:"update_messages",value:{messages:S,clearBeforeAction:C,currentUserId:A,strictStreamingOrder:y}})},u=(S,C)=>{i({type:"delete_messages",value:{messageIds:S,reqIds:C}})},d=(S,C,A)=>{i({type:"update_new_messages",value:{messages:S,clearBeforeAction:C,currentUserId:A}})},m=(S,C)=>{i({type:"delete_new_messages",value:{messageIds:S,reqIds:C}})},h=S=>{i({type:"update_initialized",value:{status:S}})},f=S=>{i({type:"update_loading",value:{status:S}})},g=S=>{i({type:"update_refreshing",value:{status:S}})},p=Object.values(o),v=l.useMemo(()=>Array.from(new Set(Object.values(s))).sort(e),[s]);return{updateInitialized:h,updateLoading:f,updateRefreshing:g,updateMessages:c,deleteMessages:u,initialized:t,loading:n,refreshing:r,messages:v,newMessages:p,updateNewMessages:d,deleteNewMessages:m}},Ls=Math.floor(Number.MAX_SAFE_INTEGER/10);function hd(e,t){let n=0,r=0;return Ve(e)&&e.sendingStatus!=="succeeded"&&(n=Ls),Ve(t)&&t.sendingStatus!=="succeeded"&&(r=Ls),e.createdAt+n-(t.createdAt+r)}const fd=(e,t,n)=>{var o;const r={prevResultLimit:t.prev,nextResultLimit:t.next,startingPoint:n==null?void 0:n.startingPoint,replyType:n==null?void 0:n.replyType},s=(o=n==null?void 0:n.collectionCreator)==null?void 0:o.call(n,r);return s||e.createMessageCollection({...r,filter:new Qe.MessageFilter(r)})};function Os(e){return e<Date.now()?An.collection.message.searchLimit:An.collection.message.defaultLimit}const gd=(e,t,n={})=>{var Te,$;const r=l.useRef(n);r.current=n;const s=l.useRef(t);s.current=t;const o=r.current.logger,i=r.current.startingPoint??Number.MAX_SAFE_INTEGER,c=Os(i),u=r.current.strictStreamingOrder??!1,d=l.useRef({prev:!1,next:!1}),m=Nn(),h=l.useRef({initialized:!1,apiInitialized:!1,instance:null}),{initialized:f,loading:g,refreshing:p,messages:v,newMessages:S,updateMessages:C,updateNewMessages:A,deleteNewMessages:y,deleteMessages:T,updateInitialized:I,updateLoading:N,updateRefreshing:O}=md(n==null?void 0:n.sortComparator),k=ce(M=>{var x,L,P,X;if(!s.current||!s.current.url)return(x=o==null?void 0:o.error)==null?void 0:x.call(o,"[useGroupChannelMessages] channel is required");try{switch(M){case Ce.CollectionEventSource.EVENT_MESSAGE_RECEIVED:case Ce.CollectionEventSource.EVENT_MESSAGE_SENT_SUCCESS:case Ce.CollectionEventSource.SYNC_MESSAGE_FILL:case void 0:(P=(L=r.current).markAsRead)==null||P.call(L,[s.current]);break}}catch(se){(X=o==null?void 0:o.warn)==null||X.call(o,"[useGroupChannelMessages/markAsReadBySource]",se)}}),R=ce((M,x)=>{var L,P,X,se,Z;if(x.length>0)switch(M){case Ce.CollectionEventSource.EVENT_MESSAGE_RECEIVED:case Ce.CollectionEventSource.SYNC_MESSAGE_FILL:{(P=(L=r.current).shouldCountNewMessages)!=null&&P.call(L)&&A(x,!1,(X=e.currentUser)==null?void 0:X.userId),(Z=(se=r.current).onMessagesReceived)==null||Z.call(se,x);break}}}),F=ce(M=>{var x,L;(L=(x=r.current).onCollectionEvent)==null||L.call(x,M)}),D=ce(async(M,x,L)=>new Promise((P,X)=>{var Xe,it,sn;h.current.instance&&h.current.instance.dispose(),k(),A([],!0,(Xe=e.currentUser)==null?void 0:Xe.userId);const se=()=>{var ge,pe;const{pendingMessages:le,failedMessages:fe}=h.current.instance??{};ws(le)&&C(le,!1,(ge=e.currentUser)==null?void 0:ge.userId),ws(fe)&&C(fe,!1,(pe=e.currentUser)==null?void 0:pe.userId)},Z=fd(M,L,{...r.current,startingPoint:x});h.current={apiInitialized:!1,initialized:!1,instance:Z},Z.setMessageCollectionHandler({onMessagesAdded:(le,fe,ge)=>{var pe;k(le.source),R(le.source,ge),C(ge,!1,(pe=e.currentUser)==null?void 0:pe.userId,u),F({kind:"messagesAdded",source:le.source,channelUrl:M.url,messages:ge})},onMessagesUpdated:(le,fe,ge)=>{var pe,Fe,Ue;k(le.source),R(le.source,ge),C(ge,!1,(pe=e.currentUser)==null?void 0:pe.userId,u),le.source===Ce.CollectionEventSource.EVENT_MESSAGE_UPDATED&&((Ue=(Fe=r.current).onMessagesUpdated)==null||Ue.call(Fe,ge)),F({kind:"messagesUpdated",source:le.source,channelUrl:M.url,messages:ge})},onMessagesDeleted:(le,fe,ge,pe)=>{const Fe=pe.map(Ee=>Ee.messageId),Ue=pe.filter(Ve).map(Ee=>Ee.reqId);T(Fe,Ue),y(Fe,Ue),F({kind:"messagesDeleted",source:le.source,channelUrl:M.url,messages:pe})},onChannelDeleted:(le,fe)=>{var ge,pe;(pe=(ge=r.current).onChannelDeleted)==null||pe.call(ge,fe)},onChannelUpdated:(le,fe)=>{var ge,pe;m(),(pe=(ge=r.current).onChannelUpdated)==null||pe.call(ge,fe,le)},onHugeGapDetected:()=>{D(M,Number.MAX_SAFE_INTEGER,An.collection.message.defaultLimit)}});let be=!1;(sn=(it=r.current).onCollectionInitializeStart)==null||sn.call(it),Z.initialize(Qe.MessageCollectionInitPolicy.CACHE_AND_REPLACE_BY_API).onCacheResult((le,fe)=>{var ge,pe,Fe,Ue,Ee;(pe=(ge=r.current).onCacheResult)==null||pe.call(ge,le,fe??[],M.url),le?(e.isCacheEnabled&&((Fe=o==null?void 0:o.error)==null||Fe.call(o,"[useGroupChannelMessages/onCacheResult]",le)),be=!0):fe&&((Ue=o==null?void 0:o.debug)==null||Ue.call(o,"[useGroupChannelMessages/onCacheResult]","message length:",fe.length),C(Z.succeededMessages,!0,(Ee=e.currentUser)==null?void 0:Ee.userId),se(),fe.length>0&&(h.current.initialized=!0,P())),F({kind:"initialized",source:"cache",channelUrl:M.url,messages:fe??[],error:le})}).onApiResult((le,fe)=>{var ge,pe,Fe,Ue,Ee,Ze,Ne;(pe=(ge=r.current).onApiResult)==null||pe.call(ge,le,fe??[],M.url),h.current.initialized=!0,h.current.apiInitialized=!0,le?((Fe=o==null?void 0:o.warn)==null||Fe.call(o,"[useGroupChannelMessages/onApiResult]",le),be?X(le):P()):fe&&((Ue=o==null?void 0:o.debug)==null||Ue.call(o,"[useGroupChannelMessages/onApiResult]","message length:",fe.length),C(Z.succeededMessages,!0,(Ee=e.currentUser)==null?void 0:Ee.userId),r.current.startingPoint||(Ne=(Ze=r.current).onMessagesReceived)==null||Ne.call(Ze,fe),e.isCacheEnabled&&se(),P()),F({kind:"initialized",source:"api",channelUrl:M.url,messages:fe??[],error:le})})}));pt(e,{onUserBanned(M,x){var L,P,X;M.isGroupChannel()&&!id(M,s.current)&&(x.userId===((L=e.currentUser)==null?void 0:L.userId)?(X=(P=r.current).onCurrentUserBanned)==null||X.call(P):m())}}),l.useLayoutEffect(()=>{const M=setTimeout(async()=>{e.currentUser&&s.current&&(I(!1),N(!0),await D(s.current,i,c),N(!1),I(!0))});return()=>clearTimeout(M)},[e,(Te=e.currentUser)==null?void 0:Te.userId,($=s.current)==null?void 0:$.url,r.current.replyType]),l.useEffect(()=>()=>{h.current.instance&&h.current.instance.dispose()},[]);const Q=ce(async()=>{e.currentUser&&s.current&&(O(!0),await D(s.current,Number.MAX_SAFE_INTEGER,An.collection.message.defaultLimit),O(!1))}),re=ce(async()=>{var x;const M=h.current.instance;if(M!=null&&M.hasPrevious&&!d.current.prev)try{d.current.prev=!0;const L=await M.loadPrevious();C(L,!1,(x=e.currentUser)==null?void 0:x.userId)}catch{}finally{d.current.prev=!1}}),G=ce(()=>{const{initialized:M,instance:x}=h.current;return M&&x?x.hasPrevious:!1}),H=ce(async()=>{var x;const M=h.current.instance;if(M!=null&&M.hasNext&&!d.current.next)try{d.current.next=!0;const L=await M.loadNext();C(L,!1,(x=e.currentUser)==null?void 0:x.userId)}catch{}finally{d.current.next=!1}}),q=ce(()=>{const{initialized:M,apiInitialized:x,instance:L}=h.current;return x&&M&&L?L.hasNext:!1}),J=M=>{var x,L,P,X;!M||M.channelUrl!==((x=s.current)==null?void 0:x.url)||(C([M],!1,(L=e.currentUser)==null?void 0:L.userId),(X=(P=r.current).onOutgoingMessageStatusChanged)==null||X.call(P,M))},K=ce((M,x)=>{var L;if(!s.current||!s.current.url)throw(L=o==null?void 0:o.error)==null||L.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((P,X)=>{s.current.sendUserMessage(M).onPending(se=>{J(se),x==null||x(se)}).onSucceeded(se=>{J(se),P(se)}).onFailed((se,Z)=>{J(Z),X(se)})})}),z=ce((M,x)=>{var L;if(!s.current||!s.current.url)throw(L=o==null?void 0:o.error)==null||L.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((P,X)=>{s.current.sendFileMessage(M).onPending(se=>{J(se),x==null||x(se)}).onSucceeded(se=>{J(se),P(se)}).onFailed((se,Z)=>{J(Z),X(se)})})}),Y=ce((M,x,L)=>{var P;if(!s.current||!s.current.url)throw(P=o==null?void 0:o.error)==null||P.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((X,se)=>{s.current.sendMultipleFilesMessage(M).onPending(Z=>{J(Z),x==null||x(Z)}).onFileUploaded(Z=>{L==null||L(Z),m()}).onSucceeded(Z=>{J(Z),X(Z)}).onFailed((Z,be)=>{J(be),se(Z)})})}),W=ce(async(M,x)=>{var P,X;if(!s.current||!s.current.url)throw(P=o==null?void 0:o.error)==null||P.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");const L=await s.current.updateUserMessage(M,x);return L.channelUrl===s.current.url&&C([L],!1,(X=e.currentUser)==null?void 0:X.userId),L}),V=ce(async(M,x)=>{var P,X;if(!s.current||!s.current.url)throw(P=o==null?void 0:o.error)==null||P.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");const L=await s.current.updateFileMessage(M,x);return L.channelUrl===s.current.url&&C([L],!1,(X=e.currentUser)==null?void 0:X.userId),L}),ee=ce(async(M,x,L)=>{var P;if(!s.current||!s.current.url)throw(P=o==null?void 0:o.error)==null||P.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((X,se)=>{let Z;M.isUserMessage()&&(Z=s.current.resendMessage(M)),M.isFileMessage()&&(Z=s.current.resendMessage(M)),M.isMultipleFilesMessage()&&(Z=s.current.resendMessage(M)),Z&&("onPending"in Z&&Z.onPending(be=>{J(be),x==null||x(be)}),"onFileUploaded"in Z&&Z.onFileUploaded(be=>{L==null||L(be),m()}),"onSucceeded"in Z&&Z.onSucceeded(be=>{J(be),X(be)}),"onFailed"in Z&&Z.onFailed((be,Xe)=>{J(Xe),se(be)}))})}),w=ce(async M=>{var x,L,P,X;if(!s.current||!s.current.url)throw(x=o==null?void 0:o.error)==null||x.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");if(M.sendingStatus==="succeeded")M.isUserMessage()&&await s.current.deleteMessage(M),M.isFileMessage()&&await s.current.deleteMessage(M),M.isMultipleFilesMessage()&&await s.current.deleteMessage(M);else try{await((L=h.current.instance)==null?void 0:L.removeFailedMessage(M.reqId))}finally{T([],[M.reqId]),(X=(P=r.current).onLocalMessageDeleted)==null||X.call(P,M)}}),_e=ce(()=>{var M;A([],!0,(M=e.currentUser)==null?void 0:M.userId)}),Re=ce(async M=>{var x;if(e.currentUser&&s.current){const L=Os(M);N(!0),C([],!0,(x=e.currentUser)==null?void 0:x.userId),await D(s.current,M,L),N(!1)}});return{initialized:f,loading:g,refreshing:p,messages:v,newMessages:S,resetNewMessages:_e,refresh:Q,loadPrevious:re,hasPrevious:G,loadNext:H,hasNext:q,sendUserMessage:K,sendFileMessage:z,sendMultipleFilesMessage:Y,updateUserMessage:W,updateFileMessage:V,resendMessage:ee,deleteMessage:w,resetWithStartingPoint:Re,_dangerous_reducer_updateMessages:C,_dangerous_reducer_deleteMessages:T}},pd=e=>e.customType==="SENDBIRD_DESK_ADMIN_MESSAGE_CUSTOM_TYPE"?!0:e.isAdminMessage()?e.message==="The channel's custom_type was updated.":!1,_d=(e,t,n)=>{const r=gd(e,t,{...n,strictStreamingOrder:!0}),s=l.useMemo(()=>r.messages.filter(o=>!pd(o)),[r.messages]);return{...r,messages:s}},Ed=()=>{const e=new Set;return{publish:t=>{e.size!==0&&[...e].forEach(n=>{n(t)})},subscribe:t=>{let n=!0;return e.add(t),()=>{n&&(n=!1,e.delete(t))}}}},bi=Ed(),Cd=({channelUrl:e,enabled:t=!0,statsTracker:n})=>{const r=l.useRef(e),s=l.useRef(t),o=l.useRef(null),i=l.useRef(!1);s.current=t;const c=l.useCallback(p=>r.current===p,[]),u=l.useCallback(()=>{i.current&&(n.clearChannel(r.current),i.current=!1)},[n]),d=l.useCallback(p=>{c(p)&&s.current&&(i.current=!0)},[c]),m=l.useCallback(({channelUrl:p,conversationId:v})=>{i.current=!0,n.markChannelJoined(v,p)},[n]),h=l.useCallback(({channelUrl:p})=>{n.clearChannel(p),i.current=!1},[n]),f=l.useCallback(p=>{if(c(p.channelUrl)){if(!s.current){o.current=p;return}o.current=null,m(p)}},[c,m]),g=l.useCallback(p=>{if(c(p.channelUrl)){if(!s.current){o.current=p;return}o.current=null,h(p)}},[c,h]);return l.useEffect(()=>{if(t){const p=o.current;if(!p||(o.current=null,p.channelUrl!==e))return;"error"in p?h(p):m(p);return}u()},[e,u,t,h,m]),l.useEffect(()=>(r.current=e,o.current=null,i.current=!1,()=>{u(),o.current=null,i.current=!1}),[e,u]),{onFetchStart:d,onFetchSuccess:f,onFetchError:g}},bd=({channelUrl:e,enabled:t=!0,scheduleForegroundTask:n,statsTracker:r})=>{const s=l.useRef(e),o=l.useRef(null),i=l.useRef(t),c=l.useRef(0),u=l.useRef(null);i.current=t;const d=l.useCallback((h=!0)=>{var g;(g=o.current)==null||g.call(o),o.current=null;const f=u.current;h&&(u.current=null),h&&f&&r.clearChannel(f)},[r]),m=l.useCallback(h=>{if(!i.current){d(),r.clearChannel(h);return}d(!1),u.current=h;const f=c.current,g=()=>{if(!i.current||f!==c.current||s.current!==h){r.clearChannel(h),u.current===h&&(u.current=null);return}r.start("ws_reconnected",h)};o.current=(n==null?void 0:n(g))??null,n||g()},[d,n,r]);return l.useEffect(()=>{t||d()},[d,t]),l.useEffect(()=>(s.current=e,c.current+=1,()=>{c.current+=1,d()}),[e,d]),{onReconnectSucceeded:m}},qt={DEFAULT_PRIMARY:"#000000",DEFAULT_BOT_MSG_BG:"#ECECEC",WHITE:"#ffffff",BLACK:"#000000"};function vi(e){return e.length===4?`#${[...e.slice(1)].map(t=>t+t).join("")}`:e}function vd(e){const t=vi(e);return[parseInt(t.slice(1,3),16),parseInt(t.slice(3,5),16),parseInt(t.slice(5,7),16)]}function Sd(e){return`#${e.map(t=>t.toString(16).padStart(2,"0")).join("")}`}function yd(e,t,n){e/=255,t/=255,n/=255;const r=Math.max(e,t,n),s=Math.min(e,t,n),o=r-s;let i=0,c=0;const u=(r+s)/2;return r!==s&&(c=u>.5?o/(2-r-s):o/(r+s)),r===e?i=(t-n)/o+(t<n?6:0):r===t?i=(n-e)/o+2:r===n&&(i=(e-t)/o+4),i/=6,[i,c,u]}function Ad(e,t,n){let r,s,o;if(t===0)r=s=o=n;else{const i=function(m,h,f){return f<0&&(f+=1),f>1&&(f-=1),f<.16666666666666666?m+(h-m)*6*f:f<.5?h:f<.6666666666666666?m+(h-m)*(.6666666666666666-f)*6:m},c=n<.5?n*(1+t):n+t-n*t,u=2*n-c;r=i(u,c,e+1/3),s=i(u,c,e),o=i(u,c,e-1/3)}return[Math.round(r*255),Math.round(s*255),Math.round(o*255)]}function ln(e,t,n){const[r,s,o]=vd(e),[i,c,u]=yd(r,s,o),d=Math.max(0,Math.min(1,u*t)),m=Math.max(0,Math.min(1,c*n)),[h,f,g]=Ad(i,m,d);return Sd([Math.round(h),Math.round(f),Math.round(g)])}function Td(e,t="light"){return{extraDark:ln(e,.6,1.2),dark:ln(e,.85,1.1),main:e,light:ln(e,t==="dark"?1.1:1.5,t==="dark"?.95:.9),extraLight:ln(e,t==="dark"?1.2:1.75,t==="dark"?.9:.8)}}function br(e){const t=vi(e),n=149,r=+`0x${t[1]}${t[2]}`,s=+`0x${t[3]}${t[4]}`,o=+`0x${t[5]}${t[6]}`;return r*.299+s*.587+o*.114>n?qt.BLACK:qt.WHITE}function Id(e,t,n,r,s){return{base:{primary:t,primaryContrastContent:n,background:e.background50,headerBackground:e.background50,modalContentBackground:e.background50},messageInput:{text:e.onlight.textHighEmphasis,placeholderText:e.onlight.textLowEmphasis,background:e.background100},messageIncoming:{text:s,background:r},messageOutgoing:{text:n,background:t},csat:{background:e.background100},conversation:{headerProfileSkeleton:e.background100},memoryDialog:{titleText:e.onlight.textHighEmphasis,markdownBodyText:e.onlight.textLowEmphasis,markdownLinkText:e.onlight.textHighEmphasis,positiveBackground:e.onlight.textHighEmphasis,positiveText:e.ondark.textHighEmphasis,positiveBorderColor:"transparent",negativeBackground:"transparent",negativeText:e.onlight.textHighEmphasis,negativeBorderColor:"transparent"}}}const xd=(e,t,n,r,s)=>({base:{primary:t,primaryContrastContent:n,background:e.background600,headerBackground:e.background500,modalContentBackground:e.background500},messageInput:{text:e.ondark.textHighEmphasis,placeholderText:e.ondark.textLowEmphasis,background:e.background400},messageIncoming:{text:s,background:r},messageOutgoing:{text:n,background:t},csat:{background:e.background400},conversation:{headerProfileSkeleton:e.background400},memoryDialog:{titleText:e.ondark.textHighEmphasis,markdownBodyText:e.ondark.textLowEmphasis,markdownLinkText:e.ondark.textHighEmphasis,positiveBackground:e.ondark.textHighEmphasis,positiveText:e.onlight.textHighEmphasis,positiveBorderColor:"transparent",negativeBackground:"transparent",negativeText:e.ondark.textHighEmphasis,negativeBorderColor:"transparent"}}),un={primary:{extraDark:"#491389",dark:"#6211c8",main:"#742ddd",light:"#c2a9fa",extraLight:"#dbd1ff"},secondary:{extraDark:"#066858",dark:"#027d69",main:"#259c72",light:"#69c085",extraLight:"#a8e2ab"},error:{extraDark:"#9d091e",dark:"#bf0711",main:"#de360b",light:"#f66161",extraLight:"#fdaaaa"},information:{extraDark:"#241389",dark:"#362ca9",main:"#4a48cd",light:"#a9bbfa",extraLight:"#d1dbff"},background700:"#000000",background600:"#161616",background500:"#2c2c2c",background400:"#393939",background300:"#bdbdbd",background200:"#e0e0e0",background100:"#eeeeee",background50:"#ffffff",onlight:{textHighEmphasis:"rgba(0, 0, 0, 1)",textMidEmphasis:"rgba(0, 0, 0, 0.75)",textLowEmphasis:"rgba(0, 0, 0, 0.55)",textDisabled:"rgba(0, 0, 0, 0.12)"},ondark:{textHighEmphasis:"rgba(255, 255, 255, 1)",textMidEmphasis:"rgba(255, 255, 255, 0.75)",textLowEmphasis:"rgba(255, 255, 255, 0.58)",textDisabled:"rgba(255, 255, 255, 0.12)"},overlay:{dark:"rgba(0, 0, 0, 0.55)",light:"rgba(22, 22, 22, 0.32)"}},Jn={h1:{fontSize:18,fontWeight:700},h2:{fontSize:16,fontWeight:700},subtitle1:{fontSize:16,fontWeight:500},subtitle2:{fontSize:16,fontWeight:400},body1:{fontSize:16,fontWeight:400},body2:{fontSize:14,fontWeight:500},body3:{fontSize:14,fontWeight:400},button:{fontSize:14,fontWeight:700},caption1:{fontSize:12,fontWeight:700},caption2:{fontSize:12,fontWeight:400},caption3:{fontSize:11,fontWeight:700},caption4:{fontSize:11,fontWeight:400}};function Ns(e){const t=Rd(e),n=Md(e,t),r=kd(n,e.colors,e.selectedTheme),s=Od(e);return{selectedTheme:e.selectedTheme,palette:t,colors:r,aiAgentColorVariables:{primary_color:r.base.primary,primary_contrast_color:r.base.primaryContrastContent,bot_message_bg_color:r.messageIncoming.background,bot_message_bg_contrast_color:r.messageIncoming.text},typography:s}}function Rd({selectedTheme:e,palette:t,primary:n}){const r=t!=null&&t.primary?t.primary:n?n===un.primary.main?un.primary:Td(n,e):un.primary;return{...un,primary:r,...t}}function Md({selectedTheme:e,primaryContrast:t,botMessageBackground:n,botMessageBackgroundContrast:r},s){const o=s.primary.main,i=t??br(o),c=n??qt.DEFAULT_BOT_MSG_BG,u=r??br(c);return(e==="light"?Id:xd)(s,o,i,c,u)}function wd(e,t,n){return typeof e=="string"?e:e[t]??n}function kd(e,t,n){var i;if(!t||Object.keys(t).length===0)return e;const r={...e},s=r,o=e;for(const c of Object.keys(t)){const u=t[c];if(u){s[c]={...s[c]};for(const[d,m]of Object.entries(u))if(m!==void 0){const h=((i=o[c])==null?void 0:i[d])??"";s[c][d]=wd(m,n,h)}}}return r}function Ld(e,t,n){const r={...e};return n.forEach(s=>{const o=t[s];o!=null&&(r[s]=o)}),r}function Od({typography:e}){if(!e)return Jn;const t={...Jn};return Object.keys(e).forEach(n=>{const r=e[n];if(r&&typeof r=="object"){const s=Jn[n],o=["fontSize","fontWeight","fontFamily","lineHeight"];t[n]=Ld(s,r,o)}}),t}const{Provider:Nd,useContext:Yr}=ve("AIAgentTheme");function Dd({logger:e,palette:t,typography:n,colors:r,appearance:s,children:o}){const i=l.useRef(null),[c,u]=l.useState(()=>Ns({selectedTheme:(s==null?void 0:s.theme)??"light",palette:t,typography:n,colors:r,primary:s==null?void 0:s.primaryColor,botMessageBackground:s==null?void 0:s.botMessageBackgroundColor})),d=l.useCallback((m,h)=>{h&&(i.current=h);const f=(s==null?void 0:s.theme)??m,g=i.current?i.current.themes[f]:null,p={primary:s==null?void 0:s.primaryColor,primaryContrast:void 0,botMessageBackground:s==null?void 0:s.botMessageBackgroundColor,botMessageBackgroundContrast:void 0};!p.primary&&(g!=null&&g.primary_color)&&(p.primary=g.primary_color,p.primaryContrast=g.primary_contrast_color),!p.botMessageBackground&&(g!=null&&g.bot_message_bg_color)&&(p.botMessageBackground=g.bot_message_bg_color,p.botMessageBackgroundContrast=g.bot_message_bg_contrast_color);const v=Ns({selectedTheme:f,palette:t,typography:n,colors:r,...p});u(v),e==null||e.info("theme.update:",f)},[s==null?void 0:s.theme,s==null?void 0:s.primaryColor,s==null?void 0:s.botMessageBackgroundColor,t,n,r,e]);return l.useEffect(()=>{(s!=null&&s.theme||s!=null&&s.primaryColor||s!=null&&s.botMessageBackgroundColor)&&d(c.selectedTheme)},[s==null?void 0:s.theme,s==null?void 0:s.primaryColor,s==null?void 0:s.botMessageBackgroundColor]),a.createElement(Nd,{value:{theme:c,updateTheme:d}},o)}const Qn=25*1024*1024,Ds=1,$s=new Set(["image/png","image/jpeg","image/jpg"]),Ps=new Set(["application/pdf"]),$d={off:"off",always:"always",handed_off_only:"handed_off_only"},Pd=()=>{const[e,t]=l.useState(()=>({maxAttachmentCount:Ds,attachmentMode:"handed_off_only",defaultUploadSizeLimit:Qn,uploadSizeLimitPerType:new Map,supportedImageMimeTypes:$s,supportedFileMimeTypes:Ps})),n=l.useCallback(({active_channel:s,upload_restriction:o})=>{t({maxAttachmentCount:(o==null?void 0:o.max_attachment_count)??Ds,attachmentMode:$d[s.attachment_mode]??"handed_off_only",defaultUploadSizeLimit:(o==null?void 0:o.default_upload_size_limit)??Qn,uploadSizeLimitPerType:new Map(Object.entries((o==null?void 0:o.upload_size_limit_per_type)??[])),supportedImageMimeTypes:new Set((o==null?void 0:o.supported_image_mime_types)??$s),supportedFileMimeTypes:new Set((o==null?void 0:o.supported_file_mime_types)??Ps)})},[]),r=l.useCallback(s=>{const{channel:o,uploadSizeLimit:i=Qn}=s,c=(d=!0)=>o!=null&&o.isAIAgent?d?ct(o):!1:!0,u=d=>{if(c())return e.defaultUploadSizeLimit??i;const m=e.defaultUploadSizeLimit??i,h=e.uploadSizeLimitPerType.get(d)??m;return Math.min(m,h)};return{maxAttachmentCount:e.maxAttachmentCount,isEnabled:()=>{if(c(!1))return!0;switch(e.attachmentMode){case"off":return!1;case"always":return!0;case"handed_off_only":return ct(o);default:return!0}},get supportedMimeTypes(){return c()?[fr]:[...e.supportedImageMimeTypes,...e.supportedFileMimeTypes]},isSupportedMimeType:d=>c()?!0:e.supportedImageMimeTypes.has(d)||e.supportedFileMimeTypes.has(d),getUploadSizeLimit:u,getUploadSizeLimitInMB:d=>u(d)/(1024*1024)}},[e]);return{updateBaseAttachmentRules:n,createAttachmentRules:r}},Fs=(...e)=>{const[t,n,r]=e;if(e.length===1&&typeof t=="object"&&t!==null)return{type:"active",context:t};if(e.length===3&&typeof t=="string"&&typeof n=="string"&&typeof r=="object"&&r!==null)return{type:"specific",aiAgentId:t,channelUrl:n,context:r};throw new Error("Invalid arguments: expected (context) or (aiAgentId, channelUrl, context)")},$t=e=>({...e,context:e.context??{}}),{Provider:Fd,useContext:ht}=ve("AIAgentMessengerSession"),Ud=l.forwardRef(function({userSessionInfo:e,children:t},n){const{_aiAgentSDK:r,chatSDK:s,aiAgentId:o,logger:i}=ye(),{updateTheme:c}=Yr(),[u,d]=l.useState(void 0),[m,h]=l.useState(void 0),[f,g]=l.useState(null),[p,v]=l.useState(null),[S,C]=l.useState(null),[A,y]=l.useState(null),[T,I]=l.useState(null),{updateBaseAttachmentRules:N,createAttachmentRules:O}=Pd();l.useEffect(()=>{const D=r.onMessengerSettingsUpdated(({settings:G})=>{const{appearance:H,bot:q,launcher:J,memory:K}=G;c(H.selected_theme,H),C(pu(q)),y(_u(J)),I(K?Cr(K):null),N(G)}),Q=r.onActiveChannelUpdated(({channelUrl:G,status:H,conversationStatus:q})=>{h({url:G,status:H,conversationStatus:q})}),re=r.onAuthTokenRefreshed(()=>{var H;const G=(H=r.session)==null?void 0:H.userSession.authToken;G&&v(q=>q?{...q,authToken:G}:null)});return()=>{D(),Q(),re()}},[r,c,N]);const k=l.useCallback(async()=>{try{const D=await r.authenticate(e),Q=r.session;return g(Q.sdkUser),v(Q.userSession),h(Q.activeChannel),d(void 0),D}catch(D){throw g(null),v(null),h(void 0),d(D),D}},[r,e]),R=l.useCallback(async()=>{await r.deauthenticate(),g(null),h(void 0),v(null),C(null),y(null),I(null)},[r]),F=l.useCallback(async()=>{if(!r.session){if(p)return i.debug("agentMessengerSession.refreshActiveChannel: stale call after deauthenticate, skipping"),"";throw i.error("agentMessengerSession.refreshActiveChannel: userSession is not ready"),new Error("userSession is not ready")}return r.session.userSession.userId!==(p==null?void 0:p.userId)?(i.debug("agentMessengerSession.refreshActiveChannel: stale call from previous session, skipping"),r.session.activeChannel.url):(h(void 0),await r.refreshActiveChannel())},[r,i,p]);return l.useImperativeHandle(n,()=>{const D=async()=>{if(!m)throw new Error("No active conversation. Please start a conversation first.");return await s.groupChannel.getChannel(m.url)};return{activeChannel:m,chatSDK:s,authenticate:k,deauthenticate:R,submitCPAAuthorizationCodes:r.submitCPAAuthorizationCodes,updateContext:async(...Q)=>{const re=Fs(...Q);if(re.type==="active"){const q=await(await D()).updateContext(o,re.context);return $t(q)}const G=await s.aiAgent.updateContext(re.aiAgentId,re.channelUrl,re.context);return $t(G)},patchContext:async(...Q)=>{const re=Fs(...Q);if(re.type==="active"){const q=await(await D()).patchContext(o,re.context);return $t(q)}const G=await s.aiAgent.patchContext(re.aiAgentId,re.channelUrl,re.context);return $t(G)},getContextObject:async()=>{const re=await(await D()).getContextObject(o);return $t(re)},requestNudgeMessage:Q=>r.requestNudgeMessage(Q)}},[k,R,m,s,o,i,r]),a.createElement(Fd,{value:{sdkUser:f,userSessionInfo:e,userSession:p,activeChannel:m,setActiveChannel:h,refreshActiveChannel:F,createConversation:r.createConversation,searchConversation:r.searchConversation,submitCPAAuthorizationCodes:r.submitCPAAuthorizationCodes,connectionError:u,aiAgentInfo:S,launcherInfo:A,memoryInfo:T,authenticate:k,deauthenticate:R,createAttachmentRules:O}},t)}),Bd={ai_responding:"not_ready",conversation_closed:"ready",form_active:"ready",handoff_pending:"ready",reconnecting:"not_ready",steward:"ready",suggested_replies:"ready",system:"ready",unavailable:"not_ready"},Hd=e=>e.disabled?Bd[e.disabledBy]==="ready":!0,Gd=e=>{var n,r,s,o,i;if(e.isUserMessage())return"text";const t=e.isFileMessage()?e.type:((r=(n=e.fileInfoList)==null?void 0:n[0])==null?void 0:r.mimeType)??((i=(o=(s=e.messageParams)==null?void 0:s.fileInfoList)==null?void 0:o[0])==null?void 0:i.mimeType);return t&&We(t)?"file_image":t&&jt(t)?"file_video":t&&Lc(t)?"file_audio":"file_document"};let Us=0;const zd=e=>(Us+=1,`${e??"unknown"}:${Us}`),At=(e,t)=>e===void 0||t===e,Si=(e,t)=>{!t.error&&t.messages.length>0&&e.conversationNotInteractiveTimeout.markHistoryLoaded("success",t.channelUrl)},yi=(e,t)=>{t.error?e.conversationNotInteractiveTimeout.markHistoryLoaded("failed",t.channelUrl):e.conversationNotInteractiveTimeout.markHistoryLoaded(t.messages.length>0?"success":"verified_empty",t.channelUrl)},Vd=(e,t)=>{Si(e,t)},qd=(e,t)=>{yi(e,t)},Kd=(e,t,n)=>{var o;if(!nt(e,n))return;const{hasResponseMetadata:r,...s}=Zo(e.data);r&&(t.typingIndicatorAbsentTimeout.markAIResponseStarted({channelUrl:e.channelUrl,userMessageId:s.userMessageId}),t.userPerceivedResponseTime.markAIResponseRaw({messageId:e.messageId,channelUrl:e.channelUrl,aiResponse:s}),t.streamStalled.markRawProgress({messageId:e.messageId,channelUrl:e.channelUrl,textLength:((o=e.message)==null?void 0:o.length)??0,aiResponse:s}))},Bs=(e,t)=>{t.streamStalled.clearMessage(e.messageId),t.userPerceivedResponseTime.clearMessage(e.messageId);const n=tt(e)?e.reqId:void 0;n&&(t.messagePendingStuck.disappear({requestId:n}),t.userPerceivedResponseTime.cancelTurn(n),t.typingIndicatorAbsentTimeout.cancelTurn(n))},er=(e,t)=>{t&&(e.conversationNotInteractiveTimeout.clearChannel(t),e.recoveryNotInteractiveTimeout.clearChannel(t),e.messagePendingStuck.clearChannel(t),e.userPerceivedResponseTime.clearChannel(t),e.typingIndicatorAbsentTimeout.clearChannel(t),e.streamStalled.clearChannel(t))},Yd=({activeChannelUrl:e,statsTrackers:t})=>{const{chatSDK:n}=ye(),{aiAgentInfo:r}=ht(),s=l.useRef(!1),o=r==null?void 0:r.userId;pt(!!e&&!!o?n:void 0,{onTypingStatusUpdated(c){if(c.url!==e)return;const u=c.getTypingUsers().some(m=>m.userId===o),d=s.current;u&&!d?t.typingIndicatorAbsentTimeout.markTypingStarted(c.url):!u&&d&&t.typingIndicatorAbsentTimeout.markTypingEnded(c.url),s.current=u}}),l.useEffect(()=>{s.current=!1},[e,o])},Wd=({enabled:e=!0,requestedChannelUrl:t,statsTrackers:n})=>{const r=l.useRef(void 0);l.useLayoutEffect(()=>{const s=r.current;if(!e){s&&(er(n,s),r.current=void 0);return}s&&s!==t&&(er(n,s),r.current=void 0),t&&s!==t&&(n.conversationNotInteractiveTimeout.start({channelUrl:t}),r.current=t)},[e,t,n]),l.useLayoutEffect(()=>()=>{const s=r.current;s&&(er(n,s),r.current=void 0)},[n])},jd=({aiAgentUserId:e,statsEnabled:t=!0,requestedChannelUrl:n,statsTrackers:r})=>{const s=l.useRef(null),o=l.useRef(null),i=l.useRef(!1),c=l.useRef(0),u=l.useRef(0),d=l.useRef(t),m=l.useMemo(()=>c.current+1,[n]);l.useLayoutEffect(()=>(i.current=!0,c.current=m,()=>{i.current=!1,c.current+=1}),[m]);const h=l.useCallback(g=>i.current&&c.current===g,[]);l.useLayoutEffect(()=>{u.current+=1,s.current=null,o.current=null},[n]),l.useLayoutEffect(()=>{const g=d.current;d.current=t,!(g||!t)&&(s.current&&(s.current.tracked=!1),o.current&&(o.current.tracked=!1))},[t]);const f=l.useCallback(g=>g.lifecycleGeneration===u.current&&At(n,g.channelUrl),[n]);return l.useEffect(()=>{if(!t)return;const g=s.current;g&&f(g)&&(g.tracked||(Si(r,g),g.tracked=!0));const p=o.current;p&&f(p)&&(p.tracked||(yi(r,p),p.tracked=!0))},[t,f,r]),l.useMemo(()=>({onCollectionEvent:g=>{if(h(m)&&At(n,g.channelUrl)){if(g.kind==="messagesDeleted"){g.messages.forEach(p=>Bs(p,r));return}t&&g.messages.forEach(p=>Kd(p,r,e))}},onCacheResult:(g,p,v)=>{if(!h(m)||!At(n,v))return;const S={error:g,messages:p,channelUrl:v,lifecycleGeneration:u.current,tracked:!1};s.current=S,t&&(Vd(r,S),S.tracked=!0)},onApiResult:(g,p,v)=>{if(!h(m)||!At(n,v))return;const S={error:g,messages:p,channelUrl:v,lifecycleGeneration:u.current,tracked:!1};o.current=S,t&&(qd(r,S),S.tracked=!0)},onLocalMessageDeleted:g=>{h(m)&&At(n,g.channelUrl)&&Bs(g,r)}}),[e,m,t,h,n,r])},Xd=({enabled:e=!0,channelUrl:t,initialized:n,inputReady:r,renderedSignal:s,statsTrackers:o})=>{const i=l.useRef(!1),c=l.useRef(0);l.useEffect(()=>{c.current+=1,i.current=!1},[t,e]),l.useEffect(()=>{e&&(o.recoveryNotInteractiveTimeout.setInputEnabled(r,t),r&&o.conversationNotInteractiveTimeout.markInputReady(t))},[t,e,r,o]),l.useEffect(()=>{if(!e||!n||i.current)return;const u=c.current,d=setTimeout(()=>{c.current===u&&(o.conversationNotInteractiveTimeout.markRendered(t),i.current=!0)});return()=>clearTimeout(d)},[t,e,n,s,o])},Zd=({channelUrl:e,enabled:t=!0,statsTrackers:n})=>{const r=l.useRef(!1),s=l.useRef(e),o=l.useRef(t),i=l.useRef(0);return l.useLayoutEffect(()=>(r.current=!0,s.current=e,o.current=t,i.current+=1,()=>{r.current=!1,i.current+=1}),[e,t]),l.useCallback(async(c,u,d={})=>{if(!r.current||!o.current)return c(v=>u==null?void 0:u(v),()=>{});let m;const h=i.current,f=s.current,g=()=>r.current&&o.current&&i.current===h&&s.current===f,p=v=>g()&&At(f,v);try{const v=await c(S=>{if(!p(S.channelUrl)){u==null||u(S);return}m=S.reqId,n.messagePendingStuck.start({requestId:S.reqId,channelUrl:S.channelUrl,messageType:Gd(S),tracksUploadProgress:d.tracksUploadProgress??!1}),u==null||u(S)},S=>{!g()||m!==S||n.messagePendingStuck.markUploadProgress(S)});return m&&(g()?n.messagePendingStuck.resolve({requestId:m}):n.messagePendingStuck.disappear({requestId:m})),v}catch(v){throw m&&(g()?n.messagePendingStuck.resolve({requestId:m}):n.messagePendingStuck.disappear({requestId:m})),v}},[n])},Jd=({channelUrl:e,enabled:t=!0,statsTrackers:n})=>{const r=l.useRef(!1),s=l.useRef(e),o=l.useRef(t),i=l.useRef(0);return l.useLayoutEffect(()=>(r.current=!0,s.current=e,o.current=t,i.current+=1,()=>{r.current=!1,i.current+=1}),[e,t]),l.useCallback(async c=>{if(!r.current||!o.current)return c(()=>{});const u=i.current,d=s.current,m=()=>r.current&&o.current&&i.current===u&&s.current===d;let h=zd(d);n.userPerceivedResponseTime.startTurn({requestId:h,channelUrl:d}),n.typingIndicatorAbsentTimeout.startTurn({requestId:h,channelUrl:d});try{const f=await c(g=>{m()&&(n.userPerceivedResponseTime.replaceTurnRequestId(h,g),n.typingIndicatorAbsentTimeout.replaceTurnRequestId(h,g),h=g)});return m()?(n.userPerceivedResponseTime.markUserMessageAck({requestId:h,messageId:f.messageId}),n.typingIndicatorAbsentTimeout.markUserMessageAck({requestId:h,messageId:f.messageId})):(n.userPerceivedResponseTime.cancelTurn(h),n.typingIndicatorAbsentTimeout.cancelTurn(h)),f}catch(f){throw n.userPerceivedResponseTime.cancelTurn(h),n.typingIndicatorAbsentTimeout.cancelTurn(h),f}},[e,n])},Qd=({requestedChannelUrl:e,activeChannelUrl:t,statsEnabled:n=!0,statsTrackers:r})=>{const{aiAgentInfo:s}=ht();Yd({activeChannelUrl:t,statsTrackers:r}),Wd({enabled:n,requestedChannelUrl:e,statsTrackers:r});const o=jd({aiAgentUserId:s==null?void 0:s.userId,statsEnabled:n,requestedChannelUrl:e,statsTrackers:r}),i=Zd({channelUrl:t,enabled:n,statsTrackers:r}),c=Jd({channelUrl:t,enabled:n,statsTrackers:r});return l.useMemo(()=>({messageCallbacks:o,runWithPendingStuckStats:i,runWithUserTurnStats:c}),[o,i,c])},Lt=()=>ye()._aiAgentSDK.statsTrackers,em=({enabled:e=!0,channelUrl:t}={})=>{const{conversationInitialRender:n}=Lt(),{watchBackgrounded:r}=ye()._aiAgentSDK,s=l.useRef(null);return l.useLayoutEffect(()=>{n.setVisible(e)},[e,n]),l.useLayoutEffect(()=>{if(!t)return;const o=n.startSpan(t);return s.current=o,()=>{o.cancel(),s.current===o&&(s.current=null)}},[t,n]),l.useMemo(()=>({onGetChannelStart:o=>{var i;(i=s.current)==null||i.onGetChannelStart(o)},onGetChannelComplete:({channelUrl:o,conversationId:i})=>{var c;(c=s.current)==null||c.onGetChannelComplete(o,i)},onGetChannelError:({channelUrl:o,error:i})=>{var c;(c=s.current)==null||c.onGetChannelError(o,i)},onCollectionInitializeStart:()=>{var o;(o=s.current)==null||o.onGetMessagesStart()},onCollectionCacheResult:(o,i)=>{var c;(c=s.current)==null||c.onGetMessagesCacheComplete(i,o)},onCollectionApiResult:(o,i)=>{const c=s.current;if(!c)return;c.onGetMessagesComplete(i,o);const u=r==null?void 0:r();Ie(()=>{u!=null&&u()?c.onRenderDiscarded():c.onRendered()})}}),[r])},Jt=(e,t)=>{const n=l.useId(),r=l.useRef(t);l.useLayoutEffect(()=>{r.current=t}),l.useLayoutEffect(()=>{const s=new Ce.ConnectionHandler({onDisconnected:o=>{var i,c;return(c=(i=r.current).onDisconnected)==null?void 0:c.call(i,o)},onConnected:o=>{var i,c;return(c=(i=r.current).onConnected)==null?void 0:c.call(i,o)},onReconnectStarted:()=>{var o,i;return(i=(o=r.current).onReconnectStarted)==null?void 0:i.call(o)},onReconnectSucceeded:()=>{var o,i;return(i=(o=r.current).onReconnectSucceeded)==null?void 0:i.call(o)},onReconnectFailed:()=>{var o,i;return(i=(o=r.current).onReconnectFailed)==null?void 0:i.call(o)},onConnectionLost:()=>{var o,i;return(i=(o=r.current).onConnectionLost)==null?void 0:i.call(o)},onConnectionDelayed:o=>{var i,c;return(c=(i=r.current).onConnectionDelayed)==null?void 0:c.call(i,o)}});return e.addConnectionHandler(n,s),()=>{e.removeConnectionHandler(n)}},[e,n])},Hs=()=>{const e=l.useRef(0);return{next:()=>(e.current+=1,e.current),current:()=>e.current,invalidate:()=>{e.current+=1},isCurrent:t=>t===e.current}};function tm(e,t={}){const{shouldInitializeConversation:n=!0,initialUserMessage:r}=t,{chatSDK:s,logger:o,aiAgentId:i,_aiAgentSDK:c}=ye(),{sdkUser:u}=ht(),d=Hs(),m=Hs(),h=Nn(),[f,g]=l.useState(void 0),[p,v]=l.useState(void 0),[S,C]=l.useState(!1),A=ce(T=>{if(n&&T.isAIAgent&&!T.conversation){const I=m.next();C(!0),c.initConversationIfNeeded(T,{initialUserMessage:r}).finally(()=>{m.isCurrent(I)&&C(!1)})}});async function y(){var I,N,O,k,R,F;const T=d.next();if(!u){o.debug("useChannel.getChannel: no sdk user, skip fetching channel");return}if(o.debug("useChannel.getChannel: start"),g(void 0),v(void 0),m.invalidate(),C(!1),e){(I=t.onFetchStart)==null||I.call(t,e);try{o.debug("useChannel.getChannel: get channel",e);const D=await s.groupChannel.getChannel(e);if(!d.isCurrent(T))return;A(D),g(D),(O=t.onFetchSuccess)==null||O.call(t,{channelUrl:D.url,conversationId:(N=D.conversation)==null?void 0:N.id}),D.url===((k=c.session)==null?void 0:k.activeChannel.url)&&c.session._updateActiveChannel({url:D.url,status:De(D)?"closed":"open",conversationStatus:(R=D.conversation)==null?void 0:R.status}),o.debug("useChannel.getChannel: fetched channel",D)}catch(D){if(!d.isCurrent(T))return;(F=t.onFetchError)==null||F.call(t,{channelUrl:e,error:D}),D instanceof Ce.SendbirdError&&v(D),o.error("useChannel.getChannel: error",D)}}}return l.useEffect(()=>(y(),()=>{d.invalidate()}),[s,u,e,i]),l.useEffect(()=>{n&&f&&A(f)},[n]),Jt(s,{async onReconnectSucceeded(){var N;if(!f){p&&await y();return}const T=d.current(),I=await f.refresh();!d.isCurrent(T)||f.url!==e||((N=t.onReconnectSucceeded)==null||N.call(t,f.url),A(I),g(I))}}),pt(s,{onChannelChanged:T=>{T.isGroupChannel()&&T.url===e&&(o.debug("useChannel.onChannelChanged: channel changed",T.url),g(T),h())}}),{channel:f,channelFetchError:p,getChannel:y,isInitializingConversation:S}}const nm=e=>{const t=e==null?void 0:e.lastMessage,n=t==null?void 0:t.extendedMessagePayload,r=n==null?void 0:n.user_input_disabled_by;if(!r)return;const s=Wt(n);switch(r){case"suggested_replies":return s.hasSuggestedReplies?r:void 0;case"steward":return s.hasSteward?r:void 0;case"system":return r;default:return}},rm=e=>{var o;const t=e==null?void 0:e.lastMessage;if(!t||!e)return!1;const n=t.extendedMessagePayload,r=Wt(n).hasActiveForm,s=e.isAIAgent&&!!((o=e.conversation)!=null&&o.handedOverAt);return r&&!s},sm=()=>{const{chatSDK:e,networkStateAdapter:t}=ye(),[n,r]=l.useState(()=>t?t.isOnline()?"connected":"reconnecting":"connected");return Jt(e,{onConnected:()=>r("connected"),onDisconnected:()=>r("disconnected"),onReconnectStarted:()=>r("reconnecting"),onReconnectSucceeded:()=>r("connected"),onReconnectFailed:()=>r("disconnected"),onConnectionLost:()=>r("reconnecting")}),l.useEffect(()=>{if(t)return t.subscribe(s=>{if(!s){r("reconnecting");return}r(o=>o==="reconnecting"&&e.connectionState===Ce.ConnectionState.OPEN?"connected":o)})},[t,e]),n},om=3e4,im=({shouldApply:e,lastMessage:t,isBlockedWhileAIResponding:n,currentUserId:r})=>{const[s,o]=l.useState(!1),i=l.useRef(null),c=t&&nt(t,r)?t.createdAt:0;return l.useEffect(()=>{const u=()=>{i.current&&(clearTimeout(i.current),i.current=null),o(!1)},d=f=>{i.current&&clearTimeout(i.current),o(!0),i.current=setTimeout(()=>{o(!1),i.current=null},f)},m=Date.now()-c,h=om-m;return n||h<=0?u():d(h),()=>{i.current&&clearTimeout(i.current)}},[n,c]),s&&e},Ai=e=>{const{chatSDK:t}=ye(),[n,r]=l.useState([]);return pt(t,{onTypingStatusUpdated(s){if(s.url===(e==null?void 0:e.url)){const o=s.getTypingUsers();r(o)}}}),n},am=({channel:e,lastMessage:t,aiAgentUserId:n,isStreamAnimating:r})=>{const[s,o]=l.useState(!1),i=Ai(e);return l.useEffect(()=>{if(!t)return;const c=i.some(d=>d.userId===n),u=nt(t,n)&&(we.isStreaming(t)||r);o(u||c)},[i,t,n,r]),s},cm=({channel:e,messages:t,isStreamAnimating:n,isInitializingConversation:r})=>{const{aiAgentInfo:s,userSession:o}=ht(),i=sm(),c=am({channel:e,lastMessage:gr(t,[Le.SendingStatus.SUCCEEDED]),aiAgentUserId:(s==null?void 0:s.userId)??"",isStreamAnimating:n}),u=im({shouldApply:!!(e!=null&&e.isAIAgent)&&!ct(e),isBlockedWhileAIResponding:c,lastMessage:gr(t,[Le.SendingStatus.PENDING,Le.SendingStatus.SUCCEEDED]),currentUserId:(o==null?void 0:o.userId)??""}),d=h=>h===""?{disabled:!1,disabledBy:"",focusPolicy:"auto"}:h==="ai_responding"?{disabled:!0,disabledBy:h,focusPolicy:"preserve"}:{disabled:!0,disabledBy:h,focusPolicy:"release"};if(!e||i==="disconnected")return d("unavailable");if(i==="reconnecting")return d("reconnecting");if(De(e))return d("conversation_closed");if(ll(e))return d("handoff_pending");if(rm(e))return d("form_active");const m=nm(e);return d(m||(c||u||r?"ai_responding":""))},lm=()=>{const[e,t]=l.useState(new Set),[n,r]=l.useState(new Map),s=l.useCallback(m=>{t(h=>{if(h.has(m))return h;const f=new Set(h);return f.add(m),f})},[]),o=l.useCallback(m=>{t(h=>{if(!h.has(m))return h;const f=new Set(h);return f.delete(m),f})},[]),i=l.useCallback((m,h)=>{r(f=>{const g=new Map(f);return g.set(m,h),g})},[]),c=l.useCallback(m=>{r(h=>{if(!h.has(m))return h;const f=new Map(h);return f.delete(m),f})},[]),u=l.useCallback(m=>n.has(m),[n]),d=n.values().next().value;return{isAnimating:e.size>0,start:s,stop:o,isHolding:u,heldTypingInfo:d,holdStart:i,holdStop:c}},{Provider:um}=ve("AIAgentConversation");function dm({children:e,channelUrl:t,onChannelDeleted:n,onMessagesReceived:r,onMessagesUpdated:s,onConversationStatusChanged:o,onConversationClosedViaDispatcher:i,onBeforeSendMessage:c,onAfterSendMessage:u=me,shouldMarkAsRead:d=!0,conversationStatsEnabled:m=!0,shouldInitializeConversation:h=!0,initialUserMessage:f,shouldCountNewMessages:g=()=>!1,sortComparator:p}){var $,M;const v=()=>d&&(R==null?void 0:R.markAsRead()),{_aiAgentSDK:S,chatSDK:C,logger:A,dispatcher:y}=ye(),T=Lt(),I={channelUrl:t,enabled:m},N=Cd({...I,statsTracker:T.conversationNotInteractiveTimeout}),O=bd({...I,scheduleForegroundTask:S.scheduleForegroundTask,statsTracker:T.recoveryNotInteractiveTimeout}),k=em(I),{channel:R,channelFetchError:F,getChannel:D,isInitializingConversation:Q}=tm(t,{shouldInitializeConversation:h,initialUserMessage:f,onFetchStart:x=>{N.onFetchStart(x),k.onGetChannelStart(x)},onFetchSuccess:x=>{N.onFetchSuccess(x),k.onGetChannelComplete(x)},onFetchError:x=>{N.onFetchError(x),k.onGetChannelError(x)},onReconnectSucceeded:O.onReconnectSucceeded}),re=R==null?void 0:R.url,G=Qd({requestedChannelUrl:t,activeChannelUrl:re,statsEnabled:m,statsTrackers:T}),H=_d(C,R,{replyType:Le.ReplyType.ONLY_REPLY_TO_CHANNEL,shouldCountNewMessages:g,logger:A,markAsRead:v,sortComparator:p,onChannelDeleted:n,onMessagesReceived:x=>r==null?void 0:r(x),onMessagesUpdated:x=>s==null?void 0:s(x),onCollectionInitializeStart:()=>{k.onCollectionInitializeStart()},onApiResult:(x,L,P)=>{k.onCollectionApiResult(x,P),G.messageCallbacks.onApiResult(x,L,P)},onCacheResult:(x,L,P)=>{k.onCollectionCacheResult(x,P),G.messageCallbacks.onCacheResult(x,L,P)},onCollectionEvent:x=>{G.messageCallbacks.onCollectionEvent(x),bi.publish(x)},onLocalMessageDeleted:x=>{G.messageCallbacks.onLocalMessageDeleted(x)},onOutgoingMessageStatusChanged:x=>{R&&S.liveMetricManager.track({type:"outgoingMessage",channel:R,message:x})}}),q=lm(),J=cm({channel:R,messages:H.messages,isStreamAnimating:q.isAnimating,isInitializingConversation:Q});Xd({enabled:m,channelUrl:re,initialized:H.initialized,inputReady:Hd(J),renderedSignal:H.messages,statsTrackers:T}),l.useEffect(()=>{v()},[d,R]);const K=($=R==null?void 0:R.conversation)==null?void 0:$.status;l.useEffect(()=>{K&&(o==null||o(K))},[K,o]),l.useEffect(()=>{const x=async L=>{const P=typeof(L==null?void 0:L.channelUrl)=="string";R&&P&&L.channelUrl!==R.url||(A.debug("conversation.dispatcher: try to close conversation",R),R!=null&&R.conversation&&R.conversation.status===he.ConversationStatus.OPEN&&(await R.closeConversation(),i==null||i()))};return y.subscribe(Be.ConversationClose,x),()=>{y.unsubscribe(Be.ConversationClose,x)}},[y,R,A,(M=R==null?void 0:R.conversation)==null?void 0:M.status,i]);const z=ce(()=>H.loadPrevious()),Y=ce(()=>H.loadNext()),W=ce(async x=>{try{await H.deleteMessage(x)}finally{x.sendingStatus!=="succeeded"&&G.messageCallbacks.onLocalMessageDeleted(x)}}),V=ce(x=>x.isUserMessage()?G.runWithUserTurnStats(L=>G.runWithPendingStuckStats(P=>H.resendMessage(x,X=>{L(X.reqId),P(X)}),void 0)):G.runWithPendingStuckStats((L,P)=>H.resendMessage(x,L,P),void 0,{tracksUploadProgress:x.isMultipleFilesMessage()})),ee=ce(()=>H.resetNewMessages()),w=ce(async x=>{var P;if(((P=R==null?void 0:R.conversation)==null?void 0:P.status)===he.ConversationStatus.CLOSED)throw new Error("Conversation is closed");c&&(x=await c(x));const L=await G.runWithUserTurnStats(X=>G.runWithPendingStuckStats(se=>H.sendUserMessage(x,Z=>{X(Z.reqId),se(Z)}),u));return u==null||u(L),L}),_e=ce(async x=>{var P;if(((P=R==null?void 0:R.conversation)==null?void 0:P.status)===he.ConversationStatus.CLOSED)throw new Error("Conversation is closed");c&&(x=await c(x));const L=await G.runWithPendingStuckStats(X=>H.sendFileMessage(x,X),u);return u==null||u(L),L}),Re=ce(async x=>{var P;if(((P=R==null?void 0:R.conversation)==null?void 0:P.status)===he.ConversationStatus.CLOSED)throw new Error("Conversation is closed");c&&(x=await c(x));const L=await G.runWithPendingStuckStats((X,se)=>H.sendMultipleFilesMessage(x,X,se),u,{tracksUploadProgress:!0});return u==null||u(L),L}),Te={_statsEnabled:m,conversation:(R==null?void 0:R.conversation)??void 0,actions:{setUserMemoryState:S.setUserMemoryState},channelSource:{channel:R,error:F,refetch:()=>D(),closeConversation:async()=>{De(R)||await(R==null?void 0:R.closeConversation())}},messageSource:{messages:H.messages,newMessages:H.newMessages,initialized:H.initialized,loadPrevious:z,loadNext:Y,deleteMessage:W,resendMessage:V,resetNewMessages:ee,sendUserMessage:w,sendFileMessage:_e,sendMultipleFilesMessage:Re},state:{streamAnimation:q,input:J}};return a.createElement(um,{value:Te},e)}function mm(e,t,n){var C,A,y,T,I,N,O,k,R,F;const[r,s]=l.useState(!1),[o,i]=l.useState(null),[c,u]=l.useState([]),[d,m]=l.useState(null),h=l.useRef(!1),f=ce(()=>{var D;return(D=n==null?void 0:n.onListRequestStart)==null?void 0:D.call(n)}),g=ce(D=>{var Q;return(Q=n==null?void 0:n.onListRequestComplete)==null?void 0:Q.call(n,D)}),p=l.useCallback(async D=>{f();try{await D.loadMore(),g()}catch(Q){throw g(Q),Q}},[f,g]),v=l.useCallback(async()=>{if(!h.current&&e.currentUser){h.current=!0,s(!1),i(null),u([]);try{d==null||d.dispose();const D=new si(e,t);D.setConversationListCollectionHandler({onChannelsAdded:()=>{u(D.channels)},onChannelsUpdated:()=>{u(D.channels)},onChannelsDeleted:()=>{u(D.channels)}}),await p(D),u(D.channels),m(D),i(null)}catch(D){m(null),i(D)}finally{s(!0),h.current=!1}}},[e,e.currentUser,(C=t.filter)==null?void 0:C.aiAgentChannelFilter,(y=(A=t.filter)==null?void 0:A.aiAgentConversationStatusFilter)==null?void 0:y.join(),(I=(T=t.filter)==null?void 0:T.aiAgentIds)==null?void 0:I.join(),(N=t.filter)==null?void 0:N.deskChannelFilter,(k=(O=t.filter)==null?void 0:O.pinnedChannelUrls)==null?void 0:k.join(),(R=t.filter)==null?void 0:R.copilotConversationOnly,(F=t.filter)==null?void 0:F.copilotSupportChannelUrl,t.limit,p]),S=l.useCallback(async()=>{if(d)try{await d.loadMore(),u(d.channels)}catch(D){i(D)}},[d]);return Jt(e,{onConnected:()=>v()}),l.useEffect(()=>{v()},[v]),l.useEffect(()=>()=>{h.current=!1,d==null||d.dispose()},[d]),{initialized:r,error:o,channels:c,loadMore:S}}const Ti=e=>{var s;const{aiAgentId:t,queryParams:n}=ye(),r=(s=n==null?void 0:n.conversationListParams)==null?void 0:s.filter;return{aiAgentIds:[t],aiAgentConversationStatusFilter:[he.ConversationStatus.CLOSED,he.ConversationStatus.OPEN],...r,...e}},hm=({enabled:e=!0}={})=>{const{conversationListInitialRender:t}=Lt(),{watchBackgrounded:n}=ye()._aiAgentSDK,r=l.useRef(null);return l.useLayoutEffect(()=>{t.setVisible(e)},[e,t]),l.useLayoutEffect(()=>{const s=t.startSpan();return r.current=s,()=>{s.cancel(),r.current===s&&(r.current=null)}},[t]),l.useMemo(()=>({onListRequestStart:()=>{var s;(s=r.current)==null||s.onListRequestStart()},onListRequestComplete:s=>{const o=r.current;if(!o||(o.onListRequestComplete(s),s))return;const i=n==null?void 0:n();Ie(()=>{i!=null&&i()?o.onRenderDiscarded():o.onRendered()})}}),[n])},{Provider:fm}=ve("AIAgentConversationList");function gm({conversationListLimit:e,conversationListFilter:t,conversationListStatsEnabled:n=!0,children:r}){var h;const{chatSDK:s,queryParams:o}=ye(),i=e??((h=o==null?void 0:o.conversationListParams)==null?void 0:h.limit),c=Ti(t),u=hm({enabled:n}),d=mm(s,{limit:i,filter:c},{onListRequestStart:()=>{u.onListRequestStart()},onListRequestComplete:f=>{u.onListRequestComplete(f)}}),m={listSource:{initialized:d.initialized,error:d.error??void 0,channels:d.channels,loadMore:()=>d.loadMore()}};return a.createElement(fm,{value:m},r)}function pm(e){let t="pending",n=e.then(r=>{t="resolved",n=r}).catch(r=>{t="rejected",n=r});return{get value(){if(t==="resolved")return n;throw n}}}const{Provider:_m,useContext:Em}=ve("MessageTemplateFetching");function Cm({children:e,internalVariables:t}){const n=l.useRef({}),r=l.useRef({}),[s,o]=l.useState({}),i=l.useCallback((d,m)=>{o(h=>({...h,[d]:{fetching:!1,error:!1,...h[d],...m}}))},[]),c=l.useCallback(async({onRequestTemplate:d,onGetCachedTemplate:m,templateKey:h,suspense:f=!1})=>{const g=m(h);if(g)return g;const p=r.current[h];if(p)return p;f||i(h,{fetching:!0});const v=d(h).catch(S=>{throw f||i(h,{error:!0}),S}).finally(()=>{f||i(h,{fetching:!1}),delete r.current[h]});return r.current[h]=v,v},[i]),u={internalVariables:t,fetchTemplate:c,suspend:(d,m)=>{if(n.current[d])return n.current[d];const h=pm(m());return n.current[d]=h,h},getIsFetching:d=>{var m;return((m=s[d])==null?void 0:m.fetching)??!1},getHasError:d=>{var m;return((m=s[d])==null?void 0:m.error)??!1}};return a.createElement(_m,{value:u},e)}const bm="remove_powered_by",Wr=(e,t)=>{var s,o;const{chatSDK:n}=ye(),{aiAgentInfo:r}=ht();if(e==="handoff-button"){const i=!!((s=t==null?void 0:t.conversation)!=null&&s.handoff);return!!(t!=null&&t.isAIAgent)&&!!(r!=null&&r.showHandoffButton)&&i&&$r(t)}if(e==="special-notice")return!!(t!=null&&t.isAIAgent)&&!!(r!=null&&r.specialNoticeEnabled)&&!!(r!=null&&r.specialNotice);if(e==="powered-by"){const i=(o=n==null?void 0:n.appInfo)==null?void 0:o.applicationAttributes;return l.useMemo(()=>!(Array.isArray(i)&&i.includes(bm)),[i])}throw new Error("Unsupported feature")},vm={required:"This question is required",minLength:e=>`Minimum ${e} characters required`,maxLength:e=>`Maximum ${e} characters allowed`,min:e=>`Minimum value is ${e}`,max:e=>`Maximum value is ${e}`,minSelect:e=>`Select at least ${e} options`,maxSelect:e=>`Select at most ${e} options`,regex:"Invalid format",invalidSelection:"Invalid selection"},Sm={getValueOrDefault:e=>e.value??e.default_value??null,validate:(e,t,n)=>{const r=t;if(e.required&&(!r||r.trim()===""))return{isValid:!1,error:n.required};if(!r)return{isValid:!0};const{rules:s}=e;if(s){if(s.min_length!==void 0&&r.length<s.min_length)return{isValid:!1,error:typeof n.minLength=="function"?n.minLength(s.min_length):n.minLength};if(s.max_length!==void 0&&r.length>s.max_length)return{isValid:!1,error:typeof n.maxLength=="function"?n.maxLength(s.max_length):n.maxLength};if(s.regex&&!new RegExp(s.regex).test(r))return{isValid:!1,error:n.regex}}return{isValid:!0}}},ym={getValueOrDefault:e=>e.value??e.default_value??null,validate:(e,t,n)=>{const r=t;if(e.required&&r===null)return{isValid:!1,error:n.required};if(r===null)return{isValid:!0};const{rules:s}=e;if(s){if(s.min!==void 0&&r<s.min)return{isValid:!1,error:typeof n.min=="function"?n.min(s.min):n.min};if(s.max!==void 0&&r>s.max)return{isValid:!1,error:typeof n.max=="function"?n.max(s.max):n.max}}return{isValid:!0}}},Am={getValueOrDefault:e=>e.value??e.default_value??null,validate:(e,t,n)=>{const r=t;return e.required&&!r?{isValid:!1,error:n.required}:r&&!e.options.includes(r)?{isValid:!1,error:n.invalidSelection}:{isValid:!0}}},Tm={getValueOrDefault:e=>e.values??e.default_values??null,validate:(e,t,n)=>{const r=t;if(e.required&&(!r||r.length===0))return{isValid:!1,error:n.required};if(!r||r.length===0)return{isValid:!0};if(r.filter(i=>!e.options.includes(i)).length>0)return{isValid:!1,error:n.invalidSelection};const{rules:o}=e;if(o){if(o.min_select!==void 0&&r.length<o.min_select)return{isValid:!1,error:typeof n.minSelect=="function"?n.minSelect(o.min_select):n.minSelect};if(o.max_select!==void 0&&r.length>o.max_select)return{isValid:!1,error:typeof n.maxSelect=="function"?n.maxSelect(o.max_select):n.maxSelect}}return{isValid:!0}}},Im={text:Sm,number:ym,"single-select":Am,"multi-select":Tm},xm={getValueOrDefault:()=>null,validate:()=>({isValid:!1})};function Ii(e){return Im[e.type]||xm}function Gs(e){return Ii(e).getValueOrDefault(e)}function Rm(e,t,n={}){const r={...vm,...n};return Ii(e).validate(e,t,r)}const Mm=(e,t={})=>{const{labels:n={},onSubmit:r,onCancel:s}=t,[o,i]=l.useState({}),[c,u]=l.useState(()=>{const v={};return e.fields.forEach(S=>{v[S.key]=Gs(S)}),v}),d=l.useMemo(()=>e.submitted_at?"submitted":e.canceled_at?"canceled":"draft",[e.submitted_at,e.canceled_at]);l.useEffect(()=>{if(d==="submitted"||d==="canceled"){const v={};let S=!1;e.fields.forEach(C=>{const A=Gs(C);JSON.stringify(c[C.key])!==JSON.stringify(A)&&(S=!0),v[C.key]=A}),S&&u(v)}},[d]);const m=(v,S)=>{u(C=>({...C,[v]:S})),i(C=>({...C,[v]:void 0}))},h=e.fields.map(v=>{var A,y,T;const S=c[v.key]??null,C={key:v.key,label:v.label,error:o[v.key],required:v.required};return v.type==="text"?{...C,type:"text",layout:v.layout,value:S,...v.placeholder&&{placeholder:v.placeholder},...((A=v.rules)==null?void 0:A.max_length)&&{maxLength:v.rules.max_length}}:v.type==="number"?{...C,type:"number",layout:v.layout,value:S,...v.placeholder&&{placeholder:v.placeholder},...((y=v.rules)==null?void 0:y.max)&&{max:v.rules.max}}:v.type==="single-select"?{...C,type:"single-select",layout:v.layout,value:S,options:v.options}:v.type==="multi-select"?{...C,type:"multi-select",layout:v.layout,value:S,options:v.options,...((T=v.rules)==null?void 0:T.max_select)&&{maxSelect:v.rules.max_select}}:{...C,type:"unknown",layout:"default",value:null}});return{state:d,fields:h,getField:v=>h.find(S=>S.key===v),updateFieldValue:m,submit:async()=>{const v={};let S=!1;for(const C of e.fields){const A=c[C.key]??null,y=Rm(C,A,n);y.isValid||(v[C.key]=y.error,S=!0)}if(i(v),!S&&r){const C={};e.fields.forEach(A=>{C[A.key]=c[A.key]??null}),await r(C)}},cancel:async()=>{await(s==null?void 0:s())}}},wm=({isMessengerOpened:e,onConversationStarted:t})=>{const{_aiAgentSDK:n,aiAgentId:r,language:s,countryCode:o,context:i}=ye(),{createConversation:c,userSession:u}=ht(),[d,m]=l.useState(null),h=u==null?void 0:u.userId;l.useEffect(()=>{if(m(null),!(e||!h))return n.onNudgeMessageReceived(v=>m(S=>({seq:((S==null?void 0:S.seq)??0)+1,response:v})))},[n,e,h]);const f=()=>m(null),g=l.useRef(!1),p=async()=>{var S;if(!d||g.current)return;g.current=!0,m(null);const v=n.session;try{const C=await c({aiAgentId:r,language:s,country:o,context:i});if(n.session!==v)return;(S=n.session)==null||S._updateActiveChannel({url:C,status:"open"}),t({channelUrl:C,initialUserMessage:d.response.callbackUserMessage})}finally{g.current=!1}};return{nudgeMessage:e?null:(d==null?void 0:d.response)??null,nudgeMessageKey:(d==null?void 0:d.seq)??0,dismissNudgeMessage:f,startNudgeConversation:p}},km=e=>{const{chatSDK:t,handlers:n,logger:r}=ye(),{aiAgentInfo:s}=ht(),o=l.useRef(new Set),i=l.useRef(new Set),c=(m,h)=>{if(!(n!=null&&n.onCustomEvent)||!(s!=null&&s.userId)||!nt(m,s.userId))return;const f=m.messageId;if(we.isStreaming(m)){i.current.add(f);return}h==="updated"&&!i.current.has(f)||(r.debug("useCustomEventForMessageReceive: bot-message-received",m),n.onCustomEvent({type:"bot-message-received",data:{message:m}}),i.current.delete(f))},u=l.useCallback(m=>{if(n!=null&&n.onCustomEvent&&m.isAdminMessage()&&m.customType==="user_action_required"&&!o.current.has(m.messageId)){const h=jo(m.data);Array.isArray(h.history)&&h.history.length===0&&(r.debug("useCustomEventForMessageReceive: user_action_required",h),n.onCustomEvent({type:"user-action-requested",data:h}),o.current.add(m.messageId))}},[n,r]),d=(m,h,f)=>{m.url===e&&(c(h,f),u(h))};return pt(t,{onMessageReceived:(m,h)=>d(m,h,"received"),onMessageUpdated:(m,h)=>d(m,h,"updated")}),{checkForUserActionRequired:u}},Lm=e=>{if(e==null||typeof e!="object")return;const t="thinking_message"in e?e.thinking_message:void 0;return typeof t=="string"&&t?t:void 0},xi=e=>{const{aiAgentInfo:t}=ht(),n=Ai(e);if(De(e))return null;const r=n[0];if(!r)return null;const s=r.userId===(t==null?void 0:t.userId),o=s?Lm(r.metaData):void 0;return{user:s?t:r,isBot:s,thinkingMessage:o}},Om=250,Nm=(e,t)=>{var i;const[n,r]=l.useState(!1),s=l.useRef(e),o=l.useRef(void 0);return e!==null?(s.current=e,n||(o.current=t==null?void 0:t.messageId,r(!0))):n&&t!==void 0&&t.sender.userId===((i=s.current)==null?void 0:i.user.userId)&&t.messageId!==o.current&&r(!1),l.useEffect(()=>{if(!n||e!==null)return;const c=setTimeout(()=>r(!1),Om);return()=>clearTimeout(c)},[n,e!==null]),e??(n?s.current:null)},Dm=(e,t,{enabled:n=!0,idleMs:r=1e3}={})=>{const s=l.useRef(null),o=l.useRef(t),i=l.useRef(t),c=l.useRef(!1);o.current=t,l.useEffect(()=>{if(s.current&&(clearTimeout(s.current),s.current=null),!n||!e){(c.current?i.current:o.current)(!1),c.current=!1,i.current=o.current;return}c.current=!0,i.current=o.current,i.current(!0),s.current=setTimeout(()=>{s.current=null,i.current(!1),c.current=!1,i.current=o.current},r)},[n,r,e]),l.useEffect(()=>()=>{s.current&&(clearTimeout(s.current),s.current=null),(c.current?i.current:o.current)(!1),c.current=!1,i.current=o.current},[])},$m=(e=1e4)=>{const t=new Map;let n=e;return{shouldAnnounce:c=>{const u=Date.now(),d=t.get(c);return d!==void 0&&u-d<n?!1:(t.set(c,u),!0)},setInterval:c=>{n=c},reset:()=>{t.clear()}}},Pm=(e,t,n=1e4,r=!0)=>{const s=l.useRef(null),o=l.useRef(null),i=l.useRef(!1);s.current||(s.current=$m(n));const c=(e==null?void 0:e.nickname.trim())||null,u=(e==null?void 0:e.userId)??c;l.useEffect(()=>{var d;(d=s.current)==null||d.setInterval(n)},[n]),l.useEffect(()=>{var h;if(!r){i.current=!1,o.current=u;return}if(!u||!c){i.current=!1,o.current=null;return}const d=!i.current,m=o.current!==u;i.current=!0,o.current=u,!(!d&&!m)&&(h=s.current)!=null&&h.shouldAnnounce(u)&&t(c)},[u,c,r,t])},Fm=({csat:e,csatPayload:t,isRenderableCSAT:n,isExpiredNow:r,announceStatus:s,onSubmittedAnnounced:o})=>{const i=(t==null?void 0:t.csat_submitted_label)??"",c=l.useRef(n&&typeof e=="number"),u=l.useRef(n&&r);l.useEffect(()=>{n&&i&&(typeof e!="number"||c.current||(c.current=!0,s&&(s({event:"csatSubmitted",submittedLabel:i}),o==null||o())))},[s,e,n,o,i]),l.useEffect(()=>{n&&r&&(u.current||(u.current=!0,s==null||s({event:"csatExpired"})))},[s,r,n])},jr=({channel:e,userSession:t,aiAgentInfo:n})=>{if(!t||!n||!e)return{fallbackIcon:void 0,url:void 0,title:""};const r=ii(e,t.userId),s={ai(o){return{fallbackIcon:o,url:n.profileUrl,title:n.nickname}},human(o){return{fallbackIcon:o,url:r==null?void 0:r.profileUrl,title:(r==null?void 0:r.nickname)||n.nickname}},channel(o){return{fallbackIcon:o,url:e==null?void 0:e.coverUrl,title:(e==null?void 0:e.name)??""}}};return e.isAIAgent?ct(e)?s.human("agent"):s.ai("delight"):e.isDesk?s.human("agent"):s.channel("user")},zs=e=>l.useReducer((t,n)=>({...t,...n}),e);var et=(e=>(e.AI_AGENT_CSAT_5="AI_AGENT_CSAT_5",e.AI_AGENT_CSAT_5_WITH_CRE="AI_AGENT_CSAT_5_WITH_CRE",e.HELPDESK_CSAT_5="HELPDESK_CSAT_5",e))(et||{});const Um=new Set(["free_text","single_choice"]),Bm=({csatPayload:e,type:t,initialCsat:n,initialCsatReason:r,initialIsResolved:s})=>{const[o,i]=zs({csatType:t,csat:n,csatReason:r,isResolved:s}),[c,u]=zs({followUpItem:!1}),d=l.useMemo(()=>{var S;const g=o.csat,p=typeof g=="number",v=(S=e.follow_up)==null?void 0:S.find(C=>p?C.scores.includes(g):C.always_visible??!1);if(Um.has(v==null?void 0:v.response_type))return v},[o.csat,e.follow_up]),m=(()=>{var g;if(typeof n=="number")return"submitted";if((t===et.AI_AGENT_CSAT_5||t===et.HELPDESK_CSAT_5)&&typeof o.csat=="number")return"submittable";if(t===et.AI_AGENT_CSAT_5_WITH_CRE){const p=typeof o.csat=="number",v=!((g=e.cre)!=null&&g.required)||typeof o.isResolved=="boolean";if(p&&v)return"submittable"}return"unsubmittable"})(),h=l.useCallback(()=>typeof o.csat>"u"?!1:d!=null&&d.required&&!o.csatReason?(u({followUpItem:!0}),!1):!0,[o,d,u]);return l.useEffect(()=>{r||(i({csatReason:""}),u({followUpItem:!1}))},[r,d,i,u]),{params:o,setParams:i,error:c,setError:u,followUpItem:d,state:m,validateParams:h,itemProps:{csatPayload:e,state:m,submitted:m==="submitted"}}},Hm=({csat:e,csatExpireAt:t,csatPayload:n,isSubmitInFlight:r=!1})=>{const s=!!n&&n.visibility&&!!et[n.type],o=!r&&typeof e!="number"&&ai(t),i=Nn();return l.useEffect(()=>{if(!s||typeof e=="number"||t==null||o)return;const c=t-Date.now();if(c<=0&&r)return;const u=setTimeout(i,Math.max(0,c));return()=>clearTimeout(u)},[i,e,t,o,s,r]),{isRenderableCSAT:s,isExpiredNow:o}},tr=5,Ut=250,Ri=50,Gm=1500,nr=e=>Math.max(0,e-Ri),_n=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():0,zm=(e,t)=>{const n=e&&t.length<=Ri,r=l.useRef(n&&t.length>0?t:null),[s,o]=l.useState(()=>!n),i=r.current!==null&&t!==r.current,c=!n||i;return l.useEffect(()=>{if(s)return;const u=()=>{r.current=null,o(!0)};if(c){u();return}if(r.current===null&&t.length>0&&(r.current=t),r.current===null)return;const d=setTimeout(u,Gm);return()=>clearTimeout(d)},[s,c,t]),!s&&!c},Vm=e=>e<1e3?{speed:tr*.5,chunkSize:2}:e<2e3?{speed:tr*.8,chunkSize:2}:{speed:tr*.6,chunkSize:3},En=(e,t)=>{let n=0;for(let r=t-1;r>=0&&e[r]==="\\";r--)n++;return n%2===1},Vs=(e,t,n,r)=>{let s=1,o=t;for(;o<e.length&&s>0;){if(En(e,o)){o++;continue}e[o]===n?s++:e[o]===r&&s--,o++}return s>0?-1:o},Mi=(e,{hideImages:t,hideLinks:n})=>{let r="",s=0,o=0;for(;s<e.length;){if(e[s]==="`"&&!En(e,s)){let h=1;for(;e[s+h]==="`";)h++;o===0?o=h:h===o&&(o=0),r+=e.slice(s,s+h),s+=h;continue}const i=e[s]==="!"&&e[s+1]==="["&&!En(e,s),c=e[s]==="["&&!En(e,s);if(o>0||!i&&!c){r+=e[s],s++;continue}if(i?!t:!n){const h=i?"![":"[";r+=h,s+=h.length;continue}const u=s,d=Vs(e,s+(i?2:1),"[","]");if(d===-1)return r;if(s=d,e[s]!=="("){r+=e.slice(u,s);continue}const m=Vs(e,s+1,"(",")");if(m===-1)return r;s=m,r+=e.slice(u,s)}return r},qm=({trackedRef:e,onVisibleTextProgress:t,onRenderedTextProgress:n})=>{const r=l.useRef(t),s=l.useRef(n),o=l.useRef(null),i=l.useRef({lastLength:0,lastReportedAt:0}).current,c=l.useRef({lastLength:0,lastReportedAt:0,lastCheckedAt:0}).current,u=l.useRef(null);l.useLayoutEffect(()=>{r.current=t,s.current=n});const d=l.useCallback(A=>{var y;(y=r.current)==null||y.call(r,A)},[]),m=l.useCallback(A=>{const y=e.initialEnabled&&(e.enabled||A<e.textLength),T=y&&e.deferImages,I=y&&e.deferLinks;return!T&&!I?A:Mi(e.text.slice(0,A),{hideImages:T,hideLinks:I}).length},[e]),h=l.useCallback((A,y,T=!1)=>{r.current&&(A<=c.lastLength||!T&&y-c.lastReportedAt<Ut||(c.lastLength=A,c.lastReportedAt=y,d(A)))},[d,c]),f=l.useCallback((A,y,T=!1)=>{if(!r.current)return;const I=Math.max(c.lastReportedAt,c.lastCheckedAt);!T&&y-I<Ut||(c.lastCheckedAt=y,h(m(A),y,!0))},[m,h,c]),g=l.useCallback((A,y,T=!1)=>{s.current&&(A<=i.lastLength||!T&&y-i.lastReportedAt<Ut||(i.lastLength=A,i.lastReportedAt=y,s.current(A)))},[i]),p=l.useCallback((A,y,T)=>{const I=A>=y,N=T-i.lastReportedAt>=Ut;if(!I&&!N)return;const O=m(A);g(O,T,I)},[m,i,g]),v=l.useCallback(()=>{c.lastLength=0,c.lastReportedAt=0,c.lastCheckedAt=0,i.lastLength=0,i.lastReportedAt=0},[i,c]),S=l.useCallback(A=>{r.current&&(o.current!==null&&A<=o.current||(o.current=A,d(A)))},[d]),C=l.useCallback(({displayedLength:A,streamTextLength:y})=>{const T=u.current;if(u.current={displayedLength:A,streamTextLength:y},!e.initialEnabled||!T||A>T.displayedLength||y<=T.streamTextLength)return;const I=_n();h(y,I,!0),g(y,I,!0)},[u,g,h,e]);return{resetProgress:v,reportVisibleTextProgress:f,reportRenderedTextProgress:p,reportNonStreamingVisibleTextProgress:S,reportMarkdownRevealProgress:C}},Km=e=>{const{text:t,enabled:n=!1,snapOnDisable:r=!1,deferredMarkdownElements:s=[],onAnimationStart:o,onAnimationProgress:i,onAnimationComplete:c,onAnimationHoldChange:u,onVisibleTextProgress:d,onRenderedTextProgress:m}=e,h=zm(n,t),f=s.includes("image"),g=s.includes("link"),[p,v]=l.useState(()=>n?h?0:nr(t.length):t.length),S=l.useRef(null),C=l.useRef({startTime:0,lastUpdate:0,lastProgressCall:0}).current,A=l.useRef({startCalled:!1,completeCalled:!1}).current,y=l.useRef({initialEnabled:n,textLength:t.length,enabled:n,text:t,deferImages:f,deferLinks:g,snapOnDisable:r,isGatingStreamingStart:h}).current,T=ce(()=>o==null?void 0:o()),I=ce(()=>i==null?void 0:i()),N=ce(()=>c==null?void 0:c()),O=ce(K=>u==null?void 0:u(K)),{resetProgress:k,reportVisibleTextProgress:R,reportRenderedTextProgress:F,reportNonStreamingVisibleTextProgress:D,reportMarkdownRevealProgress:Q}=qm({trackedRef:y,onVisibleTextProgress:d,onRenderedTextProgress:m}),re=n,G=p<t.length,H=y.initialEnabled&&(re||G);l.useLayoutEffect(()=>{y.textLength=t.length,y.enabled=n,y.text=t,y.deferImages=f,y.deferLinks=g,y.snapOnDisable=r,y.isGatingStreamingStart=h}),l.useLayoutEffect(()=>{if(y.initialEnabled){if(A.startCalled||(A.startCalled=!0,T()),!y.enabled&&y.snapOnDisable){v(t.length);const K=_n();R(t.length,K,!0),F(t.length,t.length,K);return}v(K=>t.length<K?t.length:K)}},[T,F,R,t]),l.useEffect(()=>{if(!y.initialEnabled)return;let K=h?0:nr(t.length),z=h;C.lastUpdate=0,C.startTime=0,C.lastProgressCall=0,k();const Y=W=>{C.lastUpdate===0&&(C.lastUpdate=W,C.startTime=W,C.lastProgressCall=W,K>0&&R(K,W,!0));const V=y.textLength;z&&!y.isGatingStreamingStart&&(K=nr(V),v(K),K>0&&R(K,W,!0),C.lastUpdate=W,z=!1),!y.enabled&&y.snapOnDisable&&K<V&&(K=V,v(K),R(K,W,!0),F(K,V,W));const ee=W-C.lastUpdate,w=W-C.startTime,{speed:_e,chunkSize:Re}=Vm(w),Te=_e*Re;!y.isGatingStreamingStart&&ee>=Te&&K<V&&(K=Math.min(K+Re,V),v(K),R(K,W,K>=V),F(K,V,W),C.lastUpdate=W),W-C.lastProgressCall>=Ut&&(C.lastProgressCall=W,I()),(K<V||y.enabled)&&(S.current=requestAnimationFrame(Y))};return S.current=requestAnimationFrame(Y),()=>{S.current&&cancelAnimationFrame(S.current),A.startCalled&&!A.completeCalled&&(A.completeCalled=!0,N())}},[N,I,F,R,k]),l.useEffect(()=>{y.initialEnabled&&(n||t.length>0)||(D(t.length),F(t.length,t.length,_n()))},[n,m,d,D,F,t.length,y]),l.useEffect(()=>{const K=y.initialEnabled&&A.startCalled,z=!n,Y=p>=t.length;K&&z&&Y&&!A.completeCalled&&(A.completeCalled=!0,N())},[n,p,N,t.length]);const q=l.useMemo(()=>{let K=t;y.initialEnabled&&(K=h?"":t.slice(0,p));const z=H&&f,Y=H&&g;return!z&&!Y?K:Mi(K,{hideImages:z,hideLinks:Y})},[t,p,f,g,H,h]);l.useEffect(()=>{!y.initialEnabled||H||R(p,_n(),!0)},[p,H,R]),l.useEffect(()=>{Q({displayedLength:p,streamTextLength:q.length})},[p,Q,q.length]);const J=q.length===0&&H;return l.useLayoutEffect(()=>(O(J),()=>O(!1)),[O,J]),{streamText:q,isAnimating:H,isHolding:J}},qs={visible:!1,remainingTime:0,showDescription:!1,targetTimeMs:null},Ym=e=>({visible:!0,remainingTime:e,showDescription:!0,targetTimeMs:Date.now()+e*1e3}),Wm=(e,t=Date.now())=>{if(!e.visible||e.targetTimeMs==null)return e;const n=Math.max(Math.ceil((e.targetTimeMs-t)/1e3),0);return n<=0?{...e,remainingTime:0,showDescription:!1,targetTimeMs:null}:e.remainingTime===n&&e.showDescription?e:{...e,remainingTime:n,showDescription:!0}},jm=()=>{const{chatSDK:e}=ye(),[t,n]=l.useState(qs),r=()=>n(qs);return Jt(e,{onConnectionDelayed:s=>{s>0?n(Ym(s)):r()},onReconnectSucceeded:r,onConnected:r}),l.useEffect(()=>{if(!t.visible||!t.showDescription||t.targetTimeMs==null)return;const s=setTimeout(()=>{n(o=>Wm(o))},1e3);return()=>clearTimeout(s)},[t.visible,t.showDescription,t.targetTimeMs,t.remainingTime]),{visible:t.visible,remainingTime:t.remainingTime,showDescription:t.showDescription}},Xm=e=>{const t=Math.floor(e/60),n=e%60;return`${String(t).padStart(2,"0")}:${String(n).padStart(2,"0")}`},Zm=(e,t)=>{if(!t)return{beforeText:e,highlightedText:"",afterText:""};const n=e.indexOf(t);return n<0?{beforeText:e,highlightedText:"",afterText:""}:{beforeText:e.slice(0,n),highlightedText:t,afterText:e.slice(n+t.length)}},Jm=({enabled:e=!0}={})=>{const t=Lt();return l.useCallback(({message:n,isBotMessage:r,aiAgentUserId:s})=>{if(!e)return;const o=n.messageId,i=we.isStreaming(n),c=Wt(n.extendedMessagePayload),u=c.hasMessageTemplate,d=c.hasForm,m=r&&n.isUserMessage()&&!i&&!Oc(n)&&!we.isWelcomeMessage(n,s),h=i||t.streamStalled.hasPendingStream(o),f=t.userPerceivedResponseTime.hasPendingAIResponse(o);if(!h&&!f&&!m&&!u&&!d)return;let g=!1,p=!1;const v={};return(f||m)&&(v.onVisibleTextProgress=()=>{f&&!g&&(g=t.userPerceivedResponseTime.markAIResponseVisible(o)),m&&!p&&(p=!0,t.renderedContentUnusable.commit({messageId:o,contentKind:"text",errorDomain:"empty_render"}))}),h&&(v.onRenderedTextProgress=S=>{t.streamStalled.markRenderedProgress({messageId:o,displayedLength:S})}),u&&(v.onMessageTemplateError=S=>{t.renderedContentUnusable.commit({messageId:o,contentKind:"template",errorDomain:"template_error",error:S})}),d&&(v.onFormRenderError=S=>{t.renderedContentUnusable.commit({messageId:o,contentKind:"form",errorDomain:"form_error",error:S})}),v},[e,t])},Qm=e=>{const t=l.useRef(!1);l.useEffect(()=>{t.current||e!=null&&e.onVisibleTextProgress&&(t.current=!0,e.onVisibleTextProgress(0))},[e])},rr=5e3,eh=({channelUrl:e,enabled:t=!0,isInitiallyBackgrounded:n,isForegrounded:r,subscribeToForegroundState:s})=>{const o=Lt(),i=l.useRef(t),c=l.useRef(n),u=l.useRef(t&&n()?performance.now()-rr:null),d=l.useRef(!1);i.current=t,c.current=n;const m=l.useCallback((h=r())=>{if(!i.current){d.current=!1;return}if(!h){d.current=!1;return}if(u.current===null){d.current=!1;return}if(performance.now()-u.current<rr){u.current=null,d.current=!1;return}if(!e){d.current=!0;return}u.current=null,d.current=!1,o.recoveryNotInteractiveTimeout.start("foreground_resume",e)},[e,r,o]);l.useEffect(()=>{t||(u.current=null,d.current=!1,e&&o.recoveryNotInteractiveTimeout.cancelPending(e))},[e,t,o]),l.useEffect(()=>{if(!t)return;d.current&&!!e&&r()&&m()},[e,t,r,m]),l.useEffect(()=>{if(t)return c.current()?u.current??(u.current=performance.now()-rr):u.current=null,s(h=>{if(h==="backgrounded"){u.current??(u.current=performance.now()),d.current=!1,e&&o.recoveryNotInteractiveTimeout.cancelPending(e);return}m(!0)})},[e,t,m,o,s])},th=e=>{const{conversationInitialRender:t,conversationListInitialRender:n}=Lt();l.useLayoutEffect(()=>{t.setPresentMethod(e),n.setPresentMethod(e)},[t,n,e])},nh=(e,{enabled:t=!0,opened:n=!1,filter:r}={})=>{var u,d,m;const[s,o]=l.useState(!1),i=l.useRef(0),c=()=>{if(!t)return;const h=++i.current;e.aiAgent.getUnreadMessageCount(r).then(f=>{h===i.current&&o(f.total>0)}).catch(()=>{})};return l.useEffect(()=>{if(!t){o(!1),i.current++;return}e.connectionState===Ce.ConnectionState.OPEN&&c()},[t,e,r==null?void 0:r.aiAgentChannelFilter,(u=r==null?void 0:r.aiAgentConversationStatusFilter)==null?void 0:u.join(),(d=r==null?void 0:r.aiAgentIds)==null?void 0:d.join(),r==null?void 0:r.deskChannelFilter,(m=r==null?void 0:r.pinnedChannelUrls)==null?void 0:m.join(),r==null?void 0:r.copilotConversationOnly,r==null?void 0:r.copilotSupportChannelUrl]),l.useEffect(()=>{n&&(o(!1),i.current++)},[n]),Jt(e,{onConnected:c,onReconnectSucceeded:c}),s},Rt=e=>e.replace(/\s+/g," ").trim(),rh="Code block",wi=e=>`A11Y_INLINE_CODE_${e}`,ki=e=>{let t="",n=e;for(;;){const r=n.match(/^([ \t]{0,3}>\s?)(.*)$/);if(r){t+=r[1],n=r[2];continue}break}return{blockquotePrefix:t,content:n}},Li=e=>{const t=e.match(/^([ \t]{0,3}[-+*]\s+)(.*)$/);if(t)return{content:t[2],hasListPrefix:!0};const n=e.match(/^([ \t]{0,3}\d+[.)]\s+)(.*)$/);return n?{content:n[2],hasListPrefix:!0}:{content:e,hasListPrefix:!1}},sh=e=>{const{blockquotePrefix:t,content:n}=ki(e),{content:r}=Li(n),s=r.match(/^[ \t]{0,3}([`~]{3,})(.*)$/);if(!s)return;const o=s[1],i=s[2],c=o[0];if(!(c!=="`"&&c!=="~"||!o.split("").every(u=>u===c))&&!(c==="`"&&i.includes("`")))return{char:c,blockquotePrefix:t,length:o.length}},oh=(e,t)=>{const{blockquotePrefix:n,content:r}=ki(e);if(n!==t.blockquotePrefix)return!1;const{content:s,hasListPrefix:o}=Li(r);if(o)return!1;const i=s.match(/^[ \t]{0,3}([`~]{3,})[ \t]*$/);if(!i)return!1;const c=i[1];return c[0]===t.char&&c.length>=t.length&&c.split("").every(u=>u===t.char)},ih=(e,t,n)=>{let r=n;for(;r<e.length;){const s=e[r];if(s==="\\"&&r+1<e.length){r+=2;continue}if(s===t)return r;r+=1}return-1},ah=(e,t)=>{let n=1,r=t;for(;r<e.length;){const s=e[r];if(s==="\\"&&r+1<e.length){r+=2;continue}if(s==="["){n+=1,r+=1;continue}if(s==="]"&&(n-=1,n===0))return r;r+=1}return-1},ch=(e,t)=>{let n=t,r=1,s,o=!1,i=!1;for(;n<e.length&&r>0;){const c=e[n];if(c==="\\"&&n+1<e.length){n+=2;continue}if(s){c===s&&(s=void 0),n+=1;continue}if(r===1&&o&&/\s/.test(c)){i=!0,n+=1;continue}if(r===1&&i&&(c==='"'||c==="'")){s=c,n+=1;continue}if(c==="("){r+=1,o=!0,n+=1;continue}if(c===")"){r-=1,n+=1;continue}/\s/.test(c)||(o=!0),n+=1}return r===0?n:-1},lh=e=>{let t=0,n="";for(;t<e.length;){const r=ih(e,"[",t);if(r===-1){n+=e.slice(t);break}const s=ah(e,r+1);if(s===-1){n+=e.slice(t);break}if(r>0&&e[r-1]==="!"&&Tn(e,r-1)){n+=e.slice(t,s+1),t=s+1;continue}if(e[s+1]!=="("){n+=e.slice(t,s+1),t=s+1;continue}const o=r>0&&e[r-1]==="!"&&!Tn(e,r-1)?r-1:r;n+=e.slice(t,o);const i=e.slice(r+1,s),c=ch(e,s+2);if(c===-1){n+=e.slice(o);break}n+=i,t=c}return n},Oi=(e,t,n)=>{if(!/^\d+$/.test(t))return!1;const r=e.slice(-1);return/\d/.test(r)&&/\d/.test(n)},uh=e=>e.replace(/(^|[^*\\])\*\*([^\s*](?:[\s\S]*?[^\s*])?)\*\*(?!\*)/g,(t,n,r,s,o)=>{const i=o[s+t.length]??"";return Oi(n,r,i)?t:`${n}${r}`}),dh=e=>e.replace(/(^|[^_\\])__([^\s_](?:[\s\S]*?[^\s_])?)__(?!_)/g,"$1$2"),mh=e=>e.replace(/(^|[^~\\])~~([^\s~](?:[\s\S]*?[^\s~])?)~~(?!~)/g,"$1$2"),hh=e=>{let t=e;return t=t.replace(/(^|[^*\\])\*([^\s*](?:[\s\S]*?[^\s*])?)\*(?!\*)/g,(n,r,s,o,i)=>{const c=i[o+n.length]??"";return Oi(r,s,c)?n:`${r}${s}`}),t=t.replace(/(^|[\s([{"'])_([^_\s](?:[\s\S]*?[^_\s])?)_(?=$|[\s)\]}"'.,!?:;])/g,"$1$2"),t},fh=e=>e.replace(/\\([\\`*_[\]()#+.!~|-])/g,"$1"),gh=e=>{let t=e;return t=t.replace(/^\s{0,3}#{1,6}\s+/gm,""),t=t.replace(/^\s{0,3}>\s?/gm,""),t=t.replace(/^\s{0,3}(?!([-*_])(?:\s*\1){2,}\s*$)[-*+]\s+/gm,""),t=t.replace(/^\s{0,3}\d+[.)]\s+/gm,""),t},Ks=e=>{const t=e.trim();if(!t.includes("|"))return!1;const n=t.split("|").map(r=>r.trim()).filter(Boolean);return n.length===0?!1:n.every(r=>/^:?-{3,}:?$/.test(r))},Ys=e=>{const t=[];let n="",r=!1;for(const o of e.trim()){if(r){n+=o==="|"?"|":`\\${o}`,r=!1;continue}if(o==="\\"){r=!0;continue}if(o==="|"){const i=n.trim();i&&t.push(i),n="";continue}n+=o}r&&(n+="\\");const s=n.trim();return s&&t.push(s),t},ph=e=>{const t=e.split(`
|
|
2
|
+
`),n=[];let r=0;for(;r<t.length;){const s=t[r],o=t[r+1],i=Ys(s);if(i.length>0&&o&&Ks(o)){for(n.push(i.join(" ")),r+=2;r<t.length;){const c=t[r],u=Ys(c);if(u.length===0||Ks(c))break;n.push(u.join(" ")),r+=1}continue}n.push(s),r+=1}return n.join(`
|
|
3
|
+
`)},_h=e=>e.replace(/^\s{0,3}(?:(?:-\s*){3,}|(?:\*\s*){3,}|(?:_\s*){3,})$/gm,""),Eh=(e,t)=>{const n=e.split(`
|
|
4
|
+
`),r=[];let s=0;for(;s<n.length;){const o=n[s],i=sh(o);if(!i){r.push(o),s+=1;continue}let c=-1;for(let u=s+1;u<n.length;u++)if(oh(n[u],i)){c=u;break}if(c===-1){r.push(o),s+=1;continue}r.push(` ${t} `),s=c+1}return r.join(`
|
|
5
|
+
`)},Tn=(e,t)=>{let n=0,r=t-1;for(;r>=0&&e[r]==="\\";)n+=1,r-=1;return n%2===1},Ch=e=>{const t=[];let n=0,r="";for(;n<e.length;){const s=e[n];if(s!=="`"||Tn(e,n)){r+=s,n+=1;continue}let o=n;for(;o<e.length&&e[o]==="`";)o+=1;const i=e.slice(n,o);let c=o,u=!1;for(;c<e.length&&e[c]!==`
|
|
6
|
+
`;){if(e[c]==="`"&&!Tn(e,c)&&e.startsWith(i,c)){const d=e.slice(o,c),m=t.push(d)-1;r+=wi(m),n=c+i.length,u=!0;break}c+=1}u||(r+=i,n=o)}return{text:r,inlineCodes:t}},Ni=(e,{codeBlockPlaceholder:t=rh}={})=>{const n=e==null?void 0:e.replace(/\r\n?/g,`
|
|
7
|
+
`);if(!n)return;const r=[];let s=n;s=Eh(s,t),s=gh(s);const o=Ch(s);s=o.text,r.push(...o.inlineCodes),s=lh(s),s=uh(s),s=dh(s),s=mh(s),s=hh(s),s=ph(s),s=_h(s),s=fh(s);for(let c=0;c<r.length;c++)s=s.replaceAll(wi(c),r[c]);return Rt(s)||void 0},bh=(e,t)=>{var s;const n=((s=e.name)==null?void 0:s.trim())||"",r=e.mimeType??"";return We(r)?t.image:jt(r)?t.video:ti({name:n,mimeType:r})?t.pdf(n):t.document(n)},In=e=>(e==null?void 0:e.trim())||"",vh=e=>(e?Rt(e):void 0)||void 0,Ws=30,Sh=e=>e.length>Ws?`${e.slice(0,Ws)}…`:e,yh=({agent:e,status:t,lastMessage:n,time:r,unreadCount:s},o)=>{const i=Sh(Rt(n)),c=[t,i].filter(Boolean).join(", ");return o(Rt(e),Rt(c),r,s)},Di=e=>({text:In(e),format:"plain"}),Ah=e=>({text:In(e),format:"markdown"}),sr=({markdownText:e,plainText:t,comparisonText:n})=>{const r=In(e);return r&&r!==In(n)?Ah(r):Di(t)},zt=({sender:e,message:t,messageFormat:n="plain",time:r,codeBlockPlaceholder:s})=>{const o=[],i=n==="markdown"?Ni(t,{codeBlockPlaceholder:s}):vh(t);if(r&&o.push(r),e&&o.push(e),i&&o.push(i),o.length!==0)return o.join(", ")},$i=(e,t)=>Ni(e==null?void 0:e.trim(),t!==void 0?{codeBlockPlaceholder:t}:void 0),Th=(...e)=>Rt(e.filter(Boolean).join(", "))||void 0,js=(e,t,n,r)=>{if(!t||t===n)return e;const s=$i(t,r);return s?Th(e,s):e},Ih=(e,t)=>{var r,s,o,i;const n=(r=e.message)==null?void 0:r.trim();if(e.isFileMessage()){const c=((s=e.name)==null?void 0:s.trim())||"",u=bh({name:c,mimeType:e.type},t);return js(u,n,c,t.codeBlockPlaceholder)}if(e.isMultipleFilesMessage()){const c=e.fileInfoList??[],u=c.length;if(u===0)return;const d=((i=(o=c[0])==null?void 0:o.fileName)==null?void 0:i.trim())||"",h=c.every(f=>{var g;return(g=f.mimeType)==null?void 0:g.startsWith("image")})?t.receivedFilesImageCount(u):t.multipleFilesCount(u);return js(h,n,d,t.codeBlockPlaceholder)}return $i(n,t.codeBlockPlaceholder)},xh=(e,t={})=>{const{throttleMs:n=1e3,isSuppressed:r,maxOrderedQueueSize:s=10}=t,o=Math.max(1,s);let i=null;const c=[];let u=null,d=null,m=null,h=!1,f=0;const g=(k,R,F)=>({text:k,ignoreSuppression:R,queueOrder:f++,dedupeKey:F}),p=()=>{const k=c[0]??null,R=i;return k&&R?R.queueOrder<k.queueOrder?(i=null,R):c.shift()??null:k?c.shift()??null:R!==null?(i=null,R):null},v=()=>{for(;;){const k=p();if(!k)return null;if(!(!k.ignoreSuppression&&(r!=null&&r())))return k}},S=k=>{u=k.text,d=k.dedupeKey??null,h=!0,e(k.text),m=setTimeout(()=>{m=null,h=!1;const R=v();R&&S(R)},n)},C=k=>{u=k.text,d=k.dedupeKey??null,e(k.text)},A=(k,R,F,D)=>R!=null&&D!=null?R===D:R==null&&D==null?k!=null&&k===F:!1,y=(k,R,F)=>{if(!k||!R&&(r!=null&&r()))return;const D=F==null?void 0:F.dedupeKey;if(!(h&&A(k,D,u,d)))if(h){if(((F==null?void 0:F.mode)??"latestOnly")==="ordered"){const re=c[c.length-1];if(re&&A(k,D,re.text,re.dedupeKey))return;c.push(g(k,R,D)),c.length>o&&c.shift();return}i=g(k,R,D)}else i=null,S(g(k,R,D))};return{announce:(k,R)=>{y(k,!1,R)},announceIgnoringSuppression:(k,R)=>{y(k,!0,R)},flush:()=>{const k=[];let R=p();for(;R!==null;)k.push(R),R=p();if(m!==null&&(clearTimeout(m),m=null),h=!1,k.length!==0)for(const F of k)C(F)},destroy:()=>{m!==null&&(clearTimeout(m),m=null),i=null,c.length=0,u=null,d=null,h=!1}}},Rh=e=>{switch(e){case"newMessage":case"conversationClosed":case"csatDisplayed":case"csatSubmitted":case"csatExpired":return"ordered";default:return"latestOnly"}},Mh=(e,t)=>e.screen==="conversationList"?typeof e.conversationCount=="number"?t.screenConversationListWithCount(e.conversationCount):t.screenConversationListNoCount:[e.agentName?t.screenConversationWithAgent(e.agentName):t.screenConversation,e.isClosed?t.conversationClosed:null,e.isClosed&&e.hasCSAT?t.csatDisplayed:null,e.isEmpty?t.emptyState:null].filter(r=>!!r).join(". "),wh=(e,t)=>{switch(e.event){case"newMessage":return e.body!==void 0||e.time!==void 0?[t.newMessage(1),e.time,e.senderName,e.body].filter(r=>!!r).join(", "):e.senderName?t.newMessageFromSender(e.senderName,1):t.newMessage(1);case"typing":return t.typing(e.agentName??"");case"sendFailed":return t.sendFailed;case"agentConnected":return t.agentConnected(e.agentName??"");case"conversationClosed":return t.conversationClosed;case"csatDisplayed":return t.csatDisplayed;case"csatSubmitted":return e.submittedLabel;case"csatExpired":return t.csatExpired;case"emptyState":return t.emptyState;case"inputDisabled":return t.inputDisabled}},kh=(e,t)=>{switch(e.type){case"fileSizeExceeded":return t.fileSizeExceeded(e.maxSizeMB??25);case"sendFailed":return t.sendFailed;case"csatFormError":return t.csatFormError;case"generic":return e.message}},Lh=(e,t)=>!t||!tt(e)||e.sender.userId!==t?null:e.reqId||(e.messageId>0?String(e.messageId):null),Oh=(e,t)=>Me.isAdmin(e)?Me.isCSAT(e):"sender"in e?e.sender.userId!==t:!1,Nh=e=>"messageId"in e&&e.messageId>0?String(e.messageId):"reqId"in e&&typeof e.reqId=="string"&&e.reqId.length>0?e.reqId:null,Dh=e=>e===Ce.CollectionEventSource.EVENT_MESSAGE_RECEIVED||e===Ce.CollectionEventSource.EVENT_MESSAGE_UPDATED,$h=({isOpened:e,opensConversationList:t})=>e?t?"closeConversationList":"closeConversation":t?"openConversationList":"openConversation",Ph=(e,t)=>{switch(e){case"closeConversationList":return t.closeConversationList;case"closeConversation":return t.closeConversation;case"openConversationList":return t.openConversationList;case"openConversation":return t.openConversation}},Fh=(e,t)=>{switch(e){case"closeConversation":return t.hintCloseConversation;case"openConversationList":return t.hintOpenConversationList;case"openConversation":return t.hintOpenConversation;default:return}},Uh=({intent:e,strings:t})=>({label:Ph(e,t),hint:Fh(e,t)}),Bh="1.38.0",He="sb-agent",Se={ENTRY:`${He}-entry`,MODAL_ROOT:`${He}-modal-root`,WINDOW:`${He}-window`,LAUNCHER:`${He}-launcher`,WINDOW_TITLE:`${He}-window-title`},Pi="data-sb-initial-focus",Fi="true",Hh=`[${Pi}="${Fi}"]`,Ui={[Pi]:Fi},Xr="data-sb-focus-trap-sentinel",Gh="true",Bi="data-sb-initial-focus-header",Hi="true",zh=`[${Bi}="${Hi}"]`,Gi={[Bi]:Hi},zi="data-sb-message-input",Vi="true",Vh=`textarea[${zi}="${Vi}"]:not(:disabled)`,qh={[zi]:Vi},qi=1e3,dn=2147483647,_t={MODAL:dn-1,TOOLTIP:dn-2,WINDOW:dn-3,LAUNCHER:dn-4},Ki=36,Kh=100,Yh=Bh,Zr="noopener noreferrer nofollow",Wh=()=>typeof document>"u"||document.visibilityState==="visible",vr=()=>typeof document<"u"&&document.visibilityState==="hidden",Xs=()=>vr()?"backgrounded":"foregrounded",jh={getState:Xs,subscribe:e=>{if(typeof document>"u")return()=>{};const t=()=>e(Xs());return document.addEventListener("visibilitychange",t),()=>document.removeEventListener("visibilitychange",t)}};function Xh(){return{isOnline:()=>navigator.onLine,subscribe:e=>{const t=()=>e(!0),n=()=>e(!1);return window.addEventListener("online",t),window.addEventListener("offline",n),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",n)}}}}const mn={};function Zh(){return{get:e=>{try{return localStorage.getItem(e)}catch{return mn[e]??null}},set:(e,t)=>{try{localStorage.setItem(e,t)}catch{mn[e]=t}},delete:e=>{try{localStorage.removeItem(e)}catch{delete mn[e]}},getKeys:e=>{try{const t=[];for(let n=0;n<localStorage.length;n++){const r=localStorage.key(n);r&&r.startsWith(e)&&t.push(r)}return t}catch{return Object.keys(mn).filter(t=>t.startsWith(e))}}}}const Jh={conversation:{input_placeholder:"Ask a question",input_placeholder_disabled:"Chat is unavailable in this channel",input_placeholder_steward:"Processing your request...",input_placeholder_wait_ai_agent_response:"Waiting for the agent's reply...",input_placeholder_active_form:"Please fill out the form to move forward.",input_placeholder_reconnecting:"Trying to reconnect. Refresh if persists.",unknown_message_type:"(Unknown message type)",powered_by:"Powered by",citation_title:"Source",start_new_conversation_label:"Start a conversation",scroll_to_new_messages_label:()=>"New message",failed_message_resend:"Retry",failed_message_remove:"Remove",file_upload_no_supported_files:"No supported file types available.",file_upload_replace_alert_title:"Replace attachment?",file_upload_replace_alert_description:"Uploading a different file type will replace the current one.",a11y_message_list:"Chat messages",a11y_scroll_to_bottom:"Scroll to bottom",a11y_scroll_to_new_messages:"Scroll to new messages",a11y_open_conversation_list:"Open conversation list",a11y_open_conversation:"Open conversation with Support",a11y_open_conversations:"Open conversations",a11y_close_conversation:"Close conversation",a11y_close_conversations:"Close conversations",a11y_menu:"Menu",a11y_message_input:"Message",a11y_send_message:"Send message",a11y_attach_file:"Attach file",a11y_close_messenger:"Close messenger",a11y_dismiss_nudge_message:"Dismiss message",a11y_expand_messenger:"Expand messenger",a11y_collapse_messenger:"Collapse messenger",a11y_connect_agent:"Talk to human agent",a11y_message_sender_you:"You",a11y_suggested_reply:"Suggested reply",a11y_typing_indicator:"Typing",a11y_code_block_placeholder:"Code block",a11y_typing_format:e=>`${e} is typing`,a11y_message_failed:"Message send failed",a11y_new_messages_received:e=>`${e} new ${e===1?"message":"messages"} received`,a11y_new_messages_received_from_sender:(e,t)=>`${e}: ${t} new ${t===1?"message":"messages"} received`,a11y_agent_connected:e=>"Connected to human agent",a11y_conversation_closed:"Conversation has ended",a11y_file_image:e=>`Image file: ${e}`,a11y_file_video:e=>`Video file: ${e}`,a11y_file_pdf:e=>`PDF file: ${e}`,a11y_file_document:e=>`Document file: ${e}`,a11y_received_file_image:"Image file",a11y_received_file_video:"Video file",a11y_received_file_pdf:e=>`PDF file: ${e}`,a11y_received_files_image_count:e=>`${e} ${e===1?"image":"images"}`,a11y_screen_conversation:"Conversation",a11y_screen_conversation_with_agent:e=>`Conversation with ${e}`,a11y_screen_conversation_list_no_count:"Conversation list",a11y_screen_conversation_list_with_count:e=>`Conversations, ${e} total`,a11y_csat_displayed:"Satisfaction survey displayed",a11y_empty_conversation:"No messages in this conversation",a11y_input_disabled:"Message input is disabled",a11y_file_size_exceeded:e=>`File exceeds size limit of ${e}MB`,a11y_csat_form_error:"Please complete the required fields",a11y_hint_send_message:"Sends the message",a11y_hint_open_conversation:"Opens the conversation",a11y_hint_open_conversations:"Opens conversations",a11y_hint_close_conversation:"Closes the conversation",a11y_hint_close_messenger:"Closes the messenger",a11y_hint_open_menu:"Opens the menu",a11y_hint_connect_to_agent:"Escalates to a human agent",a11y_hint_attach_file:"Opens file attachment options",a11y_hint_view_new_messages:"Scrolls to new messages",a11y_hint_open_file:"Opens the file",a11y_hint_open_image:"Opens the image",a11y_hint_send_reply:"Sends this reply",image_viewer_default_title:"Image",a11y_image_viewer_close:"Close image viewer",a11y_image_viewer_previous:"Previous image",a11y_image_viewer_next:"Next image",a11y_image_viewer_download:"Download image",attachment_document:"Files"},conversation_list:{header_title:"Conversations",ended:"Ended",system_message:"System message",footer_title:"Start a conversation",multiple_files_count:e=>`${e} ${e===1?"file":"files"}`,a11y_conversation_item:(e,t,n,r)=>`${e}, ${t}, ${n}${r>0?`, ${r} unread ${r===1?"message":"messages"}`:""}`},date_format:{just_now:"Just now",minutes_ago:e=>`${e} minutes ago`,hours_ago:e=>`${e} hours ago`,date_short:"MM/dd/yyyy",date_separator:"MMMM dd, yyyy",message_timestamp:"p"},csat:{title:"Your feedback matters to us",submitted_label:"Successfully submitted!",cre_question:"Was your issue resolved?",cre_positive_label:"Yes, thank you! 👍",cre_negative_label:"No, that didn't help.",reason_placeholder:"Share your feedback",question:"How would you rate your experience?",submit_label:"Submit",submission_expired:"We're sorry, the survey period has ended.",a11y_csat_rating_label:(e,t)=>`${e} out of 5 — ${t}`,a11y_hint_select_rating:"Selects this rating"},form:{optional_label:"optional",validation_required:"This question is required"},common:{placeholder_something_went_wrong:"Something went wrong",placeholder_no_messages:"No messages",placeholder_no_conversations:"No conversations yet",placeholder_something_went_wrong_retry_label:"Retry",button_ok:"OK",button_cancel:"Cancel"},feedback:{title:"Submit feedback",good:"Good",bad:"Bad",comment_label:"Comment (optional)",comment_placeholder:"Leave a comment",cancel:"Cancel",submit:"Submit",save:"Save",edit:"Edit feedback",remove:"Remove feedback"},handoff:{confirm_title:"Request handoff?",confirm_description:"You'll be transferred to a human agent. Your conversation history will be shared.",confirm_cancel:"Cancel",confirm_handoff:"Handoff"},memory:{dialog_title:"Memory",desc_on:"Memory is **turned on**. It remembers your conversation history to provide personalized responses tailored to your previous questions and preferences.",desc_off:"Memory is **turned off**. If turned on, it will remember your conversation history to provide personalized responses tailored to your previous questions and preferences.",button_use:"Use",button_dont_use:"Don't use",button_keep_using:"Keep using",button_disable:"Disable",button_disable_and_delete:"Disable & Delete memory",button_keep_off:"Keep off",button_enable:"Enable memory",button_cancel:"Cancel",error_message:"Failed to update memory state. Please try again.",a11y_indicator_manage:"Manage memory",a11y_indicator_on:"Memory is on",a11y_indicator_off:"Memory is off"},connection_delay:{title:"Something went wrong. You'll be reconnected shortly.",description:e=>`Estimated waiting time: ${e}`}},Sr={language:"en",strings:Jh,dateLocale:gc.enUS},Yi=e=>({MESSAGE_INPUT__PLACE_HOLDER:e.conversation.input_placeholder,MESSAGE_INPUT__PLACE_HOLDER__DISABLED:e.conversation.input_placeholder_disabled,MESSAGE_INPUT__PLACE_HOLDER__STEWARD:e.conversation.input_placeholder_steward,MESSAGE_INPUT__PLACE_HOLDER__WAIT_AI_AGENT_RESPONSE:e.conversation.input_placeholder_wait_ai_agent_response,MESSAGE_INPUT__PLACE_HOLDER__RECONNECTING:e.conversation.input_placeholder_reconnecting,UNKNOWN__UNKNOWN_MESSAGE_TYPE:e.conversation.unknown_message_type,POWERED_BY:e.conversation.powered_by,CSAT_TITLE_UNSUBMITTED:e.csat.title,CSAT_TITLE_SUBMITTED:e.csat.submitted_label,CSAT_CRE_TITLE:e.csat.cre_question,CSAT_CRE_SOLVED:e.csat.cre_positive_label,CSAT_CRE_NOT_SOLVED:e.csat.cre_negative_label,CSAT_REASON_PLACEHOLDER:e.csat.reason_placeholder,CSAT_RATING_TITLE:e.csat.question,CSAT_SUBMIT_LABEL:e.csat.submit_label,CSAT_SUBMISSION_EXPIRED:e.csat.submission_expired,DATE_FORMAT__JUST_NOW:e.date_format.just_now,DATE_FORMAT__MINUTES_AGO:e.date_format.minutes_ago,DATE_FORMAT__HOURS_AGO:e.date_format.hours_ago,DATE_FORMAT__DATE_SHORT:e.date_format.date_short,DATE_FORMAT__MESSAGE_LIST__DATE_SEPARATOR:e.date_format.date_separator,DATE_FORMAT__MESSAGE_TIMESTAMP:e.date_format.message_timestamp,CONVERSATION_LIST__HEADER_TITLE:e.conversation_list.header_title,CONVERSATION_LIST__ENDED:e.conversation_list.ended,CONVERSATION_LIST__SYSTEM_MESSAGE:e.conversation_list.system_message,CONVERSATION_LIST__NO_CONVERSATIONS:e.common.placeholder_no_conversations,CONVERSATION_LIST__MULTIPLE_FILES_COUNT:e.conversation_list.multiple_files_count,TALK_TO_AGENT:e.conversation.start_new_conversation_label,CITATION_SOURCE_TITLE:e.conversation.citation_title,FORM_PLACEHOLDER:e.conversation.input_placeholder_active_form,FORM_VALIDATION_REQUIRED:e.form.validation_required,OPTIONAL:e.form.optional_label,PLACE_HOLDER__WRONG:e.common.placeholder_something_went_wrong,PLACE_HOLDER__NO_MESSAGES:e.common.placeholder_no_messages,RETRY:e.common.placeholder_something_went_wrong_retry_label,BUTTON__OK:e.common.button_ok,BUTTON__CANCEL:e.common.button_cancel,FAILED_MESSAGE_RESEND:e.conversation.failed_message_resend,FAILED_MESSAGE_REMOVE:e.conversation.failed_message_remove,FILE_UPLOAD_NO_SUPPORTED_FILES:e.conversation.file_upload_no_supported_files,FILE_UPLOAD_REPLACE_ALERT__TITLE:e.conversation.file_upload_replace_alert_title,FILE_UPLOAD_REPLACE_ALERT__DESCRIPTION:e.conversation.file_upload_replace_alert_description,FILE_UPLOAD_FILES:e.conversation.attachment_document,FEEDBACK_TITLE:e.feedback.title,FEEDBACK_GOOD:e.feedback.good,FEEDBACK_BAD:e.feedback.bad,FEEDBACK_COMMENT_LABEL:e.feedback.comment_label,FEEDBACK_COMMENT_PLACEHOLDER:e.feedback.comment_placeholder,FEEDBACK_CANCEL:e.feedback.cancel,FEEDBACK_SUBMIT:e.feedback.submit,FEEDBACK_SAVE:e.feedback.save,FEEDBACK_EDIT:e.feedback.edit,FEEDBACK_REMOVE:e.feedback.remove,A11Y_MESSAGE_LIST:e.conversation.a11y_message_list,A11Y_SCROLL_TO_BOTTOM:e.conversation.a11y_scroll_to_bottom,A11Y_SCROLL_TO_NEW_MESSAGES:e.conversation.a11y_scroll_to_new_messages,A11Y_OPEN_CONVERSATION_LIST:e.conversation.a11y_open_conversation_list,A11Y_OPEN_CONVERSATION:e.conversation.a11y_open_conversation,A11Y_OPEN_CONVERSATIONS:e.conversation.a11y_open_conversations,A11Y_CLOSE_CONVERSATION:e.conversation.a11y_close_conversation,A11Y_CLOSE_CONVERSATIONS:e.conversation.a11y_close_conversations,A11Y_MENU:e.conversation.a11y_menu,A11Y_MESSAGE_INPUT:e.conversation.a11y_message_input,A11Y_SEND_MESSAGE:e.conversation.a11y_send_message,A11Y_ATTACH_FILE:e.conversation.a11y_attach_file,A11Y_CONNECT_AGENT:e.conversation.a11y_connect_agent,A11Y_CLOSE_MESSENGER:e.conversation.a11y_close_messenger,A11Y_DISMISS_NUDGE_MESSAGE:e.conversation.a11y_dismiss_nudge_message,A11Y_EXPAND_MESSENGER:e.conversation.a11y_expand_messenger,A11Y_COLLAPSE_MESSENGER:e.conversation.a11y_collapse_messenger,A11Y_MESSAGE_SENDER_YOU:e.conversation.a11y_message_sender_you,A11Y_SUGGESTED_REPLY:e.conversation.a11y_suggested_reply,A11Y_TYPING_INDICATOR:e.conversation.a11y_typing_indicator,A11Y_CODE_BLOCK_PLACEHOLDER:e.conversation.a11y_code_block_placeholder,A11Y_TYPING_FORMAT:e.conversation.a11y_typing_format,A11Y_MESSAGE_FAILED:e.conversation.a11y_message_failed,A11Y_NEW_MESSAGES_RECEIVED:e.conversation.a11y_new_messages_received,A11Y_NEW_MESSAGES_RECEIVED_FROM_SENDER:e.conversation.a11y_new_messages_received_from_sender,A11Y_AGENT_CONNECTED:e.conversation.a11y_agent_connected,A11Y_CONVERSATION_CLOSED:e.conversation.a11y_conversation_closed,A11Y_FILE_IMAGE:e.conversation.a11y_file_image,A11Y_FILE_VIDEO:e.conversation.a11y_file_video,A11Y_FILE_PDF:e.conversation.a11y_file_pdf,A11Y_FILE_DOCUMENT:e.conversation.a11y_file_document,A11Y_RECEIVED_FILE_IMAGE:e.conversation.a11y_received_file_image,A11Y_RECEIVED_FILE_VIDEO:e.conversation.a11y_received_file_video,A11Y_RECEIVED_FILE_PDF:e.conversation.a11y_received_file_pdf,A11Y_RECEIVED_FILES_IMAGE_COUNT:e.conversation.a11y_received_files_image_count,A11Y_SCREEN_CONVERSATION:e.conversation.a11y_screen_conversation,A11Y_SCREEN_CONVERSATION_WITH_AGENT:e.conversation.a11y_screen_conversation_with_agent,A11Y_SCREEN_CONVERSATION_LIST_NO_COUNT:e.conversation.a11y_screen_conversation_list_no_count,A11Y_SCREEN_CONVERSATION_LIST_WITH_COUNT:e.conversation.a11y_screen_conversation_list_with_count,A11Y_CSAT_DISPLAYED:e.conversation.a11y_csat_displayed,A11Y_EMPTY_CONVERSATION:e.conversation.a11y_empty_conversation,A11Y_INPUT_DISABLED:e.conversation.a11y_input_disabled,A11Y_FILE_SIZE_EXCEEDED:e.conversation.a11y_file_size_exceeded,A11Y_CSAT_FORM_ERROR:e.conversation.a11y_csat_form_error,A11Y_HINT_SEND_MESSAGE:e.conversation.a11y_hint_send_message,A11Y_HINT_OPEN_CONVERSATION:e.conversation.a11y_hint_open_conversation,A11Y_HINT_OPEN_CONVERSATIONS:e.conversation.a11y_hint_open_conversations,A11Y_HINT_CLOSE_CONVERSATION:e.conversation.a11y_hint_close_conversation,A11Y_HINT_OPEN_MENU:e.conversation.a11y_hint_open_menu,A11Y_HINT_CONNECT_TO_AGENT:e.conversation.a11y_hint_connect_to_agent,A11Y_HINT_ATTACH_FILE:e.conversation.a11y_hint_attach_file,A11Y_HINT_VIEW_NEW_MESSAGES:e.conversation.a11y_hint_view_new_messages,A11Y_HINT_OPEN_FILE:e.conversation.a11y_hint_open_file,A11Y_HINT_OPEN_IMAGE:e.conversation.a11y_hint_open_image,A11Y_HINT_SEND_REPLY:e.conversation.a11y_hint_send_reply,A11Y_CONVERSATION_ITEM:e.conversation_list.a11y_conversation_item,A11Y_CSAT_RATING_LABEL:e.csat.a11y_csat_rating_label,A11Y_HINT_SELECT_RATING:e.csat.a11y_hint_select_rating,IMAGE_VIEWER__DEFAULT_TITLE:e.conversation.image_viewer_default_title,A11Y_IMAGE_VIEWER_CLOSE:e.conversation.a11y_image_viewer_close,A11Y_IMAGE_VIEWER_PREVIOUS:e.conversation.a11y_image_viewer_previous,A11Y_IMAGE_VIEWER_NEXT:e.conversation.a11y_image_viewer_next,A11Y_IMAGE_VIEWER_DOWNLOAD:e.conversation.a11y_image_viewer_download,SCROLL_TO_NEW_MESSAGES_LABEL:e.conversation.scroll_to_new_messages_label,HANDOFF_CONFIRM__TITLE:e.handoff.confirm_title,HANDOFF_CONFIRM__DESCRIPTION:e.handoff.confirm_description,HANDOFF_CONFIRM__CANCEL:e.handoff.confirm_cancel,HANDOFF_CONFIRM__HANDOFF:e.handoff.confirm_handoff,MEMORY__DIALOG_TITLE:e.memory.dialog_title,MEMORY__DESC_ON:e.memory.desc_on,MEMORY__DESC_OFF:e.memory.desc_off,MEMORY__BUTTON_USE:e.memory.button_use,MEMORY__BUTTON_DONT_USE:e.memory.button_dont_use,MEMORY__BUTTON_KEEP_USING:e.memory.button_keep_using,MEMORY__BUTTON_DISABLE:e.memory.button_disable,MEMORY__BUTTON_DISABLE_AND_DELETE:e.memory.button_disable_and_delete,MEMORY__BUTTON_KEEP_OFF:e.memory.button_keep_off,MEMORY__BUTTON_ENABLE:e.memory.button_enable,MEMORY__BUTTON_CANCEL:e.memory.button_cancel,MEMORY__ERROR_MESSAGE:e.memory.error_message,A11Y_MEMORY_INDICATOR_MANAGE:e.memory.a11y_indicator_manage,A11Y_MEMORY_INDICATOR_ON:e.memory.a11y_indicator_on,A11Y_MEMORY_INDICATOR_OFF:e.memory.a11y_indicator_off,CONNECTION_DELAY__TITLE:e.connection_delay.title,CONNECTION_DELAY__DESCRIPTION:e.connection_delay.description}),Wi=e=>{var t;return((t=e.split("-"))==null?void 0:t[0])??Qt},Qt="en",ji=new Set([Qt,"ko","es","pt","fr","hi","it","de","tr","ja"]),Qh='@import"https://fonts.googleapis.com/css?family=Roboto:400,500,600,700&display=swap";.sb-message-template__border{position:relative}.sb-message-template__border:after{content:"";position:absolute;top:0;right:0;bottom:0;left:0;z-index:1;box-shadow:inset 0 0 0 var(--border-width) var(--border-color);border-radius:var(--border-radius);pointer-events:none}.sb-message-template__action{cursor:pointer}.sb-message-template__parent{font-family:Roboto,serif}.sb-message-template__text{font-family:inherit;font-size:14px;font-weight:400;font-stretch:normal;font-style:normal;letter-spacing:normal;text-align:left}.sb-message-template__text-button{font-family:inherit;background-color:#e0e0e0;text-align:center;padding:10px;border-radius:6px;font-size:14px;font-weight:600;font-stretch:normal;font-style:normal;letter-spacing:normal}.sendbird-theme--light .sb-message-template__text-button{color:#742ddd}.sendbird-theme--dark .sb-message-template__text-button{color:#c2a9fa}.sb-message-template__text-button:hover{opacity:1;box-shadow:#0000001a 0 1px 3px,#0000000f 0 1px 2px}.sb-message-template__text-button,.sb-message-template__image-button{cursor:pointer;border-style:none}.sb-message-template__parent{border-radius:unset;background-color:transparent;overflow:hidden}.sb-message-template__parent *{box-sizing:border-box;line-height:1.3}.sb-message-template__carousel{display:flex;width:100%;box-sizing:border-box;touch-action:pan-y}',{Provider:ef,useContext:Jr}=ve("AgentUIElementResolver"),tf=({entryElement:e,modalRootElement:t,rootElement:n,children:r})=>{const s=l.useMemo(()=>{const o=n??document.body,i=e??o,c=t??o,u=d=>d===Se.MODAL_ROOT?c:i.querySelector(`#${d}`);return{resolveElement:u,resolvePortalContainer:d=>u(d)??c}},[e,t,n]);return a.createElement(ef,{value:s},r)};function mt(e,t){const n=e.getRootNode({composed:t});return n instanceof ShadowRoot||n instanceof Document?n:document}const Zs=()=>{const e=[];let t=0;const n=new Set,r=()=>n.forEach(s=>s());return{register:s=>{const o=++t;return e.push({id:o,handler:s}),r(),()=>{const i=e.findIndex(c=>c.id===o);i>=0&&(e.splice(i,1),r())}},dismissTopmost:()=>{const s=e[e.length-1];return s?(s.handler(),!0):!1},subscribe:s=>(n.add(s),()=>{n.delete(s)}),getOpenCount:()=>e.length}},{Provider:nf,useContext:Qr}=ve("EscapeDismissStack"),Js=e=>{e.stopPropagation(),e.stopImmediatePropagation()},rf=({rootElement:e=document.body,boundaryElement:t,children:n})=>{const r=l.useRef(null),s=l.useRef(null);r.current||(r.current=Zs()),s.current||(s.current=Zs());const o=r.current,i=s.current;l.useLayoutEffect(()=>{const u=t??mt(e),d=m=>{if(m.key==="Escape"){if(o.dismissTopmost()){Js(m);return}i.dismissTopmost()&&Js(m)}};return u.addEventListener("keydown",d),()=>u.removeEventListener("keydown",d)},[t,e,i,o]);const c=l.useMemo(()=>({register:o.register,dismissTopmost:o.dismissTopmost,registerShellDismissHandler:i.register,subscribe:o.subscribe,getOpenCount:o.getOpenCount}),[i,o]);return a.createElement(nf,{value:c},n)},Xi=(e,t,n)=>{const r=l.useRef(t);l.useLayoutEffect(()=>{r.current=t},[t]),l.useLayoutEffect(()=>{if(e)return n(()=>r.current())},[e,n])},sf=(e,t)=>{const{register:n}=Qr();Xi(e,t,n)},of=(e,t)=>{const{registerShellDismissHandler:n}=Qr();Xi(e,t,n)},Zi=()=>{const{subscribe:e,getOpenCount:t}=Qr();return l.useSyncExternalStore(e,()=>t()>0,()=>!1)},af=(e,t,n)=>{const r=e[t];return r?typeof r=="function"?r():Promise.resolve(r):new Promise((s,o)=>{(typeof queueMicrotask=="function"?queueMicrotask:setTimeout)(o.bind(null,new Error("Unknown variable dynamic import: "+t+(t.split("/").length!==n?". Note that variables only represent file names one level deep.":""))))})},Qs=Yi(Sr.strings),cf={...Qs,HEADER_BUTTON__AGENT_HANDOFF:"Talk to human agent",MESSAGE_INPUT__PLACE_HOLDER__SUGGESTED_REPLIES:"Select an option to continue",BUTTON__SUBMIT:"Submit",SUBMITTED:"Submitted",TRY_AGAIN:"Please try again.",FILE_UPLOAD_NOTIFICATION__COUNT_LIMIT:"Up to %d files can be attached.",FILE_UPLOAD_NOTIFICATION__SIZE_LIMIT:"The maximum size per file is %d MB.",FILE_UPLOAD_NOTIFICATION__FILES_EXCLUDED_BY_VALIDATION:"%d files were excluded due to limits. Please select files individually.",FILE_UPLOAD_PHOTOS:"Photos",FILE_VIEWER__UNSUPPORT:"Unsupported message",A11Y_FILE_SELECTED:e=>`${e}, selected`,A11Y_FILE_REMOVE_BUTTON:e=>`Remove file: ${e}`,A11Y_FILE_UPLOAD_OPTIONS:"File upload options",A11Y_FAILED_MESSAGE_OPTIONS:"Failed message options",A11Y_FEEDBACK_OPTIONS:"Feedback options",A11Y_CSAT_TEXT_INPUT_LABEL:"Enter answer",FORM_UNAVAILABLE:"Form is no longer available.",FORM_NOT_SUPPORTED:"This form is not supported in the current version.",FORM_VALIDATION_MIN_LENGTH:e=>`Minimum ${e} characters required`,FORM_VALIDATION_MAX_LENGTH:e=>`Maximum ${e} characters allowed`,FORM_VALIDATION_MIN:e=>`Minimum value is ${e}`,FORM_VALIDATION_MAX:e=>`Maximum value is ${e}`,FORM_VALIDATION_MIN_SELECT:e=>`Select at least ${e} options`,FORM_VALIDATION_MAX_SELECT:e=>`Select at most ${e} options`,FORM_VALIDATION_REGEX_FAILED:"Invalid format",DATE_FORMAT__CONVERSATION_LIST__LIST_ITEM_TITLE:Qs.DATE_FORMAT__DATE_SHORT,DATE_FORMAT__CONVERSATION_LIST__LIST_ITEM_TITLE_CAPTION:"h:mma",CONVERSATION_LIST__TOPICS_FALLBACK:"No category",CONVERSATION_CLOSED_FOOTER_LABEL:"Your conversation has ended",START_NEW_CONVERSATION:"💬 Start a new conversation",RETURN_TO_CONVERSATION:"💬 Return to conversation",BUTTON__SAVE:"Save",NO_NAME:"(No name)",CHANNEL_FROZEN:"Channel frozen"},xn={language:Sr.language,dateLocale:Sr.dateLocale,stringSet:cf},lf=Object.freeze(Object.defineProperty({__proto__:null,default:xn},Symbol.toStringTag,{value:"Module"})),yr=new Map([[Qt,xn]]);async function uf(e){const t=yr.get(e);if(t)return t;try{if(ji.has(e)){const{default:n}=await af(Object.assign({"./languages/de.ts":()=>Promise.resolve().then(()=>require("./cjs/CIjjIGUs.cjs")),"./languages/en.ts":()=>Promise.resolve().then(()=>lf),"./languages/es.ts":()=>Promise.resolve().then(()=>require("./cjs/B9JzuCyz.cjs")),"./languages/fr.ts":()=>Promise.resolve().then(()=>require("./cjs/BQ8EaWkc.cjs")),"./languages/hi.ts":()=>Promise.resolve().then(()=>require("./cjs/Cr2LxvlJ.cjs")),"./languages/it.ts":()=>Promise.resolve().then(()=>require("./cjs/C2Oi-KA4.cjs")),"./languages/ja.ts":()=>Promise.resolve().then(()=>require("./cjs/LFX2h7v2.cjs")),"./languages/ko.ts":()=>Promise.resolve().then(()=>require("./cjs/CKr98WbE.cjs")),"./languages/pt.ts":()=>Promise.resolve().then(()=>require("./cjs/C3VEshQr.cjs")),"./languages/tr.ts":()=>Promise.resolve().then(()=>require("./cjs/C116E0pr.cjs"))}),`./languages/${e}.ts`,3);return yr.set(e,n),n}return xn}catch{return xn}}const{Provider:df,useContext:ie}=ve("Localization"),mf=({language:e=navigator.language,languageCode:t,logger:n,stringSet:r,children:s})=>{const[o,i]=l.useState(yr.get(Qt));return l.useEffect(()=>{const c=t??Wi(e);o.language!==c&&(n==null||n.debug("localization.useEffect: update language",{from:o.language,to:c}),uf(c).then(i))},[e,t,n]),a.createElement(df,{value:{language:o.language,defaultStringSet:o.stringSet,stringSet:{...o.stringSet,...r},dateLocale:o.dateLocale,format:(c,u,d)=>ut.format(c,u,{locale:o.dateLocale,...d})}},s)},Rn="data-sb-agent-theme",eo=e=>(t,...n)=>{let r="";return t.forEach((s,o)=>{r+=s+(n[o]??"")}),`[${Rn}='${e}'] & { ${r} }`},ne={light:eo("light"),dark:eo("dark")},hf=U.css(({theme:e})=>{const{palette:t}=e;return`
|
|
8
8
|
:root,
|
|
9
9
|
:host {
|
|
10
10
|
--sendbird-primary-extra-dark: ${t.primary.extraDark};
|
|
@@ -53,9 +53,9 @@
|
|
|
53
53
|
--sendbird-overlay-dark: ${t.overlay.dark};
|
|
54
54
|
--sendbird-overlay-light: ${t.overlay.light};
|
|
55
55
|
}
|
|
56
|
-
`}),
|
|
57
|
-
width: ${({$size:e})=>
|
|
58
|
-
height: ${({$size:e})=>
|
|
56
|
+
`}),ff=U.css`[${Rn}='light'] &{--sb-text-high-emphasis:var(--sendbird-onlight-text-high-emphasis);--sb-text-mid-emphasis:var(--sendbird-onlight-text-mid-emphasis);--sb-text-low-emphasis:var(--sendbird-onlight-text-low-emphasis);--sb-text-disabled:var(--sendbird-onlight-text-disabled);--sb-text-high-emphasis-inverse:var(--sendbird-ondark-text-high-emphasis);--sb-text-mid-emphasis-inverse:var(--sendbird-ondark-text-mid-emphasis);--sb-text-low-emphasis-inverse:var(--sendbird-ondark-text-low-emphasis);--sb-text-disabled-inverse:var(--sendbird-ondark-text-disabled);--sb-bg-50-600:var(--sendbird-background-50);--sb-bg-100-500:var(--sendbird-background-100);--sb-bg-300-500:var(--sendbird-background-300);--sb-bg-200-400:var(--sendbird-background-200);--sb-primary:var(--sendbird-primary-main);--sb-secondary:var(--sendbird-secondary-main);--sb-error:var(--sendbird-error-main);--sb-information:var(--sendbird-information-light);}[${Rn}='dark'] &{--sb-text-high-emphasis:var(--sendbird-ondark-text-high-emphasis);--sb-text-mid-emphasis:var(--sendbird-ondark-text-mid-emphasis);--sb-text-low-emphasis:var(--sendbird-ondark-text-low-emphasis);--sb-text-disabled:var(--sendbird-ondark-text-disabled);--sb-text-high-emphasis-inverse:var(--sendbird-onlight-text-high-emphasis);--sb-text-mid-emphasis-inverse:var(--sendbird-onlight-text-mid-emphasis);--sb-text-low-emphasis-inverse:var(--sendbird-onlight-text-low-emphasis);--sb-text-disabled-inverse:var(--sendbird-onlight-text-disabled);--sb-bg-50-600:var(--sendbird-background-600);--sb-bg-100-500:var(--sendbird-background-500);--sb-bg-300-500:var(--sendbird-background-500);--sb-bg-200-400:var(--sendbird-background-400);--sb-primary:var(--sendbird-primary-light);--sb-secondary:var(--sendbird-secondary-light);--sb-error:var(--sendbird-error-light);--sb-information:var(--sendbird-information-light);}`,E={color:{primary:{dark:"var(--sendbird-primary-dark)",main:"var(--sendbird-primary-main)"},secondary:{dark:"var(--sendbird-secondary-dark)",light:"var(--sendbird-secondary-light)"},error:{dark:"var(--sendbird-error-dark)",light:"var(--sendbird-error-light)"},information:{main:"var(--sendbird-information-main)",light:"var(--sendbird-information-light)"},background700:"var(--sendbird-background-700)",background500:"var(--sendbird-background-500)",background400:"var(--sendbird-background-400)",background300:"var(--sendbird-background-300)",background200:"var(--sendbird-background-200)",background100:"var(--sendbird-background-100)",background50:"var(--sendbird-background-50)",onlight:{textLowEmphasis:"var(--sendbird-onlight-text-low-emphasis)",textDisabled:"var(--sendbird-onlight-text-disabled)"},ondark:{textHighEmphasis:"var(--sendbird-ondark-text-high-emphasis)",textMidEmphasis:"var(--sendbird-ondark-text-mid-emphasis)",textLowEmphasis:"var(--sendbird-ondark-text-low-emphasis)",textDisabled:"var(--sendbird-ondark-text-disabled)"},overlay:{dark:"var(--sendbird-overlay-dark)"}},themedColor:{textHighEmphasis:"var(--sb-text-high-emphasis)",textMidEmphasis:"var(--sb-text-mid-emphasis)",textLowEmphasis:"var(--sb-text-low-emphasis)",textDisabled:"var(--sb-text-disabled)",textHighEmphasisInverse:"var(--sb-text-high-emphasis-inverse)",textLowEmphasisInverse:"var(--sb-text-low-emphasis-inverse)",bg_50_600:"var(--sb-bg-50-600)",bg_100_500:"var(--sb-bg-100-500)",bg_300_500:"var(--sb-bg-300-500)",bg_200_400:"var(--sb-bg-200-400)",primary:"var(--sb-primary)",error:"var(--sb-error)",secondary:"var(--sb-secondary)"}};class Kt extends l.PureComponent{constructor(t){super(t),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(t){var n,r;(r=(n=this.props).onError)==null||r.call(n,t)}render(){const{fallback:t=null,errorFallback:n=t,loadingFallback:r=t,children:s}=this.props;return this.state.hasError?n:a.createElement(l.Suspense,{fallback:r},s)}}const Je=e=>{const t=e;return typeof t=="number"?`${t}px`:t},gf=e=>a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64",...e},a.createElement("path",{className:"fill",d:"M52.552 11.448a2.666 2.666 0 0 1 .222 3.52l-.222.251-16.781 16.78 16.781 16.782a2.665 2.665 0 0 1 0 3.771 2.666 2.666 0 0 1-3.52.222l-.251-.222L32 35.771 15.219 52.552a2.665 2.665 0 0 1-3.771 0 2.666 2.666 0 0 1-.222-3.52l.222-.251L28.228 32l-16.78-16.781a2.665 2.665 0 0 1 0-3.771 2.666 2.666 0 0 1 3.52-.222l.251.222 16.78 16.78 16.782-16.78a2.665 2.665 0 0 1 3.771 0z",fill:"#000",fillRule:"evenodd"})),pf=e=>a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 16 16",...e},a.createElement("path",{className:"fill",d:"M7.33348 7.3335L2.00015 7.3335L2.00015 6.00016H5.05735L1.3335 2.27631L2.27631 1.3335L6.00015 5.05734V2.00016L7.33348 2.00016L7.33348 7.3335ZM8.66683 8.66683H14.0002V10.0002L10.943 10.0002L14.6668 13.724L13.724 14.6668L10.0002 10.943V14.0002H8.66683L8.66683 8.66683Z",fill:"#000",fillRule:"evenodd"})),_f=e=>a.createElement("svg",{viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg",...e},a.createElement("path",{className:"fill",fillRule:"evenodd",clipRule:"evenodd",d:"M2 2H7.33333V3.33333L4.27613 3.33333L7.99999 7.05719L7.05718 8L3.33333 4.27616L3.33333 7.33333H2V2ZM14 14H8.66667V12.6667H11.7239L8.00001 8.94281L8.94282 8L12.6667 11.7238V8.66667H14V14Z",fill:"#000"})),Ef=e=>a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64",fill:"evenodd",...e},a.createElement("path",{className:"fill",fill:"#0D0D0D",d:"M50.667 18.667H13.333v-5.334h37.334zM50.667 34.667H13.333v-5.334h37.334zM13.333 50.667h37.334v-5.334H13.333z"})),Cf=e=>a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64",...e},a.createElement("path",{fill:"#000",fillRule:"evenodd",d:"M59.795 29.43 7.329 2.979C4.691 1.802 1.76 4.153 2.932 6.798l6.925 18.609a2 2 0 0 0 1.544 1.275l32.273 5.394L11.4 37.47a1.998 1.998 0 0 0-1.544 1.275L2.932 57.353c-.879 2.645 1.76 4.997 4.397 3.527l52.466-26.453c2.051-.882 2.051-3.82 0-4.996z",className:"fill"})),bf=new Set(["send","chat","message","chevron-right","good","good-filled","bad","bad-filled"]),vf={close:gf,send:Cf,menu:Ef,expand:_f,collapse:pf,spinner:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/Cf3-irI8.cjs"))),chat:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/BmdfYY9c.cjs"))),message:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/CmWLVNPR.cjs"))),error:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DNmdC4-j.cjs"))),refresh:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/D00MOxhE.cjs"))),"chevron-down":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/wf-LdaaN.cjs"))),"chevron-right":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/B0k-GApQ.cjs"))),done:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/kp5wcW4s.cjs"))),"done-circle":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/Bwaslfwl.cjs"))),stop:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/w1C9O3WB.cjs"))),"stop-circle":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DGubkk9p.cjs"))),user:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/CtHfgPDp.cjs"))),"file-document":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/_YfLwFkX.cjs"))),download:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/BN09c8-A.cjs"))),attach:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DcDTXo8_.cjs"))),"close-filled":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/D1kINslt.cjs"))),agent:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/Ce1MzjFq.cjs"))),actionbook:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/CXa-CGHE.cjs"))),function:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/zbLY6xl_.cjs"))),"radio-on":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/B9NJk4MI.cjs"))),"radio-off":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/Bb0r6Nhu.cjs"))),confluence:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/c6TZaE94.cjs"))),zendesk:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DqpDy_26.cjs"))),salesforce:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/BsgzT_SF.cjs"))),sprinklr:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/D97ZpKUC.cjs"))),website:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/ygZY2D-5.cjs"))),snippet:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/BCFOnu0u.cjs"))),template:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/eJXfXI1_.cjs"))),source:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/yVmX6iux.cjs"))),copy:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/COgkkyBM.cjs"))),show:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DM-WWpci.cjs"))),mute:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/P_ra76fq.cjs"))),good:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DEgUVAck.cjs"))),bad:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/C0s7eAf7.cjs"))),"good-filled":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/Chg8xHXT.cjs"))),"bad-filled":l.lazy(()=>Promise.resolve().then(()=>require("./cjs/CGkmTaBn.cjs"))),delight:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DCB0iTxd.cjs"))),photo:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/GQlGFYP2.cjs"))),add:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DEGDJBmd.cjs"))),document:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DBHlAmeA.cjs"))),memory:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DB0sLqre.cjs"))),activity:l.lazy(()=>Promise.resolve().then(()=>require("./cjs/DP95uu-Y.cjs")))},Sf=e=>({size:t=24,color:n=E.color.primary.main,flipInRtl:r=!1})=>a.createElement(Af,{$size:t,$color:n,$rtlFlip:r},a.createElement(Kt,{errorFallback:a.createElement(Tf,null)},a.createElement(e,null))),Ji=Object.fromEntries(Object.entries(vf).map(([e,t])=>[e,Sf(t)])),yf=U.css`[dir='rtl'] &:not([dir='ltr']),&[dir='rtl']{transform:scaleX(-1);}`,Af=_.default.span.attrs({"aria-hidden":"true"})`
|
|
57
|
+
width: ${({$size:e})=>Je(e)};
|
|
58
|
+
height: ${({$size:e})=>Je(e)};
|
|
59
59
|
display: inline-block;
|
|
60
60
|
|
|
61
61
|
svg {
|
|
@@ -74,24 +74,24 @@
|
|
|
74
74
|
stroke-linejoin: round;
|
|
75
75
|
}
|
|
76
76
|
|
|
77
|
-
${({$rtlFlip:e})=>e&&
|
|
78
|
-
`,
|
|
77
|
+
${({$rtlFlip:e})=>e&&yf};
|
|
78
|
+
`,Tf=()=>a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64"},a.createElement("rect",{x:"8",y:"8",width:"48",height:"48",fill:"none",className:"stroke",rx:"4"}),a.createElement("line",{x1:"20",y1:"20",x2:"44",y2:"44",className:"stroke"}),a.createElement("line",{x1:"44",y1:"20",x2:"20",y2:"44",className:"stroke"})),{Provider:If,useContext:xf}=ve("MessengerIcon",{icons:Ji}),Rf=({icons:e,children:t})=>{const n=l.useMemo(()=>({icons:Yu(Ji,e)}),[e]);return a.createElement(If,{value:n},t)},{Provider:Mf,useContext:Qi}=ve("MessengerTheme");function wf(e){const{theme:t,appearance:n,logger:r}=e;return a.createElement(Dd,{appearance:n,palette:t==null?void 0:t.palette,typography:t==null?void 0:t.typography,colors:t==null?void 0:t.colors,logger:r},a.createElement(kf,{...e}))}function kf({rootElement:e=document.body,children:t}){const{theme:n,updateTheme:r}=Yr();return l.useLayoutEffect(()=>{e.setAttribute(Rn,n.selectedTheme)},[e,n.selectedTheme]),a.createElement(U.ThemeProvider,{theme:n},a.createElement(Mf,{value:{theme:n,updateTheme:r,rootElement:e}},t))}const Lf=(e,t)=>{l.useEffect(()=>{const n=mt(t)instanceof ShadowRoot,r=mt(t,!0);if(!(n?t:r).querySelector(`link[href*='${e}']`)){const o=r.createElement("link");o.rel="stylesheet",o.href=e,(n?t:r.head).appendChild(o)}},[e,t])},Of=(e,t=document.body)=>{l.useEffect(()=>{if(!e)return;const n=mt(t),s=n instanceof ShadowRoot?t:n.head;if(!s)return;const o=`sba-${btoa(e).slice(0,10)}`;let i=s.querySelector(`style#${o}`);i?i.textContent!==e&&(i.textContent=e):(i=s.ownerDocument.createElement("style"),i.id=o,i.textContent=e,s.appendChild(i))},[e,t])},Nf=80,Df=()=>{const{stringSet:e}=ie(),t={screenConversation:e.A11Y_SCREEN_CONVERSATION,screenConversationWithAgent:e.A11Y_SCREEN_CONVERSATION_WITH_AGENT,screenConversationListNoCount:e.A11Y_SCREEN_CONVERSATION_LIST_NO_COUNT,screenConversationListWithCount:e.A11Y_SCREEN_CONVERSATION_LIST_WITH_COUNT,newMessage:e.A11Y_NEW_MESSAGES_RECEIVED,newMessageFromSender:e.A11Y_NEW_MESSAGES_RECEIVED_FROM_SENDER,typing:e.A11Y_TYPING_FORMAT,sendFailed:e.A11Y_MESSAGE_FAILED,agentConnected:e.A11Y_AGENT_CONNECTED,conversationClosed:e.A11Y_CONVERSATION_CLOSED,csatDisplayed:e.A11Y_CSAT_DISPLAYED,csatExpired:e.CSAT_SUBMISSION_EXPIRED,emptyState:e.A11Y_EMPTY_CONVERSATION,inputDisabled:e.A11Y_INPUT_DISABLED,fileSizeExceeded:e.A11Y_FILE_SIZE_EXCEEDED,csatFormError:e.A11Y_CSAT_FORM_ERROR},n=l.useRef(t);return n.current=t,n},ea=ve("AriaLiveRegion",{announce:me,announceScreenEntry:me,announceStatus:me,announceError:me,flush:me,setSuppressionState:me}),$f=ea.Provider,es=ea.useContext,Pf={position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},Ff=({children:e})=>{const t=l.useRef(null),n=l.useRef(new Set),r=l.useRef(me),s=Df(),[o]=l.useState(()=>xh(g=>{r.current(g)},{throttleMs:1e3,isSuppressed:()=>n.current.size>0}));r.current=g=>{const p=t.current;p&&(p.textContent="",requestAnimationFrame(()=>{p.textContent=g}))},l.useEffect(()=>()=>{o.destroy()},[o]);const i=o.announce,c=o.flush,u=l.useCallback(g=>{const p=Mh(g,s.current);i(p)},[i]),d=l.useCallback((g,p)=>{const v=wh(g,s.current),S=(p==null?void 0:p.mode)??Rh(g.event);i(v,{mode:S,dedupeKey:p==null?void 0:p.dedupeKey})},[i]),m=l.useCallback((g,p)=>{const v=kh(g,s.current);o.announceIgnoringSuppression(v),p&&setTimeout(()=>{p.focus()},Nf)},[o]),h=l.useCallback((g,p)=>{if(p){n.current.add(g);return}n.current.delete(g)},[]),f=l.useMemo(()=>({announce:i,announceScreenEntry:u,announceStatus:d,announceError:m,flush:c,setSuppressionState:h}),[i,m,u,d,c,h]);return a.createElement($f,{value:f},e,a.createElement("div",{ref:t,role:"status","aria-live":"polite","aria-atomic":"true",style:Pf}))},ta=ve("ConversationAnnouncements",{announcementsEnabled:!0,announce:me,announceScreenEntry:me,announceStatus:me,announceError:me,setIsSuppressed:me,setStatusPauseState:me,flush:me}),Uf=ta.Provider,lt=ta.useContext,Bf=({children:e,announcementsEnabled:t=!0})=>{const{announce:n,announceScreenEntry:r,announceStatus:s,announceError:o,flush:i,setSuppressionState:c}=es(),u=l.useRef([]),d=l.useRef(new Set),m=l.useRef(Symbol("conversation-announcements")),h=l.useCallback(T=>{if(!t||!T){c(m.current,!1);return}c(m.current,!0)},[t,c]),f=l.useCallback(()=>{u.current=[]},[]),g=l.useCallback(()=>{if(u.current.length===0)return;if(!t){f();return}const T=[...u.current];f(),T.forEach(I=>{i(),s(I.params,I.options)})},[s,t,f,i]),p=l.useCallback((T,I)=>{if(I){d.current.add(T);return}d.current.delete(T),d.current.size===0&&g()},[g]),v=l.useCallback(T=>{t&&n(T)},[n,t]),S=l.useCallback(T=>{t&&r(T)},[r,t]),C=l.useCallback((T,I)=>{if(t){if(d.current.size>0){u.current.push({params:T,options:I});return}s(T,I)}},[s,t]),A=l.useCallback((T,I)=>{t&&o(T,I)},[o,t]);l.useLayoutEffect(()=>(t||(f(),c(m.current,!1)),()=>{f(),c(m.current,!1)}),[t,f,c]);const y=l.useMemo(()=>({announcementsEnabled:t,announce:v,announceScreenEntry:S,announceStatus:C,announceError:A,setIsSuppressed:h,setStatusPauseState:p,flush:i}),[t,i,v,A,S,C,h,p]);return a.createElement(Uf,{value:y},e)},Dn=["a[href]","button:not(:disabled)","input:not(:disabled)","select:not(:disabled)","textarea:not(:disabled)",'[tabindex]:not([tabindex="-1"])'].join(", "),na=`${Dn}, [tabindex="-1"]`,Mt=e=>{if(!e.isConnected||e.hidden)return!1;let t=e;const n=e.ownerDocument.defaultView;for(;t;){if(t.hidden||t.getAttribute("aria-hidden")==="true")return!1;if(n){const r=n.getComputedStyle(t);if(r.display==="none"||r.visibility==="hidden")return!1}t=t.parentElement}return!0},Yt=(e,t)=>{for(const n of e.querySelectorAll(t))if(!n.hasAttribute(Xr)&&Mt(n))return n;return null},ra=e=>{let t=null,n=null;for(const r of e.querySelectorAll(Dn))r.hasAttribute(Xr)||Mt(r)&&(t??(t=r),n=r);return t?{first:t,last:n}:null},sa=(e,t)=>e instanceof ShadowRoot&&!(t instanceof HTMLElement)?e.host.ownerDocument.activeElement===e.host:t instanceof HTMLElement?e instanceof Document?t===e.body||t===e.documentElement:!1:!0,Hf=(e,t,n)=>sa(e,t)||n!=null&&t instanceof HTMLElement&&n.contains(t),ts=e=>Yt(e,Hh),oa=e=>ts(e)??Yt(e,Dn),Gf=e=>{const t=ts(e);if(t)return t;const n=e.querySelector(zh);return(n?Yt(n,na):null)??Yt(e,Dn)},B=({as:e,variant:t="body1",color:n,maxTextLines:r,className:s,...o})=>a.createElement(qf,{as:e,$variant:t,className:s,$color:n,$maxTextLines:r,...o}),to=new WeakMap,zf=(e,t)=>{let n=to.get(t);n||(n=new Map,to.set(t,n));const r=n.get(e);if(r)return r;const s=t[e]??t.body1,o=U.css`font-size:${Je(s.fontSize)};font-weight:${s.fontWeight};${s.fontFamily?`font-family: ${s.fontFamily};`:""}
|
|
79
79
|
${s.lineHeight?`line-height: ${s.lineHeight};`:"line-height: 100%;"}
|
|
80
|
-
`;return n.set(e,o),o},Nf=e=>e?B.css`display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:${e};overflow:hidden;`:"",Df=_.default.span`font-stretch:normal;letter-spacing:normal;${({$variant:e,theme:t})=>Of(e,t.typography)}color:${({$color:e})=>e};${({$maxTextLines:e})=>Nf(e)}`;async function jr(e){let t=e;t&&(!t.startsWith("http://")&&!t.startsWith("https://")&&(t="https://"+t),window.open(t,"_blank","noopener,noreferrer"))}const _r='[role="dialog"][aria-modal="true"]',$f=(e,t)=>{const n=new Set(Array.from(e.ownerDocument.querySelectorAll(_r)).filter(s=>s!==e&&(s.contains(e)||e.contains(s)))),r=t==null?void 0:t.closest(_r);return r&&r!==e&&n.add(r),n},Pf=(e,t)=>Array.from(e.ownerDocument.querySelectorAll(_r)).some(n=>n!==e&&!t.has(n)&&!n.contains(e)&&It(n)),Ff=e=>{const t=ea(e)??e;t===e&&ta(e),t.focus()},ta=e=>{e.hasAttribute("tabindex")||e.setAttribute("tabindex","-1")},Uf=(e,t)=>{const n=Ji(e);if(!n){ta(e),e.focus();return}n[t].focus()},Js=(e,t)=>{const n=e.ownerDocument.createElement("span");return n.tabIndex=0,n.setAttribute(zr,Lh),n.style.cssText=["position: fixed","width: 1px","height: 1px","opacity: 0","overflow: hidden","pointer-events: none"].join(";"),n.addEventListener("focus",()=>Uf(e,t)),n},Bf=(e,t)=>{e.key==="Tab"&&(e.defaultPrevented||e.target===t&&(Ji(t)||(e.preventDefault(),t.focus())))},Ln=(e,t,{nameReady:n=!0}={})=>{const r=l.useRef(0),s=l.useRef(!1);l.useEffect(()=>{if(!e||!t.current){s.current=!1;return}r.current+=1;const o=r.current,i=t.current,c=i.getRootNode(),u=c.activeElement instanceof HTMLElement?c.activeElement:null,d=$f(i,u);return()=>{u&&xe(()=>{if(r.current!==o)return;const m=c.activeElement;i.isConnected&&m instanceof HTMLElement&&m!==i&&!i.contains(m)&&!Qi(c,m)&&m.matches(Zi)&&It(m)||Pf(i,d)||!u.isConnected||!It(u)||u.focus()})}},[e,t]),l.useEffect(()=>{if(!e||!t.current)return;const o=t.current;let i=!1;const c=()=>{if(i||s.current||!o.isConnected)return;const m=o.getRootNode().activeElement;if(m instanceof HTMLElement&&m!==o&&o.contains(m)&&It(m)){s.current=!0;return}s.current=!0,Ff(o)};if(n)return xe(c),()=>{i=!0};const u=setTimeout(()=>xe(c),Bi);return()=>{i=!0,clearTimeout(u)}},[e,t,n]),l.useEffect(()=>{if(!e||!t.current)return;const o=t.current,i=Js(o,"last"),c=Js(o,"first"),u=d=>Bf(d,o);return o.insertBefore(i,o.firstChild),o.appendChild(c),o.addEventListener("keydown",u),()=>{o.removeEventListener("keydown",u),i.remove(),c.remove()}},[e,t])},ut=({style:e,portalContainerId:t,visible:n,onClose:r,children:s,cancelable:o=!0,"aria-label":i,"aria-labelledby":c,"aria-describedby":u})=>{const d=l.useRef(null),{resolvePortalContainer:m}=qr();return Ln(n,d),Wh(n,o?r:fe),n?dc.createPortal(a.createElement(Hf,{onClick:o?r:void 0,style:e},a.createElement(Gf,{ref:d,role:"dialog","aria-modal":"true","aria-label":i,"aria-labelledby":c,"aria-describedby":u,onClick:h=>h.stopPropagation()},s)),m(t)):null},Hf=_.default.div`position:fixed;top:0;left:0;width:100%;height:100%;background:${E.color.overlay.dark};display:flex;justify-content:center;align-items:center;z-index:${ft.MODAL};`,Gf=_.default.div`border-radius:4px;overflow:hidden;box-shadow:0 16px 24px 2px rgba(13,13,13,0.12),0 6px 30px 5px rgba(13,13,13,0.08),0 6px 10px -5px rgba(13,13,13,0.04);z-index:${ft.MODAL};`,zf=({id:e,children:t})=>a.createElement(Vf,{id:e},t),Vf=_.default.span`position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0;`,Qs=(e,t)=>{const n={role:"heading","aria-level":2,"aria-label":e};return t!=null&&t.active&&t.titleId?{...n,id:t.titleId,tabIndex:-1,...t.initialFocus===!1?{}:Ni}:n},qf=()=>{const e=`${l.useId()}-`;return(t,n)=>{if(!t)return{props:{},node:null};const r=e+n,s=l.createElement(zf,{id:r,children:t});return{props:{"aria-describedby":r},node:s}}},eo=({name:e,mimeType:t,selected:n},r)=>{var o;const s=Ve(t??"")?r.A11Y_FILE_IMAGE(e):Kt(t??"")?r.A11Y_FILE_VIDEO(e):Zo({name:e,mimeType:t})?r.A11Y_FILE_PDF(e):r.A11Y_FILE_DOCUMENT(e);return n?((o=r.A11Y_FILE_SELECTED)==null?void 0:o.call(r,s))??`${s}, selected`:s},Kf=e=>t=>{t.repeat||(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),e())},Ft=({onActivate:e})=>({role:"button",tabIndex:0,onClick:e,onKeyDown:Kf(e)}),Yf=({disabled:e,currentIndex:t,totalCount:n,onNavigate:r})=>s=>{var u;if(e||n<=0)return;let o=null;switch(s.key){case"ArrowRight":case"ArrowDown":o=(t+1)%n;break;case"ArrowLeft":case"ArrowUp":o=(t-1+n)%n;break;default:return}s.preventDefault(),r(o);const i=s.currentTarget.parentElement,c=i==null?void 0:i.querySelectorAll('[role="radio"]');(u=c==null?void 0:c[o])==null||u.focus()},to=(e,t,n,r,s,o)=>{let i=-1;return(e||!s&&n===0)&&(i=0),{role:"radio","aria-checked":e,"aria-disabled":t,onKeyDown:Yf({disabled:t,currentIndex:n,totalCount:r,onNavigate:o}),tabIndex:i}},ie=()=>{const{stringSet:e}=oe(),t=qf(),n=(i,c)=>{let u=e.A11Y_HINT_OPEN_FILE,d="of";Ve(i??"")&&(u=e.A11Y_HINT_OPEN_IMAGE,d="oi"),c!==void 0&&(d+=c);const m=t(u,d);return{props:m.props,descriptionNode:m.node}},r=i=>({"aria-label":eo(i,e)});return{launcher:{button:({isOpened:i,opensConversationList:c})=>{const u=Mh({intent:Ih({isOpened:i,opensConversationList:c}),strings:{openConversation:e.A11Y_OPEN_CONVERSATION,openConversationList:e.A11Y_OPEN_CONVERSATIONS,closeConversation:e.A11Y_CLOSE_CONVERSATION,closeConversationList:e.A11Y_CLOSE_CONVERSATIONS,hintOpenConversation:e.A11Y_HINT_OPEN_CONVERSATION,hintOpenConversationList:e.A11Y_HINT_OPEN_CONVERSATIONS,hintCloseConversation:e.A11Y_HINT_CLOSE_CONVERSATION}});let d="lc";u.hint===e.A11Y_HINT_OPEN_CONVERSATION&&(d="lo"),u.hint===e.A11Y_HINT_OPEN_CONVERSATIONS&&(d="los");const m=t(u.hint,d);return{props:{"aria-label":u.label,...m.props},descriptionNode:m.node}}},messenger:{closeButton:()=>({props:{"aria-label":e.A11Y_CLOSE_MESSENGER},descriptionNode:null}),expandButton:i=>{let c=e.A11Y_EXPAND_MESSENGER;return i&&(c=e.A11Y_COLLAPSE_MESSENGER),{props:{"aria-label":c},descriptionNode:null}},connectionDelayDialog:()=>({props:{"aria-label":e.CONNECTION_DELAY__TITLE},descriptionNode:null})},conversation:{header:{menuButton:()=>{const i=e.A11Y_HINT_OPEN_MENU,c=t(i,"mb");return{props:{"aria-label":e.A11Y_MENU,...c.props},descriptionNode:c.node}},closeConversationButton:()=>{const i=e.A11Y_HINT_CLOSE_CONVERSATION,c=t(i,"cc");return{props:{"aria-label":e.A11Y_CLOSE_CONVERSATION,...c.props},descriptionNode:c.node}},handoffButton:()=>{const i=e.A11Y_HINT_CONNECT_TO_AGENT,c=t(i,"h");return{props:{"aria-label":e.A11Y_CONNECT_AGENT,...c.props},descriptionNode:c.node}},title:(i,c)=>({props:Qs(i,c),descriptionNode:null}),memoryIndicator:i=>{let c=e.A11Y_MEMORY_INDICATOR_OFF,u="mof";i&&(c=e.A11Y_MEMORY_INDICATOR_ON,u="mon");const d=t(c,u);return{props:{"aria-label":e.A11Y_MEMORY_INDICATOR_MANAGE,...d.props},descriptionNode:d.node}}},messageInput:{attachFileButton:()=>{const i=e.A11Y_HINT_ATTACH_FILE,c=t(i,"af");return{props:{"aria-label":e.A11Y_ATTACH_FILE,...c.props},descriptionNode:c.node}},sendButton:()=>{const i=e.A11Y_HINT_SEND_MESSAGE,c=t(i,"sm");return{props:{"aria-label":e.A11Y_SEND_MESSAGE,...c.props},descriptionNode:c.node}},textInput:i=>({props:{role:"textbox","aria-label":i,...Dh},descriptionNode:null})},suggestedReplies:{item:(i,c)=>{const u=e.A11Y_HINT_SEND_REPLY,d=t(u,`sr${c}`);return{props:{"aria-label":`${e.A11Y_SUGGESTED_REPLY}, ${i}`,...d.props},descriptionNode:d.node}}},feedback:{container:()=>{const i=e.A11Y_HINT_SELECT_RATING,c=t(i,"fb");return{props:c.props,descriptionNode:c.node}},button:(i,c)=>{const u=e.A11Y_HINT_SELECT_RATING,d=t(u,`f${i}`);let m=e.FEEDBACK_BAD;return i==="good"&&(m=e.FEEDBACK_GOOD),{props:{"aria-label":m,...d.props,"aria-pressed":c},descriptionNode:d.node}},optionsBottomSheet:()=>({props:{"aria-label":e.A11Y_FEEDBACK_OPTIONS},descriptionNode:null})},newMessagesButton:()=>{const i=e.A11Y_HINT_VIEW_NEW_MESSAGES,c=t(i,"nm");return{props:{"aria-label":e.A11Y_SCROLL_TO_NEW_MESSAGES,...c.props},descriptionNode:c.node}},scrollToBottomButton:()=>{const i=e.A11Y_HINT_VIEW_NEW_MESSAGES,c=t(i,"sb");return{props:{"aria-label":e.A11Y_SCROLL_TO_BOTTOM,...c.props},descriptionNode:c.node}},startNewConversationButton:({onActivate:i})=>({props:{...Ft({onActivate:i}),"aria-label":e.TALK_TO_AGENT},descriptionNode:null}),poweredByLink:()=>({props:{"aria-label":`${e.POWERED_BY} Sendbird`},descriptionNode:null}),retryButton:(i=e.RETRY)=>({props:{"aria-label":i},descriptionNode:null}),file:{label:(i,c,u)=>i?eo({name:i,mimeType:c,selected:u},e):"",preview:i=>({props:r(i),descriptionNode:null}),buttonLikePreview:({onActivate:i,...c},u)=>{const d=n(c.mimeType,u);return{props:{...Ft({onActivate:i}),...r(c),...d.props},descriptionNode:d.descriptionNode}},removeButton:i=>({props:{"aria-label":e.A11Y_FILE_REMOVE_BUTTON(i)},descriptionNode:null})},csat:{scoresContainer:i=>{const c=e.A11Y_HINT_SELECT_RATING,u=t(c,"cs");return{props:{role:"radiogroup","aria-label":i,...u.props},descriptionNode:u.node}},scoreItem:({score:i,label:c,selected:u,disabled:d,currentIndex:m,totalCount:h,hasSelection:f,onChange:g})=>{var p;const C=c.trim()||c,b=e.A11Y_HINT_SELECT_RATING,S=t(b,`cs${i}`);return{props:{disabled:d,onClick:()=>g(i),...to(u,d,m,h,f,A=>g(A+1)),...S.props,"aria-label":((p=e.A11Y_CSAT_RATING_LABEL)==null?void 0:p.call(e,i,C))??`${i} / ${h} — ${C}`},descriptionNode:S.node}},submitButton:i=>({props:{"aria-label":i},descriptionNode:null})},form:{button:i=>({props:{"aria-label":i},descriptionNode:null}),textInput:(i,c,u,d)=>({props:{...d!=null&&d.labelId?{"aria-labelledby":d.labelId}:{"aria-label":i},"aria-required":c,"aria-disabled":u},descriptionNode:null}),numberInput:(i,c,u)=>({props:{"aria-label":i,"aria-required":c,"aria-disabled":u},descriptionNode:null}),singleSelectGroup:i=>{const c={role:"radiogroup"};return i&&(c["aria-label"]=i),{props:c,descriptionNode:null}},singleSelectOption:(i,c,u,d,m,h,f)=>({props:{...to(c,u,d,m,h,f),"aria-label":i},descriptionNode:null}),multiSelectOption:(i,c,u)=>({props:{"aria-label":i,"aria-pressed":c,"aria-disabled":u},descriptionNode:null})}},conversationList:{headerTitle:(i,c)=>({props:Qs(i,c),descriptionNode:null}),footer:{button:({onActivate:i})=>({props:{...Ft({onActivate:i}),"aria-label":e.TALK_TO_AGENT},descriptionNode:null})},item:({agent:i,status:c,lastMessage:u,time:d,unreadCount:m,onActivate:h})=>{const f=hh({agent:i,status:c,lastMessage:u,time:d,unreadCount:m},e.A11Y_CONVERSATION_ITEM);if(!h)return{props:{"aria-label":f},descriptionNode:null};const g=e.A11Y_HINT_OPEN_CONVERSATION,C=t(g,"cli");return{props:{...Ft({onActivate:h}),...C.props,"aria-label":f},descriptionNode:C.node}}}}},Wf=({title:e,description:t,highlightedText:n})=>{const r=Hm(t,n);return a.createElement(Xf,null,a.createElement(Zf,null,a.createElement(H,{as:"div",variant:"h1",color:E.themedColor.textHighEmphasis},e),t&&a.createElement(Jf,null,a.createElement(H,{as:"div",variant:"body3",color:E.themedColor.textMidEmphasis},r.beforeText,r.highlightedText?a.createElement(Qf,null,r.highlightedText):null,r.afterText))))},jf=()=>{const{components:e}=On.useContext(),{stringSet:t}=oe(),{messenger:n}=ie(),r=Um(),s=r.showDescription?Bm(r.remainingTime):"",o=r.showDescription?t.CONNECTION_DELAY__DESCRIPTION(s):"";return a.createElement(ut,{portalContainerId:Se.WINDOW,visible:r.visible,onClose:fe,...n.connectionDelayDialog().props},a.createElement(e.Dialog,{title:t.CONNECTION_DELAY__TITLE,description:o,highlightedText:s||void 0}))},On=qe({template:jf,components:{Dialog:Wf}}),Xf=_.default.div`width:280px;padding:24px;margin:0 auto;border-radius:4px;box-sizing:border-box;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,Zf=_.default.div`display:flex;flex-direction:column;`,Jf=_.default.div`margin-top:16px;`,Qf=_.default.strong`font-weight:700;`,eg=({url:e})=>jr(e),{Provider:tg,Consumer:na,useContext:de}=ve("Messenger");function ng({children:e,state:t,enableCloseConversationButton:n=!1,enableExpandButton:r=!0,enableAutoDisconnectInLauncher:s=!0,...o}){const[i,c]=l.useState(!1),[u,d]=l.useState(!1),m={opened:(t==null?void 0:t.opened)??i,setOpened:(t==null?void 0:t.setOpened)??c,expanded:(t==null?void 0:t.expanded)??u,setExpanded:(t==null?void 0:t.setExpanded)??d},{resolveElement:h}=qr(),f=l.useCallback(()=>{m.setOpened(!1)},[m.setOpened]);jh(m.opened,f);const g=l.useRef(m.opened);l.useLayoutEffect(()=>{const S=g.current&&!m.opened;if(g.current=m.opened,!S)return;const p=ct(o.rootElement),A=h(Se.WINDOW);let y=!1;return xe(()=>{var T;y||kf(p,p.activeElement,A)&&((T=h(Se.LAUNCHER))==null||T.focus())}),()=>{y=!0}},[m.opened,o.rootElement,h]);const{Template:C}=On.useContext(),b=l.useMemo(()=>{var S;return{...o.handlers,onClickLink:((S=o.handlers)==null?void 0:S.onClickLink)??eg}},[o.handlers]);return a.createElement(Wu,{...o},S=>a.createElement(tg,{value:{...o,...S,state:m,enableCloseConversationButton:n,enableExpandButton:r,enableAutoDisconnectInLauncher:s,handlers:b}},a.createElement(C,null),e))}const ra=/iPad|iPhone|iPod/.test(navigator.userAgent),rg=/Android/.test(navigator.userAgent),Zt=e=>ra||rg;let Nt=null,Qn=null;const sg=(e,t=5e3)=>{Nt&&(clearInterval(Nt),clearTimeout(Qn));const n=document.title;Nt=setInterval(()=>{document.title=document.title===e?n:e},750),Qn=setTimeout(()=>{clearInterval(Nt),Nt=null,Qn=null,document.title=n},t)},sa=()=>{Promise.resolve().then(()=>require("./cjs/B93o4u0P.cjs")).then(e=>{new Audio(e.default).play().catch(()=>{})})},oa="0 16px 24px 2px rgba(33, 33, 33, 0.12), 0 6px 30px 5px rgba(33, 33, 33, 0.08), 0 6px 10px -5px rgba(33, 33, 33, 0.04)",Re=B.css`&:focus-visible{outline:2px solid ${E.themedColor.primary};outline-offset:2px;}`,no=e=>{if(typeof e=="string"||typeof e=="number")return String(e)},Nn=({visible:e,title:t,description:n,confirmText:r="OK",cancelText:s,onConfirm:o,onCancel:i,onClose:c,"aria-label":u})=>{const d=l.useId(),m=l.useId(),h=u??no(t)??no(n),f=u?void 0:t?d:n?m:void 0,g=t&&n?m:void 0,C=()=>{c(),xe(()=>o==null?void 0:o())},b=()=>{c(),xe(()=>i==null?void 0:i())};return a.createElement(ut,{portalContainerId:Se.WINDOW,visible:e,onClose:c,"aria-label":h,"aria-labelledby":f,"aria-describedby":g},a.createElement(og,null,a.createElement(ig,null,t&&a.createElement("div",{id:d},a.createElement(H,{variant:"h1",color:E.themedColor.textHighEmphasis},t)),n&&a.createElement(ag,{id:m},a.createElement(H,{variant:"body3",color:E.themedColor.textMidEmphasis},n))),a.createElement(cg,null,s&&a.createElement(ro,{onClick:b},a.createElement(H,{variant:"button",color:E.themedColor.textHighEmphasis},s)),a.createElement(ro,{onClick:C},a.createElement(H,{variant:"button",color:E.themedColor.primary},r)))))},og=_.default.div`width:360px;height:auto;padding-block:24px 12px;padding-inline:24px;margin:0 auto;border-radius:4px;box-sizing:border-box;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,ig=_.default.div`margin-bottom:16px;`,ag=_.default.div`margin-top:16px;`,cg=_.default.div`display:flex;flex-direction:row;justify-content:flex-end;`,ro=_.default.button`all:unset;display:flex;justify-content:center;align-items:center;border-radius:4px;cursor:pointer;background-color:transparent;padding:10px 16px;${Re}`,{Provider:lg,useContext:Ne}=ve("MessengerSession"),ug=l.forwardRef(function({children:e,...t},n){return a.createElement(Ld,{ref:n,...t},r=>a.createElement(dg,{...r},e))}),dg=({children:e,...t})=>{const{chatSDK:n,logger:r,appId:s,aiAgentId:o,agentPreviewConfigs:i,state:c,handlers:u,dispatcher:d,_aiAgentSDK:m}=de(),{userSessionInfo:h,authenticate:f,userSession:g,aiAgentInfo:C,launcherInfo:b}=t,[S,p]=l.useState(!1),A=l.useRef(null);ht(n,{async onUserJoined(T,I){var N,k,w,z;T.conversation&&T.conversation.type===ge.ConversationType.PROACTIVE&&I.userId===((N=n.currentUser)==null?void 0:N.userId)&&(r.info("messengerSession.onUserJoined: proactive channel joined",T.url),(w=m.session)==null||w._updateActiveChannel({url:T.url,status:"open",conversationStatus:(k=T.conversation)==null?void 0:k.status}),c.setOpened(!0),mg({sound:document.hidden||!c.opened}),(z=A.current)==null||z.call(A,{channel:T}))}}),l.useEffect(()=>{f().then(({launcher:T})=>{T.auto_open&&!Zt()&&setTimeout(()=>c.setOpened(!0),500)}).catch(T=>{var I;r.error("messengerSession: failed to initialize",T),(I=u==null?void 0:u.onInitializeFailed)==null||I.call(u,T)})},[n,s,o,h==null?void 0:h.userId]),l.useEffect(()=>{const T=()=>p(!0);return d.subscribe(Ue.AnonymousSessionTokenExpired,T),()=>d.unsubscribe(Ue.AnonymousSessionTokenExpired,T)},[d]);const y=l.useCallback(()=>{t.deauthenticate().finally(()=>window.location.reload())},[t.deauthenticate]);return!g||!C||!b?null:a.createElement(lg,{value:{...t,userSession:g,aiAgentInfo:{...C,...i==null?void 0:i.bot},launcherInfo:{...b,...i==null?void 0:i.launcher},registerOnJoinedProactiveConversation:T=>A.current=T}},e,a.createElement(Nn,{visible:S,title:"Session timed out",description:"Start a new conversation.",onConfirm:y,onClose:fe}))};function mg({sound:e}){sg("🔔You have received a new message"),e&&sa()}const Tn=`@${Be}-focused-channel`,ia=`${Date.now()}-${Math.random().toString(36).slice(2)}`,hg=()=>{try{const e=localStorage.getItem(Tn);return e?JSON.parse(e).channelUrl??null:null}catch{return null}},so=e=>{try{localStorage.setItem(Tn,JSON.stringify({channelUrl:e,tabId:ia}))}catch{}},oo=()=>{try{const e=localStorage.getItem(Tn);if(!e)return;JSON.parse(e).tabId===ia&&localStorage.removeItem(Tn)}catch{}},fg=(e,t)=>(l.useEffect(()=>{if(!t||!e)return;const n=()=>so(e),r=()=>oo();return document.hasFocus()&&so(e),window.addEventListener("focus",n),window.addEventListener("blur",r),()=>{window.removeEventListener("focus",n),window.removeEventListener("blur",r),oo()}},[t,e]),{isChannelViewedInAnyTab:()=>document.hasFocus()||hg()===e}),gg=e=>{const{config:t,chatSDK:n}=de(),{sdkUser:r}=Ne(),s=t.conversation.messageAlertSoundEnabled,{isChannelViewedInAnyTab:o}=fg(e,s);ht(n,{onMessageReceived(i,c){if(!s||i.url!==e||o())return;(Ze(c)&&c.sender.userId!==(r==null?void 0:r.userId)||c.isAdminMessage()&&!c.silent)&&sa()}})};function pg(e){return new Promise(t=>{const n=new Image;n.onload=function(){const r=String(n.width),s=String(n.height);URL.revokeObjectURL(n.src),t({width:r,height:s})},n.src=URL.createObjectURL(e)})}async function _g(e){if("file"in e&&e.file instanceof File&&e.file.type.startsWith("image/")){const{width:t,height:n}=await pg(e.file);return new De.MessageMetaArray({key:Wo,value:[t,n]})}}const Eg=({onScrollAfterSendMessage:e})=>{const{agentPreviewConfigs:t,handlers:n}=de(),r=l.useRef(t==null?void 0:t.agentAttributes);return r.current=t==null?void 0:t.agentAttributes,{onBeforeSendMessage:async s=>{const o=await _g(s),i={...s,metaArrays:o?[o]:void 0},c=Cg(r.current);return c?{...i,data:JSON.stringify(c)}:i},onAfterSendMessage:s=>{var o,i,c;e(),(o=n==null?void 0:n.onMessageSend)==null||o.call(n,s.message),s.sendingStatus===De.SendingStatus.SUCCEEDED?(i=n==null?void 0:n.onCustomEvent)==null||i.call(n,{type:"message-sent-succeeded",data:{message:s}}):s.sendingStatus===De.SendingStatus.PENDING&&((c=n==null?void 0:n.onCustomEvent)==null||c.call(n,{type:"message-sent-pending",data:{message:s}}))}}},Cg=e=>{if(!e)return null;const t={};return e.ai&&Object.keys(e.ai).length>0&&(t.ai_attrs=e.ai),e.safeguard&&Object.keys(e.safeguard).length>0&&(t.safeguard_attrs=e.safeguard),typeof e.use_prompt_cache=="boolean"&&(t.use_prompt_cache=e.use_prompt_cache),Object.keys(t).length>0?t:null},St=50,er=St-40,{Provider:bg,useContext:aa}=ve("ConversationScroll"),io={viewport:0,contentHeight:0,contentSnapshotHeight:0,shouldRecalc:!1,shouldUpdate:!1},tr=e=>Math.max(0,e.scrollHeight-e.scrollTop-e.clientHeight),ao=e=>Array.from(e.querySelectorAll(`#${Be}-message-item`));function vg({scrollMode:e,messageStackDirection:t,children:n}){const r=l.useRef(null),s=l.useRef({mutation:null,resize:null,resizeTargets:new Set}),o=l.useRef({distanceFromBottom:0,prevScrollTop:0}),i=l.useRef({awayByUser:!1,programmatic:!1,streaming:!1,reconcileTimer:null,userMessageTimer:null}),c=l.useRef(io),[u,d]=l.useState(0),[m,h]=l.useState(0),[f,g]=l.useState(!1),[C,b]=l.useState(!1),[S,p]=l.useState(!0),A=P=>{const R=tr(P);return o.current.distanceFromBottom=R,h(R),R},y=()=>{const P=i.current;P.reconcileTimer&&(clearTimeout(P.reconcileTimer),P.reconcileTimer=null)},T=l.useCallback(()=>{const P=s.current;P.mutation&&(P.mutation.disconnect(),P.mutation=null),P.resize&&(P.resize.disconnect(),P.resize=null),P.resizeTargets.clear()},[]),I=l.useMemo(()=>f||t==="bottom"?"auto":e,[f,t,e]),L=()=>{c.current.contentSnapshotHeight=c.current.contentHeight,c.current.shouldUpdate=!0,c.current.shouldRecalc=!0},N=()=>{const P=r.current;!P||!c.current.shouldUpdate||d(R=>{c.current.shouldUpdate=!1;const{contentHeight:x,contentSnapshotHeight:O,shouldRecalc:U}=c.current,j=P.clientHeight;if(O>x)return R;const re=k(P,{messageType:"outgoing"});let Z=0;if(re){const pe=re.message.offsetTop-er+j;Z=Math.max(0,pe-x)}else{const pe=x-O,Ke=j-er;Z=Math.max(0,pe-Ke)}return R===0||Z!==R||U?(c.current.shouldRecalc=!1,Z):R})},k=l.useCallback((P,R)=>{const{messageType:x="all"}=R??{},O=ao(P);let U=O;x==="outgoing"&&(U=O.filter(dt=>dt.getAttribute("data-layout-id")==="outgoingmessage"));const j=U[U.length-1];if(!j)return null;const re=P.getBoundingClientRect(),Z=j.getBoundingClientRect(),pe=P.scrollTop+(Z.top-re.top),Ke=pe+j.offsetHeight;return{message:j,scrollTop:pe,lastMessageBottom:Ke}},[]),w=l.useCallback(()=>{const P=r.current;if(!P||I!=="fixed")return;const R=k(P);c.current.contentHeight=(R==null?void 0:R.lastMessageBottom)??P.scrollHeight,!i.current.streaming&&c.current.contentSnapshotHeight>0&&L(),i.current.programmatic?o.current.distanceFromBottom=tr(P):A(P),N()},[I,k]),z=l.useCallback(()=>{T(),y(),c.current=io,d(0),h(0),p(!0),o.current.distanceFromBottom=0,o.current.prevScrollTop=0,i.current.awayByUser=!1,i.current.programmatic=!1},[T]),$=l.useCallback((P=!0)=>{const R=o.current.distanceFromBottom>St;if(i.current.awayByUser=!1,h(0),!R){xe(()=>{const x=r.current;x&&!i.current.awayByUser&&x.scrollTo({top:x.scrollHeight,behavior:"auto"})});return}i.current.programmatic||(i.current.programmatic=!0,p(!1),y()),xe(()=>{const x=r.current;if(!x){i.current.programmatic=!1,p(!0);return}if(i.current.awayByUser){i.current.programmatic=!1,A(x),p(!0);return}const O=()=>{if(r.current!==x){i.current.programmatic=!1,r.current&&A(r.current),p(!0);return}i.current.programmatic=!1,A(x),p(!0)};if(P&&!i.current.reconcileTimer){const U=setTimeout(O,500);i.current.reconcileTimer=U,x.addEventListener("scrollend",()=>{clearTimeout(U),i.current.reconcileTimer=null,O()},{once:!0})}x.scrollTo({top:x.scrollHeight,behavior:P?"smooth":"auto"}),P||O()})},[]),q=l.useCallback(()=>{const P=r.current;if(P){if(i.current.awayByUser){A(P);return}$(!1)}},[$]),Q=l.useCallback(()=>{const P=r.current,R=s.current;if(!P||!R.resize)return;const x=new Set(ao(P));for(const O of R.resizeTargets)x.has(O)||(R.resize.unobserve(O),R.resizeTargets.delete(O));for(const O of x)R.resizeTargets.has(O)||(R.resize.observe(O),R.resizeTargets.add(O))},[]),D=l.useCallback(P=>{T();const R=s.current;typeof ResizeObserver<"u"&&(R.resize=new ResizeObserver(q),Q());const x=new MutationObserver(()=>{Q(),q()});R.mutation=x,x.observe(P,{childList:!0})},[T,q,Q]),G=l.useCallback(P=>{if(!P){r.current=null,T();return}if(r.current=P,I!=="fixed"){D(P);return}z(),c.current.viewport=P.clientHeight;const R=new MutationObserver(()=>{w()});s.current.mutation=R,R.observe(P,{childList:!0,subtree:!0})},[T,I,w,z,D]),F=l.useCallback(()=>{const P=r.current;if(!P)return;const R=k(P,{messageType:"outgoing"});R&&(P.scrollTo({top:R.message.offsetTop-er,behavior:"smooth"}),i.current.userMessageTimer&&clearTimeout(i.current.userMessageTimer),i.current.userMessageTimer=setTimeout(()=>{b(!1)},500))},[k]),K=(P,R,x)=>{const O=tr(P);if(x&&O>St){i.current.programmatic=!1,i.current.awayByUser=!0,y(),A(P),p(!0),o.current.prevScrollTop=R;return}o.current.distanceFromBottom=O},he=(P,R,x)=>{const U=A(P)<=St;R&&!U&&(i.current.awayByUser=!0,y()),x&&U&&(i.current.awayByUser=!1)},W=P=>{const{scrollTop:R}=P.currentTarget,x=o.current.prevScrollTop;i.current.programmatic?K(P.currentTarget,R,R<x):he(P.currentTarget,R<x,R>x),o.current.prevScrollTop=R},Y=l.useCallback(()=>{I==="fixed"&&(b(!0),L())},[I]),X=l.useCallback(()=>{I==="fixed"?setTimeout(()=>F(),300):$()},[I,F]),M=l.useCallback(P=>{i.current.streaming=P,I==="fixed"?L():i.current.awayByUser||$()},[I,$]),J=l.useCallback(P=>{g(P),P&&(d(0),I==="fixed"&&T())},[T,I]),ae=l.useCallback(P=>{I==="auto"&&P&&!i.current.awayByUser&&$()},[I,$]),$e=!(m<=St)&&!C,ke=l.useCallback(()=>o.current.distanceFromBottom>St,[]);return a.createElement(bg,{value:{ref:G,state:{bottomSpace:u,isAwayFromBottom:$e,isScrollPositionReconciled:S,shouldCountNewMessages:ke},props:{onScroll:W},actions:{scrollToBottom:$,onBeforeMessageSend:Y,onAfterMessageSend:X,onStreamingUpdate:M,onConversationClosed:J,onTypingIndicatorUpdate:ae}}},n)}const{Provider:Sg,Context:yg,useContext:Ie}=ve("Conversation"),Ag=({children:e})=>{var s;const{channelSource:t}=Ie(),n=(s=t.channel)==null?void 0:s.url,{checkForUserActionRequired:r}=Am(n);return l.useEffect(()=>{var i;const o=(i=t.channel)==null?void 0:i.lastMessage;o&&r(o)},[t.channel,r]),a.createElement(a.Fragment,null,e)},Tg=({channelUrl:e,onClearChannelUrl:t,onNavigateToConversationList:n,conversationStatsEnabled:r,shouldMarkAsRead:s,shouldInitializeConversation:o,initialUserMessage:i,children:c})=>{const{activeChannel:u,refreshActiveChannel:d}=Ne(),m=aa(),h=e||(u==null?void 0:u.url);gg(h);const{onBeforeSendMessage:f,onAfterSendMessage:g}=Eg({onScrollAfterSendMessage:()=>{m.actions.onAfterMessageSend()}}),C=l.useCallback(A=>(m.actions.onBeforeMessageSend(),f(A)),[m.actions,f]),b=l.useCallback(A=>{const y=A.some(T=>we.isStreaming(T));m.actions.onStreamingUpdate(y)},[m.actions.onStreamingUpdate]),S=l.useCallback(A=>{m.actions.onConversationClosed(A===ge.ConversationStatus.CLOSED)},[m.actions.onConversationClosed]),p=l.useCallback(async()=>{await d(),e&&(t==null||t())},[d,e,t]);return a.createElement(sm,{key:h,channelUrl:h,onBeforeSendMessage:C,onAfterSendMessage:g,onMessagesUpdated:b,onMessagesReceived:b,onChannelDeleted:p,onConversationStatusChanged:S,conversationStatsEnabled:r,shouldMarkAsRead:s,shouldInitializeConversation:o,initialUserMessage:i,shouldCountNewMessages:m.state.shouldCountNewMessages},A=>a.createElement(Sg,{value:{...A,scrollSource:m,goToActiveConversation:p,onNavigateToConversationList:n}},a.createElement(Ag,null,c)))},ca=({children:e,...t})=>{const{config:n}=Te(),{agentPreviewConfigs:r}=de(),s=n.conversation.list.scrollMode,o=r==null?void 0:r.messageStackDirection;return a.createElement(vg,{scrollMode:s,messageStackDirection:o},a.createElement(Tg,{...t},e))},Xr=l.createContext({onDrop:fe,subscribe:()=>fe}),Er=({children:e})=>{const t=l.useRef(new Set);return a.createElement(Xr.Provider,{value:{onDrop:n=>{var r;if(n.preventDefault(),(r=n.dataTransfer)!=null&&r.files){const s=Array.from(n.dataTransfer.files);s.length>0&&t.current.forEach(o=>o(s))}},subscribe:n=>(t.current.add(n),()=>t.current.delete(n))}},e)},Ig=({onDropFiles:e})=>{const{subscribe:t}=l.useContext(Xr);l.useEffect(()=>t(e),[e])};Er.Consumer=({children:e})=>{const{onDrop:t}=l.useContext(Xr);return e({onDrop:t,onDragOver:s=>s.preventDefault()})};const la=ve("WindowTitle",{hasWindowTitleReference:!1,isTitlePending:!1,isWindowNameReady:!0,registerWindowTitleReference:()=>fe,registerWindowTitlePending:()=>fe}),xg=la.Provider,ua=la.useContext,co=()=>{const e=l.useRef(0),[t,n]=l.useState(!1),r=l.useCallback(()=>{let s=!0;return e.current+=1,e.current===1&&n(!0),()=>{s&&(s=!1,e.current=Math.max(0,e.current-1),e.current===0&&n(!1))}},[]);return[t,r]},Zr=({children:e})=>{const[t,n]=co(),[r,s]=co(),o=!r||t,i=l.useMemo(()=>({hasWindowTitleReference:t,isTitlePending:r,isWindowNameReady:o,registerWindowTitleReference:n,registerWindowTitlePending:s}),[t,r,n,s]);return a.createElement(xg,{value:i},e)},Dn=ua,da=({enabled:e,label:t})=>{const{registerWindowTitleReference:n,registerWindowTitlePending:r}=ua(),s=e&&t.trim().length>0;return l.useLayoutEffect(()=>{if(e)return r()},[r,e]),l.useLayoutEffect(()=>{if(s)return n()},[n,s]),{enabled:s,id:s?Se.WINDOW_TITLE:void 0}},Rg=(e,t)=>{const r=(t?Vt(e,t):null)??Lf(e)??e;r===e&&!e.hasAttribute("tabindex")&&e.setAttribute("tabindex","-1"),r.focus({focusVisible:!1})},ma=(e,{enabled:t,ready:n,nameReady:r=!0,targetSelector:s,suppressed:o=!1})=>{const i=l.useRef(!1);l.useEffect(()=>{if(!t){i.current=!1;return}if(i.current||!e.current||o||s&&!n)return;const c=Wr(e.current)!=null;if(!s&&!c&&!n)return;let u=!1;const d=()=>{u||i.current||!e.current||(i.current=!0,Rg(e.current,s))};if(r)return xe(d),()=>{u=!0};const m=setTimeout(()=>xe(d),Bi);return()=>{u=!0,clearTimeout(m)}},[t,n,r,s,e,o])},Mg=(e,t)=>{const{announcementsEnabled:n}=st(),{channelSource:r}=Ie(),{isWindowNameReady:s}=Dn(),o=Ki(),i=r.channel!=null||r.error!=null;ma(e,{enabled:n,ready:i,nameReady:s,targetSelector:t==="messageInput"?Nh:void 0,suppressed:o})},wg=()=>{var s;const{_statsEnabled:e,channelSource:t}=Ie(),n=(s=t.channel)==null?void 0:s.url,r=l.useCallback(o=>{const i=()=>{o(fr()?"backgrounded":"foregrounded")};return document.addEventListener("visibilitychange",i),()=>document.removeEventListener("visibilitychange",i)},[]);Vm({channelUrl:n,enabled:e,isInitiallyBackgrounded:fr,isForegrounded:Fh,subscribeToForegroundState:r})},kg=e=>Ve(e)||Kt(e);function Lg(e,t){return e.filter(n=>we.isWelcomeMessage(n,t))}const ha=(e,{previewWelcomeMessages:t,aiAgentUserId:n})=>e.filter(r=>t.length>0?!we.isWelcomeMessage(r,n):!0),Og=[],fa=()=>{var C,b,S,p,A,y;const{agentPreviewConfigs:e={},aiAgentId:t}=de(),{aiAgentInfo:n,userSession:r}=Ne(),{channelSource:s,messageSource:o,state:{input:i,streamAnimation:c}}=Ie(),u=e.welcomeMessages??Og,d=l.useMemo(()=>ha(o.messages,{previewWelcomeMessages:u,aiAgentUserId:t}),[t,o.messages,u]),m=nt(s.channel),h=(b=(C=ni(s.channel,r.userId))==null?void 0:C.nickname)==null?void 0:b.trim(),f=m?(p=(S=s.channel)==null?void 0:S.name)==null?void 0:p.trim():(A=n==null?void 0:n.nickname)==null?void 0:A.trim(),g=h||f||void 0;return{initialized:o.initialized,channelUrl:(y=s.channel)==null?void 0:y.url,agentName:g,isClosed:Fe(s.channel),isHandedOff:m,messages:d,filteredMessagesCount:d.length,hasWelcomeMessages:u.length>0,inputDisabled:i.disabled,inputDisabledBy:i.disabledBy,isStreamAnimating:c.isAnimating,currentUserId:r.userId}},Ng=(e={})=>{const{announceScreenEntry:t,announcementsEnabled:n}=st(),{initialized:r=!1,channelUrl:s,agentName:o,isClosed:i=!1,messages:c=[],hasWelcomeMessages:u=!1}=e,d=l.useRef(null),m=l.useMemo(()=>c.some(f=>Oe.isAdmin(f)&&Oe.isCSAT(f)),[c]),h=c.length===0&&!u;l.useEffect(()=>{if(!n){d.current=null;return}!r||!s||d.current!==s&&(t({screen:"conversation",agentName:o,isClosed:i,hasCSAT:m,...h?{isEmpty:!0}:{}}),d.current=s)},[o,t,n,s,m,r,i,h])},Dg=()=>{const e=fa();Ng(e)},$g=e=>({image:e.A11Y_RECEIVED_FILE_IMAGE,video:e.A11Y_RECEIVED_FILE_VIDEO,pdf:e.A11Y_RECEIVED_FILE_PDF,document:e.A11Y_FILE_DOCUMENT,receivedFilesImageCount:e.A11Y_RECEIVED_FILES_IMAGE_COUNT,multipleFilesCount:e.CONVERSATION_LIST__MULTIPLE_FILES_COUNT,codeBlockPlaceholder:e.A11Y_CODE_BLOCK_PLACEHOLDER}),lo=(e,t,n=it.format)=>{const r=ph(e,$g(t)),s="sender"in e?e.sender:void 0,o=e.createdAt!=null&&e.createdAt!==0?n(e.createdAt,t.DATE_FORMAT__MESSAGE_TIMESTAMP):void 0;return{senderName:typeof(s==null?void 0:s.nickname)=="string"&&s.nickname.trim()||void 0,body:r||void 0,time:o}},Pg={senderName:!0,body:!0,time:!0},Fg=Object.keys(Pg),Ug=(e,t)=>Fg.every(n=>e[n]===t[n]),uo=2e3,mo=400,Cr=e=>{const t=new Set;return"reqId"in e&&typeof e.reqId=="string"&&e.reqId.length>0&&t.add(`req:${e.reqId}`),"messageId"in e&&e.messageId>0&&t.add(`message:${String(e.messageId)}`),[...t]},ga=e=>{if(!Oe.isAdmin(e)||!Oe.isCSAT(e))return null;const t=Ah(e);return t?`csat:${t}`:null},Bg=e=>{const t=new Set;for(const n of e){const r=ga(n);r&&t.add(r)}return t},Hg=(e,t)=>{for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(r&&Cr(r).some(s=>t.includes(s)))return r}},nr=(e,t)=>e.some(n=>t.includes(n)),ho=()=>typeof document>"u"?null:document.activeElement instanceof HTMLElement?document.activeElement:null,rr=e=>new Map(e.map(({key:t,sendingStatus:n})=>[t,n])),Gg=()=>{const{announceStatus:e,announcementsEnabled:t}=st(),{stringSet:n,format:r}=oe(),{channelUrl:s,messages:o,isClosed:i,isHandedOff:c,agentName:u,initialized:d,inputDisabled:m,inputDisabledBy:h,isStreamAnimating:f,currentUserId:g}=fa(),{outgoingMessageStates:C,outgoingMessageStatusSignature:b}=l.useMemo(()=>{if(!g)return{outgoingMessageStates:[],outgoingMessageStatusSignature:""};const W=o.flatMap(Y=>{const X=Sh(Y,g);return!X||!("sendingStatus"in Y)?[]:[{key:X,sendingStatus:Y.sendingStatus}]});return{outgoingMessageStates:W,outgoingMessageStatusSignature:W.map(({key:Y,sendingStatus:X})=>`${Y}:${X}`).join(",")}},[g,o]),S=l.useRef({isClosed:!1,isHandedOff:!1,inputDisabled:m,inputDisabledBy:h,outgoingMessageStatuses:rr(C)}),p=l.useRef({messages:o,currentUserId:g,inputDisabledBy:h,isStreamAnimating:f,stringSet:n,format:r}),A=l.useRef([]),y=l.useRef(null),T=l.useRef([]),I=l.useRef(new Set),L=l.useRef(new Set),N=l.useRef(!1),k=l.useRef(s);p.current={messages:o,currentUserId:g,inputDisabledBy:h,isStreamAnimating:f,stringSet:n,format:r};const w=()=>p.current.isStreamAnimating||p.current.inputDisabledBy==="ai_responding",z=()=>{y.current!=null&&(clearTimeout(y.current),y.current=null)},$=(W,Y,X)=>{const M=X==null?void 0:X.replaceableForMs;if(W.length===0||!M)return;const J=Date.now();T.current=[...T.current.filter(({replaceableUntil:ae})=>ae>J),{eventKeys:W,parts:Y,replaceableUntil:J+M}]},q=()=>A.current.length>0,Q=()=>{A.current=[]},D=()=>{const[W,...Y]=A.current;if(!W)return!1;A.current=Y;const{eventKeys:X,parts:M,dedupeKey:J}=W,ae=ke=>{$(X,ke,{replaceableForMs:X.length>0?uo:void 0}),e({event:"newMessage",...ke},J?{dedupeKey:J}:void 0)};if(X.length===0)return ae(M),!0;const ye=p.current,$e=Hg(ye.messages,X);if($e){const ke=lo($e,ye.stringSet,ye.format);return ae(ke),!0}return ae(M),!0},G=()=>{for(z();D(););},F=(W=uo)=>{z(),y.current=setTimeout(()=>{if(y.current=null,w())return;const Y=ho(),[X]=A.current;if(!X)return;if(X.focusTarget!==Y){A.current=[{...X,focusTarget:Y},...A.current.slice(1)],F(mo);return}D()&&q()&&F(mo)},W)},K=(W,Y,X)=>{const M={eventKeys:Y,parts:W,focusTarget:ho(),dedupeKey:X?X.dedupeKey??void 0:Y[0]},J=Y.length===0?-1:A.current.findIndex(({eventKeys:ae})=>nr(ae,Y));J>=0?A.current=A.current.map((ae,ye)=>ye===J?{...M,dedupeKey:X?M.dedupeKey:ae.dedupeKey}:ae):A.current=[...A.current,M],F()},he=(W,Y,X)=>{if(W!=="messagesUpdated"||Y.length===0)return!1;const M=Date.now(),J=T.current.find(ae=>ae.replaceableUntil>M&&nr(ae.eventKeys,Y));return J?!Ug(X,J.parts):!1};l.useEffect(()=>{const W=k.current!==s;(!t||!d||W)&&(N.current=!1,L.current.clear(),Q(),T.current=[],I.current.clear(),z(),W&&(k.current=s),!t||!d)||N.current||(N.current=!0,k.current=s,S.current={isClosed:i,isHandedOff:c,inputDisabled:m,inputDisabledBy:h,outgoingMessageStatuses:rr(C)},I.current=new Set(o.flatMap(Y=>{if(!we.isStreaming(Y))return[];const X="sender"in Y?Y.sender:void 0;return(X==null?void 0:X.userId)===p.current.currentUserId?[]:Cr(Y)})),L.current=Bg(o))},[e,t,s,d,m,i,c,b]),l.useEffect(()=>{const W=(Y,X)=>{const M=p.current,J=Cr(Y),ae=ga(Y);if(ae!=null){if(L.current.has(ae))return;L.current.add(ae),e({event:"csatDisplayed"});return}if(we.isStreaming(Y)){J.forEach(U=>{I.current.add(U)});return}const ye=J.filter(U=>I.current.has(U)),$e=X==="messagesUpdated"&&ye.length>0;$e&&ye.forEach(U=>{I.current.delete(U)});const ke=X==="messagesUpdated"&&A.current.some(({eventKeys:U})=>nr(U,J)),P=lo(Y,M.stringSet,M.format),R=he(X,J,P);if(!$e&&X!=="messagesAdded"&&!ke&&!R)return;const x=R?{dedupeKey:null}:void 0;if($e||w()||ke){K(P,[...new Set([...ye,...J])],x);return}if(R){K(P,J,x);return}q()&&G();const O=J[0];e({event:"newMessage",...P},O?{dedupeKey:O}:void 0)};return pi.subscribe(Y=>{if(!N.current||Y.channelUrl!==s||Y.kind==="initialized"||Y.kind==="messagesDeleted"||!Th(Y.source))return;const X=p.current.currentUserId;for(const M of Y.messages)M&&yh(M,X)&&W(M,Y.kind)})},[e,s]),l.useEffect(()=>{N.current&&(w()||q()&&F())},[h,f]),l.useEffect(()=>()=>{z()},[]),l.useEffect(()=>{if(!N.current)return;const W=S.current,Y=W.outgoingMessageStatuses;W.outgoingMessageStatuses=rr(C),C.some(({key:M,sendingStatus:J})=>{const ae=Y.get(M);return ae!==void 0&&ae!=="failed"&&J==="failed"})&&e({event:"sendFailed"})},[e,b]),l.useEffect(()=>{if(!N.current)return;const W=S.current;i&&!W.isClosed&&e({event:"conversationClosed"}),W.isClosed=i},[e,i]),l.useEffect(()=>{if(!N.current)return;const W=S.current;c&&!W.isHandedOff&&e({event:"agentConnected",agentName:u}),W.isHandedOff=c},[u,e,c]),l.useEffect(()=>{if(!N.current)return;const W=S.current;m&&h!=="ai_responding"&&(!W.inputDisabled||W.inputDisabledBy==="ai_responding")&&e({event:"inputDisabled"}),W.inputDisabled=m,W.inputDisabledBy=h},[e,m,h])},zg=()=>{const{channelSource:e}=Ie(),t=yi(e.channel);return!(t!=null&&t.user.userId)||!t.user.nickname?null:{userId:t.user.userId,nickname:t.user.nickname}},Vg=e=>{const{announceStatus:t,announcementsEnabled:n}=st();Rm(e??null,r=>{t({event:"typing",agentName:r})},1e4,n)},qg=()=>{const e=zg();Vg(e)},ee=({type:e,size:t=24,className:n,color:r})=>{const{icons:s}=_f(),o=s[e];return a.createElement(Kg,{className:n},a.createElement(o,{size:t,color:r??E.color.primary.main,flipInRtl:uf.has(e)}))},Kg=_.default.span.attrs({"aria-hidden":"true"})`
|
|
80
|
+
`;return n.set(e,o),o},Vf=e=>e?U.css`display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:${e};overflow:hidden;`:"",qf=_.default.span`font-stretch:normal;letter-spacing:normal;${({$variant:e,theme:t})=>zf(e,t.typography)}color:${({$color:e})=>e};${({$maxTextLines:e})=>Vf(e)}`;async function ns(e){let t=e;t&&(!t.startsWith("http://")&&!t.startsWith("https://")&&(t="https://"+t),window.open(t,"_blank","noopener,noreferrer"))}const Ar='[role="dialog"][aria-modal="true"]',Kf=(e,t)=>{const n=new Set(Array.from(e.ownerDocument.querySelectorAll(Ar)).filter(s=>s!==e&&(s.contains(e)||e.contains(s)))),r=t==null?void 0:t.closest(Ar);return r&&r!==e&&n.add(r),n},Yf=(e,t)=>Array.from(e.ownerDocument.querySelectorAll(Ar)).some(n=>n!==e&&!t.has(n)&&!n.contains(e)&&Mt(n)),Wf=e=>{const t=oa(e)??e;t===e&&ia(e),t.focus()},ia=e=>{e.hasAttribute("tabindex")||e.setAttribute("tabindex","-1")},jf=(e,t)=>{const n=ra(e);if(!n){ia(e),e.focus();return}n[t].focus()},no=(e,t)=>{const n=e.ownerDocument.createElement("span");return n.tabIndex=0,n.setAttribute(Xr,Gh),n.style.cssText=["position: fixed","width: 1px","height: 1px","opacity: 0","overflow: hidden","pointer-events: none"].join(";"),n.addEventListener("focus",()=>jf(e,t)),n},Xf=(e,t)=>{e.key==="Tab"&&(e.defaultPrevented||e.target===t&&(ra(t)||(e.preventDefault(),t.focus())))},$n=(e,t,{nameReady:n=!0}={})=>{const r=l.useRef(0),s=l.useRef(!1);l.useEffect(()=>{if(!e||!t.current){s.current=!1;return}r.current+=1;const o=r.current,i=t.current,c=i.getRootNode(),u=c.activeElement instanceof HTMLElement?c.activeElement:null,d=Kf(i,u);return()=>{u&&Ie(()=>{if(r.current!==o)return;const m=c.activeElement;i.isConnected&&m instanceof HTMLElement&&m!==i&&!i.contains(m)&&!sa(c,m)&&m.matches(na)&&Mt(m)||Yf(i,d)||!u.isConnected||!Mt(u)||u.focus()})}},[e,t]),l.useEffect(()=>{if(!e||!t.current)return;const o=t.current;let i=!1;const c=()=>{if(i||s.current||!o.isConnected)return;const m=o.getRootNode().activeElement;if(m instanceof HTMLElement&&m!==o&&o.contains(m)&&Mt(m)){s.current=!0;return}s.current=!0,Wf(o)};if(n)return Ie(c),()=>{i=!0};const u=setTimeout(()=>Ie(c),qi);return()=>{i=!0,clearTimeout(u)}},[e,t,n]),l.useEffect(()=>{if(!e||!t.current)return;const o=t.current,i=no(o,"last"),c=no(o,"first"),u=d=>Xf(d,o);return o.insertBefore(i,o.firstChild),o.appendChild(c),o.addEventListener("keydown",u),()=>{o.removeEventListener("keydown",u),i.remove(),c.remove()}},[e,t])},ft=({style:e,portalContainerId:t,visible:n,onClose:r,children:s,cancelable:o=!0,"aria-label":i,"aria-labelledby":c,"aria-describedby":u})=>{const d=l.useRef(null),{resolvePortalContainer:m}=Jr();return $n(n,d),sf(n,o?r:me),n?pc.createPortal(a.createElement(Zf,{onClick:o?r:void 0,style:e},a.createElement(Jf,{ref:d,role:"dialog","aria-modal":"true","aria-label":i,"aria-labelledby":c,"aria-describedby":u,onClick:h=>h.stopPropagation()},s)),m(t)):null},Zf=_.default.div`position:fixed;top:0;left:0;width:100%;height:100%;background:${E.color.overlay.dark};display:flex;justify-content:center;align-items:center;z-index:${_t.MODAL};`,Jf=_.default.div`border-radius:4px;overflow:hidden;box-shadow:0 16px 24px 2px rgba(13,13,13,0.12),0 6px 30px 5px rgba(13,13,13,0.08),0 6px 10px -5px rgba(13,13,13,0.04);z-index:${_t.MODAL};`,Qf=({id:e,children:t})=>a.createElement(eg,{id:e},t),eg=_.default.span`position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0;`,ro=(e,t)=>{const n={role:"heading","aria-level":2,"aria-label":e};return t!=null&&t.active&&t.titleId?{...n,id:t.titleId,tabIndex:-1,...t.initialFocus===!1?{}:Ui}:n},tg=()=>{const e=`${l.useId()}-`;return(t,n)=>{if(!t)return{props:{},node:null};const r=e+n,s=l.createElement(Qf,{id:r,children:t});return{props:{"aria-describedby":r},node:s}}},so=({name:e,mimeType:t,selected:n},r)=>{var o;const s=We(t??"")?r.A11Y_FILE_IMAGE(e):jt(t??"")?r.A11Y_FILE_VIDEO(e):ti({name:e,mimeType:t})?r.A11Y_FILE_PDF(e):r.A11Y_FILE_DOCUMENT(e);return n?((o=r.A11Y_FILE_SELECTED)==null?void 0:o.call(r,s))??`${s}, selected`:s},ng=e=>t=>{t.repeat||(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),e())},Bt=({onActivate:e})=>({role:"button",tabIndex:0,onClick:e,onKeyDown:ng(e)}),rg=({disabled:e,currentIndex:t,totalCount:n,onNavigate:r})=>s=>{var u;if(e||n<=0)return;let o=null;switch(s.key){case"ArrowRight":case"ArrowDown":o=(t+1)%n;break;case"ArrowLeft":case"ArrowUp":o=(t-1+n)%n;break;default:return}s.preventDefault(),r(o);const i=s.currentTarget.parentElement,c=i==null?void 0:i.querySelectorAll('[role="radio"]');(u=c==null?void 0:c[o])==null||u.focus()},oo=(e,t,n,r,s,o)=>{let i=-1;return(e||!s&&n===0)&&(i=0),{role:"radio","aria-checked":e,"aria-disabled":t,onKeyDown:rg({disabled:t,currentIndex:n,totalCount:r,onNavigate:o}),tabIndex:i}},ae=()=>{const{stringSet:e}=ie(),t=tg(),n=(i,c)=>{let u=e.A11Y_HINT_OPEN_FILE,d="of";We(i??"")&&(u=e.A11Y_HINT_OPEN_IMAGE,d="oi"),c!==void 0&&(d+=c);const m=t(u,d);return{props:m.props,descriptionNode:m.node}},r=i=>({"aria-label":so(i,e)});return{launcher:{button:({isOpened:i,opensConversationList:c})=>{const u=Uh({intent:$h({isOpened:i,opensConversationList:c}),strings:{openConversation:e.A11Y_OPEN_CONVERSATION,openConversationList:e.A11Y_OPEN_CONVERSATIONS,closeConversation:e.A11Y_CLOSE_CONVERSATION,closeConversationList:e.A11Y_CLOSE_CONVERSATIONS,hintOpenConversation:e.A11Y_HINT_OPEN_CONVERSATION,hintOpenConversationList:e.A11Y_HINT_OPEN_CONVERSATIONS,hintCloseConversation:e.A11Y_HINT_CLOSE_CONVERSATION}});let d="lc";u.hint===e.A11Y_HINT_OPEN_CONVERSATION&&(d="lo"),u.hint===e.A11Y_HINT_OPEN_CONVERSATIONS&&(d="los");const m=t(u.hint,d);return{props:{"aria-label":u.label,...m.props},descriptionNode:m.node}}},messenger:{closeButton:()=>({props:{"aria-label":e.A11Y_CLOSE_MESSENGER},descriptionNode:null}),expandButton:i=>{let c=e.A11Y_EXPAND_MESSENGER;return i&&(c=e.A11Y_COLLAPSE_MESSENGER),{props:{"aria-label":c},descriptionNode:null}},connectionDelayDialog:()=>({props:{"aria-label":e.CONNECTION_DELAY__TITLE},descriptionNode:null})},conversation:{header:{menuButton:()=>{const i=e.A11Y_HINT_OPEN_MENU,c=t(i,"mb");return{props:{"aria-label":e.A11Y_MENU,...c.props},descriptionNode:c.node}},closeConversationButton:()=>{const i=e.A11Y_HINT_CLOSE_CONVERSATION,c=t(i,"cc");return{props:{"aria-label":e.A11Y_CLOSE_CONVERSATION,...c.props},descriptionNode:c.node}},handoffButton:()=>{const i=e.A11Y_HINT_CONNECT_TO_AGENT,c=t(i,"h");return{props:{"aria-label":e.A11Y_CONNECT_AGENT,...c.props},descriptionNode:c.node}},title:(i,c)=>({props:ro(i,c),descriptionNode:null}),memoryIndicator:i=>{let c=e.A11Y_MEMORY_INDICATOR_OFF,u="mof";i&&(c=e.A11Y_MEMORY_INDICATOR_ON,u="mon");const d=t(c,u);return{props:{"aria-label":e.A11Y_MEMORY_INDICATOR_MANAGE,...d.props},descriptionNode:d.node}}},messageInput:{attachFileButton:()=>{const i=e.A11Y_HINT_ATTACH_FILE,c=t(i,"af");return{props:{"aria-label":e.A11Y_ATTACH_FILE,...c.props},descriptionNode:c.node}},sendButton:()=>{const i=e.A11Y_HINT_SEND_MESSAGE,c=t(i,"sm");return{props:{"aria-label":e.A11Y_SEND_MESSAGE,...c.props},descriptionNode:c.node}},textInput:i=>({props:{role:"textbox","aria-label":i,...qh},descriptionNode:null})},suggestedReplies:{item:(i,c)=>{const u=e.A11Y_HINT_SEND_REPLY,d=t(u,`sr${c}`);return{props:{"aria-label":`${e.A11Y_SUGGESTED_REPLY}, ${i}`,...d.props},descriptionNode:d.node}}},feedback:{container:()=>{const i=e.A11Y_HINT_SELECT_RATING,c=t(i,"fb");return{props:c.props,descriptionNode:c.node}},button:(i,c)=>{const u=e.A11Y_HINT_SELECT_RATING,d=t(u,`f${i}`);let m=e.FEEDBACK_BAD;return i==="good"&&(m=e.FEEDBACK_GOOD),{props:{"aria-label":m,...d.props,"aria-pressed":c},descriptionNode:d.node}},optionsBottomSheet:()=>({props:{"aria-label":e.A11Y_FEEDBACK_OPTIONS},descriptionNode:null})},messageList:{item:({label:i,holding:c})=>c?{props:{"aria-hidden":!0},descriptionNode:null}:{props:{role:"listitem",tabIndex:-1,"aria-label":i},descriptionNode:null},typingItem:i=>({props:{role:"listitem",tabIndex:-1,"aria-label":zt({sender:i,message:e.A11Y_TYPING_INDICATOR,codeBlockPlaceholder:e.A11Y_CODE_BLOCK_PLACEHOLDER})},descriptionNode:null})},newMessagesButton:()=>{const i=e.A11Y_HINT_VIEW_NEW_MESSAGES,c=t(i,"nm");return{props:{"aria-label":e.A11Y_SCROLL_TO_NEW_MESSAGES,...c.props},descriptionNode:c.node}},scrollToBottomButton:()=>{const i=e.A11Y_HINT_VIEW_NEW_MESSAGES,c=t(i,"sb");return{props:{"aria-label":e.A11Y_SCROLL_TO_BOTTOM,...c.props},descriptionNode:c.node}},startNewConversationButton:({onActivate:i})=>({props:{...Bt({onActivate:i}),"aria-label":e.TALK_TO_AGENT},descriptionNode:null}),poweredByLink:()=>({props:{"aria-label":`${e.POWERED_BY} Sendbird`},descriptionNode:null}),retryButton:(i=e.RETRY)=>({props:{"aria-label":i},descriptionNode:null}),file:{label:(i,c,u)=>i?so({name:i,mimeType:c,selected:u},e):"",preview:i=>({props:r(i),descriptionNode:null}),buttonLikePreview:({onActivate:i,...c},u)=>{const d=n(c.mimeType,u);return{props:{...Bt({onActivate:i}),...r(c),...d.props},descriptionNode:d.descriptionNode}},removeButton:i=>({props:{"aria-label":e.A11Y_FILE_REMOVE_BUTTON(i)},descriptionNode:null})},csat:{scoresContainer:i=>{const c=e.A11Y_HINT_SELECT_RATING,u=t(c,"cs");return{props:{role:"radiogroup","aria-label":i,...u.props},descriptionNode:u.node}},scoreItem:({score:i,label:c,selected:u,disabled:d,currentIndex:m,totalCount:h,hasSelection:f,onChange:g})=>{var C;const p=c.trim()||c,v=e.A11Y_HINT_SELECT_RATING,S=t(v,`cs${i}`);return{props:{disabled:d,onClick:()=>g(i),...oo(u,d,m,h,f,A=>g(A+1)),...S.props,"aria-label":((C=e.A11Y_CSAT_RATING_LABEL)==null?void 0:C.call(e,i,p))??`${i} / ${h} — ${p}`},descriptionNode:S.node}},submitButton:i=>({props:{"aria-label":i},descriptionNode:null})},form:{button:i=>({props:{"aria-label":i},descriptionNode:null}),textInput:(i,c,u,d)=>({props:{...d!=null&&d.labelId?{"aria-labelledby":d.labelId}:{"aria-label":i},"aria-required":c,"aria-disabled":u},descriptionNode:null}),numberInput:(i,c,u)=>({props:{"aria-label":i,"aria-required":c,"aria-disabled":u},descriptionNode:null}),singleSelectGroup:i=>{const c={role:"radiogroup"};return i&&(c["aria-label"]=i),{props:c,descriptionNode:null}},singleSelectOption:(i,c,u,d,m,h,f)=>({props:{...oo(c,u,d,m,h,f),"aria-label":i},descriptionNode:null}),multiSelectOption:(i,c,u)=>({props:{"aria-label":i,"aria-pressed":c,"aria-disabled":u},descriptionNode:null})}},conversationList:{headerTitle:(i,c)=>({props:ro(i,c),descriptionNode:null}),footer:{button:({onActivate:i})=>({props:{...Bt({onActivate:i}),"aria-label":e.TALK_TO_AGENT},descriptionNode:null})},item:({agent:i,status:c,lastMessage:u,time:d,unreadCount:m,onActivate:h})=>{const f=yh({agent:i,status:c,lastMessage:u,time:d,unreadCount:m},e.A11Y_CONVERSATION_ITEM);if(!h)return{props:{"aria-label":f},descriptionNode:null};const g=e.A11Y_HINT_OPEN_CONVERSATION,p=t(g,"cli");return{props:{...Bt({onActivate:h}),...p.props,"aria-label":f},descriptionNode:p.node}}}}},sg=({title:e,description:t,highlightedText:n})=>{const r=Zm(t,n);return a.createElement(ig,null,a.createElement(ag,null,a.createElement(B,{as:"div",variant:"h1",color:E.themedColor.textHighEmphasis},e),t&&a.createElement(cg,null,a.createElement(B,{as:"div",variant:"body3",color:E.themedColor.textMidEmphasis},r.beforeText,r.highlightedText?a.createElement(lg,null,r.highlightedText):null,r.afterText))))},og=()=>{const{components:e}=Pn.useContext(),{stringSet:t}=ie(),{messenger:n}=ae(),r=jm(),s=r.showDescription?Xm(r.remainingTime):"",o=r.showDescription?t.CONNECTION_DELAY__DESCRIPTION(s):"";return a.createElement(ft,{portalContainerId:Se.WINDOW,visible:r.visible,onClose:me,...n.connectionDelayDialog().props},a.createElement(e.Dialog,{title:t.CONNECTION_DELAY__TITLE,description:o,highlightedText:s||void 0}))},Pn=je({template:og,components:{Dialog:sg}}),ig=_.default.div`width:280px;padding:24px;margin:0 auto;border-radius:4px;box-sizing:border-box;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,ag=_.default.div`display:flex;flex-direction:column;`,cg=_.default.div`margin-top:16px;`,lg=_.default.strong`font-weight:700;`,ug=({url:e})=>ns(e),{Provider:dg,Consumer:aa,useContext:ue}=ve("Messenger");function mg({children:e,state:t,enableCloseConversationButton:n=!1,enableExpandButton:r=!0,enableAutoDisconnectInLauncher:s=!0,...o}){const[i,c]=l.useState(!1),[u,d]=l.useState(!1),m={opened:(t==null?void 0:t.opened)??i,setOpened:(t==null?void 0:t.setOpened)??c,expanded:(t==null?void 0:t.expanded)??u,setExpanded:(t==null?void 0:t.setExpanded)??d},{resolveElement:h}=Jr(),f=l.useCallback(()=>{m.setOpened(!1)},[m.setOpened]);of(m.opened,f);const g=l.useRef(m.opened);l.useLayoutEffect(()=>{const S=g.current&&!m.opened;if(g.current=m.opened,!S)return;const C=mt(o.rootElement),A=h(Se.WINDOW);let y=!1;return Ie(()=>{var T;y||Hf(C,C.activeElement,A)&&((T=h(Se.LAUNCHER))==null||T.focus())}),()=>{y=!0}},[m.opened,o.rootElement,h]);const{Template:p}=Pn.useContext(),v=l.useMemo(()=>{var S;return{...o.handlers,onClickLink:((S=o.handlers)==null?void 0:S.onClickLink)??ug}},[o.handlers]);return a.createElement(td,{...o},S=>a.createElement(dg,{value:{...o,...S,state:m,enableCloseConversationButton:n,enableExpandButton:r,enableAutoDisconnectInLauncher:s,handlers:v}},a.createElement(p,null),e))}const ca=/iPad|iPhone|iPod/.test(navigator.userAgent),hg=/Android/.test(navigator.userAgent),en=e=>ca||hg;let Pt=null,or=null;const fg=(e,t=5e3)=>{Pt&&(clearInterval(Pt),clearTimeout(or));const n=document.title;Pt=setInterval(()=>{document.title=document.title===e?n:e},750),or=setTimeout(()=>{clearInterval(Pt),Pt=null,or=null,document.title=n},t)},la=()=>{Promise.resolve().then(()=>require("./cjs/B93o4u0P.cjs")).then(e=>{new Audio(e.default).play().catch(()=>{})})},ua="0 16px 24px 2px rgba(33, 33, 33, 0.12), 0 6px 30px 5px rgba(33, 33, 33, 0.08), 0 6px 10px -5px rgba(33, 33, 33, 0.04)",xe=U.css`&:focus-visible{outline:2px solid ${E.themedColor.primary};outline-offset:2px;}`,io=e=>{if(typeof e=="string"||typeof e=="number")return String(e)},Fn=({visible:e,title:t,description:n,confirmText:r="OK",cancelText:s,onConfirm:o,onCancel:i,onClose:c,"aria-label":u})=>{const d=l.useId(),m=l.useId(),h=u??io(t)??io(n),f=u?void 0:t?d:n?m:void 0,g=t&&n?m:void 0,p=()=>{c(),Ie(()=>o==null?void 0:o())},v=()=>{c(),Ie(()=>i==null?void 0:i())};return a.createElement(ft,{portalContainerId:Se.WINDOW,visible:e,onClose:c,"aria-label":h,"aria-labelledby":f,"aria-describedby":g},a.createElement(gg,null,a.createElement(pg,null,t&&a.createElement("div",{id:d},a.createElement(B,{variant:"h1",color:E.themedColor.textHighEmphasis},t)),n&&a.createElement(_g,{id:m},a.createElement(B,{variant:"body3",color:E.themedColor.textMidEmphasis},n))),a.createElement(Eg,null,s&&a.createElement(ao,{onClick:v},a.createElement(B,{variant:"button",color:E.themedColor.textHighEmphasis},s)),a.createElement(ao,{onClick:p},a.createElement(B,{variant:"button",color:E.themedColor.primary},r)))))},gg=_.default.div`width:360px;height:auto;padding-block:24px 12px;padding-inline:24px;margin:0 auto;border-radius:4px;box-sizing:border-box;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,pg=_.default.div`margin-bottom:16px;`,_g=_.default.div`margin-top:16px;`,Eg=_.default.div`display:flex;flex-direction:row;justify-content:flex-end;`,ao=_.default.button`all:unset;display:flex;justify-content:center;align-items:center;border-radius:4px;cursor:pointer;background-color:transparent;padding:10px 16px;${xe}`,{Provider:Cg,useContext:Oe}=ve("MessengerSession"),bg=l.forwardRef(function({children:e,...t},n){return a.createElement(Ud,{ref:n,...t},r=>a.createElement(vg,{...r},e))}),vg=({children:e,...t})=>{const{chatSDK:n,logger:r,appId:s,aiAgentId:o,agentPreviewConfigs:i,state:c,handlers:u,dispatcher:d,_aiAgentSDK:m}=ue(),{userSessionInfo:h,authenticate:f,userSession:g,aiAgentInfo:p,launcherInfo:v}=t,[S,C]=l.useState(!1),A=l.useRef(null);pt(n,{async onUserJoined(T,I){var O,k,R,F;T.conversation&&T.conversation.type===he.ConversationType.PROACTIVE&&I.userId===((O=n.currentUser)==null?void 0:O.userId)&&(r.info("messengerSession.onUserJoined: proactive channel joined",T.url),(R=m.session)==null||R._updateActiveChannel({url:T.url,status:"open",conversationStatus:(k=T.conversation)==null?void 0:k.status}),c.setOpened(!0),Sg({sound:document.hidden||!c.opened}),(F=A.current)==null||F.call(A,{channel:T}))}}),l.useEffect(()=>{f().then(({launcher:T})=>{T.auto_open&&!en()&&setTimeout(()=>c.setOpened(!0),500)}).catch(T=>{var I;r.error("messengerSession: failed to initialize",T),(I=u==null?void 0:u.onInitializeFailed)==null||I.call(u,T)})},[n,s,o,h==null?void 0:h.userId]),l.useEffect(()=>{const T=()=>C(!0);return d.subscribe(Be.AnonymousSessionTokenExpired,T),()=>d.unsubscribe(Be.AnonymousSessionTokenExpired,T)},[d]);const y=l.useCallback(()=>{t.deauthenticate().finally(()=>window.location.reload())},[t.deauthenticate]);return!g||!p||!v?null:a.createElement(Cg,{value:{...t,userSession:g,aiAgentInfo:{...p,...i==null?void 0:i.bot},launcherInfo:{...v,...i==null?void 0:i.launcher},registerOnJoinedProactiveConversation:T=>A.current=T}},e,a.createElement(Fn,{visible:S,title:"Session timed out",description:"Start a new conversation.",onConfirm:y,onClose:me}))};function Sg({sound:e}){fg("🔔You have received a new message"),e&&la()}const Mn=`@${He}-focused-channel`,da=`${Date.now()}-${Math.random().toString(36).slice(2)}`,yg=()=>{try{const e=localStorage.getItem(Mn);return e?JSON.parse(e).channelUrl??null:null}catch{return null}},co=e=>{try{localStorage.setItem(Mn,JSON.stringify({channelUrl:e,tabId:da}))}catch{}},lo=()=>{try{const e=localStorage.getItem(Mn);if(!e)return;JSON.parse(e).tabId===da&&localStorage.removeItem(Mn)}catch{}},Ag=(e,t)=>(l.useEffect(()=>{if(!t||!e)return;const n=()=>co(e),r=()=>lo();return document.hasFocus()&&co(e),window.addEventListener("focus",n),window.addEventListener("blur",r),()=>{window.removeEventListener("focus",n),window.removeEventListener("blur",r),lo()}},[t,e]),{isChannelViewedInAnyTab:()=>document.hasFocus()||yg()===e}),Tg=e=>{const{config:t,chatSDK:n}=ue(),{sdkUser:r}=Oe(),s=t.conversation.messageAlertSoundEnabled,{isChannelViewedInAnyTab:o}=Ag(e,s);pt(n,{onMessageReceived(i,c){if(!s||i.url!==e||o())return;(tt(c)&&c.sender.userId!==(r==null?void 0:r.userId)||c.isAdminMessage()&&!c.silent)&&la()}})};function Ig(e){return new Promise(t=>{const n=new Image;n.onload=function(){const r=String(n.width),s=String(n.height);URL.revokeObjectURL(n.src),t({width:r,height:s})},n.src=URL.createObjectURL(e)})}async function xg(e){if("file"in e&&e.file instanceof File&&e.file.type.startsWith("image/")){const{width:t,height:n}=await Ig(e.file);return new Le.MessageMetaArray({key:Jo,value:[t,n]})}}const Rg=({onScrollAfterSendMessage:e})=>{const{agentPreviewConfigs:t,handlers:n}=ue(),r=l.useRef(t==null?void 0:t.agentAttributes);return r.current=t==null?void 0:t.agentAttributes,{onBeforeSendMessage:async s=>{const o=await xg(s),i={...s,metaArrays:o?[o]:void 0},c=Mg(r.current);return c?{...i,data:JSON.stringify(c)}:i},onAfterSendMessage:s=>{var o,i,c;e(),(o=n==null?void 0:n.onMessageSend)==null||o.call(n,s.message),s.sendingStatus===Le.SendingStatus.SUCCEEDED?(i=n==null?void 0:n.onCustomEvent)==null||i.call(n,{type:"message-sent-succeeded",data:{message:s}}):s.sendingStatus===Le.SendingStatus.PENDING&&((c=n==null?void 0:n.onCustomEvent)==null||c.call(n,{type:"message-sent-pending",data:{message:s}}))}}},Mg=e=>{if(!e)return null;const t={};return e.ai&&Object.keys(e.ai).length>0&&(t.ai_attrs=e.ai),e.safeguard&&Object.keys(e.safeguard).length>0&&(t.safeguard_attrs=e.safeguard),typeof e.use_prompt_cache=="boolean"&&(t.use_prompt_cache=e.use_prompt_cache),Object.keys(t).length>0?t:null},Tt=50,ir=Tt-40,{Provider:wg,useContext:ma}=ve("ConversationScroll"),uo={viewport:0,contentHeight:0,contentSnapshotHeight:0,shouldRecalc:!1,shouldUpdate:!1},ar=e=>Math.max(0,e.scrollHeight-e.scrollTop-e.clientHeight),mo=e=>Array.from(e.querySelectorAll(`#${He}-message-item`));function kg({scrollMode:e,messageStackDirection:t,children:n}){const r=l.useRef(null),s=l.useRef({mutation:null,resize:null,resizeTargets:new Set}),o=l.useRef({distanceFromBottom:0,prevScrollTop:0}),i=l.useRef({awayByUser:!1,programmatic:!1,streaming:!1,reconcileTimer:null,userMessageTimer:null}),c=l.useRef(uo),[u,d]=l.useState(0),[m,h]=l.useState(0),[f,g]=l.useState(!1),[p,v]=l.useState(!1),[S,C]=l.useState(!0),A=$=>{const M=ar($);return o.current.distanceFromBottom=M,h(M),M},y=()=>{const $=i.current;$.reconcileTimer&&(clearTimeout($.reconcileTimer),$.reconcileTimer=null)},T=l.useCallback(()=>{const $=s.current;$.mutation&&($.mutation.disconnect(),$.mutation=null),$.resize&&($.resize.disconnect(),$.resize=null),$.resizeTargets.clear()},[]),I=l.useMemo(()=>f||t==="bottom"?"auto":e,[f,t,e]),N=()=>{c.current.contentSnapshotHeight=c.current.contentHeight,c.current.shouldUpdate=!0,c.current.shouldRecalc=!0},O=()=>{const $=r.current;!$||!c.current.shouldUpdate||d(M=>{c.current.shouldUpdate=!1;const{contentHeight:x,contentSnapshotHeight:L,shouldRecalc:P}=c.current,X=$.clientHeight;if(L>x)return M;const se=k($,{messageType:"outgoing"});let Z=0;if(se){const be=se.message.offsetTop-ir+X;Z=Math.max(0,be-x)}else{const be=x-L,Xe=X-ir;Z=Math.max(0,be-Xe)}return M===0||Z!==M||P?(c.current.shouldRecalc=!1,Z):M})},k=l.useCallback(($,M)=>{const{messageType:x="all"}=M??{},L=mo($);let P=L;x==="outgoing"&&(P=L.filter(it=>it.getAttribute("data-layout-id")==="outgoingmessage"));const X=P[P.length-1];if(!X)return null;const se=$.getBoundingClientRect(),Z=X.getBoundingClientRect(),be=$.scrollTop+(Z.top-se.top),Xe=be+X.offsetHeight;return{message:X,scrollTop:be,lastMessageBottom:Xe}},[]),R=l.useCallback(()=>{const $=r.current;if(!$||I!=="fixed")return;const M=k($);c.current.contentHeight=(M==null?void 0:M.lastMessageBottom)??$.scrollHeight,!i.current.streaming&&c.current.contentSnapshotHeight>0&&N(),i.current.programmatic?o.current.distanceFromBottom=ar($):A($),O()},[I,k]),F=l.useCallback(()=>{T(),y(),c.current=uo,d(0),h(0),C(!0),o.current.distanceFromBottom=0,o.current.prevScrollTop=0,i.current.awayByUser=!1,i.current.programmatic=!1},[T]),D=l.useCallback(($=!0)=>{const M=o.current.distanceFromBottom>Tt;if(i.current.awayByUser=!1,h(0),!M){Ie(()=>{const x=r.current;x&&!i.current.awayByUser&&x.scrollTo({top:x.scrollHeight,behavior:"auto"})});return}i.current.programmatic||(i.current.programmatic=!0,C(!1),y()),Ie(()=>{const x=r.current;if(!x){i.current.programmatic=!1,C(!0);return}if(i.current.awayByUser){i.current.programmatic=!1,A(x),C(!0);return}const L=()=>{if(r.current!==x){i.current.programmatic=!1,r.current&&A(r.current),C(!0);return}i.current.programmatic=!1,A(x),C(!0)};if($&&!i.current.reconcileTimer){const P=setTimeout(L,500);i.current.reconcileTimer=P,x.addEventListener("scrollend",()=>{clearTimeout(P),i.current.reconcileTimer=null,L()},{once:!0})}x.scrollTo({top:x.scrollHeight,behavior:$?"smooth":"auto"}),$||L()})},[]),Q=l.useCallback(()=>{const $=r.current;if($){if(i.current.awayByUser){A($);return}D(!1)}},[D]),re=l.useCallback(()=>{const $=r.current,M=s.current;if(!$||!M.resize)return;const x=new Set(mo($));for(const L of M.resizeTargets)x.has(L)||(M.resize.unobserve(L),M.resizeTargets.delete(L));for(const L of x)M.resizeTargets.has(L)||(M.resize.observe(L),M.resizeTargets.add(L))},[]),G=l.useCallback($=>{T();const M=s.current;typeof ResizeObserver<"u"&&(M.resize=new ResizeObserver(Q),re());const x=new MutationObserver(()=>{re(),Q()});M.mutation=x,x.observe($,{childList:!0})},[T,Q,re]),H=l.useCallback($=>{if(!$){r.current=null,T();return}if(r.current=$,I!=="fixed"){G($);return}F(),c.current.viewport=$.clientHeight;const M=new MutationObserver(()=>{R()});s.current.mutation=M,M.observe($,{childList:!0,subtree:!0})},[T,I,R,F,G]),q=l.useCallback(()=>{const $=r.current;if(!$)return;const M=k($,{messageType:"outgoing"});M&&($.scrollTo({top:M.message.offsetTop-ir,behavior:"smooth"}),i.current.userMessageTimer&&clearTimeout(i.current.userMessageTimer),i.current.userMessageTimer=setTimeout(()=>{v(!1)},500))},[k]),J=($,M,x)=>{const L=ar($);if(x&&L>Tt){i.current.programmatic=!1,i.current.awayByUser=!0,y(),A($),C(!0),o.current.prevScrollTop=M;return}o.current.distanceFromBottom=L},K=($,M,x)=>{const P=A($)<=Tt;M&&!P&&(i.current.awayByUser=!0,y()),x&&P&&(i.current.awayByUser=!1)},z=$=>{const{scrollTop:M}=$.currentTarget,x=o.current.prevScrollTop;i.current.programmatic?J($.currentTarget,M,M<x):K($.currentTarget,M<x,M>x),o.current.prevScrollTop=M},Y=l.useCallback(()=>{I==="fixed"&&(v(!0),N())},[I]),W=l.useCallback(()=>{I==="fixed"?setTimeout(()=>q(),300):D()},[I,q]),V=l.useCallback($=>{i.current.streaming=$,I==="fixed"?N():i.current.awayByUser||D()},[I,D]),ee=l.useCallback($=>{g($),$&&(d(0),I==="fixed"&&T())},[T,I]),w=l.useCallback($=>{I==="auto"&&$&&!i.current.awayByUser&&D()},[I,D]),Re=!(m<=Tt)&&!p,Te=l.useCallback(()=>o.current.distanceFromBottom>Tt,[]);return a.createElement(wg,{value:{ref:H,state:{bottomSpace:u,isAwayFromBottom:Re,isScrollPositionReconciled:S,shouldCountNewMessages:Te},props:{onScroll:z},actions:{scrollToBottom:D,onBeforeMessageSend:Y,onAfterMessageSend:W,onStreamingUpdate:V,onConversationClosed:ee,onTypingIndicatorUpdate:w}}},n)}const{Provider:Lg,Context:Og,useContext:Ae}=ve("Conversation"),Ng=({children:e})=>{var s;const{channelSource:t}=Ae(),n=(s=t.channel)==null?void 0:s.url,{checkForUserActionRequired:r}=km(n);return l.useEffect(()=>{var i;const o=(i=t.channel)==null?void 0:i.lastMessage;o&&r(o)},[t.channel,r]),a.createElement(a.Fragment,null,e)},Dg=({channelUrl:e,onClearChannelUrl:t,onNavigateToConversationList:n,conversationStatsEnabled:r,shouldMarkAsRead:s,shouldInitializeConversation:o,initialUserMessage:i,children:c})=>{const{activeChannel:u,refreshActiveChannel:d}=Oe(),m=ma(),h=e||(u==null?void 0:u.url);Tg(h);const{onBeforeSendMessage:f,onAfterSendMessage:g}=Rg({onScrollAfterSendMessage:()=>{m.actions.onAfterMessageSend()}}),p=l.useCallback(A=>(m.actions.onBeforeMessageSend(),f(A)),[m.actions,f]),v=l.useCallback(A=>{const y=A.some(T=>we.isStreaming(T));m.actions.onStreamingUpdate(y)},[m.actions.onStreamingUpdate]),S=l.useCallback(A=>{m.actions.onConversationClosed(A===he.ConversationStatus.CLOSED)},[m.actions.onConversationClosed]),C=l.useCallback(async()=>{await d(),e&&(t==null||t())},[d,e,t]);return a.createElement(dm,{key:h,channelUrl:h,onBeforeSendMessage:p,onAfterSendMessage:g,onMessagesUpdated:v,onMessagesReceived:v,onChannelDeleted:C,onConversationStatusChanged:S,conversationStatsEnabled:r,shouldMarkAsRead:s,shouldInitializeConversation:o,initialUserMessage:i,shouldCountNewMessages:m.state.shouldCountNewMessages},A=>a.createElement(Lg,{value:{...A,scrollSource:m,goToActiveConversation:C,onNavigateToConversationList:n}},a.createElement(Ng,null,c)))},ha=({children:e,...t})=>{const{config:n}=ye(),{agentPreviewConfigs:r}=ue(),s=n.conversation.list.scrollMode,o=r==null?void 0:r.messageStackDirection;return a.createElement(kg,{scrollMode:s,messageStackDirection:o},a.createElement(Dg,{...t},e))},rs=l.createContext({onDrop:me,subscribe:()=>me}),Tr=({children:e})=>{const t=l.useRef(new Set);return a.createElement(rs.Provider,{value:{onDrop:n=>{var r;if(n.preventDefault(),(r=n.dataTransfer)!=null&&r.files){const s=Array.from(n.dataTransfer.files);s.length>0&&t.current.forEach(o=>o(s))}},subscribe:n=>(t.current.add(n),()=>t.current.delete(n))}},e)},$g=({onDropFiles:e})=>{const{subscribe:t}=l.useContext(rs);l.useEffect(()=>t(e),[e])};Tr.Consumer=({children:e})=>{const{onDrop:t}=l.useContext(rs);return e({onDrop:t,onDragOver:s=>s.preventDefault()})};const fa=ve("WindowTitle",{hasWindowTitleReference:!1,isTitlePending:!1,isWindowNameReady:!0,registerWindowTitleReference:()=>me,registerWindowTitlePending:()=>me}),Pg=fa.Provider,ga=fa.useContext,ho=()=>{const e=l.useRef(0),[t,n]=l.useState(!1),r=l.useCallback(()=>{let s=!0;return e.current+=1,e.current===1&&n(!0),()=>{s&&(s=!1,e.current=Math.max(0,e.current-1),e.current===0&&n(!1))}},[]);return[t,r]},ss=({children:e})=>{const[t,n]=ho(),[r,s]=ho(),o=!r||t,i=l.useMemo(()=>({hasWindowTitleReference:t,isTitlePending:r,isWindowNameReady:o,registerWindowTitleReference:n,registerWindowTitlePending:s}),[t,r,n,s]);return a.createElement(Pg,{value:i},e)},Un=ga,pa=({enabled:e,label:t})=>{const{registerWindowTitleReference:n,registerWindowTitlePending:r}=ga(),s=e&&t.trim().length>0;return l.useLayoutEffect(()=>{if(e)return r()},[r,e]),l.useLayoutEffect(()=>{if(s)return n()},[n,s]),{enabled:s,id:s?Se.WINDOW_TITLE:void 0}},Fg=(e,t)=>{const r=(t?Yt(e,t):null)??Gf(e)??e;r===e&&!e.hasAttribute("tabindex")&&e.setAttribute("tabindex","-1"),r.focus({focusVisible:!1})},_a=(e,{enabled:t,ready:n,nameReady:r=!0,targetSelector:s,suppressed:o=!1})=>{const i=l.useRef(!1);l.useEffect(()=>{if(!t){i.current=!1;return}if(i.current||!e.current||o||s&&!n)return;const c=ts(e.current)!=null;if(!s&&!c&&!n)return;let u=!1;const d=()=>{u||i.current||!e.current||(i.current=!0,Fg(e.current,s))};if(r)return Ie(d),()=>{u=!0};const m=setTimeout(()=>Ie(d),qi);return()=>{u=!0,clearTimeout(m)}},[t,n,r,s,e,o])},Ug=(e,t)=>{const{announcementsEnabled:n}=lt(),{channelSource:r}=Ae(),{isWindowNameReady:s}=Un(),o=Zi(),i=r.channel!=null||r.error!=null;_a(e,{enabled:n,ready:i,nameReady:s,targetSelector:t==="messageInput"?Vh:void 0,suppressed:o})},Bg=()=>{var s;const{_statsEnabled:e,channelSource:t}=Ae(),n=(s=t.channel)==null?void 0:s.url,r=l.useCallback(o=>{const i=()=>{o(vr()?"backgrounded":"foregrounded")};return document.addEventListener("visibilitychange",i),()=>document.removeEventListener("visibilitychange",i)},[]);eh({channelUrl:n,enabled:e,isInitiallyBackgrounded:vr,isForegrounded:Wh,subscribeToForegroundState:r})},Hg=e=>We(e)||jt(e);function Gg(e,t){return e.filter(n=>we.isWelcomeMessage(n,t))}const Ea=(e,{previewWelcomeMessages:t,aiAgentUserId:n})=>e.filter(r=>t.length>0?!we.isWelcomeMessage(r,n):!0),zg=[],Ca=()=>{var p,v,S,C,A,y;const{agentPreviewConfigs:e={},aiAgentId:t}=ue(),{aiAgentInfo:n,userSession:r}=Oe(),{channelSource:s,messageSource:o,state:{input:i,streamAnimation:c}}=Ae(),u=e.welcomeMessages??zg,d=l.useMemo(()=>Ea(o.messages,{previewWelcomeMessages:u,aiAgentUserId:t}),[t,o.messages,u]),m=ct(s.channel),h=(v=(p=ii(s.channel,r.userId))==null?void 0:p.nickname)==null?void 0:v.trim(),f=m?(C=(S=s.channel)==null?void 0:S.name)==null?void 0:C.trim():(A=n==null?void 0:n.nickname)==null?void 0:A.trim(),g=h||f||void 0;return{initialized:o.initialized,channelUrl:(y=s.channel)==null?void 0:y.url,agentName:g,isClosed:De(s.channel),isHandedOff:m,messages:d,filteredMessagesCount:d.length,hasWelcomeMessages:u.length>0,inputDisabled:i.disabled,inputDisabledBy:i.disabledBy,isStreamAnimating:c.isAnimating,currentUserId:r.userId}},Vg=(e={})=>{const{announceScreenEntry:t,announcementsEnabled:n}=lt(),{initialized:r=!1,channelUrl:s,agentName:o,isClosed:i=!1,messages:c=[],hasWelcomeMessages:u=!1}=e,d=l.useRef(null),m=l.useMemo(()=>c.some(f=>Me.isAdmin(f)&&Me.isCSAT(f)),[c]),h=c.length===0&&!u;l.useEffect(()=>{if(!n){d.current=null;return}!r||!s||d.current!==s&&(t({screen:"conversation",agentName:o,isClosed:i,hasCSAT:m,...h?{isEmpty:!0}:{}}),d.current=s)},[o,t,n,s,m,r,i,h])},qg=()=>{const e=Ca();Vg(e)},Kg=e=>({image:e.A11Y_RECEIVED_FILE_IMAGE,video:e.A11Y_RECEIVED_FILE_VIDEO,pdf:e.A11Y_RECEIVED_FILE_PDF,document:e.A11Y_FILE_DOCUMENT,receivedFilesImageCount:e.A11Y_RECEIVED_FILES_IMAGE_COUNT,multipleFilesCount:e.CONVERSATION_LIST__MULTIPLE_FILES_COUNT,codeBlockPlaceholder:e.A11Y_CODE_BLOCK_PLACEHOLDER}),fo=(e,t,n=ut.format)=>{const r=Ih(e,Kg(t)),s="sender"in e?e.sender:void 0,o=e.createdAt!=null&&e.createdAt!==0?n(e.createdAt,t.DATE_FORMAT__MESSAGE_TIMESTAMP):void 0;return{senderName:typeof(s==null?void 0:s.nickname)=="string"&&s.nickname.trim()||void 0,body:r||void 0,time:o}},Yg={senderName:!0,body:!0,time:!0},Wg=Object.keys(Yg),jg=(e,t)=>Wg.every(n=>e[n]===t[n]),go=2e3,po=400,Ir=e=>{const t=new Set;return"reqId"in e&&typeof e.reqId=="string"&&e.reqId.length>0&&t.add(`req:${e.reqId}`),"messageId"in e&&e.messageId>0&&t.add(`message:${String(e.messageId)}`),[...t]},ba=e=>{if(!Me.isAdmin(e)||!Me.isCSAT(e))return null;const t=Nh(e);return t?`csat:${t}`:null},Xg=e=>{const t=new Set;for(const n of e){const r=ba(n);r&&t.add(r)}return t},Zg=(e,t)=>{for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(r&&Ir(r).some(s=>t.includes(s)))return r}},cr=(e,t)=>e.some(n=>t.includes(n)),_o=()=>typeof document>"u"?null:document.activeElement instanceof HTMLElement?document.activeElement:null,lr=e=>new Map(e.map(({key:t,sendingStatus:n})=>[t,n])),Jg=()=>{const{announceStatus:e,announcementsEnabled:t}=lt(),{stringSet:n,format:r}=ie(),{channelUrl:s,messages:o,isClosed:i,isHandedOff:c,agentName:u,initialized:d,inputDisabled:m,inputDisabledBy:h,isStreamAnimating:f,currentUserId:g}=Ca(),{outgoingMessageStates:p,outgoingMessageStatusSignature:v}=l.useMemo(()=>{if(!g)return{outgoingMessageStates:[],outgoingMessageStatusSignature:""};const z=o.flatMap(Y=>{const W=Lh(Y,g);return!W||!("sendingStatus"in Y)?[]:[{key:W,sendingStatus:Y.sendingStatus}]});return{outgoingMessageStates:z,outgoingMessageStatusSignature:z.map(({key:Y,sendingStatus:W})=>`${Y}:${W}`).join(",")}},[g,o]),S=l.useRef({isClosed:!1,isHandedOff:!1,inputDisabled:m,inputDisabledBy:h,outgoingMessageStatuses:lr(p)}),C=l.useRef({messages:o,currentUserId:g,inputDisabledBy:h,isStreamAnimating:f,stringSet:n,format:r}),A=l.useRef([]),y=l.useRef(null),T=l.useRef([]),I=l.useRef(new Set),N=l.useRef(new Set),O=l.useRef(!1),k=l.useRef(s);C.current={messages:o,currentUserId:g,inputDisabledBy:h,isStreamAnimating:f,stringSet:n,format:r};const R=()=>C.current.isStreamAnimating||C.current.inputDisabledBy==="ai_responding",F=()=>{y.current!=null&&(clearTimeout(y.current),y.current=null)},D=(z,Y,W)=>{const V=W==null?void 0:W.replaceableForMs;if(z.length===0||!V)return;const ee=Date.now();T.current=[...T.current.filter(({replaceableUntil:w})=>w>ee),{eventKeys:z,parts:Y,replaceableUntil:ee+V}]},Q=()=>A.current.length>0,re=()=>{A.current=[]},G=()=>{const[z,...Y]=A.current;if(!z)return!1;A.current=Y;const{eventKeys:W,parts:V,dedupeKey:ee}=z,w=Te=>{D(W,Te,{replaceableForMs:W.length>0?go:void 0}),e({event:"newMessage",...Te},ee?{dedupeKey:ee}:void 0)};if(W.length===0)return w(V),!0;const _e=C.current,Re=Zg(_e.messages,W);if(Re){const Te=fo(Re,_e.stringSet,_e.format);return w(Te),!0}return w(V),!0},H=()=>{for(F();G(););},q=(z=go)=>{F(),y.current=setTimeout(()=>{if(y.current=null,R())return;const Y=_o(),[W]=A.current;if(!W)return;if(W.focusTarget!==Y){A.current=[{...W,focusTarget:Y},...A.current.slice(1)],q(po);return}G()&&Q()&&q(po)},z)},J=(z,Y,W)=>{const V={eventKeys:Y,parts:z,focusTarget:_o(),dedupeKey:W?W.dedupeKey??void 0:Y[0]},ee=Y.length===0?-1:A.current.findIndex(({eventKeys:w})=>cr(w,Y));ee>=0?A.current=A.current.map((w,_e)=>_e===ee?{...V,dedupeKey:W?V.dedupeKey:w.dedupeKey}:w):A.current=[...A.current,V],q()},K=(z,Y,W)=>{if(z!=="messagesUpdated"||Y.length===0)return!1;const V=Date.now(),ee=T.current.find(w=>w.replaceableUntil>V&&cr(w.eventKeys,Y));return ee?!jg(W,ee.parts):!1};l.useEffect(()=>{const z=k.current!==s;(!t||!d||z)&&(O.current=!1,N.current.clear(),re(),T.current=[],I.current.clear(),F(),z&&(k.current=s),!t||!d)||O.current||(O.current=!0,k.current=s,S.current={isClosed:i,isHandedOff:c,inputDisabled:m,inputDisabledBy:h,outgoingMessageStatuses:lr(p)},I.current=new Set(o.flatMap(Y=>{if(!we.isStreaming(Y))return[];const W="sender"in Y?Y.sender:void 0;return(W==null?void 0:W.userId)===C.current.currentUserId?[]:Ir(Y)})),N.current=Xg(o))},[e,t,s,d,m,i,c,v]),l.useEffect(()=>{const z=(Y,W)=>{const V=C.current,ee=Ir(Y),w=ba(Y);if(w!=null){if(N.current.has(w))return;N.current.add(w),e({event:"csatDisplayed"});return}if(we.isStreaming(Y)){ee.forEach(P=>{I.current.add(P)});return}const _e=ee.filter(P=>I.current.has(P)),Re=W==="messagesUpdated"&&_e.length>0;Re&&_e.forEach(P=>{I.current.delete(P)});const Te=W==="messagesUpdated"&&A.current.some(({eventKeys:P})=>cr(P,ee)),$=fo(Y,V.stringSet,V.format),M=K(W,ee,$);if(!Re&&W!=="messagesAdded"&&!Te&&!M)return;const x=M?{dedupeKey:null}:void 0;if(Re||R()||Te){J($,[...new Set([..._e,...ee])],x);return}if(M){J($,ee,x);return}Q()&&H();const L=ee[0];e({event:"newMessage",...$},L?{dedupeKey:L}:void 0)};return bi.subscribe(Y=>{if(!O.current||Y.channelUrl!==s||Y.kind==="initialized"||Y.kind==="messagesDeleted"||!Dh(Y.source))return;const W=C.current.currentUserId;for(const V of Y.messages)V&&Oh(V,W)&&z(V,Y.kind)})},[e,s]),l.useEffect(()=>{O.current&&(R()||Q()&&q())},[h,f]),l.useEffect(()=>()=>{F()},[]),l.useEffect(()=>{if(!O.current)return;const z=S.current,Y=z.outgoingMessageStatuses;z.outgoingMessageStatuses=lr(p),p.some(({key:V,sendingStatus:ee})=>{const w=Y.get(V);return w!==void 0&&w!=="failed"&&ee==="failed"})&&e({event:"sendFailed"})},[e,v]),l.useEffect(()=>{if(!O.current)return;const z=S.current;i&&!z.isClosed&&e({event:"conversationClosed"}),z.isClosed=i},[e,i]),l.useEffect(()=>{if(!O.current)return;const z=S.current;c&&!z.isHandedOff&&e({event:"agentConnected",agentName:u}),z.isHandedOff=c},[u,e,c]),l.useEffect(()=>{if(!O.current)return;const z=S.current;m&&h!=="ai_responding"&&(!z.inputDisabled||z.inputDisabledBy==="ai_responding")&&e({event:"inputDisabled"}),z.inputDisabled=m,z.inputDisabledBy=h},[e,m,h])},Qg=()=>{const{channelSource:e}=Ae(),t=xi(e.channel);return!(t!=null&&t.user.userId)||!t.user.nickname?null:{userId:t.user.userId,nickname:t.user.nickname}},ep=e=>{const{announceStatus:t,announcementsEnabled:n}=lt();Pm(e??null,r=>{t({event:"typing",agentName:r})},1e4,n)},tp=()=>{const e=Qg();ep(e)},te=({type:e,size:t=24,className:n,color:r})=>{const{icons:s}=xf(),o=s[e];return a.createElement(np,{className:n},a.createElement(o,{size:t,color:r??E.color.primary.main,flipInRtl:bf.has(e)}))},np=_.default.span.attrs({"aria-hidden":"true"})`
|
|
81
81
|
display: inline-flex;
|
|
82
82
|
&:focus {
|
|
83
83
|
outline: none;
|
|
84
84
|
}
|
|
85
|
-
`,Yg=({visible:e,onClose:t,children:n,"aria-label":r})=>a.createElement(ut,{portalContainerId:Se.WINDOW,visible:e,onClose:t,"aria-label":r},a.createElement(Zg,null,n)),Wg=({onClick:e,destructive:t,icon:n,initialFocus:r,children:s})=>a.createElement(jg,{onClick:e,$destructive:t,"data-sb-initial-focus":r?"true":void 0},n&&a.createElement(Xg,null,a.createElement(ee,{type:n,size:24,color:E.themedColor.primary})),s),at=Object.assign(Yg,{ActionItem:Wg}),jg=_.default.button`all:unset;display:flex;align-items:center;gap:24px;width:100%;padding:12px 24px;cursor:pointer;color:${({$destructive:e})=>e?E.themedColor.error:E.themedColor.textHighEmphasis};${Re}`,Xg=_.default.div`display:flex;align-items:center;justify-content:center;flex-shrink:0;`,Zg=_.default.div`position:absolute;left:0;right:0;bottom:0;border-radius:12px 12px 0 0;flex-direction:column;align-items:flex-end;margin:0 auto;box-sizing:border-box;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,fo=40,go=.9,Jg="[data-message-listitem]",Qg='input, textarea, select, [role="textbox"], [contenteditable="true"]',ep=({event:e,list:t,isMessageAnchor:n})=>{switch(e.key){case"PageDown":return t.clientHeight*go;case"PageUp":return t.clientHeight*-go;case"ArrowDown":return n?fo:void 0;case"ArrowUp":return n?fo*-1:void 0;default:return}},tp=({listRef:e,syncScrollPosition:t})=>l.useCallback(n=>{const r=e.current;if(!r||n.defaultPrevented||n.metaKey||n.altKey||n.ctrlKey)return;const s=n.target;if(!s||!r.contains(s)||s.closest(Qg))return;const o=s===r||s.matches(Jg),i=ep({event:n,list:r,isMessageAnchor:o});if(i==null||i===0)return;const c=Math.max(0,r.scrollHeight-r.clientHeight),u=Math.min(c,Math.max(0,r.scrollTop+i));u!==r.scrollTop&&(n.preventDefault(),t(u))},[e,t]),np="[data-message-listitem]",rp=e=>Math.min(Math.max(0,e),1),sp=e=>{const n=e.getRootNode().activeElement,r=n==null?void 0:n.closest(np),s=n===e||n===r;return!n||!e.contains(n)?null:s?e:n},op=({list:e,focusRestoreTarget:t})=>{if(!t)return;const r=e.getRootNode().activeElement,s=r===e||e.contains(r),o=t===e||e.contains(t);s&&o&&t.focus({preventScroll:!0})},ip=({depsForResetScrollPositionToBottom:e,listRef:t,loadThreshold:n,messagesLength:r,onLoadNext:s,onLoadPrev:o,onScroll:i})=>{const c=l.useRef(!1),u=l.useRef(void 0),d=l.useRef(0),m=l.useRef(0),h=l.useRef(null),f=l.useRef(null),g=l.useRef(null);l.useLayoutEffect(()=>{t.current&&(t.current.scrollTop=t.current.scrollHeight)},e),l.useLayoutEffect(()=>{const p=t.current;p&&(u.current==="top"&&(p.scrollTop=p.scrollHeight-m.current,op({list:p,focusRestoreTarget:h.current}),h.current=null),u.current==="bottom"&&(p.scrollTop=d.current),u.current=void 0)},[t,r]);const C=l.useCallback(async p=>{const A=t.current;if(!A||(i==null||i(p),m.current=A.scrollHeight-A.scrollTop,d.current=A.scrollTop,c.current))return;const y=A.clientHeight*rp(n);if(A.scrollTop<=y){c.current=!0,u.current="top",h.current=sp(A),await o(),c.current=!1;return}if(A.scrollHeight-A.scrollTop-A.clientHeight<=y){c.current=!0,u.current="bottom",await s(),c.current=!1;return}u.current=void 0},[t,n,s,o,i]),b=l.useCallback(p=>{const A=t.current;if(!A)return;const y=g.current;if(y!=null){if(y===A.scrollTop){g.current=null;return}g.current=null}const T=f.current;if(T!=null&&T===A.scrollTop){f.current=null,g.current=A.scrollTop,C(p);return}f.current=null,C(p)},[C,t]),S=l.useCallback(p=>{const A=t.current;A&&(f.current=p,g.current=null,A.scrollTop=p,A.dispatchEvent(new Event("scroll",{bubbles:!0})))},[t]);return l.useLayoutEffect(()=>()=>{f.current=null,g.current=null},[]),{handleScroll:b,syncScrollPosition:S}},ap=l.forwardRef(function(t,n){const{messages:r,renderMessage:s,loading:o,LoadingComponent:i,error:c,ErrorComponent:u,empty:d,EmptyComponent:m,messageTopArea:h,messageBottomArea:f,overlayArea:g,onLoadPrev:C,onLoadNext:b,loadThreshold:S=.05,onScroll:p=fe,depsForResetScrollPositionToBottom:A,stackDirection:y="top",bottomSpacerHeight:T=0,"aria-label":I}=t,L=l.useRef(null),N=l.useCallback($=>{L.current=$,n&&(typeof n=="function"?n($):n.current=$)},[n]),{handleScroll:k,syncScrollPosition:w}=ip({depsForResetScrollPositionToBottom:A,listRef:L,loadThreshold:S,messagesLength:r.length,onLoadNext:b,onLoadPrev:C,onScroll:p}),z=tp({listRef:L,syncScrollPosition:w});return c?a.createElement(a.Fragment,null,u):o?a.createElement(a.Fragment,null,i):a.createElement(cp,{id:"infinite-list-container"},a.createElement(lp,{id:"infinite-list-inner",ref:N,onScroll:k,onKeyDown:z,role:"list","aria-label":I,tabIndex:0},y==="bottom"&&a.createElement("div",{style:{flexGrow:1}}),h,d?m:r.map(($,q)=>s({message:$,index:q})),f,T>0&&a.createElement("div",{style:{minHeight:T}})),a.createElement(up,{id:"infinite-list-overlay-container"},a.createElement(dp,{id:"infinite-list-overlay"},g)))}),cp=_.default.div`display:flex;position:relative;flex:1;overflow:hidden;`,lp=_.default.div`display:flex;flex:1;flex-direction:column;overflow-x:hidden;overflow-y:auto;overscroll-behavior:contain;scrollbar-color:${E.themedColor.textLowEmphasis}transparent;&::-webkit-scrollbar-thumb:hover{background-color:transparent;}`,up=_.default.div`position:absolute;top:0;bottom:0;left:0;right:0;pointer-events:none;`,dp=_.default.div`pointer-events:auto;`,Qe=({as:e,type:t,size:n=16,color:r,disabled:s,children:o,...i})=>{const c=s?E.themedColor.textDisabled:E.themedColor.textHighEmphasis;return a.createElement(mp,{as:e,disabled:s,...i},a.createElement(ee,{type:t,size:n,color:r??c}),o)},mp=_.default.button`all:unset;padding:4px;cursor:pointer;display:flex;align-items:center;justify-content:center;${Re}&:disabled{cursor:not-allowed;}`,gt=({className:e,children:t,size:n=26})=>a.createElement(hp,{className:e,$size:n},t??a.createElement(ee,{type:"spinner",size:n})),hp=_.default.div`display:flex;align-items:center;justify-content:center;width:${({$size:e})=>We(e)};height:${({$size:e})=>We(e)};animation:1s infinite linear;animation-name:rotate;@keyframes rotate{from{transform:rotate(0);}to{transform:rotate(360deg);}}`,fp=({files:e,initialIndex:t=0,onClose:n,visible:r})=>{const[s,o]=l.useState(t),[i,c]=l.useState(!1),{stringSet:u,format:d}=oe(),{config:m}=de(),h=e.length,f=e[s],g=m.conversation.fileViewer.downloadEnabled,C=h>1,b=(f==null?void 0:f.type)||"",S=Ve(b),p=Kt(b),A=!kg(b);l.useEffect(()=>{r&&(o(t),c(!1))},[r,t]);const y=l.useCallback(()=>{s>0&&(o(I=>I-1),c(!1))},[s]),T=l.useCallback(()=>{s<h-1&&(o(I=>I+1),c(!1))},[s,h]);return l.useEffect(()=>{if(!r)return;const I=L=>{L.key==="ArrowLeft"?y():L.key==="ArrowRight"&&T()};return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[r,y,T]),!r||!f?null:a.createElement(ut,{onClose:n,visible:r,portalContainerId:Se.MODAL_ROOT,"aria-label":(f==null?void 0:f.name)||u.IMAGE_VIEWER__DEFAULT_TITLE},a.createElement(gp,null,a.createElement(pp,null,a.createElement(_p,null,a.createElement(Ep,null,a.createElement(H,{variant:"button",maxTextLines:1,color:E.color.ondark.textHighEmphasis},f.name||u.IMAGE_VIEWER__DEFAULT_TITLE),f.timestamp&&a.createElement(H,{variant:"caption2",color:E.color.ondark.textHighEmphasis},d(new Date(f.timestamp),"h:mm a")))),a.createElement(Cp,{type:"close",size:18,color:E.color.ondark.textHighEmphasis,"aria-label":u.A11Y_IMAGE_VIEWER_CLOSE,onClick:n})),a.createElement(bp,null,C&&a.createElement(po,{$position:"left",type:"chevron-right",size:22,color:E.color.ondark.textHighEmphasis,onClick:y,"aria-label":u.A11Y_IMAGE_VIEWER_PREVIOUS,disabled:s===0,$flipped:!0}),a.createElement(vp,{onClick:I=>I.currentTarget===I.target&&n()},S&&a.createElement(a.Fragment,null,!i&&a.createElement(Sp,null,a.createElement(gt,{size:32},a.createElement(ee,{type:"spinner",color:"textLowEmphasis",size:32}))),a.createElement(yp,{src:f.url,alt:f.name||"Image",$loaded:i,onLoad:()=>c(!0)})),p&&a.createElement(Ap,{controls:!0},a.createElement("source",{src:f.url,type:b})),A&&a.createElement(Tp,null,a.createElement(H,{variant:"h1",color:E.themedColor.textHighEmphasis},u.FILE_VIEWER__UNSUPPORT))),C&&a.createElement(po,{$position:"right",type:"chevron-right",size:22,color:E.color.ondark.textHighEmphasis,onClick:T,"aria-label":u.A11Y_IMAGE_VIEWER_NEXT,disabled:s===h-1})),a.createElement(Ip,null,C&&a.createElement(H,{variant:"body2",color:E.color.ondark.textHighEmphasis},s+1,"/",h),g&&!A&&a.createElement(xp,{forwardedAs:"a",href:f.url,download:f.name||"file",type:"download",size:24,color:E.color.ondark.textHighEmphasis,"aria-label":u.A11Y_IMAGE_VIEWER_DOWNLOAD}))))},gp=_.default.div`position:fixed;top:0;left:0;right:0;bottom:0;height:100dvh;outline:none;display:flex;flex-direction:column;background-color:${E.themedColor.bg_50_600};`,pp=_.default.header`display:flex;align-items:center;justify-content:space-between;padding-top:calc(12px + env(safe-area-inset-top));padding-right:12px;padding-bottom:12px;padding-left:16px;min-height:56px;background-color:${E.color.overlay.dark};`,_p=_.default.div`flex:1;min-width:0;padding-right:8px;`,Ep=_.default.div`display:flex;flex-direction:column;gap:2px;`,Cp=_.default(Qe)`flex-shrink:0;width:28px;height:28px;border-radius:50%;`,$n=_.default.div`display:flex;align-items:center;justify-content:center;`,bp=_.default($n)`flex:1;min-height:0;position:relative;`,vp=_.default($n)`position:relative;width:100%;height:100%;min-width:0;min-height:0;`,Sp=_.default($n)`position:absolute;inset:0;pointer-events:none;`,yp=_.default.img`max-width:100%;max-height:100%;object-fit:contain;user-select:none;-webkit-user-drag:none;opacity:${e=>e.$loaded?1:0};transition:opacity 0.3s ease;`,Ap=_.default.video`max-width:100%;max-height:100%;object-fit:contain;`,Tp=_.default($n)`flex-direction:column;gap:16px;`,po=_.default(Qe)`position:absolute;${e=>e.$position==="left"?"left: 12px;":"right: 12px;"}top:50%;z-index:1;width:38px;height:38px;transform:translateY(-50%) ${e=>e.$flipped?"scaleX(-1)":""};border-radius:50%;background-color:${E.color.overlay.dark};&:disabled{opacity:0.3;}`,Ip=_.default.footer`position:relative;display:flex;align-items:center;justify-content:center;padding-top:16px;padding-right:16px;padding-bottom:calc(16px + env(safe-area-inset-bottom));padding-left:16px;min-height:56px;background-color:${E.color.overlay.dark};`,xp=_.default(Qe)`position:absolute;right:16px;top:50%;transform:translateY(-50%);padding:0;width:24px;height:24px;`,Rp=.75,pa=6,Mp=pa*2;let br=null;typeof Intl<"u"&&"Segmenter"in Intl&&(br=new Intl.Segmenter(void 0,{granularity:"grapheme"}));const wp=e=>br?Array.from(br.segment(e),t=>t.segment):[...e],kp=e=>{const t=Math.floor(e.length*Rp),n=Math.max(0,e.length-pa);return Math.max(t,n)},_o=(e,t="")=>{if(e.length<Mp)return{start:e+t,end:""};const n=wp(e),r=kp(n);return{start:n.slice(0,r).join(""),end:n.slice(r).join("")+t}},Lp=e=>{const t=e.normalize("NFC").trim(),n=t.lastIndexOf(".");if(!(n>0&&n<t.length-1))return _o(t);const s=t.slice(0,n),o=t.slice(n);return _o(s,o)},_a=({children:e,...t})=>{const{start:n,end:r}=l.useMemo(()=>Lp(e),[e]);return r?a.createElement(Op,null,a.createElement(Np,{...t},n),a.createElement(Dp,{...t},r)):a.createElement(H,{...t},n)},Op=_.default.span`display:flex;width:100%;min-width:0;overflow:hidden;direction:inherit;`,Np=_.default(H)`overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex-shrink:1;min-width:0;`,Dp=_.default(H)`flex-shrink:0;white-space:nowrap;`,Jr=({name:e,mimeType:t,type:n="FILE",iconColor:r,iconBackgroundColor:s,onClick:o,selected:i})=>{const{colors:c}=B.useTheme(),{conversation:u}=ie(),d=o?u.file.buttonLikePreview({name:e,mimeType:t,selected:i,onActivate:o}):u.file.preview({name:e,mimeType:t,selected:i});return a.createElement($p,{...d.props,$clickable:!!o},a.createElement(Fp,{$bgColor:s??c.base.primary},a.createElement(ee,{type:"file-document",size:24,color:r??c.base.primaryContrastContent})),a.createElement(Up,null,a.createElement(_a,{variant:"button",color:E.themedColor.textHighEmphasis},e),a.createElement(H,{color:E.themedColor.textMidEmphasis,variant:"caption3"},n)),d.descriptionNode)},$p=_.default.div`border:none;border-radius:12px;gap:8px;width:${se.BODY_MAX_WIDTH}px;height:64px;display:flex;align-items:center;padding:12px;box-sizing:border-box;border:1px solid ${E.themedColor.textDisabled};background-color:${E.themedColor.bg_50_600};${({$clickable:e})=>e&&Pp}`,Pp=B.css`cursor:pointer;${Re}&:hover{background-color:${E.themedColor.bg_100_500};}`,Fp=_.default.div`border-radius:8px;width:40px;height:40px;display:flex;align-items:center;justify-content:center;background-color:${({$bgColor:e})=>e};`,Up=_.default.div`display:flex;flex:1;flex-direction:column;gap:4px;min-width:0;`;function Bp({file:e,children:t,onClickFile:n}){const r=n?()=>n(e):void 0;return a.createElement(Hp,null,a.createElement(Jr,{name:e.name,mimeType:e.type,type:xr(e.name,e.type),onClick:r}),t)}const Hp=_.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${se.GAP_GROUPED}px;`,et=`${Be}-incoming-msg`,Gp=`${Be}-marked-text`;function zp({file:e,onClickMedia:t,onClickMediaFiles:n,children:r}){const{conversation:s}=ie(),o=e.type.startsWith("image"),i=(()=>{if(n)return()=>n({files:[{url:e.url,type:e.type,name:e.name}],index:0});if(t)return()=>t(e)})(),c=i?s.file.buttonLikePreview({name:e.name,mimeType:e.type,onActivate:i}):s.file.preview({name:e.name,mimeType:e.type}),u=()=>o?a.createElement(Kp,{src:e.url,alt:"image-message"}):e.type.startsWith("video")?a.createElement(Yp,{controls:!0},a.createElement("source",{src:e.url}),a.createElement("track",{kind:"captions"})):null;if(u){const d={id:`${et}-media-body`,...c.props};return a.createElement(Vp,null,a.createElement(qp,{...d},u(),c.descriptionNode),r)}return null}const Vp=_.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${se.GAP_GROUPED}px;`,qp=_.default.div`width:${se.BODY_MAX_WIDTH}px;height:160px;border-radius:12px;overflow:hidden;cursor:pointer;${te.light`
|
|
85
|
+
`,rp=({visible:e,onClose:t,children:n,"aria-label":r})=>a.createElement(ft,{portalContainerId:Se.WINDOW,visible:e,onClose:t,"aria-label":r},a.createElement(ap,null,n)),sp=({onClick:e,destructive:t,icon:n,initialFocus:r,children:s})=>a.createElement(op,{onClick:e,$destructive:t,"data-sb-initial-focus":r?"true":void 0},n&&a.createElement(ip,null,a.createElement(te,{type:n,size:24,color:E.themedColor.primary})),s),dt=Object.assign(rp,{ActionItem:sp}),op=_.default.button`all:unset;display:flex;align-items:center;gap:24px;width:100%;padding:12px 24px;cursor:pointer;color:${({$destructive:e})=>e?E.themedColor.error:E.themedColor.textHighEmphasis};${xe}`,ip=_.default.div`display:flex;align-items:center;justify-content:center;flex-shrink:0;`,ap=_.default.div`position:absolute;left:0;right:0;bottom:0;border-radius:12px 12px 0 0;flex-direction:column;align-items:flex-end;margin:0 auto;box-sizing:border-box;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,Eo=40,Co=.9,cp="[data-message-listitem]",lp='input, textarea, select, [role="textbox"], [contenteditable="true"]',up=({event:e,list:t,isMessageAnchor:n})=>{switch(e.key){case"PageDown":return t.clientHeight*Co;case"PageUp":return t.clientHeight*-Co;case"ArrowDown":return n?Eo:void 0;case"ArrowUp":return n?Eo*-1:void 0;default:return}},dp=({listRef:e,syncScrollPosition:t})=>l.useCallback(n=>{const r=e.current;if(!r||n.defaultPrevented||n.metaKey||n.altKey||n.ctrlKey)return;const s=n.target;if(!s||!r.contains(s)||s.closest(lp))return;const o=s===r||s.matches(cp),i=up({event:n,list:r,isMessageAnchor:o});if(i==null||i===0)return;const c=Math.max(0,r.scrollHeight-r.clientHeight),u=Math.min(c,Math.max(0,r.scrollTop+i));u!==r.scrollTop&&(n.preventDefault(),t(u))},[e,t]),mp="[data-message-listitem]",hp=e=>Math.min(Math.max(0,e),1),fp=e=>{const n=e.getRootNode().activeElement,r=n==null?void 0:n.closest(mp),s=n===e||n===r;return!n||!e.contains(n)?null:s?e:n},gp=({list:e,focusRestoreTarget:t})=>{if(!t)return;const r=e.getRootNode().activeElement,s=r===e||e.contains(r),o=t===e||e.contains(t);s&&o&&t.focus({preventScroll:!0})},pp=({depsForResetScrollPositionToBottom:e,listRef:t,loadThreshold:n,messagesLength:r,onLoadNext:s,onLoadPrev:o,onScroll:i})=>{const c=l.useRef(!1),u=l.useRef(void 0),d=l.useRef(0),m=l.useRef(0),h=l.useRef(null),f=l.useRef(null),g=l.useRef(null);l.useLayoutEffect(()=>{t.current&&(t.current.scrollTop=t.current.scrollHeight)},e),l.useLayoutEffect(()=>{const C=t.current;C&&(u.current==="top"&&(C.scrollTop=C.scrollHeight-m.current,gp({list:C,focusRestoreTarget:h.current}),h.current=null),u.current==="bottom"&&(C.scrollTop=d.current),u.current=void 0)},[t,r]);const p=l.useCallback(async C=>{const A=t.current;if(!A||(i==null||i(C),m.current=A.scrollHeight-A.scrollTop,d.current=A.scrollTop,c.current))return;const y=A.clientHeight*hp(n);if(A.scrollTop<=y){c.current=!0,u.current="top",h.current=fp(A),await o(),c.current=!1;return}if(A.scrollHeight-A.scrollTop-A.clientHeight<=y){c.current=!0,u.current="bottom",await s(),c.current=!1;return}u.current=void 0},[t,n,s,o,i]),v=l.useCallback(C=>{const A=t.current;if(!A)return;const y=g.current;if(y!=null){if(y===A.scrollTop){g.current=null;return}g.current=null}const T=f.current;if(T!=null&&T===A.scrollTop){f.current=null,g.current=A.scrollTop,p(C);return}f.current=null,p(C)},[p,t]),S=l.useCallback(C=>{const A=t.current;A&&(f.current=C,g.current=null,A.scrollTop=C,A.dispatchEvent(new Event("scroll",{bubbles:!0})))},[t]);return l.useLayoutEffect(()=>()=>{f.current=null,g.current=null},[]),{handleScroll:v,syncScrollPosition:S}},_p=l.forwardRef(function(t,n){const{messages:r,renderMessage:s,loading:o,LoadingComponent:i,error:c,ErrorComponent:u,empty:d,EmptyComponent:m,messageTopArea:h,messageBottomArea:f,overlayArea:g,onLoadPrev:p,onLoadNext:v,loadThreshold:S=.05,onScroll:C=me,depsForResetScrollPositionToBottom:A,stackDirection:y="top",bottomSpacerHeight:T=0,"aria-label":I}=t,N=l.useRef(null),O=l.useCallback(D=>{N.current=D,n&&(typeof n=="function"?n(D):n.current=D)},[n]),{handleScroll:k,syncScrollPosition:R}=pp({depsForResetScrollPositionToBottom:A,listRef:N,loadThreshold:S,messagesLength:r.length,onLoadNext:v,onLoadPrev:p,onScroll:C}),F=dp({listRef:N,syncScrollPosition:R});return c?a.createElement(a.Fragment,null,u):o?a.createElement(a.Fragment,null,i):a.createElement(Ep,{id:"infinite-list-container"},a.createElement(Cp,{id:"infinite-list-inner",ref:O,onScroll:k,onKeyDown:F,role:"list","aria-label":I,tabIndex:0},y==="bottom"&&a.createElement("div",{style:{flexGrow:1}}),h,d?m:r.map((D,Q)=>s({message:D,index:Q})),f,T>0&&a.createElement("div",{style:{minHeight:T}})),a.createElement(bp,{id:"infinite-list-overlay-container"},a.createElement(vp,{id:"infinite-list-overlay"},g)))}),Ep=_.default.div`display:flex;position:relative;flex:1;overflow:hidden;`,Cp=_.default.div`display:flex;flex:1;flex-direction:column;overflow-x:hidden;overflow-y:auto;overscroll-behavior:contain;scrollbar-color:${E.themedColor.textLowEmphasis}transparent;&::-webkit-scrollbar-thumb:hover{background-color:transparent;}`,bp=_.default.div`position:absolute;top:0;bottom:0;left:0;right:0;pointer-events:none;`,vp=_.default.div`pointer-events:auto;`,st=({as:e,type:t,size:n=16,color:r,disabled:s,children:o,...i})=>{const c=s?E.themedColor.textDisabled:E.themedColor.textHighEmphasis;return a.createElement(Sp,{as:e,disabled:s,...i},a.createElement(te,{type:t,size:n,color:r??c}),o)},Sp=_.default.button`all:unset;padding:4px;cursor:pointer;display:flex;align-items:center;justify-content:center;${xe}&:disabled{cursor:not-allowed;}`,Et=({className:e,children:t,size:n=26})=>a.createElement(yp,{className:e,$size:n},t??a.createElement(te,{type:"spinner",size:n})),yp=_.default.div`display:flex;align-items:center;justify-content:center;width:${({$size:e})=>Je(e)};height:${({$size:e})=>Je(e)};animation:1s infinite linear;animation-name:rotate;@keyframes rotate{from{transform:rotate(0);}to{transform:rotate(360deg);}}`,Ap=({files:e,initialIndex:t=0,onClose:n,visible:r})=>{const[s,o]=l.useState(t),[i,c]=l.useState(!1),{stringSet:u,format:d}=ie(),{config:m}=ue(),h=e.length,f=e[s],g=m.conversation.fileViewer.downloadEnabled,p=h>1,v=(f==null?void 0:f.type)||"",S=We(v),C=jt(v),A=!Hg(v);l.useEffect(()=>{r&&(o(t),c(!1))},[r,t]);const y=l.useCallback(()=>{s>0&&(o(I=>I-1),c(!1))},[s]),T=l.useCallback(()=>{s<h-1&&(o(I=>I+1),c(!1))},[s,h]);return l.useEffect(()=>{if(!r)return;const I=N=>{N.key==="ArrowLeft"?y():N.key==="ArrowRight"&&T()};return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[r,y,T]),!r||!f?null:a.createElement(ft,{onClose:n,visible:r,portalContainerId:Se.MODAL_ROOT,"aria-label":(f==null?void 0:f.name)||u.IMAGE_VIEWER__DEFAULT_TITLE},a.createElement(Tp,null,a.createElement(Ip,null,a.createElement(xp,null,a.createElement(Rp,null,a.createElement(B,{variant:"button",maxTextLines:1,color:E.color.ondark.textHighEmphasis},f.name||u.IMAGE_VIEWER__DEFAULT_TITLE),f.timestamp&&a.createElement(B,{variant:"caption2",color:E.color.ondark.textHighEmphasis},d(new Date(f.timestamp),"h:mm a")))),a.createElement(Mp,{type:"close",size:18,color:E.color.ondark.textHighEmphasis,"aria-label":u.A11Y_IMAGE_VIEWER_CLOSE,onClick:n})),a.createElement(wp,null,p&&a.createElement(bo,{$position:"left",type:"chevron-right",size:22,color:E.color.ondark.textHighEmphasis,onClick:y,"aria-label":u.A11Y_IMAGE_VIEWER_PREVIOUS,disabled:s===0,$flipped:!0}),a.createElement(kp,{onClick:I=>I.currentTarget===I.target&&n()},S&&a.createElement(a.Fragment,null,!i&&a.createElement(Lp,null,a.createElement(Et,{size:32},a.createElement(te,{type:"spinner",color:"textLowEmphasis",size:32}))),a.createElement(Op,{src:f.url,alt:f.name||"Image",$loaded:i,onLoad:()=>c(!0)})),C&&a.createElement(Np,{controls:!0},a.createElement("source",{src:f.url,type:v})),A&&a.createElement(Dp,null,a.createElement(B,{variant:"h1",color:E.themedColor.textHighEmphasis},u.FILE_VIEWER__UNSUPPORT))),p&&a.createElement(bo,{$position:"right",type:"chevron-right",size:22,color:E.color.ondark.textHighEmphasis,onClick:T,"aria-label":u.A11Y_IMAGE_VIEWER_NEXT,disabled:s===h-1})),a.createElement($p,null,p&&a.createElement(B,{variant:"body2",color:E.color.ondark.textHighEmphasis},s+1,"/",h),g&&!A&&a.createElement(Pp,{forwardedAs:"a",href:f.url,download:f.name||"file",type:"download",size:24,color:E.color.ondark.textHighEmphasis,"aria-label":u.A11Y_IMAGE_VIEWER_DOWNLOAD}))))},Tp=_.default.div`position:fixed;top:0;left:0;right:0;bottom:0;height:100dvh;outline:none;display:flex;flex-direction:column;background-color:${E.themedColor.bg_50_600};`,Ip=_.default.header`display:flex;align-items:center;justify-content:space-between;padding-top:calc(12px + env(safe-area-inset-top));padding-right:12px;padding-bottom:12px;padding-left:16px;min-height:56px;background-color:${E.color.overlay.dark};`,xp=_.default.div`flex:1;min-width:0;padding-right:8px;`,Rp=_.default.div`display:flex;flex-direction:column;gap:2px;`,Mp=_.default(st)`flex-shrink:0;width:28px;height:28px;border-radius:50%;`,Bn=_.default.div`display:flex;align-items:center;justify-content:center;`,wp=_.default(Bn)`flex:1;min-height:0;position:relative;`,kp=_.default(Bn)`position:relative;width:100%;height:100%;min-width:0;min-height:0;`,Lp=_.default(Bn)`position:absolute;inset:0;pointer-events:none;`,Op=_.default.img`max-width:100%;max-height:100%;object-fit:contain;user-select:none;-webkit-user-drag:none;opacity:${e=>e.$loaded?1:0};transition:opacity 0.3s ease;`,Np=_.default.video`max-width:100%;max-height:100%;object-fit:contain;`,Dp=_.default(Bn)`flex-direction:column;gap:16px;`,bo=_.default(st)`position:absolute;${e=>e.$position==="left"?"left: 12px;":"right: 12px;"}top:50%;z-index:1;width:38px;height:38px;transform:translateY(-50%) ${e=>e.$flipped?"scaleX(-1)":""};border-radius:50%;background-color:${E.color.overlay.dark};&:disabled{opacity:0.3;}`,$p=_.default.footer`position:relative;display:flex;align-items:center;justify-content:center;padding-top:16px;padding-right:16px;padding-bottom:calc(16px + env(safe-area-inset-bottom));padding-left:16px;min-height:56px;background-color:${E.color.overlay.dark};`,Pp=_.default(st)`position:absolute;right:16px;top:50%;transform:translateY(-50%);padding:0;width:24px;height:24px;`,Fp=.75,va=6,Up=va*2;let xr=null;typeof Intl<"u"&&"Segmenter"in Intl&&(xr=new Intl.Segmenter(void 0,{granularity:"grapheme"}));const Bp=e=>xr?Array.from(xr.segment(e),t=>t.segment):[...e],Hp=e=>{const t=Math.floor(e.length*Fp),n=Math.max(0,e.length-va);return Math.max(t,n)},vo=(e,t="")=>{if(e.length<Up)return{start:e+t,end:""};const n=Bp(e),r=Hp(n);return{start:n.slice(0,r).join(""),end:n.slice(r).join("")+t}},Gp=e=>{const t=e.normalize("NFC").trim(),n=t.lastIndexOf(".");if(!(n>0&&n<t.length-1))return vo(t);const s=t.slice(0,n),o=t.slice(n);return vo(s,o)},Sa=({children:e,...t})=>{const{start:n,end:r}=l.useMemo(()=>Gp(e),[e]);return r?a.createElement(zp,null,a.createElement(Vp,{...t},n),a.createElement(qp,{...t},r)):a.createElement(B,{...t},n)},zp=_.default.span`display:flex;width:100%;min-width:0;overflow:hidden;direction:inherit;`,Vp=_.default(B)`overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex-shrink:1;min-width:0;`,qp=_.default(B)`flex-shrink:0;white-space:nowrap;`,os=({name:e,mimeType:t,type:n="FILE",iconColor:r,iconBackgroundColor:s,onClick:o,selected:i})=>{const{colors:c}=U.useTheme(),{conversation:u}=ae(),d=o?u.file.buttonLikePreview({name:e,mimeType:t,selected:i,onActivate:o}):u.file.preview({name:e,mimeType:t,selected:i});return a.createElement(Kp,{...d.props,$clickable:!!o},a.createElement(Wp,{$bgColor:s??c.base.primary},a.createElement(te,{type:"file-document",size:24,color:r??c.base.primaryContrastContent})),a.createElement(jp,null,a.createElement(Sa,{variant:"button",color:E.themedColor.textHighEmphasis},e),a.createElement(B,{color:E.themedColor.textMidEmphasis,variant:"caption3"},n)),d.descriptionNode)},Kp=_.default.div`border:none;border-radius:12px;gap:8px;width:${oe.BODY_MAX_WIDTH}px;height:64px;display:flex;align-items:center;padding:12px;box-sizing:border-box;border:1px solid ${E.themedColor.textDisabled};background-color:${E.themedColor.bg_50_600};${({$clickable:e})=>e&&Yp}`,Yp=U.css`cursor:pointer;${xe}&:hover{background-color:${E.themedColor.bg_100_500};}`,Wp=_.default.div`border-radius:8px;width:40px;height:40px;display:flex;align-items:center;justify-content:center;background-color:${({$bgColor:e})=>e};`,jp=_.default.div`display:flex;flex:1;flex-direction:column;gap:4px;min-width:0;`;function Xp({file:e,children:t,onClickFile:n}){const r=n?()=>n(e):void 0;return a.createElement(Zp,null,a.createElement(os,{name:e.name,mimeType:e.type,type:Nr(e.name,e.type),onClick:r}),t)}const Zp=_.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${oe.GAP_GROUPED}px;`,ot=`${He}-incoming-msg`,Jp=`${He}-marked-text`;function Qp({file:e,onClickMedia:t,onClickMediaFiles:n,children:r}){const{conversation:s}=ae(),o=e.type.startsWith("image"),i=(()=>{if(n)return()=>n({files:[{url:e.url,type:e.type,name:e.name}],index:0});if(t)return()=>t(e)})(),c=i?s.file.buttonLikePreview({name:e.name,mimeType:e.type,onActivate:i}):s.file.preview({name:e.name,mimeType:e.type}),u=()=>o?a.createElement(n_,{src:e.url,alt:"image-message"}):e.type.startsWith("video")?a.createElement(r_,{controls:!0},a.createElement("source",{src:e.url}),a.createElement("track",{kind:"captions"})):null;if(u){const d={id:`${ot}-media-body`,...c.props};return a.createElement(e_,null,a.createElement(t_,{...d},u(),c.descriptionNode),r)}return null}const e_=_.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${oe.GAP_GROUPED}px;`,t_=_.default.div`width:${oe.BODY_MAX_WIDTH}px;height:160px;border-radius:12px;overflow:hidden;cursor:pointer;${ne.light`
|
|
86
86
|
background-color: ${E.color.background100};
|
|
87
87
|
`}
|
|
88
|
-
${
|
|
88
|
+
${ne.dark`
|
|
89
89
|
background-color: ${E.color.background400};
|
|
90
90
|
`}
|
|
91
|
-
`,
|
|
91
|
+
`,n_=_.default.img`width:100%;height:100%;object-fit:cover;`,r_=_.default.video`width:100%;height:100%;object-fit:cover;`,ya=({images:e,isPending:t=!1,onClickImage:n})=>{const{conversation:r}=ae(),s=e.length;if(s===0)return null;const o=Ju(s),i=!!n&&!t;return a.createElement(o_,{$width:oe.BODY_MAX_WIDTH,$columns:o},e.map((c,u)=>{const{columnSpan:d}=Qu({index:u,itemCount:s}),m=c.name||"",h=()=>{t||n==null||n(u)},f=c.type??"image/*",g=i?r.file.buttonLikePreview({name:m,mimeType:f,onActivate:h},u):r.file.preview({name:m,mimeType:f});return a.createElement(i_,{key:c.url,$clickable:i,$itemSpan:d,$isPending:t,...g.props},a.createElement(s_,{src:c.url,alt:c.name||""}),t&&a.createElement(a_,null),g.descriptionNode)}))},s_=({src:e,alt:t})=>{const[n,r]=l.useState(!1),[s,o]=l.useState(!1);return a.createElement(a.Fragment,null,!n&&!s&&a.createElement(c_,null,a.createElement(Et,{size:20},a.createElement(te,{type:"spinner",color:"textLowEmphasis",size:20}))),s&&a.createElement(l_,null,a.createElement(te,{type:"photo",color:"textLowEmphasis",size:24})),!s&&a.createElement(u_,{src:e,alt:t,$loaded:n,onLoad:()=>r(!0),onError:()=>o(!0)}))},o_=_.default.div`display:grid;grid-template-columns:repeat(${({$columns:e})=>e},1fr);width:${({$width:e})=>e}px;gap:2px;border-radius:16px;overflow:hidden;`,i_=_.default.div`position:relative;width:100%;aspect-ratio:1;overflow:hidden;cursor:${e=>e.$clickable?"pointer":"default"};${ne.light`
|
|
92
92
|
background-color: ${E.color.background100};
|
|
93
93
|
`}
|
|
94
|
-
${
|
|
94
|
+
${ne.dark`
|
|
95
95
|
background-color: ${E.color.background400};
|
|
96
96
|
`}
|
|
97
97
|
${e=>e.$itemSpan&&e.$itemSpan>1&&`
|
|
@@ -111,19 +111,19 @@
|
|
|
111
111
|
}
|
|
112
112
|
`}
|
|
113
113
|
}
|
|
114
|
-
`,
|
|
114
|
+
`,a_=_.default.div`position:absolute;top:0;left:0;width:100%;height:100%;background-color:${E.color.overlay.dark};pointer-events:none;`,Aa=_.default.div`display:flex;align-items:center;justify-content:center;`,c_=_.default(Aa)`position:absolute;inset:0;`,l_=_.default(Aa)`position:absolute;inset:0;${ne.light`
|
|
115
115
|
background-color: ${E.color.background200};
|
|
116
116
|
`}
|
|
117
|
-
${
|
|
117
|
+
${ne.dark`
|
|
118
118
|
background-color: ${E.color.background500};
|
|
119
119
|
`}
|
|
120
|
-
`,
|
|
120
|
+
`,u_=_.default.img`position:absolute;inset:0;width:100%;height:100%;object-fit:cover;opacity:${({$loaded:e})=>e?1:0};transition:opacity 0.3s ease;`,d_=({files:e,children:t,onClickMedia:n,onClickMediaFiles:r})=>{const s=o=>{const i=e[o];i&&(r?r({files:e,index:o}):n&&n({url:i.url,type:i.type||"image/*"}))};return a.createElement(m_,null,a.createElement(ya,{images:e,onClickImage:s}),t)},m_=_.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${oe.GAP_GROUPED}px;`,h_="✱",Ta=e=>{const t=new RegExp(`(\`+)([^\`]+?)\\1|(${h_}+)`,"g");return e.replace(t,(n,r,s,o)=>r?n:o?`<span id=${Jp} aria-label="masked-text">${o}</span>`:n)},f_=e=>e.replace(/\*\*(.*?)\*\*/g,"<b>$1</b>"),So=e=>{var t;return{files:e.fileInfoList.map(n=>({url:n.url,type:n.mimeType??"",name:n.fileName??""})),metadata:{localFiles:(t=e.messageParams)==null?void 0:t.fileInfoList.map(n=>n.file)}}},g_=l.lazy(async()=>({default:(await Promise.resolve().then(()=>require("./cjs/VvejebHE.cjs"))).MarkdownText})),yo=typeof __SBA_USE_SYNTAX_HIGHLIGHT__>"u"||__SBA_USE_SYNTAX_HIGHLIGHT__?l.lazy(async()=>({default:(await Promise.resolve().then(()=>require("./cjs/DlvEEpWX.cjs"))).CodeBlock})):null;function p_(e){var s,o;const t=e.maxBodyWidth??oe.BODY_MAX_WIDTH,n=l.useMemo(()=>Nc(e.message,Ta),[e.message]),r={id:`${ot}-text-body`,$maxWidth:t,$color:(s=e.customStyle)==null?void 0:s.bubbleContentColor,$bgColor:(o=e.customStyle)==null?void 0:o.bubbleBackgroundColor};return n.length===0?e.children?a.createElement(Ao,{...r},e.children):null:a.createElement(Ao,{...r},n.map((i,c)=>i.type==="text"?a.createElement(To,{key:c,variant:"body3"},a.createElement(Kt,{fallback:i.value},a.createElement(g_,{onClickImage:u=>{var d;return(d=e.onClickMedia)==null?void 0:d.call(e,{url:u,type:"image/*"})},onClickLink:e.onClickLink},i.value))):i.type==="code"?yo?a.createElement(Kt,{key:c,fallback:a.createElement(To,{variant:"body3"},i.value)},a.createElement(yo,{code:i.value,language:i.language})):a.createElement(__,{key:c},a.createElement("code",null,i.value)):null),e.children)}const Ao=_.default.div`display:flex;flex-direction:column;min-width:0;max-width:min(${({$maxWidth:e})=>e}px,100%);border-radius:12px;overflow:hidden;padding:12px 0;${({theme:e,$color:t,$bgColor:n})=>U.css`
|
|
121
121
|
color: ${t||e.colors.messageIncoming.text};
|
|
122
122
|
background-color: ${n||e.colors.messageIncoming.background};
|
|
123
123
|
`}
|
|
124
124
|
transition: max-width 0.3s;
|
|
125
125
|
overflow-wrap: break-word;
|
|
126
|
-
`,
|
|
126
|
+
`,To=_.default(B)`align-items:flex-start;line-height:140%;white-space:pre-wrap;padding:0 12px;`,__=_.default.pre`margin:0;padding:1em;overflow-x:auto;white-space:pre;font-family:monospace;font-size:13px;line-height:1.5;color:#d4d4d4;background:#1e1e1e;border-radius:4px;`;function Ia({id:e,src:t,size:n=56,onClick:r,onImageError:s,onImageLoad:o,style:i,backgroundColor:c,...u}){const[d,m]=l.useState();return a.createElement(E_,{id:e,tabIndex:r?0:void 0,onClick:r,$size:Je(n),$backgroundColor:c,style:i,...u},t&&t!==d?a.createElement(C_,{src:t,alt:"",onLoad:()=>o==null?void 0:o(t),onError:()=>{m(t),s==null||s(t)}}):a.createElement(te,{type:"user",size:n}))}const E_=_.default.div`border-radius:50%;display:inline-block;overflow:hidden;position:relative;flex-shrink:0;height:${e=>e.$size};width:${e=>e.$size};background-color:${e=>e.$backgroundColor??E.themedColor.bg_100_500};&:focus{outline:none;}${xe}`,C_=_.default.img`object-fit:cover;width:100%;height:100%;position:absolute;`,b_=({sender:e,isBotMessage:t})=>{const n=`${ot}-sender-avatar`,[r,s]=l.useState();return t&&(!e.profileUrl||e.profileUrl===r)?a.createElement(v_,{id:n},a.createElement(te,{type:"delight",size:"100%"})):a.createElement(Ia,{id:n,size:oe.AVATAR_SIZE,src:e.profileUrl,onImageError:t?s:void 0})},v_=_.default.div`flex-shrink:0;width:${oe.AVATAR_SIZE}px;height:${oe.AVATAR_SIZE}px;box-sizing:border-box;padding:4px;border-radius:50%;display:flex;justify-content:center;align-items:center;background-color:${({theme:e})=>e.colors.base.primary}!important;ellipse,path{fill:${({theme:e})=>e.colors.base.primaryContrastContent}!important;}}`,S_=({sender:e})=>a.createElement(y_,{id:`${ot}-sender-name`,variant:"caption1",color:E.themedColor.textMidEmphasis},e.nickname),y_=_.default(B)`text-align:start;width:100%;box-sizing:border-box;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;padding-block:5px;padding-inline:0 7px;`,A_=({createdAt:e})=>{const{stringSet:t,format:n}=ie();return e?a.createElement(B,{id:`${ot}-sent-time`,variant:"caption4",color:E.themedColor.textLowEmphasis},n(e,t.DATE_FORMAT__MESSAGE_TIMESTAMP)):null},xa="(prefers-reduced-motion: reduce)",T_=()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia(xa).matches,Ra=()=>{const[e,t]=l.useState(T_);return l.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const n=window.matchMedia(xa);t(n.matches);const r=s=>{t(s.matches)};return typeof n.addEventListener=="function"?(n.addEventListener("change",r),()=>{n.removeEventListener("change",r)}):(n.addListener(r),()=>{n.removeListener(r)})},[]),e},I_=({thinkingMessage:e,customStyle:t})=>{const n=Ra();return e?a.createElement(M_,{$prefersReducedMotion:n},a.createElement(w_,null,e),!n&&a.createElement(k_,null)):a.createElement(x_,{$bgColor:t==null?void 0:t.bubbleBackgroundColor},[0,1,2].map(r=>a.createElement(R_,{key:r,$color:t==null?void 0:t.bubbleContentColor,$prefersReducedMotion:n})))},x_=_.default.div`align-items:center;border-radius:16px;display:flex;gap:6px;height:26px;justify-content:center;padding:0 12px;background-color:${({theme:e,$bgColor:t})=>t||e.colors.messageIncoming.background};`,R_=_.default.span`animation:${({$prefersReducedMotion:e})=>e?"none":"blink 1.4s infinite"};animation-fill-mode:both;border-radius:50%;height:8px;width:8px;background:${({theme:e,$color:t})=>t||e.colors.messageIncoming.text};opacity:${({$prefersReducedMotion:e})=>e?.38:void 0};@keyframes blink{0%{opacity:0.12;transform:scale(1);}21.43%{opacity:0.38;transform:scale(1.2);}42.86%{opacity:0.12;transform:scale(1);}100%{opacity:0.12;transform:scale(1);}}&:nth-child(1){animation-delay:0.4s;}&:nth-child(2){animation-delay:0.6s;}&:nth-child(3){animation-delay:0.8s;}`,M_=_.default.div.attrs({id:`${ot}-typing-indicator`})`
|
|
127
127
|
position: relative;
|
|
128
128
|
overflow: hidden;
|
|
129
129
|
animation: ${({$prefersReducedMotion:e})=>e?"none":"fadeIn 0.4s ease-in-out"};
|
|
@@ -135,12 +135,12 @@
|
|
|
135
135
|
opacity: 1;
|
|
136
136
|
}
|
|
137
137
|
}
|
|
138
|
-
`,
|
|
138
|
+
`,w_=_.default(B).attrs({variant:"body3"})`
|
|
139
139
|
white-space: pre-wrap;
|
|
140
140
|
word-break: break-word;
|
|
141
141
|
color: ${E.themedColor.textHighEmphasis};
|
|
142
|
-
`,
|
|
143
|
-
`,
|
|
142
|
+
`,k_=_.default.div`position:absolute;inset:0;pointer-events:none;background-size:33% 100%;background-repeat:no-repeat;animation:shimmerSweepLtr 1.6s linear infinite;@keyframes shimmerSweepLtr{from{background-position:-33% 0;}to{background-position:133% 0;}}[dir='rtl'] &{animation-name:shimmerSweepRtl;@keyframes shimmerSweepRtl{from{background-position:133% 0;}to{background-position:-33% 0;}}}background-image:${({theme:e})=>{const t=xs(e.colors.base.background,.5),n=xs(e.colors.base.background,0);return`linear-gradient(90deg, ${n} 0%, ${t} 30%, ${t} 60%, ${n} 100%)`}};
|
|
143
|
+
`,L_=({extendedMessagePayload:e,onClickCTA:t=({url:n})=>ns(n)})=>{const n=e==null?void 0:e.cta_button;if(!n)return null;const r=()=>t(n);return a.createElement(O_,{id:`${ot}-ext-cta-button`,onClick:r},a.createElement(N_,{variant:"button"},n.label))},O_=_.default.button.attrs({type:"button"})`
|
|
144
144
|
all: unset;
|
|
145
145
|
display: flex;
|
|
146
146
|
width: 100%;
|
|
@@ -152,12 +152,12 @@
|
|
|
152
152
|
padding: 8px;
|
|
153
153
|
color: ${E.themedColor.textHighEmphasis};
|
|
154
154
|
background-color: ${E.color.background50};
|
|
155
|
-
${
|
|
155
|
+
${ne.dark`
|
|
156
156
|
background-color: ${E.color.ondark.textDisabled};
|
|
157
157
|
`}
|
|
158
158
|
|
|
159
|
-
${
|
|
160
|
-
`,
|
|
159
|
+
${xe}
|
|
160
|
+
`,N_=_.default(B)`overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,D_=e=>a.createElement(a.Fragment,null),$_=({extendedMessagePayload:e,onClickCitation:t=n=>ns(n.link)})=>{const{stringSet:n}=ie(),{theme:r}=Yr(),s=e==null?void 0:e.citations;return!s||s.length===0?null:a.createElement(P_,{id:`${ot}-ext-citation`},a.createElement(F_,{variant:"caption1",color:r.colors.messageIncoming.text},n.CITATION_SOURCE_TITLE),a.createElement(U_,null,s.map((o,i)=>a.createElement(H_,{key:`${o.embedding_id}-${i}`,onClick:()=>t(o)},a.createElement(te,{type:"source",size:16,color:r.colors.messageIncoming.text}),a.createElement(B_,{variant:"body3",color:r.colors.messageIncoming.text},o.title)))))},P_=_.default.div`display:flex;flex-direction:column;gap:8px;border-radius:8px;padding:8px 12px 6px;`,F_=_.default(B)`opacity:0.5;`,U_=_.default.div`display:flex;flex-direction:column;gap:8px;`,B_=_.default(B)`text-decoration:underline;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,H_=_.default.button.attrs({type:"button"})`
|
|
161
161
|
background: none;
|
|
162
162
|
border: none;
|
|
163
163
|
padding: 0;
|
|
@@ -172,127 +172,127 @@
|
|
|
172
172
|
&:hover {
|
|
173
173
|
opacity: 0.5;
|
|
174
174
|
}
|
|
175
|
-
`,
|
|
176
|
-
color: ${
|
|
177
|
-
border-color: ${
|
|
175
|
+
`,G_=e=>a.createElement(a.Fragment,null),Rr=e=>`${e}-filled`,z_=e=>e==="good"?he.AIAgentMessageFeedbackRating.GOOD:he.AIAgentMessageFeedbackRating.BAD,is=U.css`&:hover{opacity:0.8;}&:active{opacity:0.6;}`,hn={good:{onlight:E.color.secondary.dark,ondark:E.color.secondary.light},bad:{onlight:E.color.error.dark,ondark:E.color.error.light}},V_={good:E.themedColor.secondary,bad:E.themedColor.error},Ma=e=>U.css`color:${hn[e].onlight};border-color:${hn[e].onlight};${ne.dark`
|
|
176
|
+
color: ${hn[e].ondark};
|
|
177
|
+
border-color: ${hn[e].ondark};
|
|
178
178
|
`}
|
|
179
|
-
`,
|
|
179
|
+
`,q_=({visible:e,onClose:t,isEdit:n,initialRating:r,initialComment:s="",onSubmit:o,isCommentEnabled:i=!1})=>{const{stringSet:c}=ie(),{conversation:u}=ae(),{rootElement:d}=Qi(),m=mt(d),[h,f]=l.useState(r),[g,p]=l.useState(s),[v,S]=l.useState(!1),C=l.useRef(!1),A=h??r??"good",y=u.feedback;l.useLayoutEffect(()=>{e?(f(r),p(s)):(f(void 0),p(""))},[e,r,s]),l.useEffect(()=>{if(!e)return;const O=R=>{const F=R;F.metaKey||F.altKey||F.ctrlKey||(C.current=!0)},k=()=>{C.current=!1,S(!1)};return m.addEventListener("keydown",O),m.addEventListener("pointerdown",k),()=>{m.removeEventListener("keydown",O),m.removeEventListener("pointerdown",k)}},[m,e]);const T=()=>{h&&(o({rating:h,comment:g.trim()||void 0}),t())},I=()=>{t()};if(!e)return null;const N={feedback:y.container()};return a.createElement(ft,{portalContainerId:Se.WINDOW,visible:e,onClose:I,"aria-label":c.FEEDBACK_TITLE},a.createElement(K_,null,a.createElement(Y_,null,a.createElement(B,{variant:"h2",color:E.themedColor.textHighEmphasis},c.FEEDBACK_TITLE)),a.createElement(W_,null,a.createElement(j_,{...N.feedback.props},["good","bad"].map(O=>{const k=h===O,R=O==="good"?c.FEEDBACK_GOOD:c.FEEDBACK_BAD,F=y.button(O,k);return a.createElement(l.Fragment,{key:O},a.createElement(X_,{type:"button",$selected:k,$rating:O,...F.props,onClick:()=>f(O),"data-sb-initial-focus":O===A?"true":void 0},a.createElement(te,{type:k?Rr(O):O,size:24,color:"currentColor"}),a.createElement(B,{variant:"caption1",color:"currentColor"},R)),F.descriptionNode)}),N.feedback.descriptionNode),i&&a.createElement(Z_,null,a.createElement(B,{variant:"caption3",color:E.themedColor.textHighEmphasis},c.FEEDBACK_COMMENT_LABEL),a.createElement(J_,{placeholder:c.FEEDBACK_COMMENT_PLACEHOLDER,value:g,onChange:O=>p(O.target.value),onFocus:()=>S(C.current),onBlur:()=>S(!1),maxLength:100,$focusVisible:v,"data-focus-visible":v?"true":"false"}))),a.createElement(Q_,null,a.createElement(eE,{onClick:I},a.createElement(B,{variant:"button",color:E.themedColor.textHighEmphasis},c.FEEDBACK_CANCEL)),a.createElement(tE,{onClick:T,disabled:!h},a.createElement(B,{variant:"button"},n?c.FEEDBACK_SAVE:c.FEEDBACK_SUBMIT)))))},K_=_.default.div`width:280px;background-color:${({theme:e})=>e.colors.base.modalContentBackground};border-radius:12px;overflow:hidden;`,Y_=_.default.div`padding:24px;`,W_=_.default.div`padding-inline:24px;display:flex;flex-direction:column;gap:24px;`,j_=_.default.div`display:flex;gap:4px;`,X_=_.default.button`width:114px;height:64px;border-radius:12px;border:1px solid ${E.themedColor.textDisabled};box-sizing:border-box;cursor:pointer;display:flex;flex-direction:column;align-items:center;justify-content:center;padding:0;gap:0;transition:background-color 0.2s;color:${E.themedColor.textLowEmphasis};background-color:transparent;${({$selected:e,$rating:t})=>e&&Ma(t)}${is}`,Z_=_.default.label`display:flex;flex-direction:column;gap:6px;`,J_=_.default.textarea`font-family:inherit;font-size:12px;line-height:16px;border:1px solid ${E.themedColor.textDisabled};border-radius:4px;padding:6px 12px;color:${E.themedColor.textHighEmphasis};background-color:${E.themedColor.textLowEmphasisInverse};resize:none;field-sizing:content;min-height:28px;max-height:118px;overflow-y:auto;&::placeholder{color:${E.themedColor.textLowEmphasis};}&:focus{outline:none;}${({$focusVisible:e})=>e&&U.css`
|
|
180
180
|
outline: 2px solid ${E.themedColor.primary};
|
|
181
181
|
outline-offset: 2px;
|
|
182
182
|
`}
|
|
183
|
-
`,
|
|
183
|
+
`,Q_=_.default.div`padding-inline:24px;padding-block:16px;display:flex;justify-content:flex-end;gap:4px;`,wa=_.default.button`width:86px;height:40px;border-radius:20px;border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;transition:opacity 0.2s;`,eE=_.default(wa)`background-color:transparent;${is}`,tE=_.default(wa)`cursor:${({disabled:e})=>e?"not-allowed":"pointer"};opacity:${({disabled:e})=>e?.4:1};&:hover:not(:disabled){opacity:0.8;}&:active:not(:disabled){opacity:0.6;}background-color:${({theme:e})=>e.colors.base.primary};span{color:${({theme:e})=>e.colors.base.primaryContrastContent};}`,nE=({isBotMessage:e,isConversationClosed:t,isStreaming:n,isFeedbackEnabled:r,isFeedbackCommentEnabled:s,extendedMessagePayload:o,onFeedbackUpdate:i})=>{const{stringSet:c}=ie(),{conversation:u}=ae(),[d,m]=l.useState(!1),[h,f]=l.useState(!1),[g,p]=l.useState(void 0),[v,S]=l.useState(""),C=l.useRef(null),A=l.useRef(null),y=l.useRef(null),T=l.useRef(!1),I=u.feedback,N=o==null?void 0:o.feedback,O=(N==null?void 0:N.rating)??"none";if(O!=="none"?!1:!!(n||!e||!r||(o==null?void 0:o.bot_message_type)!=="generated"||t))return null;const R=q=>{q&&Ie(()=>{const J=q==="good"?C.current:A.current;J==null||J.focus()})},F=({restoreTrigger:q=!0}={})=>{f(!1),q&&R(y.current)},D=q=>{O==="none"?(p(q),S(""),m(!0)):(y.current=q,f(!0))},Q=()=>{i==null||i(null),F()},re=()=>{T.current=!0,F({restoreTrigger:!1}),p(N==null?void 0:N.rating),S((N==null?void 0:N.comment)??""),m(!0)},G=q=>{T.current=!1,i==null||i(q),m(!1),R(y.current)},H=()=>{m(!1),T.current&&(T.current=!1,f(!0))};return t&&O!=="none"?a.createElement(Io,{role:"presentation",$horizontal:!0},a.createElement(rE,null,a.createElement(te,{type:Rr(O),size:12,color:V_[O]})),(N==null?void 0:N.comment)&&a.createElement(xo,{variant:"caption2",style:{lineHeight:"16px"}},N.comment)):a.createElement(a.Fragment,null,a.createElement(Io,{role:"presentation"},a.createElement(sE,{role:"presentation"},["good","bad"].map(q=>{const J=O===q,K=I.button(q,J);return a.createElement(l.Fragment,{key:q},a.createElement(oE,{$selected:J,$rating:q,ref:q==="good"?C:A,...K.props,onClick:()=>D(q)},a.createElement(te,{type:J?Rr(q):q,size:14,color:"currentColor"})),K.descriptionNode)})),O!=="none"&&(N==null?void 0:N.comment)&&a.createElement(xo,{variant:"caption2"},N.comment)),a.createElement(dt,{visible:h,onClose:F,...I.optionsBottomSheet().props},a.createElement(dt.ActionItem,{onClick:re,initialFocus:!0},c.FEEDBACK_EDIT),a.createElement(dt.ActionItem,{onClick:Q,destructive:!0},c.FEEDBACK_REMOVE)),a.createElement(q_,{visible:d,onClose:H,isEdit:O!=="none",initialRating:g,initialComment:v,onSubmit:G,isCommentEnabled:s}))},Io=_.default.div`display:flex;flex-direction:${({$horizontal:e})=>e?"row":"column"};align-items:${({$horizontal:e})=>e?"flex-start":"stretch"};gap:4px;margin-top:8px;word-break:break-word;max-width:${oe.BODY_MAX_WIDTH}px;`,rE=_.default.div`padding:2px;flex-shrink:0;display:flex;align-items:center;`,sE=_.default.div`display:flex;gap:2px;`,oE=_.default.button`width:38px;height:20px;border-radius:18px;cursor:pointer;display:flex;align-items:center;justify-content:center;padding:0;transition:opacity 0.2s;box-sizing:border-box;color:${E.themedColor.textMidEmphasis};border:1px solid ${E.color.background200};background-color:transparent;${ne.dark`
|
|
184
184
|
border: 1px solid ${E.color.background400};
|
|
185
185
|
`}
|
|
186
186
|
|
|
187
|
-
${({$selected:e,$rating:t})=>e&&
|
|
187
|
+
${({$selected:e,$rating:t})=>e&&Ma(t)}
|
|
188
188
|
|
|
189
|
-
${
|
|
190
|
-
`,
|
|
189
|
+
${is}
|
|
190
|
+
`,xo=_.default(B)`color:${E.themedColor.textMidEmphasis};${ne.dark`
|
|
191
191
|
color: ${E.themedColor.textHighEmphasis};
|
|
192
192
|
`}
|
|
193
|
-
`,
|
|
193
|
+
`,as=U.css`width:100%;height:36px;border-radius:6px;cursor:pointer;transition:all 0.2s ease;padding:0 12px;border:none;outline:none;display:flex;align-items:center;justify-content:center;${xe}&:disabled{cursor:not-allowed;}`,Ro=_.default.button`${as};background-color:${E.themedColor.primary};color:${E.themedColor.textHighEmphasis};&:hover:not(:disabled){opacity:0.9;}`,iE=_.default.button`${as};color:${E.themedColor.primary};${ne.light`
|
|
194
194
|
background-color: ${E.color.background50};
|
|
195
195
|
`};
|
|
196
|
-
${
|
|
196
|
+
${ne.dark`
|
|
197
197
|
background-color: ${E.color.background700};
|
|
198
198
|
`};
|
|
199
199
|
|
|
200
200
|
&:hover:not(:disabled) {
|
|
201
201
|
opacity: 0.9;
|
|
202
202
|
}
|
|
203
|
-
`,
|
|
203
|
+
`,aE=_.default.button`${as};background-color:transparent;color:${E.themedColor.textHighEmphasis};&:hover:not(:disabled){opacity:0.7;}`,cE=e=>{switch(e){case"primary":return Ro;case"secondary":return iE;case"clear":return aE;default:return Ro}},lE=_.default.div`animation:1s infinite linear;animation-name:rotate;display:flex;align-items:center;justify-content:center;@keyframes rotate{from{transform:rotate(0);}to{transform:rotate(360deg);}}`,uE=({children:e,onClick:t,variant:n="primary",disabled:r=!1,loading:s=!1,className:o,...i})=>{const c=()=>{switch(n){case"primary":return E.themedColor.textHighEmphasisInverse;case"secondary":return E.themedColor.primary;case"clear":return E.themedColor.textHighEmphasis;default:return E.themedColor.textHighEmphasisInverse}},u=cE(n);return a.createElement(u,{onClick:t,disabled:r||s,className:o,...i},s?a.createElement(lE,null,a.createElement(te,{type:"spinner",size:22,color:c()})):a.createElement(B,{variant:"button",color:c()},e))},dE=({children:e,className:t,style:n,id:r,role:s})=>a.createElement(B,{variant:"caption4",color:E.themedColor.error,className:t,style:n,id:r,role:s},e),mE=({id:e,children:t,className:n,style:r,required:s,"aria-hidden":o})=>{const{stringSet:i}=ie();return a.createElement(B,{id:e,variant:"caption3",color:E.themedColor.textMidEmphasis,className:n,style:r,"aria-hidden":o},t,!s&&a.createElement("span",{style:{color:E.themedColor.textLowEmphasis}},` (${i.OPTIONAL})`))},hE=({value:e,onChange:t,placeholder:n,error:r=!1,submitted:s=!1,className:o,disabled:i=!1,max:c,...u})=>{const d=h=>{const g=h.target.value.replace(/[^0-9.-]/g,""),p=g.split("."),S=p.length>1?p[0]+"."+p.slice(1).join("").replace(/\./g,""):g;if(h.target.value=S,S===""||S==="-")t==null||t(null);else{const C=Number(S);if(!isNaN(C)){if(c!==void 0&&C>c)return;t==null||t(C)}}},m=e==null?"":String(e);return a.createElement(EE,{type:"text",value:m,onChange:d,placeholder:n,className:o,disabled:i||s,inputMode:"decimal",$error:r,$submitted:s,...u})},fE=U.css`width:100%;height:36px;padding:8px 12px;border-radius:6px;font-size:14px;font-weight:400;line-height:1.43;outline:none;transition:all 0.2s ease;${xe}&::placeholder{color:${E.themedColor.textLowEmphasis};}&::-webkit-inner-spin-button,&::-webkit-outer-spin-button{-webkit-appearance:none;margin:0;}`,gE=U.css`color:${E.themedColor.textHighEmphasis};border:1px solid transparent;cursor:not-allowed;${ne.light`
|
|
204
204
|
background-color: ${E.color.ondark.textMidEmphasis};
|
|
205
205
|
`}
|
|
206
|
-
${
|
|
206
|
+
${ne.dark`
|
|
207
207
|
background-color: ${E.color.onlight.textLowEmphasis};
|
|
208
208
|
`}
|
|
209
209
|
|
|
210
210
|
&::placeholder {
|
|
211
211
|
color: ${E.themedColor.textLowEmphasis};
|
|
212
212
|
}
|
|
213
|
-
`,
|
|
213
|
+
`,pE=U.css`border:1px solid ${E.themedColor.error};color:${E.themedColor.textHighEmphasis};${ne.light`
|
|
214
214
|
background-color: ${E.color.background50};
|
|
215
215
|
`}
|
|
216
|
-
${
|
|
216
|
+
${ne.dark`
|
|
217
217
|
background-color: ${E.color.onlight.textLowEmphasis};
|
|
218
218
|
`}
|
|
219
|
-
`,
|
|
219
|
+
`,_E=U.css`border:1px solid ${E.themedColor.textDisabled};color:${E.themedColor.textHighEmphasis};${ne.light`
|
|
220
220
|
background-color: ${E.color.background50};
|
|
221
221
|
`}
|
|
222
|
-
${
|
|
222
|
+
${ne.dark`
|
|
223
223
|
background-color: ${E.color.onlight.textLowEmphasis};
|
|
224
224
|
`}
|
|
225
225
|
|
|
226
226
|
&:focus {
|
|
227
227
|
border-color: ${E.themedColor.primary};
|
|
228
228
|
}
|
|
229
|
-
`,
|
|
229
|
+
`,EE=_.default.input`${fE}${({$error:e,$submitted:t})=>t?gE:e?pE:_E}`,CE=e=>{if(e.multiple){const{value:t=[],onChange:n,maxSelect:r,submitted:s=!1}=e;return{selectedValues:t,handleOptionClick:i=>{if(s)return;if(t.includes(i)){const u=t.filter(d=>d!==i);n==null||n(u)}else{if(r&&t.length>=r)return;const u=[...t,i];n==null||n(u)}}}}else{const{value:t,onChange:n,submitted:r=!1}=e;return{selectedValues:t?[t]:[],handleOptionClick:o=>{r||t!==o&&(n==null||n(o))}}}},ka=e=>{const{options:t,submitted:n=!1,error:r=!1,className:s,groupLabel:o}=e,{conversation:i}=ae(),c=e.multiple===!0,{selectedValues:u,handleOptionClick:d}=CE(e),m=t.some(h=>u.includes(h.value));return a.createElement(vE,{className:s,...c?void 0:i.form.singleSelectGroup(o).props},t.map((h,f)=>{const g=u.includes(h.value),p=o?`${o}, ${h.label}`:h.label;return a.createElement(RE,{key:h.value,type:"button",$active:g,$submitted:n,$error:r,...(c?i.form.multiSelectOption(p,g,n):i.form.singleSelectOption(p,g,n,f,t.length,m,v=>{const S=t[v];S&&d(S.value)})).props,disabled:n,onClick:()=>d(h.value)},a.createElement(B,{variant:"caption1",color:bE(g,n)},h.label))}))},bE=(e,t)=>t?e?E.themedColor.textHighEmphasis:E.themedColor.textDisabled:e?E.themedColor.primary:E.themedColor.textMidEmphasis,vE=_.default.div`display:flex;flex-wrap:wrap;gap:4px 2px;`,SE=U.css`display:inline-flex;align-items:center;padding:8px 12px;border-radius:15px;transition:all 0.2s ease;`,yE=U.css`cursor:default;background-color:${E.color.ondark.textMidEmphasis};color:${E.themedColor.textHighEmphasis};${ne.dark`
|
|
230
230
|
background-color: transparent;
|
|
231
231
|
border: 1px solid white;
|
|
232
232
|
color: white;
|
|
233
233
|
`}
|
|
234
|
-
`,
|
|
234
|
+
`,AE=U.css`cursor:default;${ne.light`
|
|
235
235
|
background-color: ${E.color.ondark.textMidEmphasis};
|
|
236
236
|
color: ${E.themedColor.textDisabled};
|
|
237
237
|
`}
|
|
238
|
-
${
|
|
238
|
+
${ne.dark`
|
|
239
239
|
background-color: ${E.color.onlight.textLowEmphasis};
|
|
240
240
|
border: 1px solid ${E.color.onlight.textLowEmphasis};
|
|
241
241
|
color: ${E.themedColor.textDisabled};
|
|
242
242
|
`}
|
|
243
|
-
`,
|
|
243
|
+
`,TE=U.css`cursor:pointer;border:1px solid ${E.themedColor.primary};${ne.light`
|
|
244
244
|
background-color: ${E.color.background50};
|
|
245
245
|
color: ${E.themedColor.primary};
|
|
246
246
|
`}
|
|
247
|
-
${
|
|
247
|
+
${ne.dark`
|
|
248
248
|
background-color: ${E.color.onlight.textLowEmphasis};
|
|
249
249
|
color: ${E.themedColor.primary};
|
|
250
250
|
`}
|
|
251
|
-
`,
|
|
251
|
+
`,IE=U.css`cursor:pointer;border:1px solid ${E.themedColor.textDisabled};${ne.light`
|
|
252
252
|
background-color: ${E.color.background50};
|
|
253
253
|
color: ${E.themedColor.textMidEmphasis};
|
|
254
254
|
`}
|
|
255
|
-
${
|
|
255
|
+
${ne.dark`
|
|
256
256
|
background-color: ${E.color.onlight.textLowEmphasis};
|
|
257
257
|
color: ${E.themedColor.textMidEmphasis};
|
|
258
258
|
`}
|
|
259
|
-
`,
|
|
260
|
-
${r} ${
|
|
259
|
+
`,xE=U.css`border-color:${E.themedColor.error}!important;`,RE=_.default.button`${SE}${({$active:e,$submitted:t,$error:n})=>{if(t)return e?yE:AE;const r=e?TE:IE;return n?U.css`
|
|
260
|
+
${r} ${xE}
|
|
261
261
|
`:r}}
|
|
262
|
-
`,
|
|
262
|
+
`,ME=e=>a.createElement(ka,{...e,multiple:!1}),wE=e=>a.createElement(ka,{...e,multiple:!0}),kE=_.default.div`width:100%;height:1px;background-color:${E.themedColor.textDisabled};`,LE=({className:e})=>a.createElement(kE,{className:e}),OE=({id:e,value:t="",onChange:n,placeholder:r,variant:s="single-line",error:o=!1,submitted:i=!1,className:c,disabled:u=!1,maxLength:d,...m})=>{const f={id:e,value:t,onChange:g=>{const p=g.target.value;d&&p.length>d||n==null||n(p)},placeholder:r,className:c,disabled:u||i,maxLength:d,$error:o,$submitted:i,...m};return s==="multi-line"?a.createElement(DE,{...f}):a.createElement(NE,{...f})},La=U.css`width:100%;padding:8px 12px;border-radius:6px;font-size:14px;font-weight:400;line-height:1.43;outline:none;transition:all 0.2s ease;${xe}&::placeholder{color:${E.themedColor.textLowEmphasis};}`,Oa=U.css`color:${E.themedColor.textHighEmphasis};border:1px solid transparent;cursor:not-allowed;${ne.light`
|
|
263
263
|
background-color: ${E.color.ondark.textMidEmphasis};
|
|
264
264
|
`}
|
|
265
|
-
${
|
|
265
|
+
${ne.dark`
|
|
266
266
|
background-color: ${E.color.onlight.textLowEmphasis};
|
|
267
267
|
`}
|
|
268
268
|
|
|
269
269
|
&::placeholder {
|
|
270
270
|
color: ${E.themedColor.textLowEmphasis};
|
|
271
271
|
}
|
|
272
|
-
`,
|
|
272
|
+
`,Na=U.css`border:1px solid ${E.themedColor.error};color:${E.themedColor.textHighEmphasis};${ne.light`
|
|
273
273
|
background-color: ${E.color.background50};
|
|
274
274
|
`}
|
|
275
|
-
${
|
|
275
|
+
${ne.dark`
|
|
276
276
|
background-color: ${E.color.onlight.textLowEmphasis};
|
|
277
277
|
`}
|
|
278
|
-
`,
|
|
278
|
+
`,Da=U.css`border:1px solid ${E.themedColor.textDisabled};color:${E.themedColor.textHighEmphasis};${ne.light`
|
|
279
279
|
background-color: ${E.color.background50};
|
|
280
280
|
`}
|
|
281
|
-
${
|
|
281
|
+
${ne.dark`
|
|
282
282
|
background-color: ${E.color.onlight.textLowEmphasis};
|
|
283
283
|
`}
|
|
284
284
|
|
|
285
285
|
&:focus {
|
|
286
286
|
border-color: ${E.themedColor.primary};
|
|
287
287
|
}
|
|
288
|
-
`,
|
|
288
|
+
`,NE=_.default.input`${La};height:36px;${({$error:e,$submitted:t})=>t?Oa:e?Na:Da}`,DE=_.default.textarea`${La};height:96px;resize:none;font-family:inherit;${({$error:e,$submitted:t})=>t?Oa:e?Na:Da}`,$E=({children:e,className:t,style:n})=>a.createElement(B,{variant:"button",color:E.themedColor.textHighEmphasis,className:t,style:n},e),ke={Title:$E,Label:mE,ErrorLabel:dE,Separator:LE,Button:uE,TextInput:OE,NumberInput:hE,SingleSelect:ME,MultiSelect:wE},PE=1,FE=new Set(["text","number","single-select","multi-select"]),$a=typeof __SBA_USE_FORM__>"u"||__SBA_USE_FORM__,UE=({messageForm:e,onError:t})=>{const n=l.useRef(void 0);l.useEffect(()=>{if($a||!e||!t)return;const r=e.key??"";n.current!==r&&(t(new Error("Form rendering is disabled")),n.current=r)},[e,t])},BE=e=>{var C,A;const t=(C=e.extendedMessagePayload)==null?void 0:C.form;if(UE({messageForm:t,onError:(A=e.statsCallbacks)==null?void 0:A.onFormRenderError}),!$a)return null;if(!t)throw new Error("Form is not provided");const{stringSet:n}=ie(),{conversation:r}=ae(),[s,o]=l.useState({submitting:!1,canceling:!1}),[i,c]=l.useState({visible:!1}),{state:u,fields:d,submit:m,cancel:h,updateFieldValue:f}=Mm(t,{labels:{required:n.FORM_VALIDATION_REQUIRED,regex:n.FORM_VALIDATION_REGEX_FAILED,minLength:n.FORM_VALIDATION_MIN_LENGTH,maxLength:n.FORM_VALIDATION_MAX_LENGTH,min:n.FORM_VALIDATION_MIN,max:n.FORM_VALIDATION_MAX,minSelect:n.FORM_VALIDATION_MIN_SELECT,maxSelect:n.FORM_VALIDATION_MAX_SELECT},onSubmit:y=>{var T;return(T=e.onSubmitForm)==null?void 0:T.call(e,{key:t.key,data:y})},onCancel:()=>{var y;return(y=e.onCancelForm)==null?void 0:y.call(e,{key:t.key})}}),g=u==="submitted",p=async()=>{o(y=>({...y,submitting:!0}));try{await m()}catch(y){c({visible:!0,description:y instanceof Error?y.message:n.TRY_AGAIN})}finally{o(y=>({...y,submitting:!1}))}},v=async()=>{o(y=>({...y,canceling:!0}));try{await h()}catch(y){c({visible:!0,description:y instanceof Error?y.message:n.TRY_AGAIN})}finally{o(y=>({...y,canceling:!1}))}},S=l.useMemo(()=>{const y=()=>t.version>PE,T=()=>t.fields.some(I=>!FE.has(I.type));return y()||T()?{visible:!1,cancelable:!0,reason:n.FORM_NOT_SUPPORTED}:u==="draft"&&(e.isHandedOff||e.isConversationClosed)?{visible:!1,cancelable:!1,reason:n.FORM_UNAVAILABLE}:{visible:!0,cancelable:!0,reason:""}},[t.version,t.fields,u,e.isHandedOff,e.isConversationClosed]);return u==="canceled"?null:S.visible?a.createElement(l.Fragment,null,a.createElement(Mo,{$maxWidth:e.maxBodyWidth??oe.BODY_MAX_WIDTH},a.createElement(ke.Title,null,t.title),a.createElement(HE,null,d.map(y=>a.createElement(GE,{key:y.key},a.createElement(ke.Label,{style:{marginBottom:"6px"},required:y.required},y.label),y.type==="text"&&a.createElement(ke.TextInput,{value:y.value||"",placeholder:y.placeholder,onChange:T=>f(y.key,T),disabled:g,error:!!y.error,submitted:g,variant:y.layout==="multiline"?"multi-line":"single-line",maxLength:y.maxLength,...r.form.textInput(y.label,y.required??!1,g).props}),y.type==="number"&&a.createElement(ke.NumberInput,{value:y.value||null,placeholder:y.placeholder,onChange:T=>f(y.key,T),disabled:g,error:!!y.error,submitted:g,max:y.max,...r.form.numberInput(y.label,y.required??!1,g).props}),y.type==="single-select"&&a.createElement(ke.SingleSelect,{options:y.options.map(T=>({label:T,value:T})),value:y.value||"",onChange:T=>f(y.key,T),submitted:g,groupLabel:y.label}),y.type==="multi-select"&&a.createElement(ke.MultiSelect,{options:y.options.map(T=>({label:T,value:T})),value:y.value||[],onChange:T=>f(y.key,T),submitted:g,maxSelect:y.maxSelect,groupLabel:y.label}),y.error&&a.createElement(ke.ErrorLabel,{style:{marginTop:"4px"}},y.error)))),a.createElement(ke.Separator,null),a.createElement(zE,null,a.createElement(ke.Button,{variant:g?"clear":"primary",...r.form.button(g?n.SUBMITTED:n.BUTTON__SUBMIT).props,onClick:p,disabled:g||s.canceling,loading:s.submitting},g?n.SUBMITTED:n.BUTTON__SUBMIT),u!=="submitted"&&a.createElement(ke.Button,{variant:"secondary",...r.form.button(n.BUTTON__CANCEL).props,onClick:v,disabled:s.submitting,loading:s.canceling},n.BUTTON__CANCEL))),a.createElement(Fn,{...i,onClose:()=>c({visible:!1,title:""})})):a.createElement(Mo,{$maxWidth:e.maxBodyWidth??oe.BODY_MAX_WIDTH},a.createElement(B,{variant:"body3"},S.reason),S.cancelable&&a.createElement(ke.Button,{variant:"primary",...r.form.button(n.BUTTON__CANCEL).props,onClick:v,loading:s.canceling},n.BUTTON__CANCEL))},Mo=_.default.div`display:flex;flex-direction:column;gap:12px;border-radius:12px;overflow:hidden;max-width:${({$maxWidth:e})=>e}px;${({theme:e})=>U.css`
|
|
289
289
|
color: ${e.colors.messageIncoming.text};
|
|
290
290
|
background-color: ${e.colors.messageIncoming.background};
|
|
291
291
|
`}
|
|
292
292
|
padding: 16px 12px;
|
|
293
293
|
transition: max-width 0.3s;
|
|
294
294
|
overflow-wrap: break-word;
|
|
295
|
-
`,
|
|
295
|
+
`,HE=_.default.div`display:flex;flex-direction:column;gap:12px;`,GE=_.default.div`display:flex;flex-direction:column;`,zE=_.default.div`display:flex;flex-direction:column;gap:8px;`,VE=e=>a.createElement(a.Fragment,null),Mr=typeof __SBA_USE_MESSAGE_TEMPLATE__>"u"||__SBA_USE_MESSAGE_TEMPLATE__?l.lazy(()=>Promise.resolve().then(()=>require("./cjs/ZOM6SoNd.cjs")).then(e=>({default:e.MessageTemplateWrapper}))):null,qE=({messageTemplate:e,onError:t})=>{const n=l.useRef(void 0);l.useEffect(()=>{if(Mr||!e||!t)return;const r=e.key??"";n.current!==r&&(t(new Error("Message template rendering is disabled")),n.current=r)},[e,t])},KE=e=>{var n,r,s;const t=(n=e.extendedMessagePayload)==null?void 0:n.message_template;return qE({messageTemplate:t,onError:(r=e.statsCallbacks)==null?void 0:r.onMessageTemplateError}),Mr?a.createElement(Kt,{errorFallback:e.messageTemplateErrorFallback,loadingFallback:e.messageTemplateLoadingFallback,onError:(s=e.statsCallbacks)==null?void 0:s.onMessageTemplateError},a.createElement(Mr,{...e})):null},YE=({extendedMessagePayload:e,onClickSuggestedReply:t,suggestedRepliesDirection:n="vertical"})=>{const{conversation:r}=ae(),[s,o]=l.useState(!1),{suggestedReplies:i}=r,c=(e==null?void 0:e.suggested_replies)??[];if(c.length===0||s)return null;const u=d=>{t&&(t({reply:d}),o(!0))};return a.createElement(WE,{id:`${ot}-ext-suggested-replies`,role:"presentation",$type:n},c.map((d,m)=>{const h=i.item(d,m);return a.createElement(l.Fragment,{key:m},a.createElement(jE,{$type:n,...h.props,onClick:()=>u(d)},a.createElement(XE,{variant:"body3"},d)),h.descriptionNode)}))},WE=_.default.div`margin:16px 0;padding:0 ${oe.HORIZONTAL_PADDING}px;position:relative;display:flex;align-self:stretch;gap:8px;${({$type:e})=>e==="vertical"?ZE:JE};`,jE=_.default.button.attrs({type:"button"})`
|
|
296
296
|
all: unset;
|
|
297
297
|
box-sizing: border-box;
|
|
298
298
|
padding: 8px 12px;
|
|
@@ -310,61 +310,61 @@
|
|
|
310
310
|
background-color: ${E.themedColor.bg_100_500};
|
|
311
311
|
}
|
|
312
312
|
|
|
313
|
-
${
|
|
313
|
+
${xe}
|
|
314
314
|
|
|
315
|
-
${({$type:e,theme:t})=>
|
|
316
|
-
`,
|
|
315
|
+
${({$type:e,theme:t})=>U.css`${e==="vertical"?QE:eC};&:active{background-color:${t.colors.base.primary};color:${t.colors.base.primaryContrastContent};}`}
|
|
316
|
+
`,XE=_.default(B)`color:inherit;`,ZE=U.css`flex-direction:column;align-items:flex-end;`,JE=U.css`flex-direction:row;overflow-x:scroll;-ms-overflow-style:none;scrollbar-width:none;&::-webkit-scrollbar{display:none;}`,QE=U.css`max-width:calc(100% - 70px);white-space:pre-wrap;`,eC=U.css`white-space:nowrap;`,tC=e=>{const{components:t}=Ct.useContext(),{stringSet:n}=ie(),r=ni(e)?a.createElement(t.TextMessageBody,{...e}):null;if(e.messageType==="user")return r;if(e.messageType==="file"){const s=e.file;return s.type.startsWith("image")||s.type.startsWith("video")?a.createElement(t.MediaMessageBody,{...e},r):a.createElement(t.FileMessageBody,{...e},r)}return e.messageType==="multipleFiles"?a.createElement(t.MultipleFilesMessageBody,{...e},r):a.createElement(t.TextMessageBody,{...e,message:n.UNKNOWN__UNKNOWN_MESSAGE_TYPE})},nC=e=>{var T,I,N,O,k;const{components:t}=Ct.useContext(),{streamText:n,isAnimating:r,isHolding:s}=Km({text:e.message,enabled:e.isStreaming,snapOnDisable:((T=e.extendedMessagePayload)==null?void 0:T.is_last_in_turn)!==!0,deferredMarkdownElements:e.deferredMarkdownElements,onAnimationStart:e.onStreamAnimationStart,onAnimationProgress:e.onStreamAnimationProgress,onAnimationComplete:e.onStreamAnimationComplete,onAnimationHoldChange:e.onStreamAnimationHoldChange,onVisibleTextProgress:(I=e.statsCallbacks)==null?void 0:I.onVisibleTextProgress,onRenderedTextProgress:(N=e.statsCallbacks)==null?void 0:N.onRenderedTextProgress});if(s)return null;const o={...e,message:n,extendedMessagePayload:r?{}:e.extendedMessagePayload},i=!!o.isTyping,c=!!o.isSenderAvatarVisible,u=Wt(o.extendedMessagePayload),d=u.hasCTAButton,m=u.hasChallenge,h=u.hasCitations,f=u.hasForm,g=u.hasMessageTemplate,p=!!o.createdAt,v=d||h,S=o.groupType==="top"||o.groupType==="single",C=o.groupType==="bottom"||o.groupType==="single",A=c?oe.AVATAR_SIZE:0,y=v&&a.createElement(l.Fragment,null,d&&a.createElement(sC,{$marginTop:12,$paddingInline:12},a.createElement(t.CTAButton,{...o})),h&&a.createElement(t.Citation,{...o}));return a.createElement(rC,{$marginBottom:i?0:kn(o.groupType)},S&&a.createElement(oC,null,c&&a.createElement(t.SenderAvatar,{...o}),a.createElement(t.SenderName,{...o})),a.createElement(aC,null,a.createElement(ur,{$extraStartPadding:A},i?a.createElement(t.TypingIndicator,{...o}):a.createElement(t.MessageBody,{...o},y)),g&&a.createElement(wo,{$startPadding:0,$endPadding:0},a.createElement(t.MessageTemplate,{...o,messageTemplateErrorFallback:o.messageTemplateErrorFallback??a.createElement(ur,{$extraStartPadding:A},a.createElement(t.MessageBody,{...o,messageType:"user",message:((k=(O=o.extendedMessagePayload)==null?void 0:O.message_template)==null?void 0:k.fallback_message)??"Cannot read this template."})),messageTemplateLoadingFallback:o.messageTemplateLoadingFallback??a.createElement(ur,{$extraStartPadding:A},a.createElement(t.TypingIndicator,{...o}))})),a.createElement(t.CustomMessageTemplate,{...o}),m&&a.createElement(t.Challenge,{...o}),f&&a.createElement(wo,{$extraStartPadding:A},a.createElement(t.Form,{...o}))),a.createElement(t.MessageLogs,{...o}),C&&p&&a.createElement(iC,{$extraStartPadding:A+8},a.createElement(t.SentTime,{...o})),a.createElement(l.Fragment,null,!i&&a.createElement(tn,{$extraStartPadding:A+8},a.createElement(t.Feedback,{...o})),o.suggestedRepliesVisible&&a.createElement(t.SuggestedReplies,{...o})))},Ct=je({template:nC,components:{SenderName:S_,SenderAvatar:b_,SentTime:A_,MessageBody:tC,TextMessageBody:p_,MediaMessageBody:Qp,FileMessageBody:Xp,MultipleFilesMessageBody:d_,TypingIndicator:I_,SuggestedReplies:YE,MessageTemplate:KE,CustomMessageTemplate:G_,Challenge:D_,CTAButton:L_,Citation:$_,Form:BE,Feedback:nE,MessageLogs:VE}}),rC=_.default.div.attrs({role:"presentation"})`
|
|
317
317
|
display: flex;
|
|
318
318
|
flex-direction: column;
|
|
319
319
|
align-items: flex-start;
|
|
320
320
|
margin-bottom: ${({$marginBottom:e})=>`${e}px`};
|
|
321
|
-
`,
|
|
321
|
+
`,tn=_.default.div.attrs({role:"presentation"})`
|
|
322
322
|
display: flex;
|
|
323
323
|
align-self: stretch;
|
|
324
324
|
justify-content: flex-start;
|
|
325
|
-
${({$startPadding:e=
|
|
325
|
+
${({$startPadding:e=oe.HORIZONTAL_PADDING,$endPadding:t=oe.HORIZONTAL_PADDING,$extraStartPadding:n=0})=>`
|
|
326
326
|
padding-inline: ${e+n}px ${t}px;
|
|
327
327
|
`}
|
|
328
|
-
`,
|
|
328
|
+
`,sC=_.default.div.attrs({role:"presentation"})`
|
|
329
329
|
display: flex;
|
|
330
330
|
flex-direction: column;
|
|
331
331
|
min-width: 0;
|
|
332
|
-
${({$marginTop:e=0,$paddingInline:t=0})=>
|
|
333
|
-
`,
|
|
332
|
+
${({$marginTop:e=0,$paddingInline:t=0})=>U.css`margin-top:${e}px;padding-inline:${t}px;`}
|
|
333
|
+
`,oC=_.default(tn)`display:flex;flex-direction:row;align-items:center;gap:8px;`,ur=_.default(tn)`display:flex;`,iC=_.default(tn)`margin-top:${oe.BODY_TIME_GAP}px;display:flex;align-items:flex-start;justify-content:flex-start;`,wo=_.default(tn).attrs({role:"presentation"})`
|
|
334
334
|
display: flex;
|
|
335
|
-
${({$startPadding:e=
|
|
335
|
+
${({$startPadding:e=oe.HORIZONTAL_PADDING,$endPadding:t=oe.HORIZONTAL_PADDING,$extraStartPadding:n=0})=>`
|
|
336
336
|
padding-inline: ${e+n}px ${t}px;
|
|
337
337
|
`}
|
|
338
|
-
`,
|
|
338
|
+
`,aC=_.default.div.attrs({role:"presentation"})`
|
|
339
339
|
display: flex;
|
|
340
340
|
flex-direction: column;
|
|
341
341
|
min-width: 0;
|
|
342
342
|
max-width: 100%;
|
|
343
|
-
gap: ${
|
|
344
|
-
`;function
|
|
343
|
+
gap: ${oe.GAP_GROUPED}px;
|
|
344
|
+
`;function cC({file:e,children:t,onClickFile:n,sendingStatus:r}){const s=(()=>{if(!(!n||r==="failed"))return()=>n==null?void 0:n(e)})();return a.createElement(lC,null,a.createElement(os,{name:e.name,mimeType:e.type,type:Nr(e.name,e.type),onClick:s}),t)}const lC=_.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${oe.GAP_GROUPED}px;`;function uC({sendingStatus:e,file:t,metadata:n,onClickMedia:r,onClickMediaFiles:s,children:o}){const{conversation:i}=ae(),{aspectRatio:c,localFile:u}=n,[d]=l.useState(()=>u instanceof Blob?URL.createObjectURL(u):t.url),[m,h]=l.useState(!1),f=(()=>{if(e!=="failed"){if(s)return()=>s({files:[{url:d,type:t.type,name:t.name}],index:0});if(r)return()=>r({...t,url:d})}})(),g=f?i.file.buttonLikePreview({name:t.name,mimeType:t.type,onActivate:f}):i.file.preview({name:t.name,mimeType:t.type}),p={...g.props,$ratio:c,$clickable:!!f};return a.createElement(dC,null,a.createElement(mC,{...p},!m&&a.createElement(Et,{size:26},a.createElement(te,{type:"spinner",color:"textLowEmphasis",size:26})),a.createElement(hC,{$loaded:m,src:d,alt:"image-message",onLoad:()=>h(!0)}),g.descriptionNode),o)}const dC=_.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${oe.GAP_GROUPED}px;`,mC=_.default.div`width:${oe.BODY_MAX_WIDTH}px;border-radius:12px;overflow:hidden;cursor:${e=>e.$clickable?"pointer":"default"};height:auto;aspect-ratio:${e=>e.$ratio};position:relative;display:flex;align-items:center;justify-content:center;${ne.light`
|
|
345
345
|
background-color: ${E.color.background100};
|
|
346
346
|
`}
|
|
347
|
-
${
|
|
347
|
+
${ne.dark`
|
|
348
348
|
background-color: ${E.color.background400};
|
|
349
349
|
`}
|
|
350
|
-
`,
|
|
350
|
+
`,hC=_.default.img`position:absolute;width:100%;height:100%;inset-block-start:0;inset-inline-start:0;object-fit:cover;opacity:${e=>e.$loaded?1:0};transition:opacity 0.5s ease;`,fC=({sendingStatus:e,files:t,metadata:n,onClickMedia:r,onClickMediaFiles:s,children:o})=>{const[i]=l.useState(()=>n.localFiles?n.localFiles.filter(m=>m instanceof Blob).map(m=>({...m,url:URL.createObjectURL(m)})):t),c=e==="pending",u=e==="failed",d=m=>{if(u||c)return;const h=i[m];h&&(s?s({files:i,index:m}):r&&r({url:h.url,type:h.type||"image/*"}))};return a.createElement(gC,null,a.createElement(ya,{images:i,isPending:c,onClickImage:d}),o)},gC=_.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${oe.GAP_GROUPED}px;`;function pC(e){var n,r;const t=l.useMemo(()=>{const s=f_(Ta(e.message));return Wo.default.sanitize(s)},[e.message]);return a.createElement(_C,{$maxWidth:e.maxBodyWidth??oe.BODY_MAX_WIDTH,$color:(n=e.customStyle)==null?void 0:n.bubbleContentColor,$bgColor:(r=e.customStyle)==null?void 0:r.bubbleBackgroundColor},a.createElement(EC,{variant:"body3",dangerouslySetInnerHTML:{__html:t}}))}const _C=_.default.div`display:flex;flex-direction:column;border-radius:12px;overflow:hidden;max-width:${({$maxWidth:e})=>e}px;${({theme:e,$color:t,$bgColor:n})=>U.css`
|
|
351
351
|
color: ${t||e.colors.messageOutgoing.text};
|
|
352
352
|
background-color: ${n||e.colors.messageOutgoing.background};
|
|
353
353
|
`}
|
|
354
354
|
padding: 12px 0;
|
|
355
355
|
transition: max-width 0.3s;
|
|
356
356
|
overflow-wrap: break-word;
|
|
357
|
-
`,
|
|
358
|
-
`,
|
|
359
|
-
`,pC=_.default(La)``,_C=_.default(La)`margin-top:${se.BODY_TIME_GAP}px;`,EC=e=>e.messageType!=="admin"?null:a.createElement(CC,null,a.createElement(H,{variant:"caption2",color:E.themedColor.textMidEmphasis},bC(Vo.default.sanitize(e.message),e.onClickLink))),CC=_.default.div`text-align:center;text-wrap:pretty;word-break:break-word;padding-inline:${se.HORIZONTAL_PADDING}px;a{text-decoration:underline;color:inherit;}`,bC=(e,t)=>{try{const n=[];let r=e,s=0;for(;r;){const o=r.match(/\[([^\]]+)\]\((https?:\/\/[^\s]+)\)/),i=r.match(/\*\*([^*]+)\*\*/),c=[o&&{match:o,type:"link"},i&&{match:i,type:"bold"}].filter(f=>!!f);if(!c.length){n.push(r);break}const u=c.reduce((f,g)=>g.match.index<f.match.index?g:f),{match:d,type:m}=u,h=d.index;h>0&&n.push(r.slice(0,h)),m==="link"?n.push(a.createElement("a",{key:s++,href:d[2],target:"_blank",rel:Vr,onClick:f=>{f.preventDefault();const g=d[2];g&&(t==null||t({url:g}))}},d[1])):m==="bold"&&n.push(a.createElement("strong",{key:s++},d[1])),r=r.slice(h+d[0].length)}return n.filter(o=>o!=="")}catch{return[e]}},vC=({direction:e,currentIndex:t,totalCount:n})=>n<=0?t:e==="next"?(t+1)%n:(t-1+n)%n,Oa=({options:e,value:t,disabled:n,hasError:r=!1,errorId:s,onChange:o})=>{const i=l.useRef([]),c=e.findIndex(h=>h.value===t),u=c>=0?c:0,d=h=>{requestAnimationFrame(()=>{var f;(f=i.current[h])==null||f.focus()})},m=h=>{const f=e[h];!f||n||(o==null||o(f.value),d(h))};return{radioGroupProps:h=>({role:"radiogroup","aria-label":h,...r&&s?{"aria-invalid":!0,"aria-errormessage":s}:{}}),getRadioProps:h=>({ref:f=>{i.current[h]=f},tabIndex:n?-1:h===u?0:-1,describedBy:r&&s?s:void 0,onArrowNavigate:f=>{m(vC({direction:f,currentIndex:h,totalCount:e.length}))}})}},SC=e=>{switch(e.key){case"ArrowDown":case"ArrowRight":return"next";case"ArrowUp":case"ArrowLeft":return"previous";default:return}},yC=({event:e,onClick:t,onArrowNavigate:n})=>{if(AC(e))return;const r=SC(e);if(r){e.preventDefault(),n==null||n(r);return}e.key!=="Enter"&&e.key!==" "||(e.preventDefault(),t==null||t())},AC=e=>e.repeat||e.currentTarget.getAttribute("aria-disabled")==="true",ts=l.forwardRef(({onClick:e,checked:t,label:n,disabled:r,tabIndex:s=0,labelVariant:o="caption2",describedBy:i,onArrowNavigate:c},u)=>{const d=t?E.themedColor.primary:r?E.themedColor.textDisabled:E.themedColor.textLowEmphasis,m=t?E.themedColor.textHighEmphasis:r?E.themedColor.textLowEmphasis:E.themedColor.textHighEmphasis;return a.createElement(xC,{ref:u,role:"radio",tabIndex:r?-1:s,"aria-checked":t,"aria-disabled":!!r,"aria-label":n,"aria-describedby":i,onClick:r?void 0:e,onKeyDown:h=>yC({event:h,onClick:e,onArrowNavigate:c})},a.createElement(TC,{"aria-hidden":"true"},a.createElement(ee,{size:20,type:t?"radio-on":"radio-off",color:d})),a.createElement(IC,{"aria-hidden":"true",variant:o,color:m},n))});ts.displayName="Radio";const TC=_.default.div`width:20px;height:20px;`,IC=_.default(H)`line-height:20px;word-break:break-word;`,xC=_.default.div`display:flex;align-items:flex-start;justify-content:flex-start;gap:2px;${Re}&[aria-disabled='false']{cursor:pointer;}`,RC=({csatPayload:e,submitted:t,defaultValue:n,value:r,onChange:s})=>{var u,d;const o=[{label:((u=e.cre)==null?void 0:u.positive_label)??"",value:!0},{label:((d=e.cre)==null?void 0:d.negative_label)??"",value:!1}],i=Oa({options:o,value:r,disabled:t,onChange:s});if(l.useEffect(()=>{typeof r>"u"&&typeof n=="boolean"&&(s==null||s(n))},[r,n]),!e.cre)return null;const c=e.cre;return a.createElement(MC,null,a.createElement(Le.Label,{required:c.required,"aria-hidden":!0},c.question),a.createElement(wC,{...i.radioGroupProps(c.question)},o.map((m,h)=>a.createElement(ts,{key:m.label,checked:r===m.value,label:m.label,disabled:t,...i.getRadioProps(h),onClick:()=>s==null?void 0:s(m.value)}))))},MC=_.default.div`display:flex;flex-direction:column;gap:8px;`,wC=_.default.div`display:flex;flex-direction:column;gap:8px;`,kC=({followUpItem:e,submitted:t,value:n="",onChange:r,hasError:s})=>{const{stringSet:o}=oe(),{conversation:i}=ie(),c=l.useId(),u=l.useId(),d=e.response_type!=="free_text",m=e.response_type==="single_choice"?e.options.map(f=>({label:f,value:f})):[],h=Oa({options:m,value:n,disabled:t,hasError:s,errorId:c,onChange:r});return a.createElement(LC,null,a.createElement(Le.Label,{id:u,required:e.required,"aria-hidden":d},e.question),e.response_type==="free_text"&&a.createElement(Le.TextInput,{variant:"multi-line",disabled:t,submitted:t,maxLength:100,value:n,onChange:f=>r(f),error:s,...i.form.textInput(o.A11Y_CSAT_TEXT_INPUT_LABEL,e.required??!1,t,{labelId:u}).props,"aria-invalid":s,"aria-errormessage":s?c:void 0}),e.response_type==="single_choice"&&a.createElement(OC,{...h.radioGroupProps(e.question)},m.map((f,g)=>a.createElement(ts,{key:f.value,checked:n===f.value,label:f.label,disabled:t,...h.getRadioProps(g),onClick:()=>r==null?void 0:r(f.value),labelVariant:"body3"}))),s&&a.createElement(NC,{role:"alert",id:c},o.FORM_VALIDATION_REQUIRED))},LC=_.default.div`display:flex;flex-direction:column;gap:8px;`,OC=_.default.div`display:flex;flex-direction:column;gap:8px;`,NC=_.default(Le.ErrorLabel)``,DC=({value:e,selected:t})=>a.createElement($C,{$selected:t,"aria-hidden":"true"},PC[e-1]),$C=_.default.div`user-select:none;-webkit-user-drag:none;width:40px;height:40px;aspect-ratio:1;opacity:${({$selected:e})=>e?1:.38};`,PC=[a.createElement("svg",{width:"40",height:"40",viewBox:"0 0 40 40",fill:"none",xmlns:"http://www.w3.org/2000/svg"},a.createElement("path",{d:"M2.08337 19.9999C2.08337 10.1048 10.1049 2.08325 20 2.08325C29.8952 2.08325 37.9167 10.1048 37.9167 19.9999C37.9167 29.8951 29.8952 37.9166 20 37.9166C10.1049 37.9166 2.08337 29.8951 2.08337 19.9999Z",fill:"url(#paint0_linear_159_173206)"}),a.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M12.5828 29.3328C13.1348 29.7473 13.9184 29.636 14.3329 29.084C15.6272 27.3607 17.6839 26.25 20 26.25C22.3164 26.25 24.373 27.3607 25.6672 29.084C26.0819 29.636 26.8654 29.7473 27.4175 29.3328C27.9695 28.9182 28.0809 28.1347 27.6662 27.5825C25.9202 25.2577 23.136 23.75 20 23.75C16.8642 23.75 14.0801 25.2577 12.334 27.5825C11.9194 28.1347 12.0308 28.9182 12.5828 29.3328Z",fill:"#141B34"}),a.createElement("path",{d:"M28.4454 13.7707C29.1329 13.8328 29.6405 14.4406 29.5785 15.1281C29.5165 15.8153 28.9095 16.3221 28.2224 16.2608C28.2224 16.2608 28.0287 16.2502 27.9272 16.2487C27.7229 16.2457 27.4387 16.2509 27.1229 16.2833C26.7869 16.3177 26.4649 16.3782 26.1804 16.4662L26.3045 16.86C26.7797 18.3675 25.5099 19.5813 24.2062 19.5813C23.5045 19.5813 22.8324 19.2617 22.43 18.6857C22.003 18.0745 21.9422 17.241 22.408 16.5344C22.751 16.0143 23.2449 15.3831 23.8964 14.8657C24.836 14.1195 26.044 13.8809 26.8675 13.7963C27.3029 13.7517 28.0154 13.7319 28.4454 13.7707Z",fill:"#141B34"}),a.createElement("path",{d:"M11.5549 13.7707C10.8674 13.8328 10.3597 14.4406 10.4218 15.1281C10.4838 15.8153 11.0908 16.3221 11.7779 16.2608C11.7779 16.2608 11.9716 16.2502 12.073 16.2487C12.2774 16.2457 12.5616 16.2509 12.8774 16.2833C13.2134 16.3177 13.5353 16.3782 13.8199 16.4662L13.6958 16.86C13.2205 18.3675 14.4904 19.5813 15.794 19.5813C16.4958 19.5813 17.168 19.2617 17.5703 18.6857C17.9971 18.0745 18.0581 17.241 17.5921 16.5344C17.2493 16.0143 16.7553 15.3831 16.1039 14.8657C15.1643 14.1195 13.9562 13.8809 13.1327 13.7963C12.6974 13.7517 11.9849 13.7319 11.5549 13.7707Z",fill:"#141B34"}),a.createElement("defs",null,a.createElement("linearGradient",{id:"paint0_linear_159_173206",x1:"20",y1:"2.08325",x2:"20",y2:"37.9166",gradientUnits:"userSpaceOnUse"},a.createElement("stop",{stopColor:"#FF2D1D"}),a.createElement("stop",{offset:"1",stopColor:"#FFA540"})))),a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},a.createElement("path",{d:"M2.083 20C2.083 10.105 10.105 2.083 20 2.083c9.895 0 17.917 8.021 17.917 17.917 0 9.895-8.022 17.917-17.917 17.917C10.105 37.917 2.083 29.895 2.083 20Z",fill:"#FFD46E"}),a.createElement("path",{d:"M14.249 27.334C15.851 26.13 17.844 25.417 20 25.417c2.156 0 4.149.714 5.751 1.917.553.415.664 1.199.25 1.751-.415.552-1.199.664-1.751.25-1.183-.889-2.652-1.416-4.25-1.416s-3.067.527-4.25 1.416c-.553.414-1.336.302-1.751-.25-.415-.552-.303-1.336.249-1.751Z",fill:"#141B34"}),a.createElement("path",{d:"M23.445 14.596c-.687.062-1.294-.445-1.356-1.132-.062-.687.445-1.295 1.132-1.357.082-.005.342-.02.482-.022.277-.004.662.002 1.097.047.823.085 2.031.323 2.97 1.07.652.518 1.146 1.15 1.489 1.67.466.706.405 1.54-.022 2.15-.402.576-1.074.896-1.775.896-1.304 0-2.573-1.214-2.098-2.722l.125-.394c-.285-.088-.607-.148-.942-.182-.316-.033-.6-.038-.804-.035-.101.002-.242.01-.294.013Z",fill:"#141B34"}),a.createElement("path",{d:"M11.779 14.596c-.687.062-1.294-.445-1.356-1.132-.062-.687.445-1.295 1.132-1.357.082-.005.342-.02.482-.022.277-.004.662.002 1.097.047.823.085 2.031.323 2.97 1.07.652.518 1.146 1.15 1.489 1.67.466.706.405 1.54-.022 2.15-.402.576-1.074.896-1.775.896-1.304 0-2.573-1.214-2.098-2.722l.124-.394c-.284-.088-.606-.148-.941-.182-.316-.033-.6-.038-.804-.035-.101.002-.243.01-.294.013Z",fill:"#141B34"})),a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},a.createElement("path",{d:"M2.083 20C2.083 10.105 10.105 2.083 20 2.083c9.895 0 17.917 8.021 17.917 17.917 0 9.895-8.022 17.917-17.917 17.917C10.105 37.917 2.083 29.895 2.083 20Z",fill:"#FFD46E"}),a.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M11.25 15c0-1.151.933-2.083 2.083-2.083h.015c1.151 0 2.084.933 2.084 2.083 0 1.151-.933 2.083-2.084 2.083h-.015c-1.15 0-2.083-.933-2.083-2.083ZM24.568 15c0-1.151.933-2.083 2.084-2.083h.015c1.151 0 2.083.933 2.083 2.083 0 1.151-.932 2.083-2.083 2.083h-.015c-1.151 0-2.084-.933-2.084-2.083Z",fill:"#141B34"}),a.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M13.75 26.667c0-.691.56-1.25 1.25-1.25h10c.69 0 1.25.559 1.25 1.25 0 .691-.56 1.25-1.25 1.25h-10c-.69 0-1.25-.559-1.25-1.25Z",fill:"#141B34"})),a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},a.createElement("path",{d:"M2.083 20C2.083 10.105 10.105 2.083 20 2.083c9.895 0 17.917 8.021 17.917 17.917 0 9.895-8.022 17.917-17.917 17.917C10.105 37.917 2.083 29.895 2.083 20Z",fill:"#FFD46E"}),a.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M12.583 24.001c.552-.414 1.335-.302 1.75.25 1.294 1.723 3.35 2.834 5.667 2.834s4.373-1.11 5.667-2.834c.415-.552 1.199-.664 1.751-.25.552.415.664 1.199.25 1.751C25.92 28.076 23.136 29.584 20 29.584s-5.92-1.508-7.666-3.832c-.415-.552-.303-1.336.249-1.751Z",fill:"#141B34"}),a.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M11.25 15c0-1.151.933-2.083 2.083-2.083h.015c1.151 0 2.084.933 2.084 2.083 0 1.151-.933 2.083-2.084 2.083h-.015c-1.15 0-2.083-.933-2.083-2.083ZM24.568 15c0-1.151.933-2.083 2.084-2.083h.015c1.151 0 2.083.933 2.083 2.083 0 1.151-.932 2.083-2.083 2.083h-.015c-1.151 0-2.084-.933-2.084-2.083Z",fill:"#141B34"})),a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},a.createElement("path",{d:"M2.083 20C2.083 10.105 10.105 2.083 20 2.083c9.895 0 17.917 8.021 17.917 17.917 0 9.895-8.022 17.917-17.917 17.917C10.105 37.917 2.083 29.895 2.083 20Z",fill:"#FFD46E"}),a.createElement("g",{clipPath:"url(#clip0_159_173224)"},a.createElement("g",{clipPath:"url(#clip1_159_173224)"},a.createElement("path",{d:"M20 30.624c3.752 0 6.904-2.532 7.789-5.956.412-1.593-.185-1.959-1.76-1.959H13.973c-1.575 0-2.173.366-1.761 1.959.885 3.424 4.037 5.956 7.788 5.956Z",fill:"#141B34"})),a.createElement("mask",{id:"mask0_159_173224",style:{maskType:"alpha"},maskUnits:"userSpaceOnUse",x:"12",y:"22",width:"16",height:"9"},a.createElement("path",{d:"M20 30.624c3.752 0 6.904-2.532 7.789-5.956.412-1.593-.185-1.959-1.76-1.959H13.973c-1.575 0-2.173.366-1.761 1.959.885 3.424 4.037 5.956 7.788 5.956Z",fill:"#141B34"})),a.createElement("g",{mask:"url(#mask0_159_173224)"},a.createElement("path",{d:"M20 32.998c3.278 0 5.936-1.594 5.936-3.561 0-1.968-2.658-3.562-5.936-3.562-3.278 0-5.936 1.594-5.936 3.562 0 1.967 2.658 3.561 5.936 3.561Z",fill:"#FF493B"}))),a.createElement("path",{d:"M11.667 15.833c0-1.381 1.12-2.5 2.5-2.5s2.5 1.12 2.5 2.5M23.333 15.833c0-1.381 1.12-2.5 2.5-2.5s2.5 1.12 2.5 2.5",stroke:"#141B34",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"}),a.createElement("defs",null,a.createElement("clipPath",{id:"clip0_159_173224"},a.createElement("rect",{width:"15.83",height:"7.915",fill:"white",transform:"translate(12.085 22.709)"})),a.createElement("clipPath",{id:"clip1_159_173224"},a.createElement("rect",{width:"15.83",height:"7.915",fill:"white",transform:"translate(12.085 22.709)"}))))],FC=({csatPayload:e,submitted:t,value:n,onChange:r})=>{const s=typeof n>"u",{conversation:o}=ie(),i=o.csat.scoresContainer(e.csat_question);return a.createElement(BC,null,a.createElement(H,{variant:"caption3",color:E.themedColor.textMidEmphasis,"aria-hidden":"true"},e.csat_question),a.createElement(HC,{...i.props},i.descriptionNode,e.csat_scores.map(({label:c,image_url:u},d)=>{const m=d+1,h=n===m,f=e.csat_scores.length,g=o.csat.scoreItem({score:m,label:c,selected:h,disabled:t,currentIndex:d,totalCount:f,hasSelection:!s,onChange:r});return a.createElement(GC,{key:d,type:"button",...g.props},a.createElement(UC,{value:m,selected:s||h,src:u}),!!c&&a.createElement(H,{"aria-hidden":"true",color:h?E.themedColor.textHighEmphasis:E.themedColor.textLowEmphasis,variant:"caption3"},c),g.descriptionNode)})))},UC=({value:e,src:t,selected:n})=>{const[r,s]=l.useState(!1),o=r?a.createElement(DC,{value:e,selected:n}):a.createElement(VC,{$selected:n,alt:"","aria-hidden":"true",src:t,onError:()=>s(!0)});return a.createElement(zC,null,o)},BC=_.default.div`display:flex;flex-direction:column;gap:8px;`,HC=_.default.div`display:flex;justify-content:space-between;align-self:center;width:100%;max-width:400px;gap:16px;`,GC=_.default.button`appearance:none;-webkit-appearance:none;background-color:transparent;border:none;padding:0;text-align:center;gap:4px;display:flex;flex-direction:column;align-items:center;justify-content:start;box-sizing:border-box;min-width:48px;max-width:68px;${Re}&:not(:disabled):hover span{color:${E.themedColor.textHighEmphasis};}`,zC=_.default.div`button:not(:disabled):hover &{border-radius:4px;cursor:pointer;background-color:${E.color.background200};${te.dark`
|
|
357
|
+
`,EC=_.default(B)`align-items:flex-start;line-height:140%;white-space:pre-wrap;padding:0 12px;`,CC=({sendingStatus:e})=>{const t=U.useTheme();switch(e){case"pending":return a.createElement(bC,{size:16},a.createElement(te,{type:"spinner",color:t.colors.messageOutgoing.background,size:16}));case"failed":return a.createElement("div",{style:{marginBottom:2}},a.createElement(te,{type:"error",color:E.themedColor.error,size:16}));case"scheduled":case"canceled":return null;default:return a.createElement("div",{style:{marginBottom:2}},a.createElement(te,{type:"done",color:E.themedColor.secondary,size:16}))}},bC=_.default(Et)`margin-bottom:2px;width:16px;height:16px;`,vC=({createdAt:e})=>{const{stringSet:t,format:n}=ie();return e?a.createElement(B,{variant:"caption4",color:E.themedColor.textLowEmphasis},n(e,t.DATE_FORMAT__MESSAGE_TIMESTAMP)):null},SC=e=>{const{components:t}=Ot.useContext(),{stringSet:n}=ie(),r=()=>{const i=ni(e)?a.createElement(t.TextMessageBody,{...e}):null;return e.messageType==="user"?i:e.messageType==="file"?e.file.type.startsWith("image")?a.createElement(t.MediaMessageBody,{...e},i):a.createElement(t.FileMessageBody,{...e},i):e.messageType==="multipleFiles"?a.createElement(t.MultipleFilesMessageBody,{...e},i):a.createElement(t.TextMessageBody,{...e,message:n.UNKNOWN__UNKNOWN_MESSAGE_TYPE})},s=e.sendingStatus==="failed"&&e.onClickFailedMessage,o=s?Bt({onActivate:()=>{var i;return(i=e.onClickFailedMessage)==null?void 0:i.call(e)}}):{};return a.createElement("div",{...o,style:{display:"contents",cursor:s?"pointer":"default"}},r())},yC=e=>a.createElement(a.Fragment,null),AC=e=>{const{components:t}=Ot.useContext(),n=e.sendingStatus==="succeeded",r=e.groupType==="bottom"||e.groupType==="single";return a.createElement(TC,{$marginBottom:kn(e.groupType)},a.createElement(IC,null,a.createElement(t.MessageBody,{...e})),a.createElement(t.MessageLogs,{...e}),r&&a.createElement(xC,{$extraEndPadding:8},n?a.createElement(t.SentTime,{...e}):a.createElement(t.SendingStatus,{...e})))},Ot=je({template:AC,components:{SendingStatus:CC,SentTime:vC,MessageBody:SC,TextMessageBody:pC,MediaMessageBody:uC,FileMessageBody:cC,MultipleFilesMessageBody:fC,MessageLogs:yC}}),TC=_.default.div`display:flex;flex:1;flex-direction:column;align-items:flex-end;margin-bottom:${({$marginBottom:e})=>`${e}px`};
|
|
358
|
+
`,Pa=_.default.div`display:flex;align-self:stretch;justify-content:flex-end;${({$startPadding:e=oe.HORIZONTAL_PADDING,$endPadding:t=oe.HORIZONTAL_PADDING,$extraEndPadding:n=0})=>`padding-inline: ${e}px ${t+n}px;`};
|
|
359
|
+
`,IC=_.default(Pa)``,xC=_.default(Pa)`margin-top:${oe.BODY_TIME_GAP}px;`,RC=e=>e.messageType!=="admin"?null:a.createElement(MC,null,a.createElement(B,{variant:"caption2",color:E.themedColor.textMidEmphasis},wC(Wo.default.sanitize(e.message),e.onClickLink))),MC=_.default.div`text-align:center;text-wrap:pretty;word-break:break-word;padding-inline:${oe.HORIZONTAL_PADDING}px;a{text-decoration:underline;color:inherit;}`,wC=(e,t)=>{try{const n=[];let r=e,s=0;for(;r;){const o=r.match(/\[([^\]]+)\]\((https?:\/\/[^\s]+)\)/),i=r.match(/\*\*([^*]+)\*\*/),c=[o&&{match:o,type:"link"},i&&{match:i,type:"bold"}].filter(f=>!!f);if(!c.length){n.push(r);break}const u=c.reduce((f,g)=>g.match.index<f.match.index?g:f),{match:d,type:m}=u,h=d.index;h>0&&n.push(r.slice(0,h)),m==="link"?n.push(a.createElement("a",{key:s++,href:d[2],target:"_blank",rel:Zr,onClick:f=>{f.preventDefault();const g=d[2];g&&(t==null||t({url:g}))}},d[1])):m==="bold"&&n.push(a.createElement("strong",{key:s++},d[1])),r=r.slice(h+d[0].length)}return n.filter(o=>o!=="")}catch{return[e]}},kC=({direction:e,currentIndex:t,totalCount:n})=>n<=0?t:e==="next"?(t+1)%n:(t-1+n)%n,Fa=({options:e,value:t,disabled:n,hasError:r=!1,errorId:s,onChange:o})=>{const i=l.useRef([]),c=e.findIndex(h=>h.value===t),u=c>=0?c:0,d=h=>{requestAnimationFrame(()=>{var f;(f=i.current[h])==null||f.focus()})},m=h=>{const f=e[h];!f||n||(o==null||o(f.value),d(h))};return{radioGroupProps:h=>({role:"radiogroup","aria-label":h,...r&&s?{"aria-invalid":!0,"aria-errormessage":s}:{}}),getRadioProps:h=>({ref:f=>{i.current[h]=f},tabIndex:n?-1:h===u?0:-1,describedBy:r&&s?s:void 0,onArrowNavigate:f=>{m(kC({direction:f,currentIndex:h,totalCount:e.length}))}})}},LC=e=>{switch(e.key){case"ArrowDown":case"ArrowRight":return"next";case"ArrowUp":case"ArrowLeft":return"previous";default:return}},OC=({event:e,onClick:t,onArrowNavigate:n})=>{if(NC(e))return;const r=LC(e);if(r){e.preventDefault(),n==null||n(r);return}e.key!=="Enter"&&e.key!==" "||(e.preventDefault(),t==null||t())},NC=e=>e.repeat||e.currentTarget.getAttribute("aria-disabled")==="true",cs=l.forwardRef(({onClick:e,checked:t,label:n,disabled:r,tabIndex:s=0,labelVariant:o="caption2",describedBy:i,onArrowNavigate:c},u)=>{const d=t?E.themedColor.primary:r?E.themedColor.textDisabled:E.themedColor.textLowEmphasis,m=t?E.themedColor.textHighEmphasis:r?E.themedColor.textLowEmphasis:E.themedColor.textHighEmphasis;return a.createElement(PC,{ref:u,role:"radio",tabIndex:r?-1:s,"aria-checked":t,"aria-disabled":!!r,"aria-label":n,"aria-describedby":i,onClick:r?void 0:e,onKeyDown:h=>OC({event:h,onClick:e,onArrowNavigate:c})},a.createElement(DC,{"aria-hidden":"true"},a.createElement(te,{size:20,type:t?"radio-on":"radio-off",color:d})),a.createElement($C,{"aria-hidden":"true",variant:o,color:m},n))});cs.displayName="Radio";const DC=_.default.div`width:20px;height:20px;`,$C=_.default(B)`line-height:20px;word-break:break-word;`,PC=_.default.div`display:flex;align-items:flex-start;justify-content:flex-start;gap:2px;${xe}&[aria-disabled='false']{cursor:pointer;}`,FC=({csatPayload:e,submitted:t,defaultValue:n,value:r,onChange:s})=>{var u,d;const o=[{label:((u=e.cre)==null?void 0:u.positive_label)??"",value:!0},{label:((d=e.cre)==null?void 0:d.negative_label)??"",value:!1}],i=Fa({options:o,value:r,disabled:t,onChange:s});if(l.useEffect(()=>{typeof r>"u"&&typeof n=="boolean"&&(s==null||s(n))},[r,n]),!e.cre)return null;const c=e.cre;return a.createElement(UC,null,a.createElement(ke.Label,{required:c.required,"aria-hidden":!0},c.question),a.createElement(BC,{...i.radioGroupProps(c.question)},o.map((m,h)=>a.createElement(cs,{key:m.label,checked:r===m.value,label:m.label,disabled:t,...i.getRadioProps(h),onClick:()=>s==null?void 0:s(m.value)}))))},UC=_.default.div`display:flex;flex-direction:column;gap:8px;`,BC=_.default.div`display:flex;flex-direction:column;gap:8px;`,HC=({followUpItem:e,submitted:t,value:n="",onChange:r,hasError:s})=>{const{stringSet:o}=ie(),{conversation:i}=ae(),c=l.useId(),u=l.useId(),d=e.response_type!=="free_text",m=e.response_type==="single_choice"?e.options.map(f=>({label:f,value:f})):[],h=Fa({options:m,value:n,disabled:t,hasError:s,errorId:c,onChange:r});return a.createElement(GC,null,a.createElement(ke.Label,{id:u,required:e.required,"aria-hidden":d},e.question),e.response_type==="free_text"&&a.createElement(ke.TextInput,{variant:"multi-line",disabled:t,submitted:t,maxLength:100,value:n,onChange:f=>r(f),error:s,...i.form.textInput(o.A11Y_CSAT_TEXT_INPUT_LABEL,e.required??!1,t,{labelId:u}).props,"aria-invalid":s,"aria-errormessage":s?c:void 0}),e.response_type==="single_choice"&&a.createElement(zC,{...h.radioGroupProps(e.question)},m.map((f,g)=>a.createElement(cs,{key:f.value,checked:n===f.value,label:f.label,disabled:t,...h.getRadioProps(g),onClick:()=>r==null?void 0:r(f.value),labelVariant:"body3"}))),s&&a.createElement(VC,{role:"alert",id:c},o.FORM_VALIDATION_REQUIRED))},GC=_.default.div`display:flex;flex-direction:column;gap:8px;`,zC=_.default.div`display:flex;flex-direction:column;gap:8px;`,VC=_.default(ke.ErrorLabel)``,qC=({value:e,selected:t})=>a.createElement(KC,{$selected:t,"aria-hidden":"true"},YC[e-1]),KC=_.default.div`user-select:none;-webkit-user-drag:none;width:40px;height:40px;aspect-ratio:1;opacity:${({$selected:e})=>e?1:.38};`,YC=[a.createElement("svg",{width:"40",height:"40",viewBox:"0 0 40 40",fill:"none",xmlns:"http://www.w3.org/2000/svg"},a.createElement("path",{d:"M2.08337 19.9999C2.08337 10.1048 10.1049 2.08325 20 2.08325C29.8952 2.08325 37.9167 10.1048 37.9167 19.9999C37.9167 29.8951 29.8952 37.9166 20 37.9166C10.1049 37.9166 2.08337 29.8951 2.08337 19.9999Z",fill:"url(#paint0_linear_159_173206)"}),a.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M12.5828 29.3328C13.1348 29.7473 13.9184 29.636 14.3329 29.084C15.6272 27.3607 17.6839 26.25 20 26.25C22.3164 26.25 24.373 27.3607 25.6672 29.084C26.0819 29.636 26.8654 29.7473 27.4175 29.3328C27.9695 28.9182 28.0809 28.1347 27.6662 27.5825C25.9202 25.2577 23.136 23.75 20 23.75C16.8642 23.75 14.0801 25.2577 12.334 27.5825C11.9194 28.1347 12.0308 28.9182 12.5828 29.3328Z",fill:"#141B34"}),a.createElement("path",{d:"M28.4454 13.7707C29.1329 13.8328 29.6405 14.4406 29.5785 15.1281C29.5165 15.8153 28.9095 16.3221 28.2224 16.2608C28.2224 16.2608 28.0287 16.2502 27.9272 16.2487C27.7229 16.2457 27.4387 16.2509 27.1229 16.2833C26.7869 16.3177 26.4649 16.3782 26.1804 16.4662L26.3045 16.86C26.7797 18.3675 25.5099 19.5813 24.2062 19.5813C23.5045 19.5813 22.8324 19.2617 22.43 18.6857C22.003 18.0745 21.9422 17.241 22.408 16.5344C22.751 16.0143 23.2449 15.3831 23.8964 14.8657C24.836 14.1195 26.044 13.8809 26.8675 13.7963C27.3029 13.7517 28.0154 13.7319 28.4454 13.7707Z",fill:"#141B34"}),a.createElement("path",{d:"M11.5549 13.7707C10.8674 13.8328 10.3597 14.4406 10.4218 15.1281C10.4838 15.8153 11.0908 16.3221 11.7779 16.2608C11.7779 16.2608 11.9716 16.2502 12.073 16.2487C12.2774 16.2457 12.5616 16.2509 12.8774 16.2833C13.2134 16.3177 13.5353 16.3782 13.8199 16.4662L13.6958 16.86C13.2205 18.3675 14.4904 19.5813 15.794 19.5813C16.4958 19.5813 17.168 19.2617 17.5703 18.6857C17.9971 18.0745 18.0581 17.241 17.5921 16.5344C17.2493 16.0143 16.7553 15.3831 16.1039 14.8657C15.1643 14.1195 13.9562 13.8809 13.1327 13.7963C12.6974 13.7517 11.9849 13.7319 11.5549 13.7707Z",fill:"#141B34"}),a.createElement("defs",null,a.createElement("linearGradient",{id:"paint0_linear_159_173206",x1:"20",y1:"2.08325",x2:"20",y2:"37.9166",gradientUnits:"userSpaceOnUse"},a.createElement("stop",{stopColor:"#FF2D1D"}),a.createElement("stop",{offset:"1",stopColor:"#FFA540"})))),a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},a.createElement("path",{d:"M2.083 20C2.083 10.105 10.105 2.083 20 2.083c9.895 0 17.917 8.021 17.917 17.917 0 9.895-8.022 17.917-17.917 17.917C10.105 37.917 2.083 29.895 2.083 20Z",fill:"#FFD46E"}),a.createElement("path",{d:"M14.249 27.334C15.851 26.13 17.844 25.417 20 25.417c2.156 0 4.149.714 5.751 1.917.553.415.664 1.199.25 1.751-.415.552-1.199.664-1.751.25-1.183-.889-2.652-1.416-4.25-1.416s-3.067.527-4.25 1.416c-.553.414-1.336.302-1.751-.25-.415-.552-.303-1.336.249-1.751Z",fill:"#141B34"}),a.createElement("path",{d:"M23.445 14.596c-.687.062-1.294-.445-1.356-1.132-.062-.687.445-1.295 1.132-1.357.082-.005.342-.02.482-.022.277-.004.662.002 1.097.047.823.085 2.031.323 2.97 1.07.652.518 1.146 1.15 1.489 1.67.466.706.405 1.54-.022 2.15-.402.576-1.074.896-1.775.896-1.304 0-2.573-1.214-2.098-2.722l.125-.394c-.285-.088-.607-.148-.942-.182-.316-.033-.6-.038-.804-.035-.101.002-.242.01-.294.013Z",fill:"#141B34"}),a.createElement("path",{d:"M11.779 14.596c-.687.062-1.294-.445-1.356-1.132-.062-.687.445-1.295 1.132-1.357.082-.005.342-.02.482-.022.277-.004.662.002 1.097.047.823.085 2.031.323 2.97 1.07.652.518 1.146 1.15 1.489 1.67.466.706.405 1.54-.022 2.15-.402.576-1.074.896-1.775.896-1.304 0-2.573-1.214-2.098-2.722l.124-.394c-.284-.088-.606-.148-.941-.182-.316-.033-.6-.038-.804-.035-.101.002-.243.01-.294.013Z",fill:"#141B34"})),a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},a.createElement("path",{d:"M2.083 20C2.083 10.105 10.105 2.083 20 2.083c9.895 0 17.917 8.021 17.917 17.917 0 9.895-8.022 17.917-17.917 17.917C10.105 37.917 2.083 29.895 2.083 20Z",fill:"#FFD46E"}),a.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M11.25 15c0-1.151.933-2.083 2.083-2.083h.015c1.151 0 2.084.933 2.084 2.083 0 1.151-.933 2.083-2.084 2.083h-.015c-1.15 0-2.083-.933-2.083-2.083ZM24.568 15c0-1.151.933-2.083 2.084-2.083h.015c1.151 0 2.083.933 2.083 2.083 0 1.151-.932 2.083-2.083 2.083h-.015c-1.151 0-2.084-.933-2.084-2.083Z",fill:"#141B34"}),a.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M13.75 26.667c0-.691.56-1.25 1.25-1.25h10c.69 0 1.25.559 1.25 1.25 0 .691-.56 1.25-1.25 1.25h-10c-.69 0-1.25-.559-1.25-1.25Z",fill:"#141B34"})),a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},a.createElement("path",{d:"M2.083 20C2.083 10.105 10.105 2.083 20 2.083c9.895 0 17.917 8.021 17.917 17.917 0 9.895-8.022 17.917-17.917 17.917C10.105 37.917 2.083 29.895 2.083 20Z",fill:"#FFD46E"}),a.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M12.583 24.001c.552-.414 1.335-.302 1.75.25 1.294 1.723 3.35 2.834 5.667 2.834s4.373-1.11 5.667-2.834c.415-.552 1.199-.664 1.751-.25.552.415.664 1.199.25 1.751C25.92 28.076 23.136 29.584 20 29.584s-5.92-1.508-7.666-3.832c-.415-.552-.303-1.336.249-1.751Z",fill:"#141B34"}),a.createElement("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M11.25 15c0-1.151.933-2.083 2.083-2.083h.015c1.151 0 2.084.933 2.084 2.083 0 1.151-.933 2.083-2.084 2.083h-.015c-1.15 0-2.083-.933-2.083-2.083ZM24.568 15c0-1.151.933-2.083 2.084-2.083h.015c1.151 0 2.083.933 2.083 2.083 0 1.151-.932 2.083-2.083 2.083h-.015c-1.151 0-2.084-.933-2.084-2.083Z",fill:"#141B34"})),a.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},a.createElement("path",{d:"M2.083 20C2.083 10.105 10.105 2.083 20 2.083c9.895 0 17.917 8.021 17.917 17.917 0 9.895-8.022 17.917-17.917 17.917C10.105 37.917 2.083 29.895 2.083 20Z",fill:"#FFD46E"}),a.createElement("g",{clipPath:"url(#clip0_159_173224)"},a.createElement("g",{clipPath:"url(#clip1_159_173224)"},a.createElement("path",{d:"M20 30.624c3.752 0 6.904-2.532 7.789-5.956.412-1.593-.185-1.959-1.76-1.959H13.973c-1.575 0-2.173.366-1.761 1.959.885 3.424 4.037 5.956 7.788 5.956Z",fill:"#141B34"})),a.createElement("mask",{id:"mask0_159_173224",style:{maskType:"alpha"},maskUnits:"userSpaceOnUse",x:"12",y:"22",width:"16",height:"9"},a.createElement("path",{d:"M20 30.624c3.752 0 6.904-2.532 7.789-5.956.412-1.593-.185-1.959-1.76-1.959H13.973c-1.575 0-2.173.366-1.761 1.959.885 3.424 4.037 5.956 7.788 5.956Z",fill:"#141B34"})),a.createElement("g",{mask:"url(#mask0_159_173224)"},a.createElement("path",{d:"M20 32.998c3.278 0 5.936-1.594 5.936-3.561 0-1.968-2.658-3.562-5.936-3.562-3.278 0-5.936 1.594-5.936 3.562 0 1.967 2.658 3.561 5.936 3.561Z",fill:"#FF493B"}))),a.createElement("path",{d:"M11.667 15.833c0-1.381 1.12-2.5 2.5-2.5s2.5 1.12 2.5 2.5M23.333 15.833c0-1.381 1.12-2.5 2.5-2.5s2.5 1.12 2.5 2.5",stroke:"#141B34",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"}),a.createElement("defs",null,a.createElement("clipPath",{id:"clip0_159_173224"},a.createElement("rect",{width:"15.83",height:"7.915",fill:"white",transform:"translate(12.085 22.709)"})),a.createElement("clipPath",{id:"clip1_159_173224"},a.createElement("rect",{width:"15.83",height:"7.915",fill:"white",transform:"translate(12.085 22.709)"}))))],WC=({csatPayload:e,submitted:t,value:n,onChange:r})=>{const s=typeof n>"u",{conversation:o}=ae(),i=o.csat.scoresContainer(e.csat_question);return a.createElement(XC,null,a.createElement(B,{variant:"caption3",color:E.themedColor.textMidEmphasis,"aria-hidden":"true"},e.csat_question),a.createElement(ZC,{...i.props},i.descriptionNode,e.csat_scores.map(({label:c,image_url:u},d)=>{const m=d+1,h=n===m,f=e.csat_scores.length,g=o.csat.scoreItem({score:m,label:c,selected:h,disabled:t,currentIndex:d,totalCount:f,hasSelection:!s,onChange:r});return a.createElement(JC,{key:d,type:"button",...g.props},a.createElement(jC,{value:m,selected:s||h,src:u}),!!c&&a.createElement(B,{"aria-hidden":"true",color:h?E.themedColor.textHighEmphasis:E.themedColor.textLowEmphasis,variant:"caption3"},c),g.descriptionNode)})))},jC=({value:e,src:t,selected:n})=>{const[r,s]=l.useState(!1),o=r?a.createElement(qC,{value:e,selected:n}):a.createElement(eb,{$selected:n,alt:"","aria-hidden":"true",src:t,onError:()=>s(!0)});return a.createElement(QC,null,o)},XC=_.default.div`display:flex;flex-direction:column;gap:8px;`,ZC=_.default.div`display:flex;justify-content:space-between;align-self:center;width:100%;max-width:400px;gap:16px;`,JC=_.default.button`appearance:none;-webkit-appearance:none;background-color:transparent;border:none;padding:0;text-align:center;gap:4px;display:flex;flex-direction:column;align-items:center;justify-content:start;box-sizing:border-box;min-width:48px;max-width:68px;${xe}&:not(:disabled):hover span{color:${E.themedColor.textHighEmphasis};}`,QC=_.default.div`button:not(:disabled):hover &{border-radius:4px;cursor:pointer;background-color:${E.color.background200};${ne.dark`
|
|
360
360
|
background-color: ${E.color.background500};
|
|
361
361
|
`}
|
|
362
362
|
}
|
|
363
|
-
`,
|
|
363
|
+
`,eb=_.default.img`user-select:none;-webkit-user-drag:none;width:40px;height:40px;aspect-ratio:1;opacity:${({$selected:e})=>e?1:.38};`,tb=({csatPayload:e})=>a.createElement(B,{variant:"button",color:E.themedColor.textHighEmphasis},e.title),dr=({csatPayload:e,type:t,renderSubmitButton:n,initialCsat:r,initialCsatReason:s,initialIsResolved:o})=>{const{params:i,setParams:c,error:u,setError:d,followUpItem:m,state:h,validateParams:f,itemProps:g}=Bm({csatPayload:e,type:t,initialCsat:r,initialCsatReason:s,initialIsResolved:o});return a.createElement(a.Fragment,null,a.createElement(nb,null,a.createElement(tb,{...g}),t===et.AI_AGENT_CSAT_5_WITH_CRE&&a.createElement(FC,{...g,defaultValue:o,value:i.isResolved,onChange:p=>c({isResolved:p})}),a.createElement(WC,{...g,value:i.csat,onChange:p=>c({csat:p})}),m&&a.createElement(HC,{...g,followUpItem:m,value:i.csatReason,onChange:p=>{c({csatReason:p}),d({followUpItem:!1})},hasError:u.followUpItem})),h!=="unsubmittable"&&a.createElement(a.Fragment,null,a.createElement(ke.Separator,null),n({state:h,params:i,validateParams:f})))},nb=_.default.div`display:flex;flex-direction:column;gap:12px;`,rb=e=>{const{stringSet:t}=ie();return ml(e,{title:t.CSAT_TITLE_UNSUBMITTED,question:t.CSAT_RATING_TITLE,cre:{question:t.CSAT_CRE_TITLE,positive_label:t.CSAT_CRE_SOLVED,negative_label:t.CSAT_CRE_NOT_SOLVED},followUp:{question:t.CSAT_REASON_PLACEHOLDER},submit_label:t.CSAT_SUBMIT_LABEL,submitted_label:t.CSAT_TITLE_SUBMITTED})},sb=()=>{const{stringSet:e}=ie();return a.createElement(B,{variant:"body2",color:E.themedColor.textMidEmphasis,style:{textAlign:"center"}},e.CSAT_SUBMISSION_EXPIRED)},ob=({onMount:e,children:t})=>(l.useEffect(()=>{e&&Ie(e)},[]),t),ib=e=>{const{conversation:t}=ae();if(e.messageType!=="admin.csat")throw new Error("Invalid message type");const{extendedMessagePayload:n,onSubmitCSAT:r,onScrollToBottom:s}=e,{csat:o,csatReason:i,csatExpireAt:c,isResolvedWhenDeterminedByUser:u}=e,d=Nn(),m=rb(n==null?void 0:n.csat),h=l.useRef(null),f=l.useRef(null),[g,p]=l.useState(!1),v=l.useRef(!1),S=l.useCallback(()=>{Ie(()=>{var I;return(I=f.current)==null?void 0:I.focus()})},[]),{isExpiredNow:C,isRenderableCSAT:A}=Hm({csat:o,csatExpireAt:c,csatPayload:m,isSubmitInFlight:g});if(Fm({csat:o,csatPayload:m,isRenderableCSAT:A,isExpiredNow:C,announceStatus:e.announceStatus,onSubmittedAnnounced:S}),!A||!m)return null;const y=()=>{var N;const I=(N=h.current)==null?void 0:N.querySelector('[aria-invalid="true"]');return I?I.getAttribute("role")==="radiogroup"?I.querySelector('[role="radio"]'):I:null},T=m.type===et.AI_AGENT_CSAT_5||m.type===et.AI_AGENT_CSAT_5_WITH_CRE||m.type===et.HELPDESK_CSAT_5?dr:()=>null;return a.createElement(ab,{ref:h},!o&&C?a.createElement(sb,null):a.createElement(T,{csatPayload:m,type:m.type,initialCsat:o,initialCsatReason:i,initialIsResolved:u,renderSubmitButton:({state:I,params:N,validateParams:O})=>I==="submitted"?a.createElement(lb,{ref:f,role:"status","aria-live":"polite","aria-atomic":"true","aria-label":m.csat_submitted_label,tabIndex:-1},a.createElement(B,{variant:"button","aria-hidden":"true"},m.csat_submitted_label)):a.createElement(ob,{onMount:s},a.createElement(cb,{type:"button",...t.csat.submitButton(m.csat_submit_label).props,onClick:async()=>{if(v.current)return;const k=ai(c);if(!k&&O()){v.current=!0,p(!0);try{await r(N)}catch(R){throw v.current=!1,p(!1),R}}else d(),k||Ie(()=>{var R;(R=e.announceError)==null||R.call(e,{type:"csatFormError"},y())})}},a.createElement(B,{variant:"button"},m.csat_submit_label)))}))},ab=_.default.div`display:flex;flex-direction:column;background-color:${({theme:e})=>e.colors.csat.background};border-radius:16px;gap:16px;padding:16px;`,cb=_.default.button`all:unset;width:100%;box-sizing:border-box;background-color:${({theme:e})=>e.colors.base.primary};color:${({theme:e})=>e.colors.base.primaryContrastContent};border-radius:6px;padding:10px 20px;display:flex;align-items:center;justify-content:center;cursor:pointer;text-align:center;word-break:break-word;${xe}&:hover{background-color:${E.color.primary.dark};}`,lb=_.default.div`width:100%;box-sizing:border-box;color:${E.themedColor.textHighEmphasis};background-color:${E.color.background200};border-radius:6px;padding:10px 20px;display:flex;align-items:center;justify-content:center;text-align:center;word-break:break-word;${ne.dark`
|
|
364
364
|
background-color: ${E.color.onlight.textDisabled};
|
|
365
365
|
`}
|
|
366
|
-
`,
|
|
367
|
-
`,
|
|
366
|
+
`,ub=e=>{const{components:t}=Hn.useContext(),n=e.messageType==="admin"?a.createElement(t.AdminMessage,{...e}):e.messageType==="admin.csat"?a.createElement(t.CSATMessage,{...e}):null;return a.createElement(db,{$marginBottom:kn(e.groupType)},n)},Hn=je({template:ub,components:{AdminMessage:RC,CSATMessage:ib}}),db=_.default.div`padding-inline:${oe.HORIZONTAL_PADDING}px;margin-bottom:${({$marginBottom:e})=>e}px;`,ls=({title:e,titleId:t,description:n,descriptionId:r,negativeText:s,positiveText:o,onCancel:i,onConfirm:c,buttonLayout:u="horizontal",styles:d})=>{const m=s!==void 0&&i!==void 0,h=o!==void 0&&c!==void 0,f=m?a.createElement(pb,{type:"button",onClick:i,$fullWidth:u!=="horizontal",$background:d==null?void 0:d.negativeBackground,$borderColor:d==null?void 0:d.negativeBorderColor},a.createElement(B,{variant:"button",color:(d==null?void 0:d.negativeText)??E.themedColor.textHighEmphasis},s)):null,g=h?a.createElement(_b,{type:"button",onClick:c,$fullWidth:u!=="horizontal",$background:d==null?void 0:d.positiveBackground,$borderColor:d==null?void 0:d.positiveBorderColor},a.createElement(B,{variant:"button",color:(d==null?void 0:d.positiveText)??E.themedColor.textHighEmphasisInverse},o)):null;return a.createElement(mb,null,a.createElement(hb,null,a.createElement(B,{as:"div",id:t,variant:"h2",color:(d==null?void 0:d.titleColor)??E.themedColor.textHighEmphasis},e)),a.createElement(fb,null,a.createElement(B,{as:"div",id:r,variant:"body3",color:(d==null?void 0:d.descriptionColor)??E.themedColor.textMidEmphasis},n)),a.createElement(gb,{$buttonLayout:u},u==="horizontal"?a.createElement(a.Fragment,null,f,g):a.createElement(a.Fragment,null,g,f)))},mb=_.default.div`display:flex;flex-direction:column;width:280px;border-radius:16px;overflow:hidden;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,hb=_.default.div`padding:24px 24px 16px;`,fb=_.default.div`padding-inline:24px;`,gb=_.default.div`display:flex;flex-direction:${({$buttonLayout:e})=>e==="vertical-full-width"?"column":"row"};align-items:center;justify-content:flex-end;gap:4px;padding:16px 24px;`,pb=_.default.button`display:flex;align-items:center;justify-content:center;box-sizing:border-box;width:${({$fullWidth:e})=>e?"100%":"auto"};padding:12px 20px;border-radius:20px;cursor:pointer;border:1px solid ${({$borderColor:e})=>e??"transparent"};background:${({$background:e})=>e??"none"};white-space:nowrap;overflow:hidden;text-overflow:ellipsis;&:hover{opacity:0.8;}`,_b=_.default.button`display:flex;align-items:center;justify-content:center;box-sizing:border-box;width:${({$fullWidth:e})=>e?"100%":"auto"};padding:12px 20px;border-radius:20px;cursor:pointer;border:1px solid ${({$borderColor:e})=>e??"transparent"};background-color:${({$background:e})=>e??E.themedColor.textHighEmphasis};white-space:nowrap;overflow:hidden;text-overflow:ellipsis;&:hover{opacity:0.8;}`,fn=16,Eb=({status:e})=>e===vn.COMPLETED?a.createElement(te,{type:"done-circle",size:fn,color:E.themedColor.textHighEmphasis}):e===vn.CANCELED?a.createElement(te,{type:"stop-circle",size:fn,color:E.themedColor.textLowEmphasis}):a.createElement(Et,{size:fn},a.createElement(te,{type:"spinner",size:fn,color:E.themedColor.textHighEmphasis})),Ua=24,Cb=8,bb=40,vb=({task:e,isFirst:t,isLast:n})=>a.createElement(Sb,{role:"listitem"},a.createElement(yb,null,a.createElement(ko,{$hidden:t}),a.createElement(Ab,null,a.createElement(Eb,{status:e.status})),a.createElement(ko,{$hidden:n})),a.createElement(Tb,null,a.createElement(B,{as:"div",variant:"body3",color:e.status===vn.CANCELED?E.themedColor.textLowEmphasis:E.themedColor.textHighEmphasis},e.user_facing_title))),Sb=_.default.div`display:flex;gap:4px;`,yb=_.default.div`display:flex;flex-direction:column;align-items:center;width:${Ua}px;flex-shrink:0;`,ko=_.default.div`width:1px;flex:1;transform:translateX(-25%);${({$hidden:e})=>e&&"visibility: hidden;"}background-image:repeating-linear-gradient( to bottom,${E.themedColor.textHighEmphasis}0 2px,transparent 2px 4px );`,Ab=_.default.div`display:flex;height:${Ua}px;align-items:center;justify-content:center;`,Tb=_.default.div`display:flex;flex:1;align-items:center;box-sizing:border-box;min-width:0;min-height:${bb}px;padding-block:${Cb}px;`,Ib=({steward:e,onCancelSteward:t})=>{const{logger:n}=ue(),[r,s]=l.useState(!1),[o,i]=l.useState(!1),c=!!e.cancellation_option,u=Rc(e.status);return a.createElement(xb,{$marginBottom:kn("single")},a.createElement(Rb,null,a.createElement(Mb,null,a.createElement(wb,null,a.createElement(B,{as:"div",variant:"caption1",color:E.themedColor.textHighEmphasis},e.title),!!e.description&&a.createElement(B,{as:"div",variant:"caption4",color:E.themedColor.textLowEmphasis},e.description)),c&&a.createElement(Nb,{type:"button","aria-label":"Stop steward",disabled:o,onClick:()=>s(!0)},a.createElement(te,{type:"stop",size:16,color:o?E.themedColor.textDisabled:E.themedColor.textHighEmphasis}))),a.createElement(kb,null),e.tasks.length===0?u!==Gt.IN_PROGRESS?null:a.createElement(Ob,null,a.createElement(Et,{size:16},a.createElement(te,{type:"spinner",size:16,color:E.themedColor.textHighEmphasis}))):a.createElement(Lb,{role:"list"},e.tasks.map((d,m)=>a.createElement(vb,{key:d.id,task:d,isFirst:m===0,isLast:m===e.tasks.length-1})))),r&&e.cancellation_option&&a.createElement(ft,{portalContainerId:Se.WINDOW,visible:r,onClose:()=>s(!1)},a.createElement(ls,{title:e.cancellation_option.title,description:e.cancellation_option.description,negativeText:e.cancellation_option.negative_text,positiveText:e.cancellation_option.positive_text,onCancel:()=>s(!1),onConfirm:async()=>{s(!1),i(!0);try{await(t==null?void 0:t())}catch(d){n.warn("steward.cancelSteward: failed",d)}finally{i(!1)}}})))},xb=_.default.div`display:flex;flex-direction:column;margin:0 ${oe.HORIZONTAL_PADDING}px;margin-bottom:${({$marginBottom:e})=>`${e}px`};
|
|
367
|
+
`,Rb=_.default.div`display:flex;flex-direction:column;border-radius:12px;overflow:hidden;padding:16px;border:1px solid ${E.themedColor.bg_300_500};background-color:${E.themedColor.bg_50_600};box-shadow:0 8px 20px rgba(0,0,0,0.12);`,Mb=_.default.div`display:flex;flex-direction:row;align-items:flex-start;gap:8px;`,wb=_.default.div`display:flex;flex-direction:column;gap:4px;flex:1;min-width:0;`,kb=_.default.div`height:1px;margin-block:12px;background-color:${E.themedColor.bg_200_400};`,Lb=_.default.div`display:flex;flex-direction:column;`,Ob=_.default.div`display:flex;width:100%;height:40px;align-items:center;justify-content:center;`,Nb=_.default.button`width:32px;height:32px;border-radius:50%;display:flex;align-items:center;justify-content:center;flex-shrink:0;border:none;cursor:pointer;color:${E.themedColor.textHighEmphasis};background-color:${E.themedColor.bg_200_400};&:hover:not(:disabled){opacity:0.8;}&:disabled{cursor:default;}`,Db=({className:e,label:t,onClick:n})=>{const{colors:r}=U.useTheme(),{conversation:s}=ae(),o={newMessages:s.newMessagesButton()};return a.createElement($b,{className:e,onClick:n,...o.newMessages.props},a.createElement(B,{variant:"button",color:r.base.primaryContrastContent},t),a.createElement(te,{size:16,type:"chevron-down",color:r.base.primaryContrastContent}),o.newMessages.descriptionNode)},$b=_.default.button`all:unset;cursor:pointer;display:flex;align-items:center;gap:4px;padding:10px 12px 10px 16px;border-radius:24px;background-color:${({theme:e})=>e.colors.base.primary};box-shadow:0 8px 10px 1px rgba(13,13,13,0.12),0 3px 14px 2px rgba(13,13,13,0.08),0 3px 5px -3px rgba(13,13,13,0.04);&:focus{outline:none;}${xe}`,us=({iconSize:e=64,icon:t,className:n,label:r,children:s})=>a.createElement(Fb,{className:n},t&&a.createElement(te,{type:t,size:e,color:E.themedColor.textLowEmphasis}),r&&a.createElement(B,{variant:"body1",color:E.themedColor.textMidEmphasis},r),s),Pb=_.default.div`position:relative;display:flex;justify-content:center;align-items:center;width:100%;height:100%;`,Fb=_.default.div`display:flex;flex-direction:column;min-height:104px;align-items:center;gap:20px;text-align:center;`,Ub=({label:e="Something went wrong",icon:t="error",action:n,...r})=>a.createElement(us,{icon:t,label:e,...r},n&&a.createElement(Bb,{onClick:n.onClick,label:n.label??"Retry"})),Bb=({label:e,onClick:t})=>{const{conversation:n}=ae();return a.createElement(Hb,{tabIndex:0,...n.retryButton(e).props,onClick:t},a.createElement(te,{type:"refresh",size:20}),a.createElement(B,{variant:"button",color:E.color.primary.main},e))},Hb=_.default.button`all:unset;display:flex;cursor:pointer;gap:4px;align-items:center;justify-content:center;${xe}`,Gb=({iconSize:e=48,className:t})=>a.createElement(Et,{size:e,className:t}),zb=({label:e="No channels",icon:t="chat",...n})=>a.createElement(us,{icon:t,label:e,...n}),Vb=({label:e="No messages",icon:t="message",...n})=>a.createElement(us,{icon:t,label:e,...n}),qb=e=>{const{components:t}=Gn.useContext(),n=e.type==="loading"?a.createElement(t.Loading,{...e}):e.type==="error"?a.createElement(t.Error,{...e}):e.type==="noChannels"?a.createElement(t.NoChannels,{...e}):e.type==="noMessages"?a.createElement(t.NoMessages,{...e}):null;return n&&a.createElement(Pb,null,n)},Gn=je({template:qb,components:{Loading:Gb,Error:Ub,NoChannels:zb,NoMessages:Vb}}),Vt=e=>{const{Template:t}=Gn.useContext();return a.createElement(t,{...e})},Kb=[0,150,450];function Yb({enabled:e}){const{state:t,actions:n}=ma(),r=l.useRef(0),s=l.useRef(t.isAwayFromBottom);s.current=t.isAwayFromBottom,l.useEffect(()=>{if(!e){r.current+=1;return}const o=r.current+1;r.current=o;const i=Kb.map(c=>setTimeout(()=>{Ie(()=>{r.current===o&&(s.current||n.scrollToBottom(!1))})},c));return()=>{r.current+=1,i.forEach(c=>clearTimeout(c))}},[n.scrollToBottom,e])}const Wb=({className:e,date:t=Date.now(),role:n,style:r})=>{const{format:s,stringSet:o}=ie();return a.createElement(jb,{id:`${He}-date-separator`,role:n,style:r,className:e},a.createElement(B,{variant:"caption4",color:E.themedColor.textMidEmphasis},s(t,o.DATE_FORMAT__MESSAGE_LIST__DATE_SEPARATOR)))},jb=_.default.div`display:flex;justify-content:center;align-items:center;text-align:center;word-break:break-word;`,Xb=({className:e,style:t,onClick:n})=>{const{conversation:r}=ae(),s={scrollToBottom:r.scrollToBottomButton()};return a.createElement(Zb,{className:e,style:t,onClick:n,tabIndex:0,...s.scrollToBottom.props},a.createElement(te,{size:24,type:"chevron-down",color:E.color.primary.main}),s.scrollToBottom.descriptionNode??null)},Zb=_.default.button`all:unset;cursor:pointer;display:flex;align-items:center;justify-content:center;width:40px;height:40px;border-radius:24px;box-shadow:0 2px 8px 0 rgba(0,0,0,0.08),0 4px 6px 0 rgba(0,0,0,0.12);${ne.light`
|
|
368
368
|
background-color: ${E.color.background50};
|
|
369
369
|
&:hover {
|
|
370
370
|
background-color: ${E.color.background100};
|
|
@@ -373,7 +373,7 @@
|
|
|
373
373
|
background-color: ${E.color.background200};
|
|
374
374
|
}
|
|
375
375
|
`}
|
|
376
|
-
${
|
|
376
|
+
${ne.dark`
|
|
377
377
|
background-color: ${E.color.background400};
|
|
378
378
|
&:hover {
|
|
379
379
|
background-color: ${E.color.background500};
|
|
@@ -387,22 +387,22 @@
|
|
|
387
387
|
outline: none;
|
|
388
388
|
}
|
|
389
389
|
|
|
390
|
-
${
|
|
391
|
-
`,
|
|
390
|
+
${xe}
|
|
391
|
+
`,Jb=()=>null,zn=je({template:Jb,components:{DateSeparator:Wb,ScrollToBottomButton:Xb}}),Qb=()=>{const{stringSet:e,format:t}=ie(),{agentPreviewConfigs:n={},aiAgentId:r}=ue(),{aiAgentInfo:s}=Oe(),{messageSource:o}=Ae(),{Template:i}=Ct.useContext(),{components:c}=zn.useContext(),u=n.welcomeMessages??[],d=o.messages,m=Gg(d,r),h=d[m.length+1],f=m[0]??h;return{filteredMessages:Ea(d,{previewWelcomeMessages:u,aiAgentUserId:r}),shouldShowOriginalDate:g=>g>0||u.length===0?!0:h&&!ut.isSameDay(h.createdAt,(f==null?void 0:f.createdAt)??0),renderAgentPreviewWelcomeMessages:()=>u.length===0?null:a.createElement(a.Fragment,null,a.createElement(c.DateSeparator,{role:"listitem",style:{margin:"16px 0"},date:f==null?void 0:f.createdAt}),u.map((g,p)=>{const v=p===u.length-1,S=m.length!==d.length,C=u.length===1?"single":p===0?"top":v||S?"bottom":"middle",A=(f==null?void 0:f.createdAt)??Date.now();return a.createElement("div",{key:p,role:"listitem",tabIndex:-1,"aria-label":zt({sender:(s==null?void 0:s.nickname)||"",message:g.message,messageFormat:"markdown",time:t(A,e.DATE_FORMAT__MESSAGE_TIMESTAMP),codeBlockPlaceholder:e.A11Y_CODE_BLOCK_PLACEHOLDER}),"data-message-listitem":""},a.createElement(i,{messageType:"user",message:g.message,sender:s,groupType:C,createdAt:A,extendedMessagePayload:{suggested_replies:g.suggestedReplies},suggestedRepliesDirection:n.suggestedRepliesDirection,suggestedRepliesVisible:v&&!S,isBotMessage:!0,onClickSuggestedReply:async({reply:y})=>{o.sendUserMessage({message:y})}}))}))}},ev=()=>{const{messageSource:e,scrollSource:t}=Ae();l.useEffect(()=>{!t.state.isAwayFromBottom&&t.state.isScrollPositionReconciled&&e.resetNewMessages()},[t.state.isAwayFromBottom,t.state.isScrollPositionReconciled])},Lo="https://delight.ai?utm_medium=product&utm_source=aiagent&utm_campaign=fy26-glbl-ai-agent-poweredby",tv=({style:e})=>{const{stringSet:t}=ie(),{handlers:n}=ue(),{conversation:r}=ae();return Wr("powered-by")?a.createElement(nv,{variant:"caption2",style:e},t.POWERED_BY+" ",a.createElement(rv,{variant:"caption2",forwardedAs:"a",href:Lo,...r.poweredByLink().props,rel:Zr,target:"_blank",onClick:o=>{o.preventDefault(),n.onClickLink({url:Lo})}},"Sendbird")):null},nv=_.default(B)`color:${E.themedColor.textLowEmphasis};text-align:center;`,rv=_.default(B)`color:${E.themedColor.textLowEmphasis};cursor:pointer;text-decoration:none;`,sv=()=>{var c;const{stringSet:e}=ie(),{conversation:t}=ae(),{channelSource:n,goToActiveConversation:r,scrollSource:s}=Ae(),o=De(n.channel),i=l.useRef(o);return l.useEffect(()=>{if(!i.current&&o){const m=setTimeout(()=>{s.actions.scrollToBottom()},100);return()=>clearTimeout(m)}i.current=o},[o,s.actions.scrollToBottom]),!((c=n.channel)!=null&&c.isAIAgent)||!o?null:a.createElement(ov,null,a.createElement(iv,{variant:"button",color:E.themedColor.textHighEmphasis,...t.startNewConversationButton({onActivate:r}).props},e.TALK_TO_AGENT))},ov=_.default.div`display:flex;justify-content:center;margin-bottom:16px;`,iv=_.default(B)`border-radius:6px;box-sizing:border-box;padding:10px 20px;cursor:pointer;user-select:none;background-color:${E.color.background50};border:1px solid ${E.color.onlight.textDisabled};${ne.dark`
|
|
392
392
|
background-color: ${E.color.background700};
|
|
393
393
|
border-color: ${E.color.ondark.textLowEmphasis};
|
|
394
394
|
`}
|
|
395
|
-
`,Zb=({statsCallbacks:e,...t})=>(zm(e),a.createElement(pb,{...t})),Jb=(e,t,n)=>t&&we.isWelcomeMessage(e,n)&&we.isWelcomeMessage(t,n)?!1:!mc.isSameDay((t==null?void 0:t.createdAt)??0,e.createdAt),Qb=()=>{var X;const{Template:e}=wt.useContext(),{Template:t}=pt.useContext(),{Template:n}=Pn.useContext(),{components:r}=Un.useContext(),{stringSet:s,format:o}=oe(),{announceError:i,announceStatus:c}=st(),{file:u}=ie().conversation,{config:d,cache:m,agentPreviewConfigs:h,chatSDK:f,handlers:g,state:C}=de(),{userSession:b,aiAgentInfo:S,connectionError:p}=Ne(),{_statsEnabled:A,conversation:y,channelSource:T,messageSource:I,scrollSource:L,state:{input:N,streamAnimation:k}}=Ie(),{filteredMessages:w,shouldShowOriginalDate:z,renderAgentPreviewWelcomeMessages:$}=zb(),q=yi(T.channel),Q=Gm({enabled:A}),[D,G]=l.useState(null),[F,K]=l.useState(null);l.useEffect(()=>{L.actions.onTypingIndicatorUpdate(!!q)},[!!q,L.actions.onTypingIndicatorUpdate]),Vb(),Pb({enabled:I.initialized&&I.messages.length>0});const he=(M,J=!1)=>{var ae;return J?S:((ae=T.channel)==null?void 0:ae.members.find(ye=>ye.userId===M.sender.userId))??M.sender},W=M=>{if(M.sendingStatus==="failed"&&!N.disabled)return()=>K(M)},Y=({message:M,index:J})=>{const ae=Ac(M),ye=w[J-1],$e=w[J+1],ke=w[w.length-1],P=M===ke,R=rt(M,S.userId),x=!(S.isUserFeedbackEnabled&&R&&!we.isWelcomeMessage(M)),O=Tc(M,ye,$e,x),U=Jb(M,ye,S.userId)&&z(J),j=ne=>{G({files:ne.files.map(ce=>({...ce,timestamp:M.createdAt})),index:ne.index})},re=ne=>{j({files:[ne],index:0})},Z=U?a.createElement(r.DateSeparator,{role:"listitem",style:{margin:"16px 0"},date:M.createdAt}):null,pe={data:M.data,maxBodyWidth:C.expanded?se.WIDE_BODY_MAX_WIDTH:void 0,extendedMessagePayload:M.extendedMessagePayload,createdAt:M.createdAt,groupType:O,onClickMedia:re,onClickMediaFiles:j,onClickFile:g.onClickLink,onClickCTA:g.onClickLink,onClickCitation:ne=>g.onClickLink({url:ne.link}),onClickLink:g.onClickLink},Ke=()=>{if(Oe.isOutgoing(M,b.userId))return"outgoingmessage";if(Oe.isIncoming(M,b.userId))return"incomingmessage"},dt=M.createdAt!=null&&M.createdAt!==0?o(M.createdAt,s.DATE_FORMAT__MESSAGE_TIMESTAMP):void 0,ot=(()=>{var ce,_e,Ee,Ae,ue,Me;const ne=(ce=M.message)==null?void 0:ce.trim();if(M.isFileMessage()){const Pe=((_e=M.name)==null?void 0:_e.trim())||"";return Jn({markdownText:ne,comparisonText:Pe,plainText:u.label(Pe,M.type)})}if(M.isMultipleFilesMessage()){const Pe=((ue=(Ae=(Ee=M.fileInfoList)==null?void 0:Ee[0])==null?void 0:Ae.fileName)==null?void 0:ue.trim())||"",tn=((Me=M.fileInfoList)==null?void 0:Me.length)??0;return Jn({markdownText:ne,comparisonText:Pe,plainText:tn>0?s.CONVERSATION_LIST__MULTIPLE_FILES_COUNT(tn):""})}return ne?Jn({markdownText:ne}):wi("")})(),me=(()=>{if(Oe.isAdmin(M))return Pt({message:ot.text,messageFormat:ot.format,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER});if(Oe.isOutgoing(M,b.userId))return Pt({sender:s.A11Y_MESSAGE_SENDER_YOU,message:ot.text,messageFormat:"plain",time:dt,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER});if(Oe.isIncoming(M,b.userId))return Pt({sender:he(M,R).nickname,message:ot.text,messageFormat:ot.format,time:dt,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER})})(),be=(()=>{var ne,ce;if(Oe.isAdmin(M))return Oe.isCSAT(M)?y?a.createElement(n,{...pe,...y,isResolvedWhenDeterminedByUser:rl(y),messageType:"admin.csat",announceError:i,announceStatus:c,onSubmitCSAT:async _e=>{var Ee;await((Ee=T.channel)==null?void 0:Ee.submitCSAT(_e))},onScrollToBottom:()=>L.actions.scrollToBottom()}):null:a.createElement(n,{...pe,messageType:"admin",message:M.message});if(Oe.isSteward(M)){const _e=Q({message:M,isBotMessage:R,aiAgentUserId:S.userId});return a.createElement(Zb,{steward:M.extendedMessagePayload.steward,statsCallbacks:_e,onCancelSteward:async()=>{await f.aiAgent.cancelStewardTask({channelUrl:M.channelUrl,messageId:M.messageId})}})}if(Oe.isOutgoing(M,b.userId)){const _e={...pe,message:M.message,sender:he(M),sendingStatus:M.sendingStatus,onClickFailedMessage:W(M)};if(M.isUserMessage())return a.createElement(e,{messageType:"user",..._e});if(M.isFileMessage()){const[Ee,Ae]=((ne=M.metaArrays.find(ue=>ue.key===Wo))==null?void 0:ne.value)??[];return a.createElement(e,{messageType:"file",file:M,metadata:{aspectRatio:Ee&&Ae?`${Ee}/${Ae}`:"1/1",localFile:(ce=M.messageParams)==null?void 0:ce.file},..._e})}if(M.isMultipleFilesMessage()){const{files:Ee,metadata:Ae}=Eo(M);return a.createElement(e,{messageType:"multipleFiles",files:Ee,metadata:Ae,..._e})}}if(Oe.isIncoming(M,b.userId)){const _e=we.isStreaming(M),Ee=Q({message:M,isBotMessage:R,aiAgentUserId:S.userId}),Ae={...pe,statsCallbacks:Ee,sender:he(M,R),message:M.message,suggestedRepliesVisible:P,suggestedRepliesDirection:h==null?void 0:h.suggestedRepliesDirection,isBotMessage:R,isStreaming:_e,isHandedOff:nt(T.channel),isConversationClosed:Fe(T.channel),isFeedbackEnabled:S.isUserFeedbackEnabled,isFeedbackCommentEnabled:S.isUserFeedbackCommentOptionEnabled,isSenderAvatarVisible:d.conversation.list.senderAvatarEnabled,deferredMarkdownElements:d.conversation.list.deferredMarkdownElements,onClickSuggestedReply:async({reply:ue})=>{I.sendUserMessage({message:ue})},onRequestMessageTemplate:async ue=>{const{template:Me}=await f.aiAgent.getMessageTemplate(ue);return m.template.set(ue,Me),Me},onGetCachedMessageTemplate:ue=>m.template.get(ue),onHandleTemplateInternalAction:ue=>{if(ue.type==="internal"&&ue.internalData){const{method:Me,payload:Pe}=ue.internalData;Me==="message.send"&&(Pe!=null&&Pe.message)&&I.sendUserMessage({message:Pe.message})}},onFeedbackUpdate:ue=>{const Me={messageId:M.messageId,channelUrl:M.channelUrl};if(!ue)return f.aiAgent.deleteMessageFeedback(Me);const Pe={...Me,rating:O_(ue.rating),comment:ue.comment};return we.hasFeedback(M)?f.aiAgent.updateMessageFeedback(Pe):f.aiAgent.createMessageFeedback(Pe)},onSubmitForm:({key:ue,data:Me})=>f.aiAgent.submitForm({messageId:M.messageId,channelUrl:M.channelUrl,formKey:ue,formData:Me}),onCancelForm:({key:ue})=>f.aiAgent.cancelForm({messageId:M.messageId,channelUrl:M.channelUrl,formKey:ue}),onSendChallengeAction:({key:ue,requestId:Me,action:Pe,data:tn})=>f.aiAgent.sendChallengeAction({channelUrl:M.channelUrl,key:ue,requestId:Me,action:Pe,data:tn}),onStreamAnimationStart:()=>{k.start(M.messageId)},onStreamAnimationProgress:()=>{L.actions.onStreamingUpdate(!0)},onStreamAnimationComplete:()=>{k.stop(M.messageId),L.actions.onStreamingUpdate(!1)}};if(M.isUserMessage())return a.createElement(t,{messageType:"user",...Ae});if(M.isFileMessage())return a.createElement(t,{messageType:"file",file:M,...Ae});if(M.isMultipleFilesMessage()){const{files:ue}=Eo(M);return a.createElement(t,{messageType:"multipleFiles",files:ue,...Ae})}}})();return a.createElement(l.Fragment,{key:ae},Z,a.createElement("div",{id:`${Be}-message-item`,role:"listitem",tabIndex:-1,"aria-label":me,"data-message-listitem":"","data-layout-id":Ke()},be))};return a.createElement(ev,{id:`${Be}-message-list`},a.createElement(ap,{ref:L.ref,onScroll:L.props.onScroll,stackDirection:h==null?void 0:h.messageStackDirection,messages:w,renderMessage:Y,onLoadPrev:I.loadPrevious,onLoadNext:I.loadNext,depsForResetScrollPositionToBottom:[I.initialized,I.messages.length!==0],bottomSpacerHeight:L.state.bottomSpace,"aria-label":s.A11Y_MESSAGE_LIST,loading:!I.initialized||!T.channel,empty:w.length===0&&!q,error:!!(p||T.error),LoadingComponent:a.createElement(Ht,{type:"loading"}),EmptyComponent:(()=>{const M=$();return M?a.createElement("div",{style:{width:"100%"}},M):a.createElement(Ht,{type:"noMessages",label:s.PLACE_HOLDER__NO_MESSAGES})})(),ErrorComponent:a.createElement(Ht,{type:"error",label:(p==null?void 0:p.message)??((X=T.error)==null?void 0:X.message),action:T.error?{label:s.RETRY,onClick:()=>T.refetch()}:void 0}),messageTopArea:a.createElement(a.Fragment,null,a.createElement(qb,{style:{marginTop:16}}),$()),messageBottomArea:a.createElement(a.Fragment,null,q&&a.createElement("div",{id:`${Be}-message-item`,role:"listitem",tabIndex:-1,"aria-label":Pt({sender:q.user.nickname,message:s.A11Y_TYPING_INDICATOR,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER}),"data-message-listitem":"",style:{marginTop:w.length===0?8:0}},a.createElement(t,{isTyping:!0,isBotMessage:q.isBot,sender:q.user,thinkingMessage:q.thinkingMessage,messageType:"user",groupType:"single",message:"",isSenderAvatarVisible:d.conversation.list.senderAvatarEnabled})),d.conversation.list.isTalkToAgentViewEnabled&&a.createElement(Wb,null)),overlayArea:a.createElement(a.Fragment,null,d.conversation.list.newMessageIndicatorEnabled&&L.state.isAwayFromBottom&&I.newMessages.length>0&&a.createElement(tv,{label:s.SCROLL_TO_NEW_MESSAGES_LABEL(I.newMessages),onClick:()=>L.actions.scrollToBottom()}),L.state.isAwayFromBottom&&I.newMessages.length===0&&!q&&a.createElement(r.ScrollToBottomButton,{onClick:()=>L.actions.scrollToBottom(),style:{position:"absolute",bottom:12,insetInlineEnd:16}}))}),D&&a.createElement(fp,{files:D.files,initialIndex:D.index,onClose:()=>G(null),visible:!0}),F&&a.createElement(at,{visible:!0,onClose:()=>K(null),"aria-label":s.A11Y_FAILED_MESSAGE_OPTIONS},a.createElement(at.ActionItem,{onClick:()=>{I.resendMessage(F),K(null)}},s.FAILED_MESSAGE_RESEND),a.createElement(at.ActionItem,{destructive:!0,onClick:()=>{I.deleteMessage(F),K(null)}},s.FAILED_MESSAGE_REMOVE)))},ev=_.default.div`overflow-y:hidden;display:flex;flex:1;position:relative;`,tv=_.default(Tb)`position:absolute;bottom:12px;left:50%;transform:translateX(-50%);`,nv=()=>a.createElement(Qb,null),Mo={file:"attach",snippet:"snippet",site:"website",sb_sprinklr:"sprinklr",sb_salesforce:"salesforce",sb_confluence:"confluence",sb_zendesk:"zendesk",sb_desk:"snippet"},Da=({actionbook:e,functionCalls:t,groundedness:n,agentMessageTemplates:r,flaggedTypes:s,onClickActionbook:o,onClickFunctionCall:i,onClickFunctionCallDetail:c,onClickGroundedness:u,onClickAgentMessageTemplate:d,topContent:m,bottomContent:h,renderCustomGroundednessIcon:f=C=>C.default,style:g={}})=>{const{iconColor:C="#000000",textColor:b="#000000",highlightColor:S=Gt.DEFAULT_PRIMARY}=g;return a.createElement(wo,null,m,e&&a.createElement(wo,null,a.createElement(In,null,a.createElement(Dt,null,a.createElement(ee,{size:16,type:"actionbook",color:C})),a.createElement(dn,{$clickable:!!o,$highlightColor:S,variant:"body2",color:b,onClick:()=>o==null?void 0:o(e),maxTextLines:1},e.name))),t==null?void 0:t.map(p=>a.createElement(gn,{key:p.key},a.createElement(Dt,null,a.createElement(ee,{size:16,type:"function",color:C})),a.createElement(In,null,a.createElement(dn,{$clickable:!!i,$highlightColor:S,variant:"body2",color:b,onClick:()=>i==null?void 0:i(p),maxTextLines:1},p.name),c&&a.createElement(rv,{role:"button",onClick:()=>c==null?void 0:c(p)},a.createElement(H,{variant:"body2",color:S},"View details"),a.createElement(ee,{type:"chevron-right",size:16,color:S}))))),n==null?void 0:n.map(p=>a.createElement(gn,{key:p.id},a.createElement(Dt,null,f({default:a.createElement(ee,{size:16,type:Mo[p.source_type]??Mo.snippet,color:C}),sourceType:p.source_type})),a.createElement(dn,{$clickable:!!u,$highlightColor:S,variant:"body2",color:b,onClick:()=>u==null?void 0:u(p),maxTextLines:1},p.preview_title))),r==null?void 0:r.map(p=>a.createElement(gn,{key:p.key},a.createElement(Dt,null,a.createElement(ee,{size:16,type:"template",color:C})),a.createElement(dn,{$clickable:!!d,$highlightColor:S,variant:"body2",color:b,onClick:()=>d==null?void 0:d(p),maxTextLines:1},p.name))),!!(s!=null&&s.length)&&a.createElement(sv,null,a.createElement(Dt,null,a.createElement(ee,{size:16,type:"activity",color:C})),a.createElement(ov,{variant:"body2",color:b},s.map(p=>p.replace(/_/g," ")).join(" · "))),h)},$a=_.default(H)`font-weight:400;`,dn=_.default($a)`${({$clickable:e,$highlightColor:t})=>e&&B.css`
|
|
395
|
+
`,av=({statsCallbacks:e,...t})=>(Qm(e),a.createElement(Ib,{...t})),cv=(e,t,n)=>t&&we.isWelcomeMessage(e,n)&&we.isWelcomeMessage(t,n)?!1:!_c.isSameDay((t==null?void 0:t.createdAt)??0,e.createdAt),lv=()=>{var ee;const{Template:e}=Ot.useContext(),{Template:t}=Ct.useContext(),{Template:n}=Hn.useContext(),{components:r}=zn.useContext(),{stringSet:s,format:o}=ie(),{announceError:i,announceStatus:c}=lt(),{file:u,messageList:d}=ae().conversation,{config:m,cache:h,agentPreviewConfigs:f,chatSDK:g,handlers:p,state:v}=ue(),{userSession:S,aiAgentInfo:C,connectionError:A}=Oe(),{_statsEnabled:y,conversation:T,channelSource:I,messageSource:N,scrollSource:O,state:{input:k,streamAnimation:R}}=Ae(),{filteredMessages:F,shouldShowOriginalDate:D,renderAgentPreviewWelcomeMessages:Q}=Qb(),re=Jm({enabled:y}),G=Nm(xi(I.channel),Bc(F,S.userId)),[H,q]=l.useState(null),[J,K]=l.useState(null),z=De(I.channel)?void 0:G??R.heldTypingInfo;l.useEffect(()=>{O.actions.onTypingIndicatorUpdate(!!z)},[!!z,O.actions.onTypingIndicatorUpdate]),ev(),Yb({enabled:N.initialized&&N.messages.length>0});const Y=w=>{var _e;return Mc(w,{aiAgentInfo:C,members:(_e=I.channel)==null?void 0:_e.members})},W=w=>{if(w.sendingStatus==="failed"&&!k.disabled)return()=>K(w)},V=({message:w,index:_e})=>{const Re=wc(w),Te=F[_e-1],$=F[_e+1],M=F[F.length-1],x=w===M,L=nt(w,C.userId),P=!(C.isUserFeedbackEnabled&&L&&!we.isWelcomeMessage(w)),X=kc(w,Te,$,P),se=cv(w,Te,C.userId)&&D(_e),Z=Ee=>{q({files:Ee.files.map(Ze=>({...Ze,timestamp:w.createdAt})),index:Ee.index})},be=Ee=>{Z({files:[Ee],index:0})},Xe=se?a.createElement(r.DateSeparator,{role:"listitem",style:{margin:"16px 0"},date:w.createdAt}):null,it={data:w.data,maxBodyWidth:v.expanded?oe.WIDE_BODY_MAX_WIDTH:void 0,extendedMessagePayload:w.extendedMessagePayload,createdAt:w.createdAt,groupType:X,onClickMedia:be,onClickMediaFiles:Z,onClickFile:p.onClickLink,onClickCTA:p.onClickLink,onClickCitation:Ee=>p.onClickLink({url:Ee.link}),onClickLink:p.onClickLink},sn=()=>{if(Me.isOutgoing(w,S.userId))return"outgoingmessage";if(Me.isIncoming(w,S.userId))return"incomingmessage"},le=w.createdAt!=null&&w.createdAt!==0?o(w.createdAt,s.DATE_FORMAT__MESSAGE_TIMESTAMP):void 0,fe=(()=>{var Ze,Ne,Ge,qe,de,$e;const Ee=(Ze=w.message)==null?void 0:Ze.trim();if(w.isFileMessage()){const Pe=((Ne=w.name)==null?void 0:Ne.trim())||"";return sr({markdownText:Ee,comparisonText:Pe,plainText:u.label(Pe,w.type)})}if(w.isMultipleFilesMessage()){const Pe=((de=(qe=(Ge=w.fileInfoList)==null?void 0:Ge[0])==null?void 0:qe.fileName)==null?void 0:de.trim())||"",on=(($e=w.fileInfoList)==null?void 0:$e.length)??0;return sr({markdownText:Ee,comparisonText:Pe,plainText:on>0?s.CONVERSATION_LIST__MULTIPLE_FILES_COUNT(on):""})}return Ee?sr({markdownText:Ee}):Di("")})(),ge=(()=>{if(Me.isAdmin(w))return zt({message:fe.text,messageFormat:fe.format,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER});if(Me.isOutgoing(w,S.userId))return zt({sender:s.A11Y_MESSAGE_SENDER_YOU,message:fe.text,messageFormat:"plain",time:le,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER});if(Me.isIncoming(w,S.userId))return zt({sender:Y(w).nickname,message:fe.text,messageFormat:fe.format,time:le,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER})})(),pe=(()=>{var Ee,Ze;if(Me.isAdmin(w))return Me.isCSAT(w)?T?a.createElement(n,{...it,...T,isResolvedWhenDeterminedByUser:ul(T),messageType:"admin.csat",announceError:i,announceStatus:c,onSubmitCSAT:async Ne=>{var Ge;await((Ge=I.channel)==null?void 0:Ge.submitCSAT(Ne))},onScrollToBottom:()=>O.actions.scrollToBottom()}):null:a.createElement(n,{...it,messageType:"admin",message:w.message});if(Me.isSteward(w)){const Ne=re({message:w,isBotMessage:L,aiAgentUserId:C.userId});return a.createElement(av,{steward:w.extendedMessagePayload.steward,statsCallbacks:Ne,onCancelSteward:async()=>{await g.aiAgent.cancelStewardTask({channelUrl:w.channelUrl,messageId:w.messageId})}})}if(Me.isOutgoing(w,S.userId)){const Ne={...it,message:w.message,sender:Y(w),sendingStatus:w.sendingStatus,onClickFailedMessage:W(w)};if(w.isUserMessage())return a.createElement(e,{messageType:"user",...Ne});if(w.isFileMessage()){const[Ge,qe]=((Ee=w.metaArrays.find(de=>de.key===Jo))==null?void 0:Ee.value)??[];return a.createElement(e,{messageType:"file",file:w,metadata:{aspectRatio:Ge&&qe?`${Ge}/${qe}`:"1/1",localFile:(Ze=w.messageParams)==null?void 0:Ze.file},...Ne})}if(w.isMultipleFilesMessage()){const{files:Ge,metadata:qe}=So(w);return a.createElement(e,{messageType:"multipleFiles",files:Ge,metadata:qe,...Ne})}}if(Me.isIncoming(w,S.userId)){const Ne=we.isStreaming(w),Ge=re({message:w,isBotMessage:L,aiAgentUserId:C.userId}),qe={...it,statsCallbacks:Ge,sender:Y(w),message:w.message,suggestedRepliesVisible:x,suggestedRepliesDirection:f==null?void 0:f.suggestedRepliesDirection,isBotMessage:L,isStreaming:Ne,isHandedOff:ct(I.channel),isConversationClosed:De(I.channel),isFeedbackEnabled:C.isUserFeedbackEnabled,isFeedbackCommentEnabled:C.isUserFeedbackCommentOptionEnabled,isSenderAvatarVisible:m.conversation.list.senderAvatarEnabled,deferredMarkdownElements:m.conversation.list.deferredMarkdownElements,onClickSuggestedReply:async({reply:de})=>{N.sendUserMessage({message:de})},onRequestMessageTemplate:async de=>{const{template:$e}=await g.aiAgent.getMessageTemplate(de);return h.template.set(de,$e),$e},onGetCachedMessageTemplate:de=>h.template.get(de),onHandleTemplateInternalAction:de=>{if(de.type==="internal"&&de.internalData){const{method:$e,payload:Pe}=de.internalData;$e==="message.send"&&(Pe!=null&&Pe.message)&&N.sendUserMessage({message:Pe.message})}},onFeedbackUpdate:de=>{const $e={messageId:w.messageId,channelUrl:w.channelUrl};if(!de)return g.aiAgent.deleteMessageFeedback($e);const Pe={...$e,rating:z_(de.rating),comment:de.comment};return we.hasFeedback(w)?g.aiAgent.updateMessageFeedback(Pe):g.aiAgent.createMessageFeedback(Pe)},onSubmitForm:({key:de,data:$e})=>g.aiAgent.submitForm({messageId:w.messageId,channelUrl:w.channelUrl,formKey:de,formData:$e}),onCancelForm:({key:de})=>g.aiAgent.cancelForm({messageId:w.messageId,channelUrl:w.channelUrl,formKey:de}),onSendChallengeAction:({key:de,requestId:$e,action:Pe,data:on})=>g.aiAgent.sendChallengeAction({channelUrl:w.channelUrl,key:de,requestId:$e,action:Pe,data:on}),onStreamAnimationStart:()=>{R.start(w.messageId)},onStreamAnimationProgress:()=>{O.actions.onStreamingUpdate(!0)},onStreamAnimationComplete:()=>{R.stop(w.messageId),O.actions.onStreamingUpdate(!1)},onStreamAnimationHoldChange:de=>{de?R.holdStart(w.messageId,{user:Y(w),isBot:L}):R.holdStop(w.messageId)}};if(w.isUserMessage())return a.createElement(t,{messageType:"user",...qe});if(w.isFileMessage())return a.createElement(t,{messageType:"file",file:w,...qe});if(w.isMultipleFilesMessage()){const{files:de}=So(w);return a.createElement(t,{messageType:"multipleFiles",files:de,...qe})}}})(),Fe=R.isHolding(w.messageId),Ue=d.item({label:ge,holding:Fe});return a.createElement(l.Fragment,{key:Re},Xe,a.createElement("div",{id:`${He}-message-item`,...Ue.props,"data-message-listitem":"","data-layout-id":sn()},pe))};return a.createElement(uv,{id:`${He}-message-list`},a.createElement(_p,{ref:O.ref,onScroll:O.props.onScroll,stackDirection:f==null?void 0:f.messageStackDirection,messages:F,renderMessage:V,onLoadPrev:N.loadPrevious,onLoadNext:N.loadNext,depsForResetScrollPositionToBottom:[N.initialized,N.messages.length!==0],bottomSpacerHeight:O.state.bottomSpace,"aria-label":s.A11Y_MESSAGE_LIST,loading:!N.initialized||!I.channel,empty:F.length===0&&!z,error:!!(A||I.error),LoadingComponent:a.createElement(Vt,{type:"loading"}),EmptyComponent:(()=>{const w=Q();return w?a.createElement("div",{style:{width:"100%"}},w):a.createElement(Vt,{type:"noMessages",label:s.PLACE_HOLDER__NO_MESSAGES})})(),ErrorComponent:a.createElement(Vt,{type:"error",label:(A==null?void 0:A.message)??((ee=I.error)==null?void 0:ee.message),action:I.error?{label:s.RETRY,onClick:()=>I.refetch()}:void 0}),messageTopArea:a.createElement(a.Fragment,null,a.createElement(tv,{style:{marginTop:16}}),Q()),messageBottomArea:a.createElement(a.Fragment,null,z&&a.createElement("div",{id:`${He}-message-item`,...d.typingItem(z.user.nickname).props,"data-message-listitem":"",style:{marginTop:F.length===0?8:0}},a.createElement(t,{isTyping:!0,isBotMessage:z.isBot,sender:z.user,thinkingMessage:z.thinkingMessage,messageType:"user",groupType:"single",message:"",isSenderAvatarVisible:m.conversation.list.senderAvatarEnabled})),m.conversation.list.isTalkToAgentViewEnabled&&a.createElement(sv,null)),overlayArea:a.createElement(a.Fragment,null,m.conversation.list.newMessageIndicatorEnabled&&O.state.isAwayFromBottom&&N.newMessages.length>0&&a.createElement(dv,{label:s.SCROLL_TO_NEW_MESSAGES_LABEL(N.newMessages),onClick:()=>O.actions.scrollToBottom()}),O.state.isAwayFromBottom&&N.newMessages.length===0&&!z&&a.createElement(r.ScrollToBottomButton,{onClick:()=>O.actions.scrollToBottom(),style:{position:"absolute",bottom:12,insetInlineEnd:16}}))}),H&&a.createElement(Ap,{files:H.files,initialIndex:H.index,onClose:()=>q(null),visible:!0}),J&&a.createElement(dt,{visible:!0,onClose:()=>K(null),"aria-label":s.A11Y_FAILED_MESSAGE_OPTIONS},a.createElement(dt.ActionItem,{onClick:()=>{N.resendMessage(J),K(null)}},s.FAILED_MESSAGE_RESEND),a.createElement(dt.ActionItem,{destructive:!0,onClick:()=>{N.deleteMessage(J),K(null)}},s.FAILED_MESSAGE_REMOVE)))},uv=_.default.div`overflow-y:hidden;display:flex;flex:1;position:relative;`,dv=_.default(Db)`position:absolute;bottom:12px;left:50%;transform:translateX(-50%);`,mv=()=>a.createElement(lv,null),Oo={file:"attach",snippet:"snippet",site:"website",sb_sprinklr:"sprinklr",sb_salesforce:"salesforce",sb_confluence:"confluence",sb_zendesk:"zendesk",sb_desk:"snippet"},Ba=({actionbook:e,functionCalls:t,groundedness:n,agentMessageTemplates:r,flaggedTypes:s,onClickActionbook:o,onClickFunctionCall:i,onClickFunctionCallDetail:c,onClickGroundedness:u,onClickAgentMessageTemplate:d,topContent:m,bottomContent:h,renderCustomGroundednessIcon:f=p=>p.default,style:g={}})=>{const{iconColor:p="#000000",textColor:v="#000000",highlightColor:S=qt.DEFAULT_PRIMARY}=g;return a.createElement(No,null,m,e&&a.createElement(No,null,a.createElement(wn,null,a.createElement(Ft,null,a.createElement(te,{size:16,type:"actionbook",color:p})),a.createElement(gn,{$clickable:!!o,$highlightColor:S,variant:"body2",color:v,onClick:()=>o==null?void 0:o(e),maxTextLines:1},e.name))),t==null?void 0:t.map(C=>a.createElement(Cn,{key:C.key},a.createElement(Ft,null,a.createElement(te,{size:16,type:"function",color:p})),a.createElement(wn,null,a.createElement(gn,{$clickable:!!i,$highlightColor:S,variant:"body2",color:v,onClick:()=>i==null?void 0:i(C),maxTextLines:1},C.name),c&&a.createElement(hv,{role:"button",onClick:()=>c==null?void 0:c(C)},a.createElement(B,{variant:"body2",color:S},"View details"),a.createElement(te,{type:"chevron-right",size:16,color:S}))))),n==null?void 0:n.map(C=>a.createElement(Cn,{key:C.id},a.createElement(Ft,null,f({default:a.createElement(te,{size:16,type:Oo[C.source_type]??Oo.snippet,color:p}),sourceType:C.source_type})),a.createElement(gn,{$clickable:!!u,$highlightColor:S,variant:"body2",color:v,onClick:()=>u==null?void 0:u(C),maxTextLines:1},C.preview_title))),r==null?void 0:r.map(C=>a.createElement(Cn,{key:C.key},a.createElement(Ft,null,a.createElement(te,{size:16,type:"template",color:p})),a.createElement(gn,{$clickable:!!d,$highlightColor:S,variant:"body2",color:v,onClick:()=>d==null?void 0:d(C),maxTextLines:1},C.name))),!!(s!=null&&s.length)&&a.createElement(fv,null,a.createElement(Ft,null,a.createElement(te,{size:16,type:"activity",color:p})),a.createElement(gv,{variant:"body2",color:v},s.map(C=>C.replace(/_/g," ")).join(" · "))),h)},Ha=_.default(B)`font-weight:400;`,gn=_.default(Ha)`${({$clickable:e,$highlightColor:t})=>e&&U.css`
|
|
396
396
|
cursor: pointer;
|
|
397
397
|
text-decoration: underline;
|
|
398
398
|
&:hover {
|
|
399
399
|
color: ${t};
|
|
400
400
|
}
|
|
401
401
|
`}
|
|
402
|
-
`,
|
|
402
|
+
`,Ft=_.default.div`display:flex;align-items:center;justify-content:center;flex-shrink:0;`,wn=_.default.div`display:flex;gap:8px;align-items:center;word-break:break-word;`,hv=_.default(wn)`cursor:pointer;gap:4px;`,Cn=_.default(wn)`flex-direction:row;align-items:center;`,fv=_.default(Cn)`align-items:flex-start;max-width:100%;`,gv=_.default(Ha)`min-width:0;`,No=_.default.div`display:flex;gap:4px;flex-direction:column;align-items:flex-start;`,Ga=ve("DashboardTester"),pv=Ga.Provider;function _v({testerType:e,origin:t,children:n}){return a.createElement(pv,{value:{testerType:e,origin:t}},e&&a.createElement(Ev,null),n)}const za=Ga.useContext,Ev=()=>a.createElement(a.Fragment,null,a.createElement(Ct.MessageLogs,{component:Do}),a.createElement(Ot.MessageLogs,{component:Do})),Do=({extendedMessagePayload:e={}})=>{const{handlers:t}=ue(),{manual:n,groundedness:r,function_calls:s,agent_message_templates:o,flagged_types:i,is_thinking:c}=e,u=!!n||[r,s,o,i].some(d=>d==null?void 0:d.length);return c||!u?a.createElement(a.Fragment,null):a.createElement(Cv,null,a.createElement(bv,{$width:4}),a.createElement(Ba,{actionbook:n,functionCalls:s,groundedness:r,agentMessageTemplates:o,flaggedTypes:i,onClickFunctionCallDetail:t==null?void 0:t.onFunctionCallDetailClick,style:{iconColor:E.themedColor.textHighEmphasis,textColor:E.themedColor.textHighEmphasis,barColor:E.themedColor.textDisabled},topContent:a.createElement(B,{variant:"caption4",color:E.themedColor.textLowEmphasis},"Only visible in the tester")}))},Cv=_.default.div`display:flex;gap:16px;margin:6px ${oe.HORIZONTAL_PADDING}px 4px ${oe.HORIZONTAL_PADDING+oe.AVATAR_SIZE}px;align-self:stretch;`,bv=_.default.div`width:${({$width:e})=>e}px;background-color:${E.themedColor.textDisabled};border-radius:100px;flex-shrink:0;`,vv=()=>{var s;const{origin:e}=za(),{appId:t,aiAgentId:n}=ye(),{channelSource:r}=Ae();return(s=r.channel)!=null&&s.conversation?a.createElement(Sv,null,a.createElement(wr,{style:{gap:4}},a.createElement(te,{color:E.themedColor.textLowEmphasis,size:12,type:"show"}),a.createElement(B,{as:"i",color:E.themedColor.textLowEmphasis,variant:"caption2"},"Only visible in the tester")),a.createElement(wr,{role:"button",style:{gap:4},onClick:()=>{var u,d;const o=e??window.location.origin,i=(d=(u=r.channel)==null?void 0:u.conversation)==null?void 0:d.id,c=`${o}/ai-agent/${t}/${n}/evaluate/conversations/${i}`;navigator.clipboard.writeText(c)}},a.createElement(B,{variant:"body3",color:E.themedColor.textHighEmphasis},"Copy ",a.createElement("span",{style:{color:E.themedColor.primary}},"conversation link")),a.createElement(te,{color:E.themedColor.primary,size:14,type:"copy"}))):null},wr=_.default.div`display:flex;justify-content:center;align-items:center;`,Sv=_.default(wr)`flex-direction:column;padding-block:16px;background-color:${E.themedColor.bg_100_500};gap:8px;`,yv=(e,t)=>{const n=[],r=[],s=[];for(const o of e){const i=t.isSupportedMimeType(o.type),c=o.size<=t.getUploadSizeLimit(o.type);i&&c?n.push(o):i?r.push(o):s.push(o)}return{passed:n,failedBySize:r,failedByType:s}},Va=l.createContext(void 0),Av=({children:e})=>{var Q,re;const{chatSDK:t}=ue(),{createAttachmentRules:n}=Oe(),{stringSet:r}=ie(),{channelSource:s,state:o}=Ae(),[i,c]=l.useState([]),{announceError:u}=es(),[d,m]=l.useState(null),h=n({channel:s.channel,uploadSizeLimit:(Q=t.appInfo)==null?void 0:Q.uploadSizeLimit}),f=((re=o==null?void 0:o.input)==null?void 0:re.disabled)??!1,g=h.isEnabled(),p=h.maxAttachmentCount,v=()=>m(null),S=G=>m(G),C=()=>{S({title:r.FILE_UPLOAD_NOTIFICATION__COUNT_LIMIT.replace("%d",p.toString())})},A=G=>{S({title:r.FILE_UPLOAD_NOTIFICATION__SIZE_LIMIT.replace("%d",G.toString())}),u({type:"fileSizeExceeded",maxSizeMB:G})},y=G=>{S({title:r.FILE_UPLOAD_NOTIFICATION__FILES_EXCLUDED_BY_VALIDATION.replace("%d",G.toString())})},T=G=>G.map(H=>({file:H,preview:{url:URL.createObjectURL(H),type:H.type,name:H.name}})),I=G=>{c(H=>[...H,...T(G)])},N=G=>{c(H=>(H.forEach(q=>URL.revokeObjectURL(q.preview.url)),T(G)))},O=G=>{const{passed:H,failedBySize:q,failedByType:J}=yv(G,h),K=q.length+J.length,z=G.length===1?q[0]:void 0;return z?A(h.getUploadSizeLimitInMB(z.type)):K>0&&y(K),H},k=G=>{const H=O(G.files);H.length!==0&&(G.type==="append"?I(H):N(H))},R=G=>{if(!g||f||!ju(G))return;const H=Zu({currentFiles:i.map(({file:q})=>q),incomingFiles:G,maxAttachmentCount:p});switch(H.type){case"reject":C();return;case"confirm_replace":S({title:r.FILE_UPLOAD_REPLACE_ALERT__TITLE,description:r.FILE_UPLOAD_REPLACE_ALERT__DESCRIPTION,confirmText:r.BUTTON__OK,cancelText:r.BUTTON__CANCEL,onConfirm:()=>k(H.action)});return;case"apply":k(H.action);return}},F=G=>{c(H=>{var J;const q=(J=H[G])==null?void 0:J.preview;return q&&URL.revokeObjectURL(q.url),H.filter((K,z)=>z!==G)})},D=()=>{c(G=>(G.forEach(H=>URL.revokeObjectURL(H.preview.url)),[]))};return a.createElement(Va.Provider,{value:{files:i,addFiles:R,removeFile:F,clearFiles:D,isFileUploadEnabled:g,acceptableMimeTypes:h.supportedMimeTypes,maxAttachmentCount:h.maxAttachmentCount,showFileUploadAlert:S}},e,a.createElement(Fn,{visible:!!d,...d??{},onClose:v}))},ds=()=>{const e=l.useContext(Va);if(!e)throw new Error("useFileUpload must be used within FileUploadProvider");return e};function Tv({elementRef:e,ready:t,onRestore:n}){const r=l.useRef(!1);l.useEffect(()=>{var i;!t||!r.current||(n==null||n(),(i=e.current)==null||i.focus(),r.current=!1)},[t,n]);const s=l.useCallback(()=>{r.current=!0},[]),o=l.useCallback(()=>{r.current=!1},[]);return{requestRestore:s,cancelRestore:o}}function Iv({blurred:e,elementRef:t,document:n=window.document,onRecoverFocus:r}){const s=l.useRef(!1);e&&t.current&&n.activeElement===t.current&&(s.current=!0),l.useLayoutEffect(()=>{var o;!e&&s.current&&(r==null||r(),(o=t.current)==null||o.focus(),s.current=!1)},[e,r])}const xv=()=>{const{announceError:e}=lt();return l.useCallback(t=>{e({type:"sendFailed"},t)},[e])},Rv=1e3,Mv=(e,t,n)=>{const{announcementsEnabled:r,setIsSuppressed:s}=lt(),o=n??!0,i=l.useRef(!1),c=l.useRef(void 0),u=l.useCallback(d=>{var m;d&&o&&(i.current=!0,c.current=e,e==null||e.startTyping()),d||(i.current&&o&&((m=c.current)==null||m.endTyping()),i.current=!1,c.current=void 0),s(d)},[e,s,o]);l.useLayoutEffect(()=>{s(i.current)},[r,s]),Dm(t,u,{enabled:o,idleMs:Rv})},wv=({enabled:e=!0,focusRoot:t})=>{const[n,r]=l.useState(!1),s=l.useRef(!1),o=l.useRef(!1);l.useEffect(()=>{if(!e){r(!1);return}const d=h=>{const f=h;f.metaKey||f.altKey||f.ctrlKey||(s.current=!0)},m=()=>{s.current=!1,r(!1)};return t.addEventListener("keydown",d),t.addEventListener("pointerdown",m),()=>{t.removeEventListener("keydown",d),t.removeEventListener("pointerdown",m)}},[e,t]);const i=l.useCallback(()=>{if(o.current){o.current=!1,r(!1);return}r(s.current)},[]),c=l.useCallback(()=>{r(!1)},[]),u=l.useCallback(()=>{o.current=!0,r(!1)},[]);return{isFocusVisible:n,suppressNextFocusVisible:u,focusHandlers:{onFocus:i,onBlur:c}}},kv=_.default.div`&::-webkit-scrollbar{display:none;}overflow-x:auto;display:flex;flex-direction:row;gap:10px;padding:8px 16px;background-color:transparent;`,Lv=_.default.div`display:flex;flex-shrink:0;position:relative;margin-block-start:8px;border-radius:12px;height:64px;img{border-radius:12px;object-fit:cover;width:64px;-webkit-user-drag:none;}&:hover button,&:focus-within button{opacity:1;}`,Ov=_.default.button`display:flex;align-items:center;justify-content:center;position:absolute;inset-inline-end:-8px;inset-block-start:-8px;cursor:pointer;border-radius:50%;border:none;padding:0;opacity:${({$mobile:e})=>e?1:0};transition:opacity 0.12s ease-in-out;${ne.light`
|
|
403
403
|
background-color: ${E.color.background50};
|
|
404
404
|
`}
|
|
405
|
-
${
|
|
405
|
+
${ne.dark`
|
|
406
406
|
background-color: ${E.color.background500};
|
|
407
407
|
`}
|
|
408
408
|
path {
|
|
@@ -424,7 +424,7 @@
|
|
|
424
424
|
circle {
|
|
425
425
|
stroke: ${E.themedColor.bg_50_600};
|
|
426
426
|
}
|
|
427
|
-
`,
|
|
427
|
+
`,Nv=()=>{const e=en(),{conversation:t}=ae(),{files:n,removeFile:r,isFileUploadEnabled:s}=ds();return s&&n.length>0?a.createElement(kv,null,n.map(({preview:{type:i,name:c,url:u}},d)=>{let m=a.createElement(os,{name:c,mimeType:i,type:Nr(c,i),selected:!0});return i.startsWith("image/")&&(m=a.createElement("img",{alt:t.file.label(c,i,!0),src:u})),a.createElement(Lv,{key:u},a.createElement(Ov,{type:"button",...t.file.removeButton(c).props,$mobile:e,onClick:()=>r(d)},a.createElement(te,{type:"close-filled",color:E.themedColor.textMidEmphasis})),m)})):null},Dv={textArea:U.css`min-height:40px;height:40px;font-size:16px;line-height:24px;`},qa=_.default.button`all:unset;cursor:pointer;display:flex;align-items:center;justify-content:center;width:32px;height:32px;${xe}`,$o=_.default.div`width:100%;position:relative;background-color:${({theme:e})=>e.colors.messageInput.background};border-radius:20px;`,Po=_.default.div`display:flex;flex-direction:row;align-items:flex-end;position:relative;`,Fo=_.default.textarea`all:unset;display:block;flex:1;min-width:0;padding-top:8px;padding-bottom:8px;padding-inline-start:16px;padding-inline-end:12px;box-sizing:border-box;font-size:14px;line-height:20px;color:${({theme:e})=>e.colors.messageInput.text};resize:none;width:100%;height:${Ki}px;overflow-wrap:break-word;white-space:pre-wrap;overflow-x:hidden;${ca&&Dv.textArea};${({$focusVisible:e})=>e&&U.css`
|
|
428
428
|
outline: 2px solid ${E.themedColor.primary};
|
|
429
429
|
outline-offset: 2px;
|
|
430
430
|
`}
|
|
@@ -440,18 +440,18 @@
|
|
|
440
440
|
}
|
|
441
441
|
}
|
|
442
442
|
|
|
443
|
-
${({$blocked:e})=>e&&
|
|
444
|
-
|
|
443
|
+
${({$blocked:e})=>e&&U.css`cursor:not-allowed;&::placeholder{color:${E.themedColor.textDisabled};}`}
|
|
444
|
+
`,$v=_.default.input`display:none;`;_.default.div`display:flex;align-items:center;gap:24px;`;const Pv=_.default(qa)`flex-shrink:0;border-radius:8px;&:disabled{cursor:not-allowed;}&:not(:disabled){&:hover{background-color:${E.themedColor.bg_100_500};path{fill:${E.themedColor.textHighEmphasis};}}&:active{background-color:${E.themedColor.bg_200_400};}}`,Uo=_.default.div`padding:10px 16px 10px 12px;position:relative;display:flex;align-items:center;gap:8px;`,Bo=e=>e.startsWith("image/"),Ho=({disabled:e})=>{const{stringSet:t}=ie(),{conversation:n}=ae(),{config:r}=ue(),s=l.useRef(null),o=l.useRef(null),[i,c]=l.useState(!1),{addFiles:u,isFileUploadEnabled:d,acceptableMimeTypes:m,showFileUploadAlert:h}=ds(),f=m.includes(fr),g=f?["image/*"]:m.filter(Bo),p=f?[fr]:m.filter(O=>!Bo(O)),v=r.conversation.input.gallery.photoEnabled,S=r.conversation.input.fileEnabled,C=()=>f||g.length>0,A=()=>f||p.length>0,y=O=>{const k=O.currentTarget.files;k&&u(Array.from(k)),O.target.value=""},T=()=>{c(!0)},I=l.useMemo(()=>{const O=[];return v&&O.push({type:"image",icon:"photo",label:t.FILE_UPLOAD_PHOTOS,accept:g.join(","),inputRef:s,onSelect:()=>{if(!C()){h({title:t.FILE_UPLOAD_NO_SUPPORTED_FILES});return}c(!1),setTimeout(()=>{var k;return(k=s.current)==null?void 0:k.click()},100)}}),S&&O.push({type:"file",icon:"document",label:t.FILE_UPLOAD_FILES,accept:m.join(","),inputRef:o,onSelect:()=>{if(!A()){h({title:t.FILE_UPLOAD_NO_SUPPORTED_FILES});return}c(!1),setTimeout(()=>{var k;return(k=o.current)==null?void 0:k.click()},100)}}),O},[g,m,t,v,S]);if(!d)return null;const N={attach:n.messageInput.attachFileButton()};return a.createElement(a.Fragment,null,a.createElement(Pv,{...N.attach.props,disabled:e,onClick:T},a.createElement(te,{type:"add",color:e?E.themedColor.textDisabled:E.color.primary.main,size:20}),N.attach.descriptionNode),I.map(O=>a.createElement($v,{key:O.type,type:"file",ref:O.inputRef,multiple:O.type==="image",onChange:y,accept:O.accept})),a.createElement(dt,{visible:i,onClose:()=>c(!1),"aria-label":t.A11Y_FILE_UPLOAD_OPTIONS},I.map(O=>a.createElement(dt.ActionItem,{key:O.type,onClick:O.onSelect,icon:O.icon},O.label))))},Fv=()=>{const e=l.useRef(null),[t,n]=l.useState(""),{stringSet:r}=ie(),{conversation:s}=ae(),{rootElement:o}=ue(),i=mt(o),{focusHandlers:c,isFocusVisible:u,suppressNextFocusVisible:d}=wv({focusRoot:i}),{channelSource:m,messageSource:h,state:f}=Ae(),{files:g,addFiles:p,clearFiles:v}=ds(),S=xv(),{focusPolicy:C,disabled:A,disabledBy:y}=f.input,T=C==="preserve",I=C==="release",N=(()=>{if(!A)return r.MESSAGE_INPUT__PLACE_HOLDER;switch(y){case"form_active":return r.FORM_PLACEHOLDER;case"ai_responding":return r.MESSAGE_INPUT__PLACE_HOLDER__WAIT_AI_AGENT_RESPONSE;case"suggested_replies":return r.MESSAGE_INPUT__PLACE_HOLDER__SUGGESTED_REPLIES;case"steward":return r.MESSAGE_INPUT__PLACE_HOLDER__STEWARD;case"system":return r.MESSAGE_INPUT__PLACE_HOLDER__DISABLED;case"reconnecting":return r.MESSAGE_INPUT__PLACE_HOLDER__RECONNECTING;case"unavailable":case"conversation_closed":default:return r.MESSAGE_INPUT__PLACE_HOLDER__DISABLED}})();$g({onDropFiles:V=>{p(V)}}),Iv({blurred:I,elementRef:e,document:i,onRecoverFocus:()=>{d()}}),Mv(m.channel,t,!A);const O=t.trim().length>0,k=g.length>0,R=!A&&(O||k),F={input:s.messageInput.textInput(r.A11Y_MESSAGE_INPUT),send:s.messageInput.sendButton()},D=()=>{e.current&&(e.current.value="",e.current.style.height=""),v(),n("")},Q=()=>{var V;d(),(V=e.current)==null||V.focus()},{requestRestore:re,cancelRestore:G}=Tv({elementRef:e,ready:T,onRestore:d}),H=V=>{G(),S(V)},q=()=>{G()},J=async V=>{try{await V(),q()}catch{H(e.current)}},K=async()=>{if(A)return;const V=t.trim();if(!V&&!g.length)return;const ee=[...g];if(re(),D(),Q(),ee.length===0){await J(()=>h.sendUserMessage({message:V}));return}if(ee.length===1)await J(()=>h.sendFileMessage({message:V,file:ee[0].file}));else{const w=ee.map(({file:_e})=>({file:_e}));await J(()=>h.sendMultipleFilesMessage({message:V,fileInfoList:w}))}},z=V=>{const ee=Array.from(V.clipboardData.files);ee.length>0&&(V.preventDefault(),p(ee))},Y=V=>{V.key!=="Enter"||V.nativeEvent.isComposing||V.shiftKey||(V.preventDefault(),K())},W=V=>{if(A){e.current&&(e.current.value=t);return}if(e.current){e.current.style.height="";const ee=Math.min(Kh,e.current.scrollHeight);Ki<ee&&(e.current.style.height=`${ee}px`)}n(V.target.value)};return I?a.createElement(Uo,null,a.createElement(Ho,{disabled:!0}),a.createElement($o,null,a.createElement(Po,null,a.createElement(Fo,{rows:1,...F.input.props,disabled:!0,placeholder:N,$blocked:!0,$focusVisible:!1,"data-focus-visible":"false"})))):a.createElement(Uo,{"data-message-composer":""},a.createElement(Ho,{disabled:A}),a.createElement($o,null,a.createElement(Nv,null),a.createElement(Po,null,a.createElement(Fo,{ref:e,rows:1,...F.input.props,readOnly:T,"aria-disabled":T?"true":void 0,placeholder:N,maxLength:5e3,$blocked:A,$focusVisible:u,"data-focus-visible":u?"true":"false",onKeyDown:Y,onChange:W,onFocus:c.onFocus,onBlur:c.onBlur,onPaste:z}))),R&&a.createElement(qa,{...F.send.props,onClick:()=>K()},a.createElement(te,{type:"send",color:E.color.primary.main,size:20}),F.send.descriptionNode))},Uv=_.default.div`padding:8px 16px;text-align:center;word-break:break-word;white-space:pre-wrap;line-height:1.43;letter-spacing:-0.2px;font-size:14px;font-weight:400;color:${E.themedColor.textLowEmphasis};&& a{font-weight:700;text-decoration:none;${ne.light`
|
|
445
445
|
color: ${E.color.information.light};
|
|
446
446
|
`};
|
|
447
|
-
${
|
|
447
|
+
${ne.dark`
|
|
448
448
|
color: ${E.color.information.main};
|
|
449
449
|
`};
|
|
450
450
|
}
|
|
451
|
-
`,wv=l.lazy(()=>Promise.resolve().then(()=>require("./cjs/VvejebHE.cjs")).then(e=>({default:e.MarkdownText}))),kv=()=>{const{aiAgentInfo:e,userSession:t}=Ne(),{handlers:n}=de(),{messageSource:r,channelSource:s}=Ie(),[o,i]=l.useState(null),c=Hr("special-notice",s.channel),u=l.useCallback(()=>s.channel?c?r.messages.some(d=>rt(d,(t==null?void 0:t.userId)??"")):!0:null,[s.channel,c,r.messages,t==null?void 0:t.userId]);return l.useEffect(()=>{o||i(u())},[u,o]),o||!e.specialNotice?null:a.createElement(Mv,null,a.createElement(wv,{onClickLink:n.onClickLink},e.specialNotice))},Lv=()=>a.createElement(Ov,null,a.createElement(kv,null),a.createElement(fv,null,a.createElement(Rv,null))),Ov=_.default.div`z-index:0;border:none;width:100%;`,Nv=()=>{var s;const{testerType:e}=Fa(),{channelSource:t}=Ie(),n=Fe(t.channel),r=!!e&&((s=t.channel)==null?void 0:s.isAIAgent);return n&&r?a.createElement(dv,null):a.createElement(Lv,null)},Ha=({start:e,title:t,titleAlign:n="start",end:r,containerProps:s})=>{const o=l.useRef(null),i=l.useRef(null),[c,u]=l.useState(0),[d,m]=l.useState(0);return l.useLayoutEffect(()=>{o.current&&u(o.current.offsetWidth),i.current&&m(i.current.offsetWidth)},[e,r]),a.createElement(Dv,{...s},a.createElement($v,null,n==="center"&&t&&a.createElement(Pv,{$sideWidth:Math.max(c,d)},a.createElement(Fv,null,t)),a.createElement(Uv,null,a.createElement(Bv,{ref:o},e),(n==="start"||n==="end")&&t&&a.createElement(Gv,{$align:n,$hasStart:!!e,$hasEnd:!!r},t),a.createElement(Hv,{ref:i},r))))},Dv=_.default.div`position:relative;width:100%;background-color:${({theme:e})=>e.colors.base.headerBackground};border-bottom:1px solid ${E.themedColor.textDisabled};`,$v=_.default.div`position:relative;height:56px;padding:11px 12px;`,Pv=_.default.div`position:absolute;left:${({$sideWidth:e})=>e}px;right:${({$sideWidth:e})=>e}px;top:0;bottom:0;display:flex;align-items:center;justify-content:center;`,Fv=_.default.div`max-width:100%;overflow:hidden;`,Uv=_.default.div`display:flex;flex-direction:row;align-items:center;justify-content:space-between;height:100%;z-index:1;`,Bv=_.default.div`flex-shrink:0;display:flex;align-items:center;`,Hv=_.default.div`flex-shrink:0;display:flex;align-items:center;`,Gv=_.default.div`flex:1;overflow:hidden;display:flex;align-items:${({$align:e})=>e==="start"?"flex-start":"flex-end"};margin-left:${({$hasStart:e})=>e?8:0}px;margin-right:${({$hasEnd:e})=>e?8:0}px;`,kt=(e=16)=>Zt()?e*1.5:e,zv=()=>{const{state:e}=de(),{messenger:t}=ie(),n=kt(),r=()=>{e.setOpened(!1)};return a.createElement(Qe,{...t.closeButton().props,type:"close",size:n,onClick:r})},Vv=()=>{const{enableCloseConversationButton:e,dispatcher:t}=de(),{channelSource:n}=Ie(),{conversation:r}=ie(),s=n.channel,o=kt(),i=(s==null?void 0:s.isAIAgent)&&e,c=!Mr(s);if(!i)return null;const u={close:r.header.closeConversationButton()},d=async()=>{s&&await t.send(tt.CloseConversation({channelUrl:s.url}))};return a.createElement(a.Fragment,null,a.createElement(Qe,{...u.close.props,type:"mute",size:o,disabled:c,onClick:d}),u.close.descriptionNode)},qv=()=>{const{state:e,enableExpandButton:t}=de(),{messenger:n}=ie(),r=kt();return t?a.createElement(Qe,{...n.expandButton(e.expanded).props,type:e.expanded?"collapse":"expand",size:r,onClick:()=>e.setExpanded(!e.expanded)}):null},Kv=({label:e,children:t,position:n="top",disabled:r})=>r?t:a.createElement(Ar,null,t,a.createElement(jv,{$position:n},a.createElement(Xv,{variant:"caption1"},e),a.createElement(Yv,{$position:n}))),Yv=({$position:e})=>a.createElement("svg",{style:{transform:e==="top"?"rotate(0)":"rotate(180deg)"},xmlns:"http://www.w3.org/2000/svg",width:"12",height:"6",viewBox:"0 0 12 6",fill:"none"},a.createElement("path",{d:"M6 6L0 0h12L6 6Z",fill:E.themedColor.textHighEmphasis})),Wv={top:B.css`flex-direction:column;top:0;transform:translate(-50%,-100%);`,bottom:B.css`flex-direction:column-reverse;bottom:0;transform:translate(-50%,100%);`},Ar=_.default.div`position:relative;`,jv=_.default.div`display:flex;align-items:center;position:absolute;left:50%;z-index:${ft.TOOLTIP};${({$position:e})=>Wv[e]}opacity:0;transition:opacity 0.2s ease-in-out;pointer-events:none;${Ar}:hover &,${Ar}:focus-within &{opacity:1;}`,Xv=_.default(H)`padding:6px 8px;background:${E.themedColor.textHighEmphasis};color:${E.themedColor.textHighEmphasisInverse};border-radius:4px;font-size:12px;white-space:nowrap;`,Zv=2e3,Fo=0,Jv=1500,mn=Symbol("header-focus-status-pause"),Uo="data-sb-header-focus-protected",Qv="[data-message-composer]",Bo=new WeakMap,ir=e=>{const t=Bo.get(e);if(t)return t;const n={focusedTargetIds:new Set,pendingBlurTimeouts:new Map,maxPauseTimeout:null};return Bo.set(e,n),n},ar=(e,t)=>{const n=e.pendingBlurTimeouts.get(t);n&&(clearTimeout(n),e.pendingBlurTimeouts.delete(t))},pn=e=>{e.maxPauseTimeout&&(clearTimeout(e.maxPauseTimeout),e.maxPauseTimeout=null)},eS=e=>{e.pendingBlurTimeouts.forEach(t=>clearTimeout(t)),e.pendingBlurTimeouts.clear(),e.focusedTargetIds.clear(),pn(e)},tS=e=>{const t=e.hasAttribute("tabindex"),n=e.getAttribute("tabindex");return t||e.tabIndex>=0?()=>{}:(e.setAttribute("tabindex","-1"),()=>{if(n===null){e.removeAttribute("tabindex");return}e.setAttribute("tabindex",n)})},nS=e=>e instanceof HTMLBodyElement||(e instanceof HTMLButtonElement||e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&e.disabled?!0:(e instanceof HTMLElement&&e.closest(Qv),!1),os=()=>{const{setStatusPauseState:e}=st(),t=l.useRef(Symbol("header-focus-target")),n=l.useRef(!1),r=l.useRef(0),s=l.useRef(null),o=l.useCallback(()=>{s.current&&(clearTimeout(s.current),s.current=null)},[]),i=l.useCallback(()=>{if(n.current)return;n.current=!0,r.current=Date.now()+Jv,o();const u=ir(e);ar(u,t.current),u.focusedTargetIds.add(t.current),u.focusedTargetIds.size===1&&e(mn,!0),pn(u),u.maxPauseTimeout=setTimeout(()=>{eS(u),e(mn,!1)},Zv)},[o,e]),c=l.useCallback(u=>{if(!n.current)return;n.current=!1;const d=u.currentTarget,m=ir(e),h=d instanceof HTMLElement&&Date.now()<=r.current;ar(m,t.current),h&&(o(),s.current=setTimeout(()=>{if(s.current=null,!(d instanceof HTMLElement)||!d.isConnected)return;const g=d.ownerDocument.activeElement,C=g instanceof HTMLElement&&g.hasAttribute(Uo);if(g===d||C||!nS(g))return;const b=tS(d);d.focus({preventScroll:!0}),b()},Fo)),m.pendingBlurTimeouts.set(t.current,setTimeout(()=>{m.pendingBlurTimeouts.delete(t.current),m.focusedTargetIds.delete(t.current),m.focusedTargetIds.size===0&&(pn(m),e(mn,!1))},Fo))},[o,e]);return l.useEffect(()=>()=>{const u=ir(e);n.current=!1,o(),ar(u,t.current),u.focusedTargetIds.delete(t.current)&&u.focusedTargetIds.size===0&&(pn(u),e(mn,!1))},[o,e]),{[Uo]:"true",onFocus:i,onBlur:c}},rS=()=>{const{logger:e}=de(),{stringSet:t}=oe(),{channelSource:n}=Ie(),{conversation:r}=ie(),s=n.channel,o=kt(),i=Hr("handoff-button",s),c=!Mr(s)||nt(s),[u,d]=l.useState(!1),m=os(),h=async()=>{d(!1);try{const g=await(s==null?void 0:s.markConversationAsHandoff());e.info("conversation.handleAgentHandoff: success",g)}catch(g){e.error("conversation.handleAgentHandoff: error",g)}};if(!i)return null;const f={handoff:r.header.handoffButton()};return a.createElement(a.Fragment,null,a.createElement(a.Fragment,null,a.createElement(Kv,{label:t.HEADER_BUTTON__AGENT_HANDOFF,position:"bottom",disabled:c},a.createElement(Qe,{...f.handoff.props,type:"agent",size:o,disabled:c,...m,onClick:()=>d(!0)})),f.handoff.descriptionNode),a.createElement(ut,{portalContainerId:Se.WINDOW,visible:u,onClose:()=>d(!1)},a.createElement(ns,{title:t.HANDOFF_CONFIRM__TITLE,description:t.HANDOFF_CONFIRM__DESCRIPTION,negativeText:t.HANDOFF_CONFIRM__CANCEL,positiveText:t.HANDOFF_CONFIRM__HANDOFF,onCancel:()=>d(!1),onConfirm:h})))},sS=l.lazy(()=>Promise.resolve().then(()=>require("./cjs/VvejebHE.cjs")).then(e=>({default:e.MarkdownText}))),oS=()=>{const{logger:e}=de(),{stringSet:t}=oe(),{memoryInfo:n,sdkUser:r}=Ne(),{actions:s}=Ie(),{conversation:o}=ie(),i=kt(20),c=os(),[u,d]=l.useState(null),[m,h]=l.useState(!1),f=l.useRef(!1);if(l.useEffect(()=>{r&&(n!=null&&n.consentDialog)&&d({...n})},[r,n==null?void 0:n.consentDialog]),!r||!n)return null;const g=o.header.memoryIndicator(n.enabled),C=async b=>{if(!f.current){f.current=!0,h(!1);try{await s.setUserMemoryState({enabled:b}),d(null)}catch(S){e.error("memoryIndicator.setUserMemoryState: error",S),h(!0)}finally{f.current=!1}}};return a.createElement(a.Fragment,null,n.showIndicator&&a.createElement(a.Fragment,null,a.createElement(lS,{...g.props,as:"button",type:"button",onClick:()=>d({...n}),...c,$size:i},a.createElement(ee,{type:"memory",size:i,color:E.themedColor.textHighEmphasis}),a.createElement(uS,{$enabled:n.enabled})),g.descriptionNode),u&&a.createElement(iS,{memoryInfo:u,onClose:()=>d(null),onSetEnabled:C}),a.createElement(Nn,{visible:m,title:t.PLACE_HOLDER__WRONG,description:t.MEMORY__ERROR_MESSAGE,onClose:()=>h(!1)}))},iS=({memoryInfo:e,onClose:t,onSetEnabled:n})=>{var h;const{stringSet:r}=oe(),{colors:s}=B.useTheme(),o=l.useId(),i=l.useId(),c=Hu(e),u=c==="consent",d={consent:{body:((h=e.consentDialog)==null?void 0:h.body)??"",negativeText:r.MEMORY__BUTTON_DONT_USE,positiveText:r.MEMORY__BUTTON_USE,onCancel:()=>n(!1),onConfirm:()=>n(!0)},on:{body:r.MEMORY__DESC_ON,negativeText:e.deleteOnOff?r.MEMORY__BUTTON_DISABLE_AND_DELETE:r.MEMORY__BUTTON_DISABLE,positiveText:r.MEMORY__BUTTON_KEEP_USING,onCancel:()=>n(!1),onConfirm:t},off:{body:r.MEMORY__DESC_OFF,negativeText:r.MEMORY__BUTTON_ENABLE,positiveText:r.MEMORY__BUTTON_KEEP_OFF,onCancel:()=>n(!0),onConfirm:t},readonly:{body:e.enabled?r.MEMORY__DESC_ON:r.MEMORY__DESC_OFF,negativeText:void 0,positiveText:r.MEMORY__BUTTON_CANCEL,onCancel:void 0,onConfirm:t}}[c],m=s.memoryDialog;return a.createElement(ut,{visible:!0,portalContainerId:Se.WINDOW,onClose:t,cancelable:!u,"aria-labelledby":o,"aria-describedby":i},a.createElement(ns,{title:r.MEMORY__DIALOG_TITLE,titleId:o,description:a.createElement(aS,null,d.body),descriptionId:i,negativeText:d.negativeText,positiveText:d.positiveText,buttonLayout:u?"horizontal":"vertical-full-width",onCancel:d.onCancel,onConfirm:d.onConfirm,styles:{titleColor:m.titleText,positiveBackground:m.positiveBackground,positiveText:m.positiveText,positiveBorderColor:m.positiveBorderColor,negativeBackground:m.negativeBackground,negativeText:m.negativeText,negativeBorderColor:m.negativeBorderColor}}))},aS=({children:e})=>{const{handlers:t}=de();return a.createElement(dS,null,a.createElement(zt,{fallback:e},a.createElement(sS,{onClickLink:t.onClickLink},e)))},cS=B.css`all:unset;box-sizing:border-box;width:${({$size:e})=>e}px;height:${({$size:e})=>e}px;display:flex;align-items:center;justify-content:center;position:relative;`,lS=_.default.button`${cS};cursor:pointer;${Re}`,uS=_.default.span`position:absolute;top:0;inset-inline-end:0;width:8px;height:8px;border-radius:999px;background-color:${({$enabled:e})=>e?E.themedColor.secondary:E.color.background300};box-shadow:0 0 0 2px ${E.color.background50};${te.dark`
|
|
451
|
+
`,Bv=l.lazy(()=>Promise.resolve().then(()=>require("./cjs/VvejebHE.cjs")).then(e=>({default:e.MarkdownText}))),Hv=()=>{const{aiAgentInfo:e,userSession:t}=Oe(),{handlers:n}=ue(),{messageSource:r,channelSource:s}=Ae(),[o,i]=l.useState(null),c=Wr("special-notice",s.channel),u=l.useCallback(()=>s.channel?c?r.messages.some(d=>nt(d,(t==null?void 0:t.userId)??"")):!0:null,[s.channel,c,r.messages,t==null?void 0:t.userId]);return l.useEffect(()=>{o||i(u())},[u,o]),o||!e.specialNotice?null:a.createElement(Uv,null,a.createElement(Bv,{onClickLink:n.onClickLink},e.specialNotice))},Gv=()=>a.createElement(zv,null,a.createElement(Hv,null),a.createElement(Av,null,a.createElement(Fv,null))),zv=_.default.div`z-index:0;border:none;width:100%;`,Vv=()=>{var s;const{testerType:e}=za(),{channelSource:t}=Ae(),n=De(t.channel),r=!!e&&((s=t.channel)==null?void 0:s.isAIAgent);return n&&r?a.createElement(vv,null):a.createElement(Gv,null)},Ka=({start:e,title:t,titleAlign:n="start",end:r,containerProps:s})=>{const o=l.useRef(null),i=l.useRef(null),[c,u]=l.useState(0),[d,m]=l.useState(0);return l.useLayoutEffect(()=>{o.current&&u(o.current.offsetWidth),i.current&&m(i.current.offsetWidth)},[e,r]),a.createElement(qv,{...s},a.createElement(Kv,null,n==="center"&&t&&a.createElement(Yv,{$sideWidth:Math.max(c,d)},a.createElement(Wv,null,t)),a.createElement(jv,null,a.createElement(Xv,{ref:o},e),(n==="start"||n==="end")&&t&&a.createElement(Jv,{$align:n,$hasStart:!!e,$hasEnd:!!r},t),a.createElement(Zv,{ref:i},r))))},qv=_.default.div`position:relative;width:100%;background-color:${({theme:e})=>e.colors.base.headerBackground};border-bottom:1px solid ${E.themedColor.textDisabled};`,Kv=_.default.div`position:relative;height:56px;padding:11px 12px;`,Yv=_.default.div`position:absolute;left:${({$sideWidth:e})=>e}px;right:${({$sideWidth:e})=>e}px;top:0;bottom:0;display:flex;align-items:center;justify-content:center;`,Wv=_.default.div`max-width:100%;overflow:hidden;`,jv=_.default.div`display:flex;flex-direction:row;align-items:center;justify-content:space-between;height:100%;z-index:1;`,Xv=_.default.div`flex-shrink:0;display:flex;align-items:center;`,Zv=_.default.div`flex-shrink:0;display:flex;align-items:center;`,Jv=_.default.div`flex:1;overflow:hidden;display:flex;align-items:${({$align:e})=>e==="start"?"flex-start":"flex-end"};margin-left:${({$hasStart:e})=>e?8:0}px;margin-right:${({$hasEnd:e})=>e?8:0}px;`,Nt=(e=16)=>en()?e*1.5:e,Qv=()=>{const{state:e}=ue(),{messenger:t}=ae(),n=Nt(),r=()=>{e.setOpened(!1)};return a.createElement(st,{...t.closeButton().props,type:"close",size:n,onClick:r})},eS=()=>{const{enableCloseConversationButton:e,dispatcher:t}=ue(),{channelSource:n}=Ae(),{conversation:r}=ae(),s=n.channel,o=Nt(),i=(s==null?void 0:s.isAIAgent)&&e,c=!$r(s);if(!i)return null;const u={close:r.header.closeConversationButton()},d=async()=>{s&&await t.send(at.CloseConversation({channelUrl:s.url}))};return a.createElement(a.Fragment,null,a.createElement(st,{...u.close.props,type:"mute",size:o,disabled:c,onClick:d}),u.close.descriptionNode)},tS=()=>{const{state:e,enableExpandButton:t}=ue(),{messenger:n}=ae(),r=Nt();return t?a.createElement(st,{...n.expandButton(e.expanded).props,type:e.expanded?"collapse":"expand",size:r,onClick:()=>e.setExpanded(!e.expanded)}):null},nS=({label:e,children:t,position:n="top",disabled:r})=>r?t:a.createElement(kr,null,t,a.createElement(oS,{$position:n},a.createElement(iS,{variant:"caption1"},e),a.createElement(rS,{$position:n}))),rS=({$position:e})=>a.createElement("svg",{style:{transform:e==="top"?"rotate(0)":"rotate(180deg)"},xmlns:"http://www.w3.org/2000/svg",width:"12",height:"6",viewBox:"0 0 12 6",fill:"none"},a.createElement("path",{d:"M6 6L0 0h12L6 6Z",fill:E.themedColor.textHighEmphasis})),sS={top:U.css`flex-direction:column;top:0;transform:translate(-50%,-100%);`,bottom:U.css`flex-direction:column-reverse;bottom:0;transform:translate(-50%,100%);`},kr=_.default.div`position:relative;`,oS=_.default.div`display:flex;align-items:center;position:absolute;left:50%;z-index:${_t.TOOLTIP};${({$position:e})=>sS[e]}opacity:0;transition:opacity 0.2s ease-in-out;pointer-events:none;${kr}:hover &,${kr}:focus-within &{opacity:1;}`,iS=_.default(B)`padding:6px 8px;background:${E.themedColor.textHighEmphasis};color:${E.themedColor.textHighEmphasisInverse};border-radius:4px;font-size:12px;white-space:nowrap;`,aS=2e3,Go=0,cS=1500,pn=Symbol("header-focus-status-pause"),zo="data-sb-header-focus-protected",lS="[data-message-composer]",Vo=new WeakMap,mr=e=>{const t=Vo.get(e);if(t)return t;const n={focusedTargetIds:new Set,pendingBlurTimeouts:new Map,maxPauseTimeout:null};return Vo.set(e,n),n},hr=(e,t)=>{const n=e.pendingBlurTimeouts.get(t);n&&(clearTimeout(n),e.pendingBlurTimeouts.delete(t))},bn=e=>{e.maxPauseTimeout&&(clearTimeout(e.maxPauseTimeout),e.maxPauseTimeout=null)},uS=e=>{e.pendingBlurTimeouts.forEach(t=>clearTimeout(t)),e.pendingBlurTimeouts.clear(),e.focusedTargetIds.clear(),bn(e)},dS=e=>{const t=e.hasAttribute("tabindex"),n=e.getAttribute("tabindex");return t||e.tabIndex>=0?()=>{}:(e.setAttribute("tabindex","-1"),()=>{if(n===null){e.removeAttribute("tabindex");return}e.setAttribute("tabindex",n)})},mS=e=>e instanceof HTMLBodyElement||(e instanceof HTMLButtonElement||e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&e.disabled?!0:(e instanceof HTMLElement&&e.closest(lS),!1),ms=()=>{const{setStatusPauseState:e}=lt(),t=l.useRef(Symbol("header-focus-target")),n=l.useRef(!1),r=l.useRef(0),s=l.useRef(null),o=l.useCallback(()=>{s.current&&(clearTimeout(s.current),s.current=null)},[]),i=l.useCallback(()=>{if(n.current)return;n.current=!0,r.current=Date.now()+cS,o();const u=mr(e);hr(u,t.current),u.focusedTargetIds.add(t.current),u.focusedTargetIds.size===1&&e(pn,!0),bn(u),u.maxPauseTimeout=setTimeout(()=>{uS(u),e(pn,!1)},aS)},[o,e]),c=l.useCallback(u=>{if(!n.current)return;n.current=!1;const d=u.currentTarget,m=mr(e),h=d instanceof HTMLElement&&Date.now()<=r.current;hr(m,t.current),h&&(o(),s.current=setTimeout(()=>{if(s.current=null,!(d instanceof HTMLElement)||!d.isConnected)return;const g=d.ownerDocument.activeElement,p=g instanceof HTMLElement&&g.hasAttribute(zo);if(g===d||p||!mS(g))return;const v=dS(d);d.focus({preventScroll:!0}),v()},Go)),m.pendingBlurTimeouts.set(t.current,setTimeout(()=>{m.pendingBlurTimeouts.delete(t.current),m.focusedTargetIds.delete(t.current),m.focusedTargetIds.size===0&&(bn(m),e(pn,!1))},Go))},[o,e]);return l.useEffect(()=>()=>{const u=mr(e);n.current=!1,o(),hr(u,t.current),u.focusedTargetIds.delete(t.current)&&u.focusedTargetIds.size===0&&(bn(u),e(pn,!1))},[o,e]),{[zo]:"true",onFocus:i,onBlur:c}},hS=()=>{const{logger:e}=ue(),{stringSet:t}=ie(),{channelSource:n}=Ae(),{conversation:r}=ae(),s=n.channel,o=Nt(),i=Wr("handoff-button",s),c=!$r(s)||ct(s),[u,d]=l.useState(!1),m=ms(),h=async()=>{d(!1);try{const g=await(s==null?void 0:s.markConversationAsHandoff());e.info("conversation.handleAgentHandoff: success",g)}catch(g){e.error("conversation.handleAgentHandoff: error",g)}};if(!i)return null;const f={handoff:r.header.handoffButton()};return a.createElement(a.Fragment,null,a.createElement(a.Fragment,null,a.createElement(nS,{label:t.HEADER_BUTTON__AGENT_HANDOFF,position:"bottom",disabled:c},a.createElement(st,{...f.handoff.props,type:"agent",size:o,disabled:c,...m,onClick:()=>d(!0)})),f.handoff.descriptionNode),a.createElement(ft,{portalContainerId:Se.WINDOW,visible:u,onClose:()=>d(!1)},a.createElement(ls,{title:t.HANDOFF_CONFIRM__TITLE,description:t.HANDOFF_CONFIRM__DESCRIPTION,negativeText:t.HANDOFF_CONFIRM__CANCEL,positiveText:t.HANDOFF_CONFIRM__HANDOFF,onCancel:()=>d(!1),onConfirm:h})))},fS=l.lazy(()=>Promise.resolve().then(()=>require("./cjs/VvejebHE.cjs")).then(e=>({default:e.MarkdownText}))),gS=()=>{const{logger:e}=ue(),{stringSet:t}=ie(),{memoryInfo:n,sdkUser:r}=Oe(),{actions:s}=Ae(),{conversation:o}=ae(),i=Nt(20),c=ms(),[u,d]=l.useState(null),[m,h]=l.useState(!1),f=l.useRef(!1);if(l.useEffect(()=>{r&&(n!=null&&n.consentDialog)&&d({...n})},[r,n==null?void 0:n.consentDialog]),!r||!n)return null;const g=o.header.memoryIndicator(n.enabled),p=async v=>{if(!f.current){f.current=!0,h(!1);try{await s.setUserMemoryState({enabled:v}),d(null)}catch(S){e.error("memoryIndicator.setUserMemoryState: error",S),h(!0)}finally{f.current=!1}}};return a.createElement(a.Fragment,null,n.showIndicator&&a.createElement(a.Fragment,null,a.createElement(CS,{...g.props,as:"button",type:"button",onClick:()=>d({...n}),...c,$size:i},a.createElement(te,{type:"memory",size:i,color:E.themedColor.textHighEmphasis}),a.createElement(bS,{$enabled:n.enabled})),g.descriptionNode),u&&a.createElement(pS,{memoryInfo:u,onClose:()=>d(null),onSetEnabled:p}),a.createElement(Fn,{visible:m,title:t.PLACE_HOLDER__WRONG,description:t.MEMORY__ERROR_MESSAGE,onClose:()=>h(!1)}))},pS=({memoryInfo:e,onClose:t,onSetEnabled:n})=>{var h;const{stringSet:r}=ie(),{colors:s}=U.useTheme(),o=l.useId(),i=l.useId(),c=Wu(e),u=c==="consent",d={consent:{body:((h=e.consentDialog)==null?void 0:h.body)??"",negativeText:r.MEMORY__BUTTON_DONT_USE,positiveText:r.MEMORY__BUTTON_USE,onCancel:()=>n(!1),onConfirm:()=>n(!0)},on:{body:r.MEMORY__DESC_ON,negativeText:e.deleteOnOff?r.MEMORY__BUTTON_DISABLE_AND_DELETE:r.MEMORY__BUTTON_DISABLE,positiveText:r.MEMORY__BUTTON_KEEP_USING,onCancel:()=>n(!1),onConfirm:t},off:{body:r.MEMORY__DESC_OFF,negativeText:r.MEMORY__BUTTON_ENABLE,positiveText:r.MEMORY__BUTTON_KEEP_OFF,onCancel:()=>n(!0),onConfirm:t},readonly:{body:e.enabled?r.MEMORY__DESC_ON:r.MEMORY__DESC_OFF,negativeText:void 0,positiveText:r.MEMORY__BUTTON_CANCEL,onCancel:void 0,onConfirm:t}}[c],m=s.memoryDialog;return a.createElement(ft,{visible:!0,portalContainerId:Se.WINDOW,onClose:t,cancelable:!u,"aria-labelledby":o,"aria-describedby":i},a.createElement(ls,{title:r.MEMORY__DIALOG_TITLE,titleId:o,description:a.createElement(_S,null,d.body),descriptionId:i,negativeText:d.negativeText,positiveText:d.positiveText,buttonLayout:u?"horizontal":"vertical-full-width",onCancel:d.onCancel,onConfirm:d.onConfirm,styles:{titleColor:m.titleText,positiveBackground:m.positiveBackground,positiveText:m.positiveText,positiveBorderColor:m.positiveBorderColor,negativeBackground:m.negativeBackground,negativeText:m.negativeText,negativeBorderColor:m.negativeBorderColor}}))},_S=({children:e})=>{const{handlers:t}=ue();return a.createElement(vS,null,a.createElement(Kt,{fallback:e},a.createElement(fS,{onClickLink:t.onClickLink},e)))},ES=U.css`all:unset;box-sizing:border-box;width:${({$size:e})=>e}px;height:${({$size:e})=>e}px;display:flex;align-items:center;justify-content:center;position:relative;`,CS=_.default.button`${ES};cursor:pointer;${xe}`,bS=_.default.span`position:absolute;top:0;inset-inline-end:0;width:8px;height:8px;border-radius:999px;background-color:${({$enabled:e})=>e?E.themedColor.secondary:E.color.background300};box-shadow:0 0 0 2px ${E.color.background50};${ne.dark`
|
|
452
452
|
box-shadow: 0 0 0 2px ${E.color.background500};
|
|
453
453
|
`}
|
|
454
|
-
`,
|
|
454
|
+
`,vS=_.default.div`color:${({theme:e})=>e.colors.memoryDialog.markdownBodyText};line-height:20px;word-break:break-word;&& a{color:${({theme:e})=>e.colors.memoryDialog.markdownLinkText};font-weight:inherit;text-decoration:underline;}`,SS=()=>{const{conversation:e}=ae(),{onNavigateToConversationList:t}=Ae();if(!t)return null;const n={menu:e.header.menuButton()};return a.createElement(a.Fragment,null,a.createElement(st,{...n.menu.props,...Ui,type:"menu",size:24,onClick:()=>t()}),n.menu.descriptionNode)},Ya=({channel:e,size:t=40,skeletonColor:n=E.themedColor.bg_100_500})=>{const{userSession:r,aiAgentInfo:s}=Oe(),{fallbackIcon:o,url:i}=jr({channel:e,aiAgentInfo:s,userSession:r}),[c,u]=l.useState();c&&c.url!==i&&u(void 0);const d=U.useTheme(),{primary:m,primaryContrastContent:h}=d.colors.base;if(!o)return a.createElement(qo,{"aria-hidden":"true",$size:t,$bgColor:n});if(i&&(c==null?void 0:c.status)!=="failed"){const f=(c==null?void 0:c.status)==="loaded"?m:n;return a.createElement(Ia,{src:i,size:t,"aria-hidden":"true",onImageError:g=>u({url:g,status:"failed"}),onImageLoad:g=>u({url:g,status:"loaded"}),backgroundColor:f})}return a.createElement(qo,{"aria-hidden":"true",$size:t,$bgColor:m},a.createElement(te,{type:o,size:t*.55,color:h}))},qo=_.default.div`width:${({$size:e})=>e}px;height:${({$size:e})=>e}px;border-radius:50%;background-color:${({$bgColor:e})=>e};display:flex;align-items:center;justify-content:center;flex-shrink:0;`,yS=()=>{const{channelSource:e}=Ae(),{aiAgentInfo:t,userSession:n}=Oe(),{conversation:r}=ae(),{config:s}=ye(),{announcementsEnabled:o}=lt(),i=U.useTheme(),c=e.channel,u=jr({channel:c,userSession:n,aiAgentInfo:t}),d=s.conversation.header.avatarEnabled,m=ms(),h=pa({enabled:o,label:u.title}),f={title:r.header.title(u.title,{active:h.enabled,titleId:h.id,initialFocus:!1})};return a.createElement(AS,null,d&&a.createElement(Ya,{channel:c,size:34,skeletonColor:i.colors.conversation.headerProfileSkeleton}),a.createElement(TS,{...f.title.props,...m},u.title))},AS=_.default.div`display:flex;flex-direction:row;align-items:center;gap:6px;min-width:0;width:100%;overflow:hidden;`,TS=_.default(B).attrs({variant:"h2",color:E.themedColor.textHighEmphasis})`
|
|
455
455
|
margin: 0;
|
|
456
456
|
flex: 1;
|
|
457
457
|
min-width: 0;
|
|
@@ -463,10 +463,10 @@
|
|
|
463
463
|
&:focus {
|
|
464
464
|
outline: none;
|
|
465
465
|
}
|
|
466
|
-
`,
|
|
466
|
+
`,IS=e=>{const{components:t}=bt.useContext();return a.createElement(Ka,{start:a.createElement(t.StartArea,null),title:a.createElement(t.TitleArea,null),titleAlign:e.titleAlign,end:a.createElement(t.EndArea,null),containerProps:Gi})},xS=()=>{const{components:e}=bt.useContext();return a.createElement(e.MenuButton,null)},RS=()=>{const{components:e}=bt.useContext();return a.createElement(e.Title,null)},MS=()=>{const{components:e}=bt.useContext();return a.createElement(kS,null,a.createElement(e.MemoryIndicator,null),a.createElement(e.HandoffButton,null),a.createElement(e.ConversationCloseButton,null),a.createElement(e.ExpandButton,null),a.createElement(e.CloseButton,null))},bt=je({template:IS,components:{StartArea:xS,TitleArea:RS,EndArea:MS,MenuButton:SS,Title:yS,MemoryIndicator:gS,HandoffButton:hS,ConversationCloseButton:eS,ExpandButton:tS,CloseButton:Qv}}),wS=()=>{const{Template:e}=bt.useContext();return a.createElement(e,{titleAlign:"start"})},kS=_.default.div`display:flex;gap:10px;align-items:center;justify-content:center;`,hs=({children:e,onNavigateToConversationList:t,channelUrl:n,onClearChannelUrl:r,shouldMarkAsRead:s,shouldInitializeConversation:o,initialUserMessage:i,announcementsEnabled:c=!0,conversationStatsEnabled:u,initialFocusTarget:d,style:m,closedChannelUrl:h,onClearClosedChannelUrl:f})=>{const{Template:g}=Vn.useContext();return a.createElement(ha,{onNavigateToConversationList:t,channelUrl:n??h,onClearChannelUrl:r??f,conversationStatsEnabled:u,shouldMarkAsRead:s,shouldInitializeConversation:o,initialUserMessage:i},a.createElement(Tr,null,a.createElement(Tr.Consumer,null,p=>a.createElement(Bf,{announcementsEnabled:c},a.createElement(LS,null),a.createElement(OS,null),a.createElement(NS,{style:m,dragHandlers:p,initialFocusTarget:d},a.createElement(g,null)),e))))},LS=()=>(Bg(),null),OS=()=>(tp(),qg(),Jg(),null),NS=({style:e,dragHandlers:t,initialFocusTarget:n,children:r})=>{const s=l.useRef(null);return Ug(s,n),a.createElement($S,{ref:s,style:e,...t},r)},DS=e=>{const{components:t}=Vn.useContext();return a.createElement(a.Fragment,null,a.createElement(t.Header,null),a.createElement(t.Body,null),a.createElement(t.Footer,null))},Vn=je({template:DS,components:{Header:wS,Body:mv,Footer:Vv}}),$S=_.default.div`height:100%;width:100%;display:flex;flex-direction:column;flex:1;background-color:${({theme:e})=>e.colors.base.background};`,Wa=ve("ConversationListAnnouncements",{announcementsEnabled:!0,announceScreenEntry:me}),PS=Wa.Provider,fs=Wa.useContext,FS=({children:e,announcementsEnabled:t=!0})=>{const{announceScreenEntry:n}=es(),r=l.useCallback(o=>{t&&n(o)},[n,t]),s=l.useMemo(()=>({announcementsEnabled:t,announceScreenEntry:r}),[t,r]);return a.createElement(PS,{value:s},e)},{Provider:US,Context:BS,useContext:nn}=ve("ConversationList");function ja({conversationListLimit:e,conversationListFilter:t,conversationListStatsEnabled:n,onOpenConversationView:r=me,children:s}){return a.createElement(gm,{conversationListLimit:e,conversationListFilter:t,conversationListStatsEnabled:n},o=>a.createElement(US,{value:{...o,onOpenConversationView:r}},s))}const HS=e=>{const{announcementsEnabled:t}=fs(),{listSource:n}=nn(),r=Zi();_a(e,{enabled:t,ready:n.initialized,suppressed:r})},GS=()=>{const{announceScreenEntry:e,announcementsEnabled:t}=fs(),{listSource:n}=nn(),r=l.useRef(!1);l.useEffect(()=>{if(!t){r.current=!1;return}if(!n.initialized||r.current)return;const s=n.channels.length,o=setTimeout(()=>{e({screen:"conversationList",conversationCount:s}),r.current=!0},0);return()=>clearTimeout(o)},[e,t,n.initialized])},zS=({channel:e})=>a.createElement(Ya,{channel:e}),Lr=99,VS=e=>{var S,C;const{channel:t,onClick:n}=e,{stringSet:r,format:s}=ie(),{userSession:o,aiAgentInfo:i}=Oe(),{conversationList:c}=ae(),u=jr({channel:t,userSession:o,aiAgentInfo:i}),d=zu(t,{formatMultipleFilesCount:r.CONVERSATION_LIST__MULTIPLE_FILES_COUNT}),m=qu(t,s,{justNow:r.DATE_FORMAT__JUST_NOW,minutesAgo:r.DATE_FORMAT__MINUTES_AGO,hoursAgo:r.DATE_FORMAT__HOURS_AGO,dateShortFormat:r.DATE_FORMAT__DATE_SHORT}),h=t.unreadMessageCount,f=(S=t.lastMessage)!=null&&S.isAdminMessage()?r.CONVERSATION_LIST__SYSTEM_MESSAGE:u.title,g=De(t)?r.CONVERSATION_LIST__ENDED:"",p=n?()=>n():void 0,v=c.item({agent:f,status:g,lastMessage:d,time:m,unreadCount:h,onActivate:p});return a.createElement(qS,{"data-testid":"sb-conversation-list-item",$clickable:!!p,...v.props},a.createElement(KS,null,a.createElement(zS,{...e})),a.createElement(YS,null,a.createElement(WS,null,(C=t.lastMessage)!=null&&C.isFileMessage()&&(!t.lastMessage.message||t.lastMessage.name===t.lastMessage.message)?a.createElement(Sa,{variant:"subtitle1",color:E.themedColor.textHighEmphasis},d):a.createElement(B,{variant:"subtitle1",color:E.themedColor.textHighEmphasis,maxTextLines:1},d),a.createElement(jS,null,De(t)&&a.createElement(a.Fragment,null,a.createElement(B,{variant:"caption1",color:E.themedColor.textMidEmphasis,maxTextLines:1},r.CONVERSATION_LIST__ENDED),a.createElement(XS,null)),a.createElement(B,{variant:"caption2",color:E.themedColor.textLowEmphasis,maxTextLines:1},m))),h>0&&a.createElement(ZS,{$count:h},a.createElement(B,{variant:"caption3",color:E.themedColor.textHighEmphasisInverse},h<=Lr?h:`${Lr}+`))),v.descriptionNode)},gs=je({template:VS,components:{}}),qS=_.default.div`display:flex;flex-shrink:0;flex-direction:row;align-items:center;position:relative;width:100%;height:72px;box-sizing:border-box;gap:16px;cursor:${({$clickable:e})=>e?"pointer":"default"};`,KS=_.default.div`display:flex;align-items:center;justify-content:center;padding-inline-start:16px;`,YS=_.default.div`display:flex;flex-direction:row;align-items:center;flex:1;min-width:0;padding-inline-end:16px;height:100%;gap:8px;border-bottom:1px solid ${E.themedColor.textDisabled};`,WS=_.default.div`display:flex;flex-direction:column;justify-content:center;flex:1;min-width:0;gap:4px;word-break:break-word;overflow-wrap:break-word;`,jS=_.default.div`display:flex;align-items:center;gap:6px;`,XS=_.default.div`width:2px;height:2px;border-radius:1px;background-color:${E.themedColor.textLowEmphasis};`,ZS=_.default.div`display:flex;align-items:center;justify-content:center;height:20px;padding:4px;border-radius:10px;background-color:${E.themedColor.error};${({$count:e})=>e<=Lr&&U.css`
|
|
467
467
|
width: 20px;
|
|
468
468
|
`}
|
|
469
|
-
`,
|
|
469
|
+
`,JS=({items:e,renderItem:t,onEndReached:n,role:r,"aria-label":s})=>{const o=i=>{const c=i.target;c.scrollHeight-c.scrollTop-c.clientHeight<=2&&(n==null||n())};return a.createElement(QS,{role:r,"aria-label":s,onScroll:i=>o(i)},e.map((i,c)=>{const u=t(i,c);if(r!=="list")return u;const d=l.isValidElement(u)&&u.key!=null?u.key:c;return a.createElement(ey,{key:d,role:"listitem"},u)}))},QS=_.default.div`width:100%;height:100%;display:flex;flex-direction:column;flex:1;overflow:auto;overscroll-behavior:contain;`,ey=_.default.div`flex-shrink:0;`,ty=()=>{const{stringSet:e}=ie(),{listSource:t,onOpenConversationView:n}=nn(),{Template:r}=gs.useContext();return t.initialized?t.channels.length===0?a.createElement(Vt,{type:"noChannels",label:e.CONVERSATION_LIST__NO_CONVERSATIONS}):a.createElement(JS,{role:"list","aria-label":e.CONVERSATION_LIST__HEADER_TITLE,items:t.channels,renderItem:s=>{var o,i,c;return a.createElement(r,{key:s.url,channel:s,onClick:()=>n(s.url,De(s)?"closed":"open"),channelUrl:s.url,title:(i=(o=s.conversation)==null?void 0:o.topics)==null?void 0:i.join(", "),lastMessageTimestamp:(c=s.lastMessage)==null?void 0:c.createdAt})},onEndReached:()=>{t.loadMore()}}):a.createElement(Vt,{type:"loading"})},ny=()=>{const{stringSet:e}=ie(),{_aiAgentSDK:t}=ye(),{language:n,countryCode:r,context:s}=ue(),{aiAgentInfo:o,refreshActiveChannel:i,createConversation:c}=Oe(),{onOpenConversationView:u}=nn(),{conversationList:d}=ae(),m=async()=>{var h;if(o.isMultipleActiveConversationsEnabled){const f=await c({aiAgentId:o.userId,language:n,country:r,context:s});(h=t.session)==null||h._updateActiveChannel({url:f,status:"open"}),u(f,"open",{initialFocusTarget:"messageInput"})}else{const f=await i();u(f,"open",{initialFocusTarget:"messageInput"})}};return a.createElement(ry,{...d.footer.button({onActivate:m}).props},a.createElement(sy,{variant:"h1"},e.TALK_TO_AGENT))},ry=_.default.div`background-color:${({theme:e})=>e.colors.base.primary};display:flex;align-items:center;justify-content:center;padding:16px;cursor:pointer;`,sy=_.default(B)`color:${({theme:e})=>e.colors.base.primaryContrastContent};overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,oy=()=>{const{state:e}=ue(),{messenger:t}=ae(),n=Nt(),r=()=>{e.setOpened(!1)};return a.createElement(st,{...t.closeButton().props,type:"close",size:n,onClick:r})},iy=()=>{const{stringSet:e}=ie(),{announcementsEnabled:t}=fs(),{conversationList:n}=ae(),r=e.CONVERSATION_LIST__HEADER_TITLE,s=pa({enabled:t,label:r}),o={title:n.headerTitle(r,{active:s.enabled,titleId:s.id})};return a.createElement(ay,{forwardedAs:"h2",variant:"h2",color:E.themedColor.textHighEmphasis,...o.title.props},r)},ay=_.default(B)`margin:0;padding:0 4px;min-width:0;width:100%;box-sizing:border-box;text-overflow:ellipsis;overflow:hidden;white-space:nowrap;`,cy=e=>{const{components:t}=Dt.useContext();return a.createElement(Ka,{start:a.createElement(t.StartArea,null),title:a.createElement(t.TitleArea,null),titleAlign:e.titleAlign,end:a.createElement(t.EndArea,null),containerProps:Gi})},ly=()=>null,uy=()=>{const{components:e}=Dt.useContext();return a.createElement(e.Title,null)},dy=()=>{const{components:e}=Dt.useContext();return a.createElement(e.CloseButton,null)},Dt=je({template:cy,components:{StartArea:ly,TitleArea:uy,EndArea:dy,Title:iy,CloseButton:oy}}),my=()=>{const{Template:e}=Dt.useContext();return a.createElement(e,{titleAlign:"start"})},hy=()=>(GS(),null),ps=({conversationListLimit:e,conversationListFilter:t,children:n,onOpenConversationView:r,announcementsEnabled:s=!0,conversationListStatsEnabled:o,style:i})=>{const{Template:c}=qn.useContext();return a.createElement(ja,{conversationListLimit:e,conversationListFilter:t,conversationListStatsEnabled:o,onOpenConversationView:r},a.createElement(FS,{announcementsEnabled:s},a.createElement(hy,null),a.createElement(fy,{style:i},a.createElement(c,null)),n))},fy=({style:e,children:t})=>{const n=l.useRef(null);return HS(n),a.createElement(py,{ref:n,style:e},t)},gy=()=>{const{components:e}=qn.useContext();return a.createElement(a.Fragment,null,a.createElement(e.Header,null),a.createElement(e.Body,null),a.createElement(e.Footer,null))},qn=je({template:gy,components:{Header:my,Body:ty,Footer:ny}}),py=_.default.div`height:100%;width:100%;display:flex;flex-direction:column;flex:1;background-color:${({theme:e})=>e.colors.base.background};`,_y=U.css`:where(#${Se.ENTRY}) :not(code *){font-family:'Roboto',sans-serif;box-sizing:border-box;}`,Ey=[_y,hf,ff],Cy=(e,...t)=>U.createGlobalStyle(e,...Ey,...t),by=Cy``,vy=Gu(Vn,Ct,Ot,Hn,zn,qn,bt,gs,Dt,Gn,Pn),Sy=typeof __SBA_USE_MESSAGE_TEMPLATE__>"u"||__SBA_USE_MESSAGE_TEMPLATE__;function Xa({appearance:e,rootElement:t,logger:n,language:r,languageCode:s,stringSet:o,children:i,messageTemplate:c,icons:u,theme:d,entryElement:m,modalRootElement:h}){Of(Sy?Qh:"",t);const[f,g]=l.useState(null),p=l.useCallback(C=>{g(A=>A===C?A:C)},[]),v=m??f,S=a.createElement(U.StyleSheetManager,{target:t},a.createElement(wf,{rootElement:t,logger:n,appearance:e,theme:d},a.createElement(rf,{rootElement:t,boundaryElement:v},a.createElement(Cm,{internalVariables:c==null?void 0:c.__internalVariables},a.createElement(mf,{stringSet:o,logger:n,language:r,languageCode:s},a.createElement(Rf,{icons:u},a.createElement(vy,null,a.createElement(tf,{entryElement:v,modalRootElement:h,rootElement:t},i),a.createElement(by,null))))))));return m?S:a.createElement("div",{ref:p,style:{display:"contents"}},S)}const yy=()=>{const[e,t]=l.useState(null),[n,r]=l.useState(null),s=l.useCallback(i=>{t(c=>c===i?c:i)},[]),o=l.useCallback(i=>{r(c=>c===i?c:i)},[]);return{entryElement:e,modalRootElement:n,setEntryElement:s,setModalRootElement:o}},_s=l.forwardRef(function({rootElement:t=document.body,logLevel:n=Ce.LogLevel.WARN,language:r=navigator.language,userSessionInfo:s,children:o,chatParams:i,icons:c,...u},d){var S,C,A;Ht.level!==n&&(Ht.level=n);const{entryElement:m,modalRootElement:h,setEntryElement:f,setModalRootElement:g}=yy();Lf("https://fonts.googleapis.com/css2?family=Roboto&display=swap",t);const p=Wi(r),v=ji.has(p)?p:Qt;return a.createElement("div",{ref:f,id:Se.ENTRY,lang:v,style:{width:"fit-content",height:"fit-content",...u.entryStyle}},m&&h&&a.createElement(Xa,{logger:Ht,rootElement:t,appearance:(S=u.agentPreviewConfigs)==null?void 0:S.appearance,stringSet:u.stringSet,language:v,messageTemplate:u.messageTemplate,icons:c,theme:u.theme,entryElement:m,modalRootElement:h},a.createElement(mg,{rootElement:t,language:r,logger:Ht,dispatcher:Za,chatParams:{...i,...u.customApiHost&&{customApiHost:u.customApiHost},...u.customWebSocketHost&&{customWebSocketHost:u.customWebSocketHost}},chatSDK:u.customChatSDK,_forceCreateChannel:(C=u.agentPreviewConfigs)==null?void 0:C.forceCreateChannel,_agentVersion:(A=u.agentPreviewConfigs)==null?void 0:A.agentVersion,...u},a.createElement(bg,{ref:d,userSessionInfo:s},a.createElement(_v,{...u._UNSAFE_INTERNAL_dashboardTester},a.createElement(Ff,null,o))))),a.createElement("div",{ref:g,id:Se.MODAL_ROOT,dir:u.dir}))}),Ht=new ci(Ce.LogLevel.WARN),Za=new oi(Ht),{Provider:Ay,useContext:rn}=ve("PageChildren"),Ja=({children:e})=>{const[t,n]=l.useState(()=>hs),[r,s]=l.useState(null),[o,i]=l.useState(()=>ps),[c,u]=l.useState(null),d=l.useCallback(h=>{n(()=>h)},[]),m=l.useCallback(h=>{i(()=>h)},[]);return a.createElement(Ay,{value:{conversationComponent:t,setConversationComponent:d,conversationChildren:r,setConversationChildren:s,conversationListComponent:o,setConversationListComponent:m,conversationListChildren:c,setConversationListChildren:u}},e)},Es=(e,t)=>e?{role:"dialog","aria-modal":"true",...t?{"aria-labelledby":Se.WINDOW_TITLE}:{"aria-label":"Messenger"}}:{"aria-hidden":"true",inert:!0},Qa=({children:e,isOpened:t,zIndex:n=_t.WINDOW})=>a.createElement(ss,null,a.createElement(Ty,{isOpened:t,zIndex:n},e)),Ty=({children:e,isOpened:t,zIndex:n=_t.WINDOW})=>{const{dir:r,rootElement:s}=ue(),o=mt(s,!0),i=l.useRef(null),{hasWindowTitleReference:c,isWindowNameReady:u}=Un();return $n(t,i,{nameReady:u}),l.useEffect(()=>{const d="sb-agent-block-scroll";return t?o.body.classList.add(d):o.body.classList.remove(d),()=>{o.body.classList.remove(d)}},[o,t]),a.createElement(Iy,{ref:i,id:Se.WINDOW,dir:r,...Es(t,c),$visible:t,$zIndex:n},e)},Iy=_.default.div`width:100%;height:100%;position:fixed;top:0;left:0;z-index:${({$zIndex:e})=>e};visibility:${({$visible:e})=>e?"visible":"hidden"};`,xy=48,Ry=2/3,Ko=12;function ec({className:e,children:t,isOpened:n,onClick:r,"aria-label":s,"aria-describedby":o,type:i,imageUrl:c,dir:u,animated:d=!0,backgroundColor:m,size:h=xy,hasUnread:f=!1}){const g=Ra(),p=d&&!g,v=br(m),S=Math.round(h*Ry);return a.createElement(ky,{dir:u,id:Se.LAUNCHER,className:e,"aria-label":s,"aria-describedby":o,onClick:r,$animated:p,$backgroundColor:m,$prefersReducedMotion:g,$size:h},a.createElement(Ly,{$isOpened:n,$animated:p,$fillColor:v,$iconSize:S,$prefersReducedMotion:g},a.createElement(Yo.Open,{url:c,isDefaultIcon:i==="default_icon",size:S})),a.createElement(Oy,{$isOpened:n,$animated:p,$fillColor:v,$iconSize:S,$prefersReducedMotion:g},a.createElement(Yo.Close,{size:S})),f&&a.createElement(Ny,null),t)}const My=U.css`&:hover{transition:transform 250ms cubic-bezier(0.33,0,0,1);transform:scale(1.1);}&:active{transform:scale(0.8);}`,wy=U.css`img{width:100%;height:100%;object-fit:cover;user-select:none;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;-webkit-user-drag:none;&[data-default-icon='true']{width:${({$iconSize:e})=>e}px;height:${({$iconSize:e})=>e}px;filter:${({$fillColor:e})=>e===qt.WHITE?"grayscale(100%) brightness(2000%)":"grayscale(100%) invert(100%) saturate(0%) brightness(0%) contrast(1000%)"};}}`,tc=U.css`svg{width:${({$iconSize:e})=>e}px;height:${({$iconSize:e})=>e}px;${({$fillColor:e})=>U.css`
|
|
470
470
|
ellipse,
|
|
471
471
|
path {
|
|
472
472
|
fill: ${e};
|
|
@@ -476,7 +476,7 @@
|
|
|
476
476
|
}
|
|
477
477
|
`}
|
|
478
478
|
}
|
|
479
|
-
`,
|
|
479
|
+
`,ky=_.default.button`position:relative;padding:0;width:${({$size:e})=>e}px;height:${({$size:e})=>e}px;background:${({$backgroundColor:e})=>e};border-radius:50%;transition:${({$prefersReducedMotion:e})=>e?"none":"all 0.3s cubic-bezier(0.31, -0.105, 0.43, 1.4)"};border:none;display:flex;justify-content:center;align-items:center;box-shadow:${ua};${({$animated:e})=>e&&My}`,nc=_.default.span.attrs({"aria-hidden":"true"})`
|
|
480
480
|
position: absolute;
|
|
481
481
|
width: 100%;
|
|
482
482
|
height: 100%;
|
|
@@ -486,23 +486,23 @@
|
|
|
486
486
|
display: flex;
|
|
487
487
|
justify-content: center;
|
|
488
488
|
align-items: center;
|
|
489
|
-
`,
|
|
489
|
+
`,Ly=_.default(nc)`transition:${({$prefersReducedMotion:e})=>e?"none":"transform 0.16s linear, opacity 0.08s linear, scale 0.16s linear"};opacity:${({$isOpened:e})=>e?0:1};transform:${({$animated:e,$isOpened:t})=>e&&(t?"rotate(-90deg) scale(0)":"rotate(0deg)")};${wy}${tc}`,Oy=_.default(nc)`transition:${({$prefersReducedMotion:e})=>e?"none":"transform 0.16s linear, opacity 0.08s linear, scale 0.16s linear"};scale:${({$isOpened:e})=>e?1:0};transform:${({$animated:e,$isOpened:t})=>e&&(t?"rotate(0deg)":"rotate(-90deg)")};${tc}`,Ny=_.default.span.attrs({"aria-hidden":"true"})`
|
|
490
490
|
position: absolute;
|
|
491
491
|
top: 1px;
|
|
492
492
|
inset-inline-end: 1px;
|
|
493
|
-
width: ${
|
|
494
|
-
height: ${
|
|
493
|
+
width: ${Ko}px;
|
|
494
|
+
height: ${Ko}px;
|
|
495
495
|
border-radius: 50%;
|
|
496
496
|
background-color: ${E.themedColor.error};
|
|
497
|
-
`,
|
|
497
|
+
`,Yo={Open:e=>e.url?a.createElement("img",{src:e.url,alt:"","data-default-icon":e.isDefaultIcon}):a.createElement(te,{size:e.size,type:"delight"}),Close:({size:e})=>a.createElement(te,{size:e,type:"chevron-down"})};function rc({className:e,size:t,entryPoint:n="Conversation",activeRoute:r}){const{colors:s}=U.useTheme(),{chatSDK:o,config:i,dir:c,state:u}=ue(),{resolveElement:d}=Jr(),{launcher:m}=ae(),{launcherInfo:h}=Oe(),f=i.launcher.unreadBadgeEnabled,g=Ti(),p=nh(o,{enabled:f,opened:u.opened,filter:g}),v=(r??n)==="ConversationList",S={launcher:m.button({isOpened:u.opened,opensConversationList:v})};th("launcher_toggle"),$y();const C=()=>{Ie(()=>{const T=d(Se.WINDOW),I=T?oa(T):null;I==null||I.focus()})},A=()=>{Ie(()=>{var T;(T=d(Se.LAUNCHER))==null||T.focus()})},y=()=>{const T=!u.opened;u.setOpened(T),T?C():A()};return a.createElement(ec,{dir:c,className:e,isOpened:u.opened,onClick:y,type:h.type,imageUrl:h.imageUrl,backgroundColor:s.base.primary,size:t,hasUnread:f&&!u.opened&&p,...S.launcher.props},S.launcher.descriptionNode)}const Dy=1e3*60;function $y(){const{chatSDK:e,state:t,logger:n,enableAutoDisconnectInLauncher:r}=ue(),s=l.useRef(null);l.useEffect(()=>{if(!r)return;function o(){s.current&&(clearTimeout(s.current),s.current=null)}function i(){e.connectionState===Ce.ConnectionState.CLOSED&&(e.reconnect(),n.debug("useSDKInactivityTimeout: reconnected")),o(),n.debug("useSDKInactivityTimeout: clear disconnect schedule")}function c(){o(),s.current=setTimeout(async()=>{await e.disconnectWebSocket(),n.debug("useSDKInactivityTimeout: disconnected")},Dy)}t.opened?i():(c(),n.debug("useSDKInactivityTimeout: schedule disconnect"))},[r,e,t.opened])}const sc=l.createContext(null);function Kn(){const e=l.useContext(sc);if(!e)throw new Error("useNavigator() must be used within <Navigator />");return e}function oc({children:e}){const t=Kn();return typeof e=="function"?e(t):a.createElement(a.Fragment,null,e)}function ic({children:e}){return a.createElement(a.Fragment,null,e)}const Py=U.keyframes`0%{transform:translateY(40px);opacity:0;}100%{transform:translateY(0px);opacity:1;}`,Fy=U.keyframes`0%{transform:translateY(0px);opacity:1;}100%{transform:translateY(40px);opacity:0;}`,Uy=U.css`animation-name:${Py};animation-duration:0.3s;animation-fill-mode:forwards;`,By=U.css``,Hy=U.css`animation-name:${Fy};animation-duration:0.3s;animation-fill-mode:forwards;`,Gy=U.css`visibility:hidden;`,zy=_.default.div`position:absolute;top:0;left:0;width:100%;height:100%;${({$transitionState:e})=>{switch(e){case"entering":return Uy;case"entered":return By;case"exiting":return Hy;case"exited":return Gy;default:return""}}}${({$active:e})=>e?U.css`
|
|
498
498
|
z-index: 999;
|
|
499
|
-
`:
|
|
500
|
-
`;function
|
|
499
|
+
`:U.css`z-index:1;pointer-events:none;`}
|
|
500
|
+
`;function xt({initialId:e,children:t}){const[n,r]=l.useState([e]),s=n[n.length-1],o=l.useCallback((C,A)=>{r(y=>[...y,C]),f(y=>({...y,[C]:!0})),A!=null&&A.reset&&S(y=>({...y,[C]:(y[C]||0)+1})),p(y=>({...y,[C]:"entering"})),setTimeout(()=>{p(y=>({...y,[C]:"entered"}))},300)},[]),i=l.useCallback(()=>{r(C=>{if(C.length<=1)return C;const A=C[C.length-1];return p(y=>({...y,[A]:"exiting"})),setTimeout(()=>{p(y=>({...y,[A]:"exited"})),r(y=>y.slice(0,-1))},300),C})},[]),c=l.useMemo(()=>({navigation:{navigate:o,pop:i},activeScreenId:s}),[o,i,s]),u=l.useMemo(()=>l.Children.toArray(t).filter(C=>C.type===oc),[t]),d=l.useMemo(()=>l.Children.toArray(t).filter(C=>C.type===ic),[t]),m=l.useMemo(()=>{const C={};return u.forEach(A=>{const{id:y,lazy:T,children:I}=A.props;C[y]={lazy:T,element:typeof I=="function"?I(c):I}}),C},[u,c]),[h,f]=l.useState(()=>{const C={};return Object.entries(m).forEach(([A,{lazy:y}])=>{y===!1&&(C[A]=!0)}),C[e]=!0,C}),[g,p]=l.useState(()=>{const C={};return Object.keys(m).forEach(A=>{A===e?C[A]="entered":C[A]="exited"}),C}),[v,S]=l.useState({});return a.createElement(sc.Provider,{value:c},d,a.createElement(Vy,null,Object.keys(m).map(C=>{var I;if(!h[C])return null;const A=g[C]||"exited",y=C===s,T=`${C}-${v[C]||0}`;return a.createElement(zy,{key:T,$transitionState:A,$active:y,"aria-hidden":y?void 0:!0,inert:y?void 0:!0},(I=m[C])==null?void 0:I.element)})))}const Vy=_.default.div`position:relative;width:100%;height:100%;`;xt.Screen=oc;xt.Effect=ic;const ze={conv:"conv",convList:"conv-list"},qy=e=>e===ze.convList?"ConversationList":"Conversation",ac=({isOpened:e,entryPoint:t,selectedChannelUrl:n,setSelectedChannelUrl:r,nudgeConversation:s,onActiveRouteChange:o})=>{const{conversationComponent:i,conversationChildren:c,conversationListComponent:u,conversationListChildren:d}=rn(),[m,h]=l.useState(),f=(()=>{switch(t){case"Conversation":return ze.conv;case"ConversationList":return ze.convList;default:return ze.conv}})(),g=a.createElement(a.Fragment,null,a.createElement(Ky,{onOpenConversationView:(p,v)=>{r(v),h(void 0),p.navigate(ze.conv)}}),a.createElement(Wy,{onActiveRouteChange:o}));return a.createElement(xt,{initialId:f},a.createElement(xt.Effect,null,a.createElement(Yy,{nudgeConversation:s,onNavigate:p=>{h("messageInput"),p.navigate(ze.conv)}})),a.createElement(xt.Screen,{id:ze.conv},({navigation:p,activeScreenId:v})=>{const S=v===ze.conv,C=e&&S;return a.createElement(a.Fragment,null,g,a.createElement(i,{key:n,channelUrl:n,onClearChannelUrl:()=>r(void 0),onNavigateToConversationList:()=>{h(void 0),p.navigate(ze.convList)},announcementsEnabled:C,conversationStatsEnabled:C,shouldMarkAsRead:C,shouldInitializeConversation:C,initialUserMessage:s&&s.channelUrl===n?s.initialUserMessage:void 0,initialFocusTarget:m},c))}),a.createElement(xt.Screen,{id:ze.convList,lazy:!0},({navigation:p,activeScreenId:v})=>{const S=v===ze.convList,C=e&&S;return a.createElement(a.Fragment,null,g,a.createElement(u,{announcementsEnabled:C,conversationListStatsEnabled:C,onOpenConversationView:(A,y,T)=>{r(A),h(T==null?void 0:T.initialFocusTarget),p.navigate(ze.conv)}},d))}))},Ky=({onOpenConversationView:e})=>{const{registerOnJoinedProactiveConversation:t}=Oe(),{navigation:n}=Kn();return t(({channel:r})=>{e(n,r.url)}),null},Yy=({nudgeConversation:e,onNavigate:t})=>{const{navigation:n}=Kn();return l.useEffect(()=>{e&&t(n)},[e]),null},Wy=({onActiveRouteChange:e})=>{const{activeScreenId:t}=Kn();return l.useEffect(()=>{e==null||e(qy(t))},[t,e]),null},jy=({isExpanded:e,isOpened:t,children:n,launcher:r})=>a.createElement(ss,null,a.createElement(Xy,{isExpanded:e,isOpened:t,launcher:r},n)),Xy=({isExpanded:e,isOpened:t,children:n,launcher:r})=>{const{dir:s}=ue(),o=l.useRef(null),{hasWindowTitleReference:i,isWindowNameReady:c}=Un();return $n(t,o,{nameReady:c}),a.createElement(Zy,null,a.createElement(Jy,{ref:o,dir:s,id:Se.WINDOW,...Es(t,i),$isExpanded:e,$isOpened:t},n),r)},Zy=_.default.div`display:flex;flex-direction:column;gap:8px;align-items:flex-end;`,Jy=_.default.div`background:${({theme:e})=>e.colors.base.background};display:flex;overscroll-behavior:none;-webkit-overflow-scrolling:auto;height:640px;min-height:80px;width:400px;max-width:80vw;max-height:80vh;box-shadow:0px 16px 24px 2px rgba(33,33,33,0.12),0px 6px 30px 5px rgba(33,33,33,0.08),0px 6px 10px -5px rgba(33,33,33,0.04);border-radius:16px;overflow:hidden;transition:width 200ms ease 0s,height 200ms ease 0s,max-height 200ms ease 0s,transform 150ms cubic-bezier(0,1.2,1,1) 0s,opacity 83ms ease-out 0s;transform:scale(0.15);opacity:0;transform-origin:right bottom;[dir='rtl'] &:not([dir='ltr']),&[dir='rtl']{transform-origin:left bottom;}${({$isOpened:e})=>e&&eA};${({$isExpanded:e})=>e&&Qy};`,Qy=U.css`width:743px;height:723px;`,eA=U.css`pointer-events:all;transform:scale(1);opacity:1;transition:width 200ms ease 0s,height 200ms ease 0s,max-height 200ms ease 0s,transform 300ms cubic-bezier(0,1.2,1,1) 0s,opacity 83ms ease-out 0s;`,cc=({isMessengerOpened:e,onConversationStarted:t,className:n})=>{const{stringSet:r}=ie(),{dir:s}=ue(),{nudgeMessage:o,nudgeMessageKey:i,dismissNudgeMessage:c,startNudgeConversation:u}=wm({isMessengerOpened:e,onConversationStarted:t});return o?a.createElement(nA,{key:i,className:n,dir:s},a.createElement(rA,{onClick:u},a.createElement(sA,{variant:"body3",color:E.themedColor.textHighEmphasis,maxTextLines:2},o.message)),a.createElement(oA,{type:"close",size:16,"aria-label":r.A11Y_DISMISS_NUDGE_MESSAGE,onClick:c})):null},lc=12,tA=U.keyframes`from{opacity:0;transform:scale(0.8);}`,nA=_.default.div`position:relative;display:flex;align-items:flex-start;gap:8px;padding:16px;min-width:120px;max-width:320px;box-sizing:border-box;border-radius:${lc}px;background-color:${E.themedColor.bg_50_600};box-shadow:${ua};animation-name:${tA};animation-duration:0.3s;animation-timing-function:cubic-bezier(0.31,-0.105,0.43,1.4);@media (prefers-reduced-motion:reduce){animation-name:none;}`,rA=_.default.button`all:unset;flex:1;min-width:0;cursor:pointer;text-align:start;${xe}&::after{content:'';position:absolute;inset:0;border-radius:${lc}px;}`,sA=_.default(B)`line-height:20px;overflow-wrap:anywhere;white-space:pre-line;`,oA=_.default(st)`position:relative;margin:-4px;`,iA=l.forwardRef(function({children:e,initialChannelUrl:t,...n},r){const s=en(),[o,i]=l.useState(t),[c,u]=l.useState(),[d,m]=l.useState(n.entryPoint??"Conversation"),h=s?Qa:jy;return a.createElement(_s,{enableExpandButton:!s,ref:r,...n},a.createElement(aa,null,({state:f})=>a.createElement(Ja,null,a.createElement(h,{isExpanded:f.expanded,isOpened:f.opened,...s&&{zIndex:"auto"},launcher:a.createElement(a.Fragment,null,a.createElement(cc,{isMessengerOpened:f.opened,onConversationStarted:g=>{i(g.channelUrl),u(g),f.setOpened(!0)}}),a.createElement(rc,{entryPoint:n.entryPoint,activeRoute:d}))},a.createElement(ac,{isOpened:f.opened,entryPoint:n.entryPoint,selectedChannelUrl:o,setSelectedChannelUrl:i,nudgeConversation:c,onActiveRouteChange:m})),e)))}),{Provider:aA,useContext:Yn}=ve("FixedMessengerStyle");function uc(e,t,n,r=0){return U.css`&&{position:fixed;z-index:${_t.LAUNCHER};${dc(e,t,n,r)};}`}function dc(e,t,n,r=0){const{top:s,bottom:o,start:i,end:c}=n;let u="",d="";switch(e){case"start":d=`inset-inline-start: ${Je(i)}`;break;case"end":d=`inset-inline-end: ${Je(c)}`;break}switch(t){case"top":u=`top: calc(${Je(s)} + ${r}px)`;break;case"bottom":u=`bottom: calc(${Je(o)} + ${r}px)`;break}return U.css`${u};${d};`}function cA(e){const{horizontal:t,vertical:n,margin:r,launcherSize:s}=Yn();return a.createElement(lA,{...e,size:s,$horizontal:t,$vertical:n,$margin:r})}const lA=_.default(rc)`${({$horizontal:e,$vertical:t,$margin:n})=>uc(e,t,n)};`,uA=({isExpanded:e,isOpened:t,children:n})=>a.createElement(ss,null,a.createElement(dA,{isExpanded:e,isOpened:t},n)),dA=({isExpanded:e,isOpened:t,children:n})=>{const{dir:r}=ue(),{horizontal:s,vertical:o,margin:i,launcherSize:c}=Yn(),u=l.useRef(null),{hasWindowTitleReference:d,isWindowNameReady:m}=Un();return $n(t,u,{nameReady:m}),a.createElement(mA,{ref:u,dir:r,id:Se.WINDOW,...Es(t,d),$isExpanded:e,$isOpened:t,$horizontal:s,$vertical:o,$margin:i,$launcherSize:c},n)},mA=_.default.div`background:${({theme:e})=>e.colors.base.background};display:flex;overscroll-behavior:none;-webkit-overflow-scrolling:auto;position:fixed;pointer-events:none;visibility:hidden;${({$horizontal:e,$vertical:t,$margin:n,$launcherSize:r})=>dc(e,t,n,r+12)};height:640px;min-height:80px;width:400px;max-width:80vw;max-height:80vh;box-shadow:0px 16px 24px 2px rgba(33,33,33,0.12),0px 6px 30px 5px rgba(33,33,33,0.08),0px 6px 10px -5px rgba(33,33,33,0.04);border-radius:16px;overflow:hidden;transition:width 200ms ease 0s,height 200ms ease 0s,max-height 200ms ease 0s,transform 150ms cubic-bezier(0,1.2,1,1) 0s,opacity 83ms ease-out 0s,visibility 0s linear 150ms;transform:scale(0.15);opacity:0;transform-origin:${({$horizontal:e,$vertical:t})=>`${e==="start"?"left":"right"} ${t}`};
|
|
501
501
|
[dir='rtl'] &:not([dir='ltr']),
|
|
502
502
|
&[dir='rtl'] {
|
|
503
503
|
transform-origin: ${({$horizontal:e,$vertical:t})=>`${e==="start"?"right":"left"} ${t}`};
|
|
504
504
|
}
|
|
505
505
|
|
|
506
|
-
${({$isOpened:e})=>e&&
|
|
507
|
-
${({$isExpanded:e})=>e&&
|
|
508
|
-
`,
|
|
506
|
+
${({$isOpened:e})=>e&&fA};
|
|
507
|
+
${({$isExpanded:e})=>e&&hA};
|
|
508
|
+
`,hA=U.css`width:743px;height:723px;`,fA=U.css`z-index:${_t.WINDOW};pointer-events:all;visibility:visible;transform:scale(1);opacity:1;transition:width 200ms ease 0s,height 200ms ease 0s,max-height 200ms ease 0s,transform 300ms cubic-bezier(0,1.2,1,1) 0s,opacity 83ms ease-out 0s,visibility 0s linear 0s;`,gA=8,pA=e=>{const{horizontal:t,vertical:n,margin:r,launcherSize:s}=Yn();return a.createElement(_A,{...e,$horizontal:t,$vertical:n,$margin:r,$launcherSize:s})},_A=_.default(cc)`${({$horizontal:e,$vertical:t,$margin:n,$launcherSize:r})=>uc(e,t,n,r+gA)};`,mc={top:24,bottom:24,start:24,end:24},EA=l.forwardRef(function({children:e,initialChannelUrl:t,...n},r){const[s,o]=l.useState(t),[i,c]=l.useState(),[u,d]=l.useState(n.entryPoint??"Conversation"),[m,h]=l.useState("end-bottom"),[f,g]=l.useState(mc),[p,v]=l.useState(48),S=en(),C=S?Qa:uA,{horizontal:A,vertical:y}=l.useMemo(()=>{const[T,I]=m.split("-");return{horizontal:T==="start"?"start":"end",vertical:I==="top"?"top":"bottom"}},[m]);return a.createElement(_s,{enableExpandButton:!S,ref:r,...n},a.createElement(aa,null,({state:T})=>a.createElement(aA,{value:{horizontal:A,vertical:y,margin:f,launcherSize:p,setPosition:h,setMargin:g,setLauncherSize:v}},a.createElement(Ja,null,a.createElement(C,{isExpanded:T.expanded,isOpened:T.opened},a.createElement(ac,{isOpened:T.opened,entryPoint:n.entryPoint,selectedChannelUrl:s,setSelectedChannelUrl:o,nudgeConversation:i,onActiveRouteChange:d})),a.createElement(cA,{entryPoint:n.entryPoint,activeRoute:u}),a.createElement(pA,{isMessengerOpened:T.opened,onConversationStarted:I=>{o(I.channelUrl),c(I),T.setOpened(!0)}}),e))))}),CA=e=>{var s,o,i,c;const{setPosition:t,setMargin:n,setLauncherSize:r}=Yn();return l.useLayoutEffect(()=>{e.position&&t(e.position),e.margin&&n({...mc,...e.margin}),e.launcherSize&&r(e.launcherSize)},[e.position,(s=e.margin)==null?void 0:s.top,(o=e.margin)==null?void 0:o.bottom,(i=e.margin)==null?void 0:i.start,(c=e.margin)==null?void 0:c.end,e.launcherSize]),null},bA=({children:e})=>{const{setConversationChildren:t}=rn();return l.useLayoutEffect(()=>(t(e),()=>t(null)),[e]),null},vA=({component:e})=>{const{setConversationComponent:t}=rn();return l.useLayoutEffect(()=>(t(e),()=>t(hs)),[e,t]),null},SA=({children:e})=>{const{setConversationListChildren:t}=rn();return l.useLayoutEffect(()=>(t(e),()=>t(null)),[e]),null},yA=({component:e})=>{const{setConversationListComponent:t}=rn();return l.useLayoutEffect(()=>(t(e),()=>t(ps)),[e,t]),null},AA=Object.assign(EA,{Style:CA,Conversation:vA,ConversationChildren:bA,ConversationList:yA,ConversationListChildren:SA}),TA=e=>{const{refreshActiveChannel:t}=Oe(),[n,r]=l.useState(!1),s=l.useRef(null),o=l.useRef(null);return l.useEffect(()=>{n&&t().then(()=>{var i;(i=s.current)==null||i.call(s),r(!1)}).catch(i=>{var c;(c=o.current)==null||c.call(o,i),r(!1)})},[n]),l.useCallback(()=>new Promise((i,c)=>{s.current=i,o.current=c,e().then(()=>r(!0)).catch(c)}),[e])};pi.set(Ce.SendbirdPlatform.JS,{deviceOSPlatform:Hc()?Ce.DeviceOsPlatform.MOBILE_WEB:Ce.DeviceOsPlatform.WEB,messengerVersion:Yh,keyValueStorage:Zh(),networkStateAdapter:Xh(),foregroundStateAdapter:jh});exports.ANCHOR_REL=Zr;exports.AgentProviderContainer=_s;exports.AgentUIProviderContainer=Xa;exports.AnonymousSessionInfo=pr;exports.CSATType=et;exports.Commands=at;exports.ConnectionDelayLayout=Pn;exports.Conversation=hs;exports.ConversationContext=Og;exports.ConversationContextProvider=ha;exports.ConversationHeaderLayout=bt;exports.ConversationLayout=Vn;exports.ConversationList=ps;exports.ConversationListContext=BS;exports.ConversationListContextProvider=ja;exports.ConversationListHeaderLayout=Dt;exports.ConversationListItemLayout=gs;exports.ConversationListLayout=qn;exports.DefaultMessenger=iA;exports.DeskTicketPriority=Vr;exports.DeskTicketStatus=zr;exports.FixedMessenger=AA;exports.ID_INCOMING=ot;exports.IncomingMessageLayout=Ct;exports.LauncherBase=ec;exports.LogLevel=Fr;exports.ManualSessionInfo=li;exports.MessageListUILayout=zn;exports.MessageLogs=Ba;exports.OutgoingMessageLayout=Ot;exports.PlaceholderLayout=Gn;exports.SystemMessageLayout=Hn;exports.cssVars=E;exports.escapeMarkdownSyntax=Fc;exports.flattenObject=Su;exports.mapCommonStringsToReactFormat=Yi;exports.messengerDispatcher=Za;exports.noop=me;exports.parseToMessageTemplate=fi;exports.parseToUITemplate=bu;exports.pickColorByTheme=vu;exports.replaceVariablesAsync=Au;exports.replaceVariablesSync=yu;exports.useAIAgentContext=ye;exports.useConversationContext=Ae;exports.useConversationListContext=nn;exports.useLocalizationContext=ie;exports.useMessageTemplateFetchingContext=Em;exports.useMessengerContext=ue;exports.useMessengerSessionContext=Oe;exports.useMessengerThemeContext=Qi;exports.useRefreshActiveChannel=TA;
|