@sendbird/ai-agent-messenger-react 1.31.1 → 1.33.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 +187 -187
- package/dist/index.d.ts +1507 -121
- package/dist/index.js +7487 -5593
- package/package.json +4 -4
package/dist/index.cjs
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
"use strict";var ha=Object.defineProperty;var pa=(e,t,n)=>t in e?ha(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var S=(e,t,n)=>pa(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ue=require("@sendbird/chat"),u=require("react"),D=require("styled-components"),Je=require("date-fns"),_a=require("date-fns/locale/en-US"),He=require("@sendbird/chat/message"),Ea=require("react-dom"),Ee=require("@sendbird/chat/aiAgent"),Ye=require("@sendbird/chat/groupChannel"),ba=require("date-fns/isSameDay"),Ca=require("dompurify"),rr=e=>e&&e.__esModule?e:{default:e};function va(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 ya=rr(ue),i=va(u),p=rr(D),ds=rr(Ca),ct="sb-agent",ms="KEY_IMG_ASPECT_RATIO",Hn="*/*",ee={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 tn=(e=>(e.IN_PROGRESS="IN_PROGRESS",e.COMPLETED="COMPLETED",e.CANCELED="CANCELED",e))(tn||{}),It=(e=>(e.IN_PROGRESS="IN_PROGRESS",e.COMPLETED="COMPLETED",e.CANCELED="CANCELED",e))(It||{});const fs=e=>{var t;return!!((t=e==null?void 0:e.extendedMessagePayload)!=null&&t.steward)},Sa=e=>e===It.COMPLETED||e===It.CANCELED?e:It.IN_PROGRESS,Tn=e=>tt(e)&&!fs(e),tt=e=>!!e&&"sender"in e,Aa=e=>tt(e)?e.sendingStatus==="succeeded"?String(e.messageId):e.reqId:String(e.messageId),xa=(e,t,n,r=!0)=>{if(!r||!Tn(e))return"single";const o=()=>{if(!Tn(t))return!1;const c=t.sender.userId===e.sender.userId,d=Je.isSameMinute(t.createdAt,e.createdAt);return c&&d},s=()=>{if(!Tn(n))return!1;const c=n.sender.userId===e.sender.userId,d=Je.isSameMinute(n.createdAt,e.createdAt);return c&&d},a=o(),l=s();return a&&l?"middle":a?"bottom":l?"top":"single"},gt=(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,we={isAdmin:e=>e.isAdminMessage(),isCSAT:e=>{var t;return e.isAdminMessage()&&!!((t=e.extendedMessagePayload)!=null&&t.csat)},isSteward:e=>fs(e),isIncoming:(e,t)=>tt(e)&&e.sender.userId!==t,isOutgoing:(e,t)=>tt(e)&&(e.sender.userId===t||e.sendingStatus===He.SendingStatus.PENDING)},ze=e=>e.startsWith("image/"),mn=e=>e.startsWith("video/"),gs=({name:e="",mimeType:t=""})=>t==="application/pdf"||/\.pdf$/i.test(e.trim()),or=(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"},hs=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},fn=e=>{switch(e){case"top":case"middle":return ee.GAP_GROUPED;default:return ee.GAP_UNGROUPED}},Ta=(e,t)=>{const n=/```(\w+)?\n([\s\S]*?)```/g,r=[];let o=0;return e.replace(n,(s,...a)=>{const[l,c,d]=a;return o<d&&r.push({type:"text",value:e.slice(o,d).trim()}),r.push({type:"code",value:c.trim(),language:l?l.trim():"plaintext"}),o=d+s.length,s}),o<e.length&&r.push({type:"text",value:e.slice(o).trim()}),t?r.map(s=>s.type!=="text"?s:{...s,value:t(s.value)}):r},Ia=e=>e.replace(/\[([^\]]+)\](?!\()/g,"\\[$1\\]"),wa=e=>e.replace(/([a-zA-Z0-9])_(?=[a-zA-Z0-9])/g,"$1\\_"),Ma=e=>e.replace(/~~/g,"\\~\\~"),ka=e=>{let t=e;return t=Ia(t),t=wa(t),t=Ma(t),t},Ra=typeof navigator<"u"&&navigator.product==="ReactNative",Gr=(e,t)=>{const n=r=>!t||t.length===0?!0:tt(r)&&t.includes(r.sendingStatus);return Ra?e.find(n):e.findLast(n)};function ce(){}function La(){const e=typeof navigator<"u"?navigator.userAgent:"",t=/iPad|iPhone|iPod/.test(e),n=/Android/.test(e);return t||n}function Oa(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 Gn=e=>{try{return JSON.parse(e===""?"{}":e)}catch{return{}}},We={isStreaming(e){const t=Gn(e.data);return typeof t=="object"&&!!t.stream},isWelcomeMessage(e,t){var n;if(((n=e.extendedMessagePayload)==null?void 0:n.bot_message_type)==="welcome")return!0;if(gt(e,t)){const r=Gn(e.data);return!(r!=null&&r.respond_mesg_id)&&!(r!=null&&r.stream)}return!1},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)}},In=`@${ct}`,Na=({appId:e,aiAgentId:t,storage:n})=>{const r={templateBase:`${In}-template`,template:o=>`${r.templateBase}/templates/${o}`,templateToken:()=>`${r.templateBase}/tokens`,messengerSession:o=>{const s=Oa(`${e}/${t}/${o}`);return`${In}-udata/${s}`},anonUserSession:()=>`${In}-session/${e}/${t}`};return{template:{set:(o,s)=>n.set(r.template(o),s),get:o=>n.get(r.template(o)),setCachedToken:o=>n.set(r.templateToken(),o),getCachedToken:()=>n.get(r.templateToken()),clear:()=>{n.getKeys(r.templateBase).forEach(n.delete)}},messenger:{getSettings:o=>{try{const s=n.get(r.messengerSession(o));return s?JSON.parse(s):null}catch{return null}},setSettings:(o,s)=>{try{delete s.auto_created_user;const a=JSON.stringify(s);n.set(r.messengerSession(o),a)}catch{return}},getAnonUser:()=>{try{const o=n.get(r.anonUserSession());return o?JSON.parse(o):null}catch{return null}},setAnonUser:o=>{try{const s=JSON.stringify(o);n.set(r.anonUserSession(),s)}catch{return}},clear:o=>{try{o&&n.delete(r.messengerSession(o)),n.delete(r.anonUserSession())}catch{return}}}}},ps=(e,t,n={})=>{let r=null,o=null,s=null;const{leading:a=!0,trailing:l=!0}=n,c=(...d)=>{const m=Date.now();if(s===null||m-s>=t)a?(e(...d),s=m):(o=d,s=m);else if(o=d,l&&!r){const f=t-(m-s);r=setTimeout(()=>{o&&l&&(e(...o),s=Date.now()),r=null,o=null},f)}};return c.cancel=()=>{r&&(clearTimeout(r),r=null),o=null,s=null},c},Da=()=>{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 $a{constructor(t){S(this,"_params");this._params={aiAgentChannelFilter:(t==null?void 0:t.aiAgentChannelFilter)??Ee.AIAgentChannelFilter.INCLUDE,aiAgentConversationStatusFilter:(t==null?void 0:t.aiAgentConversationStatusFilter)??[Ee.ConversationStatus.OPEN,Ee.ConversationStatus.CLOSED],aiAgentIds:(t==null?void 0:t.aiAgentIds)??[],deskChannelFilter:(t==null?void 0:t.deskChannelFilter)??Ee.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:o,aiAgentConversationStatusFilter:s,aiAgentIds:a,deskChannelFilter:l}=this._params;return r!=null&&r.includes(t.url)?!0:t.isAIAgent?!(!t.conversation||o===Ee.AIAgentChannelFilter.EXCLUDE||a&&a.length>0&&!a.includes(t.conversation.aiAgentId)||s&&s.length>0&&!s.some(d=>{var m;return((m=t.conversation)==null?void 0:m.status)===d})):t.isDesk?l!==Ee.DeskChannelFilter.EXCLUDE:!1}}class _s extends Ye.BaseChannelCollection{constructor(n,r){const o=new $a(r.filter),s=n,a=s.aiAgent._manager,l=r.limit??20,c=Ye.GroupChannelListOrder.LATEST_LAST_MESSAGE,d={getRemoteChannels:(m,f,g,E)=>a.getMyGroupChannels(m,f.params,E),changeLogSync:m=>{const{aiAgentChannelFilter:f,aiAgentIds:g,deskChannelFilter:E,pinnedChannelUrls:y,copilotConversationOnly:v,copilotSupportChannelUrl:b}=o.params,_={aiAgentChannelFilter:f,aiAgentIds:g,deskChannelFilter:E,pinnedChannelUrls:y,copilotConversationOnly:v,copilotSupportChannelUrl:b};return a.getMyGroupChannelChangeLogs(m,_,Ye.GroupChannelEventSource.SYNC_CHANNEL_CHANGELOGS)}};super(s.aiAgent._iid,{filter:o,order:c,limit:l,syncKeyPrefix:"aiAgent",fetcher:d});S(this,"_params");S(this,"_sdk");S(this,"_throttledOnChannelChanged");S(this,"_key");S(this,"_pendingChannels",[]);this._sdk=n,this._params=r,this._key=`clc-${Da()}`,this._throttledOnChannelChanged=ps(()=>{var E;const m=[...this._pendingChannels];this._pendingChannels=[];const f=new Map;for(const{channel:y,context:v}of m)f.delete(y.url),f.set(y.url,{channel:y,context:v});const g=new Map;for(const{channel:y,context:v}of f.values())g.has(v)||g.set(v,new Map),g.get(v).set(y.url,y);for(const[y,v]of g){const b=Array.from(v.values()),_=(E=this._sdk.currentUser)==null?void 0:E.userId,C=b.filter(A=>this.filter.match(A,_)),x=b.filter(A=>!this.filter.match(A,_)).map(A=>A.url);C.length>0&&this._base._addChannelsToView(C,y,!1),x.length>0&&this._removeChannels(x,y)}},250,{trailing:!0,leading:!0}),this._base._subscribeChannelEvent(this._key,{onUpdate:(m,f)=>{for(const g of m)this._pendingChannels.push({channel:g,context:f});this._throttledOnChannelChanged()},onRemove:(m,f)=>{this._removeChannels(m,f)}})}get _base(){return this}_removeChannels(n,r){const o=new Set(n);this._pendingChannels=this._pendingChannels.filter(({channel:s})=>!o.has(s.url)),this._base._removeChannelsFromView(n,r)}get channels(){var l;const n=((l=this._params.filter)==null?void 0:l.pinnedChannelUrls)??[],r=[],o=new Map(super.channels.map(c=>[c.url,c])),s=new Set;for(const c of n){const d=o.get(c);d&&!s.has(c)&&(r.push(d),s.add(c))}const a=super.channels.filter(c=>!s.has(c.url));return[...r,...a]}setConversationListCollectionHandler(n){super.setGroupChannelCollectionHandler(n)}dispose(){super.dispose(),this._throttledOnChannelChanged.cancel(),this._base._unsubscribeChannelEvent(this._key)}}class Es{constructor(t){S(this,"subscribers",{});this.logger=t}async send(t){const n=Pa(),r=this.subscribers[t.type];if(r){this.logger.debug(`messenger.dispatcher: dispatching command: ${t.type}`,t.payload);const o=r.map(s=>s(t.payload));await Promise.all(o).catch(s=>{this.logger.error(`messenger.dispatcher: error in callback for command: ${t.type}`,s)})}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(o=>o!==n))}}const Pa=()=>{let e=ce,t=ce;return{promise:new Promise((r,o)=>{e=r,t=o}),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))(Be||{});class Lt{constructor(t={}){S(this,"payload");this.payload=t}toJSON(){return JSON.stringify({type:this.type,payload:this.payload})}}const Qe={CloseConversation:e=>new Fa(e),MessengerSettingsUpdated:e=>new Ua(e),ActiveChannelUpdated:e=>new Ba(e),AnonymousSessionTokenExpired:()=>new Ha,AuthTokenRefreshed:()=>new Ga};class Fa extends Lt{constructor(){super(...arguments);S(this,"type","conv.close")}}class Ua extends Lt{constructor(){super(...arguments);S(this,"type","messenger.settings.updated")}}class Ba extends Lt{constructor(){super(...arguments);S(this,"type","active.channel.updated")}}class Ha extends Lt{constructor(){super(...arguments);S(this,"type","anon.token.expired")}}class Ga extends Lt{constructor(){super(...arguments);S(this,"type","auth.token.refreshed")}}var sr=(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))(sr||{});class bs{constructor(t){S(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 Cs{constructor({userId:t,authToken:n,sessionHandler:r}){S(this,"userId");S(this,"authToken");S(this,"sessionHandler");this.userId=t,this.authToken=n,this.sessionHandler=r}}class zn{constructor(){S(this,"userId");S(this,"authToken");S(this,"sessionHandler")}}const za=e=>({onSessionTokenRequired:t=>{t(null),e.send(Qe.AnonymousSessionTokenExpired())}}),Va="ai_agent:stats",Ya="conversation_initial_render",Wa=800220;var Ce=(e=>(e.AUTH="auth_duration",e.GET_CHANNEL="get_channel_duration",e.GET_MESSAGES="get_messages_duration",e.TOTAL_DURATION="total_duration",e.TOTAL_DURATION_FROM_CACHE="total_duration_from_cache",e))(Ce||{});class qa{constructor(){S(this,"timers",new Map);S(this,"committed",!1);S(this,"commitCallback",null);S(this,"conversationId",null);S(this,"channelUrl",null);S(this,"errorCode",null);S(this,"errorDescription",null);S(this,"extraData",{})}setCommitCallback(t){return this.commitCallback=t,this}setConversationId(t){return this.conversationId=t,this}setChannelUrl(t){return this.setExtra("channel_url",t),this}setError(t,n){return this.errorCode=t??Wa,this.errorDescription=n,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:Date.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:Date.now()}),this)}getDuration(t){const n=this.timers.get(t);return!n||n.startTime===null||n.endTime===null?null:n.endTime-n.startTime}isCommitted(){return this.committed}commit(){if(this.committed||!this.commitCallback)return!1;const t=this.buildPayload();return t?(this.committed=!0,this.commitCallback(Va,t)):!1}}class Ka extends qa{constructor(){super(...arguments);S(this,"presentMethod","direct_present")}setPresentMethod(n){return this.presentMethod=n,this}getMetricKey(){return Ya}buildPayload(){const n=this.getDuration(Ce.AUTH),r=this.getDuration(Ce.GET_CHANNEL),o=this.getDuration(Ce.GET_MESSAGES),s=this.getDuration(Ce.TOTAL_DURATION_FROM_CACHE),a=this.getDuration(Ce.TOTAL_DURATION),l={...this.extraData,present_method:this.presentMethod,...n!==null&&{auth_duration:n},...r!==null&&{get_channel_duration:r},...o!==null&&{get_messages_duration:o},...s!==null&&{total_duration_from_cache:s}},c={key:this.getMetricKey(),value:a!==null?String(a):"0"};return this.conversationId!==null&&(c.conversation_id=this.conversationId),this.errorCode!==null&&(c.error_code=this.errorCode),this.errorDescription!==null&&(c.error_description=this.errorDescription),Object.keys(l).length>0&&(c.extra=l),c}}class ja{constructor(t){S(this,"commitCallback");S(this,"presentMethod","direct_present");S(this,"stats",null);this.commitCallback=t}getOrCreateStats(){return(!this.stats||this.stats.isCommitted())&&(this.stats=new Ka().setCommitCallback(this.commitCallback).setPresentMethod(this.presentMethod)),this.stats}onAuthStart(){this.getOrCreateStats().startTimer(Ce.TOTAL_DURATION).startTimer(Ce.TOTAL_DURATION_FROM_CACHE).startTimer(Ce.AUTH)}onAuthComplete(){var t;(t=this.stats)==null||t.stopTimer(Ce.AUTH)}onAuthError(t){this.stats&&!this.stats.isCommitted()&&this.stats.stopTimer(Ce.AUTH).setError(t instanceof ue.SendbirdError?t.code:void 0,t.message).stopTimer(Ce.TOTAL_DURATION).commit()}onGetChannelStart(){var t;(t=this.stats)==null||t.startTimer(Ce.GET_CHANNEL)}onGetChannelComplete(t){this.stats&&(this.stats.stopTimer(Ce.GET_CHANNEL),t!==void 0&&this.stats.setConversationId(t),this.stats.startTimer(Ce.GET_MESSAGES))}onGetChannelError(t){this.stats&&!this.stats.isCommitted()&&this.stats.stopTimer(Ce.GET_CHANNEL).setError(t instanceof ue.SendbirdError?t.code:void 0,t.message).stopTimer(Ce.TOTAL_DURATION).commit()}onCacheResult(t){this.stats&&!this.stats.isCommitted()&&(t&&this.stats.setError(t instanceof ue.SendbirdError?t.code:void 0,t.message),this.stats.stopTimer(Ce.TOTAL_DURATION_FROM_CACHE))}onApiResult(t){this.stats&&!this.stats.isCommitted()&&(t&&this.stats.setError(t instanceof ue.SendbirdError?t.code:void 0,t.message),this.stats.stopTimer(Ce.TOTAL_DURATION).stopTimer(Ce.GET_MESSAGES).commit())}setChannelUrl(t){var n;(n=this.stats)==null||n.setChannelUrl(t)}cleanup(){var t;(t=this.stats)==null||t.commit()}setPresentMethod(t){var n;this.presentMethod=t,(n=this.stats)==null||n.setPresentMethod(t)}clear(){this.stats=null}}function Xa(){let e=null,t=0;const n=(r,o)=>{if((e==null?void 0:e.key)===r)return e.promise;const s=++t,l=(e?e.promise.catch(()=>{}).then(()=>o()):o()).finally(()=>{(e==null?void 0:e.id)===s&&(e=null)});return e={key:r,id:s,promise:l},l};return n.isPending=()=>e!==null,n}const vs=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0)),zr={isTalkToAgentViewEnabled:!0,scrollMode:"auto",newMessageIndicatorEnabled:!0,senderAvatarEnabled:!0},ir={conversation:{...zr,messageAlertSoundEnabled:!1,list:{...zr,deferredMarkdownElements:[]},header:{avatarEnabled:!0},input:{camera:{photoEnabled:!0},gallery:{photoEnabled:!0},fileEnabled:!0},fileViewer:{downloadEnabled:!0}},launcher:{unreadBadgeEnabled:!1}},Vr=e=>e?{conversation:Qa(e.conversation),launcher:Za(e.launcher)}:ir,Za=e=>ut(ir.launcher,e),Ja=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},Qa=e=>{const t=ir.conversation;if(!e)return t;const{list:n={},header:r={},input:o,fileViewer:s={},messageAlertSoundEnabled:a=t.messageAlertSoundEnabled,...l}=e,{camera:c={},gallery:d={},fileEnabled:m=t.input.fileEnabled}=o??{},f={...ut(t.list,l,n),deferredMarkdownElements:Ja(n)};return{...f,messageAlertSoundEnabled:a,list:f,header:ut(t.header,r),input:{camera:ut(t.input.camera,c),gallery:ut(t.input.gallery,d),fileEnabled:m},fileViewer:ut(t.fileViewer,s)}},ut=(e,...t)=>{const n={...e};for(const r of t)r&&Object.assign(n,vs(r));return n},el=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}),tl=e=>({type:e.image_type||"default_icon",imageUrl:e.image_url}),Vn=e=>({enabled:e.enabled,showIndicator:e.show_indicator,toggleAllowed:e.toggle_allowed,deleteOnOff:e.delete_on_off,consentDialog:e.consent_dialog}),ys=(e,t)=>{if(e)return e.members.filter(n=>n.userId!==t).sort((n,r)=>r.joinedAt-n.joinedAt)[0]},Ne=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===Ee.ConversationStatus.CLOSED||e!=null&&e.isDesk&&((n=e==null?void 0:e.helpdeskInfo)==null?void 0:n.ticketStatus)==="closed")},ar=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===Ee.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,o;return typeof(((n=e==null?void 0:e.conversation)==null?void 0:n.handedOverAt)??((o=(r=e==null?void 0:e.conversation)==null?void 0:r.handoff)==null?void 0:o.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 Ss(e){return!!e&&e<=Date.now()}function ol(e){return!e.title}function sl(e,t){var n;if(e)return ol(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 il{constructor(){S(this,"_channelHandlerId",null);S(this,"_connectionHandlerId",null);S(this,"_handleActiveChannelChangedThrottled",null);S(this,"_setupChannelHandler",()=>{const t=Date.now();this._channelHandlerId=`aiagent_channel_${t}`,this._connectionHandlerId=`aiagent_connection_${t}`,this._handleActiveChannelChangedThrottled=ps(o=>{var s,a;(a=this._session)==null||a._updateActiveChannel({url:o.url,status:Ne(o)?"closed":"open",conversationStatus:(s=o.conversation)==null?void 0:s.status}),this._logger.debug("AIAgentEventManager: activeChannel updated",o.url)},250,{leading:!0,trailing:!1});const n=new Ye.GroupChannelHandler({onChannelChanged:o=>{var s,a;o.isGroupChannel()&&o.url===((s=this._session)==null?void 0:s.activeChannel.url)&&((a=this._handleActiveChannelChangedThrottled)==null||a.call(this,o))}}),r=new ue.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})});S(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")});S(this,"_syncActiveChannelOnReconnect",async()=>{var n,r,o;const t=(n=this._session)==null?void 0:n.activeChannel.url;if(t)try{const a=await(await this._chatClient.chatSDK.groupChannel.getChannel(t)).refresh();a.url===t&&((o=this._session)==null||o._updateActiveChannel({url:a.url,status:Ne(a)?"closed":"open",conversationStatus:(r=a.conversation)==null?void 0:r.status}),this._logger.debug("AIAgentEventManager: activeChannel synced on reconnect",a.url))}catch(s){this._logger.error("AIAgentEventManager: failed to sync activeChannel on reconnect",s)}});S(this,"_initConversationIfNeeded",async t=>{if(t.isAIAgent&&!t.conversation)try{await t.initConversation({aiAgentId:this.aiAgentId})}catch(n){this._logger.warn("AIAgentEventManager: initConversation failed",n)}});S(this,"onMessengerSettingsUpdated",t=>(this._dispatcher.subscribe(Be.MessengerSettingsUpdated,t),()=>{this._dispatcher.unsubscribe(Be.MessengerSettingsUpdated,t)}));S(this,"onActiveChannelUpdated",t=>(this._dispatcher.subscribe(Be.ActiveChannelUpdated,t),()=>{this._dispatcher.unsubscribe(Be.ActiveChannelUpdated,t)}));S(this,"onAuthTokenRefreshed",t=>(this._dispatcher.subscribe(Be.AuthTokenRefreshed,t),()=>{this._dispatcher.unsubscribe(Be.AuthTokenRefreshed,t)}))}}class al{constructor(t){S(this,"_sdkUser");S(this,"_userSession");S(this,"_dispatcher");S(this,"_activeChannel");S(this,"_updateActiveChannel",t=>{this._activeChannel=t,this._dispatcher.send(Qe.ActiveChannelUpdated({channelUrl:t.url,status:t.status,conversationStatus:t.conversationStatus}))});S(this,"_updateAuthToken",t=>{this._userSession.authToken=t,this._dispatcher.send(Qe.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 As=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)}},xs=e=>JSON.parse(e),ll=e=>JSON.parse(e);function cl(e,t){const[n,r]=t.split(",").map(o=>o.trim());return e==="dark"&&r||n}function ul(e){const t={};function n(r,o=""){for(const[s,a]of Object.entries(r)){const l=o?`${o}.${s}`:s;a&&typeof a=="object"&&!Array.isArray(a)?n(a,l):t[l]=a}}return n(e),t}function dl({template:e,variables:t,variableKeyPattern:n,variableValueTransformer:r}){return Object.entries(t).reduce((o,[s,a])=>{if(!r&&!["number","boolean","string"].includes(typeof a))throw new Error(`If transformer is not provided, value(${s}:${a}) must be a {string, number, or boolean}`);const l=r?r(a):String(a),c=n(s);return o.replace(c,As(l))},e)}async function ml({template:e,variables:t,variableKeyPattern:n,variableValueTransformer:r}){return(await Promise.all(Object.entries(t).map(async([s,a])=>{const l=await r(a);return{regex:n(s),transformedValue:l}}))).reduce((s,{regex:a,transformedValue:l})=>s.replace(a,As(l)),e)}var Yn=(e=>(e[e.EXTERNAL_AUTH_TOKEN_EXPIRED=1]="EXTERNAL_AUTH_TOKEN_EXPIRED",e))(Yn||{});const Ts=e=>typeof e=="object"&&e!==null,Yr=(e,t)=>t in e&&typeof e[t]=="string"&&e[t]!=="",fl=e=>!Ts(e)||!Yr(e,"channel_url")||!Yr(e,"ai_agent_id")?null:{channelUrl:e.channel_url,aiAgentId:e.ai_agent_id},gl={1:fl};function hl(e){if(!Ts(e)||!("cat"in e)||typeof e.cat!="number"||!("data"in e))return null;const t=e.cat,n=gl[t];if(!n)return null;const r=n(e.data);return r?{category:t,data:r}:null}function pl(e,t,n,r){const o=ya.default.init({appId:e,modules:[new Ye.GroupChannelModule,new Ee.AIAgentModule],localCacheEnabled:!0,options:new ue.SendbirdChatOptions({typingIndicatorInvalidateTime:2e4}),...r});return o.addSendbirdExtensions([{version:n,product:ue.SendbirdProduct.AI_AGENT,platform:t.platform}],{platform:t.deviceOSPlatform,version:t.deviceOSVersion},t.customData)||console.warn("Invalid Sendbird Extensions",t),o}function _l(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 El=[400300,400301,400302,400310];class lr{constructor(t,n,r){S(this,"chatSDK");S(this,"_logger");S(this,"_cache");S(this,"connect",async(t,n,r,o)=>{if(this._logger.debug("ChatClient.connect: start",t.userId),n){const s=new ue.SessionHandler({...n,onSessionTokenRequired:this._interceptTokenRefresh(n.onSessionTokenRequired,r,o)});this.chatSDK.setSessionHandler(s),this.chatSDK.aiAgent.addEventHandler(Yn.EXTERNAL_AUTH_TOKEN_EXPIRED.toString(),a=>{var c;this._logger.debug("ChatClient.connect: EXTERNAL_AUTH_TOKEN_EXPIRED event received",a);const l=hl(a);(l==null?void 0:l.category)===Yn.EXTERNAL_AUTH_TOKEN_EXPIRED&&(this._logger.debug("ChatClient.connect: calling onExternalAuthTokenExpired handler",l.data),(c=n==null?void 0:n.onExternalAuthTokenExpired)==null||c.call(n,l.data))})}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(s){const a=s;if(this.chatSDK.isCacheEnabled){if(this._isCacheRestrictedError(a))this._logger.warn("ChatClient.connect","offline connect restricted",a.message,a.code),this._logger.warn("ChatClient.connect","clear cached-data"),await this.chatSDK.clearCachedData().catch(l=>this._logger.warn("ChatClient.connect","clear cached-data failure",l));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",a.message,a.code),a}});S(this,"disconnect",async()=>{this._logger.debug("ChatClient.disconnect: start"),this.chatSDK.aiAgent.removeAllEventHandlers(),await this.chatSDK.disconnect(),this._cache.template.clear(),this._logger.debug("ChatClient.disconnect: end")});S(this,"getChannel",async t=>this.chatSDK.groupChannel.getChannel(t));S(this,"patchContext",async(t,n,r)=>this.chatSDK.aiAgent.patchContext(t,n,r));S(this,"updateContext",async(t,n,r)=>this.chatSDK.aiAgent.updateContext(t,n,r));S(this,"requestMessengerSettings",async t=>{var o;if(t.userId===""){const s=new Error("userId cannot be empty string for messenger settings request");throw this._logger.error("ChatClient.requestMessengerSettings: invalid userId",s),s}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",(o=r.active_channel)==null?void 0:o.channel_url),r});S(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});S(this,"clearUserMemories",async(t={})=>{this._logger.debug("ChatClient.clearUserMemories: requesting",t),await this.chatSDK.aiAgent.clearUserMemories(t),this._logger.debug("ChatClient.clearUserMemories: completed")});S(this,"_interceptTokenRefresh",(t,n,r)=>{if(t)return async(o,s)=>{new Promise((a,l)=>t==null?void 0:t(a,l)).then(a=>{a?n==null||n(a):r==null||r(),o(a)}).catch(a=>{r==null||r(),s(a)})}});S(this,"_isCacheRestrictedError",t=>El.some(n=>t.code===n));S(this,"_syncTemplatesIfNeeded",async()=>{var r,o;const t=(o=(r=this.chatSDK.appInfo)==null?void 0:r.aiAgentInfo)==null?void 0:o.templateListToken;if(!t)return;const n=this._cache.template.getCachedToken();if(!(n&&n===t)){this._logger.debug("ChatClient._syncTemplatesIfNeeded: syncing templates");try{const{templates:s,token:a}=await this.chatSDK.aiAgent.getMessageTemplates({limit:20});for(const{template:l}of s){const{key:c}=xs(l);this._cache.template.set(c,l)}this._cache.template.setCachedToken(a),this._logger.debug("ChatClient._syncTemplatesIfNeeded: sync completed")}catch(s){this._logger.error("ChatClient._syncTemplatesIfNeeded: error",s)}}});this.chatSDK=t,this._logger=n,this._cache=r}static init(t){let n;return t.chatSDK?(_l(t.chatSDK),n=t.chatSDK):n=pl(t.appId,t.extensions,t.messengerVersion,t.chatParams),new lr(n,t.logger,t.cache)}}const Ht=new Map,Is={set:(e,t)=>{Ht.set(e,t)},get:e=>{if(Ht.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=Ht.get(e);if(!n)throw new Error(`AIAgent platform "${e}" is not configured.`);return{platform:e,...n}}const t=Ht.entries().next().value;return{platform:t[0],...t[1]}}};class Wr extends Error{constructor(n,r){const o=(r==null?void 0:r.detail)??"";super(o||`Desk API error (${n})`);S(this,"status");S(this,"code");S(this,"detail");this.name="DeskApiError",this.status=n,this.code=(r==null?void 0:r.code)??"",this.detail=o}}var cr=(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))(cr||{}),ur=(e=>(e.URGENT="URGENT",e.HIGH="HIGH",e.MEDIUM="MEDIUM",e.LOW="LOW",e))(ur||{}),ws=(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))(ws||{});const bl=e=>e==="desk401103"||e==="desk401106"||e==="desk401107"||e==="desk401108"||e==="desk401109";class Cl{constructor(t){S(this,"_appId");S(this,"_apiHost");S(this,"_logger");S(this,"_credential",null);S(this,"_authRefreshPromise",null);S(this,"_onDeskTokenRefreshRequired",async()=>!1);S(this,"request",async(t,n)=>{const r=n.authRequired??!0,o=`${this._apiHost}${t}`;r&&this._authRefreshPromise&&(this._logger.debug("DeskApiClient: waiting for in-flight recovery..."),await this._authRefreshPromise);const s=await this._fetch(o,n);return r&&s.status===401?this._handleUnauthorized(s,o,n):this._toResult(s)});S(this,"setCredential",(t,n=async()=>!1)=>{this._authRefreshPromise=null,this._onDeskTokenRefreshRequired=n,this._credential=t});S(this,"clearCredential",()=>{this._authRefreshPromise=null,this._credential=null,this._onDeskTokenRefreshRequired=async()=>!1});S(this,"_handleUnauthorized",async(t,n,r)=>{const o=await this._parseErrorCode(t);if(!bl(o))return this._toResult(t);if(!await this._refresh(o)||this._credential===null)return this._toResult(t);const a=await this._fetch(n,r);return this._toResult(a)});S(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}});S(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))}:{}}));S(this,"_buildParams",t=>new URLSearchParams({sendbirdAppId:this._appId,...t}));S(this,"_buildBody",t=>({sendbirdAppId:this._appId,...t}));S(this,"_buildHeaders",(t,n)=>({"content-type":"application/json",...t&&this._credential?{sendbirdDeskToken:this._credential.deskToken}:{},...n}));S(this,"_toResult",async t=>{if(!t.ok){const r=await t.json().catch(()=>({}));throw new Wr(t.status,r)}const n=await t.text();if(n)try{return JSON.parse(n)}catch{throw new Wr(t.status,{})}});S(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}.sendbird.com/sapi`,this._logger=t.logger}get credential(){return this._credential}}class nn{constructor(t,n){S(this,"id");S(this,"title");S(this,"status");S(this,"agent");S(this,"priority");S(this,"group");S(this,"firstResponseTime");S(this,"issuedAt");S(this,"customFields");S(this,"_client");S(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 nn({id:t.id,title:t.channelName??null,status:t.status2??cr.INITIALIZED,agent:(()=>{var s;const o=(s=t.recentAssignment)==null?void 0:s.agent;return o?{userId:o.sendbirdId??"",name:o.displayName??"",profileUrl:o.photoThumbnailUrl??""}:null})(),priority:t.priority??ur.MEDIUM,group:t.group??0,firstResponseTime:t.firstResponseTime??-1,issuedAt:t.issuedAt??null,customFields:Object.fromEntries(((r=t.customFields)==null?void 0:r.map(o=>[o.key,o.value]))??[])},n)}}class dr{constructor(t){S(this,"_logger");S(this,"_apiClient");S(this,"_onDeskTokenRefreshRequired");S(this,"refreshDeskAuthToken",async t=>this._apiClient.credential?this.authenticate({userId:this._apiClient.credential.userId,accessToken:t,onDeskTokenRefreshRequired:this._onDeskTokenRefreshRequired}):!1);S(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}});S(this,"deauthenticate",()=>{this._apiClient.clearCredential(),this._onDeskTokenRefreshRequired=void 0,this._logger.debug("DeskClient.deauthenticate: token cleared")});S(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")});S(this,"getTicket",async t=>{this._assertAuthenticated(this._apiClient);const n=await this._apiClient.request(`/tickets/${encodeURIComponent(t)}/`,{method:"GET"});return nn._fromResponse(n,this)});S(this,"createTicket",async t=>{this._assertAuthenticated(this._apiClient);const n=await this._apiClient.request("/tickets/",{method:"POST",body:vs({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 nn._fromResponse(n,this)});this._logger=t.logger,this._apiClient=new Cl(t)}static init(t){return new dr(t)}_assertAuthenticated(t){if(t.credential==null)throw new Error("DeskClient is not authenticated")}}class mr{constructor(){S(this,"authenticate",async t=>!1);S(this,"deauthenticate",()=>{});S(this,"refreshDeskAuthToken",async()=>!1);S(this,"setCustomerLanguage",async()=>{});S(this,"getTicket",async()=>{throw new Error("DeskClient is disabled via __SBA_USE_DESK_CLIENT__")})}static init(){return new mr}}function vl(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 yl=1440*60*1e3,Sl=typeof __SBA_USE_DESK_CLIENT__>"u"||__SBA_USE_DESK_CLIENT__;function je(e){if(!e)throw new Error("Not authenticated. Call authenticate() first.")}function Al(e,t){return Object.entries(t).every(([n,r])=>e[n]===r)}class rn extends il{constructor(n){super();S(this,"appId");S(this,"aiAgentId");S(this,"_chatClient");S(this,"_deskClient");S(this,"_cache");S(this,"_logger");S(this,"_dispatcher");S(this,"_session",null);S(this,"language");S(this,"countryCode");S(this,"context");S(this,"queryParams");S(this,"_config");S(this,"_networkStateAdapter");S(this,"_forceCreateChannel");S(this,"_agentVersion");S(this,"_statsTrackers");S(this,"_operationQueue",Xa());S(this,"dispose",()=>{this._operationQueue.isPending()||(this._logger.debug("AIAgent.dispose: start"),this._chatClient.chatSDK.connectionState==="OPEN"&&this._chatClient.chatSDK.disconnectWebSocket(),this._removeChannelHandler(),this._session=null,this._deskClient.deauthenticate(),this._statsTrackers.initialRender.clear(),this._logger.debug("AIAgent.dispose: end"))});S(this,"initConversationIfNeeded",n=>this._initConversationIfNeeded(n));S(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 a,l,c,d,m;this._logger.debug("AIAgent.authenticate: start"),this._statsTrackers.initialRender.onAuthStart();const o=this._getSessionCandidate(n),s=(a=o.userSessionCandidate)!=null&&a.userId?this._cache.messenger.getSettings(o.userSessionCandidate.userId):null;s!=null&&s.bot&&this._dispatcher.send(Qe.MessengerSettingsUpdated({settings:s,source:"cache"}));try{const f=await this._chatClient.requestMessengerSettings({aiAgentId:this.aiAgentId,userId:(l=o.userSessionCandidate)==null?void 0:l.userId,language:this.language,country:this.countryCode,context:this.context,knownActiveChannelUrl:(c=s==null?void 0:s.active_channel)==null?void 0:c.channel_url,forceCreateChannel:this._forceCreateChannel,agentVersion:this._agentVersion});let g;if(f.auto_created_user)if(o.type==="manual")this._logger.warn("Received auto created user info but current session is manual. Ignoring auto created user info."),g={userId:o.userSessionCandidate.userId,authToken:o.userSessionCandidate.authToken};else{const{user_id:v,session_token:b,expire_at:_}=f.auto_created_user;this._cache.messenger.setAnonUser({userId:v,authToken:b,expireAt:_}),g={userId:v,authToken:b},this._logger.debug("AIAgent.authenticate: anonymous user created",v)}else g={userId:((d=o.userSessionCandidate)==null?void 0:d.userId)??"",authToken:((m=o.userSessionCandidate)==null?void 0:m.authToken)??""};this._cache.messenger.setSettings(g.userId,f),this._dispatcher.send(Qe.MessengerSettingsUpdated({settings:f,source:"server"}));const E=(()=>{var v;return o.type==="anonymous"?za(this._dispatcher):(v=o.userSessionCandidate)==null?void 0:v.sessionHandler})(),y=await this._chatClient.connect(g,E,v=>{var b;this._logger.debug("AIAgent: session token refreshed"),(b=this._session)==null||b._updateAuthToken(v),this._deskClient.refreshDeskAuthToken(v)},()=>{this._logger.debug("AIAgent: session token unavailable, deauthenticating desk"),this._deskClient.deauthenticate()});return await this._deskClient.authenticate({userId:g.userId,accessToken:g.authToken,onDeskTokenRefreshRequired:async({reason:v})=>{var b;if(v===ws.ERR_SESSION_KEY_EXPIRED){await new Promise(C=>setTimeout(C,2e3));const _=(b=this._session)==null?void 0:b.userSession.authToken;return _?await this._deskClient.refreshDeskAuthToken(_):!1}return!1}}),(s==null?void 0:s.language)!==f.language&&this._deskClient.setCustomerLanguage(this.language).catch(()=>{}),this._statsTrackers.initialRender.onAuthComplete(),this._session=new al({sdkUser:y,userSession:g,activeChannel:{url:f.active_channel.channel_url,status:"open"},dispatcher:this._dispatcher}),this._setupChannelHandler(),this._logger.debug("AIAgent.authenticate: end",{userId:g.userId}),f}catch(f){throw this._statsTrackers.initialRender.onAuthError(f),f}})});S(this,"deauthenticate",()=>this._operationQueue("deauth",async()=>{var n;this._logger.debug("AIAgent.deauthenticate: start"),await this._chatClient.disconnect(),this._deskClient.deauthenticate(),this._cache.messenger.clear((n=this._session)==null?void 0:n.userSession.userId),this._session=null,this._removeChannelHandler(),this._statsTrackers.initialRender.clear(),this._logger.debug("AIAgent.deauthenticate: end")}));S(this,"createConversation",async n=>{je(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}),o=r.active_channel.channel_url;return this._cache.messenger.setSettings(this._session.userSession.userId,r),this._logger.debug("AIAgent.createConversation: end",o),o});S(this,"searchConversation",async n=>{if(je(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:Ee.ConversationStatus.OPEN,limit:100}),o=[];for(;r.hasNext;){const s=await r.next();for(const a of s)Al(a.context??{},n.context)&&o.push(a.channelInfo.url)}return this._logger.debug("AIAgent.searchConversation: end",{count:o.length}),o});S(this,"closeConversation",async n=>{var o;je(this._session),this._logger.debug("AIAgent.closeConversation: start",n);const r=await this._chatClient.getChannel(n);((o=r.conversation)==null?void 0:o.status)===Ee.ConversationStatus.OPEN?(await r.closeConversation(),this._session.activeChannel.url===n&&this._session._updateActiveChannel({url:n,status:"closed",conversationStatus:Ee.ConversationStatus.CLOSED}),this._logger.debug("AIAgent.closeConversation: end")):this._logger.debug("AIAgent.closeConversation: already closed or not an AI agent conversation")});S(this,"createConversationListCollection",n=>new _s(this.chatSDK,n??{}));S(this,"patchContext",async(n,r)=>{je(this._session),this._logger.debug("AIAgent.patchContext: start",{channelUrl:n,context:r});const o=await this._chatClient.patchContext(this.aiAgentId,n,r);return this._logger.debug("AIAgent.patchContext: end",o),{...o,context:o.context??{}}});S(this,"updateContext",async(n,r)=>{je(this._session),this._logger.debug("AIAgent.updateContext: start",{channelUrl:n,context:r});const o=await this._chatClient.updateContext(this.aiAgentId,n,r);return this._logger.debug("AIAgent.updateContext: end",o),{...o,context:o.context??{}}});S(this,"getContextObject",async n=>{je(this._session),this._logger.debug("AIAgent.getContextObject: start",n);const o=await(await this._chatClient.getChannel(n)).getContextObject(this.aiAgentId);return this._logger.debug("AIAgent.getContextObject: end",o),{...o,context:o.context??{}}});S(this,"clearUserMemories",async(n={})=>{je(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")});S(this,"setUserMemoryState",async n=>{je(this._session);const r=this._session;this._logger.debug("AIAgent.setUserMemoryState: start",n.enabled);const o={...n,contextAiAgentId:n.contextAiAgentId??this.aiAgentId},s=r.userSession.userId,a=await this._chatClient.setUserMemoryState(o);if(this._session!==r)return this._logger.debug("AIAgent.setUserMemoryState: session changed during request, discarding stale result"),Vn(a);const l=this._cache.messenger.getSettings(s);if(l){const c={...l,memory:a};this._cache.messenger.setSettings(s,c),this._dispatcher.send(Qe.MessengerSettingsUpdated({settings:c,source:"cache"}))}return this._logger.debug("AIAgent.setUserMemoryState: end",a.enabled),Vn(a)});S(this,"refreshActiveChannel",async n=>{var l,c,d;je(this._session);const r=this._session,o=(n==null?void 0:n.useKnownActiveChannelUrl)??!0;this._logger.debug("AIAgent.refreshActiveChannel: start",{useKnownActiveChannelUrl:o});const s=await this._chatClient.requestMessengerSettings({aiAgentId:this.aiAgentId,userId:r.userSession.userId,language:this.language,country:this.countryCode,context:this.context,knownActiveChannelUrl:o?(c=(l=this._cache.messenger.getSettings(r.userSession.userId))==null?void 0:l.active_channel)==null?void 0:c.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)??s.active_channel.channel_url;const a=s.active_channel.channel_url;return this._cache.messenger.setSettings(this._session.userSession.userId,s),this._session._updateActiveChannel({url:a,status:"open"}),this._logger.debug("AIAgent.refreshActiveChannel: end",a),a});S(this,"_getSessionCandidate",n=>n instanceof Cs?{type:"manual",userSessionCandidate:this._getManualSessionInfo(n)}:n instanceof zn?{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});S(this,"_getAnonymousSessionInfo",()=>{const n=this._cache.messenger.getAnonUser();return n?n.expireAt-yl<=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});S(this,"_getManualSessionInfo",n=>{if(!n||n instanceof zn)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(o=>!(o 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=Vr(n.config),this.queryParams=n.queryParams,this._networkStateAdapter=n.networkStateAdapter,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={initialRender:new ja((r,o)=>this._chatClient.chatSDK.aiAgent.appendStat(r,o))}}static init(n){var f;const r=Is.get(n.platform),o=n.logger??new bs(n.logLevel??sr.WARN),s=n.dispatcher??new Es(o),a=n.useMMKVStorage?vl(n.useMMKVStorage):r.keyValueStorage,l=n.useMMKVStorage?{...n.chatParams,useMMKVStorageStore:n.useMMKVStorage}:n.chatParams,c=Na({appId:n.appId,aiAgentId:n.aiAgentId,storage:a}),d=lr.init({appId:n.appId,messengerVersion:r.messengerVersion,extensions:{platform:r.platform,deviceOSPlatform:r.deviceOSPlatform,deviceOSVersion:r.deviceOSVersion},chatParams:l,chatSDK:n.chatSDK,logger:o,cache:c}),m=Sl?dr.init({appId:n.appId,logger:o,customApiHost:(f=n.deskParams)==null?void 0:f.customApiHost}):mr.init();return o.debug("AIAgent.init: created",{appId:n.appId,aiAgentId:n.aiAgentId}),new rn({appId:n.appId,aiAgentId:n.aiAgentId,language:n.language,countryCode:n.countryCode,context:n.context,config:n.config,queryParams:n.queryParams,networkStateAdapter:r.networkStateAdapter,forceCreateChannel:n._forceCreateChannel,agentVersion:n._agentVersion,chatClient:d,deskClient:m,cache:c,logger:o,dispatcher:s})}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=Vr(n)}get agentVersion(){return this._agentVersion}set agentVersion(n){this._agentVersion=n}get networkStateAdapter(){return this._networkStateAdapter}get logger(){return this._logger}get dispatcher(){return this._dispatcher}get cache(){return this._cache}get statsTrackers(){return this._statsTrackers}}const pe=(e,t)=>{const n=u.createContext(t??null),r=({children:a,value:l})=>i.createElement(n.Provider,{value:l},typeof a=="function"?a(l):a),o=({children:a})=>i.createElement(n.Consumer,null,l=>l?typeof a=="function"?a(l):a:null),s=()=>{const a=u.useContext(n);if(!a)throw new Error(`use${e}Context must be used within a ${e}Provider`);return a};return n.displayName=`${e}Context`,r.displayName=`${e}Provider`,o.displayName=`${e}Consumer`,s.displayName=`use${e}Context`,{Context:n,Provider:r,Consumer:o,useContext:s}};function Ge(e){const t=u.createContext({Template:e.template,updateTemplate:()=>{},components:e.components,updateComponent:()=>{}});function n({children:s}){const[a,l]=u.useState(()=>e.template),[c,d]=u.useState(e.components),m={Template:a,updateTemplate:f=>l(()=>f),components:c,updateComponent:(f,g)=>d(E=>({...E,[f]:g}))};return i.createElement(t.Provider,{value:m},s)}function r({template:s,children:a}){const{updateTemplate:l}=u.useContext(t);return u.useLayoutEffect(()=>{s&&l(s)},[s]),i.createElement(i.Fragment,null,a)}function o({children:s}){return i.createElement(n,null,s)}return o.defaults=e,o.useContext=()=>u.useContext(t),o.Context=t,o.Template=r,Object.keys(e.components).forEach(s=>{o[s]=function({component:l}){const{updateComponent:c}=u.useContext(t);return u.useLayoutEffect(()=>{l&&c(s,l)},[l]),null}}),o}function xl(...e){return function({children:n}){return e.reduce((r,o)=>i.createElement(o,null,r),n)}}function Tl(e,t){const n=e.lastMessage;return n!=null&&n.isAdminMessage()?n.message??"":Ms(e,t)}function Ms(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 o=n.fileInfoList.length;return((r=t==null?void 0:t.formatMultipleFilesCount)==null?void 0:r.call(t,o))??`${o} photos`}return e.name}function Il(e,t,n){var a;const r=new Date,o=new Date(((a=e.lastMessage)==null?void 0:a.createdAt)||e.createdAt),s=Je.differenceInMinutes(r,o);return s<1?n.justNow:s<60?n.minutesAgo(s):Je.isToday(o)?n.hoursAgo(Je.differenceInHours(r,o)):t(o,n.dateShortFormat)}const wl=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},Gt=e=>Math.max(0,Math.min(255,e)).toString(16).padStart(2,"0"),qr=(e,t)=>{const n=Gt(Math.round(t*255));if(e.startsWith("#")){const o=e.slice(1);return o.length===3||o.length===4?`#${o[0]}${o[0]}${o[1]}${o[1]}${o[2]}${o[2]}${n}`:`#${o.slice(0,6)}${n}`}const r=wl(e);return r?`#${Gt(r[0])}${Gt(r[1])}${Gt(r[2])}${n}`:e},Ml=(e,t)=>{if(!t)return e;const n={...e};for(const[r,o]of Object.entries(t))o&&(n[r]=o);return n},kl=e=>e.consentDialog?"consent":e.toggleAllowed?e.enabled?"on":"off":"readonly",Rl=e=>e.length>0,Ll=e=>{const t=e[0];if(!t)return e;const n=e.some(o=>ze(o.type)),r=e.some(o=>!ze(o.type));return n&&r?ze(t.type)?e.filter(o=>ze(o.type)):[t]:r?[t]:e},Kr=e=>e.length===0?"empty":e.every(t=>ze(t.type))?"images":"non_images",Ol=({currentFiles:e,incomingFiles:t,maxAttachmentCount:n})=>{const r=Ll(t),o=Kr(e),s=Kr(r),l=o==="images"&&s==="images"?{type:"append",files:r,nextFiles:[...e,...r]}:{type:"replace",files:r,nextFiles:r};return l.nextFiles.length>n?{type:"reject",reason:"count_limit",maxAttachmentCount:n,nextFileCount:l.nextFiles.length}:l.type==="replace"&&o!=="empty"&&o!==s?{type:"confirm_replace",action:l}:{type:"apply",action:l}},mt=3,ks=6,Nl=e=>e%mt===0?mt:ks,Dl=({index:e,itemCount:t})=>{const n=t%mt,r=n>0,o=r?t-n:t,s=r&&e>=o,a=s?n:mt,l=s?e-o:e%mt,c=!r&&e>=t-mt;return{columnSpan:r?ks/a:1,rowItemCount:a,isLastInRow:l===a-1,isLastRow:s||c}},Rs=pe("AIAgent"),$l=Rs.Provider,Re=Rs.useContext;function Pl(e){const t=Fl(e);return i.createElement($l,{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 Fl(e){const t=u.useRef(null),n=u.useRef(null);if(!t.current||!n.current)t.current=rn.init(e);else{const o=Ul(n.current,e);(o.appId||o.aiAgentId||o.chatSDK)&&(t.current.dispose(),t.current=rn.init({...e,chatParams:o.appId?{...e.chatParams,newInstance:!0}:e.chatParams}))}n.current=e,u.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}function Ul(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}}const jr=Symbol("conversationMessageEventBridge"),Ct=Symbol("conversationMessageEventPublisher"),Bl=(e,t)=>{const n=e;if(n[Ct]=t,n[jr])return e;n[jr]=!0;const r=e.setMessageCollectionHandler.bind(e);e.setMessageCollectionHandler=s=>{r({...s,onMessagesAdded:(a,l,c)=>{var d,m;(d=s.onMessagesAdded)==null||d.call(s,a,l,c),(m=n[Ct])==null||m.call(n,{kind:"messagesAdded",source:a.source,messages:c})},onMessagesUpdated:(a,l,c)=>{var d,m;(d=s.onMessagesUpdated)==null||d.call(s,a,l,c),(m=n[Ct])==null||m.call(n,{kind:"messagesUpdated",source:a.source,messages:c})}})};const o=e.initialize.bind(e);return e.initialize=s=>{const a=o(s),l=a.onCacheResult.bind(a),c=a.onApiResult.bind(a);return a.onCacheResult=d=>l((m,f)=>{var g;d(m,f),(g=n[Ct])==null||g.call(n,{kind:"initialized",source:"cache",messages:f??[]})}),a.onApiResult=d=>c((m,f)=>{var g;d(m,f),(g=n[Ct])==null||g.call(n,{kind:"initialized",source:"api",messages:f??[]})}),a},e},gn=()=>{const[,e]=u.useState(0);return u.useCallback(()=>e(t=>t+1),[])};let Hl=0;function Gl(){return u.useState(()=>`${Hl++}`)[0]}const ht=(e,t,n)=>{const r=u.useRef(t),s=Gl();r.current=t,u.useEffect(()=>{var l;const a=c=>{const d=c;return Object.keys(d).forEach(f=>{d[f]=(...g)=>{var y;const E=r.current;(y=E[f])==null||y.call(E,...g)}}),d};return(l=e==null?void 0:e.groupChannel)==null||l.addGroupChannelHandler(s,a(new Ye.GroupChannelHandler)),()=>{var c;(c=e==null?void 0:e.groupChannel)==null||c.removeGroupChannelHandler(s)}},[e==null?void 0:e.groupChannel,s])};function zl(e,t){return!e||!t?!0:e.url!==t.url}function Fe(e){return e!=null&&"sendingStatus"in e}function Vl(e,t="##__USER_ID_IS_NOT_PROVIDED__##"){var n;return Fe(e)?((n=e.sender)==null?void 0:n.userId)===t:!1}function Yl(e,t){return Vl(e,t)||e.isAdminMessage()?!1:e.updatedAt===0}function Xr(e){return"sendingStatus"in e?e.sendingStatus==="succeeded"?String(e.messageId):e.reqId:String(e.messageId)}const on={collection:{groupChannel:{defaultOrder:Ye.GroupChannelListOrder.LATEST_LAST_MESSAGE},message:{defaultLimit:{next:25,prev:25},searchLimit:{next:10,prev:10}}}};function Zr(e){return!e||!Array.isArray(e)?!1:e.length!==0}function Jr(e,t){return e.reduce((n,r)=>{const o=t(r);return n[o]=r,n},{})}const Wl=({...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=ql(t.value.messages);else{const n={...e.messageMap},r=[],o=[];t.value.messages.forEach(s=>{const a=Fe(s)?s.reqId:void 0,l=s.messageId||void 0;[a,l].forEach(c=>{if(!c)return;const d=n[c];Kl(d,s,t.value.strictStreamingOrder)&&(d&&r.push(d),s.parentMessageId>0&&(d!=null&&d.parentMessage)&&s.applyParentMessage(d.parentMessage),o.push(s))})}),r.forEach(s=>{Fe(s)&&delete n[s.reqId],delete n[s.messageId]}),o.forEach(s=>{Fe(s)&&(n[s.reqId]=s),s.messageId!==0&&(n[s.messageId]=s)}),e.messageMap=n}return e}case"update_new_messages":{const n=t.value.currentUserId,r=t.value.messages.filter(o=>Yl(o,n));return t.value.clearBeforeAction?e.newMessageMap=Jr(r,Xr):(r.map(s=>s.messageId).forEach(s=>delete e.newMessageMap[s]),e.newMessageMap={...e.newMessageMap,...Jr(r,Xr)}),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 o=e[n][r];o&&(Fe(o)&&delete e[n][o.reqId],delete e[n][o.messageId])}),t.value.reqIds.forEach(r=>{const o=e[n][r];o&&(Fe(o)&&delete e[n][o.reqId],delete e[n][o.messageId])}),e}}},ql=e=>e.reduce((t,n)=>(Fe(n)?(t[n.reqId]=n,n.sendingStatus===He.SendingStatus.SUCCEEDED&&(t[n.messageId]=n)):t[n.messageId]=n,t),{}),Kl=(e,t,n=!1)=>{var r,o;if(!Fe(e)||!Fe(t))return!0;if(n&&e&&eo(e)&&eo(t)){const s=((r=e.message)==null?void 0:r.length)||0,a=((o=t.message)==null?void 0:o.length)||0;if(s>a)return!1}return e.sendingStatus===He.SendingStatus.SUCCEEDED?t.sendingStatus===He.SendingStatus.SUCCEEDED:e.sendingStatus!==t.sendingStatus},jl=(e=Xl)=>{const[{initialized:t,loading:n,refreshing:r,messageMap:o,newMessageMap:s},a]=u.useReducer(Wl,{initialized:!1,loading:!0,refreshing:!1,messageMap:{},newMessageMap:{}}),l=(b,_,C,x)=>{a({type:"update_messages",value:{messages:b,clearBeforeAction:_,currentUserId:C,strictStreamingOrder:x}})},c=(b,_)=>{a({type:"delete_messages",value:{messageIds:b,reqIds:_}})},d=(b,_,C)=>{a({type:"update_new_messages",value:{messages:b,clearBeforeAction:_,currentUserId:C}})},m=(b,_)=>{a({type:"delete_new_messages",value:{messageIds:b,reqIds:_}})},f=b=>{a({type:"update_initialized",value:{status:b}})},g=b=>{a({type:"update_loading",value:{status:b}})},E=b=>{a({type:"update_refreshing",value:{status:b}})},y=Object.values(s),v=u.useMemo(()=>Array.from(new Set(Object.values(o))).sort(e),[o]);return{updateInitialized:f,updateLoading:g,updateRefreshing:E,updateMessages:l,deleteMessages:c,initialized:t,loading:n,refreshing:r,messages:v,newMessages:y,updateNewMessages:d,deleteNewMessages:m}},Qr=Math.floor(Number.MAX_SAFE_INTEGER/10);function Xl(e,t){let n=0,r=0;return Fe(e)&&e.sendingStatus!=="succeeded"&&(n=Qr),Fe(t)&&t.sendingStatus!=="succeeded"&&(r=Qr),e.createdAt+n-(t.createdAt+r)}function eo(e){try{const t=JSON.parse(e.data||"{}");return typeof t=="object"&&!!t.stream}catch{return!1}}function ye(e){const t=u.useRef(e);return t.current=e,u.useCallback((...n)=>t.current(...n),[t])}const Zl=(e,t,n)=>{var s;const r={prevResultLimit:t.prev,nextResultLimit:t.next,startingPoint:n==null?void 0:n.startingPoint,replyType:n==null?void 0:n.replyType},o=(s=n==null?void 0:n.collectionCreator)==null?void 0:s.call(n,r);return o||e.createMessageCollection({...r,filter:new Ye.MessageFilter(r)})};function to(e){return e<Date.now()?on.collection.message.searchLimit:on.collection.message.defaultLimit}const Jl=(e,t,n={})=>{var De,xe;const r=u.useRef(n);r.current=n;const o=u.useRef(t);o.current=t;const s=r.current.logger,a=r.current.startingPoint??Number.MAX_SAFE_INTEGER,l=to(a),c=r.current.strictStreamingOrder??!1,d=u.useRef({prev:!1,next:!1}),m=gn(),f=u.useRef({initialized:!1,apiInitialized:!1,instance:null}),{initialized:g,loading:E,refreshing:y,messages:v,newMessages:b,updateMessages:_,updateNewMessages:C,deleteNewMessages:x,deleteMessages:A,updateInitialized:w,updateLoading:M,updateRefreshing:k}=jl(n==null?void 0:n.sortComparator),R=ye(I=>{var L,N,K,G;if(!o.current||!o.current.url)return(L=s==null?void 0:s.error)==null?void 0:L.call(s,"[useGroupChannelMessages] channel is required");try{switch(I){case ue.CollectionEventSource.EVENT_MESSAGE_RECEIVED:case ue.CollectionEventSource.EVENT_MESSAGE_SENT_SUCCESS:case ue.CollectionEventSource.SYNC_MESSAGE_FILL:case void 0:(K=(N=r.current).markAsRead)==null||K.call(N,[o.current]);break}}catch(H){(G=s==null?void 0:s.warn)==null||G.call(s,"[useGroupChannelMessages/markAsReadBySource]",H)}}),O=ye((I,L)=>{var N,K,G,H,U;if(L.length>0)switch(I){case ue.CollectionEventSource.EVENT_MESSAGE_RECEIVED:case ue.CollectionEventSource.SYNC_MESSAGE_FILL:{(K=(N=r.current).shouldCountNewMessages)!=null&&K.call(N)&&C(L,!1,(G=e.currentUser)==null?void 0:G.userId),(U=(H=r.current).onMessagesReceived)==null||U.call(H,L);break}}}),z=ye(I=>{var L,N;(N=(L=r.current).onCollectionEvent)==null||N.call(L,I)}),Y=ye(async(I,L,N)=>new Promise((K,G)=>{var Pe;f.current.instance&&f.current.instance.dispose(),R(),C([],!0,(Pe=e.currentUser)==null?void 0:Pe.userId);const H=()=>{var me,te;const{pendingMessages:ne,failedMessages:fe}=f.current.instance??{};Zr(ne)&&_(ne,!1,(me=e.currentUser)==null?void 0:me.userId),Zr(fe)&&_(fe,!1,(te=e.currentUser)==null?void 0:te.userId)},U=Zl(I,N,{...r.current,startingPoint:L});f.current={apiInitialized:!1,initialized:!1,instance:U},U.setMessageCollectionHandler({onMessagesAdded:(ne,fe,me)=>{var te;R(ne.source),O(ne.source,me),_(me,!1,(te=e.currentUser)==null?void 0:te.userId,c),z({kind:"messagesAdded",source:ne.source,messages:me})},onMessagesUpdated:(ne,fe,me)=>{var te,ve,ge;R(ne.source),O(ne.source,me),_(me,!1,(te=e.currentUser)==null?void 0:te.userId,c),ne.source===ue.CollectionEventSource.EVENT_MESSAGE_UPDATED&&((ge=(ve=r.current).onMessagesUpdated)==null||ge.call(ve,me)),z({kind:"messagesUpdated",source:ne.source,messages:me})},onMessagesDeleted:(ne,fe,me,te)=>{const ve=te.map(j=>j.messageId),ge=te.filter(Fe).map(j=>j.reqId);A(ve,ge),x(ve,ge),z({kind:"messagesDeleted",source:ne.source,messages:te})},onChannelDeleted:(ne,fe)=>{var me,te;(te=(me=r.current).onChannelDeleted)==null||te.call(me,fe)},onChannelUpdated:(ne,fe)=>{var me,te;m(),(te=(me=r.current).onChannelUpdated)==null||te.call(me,fe,ne)},onHugeGapDetected:()=>{Y(I,Number.MAX_SAFE_INTEGER,on.collection.message.defaultLimit)}});let de=!1;U.initialize(Ye.MessageCollectionInitPolicy.CACHE_AND_REPLACE_BY_API).onCacheResult((ne,fe)=>{var me,te,ve,ge,j;(te=(me=r.current).onCacheResult)==null||te.call(me,ne,fe??[]),ne?(e.isCacheEnabled&&((ve=s==null?void 0:s.error)==null||ve.call(s,"[useGroupChannelMessages/onCacheResult]",ne)),de=!0):fe&&((ge=s==null?void 0:s.debug)==null||ge.call(s,"[useGroupChannelMessages/onCacheResult]","message length:",fe.length),_(U.succeededMessages,!0,(j=e.currentUser)==null?void 0:j.userId),H(),fe.length>0&&(f.current.initialized=!0,K())),z({kind:"initialized",source:"cache",messages:fe??[]})}).onApiResult((ne,fe)=>{var me,te,ve,ge,j,he,Te;(te=(me=r.current).onApiResult)==null||te.call(me,ne,fe??[]),f.current.initialized=!0,f.current.apiInitialized=!0,ne?((ve=s==null?void 0:s.warn)==null||ve.call(s,"[useGroupChannelMessages/onApiResult]",ne),de?G(ne):K()):fe&&((ge=s==null?void 0:s.debug)==null||ge.call(s,"[useGroupChannelMessages/onApiResult]","message length:",fe.length),_(U.succeededMessages,!0,(j=e.currentUser)==null?void 0:j.userId),r.current.startingPoint||(Te=(he=r.current).onMessagesReceived)==null||Te.call(he,fe),e.isCacheEnabled&&H(),K()),z({kind:"initialized",source:"api",messages:fe??[]})})}));ht(e,{onUserBanned(I,L){var N,K,G;I.isGroupChannel()&&!zl(I,o.current)&&(L.userId===((N=e.currentUser)==null?void 0:N.userId)?(G=(K=r.current).onCurrentUserBanned)==null||G.call(K):m())}}),u.useLayoutEffect(()=>{const I=setTimeout(async()=>{e.currentUser&&o.current&&(w(!1),M(!0),await Y(o.current,a,l),M(!1),w(!0))});return()=>clearTimeout(I)},[e,(De=e.currentUser)==null?void 0:De.userId,(xe=o.current)==null?void 0:xe.url,r.current.replyType]),u.useEffect(()=>()=>{f.current.instance&&f.current.instance.dispose()},[]);const P=ye(async()=>{e.currentUser&&o.current&&(k(!0),await Y(o.current,Number.MAX_SAFE_INTEGER,on.collection.message.defaultLimit),k(!1))}),V=ye(async()=>{var L;const I=f.current.instance;if(I!=null&&I.hasPrevious&&!d.current.prev)try{d.current.prev=!0;const N=await I.loadPrevious();_(N,!1,(L=e.currentUser)==null?void 0:L.userId)}catch{}finally{d.current.prev=!1}}),B=ye(()=>{const{initialized:I,instance:L}=f.current;return I&&L?L.hasPrevious:!1}),W=ye(async()=>{var L;const I=f.current.instance;if(I!=null&&I.hasNext&&!d.current.next)try{d.current.next=!0;const N=await I.loadNext();_(N,!1,(L=e.currentUser)==null?void 0:L.userId)}catch{}finally{d.current.next=!1}}),q=ye(()=>{const{initialized:I,apiInitialized:L,instance:N}=f.current;return L&&I&&N?N.hasNext:!1}),ie=ye((I,L)=>{var N;if(!o.current||!o.current.url)throw(N=s==null?void 0:s.error)==null||N.call(s,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((K,G)=>{o.current.sendUserMessage(I).onPending(H=>{var U;H.channelUrl===o.current.url&&_([H],!1,(U=e.currentUser)==null?void 0:U.userId),L==null||L(H)}).onSucceeded(H=>{var U;H.channelUrl===o.current.url&&_([H],!1,(U=e.currentUser)==null?void 0:U.userId),K(H)}).onFailed((H,U)=>{var de;U&&U.channelUrl===o.current.url&&_([U],!1,(de=e.currentUser)==null?void 0:de.userId),G(H)})})}),_e=ye((I,L)=>{var N;if(!o.current||!o.current.url)throw(N=s==null?void 0:s.error)==null||N.call(s,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((K,G)=>{o.current.sendFileMessage(I).onPending(H=>{var U;H.channelUrl===o.current.url&&_([H],!1,(U=e.currentUser)==null?void 0:U.userId),L==null||L(H)}).onSucceeded(H=>{var U;H.channelUrl===o.current.url&&_([H],!1,(U=e.currentUser)==null?void 0:U.userId),K(H)}).onFailed((H,U)=>{var de;U&&U.channelUrl===o.current.url&&_([U],!1,(de=e.currentUser)==null?void 0:de.userId),G(H)})})}),Le=ye(async(I,L)=>{var N;if(!o.current||!o.current.url)throw(N=s==null?void 0:s.error)==null||N.call(s,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise(K=>{const G=[];o.current.sendFileMessages(I).onPending(H=>{var U;H.channelUrl===o.current.url&&_([H],!1,(U=e.currentUser)==null?void 0:U.userId),L==null||L(H)}).onSucceeded(H=>{var U;H.isFileMessage()&&H.channelUrl===o.current.url&&(_([H],!1,(U=e.currentUser)==null?void 0:U.userId),G.push(H)),G.length===I.length&&K(G)}).onFailed((H,U)=>{var de;U&&U.channelUrl===o.current.url?(_([U],!1,(de=e.currentUser)==null?void 0:de.userId),G.push(U)):G.push(null),G.length===I.length&&K(G)})})}),J=ye((I,L)=>{var N;if(!o.current||!o.current.url)throw(N=s==null?void 0:s.error)==null||N.call(s,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((K,G)=>{o.current.sendMultipleFilesMessage(I).onPending(H=>{var U;H.channelUrl===o.current.url&&_([H],!1,(U=e.currentUser)==null?void 0:U.userId),L==null||L(H)}).onFileUploaded(()=>{m()}).onSucceeded(H=>{var U;H.channelUrl===o.current.url&&_([H],!1,(U=e.currentUser)==null?void 0:U.userId),K(H)}).onFailed((H,U)=>{var de;U&&U.channelUrl===o.current.url&&_([U],!1,(de=e.currentUser)==null?void 0:de.userId),G(H)})})}),T=ye(async(I,L)=>{var K,G;if(!o.current||!o.current.url)throw(K=s==null?void 0:s.error)==null||K.call(s,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");const N=await o.current.updateUserMessage(I,L);return N.channelUrl===o.current.url&&_([N],!1,(G=e.currentUser)==null?void 0:G.userId),N}),F=ye(async(I,L)=>{var K,G;if(!o.current||!o.current.url)throw(K=s==null?void 0:s.error)==null||K.call(s,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");const N=await o.current.updateFileMessage(I,L);return N.channelUrl===o.current.url&&_([N],!1,(G=e.currentUser)==null?void 0:G.userId),N}),Q=ye(async I=>{var L;if(!o.current||!o.current.url)throw(L=s==null?void 0:s.error)==null||L.call(s,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((N,K)=>{let G;I.isUserMessage()&&(G=o.current.resendMessage(I)),I.isFileMessage()&&(G=o.current.resendMessage(I)),I.isMultipleFilesMessage()&&(G=o.current.resendMessage(I)),G&&("onPending"in G&&G.onPending(H=>{var U;H.channelUrl===o.current.url&&_([H],!1,(U=e.currentUser)==null?void 0:U.userId)}),"onFileUploaded"in G&&G.onFileUploaded(()=>{m()}),"onSucceeded"in G&&G.onSucceeded(H=>{var U;H.channelUrl===o.current.url&&_([H],!1,(U=e.currentUser)==null?void 0:U.userId),N(H)}),"onFailed"in G&&G.onFailed((H,U)=>{var de;U&&U.channelUrl===o.current.url&&_([U],!1,(de=e.currentUser)==null?void 0:de.userId),K(H)}))})}),re=ye(async I=>{var L,N;if(!o.current||!o.current.url)throw(L=s==null?void 0:s.error)==null||L.call(s,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");if(I.sendingStatus==="succeeded")I.isUserMessage()&&await o.current.deleteMessage(I),I.isFileMessage()&&await o.current.deleteMessage(I),I.isMultipleFilesMessage()&&await o.current.deleteMessage(I);else try{await((N=f.current.instance)==null?void 0:N.removeFailedMessage(I.reqId))}finally{A([],[I.reqId])}}),le=ye(()=>{var I;C([],!0,(I=e.currentUser)==null?void 0:I.userId)}),Oe=ye(async I=>{var L;if(e.currentUser&&o.current){const N=to(I);M(!0),_([],!0,(L=e.currentUser)==null?void 0:L.userId),await Y(o.current,I,N),M(!1)}});return{initialized:g,loading:E,refreshing:y,messages:v,newMessages:b,resetNewMessages:le,refresh:P,loadPrevious:V,hasPrevious:B,loadNext:W,hasNext:q,sendUserMessage:ie,sendFileMessage:_e,sendFileMessages:Le,sendMultipleFilesMessage:J,updateUserMessage:T,updateFileMessage:F,resendMessage:Q,deleteMessage:re,resetWithStartingPoint:Oe,_dangerous_reducer_updateMessages:_,_dangerous_reducer_deleteMessages:A}},Ql=(e,t,n)=>{const r=u.useRef(0),o=u.useRef(new Set),s=u.useCallback(d=>{const m={id:r.current+=1,...d};o.current.forEach(f=>{f(m)})},[]),a=u.useCallback(d=>{var f;const m=((f=n==null?void 0:n.collectionCreator)==null?void 0:f.call(n,d))??(t==null?void 0:t.createMessageCollection({...d??{},filter:new Ye.MessageFilter(d)}));if(!m)throw new Error("Group channel is required to create a message collection");return Bl(m,s)},[t,n==null?void 0:n.collectionCreator,s]),l=Jl(e,t,{...n,collectionCreator:a,strictStreamingOrder:!0}),c=u.useCallback(d=>(o.current.add(d),()=>{o.current.delete(d)}),[]);return{...l,subscribeMessageEvents:c}},Mt={DEFAULT_PRIMARY:"#000000",DEFAULT_BOT_MSG_BG:"#ECECEC",WHITE:"#ffffff",BLACK:"#000000"};function Ls(e){return e.length===4?`#${[...e.slice(1)].map(t=>t+t).join("")}`:e}function ec(e){const t=Ls(e);return[parseInt(t.slice(1,3),16),parseInt(t.slice(3,5),16),parseInt(t.slice(5,7),16)]}function tc(e){return`#${e.map(t=>t.toString(16).padStart(2,"0")).join("")}`}function nc(e,t,n){e/=255,t/=255,n/=255;const r=Math.max(e,t,n),o=Math.min(e,t,n),s=r-o;let a=0,l=0;const c=(r+o)/2;return r!==o&&(l=c>.5?s/(2-r-o):s/(r+o)),r===e?a=(t-n)/s+(t<n?6:0):r===t?a=(n-e)/s+2:r===n&&(a=(e-t)/s+4),a/=6,[a,l,c]}function rc(e,t,n){let r,o,s;if(t===0)r=o=s=n;else{const a=function(m,f,g){return g<0&&(g+=1),g>1&&(g-=1),g<.16666666666666666?m+(f-m)*6*g:g<.5?f:g<.6666666666666666?m+(f-m)*(.6666666666666666-g)*6:m},l=n<.5?n*(1+t):n+t-n*t,c=2*n-l;r=a(c,l,e+1/3),o=a(c,l,e),s=a(c,l,e-1/3)}return[Math.round(r*255),Math.round(o*255),Math.round(s*255)]}function zt(e,t,n){const[r,o,s]=ec(e),[a,l,c]=nc(r,o,s),d=Math.max(0,Math.min(1,c*t)),m=Math.max(0,Math.min(1,l*n)),[f,g,E]=rc(a,m,d);return tc([Math.round(f),Math.round(g),Math.round(E)])}function oc(e,t="light"){return{extraDark:zt(e,.6,1.2),dark:zt(e,.85,1.1),main:e,light:zt(e,t==="dark"?1.1:1.5,t==="dark"?.95:.9),extraLight:zt(e,t==="dark"?1.2:1.75,t==="dark"?.9:.8)}}function Wn(e){const t=Ls(e),n=149,r=+`0x${t[1]}${t[2]}`,o=+`0x${t[3]}${t[4]}`,s=+`0x${t[5]}${t[6]}`;return r*.299+o*.587+s*.114>n?Mt.BLACK:Mt.WHITE}function sc(e,t,n,r,o){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:o,background:r},messageOutgoing:{text:n,background:t},csat:{background: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 ic=(e,t,n,r,o)=>({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:o,background:r},messageOutgoing:{text:n,background:t},csat:{background: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"}}),Vt={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)"}},wn={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 no(e){const t=ac(e),n=lc(e,t),r=uc(n,e.colors,e.selectedTheme),o=mc(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:o}}function ac({selectedTheme:e,palette:t,primary:n}){const r=t!=null&&t.primary?t.primary:n?n===Vt.primary.main?Vt.primary:oc(n,e):Vt.primary;return{...Vt,primary:r,...t}}function lc({selectedTheme:e,primaryContrast:t,botMessageBackground:n,botMessageBackgroundContrast:r},o){const s=o.primary.main,a=t??Wn(s),l=n??Mt.DEFAULT_BOT_MSG_BG,c=r??Wn(l);return(e==="light"?sc:ic)(o,s,a,l,c)}function cc(e,t,n){return typeof e=="string"?e:e[t]??n}function uc(e,t,n){var a;if(!t||Object.keys(t).length===0)return e;const r={...e},o=r,s=e;for(const l of Object.keys(t)){const c=t[l];if(c){o[l]={...o[l]};for(const[d,m]of Object.entries(c))if(m!==void 0){const f=((a=s[l])==null?void 0:a[d])??"";o[l][d]=cc(m,n,f)}}}return r}function dc(e,t,n){const r={...e};return n.forEach(o=>{const s=t[o];s!=null&&(r[o]=s)}),r}function mc({typography:e}){if(!e)return wn;const t={...wn};return Object.keys(e).forEach(n=>{const r=e[n];if(r&&typeof r=="object"){const o=wn[n],s=["fontSize","fontWeight","fontFamily","lineHeight"];t[n]=dc(o,r,s)}}),t}const{Provider:fc,useContext:fr}=pe("AIAgentTheme");function gc({logger:e,palette:t,typography:n,colors:r,appearance:o,children:s}){const a=u.useRef(null),[l,c]=u.useState(()=>no({selectedTheme:(o==null?void 0:o.theme)??"light",palette:t,typography:n,colors:r,primary:o==null?void 0:o.primaryColor,botMessageBackground:o==null?void 0:o.botMessageBackgroundColor})),d=u.useCallback((m,f)=>{f&&(a.current=f);const g=(o==null?void 0:o.theme)??m,E=a.current?a.current.themes[g]:null,y={primary:o==null?void 0:o.primaryColor,primaryContrast:void 0,botMessageBackground:o==null?void 0:o.botMessageBackgroundColor,botMessageBackgroundContrast:void 0};!y.primary&&(E!=null&&E.primary_color)&&(y.primary=E.primary_color,y.primaryContrast=E.primary_contrast_color),!y.botMessageBackground&&(E!=null&&E.bot_message_bg_color)&&(y.botMessageBackground=E.bot_message_bg_color,y.botMessageBackgroundContrast=E.bot_message_bg_contrast_color);const v=no({selectedTheme:g,palette:t,typography:n,colors:r,...y});c(v),e==null||e.info("theme.update:",g)},[o==null?void 0:o.theme,o==null?void 0:o.primaryColor,o==null?void 0:o.botMessageBackgroundColor,t,n,r,e]);return u.useEffect(()=>{(o!=null&&o.theme||o!=null&&o.primaryColor||o!=null&&o.botMessageBackgroundColor)&&d(l.selectedTheme)},[o==null?void 0:o.theme,o==null?void 0:o.primaryColor,o==null?void 0:o.botMessageBackgroundColor]),i.createElement(fc,{value:{theme:l,updateTheme:d}},s)}const Mn=25*1024*1024,ro=1,oo=new Set(["image/png","image/jpeg","image/jpg"]),so=new Set(["application/pdf"]),hc={off:"off",always:"always",handed_off_only:"handed_off_only"},pc=()=>{const[e,t]=u.useState(()=>({maxAttachmentCount:ro,attachmentMode:"handed_off_only",defaultUploadSizeLimit:Mn,uploadSizeLimitPerType:new Map,supportedImageMimeTypes:oo,supportedFileMimeTypes:so})),n=u.useCallback(({active_channel:o,upload_restriction:s})=>{t({maxAttachmentCount:(s==null?void 0:s.max_attachment_count)??ro,attachmentMode:hc[o.attachment_mode]??"handed_off_only",defaultUploadSizeLimit:(s==null?void 0:s.default_upload_size_limit)??Mn,uploadSizeLimitPerType:new Map(Object.entries((s==null?void 0:s.upload_size_limit_per_type)??[])),supportedImageMimeTypes:new Set((s==null?void 0:s.supported_image_mime_types)??oo),supportedFileMimeTypes:new Set((s==null?void 0:s.supported_file_mime_types)??so)})},[]),r=u.useCallback(o=>{const{channel:s,uploadSizeLimit:a=Mn}=o,l=(d=!0)=>s!=null&&s.isAIAgent?d?nt(s):!1:!0,c=d=>{if(l())return e.defaultUploadSizeLimit??a;const m=e.defaultUploadSizeLimit??a,f=e.uploadSizeLimitPerType.get(d)??m;return Math.min(m,f)};return{maxAttachmentCount:e.maxAttachmentCount,isEnabled:()=>{if(l(!1))return!0;switch(e.attachmentMode){case"off":return!1;case"always":return!0;case"handed_off_only":return nt(s);default:return!0}},get supportedMimeTypes(){return l()?[Hn]:[...e.supportedImageMimeTypes,...e.supportedFileMimeTypes]},isSupportedMimeType:d=>l()?!0:e.supportedImageMimeTypes.has(d)||e.supportedFileMimeTypes.has(d),getUploadSizeLimit:c,getUploadSizeLimitInMB:d=>c(d)/(1024*1024)}},[e]);return{updateBaseAttachmentRules:n,createAttachmentRules:r}},io=(...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)")},vt=e=>({...e,context:e.context??{}}),{Provider:_c,useContext:pt}=pe("AIAgentMessengerSession"),Ec=u.forwardRef(function({userSessionInfo:e,children:t},n){const{_aiAgentSDK:r,chatSDK:o,aiAgentId:s,logger:a}=Re(),{updateTheme:l}=fr(),[c,d]=u.useState(void 0),[m,f]=u.useState(void 0),[g,E]=u.useState(null),[y,v]=u.useState(null),[b,_]=u.useState(null),[C,x]=u.useState(null),[A,w]=u.useState(null),{updateBaseAttachmentRules:M,createAttachmentRules:k}=pc();u.useEffect(()=>{const Y=r.onMessengerSettingsUpdated(({settings:B})=>{const{appearance:W,bot:q,launcher:ie,memory:_e}=B;l(W.selected_theme,W),_(el(q)),x(tl(ie)),w(_e?Vn(_e):null),M(B)}),P=r.onActiveChannelUpdated(({channelUrl:B,status:W,conversationStatus:q})=>{f({url:B,status:W,conversationStatus:q})}),V=r.onAuthTokenRefreshed(()=>{var W;const B=(W=r.session)==null?void 0:W.userSession.authToken;B&&v(q=>q?{...q,authToken:B}:null)});return()=>{Y(),P(),V()}},[r,l,M]);const R=u.useCallback(async()=>{try{const Y=await r.authenticate(e),P=r.session;return E(P.sdkUser),v(P.userSession),f(P.activeChannel),d(void 0),Y}catch(Y){throw E(null),v(null),f(void 0),d(Y),Y}},[r,e]),O=u.useCallback(async()=>{await r.deauthenticate(),E(null),f(void 0),v(null),_(null),x(null),w(null)},[r]),z=u.useCallback(async()=>{if(!r.session){if(y)return a.debug("agentMessengerSession.refreshActiveChannel: stale call after deauthenticate, skipping"),"";throw a.error("agentMessengerSession.refreshActiveChannel: userSession is not ready"),new Error("userSession is not ready")}return r.session.userSession.userId!==(y==null?void 0:y.userId)?(a.debug("agentMessengerSession.refreshActiveChannel: stale call from previous session, skipping"),r.session.activeChannel.url):(f(void 0),await r.refreshActiveChannel())},[r,a,y]);return u.useImperativeHandle(n,()=>{const Y=async()=>{if(!m)throw new Error("No active conversation. Please start a conversation first.");return await o.groupChannel.getChannel(m.url)};return{activeChannel:m,chatSDK:o,authenticate:R,deauthenticate:O,updateContext:async(...P)=>{const V=io(...P);if(V.type==="active"){const q=await(await Y()).updateContext(s,V.context);return vt(q)}const B=await o.aiAgent.updateContext(V.aiAgentId,V.channelUrl,V.context);return vt(B)},patchContext:async(...P)=>{const V=io(...P);if(V.type==="active"){const q=await(await Y()).patchContext(s,V.context);return vt(q)}const B=await o.aiAgent.patchContext(V.aiAgentId,V.channelUrl,V.context);return vt(B)},getContextObject:async()=>{const V=await(await Y()).getContextObject(s);return vt(V)}}},[R,O,m,o,s,a]),i.createElement(_c,{value:{sdkUser:g,userSessionInfo:e,userSession:y,activeChannel:m,setActiveChannel:f,refreshActiveChannel:z,createConversation:r.createConversation,searchConversation:r.searchConversation,connectionError:c,aiAgentInfo:b,launcherInfo:C,memoryInfo:A,authenticate:R,deauthenticate:O,createAttachmentRules:k,statsTrackers:r.statsTrackers}},t)}),Ot=(e,t)=>{const n=u.useId(),r=u.useRef(t);u.useLayoutEffect(()=>{r.current=t}),u.useLayoutEffect(()=>{const o=new ue.ConnectionHandler({onDisconnected:s=>{var a,l;return(l=(a=r.current).onDisconnected)==null?void 0:l.call(a,s)},onConnected:s=>{var a,l;return(l=(a=r.current).onConnected)==null?void 0:l.call(a,s)},onReconnectStarted:()=>{var s,a;return(a=(s=r.current).onReconnectStarted)==null?void 0:a.call(s)},onReconnectSucceeded:()=>{var s,a;return(a=(s=r.current).onReconnectSucceeded)==null?void 0:a.call(s)},onReconnectFailed:()=>{var s,a;return(a=(s=r.current).onReconnectFailed)==null?void 0:a.call(s)},onConnectionLost:()=>{var s,a;return(a=(s=r.current).onConnectionLost)==null?void 0:a.call(s)},onConnectionDelayed:s=>{var a,l;return(l=(a=r.current).onConnectionDelayed)==null?void 0:l.call(a,s)}});return e.addConnectionHandler(n,o),()=>{e.removeConnectionHandler(n)}},[e,n])};function bc(e){const{chatSDK:t,logger:n,aiAgentId:r,_aiAgentSDK:o}=Re(),{sdkUser:s,statsTrackers:a}=pt(),l=gn(),[c,d]=u.useState(void 0),[m,f]=u.useState(void 0),[g,E]=u.useState(!1);function y(b){b.isAIAgent&&!b.conversation&&(E(!0),o.initConversationIfNeeded(b).finally(()=>E(!1)))}async function v(){var b,_,C;if(!s){n.debug("useChannel.getChannel: no sdk user, skip fetching channel");return}if(n.debug("useChannel.getChannel: start"),d(void 0),f(void 0),E(!1),e){a.initialRender.onGetChannelStart();try{n.debug("useChannel.getChannel: get channel",e);const x=await t.groupChannel.getChannel(e);y(x),d(x),a.initialRender.onGetChannelComplete((b=x.conversation)==null?void 0:b.id),x.url===((_=o.session)==null?void 0:_.activeChannel.url)&&o.session._updateActiveChannel({url:x.url,status:Ne(x)?"closed":"open",conversationStatus:(C=x.conversation)==null?void 0:C.status}),n.debug("useChannel.getChannel: fetched channel",x)}catch(x){a.initialRender.onGetChannelError(x),x instanceof ue.SendbirdError&&f(x),n.error("useChannel.getChannel: error",x)}}}return u.useEffect(()=>{v()},[t,s,e,r]),Ot(t,{async onReconnectSucceeded(){if(!c)return;const b=await c.refresh();y(b),d(b)}}),ht(t,{onChannelChanged:b=>{b.isGroupChannel()&&b.url===e&&(n.debug("useChannel.onChannelChanged: channel changed",b.url),d(b),l())}}),{channel:c,channelFetchError:m,getChannel:v,isInitializingConversation:g}}const Cc=new Set(["suggested_replies","steward","system"]),vc=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||!Cc.has(r)))return r},yc=e=>{var a;const t=e==null?void 0:e.lastMessage;if(!t||!e)return!1;const n=t.extendedMessagePayload,r=n==null?void 0:n.form,o=!!r&&!r.submitted_at&&!r.canceled_at,s=e.isAIAgent&&!!((a=e.conversation)!=null&&a.handedOverAt);return o&&!s},Sc=()=>{const{chatSDK:e,networkStateAdapter:t}=Re(),[n,r]=u.useState(()=>t?t.isOnline()?"connected":"reconnecting":"connected");return Ot(e,{onConnected:()=>r("connected"),onDisconnected:()=>r("disconnected"),onReconnectStarted:()=>r("reconnecting"),onReconnectSucceeded:()=>r("connected"),onReconnectFailed:()=>r("disconnected"),onConnectionLost:()=>r("reconnecting")}),u.useEffect(()=>{if(t)return t.subscribe(o=>{if(!o){r("reconnecting");return}r(s=>s==="reconnecting"&&e.connectionState===ue.ConnectionState.OPEN?"connected":s)})},[t,e]),n},Ac=3e4,xc=({shouldApply:e,lastMessage:t,isBlockedWhileAIResponding:n,currentUserId:r})=>{const[o,s]=u.useState(!1),a=u.useRef(null),l=t&>(t,r)?t.createdAt:0;return u.useEffect(()=>{const c=()=>{a.current&&(clearTimeout(a.current),a.current=null),s(!1)},d=g=>{a.current&&clearTimeout(a.current),s(!0),a.current=setTimeout(()=>{s(!1),a.current=null},g)},m=Date.now()-l,f=Ac-m;return n||f<=0?c():d(f),()=>{a.current&&clearTimeout(a.current)}},[n,l]),o&&e},Os=e=>{const{chatSDK:t}=Re(),[n,r]=u.useState([]);return ht(t,{onTypingStatusUpdated(o){if(o.url===(e==null?void 0:e.url)){const s=o.getTypingUsers();r(s)}}}),n},Tc=({channel:e,lastMessage:t,aiAgentUserId:n,isStreamAnimating:r})=>{const[o,s]=u.useState(!1),a=Os(e);return u.useEffect(()=>{if(!t)return;const l=a.some(d=>d.userId===n),c=gt(t,n)&&(We.isStreaming(t)||r);s(c||l)},[a,t,n,r]),o},Ic=({channel:e,messages:t,isStreamAnimating:n,isInitializingConversation:r})=>{const{aiAgentInfo:o,userSession:s}=pt(),a=Sc(),l=Tc({channel:e,lastMessage:Gr(t,[He.SendingStatus.SUCCEEDED]),aiAgentUserId:(o==null?void 0:o.userId)??"",isStreamAnimating:n}),c=xc({shouldApply:!!(e!=null&&e.isAIAgent)&&!nt(e),isBlockedWhileAIResponding:l,lastMessage:Gr(t,[He.SendingStatus.PENDING,He.SendingStatus.SUCCEEDED]),currentUserId:(s==null?void 0:s.userId)??""}),d=f=>f===""?{disabled:!1,disabledBy:"",focusPolicy:"auto"}:f==="ai_responding"?{disabled:!0,disabledBy:f,focusPolicy:"preserve"}:{disabled:!0,disabledBy:f,focusPolicy:"release"};if(!e||a==="disconnected")return d("unavailable");if(a==="reconnecting")return d("reconnecting");if(Ne(e))return d("conversation_closed");if(nl(e))return d("handoff_pending");if(yc(e))return d("form_active");const m=vc(e);return d(m||(l||c||r?"ai_responding":""))},wc=()=>{const[e,t]=u.useState(new Set),n=u.useCallback(o=>{t(s=>{if(s.has(o))return s;const a=new Set(s);return a.add(o),a})},[]),r=u.useCallback(o=>{t(s=>{if(!s.has(o))return s;const a=new Set(s);return a.delete(o),a})},[]);return{isAnimating:e.size>0,start:n,stop:r}},{Provider:Mc}=pe("AIAgentConversation");function kc({children:e,channelUrl:t,onChannelDeleted:n,onMessagesReceived:r,onMessagesUpdated:o,onConversationClosedStatusChanged:s,onConversationClosedViaDispatcher:a,onBeforeSendMessage:l,onAfterSendMessage:c=ce,shouldMarkAsRead:d=!0,shouldCountNewMessages:m=()=>!1,sortComparator:f}){var Y;const g=()=>d&&(_==null?void 0:_.markAsRead()),{_aiAgentSDK:E,chatSDK:y,logger:v,dispatcher:b}=Re(),{channel:_,channelFetchError:C,getChannel:x,isInitializingConversation:A}=bc(t),{statsTrackers:w}=pt();u.useEffect(()=>{if(t)return w.initialRender.setChannelUrl(t),()=>{w.initialRender.cleanup()}},[t,w]);const M=Ql(y,_,{replyType:He.ReplyType.ONLY_REPLY_TO_CHANNEL,shouldCountNewMessages:m,onChannelDeleted:n,onMessagesReceived:P=>r==null?void 0:r(P),onMessagesUpdated:P=>o==null?void 0:o(P),onCacheResult:P=>w.initialRender.onCacheResult(P),onApiResult:P=>w.initialRender.onApiResult(P),logger:v,markAsRead:g,sortComparator:f}),k=wc(),R=Ic({channel:_,messages:M.messages,isStreamAnimating:k.isAnimating,isInitializingConversation:A});u.useEffect(()=>{g()},[d,_]);const O=Ne(_);u.useEffect(()=>{s==null||s(O)},[O,s]),u.useEffect(()=>{const P=async V=>{const B=typeof(V==null?void 0:V.channelUrl)=="string";_&&B&&V.channelUrl!==_.url||(v.debug("conversation.dispatcher: try to close conversation",_),_!=null&&_.conversation&&_.conversation.status===Ee.ConversationStatus.OPEN&&(await _.closeConversation(),a==null||a()))};return b.subscribe(Be.ConversationClose,P),()=>{b.unsubscribe(Be.ConversationClose,P)}},[b,_,v,(Y=_==null?void 0:_.conversation)==null?void 0:Y.status,a]);const z={conversation:(_==null?void 0:_.conversation)??void 0,actions:{setUserMemoryState:E.setUserMemoryState},channelSource:{channel:_,error:C,refetch:()=>x(),closeConversation:async()=>{Ne(_)||await(_==null?void 0:_.closeConversation())}},messageSource:{messages:M.messages,newMessages:M.newMessages,initialized:M.initialized,subscribeMessageEvents:M.subscribeMessageEvents,loadPrevious:()=>M.loadPrevious(),loadNext:()=>M.loadNext(),deleteMessage:P=>M.deleteMessage(P),resendMessage:P=>M.resendMessage(P),resetNewMessages:()=>M.resetNewMessages(),sendUserMessage:async P=>{var B;if(((B=_==null?void 0:_.conversation)==null?void 0:B.status)===Ee.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(P=await l(P));const V=await M.sendUserMessage(P,c);return c==null||c(V),V},sendFileMessage:async P=>{var B;if(((B=_==null?void 0:_.conversation)==null?void 0:B.status)===Ee.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(P=await l(P));const V=await M.sendFileMessage(P,c);return c==null||c(V),V},sendMultipleFilesMessage:async P=>{var B;if(((B=_==null?void 0:_.conversation)==null?void 0:B.status)===Ee.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(P=await l(P));const V=await M.sendMultipleFilesMessage(P,c);return c==null||c(V),V}},state:{streamAnimation:k,input:R}};return i.createElement(Mc,{value:z},e)}function Rc(e,t){var E,y,v,b,_,C,x,A,w,M;const[n,r]=u.useState(!1),[o,s]=u.useState(null),[a,l]=u.useState([]),[c,d]=u.useState(null),m=u.useRef(!1),f=u.useCallback(async()=>{if(!m.current&&e.currentUser){m.current=!0,r(!1),s(null),l([]);try{c==null||c.dispose();const k=new _s(e,t);k.setConversationListCollectionHandler({onChannelsAdded:()=>{l(k.channels)},onChannelsUpdated:()=>{l(k.channels)},onChannelsDeleted:()=>{l(k.channels)}}),await k.loadMore(),l(k.channels),d(k),s(null)}catch(k){d(null),s(k)}finally{r(!0),m.current=!1}}},[e,e.currentUser,(E=t.filter)==null?void 0:E.aiAgentChannelFilter,(v=(y=t.filter)==null?void 0:y.aiAgentConversationStatusFilter)==null?void 0:v.join(),(_=(b=t.filter)==null?void 0:b.aiAgentIds)==null?void 0:_.join(),(C=t.filter)==null?void 0:C.deskChannelFilter,(A=(x=t.filter)==null?void 0:x.pinnedChannelUrls)==null?void 0:A.join(),(w=t.filter)==null?void 0:w.copilotConversationOnly,(M=t.filter)==null?void 0:M.copilotSupportChannelUrl,t.limit]),g=u.useCallback(async()=>{if(c)try{await c.loadMore(),l(c.channels)}catch(k){s(k)}},[c]);return Ot(e,{onConnected:()=>f()}),u.useEffect(()=>{f()},[f]),u.useEffect(()=>()=>{m.current=!1,c==null||c.dispose()},[c]),{initialized:n,error:o,channels:a,loadMore:g}}const Ns=e=>{var o;const{aiAgentId:t,queryParams:n}=Re(),r=(o=n==null?void 0:n.conversationListParams)==null?void 0:o.filter;return{aiAgentIds:[t],aiAgentConversationStatusFilter:[Ee.ConversationStatus.CLOSED,Ee.ConversationStatus.OPEN],...r,...e}},{Provider:Lc}=pe("AIAgentConversationList");function Oc({conversationListLimit:e,conversationListFilter:t,children:n}){var d;const{chatSDK:r,queryParams:o}=Re(),s=e??((d=o==null?void 0:o.conversationListParams)==null?void 0:d.limit),a=Ns(t),l=Rc(r,{limit:s,filter:a}),c={listSource:{initialized:l.initialized,error:l.error??void 0,channels:l.channels,loadMore:()=>l.loadMore()}};return i.createElement(Lc,{value:c},n)}function Nc(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:Dc,useContext:$c}=pe("MessageTemplateFetching");function Pc({children:e,internalVariables:t}){const n=u.useRef({}),r=u.useRef({}),[o,s]=u.useState({}),a=u.useCallback((d,m)=>{s(f=>({...f,[d]:{fetching:!1,error:!1,...f[d],...m}}))},[]),l=u.useCallback(async({onRequestTemplate:d,onGetCachedTemplate:m,templateKey:f,suspense:g=!1})=>{const E=m(f);if(E)return E;const y=r.current[f];if(y)return y;g||a(f,{fetching:!0});const v=d(f).catch(b=>{throw g||a(f,{error:!0}),b}).finally(()=>{g||a(f,{fetching:!1}),delete r.current[f]});return r.current[f]=v,v},[a]),c={internalVariables:t,fetchTemplate:l,suspend:(d,m)=>{if(n.current[d])return n.current[d];const f=Nc(m());return n.current[d]=f,f},getIsFetching:d=>{var m;return((m=o[d])==null?void 0:m.fetching)??!1},getHasError:d=>{var m;return((m=o[d])==null?void 0:m.error)??!1}};return i.createElement(Dc,{value:c},e)}const Fc="remove_powered_by",gr=(e,t)=>{var o,s;const{chatSDK:n}=Re(),{aiAgentInfo:r}=pt();if(e==="handoff-button"){const a=!!((o=t==null?void 0:t.conversation)!=null&&o.handoff);return!!(t!=null&&t.isAIAgent)&&!!(r!=null&&r.showHandoffButton)&&a&&ar(t)}if(e==="special-notice")return!!(t!=null&&t.isAIAgent)&&!!(r!=null&&r.specialNoticeEnabled)&&!!(r!=null&&r.specialNotice);if(e==="powered-by"){const a=(s=n==null?void 0:n.appInfo)==null?void 0:s.applicationAttributes;return u.useMemo(()=>!(Array.isArray(a)&&a.includes(Fc)),[a])}throw new Error("Unsupported feature")},Uc={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"},Bc={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:o}=e;if(o){if(o.min_length!==void 0&&r.length<o.min_length)return{isValid:!1,error:typeof n.minLength=="function"?n.minLength(o.min_length):n.minLength};if(o.max_length!==void 0&&r.length>o.max_length)return{isValid:!1,error:typeof n.maxLength=="function"?n.maxLength(o.max_length):n.maxLength};if(o.regex&&!new RegExp(o.regex).test(r))return{isValid:!1,error:n.regex}}return{isValid:!0}}},Hc={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:o}=e;if(o){if(o.min!==void 0&&r<o.min)return{isValid:!1,error:typeof n.min=="function"?n.min(o.min):n.min};if(o.max!==void 0&&r>o.max)return{isValid:!1,error:typeof n.max=="function"?n.max(o.max):n.max}}return{isValid:!0}}},Gc={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}}},zc={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(a=>!e.options.includes(a)).length>0)return{isValid:!1,error:n.invalidSelection};const{rules:s}=e;if(s){if(s.min_select!==void 0&&r.length<s.min_select)return{isValid:!1,error:typeof n.minSelect=="function"?n.minSelect(s.min_select):n.minSelect};if(s.max_select!==void 0&&r.length>s.max_select)return{isValid:!1,error:typeof n.maxSelect=="function"?n.maxSelect(s.max_select):n.maxSelect}}return{isValid:!0}}},Vc={text:Bc,number:Hc,"single-select":Gc,"multi-select":zc},Yc={getValueOrDefault:()=>null,validate:()=>({isValid:!1})};function Ds(e){return Vc[e.type]||Yc}function ao(e){return Ds(e).getValueOrDefault(e)}function Wc(e,t,n={}){const r={...Uc,...n};return Ds(e).validate(e,t,r)}const qc=(e,t={})=>{const{labels:n={},onSubmit:r,onCancel:o}=t,[s,a]=u.useState({}),[l,c]=u.useState(()=>{const v={};return e.fields.forEach(b=>{v[b.key]=ao(b)}),v}),d=u.useMemo(()=>e.submitted_at?"submitted":e.canceled_at?"canceled":"draft",[e.submitted_at,e.canceled_at]);u.useEffect(()=>{if(d==="submitted"||d==="canceled"){const v={};let b=!1;e.fields.forEach(_=>{const C=ao(_);JSON.stringify(l[_.key])!==JSON.stringify(C)&&(b=!0),v[_.key]=C}),b&&c(v)}},[d]);const m=(v,b)=>{c(_=>({..._,[v]:b})),a(_=>({..._,[v]:void 0}))},f=e.fields.map(v=>{var C,x,A;const b=l[v.key]??null,_={key:v.key,label:v.label,error:s[v.key],required:v.required};return v.type==="text"?{..._,type:"text",layout:v.layout,value:b,...v.placeholder&&{placeholder:v.placeholder},...((C=v.rules)==null?void 0:C.max_length)&&{maxLength:v.rules.max_length}}:v.type==="number"?{..._,type:"number",layout:v.layout,value:b,...v.placeholder&&{placeholder:v.placeholder},...((x=v.rules)==null?void 0:x.max)&&{max:v.rules.max}}:v.type==="single-select"?{..._,type:"single-select",layout:v.layout,value:b,options:v.options}:v.type==="multi-select"?{..._,type:"multi-select",layout:v.layout,value:b,options:v.options,...((A=v.rules)==null?void 0:A.max_select)&&{maxSelect:v.rules.max_select}}:{..._,type:"unknown",layout:"default",value:null}});return{state:d,fields:f,getField:v=>f.find(b=>b.key===v),updateFieldValue:m,submit:async()=>{const v={};let b=!1;for(const _ of e.fields){const C=l[_.key]??null,x=Wc(_,C,n);x.isValid||(v[_.key]=x.error,b=!0)}if(a(v),!b&&r){const _={};e.fields.forEach(C=>{_[C.key]=l[C.key]??null}),await r(_)}},cancel:async()=>{await(o==null?void 0:o())}}},Kc=e=>{const{chatSDK:t,handlers:n,logger:r}=Re(),{aiAgentInfo:o}=pt(),s=u.useRef(new Set),a=u.useRef(new Set),l=(m,f)=>{if(!(n!=null&&n.onCustomEvent)||!(o!=null&&o.userId)||!gt(m,o.userId))return;const g=m.messageId;if(We.isStreaming(m)){a.current.add(g);return}f==="updated"&&!a.current.has(g)||(r.debug("useCustomEventForMessageReceive: bot-message-received",m),n.onCustomEvent({type:"bot-message-received",data:{message:m}}),a.current.delete(g))},c=u.useCallback(m=>{if(n!=null&&n.onCustomEvent&&m.isAdminMessage()&&m.customType==="user_action_required"&&!s.current.has(m.messageId)){const f=Gn(m.data);Array.isArray(f.history)&&f.history.length===0&&(r.debug("useCustomEventForMessageReceive: user_action_required",f),n.onCustomEvent({type:"user-action-requested",data:f}),s.current.add(m.messageId))}},[n,r]),d=(m,f,g)=>{m.url===e&&(l(f,g),c(f))};return ht(t,{onMessageReceived:(m,f)=>d(m,f,"received"),onMessageUpdated:(m,f)=>d(m,f,"updated")}),{checkForUserActionRequired:c}},jc=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},$s=e=>{const{aiAgentInfo:t}=pt(),n=Os(e);if(Ne(e))return null;const r=n[0];if(!r)return null;const o=r.userId===(t==null?void 0:t.userId),s=o?jc(r.metaData):void 0;return{user:o?t:r,isBot:o,thinkingMessage:s}},Xc=(e,t,{enabled:n=!0,idleMs:r=1e3}={})=>{const o=u.useRef(null),s=u.useRef(t),a=u.useRef(t),l=u.useRef(!1);s.current=t,u.useEffect(()=>{if(o.current&&(clearTimeout(o.current),o.current=null),!n||!e){(l.current?a.current:s.current)(!1),l.current=!1,a.current=s.current;return}l.current=!0,a.current=s.current,a.current(!0),o.current=setTimeout(()=>{o.current=null,a.current(!1),l.current=!1,a.current=s.current},r)},[n,r,e]),u.useEffect(()=>()=>{o.current&&(clearTimeout(o.current),o.current=null),(l.current?a.current:s.current)(!1),l.current=!1,a.current=s.current},[])},Zc=(e=1e4)=>{const t=new Map;let n=e;return{shouldAnnounce:l=>{const c=Date.now(),d=t.get(l);return d!==void 0&&c-d<n?!1:(t.set(l,c),!0)},setInterval:l=>{n=l},reset:()=>{t.clear()}}},Jc=(e,t,n=1e4,r=!0)=>{const o=u.useRef(null),s=u.useRef(null),a=u.useRef(!1);o.current||(o.current=Zc(n));const l=(e==null?void 0:e.nickname.trim())||null,c=(e==null?void 0:e.userId)??l;u.useEffect(()=>{var d;(d=o.current)==null||d.setInterval(n)},[n]),u.useEffect(()=>{var f;if(!r){a.current=!1,s.current=c;return}if(!c||!l){a.current=!1,s.current=null;return}const d=!a.current,m=s.current!==c;a.current=!0,s.current=c,!(!d&&!m)&&(f=o.current)!=null&&f.shouldAnnounce(c)&&t(l)},[c,l,r,t])},Qc=({csat:e,csatPayload:t,isRenderableCSAT:n,isExpiredNow:r,announceStatus:o,onSubmittedAnnounced:s})=>{const a=(t==null?void 0:t.csat_submitted_label)??"",l=u.useRef(n&&typeof e=="number"),c=u.useRef(n&&r);u.useEffect(()=>{n&&a&&(typeof e!="number"||l.current||(l.current=!0,o&&(o({event:"csatSubmitted",submittedLabel:a}),s==null||s())))},[o,e,n,s,a]),u.useEffect(()=>{n&&r&&(c.current||(c.current=!0,o==null||o({event:"csatExpired"})))},[o,r,n])},hr=({channel:e,userSession:t,aiAgentInfo:n})=>{if(!t||!n||!e)return{fallbackIcon:"delight",url:void 0,title:""};const r=ys(e,t.userId),o={ai(s){return{fallbackIcon:s,url:n.profileUrl,title:n.nickname}},human(s){return{fallbackIcon:s,url:r==null?void 0:r.profileUrl,title:(r==null?void 0:r.nickname)||n.nickname}},channel(s){return{fallbackIcon:s,url:e==null?void 0:e.coverUrl,title:(e==null?void 0:e.name)??""}}};return e.isAIAgent?nt(e)?o.human("agent"):o.ai("delight"):e.isDesk?o.human("agent"):o.channel("user")},lo=e=>u.useReducer((t,n)=>({...t,...n}),e);var qe=(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))(qe||{});const eu=new Set(["free_text","single_choice"]),tu=({csatPayload:e,type:t,initialCsat:n,initialCsatReason:r,initialIsResolved:o})=>{const[s,a]=lo({csatType:t,csat:n,csatReason:r,isResolved:o}),[l,c]=lo({followUpItem:!1}),d=u.useMemo(()=>{var b;const E=s.csat,y=typeof E=="number",v=(b=e.follow_up)==null?void 0:b.find(_=>y?_.scores.includes(E):_.always_visible??!1);if(eu.has(v==null?void 0:v.response_type))return v},[s.csat,e.follow_up]),m=(()=>{var E;if(typeof n=="number")return"submitted";if((t===qe.AI_AGENT_CSAT_5||t===qe.HELPDESK_CSAT_5)&&typeof s.csat=="number")return"submittable";if(t===qe.AI_AGENT_CSAT_5_WITH_CRE){const y=typeof s.csat=="number",v=!((E=e.cre)!=null&&E.required)||typeof s.isResolved=="boolean";if(y&&v)return"submittable"}return"unsubmittable"})(),f=u.useCallback(()=>typeof s.csat>"u"?!1:d!=null&&d.required&&!s.csatReason?(c({followUpItem:!0}),!1):!0,[s,d,c]);return u.useEffect(()=>{r||(a({csatReason:""}),c({followUpItem:!1}))},[r,d,a,c]),{params:s,setParams:a,error:l,setError:c,followUpItem:d,state:m,validateParams:f,itemProps:{csatPayload:e,state:m,submitted:m==="submitted"}}},nu=({csat:e,csatExpireAt:t,csatPayload:n,isSubmitInFlight:r=!1})=>{const o=!!n&&n.visibility&&!!qe[n.type],s=!r&&typeof e!="number"&&Ss(t),a=gn();return u.useEffect(()=>{if(!o||typeof e=="number"||t==null||s)return;const l=t-Date.now();if(l<=0&&r)return;const c=setTimeout(a,Math.max(0,l));return()=>clearTimeout(c)},[a,e,t,s,o,r]),{isRenderableCSAT:o,isExpiredNow:s}},kn=5,ru=250,ou=50,co=e=>Math.max(0,e-ou),su=e=>e<1e3?{speed:kn*.5,chunkSize:2}:e<2e3?{speed:kn*.8,chunkSize:2}:{speed:kn*.6,chunkSize:3},Zt=(e,t)=>{let n=0;for(let r=t-1;r>=0&&e[r]==="\\";r--)n++;return n%2===1},uo=(e,t,n,r)=>{let o=1,s=t;for(;s<e.length&&o>0;){if(Zt(e,s)){s++;continue}e[s]===n?o++:e[s]===r&&o--,s++}return o>0?-1:s},iu=(e,{hideImages:t,hideLinks:n})=>{let r="",o=0,s=0;for(;o<e.length;){if(e[o]==="`"&&!Zt(e,o)){let f=1;for(;e[o+f]==="`";)f++;s===0?s=f:f===s&&(s=0),r+=e.slice(o,o+f),o+=f;continue}const a=e[o]==="!"&&e[o+1]==="["&&!Zt(e,o),l=e[o]==="["&&!Zt(e,o);if(s>0||!a&&!l){r+=e[o],o++;continue}if(a?!t:!n){const f=a?"![":"[";r+=f,o+=f.length;continue}const c=o,d=uo(e,o+(a?2:1),"[","]");if(d===-1)return r;if(o=d,e[o]!=="("){r+=e.slice(c,o);continue}const m=uo(e,o+1,"(",")");if(m===-1)return r;o=m,r+=e.slice(c,o)}return r},au=e=>{const{text:t,enabled:n=!1,deferredMarkdownElements:r=[],onAnimationStart:o,onAnimationProgress:s,onAnimationComplete:a}=e,[l,c]=u.useState(()=>co(t.length)),d=u.useRef(null),m=u.useRef({startTime:0,lastUpdate:0,lastProgressCall:0}).current,f=u.useRef({onStart:o,onProgress:s,onComplete:a}).current,g=u.useRef({startCalled:!1,completeCalled:!1}).current,E=u.useRef({initialEnabled:n,textLength:t.length,enabled:n}).current,y=n,v=l<t.length,b=E.initialEnabled&&(y||v);u.useLayoutEffect(()=>{f.onStart=o,f.onProgress=s,f.onComplete=a,E.textLength=t.length,E.enabled=n}),u.useLayoutEffect(()=>{var A;E.initialEnabled&&(g.startCalled||(g.startCalled=!0,(A=f.onStart)==null||A.call(f)),c(w=>t.length<w?t.length:w))},[t]),u.useEffect(()=>{if(!E.initialEnabled)return;let A=co(t.length);m.lastUpdate=0,m.startTime=0,m.lastProgressCall=0;const w=M=>{var B;m.lastUpdate===0&&(m.lastUpdate=M,m.startTime=M,m.lastProgressCall=M);const k=E.textLength,R=M-m.lastUpdate,O=M-m.startTime,{speed:z,chunkSize:Y}=su(O),P=z*Y;R>=P&&A<k&&(A=Math.min(A+Y,k),c(A),m.lastUpdate=M),M-m.lastProgressCall>=ru&&(m.lastProgressCall=M,(B=f.onProgress)==null||B.call(f)),(A<k||E.enabled)&&(d.current=requestAnimationFrame(w))};return d.current=requestAnimationFrame(w),()=>{var M;d.current&&cancelAnimationFrame(d.current),g.startCalled&&!g.completeCalled&&(g.completeCalled=!0,(M=f.onComplete)==null||M.call(f))}},[]),u.useEffect(()=>{var k;const A=E.initialEnabled&&g.startCalled,w=!n,M=l>=t.length&&t.length>0;A&&w&&M&&!g.completeCalled&&(g.completeCalled=!0,(k=f.onComplete)==null||k.call(f))},[n,l,t.length]);const _=r.includes("image"),C=r.includes("link");return{streamText:u.useMemo(()=>{const A=E.initialEnabled?t.slice(0,l):t,w=b&&_,M=b&&C;return!w&&!M?A:iu(A,{hideImages:w,hideLinks:M})},[t,l,_,C,b]),isAnimating:b}},mo={visible:!1,remainingTime:0,showDescription:!1,targetTimeMs:null},lu=e=>({visible:!0,remainingTime:e,showDescription:!0,targetTimeMs:Date.now()+e*1e3}),cu=(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}},uu=()=>{const{chatSDK:e}=Re(),[t,n]=u.useState(mo),r=()=>n(mo);return Ot(e,{onConnectionDelayed:o=>{o>0?n(lu(o)):r()},onReconnectSucceeded:r,onConnected:r}),u.useEffect(()=>{if(!t.visible||!t.showDescription||t.targetTimeMs==null)return;const o=setTimeout(()=>{n(s=>cu(s))},1e3);return()=>clearTimeout(o)},[t.visible,t.showDescription,t.targetTimeMs,t.remainingTime]),{visible:t.visible,remainingTime:t.remainingTime,showDescription:t.showDescription}},du=e=>{const t=Math.floor(e/60),n=e%60;return`${String(t).padStart(2,"0")}:${String(n).padStart(2,"0")}`},mu=(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)}},fu=(e,{enabled:t=!0,opened:n=!1,filter:r}={})=>{var c,d,m;const[o,s]=u.useState(!1),a=u.useRef(0),l=()=>{if(!t)return;const f=++a.current;e.aiAgent.getUnreadMessageCount(r).then(g=>{f===a.current&&s(g.total>0)}).catch(()=>{})};return u.useEffect(()=>{if(!t){s(!1),a.current++;return}e.connectionState===ue.ConnectionState.OPEN&&l()},[t,e,r==null?void 0:r.aiAgentChannelFilter,(c=r==null?void 0:r.aiAgentConversationStatusFilter)==null?void 0:c.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]),u.useEffect(()=>{n&&(s(!1),a.current++)},[n]),Ot(e,{onConnected:l,onReconnectSucceeded:l}),o},pr=e=>e.replace(/\s+/g," ").trim(),gu="Code block",Ps=e=>`A11Y_INLINE_CODE_${e}`,Fs=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}},Us=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}},hu=e=>{const{blockquotePrefix:t,content:n}=Fs(e),{content:r}=Us(n),o=r.match(/^[ \t]{0,3}([`~]{3,})(.*)$/);if(!o)return;const s=o[1],a=o[2],l=s[0];if(!(l!=="`"&&l!=="~"||!s.split("").every(c=>c===l))&&!(l==="`"&&a.includes("`")))return{char:l,blockquotePrefix:t,length:s.length}},pu=(e,t)=>{const{blockquotePrefix:n,content:r}=Fs(e);if(n!==t.blockquotePrefix)return!1;const{content:o,hasListPrefix:s}=Us(r);if(s)return!1;const a=o.match(/^[ \t]{0,3}([`~]{3,})[ \t]*$/);if(!a)return!1;const l=a[1];return l[0]===t.char&&l.length>=t.length&&l.split("").every(c=>c===t.char)},_u=(e,t,n)=>{let r=n;for(;r<e.length;){const o=e[r];if(o==="\\"&&r+1<e.length){r+=2;continue}if(o===t)return r;r+=1}return-1},Eu=(e,t)=>{let n=1,r=t;for(;r<e.length;){const o=e[r];if(o==="\\"&&r+1<e.length){r+=2;continue}if(o==="["){n+=1,r+=1;continue}if(o==="]"&&(n-=1,n===0))return r;r+=1}return-1},bu=(e,t)=>{let n=t,r=1,o,s=!1,a=!1;for(;n<e.length&&r>0;){const l=e[n];if(l==="\\"&&n+1<e.length){n+=2;continue}if(o){l===o&&(o=void 0),n+=1;continue}if(r===1&&s&&/\s/.test(l)){a=!0,n+=1;continue}if(r===1&&a&&(l==='"'||l==="'")){o=l,n+=1;continue}if(l==="("){r+=1,s=!0,n+=1;continue}if(l===")"){r-=1,n+=1;continue}/\s/.test(l)||(s=!0),n+=1}return r===0?n:-1},Cu=e=>{let t=0,n="";for(;t<e.length;){const r=_u(e,"[",t);if(r===-1){n+=e.slice(t);break}const o=Eu(e,r+1);if(o===-1){n+=e.slice(t);break}if(r>0&&e[r-1]==="!"&&sn(e,r-1)){n+=e.slice(t,o+1),t=o+1;continue}if(e[o+1]!=="("){n+=e.slice(t,o+1),t=o+1;continue}const s=r>0&&e[r-1]==="!"&&!sn(e,r-1)?r-1:r;n+=e.slice(t,s);const a=e.slice(r+1,o),l=bu(e,o+2);if(l===-1){n+=e.slice(s);break}n+=a,t=l}return n},Bs=(e,t,n)=>{if(!/^\d+$/.test(t))return!1;const r=e.slice(-1);return/\d/.test(r)&&/\d/.test(n)},vu=e=>e.replace(/(^|[^*\\])\*\*([^\s*](?:[\s\S]*?[^\s*])?)\*\*(?!\*)/g,(t,n,r,o,s)=>{const a=s[o+t.length]??"";return Bs(n,r,a)?t:`${n}${r}`}),yu=e=>e.replace(/(^|[^_\\])__([^\s_](?:[\s\S]*?[^\s_])?)__(?!_)/g,"$1$2"),Su=e=>e.replace(/(^|[^~\\])~~([^\s~](?:[\s\S]*?[^\s~])?)~~(?!~)/g,"$1$2"),Au=e=>{let t=e;return t=t.replace(/(^|[^*\\])\*([^\s*](?:[\s\S]*?[^\s*])?)\*(?!\*)/g,(n,r,o,s,a)=>{const l=a[s+n.length]??"";return Bs(r,o,l)?n:`${r}${o}`}),t=t.replace(/(^|[\s([{"'])_([^_\s](?:[\s\S]*?[^_\s])?)_(?=$|[\s)\]}"'.,!?:;])/g,"$1$2"),t},xu=e=>e.replace(/\\([\\`*_[\]()#+.!~|-])/g,"$1"),Tu=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},fo=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))},go=e=>{const t=[];let n="",r=!1;for(const s of e.trim()){if(r){n+=s==="|"?"|":`\\${s}`,r=!1;continue}if(s==="\\"){r=!0;continue}if(s==="|"){const a=n.trim();a&&t.push(a),n="";continue}n+=s}r&&(n+="\\");const o=n.trim();return o&&t.push(o),t},Iu=e=>{const t=e.split(`
|
|
2
|
-
`),n=[];let r=0;for(;r<t.length;){const
|
|
3
|
-
`)},
|
|
4
|
-
`),r=[];let
|
|
5
|
-
`)},
|
|
6
|
-
`;){if(e[
|
|
7
|
-
`);if(!n)return;const r=[];let o=n;o=Mu(o,t),o=Tu(o);const s=ku(o);o=s.text,r.push(...s.inlineCodes),o=Cu(o),o=vu(o),o=yu(o),o=Su(o),o=Au(o),o=Iu(o),o=wu(o),o=xu(o);for(let l=0;l<r.length;l++)o=o.replaceAll(Ps(l),r[l]);return pr(o)||void 0},Ru=(e,t)=>{var o;const n=((o=e.name)==null?void 0:o.trim())||"",r=e.mimeType??"";return ze(r)?t.image:mn(r)?t.video:gs({name:n,mimeType:r})?t.pdf(n):t.document(n)},an=e=>(e==null?void 0:e.trim())||"",Lu=e=>(e?pr(e):void 0)||void 0,Gs=e=>({text:an(e),format:"plain"}),Ou=e=>({text:an(e),format:"markdown"}),Rn=({markdownText:e,plainText:t,comparisonText:n})=>{const r=an(e);return r&&r!==an(n)?Ou(r):Gs(t)},At=({sender:e,message:t,messageFormat:n="plain",time:r,codeBlockPlaceholder:o})=>{const s=[],a=n==="markdown"?Hs(t,{codeBlockPlaceholder:o}):Lu(t);if(r&&s.push(r),e&&s.push(e),a&&s.push(a),s.length!==0)return s.join(", ")},zs=(e,t)=>Hs(e==null?void 0:e.trim(),t!==void 0?{codeBlockPlaceholder:t}:void 0),Nu=(...e)=>pr(e.filter(Boolean).join(", "))||void 0,ho=(e,t,n,r)=>{if(!t||t===n)return e;const o=zs(t,r);return o?Nu(e,o):e},Du=(e,t)=>{var r,o,s,a;const n=(r=e.message)==null?void 0:r.trim();if(e.isFileMessage()){const l=((o=e.name)==null?void 0:o.trim())||"",c=Ru({name:l,mimeType:e.type},t);return ho(c,n,l,t.codeBlockPlaceholder)}if(e.isMultipleFilesMessage()){const l=e.fileInfoList??[],c=l.length;if(c===0)return;const d=((a=(s=l[0])==null?void 0:s.fileName)==null?void 0:a.trim())||"",f=l.every(g=>{var E;return(E=g.mimeType)==null?void 0:E.startsWith("image")})?t.receivedFilesImageCount(c):t.multipleFilesCount(c);return ho(f,n,d,t.codeBlockPlaceholder)}return zs(n,t.codeBlockPlaceholder)},$u=(e,t={})=>{const{throttleMs:n=1e3,isSuppressed:r,maxOrderedQueueSize:o=10}=t,s=Math.max(1,o);let a=null;const l=[];let c=null,d=null,m=null,f=!1,g=0;const E=(R,O,z)=>({text:R,ignoreSuppression:O,queueOrder:g++,dedupeKey:z}),y=()=>{const R=l[0]??null,O=a;return R&&O?O.queueOrder<R.queueOrder?(a=null,O):l.shift()??null:R?l.shift()??null:O!==null?(a=null,O):null},v=()=>{for(;;){const R=y();if(!R)return null;if(!(!R.ignoreSuppression&&(r!=null&&r())))return R}},b=R=>{c=R.text,d=R.dedupeKey??null,f=!0,e(R.text),m=setTimeout(()=>{m=null,f=!1;const O=v();O&&b(O)},n)},_=R=>{c=R.text,d=R.dedupeKey??null,e(R.text)},C=(R,O,z,Y)=>O!=null&&Y!=null?O===Y:O==null&&Y==null?R!=null&&R===z:!1,x=(R,O,z)=>{if(!R||!O&&(r!=null&&r()))return;const Y=z==null?void 0:z.dedupeKey;if(!(f&&C(R,Y,c,d)))if(f){if(((z==null?void 0:z.mode)??"latestOnly")==="ordered"){const V=l[l.length-1];if(V&&C(R,Y,V.text,V.dedupeKey))return;l.push(E(R,O,Y)),l.length>s&&l.shift();return}a=E(R,O,Y)}else a=null,b(E(R,O,Y))};return{announce:(R,O)=>{x(R,!1,O)},announceIgnoringSuppression:(R,O)=>{x(R,!0,O)},flush:()=>{const R=[];let O=y();for(;O!==null;)R.push(O),O=y();if(m!==null&&(clearTimeout(m),m=null),f=!1,R.length!==0)for(const z of R)_(z)},destroy:()=>{m!==null&&(clearTimeout(m),m=null),a=null,l.length=0,c=null,d=null,f=!1}}},Pu=e=>{switch(e){case"newMessage":case"conversationClosed":case"csatDisplayed":case"csatSubmitted":case"csatExpired":return"ordered";default:return"latestOnly"}},Fu=(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(". "),Uu=(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}},Bu=(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}},Hu=(e,t)=>!t||!tt(e)||e.sender.userId!==t?null:e.reqId||(e.messageId>0?String(e.messageId):null),Gu=(e,t)=>we.isAdmin(e)?we.isCSAT(e):"sender"in e?e.sender.userId!==t:!1,zu=e=>"messageId"in e&&e.messageId>0?String(e.messageId):"reqId"in e&&typeof e.reqId=="string"&&e.reqId.length>0?e.reqId:null,Vu=e=>e===ue.CollectionEventSource.EVENT_MESSAGE_RECEIVED||e===ue.CollectionEventSource.EVENT_MESSAGE_UPDATED,Yu=({isOpened:e,opensConversationList:t})=>e?t?"closeConversationList":"closeConversation":t?"openConversationList":"openConversation",Wu=(e,t)=>{switch(e){case"closeConversationList":return t.closeConversationList;case"closeConversation":return t.closeConversation;case"openConversationList":return t.openConversationList;case"openConversation":return t.openConversation}},qu=(e,t)=>{switch(e){case"closeConversation":return t.hintCloseConversation;case"openConversationList":return t.hintOpenConversationList;case"openConversation":return t.hintOpenConversation;default:return}},Ku=({intent:e,strings:t})=>({label:Wu(e,t),hint:qu(e,t)}),ju="1.31.1",$e="sb-agent",be={ENTRY:`${$e}-entry`,MODAL_ROOT:`${$e}-modal-root`,WINDOW:`${$e}-window`,LAUNCHER:`${$e}-launcher`,WINDOW_TITLE:`${$e}-window-title`},Vs="data-sb-initial-focus",Ys="true",Xu=`[${Vs}="${Ys}"]`,Ws={[Vs]:Ys},_r="data-sb-focus-trap-sentinel",Zu="true",qs="data-sb-initial-focus-header",Ks="true",Ju=`[${qs}="${Ks}"]`,js={[qs]:Ks},Xs="data-sb-message-input",Zs="true",Qu=`textarea[${Xs}="${Zs}"]:not(:disabled)`,ed={[Xs]:Zs},Js=1e3,Yt=2147483647,it={MODAL:Yt-1,TOOLTIP:Yt-2,WINDOW:Yt-3,LAUNCHER:Yt-4},Qs=36,td=100,nd=ju,Er="noopener noreferrer nofollow";function rd(){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 Wt={};function od(){return{get:e=>{try{return localStorage.getItem(e)}catch{return Wt[e]??null}},set:(e,t)=>{try{localStorage.setItem(e,t)}catch{Wt[e]=t}},delete:e=>{try{localStorage.removeItem(e)}catch{delete Wt[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(Wt).filter(t=>t.startsWith(e))}}}}const sd={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_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}`}},qn={language:"en",strings:sd,dateLocale:_a.enUS},ei=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_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}),ti=e=>{var t;return((t=e.split("-"))==null?void 0:t[0])??Nt},Nt="en",ni=new Set([Nt,"ko","es","pt","fr","hi","it","de","tr","ja"]),id='@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:ad,useContext:br}=pe("AgentUIElementResolver"),ld=({entryElement:e,modalRootElement:t,rootElement:n,children:r})=>{const o=u.useMemo(()=>{const s=n??document.body,a=e??s,l=t??s,c=d=>d===be.MODAL_ROOT?l:a.querySelector(`#${d}`);return{resolveElement:c,resolvePortalContainer:d=>c(d)??l}},[e,t,n]);return i.createElement(ad,{value:o},r)};function st(e,t){const n=e.getRootNode({composed:t});return n instanceof ShadowRoot||n instanceof Document?n:document}const po=()=>{const e=[];let t=0;const n=new Set,r=()=>n.forEach(o=>o());return{register:o=>{const s=++t;return e.push({id:s,handler:o}),r(),()=>{const a=e.findIndex(l=>l.id===s);a>=0&&(e.splice(a,1),r())}},dismissTopmost:()=>{const o=e[e.length-1];return o?(o.handler(),!0):!1},subscribe:o=>(n.add(o),()=>{n.delete(o)}),getOpenCount:()=>e.length}},{Provider:cd,useContext:Cr}=pe("EscapeDismissStack"),_o=e=>{e.stopPropagation(),e.stopImmediatePropagation()},ud=({rootElement:e=document.body,boundaryElement:t,children:n})=>{const r=u.useRef(null),o=u.useRef(null);r.current||(r.current=po()),o.current||(o.current=po());const s=r.current,a=o.current;u.useLayoutEffect(()=>{const c=t??st(e),d=m=>{if(m.key==="Escape"){if(s.dismissTopmost()){_o(m);return}a.dismissTopmost()&&_o(m)}};return c.addEventListener("keydown",d),()=>c.removeEventListener("keydown",d)},[t,e,a,s]);const l=u.useMemo(()=>({register:s.register,dismissTopmost:s.dismissTopmost,registerShellDismissHandler:a.register,subscribe:s.subscribe,getOpenCount:s.getOpenCount}),[a,s]);return i.createElement(cd,{value:l},n)},ri=(e,t,n)=>{const r=u.useRef(t);u.useLayoutEffect(()=>{r.current=t},[t]),u.useLayoutEffect(()=>{if(e)return n(()=>r.current())},[e,n])},dd=(e,t)=>{const{register:n}=Cr();ri(e,t,n)},md=(e,t)=>{const{registerShellDismissHandler:n}=Cr();ri(e,t,n)},oi=()=>{const{subscribe:e,getOpenCount:t}=Cr();return u.useSyncExternalStore(e,()=>t()>0,()=>!1)},fd=(e,t,n)=>{const r=e[t];return r?typeof r=="function"?r():Promise.resolve(r):new Promise((o,s)=>{(typeof queueMicrotask=="function"?queueMicrotask:setTimeout)(s.bind(null,new Error("Unknown variable dynamic import: "+t+(t.split("/").length!==n?". Note that variables only represent file names one level deep.":""))))})},Eo=ei(qn.strings),gd={...Eo,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:Eo.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"},ln={language:qn.language,dateLocale:qn.dateLocale,stringSet:gd},hd=Object.freeze(Object.defineProperty({__proto__:null,default:ln},Symbol.toStringTag,{value:"Module"})),Kn=new Map([[Nt,ln]]);async function pd(e){const t=Kn.get(e);if(t)return t;try{if(ni.has(e)){const{default:n}=await fd(Object.assign({"./languages/de.ts":()=>Promise.resolve().then(()=>require("./cjs/I-l-5Zo-.cjs")),"./languages/en.ts":()=>Promise.resolve().then(()=>hd),"./languages/es.ts":()=>Promise.resolve().then(()=>require("./cjs/D_km8dcd.cjs")),"./languages/fr.ts":()=>Promise.resolve().then(()=>require("./cjs/CLIpC7kY.cjs")),"./languages/hi.ts":()=>Promise.resolve().then(()=>require("./cjs/ChrM6HN1.cjs")),"./languages/it.ts":()=>Promise.resolve().then(()=>require("./cjs/CPZf2TWM.cjs")),"./languages/ja.ts":()=>Promise.resolve().then(()=>require("./cjs/D7UQ9OK7.cjs")),"./languages/ko.ts":()=>Promise.resolve().then(()=>require("./cjs/BMDJStMQ.cjs")),"./languages/pt.ts":()=>Promise.resolve().then(()=>require("./cjs/etCQgYrr.cjs")),"./languages/tr.ts":()=>Promise.resolve().then(()=>require("./cjs/DKQwAy8C.cjs"))}),`./languages/${e}.ts`,3);return Kn.set(e,n),n}return ln}catch{return ln}}const{Provider:_d,useContext:se}=pe("Localization"),Ed=({language:e=navigator.language,languageCode:t,logger:n,stringSet:r,children:o})=>{const[s,a]=u.useState(Kn.get(Nt));return u.useEffect(()=>{const l=t??ti(e);s.language!==l&&(n==null||n.debug("localization.useEffect: update language",{from:s.language,to:l}),pd(l).then(a))},[e,t,n]),i.createElement(_d,{value:{language:s.language,defaultStringSet:s.stringSet,stringSet:{...s.stringSet,...r},dateLocale:s.dateLocale,format:(l,c,d)=>Je.format(l,c,{locale:s.dateLocale,...d})}},o)},cn="data-sb-agent-theme",bo=e=>(t,...n)=>{let r="";return t.forEach((o,s)=>{r+=o+(n[s]??"")}),`[${cn}='${e}'] & { ${r} }`},Z={light:bo("light"),dark:bo("dark")},bd=D.css(({theme:e})=>{const{palette:t}=e;return`
|
|
1
|
+
"use strict";var rc=Object.defineProperty;var sc=(e,t,n)=>t in e?rc(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var S=(e,t,n)=>sc(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const fe=require("@sendbird/chat"),l=require("react"),P=require("styled-components"),ot=require("date-fns"),oc=require("date-fns/locale/en-US"),Ke=require("@sendbird/chat/message"),ic=require("react-dom"),Se=require("@sendbird/chat/aiAgent"),Ze=require("@sendbird/chat/groupChannel"),ac=require("date-fns/isSameDay"),cc=require("dompurify"),Sr=e=>e&&e.__esModule?e:{default:e};function lc(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 uc=Sr(fe),a=lc(l),b=Sr(P),Go=Sr(cc),zo=e=>{try{return JSON.parse(e===""?"{}":e)}catch{return{}}},dc=e=>{const t=zo(e);return typeof t=="object"&&t!==null?t:{}},Vo=e=>typeof e=="string"?dc(e):e??{},mc=e=>!!Vo(e).stream,ls=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},qo=e=>{const t=Vo(e),n=ls(t.user_message_id)??ls(t.respond_mesg_id);return{isStreaming:!!t.stream,hasResponseMetadata:Object.prototype.hasOwnProperty.call(t,"stream")||n!==void 0,...n!==void 0&&{userMessageId:n}}},bt="sb-agent",Yo="KEY_IMG_ASPECT_RATIO",ir="*/*",te={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||{}),Pt=(e=>(e.IN_PROGRESS="IN_PROGRESS",e.COMPLETED="COMPLETED",e.CANCELED="CANCELED",e))(Pt||{});const hc=e=>!!(e!=null&&e.cta_button),fc=e=>{var t;return!!((t=e==null?void 0:e.citations)!=null&&t.length)},Wo=e=>!!(e!=null&&e.form)&&!e.form.canceled_at,gc=e=>{var t;return Wo(e)&&!((t=e==null?void 0:e.form)!=null&&t.submitted_at)},pc=e=>{var t;return!!((t=e==null?void 0:e.suggested_replies)!=null&&t.length)},Ve=e=>{let t;return{enumerable:!0,get:()=>(t??(t=e()),t)}},Rn=e=>Object.defineProperties({},{hasMessageTemplate:Ve(()=>!!(e!=null&&e.message_template)),hasCTAButton:Ve(()=>hc(e)),hasChallenge:Ve(()=>!!(e!=null&&e.challenge)),isThinking:Ve(()=>!!(e!=null&&e.is_thinking)),hasCSAT:Ve(()=>!!(e!=null&&e.csat)),hasSuggestedReplies:Ve(()=>pc(e)),hasCustomMessageTemplates:Ve(()=>{var t;return!!((t=e==null?void 0:e.custom_message_templates)!=null&&t.length)}),hasForm:Ve(()=>Wo(e)),hasActiveForm:Ve(()=>gc(e)),hasSteward:Ve(()=>!!(e!=null&&e.steward)),hasCitations:Ve(()=>fc(e))}),_c=e=>{const t=Rn(e);return t.hasMessageTemplate||t.hasCTAButton||t.hasCSAT||t.hasSuggestedReplies||t.hasForm||t.hasSteward||t.hasCitations},Ko=e=>{var t;return!!((t=e==null?void 0:e.extendedMessagePayload)!=null&&t.steward)},Ec=e=>e===Pt.COMPLETED||e===Pt.CANCELED?e:Pt.IN_PROGRESS,zn=e=>nt(e)&&!Ko(e),nt=e=>!!e&&"sender"in e,Cc=e=>nt(e)?e.sendingStatus==="succeeded"?String(e.messageId):e.reqId:String(e.messageId),bc=(e,t,n,r=!0)=>{if(!r||!zn(e))return"single";const s=()=>{if(!zn(t))return!1;const u=t.sender.userId===e.sender.userId,d=ot.isSameMinute(t.createdAt,e.createdAt);return u&&d},o=()=>{if(!zn(n))return!1;const u=n.sender.userId===e.sender.userId,d=ot.isSameMinute(n.createdAt,e.createdAt);return u&&d},i=s(),c=o();return i&&c?"middle":i?"bottom":c?"top":"single"},mt=(e,t)=>(()=>{var r;return nt(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=>Ko(e),isIncoming:(e,t)=>nt(e)&&e.sender.userId!==t,isOutgoing:(e,t)=>nt(e)&&(e.sender.userId===t||e.sendingStatus===Ke.SendingStatus.PENDING)},We=e=>e.startsWith("image/"),zt=e=>e.startsWith("video/"),vc=e=>e.startsWith("audio/"),jo=({name:e="",mimeType:t=""})=>t==="application/pdf"||/\.pdf$/i.test(e.trim()),Ar=(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"},Xo=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},yc=e=>{if(e.message&&e.message.trim().length>0)return!0;const t=e.extendedMessagePayload;return _c(t)},Mn=e=>{switch(e){case"top":case"middle":return te.GAP_GROUPED;default:return te.GAP_UNGROUPED}},Sc=(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},Ac=e=>e.replace(/\[([^\]]+)\](?!\()/g,"\\[$1\\]"),Tc=e=>e.replace(/([a-zA-Z0-9])_(?=[a-zA-Z0-9])/g,"$1\\_"),Ic=e=>e.replace(/~~/g,"\\~\\~"),xc=e=>{let t=e;return t=Ac(t),t=Tc(t),t=Ic(t),t},Rc=typeof navigator<"u"&&navigator.product==="ReactNative",us=(e,t)=>{const n=r=>!t||t.length===0?!0:nt(r)&&t.includes(r.sendingStatus);return Rc?e.find(n):e.findLast(n)};function le(){}function Mc(){const e=typeof navigator<"u"?navigator.userAgent:"",t=/iPad|iPhone|iPod/.test(e),n=/Android/.test(e);return t||n}function wc(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 Me={isStreaming(e){return mc(e.data)},isExplicitWelcomeMessage(e){var t;return((t=e.extendedMessagePayload)==null?void 0:t.bot_message_type)==="welcome"},isWelcomeMessage(e,t){var r;if(Me.isExplicitWelcomeMessage(e))return!0;if(((r=e.extendedMessagePayload)==null?void 0:r.bot_message_type)!==void 0||!mt(e,t))return!1;const n=qo(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)}},Vn=`@${bt}`,kc=({appId:e,aiAgentId:t,storage:n})=>{const r={templateBase:`${Vn}-template`,template:s=>`${r.templateBase}/templates/${s}`,templateToken:()=>`${r.templateBase}/tokens`,messengerSession:s=>{const o=wc(`${e}/${t}/${s}`);return`${Vn}-udata/${o}`},anonUserSession:()=>`${Vn}-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}}}}},Zo=(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},Lc=()=>{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 Oc{constructor(t){S(this,"_params");this._params={aiAgentChannelFilter:(t==null?void 0:t.aiAgentChannelFilter)??Se.AIAgentChannelFilter.INCLUDE,aiAgentConversationStatusFilter:(t==null?void 0:t.aiAgentConversationStatusFilter)??[Se.ConversationStatus.OPEN,Se.ConversationStatus.CLOSED],aiAgentIds:(t==null?void 0:t.aiAgentIds)??[],deskChannelFilter:(t==null?void 0:t.deskChannelFilter)??Se.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===Se.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!==Se.DeskChannelFilter.EXCLUDE:!1}}class Jo extends Ze.BaseChannelCollection{constructor(n,r){const s=new Oc(r.filter),o=n,i=o.aiAgent._manager,c=r.limit??20,u=Ze.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:E}=s.params,_={aiAgentChannelFilter:h,aiAgentIds:f,deskChannelFilter:g,pinnedChannelUrls:p,copilotConversationOnly:v,copilotSupportChannelUrl:E};return i.getMyGroupChannelChangeLogs(m,_,Ze.GroupChannelEventSource.SYNC_CHANNEL_CHANGELOGS)}};super(o.aiAgent._iid,{filter:s,order:u,limit:c,syncKeyPrefix:"aiAgent",fetcher:d});S(this,"_params");S(this,"_sdk");S(this,"_throttledOnChannelChanged");S(this,"_key");S(this,"_pendingChannels",[]);this._sdk=n,this._params=r,this._key=`clc-${Lc()}`,this._throttledOnChannelChanged=Zo(()=>{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 E=Array.from(v.values()),_=(g=this._sdk.currentUser)==null?void 0:g.userId,y=E.filter(T=>this.filter.match(T,_)),A=E.filter(T=>!this.filter.match(T,_)).map(T=>T.url);y.length>0&&this._base._addChannelsToView(y,p,!1),A.length>0&&this._removeChannels(A,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 Qo{constructor(t){S(this,"subscribers",{});this.logger=t}async send(t){const n=Nc(),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 Nc=()=>{let e=le,t=le;return{promise:new Promise((r,s)=>{e=r,t=s}),resolve:e,reject:t}};var Ye=(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))(Ye||{});class Vt{constructor(t={}){S(this,"payload");this.payload=t}toJSON(){return JSON.stringify({type:this.type,payload:this.payload})}}const it={CloseConversation:e=>new Dc(e),MessengerSettingsUpdated:e=>new $c(e),ActiveChannelUpdated:e=>new Fc(e),AnonymousSessionTokenExpired:()=>new Pc,AuthTokenRefreshed:()=>new Uc};class Dc extends Vt{constructor(){super(...arguments);S(this,"type","conv.close")}}class $c extends Vt{constructor(){super(...arguments);S(this,"type","messenger.settings.updated")}}class Fc extends Vt{constructor(){super(...arguments);S(this,"type","active.channel.updated")}}class Pc extends Vt{constructor(){super(...arguments);S(this,"type","anon.token.expired")}}class Uc extends Vt{constructor(){super(...arguments);S(this,"type","auth.token.refreshed")}}var Tr=(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))(Tr||{});class ei{constructor(t){S(this,"level");this.level=t}verbose(...t){this.level<=0&&console.log(`[${bt}/verbose]`,...t)}debug(...t){this.level<=1&&console.log(`[${bt}/debug]`,...t)}info(...t){this.level<=2&&console.log(`[${bt}/info]`,...t)}warn(...t){this.level<=3&&console.warn(`[${bt}/warn]`,...t)}error(...t){this.level<=4&&console.error(`[${bt}/error]`,...t)}}class ti{constructor({userId:t,authToken:n,sessionHandler:r}){S(this,"userId");S(this,"authToken");S(this,"sessionHandler");this.userId=t,this.authToken=n,this.sessionHandler=r}}class ar{constructor(){S(this,"userId");S(this,"authToken");S(this,"sessionHandler")}}const Bc=e=>({onSessionTokenRequired:t=>{t(null),e.send(it.AnonymousSessionTokenExpired())}}),ni="ai_agent:stats",Hc="conversation_initial_render",ds="conversation_not_interactive_timeout",Gc="recovery_not_interactive_timeout",zc="conversation_list_initial_render",Vc="message_pending_stuck",ms="aiev_auth_expired_unhandled",qc="user_perceived_response_time",Yc="stream_stalled",Wc="ai_typing_indicator_absent_timeout",Kc="rendered_content_unusable",ri=800220;var he=(e=>(e.AUTH="auth_duration_ms",e.GET_CHANNEL="get_channel_duration_ms",e.GET_MESSAGES="get_messages_duration_ms",e.TOTAL_DURATION="total_duration_ms",e.TOTAL_DURATION_FROM_CACHE="total_duration_from_cache_ms",e))(he||{});const En={now:()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()},si=(e,t,n)=>{const r={key:e,value:String(t)};return(n==null?void 0:n.conversationId)!==void 0&&(r.conversation_id=n.conversationId),n!=null&&n.error&&(r.error_code=n.error.code??ri,r.error_description=n.error.message??""),n!=null&&n.extra&&Object.keys(n.extra).length>0&&(r.extra=n.extra),r},It=e=>(e==null?void 0:e.clock)??En,jc=((e,t)=>setTimeout(e,t)),Xc=(e=>clearTimeout(e)),qt=e=>(e==null?void 0:e.setTimeout)??jc,Yt=e=>(e==null?void 0:e.clearTimeout)??Xc,Qe=(e,t,n,r)=>e(ni,si(t,n,r)),Ae=(e,t)=>{e!==null&&t(e)},wn=(e,t)=>{if(e.size<t)return;const n=e.keys().next();n.done||e.delete(n.value)},dt=(e,t)=>!(e.channelUrl&&t&&e.channelUrl!==t),oi=(e,t)=>{for(const n of e)if(n.userMessageId===void 0&&dt(n,t))return!0;return!1};class Zc{constructor(t){S(this,"callback");this.callback=t}onPayloadParseFailed(t){Qe(this.callback,ms,"payload_parse_failed",{extra:{agent_id:t.aiAgentId}})}onCallbackNotFound(t){Qe(this.callback,ms,"callback_not_found",{extra:{agent_id:t.aiAgentId}})}clear(){}}class Jc{constructor(){S(this,"timers",new Map);S(this,"committed",!1);S(this,"commitCallback",null);S(this,"conversationId",null);S(this,"channelUrl",null);S(this,"errorCode",null);S(this,"errorDescription",null);S(this,"extraData",{})}setCommitCallback(t){return this.commitCallback=t,this}setConversationId(t){return this.conversationId=t,this}setChannelUrl(t){return this.setExtra("channel_url",t),this}setError(t,n){return this.errorCode=t??ri,this.errorDescription=n,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:En.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:En.now()}),this)}getDuration(t){const n=this.timers.get(t);return!n||n.startTime===null||n.endTime===null?null:n.endTime-n.startTime}isCommitted(){return this.committed}commit(){if(this.committed||!this.commitCallback)return!1;const t=this.buildPayload();return t?(this.committed=!0,this.commitCallback(ni,t)):!1}}class Qc extends Jc{constructor(){super(...arguments);S(this,"presentMethod","direct_present")}setPresentMethod(n){return this.presentMethod=n,this}getMetricKey(){return Hc}buildPayload(){const n=this.getDuration(he.AUTH),r=this.getDuration(he.GET_CHANNEL),s=this.getDuration(he.GET_MESSAGES),o=this.getDuration(he.TOTAL_DURATION_FROM_CACHE),i=this.getDuration(he.TOTAL_DURATION),c={...this.extraData,present_method:this.presentMethod,...n!==null&&{[he.AUTH]:n},...r!==null&&{[he.GET_CHANNEL]:r},...s!==null&&{[he.GET_MESSAGES]:s},...o!==null&&{[he.TOTAL_DURATION_FROM_CACHE]:o}};return si(this.getMetricKey(),i??0,{conversationId:this.conversationId??void 0,error:this.errorCode!==null?{code:this.errorCode,message:this.errorDescription??""}:void 0,extra:c})}}class el{constructor(t){S(this,"commitCallback");S(this,"apiResultReceived",!1);S(this,"channelUrl");S(this,"consumed",!1);S(this,"consumedByAuthError",!1);S(this,"presentMethod","direct_present");S(this,"renderedAfterApiResult",!1);S(this,"stats",null);this.commitCallback=t}getOrCreateStats(){var t;return this.consumed?null:(t=this.stats)!=null&&t.isCommitted()?(this.consumed=!0,null):(this.stats||(this.stats=new Qc().setCommitCallback(this.commitCallback).setPresentMethod(this.presentMethod),this.apiResultReceived=!1,this.renderedAfterApiResult=!1),this.stats)}getActiveStats(){return this.consumed||!this.stats||this.stats.isCommitted()?null:this.stats}matchesChannelUrl(t){return t===void 0||this.channelUrl===void 0||t===this.channelUrl}pinChannelUrl(t){var n;return t===void 0?!0:this.matchesChannelUrl(t)?(this.channelUrl=t,(n=this.stats)==null||n.setChannelUrl(t),!0):!1}consume(t){return t&&(this.consumed=!0),t}commitIfReady(t){return this.consumed||!this.stats||this.stats.isCommitted()?!0:!this.matchesChannelUrl(t)||!this.apiResultReceived||!this.renderedAfterApiResult?!1:this.consume(this.stats.stopTimer(he.TOTAL_DURATION).commit())}start(t){const n=this.getOrCreateStats();!n||!this.pinChannelUrl(t)||n.startTimer(he.TOTAL_DURATION).startTimer(he.TOTAL_DURATION_FROM_CACHE)}onAuthStart(){var t;this.consumedByAuthError&&this.clear(),(t=this.getOrCreateStats())==null||t.startTimer(he.AUTH)}onAuthComplete(){var t;(t=this.getActiveStats())==null||t.stopTimer(he.AUTH)}onAuthError(t){const n=this.getActiveStats();n&&this.consume(n.stopTimer(he.AUTH).setError(t instanceof fe.SendbirdError?t.code:void 0,t.message).stopTimer(he.TOTAL_DURATION).commit())&&(this.consumedByAuthError=!0)}onGetChannelStart(t){const n=this.getActiveStats();!n||!this.pinChannelUrl(t)||n.startTimer(he.GET_CHANNEL)}onGetChannelComplete(t){const n=typeof t=="object"?t.channelUrl:void 0,r=typeof t=="object"?t.conversationId:t,s=this.getActiveStats();!s||!this.pinChannelUrl(n)||(s.stopTimer(he.GET_CHANNEL),r!==void 0&&s.setConversationId(r),s.startTimer(he.GET_MESSAGES))}onGetChannelError(t){const n=t instanceof Error?void 0:t.channelUrl,r=t instanceof Error?t:t.error,s=this.getActiveStats();s&&this.pinChannelUrl(n)&&this.consume(s.stopTimer(he.GET_CHANNEL).setError(r instanceof fe.SendbirdError?r.code:void 0,r.message).stopTimer(he.TOTAL_DURATION).commit())}onCacheResult(t){const n=this.getActiveStats();n&&(t&&n.setError(t instanceof fe.SendbirdError?t.code:void 0,t.message),n.stopTimer(he.TOTAL_DURATION_FROM_CACHE))}onApiResult(t){const n=this.getActiveStats();if(n){if(t){this.consume(n.setError(t instanceof fe.SendbirdError?t.code:void 0,t.message).stopTimer(he.TOTAL_DURATION).stopTimer(he.GET_MESSAGES).commit());return}this.apiResultReceived=!0,this.renderedAfterApiResult=!1,n.stopTimer(he.GET_MESSAGES),this.commitIfReady()}}setChannelUrl(t){this.pinChannelUrl(t)}commitPending(){const t=this.getActiveStats();return t?this.consume(t.stopTimer(he.TOTAL_DURATION).commit()):!0}markRendered(t){return this.matchesChannelUrl(t)?(this.renderedAfterApiResult=!0,this.commitIfReady(t)):!1}setPresentMethod(t){var n;this.presentMethod=t,(n=this.getActiveStats())==null||n.setPresentMethod(t)}clear(){this.stats=null,this.apiResultReceived=!1,this.channelUrl=void 0,this.consumed=!1,this.consumedByAuthError=!1,this.renderedAfterApiResult=!1}}const hs=()=>({initialized:!1,listStarted:!1,listCompleted:!1,rendered:!1});class tl{constructor(t,n){S(this,"callback");S(this,"clock");S(this,"measurement",hs());S(this,"renderedCommitted",!1);S(this,"startedAt",null);S(this,"listStartedAt",null);S(this,"authStartedAt",null);S(this,"authDuration",null);S(this,"listDuration",null);S(this,"presentMethod","direct_present");S(this,"committed",!1);this.callback=t,this.clock=It(n)}onInitializeStart(){this.measurement.rendered||(this.measurement.initialized&&this.clearMeasurementState(),this.renderedCommitted=!1,this.startMeasurement())}onListRequestStart(){this.measurement.listStarted&&!this.measurement.listCompleted&&!this.measurement.rendered&&this.clearMeasurementState(),this.markListRequestStartOnce()}onListRequestComplete(){this.markListRequestCompleteOnce()}onRendered(){this.markRenderedOnce()}setPresentMethod(t){this.presentMethod=t}start(t){this.committed||(this.startedAt=this.clock.now(),t&&(this.presentMethod=t))}onAuthStart(){this.committed&&(this.clearMeasurementState(),this.renderedCommitted=!1),this.authDuration=null,this.authStartedAt=this.clock.now()}onAuthComplete(){if(!(this.committed||this.authDuration!==null)){if(this.authStartedAt===null){this.authDuration=0;return}this.authDuration=this.clock.now()-this.authStartedAt,this.authStartedAt=null}}markListRequestStart(){this.committed||(this.startedAt===null&&this.start(),this.listStartedAt=this.clock.now())}markListRequestComplete(){this.committed||this.listStartedAt===null||(this.listDuration=this.clock.now()-this.listStartedAt)}markRendered(){this.committed||this.startedAt===null||(this.committed=!0,Qe(this.callback,zc,this.clock.now()-this.startedAt,{extra:{...this.authDuration!==null&&{auth_duration_ms:this.authDuration},...this.listDuration!==null&&{get_list_duration_ms:this.listDuration},present_method:this.presentMethod}}))}clear(){this.clearMeasurementState(),this.clearAuthState(),this.renderedCommitted=!1}clearMeasurementState(){this.startedAt=null,this.listStartedAt=null,this.listDuration=null,this.committed=!1,this.measurement=hs()}clearAuthState(){this.authStartedAt=null,this.authDuration=null}startMeasurement(){this.measurement.initialized||(this.clearMeasurementState(),this.start(),this.measurement.initialized=!0)}markListRequestStartOnce(){this.startMeasurement(),!this.measurement.listStarted&&(this.markListRequestStart(),this.measurement.listStarted=!0)}markListRequestCompleteOnce(){this.markListRequestStartOnce(),!this.measurement.listCompleted&&(this.markListRequestComplete(),this.measurement.listCompleted=!0)}markRenderedOnce(){this.renderedCommitted||(this.startMeasurement(),!this.measurement.rendered&&(this.markRendered(),this.measurement.rendered=!0,this.renderedCommitted=!0))}}class nl{constructor(t,n){S(this,"callback");S(this,"clock");S(this,"setTimeoutFn");S(this,"clearTimeoutFn");S(this,"measurements",new Map);this.callback=t,this.clock=It(n),this.setTimeoutFn=qt(n),this.clearTimeoutFn=Yt(n)}start(t){const n=this.getKey(t==null?void 0:t.channelUrl);this.clearKey(n);const r={startedAt:this.clock.now(),channelUrl:t==null?void 0:t.channelUrl,conversationId:t==null?void 0:t.conversationId,committed:!1,inputEnabled:!1,phaseReached:"auth",historyLoadResult:"pending",timer:null};r.timer=this.setTimeoutFn(()=>this.commitTimeout(n),1e4),this.measurements.set(n,r)}markChannelJoined(t,n){const r=this.getMeasurement(n);!r||r.committed||(r.phaseReached="channel_join",t!==void 0&&(r.conversationId=t))}markHistoryLoaded(t,n){const r=this.getMeasurement(n);!r||r.committed||(r.phaseReached="history_load",r.historyLoadResult=t,this.cancelIfReady(n))}markInputEnabled(t){const n=this.getMeasurement(t);!n||n.committed||(n.phaseReached="input_enable",n.inputEnabled=!0,this.cancelIfReady(t))}markRendered(t){const n=this.getMeasurement(t);!n||n.committed||(n.phaseReached="render")}clear(){this.measurements.forEach(t=>Ae(t.timer,this.clearTimeoutFn)),this.measurements.clear()}clearChannel(t){t!==void 0&&this.clearKey(this.getKey(t))}clearKey(t){const n=this.measurements.get(t);n&&(Ae(n.timer,this.clearTimeoutFn),this.measurements.delete(t))}cancelIfReady(t){const n=this.getMeasurement(t);!n||!n.inputEnabled||n.historyLoadResult==="pending"||this.clearKey(this.getKey(n.channelUrl))}commitTimeout(t){const n=this.measurements.get(t);!n||n.committed||(n.committed=!0,n.timer=null,Qe(this.callback,ds,this.clock.now()-n.startedAt,{conversationId:n.conversationId,error:{message:ds},extra:{outcome:"timeout",phase_reached:n.phaseReached,history_load_result:n.historyLoadResult}}),this.measurements.delete(t))}getMeasurement(t){return t!==void 0?this.measurements.get(this.getKey(t)):this.measurements.size===1?Array.from(this.measurements.values())[0]:this.measurements.get(this.getKey())}getKey(t){return t??"__default__"}}const rl=5e3,fs=1e4;class sl{constructor(t,n){S(this,"callback");S(this,"setTimeoutFn");S(this,"clearTimeoutFn");S(this,"measurements",new Map);this.callback=t,this.setTimeoutFn=qt(n),this.clearTimeoutFn=Yt(n)}start(t){if(!t.requestId||this.measurements.has(t.requestId))return;const n=t.messageType!=="text"&&t.tracksUploadProgress===!0,r={channelUrl:t.channelUrl,messageType:t.messageType,stuckReason:n?"upload_no_progress":"pending_too_long",timer:null},s=n?fs:rl;r.timer=this.setTimeoutFn(()=>this.detect(t.requestId),s),this.measurements.set(t.requestId,r)}resolve(t){const n=this.measurements.get(t.requestId);n&&(Ae(n.timer,this.clearTimeoutFn),this.measurements.delete(t.requestId))}disappear(t){const n=this.measurements.get(t.requestId);n&&(Ae(n.timer,this.clearTimeoutFn),this.measurements.delete(t.requestId))}markUploadProgress(t){const n=this.measurements.get(t);n&&n.stuckReason==="upload_no_progress"&&(Ae(n.timer,this.clearTimeoutFn),n.timer=this.setTimeoutFn(()=>this.detect(t),fs))}clear(){this.measurements.forEach(t=>Ae(t.timer,this.clearTimeoutFn)),this.measurements.clear()}clearChannel(t){t&&this.measurements.forEach((n,r)=>{n.channelUrl===t&&(Ae(n.timer,this.clearTimeoutFn),this.measurements.delete(r))})}detect(t){const n=this.measurements.get(t);n&&(this.measurements.delete(t),this.commit(t,n))}commit(t,n){Qe(this.callback,Vc,n.stuckReason,{extra:{message_type:n.messageType,request_id:t}})}}class ol{constructor(t,n){S(this,"callback");S(this,"clock");S(this,"setTimeoutFn");S(this,"clearTimeoutFn");S(this,"measurements",new Map);this.callback=t,this.clock=It(n),this.setTimeoutFn=qt(n),this.clearTimeoutFn=Yt(n)}start(t,n){const r=this.getKey(n);let s=this.measurements.get(r);s&&s.startedAt!==null||s!=null&&s.inputEnabled||(s={startedAt:this.clock.now(),triggerType:t,inputEnabled:(s==null?void 0:s.inputEnabled)??!1,timer:this.setTimeoutFn(()=>this.commitTimeout(r),1e4)},this.measurements.set(r,s))}setInputEnabled(t,n){const r=this.getKey(n);let s=this.measurements.get(r);if(!s){if(!t)return;s={startedAt:null,triggerType:null,inputEnabled:t,timer:null},this.measurements.set(r,s)}s.inputEnabled=t,t&&this.cancelMeasurement(s)}cancelPending(t){const n=this.getKey(t),r=this.measurements.get(n);r&&(this.cancelMeasurement(r),r.inputEnabled||this.measurements.delete(n))}clear(){this.measurements.forEach(t=>Ae(t.timer,this.clearTimeoutFn)),this.measurements.clear()}clearChannel(t){t!==void 0&&this.clearKey(this.getKey(t))}clearKey(t){const n=this.measurements.get(t);n&&(Ae(n.timer,this.clearTimeoutFn),this.measurements.delete(t))}commitTimeout(t){const n=this.measurements.get(t);if(!n||n.startedAt===null||n.triggerType===null)return;if(n.inputEnabled){this.cancelMeasurement(n);return}const r=this.clock.now()-n.startedAt,s=n.triggerType;this.measurements.delete(t),Qe(this.callback,Gc,r,{extra:{trigger_type:s}})}cancelMeasurement(t){Ae(t.timer,this.clearTimeoutFn),t.timer=null,t.startedAt=null,t.triggerType=null}getKey(t){return t??"__default__"}}const il=500;class al{constructor(t){S(this,"callback");S(this,"committed",new Set);this.callback=t}commit(t){const n=`${t.messageId}:${t.contentKind}:${t.errorDomain}`;this.committed.has(n)||(wn(this.committed,il),this.committed.add(n),Qe(this.callback,Kc,t.errorDomain,{error:t.error?{code:t.error.code,message:t.errorDomain}:void 0,extra:{content_kind:t.contentKind,message_id:String(t.messageId)}}))}clear(){this.committed.clear()}}const gs=1e4,Ct=5e3,cl=500;class ll{constructor(t,n){S(this,"callback");S(this,"clock");S(this,"setTimeoutFn");S(this,"clearTimeoutFn");S(this,"streams",new Map);S(this,"emittedMessageChannels",new Map);this.callback=t,this.clock=It(n),this.setTimeoutFn=qt(n),this.clearTimeoutFn=Yt(n)}markRawProgress(t){if(!t.aiResponse.isStreaming){this.completeDelivery(t.messageId,t.textLength);return}if(this.emittedMessageChannels.has(t.messageId))return;const n=this.getOrCreate(t.messageId,t.channelUrl);t.textLength>n.lastRawLength?(n.chunksReceived+=1,n.lastRawLength=t.textLength,n.lastRawAt=this.clock.now(),Ae(n.deliveryTimer,this.clearTimeoutFn),n.deliveryTimer=null,this.scheduleDeliveryStallCheck(t.messageId,n)):this.scheduleDeliveryStallCheck(t.messageId,n),n.lastRenderedLength<n.lastRawLength&&n.renderTimer===null&&(n.lastRenderAt=this.clock.now(),this.scheduleRenderStallCheck(t.messageId,n,Ct))}markRenderedProgress(t){const n=this.streams.get(t.messageId);if(!(!n||t.displayedLength<=n.lastRenderedLength)){if(n.lastRenderedLength=t.displayedLength,n.lastRenderAt=this.clock.now(),n.lastRenderedLength>=n.lastRawLength){if(n.deliveryTimer===null){this.clearStream(t.messageId,n);return}Ae(n.renderTimer,this.clearTimeoutFn),n.renderTimer=null;return}this.scheduleRenderStallCheck(t.messageId,n,Ct)}}hasPendingStream(t){return this.streams.has(t)}complete(t){const n=this.streams.get(t);n&&this.clearStream(t,n)}completeDelivery(t,n){const r=this.streams.get(t);if(r){if(n>r.lastRawLength&&(r.lastRawLength=n,r.lastRawAt=this.clock.now()),Ae(r.deliveryTimer,this.clearTimeoutFn),r.deliveryTimer=null,r.lastRenderedLength>=r.lastRawLength){this.clearStream(t,r);return}r.renderTimer===null&&(r.lastRenderAt=this.clock.now(),this.scheduleRenderStallCheck(t,r,Ct))}}clearMessage(t){const n=this.streams.get(t);n&&this.clearStream(t,n),this.emittedMessageChannels.delete(t)}clear(){this.streams.forEach(t=>{Ae(t.deliveryTimer,this.clearTimeoutFn),Ae(t.renderTimer,this.clearTimeoutFn)}),this.streams.clear(),this.emittedMessageChannels.clear()}clearChannel(t){t&&(this.streams.forEach((n,r)=>{n.channelUrl!==t&&n.channelUrl!==void 0||this.clearStream(r,n)}),this.emittedMessageChannels.forEach((n,r)=>{(n===t||n===void 0)&&this.emittedMessageChannels.delete(r)}))}detectDelivery(t){const n=this.streams.get(t);n&&(n.deliveryTimer=null,Ae(n.renderTimer,this.clearTimeoutFn),n.renderTimer=null,this.emit(t,n,"delivery"))}detectRender(t){const n=this.streams.get(t);if(!n||(n.renderTimer=null,n.lastRenderedLength>=n.lastRawLength))return;const r=this.clock.now()-n.lastRenderAt;if(r<Ct){this.scheduleRenderStallCheck(t,n,Ct-r);return}const s=this.clock.now()-n.lastRawAt;if(s>=Ct&&n.deliveryTimer!==null){const o=gs-s;if(o>0){this.scheduleRenderStallCheck(t,n,o);return}}this.emit(t,n,"render")}scheduleRenderStallCheck(t,n,r){n.renderTimer===null&&(n.renderTimer=this.setTimeoutFn(()=>this.detectRender(t),r))}scheduleDeliveryStallCheck(t,n){n.deliveryTimer===null&&(n.deliveryTimer=this.setTimeoutFn(()=>this.detectDelivery(t),gs))}emit(t,n,r){if(this.emittedMessageChannels.has(t))return;const s=r==="delivery"?n.lastRawAt:n.lastRenderAt;Qe(this.callback,Yc,this.clock.now()-s,{extra:{message_id:String(t),stall_kind:r}}),this.rememberEmitted(t,n.channelUrl),this.clearStream(t,n)}getOrCreate(t,n){const r=this.streams.get(t);if(r)return r;const s=this.clock.now(),o={channelUrl:n,chunksReceived:0,lastRawAt:s,lastRenderAt:s,lastRawLength:0,lastRenderedLength:0,deliveryTimer:null,renderTimer:null};return this.streams.set(t,o),o}rememberEmitted(t,n){this.emittedMessageChannels.has(t)||wn(this.emittedMessageChannels,cl),this.emittedMessageChannels.set(t,n)}clearStream(t,n){Ae(n.deliveryTimer,this.clearTimeoutFn),Ae(n.renderTimer,this.clearTimeoutFn),this.streams.delete(t)}}const ps=3e3,ul=3e4;class dl{constructor(t,n){S(this,"callback");S(this,"clock");S(this,"setTimeoutFn");S(this,"clearTimeoutFn");S(this,"turns",new Map);S(this,"pendingAIResponseStartsByUserMessageId",new Map);this.callback=t,this.clock=It(n),this.setTimeoutFn=qt(n),this.clearTimeoutFn=Yt(n)}startTurn(t){this.cancelTurn(t.requestId);const n={requestId:t.requestId,channelUrl:t.channelUrl,beforeTpstStartedAt:this.clock.now(),afterTpenStartedAt:null,timer:null};n.timer=this.setTimeoutFn(()=>this.commitTimeout(n.requestId),ul),this.turns.set(t.requestId,n)}markUserMessageAck(t){const n=this.turns.get(t.requestId);if(!n)return;n.userMessageId=t.messageId;const r=this.pendingAIResponseStartsByUserMessageId.get(t.messageId);r&&(this.pendingAIResponseStartsByUserMessageId.delete(t.messageId),this.applyAIResponseStarted({channelUrl:r.channelUrl,matchesUserMessage:!0,userMessageId:t.messageId},r.startedAt))}replaceTurnRequestId(t,n){if(t===n)return;const r=this.turns.get(t);r&&(this.turns.delete(t),r.requestId=n,this.turns.set(n,r))}cancelTurn(t){this.cleanupTurn(t)}markTypingStarted(t){const n=this.clock.now();this.turns.forEach(r=>{dt(r,t)&&(this.recordAfterTpen(r,n),this.recordBeforeTpst(r,n))})}markTypingEnded(t){const n=this.clock.now();this.turns.forEach(r=>{dt(r,t)&&(this.recordBeforeTpst(r,n),r.afterTpenStartedAt=n)})}markAIResponseStarted(t={}){const n=t.channelUrl,r=t.userMessageId,s=r!==void 0,o=this.clock.now();this.applyAIResponseStarted({channelUrl:n,matchesUserMessage:s,userMessageId:r},o)||!s||r===void 0||!this.hasUnackedTurn(n)||this.pendingAIResponseStartsByUserMessageId.has(r)||(wn(this.pendingAIResponseStartsByUserMessageId,100),this.pendingAIResponseStartsByUserMessageId.set(r,{channelUrl:n,startedAt:o}))}applyAIResponseStarted(t,n){if(!t.matchesUserMessage){const s=this.findSingleTurn(t.channelUrl);return s?(this.completeTurn(s.requestId,s.turn,n),!0):!1}let r=!1;return this.turns.forEach((s,o)=>{dt(s,t.channelUrl)&&(t.matchesUserMessage&&s.userMessageId!==t.userMessageId||(r=!0,this.completeTurn(o,s,n)))}),r}findSingleTurn(t){let n,r=0;return this.turns.forEach((s,o)=>{dt(s,t)&&(r+=1,!(r>1)&&(n={requestId:o,turn:s}))}),r===1?n:void 0}completeTurn(t,n,r){this.recordBeforeTpst(n,r),this.recordAfterTpen(n,r),this.commitIfAbsent(t,n)}hasUnackedTurn(t){return oi(this.turns.values(),t)}clear(){this.turns.forEach(t=>{Ae(t.timer,this.clearTimeoutFn)}),this.turns.clear(),this.pendingAIResponseStartsByUserMessageId.clear()}clearChannel(t){t&&(this.turns.forEach((n,r)=>{n.channelUrl===t&&this.cleanupTurn(r)}),this.pendingAIResponseStartsByUserMessageId.forEach((n,r)=>{n.channelUrl===t&&this.pendingAIResponseStartsByUserMessageId.delete(r)}))}commitTimeout(t){const n=this.turns.get(t);if(!n)return;const r=this.clock.now();this.recordBeforeTpst(n,r),this.recordAfterTpen(n,r),this.commitIfAbsent(t,n)}recordBeforeTpst(t,n){if(t.beforeTpstStartedAt===null)return;const r=n-t.beforeTpstStartedAt;r>=ps&&(t.beforeTpstAbsentMs=r),t.beforeTpstStartedAt=null}recordAfterTpen(t,n){if(t.afterTpenStartedAt===null)return;const r=n-t.afterTpenStartedAt;r>=ps&&(t.afterTpenAbsentMs=r),t.afterTpenStartedAt=null}commitIfAbsent(t,n){const r=n.beforeTpstAbsentMs,s=n.afterTpenAbsentMs;if(r===void 0&&s===void 0){this.cleanupTurn(t);return}Qe(this.callback,Wc,(r??0)+(s??0),{extra:{...r!==void 0&&{before_tpst_absent_ms:r},...s!==void 0&&{after_tpen_absent_ms:s}}}),this.cleanupTurn(t)}cleanupTurn(t){const n=this.turns.get(t);n&&(Ae(n.timer,this.clearTimeoutFn),this.turns.delete(t))}}class ml{constructor(t,n){S(this,"callback");S(this,"clock");S(this,"random");S(this,"sampledByRequestId",new Map);S(this,"sampledByAIMessageId",new Map);S(this,"pendingAIResponseByUserMessageId",new Map);S(this,"collectedCount",0);this.callback=t,this.clock=It(n),this.random=(n==null?void 0:n.random)??Math.random}startTurn(t){this.collectedCount>=10||this.random()>=.15||(this.collectedCount+=1,this.sampledByRequestId.set(t.requestId,{requestId:t.requestId,channelUrl:t.channelUrl,startedAt:this.clock.now()}))}markUserMessageAck(t){const n=this.sampledByRequestId.get(t.requestId);if(!n)return;n.ackAt=this.clock.now(),n.userMessageId=t.messageId;const r=this.pendingAIResponseByUserMessageId.get(t.messageId);r&&(this.pendingAIResponseByUserMessageId.delete(t.messageId),this.applyAIResponseRaw(n,r))}replaceTurnRequestId(t,n){if(t===n)return;const r=this.sampledByRequestId.get(t);r&&(this.sampledByRequestId.delete(t),r.requestId=n,this.sampledByRequestId.set(n,r))}cancelTurn(t){const n=this.sampledByRequestId.get(t);n&&(this.deleteTurn(n),this.collectedCount>0&&(this.collectedCount-=1))}markAIResponseRaw(t){const n=this.clock.now(),r=t.aiResponse.userMessageId;if(r===void 0&&this.hasUnackedTurn(t.channelUrl))return;const s=this.findPendingTurn(t.channelUrl,r);if(s){this.applyAIResponseRaw(s,{...t,firstChunkAt:n});return}r===void 0||!this.hasUnackedTurn(t.channelUrl)||this.bufferAIResponseRaw({messageId:t.messageId,...t.channelUrl!==void 0&&{channelUrl:t.channelUrl},aiResponse:t.aiResponse,firstChunkAt:n},r)}markAIResponseVisible(t){const n=this.sampledByAIMessageId.get(t);if(!n||n.ackAt===void 0||n.firstChunkAt===void 0||n.userMessageId===void 0)return!1;const r=this.clock.now();return Qe(this.callback,qc,r-n.startedAt,{extra:{ack_to_first_chunk_ms:n.firstChunkAt-n.ackAt,first_chunk_to_render_ms:r-n.firstChunkAt,is_streaming:!!n.isStreaming,send_to_ack_ms:n.ackAt-n.startedAt}}),this.deleteTurn(n),!0}hasPendingAIResponse(t){return this.sampledByAIMessageId.has(t)}clearMessage(t){this.pendingAIResponseByUserMessageId.forEach((r,s)=>{r.messageId===t&&this.pendingAIResponseByUserMessageId.delete(s)});const n=this.sampledByAIMessageId.get(t);n&&(this.deleteTurn(n),this.collectedCount>0&&(this.collectedCount-=1))}clearChannel(t){t&&(this.sampledByRequestId.forEach(n=>{n.channelUrl===t&&(this.deleteTurn(n),this.collectedCount>0&&(this.collectedCount-=1))}),this.pendingAIResponseByUserMessageId.forEach((n,r)=>{n.channelUrl===t&&this.pendingAIResponseByUserMessageId.delete(r)}))}clear(){this.sampledByRequestId.clear(),this.sampledByAIMessageId.clear(),this.pendingAIResponseByUserMessageId.clear(),this.collectedCount=0}findPendingTurn(t,n){if(n!==void 0){for(const s of this.sampledByRequestId.values())if(!(s.ackAt===void 0||s.firstChunkAt!==void 0)&&dt(s,t)&&s.userMessageId===n)return s;return}let r;for(const s of this.sampledByRequestId.values())if(!(s.ackAt===void 0||s.firstChunkAt!==void 0)&&dt(s,t)){if(r)return;r=s}return r}applyAIResponseRaw(t,n){t.firstChunkAt===void 0&&(t.firstChunkAt=t.ackAt===void 0?n.firstChunkAt:Math.max(n.firstChunkAt,t.ackAt),t.aiMessageId=n.messageId,t.channelUrl=t.channelUrl??n.channelUrl,t.isStreaming=n.aiResponse.isStreaming,this.sampledByAIMessageId.set(n.messageId,t))}bufferAIResponseRaw(t,n){this.pendingAIResponseByUserMessageId.has(n)||(wn(this.pendingAIResponseByUserMessageId,100),this.pendingAIResponseByUserMessageId.set(n,t))}hasUnackedTurn(t){return oi(this.sampledByRequestId.values(),t)}deleteTurn(t){this.sampledByRequestId.delete(t.requestId),t.aiMessageId!==void 0&&this.sampledByAIMessageId.delete(t.aiMessageId),t.userMessageId!==void 0&&this.pendingAIResponseByUserMessageId.delete(t.userMessageId)}}function hl(){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 ii=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0)),_s={isTalkToAgentViewEnabled:!0,scrollMode:"auto",newMessageIndicatorEnabled:!0,senderAvatarEnabled:!0},Ir={conversation:{..._s,messageAlertSoundEnabled:!1,list:{..._s,deferredMarkdownElements:[]},header:{avatarEnabled:!0},input:{camera:{photoEnabled:!0},gallery:{photoEnabled:!0},fileEnabled:!0},fileViewer:{downloadEnabled:!0}},launcher:{unreadBadgeEnabled:!1}},Es=e=>e?{conversation:pl(e.conversation),launcher:fl(e.launcher)}:Ir,fl=e=>vt(Ir.launcher,e),gl=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},pl=e=>{const t=Ir.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={...vt(t.list,c,n),deferredMarkdownElements:gl(n)};return{...h,messageAlertSoundEnabled:i,list:h,header:vt(t.header,r),input:{camera:vt(t.input.camera,u),gallery:vt(t.input.gallery,d),fileEnabled:m},fileViewer:vt(t.fileViewer,o)}},vt=(e,...t)=>{const n={...e};for(const r of t)r&&Object.assign(n,ii(r));return n},_l=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}),El=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}),ai=(e,t)=>{if(e)return e.members.filter(n=>n.userId!==t).sort((n,r)=>r.joinedAt-n.joinedAt)[0]},Be=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===Se.ConversationStatus.CLOSED||e!=null&&e.isDesk&&((n=e==null?void 0:e.helpdeskInfo)==null?void 0:n.ticketStatus)==="closed")},xr=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===Se.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 Cl(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 bl(e){var t;if(((t=e==null?void 0:e.resolution)==null?void 0:t.determinedBy)==="user")return e.resolution.isResolved}function ci(e){return!!e&&e<=Date.now()}function vl(e){return!e.title}function yl(e,t){var n;if(e)return vl(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 Sl{constructor(){S(this,"_channelHandlerId",null);S(this,"_connectionHandlerId",null);S(this,"_handleActiveChannelChangedThrottled",null);S(this,"_setupChannelHandler",()=>{const t=Date.now();this._channelHandlerId=`aiagent_channel_${t}`,this._connectionHandlerId=`aiagent_connection_${t}`,this._handleActiveChannelChangedThrottled=Zo(s=>{var o,i;(i=this._session)==null||i._updateActiveChannel({url:s.url,status:Be(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 Ze.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 fe.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})});S(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")});S(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:Be(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)}});S(this,"_initConversationIfNeeded",async t=>{if(t.isAIAgent&&!t.conversation)try{await t.initConversation({aiAgentId:this.aiAgentId})}catch(n){this._logger.warn("AIAgentEventManager: initConversation failed",n)}});S(this,"onMessengerSettingsUpdated",t=>(this._dispatcher.subscribe(Ye.MessengerSettingsUpdated,t),()=>{this._dispatcher.unsubscribe(Ye.MessengerSettingsUpdated,t)}));S(this,"onActiveChannelUpdated",t=>(this._dispatcher.subscribe(Ye.ActiveChannelUpdated,t),()=>{this._dispatcher.unsubscribe(Ye.ActiveChannelUpdated,t)}));S(this,"onAuthTokenRefreshed",t=>(this._dispatcher.subscribe(Ye.AuthTokenRefreshed,t),()=>{this._dispatcher.unsubscribe(Ye.AuthTokenRefreshed,t)}))}}class Al{constructor(t){S(this,"_sdkUser");S(this,"_userSession");S(this,"_dispatcher");S(this,"_activeChannel");S(this,"_updateActiveChannel",t=>{this._activeChannel=t,this._dispatcher.send(it.ActiveChannelUpdated({channelUrl:t.url,status:t.status,conversationStatus:t.conversationStatus}))});S(this,"_updateAuthToken",t=>{this._userSession.authToken=t,this._dispatcher.send(it.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),Tl=e=>JSON.parse(e);function Il(e,t){const[n,r]=t.split(",").map(s=>s.trim());return e==="dark"&&r||n}function xl(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 Rl({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 Ml({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 Rr=(e=>(e[e.EXTERNAL_AUTH_TOKEN_EXPIRED=1]="EXTERNAL_AUTH_TOKEN_EXPIRED",e))(Rr||{});const di=e=>typeof e=="object"&&e!==null,Cs=(e,t)=>t in e&&typeof e[t]=="string"&&e[t]!=="",wl=e=>!di(e)||!Cs(e,"channel_url")||!Cs(e,"ai_agent_id")?null:{channelUrl:e.channel_url,aiAgentId:e.ai_agent_id},kl={1:wl};function Ll(e){if(!di(e)||!("cat"in e)||typeof e.cat!="number"||!("data"in e))return null;const t=e.cat,n=kl[t];if(!n)return null;const r=n(e.data);return r?{category:t,data:r}:null}function Ol(e,t,n,r){const s=uc.default.init({appId:e,modules:[new Ze.GroupChannelModule,new Se.AIAgentModule],localCacheEnabled:!0,options:new fe.SendbirdChatOptions({typingIndicatorInvalidateTime:2e4}),...r});return s.addSendbirdExtensions([{version:n,product:fe.SendbirdProduct.AI_AGENT,platform:t.platform}],{platform:t.deviceOSPlatform,version:t.deviceOSVersion},t.customData)||console.warn("Invalid Sendbird Extensions",t),s}function Nl(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 Dl=[400300,400301,400302,400310],$l=Rr.EXTERNAL_AUTH_TOKEN_EXPIRED.toString(),Fl=e=>`${$l}:${e}`;class Mr{constructor(t,n,r,s,o){S(this,"chatSDK");S(this,"_aiAgentId");S(this,"_externalAuthTokenExpiredEventHandlerKey");S(this,"_logger");S(this,"_cache");S(this,"_statsTrackers");S(this,"_sessionHandler");S(this,"_aiEventHandlerRegistered",!1);S(this,"connect",async(t,n,r,s)=>{if(this._logger.debug("ChatClient.connect: start",t.userId),n){this._sessionHandler=n;const o=new fe.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}});S(this,"_registerAIEventHandler",()=>{this._aiEventHandlerRegistered||(this._aiEventHandlerRegistered=!0,this.chatSDK.aiAgent.addEventHandler(this._externalAuthTokenExpiredEventHandlerKey,this._handleAIEvent))});S(this,"_handleAIEvent",t=>{var o;this._logger.debug("ChatClient.connect: EXTERNAL_AUTH_TOKEN_EXPIRED event received",t);const n=Ll(t),r=typeof t.cat=="number"?t.cat:void 0;if(r!==void 0&&r!==Rr.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)});S(this,"dispose",()=>{this._aiEventHandlerRegistered&&(this.chatSDK.aiAgent.removeEventHandler(this._externalAuthTokenExpiredEventHandlerKey),this._aiEventHandlerRegistered=!1),this._sessionHandler=void 0});S(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")});S(this,"getChannel",async t=>this.chatSDK.groupChannel.getChannel(t));S(this,"patchContext",async(t,n,r)=>this.chatSDK.aiAgent.patchContext(t,n,r));S(this,"updateContext",async(t,n,r)=>this.chatSDK.aiAgent.updateContext(t,n,r));S(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});S(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});S(this,"clearUserMemories",async(t={})=>{this._logger.debug("ChatClient.clearUserMemories: requesting",t),await this.chatSDK.aiAgent.clearUserMemories(t),this._logger.debug("ChatClient.clearUserMemories: completed")});S(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)})}});S(this,"_isCacheRestrictedError",t=>Dl.some(n=>t.code===n));S(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=Fl(n),this._logger=r,this._cache=s,this._statsTrackers=o}static init(t){let n;return t.chatSDK?(Nl(t.chatSDK),n=t.chatSDK):n=Ol(t.appId,t.extensions,t.messengerVersion,t.chatParams),new Mr(n,t.aiAgentId,t.logger,t.cache,t.statsTrackers)}}const tn=new Map,mi={set:(e,t)=>{tn.set(e,t)},get:e=>{if(tn.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=tn.get(e);if(!n)throw new Error(`AIAgent platform "${e}" is not configured.`);return{platform:e,...n}}const t=tn.entries().next().value;return{platform:t[0],...t[1]}}};class bs extends Error{constructor(n,r){const s=(r==null?void 0:r.detail)??"";super(s||`Desk API error (${n})`);S(this,"status");S(this,"code");S(this,"detail");this.name="DeskApiError",this.status=n,this.code=(r==null?void 0:r.code)??"",this.detail=s}}var wr=(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))(wr||{}),kr=(e=>(e.URGENT="URGENT",e.HIGH="HIGH",e.MEDIUM="MEDIUM",e.LOW="LOW",e))(kr||{}),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 Pl=e=>e==="desk401103"||e==="desk401106"||e==="desk401107"||e==="desk401108"||e==="desk401109";class Ul{constructor(t){S(this,"_appId");S(this,"_apiHost");S(this,"_logger");S(this,"_credential",null);S(this,"_authRefreshPromise",null);S(this,"_onDeskTokenRefreshRequired",async()=>!1);S(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)});S(this,"setCredential",(t,n=async()=>!1)=>{this._authRefreshPromise=null,this._onDeskTokenRefreshRequired=n,this._credential=t});S(this,"clearCredential",()=>{this._authRefreshPromise=null,this._credential=null,this._onDeskTokenRefreshRequired=async()=>!1});S(this,"_handleUnauthorized",async(t,n,r)=>{const s=await this._parseErrorCode(t);if(!Pl(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)});S(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}});S(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))}:{}}));S(this,"_buildParams",t=>new URLSearchParams({sendbirdAppId:this._appId,...t}));S(this,"_buildBody",t=>({sendbirdAppId:this._appId,...t}));S(this,"_buildHeaders",(t,n)=>({"content-type":"application/json",...t&&this._credential?{sendbirdDeskToken:this._credential.deskToken}:{},...n}));S(this,"_toResult",async t=>{if(!t.ok){const r=await t.json().catch(()=>({}));throw new bs(t.status,r)}const n=await t.text();if(n)try{return JSON.parse(n)}catch{throw new bs(t.status,{})}});S(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}.sendbird.com/sapi`,this._logger=t.logger}get credential(){return this._credential}}class Cn{constructor(t,n){S(this,"id");S(this,"title");S(this,"status");S(this,"agent");S(this,"priority");S(this,"group");S(this,"firstResponseTime");S(this,"issuedAt");S(this,"customFields");S(this,"_client");S(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 Cn({id:t.id,title:t.channelName??null,status:t.status2??wr.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??kr.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 Lr{constructor(t){S(this,"_logger");S(this,"_apiClient");S(this,"_onDeskTokenRefreshRequired");S(this,"refreshDeskAuthToken",async t=>this._apiClient.credential?this.authenticate({userId:this._apiClient.credential.userId,accessToken:t,onDeskTokenRefreshRequired:this._onDeskTokenRefreshRequired}):!1);S(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}});S(this,"deauthenticate",()=>{this._apiClient.clearCredential(),this._onDeskTokenRefreshRequired=void 0,this._logger.debug("DeskClient.deauthenticate: token cleared")});S(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")});S(this,"getTicket",async t=>{this._assertAuthenticated(this._apiClient);const n=await this._apiClient.request(`/tickets/${encodeURIComponent(t)}/`,{method:"GET"});return Cn._fromResponse(n,this)});S(this,"createTicket",async t=>{this._assertAuthenticated(this._apiClient);const n=await this._apiClient.request("/tickets/",{method:"POST",body:ii({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 Cn._fromResponse(n,this)});this._logger=t.logger,this._apiClient=new Ul(t)}static init(t){return new Lr(t)}_assertAuthenticated(t){if(t.credential==null)throw new Error("DeskClient is not authenticated")}}class Or{constructor(){S(this,"authenticate",async t=>!1);S(this,"deauthenticate",()=>{});S(this,"refreshDeskAuthToken",async()=>!1);S(this,"setCustomerLanguage",async()=>{});S(this,"getTicket",async()=>{throw new Error("DeskClient is disabled via __SBA_USE_DESK_CLIENT__")})}static init(){return new Or}}function Bl(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 Hl=1440*60*1e3,Gl=typeof __SBA_USE_DESK_CLIENT__>"u"||__SBA_USE_DESK_CLIENT__;function tt(e){if(!e)throw new Error("Not authenticated. Call authenticate() first.")}function zl(e,t){return Object.entries(t).every(([n,r])=>e[n]===r)}const Vl=e=>{const t={conversationInitialRender:new el(e),conversationNotInteractiveTimeout:new nl(e),recoveryNotInteractiveTimeout:new ol(e),conversationListInitialRender:new tl(e),aievAuthExpiredUnhandled:new Zc(e),messagePendingStuck:new sl(e),userPerceivedResponseTime:new ml(e),streamStalled:new ll(e),typingIndicatorAbsentTimeout:new dl(e),renderedContentUnusable:new al(e)};return{...t,clear:()=>{Object.values(t).forEach(n=>n.clear())}}};class bn extends Sl{constructor(n){super();S(this,"appId");S(this,"aiAgentId");S(this,"_chatClient");S(this,"_deskClient");S(this,"_cache");S(this,"_logger");S(this,"_dispatcher");S(this,"_session",null);S(this,"language");S(this,"countryCode");S(this,"context");S(this,"queryParams");S(this,"_config");S(this,"_networkStateAdapter");S(this,"_scheduleForegroundTask");S(this,"_forceCreateChannel");S(this,"_agentVersion");S(this,"_statsTrackers");S(this,"_operationQueue",hl());S(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._logger.debug("AIAgent.dispose: end"))});S(this,"initConversationIfNeeded",n=>this._initConversationIfNeeded(n));S(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(it.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:E,expire_at:_}=h.auto_created_user;this._cache.messenger.setAnonUser({userId:v,authToken:E,expireAt:_}),f={userId:v,authToken:E},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(it.MessengerSettingsUpdated({settings:h,source:"server"}));const g=(()=>{var v;return s.type==="anonymous"?Bc(this._dispatcher):(v=s.userSessionCandidate)==null?void 0:v.sessionHandler})(),p=await this._chatClient.connect(f,g,v=>{var E;this._logger.debug("AIAgent: session token refreshed"),(E=this._session)==null||E._updateAuthToken(v),this._deskClient.refreshDeskAuthToken(v)},()=>{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:v})=>{var E;if(v===hi.ERR_SESSION_KEY_EXPIRED){await new Promise(y=>setTimeout(y,2e3));const _=(E=this._session)==null?void 0:E.userSession.authToken;return _?await this._deskClient.refreshDeskAuthToken(_):!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 Al({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),h}})});S(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")}));S(this,"createConversation",async n=>{tt(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});S(this,"searchConversation",async n=>{if(tt(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:Se.ConversationStatus.OPEN,limit:100}),s=[];for(;r.hasNext;){const o=await r.next();for(const i of o)zl(i.context??{},n.context)&&s.push(i.channelInfo.url)}return this._logger.debug("AIAgent.searchConversation: end",{count:s.length}),s});S(this,"closeConversation",async n=>{var s;tt(this._session),this._logger.debug("AIAgent.closeConversation: start",n);const r=await this._chatClient.getChannel(n);((s=r.conversation)==null?void 0:s.status)===Se.ConversationStatus.OPEN?(await r.closeConversation(),this._session.activeChannel.url===n&&this._session._updateActiveChannel({url:n,status:"closed",conversationStatus:Se.ConversationStatus.CLOSED}),this._logger.debug("AIAgent.closeConversation: end")):this._logger.debug("AIAgent.closeConversation: already closed or not an AI agent conversation")});S(this,"createConversationListCollection",n=>new Jo(this.chatSDK,n??{}));S(this,"patchContext",async(n,r)=>{tt(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??{}}});S(this,"updateContext",async(n,r)=>{tt(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??{}}});S(this,"getContextObject",async n=>{tt(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??{}}});S(this,"clearUserMemories",async(n={})=>{tt(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")});S(this,"setUserMemoryState",async n=>{tt(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(it.MessengerSettingsUpdated({settings:u,source:"cache"}))}return this._logger.debug("AIAgent.setUserMemoryState: end",i.enabled),cr(i)});S(this,"refreshActiveChannel",async n=>{var c,u,d;tt(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});S(this,"_getSessionCandidate",n=>n instanceof ti?{type:"manual",userSessionCandidate:this._getManualSessionInfo(n)}:n instanceof ar?{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});S(this,"_getAnonymousSessionInfo",()=>{const n=this._cache.messenger.getAnonUser();return n?n.expireAt-Hl<=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});S(this,"_getManualSessionInfo",n=>{if(!n||n instanceof ar)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=Es(n.config),this.queryParams=n.queryParams,this._networkStateAdapter=n.networkStateAdapter,this._scheduleForegroundTask=n.scheduleForegroundTask,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}static init(n){var g;const r=mi.get(n.platform),s=n.logger??new ei(n.logLevel??Tr.WARN),o=n.dispatcher??new Qo(s),i=n.useMMKVStorage?Bl(n.useMMKVStorage):r.keyValueStorage,c=n.useMMKVStorage?{...n.chatParams,useMMKVStorageStore:n.useMMKVStorage}:n.chatParams,u=kc({appId:n.appId,aiAgentId:n.aiAgentId,storage:i});let d;const h=Vl((p,v)=>{if(!d)throw new Error("ChatClient is not initialized.");return d.chatSDK.aiAgent.appendStat(p,v)});d=Mr.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=Gl?Lr.init({appId:n.appId,logger:s,customApiHost:(g=n.deskParams)==null?void 0:g.customApiHost}):Or.init();return s.debug("AIAgent.init: created",{appId:n.appId,aiAgentId:n.aiAgentId}),new bn({appId:n.appId,aiAgentId:n.aiAgentId,language:n.language,countryCode:n.countryCode,context:n.context,config:n.config,queryParams:n.queryParams,networkStateAdapter:r.networkStateAdapter,scheduleForegroundTask:r.scheduleForegroundTask??(p=>p()),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=Es(n)}get agentVersion(){return this._agentVersion}set agentVersion(n){this._agentVersion=n}get statsTrackers(){return this._statsTrackers}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}}const Ce=(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 ql(...e){return function({children:n}){return e.reduce((r,s)=>a.createElement(s,null,r),n)}}function Yl(e,t){const n=e.lastMessage;return n!=null&&n.isAdminMessage()?n.message??"":fi(e,t)}function fi(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 Wl(e,t,n){var i;const r=new Date,s=new Date(((i=e.lastMessage)==null?void 0:i.createdAt)||e.createdAt),o=ot.differenceInMinutes(r,s);return o<1?n.justNow:o<60?n.minutesAgo(o):ot.isToday(s)?n.hoursAgo(ot.differenceInHours(r,s)):t(s,n.dateShortFormat)}const Kl=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},nn=e=>Math.max(0,Math.min(255,e)).toString(16).padStart(2,"0"),vs=(e,t)=>{const n=nn(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=Kl(e);return r?`#${nn(r[0])}${nn(r[1])}${nn(r[2])}${n}`:e},jl=(e,t)=>{if(!t)return e;const n={...e};for(const[r,s]of Object.entries(t))s&&(n[r]=s);return n},Xl=e=>e.consentDialog?"consent":e.toggleAllowed?e.enabled?"on":"off":"readonly",Zl=e=>e.length>0,Jl=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},ys=e=>e.length===0?"empty":e.every(t=>We(t.type))?"images":"non_images",Ql=({currentFiles:e,incomingFiles:t,maxAttachmentCount:n})=>{const r=Jl(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}},At=3,gi=6,eu=e=>e%At===0?At:gi,tu=({index:e,itemCount:t})=>{const n=t%At,r=n>0,s=r?t-n:t,o=r&&e>=s,i=o?n:At,c=o?e-s:e%At,u=!r&&e>=t-At;return{columnSpan:r?gi/i:1,rowItemCount:i,isLastInRow:c===i-1,isLastRow:o||u}},pi=Ce("AIAgent"),nu=pi.Provider,ke=pi.useContext;function ru(e){const t=su(e);return a.createElement(nu,{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 su(e){const t=l.useRef(null),n=l.useRef(null);if(!t.current||!n.current)t.current=bn.init(e);else{const s=ou(n.current,e);(s.appId||s.aiAgentId||s.chatSDK)&&(t.current.dispose(),t.current=bn.init({...e,chatParams:s.appId?{...e.chatParams,newInstance:!0}:e.chatParams}))}n.current=e,l.useEffect(()=>()=>{var s;(s=t.current)==null||s.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}function ou(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}}const Ss=Symbol("conversationMessageEventBridge"),wt=Symbol("conversationMessageEventPublisher"),iu=(e,t)=>{const n=e;if(n[wt]=t,n[Ss])return e;n[Ss]=!0;const r=e.setMessageCollectionHandler.bind(e);e.setMessageCollectionHandler=o=>{r({...o,onMessagesAdded:(i,c,u)=>{var d,m;(d=o.onMessagesAdded)==null||d.call(o,i,c,u),(m=n[wt])==null||m.call(n,{kind:"messagesAdded",source:i.source,messages:u})},onMessagesUpdated:(i,c,u)=>{var d,m;(d=o.onMessagesUpdated)==null||d.call(o,i,c,u),(m=n[wt])==null||m.call(n,{kind:"messagesUpdated",source:i.source,messages:u})}})};const s=e.initialize.bind(e);return e.initialize=o=>{const i=s(o),c=i.onCacheResult.bind(i),u=i.onApiResult.bind(i);return i.onCacheResult=d=>c((m,h)=>{var f;d(m,h),(f=n[wt])==null||f.call(n,{kind:"initialized",source:"cache",messages:h??[]})}),i.onApiResult=d=>u((m,h)=>{var f;d(m,h),(f=n[wt])==null||f.call(n,{kind:"initialized",source:"api",messages:h??[]})}),i},e},kn=()=>{const[,e]=l.useState(0);return l.useCallback(()=>e(t=>t+1),[])};let au=0;function cu(){return l.useState(()=>`${au++}`)[0]}const ht=(e,t,n)=>{const r=l.useRef(t),o=cu();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 Ze.GroupChannelHandler)),()=>{var u;(u=e==null?void 0:e.groupChannel)==null||u.removeGroupChannelHandler(o)}},[e==null?void 0:e.groupChannel,o])};function lu(e,t){return!e||!t?!0:e.url!==t.url}function ze(e){return e!=null&&"sendingStatus"in e}function uu(e,t="##__USER_ID_IS_NOT_PROVIDED__##"){var n;return ze(e)?((n=e.sender)==null?void 0:n.userId)===t:!1}function du(e,t){return uu(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 vn={collection:{groupChannel:{defaultOrder:Ze.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 mu=({...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=hu(t.value.messages);else{const n={...e.messageMap},r=[],s=[];t.value.messages.forEach(o=>{const i=ze(o)?o.reqId:void 0,c=o.messageId||void 0;[i,c].forEach(u=>{if(!u)return;const d=n[u];fu(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=>{ze(o)&&delete n[o.reqId],delete n[o.messageId]}),s.forEach(o=>{ze(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=>du(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&&(ze(s)&&delete e[n][s.reqId],delete e[n][s.messageId])}),t.value.reqIds.forEach(r=>{const s=e[n][r];s&&(ze(s)&&delete e[n][s.reqId],delete e[n][s.messageId])}),e}}},hu=e=>e.reduce((t,n)=>(ze(n)?(t[n.reqId]=n,n.sendingStatus===Ke.SendingStatus.SUCCEEDED&&(t[n.messageId]=n)):t[n.messageId]=n,t),{}),fu=(e,t,n=!1)=>{var r,s;if(!ze(e)||!ze(t))return!0;if(n&&e&&Me.isStreaming(e)&&Me.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===Ke.SendingStatus.SUCCEEDED?t.sendingStatus===Ke.SendingStatus.SUCCEEDED:e.sendingStatus!==t.sendingStatus},gu=(e=pu)=>{const[{initialized:t,loading:n,refreshing:r,messageMap:s,newMessageMap:o},i]=l.useReducer(mu,{initialized:!1,loading:!0,refreshing:!1,messageMap:{},newMessageMap:{}}),c=(E,_,y,A)=>{i({type:"update_messages",value:{messages:E,clearBeforeAction:_,currentUserId:y,strictStreamingOrder:A}})},u=(E,_)=>{i({type:"delete_messages",value:{messageIds:E,reqIds:_}})},d=(E,_,y)=>{i({type:"update_new_messages",value:{messages:E,clearBeforeAction:_,currentUserId:y}})},m=(E,_)=>{i({type:"delete_new_messages",value:{messageIds:E,reqIds:_}})},h=E=>{i({type:"update_initialized",value:{status:E}})},f=E=>{i({type:"update_loading",value:{status:E}})},g=E=>{i({type:"update_refreshing",value:{status:E}})},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}},xs=Math.floor(Number.MAX_SAFE_INTEGER/10);function pu(e,t){let n=0,r=0;return ze(e)&&e.sendingStatus!=="succeeded"&&(n=xs),ze(t)&&t.sendingStatus!=="succeeded"&&(r=xs),e.createdAt+n-(t.createdAt+r)}function Ee(e){const t=l.useRef(e);return t.current=e,l.useCallback((...n)=>t.current(...n),[t])}const _u=(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 Ze.MessageFilter(r)})};function Rs(e){return e<Date.now()?vn.collection.message.searchLimit:vn.collection.message.defaultLimit}const Eu=(e,t,n={})=>{var He,$;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=kn(),h=l.useRef({initialized:!1,apiInitialized:!1,instance:null}),{initialized:f,loading:g,refreshing:p,messages:v,newMessages:E,updateMessages:_,updateNewMessages:y,deleteNewMessages:A,deleteMessages:T,updateInitialized:R,updateLoading:L,updateRefreshing:N}=gu(n==null?void 0:n.sortComparator),x=Ee(M=>{var k,F,j,K;if(!s.current||!s.current.url)return(k=o==null?void 0:o.error)==null?void 0:k.call(o,"[useGroupChannelMessages] channel is required");try{switch(M){case fe.CollectionEventSource.EVENT_MESSAGE_RECEIVED:case fe.CollectionEventSource.EVENT_MESSAGE_SENT_SUCCESS:case fe.CollectionEventSource.SYNC_MESSAGE_FILL:case void 0:(j=(F=r.current).markAsRead)==null||j.call(F,[s.current]);break}}catch(X){(K=o==null?void 0:o.warn)==null||K.call(o,"[useGroupChannelMessages/markAsReadBySource]",X)}}),w=Ee((M,k)=>{var F,j,K,X,U;if(k.length>0)switch(M){case fe.CollectionEventSource.EVENT_MESSAGE_RECEIVED:case fe.CollectionEventSource.SYNC_MESSAGE_FILL:{(j=(F=r.current).shouldCountNewMessages)!=null&&j.call(F)&&y(k,!1,(K=e.currentUser)==null?void 0:K.userId),(U=(X=r.current).onMessagesReceived)==null||U.call(X,k);break}}}),Y=Ee(M=>{var k,F;(F=(k=r.current).onCollectionEvent)==null||F.call(k,M)}),O=Ee(async(M,k,F)=>new Promise((j,K)=>{var ye;h.current.instance&&h.current.instance.dispose(),x(),y([],!0,(ye=e.currentUser)==null?void 0:ye.userId);const X=()=>{var ge,pe;const{pendingMessages:ie,failedMessages:de}=h.current.instance??{};Ts(ie)&&_(ie,!1,(ge=e.currentUser)==null?void 0:ge.userId),Ts(de)&&_(de,!1,(pe=e.currentUser)==null?void 0:pe.userId)},U=_u(M,F,{...r.current,startingPoint:k});h.current={apiInitialized:!1,initialized:!1,instance:U},U.setMessageCollectionHandler({onMessagesAdded:(ie,de,ge)=>{var pe;x(ie.source),w(ie.source,ge),_(ge,!1,(pe=e.currentUser)==null?void 0:pe.userId,u),Y({kind:"messagesAdded",source:ie.source,channelUrl:M.url,messages:ge})},onMessagesUpdated:(ie,de,ge)=>{var pe,_e,xe;x(ie.source),w(ie.source,ge),_(ge,!1,(pe=e.currentUser)==null?void 0:pe.userId,u),ie.source===fe.CollectionEventSource.EVENT_MESSAGE_UPDATED&&((xe=(_e=r.current).onMessagesUpdated)==null||xe.call(_e,ge)),Y({kind:"messagesUpdated",source:ie.source,channelUrl:M.url,messages:ge})},onMessagesDeleted:(ie,de,ge,pe)=>{const _e=pe.map(be=>be.messageId),xe=pe.filter(ze).map(be=>be.reqId);T(_e,xe),A(_e,xe),Y({kind:"messagesDeleted",source:ie.source,channelUrl:M.url,messages:pe})},onChannelDeleted:(ie,de)=>{var ge,pe;(pe=(ge=r.current).onChannelDeleted)==null||pe.call(ge,de)},onChannelUpdated:(ie,de)=>{var ge,pe;m(),(pe=(ge=r.current).onChannelUpdated)==null||pe.call(ge,de,ie)},onHugeGapDetected:()=>{O(M,Number.MAX_SAFE_INTEGER,vn.collection.message.defaultLimit)}});let J=!1;U.initialize(Ze.MessageCollectionInitPolicy.CACHE_AND_REPLACE_BY_API).onCacheResult((ie,de)=>{var ge,pe,_e,xe,be;(pe=(ge=r.current).onCacheResult)==null||pe.call(ge,ie,de??[],M.url),ie?(e.isCacheEnabled&&((_e=o==null?void 0:o.error)==null||_e.call(o,"[useGroupChannelMessages/onCacheResult]",ie)),J=!0):de&&((xe=o==null?void 0:o.debug)==null||xe.call(o,"[useGroupChannelMessages/onCacheResult]","message length:",de.length),_(U.succeededMessages,!0,(be=e.currentUser)==null?void 0:be.userId),X(),de.length>0&&(h.current.initialized=!0,j())),Y({kind:"initialized",source:"cache",channelUrl:M.url,messages:de??[]})}).onApiResult((ie,de)=>{var ge,pe,_e,xe,be,$e,Fe;(pe=(ge=r.current).onApiResult)==null||pe.call(ge,ie,de??[],M.url),h.current.initialized=!0,h.current.apiInitialized=!0,ie?((_e=o==null?void 0:o.warn)==null||_e.call(o,"[useGroupChannelMessages/onApiResult]",ie),J?K(ie):j()):de&&((xe=o==null?void 0:o.debug)==null||xe.call(o,"[useGroupChannelMessages/onApiResult]","message length:",de.length),_(U.succeededMessages,!0,(be=e.currentUser)==null?void 0:be.userId),r.current.startingPoint||(Fe=($e=r.current).onMessagesReceived)==null||Fe.call($e,de),e.isCacheEnabled&&X(),j()),Y({kind:"initialized",source:"api",channelUrl:M.url,messages:de??[]})})}));ht(e,{onUserBanned(M,k){var F,j,K;M.isGroupChannel()&&!lu(M,s.current)&&(k.userId===((F=e.currentUser)==null?void 0:F.userId)?(K=(j=r.current).onCurrentUserBanned)==null||K.call(j):m())}}),l.useLayoutEffect(()=>{const M=setTimeout(async()=>{e.currentUser&&s.current&&(R(!1),L(!0),await O(s.current,i,c),L(!1),R(!0))});return()=>clearTimeout(M)},[e,(He=e.currentUser)==null?void 0:He.userId,($=s.current)==null?void 0:$.url,r.current.replyType]),l.useEffect(()=>()=>{h.current.instance&&h.current.instance.dispose()},[]);const Z=Ee(async()=>{e.currentUser&&s.current&&(N(!0),await O(s.current,Number.MAX_SAFE_INTEGER,vn.collection.message.defaultLimit),N(!1))}),G=Ee(async()=>{var k;const M=h.current.instance;if(M!=null&&M.hasPrevious&&!d.current.prev)try{d.current.prev=!0;const F=await M.loadPrevious();_(F,!1,(k=e.currentUser)==null?void 0:k.userId)}catch{}finally{d.current.prev=!1}}),D=Ee(()=>{const{initialized:M,instance:k}=h.current;return M&&k?k.hasPrevious:!1}),z=Ee(async()=>{var k;const M=h.current.instance;if(M!=null&&M.hasNext&&!d.current.next)try{d.current.next=!0;const F=await M.loadNext();_(F,!1,(k=e.currentUser)==null?void 0:k.userId)}catch{}finally{d.current.next=!1}}),q=Ee(()=>{const{initialized:M,apiInitialized:k,instance:F}=h.current;return k&&M&&F?F.hasNext:!1}),ne=Ee((M,k)=>{var F;if(!s.current||!s.current.url)throw(F=o==null?void 0:o.error)==null||F.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((j,K)=>{s.current.sendUserMessage(M).onPending(X=>{var U;X.channelUrl===s.current.url&&_([X],!1,(U=e.currentUser)==null?void 0:U.userId),k==null||k(X)}).onSucceeded(X=>{var U;X.channelUrl===s.current.url&&_([X],!1,(U=e.currentUser)==null?void 0:U.userId),j(X)}).onFailed((X,U)=>{var J;U&&U.channelUrl===s.current.url&&_([U],!1,(J=e.currentUser)==null?void 0:J.userId),K(X)})})}),ue=Ee((M,k)=>{var F;if(!s.current||!s.current.url)throw(F=o==null?void 0:o.error)==null||F.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((j,K)=>{s.current.sendFileMessage(M).onPending(X=>{var U;X.channelUrl===s.current.url&&_([X],!1,(U=e.currentUser)==null?void 0:U.userId),k==null||k(X)}).onSucceeded(X=>{var U;X.channelUrl===s.current.url&&_([X],!1,(U=e.currentUser)==null?void 0:U.userId),j(X)}).onFailed((X,U)=>{var J;U&&U.channelUrl===s.current.url&&_([U],!1,(J=e.currentUser)==null?void 0:J.userId),K(X)})})}),Ie=Ee(async(M,k)=>{var F;if(!s.current||!s.current.url)throw(F=o==null?void 0:o.error)==null||F.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise(j=>{const K=[];s.current.sendFileMessages(M).onPending(X=>{var U;X.channelUrl===s.current.url&&_([X],!1,(U=e.currentUser)==null?void 0:U.userId),k==null||k(X)}).onSucceeded(X=>{var U;X.isFileMessage()&&X.channelUrl===s.current.url&&(_([X],!1,(U=e.currentUser)==null?void 0:U.userId),K.push(X)),K.length===M.length&&j(K)}).onFailed((X,U)=>{var J;U&&U.channelUrl===s.current.url?(_([U],!1,(J=e.currentUser)==null?void 0:J.userId),K.push(U)):K.push(null),K.length===M.length&&j(K)})})}),B=Ee((M,k,F)=>{var j;if(!s.current||!s.current.url)throw(j=o==null?void 0:o.error)==null||j.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((K,X)=>{s.current.sendMultipleFilesMessage(M).onPending(U=>{var J;U.channelUrl===s.current.url&&_([U],!1,(J=e.currentUser)==null?void 0:J.userId),k==null||k(U)}).onFileUploaded(U=>{F==null||F(U),m()}).onSucceeded(U=>{var J;U.channelUrl===s.current.url&&_([U],!1,(J=e.currentUser)==null?void 0:J.userId),K(U)}).onFailed((U,J)=>{var ye;J&&J.channelUrl===s.current.url&&_([J],!1,(ye=e.currentUser)==null?void 0:ye.userId),X(U)})})}),V=Ee(async(M,k)=>{var j,K;if(!s.current||!s.current.url)throw(j=o==null?void 0:o.error)==null||j.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");const F=await s.current.updateUserMessage(M,k);return F.channelUrl===s.current.url&&_([F],!1,(K=e.currentUser)==null?void 0:K.userId),F}),I=Ee(async(M,k)=>{var j,K;if(!s.current||!s.current.url)throw(j=o==null?void 0:o.error)==null||j.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");const F=await s.current.updateFileMessage(M,k);return F.channelUrl===s.current.url&&_([F],!1,(K=e.currentUser)==null?void 0:K.userId),F}),W=Ee(async(M,k,F)=>{var j;if(!s.current||!s.current.url)throw(j=o==null?void 0:o.error)==null||j.call(o,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((K,X)=>{let U;M.isUserMessage()&&(U=s.current.resendMessage(M)),M.isFileMessage()&&(U=s.current.resendMessage(M)),M.isMultipleFilesMessage()&&(U=s.current.resendMessage(M)),U&&("onPending"in U&&U.onPending(J=>{var ye;J.channelUrl===s.current.url&&_([J],!1,(ye=e.currentUser)==null?void 0:ye.userId),k==null||k(J)}),"onFileUploaded"in U&&U.onFileUploaded(J=>{F==null||F(J),m()}),"onSucceeded"in U&&U.onSucceeded(J=>{var ye;J.channelUrl===s.current.url&&_([J],!1,(ye=e.currentUser)==null?void 0:ye.userId),K(J)}),"onFailed"in U&&U.onFailed((J,ye)=>{var ie;ye&&ye.channelUrl===s.current.url&&_([ye],!1,(ie=e.currentUser)==null?void 0:ie.userId),X(J)}))})}),re=Ee(async M=>{var k,F;if(!s.current||!s.current.url)throw(k=o==null?void 0:o.error)==null||k.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((F=h.current.instance)==null?void 0:F.removeFailedMessage(M.reqId))}finally{T([],[M.reqId])}}),oe=Ee(()=>{var M;y([],!0,(M=e.currentUser)==null?void 0:M.userId)}),De=Ee(async M=>{var k;if(e.currentUser&&s.current){const F=Rs(M);L(!0),_([],!0,(k=e.currentUser)==null?void 0:k.userId),await O(s.current,M,F),L(!1)}});return{initialized:f,loading:g,refreshing:p,messages:v,newMessages:E,resetNewMessages:oe,refresh:Z,loadPrevious:G,hasPrevious:D,loadNext:z,hasNext:q,sendUserMessage:ne,sendFileMessage:ue,sendFileMessages:Ie,sendMultipleFilesMessage:B,updateUserMessage:V,updateFileMessage:I,resendMessage:W,deleteMessage:re,resetWithStartingPoint:De,_dangerous_reducer_updateMessages:_,_dangerous_reducer_deleteMessages:T}},Cu=(e,t,n)=>{const r=l.useRef(0),s=l.useRef(new Set),o=l.useCallback(d=>{const m={id:r.current+=1,...d};s.current.forEach(h=>{h(m)})},[]),i=l.useCallback(d=>{var h;const m=((h=n==null?void 0:n.collectionCreator)==null?void 0:h.call(n,d))??(t==null?void 0:t.createMessageCollection({...d??{},filter:new Ze.MessageFilter(d)}));if(!m)throw new Error("Group channel is required to create a message collection");return iu(m,o)},[t,n==null?void 0:n.collectionCreator,o]),c=Eu(e,t,{...n,collectionCreator:i,strictStreamingOrder:!0}),u=l.useCallback(d=>(s.current.add(d),()=>{s.current.delete(d)}),[]);return{...c,subscribeMessageEvents:u}},bu=({channelUrl:e,enabled:t=!0,statsTracker:n})=>{const r=l.useRef(e),s=l.useRef(t),o=l.useRef(!1),i=l.useRef(null),c=l.useRef(null),u=l.useRef(null);s.current=t;const d=l.useCallback(_=>r.current===_,[]),m=l.useCallback(()=>{o.current&&(n.clear(),o.current=!1,i.current=null)},[n]),h=l.useCallback(_=>{if(!s.current)return;const y=!o.current||i.current!==_;n.start(_),y&&n.onGetChannelStart(_),o.current=!0,i.current=_},[n]),f=l.useCallback(_=>{d(_)&&(u.current=_,c.current=null,h(_))},[d,h]),g=l.useCallback(({channelUrl:_,conversationId:y})=>{o.current||h(_),n.onGetChannelComplete({channelUrl:_,conversationId:y})},[h,n]),p=l.useCallback(({channelUrl:_,error:y})=>{o.current||h(_),n.onGetChannelError({channelUrl:_,error:y})},[h,n]),v=l.useCallback(_=>{if(d(_.channelUrl)){if(u.current=null,!s.current){c.current=_;return}c.current=null,g(_)}},[d,g]),E=l.useCallback(_=>{if(d(_.channelUrl)){if(u.current=null,!s.current){c.current=_;return}c.current=null,p(_)}},[d,p]);return l.useEffect(()=>{if(t){const _=c.current;if(_){if(c.current=null,_.channelUrl!==e)return;"error"in _?p(_):g(_);return}const y=u.current;if(y){if(y!==e){u.current=null;return}h(y)}return}m()},[e,m,t,p,g,h]),l.useEffect(()=>(r.current=e,o.current=!1,i.current=null,c.current=null,u.current=null,()=>{m(),o.current=!1,i.current=null,c.current=null,u.current=null}),[e,m]),{onFetchStart:f,onFetchSuccess:v,onFetchError:E}},vu=({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}},yu=({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}},Bt={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 Su(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 Au(e){return`#${e.map(t=>t.toString(16).padStart(2,"0")).join("")}`}function Tu(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 Iu(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 rn(e,t,n){const[r,s,o]=Su(e),[i,c,u]=Tu(r,s,o),d=Math.max(0,Math.min(1,u*t)),m=Math.max(0,Math.min(1,c*n)),[h,f,g]=Iu(i,m,d);return Au([Math.round(h),Math.round(f),Math.round(g)])}function xu(e,t="light"){return{extraDark:rn(e,.6,1.2),dark:rn(e,.85,1.1),main:e,light:rn(e,t==="dark"?1.1:1.5,t==="dark"?.95:.9),extraLight:rn(e,t==="dark"?1.2:1.75,t==="dark"?.9:.8)}}function lr(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?Bt.BLACK:Bt.WHITE}function Ru(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},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 Mu=(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},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"}}),sn={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)"}},qn={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=wu(e),n=ku(e,t),r=Ou(n,e.colors,e.selectedTheme),s=Du(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 wu({selectedTheme:e,palette:t,primary:n}){const r=t!=null&&t.primary?t.primary:n?n===sn.primary.main?sn.primary:xu(n,e):sn.primary;return{...sn,primary:r,...t}}function ku({selectedTheme:e,primaryContrast:t,botMessageBackground:n,botMessageBackgroundContrast:r},s){const o=s.primary.main,i=t??lr(o),c=n??Bt.DEFAULT_BOT_MSG_BG,u=r??lr(c);return(e==="light"?Ru:Mu)(s,o,i,c,u)}function Lu(e,t,n){return typeof e=="string"?e:e[t]??n}function Ou(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]=Lu(m,n,h)}}}return r}function Nu(e,t,n){const r={...e};return n.forEach(s=>{const o=t[s];o!=null&&(r[s]=o)}),r}function Du({typography:e}){if(!e)return qn;const t={...qn};return Object.keys(e).forEach(n=>{const r=e[n];if(r&&typeof r=="object"){const s=qn[n],o=["fontSize","fontWeight","fontFamily","lineHeight"];t[n]=Nu(s,r,o)}}),t}const{Provider:$u,useContext:Nr}=Ce("AIAgentTheme");function Fu({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,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=Ms({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($u,{value:{theme:c,updateTheme:d}},o)}const Yn=25*1024*1024,ws=1,ks=new Set(["image/png","image/jpeg","image/jpg"]),Ls=new Set(["application/pdf"]),Pu={off:"off",always:"always",handed_off_only:"handed_off_only"},Uu=()=>{const[e,t]=l.useState(()=>({maxAttachmentCount:ws,attachmentMode:"handed_off_only",defaultUploadSizeLimit:Yn,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:Pu[s.attachment_mode]??"handed_off_only",defaultUploadSizeLimit:(o==null?void 0:o.default_upload_size_limit)??Yn,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=Yn}=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()?[ir]:[...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)")},kt=e=>({...e,context:e.context??{}}),{Provider:Bu,useContext:ft}=Ce("AIAgentMessengerSession"),Hu=l.forwardRef(function({userSessionInfo:e,children:t},n){const{_aiAgentSDK:r,chatSDK:s,aiAgentId:o,logger:i}=ke(),{updateTheme:c}=Nr(),[u,d]=l.useState(void 0),[m,h]=l.useState(void 0),[f,g]=l.useState(null),[p,v]=l.useState(null),[E,_]=l.useState(null),[y,A]=l.useState(null),[T,R]=l.useState(null),{updateBaseAttachmentRules:L,createAttachmentRules:N}=Uu();l.useEffect(()=>{const O=r.onMessengerSettingsUpdated(({settings:D})=>{const{appearance:z,bot:q,launcher:ne,memory:ue}=D;c(z.selected_theme,z),_(_l(q)),A(El(ne)),R(ue?cr(ue):null),L(D)}),Z=r.onActiveChannelUpdated(({channelUrl:D,status:z,conversationStatus:q})=>{h({url:D,status:z,conversationStatus:q})}),G=r.onAuthTokenRefreshed(()=>{var z;const D=(z=r.session)==null?void 0:z.userSession.authToken;D&&v(q=>q?{...q,authToken:D}:null)});return()=>{O(),Z(),G()}},[r,c,L]);const x=l.useCallback(async()=>{try{const O=await r.authenticate(e),Z=r.session;return g(Z.sdkUser),v(Z.userSession),h(Z.activeChannel),d(void 0),O}catch(O){throw g(null),v(null),h(void 0),d(O),O}},[r,e]),w=l.useCallback(async()=>{await r.deauthenticate(),g(null),h(void 0),v(null),_(null),A(null),R(null)},[r]),Y=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 O=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:x,deauthenticate:w,updateContext:async(...Z)=>{const G=Os(...Z);if(G.type==="active"){const q=await(await O()).updateContext(o,G.context);return kt(q)}const D=await s.aiAgent.updateContext(G.aiAgentId,G.channelUrl,G.context);return kt(D)},patchContext:async(...Z)=>{const G=Os(...Z);if(G.type==="active"){const q=await(await O()).patchContext(o,G.context);return kt(q)}const D=await s.aiAgent.patchContext(G.aiAgentId,G.channelUrl,G.context);return kt(D)},getContextObject:async()=>{const G=await(await O()).getContextObject(o);return kt(G)}}},[x,w,m,s,o,i]),a.createElement(Bu,{value:{sdkUser:f,userSessionInfo:e,userSession:p,activeChannel:m,setActiveChannel:h,refreshActiveChannel:Y,createConversation:r.createConversation,searchConversation:r.searchConversation,connectionError:u,aiAgentInfo:E,launcherInfo:y,memoryInfo:T,authenticate:x,deauthenticate:w,createAttachmentRules:N}},t)}),Gu={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"},zu=e=>e.disabled?Gu[e.disabledBy]==="ready":!0,Vu=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&&zt(t)?"file_video":t&&vc(t)?"file_audio":"file_document"};let Ns=0;const qu=e=>(Ns+=1,`${e??"unknown"}:${Ns}`),yt=(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)},Yu=(e,t)=>{e.conversationInitialRender.onCacheResult(t.error),Ei(e,t)},Wu=(e,t)=>{e.conversationInitialRender.onApiResult(t.error),Ci(e,t)},Ku=(e,t,n)=>{var o;if(!mt(e,n))return;const{hasResponseMetadata:r,...s}=qo(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=nt(e)?e.reqId:void 0;n&&(t.messagePendingStuck.disappear({requestId:n}),t.userPerceivedResponseTime.cancelTurn(n),t.typingIndicatorAbsentTimeout.cancelTurn(n))},Wn=(e,t)=>{t&&(e.conversationInitialRender.clear(),e.conversationNotInteractiveTimeout.clearChannel(t),e.recoveryNotInteractiveTimeout.clearChannel(t),e.messagePendingStuck.clearChannel(t),e.userPerceivedResponseTime.clearChannel(t),e.typingIndicatorAbsentTimeout.clearChannel(t),e.streamStalled.clearChannel(t))},ju=({activeChannelUrl:e,statsTrackers:t})=>{const{chatSDK:n}=ke(),{aiAgentInfo:r}=ft(),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])},Xu=({enabled:e=!0,requestedChannelUrl:t,statsTrackers:n})=>{const r=l.useRef(void 0),s=l.useRef(e);l.useLayoutEffect(()=>{const o=r.current,i=s.current;if(s.current=e,!e){o&&(Wn(n,o),r.current=void 0);return}o&&o!==t&&(Wn(n,o),r.current=void 0),t&&o!==t&&(i||n.conversationInitialRender.start(),n.conversationInitialRender.setChannelUrl(t),n.conversationNotInteractiveTimeout.start({channelUrl:t}),r.current=t)},[e,t,n]),l.useLayoutEffect(()=>()=>{const o=r.current;o&&(Wn(n,o),r.current=void 0)},[n])},Zu=({aiAgentUserId:e,conversationStatsEnabled: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&&yt(n,g.channelUrl),[n]);return l.useEffect(()=>{if(!t)return;const g=s.current;g&&f(g)&&(g.tracked||(r.conversationInitialRender.onCacheResult(g.error),g.tracked=!0),Ei(r,g));const p=o.current;p&&f(p)&&(p.tracked||(r.conversationInitialRender.onApiResult(p.error),p.tracked=!0),Ci(r,p))},[t,f,r]),l.useMemo(()=>({onCollectionEvent:g=>{if(h(m)&&yt(n,g.channelUrl)){if(g.kind==="messagesDeleted"){g.messages.forEach(p=>Ds(p,r));return}t&&g.messages.forEach(p=>Ku(p,r,e))}},onCacheResult:(g,p,v)=>{if(!h(m)||!yt(n,v))return;const E={error:g,messages:p,channelUrl:v,lifecycleGeneration:u.current,tracked:!1};s.current=E,t&&(Yu(r,E),E.tracked=!0)},onApiResult:(g,p,v)=>{if(!h(m)||!yt(n,v))return;const E={error:g,messages:p,channelUrl:v,lifecycleGeneration:u.current,tracked:!1};o.current=E,t&&(Wu(r,E),E.tracked=!0)},onLocalMessageDeleted:g=>{h(m)&&yt(n,g.channelUrl)&&Ds(g,r)}}),[e,m,t,h,n,r])},Ju=({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.markInputEnabled(t))},[t,e,r,o]),l.useEffect(()=>{if(!e||!n||i.current)return;const u=c.current,d=setTimeout(()=>{c.current===u&&(o.conversationInitialRender.markRendered(t)&&(i.current=!0),o.conversationNotInteractiveTimeout.markRendered(t))});return()=>clearTimeout(d)},[t,e,n,s,o])},Qu=({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()&&yt(f,v);try{const v=await c(E=>{if(!p(E.channelUrl)){u==null||u(E);return}m=E.reqId,n.messagePendingStuck.start({requestId:E.reqId,channelUrl:E.channelUrl,messageType:Vu(E),tracksUploadProgress:d.tracksUploadProgress??!1}),u==null||u(E)},E=>{!g()||m!==E||n.messagePendingStuck.markUploadProgress(E)});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])},ed=({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=qu(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])},td=({requestedChannelUrl:e,activeChannelUrl:t,conversationStatsEnabled:n=!0,statsTrackers:r})=>{const{aiAgentInfo:s}=ft();ju({activeChannelUrl:t,statsTrackers:r}),Xu({enabled:n,requestedChannelUrl:e,statsTrackers:r});const o=Zu({aiAgentUserId:s==null?void 0:s.userId,conversationStatsEnabled:n,requestedChannelUrl:e,statsTrackers:r}),i=Qu({channelUrl:t,enabled:n,statsTrackers:r}),c=ed({channelUrl:t,enabled:n,statsTrackers:r});return l.useMemo(()=>({messageCallbacks:o,runWithPendingStuckStats:i,runWithUserTurnStats:c}),[o,i,c])},Wt=()=>ke()._aiAgentSDK.statsTrackers,Kt=(e,t)=>{const n=l.useId(),r=l.useRef(t);l.useLayoutEffect(()=>{r.current=t}),l.useLayoutEffect(()=>{const s=new fe.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 nd(e,t={}){const{chatSDK:n,logger:r,aiAgentId:s,_aiAgentSDK:o}=ke(),{sdkUser:i}=ft(),c=$s(),u=$s(),d=kn(),[m,h]=l.useState(void 0),[f,g]=l.useState(void 0),[p,v]=l.useState(!1);function E(y){if(y.isAIAgent&&!y.conversation){const A=u.next();v(!0),o.initConversationIfNeeded(y).finally(()=>{u.isCurrent(A)&&v(!1)})}}async function _(){var A,T,R,L,N,x;const y=c.next();if(!i){r.debug("useChannel.getChannel: no sdk user, skip fetching channel");return}if(r.debug("useChannel.getChannel: start"),h(void 0),g(void 0),u.invalidate(),v(!1),e){(A=t.onFetchStart)==null||A.call(t,e);try{r.debug("useChannel.getChannel: get channel",e);const w=await n.groupChannel.getChannel(e);if(!c.isCurrent(y))return;E(w),h(w),(R=t.onFetchSuccess)==null||R.call(t,{channelUrl:w.url,conversationId:(T=w.conversation)==null?void 0:T.id}),w.url===((L=o.session)==null?void 0:L.activeChannel.url)&&o.session._updateActiveChannel({url:w.url,status:Be(w)?"closed":"open",conversationStatus:(N=w.conversation)==null?void 0:N.status}),r.debug("useChannel.getChannel: fetched channel",w)}catch(w){if(!c.isCurrent(y))return;(x=t.onFetchError)==null||x.call(t,{channelUrl:e,error:w}),w instanceof fe.SendbirdError&&g(w),r.error("useChannel.getChannel: error",w)}}}return l.useEffect(()=>(_(),()=>{c.invalidate()}),[n,i,e,s]),Kt(n,{async onReconnectSucceeded(){var T;if(!m){f&&await _();return}const y=c.current(),A=await m.refresh();!c.isCurrent(y)||m.url!==e||((T=t.onReconnectSucceeded)==null||T.call(t,m.url),E(A),h(A))}}),ht(n,{onChannelChanged:y=>{y.isGroupChannel()&&y.url===e&&(r.debug("useChannel.onChannelChanged: channel changed",y.url),h(y),d())}}),{channel:m,channelFetchError:f,getChannel:_,isInitializingConversation:p}}const rd=new Set(["suggested_replies","steward","system"]),sd=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||!rd.has(r)))return r},od=e=>{var o;const t=e==null?void 0:e.lastMessage;if(!t||!e)return!1;const n=t.extendedMessagePayload,r=Rn(n).hasActiveForm,s=e.isAIAgent&&!!((o=e.conversation)!=null&&o.handedOverAt);return r&&!s},id=()=>{const{chatSDK:e,networkStateAdapter:t}=ke(),[n,r]=l.useState(()=>t?t.isOnline()?"connected":"reconnecting":"connected");return Kt(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===fe.ConnectionState.OPEN?"connected":o)})},[t,e]),n},ad=3e4,cd=({shouldApply:e,lastMessage:t,isBlockedWhileAIResponding:n,currentUserId:r})=>{const[s,o]=l.useState(!1),i=l.useRef(null),c=t&&mt(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=ad-m;return n||h<=0?u():d(h),()=>{i.current&&clearTimeout(i.current)}},[n,c]),s&&e},bi=e=>{const{chatSDK:t}=ke(),[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},ld=({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=mt(t,n)&&(Me.isStreaming(t)||r);o(u||c)},[i,t,n,r]),s},ud=({channel:e,messages:t,isStreamAnimating:n,isInitializingConversation:r})=>{const{aiAgentInfo:s,userSession:o}=ft(),i=id(),c=ld({channel:e,lastMessage:us(t,[Ke.SendingStatus.SUCCEEDED]),aiAgentUserId:(s==null?void 0:s.userId)??"",isStreamAnimating:n}),u=cd({shouldApply:!!(e!=null&&e.isAIAgent)&&!ct(e),isBlockedWhileAIResponding:c,lastMessage:us(t,[Ke.SendingStatus.PENDING,Ke.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(Be(e))return d("conversation_closed");if(Cl(e))return d("handoff_pending");if(od(e))return d("form_active");const m=sd(e);return d(m||(c||u||r?"ai_responding":""))},dd=()=>{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:md}=Ce("AIAgentConversation"),hd=({initialRenderStats:e,notInteractiveStats:t,recoveryStats:n})=>({onFetchStart:r=>{e.onFetchStart(r),t.onFetchStart(r)},onFetchSuccess:r=>{e.onFetchSuccess(r),t.onFetchSuccess(r)},onFetchError:r=>{e.onFetchError(r),t.onFetchError(r)},onReconnectSucceeded:n.onReconnectSucceeded});function fd({children:e,channelUrl:t,onChannelDeleted:n,onMessagesReceived:r,onMessagesUpdated:s,onConversationClosedStatusChanged:o,onConversationClosedViaDispatcher:i,onBeforeSendMessage:c,onAfterSendMessage:u=le,shouldMarkAsRead:d=!0,conversationStatsEnabled:m=!0,shouldCountNewMessages:h=()=>!1,sortComparator:f}){var Ie;const g=()=>d&&(x==null?void 0:x.markAsRead()),{_aiAgentSDK:p,chatSDK:v,logger:E,dispatcher:_}=ke(),y=Wt(),A={channelUrl:t,enabled:m},T=bu({...A,statsTracker:y.conversationInitialRender}),R=vu({...A,statsTracker:y.conversationNotInteractiveTimeout}),L=yu({...A,scheduleForegroundTask:p.scheduleForegroundTask,statsTracker:y.recoveryNotInteractiveTimeout}),N=hd({initialRenderStats:T,notInteractiveStats:R,recoveryStats:L}),{channel:x,channelFetchError:w,getChannel:Y,isInitializingConversation:O}=nd(t,N),Z=x==null?void 0:x.url,G=td({requestedChannelUrl:t,activeChannelUrl:Z,conversationStatsEnabled:m,statsTrackers:y}),D=Cu(v,x,{replyType:Ke.ReplyType.ONLY_REPLY_TO_CHANNEL,shouldCountNewMessages:h,onChannelDeleted:n,onMessagesReceived:B=>r==null?void 0:r(B),onMessagesUpdated:B=>s==null?void 0:s(B),...G.messageCallbacks,logger:E,markAsRead:g,sortComparator:f}),z=dd(),q=ud({channel:x,messages:D.messages,isStreamAnimating:z.isAnimating,isInitializingConversation:O});Ju({enabled:m,channelUrl:Z,initialized:D.initialized,inputReady:zu(q),renderedSignal:D.messages,statsTrackers:y}),l.useEffect(()=>{g()},[d,x]);const ne=Be(x);l.useEffect(()=>{o==null||o(ne)},[ne,o]),l.useEffect(()=>{const B=async V=>{const I=typeof(V==null?void 0:V.channelUrl)=="string";x&&I&&V.channelUrl!==x.url||(E.debug("conversation.dispatcher: try to close conversation",x),x!=null&&x.conversation&&x.conversation.status===Se.ConversationStatus.OPEN&&(await x.closeConversation(),i==null||i()))};return _.subscribe(Ye.ConversationClose,B),()=>{_.unsubscribe(Ye.ConversationClose,B)}},[_,x,E,(Ie=x==null?void 0:x.conversation)==null?void 0:Ie.status,i]);const ue={conversation:(x==null?void 0:x.conversation)??void 0,actions:{setUserMemoryState:p.setUserMemoryState},channelSource:{channel:x,error:w,refetch:()=>Y(),closeConversation:async()=>{Be(x)||await(x==null?void 0:x.closeConversation())}},messageSource:{messages:D.messages,newMessages:D.newMessages,initialized:D.initialized,subscribeMessageEvents:D.subscribeMessageEvents,loadPrevious:()=>D.loadPrevious(),loadNext:()=>D.loadNext(),deleteMessage:async B=>{try{await D.deleteMessage(B)}finally{B.sendingStatus!=="succeeded"&&G.messageCallbacks.onLocalMessageDeleted(B)}},resendMessage:B=>B.isUserMessage()?G.runWithUserTurnStats(V=>G.runWithPendingStuckStats(I=>D.resendMessage(B,W=>{V(W.reqId),I(W)}),void 0)):G.runWithPendingStuckStats((V,I)=>D.resendMessage(B,V,I),void 0,{tracksUploadProgress:B.isMultipleFilesMessage()}),resetNewMessages:()=>D.resetNewMessages(),sendUserMessage:async B=>{var I;if(((I=x==null?void 0:x.conversation)==null?void 0:I.status)===Se.ConversationStatus.CLOSED)throw new Error("Conversation is closed");c&&(B=await c(B));const V=await G.runWithUserTurnStats(W=>G.runWithPendingStuckStats(re=>D.sendUserMessage(B,oe=>{W(oe.reqId),re(oe)}),u));return u==null||u(V),V},sendFileMessage:async B=>{var I;if(((I=x==null?void 0:x.conversation)==null?void 0:I.status)===Se.ConversationStatus.CLOSED)throw new Error("Conversation is closed");c&&(B=await c(B));const V=await G.runWithPendingStuckStats(W=>D.sendFileMessage(B,W),u);return u==null||u(V),V},sendMultipleFilesMessage:async B=>{var I;if(((I=x==null?void 0:x.conversation)==null?void 0:I.status)===Se.ConversationStatus.CLOSED)throw new Error("Conversation is closed");c&&(B=await c(B));const V=await G.runWithPendingStuckStats((W,re)=>D.sendMultipleFilesMessage(B,W,re),u,{tracksUploadProgress:!0});return u==null||u(V),V}},state:{streamAnimation:z,input:q}};return a.createElement(md,{value:ue},e)}function gd(e,t,n){var _,y,A,T,R,L,N,x,w,Y;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=Ee(()=>{var O;return(O=n==null?void 0:n.onListRequestStart)==null?void 0:O.call(n)}),g=Ee(()=>{var O;return(O=n==null?void 0:n.onListRequestComplete)==null?void 0:O.call(n)}),p=l.useCallback(async O=>{f(),await O.loadMore(),g()},[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 O=new Jo(e,t);O.setConversationListCollectionHandler({onChannelsAdded:()=>{u(O.channels)},onChannelsUpdated:()=>{u(O.channels)},onChannelsDeleted:()=>{u(O.channels)}}),await p(O),u(O.channels),m(O),i(null)}catch(O){m(null),i(O)}finally{s(!0),h.current=!1}}},[e,e.currentUser,(_=t.filter)==null?void 0:_.aiAgentChannelFilter,(A=(y=t.filter)==null?void 0:y.aiAgentConversationStatusFilter)==null?void 0:A.join(),(R=(T=t.filter)==null?void 0:T.aiAgentIds)==null?void 0:R.join(),(L=t.filter)==null?void 0:L.deskChannelFilter,(x=(N=t.filter)==null?void 0:N.pinnedChannelUrls)==null?void 0:x.join(),(w=t.filter)==null?void 0:w.copilotConversationOnly,(Y=t.filter)==null?void 0:Y.copilotSupportChannelUrl,t.limit,p]),E=l.useCallback(async()=>{if(d)try{await d.loadMore(),u(d.channels)}catch(O){i(O)}},[d]);return Kt(e,{onConnected:()=>v()}),l.useEffect(()=>{v()},[v]),l.useEffect(()=>()=>{h.current=!1,d==null||d.dispose()},[d]),{initialized:r,error:o,channels:c,loadMore:E}}const vi=e=>{var s;const{aiAgentId:t,queryParams:n}=ke(),r=(s=n==null?void 0:n.conversationListParams)==null?void 0:s.filter;return{aiAgentIds:[t],aiAgentConversationStatusFilter:[Se.ConversationStatus.CLOSED,Se.ConversationStatus.OPEN],...r,...e}},pd=({enabled:e=!0}={})=>{const n=Wt().conversationListInitialRender,r=l.useRef(e),s=l.useRef(!1),o=l.useRef(!1),i=l.useRef(!1);r.current=e,l.useEffect(()=>{if(!e){o.current&&(s.current=!0);return}if(o.current&&!s.current)return;const m=s.current&&i.current;n.onInitializeStart(),o.current=!0,s.current=!1,m&&n.onListRequestStart()},[e,n]),l.useEffect(()=>()=>{n.clear(),o.current=!1,s.current=!1,i.current=!1},[n]);const c=l.useCallback(()=>r.current&&o.current&&!s.current,[]),u=l.useMemo(()=>({onListRequestStart:()=>{i.current=!0,c()&&n.onListRequestStart()},onListRequestComplete:()=>{i.current=!1,c()&&n.onListRequestComplete()}}),[c,n]),d=l.useCallback(()=>{c()&&n.onRendered()},[c,n]);return l.useMemo(()=>({collectionCallbacks:u,onRendered:d}),[u,d])},{Provider:_d}=Ce("AIAgentConversationList");function Ed({conversationListLimit:e,conversationListFilter:t,conversationListStatsEnabled:n=!0,children:r}){var h;const{chatSDK:s,queryParams:o}=ke(),i=pd({enabled:n}),c=e??((h=o==null?void 0:o.conversationListParams)==null?void 0:h.limit),u=vi(t),d=gd(s,{limit:c,filter:u},i.collectionCallbacks);l.useEffect(()=>{n&&d.initialized&&(d.error||i.onRendered())},[n,d.error,d.initialized,i]);const m={listSource:{initialized:d.initialized,error:d.error??void 0,channels:d.channels,loadMore:()=>d.loadMore()}};return a.createElement(_d,{value:m},r)}function Cd(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:bd,useContext:vd}=Ce("MessageTemplateFetching");function yd({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(E=>{throw f||i(h,{error:!0}),E}).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=Cd(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(bd,{value:u},e)}const Sd="remove_powered_by",Dr=(e,t)=>{var s,o;const{chatSDK:n}=ke(),{aiAgentInfo:r}=ft();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&&xr(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(Sd)),[i])}throw new Error("Unsupported feature")},Ad={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"},Td={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}}},Id={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}}},xd={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}}},Rd={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}}},Md={text:Td,number:Id,"single-select":xd,"multi-select":Rd},wd={getValueOrDefault:()=>null,validate:()=>({isValid:!1})};function yi(e){return Md[e.type]||wd}function Fs(e){return yi(e).getValueOrDefault(e)}function kd(e,t,n={}){const r={...Ad,...n};return yi(e).validate(e,t,r)}const Ld=(e,t={})=>{const{labels:n={},onSubmit:r,onCancel:s}=t,[o,i]=l.useState({}),[c,u]=l.useState(()=>{const v={};return e.fields.forEach(E=>{v[E.key]=Fs(E)}),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 E=!1;e.fields.forEach(_=>{const y=Fs(_);JSON.stringify(c[_.key])!==JSON.stringify(y)&&(E=!0),v[_.key]=y}),E&&u(v)}},[d]);const m=(v,E)=>{u(_=>({..._,[v]:E})),i(_=>({..._,[v]:void 0}))},h=e.fields.map(v=>{var y,A,T;const E=c[v.key]??null,_={key:v.key,label:v.label,error:o[v.key],required:v.required};return v.type==="text"?{..._,type:"text",layout:v.layout,value:E,...v.placeholder&&{placeholder:v.placeholder},...((y=v.rules)==null?void 0:y.max_length)&&{maxLength:v.rules.max_length}}:v.type==="number"?{..._,type:"number",layout:v.layout,value:E,...v.placeholder&&{placeholder:v.placeholder},...((A=v.rules)==null?void 0:A.max)&&{max:v.rules.max}}:v.type==="single-select"?{..._,type:"single-select",layout:v.layout,value:E,options:v.options}:v.type==="multi-select"?{..._,type:"multi-select",layout:v.layout,value:E,options:v.options,...((T=v.rules)==null?void 0:T.max_select)&&{maxSelect:v.rules.max_select}}:{..._,type:"unknown",layout:"default",value:null}});return{state:d,fields:h,getField:v=>h.find(E=>E.key===v),updateFieldValue:m,submit:async()=>{const v={};let E=!1;for(const _ of e.fields){const y=c[_.key]??null,A=kd(_,y,n);A.isValid||(v[_.key]=A.error,E=!0)}if(i(v),!E&&r){const _={};e.fields.forEach(y=>{_[y.key]=c[y.key]??null}),await r(_)}},cancel:async()=>{await(s==null?void 0:s())}}},Od=e=>{const{chatSDK:t,handlers:n,logger:r}=ke(),{aiAgentInfo:s}=ft(),o=l.useRef(new Set),i=l.useRef(new Set),c=(m,h)=>{if(!(n!=null&&n.onCustomEvent)||!(s!=null&&s.userId)||!mt(m,s.userId))return;const f=m.messageId;if(Me.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=zo(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}},Nd=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},Si=e=>{const{aiAgentInfo:t}=ft(),n=bi(e);if(Be(e))return null;const r=n[0];if(!r)return null;const s=r.userId===(t==null?void 0:t.userId),o=s?Nd(r.metaData):void 0;return{user:s?t:r,isBot:s,thinkingMessage:o}},Dd=(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},[])},$d=(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()}}},Fd=(e,t,n=1e4,r=!0)=>{const s=l.useRef(null),o=l.useRef(null),i=l.useRef(!1);s.current||(s.current=$d(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])},Pd=({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])},$r=({channel:e,userSession:t,aiAgentInfo:n})=>{if(!t||!n||!e)return{fallbackIcon:"delight",url:void 0,title:""};const r=ai(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")},Ps=e=>l.useReducer((t,n)=>({...t,...n}),e);var Je=(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))(Je||{});const Ud=new Set(["free_text","single_choice"]),Bd=({csatPayload:e,type:t,initialCsat:n,initialCsatReason:r,initialIsResolved:s})=>{const[o,i]=Ps({csatType:t,csat:n,csatReason:r,isResolved:s}),[c,u]=Ps({followUpItem:!1}),d=l.useMemo(()=>{var E;const g=o.csat,p=typeof g=="number",v=(E=e.follow_up)==null?void 0:E.find(_=>p?_.scores.includes(g):_.always_visible??!1);if(Ud.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===Je.AI_AGENT_CSAT_5||t===Je.HELPDESK_CSAT_5)&&typeof o.csat=="number")return"submittable";if(t===Je.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"}}},Hd=({csat:e,csatExpireAt:t,csatPayload:n,isSubmitInFlight:r=!1})=>{const s=!!n&&n.visibility&&!!Je[n.type],o=!r&&typeof e!="number"&&ci(t),i=kn();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}},Kn=5,Nt=250,Gd=50,Us=e=>Math.max(0,e-Gd),ur=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():0,zd=e=>e<1e3?{speed:Kn*.5,chunkSize:2}:e<2e3?{speed:Kn*.8,chunkSize:2}:{speed:Kn*.6,chunkSize:3},hn=(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(hn(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]==="`"&&!hn(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]==="["&&!hn(e,s),c=e[s]==="["&&!hn(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},Vd=({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(y=>{var A;(A=r.current)==null||A.call(r,y)},[]),m=l.useCallback(y=>{const A=e.initialEnabled&&(e.enabled||y<e.textLength),T=A&&e.deferImages,R=A&&e.deferLinks;return!T&&!R?y:Ai(e.text.slice(0,y),{hideImages:T,hideLinks:R}).length},[e]),h=l.useCallback((y,A,T=!1)=>{r.current&&(y<=c.lastLength||!T&&A-c.lastReportedAt<Nt||(c.lastLength=y,c.lastReportedAt=A,d(y)))},[d,c]),f=l.useCallback((y,A,T=!1)=>{if(!r.current)return;const R=Math.max(c.lastReportedAt,c.lastCheckedAt);!T&&A-R<Nt||(c.lastCheckedAt=A,h(m(y),A,!0))},[m,h,c]),g=l.useCallback((y,A,T=!1)=>{s.current&&(y<=i.lastLength||!T&&A-i.lastReportedAt<Nt||(i.lastLength=y,i.lastReportedAt=A,s.current(y)))},[i]),p=l.useCallback((y,A,T)=>{const R=y>=A,L=T-i.lastReportedAt>=Nt;if(!R&&!L)return;const N=m(y);g(N,T,R)},[m,i,g]),v=l.useCallback(()=>{c.lastLength=0,c.lastReportedAt=0,c.lastCheckedAt=0,i.lastLength=0,i.lastReportedAt=0},[i,c]),E=l.useCallback(y=>{r.current&&(o.current!==null&&y<=o.current||(o.current=y,d(y)))},[d]),_=l.useCallback(({displayedLength:y,streamTextLength:A})=>{const T=u.current;if(u.current={displayedLength:y,streamTextLength:A},!e.initialEnabled||!T||y>T.displayedLength||A<=T.streamTextLength)return;const R=ur();h(A,R,!0),g(A,R,!0)},[u,g,h,e]);return{resetProgress:v,reportVisibleTextProgress:f,reportRenderedTextProgress:p,reportNonStreamingVisibleTextProgress:E,reportMarkdownRevealProgress:_}},qd=e=>{const{text:t,enabled:n=!1,deferredMarkdownElements:r=[],onAnimationStart:s,onAnimationProgress:o,onAnimationComplete:i,onVisibleTextProgress:c,onRenderedTextProgress:u}=e,d=r.includes("image"),m=r.includes("link"),[h,f]=l.useState(()=>Us(t.length)),g=l.useRef(null),p=l.useRef({startTime:0,lastUpdate:0,lastProgressCall:0}).current,v=l.useRef({startCalled:!1,completeCalled:!1}).current,E=l.useRef({initialEnabled:n,textLength:t.length,enabled:n,text:t,deferImages:d,deferLinks:m}).current,_=Ee(()=>s==null?void 0:s()),y=Ee(()=>o==null?void 0:o()),A=Ee(()=>i==null?void 0:i()),{resetProgress:T,reportVisibleTextProgress:R,reportRenderedTextProgress:L,reportNonStreamingVisibleTextProgress:N,reportMarkdownRevealProgress:x}=Vd({trackedRef:E,onVisibleTextProgress:c,onRenderedTextProgress:u}),w=n,Y=h<t.length,O=E.initialEnabled&&(w||Y);l.useLayoutEffect(()=>{E.textLength=t.length,E.enabled=n,E.text=t,E.deferImages=d,E.deferLinks=m}),l.useLayoutEffect(()=>{E.initialEnabled&&(v.startCalled||(v.startCalled=!0,_()),f(G=>t.length<G?t.length:G))},[_,t]),l.useEffect(()=>{if(!E.initialEnabled)return;let G=Us(t.length);p.lastUpdate=0,p.startTime=0,p.lastProgressCall=0,T();const D=z=>{p.lastUpdate===0&&(p.lastUpdate=z,p.startTime=z,p.lastProgressCall=z,G>0&&R(G,z,!0));const q=E.textLength,ne=z-p.lastUpdate,ue=z-p.startTime,{speed:Ie,chunkSize:B}=zd(ue),V=Ie*B;ne>=V&&G<q&&(G=Math.min(G+B,q),f(G),R(G,z,G>=q),L(G,q,z),p.lastUpdate=z),z-p.lastProgressCall>=Nt&&(p.lastProgressCall=z,y()),(G<q||E.enabled)&&(g.current=requestAnimationFrame(D))};return g.current=requestAnimationFrame(D),()=>{g.current&&cancelAnimationFrame(g.current),v.startCalled&&!v.completeCalled&&(v.completeCalled=!0,A())}},[A,y,L,R,T]),l.useEffect(()=>{E.initialEnabled&&(n||t.length>0)||(N(t.length),L(t.length,t.length,ur()))},[n,u,c,N,L,t.length,E]),l.useEffect(()=>{const G=E.initialEnabled&&v.startCalled,D=!n,z=h>=t.length;G&&D&&z&&!v.completeCalled&&(v.completeCalled=!0,A())},[n,h,A,t.length]);const Z=l.useMemo(()=>{const G=E.initialEnabled?t.slice(0,h):t,D=O&&d,z=O&&m;return!D&&!z?G:Ai(G,{hideImages:D,hideLinks:z})},[t,h,d,m,O]);return l.useEffect(()=>{!E.initialEnabled||O||R(h,ur(),!0)},[h,O,R]),l.useEffect(()=>{x({displayedLength:h,streamTextLength:Z.length})},[h,x,Z.length]),{streamText:Z,isAnimating:O}},Hs={visible:!1,remainingTime:0,showDescription:!1,targetTimeMs:null},Yd=e=>({visible:!0,remainingTime:e,showDescription:!0,targetTimeMs:Date.now()+e*1e3}),Wd=(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}},Kd=()=>{const{chatSDK:e}=ke(),[t,n]=l.useState(Hs),r=()=>n(Hs);return Kt(e,{onConnectionDelayed:s=>{s>0?n(Yd(s)):r()},onReconnectSucceeded:r,onConnected:r}),l.useEffect(()=>{if(!t.visible||!t.showDescription||t.targetTimeMs==null)return;const s=setTimeout(()=>{n(o=>Wd(o))},1e3);return()=>clearTimeout(s)},[t.visible,t.showDescription,t.targetTimeMs,t.remainingTime]),{visible:t.visible,remainingTime:t.remainingTime,showDescription:t.showDescription}},jd=e=>{const t=Math.floor(e/60),n=e%60;return`${String(t).padStart(2,"0")}:${String(n).padStart(2,"0")}`},Xd=(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)}},Zd=({enabled:e=!0}={})=>{const t=Wt();return l.useCallback(({message:n,isBotMessage:r,aiAgentUserId:s})=>{if(!e)return;const o=n.messageId,i=Me.isStreaming(n),c=Rn(n.extendedMessagePayload),u=c.hasMessageTemplate,d=c.hasForm,m=r&&n.isUserMessage()&&!i&&!yc(n)&&!Me.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=E=>{t.streamStalled.markRenderedProgress({messageId:o,displayedLength:E})}),u&&(v.onMessageTemplateError=E=>{t.renderedContentUnusable.commit({messageId:o,contentKind:"template",errorDomain:"template_error",error:E})}),d&&(v.onFormRenderError=E=>{t.renderedContentUnusable.commit({messageId:o,contentKind:"form",errorDomain:"form_error",error:E})}),v},[e,t])},Jd=e=>{const t=l.useRef(!1);l.useEffect(()=>{t.current||e!=null&&e.onVisibleTextProgress&&(t.current=!0,e.onVisibleTextProgress(0))},[e])},jn=5e3,on=()=>En.now(),Qd=({channelUrl:e,enabled:t=!0,isInitiallyBackgrounded:n,isForegrounded:r,subscribeToForegroundState:s})=>{const o=Wt(),i=l.useRef(t),c=l.useRef(n),u=l.useRef(t&&n()?on()-jn: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(on()-u.current<jn){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=on()-jn):u.current=null,s(h=>{if(h==="backgrounded"){u.current??(u.current=on()),d.current=!1,e&&o.recoveryNotInteractiveTimeout.cancelPending(e);return}m(!0)})},[e,t,m,o,s])},em=e=>{const{conversationInitialRender:t,conversationListInitialRender:n}=Wt();l.useLayoutEffect(()=>{t.setPresentMethod(e),n.setPresentMethod(e)},[t,n,e])},tm=(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===fe.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]),Kt(e,{onConnected:c,onReconnectSucceeded:c}),s},Fr=e=>e.replace(/\s+/g," ").trim(),nm="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}},rm=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}},sm=(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)},om=(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},im=(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},am=(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},cm=e=>{let t=0,n="";for(;t<e.length;){const r=om(e,"[",t);if(r===-1){n+=e.slice(t);break}const s=im(e,r+1);if(s===-1){n+=e.slice(t);break}if(r>0&&e[r-1]==="!"&&yn(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]==="!"&&!yn(e,r-1)?r-1:r;n+=e.slice(t,o);const i=e.slice(r+1,s),c=am(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)},lm=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}`}),um=e=>e.replace(/(^|[^_\\])__([^\s_](?:[\s\S]*?[^\s_])?)__(?!_)/g,"$1$2"),dm=e=>e.replace(/(^|[^~\\])~~([^\s~](?:[\s\S]*?[^\s~])?)~~(?!~)/g,"$1$2"),mm=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},hm=e=>e.replace(/\\([\\`*_[\]()#+.!~|-])/g,"$1"),fm=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},gm=e=>{const t=e.split(`
|
|
2
|
+
`),n=[];let r=0;for(;r<t.length;){const s=t[r],o=t[r+1],i=zs(s);if(i.length>0&&o&&Gs(o)){for(n.push(i.join(" ")),r+=2;r<t.length;){const c=t[r],u=zs(c);if(u.length===0||Gs(c))break;n.push(u.join(" ")),r+=1}continue}n.push(s),r+=1}return n.join(`
|
|
3
|
+
`)},pm=e=>e.replace(/^\s{0,3}(?:(?:-\s*){3,}|(?:\*\s*){3,}|(?:_\s*){3,})$/gm,""),_m=(e,t)=>{const n=e.split(`
|
|
4
|
+
`),r=[];let s=0;for(;s<n.length;){const o=n[s],i=rm(o);if(!i){r.push(o),s+=1;continue}let c=-1;for(let u=s+1;u<n.length;u++)if(sm(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
|
+
`)},yn=(e,t)=>{let n=0,r=t-1;for(;r>=0&&e[r]==="\\";)n+=1,r-=1;return n%2===1},Em=e=>{const t=[];let n=0,r="";for(;n<e.length;){const s=e[n];if(s!=="`"||yn(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]==="`"&&!yn(e,c)&&e.startsWith(i,c)){const d=e.slice(o,c),m=t.push(d)-1;r+=Ti(m),n=c+i.length,u=!0;break}c+=1}u||(r+=i,n=o)}return{text:r,inlineCodes:t}},Mi=(e,{codeBlockPlaceholder:t=nm}={})=>{const n=e==null?void 0:e.replace(/\r\n?/g,`
|
|
7
|
+
`);if(!n)return;const r=[];let s=n;s=_m(s,t),s=fm(s);const o=Em(s);s=o.text,r.push(...o.inlineCodes),s=cm(s),s=lm(s),s=um(s),s=dm(s),s=mm(s),s=gm(s),s=pm(s),s=hm(s);for(let c=0;c<r.length;c++)s=s.replaceAll(Ti(c),r[c]);return Fr(s)||void 0},Cm=(e,t)=>{var s;const n=((s=e.name)==null?void 0:s.trim())||"",r=e.mimeType??"";return We(r)?t.image:zt(r)?t.video:jo({name:n,mimeType:r})?t.pdf(n):t.document(n)},Sn=e=>(e==null?void 0:e.trim())||"",bm=e=>(e?Fr(e):void 0)||void 0,wi=e=>({text:Sn(e),format:"plain"}),vm=e=>({text:Sn(e),format:"markdown"}),Xn=({markdownText:e,plainText:t,comparisonText:n})=>{const r=Sn(e);return r&&r!==Sn(n)?vm(r):wi(t)},Dt=({sender:e,message:t,messageFormat:n="plain",time:r,codeBlockPlaceholder:s})=>{const o=[],i=n==="markdown"?Mi(t,{codeBlockPlaceholder:s}):bm(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),ym=(...e)=>Fr(e.filter(Boolean).join(", "))||void 0,Vs=(e,t,n,r)=>{if(!t||t===n)return e;const s=ki(t,r);return s?ym(e,s):e},Sm=(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=Cm({name:c,mimeType:e.type},t);return Vs(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 Vs(h,n,d,t.codeBlockPlaceholder)}return ki(n,t.codeBlockPlaceholder)},Am=(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=(x,w,Y)=>({text:x,ignoreSuppression:w,queueOrder:f++,dedupeKey:Y}),p=()=>{const x=c[0]??null,w=i;return x&&w?w.queueOrder<x.queueOrder?(i=null,w):c.shift()??null:x?c.shift()??null:w!==null?(i=null,w):null},v=()=>{for(;;){const x=p();if(!x)return null;if(!(!x.ignoreSuppression&&(r!=null&&r())))return x}},E=x=>{u=x.text,d=x.dedupeKey??null,h=!0,e(x.text),m=setTimeout(()=>{m=null,h=!1;const w=v();w&&E(w)},n)},_=x=>{u=x.text,d=x.dedupeKey??null,e(x.text)},y=(x,w,Y,O)=>w!=null&&O!=null?w===O:w==null&&O==null?x!=null&&x===Y:!1,A=(x,w,Y)=>{if(!x||!w&&(r!=null&&r()))return;const O=Y==null?void 0:Y.dedupeKey;if(!(h&&y(x,O,u,d)))if(h){if(((Y==null?void 0:Y.mode)??"latestOnly")==="ordered"){const G=c[c.length-1];if(G&&y(x,O,G.text,G.dedupeKey))return;c.push(g(x,w,O)),c.length>o&&c.shift();return}i=g(x,w,O)}else i=null,E(g(x,w,O))};return{announce:(x,w)=>{A(x,!1,w)},announceIgnoringSuppression:(x,w)=>{A(x,!0,w)},flush:()=>{const x=[];let w=p();for(;w!==null;)x.push(w),w=p();if(m!==null&&(clearTimeout(m),m=null),h=!1,x.length!==0)for(const Y of x)_(Y)},destroy:()=>{m!==null&&(clearTimeout(m),m=null),i=null,c.length=0,u=null,d=null,h=!1}}},Tm=e=>{switch(e){case"newMessage":case"conversationClosed":case"csatDisplayed":case"csatSubmitted":case"csatExpired":return"ordered";default:return"latestOnly"}},Im=(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(". "),xm=(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}},Rm=(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}},Mm=(e,t)=>!t||!nt(e)||e.sender.userId!==t?null:e.reqId||(e.messageId>0?String(e.messageId):null),wm=(e,t)=>Oe.isAdmin(e)?Oe.isCSAT(e):"sender"in e?e.sender.userId!==t:!1,km=e=>"messageId"in e&&e.messageId>0?String(e.messageId):"reqId"in e&&typeof e.reqId=="string"&&e.reqId.length>0?e.reqId:null,Lm=e=>e===fe.CollectionEventSource.EVENT_MESSAGE_RECEIVED||e===fe.CollectionEventSource.EVENT_MESSAGE_UPDATED,Om=({isOpened:e,opensConversationList:t})=>e?t?"closeConversationList":"closeConversation":t?"openConversationList":"openConversation",Nm=(e,t)=>{switch(e){case"closeConversationList":return t.closeConversationList;case"closeConversation":return t.closeConversation;case"openConversationList":return t.openConversationList;case"openConversation":return t.openConversation}},Dm=(e,t)=>{switch(e){case"closeConversation":return t.hintCloseConversation;case"openConversationList":return t.hintOpenConversationList;case"openConversation":return t.hintOpenConversation;default:return}},$m=({intent:e,strings:t})=>({label:Nm(e,t),hint:Dm(e,t)}),Fm="1.33.0",Ge="sb-agent",ve={ENTRY:`${Ge}-entry`,MODAL_ROOT:`${Ge}-modal-root`,WINDOW:`${Ge}-window`,LAUNCHER:`${Ge}-launcher`,WINDOW_TITLE:`${Ge}-window-title`},Li="data-sb-initial-focus",Oi="true",Pm=`[${Li}="${Oi}"]`,Ni={[Li]:Oi},Pr="data-sb-focus-trap-sentinel",Um="true",Di="data-sb-initial-focus-header",$i="true",Bm=`[${Di}="${$i}"]`,Fi={[Di]:$i},Pi="data-sb-message-input",Ui="true",Hm=`textarea[${Pi}="${Ui}"]:not(:disabled)`,Gm={[Pi]:Ui},Bi=1e3,an=2147483647,gt={MODAL:an-1,TOOLTIP:an-2,WINDOW:an-3,LAUNCHER:an-4},Hi=36,zm=100,Vm=Fm,Ur="noopener noreferrer nofollow",dr=()=>typeof document>"u"||document.visibilityState==="visible",qs=()=>typeof document<"u"&&document.visibilityState==="hidden",qm=e=>{if(dr()){e();return}if(typeof document>"u")return;const t=()=>{dr()&&(document.removeEventListener("visibilitychange",t),e())};return document.addEventListener("visibilitychange",t),()=>document.removeEventListener("visibilitychange",t)};function Ym(){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 Wm(){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 Km={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_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}`}},mr={language:"en",strings:Km,dateLocale:oc.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_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])??jt},jt="en",Vi=new Set([jt,"ko","es","pt","fr","hi","it","de","tr","ja"]),jm='@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:Xm,useContext:Br}=Ce("AgentUIElementResolver"),Zm=({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===ve.MODAL_ROOT?c:i.querySelector(`#${d}`);return{resolveElement:u,resolvePortalContainer:d=>u(d)??c}},[e,t,n]);return a.createElement(Xm,{value:s},r)};function lt(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:Jm,useContext:Hr}=Ce("EscapeDismissStack"),Ws=e=>{e.stopPropagation(),e.stopImmediatePropagation()},Qm=({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??lt(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(Jm,{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])},eh=(e,t)=>{const{register:n}=Hr();qi(e,t,n)},th=(e,t)=>{const{registerShellDismissHandler:n}=Hr();qi(e,t,n)},Yi=()=>{const{subscribe:e,getOpenCount:t}=Hr();return l.useSyncExternalStore(e,()=>t()>0,()=>!1)},nh=(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.":""))))})},Ks=Gi(mr.strings),rh={...Ks,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:Ks.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"},An={language:mr.language,dateLocale:mr.dateLocale,stringSet:rh},sh=Object.freeze(Object.defineProperty({__proto__:null,default:An},Symbol.toStringTag,{value:"Module"})),hr=new Map([[jt,An]]);async function oh(e){const t=hr.get(e);if(t)return t;try{if(Vi.has(e)){const{default:n}=await nh(Object.assign({"./languages/de.ts":()=>Promise.resolve().then(()=>require("./cjs/I-l-5Zo-.cjs")),"./languages/en.ts":()=>Promise.resolve().then(()=>sh),"./languages/es.ts":()=>Promise.resolve().then(()=>require("./cjs/D_km8dcd.cjs")),"./languages/fr.ts":()=>Promise.resolve().then(()=>require("./cjs/CLIpC7kY.cjs")),"./languages/hi.ts":()=>Promise.resolve().then(()=>require("./cjs/ChrM6HN1.cjs")),"./languages/it.ts":()=>Promise.resolve().then(()=>require("./cjs/CPZf2TWM.cjs")),"./languages/ja.ts":()=>Promise.resolve().then(()=>require("./cjs/D7UQ9OK7.cjs")),"./languages/ko.ts":()=>Promise.resolve().then(()=>require("./cjs/BMDJStMQ.cjs")),"./languages/pt.ts":()=>Promise.resolve().then(()=>require("./cjs/etCQgYrr.cjs")),"./languages/tr.ts":()=>Promise.resolve().then(()=>require("./cjs/DKQwAy8C.cjs"))}),`./languages/${e}.ts`,3);return hr.set(e,n),n}return An}catch{return An}}const{Provider:ih,useContext:ae}=Ce("Localization"),ah=({language:e=navigator.language,languageCode:t,logger:n,stringSet:r,children:s})=>{const[o,i]=l.useState(hr.get(jt));return l.useEffect(()=>{const c=t??zi(e);o.language!==c&&(n==null||n.debug("localization.useEffect: update language",{from:o.language,to:c}),oh(c).then(i))},[e,t,n]),a.createElement(ih,{value:{language:o.language,defaultStringSet:o.stringSet,stringSet:{...o.stringSet,...r},dateLocale:o.dateLocale,format:(c,u,d)=>ot.format(c,u,{locale:o.dateLocale,...d})}},s)},Tn="data-sb-agent-theme",js=e=>(t,...n)=>{let r="";return t.forEach((s,o)=>{r+=s+(n[o]??"")}),`[${Tn}='${e}'] & { ${r} }`},ee={light:js("light"),dark:js("dark")},ch=P.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
|
+
`}),lh=P.css`[${Tn}='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);}[${Tn}='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);}`,C={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 Ht 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 Xe=e=>{const t=e;return typeof t=="number"?`${t}px`:t},uh=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"})),dh=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"})),mh=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"})),hh=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"})),fh=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"})),gh=new Set(["send","chat","message","chevron-right","good","good-filled","bad","bad-filled"]),ph={close:uh,send:fh,menu:hh,expand:mh,collapse:dh,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")))},_h=e=>({size:t=24,color:n=C.color.primary.main,flipInRtl:r=!1})=>a.createElement(Ch,{$size:t,$color:n,$rtlFlip:r},a.createElement(Ht,{errorFallback:a.createElement(bh,null)},a.createElement(e,null))),Wi=Object.fromEntries(Object.entries(ph).map(([e,t])=>[e,_h(t)])),Eh=P.css`[dir='rtl'] &:not([dir='ltr']),&[dir='rtl']{transform:scaleX(-1);}`,Ch=b.default.span.attrs({"aria-hidden":"true"})`
|
|
57
|
+
width: ${({$size:e})=>Xe(e)};
|
|
58
|
+
height: ${({$size:e})=>Xe(e)};
|
|
59
59
|
display: inline-block;
|
|
60
60
|
|
|
61
61
|
svg {
|
|
@@ -74,25 +74,25 @@
|
|
|
74
74
|
stroke-linejoin: round;
|
|
75
75
|
}
|
|
76
76
|
|
|
77
|
-
${({$rtlFlip:e})=>e&&
|
|
78
|
-
`,
|
|
79
|
-
${
|
|
80
|
-
`;return n.set(e,s),s},Kd=e=>e?D.css`display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:${e};overflow:hidden;`:"",jd=p.default.span`font-stretch:normal;letter-spacing:normal;${({$variant:e,theme:t})=>qd(e,t.typography)}color:${({$color:e})=>e};${({$maxTextLines:e})=>Kd(e)}`,hn=["a[href]","button:not(:disabled)","input:not(:disabled)","select:not(:disabled)","textarea:not(:disabled)",'[tabindex]:not([tabindex="-1"])'].join(", "),ci=`${hn}, [tabindex="-1"]`,ft=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};async function yr(e){let t=e;t&&(!t.startsWith("http://")&&!t.startsWith("https://")&&(t="https://"+t),window.open(t,"_blank","noopener,noreferrer"))}function Me(e){requestAnimationFrame(()=>{requestAnimationFrame(()=>{e()})})}const Rt=(e,t)=>{for(const n of e.querySelectorAll(t))if(!n.hasAttribute(_r)&&ft(n))return n;return null},ui=e=>{let t=null,n=null;for(const r of e.querySelectorAll(hn))r.hasAttribute(_r)||ft(r)&&(t??(t=r),n=r);return t?{first:t,last:n}:null},Sr=e=>Rt(e,Xu),di=e=>Sr(e)??Rt(e,hn),Xd=e=>{const t=Sr(e);if(t)return t;const n=e.querySelector(Ju);return(n?Rt(n,ci):null)??Rt(e,hn)},jn='[role="dialog"][aria-modal="true"]',Zd=(e,t)=>{const n=new Set(Array.from(e.ownerDocument.querySelectorAll(jn)).filter(o=>o!==e&&(o.contains(e)||e.contains(o)))),r=t==null?void 0:t.closest(jn);return r&&r!==e&&n.add(r),n},Jd=(e,t)=>Array.from(e.ownerDocument.querySelectorAll(jn)).some(n=>n!==e&&!t.has(n)&&!n.contains(e)&&ft(n)),Qd=e=>{const t=di(e)??e;t===e&&mi(e),t.focus()},mi=e=>{e.hasAttribute("tabindex")||e.setAttribute("tabindex","-1")},em=(e,t)=>{const n=ui(e);if(!n){mi(e),e.focus();return}n[t].focus()},vo=(e,t)=>{const n=e.ownerDocument.createElement("span");return n.tabIndex=0,n.setAttribute(_r,Zu),n.style.cssText=["position: fixed","width: 1px","height: 1px","opacity: 0","overflow: hidden","pointer-events: none"].join(";"),n.addEventListener("focus",()=>em(e,t)),n},tm=(e,t)=>{e.key==="Tab"&&(e.defaultPrevented||e.target===t&&(ui(t)||(e.preventDefault(),t.focus())))},nm=(e,t)=>t instanceof HTMLElement?e instanceof Document?t===e.body||t===e.documentElement:!1:!0,pn=(e,t,{nameReady:n=!0}={})=>{const r=u.useRef(0),o=u.useRef(!1);u.useEffect(()=>{if(!e||!t.current){o.current=!1;return}r.current+=1;const s=r.current,a=t.current,l=a.getRootNode(),c=l.activeElement instanceof HTMLElement?l.activeElement:null,d=Zd(a,c);return()=>{c&&Me(()=>{if(r.current!==s)return;const m=l.activeElement;a.isConnected&&m instanceof HTMLElement&&m!==a&&!a.contains(m)&&!nm(l,m)&&m.matches(ci)&&ft(m)||Jd(a,d)||!c.isConnected||!ft(c)||c.focus()})}},[e,t]),u.useEffect(()=>{if(!e||!t.current)return;const s=t.current;let a=!1;const l=()=>{if(a||o.current||!s.isConnected)return;const m=s.getRootNode().activeElement;if(m instanceof HTMLElement&&m!==s&&s.contains(m)&&ft(m)){o.current=!0;return}o.current=!0,Qd(s)};if(n)return Me(l),()=>{a=!0};const c=setTimeout(()=>Me(l),Js);return()=>{a=!0,clearTimeout(c)}},[e,t,n]),u.useEffect(()=>{if(!e||!t.current)return;const s=t.current,a=vo(s,"last"),l=vo(s,"first"),c=d=>tm(d,s);return s.insertBefore(a,s.firstChild),s.appendChild(l),s.addEventListener("keydown",c),()=>{s.removeEventListener("keydown",c),a.remove(),l.remove()}},[e,t])},ot=({style:e,portalContainerId:t,visible:n,onClose:r,children:o,cancelable:s=!0,"aria-label":a,"aria-labelledby":l,"aria-describedby":c})=>{const d=u.useRef(null),{resolvePortalContainer:m}=br();return pn(n,d),dd(n,s?r:ce),n?Ea.createPortal(i.createElement(rm,{onClick:s?r:void 0,style:e},i.createElement(om,{ref:d,role:"dialog","aria-modal":"true","aria-label":a,"aria-labelledby":l,"aria-describedby":c,onClick:f=>f.stopPropagation()},o)),m(t)):null},rm=p.default.div`position:fixed;top:0;left:0;width:100%;height:100%;background:${h.color.overlay.dark};display:flex;justify-content:center;align-items:center;z-index:${it.MODAL};`,om=p.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:${it.MODAL};`,sm=({id:e,children:t})=>i.createElement(im,{id:e},t),im=p.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;`,yo=(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?{}:Ws}:n},am=()=>{const e=`${u.useId()}-`;return(t,n)=>{if(!t)return{props:{},node:null};const r=e+n,o=u.createElement(sm,{id:r,children:t});return{props:{"aria-describedby":r},node:o}}},So=({name:e,mimeType:t,selected:n},r)=>{var s;const o=ze(t??"")?r.A11Y_FILE_IMAGE(e):mn(t??"")?r.A11Y_FILE_VIDEO(e):gs({name:e,mimeType:t})?r.A11Y_FILE_PDF(e):r.A11Y_FILE_DOCUMENT(e);return n?((s=r.A11Y_FILE_SELECTED)==null?void 0:s.call(r,o))??`${o}, selected`:o},lm=e=>t=>{t.repeat||(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),e())},xt=({onActivate:e})=>({role:"button",tabIndex:0,onClick:e,onKeyDown:lm(e)}),cm=({disabled:e,currentIndex:t,totalCount:n,onNavigate:r})=>o=>{var c;if(e||n<=0)return;let s=null;switch(o.key){case"ArrowRight":case"ArrowDown":s=(t+1)%n;break;case"ArrowLeft":case"ArrowUp":s=(t-1+n)%n;break;default:return}o.preventDefault(),r(s);const a=o.currentTarget.parentElement,l=a==null?void 0:a.querySelectorAll('[role="radio"]');(c=l==null?void 0:l[s])==null||c.focus()},Ao=(e,t,n,r,o,s)=>{let a=-1;return(e||!o&&n===0)&&(a=0),{role:"radio","aria-checked":e,"aria-disabled":t,onKeyDown:cm({disabled:t,currentIndex:n,totalCount:r,onNavigate:s}),tabIndex:a}},oe=()=>{const{stringSet:e}=se(),t=am(),n=(a,l)=>{let c=e.A11Y_HINT_OPEN_FILE,d="of";ze(a??"")&&(c=e.A11Y_HINT_OPEN_IMAGE,d="oi"),l!==void 0&&(d+=l);const m=t(c,d);return{props:m.props,descriptionNode:m.node}},r=a=>({"aria-label":So(a,e)});return{launcher:{button:({isOpened:a,opensConversationList:l})=>{const c=Ku({intent:Yu({isOpened:a,opensConversationList:l}),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";c.hint===e.A11Y_HINT_OPEN_CONVERSATION&&(d="lo"),c.hint===e.A11Y_HINT_OPEN_CONVERSATIONS&&(d="los");const m=t(c.hint,d);return{props:{"aria-label":c.label,...m.props},descriptionNode:m.node}}},messenger:{closeButton:()=>({props:{"aria-label":e.A11Y_CLOSE_MESSENGER},descriptionNode:null}),expandButton:a=>{let l=e.A11Y_EXPAND_MESSENGER;return a&&(l=e.A11Y_COLLAPSE_MESSENGER),{props:{"aria-label":l},descriptionNode:null}},connectionDelayDialog:()=>({props:{"aria-label":e.CONNECTION_DELAY__TITLE},descriptionNode:null})},conversation:{header:{menuButton:()=>{const a=e.A11Y_HINT_OPEN_MENU,l=t(a,"mb");return{props:{"aria-label":e.A11Y_MENU,...l.props},descriptionNode:l.node}},closeConversationButton:()=>{const a=e.A11Y_HINT_CLOSE_CONVERSATION,l=t(a,"cc");return{props:{"aria-label":e.A11Y_CLOSE_CONVERSATION,...l.props},descriptionNode:l.node}},handoffButton:()=>{const a=e.A11Y_HINT_CONNECT_TO_AGENT,l=t(a,"h");return{props:{"aria-label":e.A11Y_CONNECT_AGENT,...l.props},descriptionNode:l.node}},title:(a,l)=>({props:yo(a,l),descriptionNode:null}),memoryIndicator:a=>{let l=e.A11Y_MEMORY_INDICATOR_OFF,c="mof";a&&(l=e.A11Y_MEMORY_INDICATOR_ON,c="mon");const d=t(l,c);return{props:{"aria-label":e.A11Y_MEMORY_INDICATOR_MANAGE,...d.props},descriptionNode:d.node}}},messageInput:{attachFileButton:()=>{const a=e.A11Y_HINT_ATTACH_FILE,l=t(a,"af");return{props:{"aria-label":e.A11Y_ATTACH_FILE,...l.props},descriptionNode:l.node}},sendButton:()=>{const a=e.A11Y_HINT_SEND_MESSAGE,l=t(a,"sm");return{props:{"aria-label":e.A11Y_SEND_MESSAGE,...l.props},descriptionNode:l.node}},textInput:a=>({props:{role:"textbox","aria-label":a,...ed},descriptionNode:null})},suggestedReplies:{item:(a,l)=>{const c=e.A11Y_HINT_SEND_REPLY,d=t(c,`sr${l}`);return{props:{"aria-label":`${e.A11Y_SUGGESTED_REPLY}, ${a}`,...d.props},descriptionNode:d.node}}},feedback:{container:()=>{const a=e.A11Y_HINT_SELECT_RATING,l=t(a,"fb");return{props:l.props,descriptionNode:l.node}},button:(a,l)=>{const c=e.A11Y_HINT_SELECT_RATING,d=t(c,`f${a}`);let m=e.FEEDBACK_BAD;return a==="good"&&(m=e.FEEDBACK_GOOD),{props:{"aria-label":m,...d.props,"aria-pressed":l},descriptionNode:d.node}},optionsBottomSheet:()=>({props:{"aria-label":e.A11Y_FEEDBACK_OPTIONS},descriptionNode:null})},newMessagesButton:()=>{const a=e.A11Y_HINT_VIEW_NEW_MESSAGES,l=t(a,"nm");return{props:{"aria-label":e.A11Y_SCROLL_TO_NEW_MESSAGES,...l.props},descriptionNode:l.node}},scrollToBottomButton:()=>{const a=e.A11Y_HINT_VIEW_NEW_MESSAGES,l=t(a,"sb");return{props:{"aria-label":e.A11Y_SCROLL_TO_BOTTOM,...l.props},descriptionNode:l.node}},startNewConversationButton:({onActivate:a})=>({props:{...xt({onActivate:a}),"aria-label":e.TALK_TO_AGENT},descriptionNode:null}),poweredByLink:()=>({props:{"aria-label":`${e.POWERED_BY} Sendbird`},descriptionNode:null}),retryButton:(a=e.RETRY)=>({props:{"aria-label":a},descriptionNode:null}),file:{label:(a,l,c)=>a?So({name:a,mimeType:l,selected:c},e):"",preview:a=>({props:r(a),descriptionNode:null}),buttonLikePreview:({onActivate:a,...l},c)=>{const d=n(l.mimeType,c);return{props:{...xt({onActivate:a}),...r(l),...d.props},descriptionNode:d.descriptionNode}},removeButton:a=>({props:{"aria-label":e.A11Y_FILE_REMOVE_BUTTON(a)},descriptionNode:null})},csat:{scoresContainer:a=>{const l=e.A11Y_HINT_SELECT_RATING,c=t(l,"cs");return{props:{role:"radiogroup","aria-label":a,...c.props},descriptionNode:c.node}},scoreItem:({score:a,label:l,selected:c,disabled:d,currentIndex:m,totalCount:f,hasSelection:g,onChange:E})=>{var _;const y=l.trim()||l,v=e.A11Y_HINT_SELECT_RATING,b=t(v,`cs${a}`);return{props:{disabled:d,onClick:()=>E(a),...Ao(c,d,m,f,g,C=>E(C+1)),...b.props,"aria-label":((_=e.A11Y_CSAT_RATING_LABEL)==null?void 0:_.call(e,a,y))??`${a} / ${f} — ${y}`},descriptionNode:b.node}},submitButton:a=>({props:{"aria-label":a},descriptionNode:null})},form:{button:a=>({props:{"aria-label":a},descriptionNode:null}),textInput:(a,l,c,d)=>({props:{...d!=null&&d.labelId?{"aria-labelledby":d.labelId}:{"aria-label":a},"aria-required":l,"aria-disabled":c},descriptionNode:null}),numberInput:(a,l,c)=>({props:{"aria-label":a,"aria-required":l,"aria-disabled":c},descriptionNode:null}),singleSelectGroup:a=>{const l={role:"radiogroup"};return a&&(l["aria-label"]=a),{props:l,descriptionNode:null}},singleSelectOption:(a,l,c,d,m,f,g)=>({props:{...Ao(l,c,d,m,f,g),"aria-label":a},descriptionNode:null}),multiSelectOption:(a,l,c)=>({props:{"aria-label":a,"aria-pressed":l,"aria-disabled":c},descriptionNode:null})}},conversationList:{headerTitle:(a,l)=>({props:yo(a,l),descriptionNode:null}),footer:{button:({onActivate:a})=>({props:{...xt({onActivate:a}),"aria-label":e.TALK_TO_AGENT},descriptionNode:null})},item:({agent:a,status:l,time:c,unreadCount:d,onActivate:m})=>{if(!m)return{props:{"aria-label":e.A11Y_CONVERSATION_ITEM(a,l,c,d)},descriptionNode:null};const f=e.A11Y_HINT_OPEN_CONVERSATION,g=t(f,"cli");return{props:{...xt({onActivate:m}),...g.props,"aria-label":e.A11Y_CONVERSATION_ITEM(a,l,c,d)},descriptionNode:g.node}}}}},um=({title:e,description:t,highlightedText:n})=>{const r=mu(t,n);return i.createElement(mm,null,i.createElement(fm,null,i.createElement($,{as:"div",variant:"h1",color:h.themedColor.textHighEmphasis},e),t&&i.createElement(gm,null,i.createElement($,{as:"div",variant:"body3",color:h.themedColor.textMidEmphasis},r.beforeText,r.highlightedText?i.createElement(hm,null,r.highlightedText):null,r.afterText))))},dm=()=>{const{components:e}=_n.useContext(),{stringSet:t}=se(),{messenger:n}=oe(),r=uu(),o=r.showDescription?du(r.remainingTime):"",s=r.showDescription?t.CONNECTION_DELAY__DESCRIPTION(o):"";return i.createElement(ot,{portalContainerId:be.WINDOW,visible:r.visible,onClose:ce,...n.connectionDelayDialog().props},i.createElement(e.Dialog,{title:t.CONNECTION_DELAY__TITLE,description:s,highlightedText:o||void 0}))},_n=Ge({template:dm,components:{Dialog:um}}),mm=p.default.div`width:280px;padding:24px;margin:0 auto;border-radius:4px;box-sizing:border-box;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,fm=p.default.div`display:flex;flex-direction:column;`,gm=p.default.div`margin-top:16px;`,hm=p.default.strong`font-weight:700;`,pm=({url:e})=>yr(e),{Provider:_m,Consumer:fi,useContext:ae}=pe("Messenger");function Em({children:e,state:t,enableCloseConversationButton:n=!1,enableExpandButton:r=!0,enableAutoDisconnectInLauncher:o=!0,...s}){const[a,l]=u.useState(!1),[c,d]=u.useState(!1),m={opened:(t==null?void 0:t.opened)??a,setOpened:(t==null?void 0:t.setOpened)??l,expanded:(t==null?void 0:t.expanded)??c,setExpanded:(t==null?void 0:t.setExpanded)??d},{resolveElement:f}=br(),g=u.useCallback(()=>{var v;m.setOpened(!1),(v=f(be.LAUNCHER))==null||v.focus()},[m.setOpened,f]);md(m.opened,g);const{Template:E}=_n.useContext(),y=u.useMemo(()=>{var v;return{...s.handlers,onClickLink:((v=s.handlers)==null?void 0:v.onClickLink)??pm}},[s.handlers]);return i.createElement(Pl,{...s},v=>i.createElement(_m,{value:{...s,...v,state:m,enableCloseConversationButton:n,enableExpandButton:r,enableAutoDisconnectInLauncher:o,handlers:y}},i.createElement(E,null),e))}const gi=/iPad|iPhone|iPod/.test(navigator.userAgent),bm=/Android/.test(navigator.userAgent),Dt=e=>gi||bm;let yt=null,Ln=null;const Cm=(e,t=5e3)=>{yt&&(clearInterval(yt),clearTimeout(Ln));const n=document.title;yt=setInterval(()=>{document.title=document.title===e?n:e},750),Ln=setTimeout(()=>{clearInterval(yt),yt=null,Ln=null,document.title=n},t)},hi=()=>{Promise.resolve().then(()=>require("./cjs/B93o4u0P.cjs")).then(e=>{new Audio(e.default).play().catch(()=>{})})},Ae=D.css`&:focus-visible{outline:2px solid ${h.themedColor.primary};outline-offset:2px;}`,xo=e=>{if(typeof e=="string"||typeof e=="number")return String(e)},En=({visible:e,title:t,description:n,confirmText:r="OK",cancelText:o,onConfirm:s,onCancel:a,onClose:l,"aria-label":c})=>{const d=u.useId(),m=u.useId(),f=c??xo(t)??xo(n),g=c?void 0:t?d:n?m:void 0,E=t&&n?m:void 0,y=()=>{l(),Me(()=>s==null?void 0:s())},v=()=>{l(),Me(()=>a==null?void 0:a())};return i.createElement(ot,{portalContainerId:be.WINDOW,visible:e,onClose:l,"aria-label":f,"aria-labelledby":g,"aria-describedby":E},i.createElement(vm,null,i.createElement(ym,null,t&&i.createElement("div",{id:d},i.createElement($,{variant:"h1",color:h.themedColor.textHighEmphasis},t)),n&&i.createElement(Sm,{id:m},i.createElement($,{variant:"body3",color:h.themedColor.textMidEmphasis},n))),i.createElement(Am,null,o&&i.createElement(To,{onClick:v},i.createElement($,{variant:"button",color:h.themedColor.textHighEmphasis},o)),i.createElement(To,{onClick:y},i.createElement($,{variant:"button",color:h.themedColor.primary},r)))))},vm=p.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};`,ym=p.default.div`margin-bottom:16px;`,Sm=p.default.div`margin-top:16px;`,Am=p.default.div`display:flex;flex-direction:row;justify-content:flex-end;`,To=p.default.button`all:unset;display:flex;justify-content:center;align-items:center;border-radius:4px;cursor:pointer;background-color:transparent;padding:10px 16px;${Ae}`,{Provider:xm,useContext:ke}=pe("MessengerSession"),Tm=u.forwardRef(function({children:e,...t},n){return i.createElement(Ec,{ref:n,...t},r=>i.createElement(Im,{...r},e))}),Im=({children:e,...t})=>{const{chatSDK:n,logger:r,appId:o,aiAgentId:s,agentPreviewConfigs:a,state:l,handlers:c,dispatcher:d,_aiAgentSDK:m}=ae(),{userSessionInfo:f,authenticate:g,userSession:E,aiAgentInfo:y,launcherInfo:v}=t,[b,_]=u.useState(!1),C=u.useRef(null);ht(n,{async onUserJoined(A,w){var k,R,O,z;A.conversation&&A.conversation.type===Ee.ConversationType.PROACTIVE&&w.userId===((k=n.currentUser)==null?void 0:k.userId)&&(r.info("messengerSession.onUserJoined: proactive channel joined",A.url),(O=m.session)==null||O._updateActiveChannel({url:A.url,status:"open",conversationStatus:(R=A.conversation)==null?void 0:R.status}),l.setOpened(!0),wm({sound:document.hidden||!l.opened}),(z=C.current)==null||z.call(C,{channel:A}))}}),u.useEffect(()=>{g().then(({launcher:A})=>{A.auto_open&&!Dt()&&setTimeout(()=>l.setOpened(!0),500)}).catch(A=>{var w;r.error("messengerSession: failed to initialize",A),(w=c==null?void 0:c.onInitializeFailed)==null||w.call(c,A)})},[n,o,s,f==null?void 0:f.userId]),u.useEffect(()=>{const A=()=>_(!0);return d.subscribe(Be.AnonymousSessionTokenExpired,A),()=>d.unsubscribe(Be.AnonymousSessionTokenExpired,A)},[d]);const x=u.useCallback(()=>{t.deauthenticate().finally(()=>window.location.reload())},[t.deauthenticate]);return!E||!y||!v?null:i.createElement(xm,{value:{...t,userSession:E,aiAgentInfo:{...y,...a==null?void 0:a.bot},launcherInfo:{...v,...a==null?void 0:a.launcher},registerOnJoinedProactiveConversation:A=>C.current=A}},e,i.createElement(En,{visible:b,title:"Session timed out",description:"Start a new conversation.",onConfirm:x,onClose:ce}))};function wm({sound:e}){Cm("🔔You have received a new message"),e&&hi()}const un=`@${$e}-focused-channel`,pi=`${Date.now()}-${Math.random().toString(36).slice(2)}`,Mm=()=>{try{const e=localStorage.getItem(un);return e?JSON.parse(e).channelUrl??null:null}catch{return null}},Io=e=>{try{localStorage.setItem(un,JSON.stringify({channelUrl:e,tabId:pi}))}catch{}},wo=()=>{try{const e=localStorage.getItem(un);if(!e)return;JSON.parse(e).tabId===pi&&localStorage.removeItem(un)}catch{}},km=(e,t)=>(u.useEffect(()=>{if(!t||!e)return;const n=()=>Io(e),r=()=>wo();return document.hasFocus()&&Io(e),window.addEventListener("focus",n),window.addEventListener("blur",r),()=>{window.removeEventListener("focus",n),window.removeEventListener("blur",r),wo()}},[t,e]),{isChannelViewedInAnyTab:()=>document.hasFocus()||Mm()===e}),Rm=e=>{const{config:t,chatSDK:n}=ae(),{sdkUser:r}=ke(),o=t.conversation.messageAlertSoundEnabled,{isChannelViewedInAnyTab:s}=km(e,o);ht(n,{onMessageReceived(a,l){if(!o||a.url!==e||s())return;(tt(l)&&l.sender.userId!==(r==null?void 0:r.userId)||l.isAdminMessage()&&!l.silent)&&hi()}})};function Lm(e){return new Promise(t=>{const n=new Image;n.onload=function(){const r=String(n.width),o=String(n.height);URL.revokeObjectURL(n.src),t({width:r,height:o})},n.src=URL.createObjectURL(e)})}async function Om(e){if("file"in e&&e.file instanceof File&&e.file.type.startsWith("image/")){const{width:t,height:n}=await Lm(e.file);return new He.MessageMetaArray({key:ms,value:[t,n]})}}const Nm=({onScrollAfterSendMessage:e})=>{const{agentPreviewConfigs:t,handlers:n}=ae(),r=u.useRef(t==null?void 0:t.agentAttributes);return r.current=t==null?void 0:t.agentAttributes,{onBeforeSendMessage:async o=>{const s=await Om(o),a={...o,metaArrays:s?[s]:void 0},l=Dm(r.current);return l?{...a,data:JSON.stringify(l)}:a},onAfterSendMessage:o=>{var s,a,l;e(),(s=n==null?void 0:n.onMessageSend)==null||s.call(n,o.message),o.sendingStatus===He.SendingStatus.SUCCEEDED?(a=n==null?void 0:n.onCustomEvent)==null||a.call(n,{type:"message-sent-succeeded",data:{message:o}}):o.sendingStatus===He.SendingStatus.PENDING&&((l=n==null?void 0:n.onCustomEvent)==null||l.call(n,{type:"message-sent-pending",data:{message:o}}))}}},Dm=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},dt=50,On=dt-40,{Provider:$m,useContext:_i}=pe("ConversationScroll"),Mo={viewport:0,contentHeight:0,contentSnapshotHeight:0,shouldRecalc:!1,shouldUpdate:!1},Nn=e=>Math.max(0,e.scrollHeight-e.scrollTop-e.clientHeight);function Pm({scrollMode:e,messageStackDirection:t,children:n}){const r=u.useRef(null),o=u.useRef(null),s=u.useRef(0),a=u.useRef(0),l=u.useRef(!1),c=u.useRef(!1),d=u.useRef(null),m=u.useRef(Mo),f=u.useRef(!1),g=u.useRef(null),[E,y]=u.useState(0),[v,b]=u.useState(0),[_,C]=u.useState(!1),[x,A]=u.useState(!1),[w,M]=u.useState(!0),k=I=>{const L=Nn(I);return s.current=L,b(L),L},R=()=>{d.current&&(clearTimeout(d.current),d.current=null)},O=u.useMemo(()=>_||t==="bottom"?"auto":e,[_,t,e]),z=()=>{m.current.contentSnapshotHeight=m.current.contentHeight,m.current.shouldUpdate=!0,m.current.shouldRecalc=!0},Y=()=>{const I=r.current;!I||!m.current.shouldUpdate||y(L=>{m.current.shouldUpdate=!1;const{contentHeight:N,contentSnapshotHeight:K,shouldRecalc:G}=m.current,H=I.clientHeight;if(K>N)return L;const U=P(I,{messageType:"outgoing"});let de=0;if(U){const Pe=U.message.offsetTop-On+H;de=Math.max(0,Pe-N)}else{const Pe=N-K,ne=H-On;de=Math.max(0,Pe-ne)}return L===0||de!==L||G?(m.current.shouldRecalc=!1,de):L})},P=u.useCallback((I,L)=>{const{messageType:N="all"}=L??{},K=Array.from(I.querySelectorAll(`#${$e}-message-item`));let G=K;N==="outgoing"&&(G=K.filter(fe=>fe.getAttribute("data-layout-id")==="outgoingmessage"));const H=G[G.length-1];if(!H)return null;const U=I.getBoundingClientRect(),de=H.getBoundingClientRect(),Pe=I.scrollTop+(de.top-U.top),ne=Pe+H.offsetHeight;return{message:H,scrollTop:Pe,lastMessageBottom:ne}},[]),V=u.useCallback(()=>{const I=r.current;if(!I||O!=="fixed")return;const L=P(I);m.current.contentHeight=(L==null?void 0:L.lastMessageBottom)??I.scrollHeight,!f.current&&m.current.contentSnapshotHeight>0&&z(),c.current?s.current=Nn(I):k(I),Y()},[O,P]),B=u.useCallback(()=>{o.current&&(o.current.disconnect(),o.current=null),R(),m.current=Mo,y(0),b(0),M(!0),s.current=0,l.current=!1,a.current=0,c.current=!1},[]),W=u.useCallback((I=!0)=>{const L=s.current>dt;if(l.current=!1,b(0),!L){Me(()=>{const N=r.current;N&&!l.current&&N.scrollTo({top:N.scrollHeight,behavior:"auto"})});return}c.current||(c.current=!0,M(!1),R()),Me(()=>{const N=r.current;if(!N){c.current=!1,M(!0);return}if(l.current){c.current=!1,k(N),M(!0);return}const K=()=>{if(r.current!==N){c.current=!1,r.current&&k(r.current),M(!0);return}c.current=!1,k(N),M(!0)};if(I&&!d.current){const G=setTimeout(K,500);d.current=G,N.addEventListener("scrollend",()=>{clearTimeout(G),d.current=null,K()},{once:!0})}N.scrollTo({top:N.scrollHeight,behavior:I?"smooth":"auto"}),I||K()})},[]),q=u.useCallback(I=>{I&&(r.current=I,O==="fixed"&&(B(),m.current.viewport=I.clientHeight,o.current=new MutationObserver(()=>{V()}),o.current.observe(I,{childList:!0,subtree:!0})))},[O,V,B]),ie=u.useCallback(()=>{const I=r.current;if(!I)return;const L=P(I,{messageType:"outgoing"});L&&(I.scrollTo({top:L.message.offsetTop-On,behavior:"smooth"}),g.current&&clearTimeout(g.current),g.current=setTimeout(()=>{A(!1)},500))},[P]),_e=(I,L,N)=>{const K=Nn(I);if(N&&K>dt){c.current=!1,l.current=!0,R(),k(I),M(!0),a.current=L;return}s.current=K},Le=(I,L,N)=>{const G=k(I)<=dt;L&&!G&&(l.current=!0,R()),N&&G&&(l.current=!1)},J=I=>{const{scrollTop:L}=I.currentTarget,N=a.current;c.current?_e(I.currentTarget,L,L<N):Le(I.currentTarget,L<N,L>N),a.current=L},T=u.useCallback(()=>{O==="fixed"&&(A(!0),z())},[O]),F=u.useCallback(()=>{O==="fixed"?setTimeout(()=>ie(),300):W()},[O,ie]),Q=u.useCallback(I=>{f.current=I,O==="fixed"?z():l.current||W()},[O,W]),re=u.useCallback(I=>{C(I),I&&(y(0),o.current&&(o.current.disconnect(),o.current=null))},[]),le=u.useCallback(I=>{O==="auto"&&I&&!l.current&&W()},[O,W]),De=!(v<=dt)&&!x,xe=u.useCallback(()=>s.current>dt,[]);return i.createElement($m,{value:{ref:q,state:{bottomSpace:E,isAwayFromBottom:De,isScrollPositionReconciled:w,shouldCountNewMessages:xe},props:{onScroll:J},actions:{scrollToBottom:W,onBeforeMessageSend:T,onAfterMessageSend:F,onStreamingUpdate:Q,onConversationClosed:re,onTypingIndicatorUpdate:le}}},n)}const{Provider:Fm,Context:Um,useContext:Se}=pe("Conversation"),Bm=({children:e})=>{var o;const{channelSource:t}=Se(),n=(o=t.channel)==null?void 0:o.url,{checkForUserActionRequired:r}=Kc(n);return u.useEffect(()=>{var a;const s=(a=t.channel)==null?void 0:a.lastMessage;s&&r(s)},[t.channel,r]),i.createElement(i.Fragment,null,e)},Hm=({channelUrl:e,onClearChannelUrl:t,onNavigateToConversationList:n,shouldMarkAsRead:r,children:o})=>{const{activeChannel:s,refreshActiveChannel:a}=ke(),l=_i(),c=e||(s==null?void 0:s.url);Rm(c);const{onBeforeSendMessage:d,onAfterSendMessage:m}=Nm({onScrollAfterSendMessage:()=>{l.actions.onAfterMessageSend()}}),f=u.useCallback(y=>(l.actions.onBeforeMessageSend(),d(y)),[l.actions,d]),g=u.useCallback(y=>{const v=y.some(b=>We.isStreaming(b));l.actions.onStreamingUpdate(v)},[l.actions.onStreamingUpdate]),E=u.useCallback(async()=>{await a(),e&&(t==null||t())},[a,e,t]);return i.createElement(kc,{key:c,channelUrl:c,onBeforeSendMessage:f,onAfterSendMessage:m,onMessagesUpdated:g,onMessagesReceived:g,onChannelDeleted:E,onConversationClosedStatusChanged:l.actions.onConversationClosed,shouldMarkAsRead:r,shouldCountNewMessages:l.state.shouldCountNewMessages},y=>i.createElement(Fm,{value:{...y,scrollSource:l,goToActiveConversation:E,onNavigateToConversationList:n}},i.createElement(Bm,null,o)))},Ei=({children:e,...t})=>{const{config:n}=Re(),{agentPreviewConfigs:r}=ae(),o=n.conversation.list.scrollMode,s=r==null?void 0:r.messageStackDirection;return i.createElement(Pm,{scrollMode:o,messageStackDirection:s},i.createElement(Hm,{...t},e))},Ar=u.createContext({onDrop:ce,subscribe:()=>ce}),Xn=({children:e})=>{const t=u.useRef(new Set);return i.createElement(Ar.Provider,{value:{onDrop:n=>{var r;if(n.preventDefault(),(r=n.dataTransfer)!=null&&r.files){const o=Array.from(n.dataTransfer.files);o.length>0&&t.current.forEach(s=>s(o))}},subscribe:n=>(t.current.add(n),()=>t.current.delete(n))}},e)},Gm=({onDropFiles:e})=>{const{subscribe:t}=u.useContext(Ar);u.useEffect(()=>t(e),[e])};Xn.Consumer=({children:e})=>{const{onDrop:t}=u.useContext(Ar);return e({onDrop:t,onDragOver:o=>o.preventDefault()})};const bi=pe("WindowTitle",{hasWindowTitleReference:!1,isTitlePending:!1,isWindowNameReady:!0,registerWindowTitleReference:()=>ce,registerWindowTitlePending:()=>ce}),zm=bi.Provider,Ci=bi.useContext,ko=()=>{const e=u.useRef(0),[t,n]=u.useState(!1),r=u.useCallback(()=>{let o=!0;return e.current+=1,e.current===1&&n(!0),()=>{o&&(o=!1,e.current=Math.max(0,e.current-1),e.current===0&&n(!1))}},[]);return[t,r]},xr=({children:e})=>{const[t,n]=ko(),[r,o]=ko(),s=!r||t,a=u.useMemo(()=>({hasWindowTitleReference:t,isTitlePending:r,isWindowNameReady:s,registerWindowTitleReference:n,registerWindowTitlePending:o}),[t,r,n,o]);return i.createElement(zm,{value:a},e)},bn=Ci,vi=({enabled:e,label:t})=>{const{registerWindowTitleReference:n,registerWindowTitlePending:r}=Ci(),o=e&&t.trim().length>0;return u.useLayoutEffect(()=>{if(e)return r()},[r,e]),u.useLayoutEffect(()=>{if(o)return n()},[n,o]),{enabled:o,id:o?be.WINDOW_TITLE:void 0}},Vm=(e,t)=>{const r=(t?Rt(e,t):null)??Xd(e)??e;r===e&&!e.hasAttribute("tabindex")&&e.setAttribute("tabindex","-1"),r.focus({focusVisible:!1})},yi=(e,{enabled:t,ready:n,nameReady:r=!0,targetSelector:o,suppressed:s=!1})=>{const a=u.useRef(!1);u.useEffect(()=>{if(!t){a.current=!1;return}if(a.current||!e.current||s||o&&!n)return;const l=Sr(e.current)!=null;if(!o&&!l&&!n)return;let c=!1;const d=()=>{c||a.current||!e.current||(a.current=!0,Vm(e.current,o))};if(r)return Me(d),()=>{c=!0};const m=setTimeout(()=>Me(d),Js);return()=>{c=!0,clearTimeout(m)}},[t,n,r,o,e,s])},Ym=(e,t)=>{const{announcementsEnabled:n}=Xe(),{channelSource:r}=Se(),{isWindowNameReady:o}=bn(),s=oi(),a=r.channel!=null||r.error!=null;yi(e,{enabled:n,ready:a,nameReady:o,targetSelector:t==="messageInput"?Qu:void 0,suppressed:s})},Wm=e=>ze(e)||mn(e);function qm(e){return e.isAdminMessage()?e.message==="The channel's custom_type was updated.":!1}function Km(e,t){return e.filter(n=>We.isWelcomeMessage(n,t))}const Si=(e,{previewWelcomeMessages:t,aiAgentUserId:n})=>e.filter(r=>qm(r)?!1:t.length>0?!We.isWelcomeMessage(r,n):!0),jm=[],Ai=()=>{var y,v,b,_,C,x;const{agentPreviewConfigs:e={},aiAgentId:t}=ae(),{aiAgentInfo:n,userSession:r}=ke(),{channelSource:o,messageSource:s,state:{input:a,streamAnimation:l}}=Se(),c=e.welcomeMessages??jm,d=u.useMemo(()=>Si(s.messages,{previewWelcomeMessages:c,aiAgentUserId:t}),[t,s.messages,c]),m=nt(o.channel),f=(v=(y=ys(o.channel,r.userId))==null?void 0:y.nickname)==null?void 0:v.trim(),g=m?(_=(b=o.channel)==null?void 0:b.name)==null?void 0:_.trim():(C=n==null?void 0:n.nickname)==null?void 0:C.trim(),E=f||g||void 0;return{initialized:s.initialized,channelUrl:(x=o.channel)==null?void 0:x.url,agentName:E,isClosed:Ne(o.channel),isHandedOff:m,messages:d,filteredMessagesCount:d.length,hasWelcomeMessages:c.length>0,inputDisabled:a.disabled,inputDisabledBy:a.disabledBy,isStreamAnimating:l.isAnimating,subscribeMessageEvents:s.subscribeMessageEvents,currentUserId:r.userId}},Xm=(e={})=>{const{announceScreenEntry:t,announcementsEnabled:n}=Xe(),{initialized:r=!1,channelUrl:o,agentName:s,isClosed:a=!1,messages:l=[],hasWelcomeMessages:c=!1}=e,d=u.useRef(null),m=u.useMemo(()=>l.some(g=>we.isAdmin(g)&&we.isCSAT(g)),[l]),f=l.length===0&&!c;u.useEffect(()=>{if(!n){d.current=null;return}!r||!o||d.current!==o&&(t({screen:"conversation",agentName:s,isClosed:a,hasCSAT:m,...f?{isEmpty:!0}:{}}),d.current=o)},[s,t,n,o,m,r,a,f])},Zm=()=>{const e=Ai();Xm(e)},Jm=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}),Ro=(e,t,n=Je.format)=>{const r=Du(e,Jm(t)),o="sender"in e?e.sender:void 0,s=e.createdAt!=null&&e.createdAt!==0?n(e.createdAt,t.DATE_FORMAT__MESSAGE_TIMESTAMP):void 0;return{senderName:typeof(o==null?void 0:o.nickname)=="string"&&o.nickname.trim()||void 0,body:r||void 0,time:s}},Qm={senderName:!0,body:!0,time:!0},ef=Object.keys(Qm),tf=(e,t)=>ef.every(n=>e[n]===t[n]),Lo=2e3,Oo=400,Zn=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]},xi=e=>{if(!we.isAdmin(e)||!we.isCSAT(e))return null;const t=zu(e);return t?`csat:${t}`:null},nf=e=>{const t=new Set;for(const n of e){const r=xi(n);r&&t.add(r)}return t},rf=(e,t)=>{for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(r&&Zn(r).some(o=>t.includes(o)))return r}},Dn=(e,t)=>e.some(n=>t.includes(n)),No=()=>typeof document>"u"?null:document.activeElement instanceof HTMLElement?document.activeElement:null,$n=e=>new Map(e.map(({key:t,sendingStatus:n})=>[t,n])),of=()=>{const{announceStatus:e,announcementsEnabled:t}=Xe(),{stringSet:n,format:r}=se(),{channelUrl:o,messages:s,isClosed:a,isHandedOff:l,agentName:c,initialized:d,inputDisabled:m,inputDisabledBy:f,isStreamAnimating:g,subscribeMessageEvents:E,currentUserId:y}=Ai(),{outgoingMessageStates:v,outgoingMessageStatusSignature:b}=u.useMemo(()=>{if(!y)return{outgoingMessageStates:[],outgoingMessageStatusSignature:""};const J=s.flatMap(T=>{const F=Hu(T,y);return!F||!("sendingStatus"in T)?[]:[{key:F,sendingStatus:T.sendingStatus}]});return{outgoingMessageStates:J,outgoingMessageStatusSignature:J.map(({key:T,sendingStatus:F})=>`${T}:${F}`).join(",")}},[y,s]),_=u.useRef({isClosed:!1,isHandedOff:!1,inputDisabled:m,inputDisabledBy:f,outgoingMessageStatuses:$n(v)}),C=u.useRef({messages:s,currentUserId:y,inputDisabledBy:f,isStreamAnimating:g,stringSet:n,format:r}),x=u.useRef([]),A=u.useRef(null),w=u.useRef([]),M=u.useRef(new Set),k=u.useRef(new Set),R=u.useRef(!1),O=u.useRef(o);C.current={messages:s,currentUserId:y,inputDisabledBy:f,isStreamAnimating:g,stringSet:n,format:r};const z=()=>C.current.isStreamAnimating||C.current.inputDisabledBy==="ai_responding",Y=()=>{A.current!=null&&(clearTimeout(A.current),A.current=null)},P=(J,T,F)=>{const Q=F==null?void 0:F.replaceableForMs;if(J.length===0||!Q)return;const re=Date.now();w.current=[...w.current.filter(({replaceableUntil:le})=>le>re),{eventKeys:J,parts:T,replaceableUntil:re+Q}]},V=()=>x.current.length>0,B=()=>{x.current=[]},W=()=>{const[J,...T]=x.current;if(!J)return!1;x.current=T;const{eventKeys:F,parts:Q,dedupeKey:re}=J,le=xe=>{P(F,xe,{replaceableForMs:F.length>0?Lo:void 0}),e({event:"newMessage",...xe},re?{dedupeKey:re}:void 0)};if(F.length===0)return le(Q),!0;const Oe=C.current,De=rf(Oe.messages,F);if(De){const xe=Ro(De,Oe.stringSet,Oe.format);return le(xe),!0}return le(Q),!0},q=()=>{for(Y();W(););},ie=(J=Lo)=>{Y(),A.current=setTimeout(()=>{if(A.current=null,z())return;const T=No(),[F]=x.current;if(!F)return;if(F.focusTarget!==T){x.current=[{...F,focusTarget:T},...x.current.slice(1)],ie(Oo);return}W()&&V()&&ie(Oo)},J)},_e=(J,T,F)=>{const Q={eventKeys:T,parts:J,focusTarget:No(),dedupeKey:F?F.dedupeKey??void 0:T[0]},re=T.length===0?-1:x.current.findIndex(({eventKeys:le})=>Dn(le,T));re>=0?x.current=x.current.map((le,Oe)=>Oe===re?{...Q,dedupeKey:F?Q.dedupeKey:le.dedupeKey}:le):x.current=[...x.current,Q],ie()},Le=(J,T,F)=>{if(J!=="messagesUpdated"||T.length===0)return!1;const Q=Date.now(),re=w.current.find(le=>le.replaceableUntil>Q&&Dn(le.eventKeys,T));return re?!tf(F,re.parts):!1};u.useEffect(()=>{const J=O.current!==o;(!t||!d||J)&&(R.current=!1,k.current.clear(),B(),w.current=[],M.current.clear(),Y(),J&&(O.current=o),!t||!d)||R.current||(R.current=!0,O.current=o,_.current={isClosed:a,isHandedOff:l,inputDisabled:m,inputDisabledBy:f,outgoingMessageStatuses:$n(v)},M.current=new Set(s.flatMap(T=>{if(!We.isStreaming(T))return[];const F="sender"in T?T.sender:void 0;return(F==null?void 0:F.userId)===C.current.currentUserId?[]:Zn(T)})),k.current=nf(s))},[e,t,o,d,m,a,l,b]),u.useEffect(()=>{const J=(T,F)=>{const Q=C.current,re=Zn(T),le=xi(T);if(le!=null){if(k.current.has(le))return;k.current.add(le),e({event:"csatDisplayed"});return}if(We.isStreaming(T)){re.forEach(G=>{M.current.add(G)});return}const Oe=re.filter(G=>M.current.has(G)),De=F==="messagesUpdated"&&Oe.length>0;De&&Oe.forEach(G=>{M.current.delete(G)});const xe=F==="messagesUpdated"&&x.current.some(({eventKeys:G})=>Dn(G,re)),I=Ro(T,Q.stringSet,Q.format),L=Le(F,re,I);if(!De&&F!=="messagesAdded"&&!xe&&!L)return;const N=L?{dedupeKey:null}:void 0;if(De||z()||xe){_e(I,[...new Set([...Oe,...re])],N);return}if(L){_e(I,re,N);return}V()&&q();const K=re[0];e({event:"newMessage",...I},K?{dedupeKey:K}:void 0)};return E(T=>{if(!R.current||T.kind==="initialized"||!Vu(T.source))return;const F=C.current.currentUserId;for(const Q of T.messages)Q&&Gu(Q,F)&&J(Q,T.kind)})},[e,E]),u.useEffect(()=>{R.current&&(z()||V()&&ie())},[f,g]),u.useEffect(()=>()=>{Y()},[]),u.useEffect(()=>{if(!R.current)return;const J=_.current,T=J.outgoingMessageStatuses;J.outgoingMessageStatuses=$n(v),v.some(({key:Q,sendingStatus:re})=>{const le=T.get(Q);return le!==void 0&&le!=="failed"&&re==="failed"})&&e({event:"sendFailed"})},[e,b]),u.useEffect(()=>{if(!R.current)return;const J=_.current;a&&!J.isClosed&&e({event:"conversationClosed"}),J.isClosed=a},[e,a]),u.useEffect(()=>{if(!R.current)return;const J=_.current;l&&!J.isHandedOff&&e({event:"agentConnected",agentName:c}),J.isHandedOff=l},[c,e,l]),u.useEffect(()=>{if(!R.current)return;const J=_.current;m&&f!=="ai_responding"&&(!J.inputDisabled||J.inputDisabledBy==="ai_responding")&&e({event:"inputDisabled"}),J.inputDisabled=m,J.inputDisabledBy=f},[e,m,f])},sf=()=>{const{channelSource:e}=Se(),t=$s(e.channel);return!(t!=null&&t.user.userId)||!t.user.nickname?null:{userId:t.user.userId,nickname:t.user.nickname}},af=e=>{const{announceStatus:t,announcementsEnabled:n}=Xe();Jc(e??null,r=>{t({event:"typing",agentName:r})},1e4,n)},lf=()=>{const e=sf();af(e)},X=({type:e,size:t=24,className:n,color:r})=>{const{icons:o}=Od(),s=o[e];return i.createElement(cf,{className:n},i.createElement(s,{size:t,color:r??h.color.primary.main,flipInRtl:Td.has(e)}))},cf=p.default.span.attrs({"aria-hidden":"true"})`
|
|
77
|
+
${({$rtlFlip:e})=>e&&Eh};
|
|
78
|
+
`,bh=()=>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:vh,useContext:yh}=Ce("MessengerIcon",{icons:Wi}),Sh=({icons:e,children:t})=>{const n=l.useMemo(()=>({icons:jl(Wi,e)}),[e]);return a.createElement(vh,{value:n},t)},{Provider:Ah,useContext:Ki}=Ce("MessengerTheme");function Th(e){const{theme:t,appearance:n,logger:r}=e;return a.createElement(Fu,{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(Ih,{...e}))}function Ih({rootElement:e=document.body,children:t}){const{theme:n,updateTheme:r}=Nr();return l.useLayoutEffect(()=>{e.setAttribute(Tn,n.selectedTheme)},[e,n.selectedTheme]),a.createElement(P.ThemeProvider,{theme:n},a.createElement(Ah,{value:{theme:n,updateTheme:r,rootElement:e}},t))}const xh=(e,t)=>{l.useEffect(()=>{const n=lt(t)instanceof ShadowRoot,r=lt(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])},Rh=(e,t=document.body)=>{l.useEffect(()=>{if(!e)return;const n=lt(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])},Mh=80,wh=()=>{const{stringSet:e}=ae(),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},ji=Ce("AriaLiveRegion",{announce:le,announceScreenEntry:le,announceStatus:le,announceError:le,flush:le,setSuppressionState:le}),kh=ji.Provider,Gr=ji.useContext,Lh={position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},Oh=({children:e})=>{const t=l.useRef(null),n=l.useRef(new Set),r=l.useRef(le),s=wh(),[o]=l.useState(()=>Am(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=Im(g,s.current);i(p)},[i]),d=l.useCallback((g,p)=>{const v=xm(g,s.current),E=(p==null?void 0:p.mode)??Tm(g.event);i(v,{mode:E,dedupeKey:p==null?void 0:p.dedupeKey})},[i]),m=l.useCallback((g,p)=>{const v=Rm(g,s.current);o.announceIgnoringSuppression(v),p&&setTimeout(()=>{p.focus()},Mh)},[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(kh,{value:f},e,a.createElement("div",{ref:t,role:"status","aria-live":"polite","aria-atomic":"true",style:Lh}))},Xi=Ce("ConversationAnnouncements",{announcementsEnabled:!0,announce:le,announceScreenEntry:le,announceStatus:le,announceError:le,setIsSuppressed:le,setStatusPauseState:le,flush:le}),Nh=Xi.Provider,rt=Xi.useContext,Dh=({children:e,announcementsEnabled:t=!0})=>{const{announce:n,announceScreenEntry:r,announceStatus:s,announceError:o,flush:i,setSuppressionState:c}=Gr(),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(R=>{i(),s(R.params,R.options)})},[s,t,f,i]),p=l.useCallback((T,R)=>{if(R){d.current.add(T);return}d.current.delete(T),d.current.size===0&&g()},[g]),v=l.useCallback(T=>{t&&n(T)},[n,t]),E=l.useCallback(T=>{t&&r(T)},[r,t]),_=l.useCallback((T,R)=>{if(t){if(d.current.size>0){u.current.push({params:T,options:R});return}s(T,R)}},[s,t]),y=l.useCallback((T,R)=>{t&&o(T,R)},[o,t]);l.useLayoutEffect(()=>(t||(f(),c(m.current,!1)),()=>{f(),c(m.current,!1)}),[t,f,c]);const A=l.useMemo(()=>({announcementsEnabled:t,announce:v,announceScreenEntry:E,announceStatus:_,announceError:y,setIsSuppressed:h,setStatusPauseState:p,flush:i}),[t,i,v,y,E,_,h,p]);return a.createElement(Nh,{value:A},e)},Ln=["a[href]","button:not(:disabled)","input:not(:disabled)","select:not(:disabled)","textarea:not(:disabled)",'[tabindex]:not([tabindex="-1"])'].join(", "),Zi=`${Ln}, [tabindex="-1"]`,Tt=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},Gt=(e,t)=>{for(const n of e.querySelectorAll(t))if(!n.hasAttribute(Pr)&&Tt(n))return n;return null},Ji=e=>{let t=null,n=null;for(const r of e.querySelectorAll(Ln))r.hasAttribute(Pr)||Tt(r)&&(t??(t=r),n=r);return t?{first:t,last:n}:null},Qi=(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,$h=(e,t,n)=>Qi(e,t)||n!=null&&t instanceof HTMLElement&&n.contains(t),zr=e=>Gt(e,Pm),ea=e=>zr(e)??Gt(e,Ln),Fh=e=>{const t=zr(e);if(t)return t;const n=e.querySelector(Bm);return(n?Gt(n,Zi):null)??Gt(e,Ln)},H=({as:e,variant:t="body1",color:n,maxTextLines:r,className:s,...o})=>a.createElement(Bh,{as:e,$variant:t,className:s,$color:n,$maxTextLines:r,...o}),Xs=new WeakMap,Ph=(e,t)=>{let n=Xs.get(t);n||(n=new Map,Xs.set(t,n));const r=n.get(e);if(r)return r;const s=t[e]??t.body1,o=P.css`font-size:${Xe(s.fontSize)};font-weight:${s.fontWeight};${s.fontFamily?`font-family: ${s.fontFamily};`:""}
|
|
79
|
+
${s.lineHeight?`line-height: ${s.lineHeight};`:"line-height: 100%;"}
|
|
80
|
+
`;return n.set(e,o),o},Uh=e=>e?P.css`display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:${e};overflow:hidden;`:"",Bh=b.default.span`font-stretch:normal;letter-spacing:normal;${({$variant:e,theme:t})=>Ph(e,t.typography)}color:${({$color:e})=>e};${({$maxTextLines:e})=>Uh(e)}`;async function Vr(e){let t=e;t&&(!t.startsWith("http://")&&!t.startsWith("https://")&&(t="https://"+t),window.open(t,"_blank","noopener,noreferrer"))}function we(e){requestAnimationFrame(()=>{requestAnimationFrame(()=>{e()})})}const fr='[role="dialog"][aria-modal="true"]',Hh=(e,t)=>{const n=new Set(Array.from(e.ownerDocument.querySelectorAll(fr)).filter(s=>s!==e&&(s.contains(e)||e.contains(s)))),r=t==null?void 0:t.closest(fr);return r&&r!==e&&n.add(r),n},Gh=(e,t)=>Array.from(e.ownerDocument.querySelectorAll(fr)).some(n=>n!==e&&!t.has(n)&&!n.contains(e)&&Tt(n)),zh=e=>{const t=ea(e)??e;t===e&&ta(e),t.focus()},ta=e=>{e.hasAttribute("tabindex")||e.setAttribute("tabindex","-1")},Vh=(e,t)=>{const n=Ji(e);if(!n){ta(e),e.focus();return}n[t].focus()},Zs=(e,t)=>{const n=e.ownerDocument.createElement("span");return n.tabIndex=0,n.setAttribute(Pr,Um),n.style.cssText=["position: fixed","width: 1px","height: 1px","opacity: 0","overflow: hidden","pointer-events: none"].join(";"),n.addEventListener("focus",()=>Vh(e,t)),n},qh=(e,t)=>{e.key==="Tab"&&(e.defaultPrevented||e.target===t&&(Ji(t)||(e.preventDefault(),t.focus())))},On=(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=Hh(i,u);return()=>{u&&we(()=>{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)&&Tt(m)||Gh(i,d)||!u.isConnected||!Tt(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)&&Tt(m)){s.current=!0;return}s.current=!0,zh(o)};if(n)return we(c),()=>{i=!0};const u=setTimeout(()=>we(c),Bi);return()=>{i=!0,clearTimeout(u)}},[e,t,n]),l.useEffect(()=>{if(!e||!t.current)return;const o=t.current,i=Zs(o,"last"),c=Zs(o,"first"),u=d=>qh(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}=Br();return On(n,d),eh(n,o?r:le),n?ic.createPortal(a.createElement(Yh,{onClick:o?r:void 0,style:e},a.createElement(Wh,{ref:d,role:"dialog","aria-modal":"true","aria-label":i,"aria-labelledby":c,"aria-describedby":u,onClick:h=>h.stopPropagation()},s)),m(t)):null},Yh=b.default.div`position:fixed;top:0;left:0;width:100%;height:100%;background:${C.color.overlay.dark};display:flex;justify-content:center;align-items:center;z-index:${gt.MODAL};`,Wh=b.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:${gt.MODAL};`,Kh=({id:e,children:t})=>a.createElement(jh,{id:e},t),jh=b.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;`,Js=(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},Xh=()=>{const e=`${l.useId()}-`;return(t,n)=>{if(!t)return{props:{},node:null};const r=e+n,s=l.createElement(Kh,{id:r,children:t});return{props:{"aria-describedby":r},node:s}}},Qs=({name:e,mimeType:t,selected:n},r)=>{var o;const s=We(t??"")?r.A11Y_FILE_IMAGE(e):zt(t??"")?r.A11Y_FILE_VIDEO(e):jo({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},Zh=e=>t=>{t.repeat||(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),e())},$t=({onActivate:e})=>({role:"button",tabIndex:0,onClick:e,onKeyDown:Zh(e)}),Jh=({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()},eo=(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:Jh({disabled:t,currentIndex:n,totalCount:r,onNavigate:o}),tabIndex:i}},se=()=>{const{stringSet:e}=ae(),t=Xh(),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":Qs(i,e)});return{launcher:{button:({isOpened:i,opensConversationList:c})=>{const u=$m({intent:Om({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:Js(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,...Gm},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:{...$t({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?Qs({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:{...$t({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 _;const p=c.trim()||c,v=e.A11Y_HINT_SELECT_RATING,E=t(v,`cs${i}`);return{props:{disabled:d,onClick:()=>g(i),...eo(u,d,m,h,f,y=>g(y+1)),...E.props,"aria-label":((_=e.A11Y_CSAT_RATING_LABEL)==null?void 0:_.call(e,i,p))??`${i} / ${h} — ${p}`},descriptionNode:E.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:{...eo(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:Js(i,c),descriptionNode:null}),footer:{button:({onActivate:i})=>({props:{...$t({onActivate:i}),"aria-label":e.TALK_TO_AGENT},descriptionNode:null})},item:({agent:i,status:c,time:u,unreadCount:d,onActivate:m})=>{if(!m)return{props:{"aria-label":e.A11Y_CONVERSATION_ITEM(i,c,u,d)},descriptionNode:null};const h=e.A11Y_HINT_OPEN_CONVERSATION,f=t(h,"cli");return{props:{...$t({onActivate:m}),...f.props,"aria-label":e.A11Y_CONVERSATION_ITEM(i,c,u,d)},descriptionNode:f.node}}}}},Qh=({title:e,description:t,highlightedText:n})=>{const r=Xd(t,n);return a.createElement(tf,null,a.createElement(nf,null,a.createElement(H,{as:"div",variant:"h1",color:C.themedColor.textHighEmphasis},e),t&&a.createElement(rf,null,a.createElement(H,{as:"div",variant:"body3",color:C.themedColor.textMidEmphasis},r.beforeText,r.highlightedText?a.createElement(sf,null,r.highlightedText):null,r.afterText))))},ef=()=>{const{components:e}=Nn.useContext(),{stringSet:t}=ae(),{messenger:n}=se(),r=Kd(),s=r.showDescription?jd(r.remainingTime):"",o=r.showDescription?t.CONNECTION_DELAY__DESCRIPTION(s):"";return a.createElement(ut,{portalContainerId:ve.WINDOW,visible:r.visible,onClose:le,...n.connectionDelayDialog().props},a.createElement(e.Dialog,{title:t.CONNECTION_DELAY__TITLE,description:o,highlightedText:s||void 0}))},Nn=je({template:ef,components:{Dialog:Qh}}),tf=b.default.div`width:280px;padding:24px;margin:0 auto;border-radius:4px;box-sizing:border-box;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,nf=b.default.div`display:flex;flex-direction:column;`,rf=b.default.div`margin-top:16px;`,sf=b.default.strong`font-weight:700;`,of=({url:e})=>Vr(e),{Provider:af,Consumer:na,useContext:ce}=Ce("Messenger");function cf({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}=Br(),f=l.useCallback(()=>{m.setOpened(!1)},[m.setOpened]);th(m.opened,f);const g=l.useRef(m.opened);l.useLayoutEffect(()=>{const E=g.current&&!m.opened;if(g.current=m.opened,!E)return;const _=lt(o.rootElement),y=h(ve.WINDOW);let A=!1;return we(()=>{var T;A||$h(_,_.activeElement,y)&&((T=h(ve.LAUNCHER))==null||T.focus())}),()=>{A=!0}},[m.opened,o.rootElement,h]);const{Template:p}=Nn.useContext(),v=l.useMemo(()=>{var E;return{...o.handlers,onClickLink:((E=o.handlers)==null?void 0:E.onClickLink)??of}},[o.handlers]);return a.createElement(ru,{...o},E=>a.createElement(af,{value:{...o,...E,state:m,enableCloseConversationButton:n,enableExpandButton:r,enableAutoDisconnectInLauncher:s,handlers:v}},a.createElement(p,null),e))}const ra=/iPad|iPhone|iPod/.test(navigator.userAgent),lf=/Android/.test(navigator.userAgent),Xt=e=>ra||lf;let Lt=null,Zn=null;const uf=(e,t=5e3)=>{Lt&&(clearInterval(Lt),clearTimeout(Zn));const n=document.title;Lt=setInterval(()=>{document.title=document.title===e?n:e},750),Zn=setTimeout(()=>{clearInterval(Lt),Lt=null,Zn=null,document.title=n},t)},sa=()=>{Promise.resolve().then(()=>require("./cjs/B93o4u0P.cjs")).then(e=>{new Audio(e.default).play().catch(()=>{})})},Re=P.css`&:focus-visible{outline:2px solid ${C.themedColor.primary};outline-offset:2px;}`,to=e=>{if(typeof e=="string"||typeof e=="number")return String(e)},Dn=({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??to(t)??to(n),f=u?void 0:t?d:n?m:void 0,g=t&&n?m:void 0,p=()=>{c(),we(()=>o==null?void 0:o())},v=()=>{c(),we(()=>i==null?void 0:i())};return a.createElement(ut,{portalContainerId:ve.WINDOW,visible:e,onClose:c,"aria-label":h,"aria-labelledby":f,"aria-describedby":g},a.createElement(df,null,a.createElement(mf,null,t&&a.createElement("div",{id:d},a.createElement(H,{variant:"h1",color:C.themedColor.textHighEmphasis},t)),n&&a.createElement(hf,{id:m},a.createElement(H,{variant:"body3",color:C.themedColor.textMidEmphasis},n))),a.createElement(ff,null,s&&a.createElement(no,{onClick:v},a.createElement(H,{variant:"button",color:C.themedColor.textHighEmphasis},s)),a.createElement(no,{onClick:p},a.createElement(H,{variant:"button",color:C.themedColor.primary},r)))))},df=b.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};`,mf=b.default.div`margin-bottom:16px;`,hf=b.default.div`margin-top:16px;`,ff=b.default.div`display:flex;flex-direction:row;justify-content:flex-end;`,no=b.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:gf,useContext:Ne}=Ce("MessengerSession"),pf=l.forwardRef(function({children:e,...t},n){return a.createElement(Hu,{ref:n,...t},r=>a.createElement(_f,{...r},e))}),_f=({children:e,...t})=>{const{chatSDK:n,logger:r,appId:s,aiAgentId:o,agentPreviewConfigs:i,state:c,handlers:u,dispatcher:d,_aiAgentSDK:m}=ce(),{userSessionInfo:h,authenticate:f,userSession:g,aiAgentInfo:p,launcherInfo:v}=t,[E,_]=l.useState(!1),y=l.useRef(null);ht(n,{async onUserJoined(T,R){var N,x,w,Y;T.conversation&&T.conversation.type===Se.ConversationType.PROACTIVE&&R.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:(x=T.conversation)==null?void 0:x.status}),c.setOpened(!0),Ef({sound:document.hidden||!c.opened}),(Y=y.current)==null||Y.call(y,{channel:T}))}}),l.useEffect(()=>{f().then(({launcher:T})=>{T.auto_open&&!Xt()&&setTimeout(()=>c.setOpened(!0),500)}).catch(T=>{var R;r.error("messengerSession: failed to initialize",T),(R=u==null?void 0:u.onInitializeFailed)==null||R.call(u,T)})},[n,s,o,h==null?void 0:h.userId]),l.useEffect(()=>{const T=()=>_(!0);return d.subscribe(Ye.AnonymousSessionTokenExpired,T),()=>d.unsubscribe(Ye.AnonymousSessionTokenExpired,T)},[d]);const A=l.useCallback(()=>{t.deauthenticate().finally(()=>window.location.reload())},[t.deauthenticate]);return!g||!p||!v?null:a.createElement(gf,{value:{...t,userSession:g,aiAgentInfo:{...p,...i==null?void 0:i.bot},launcherInfo:{...v,...i==null?void 0:i.launcher},registerOnJoinedProactiveConversation:T=>y.current=T}},e,a.createElement(Dn,{visible:E,title:"Session timed out",description:"Start a new conversation.",onConfirm:A,onClose:le}))};function Ef({sound:e}){uf("🔔You have received a new message"),e&&sa()}const In=`@${Ge}-focused-channel`,oa=`${Date.now()}-${Math.random().toString(36).slice(2)}`,Cf=()=>{try{const e=localStorage.getItem(In);return e?JSON.parse(e).channelUrl??null:null}catch{return null}},ro=e=>{try{localStorage.setItem(In,JSON.stringify({channelUrl:e,tabId:oa}))}catch{}},so=()=>{try{const e=localStorage.getItem(In);if(!e)return;JSON.parse(e).tabId===oa&&localStorage.removeItem(In)}catch{}},bf=(e,t)=>(l.useEffect(()=>{if(!t||!e)return;const n=()=>ro(e),r=()=>so();return document.hasFocus()&&ro(e),window.addEventListener("focus",n),window.addEventListener("blur",r),()=>{window.removeEventListener("focus",n),window.removeEventListener("blur",r),so()}},[t,e]),{isChannelViewedInAnyTab:()=>document.hasFocus()||Cf()===e}),vf=e=>{const{config:t,chatSDK:n}=ce(),{sdkUser:r}=Ne(),s=t.conversation.messageAlertSoundEnabled,{isChannelViewedInAnyTab:o}=bf(e,s);ht(n,{onMessageReceived(i,c){if(!s||i.url!==e||o())return;(nt(c)&&c.sender.userId!==(r==null?void 0:r.userId)||c.isAdminMessage()&&!c.silent)&&sa()}})};function yf(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 Sf(e){if("file"in e&&e.file instanceof File&&e.file.type.startsWith("image/")){const{width:t,height:n}=await yf(e.file);return new Ke.MessageMetaArray({key:Yo,value:[t,n]})}}const Af=({onScrollAfterSendMessage:e})=>{const{agentPreviewConfigs:t,handlers:n}=ce(),r=l.useRef(t==null?void 0:t.agentAttributes);return r.current=t==null?void 0:t.agentAttributes,{onBeforeSendMessage:async s=>{const o=await Sf(s),i={...s,metaArrays:o?[o]:void 0},c=Tf(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===Ke.SendingStatus.SUCCEEDED?(i=n==null?void 0:n.onCustomEvent)==null||i.call(n,{type:"message-sent-succeeded",data:{message:s}}):s.sendingStatus===Ke.SendingStatus.PENDING&&((c=n==null?void 0:n.onCustomEvent)==null||c.call(n,{type:"message-sent-pending",data:{message:s}}))}}},Tf=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,Jn=St-40,{Provider:If,useContext:ia}=Ce("ConversationScroll"),oo={viewport:0,contentHeight:0,contentSnapshotHeight:0,shouldRecalc:!1,shouldUpdate:!1},Qn=e=>Math.max(0,e.scrollHeight-e.scrollTop-e.clientHeight),io=e=>Array.from(e.querySelectorAll(`#${Ge}-message-item`));function xf({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(oo),[u,d]=l.useState(0),[m,h]=l.useState(0),[f,g]=l.useState(!1),[p,v]=l.useState(!1),[E,_]=l.useState(!0),y=$=>{const M=Qn($);return o.current.distanceFromBottom=M,h(M),M},A=()=>{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()},[]),R=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 $=r.current;!$||!c.current.shouldUpdate||d(M=>{c.current.shouldUpdate=!1;const{contentHeight:k,contentSnapshotHeight:F,shouldRecalc:j}=c.current,K=$.clientHeight;if(F>k)return M;const X=x($,{messageType:"outgoing"});let U=0;if(X){const J=X.message.offsetTop-Jn+K;U=Math.max(0,J-k)}else{const J=k-F,ye=K-Jn;U=Math.max(0,J-ye)}return M===0||U!==M||j?(c.current.shouldRecalc=!1,U):M})},x=l.useCallback(($,M)=>{const{messageType:k="all"}=M??{},F=io($);let j=F;k==="outgoing"&&(j=F.filter(ie=>ie.getAttribute("data-layout-id")==="outgoingmessage"));const K=j[j.length-1];if(!K)return null;const X=$.getBoundingClientRect(),U=K.getBoundingClientRect(),J=$.scrollTop+(U.top-X.top),ye=J+K.offsetHeight;return{message:K,scrollTop:J,lastMessageBottom:ye}},[]),w=l.useCallback(()=>{const $=r.current;if(!$||R!=="fixed")return;const M=x($);c.current.contentHeight=(M==null?void 0:M.lastMessageBottom)??$.scrollHeight,!i.current.streaming&&c.current.contentSnapshotHeight>0&&L(),i.current.programmatic?o.current.distanceFromBottom=Qn($):y($),N()},[R,x]),Y=l.useCallback(()=>{T(),A(),c.current=oo,d(0),h(0),_(!0),o.current.distanceFromBottom=0,o.current.prevScrollTop=0,i.current.awayByUser=!1,i.current.programmatic=!1},[T]),O=l.useCallback(($=!0)=>{const M=o.current.distanceFromBottom>St;if(i.current.awayByUser=!1,h(0),!M){we(()=>{const k=r.current;k&&!i.current.awayByUser&&k.scrollTo({top:k.scrollHeight,behavior:"auto"})});return}i.current.programmatic||(i.current.programmatic=!0,_(!1),A()),we(()=>{const k=r.current;if(!k){i.current.programmatic=!1,_(!0);return}if(i.current.awayByUser){i.current.programmatic=!1,y(k),_(!0);return}const F=()=>{if(r.current!==k){i.current.programmatic=!1,r.current&&y(r.current),_(!0);return}i.current.programmatic=!1,y(k),_(!0)};if($&&!i.current.reconcileTimer){const j=setTimeout(F,500);i.current.reconcileTimer=j,k.addEventListener("scrollend",()=>{clearTimeout(j),i.current.reconcileTimer=null,F()},{once:!0})}k.scrollTo({top:k.scrollHeight,behavior:$?"smooth":"auto"}),$||F()})},[]),Z=l.useCallback(()=>{const $=r.current;if($){if(i.current.awayByUser){y($);return}O(!1)}},[O]),G=l.useCallback(()=>{const $=r.current,M=s.current;if(!$||!M.resize)return;const k=new Set(io($));for(const F of M.resizeTargets)k.has(F)||(M.resize.unobserve(F),M.resizeTargets.delete(F));for(const F of k)M.resizeTargets.has(F)||(M.resize.observe(F),M.resizeTargets.add(F))},[]),D=l.useCallback($=>{T();const M=s.current;typeof ResizeObserver<"u"&&(M.resize=new ResizeObserver(Z),G());const k=new MutationObserver(()=>{G(),Z()});M.mutation=k,k.observe($,{childList:!0})},[T,Z,G]),z=l.useCallback($=>{if(!$){r.current=null,T();return}if(r.current=$,R!=="fixed"){D($);return}Y(),c.current.viewport=$.clientHeight;const M=new MutationObserver(()=>{w()});s.current.mutation=M,M.observe($,{childList:!0,subtree:!0})},[T,R,w,Y,D]),q=l.useCallback(()=>{const $=r.current;if(!$)return;const M=x($,{messageType:"outgoing"});M&&($.scrollTo({top:M.message.offsetTop-Jn,behavior:"smooth"}),i.current.userMessageTimer&&clearTimeout(i.current.userMessageTimer),i.current.userMessageTimer=setTimeout(()=>{v(!1)},500))},[x]),ne=($,M,k)=>{const F=Qn($);if(k&&F>St){i.current.programmatic=!1,i.current.awayByUser=!0,A(),y($),_(!0),o.current.prevScrollTop=M;return}o.current.distanceFromBottom=F},ue=($,M,k)=>{const j=y($)<=St;M&&!j&&(i.current.awayByUser=!0,A()),k&&j&&(i.current.awayByUser=!1)},Ie=$=>{const{scrollTop:M}=$.currentTarget,k=o.current.prevScrollTop;i.current.programmatic?ne($.currentTarget,M,M<k):ue($.currentTarget,M<k,M>k),o.current.prevScrollTop=M},B=l.useCallback(()=>{R==="fixed"&&(v(!0),L())},[R]),V=l.useCallback(()=>{R==="fixed"?setTimeout(()=>q(),300):O()},[R,q]),I=l.useCallback($=>{i.current.streaming=$,R==="fixed"?L():i.current.awayByUser||O()},[R,O]),W=l.useCallback($=>{g($),$&&(d(0),R==="fixed"&&T())},[T,R]),re=l.useCallback($=>{R==="auto"&&$&&!i.current.awayByUser&&O()},[R,O]),De=!(m<=St)&&!p,He=l.useCallback(()=>o.current.distanceFromBottom>St,[]);return a.createElement(If,{value:{ref:z,state:{bottomSpace:u,isAwayFromBottom:De,isScrollPositionReconciled:E,shouldCountNewMessages:He},props:{onScroll:Ie},actions:{scrollToBottom:O,onBeforeMessageSend:B,onAfterMessageSend:V,onStreamingUpdate:I,onConversationClosed:W,onTypingIndicatorUpdate:re}}},n)}const{Provider:Rf,Context:Mf,useContext:Te}=Ce("Conversation"),wf=({children:e})=>{var s;const{channelSource:t}=Te(),n=(s=t.channel)==null?void 0:s.url,{checkForUserActionRequired:r}=Od(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)},kf=({channelUrl:e,onClearChannelUrl:t,onNavigateToConversationList:n,conversationStatsEnabled:r,shouldMarkAsRead:s,children:o})=>{const{activeChannel:i,refreshActiveChannel:c}=Ne(),u=ia(),d=e||(i==null?void 0:i.url);vf(d);const{onBeforeSendMessage:m,onAfterSendMessage:h}=Af({onScrollAfterSendMessage:()=>{u.actions.onAfterMessageSend()}}),f=l.useCallback(v=>(u.actions.onBeforeMessageSend(),m(v)),[u.actions,m]),g=l.useCallback(v=>{const E=v.some(_=>Me.isStreaming(_));u.actions.onStreamingUpdate(E)},[u.actions.onStreamingUpdate]),p=l.useCallback(async()=>{await c(),e&&(t==null||t())},[c,e,t]);return a.createElement(fd,{key:d,channelUrl:d,onBeforeSendMessage:f,onAfterSendMessage:h,onMessagesUpdated:g,onMessagesReceived:g,onChannelDeleted:p,onConversationClosedStatusChanged:u.actions.onConversationClosed,conversationStatsEnabled:r,shouldMarkAsRead:s,shouldCountNewMessages:u.state.shouldCountNewMessages},v=>a.createElement(Rf,{value:{...v,conversationStatsEnabled:r??!0,scrollSource:u,goToActiveConversation:p,onNavigateToConversationList:n}},a.createElement(wf,null,o)))},aa=({children:e,...t})=>{const{config:n}=ke(),{agentPreviewConfigs:r}=ce(),s=n.conversation.list.scrollMode,o=r==null?void 0:r.messageStackDirection;return a.createElement(xf,{scrollMode:s,messageStackDirection:o},a.createElement(kf,{...t},e))},qr=l.createContext({onDrop:le,subscribe:()=>le}),gr=({children:e})=>{const t=l.useRef(new Set);return a.createElement(qr.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)},Lf=({onDropFiles:e})=>{const{subscribe:t}=l.useContext(qr);l.useEffect(()=>t(e),[e])};gr.Consumer=({children:e})=>{const{onDrop:t}=l.useContext(qr);return e({onDrop:t,onDragOver:s=>s.preventDefault()})};const ca=Ce("WindowTitle",{hasWindowTitleReference:!1,isTitlePending:!1,isWindowNameReady:!0,registerWindowTitleReference:()=>le,registerWindowTitlePending:()=>le}),Of=ca.Provider,la=ca.useContext,ao=()=>{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]},Yr=({children:e})=>{const[t,n]=ao(),[r,s]=ao(),o=!r||t,i=l.useMemo(()=>({hasWindowTitleReference:t,isTitlePending:r,isWindowNameReady:o,registerWindowTitleReference:n,registerWindowTitlePending:s}),[t,r,n,s]);return a.createElement(Of,{value:i},e)},$n=la,ua=({enabled:e,label:t})=>{const{registerWindowTitleReference:n,registerWindowTitlePending:r}=la(),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?ve.WINDOW_TITLE:void 0}},Nf=(e,t)=>{const r=(t?Gt(e,t):null)??Fh(e)??e;r===e&&!e.hasAttribute("tabindex")&&e.setAttribute("tabindex","-1"),r.focus({focusVisible:!1})},da=(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=zr(e.current)!=null;if(!s&&!c&&!n)return;let u=!1;const d=()=>{u||i.current||!e.current||(i.current=!0,Nf(e.current,s))};if(r)return we(d),()=>{u=!0};const m=setTimeout(()=>we(d),Bi);return()=>{u=!0,clearTimeout(m)}},[t,n,r,s,e,o])},Df=(e,t)=>{const{announcementsEnabled:n}=rt(),{channelSource:r}=Te(),{isWindowNameReady:s}=$n(),o=Yi(),i=r.channel!=null||r.error!=null;da(e,{enabled:n,ready:i,nameReady:s,targetSelector:t==="messageInput"?Hm:void 0,suppressed:o})},$f=({enabled:e=!0}={})=>{var s;const{channelSource:t}=Te(),n=(s=t.channel)==null?void 0:s.url,r=l.useCallback(o=>{const i=()=>{o(qs()?"backgrounded":"foregrounded")};return document.addEventListener("visibilitychange",i),()=>document.removeEventListener("visibilitychange",i)},[]);Qd({channelUrl:n,enabled:e,isInitiallyBackgrounded:qs,isForegrounded:dr,subscribeToForegroundState:r})},Ff=e=>We(e)||zt(e);function Pf(e){return e.isAdminMessage()?e.message==="The channel's custom_type was updated.":!1}function Uf(e,t){return e.filter(n=>Me.isWelcomeMessage(n,t))}const ma=(e,{previewWelcomeMessages:t,aiAgentUserId:n})=>e.filter(r=>Pf(r)?!1:t.length>0?!Me.isWelcomeMessage(r,n):!0),Bf=[],ha=()=>{var p,v,E,_,y,A;const{agentPreviewConfigs:e={},aiAgentId:t}=ce(),{aiAgentInfo:n,userSession:r}=Ne(),{channelSource:s,messageSource:o,state:{input:i,streamAnimation:c}}=Te(),u=e.welcomeMessages??Bf,d=l.useMemo(()=>ma(o.messages,{previewWelcomeMessages:u,aiAgentUserId:t}),[t,o.messages,u]),m=ct(s.channel),h=(v=(p=ai(s.channel,r.userId))==null?void 0:p.nickname)==null?void 0:v.trim(),f=m?(_=(E=s.channel)==null?void 0:E.name)==null?void 0:_.trim():(y=n==null?void 0:n.nickname)==null?void 0:y.trim(),g=h||f||void 0;return{initialized:o.initialized,channelUrl:(A=s.channel)==null?void 0:A.url,agentName:g,isClosed:Be(s.channel),isHandedOff:m,messages:d,filteredMessagesCount:d.length,hasWelcomeMessages:u.length>0,inputDisabled:i.disabled,inputDisabledBy:i.disabledBy,isStreamAnimating:c.isAnimating,subscribeMessageEvents:o.subscribeMessageEvents,currentUserId:r.userId}},Hf=(e={})=>{const{announceScreenEntry:t,announcementsEnabled:n}=rt(),{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])},Gf=()=>{const e=ha();Hf(e)},zf=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}),co=(e,t,n=ot.format)=>{const r=Sm(e,zf(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}},Vf={senderName:!0,body:!0,time:!0},qf=Object.keys(Vf),Yf=(e,t)=>qf.every(n=>e[n]===t[n]),lo=2e3,uo=400,pr=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]},fa=e=>{if(!Oe.isAdmin(e)||!Oe.isCSAT(e))return null;const t=km(e);return t?`csat:${t}`:null},Wf=e=>{const t=new Set;for(const n of e){const r=fa(n);r&&t.add(r)}return t},Kf=(e,t)=>{for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(r&&pr(r).some(s=>t.includes(s)))return r}},er=(e,t)=>e.some(n=>t.includes(n)),mo=()=>typeof document>"u"?null:document.activeElement instanceof HTMLElement?document.activeElement:null,tr=e=>new Map(e.map(({key:t,sendingStatus:n})=>[t,n])),jf=()=>{const{announceStatus:e,announcementsEnabled:t}=rt(),{stringSet:n,format:r}=ae(),{channelUrl:s,messages:o,isClosed:i,isHandedOff:c,agentName:u,initialized:d,inputDisabled:m,inputDisabledBy:h,isStreamAnimating:f,subscribeMessageEvents:g,currentUserId:p}=ha(),{outgoingMessageStates:v,outgoingMessageStatusSignature:E}=l.useMemo(()=>{if(!p)return{outgoingMessageStates:[],outgoingMessageStatusSignature:""};const B=o.flatMap(V=>{const I=Mm(V,p);return!I||!("sendingStatus"in V)?[]:[{key:I,sendingStatus:V.sendingStatus}]});return{outgoingMessageStates:B,outgoingMessageStatusSignature:B.map(({key:V,sendingStatus:I})=>`${V}:${I}`).join(",")}},[p,o]),_=l.useRef({isClosed:!1,isHandedOff:!1,inputDisabled:m,inputDisabledBy:h,outgoingMessageStatuses:tr(v)}),y=l.useRef({messages:o,currentUserId:p,inputDisabledBy:h,isStreamAnimating:f,stringSet:n,format:r}),A=l.useRef([]),T=l.useRef(null),R=l.useRef([]),L=l.useRef(new Set),N=l.useRef(new Set),x=l.useRef(!1),w=l.useRef(s);y.current={messages:o,currentUserId:p,inputDisabledBy:h,isStreamAnimating:f,stringSet:n,format:r};const Y=()=>y.current.isStreamAnimating||y.current.inputDisabledBy==="ai_responding",O=()=>{T.current!=null&&(clearTimeout(T.current),T.current=null)},Z=(B,V,I)=>{const W=I==null?void 0:I.replaceableForMs;if(B.length===0||!W)return;const re=Date.now();R.current=[...R.current.filter(({replaceableUntil:oe})=>oe>re),{eventKeys:B,parts:V,replaceableUntil:re+W}]},G=()=>A.current.length>0,D=()=>{A.current=[]},z=()=>{const[B,...V]=A.current;if(!B)return!1;A.current=V;const{eventKeys:I,parts:W,dedupeKey:re}=B,oe=$=>{Z(I,$,{replaceableForMs:I.length>0?lo:void 0}),e({event:"newMessage",...$},re?{dedupeKey:re}:void 0)};if(I.length===0)return oe(W),!0;const De=y.current,He=Kf(De.messages,I);if(He){const $=co(He,De.stringSet,De.format);return oe($),!0}return oe(W),!0},q=()=>{for(O();z(););},ne=(B=lo)=>{O(),T.current=setTimeout(()=>{if(T.current=null,Y())return;const V=mo(),[I]=A.current;if(!I)return;if(I.focusTarget!==V){A.current=[{...I,focusTarget:V},...A.current.slice(1)],ne(uo);return}z()&&G()&&ne(uo)},B)},ue=(B,V,I)=>{const W={eventKeys:V,parts:B,focusTarget:mo(),dedupeKey:I?I.dedupeKey??void 0:V[0]},re=V.length===0?-1:A.current.findIndex(({eventKeys:oe})=>er(oe,V));re>=0?A.current=A.current.map((oe,De)=>De===re?{...W,dedupeKey:I?W.dedupeKey:oe.dedupeKey}:oe):A.current=[...A.current,W],ne()},Ie=(B,V,I)=>{if(B!=="messagesUpdated"||V.length===0)return!1;const W=Date.now(),re=R.current.find(oe=>oe.replaceableUntil>W&&er(oe.eventKeys,V));return re?!Yf(I,re.parts):!1};l.useEffect(()=>{const B=w.current!==s;(!t||!d||B)&&(x.current=!1,N.current.clear(),D(),R.current=[],L.current.clear(),O(),B&&(w.current=s),!t||!d)||x.current||(x.current=!0,w.current=s,_.current={isClosed:i,isHandedOff:c,inputDisabled:m,inputDisabledBy:h,outgoingMessageStatuses:tr(v)},L.current=new Set(o.flatMap(V=>{if(!Me.isStreaming(V))return[];const I="sender"in V?V.sender:void 0;return(I==null?void 0:I.userId)===y.current.currentUserId?[]:pr(V)})),N.current=Wf(o))},[e,t,s,d,m,i,c,E]),l.useEffect(()=>{const B=(V,I)=>{const W=y.current,re=pr(V),oe=fa(V);if(oe!=null){if(N.current.has(oe))return;N.current.add(oe),e({event:"csatDisplayed"});return}if(Me.isStreaming(V)){re.forEach(K=>{L.current.add(K)});return}const De=re.filter(K=>L.current.has(K)),He=I==="messagesUpdated"&&De.length>0;He&&De.forEach(K=>{L.current.delete(K)});const $=I==="messagesUpdated"&&A.current.some(({eventKeys:K})=>er(K,re)),M=co(V,W.stringSet,W.format),k=Ie(I,re,M);if(!He&&I!=="messagesAdded"&&!$&&!k)return;const F=k?{dedupeKey:null}:void 0;if(He||Y()||$){ue(M,[...new Set([...De,...re])],F);return}if(k){ue(M,re,F);return}G()&&q();const j=re[0];e({event:"newMessage",...M},j?{dedupeKey:j}:void 0)};return g(V=>{if(!x.current||V.kind==="initialized"||!Lm(V.source))return;const I=y.current.currentUserId;for(const W of V.messages)W&&wm(W,I)&&B(W,V.kind)})},[e,g]),l.useEffect(()=>{x.current&&(Y()||G()&&ne())},[h,f]),l.useEffect(()=>()=>{O()},[]),l.useEffect(()=>{if(!x.current)return;const B=_.current,V=B.outgoingMessageStatuses;B.outgoingMessageStatuses=tr(v),v.some(({key:W,sendingStatus:re})=>{const oe=V.get(W);return oe!==void 0&&oe!=="failed"&&re==="failed"})&&e({event:"sendFailed"})},[e,E]),l.useEffect(()=>{if(!x.current)return;const B=_.current;i&&!B.isClosed&&e({event:"conversationClosed"}),B.isClosed=i},[e,i]),l.useEffect(()=>{if(!x.current)return;const B=_.current;c&&!B.isHandedOff&&e({event:"agentConnected",agentName:u}),B.isHandedOff=c},[u,e,c]),l.useEffect(()=>{if(!x.current)return;const B=_.current;m&&h!=="ai_responding"&&(!B.inputDisabled||B.inputDisabledBy==="ai_responding")&&e({event:"inputDisabled"}),B.inputDisabled=m,B.inputDisabledBy=h},[e,m,h])},Xf=()=>{const{channelSource:e}=Te(),t=Si(e.channel);return!(t!=null&&t.user.userId)||!t.user.nickname?null:{userId:t.user.userId,nickname:t.user.nickname}},Zf=e=>{const{announceStatus:t,announcementsEnabled:n}=rt();Fd(e??null,r=>{t({event:"typing",agentName:r})},1e4,n)},Jf=()=>{const e=Xf();Zf(e)},Q=({type:e,size:t=24,className:n,color:r})=>{const{icons:s}=yh(),o=s[e];return a.createElement(Qf,{className:n},a.createElement(o,{size:t,color:r??C.color.primary.main,flipInRtl:gh.has(e)}))},Qf=b.default.span.attrs({"aria-hidden":"true"})`
|
|
81
81
|
display: inline-flex;
|
|
82
82
|
&:focus {
|
|
83
83
|
outline: none;
|
|
84
84
|
}
|
|
85
|
-
`,uf=.75,Ti=6,df=Ti*2;let Jn=null;typeof Intl<"u"&&"Segmenter"in Intl&&(Jn=new Intl.Segmenter(void 0,{granularity:"grapheme"}));const mf=e=>Jn?Array.from(Jn.segment(e),t=>t.segment):[...e],ff=e=>{const t=Math.floor(e.length*uf),n=Math.max(0,e.length-Ti);return Math.max(t,n)},Do=(e,t="")=>{if(e.length<df)return{start:e+t,end:""};const n=mf(e),r=ff(n);return{start:n.slice(0,r).join(""),end:n.slice(r).join("")+t}},gf=e=>{const t=e.normalize("NFC").trim(),n=t.lastIndexOf(".");if(!(n>0&&n<t.length-1))return Do(t);const o=t.slice(0,n),s=t.slice(n);return Do(o,s)},Ii=({children:e,...t})=>{const{start:n,end:r}=u.useMemo(()=>gf(e),[e]);return r?i.createElement(hf,null,i.createElement(pf,{...t},n),i.createElement(_f,{...t},r)):i.createElement($,{...t},n)},hf=p.default.span`display:flex;width:100%;min-width:0;overflow:hidden;direction:inherit;`,pf=p.default($)`overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex-shrink:1;min-width:0;`,_f=p.default($)`flex-shrink:0;white-space:nowrap;`,Tr=({name:e,mimeType:t,type:n="FILE",iconColor:r,iconBackgroundColor:o,onClick:s,selected:a})=>{const{colors:l}=D.useTheme(),{conversation:c}=oe(),d=s?c.file.buttonLikePreview({name:e,mimeType:t,selected:a,onActivate:s}):c.file.preview({name:e,mimeType:t,selected:a});return i.createElement(Ef,{...d.props,$clickable:!!s},i.createElement(Cf,{$bgColor:o??l.base.primary},i.createElement(X,{type:"file-document",size:24,color:r??l.base.primaryContrastContent})),i.createElement(vf,null,i.createElement(Ii,{variant:"button",color:h.themedColor.textHighEmphasis},e),i.createElement($,{color:h.themedColor.textMidEmphasis,variant:"caption3"},n)),d.descriptionNode)},Ef=p.default.div`border:none;border-radius:12px;gap:8px;width:${ee.BODY_MAX_WIDTH}px;height:64px;display:flex;align-items:center;padding:12px;box-sizing:border-box;border:1px solid ${h.themedColor.textDisabled};background-color:${h.themedColor.bg_50_600};${({$clickable:e})=>e&&bf}`,bf=D.css`cursor:pointer;${Ae}&:hover{background-color:${h.themedColor.bg_100_500};}`,Cf=p.default.div`border-radius:8px;width:40px;height:40px;display:flex;align-items:center;justify-content:center;background-color:${({$bgColor:e})=>e};`,vf=p.default.div`display:flex;flex:1;flex-direction:column;gap:4px;min-width:0;`;function yf({file:e,children:t,onClickFile:n}){const r=n?()=>n(e):void 0;return i.createElement(Sf,null,i.createElement(Tr,{name:e.name,mimeType:e.type,type:or(e.name,e.type),onClick:r}),t)}const Sf=p.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${ee.GAP_GROUPED}px;`,Ke=`${$e}-incoming-msg`,Af=`${$e}-marked-text`;function xf({file:e,onClickMedia:t,onClickMediaFiles:n,children:r}){const{conversation:o}=oe(),s=e.type.startsWith("image"),a=(()=>{if(n)return()=>n({files:[{url:e.url,type:e.type,name:e.name}],index:0});if(t)return()=>t(e)})(),l=a?o.file.buttonLikePreview({name:e.name,mimeType:e.type,onActivate:a}):o.file.preview({name:e.name,mimeType:e.type}),c=()=>s?i.createElement(wf,{src:e.url,alt:"image-message"}):e.type.startsWith("video")?i.createElement(Mf,{controls:!0},i.createElement("source",{src:e.url}),i.createElement("track",{kind:"captions"})):null;if(c){const d={id:`${Ke}-media-body`,...l.props};return i.createElement(Tf,null,i.createElement(If,{...d},c(),l.descriptionNode),r)}return null}const Tf=p.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${ee.GAP_GROUPED}px;`,If=p.default.div`width:${ee.BODY_MAX_WIDTH}px;height:160px;border-radius:12px;overflow:hidden;cursor:pointer;${Z.light`
|
|
86
|
-
background-color: ${
|
|
85
|
+
`,eg=({visible:e,onClose:t,children:n,"aria-label":r})=>a.createElement(ut,{portalContainerId:ve.WINDOW,visible:e,onClose:t,"aria-label":r},a.createElement(sg,null,n)),tg=({onClick:e,destructive:t,icon:n,initialFocus:r,children:s})=>a.createElement(ng,{onClick:e,$destructive:t,"data-sb-initial-focus":r?"true":void 0},n&&a.createElement(rg,null,a.createElement(Q,{type:n,size:24,color:C.themedColor.primary})),s),at=Object.assign(eg,{ActionItem:tg}),ng=b.default.button`all:unset;display:flex;align-items:center;gap:24px;width:100%;padding:12px 24px;cursor:pointer;color:${({$destructive:e})=>e?C.themedColor.error:C.themedColor.textHighEmphasis};${Re}`,rg=b.default.div`display:flex;align-items:center;justify-content:center;flex-shrink:0;`,sg=b.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};`,ho=40,fo=.9,og="[data-message-listitem]",ig='input, textarea, select, [role="textbox"], [contenteditable="true"]',ag=({event:e,list:t,isMessageAnchor:n})=>{switch(e.key){case"PageDown":return t.clientHeight*fo;case"PageUp":return t.clientHeight*-fo;case"ArrowDown":return n?ho:void 0;case"ArrowUp":return n?ho*-1:void 0;default:return}},cg=({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(ig))return;const o=s===r||s.matches(og),i=ag({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]),lg="[data-message-listitem]",ug=e=>Math.min(Math.max(0,e),1),dg=e=>{const n=e.getRootNode().activeElement,r=n==null?void 0:n.closest(lg),s=n===e||n===r;return!n||!e.contains(n)?null:s?e:n},mg=({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})},hg=({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 _=t.current;_&&(u.current==="top"&&(_.scrollTop=_.scrollHeight-m.current,mg({list:_,focusRestoreTarget:h.current}),h.current=null),u.current==="bottom"&&(_.scrollTop=d.current),u.current=void 0)},[t,r]);const p=l.useCallback(async _=>{const y=t.current;if(!y||(i==null||i(_),m.current=y.scrollHeight-y.scrollTop,d.current=y.scrollTop,c.current))return;const A=y.clientHeight*ug(n);if(y.scrollTop<=A){c.current=!0,u.current="top",h.current=dg(y),await o(),c.current=!1;return}if(y.scrollHeight-y.scrollTop-y.clientHeight<=A){c.current=!0,u.current="bottom",await s(),c.current=!1;return}u.current=void 0},[t,n,s,o,i]),v=l.useCallback(_=>{const y=t.current;if(!y)return;const A=g.current;if(A!=null){if(A===y.scrollTop){g.current=null;return}g.current=null}const T=f.current;if(T!=null&&T===y.scrollTop){f.current=null,g.current=y.scrollTop,p(_);return}f.current=null,p(_)},[p,t]),E=l.useCallback(_=>{const y=t.current;y&&(f.current=_,g.current=null,y.scrollTop=_,y.dispatchEvent(new Event("scroll",{bubbles:!0})))},[t]);return l.useLayoutEffect(()=>()=>{f.current=null,g.current=null},[]),{handleScroll:v,syncScrollPosition:E}},fg=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:E=.05,onScroll:_=le,depsForResetScrollPositionToBottom:y,stackDirection:A="top",bottomSpacerHeight:T=0,"aria-label":R}=t,L=l.useRef(null),N=l.useCallback(O=>{L.current=O,n&&(typeof n=="function"?n(O):n.current=O)},[n]),{handleScroll:x,syncScrollPosition:w}=hg({depsForResetScrollPositionToBottom:y,listRef:L,loadThreshold:E,messagesLength:r.length,onLoadNext:v,onLoadPrev:p,onScroll:_}),Y=cg({listRef:L,syncScrollPosition:w});return c?a.createElement(a.Fragment,null,u):o?a.createElement(a.Fragment,null,i):a.createElement(gg,{id:"infinite-list-container"},a.createElement(pg,{id:"infinite-list-inner",ref:N,onScroll:x,onKeyDown:Y,role:"list","aria-label":R,tabIndex:0},A==="bottom"&&a.createElement("div",{style:{flexGrow:1}}),h,d?m:r.map((O,Z)=>s({message:O,index:Z})),f,T>0&&a.createElement("div",{style:{minHeight:T}})),a.createElement(_g,{id:"infinite-list-overlay-container"},a.createElement(Eg,{id:"infinite-list-overlay"},g)))}),gg=b.default.div`display:flex;position:relative;flex:1;overflow:hidden;`,pg=b.default.div`display:flex;flex:1;flex-direction:column;overflow-x:hidden;overflow-y:auto;overscroll-behavior:contain;scrollbar-color:${C.themedColor.textLowEmphasis}transparent;&::-webkit-scrollbar-thumb:hover{background-color:transparent;}`,_g=b.default.div`position:absolute;top:0;bottom:0;left:0;right:0;pointer-events:none;`,Eg=b.default.div`pointer-events:auto;`,st=({as:e,type:t,size:n=16,color:r,disabled:s,children:o,...i})=>{const c=s?C.themedColor.textDisabled:C.themedColor.textHighEmphasis;return a.createElement(Cg,{as:e,disabled:s,...i},a.createElement(Q,{type:t,size:n,color:r??c}),o)},Cg=b.default.button`all:unset;padding:4px;cursor:pointer;display:flex;align-items:center;justify-content:center;${Re}&:disabled{cursor:not-allowed;}`,pt=({className:e,children:t,size:n=26})=>a.createElement(bg,{className:e,$size:n},t??a.createElement(Q,{type:"spinner",size:n})),bg=b.default.div`display:flex;align-items:center;justify-content:center;width:${({$size:e})=>Xe(e)};height:${({$size:e})=>Xe(e)};animation:1s infinite linear;animation-name:rotate;@keyframes rotate{from{transform:rotate(0);}to{transform:rotate(360deg);}}`,vg=({files:e,initialIndex:t=0,onClose:n,visible:r})=>{const[s,o]=l.useState(t),[i,c]=l.useState(!1),{stringSet:u,format:d}=ae(),{config:m}=ce(),h=e.length,f=e[s],g=m.conversation.fileViewer.downloadEnabled,p=h>1,v=(f==null?void 0:f.type)||"",E=We(v),_=zt(v),y=!Ff(v);l.useEffect(()=>{r&&(o(t),c(!1))},[r,t]);const A=l.useCallback(()=>{s>0&&(o(R=>R-1),c(!1))},[s]),T=l.useCallback(()=>{s<h-1&&(o(R=>R+1),c(!1))},[s,h]);return l.useEffect(()=>{if(!r)return;const R=L=>{L.key==="ArrowLeft"?A():L.key==="ArrowRight"&&T()};return window.addEventListener("keydown",R),()=>window.removeEventListener("keydown",R)},[r,A,T]),!r||!f?null:a.createElement(ut,{onClose:n,visible:r,portalContainerId:ve.MODAL_ROOT,"aria-label":(f==null?void 0:f.name)||u.IMAGE_VIEWER__DEFAULT_TITLE},a.createElement(yg,null,a.createElement(Sg,null,a.createElement(Ag,null,a.createElement(Tg,null,a.createElement(H,{variant:"button",maxTextLines:1,color:C.color.ondark.textHighEmphasis},f.name||u.IMAGE_VIEWER__DEFAULT_TITLE),f.timestamp&&a.createElement(H,{variant:"caption2",color:C.color.ondark.textHighEmphasis},d(new Date(f.timestamp),"h:mm a")))),a.createElement(Ig,{type:"close",size:18,color:C.color.ondark.textHighEmphasis,"aria-label":u.A11Y_IMAGE_VIEWER_CLOSE,onClick:n})),a.createElement(xg,null,p&&a.createElement(go,{$position:"left",type:"chevron-right",size:22,color:C.color.ondark.textHighEmphasis,onClick:A,"aria-label":u.A11Y_IMAGE_VIEWER_PREVIOUS,disabled:s===0,$flipped:!0}),a.createElement(Rg,{onClick:R=>R.currentTarget===R.target&&n()},E&&a.createElement(a.Fragment,null,!i&&a.createElement(Mg,null,a.createElement(pt,{size:32},a.createElement(Q,{type:"spinner",color:"textLowEmphasis",size:32}))),a.createElement(wg,{src:f.url,alt:f.name||"Image",$loaded:i,onLoad:()=>c(!0)})),_&&a.createElement(kg,{controls:!0},a.createElement("source",{src:f.url,type:v})),y&&a.createElement(Lg,null,a.createElement(H,{variant:"h1",color:C.themedColor.textHighEmphasis},u.FILE_VIEWER__UNSUPPORT))),p&&a.createElement(go,{$position:"right",type:"chevron-right",size:22,color:C.color.ondark.textHighEmphasis,onClick:T,"aria-label":u.A11Y_IMAGE_VIEWER_NEXT,disabled:s===h-1})),a.createElement(Og,null,p&&a.createElement(H,{variant:"body2",color:C.color.ondark.textHighEmphasis},s+1,"/",h),g&&!y&&a.createElement(Ng,{forwardedAs:"a",href:f.url,download:f.name||"file",type:"download",size:24,color:C.color.ondark.textHighEmphasis,"aria-label":u.A11Y_IMAGE_VIEWER_DOWNLOAD}))))},yg=b.default.div`position:fixed;top:0;left:0;right:0;bottom:0;height:100dvh;outline:none;display:flex;flex-direction:column;background-color:${C.themedColor.bg_50_600};`,Sg=b.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:${C.color.overlay.dark};`,Ag=b.default.div`flex:1;min-width:0;padding-right:8px;`,Tg=b.default.div`display:flex;flex-direction:column;gap:2px;`,Ig=b.default(st)`flex-shrink:0;width:28px;height:28px;border-radius:50%;`,Fn=b.default.div`display:flex;align-items:center;justify-content:center;`,xg=b.default(Fn)`flex:1;min-height:0;position:relative;`,Rg=b.default(Fn)`position:relative;width:100%;height:100%;min-width:0;min-height:0;`,Mg=b.default(Fn)`position:absolute;inset:0;pointer-events:none;`,wg=b.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;`,kg=b.default.video`max-width:100%;max-height:100%;object-fit:contain;`,Lg=b.default(Fn)`flex-direction:column;gap:16px;`,go=b.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:${C.color.overlay.dark};&:disabled{opacity:0.3;}`,Og=b.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:${C.color.overlay.dark};`,Ng=b.default(st)`position:absolute;right:16px;top:50%;transform:translateY(-50%);padding:0;width:24px;height:24px;`,Dg=.75,ga=6,$g=ga*2;let _r=null;typeof Intl<"u"&&"Segmenter"in Intl&&(_r=new Intl.Segmenter(void 0,{granularity:"grapheme"}));const Fg=e=>_r?Array.from(_r.segment(e),t=>t.segment):[...e],Pg=e=>{const t=Math.floor(e.length*Dg),n=Math.max(0,e.length-ga);return Math.max(t,n)},po=(e,t="")=>{if(e.length<$g)return{start:e+t,end:""};const n=Fg(e),r=Pg(n);return{start:n.slice(0,r).join(""),end:n.slice(r).join("")+t}},Ug=e=>{const t=e.normalize("NFC").trim(),n=t.lastIndexOf(".");if(!(n>0&&n<t.length-1))return po(t);const s=t.slice(0,n),o=t.slice(n);return po(s,o)},pa=({children:e,...t})=>{const{start:n,end:r}=l.useMemo(()=>Ug(e),[e]);return r?a.createElement(Bg,null,a.createElement(Hg,{...t},n),a.createElement(Gg,{...t},r)):a.createElement(H,{...t},n)},Bg=b.default.span`display:flex;width:100%;min-width:0;overflow:hidden;direction:inherit;`,Hg=b.default(H)`overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex-shrink:1;min-width:0;`,Gg=b.default(H)`flex-shrink:0;white-space:nowrap;`,Wr=({name:e,mimeType:t,type:n="FILE",iconColor:r,iconBackgroundColor:s,onClick:o,selected:i})=>{const{colors:c}=P.useTheme(),{conversation:u}=se(),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(zg,{...d.props,$clickable:!!o},a.createElement(qg,{$bgColor:s??c.base.primary},a.createElement(Q,{type:"file-document",size:24,color:r??c.base.primaryContrastContent})),a.createElement(Yg,null,a.createElement(pa,{variant:"button",color:C.themedColor.textHighEmphasis},e),a.createElement(H,{color:C.themedColor.textMidEmphasis,variant:"caption3"},n)),d.descriptionNode)},zg=b.default.div`border:none;border-radius:12px;gap:8px;width:${te.BODY_MAX_WIDTH}px;height:64px;display:flex;align-items:center;padding:12px;box-sizing:border-box;border:1px solid ${C.themedColor.textDisabled};background-color:${C.themedColor.bg_50_600};${({$clickable:e})=>e&&Vg}`,Vg=P.css`cursor:pointer;${Re}&:hover{background-color:${C.themedColor.bg_100_500};}`,qg=b.default.div`border-radius:8px;width:40px;height:40px;display:flex;align-items:center;justify-content:center;background-color:${({$bgColor:e})=>e};`,Yg=b.default.div`display:flex;flex:1;flex-direction:column;gap:4px;min-width:0;`;function Wg({file:e,children:t,onClickFile:n}){const r=n?()=>n(e):void 0;return a.createElement(Kg,null,a.createElement(Wr,{name:e.name,mimeType:e.type,type:Ar(e.name,e.type),onClick:r}),t)}const Kg=b.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${te.GAP_GROUPED}px;`,et=`${Ge}-incoming-msg`,jg=`${Ge}-marked-text`;function Xg({file:e,onClickMedia:t,onClickMediaFiles:n,children:r}){const{conversation:s}=se(),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(Qg,{src:e.url,alt:"image-message"}):e.type.startsWith("video")?a.createElement(ep,{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(Zg,null,a.createElement(Jg,{...d},u(),c.descriptionNode),r)}return null}const Zg=b.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${te.GAP_GROUPED}px;`,Jg=b.default.div`width:${te.BODY_MAX_WIDTH}px;height:160px;border-radius:12px;overflow:hidden;cursor:pointer;${ee.light`
|
|
86
|
+
background-color: ${C.color.background100};
|
|
87
87
|
`}
|
|
88
|
-
${
|
|
89
|
-
background-color: ${
|
|
88
|
+
${ee.dark`
|
|
89
|
+
background-color: ${C.color.background400};
|
|
90
90
|
`}
|
|
91
|
-
`,
|
|
92
|
-
background-color: ${
|
|
91
|
+
`,Qg=b.default.img`width:100%;height:100%;object-fit:cover;`,ep=b.default.video`width:100%;height:100%;object-fit:cover;`,_a=({images:e,isPending:t=!1,onClickImage:n})=>{const{conversation:r}=se(),s=e.length;if(s===0)return null;const o=eu(s),i=!!n&&!t;return a.createElement(np,{$width:te.BODY_MAX_WIDTH,$columns:o},e.map((c,u)=>{const{columnSpan:d}=tu({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(rp,{key:c.url,$clickable:i,$itemSpan:d,$isPending:t,...g.props},a.createElement(tp,{src:c.url,alt:c.name||""}),t&&a.createElement(sp,null),g.descriptionNode)}))},tp=({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(op,null,a.createElement(pt,{size:20},a.createElement(Q,{type:"spinner",color:"textLowEmphasis",size:20}))),s&&a.createElement(ip,null,a.createElement(Q,{type:"photo",color:"textLowEmphasis",size:24})),!s&&a.createElement(ap,{src:e,alt:t,$loaded:n,onLoad:()=>r(!0),onError:()=>o(!0)}))},np=b.default.div`display:grid;grid-template-columns:repeat(${({$columns:e})=>e},1fr);width:${({$width:e})=>e}px;gap:2px;border-radius:16px;overflow:hidden;`,rp=b.default.div`position:relative;width:100%;aspect-ratio:1;overflow:hidden;cursor:${e=>e.$clickable?"pointer":"default"};${ee.light`
|
|
92
|
+
background-color: ${C.color.background100};
|
|
93
93
|
`}
|
|
94
|
-
${
|
|
95
|
-
background-color: ${
|
|
94
|
+
${ee.dark`
|
|
95
|
+
background-color: ${C.color.background400};
|
|
96
96
|
`}
|
|
97
97
|
${e=>e.$itemSpan&&e.$itemSpan>1&&`
|
|
98
98
|
grid-column: span ${e.$itemSpan};
|
|
@@ -100,7 +100,7 @@
|
|
|
100
100
|
`}
|
|
101
101
|
|
|
102
102
|
&:focus-visible {
|
|
103
|
-
outline: 2px solid ${
|
|
103
|
+
outline: 2px solid ${C.color.primary.main};
|
|
104
104
|
outline-offset: -2px;
|
|
105
105
|
}
|
|
106
106
|
|
|
@@ -111,19 +111,19 @@
|
|
|
111
111
|
}
|
|
112
112
|
`}
|
|
113
113
|
}
|
|
114
|
-
`,
|
|
115
|
-
background-color: ${
|
|
114
|
+
`,sp=b.default.div`position:absolute;top:0;left:0;width:100%;height:100%;background-color:${C.color.overlay.dark};pointer-events:none;`,Ea=b.default.div`display:flex;align-items:center;justify-content:center;`,op=b.default(Ea)`position:absolute;inset:0;`,ip=b.default(Ea)`position:absolute;inset:0;${ee.light`
|
|
115
|
+
background-color: ${C.color.background200};
|
|
116
116
|
`}
|
|
117
|
-
${
|
|
118
|
-
background-color: ${
|
|
117
|
+
${ee.dark`
|
|
118
|
+
background-color: ${C.color.background500};
|
|
119
119
|
`}
|
|
120
|
-
`,
|
|
120
|
+
`,ap=b.default.img`position:absolute;inset:0;width:100%;height:100%;object-fit:cover;opacity:${({$loaded:e})=>e?1:0};transition:opacity 0.3s ease;`,cp=({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(lp,null,a.createElement(_a,{images:e,onClickImage:s}),t)},lp=b.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${te.GAP_GROUPED}px;`,up="✱",Ca=e=>{const t=new RegExp(`(\`+)([^\`]+?)\\1|(${up}+)`,"g");return e.replace(t,(n,r,s,o)=>r?n:o?`<span id=${jg} aria-label="masked-text">${o}</span>`:n)},dp=e=>e.replace(/\*\*(.*?)\*\*/g,"<b>$1</b>"),_o=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)}}},mp=l.lazy(async()=>({default:(await Promise.resolve().then(()=>require("./cjs/VvejebHE.cjs"))).MarkdownText})),Eo=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 hp(e){var s,o;const t=e.maxBodyWidth??te.BODY_MAX_WIDTH,n=l.useMemo(()=>Sc(e.message,Ca),[e.message]),r={id:`${et}-text-body`,$maxWidth:t,$color:(s=e.customStyle)==null?void 0:s.bubbleContentColor,$bgColor:(o=e.customStyle)==null?void 0:o.bubbleBackgroundColor,$surface:e.surface??"bubble"};return n.length===0?e.children?a.createElement(Co,{...r},e.children):null:a.createElement(Co,{...r},n.map((i,c)=>i.type==="text"?a.createElement(bo,{key:c,variant:"body3"},a.createElement(Ht,{fallback:i.value},a.createElement(mp,{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"?Eo?a.createElement(Ht,{key:c,fallback:a.createElement(bo,{variant:"body3"},i.value)},a.createElement(Eo,{code:i.value,language:i.language})):a.createElement(fp,{key:c},a.createElement("code",null,i.value)):null),e.children)}const Co=b.default.div`display:flex;flex-direction:column;min-width:0;max-width:min(${({$maxWidth:e})=>e}px,100%);${({theme:e,$color:t,$bgColor:n,$surface:r})=>P.css`
|
|
121
121
|
color: ${t||e.colors.messageIncoming.text};
|
|
122
|
-
${r==="bubble"?
|
|
122
|
+
${r==="bubble"?P.css`background-color:${n||e.colors.messageIncoming.background};border-radius:12px;overflow:hidden;padding:12px 0;`:P.css`background-color:transparent;border-radius:0;overflow:visible;padding:0;`}
|
|
123
123
|
`}
|
|
124
124
|
transition: max-width 0.3s;
|
|
125
125
|
overflow-wrap: break-word;
|
|
126
|
-
`,
|
|
126
|
+
`,bo=b.default(H)`align-items:flex-start;line-height:140%;white-space:pre-wrap;padding:0 12px;`,fp=b.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 ba({id:e,src:t,size:n=56,onClick:r,onImageError:s,style:o,...i}){const[c,u]=l.useState();return a.createElement(gp,{id:e,tabIndex:r?0:void 0,onClick:r,$size:Xe(n),style:o,...i},t&&t!==c?a.createElement(pp,{src:t,alt:"",onError:()=>{u(t),s==null||s(t)}}):a.createElement(Q,{type:"user",size:n}))}const gp=b.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:${C.themedColor.bg_100_500};&:focus{outline:none;}${Re}`,pp=b.default.img`object-fit:cover;width:100%;height:100%;position:absolute;`,_p=({sender:e,isBotMessage:t})=>{const n=`${et}-sender-avatar`,[r,s]=l.useState();return t&&(!e.profileUrl||e.profileUrl===r)?a.createElement(Ep,{id:n},a.createElement(Q,{type:"delight",size:"100%"})):a.createElement(ba,{id:n,size:te.AVATAR_SIZE,src:e.profileUrl,onImageError:t?s:void 0})},Ep=b.default.div`flex-shrink:0;width:${te.AVATAR_SIZE}px;height:${te.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;}}`,Cp=({sender:e})=>a.createElement(bp,{id:`${et}-sender-name`,variant:"caption1",color:C.themedColor.textMidEmphasis},e.nickname),bp=b.default(H)`text-align:start;width:100%;box-sizing:border-box;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;padding-block:5px;padding-inline:0 7px;`,vp=({createdAt:e})=>{const{stringSet:t,format:n}=ae();return e?a.createElement(H,{id:`${et}-sent-time`,variant:"caption4",color:C.themedColor.textLowEmphasis},n(e,t.DATE_FORMAT__MESSAGE_TIMESTAMP)):null},va="(prefers-reduced-motion: reduce)",yp=()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia(va).matches,ya=()=>{const[e,t]=l.useState(yp);return l.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const n=window.matchMedia(va);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},Sp=({thinkingMessage:e,customStyle:t})=>{const n=ya();return e?a.createElement(Ip,{$prefersReducedMotion:n},a.createElement(xp,null,e),!n&&a.createElement(Rp,null)):a.createElement(Ap,{$bgColor:t==null?void 0:t.bubbleBackgroundColor},[0,1,2].map(r=>a.createElement(Tp,{key:r,$color:t==null?void 0:t.bubbleContentColor,$prefersReducedMotion:n})))},Ap=b.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};`,Tp=b.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;}`,Ip=b.default.div.attrs({id:`${et}-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
|
+
`,xp=b.default(H).attrs({variant:"body3"})`
|
|
139
139
|
white-space: pre-wrap;
|
|
140
140
|
word-break: break-word;
|
|
141
|
-
color: ${
|
|
142
|
-
`,
|
|
143
|
-
`,
|
|
141
|
+
color: ${C.themedColor.textHighEmphasis};
|
|
142
|
+
`,Rp=b.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=vs(e.colors.base.background,.5),n=vs(e.colors.base.background,0);return`linear-gradient(90deg, ${n} 0%, ${t} 30%, ${t} 60%, ${n} 100%)`}};
|
|
143
|
+
`,Mp=({extendedMessagePayload:e,onClickCTA:t=({url:n})=>Vr(n)})=>{const n=e==null?void 0:e.cta_button;if(!n)return null;const r=()=>t(n);return a.createElement(wp,{id:`${et}-ext-cta-button`,onClick:r},a.createElement(kp,{variant:"button"},n.label))},wp=b.default.button.attrs({type:"button"})`
|
|
144
144
|
all: unset;
|
|
145
145
|
display: flex;
|
|
146
146
|
width: 100%;
|
|
@@ -150,14 +150,14 @@
|
|
|
150
150
|
cursor: pointer;
|
|
151
151
|
border-radius: 6px;
|
|
152
152
|
padding: 8px;
|
|
153
|
-
color: ${
|
|
154
|
-
background-color: ${
|
|
155
|
-
${
|
|
156
|
-
background-color: ${
|
|
153
|
+
color: ${C.themedColor.textHighEmphasis};
|
|
154
|
+
background-color: ${C.color.background50};
|
|
155
|
+
${ee.dark`
|
|
156
|
+
background-color: ${C.color.ondark.textDisabled};
|
|
157
157
|
`}
|
|
158
158
|
|
|
159
|
-
${
|
|
160
|
-
`,
|
|
159
|
+
${Re}
|
|
160
|
+
`,kp=b.default(H)`overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,Lp=e=>a.createElement(a.Fragment,null),Op=({extendedMessagePayload:e,onClickCitation:t=n=>Vr(n.link)})=>{const{stringSet:n}=ae(),{theme:r}=Nr(),s=e==null?void 0:e.citations;return!s||s.length===0?null:a.createElement(Np,{id:`${et}-ext-citation`},a.createElement(Dp,{variant:"caption1",color:r.colors.messageIncoming.text},n.CITATION_SOURCE_TITLE),a.createElement($p,null,s.map((o,i)=>a.createElement(Pp,{key:`${o.embedding_id}-${i}`,onClick:()=>t(o)},a.createElement(Q,{type:"source",size:16,color:r.colors.messageIncoming.text}),a.createElement(Fp,{variant:"body3",color:r.colors.messageIncoming.text},o.title)))))},Np=b.default.div`display:flex;flex-direction:column;gap:8px;border-radius:8px;padding:8px 12px 6px;`,Dp=b.default(H)`opacity:0.5;`,$p=b.default.div`display:flex;flex-direction:column;gap:8px;`,Fp=b.default(H)`text-decoration:underline;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,Pp=b.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
|
+
`,Up=e=>a.createElement(a.Fragment,null),Er=e=>`${e}-filled`,Bp=e=>e==="good"?Se.AIAgentMessageFeedbackRating.GOOD:Se.AIAgentMessageFeedbackRating.BAD,Kr=P.css`&:hover{opacity:0.8;}&:active{opacity:0.6;}`,ln={good:{onlight:C.color.secondary.dark,ondark:C.color.secondary.light},bad:{onlight:C.color.error.dark,ondark:C.color.error.light}},Hp={good:C.themedColor.secondary,bad:C.themedColor.error},Sa=e=>P.css`color:${ln[e].onlight};border-color:${ln[e].onlight};${ee.dark`
|
|
176
|
+
color: ${ln[e].ondark};
|
|
177
|
+
border-color: ${ln[e].ondark};
|
|
178
178
|
`}
|
|
179
|
-
`,
|
|
180
|
-
outline: 2px solid ${
|
|
179
|
+
`,Gp=({visible:e,onClose:t,isEdit:n,initialRating:r,initialComment:s="",onSubmit:o,isCommentEnabled:i=!1})=>{const{stringSet:c}=ae(),{conversation:u}=se(),{rootElement:d}=Ki(),m=lt(d),[h,f]=l.useState(r),[g,p]=l.useState(s),[v,E]=l.useState(!1),_=l.useRef(!1),y=h??r??"good",A=u.feedback;l.useLayoutEffect(()=>{e?(f(r),p(s)):(f(void 0),p(""))},[e,r,s]),l.useEffect(()=>{if(!e)return;const N=w=>{const Y=w;Y.metaKey||Y.altKey||Y.ctrlKey||(_.current=!0)},x=()=>{_.current=!1,E(!1)};return m.addEventListener("keydown",N),m.addEventListener("pointerdown",x),()=>{m.removeEventListener("keydown",N),m.removeEventListener("pointerdown",x)}},[m,e]);const T=()=>{h&&(o({rating:h,comment:g.trim()||void 0}),t())},R=()=>{t()};if(!e)return null;const L={feedback:A.container()};return a.createElement(ut,{portalContainerId:ve.WINDOW,visible:e,onClose:R,"aria-label":c.FEEDBACK_TITLE},a.createElement(zp,null,a.createElement(Vp,null,a.createElement(H,{variant:"h2",color:C.themedColor.textHighEmphasis},c.FEEDBACK_TITLE)),a.createElement(qp,null,a.createElement(Yp,{...L.feedback.props},["good","bad"].map(N=>{const x=h===N,w=N==="good"?c.FEEDBACK_GOOD:c.FEEDBACK_BAD,Y=A.button(N,x);return a.createElement(l.Fragment,{key:N},a.createElement(Wp,{type:"button",$selected:x,$rating:N,...Y.props,onClick:()=>f(N),"data-sb-initial-focus":N===y?"true":void 0},a.createElement(Q,{type:x?Er(N):N,size:24,color:"currentColor"}),a.createElement(H,{variant:"caption1",color:"currentColor"},w)),Y.descriptionNode)}),L.feedback.descriptionNode),i&&a.createElement(Kp,null,a.createElement(H,{variant:"caption3",color:C.themedColor.textHighEmphasis},c.FEEDBACK_COMMENT_LABEL),a.createElement(jp,{placeholder:c.FEEDBACK_COMMENT_PLACEHOLDER,value:g,onChange:N=>p(N.target.value),onFocus:()=>E(_.current),onBlur:()=>E(!1),maxLength:100,$focusVisible:v,"data-focus-visible":v?"true":"false"}))),a.createElement(Xp,null,a.createElement(Zp,{onClick:R},a.createElement(H,{variant:"button",color:C.themedColor.textHighEmphasis},c.FEEDBACK_CANCEL)),a.createElement(Jp,{onClick:T,disabled:!h},a.createElement(H,{variant:"button"},n?c.FEEDBACK_SAVE:c.FEEDBACK_SUBMIT)))))},zp=b.default.div`width:280px;background-color:${({theme:e})=>e.colors.base.modalContentBackground};border-radius:12px;overflow:hidden;`,Vp=b.default.div`padding:24px;`,qp=b.default.div`padding-inline:24px;display:flex;flex-direction:column;gap:24px;`,Yp=b.default.div`display:flex;gap:4px;`,Wp=b.default.button`width:114px;height:64px;border-radius:12px;border:1px solid ${C.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:${C.themedColor.textLowEmphasis};background-color:transparent;${({$selected:e,$rating:t})=>e&&Sa(t)}${Kr}`,Kp=b.default.label`display:flex;flex-direction:column;gap:6px;`,jp=b.default.textarea`font-family:inherit;font-size:12px;line-height:16px;border:1px solid ${C.themedColor.textDisabled};border-radius:4px;padding:6px 12px;color:${C.themedColor.textHighEmphasis};background-color:${C.themedColor.textLowEmphasisInverse};resize:none;field-sizing:content;min-height:28px;max-height:118px;overflow-y:auto;&::placeholder{color:${C.themedColor.textLowEmphasis};}&:focus{outline:none;}${({$focusVisible:e})=>e&&P.css`
|
|
180
|
+
outline: 2px solid ${C.themedColor.primary};
|
|
181
181
|
outline-offset: 2px;
|
|
182
182
|
`}
|
|
183
|
-
`,
|
|
184
|
-
border: 1px solid ${
|
|
183
|
+
`,Xp=b.default.div`padding-inline:24px;padding-block:16px;display:flex;justify-content:flex-end;gap:4px;`,Aa=b.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;`,Zp=b.default(Aa)`background-color:transparent;${Kr}`,Jp=b.default(Aa)`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};}`,Qp=({isBotMessage:e,isConversationClosed:t,isStreaming:n,isFeedbackEnabled:r,isFeedbackCommentEnabled:s,extendedMessagePayload:o,onFeedbackUpdate:i})=>{const{stringSet:c}=ae(),{conversation:u}=se(),[d,m]=l.useState(!1),[h,f]=l.useState(!1),[g,p]=l.useState(void 0),[v,E]=l.useState(""),_=l.useRef(null),y=l.useRef(null),A=l.useRef(null),T=l.useRef(!1),R=u.feedback,L=o==null?void 0:o.feedback,N=(L==null?void 0:L.rating)??"none";if(N!=="none"?!1:!!(n||!e||!r||(o==null?void 0:o.bot_message_type)!=="generated"||t))return null;const w=q=>{q&&we(()=>{const ne=q==="good"?_.current:y.current;ne==null||ne.focus()})},Y=({restoreTrigger:q=!0}={})=>{f(!1),q&&w(A.current)},O=q=>{N==="none"?(p(q),E(""),m(!0)):(A.current=q,f(!0))},Z=()=>{i==null||i(null),Y()},G=()=>{T.current=!0,Y({restoreTrigger:!1}),p(L==null?void 0:L.rating),E((L==null?void 0:L.comment)??""),m(!0)},D=q=>{T.current=!1,i==null||i(q),m(!1),w(A.current)},z=()=>{m(!1),T.current&&(T.current=!1,f(!0))};return t&&N!=="none"?a.createElement(vo,{role:"presentation",$horizontal:!0},a.createElement(e_,null,a.createElement(Q,{type:Er(N),size:12,color:Hp[N]})),(L==null?void 0:L.comment)&&a.createElement(yo,{variant:"caption2",style:{lineHeight:"16px"}},L.comment)):a.createElement(a.Fragment,null,a.createElement(vo,{role:"presentation"},a.createElement(t_,{role:"presentation"},["good","bad"].map(q=>{const ne=N===q,ue=R.button(q,ne);return a.createElement(l.Fragment,{key:q},a.createElement(n_,{$selected:ne,$rating:q,ref:q==="good"?_:y,...ue.props,onClick:()=>O(q)},a.createElement(Q,{type:ne?Er(q):q,size:14,color:"currentColor"})),ue.descriptionNode)})),N!=="none"&&(L==null?void 0:L.comment)&&a.createElement(yo,{variant:"caption2"},L.comment)),a.createElement(at,{visible:h,onClose:Y,...R.optionsBottomSheet().props},a.createElement(at.ActionItem,{onClick:G,initialFocus:!0},c.FEEDBACK_EDIT),a.createElement(at.ActionItem,{onClick:Z,destructive:!0},c.FEEDBACK_REMOVE)),a.createElement(Gp,{visible:d,onClose:z,isEdit:N!=="none",initialRating:g,initialComment:v,onSubmit:D,isCommentEnabled:s}))},vo=b.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:${te.BODY_MAX_WIDTH}px;`,e_=b.default.div`padding:2px;flex-shrink:0;display:flex;align-items:center;`,t_=b.default.div`display:flex;gap:2px;`,n_=b.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:${C.themedColor.textMidEmphasis};border:1px solid ${C.color.background200};background-color:transparent;${ee.dark`
|
|
184
|
+
border: 1px solid ${C.color.background400};
|
|
185
185
|
`}
|
|
186
186
|
|
|
187
|
-
${({$selected:e,$rating:t})=>e&&
|
|
187
|
+
${({$selected:e,$rating:t})=>e&&Sa(t)}
|
|
188
188
|
|
|
189
|
-
${
|
|
190
|
-
`,
|
|
191
|
-
color: ${
|
|
189
|
+
${Kr}
|
|
190
|
+
`,yo=b.default(H)`color:${C.themedColor.textMidEmphasis};${ee.dark`
|
|
191
|
+
color: ${C.themedColor.textHighEmphasis};
|
|
192
192
|
`}
|
|
193
|
-
`,
|
|
194
|
-
background-color: ${
|
|
193
|
+
`,jr=P.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;${Re}&:disabled{cursor:not-allowed;}`,So=b.default.button`${jr};background-color:${C.themedColor.primary};color:${C.themedColor.textHighEmphasis};&:hover:not(:disabled){opacity:0.9;}`,r_=b.default.button`${jr};color:${C.themedColor.primary};${ee.light`
|
|
194
|
+
background-color: ${C.color.background50};
|
|
195
195
|
`};
|
|
196
|
-
${
|
|
197
|
-
background-color: ${
|
|
196
|
+
${ee.dark`
|
|
197
|
+
background-color: ${C.color.background700};
|
|
198
198
|
`};
|
|
199
199
|
|
|
200
200
|
&:hover:not(:disabled) {
|
|
201
201
|
opacity: 0.9;
|
|
202
202
|
}
|
|
203
|
-
`,
|
|
204
|
-
background-color: ${
|
|
203
|
+
`,s_=b.default.button`${jr};background-color:transparent;color:${C.themedColor.textHighEmphasis};&:hover:not(:disabled){opacity:0.7;}`,o_=e=>{switch(e){case"primary":return So;case"secondary":return r_;case"clear":return s_;default:return So}},i_=b.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);}}`,a_=({children:e,onClick:t,variant:n="primary",disabled:r=!1,loading:s=!1,className:o,...i})=>{const c=()=>{switch(n){case"primary":return C.themedColor.textHighEmphasisInverse;case"secondary":return C.themedColor.primary;case"clear":return C.themedColor.textHighEmphasis;default:return C.themedColor.textHighEmphasisInverse}},u=o_(n);return a.createElement(u,{onClick:t,disabled:r||s,className:o,...i},s?a.createElement(i_,null,a.createElement(Q,{type:"spinner",size:22,color:c()})):a.createElement(H,{variant:"button",color:c()},e))},c_=({children:e,className:t,style:n,id:r,role:s})=>a.createElement(H,{variant:"caption4",color:C.themedColor.error,className:t,style:n,id:r,role:s},e),l_=({id:e,children:t,className:n,style:r,required:s,"aria-hidden":o})=>{const{stringSet:i}=ae();return a.createElement(H,{id:e,variant:"caption3",color:C.themedColor.textMidEmphasis,className:n,style:r,"aria-hidden":o},t,!s&&a.createElement("span",{style:{color:C.themedColor.textLowEmphasis}},` (${i.OPTIONAL})`))},u_=({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("."),E=p.length>1?p[0]+"."+p.slice(1).join("").replace(/\./g,""):g;if(h.target.value=E,E===""||E==="-")t==null||t(null);else{const _=Number(E);if(!isNaN(_)){if(c!==void 0&&_>c)return;t==null||t(_)}}},m=e==null?"":String(e);return a.createElement(g_,{type:"text",value:m,onChange:d,placeholder:n,className:o,disabled:i||s,inputMode:"decimal",$error:r,$submitted:s,...u})},d_=P.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;${Re}&::placeholder{color:${C.themedColor.textLowEmphasis};}&::-webkit-inner-spin-button,&::-webkit-outer-spin-button{-webkit-appearance:none;margin:0;}`,m_=P.css`color:${C.themedColor.textHighEmphasis};border:1px solid transparent;cursor:not-allowed;${ee.light`
|
|
204
|
+
background-color: ${C.color.ondark.textMidEmphasis};
|
|
205
205
|
`}
|
|
206
|
-
${
|
|
207
|
-
background-color: ${
|
|
206
|
+
${ee.dark`
|
|
207
|
+
background-color: ${C.color.onlight.textLowEmphasis};
|
|
208
208
|
`}
|
|
209
209
|
|
|
210
210
|
&::placeholder {
|
|
211
|
-
color: ${
|
|
211
|
+
color: ${C.themedColor.textLowEmphasis};
|
|
212
212
|
}
|
|
213
|
-
`,
|
|
214
|
-
background-color: ${
|
|
213
|
+
`,h_=P.css`border:1px solid ${C.themedColor.error};color:${C.themedColor.textHighEmphasis};${ee.light`
|
|
214
|
+
background-color: ${C.color.background50};
|
|
215
215
|
`}
|
|
216
|
-
${
|
|
217
|
-
background-color: ${
|
|
216
|
+
${ee.dark`
|
|
217
|
+
background-color: ${C.color.onlight.textLowEmphasis};
|
|
218
218
|
`}
|
|
219
|
-
`,
|
|
220
|
-
background-color: ${
|
|
219
|
+
`,f_=P.css`border:1px solid ${C.themedColor.textDisabled};color:${C.themedColor.textHighEmphasis};${ee.light`
|
|
220
|
+
background-color: ${C.color.background50};
|
|
221
221
|
`}
|
|
222
|
-
${
|
|
223
|
-
background-color: ${
|
|
222
|
+
${ee.dark`
|
|
223
|
+
background-color: ${C.color.onlight.textLowEmphasis};
|
|
224
224
|
`}
|
|
225
225
|
|
|
226
226
|
&:focus {
|
|
227
|
-
border-color: ${
|
|
227
|
+
border-color: ${C.themedColor.primary};
|
|
228
228
|
}
|
|
229
|
-
`,
|
|
229
|
+
`,g_=b.default.input`${d_}${({$error:e,$submitted:t})=>t?m_:e?h_:f_}`,p_=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))}}}},Ta=e=>{const{options:t,submitted:n=!1,error:r=!1,className:s,groupLabel:o}=e,{conversation:i}=se(),c=e.multiple===!0,{selectedValues:u,handleOptionClick:d}=p_(e),m=t.some(h=>u.includes(h.value));return a.createElement(E_,{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(T_,{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 E=t[v];E&&d(E.value)})).props,disabled:n,onClick:()=>d(h.value)},a.createElement(H,{variant:"caption1",color:__(g,n)},h.label))}))},__=(e,t)=>t?e?C.themedColor.textHighEmphasis:C.themedColor.textDisabled:e?C.themedColor.primary:C.themedColor.textMidEmphasis,E_=b.default.div`display:flex;flex-wrap:wrap;gap:4px 2px;`,C_=P.css`display:inline-flex;align-items:center;padding:8px 12px;border-radius:15px;transition:all 0.2s ease;`,b_=P.css`cursor:default;background-color:${C.color.ondark.textMidEmphasis};color:${C.themedColor.textHighEmphasis};${ee.dark`
|
|
230
230
|
background-color: transparent;
|
|
231
231
|
border: 1px solid white;
|
|
232
232
|
color: white;
|
|
233
233
|
`}
|
|
234
|
-
`,
|
|
235
|
-
background-color: ${
|
|
236
|
-
color: ${
|
|
234
|
+
`,v_=P.css`cursor:default;${ee.light`
|
|
235
|
+
background-color: ${C.color.ondark.textMidEmphasis};
|
|
236
|
+
color: ${C.themedColor.textDisabled};
|
|
237
237
|
`}
|
|
238
|
-
${
|
|
239
|
-
background-color: ${
|
|
240
|
-
border: 1px solid ${
|
|
241
|
-
color: ${
|
|
238
|
+
${ee.dark`
|
|
239
|
+
background-color: ${C.color.onlight.textLowEmphasis};
|
|
240
|
+
border: 1px solid ${C.color.onlight.textLowEmphasis};
|
|
241
|
+
color: ${C.themedColor.textDisabled};
|
|
242
242
|
`}
|
|
243
|
-
`,
|
|
244
|
-
background-color: ${
|
|
245
|
-
color: ${
|
|
243
|
+
`,y_=P.css`cursor:pointer;border:1px solid ${C.themedColor.primary};${ee.light`
|
|
244
|
+
background-color: ${C.color.background50};
|
|
245
|
+
color: ${C.themedColor.primary};
|
|
246
246
|
`}
|
|
247
|
-
${
|
|
248
|
-
background-color: ${
|
|
249
|
-
color: ${
|
|
247
|
+
${ee.dark`
|
|
248
|
+
background-color: ${C.color.onlight.textLowEmphasis};
|
|
249
|
+
color: ${C.themedColor.primary};
|
|
250
250
|
`}
|
|
251
|
-
`,
|
|
252
|
-
background-color: ${
|
|
253
|
-
color: ${
|
|
251
|
+
`,S_=P.css`cursor:pointer;border:1px solid ${C.themedColor.textDisabled};${ee.light`
|
|
252
|
+
background-color: ${C.color.background50};
|
|
253
|
+
color: ${C.themedColor.textMidEmphasis};
|
|
254
254
|
`}
|
|
255
|
-
${
|
|
256
|
-
background-color: ${
|
|
257
|
-
color: ${
|
|
255
|
+
${ee.dark`
|
|
256
|
+
background-color: ${C.color.onlight.textLowEmphasis};
|
|
257
|
+
color: ${C.themedColor.textMidEmphasis};
|
|
258
258
|
`}
|
|
259
|
-
`,
|
|
260
|
-
${r} ${
|
|
259
|
+
`,A_=P.css`border-color:${C.themedColor.error}!important;`,T_=b.default.button`${C_}${({$active:e,$submitted:t,$error:n})=>{if(t)return e?b_:v_;const r=e?y_:S_;return n?P.css`
|
|
260
|
+
${r} ${A_}
|
|
261
261
|
`:r}}
|
|
262
|
-
`,
|
|
263
|
-
background-color: ${
|
|
262
|
+
`,I_=e=>a.createElement(Ta,{...e,multiple:!1}),x_=e=>a.createElement(Ta,{...e,multiple:!0}),R_=b.default.div`width:100%;height:1px;background-color:${C.themedColor.textDisabled};`,M_=({className:e})=>a.createElement(R_,{className:e}),w_=({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(L_,{...f}):a.createElement(k_,{...f})},Ia=P.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;${Re}&::placeholder{color:${C.themedColor.textLowEmphasis};}`,xa=P.css`color:${C.themedColor.textHighEmphasis};border:1px solid transparent;cursor:not-allowed;${ee.light`
|
|
263
|
+
background-color: ${C.color.ondark.textMidEmphasis};
|
|
264
264
|
`}
|
|
265
|
-
${
|
|
266
|
-
background-color: ${
|
|
265
|
+
${ee.dark`
|
|
266
|
+
background-color: ${C.color.onlight.textLowEmphasis};
|
|
267
267
|
`}
|
|
268
268
|
|
|
269
269
|
&::placeholder {
|
|
270
|
-
color: ${
|
|
270
|
+
color: ${C.themedColor.textLowEmphasis};
|
|
271
271
|
}
|
|
272
|
-
`,
|
|
273
|
-
background-color: ${
|
|
272
|
+
`,Ra=P.css`border:1px solid ${C.themedColor.error};color:${C.themedColor.textHighEmphasis};${ee.light`
|
|
273
|
+
background-color: ${C.color.background50};
|
|
274
274
|
`}
|
|
275
|
-
${
|
|
276
|
-
background-color: ${
|
|
275
|
+
${ee.dark`
|
|
276
|
+
background-color: ${C.color.onlight.textLowEmphasis};
|
|
277
277
|
`}
|
|
278
|
-
`,
|
|
279
|
-
background-color: ${
|
|
278
|
+
`,Ma=P.css`border:1px solid ${C.themedColor.textDisabled};color:${C.themedColor.textHighEmphasis};${ee.light`
|
|
279
|
+
background-color: ${C.color.background50};
|
|
280
280
|
`}
|
|
281
|
-
${
|
|
282
|
-
background-color: ${
|
|
281
|
+
${ee.dark`
|
|
282
|
+
background-color: ${C.color.onlight.textLowEmphasis};
|
|
283
283
|
`}
|
|
284
284
|
|
|
285
285
|
&:focus {
|
|
286
|
-
border-color: ${
|
|
286
|
+
border-color: ${C.themedColor.primary};
|
|
287
287
|
}
|
|
288
|
-
`,
|
|
288
|
+
`,k_=b.default.input`${Ia};height:36px;${({$error:e,$submitted:t})=>t?xa:e?Ra:Ma}`,L_=b.default.textarea`${Ia};height:96px;resize:none;font-family:inherit;${({$error:e,$submitted:t})=>t?xa:e?Ra:Ma}`,O_=({children:e,className:t,style:n})=>a.createElement(H,{variant:"button",color:C.themedColor.textHighEmphasis,className:t,style:n},e),Le={Title:O_,Label:l_,ErrorLabel:c_,Separator:M_,Button:a_,TextInput:w_,NumberInput:u_,SingleSelect:I_,MultiSelect:x_},N_=1,D_=new Set(["text","number","single-select","multi-select"]),wa=typeof __SBA_USE_FORM__>"u"||__SBA_USE_FORM__,$_=({messageForm:e,onError:t})=>{const n=l.useRef(void 0);l.useEffect(()=>{if(wa||!e||!t)return;const r=e.key??"";n.current!==r&&(t(new Error("Form rendering is disabled")),n.current=r)},[e,t])},F_=e=>{var _,y;const t=(_=e.extendedMessagePayload)==null?void 0:_.form;if($_({messageForm:t,onError:(y=e.statsCallbacks)==null?void 0:y.onFormRenderError}),!wa)return null;if(!t)throw new Error("Form is not provided");const{stringSet:n}=ae(),{conversation:r}=se(),[s,o]=l.useState({submitting:!1,canceling:!1}),[i,c]=l.useState({visible:!1}),{state:u,fields:d,submit:m,cancel:h,updateFieldValue:f}=Ld(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:A=>{var T;return(T=e.onSubmitForm)==null?void 0:T.call(e,{key:t.key,data:A})},onCancel:()=>{var A;return(A=e.onCancelForm)==null?void 0:A.call(e,{key:t.key})}}),g=u==="submitted",p=async()=>{o(A=>({...A,submitting:!0}));try{await m()}catch(A){c({visible:!0,description:A instanceof Error?A.message:n.TRY_AGAIN})}finally{o(A=>({...A,submitting:!1}))}},v=async()=>{o(A=>({...A,canceling:!0}));try{await h()}catch(A){c({visible:!0,description:A instanceof Error?A.message:n.TRY_AGAIN})}finally{o(A=>({...A,canceling:!1}))}},E=l.useMemo(()=>{const A=()=>t.version>N_,T=()=>t.fields.some(R=>!D_.has(R.type));return A()||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:E.visible?a.createElement(l.Fragment,null,a.createElement(Ao,{$maxWidth:e.maxBodyWidth??te.BODY_MAX_WIDTH},a.createElement(Le.Title,null,t.title),a.createElement(P_,null,d.map(A=>a.createElement(U_,{key:A.key},a.createElement(Le.Label,{style:{marginBottom:"6px"},required:A.required},A.label),A.type==="text"&&a.createElement(Le.TextInput,{value:A.value||"",placeholder:A.placeholder,onChange:T=>f(A.key,T),disabled:g,error:!!A.error,submitted:g,variant:A.layout==="multiline"?"multi-line":"single-line",maxLength:A.maxLength,...r.form.textInput(A.label,A.required??!1,g).props}),A.type==="number"&&a.createElement(Le.NumberInput,{value:A.value||null,placeholder:A.placeholder,onChange:T=>f(A.key,T),disabled:g,error:!!A.error,submitted:g,max:A.max,...r.form.numberInput(A.label,A.required??!1,g).props}),A.type==="single-select"&&a.createElement(Le.SingleSelect,{options:A.options.map(T=>({label:T,value:T})),value:A.value||"",onChange:T=>f(A.key,T),submitted:g,groupLabel:A.label}),A.type==="multi-select"&&a.createElement(Le.MultiSelect,{options:A.options.map(T=>({label:T,value:T})),value:A.value||[],onChange:T=>f(A.key,T),submitted:g,maxSelect:A.maxSelect,groupLabel:A.label}),A.error&&a.createElement(Le.ErrorLabel,{style:{marginTop:"4px"}},A.error)))),a.createElement(Le.Separator,null),a.createElement(B_,null,a.createElement(Le.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(Le.Button,{variant:"secondary",...r.form.button(n.BUTTON__CANCEL).props,onClick:v,disabled:s.submitting,loading:s.canceling},n.BUTTON__CANCEL))),a.createElement(Dn,{...i,onClose:()=>c({visible:!1,title:""})})):a.createElement(Ao,{$maxWidth:e.maxBodyWidth??te.BODY_MAX_WIDTH},a.createElement(H,{variant:"body3"},E.reason),E.cancelable&&a.createElement(Le.Button,{variant:"primary",...r.form.button(n.BUTTON__CANCEL).props,onClick:v,loading:s.canceling},n.BUTTON__CANCEL))},Ao=b.default.div`display:flex;flex-direction:column;gap:12px;border-radius:12px;overflow:hidden;max-width:${({$maxWidth:e})=>e}px;${({theme:e})=>P.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
|
+
`,P_=b.default.div`display:flex;flex-direction:column;gap:12px;`,U_=b.default.div`display:flex;flex-direction:column;`,B_=b.default.div`display:flex;flex-direction:column;gap:8px;`,H_=e=>a.createElement(a.Fragment,null),Cr=typeof __SBA_USE_MESSAGE_TEMPLATE__>"u"||__SBA_USE_MESSAGE_TEMPLATE__?l.lazy(()=>Promise.resolve().then(()=>require("./cjs/BjKg30ip.cjs")).then(e=>({default:e.MessageTemplateWrapper}))):null,G_=({messageTemplate:e,onError:t})=>{const n=l.useRef(void 0);l.useEffect(()=>{if(Cr||!e||!t)return;const r=e.key??"";n.current!==r&&(t(new Error("Message template rendering is disabled")),n.current=r)},[e,t])},z_=e=>{var n,r,s;const t=(n=e.extendedMessagePayload)==null?void 0:n.message_template;return G_({messageTemplate:t,onError:(r=e.statsCallbacks)==null?void 0:r.onMessageTemplateError}),Cr?a.createElement(Ht,{errorFallback:e.messageTemplateErrorFallback,loadingFallback:e.messageTemplateLoadingFallback,onError:(s=e.statsCallbacks)==null?void 0:s.onMessageTemplateError},a.createElement(Cr,{...e})):null},V_=({extendedMessagePayload:e,onClickSuggestedReply:t,suggestedRepliesDirection:n="vertical"})=>{const{conversation:r}=se(),[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(q_,{id:`${et}-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(Y_,{$type:n,...h.props,onClick:()=>u(d)},a.createElement(W_,{variant:"body3"},d)),h.descriptionNode)}))},q_=b.default.div`margin:16px 0;padding:0 ${te.HORIZONTAL_PADDING}px;position:relative;display:flex;align-self:stretch;gap:8px;${({$type:e})=>e==="vertical"?K_:j_};`,Y_=b.default.button.attrs({type:"button"})`
|
|
296
296
|
all: unset;
|
|
297
297
|
box-sizing: border-box;
|
|
298
298
|
padding: 8px 12px;
|
|
@@ -302,30 +302,30 @@
|
|
|
302
302
|
border-radius: 20px / clamp(20px, 5%, 100px);
|
|
303
303
|
cursor: pointer;
|
|
304
304
|
word-break: break-word;
|
|
305
|
-
color: ${
|
|
306
|
-
border: 1px solid ${
|
|
307
|
-
background-color: ${
|
|
305
|
+
color: ${C.color.primary.main};
|
|
306
|
+
border: 1px solid ${C.color.primary.main};
|
|
307
|
+
background-color: ${C.themedColor.bg_50_600};
|
|
308
308
|
|
|
309
309
|
&:hover {
|
|
310
|
-
background-color: ${
|
|
310
|
+
background-color: ${C.themedColor.bg_100_500};
|
|
311
311
|
}
|
|
312
312
|
|
|
313
|
-
${
|
|
313
|
+
${Re}
|
|
314
314
|
|
|
315
|
-
${({$type:e,theme:t})=>
|
|
316
|
-
`,
|
|
315
|
+
${({$type:e,theme:t})=>P.css`${e==="vertical"?X_:Z_};&:active{background-color:${t.colors.base.primary};color:${t.colors.base.primaryContrastContent};}`}
|
|
316
|
+
`,W_=b.default(H)`color:inherit;`,K_=P.css`flex-direction:column;align-items:flex-end;`,j_=P.css`flex-direction:row;overflow-x:scroll;-ms-overflow-style:none;scrollbar-width:none;&::-webkit-scrollbar{display:none;}`,X_=P.css`max-width:calc(100% - 70px);white-space:pre-wrap;`,Z_=P.css`white-space:nowrap;`,J_=e=>{const{components:t}=_t.useContext(),{stringSet:n}=ae(),r=Xo(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})},Q_=e=>{var y,A,T,R;const{components:t}=_t.useContext(),{streamText:n,isAnimating:r}=qd({text:e.message,enabled:e.isStreaming,deferredMarkdownElements:e.deferredMarkdownElements,onAnimationStart:e.onStreamAnimationStart,onAnimationProgress:e.onStreamAnimationProgress,onAnimationComplete:e.onStreamAnimationComplete,onVisibleTextProgress:(y=e.statsCallbacks)==null?void 0:y.onVisibleTextProgress,onRenderedTextProgress:(A=e.statsCallbacks)==null?void 0:A.onRenderedTextProgress}),s={...e,message:n,extendedMessagePayload:r?{}:e.extendedMessagePayload},o=!!s.isTyping,i=!!s.isSenderAvatarVisible,c=Rn(s.extendedMessagePayload),u=c.hasCTAButton,d=c.hasChallenge,m=c.hasCitations,h=c.hasForm,f=c.hasMessageTemplate,g=!!s.createdAt,p=u||m,v=s.groupType==="top"||s.groupType==="single",E=s.groupType==="bottom"||s.groupType==="single",_=i?te.AVATAR_SIZE:0;return a.createElement(eE,{$marginBottom:o?0:Mn(s.groupType)},v&&a.createElement(rE,null,i&&a.createElement(t.SenderAvatar,{...s}),a.createElement(t.SenderName,{...s})),a.createElement(oE,null,a.createElement(nr,{$extraStartPadding:_},o?a.createElement(t.TypingIndicator,{...s}):p?a.createElement(tE,{$maxWidth:s.maxBodyWidth??te.BODY_MAX_WIDTH},a.createElement(t.MessageBody,{...s,surface:"plain"}),u&&a.createElement(nE,{$marginTop:12,$paddingInline:12},a.createElement(t.CTAButton,{...s})),m&&a.createElement(t.Citation,{...s})):a.createElement(t.MessageBody,{...s})),f&&a.createElement(To,{$startPadding:0,$endPadding:0},a.createElement(t.MessageTemplate,{...s,messageTemplateErrorFallback:s.messageTemplateErrorFallback??a.createElement(nr,{$extraStartPadding:_},a.createElement(t.MessageBody,{...s,messageType:"user",message:((R=(T=s.extendedMessagePayload)==null?void 0:T.message_template)==null?void 0:R.fallback_message)??"Cannot read this template."})),messageTemplateLoadingFallback:s.messageTemplateLoadingFallback??a.createElement(nr,{$extraStartPadding:_},a.createElement(t.TypingIndicator,{...s}))})),a.createElement(t.CustomMessageTemplate,{...s}),d&&a.createElement(t.Challenge,{...s}),h&&a.createElement(To,{$extraStartPadding:_},a.createElement(t.Form,{...s}))),a.createElement(t.MessageLogs,{...s}),E&&g&&a.createElement(sE,{$extraStartPadding:_+8},a.createElement(t.SentTime,{...s})),a.createElement(l.Fragment,null,!o&&a.createElement(Zt,{$extraStartPadding:_+8},a.createElement(t.Feedback,{...s})),s.suggestedRepliesVisible&&a.createElement(t.SuggestedReplies,{...s})))},_t=je({template:Q_,components:{SenderName:Cp,SenderAvatar:_p,SentTime:vp,MessageBody:J_,TextMessageBody:hp,MediaMessageBody:Xg,FileMessageBody:Wg,MultipleFilesMessageBody:cp,TypingIndicator:Sp,SuggestedReplies:V_,MessageTemplate:z_,CustomMessageTemplate:Up,Challenge:Lp,CTAButton:Mp,Citation:Op,Form:F_,Feedback:Qp,MessageLogs:H_}}),eE=b.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
|
+
`,Zt=b.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=te.HORIZONTAL_PADDING,$endPadding:t=te.HORIZONTAL_PADDING,$extraStartPadding:n=0})=>`
|
|
326
326
|
padding-inline: ${e+n}px ${t}px;
|
|
327
327
|
`}
|
|
328
|
-
`,
|
|
328
|
+
`,tE=b.default.div.attrs({role:"presentation"})`
|
|
329
329
|
display: flex;
|
|
330
330
|
flex-direction: column;
|
|
331
331
|
min-width: 0;
|
|
@@ -333,69 +333,62 @@
|
|
|
333
333
|
border-radius: 12px;
|
|
334
334
|
overflow: hidden;
|
|
335
335
|
padding: 12px 0;
|
|
336
|
-
${({theme:e})=>
|
|
337
|
-
|
|
336
|
+
${({theme:e})=>P.css`color:${e.colors.messageIncoming.text};background-color:${e.colors.messageIncoming.background};`}
|
|
337
|
+
`,nE=b.default.div.attrs({role:"presentation"})`
|
|
338
338
|
display: flex;
|
|
339
339
|
flex-direction: column;
|
|
340
340
|
min-width: 0;
|
|
341
|
-
${({$marginTop:e=0,$paddingInline:t=0})=>
|
|
342
|
-
`,
|
|
341
|
+
${({$marginTop:e=0,$paddingInline:t=0})=>P.css`margin-top:${e}px;padding-inline:${t}px;`}
|
|
342
|
+
`,rE=b.default(Zt)`display:flex;flex-direction:row;align-items:center;gap:8px;`,nr=b.default(Zt)`display:flex;`,sE=b.default(Zt)`margin-top:${te.BODY_TIME_GAP}px;display:flex;align-items:flex-start;justify-content:flex-start;`,To=b.default(Zt).attrs({role:"presentation"})`
|
|
343
343
|
display: flex;
|
|
344
|
-
${({$startPadding:e=
|
|
344
|
+
${({$startPadding:e=te.HORIZONTAL_PADDING,$endPadding:t=te.HORIZONTAL_PADDING,$extraStartPadding:n=0})=>`
|
|
345
345
|
padding-inline: ${e+n}px ${t}px;
|
|
346
346
|
`}
|
|
347
|
-
`,
|
|
347
|
+
`,oE=b.default.div.attrs({role:"presentation"})`
|
|
348
348
|
display: flex;
|
|
349
349
|
flex-direction: column;
|
|
350
350
|
min-width: 0;
|
|
351
351
|
max-width: 100%;
|
|
352
|
-
gap: ${
|
|
353
|
-
`;function
|
|
354
|
-
background-color: ${
|
|
352
|
+
gap: ${te.GAP_GROUPED}px;
|
|
353
|
+
`;function iE({file:e,children:t,onClickFile:n,sendingStatus:r}){const s=(()=>{if(!(!n||r==="failed"))return()=>n==null?void 0:n(e)})();return a.createElement(aE,null,a.createElement(Wr,{name:e.name,mimeType:e.type,type:Ar(e.name,e.type),onClick:s}),t)}const aE=b.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${te.GAP_GROUPED}px;`;function cE({sendingStatus:e,file:t,metadata:n,onClickMedia:r,onClickMediaFiles:s,children:o}){const{conversation:i}=se(),{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(lE,null,a.createElement(uE,{...p},!m&&a.createElement(pt,{size:26},a.createElement(Q,{type:"spinner",color:"textLowEmphasis",size:26})),a.createElement(dE,{$loaded:m,src:d,alt:"image-message",onLoad:()=>h(!0)}),g.descriptionNode),o)}const lE=b.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${te.GAP_GROUPED}px;`,uE=b.default.div`width:${te.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;${ee.light`
|
|
354
|
+
background-color: ${C.color.background100};
|
|
355
355
|
`}
|
|
356
|
-
${
|
|
357
|
-
background-color: ${
|
|
356
|
+
${ee.dark`
|
|
357
|
+
background-color: ${C.color.background400};
|
|
358
358
|
`}
|
|
359
|
-
`,
|
|
359
|
+
`,dE=b.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;`,mE=({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(hE,null,a.createElement(_a,{images:i,isPending:c,onClickImage:d}),o)},hE=b.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${te.GAP_GROUPED}px;`;function fE(e){var n,r;const t=l.useMemo(()=>{const s=dp(Ca(e.message));return Go.default.sanitize(s)},[e.message]);return a.createElement(gE,{$maxWidth:e.maxBodyWidth??te.BODY_MAX_WIDTH,$color:(n=e.customStyle)==null?void 0:n.bubbleContentColor,$bgColor:(r=e.customStyle)==null?void 0:r.bubbleBackgroundColor},a.createElement(pE,{variant:"body3",dangerouslySetInnerHTML:{__html:t}}))}const gE=b.default.div`display:flex;flex-direction:column;border-radius:12px;overflow:hidden;max-width:${({$maxWidth:e})=>e}px;${({theme:e,$color:t,$bgColor:n})=>P.css`
|
|
360
360
|
color: ${t||e.colors.messageOutgoing.text};
|
|
361
361
|
background-color: ${n||e.colors.messageOutgoing.background};
|
|
362
362
|
`}
|
|
363
363
|
padding: 12px 0;
|
|
364
364
|
transition: max-width 0.3s;
|
|
365
365
|
overflow-wrap: break-word;
|
|
366
|
-
`,
|
|
367
|
-
`,
|
|
368
|
-
`,rp=p.default(Gi)``,op=p.default(Gi)`margin-top:${ee.BODY_TIME_GAP}px;`,sp=e=>e.messageType!=="admin"?null:i.createElement(ip,null,i.createElement($,{variant:"caption2",color:h.themedColor.textMidEmphasis},ap(ds.default.sanitize(e.message),e.onClickLink))),ip=p.default.div`text-align:center;text-wrap:pretty;word-break:break-word;padding-inline:${ee.HORIZONTAL_PADDING}px;a{text-decoration:underline;color:inherit;}`,ap=(e,t)=>{try{const n=[];let r=e,o=0;for(;r;){const s=r.match(/\[([^\]]+)\]\((https?:\/\/[^\s]+)\)/),a=r.match(/\*\*([^*]+)\*\*/),l=[s&&{match:s,type:"link"},a&&{match:a,type:"bold"}].filter(g=>!!g);if(!l.length){n.push(r);break}const c=l.reduce((g,E)=>E.match.index<g.match.index?E:g),{match:d,type:m}=c,f=d.index;f>0&&n.push(r.slice(0,f)),m==="link"?n.push(i.createElement("a",{key:o++,href:d[2],target:"_blank",rel:Er,onClick:g=>{g.preventDefault();const E=d[2];E&&(t==null||t({url:E}))}},d[1])):m==="bold"&&n.push(i.createElement("strong",{key:o++},d[1])),r=r.slice(f+d[0].length)}return n.filter(s=>s!=="")}catch{return[e]}},lp=({direction:e,currentIndex:t,totalCount:n})=>n<=0?t:e==="next"?(t+1)%n:(t-1+n)%n,zi=({options:e,value:t,disabled:n,hasError:r=!1,errorId:o,onChange:s})=>{const a=u.useRef([]),l=e.findIndex(f=>f.value===t),c=l>=0?l:0,d=f=>{requestAnimationFrame(()=>{var g;(g=a.current[f])==null||g.focus()})},m=f=>{const g=e[f];!g||n||(s==null||s(g.value),d(f))};return{radioGroupProps:f=>({role:"radiogroup","aria-label":f,...r&&o?{"aria-invalid":!0,"aria-errormessage":o}:{}}),getRadioProps:f=>({ref:g=>{a.current[f]=g},tabIndex:n?-1:f===c?0:-1,describedBy:r&&o?o:void 0,onArrowNavigate:g=>{m(lp({direction:g,currentIndex:f,totalCount:e.length}))}})}},cp=e=>{switch(e.key){case"ArrowDown":case"ArrowRight":return"next";case"ArrowUp":case"ArrowLeft":return"previous";default:return}},up=({event:e,onClick:t,onArrowNavigate:n})=>{if(dp(e))return;const r=cp(e);if(r){e.preventDefault(),n==null||n(r);return}e.key!=="Enter"&&e.key!==" "||(e.preventDefault(),t==null||t())},dp=e=>e.repeat||e.currentTarget.getAttribute("aria-disabled")==="true",Mr=u.forwardRef(({onClick:e,checked:t,label:n,disabled:r,tabIndex:o=0,labelVariant:s="caption2",describedBy:a,onArrowNavigate:l},c)=>{const d=t?h.themedColor.primary:r?h.themedColor.textDisabled:h.themedColor.textLowEmphasis,m=t?h.themedColor.textHighEmphasis:r?h.themedColor.textLowEmphasis:h.themedColor.textHighEmphasis;return i.createElement(gp,{ref:c,role:"radio",tabIndex:r?-1:o,"aria-checked":t,"aria-disabled":!!r,"aria-label":n,"aria-describedby":a,onClick:r?void 0:e,onKeyDown:f=>up({event:f,onClick:e,onArrowNavigate:l})},i.createElement(mp,{"aria-hidden":"true"},i.createElement(X,{size:20,type:t?"radio-on":"radio-off",color:d})),i.createElement(fp,{"aria-hidden":"true",variant:s,color:m},n))});Mr.displayName="Radio";const mp=p.default.div`width:20px;height:20px;`,fp=p.default($)`line-height:20px;word-break:break-word;`,gp=p.default.div`display:flex;align-items:flex-start;justify-content:flex-start;gap:2px;${Ae}&[aria-disabled='false']{cursor:pointer;}`,hp=({csatPayload:e,submitted:t,defaultValue:n,value:r,onChange:o})=>{var c,d;const s=[{label:((c=e.cre)==null?void 0:c.positive_label)??"",value:!0},{label:((d=e.cre)==null?void 0:d.negative_label)??"",value:!1}],a=zi({options:s,value:r,disabled:t,onChange:o});if(u.useEffect(()=>{typeof r>"u"&&typeof n=="boolean"&&(o==null||o(n))},[r,n]),!e.cre)return null;const l=e.cre;return i.createElement(pp,null,i.createElement(Ie.Label,{required:l.required,"aria-hidden":!0},l.question),i.createElement(_p,{...a.radioGroupProps(l.question)},s.map((m,f)=>i.createElement(Mr,{key:m.label,checked:r===m.value,label:m.label,disabled:t,...a.getRadioProps(f),onClick:()=>o==null?void 0:o(m.value)}))))},pp=p.default.div`display:flex;flex-direction:column;gap:8px;`,_p=p.default.div`display:flex;flex-direction:column;gap:8px;`,Ep=({followUpItem:e,submitted:t,value:n="",onChange:r,hasError:o})=>{const{stringSet:s}=se(),{conversation:a}=oe(),l=u.useId(),c=u.useId(),d=e.response_type!=="free_text",m=e.response_type==="single_choice"?e.options.map(g=>({label:g,value:g})):[],f=zi({options:m,value:n,disabled:t,hasError:o,errorId:l,onChange:r});return i.createElement(bp,null,i.createElement(Ie.Label,{id:c,required:e.required,"aria-hidden":d},e.question),e.response_type==="free_text"&&i.createElement(Ie.TextInput,{variant:"multi-line",disabled:t,submitted:t,maxLength:100,value:n,onChange:g=>r(g),error:o,...a.form.textInput(s.A11Y_CSAT_TEXT_INPUT_LABEL,e.required??!1,t,{labelId:c}).props,"aria-invalid":o,"aria-errormessage":o?l:void 0}),e.response_type==="single_choice"&&i.createElement(Cp,{...f.radioGroupProps(e.question)},m.map((g,E)=>i.createElement(Mr,{key:g.value,checked:n===g.value,label:g.label,disabled:t,...f.getRadioProps(E),onClick:()=>r==null?void 0:r(g.value),labelVariant:"body3"}))),o&&i.createElement(vp,{role:"alert",id:l},s.FORM_VALIDATION_REQUIRED))},bp=p.default.div`display:flex;flex-direction:column;gap:8px;`,Cp=p.default.div`display:flex;flex-direction:column;gap:8px;`,vp=p.default(Ie.ErrorLabel)``,yp=({value:e,selected:t})=>i.createElement(Sp,{$selected:t,"aria-hidden":"true"},Ap[e-1]),Sp=p.default.div`user-select:none;-webkit-user-drag:none;width:40px;height:40px;aspect-ratio:1;opacity:${({$selected:e})=>e?1:.38};`,Ap=[i.createElement("svg",{width:"40",height:"40",viewBox:"0 0 40 40",fill:"none",xmlns:"http://www.w3.org/2000/svg"},i.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)"}),i.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"}),i.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"}),i.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"}),i.createElement("defs",null,i.createElement("linearGradient",{id:"paint0_linear_159_173206",x1:"20",y1:"2.08325",x2:"20",y2:"37.9166",gradientUnits:"userSpaceOnUse"},i.createElement("stop",{stopColor:"#FF2D1D"}),i.createElement("stop",{offset:"1",stopColor:"#FFA540"})))),i.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},i.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"}),i.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"}),i.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"}),i.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"})),i.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},i.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"}),i.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"}),i.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"})),i.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},i.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"}),i.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"}),i.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"})),i.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"40",height:"40",viewBox:"0 0 40 40",fill:"none"},i.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"}),i.createElement("g",{clipPath:"url(#clip0_159_173224)"},i.createElement("g",{clipPath:"url(#clip1_159_173224)"},i.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"})),i.createElement("mask",{id:"mask0_159_173224",style:{maskType:"alpha"},maskUnits:"userSpaceOnUse",x:"12",y:"22",width:"16",height:"9"},i.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"})),i.createElement("g",{mask:"url(#mask0_159_173224)"},i.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"}))),i.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"}),i.createElement("defs",null,i.createElement("clipPath",{id:"clip0_159_173224"},i.createElement("rect",{width:"15.83",height:"7.915",fill:"white",transform:"translate(12.085 22.709)"})),i.createElement("clipPath",{id:"clip1_159_173224"},i.createElement("rect",{width:"15.83",height:"7.915",fill:"white",transform:"translate(12.085 22.709)"}))))],xp=({csatPayload:e,submitted:t,value:n,onChange:r})=>{const o=typeof n>"u",{conversation:s}=oe(),a=s.csat.scoresContainer(e.csat_question);return i.createElement(Ip,null,i.createElement($,{variant:"caption3",color:h.themedColor.textMidEmphasis,"aria-hidden":"true"},e.csat_question),i.createElement(wp,{...a.props},a.descriptionNode,e.csat_scores.map(({label:l,image_url:c},d)=>{const m=d+1,f=n===m,g=e.csat_scores.length,E=s.csat.scoreItem({score:m,label:l,selected:f,disabled:t,currentIndex:d,totalCount:g,hasSelection:!o,onChange:r});return i.createElement(Mp,{key:d,type:"button",...E.props},i.createElement(Tp,{value:m,selected:o||f,src:c}),!!l&&i.createElement($,{"aria-hidden":"true",color:f?h.themedColor.textHighEmphasis:h.themedColor.textLowEmphasis,variant:"caption3"},l),E.descriptionNode)})))},Tp=({value:e,src:t,selected:n})=>{const[r,o]=u.useState(!1),s=r?i.createElement(yp,{value:e,selected:n}):i.createElement(Rp,{$selected:n,alt:"","aria-hidden":"true",src:t,onError:()=>o(!0)});return i.createElement(kp,null,s)},Ip=p.default.div`display:flex;flex-direction:column;gap:8px;`,wp=p.default.div`display:flex;justify-content:space-between;align-self:center;width:100%;max-width:400px;gap:16px;`,Mp=p.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;${Ae}&:not(:disabled):hover span{color:${h.themedColor.textHighEmphasis};}`,kp=p.default.div`button:not(:disabled):hover &{border-radius:4px;cursor:pointer;background-color:${h.color.background200};${Z.dark`
|
|
369
|
-
background-color: ${
|
|
366
|
+
`,pE=b.default(H)`align-items:flex-start;line-height:140%;white-space:pre-wrap;padding:0 12px;`,_E=({sendingStatus:e})=>{const t=P.useTheme();switch(e){case"pending":return a.createElement(EE,{size:16},a.createElement(Q,{type:"spinner",color:t.colors.messageOutgoing.background,size:16}));case"failed":return a.createElement("div",{style:{marginBottom:2}},a.createElement(Q,{type:"error",color:C.themedColor.error,size:16}));case"scheduled":case"canceled":return null;default:return a.createElement("div",{style:{marginBottom:2}},a.createElement(Q,{type:"done",color:C.themedColor.secondary,size:16}))}},EE=b.default(pt)`margin-bottom:2px;width:16px;height:16px;`,CE=({createdAt:e})=>{const{stringSet:t,format:n}=ae();return e?a.createElement(H,{variant:"caption4",color:C.themedColor.textLowEmphasis},n(e,t.DATE_FORMAT__MESSAGE_TIMESTAMP)):null},bE=e=>{const{components:t}=xt.useContext(),{stringSet:n}=ae(),r=()=>{const i=Xo(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?$t({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())},vE=e=>a.createElement(a.Fragment,null),yE=e=>{const{components:t}=xt.useContext(),n=e.sendingStatus==="succeeded",r=e.groupType==="bottom"||e.groupType==="single";return a.createElement(SE,{$marginBottom:Mn(e.groupType)},a.createElement(AE,null,a.createElement(t.MessageBody,{...e})),a.createElement(t.MessageLogs,{...e}),r&&a.createElement(TE,{$extraEndPadding:8},n?a.createElement(t.SentTime,{...e}):a.createElement(t.SendingStatus,{...e})))},xt=je({template:yE,components:{SendingStatus:_E,SentTime:CE,MessageBody:bE,TextMessageBody:fE,MediaMessageBody:cE,FileMessageBody:iE,MultipleFilesMessageBody:mE,MessageLogs:vE}}),SE=b.default.div`display:flex;flex:1;flex-direction:column;align-items:flex-end;margin-bottom:${({$marginBottom:e})=>`${e}px`};
|
|
367
|
+
`,ka=b.default.div`display:flex;align-self:stretch;justify-content:flex-end;${({$startPadding:e=te.HORIZONTAL_PADDING,$endPadding:t=te.HORIZONTAL_PADDING,$extraEndPadding:n=0})=>`padding-inline: ${e}px ${t+n}px;`};
|
|
368
|
+
`,AE=b.default(ka)``,TE=b.default(ka)`margin-top:${te.BODY_TIME_GAP}px;`,IE=e=>e.messageType!=="admin"?null:a.createElement(xE,null,a.createElement(H,{variant:"caption2",color:C.themedColor.textMidEmphasis},RE(Go.default.sanitize(e.message),e.onClickLink))),xE=b.default.div`text-align:center;text-wrap:pretty;word-break:break-word;padding-inline:${te.HORIZONTAL_PADDING}px;a{text-decoration:underline;color:inherit;}`,RE=(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:Ur,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]}},ME=({direction:e,currentIndex:t,totalCount:n})=>n<=0?t:e==="next"?(t+1)%n:(t-1+n)%n,La=({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(ME({direction:f,currentIndex:h,totalCount:e.length}))}})}},wE=e=>{switch(e.key){case"ArrowDown":case"ArrowRight":return"next";case"ArrowUp":case"ArrowLeft":return"previous";default:return}},kE=({event:e,onClick:t,onArrowNavigate:n})=>{if(LE(e))return;const r=wE(e);if(r){e.preventDefault(),n==null||n(r);return}e.key!=="Enter"&&e.key!==" "||(e.preventDefault(),t==null||t())},LE=e=>e.repeat||e.currentTarget.getAttribute("aria-disabled")==="true",Xr=l.forwardRef(({onClick:e,checked:t,label:n,disabled:r,tabIndex:s=0,labelVariant:o="caption2",describedBy:i,onArrowNavigate:c},u)=>{const d=t?C.themedColor.primary:r?C.themedColor.textDisabled:C.themedColor.textLowEmphasis,m=t?C.themedColor.textHighEmphasis:r?C.themedColor.textLowEmphasis:C.themedColor.textHighEmphasis;return a.createElement(DE,{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=>kE({event:h,onClick:e,onArrowNavigate:c})},a.createElement(OE,{"aria-hidden":"true"},a.createElement(Q,{size:20,type:t?"radio-on":"radio-off",color:d})),a.createElement(NE,{"aria-hidden":"true",variant:o,color:m},n))});Xr.displayName="Radio";const OE=b.default.div`width:20px;height:20px;`,NE=b.default(H)`line-height:20px;word-break:break-word;`,DE=b.default.div`display:flex;align-items:flex-start;justify-content:flex-start;gap:2px;${Re}&[aria-disabled='false']{cursor:pointer;}`,$E=({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=La({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(FE,null,a.createElement(Le.Label,{required:c.required,"aria-hidden":!0},c.question),a.createElement(PE,{...i.radioGroupProps(c.question)},o.map((m,h)=>a.createElement(Xr,{key:m.label,checked:r===m.value,label:m.label,disabled:t,...i.getRadioProps(h),onClick:()=>s==null?void 0:s(m.value)}))))},FE=b.default.div`display:flex;flex-direction:column;gap:8px;`,PE=b.default.div`display:flex;flex-direction:column;gap:8px;`,UE=({followUpItem:e,submitted:t,value:n="",onChange:r,hasError:s})=>{const{stringSet:o}=ae(),{conversation:i}=se(),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=La({options:m,value:n,disabled:t,hasError:s,errorId:c,onChange:r});return a.createElement(BE,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(HE,{...h.radioGroupProps(e.question)},m.map((f,g)=>a.createElement(Xr,{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(GE,{role:"alert",id:c},o.FORM_VALIDATION_REQUIRED))},BE=b.default.div`display:flex;flex-direction:column;gap:8px;`,HE=b.default.div`display:flex;flex-direction:column;gap:8px;`,GE=b.default(Le.ErrorLabel)``,zE=({value:e,selected:t})=>a.createElement(VE,{$selected:t,"aria-hidden":"true"},qE[e-1]),VE=b.default.div`user-select:none;-webkit-user-drag:none;width:40px;height:40px;aspect-ratio:1;opacity:${({$selected:e})=>e?1:.38};`,qE=[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)"}))))],YE=({csatPayload:e,submitted:t,value:n,onChange:r})=>{const s=typeof n>"u",{conversation:o}=se(),i=o.csat.scoresContainer(e.csat_question);return a.createElement(KE,null,a.createElement(H,{variant:"caption3",color:C.themedColor.textMidEmphasis,"aria-hidden":"true"},e.csat_question),a.createElement(jE,{...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(XE,{key:d,type:"button",...g.props},a.createElement(WE,{value:m,selected:s||h,src:u}),!!c&&a.createElement(H,{"aria-hidden":"true",color:h?C.themedColor.textHighEmphasis:C.themedColor.textLowEmphasis,variant:"caption3"},c),g.descriptionNode)})))},WE=({value:e,src:t,selected:n})=>{const[r,s]=l.useState(!1),o=r?a.createElement(zE,{value:e,selected:n}):a.createElement(JE,{$selected:n,alt:"","aria-hidden":"true",src:t,onError:()=>s(!0)});return a.createElement(ZE,null,o)},KE=b.default.div`display:flex;flex-direction:column;gap:8px;`,jE=b.default.div`display:flex;justify-content:space-between;align-self:center;width:100%;max-width:400px;gap:16px;`,XE=b.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:${C.themedColor.textHighEmphasis};}`,ZE=b.default.div`button:not(:disabled):hover &{border-radius:4px;cursor:pointer;background-color:${C.color.background200};${ee.dark`
|
|
369
|
+
background-color: ${C.color.background500};
|
|
370
370
|
`}
|
|
371
371
|
}
|
|
372
|
-
`,
|
|
373
|
-
background-color: ${
|
|
372
|
+
`,JE=b.default.img`user-select:none;-webkit-user-drag:none;width:40px;height:40px;aspect-ratio:1;opacity:${({$selected:e})=>e?1:.38};`,QE=({csatPayload:e})=>a.createElement(H,{variant:"button",color:C.themedColor.textHighEmphasis},e.title),rr=({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}=Bd({csatPayload:e,type:t,initialCsat:r,initialCsatReason:s,initialIsResolved:o});return a.createElement(a.Fragment,null,a.createElement(eC,null,a.createElement(QE,{...g}),t===Je.AI_AGENT_CSAT_5_WITH_CRE&&a.createElement($E,{...g,defaultValue:o,value:i.isResolved,onChange:p=>c({isResolved:p})}),a.createElement(YE,{...g,value:i.csat,onChange:p=>c({csat:p})}),m&&a.createElement(UE,{...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(Le.Separator,null),n({state:h,params:i,validateParams:f})))},eC=b.default.div`display:flex;flex-direction:column;gap:12px;`,tC=e=>{const{stringSet:t}=ae();return yl(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})},nC=()=>{const{stringSet:e}=ae();return a.createElement(H,{variant:"body2",color:C.themedColor.textMidEmphasis,style:{textAlign:"center"}},e.CSAT_SUBMISSION_EXPIRED)},rC=({onMount:e,children:t})=>(l.useEffect(()=>{e&&we(e)},[]),t),sC=e=>{const{conversation:t}=se();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=kn(),m=tC(n==null?void 0:n.csat),h=l.useRef(null),f=l.useRef(null),[g,p]=l.useState(!1),v=l.useRef(!1),E=l.useCallback(()=>{we(()=>{var R;return(R=f.current)==null?void 0:R.focus()})},[]),{isExpiredNow:_,isRenderableCSAT:y}=Hd({csat:o,csatExpireAt:c,csatPayload:m,isSubmitInFlight:g});if(Pd({csat:o,csatPayload:m,isRenderableCSAT:y,isExpiredNow:_,announceStatus:e.announceStatus,onSubmittedAnnounced:E}),!y||!m)return null;const A=()=>{var L;const R=(L=h.current)==null?void 0:L.querySelector('[aria-invalid="true"]');return R?R.getAttribute("role")==="radiogroup"?R.querySelector('[role="radio"]'):R:null},T=m.type===Je.AI_AGENT_CSAT_5||m.type===Je.AI_AGENT_CSAT_5_WITH_CRE||m.type===Je.HELPDESK_CSAT_5?rr:()=>null;return a.createElement(oC,{ref:h},!o&&_?a.createElement(nC,null):a.createElement(T,{csatPayload:m,type:m.type,initialCsat:o,initialCsatReason:i,initialIsResolved:u,renderSubmitButton:({state:R,params:L,validateParams:N})=>R==="submitted"?a.createElement(aC,{ref:f,role:"status","aria-live":"polite","aria-atomic":"true","aria-label":m.csat_submitted_label,tabIndex:-1},a.createElement(H,{variant:"button","aria-hidden":"true"},m.csat_submitted_label)):a.createElement(rC,{onMount:s},a.createElement(iC,{type:"button",...t.csat.submitButton(m.csat_submit_label).props,onClick:async()=>{if(v.current)return;const x=ci(c);if(!x&&N()){v.current=!0,p(!0);try{await r(L)}catch(w){throw v.current=!1,p(!1),w}}else d(),x||we(()=>{var w;(w=e.announceError)==null||w.call(e,{type:"csatFormError"},A())})}},a.createElement(H,{variant:"button"},m.csat_submit_label)))}))},oC=b.default.div`display:flex;flex-direction:column;background-color:${({theme:e})=>e.colors.csat.background};border-radius:16px;gap:16px;padding:16px;`,iC=b.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;${Re}&:hover{background-color:${C.color.primary.dark};}`,aC=b.default.div`width:100%;box-sizing:border-box;color:${C.themedColor.textHighEmphasis};background-color:${C.color.background200};border-radius:6px;padding:10px 20px;display:flex;align-items:center;justify-content:center;text-align:center;word-break:break-word;${ee.dark`
|
|
373
|
+
background-color: ${C.color.onlight.textDisabled};
|
|
374
374
|
`}
|
|
375
|
-
`,
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
&:hover {
|
|
379
|
-
color: ${t};
|
|
380
|
-
}
|
|
381
|
-
`}
|
|
382
|
-
`,St=p.default.div`display:flex;align-items:center;justify-content:center;flex-shrink:0;`,dn=p.default.div`display:flex;gap:8px;align-items:center;word-break:break-word;`,zp=p.default(dn)`cursor:pointer;gap:4px;`,Jt=p.default(dn)`flex-direction:row;align-items:center;`,Vp=p.default(Jt)`align-items:flex-start;max-width:100%;`,Yp=p.default(Yi)`min-width:0;`,qo=p.default.div`display:flex;gap:4px;flex-direction:column;align-items:flex-start;`,Wi=u.createContext(null);function Wp({testerType:e,origin:t,children:n}){return i.createElement(Wi.Provider,{value:{testerType:e,isActionbookTester:e==="actionbook",origin:t}},e&&i.createElement(qp,null),n)}const _t=()=>{const e=u.useContext(Wi);if(!e)throw new Error("_UNSAFE_INTERNAL_DashboardTesterProvider not found");return e},qp=()=>{const{isActionbookTester:e}=_t();return i.createElement(rt.Template,{template:e?Kp:void 0},i.createElement(rt.MessageLogs,{component:jp}))},Kp=e=>i.createElement(Hi,{...e,testerMode:!0,maxBodyWidth:ee.WIDE_BODY_MAX_WIDTH}),jp=({extendedMessagePayload:e={}})=>{const{handlers:t}=ae(),{manual:n,groundedness:r,function_calls:o,agent_message_templates:s,flagged_types:a,is_thinking:l}=e;return l||!n&&!(r!=null&&r.length)&&!(o!=null&&o.length)&&!(s!=null&&s.length)&&!(a!=null&&a.length)?i.createElement(i.Fragment,null):i.createElement(Xp,null,i.createElement(Zp,{$width:4}),i.createElement(Vi,{actionbook:n,functionCalls:o,groundedness:r,agentMessageTemplates:s,flaggedTypes:a,onClickFunctionCallDetail:t==null?void 0:t.onFunctionCallDetailClick,style:{iconColor:h.themedColor.textHighEmphasis,textColor:h.themedColor.textHighEmphasis,barColor:h.themedColor.textDisabled},topContent:i.createElement($,{variant:"caption4",color:h.themedColor.textLowEmphasis},"Only visible in the tester")}))},Xp=p.default.div`display:flex;gap:16px;margin:6px ${ee.HORIZONTAL_PADDING}px 4px ${ee.HORIZONTAL_PADDING+ee.AVATAR_SIZE}px;align-self:stretch;`,Zp=p.default.div`width:${({$width:e})=>e}px;background-color:${h.themedColor.textDisabled};border-radius:100px;flex-shrink:0;`,Ko=40,jo=.9,Jp="[data-message-listitem]",Qp='input, textarea, select, [role="textbox"], [contenteditable="true"]',e_=({event:e,list:t,isMessageAnchor:n})=>{switch(e.key){case"PageDown":return t.clientHeight*jo;case"PageUp":return t.clientHeight*-jo;case"ArrowDown":return n?Ko:void 0;case"ArrowUp":return n?Ko*-1:void 0;default:return}},t_=({listRef:e,syncScrollPosition:t})=>u.useCallback(n=>{const r=e.current;if(!r||n.defaultPrevented||n.metaKey||n.altKey||n.ctrlKey)return;const o=n.target;if(!o||!r.contains(o)||o.closest(Qp))return;const s=o===r||o.matches(Jp),a=e_({event:n,list:r,isMessageAnchor:s});if(a==null||a===0)return;const l=Math.max(0,r.scrollHeight-r.clientHeight),c=Math.min(l,Math.max(0,r.scrollTop+a));c!==r.scrollTop&&(n.preventDefault(),t(c))},[e,t]),n_="[data-message-listitem]",r_=e=>Math.min(Math.max(0,e),1),o_=e=>{const n=e.getRootNode().activeElement,r=n==null?void 0:n.closest(n_),o=n===e||n===r;return!n||!e.contains(n)?null:o?e:n},s_=({list:e,focusRestoreTarget:t})=>{if(!t)return;const r=e.getRootNode().activeElement,o=r===e||e.contains(r),s=t===e||e.contains(t);o&&s&&t.focus({preventScroll:!0})},i_=({depsForResetScrollPositionToBottom:e,listRef:t,loadThreshold:n,messagesLength:r,onLoadNext:o,onLoadPrev:s,onScroll:a})=>{const l=u.useRef(!1),c=u.useRef(void 0),d=u.useRef(0),m=u.useRef(0),f=u.useRef(null),g=u.useRef(null),E=u.useRef(null);u.useLayoutEffect(()=>{t.current&&(t.current.scrollTop=t.current.scrollHeight)},e),u.useLayoutEffect(()=>{const _=t.current;_&&(c.current==="top"&&(_.scrollTop=_.scrollHeight-m.current,s_({list:_,focusRestoreTarget:f.current}),f.current=null),c.current==="bottom"&&(_.scrollTop=d.current),c.current=void 0)},[t,r]);const y=u.useCallback(async _=>{const C=t.current;if(!C||(a==null||a(_),m.current=C.scrollHeight-C.scrollTop,d.current=C.scrollTop,l.current))return;const x=C.clientHeight*r_(n);if(C.scrollTop<=x){l.current=!0,c.current="top",f.current=o_(C),await s(),l.current=!1;return}if(C.scrollHeight-C.scrollTop-C.clientHeight<=x){l.current=!0,c.current="bottom",await o(),l.current=!1;return}c.current=void 0},[t,n,o,s,a]),v=u.useCallback(_=>{const C=t.current;if(!C)return;const x=E.current;if(x!=null){if(x===C.scrollTop){E.current=null;return}E.current=null}const A=g.current;if(A!=null&&A===C.scrollTop){g.current=null,E.current=C.scrollTop,y(_);return}g.current=null,y(_)},[y,t]),b=u.useCallback(_=>{const C=t.current;C&&(g.current=_,E.current=null,C.scrollTop=_,C.dispatchEvent(new Event("scroll",{bubbles:!0})))},[t]);return u.useLayoutEffect(()=>()=>{g.current=null,E.current=null},[]),{handleScroll:v,syncScrollPosition:b}},a_=u.forwardRef(function(t,n){const{messages:r,renderMessage:o,loading:s,LoadingComponent:a,error:l,ErrorComponent:c,empty:d,EmptyComponent:m,messageTopArea:f,messageBottomArea:g,overlayArea:E,onLoadPrev:y,onLoadNext:v,loadThreshold:b=.05,onScroll:_=ce,depsForResetScrollPositionToBottom:C,stackDirection:x="top",bottomSpacerHeight:A=0,"aria-label":w}=t,M=u.useRef(null),k=u.useCallback(Y=>{M.current=Y,n&&(typeof n=="function"?n(Y):n.current=Y)},[n]),{handleScroll:R,syncScrollPosition:O}=i_({depsForResetScrollPositionToBottom:C,listRef:M,loadThreshold:b,messagesLength:r.length,onLoadNext:v,onLoadPrev:y,onScroll:_}),z=t_({listRef:M,syncScrollPosition:O});return l?i.createElement(i.Fragment,null,c):s?i.createElement(i.Fragment,null,a):i.createElement(l_,{id:"infinite-list-container"},i.createElement(c_,{id:"infinite-list-inner",ref:k,onScroll:R,onKeyDown:z,role:"list","aria-label":w,tabIndex:0},x==="bottom"&&i.createElement("div",{style:{flexGrow:1}}),f,d?m:r.map((Y,P)=>o({message:Y,index:P})),g,A>0&&i.createElement("div",{style:{minHeight:A}})),i.createElement(u_,{id:"infinite-list-overlay-container"},i.createElement(d_,{id:"infinite-list-overlay"},E)))}),l_=p.default.div`display:flex;position:relative;flex:1;overflow:hidden;`,c_=p.default.div`display:flex;flex:1;flex-direction:column;overflow-x:hidden;overflow-y:auto;overscroll-behavior:contain;scrollbar-color:${h.themedColor.textLowEmphasis}transparent;&::-webkit-scrollbar-thumb:hover{background-color:transparent;}`,u_=p.default.div`position:absolute;top:0;bottom:0;left:0;right:0;pointer-events:none;`,d_=p.default.div`pointer-events:auto;`,Ze=({as:e,type:t,size:n=16,color:r,disabled:o,children:s,...a})=>{const l=o?h.themedColor.textDisabled:h.themedColor.textHighEmphasis;return i.createElement(m_,{as:e,disabled:o,...a},i.createElement(X,{type:t,size:n,color:r??l}),s)},m_=p.default.button`all:unset;padding:4px;cursor:pointer;display:flex;align-items:center;justify-content:center;${Ae}&:disabled{cursor:not-allowed;}`,f_=({files:e,initialIndex:t=0,onClose:n,visible:r})=>{const[o,s]=u.useState(t),[a,l]=u.useState(!1),{stringSet:c,format:d}=se(),{config:m}=ae(),f=e.length,g=e[o],E=m.conversation.fileViewer.downloadEnabled,y=f>1,v=(g==null?void 0:g.type)||"",b=ze(v),_=mn(v),C=!Wm(v);u.useEffect(()=>{r&&(s(t),l(!1))},[r,t]);const x=u.useCallback(()=>{o>0&&(s(w=>w-1),l(!1))},[o]),A=u.useCallback(()=>{o<f-1&&(s(w=>w+1),l(!1))},[o,f]);return u.useEffect(()=>{if(!r)return;const w=M=>{M.key==="ArrowLeft"?x():M.key==="ArrowRight"&&A()};return window.addEventListener("keydown",w),()=>window.removeEventListener("keydown",w)},[r,x,A]),!r||!g?null:i.createElement(ot,{onClose:n,visible:r,portalContainerId:be.MODAL_ROOT,"aria-label":(g==null?void 0:g.name)||c.IMAGE_VIEWER__DEFAULT_TITLE},i.createElement(g_,null,i.createElement(h_,null,i.createElement(p_,null,i.createElement(__,null,i.createElement($,{variant:"button",maxTextLines:1,color:h.color.ondark.textHighEmphasis},g.name||c.IMAGE_VIEWER__DEFAULT_TITLE),g.timestamp&&i.createElement($,{variant:"caption2",color:h.color.ondark.textHighEmphasis},d(new Date(g.timestamp),"h:mm a")))),i.createElement(E_,{type:"close",size:18,color:h.color.ondark.textHighEmphasis,"aria-label":c.A11Y_IMAGE_VIEWER_CLOSE,onClick:n})),i.createElement(b_,null,y&&i.createElement(Xo,{$position:"left",type:"chevron-right",size:22,color:h.color.ondark.textHighEmphasis,onClick:x,"aria-label":c.A11Y_IMAGE_VIEWER_PREVIOUS,disabled:o===0,$flipped:!0}),i.createElement(C_,{onClick:w=>w.currentTarget===w.target&&n()},b&&i.createElement(i.Fragment,null,!a&&i.createElement(v_,null,i.createElement(at,{size:32},i.createElement(X,{type:"spinner",color:"textLowEmphasis",size:32}))),i.createElement(y_,{src:g.url,alt:g.name||"Image",$loaded:a,onLoad:()=>l(!0)})),_&&i.createElement(S_,{controls:!0},i.createElement("source",{src:g.url,type:v})),C&&i.createElement(A_,null,i.createElement($,{variant:"h1",color:h.themedColor.textHighEmphasis},c.FILE_VIEWER__UNSUPPORT))),y&&i.createElement(Xo,{$position:"right",type:"chevron-right",size:22,color:h.color.ondark.textHighEmphasis,onClick:A,"aria-label":c.A11Y_IMAGE_VIEWER_NEXT,disabled:o===f-1})),i.createElement(x_,null,y&&i.createElement($,{variant:"body2",color:h.color.ondark.textHighEmphasis},o+1,"/",f),E&&!C&&i.createElement(T_,{forwardedAs:"a",href:g.url,download:g.name||"file",type:"download",size:24,color:h.color.ondark.textHighEmphasis,"aria-label":c.A11Y_IMAGE_VIEWER_DOWNLOAD}))))},g_=p.default.div`position:fixed;top:0;left:0;right:0;bottom:0;height:100dvh;outline:none;display:flex;flex-direction:column;background-color:${h.themedColor.bg_50_600};`,h_=p.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:${h.color.overlay.dark};`,p_=p.default.div`flex:1;min-width:0;padding-right:8px;`,__=p.default.div`display:flex;flex-direction:column;gap:2px;`,E_=p.default(Ze)`flex-shrink:0;width:28px;height:28px;border-radius:50%;`,vn=p.default.div`display:flex;align-items:center;justify-content:center;`,b_=p.default(vn)`flex:1;min-height:0;position:relative;`,C_=p.default(vn)`position:relative;width:100%;height:100%;min-width:0;min-height:0;`,v_=p.default(vn)`position:absolute;inset:0;pointer-events:none;`,y_=p.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;`,S_=p.default.video`max-width:100%;max-height:100%;object-fit:contain;`,A_=p.default(vn)`flex-direction:column;gap:16px;`,Xo=p.default(Ze)`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:${h.color.overlay.dark};&:disabled{opacity:0.3;}`,x_=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:${h.color.overlay.dark};`,T_=p.default(Ze)`position:absolute;right:16px;top:50%;transform:translateY(-50%);padding:0;width:24px;height:24px;`,kr=({title:e,titleId:t,description:n,descriptionId:r,negativeText:o,positiveText:s,onCancel:a,onConfirm:l,buttonLayout:c="horizontal",styles:d})=>{const m=o!==void 0&&a!==void 0,f=s!==void 0&&l!==void 0,g=m?i.createElement(R_,{type:"button",onClick:a,$fullWidth:c!=="horizontal",$background:d==null?void 0:d.negativeBackground,$borderColor:d==null?void 0:d.negativeBorderColor},i.createElement($,{variant:"button",color:(d==null?void 0:d.negativeText)??h.themedColor.textHighEmphasis},o)):null,E=f?i.createElement(L_,{type:"button",onClick:l,$fullWidth:c!=="horizontal",$background:d==null?void 0:d.positiveBackground,$borderColor:d==null?void 0:d.positiveBorderColor},i.createElement($,{variant:"button",color:(d==null?void 0:d.positiveText)??h.themedColor.textHighEmphasisInverse},s)):null;return i.createElement(I_,null,i.createElement(w_,null,i.createElement($,{as:"div",id:t,variant:"h2",color:(d==null?void 0:d.titleColor)??h.themedColor.textHighEmphasis},e)),i.createElement(M_,null,i.createElement($,{as:"div",id:r,variant:"body3",color:(d==null?void 0:d.descriptionColor)??h.themedColor.textMidEmphasis},n)),i.createElement(k_,{$buttonLayout:c},c==="horizontal"?i.createElement(i.Fragment,null,g,E):i.createElement(i.Fragment,null,E,g)))},I_=p.default.div`display:flex;flex-direction:column;width:280px;border-radius:16px;overflow:hidden;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,w_=p.default.div`padding:24px 24px 16px;`,M_=p.default.div`padding-inline:24px;`,k_=p.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;`,R_=p.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;}`,L_=p.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??h.themedColor.textHighEmphasis};white-space:nowrap;overflow:hidden;text-overflow:ellipsis;&:hover{opacity:0.8;}`,jt=16,O_=({status:e})=>e===tn.COMPLETED?i.createElement(X,{type:"done-circle",size:jt,color:h.themedColor.textHighEmphasis}):e===tn.CANCELED?i.createElement(X,{type:"stop-circle",size:jt,color:h.themedColor.textLowEmphasis}):i.createElement(at,{size:jt},i.createElement(X,{type:"spinner",size:jt,color:h.themedColor.textHighEmphasis})),qi=24,N_=8,D_=40,$_=({task:e,isFirst:t,isLast:n})=>i.createElement(P_,{role:"listitem"},i.createElement(F_,null,i.createElement(Zo,{$hidden:t}),i.createElement(U_,null,i.createElement(O_,{status:e.status})),i.createElement(Zo,{$hidden:n})),i.createElement(B_,null,i.createElement($,{as:"div",variant:"body3",color:e.status===tn.CANCELED?h.themedColor.textLowEmphasis:h.themedColor.textHighEmphasis},e.user_facing_title))),P_=p.default.div`display:flex;gap:4px;`,F_=p.default.div`display:flex;flex-direction:column;align-items:center;width:${qi}px;flex-shrink:0;`,Zo=p.default.div`width:1px;flex:1;transform:translateX(-25%);${({$hidden:e})=>e&&"visibility: hidden;"}background-image:repeating-linear-gradient( to bottom,${h.themedColor.textHighEmphasis}0 2px,transparent 2px 4px );`,U_=p.default.div`display:flex;height:${qi}px;align-items:center;justify-content:center;`,B_=p.default.div`display:flex;flex:1;align-items:center;box-sizing:border-box;min-width:0;min-height:${D_}px;padding-block:${N_}px;`,H_=({steward:e,onCancelSteward:t})=>{const{logger:n}=ae(),[r,o]=u.useState(!1),[s,a]=u.useState(!1),l=!!e.cancellation_option,c=Sa(e.status);return i.createElement(G_,{$marginBottom:fn("single")},i.createElement(z_,null,i.createElement(V_,null,i.createElement(Y_,null,i.createElement($,{as:"div",variant:"caption1",color:h.themedColor.textHighEmphasis},e.title),!!e.description&&i.createElement($,{as:"div",variant:"caption4",color:h.themedColor.textLowEmphasis},e.description)),l&&i.createElement(j_,{type:"button","aria-label":"Stop steward",disabled:s,onClick:()=>o(!0)},i.createElement(X,{type:"stop",size:16,color:s?h.themedColor.textDisabled:h.themedColor.textHighEmphasis}))),i.createElement(W_,null),e.tasks.length===0?c!==It.IN_PROGRESS?null:i.createElement(K_,null,i.createElement(at,{size:16},i.createElement(X,{type:"spinner",size:16,color:h.themedColor.textHighEmphasis}))):i.createElement(q_,{role:"list"},e.tasks.map((d,m)=>i.createElement($_,{key:d.id,task:d,isFirst:m===0,isLast:m===e.tasks.length-1})))),r&&e.cancellation_option&&i.createElement(ot,{portalContainerId:be.WINDOW,visible:r,onClose:()=>o(!1)},i.createElement(kr,{title:e.cancellation_option.title,description:e.cancellation_option.description,negativeText:e.cancellation_option.negative_text,positiveText:e.cancellation_option.positive_text,onCancel:()=>o(!1),onConfirm:async()=>{o(!1),a(!0);try{await(t==null?void 0:t())}catch(d){n.warn("steward.cancelSteward: failed",d)}finally{a(!1)}}})))},G_=p.default.div`display:flex;flex-direction:column;margin:0 ${ee.HORIZONTAL_PADDING}px;margin-bottom:${({$marginBottom:e})=>`${e}px`};
|
|
383
|
-
`,z_=p.default.div`display:flex;flex-direction:column;border-radius:12px;overflow:hidden;padding:16px;border:1px solid ${h.themedColor.bg_300_500};background-color:${h.themedColor.bg_50_600};box-shadow:0 8px 20px rgba(0,0,0,0.12);`,V_=p.default.div`display:flex;flex-direction:row;align-items:flex-start;gap:8px;`,Y_=p.default.div`display:flex;flex-direction:column;gap:4px;flex:1;min-width:0;`,W_=p.default.div`height:1px;margin-block:12px;background-color:${h.themedColor.bg_200_400};`,q_=p.default.div`display:flex;flex-direction:column;`,K_=p.default.div`display:flex;width:100%;height:40px;align-items:center;justify-content:center;`,j_=p.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:${h.themedColor.textHighEmphasis};background-color:${h.themedColor.bg_200_400};&:hover:not(:disabled){opacity:0.8;}&:disabled{cursor:default;}`,X_=({className:e,label:t,onClick:n})=>{const{colors:r}=D.useTheme(),{conversation:o}=oe(),s={newMessages:o.newMessagesButton()};return i.createElement(Z_,{className:e,onClick:n,...s.newMessages.props},i.createElement($,{variant:"button",color:r.base.primaryContrastContent},t),i.createElement(X,{size:16,type:"chevron-down",color:r.base.primaryContrastContent}),s.newMessages.descriptionNode)},Z_=p.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;}${Ae}`,Rr=({iconSize:e=64,icon:t,className:n,label:r,children:o})=>i.createElement(Q_,{className:n},t&&i.createElement(X,{type:t,size:e,color:h.themedColor.textLowEmphasis}),r&&i.createElement($,{variant:"body1",color:h.themedColor.textMidEmphasis},r),o),J_=p.default.div`position:relative;display:flex;justify-content:center;align-items:center;width:100%;height:100%;`,Q_=p.default.div`display:flex;flex-direction:column;min-height:104px;align-items:center;gap:20px;text-align:center;`,eE=({label:e="Something went wrong",icon:t="error",action:n,...r})=>i.createElement(Rr,{icon:t,label:e,...r},n&&i.createElement(tE,{onClick:n.onClick,label:n.label??"Retry"})),tE=({label:e,onClick:t})=>{const{conversation:n}=oe();return i.createElement(nE,{tabIndex:0,...n.retryButton(e).props,onClick:t},i.createElement(X,{type:"refresh",size:20}),i.createElement($,{variant:"button",color:h.color.primary.main},e))},nE=p.default.button`all:unset;display:flex;cursor:pointer;gap:4px;align-items:center;justify-content:center;${Ae}`,rE=({iconSize:e=48,className:t})=>i.createElement(at,{size:e,className:t}),oE=({label:e="No channels",icon:t="chat",...n})=>i.createElement(Rr,{icon:t,label:e,...n}),sE=({label:e="No messages",icon:t="message",...n})=>i.createElement(Rr,{icon:t,label:e,...n}),iE=e=>{const{components:t}=yn.useContext(),n=e.type==="loading"?i.createElement(t.Loading,{...e}):e.type==="error"?i.createElement(t.Error,{...e}):e.type==="noChannels"?i.createElement(t.NoChannels,{...e}):e.type==="noMessages"?i.createElement(t.NoMessages,{...e}):null;return n&&i.createElement(J_,null,n)},yn=Ge({template:iE,components:{Loading:rE,Error:eE,NoChannels:oE,NoMessages:sE}}),wt=e=>{const{Template:t}=yn.useContext();return i.createElement(t,{...e})},aE=[0,150,450];function lE({enabled:e}){const{state:t,actions:n}=_i(),r=u.useRef(0),o=u.useRef(t.isAwayFromBottom);o.current=t.isAwayFromBottom,u.useEffect(()=>{if(!e){r.current+=1;return}const s=r.current+1;r.current=s;const a=aE.map(l=>setTimeout(()=>{Me(()=>{r.current===s&&(o.current||n.scrollToBottom(!1))})},l));return()=>{r.current+=1,a.forEach(l=>clearTimeout(l))}},[n.scrollToBottom,e])}const cE=({className:e,date:t=Date.now(),role:n,style:r})=>{const{format:o,stringSet:s}=se();return i.createElement(uE,{id:`${$e}-date-separator`,role:n,style:r,className:e},i.createElement($,{variant:"caption4",color:h.themedColor.textMidEmphasis},o(t,s.DATE_FORMAT__MESSAGE_LIST__DATE_SEPARATOR)))},uE=p.default.div`display:flex;justify-content:center;align-items:center;text-align:center;word-break:break-word;`,dE=({className:e,style:t,onClick:n})=>{const{conversation:r}=oe(),o={scrollToBottom:r.scrollToBottomButton()};return i.createElement(mE,{className:e,style:t,onClick:n,tabIndex:0,...o.scrollToBottom.props},i.createElement(X,{size:24,type:"chevron-down",color:h.color.primary.main}),o.scrollToBottom.descriptionNode??null)},mE=p.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);${Z.light`
|
|
384
|
-
background-color: ${h.color.background50};
|
|
375
|
+
`,cC=e=>{const{components:t}=Pn.useContext(),n=e.messageType==="admin"?a.createElement(t.AdminMessage,{...e}):e.messageType==="admin.csat"?a.createElement(t.CSATMessage,{...e}):null;return a.createElement(lC,{$marginBottom:Mn(e.groupType)},n)},Pn=je({template:cC,components:{AdminMessage:IE,CSATMessage:sC}}),lC=b.default.div`padding-inline:${te.HORIZONTAL_PADDING}px;margin-bottom:${({$marginBottom:e})=>e}px;`,Zr=({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(fC,{type:"button",onClick:i,$fullWidth:u!=="horizontal",$background:d==null?void 0:d.negativeBackground,$borderColor:d==null?void 0:d.negativeBorderColor},a.createElement(H,{variant:"button",color:(d==null?void 0:d.negativeText)??C.themedColor.textHighEmphasis},s)):null,g=h?a.createElement(gC,{type:"button",onClick:c,$fullWidth:u!=="horizontal",$background:d==null?void 0:d.positiveBackground,$borderColor:d==null?void 0:d.positiveBorderColor},a.createElement(H,{variant:"button",color:(d==null?void 0:d.positiveText)??C.themedColor.textHighEmphasisInverse},o)):null;return a.createElement(uC,null,a.createElement(dC,null,a.createElement(H,{as:"div",id:t,variant:"h2",color:(d==null?void 0:d.titleColor)??C.themedColor.textHighEmphasis},e)),a.createElement(mC,null,a.createElement(H,{as:"div",id:r,variant:"body3",color:(d==null?void 0:d.descriptionColor)??C.themedColor.textMidEmphasis},n)),a.createElement(hC,{$buttonLayout:u},u==="horizontal"?a.createElement(a.Fragment,null,f,g):a.createElement(a.Fragment,null,g,f)))},uC=b.default.div`display:flex;flex-direction:column;width:280px;border-radius:16px;overflow:hidden;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,dC=b.default.div`padding:24px 24px 16px;`,mC=b.default.div`padding-inline:24px;`,hC=b.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;`,fC=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:${({$background:e})=>e??"none"};white-space:nowrap;overflow:hidden;text-overflow:ellipsis;&:hover{opacity:0.8;}`,gC=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??C.themedColor.textHighEmphasis};white-space:nowrap;overflow:hidden;text-overflow:ellipsis;&:hover{opacity:0.8;}`,un=16,pC=({status:e})=>e===_n.COMPLETED?a.createElement(Q,{type:"done-circle",size:un,color:C.themedColor.textHighEmphasis}):e===_n.CANCELED?a.createElement(Q,{type:"stop-circle",size:un,color:C.themedColor.textLowEmphasis}):a.createElement(pt,{size:un},a.createElement(Q,{type:"spinner",size:un,color:C.themedColor.textHighEmphasis})),Oa=24,_C=8,EC=40,CC=({task:e,isFirst:t,isLast:n})=>a.createElement(bC,{role:"listitem"},a.createElement(vC,null,a.createElement(Io,{$hidden:t}),a.createElement(yC,null,a.createElement(pC,{status:e.status})),a.createElement(Io,{$hidden:n})),a.createElement(SC,null,a.createElement(H,{as:"div",variant:"body3",color:e.status===_n.CANCELED?C.themedColor.textLowEmphasis:C.themedColor.textHighEmphasis},e.user_facing_title))),bC=b.default.div`display:flex;gap:4px;`,vC=b.default.div`display:flex;flex-direction:column;align-items:center;width:${Oa}px;flex-shrink:0;`,Io=b.default.div`width:1px;flex:1;transform:translateX(-25%);${({$hidden:e})=>e&&"visibility: hidden;"}background-image:repeating-linear-gradient( to bottom,${C.themedColor.textHighEmphasis}0 2px,transparent 2px 4px );`,yC=b.default.div`display:flex;height:${Oa}px;align-items:center;justify-content:center;`,SC=b.default.div`display:flex;flex:1;align-items:center;box-sizing:border-box;min-width:0;min-height:${EC}px;padding-block:${_C}px;`,AC=({steward:e,onCancelSteward:t})=>{const{logger:n}=ce(),[r,s]=l.useState(!1),[o,i]=l.useState(!1),c=!!e.cancellation_option,u=Ec(e.status);return a.createElement(TC,{$marginBottom:Mn("single")},a.createElement(IC,null,a.createElement(xC,null,a.createElement(RC,null,a.createElement(H,{as:"div",variant:"caption1",color:C.themedColor.textHighEmphasis},e.title),!!e.description&&a.createElement(H,{as:"div",variant:"caption4",color:C.themedColor.textLowEmphasis},e.description)),c&&a.createElement(LC,{type:"button","aria-label":"Stop steward",disabled:o,onClick:()=>s(!0)},a.createElement(Q,{type:"stop",size:16,color:o?C.themedColor.textDisabled:C.themedColor.textHighEmphasis}))),a.createElement(MC,null),e.tasks.length===0?u!==Pt.IN_PROGRESS?null:a.createElement(kC,null,a.createElement(pt,{size:16},a.createElement(Q,{type:"spinner",size:16,color:C.themedColor.textHighEmphasis}))):a.createElement(wC,{role:"list"},e.tasks.map((d,m)=>a.createElement(CC,{key:d.id,task:d,isFirst:m===0,isLast:m===e.tasks.length-1})))),r&&e.cancellation_option&&a.createElement(ut,{portalContainerId:ve.WINDOW,visible:r,onClose:()=>s(!1)},a.createElement(Zr,{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)}}})))},TC=b.default.div`display:flex;flex-direction:column;margin:0 ${te.HORIZONTAL_PADDING}px;margin-bottom:${({$marginBottom:e})=>`${e}px`};
|
|
376
|
+
`,IC=b.default.div`display:flex;flex-direction:column;border-radius:12px;overflow:hidden;padding:16px;border:1px solid ${C.themedColor.bg_300_500};background-color:${C.themedColor.bg_50_600};box-shadow:0 8px 20px rgba(0,0,0,0.12);`,xC=b.default.div`display:flex;flex-direction:row;align-items:flex-start;gap:8px;`,RC=b.default.div`display:flex;flex-direction:column;gap:4px;flex:1;min-width:0;`,MC=b.default.div`height:1px;margin-block:12px;background-color:${C.themedColor.bg_200_400};`,wC=b.default.div`display:flex;flex-direction:column;`,kC=b.default.div`display:flex;width:100%;height:40px;align-items:center;justify-content:center;`,LC=b.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:${C.themedColor.textHighEmphasis};background-color:${C.themedColor.bg_200_400};&:hover:not(:disabled){opacity:0.8;}&:disabled{cursor:default;}`,OC=({className:e,label:t,onClick:n})=>{const{colors:r}=P.useTheme(),{conversation:s}=se(),o={newMessages:s.newMessagesButton()};return a.createElement(NC,{className:e,onClick:n,...o.newMessages.props},a.createElement(H,{variant:"button",color:r.base.primaryContrastContent},t),a.createElement(Q,{size:16,type:"chevron-down",color:r.base.primaryContrastContent}),o.newMessages.descriptionNode)},NC=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;}${Re}`,Jr=({iconSize:e=64,icon:t,className:n,label:r,children:s})=>a.createElement($C,{className:n},t&&a.createElement(Q,{type:t,size:e,color:C.themedColor.textLowEmphasis}),r&&a.createElement(H,{variant:"body1",color:C.themedColor.textMidEmphasis},r),s),DC=b.default.div`position:relative;display:flex;justify-content:center;align-items:center;width:100%;height:100%;`,$C=b.default.div`display:flex;flex-direction:column;min-height:104px;align-items:center;gap:20px;text-align:center;`,FC=({label:e="Something went wrong",icon:t="error",action:n,...r})=>a.createElement(Jr,{icon:t,label:e,...r},n&&a.createElement(PC,{onClick:n.onClick,label:n.label??"Retry"})),PC=({label:e,onClick:t})=>{const{conversation:n}=se();return a.createElement(UC,{tabIndex:0,...n.retryButton(e).props,onClick:t},a.createElement(Q,{type:"refresh",size:20}),a.createElement(H,{variant:"button",color:C.color.primary.main},e))},UC=b.default.button`all:unset;display:flex;cursor:pointer;gap:4px;align-items:center;justify-content:center;${Re}`,BC=({iconSize:e=48,className:t})=>a.createElement(pt,{size:e,className:t}),HC=({label:e="No channels",icon:t="chat",...n})=>a.createElement(Jr,{icon:t,label:e,...n}),GC=({label:e="No messages",icon:t="message",...n})=>a.createElement(Jr,{icon:t,label:e,...n}),zC=e=>{const{components:t}=Un.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(DC,null,n)},Un=je({template:zC,components:{Loading:BC,Error:FC,NoChannels:HC,NoMessages:GC}}),Ut=e=>{const{Template:t}=Un.useContext();return a.createElement(t,{...e})},VC=[0,150,450];function qC({enabled:e}){const{state:t,actions:n}=ia(),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=VC.map(c=>setTimeout(()=>{we(()=>{r.current===o&&(s.current||n.scrollToBottom(!1))})},c));return()=>{r.current+=1,i.forEach(c=>clearTimeout(c))}},[n.scrollToBottom,e])}const YC=({className:e,date:t=Date.now(),role:n,style:r})=>{const{format:s,stringSet:o}=ae();return a.createElement(WC,{id:`${Ge}-date-separator`,role:n,style:r,className:e},a.createElement(H,{variant:"caption4",color:C.themedColor.textMidEmphasis},s(t,o.DATE_FORMAT__MESSAGE_LIST__DATE_SEPARATOR)))},WC=b.default.div`display:flex;justify-content:center;align-items:center;text-align:center;word-break:break-word;`,KC=({className:e,style:t,onClick:n})=>{const{conversation:r}=se(),s={scrollToBottom:r.scrollToBottomButton()};return a.createElement(jC,{className:e,style:t,onClick:n,tabIndex:0,...s.scrollToBottom.props},a.createElement(Q,{size:24,type:"chevron-down",color:C.color.primary.main}),s.scrollToBottom.descriptionNode??null)},jC=b.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);${ee.light`
|
|
377
|
+
background-color: ${C.color.background50};
|
|
385
378
|
&:hover {
|
|
386
|
-
background-color: ${
|
|
379
|
+
background-color: ${C.color.background100};
|
|
387
380
|
}
|
|
388
381
|
&:active {
|
|
389
|
-
background-color: ${
|
|
382
|
+
background-color: ${C.color.background200};
|
|
390
383
|
}
|
|
391
384
|
`}
|
|
392
|
-
${
|
|
393
|
-
background-color: ${
|
|
385
|
+
${ee.dark`
|
|
386
|
+
background-color: ${C.color.background400};
|
|
394
387
|
&:hover {
|
|
395
|
-
background-color: ${
|
|
388
|
+
background-color: ${C.color.background500};
|
|
396
389
|
}
|
|
397
390
|
&:active {
|
|
398
|
-
background-color: ${
|
|
391
|
+
background-color: ${C.color.background700};
|
|
399
392
|
}
|
|
400
393
|
`}
|
|
401
394
|
|
|
@@ -403,38 +396,45 @@
|
|
|
403
396
|
outline: none;
|
|
404
397
|
}
|
|
405
398
|
|
|
406
|
-
${
|
|
407
|
-
`,
|
|
408
|
-
background-color: ${
|
|
409
|
-
border-color: ${
|
|
399
|
+
${Re}
|
|
400
|
+
`,XC=()=>null,Bn=je({template:XC,components:{DateSeparator:YC,ScrollToBottomButton:KC}}),ZC=()=>{const{stringSet:e,format:t}=ae(),{agentPreviewConfigs:n={},aiAgentId:r}=ce(),{aiAgentInfo:s}=Ne(),{messageSource:o}=Te(),{Template:i}=_t.useContext(),{components:c}=Bn.useContext(),u=n.welcomeMessages??[],d=o.messages,m=Uf(d,r),h=d[m.length+1],f=m[0]??h;return{filteredMessages:ma(d,{previewWelcomeMessages:u,aiAgentUserId:r}),shouldShowOriginalDate:g=>g>0||u.length===0?!0:h&&!ot.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,E=m.length!==d.length,_=u.length===1?"single":p===0?"top":v||E?"bottom":"middle",y=(f==null?void 0:f.createdAt)??Date.now();return a.createElement("div",{key:p,role:"listitem",tabIndex:-1,"aria-label":Dt({sender:(s==null?void 0:s.nickname)||"",message:g.message,messageFormat:"markdown",time:t(y,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:_,createdAt:y,extendedMessagePayload:{suggested_replies:g.suggestedReplies},suggestedRepliesDirection:n.suggestedRepliesDirection,suggestedRepliesVisible:v&&!E,isBotMessage:!0,onClickSuggestedReply:async({reply:A})=>{o.sendUserMessage({message:A})}}))}))}},JC=()=>{const{messageSource:e,scrollSource:t}=Te();l.useEffect(()=>{!t.state.isAwayFromBottom&&t.state.isScrollPositionReconciled&&e.resetNewMessages()},[t.state.isAwayFromBottom,t.state.isScrollPositionReconciled])},xo="https://delight.ai?utm_medium=product&utm_source=aiagent&utm_campaign=fy26-glbl-ai-agent-poweredby",QC=({style:e})=>{const{stringSet:t}=ae(),{handlers:n}=ce(),{conversation:r}=se();return Dr("powered-by")?a.createElement(eb,{variant:"caption2",style:e},t.POWERED_BY+" ",a.createElement(tb,{variant:"caption2",forwardedAs:"a",href:xo,...r.poweredByLink().props,rel:Ur,target:"_blank",onClick:o=>{o.preventDefault(),n.onClickLink({url:xo})}},"Sendbird")):null},eb=b.default(H)`color:${C.themedColor.textLowEmphasis};text-align:center;`,tb=b.default(H)`color:${C.themedColor.textLowEmphasis};cursor:pointer;text-decoration:none;`,nb=()=>{var c;const{stringSet:e}=ae(),{conversation:t}=se(),{channelSource:n,goToActiveConversation:r,scrollSource:s}=Te(),o=Be(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(rb,null,a.createElement(sb,{variant:"button",color:C.themedColor.textHighEmphasis,...t.startNewConversationButton({onActivate:r}).props},e.TALK_TO_AGENT))},rb=b.default.div`display:flex;justify-content:center;margin-bottom:16px;`,sb=b.default(H)`border-radius:6px;box-sizing:border-box;padding:10px 20px;cursor:pointer;user-select:none;background-color:${C.color.background50};border:1px solid ${C.color.onlight.textDisabled};${ee.dark`
|
|
401
|
+
background-color: ${C.color.background700};
|
|
402
|
+
border-color: ${C.color.ondark.textLowEmphasis};
|
|
410
403
|
`}
|
|
411
|
-
`,yE=()=>{var J;const{Template:e}=Pt.useContext(),{Template:t}=rt.useContext(),{Template:n}=Cn.useContext(),{components:r}=Sn.useContext(),{stringSet:o,format:s}=se(),{announceError:a,announceStatus:l}=Xe(),{file:c}=oe().conversation,{config:d,cache:m,agentPreviewConfigs:f,chatSDK:g,handlers:E,state:y}=ae(),{userSession:v,aiAgentInfo:b,connectionError:_}=ke(),{conversation:C,channelSource:x,messageSource:A,scrollSource:w,state:{input:M,streamAnimation:k}}=Se(),{isActionbookTester:R}=_t(),{filteredMessages:O,shouldShowOriginalDate:z,renderAgentPreviewWelcomeMessages:Y}=gE(),P=$s(x.channel),[V,B]=u.useState(null),[W,q]=u.useState(null);u.useEffect(()=>{w.actions.onTypingIndicatorUpdate(!!P)},[!!P,w.actions.onTypingIndicatorUpdate]),hE(),lE({enabled:A.initialized&&A.messages.length>0});const ie=(T,F=!1)=>{var Q;return F?b:((Q=x.channel)==null?void 0:Q.members.find(re=>re.userId===T.sender.userId))??T.sender},_e=T=>{if(T.sendingStatus==="failed"&&!M.disabled)return()=>q(T)},Le=({message:T,index:F})=>{const Q=Aa(T),re=O[F-1],le=O[F+1],Oe=O[O.length-1],De=T===Oe,xe=gt(T,b.userId),I=!(b.isUserFeedbackEnabled&&xe&&!We.isWelcomeMessage(T)),L=xa(T,re,le,I),N=!ba.isSameDay((re==null?void 0:re.createdAt)??0,T.createdAt)&&z(F)&&!R,K=te=>{B({files:te.files.map(ve=>({...ve,timestamp:T.createdAt})),index:te.index})},G=te=>{K({files:[te],index:0})},H=N?i.createElement(r.DateSeparator,{role:"listitem",style:{margin:"16px 0"},date:T.createdAt}):null,U={data:T.data,maxBodyWidth:y.expanded?ee.WIDE_BODY_MAX_WIDTH:void 0,extendedMessagePayload:T.extendedMessagePayload,createdAt:T.createdAt,groupType:L,onClickMedia:G,onClickMediaFiles:K,onClickFile:E.onClickLink,onClickCTA:E.onClickLink,onClickCitation:te=>E.onClickLink({url:te.link}),onClickLink:E.onClickLink},de=()=>{if(we.isOutgoing(T,v.userId))return"outgoingmessage";if(we.isIncoming(T,v.userId))return"incomingmessage"},Pe=T.createdAt!=null&&T.createdAt!==0?s(T.createdAt,o.DATE_FORMAT__MESSAGE_TIMESTAMP):void 0,ne=(()=>{var ve,ge,j,he,Te,Ut;const te=(ve=T.message)==null?void 0:ve.trim();if(T.isFileMessage()){const Bt=((ge=T.name)==null?void 0:ge.trim())||"";return Rn({markdownText:te,comparisonText:Bt,plainText:c.label(Bt,T.type)})}if(T.isMultipleFilesMessage()){const Bt=((Te=(he=(j=T.fileInfoList)==null?void 0:j[0])==null?void 0:he.fileName)==null?void 0:Te.trim())||"",Hr=((Ut=T.fileInfoList)==null?void 0:Ut.length)??0;return Rn({markdownText:te,comparisonText:Bt,plainText:Hr>0?o.CONVERSATION_LIST__MULTIPLE_FILES_COUNT(Hr):""})}return te?Rn({markdownText:te}):Gs("")})(),fe=(()=>{if(we.isAdmin(T))return At({message:ne.text,messageFormat:ne.format,codeBlockPlaceholder:o.A11Y_CODE_BLOCK_PLACEHOLDER});if(we.isOutgoing(T,v.userId))return At({sender:o.A11Y_MESSAGE_SENDER_YOU,message:ne.text,messageFormat:"plain",time:Pe,codeBlockPlaceholder:o.A11Y_CODE_BLOCK_PLACEHOLDER});if(we.isIncoming(T,v.userId))return At({sender:ie(T,xe).nickname,message:ne.text,messageFormat:ne.format,time:Pe,codeBlockPlaceholder:o.A11Y_CODE_BLOCK_PLACEHOLDER})})(),me=(()=>{var te,ve;if(we.isAdmin(T))return we.isCSAT(T)?C?i.createElement(n,{...U,...C,isResolvedWhenDeterminedByUser:rl(C),messageType:"admin.csat",announceError:a,announceStatus:l,onSubmitCSAT:async ge=>{var j;await((j=x.channel)==null?void 0:j.submitCSAT(ge))},onScrollToBottom:()=>w.actions.scrollToBottom()}):null:i.createElement(n,{...U,messageType:"admin",message:T.message});if(we.isSteward(T))return i.createElement(H_,{steward:T.extendedMessagePayload.steward,onCancelSteward:async()=>{await g.aiAgent.cancelStewardTask({channelUrl:T.channelUrl,messageId:T.messageId})}});if(we.isOutgoing(T,v.userId)){const ge={...U,message:T.message,sender:ie(T),sendingStatus:T.sendingStatus,onClickFailedMessage:_e(T)};if(T.isUserMessage())return i.createElement(e,{messageType:"user",...ge});if(T.isFileMessage()){const[j,he]=((te=T.metaArrays.find(Te=>Te.key===ms))==null?void 0:te.value)??[];return i.createElement(e,{messageType:"file",file:T,metadata:{aspectRatio:j&&he?`${j}/${he}`:"1/1",localFile:(ve=T.messageParams)==null?void 0:ve.file},...ge})}if(T.isMultipleFilesMessage()){const{files:j,metadata:he}=$o(T);return i.createElement(e,{messageType:"multipleFiles",files:j,metadata:he,...ge})}}if(we.isIncoming(T,v.userId)){const ge={...U,sender:ie(T,xe),message:T.message,suggestedRepliesVisible:De,suggestedRepliesDirection:f==null?void 0:f.suggestedRepliesDirection,isBotMessage:xe,isStreaming:We.isStreaming(T),isHandedOff:nt(x.channel),isConversationClosed:Ne(x.channel),isFeedbackEnabled:b.isUserFeedbackEnabled,isFeedbackCommentEnabled:b.isUserFeedbackCommentOptionEnabled,isSenderAvatarVisible:d.conversation.list.senderAvatarEnabled,deferredMarkdownElements:d.conversation.list.deferredMarkdownElements,onClickSuggestedReply:async({reply:j})=>{A.sendUserMessage({message:j})},onRequestMessageTemplate:async j=>{const{template:he}=await g.aiAgent.getMessageTemplate(j);return m.template.set(j,he),he},onGetCachedMessageTemplate:j=>m.template.get(j),onHandleTemplateInternalAction:j=>{if(j.type==="internal"&&j.internalData){const{method:he,payload:Te}=j.internalData;he==="message.send"&&(Te!=null&&Te.message)&&A.sendUserMessage({message:Te.message})}},onFeedbackUpdate:j=>{const he={messageId:T.messageId,channelUrl:T.channelUrl};if(!j)return g.aiAgent.deleteMessageFeedback(he);const Te={...he,rating:vg(j.rating),comment:j.comment};return We.hasFeedback(T)?g.aiAgent.updateMessageFeedback(Te):g.aiAgent.createMessageFeedback(Te)},onSubmitForm:({key:j,data:he})=>g.aiAgent.submitForm({messageId:T.messageId,channelUrl:T.channelUrl,formKey:j,formData:he}),onCancelForm:({key:j})=>g.aiAgent.cancelForm({messageId:T.messageId,channelUrl:T.channelUrl,formKey:j}),onSendChallengeAction:({key:j,requestId:he,action:Te,data:Ut})=>g.aiAgent.sendChallengeAction({channelUrl:T.channelUrl,key:j,requestId:he,action:Te,data:Ut}),onStreamAnimationStart:()=>{k.start(T.messageId)},onStreamAnimationProgress:()=>{w.actions.onStreamingUpdate(!0)},onStreamAnimationComplete:()=>{k.stop(T.messageId),w.actions.onStreamingUpdate(!1)}};if(T.isUserMessage())return i.createElement(t,{messageType:"user",...ge});if(T.isFileMessage())return i.createElement(t,{messageType:"file",file:T,...ge});if(T.isMultipleFilesMessage()){const{files:j}=$o(T);return i.createElement(t,{messageType:"multipleFiles",files:j,...ge})}}})();return i.createElement(u.Fragment,{key:Q},H,i.createElement("div",{id:`${$e}-message-item`,role:"listitem",tabIndex:-1,"aria-label":fe,"data-message-listitem":"","data-layout-id":de()},me))};return i.createElement(SE,{id:`${$e}-message-list`},i.createElement(a_,{ref:w.ref,onScroll:w.props.onScroll,stackDirection:f==null?void 0:f.messageStackDirection,messages:O,renderMessage:Le,onLoadPrev:A.loadPrevious,onLoadNext:A.loadNext,depsForResetScrollPositionToBottom:[A.initialized,A.messages.length!==0],bottomSpacerHeight:w.state.bottomSpace,"aria-label":o.A11Y_MESSAGE_LIST,loading:!A.initialized||!x.channel,empty:O.length===0&&!P,error:!!(_||x.error),LoadingComponent:i.createElement(wt,{type:"loading"}),EmptyComponent:(()=>{const T=Y();return T?i.createElement("div",{style:{width:"100%"}},T):i.createElement(wt,{type:"noMessages",label:o.PLACE_HOLDER__NO_MESSAGES})})(),ErrorComponent:i.createElement(wt,{type:"error",label:(_==null?void 0:_.message)??((J=x.error)==null?void 0:J.message),action:x.error?{label:o.RETRY,onClick:()=>x.refetch()}:void 0}),messageTopArea:i.createElement(i.Fragment,null,i.createElement(pE,{style:{marginTop:16}}),Y()),messageBottomArea:i.createElement(i.Fragment,null,P&&i.createElement("div",{id:`${$e}-message-item`,role:"listitem",tabIndex:-1,"aria-label":At({sender:P.user.nickname,message:o.A11Y_TYPING_INDICATOR,codeBlockPlaceholder:o.A11Y_CODE_BLOCK_PLACEHOLDER}),"data-message-listitem":"",style:{marginTop:O.length===0?8:0}},i.createElement(t,{isTyping:!0,isBotMessage:P.isBot,sender:P.user,thinkingMessage:P.thinkingMessage,messageType:"user",groupType:"single",message:"",isSenderAvatarVisible:d.conversation.list.senderAvatarEnabled})),d.conversation.list.isTalkToAgentViewEnabled&&i.createElement(bE,null)),overlayArea:i.createElement(i.Fragment,null,d.conversation.list.newMessageIndicatorEnabled&&w.state.isAwayFromBottom&&A.newMessages.length>0&&i.createElement(AE,{label:o.SCROLL_TO_NEW_MESSAGES_LABEL(A.newMessages),onClick:()=>w.actions.scrollToBottom()}),w.state.isAwayFromBottom&&A.newMessages.length===0&&!P&&i.createElement(r.ScrollToBottomButton,{onClick:()=>w.actions.scrollToBottom(),style:{position:"absolute",bottom:12,insetInlineEnd:16}}))}),V&&i.createElement(f_,{files:V.files,initialIndex:V.index,onClose:()=>B(null),visible:!0}),W&&i.createElement(et,{visible:!0,onClose:()=>q(null),"aria-label":o.A11Y_FAILED_MESSAGE_OPTIONS},i.createElement(et.ActionItem,{onClick:()=>{A.resendMessage(W),q(null)}},o.FAILED_MESSAGE_RESEND),i.createElement(et.ActionItem,{destructive:!0,onClick:()=>{A.deleteMessage(W),q(null)}},o.FAILED_MESSAGE_REMOVE)))},SE=p.default.div`overflow-y:hidden;display:flex;flex:1;position:relative;`,AE=p.default(X_)`position:absolute;bottom:12px;left:50%;transform:translateX(-50%);`,xE=()=>i.createElement(yE,null),TE=()=>{var o;const{origin:e}=_t(),{appId:t,aiAgentId:n}=Re(),{channelSource:r}=Se();return(o=r.channel)!=null&&o.conversation?i.createElement(IE,null,i.createElement(er,{style:{gap:4}},i.createElement(X,{color:h.themedColor.textLowEmphasis,size:12,type:"show"}),i.createElement($,{as:"i",color:h.themedColor.textLowEmphasis,variant:"caption2"},"Only visible in the tester")),i.createElement(er,{role:"button",style:{gap:4},onClick:()=>{var c,d;const s=e??window.location.origin,a=(d=(c=r.channel)==null?void 0:c.conversation)==null?void 0:d.id,l=`${s}/ai-agent/${t}/${n}/evaluate/conversations/${a}`;navigator.clipboard.writeText(l)}},i.createElement($,{variant:"body3",color:h.themedColor.textHighEmphasis},"Copy ",i.createElement("span",{style:{color:h.themedColor.primary}},"conversation link")),i.createElement(X,{color:h.themedColor.primary,size:14,type:"copy"}))):null},er=p.default.div`display:flex;justify-content:center;align-items:center;`,IE=p.default(er)`flex-direction:column;padding-block:16px;background-color:${h.themedColor.bg_100_500};gap:8px;`,wE=(e,t)=>{const n=[],r=[],o=[];for(const s of e){const a=t.isSupportedMimeType(s.type),l=s.size<=t.getUploadSizeLimit(s.type);a&&l?n.push(s):a?r.push(s):o.push(s)}return{passed:n,failedBySize:r,failedByType:o}},Ki=u.createContext(void 0),ME=({children:e})=>{var P,V;const{chatSDK:t}=ae(),{createAttachmentRules:n}=ke(),{stringSet:r}=se(),{channelSource:o,state:s}=Se(),[a,l]=u.useState([]),{announceError:c}=vr(),[d,m]=u.useState(null),f=n({channel:o.channel,uploadSizeLimit:(P=t.appInfo)==null?void 0:P.uploadSizeLimit}),g=((V=s==null?void 0:s.input)==null?void 0:V.disabled)??!1,E=f.isEnabled(),y=f.maxAttachmentCount,v=()=>m(null),b=B=>m(B),_=()=>{b({title:r.FILE_UPLOAD_NOTIFICATION__COUNT_LIMIT.replace("%d",y.toString())})},C=B=>{b({title:r.FILE_UPLOAD_NOTIFICATION__SIZE_LIMIT.replace("%d",B.toString())}),c({type:"fileSizeExceeded",maxSizeMB:B})},x=B=>{b({title:r.FILE_UPLOAD_NOTIFICATION__FILES_EXCLUDED_BY_VALIDATION.replace("%d",B.toString())})},A=B=>B.map(W=>({file:W,preview:{url:URL.createObjectURL(W),type:W.type,name:W.name}})),w=B=>{l(W=>[...W,...A(B)])},M=B=>{l(W=>(W.forEach(q=>URL.revokeObjectURL(q.preview.url)),A(B)))},k=B=>{const{passed:W,failedBySize:q,failedByType:ie}=wE(B,f),_e=q.length+ie.length,Le=B.length===1?q[0]:void 0;return Le?C(f.getUploadSizeLimitInMB(Le.type)):_e>0&&x(_e),W},R=B=>{const W=k(B.files);W.length!==0&&(B.type==="append"?w(W):M(W))},O=B=>{if(!E||g||!Rl(B))return;const W=Ol({currentFiles:a.map(({file:q})=>q),incomingFiles:B,maxAttachmentCount:y});switch(W.type){case"reject":_();return;case"confirm_replace":b({title:r.FILE_UPLOAD_REPLACE_ALERT__TITLE,description:r.FILE_UPLOAD_REPLACE_ALERT__DESCRIPTION,confirmText:r.BUTTON__OK,cancelText:r.BUTTON__CANCEL,onConfirm:()=>R(W.action)});return;case"apply":R(W.action);return}},z=B=>{l(W=>{var ie;const q=(ie=W[B])==null?void 0:ie.preview;return q&&URL.revokeObjectURL(q.url),W.filter((_e,Le)=>Le!==B)})},Y=()=>{l(B=>(B.forEach(W=>URL.revokeObjectURL(W.preview.url)),[]))};return i.createElement(Ki.Provider,{value:{files:a,addFiles:O,removeFile:z,clearFiles:Y,isFileUploadEnabled:E,acceptableMimeTypes:f.supportedMimeTypes,maxAttachmentCount:f.maxAttachmentCount,showFileUploadAlert:b}},e,i.createElement(En,{visible:!!d,...d??{},onClose:v}))},Lr=()=>{const e=u.useContext(Ki);if(!e)throw new Error("useFileUpload must be used within FileUploadProvider");return e};function kE({elementRef:e,ready:t,onRestore:n}){const r=u.useRef(!1);u.useEffect(()=>{var a;!t||!r.current||(n==null||n(),(a=e.current)==null||a.focus(),r.current=!1)},[t,n]);const o=u.useCallback(()=>{r.current=!0},[]),s=u.useCallback(()=>{r.current=!1},[]);return{requestRestore:o,cancelRestore:s}}function RE({blurred:e,elementRef:t,document:n=window.document,onRecoverFocus:r}){const o=u.useRef(!1);e&&t.current&&n.activeElement===t.current&&(o.current=!0),u.useLayoutEffect(()=>{var s;!e&&o.current&&(r==null||r(),(s=t.current)==null||s.focus(),o.current=!1)},[e,r])}const LE=()=>{const{announceError:e}=Xe();return u.useCallback(t=>{e({type:"sendFailed"},t)},[e])},OE=1e3,NE=(e,t,n)=>{const{announcementsEnabled:r,setIsSuppressed:o}=Xe(),s=n??!0,a=u.useRef(!1),l=u.useRef(void 0),c=u.useCallback(d=>{var m;d&&s&&(a.current=!0,l.current=e,e==null||e.startTyping()),d||(a.current&&s&&((m=l.current)==null||m.endTyping()),a.current=!1,l.current=void 0),o(d)},[e,o,s]);u.useLayoutEffect(()=>{o(a.current)},[r,o]),Xc(t,c,{enabled:s,idleMs:OE})},DE=({enabled:e=!0,focusRoot:t})=>{const[n,r]=u.useState(!1),o=u.useRef(!1),s=u.useRef(!1);u.useEffect(()=>{if(!e){r(!1);return}const d=f=>{const g=f;g.metaKey||g.altKey||g.ctrlKey||(o.current=!0)},m=()=>{o.current=!1,r(!1)};return t.addEventListener("keydown",d),t.addEventListener("pointerdown",m),()=>{t.removeEventListener("keydown",d),t.removeEventListener("pointerdown",m)}},[e,t]);const a=u.useCallback(()=>{if(s.current){s.current=!1,r(!1);return}r(o.current)},[]),l=u.useCallback(()=>{r(!1)},[]),c=u.useCallback(()=>{s.current=!0,r(!1)},[]);return{isFocusVisible:n,suppressNextFocusVisible:c,focusHandlers:{onFocus:a,onBlur:l}}},$E=p.default.div`&::-webkit-scrollbar{display:none;}overflow-x:auto;display:flex;flex-direction:row;gap:10px;padding:8px 16px;background-color:transparent;`,PE=p.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;}`,FE=p.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;${Z.light`
|
|
412
|
-
|
|
404
|
+
`,ob=({statsCallbacks:e,...t})=>(Jd(e),a.createElement(AC,{...t})),ib=(e,t,n)=>t&&Me.isWelcomeMessage(e,n)&&Me.isWelcomeMessage(t,n)?!1:!ac.isSameDay((t==null?void 0:t.createdAt)??0,e.createdAt),ab=()=>{var V;const{Template:e}=xt.useContext(),{Template:t}=_t.useContext(),{Template:n}=Pn.useContext(),{components:r}=Bn.useContext(),{stringSet:s,format:o}=ae(),{announceError:i,announceStatus:c}=rt(),{file:u}=se().conversation,{config:d,cache:m,agentPreviewConfigs:h,chatSDK:f,handlers:g,state:p}=ce(),{userSession:v,aiAgentInfo:E,connectionError:_}=Ne(),{conversationStatsEnabled:y=!0,conversation:A,channelSource:T,messageSource:R,scrollSource:L,state:{input:N,streamAnimation:x}}=Te(),{filteredMessages:w,shouldShowOriginalDate:Y,renderAgentPreviewWelcomeMessages:O}=ZC(),Z=Si(T.channel),G=Zd({enabled:y}),[D,z]=l.useState(null),[q,ne]=l.useState(null);l.useEffect(()=>{L.actions.onTypingIndicatorUpdate(!!Z)},[!!Z,L.actions.onTypingIndicatorUpdate]),JC(),qC({enabled:R.initialized&&R.messages.length>0});const ue=(I,W=!1)=>{var re;return W?E:((re=T.channel)==null?void 0:re.members.find(oe=>oe.userId===I.sender.userId))??I.sender},Ie=I=>{if(I.sendingStatus==="failed"&&!N.disabled)return()=>ne(I)},B=({message:I,index:W})=>{const re=Cc(I),oe=w[W-1],De=w[W+1],He=w[w.length-1],$=I===He,M=mt(I,E.userId),k=!(E.isUserFeedbackEnabled&&M&&!Me.isWelcomeMessage(I)),F=bc(I,oe,De,k),j=ib(I,oe,E.userId)&&Y(W),K=_e=>{z({files:_e.files.map(xe=>({...xe,timestamp:I.createdAt})),index:_e.index})},X=_e=>{K({files:[_e],index:0})},U=j?a.createElement(r.DateSeparator,{role:"listitem",style:{margin:"16px 0"},date:I.createdAt}):null,J={data:I.data,maxBodyWidth:p.expanded?te.WIDE_BODY_MAX_WIDTH:void 0,extendedMessagePayload:I.extendedMessagePayload,createdAt:I.createdAt,groupType:F,onClickMedia:X,onClickMediaFiles:K,onClickFile:g.onClickLink,onClickCTA:g.onClickLink,onClickCitation:_e=>g.onClickLink({url:_e.link}),onClickLink:g.onClickLink},ye=()=>{if(Oe.isOutgoing(I,v.userId))return"outgoingmessage";if(Oe.isIncoming(I,v.userId))return"incomingmessage"},ie=I.createdAt!=null&&I.createdAt!==0?o(I.createdAt,s.DATE_FORMAT__MESSAGE_TIMESTAMP):void 0,de=(()=>{var xe,be,$e,Fe,me,Pe;const _e=(xe=I.message)==null?void 0:xe.trim();if(I.isFileMessage()){const Ue=((be=I.name)==null?void 0:be.trim())||"";return Xn({markdownText:_e,comparisonText:Ue,plainText:u.label(Ue,I.type)})}if(I.isMultipleFilesMessage()){const Ue=((me=(Fe=($e=I.fileInfoList)==null?void 0:$e[0])==null?void 0:Fe.fileName)==null?void 0:me.trim())||"",en=((Pe=I.fileInfoList)==null?void 0:Pe.length)??0;return Xn({markdownText:_e,comparisonText:Ue,plainText:en>0?s.CONVERSATION_LIST__MULTIPLE_FILES_COUNT(en):""})}return _e?Xn({markdownText:_e}):wi("")})(),ge=(()=>{if(Oe.isAdmin(I))return Dt({message:de.text,messageFormat:de.format,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER});if(Oe.isOutgoing(I,v.userId))return Dt({sender:s.A11Y_MESSAGE_SENDER_YOU,message:de.text,messageFormat:"plain",time:ie,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER});if(Oe.isIncoming(I,v.userId))return Dt({sender:ue(I,M).nickname,message:de.text,messageFormat:de.format,time:ie,codeBlockPlaceholder:s.A11Y_CODE_BLOCK_PLACEHOLDER})})(),pe=(()=>{var _e,xe;if(Oe.isAdmin(I))return Oe.isCSAT(I)?A?a.createElement(n,{...J,...A,isResolvedWhenDeterminedByUser:bl(A),messageType:"admin.csat",announceError:i,announceStatus:c,onSubmitCSAT:async be=>{var $e;await(($e=T.channel)==null?void 0:$e.submitCSAT(be))},onScrollToBottom:()=>L.actions.scrollToBottom()}):null:a.createElement(n,{...J,messageType:"admin",message:I.message});if(Oe.isSteward(I)){const be=G({message:I,isBotMessage:M,aiAgentUserId:E.userId});return a.createElement(ob,{steward:I.extendedMessagePayload.steward,statsCallbacks:be,onCancelSteward:async()=>{await f.aiAgent.cancelStewardTask({channelUrl:I.channelUrl,messageId:I.messageId})}})}if(Oe.isOutgoing(I,v.userId)){const be={...J,message:I.message,sender:ue(I),sendingStatus:I.sendingStatus,onClickFailedMessage:Ie(I)};if(I.isUserMessage())return a.createElement(e,{messageType:"user",...be});if(I.isFileMessage()){const[$e,Fe]=((_e=I.metaArrays.find(me=>me.key===Yo))==null?void 0:_e.value)??[];return a.createElement(e,{messageType:"file",file:I,metadata:{aspectRatio:$e&&Fe?`${$e}/${Fe}`:"1/1",localFile:(xe=I.messageParams)==null?void 0:xe.file},...be})}if(I.isMultipleFilesMessage()){const{files:$e,metadata:Fe}=_o(I);return a.createElement(e,{messageType:"multipleFiles",files:$e,metadata:Fe,...be})}}if(Oe.isIncoming(I,v.userId)){const be=Me.isStreaming(I),$e=G({message:I,isBotMessage:M,aiAgentUserId:E.userId}),Fe={...J,statsCallbacks:$e,sender:ue(I,M),message:I.message,suggestedRepliesVisible:$,suggestedRepliesDirection:h==null?void 0:h.suggestedRepliesDirection,isBotMessage:M,isStreaming:be,isHandedOff:ct(T.channel),isConversationClosed:Be(T.channel),isFeedbackEnabled:E.isUserFeedbackEnabled,isFeedbackCommentEnabled:E.isUserFeedbackCommentOptionEnabled,isSenderAvatarVisible:d.conversation.list.senderAvatarEnabled,deferredMarkdownElements:d.conversation.list.deferredMarkdownElements,onClickSuggestedReply:async({reply:me})=>{R.sendUserMessage({message:me})},onRequestMessageTemplate:async me=>{const{template:Pe}=await f.aiAgent.getMessageTemplate(me);return m.template.set(me,Pe),Pe},onGetCachedMessageTemplate:me=>m.template.get(me),onHandleTemplateInternalAction:me=>{if(me.type==="internal"&&me.internalData){const{method:Pe,payload:Ue}=me.internalData;Pe==="message.send"&&(Ue!=null&&Ue.message)&&R.sendUserMessage({message:Ue.message})}},onFeedbackUpdate:me=>{const Pe={messageId:I.messageId,channelUrl:I.channelUrl};if(!me)return f.aiAgent.deleteMessageFeedback(Pe);const Ue={...Pe,rating:Bp(me.rating),comment:me.comment};return Me.hasFeedback(I)?f.aiAgent.updateMessageFeedback(Ue):f.aiAgent.createMessageFeedback(Ue)},onSubmitForm:({key:me,data:Pe})=>f.aiAgent.submitForm({messageId:I.messageId,channelUrl:I.channelUrl,formKey:me,formData:Pe}),onCancelForm:({key:me})=>f.aiAgent.cancelForm({messageId:I.messageId,channelUrl:I.channelUrl,formKey:me}),onSendChallengeAction:({key:me,requestId:Pe,action:Ue,data:en})=>f.aiAgent.sendChallengeAction({channelUrl:I.channelUrl,key:me,requestId:Pe,action:Ue,data:en}),onStreamAnimationStart:()=>{x.start(I.messageId)},onStreamAnimationProgress:()=>{L.actions.onStreamingUpdate(!0)},onStreamAnimationComplete:()=>{x.stop(I.messageId),L.actions.onStreamingUpdate(!1)}};if(I.isUserMessage())return a.createElement(t,{messageType:"user",...Fe});if(I.isFileMessage())return a.createElement(t,{messageType:"file",file:I,...Fe});if(I.isMultipleFilesMessage()){const{files:me}=_o(I);return a.createElement(t,{messageType:"multipleFiles",files:me,...Fe})}}})();return a.createElement(l.Fragment,{key:re},U,a.createElement("div",{id:`${Ge}-message-item`,role:"listitem",tabIndex:-1,"aria-label":ge,"data-message-listitem":"","data-layout-id":ye()},pe))};return a.createElement(cb,{id:`${Ge}-message-list`},a.createElement(fg,{ref:L.ref,onScroll:L.props.onScroll,stackDirection:h==null?void 0:h.messageStackDirection,messages:w,renderMessage:B,onLoadPrev:R.loadPrevious,onLoadNext:R.loadNext,depsForResetScrollPositionToBottom:[R.initialized,R.messages.length!==0],bottomSpacerHeight:L.state.bottomSpace,"aria-label":s.A11Y_MESSAGE_LIST,loading:!R.initialized||!T.channel,empty:w.length===0&&!Z,error:!!(_||T.error),LoadingComponent:a.createElement(Ut,{type:"loading"}),EmptyComponent:(()=>{const I=O();return I?a.createElement("div",{style:{width:"100%"}},I):a.createElement(Ut,{type:"noMessages",label:s.PLACE_HOLDER__NO_MESSAGES})})(),ErrorComponent:a.createElement(Ut,{type:"error",label:(_==null?void 0:_.message)??((V=T.error)==null?void 0:V.message),action:T.error?{label:s.RETRY,onClick:()=>T.refetch()}:void 0}),messageTopArea:a.createElement(a.Fragment,null,a.createElement(QC,{style:{marginTop:16}}),O()),messageBottomArea:a.createElement(a.Fragment,null,Z&&a.createElement("div",{id:`${Ge}-message-item`,role:"listitem",tabIndex:-1,"aria-label":Dt({sender:Z.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:Z.isBot,sender:Z.user,thinkingMessage:Z.thinkingMessage,messageType:"user",groupType:"single",message:"",isSenderAvatarVisible:d.conversation.list.senderAvatarEnabled})),d.conversation.list.isTalkToAgentViewEnabled&&a.createElement(nb,null)),overlayArea:a.createElement(a.Fragment,null,d.conversation.list.newMessageIndicatorEnabled&&L.state.isAwayFromBottom&&R.newMessages.length>0&&a.createElement(lb,{label:s.SCROLL_TO_NEW_MESSAGES_LABEL(R.newMessages),onClick:()=>L.actions.scrollToBottom()}),L.state.isAwayFromBottom&&R.newMessages.length===0&&!Z&&a.createElement(r.ScrollToBottomButton,{onClick:()=>L.actions.scrollToBottom(),style:{position:"absolute",bottom:12,insetInlineEnd:16}}))}),D&&a.createElement(vg,{files:D.files,initialIndex:D.index,onClose:()=>z(null),visible:!0}),q&&a.createElement(at,{visible:!0,onClose:()=>ne(null),"aria-label":s.A11Y_FAILED_MESSAGE_OPTIONS},a.createElement(at.ActionItem,{onClick:()=>{R.resendMessage(q),ne(null)}},s.FAILED_MESSAGE_RESEND),a.createElement(at.ActionItem,{destructive:!0,onClick:()=>{R.deleteMessage(q),ne(null)}},s.FAILED_MESSAGE_REMOVE)))},cb=b.default.div`overflow-y:hidden;display:flex;flex:1;position:relative;`,lb=b.default(OC)`position:absolute;bottom:12px;left:50%;transform:translateX(-50%);`,ub=()=>a.createElement(ab,null),Ro={file:"attach",snippet:"snippet",site:"website",sb_sprinklr:"sprinklr",sb_salesforce:"salesforce",sb_confluence:"confluence",sb_zendesk:"zendesk",sb_desk:"snippet"},Na=({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:E=Bt.DEFAULT_PRIMARY}=g;return a.createElement(Mo,null,m,e&&a.createElement(Mo,null,a.createElement(xn,null,a.createElement(Ot,null,a.createElement(Q,{size:16,type:"actionbook",color:p})),a.createElement(dn,{$clickable:!!o,$highlightColor:E,variant:"body2",color:v,onClick:()=>o==null?void 0:o(e),maxTextLines:1},e.name))),t==null?void 0:t.map(_=>a.createElement(fn,{key:_.key},a.createElement(Ot,null,a.createElement(Q,{size:16,type:"function",color:p})),a.createElement(xn,null,a.createElement(dn,{$clickable:!!i,$highlightColor:E,variant:"body2",color:v,onClick:()=>i==null?void 0:i(_),maxTextLines:1},_.name),c&&a.createElement(db,{role:"button",onClick:()=>c==null?void 0:c(_)},a.createElement(H,{variant:"body2",color:E},"View details"),a.createElement(Q,{type:"chevron-right",size:16,color:E}))))),n==null?void 0:n.map(_=>a.createElement(fn,{key:_.id},a.createElement(Ot,null,f({default:a.createElement(Q,{size:16,type:Ro[_.source_type]??Ro.snippet,color:p}),sourceType:_.source_type})),a.createElement(dn,{$clickable:!!u,$highlightColor:E,variant:"body2",color:v,onClick:()=>u==null?void 0:u(_),maxTextLines:1},_.preview_title))),r==null?void 0:r.map(_=>a.createElement(fn,{key:_.key},a.createElement(Ot,null,a.createElement(Q,{size:16,type:"template",color:p})),a.createElement(dn,{$clickable:!!d,$highlightColor:E,variant:"body2",color:v,onClick:()=>d==null?void 0:d(_),maxTextLines:1},_.name))),!!(s!=null&&s.length)&&a.createElement(mb,null,a.createElement(Ot,null,a.createElement(Q,{size:16,type:"activity",color:p})),a.createElement(hb,{variant:"body2",color:v},s.map(_=>_.replace(/_/g," ")).join(" · "))),h)},Da=b.default(H)`font-weight:400;`,dn=b.default(Da)`${({$clickable:e,$highlightColor:t})=>e&&P.css`
|
|
405
|
+
cursor: pointer;
|
|
406
|
+
text-decoration: underline;
|
|
407
|
+
&:hover {
|
|
408
|
+
color: ${t};
|
|
409
|
+
}
|
|
410
|
+
`}
|
|
411
|
+
`,Ot=b.default.div`display:flex;align-items:center;justify-content:center;flex-shrink:0;`,xn=b.default.div`display:flex;gap:8px;align-items:center;word-break:break-word;`,db=b.default(xn)`cursor:pointer;gap:4px;`,fn=b.default(xn)`flex-direction:row;align-items:center;`,mb=b.default(fn)`align-items:flex-start;max-width:100%;`,hb=b.default(Da)`min-width:0;`,Mo=b.default.div`display:flex;gap:4px;flex-direction:column;align-items:flex-start;`,$a=Ce("DashboardTester"),fb=$a.Provider;function gb({testerType:e,origin:t,children:n}){return a.createElement(fb,{value:{testerType:e,origin:t}},e&&a.createElement(pb,null),n)}const Fa=$a.useContext,pb=()=>a.createElement(a.Fragment,null,a.createElement(_t.MessageLogs,{component:wo}),a.createElement(xt.MessageLogs,{component:wo})),wo=({extendedMessagePayload:e={}})=>{const{handlers:t}=ce(),{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(_b,null,a.createElement(Eb,{$width:4}),a.createElement(Na,{actionbook:n,functionCalls:s,groundedness:r,agentMessageTemplates:o,flaggedTypes:i,onClickFunctionCallDetail:t==null?void 0:t.onFunctionCallDetailClick,style:{iconColor:C.themedColor.textHighEmphasis,textColor:C.themedColor.textHighEmphasis,barColor:C.themedColor.textDisabled},topContent:a.createElement(H,{variant:"caption4",color:C.themedColor.textLowEmphasis},"Only visible in the tester")}))},_b=b.default.div`display:flex;gap:16px;margin:6px ${te.HORIZONTAL_PADDING}px 4px ${te.HORIZONTAL_PADDING+te.AVATAR_SIZE}px;align-self:stretch;`,Eb=b.default.div`width:${({$width:e})=>e}px;background-color:${C.themedColor.textDisabled};border-radius:100px;flex-shrink:0;`,Cb=()=>{var s;const{origin:e}=Fa(),{appId:t,aiAgentId:n}=ke(),{channelSource:r}=Te();return(s=r.channel)!=null&&s.conversation?a.createElement(bb,null,a.createElement(br,{style:{gap:4}},a.createElement(Q,{color:C.themedColor.textLowEmphasis,size:12,type:"show"}),a.createElement(H,{as:"i",color:C.themedColor.textLowEmphasis,variant:"caption2"},"Only visible in the tester")),a.createElement(br,{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(H,{variant:"body3",color:C.themedColor.textHighEmphasis},"Copy ",a.createElement("span",{style:{color:C.themedColor.primary}},"conversation link")),a.createElement(Q,{color:C.themedColor.primary,size:14,type:"copy"}))):null},br=b.default.div`display:flex;justify-content:center;align-items:center;`,bb=b.default(br)`flex-direction:column;padding-block:16px;background-color:${C.themedColor.bg_100_500};gap:8px;`,vb=(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}},Pa=l.createContext(void 0),yb=({children:e})=>{var Z,G;const{chatSDK:t}=ce(),{createAttachmentRules:n}=Ne(),{stringSet:r}=ae(),{channelSource:s,state:o}=Te(),[i,c]=l.useState([]),{announceError:u}=Gr(),[d,m]=l.useState(null),h=n({channel:s.channel,uploadSizeLimit:(Z=t.appInfo)==null?void 0:Z.uploadSizeLimit}),f=((G=o==null?void 0:o.input)==null?void 0:G.disabled)??!1,g=h.isEnabled(),p=h.maxAttachmentCount,v=()=>m(null),E=D=>m(D),_=()=>{E({title:r.FILE_UPLOAD_NOTIFICATION__COUNT_LIMIT.replace("%d",p.toString())})},y=D=>{E({title:r.FILE_UPLOAD_NOTIFICATION__SIZE_LIMIT.replace("%d",D.toString())}),u({type:"fileSizeExceeded",maxSizeMB:D})},A=D=>{E({title:r.FILE_UPLOAD_NOTIFICATION__FILES_EXCLUDED_BY_VALIDATION.replace("%d",D.toString())})},T=D=>D.map(z=>({file:z,preview:{url:URL.createObjectURL(z),type:z.type,name:z.name}})),R=D=>{c(z=>[...z,...T(D)])},L=D=>{c(z=>(z.forEach(q=>URL.revokeObjectURL(q.preview.url)),T(D)))},N=D=>{const{passed:z,failedBySize:q,failedByType:ne}=vb(D,h),ue=q.length+ne.length,Ie=D.length===1?q[0]:void 0;return Ie?y(h.getUploadSizeLimitInMB(Ie.type)):ue>0&&A(ue),z},x=D=>{const z=N(D.files);z.length!==0&&(D.type==="append"?R(z):L(z))},w=D=>{if(!g||f||!Zl(D))return;const z=Ql({currentFiles:i.map(({file:q})=>q),incomingFiles:D,maxAttachmentCount:p});switch(z.type){case"reject":_();return;case"confirm_replace":E({title:r.FILE_UPLOAD_REPLACE_ALERT__TITLE,description:r.FILE_UPLOAD_REPLACE_ALERT__DESCRIPTION,confirmText:r.BUTTON__OK,cancelText:r.BUTTON__CANCEL,onConfirm:()=>x(z.action)});return;case"apply":x(z.action);return}},Y=D=>{c(z=>{var ne;const q=(ne=z[D])==null?void 0:ne.preview;return q&&URL.revokeObjectURL(q.url),z.filter((ue,Ie)=>Ie!==D)})},O=()=>{c(D=>(D.forEach(z=>URL.revokeObjectURL(z.preview.url)),[]))};return a.createElement(Pa.Provider,{value:{files:i,addFiles:w,removeFile:Y,clearFiles:O,isFileUploadEnabled:g,acceptableMimeTypes:h.supportedMimeTypes,maxAttachmentCount:h.maxAttachmentCount,showFileUploadAlert:E}},e,a.createElement(Dn,{visible:!!d,...d??{},onClose:v}))},Qr=()=>{const e=l.useContext(Pa);if(!e)throw new Error("useFileUpload must be used within FileUploadProvider");return e};function Sb({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 Ab({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 Tb=()=>{const{announceError:e}=rt();return l.useCallback(t=>{e({type:"sendFailed"},t)},[e])},Ib=1e3,xb=(e,t,n)=>{const{announcementsEnabled:r,setIsSuppressed:s}=rt(),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]),Dd(t,u,{enabled:o,idleMs:Ib})},Rb=({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}}},Mb=b.default.div`&::-webkit-scrollbar{display:none;}overflow-x:auto;display:flex;flex-direction:row;gap:10px;padding:8px 16px;background-color:transparent;`,wb=b.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;}`,kb=b.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;${ee.light`
|
|
412
|
+
background-color: ${C.color.background50};
|
|
413
413
|
`}
|
|
414
|
-
${
|
|
415
|
-
background-color: ${
|
|
414
|
+
${ee.dark`
|
|
415
|
+
background-color: ${C.color.background500};
|
|
416
416
|
`}
|
|
417
417
|
path {
|
|
418
|
-
fill: ${
|
|
418
|
+
fill: ${C.themedColor.textMidEmphasis};
|
|
419
419
|
}
|
|
420
420
|
|
|
421
421
|
&:hover {
|
|
422
422
|
path {
|
|
423
|
-
fill: ${
|
|
423
|
+
fill: ${C.themedColor.textHighEmphasis};
|
|
424
424
|
}
|
|
425
425
|
}
|
|
426
426
|
|
|
427
427
|
&:focus-visible {
|
|
428
428
|
opacity: 1;
|
|
429
|
-
outline: 2px solid ${
|
|
429
|
+
outline: 2px solid ${C.color.primary.main};
|
|
430
430
|
outline-offset: 2px;
|
|
431
431
|
}
|
|
432
432
|
|
|
433
433
|
circle {
|
|
434
|
-
stroke: ${
|
|
434
|
+
stroke: ${C.themedColor.bg_50_600};
|
|
435
435
|
}
|
|
436
|
-
`,
|
|
437
|
-
outline: 2px solid ${
|
|
436
|
+
`,Lb=()=>{const e=Xt(),{conversation:t}=se(),{files:n,removeFile:r,isFileUploadEnabled:s}=Qr();return s&&n.length>0?a.createElement(Mb,null,n.map(({preview:{type:i,name:c,url:u}},d)=>{let m=a.createElement(Wr,{name:c,mimeType:i,type:Ar(c,i),selected:!0});return i.startsWith("image/")&&(m=a.createElement("img",{alt:t.file.label(c,i,!0),src:u})),a.createElement(wb,{key:u},a.createElement(kb,{type:"button",...t.file.removeButton(c).props,$mobile:e,onClick:()=>r(d)},a.createElement(Q,{type:"close-filled",color:C.themedColor.textMidEmphasis})),m)})):null},Ob={textArea:P.css`min-height:40px;height:40px;font-size:16px;line-height:24px;`},Ua=b.default.button`all:unset;cursor:pointer;display:flex;align-items:center;justify-content:center;width:32px;height:32px;${Re}`,ko=b.default.div`width:100%;position:relative;background-color:${({theme:e})=>e.colors.messageInput.background};border-radius:20px;`,Lo=b.default.div`display:flex;flex-direction:row;align-items:flex-end;position:relative;`,Oo=b.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:${Hi}px;overflow-wrap:break-word;white-space:pre-wrap;overflow-x:hidden;${ra&&Ob.textArea};${({$focusVisible:e})=>e&&P.css`
|
|
437
|
+
outline: 2px solid ${C.themedColor.primary};
|
|
438
438
|
outline-offset: 2px;
|
|
439
439
|
`}
|
|
440
440
|
|
|
@@ -445,22 +445,22 @@
|
|
|
445
445
|
&:disabled {
|
|
446
446
|
cursor: not-allowed;
|
|
447
447
|
&::placeholder {
|
|
448
|
-
color: ${
|
|
448
|
+
color: ${C.themedColor.textDisabled};
|
|
449
449
|
}
|
|
450
450
|
}
|
|
451
451
|
|
|
452
|
-
${({$blocked:e})=>e&&
|
|
453
|
-
`,
|
|
454
|
-
color: ${
|
|
452
|
+
${({$blocked:e})=>e&&P.css`cursor:not-allowed;&::placeholder{color:${C.themedColor.textDisabled};}`}
|
|
453
|
+
`,Nb=b.default.input`display:none;`;b.default.div`display:flex;align-items:center;gap:24px;`;const Db=b.default(Ua)`flex-shrink:0;border-radius:8px;&:disabled{cursor:not-allowed;}&:not(:disabled){&:hover{background-color:${C.themedColor.bg_100_500};path{fill:${C.themedColor.textHighEmphasis};}}&:active{background-color:${C.themedColor.bg_200_400};}}`,No=b.default.div`padding:10px 16px 10px 12px;position:relative;display:flex;align-items:center;gap:8px;`,Do=e=>e.startsWith("image/"),$o=({disabled:e})=>{const{stringSet:t}=ae(),{conversation:n}=se(),{config:r}=ce(),s=l.useRef(null),o=l.useRef(null),[i,c]=l.useState(!1),{addFiles:u,isFileUploadEnabled:d,acceptableMimeTypes:m,showFileUploadAlert:h}=Qr(),f=m.includes(ir),g=f?["image/*"]:m.filter(Do),p=f?[ir]:m.filter(N=>!Do(N)),v=r.conversation.input.gallery.photoEnabled,E=r.conversation.input.fileEnabled,_=()=>f||g.length>0,y=()=>f||p.length>0,A=N=>{const x=N.currentTarget.files;x&&u(Array.from(x)),N.target.value=""},T=()=>{c(!0)},R=l.useMemo(()=>{const N=[];return v&&N.push({type:"image",icon:"photo",label:t.FILE_UPLOAD_PHOTOS,accept:g.join(","),inputRef:s,onSelect:()=>{if(!_()){h({title:t.FILE_UPLOAD_NO_SUPPORTED_FILES});return}c(!1),setTimeout(()=>{var x;return(x=s.current)==null?void 0:x.click()},100)}}),E&&N.push({type:"file",icon:"document",label:t.FILE_UPLOAD_FILES,accept:m.join(","),inputRef:o,onSelect:()=>{if(!y()){h({title:t.FILE_UPLOAD_NO_SUPPORTED_FILES});return}c(!1),setTimeout(()=>{var x;return(x=o.current)==null?void 0:x.click()},100)}}),N},[g,m,t,v,E]);if(!d)return null;const L={attach:n.messageInput.attachFileButton()};return a.createElement(a.Fragment,null,a.createElement(Db,{...L.attach.props,disabled:e,onClick:T},a.createElement(Q,{type:"add",color:e?C.themedColor.textDisabled:C.color.primary.main,size:20}),L.attach.descriptionNode),R.map(N=>a.createElement(Nb,{key:N.type,type:"file",ref:N.inputRef,multiple:N.type==="image",onChange:A,accept:N.accept})),a.createElement(at,{visible:i,onClose:()=>c(!1),"aria-label":t.A11Y_FILE_UPLOAD_OPTIONS},R.map(N=>a.createElement(at.ActionItem,{key:N.type,onClick:N.onSelect,icon:N.icon},N.label))))},$b=()=>{const e=l.useRef(null),[t,n]=l.useState(""),{stringSet:r}=ae(),{conversation:s}=se(),{rootElement:o}=ce(),i=lt(o),{focusHandlers:c,isFocusVisible:u,suppressNextFocusVisible:d}=Rb({focusRoot:i}),{channelSource:m,messageSource:h,state:f}=Te(),{files:g,addFiles:p,clearFiles:v}=Qr(),E=Tb(),{focusPolicy:_,disabled:y,disabledBy:A}=f.input,T=_==="preserve",R=_==="release",L=(()=>{if(!y)return r.MESSAGE_INPUT__PLACE_HOLDER;switch(A){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}})();Lf({onDropFiles:I=>{p(I)}}),Ab({blurred:R,elementRef:e,document:i,onRecoverFocus:()=>{d()}}),xb(m.channel,t,!y);const N=t.trim().length>0,x=g.length>0,w=!y&&(N||x),Y={input:s.messageInput.textInput(r.A11Y_MESSAGE_INPUT),send:s.messageInput.sendButton()},O=()=>{e.current&&(e.current.value="",e.current.style.height=""),v(),n("")},Z=()=>{var I;d(),(I=e.current)==null||I.focus()},{requestRestore:G,cancelRestore:D}=Sb({elementRef:e,ready:T,onRestore:d}),z=I=>{D(),E(I)},q=()=>{D()},ne=async I=>{try{await I(),q()}catch{z(e.current)}},ue=async()=>{if(y)return;const I=t.trim();if(!I&&!g.length)return;const W=[...g];if(G(),O(),Z(),W.length===0){await ne(()=>h.sendUserMessage({message:I}));return}if(W.length===1)await ne(()=>h.sendFileMessage({message:I,file:W[0].file}));else{const re=W.map(({file:oe})=>({file:oe}));await ne(()=>h.sendMultipleFilesMessage({message:I,fileInfoList:re}))}},Ie=I=>{const W=Array.from(I.clipboardData.files);W.length>0&&(I.preventDefault(),p(W))},B=I=>{I.key!=="Enter"||I.nativeEvent.isComposing||I.shiftKey||(I.preventDefault(),ue())},V=I=>{if(y){e.current&&(e.current.value=t);return}if(e.current){e.current.style.height="";const W=Math.min(zm,e.current.scrollHeight);Hi<W&&(e.current.style.height=`${W}px`)}n(I.target.value)};return R?a.createElement(No,null,a.createElement($o,{disabled:!0}),a.createElement(ko,null,a.createElement(Lo,null,a.createElement(Oo,{rows:1,...Y.input.props,disabled:!0,placeholder:L,$blocked:!0,$focusVisible:!1,"data-focus-visible":"false"})))):a.createElement(No,{"data-message-composer":""},a.createElement($o,{disabled:y}),a.createElement(ko,null,a.createElement(Lb,null),a.createElement(Lo,null,a.createElement(Oo,{ref:e,rows:1,...Y.input.props,readOnly:T,"aria-disabled":T?"true":void 0,placeholder:L,maxLength:5e3,$blocked:y,$focusVisible:u,"data-focus-visible":u?"true":"false",onKeyDown:B,onChange:V,onFocus:c.onFocus,onBlur:c.onBlur,onPaste:Ie}))),w&&a.createElement(Ua,{...Y.send.props,onClick:()=>ue()},a.createElement(Q,{type:"send",color:C.color.primary.main,size:20}),Y.send.descriptionNode))},Fb=b.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:${C.themedColor.textLowEmphasis};&& a{font-weight:700;text-decoration:none;${ee.light`
|
|
454
|
+
color: ${C.color.information.light};
|
|
455
455
|
`};
|
|
456
|
-
${
|
|
457
|
-
color: ${
|
|
456
|
+
${ee.dark`
|
|
457
|
+
color: ${C.color.information.main};
|
|
458
458
|
`};
|
|
459
459
|
}
|
|
460
|
-
`,YE=u.lazy(()=>Promise.resolve().then(()=>require("./cjs/VvejebHE.cjs")).then(e=>({default:e.MarkdownText}))),WE=()=>{const{aiAgentInfo:e,userSession:t}=ke(),{handlers:n}=ae(),{messageSource:r,channelSource:o}=Se(),[s,a]=u.useState(null),l=gr("special-notice",o.channel),c=u.useCallback(()=>o.channel?l?r.messages.some(d=>gt(d,(t==null?void 0:t.userId)??"")):!0:null,[o.channel,l,r.messages,t==null?void 0:t.userId]);return u.useEffect(()=>{s||a(c())},[c,s]),s||!e.specialNotice?null:i.createElement(VE,null,i.createElement(YE,{onClickLink:n.onClickLink},e.specialNotice))},qE=()=>i.createElement(KE,null,i.createElement(WE,null),i.createElement(ME,null,i.createElement(zE,null))),KE=p.default.div`z-index:0;border:none;width:100%;`,jE=()=>{var o;const{testerType:e}=_t(),{channelSource:t}=Se(),n=Ne(t.channel),r=!!e&&((o=t.channel)==null?void 0:o.isAIAgent);return n&&r?i.createElement(TE,null):i.createElement(qE,null)},Xi=({start:e,title:t,titleAlign:n="start",end:r,containerProps:o})=>{const s=u.useRef(null),a=u.useRef(null),[l,c]=u.useState(0),[d,m]=u.useState(0);return u.useLayoutEffect(()=>{s.current&&c(s.current.offsetWidth),a.current&&m(a.current.offsetWidth)},[e,r]),i.createElement(XE,{...o},i.createElement(ZE,null,n==="center"&&t&&i.createElement(JE,{$sideWidth:Math.max(l,d)},i.createElement(QE,null,t)),i.createElement(eb,null,i.createElement(tb,{ref:s},e),(n==="start"||n==="end")&&t&&i.createElement(rb,{$align:n,$hasStart:!!e,$hasEnd:!!r},t),i.createElement(nb,{ref:a},r))))},XE=p.default.div`position:relative;width:100%;background-color:${({theme:e})=>e.colors.base.headerBackground};border-bottom:1px solid ${h.themedColor.textDisabled};`,ZE=p.default.div`position:relative;height:56px;padding:11px 12px;`,JE=p.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;`,QE=p.default.div`max-width:100%;overflow:hidden;`,eb=p.default.div`display:flex;flex-direction:row;align-items:center;justify-content:space-between;height:100%;z-index:1;`,tb=p.default.div`flex-shrink:0;display:flex;align-items:center;`,nb=p.default.div`flex-shrink:0;display:flex;align-items:center;`,rb=p.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;`,Et=(e=16)=>Dt()?e*1.5:e,ob=()=>{const{state:e}=ae(),{messenger:t}=oe(),n=Et(),r=()=>{e.setOpened(!1)};return i.createElement(Ze,{...t.closeButton().props,type:"close",size:n,onClick:r})},sb=()=>{const{enableCloseConversationButton:e,dispatcher:t}=ae(),{channelSource:n}=Se(),{conversation:r}=oe(),o=n.channel,s=Et(),a=(o==null?void 0:o.isAIAgent)&&e,l=!ar(o);if(!a)return null;const c={close:r.header.closeConversationButton()},d=async()=>{o&&await t.send(Qe.CloseConversation({channelUrl:o.url}))};return i.createElement(i.Fragment,null,i.createElement(Ze,{...c.close.props,type:"mute",size:s,disabled:l,onClick:d}),c.close.descriptionNode)},ib=()=>{const{state:e,enableExpandButton:t}=ae(),{messenger:n}=oe(),r=Et();return t?i.createElement(Ze,{...n.expandButton(e.expanded).props,type:e.expanded?"collapse":"expand",size:r,onClick:()=>e.setExpanded(!e.expanded)}):null},ab=({label:e,children:t,position:n="top",disabled:r})=>r?t:i.createElement(tr,null,t,i.createElement(ub,{$position:n},i.createElement(db,{variant:"caption1"},e),i.createElement(lb,{$position:n}))),lb=({$position:e})=>i.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"},i.createElement("path",{d:"M6 6L0 0h12L6 6Z",fill:h.themedColor.textHighEmphasis})),cb={top:D.css`flex-direction:column;top:0;transform:translate(-50%,-100%);`,bottom:D.css`flex-direction:column-reverse;bottom:0;transform:translate(-50%,100%);`},tr=p.default.div`position:relative;`,ub=p.default.div`display:flex;align-items:center;position:absolute;left:50%;z-index:${it.TOOLTIP};${({$position:e})=>cb[e]}opacity:0;transition:opacity 0.2s ease-in-out;pointer-events:none;${tr}:hover &,${tr}:focus-within &{opacity:1;}`,db=p.default($)`padding:6px 8px;background:${h.themedColor.textHighEmphasis};color:${h.themedColor.textHighEmphasisInverse};border-radius:4px;font-size:12px;white-space:nowrap;`,mb=2e3,ss=0,fb=1500,Xt=Symbol("header-focus-status-pause"),is="data-sb-header-focus-protected",gb="[data-message-composer]",as=new WeakMap,Un=e=>{const t=as.get(e);if(t)return t;const n={focusedTargetIds:new Set,pendingBlurTimeouts:new Map,maxPauseTimeout:null};return as.set(e,n),n},Bn=(e,t)=>{const n=e.pendingBlurTimeouts.get(t);n&&(clearTimeout(n),e.pendingBlurTimeouts.delete(t))},Qt=e=>{e.maxPauseTimeout&&(clearTimeout(e.maxPauseTimeout),e.maxPauseTimeout=null)},hb=e=>{e.pendingBlurTimeouts.forEach(t=>clearTimeout(t)),e.pendingBlurTimeouts.clear(),e.focusedTargetIds.clear(),Qt(e)},pb=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)})},_b=e=>e instanceof HTMLBodyElement||(e instanceof HTMLButtonElement||e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&e.disabled?!0:(e instanceof HTMLElement&&e.closest(gb),!1),Or=()=>{const{setStatusPauseState:e}=Xe(),t=u.useRef(Symbol("header-focus-target")),n=u.useRef(!1),r=u.useRef(0),o=u.useRef(null),s=u.useCallback(()=>{o.current&&(clearTimeout(o.current),o.current=null)},[]),a=u.useCallback(()=>{if(n.current)return;n.current=!0,r.current=Date.now()+fb,s();const c=Un(e);Bn(c,t.current),c.focusedTargetIds.add(t.current),c.focusedTargetIds.size===1&&e(Xt,!0),Qt(c),c.maxPauseTimeout=setTimeout(()=>{hb(c),e(Xt,!1)},mb)},[s,e]),l=u.useCallback(c=>{if(!n.current)return;n.current=!1;const d=c.currentTarget,m=Un(e),f=d instanceof HTMLElement&&Date.now()<=r.current;Bn(m,t.current),f&&(s(),o.current=setTimeout(()=>{if(o.current=null,!(d instanceof HTMLElement)||!d.isConnected)return;const E=d.ownerDocument.activeElement,y=E instanceof HTMLElement&&E.hasAttribute(is);if(E===d||y||!_b(E))return;const v=pb(d);d.focus({preventScroll:!0}),v()},ss)),m.pendingBlurTimeouts.set(t.current,setTimeout(()=>{m.pendingBlurTimeouts.delete(t.current),m.focusedTargetIds.delete(t.current),m.focusedTargetIds.size===0&&(Qt(m),e(Xt,!1))},ss))},[s,e]);return u.useEffect(()=>()=>{const c=Un(e);n.current=!1,s(),Bn(c,t.current),c.focusedTargetIds.delete(t.current)&&c.focusedTargetIds.size===0&&(Qt(c),e(Xt,!1))},[s,e]),{[is]:"true",onFocus:a,onBlur:l}},Eb=()=>{const{logger:e}=ae(),{stringSet:t}=se(),{channelSource:n}=Se(),{conversation:r}=oe(),o=n.channel,s=Et(),a=gr("handoff-button",o),l=!ar(o)||nt(o),[c,d]=u.useState(!1),m=Or(),f=async()=>{d(!1);try{const E=await(o==null?void 0:o.markConversationAsHandoff());e.info("conversation.handleAgentHandoff: success",E)}catch(E){e.error("conversation.handleAgentHandoff: error",E)}};if(!a)return null;const g={handoff:r.header.handoffButton()};return i.createElement(i.Fragment,null,i.createElement(i.Fragment,null,i.createElement(ab,{label:t.HEADER_BUTTON__AGENT_HANDOFF,position:"bottom",disabled:l},i.createElement(Ze,{...g.handoff.props,type:"agent",size:s,disabled:l,...m,onClick:()=>d(!0)})),g.handoff.descriptionNode),i.createElement(ot,{portalContainerId:be.WINDOW,visible:c,onClose:()=>d(!1)},i.createElement(kr,{title:t.HANDOFF_CONFIRM__TITLE,description:t.HANDOFF_CONFIRM__DESCRIPTION,negativeText:t.HANDOFF_CONFIRM__CANCEL,positiveText:t.HANDOFF_CONFIRM__HANDOFF,onCancel:()=>d(!1),onConfirm:f})))},bb=u.lazy(()=>Promise.resolve().then(()=>require("./cjs/VvejebHE.cjs")).then(e=>({default:e.MarkdownText}))),Cb=()=>{const{logger:e}=ae(),{stringSet:t}=se(),{memoryInfo:n,sdkUser:r}=ke(),{actions:o}=Se(),{conversation:s}=oe(),a=Et(20),l=Or(),[c,d]=u.useState(null),[m,f]=u.useState(!1),g=u.useRef(!1);if(u.useEffect(()=>{r&&(n!=null&&n.consentDialog)&&d({...n})},[r,n==null?void 0:n.consentDialog]),!r||!n)return null;const E=s.header.memoryIndicator(n.enabled),y=async v=>{if(!g.current){g.current=!0,f(!1);try{await o.setUserMemoryState({enabled:v}),d(null)}catch(b){e.error("memoryIndicator.setUserMemoryState: error",b),f(!0)}finally{g.current=!1}}};return i.createElement(i.Fragment,null,n.showIndicator&&i.createElement(i.Fragment,null,i.createElement(Ab,{...E.props,as:"button",type:"button",onClick:()=>d({...n}),...l,$size:a},i.createElement(X,{type:"memory",size:a,color:h.themedColor.textHighEmphasis}),i.createElement(xb,{$enabled:n.enabled})),E.descriptionNode),c&&i.createElement(vb,{memoryInfo:c,onClose:()=>d(null),onSetEnabled:y}),i.createElement(En,{visible:m,title:t.PLACE_HOLDER__WRONG,description:t.MEMORY__ERROR_MESSAGE,onClose:()=>f(!1)}))},vb=({memoryInfo:e,onClose:t,onSetEnabled:n})=>{var f;const{stringSet:r}=se(),{colors:o}=D.useTheme(),s=u.useId(),a=u.useId(),l=kl(e),c=l==="consent",d={consent:{body:((f=e.consentDialog)==null?void 0:f.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}}[l],m=o.memoryDialog;return i.createElement(ot,{visible:!0,portalContainerId:be.WINDOW,onClose:t,cancelable:!c,"aria-labelledby":s,"aria-describedby":a},i.createElement(kr,{title:r.MEMORY__DIALOG_TITLE,titleId:s,description:i.createElement(yb,null,d.body),descriptionId:a,negativeText:d.negativeText,positiveText:d.positiveText,buttonLayout:c?"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}}))},yb=({children:e})=>{const{handlers:t}=ae();return i.createElement(Tb,null,i.createElement(kt,{fallback:e},i.createElement(bb,{onClickLink:t.onClickLink},e)))},Sb=D.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;`,Ab=p.default.button`${Sb};cursor:pointer;${Ae}`,xb=p.default.span`position:absolute;top:0;inset-inline-end:0;width:8px;height:8px;border-radius:999px;background-color:${({$enabled:e})=>e?h.themedColor.secondary:h.color.background300};box-shadow:0 0 0 2px ${h.color.background50};${Z.dark`
|
|
461
|
-
box-shadow: 0 0 0 2px ${
|
|
460
|
+
`,Pb=l.lazy(()=>Promise.resolve().then(()=>require("./cjs/VvejebHE.cjs")).then(e=>({default:e.MarkdownText}))),Ub=()=>{const{aiAgentInfo:e,userSession:t}=Ne(),{handlers:n}=ce(),{messageSource:r,channelSource:s}=Te(),[o,i]=l.useState(null),c=Dr("special-notice",s.channel),u=l.useCallback(()=>s.channel?c?r.messages.some(d=>mt(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(Fb,null,a.createElement(Pb,{onClickLink:n.onClickLink},e.specialNotice))},Bb=()=>a.createElement(Hb,null,a.createElement(Ub,null),a.createElement(yb,null,a.createElement($b,null))),Hb=b.default.div`z-index:0;border:none;width:100%;`,Gb=()=>{var s;const{testerType:e}=Fa(),{channelSource:t}=Te(),n=Be(t.channel),r=!!e&&((s=t.channel)==null?void 0:s.isAIAgent);return n&&r?a.createElement(Cb,null):a.createElement(Bb,null)},Ba=({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(zb,{...s},a.createElement(Vb,null,n==="center"&&t&&a.createElement(qb,{$sideWidth:Math.max(c,d)},a.createElement(Yb,null,t)),a.createElement(Wb,null,a.createElement(Kb,{ref:o},e),(n==="start"||n==="end")&&t&&a.createElement(Xb,{$align:n,$hasStart:!!e,$hasEnd:!!r},t),a.createElement(jb,{ref:i},r))))},zb=b.default.div`position:relative;width:100%;background-color:${({theme:e})=>e.colors.base.headerBackground};border-bottom:1px solid ${C.themedColor.textDisabled};`,Vb=b.default.div`position:relative;height:56px;padding:11px 12px;`,qb=b.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;`,Yb=b.default.div`max-width:100%;overflow:hidden;`,Wb=b.default.div`display:flex;flex-direction:row;align-items:center;justify-content:space-between;height:100%;z-index:1;`,Kb=b.default.div`flex-shrink:0;display:flex;align-items:center;`,jb=b.default.div`flex-shrink:0;display:flex;align-items:center;`,Xb=b.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;`,Rt=(e=16)=>Xt()?e*1.5:e,Zb=()=>{const{state:e}=ce(),{messenger:t}=se(),n=Rt(),r=()=>{e.setOpened(!1)};return a.createElement(st,{...t.closeButton().props,type:"close",size:n,onClick:r})},Jb=()=>{const{enableCloseConversationButton:e,dispatcher:t}=ce(),{channelSource:n}=Te(),{conversation:r}=se(),s=n.channel,o=Rt(),i=(s==null?void 0:s.isAIAgent)&&e,c=!xr(s);if(!i)return null;const u={close:r.header.closeConversationButton()},d=async()=>{s&&await t.send(it.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)},Qb=()=>{const{state:e,enableExpandButton:t}=ce(),{messenger:n}=se(),r=Rt();return t?a.createElement(st,{...n.expandButton(e.expanded).props,type:e.expanded?"collapse":"expand",size:r,onClick:()=>e.setExpanded(!e.expanded)}):null},ev=({label:e,children:t,position:n="top",disabled:r})=>r?t:a.createElement(vr,null,t,a.createElement(rv,{$position:n},a.createElement(sv,{variant:"caption1"},e),a.createElement(tv,{$position:n}))),tv=({$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:C.themedColor.textHighEmphasis})),nv={top:P.css`flex-direction:column;top:0;transform:translate(-50%,-100%);`,bottom:P.css`flex-direction:column-reverse;bottom:0;transform:translate(-50%,100%);`},vr=b.default.div`position:relative;`,rv=b.default.div`display:flex;align-items:center;position:absolute;left:50%;z-index:${gt.TOOLTIP};${({$position:e})=>nv[e]}opacity:0;transition:opacity 0.2s ease-in-out;pointer-events:none;${vr}:hover &,${vr}:focus-within &{opacity:1;}`,sv=b.default(H)`padding:6px 8px;background:${C.themedColor.textHighEmphasis};color:${C.themedColor.textHighEmphasisInverse};border-radius:4px;font-size:12px;white-space:nowrap;`,ov=2e3,Fo=0,iv=1500,mn=Symbol("header-focus-status-pause"),Po="data-sb-header-focus-protected",av="[data-message-composer]",Uo=new WeakMap,sr=e=>{const t=Uo.get(e);if(t)return t;const n={focusedTargetIds:new Set,pendingBlurTimeouts:new Map,maxPauseTimeout:null};return Uo.set(e,n),n},or=(e,t)=>{const n=e.pendingBlurTimeouts.get(t);n&&(clearTimeout(n),e.pendingBlurTimeouts.delete(t))},gn=e=>{e.maxPauseTimeout&&(clearTimeout(e.maxPauseTimeout),e.maxPauseTimeout=null)},cv=e=>{e.pendingBlurTimeouts.forEach(t=>clearTimeout(t)),e.pendingBlurTimeouts.clear(),e.focusedTargetIds.clear(),gn(e)},lv=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)})},uv=e=>e instanceof HTMLBodyElement||(e instanceof HTMLButtonElement||e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&e.disabled?!0:(e instanceof HTMLElement&&e.closest(av),!1),es=()=>{const{setStatusPauseState:e}=rt(),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()+iv,o();const u=sr(e);or(u,t.current),u.focusedTargetIds.add(t.current),u.focusedTargetIds.size===1&&e(mn,!0),gn(u),u.maxPauseTimeout=setTimeout(()=>{cv(u),e(mn,!1)},ov)},[o,e]),c=l.useCallback(u=>{if(!n.current)return;n.current=!1;const d=u.currentTarget,m=sr(e),h=d instanceof HTMLElement&&Date.now()<=r.current;or(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(Po);if(g===d||p||!uv(g))return;const v=lv(d);d.focus({preventScroll:!0}),v()},Fo)),m.pendingBlurTimeouts.set(t.current,setTimeout(()=>{m.pendingBlurTimeouts.delete(t.current),m.focusedTargetIds.delete(t.current),m.focusedTargetIds.size===0&&(gn(m),e(mn,!1))},Fo))},[o,e]);return l.useEffect(()=>()=>{const u=sr(e);n.current=!1,o(),or(u,t.current),u.focusedTargetIds.delete(t.current)&&u.focusedTargetIds.size===0&&(gn(u),e(mn,!1))},[o,e]),{[Po]:"true",onFocus:i,onBlur:c}},dv=()=>{const{logger:e}=ce(),{stringSet:t}=ae(),{channelSource:n}=Te(),{conversation:r}=se(),s=n.channel,o=Rt(),i=Dr("handoff-button",s),c=!xr(s)||ct(s),[u,d]=l.useState(!1),m=es(),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(ev,{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(ut,{portalContainerId:ve.WINDOW,visible:u,onClose:()=>d(!1)},a.createElement(Zr,{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})))},mv=l.lazy(()=>Promise.resolve().then(()=>require("./cjs/VvejebHE.cjs")).then(e=>({default:e.MarkdownText}))),hv=()=>{const{logger:e}=ce(),{stringSet:t}=ae(),{memoryInfo:n,sdkUser:r}=Ne(),{actions:s}=Te(),{conversation:o}=se(),i=Rt(20),c=es(),[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(E){e.error("memoryIndicator.setUserMemoryState: error",E),h(!0)}finally{f.current=!1}}};return a.createElement(a.Fragment,null,n.showIndicator&&a.createElement(a.Fragment,null,a.createElement(_v,{...g.props,as:"button",type:"button",onClick:()=>d({...n}),...c,$size:i},a.createElement(Q,{type:"memory",size:i,color:C.themedColor.textHighEmphasis}),a.createElement(Ev,{$enabled:n.enabled})),g.descriptionNode),u&&a.createElement(fv,{memoryInfo:u,onClose:()=>d(null),onSetEnabled:p}),a.createElement(Dn,{visible:m,title:t.PLACE_HOLDER__WRONG,description:t.MEMORY__ERROR_MESSAGE,onClose:()=>h(!1)}))},fv=({memoryInfo:e,onClose:t,onSetEnabled:n})=>{var h;const{stringSet:r}=ae(),{colors:s}=P.useTheme(),o=l.useId(),i=l.useId(),c=Xl(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:ve.WINDOW,onClose:t,cancelable:!u,"aria-labelledby":o,"aria-describedby":i},a.createElement(Zr,{title:r.MEMORY__DIALOG_TITLE,titleId:o,description:a.createElement(gv,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}}))},gv=({children:e})=>{const{handlers:t}=ce();return a.createElement(Cv,null,a.createElement(Ht,{fallback:e},a.createElement(mv,{onClickLink:t.onClickLink},e)))},pv=P.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;`,_v=b.default.button`${pv};cursor:pointer;${Re}`,Ev=b.default.span`position:absolute;top:0;inset-inline-end:0;width:8px;height:8px;border-radius:999px;background-color:${({$enabled:e})=>e?C.themedColor.secondary:C.color.background300};box-shadow:0 0 0 2px ${C.color.background50};${ee.dark`
|
|
461
|
+
box-shadow: 0 0 0 2px ${C.color.background500};
|
|
462
462
|
`}
|
|
463
|
-
`,
|
|
463
|
+
`,Cv=b.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;}`,bv=()=>{const{conversation:e}=se(),{onNavigateToConversationList:t}=Te();if(!t)return null;const n={menu:e.header.menuButton()};return a.createElement(a.Fragment,null,a.createElement(st,{...n.menu.props,...Ni,type:"menu",size:24,onClick:()=>t()}),n.menu.descriptionNode)},Ha=({channel:e,size:t=40})=>{const{userSession:n,aiAgentInfo:r}=Ne(),{fallbackIcon:s,url:o}=$r({channel:e,aiAgentInfo:r,userSession:n}),[i,c]=l.useState(),u=P.useTheme();return o&&o!==i?a.createElement(ba,{src:o,size:t,"aria-hidden":"true",onImageError:c}):a.createElement(vv,{"aria-hidden":"true",$size:t,$bgColor:u.colors.base.primary},a.createElement(Q,{type:s,size:t*.55,color:u.colors.base.primaryContrastContent}))},vv=b.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;`,yv=()=>{const{channelSource:e}=Te(),{aiAgentInfo:t,userSession:n}=Ne(),{conversation:r}=se(),{config:s}=ke(),{announcementsEnabled:o}=rt(),i=e.channel,c=$r({channel:i,userSession:n,aiAgentInfo:t}),u=s.conversation.header.avatarEnabled,d=es(),m=ua({enabled:o,label:c.title}),h={title:r.header.title(c.title,{active:m.enabled,titleId:m.id,initialFocus:!1})};return a.createElement(Sv,null,u&&a.createElement(Ha,{channel:i,size:34}),a.createElement(Av,{...h.title.props,...d},c.title))},Sv=b.default.div`display:flex;flex-direction:row;align-items:center;gap:6px;min-width:0;width:100%;overflow:hidden;`,Av=b.default(H).attrs({variant:"h2",color:C.themedColor.textHighEmphasis})`
|
|
464
464
|
margin: 0;
|
|
465
465
|
flex: 1;
|
|
466
466
|
min-width: 0;
|
|
@@ -472,10 +472,10 @@
|
|
|
472
472
|
&:focus {
|
|
473
473
|
outline: none;
|
|
474
474
|
}
|
|
475
|
-
`,
|
|
475
|
+
`,Tv=e=>{const{components:t}=Et.useContext();return a.createElement(Ba,{start:a.createElement(t.StartArea,null),title:a.createElement(t.TitleArea,null),titleAlign:e.titleAlign,end:a.createElement(t.EndArea,null),containerProps:Fi})},Iv=()=>{const{components:e}=Et.useContext();return a.createElement(e.MenuButton,null)},xv=()=>{const{components:e}=Et.useContext();return a.createElement(e.Title,null)},Rv=()=>{const{components:e}=Et.useContext();return a.createElement(wv,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))},Et=je({template:Tv,components:{StartArea:Iv,TitleArea:xv,EndArea:Rv,MenuButton:bv,Title:yv,MemoryIndicator:hv,HandoffButton:dv,ConversationCloseButton:Jb,ExpandButton:Qb,CloseButton:Zb}}),Mv=()=>{const{Template:e}=Et.useContext();return a.createElement(e,{titleAlign:"start"})},wv=b.default.div`display:flex;gap:10px;align-items:center;justify-content:center;`,ts=({children:e,onNavigateToConversationList:t,channelUrl:n,onClearChannelUrl:r,shouldMarkAsRead:s,announcementsEnabled:o=!0,conversationStatsEnabled:i=!0,initialFocusTarget:c,style:u,closedChannelUrl:d,onClearClosedChannelUrl:m})=>{const{Template:h}=Hn.useContext();return a.createElement(aa,{onNavigateToConversationList:t,channelUrl:n??d,onClearChannelUrl:r??m,conversationStatsEnabled:i,shouldMarkAsRead:s},a.createElement(gr,null,a.createElement(gr.Consumer,null,f=>a.createElement(Dh,{announcementsEnabled:o},a.createElement(kv,{enabled:i}),a.createElement(Lv,null),a.createElement(Ov,{style:u,dragHandlers:f,initialFocusTarget:c},a.createElement(h,null)),e))))},kv=({enabled:e})=>($f({enabled:e}),null),Lv=()=>(Jf(),Gf(),jf(),null),Ov=({style:e,dragHandlers:t,initialFocusTarget:n,children:r})=>{const s=l.useRef(null);return Df(s,n),a.createElement(Dv,{ref:s,style:e,...t},r)},Nv=e=>{const{components:t}=Hn.useContext();return a.createElement(a.Fragment,null,a.createElement(t.Header,null),a.createElement(t.Body,null),a.createElement(t.Footer,null))},Hn=je({template:Nv,components:{Header:Mv,Body:ub,Footer:Gb}}),Dv=b.default.div`height:100%;width:100%;display:flex;flex-direction:column;flex:1;background-color:${({theme:e})=>e.colors.base.background};`,Ga=Ce("ConversationListAnnouncements",{announcementsEnabled:!0,announceScreenEntry:le}),$v=Ga.Provider,ns=Ga.useContext,Fv=({children:e,announcementsEnabled:t=!0})=>{const{announceScreenEntry:n}=Gr(),r=l.useCallback(o=>{t&&n(o)},[n,t]),s=l.useMemo(()=>({announcementsEnabled:t,announceScreenEntry:r}),[t,r]);return a.createElement($v,{value:s},e)},{Provider:Pv,Context:Uv,useContext:Jt}=Ce("ConversationList");function za({conversationListLimit:e,conversationListFilter:t,conversationListStatsEnabled:n,onOpenConversationView:r=le,children:s}){return a.createElement(Ed,{conversationListLimit:e,conversationListFilter:t,conversationListStatsEnabled:n},o=>a.createElement(Pv,{value:{...o,onOpenConversationView:r}},s))}const Bv=e=>{const{announcementsEnabled:t}=ns(),{listSource:n}=Jt(),r=Yi();da(e,{enabled:t,ready:n.initialized,suppressed:r})},Hv=()=>{const{announceScreenEntry:e,announcementsEnabled:t}=ns(),{listSource:n}=Jt(),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])},Gv=({channel:e})=>a.createElement(Ha,{channel:e}),yr=99,zv=e=>{var E,_;const{channel:t,onClick:n}=e,{stringSet:r,format:s}=ae(),{userSession:o,aiAgentInfo:i}=Ne(),{conversationList:c}=se(),u=$r({channel:t,userSession:o,aiAgentInfo:i}),d=Yl(t,{formatMultipleFilesCount:r.CONVERSATION_LIST__MULTIPLE_FILES_COUNT}),m=Wl(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=(E=t.lastMessage)!=null&&E.isAdminMessage()?r.CONVERSATION_LIST__SYSTEM_MESSAGE:u.title,g=Be(t)?r.CONVERSATION_LIST__ENDED:fi(t,{formatMultipleFilesCount:r.CONVERSATION_LIST__MULTIPLE_FILES_COUNT}),p=n?()=>n():void 0,v=c.item({agent:f,status:g,time:m,unreadCount:h,onActivate:p});return a.createElement(Vv,{"data-testid":"sb-conversation-list-item",$clickable:!!p,...v.props},a.createElement(qv,null,a.createElement(Gv,{...e})),a.createElement(Yv,null,a.createElement(Wv,null,(_=t.lastMessage)!=null&&_.isFileMessage()&&(!t.lastMessage.message||t.lastMessage.name===t.lastMessage.message)?a.createElement(pa,{variant:"subtitle1",color:C.themedColor.textHighEmphasis},d):a.createElement(H,{variant:"subtitle1",color:C.themedColor.textHighEmphasis,maxTextLines:1},d),a.createElement(Kv,null,Be(t)&&a.createElement(a.Fragment,null,a.createElement(H,{variant:"caption1",color:C.themedColor.textMidEmphasis,maxTextLines:1},r.CONVERSATION_LIST__ENDED),a.createElement(jv,null)),a.createElement(H,{variant:"caption2",color:C.themedColor.textLowEmphasis,maxTextLines:1},m))),h>0&&a.createElement(Xv,{$count:h},a.createElement(H,{variant:"caption3",color:C.themedColor.textHighEmphasisInverse},h<=yr?h:`${yr}+`))),v.descriptionNode)},rs=je({template:zv,components:{}}),Vv=b.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"};`,qv=b.default.div`display:flex;align-items:center;justify-content:center;padding-inline-start:16px;`,Yv=b.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 ${C.themedColor.textDisabled};`,Wv=b.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;`,Kv=b.default.div`display:flex;align-items:center;gap:6px;`,jv=b.default.div`width:2px;height:2px;border-radius:1px;background-color:${C.themedColor.textLowEmphasis};`,Xv=b.default.div`display:flex;align-items:center;justify-content:center;height:20px;padding:4px;border-radius:10px;background-color:${C.themedColor.error};${({$count:e})=>e<=yr&&P.css`
|
|
476
476
|
width: 20px;
|
|
477
477
|
`}
|
|
478
|
-
`,
|
|
478
|
+
`,Zv=({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(Jv,{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(Qv,{key:d,role:"listitem"},u)}))},Jv=b.default.div`width:100%;height:100%;display:flex;flex-direction:column;flex:1;overflow:auto;overscroll-behavior:contain;`,Qv=b.default.div`flex-shrink:0;`,ey=()=>{const{stringSet:e}=ae(),{listSource:t,onOpenConversationView:n}=Jt(),{Template:r}=rs.useContext();return t.initialized?t.channels.length===0?a.createElement(Ut,{type:"noChannels",label:e.CONVERSATION_LIST__NO_CONVERSATIONS}):a.createElement(Zv,{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,Be(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(Ut,{type:"loading"})},ty=()=>{const{stringSet:e}=ae(),{_aiAgentSDK:t}=ke(),{language:n,countryCode:r,context:s}=ce(),{aiAgentInfo:o,refreshActiveChannel:i,createConversation:c}=Ne(),{onOpenConversationView:u}=Jt(),{conversationList:d}=se(),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(ny,{...d.footer.button({onActivate:m}).props},a.createElement(ry,{variant:"h1"},e.TALK_TO_AGENT))},ny=b.default.div`background-color:${({theme:e})=>e.colors.base.primary};display:flex;align-items:center;justify-content:center;padding:16px;cursor:pointer;`,ry=b.default(H)`color:${({theme:e})=>e.colors.base.primaryContrastContent};overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,sy=()=>{const{state:e}=ce(),{messenger:t}=se(),n=Rt(),r=()=>{e.setOpened(!1)};return a.createElement(st,{...t.closeButton().props,type:"close",size:n,onClick:r})},oy=()=>{const{stringSet:e}=ae(),{announcementsEnabled:t}=ns(),{conversationList:n}=se(),r=e.CONVERSATION_LIST__HEADER_TITLE,s=ua({enabled:t,label:r}),o={title:n.headerTitle(r,{active:s.enabled,titleId:s.id})};return a.createElement(iy,{forwardedAs:"h2",variant:"h2",color:C.themedColor.textHighEmphasis,...o.title.props},r)},iy=b.default(H)`margin:0;padding:0 4px;min-width:0;width:100%;box-sizing:border-box;text-overflow:ellipsis;overflow:hidden;white-space:nowrap;`,ay=e=>{const{components:t}=Mt.useContext();return a.createElement(Ba,{start:a.createElement(t.StartArea,null),title:a.createElement(t.TitleArea,null),titleAlign:e.titleAlign,end:a.createElement(t.EndArea,null),containerProps:Fi})},cy=()=>null,ly=()=>{const{components:e}=Mt.useContext();return a.createElement(e.Title,null)},uy=()=>{const{components:e}=Mt.useContext();return a.createElement(e.CloseButton,null)},Mt=je({template:ay,components:{StartArea:cy,TitleArea:ly,EndArea:uy,Title:oy,CloseButton:sy}}),dy=()=>{const{Template:e}=Mt.useContext();return a.createElement(e,{titleAlign:"start"})},my=()=>(Hv(),null),ss=({conversationListLimit:e,conversationListFilter:t,children:n,onOpenConversationView:r,announcementsEnabled:s=!0,conversationListStatsEnabled:o=!0,style:i})=>{const{Template:c}=Gn.useContext();return a.createElement(za,{conversationListLimit:e,conversationListFilter:t,conversationListStatsEnabled:o,onOpenConversationView:r},a.createElement(Fv,{announcementsEnabled:s},a.createElement(my,null),a.createElement(hy,{style:i},a.createElement(c,null)),n))},hy=({style:e,children:t})=>{const n=l.useRef(null);return Bv(n),a.createElement(gy,{ref:n,style:e},t)},fy=()=>{const{components:e}=Gn.useContext();return a.createElement(a.Fragment,null,a.createElement(e.Header,null),a.createElement(e.Body,null),a.createElement(e.Footer,null))},Gn=je({template:fy,components:{Header:dy,Body:ey,Footer:ty}}),gy=b.default.div`height:100%;width:100%;display:flex;flex-direction:column;flex:1;background-color:${({theme:e})=>e.colors.base.background};`,py=P.css`:where(#${ve.ENTRY}) :not(code *){font-family:'Roboto',sans-serif;box-sizing:border-box;}`,_y=[py,ch,lh],Ey=(e,...t)=>P.createGlobalStyle(e,..._y,...t),Cy=Ey``,by=ql(Hn,_t,xt,Pn,Bn,Gn,Et,rs,Mt,Un,Nn),vy=typeof __SBA_USE_MESSAGE_TEMPLATE__>"u"||__SBA_USE_MESSAGE_TEMPLATE__;function Va({appearance:e,rootElement:t,logger:n,language:r,languageCode:s,stringSet:o,children:i,messageTemplate:c,icons:u,theme:d,entryElement:m,modalRootElement:h}){Rh(vy?jm:"",t);const[f,g]=l.useState(null),p=l.useCallback(_=>{g(y=>y===_?y:_)},[]),v=m??f,E=a.createElement(P.StyleSheetManager,{target:t},a.createElement(Th,{rootElement:t,logger:n,appearance:e,theme:d},a.createElement(Qm,{rootElement:t,boundaryElement:v},a.createElement(yd,{internalVariables:c==null?void 0:c.__internalVariables},a.createElement(ah,{stringSet:o,logger:n,language:r,languageCode:s},a.createElement(Sh,{icons:u},a.createElement(by,null,a.createElement(Zm,{entryElement:v,modalRootElement:h,rootElement:t},i),a.createElement(Cy,null))))))));return m?E:a.createElement("div",{ref:p,style:{display:"contents"}},E)}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}},os=l.forwardRef(function({rootElement:t=document.body,logLevel:n=fe.LogLevel.WARN,language:r=navigator.language,userSessionInfo:s,children:o,chatParams:i,icons:c,...u},d){var E,_,y;Ft.level!==n&&(Ft.level=n);const{entryElement:m,modalRootElement:h,setEntryElement:f,setModalRootElement:g}=yy();xh("https://fonts.googleapis.com/css2?family=Roboto&display=swap",t);const p=zi(r),v=Vi.has(p)?p:jt;return a.createElement("div",{ref:f,id:ve.ENTRY,lang:v,style:{width:"fit-content",height:"fit-content",...u.entryStyle}},m&&h&&a.createElement(Va,{logger:Ft,rootElement:t,appearance:(E=u.agentPreviewConfigs)==null?void 0:E.appearance,stringSet:u.stringSet,language:v,messageTemplate:u.messageTemplate,icons:c,theme:u.theme,entryElement:m,modalRootElement:h},a.createElement(cf,{rootElement:t,language:r,logger:Ft,dispatcher:qa,chatParams:{...i,...u.customApiHost&&{customApiHost:u.customApiHost},...u.customWebSocketHost&&{customWebSocketHost:u.customWebSocketHost}},chatSDK:u.customChatSDK,_forceCreateChannel:(_=u.agentPreviewConfigs)==null?void 0:_.forceCreateChannel,_agentVersion:(y=u.agentPreviewConfigs)==null?void 0:y.agentVersion,...u},a.createElement(pf,{ref:d,userSessionInfo:s},a.createElement(gb,{...u._UNSAFE_INTERNAL_dashboardTester},a.createElement(Oh,null,o))))),a.createElement("div",{ref:g,id:ve.MODAL_ROOT,dir:u.dir}))}),Ft=new ei(fe.LogLevel.WARN),qa=new Qo(Ft),{Provider:Sy,useContext:Qt}=Ce("PageChildren"),Ya=({children:e})=>{const[t,n]=l.useState(()=>ts),[r,s]=l.useState(null),[o,i]=l.useState(()=>ss),[c,u]=l.useState(null),d=l.useCallback(h=>{n(()=>h)},[]),m=l.useCallback(h=>{i(()=>h)},[]);return a.createElement(Sy,{value:{conversationComponent:t,setConversationComponent:d,conversationChildren:r,setConversationChildren:s,conversationListComponent:o,setConversationListComponent:m,conversationListChildren:c,setConversationListChildren:u}},e)},is=(e,t)=>e?{role:"dialog","aria-modal":"true",...t?{"aria-labelledby":ve.WINDOW_TITLE}:{"aria-label":"Messenger"}}:{"aria-hidden":"true",inert:!0},Wa=({children:e,isOpened:t,zIndex:n=gt.WINDOW})=>a.createElement(Yr,null,a.createElement(Ay,{isOpened:t,zIndex:n},e)),Ay=({children:e,isOpened:t,zIndex:n=gt.WINDOW})=>{const{dir:r,rootElement:s}=ce(),o=lt(s,!0),i=l.useRef(null),{hasWindowTitleReference:c,isWindowNameReady:u}=$n();return On(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(Ty,{ref:i,id:ve.WINDOW,dir:r,...is(t,c),$visible:t,$zIndex:n},e)},Ty=b.default.div`width:100%;height:100%;position:fixed;top:0;left:0;z-index:${({$zIndex:e})=>e};visibility:${({$visible:e})=>e?"visible":"hidden"};`,Iy=48,xy=2/3,Bo=12;function Ka({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=Iy,hasUnread:f=!1}){const g=ya(),p=d&&!g,v=lr(m),E=Math.round(h*xy);return a.createElement(wy,{dir:u,id:ve.LAUNCHER,className:e,"aria-label":s,"aria-describedby":o,onClick:r,$animated:p,$backgroundColor:m,$prefersReducedMotion:g,$size:h},a.createElement(ky,{$isOpened:n,$animated:p,$fillColor:v,$iconSize:E,$prefersReducedMotion:g},a.createElement(Ho.Open,{url:c,isDefaultIcon:i==="default_icon",size:E})),a.createElement(Ly,{$isOpened:n,$animated:p,$fillColor:v,$iconSize:E,$prefersReducedMotion:g},a.createElement(Ho.Close,{size:E})),f&&a.createElement(Oy,null),t)}const Ry=P.css`&:hover{transition:transform 250ms cubic-bezier(0.33,0,0,1);transform:scale(1.1);}&:active{transform:scale(0.8);}`,My=P.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===Bt.WHITE?"grayscale(100%) brightness(2000%)":"grayscale(100%) invert(100%) saturate(0%) brightness(0%) contrast(1000%)"};}}`,ja=P.css`svg{width:${({$iconSize:e})=>e}px;height:${({$iconSize:e})=>e}px;${({$fillColor:e})=>P.css`
|
|
479
479
|
ellipse,
|
|
480
480
|
path {
|
|
481
481
|
fill: ${e};
|
|
@@ -485,7 +485,7 @@
|
|
|
485
485
|
}
|
|
486
486
|
`}
|
|
487
487
|
}
|
|
488
|
-
|
|
488
|
+
`,wy=b.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: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);${({$animated:e})=>e&&Ry}`,Xa=b.default.span.attrs({"aria-hidden":"true"})`
|
|
489
489
|
position: absolute;
|
|
490
490
|
width: 100%;
|
|
491
491
|
height: 100%;
|
|
@@ -495,23 +495,23 @@
|
|
|
495
495
|
display: flex;
|
|
496
496
|
justify-content: center;
|
|
497
497
|
align-items: center;
|
|
498
|
-
`,
|
|
498
|
+
`,ky=b.default(Xa)`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)")};${My}${ja}`,Ly=b.default(Xa)`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)")};${ja}`,Oy=b.default.span.attrs({"aria-hidden":"true"})`
|
|
499
499
|
position: absolute;
|
|
500
500
|
top: 1px;
|
|
501
501
|
inset-inline-end: 1px;
|
|
502
|
-
width: ${
|
|
503
|
-
height: ${
|
|
502
|
+
width: ${Bo}px;
|
|
503
|
+
height: ${Bo}px;
|
|
504
504
|
border-radius: 50%;
|
|
505
|
-
background-color: ${
|
|
506
|
-
`,
|
|
505
|
+
background-color: ${C.themedColor.error};
|
|
506
|
+
`,Ho={Open:e=>e.url?a.createElement("img",{src:e.url,alt:"","data-default-icon":e.isDefaultIcon}):a.createElement(Q,{size:e.size,type:"delight"}),Close:({size:e})=>a.createElement(Q,{size:e,type:"chevron-down"})};function Za({className:e,size:t,entryPoint:n="Conversation",activeRoute:r}){const{colors:s}=P.useTheme(),{chatSDK:o,config:i,dir:c,state:u}=ce(),{resolveElement:d}=Br(),{launcher:m}=se(),{launcherInfo:h}=Ne(),f=i.launcher.unreadBadgeEnabled,g=vi(),p=tm(o,{enabled:f,opened:u.opened,filter:g}),v=(r??n)==="ConversationList",E={launcher:m.button({isOpened:u.opened,opensConversationList:v})};em("launcher_toggle"),Dy();const _=()=>{we(()=>{const T=d(ve.WINDOW),R=T?ea(T):null;R==null||R.focus()})},y=()=>{we(()=>{var T;(T=d(ve.LAUNCHER))==null||T.focus()})},A=()=>{const T=!u.opened;u.setOpened(T),T?_():y()};return a.createElement(Ka,{dir:c,className:e,isOpened:u.opened,onClick:A,type:h.type,imageUrl:h.imageUrl,backgroundColor:s.base.primary,size:t,hasUnread:f&&!u.opened&&p,...E.launcher.props},E.launcher.descriptionNode)}const Ny=1e3*60;function Dy(){const{chatSDK:e,state:t,logger:n,enableAutoDisconnectInLauncher:r}=ce(),s=l.useRef(null);l.useEffect(()=>{if(!r)return;function o(){s.current&&(clearTimeout(s.current),s.current=null)}function i(){e.connectionState===fe.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")},Ny)}t.opened?i():(c(),n.debug("useSDKInactivityTimeout: schedule disconnect"))},[r,e,t.opened])}const Ja=l.createContext(null);function as(){const e=l.useContext(Ja);if(!e)throw new Error("useNavigator() must be used within <Navigator />");return e}function Qa({children:e}){const t=as();return typeof e=="function"?e(t):a.createElement(a.Fragment,null,e)}const $y=P.keyframes`0%{transform:translateY(40px);opacity:0;}100%{transform:translateY(0px);opacity:1;}`,Fy=P.keyframes`0%{transform:translateY(0px);opacity:1;}100%{transform:translateY(40px);opacity:0;}`,Py=P.css`animation-name:${$y};animation-duration:0.3s;animation-fill-mode:forwards;`,Uy=P.css``,By=P.css`animation-name:${Fy};animation-duration:0.3s;animation-fill-mode:forwards;`,Hy=P.css`visibility:hidden;`,Gy=b.default.div`position:absolute;top:0;left:0;width:100%;height:100%;${({$transitionState:e})=>{switch(e){case"entering":return Py;case"entered":return Uy;case"exiting":return By;case"exited":return Hy;default:return""}}}${({$active:e})=>e?P.css`
|
|
507
507
|
z-index: 999;
|
|
508
|
-
`:
|
|
509
|
-
`;function
|
|
508
|
+
`:P.css`z-index:1;pointer-events:none;`}
|
|
509
|
+
`;function pn({initialId:e,children:t}){const[n,r]=l.useState([e]),s=n[n.length-1],o=l.useCallback((E,_)=>{r(y=>[...y,E]),h(y=>({...y,[E]:!0})),_!=null&&_.reset&&v(y=>({...y,[E]:(y[E]||0)+1})),g(y=>({...y,[E]:"entering"})),setTimeout(()=>{g(y=>({...y,[E]:"entered"}))},300)},[]),i=l.useCallback(()=>{r(E=>{if(E.length<=1)return E;const _=E[E.length-1];return g(y=>({...y,[_]:"exiting"})),setTimeout(()=>{g(y=>({...y,[_]:"exited"})),r(y=>y.slice(0,-1))},300),E})},[]),c=l.useMemo(()=>({navigation:{navigate:o,pop:i},activeScreenId:s}),[o,i,s]),u=l.useMemo(()=>l.Children.toArray(t).filter(E=>E.type===Qa),[t]),d=l.useMemo(()=>{const E={};return u.forEach(_=>{const{id:y,lazy:A,children:T}=_.props;E[y]={lazy:A,element:typeof T=="function"?T(c):T}}),E},[u,c]),[m,h]=l.useState(()=>{const E={};return Object.entries(d).forEach(([_,{lazy:y}])=>{y===!1&&(E[_]=!0)}),E[e]=!0,E}),[f,g]=l.useState(()=>{const E={};return Object.keys(d).forEach(_=>{_===e?E[_]="entered":E[_]="exited"}),E}),[p,v]=l.useState({});return a.createElement(Ja.Provider,{value:c},a.createElement(zy,null,Object.keys(d).map(E=>{var T;if(!m[E])return null;const _=f[E]||"exited",y=E===s,A=`${E}-${p[E]||0}`;return a.createElement(Gy,{key:A,$transitionState:_,$active:y,"aria-hidden":y?void 0:!0,inert:y?void 0:!0},(T=d[E])==null?void 0:T.element)})))}const zy=b.default.div`position:relative;width:100%;height:100%;`;pn.Screen=Qa;const qe={conv:"conv",convList:"conv-list"},Vy=e=>e===qe.convList?"ConversationList":"Conversation",qy=({isOpened:e,activeScreenId:t})=>e&&t===qe.conv,ec=({isOpened:e,entryPoint:t,selectedChannelUrl:n,setSelectedChannelUrl:r,onActiveRouteChange:s})=>{const{conversationComponent:o,conversationChildren:i,conversationListComponent:c,conversationListChildren:u}=Qt(),[d,m]=l.useState(),h=(()=>{switch(t){case"Conversation":return qe.conv;case"ConversationList":return qe.convList;default:return qe.conv}})(),f=a.createElement(a.Fragment,null,a.createElement(Yy,{onOpenConversationView:(g,p)=>{r(p),m(void 0),g.navigate(qe.conv)}}),a.createElement(Wy,{onActiveRouteChange:s}));return a.createElement(pn,{initialId:h},a.createElement(pn.Screen,{id:qe.conv},({navigation:g,activeScreenId:p})=>{const v=qy({isOpened:e,activeScreenId:p});return a.createElement(a.Fragment,null,f,a.createElement(o,{key:n,channelUrl:n,onClearChannelUrl:()=>r(void 0),onNavigateToConversationList:()=>{m(void 0),g.navigate(qe.convList)},announcementsEnabled:v,conversationStatsEnabled:v,shouldMarkAsRead:v,initialFocusTarget:d},i))}),a.createElement(pn.Screen,{id:qe.convList,lazy:!0},({navigation:g,activeScreenId:p})=>{const v=e&&p===qe.convList;return a.createElement(a.Fragment,null,f,a.createElement(c,{announcementsEnabled:v,conversationListStatsEnabled:v,onOpenConversationView:(E,_,y)=>{r(E),m(y==null?void 0:y.initialFocusTarget),g.navigate(qe.conv)}},u))}))},Yy=({onOpenConversationView:e})=>{const{registerOnJoinedProactiveConversation:t}=Ne(),{navigation:n}=as();return t(({channel:r})=>{e(n,r.url)}),null},Wy=({onActiveRouteChange:e})=>{const{activeScreenId:t}=as();return l.useEffect(()=>{e==null||e(Vy(t))},[t,e]),null},Ky=({isExpanded:e,isOpened:t,children:n,launcher:r})=>a.createElement(Yr,null,a.createElement(jy,{isExpanded:e,isOpened:t,launcher:r},n)),jy=({isExpanded:e,isOpened:t,children:n,launcher:r})=>{const{dir:s}=ce(),o=l.useRef(null),{hasWindowTitleReference:i,isWindowNameReady:c}=$n();return On(t,o,{nameReady:c}),a.createElement(Xy,null,a.createElement(Zy,{ref:o,dir:s,id:ve.WINDOW,...is(t,i),$isExpanded:e,$isOpened:t},n),r)},Xy=b.default.div`display:flex;flex-direction:column;gap:8px;align-items:flex-end;`,Zy=b.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&&Qy};${({$isExpanded:e})=>e&&Jy};`,Jy=P.css`width:743px;height:723px;`,Qy=P.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;`,eS=l.forwardRef(function({children:e,initialChannelUrl:t,...n},r){const s=Xt(),[o,i]=l.useState(t),[c,u]=l.useState(n.entryPoint??"Conversation"),d=s?Wa:Ky;return a.createElement(os,{enableExpandButton:!s,ref:r,...n},a.createElement(na,null,({state:m})=>a.createElement(Ya,null,a.createElement(d,{isExpanded:m.expanded,isOpened:m.opened,...s&&{zIndex:"auto"},launcher:a.createElement(Za,{entryPoint:n.entryPoint,activeRoute:c})},a.createElement(ec,{isOpened:m.opened,entryPoint:n.entryPoint,selectedChannelUrl:o,setSelectedChannelUrl:i,onActiveRouteChange:u})),e)))}),{Provider:tS,useContext:cs}=Ce("FixedMessengerStyle");function tc(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: ${Xe(i)}`;break;case"end":d=`inset-inline-end: ${Xe(c)}`;break}switch(t){case"top":u=`top: calc(${Xe(s)} + ${r}px)`;break;case"bottom":u=`bottom: calc(${Xe(o)} + ${r}px)`;break}return P.css`${u};${d};`}function nS(e){const{horizontal:t,vertical:n,margin:r,launcherSize:s}=cs();return a.createElement(rS,{...e,size:s,$horizontal:t,$vertical:n,$margin:r})}const rS=b.default(Za)`position:fixed;z-index:${gt.LAUNCHER};${({$horizontal:e,$vertical:t,$margin:n})=>tc(e,t,n)};`,sS=({isExpanded:e,isOpened:t,children:n})=>a.createElement(Yr,null,a.createElement(oS,{isExpanded:e,isOpened:t},n)),oS=({isExpanded:e,isOpened:t,children:n})=>{const{dir:r}=ce(),{horizontal:s,vertical:o,margin:i,launcherSize:c}=cs(),u=l.useRef(null),{hasWindowTitleReference:d,isWindowNameReady:m}=$n();return On(t,u,{nameReady:m}),a.createElement(iS,{ref:u,dir:r,id:ve.WINDOW,...is(t,d),$isExpanded:e,$isOpened:t,$horizontal:s,$vertical:o,$margin:i,$launcherSize:c},n)},iS=b.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})=>tc(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}`};
|
|
510
510
|
[dir='rtl'] &:not([dir='ltr']),
|
|
511
511
|
&[dir='rtl'] {
|
|
512
512
|
transform-origin: ${({$horizontal:e,$vertical:t})=>`${e==="start"?"right":"left"} ${t}`};
|
|
513
513
|
}
|
|
514
514
|
|
|
515
|
-
${({$isOpened:e})=>e&&
|
|
516
|
-
${({$isExpanded:e})=>e&&
|
|
517
|
-
`,
|
|
515
|
+
${({$isOpened:e})=>e&&cS};
|
|
516
|
+
${({$isExpanded:e})=>e&&aS};
|
|
517
|
+
`,aS=P.css`width:743px;height:723px;`,cS=P.css`z-index:${gt.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;`,nc={top:24,bottom:24,start:24,end:24},lS=l.forwardRef(function({children:e,initialChannelUrl:t,...n},r){const[s,o]=l.useState(t),[i,c]=l.useState(n.entryPoint??"Conversation"),[u,d]=l.useState("end-bottom"),[m,h]=l.useState(nc),[f,g]=l.useState(48),p=Xt(),v=p?Wa:sS,{horizontal:E,vertical:_}=l.useMemo(()=>{const[y,A]=u.split("-");return{horizontal:y==="start"?"start":"end",vertical:A==="top"?"top":"bottom"}},[u]);return a.createElement(os,{enableExpandButton:!p,ref:r,...n},a.createElement(na,null,({state:y})=>a.createElement(tS,{value:{horizontal:E,vertical:_,margin:m,launcherSize:f,setPosition:d,setMargin:h,setLauncherSize:g}},a.createElement(Ya,null,a.createElement(v,{isExpanded:y.expanded,isOpened:y.opened},a.createElement(ec,{isOpened:y.opened,entryPoint:n.entryPoint,selectedChannelUrl:s,setSelectedChannelUrl:o,onActiveRouteChange:c})),a.createElement(nS,{entryPoint:n.entryPoint,activeRoute:i}),e))))}),uS=e=>{var s,o,i,c;const{setPosition:t,setMargin:n,setLauncherSize:r}=cs();return l.useLayoutEffect(()=>{e.position&&t(e.position),e.margin&&n({...nc,...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},dS=({children:e})=>{const{setConversationChildren:t}=Qt();return l.useLayoutEffect(()=>(t(e),()=>t(null)),[e]),null},mS=({component:e})=>{const{setConversationComponent:t}=Qt();return l.useLayoutEffect(()=>(t(e),()=>t(ts)),[e,t]),null},hS=({children:e})=>{const{setConversationListChildren:t}=Qt();return l.useLayoutEffect(()=>(t(e),()=>t(null)),[e]),null},fS=({component:e})=>{const{setConversationListComponent:t}=Qt();return l.useLayoutEffect(()=>(t(e),()=>t(ss)),[e,t]),null},gS=Object.assign(lS,{Style:uS,Conversation:mS,ConversationChildren:dS,ConversationList:fS,ConversationListChildren:hS}),pS=e=>{const{refreshActiveChannel:t}=Ne(),[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])};mi.set(fe.SendbirdPlatform.JS,{deviceOSPlatform:Mc()?fe.DeviceOsPlatform.MOBILE_WEB:fe.DeviceOsPlatform.WEB,messengerVersion:Vm,keyValueStorage:Wm(),networkStateAdapter:Ym(),scheduleForegroundTask:qm});exports.ANCHOR_REL=Ur;exports.AgentProviderContainer=os;exports.AgentUIProviderContainer=Va;exports.AnonymousSessionInfo=ar;exports.CSATType=Je;exports.Commands=it;exports.ConnectionDelayLayout=Nn;exports.Conversation=ts;exports.ConversationContext=Mf;exports.ConversationContextProvider=aa;exports.ConversationHeaderLayout=Et;exports.ConversationLayout=Hn;exports.ConversationList=ss;exports.ConversationListContext=Uv;exports.ConversationListContextProvider=za;exports.ConversationListHeaderLayout=Mt;exports.ConversationListItemLayout=rs;exports.ConversationListLayout=Gn;exports.DefaultMessenger=eS;exports.DeskTicketPriority=kr;exports.DeskTicketStatus=wr;exports.FixedMessenger=gS;exports.ID_INCOMING=et;exports.IncomingMessageLayout=_t;exports.LauncherBase=Ka;exports.LogLevel=Tr;exports.ManualSessionInfo=ti;exports.MessageListUILayout=Bn;exports.MessageLogs=Na;exports.OutgoingMessageLayout=xt;exports.PlaceholderLayout=Un;exports.SystemMessageLayout=Pn;exports.cssVars=C;exports.escapeMarkdownSyntax=xc;exports.flattenObject=xl;exports.mapCommonStringsToReactFormat=Gi;exports.messengerDispatcher=qa;exports.noop=le;exports.parseToMessageTemplate=ui;exports.parseToUITemplate=Tl;exports.pickColorByTheme=Il;exports.replaceVariablesAsync=Ml;exports.replaceVariablesSync=Rl;exports.useAIAgentContext=ke;exports.useConversationContext=Te;exports.useConversationListContext=Jt;exports.useLocalizationContext=ae;exports.useMessageTemplateFetchingContext=vd;exports.useMessengerContext=ce;exports.useMessengerSessionContext=Ne;exports.useMessengerThemeContext=Ki;exports.useRefreshActiveChannel=pS;
|