@sendbird/ai-agent-messenger-react 1.29.0 → 1.30.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/cjs/{h1huMI7F.cjs → BMDJStMQ.cjs} +1 -1
- package/dist/cjs/{B7ulsf2M.cjs → CLIpC7kY.cjs} +1 -1
- package/dist/cjs/{BeAZATeH.cjs → CPZf2TWM.cjs} +1 -1
- package/dist/cjs/{BVmiN3Wy.cjs → ChrM6HN1.cjs} +1 -1
- package/dist/cjs/{Dl7xer_X.cjs → D7UQ9OK7.cjs} +1 -1
- package/dist/cjs/{CjZUGQLK.cjs → DKQwAy8C.cjs} +1 -1
- package/dist/cjs/{ByN4PZlT.cjs → D_km8dcd.cjs} +1 -1
- package/dist/cjs/{BrQW3MrE.cjs → I-l-5Zo-.cjs} +1 -1
- package/dist/cjs/{BSS6fNF-.cjs → etCQgYrr.cjs} +1 -1
- package/dist/es/{ahIfmQ8u.js → BDCT28XM.js} +1 -1
- package/dist/es/{CMs_SQSN.js → BWCZN9kg.js} +1 -1
- package/dist/es/{CxcLZ0g9.js → C5fUw0RP.js} +1 -1
- package/dist/es/{BmrXsz9f.js → CZXgaS-3.js} +1 -1
- package/dist/es/{BuGgkwTL.js → DbWklFH0.js} +1 -1
- package/dist/es/{zRUBdEcH.js → Dh05zfqw.js} +1 -1
- package/dist/es/{BP9Kjsra.js → FMOCAKFw.js} +1 -1
- package/dist/es/{DFE9WxEE.js → RwjGyHFV.js} +1 -1
- package/dist/es/{BSsMjwta.js → hPxGrQQg.js} +1 -1
- package/dist/index.cjs +151 -151
- package/dist/index.d.ts +53 -9
- package/dist/index.js +3245 -3180
- package/package.json +2 -2
package/dist/index.cjs
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
"use strict";var ia=Object.defineProperty;var aa=(e,t,n)=>t in e?ia(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var S=(e,t,n)=>aa(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ge=require("@sendbird/chat"),u=require("react"),D=require("styled-components"),Xe=require("date-fns"),la=require("date-fns/locale/en-US"),Be=require("@sendbird/chat/message"),ca=require("react-dom"),be=require("@sendbird/chat/aiAgent"),ze=require("@sendbird/chat/groupChannel"),ua=require("date-fns/isSameDay"),da=require("dompurify"),er=e=>e&&e.__esModule?e:{default:e};function ma(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 fa=er(ge),i=ma(u),p=er(D),is=er(da),ct="sb-agent",as="KEY_IMG_ASPECT_RATIO",Fn="*/*",ne={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 Zt=(e=>(e.IN_PROGRESS="IN_PROGRESS",e.COMPLETED="COMPLETED",e.CANCELED="CANCELED",e))(Zt||{}),xt=(e=>(e.IN_PROGRESS="IN_PROGRESS",e.COMPLETED="COMPLETED",e.CANCELED="CANCELED",e))(xt||{});const ls=e=>{var t;return!!((t=e==null?void 0:e.extendedMessagePayload)!=null&&t.steward)},ha=e=>e===xt.COMPLETED||e===xt.CANCELED?e:xt.IN_PROGRESS,yn=e=>Qe(e)&&!ls(e),Qe=e=>!!e&&"sender"in e,ga=e=>Qe(e)?e.sendingStatus==="succeeded"?String(e.messageId):e.reqId:String(e.messageId),pa=(e,t,n,r=!0)=>{if(!r||!yn(e))return"single";const o=()=>{if(!yn(t))return!1;const c=t.sender.userId===e.sender.userId,d=Xe.isSameMinute(t.createdAt,e.createdAt);return c&&d},s=()=>{if(!yn(n))return!1;const c=n.sender.userId===e.sender.userId,d=Xe.isSameMinute(n.createdAt,e.createdAt);return c&&d},a=o(),l=s();return a&&l?"middle":a?"bottom":l?"top":"single"},ft=(e,t)=>(()=>{var r;return Qe(e)?e.sender.userId:((r=e==null?void 0:e.sender)==null?void 0:r.userId)??void 0})()===t,Ie={isAdmin:e=>e.isAdminMessage(),isCSAT:e=>{var t;return e.isAdminMessage()&&!!((t=e.extendedMessagePayload)!=null&&t.csat)},isSteward:e=>ls(e),isIncoming:(e,t)=>Qe(e)&&e.sender.userId!==t,isOutgoing:(e,t)=>Qe(e)&&(e.sender.userId===t||e.sendingStatus===Be.SendingStatus.PENDING)},He=e=>e.startsWith("image/"),cn=e=>e.startsWith("video/"),cs=({name:e="",mimeType:t=""})=>t==="application/pdf"||/\.pdf$/i.test(e.trim()),tr=(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"},us=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},un=e=>{switch(e){case"top":case"middle":return ne.GAP_GROUPED;default:return ne.GAP_UNGROUPED}},_a=(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},Ea=e=>e.replace(/\[([^\]]+)\](?!\()/g,"\\[$1\\]"),ba=e=>e.replace(/([a-zA-Z0-9])_(?=[a-zA-Z0-9])/g,"$1\\_"),Ca=e=>e.replace(/~~/g,"\\~\\~"),va=e=>{let t=e;return t=Ea(t),t=ba(t),t=Ca(t),t},ya=typeof navigator<"u"&&navigator.product==="ReactNative",Br=(e,t)=>{const n=r=>!t||t.length===0?!0:Qe(r)&&t.includes(r.sendingStatus);return ya?e.find(n):e.findLast(n)};function he(){}function Sa(){const e=typeof navigator<"u"?navigator.userAgent:"",t=/iPad|iPhone|iPod/.test(e),n=/Android/.test(e);return t||n}function Aa(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 Bn=e=>{try{return JSON.parse(e===""?"{}":e)}catch{return{}}},Ve={isStreaming(e){const t=Bn(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(ft(e,t)){const r=Bn(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)}},Sn=`@${ct}`,xa=({appId:e,aiAgentId:t,storage:n})=>{const r={templateBase:`${Sn}-template`,template:o=>`${r.templateBase}/templates/${o}`,templateToken:()=>`${r.templateBase}/tokens`,messengerSession:o=>{const s=Aa(`${e}/${t}/${o}`);return`${Sn}-udata/${s}`},anonUserSession:()=>`${Sn}-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}}}}},ds=(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},Ta=()=>{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 Ia{constructor(t){S(this,"_params");this._params={aiAgentChannelFilter:(t==null?void 0:t.aiAgentChannelFilter)??be.AIAgentChannelFilter.INCLUDE,aiAgentConversationStatusFilter:(t==null?void 0:t.aiAgentConversationStatusFilter)??[be.ConversationStatus.OPEN,be.ConversationStatus.CLOSED],aiAgentIds:(t==null?void 0:t.aiAgentIds)??[],deskChannelFilter:(t==null?void 0:t.deskChannelFilter)??be.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===be.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!==be.DeskChannelFilter.EXCLUDE:!1}}class ms extends ze.BaseChannelCollection{constructor(n,r){const o=new Ia(r.filter),s=n,a=s.aiAgent._manager,l=r.limit??20,c=ze.GroupChannelListOrder.LATEST_LAST_MESSAGE,d={getRemoteChannels:(m,f,h,_)=>a.getMyGroupChannels(m,f.params,_),changeLogSync:m=>{const{aiAgentChannelFilter:f,aiAgentIds:h,deskChannelFilter:_,pinnedChannelUrls:y,copilotConversationOnly:C,copilotSupportChannelUrl:v}=o.params,b={aiAgentChannelFilter:f,aiAgentIds:h,deskChannelFilter:_,pinnedChannelUrls:y,copilotConversationOnly:C,copilotSupportChannelUrl:v};return a.getMyGroupChannelChangeLogs(m,b,ze.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-${Ta()}`,this._throttledOnChannelChanged=ds(()=>{var _;const m=[...this._pendingChannels];this._pendingChannels=[];const f=new Map;for(const{channel:y,context:C}of m)f.delete(y.url),f.set(y.url,{channel:y,context:C});const h=new Map;for(const{channel:y,context:C}of f.values())h.has(C)||h.set(C,new Map),h.get(C).set(y.url,y);for(const[y,C]of h){const v=Array.from(C.values()),b=(_=this._sdk.currentUser)==null?void 0:_.userId,E=v.filter(x=>this.filter.match(x,b)),A=v.filter(x=>!this.filter.match(x,b)).map(x=>x.url);E.length>0&&this._base._addChannelsToView(E,y,!1),A.length>0&&this._removeChannels(A,y)}},250,{trailing:!0,leading:!0}),this._base._subscribeChannelEvent(this._key,{onUpdate:(m,f)=>{for(const h of m)this._pendingChannels.push({channel:h,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 fs{constructor(t){S(this,"subscribers",{});this.logger=t}async send(t){const n=wa(),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 wa=()=>{let e=he,t=he;return{promise:new Promise((r,o)=>{e=r,t=o}),resolve:e,reject:t}};var Fe=(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))(Fe||{});class kt{constructor(t={}){S(this,"payload");this.payload=t}toJSON(){return JSON.stringify({type:this.type,payload:this.payload})}}const Ze={CloseConversation:e=>new Ma(e),MessengerSettingsUpdated:e=>new ka(e),ActiveChannelUpdated:e=>new Ra(e),AnonymousSessionTokenExpired:()=>new La,AuthTokenRefreshed:()=>new Oa};class Ma extends kt{constructor(){super(...arguments);S(this,"type","conv.close")}}class ka extends kt{constructor(){super(...arguments);S(this,"type","messenger.settings.updated")}}class Ra extends kt{constructor(){super(...arguments);S(this,"type","active.channel.updated")}}class La extends kt{constructor(){super(...arguments);S(this,"type","anon.token.expired")}}class Oa extends kt{constructor(){super(...arguments);S(this,"type","auth.token.refreshed")}}var nr=(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))(nr||{});class hs{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 gs{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 Un{constructor(){S(this,"userId");S(this,"authToken");S(this,"sessionHandler")}}const Na=e=>({onSessionTokenRequired:t=>{t(null),e.send(Ze.AnonymousSessionTokenExpired())}}),Da="ai_agent:stats",$a="conversation_initial_render",Pa=800220;var ve=(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))(ve||{});class Fa{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??Pa,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(Da,t)):!1}}class Ba extends Fa{constructor(){super(...arguments);S(this,"presentMethod","direct_present")}setPresentMethod(n){return this.presentMethod=n,this}getMetricKey(){return $a}buildPayload(){const n=this.getDuration(ve.AUTH),r=this.getDuration(ve.GET_CHANNEL),o=this.getDuration(ve.GET_MESSAGES),s=this.getDuration(ve.TOTAL_DURATION_FROM_CACHE),a=this.getDuration(ve.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 Ua{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 Ba().setCommitCallback(this.commitCallback).setPresentMethod(this.presentMethod)),this.stats}onAuthStart(){this.getOrCreateStats().startTimer(ve.TOTAL_DURATION).startTimer(ve.TOTAL_DURATION_FROM_CACHE).startTimer(ve.AUTH)}onAuthComplete(){var t;(t=this.stats)==null||t.stopTimer(ve.AUTH)}onAuthError(t){this.stats&&!this.stats.isCommitted()&&this.stats.stopTimer(ve.AUTH).setError(t instanceof ge.SendbirdError?t.code:void 0,t.message).stopTimer(ve.TOTAL_DURATION).commit()}onGetChannelStart(){var t;(t=this.stats)==null||t.startTimer(ve.GET_CHANNEL)}onGetChannelComplete(t){this.stats&&(this.stats.stopTimer(ve.GET_CHANNEL),t!==void 0&&this.stats.setConversationId(t),this.stats.startTimer(ve.GET_MESSAGES))}onGetChannelError(t){this.stats&&!this.stats.isCommitted()&&this.stats.stopTimer(ve.GET_CHANNEL).setError(t instanceof ge.SendbirdError?t.code:void 0,t.message).stopTimer(ve.TOTAL_DURATION).commit()}onCacheResult(t){this.stats&&!this.stats.isCommitted()&&(t&&this.stats.setError(t instanceof ge.SendbirdError?t.code:void 0,t.message),this.stats.stopTimer(ve.TOTAL_DURATION_FROM_CACHE))}onApiResult(t){this.stats&&!this.stats.isCommitted()&&(t&&this.stats.setError(t instanceof ge.SendbirdError?t.code:void 0,t.message),this.stats.stopTimer(ve.TOTAL_DURATION).stopTimer(ve.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 Ha(){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 ps=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0)),Ur={isTalkToAgentViewEnabled:!0,scrollMode:"auto",newMessageIndicatorEnabled:!0,senderAvatarEnabled:!0},rr={conversation:{...Ur,messageAlertSoundEnabled:!1,list:{...Ur,markdownImageRenderMode:"default"},header:{avatarEnabled:!0},input:{camera:{photoEnabled:!0},gallery:{photoEnabled:!0},fileEnabled:!0},fileViewer:{downloadEnabled:!0}},launcher:{unreadBadgeEnabled:!1}},Hr=e=>e?{conversation:za(e.conversation),launcher:Ga(e.launcher)}:rr,Ga=e=>ut(rr.launcher,e),za=e=>{const t=rr.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);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,ps(r));return n},Va=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}),Ya=e=>({type:e.image_type||"default_icon",imageUrl:e.image_url}),Hn=e=>({enabled:e.enabled,showIndicator:e.show_indicator,toggleAllowed:e.toggle_allowed,deleteOnOff:e.delete_on_off,consentDialog:e.consent_dialog}),_s=(e,t)=>{if(e)return e.members.filter(n=>n.userId!==t).sort((n,r)=>r.joinedAt-n.joinedAt)[0]},Re=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===be.ConversationStatus.CLOSED||e!=null&&e.isDesk&&((n=e==null?void 0:e.helpdeskInfo)==null?void 0:n.ticketStatus)==="closed")},or=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===be.ConversationStatus.OPEN||e!=null&&e.isDesk&&((n=e==null?void 0:e.helpdeskInfo)==null?void 0:n.ticketStatus)==="open")};function et(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 Wa(e){var r;const t=(r=e==null?void 0:e.conversation)==null?void 0:r.handoff;return t?typeof t.requestedAt=="number"&&!et(e):!1}function qa(e){var t;if(((t=e==null?void 0:e.resolution)==null?void 0:t.determinedBy)==="user")return e.resolution.isResolved}function Es(e){return!!e&&e<=Date.now()}function Ka(e){return!e.title}function ja(e,t){var n;if(e)return Ka(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 Xa{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=ds(o=>{var s,a;(a=this._session)==null||a._updateActiveChannel({url:o.url,status:Re(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 ze.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 ge.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:Re(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(Fe.MessengerSettingsUpdated,t),()=>{this._dispatcher.unsubscribe(Fe.MessengerSettingsUpdated,t)}));S(this,"onActiveChannelUpdated",t=>(this._dispatcher.subscribe(Fe.ActiveChannelUpdated,t),()=>{this._dispatcher.unsubscribe(Fe.ActiveChannelUpdated,t)}));S(this,"onAuthTokenRefreshed",t=>(this._dispatcher.subscribe(Fe.AuthTokenRefreshed,t),()=>{this._dispatcher.unsubscribe(Fe.AuthTokenRefreshed,t)}))}}class Za{constructor(t){S(this,"_sdkUser");S(this,"_userSession");S(this,"_dispatcher");S(this,"_activeChannel");S(this,"_updateActiveChannel",t=>{this._activeChannel=t,this._dispatcher.send(Ze.ActiveChannelUpdated({channelUrl:t.url,status:t.status,conversationStatus:t.conversationStatus}))});S(this,"_updateAuthToken",t=>{this._userSession.authToken=t,this._dispatcher.send(Ze.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 bs=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)}},Cs=e=>JSON.parse(e),Ja=e=>JSON.parse(e);function Qa(e,t){const[n,r]=t.split(",").map(o=>o.trim());return e==="dark"&&r||n}function el(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 tl({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,bs(l))},e)}async function nl({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,bs(l)),e)}var Gn=(e=>(e[e.EXTERNAL_AUTH_TOKEN_EXPIRED=1]="EXTERNAL_AUTH_TOKEN_EXPIRED",e))(Gn||{});const vs=e=>typeof e=="object"&&e!==null,Gr=(e,t)=>t in e&&typeof e[t]=="string"&&e[t]!=="",rl=e=>!vs(e)||!Gr(e,"channel_url")||!Gr(e,"ai_agent_id")?null:{channelUrl:e.channel_url,aiAgentId:e.ai_agent_id},ol={1:rl};function sl(e){if(!vs(e)||!("cat"in e)||typeof e.cat!="number"||!("data"in e))return null;const t=e.cat,n=ol[t];if(!n)return null;const r=n(e.data);return r?{category:t,data:r}:null}function il(e,t,n,r){const o=fa.default.init({appId:e,modules:[new ze.GroupChannelModule,new be.AIAgentModule],localCacheEnabled:!0,options:new ge.SendbirdChatOptions({typingIndicatorInvalidateTime:2e4}),...r});return o.addSendbirdExtensions([{version:n,product:ge.SendbirdProduct.AI_AGENT,platform:t.platform}],{platform:t.deviceOSPlatform,version:t.deviceOSVersion},t.customData)||console.warn("Invalid Sendbird Extensions",t),o}function al(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 ll=[400300,400301,400302,400310];class sr{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 ge.SessionHandler({...n,onSessionTokenRequired:this._interceptTokenRefresh(n.onSessionTokenRequired,r,o)});this.chatSDK.setSessionHandler(s),this.chatSDK.aiAgent.addEventHandler(Gn.EXTERNAL_AUTH_TOKEN_EXPIRED.toString(),a=>{var c;this._logger.debug("ChatClient.connect: EXTERNAL_AUTH_TOKEN_EXPIRED event received",a);const l=sl(a);(l==null?void 0:l.category)===Gn.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=>ll.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}=Cs(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?(al(t.chatSDK),n=t.chatSDK):n=il(t.appId,t.extensions,t.messengerVersion,t.chatParams),new sr(n,t.logger,t.cache)}}const Pt=new Map,ys={set:(e,t)=>{Pt.set(e,t)},get:e=>{if(Pt.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=Pt.get(e);if(!n)throw new Error(`AIAgent platform "${e}" is not configured.`);return{platform:e,...n}}const t=Pt.entries().next().value;return{platform:t[0],...t[1]}}};class zr 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 ir=(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))(ir||{}),ar=(e=>(e.URGENT="URGENT",e.HIGH="HIGH",e.MEDIUM="MEDIUM",e.LOW="LOW",e))(ar||{}),Ss=(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))(Ss||{});const cl=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,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(!cl(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 zr(t.status,r)}const n=await t.text();if(n)try{return JSON.parse(n)}catch{throw new zr(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 Jt{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 Jt({id:t.id,title:t.channelName??null,status:t.status2??ir.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??ar.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 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 Jt._fromResponse(n,this)});S(this,"createTicket",async t=>{this._assertAuthenticated(this._apiClient);const n=await this._apiClient.request("/tickets/",{method:"POST",body:ps({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 Jt._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 cr{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 cr}}function dl(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 ml=1440*60*1e3,fl=typeof __SBA_USE_DESK_CLIENT__>"u"||__SBA_USE_DESK_CLIENT__;function qe(e){if(!e)throw new Error("Not authenticated. Call authenticate() first.")}function hl(e,t){return Object.entries(t).every(([n,r])=>e[n]===r)}class Qt extends Xa{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",Ha());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(Ze.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 h;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."),h={userId:o.userSessionCandidate.userId,authToken:o.userSessionCandidate.authToken};else{const{user_id:C,session_token:v,expire_at:b}=f.auto_created_user;this._cache.messenger.setAnonUser({userId:C,authToken:v,expireAt:b}),h={userId:C,authToken:v},this._logger.debug("AIAgent.authenticate: anonymous user created",C)}else h={userId:((d=o.userSessionCandidate)==null?void 0:d.userId)??"",authToken:((m=o.userSessionCandidate)==null?void 0:m.authToken)??""};this._cache.messenger.setSettings(h.userId,f),this._dispatcher.send(Ze.MessengerSettingsUpdated({settings:f,source:"server"}));const _=(()=>{var C;return o.type==="anonymous"?Na(this._dispatcher):(C=o.userSessionCandidate)==null?void 0:C.sessionHandler})(),y=await this._chatClient.connect(h,_,C=>{var v;this._logger.debug("AIAgent: session token refreshed"),(v=this._session)==null||v._updateAuthToken(C),this._deskClient.refreshDeskAuthToken(C)},()=>{this._logger.debug("AIAgent: session token unavailable, deauthenticating desk"),this._deskClient.deauthenticate()});return await this._deskClient.authenticate({userId:h.userId,accessToken:h.authToken,onDeskTokenRefreshRequired:async({reason:C})=>{var v;if(C===Ss.ERR_SESSION_KEY_EXPIRED){await new Promise(E=>setTimeout(E,2e3));const b=(v=this._session)==null?void 0:v.userSession.authToken;return b?await this._deskClient.refreshDeskAuthToken(b):!1}return!1}}),(s==null?void 0:s.language)!==f.language&&this._deskClient.setCustomerLanguage(this.language).catch(()=>{}),this._statsTrackers.initialRender.onAuthComplete(),this._session=new Za({sdkUser:y,userSession:h,activeChannel:{url:f.active_channel.channel_url,status:"open"},dispatcher:this._dispatcher}),this._setupChannelHandler(),this._logger.debug("AIAgent.authenticate: end",{userId:h.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=>{qe(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(qe(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:be.ConversationStatus.OPEN,limit:100}),o=[];for(;r.hasNext;){const s=await r.next();for(const a of s)hl(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;qe(this._session),this._logger.debug("AIAgent.closeConversation: start",n);const r=await this._chatClient.getChannel(n);((o=r.conversation)==null?void 0:o.status)===be.ConversationStatus.OPEN?(await r.closeConversation(),this._session.activeChannel.url===n&&this._session._updateActiveChannel({url:n,status:"closed",conversationStatus:be.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 ms(this.chatSDK,n??{}));S(this,"patchContext",async(n,r)=>{qe(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)=>{qe(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=>{qe(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={})=>{qe(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=>{qe(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"),Hn(a);const l=this._cache.messenger.getSettings(s);if(l){const c={...l,memory:a};this._cache.messenger.setSettings(s,c),this._dispatcher.send(Ze.MessengerSettingsUpdated({settings:c,source:"cache"}))}return this._logger.debug("AIAgent.setUserMemoryState: end",a.enabled),Hn(a)});S(this,"refreshActiveChannel",async n=>{var l,c,d;qe(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 gs?{type:"manual",userSessionCandidate:this._getManualSessionInfo(n)}:n instanceof Un?{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-ml<=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 Un)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=Hr(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 Ua((r,o)=>this._chatClient.chatSDK.aiAgent.appendStat(r,o))}}static init(n){var f;const r=ys.get(n.platform),o=n.logger??new hs(n.logLevel??nr.WARN),s=n.dispatcher??new fs(o),a=n.useMMKVStorage?dl(n.useMMKVStorage):r.keyValueStorage,l=n.useMMKVStorage?{...n.chatParams,useMMKVStorageStore:n.useMMKVStorage}:n.chatParams,c=xa({appId:n.appId,aiAgentId:n.aiAgentId,storage:a}),d=sr.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=fl?lr.init({appId:n.appId,logger:o,customApiHost:(f=n.deskParams)==null?void 0:f.customApiHost}):cr.init();return o.debug("AIAgent.init: created",{appId:n.appId,aiAgentId:n.aiAgentId}),new Qt({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=Hr(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 Ee=(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 Ue(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,h)=>d(_=>({..._,[f]:h}))};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 gl(...e){return function({children:n}){return e.reduce((r,o)=>i.createElement(o,null,r),n)}}function pl(e,t){const n=e.lastMessage;return n!=null&&n.isAdminMessage()?n.message??"":As(e,t)}function As(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 _l(e,t,n){var a;const r=new Date,o=new Date(((a=e.lastMessage)==null?void 0:a.createdAt)||e.createdAt),s=Xe.differenceInMinutes(r,o);return s<1?n.justNow:s<60?n.minutesAgo(s):Xe.isToday(o)?n.hoursAgo(Xe.differenceInHours(r,o)):t(o,n.dateShortFormat)}const El=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},Ft=e=>Math.max(0,Math.min(255,e)).toString(16).padStart(2,"0"),Vr=(e,t)=>{const n=Ft(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=El(e);return r?`#${Ft(r[0])}${Ft(r[1])}${Ft(r[2])}${n}`:e},bl=(e,t)=>{if(!t)return e;const n={...e};for(const[r,o]of Object.entries(t))o&&(n[r]=o);return n},Cl=e=>e.consentDialog?"consent":e.toggleAllowed?e.enabled?"on":"off":"readonly",vl=e=>e.length>0,yl=e=>{const t=e[0];if(!t)return e;const n=e.some(o=>He(o.type)),r=e.some(o=>!He(o.type));return n&&r?He(t.type)?e.filter(o=>He(o.type)):[t]:r?[t]:e},Yr=e=>e.length===0?"empty":e.every(t=>He(t.type))?"images":"non_images",Sl=({currentFiles:e,incomingFiles:t,maxAttachmentCount:n})=>{const r=yl(t),o=Yr(e),s=Yr(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,xs=6,Al=e=>e%mt===0?mt:xs,xl=({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?xs/a:1,rowItemCount:a,isLastInRow:l===a-1,isLastRow:s||c}},Ts=Ee("AIAgent"),Tl=Ts.Provider,Me=Ts.useContext;function Il(e){const t=wl(e);return i.createElement(Tl,{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 wl(e){const t=u.useRef(null),n=u.useRef(null);if(!t.current||!n.current)t.current=Qt.init(e);else{const o=Ml(n.current,e);(o.appId||o.aiAgentId||o.chatSDK)&&(t.current.dispose(),t.current=Qt.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 Ml(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 Wr=Symbol("conversationMessageEventBridge"),bt=Symbol("conversationMessageEventPublisher"),kl=(e,t)=>{const n=e;if(n[bt]=t,n[Wr])return e;n[Wr]=!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[bt])==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[bt])==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 h;d(m,f),(h=n[bt])==null||h.call(n,{kind:"initialized",source:"cache",messages:f??[]})}),a.onApiResult=d=>c((m,f)=>{var h;d(m,f),(h=n[bt])==null||h.call(n,{kind:"initialized",source:"api",messages:f??[]})}),a},e},dn=()=>{const[,e]=u.useState(0);return u.useCallback(()=>e(t=>t+1),[])};let Rl=0;function Ll(){return u.useState(()=>`${Rl++}`)[0]}const ht=(e,t,n)=>{const r=u.useRef(t),s=Ll();r.current=t,u.useEffect(()=>{var l;const a=c=>{const d=c;return Object.keys(d).forEach(f=>{d[f]=(...h)=>{var y;const _=r.current;(y=_[f])==null||y.call(_,...h)}}),d};return(l=e==null?void 0:e.groupChannel)==null||l.addGroupChannelHandler(s,a(new ze.GroupChannelHandler)),()=>{var c;(c=e==null?void 0:e.groupChannel)==null||c.removeGroupChannelHandler(s)}},[e==null?void 0:e.groupChannel,s])};function Ol(e,t){return!e||!t?!0:e.url!==t.url}function De(e){return e!=null&&"sendingStatus"in e}function Nl(e,t="##__USER_ID_IS_NOT_PROVIDED__##"){var n;return De(e)?((n=e.sender)==null?void 0:n.userId)===t:!1}function Dl(e,t){return Nl(e,t)||e.isAdminMessage()?!1:e.updatedAt===0}function qr(e){return"sendingStatus"in e?e.sendingStatus==="succeeded"?String(e.messageId):e.reqId:String(e.messageId)}const en={collection:{groupChannel:{defaultOrder:ze.GroupChannelListOrder.LATEST_LAST_MESSAGE},message:{defaultLimit:{next:25,prev:25},searchLimit:{next:10,prev:10}}}};function Kr(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 $l=({...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=Pl(t.value.messages);else{const n={...e.messageMap},r=[],o=[];t.value.messages.forEach(s=>{const a=De(s)?s.reqId:void 0,l=s.messageId||void 0;[a,l].forEach(c=>{if(!c)return;const d=n[c];Fl(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=>{De(s)&&delete n[s.reqId],delete n[s.messageId]}),o.forEach(s=>{De(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=>Dl(o,n));return t.value.clearBeforeAction?e.newMessageMap=jr(r,qr):(r.map(s=>s.messageId).forEach(s=>delete e.newMessageMap[s]),e.newMessageMap={...e.newMessageMap,...jr(r,qr)}),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&&(De(o)&&delete e[n][o.reqId],delete e[n][o.messageId])}),t.value.reqIds.forEach(r=>{const o=e[n][r];o&&(De(o)&&delete e[n][o.reqId],delete e[n][o.messageId])}),e}}},Pl=e=>e.reduce((t,n)=>(De(n)?(t[n.reqId]=n,n.sendingStatus===Be.SendingStatus.SUCCEEDED&&(t[n.messageId]=n)):t[n.messageId]=n,t),{}),Fl=(e,t,n=!1)=>{var r,o;if(!De(e)||!De(t))return!0;if(n&&e&&Zr(e)&&Zr(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===Be.SendingStatus.SUCCEEDED?t.sendingStatus===Be.SendingStatus.SUCCEEDED:e.sendingStatus!==t.sendingStatus},Bl=(e=Ul)=>{const[{initialized:t,loading:n,refreshing:r,messageMap:o,newMessageMap:s},a]=u.useReducer($l,{initialized:!1,loading:!0,refreshing:!1,messageMap:{},newMessageMap:{}}),l=(v,b,E,A)=>{a({type:"update_messages",value:{messages:v,clearBeforeAction:b,currentUserId:E,strictStreamingOrder:A}})},c=(v,b)=>{a({type:"delete_messages",value:{messageIds:v,reqIds:b}})},d=(v,b,E)=>{a({type:"update_new_messages",value:{messages:v,clearBeforeAction:b,currentUserId:E}})},m=(v,b)=>{a({type:"delete_new_messages",value:{messageIds:v,reqIds:b}})},f=v=>{a({type:"update_initialized",value:{status:v}})},h=v=>{a({type:"update_loading",value:{status:v}})},_=v=>{a({type:"update_refreshing",value:{status:v}})},y=Object.values(s),C=u.useMemo(()=>Array.from(new Set(Object.values(o))).sort(e),[o]);return{updateInitialized:f,updateLoading:h,updateRefreshing:_,updateMessages:l,deleteMessages:c,initialized:t,loading:n,refreshing:r,messages:C,newMessages:y,updateNewMessages:d,deleteNewMessages:m}},Xr=Math.floor(Number.MAX_SAFE_INTEGER/10);function Ul(e,t){let n=0,r=0;return De(e)&&e.sendingStatus!=="succeeded"&&(n=Xr),De(t)&&t.sendingStatus!=="succeeded"&&(r=Xr),e.createdAt+n-(t.createdAt+r)}function Zr(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 Hl=(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 ze.MessageFilter(r)})};function Jr(e){return e<Date.now()?en.collection.message.searchLimit:en.collection.message.defaultLimit}const Gl=(e,t,n={})=>{var Oe,ke;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=Jr(a),c=r.current.strictStreamingOrder??!1,d=u.useRef({prev:!1,next:!1}),m=dn(),f=u.useRef({initialized:!1,apiInitialized:!1,instance:null}),{initialized:h,loading:_,refreshing:y,messages:C,newMessages:v,updateMessages:b,updateNewMessages:E,deleteNewMessages:A,deleteMessages:x,updateInitialized:k,updateLoading:R,updateRefreshing:I}=Bl(n==null?void 0:n.sortComparator),w=ye(T=>{var M,N,j,B;if(!o.current||!o.current.url)return(M=s==null?void 0:s.error)==null?void 0:M.call(s,"[useGroupChannelMessages] channel is required");try{switch(T){case ge.CollectionEventSource.EVENT_MESSAGE_RECEIVED:case ge.CollectionEventSource.EVENT_MESSAGE_SENT_SUCCESS:case ge.CollectionEventSource.SYNC_MESSAGE_FILL:case void 0:(j=(N=r.current).markAsRead)==null||j.call(N,[o.current]);break}}catch(z){(B=s==null?void 0:s.warn)==null||B.call(s,"[useGroupChannelMessages/markAsReadBySource]",z)}}),O=ye((T,M)=>{var N,j,B,z,U;if(M.length>0)switch(T){case ge.CollectionEventSource.EVENT_MESSAGE_RECEIVED:case ge.CollectionEventSource.SYNC_MESSAGE_FILL:{(j=(N=r.current).shouldCountNewMessages)!=null&&j.call(N)&&E(M,!1,(B=e.currentUser)==null?void 0:B.userId),(U=(z=r.current).onMessagesReceived)==null||U.call(z,M);break}}}),$=ye(T=>{var M,N;(N=(M=r.current).onCollectionEvent)==null||N.call(M,T)}),V=ye(async(T,M,N)=>new Promise((j,B)=>{var $e;f.current.instance&&f.current.instance.dispose(),w(),E([],!0,($e=e.currentUser)==null?void 0:$e.userId);const z=()=>{var ie,re;const{pendingMessages:ae,failedMessages:te}=f.current.instance??{};Kr(ae)&&b(ae,!1,(ie=e.currentUser)==null?void 0:ie.userId),Kr(te)&&b(te,!1,(re=e.currentUser)==null?void 0:re.userId)},U=Hl(T,N,{...r.current,startingPoint:M});f.current={apiInitialized:!1,initialized:!1,instance:U},U.setMessageCollectionHandler({onMessagesAdded:(ae,te,ie)=>{var re;w(ae.source),O(ae.source,ie),b(ie,!1,(re=e.currentUser)==null?void 0:re.userId,c),$({kind:"messagesAdded",source:ae.source,messages:ie})},onMessagesUpdated:(ae,te,ie)=>{var re,Z,le;w(ae.source),O(ae.source,ie),b(ie,!1,(re=e.currentUser)==null?void 0:re.userId,c),ae.source===ge.CollectionEventSource.EVENT_MESSAGE_UPDATED&&((le=(Z=r.current).onMessagesUpdated)==null||le.call(Z,ie)),$({kind:"messagesUpdated",source:ae.source,messages:ie})},onMessagesDeleted:(ae,te,ie,re)=>{const Z=re.map(pe=>pe.messageId),le=re.filter(De).map(pe=>pe.reqId);x(Z,le),A(Z,le),$({kind:"messagesDeleted",source:ae.source,messages:re})},onChannelDeleted:(ae,te)=>{var ie,re;(re=(ie=r.current).onChannelDeleted)==null||re.call(ie,te)},onChannelUpdated:(ae,te)=>{var ie,re;m(),(re=(ie=r.current).onChannelUpdated)==null||re.call(ie,te,ae)},onHugeGapDetected:()=>{V(T,Number.MAX_SAFE_INTEGER,en.collection.message.defaultLimit)}});let ue=!1;U.initialize(ze.MessageCollectionInitPolicy.CACHE_AND_REPLACE_BY_API).onCacheResult((ae,te)=>{var ie,re,Z,le,pe;(re=(ie=r.current).onCacheResult)==null||re.call(ie,ae,te??[]),ae?(e.isCacheEnabled&&((Z=s==null?void 0:s.error)==null||Z.call(s,"[useGroupChannelMessages/onCacheResult]",ae)),ue=!0):te&&((le=s==null?void 0:s.debug)==null||le.call(s,"[useGroupChannelMessages/onCacheResult]","message length:",te.length),b(U.succeededMessages,!0,(pe=e.currentUser)==null?void 0:pe.userId),z(),te.length>0&&(f.current.initialized=!0,j())),$({kind:"initialized",source:"cache",messages:te??[]})}).onApiResult((ae,te)=>{var ie,re,Z,le,pe,rt,ot;(re=(ie=r.current).onApiResult)==null||re.call(ie,ae,te??[]),f.current.initialized=!0,f.current.apiInitialized=!0,ae?((Z=s==null?void 0:s.warn)==null||Z.call(s,"[useGroupChannelMessages/onApiResult]",ae),ue?B(ae):j()):te&&((le=s==null?void 0:s.debug)==null||le.call(s,"[useGroupChannelMessages/onApiResult]","message length:",te.length),b(U.succeededMessages,!0,(pe=e.currentUser)==null?void 0:pe.userId),r.current.startingPoint||(ot=(rt=r.current).onMessagesReceived)==null||ot.call(rt,te),e.isCacheEnabled&&z(),j()),$({kind:"initialized",source:"api",messages:te??[]})})}));ht(e,{onUserBanned(T,M){var N,j,B;T.isGroupChannel()&&!Ol(T,o.current)&&(M.userId===((N=e.currentUser)==null?void 0:N.userId)?(B=(j=r.current).onCurrentUserBanned)==null||B.call(j):m())}}),u.useLayoutEffect(()=>{const T=setTimeout(async()=>{e.currentUser&&o.current&&(k(!1),R(!0),await V(o.current,a,l),R(!1),k(!0))});return()=>clearTimeout(T)},[e,(Oe=e.currentUser)==null?void 0:Oe.userId,(ke=o.current)==null?void 0:ke.url,r.current.replyType]),u.useEffect(()=>()=>{f.current.instance&&f.current.instance.dispose()},[]);const H=ye(async()=>{e.currentUser&&o.current&&(I(!0),await V(o.current,Number.MAX_SAFE_INTEGER,en.collection.message.defaultLimit),I(!1))}),Y=ye(async()=>{var M;const T=f.current.instance;if(T!=null&&T.hasPrevious&&!d.current.prev)try{d.current.prev=!0;const N=await T.loadPrevious();b(N,!1,(M=e.currentUser)==null?void 0:M.userId)}catch{}finally{d.current.prev=!1}}),G=ye(()=>{const{initialized:T,instance:M}=f.current;return T&&M?M.hasPrevious:!1}),W=ye(async()=>{var M;const T=f.current.instance;if(T!=null&&T.hasNext&&!d.current.next)try{d.current.next=!0;const N=await T.loadNext();b(N,!1,(M=e.currentUser)==null?void 0:M.userId)}catch{}finally{d.current.next=!1}}),q=ye(()=>{const{initialized:T,apiInitialized:M,instance:N}=f.current;return M&&T&&N?N.hasNext:!1}),ce=ye((T,M)=>{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((j,B)=>{o.current.sendUserMessage(T).onPending(z=>{var U;z.channelUrl===o.current.url&&b([z],!1,(U=e.currentUser)==null?void 0:U.userId),M==null||M(z)}).onSucceeded(z=>{var U;z.channelUrl===o.current.url&&b([z],!1,(U=e.currentUser)==null?void 0:U.userId),j(z)}).onFailed((z,U)=>{var ue;U&&U.channelUrl===o.current.url&&b([U],!1,(ue=e.currentUser)==null?void 0:ue.userId),B(z)})})}),_e=ye((T,M)=>{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((j,B)=>{o.current.sendFileMessage(T).onPending(z=>{var U;z.channelUrl===o.current.url&&b([z],!1,(U=e.currentUser)==null?void 0:U.userId),M==null||M(z)}).onSucceeded(z=>{var U;z.channelUrl===o.current.url&&b([z],!1,(U=e.currentUser)==null?void 0:U.userId),j(z)}).onFailed((z,U)=>{var ue;U&&U.channelUrl===o.current.url&&b([U],!1,(ue=e.currentUser)==null?void 0:ue.userId),B(z)})})}),L=ye(async(T,M)=>{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(j=>{const B=[];o.current.sendFileMessages(T).onPending(z=>{var U;z.channelUrl===o.current.url&&b([z],!1,(U=e.currentUser)==null?void 0:U.userId),M==null||M(z)}).onSucceeded(z=>{var U;z.isFileMessage()&&z.channelUrl===o.current.url&&(b([z],!1,(U=e.currentUser)==null?void 0:U.userId),B.push(z)),B.length===T.length&&j(B)}).onFailed((z,U)=>{var ue;U&&U.channelUrl===o.current.url?(b([U],!1,(ue=e.currentUser)==null?void 0:ue.userId),B.push(U)):B.push(null),B.length===T.length&&j(B)})})}),X=ye((T,M)=>{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((j,B)=>{o.current.sendMultipleFilesMessage(T).onPending(z=>{var U;z.channelUrl===o.current.url&&b([z],!1,(U=e.currentUser)==null?void 0:U.userId),M==null||M(z)}).onFileUploaded(()=>{m()}).onSucceeded(z=>{var U;z.channelUrl===o.current.url&&b([z],!1,(U=e.currentUser)==null?void 0:U.userId),j(z)}).onFailed((z,U)=>{var ue;U&&U.channelUrl===o.current.url&&b([U],!1,(ue=e.currentUser)==null?void 0:ue.userId),B(z)})})}),K=ye(async(T,M)=>{var j,B;if(!o.current||!o.current.url)throw(j=s==null?void 0:s.error)==null||j.call(s,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");const N=await o.current.updateUserMessage(T,M);return N.channelUrl===o.current.url&&b([N],!1,(B=e.currentUser)==null?void 0:B.userId),N}),F=ye(async(T,M)=>{var j,B;if(!o.current||!o.current.url)throw(j=s==null?void 0:s.error)==null||j.call(s,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");const N=await o.current.updateFileMessage(T,M);return N.channelUrl===o.current.url&&b([N],!1,(B=e.currentUser)==null?void 0:B.userId),N}),ee=ye(async T=>{var M;if(!o.current||!o.current.url)throw(M=s==null?void 0:s.error)==null||M.call(s,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((N,j)=>{let B;T.isUserMessage()&&(B=o.current.resendMessage(T)),T.isFileMessage()&&(B=o.current.resendMessage(T)),T.isMultipleFilesMessage()&&(B=o.current.resendMessage(T)),B&&("onPending"in B&&B.onPending(z=>{var U;z.channelUrl===o.current.url&&b([z],!1,(U=e.currentUser)==null?void 0:U.userId)}),"onFileUploaded"in B&&B.onFileUploaded(()=>{m()}),"onSucceeded"in B&&B.onSucceeded(z=>{var U;z.channelUrl===o.current.url&&b([z],!1,(U=e.currentUser)==null?void 0:U.userId),N(z)}),"onFailed"in B&&B.onFailed((z,U)=>{var ue;U&&U.channelUrl===o.current.url&&b([U],!1,(ue=e.currentUser)==null?void 0:ue.userId),j(z)}))})}),de=ye(async T=>{var M,N;if(!o.current||!o.current.url)throw(M=s==null?void 0:s.error)==null||M.call(s,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");if(T.sendingStatus==="succeeded")T.isUserMessage()&&await o.current.deleteMessage(T),T.isFileMessage()&&await o.current.deleteMessage(T),T.isMultipleFilesMessage()&&await o.current.deleteMessage(T);else try{await((N=f.current.instance)==null?void 0:N.removeFailedMessage(T.reqId))}finally{x([],[T.reqId])}}),fe=ye(()=>{var T;E([],!0,(T=e.currentUser)==null?void 0:T.userId)}),xe=ye(async T=>{var M;if(e.currentUser&&o.current){const N=Jr(T);R(!0),b([],!0,(M=e.currentUser)==null?void 0:M.userId),await V(o.current,T,N),R(!1)}});return{initialized:h,loading:_,refreshing:y,messages:C,newMessages:v,resetNewMessages:fe,refresh:H,loadPrevious:Y,hasPrevious:G,loadNext:W,hasNext:q,sendUserMessage:ce,sendFileMessage:_e,sendFileMessages:L,sendMultipleFilesMessage:X,updateUserMessage:K,updateFileMessage:F,resendMessage:ee,deleteMessage:de,resetWithStartingPoint:xe,_dangerous_reducer_updateMessages:b,_dangerous_reducer_deleteMessages:x}},zl=(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 ze.MessageFilter(d)}));if(!m)throw new Error("Group channel is required to create a message collection");return kl(m,s)},[t,n==null?void 0:n.collectionCreator,s]),l=Gl(e,t,{...n,collectionCreator:a,strictStreamingOrder:!0}),c=u.useCallback(d=>(o.current.add(d),()=>{o.current.delete(d)}),[]);return{...l,subscribeMessageEvents:c}},It={DEFAULT_PRIMARY:"#000000",DEFAULT_BOT_MSG_BG:"#ECECEC",WHITE:"#ffffff",BLACK:"#000000"};function Is(e){return e.length===4?`#${[...e.slice(1)].map(t=>t+t).join("")}`:e}function Vl(e){const t=Is(e);return[parseInt(t.slice(1,3),16),parseInt(t.slice(3,5),16),parseInt(t.slice(5,7),16)]}function Yl(e){return`#${e.map(t=>t.toString(16).padStart(2,"0")).join("")}`}function Wl(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 ql(e,t,n){let r,o,s;if(t===0)r=o=s=n;else{const a=function(m,f,h){return h<0&&(h+=1),h>1&&(h-=1),h<.16666666666666666?m+(f-m)*6*h:h<.5?f:h<.6666666666666666?m+(f-m)*(.6666666666666666-h)*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 Bt(e,t,n){const[r,o,s]=Vl(e),[a,l,c]=Wl(r,o,s),d=Math.max(0,Math.min(1,c*t)),m=Math.max(0,Math.min(1,l*n)),[f,h,_]=ql(a,m,d);return Yl([Math.round(f),Math.round(h),Math.round(_)])}function Kl(e,t="light"){return{extraDark:Bt(e,.6,1.2),dark:Bt(e,.85,1.1),main:e,light:Bt(e,t==="dark"?1.1:1.5,t==="dark"?.95:.9),extraLight:Bt(e,t==="dark"?1.2:1.75,t==="dark"?.9:.8)}}function zn(e){const t=Is(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?It.BLACK:It.WHITE}function jl(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 Xl=(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"}}),Ut={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)"}},An={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 Qr(e){const t=Zl(e),n=Jl(e,t),r=ec(n,e.colors,e.selectedTheme),o=nc(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 Zl({selectedTheme:e,palette:t,primary:n}){const r=t!=null&&t.primary?t.primary:n?n===Ut.primary.main?Ut.primary:Kl(n,e):Ut.primary;return{...Ut,primary:r,...t}}function Jl({selectedTheme:e,primaryContrast:t,botMessageBackground:n,botMessageBackgroundContrast:r},o){const s=o.primary.main,a=t??zn(s),l=n??It.DEFAULT_BOT_MSG_BG,c=r??zn(l);return(e==="light"?jl:Xl)(o,s,a,l,c)}function Ql(e,t,n){return typeof e=="string"?e:e[t]??n}function ec(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]=Ql(m,n,f)}}}return r}function tc(e,t,n){const r={...e};return n.forEach(o=>{const s=t[o];s!=null&&(r[o]=s)}),r}function nc({typography:e}){if(!e)return An;const t={...An};return Object.keys(e).forEach(n=>{const r=e[n];if(r&&typeof r=="object"){const o=An[n],s=["fontSize","fontWeight","fontFamily","lineHeight"];t[n]=tc(o,r,s)}}),t}const{Provider:rc,useContext:ur}=Ee("AIAgentTheme");function oc({logger:e,palette:t,typography:n,colors:r,appearance:o,children:s}){const a=u.useRef(null),[l,c]=u.useState(()=>Qr({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 h=(o==null?void 0:o.theme)??m,_=a.current?a.current.themes[h]:null,y={primary:o==null?void 0:o.primaryColor,primaryContrast:void 0,botMessageBackground:o==null?void 0:o.botMessageBackgroundColor,botMessageBackgroundContrast:void 0};!y.primary&&(_!=null&&_.primary_color)&&(y.primary=_.primary_color,y.primaryContrast=_.primary_contrast_color),!y.botMessageBackground&&(_!=null&&_.bot_message_bg_color)&&(y.botMessageBackground=_.bot_message_bg_color,y.botMessageBackgroundContrast=_.bot_message_bg_contrast_color);const C=Qr({selectedTheme:h,palette:t,typography:n,colors:r,...y});c(C),e==null||e.info("theme.update:",h)},[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(rc,{value:{theme:l,updateTheme:d}},s)}const xn=25*1024*1024,eo=1,to=new Set(["image/png","image/jpeg","image/jpg"]),no=new Set(["application/pdf"]),sc={off:"off",always:"always",handed_off_only:"handed_off_only"},ic=()=>{const[e,t]=u.useState(()=>({maxAttachmentCount:eo,attachmentMode:"handed_off_only",defaultUploadSizeLimit:xn,uploadSizeLimitPerType:new Map,supportedImageMimeTypes:to,supportedFileMimeTypes:no})),n=u.useCallback(({active_channel:o,upload_restriction:s})=>{t({maxAttachmentCount:(s==null?void 0:s.max_attachment_count)??eo,attachmentMode:sc[o.attachment_mode]??"handed_off_only",defaultUploadSizeLimit:(s==null?void 0:s.default_upload_size_limit)??xn,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)??to),supportedFileMimeTypes:new Set((s==null?void 0:s.supported_file_mime_types)??no)})},[]),r=u.useCallback(o=>{const{channel:s,uploadSizeLimit:a=xn}=o,l=(d=!0)=>s!=null&&s.isAIAgent?d?et(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 et(s);default:return!0}},get supportedMimeTypes(){return l()?[Fn]:[...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}},ro=(...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)")},Ct=e=>({...e,context:e.context??{}}),{Provider:ac,useContext:gt}=Ee("AIAgentMessengerSession"),lc=u.forwardRef(function({userSessionInfo:e,children:t},n){const{_aiAgentSDK:r,chatSDK:o,aiAgentId:s,logger:a}=Me(),{updateTheme:l}=ur(),[c,d]=u.useState(void 0),[m,f]=u.useState(void 0),[h,_]=u.useState(null),[y,C]=u.useState(null),[v,b]=u.useState(null),[E,A]=u.useState(null),[x,k]=u.useState(null),{updateBaseAttachmentRules:R,createAttachmentRules:I}=ic();u.useEffect(()=>{const V=r.onMessengerSettingsUpdated(({settings:G})=>{const{appearance:W,bot:q,launcher:ce,memory:_e}=G;l(W.selected_theme,W),b(Va(q)),A(Ya(ce)),k(_e?Hn(_e):null),R(G)}),H=r.onActiveChannelUpdated(({channelUrl:G,status:W,conversationStatus:q})=>{f({url:G,status:W,conversationStatus:q})}),Y=r.onAuthTokenRefreshed(()=>{var W;const G=(W=r.session)==null?void 0:W.userSession.authToken;G&&C(q=>q?{...q,authToken:G}:null)});return()=>{V(),H(),Y()}},[r,l,R]);const w=u.useCallback(async()=>{try{const V=await r.authenticate(e),H=r.session;return _(H.sdkUser),C(H.userSession),f(H.activeChannel),d(void 0),V}catch(V){throw _(null),C(null),f(void 0),d(V),V}},[r,e]),O=u.useCallback(async()=>{await r.deauthenticate(),_(null),f(void 0),C(null),b(null),A(null),k(null)},[r]),$=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 V=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:w,deauthenticate:O,updateContext:async(...H)=>{const Y=ro(...H);if(Y.type==="active"){const q=await(await V()).updateContext(s,Y.context);return Ct(q)}const G=await o.aiAgent.updateContext(Y.aiAgentId,Y.channelUrl,Y.context);return Ct(G)},patchContext:async(...H)=>{const Y=ro(...H);if(Y.type==="active"){const q=await(await V()).patchContext(s,Y.context);return Ct(q)}const G=await o.aiAgent.patchContext(Y.aiAgentId,Y.channelUrl,Y.context);return Ct(G)},getContextObject:async()=>{const Y=await(await V()).getContextObject(s);return Ct(Y)}}},[w,O,m,o,s,a]),i.createElement(ac,{value:{sdkUser:h,userSessionInfo:e,userSession:y,activeChannel:m,setActiveChannel:f,refreshActiveChannel:$,createConversation:r.createConversation,searchConversation:r.searchConversation,connectionError:c,aiAgentInfo:v,launcherInfo:E,memoryInfo:x,authenticate:w,deauthenticate:O,createAttachmentRules:I,statsTrackers:r.statsTrackers}},t)}),Rt=(e,t)=>{const n=u.useId(),r=u.useRef(t);u.useLayoutEffect(()=>{r.current=t}),u.useLayoutEffect(()=>{const o=new ge.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 cc(e){const{chatSDK:t,logger:n,aiAgentId:r,_aiAgentSDK:o}=Me(),{sdkUser:s,statsTrackers:a}=gt(),l=dn(),[c,d]=u.useState(void 0),[m,f]=u.useState(void 0),[h,_]=u.useState(!1);function y(v){v.isAIAgent&&!v.conversation&&(_(!0),o.initConversationIfNeeded(v).finally(()=>_(!1)))}async function C(){var v,b,E;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),_(!1),e){a.initialRender.onGetChannelStart();try{n.debug("useChannel.getChannel: get channel",e);const A=await t.groupChannel.getChannel(e);y(A),d(A),a.initialRender.onGetChannelComplete((v=A.conversation)==null?void 0:v.id),A.url===((b=o.session)==null?void 0:b.activeChannel.url)&&o.session._updateActiveChannel({url:A.url,status:Re(A)?"closed":"open",conversationStatus:(E=A.conversation)==null?void 0:E.status}),n.debug("useChannel.getChannel: fetched channel",A)}catch(A){a.initialRender.onGetChannelError(A),A instanceof ge.SendbirdError&&f(A),n.error("useChannel.getChannel: error",A)}}}return u.useEffect(()=>{C()},[t,s,e,r]),Rt(t,{async onReconnectSucceeded(){if(!c)return;const v=await c.refresh();y(v),d(v)}}),ht(t,{onChannelChanged:v=>{v.isGroupChannel()&&v.url===e&&(n.debug("useChannel.onChannelChanged: channel changed",v.url),d(v),l())}}),{channel:c,channelFetchError:m,getChannel:C,isInitializingConversation:h}}const uc=new Set(["suggested_replies","steward","system"]),dc=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||!uc.has(r)))return r},mc=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},fc=()=>{const{chatSDK:e,networkStateAdapter:t}=Me(),[n,r]=u.useState(()=>t?t.isOnline()?"connected":"reconnecting":"connected");return Rt(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===ge.ConnectionState.OPEN?"connected":s)})},[t,e]),n},hc=3e4,gc=({shouldApply:e,lastMessage:t,isBlockedWhileAIResponding:n,currentUserId:r})=>{const[o,s]=u.useState(!1),a=u.useRef(null),l=t&&ft(t,r)?t.createdAt:0;return u.useEffect(()=>{const c=()=>{a.current&&(clearTimeout(a.current),a.current=null),s(!1)},d=h=>{a.current&&clearTimeout(a.current),s(!0),a.current=setTimeout(()=>{s(!1),a.current=null},h)},m=Date.now()-l,f=hc-m;return n||f<=0?c():d(f),()=>{a.current&&clearTimeout(a.current)}},[n,l]),o&&e},ws=e=>{const{chatSDK:t}=Me(),[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},pc=({channel:e,lastMessage:t,aiAgentUserId:n,isStreamAnimating:r})=>{const[o,s]=u.useState(!1),a=ws(e);return u.useEffect(()=>{if(!t)return;const l=a.some(d=>d.userId===n),c=ft(t,n)&&(Ve.isStreaming(t)||r);s(c||l)},[a,t,n,r]),o},_c=({channel:e,messages:t,isStreamAnimating:n,isInitializingConversation:r})=>{const{aiAgentInfo:o,userSession:s}=gt(),a=fc(),l=pc({channel:e,lastMessage:Br(t,[Be.SendingStatus.SUCCEEDED]),aiAgentUserId:(o==null?void 0:o.userId)??"",isStreamAnimating:n}),c=gc({shouldApply:!!(e!=null&&e.isAIAgent)&&!et(e),isBlockedWhileAIResponding:l,lastMessage:Br(t,[Be.SendingStatus.PENDING,Be.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(Re(e))return d("conversation_closed");if(Wa(e))return d("handoff_pending");if(mc(e))return d("form_active");const m=dc(e);return d(m||(l||c||r?"ai_responding":""))},Ec=()=>{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:bc}=Ee("AIAgentConversation");function Cc({children:e,channelUrl:t,onChannelDeleted:n,onMessagesReceived:r,onMessagesUpdated:o,onConversationClosedStatusChanged:s,onConversationClosedViaDispatcher:a,onBeforeSendMessage:l,onAfterSendMessage:c=he,shouldMarkAsRead:d=!0,shouldCountNewMessages:m=()=>!1,sortComparator:f}){var V;const h=()=>d&&(b==null?void 0:b.markAsRead()),{_aiAgentSDK:_,chatSDK:y,logger:C,dispatcher:v}=Me(),{channel:b,channelFetchError:E,getChannel:A,isInitializingConversation:x}=cc(t),{statsTrackers:k}=gt();u.useEffect(()=>{if(t)return k.initialRender.setChannelUrl(t),()=>{k.initialRender.cleanup()}},[t,k]);const R=zl(y,b,{replyType:Be.ReplyType.ONLY_REPLY_TO_CHANNEL,shouldCountNewMessages:m,onChannelDeleted:n,onMessagesReceived:H=>r==null?void 0:r(H),onMessagesUpdated:H=>o==null?void 0:o(H),onCacheResult:H=>k.initialRender.onCacheResult(H),onApiResult:H=>k.initialRender.onApiResult(H),logger:C,markAsRead:h,sortComparator:f}),I=Ec(),w=_c({channel:b,messages:R.messages,isStreamAnimating:I.isAnimating,isInitializingConversation:x});u.useEffect(()=>{h()},[d,b]);const O=Re(b);u.useEffect(()=>{s==null||s(O)},[O,s]),u.useEffect(()=>{const H=async Y=>{const G=typeof(Y==null?void 0:Y.channelUrl)=="string";b&&G&&Y.channelUrl!==b.url||(C.debug("conversation.dispatcher: try to close conversation",b),b!=null&&b.conversation&&b.conversation.status===be.ConversationStatus.OPEN&&(await b.closeConversation(),a==null||a()))};return v.subscribe(Fe.ConversationClose,H),()=>{v.unsubscribe(Fe.ConversationClose,H)}},[v,b,C,(V=b==null?void 0:b.conversation)==null?void 0:V.status,a]);const $={conversation:(b==null?void 0:b.conversation)??void 0,actions:{setUserMemoryState:_.setUserMemoryState},channelSource:{channel:b,error:E,refetch:()=>A(),closeConversation:async()=>{Re(b)||await(b==null?void 0:b.closeConversation())}},messageSource:{messages:R.messages,newMessages:R.newMessages,initialized:R.initialized,subscribeMessageEvents:R.subscribeMessageEvents,loadPrevious:()=>R.loadPrevious(),loadNext:()=>R.loadNext(),deleteMessage:H=>R.deleteMessage(H),resendMessage:H=>R.resendMessage(H),resetNewMessages:()=>R.resetNewMessages(),sendUserMessage:async H=>{var G;if(((G=b==null?void 0:b.conversation)==null?void 0:G.status)===be.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(H=await l(H));const Y=await R.sendUserMessage(H,c);return c==null||c(Y),Y},sendFileMessage:async H=>{var G;if(((G=b==null?void 0:b.conversation)==null?void 0:G.status)===be.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(H=await l(H));const Y=await R.sendFileMessage(H,c);return c==null||c(Y),Y},sendMultipleFilesMessage:async H=>{var G;if(((G=b==null?void 0:b.conversation)==null?void 0:G.status)===be.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(H=await l(H));const Y=await R.sendMultipleFilesMessage(H,c);return c==null||c(Y),Y}},state:{streamAnimation:I,input:w}};return i.createElement(bc,{value:$},e)}function vc(e,t){var _,y,C,v,b,E,A,x,k,R;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 I=new ms(e,t);I.setConversationListCollectionHandler({onChannelsAdded:()=>{l(I.channels)},onChannelsUpdated:()=>{l(I.channels)},onChannelsDeleted:()=>{l(I.channels)}}),await I.loadMore(),l(I.channels),d(I),s(null)}catch(I){d(null),s(I)}finally{r(!0),m.current=!1}}},[e,e.currentUser,(_=t.filter)==null?void 0:_.aiAgentChannelFilter,(C=(y=t.filter)==null?void 0:y.aiAgentConversationStatusFilter)==null?void 0:C.join(),(b=(v=t.filter)==null?void 0:v.aiAgentIds)==null?void 0:b.join(),(E=t.filter)==null?void 0:E.deskChannelFilter,(x=(A=t.filter)==null?void 0:A.pinnedChannelUrls)==null?void 0:x.join(),(k=t.filter)==null?void 0:k.copilotConversationOnly,(R=t.filter)==null?void 0:R.copilotSupportChannelUrl,t.limit]),h=u.useCallback(async()=>{if(c)try{await c.loadMore(),l(c.channels)}catch(I){s(I)}},[c]);return Rt(e,{onConnected:()=>f()}),u.useEffect(()=>{f()},[f]),u.useEffect(()=>()=>{m.current=!1,c==null||c.dispose()},[c]),{initialized:n,error:o,channels:a,loadMore:h}}const Ms=e=>{var o;const{aiAgentId:t,queryParams:n}=Me(),r=(o=n==null?void 0:n.conversationListParams)==null?void 0:o.filter;return{aiAgentIds:[t],aiAgentConversationStatusFilter:[be.ConversationStatus.CLOSED,be.ConversationStatus.OPEN],...r,...e}},{Provider:yc}=Ee("AIAgentConversationList");function Sc({conversationListLimit:e,conversationListFilter:t,children:n}){var d;const{chatSDK:r,queryParams:o}=Me(),s=e??((d=o==null?void 0:o.conversationListParams)==null?void 0:d.limit),a=Ms(t),l=vc(r,{limit:s,filter:a}),c={listSource:{initialized:l.initialized,error:l.error??void 0,channels:l.channels,loadMore:()=>l.loadMore()}};return i.createElement(yc,{value:c},n)}function Ac(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:xc,useContext:Tc}=Ee("MessageTemplateFetching");function Ic({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:h=!1})=>{const _=m(f);if(_)return _;const y=r.current[f];if(y)return y;h||a(f,{fetching:!0});const C=d(f).catch(v=>{throw h||a(f,{error:!0}),v}).finally(()=>{h||a(f,{fetching:!1}),delete r.current[f]});return r.current[f]=C,C},[a]),c={internalVariables:t,fetchTemplate:l,suspend:(d,m)=>{if(n.current[d])return n.current[d];const f=Ac(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(xc,{value:c},e)}const wc="remove_powered_by",dr=(e,t)=>{var o,s;const{chatSDK:n}=Me(),{aiAgentInfo:r}=gt();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&&or(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(wc)),[a])}throw new Error("Unsupported feature")},Mc={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"},kc={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}}},Rc={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}}},Lc={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}}},Oc={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}}},Nc={text:kc,number:Rc,"single-select":Lc,"multi-select":Oc},Dc={getValueOrDefault:()=>null,validate:()=>({isValid:!1})};function ks(e){return Nc[e.type]||Dc}function oo(e){return ks(e).getValueOrDefault(e)}function $c(e,t,n={}){const r={...Mc,...n};return ks(e).validate(e,t,r)}const Pc=(e,t={})=>{const{labels:n={},onSubmit:r,onCancel:o}=t,[s,a]=u.useState({}),[l,c]=u.useState(()=>{const C={};return e.fields.forEach(v=>{C[v.key]=oo(v)}),C}),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 C={};let v=!1;e.fields.forEach(b=>{const E=oo(b);JSON.stringify(l[b.key])!==JSON.stringify(E)&&(v=!0),C[b.key]=E}),v&&c(C)}},[d]);const m=(C,v)=>{c(b=>({...b,[C]:v})),a(b=>({...b,[C]:void 0}))},f=e.fields.map(C=>{var E,A,x;const v=l[C.key]??null,b={key:C.key,label:C.label,error:s[C.key],required:C.required};return C.type==="text"?{...b,type:"text",layout:C.layout,value:v,...C.placeholder&&{placeholder:C.placeholder},...((E=C.rules)==null?void 0:E.max_length)&&{maxLength:C.rules.max_length}}:C.type==="number"?{...b,type:"number",layout:C.layout,value:v,...C.placeholder&&{placeholder:C.placeholder},...((A=C.rules)==null?void 0:A.max)&&{max:C.rules.max}}:C.type==="single-select"?{...b,type:"single-select",layout:C.layout,value:v,options:C.options}:C.type==="multi-select"?{...b,type:"multi-select",layout:C.layout,value:v,options:C.options,...((x=C.rules)==null?void 0:x.max_select)&&{maxSelect:C.rules.max_select}}:{...b,type:"unknown",layout:"default",value:null}});return{state:d,fields:f,getField:C=>f.find(v=>v.key===C),updateFieldValue:m,submit:async()=>{const C={};let v=!1;for(const b of e.fields){const E=l[b.key]??null,A=$c(b,E,n);A.isValid||(C[b.key]=A.error,v=!0)}if(a(C),!v&&r){const b={};e.fields.forEach(E=>{b[E.key]=l[E.key]??null}),await r(b)}},cancel:async()=>{await(o==null?void 0:o())}}},Fc=e=>{const{chatSDK:t,handlers:n,logger:r}=Me(),{aiAgentInfo:o}=gt(),s=u.useRef(new Set),a=u.useRef(new Set),l=(m,f)=>{if(!(n!=null&&n.onCustomEvent)||!(o!=null&&o.userId)||!ft(m,o.userId))return;const h=m.messageId;if(Ve.isStreaming(m)){a.current.add(h);return}f==="updated"&&!a.current.has(h)||(r.debug("useCustomEventForMessageReceive: bot-message-received",m),n.onCustomEvent({type:"bot-message-received",data:{message:m}}),a.current.delete(h))},c=u.useCallback(m=>{if(n!=null&&n.onCustomEvent&&m.isAdminMessage()&&m.customType==="user_action_required"&&!s.current.has(m.messageId)){const f=Bn(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,h)=>{m.url===e&&(l(f,h),c(f))};return ht(t,{onMessageReceived:(m,f)=>d(m,f,"received"),onMessageUpdated:(m,f)=>d(m,f,"updated")}),{checkForUserActionRequired:c}},Bc=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},Rs=e=>{const{aiAgentInfo:t}=gt(),n=ws(e);if(Re(e))return null;const r=n[0];if(!r)return null;const o=r.userId===(t==null?void 0:t.userId),s=o?Bc(r.metaData):void 0;return{user:o?t:r,isBot:o,thinkingMessage:s}},Uc=(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},[])},Hc=(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()}}},Gc=(e,t,n=1e4,r=!0)=>{const o=u.useRef(null),s=u.useRef(null),a=u.useRef(!1);o.current||(o.current=Hc(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])};var Ye=(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))(Ye||{});const zc=({csat:e,csatExpireAt:t,csatPayload:n,isSubmitInFlight:r})=>{const o=!!n&&n.visibility&&!!Ye[n.type],s=!r&&typeof e!="number"&&Es(t),a=dn();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}},Vc=({csat:e,csatExpireAt:t,csatPayload:n,announceStatus:r,onSubmittedAnnounced:o,isSubmitInFlight:s=!1})=>{const{isRenderableCSAT:a,isExpiredNow:l}=zc({csat:e,csatExpireAt:t,csatPayload:n,isSubmitInFlight:s}),c=(n==null?void 0:n.csat_submitted_label)??"",d=u.useRef(a&&typeof e=="number"),m=u.useRef(a&&l);return u.useEffect(()=>{a&&c&&(typeof e!="number"||d.current||(d.current=!0,r({event:"csatSubmitted",submittedLabel:c}),o==null||o()))},[r,e,a,o,c]),u.useEffect(()=>{a&&l&&(m.current||(m.current=!0,r({event:"csatExpired"})))},[r,l,a]),{isExpiredNow:l,isRenderableCSAT:a}},mr=({channel:e,userSession:t,aiAgentInfo:n})=>{if(!t||!n||!e)return{fallbackIcon:"delight",url:void 0,title:""};const r=_s(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?et(e)?o.human("agent"):o.ai("delight"):e.isDesk?o.human("agent"):o.channel("user")},so=e=>u.useReducer((t,n)=>({...t,...n}),e),Yc=new Set(["free_text","single_choice"]),Wc=({csatPayload:e,type:t,initialCsat:n,initialCsatReason:r,initialIsResolved:o})=>{const[s,a]=so({csatType:t,csat:n,csatReason:r,isResolved:o}),[l,c]=so({followUpItem:!1}),d=u.useMemo(()=>{var v;const _=s.csat,y=typeof _=="number",C=(v=e.follow_up)==null?void 0:v.find(b=>y?b.scores.includes(_):b.always_visible??!1);if(Yc.has(C==null?void 0:C.response_type))return C},[s.csat,e.follow_up]),m=(()=>{var _;if(typeof n=="number")return"submitted";if((t===Ye.AI_AGENT_CSAT_5||t===Ye.HELPDESK_CSAT_5)&&typeof s.csat=="number")return"submittable";if(t===Ye.AI_AGENT_CSAT_5_WITH_CRE){const y=typeof s.csat=="number",C=!((_=e.cre)!=null&&_.required)||typeof s.isResolved=="boolean";if(y&&C)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"}}},Tn=5,qc=250,Kc=50,io=e=>Math.max(0,e-Kc),jc=e=>e<1e3?{speed:Tn*.5,chunkSize:2}:e<2e3?{speed:Tn*.8,chunkSize:2}:{speed:Tn*.6,chunkSize:3},Ht=(e,t)=>{let n=0;for(let r=t-1;r>=0&&e[r]==="\\";r--)n++;return n%2===1},Xc=(e,t)=>{if(!t)return e;let n="",r=0,o=0;for(;r<e.length;){if(e[r]==="`"&&!Ht(e,r)){let c=1;for(;e[r+c]==="`";)c++;o===0?o=c:c===o&&(o=0),n+=e.slice(r,r+c),r+=c;continue}if(o>0||e[r]!=="!"||e[r+1]!=="["||Ht(e,r)){n+=e[r],r++;continue}const s=r;r+=2;let a=1;for(;r<e.length&&a>0;){if(Ht(e,r)){r++;continue}e[r]==="["?a++:e[r]==="]"&&a--,r++}if(a>0||r>=e.length)return n;if(e[r]!=="("){n+=e.slice(s,r);continue}r++;let l=1;for(;r<e.length&&l>0;){if(Ht(e,r)){r++;continue}e[r]==="("?l++:e[r]===")"&&l--,r++}if(l>0)return n;n+=e.slice(s,r)}return n},Zc=e=>{const{text:t,enabled:n=!1,markdownImageRenderMode:r="default",onAnimationStart:o,onAnimationProgress:s,onAnimationComplete:a}=e,[l,c]=u.useState(()=>io(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,h=u.useRef({startCalled:!1,completeCalled:!1}).current,_=u.useRef({initialEnabled:n,textLength:t.length,enabled:n}).current,y=n,C=l<t.length,v=_.initialEnabled&&(y||C);return u.useLayoutEffect(()=>{f.onStart=o,f.onProgress=s,f.onComplete=a,_.textLength=t.length,_.enabled=n}),u.useLayoutEffect(()=>{var E;_.initialEnabled&&(h.startCalled||(h.startCalled=!0,(E=f.onStart)==null||E.call(f)),c(A=>t.length<A?t.length:A))},[t]),u.useEffect(()=>{if(!_.initialEnabled)return;let E=io(t.length);m.lastUpdate=0,m.startTime=0,m.lastProgressCall=0;const A=x=>{var H;m.lastUpdate===0&&(m.lastUpdate=x,m.startTime=x,m.lastProgressCall=x);const k=_.textLength,R=x-m.lastUpdate,I=x-m.startTime,{speed:w,chunkSize:O}=jc(I),$=w*O;R>=$&&E<k&&(E=Math.min(E+O,k),c(E),m.lastUpdate=x),x-m.lastProgressCall>=qc&&(m.lastProgressCall=x,(H=f.onProgress)==null||H.call(f)),(E<k||_.enabled)&&(d.current=requestAnimationFrame(A))};return d.current=requestAnimationFrame(A),()=>{var x;d.current&&cancelAnimationFrame(d.current),h.startCalled&&!h.completeCalled&&(h.completeCalled=!0,(x=f.onComplete)==null||x.call(f))}},[]),u.useEffect(()=>{var k;const E=_.initialEnabled&&h.startCalled,A=!n,x=l>=t.length&&t.length>0;E&&A&&x&&!h.completeCalled&&(h.completeCalled=!0,(k=f.onComplete)==null||k.call(f))},[n,l,t.length]),{streamText:u.useMemo(()=>{const E=_.initialEnabled?t.slice(0,l):t;return r!=="complete-only"?E:Xc(E,v)},[t,l,r,v]),isAnimating:v}},ao={visible:!1,remainingTime:0,showDescription:!1,targetTimeMs:null},Jc=e=>({visible:!0,remainingTime:e,showDescription:!0,targetTimeMs:Date.now()+e*1e3}),Qc=(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}},eu=()=>{const{chatSDK:e}=Me(),[t,n]=u.useState(ao),r=()=>n(ao);return Rt(e,{onConnectionDelayed:o=>{o>0?n(Jc(o)):r()},onReconnectSucceeded:r,onConnected:r}),u.useEffect(()=>{if(!t.visible||!t.showDescription||t.targetTimeMs==null)return;const o=setTimeout(()=>{n(s=>Qc(s))},1e3);return()=>clearTimeout(o)},[t.visible,t.showDescription,t.targetTimeMs,t.remainingTime]),{visible:t.visible,remainingTime:t.remainingTime,showDescription:t.showDescription}},tu=e=>{const t=Math.floor(e/60),n=e%60;return`${String(t).padStart(2,"0")}:${String(n).padStart(2,"0")}`},nu=(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)}},ru=(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(h=>{f===a.current&&s(h.total>0)}).catch(()=>{})};return u.useEffect(()=>{if(!t){s(!1),a.current++;return}e.connectionState===ge.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]),Rt(e,{onConnected:l,onReconnectSucceeded:l}),o},fr=e=>e.replace(/\s+/g," ").trim(),ou="Code block",Ls=e=>`A11Y_INLINE_CODE_${e}`,Os=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}},Ns=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}},su=e=>{const{blockquotePrefix:t,content:n}=Os(e),{content:r}=Ns(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}},iu=(e,t)=>{const{blockquotePrefix:n,content:r}=Os(e);if(n!==t.blockquotePrefix)return!1;const{content:o,hasListPrefix:s}=Ns(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)},au=(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},lu=(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},cu=(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},uu=e=>{let t=0,n="";for(;t<e.length;){const r=au(e,"[",t);if(r===-1){n+=e.slice(t);break}const o=lu(e,r+1);if(o===-1){n+=e.slice(t);break}if(r>0&&e[r-1]==="!"&&tn(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]==="!"&&!tn(e,r-1)?r-1:r;n+=e.slice(t,s);const a=e.slice(r+1,o),l=cu(e,o+2);if(l===-1){n+=e.slice(s);break}n+=a,t=l}return n},Ds=(e,t,n)=>{if(!/^\d+$/.test(t))return!1;const r=e.slice(-1);return/\d/.test(r)&&/\d/.test(n)},du=e=>e.replace(/(^|[^*\\])\*\*([^\s*](?:[\s\S]*?[^\s*])?)\*\*(?!\*)/g,(t,n,r,o,s)=>{const a=s[o+t.length]??"";return Ds(n,r,a)?t:`${n}${r}`}),mu=e=>e.replace(/(^|[^_\\])__([^\s_](?:[\s\S]*?[^\s_])?)__(?!_)/g,"$1$2"),fu=e=>e.replace(/(^|[^~\\])~~([^\s~](?:[\s\S]*?[^\s~])?)~~(?!~)/g,"$1$2"),hu=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 Ds(r,o,l)?n:`${r}${o}`}),t=t.replace(/(^|[\s([{"'])_([^_\s](?:[\s\S]*?[^_\s])?)_(?=$|[\s)\]}"'.,!?:;])/g,"$1$2"),t},gu=e=>e.replace(/\\([\\`*_[\]()#+.!~|-])/g,"$1"),pu=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},lo=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))},co=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},_u=e=>{const t=e.split(`
|
|
2
|
-
`),n=[];let r=0;for(;r<t.length;){const o=t[r],s=t[r+1],a=
|
|
3
|
-
`)},
|
|
4
|
-
`),r=[];let o=0;for(;o<n.length;){const s=n[o],a=
|
|
5
|
-
`)},
|
|
6
|
-
`;){if(e[l]==="`"&&!
|
|
7
|
-
`);if(!n)return;const r=[];let o=n;o=bu(o,t),o=pu(o);const s=Cu(o);o=s.text,r.push(...s.inlineCodes),o=uu(o),o=du(o),o=mu(o),o=fu(o),o=hu(o),o=_u(o),o=Eu(o),o=gu(o);for(let l=0;l<r.length;l++)o=o.replaceAll(Ls(l),r[l]);return fr(o)||void 0},vu=(e,t)=>{var o;const n=((o=e.name)==null?void 0:o.trim())||"",r=e.mimeType??"";return He(r)?t.image:cn(r)?t.video:cs({name:n,mimeType:r})?t.pdf(n):t.document(n)},nn=e=>(e==null?void 0:e.trim())||"",yu=e=>(e?fr(e):void 0)||void 0,Ps=e=>({text:nn(e),format:"plain"}),Su=e=>({text:nn(e),format:"markdown"}),In=({markdownText:e,plainText:t,comparisonText:n})=>{const r=nn(e);return r&&r!==nn(n)?Su(r):Ps(t)},yt=({sender:e,message:t,messageFormat:n="plain",time:r,codeBlockPlaceholder:o})=>{const s=[],a=n==="markdown"?$s(t,{codeBlockPlaceholder:o}):yu(t);if(r&&s.push(r),e&&s.push(e),a&&s.push(a),s.length!==0)return s.join(", ")},Fs=(e,t)=>$s(e==null?void 0:e.trim(),t!==void 0?{codeBlockPlaceholder:t}:void 0),Au=(...e)=>fr(e.filter(Boolean).join(", "))||void 0,uo=(e,t,n,r)=>{if(!t||t===n)return e;const o=Fs(t,r);return o?Au(e,o):e},xu=(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=vu({name:l,mimeType:e.type},t);return uo(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(h=>{var _;return(_=h.mimeType)==null?void 0:_.startsWith("image")})?t.receivedFilesImageCount(c):t.multipleFilesCount(c);return uo(f,n,d,t.codeBlockPlaceholder)}return Fs(n,t.codeBlockPlaceholder)},Tu=(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,h=0;const _=(w,O,$)=>({text:w,ignoreSuppression:O,queueOrder:h++,dedupeKey:$}),y=()=>{const w=l[0]??null,O=a;return w&&O?O.queueOrder<w.queueOrder?(a=null,O):l.shift()??null:w?l.shift()??null:O!==null?(a=null,O):null},C=()=>{for(;;){const w=y();if(!w)return null;if(!(!w.ignoreSuppression&&(r!=null&&r())))return w}},v=w=>{c=w.text,d=w.dedupeKey??null,f=!0,e(w.text),m=setTimeout(()=>{m=null,f=!1;const O=C();O&&v(O)},n)},b=w=>{c=w.text,d=w.dedupeKey??null,e(w.text)},E=(w,O,$,V)=>O!=null&&V!=null?O===V:O==null&&V==null?w!=null&&w===$:!1,A=(w,O,$)=>{if(!w||!O&&(r!=null&&r()))return;const V=$==null?void 0:$.dedupeKey;if(!(f&&E(w,V,c,d)))if(f){if((($==null?void 0:$.mode)??"latestOnly")==="ordered"){const Y=l[l.length-1];if(Y&&E(w,V,Y.text,Y.dedupeKey))return;l.push(_(w,O,V)),l.length>s&&l.shift();return}a=_(w,O,V)}else a=null,v(_(w,O,V))};return{announce:(w,O)=>{A(w,!1,O)},announceIgnoringSuppression:(w,O)=>{A(w,!0,O)},flush:()=>{const w=[];let O=y();for(;O!==null;)w.push(O),O=y();if(m!==null&&(clearTimeout(m),m=null),f=!1,w.length!==0)for(const $ of w)b($)},destroy:()=>{m!==null&&(clearTimeout(m),m=null),a=null,l.length=0,c=null,d=null,f=!1}}},Iu=e=>{switch(e){case"newMessage":case"conversationClosed":case"csatDisplayed":case"csatSubmitted":case"csatExpired":return"ordered";default:return"latestOnly"}},wu=(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(". "),Mu=(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}},ku=(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}},Ru=(e,t)=>!t||!Qe(e)||e.sender.userId!==t?null:e.reqId||(e.messageId>0?String(e.messageId):null),Lu=(e,t)=>Ie.isAdmin(e)?Ie.isCSAT(e):"sender"in e?e.sender.userId!==t:!1,Ou=e=>"messageId"in e&&e.messageId>0?String(e.messageId):"reqId"in e&&typeof e.reqId=="string"&&e.reqId.length>0?e.reqId:null,Nu=e=>e===ge.CollectionEventSource.EVENT_MESSAGE_RECEIVED||e===ge.CollectionEventSource.EVENT_MESSAGE_UPDATED,Du=({isOpened:e,opensConversationList:t})=>e?t?"closeConversationList":"closeConversation":t?"openConversationList":"openConversation",$u=(e,t)=>{switch(e){case"closeConversationList":return t.closeConversationList;case"closeConversation":return t.closeConversation;case"openConversationList":return t.openConversationList;case"openConversation":return t.openConversation}},Pu=(e,t)=>{switch(e){case"closeConversation":return t.hintCloseConversation;case"openConversationList":return t.hintOpenConversationList;case"openConversation":return t.hintOpenConversation;default:return}},Fu=({intent:e,strings:t})=>({label:$u(e,t),hint:Pu(e,t)}),Bu="1.29.0",Ne="sb-agent",Ce={ENTRY:`${Ne}-entry`,MODAL_ROOT:`${Ne}-modal-root`,WINDOW:`${Ne}-window`,LAUNCHER:`${Ne}-launcher`,WINDOW_TITLE:`${Ne}-window-title`},Bs="data-sb-initial-focus",Us="true",Uu=`[${Bs}="${Us}"]`,Hs={[Bs]:Us},hr="data-sb-focus-trap-sentinel",Hu="true",Gs="data-sb-initial-focus-header",zs="true",Gu=`[${Gs}="${zs}"]`,Vs={[Gs]:zs},Gt=2147483647,it={MODAL:Gt-1,TOOLTIP:Gt-2,WINDOW:Gt-3,LAUNCHER:Gt-4},Ys=36,zu=100,Vu=Bu,gr="noopener noreferrer nofollow";function Yu(){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 zt={};function Wu(){return{get:e=>{try{return localStorage.getItem(e)}catch{return zt[e]??null}},set:(e,t)=>{try{localStorage.setItem(e,t)}catch{zt[e]=t}},delete:e=>{try{localStorage.removeItem(e)}catch{delete zt[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(zt).filter(t=>t.startsWith(e))}}}}const qu={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:"User 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}`}},Vn={language:"en",strings:qu,dateLocale:la.enUS},Ws=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}),qs=e=>{var t;return((t=e.split("-"))==null?void 0:t[0])??Lt},Lt="en",Ks=new Set([Lt,"ko","es","pt","fr","hi","it","de","tr","ja"]),Ku='@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:ju,useContext:pr}=Ee("AgentUIElementResolver"),Xu=({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===Ce.MODAL_ROOT?l:a.querySelector(`#${d}`);return{resolveElement:c,resolvePortalContainer:d=>c(d)??l}},[e,t,n]);return i.createElement(ju,{value:o},r)};function st(e,t){const n=e.getRootNode({composed:t});return n instanceof ShadowRoot||n instanceof Document?n:document}const mo=()=>{const e=[];let t=0;return{register:n=>{const r=++t;return e.push({id:r,handler:n}),()=>{const o=e.findIndex(s=>s.id===r);o>=0&&e.splice(o,1)}},dismissTopmost:()=>{const n=e[e.length-1];return n?(n.handler(),!0):!1}}},{Provider:Zu,useContext:js}=Ee("EscapeDismissStack"),fo=e=>{e.stopPropagation(),e.stopImmediatePropagation()},Ju=({rootElement:e=document.body,boundaryElement:t,children:n})=>{const r=u.useRef(null),o=u.useRef(null);r.current||(r.current=mo()),o.current||(o.current=mo());const s=r.current,a=o.current;u.useLayoutEffect(()=>{const c=t??st(e),d=m=>{if(m.key==="Escape"){if(s.dismissTopmost()){fo(m);return}a.dismissTopmost()&&fo(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}),[a,s]);return i.createElement(Zu,{value:l},n)},Xs=(e,t,n)=>{const r=u.useRef(t);u.useLayoutEffect(()=>{r.current=t},[t]),u.useLayoutEffect(()=>{if(e)return n(()=>r.current())},[e,n])},Qu=(e,t)=>{const{register:n}=js();Xs(e,t,n)},ed=(e,t)=>{const{registerShellDismissHandler:n}=js();Xs(e,t,n)},td=(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.":""))))})},ho=Ws(Vn.strings),nd={...ho,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:ho.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"},rn={language:Vn.language,dateLocale:Vn.dateLocale,stringSet:nd},rd=Object.freeze(Object.defineProperty({__proto__:null,default:rn},Symbol.toStringTag,{value:"Module"})),Yn=new Map([[Lt,rn]]);async function od(e){const t=Yn.get(e);if(t)return t;try{if(Ks.has(e)){const{default:n}=await td(Object.assign({"./languages/de.ts":()=>Promise.resolve().then(()=>require("./cjs/BrQW3MrE.cjs")),"./languages/en.ts":()=>Promise.resolve().then(()=>rd),"./languages/es.ts":()=>Promise.resolve().then(()=>require("./cjs/ByN4PZlT.cjs")),"./languages/fr.ts":()=>Promise.resolve().then(()=>require("./cjs/B7ulsf2M.cjs")),"./languages/hi.ts":()=>Promise.resolve().then(()=>require("./cjs/BVmiN3Wy.cjs")),"./languages/it.ts":()=>Promise.resolve().then(()=>require("./cjs/BeAZATeH.cjs")),"./languages/ja.ts":()=>Promise.resolve().then(()=>require("./cjs/Dl7xer_X.cjs")),"./languages/ko.ts":()=>Promise.resolve().then(()=>require("./cjs/h1huMI7F.cjs")),"./languages/pt.ts":()=>Promise.resolve().then(()=>require("./cjs/BSS6fNF-.cjs")),"./languages/tr.ts":()=>Promise.resolve().then(()=>require("./cjs/CjZUGQLK.cjs"))}),`./languages/${e}.ts`,3);return Yn.set(e,n),n}return rn}catch{return rn}}const{Provider:sd,useContext:se}=Ee("Localization"),id=({language:e=navigator.language,languageCode:t,logger:n,stringSet:r,children:o})=>{const[s,a]=u.useState(Yn.get(Lt));return u.useEffect(()=>{const l=t??qs(e);s.language!==l&&(n==null||n.debug("localization.useEffect: update language",{from:s.language,to:l}),od(l).then(a))},[e,t,n]),i.createElement(sd,{value:{language:s.language,defaultStringSet:s.stringSet,stringSet:{...s.stringSet,...r},dateLocale:s.dateLocale,format:(l,c,d)=>Xe.format(l,c,{locale:s.dateLocale,...d})}},o)},on="data-sb-agent-theme",go=e=>(t,...n)=>{let r="";return t.forEach((o,s)=>{r+=o+(n[s]??"")}),`[${on}='${e}'] & { ${r} }`},J={light:go("light"),dark:go("dark")},ad=D.css(({theme:e})=>{const{palette:t}=e;return`
|
|
1
|
+
"use strict";var da=Object.defineProperty;var ma=(e,t,n)=>t in e?da(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var A=(e,t,n)=>ma(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const he=require("@sendbird/chat"),u=require("react"),D=require("styled-components"),Xe=require("date-fns"),fa=require("date-fns/locale/en-US"),Ue=require("@sendbird/chat/message"),ga=require("react-dom"),be=require("@sendbird/chat/aiAgent"),ze=require("@sendbird/chat/groupChannel"),ha=require("date-fns/isSameDay"),pa=require("dompurify"),tr=e=>e&&e.__esModule?e:{default:e};function _a(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 Ea=tr(he),i=_a(u),p=tr(D),ls=tr(pa),ct="sb-agent",cs="KEY_IMG_ASPECT_RATIO",Un="*/*",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 Jt=(e=>(e.IN_PROGRESS="IN_PROGRESS",e.COMPLETED="COMPLETED",e.CANCELED="CANCELED",e))(Jt||{}),Tt=(e=>(e.IN_PROGRESS="IN_PROGRESS",e.COMPLETED="COMPLETED",e.CANCELED="CANCELED",e))(Tt||{});const us=e=>{var t;return!!((t=e==null?void 0:e.extendedMessagePayload)!=null&&t.steward)},ba=e=>e===Tt.COMPLETED||e===Tt.CANCELED?e:Tt.IN_PROGRESS,Sn=e=>Qe(e)&&!us(e),Qe=e=>!!e&&"sender"in e,Ca=e=>Qe(e)?e.sendingStatus==="succeeded"?String(e.messageId):e.reqId:String(e.messageId),va=(e,t,n,r=!0)=>{if(!r||!Sn(e))return"single";const o=()=>{if(!Sn(t))return!1;const c=t.sender.userId===e.sender.userId,d=Xe.isSameMinute(t.createdAt,e.createdAt);return c&&d},s=()=>{if(!Sn(n))return!1;const c=n.sender.userId===e.sender.userId,d=Xe.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 Qe(e)?e.sender.userId:((r=e==null?void 0:e.sender)==null?void 0:r.userId)??void 0})()===t,Ie={isAdmin:e=>e.isAdminMessage(),isCSAT:e=>{var t;return e.isAdminMessage()&&!!((t=e.extendedMessagePayload)!=null&&t.csat)},isSteward:e=>us(e),isIncoming:(e,t)=>Qe(e)&&e.sender.userId!==t,isOutgoing:(e,t)=>Qe(e)&&(e.sender.userId===t||e.sendingStatus===Ue.SendingStatus.PENDING)},He=e=>e.startsWith("image/"),cn=e=>e.startsWith("video/"),ds=({name:e="",mimeType:t=""})=>t==="application/pdf"||/\.pdf$/i.test(e.trim()),nr=(e,t)=>{if(e&&!e.startsWith(".")){const n=e.split(".").pop();if(n&&n!==e)return n.toUpperCase()}if(t){const[,n]=t.split("/");if(n)return n.toUpperCase()}return"FILE"},ms=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},un=e=>{switch(e){case"top":case"middle":return ee.GAP_GROUPED;default:return ee.GAP_UNGROUPED}},ya=(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},Sa=e=>e.replace(/\[([^\]]+)\](?!\()/g,"\\[$1\\]"),Aa=e=>e.replace(/([a-zA-Z0-9])_(?=[a-zA-Z0-9])/g,"$1\\_"),xa=e=>e.replace(/~~/g,"\\~\\~"),Ta=e=>{let t=e;return t=Sa(t),t=Aa(t),t=xa(t),t},Ia=typeof navigator<"u"&&navigator.product==="ReactNative",Ur=(e,t)=>{const n=r=>!t||t.length===0?!0:Qe(r)&&t.includes(r.sendingStatus);return Ia?e.find(n):e.findLast(n)};function ge(){}function wa(){const e=typeof navigator<"u"?navigator.userAgent:"",t=/iPad|iPhone|iPod/.test(e),n=/Android/.test(e);return t||n}function Ma(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 Bn=e=>{try{return JSON.parse(e===""?"{}":e)}catch{return{}}},Ve={isStreaming(e){const t=Bn(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=Bn(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)}},An=`@${ct}`,ka=({appId:e,aiAgentId:t,storage:n})=>{const r={templateBase:`${An}-template`,template:o=>`${r.templateBase}/templates/${o}`,templateToken:()=>`${r.templateBase}/tokens`,messengerSession:o=>{const s=Ma(`${e}/${t}/${o}`);return`${An}-udata/${s}`},anonUserSession:()=>`${An}-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}}}}},fs=(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},Ra=()=>{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 La{constructor(t){A(this,"_params");this._params={aiAgentChannelFilter:(t==null?void 0:t.aiAgentChannelFilter)??be.AIAgentChannelFilter.INCLUDE,aiAgentConversationStatusFilter:(t==null?void 0:t.aiAgentConversationStatusFilter)??[be.ConversationStatus.OPEN,be.ConversationStatus.CLOSED],aiAgentIds:(t==null?void 0:t.aiAgentIds)??[],deskChannelFilter:(t==null?void 0:t.deskChannelFilter)??be.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===be.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!==be.DeskChannelFilter.EXCLUDE:!1}}class gs extends ze.BaseChannelCollection{constructor(n,r){const o=new La(r.filter),s=n,a=s.aiAgent._manager,l=r.limit??20,c=ze.GroupChannelListOrder.LATEST_LAST_MESSAGE,d={getRemoteChannels:(m,f,g,_)=>a.getMyGroupChannels(m,f.params,_),changeLogSync:m=>{const{aiAgentChannelFilter:f,aiAgentIds:g,deskChannelFilter:_,pinnedChannelUrls:v,copilotConversationOnly:y,copilotSupportChannelUrl:b}=o.params,E={aiAgentChannelFilter:f,aiAgentIds:g,deskChannelFilter:_,pinnedChannelUrls:v,copilotConversationOnly:y,copilotSupportChannelUrl:b};return a.getMyGroupChannelChangeLogs(m,E,ze.GroupChannelEventSource.SYNC_CHANNEL_CHANGELOGS)}};super(s.aiAgent._iid,{filter:o,order:c,limit:l,syncKeyPrefix:"aiAgent",fetcher:d});A(this,"_params");A(this,"_sdk");A(this,"_throttledOnChannelChanged");A(this,"_key");A(this,"_pendingChannels",[]);this._sdk=n,this._params=r,this._key=`clc-${Ra()}`,this._throttledOnChannelChanged=fs(()=>{var _;const m=[...this._pendingChannels];this._pendingChannels=[];const f=new Map;for(const{channel:v,context:y}of m)f.delete(v.url),f.set(v.url,{channel:v,context:y});const g=new Map;for(const{channel:v,context:y}of f.values())g.has(y)||g.set(y,new Map),g.get(y).set(v.url,v);for(const[v,y]of g){const b=Array.from(y.values()),E=(_=this._sdk.currentUser)==null?void 0:_.userId,C=b.filter(x=>this.filter.match(x,E)),S=b.filter(x=>!this.filter.match(x,E)).map(x=>x.url);C.length>0&&this._base._addChannelsToView(C,v,!1),S.length>0&&this._removeChannels(S,v)}},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 hs{constructor(t){A(this,"subscribers",{});this.logger=t}async send(t){const n=Oa(),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 Oa=()=>{let e=ge,t=ge;return{promise:new Promise((r,o)=>{e=r,t=o}),resolve:e,reject:t}};var Fe=(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))(Fe||{});class Rt{constructor(t={}){A(this,"payload");this.payload=t}toJSON(){return JSON.stringify({type:this.type,payload:this.payload})}}const Ze={CloseConversation:e=>new Na(e),MessengerSettingsUpdated:e=>new Da(e),ActiveChannelUpdated:e=>new $a(e),AnonymousSessionTokenExpired:()=>new Pa,AuthTokenRefreshed:()=>new Fa};class Na extends Rt{constructor(){super(...arguments);A(this,"type","conv.close")}}class Da extends Rt{constructor(){super(...arguments);A(this,"type","messenger.settings.updated")}}class $a extends Rt{constructor(){super(...arguments);A(this,"type","active.channel.updated")}}class Pa extends Rt{constructor(){super(...arguments);A(this,"type","anon.token.expired")}}class Fa extends Rt{constructor(){super(...arguments);A(this,"type","auth.token.refreshed")}}var rr=(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))(rr||{});class ps{constructor(t){A(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 _s{constructor({userId:t,authToken:n,sessionHandler:r}){A(this,"userId");A(this,"authToken");A(this,"sessionHandler");this.userId=t,this.authToken=n,this.sessionHandler=r}}class Hn{constructor(){A(this,"userId");A(this,"authToken");A(this,"sessionHandler")}}const Ua=e=>({onSessionTokenRequired:t=>{t(null),e.send(Ze.AnonymousSessionTokenExpired())}}),Ba="ai_agent:stats",Ha="conversation_initial_render",Ga=800220;var ve=(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))(ve||{});class za{constructor(){A(this,"timers",new Map);A(this,"committed",!1);A(this,"commitCallback",null);A(this,"conversationId",null);A(this,"channelUrl",null);A(this,"errorCode",null);A(this,"errorDescription",null);A(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??Ga,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(Ba,t)):!1}}class Va extends za{constructor(){super(...arguments);A(this,"presentMethod","direct_present")}setPresentMethod(n){return this.presentMethod=n,this}getMetricKey(){return Ha}buildPayload(){const n=this.getDuration(ve.AUTH),r=this.getDuration(ve.GET_CHANNEL),o=this.getDuration(ve.GET_MESSAGES),s=this.getDuration(ve.TOTAL_DURATION_FROM_CACHE),a=this.getDuration(ve.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 Ya{constructor(t){A(this,"commitCallback");A(this,"presentMethod","direct_present");A(this,"stats",null);this.commitCallback=t}getOrCreateStats(){return(!this.stats||this.stats.isCommitted())&&(this.stats=new Va().setCommitCallback(this.commitCallback).setPresentMethod(this.presentMethod)),this.stats}onAuthStart(){this.getOrCreateStats().startTimer(ve.TOTAL_DURATION).startTimer(ve.TOTAL_DURATION_FROM_CACHE).startTimer(ve.AUTH)}onAuthComplete(){var t;(t=this.stats)==null||t.stopTimer(ve.AUTH)}onAuthError(t){this.stats&&!this.stats.isCommitted()&&this.stats.stopTimer(ve.AUTH).setError(t instanceof he.SendbirdError?t.code:void 0,t.message).stopTimer(ve.TOTAL_DURATION).commit()}onGetChannelStart(){var t;(t=this.stats)==null||t.startTimer(ve.GET_CHANNEL)}onGetChannelComplete(t){this.stats&&(this.stats.stopTimer(ve.GET_CHANNEL),t!==void 0&&this.stats.setConversationId(t),this.stats.startTimer(ve.GET_MESSAGES))}onGetChannelError(t){this.stats&&!this.stats.isCommitted()&&this.stats.stopTimer(ve.GET_CHANNEL).setError(t instanceof he.SendbirdError?t.code:void 0,t.message).stopTimer(ve.TOTAL_DURATION).commit()}onCacheResult(t){this.stats&&!this.stats.isCommitted()&&(t&&this.stats.setError(t instanceof he.SendbirdError?t.code:void 0,t.message),this.stats.stopTimer(ve.TOTAL_DURATION_FROM_CACHE))}onApiResult(t){this.stats&&!this.stats.isCommitted()&&(t&&this.stats.setError(t instanceof he.SendbirdError?t.code:void 0,t.message),this.stats.stopTimer(ve.TOTAL_DURATION).stopTimer(ve.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 Wa(){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 Es=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0)),Br={isTalkToAgentViewEnabled:!0,scrollMode:"auto",newMessageIndicatorEnabled:!0,senderAvatarEnabled:!0},or={conversation:{...Br,messageAlertSoundEnabled:!1,list:{...Br,markdownImageRenderMode:"default",markdownLinkRenderMode:"default"},header:{avatarEnabled:!0},input:{camera:{photoEnabled:!0},gallery:{photoEnabled:!0},fileEnabled:!0},fileViewer:{downloadEnabled:!0}},launcher:{unreadBadgeEnabled:!1}},Hr=e=>e?{conversation:Ka(e.conversation),launcher:qa(e.launcher)}:or,qa=e=>ut(or.launcher,e),Ka=e=>{const t=or.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);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,Es(r));return n},ja=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}),Xa=e=>({type:e.image_type||"default_icon",imageUrl:e.image_url}),Gn=e=>({enabled:e.enabled,showIndicator:e.show_indicator,toggleAllowed:e.toggle_allowed,deleteOnOff:e.delete_on_off,consentDialog:e.consent_dialog}),bs=(e,t)=>{if(e)return e.members.filter(n=>n.userId!==t).sort((n,r)=>r.joinedAt-n.joinedAt)[0]},Le=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===be.ConversationStatus.CLOSED||e!=null&&e.isDesk&&((n=e==null?void 0:e.helpdeskInfo)==null?void 0:n.ticketStatus)==="closed")},sr=e=>{var t,n;return!!(e!=null&&e.isAIAgent&&((t=e==null?void 0:e.conversation)==null?void 0:t.status)===be.ConversationStatus.OPEN||e!=null&&e.isDesk&&((n=e==null?void 0:e.helpdeskInfo)==null?void 0:n.ticketStatus)==="open")};function et(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 Za(e){var r;const t=(r=e==null?void 0:e.conversation)==null?void 0:r.handoff;return t?typeof t.requestedAt=="number"&&!et(e):!1}function Ja(e){var t;if(((t=e==null?void 0:e.resolution)==null?void 0:t.determinedBy)==="user")return e.resolution.isResolved}function Cs(e){return!!e&&e<=Date.now()}function Qa(e){return!e.title}function el(e,t){var n;if(e)return Qa(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 tl{constructor(){A(this,"_channelHandlerId",null);A(this,"_connectionHandlerId",null);A(this,"_handleActiveChannelChangedThrottled",null);A(this,"_setupChannelHandler",()=>{const t=Date.now();this._channelHandlerId=`aiagent_channel_${t}`,this._connectionHandlerId=`aiagent_connection_${t}`,this._handleActiveChannelChangedThrottled=fs(o=>{var s,a;(a=this._session)==null||a._updateActiveChannel({url:o.url,status:Le(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 ze.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 he.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})});A(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")});A(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:Le(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)}});A(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)}});A(this,"onMessengerSettingsUpdated",t=>(this._dispatcher.subscribe(Fe.MessengerSettingsUpdated,t),()=>{this._dispatcher.unsubscribe(Fe.MessengerSettingsUpdated,t)}));A(this,"onActiveChannelUpdated",t=>(this._dispatcher.subscribe(Fe.ActiveChannelUpdated,t),()=>{this._dispatcher.unsubscribe(Fe.ActiveChannelUpdated,t)}));A(this,"onAuthTokenRefreshed",t=>(this._dispatcher.subscribe(Fe.AuthTokenRefreshed,t),()=>{this._dispatcher.unsubscribe(Fe.AuthTokenRefreshed,t)}))}}class nl{constructor(t){A(this,"_sdkUser");A(this,"_userSession");A(this,"_dispatcher");A(this,"_activeChannel");A(this,"_updateActiveChannel",t=>{this._activeChannel=t,this._dispatcher.send(Ze.ActiveChannelUpdated({channelUrl:t.url,status:t.status,conversationStatus:t.conversationStatus}))});A(this,"_updateAuthToken",t=>{this._userSession.authToken=t,this._dispatcher.send(Ze.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 vs=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)}},ys=e=>JSON.parse(e),rl=e=>JSON.parse(e);function ol(e,t){const[n,r]=t.split(",").map(o=>o.trim());return e==="dark"&&r||n}function sl(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 il({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,vs(l))},e)}async function al({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,vs(l)),e)}var zn=(e=>(e[e.EXTERNAL_AUTH_TOKEN_EXPIRED=1]="EXTERNAL_AUTH_TOKEN_EXPIRED",e))(zn||{});const Ss=e=>typeof e=="object"&&e!==null,Gr=(e,t)=>t in e&&typeof e[t]=="string"&&e[t]!=="",ll=e=>!Ss(e)||!Gr(e,"channel_url")||!Gr(e,"ai_agent_id")?null:{channelUrl:e.channel_url,aiAgentId:e.ai_agent_id},cl={1:ll};function ul(e){if(!Ss(e)||!("cat"in e)||typeof e.cat!="number"||!("data"in e))return null;const t=e.cat,n=cl[t];if(!n)return null;const r=n(e.data);return r?{category:t,data:r}:null}function dl(e,t,n,r){const o=Ea.default.init({appId:e,modules:[new ze.GroupChannelModule,new be.AIAgentModule],localCacheEnabled:!0,options:new he.SendbirdChatOptions({typingIndicatorInvalidateTime:2e4}),...r});return o.addSendbirdExtensions([{version:n,product:he.SendbirdProduct.AI_AGENT,platform:t.platform}],{platform:t.deviceOSPlatform,version:t.deviceOSVersion},t.customData)||console.warn("Invalid Sendbird Extensions",t),o}function ml(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 fl=[400300,400301,400302,400310];class ir{constructor(t,n,r){A(this,"chatSDK");A(this,"_logger");A(this,"_cache");A(this,"connect",async(t,n,r,o)=>{if(this._logger.debug("ChatClient.connect: start",t.userId),n){const s=new he.SessionHandler({...n,onSessionTokenRequired:this._interceptTokenRefresh(n.onSessionTokenRequired,r,o)});this.chatSDK.setSessionHandler(s),this.chatSDK.aiAgent.addEventHandler(zn.EXTERNAL_AUTH_TOKEN_EXPIRED.toString(),a=>{var c;this._logger.debug("ChatClient.connect: EXTERNAL_AUTH_TOKEN_EXPIRED event received",a);const l=ul(a);(l==null?void 0:l.category)===zn.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}});A(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")});A(this,"getChannel",async t=>this.chatSDK.groupChannel.getChannel(t));A(this,"patchContext",async(t,n,r)=>this.chatSDK.aiAgent.patchContext(t,n,r));A(this,"updateContext",async(t,n,r)=>this.chatSDK.aiAgent.updateContext(t,n,r));A(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});A(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});A(this,"clearUserMemories",async(t={})=>{this._logger.debug("ChatClient.clearUserMemories: requesting",t),await this.chatSDK.aiAgent.clearUserMemories(t),this._logger.debug("ChatClient.clearUserMemories: completed")});A(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)})}});A(this,"_isCacheRestrictedError",t=>fl.some(n=>t.code===n));A(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}=ys(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?(ml(t.chatSDK),n=t.chatSDK):n=dl(t.appId,t.extensions,t.messengerVersion,t.chatParams),new ir(n,t.logger,t.cache)}}const Ft=new Map,As={set:(e,t)=>{Ft.set(e,t)},get:e=>{if(Ft.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=Ft.get(e);if(!n)throw new Error(`AIAgent platform "${e}" is not configured.`);return{platform:e,...n}}const t=Ft.entries().next().value;return{platform:t[0],...t[1]}}};class zr extends Error{constructor(n,r){const o=(r==null?void 0:r.detail)??"";super(o||`Desk API error (${n})`);A(this,"status");A(this,"code");A(this,"detail");this.name="DeskApiError",this.status=n,this.code=(r==null?void 0:r.code)??"",this.detail=o}}var ar=(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))(ar||{}),lr=(e=>(e.URGENT="URGENT",e.HIGH="HIGH",e.MEDIUM="MEDIUM",e.LOW="LOW",e))(lr||{}),xs=(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))(xs||{});const gl=e=>e==="desk401103"||e==="desk401106"||e==="desk401107"||e==="desk401108"||e==="desk401109";class hl{constructor(t){A(this,"_appId");A(this,"_apiHost");A(this,"_logger");A(this,"_credential",null);A(this,"_authRefreshPromise",null);A(this,"_onDeskTokenRefreshRequired",async()=>!1);A(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)});A(this,"setCredential",(t,n=async()=>!1)=>{this._authRefreshPromise=null,this._onDeskTokenRefreshRequired=n,this._credential=t});A(this,"clearCredential",()=>{this._authRefreshPromise=null,this._credential=null,this._onDeskTokenRefreshRequired=async()=>!1});A(this,"_handleUnauthorized",async(t,n,r)=>{const o=await this._parseErrorCode(t);if(!gl(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)});A(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}});A(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))}:{}}));A(this,"_buildParams",t=>new URLSearchParams({sendbirdAppId:this._appId,...t}));A(this,"_buildBody",t=>({sendbirdAppId:this._appId,...t}));A(this,"_buildHeaders",(t,n)=>({"content-type":"application/json",...t&&this._credential?{sendbirdDeskToken:this._credential.deskToken}:{},...n}));A(this,"_toResult",async t=>{if(!t.ok){const r=await t.json().catch(()=>({}));throw new zr(t.status,r)}const n=await t.text();if(n)try{return JSON.parse(n)}catch{throw new zr(t.status,{})}});A(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 Qt{constructor(t,n){A(this,"id");A(this,"title");A(this,"status");A(this,"agent");A(this,"priority");A(this,"group");A(this,"firstResponseTime");A(this,"issuedAt");A(this,"customFields");A(this,"_client");A(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 Qt({id:t.id,title:t.channelName??null,status:t.status2??ar.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??lr.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 cr{constructor(t){A(this,"_logger");A(this,"_apiClient");A(this,"_onDeskTokenRefreshRequired");A(this,"refreshDeskAuthToken",async t=>this._apiClient.credential?this.authenticate({userId:this._apiClient.credential.userId,accessToken:t,onDeskTokenRefreshRequired:this._onDeskTokenRefreshRequired}):!1);A(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}});A(this,"deauthenticate",()=>{this._apiClient.clearCredential(),this._onDeskTokenRefreshRequired=void 0,this._logger.debug("DeskClient.deauthenticate: token cleared")});A(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")});A(this,"getTicket",async t=>{this._assertAuthenticated(this._apiClient);const n=await this._apiClient.request(`/tickets/${encodeURIComponent(t)}/`,{method:"GET"});return Qt._fromResponse(n,this)});A(this,"createTicket",async t=>{this._assertAuthenticated(this._apiClient);const n=await this._apiClient.request("/tickets/",{method:"POST",body:Es({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 Qt._fromResponse(n,this)});this._logger=t.logger,this._apiClient=new hl(t)}static init(t){return new cr(t)}_assertAuthenticated(t){if(t.credential==null)throw new Error("DeskClient is not authenticated")}}class ur{constructor(){A(this,"authenticate",async t=>!1);A(this,"deauthenticate",()=>{});A(this,"refreshDeskAuthToken",async()=>!1);A(this,"setCustomerLanguage",async()=>{});A(this,"getTicket",async()=>{throw new Error("DeskClient is disabled via __SBA_USE_DESK_CLIENT__")})}static init(){return new ur}}function pl(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 _l=1440*60*1e3,El=typeof __SBA_USE_DESK_CLIENT__>"u"||__SBA_USE_DESK_CLIENT__;function qe(e){if(!e)throw new Error("Not authenticated. Call authenticate() first.")}function bl(e,t){return Object.entries(t).every(([n,r])=>e[n]===r)}class en extends tl{constructor(n){super();A(this,"appId");A(this,"aiAgentId");A(this,"_chatClient");A(this,"_deskClient");A(this,"_cache");A(this,"_logger");A(this,"_dispatcher");A(this,"_session",null);A(this,"language");A(this,"countryCode");A(this,"context");A(this,"queryParams");A(this,"_config");A(this,"_networkStateAdapter");A(this,"_forceCreateChannel");A(this,"_agentVersion");A(this,"_statsTrackers");A(this,"_operationQueue",Wa());A(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"))});A(this,"initConversationIfNeeded",n=>this._initConversationIfNeeded(n));A(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(Ze.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:y,session_token:b,expire_at:E}=f.auto_created_user;this._cache.messenger.setAnonUser({userId:y,authToken:b,expireAt:E}),g={userId:y,authToken:b},this._logger.debug("AIAgent.authenticate: anonymous user created",y)}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(Ze.MessengerSettingsUpdated({settings:f,source:"server"}));const _=(()=>{var y;return o.type==="anonymous"?Ua(this._dispatcher):(y=o.userSessionCandidate)==null?void 0:y.sessionHandler})(),v=await this._chatClient.connect(g,_,y=>{var b;this._logger.debug("AIAgent: session token refreshed"),(b=this._session)==null||b._updateAuthToken(y),this._deskClient.refreshDeskAuthToken(y)},()=>{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:y})=>{var b;if(y===xs.ERR_SESSION_KEY_EXPIRED){await new Promise(C=>setTimeout(C,2e3));const E=(b=this._session)==null?void 0:b.userSession.authToken;return E?await this._deskClient.refreshDeskAuthToken(E):!1}return!1}}),(s==null?void 0:s.language)!==f.language&&this._deskClient.setCustomerLanguage(this.language).catch(()=>{}),this._statsTrackers.initialRender.onAuthComplete(),this._session=new nl({sdkUser:v,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}})});A(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")}));A(this,"createConversation",async n=>{qe(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});A(this,"searchConversation",async n=>{if(qe(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:be.ConversationStatus.OPEN,limit:100}),o=[];for(;r.hasNext;){const s=await r.next();for(const a of s)bl(a.context??{},n.context)&&o.push(a.channelInfo.url)}return this._logger.debug("AIAgent.searchConversation: end",{count:o.length}),o});A(this,"closeConversation",async n=>{var o;qe(this._session),this._logger.debug("AIAgent.closeConversation: start",n);const r=await this._chatClient.getChannel(n);((o=r.conversation)==null?void 0:o.status)===be.ConversationStatus.OPEN?(await r.closeConversation(),this._session.activeChannel.url===n&&this._session._updateActiveChannel({url:n,status:"closed",conversationStatus:be.ConversationStatus.CLOSED}),this._logger.debug("AIAgent.closeConversation: end")):this._logger.debug("AIAgent.closeConversation: already closed or not an AI agent conversation")});A(this,"createConversationListCollection",n=>new gs(this.chatSDK,n??{}));A(this,"patchContext",async(n,r)=>{qe(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??{}}});A(this,"updateContext",async(n,r)=>{qe(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??{}}});A(this,"getContextObject",async n=>{qe(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??{}}});A(this,"clearUserMemories",async(n={})=>{qe(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")});A(this,"setUserMemoryState",async n=>{qe(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"),Gn(a);const l=this._cache.messenger.getSettings(s);if(l){const c={...l,memory:a};this._cache.messenger.setSettings(s,c),this._dispatcher.send(Ze.MessengerSettingsUpdated({settings:c,source:"cache"}))}return this._logger.debug("AIAgent.setUserMemoryState: end",a.enabled),Gn(a)});A(this,"refreshActiveChannel",async n=>{var l,c,d;qe(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});A(this,"_getSessionCandidate",n=>n instanceof _s?{type:"manual",userSessionCandidate:this._getManualSessionInfo(n)}:n instanceof Hn?{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});A(this,"_getAnonymousSessionInfo",()=>{const n=this._cache.messenger.getAnonUser();return n?n.expireAt-_l<=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});A(this,"_getManualSessionInfo",n=>{if(!n||n instanceof Hn)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=Hr(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 Ya((r,o)=>this._chatClient.chatSDK.aiAgent.appendStat(r,o))}}static init(n){var f;const r=As.get(n.platform),o=n.logger??new ps(n.logLevel??rr.WARN),s=n.dispatcher??new hs(o),a=n.useMMKVStorage?pl(n.useMMKVStorage):r.keyValueStorage,l=n.useMMKVStorage?{...n.chatParams,useMMKVStorageStore:n.useMMKVStorage}:n.chatParams,c=ka({appId:n.appId,aiAgentId:n.aiAgentId,storage:a}),d=ir.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=El?cr.init({appId:n.appId,logger:o,customApiHost:(f=n.deskParams)==null?void 0:f.customApiHost}):ur.init();return o.debug("AIAgent.init: created",{appId:n.appId,aiAgentId:n.aiAgentId}),new en({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=Hr(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 Ee=(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 Be(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(_=>({..._,[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 Cl(...e){return function({children:n}){return e.reduce((r,o)=>i.createElement(o,null,r),n)}}function vl(e,t){const n=e.lastMessage;return n!=null&&n.isAdminMessage()?n.message??"":Ts(e,t)}function Ts(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 yl(e,t,n){var a;const r=new Date,o=new Date(((a=e.lastMessage)==null?void 0:a.createdAt)||e.createdAt),s=Xe.differenceInMinutes(r,o);return s<1?n.justNow:s<60?n.minutesAgo(s):Xe.isToday(o)?n.hoursAgo(Xe.differenceInHours(r,o)):t(o,n.dateShortFormat)}const Sl=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},Ut=e=>Math.max(0,Math.min(255,e)).toString(16).padStart(2,"0"),Vr=(e,t)=>{const n=Ut(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=Sl(e);return r?`#${Ut(r[0])}${Ut(r[1])}${Ut(r[2])}${n}`:e},Al=(e,t)=>{if(!t)return e;const n={...e};for(const[r,o]of Object.entries(t))o&&(n[r]=o);return n},xl=e=>e.consentDialog?"consent":e.toggleAllowed?e.enabled?"on":"off":"readonly",Tl=e=>e.length>0,Il=e=>{const t=e[0];if(!t)return e;const n=e.some(o=>He(o.type)),r=e.some(o=>!He(o.type));return n&&r?He(t.type)?e.filter(o=>He(o.type)):[t]:r?[t]:e},Yr=e=>e.length===0?"empty":e.every(t=>He(t.type))?"images":"non_images",wl=({currentFiles:e,incomingFiles:t,maxAttachmentCount:n})=>{const r=Il(t),o=Yr(e),s=Yr(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,Is=6,Ml=e=>e%mt===0?mt:Is,kl=({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?Is/a:1,rowItemCount:a,isLastInRow:l===a-1,isLastRow:s||c}},ws=Ee("AIAgent"),Rl=ws.Provider,ke=ws.useContext;function Ll(e){const t=Ol(e);return i.createElement(Rl,{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 Ol(e){const t=u.useRef(null),n=u.useRef(null);if(!t.current||!n.current)t.current=en.init(e);else{const o=Nl(n.current,e);(o.appId||o.aiAgentId||o.chatSDK)&&(t.current.dispose(),t.current=en.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 Nl(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 Wr=Symbol("conversationMessageEventBridge"),Ct=Symbol("conversationMessageEventPublisher"),Dl=(e,t)=>{const n=e;if(n[Ct]=t,n[Wr])return e;n[Wr]=!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},dn=()=>{const[,e]=u.useState(0);return u.useCallback(()=>e(t=>t+1),[])};let $l=0;function Pl(){return u.useState(()=>`${$l++}`)[0]}const ht=(e,t,n)=>{const r=u.useRef(t),s=Pl();r.current=t,u.useEffect(()=>{var l;const a=c=>{const d=c;return Object.keys(d).forEach(f=>{d[f]=(...g)=>{var v;const _=r.current;(v=_[f])==null||v.call(_,...g)}}),d};return(l=e==null?void 0:e.groupChannel)==null||l.addGroupChannelHandler(s,a(new ze.GroupChannelHandler)),()=>{var c;(c=e==null?void 0:e.groupChannel)==null||c.removeGroupChannelHandler(s)}},[e==null?void 0:e.groupChannel,s])};function Fl(e,t){return!e||!t?!0:e.url!==t.url}function De(e){return e!=null&&"sendingStatus"in e}function Ul(e,t="##__USER_ID_IS_NOT_PROVIDED__##"){var n;return De(e)?((n=e.sender)==null?void 0:n.userId)===t:!1}function Bl(e,t){return Ul(e,t)||e.isAdminMessage()?!1:e.updatedAt===0}function qr(e){return"sendingStatus"in e?e.sendingStatus==="succeeded"?String(e.messageId):e.reqId:String(e.messageId)}const tn={collection:{groupChannel:{defaultOrder:ze.GroupChannelListOrder.LATEST_LAST_MESSAGE},message:{defaultLimit:{next:25,prev:25},searchLimit:{next:10,prev:10}}}};function Kr(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 Hl=({...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=Gl(t.value.messages);else{const n={...e.messageMap},r=[],o=[];t.value.messages.forEach(s=>{const a=De(s)?s.reqId:void 0,l=s.messageId||void 0;[a,l].forEach(c=>{if(!c)return;const d=n[c];zl(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=>{De(s)&&delete n[s.reqId],delete n[s.messageId]}),o.forEach(s=>{De(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=>Bl(o,n));return t.value.clearBeforeAction?e.newMessageMap=jr(r,qr):(r.map(s=>s.messageId).forEach(s=>delete e.newMessageMap[s]),e.newMessageMap={...e.newMessageMap,...jr(r,qr)}),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&&(De(o)&&delete e[n][o.reqId],delete e[n][o.messageId])}),t.value.reqIds.forEach(r=>{const o=e[n][r];o&&(De(o)&&delete e[n][o.reqId],delete e[n][o.messageId])}),e}}},Gl=e=>e.reduce((t,n)=>(De(n)?(t[n.reqId]=n,n.sendingStatus===Ue.SendingStatus.SUCCEEDED&&(t[n.messageId]=n)):t[n.messageId]=n,t),{}),zl=(e,t,n=!1)=>{var r,o;if(!De(e)||!De(t))return!0;if(n&&e&&Zr(e)&&Zr(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===Ue.SendingStatus.SUCCEEDED?t.sendingStatus===Ue.SendingStatus.SUCCEEDED:e.sendingStatus!==t.sendingStatus},Vl=(e=Yl)=>{const[{initialized:t,loading:n,refreshing:r,messageMap:o,newMessageMap:s},a]=u.useReducer(Hl,{initialized:!1,loading:!0,refreshing:!1,messageMap:{},newMessageMap:{}}),l=(b,E,C,S)=>{a({type:"update_messages",value:{messages:b,clearBeforeAction:E,currentUserId:C,strictStreamingOrder:S}})},c=(b,E)=>{a({type:"delete_messages",value:{messageIds:b,reqIds:E}})},d=(b,E,C)=>{a({type:"update_new_messages",value:{messages:b,clearBeforeAction:E,currentUserId:C}})},m=(b,E)=>{a({type:"delete_new_messages",value:{messageIds:b,reqIds:E}})},f=b=>{a({type:"update_initialized",value:{status:b}})},g=b=>{a({type:"update_loading",value:{status:b}})},_=b=>{a({type:"update_refreshing",value:{status:b}})},v=Object.values(s),y=u.useMemo(()=>Array.from(new Set(Object.values(o))).sort(e),[o]);return{updateInitialized:f,updateLoading:g,updateRefreshing:_,updateMessages:l,deleteMessages:c,initialized:t,loading:n,refreshing:r,messages:y,newMessages:v,updateNewMessages:d,deleteNewMessages:m}},Xr=Math.floor(Number.MAX_SAFE_INTEGER/10);function Yl(e,t){let n=0,r=0;return De(e)&&e.sendingStatus!=="succeeded"&&(n=Xr),De(t)&&t.sendingStatus!=="succeeded"&&(r=Xr),e.createdAt+n-(t.createdAt+r)}function Zr(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 Wl=(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 ze.MessageFilter(r)})};function Jr(e){return e<Date.now()?tn.collection.message.searchLimit:tn.collection.message.defaultLimit}const ql=(e,t,n={})=>{var Oe,Re;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=Jr(a),c=r.current.strictStreamingOrder??!1,d=u.useRef({prev:!1,next:!1}),m=dn(),f=u.useRef({initialized:!1,apiInitialized:!1,instance:null}),{initialized:g,loading:_,refreshing:v,messages:y,newMessages:b,updateMessages:E,updateNewMessages:C,deleteNewMessages:S,deleteMessages:x,updateInitialized:w,updateLoading:k,updateRefreshing:I}=Vl(n==null?void 0:n.sortComparator),M=ye(T=>{var R,N,j,U;if(!o.current||!o.current.url)return(R=s==null?void 0:s.error)==null?void 0:R.call(s,"[useGroupChannelMessages] channel is required");try{switch(T){case he.CollectionEventSource.EVENT_MESSAGE_RECEIVED:case he.CollectionEventSource.EVENT_MESSAGE_SENT_SUCCESS:case he.CollectionEventSource.SYNC_MESSAGE_FILL:case void 0:(j=(N=r.current).markAsRead)==null||j.call(N,[o.current]);break}}catch(G){(U=s==null?void 0:s.warn)==null||U.call(s,"[useGroupChannelMessages/markAsReadBySource]",G)}}),O=ye((T,R)=>{var N,j,U,G,B;if(R.length>0)switch(T){case he.CollectionEventSource.EVENT_MESSAGE_RECEIVED:case he.CollectionEventSource.SYNC_MESSAGE_FILL:{(j=(N=r.current).shouldCountNewMessages)!=null&&j.call(N)&&C(R,!1,(U=e.currentUser)==null?void 0:U.userId),(B=(G=r.current).onMessagesReceived)==null||B.call(G,R);break}}}),F=ye(T=>{var R,N;(N=(R=r.current).onCollectionEvent)==null||N.call(R,T)}),Y=ye(async(T,R,N)=>new Promise((j,U)=>{var $e;f.current.instance&&f.current.instance.dispose(),M(),C([],!0,($e=e.currentUser)==null?void 0:$e.userId);const G=()=>{var ie,re;const{pendingMessages:ae,failedMessages:ne}=f.current.instance??{};Kr(ae)&&E(ae,!1,(ie=e.currentUser)==null?void 0:ie.userId),Kr(ne)&&E(ne,!1,(re=e.currentUser)==null?void 0:re.userId)},B=Wl(T,N,{...r.current,startingPoint:R});f.current={apiInitialized:!1,initialized:!1,instance:B},B.setMessageCollectionHandler({onMessagesAdded:(ae,ne,ie)=>{var re;M(ae.source),O(ae.source,ie),E(ie,!1,(re=e.currentUser)==null?void 0:re.userId,c),F({kind:"messagesAdded",source:ae.source,messages:ie})},onMessagesUpdated:(ae,ne,ie)=>{var re,Z,le;M(ae.source),O(ae.source,ie),E(ie,!1,(re=e.currentUser)==null?void 0:re.userId,c),ae.source===he.CollectionEventSource.EVENT_MESSAGE_UPDATED&&((le=(Z=r.current).onMessagesUpdated)==null||le.call(Z,ie)),F({kind:"messagesUpdated",source:ae.source,messages:ie})},onMessagesDeleted:(ae,ne,ie,re)=>{const Z=re.map(pe=>pe.messageId),le=re.filter(De).map(pe=>pe.reqId);x(Z,le),S(Z,le),F({kind:"messagesDeleted",source:ae.source,messages:re})},onChannelDeleted:(ae,ne)=>{var ie,re;(re=(ie=r.current).onChannelDeleted)==null||re.call(ie,ne)},onChannelUpdated:(ae,ne)=>{var ie,re;m(),(re=(ie=r.current).onChannelUpdated)==null||re.call(ie,ne,ae)},onHugeGapDetected:()=>{Y(T,Number.MAX_SAFE_INTEGER,tn.collection.message.defaultLimit)}});let ue=!1;B.initialize(ze.MessageCollectionInitPolicy.CACHE_AND_REPLACE_BY_API).onCacheResult((ae,ne)=>{var ie,re,Z,le,pe;(re=(ie=r.current).onCacheResult)==null||re.call(ie,ae,ne??[]),ae?(e.isCacheEnabled&&((Z=s==null?void 0:s.error)==null||Z.call(s,"[useGroupChannelMessages/onCacheResult]",ae)),ue=!0):ne&&((le=s==null?void 0:s.debug)==null||le.call(s,"[useGroupChannelMessages/onCacheResult]","message length:",ne.length),E(B.succeededMessages,!0,(pe=e.currentUser)==null?void 0:pe.userId),G(),ne.length>0&&(f.current.initialized=!0,j())),F({kind:"initialized",source:"cache",messages:ne??[]})}).onApiResult((ae,ne)=>{var ie,re,Z,le,pe,rt,ot;(re=(ie=r.current).onApiResult)==null||re.call(ie,ae,ne??[]),f.current.initialized=!0,f.current.apiInitialized=!0,ae?((Z=s==null?void 0:s.warn)==null||Z.call(s,"[useGroupChannelMessages/onApiResult]",ae),ue?U(ae):j()):ne&&((le=s==null?void 0:s.debug)==null||le.call(s,"[useGroupChannelMessages/onApiResult]","message length:",ne.length),E(B.succeededMessages,!0,(pe=e.currentUser)==null?void 0:pe.userId),r.current.startingPoint||(ot=(rt=r.current).onMessagesReceived)==null||ot.call(rt,ne),e.isCacheEnabled&&G(),j()),F({kind:"initialized",source:"api",messages:ne??[]})})}));ht(e,{onUserBanned(T,R){var N,j,U;T.isGroupChannel()&&!Fl(T,o.current)&&(R.userId===((N=e.currentUser)==null?void 0:N.userId)?(U=(j=r.current).onCurrentUserBanned)==null||U.call(j):m())}}),u.useLayoutEffect(()=>{const T=setTimeout(async()=>{e.currentUser&&o.current&&(w(!1),k(!0),await Y(o.current,a,l),k(!1),w(!0))});return()=>clearTimeout(T)},[e,(Oe=e.currentUser)==null?void 0:Oe.userId,(Re=o.current)==null?void 0:Re.url,r.current.replyType]),u.useEffect(()=>()=>{f.current.instance&&f.current.instance.dispose()},[]);const z=ye(async()=>{e.currentUser&&o.current&&(I(!0),await Y(o.current,Number.MAX_SAFE_INTEGER,tn.collection.message.defaultLimit),I(!1))}),V=ye(async()=>{var R;const T=f.current.instance;if(T!=null&&T.hasPrevious&&!d.current.prev)try{d.current.prev=!0;const N=await T.loadPrevious();E(N,!1,(R=e.currentUser)==null?void 0:R.userId)}catch{}finally{d.current.prev=!1}}),H=ye(()=>{const{initialized:T,instance:R}=f.current;return T&&R?R.hasPrevious:!1}),W=ye(async()=>{var R;const T=f.current.instance;if(T!=null&&T.hasNext&&!d.current.next)try{d.current.next=!0;const N=await T.loadNext();E(N,!1,(R=e.currentUser)==null?void 0:R.userId)}catch{}finally{d.current.next=!1}}),q=ye(()=>{const{initialized:T,apiInitialized:R,instance:N}=f.current;return R&&T&&N?N.hasNext:!1}),ce=ye((T,R)=>{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((j,U)=>{o.current.sendUserMessage(T).onPending(G=>{var B;G.channelUrl===o.current.url&&E([G],!1,(B=e.currentUser)==null?void 0:B.userId),R==null||R(G)}).onSucceeded(G=>{var B;G.channelUrl===o.current.url&&E([G],!1,(B=e.currentUser)==null?void 0:B.userId),j(G)}).onFailed((G,B)=>{var ue;B&&B.channelUrl===o.current.url&&E([B],!1,(ue=e.currentUser)==null?void 0:ue.userId),U(G)})})}),_e=ye((T,R)=>{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((j,U)=>{o.current.sendFileMessage(T).onPending(G=>{var B;G.channelUrl===o.current.url&&E([G],!1,(B=e.currentUser)==null?void 0:B.userId),R==null||R(G)}).onSucceeded(G=>{var B;G.channelUrl===o.current.url&&E([G],!1,(B=e.currentUser)==null?void 0:B.userId),j(G)}).onFailed((G,B)=>{var ue;B&&B.channelUrl===o.current.url&&E([B],!1,(ue=e.currentUser)==null?void 0:ue.userId),U(G)})})}),L=ye(async(T,R)=>{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(j=>{const U=[];o.current.sendFileMessages(T).onPending(G=>{var B;G.channelUrl===o.current.url&&E([G],!1,(B=e.currentUser)==null?void 0:B.userId),R==null||R(G)}).onSucceeded(G=>{var B;G.isFileMessage()&&G.channelUrl===o.current.url&&(E([G],!1,(B=e.currentUser)==null?void 0:B.userId),U.push(G)),U.length===T.length&&j(U)}).onFailed((G,B)=>{var ue;B&&B.channelUrl===o.current.url?(E([B],!1,(ue=e.currentUser)==null?void 0:ue.userId),U.push(B)):U.push(null),U.length===T.length&&j(U)})})}),X=ye((T,R)=>{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((j,U)=>{o.current.sendMultipleFilesMessage(T).onPending(G=>{var B;G.channelUrl===o.current.url&&E([G],!1,(B=e.currentUser)==null?void 0:B.userId),R==null||R(G)}).onFileUploaded(()=>{m()}).onSucceeded(G=>{var B;G.channelUrl===o.current.url&&E([G],!1,(B=e.currentUser)==null?void 0:B.userId),j(G)}).onFailed((G,B)=>{var ue;B&&B.channelUrl===o.current.url&&E([B],!1,(ue=e.currentUser)==null?void 0:ue.userId),U(G)})})}),K=ye(async(T,R)=>{var j,U;if(!o.current||!o.current.url)throw(j=s==null?void 0:s.error)==null||j.call(s,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");const N=await o.current.updateUserMessage(T,R);return N.channelUrl===o.current.url&&E([N],!1,(U=e.currentUser)==null?void 0:U.userId),N}),P=ye(async(T,R)=>{var j,U;if(!o.current||!o.current.url)throw(j=s==null?void 0:s.error)==null||j.call(s,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");const N=await o.current.updateFileMessage(T,R);return N.channelUrl===o.current.url&&E([N],!1,(U=e.currentUser)==null?void 0:U.userId),N}),te=ye(async T=>{var R;if(!o.current||!o.current.url)throw(R=s==null?void 0:s.error)==null||R.call(s,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");return new Promise((N,j)=>{let U;T.isUserMessage()&&(U=o.current.resendMessage(T)),T.isFileMessage()&&(U=o.current.resendMessage(T)),T.isMultipleFilesMessage()&&(U=o.current.resendMessage(T)),U&&("onPending"in U&&U.onPending(G=>{var B;G.channelUrl===o.current.url&&E([G],!1,(B=e.currentUser)==null?void 0:B.userId)}),"onFileUploaded"in U&&U.onFileUploaded(()=>{m()}),"onSucceeded"in U&&U.onSucceeded(G=>{var B;G.channelUrl===o.current.url&&E([G],!1,(B=e.currentUser)==null?void 0:B.userId),N(G)}),"onFailed"in U&&U.onFailed((G,B)=>{var ue;B&&B.channelUrl===o.current.url&&E([B],!1,(ue=e.currentUser)==null?void 0:ue.userId),j(G)}))})}),de=ye(async T=>{var R,N;if(!o.current||!o.current.url)throw(R=s==null?void 0:s.error)==null||R.call(s,"[useGroupChannelMessages] channel is required"),new Error("Channel is required");if(T.sendingStatus==="succeeded")T.isUserMessage()&&await o.current.deleteMessage(T),T.isFileMessage()&&await o.current.deleteMessage(T),T.isMultipleFilesMessage()&&await o.current.deleteMessage(T);else try{await((N=f.current.instance)==null?void 0:N.removeFailedMessage(T.reqId))}finally{x([],[T.reqId])}}),fe=ye(()=>{var T;C([],!0,(T=e.currentUser)==null?void 0:T.userId)}),xe=ye(async T=>{var R;if(e.currentUser&&o.current){const N=Jr(T);k(!0),E([],!0,(R=e.currentUser)==null?void 0:R.userId),await Y(o.current,T,N),k(!1)}});return{initialized:g,loading:_,refreshing:v,messages:y,newMessages:b,resetNewMessages:fe,refresh:z,loadPrevious:V,hasPrevious:H,loadNext:W,hasNext:q,sendUserMessage:ce,sendFileMessage:_e,sendFileMessages:L,sendMultipleFilesMessage:X,updateUserMessage:K,updateFileMessage:P,resendMessage:te,deleteMessage:de,resetWithStartingPoint:xe,_dangerous_reducer_updateMessages:E,_dangerous_reducer_deleteMessages:x}},Kl=(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 ze.MessageFilter(d)}));if(!m)throw new Error("Group channel is required to create a message collection");return Dl(m,s)},[t,n==null?void 0:n.collectionCreator,s]),l=ql(e,t,{...n,collectionCreator:a,strictStreamingOrder:!0}),c=u.useCallback(d=>(o.current.add(d),()=>{o.current.delete(d)}),[]);return{...l,subscribeMessageEvents:c}},wt={DEFAULT_PRIMARY:"#000000",DEFAULT_BOT_MSG_BG:"#ECECEC",WHITE:"#ffffff",BLACK:"#000000"};function Ms(e){return e.length===4?`#${[...e.slice(1)].map(t=>t+t).join("")}`:e}function jl(e){const t=Ms(e);return[parseInt(t.slice(1,3),16),parseInt(t.slice(3,5),16),parseInt(t.slice(5,7),16)]}function Xl(e){return`#${e.map(t=>t.toString(16).padStart(2,"0")).join("")}`}function Zl(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 Jl(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 Bt(e,t,n){const[r,o,s]=jl(e),[a,l,c]=Zl(r,o,s),d=Math.max(0,Math.min(1,c*t)),m=Math.max(0,Math.min(1,l*n)),[f,g,_]=Jl(a,m,d);return Xl([Math.round(f),Math.round(g),Math.round(_)])}function Ql(e,t="light"){return{extraDark:Bt(e,.6,1.2),dark:Bt(e,.85,1.1),main:e,light:Bt(e,t==="dark"?1.1:1.5,t==="dark"?.95:.9),extraLight:Bt(e,t==="dark"?1.2:1.75,t==="dark"?.9:.8)}}function Vn(e){const t=Ms(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?wt.BLACK:wt.WHITE}function ec(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 tc=(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"}}),Ht={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)"}},xn={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 Qr(e){const t=nc(e),n=rc(e,t),r=sc(n,e.colors,e.selectedTheme),o=ac(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 nc({selectedTheme:e,palette:t,primary:n}){const r=t!=null&&t.primary?t.primary:n?n===Ht.primary.main?Ht.primary:Ql(n,e):Ht.primary;return{...Ht,primary:r,...t}}function rc({selectedTheme:e,primaryContrast:t,botMessageBackground:n,botMessageBackgroundContrast:r},o){const s=o.primary.main,a=t??Vn(s),l=n??wt.DEFAULT_BOT_MSG_BG,c=r??Vn(l);return(e==="light"?ec:tc)(o,s,a,l,c)}function oc(e,t,n){return typeof e=="string"?e:e[t]??n}function sc(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]=oc(m,n,f)}}}return r}function ic(e,t,n){const r={...e};return n.forEach(o=>{const s=t[o];s!=null&&(r[o]=s)}),r}function ac({typography:e}){if(!e)return xn;const t={...xn};return Object.keys(e).forEach(n=>{const r=e[n];if(r&&typeof r=="object"){const o=xn[n],s=["fontSize","fontWeight","fontFamily","lineHeight"];t[n]=ic(o,r,s)}}),t}const{Provider:lc,useContext:dr}=Ee("AIAgentTheme");function cc({logger:e,palette:t,typography:n,colors:r,appearance:o,children:s}){const a=u.useRef(null),[l,c]=u.useState(()=>Qr({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,_=a.current?a.current.themes[g]:null,v={primary:o==null?void 0:o.primaryColor,primaryContrast:void 0,botMessageBackground:o==null?void 0:o.botMessageBackgroundColor,botMessageBackgroundContrast:void 0};!v.primary&&(_!=null&&_.primary_color)&&(v.primary=_.primary_color,v.primaryContrast=_.primary_contrast_color),!v.botMessageBackground&&(_!=null&&_.bot_message_bg_color)&&(v.botMessageBackground=_.bot_message_bg_color,v.botMessageBackgroundContrast=_.bot_message_bg_contrast_color);const y=Qr({selectedTheme:g,palette:t,typography:n,colors:r,...v});c(y),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(lc,{value:{theme:l,updateTheme:d}},s)}const Tn=25*1024*1024,eo=1,to=new Set(["image/png","image/jpeg","image/jpg"]),no=new Set(["application/pdf"]),uc={off:"off",always:"always",handed_off_only:"handed_off_only"},dc=()=>{const[e,t]=u.useState(()=>({maxAttachmentCount:eo,attachmentMode:"handed_off_only",defaultUploadSizeLimit:Tn,uploadSizeLimitPerType:new Map,supportedImageMimeTypes:to,supportedFileMimeTypes:no})),n=u.useCallback(({active_channel:o,upload_restriction:s})=>{t({maxAttachmentCount:(s==null?void 0:s.max_attachment_count)??eo,attachmentMode:uc[o.attachment_mode]??"handed_off_only",defaultUploadSizeLimit:(s==null?void 0:s.default_upload_size_limit)??Tn,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)??to),supportedFileMimeTypes:new Set((s==null?void 0:s.supported_file_mime_types)??no)})},[]),r=u.useCallback(o=>{const{channel:s,uploadSizeLimit:a=Tn}=o,l=(d=!0)=>s!=null&&s.isAIAgent?d?et(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 et(s);default:return!0}},get supportedMimeTypes(){return l()?[Un]:[...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}},ro=(...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:mc,useContext:pt}=Ee("AIAgentMessengerSession"),fc=u.forwardRef(function({userSessionInfo:e,children:t},n){const{_aiAgentSDK:r,chatSDK:o,aiAgentId:s,logger:a}=ke(),{updateTheme:l}=dr(),[c,d]=u.useState(void 0),[m,f]=u.useState(void 0),[g,_]=u.useState(null),[v,y]=u.useState(null),[b,E]=u.useState(null),[C,S]=u.useState(null),[x,w]=u.useState(null),{updateBaseAttachmentRules:k,createAttachmentRules:I}=dc();u.useEffect(()=>{const Y=r.onMessengerSettingsUpdated(({settings:H})=>{const{appearance:W,bot:q,launcher:ce,memory:_e}=H;l(W.selected_theme,W),E(ja(q)),S(Xa(ce)),w(_e?Gn(_e):null),k(H)}),z=r.onActiveChannelUpdated(({channelUrl:H,status:W,conversationStatus:q})=>{f({url:H,status:W,conversationStatus:q})}),V=r.onAuthTokenRefreshed(()=>{var W;const H=(W=r.session)==null?void 0:W.userSession.authToken;H&&y(q=>q?{...q,authToken:H}:null)});return()=>{Y(),z(),V()}},[r,l,k]);const M=u.useCallback(async()=>{try{const Y=await r.authenticate(e),z=r.session;return _(z.sdkUser),y(z.userSession),f(z.activeChannel),d(void 0),Y}catch(Y){throw _(null),y(null),f(void 0),d(Y),Y}},[r,e]),O=u.useCallback(async()=>{await r.deauthenticate(),_(null),f(void 0),y(null),E(null),S(null),w(null)},[r]),F=u.useCallback(async()=>{if(!r.session){if(v)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!==(v==null?void 0:v.userId)?(a.debug("agentMessengerSession.refreshActiveChannel: stale call from previous session, skipping"),r.session.activeChannel.url):(f(void 0),await r.refreshActiveChannel())},[r,a,v]);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:M,deauthenticate:O,updateContext:async(...z)=>{const V=ro(...z);if(V.type==="active"){const q=await(await Y()).updateContext(s,V.context);return vt(q)}const H=await o.aiAgent.updateContext(V.aiAgentId,V.channelUrl,V.context);return vt(H)},patchContext:async(...z)=>{const V=ro(...z);if(V.type==="active"){const q=await(await Y()).patchContext(s,V.context);return vt(q)}const H=await o.aiAgent.patchContext(V.aiAgentId,V.channelUrl,V.context);return vt(H)},getContextObject:async()=>{const V=await(await Y()).getContextObject(s);return vt(V)}}},[M,O,m,o,s,a]),i.createElement(mc,{value:{sdkUser:g,userSessionInfo:e,userSession:v,activeChannel:m,setActiveChannel:f,refreshActiveChannel:F,createConversation:r.createConversation,searchConversation:r.searchConversation,connectionError:c,aiAgentInfo:b,launcherInfo:C,memoryInfo:x,authenticate:M,deauthenticate:O,createAttachmentRules:I,statsTrackers:r.statsTrackers}},t)}),Lt=(e,t)=>{const n=u.useId(),r=u.useRef(t);u.useLayoutEffect(()=>{r.current=t}),u.useLayoutEffect(()=>{const o=new he.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 gc(e){const{chatSDK:t,logger:n,aiAgentId:r,_aiAgentSDK:o}=ke(),{sdkUser:s,statsTrackers:a}=pt(),l=dn(),[c,d]=u.useState(void 0),[m,f]=u.useState(void 0),[g,_]=u.useState(!1);function v(b){b.isAIAgent&&!b.conversation&&(_(!0),o.initConversationIfNeeded(b).finally(()=>_(!1)))}async function y(){var b,E,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),_(!1),e){a.initialRender.onGetChannelStart();try{n.debug("useChannel.getChannel: get channel",e);const S=await t.groupChannel.getChannel(e);v(S),d(S),a.initialRender.onGetChannelComplete((b=S.conversation)==null?void 0:b.id),S.url===((E=o.session)==null?void 0:E.activeChannel.url)&&o.session._updateActiveChannel({url:S.url,status:Le(S)?"closed":"open",conversationStatus:(C=S.conversation)==null?void 0:C.status}),n.debug("useChannel.getChannel: fetched channel",S)}catch(S){a.initialRender.onGetChannelError(S),S instanceof he.SendbirdError&&f(S),n.error("useChannel.getChannel: error",S)}}}return u.useEffect(()=>{y()},[t,s,e,r]),Lt(t,{async onReconnectSucceeded(){if(!c)return;const b=await c.refresh();v(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:y,isInitializingConversation:g}}const hc=new Set(["suggested_replies","steward","system"]),pc=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||!hc.has(r)))return r},_c=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},Ec=()=>{const{chatSDK:e,networkStateAdapter:t}=ke(),[n,r]=u.useState(()=>t?t.isOnline()?"connected":"reconnecting":"connected");return Lt(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===he.ConnectionState.OPEN?"connected":s)})},[t,e]),n},bc=3e4,Cc=({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=bc-m;return n||f<=0?c():d(f),()=>{a.current&&clearTimeout(a.current)}},[n,l]),o&&e},ks=e=>{const{chatSDK:t}=ke(),[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},vc=({channel:e,lastMessage:t,aiAgentUserId:n,isStreamAnimating:r})=>{const[o,s]=u.useState(!1),a=ks(e);return u.useEffect(()=>{if(!t)return;const l=a.some(d=>d.userId===n),c=gt(t,n)&&(Ve.isStreaming(t)||r);s(c||l)},[a,t,n,r]),o},yc=({channel:e,messages:t,isStreamAnimating:n,isInitializingConversation:r})=>{const{aiAgentInfo:o,userSession:s}=pt(),a=Ec(),l=vc({channel:e,lastMessage:Ur(t,[Ue.SendingStatus.SUCCEEDED]),aiAgentUserId:(o==null?void 0:o.userId)??"",isStreamAnimating:n}),c=Cc({shouldApply:!!(e!=null&&e.isAIAgent)&&!et(e),isBlockedWhileAIResponding:l,lastMessage:Ur(t,[Ue.SendingStatus.PENDING,Ue.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(Le(e))return d("conversation_closed");if(Za(e))return d("handoff_pending");if(_c(e))return d("form_active");const m=pc(e);return d(m||(l||c||r?"ai_responding":""))},Sc=()=>{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:Ac}=Ee("AIAgentConversation");function xc({children:e,channelUrl:t,onChannelDeleted:n,onMessagesReceived:r,onMessagesUpdated:o,onConversationClosedStatusChanged:s,onConversationClosedViaDispatcher:a,onBeforeSendMessage:l,onAfterSendMessage:c=ge,shouldMarkAsRead:d=!0,shouldCountNewMessages:m=()=>!1,sortComparator:f}){var Y;const g=()=>d&&(E==null?void 0:E.markAsRead()),{_aiAgentSDK:_,chatSDK:v,logger:y,dispatcher:b}=ke(),{channel:E,channelFetchError:C,getChannel:S,isInitializingConversation:x}=gc(t),{statsTrackers:w}=pt();u.useEffect(()=>{if(t)return w.initialRender.setChannelUrl(t),()=>{w.initialRender.cleanup()}},[t,w]);const k=Kl(v,E,{replyType:Ue.ReplyType.ONLY_REPLY_TO_CHANNEL,shouldCountNewMessages:m,onChannelDeleted:n,onMessagesReceived:z=>r==null?void 0:r(z),onMessagesUpdated:z=>o==null?void 0:o(z),onCacheResult:z=>w.initialRender.onCacheResult(z),onApiResult:z=>w.initialRender.onApiResult(z),logger:y,markAsRead:g,sortComparator:f}),I=Sc(),M=yc({channel:E,messages:k.messages,isStreamAnimating:I.isAnimating,isInitializingConversation:x});u.useEffect(()=>{g()},[d,E]);const O=Le(E);u.useEffect(()=>{s==null||s(O)},[O,s]),u.useEffect(()=>{const z=async V=>{const H=typeof(V==null?void 0:V.channelUrl)=="string";E&&H&&V.channelUrl!==E.url||(y.debug("conversation.dispatcher: try to close conversation",E),E!=null&&E.conversation&&E.conversation.status===be.ConversationStatus.OPEN&&(await E.closeConversation(),a==null||a()))};return b.subscribe(Fe.ConversationClose,z),()=>{b.unsubscribe(Fe.ConversationClose,z)}},[b,E,y,(Y=E==null?void 0:E.conversation)==null?void 0:Y.status,a]);const F={conversation:(E==null?void 0:E.conversation)??void 0,actions:{setUserMemoryState:_.setUserMemoryState},channelSource:{channel:E,error:C,refetch:()=>S(),closeConversation:async()=>{Le(E)||await(E==null?void 0:E.closeConversation())}},messageSource:{messages:k.messages,newMessages:k.newMessages,initialized:k.initialized,subscribeMessageEvents:k.subscribeMessageEvents,loadPrevious:()=>k.loadPrevious(),loadNext:()=>k.loadNext(),deleteMessage:z=>k.deleteMessage(z),resendMessage:z=>k.resendMessage(z),resetNewMessages:()=>k.resetNewMessages(),sendUserMessage:async z=>{var H;if(((H=E==null?void 0:E.conversation)==null?void 0:H.status)===be.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(z=await l(z));const V=await k.sendUserMessage(z,c);return c==null||c(V),V},sendFileMessage:async z=>{var H;if(((H=E==null?void 0:E.conversation)==null?void 0:H.status)===be.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(z=await l(z));const V=await k.sendFileMessage(z,c);return c==null||c(V),V},sendMultipleFilesMessage:async z=>{var H;if(((H=E==null?void 0:E.conversation)==null?void 0:H.status)===be.ConversationStatus.CLOSED)throw new Error("Conversation is closed");l&&(z=await l(z));const V=await k.sendMultipleFilesMessage(z,c);return c==null||c(V),V}},state:{streamAnimation:I,input:M}};return i.createElement(Ac,{value:F},e)}function Tc(e,t){var _,v,y,b,E,C,S,x,w,k;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 I=new gs(e,t);I.setConversationListCollectionHandler({onChannelsAdded:()=>{l(I.channels)},onChannelsUpdated:()=>{l(I.channels)},onChannelsDeleted:()=>{l(I.channels)}}),await I.loadMore(),l(I.channels),d(I),s(null)}catch(I){d(null),s(I)}finally{r(!0),m.current=!1}}},[e,e.currentUser,(_=t.filter)==null?void 0:_.aiAgentChannelFilter,(y=(v=t.filter)==null?void 0:v.aiAgentConversationStatusFilter)==null?void 0:y.join(),(E=(b=t.filter)==null?void 0:b.aiAgentIds)==null?void 0:E.join(),(C=t.filter)==null?void 0:C.deskChannelFilter,(x=(S=t.filter)==null?void 0:S.pinnedChannelUrls)==null?void 0:x.join(),(w=t.filter)==null?void 0:w.copilotConversationOnly,(k=t.filter)==null?void 0:k.copilotSupportChannelUrl,t.limit]),g=u.useCallback(async()=>{if(c)try{await c.loadMore(),l(c.channels)}catch(I){s(I)}},[c]);return Lt(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 Rs=e=>{var o;const{aiAgentId:t,queryParams:n}=ke(),r=(o=n==null?void 0:n.conversationListParams)==null?void 0:o.filter;return{aiAgentIds:[t],aiAgentConversationStatusFilter:[be.ConversationStatus.CLOSED,be.ConversationStatus.OPEN],...r,...e}},{Provider:Ic}=Ee("AIAgentConversationList");function wc({conversationListLimit:e,conversationListFilter:t,children:n}){var d;const{chatSDK:r,queryParams:o}=ke(),s=e??((d=o==null?void 0:o.conversationListParams)==null?void 0:d.limit),a=Rs(t),l=Tc(r,{limit:s,filter:a}),c={listSource:{initialized:l.initialized,error:l.error??void 0,channels:l.channels,loadMore:()=>l.loadMore()}};return i.createElement(Ic,{value:c},n)}function Mc(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:kc,useContext:Rc}=Ee("MessageTemplateFetching");function Lc({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 _=m(f);if(_)return _;const v=r.current[f];if(v)return v;g||a(f,{fetching:!0});const y=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]=y,y},[a]),c={internalVariables:t,fetchTemplate:l,suspend:(d,m)=>{if(n.current[d])return n.current[d];const f=Mc(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(kc,{value:c},e)}const Oc="remove_powered_by",mr=(e,t)=>{var o,s;const{chatSDK:n}=ke(),{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&&sr(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(Oc)),[a])}throw new Error("Unsupported feature")},Nc={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"},Dc={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}}},$c={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}}},Pc={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}}},Fc={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}}},Uc={text:Dc,number:$c,"single-select":Pc,"multi-select":Fc},Bc={getValueOrDefault:()=>null,validate:()=>({isValid:!1})};function Ls(e){return Uc[e.type]||Bc}function oo(e){return Ls(e).getValueOrDefault(e)}function Hc(e,t,n={}){const r={...Nc,...n};return Ls(e).validate(e,t,r)}const Gc=(e,t={})=>{const{labels:n={},onSubmit:r,onCancel:o}=t,[s,a]=u.useState({}),[l,c]=u.useState(()=>{const y={};return e.fields.forEach(b=>{y[b.key]=oo(b)}),y}),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 y={};let b=!1;e.fields.forEach(E=>{const C=oo(E);JSON.stringify(l[E.key])!==JSON.stringify(C)&&(b=!0),y[E.key]=C}),b&&c(y)}},[d]);const m=(y,b)=>{c(E=>({...E,[y]:b})),a(E=>({...E,[y]:void 0}))},f=e.fields.map(y=>{var C,S,x;const b=l[y.key]??null,E={key:y.key,label:y.label,error:s[y.key],required:y.required};return y.type==="text"?{...E,type:"text",layout:y.layout,value:b,...y.placeholder&&{placeholder:y.placeholder},...((C=y.rules)==null?void 0:C.max_length)&&{maxLength:y.rules.max_length}}:y.type==="number"?{...E,type:"number",layout:y.layout,value:b,...y.placeholder&&{placeholder:y.placeholder},...((S=y.rules)==null?void 0:S.max)&&{max:y.rules.max}}:y.type==="single-select"?{...E,type:"single-select",layout:y.layout,value:b,options:y.options}:y.type==="multi-select"?{...E,type:"multi-select",layout:y.layout,value:b,options:y.options,...((x=y.rules)==null?void 0:x.max_select)&&{maxSelect:y.rules.max_select}}:{...E,type:"unknown",layout:"default",value:null}});return{state:d,fields:f,getField:y=>f.find(b=>b.key===y),updateFieldValue:m,submit:async()=>{const y={};let b=!1;for(const E of e.fields){const C=l[E.key]??null,S=Hc(E,C,n);S.isValid||(y[E.key]=S.error,b=!0)}if(a(y),!b&&r){const E={};e.fields.forEach(C=>{E[C.key]=l[C.key]??null}),await r(E)}},cancel:async()=>{await(o==null?void 0:o())}}},zc=e=>{const{chatSDK:t,handlers:n,logger:r}=ke(),{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(Ve.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=Bn(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}},Vc=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},Os=e=>{const{aiAgentInfo:t}=pt(),n=ks(e);if(Le(e))return null;const r=n[0];if(!r)return null;const o=r.userId===(t==null?void 0:t.userId),s=o?Vc(r.metaData):void 0;return{user:o?t:r,isBot:o,thinkingMessage:s}},Yc=(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},[])},Wc=(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()}}},qc=(e,t,n=1e4,r=!0)=>{const o=u.useRef(null),s=u.useRef(null),a=u.useRef(!1);o.current||(o.current=Wc(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])};var Ye=(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))(Ye||{});const Kc=({csat:e,csatExpireAt:t,csatPayload:n,isSubmitInFlight:r})=>{const o=!!n&&n.visibility&&!!Ye[n.type],s=!r&&typeof e!="number"&&Cs(t),a=dn();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}},jc=({csat:e,csatExpireAt:t,csatPayload:n,announceStatus:r,onSubmittedAnnounced:o,isSubmitInFlight:s=!1})=>{const{isRenderableCSAT:a,isExpiredNow:l}=Kc({csat:e,csatExpireAt:t,csatPayload:n,isSubmitInFlight:s}),c=(n==null?void 0:n.csat_submitted_label)??"",d=u.useRef(a&&typeof e=="number"),m=u.useRef(a&&l);return u.useEffect(()=>{a&&c&&(typeof e!="number"||d.current||(d.current=!0,r({event:"csatSubmitted",submittedLabel:c}),o==null||o()))},[r,e,a,o,c]),u.useEffect(()=>{a&&l&&(m.current||(m.current=!0,r({event:"csatExpired"})))},[r,l,a]),{isExpiredNow:l,isRenderableCSAT:a}},fr=({channel:e,userSession:t,aiAgentInfo:n})=>{if(!t||!n||!e)return{fallbackIcon:"delight",url:void 0,title:""};const r=bs(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?et(e)?o.human("agent"):o.ai("delight"):e.isDesk?o.human("agent"):o.channel("user")},so=e=>u.useReducer((t,n)=>({...t,...n}),e),Xc=new Set(["free_text","single_choice"]),Zc=({csatPayload:e,type:t,initialCsat:n,initialCsatReason:r,initialIsResolved:o})=>{const[s,a]=so({csatType:t,csat:n,csatReason:r,isResolved:o}),[l,c]=so({followUpItem:!1}),d=u.useMemo(()=>{var b;const _=s.csat,v=typeof _=="number",y=(b=e.follow_up)==null?void 0:b.find(E=>v?E.scores.includes(_):E.always_visible??!1);if(Xc.has(y==null?void 0:y.response_type))return y},[s.csat,e.follow_up]),m=(()=>{var _;if(typeof n=="number")return"submitted";if((t===Ye.AI_AGENT_CSAT_5||t===Ye.HELPDESK_CSAT_5)&&typeof s.csat=="number")return"submittable";if(t===Ye.AI_AGENT_CSAT_5_WITH_CRE){const v=typeof s.csat=="number",y=!((_=e.cre)!=null&&_.required)||typeof s.isResolved=="boolean";if(v&&y)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"}}},In=5,Jc=250,Qc=50,io=e=>Math.max(0,e-Qc),eu=e=>e<1e3?{speed:In*.5,chunkSize:2}:e<2e3?{speed:In*.8,chunkSize:2}:{speed:In*.6,chunkSize:3},jt=(e,t)=>{let n=0;for(let r=t-1;r>=0&&e[r]==="\\";r--)n++;return n%2===1},ao=(e,t,n,r)=>{let o=1,s=t;for(;s<e.length&&o>0;){if(jt(e,s)){s++;continue}e[s]===n?o++:e[s]===r&&o--,s++}return o>0?-1:s},tu=(e,{hideImages:t,hideLinks:n})=>{let r="",o=0,s=0;for(;o<e.length;){if(e[o]==="`"&&!jt(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]==="["&&!jt(e,o),l=e[o]==="["&&!jt(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=ao(e,o+(a?2:1),"[","]");if(d===-1)return r;if(o=d,e[o]!=="("){r+=e.slice(c,o);continue}const m=ao(e,o+1,"(",")");if(m===-1)return r;o=m,r+=e.slice(c,o)}return r},nu=e=>{const{text:t,enabled:n=!1,markdownImageRenderMode:r="default",markdownLinkRenderMode:o="default",onAnimationStart:s,onAnimationProgress:a,onAnimationComplete:l}=e,[c,d]=u.useState(()=>io(t.length)),m=u.useRef(null),f=u.useRef({startTime:0,lastUpdate:0,lastProgressCall:0}).current,g=u.useRef({onStart:s,onProgress:a,onComplete:l}).current,_=u.useRef({startCalled:!1,completeCalled:!1}).current,v=u.useRef({initialEnabled:n,textLength:t.length,enabled:n}).current,y=n,b=c<t.length,E=v.initialEnabled&&(y||b);return u.useLayoutEffect(()=>{g.onStart=s,g.onProgress=a,g.onComplete=l,v.textLength=t.length,v.enabled=n}),u.useLayoutEffect(()=>{var S;v.initialEnabled&&(_.startCalled||(_.startCalled=!0,(S=g.onStart)==null||S.call(g)),d(x=>t.length<x?t.length:x))},[t]),u.useEffect(()=>{if(!v.initialEnabled)return;let S=io(t.length);f.lastUpdate=0,f.startTime=0,f.lastProgressCall=0;const x=w=>{var V;f.lastUpdate===0&&(f.lastUpdate=w,f.startTime=w,f.lastProgressCall=w);const k=v.textLength,I=w-f.lastUpdate,M=w-f.startTime,{speed:O,chunkSize:F}=eu(M),Y=O*F;I>=Y&&S<k&&(S=Math.min(S+F,k),d(S),f.lastUpdate=w),w-f.lastProgressCall>=Jc&&(f.lastProgressCall=w,(V=g.onProgress)==null||V.call(g)),(S<k||v.enabled)&&(m.current=requestAnimationFrame(x))};return m.current=requestAnimationFrame(x),()=>{var w;m.current&&cancelAnimationFrame(m.current),_.startCalled&&!_.completeCalled&&(_.completeCalled=!0,(w=g.onComplete)==null||w.call(g))}},[]),u.useEffect(()=>{var k;const S=v.initialEnabled&&_.startCalled,x=!n,w=c>=t.length&&t.length>0;S&&x&&w&&!_.completeCalled&&(_.completeCalled=!0,(k=g.onComplete)==null||k.call(g))},[n,c,t.length]),{streamText:u.useMemo(()=>{const S=v.initialEnabled?t.slice(0,c):t,x=E&&r==="complete-only",w=E&&o==="complete-only";return!x&&!w?S:tu(S,{hideImages:x,hideLinks:w})},[t,c,r,o,E]),isAnimating:E}},lo={visible:!1,remainingTime:0,showDescription:!1,targetTimeMs:null},ru=e=>({visible:!0,remainingTime:e,showDescription:!0,targetTimeMs:Date.now()+e*1e3}),ou=(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}},su=()=>{const{chatSDK:e}=ke(),[t,n]=u.useState(lo),r=()=>n(lo);return Lt(e,{onConnectionDelayed:o=>{o>0?n(ru(o)):r()},onReconnectSucceeded:r,onConnected:r}),u.useEffect(()=>{if(!t.visible||!t.showDescription||t.targetTimeMs==null)return;const o=setTimeout(()=>{n(s=>ou(s))},1e3);return()=>clearTimeout(o)},[t.visible,t.showDescription,t.targetTimeMs,t.remainingTime]),{visible:t.visible,remainingTime:t.remainingTime,showDescription:t.showDescription}},iu=e=>{const t=Math.floor(e/60),n=e%60;return`${String(t).padStart(2,"0")}:${String(n).padStart(2,"0")}`},au=(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)}},lu=(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===he.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]),Lt(e,{onConnected:l,onReconnectSucceeded:l}),o},gr=e=>e.replace(/\s+/g," ").trim(),cu="Code block",Ns=e=>`A11Y_INLINE_CODE_${e}`,Ds=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}},$s=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}},uu=e=>{const{blockquotePrefix:t,content:n}=Ds(e),{content:r}=$s(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}},du=(e,t)=>{const{blockquotePrefix:n,content:r}=Ds(e);if(n!==t.blockquotePrefix)return!1;const{content:o,hasListPrefix:s}=$s(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)},mu=(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},fu=(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},gu=(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},hu=e=>{let t=0,n="";for(;t<e.length;){const r=mu(e,"[",t);if(r===-1){n+=e.slice(t);break}const o=fu(e,r+1);if(o===-1){n+=e.slice(t);break}if(r>0&&e[r-1]==="!"&&nn(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]==="!"&&!nn(e,r-1)?r-1:r;n+=e.slice(t,s);const a=e.slice(r+1,o),l=gu(e,o+2);if(l===-1){n+=e.slice(s);break}n+=a,t=l}return n},Ps=(e,t,n)=>{if(!/^\d+$/.test(t))return!1;const r=e.slice(-1);return/\d/.test(r)&&/\d/.test(n)},pu=e=>e.replace(/(^|[^*\\])\*\*([^\s*](?:[\s\S]*?[^\s*])?)\*\*(?!\*)/g,(t,n,r,o,s)=>{const a=s[o+t.length]??"";return Ps(n,r,a)?t:`${n}${r}`}),_u=e=>e.replace(/(^|[^_\\])__([^\s_](?:[\s\S]*?[^\s_])?)__(?!_)/g,"$1$2"),Eu=e=>e.replace(/(^|[^~\\])~~([^\s~](?:[\s\S]*?[^\s~])?)~~(?!~)/g,"$1$2"),bu=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 Ps(r,o,l)?n:`${r}${o}`}),t=t.replace(/(^|[\s([{"'])_([^_\s](?:[\s\S]*?[^_\s])?)_(?=$|[\s)\]}"'.,!?:;])/g,"$1$2"),t},Cu=e=>e.replace(/\\([\\`*_[\]()#+.!~|-])/g,"$1"),vu=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},co=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))},uo=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},yu=e=>{const t=e.split(`
|
|
2
|
+
`),n=[];let r=0;for(;r<t.length;){const o=t[r],s=t[r+1],a=uo(o);if(a.length>0&&s&&co(s)){for(n.push(a.join(" ")),r+=2;r<t.length;){const l=t[r],c=uo(l);if(c.length===0||co(l))break;n.push(c.join(" ")),r+=1}continue}n.push(o),r+=1}return n.join(`
|
|
3
|
+
`)},Su=e=>e.replace(/^\s{0,3}(?:(?:-\s*){3,}|(?:\*\s*){3,}|(?:_\s*){3,})$/gm,""),Au=(e,t)=>{const n=e.split(`
|
|
4
|
+
`),r=[];let o=0;for(;o<n.length;){const s=n[o],a=uu(s);if(!a){r.push(s),o+=1;continue}let l=-1;for(let c=o+1;c<n.length;c++)if(du(n[c],a)){l=c;break}if(l===-1){r.push(s),o+=1;continue}r.push(` ${t} `),o=l+1}return r.join(`
|
|
5
|
+
`)},nn=(e,t)=>{let n=0,r=t-1;for(;r>=0&&e[r]==="\\";)n+=1,r-=1;return n%2===1},xu=e=>{const t=[];let n=0,r="";for(;n<e.length;){const o=e[n];if(o!=="`"||nn(e,n)){r+=o,n+=1;continue}let s=n;for(;s<e.length&&e[s]==="`";)s+=1;const a=e.slice(n,s);let l=s,c=!1;for(;l<e.length&&e[l]!==`
|
|
6
|
+
`;){if(e[l]==="`"&&!nn(e,l)&&e.startsWith(a,l)){const d=e.slice(s,l),m=t.push(d)-1;r+=Ns(m),n=l+a.length,c=!0;break}l+=1}c||(r+=a,n=s)}return{text:r,inlineCodes:t}},Fs=(e,{codeBlockPlaceholder:t=cu}={})=>{const n=e==null?void 0:e.replace(/\r\n?/g,`
|
|
7
|
+
`);if(!n)return;const r=[];let o=n;o=Au(o,t),o=vu(o);const s=xu(o);o=s.text,r.push(...s.inlineCodes),o=hu(o),o=pu(o),o=_u(o),o=Eu(o),o=bu(o),o=yu(o),o=Su(o),o=Cu(o);for(let l=0;l<r.length;l++)o=o.replaceAll(Ns(l),r[l]);return gr(o)||void 0},Tu=(e,t)=>{var o;const n=((o=e.name)==null?void 0:o.trim())||"",r=e.mimeType??"";return He(r)?t.image:cn(r)?t.video:ds({name:n,mimeType:r})?t.pdf(n):t.document(n)},rn=e=>(e==null?void 0:e.trim())||"",Iu=e=>(e?gr(e):void 0)||void 0,Us=e=>({text:rn(e),format:"plain"}),wu=e=>({text:rn(e),format:"markdown"}),wn=({markdownText:e,plainText:t,comparisonText:n})=>{const r=rn(e);return r&&r!==rn(n)?wu(r):Us(t)},St=({sender:e,message:t,messageFormat:n="plain",time:r,codeBlockPlaceholder:o})=>{const s=[],a=n==="markdown"?Fs(t,{codeBlockPlaceholder:o}):Iu(t);if(r&&s.push(r),e&&s.push(e),a&&s.push(a),s.length!==0)return s.join(", ")},Bs=(e,t)=>Fs(e==null?void 0:e.trim(),t!==void 0?{codeBlockPlaceholder:t}:void 0),Mu=(...e)=>gr(e.filter(Boolean).join(", "))||void 0,mo=(e,t,n,r)=>{if(!t||t===n)return e;const o=Bs(t,r);return o?Mu(e,o):e},ku=(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=Tu({name:l,mimeType:e.type},t);return mo(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 _;return(_=g.mimeType)==null?void 0:_.startsWith("image")})?t.receivedFilesImageCount(c):t.multipleFilesCount(c);return mo(f,n,d,t.codeBlockPlaceholder)}return Bs(n,t.codeBlockPlaceholder)},Ru=(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 _=(M,O,F)=>({text:M,ignoreSuppression:O,queueOrder:g++,dedupeKey:F}),v=()=>{const M=l[0]??null,O=a;return M&&O?O.queueOrder<M.queueOrder?(a=null,O):l.shift()??null:M?l.shift()??null:O!==null?(a=null,O):null},y=()=>{for(;;){const M=v();if(!M)return null;if(!(!M.ignoreSuppression&&(r!=null&&r())))return M}},b=M=>{c=M.text,d=M.dedupeKey??null,f=!0,e(M.text),m=setTimeout(()=>{m=null,f=!1;const O=y();O&&b(O)},n)},E=M=>{c=M.text,d=M.dedupeKey??null,e(M.text)},C=(M,O,F,Y)=>O!=null&&Y!=null?O===Y:O==null&&Y==null?M!=null&&M===F:!1,S=(M,O,F)=>{if(!M||!O&&(r!=null&&r()))return;const Y=F==null?void 0:F.dedupeKey;if(!(f&&C(M,Y,c,d)))if(f){if(((F==null?void 0:F.mode)??"latestOnly")==="ordered"){const V=l[l.length-1];if(V&&C(M,Y,V.text,V.dedupeKey))return;l.push(_(M,O,Y)),l.length>s&&l.shift();return}a=_(M,O,Y)}else a=null,b(_(M,O,Y))};return{announce:(M,O)=>{S(M,!1,O)},announceIgnoringSuppression:(M,O)=>{S(M,!0,O)},flush:()=>{const M=[];let O=v();for(;O!==null;)M.push(O),O=v();if(m!==null&&(clearTimeout(m),m=null),f=!1,M.length!==0)for(const F of M)E(F)},destroy:()=>{m!==null&&(clearTimeout(m),m=null),a=null,l.length=0,c=null,d=null,f=!1}}},Lu=e=>{switch(e){case"newMessage":case"conversationClosed":case"csatDisplayed":case"csatSubmitted":case"csatExpired":return"ordered";default:return"latestOnly"}},Ou=(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(". "),Nu=(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}},Du=(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}},$u=(e,t)=>!t||!Qe(e)||e.sender.userId!==t?null:e.reqId||(e.messageId>0?String(e.messageId):null),Pu=(e,t)=>Ie.isAdmin(e)?Ie.isCSAT(e):"sender"in e?e.sender.userId!==t:!1,Fu=e=>"messageId"in e&&e.messageId>0?String(e.messageId):"reqId"in e&&typeof e.reqId=="string"&&e.reqId.length>0?e.reqId:null,Uu=e=>e===he.CollectionEventSource.EVENT_MESSAGE_RECEIVED||e===he.CollectionEventSource.EVENT_MESSAGE_UPDATED,Bu=({isOpened:e,opensConversationList:t})=>e?t?"closeConversationList":"closeConversation":t?"openConversationList":"openConversation",Hu=(e,t)=>{switch(e){case"closeConversationList":return t.closeConversationList;case"closeConversation":return t.closeConversation;case"openConversationList":return t.openConversationList;case"openConversation":return t.openConversation}},Gu=(e,t)=>{switch(e){case"closeConversation":return t.hintCloseConversation;case"openConversationList":return t.hintOpenConversationList;case"openConversation":return t.hintOpenConversation;default:return}},zu=({intent:e,strings:t})=>({label:Hu(e,t),hint:Gu(e,t)}),Vu="1.30.0",Ne="sb-agent",Ce={ENTRY:`${Ne}-entry`,MODAL_ROOT:`${Ne}-modal-root`,WINDOW:`${Ne}-window`,LAUNCHER:`${Ne}-launcher`,WINDOW_TITLE:`${Ne}-window-title`},Hs="data-sb-initial-focus",Gs="true",Yu=`[${Hs}="${Gs}"]`,zs={[Hs]:Gs},hr="data-sb-focus-trap-sentinel",Wu="true",Vs="data-sb-initial-focus-header",Ys="true",qu=`[${Vs}="${Ys}"]`,Ws={[Vs]:Ys},qs="data-sb-message-input",Ks="true",Ku=`textarea[${qs}="${Ks}"]:not(:disabled)`,ju={[qs]:Ks},js=1e3,Gt=2147483647,it={MODAL:Gt-1,TOOLTIP:Gt-2,WINDOW:Gt-3,LAUNCHER:Gt-4},Xs=36,Xu=100,Zu=Vu,pr="noopener noreferrer nofollow";function Ju(){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 zt={};function Qu(){return{get:e=>{try{return localStorage.getItem(e)}catch{return zt[e]??null}},set:(e,t)=>{try{localStorage.setItem(e,t)}catch{zt[e]=t}},delete:e=>{try{localStorage.removeItem(e)}catch{delete zt[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(zt).filter(t=>t.startsWith(e))}}}}const ed={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}`}},Yn={language:"en",strings:ed,dateLocale:fa.enUS},Zs=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}),Js=e=>{var t;return((t=e.split("-"))==null?void 0:t[0])??Ot},Ot="en",Qs=new Set([Ot,"ko","es","pt","fr","hi","it","de","tr","ja"]),td='@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:nd,useContext:_r}=Ee("AgentUIElementResolver"),rd=({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===Ce.MODAL_ROOT?l:a.querySelector(`#${d}`);return{resolveElement:c,resolvePortalContainer:d=>c(d)??l}},[e,t,n]);return i.createElement(nd,{value:o},r)};function st(e,t){const n=e.getRootNode({composed:t});return n instanceof ShadowRoot||n instanceof Document?n:document}const fo=()=>{const e=[];let t=0;return{register:n=>{const r=++t;return e.push({id:r,handler:n}),()=>{const o=e.findIndex(s=>s.id===r);o>=0&&e.splice(o,1)}},dismissTopmost:()=>{const n=e[e.length-1];return n?(n.handler(),!0):!1}}},{Provider:od,useContext:ei}=Ee("EscapeDismissStack"),go=e=>{e.stopPropagation(),e.stopImmediatePropagation()},sd=({rootElement:e=document.body,boundaryElement:t,children:n})=>{const r=u.useRef(null),o=u.useRef(null);r.current||(r.current=fo()),o.current||(o.current=fo());const s=r.current,a=o.current;u.useLayoutEffect(()=>{const c=t??st(e),d=m=>{if(m.key==="Escape"){if(s.dismissTopmost()){go(m);return}a.dismissTopmost()&&go(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}),[a,s]);return i.createElement(od,{value:l},n)},ti=(e,t,n)=>{const r=u.useRef(t);u.useLayoutEffect(()=>{r.current=t},[t]),u.useLayoutEffect(()=>{if(e)return n(()=>r.current())},[e,n])},id=(e,t)=>{const{register:n}=ei();ti(e,t,n)},ad=(e,t)=>{const{registerShellDismissHandler:n}=ei();ti(e,t,n)},ld=(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.":""))))})},ho=Zs(Yn.strings),cd={...ho,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:ho.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"},on={language:Yn.language,dateLocale:Yn.dateLocale,stringSet:cd},ud=Object.freeze(Object.defineProperty({__proto__:null,default:on},Symbol.toStringTag,{value:"Module"})),Wn=new Map([[Ot,on]]);async function dd(e){const t=Wn.get(e);if(t)return t;try{if(Qs.has(e)){const{default:n}=await ld(Object.assign({"./languages/de.ts":()=>Promise.resolve().then(()=>require("./cjs/I-l-5Zo-.cjs")),"./languages/en.ts":()=>Promise.resolve().then(()=>ud),"./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 Wn.set(e,n),n}return on}catch{return on}}const{Provider:md,useContext:se}=Ee("Localization"),fd=({language:e=navigator.language,languageCode:t,logger:n,stringSet:r,children:o})=>{const[s,a]=u.useState(Wn.get(Ot));return u.useEffect(()=>{const l=t??Js(e);s.language!==l&&(n==null||n.debug("localization.useEffect: update language",{from:s.language,to:l}),dd(l).then(a))},[e,t,n]),i.createElement(md,{value:{language:s.language,defaultStringSet:s.stringSet,stringSet:{...s.stringSet,...r},dateLocale:s.dateLocale,format:(l,c,d)=>Xe.format(l,c,{locale:s.dateLocale,...d})}},o)},sn="data-sb-agent-theme",po=e=>(t,...n)=>{let r="";return t.forEach((o,s)=>{r+=o+(n[s]??"")}),`[${sn}='${e}'] & { ${r} }`},J={light:po("light"),dark:po("dark")},gd=D.css(({theme:e})=>{const{palette:t}=e;return`
|
|
8
8
|
:root,
|
|
9
9
|
:host {
|
|
10
10
|
--sendbird-primary-extra-dark: ${t.primary.extraDark};
|
|
@@ -53,7 +53,7 @@
|
|
|
53
53
|
--sendbird-overlay-dark: ${t.overlay.dark};
|
|
54
54
|
--sendbird-overlay-light: ${t.overlay.light};
|
|
55
55
|
}
|
|
56
|
-
`}),
|
|
56
|
+
`}),hd=D.css`[${sn}='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);}[${sn}='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);}`,h={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 Mt extends u.PureComponent{constructor(t){super(t),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}render(){const{fallback:t=null,errorFallback:n=t,loadingFallback:r=t,children:o}=this.props;return this.state.hasError?n:i.createElement(u.Suspense,{fallback:r},o)}}const Ge=e=>{const t=e;return typeof t=="number"?`${t}px`:t},pd=e=>i.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64",...e},i.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"})),_d=e=>i.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 16 16",...e},i.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"})),Ed=e=>i.createElement("svg",{viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg",...e},i.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"})),bd=e=>i.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64",fill:"evenodd",...e},i.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"})),Cd=e=>i.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64",...e},i.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"})),vd=new Set(["send","chat","message","chevron-right","good","good-filled","bad","bad-filled"]),yd={close:pd,send:Cd,menu:bd,expand:Ed,collapse:_d,spinner:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/Cf3-irI8.cjs"))),chat:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/BmdfYY9c.cjs"))),message:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/CmWLVNPR.cjs"))),error:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/DNmdC4-j.cjs"))),refresh:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/D00MOxhE.cjs"))),"chevron-down":u.lazy(()=>Promise.resolve().then(()=>require("./cjs/wf-LdaaN.cjs"))),"chevron-right":u.lazy(()=>Promise.resolve().then(()=>require("./cjs/B0k-GApQ.cjs"))),done:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/kp5wcW4s.cjs"))),"done-circle":u.lazy(()=>Promise.resolve().then(()=>require("./cjs/Bwaslfwl.cjs"))),stop:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/w1C9O3WB.cjs"))),"stop-circle":u.lazy(()=>Promise.resolve().then(()=>require("./cjs/DGubkk9p.cjs"))),user:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/CtHfgPDp.cjs"))),"file-document":u.lazy(()=>Promise.resolve().then(()=>require("./cjs/_YfLwFkX.cjs"))),download:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/BN09c8-A.cjs"))),attach:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/DcDTXo8_.cjs"))),"close-filled":u.lazy(()=>Promise.resolve().then(()=>require("./cjs/D1kINslt.cjs"))),agent:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/Ce1MzjFq.cjs"))),actionbook:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/CXa-CGHE.cjs"))),function:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/zbLY6xl_.cjs"))),"radio-on":u.lazy(()=>Promise.resolve().then(()=>require("./cjs/B9NJk4MI.cjs"))),"radio-off":u.lazy(()=>Promise.resolve().then(()=>require("./cjs/Bb0r6Nhu.cjs"))),confluence:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/c6TZaE94.cjs"))),zendesk:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/DqpDy_26.cjs"))),salesforce:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/BsgzT_SF.cjs"))),sprinklr:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/D97ZpKUC.cjs"))),website:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/ygZY2D-5.cjs"))),snippet:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/BCFOnu0u.cjs"))),template:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/eJXfXI1_.cjs"))),source:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/yVmX6iux.cjs"))),copy:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/COgkkyBM.cjs"))),show:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/DM-WWpci.cjs"))),mute:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/P_ra76fq.cjs"))),good:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/DEgUVAck.cjs"))),bad:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/C0s7eAf7.cjs"))),"good-filled":u.lazy(()=>Promise.resolve().then(()=>require("./cjs/Chg8xHXT.cjs"))),"bad-filled":u.lazy(()=>Promise.resolve().then(()=>require("./cjs/CGkmTaBn.cjs"))),delight:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/DCB0iTxd.cjs"))),photo:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/GQlGFYP2.cjs"))),add:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/DEGDJBmd.cjs"))),document:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/DBHlAmeA.cjs"))),memory:u.lazy(()=>Promise.resolve().then(()=>require("./cjs/DB0sLqre.cjs")))},Sd=e=>({size:t=24,color:n=h.color.primary.main,flipInRtl:r=!1})=>i.createElement(xd,{$size:t,$color:n,$rtlFlip:r},i.createElement(Mt,{errorFallback:i.createElement(Td,null)},i.createElement(e,null))),ni=Object.fromEntries(Object.entries(yd).map(([e,t])=>[e,Sd(t)])),Ad=D.css`[dir='rtl'] &:not([dir='ltr']),&[dir='rtl']{transform:scaleX(-1);}`,xd=p.default.span.attrs({"aria-hidden":"true"})`
|
|
57
57
|
width: ${({$size:e})=>Ge(e)};
|
|
58
58
|
height: ${({$size:e})=>Ge(e)};
|
|
59
59
|
display: inline-block;
|
|
@@ -74,25 +74,25 @@
|
|
|
74
74
|
stroke-linejoin: round;
|
|
75
75
|
}
|
|
76
76
|
|
|
77
|
-
${({$rtlFlip:e})=>e&&
|
|
78
|
-
`,
|
|
77
|
+
${({$rtlFlip:e})=>e&&Ad};
|
|
78
|
+
`,Td=()=>i.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 64 64"},i.createElement("rect",{x:"8",y:"8",width:"48",height:"48",fill:"none",className:"stroke",rx:"4"}),i.createElement("line",{x1:"20",y1:"20",x2:"44",y2:"44",className:"stroke"}),i.createElement("line",{x1:"44",y1:"20",x2:"20",y2:"44",className:"stroke"})),{Provider:Id,useContext:wd}=Ee("MessengerIcon",{icons:ni}),Md=({icons:e,children:t})=>{const n=u.useMemo(()=>({icons:Al(ni,e)}),[e]);return i.createElement(Id,{value:n},t)},{Provider:kd,useContext:ri}=Ee("MessengerTheme");function Rd(e){const{theme:t,appearance:n,logger:r}=e;return i.createElement(cc,{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},i.createElement(Ld,{...e}))}function Ld({rootElement:e=document.body,children:t}){const{theme:n,updateTheme:r}=dr();return u.useLayoutEffect(()=>{e.setAttribute(sn,n.selectedTheme)},[e,n.selectedTheme]),i.createElement(D.ThemeProvider,{theme:n},i.createElement(kd,{value:{theme:n,updateTheme:r,rootElement:e}},t))}const Od=(e,t)=>{u.useEffect(()=>{const n=st(t)instanceof ShadowRoot,r=st(t,!0);if(!(n?t:r).querySelector(`link[href*='${e}']`)){const s=r.createElement("link");s.rel="stylesheet",s.href=e,(n?t:r.head).appendChild(s)}},[e,t])},Nd=(e,t=document.body)=>{u.useEffect(()=>{if(!e)return;const n=st(t),o=n instanceof ShadowRoot?t:n.head;if(!o)return;const s=`sba-${btoa(e).slice(0,10)}`;let a=o.querySelector(`style#${s}`);a?a.textContent!==e&&(a.textContent=e):(a=o.ownerDocument.createElement("style"),a.id=s,a.textContent=e,o.appendChild(a))},[e,t])},Dd=80,$d=()=>{const{stringSet:e}=se(),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=u.useRef(t);return n.current=t,n},oi=Ee("AriaLiveRegion",{announce:ge,announceScreenEntry:ge,announceStatus:ge,announceError:ge,flush:ge,setSuppressionState:ge}),Pd=oi.Provider,Er=oi.useContext,Fd={position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},Ud=({children:e})=>{const t=u.useRef(null),n=u.useRef(new Set),r=u.useRef(ge),o=$d(),[s]=u.useState(()=>Ru(_=>{r.current(_)},{throttleMs:1e3,isSuppressed:()=>n.current.size>0}));r.current=_=>{const v=t.current;v&&(v.textContent="",requestAnimationFrame(()=>{v.textContent=_}))},u.useEffect(()=>()=>{s.destroy()},[s]);const a=s.announce,l=s.flush,c=u.useCallback(_=>{const v=Ou(_,o.current);a(v)},[a]),d=u.useCallback((_,v)=>{const y=Nu(_,o.current),b=(v==null?void 0:v.mode)??Lu(_.event);a(y,{mode:b,dedupeKey:v==null?void 0:v.dedupeKey})},[a]),m=u.useCallback((_,v)=>{const y=Du(_,o.current);s.announceIgnoringSuppression(y),v&&setTimeout(()=>{v.focus()},Dd)},[s]),f=u.useCallback((_,v)=>{if(v){n.current.add(_);return}n.current.delete(_)},[]),g=u.useMemo(()=>({announce:a,announceScreenEntry:c,announceStatus:d,announceError:m,flush:l,setSuppressionState:f}),[a,m,c,d,l,f]);return i.createElement(Pd,{value:g},e,i.createElement("div",{ref:t,role:"status","aria-live":"polite","aria-atomic":"true",style:Fd}))},si=Ee("ConversationAnnouncements",{announcementsEnabled:!0,announce:ge,announceScreenEntry:ge,announceStatus:ge,announceError:ge,setIsSuppressed:ge,setStatusPauseState:ge,flush:ge}),Bd=si.Provider,Ke=si.useContext,Hd=({children:e,announcementsEnabled:t=!0})=>{const{announce:n,announceScreenEntry:r,announceStatus:o,announceError:s,flush:a,setSuppressionState:l}=Er(),c=u.useRef([]),d=u.useRef(new Set),m=u.useRef(Symbol("conversation-announcements")),f=u.useCallback(x=>{if(!t||!x){l(m.current,!1);return}l(m.current,!0)},[t,l]),g=u.useCallback(()=>{c.current=[]},[]),_=u.useCallback(()=>{if(c.current.length===0)return;if(!t){g();return}const x=[...c.current];g(),x.forEach(w=>{a(),o(w.params,w.options)})},[o,t,g,a]),v=u.useCallback((x,w)=>{if(w){d.current.add(x);return}d.current.delete(x),d.current.size===0&&_()},[_]),y=u.useCallback(x=>{t&&n(x)},[n,t]),b=u.useCallback(x=>{t&&r(x)},[r,t]),E=u.useCallback((x,w)=>{if(t){if(d.current.size>0){c.current.push({params:x,options:w});return}o(x,w)}},[o,t]),C=u.useCallback((x,w)=>{t&&s(x,w)},[s,t]);u.useLayoutEffect(()=>(t||(g(),l(m.current,!1)),()=>{g(),l(m.current,!1)}),[t,g,l]);const S=u.useMemo(()=>({announcementsEnabled:t,announce:y,announceScreenEntry:b,announceStatus:E,announceError:C,setIsSuppressed:f,setStatusPauseState:v,flush:a}),[t,a,y,C,b,E,f,v]);return i.createElement(Bd,{value:S},e)},$=({as:e,variant:t="body1",color:n,maxTextLines:r,className:o,...s})=>i.createElement(Vd,{as:e,$variant:t,className:o,$color:n,$maxTextLines:r,...s}),_o=new WeakMap,Gd=(e,t)=>{let n=_o.get(t);n||(n=new Map,_o.set(t,n));const r=n.get(e);if(r)return r;const o=t[e]??t.body1,s=D.css`font-size:${Ge(o.fontSize)};font-weight:${o.fontWeight};${o.fontFamily?`font-family: ${o.fontFamily};`:""}
|
|
79
79
|
${o.lineHeight?`line-height: ${o.lineHeight};`:"line-height: 100%;"}
|
|
80
|
-
`;return n.set(e,s),s},$d=e=>e?D.css`display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:${e};overflow:hidden;`:"",Pd=p.default.span`font-stretch:normal;letter-spacing:normal;${({$variant:e,theme:t})=>Dd(e,t.typography)}color:${({$color:e})=>e};${({$maxTextLines:e})=>$d(e)}`,mn=["a[href]","button:not(:disabled)","input:not(:disabled)","select:not(:disabled)","textarea:not(:disabled)",'[tabindex]:not([tabindex="-1"])'].join(", "),ti=`${mn}, [tabindex="-1"]`,Mt=e=>{if(!e.isConnected||e.hidden)return!1;let t=e;const n=e.ownerDocument.defaultView;for(;t;){if(t.hidden||t.getAttribute("aria-hidden")==="true")return!1;if(n){const r=n.getComputedStyle(t);if(r.display==="none"||r.visibility==="hidden")return!1}t=t.parentElement}return!0};async function Er(e){let t=e;t&&(!t.startsWith("http://")&&!t.startsWith("https://")&&(t="https://"+t),window.open(t,"_blank","noopener,noreferrer"))}function Le(e){requestAnimationFrame(()=>{requestAnimationFrame(()=>{e()})})}const sn=(e,t)=>{for(const n of e.querySelectorAll(t))if(!n.hasAttribute(hr)&&Mt(n))return n;return null},ni=e=>{let t=null,n=null;for(const r of e.querySelectorAll(mn))r.hasAttribute(hr)||Mt(r)&&(t??(t=r),n=r);return t?{first:t,last:n}:null},br=e=>sn(e,Uu),ri=e=>br(e)??sn(e,mn),Fd=e=>{const t=br(e);if(t)return t;const n=e.querySelector(Gu);return(n?sn(n,ti):null)??sn(e,mn)},Wn='[role="dialog"][aria-modal="true"]',Bd=(e,t)=>{const n=new Set(Array.from(e.ownerDocument.querySelectorAll(Wn)).filter(o=>o!==e&&(o.contains(e)||e.contains(o)))),r=t==null?void 0:t.closest(Wn);return r&&r!==e&&n.add(r),n},Ud=(e,t)=>Array.from(e.ownerDocument.querySelectorAll(Wn)).some(n=>n!==e&&!t.has(n)&&!n.contains(e)&&Mt(n)),Hd=e=>{const t=ri(e)??e;t===e&&oi(e),t.focus()},oi=e=>{e.hasAttribute("tabindex")||e.setAttribute("tabindex","-1")},Gd=(e,t)=>{const n=ni(e);if(!n){oi(e),e.focus();return}n[t].focus()},_o=(e,t)=>{const n=e.ownerDocument.createElement("span");return n.tabIndex=0,n.setAttribute(hr,Hu),n.style.cssText=["position: fixed","width: 1px","height: 1px","opacity: 0","overflow: hidden","pointer-events: none"].join(";"),n.addEventListener("focus",()=>Gd(e,t)),n},zd=(e,t)=>{e.key==="Tab"&&(e.defaultPrevented||e.target===t&&(ni(t)||(e.preventDefault(),t.focus())))},Vd=(e,t)=>t instanceof HTMLElement?e instanceof Document?t===e.body||t===e.documentElement:!1:!0,fn=(e,t)=>{const n=u.useRef(0);u.useEffect(()=>{if(!e||!t.current)return;n.current+=1;const r=n.current,o=t.current,s=o.getRootNode(),a=s.activeElement instanceof HTMLElement?s.activeElement:null,l=Bd(o,a);let c=!1;return Le(()=>{c||!o.isConnected||Hd(o)}),()=>{c=!0,a&&Le(()=>{if(n.current!==r)return;const d=s.activeElement;o.isConnected&&d instanceof HTMLElement&&d!==o&&!o.contains(d)&&!Vd(s,d)&&d.matches(ti)&&Mt(d)||Ud(o,l)||!a.isConnected||!Mt(a)||a.focus()})}},[e,t]),u.useEffect(()=>{if(!e||!t.current)return;const r=t.current,o=_o(r,"last"),s=_o(r,"first"),a=l=>zd(l,r);return r.insertBefore(o,r.firstChild),r.appendChild(s),r.addEventListener("keydown",a),()=>{r.removeEventListener("keydown",a),o.remove(),s.remove()}},[e,t])},nt=({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}=pr();return fn(n,d),Qu(n,s?r:he),n?ca.createPortal(i.createElement(Yd,{onClick:s?r:void 0,style:e},i.createElement(Wd,{ref:d,role:"dialog","aria-modal":"true","aria-label":a,"aria-labelledby":l,"aria-describedby":c,onClick:f=>f.stopPropagation()},o)),m(t)):null},Yd=p.default.div`position:fixed;top:0;left:0;width:100%;height:100%;background:${g.color.overlay.dark};display:flex;justify-content:center;align-items:center;z-index:${it.MODAL};`,Wd=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};`,qd=({id:e,children:t})=>i.createElement(Kd,{id:e},t),Kd=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;`,Eo=(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,...Hs}:n},jd=()=>{const e=`${u.useId()}-`;return(t,n)=>{if(!t)return{props:{},node:null};const r=e+n,o=u.createElement(qd,{id:r,children:t});return{props:{"aria-describedby":r},node:o}}},bo=({name:e,mimeType:t,selected:n},r)=>{var s;const o=He(t??"")?r.A11Y_FILE_IMAGE(e):cn(t??"")?r.A11Y_FILE_VIDEO(e):cs({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},Xd=e=>t=>{t.repeat||(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),e())},St=({onActivate:e})=>({role:"button",tabIndex:0,onClick:e,onKeyDown:Xd(e)}),Zd=({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()},Co=(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:Zd({disabled:t,currentIndex:n,totalCount:r,onNavigate:s}),tabIndex:a}},oe=()=>{const{stringSet:e}=se(),t=jd(),n=(a,l)=>{let c=e.A11Y_HINT_OPEN_FILE,d="of";He(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":bo(a,e)});return{launcher:{button:({isOpened:a,opensConversationList:l})=>{const c=Fu({intent:Du({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:Eo(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},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:{...St({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?bo({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:{...St({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:h,onChange:_})=>{var b;const y=l.trim()||l,C=e.A11Y_HINT_SELECT_RATING,v=t(C,`cs${a}`);return{props:{disabled:d,onClick:()=>_(a),...Co(c,d,m,f,h,E=>_(E+1)),...v.props,"aria-label":((b=e.A11Y_CSAT_RATING_LABEL)==null?void 0:b.call(e,a,y))??`${a} / ${f} — ${y}`},descriptionNode:v.node}},submitButton:a=>({props:{"aria-label":a},descriptionNode:null})},form:{button:a=>({props:{"aria-label":a},descriptionNode:null}),textInput:(a,l,c)=>({props:{"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,h)=>({props:{...Co(l,c,d,m,f,h),"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:Eo(a,l),descriptionNode:null}),footer:{button:({onActivate:a})=>({props:{...St({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,h=t(f,"cli");return{props:{...St({onActivate:m}),...h.props,"aria-label":e.A11Y_CONVERSATION_ITEM(a,l,c,d)},descriptionNode:h.node}}}}},Jd=({title:e,description:t,highlightedText:n})=>{const r=nu(t,n);return i.createElement(em,null,i.createElement(tm,null,i.createElement(P,{as:"div",variant:"h1",color:g.themedColor.textHighEmphasis},e),t&&i.createElement(nm,null,i.createElement(P,{as:"div",variant:"body3",color:g.themedColor.textMidEmphasis},r.beforeText,r.highlightedText?i.createElement(rm,null,r.highlightedText):null,r.afterText))))},Qd=()=>{const{components:e}=hn.useContext(),{stringSet:t}=se(),{messenger:n}=oe(),r=eu(),o=r.showDescription?tu(r.remainingTime):"",s=r.showDescription?t.CONNECTION_DELAY__DESCRIPTION(o):"";return i.createElement(nt,{portalContainerId:Ce.WINDOW,visible:r.visible,onClose:he,...n.connectionDelayDialog().props},i.createElement(e.Dialog,{title:t.CONNECTION_DELAY__TITLE,description:s,highlightedText:o||void 0}))},hn=Ue({template:Qd,components:{Dialog:Jd}}),em=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};`,tm=p.default.div`display:flex;flex-direction:column;`,nm=p.default.div`margin-top:16px;`,rm=p.default.strong`font-weight:700;`,om=({url:e})=>Er(e),{Provider:sm,Consumer:si,useContext:me}=Ee("Messenger");function im({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}=pr(),h=u.useCallback(()=>{var C;m.setOpened(!1),(C=f(Ce.LAUNCHER))==null||C.focus()},[m.setOpened,f]);ed(m.opened,h);const{Template:_}=hn.useContext(),y=u.useMemo(()=>{var C;return{...s.handlers,onClickLink:((C=s.handlers)==null?void 0:C.onClickLink)??om}},[s.handlers]);return i.createElement(Il,{...s},C=>i.createElement(sm,{value:{...s,...C,state:m,enableCloseConversationButton:n,enableExpandButton:r,enableAutoDisconnectInLauncher:o,handlers:y}},i.createElement(_,null),e))}const ii=/iPad|iPhone|iPod/.test(navigator.userAgent),am=/Android/.test(navigator.userAgent),Ot=e=>ii||am;let vt=null,wn=null;const lm=(e,t=5e3)=>{vt&&(clearInterval(vt),clearTimeout(wn));const n=document.title;vt=setInterval(()=>{document.title=document.title===e?n:e},750),wn=setTimeout(()=>{clearInterval(vt),vt=null,wn=null,document.title=n},t)},ai=()=>{Promise.resolve().then(()=>require("./cjs/B93o4u0P.cjs")).then(e=>{new Audio(e.default).play().catch(()=>{})})},Ae=D.css`&:focus-visible{outline:2px solid ${g.themedColor.primary};outline-offset:2px;}`,vo=e=>{if(typeof e=="string"||typeof e=="number")return String(e)},gn=({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??vo(t)??vo(n),h=c?void 0:t?d:n?m:void 0,_=t&&n?m:void 0,y=()=>{l(),Le(()=>s==null?void 0:s())},C=()=>{l(),Le(()=>a==null?void 0:a())};return i.createElement(nt,{portalContainerId:Ce.WINDOW,visible:e,onClose:l,"aria-label":f,"aria-labelledby":h,"aria-describedby":_},i.createElement(cm,null,i.createElement(um,null,t&&i.createElement("div",{id:d},i.createElement(P,{variant:"h1",color:g.themedColor.textHighEmphasis},t)),n&&i.createElement(dm,{id:m},i.createElement(P,{variant:"body3",color:g.themedColor.textMidEmphasis},n))),i.createElement(mm,null,o&&i.createElement(yo,{onClick:C},i.createElement(P,{variant:"button",color:g.themedColor.textHighEmphasis},o)),i.createElement(yo,{onClick:y},i.createElement(P,{variant:"button",color:g.themedColor.primary},r)))))},cm=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};`,um=p.default.div`margin-bottom:16px;`,dm=p.default.div`margin-top:16px;`,mm=p.default.div`display:flex;flex-direction:row;justify-content:flex-end;`,yo=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:fm,useContext:we}=Ee("MessengerSession"),hm=u.forwardRef(function({children:e,...t},n){return i.createElement(lc,{ref:n,...t},r=>i.createElement(gm,{...r},e))}),gm=({children:e,...t})=>{const{chatSDK:n,logger:r,appId:o,aiAgentId:s,agentPreviewConfigs:a,state:l,handlers:c,dispatcher:d,_aiAgentSDK:m}=me(),{userSessionInfo:f,authenticate:h,userSession:_,aiAgentInfo:y,launcherInfo:C}=t,[v,b]=u.useState(!1),E=u.useRef(null);ht(n,{async onUserJoined(x,k){var I,w,O,$;x.conversation&&x.conversation.type===be.ConversationType.PROACTIVE&&k.userId===((I=n.currentUser)==null?void 0:I.userId)&&(r.info("messengerSession.onUserJoined: proactive channel joined",x.url),(O=m.session)==null||O._updateActiveChannel({url:x.url,status:"open",conversationStatus:(w=x.conversation)==null?void 0:w.status}),l.setOpened(!0),pm({sound:document.hidden||!l.opened}),($=E.current)==null||$.call(E,{channel:x}))}}),u.useEffect(()=>{h().then(({launcher:x})=>{x.auto_open&&!Ot()&&setTimeout(()=>l.setOpened(!0),500)}).catch(x=>{var k;r.error("messengerSession: failed to initialize",x),(k=c==null?void 0:c.onInitializeFailed)==null||k.call(c,x)})},[n,o,s,f==null?void 0:f.userId]),u.useEffect(()=>{const x=()=>b(!0);return d.subscribe(Fe.AnonymousSessionTokenExpired,x),()=>d.unsubscribe(Fe.AnonymousSessionTokenExpired,x)},[d]);const A=u.useCallback(()=>{t.deauthenticate().finally(()=>window.location.reload())},[t.deauthenticate]);return!_||!y||!C?null:i.createElement(fm,{value:{...t,userSession:_,aiAgentInfo:{...y,...a==null?void 0:a.bot},launcherInfo:{...C,...a==null?void 0:a.launcher},registerOnJoinedProactiveConversation:x=>E.current=x}},e,i.createElement(gn,{visible:v,title:"Session timed out",description:"Start a new conversation.",onConfirm:A,onClose:he}))};function pm({sound:e}){lm("🔔You have received a new message"),e&&ai()}const an=`@${Ne}-focused-channel`,li=`${Date.now()}-${Math.random().toString(36).slice(2)}`,_m=()=>{try{const e=localStorage.getItem(an);return e?JSON.parse(e).channelUrl??null:null}catch{return null}},So=e=>{try{localStorage.setItem(an,JSON.stringify({channelUrl:e,tabId:li}))}catch{}},Ao=()=>{try{const e=localStorage.getItem(an);if(!e)return;JSON.parse(e).tabId===li&&localStorage.removeItem(an)}catch{}},Em=(e,t)=>(u.useEffect(()=>{if(!t||!e)return;const n=()=>So(e),r=()=>Ao();return document.hasFocus()&&So(e),window.addEventListener("focus",n),window.addEventListener("blur",r),()=>{window.removeEventListener("focus",n),window.removeEventListener("blur",r),Ao()}},[t,e]),{isChannelViewedInAnyTab:()=>document.hasFocus()||_m()===e}),bm=e=>{const{config:t,chatSDK:n}=me(),{sdkUser:r}=we(),o=t.conversation.messageAlertSoundEnabled,{isChannelViewedInAnyTab:s}=Em(e,o);ht(n,{onMessageReceived(a,l){if(!o||a.url!==e||s())return;(Qe(l)&&l.sender.userId!==(r==null?void 0:r.userId)||l.isAdminMessage()&&!l.silent)&&ai()}})};function Cm(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 vm(e){if("file"in e&&e.file instanceof File&&e.file.type.startsWith("image/")){const{width:t,height:n}=await Cm(e.file);return new Be.MessageMetaArray({key:as,value:[t,n]})}}const ym=({onScrollAfterSendMessage:e})=>{const{agentPreviewConfigs:t,handlers:n}=me(),r=u.useRef(t==null?void 0:t.agentAttributes);return r.current=t==null?void 0:t.agentAttributes,{onBeforeSendMessage:async o=>{const s=await vm(o),a={...o,metaArrays:s?[s]:void 0},l=Sm(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===Be.SendingStatus.SUCCEEDED?(a=n==null?void 0:n.onCustomEvent)==null||a.call(n,{type:"message-sent-succeeded",data:{message:o}}):o.sendingStatus===Be.SendingStatus.PENDING&&((l=n==null?void 0:n.onCustomEvent)==null||l.call(n,{type:"message-sent-pending",data:{message:o}}))}}},Sm=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,Mn=dt-40,{Provider:Am,useContext:ci}=Ee("ConversationScroll"),xo={viewport:0,contentHeight:0,contentSnapshotHeight:0,shouldRecalc:!1,shouldUpdate:!1},kn=e=>Math.max(0,e.scrollHeight-e.scrollTop-e.clientHeight);function xm({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(xo),f=u.useRef(!1),h=u.useRef(null),[_,y]=u.useState(0),[C,v]=u.useState(0),[b,E]=u.useState(!1),[A,x]=u.useState(!1),[k,R]=u.useState(!0),I=T=>{const M=kn(T);return s.current=M,v(M),M},w=()=>{d.current&&(clearTimeout(d.current),d.current=null)},O=u.useMemo(()=>b||t==="bottom"?"auto":e,[b,t,e]),$=()=>{m.current.contentSnapshotHeight=m.current.contentHeight,m.current.shouldUpdate=!0,m.current.shouldRecalc=!0},V=()=>{const T=r.current;!T||!m.current.shouldUpdate||y(M=>{m.current.shouldUpdate=!1;const{contentHeight:N,contentSnapshotHeight:j,shouldRecalc:B}=m.current,z=T.clientHeight;if(j>N)return M;const U=H(T,{messageType:"outgoing"});let ue=0;if(U){const $e=U.message.offsetTop-Mn+z;ue=Math.max(0,$e-N)}else{const $e=N-j,ae=z-Mn;ue=Math.max(0,$e-ae)}return M===0||ue!==M||B?(m.current.shouldRecalc=!1,ue):M})},H=u.useCallback((T,M)=>{const{messageType:N="all"}=M??{},j=Array.from(T.querySelectorAll(`#${Ne}-message-item`));let B=j;N==="outgoing"&&(B=j.filter(te=>te.getAttribute("data-layout-id")==="outgoingmessage"));const z=B[B.length-1];if(!z)return null;const U=T.getBoundingClientRect(),ue=z.getBoundingClientRect(),$e=T.scrollTop+(ue.top-U.top),ae=$e+z.offsetHeight;return{message:z,scrollTop:$e,lastMessageBottom:ae}},[]),Y=u.useCallback(()=>{const T=r.current;if(!T||O!=="fixed")return;const M=H(T);m.current.contentHeight=(M==null?void 0:M.lastMessageBottom)??T.scrollHeight,!f.current&&m.current.contentSnapshotHeight>0&&$(),c.current?s.current=kn(T):I(T),V()},[O,H]),G=u.useCallback(()=>{o.current&&(o.current.disconnect(),o.current=null),w(),m.current=xo,y(0),v(0),R(!0),s.current=0,l.current=!1,a.current=0,c.current=!1},[]),W=u.useCallback((T=!0)=>{const M=s.current>dt;if(l.current=!1,v(0),!M){Le(()=>{const N=r.current;N&&!l.current&&N.scrollTo({top:N.scrollHeight,behavior:"auto"})});return}c.current||(c.current=!0,R(!1),w()),Le(()=>{const N=r.current;if(!N){c.current=!1,R(!0);return}if(l.current){c.current=!1,I(N),R(!0);return}const j=()=>{if(r.current!==N){c.current=!1,r.current&&I(r.current),R(!0);return}c.current=!1,I(N),R(!0)};if(T&&!d.current){const B=setTimeout(j,500);d.current=B,N.addEventListener("scrollend",()=>{clearTimeout(B),d.current=null,j()},{once:!0})}N.scrollTo({top:N.scrollHeight,behavior:T?"smooth":"auto"}),T||j()})},[]),q=u.useCallback(T=>{T&&(r.current=T,O==="fixed"&&(G(),m.current.viewport=T.clientHeight,o.current=new MutationObserver(()=>{Y()}),o.current.observe(T,{childList:!0,subtree:!0})))},[O,Y,G]),ce=u.useCallback(()=>{const T=r.current;if(!T)return;const M=H(T,{messageType:"outgoing"});M&&(T.scrollTo({top:M.message.offsetTop-Mn,behavior:"smooth"}),h.current&&clearTimeout(h.current),h.current=setTimeout(()=>{x(!1)},500))},[H]),_e=(T,M,N)=>{const j=kn(T);if(N&&j>dt){c.current=!1,l.current=!0,w(),I(T),R(!0),a.current=M;return}s.current=j},L=(T,M,N)=>{const B=I(T)<=dt;M&&!B&&(l.current=!0,w()),N&&B&&(l.current=!1)},X=T=>{const{scrollTop:M}=T.currentTarget,N=a.current;c.current?_e(T.currentTarget,M,M<N):L(T.currentTarget,M<N,M>N),a.current=M},K=u.useCallback(()=>{O==="fixed"&&(x(!0),$())},[O]),F=u.useCallback(()=>{O==="fixed"?setTimeout(()=>ce(),300):W()},[O,ce]),ee=u.useCallback(T=>{f.current=T,O==="fixed"?$():l.current||W()},[O,W]),de=u.useCallback(T=>{E(T),T&&(y(0),o.current&&(o.current.disconnect(),o.current=null))},[]),fe=u.useCallback(T=>{O==="auto"&&T&&!l.current&&W()},[O,W]),Oe=!(C<=dt)&&!A,ke=u.useCallback(()=>s.current>dt,[]);return i.createElement(Am,{value:{ref:q,state:{bottomSpace:_,isAwayFromBottom:Oe,isScrollPositionReconciled:k,shouldCountNewMessages:ke},props:{onScroll:X},actions:{scrollToBottom:W,onBeforeMessageSend:K,onAfterMessageSend:F,onStreamingUpdate:ee,onConversationClosed:de,onTypingIndicatorUpdate:fe}}},n)}const{Provider:Tm,Context:Im,useContext:Se}=Ee("Conversation"),wm=({children:e})=>{var o;const{channelSource:t}=Se(),n=(o=t.channel)==null?void 0:o.url,{checkForUserActionRequired:r}=Fc(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)},Mm=({channelUrl:e,onClearChannelUrl:t,onNavigateToConversationList:n,shouldMarkAsRead:r,children:o})=>{const{activeChannel:s,refreshActiveChannel:a}=we(),l=ci(),c=e||(s==null?void 0:s.url);bm(c);const{onBeforeSendMessage:d,onAfterSendMessage:m}=ym({onScrollAfterSendMessage:()=>{l.actions.onAfterMessageSend()}}),f=u.useCallback(y=>(l.actions.onBeforeMessageSend(),d(y)),[l.actions,d]),h=u.useCallback(y=>{const C=y.some(v=>Ve.isStreaming(v));l.actions.onStreamingUpdate(C)},[l.actions.onStreamingUpdate]),_=u.useCallback(async()=>{await a(),e&&(t==null||t())},[a,e,t]);return i.createElement(Cc,{key:c,channelUrl:c,onBeforeSendMessage:f,onAfterSendMessage:m,onMessagesUpdated:h,onMessagesReceived:h,onChannelDeleted:_,onConversationClosedStatusChanged:l.actions.onConversationClosed,shouldMarkAsRead:r,shouldCountNewMessages:l.state.shouldCountNewMessages},y=>i.createElement(Tm,{value:{...y,scrollSource:l,goToActiveConversation:_,onNavigateToConversationList:n}},i.createElement(wm,null,o)))},ui=({children:e,...t})=>{const{config:n}=Me(),{agentPreviewConfigs:r}=me(),o=n.conversation.list.scrollMode,s=r==null?void 0:r.messageStackDirection;return i.createElement(xm,{scrollMode:o,messageStackDirection:s},i.createElement(Mm,{...t},e))},Cr=u.createContext({onDrop:he,subscribe:()=>he}),qn=({children:e})=>{const t=u.useRef(new Set);return i.createElement(Cr.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)},km=({onDropFiles:e})=>{const{subscribe:t}=u.useContext(Cr);u.useEffect(()=>t(e),[e])};qn.Consumer=({children:e})=>{const{onDrop:t}=u.useContext(Cr);return e({onDrop:t,onDragOver:o=>o.preventDefault()})};const Rm=e=>{const t=Fd(e)??e;t===e&&!e.hasAttribute("tabindex")&&e.setAttribute("tabindex","-1"),t.focus()},di=(e,{enabled:t,ready:n})=>{const r=u.useRef(!1);u.useEffect(()=>{if(!t){r.current=!1;return}if(r.current||!e.current||!(br(e.current)!=null)&&!n)return;let s=!1;return Le(()=>{s||r.current||!e.current||(r.current=!0,Rm(e.current))}),()=>{s=!0}},[t,n,e])},Lm=e=>{const{announcementsEnabled:t}=Ke(),{channelSource:n}=Se(),r=n.channel!=null||n.error!=null;di(e,{enabled:t,ready:r})},Om=e=>He(e)||cn(e);function Nm(e){return e.isAdminMessage()?e.message==="The channel's custom_type was updated.":!1}function Dm(e,t){return e.filter(n=>Ve.isWelcomeMessage(n,t))}const mi=(e,{previewWelcomeMessages:t,aiAgentUserId:n})=>e.filter(r=>Nm(r)?!1:t.length>0?!Ve.isWelcomeMessage(r,n):!0),$m=[],fi=()=>{var y,C,v,b,E,A;const{agentPreviewConfigs:e={},aiAgentId:t}=me(),{aiAgentInfo:n,userSession:r}=we(),{channelSource:o,messageSource:s,state:{input:a,streamAnimation:l}}=Se(),c=e.welcomeMessages??$m,d=u.useMemo(()=>mi(s.messages,{previewWelcomeMessages:c,aiAgentUserId:t}),[t,s.messages,c]),m=et(o.channel),f=(C=(y=_s(o.channel,r.userId))==null?void 0:y.nickname)==null?void 0:C.trim(),h=m?(b=(v=o.channel)==null?void 0:v.name)==null?void 0:b.trim():(E=n==null?void 0:n.nickname)==null?void 0:E.trim(),_=f||h||void 0;return{initialized:s.initialized,channelUrl:(A=o.channel)==null?void 0:A.url,agentName:_,isClosed:Re(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}},Pm=(e={})=>{const{announceScreenEntry:t,announcementsEnabled:n}=Ke(),{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(h=>Ie.isAdmin(h)&&Ie.isCSAT(h)),[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])},Fm=()=>{const e=fi();Pm(e)},Bm=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}),To=(e,t,n=Xe.format)=>{const r=xu(e,Bm(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}},Um={senderName:!0,body:!0,time:!0},Hm=Object.keys(Um),Gm=(e,t)=>Hm.every(n=>e[n]===t[n]),Io=2e3,wo=400,Kn=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]},hi=e=>{if(!Ie.isAdmin(e)||!Ie.isCSAT(e))return null;const t=Ou(e);return t?`csat:${t}`:null},zm=e=>{const t=new Set;for(const n of e){const r=hi(n);r&&t.add(r)}return t},Vm=(e,t)=>{for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(r&&Kn(r).some(o=>t.includes(o)))return r}},Rn=(e,t)=>e.some(n=>t.includes(n)),Mo=()=>typeof document>"u"?null:document.activeElement instanceof HTMLElement?document.activeElement:null,Ln=e=>new Map(e.map(({key:t,sendingStatus:n})=>[t,n])),Ym=()=>{const{announceStatus:e,announcementsEnabled:t}=Ke(),{stringSet:n,format:r}=se(),{channelUrl:o,messages:s,isClosed:a,isHandedOff:l,agentName:c,initialized:d,inputDisabled:m,inputDisabledBy:f,isStreamAnimating:h,subscribeMessageEvents:_,currentUserId:y}=fi(),{outgoingMessageStates:C,outgoingMessageStatusSignature:v}=u.useMemo(()=>{if(!y)return{outgoingMessageStates:[],outgoingMessageStatusSignature:""};const X=s.flatMap(K=>{const F=Ru(K,y);return!F||!("sendingStatus"in K)?[]:[{key:F,sendingStatus:K.sendingStatus}]});return{outgoingMessageStates:X,outgoingMessageStatusSignature:X.map(({key:K,sendingStatus:F})=>`${K}:${F}`).join(",")}},[y,s]),b=u.useRef({isClosed:!1,isHandedOff:!1,inputDisabled:m,inputDisabledBy:f,outgoingMessageStatuses:Ln(C)}),E=u.useRef({messages:s,currentUserId:y,inputDisabledBy:f,isStreamAnimating:h,stringSet:n,format:r}),A=u.useRef([]),x=u.useRef(null),k=u.useRef([]),R=u.useRef(new Set),I=u.useRef(new Set),w=u.useRef(!1),O=u.useRef(o);E.current={messages:s,currentUserId:y,inputDisabledBy:f,isStreamAnimating:h,stringSet:n,format:r};const $=()=>E.current.isStreamAnimating||E.current.inputDisabledBy==="ai_responding",V=()=>{x.current!=null&&(clearTimeout(x.current),x.current=null)},H=(X,K,F)=>{const ee=F==null?void 0:F.replaceableForMs;if(X.length===0||!ee)return;const de=Date.now();k.current=[...k.current.filter(({replaceableUntil:fe})=>fe>de),{eventKeys:X,parts:K,replaceableUntil:de+ee}]},Y=()=>A.current.length>0,G=()=>{A.current=[]},W=()=>{const[X,...K]=A.current;if(!X)return!1;A.current=K;const{eventKeys:F,parts:ee,dedupeKey:de}=X,fe=ke=>{H(F,ke,{replaceableForMs:F.length>0?Io:void 0}),e({event:"newMessage",...ke},de?{dedupeKey:de}:void 0)};if(F.length===0)return fe(ee),!0;const xe=E.current,Oe=Vm(xe.messages,F);if(Oe){const ke=To(Oe,xe.stringSet,xe.format);return fe(ke),!0}return fe(ee),!0},q=()=>{for(V();W(););},ce=(X=Io)=>{V(),x.current=setTimeout(()=>{if(x.current=null,$())return;const K=Mo(),[F]=A.current;if(!F)return;if(F.focusTarget!==K){A.current=[{...F,focusTarget:K},...A.current.slice(1)],ce(wo);return}W()&&Y()&&ce(wo)},X)},_e=(X,K,F)=>{const ee={eventKeys:K,parts:X,focusTarget:Mo(),dedupeKey:F?F.dedupeKey??void 0:K[0]},de=K.length===0?-1:A.current.findIndex(({eventKeys:fe})=>Rn(fe,K));de>=0?A.current=A.current.map((fe,xe)=>xe===de?{...ee,dedupeKey:F?ee.dedupeKey:fe.dedupeKey}:fe):A.current=[...A.current,ee],ce()},L=(X,K,F)=>{if(X!=="messagesUpdated"||K.length===0)return!1;const ee=Date.now(),de=k.current.find(fe=>fe.replaceableUntil>ee&&Rn(fe.eventKeys,K));return de?!Gm(F,de.parts):!1};u.useEffect(()=>{const X=O.current!==o;(!t||!d||X)&&(w.current=!1,I.current.clear(),G(),k.current=[],R.current.clear(),V(),X&&(O.current=o),!t||!d)||w.current||(w.current=!0,O.current=o,b.current={isClosed:a,isHandedOff:l,inputDisabled:m,inputDisabledBy:f,outgoingMessageStatuses:Ln(C)},R.current=new Set(s.flatMap(K=>{if(!Ve.isStreaming(K))return[];const F="sender"in K?K.sender:void 0;return(F==null?void 0:F.userId)===E.current.currentUserId?[]:Kn(K)})),I.current=zm(s))},[e,t,o,d,m,a,l,v]),u.useEffect(()=>{const X=(K,F)=>{const ee=E.current,de=Kn(K),fe=hi(K);if(fe!=null){if(I.current.has(fe))return;I.current.add(fe),e({event:"csatDisplayed"});return}if(Ve.isStreaming(K)){de.forEach(B=>{R.current.add(B)});return}const xe=de.filter(B=>R.current.has(B)),Oe=F==="messagesUpdated"&&xe.length>0;Oe&&xe.forEach(B=>{R.current.delete(B)});const ke=F==="messagesUpdated"&&A.current.some(({eventKeys:B})=>Rn(B,de)),T=To(K,ee.stringSet,ee.format),M=L(F,de,T);if(!Oe&&F!=="messagesAdded"&&!ke&&!M)return;const N=M?{dedupeKey:null}:void 0;if(Oe||$()||ke){_e(T,[...new Set([...xe,...de])],N);return}if(M){_e(T,de,N);return}Y()&&q();const j=de[0];e({event:"newMessage",...T},j?{dedupeKey:j}:void 0)};return _(K=>{if(!w.current||K.kind==="initialized"||!Nu(K.source))return;const F=E.current.currentUserId;for(const ee of K.messages)ee&&Lu(ee,F)&&X(ee,K.kind)})},[e,_]),u.useEffect(()=>{w.current&&($()||Y()&&ce())},[f,h]),u.useEffect(()=>()=>{V()},[]),u.useEffect(()=>{if(!w.current)return;const X=b.current,K=X.outgoingMessageStatuses;X.outgoingMessageStatuses=Ln(C),C.some(({key:ee,sendingStatus:de})=>{const fe=K.get(ee);return fe!==void 0&&fe!=="failed"&&de==="failed"})&&e({event:"sendFailed"})},[e,v]),u.useEffect(()=>{if(!w.current)return;const X=b.current;a&&!X.isClosed&&e({event:"conversationClosed"}),X.isClosed=a},[e,a]),u.useEffect(()=>{if(!w.current)return;const X=b.current;l&&!X.isHandedOff&&e({event:"agentConnected",agentName:c}),X.isHandedOff=l},[c,e,l]),u.useEffect(()=>{if(!w.current)return;const X=b.current;m&&f!=="ai_responding"&&(!X.inputDisabled||X.inputDisabledBy==="ai_responding")&&e({event:"inputDisabled"}),X.inputDisabled=m,X.inputDisabledBy=f},[e,m,f])},Wm=()=>{const{channelSource:e}=Se(),t=Rs(e.channel);return!(t!=null&&t.user.userId)||!t.user.nickname?null:{userId:t.user.userId,nickname:t.user.nickname}},qm=e=>{const{announceStatus:t,announcementsEnabled:n}=Ke();Gc(e??null,r=>{t({event:"typing",agentName:r})},1e4,n)},Km=()=>{const e=Wm();qm(e)},Q=({type:e,size:t=24,className:n,color:r})=>{const{icons:o}=vd(),s=o[e];return i.createElement(jm,{className:n},i.createElement(s,{size:t,color:r??g.color.primary.main,flipInRtl:hd.has(e)}))},jm=p.default.span.attrs({"aria-hidden":"true"})`
|
|
80
|
+
`;return n.set(e,s),s},zd=e=>e?D.css`display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:${e};overflow:hidden;`:"",Vd=p.default.span`font-stretch:normal;letter-spacing:normal;${({$variant:e,theme:t})=>Gd(e,t.typography)}color:${({$color:e})=>e};${({$maxTextLines:e})=>zd(e)}`,mn=["a[href]","button:not(:disabled)","input:not(:disabled)","select:not(:disabled)","textarea:not(:disabled)",'[tabindex]:not([tabindex="-1"])'].join(", "),ii=`${mn}, [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 br(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 kt=(e,t)=>{for(const n of e.querySelectorAll(t))if(!n.hasAttribute(hr)&&ft(n))return n;return null},ai=e=>{let t=null,n=null;for(const r of e.querySelectorAll(mn))r.hasAttribute(hr)||ft(r)&&(t??(t=r),n=r);return t?{first:t,last:n}:null},Cr=e=>kt(e,Yu),li=e=>Cr(e)??kt(e,mn),Yd=e=>{const t=Cr(e);if(t)return t;const n=e.querySelector(qu);return(n?kt(n,ii):null)??kt(e,mn)},qn='[role="dialog"][aria-modal="true"]',Wd=(e,t)=>{const n=new Set(Array.from(e.ownerDocument.querySelectorAll(qn)).filter(o=>o!==e&&(o.contains(e)||e.contains(o)))),r=t==null?void 0:t.closest(qn);return r&&r!==e&&n.add(r),n},qd=(e,t)=>Array.from(e.ownerDocument.querySelectorAll(qn)).some(n=>n!==e&&!t.has(n)&&!n.contains(e)&&ft(n)),Kd=e=>{const t=li(e)??e;t===e&&ci(e),t.focus()},ci=e=>{e.hasAttribute("tabindex")||e.setAttribute("tabindex","-1")},jd=(e,t)=>{const n=ai(e);if(!n){ci(e),e.focus();return}n[t].focus()},Eo=(e,t)=>{const n=e.ownerDocument.createElement("span");return n.tabIndex=0,n.setAttribute(hr,Wu),n.style.cssText=["position: fixed","width: 1px","height: 1px","opacity: 0","overflow: hidden","pointer-events: none"].join(";"),n.addEventListener("focus",()=>jd(e,t)),n},Xd=(e,t)=>{e.key==="Tab"&&(e.defaultPrevented||e.target===t&&(ai(t)||(e.preventDefault(),t.focus())))},Zd=(e,t)=>t instanceof HTMLElement?e instanceof Document?t===e.body||t===e.documentElement:!1:!0,fn=(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=Wd(a,c);return()=>{c&&we(()=>{if(r.current!==s)return;const m=l.activeElement;a.isConnected&&m instanceof HTMLElement&&m!==a&&!a.contains(m)&&!Zd(l,m)&&m.matches(ii)&&ft(m)||qd(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,Kd(s)};if(n)return we(l),()=>{a=!0};const c=setTimeout(()=>we(l),js);return()=>{a=!0,clearTimeout(c)}},[e,t,n]),u.useEffect(()=>{if(!e||!t.current)return;const s=t.current,a=Eo(s,"last"),l=Eo(s,"first"),c=d=>Xd(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])},nt=({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}=_r();return fn(n,d),id(n,s?r:ge),n?ga.createPortal(i.createElement(Jd,{onClick:s?r:void 0,style:e},i.createElement(Qd,{ref:d,role:"dialog","aria-modal":"true","aria-label":a,"aria-labelledby":l,"aria-describedby":c,onClick:f=>f.stopPropagation()},o)),m(t)):null},Jd=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};`,Qd=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};`,em=({id:e,children:t})=>i.createElement(tm,{id:e},t),tm=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;`,bo=(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?{}:zs}:n},nm=()=>{const e=`${u.useId()}-`;return(t,n)=>{if(!t)return{props:{},node:null};const r=e+n,o=u.createElement(em,{id:r,children:t});return{props:{"aria-describedby":r},node:o}}},Co=({name:e,mimeType:t,selected:n},r)=>{var s;const o=He(t??"")?r.A11Y_FILE_IMAGE(e):cn(t??"")?r.A11Y_FILE_VIDEO(e):ds({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},rm=e=>t=>{t.repeat||(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),e())},At=({onActivate:e})=>({role:"button",tabIndex:0,onClick:e,onKeyDown:rm(e)}),om=({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()},vo=(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:om({disabled:t,currentIndex:n,totalCount:r,onNavigate:s}),tabIndex:a}},oe=()=>{const{stringSet:e}=se(),t=nm(),n=(a,l)=>{let c=e.A11Y_HINT_OPEN_FILE,d="of";He(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":Co(a,e)});return{launcher:{button:({isOpened:a,opensConversationList:l})=>{const c=zu({intent:Bu({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:bo(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,...ju},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:{...At({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?Co({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:{...At({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:_})=>{var E;const v=l.trim()||l,y=e.A11Y_HINT_SELECT_RATING,b=t(y,`cs${a}`);return{props:{disabled:d,onClick:()=>_(a),...vo(c,d,m,f,g,C=>_(C+1)),...b.props,"aria-label":((E=e.A11Y_CSAT_RATING_LABEL)==null?void 0:E.call(e,a,v))??`${a} / ${f} — ${v}`},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:{...vo(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:bo(a,l),descriptionNode:null}),footer:{button:({onActivate:a})=>({props:{...At({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:{...At({onActivate:m}),...g.props,"aria-label":e.A11Y_CONVERSATION_ITEM(a,l,c,d)},descriptionNode:g.node}}}}},sm=({title:e,description:t,highlightedText:n})=>{const r=au(t,n);return i.createElement(am,null,i.createElement(lm,null,i.createElement($,{as:"div",variant:"h1",color:h.themedColor.textHighEmphasis},e),t&&i.createElement(cm,null,i.createElement($,{as:"div",variant:"body3",color:h.themedColor.textMidEmphasis},r.beforeText,r.highlightedText?i.createElement(um,null,r.highlightedText):null,r.afterText))))},im=()=>{const{components:e}=gn.useContext(),{stringSet:t}=se(),{messenger:n}=oe(),r=su(),o=r.showDescription?iu(r.remainingTime):"",s=r.showDescription?t.CONNECTION_DELAY__DESCRIPTION(o):"";return i.createElement(nt,{portalContainerId:Ce.WINDOW,visible:r.visible,onClose:ge,...n.connectionDelayDialog().props},i.createElement(e.Dialog,{title:t.CONNECTION_DELAY__TITLE,description:s,highlightedText:o||void 0}))},gn=Be({template:im,components:{Dialog:sm}}),am=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};`,lm=p.default.div`display:flex;flex-direction:column;`,cm=p.default.div`margin-top:16px;`,um=p.default.strong`font-weight:700;`,dm=({url:e})=>br(e),{Provider:mm,Consumer:ui,useContext:me}=Ee("Messenger");function fm({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}=_r(),g=u.useCallback(()=>{var y;m.setOpened(!1),(y=f(Ce.LAUNCHER))==null||y.focus()},[m.setOpened,f]);ad(m.opened,g);const{Template:_}=gn.useContext(),v=u.useMemo(()=>{var y;return{...s.handlers,onClickLink:((y=s.handlers)==null?void 0:y.onClickLink)??dm}},[s.handlers]);return i.createElement(Ll,{...s},y=>i.createElement(mm,{value:{...s,...y,state:m,enableCloseConversationButton:n,enableExpandButton:r,enableAutoDisconnectInLauncher:o,handlers:v}},i.createElement(_,null),e))}const di=/iPad|iPhone|iPod/.test(navigator.userAgent),gm=/Android/.test(navigator.userAgent),Nt=e=>di||gm;let yt=null,Mn=null;const hm=(e,t=5e3)=>{yt&&(clearInterval(yt),clearTimeout(Mn));const n=document.title;yt=setInterval(()=>{document.title=document.title===e?n:e},750),Mn=setTimeout(()=>{clearInterval(yt),yt=null,Mn=null,document.title=n},t)},mi=()=>{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;}`,yo=e=>{if(typeof e=="string"||typeof e=="number")return String(e)},hn=({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??yo(t)??yo(n),g=c?void 0:t?d:n?m:void 0,_=t&&n?m:void 0,v=()=>{l(),we(()=>s==null?void 0:s())},y=()=>{l(),we(()=>a==null?void 0:a())};return i.createElement(nt,{portalContainerId:Ce.WINDOW,visible:e,onClose:l,"aria-label":f,"aria-labelledby":g,"aria-describedby":_},i.createElement(pm,null,i.createElement(_m,null,t&&i.createElement("div",{id:d},i.createElement($,{variant:"h1",color:h.themedColor.textHighEmphasis},t)),n&&i.createElement(Em,{id:m},i.createElement($,{variant:"body3",color:h.themedColor.textMidEmphasis},n))),i.createElement(bm,null,o&&i.createElement(So,{onClick:y},i.createElement($,{variant:"button",color:h.themedColor.textHighEmphasis},o)),i.createElement(So,{onClick:v},i.createElement($,{variant:"button",color:h.themedColor.primary},r)))))},pm=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};`,_m=p.default.div`margin-bottom:16px;`,Em=p.default.div`margin-top:16px;`,bm=p.default.div`display:flex;flex-direction:row;justify-content:flex-end;`,So=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:Cm,useContext:Me}=Ee("MessengerSession"),vm=u.forwardRef(function({children:e,...t},n){return i.createElement(fc,{ref:n,...t},r=>i.createElement(ym,{...r},e))}),ym=({children:e,...t})=>{const{chatSDK:n,logger:r,appId:o,aiAgentId:s,agentPreviewConfigs:a,state:l,handlers:c,dispatcher:d,_aiAgentSDK:m}=me(),{userSessionInfo:f,authenticate:g,userSession:_,aiAgentInfo:v,launcherInfo:y}=t,[b,E]=u.useState(!1),C=u.useRef(null);ht(n,{async onUserJoined(x,w){var I,M,O,F;x.conversation&&x.conversation.type===be.ConversationType.PROACTIVE&&w.userId===((I=n.currentUser)==null?void 0:I.userId)&&(r.info("messengerSession.onUserJoined: proactive channel joined",x.url),(O=m.session)==null||O._updateActiveChannel({url:x.url,status:"open",conversationStatus:(M=x.conversation)==null?void 0:M.status}),l.setOpened(!0),Sm({sound:document.hidden||!l.opened}),(F=C.current)==null||F.call(C,{channel:x}))}}),u.useEffect(()=>{g().then(({launcher:x})=>{x.auto_open&&!Nt()&&setTimeout(()=>l.setOpened(!0),500)}).catch(x=>{var w;r.error("messengerSession: failed to initialize",x),(w=c==null?void 0:c.onInitializeFailed)==null||w.call(c,x)})},[n,o,s,f==null?void 0:f.userId]),u.useEffect(()=>{const x=()=>E(!0);return d.subscribe(Fe.AnonymousSessionTokenExpired,x),()=>d.unsubscribe(Fe.AnonymousSessionTokenExpired,x)},[d]);const S=u.useCallback(()=>{t.deauthenticate().finally(()=>window.location.reload())},[t.deauthenticate]);return!_||!v||!y?null:i.createElement(Cm,{value:{...t,userSession:_,aiAgentInfo:{...v,...a==null?void 0:a.bot},launcherInfo:{...y,...a==null?void 0:a.launcher},registerOnJoinedProactiveConversation:x=>C.current=x}},e,i.createElement(hn,{visible:b,title:"Session timed out",description:"Start a new conversation.",onConfirm:S,onClose:ge}))};function Sm({sound:e}){hm("🔔You have received a new message"),e&&mi()}const an=`@${Ne}-focused-channel`,fi=`${Date.now()}-${Math.random().toString(36).slice(2)}`,Am=()=>{try{const e=localStorage.getItem(an);return e?JSON.parse(e).channelUrl??null:null}catch{return null}},Ao=e=>{try{localStorage.setItem(an,JSON.stringify({channelUrl:e,tabId:fi}))}catch{}},xo=()=>{try{const e=localStorage.getItem(an);if(!e)return;JSON.parse(e).tabId===fi&&localStorage.removeItem(an)}catch{}},xm=(e,t)=>(u.useEffect(()=>{if(!t||!e)return;const n=()=>Ao(e),r=()=>xo();return document.hasFocus()&&Ao(e),window.addEventListener("focus",n),window.addEventListener("blur",r),()=>{window.removeEventListener("focus",n),window.removeEventListener("blur",r),xo()}},[t,e]),{isChannelViewedInAnyTab:()=>document.hasFocus()||Am()===e}),Tm=e=>{const{config:t,chatSDK:n}=me(),{sdkUser:r}=Me(),o=t.conversation.messageAlertSoundEnabled,{isChannelViewedInAnyTab:s}=xm(e,o);ht(n,{onMessageReceived(a,l){if(!o||a.url!==e||s())return;(Qe(l)&&l.sender.userId!==(r==null?void 0:r.userId)||l.isAdminMessage()&&!l.silent)&&mi()}})};function Im(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 wm(e){if("file"in e&&e.file instanceof File&&e.file.type.startsWith("image/")){const{width:t,height:n}=await Im(e.file);return new Ue.MessageMetaArray({key:cs,value:[t,n]})}}const Mm=({onScrollAfterSendMessage:e})=>{const{agentPreviewConfigs:t,handlers:n}=me(),r=u.useRef(t==null?void 0:t.agentAttributes);return r.current=t==null?void 0:t.agentAttributes,{onBeforeSendMessage:async o=>{const s=await wm(o),a={...o,metaArrays:s?[s]:void 0},l=km(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===Ue.SendingStatus.SUCCEEDED?(a=n==null?void 0:n.onCustomEvent)==null||a.call(n,{type:"message-sent-succeeded",data:{message:o}}):o.sendingStatus===Ue.SendingStatus.PENDING&&((l=n==null?void 0:n.onCustomEvent)==null||l.call(n,{type:"message-sent-pending",data:{message:o}}))}}},km=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,kn=dt-40,{Provider:Rm,useContext:gi}=Ee("ConversationScroll"),To={viewport:0,contentHeight:0,contentSnapshotHeight:0,shouldRecalc:!1,shouldUpdate:!1},Rn=e=>Math.max(0,e.scrollHeight-e.scrollTop-e.clientHeight);function Lm({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(To),f=u.useRef(!1),g=u.useRef(null),[_,v]=u.useState(0),[y,b]=u.useState(0),[E,C]=u.useState(!1),[S,x]=u.useState(!1),[w,k]=u.useState(!0),I=T=>{const R=Rn(T);return s.current=R,b(R),R},M=()=>{d.current&&(clearTimeout(d.current),d.current=null)},O=u.useMemo(()=>E||t==="bottom"?"auto":e,[E,t,e]),F=()=>{m.current.contentSnapshotHeight=m.current.contentHeight,m.current.shouldUpdate=!0,m.current.shouldRecalc=!0},Y=()=>{const T=r.current;!T||!m.current.shouldUpdate||v(R=>{m.current.shouldUpdate=!1;const{contentHeight:N,contentSnapshotHeight:j,shouldRecalc:U}=m.current,G=T.clientHeight;if(j>N)return R;const B=z(T,{messageType:"outgoing"});let ue=0;if(B){const $e=B.message.offsetTop-kn+G;ue=Math.max(0,$e-N)}else{const $e=N-j,ae=G-kn;ue=Math.max(0,$e-ae)}return R===0||ue!==R||U?(m.current.shouldRecalc=!1,ue):R})},z=u.useCallback((T,R)=>{const{messageType:N="all"}=R??{},j=Array.from(T.querySelectorAll(`#${Ne}-message-item`));let U=j;N==="outgoing"&&(U=j.filter(ne=>ne.getAttribute("data-layout-id")==="outgoingmessage"));const G=U[U.length-1];if(!G)return null;const B=T.getBoundingClientRect(),ue=G.getBoundingClientRect(),$e=T.scrollTop+(ue.top-B.top),ae=$e+G.offsetHeight;return{message:G,scrollTop:$e,lastMessageBottom:ae}},[]),V=u.useCallback(()=>{const T=r.current;if(!T||O!=="fixed")return;const R=z(T);m.current.contentHeight=(R==null?void 0:R.lastMessageBottom)??T.scrollHeight,!f.current&&m.current.contentSnapshotHeight>0&&F(),c.current?s.current=Rn(T):I(T),Y()},[O,z]),H=u.useCallback(()=>{o.current&&(o.current.disconnect(),o.current=null),M(),m.current=To,v(0),b(0),k(!0),s.current=0,l.current=!1,a.current=0,c.current=!1},[]),W=u.useCallback((T=!0)=>{const R=s.current>dt;if(l.current=!1,b(0),!R){we(()=>{const N=r.current;N&&!l.current&&N.scrollTo({top:N.scrollHeight,behavior:"auto"})});return}c.current||(c.current=!0,k(!1),M()),we(()=>{const N=r.current;if(!N){c.current=!1,k(!0);return}if(l.current){c.current=!1,I(N),k(!0);return}const j=()=>{if(r.current!==N){c.current=!1,r.current&&I(r.current),k(!0);return}c.current=!1,I(N),k(!0)};if(T&&!d.current){const U=setTimeout(j,500);d.current=U,N.addEventListener("scrollend",()=>{clearTimeout(U),d.current=null,j()},{once:!0})}N.scrollTo({top:N.scrollHeight,behavior:T?"smooth":"auto"}),T||j()})},[]),q=u.useCallback(T=>{T&&(r.current=T,O==="fixed"&&(H(),m.current.viewport=T.clientHeight,o.current=new MutationObserver(()=>{V()}),o.current.observe(T,{childList:!0,subtree:!0})))},[O,V,H]),ce=u.useCallback(()=>{const T=r.current;if(!T)return;const R=z(T,{messageType:"outgoing"});R&&(T.scrollTo({top:R.message.offsetTop-kn,behavior:"smooth"}),g.current&&clearTimeout(g.current),g.current=setTimeout(()=>{x(!1)},500))},[z]),_e=(T,R,N)=>{const j=Rn(T);if(N&&j>dt){c.current=!1,l.current=!0,M(),I(T),k(!0),a.current=R;return}s.current=j},L=(T,R,N)=>{const U=I(T)<=dt;R&&!U&&(l.current=!0,M()),N&&U&&(l.current=!1)},X=T=>{const{scrollTop:R}=T.currentTarget,N=a.current;c.current?_e(T.currentTarget,R,R<N):L(T.currentTarget,R<N,R>N),a.current=R},K=u.useCallback(()=>{O==="fixed"&&(x(!0),F())},[O]),P=u.useCallback(()=>{O==="fixed"?setTimeout(()=>ce(),300):W()},[O,ce]),te=u.useCallback(T=>{f.current=T,O==="fixed"?F():l.current||W()},[O,W]),de=u.useCallback(T=>{C(T),T&&(v(0),o.current&&(o.current.disconnect(),o.current=null))},[]),fe=u.useCallback(T=>{O==="auto"&&T&&!l.current&&W()},[O,W]),Oe=!(y<=dt)&&!S,Re=u.useCallback(()=>s.current>dt,[]);return i.createElement(Rm,{value:{ref:q,state:{bottomSpace:_,isAwayFromBottom:Oe,isScrollPositionReconciled:w,shouldCountNewMessages:Re},props:{onScroll:X},actions:{scrollToBottom:W,onBeforeMessageSend:K,onAfterMessageSend:P,onStreamingUpdate:te,onConversationClosed:de,onTypingIndicatorUpdate:fe}}},n)}const{Provider:Om,Context:Nm,useContext:Se}=Ee("Conversation"),Dm=({children:e})=>{var o;const{channelSource:t}=Se(),n=(o=t.channel)==null?void 0:o.url,{checkForUserActionRequired:r}=zc(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)},$m=({channelUrl:e,onClearChannelUrl:t,onNavigateToConversationList:n,shouldMarkAsRead:r,children:o})=>{const{activeChannel:s,refreshActiveChannel:a}=Me(),l=gi(),c=e||(s==null?void 0:s.url);Tm(c);const{onBeforeSendMessage:d,onAfterSendMessage:m}=Mm({onScrollAfterSendMessage:()=>{l.actions.onAfterMessageSend()}}),f=u.useCallback(v=>(l.actions.onBeforeMessageSend(),d(v)),[l.actions,d]),g=u.useCallback(v=>{const y=v.some(b=>Ve.isStreaming(b));l.actions.onStreamingUpdate(y)},[l.actions.onStreamingUpdate]),_=u.useCallback(async()=>{await a(),e&&(t==null||t())},[a,e,t]);return i.createElement(xc,{key:c,channelUrl:c,onBeforeSendMessage:f,onAfterSendMessage:m,onMessagesUpdated:g,onMessagesReceived:g,onChannelDeleted:_,onConversationClosedStatusChanged:l.actions.onConversationClosed,shouldMarkAsRead:r,shouldCountNewMessages:l.state.shouldCountNewMessages},v=>i.createElement(Om,{value:{...v,scrollSource:l,goToActiveConversation:_,onNavigateToConversationList:n}},i.createElement(Dm,null,o)))},hi=({children:e,...t})=>{const{config:n}=ke(),{agentPreviewConfigs:r}=me(),o=n.conversation.list.scrollMode,s=r==null?void 0:r.messageStackDirection;return i.createElement(Lm,{scrollMode:o,messageStackDirection:s},i.createElement($m,{...t},e))},vr=u.createContext({onDrop:ge,subscribe:()=>ge}),Kn=({children:e})=>{const t=u.useRef(new Set);return i.createElement(vr.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)},Pm=({onDropFiles:e})=>{const{subscribe:t}=u.useContext(vr);u.useEffect(()=>t(e),[e])};Kn.Consumer=({children:e})=>{const{onDrop:t}=u.useContext(vr);return e({onDrop:t,onDragOver:o=>o.preventDefault()})};const pi=Ee("WindowTitle",{hasWindowTitleReference:!1,isTitlePending:!1,isWindowNameReady:!0,registerWindowTitleReference:()=>ge,registerWindowTitlePending:()=>ge}),Fm=pi.Provider,_i=pi.useContext,Io=()=>{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]},yr=({children:e})=>{const[t,n]=Io(),[r,o]=Io(),s=!r||t,a=u.useMemo(()=>({hasWindowTitleReference:t,isTitlePending:r,isWindowNameReady:s,registerWindowTitleReference:n,registerWindowTitlePending:o}),[t,r,n,o]);return i.createElement(Fm,{value:a},e)},pn=_i,Ei=({enabled:e,label:t})=>{const{registerWindowTitleReference:n,registerWindowTitlePending:r}=_i(),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?Ce.WINDOW_TITLE:void 0}},Um=(e,t)=>{const r=(t?kt(e,t):null)??Yd(e)??e;r===e&&!e.hasAttribute("tabindex")&&e.setAttribute("tabindex","-1"),r.focus()},bi=(e,{enabled:t,ready:n,nameReady:r=!0,targetSelector:o})=>{const s=u.useRef(!1);u.useEffect(()=>{if(!t){s.current=!1;return}if(s.current||!e.current||o&&!n)return;const a=Cr(e.current)!=null;if(!o&&!a&&!n)return;let l=!1;const c=()=>{l||s.current||!e.current||(s.current=!0,Um(e.current,o))};if(r)return we(c),()=>{l=!0};const d=setTimeout(()=>we(c),js);return()=>{l=!0,clearTimeout(d)}},[t,n,r,o,e])},Bm=(e,t)=>{const{announcementsEnabled:n}=Ke(),{channelSource:r}=Se(),{isWindowNameReady:o}=pn(),s=r.channel!=null||r.error!=null;bi(e,{enabled:n,ready:s,nameReady:o,targetSelector:t==="messageInput"?Ku:void 0})},Hm=e=>He(e)||cn(e);function Gm(e){return e.isAdminMessage()?e.message==="The channel's custom_type was updated.":!1}function zm(e,t){return e.filter(n=>Ve.isWelcomeMessage(n,t))}const Ci=(e,{previewWelcomeMessages:t,aiAgentUserId:n})=>e.filter(r=>Gm(r)?!1:t.length>0?!Ve.isWelcomeMessage(r,n):!0),Vm=[],vi=()=>{var v,y,b,E,C,S;const{agentPreviewConfigs:e={},aiAgentId:t}=me(),{aiAgentInfo:n,userSession:r}=Me(),{channelSource:o,messageSource:s,state:{input:a,streamAnimation:l}}=Se(),c=e.welcomeMessages??Vm,d=u.useMemo(()=>Ci(s.messages,{previewWelcomeMessages:c,aiAgentUserId:t}),[t,s.messages,c]),m=et(o.channel),f=(y=(v=bs(o.channel,r.userId))==null?void 0:v.nickname)==null?void 0:y.trim(),g=m?(E=(b=o.channel)==null?void 0:b.name)==null?void 0:E.trim():(C=n==null?void 0:n.nickname)==null?void 0:C.trim(),_=f||g||void 0;return{initialized:s.initialized,channelUrl:(S=o.channel)==null?void 0:S.url,agentName:_,isClosed:Le(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}},Ym=(e={})=>{const{announceScreenEntry:t,announcementsEnabled:n}=Ke(),{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=>Ie.isAdmin(g)&&Ie.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])},Wm=()=>{const e=vi();Ym(e)},qm=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}),wo=(e,t,n=Xe.format)=>{const r=ku(e,qm(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}},Km={senderName:!0,body:!0,time:!0},jm=Object.keys(Km),Xm=(e,t)=>jm.every(n=>e[n]===t[n]),Mo=2e3,ko=400,jn=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]},yi=e=>{if(!Ie.isAdmin(e)||!Ie.isCSAT(e))return null;const t=Fu(e);return t?`csat:${t}`:null},Zm=e=>{const t=new Set;for(const n of e){const r=yi(n);r&&t.add(r)}return t},Jm=(e,t)=>{for(let n=e.length-1;n>=0;n-=1){const r=e[n];if(r&&jn(r).some(o=>t.includes(o)))return r}},Ln=(e,t)=>e.some(n=>t.includes(n)),Ro=()=>typeof document>"u"?null:document.activeElement instanceof HTMLElement?document.activeElement:null,On=e=>new Map(e.map(({key:t,sendingStatus:n})=>[t,n])),Qm=()=>{const{announceStatus:e,announcementsEnabled:t}=Ke(),{stringSet:n,format:r}=se(),{channelUrl:o,messages:s,isClosed:a,isHandedOff:l,agentName:c,initialized:d,inputDisabled:m,inputDisabledBy:f,isStreamAnimating:g,subscribeMessageEvents:_,currentUserId:v}=vi(),{outgoingMessageStates:y,outgoingMessageStatusSignature:b}=u.useMemo(()=>{if(!v)return{outgoingMessageStates:[],outgoingMessageStatusSignature:""};const X=s.flatMap(K=>{const P=$u(K,v);return!P||!("sendingStatus"in K)?[]:[{key:P,sendingStatus:K.sendingStatus}]});return{outgoingMessageStates:X,outgoingMessageStatusSignature:X.map(({key:K,sendingStatus:P})=>`${K}:${P}`).join(",")}},[v,s]),E=u.useRef({isClosed:!1,isHandedOff:!1,inputDisabled:m,inputDisabledBy:f,outgoingMessageStatuses:On(y)}),C=u.useRef({messages:s,currentUserId:v,inputDisabledBy:f,isStreamAnimating:g,stringSet:n,format:r}),S=u.useRef([]),x=u.useRef(null),w=u.useRef([]),k=u.useRef(new Set),I=u.useRef(new Set),M=u.useRef(!1),O=u.useRef(o);C.current={messages:s,currentUserId:v,inputDisabledBy:f,isStreamAnimating:g,stringSet:n,format:r};const F=()=>C.current.isStreamAnimating||C.current.inputDisabledBy==="ai_responding",Y=()=>{x.current!=null&&(clearTimeout(x.current),x.current=null)},z=(X,K,P)=>{const te=P==null?void 0:P.replaceableForMs;if(X.length===0||!te)return;const de=Date.now();w.current=[...w.current.filter(({replaceableUntil:fe})=>fe>de),{eventKeys:X,parts:K,replaceableUntil:de+te}]},V=()=>S.current.length>0,H=()=>{S.current=[]},W=()=>{const[X,...K]=S.current;if(!X)return!1;S.current=K;const{eventKeys:P,parts:te,dedupeKey:de}=X,fe=Re=>{z(P,Re,{replaceableForMs:P.length>0?Mo:void 0}),e({event:"newMessage",...Re},de?{dedupeKey:de}:void 0)};if(P.length===0)return fe(te),!0;const xe=C.current,Oe=Jm(xe.messages,P);if(Oe){const Re=wo(Oe,xe.stringSet,xe.format);return fe(Re),!0}return fe(te),!0},q=()=>{for(Y();W(););},ce=(X=Mo)=>{Y(),x.current=setTimeout(()=>{if(x.current=null,F())return;const K=Ro(),[P]=S.current;if(!P)return;if(P.focusTarget!==K){S.current=[{...P,focusTarget:K},...S.current.slice(1)],ce(ko);return}W()&&V()&&ce(ko)},X)},_e=(X,K,P)=>{const te={eventKeys:K,parts:X,focusTarget:Ro(),dedupeKey:P?P.dedupeKey??void 0:K[0]},de=K.length===0?-1:S.current.findIndex(({eventKeys:fe})=>Ln(fe,K));de>=0?S.current=S.current.map((fe,xe)=>xe===de?{...te,dedupeKey:P?te.dedupeKey:fe.dedupeKey}:fe):S.current=[...S.current,te],ce()},L=(X,K,P)=>{if(X!=="messagesUpdated"||K.length===0)return!1;const te=Date.now(),de=w.current.find(fe=>fe.replaceableUntil>te&&Ln(fe.eventKeys,K));return de?!Xm(P,de.parts):!1};u.useEffect(()=>{const X=O.current!==o;(!t||!d||X)&&(M.current=!1,I.current.clear(),H(),w.current=[],k.current.clear(),Y(),X&&(O.current=o),!t||!d)||M.current||(M.current=!0,O.current=o,E.current={isClosed:a,isHandedOff:l,inputDisabled:m,inputDisabledBy:f,outgoingMessageStatuses:On(y)},k.current=new Set(s.flatMap(K=>{if(!Ve.isStreaming(K))return[];const P="sender"in K?K.sender:void 0;return(P==null?void 0:P.userId)===C.current.currentUserId?[]:jn(K)})),I.current=Zm(s))},[e,t,o,d,m,a,l,b]),u.useEffect(()=>{const X=(K,P)=>{const te=C.current,de=jn(K),fe=yi(K);if(fe!=null){if(I.current.has(fe))return;I.current.add(fe),e({event:"csatDisplayed"});return}if(Ve.isStreaming(K)){de.forEach(U=>{k.current.add(U)});return}const xe=de.filter(U=>k.current.has(U)),Oe=P==="messagesUpdated"&&xe.length>0;Oe&&xe.forEach(U=>{k.current.delete(U)});const Re=P==="messagesUpdated"&&S.current.some(({eventKeys:U})=>Ln(U,de)),T=wo(K,te.stringSet,te.format),R=L(P,de,T);if(!Oe&&P!=="messagesAdded"&&!Re&&!R)return;const N=R?{dedupeKey:null}:void 0;if(Oe||F()||Re){_e(T,[...new Set([...xe,...de])],N);return}if(R){_e(T,de,N);return}V()&&q();const j=de[0];e({event:"newMessage",...T},j?{dedupeKey:j}:void 0)};return _(K=>{if(!M.current||K.kind==="initialized"||!Uu(K.source))return;const P=C.current.currentUserId;for(const te of K.messages)te&&Pu(te,P)&&X(te,K.kind)})},[e,_]),u.useEffect(()=>{M.current&&(F()||V()&&ce())},[f,g]),u.useEffect(()=>()=>{Y()},[]),u.useEffect(()=>{if(!M.current)return;const X=E.current,K=X.outgoingMessageStatuses;X.outgoingMessageStatuses=On(y),y.some(({key:te,sendingStatus:de})=>{const fe=K.get(te);return fe!==void 0&&fe!=="failed"&&de==="failed"})&&e({event:"sendFailed"})},[e,b]),u.useEffect(()=>{if(!M.current)return;const X=E.current;a&&!X.isClosed&&e({event:"conversationClosed"}),X.isClosed=a},[e,a]),u.useEffect(()=>{if(!M.current)return;const X=E.current;l&&!X.isHandedOff&&e({event:"agentConnected",agentName:c}),X.isHandedOff=l},[c,e,l]),u.useEffect(()=>{if(!M.current)return;const X=E.current;m&&f!=="ai_responding"&&(!X.inputDisabled||X.inputDisabledBy==="ai_responding")&&e({event:"inputDisabled"}),X.inputDisabled=m,X.inputDisabledBy=f},[e,m,f])},ef=()=>{const{channelSource:e}=Se(),t=Os(e.channel);return!(t!=null&&t.user.userId)||!t.user.nickname?null:{userId:t.user.userId,nickname:t.user.nickname}},tf=e=>{const{announceStatus:t,announcementsEnabled:n}=Ke();qc(e??null,r=>{t({event:"typing",agentName:r})},1e4,n)},nf=()=>{const e=ef();tf(e)},Q=({type:e,size:t=24,className:n,color:r})=>{const{icons:o}=wd(),s=o[e];return i.createElement(rf,{className:n},i.createElement(s,{size:t,color:r??h.color.primary.main,flipInRtl:vd.has(e)}))},rf=p.default.span.attrs({"aria-hidden":"true"})`
|
|
81
81
|
display: inline-flex;
|
|
82
82
|
&:focus {
|
|
83
83
|
outline: none;
|
|
84
84
|
}
|
|
85
|
-
`,
|
|
86
|
-
background-color: ${
|
|
85
|
+
`,of=.75,Si=6,sf=Si*2;let Xn=null;typeof Intl<"u"&&"Segmenter"in Intl&&(Xn=new Intl.Segmenter(void 0,{granularity:"grapheme"}));const af=e=>Xn?Array.from(Xn.segment(e),t=>t.segment):[...e],lf=e=>{const t=Math.floor(e.length*of),n=Math.max(0,e.length-Si);return Math.max(t,n)},Lo=(e,t="")=>{if(e.length<sf)return{start:e+t,end:""};const n=af(e),r=lf(n);return{start:n.slice(0,r).join(""),end:n.slice(r).join("")+t}},cf=e=>{const t=e.normalize("NFC").trim(),n=t.lastIndexOf(".");if(!(n>0&&n<t.length-1))return Lo(t);const o=t.slice(0,n),s=t.slice(n);return Lo(o,s)},Ai=({children:e,...t})=>{const{start:n,end:r}=u.useMemo(()=>cf(e),[e]);return r?i.createElement(uf,null,i.createElement(df,{...t},n),i.createElement(mf,{...t},r)):i.createElement($,{...t},n)},uf=p.default.span`display:flex;width:100%;min-width:0;overflow:hidden;direction:inherit;`,df=p.default($)`overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex-shrink:1;min-width:0;`,mf=p.default($)`flex-shrink:0;white-space:nowrap;`,Sr=({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(ff,{...d.props,$clickable:!!s},i.createElement(hf,{$bgColor:o??l.base.primary},i.createElement(Q,{type:"file-document",size:24,color:r??l.base.primaryContrastContent})),i.createElement(pf,null,i.createElement(Ai,{variant:"button",color:h.themedColor.textHighEmphasis},e),i.createElement($,{color:h.themedColor.textMidEmphasis,variant:"caption3"},n)),d.descriptionNode)},ff=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&&gf}`,gf=D.css`cursor:pointer;${Ae}&:hover{background-color:${h.themedColor.bg_100_500};}`,hf=p.default.div`border-radius:8px;width:40px;height:40px;display:flex;align-items:center;justify-content:center;background-color:${({$bgColor:e})=>e};`,pf=p.default.div`display:flex;flex:1;flex-direction:column;gap:4px;min-width:0;`;function _f({file:e,children:t,onClickFile:n}){const r=n?()=>n(e):void 0;return i.createElement(Ef,null,i.createElement(Sr,{name:e.name,mimeType:e.type,type:nr(e.name,e.type),onClick:r}),t)}const Ef=p.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${ee.GAP_GROUPED}px;`,We=`${Ne}-incoming-msg`,bf=`${Ne}-marked-text`;function Cf({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(Sf,{src:e.url,alt:"image-message"}):e.type.startsWith("video")?i.createElement(Af,{controls:!0},i.createElement("source",{src:e.url}),i.createElement("track",{kind:"captions"})):null;if(c){const d={id:`${We}-media-body`,...l.props};return i.createElement(vf,null,i.createElement(yf,{...d},c(),l.descriptionNode),r)}return null}const vf=p.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${ee.GAP_GROUPED}px;`,yf=p.default.div`width:${ee.BODY_MAX_WIDTH}px;height:160px;border-radius:12px;overflow:hidden;cursor:pointer;${J.light`
|
|
86
|
+
background-color: ${h.color.background100};
|
|
87
87
|
`}
|
|
88
88
|
${J.dark`
|
|
89
|
-
background-color: ${
|
|
89
|
+
background-color: ${h.color.background400};
|
|
90
90
|
`}
|
|
91
|
-
`,
|
|
92
|
-
background-color: ${
|
|
91
|
+
`,Sf=p.default.img`width:100%;height:100%;object-fit:cover;`,Af=p.default.video`width:100%;height:100%;object-fit:cover;`,at=({className:e,children:t,size:n=26})=>i.createElement(xf,{className:e,$size:n},t??i.createElement(Q,{type:"spinner",size:n})),xf=p.default.div`display:flex;align-items:center;justify-content:center;width:${({$size:e})=>Ge(e)};height:${({$size:e})=>Ge(e)};animation:1s infinite linear;animation-name:rotate;@keyframes rotate{from{transform:rotate(0);}to{transform:rotate(360deg);}}`,xi=({images:e,isPending:t=!1,onClickImage:n})=>{const{conversation:r}=oe(),o=e.length;if(o===0)return null;const s=Ml(o),a=!!n&&!t;return i.createElement(If,{$width:ee.BODY_MAX_WIDTH,$columns:s},e.map((l,c)=>{const{columnSpan:d}=kl({index:c,itemCount:o}),m=l.name||"",f=()=>{t||n==null||n(c)},g=l.type??"image/*",_=a?r.file.buttonLikePreview({name:m,mimeType:g,onActivate:f},c):r.file.preview({name:m,mimeType:g});return i.createElement(wf,{key:l.url,$clickable:a,$itemSpan:d,$isPending:t,..._.props},i.createElement(Tf,{src:l.url,alt:l.name||""}),t&&i.createElement(Mf,null),_.descriptionNode)}))},Tf=({src:e,alt:t})=>{const[n,r]=u.useState(!1),[o,s]=u.useState(!1);return i.createElement(i.Fragment,null,!n&&!o&&i.createElement(kf,null,i.createElement(at,{size:20},i.createElement(Q,{type:"spinner",color:"textLowEmphasis",size:20}))),o&&i.createElement(Rf,null,i.createElement(Q,{type:"photo",color:"textLowEmphasis",size:24})),!o&&i.createElement(Lf,{src:e,alt:t,$loaded:n,onLoad:()=>r(!0),onError:()=>s(!0)}))},If=p.default.div`display:grid;grid-template-columns:repeat(${({$columns:e})=>e},1fr);width:${({$width:e})=>e}px;gap:2px;border-radius:16px;overflow:hidden;`,wf=p.default.div`position:relative;width:100%;aspect-ratio:1;overflow:hidden;cursor:${e=>e.$clickable?"pointer":"default"};${J.light`
|
|
92
|
+
background-color: ${h.color.background100};
|
|
93
93
|
`}
|
|
94
94
|
${J.dark`
|
|
95
|
-
background-color: ${
|
|
95
|
+
background-color: ${h.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 ${h.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
|
+
`,Mf=p.default.div`position:absolute;top:0;left:0;width:100%;height:100%;background-color:${h.color.overlay.dark};pointer-events:none;`,Ti=p.default.div`display:flex;align-items:center;justify-content:center;`,kf=p.default(Ti)`position:absolute;inset:0;`,Rf=p.default(Ti)`position:absolute;inset:0;${J.light`
|
|
115
|
+
background-color: ${h.color.background200};
|
|
116
116
|
`}
|
|
117
117
|
${J.dark`
|
|
118
|
-
background-color: ${
|
|
118
|
+
background-color: ${h.color.background500};
|
|
119
119
|
`}
|
|
120
|
-
`,
|
|
120
|
+
`,Lf=p.default.img`position:absolute;inset:0;width:100%;height:100%;object-fit:cover;opacity:${({$loaded:e})=>e?1:0};transition:opacity 0.3s ease;`,Of=({files:e,children:t,onClickMedia:n,onClickMediaFiles:r})=>{const o=s=>{const a=e[s];a&&(r?r({files:e,index:s}):n&&n({url:a.url,type:a.type||"image/*"}))};return i.createElement(Nf,null,i.createElement(xi,{images:e,onClickImage:o}),t)},Nf=p.default.div`display:flex;flex-direction:column;align-items:flex-start;gap:${ee.GAP_GROUPED}px;`,Df="✱",Ii=e=>{const t=new RegExp(`(\`+)([^\`]+?)\\1|(${Df}+)`,"g");return e.replace(t,(n,r,o,s)=>r?n:s?`<span id=${bf} aria-label="masked-text">${s}</span>`:n)},$f=e=>e.replace(/\*\*(.*?)\*\*/g,"<b>$1</b>"),Oo=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)}}},Pf=u.lazy(async()=>({default:(await Promise.resolve().then(()=>require("./cjs/VvejebHE.cjs"))).MarkdownText})),No=typeof __SBA_USE_SYNTAX_HIGHLIGHT__>"u"||__SBA_USE_SYNTAX_HIGHLIGHT__?u.lazy(async()=>({default:(await Promise.resolve().then(()=>require("./cjs/DlvEEpWX.cjs"))).CodeBlock})):null;function Ff(e){var o,s;const t=e.maxBodyWidth??ee.BODY_MAX_WIDTH,n=u.useMemo(()=>ya(e.message,Ii),[e.message]),r={id:`${We}-text-body`,$maxWidth:t,$color:(o=e.customStyle)==null?void 0:o.bubbleContentColor,$bgColor:(s=e.customStyle)==null?void 0:s.bubbleBackgroundColor,$surface:e.surface??"bubble"};return n.length===0?e.children?i.createElement(Do,{...r},e.children):null:i.createElement(Do,{...r},n.map((a,l)=>a.type==="text"?i.createElement($o,{key:l,variant:"body3"},i.createElement(Mt,{fallback:a.value},i.createElement(Pf,{onClickImage:c=>{var d;return(d=e.onClickMedia)==null?void 0:d.call(e,{url:c,type:"image/*"})},onClickLink:e.onClickLink},a.value))):a.type==="code"?No?i.createElement(Mt,{key:l,fallback:i.createElement($o,{variant:"body3"},a.value)},i.createElement(No,{code:a.value,language:a.language})):i.createElement(Uf,{key:l},i.createElement("code",null,a.value)):null),e.children)}const Do=p.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})=>D.css`
|
|
121
121
|
color: ${t||e.colors.messageIncoming.text};
|
|
122
122
|
${r==="bubble"?D.css`background-color:${n||e.colors.messageIncoming.background};border-radius:12px;overflow:hidden;padding:12px 0;`:D.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
|
+
`,$o=p.default($)`align-items:flex-start;line-height:140%;white-space:pre-wrap;padding:0 12px;`,Uf=p.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 wi({id:e,src:t,size:n=56,onClick:r,style:o,...s}){return i.createElement(Bf,{id:e,tabIndex:r?0:void 0,onClick:r,$size:Ge(n),style:o,...s},t?i.createElement(Hf,{src:t,alt:""}):i.createElement(Q,{type:"user",size:n}))}const Bf=p.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:${h.themedColor.bg_100_500};&:focus{outline:none;}${Ae}`,Hf=p.default.img`object-fit:cover;width:100%;height:100%;position:absolute;`,Gf=({sender:e,isBotMessage:t})=>{const n=`${We}-sender-avatar`;return t&&!e.profileUrl?i.createElement(zf,{id:n},i.createElement(Q,{type:"delight",size:"100%"})):i.createElement(wi,{id:n,size:ee.AVATAR_SIZE,src:e.profileUrl})},zf=p.default.div`flex-shrink:0;width:${ee.AVATAR_SIZE}px;height:${ee.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;}}`,Vf=({sender:e})=>i.createElement(Yf,{id:`${We}-sender-name`,variant:"caption1",color:h.themedColor.textMidEmphasis},e.nickname),Yf=p.default($)`text-align:start;width:100%;box-sizing:border-box;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;padding-block:5px;padding-inline:0 7px;`,Wf=({createdAt:e})=>{const{stringSet:t,format:n}=se();return e?i.createElement($,{id:`${We}-sent-time`,variant:"caption4",color:h.themedColor.textLowEmphasis},n(e,t.DATE_FORMAT__MESSAGE_TIMESTAMP)):null},Mi="(prefers-reduced-motion: reduce)",qf=()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia(Mi).matches,ki=()=>{const[e,t]=u.useState(qf);return u.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const n=window.matchMedia(Mi);t(n.matches);const r=o=>{t(o.matches)};return typeof n.addEventListener=="function"?(n.addEventListener("change",r),()=>{n.removeEventListener("change",r)}):(n.addListener(r),()=>{n.removeListener(r)})},[]),e},Kf=({thinkingMessage:e,customStyle:t})=>{const n=ki();return e?i.createElement(Zf,{$prefersReducedMotion:n},i.createElement(Jf,null,e),!n&&i.createElement(Qf,null)):i.createElement(jf,{$bgColor:t==null?void 0:t.bubbleBackgroundColor},[0,1,2].map(r=>i.createElement(Xf,{key:r,$color:t==null?void 0:t.bubbleContentColor,$prefersReducedMotion:n})))},jf=p.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};`,Xf=p.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;}`,Zf=p.default.div.attrs({id:`${We}-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
|
+
`,Jf=p.default($).attrs({variant:"body3"})`
|
|
139
139
|
white-space: pre-wrap;
|
|
140
140
|
word-break: break-word;
|
|
141
|
-
color: ${
|
|
142
|
-
`,
|
|
143
|
-
`,
|
|
141
|
+
color: ${h.themedColor.textHighEmphasis};
|
|
142
|
+
`,Qf=p.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=Vr(e.colors.base.background,.5),n=Vr(e.colors.base.background,0);return`linear-gradient(90deg, ${n} 0%, ${t} 30%, ${t} 60%, ${n} 100%)`}};
|
|
143
|
+
`,eg=({extendedMessagePayload:e,onClickCTA:t=({url:n})=>br(n)})=>{const n=e==null?void 0:e.cta_button;if(!n)return null;const r=()=>t(n);return i.createElement(tg,{id:`${We}-ext-cta-button`,onClick:r},i.createElement(ng,{variant:"button"},n.label))},tg=p.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: ${
|
|
153
|
+
color: ${h.themedColor.textHighEmphasis};
|
|
154
|
+
background-color: ${h.color.background50};
|
|
155
155
|
${J.dark`
|
|
156
|
-
background-color: ${
|
|
156
|
+
background-color: ${h.color.ondark.textDisabled};
|
|
157
157
|
`}
|
|
158
158
|
|
|
159
159
|
${Ae}
|
|
160
|
-
`,
|
|
160
|
+
`,ng=p.default($)`overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,rg=e=>i.createElement(i.Fragment,null),og=({extendedMessagePayload:e,onClickCitation:t=n=>br(n.link)})=>{const{stringSet:n}=se(),{theme:r}=dr(),o=e==null?void 0:e.citations;return!o||o.length===0?null:i.createElement(sg,{id:`${We}-ext-citation`},i.createElement(ig,{variant:"caption1",color:r.colors.messageIncoming.text},n.CITATION_SOURCE_TITLE),i.createElement(ag,null,o.map((s,a)=>i.createElement(cg,{key:`${s.embedding_id}-${a}`,onClick:()=>t(s)},i.createElement(Q,{type:"source",size:16,color:r.colors.messageIncoming.text}),i.createElement(lg,{variant:"body3",color:r.colors.messageIncoming.text},s.title)))))},sg=p.default.div`display:flex;flex-direction:column;gap:8px;border-radius:8px;padding:8px 12px 6px;`,ig=p.default($)`opacity:0.5;`,ag=p.default.div`display:flex;flex-direction:column;gap:8px;`,lg=p.default($)`text-decoration:underline;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,cg=p.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
|
-
`,
|
|
175
|
+
`,ug=e=>i.createElement(i.Fragment,null),dg=({visible:e,onClose:t,children:n,"aria-label":r})=>i.createElement(nt,{portalContainerId:Ce.WINDOW,visible:e,onClose:t,"aria-label":r},i.createElement(hg,null,n)),mg=({onClick:e,destructive:t,icon:n,initialFocus:r,children:o})=>i.createElement(fg,{onClick:e,$destructive:t,"data-sb-initial-focus":r?"true":void 0},n&&i.createElement(gg,null,i.createElement(Q,{type:n,size:24,color:h.themedColor.primary})),o),Je=Object.assign(dg,{ActionItem:mg}),fg=p.default.button`all:unset;display:flex;align-items:center;gap:24px;width:100%;padding:12px 24px;cursor:pointer;color:${({$destructive:e})=>e?h.themedColor.error:h.themedColor.textHighEmphasis};${Ae}`,gg=p.default.div`display:flex;align-items:center;justify-content:center;flex-shrink:0;`,hg=p.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};`,Zn=e=>`${e}-filled`,pg=e=>e==="good"?be.AIAgentMessageFeedbackRating.GOOD:be.AIAgentMessageFeedbackRating.BAD,Ar=D.css`&:hover{opacity:0.8;}&:active{opacity:0.6;}`,Vt={good:{onlight:h.color.secondary.dark,ondark:h.color.secondary.light},bad:{onlight:h.color.error.dark,ondark:h.color.error.light}},_g={good:h.themedColor.secondary,bad:h.themedColor.error},Ri=e=>D.css`color:${Vt[e].onlight};border-color:${Vt[e].onlight};${J.dark`
|
|
176
176
|
color: ${Vt[e].ondark};
|
|
177
177
|
border-color: ${Vt[e].ondark};
|
|
178
178
|
`}
|
|
179
|
-
`,
|
|
180
|
-
outline: 2px solid ${
|
|
179
|
+
`,Eg=({visible:e,onClose:t,isEdit:n,initialRating:r,initialComment:o="",onSubmit:s,isCommentEnabled:a=!1})=>{const{stringSet:l}=se(),{conversation:c}=oe(),{rootElement:d}=ri(),m=st(d),[f,g]=u.useState(r),[_,v]=u.useState(o),[y,b]=u.useState(!1),E=u.useRef(!1),C=f??r??"good",S=c.feedback;u.useLayoutEffect(()=>{e?(g(r),v(o)):(g(void 0),v(""))},[e,r,o]),u.useEffect(()=>{if(!e)return;const I=O=>{const F=O;F.metaKey||F.altKey||F.ctrlKey||(E.current=!0)},M=()=>{E.current=!1,b(!1)};return m.addEventListener("keydown",I),m.addEventListener("pointerdown",M),()=>{m.removeEventListener("keydown",I),m.removeEventListener("pointerdown",M)}},[m,e]);const x=()=>{f&&(s({rating:f,comment:_.trim()||void 0}),t())},w=()=>{t()};if(!e)return null;const k={feedback:S.container()};return i.createElement(nt,{portalContainerId:Ce.WINDOW,visible:e,onClose:w,"aria-label":l.FEEDBACK_TITLE},i.createElement(bg,null,i.createElement(Cg,null,i.createElement($,{variant:"h2",color:h.themedColor.textHighEmphasis},l.FEEDBACK_TITLE)),i.createElement(vg,null,i.createElement(yg,{...k.feedback.props},["good","bad"].map(I=>{const M=f===I,O=I==="good"?l.FEEDBACK_GOOD:l.FEEDBACK_BAD,F=S.button(I,M);return i.createElement(u.Fragment,{key:I},i.createElement(Sg,{type:"button",$selected:M,$rating:I,...F.props,onClick:()=>g(I),"data-sb-initial-focus":I===C?"true":void 0},i.createElement(Q,{type:M?Zn(I):I,size:24,color:"currentColor"}),i.createElement($,{variant:"caption1",color:"currentColor"},O)),F.descriptionNode)}),k.feedback.descriptionNode),a&&i.createElement(Ag,null,i.createElement($,{variant:"caption3",color:h.themedColor.textHighEmphasis},l.FEEDBACK_COMMENT_LABEL),i.createElement(xg,{placeholder:l.FEEDBACK_COMMENT_PLACEHOLDER,value:_,onChange:I=>v(I.target.value),onFocus:()=>b(E.current),onBlur:()=>b(!1),maxLength:100,$focusVisible:y,"data-focus-visible":y?"true":"false"}))),i.createElement(Tg,null,i.createElement(Ig,{onClick:w},i.createElement($,{variant:"button",color:h.themedColor.textHighEmphasis},l.FEEDBACK_CANCEL)),i.createElement(wg,{onClick:x,disabled:!f},i.createElement($,{variant:"button"},n?l.FEEDBACK_SAVE:l.FEEDBACK_SUBMIT)))))},bg=p.default.div`width:280px;background-color:${({theme:e})=>e.colors.base.modalContentBackground};border-radius:12px;overflow:hidden;`,Cg=p.default.div`padding:24px;`,vg=p.default.div`padding-inline:24px;display:flex;flex-direction:column;gap:24px;`,yg=p.default.div`display:flex;gap:4px;`,Sg=p.default.button`width:114px;height:64px;border-radius:12px;border:1px solid ${h.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:${h.themedColor.textLowEmphasis};background-color:transparent;${({$selected:e,$rating:t})=>e&&Ri(t)}${Ar}`,Ag=p.default.label`display:flex;flex-direction:column;gap:6px;`,xg=p.default.textarea`font-family:inherit;font-size:12px;line-height:16px;border:1px solid ${h.themedColor.textDisabled};border-radius:4px;padding:6px 12px;color:${h.themedColor.textHighEmphasis};background-color:${h.themedColor.textLowEmphasisInverse};resize:none;field-sizing:content;min-height:28px;max-height:118px;overflow-y:auto;&::placeholder{color:${h.themedColor.textLowEmphasis};}&:focus{outline:none;}${({$focusVisible:e})=>e&&D.css`
|
|
180
|
+
outline: 2px solid ${h.themedColor.primary};
|
|
181
181
|
outline-offset: 2px;
|
|
182
182
|
`}
|
|
183
|
-
`,
|
|
184
|
-
border: 1px solid ${
|
|
183
|
+
`,Tg=p.default.div`padding-inline:24px;padding-block:16px;display:flex;justify-content:flex-end;gap:4px;`,Li=p.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;`,Ig=p.default(Li)`background-color:transparent;${Ar}`,wg=p.default(Li)`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};}`,Mg=({isBotMessage:e,isConversationClosed:t,isStreaming:n,isFeedbackEnabled:r,isFeedbackCommentEnabled:o,extendedMessagePayload:s,onFeedbackUpdate:a})=>{const{stringSet:l}=se(),{conversation:c}=oe(),[d,m]=u.useState(!1),[f,g]=u.useState(!1),[_,v]=u.useState(void 0),[y,b]=u.useState(""),E=u.useRef(null),C=u.useRef(null),S=u.useRef(null),x=u.useRef(!1),w=c.feedback,k=s==null?void 0:s.feedback,I=(k==null?void 0:k.rating)??"none";if(I!=="none"?!1:!!(n||!e||!r||(s==null?void 0:s.bot_message_type)!=="generated"||t))return null;const O=q=>{q&&we(()=>{const ce=q==="good"?E.current:C.current;ce==null||ce.focus()})},F=({restoreTrigger:q=!0}={})=>{g(!1),q&&O(S.current)},Y=q=>{I==="none"?(v(q),b(""),m(!0)):(S.current=q,g(!0))},z=()=>{a==null||a(null),F()},V=()=>{x.current=!0,F({restoreTrigger:!1}),v(k==null?void 0:k.rating),b((k==null?void 0:k.comment)??""),m(!0)},H=q=>{x.current=!1,a==null||a(q),m(!1),O(S.current)},W=()=>{m(!1),x.current&&(x.current=!1,g(!0))};return t&&I!=="none"?i.createElement(Po,{role:"presentation",$horizontal:!0},i.createElement(kg,null,i.createElement(Q,{type:Zn(I),size:12,color:_g[I]})),(k==null?void 0:k.comment)&&i.createElement(Fo,{variant:"caption2",style:{lineHeight:"16px"}},k.comment)):i.createElement(i.Fragment,null,i.createElement(Po,{role:"presentation"},i.createElement(Rg,{role:"presentation"},["good","bad"].map(q=>{const ce=I===q,_e=w.button(q,ce);return i.createElement(u.Fragment,{key:q},i.createElement(Lg,{$selected:ce,$rating:q,ref:q==="good"?E:C,..._e.props,onClick:()=>Y(q)},i.createElement(Q,{type:ce?Zn(q):q,size:14,color:"currentColor"})),_e.descriptionNode)})),I!=="none"&&(k==null?void 0:k.comment)&&i.createElement(Fo,{variant:"caption2"},k.comment)),i.createElement(Je,{visible:f,onClose:F,...w.optionsBottomSheet().props},i.createElement(Je.ActionItem,{onClick:V,initialFocus:!0},l.FEEDBACK_EDIT),i.createElement(Je.ActionItem,{onClick:z,destructive:!0},l.FEEDBACK_REMOVE)),i.createElement(Eg,{visible:d,onClose:W,isEdit:I!=="none",initialRating:_,initialComment:y,onSubmit:H,isCommentEnabled:o}))},Po=p.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:${ee.BODY_MAX_WIDTH}px;`,kg=p.default.div`padding:2px;flex-shrink:0;display:flex;align-items:center;`,Rg=p.default.div`display:flex;gap:2px;`,Lg=p.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:${h.themedColor.textMidEmphasis};border:1px solid ${h.color.background200};background-color:transparent;${J.dark`
|
|
184
|
+
border: 1px solid ${h.color.background400};
|
|
185
185
|
`}
|
|
186
186
|
|
|
187
|
-
${({$selected:e,$rating:t})=>e&&
|
|
187
|
+
${({$selected:e,$rating:t})=>e&&Ri(t)}
|
|
188
188
|
|
|
189
|
-
${
|
|
190
|
-
|
|
191
|
-
color: ${
|
|
189
|
+
${Ar}
|
|
190
|
+
`,Fo=p.default($)`color:${h.themedColor.textMidEmphasis};${J.dark`
|
|
191
|
+
color: ${h.themedColor.textHighEmphasis};
|
|
192
192
|
`}
|
|
193
|
-
`,
|
|
194
|
-
background-color: ${
|
|
193
|
+
`,xr=D.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;${Ae}&:disabled{cursor:not-allowed;}`,Uo=p.default.button`${xr};background-color:${h.themedColor.primary};color:${h.themedColor.textHighEmphasis};&:hover:not(:disabled){opacity:0.9;}`,Og=p.default.button`${xr};color:${h.themedColor.primary};${J.light`
|
|
194
|
+
background-color: ${h.color.background50};
|
|
195
195
|
`};
|
|
196
196
|
${J.dark`
|
|
197
|
-
background-color: ${
|
|
197
|
+
background-color: ${h.color.background700};
|
|
198
198
|
`};
|
|
199
199
|
|
|
200
200
|
&:hover:not(:disabled) {
|
|
201
201
|
opacity: 0.9;
|
|
202
202
|
}
|
|
203
|
-
`,
|
|
204
|
-
background-color: ${
|
|
203
|
+
`,Ng=p.default.button`${xr};background-color:transparent;color:${h.themedColor.textHighEmphasis};&:hover:not(:disabled){opacity:0.7;}`,Dg=e=>{switch(e){case"primary":return Uo;case"secondary":return Og;case"clear":return Ng;default:return Uo}},$g=p.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);}}`,Pg=({children:e,onClick:t,variant:n="primary",disabled:r=!1,loading:o=!1,className:s,...a})=>{const l=()=>{switch(n){case"primary":return h.themedColor.textHighEmphasisInverse;case"secondary":return h.themedColor.primary;case"clear":return h.themedColor.textHighEmphasis;default:return h.themedColor.textHighEmphasisInverse}},c=Dg(n);return i.createElement(c,{onClick:t,disabled:r||o,className:s,...a},o?i.createElement($g,null,i.createElement(Q,{type:"spinner",size:22,color:l()})):i.createElement($,{variant:"button",color:l()},e))},Fg=({children:e,className:t,style:n,id:r,role:o})=>i.createElement($,{variant:"caption4",color:h.themedColor.error,className:t,style:n,id:r,role:o},e),Ug=({id:e,children:t,className:n,style:r,required:o,"aria-hidden":s})=>{const{stringSet:a}=se();return i.createElement($,{id:e,variant:"caption3",color:h.themedColor.textMidEmphasis,className:n,style:r,"aria-hidden":s},t,!o&&i.createElement("span",{style:{color:h.themedColor.textLowEmphasis}},` (${a.OPTIONAL})`))},Bg=({value:e,onChange:t,placeholder:n,error:r=!1,submitted:o=!1,className:s,disabled:a=!1,max:l,...c})=>{const d=f=>{const _=f.target.value.replace(/[^0-9.-]/g,""),v=_.split("."),b=v.length>1?v[0]+"."+v.slice(1).join("").replace(/\./g,""):_;if(f.target.value=b,b===""||b==="-")t==null||t(null);else{const E=Number(b);if(!isNaN(E)){if(l!==void 0&&E>l)return;t==null||t(E)}}},m=e==null?"":String(e);return i.createElement(Yg,{type:"text",value:m,onChange:d,placeholder:n,className:s,disabled:a||o,inputMode:"decimal",$error:r,$submitted:o,...c})},Hg=D.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;${Ae}&::placeholder{color:${h.themedColor.textLowEmphasis};}&::-webkit-inner-spin-button,&::-webkit-outer-spin-button{-webkit-appearance:none;margin:0;}`,Gg=D.css`color:${h.themedColor.textHighEmphasis};border:1px solid transparent;cursor:not-allowed;${J.light`
|
|
204
|
+
background-color: ${h.color.ondark.textMidEmphasis};
|
|
205
205
|
`}
|
|
206
206
|
${J.dark`
|
|
207
|
-
background-color: ${
|
|
207
|
+
background-color: ${h.color.onlight.textLowEmphasis};
|
|
208
208
|
`}
|
|
209
209
|
|
|
210
210
|
&::placeholder {
|
|
211
|
-
color: ${
|
|
211
|
+
color: ${h.themedColor.textLowEmphasis};
|
|
212
212
|
}
|
|
213
|
-
`,
|
|
214
|
-
background-color: ${
|
|
213
|
+
`,zg=D.css`border:1px solid ${h.themedColor.error};color:${h.themedColor.textHighEmphasis};${J.light`
|
|
214
|
+
background-color: ${h.color.background50};
|
|
215
215
|
`}
|
|
216
216
|
${J.dark`
|
|
217
|
-
background-color: ${
|
|
217
|
+
background-color: ${h.color.onlight.textLowEmphasis};
|
|
218
218
|
`}
|
|
219
|
-
|
|
220
|
-
background-color: ${
|
|
219
|
+
`,Vg=D.css`border:1px solid ${h.themedColor.textDisabled};color:${h.themedColor.textHighEmphasis};${J.light`
|
|
220
|
+
background-color: ${h.color.background50};
|
|
221
221
|
`}
|
|
222
222
|
${J.dark`
|
|
223
|
-
background-color: ${
|
|
223
|
+
background-color: ${h.color.onlight.textLowEmphasis};
|
|
224
224
|
`}
|
|
225
225
|
|
|
226
226
|
&:focus {
|
|
227
|
-
border-color: ${
|
|
227
|
+
border-color: ${h.themedColor.primary};
|
|
228
228
|
}
|
|
229
|
-
`,
|
|
229
|
+
`,Yg=p.default.input`${Hg}${({$error:e,$submitted:t})=>t?Gg:e?zg:Vg}`,Wg=e=>{if(e.multiple){const{value:t=[],onChange:n,maxSelect:r,submitted:o=!1}=e;return{selectedValues:t,handleOptionClick:a=>{if(o)return;if(t.includes(a)){const c=t.filter(d=>d!==a);n==null||n(c)}else{if(r&&t.length>=r)return;const c=[...t,a];n==null||n(c)}}}}else{const{value:t,onChange:n,submitted:r=!1}=e;return{selectedValues:t?[t]:[],handleOptionClick:s=>{r||t!==s&&(n==null||n(s))}}}},Oi=e=>{const{options:t,submitted:n=!1,error:r=!1,className:o,groupLabel:s}=e,{conversation:a}=oe(),l=e.multiple===!0,{selectedValues:c,handleOptionClick:d}=Wg(e),m=t.some(f=>c.includes(f.value));return i.createElement(Kg,{className:o,...l?void 0:a.form.singleSelectGroup(s).props},t.map((f,g)=>{const _=c.includes(f.value),v=s?`${s}, ${f.label}`:f.label;return i.createElement(th,{key:f.value,type:"button",$active:_,$submitted:n,$error:r,...(l?a.form.multiSelectOption(v,_,n):a.form.singleSelectOption(v,_,n,g,t.length,m,y=>{const b=t[y];b&&d(b.value)})).props,disabled:n,onClick:()=>d(f.value)},i.createElement($,{variant:"caption1",color:qg(_,n)},f.label))}))},qg=(e,t)=>t?e?h.themedColor.textHighEmphasis:h.themedColor.textDisabled:e?h.themedColor.primary:h.themedColor.textMidEmphasis,Kg=p.default.div`display:flex;flex-wrap:wrap;gap:4px 2px;`,jg=D.css`display:inline-flex;align-items:center;padding:8px 12px;border-radius:15px;transition:all 0.2s ease;`,Xg=D.css`cursor:default;background-color:${h.color.ondark.textMidEmphasis};color:${h.themedColor.textHighEmphasis};${J.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
|
+
`,Zg=D.css`cursor:default;${J.light`
|
|
235
|
+
background-color: ${h.color.ondark.textMidEmphasis};
|
|
236
|
+
color: ${h.themedColor.textDisabled};
|
|
237
237
|
`}
|
|
238
238
|
${J.dark`
|
|
239
|
-
background-color: ${
|
|
240
|
-
border: 1px solid ${
|
|
241
|
-
color: ${
|
|
239
|
+
background-color: ${h.color.onlight.textLowEmphasis};
|
|
240
|
+
border: 1px solid ${h.color.onlight.textLowEmphasis};
|
|
241
|
+
color: ${h.themedColor.textDisabled};
|
|
242
242
|
`}
|
|
243
|
-
`,
|
|
244
|
-
background-color: ${
|
|
245
|
-
color: ${
|
|
243
|
+
`,Jg=D.css`cursor:pointer;border:1px solid ${h.themedColor.primary};${J.light`
|
|
244
|
+
background-color: ${h.color.background50};
|
|
245
|
+
color: ${h.themedColor.primary};
|
|
246
246
|
`}
|
|
247
247
|
${J.dark`
|
|
248
|
-
background-color: ${
|
|
249
|
-
color: ${
|
|
248
|
+
background-color: ${h.color.onlight.textLowEmphasis};
|
|
249
|
+
color: ${h.themedColor.primary};
|
|
250
250
|
`}
|
|
251
|
-
`,
|
|
252
|
-
background-color: ${
|
|
253
|
-
color: ${
|
|
251
|
+
`,Qg=D.css`cursor:pointer;border:1px solid ${h.themedColor.textDisabled};${J.light`
|
|
252
|
+
background-color: ${h.color.background50};
|
|
253
|
+
color: ${h.themedColor.textMidEmphasis};
|
|
254
254
|
`}
|
|
255
255
|
${J.dark`
|
|
256
|
-
background-color: ${
|
|
257
|
-
color: ${
|
|
256
|
+
background-color: ${h.color.onlight.textLowEmphasis};
|
|
257
|
+
color: ${h.themedColor.textMidEmphasis};
|
|
258
258
|
`}
|
|
259
|
-
`,
|
|
260
|
-
${r} ${
|
|
259
|
+
`,eh=D.css`border-color:${h.themedColor.error}!important;`,th=p.default.button`${jg}${({$active:e,$submitted:t,$error:n})=>{if(t)return e?Xg:Zg;const r=e?Jg:Qg;return n?D.css`
|
|
260
|
+
${r} ${eh}
|
|
261
261
|
`:r}}
|
|
262
|
-
`,
|
|
263
|
-
background-color: ${
|
|
262
|
+
`,nh=e=>i.createElement(Oi,{...e,multiple:!1}),rh=e=>i.createElement(Oi,{...e,multiple:!0}),oh=p.default.div`width:100%;height:1px;background-color:${h.themedColor.textDisabled};`,sh=({className:e})=>i.createElement(oh,{className:e}),ih=({id:e,value:t="",onChange:n,placeholder:r,variant:o="single-line",error:s=!1,submitted:a=!1,className:l,disabled:c=!1,maxLength:d,...m})=>{const g={id:e,value:t,onChange:_=>{const v=_.target.value;d&&v.length>d||n==null||n(v)},placeholder:r,className:l,disabled:c||a,maxLength:d,$error:s,$submitted:a,...m};return o==="multi-line"?i.createElement(lh,{...g}):i.createElement(ah,{...g})},Ni=D.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;${Ae}&::placeholder{color:${h.themedColor.textLowEmphasis};}`,Di=D.css`color:${h.themedColor.textHighEmphasis};border:1px solid transparent;cursor:not-allowed;${J.light`
|
|
263
|
+
background-color: ${h.color.ondark.textMidEmphasis};
|
|
264
264
|
`}
|
|
265
265
|
${J.dark`
|
|
266
|
-
background-color: ${
|
|
266
|
+
background-color: ${h.color.onlight.textLowEmphasis};
|
|
267
267
|
`}
|
|
268
268
|
|
|
269
269
|
&::placeholder {
|
|
270
|
-
color: ${
|
|
270
|
+
color: ${h.themedColor.textLowEmphasis};
|
|
271
271
|
}
|
|
272
|
-
|
|
273
|
-
background-color: ${
|
|
272
|
+
`,$i=D.css`border:1px solid ${h.themedColor.error};color:${h.themedColor.textHighEmphasis};${J.light`
|
|
273
|
+
background-color: ${h.color.background50};
|
|
274
274
|
`}
|
|
275
275
|
${J.dark`
|
|
276
|
-
background-color: ${
|
|
276
|
+
background-color: ${h.color.onlight.textLowEmphasis};
|
|
277
277
|
`}
|
|
278
|
-
`,
|
|
279
|
-
background-color: ${
|
|
278
|
+
`,Pi=D.css`border:1px solid ${h.themedColor.textDisabled};color:${h.themedColor.textHighEmphasis};${J.light`
|
|
279
|
+
background-color: ${h.color.background50};
|
|
280
280
|
`}
|
|
281
281
|
${J.dark`
|
|
282
|
-
background-color: ${
|
|
282
|
+
background-color: ${h.color.onlight.textLowEmphasis};
|
|
283
283
|
`}
|
|
284
284
|
|
|
285
285
|
&:focus {
|
|
286
|
-
border-color: ${
|
|
286
|
+
border-color: ${h.themedColor.primary};
|
|
287
287
|
}
|
|
288
|
-
`,
|
|
288
|
+
`,ah=p.default.input`${Ni};height:36px;${({$error:e,$submitted:t})=>t?Di:e?$i:Pi}`,lh=p.default.textarea`${Ni};height:96px;resize:none;font-family:inherit;${({$error:e,$submitted:t})=>t?Di:e?$i:Pi}`,ch=({children:e,className:t,style:n})=>i.createElement($,{variant:"button",color:h.themedColor.textHighEmphasis,className:t,style:n},e),Te={Title:ch,Label:Ug,ErrorLabel:Fg,Separator:sh,Button:Pg,TextInput:ih,NumberInput:Bg,SingleSelect:nh,MultiSelect:rh},uh=1,dh=new Set(["text","number","single-select","multi-select"]),mh=typeof __SBA_USE_FORM__>"u"||__SBA_USE_FORM__,fh=e=>{var E;if(!mh)return null;const t=(E=e.extendedMessagePayload)==null?void 0:E.form;if(!t)throw new Error("Form is not provided");const{stringSet:n}=se(),{conversation:r}=oe(),[o,s]=u.useState({submitting:!1,canceling:!1}),[a,l]=u.useState({visible:!1}),{state:c,fields:d,submit:m,cancel:f,updateFieldValue:g}=Gc(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:C=>{var S;return(S=e.onSubmitForm)==null?void 0:S.call(e,{key:t.key,data:C})},onCancel:()=>{var C;return(C=e.onCancelForm)==null?void 0:C.call(e,{key:t.key})}}),_=c==="submitted",v=async()=>{s(C=>({...C,submitting:!0}));try{await m()}catch(C){l({visible:!0,description:C instanceof Error?C.message:n.TRY_AGAIN})}finally{s(C=>({...C,submitting:!1}))}},y=async()=>{s(C=>({...C,canceling:!0}));try{await f()}catch(C){l({visible:!0,description:C instanceof Error?C.message:n.TRY_AGAIN})}finally{s(C=>({...C,canceling:!1}))}},b=u.useMemo(()=>{const C=()=>t.version>uh,S=()=>t.fields.some(x=>!dh.has(x.type));return C()||S()?{visible:!1,cancelable:!0,reason:n.FORM_NOT_SUPPORTED}:c==="draft"&&(e.isHandedOff||e.isConversationClosed)?{visible:!1,cancelable:!1,reason:n.FORM_UNAVAILABLE}:{visible:!0,cancelable:!0,reason:""}},[t.version,t.fields,c,e.isHandedOff,e.isConversationClosed]);return c==="canceled"?null:b.visible?i.createElement(u.Fragment,null,i.createElement(Bo,{$maxWidth:e.maxBodyWidth??ee.BODY_MAX_WIDTH},i.createElement(Te.Title,null,t.title),i.createElement(gh,null,d.map(C=>i.createElement(hh,{key:C.key},i.createElement(Te.Label,{style:{marginBottom:"6px"},required:C.required},C.label),C.type==="text"&&i.createElement(Te.TextInput,{value:C.value||"",placeholder:C.placeholder,onChange:S=>g(C.key,S),disabled:_,error:!!C.error,submitted:_,variant:C.layout==="multiline"?"multi-line":"single-line",maxLength:C.maxLength,...r.form.textInput(C.label,C.required??!1,_).props}),C.type==="number"&&i.createElement(Te.NumberInput,{value:C.value||null,placeholder:C.placeholder,onChange:S=>g(C.key,S),disabled:_,error:!!C.error,submitted:_,max:C.max,...r.form.numberInput(C.label,C.required??!1,_).props}),C.type==="single-select"&&i.createElement(Te.SingleSelect,{options:C.options.map(S=>({label:S,value:S})),value:C.value||"",onChange:S=>g(C.key,S),submitted:_,groupLabel:C.label}),C.type==="multi-select"&&i.createElement(Te.MultiSelect,{options:C.options.map(S=>({label:S,value:S})),value:C.value||[],onChange:S=>g(C.key,S),submitted:_,maxSelect:C.maxSelect,groupLabel:C.label}),C.error&&i.createElement(Te.ErrorLabel,{style:{marginTop:"4px"}},C.error)))),i.createElement(Te.Separator,null),i.createElement(ph,null,i.createElement(Te.Button,{variant:_?"clear":"primary",...r.form.button(_?n.SUBMITTED:n.BUTTON__SUBMIT).props,onClick:v,disabled:_||o.canceling,loading:o.submitting},_?n.SUBMITTED:n.BUTTON__SUBMIT),c!=="submitted"&&i.createElement(Te.Button,{variant:"secondary",...r.form.button(n.BUTTON__CANCEL).props,onClick:y,disabled:o.submitting,loading:o.canceling},n.BUTTON__CANCEL))),i.createElement(hn,{...a,onClose:()=>l({visible:!1,title:""})})):i.createElement(Bo,{$maxWidth:e.maxBodyWidth??ee.BODY_MAX_WIDTH},i.createElement($,{variant:"body3"},b.reason),b.cancelable&&i.createElement(Te.Button,{variant:"primary",...r.form.button(n.BUTTON__CANCEL).props,onClick:y,loading:o.canceling},n.BUTTON__CANCEL))},Bo=p.default.div`display:flex;flex-direction:column;gap:12px;border-radius:12px;overflow:hidden;max-width:${({$maxWidth:e})=>e}px;${({theme:e})=>D.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
|
+
`,gh=p.default.div`display:flex;flex-direction:column;gap:12px;`,hh=p.default.div`display:flex;flex-direction:column;`,ph=p.default.div`display:flex;flex-direction:column;gap:8px;`,_h=e=>i.createElement(i.Fragment,null),Ho=typeof __SBA_USE_MESSAGE_TEMPLATE__>"u"||__SBA_USE_MESSAGE_TEMPLATE__?u.lazy(()=>Promise.resolve().then(()=>require("./cjs/BjKg30ip.cjs")).then(e=>({default:e.MessageTemplateWrapper}))):null,Eh=e=>Ho?i.createElement(Mt,{errorFallback:e.messageTemplateErrorFallback,loadingFallback:e.messageTemplateLoadingFallback},i.createElement(Ho,{...e})):null,bh=({extendedMessagePayload:e,onClickSuggestedReply:t,suggestedRepliesDirection:n="vertical"})=>{const{conversation:r}=oe(),[o,s]=u.useState(!1),{suggestedReplies:a}=r,l=(e==null?void 0:e.suggested_replies)??[];if(l.length===0||o)return null;const c=d=>{t&&(t({reply:d}),s(!0))};return i.createElement(Ch,{id:`${We}-ext-suggested-replies`,role:"presentation",$type:n},l.map((d,m)=>{const f=a.item(d,m);return i.createElement(u.Fragment,{key:m},i.createElement(vh,{$type:n,...f.props,onClick:()=>c(d)},i.createElement(yh,{variant:"body3"},d)),f.descriptionNode)}))},Ch=p.default.div`margin:16px 0;padding:0 ${ee.HORIZONTAL_PADDING}px;position:relative;display:flex;align-self:stretch;gap:8px;${({$type:e})=>e==="vertical"?Sh:Ah};`,vh=p.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: ${h.color.primary.main};
|
|
306
|
+
border: 1px solid ${h.color.primary.main};
|
|
307
|
+
background-color: ${h.themedColor.bg_50_600};
|
|
308
308
|
|
|
309
309
|
&:hover {
|
|
310
|
-
background-color: ${
|
|
310
|
+
background-color: ${h.themedColor.bg_100_500};
|
|
311
311
|
}
|
|
312
312
|
|
|
313
313
|
${Ae}
|
|
314
314
|
|
|
315
|
-
${({$type:e,theme:t})=>D.css`${e==="vertical"?
|
|
316
|
-
`,
|
|
315
|
+
${({$type:e,theme:t})=>D.css`${e==="vertical"?xh:Th};&:active{background-color:${t.colors.base.primary};color:${t.colors.base.primaryContrastContent};}`}
|
|
316
|
+
`,yh=p.default($)`color:inherit;`,Sh=D.css`flex-direction:column;align-items:flex-end;`,Ah=D.css`flex-direction:row;overflow-x:scroll;-ms-overflow-style:none;scrollbar-width:none;&::-webkit-scrollbar{display:none;}`,xh=D.css`max-width:calc(100% - 70px);white-space:pre-wrap;`,Th=D.css`white-space:nowrap;`,Ih=e=>{const{components:t}=tt.useContext(),{stringSet:n}=se(),r=ms(e)?i.createElement(t.TextMessageBody,{...e}):null;if(e.messageType==="user")return r;if(e.messageType==="file"){const o=e.file;return o.type.startsWith("image")||o.type.startsWith("video")?i.createElement(t.MediaMessageBody,{...e},r):i.createElement(t.FileMessageBody,{...e},r)}return e.messageType==="multipleFiles"?i.createElement(t.MultipleFilesMessageBody,{...e},r):i.createElement(t.TextMessageBody,{...e,message:n.UNKNOWN__UNKNOWN_MESSAGE_TYPE})},wh=e=>i.createElement(Fi,{...e,testerMode:!1}),tt=Be({template:wh,components:{SenderName:Vf,SenderAvatar:Gf,SentTime:Wf,MessageBody:Ih,TextMessageBody:Ff,MediaMessageBody:Cf,FileMessageBody:_f,MultipleFilesMessageBody:Of,TypingIndicator:Kf,SuggestedReplies:bh,MessageTemplate:Eh,CustomMessageTemplate:ug,Challenge:rg,CTAButton:eg,Citation:og,Form:fh,Feedback:Mg,MessageLogs:_h}}),Fi=e=>{var C,S,x,w,k,I,M,O;const{components:t}=tt.useContext(),{streamText:n,isAnimating:r}=nu({text:e.message,enabled:e.isStreaming,markdownImageRenderMode:e.markdownImageRenderMode,markdownLinkRenderMode:e.markdownLinkRenderMode,onAnimationStart:e.onStreamAnimationStart,onAnimationProgress:e.onStreamAnimationProgress,onAnimationComplete:e.onStreamAnimationComplete}),o={...e,message:n,extendedMessagePayload:r?{}:e.extendedMessagePayload},s=!!o.isTyping,a=o.testerMode,l=!!o.isSenderAvatarVisible,c=!!((C=o.extendedMessagePayload)!=null&&C.form)&&!((S=o.extendedMessagePayload)!=null&&S.form.canceled_at),d=!!((x=o.extendedMessagePayload)!=null&&x.message_template),m=!!((w=o.extendedMessagePayload)!=null&&w.challenge),f=!!((k=o.extendedMessagePayload)!=null&&k.cta_button),g=!!((I=o.extendedMessagePayload)!=null&&I.citations)&&o.extendedMessagePayload.citations.length>0,_=!!o.createdAt,v=f||g,y=o.groupType==="top"||o.groupType==="single",b=o.groupType==="bottom"||o.groupType==="single",E=a||!l?0:ee.AVATAR_SIZE;return i.createElement(Mh,{$marginBottom:s?0:un(o.groupType)},y&&i.createElement(Lh,null,!a&&l&&i.createElement(t.SenderAvatar,{...o}),i.createElement(t.SenderName,{...o})),i.createElement(Nh,null,i.createElement(Nn,{$extraStartPadding:E},s?i.createElement(t.TypingIndicator,{...o}):v?i.createElement(kh,{$maxWidth:o.maxBodyWidth??ee.BODY_MAX_WIDTH},i.createElement(t.MessageBody,{...o,surface:"plain"}),f&&i.createElement(Rh,{$marginTop:12,$paddingInline:12},i.createElement(t.CTAButton,{...o})),g&&i.createElement(t.Citation,{...o})):i.createElement(t.MessageBody,{...o})),d&&i.createElement(Go,{$startPadding:0,$endPadding:0},i.createElement(t.MessageTemplate,{...o,messageTemplateErrorFallback:o.messageTemplateErrorFallback??i.createElement(Nn,{$extraStartPadding:E},i.createElement(t.MessageBody,{...o,messageType:"user",message:((O=(M=o.extendedMessagePayload)==null?void 0:M.message_template)==null?void 0:O.fallback_message)??"Cannot read this template."})),messageTemplateLoadingFallback:o.messageTemplateLoadingFallback??i.createElement(Nn,{$extraStartPadding:E},i.createElement(t.TypingIndicator,{...o}))})),i.createElement(t.CustomMessageTemplate,{...o}),m&&i.createElement(t.Challenge,{...o}),c&&i.createElement(Go,{$extraStartPadding:E},i.createElement(t.Form,{...o}))),i.createElement(t.MessageLogs,{...o}),b&&_&&i.createElement(Oh,{$extraStartPadding:E+8},i.createElement(t.SentTime,{...o})),i.createElement(u.Fragment,null,!s&&i.createElement(Dt,{$extraStartPadding:E+8},i.createElement(t.Feedback,{...o})),o.suggestedRepliesVisible&&i.createElement(t.SuggestedReplies,{...o})))},Mh=p.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
|
+
`,Dt=p.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=ee.HORIZONTAL_PADDING,$endPadding:t=ee.HORIZONTAL_PADDING,$extraStartPadding:n=0})=>`
|
|
326
326
|
padding-inline: ${e+n}px ${t}px;
|
|
327
327
|
`}
|
|
328
|
-
`,
|
|
328
|
+
`,kh=p.default.div.attrs({role:"presentation"})`
|
|
329
329
|
display: flex;
|
|
330
330
|
flex-direction: column;
|
|
331
331
|
min-width: 0;
|
|
@@ -334,68 +334,68 @@
|
|
|
334
334
|
overflow: hidden;
|
|
335
335
|
padding: 12px 0;
|
|
336
336
|
${({theme:e})=>D.css`color:${e.colors.messageIncoming.text};background-color:${e.colors.messageIncoming.background};`}
|
|
337
|
-
`,
|
|
337
|
+
`,Rh=p.default.div.attrs({role:"presentation"})`
|
|
338
338
|
display: flex;
|
|
339
339
|
flex-direction: column;
|
|
340
340
|
min-width: 0;
|
|
341
341
|
${({$marginTop:e=0,$paddingInline:t=0})=>D.css`margin-top:${e}px;padding-inline:${t}px;`}
|
|
342
|
-
`,
|
|
342
|
+
`,Lh=p.default(Dt)`display:flex;flex-direction:row;align-items:center;gap:8px;`,Nn=p.default(Dt)`display:flex;`,Oh=p.default(Dt)`margin-top:${ee.BODY_TIME_GAP}px;display:flex;align-items:flex-start;justify-content:flex-start;`,Go=p.default(Dt).attrs({role:"presentation"})`
|
|
343
343
|
display: flex;
|
|
344
|
-
${({$startPadding:e=
|
|
344
|
+
${({$startPadding:e=ee.HORIZONTAL_PADDING,$endPadding:t=ee.HORIZONTAL_PADDING,$extraStartPadding:n=0})=>`
|
|
345
345
|
padding-inline: ${e+n}px ${t}px;
|
|
346
346
|
`}
|
|
347
|
-
`,
|
|
347
|
+
`,Nh=p.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: ${ee.GAP_GROUPED}px;
|
|
353
|
+
`;function Dh({file:e,children:t,onClickFile:n,sendingStatus:r}){const o=(()=>{if(!(!n||r==="failed"))return()=>n==null?void 0:n(e)})();return i.createElement($h,null,i.createElement(Sr,{name:e.name,mimeType:e.type,type:nr(e.name,e.type),onClick:o}),t)}const $h=p.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${ee.GAP_GROUPED}px;`;function Ph({sendingStatus:e,file:t,metadata:n,onClickMedia:r,onClickMediaFiles:o,children:s}){const{conversation:a}=oe(),{aspectRatio:l,localFile:c}=n,[d]=u.useState(()=>c instanceof Blob?URL.createObjectURL(c):t.url),[m,f]=u.useState(!1),g=(()=>{if(e!=="failed"){if(o)return()=>o({files:[{url:d,type:t.type,name:t.name}],index:0});if(r)return()=>r({...t,url:d})}})(),_=g?a.file.buttonLikePreview({name:t.name,mimeType:t.type,onActivate:g}):a.file.preview({name:t.name,mimeType:t.type}),v={..._.props,$ratio:l,$clickable:!!g};return i.createElement(Fh,null,i.createElement(Uh,{...v},!m&&i.createElement(at,{size:26},i.createElement(Q,{type:"spinner",color:"textLowEmphasis",size:26})),i.createElement(Bh,{$loaded:m,src:d,alt:"image-message",onLoad:()=>f(!0)}),_.descriptionNode),s)}const Fh=p.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${ee.GAP_GROUPED}px;`,Uh=p.default.div`width:${ee.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;${J.light`
|
|
354
|
+
background-color: ${h.color.background100};
|
|
355
355
|
`}
|
|
356
356
|
${J.dark`
|
|
357
|
-
background-color: ${
|
|
357
|
+
background-color: ${h.color.background400};
|
|
358
358
|
`}
|
|
359
|
-
`,
|
|
359
|
+
`,Bh=p.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;`,Hh=({sendingStatus:e,files:t,metadata:n,onClickMedia:r,onClickMediaFiles:o,children:s})=>{const[a]=u.useState(()=>n.localFiles?n.localFiles.filter(m=>m instanceof Blob).map(m=>({...m,url:URL.createObjectURL(m)})):t),l=e==="pending",c=e==="failed",d=m=>{if(c||l)return;const f=a[m];f&&(o?o({files:a,index:m}):r&&r({url:f.url,type:f.type||"image/*"}))};return i.createElement(Gh,null,i.createElement(xi,{images:a,isPending:l,onClickImage:d}),s)},Gh=p.default.div`display:flex;flex-direction:column;align-items:flex-end;gap:${ee.GAP_GROUPED}px;`;function zh(e){var n,r;const t=u.useMemo(()=>{const o=$f(Ii(e.message));return ls.default.sanitize(o)},[e.message]);return i.createElement(Vh,{$maxWidth:e.maxBodyWidth??ee.BODY_MAX_WIDTH,$color:(n=e.customStyle)==null?void 0:n.bubbleContentColor,$bgColor:(r=e.customStyle)==null?void 0:r.bubbleBackgroundColor},i.createElement(Yh,{variant:"body3",dangerouslySetInnerHTML:{__html:t}}))}const Vh=p.default.div`display:flex;flex-direction:column;border-radius:12px;overflow:hidden;max-width:${({$maxWidth:e})=>e}px;${({theme:e,$color:t,$bgColor:n})=>D.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
|
-
`,qg=p.default(Ri)``,Kg=p.default(Ri)`margin-top:${ne.BODY_TIME_GAP}px;`,jg=e=>e.messageType!=="admin"?null:i.createElement(Xg,null,i.createElement(P,{variant:"caption2",color:g.themedColor.textMidEmphasis},Zg(is.default.sanitize(e.message),e.onClickLink))),Xg=p.default.div`text-align:center;text-wrap:pretty;word-break:break-word;padding-inline:${ne.HORIZONTAL_PADDING}px;a{text-decoration:underline;color:inherit;}`,Zg=(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(h=>!!h);if(!l.length){n.push(r);break}const c=l.reduce((h,_)=>_.match.index<h.match.index?_:h),{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:gr,onClick:h=>{h.preventDefault();const _=d[2];_&&(t==null||t({url:_}))}},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]}},Jg=({direction:e,currentIndex:t,totalCount:n})=>n<=0?t:e==="next"?(t+1)%n:(t-1+n)%n,Li=({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 h;(h=a.current[f])==null||h.focus()})},m=f=>{const h=e[f];!h||n||(s==null||s(h.value),d(f))};return{radioGroupProps:f=>({role:"radiogroup","aria-label":f,...r&&o?{"aria-invalid":!0,"aria-errormessage":o}:{}}),getRadioProps:f=>({ref:h=>{a.current[f]=h},tabIndex:n?-1:f===c?0:-1,describedBy:r&&o?o:void 0,onArrowNavigate:h=>{m(Jg({direction:h,currentIndex:f,totalCount:e.length}))}})}},Qg=e=>{switch(e.key){case"ArrowDown":case"ArrowRight":return"next";case"ArrowUp":case"ArrowLeft":return"previous";default:return}},ep=({event:e,onClick:t,onArrowNavigate:n})=>{if(tp(e))return;const r=Qg(e);if(r){e.preventDefault(),n==null||n(r);return}e.key!=="Enter"&&e.key!==" "||(e.preventDefault(),t==null||t())},tp=e=>e.repeat||e.currentTarget.getAttribute("aria-disabled")==="true",Ar=u.forwardRef(({onClick:e,checked:t,label:n,disabled:r,tabIndex:o=0,labelVariant:s="caption2",describedBy:a,onArrowNavigate:l},c)=>{const d=t?g.themedColor.primary:r?g.themedColor.textDisabled:g.themedColor.textLowEmphasis,m=t?g.themedColor.textHighEmphasis:r?g.themedColor.textLowEmphasis:g.themedColor.textHighEmphasis;return i.createElement(op,{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=>ep({event:f,onClick:e,onArrowNavigate:l})},i.createElement(np,{"aria-hidden":"true"},i.createElement(Q,{size:20,type:t?"radio-on":"radio-off",color:d})),i.createElement(rp,{"aria-hidden":"true",variant:s,color:m},n))});Ar.displayName="Radio";const np=p.default.div`width:20px;height:20px;`,rp=p.default(P)`line-height:20px;word-break:break-word;`,op=p.default.div`display:flex;align-items:flex-start;justify-content:flex-start;gap:2px;${Ae}&[aria-disabled='false']{cursor:pointer;}`,sp=({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=Li({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(ip,null,i.createElement(Te.Label,{required:l.required,"aria-hidden":!0},l.question),i.createElement(ap,{...a.radioGroupProps(l.question)},s.map((m,f)=>i.createElement(Ar,{key:m.label,checked:r===m.value,label:m.label,disabled:t,...a.getRadioProps(f),onClick:()=>o==null?void 0:o(m.value)}))))},ip=p.default.div`display:flex;flex-direction:column;gap:8px;`,ap=p.default.div`display:flex;flex-direction:column;gap:8px;`,lp=({followUpItem:e,submitted:t,value:n="",onChange:r,hasError:o})=>{const{stringSet:s}=se(),{conversation:a}=oe(),l=u.useId(),c=e.response_type!=="free_text",d=e.response_type==="single_choice"?e.options.map(f=>({label:f,value:f})):[],m=Li({options:d,value:n,disabled:t,hasError:o,errorId:l,onChange:r});return i.createElement(cp,null,i.createElement(Te.Label,{required:e.required,"aria-hidden":c},e.question),e.response_type==="free_text"&&i.createElement(Te.TextInput,{variant:"multi-line",disabled:t,submitted:t,maxLength:100,value:n,onChange:f=>r(f),error:o,...a.form.textInput(s.A11Y_CSAT_TEXT_INPUT_LABEL,e.required??!1,t).props,"aria-invalid":o,"aria-errormessage":o?l:void 0}),e.response_type==="single_choice"&&i.createElement(up,{...m.radioGroupProps(e.question)},d.map((f,h)=>i.createElement(Ar,{key:f.value,checked:n===f.value,label:f.label,disabled:t,...m.getRadioProps(h),onClick:()=>r==null?void 0:r(f.value),labelVariant:"body3"}))),o&&i.createElement(dp,{role:"alert",id:l},s.FORM_VALIDATION_REQUIRED))},cp=p.default.div`display:flex;flex-direction:column;gap:8px;`,up=p.default.div`display:flex;flex-direction:column;gap:8px;`,dp=p.default(Te.ErrorLabel)``,mp=({value:e,selected:t})=>i.createElement(fp,{$selected:t,"aria-hidden":"true"},hp[e-1]),fp=p.default.div`user-select:none;-webkit-user-drag:none;width:40px;height:40px;aspect-ratio:1;opacity:${({$selected:e})=>e?1:.38};`,hp=[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)"}))))],gp=({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(_p,null,i.createElement(P,{variant:"caption3",color:g.themedColor.textMidEmphasis,"aria-hidden":"true"},e.csat_question),i.createElement(Ep,{...a.props},a.descriptionNode,e.csat_scores.map(({label:l,image_url:c},d)=>{const m=d+1,f=n===m,h=e.csat_scores.length,_=s.csat.scoreItem({score:m,label:l,selected:f,disabled:t,currentIndex:d,totalCount:h,hasSelection:!o,onChange:r});return i.createElement(bp,{key:d,type:"button",..._.props},i.createElement(pp,{value:m,selected:o||f,src:c}),!!l&&i.createElement(P,{"aria-hidden":"true",color:f?g.themedColor.textHighEmphasis:g.themedColor.textLowEmphasis,variant:"caption3"},l),_.descriptionNode)})))},pp=({value:e,src:t,selected:n})=>{const[r,o]=u.useState(!1),s=r?i.createElement(mp,{value:e,selected:n}):i.createElement(vp,{$selected:n,alt:"","aria-hidden":"true",src:t,onError:()=>o(!0)});return i.createElement(Cp,null,s)},_p=p.default.div`display:flex;flex-direction:column;gap:8px;`,Ep=p.default.div`display:flex;justify-content:space-between;align-self:center;width:100%;max-width:400px;gap:16px;`,bp=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:${g.themedColor.textHighEmphasis};}`,Cp=p.default.div`button:not(:disabled):hover &{border-radius:4px;cursor:pointer;background-color:${g.color.background200};${J.dark`
|
|
369
|
-
background-color: ${
|
|
366
|
+
`,Yh=p.default($)`align-items:flex-start;line-height:140%;white-space:pre-wrap;padding:0 12px;`,Wh=({sendingStatus:e})=>{const t=D.useTheme();switch(e){case"pending":return i.createElement(qh,{size:16},i.createElement(Q,{type:"spinner",color:t.colors.messageOutgoing.background,size:16}));case"failed":return i.createElement("div",{style:{marginBottom:2}},i.createElement(Q,{type:"error",color:h.themedColor.error,size:16}));case"scheduled":case"canceled":return null;default:return i.createElement("div",{style:{marginBottom:2}},i.createElement(Q,{type:"done",color:h.themedColor.secondary,size:16}))}},qh=p.default(at)`margin-bottom:2px;width:16px;height:16px;`,Kh=({createdAt:e})=>{const{stringSet:t,format:n}=se();return e?i.createElement($,{variant:"caption4",color:h.themedColor.textLowEmphasis},n(e,t.DATE_FORMAT__MESSAGE_TIMESTAMP)):null},jh=e=>{const{components:t}=$t.useContext(),{stringSet:n}=se(),r=()=>{const a=ms(e)?i.createElement(t.TextMessageBody,{...e}):null;return e.messageType==="user"?a:e.messageType==="file"?e.file.type.startsWith("image")?i.createElement(t.MediaMessageBody,{...e},a):i.createElement(t.FileMessageBody,{...e},a):e.messageType==="multipleFiles"?i.createElement(t.MultipleFilesMessageBody,{...e},a):i.createElement(t.TextMessageBody,{...e,message:n.UNKNOWN__UNKNOWN_MESSAGE_TYPE})},o=e.sendingStatus==="failed"&&e.onClickFailedMessage,s=o?At({onActivate:()=>{var a;return(a=e.onClickFailedMessage)==null?void 0:a.call(e)}}):{};return i.createElement("div",{...s,style:{display:"contents",cursor:o?"pointer":"default"}},r())},Xh=e=>{const{components:t}=$t.useContext(),n=e.sendingStatus==="succeeded",r=e.groupType==="bottom"||e.groupType==="single";return i.createElement(Zh,{$marginBottom:un(e.groupType)},i.createElement(Jh,null,i.createElement(t.MessageBody,{...e})),r&&i.createElement(Qh,{$extraEndPadding:8},n?i.createElement(t.SentTime,{...e}):i.createElement(t.SendingStatus,{...e})))},$t=Be({template:Xh,components:{SendingStatus:Wh,SentTime:Kh,MessageBody:jh,TextMessageBody:zh,MediaMessageBody:Ph,FileMessageBody:Dh,MultipleFilesMessageBody:Hh}}),Zh=p.default.div`display:flex;flex:1;flex-direction:column;align-items:flex-end;margin-bottom:${({$marginBottom:e})=>`${e}px`};
|
|
367
|
+
`,Ui=p.default.div`display:flex;align-self:stretch;justify-content:flex-end;${({$startPadding:e=ee.HORIZONTAL_PADDING,$endPadding:t=ee.HORIZONTAL_PADDING,$extraEndPadding:n=0})=>`padding-inline: ${e}px ${t+n}px;`};
|
|
368
|
+
`,Jh=p.default(Ui)``,Qh=p.default(Ui)`margin-top:${ee.BODY_TIME_GAP}px;`,ep=e=>e.messageType!=="admin"?null:i.createElement(tp,null,i.createElement($,{variant:"caption2",color:h.themedColor.textMidEmphasis},np(ls.default.sanitize(e.message),e.onClickLink))),tp=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;}`,np=(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,_)=>_.match.index<g.match.index?_: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:pr,onClick:g=>{g.preventDefault();const _=d[2];_&&(t==null||t({url:_}))}},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]}},rp=({direction:e,currentIndex:t,totalCount:n})=>n<=0?t:e==="next"?(t+1)%n:(t-1+n)%n,Bi=({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(rp({direction:g,currentIndex:f,totalCount:e.length}))}})}},op=e=>{switch(e.key){case"ArrowDown":case"ArrowRight":return"next";case"ArrowUp":case"ArrowLeft":return"previous";default:return}},sp=({event:e,onClick:t,onArrowNavigate:n})=>{if(ip(e))return;const r=op(e);if(r){e.preventDefault(),n==null||n(r);return}e.key!=="Enter"&&e.key!==" "||(e.preventDefault(),t==null||t())},ip=e=>e.repeat||e.currentTarget.getAttribute("aria-disabled")==="true",Tr=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(cp,{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=>sp({event:f,onClick:e,onArrowNavigate:l})},i.createElement(ap,{"aria-hidden":"true"},i.createElement(Q,{size:20,type:t?"radio-on":"radio-off",color:d})),i.createElement(lp,{"aria-hidden":"true",variant:s,color:m},n))});Tr.displayName="Radio";const ap=p.default.div`width:20px;height:20px;`,lp=p.default($)`line-height:20px;word-break:break-word;`,cp=p.default.div`display:flex;align-items:flex-start;justify-content:flex-start;gap:2px;${Ae}&[aria-disabled='false']{cursor:pointer;}`,up=({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=Bi({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(dp,null,i.createElement(Te.Label,{required:l.required,"aria-hidden":!0},l.question),i.createElement(mp,{...a.radioGroupProps(l.question)},s.map((m,f)=>i.createElement(Tr,{key:m.label,checked:r===m.value,label:m.label,disabled:t,...a.getRadioProps(f),onClick:()=>o==null?void 0:o(m.value)}))))},dp=p.default.div`display:flex;flex-direction:column;gap:8px;`,mp=p.default.div`display:flex;flex-direction:column;gap:8px;`,fp=({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=Bi({options:m,value:n,disabled:t,hasError:o,errorId:l,onChange:r});return i.createElement(gp,null,i.createElement(Te.Label,{id:c,required:e.required,"aria-hidden":d},e.question),e.response_type==="free_text"&&i.createElement(Te.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(hp,{...f.radioGroupProps(e.question)},m.map((g,_)=>i.createElement(Tr,{key:g.value,checked:n===g.value,label:g.label,disabled:t,...f.getRadioProps(_),onClick:()=>r==null?void 0:r(g.value),labelVariant:"body3"}))),o&&i.createElement(pp,{role:"alert",id:l},s.FORM_VALIDATION_REQUIRED))},gp=p.default.div`display:flex;flex-direction:column;gap:8px;`,hp=p.default.div`display:flex;flex-direction:column;gap:8px;`,pp=p.default(Te.ErrorLabel)``,_p=({value:e,selected:t})=>i.createElement(Ep,{$selected:t,"aria-hidden":"true"},bp[e-1]),Ep=p.default.div`user-select:none;-webkit-user-drag:none;width:40px;height:40px;aspect-ratio:1;opacity:${({$selected:e})=>e?1:.38};`,bp=[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)"}))))],Cp=({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(yp,null,i.createElement($,{variant:"caption3",color:h.themedColor.textMidEmphasis,"aria-hidden":"true"},e.csat_question),i.createElement(Sp,{...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,_=s.csat.scoreItem({score:m,label:l,selected:f,disabled:t,currentIndex:d,totalCount:g,hasSelection:!o,onChange:r});return i.createElement(Ap,{key:d,type:"button",..._.props},i.createElement(vp,{value:m,selected:o||f,src:c}),!!l&&i.createElement($,{"aria-hidden":"true",color:f?h.themedColor.textHighEmphasis:h.themedColor.textLowEmphasis,variant:"caption3"},l),_.descriptionNode)})))},vp=({value:e,src:t,selected:n})=>{const[r,o]=u.useState(!1),s=r?i.createElement(_p,{value:e,selected:n}):i.createElement(Tp,{$selected:n,alt:"","aria-hidden":"true",src:t,onError:()=>o(!0)});return i.createElement(xp,null,s)},yp=p.default.div`display:flex;flex-direction:column;gap:8px;`,Sp=p.default.div`display:flex;justify-content:space-between;align-self:center;width:100%;max-width:400px;gap:16px;`,Ap=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};}`,xp=p.default.div`button:not(:disabled):hover &{border-radius:4px;cursor:pointer;background-color:${h.color.background200};${J.dark`
|
|
369
|
+
background-color: ${h.color.background500};
|
|
370
370
|
`}
|
|
371
371
|
}
|
|
372
|
-
`,
|
|
373
|
-
background-color: ${
|
|
372
|
+
`,Tp=p.default.img`user-select:none;-webkit-user-drag:none;width:40px;height:40px;aspect-ratio:1;opacity:${({$selected:e})=>e?1:.38};`,Ip=({csatPayload:e})=>i.createElement($,{variant:"button",color:h.themedColor.textHighEmphasis},e.title),Dn=({csatPayload:e,type:t,renderSubmitButton:n,initialCsat:r,initialCsatReason:o,initialIsResolved:s})=>{const{params:a,setParams:l,error:c,setError:d,followUpItem:m,state:f,validateParams:g,itemProps:_}=Zc({csatPayload:e,type:t,initialCsat:r,initialCsatReason:o,initialIsResolved:s});return i.createElement(i.Fragment,null,i.createElement(wp,null,i.createElement(Ip,{..._}),t===Ye.AI_AGENT_CSAT_5_WITH_CRE&&i.createElement(up,{..._,defaultValue:s,value:a.isResolved,onChange:v=>l({isResolved:v})}),i.createElement(Cp,{..._,value:a.csat,onChange:v=>l({csat:v})}),m&&i.createElement(fp,{..._,followUpItem:m,value:a.csatReason,onChange:v=>{l({csatReason:v}),d({followUpItem:!1})},hasError:c.followUpItem})),f!=="unsubmittable"&&i.createElement(i.Fragment,null,i.createElement(Te.Separator,null),n({state:f,params:a,validateParams:g})))},wp=p.default.div`display:flex;flex-direction:column;gap:12px;`,Mp=e=>{const{stringSet:t}=se();return el(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})},kp=()=>{const{stringSet:e}=se();return i.createElement($,{variant:"body2",color:h.themedColor.textMidEmphasis,style:{textAlign:"center"}},e.CSAT_SUBMISSION_EXPIRED)},Rp=({onMount:e,children:t})=>(u.useEffect(()=>{e&&we(e)},[]),t),Lp=e=>{const{conversation:t}=oe(),{announceError:n,announceStatus:r}=Ke();if(e.messageType!=="admin.csat")throw new Error("Invalid message type");const{extendedMessagePayload:o,onSubmitCSAT:s,onScrollToBottom:a}=e,{csat:l,csatReason:c,csatExpireAt:d,isResolvedWhenDeterminedByUser:m}=e,f=dn(),g=Mp(o==null?void 0:o.csat),_=u.useRef(null),v=u.useRef(null),[y,b]=u.useState(!1),E=u.useRef(!1),C=u.useCallback(()=>{we(()=>{var I;return(I=v.current)==null?void 0:I.focus()})},[]),{isExpiredNow:S,isRenderableCSAT:x}=jc({csat:l,csatExpireAt:d,csatPayload:g,announceStatus:r,onSubmittedAnnounced:C,isSubmitInFlight:y});if(!x||!g)return null;const w=()=>{var M;const I=(M=_.current)==null?void 0:M.querySelector('[aria-invalid="true"]');return I?I.getAttribute("role")==="radiogroup"?I.querySelector('[role="radio"]'):I:null},k=g.type===Ye.AI_AGENT_CSAT_5||g.type===Ye.AI_AGENT_CSAT_5_WITH_CRE||g.type===Ye.HELPDESK_CSAT_5?Dn:()=>null;return i.createElement(Op,{ref:_},!l&&S?i.createElement(kp,null):i.createElement(k,{csatPayload:g,type:g.type,initialCsat:l,initialCsatReason:c,initialIsResolved:m,renderSubmitButton:({state:I,params:M,validateParams:O})=>I==="submitted"?i.createElement(Dp,{ref:v,role:"status","aria-live":"polite","aria-atomic":"true","aria-label":g.csat_submitted_label,tabIndex:-1},i.createElement($,{variant:"button","aria-hidden":"true"},g.csat_submitted_label)):i.createElement(Rp,{onMount:a},i.createElement(Np,{type:"button",...t.csat.submitButton(g.csat_submit_label).props,onClick:async()=>{if(E.current)return;const F=Cs(d);if(!F&&O()){E.current=!0,b(!0);try{await s(M)}catch(Y){throw E.current=!1,b(!1),Y}}else f(),F||we(()=>{n({type:"csatFormError"},w())})}},i.createElement($,{variant:"button"},g.csat_submit_label)))}))},Op=p.default.div`display:flex;flex-direction:column;background-color:${({theme:e})=>e.colors.csat.background};border-radius:16px;gap:16px;padding:16px;`,Np=p.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;${Ae}&:hover{background-color:${h.color.primary.dark};}`,Dp=p.default.div`width:100%;box-sizing:border-box;color:${h.themedColor.textHighEmphasis};background-color:${h.color.background200};border-radius:6px;padding:10px 20px;display:flex;align-items:center;justify-content:center;text-align:center;word-break:break-word;${J.dark`
|
|
373
|
+
background-color: ${h.color.onlight.textDisabled};
|
|
374
374
|
`}
|
|
375
|
-
|
|
375
|
+
`,$p=e=>{const{components:t}=_n.useContext(),n=e.messageType==="admin"?i.createElement(t.AdminMessage,{...e}):e.messageType==="admin.csat"?i.createElement(t.CSATMessage,{...e}):null;return i.createElement(Pp,{$marginBottom:un(e.groupType)},n)},_n=Be({template:$p,components:{AdminMessage:ep,CSATMessage:Lp}}),Pp=p.default.div`padding-inline:${ee.HORIZONTAL_PADDING}px;margin-bottom:${({$marginBottom:e})=>e}px;`,zo={file:"attach",snippet:"snippet",site:"website",sb_sprinklr:"sprinklr",sb_salesforce:"salesforce",sb_confluence:"confluence",sb_zendesk:"zendesk",sb_desk:"snippet"},Hi=({actionbook:e,functionCalls:t,groundedness:n,agentMessageTemplates:r,onClickActionbook:o,onClickFunctionCall:s,onClickFunctionCallDetail:a,onClickGroundedness:l,onClickAgentMessageTemplate:c,topContent:d,bottomContent:m,renderCustomGroundednessIcon:f=_=>_.default,style:g={}})=>{const{iconColor:_="#000000",textColor:v="#000000",highlightColor:y=wt.DEFAULT_PRIMARY}=g;return i.createElement(Vo,null,d,e&&i.createElement(Vo,null,i.createElement(ln,null,i.createElement(Wt,null,i.createElement(Q,{size:16,type:"actionbook",color:_})),i.createElement(Yt,{$clickable:!!o,$highlightColor:y,variant:"body2",color:v,onClick:()=>o==null?void 0:o(e),maxTextLines:1},e.name))),t==null?void 0:t.map(b=>i.createElement($n,{key:b.key},i.createElement(Wt,null,i.createElement(Q,{size:16,type:"function",color:_})),i.createElement(ln,null,i.createElement(Yt,{$clickable:!!s,$highlightColor:y,variant:"body2",color:v,onClick:()=>s==null?void 0:s(b),maxTextLines:1},b.name),a&&i.createElement(Up,{role:"button",onClick:()=>a==null?void 0:a(b)},i.createElement($,{variant:"body2",color:y},"View details"),i.createElement(Q,{type:"chevron-right",size:16,color:y}))))),n==null?void 0:n.map(b=>i.createElement($n,{key:b.id},i.createElement(Wt,null,f({default:i.createElement(Q,{size:16,type:zo[b.source_type]??zo.snippet,color:_}),sourceType:b.source_type})),i.createElement(Yt,{$clickable:!!l,$highlightColor:y,variant:"body2",color:v,onClick:()=>l==null?void 0:l(b),maxTextLines:1},b.preview_title))),r==null?void 0:r.map(b=>i.createElement($n,{key:b.key},i.createElement(Wt,null,i.createElement(Q,{size:16,type:"template",color:_})),i.createElement(Yt,{$clickable:!!c,$highlightColor:y,variant:"body2",color:v,onClick:()=>c==null?void 0:c(b),maxTextLines:1},b.name))),m)},Fp=p.default($)`font-weight:400;`,Yt=p.default(Fp)`${({$clickable:e,$highlightColor:t})=>e&&D.css`
|
|
376
376
|
cursor: pointer;
|
|
377
377
|
text-decoration: underline;
|
|
378
378
|
&:hover {
|
|
379
379
|
color: ${t};
|
|
380
380
|
}
|
|
381
381
|
`}
|
|
382
|
-
`,Wt=p.default.div`display:flex;align-items:center;justify-content:center;flex-shrink:0;`,ln=p.default.div`display:flex;gap:8px;align-items:center;word-break:break-word;`,Np=p.default(ln)`cursor:pointer;gap:4px;`,Dn=p.default(ln)`flex-direction:row;align-items:center;`,Go=p.default.div`display:flex;gap:4px;flex-direction:column;align-items:flex-start;`,Ni=u.createContext(null);function Dp({testerType:e,origin:t,children:n}){return i.createElement(Ni.Provider,{value:{testerType:e,isActionbookTester:e==="actionbook",origin:t}},e&&i.createElement($p,null),n)}const pt=()=>{const e=u.useContext(Ni);if(!e)throw new Error("_UNSAFE_INTERNAL_DashboardTesterProvider not found");return e},$p=()=>{const{isActionbookTester:e}=pt();return i.createElement(tt.Template,{template:e?Pp:void 0},i.createElement(tt.MessageLogs,{component:Fp}))},Pp=e=>i.createElement(ki,{...e,testerMode:!0,maxBodyWidth:ne.WIDE_BODY_MAX_WIDTH}),Fp=({extendedMessagePayload:e={}})=>{const{handlers:t}=me(),{manual:n,groundedness:r,function_calls:o,agent_message_templates:s,is_thinking:a}=e;return a||!n&&!(r!=null&&r.length)&&!(o!=null&&o.length)&&!(s!=null&&s.length)?i.createElement(i.Fragment,null):i.createElement(Bp,null,i.createElement(Up,{$width:4}),i.createElement(Oi,{actionbook:n,functionCalls:o,groundedness:r,agentMessageTemplates:s,onClickFunctionCallDetail:t==null?void 0:t.onFunctionCallDetailClick,style:{iconColor:g.themedColor.textHighEmphasis,textColor:g.themedColor.textHighEmphasis,barColor:g.themedColor.textDisabled},bottomContent:i.createElement(Hp,{variant:"caption2",color:g.themedColor.textLowEmphasis},"Only visible in the tester")}))},Bp=p.default.div`display:flex;gap:16px;margin:16px ${ne.HORIZONTAL_PADDING}px 0;align-self:stretch;`,Up=p.default.div`width:${({$width:e})=>e}px;background-color:${g.themedColor.textDisabled};border-radius:100px;flex-shrink:0;`,Hp=p.default(P)`margin-top:5px;`,zo=40,Vo=.9,Gp="[data-message-listitem]",zp='input, textarea, select, [role="textbox"], [contenteditable="true"]',Vp=({event:e,list:t,isMessageAnchor:n})=>{switch(e.key){case"PageDown":return t.clientHeight*Vo;case"PageUp":return t.clientHeight*-Vo;case"ArrowDown":return n?zo:void 0;case"ArrowUp":return n?zo*-1:void 0;default:return}},Yp=({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(zp))return;const s=o===r||o.matches(Gp),a=Vp({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]),Wp="[data-message-listitem]",qp=e=>Math.min(Math.max(0,e),1),Kp=e=>{const n=e.getRootNode().activeElement,r=n==null?void 0:n.closest(Wp),o=n===e||n===r;return!n||!e.contains(n)?null:o?e:n},jp=({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})},Xp=({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),h=u.useRef(null),_=u.useRef(null);u.useLayoutEffect(()=>{t.current&&(t.current.scrollTop=t.current.scrollHeight)},e),u.useLayoutEffect(()=>{const b=t.current;b&&(c.current==="top"&&(b.scrollTop=b.scrollHeight-m.current,jp({list:b,focusRestoreTarget:f.current}),f.current=null),c.current==="bottom"&&(b.scrollTop=d.current),c.current=void 0)},[t,r]);const y=u.useCallback(async b=>{const E=t.current;if(!E||(a==null||a(b),m.current=E.scrollHeight-E.scrollTop,d.current=E.scrollTop,l.current))return;const A=E.clientHeight*qp(n);if(E.scrollTop<=A){l.current=!0,c.current="top",f.current=Kp(E),await s(),l.current=!1;return}if(E.scrollHeight-E.scrollTop-E.clientHeight<=A){l.current=!0,c.current="bottom",await o(),l.current=!1;return}c.current=void 0},[t,n,o,s,a]),C=u.useCallback(b=>{const E=t.current;if(!E)return;const A=_.current;if(A!=null){if(A===E.scrollTop){_.current=null;return}_.current=null}const x=h.current;if(x!=null&&x===E.scrollTop){h.current=null,_.current=E.scrollTop,y(b);return}h.current=null,y(b)},[y,t]),v=u.useCallback(b=>{const E=t.current;E&&(h.current=b,_.current=null,E.scrollTop=b,E.dispatchEvent(new Event("scroll",{bubbles:!0})))},[t]);return u.useLayoutEffect(()=>()=>{h.current=null,_.current=null},[]),{handleScroll:C,syncScrollPosition:v}},Zp=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:h,overlayArea:_,onLoadPrev:y,onLoadNext:C,loadThreshold:v=.05,onScroll:b=he,depsForResetScrollPositionToBottom:E,stackDirection:A="top",bottomSpacerHeight:x=0,"aria-label":k}=t,R=u.useRef(null),I=u.useCallback(V=>{R.current=V,n&&(typeof n=="function"?n(V):n.current=V)},[n]),{handleScroll:w,syncScrollPosition:O}=Xp({depsForResetScrollPositionToBottom:E,listRef:R,loadThreshold:v,messagesLength:r.length,onLoadNext:C,onLoadPrev:y,onScroll:b}),$=Yp({listRef:R,syncScrollPosition:O});return l?i.createElement(i.Fragment,null,c):s?i.createElement(i.Fragment,null,a):i.createElement(Jp,{id:"infinite-list-container"},i.createElement(Qp,{id:"infinite-list-inner",ref:I,onScroll:w,onKeyDown:$,role:"list","aria-label":k,tabIndex:0},A==="bottom"&&i.createElement("div",{style:{flexGrow:1}}),f,d?m:r.map((V,H)=>o({message:V,index:H})),h,x>0&&i.createElement("div",{style:{minHeight:x}})),i.createElement(e_,{id:"infinite-list-overlay-container"},i.createElement(t_,{id:"infinite-list-overlay"},_)))}),Jp=p.default.div`display:flex;position:relative;flex:1;overflow:hidden;`,Qp=p.default.div`display:flex;flex:1;flex-direction:column;overflow-x:hidden;overflow-y:auto;overscroll-behavior:contain;scrollbar-color:${g.themedColor.textLowEmphasis}transparent;&::-webkit-scrollbar-thumb:hover{background-color:transparent;}`,e_=p.default.div`position:absolute;top:0;bottom:0;left:0;right:0;pointer-events:none;`,t_=p.default.div`pointer-events:auto;`,je=({as:e,type:t,size:n=16,color:r,disabled:o,children:s,...a})=>{const l=o?g.themedColor.textDisabled:g.themedColor.textHighEmphasis;return i.createElement(n_,{as:e,disabled:o,...a},i.createElement(Q,{type:t,size:n,color:r??l}),s)},n_=p.default.button`all:unset;padding:4px;cursor:pointer;display:flex;align-items:center;justify-content:center;${Ae}&:disabled{cursor:not-allowed;}`,r_=({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}=me(),f=e.length,h=e[o],_=m.conversation.fileViewer.downloadEnabled,y=f>1,C=(h==null?void 0:h.type)||"",v=He(C),b=cn(C),E=!Om(C);u.useEffect(()=>{r&&(s(t),l(!1))},[r,t]);const A=u.useCallback(()=>{o>0&&(s(k=>k-1),l(!1))},[o]),x=u.useCallback(()=>{o<f-1&&(s(k=>k+1),l(!1))},[o,f]);return u.useEffect(()=>{if(!r)return;const k=R=>{R.key==="ArrowLeft"?A():R.key==="ArrowRight"&&x()};return window.addEventListener("keydown",k),()=>window.removeEventListener("keydown",k)},[r,A,x]),!r||!h?null:i.createElement(nt,{onClose:n,visible:r,portalContainerId:Ce.MODAL_ROOT,"aria-label":(h==null?void 0:h.name)||c.IMAGE_VIEWER__DEFAULT_TITLE},i.createElement(o_,null,i.createElement(s_,null,i.createElement(i_,null,i.createElement(a_,null,i.createElement(P,{variant:"button",maxTextLines:1,color:g.color.ondark.textHighEmphasis},h.name||c.IMAGE_VIEWER__DEFAULT_TITLE),h.timestamp&&i.createElement(P,{variant:"caption2",color:g.color.ondark.textHighEmphasis},d(new Date(h.timestamp),"h:mm a")))),i.createElement(l_,{type:"close",size:18,color:g.color.ondark.textHighEmphasis,"aria-label":c.A11Y_IMAGE_VIEWER_CLOSE,onClick:n})),i.createElement(c_,{onClick:k=>k.currentTarget===k.target&&n()},y&&i.createElement(Yo,{$position:"left",type:"chevron-right",size:22,color:g.color.ondark.textHighEmphasis,onClick:A,"aria-label":c.A11Y_IMAGE_VIEWER_PREVIOUS,disabled:o===0,$flipped:!0}),i.createElement(u_,null,v&&i.createElement(i.Fragment,null,!a&&i.createElement(d_,null,i.createElement(at,{size:32},i.createElement(Q,{type:"spinner",color:"textLowEmphasis",size:32}))),i.createElement(m_,{src:h.url,alt:h.name||"Image",$loaded:a,onLoad:()=>l(!0)})),b&&i.createElement(f_,{controls:!0},i.createElement("source",{src:h.url,type:C})),E&&i.createElement(h_,null,i.createElement(P,{variant:"h1",color:g.themedColor.textHighEmphasis},c.FILE_VIEWER__UNSUPPORT))),y&&i.createElement(Yo,{$position:"right",type:"chevron-right",size:22,color:g.color.ondark.textHighEmphasis,onClick:x,"aria-label":c.A11Y_IMAGE_VIEWER_NEXT,disabled:o===f-1})),i.createElement(g_,null,y&&i.createElement(P,{variant:"body2",color:g.color.ondark.textHighEmphasis},o+1,"/",f),_&&!E&&i.createElement(p_,{forwardedAs:"a",href:h.url,download:h.name||"file",type:"download",size:24,color:g.color.ondark.textHighEmphasis,"aria-label":c.A11Y_IMAGE_VIEWER_DOWNLOAD}))))},o_=p.default.div`position:fixed;inset:0;outline:none;display:flex;flex-direction:column;background-color:${g.themedColor.bg_50_600};`,s_=p.default.header`display:flex;align-items:center;justify-content:space-between;padding:12px 12px 12px 16px;min-height:56px;background-color:${g.color.overlay.dark};`,i_=p.default.div`flex:1;min-width:0;padding-right:8px;`,a_=p.default.div`display:flex;flex-direction:column;gap:2px;`,l_=p.default(je)`flex-shrink:0;width:28px;height:28px;border-radius:50%;`,_n=p.default.div`display:flex;align-items:center;justify-content:center;`,c_=p.default(_n)`flex:1;min-height:0;position:relative;`,u_=p.default(_n)`position:relative;max-width:100%;max-height:100%;`,d_=p.default(_n)`position:absolute;inset:0;`,m_=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;`,f_=p.default.video`max-width:100%;max-height:100%;object-fit:contain;`,h_=p.default(_n)`flex-direction:column;gap:16px;`,Yo=p.default(je)`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:${g.color.overlay.dark};&:disabled{opacity:0.3;}`,g_=p.default.footer`position:relative;display:flex;align-items:center;justify-content:center;padding:16px;min-height:56px;background-color:${g.color.overlay.dark};`,p_=p.default(je)`position:absolute;right:16px;top:50%;transform:translateY(-50%);padding:0;width:24px;height:24px;`,xr=({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,h=m?i.createElement(v_,{type:"button",onClick:a,$fullWidth:c!=="horizontal",$background:d==null?void 0:d.negativeBackground,$borderColor:d==null?void 0:d.negativeBorderColor},i.createElement(P,{variant:"button",color:(d==null?void 0:d.negativeText)??g.themedColor.textHighEmphasis},o)):null,_=f?i.createElement(y_,{type:"button",onClick:l,$fullWidth:c!=="horizontal",$background:d==null?void 0:d.positiveBackground,$borderColor:d==null?void 0:d.positiveBorderColor},i.createElement(P,{variant:"button",color:(d==null?void 0:d.positiveText)??g.themedColor.textHighEmphasisInverse},s)):null;return i.createElement(__,null,i.createElement(E_,null,i.createElement(P,{as:"div",id:t,variant:"h2",color:(d==null?void 0:d.titleColor)??g.themedColor.textHighEmphasis},e)),i.createElement(b_,null,i.createElement(P,{as:"div",id:r,variant:"body3",color:(d==null?void 0:d.descriptionColor)??g.themedColor.textMidEmphasis},n)),i.createElement(C_,{$buttonLayout:c},c==="horizontal"?i.createElement(i.Fragment,null,h,_):i.createElement(i.Fragment,null,_,h)))},__=p.default.div`display:flex;flex-direction:column;width:280px;border-radius:16px;overflow:hidden;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,E_=p.default.div`padding:24px 24px 16px;`,b_=p.default.div`padding-inline:24px;`,C_=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;`,v_=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;}`,y_=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??g.themedColor.textHighEmphasis};white-space:nowrap;overflow:hidden;text-overflow:ellipsis;&:hover{opacity:0.8;}`,qt=16,S_=({status:e})=>e===Zt.COMPLETED?i.createElement(Q,{type:"done-circle",size:qt,color:g.themedColor.textHighEmphasis}):e===Zt.CANCELED?i.createElement(Q,{type:"stop-circle",size:qt,color:g.themedColor.textLowEmphasis}):i.createElement(at,{size:qt},i.createElement(Q,{type:"spinner",size:qt,color:g.themedColor.textHighEmphasis})),Di=24,A_=8,x_=40,T_=({task:e,isFirst:t,isLast:n})=>i.createElement(I_,{role:"listitem"},i.createElement(w_,null,i.createElement(Wo,{$hidden:t}),i.createElement(M_,null,i.createElement(S_,{status:e.status})),i.createElement(Wo,{$hidden:n})),i.createElement(k_,null,i.createElement(P,{as:"div",variant:"body3",color:e.status===Zt.CANCELED?g.themedColor.textLowEmphasis:g.themedColor.textHighEmphasis},e.user_facing_title))),I_=p.default.div`display:flex;gap:4px;`,w_=p.default.div`display:flex;flex-direction:column;align-items:center;width:${Di}px;flex-shrink:0;`,Wo=p.default.div`width:1px;flex:1;transform:translateX(-25%);${({$hidden:e})=>e&&"visibility: hidden;"}background-image:repeating-linear-gradient( to bottom,${g.themedColor.textHighEmphasis}0 2px,transparent 2px 4px );`,M_=p.default.div`display:flex;height:${Di}px;align-items:center;justify-content:center;`,k_=p.default.div`display:flex;flex:1;align-items:center;box-sizing:border-box;min-width:0;min-height:${x_}px;padding-block:${A_}px;`,R_=({steward:e,onCancelSteward:t})=>{const{logger:n}=me(),[r,o]=u.useState(!1),[s,a]=u.useState(!1),l=!!e.cancellation_option,c=ha(e.status);return i.createElement(L_,{$marginBottom:un("single")},i.createElement(O_,null,i.createElement(N_,null,i.createElement(D_,null,i.createElement(P,{as:"div",variant:"caption1",color:g.themedColor.textHighEmphasis},e.title),!!e.description&&i.createElement(P,{as:"div",variant:"caption4",color:g.themedColor.textLowEmphasis},e.description)),l&&i.createElement(B_,{type:"button","aria-label":"Stop steward",disabled:s,onClick:()=>o(!0)},i.createElement(Q,{type:"stop",size:16,color:s?g.themedColor.textDisabled:g.themedColor.textHighEmphasis}))),i.createElement($_,null),e.tasks.length===0?c!==xt.IN_PROGRESS?null:i.createElement(F_,null,i.createElement(at,{size:16},i.createElement(Q,{type:"spinner",size:16,color:g.themedColor.textHighEmphasis}))):i.createElement(P_,{role:"list"},e.tasks.map((d,m)=>i.createElement(T_,{key:d.id,task:d,isFirst:m===0,isLast:m===e.tasks.length-1})))),r&&e.cancellation_option&&i.createElement(nt,{portalContainerId:Ce.WINDOW,visible:r,onClose:()=>o(!1)},i.createElement(xr,{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)}}})))},L_=p.default.div`display:flex;flex-direction:column;margin:0 ${ne.HORIZONTAL_PADDING}px;margin-bottom:${({$marginBottom:e})=>`${e}px`};
|
|
383
|
-
`,
|
|
384
|
-
background-color: ${
|
|
382
|
+
`,Wt=p.default.div`display:flex;align-items:center;justify-content:center;flex-shrink:0;`,ln=p.default.div`display:flex;gap:8px;align-items:center;word-break:break-word;`,Up=p.default(ln)`cursor:pointer;gap:4px;`,$n=p.default(ln)`flex-direction:row;align-items:center;`,Vo=p.default.div`display:flex;gap:4px;flex-direction:column;align-items:flex-start;`,Gi=u.createContext(null);function Bp({testerType:e,origin:t,children:n}){return i.createElement(Gi.Provider,{value:{testerType:e,isActionbookTester:e==="actionbook",origin:t}},e&&i.createElement(Hp,null),n)}const _t=()=>{const e=u.useContext(Gi);if(!e)throw new Error("_UNSAFE_INTERNAL_DashboardTesterProvider not found");return e},Hp=()=>{const{isActionbookTester:e}=_t();return i.createElement(tt.Template,{template:e?Gp:void 0},i.createElement(tt.MessageLogs,{component:zp}))},Gp=e=>i.createElement(Fi,{...e,testerMode:!0,maxBodyWidth:ee.WIDE_BODY_MAX_WIDTH}),zp=({extendedMessagePayload:e={}})=>{const{handlers:t}=me(),{manual:n,groundedness:r,function_calls:o,agent_message_templates:s,is_thinking:a}=e;return a||!n&&!(r!=null&&r.length)&&!(o!=null&&o.length)&&!(s!=null&&s.length)?i.createElement(i.Fragment,null):i.createElement(Vp,null,i.createElement(Yp,{$width:4}),i.createElement(Hi,{actionbook:n,functionCalls:o,groundedness:r,agentMessageTemplates:s,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")}))},Vp=p.default.div`display:flex;gap:16px;margin:6px ${ee.HORIZONTAL_PADDING}px 4px ${ee.HORIZONTAL_PADDING+ee.AVATAR_SIZE}px;align-self:stretch;`,Yp=p.default.div`width:${({$width:e})=>e}px;background-color:${h.themedColor.textDisabled};border-radius:100px;flex-shrink:0;`,Yo=40,Wo=.9,Wp="[data-message-listitem]",qp='input, textarea, select, [role="textbox"], [contenteditable="true"]',Kp=({event:e,list:t,isMessageAnchor:n})=>{switch(e.key){case"PageDown":return t.clientHeight*Wo;case"PageUp":return t.clientHeight*-Wo;case"ArrowDown":return n?Yo:void 0;case"ArrowUp":return n?Yo*-1:void 0;default:return}},jp=({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(Wp),a=Kp({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]),Xp="[data-message-listitem]",Zp=e=>Math.min(Math.max(0,e),1),Jp=e=>{const n=e.getRootNode().activeElement,r=n==null?void 0:n.closest(Xp),o=n===e||n===r;return!n||!e.contains(n)?null:o?e:n},Qp=({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})},e_=({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),_=u.useRef(null);u.useLayoutEffect(()=>{t.current&&(t.current.scrollTop=t.current.scrollHeight)},e),u.useLayoutEffect(()=>{const E=t.current;E&&(c.current==="top"&&(E.scrollTop=E.scrollHeight-m.current,Qp({list:E,focusRestoreTarget:f.current}),f.current=null),c.current==="bottom"&&(E.scrollTop=d.current),c.current=void 0)},[t,r]);const v=u.useCallback(async E=>{const C=t.current;if(!C||(a==null||a(E),m.current=C.scrollHeight-C.scrollTop,d.current=C.scrollTop,l.current))return;const S=C.clientHeight*Zp(n);if(C.scrollTop<=S){l.current=!0,c.current="top",f.current=Jp(C),await s(),l.current=!1;return}if(C.scrollHeight-C.scrollTop-C.clientHeight<=S){l.current=!0,c.current="bottom",await o(),l.current=!1;return}c.current=void 0},[t,n,o,s,a]),y=u.useCallback(E=>{const C=t.current;if(!C)return;const S=_.current;if(S!=null){if(S===C.scrollTop){_.current=null;return}_.current=null}const x=g.current;if(x!=null&&x===C.scrollTop){g.current=null,_.current=C.scrollTop,v(E);return}g.current=null,v(E)},[v,t]),b=u.useCallback(E=>{const C=t.current;C&&(g.current=E,_.current=null,C.scrollTop=E,C.dispatchEvent(new Event("scroll",{bubbles:!0})))},[t]);return u.useLayoutEffect(()=>()=>{g.current=null,_.current=null},[]),{handleScroll:y,syncScrollPosition:b}},t_=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:_,onLoadPrev:v,onLoadNext:y,loadThreshold:b=.05,onScroll:E=ge,depsForResetScrollPositionToBottom:C,stackDirection:S="top",bottomSpacerHeight:x=0,"aria-label":w}=t,k=u.useRef(null),I=u.useCallback(Y=>{k.current=Y,n&&(typeof n=="function"?n(Y):n.current=Y)},[n]),{handleScroll:M,syncScrollPosition:O}=e_({depsForResetScrollPositionToBottom:C,listRef:k,loadThreshold:b,messagesLength:r.length,onLoadNext:y,onLoadPrev:v,onScroll:E}),F=jp({listRef:k,syncScrollPosition:O});return l?i.createElement(i.Fragment,null,c):s?i.createElement(i.Fragment,null,a):i.createElement(n_,{id:"infinite-list-container"},i.createElement(r_,{id:"infinite-list-inner",ref:I,onScroll:M,onKeyDown:F,role:"list","aria-label":w,tabIndex:0},S==="bottom"&&i.createElement("div",{style:{flexGrow:1}}),f,d?m:r.map((Y,z)=>o({message:Y,index:z})),g,x>0&&i.createElement("div",{style:{minHeight:x}})),i.createElement(o_,{id:"infinite-list-overlay-container"},i.createElement(s_,{id:"infinite-list-overlay"},_)))}),n_=p.default.div`display:flex;position:relative;flex:1;overflow:hidden;`,r_=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;}`,o_=p.default.div`position:absolute;top:0;bottom:0;left:0;right:0;pointer-events:none;`,s_=p.default.div`pointer-events:auto;`,je=({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(i_,{as:e,disabled:o,...a},i.createElement(Q,{type:t,size:n,color:r??l}),s)},i_=p.default.button`all:unset;padding:4px;cursor:pointer;display:flex;align-items:center;justify-content:center;${Ae}&:disabled{cursor:not-allowed;}`,a_=({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}=me(),f=e.length,g=e[o],_=m.conversation.fileViewer.downloadEnabled,v=f>1,y=(g==null?void 0:g.type)||"",b=He(y),E=cn(y),C=!Hm(y);u.useEffect(()=>{r&&(s(t),l(!1))},[r,t]);const S=u.useCallback(()=>{o>0&&(s(w=>w-1),l(!1))},[o]),x=u.useCallback(()=>{o<f-1&&(s(w=>w+1),l(!1))},[o,f]);return u.useEffect(()=>{if(!r)return;const w=k=>{k.key==="ArrowLeft"?S():k.key==="ArrowRight"&&x()};return window.addEventListener("keydown",w),()=>window.removeEventListener("keydown",w)},[r,S,x]),!r||!g?null:i.createElement(nt,{onClose:n,visible:r,portalContainerId:Ce.MODAL_ROOT,"aria-label":(g==null?void 0:g.name)||c.IMAGE_VIEWER__DEFAULT_TITLE},i.createElement(l_,null,i.createElement(c_,null,i.createElement(u_,null,i.createElement(d_,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(m_,{type:"close",size:18,color:h.color.ondark.textHighEmphasis,"aria-label":c.A11Y_IMAGE_VIEWER_CLOSE,onClick:n})),i.createElement(f_,{onClick:w=>w.currentTarget===w.target&&n()},v&&i.createElement(qo,{$position:"left",type:"chevron-right",size:22,color:h.color.ondark.textHighEmphasis,onClick:S,"aria-label":c.A11Y_IMAGE_VIEWER_PREVIOUS,disabled:o===0,$flipped:!0}),i.createElement(g_,null,b&&i.createElement(i.Fragment,null,!a&&i.createElement(h_,null,i.createElement(at,{size:32},i.createElement(Q,{type:"spinner",color:"textLowEmphasis",size:32}))),i.createElement(p_,{src:g.url,alt:g.name||"Image",$loaded:a,onLoad:()=>l(!0)})),E&&i.createElement(__,{controls:!0},i.createElement("source",{src:g.url,type:y})),C&&i.createElement(E_,null,i.createElement($,{variant:"h1",color:h.themedColor.textHighEmphasis},c.FILE_VIEWER__UNSUPPORT))),v&&i.createElement(qo,{$position:"right",type:"chevron-right",size:22,color:h.color.ondark.textHighEmphasis,onClick:x,"aria-label":c.A11Y_IMAGE_VIEWER_NEXT,disabled:o===f-1})),i.createElement(b_,null,v&&i.createElement($,{variant:"body2",color:h.color.ondark.textHighEmphasis},o+1,"/",f),_&&!C&&i.createElement(C_,{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}))))},l_=p.default.div`position:fixed;inset:0;outline:none;display:flex;flex-direction:column;background-color:${h.themedColor.bg_50_600};`,c_=p.default.header`display:flex;align-items:center;justify-content:space-between;padding:12px 12px 12px 16px;min-height:56px;background-color:${h.color.overlay.dark};`,u_=p.default.div`flex:1;min-width:0;padding-right:8px;`,d_=p.default.div`display:flex;flex-direction:column;gap:2px;`,m_=p.default(je)`flex-shrink:0;width:28px;height:28px;border-radius:50%;`,En=p.default.div`display:flex;align-items:center;justify-content:center;`,f_=p.default(En)`flex:1;min-height:0;position:relative;`,g_=p.default(En)`position:relative;max-width:100%;max-height:100%;`,h_=p.default(En)`position:absolute;inset:0;`,p_=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;`,__=p.default.video`max-width:100%;max-height:100%;object-fit:contain;`,E_=p.default(En)`flex-direction:column;gap:16px;`,qo=p.default(je)`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;}`,b_=p.default.footer`position:relative;display:flex;align-items:center;justify-content:center;padding:16px;min-height:56px;background-color:${h.color.overlay.dark};`,C_=p.default(je)`position:absolute;right:16px;top:50%;transform:translateY(-50%);padding:0;width:24px;height:24px;`,Ir=({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(x_,{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,_=f?i.createElement(T_,{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(v_,null,i.createElement(y_,null,i.createElement($,{as:"div",id:t,variant:"h2",color:(d==null?void 0:d.titleColor)??h.themedColor.textHighEmphasis},e)),i.createElement(S_,null,i.createElement($,{as:"div",id:r,variant:"body3",color:(d==null?void 0:d.descriptionColor)??h.themedColor.textMidEmphasis},n)),i.createElement(A_,{$buttonLayout:c},c==="horizontal"?i.createElement(i.Fragment,null,g,_):i.createElement(i.Fragment,null,_,g)))},v_=p.default.div`display:flex;flex-direction:column;width:280px;border-radius:16px;overflow:hidden;background-color:${({theme:e})=>e.colors.base.modalContentBackground};`,y_=p.default.div`padding:24px 24px 16px;`,S_=p.default.div`padding-inline:24px;`,A_=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;`,x_=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;}`,T_=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;}`,qt=16,I_=({status:e})=>e===Jt.COMPLETED?i.createElement(Q,{type:"done-circle",size:qt,color:h.themedColor.textHighEmphasis}):e===Jt.CANCELED?i.createElement(Q,{type:"stop-circle",size:qt,color:h.themedColor.textLowEmphasis}):i.createElement(at,{size:qt},i.createElement(Q,{type:"spinner",size:qt,color:h.themedColor.textHighEmphasis})),zi=24,w_=8,M_=40,k_=({task:e,isFirst:t,isLast:n})=>i.createElement(R_,{role:"listitem"},i.createElement(L_,null,i.createElement(Ko,{$hidden:t}),i.createElement(O_,null,i.createElement(I_,{status:e.status})),i.createElement(Ko,{$hidden:n})),i.createElement(N_,null,i.createElement($,{as:"div",variant:"body3",color:e.status===Jt.CANCELED?h.themedColor.textLowEmphasis:h.themedColor.textHighEmphasis},e.user_facing_title))),R_=p.default.div`display:flex;gap:4px;`,L_=p.default.div`display:flex;flex-direction:column;align-items:center;width:${zi}px;flex-shrink:0;`,Ko=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 );`,O_=p.default.div`display:flex;height:${zi}px;align-items:center;justify-content:center;`,N_=p.default.div`display:flex;flex:1;align-items:center;box-sizing:border-box;min-width:0;min-height:${M_}px;padding-block:${w_}px;`,D_=({steward:e,onCancelSteward:t})=>{const{logger:n}=me(),[r,o]=u.useState(!1),[s,a]=u.useState(!1),l=!!e.cancellation_option,c=ba(e.status);return i.createElement($_,{$marginBottom:un("single")},i.createElement(P_,null,i.createElement(F_,null,i.createElement(U_,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(z_,{type:"button","aria-label":"Stop steward",disabled:s,onClick:()=>o(!0)},i.createElement(Q,{type:"stop",size:16,color:s?h.themedColor.textDisabled:h.themedColor.textHighEmphasis}))),i.createElement(B_,null),e.tasks.length===0?c!==Tt.IN_PROGRESS?null:i.createElement(G_,null,i.createElement(at,{size:16},i.createElement(Q,{type:"spinner",size:16,color:h.themedColor.textHighEmphasis}))):i.createElement(H_,{role:"list"},e.tasks.map((d,m)=>i.createElement(k_,{key:d.id,task:d,isFirst:m===0,isLast:m===e.tasks.length-1})))),r&&e.cancellation_option&&i.createElement(nt,{portalContainerId:Ce.WINDOW,visible:r,onClose:()=>o(!1)},i.createElement(Ir,{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)}}})))},$_=p.default.div`display:flex;flex-direction:column;margin:0 ${ee.HORIZONTAL_PADDING}px;margin-bottom:${({$marginBottom:e})=>`${e}px`};
|
|
383
|
+
`,P_=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);`,F_=p.default.div`display:flex;flex-direction:row;align-items:flex-start;gap:8px;`,U_=p.default.div`display:flex;flex-direction:column;gap:4px;flex:1;min-width:0;`,B_=p.default.div`height:1px;margin-block:12px;background-color:${h.themedColor.bg_200_400};`,H_=p.default.div`display:flex;flex-direction:column;`,G_=p.default.div`display:flex;width:100%;height:40px;align-items:center;justify-content:center;`,z_=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;}`,V_=({className:e,label:t,onClick:n})=>{const{colors:r}=D.useTheme(),{conversation:o}=oe(),s={newMessages:o.newMessagesButton()};return i.createElement(Y_,{className:e,onClick:n,...s.newMessages.props},i.createElement($,{variant:"button",color:r.base.primaryContrastContent},t),i.createElement(Q,{size:16,type:"chevron-down",color:r.base.primaryContrastContent}),s.newMessages.descriptionNode)},Y_=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}`,wr=({iconSize:e=64,icon:t,className:n,label:r,children:o})=>i.createElement(q_,{className:n},t&&i.createElement(Q,{type:t,size:e,color:h.themedColor.textLowEmphasis}),r&&i.createElement($,{variant:"body1",color:h.themedColor.textMidEmphasis},r),o),W_=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;`,K_=({label:e="Something went wrong",icon:t="error",action:n,...r})=>i.createElement(wr,{icon:t,label:e,...r},n&&i.createElement(j_,{onClick:n.onClick,label:n.label??"Retry"})),j_=({label:e,onClick:t})=>{const{conversation:n}=oe();return i.createElement(X_,{tabIndex:0,...n.retryButton(e).props,onClick:t},i.createElement(Q,{type:"refresh",size:20}),i.createElement($,{variant:"button",color:h.color.primary.main},e))},X_=p.default.button`all:unset;display:flex;cursor:pointer;gap:4px;align-items:center;justify-content:center;${Ae}`,Z_=({iconSize:e=48,className:t})=>i.createElement(at,{size:e,className:t}),J_=({label:e="No channels",icon:t="chat",...n})=>i.createElement(wr,{icon:t,label:e,...n}),Q_=({label:e="No messages",icon:t="message",...n})=>i.createElement(wr,{icon:t,label:e,...n}),eE=e=>{const{components:t}=bn.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(W_,null,n)},bn=Be({template:eE,components:{Loading:Z_,Error:K_,NoChannels:J_,NoMessages:Q_}}),It=e=>{const{Template:t}=bn.useContext();return i.createElement(t,{...e})},tE=[0,150,450];function nE({enabled:e}){const{state:t,actions:n}=gi(),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=tE.map(l=>setTimeout(()=>{we(()=>{r.current===s&&(o.current||n.scrollToBottom(!1))})},l));return()=>{r.current+=1,a.forEach(l=>clearTimeout(l))}},[n.scrollToBottom,e])}const rE=({className:e,date:t=Date.now(),role:n,style:r})=>{const{format:o,stringSet:s}=se();return i.createElement(oE,{id:`${Ne}-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)))},oE=p.default.div`display:flex;justify-content:center;align-items:center;text-align:center;word-break:break-word;`,sE=({className:e,style:t,onClick:n})=>{const{conversation:r}=oe(),o={scrollToBottom:r.scrollToBottomButton()};return i.createElement(iE,{className:e,style:t,onClick:n,tabIndex:0,...o.scrollToBottom.props},i.createElement(Q,{size:24,type:"chevron-down",color:h.color.primary.main}),o.scrollToBottom.descriptionNode??null)},iE=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);${J.light`
|
|
384
|
+
background-color: ${h.color.background50};
|
|
385
385
|
&:hover {
|
|
386
|
-
background-color: ${
|
|
386
|
+
background-color: ${h.color.background100};
|
|
387
387
|
}
|
|
388
388
|
&:active {
|
|
389
|
-
background-color: ${
|
|
389
|
+
background-color: ${h.color.background200};
|
|
390
390
|
}
|
|
391
391
|
`}
|
|
392
392
|
${J.dark`
|
|
393
|
-
background-color: ${
|
|
393
|
+
background-color: ${h.color.background400};
|
|
394
394
|
&:hover {
|
|
395
|
-
background-color: ${
|
|
395
|
+
background-color: ${h.color.background500};
|
|
396
396
|
}
|
|
397
397
|
&:active {
|
|
398
|
-
background-color: ${
|
|
398
|
+
background-color: ${h.color.background700};
|
|
399
399
|
}
|
|
400
400
|
`}
|
|
401
401
|
|
|
@@ -404,37 +404,37 @@
|
|
|
404
404
|
}
|
|
405
405
|
|
|
406
406
|
${Ae}
|
|
407
|
-
`,
|
|
408
|
-
background-color: ${
|
|
409
|
-
border-color: ${
|
|
407
|
+
`,aE=()=>null,Cn=Be({template:aE,components:{DateSeparator:rE,ScrollToBottomButton:sE}}),lE=()=>{const{stringSet:e,format:t}=se(),{agentPreviewConfigs:n={},aiAgentId:r}=me(),{aiAgentInfo:o}=Me(),{messageSource:s}=Se(),{Template:a}=tt.useContext(),{components:l}=Cn.useContext(),c=n.welcomeMessages??[],d=s.messages,m=zm(d,r),f=d[m.length+1],g=m[0]??f;return{filteredMessages:Ci(d,{previewWelcomeMessages:c,aiAgentUserId:r}),shouldShowOriginalDate:_=>_>0||c.length===0?!0:f&&!Xe.isSameDay(f.createdAt,(g==null?void 0:g.createdAt)??0),renderAgentPreviewWelcomeMessages:()=>c.length===0?null:i.createElement(i.Fragment,null,i.createElement(l.DateSeparator,{role:"listitem",style:{margin:"16px 0"},date:g==null?void 0:g.createdAt}),c.map((_,v)=>{const y=v===c.length-1,b=m.length!==d.length,E=c.length===1?"single":v===0?"top":y||b?"bottom":"middle",C=(g==null?void 0:g.createdAt)??Date.now();return i.createElement("div",{key:v,role:"listitem",tabIndex:-1,"aria-label":St({sender:(o==null?void 0:o.nickname)||"",message:_.message,messageFormat:"markdown",time:t(C,e.DATE_FORMAT__MESSAGE_TIMESTAMP),codeBlockPlaceholder:e.A11Y_CODE_BLOCK_PLACEHOLDER}),"data-message-listitem":""},i.createElement(a,{messageType:"user",message:_.message,sender:o,groupType:E,createdAt:C,extendedMessagePayload:{suggested_replies:_.suggestedReplies},suggestedRepliesDirection:n.suggestedRepliesDirection,suggestedRepliesVisible:y&&!b,isBotMessage:!0,onClickSuggestedReply:async({reply:S})=>{s.sendUserMessage({message:S})}}))}))}},cE=()=>{const{messageSource:e,scrollSource:t}=Se();u.useEffect(()=>{!t.state.isAwayFromBottom&&t.state.isScrollPositionReconciled&&e.resetNewMessages()},[t.state.isAwayFromBottom,t.state.isScrollPositionReconciled])},jo="https://delight.ai?utm_medium=product&utm_source=aiagent&utm_campaign=fy26-glbl-ai-agent-poweredby",uE=({style:e})=>{const{stringSet:t}=se(),{handlers:n}=me(),{conversation:r}=oe(),{isActionbookTester:o}=_t();return!mr("powered-by")||o?null:i.createElement(dE,{variant:"caption2",style:e},t.POWERED_BY+" ",i.createElement(mE,{variant:"caption2",forwardedAs:"a",href:jo,...r.poweredByLink().props,rel:pr,target:"_blank",onClick:a=>{a.preventDefault(),n.onClickLink({url:jo})}},"Sendbird"))},dE=p.default($)`color:${h.themedColor.textLowEmphasis};text-align:center;`,mE=p.default($)`color:${h.themedColor.textLowEmphasis};cursor:pointer;text-decoration:none;`,fE=()=>{var l;const{stringSet:e}=se(),{conversation:t}=oe(),{channelSource:n,goToActiveConversation:r,scrollSource:o}=Se(),s=Le(n.channel),a=u.useRef(s);return u.useEffect(()=>{if(!a.current&&s){const m=setTimeout(()=>{o.actions.scrollToBottom()},100);return()=>clearTimeout(m)}a.current=s},[s,o.actions.scrollToBottom]),!((l=n.channel)!=null&&l.isAIAgent)||!s?null:i.createElement(gE,null,i.createElement(hE,{variant:"button",color:h.themedColor.textHighEmphasis,...t.startNewConversationButton({onActivate:r}).props},e.TALK_TO_AGENT))},gE=p.default.div`display:flex;justify-content:center;margin-bottom:16px;`,hE=p.default($)`border-radius:6px;box-sizing:border-box;padding:10px 20px;cursor:pointer;user-select:none;background-color:${h.color.background50};border:1px solid ${h.color.onlight.textDisabled};${J.dark`
|
|
408
|
+
background-color: ${h.color.background700};
|
|
409
|
+
border-color: ${h.color.ondark.textLowEmphasis};
|
|
410
410
|
`}
|
|
411
|
-
`,mE=()=>{var _e;const{Template:e}=Dt.useContext(),{Template:t}=tt.useContext(),{Template:n}=pn.useContext(),{components:r}=bn.useContext(),{stringSet:o,format:s}=se(),{file:a}=oe().conversation,{config:l,cache:c,agentPreviewConfigs:d,chatSDK:m,handlers:f,state:h}=me(),{userSession:_,aiAgentInfo:y,connectionError:C}=we(),{conversation:v,channelSource:b,messageSource:E,scrollSource:A,state:{input:x,streamAnimation:k}}=Se(),{isActionbookTester:R}=pt(),{filteredMessages:I,shouldShowOriginalDate:w,renderAgentPreviewWelcomeMessages:O}=oE(),$=Rs(b.channel),[V,H]=u.useState(null),[Y,G]=u.useState(null);u.useEffect(()=>{A.actions.onTypingIndicatorUpdate(!!$)},[!!$,A.actions.onTypingIndicatorUpdate]),sE(),J_({enabled:E.initialized&&E.messages.length>0});const W=(L,X=!1)=>{var K;return X?y:((K=b.channel)==null?void 0:K.members.find(F=>F.userId===L.sender.userId))??L.sender},q=L=>{if(L.sendingStatus==="failed"&&!x.disabled)return()=>G(L)},ce=({message:L,index:X})=>{const K=ga(L),F=I[X-1],ee=I[X+1],de=I[I.length-1],fe=L===de,xe=ft(L,y.userId),Oe=!(y.isUserFeedbackEnabled&&xe&&!Ve.isWelcomeMessage(L)),ke=pa(L,F,ee,Oe),T=!ua.isSameDay((F==null?void 0:F.createdAt)??0,L.createdAt)&&w(X)&&!R,M=te=>{H({files:te.files.map(ie=>({...ie,timestamp:L.createdAt})),index:te.index})},N=te=>{M({files:[te],index:0})},j=T?i.createElement(r.DateSeparator,{style:{margin:"16px 0"},date:L.createdAt}):null,B={data:L.data,maxBodyWidth:h.expanded?ne.WIDE_BODY_MAX_WIDTH:void 0,extendedMessagePayload:L.extendedMessagePayload,createdAt:L.createdAt,groupType:ke,onClickMedia:N,onClickMediaFiles:M,onClickFile:f.onClickLink,onClickCTA:f.onClickLink,onClickCitation:te=>f.onClickLink({url:te.link}),onClickLink:f.onClickLink},z=()=>{if(Ie.isOutgoing(L,_.userId))return"outgoingmessage";if(Ie.isIncoming(L,_.userId))return"incomingmessage"},U=L.createdAt!=null&&L.createdAt!==0?s(L.createdAt,o.DATE_FORMAT__MESSAGE_TIMESTAMP):void 0,ue=(()=>{var ie,re,Z,le,pe,rt;const te=(ie=L.message)==null?void 0:ie.trim();if(L.isFileMessage()){const ot=((re=L.name)==null?void 0:re.trim())||"";return In({markdownText:te,comparisonText:ot,plainText:a.label(ot,L.type)})}if(L.isMultipleFilesMessage()){const ot=((pe=(le=(Z=L.fileInfoList)==null?void 0:Z[0])==null?void 0:le.fileName)==null?void 0:pe.trim())||"",Fr=((rt=L.fileInfoList)==null?void 0:rt.length)??0;return In({markdownText:te,comparisonText:ot,plainText:Fr>0?o.CONVERSATION_LIST__MULTIPLE_FILES_COUNT(Fr):""})}return te?In({markdownText:te}):Ps("")})(),$e=(()=>{if(Ie.isAdmin(L))return yt({message:ue.text,messageFormat:ue.format,codeBlockPlaceholder:o.A11Y_CODE_BLOCK_PLACEHOLDER});if(Ie.isOutgoing(L,_.userId))return yt({sender:o.A11Y_MESSAGE_SENDER_YOU,message:ue.text,messageFormat:"plain",time:U,codeBlockPlaceholder:o.A11Y_CODE_BLOCK_PLACEHOLDER});if(Ie.isIncoming(L,_.userId))return yt({sender:W(L,xe).nickname,message:ue.text,messageFormat:ue.format,time:U,codeBlockPlaceholder:o.A11Y_CODE_BLOCK_PLACEHOLDER})})(),ae=(()=>{var te,ie;if(Ie.isAdmin(L))return Ie.isCSAT(L)?v?i.createElement(n,{...B,...v,isResolvedWhenDeterminedByUser:qa(v),messageType:"admin.csat",onSubmitCSAT:async re=>{var Z;await((Z=b.channel)==null?void 0:Z.submitCSAT(re))},onScrollToBottom:()=>A.actions.scrollToBottom()}):null:i.createElement(n,{...B,messageType:"admin",message:L.message});if(Ie.isSteward(L))return i.createElement(R_,{steward:L.extendedMessagePayload.steward,onCancelSteward:async()=>{await m.aiAgent.cancelStewardTask({channelUrl:L.channelUrl,messageId:L.messageId})}});if(Ie.isOutgoing(L,_.userId)){const re={...B,message:L.message,sender:W(L),sendingStatus:L.sendingStatus,onClickFailedMessage:q(L)};if(L.isUserMessage())return i.createElement(e,{messageType:"user",...re});if(L.isFileMessage()){const[Z,le]=((te=L.metaArrays.find(pe=>pe.key===as))==null?void 0:te.value)??[];return i.createElement(e,{messageType:"file",file:L,metadata:{aspectRatio:Z&&le?`${Z}/${le}`:"1/1",localFile:(ie=L.messageParams)==null?void 0:ie.file},...re})}if(L.isMultipleFilesMessage()){const{files:Z,metadata:le}=Ro(L);return i.createElement(e,{messageType:"multipleFiles",files:Z,metadata:le,...re})}}if(Ie.isIncoming(L,_.userId)){const re={...B,sender:W(L,xe),message:L.message,suggestedRepliesVisible:fe,suggestedRepliesDirection:d==null?void 0:d.suggestedRepliesDirection,isBotMessage:xe,isStreaming:Ve.isStreaming(L),isHandedOff:et(b.channel),isConversationClosed:Re(b.channel),isFeedbackEnabled:y.isUserFeedbackEnabled,isFeedbackCommentEnabled:y.isUserFeedbackCommentOptionEnabled,isSenderAvatarVisible:l.conversation.list.senderAvatarEnabled,markdownImageRenderMode:l.conversation.list.markdownImageRenderMode,onClickSuggestedReply:async({reply:Z})=>{E.sendUserMessage({message:Z})},onRequestMessageTemplate:async Z=>{const{template:le}=await m.aiAgent.getMessageTemplate(Z);return c.template.set(Z,le),le},onGetCachedMessageTemplate:Z=>c.template.get(Z),onHandleTemplateInternalAction:Z=>{if(Z.type==="internal"&&Z.internalData){const{method:le,payload:pe}=Z.internalData;le==="message.send"&&(pe!=null&&pe.message)&&E.sendUserMessage({message:pe.message})}},onFeedbackUpdate:Z=>{const le={messageId:L.messageId,channelUrl:L.channelUrl};if(!Z)return m.aiAgent.deleteMessageFeedback(le);const pe={...le,rating:lh(Z.rating),comment:Z.comment};return Ve.hasFeedback(L)?m.aiAgent.updateMessageFeedback(pe):m.aiAgent.createMessageFeedback(pe)},onSubmitForm:({key:Z,data:le})=>m.aiAgent.submitForm({messageId:L.messageId,channelUrl:L.channelUrl,formKey:Z,formData:le}),onCancelForm:({key:Z})=>m.aiAgent.cancelForm({messageId:L.messageId,channelUrl:L.channelUrl,formKey:Z}),onSendChallengeAction:({key:Z,requestId:le,action:pe,data:rt})=>m.aiAgent.sendChallengeAction({channelUrl:L.channelUrl,key:Z,requestId:le,action:pe,data:rt}),onStreamAnimationStart:()=>{k.start(L.messageId)},onStreamAnimationProgress:()=>{A.actions.onStreamingUpdate(!0)},onStreamAnimationComplete:()=>{k.stop(L.messageId),A.actions.onStreamingUpdate(!1)}};if(L.isUserMessage())return i.createElement(t,{messageType:"user",...re});if(L.isFileMessage())return i.createElement(t,{messageType:"file",file:L,...re});if(L.isMultipleFilesMessage()){const{files:Z}=Ro(L);return i.createElement(t,{messageType:"multipleFiles",files:Z,...re})}}})();return i.createElement("div",{key:K,id:`${Ne}-message-item`,role:"listitem",tabIndex:-1,"aria-label":$e,"data-message-listitem":"","data-layout-id":z()},j,ae)};return i.createElement(fE,{id:`${Ne}-message-list`},i.createElement(Zp,{ref:A.ref,onScroll:A.props.onScroll,stackDirection:d==null?void 0:d.messageStackDirection,messages:I,renderMessage:ce,onLoadPrev:E.loadPrevious,onLoadNext:E.loadNext,depsForResetScrollPositionToBottom:[E.initialized,E.messages.length!==0],bottomSpacerHeight:A.state.bottomSpace,"aria-label":o.A11Y_MESSAGE_LIST,loading:!E.initialized||!b.channel,empty:I.length===0&&!$,error:!!(C||b.error),LoadingComponent:i.createElement(Tt,{type:"loading"}),EmptyComponent:(()=>{const L=O();return L?i.createElement("div",{style:{width:"100%"}},L):i.createElement(Tt,{type:"noMessages",label:o.PLACE_HOLDER__NO_MESSAGES})})(),ErrorComponent:i.createElement(Tt,{type:"error",label:(C==null?void 0:C.message)??((_e=b.error)==null?void 0:_e.message),action:b.error?{label:o.RETRY,onClick:()=>b.refetch()}:void 0}),messageTopArea:i.createElement(i.Fragment,null,i.createElement(iE,{style:{marginTop:16}}),O()),messageBottomArea:i.createElement(i.Fragment,null,$&&i.createElement("div",{id:`${Ne}-message-item`,role:"listitem",tabIndex:-1,"aria-label":yt({sender:$.user.nickname,message:o.A11Y_TYPING_INDICATOR,codeBlockPlaceholder:o.A11Y_CODE_BLOCK_PLACEHOLDER}),"data-message-listitem":"",style:{marginTop:I.length===0?8:0}},i.createElement(t,{isTyping:!0,isBotMessage:$.isBot,sender:$.user,thinkingMessage:$.thinkingMessage,messageType:"user",groupType:"single",message:"",isSenderAvatarVisible:l.conversation.list.senderAvatarEnabled})),l.conversation.list.isTalkToAgentViewEnabled&&i.createElement(cE,null)),overlayArea:i.createElement(i.Fragment,null,l.conversation.list.newMessageIndicatorEnabled&&A.state.isAwayFromBottom&&E.newMessages.length>0&&i.createElement(hE,{label:o.SCROLL_TO_NEW_MESSAGES_LABEL(E.newMessages),onClick:()=>A.actions.scrollToBottom()}),A.state.isAwayFromBottom&&E.newMessages.length===0&&!$&&i.createElement(r.ScrollToBottomButton,{onClick:()=>A.actions.scrollToBottom(),style:{position:"absolute",bottom:12,insetInlineEnd:16}}))}),V&&i.createElement(r_,{files:V.files,initialIndex:V.index,onClose:()=>H(null),visible:!0}),Y&&i.createElement(Je,{visible:!0,onClose:()=>G(null),"aria-label":o.A11Y_FAILED_MESSAGE_OPTIONS},i.createElement(Je.ActionItem,{onClick:()=>{E.resendMessage(Y),G(null)}},o.FAILED_MESSAGE_RESEND),i.createElement(Je.ActionItem,{destructive:!0,onClick:()=>{E.deleteMessage(Y),G(null)}},o.FAILED_MESSAGE_REMOVE)))},fE=p.default.div`overflow-y:hidden;display:flex;flex:1;position:relative;`,hE=p.default(U_)`position:absolute;bottom:12px;left:50%;transform:translateX(-50%);`,gE=()=>i.createElement(mE,null),pE=()=>{var o;const{origin:e}=pt(),{appId:t,aiAgentId:n}=Me(),{channelSource:r}=Se();return(o=r.channel)!=null&&o.conversation?i.createElement(_E,null,i.createElement(Zn,{style:{gap:4}},i.createElement(Q,{color:g.themedColor.textLowEmphasis,size:12,type:"show"}),i.createElement(P,{as:"i",color:g.themedColor.textLowEmphasis,variant:"caption2"},"Only visible in the tester")),i.createElement(Zn,{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(P,{variant:"body3",color:g.themedColor.textHighEmphasis},"Copy ",i.createElement("span",{style:{color:g.themedColor.primary}},"conversation link")),i.createElement(Q,{color:g.themedColor.primary,size:14,type:"copy"}))):null},Zn=p.default.div`display:flex;justify-content:center;align-items:center;`,_E=p.default(Zn)`flex-direction:column;padding-block:16px;background-color:${g.themedColor.bg_100_500};gap:8px;`,EE=(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}},$i=u.createContext(void 0),bE=({children:e})=>{var H,Y;const{chatSDK:t}=me(),{createAttachmentRules:n}=we(),{stringSet:r}=se(),{channelSource:o,state:s}=Se(),[a,l]=u.useState([]),{announceError:c}=_r(),[d,m]=u.useState(null),f=n({channel:o.channel,uploadSizeLimit:(H=t.appInfo)==null?void 0:H.uploadSizeLimit}),h=((Y=s==null?void 0:s.input)==null?void 0:Y.disabled)??!1,_=f.isEnabled(),y=f.maxAttachmentCount,C=()=>m(null),v=G=>m(G),b=()=>{v({title:r.FILE_UPLOAD_NOTIFICATION__COUNT_LIMIT.replace("%d",y.toString())})},E=G=>{v({title:r.FILE_UPLOAD_NOTIFICATION__SIZE_LIMIT.replace("%d",G.toString())}),c({type:"fileSizeExceeded",maxSizeMB:G})},A=G=>{v({title:r.FILE_UPLOAD_NOTIFICATION__FILES_EXCLUDED_BY_VALIDATION.replace("%d",G.toString())})},x=G=>G.map(W=>({file:W,preview:{url:URL.createObjectURL(W),type:W.type,name:W.name}})),k=G=>{l(W=>[...W,...x(G)])},R=G=>{l(W=>(W.forEach(q=>URL.revokeObjectURL(q.preview.url)),x(G)))},I=G=>{const{passed:W,failedBySize:q,failedByType:ce}=EE(G,f),_e=q.length+ce.length,L=G.length===1?q[0]:void 0;return L?E(f.getUploadSizeLimitInMB(L.type)):_e>0&&A(_e),W},w=G=>{const W=I(G.files);W.length!==0&&(G.type==="append"?k(W):R(W))},O=G=>{if(!_||h||!vl(G))return;const W=Sl({currentFiles:a.map(({file:q})=>q),incomingFiles:G,maxAttachmentCount:y});switch(W.type){case"reject":b();return;case"confirm_replace":v({title:r.FILE_UPLOAD_REPLACE_ALERT__TITLE,description:r.FILE_UPLOAD_REPLACE_ALERT__DESCRIPTION,confirmText:r.BUTTON__OK,cancelText:r.BUTTON__CANCEL,onConfirm:()=>w(W.action)});return;case"apply":w(W.action);return}},$=G=>{l(W=>{var ce;const q=(ce=W[G])==null?void 0:ce.preview;return q&&URL.revokeObjectURL(q.url),W.filter((_e,L)=>L!==G)})},V=()=>{l(G=>(G.forEach(W=>URL.revokeObjectURL(W.preview.url)),[]))};return i.createElement($i.Provider,{value:{files:a,addFiles:O,removeFile:$,clearFiles:V,isFileUploadEnabled:_,acceptableMimeTypes:f.supportedMimeTypes,maxAttachmentCount:f.maxAttachmentCount,showFileUploadAlert:v}},e,i.createElement(gn,{visible:!!d,...d??{},onClose:C}))},Ir=()=>{const e=u.useContext($i);if(!e)throw new Error("useFileUpload must be used within FileUploadProvider");return e};function CE({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 vE({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 yE=()=>{const{announceError:e}=Ke();return u.useCallback(t=>{e({type:"sendFailed"},t)},[e])},SE=1e3,AE=(e,t,n)=>{const{announcementsEnabled:r,setIsSuppressed:o}=Ke(),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]),Uc(t,c,{enabled:s,idleMs:SE})},xE=({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 h=f;h.metaKey||h.altKey||h.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}}},TE=p.default.div`&::-webkit-scrollbar{display:none;}overflow-x:auto;display:flex;flex-direction:row;gap:10px;padding:8px 16px;background-color:transparent;`,IE=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;}`,wE=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;${J.light`
|
|
412
|
-
background-color: ${
|
|
411
|
+
`,pE=()=>{var _e;const{Template:e}=$t.useContext(),{Template:t}=tt.useContext(),{Template:n}=_n.useContext(),{components:r}=Cn.useContext(),{stringSet:o,format:s}=se(),{file:a}=oe().conversation,{config:l,cache:c,agentPreviewConfigs:d,chatSDK:m,handlers:f,state:g}=me(),{userSession:_,aiAgentInfo:v,connectionError:y}=Me(),{conversation:b,channelSource:E,messageSource:C,scrollSource:S,state:{input:x,streamAnimation:w}}=Se(),{isActionbookTester:k}=_t(),{filteredMessages:I,shouldShowOriginalDate:M,renderAgentPreviewWelcomeMessages:O}=lE(),F=Os(E.channel),[Y,z]=u.useState(null),[V,H]=u.useState(null);u.useEffect(()=>{S.actions.onTypingIndicatorUpdate(!!F)},[!!F,S.actions.onTypingIndicatorUpdate]),cE(),nE({enabled:C.initialized&&C.messages.length>0});const W=(L,X=!1)=>{var K;return X?v:((K=E.channel)==null?void 0:K.members.find(P=>P.userId===L.sender.userId))??L.sender},q=L=>{if(L.sendingStatus==="failed"&&!x.disabled)return()=>H(L)},ce=({message:L,index:X})=>{const K=Ca(L),P=I[X-1],te=I[X+1],de=I[I.length-1],fe=L===de,xe=gt(L,v.userId),Oe=!(v.isUserFeedbackEnabled&&xe&&!Ve.isWelcomeMessage(L)),Re=va(L,P,te,Oe),T=!ha.isSameDay((P==null?void 0:P.createdAt)??0,L.createdAt)&&M(X)&&!k,R=ne=>{z({files:ne.files.map(ie=>({...ie,timestamp:L.createdAt})),index:ne.index})},N=ne=>{R({files:[ne],index:0})},j=T?i.createElement(r.DateSeparator,{role:"listitem",style:{margin:"16px 0"},date:L.createdAt}):null,U={data:L.data,maxBodyWidth:g.expanded?ee.WIDE_BODY_MAX_WIDTH:void 0,extendedMessagePayload:L.extendedMessagePayload,createdAt:L.createdAt,groupType:Re,onClickMedia:N,onClickMediaFiles:R,onClickFile:f.onClickLink,onClickCTA:f.onClickLink,onClickCitation:ne=>f.onClickLink({url:ne.link}),onClickLink:f.onClickLink},G=()=>{if(Ie.isOutgoing(L,_.userId))return"outgoingmessage";if(Ie.isIncoming(L,_.userId))return"incomingmessage"},B=L.createdAt!=null&&L.createdAt!==0?s(L.createdAt,o.DATE_FORMAT__MESSAGE_TIMESTAMP):void 0,ue=(()=>{var ie,re,Z,le,pe,rt;const ne=(ie=L.message)==null?void 0:ie.trim();if(L.isFileMessage()){const ot=((re=L.name)==null?void 0:re.trim())||"";return wn({markdownText:ne,comparisonText:ot,plainText:a.label(ot,L.type)})}if(L.isMultipleFilesMessage()){const ot=((pe=(le=(Z=L.fileInfoList)==null?void 0:Z[0])==null?void 0:le.fileName)==null?void 0:pe.trim())||"",Fr=((rt=L.fileInfoList)==null?void 0:rt.length)??0;return wn({markdownText:ne,comparisonText:ot,plainText:Fr>0?o.CONVERSATION_LIST__MULTIPLE_FILES_COUNT(Fr):""})}return ne?wn({markdownText:ne}):Us("")})(),$e=(()=>{if(Ie.isAdmin(L))return St({message:ue.text,messageFormat:ue.format,codeBlockPlaceholder:o.A11Y_CODE_BLOCK_PLACEHOLDER});if(Ie.isOutgoing(L,_.userId))return St({sender:o.A11Y_MESSAGE_SENDER_YOU,message:ue.text,messageFormat:"plain",time:B,codeBlockPlaceholder:o.A11Y_CODE_BLOCK_PLACEHOLDER});if(Ie.isIncoming(L,_.userId))return St({sender:W(L,xe).nickname,message:ue.text,messageFormat:ue.format,time:B,codeBlockPlaceholder:o.A11Y_CODE_BLOCK_PLACEHOLDER})})(),ae=(()=>{var ne,ie;if(Ie.isAdmin(L))return Ie.isCSAT(L)?b?i.createElement(n,{...U,...b,isResolvedWhenDeterminedByUser:Ja(b),messageType:"admin.csat",onSubmitCSAT:async re=>{var Z;await((Z=E.channel)==null?void 0:Z.submitCSAT(re))},onScrollToBottom:()=>S.actions.scrollToBottom()}):null:i.createElement(n,{...U,messageType:"admin",message:L.message});if(Ie.isSteward(L))return i.createElement(D_,{steward:L.extendedMessagePayload.steward,onCancelSteward:async()=>{await m.aiAgent.cancelStewardTask({channelUrl:L.channelUrl,messageId:L.messageId})}});if(Ie.isOutgoing(L,_.userId)){const re={...U,message:L.message,sender:W(L),sendingStatus:L.sendingStatus,onClickFailedMessage:q(L)};if(L.isUserMessage())return i.createElement(e,{messageType:"user",...re});if(L.isFileMessage()){const[Z,le]=((ne=L.metaArrays.find(pe=>pe.key===cs))==null?void 0:ne.value)??[];return i.createElement(e,{messageType:"file",file:L,metadata:{aspectRatio:Z&&le?`${Z}/${le}`:"1/1",localFile:(ie=L.messageParams)==null?void 0:ie.file},...re})}if(L.isMultipleFilesMessage()){const{files:Z,metadata:le}=Oo(L);return i.createElement(e,{messageType:"multipleFiles",files:Z,metadata:le,...re})}}if(Ie.isIncoming(L,_.userId)){const re={...U,sender:W(L,xe),message:L.message,suggestedRepliesVisible:fe,suggestedRepliesDirection:d==null?void 0:d.suggestedRepliesDirection,isBotMessage:xe,isStreaming:Ve.isStreaming(L),isHandedOff:et(E.channel),isConversationClosed:Le(E.channel),isFeedbackEnabled:v.isUserFeedbackEnabled,isFeedbackCommentEnabled:v.isUserFeedbackCommentOptionEnabled,isSenderAvatarVisible:l.conversation.list.senderAvatarEnabled,markdownImageRenderMode:l.conversation.list.markdownImageRenderMode,markdownLinkRenderMode:l.conversation.list.markdownLinkRenderMode,onClickSuggestedReply:async({reply:Z})=>{C.sendUserMessage({message:Z})},onRequestMessageTemplate:async Z=>{const{template:le}=await m.aiAgent.getMessageTemplate(Z);return c.template.set(Z,le),le},onGetCachedMessageTemplate:Z=>c.template.get(Z),onHandleTemplateInternalAction:Z=>{if(Z.type==="internal"&&Z.internalData){const{method:le,payload:pe}=Z.internalData;le==="message.send"&&(pe!=null&&pe.message)&&C.sendUserMessage({message:pe.message})}},onFeedbackUpdate:Z=>{const le={messageId:L.messageId,channelUrl:L.channelUrl};if(!Z)return m.aiAgent.deleteMessageFeedback(le);const pe={...le,rating:pg(Z.rating),comment:Z.comment};return Ve.hasFeedback(L)?m.aiAgent.updateMessageFeedback(pe):m.aiAgent.createMessageFeedback(pe)},onSubmitForm:({key:Z,data:le})=>m.aiAgent.submitForm({messageId:L.messageId,channelUrl:L.channelUrl,formKey:Z,formData:le}),onCancelForm:({key:Z})=>m.aiAgent.cancelForm({messageId:L.messageId,channelUrl:L.channelUrl,formKey:Z}),onSendChallengeAction:({key:Z,requestId:le,action:pe,data:rt})=>m.aiAgent.sendChallengeAction({channelUrl:L.channelUrl,key:Z,requestId:le,action:pe,data:rt}),onStreamAnimationStart:()=>{w.start(L.messageId)},onStreamAnimationProgress:()=>{S.actions.onStreamingUpdate(!0)},onStreamAnimationComplete:()=>{w.stop(L.messageId),S.actions.onStreamingUpdate(!1)}};if(L.isUserMessage())return i.createElement(t,{messageType:"user",...re});if(L.isFileMessage())return i.createElement(t,{messageType:"file",file:L,...re});if(L.isMultipleFilesMessage()){const{files:Z}=Oo(L);return i.createElement(t,{messageType:"multipleFiles",files:Z,...re})}}})();return i.createElement(u.Fragment,{key:K},j,i.createElement("div",{id:`${Ne}-message-item`,role:"listitem",tabIndex:-1,"aria-label":$e,"data-message-listitem":"","data-layout-id":G()},ae))};return i.createElement(_E,{id:`${Ne}-message-list`},i.createElement(t_,{ref:S.ref,onScroll:S.props.onScroll,stackDirection:d==null?void 0:d.messageStackDirection,messages:I,renderMessage:ce,onLoadPrev:C.loadPrevious,onLoadNext:C.loadNext,depsForResetScrollPositionToBottom:[C.initialized,C.messages.length!==0],bottomSpacerHeight:S.state.bottomSpace,"aria-label":o.A11Y_MESSAGE_LIST,loading:!C.initialized||!E.channel,empty:I.length===0&&!F,error:!!(y||E.error),LoadingComponent:i.createElement(It,{type:"loading"}),EmptyComponent:(()=>{const L=O();return L?i.createElement("div",{style:{width:"100%"}},L):i.createElement(It,{type:"noMessages",label:o.PLACE_HOLDER__NO_MESSAGES})})(),ErrorComponent:i.createElement(It,{type:"error",label:(y==null?void 0:y.message)??((_e=E.error)==null?void 0:_e.message),action:E.error?{label:o.RETRY,onClick:()=>E.refetch()}:void 0}),messageTopArea:i.createElement(i.Fragment,null,i.createElement(uE,{style:{marginTop:16}}),O()),messageBottomArea:i.createElement(i.Fragment,null,F&&i.createElement("div",{id:`${Ne}-message-item`,role:"listitem",tabIndex:-1,"aria-label":St({sender:F.user.nickname,message:o.A11Y_TYPING_INDICATOR,codeBlockPlaceholder:o.A11Y_CODE_BLOCK_PLACEHOLDER}),"data-message-listitem":"",style:{marginTop:I.length===0?8:0}},i.createElement(t,{isTyping:!0,isBotMessage:F.isBot,sender:F.user,thinkingMessage:F.thinkingMessage,messageType:"user",groupType:"single",message:"",isSenderAvatarVisible:l.conversation.list.senderAvatarEnabled})),l.conversation.list.isTalkToAgentViewEnabled&&i.createElement(fE,null)),overlayArea:i.createElement(i.Fragment,null,l.conversation.list.newMessageIndicatorEnabled&&S.state.isAwayFromBottom&&C.newMessages.length>0&&i.createElement(EE,{label:o.SCROLL_TO_NEW_MESSAGES_LABEL(C.newMessages),onClick:()=>S.actions.scrollToBottom()}),S.state.isAwayFromBottom&&C.newMessages.length===0&&!F&&i.createElement(r.ScrollToBottomButton,{onClick:()=>S.actions.scrollToBottom(),style:{position:"absolute",bottom:12,insetInlineEnd:16}}))}),Y&&i.createElement(a_,{files:Y.files,initialIndex:Y.index,onClose:()=>z(null),visible:!0}),V&&i.createElement(Je,{visible:!0,onClose:()=>H(null),"aria-label":o.A11Y_FAILED_MESSAGE_OPTIONS},i.createElement(Je.ActionItem,{onClick:()=>{C.resendMessage(V),H(null)}},o.FAILED_MESSAGE_RESEND),i.createElement(Je.ActionItem,{destructive:!0,onClick:()=>{C.deleteMessage(V),H(null)}},o.FAILED_MESSAGE_REMOVE)))},_E=p.default.div`overflow-y:hidden;display:flex;flex:1;position:relative;`,EE=p.default(V_)`position:absolute;bottom:12px;left:50%;transform:translateX(-50%);`,bE=()=>i.createElement(pE,null),CE=()=>{var o;const{origin:e}=_t(),{appId:t,aiAgentId:n}=ke(),{channelSource:r}=Se();return(o=r.channel)!=null&&o.conversation?i.createElement(vE,null,i.createElement(Jn,{style:{gap:4}},i.createElement(Q,{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(Jn,{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(Q,{color:h.themedColor.primary,size:14,type:"copy"}))):null},Jn=p.default.div`display:flex;justify-content:center;align-items:center;`,vE=p.default(Jn)`flex-direction:column;padding-block:16px;background-color:${h.themedColor.bg_100_500};gap:8px;`,yE=(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}},Vi=u.createContext(void 0),SE=({children:e})=>{var z,V;const{chatSDK:t}=me(),{createAttachmentRules:n}=Me(),{stringSet:r}=se(),{channelSource:o,state:s}=Se(),[a,l]=u.useState([]),{announceError:c}=Er(),[d,m]=u.useState(null),f=n({channel:o.channel,uploadSizeLimit:(z=t.appInfo)==null?void 0:z.uploadSizeLimit}),g=((V=s==null?void 0:s.input)==null?void 0:V.disabled)??!1,_=f.isEnabled(),v=f.maxAttachmentCount,y=()=>m(null),b=H=>m(H),E=()=>{b({title:r.FILE_UPLOAD_NOTIFICATION__COUNT_LIMIT.replace("%d",v.toString())})},C=H=>{b({title:r.FILE_UPLOAD_NOTIFICATION__SIZE_LIMIT.replace("%d",H.toString())}),c({type:"fileSizeExceeded",maxSizeMB:H})},S=H=>{b({title:r.FILE_UPLOAD_NOTIFICATION__FILES_EXCLUDED_BY_VALIDATION.replace("%d",H.toString())})},x=H=>H.map(W=>({file:W,preview:{url:URL.createObjectURL(W),type:W.type,name:W.name}})),w=H=>{l(W=>[...W,...x(H)])},k=H=>{l(W=>(W.forEach(q=>URL.revokeObjectURL(q.preview.url)),x(H)))},I=H=>{const{passed:W,failedBySize:q,failedByType:ce}=yE(H,f),_e=q.length+ce.length,L=H.length===1?q[0]:void 0;return L?C(f.getUploadSizeLimitInMB(L.type)):_e>0&&S(_e),W},M=H=>{const W=I(H.files);W.length!==0&&(H.type==="append"?w(W):k(W))},O=H=>{if(!_||g||!Tl(H))return;const W=wl({currentFiles:a.map(({file:q})=>q),incomingFiles:H,maxAttachmentCount:v});switch(W.type){case"reject":E();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:()=>M(W.action)});return;case"apply":M(W.action);return}},F=H=>{l(W=>{var ce;const q=(ce=W[H])==null?void 0:ce.preview;return q&&URL.revokeObjectURL(q.url),W.filter((_e,L)=>L!==H)})},Y=()=>{l(H=>(H.forEach(W=>URL.revokeObjectURL(W.preview.url)),[]))};return i.createElement(Vi.Provider,{value:{files:a,addFiles:O,removeFile:F,clearFiles:Y,isFileUploadEnabled:_,acceptableMimeTypes:f.supportedMimeTypes,maxAttachmentCount:f.maxAttachmentCount,showFileUploadAlert:b}},e,i.createElement(hn,{visible:!!d,...d??{},onClose:y}))},Mr=()=>{const e=u.useContext(Vi);if(!e)throw new Error("useFileUpload must be used within FileUploadProvider");return e};function AE({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 xE({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 TE=()=>{const{announceError:e}=Ke();return u.useCallback(t=>{e({type:"sendFailed"},t)},[e])},IE=1e3,wE=(e,t,n)=>{const{announcementsEnabled:r,setIsSuppressed:o}=Ke(),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]),Yc(t,c,{enabled:s,idleMs:IE})},ME=({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}}},kE=p.default.div`&::-webkit-scrollbar{display:none;}overflow-x:auto;display:flex;flex-direction:row;gap:10px;padding:8px 16px;background-color:transparent;`,RE=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;}`,LE=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;${J.light`
|
|
412
|
+
background-color: ${h.color.background50};
|
|
413
413
|
`}
|
|
414
414
|
${J.dark`
|
|
415
|
-
background-color: ${
|
|
415
|
+
background-color: ${h.color.background500};
|
|
416
416
|
`}
|
|
417
417
|
path {
|
|
418
|
-
fill: ${
|
|
418
|
+
fill: ${h.themedColor.textMidEmphasis};
|
|
419
419
|
}
|
|
420
420
|
|
|
421
421
|
&:hover {
|
|
422
422
|
path {
|
|
423
|
-
fill: ${
|
|
423
|
+
fill: ${h.themedColor.textHighEmphasis};
|
|
424
424
|
}
|
|
425
425
|
}
|
|
426
426
|
|
|
427
427
|
&:focus-visible {
|
|
428
428
|
opacity: 1;
|
|
429
|
-
outline: 2px solid ${
|
|
429
|
+
outline: 2px solid ${h.color.primary.main};
|
|
430
430
|
outline-offset: 2px;
|
|
431
431
|
}
|
|
432
432
|
|
|
433
433
|
circle {
|
|
434
|
-
stroke: ${
|
|
434
|
+
stroke: ${h.themedColor.bg_50_600};
|
|
435
435
|
}
|
|
436
|
-
`,
|
|
437
|
-
outline: 2px solid ${
|
|
436
|
+
`,OE=()=>{const e=Nt(),{conversation:t}=oe(),{files:n,removeFile:r,isFileUploadEnabled:o}=Mr();return o&&n.length>0?i.createElement(kE,null,n.map(({preview:{type:a,name:l,url:c}},d)=>{let m=i.createElement(Sr,{name:l,mimeType:a,type:nr(l,a),selected:!0});return a.startsWith("image/")&&(m=i.createElement("img",{alt:t.file.label(l,a,!0),src:c})),i.createElement(RE,{key:c},i.createElement(LE,{type:"button",...t.file.removeButton(l).props,$mobile:e,onClick:()=>r(d)},i.createElement(Q,{type:"close-filled",color:h.themedColor.textMidEmphasis})),m)})):null},NE={textArea:D.css`min-height:40px;height:40px;font-size:16px;line-height:24px;`},Yi=p.default.button`all:unset;cursor:pointer;display:flex;align-items:center;justify-content:center;width:32px;height:32px;${Ae}`,Xo=p.default.div`width:100%;position:relative;background-color:${({theme:e})=>e.colors.messageInput.background};border-radius:20px;`,Zo=p.default.div`display:flex;flex-direction:row;align-items:flex-end;position:relative;`,Jo=p.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:${Xs}px;overflow-wrap:break-word;white-space:pre-wrap;overflow-x:hidden;${di&&NE.textArea};${({$focusVisible:e})=>e&&D.css`
|
|
437
|
+
outline: 2px solid ${h.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: ${({theme:e})=>e.colors.messageInput.placeholderText};
|
|
449
449
|
}
|
|
450
450
|
}
|
|
451
451
|
|
|
452
|
-
${({$blocked:e})=>e&&D.css`cursor:not-allowed;&::placeholder{color:${
|
|
453
|
-
`,
|
|
454
|
-
color: ${
|
|
452
|
+
${({$blocked:e})=>e&&D.css`cursor:not-allowed;&::placeholder{color:${({theme:t})=>t.colors.messageInput.placeholderText};}`}
|
|
453
|
+
`,DE=p.default.input`display:none;`;p.default.div`display:flex;align-items:center;gap:24px;`;const $E=p.default(Yi)`flex-shrink:0;border-radius:8px;&:disabled{cursor:not-allowed;}&:not(:disabled){&:hover{background-color:${h.themedColor.bg_100_500};path{fill:${h.themedColor.textHighEmphasis};}}&:active{background-color:${h.themedColor.bg_200_400};}}`,Qo=p.default.div`padding:10px 16px 10px 12px;position:relative;display:flex;align-items:center;gap:8px;`,es=e=>e.startsWith("image/"),ts=({disabled:e})=>{const{stringSet:t}=se(),{conversation:n}=oe(),{config:r}=me(),o=u.useRef(null),s=u.useRef(null),[a,l]=u.useState(!1),{addFiles:c,isFileUploadEnabled:d,acceptableMimeTypes:m,showFileUploadAlert:f}=Mr(),g=m.includes(Un),_=g?["image/*"]:m.filter(es),v=g?[Un]:m.filter(I=>!es(I)),y=r.conversation.input.gallery.photoEnabled,b=r.conversation.input.fileEnabled,E=()=>g||_.length>0,C=()=>g||v.length>0,S=I=>{const M=I.currentTarget.files;M&&c(Array.from(M)),I.target.value=""},x=()=>{l(!0)},w=u.useMemo(()=>{const I=[];return y&&I.push({type:"image",icon:"photo",label:t.FILE_UPLOAD_PHOTOS,accept:_.join(","),inputRef:o,onSelect:()=>{if(!E()){f({title:t.FILE_UPLOAD_NO_SUPPORTED_FILES});return}l(!1),setTimeout(()=>{var M;return(M=o.current)==null?void 0:M.click()},100)}}),b&&I.push({type:"file",icon:"document",label:t.FILE_UPLOAD_FILES,accept:m.join(","),inputRef:s,onSelect:()=>{if(!C()){f({title:t.FILE_UPLOAD_NO_SUPPORTED_FILES});return}l(!1),setTimeout(()=>{var M;return(M=s.current)==null?void 0:M.click()},100)}}),I},[_,m,t,y,b]);if(!d)return null;const k={attach:n.messageInput.attachFileButton()};return i.createElement(i.Fragment,null,i.createElement($E,{...k.attach.props,disabled:e,onClick:x},i.createElement(Q,{type:"add",color:e?h.themedColor.textDisabled:h.color.primary.main,size:20}),k.attach.descriptionNode),w.map(I=>i.createElement(DE,{key:I.type,type:"file",ref:I.inputRef,multiple:I.type==="image",onChange:S,accept:I.accept})),i.createElement(Je,{visible:a,onClose:()=>l(!1),"aria-label":t.A11Y_FILE_UPLOAD_OPTIONS},w.map(I=>i.createElement(Je.ActionItem,{key:I.type,onClick:I.onSelect,icon:I.icon},I.label))))},PE=()=>{const e=u.useRef(null),[t,n]=u.useState(""),{stringSet:r}=se(),{conversation:o}=oe(),{rootElement:s}=me(),a=st(s),{focusHandlers:l,isFocusVisible:c,suppressNextFocusVisible:d}=ME({focusRoot:a}),{channelSource:m,messageSource:f,state:g}=Se(),{files:_,addFiles:v,clearFiles:y}=Mr(),b=TE(),{focusPolicy:E,disabled:C,disabledBy:S}=g.input,x=E==="preserve",w=E==="release",k=(()=>{if(!C)return r.MESSAGE_INPUT__PLACE_HOLDER;switch(S){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}})();Pm({onDropFiles:P=>{v(P)}}),xE({blurred:w,elementRef:e,document:a,onRecoverFocus:()=>{d()}}),wE(m.channel,t,!C);const I=t.trim().length>0,M=_.length>0,O=!C&&(I||M),F={input:o.messageInput.textInput(r.A11Y_MESSAGE_INPUT),send:o.messageInput.sendButton()},Y=()=>{e.current&&(e.current.value="",e.current.style.height=""),y(),n("")},z=()=>{var P;d(),(P=e.current)==null||P.focus()},{requestRestore:V,cancelRestore:H}=AE({elementRef:e,ready:x,onRestore:d}),W=P=>{H(),b(P)},q=()=>{H()},ce=async P=>{try{await P(),q()}catch{W(e.current)}},_e=async()=>{if(C)return;const P=t.trim();if(!P&&!_.length)return;const te=[..._];if(V(),Y(),z(),te.length===0){await ce(()=>f.sendUserMessage({message:P}));return}if(te.length===1)await ce(()=>f.sendFileMessage({message:P,file:te[0].file}));else{const de=te.map(({file:fe})=>({file:fe}));await ce(()=>f.sendMultipleFilesMessage({message:P,fileInfoList:de}))}},L=P=>{const te=Array.from(P.clipboardData.files);te.length>0&&(P.preventDefault(),v(te))},X=P=>{P.key!=="Enter"||P.nativeEvent.isComposing||P.shiftKey||(P.preventDefault(),_e())},K=P=>{if(C){e.current&&(e.current.value=t);return}if(e.current){e.current.style.height="";const te=Math.min(Xu,e.current.scrollHeight);Xs<te&&(e.current.style.height=`${te}px`)}n(P.target.value)};return w?i.createElement(Qo,null,i.createElement(ts,{disabled:!0}),i.createElement(Xo,null,i.createElement(Zo,null,i.createElement(Jo,{rows:1,...F.input.props,disabled:!0,placeholder:k,$blocked:!0,$focusVisible:!1,"data-focus-visible":"false"})))):i.createElement(Qo,{"data-message-composer":""},i.createElement(ts,{disabled:C}),i.createElement(Xo,null,i.createElement(OE,null),i.createElement(Zo,null,i.createElement(Jo,{ref:e,rows:1,...F.input.props,readOnly:x,"aria-disabled":x?"true":void 0,placeholder:k,maxLength:5e3,$blocked:C,$focusVisible:c,"data-focus-visible":c?"true":"false",onKeyDown:X,onChange:K,onFocus:l.onFocus,onBlur:l.onBlur,onPaste:L}))),O&&i.createElement(Yi,{...F.send.props,onClick:()=>_e()},i.createElement(Q,{type:"send",color:h.color.primary.main,size:20}),F.send.descriptionNode))},FE=p.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:${h.themedColor.textLowEmphasis};&& a{font-weight:700;text-decoration:none;${J.light`
|
|
454
|
+
color: ${h.color.information.light};
|
|
455
455
|
`};
|
|
456
456
|
${J.dark`
|
|
457
|
-
color: ${
|
|
457
|
+
color: ${h.color.information.main};
|
|
458
458
|
`};
|
|
459
459
|
}
|
|
460
|
-
`,DE=u.lazy(()=>Promise.resolve().then(()=>require("./cjs/VvejebHE.cjs")).then(e=>({default:e.MarkdownText}))),$E=()=>{const{aiAgentInfo:e,userSession:t}=we(),{handlers:n}=me(),{messageSource:r,channelSource:o}=Se(),[s,a]=u.useState(null),l=dr("special-notice",o.channel),c=u.useCallback(()=>o.channel?l?r.messages.some(d=>ft(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(NE,null,i.createElement(DE,{onClickLink:n.onClickLink},e.specialNotice))},PE=()=>i.createElement(FE,null,i.createElement($E,null),i.createElement(bE,null,i.createElement(OE,null))),FE=p.default.div`z-index:0;border:none;width:100%;`,BE=()=>{var o;const{testerType:e}=pt(),{channelSource:t}=Se(),n=Re(t.channel),r=!!e&&((o=t.channel)==null?void 0:o.isAIAgent);return n&&r?i.createElement(pE,null):i.createElement(PE,null)},Fi=({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(UE,{...o},i.createElement(HE,null,n==="center"&&t&&i.createElement(GE,{$sideWidth:Math.max(l,d)},i.createElement(zE,null,t)),i.createElement(VE,null,i.createElement(YE,{ref:s},e),(n==="start"||n==="end")&&t&&i.createElement(qE,{$align:n,$hasStart:!!e,$hasEnd:!!r},t),i.createElement(WE,{ref:a},r))))},UE=p.default.div`position:relative;width:100%;background-color:${({theme:e})=>e.colors.base.headerBackground};border-bottom:1px solid ${g.themedColor.textDisabled};`,HE=p.default.div`position:relative;height:56px;padding:11px 12px;`,GE=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;`,zE=p.default.div`max-width:100%;overflow:hidden;`,VE=p.default.div`display:flex;flex-direction:row;align-items:center;justify-content:space-between;height:100%;z-index:1;`,YE=p.default.div`flex-shrink:0;display:flex;align-items:center;`,WE=p.default.div`flex-shrink:0;display:flex;align-items:center;`,qE=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;`,_t=(e=16)=>Ot()?e*1.5:e,KE=()=>{const{state:e}=me(),{messenger:t}=oe(),n=_t(),r=()=>{e.setOpened(!1)};return i.createElement(je,{...t.closeButton().props,type:"close",size:n,onClick:r})},jE=()=>{const{enableCloseConversationButton:e,dispatcher:t}=me(),{channelSource:n}=Se(),{conversation:r}=oe(),o=n.channel,s=_t(),a=(o==null?void 0:o.isAIAgent)&&e,l=!or(o);if(!a)return null;const c={close:r.header.closeConversationButton()},d=async()=>{o&&await t.send(Ze.CloseConversation({channelUrl:o.url}))};return i.createElement(i.Fragment,null,i.createElement(je,{...c.close.props,type:"mute",size:s,disabled:l,onClick:d}),c.close.descriptionNode)},XE=()=>{const{state:e,enableExpandButton:t}=me(),{messenger:n}=oe(),r=_t();return t?i.createElement(je,{...n.expandButton(e.expanded).props,type:e.expanded?"collapse":"expand",size:r,onClick:()=>e.setExpanded(!e.expanded)}):null},ZE=({label:e,children:t,position:n="top",disabled:r})=>r?t:i.createElement(Jn,null,t,i.createElement(eb,{$position:n},i.createElement(tb,{variant:"caption1"},e),i.createElement(JE,{$position:n}))),JE=({$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:g.themedColor.textHighEmphasis})),QE={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%);`},Jn=p.default.div`position:relative;`,eb=p.default.div`display:flex;align-items:center;position:absolute;left:50%;z-index:${it.TOOLTIP};${({$position:e})=>QE[e]}opacity:0;transition:opacity 0.2s ease-in-out;pointer-events:none;${Jn}:hover &,${Jn}:focus-within &{opacity:1;}`,tb=p.default(P)`padding:6px 8px;background:${g.themedColor.textHighEmphasis};color:${g.themedColor.textHighEmphasisInverse};border-radius:4px;font-size:12px;white-space:nowrap;`,nb=2e3,es=0,rb=1500,Kt=Symbol("header-focus-status-pause"),ts="data-sb-header-focus-protected",ob="[data-message-composer]",ns=new WeakMap,$n=e=>{const t=ns.get(e);if(t)return t;const n={focusedTargetIds:new Set,pendingBlurTimeouts:new Map,maxPauseTimeout:null};return ns.set(e,n),n},Pn=(e,t)=>{const n=e.pendingBlurTimeouts.get(t);n&&(clearTimeout(n),e.pendingBlurTimeouts.delete(t))},jt=e=>{e.maxPauseTimeout&&(clearTimeout(e.maxPauseTimeout),e.maxPauseTimeout=null)},sb=e=>{e.pendingBlurTimeouts.forEach(t=>clearTimeout(t)),e.pendingBlurTimeouts.clear(),e.focusedTargetIds.clear(),jt(e)},ib=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)})},ab=e=>e instanceof HTMLBodyElement||(e instanceof HTMLButtonElement||e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&e.disabled?!0:(e instanceof HTMLElement&&e.closest(ob),!1),wr=()=>{const{setStatusPauseState:e}=Ke(),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()+rb,s();const c=$n(e);Pn(c,t.current),c.focusedTargetIds.add(t.current),c.focusedTargetIds.size===1&&e(Kt,!0),jt(c),c.maxPauseTimeout=setTimeout(()=>{sb(c),e(Kt,!1)},nb)},[s,e]),l=u.useCallback(c=>{if(!n.current)return;n.current=!1;const d=c.currentTarget,m=$n(e),f=d instanceof HTMLElement&&Date.now()<=r.current;Pn(m,t.current),f&&(s(),o.current=setTimeout(()=>{if(o.current=null,!(d instanceof HTMLElement)||!d.isConnected)return;const _=d.ownerDocument.activeElement,y=_ instanceof HTMLElement&&_.hasAttribute(ts);if(_===d||y||!ab(_))return;const C=ib(d);d.focus({preventScroll:!0}),C()},es)),m.pendingBlurTimeouts.set(t.current,setTimeout(()=>{m.pendingBlurTimeouts.delete(t.current),m.focusedTargetIds.delete(t.current),m.focusedTargetIds.size===0&&(jt(m),e(Kt,!1))},es))},[s,e]);return u.useEffect(()=>()=>{const c=$n(e);n.current=!1,s(),Pn(c,t.current),c.focusedTargetIds.delete(t.current)&&c.focusedTargetIds.size===0&&(jt(c),e(Kt,!1))},[s,e]),{[ts]:"true",onFocus:a,onBlur:l}},lb=()=>{const{logger:e}=me(),{stringSet:t}=se(),{channelSource:n}=Se(),{conversation:r}=oe(),o=n.channel,s=_t(),a=dr("handoff-button",o),l=!or(o)||et(o),[c,d]=u.useState(!1),m=wr(),f=async()=>{d(!1);try{const _=await(o==null?void 0:o.markConversationAsHandoff());e.info("conversation.handleAgentHandoff: success",_)}catch(_){e.error("conversation.handleAgentHandoff: error",_)}};if(!a)return null;const h={handoff:r.header.handoffButton()};return i.createElement(i.Fragment,null,i.createElement(i.Fragment,null,i.createElement(ZE,{label:t.HEADER_BUTTON__AGENT_HANDOFF,position:"bottom",disabled:l},i.createElement(je,{...h.handoff.props,type:"agent",size:s,disabled:l,...m,onClick:()=>d(!0)})),h.handoff.descriptionNode),i.createElement(nt,{portalContainerId:Ce.WINDOW,visible:c,onClose:()=>d(!1)},i.createElement(xr,{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})))},cb=u.lazy(()=>Promise.resolve().then(()=>require("./cjs/VvejebHE.cjs")).then(e=>({default:e.MarkdownText}))),ub=()=>{const{logger:e}=me(),{stringSet:t}=se(),{memoryInfo:n,sdkUser:r}=we(),{actions:o}=Se(),{conversation:s}=oe(),a=_t(20),l=wr(),[c,d]=u.useState(null),[m,f]=u.useState(!1),h=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 _=s.header.memoryIndicator(n.enabled),y=async C=>{if(!h.current){h.current=!0,f(!1);try{await o.setUserMemoryState({enabled:C}),d(null)}catch(v){e.error("memoryIndicator.setUserMemoryState: error",v),f(!0)}finally{h.current=!1}}};return i.createElement(i.Fragment,null,n.showIndicator&&i.createElement(i.Fragment,null,i.createElement(hb,{..._.props,as:"button",type:"button",onClick:()=>d({...n}),...l,$size:a},i.createElement(Q,{type:"memory",size:a,color:g.themedColor.textHighEmphasis}),i.createElement(gb,{$enabled:n.enabled})),_.descriptionNode),c&&i.createElement(db,{memoryInfo:c,onClose:()=>d(null),onSetEnabled:y}),i.createElement(gn,{visible:m,title:t.PLACE_HOLDER__WRONG,description:t.MEMORY__ERROR_MESSAGE,onClose:()=>f(!1)}))},db=({memoryInfo:e,onClose:t,onSetEnabled:n})=>{var f;const{stringSet:r}=se(),{colors:o}=D.useTheme(),s=u.useId(),a=u.useId(),l=Cl(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(nt,{visible:!0,portalContainerId:Ce.WINDOW,onClose:t,cancelable:!c,"aria-labelledby":s,"aria-describedby":a},i.createElement(xr,{title:r.MEMORY__DIALOG_TITLE,titleId:s,description:i.createElement(mb,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}}))},mb=({children:e})=>{const{handlers:t}=me();return i.createElement(pb,null,i.createElement(wt,{fallback:e},i.createElement(cb,{onClickLink:t.onClickLink},e)))},fb=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;`,hb=p.default.button`${fb};cursor:pointer;${Ae}`,gb=p.default.span`position:absolute;top:0;inset-inline-end:0;width:8px;height:8px;border-radius:999px;background-color:${({$enabled:e})=>e?g.themedColor.secondary:g.color.background300};box-shadow:0 0 0 2px ${g.color.background50};${J.dark`
|
|
461
|
-
box-shadow: 0 0 0 2px ${
|
|
460
|
+
`,UE=u.lazy(()=>Promise.resolve().then(()=>require("./cjs/VvejebHE.cjs")).then(e=>({default:e.MarkdownText}))),BE=()=>{const{aiAgentInfo:e,userSession:t}=Me(),{handlers:n}=me(),{messageSource:r,channelSource:o}=Se(),[s,a]=u.useState(null),l=mr("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(FE,null,i.createElement(UE,{onClickLink:n.onClickLink},e.specialNotice))},HE=()=>i.createElement(GE,null,i.createElement(BE,null),i.createElement(SE,null,i.createElement(PE,null))),GE=p.default.div`z-index:0;border:none;width:100%;`,zE=()=>{var o;const{testerType:e}=_t(),{channelSource:t}=Se(),n=Le(t.channel),r=!!e&&((o=t.channel)==null?void 0:o.isAIAgent);return n&&r?i.createElement(CE,null):i.createElement(HE,null)},Wi=({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(VE,{...o},i.createElement(YE,null,n==="center"&&t&&i.createElement(WE,{$sideWidth:Math.max(l,d)},i.createElement(qE,null,t)),i.createElement(KE,null,i.createElement(jE,{ref:s},e),(n==="start"||n==="end")&&t&&i.createElement(ZE,{$align:n,$hasStart:!!e,$hasEnd:!!r},t),i.createElement(XE,{ref:a},r))))},VE=p.default.div`position:relative;width:100%;background-color:${({theme:e})=>e.colors.base.headerBackground};border-bottom:1px solid ${h.themedColor.textDisabled};`,YE=p.default.div`position:relative;height:56px;padding:11px 12px;`,WE=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;`,KE=p.default.div`display:flex;flex-direction:row;align-items:center;justify-content:space-between;height:100%;z-index:1;`,jE=p.default.div`flex-shrink:0;display:flex;align-items:center;`,XE=p.default.div`flex-shrink:0;display:flex;align-items:center;`,ZE=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)=>Nt()?e*1.5:e,JE=()=>{const{state:e}=me(),{messenger:t}=oe(),n=Et(),r=()=>{e.setOpened(!1)};return i.createElement(je,{...t.closeButton().props,type:"close",size:n,onClick:r})},QE=()=>{const{enableCloseConversationButton:e,dispatcher:t}=me(),{channelSource:n}=Se(),{conversation:r}=oe(),o=n.channel,s=Et(),a=(o==null?void 0:o.isAIAgent)&&e,l=!sr(o);if(!a)return null;const c={close:r.header.closeConversationButton()},d=async()=>{o&&await t.send(Ze.CloseConversation({channelUrl:o.url}))};return i.createElement(i.Fragment,null,i.createElement(je,{...c.close.props,type:"mute",size:s,disabled:l,onClick:d}),c.close.descriptionNode)},eb=()=>{const{state:e,enableExpandButton:t}=me(),{messenger:n}=oe(),r=Et();return t?i.createElement(je,{...n.expandButton(e.expanded).props,type:e.expanded?"collapse":"expand",size:r,onClick:()=>e.setExpanded(!e.expanded)}):null},tb=({label:e,children:t,position:n="top",disabled:r})=>r?t:i.createElement(Qn,null,t,i.createElement(ob,{$position:n},i.createElement(sb,{variant:"caption1"},e),i.createElement(nb,{$position:n}))),nb=({$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})),rb={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%);`},Qn=p.default.div`position:relative;`,ob=p.default.div`display:flex;align-items:center;position:absolute;left:50%;z-index:${it.TOOLTIP};${({$position:e})=>rb[e]}opacity:0;transition:opacity 0.2s ease-in-out;pointer-events:none;${Qn}:hover &,${Qn}:focus-within &{opacity:1;}`,sb=p.default($)`padding:6px 8px;background:${h.themedColor.textHighEmphasis};color:${h.themedColor.textHighEmphasisInverse};border-radius:4px;font-size:12px;white-space:nowrap;`,ib=2e3,ns=0,ab=1500,Kt=Symbol("header-focus-status-pause"),rs="data-sb-header-focus-protected",lb="[data-message-composer]",os=new WeakMap,Pn=e=>{const t=os.get(e);if(t)return t;const n={focusedTargetIds:new Set,pendingBlurTimeouts:new Map,maxPauseTimeout:null};return os.set(e,n),n},Fn=(e,t)=>{const n=e.pendingBlurTimeouts.get(t);n&&(clearTimeout(n),e.pendingBlurTimeouts.delete(t))},Xt=e=>{e.maxPauseTimeout&&(clearTimeout(e.maxPauseTimeout),e.maxPauseTimeout=null)},cb=e=>{e.pendingBlurTimeouts.forEach(t=>clearTimeout(t)),e.pendingBlurTimeouts.clear(),e.focusedTargetIds.clear(),Xt(e)},ub=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)})},db=e=>e instanceof HTMLBodyElement||(e instanceof HTMLButtonElement||e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&e.disabled?!0:(e instanceof HTMLElement&&e.closest(lb),!1),kr=()=>{const{setStatusPauseState:e}=Ke(),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()+ab,s();const c=Pn(e);Fn(c,t.current),c.focusedTargetIds.add(t.current),c.focusedTargetIds.size===1&&e(Kt,!0),Xt(c),c.maxPauseTimeout=setTimeout(()=>{cb(c),e(Kt,!1)},ib)},[s,e]),l=u.useCallback(c=>{if(!n.current)return;n.current=!1;const d=c.currentTarget,m=Pn(e),f=d instanceof HTMLElement&&Date.now()<=r.current;Fn(m,t.current),f&&(s(),o.current=setTimeout(()=>{if(o.current=null,!(d instanceof HTMLElement)||!d.isConnected)return;const _=d.ownerDocument.activeElement,v=_ instanceof HTMLElement&&_.hasAttribute(rs);if(_===d||v||!db(_))return;const y=ub(d);d.focus({preventScroll:!0}),y()},ns)),m.pendingBlurTimeouts.set(t.current,setTimeout(()=>{m.pendingBlurTimeouts.delete(t.current),m.focusedTargetIds.delete(t.current),m.focusedTargetIds.size===0&&(Xt(m),e(Kt,!1))},ns))},[s,e]);return u.useEffect(()=>()=>{const c=Pn(e);n.current=!1,s(),Fn(c,t.current),c.focusedTargetIds.delete(t.current)&&c.focusedTargetIds.size===0&&(Xt(c),e(Kt,!1))},[s,e]),{[rs]:"true",onFocus:a,onBlur:l}},mb=()=>{const{logger:e}=me(),{stringSet:t}=se(),{channelSource:n}=Se(),{conversation:r}=oe(),o=n.channel,s=Et(),a=mr("handoff-button",o),l=!sr(o)||et(o),[c,d]=u.useState(!1),m=kr(),f=async()=>{d(!1);try{const _=await(o==null?void 0:o.markConversationAsHandoff());e.info("conversation.handleAgentHandoff: success",_)}catch(_){e.error("conversation.handleAgentHandoff: error",_)}};if(!a)return null;const g={handoff:r.header.handoffButton()};return i.createElement(i.Fragment,null,i.createElement(i.Fragment,null,i.createElement(tb,{label:t.HEADER_BUTTON__AGENT_HANDOFF,position:"bottom",disabled:l},i.createElement(je,{...g.handoff.props,type:"agent",size:s,disabled:l,...m,onClick:()=>d(!0)})),g.handoff.descriptionNode),i.createElement(nt,{portalContainerId:Ce.WINDOW,visible:c,onClose:()=>d(!1)},i.createElement(Ir,{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})))},fb=u.lazy(()=>Promise.resolve().then(()=>require("./cjs/VvejebHE.cjs")).then(e=>({default:e.MarkdownText}))),gb=()=>{const{logger:e}=me(),{stringSet:t}=se(),{memoryInfo:n,sdkUser:r}=Me(),{actions:o}=Se(),{conversation:s}=oe(),a=Et(20),l=kr(),[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 _=s.header.memoryIndicator(n.enabled),v=async y=>{if(!g.current){g.current=!0,f(!1);try{await o.setUserMemoryState({enabled:y}),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(Eb,{..._.props,as:"button",type:"button",onClick:()=>d({...n}),...l,$size:a},i.createElement(Q,{type:"memory",size:a,color:h.themedColor.textHighEmphasis}),i.createElement(bb,{$enabled:n.enabled})),_.descriptionNode),c&&i.createElement(hb,{memoryInfo:c,onClose:()=>d(null),onSetEnabled:v}),i.createElement(hn,{visible:m,title:t.PLACE_HOLDER__WRONG,description:t.MEMORY__ERROR_MESSAGE,onClose:()=>f(!1)}))},hb=({memoryInfo:e,onClose:t,onSetEnabled:n})=>{var f;const{stringSet:r}=se(),{colors:o}=D.useTheme(),s=u.useId(),a=u.useId(),l=xl(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(nt,{visible:!0,portalContainerId:Ce.WINDOW,onClose:t,cancelable:!c,"aria-labelledby":s,"aria-describedby":a},i.createElement(Ir,{title:r.MEMORY__DIALOG_TITLE,titleId:s,description:i.createElement(pb,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}}))},pb=({children:e})=>{const{handlers:t}=me();return i.createElement(Cb,null,i.createElement(Mt,{fallback:e},i.createElement(fb,{onClickLink:t.onClickLink},e)))},_b=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;`,Eb=p.default.button`${_b};cursor:pointer;${Ae}`,bb=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};${J.dark`
|
|
461
|
+
box-shadow: 0 0 0 2px ${h.color.background500};
|
|
462
462
|
`}
|
|
463
|
-
`,
|
|
463
|
+
`,Cb=p.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;}`,vb=()=>{const{conversation:e}=oe(),{onNavigateToConversationList:t}=Se();if(!t)return null;const n={menu:e.header.menuButton()};return i.createElement(i.Fragment,null,i.createElement(je,{...n.menu.props,...zs,type:"menu",size:24,onClick:()=>t()}),n.menu.descriptionNode)},qi=({channel:e,size:t=40})=>{const{userSession:n,aiAgentInfo:r}=Me(),{fallbackIcon:o,url:s}=fr({channel:e,aiAgentInfo:r,userSession:n}),a=D.useTheme();return s?i.createElement(wi,{src:s,size:t,"aria-hidden":"true"}):i.createElement(yb,{"aria-hidden":"true",$size:t,$bgColor:a.colors.base.primary},i.createElement(Q,{type:o,size:t*.55,color:a.colors.base.primaryContrastContent}))},yb=p.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;`,Sb=()=>{const{channelSource:e}=Se(),{aiAgentInfo:t,userSession:n}=Me(),{conversation:r}=oe(),{config:o}=ke(),{announcementsEnabled:s}=Ke(),a=e.channel,l=fr({channel:a,userSession:n,aiAgentInfo:t}),c=o.conversation.header.avatarEnabled,d=kr(),m=Ei({enabled:s,label:l.title}),f={title:r.header.title(l.title,{active:m.enabled,titleId:m.id,initialFocus:!1})};return i.createElement(Ab,null,c&&i.createElement(qi,{channel:a,size:34}),i.createElement(xb,{...f.title.props,...d},l.title))},Ab=p.default.div`display:flex;flex-direction:row;align-items:center;gap:6px;min-width:0;width:100%;overflow:hidden;`,xb=p.default($).attrs({variant:"h2",color:h.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
|
+
`,Tb=e=>{const{components:t}=lt.useContext();return i.createElement(Wi,{start:i.createElement(t.StartArea,null),title:i.createElement(t.TitleArea,null),titleAlign:e.titleAlign,end:i.createElement(t.EndArea,null),containerProps:Ws})},Ib=()=>{const{components:e}=lt.useContext();return i.createElement(e.MenuButton,null)},wb=()=>{const{components:e}=lt.useContext();return i.createElement(e.Title,null)},Mb=()=>{const{components:e}=lt.useContext();return i.createElement(Rb,null,i.createElement(e.MemoryIndicator,null),i.createElement(e.HandoffButton,null),i.createElement(e.ConversationCloseButton,null),i.createElement(e.ExpandButton,null),i.createElement(e.CloseButton,null))},lt=Be({template:Tb,components:{StartArea:Ib,TitleArea:wb,EndArea:Mb,MenuButton:vb,Title:Sb,MemoryIndicator:gb,HandoffButton:mb,ConversationCloseButton:QE,ExpandButton:eb,CloseButton:JE}}),kb=()=>{const{isActionbookTester:e}=_t(),{Template:t}=lt.useContext();return e?null:i.createElement(t,{titleAlign:"start"})},Rb=p.default.div`display:flex;gap:10px;align-items:center;justify-content:center;`,Ki=({children:e,onNavigateToConversationList:t,channelUrl:n,onClearChannelUrl:r,shouldMarkAsRead:o,announcementsEnabled:s,initialFocusTarget:a,style:l,closedChannelUrl:c,onClearClosedChannelUrl:d})=>{const{Template:m}=vn.useContext();return i.createElement(hi,{onNavigateToConversationList:t,channelUrl:n??c,onClearChannelUrl:r??d,shouldMarkAsRead:o},i.createElement(Kn,null,i.createElement(Kn.Consumer,null,f=>i.createElement(Hd,{announcementsEnabled:s},i.createElement(Lb,null),i.createElement(Ob,{style:l,dragHandlers:f,initialFocusTarget:a},i.createElement(m,null)),e))))},Lb=()=>(nf(),Wm(),Qm(),null),Ob=({style:e,dragHandlers:t,initialFocusTarget:n,children:r})=>{const o=u.useRef(null);return Bm(o,n),i.createElement(Db,{ref:o,style:e,...t},r)},Nb=e=>{const{components:t}=vn.useContext();return i.createElement(i.Fragment,null,i.createElement(t.Header,null),i.createElement(t.Body,null),i.createElement(t.Footer,null))},vn=Be({template:Nb,components:{Header:kb,Body:bE,Footer:zE}}),Db=p.default.div`height:100%;width:100%;display:flex;flex-direction:column;flex:1;background-color:${({theme:e})=>e.colors.base.background};`,ji=Ee("ConversationListAnnouncements",{announcementsEnabled:!0,announceScreenEntry:ge}),$b=ji.Provider,Rr=ji.useContext,Pb=({children:e,announcementsEnabled:t=!0})=>{const{announceScreenEntry:n}=Er(),r=u.useCallback(s=>{t&&n(s)},[n,t]),o=u.useMemo(()=>({announcementsEnabled:t,announceScreenEntry:r}),[t,r]);return i.createElement($b,{value:o},e)},{Provider:Fb,Context:Ub,useContext:Pt}=Ee("ConversationList");function Xi({conversationListLimit:e,conversationListFilter:t,onOpenConversationView:n=ge,children:r}){return i.createElement(wc,{conversationListLimit:e,conversationListFilter:t},o=>i.createElement(Fb,{value:{...o,onOpenConversationView:n}},r))}const Bb=e=>{const{announcementsEnabled:t}=Rr(),{listSource:n}=Pt();bi(e,{enabled:t,ready:n.initialized})},Hb=()=>{const{announceScreenEntry:e,announcementsEnabled:t}=Rr(),{listSource:n}=Pt(),r=u.useRef(!1);u.useEffect(()=>{if(!t){r.current=!1;return}if(!n.initialized||r.current)return;const o=n.channels.length,s=setTimeout(()=>{e({screen:"conversationList",conversationCount:o}),r.current=!0},0);return()=>clearTimeout(s)},[e,t,n.initialized])},Gb=({channel:e})=>i.createElement(qi,{channel:e}),er=99,zb=e=>{var b,E;const{channel:t,onClick:n}=e,{stringSet:r,format:o}=se(),{userSession:s,aiAgentInfo:a}=Me(),{conversationList:l}=oe(),c=fr({channel:t,userSession:s,aiAgentInfo:a}),d=vl(t,{formatMultipleFilesCount:r.CONVERSATION_LIST__MULTIPLE_FILES_COUNT}),m=yl(t,o,{justNow:r.DATE_FORMAT__JUST_NOW,minutesAgo:r.DATE_FORMAT__MINUTES_AGO,hoursAgo:r.DATE_FORMAT__HOURS_AGO,dateShortFormat:r.DATE_FORMAT__DATE_SHORT}),f=t.unreadMessageCount,g=(b=t.lastMessage)!=null&&b.isAdminMessage()?r.CONVERSATION_LIST__SYSTEM_MESSAGE:c.title,_=Le(t)?r.CONVERSATION_LIST__ENDED:Ts(t,{formatMultipleFilesCount:r.CONVERSATION_LIST__MULTIPLE_FILES_COUNT}),v=n?()=>n():void 0,y=l.item({agent:g,status:_,time:m,unreadCount:f,onActivate:v});return i.createElement(Vb,{"data-testid":"sb-conversation-list-item",$clickable:!!v,...y.props},i.createElement(Yb,null,i.createElement(Gb,{...e})),i.createElement(Wb,null,i.createElement(qb,null,(E=t.lastMessage)!=null&&E.isFileMessage()&&(!t.lastMessage.message||t.lastMessage.name===t.lastMessage.message)?i.createElement(Ai,{variant:"subtitle1",color:h.themedColor.textHighEmphasis},d):i.createElement($,{variant:"subtitle1",color:h.themedColor.textHighEmphasis,maxTextLines:1},d),i.createElement(Kb,null,Le(t)&&i.createElement(i.Fragment,null,i.createElement($,{variant:"caption1",color:h.themedColor.textMidEmphasis,maxTextLines:1},r.CONVERSATION_LIST__ENDED),i.createElement(jb,null)),i.createElement($,{variant:"caption2",color:h.themedColor.textLowEmphasis,maxTextLines:1},m))),f>0&&i.createElement(Xb,{$count:f},i.createElement($,{variant:"caption3",color:h.themedColor.textHighEmphasisInverse},f<=er?f:`${er}+`))),y.descriptionNode)},Lr=Be({template:zb,components:{}}),Vb=p.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"};`,Yb=p.default.div`display:flex;align-items:center;justify-content:center;padding-inline-start:16px;`,Wb=p.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 ${h.themedColor.textDisabled};`,qb=p.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;`,Kb=p.default.div`display:flex;align-items:center;gap:6px;`,jb=p.default.div`width:2px;height:2px;border-radius:1px;background-color:${h.themedColor.textLowEmphasis};`,Xb=p.default.div`display:flex;align-items:center;justify-content:center;height:20px;padding:4px;border-radius:10px;background-color:${h.themedColor.error};${({$count:e})=>e<=er&&D.css`
|
|
476
476
|
width: 20px;
|
|
477
477
|
`}
|
|
478
|
-
`,
|
|
478
|
+
`,Zb=({items:e,renderItem:t,onEndReached:n,role:r,"aria-label":o})=>{const s=a=>{const l=a.target;l.scrollHeight-l.scrollTop-l.clientHeight<=2&&(n==null||n())};return i.createElement(Jb,{role:r,"aria-label":o,onScroll:a=>s(a)},e.map((a,l)=>{const c=t(a,l);if(r!=="list")return c;const d=u.isValidElement(c)&&c.key!=null?c.key:l;return i.createElement(Qb,{key:d,role:"listitem"},c)}))},Jb=p.default.div`width:100%;height:100%;display:flex;flex-direction:column;flex:1;overflow:auto;overscroll-behavior:contain;`,Qb=p.default.div`flex-shrink:0;`,eC=()=>{const{stringSet:e}=se(),{listSource:t,onOpenConversationView:n}=Pt(),{Template:r}=Lr.useContext();return t.initialized?t.channels.length===0?i.createElement(It,{type:"noChannels",label:e.CONVERSATION_LIST__NO_CONVERSATIONS}):i.createElement(Zb,{role:"list","aria-label":e.CONVERSATION_LIST__HEADER_TITLE,items:t.channels,renderItem:o=>{var s,a,l;return i.createElement(r,{key:o.url,channel:o,onClick:()=>n(o.url,Le(o)?"closed":"open"),channelUrl:o.url,title:(a=(s=o.conversation)==null?void 0:s.topics)==null?void 0:a.join(", "),lastMessageTimestamp:(l=o.lastMessage)==null?void 0:l.createdAt})},onEndReached:()=>{t.loadMore()}}):i.createElement(It,{type:"loading"})},tC=()=>{const{stringSet:e}=se(),{_aiAgentSDK:t}=ke(),{language:n,countryCode:r,context:o}=me(),{aiAgentInfo:s,refreshActiveChannel:a,createConversation:l}=Me(),{onOpenConversationView:c}=Pt(),{conversationList:d}=oe(),m=async()=>{var f;if(s.isMultipleActiveConversationsEnabled){const g=await l({aiAgentId:s.userId,language:n,country:r,context:o});(f=t.session)==null||f._updateActiveChannel({url:g,status:"open"}),c(g,"open",{initialFocusTarget:"messageInput"})}else{const g=await a();c(g,"open",{initialFocusTarget:"messageInput"})}};return i.createElement(nC,{...d.footer.button({onActivate:m}).props},i.createElement(rC,{variant:"h1"},e.TALK_TO_AGENT))},nC=p.default.div`background-color:${({theme:e})=>e.colors.base.primary};display:flex;align-items:center;justify-content:center;padding:16px;cursor:pointer;`,rC=p.default($)`color:${({theme:e})=>e.colors.base.primaryContrastContent};overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`,oC=()=>{const{state:e}=me(),{messenger:t}=oe(),n=Et(),r=()=>{e.setOpened(!1)};return i.createElement(je,{...t.closeButton().props,type:"close",size:n,onClick:r})},sC=()=>{const{stringSet:e}=se(),{announcementsEnabled:t}=Rr(),{conversationList:n}=oe(),r=e.CONVERSATION_LIST__HEADER_TITLE,o=Ei({enabled:t,label:r}),s={title:n.headerTitle(r,{active:o.enabled,titleId:o.id})};return i.createElement(iC,{forwardedAs:"h2",variant:"h2",color:h.themedColor.textHighEmphasis,...s.title.props},r)},iC=p.default($)`margin:0;padding:0 4px;min-width:0;width:100%;box-sizing:border-box;text-overflow:ellipsis;overflow:hidden;white-space:nowrap;`,aC=e=>{const{components:t}=bt.useContext();return i.createElement(Wi,{start:i.createElement(t.StartArea,null),title:i.createElement(t.TitleArea,null),titleAlign:e.titleAlign,end:i.createElement(t.EndArea,null),containerProps:Ws})},lC=()=>null,cC=()=>{const{components:e}=bt.useContext();return i.createElement(e.Title,null)},uC=()=>{const{components:e}=bt.useContext();return i.createElement(e.CloseButton,null)},bt=Be({template:aC,components:{StartArea:lC,TitleArea:cC,EndArea:uC,Title:sC,CloseButton:oC}}),dC=()=>{const{Template:e}=bt.useContext();return i.createElement(e,{titleAlign:"start"})},mC=()=>(Hb(),null),Zi=({conversationListLimit:e,conversationListFilter:t,children:n,onOpenConversationView:r,announcementsEnabled:o=!0,style:s})=>{const{Template:a}=yn.useContext();return i.createElement(Xi,{conversationListLimit:e,conversationListFilter:t,onOpenConversationView:r},i.createElement(Pb,{announcementsEnabled:o},i.createElement(mC,null),i.createElement(fC,{style:s},i.createElement(a,null)),n))},fC=({style:e,children:t})=>{const n=u.useRef(null);return Bb(n),i.createElement(hC,{ref:n,style:e},t)},gC=()=>{const{components:e}=yn.useContext();return i.createElement(i.Fragment,null,i.createElement(e.Header,null),i.createElement(e.Body,null),i.createElement(e.Footer,null))},yn=Be({template:gC,components:{Header:dC,Body:eC,Footer:tC}}),hC=p.default.div`height:100%;width:100%;display:flex;flex-direction:column;flex:1;background-color:${({theme:e})=>e.colors.base.background};`,pC=D.css`:where(#${Ce.ENTRY}) :not(code *){font-family:'Roboto',sans-serif;box-sizing:border-box;}`,_C=[pC,gd,hd],EC=(e,...t)=>D.createGlobalStyle(e,..._C,...t),bC=EC``,CC=Cl(vn,tt,$t,_n,Cn,yn,lt,Lr,bt,bn,gn),vC=typeof __SBA_USE_MESSAGE_TEMPLATE__>"u"||__SBA_USE_MESSAGE_TEMPLATE__;function Ji({appearance:e,rootElement:t,logger:n,language:r,languageCode:o,stringSet:s,children:a,messageTemplate:l,icons:c,theme:d,entryElement:m,modalRootElement:f}){Nd(vC?td:"",t);const[g,_]=u.useState(null),v=u.useCallback(E=>{_(C=>C===E?C:E)},[]),y=m??g,b=i.createElement(D.StyleSheetManager,{target:t},i.createElement(Rd,{rootElement:t,logger:n,appearance:e,theme:d},i.createElement(sd,{rootElement:t,boundaryElement:y},i.createElement(Lc,{internalVariables:l==null?void 0:l.__internalVariables},i.createElement(fd,{stringSet:s,logger:n,language:r,languageCode:o},i.createElement(Md,{icons:c},i.createElement(CC,null,i.createElement(rd,{entryElement:y,modalRootElement:f,rootElement:t},a),i.createElement(bC,null))))))));return m?b:i.createElement("div",{ref:v,style:{display:"contents"}},b)}const yC=()=>{const[e,t]=u.useState(null),[n,r]=u.useState(null),o=u.useCallback(a=>{t(l=>l===a?l:a)},[]),s=u.useCallback(a=>{r(l=>l===a?l:a)},[]);return{entryElement:e,modalRootElement:n,setEntryElement:o,setModalRootElement:s}},Or=u.forwardRef(function({rootElement:t=document.body,logLevel:n=he.LogLevel.WARN,language:r=navigator.language,userSessionInfo:o,children:s,chatParams:a,icons:l,...c},d){var b,E,C;xt.level!==n&&(xt.level=n);const{entryElement:m,modalRootElement:f,setEntryElement:g,setModalRootElement:_}=yC();Od("https://fonts.googleapis.com/css2?family=Roboto&display=swap",t);const v=Js(r),y=Qs.has(v)?v:Ot;return i.createElement("div",{ref:g,id:Ce.ENTRY,lang:y,style:{width:"fit-content",height:"fit-content",...c.entryStyle}},m&&f&&i.createElement(Ji,{logger:xt,rootElement:t,appearance:(b=c.agentPreviewConfigs)==null?void 0:b.appearance,stringSet:c.stringSet,language:y,messageTemplate:c.messageTemplate,icons:l,theme:c.theme,entryElement:m,modalRootElement:f},i.createElement(fm,{rootElement:t,language:r,logger:xt,dispatcher:Qi,chatParams:{...a,...c.customApiHost&&{customApiHost:c.customApiHost},...c.customWebSocketHost&&{customWebSocketHost:c.customWebSocketHost}},chatSDK:c.customChatSDK,_forceCreateChannel:(E=c.agentPreviewConfigs)==null?void 0:E.forceCreateChannel,_agentVersion:(C=c.agentPreviewConfigs)==null?void 0:C.agentVersion,...c},i.createElement(vm,{ref:d,userSessionInfo:o},i.createElement(Bp,{...c._UNSAFE_INTERNAL_dashboardTester},i.createElement(Ud,null,s))))),i.createElement("div",{ref:_,id:Ce.MODAL_ROOT,dir:c.dir}))}),xt=new ps(he.LogLevel.WARN),Qi=new hs(xt),{Provider:SC,useContext:Nr}=Ee("PageChildren"),ea=({children:e})=>{const[t,n]=u.useState(null),[r,o]=u.useState(null);return i.createElement(SC,{value:{conversationChildren:t,setConversationChildren:n,conversationListChildren:r,setConversationListChildren:o}},e)},Dr=(e,t)=>e?{role:"dialog","aria-modal":"true",...t?{"aria-labelledby":Ce.WINDOW_TITLE}:{"aria-label":"Messenger"}}:{"aria-hidden":"true",inert:!0},ta=({children:e,isOpened:t,zIndex:n=it.WINDOW})=>i.createElement(yr,null,i.createElement(AC,{isOpened:t,zIndex:n},e)),AC=({children:e,isOpened:t,zIndex:n=it.WINDOW})=>{const{dir:r,rootElement:o}=me(),s=st(o,!0),a=u.useRef(null),{hasWindowTitleReference:l,isWindowNameReady:c}=pn();return fn(t,a,{nameReady:c}),u.useEffect(()=>{const d="sb-agent-block-scroll";return t?s.body.classList.add(d):s.body.classList.remove(d),()=>{s.body.classList.remove(d)}},[s,t]),i.createElement(xC,{ref:a,id:Ce.WINDOW,dir:r,...Dr(t,l),$visible:t,$zIndex:n},e)},xC=p.default.div`width:100%;height:100%;position:fixed;top:0;left:0;z-index:${({$zIndex:e})=>e};visibility:${({$visible:e})=>e?"visible":"hidden"};`,TC=48,IC=2/3,ss=12;function na({className:e,children:t,isOpened:n,onClick:r,"aria-label":o,"aria-describedby":s,type:a,imageUrl:l,dir:c,animated:d=!0,backgroundColor:m,size:f=TC,hasUnread:g=!1}){const _=ki(),v=d&&!_,y=Vn(m),b=Math.round(f*IC);return i.createElement(kC,{dir:c,id:Ce.LAUNCHER,className:e,"aria-label":o,"aria-describedby":s,onClick:r,$animated:v,$backgroundColor:m,$prefersReducedMotion:_,$size:f},i.createElement(RC,{$isOpened:n,$animated:v,$fillColor:y,$iconSize:b,$prefersReducedMotion:_},i.createElement(is.Open,{url:l,isDefaultIcon:a==="default_icon",size:b})),i.createElement(LC,{$isOpened:n,$animated:v,$fillColor:y,$iconSize:b,$prefersReducedMotion:_},i.createElement(is.Close,{size:b})),g&&i.createElement(OC,null),t)}const wC=D.css`&:hover{transition:transform 250ms cubic-bezier(0.33,0,0,1);transform:scale(1.1);}&:active{transform:scale(0.8);}`,MC=D.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===wt.WHITE?"grayscale(100%) brightness(2000%)":"grayscale(100%) invert(100%) saturate(0%) brightness(0%) contrast(1000%)"};}}`,ra=D.css`svg{width:${({$iconSize:e})=>e}px;height:${({$iconSize:e})=>e}px;${({$fillColor:e})=>D.css`
|
|
479
479
|
ellipse,
|
|
480
480
|
path {
|
|
481
481
|
fill: ${e};
|
|
@@ -485,7 +485,7 @@
|
|
|
485
485
|
}
|
|
486
486
|
`}
|
|
487
487
|
}
|
|
488
|
-
`,
|
|
488
|
+
`,kC=p.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&&wC}`,oa=p.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
|
+
`,RC=p.default(oa)`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)")};${MC}${ra}`,LC=p.default(oa)`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)")};${ra}`,OC=p.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: ${ss}px;
|
|
503
|
+
height: ${ss}px;
|
|
504
504
|
border-radius: 50%;
|
|
505
|
-
background-color: ${
|
|
506
|
-
`,
|
|
505
|
+
background-color: ${h.themedColor.error};
|
|
506
|
+
`,is={Open:e=>e.url?i.createElement("img",{src:e.url,alt:"","data-default-icon":e.isDefaultIcon}):i.createElement(Q,{size:e.size,type:"delight"}),Close:({size:e})=>i.createElement(Q,{size:e,type:"chevron-down"})};function sa({className:e,size:t,entryPoint:n="Conversation",activeRoute:r}){const{colors:o}=D.useTheme(),{chatSDK:s,config:a,dir:l,state:c}=me(),{resolveElement:d}=_r(),{launcher:m}=oe(),{launcherInfo:f,statsTrackers:g}=Me(),_=a.launcher.unreadBadgeEnabled,v=Rs(),y=lu(s,{enabled:_,opened:c.opened,filter:v}),b=(r??n)==="ConversationList",E={launcher:m.button({isOpened:c.opened,opensConversationList:b})};u.useLayoutEffect(()=>{g.initialRender.setPresentMethod("launcher_toggle")},[g]),DC();const C=()=>{we(()=>{const w=d(Ce.WINDOW),k=w?li(w):null;k==null||k.focus()})},S=()=>{we(()=>{var w;(w=d(Ce.LAUNCHER))==null||w.focus()})},x=()=>{const w=!c.opened;c.setOpened(w),w?C():S()};return i.createElement(na,{dir:l,className:e,isOpened:c.opened,onClick:x,type:f.type,imageUrl:f.imageUrl,backgroundColor:o.base.primary,size:t,hasUnread:_&&!c.opened&&y,...E.launcher.props},E.launcher.descriptionNode)}const NC=1e3*60;function DC(){const{chatSDK:e,state:t,logger:n,enableAutoDisconnectInLauncher:r}=me(),o=u.useRef(null);u.useEffect(()=>{if(!r)return;function s(){o.current&&(clearTimeout(o.current),o.current=null)}function a(){e.connectionState===he.ConnectionState.CLOSED&&(e.reconnect(),n.debug("useSDKInactivityTimeout: reconnected")),s(),n.debug("useSDKInactivityTimeout: clear disconnect schedule")}function l(){s(),o.current=setTimeout(async()=>{await e.disconnectWebSocket(),n.debug("useSDKInactivityTimeout: disconnected")},NC)}t.opened?a():(l(),n.debug("useSDKInactivityTimeout: schedule disconnect"))},[r,e,t.opened])}const ia=u.createContext(null);function $r(){const e=u.useContext(ia);if(!e)throw new Error("useNavigator() must be used within <Navigator />");return e}function aa({children:e}){const t=$r();return typeof e=="function"?e(t):i.createElement(i.Fragment,null,e)}const $C=D.keyframes`0%{transform:translateY(40px);opacity:0;}100%{transform:translateY(0px);opacity:1;}`,PC=D.keyframes`0%{transform:translateY(0px);opacity:1;}100%{transform:translateY(40px);opacity:0;}`,FC=D.css`animation-name:${$C};animation-duration:0.3s;animation-fill-mode:forwards;`,UC=D.css``,BC=D.css`animation-name:${PC};animation-duration:0.3s;animation-fill-mode:forwards;`,HC=D.css`visibility:hidden;`,GC=p.default.div`position:absolute;top:0;left:0;width:100%;height:100%;${({$transitionState:e})=>{switch(e){case"entering":return FC;case"entered":return UC;case"exiting":return BC;case"exited":return HC;default:return""}}}${({$active:e})=>e?D.css`
|
|
507
507
|
z-index: 999;
|
|
508
508
|
`:D.css`z-index:1;pointer-events:none;`}
|
|
509
|
-
`;function
|
|
509
|
+
`;function Zt({initialId:e,children:t}){const[n,r]=u.useState([e]),o=n[n.length-1],s=u.useCallback((b,E)=>{r(C=>[...C,b]),f(C=>({...C,[b]:!0})),E!=null&&E.reset&&y(C=>({...C,[b]:(C[b]||0)+1})),_(C=>({...C,[b]:"entering"})),setTimeout(()=>{_(C=>({...C,[b]:"entered"}))},300)},[]),a=u.useCallback(()=>{r(b=>{if(b.length<=1)return b;const E=b[b.length-1];return _(C=>({...C,[E]:"exiting"})),setTimeout(()=>{_(C=>({...C,[E]:"exited"})),r(C=>C.slice(0,-1))},300),b})},[]),l=u.useMemo(()=>({navigation:{navigate:s,pop:a},activeScreenId:o}),[s,a,o]),c=u.useMemo(()=>u.Children.toArray(t).filter(b=>b.type===aa),[t]),d=u.useMemo(()=>{const b={};return c.forEach(E=>{const{id:C,lazy:S,children:x}=E.props;b[C]={lazy:S,element:typeof x=="function"?x(l):x}}),b},[c,l]),[m,f]=u.useState(()=>{const b={};return Object.entries(d).forEach(([E,{lazy:C}])=>{C===!1&&(b[E]=!0)}),b[e]=!0,b}),[g,_]=u.useState(()=>{const b={};return Object.keys(d).forEach(E=>{E===e?b[E]="entered":b[E]="exited"}),b}),[v,y]=u.useState({});return i.createElement(ia.Provider,{value:l},i.createElement(zC,null,Object.keys(d).map(b=>{var x;if(!m[b])return null;const E=g[b]||"exited",C=b===o,S=`${b}-${v[b]||0}`;return i.createElement(GC,{key:S,$transitionState:E,$active:C,"aria-hidden":C?void 0:!0,inert:C?void 0:!0},(x=d[b])==null?void 0:x.element)})))}const zC=p.default.div`position:relative;width:100%;height:100%;`;Zt.Screen=aa;const Pe={conv:"conv",convList:"conv-list"},VC=e=>e===Pe.convList?"ConversationList":"Conversation",as=({isOpened:e,activeScreenId:t})=>e&&t===Pe.conv,la=({isOpened:e,entryPoint:t,selectedChannelUrl:n,setSelectedChannelUrl:r,onActiveRouteChange:o})=>{const{conversationChildren:s,conversationListChildren:a}=Nr(),[l,c]=u.useState(),d=(()=>{switch(t){case"Conversation":return Pe.conv;case"ConversationList":return Pe.convList;default:return Pe.conv}})(),m=i.createElement(i.Fragment,null,i.createElement(YC,{onOpenConversationView:(f,g)=>{r(g),c(void 0),f.navigate(Pe.conv)}}),i.createElement(WC,{onActiveRouteChange:o}));return i.createElement(Zt,{initialId:d},i.createElement(Zt.Screen,{id:Pe.conv},({navigation:f,activeScreenId:g})=>i.createElement(Ki,{key:n,channelUrl:n,onClearChannelUrl:()=>r(void 0),onNavigateToConversationList:()=>{c(void 0),f.navigate(Pe.convList)},announcementsEnabled:as({isOpened:e,activeScreenId:g}),shouldMarkAsRead:as({isOpened:e,activeScreenId:g}),initialFocusTarget:l},m,s)),i.createElement(Zt.Screen,{id:Pe.convList,lazy:!0},({navigation:f,activeScreenId:g})=>{const _=e&&g===Pe.convList;return i.createElement(Zi,{announcementsEnabled:_,onOpenConversationView:(v,y,b)=>{r(v),c(b==null?void 0:b.initialFocusTarget),f.navigate(Pe.conv)}},m,a)}))},YC=({onOpenConversationView:e})=>{const{registerOnJoinedProactiveConversation:t}=Me(),{navigation:n}=$r();return t(({channel:r})=>{e(n,r.url)}),null},WC=({onActiveRouteChange:e})=>{const{activeScreenId:t}=$r();return u.useEffect(()=>{e==null||e(VC(t))},[t,e]),null},qC=({isExpanded:e,isOpened:t,children:n,launcher:r})=>i.createElement(yr,null,i.createElement(KC,{isExpanded:e,isOpened:t,launcher:r},n)),KC=({isExpanded:e,isOpened:t,children:n,launcher:r})=>{const{dir:o}=me(),s=u.useRef(null),{hasWindowTitleReference:a,isWindowNameReady:l}=pn();return fn(t,s,{nameReady:l}),i.createElement(jC,null,i.createElement(XC,{ref:s,dir:o,id:Ce.WINDOW,...Dr(t,a),$isExpanded:e,$isOpened:t},n),r)},jC=p.default.div`display:flex;flex-direction:column;gap:8px;align-items:flex-end;`,XC=p.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&&JC};${({$isExpanded:e})=>e&&ZC};`,ZC=D.css`width:743px;height:723px;`,JC=D.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;`,QC=u.forwardRef(function({children:e,initialChannelUrl:t,...n},r){const o=Nt(),[s,a]=u.useState(t),[l,c]=u.useState(n.entryPoint??"Conversation"),d=o?ta:qC;return i.createElement(Or,{enableExpandButton:!o,ref:r,...n},i.createElement(ui,null,({state:m})=>i.createElement(ea,null,i.createElement(d,{isExpanded:m.expanded,isOpened:m.opened,...o&&{zIndex:"auto"},launcher:i.createElement(sa,{entryPoint:n.entryPoint,activeRoute:l})},i.createElement(la,{isOpened:m.opened,entryPoint:n.entryPoint,selectedChannelUrl:s,setSelectedChannelUrl:a,onActiveRouteChange:c})),e)))}),{Provider:ev,useContext:Pr}=Ee("FixedMessengerStyle");function ca(e,t,n,r=0){const{top:o,bottom:s,start:a,end:l}=n;let c="",d="";switch(e){case"start":d=`inset-inline-start: ${Ge(a)}`;break;case"end":d=`inset-inline-end: ${Ge(l)}`;break}switch(t){case"top":c=`top: calc(${Ge(o)} + ${r}px)`;break;case"bottom":c=`bottom: calc(${Ge(s)} + ${r}px)`;break}return D.css`${c};${d};`}function tv(e){const{horizontal:t,vertical:n,margin:r,launcherSize:o}=Pr();return i.createElement(nv,{...e,size:o,$horizontal:t,$vertical:n,$margin:r})}const nv=p.default(sa)`position:fixed;z-index:${it.LAUNCHER};${({$horizontal:e,$vertical:t,$margin:n})=>ca(e,t,n)};`,rv=({isExpanded:e,isOpened:t,children:n})=>i.createElement(yr,null,i.createElement(ov,{isExpanded:e,isOpened:t},n)),ov=({isExpanded:e,isOpened:t,children:n})=>{const{dir:r}=me(),{horizontal:o,vertical:s,margin:a,launcherSize:l}=Pr(),c=u.useRef(null),{hasWindowTitleReference:d,isWindowNameReady:m}=pn();return fn(t,c,{nameReady:m}),i.createElement(sv,{ref:c,dir:r,id:Ce.WINDOW,...Dr(t,d),$isExpanded:e,$isOpened:t,$horizontal:o,$vertical:s,$margin:a,$launcherSize:l},n)},sv=p.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})=>ca(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&&av};
|
|
516
|
+
${({$isExpanded:e})=>e&&iv};
|
|
517
|
+
`,iv=D.css`width:743px;height:723px;`,av=D.css`z-index:${it.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;`,ua={top:24,bottom:24,start:24,end:24},lv=u.forwardRef(function({children:e,initialChannelUrl:t,...n},r){const[o,s]=u.useState(t),[a,l]=u.useState(n.entryPoint??"Conversation"),[c,d]=u.useState("end-bottom"),[m,f]=u.useState(ua),[g,_]=u.useState(48),v=Nt(),y=v?ta:rv,{horizontal:b,vertical:E}=u.useMemo(()=>{const[C,S]=c.split("-");return{horizontal:C==="start"?"start":"end",vertical:S==="top"?"top":"bottom"}},[c]);return i.createElement(Or,{enableExpandButton:!v,ref:r,...n},i.createElement(ui,null,({state:C})=>i.createElement(ev,{value:{horizontal:b,vertical:E,margin:m,launcherSize:g,setPosition:d,setMargin:f,setLauncherSize:_}},i.createElement(ea,null,i.createElement(y,{isExpanded:C.expanded,isOpened:C.opened},i.createElement(la,{isOpened:C.opened,entryPoint:n.entryPoint,selectedChannelUrl:o,setSelectedChannelUrl:s,onActiveRouteChange:l})),i.createElement(tv,{entryPoint:n.entryPoint,activeRoute:a}),e))))}),cv=e=>{var o,s,a,l;const{setPosition:t,setMargin:n,setLauncherSize:r}=Pr();return u.useLayoutEffect(()=>{e.position&&t(e.position),e.margin&&n({...ua,...e.margin}),e.launcherSize&&r(e.launcherSize)},[e.position,(o=e.margin)==null?void 0:o.top,(s=e.margin)==null?void 0:s.bottom,(a=e.margin)==null?void 0:a.start,(l=e.margin)==null?void 0:l.end,e.launcherSize]),null},uv=({children:e})=>{const{setConversationChildren:t}=Nr();return u.useLayoutEffect(()=>(t(e),()=>t(null)),[e]),null},dv=({children:e})=>{const{setConversationListChildren:t}=Nr();return u.useLayoutEffect(()=>(t(e),()=>t(null)),[e]),null},mv=Object.assign(lv,{Style:cv,ConversationChildren:uv,ConversationListChildren:dv}),fv=e=>{const{refreshActiveChannel:t}=Me(),[n,r]=u.useState(!1),o=u.useRef(null),s=u.useRef(null);return u.useEffect(()=>{n&&t().then(()=>{var a;(a=o.current)==null||a.call(o),r(!1)}).catch(a=>{var l;(l=s.current)==null||l.call(s,a),r(!1)})},[n]),u.useCallback(()=>new Promise((a,l)=>{o.current=a,s.current=l,e().then(()=>r(!0)).catch(l)}),[e])};As.set(he.SendbirdPlatform.JS,{deviceOSPlatform:wa()?he.DeviceOsPlatform.MOBILE_WEB:he.DeviceOsPlatform.WEB,messengerVersion:Zu,keyValueStorage:Qu(),networkStateAdapter:Ju()});exports.ANCHOR_REL=pr;exports.AgentProviderContainer=Or;exports.AgentUIProviderContainer=Ji;exports.AnonymousSessionInfo=Hn;exports.CSATType=Ye;exports.Commands=Ze;exports.ConnectionDelayLayout=gn;exports.Conversation=Ki;exports.ConversationContext=Nm;exports.ConversationContextProvider=hi;exports.ConversationHeaderLayout=lt;exports.ConversationLayout=vn;exports.ConversationList=Zi;exports.ConversationListContext=Ub;exports.ConversationListContextProvider=Xi;exports.ConversationListHeaderLayout=bt;exports.ConversationListItemLayout=Lr;exports.ConversationListLayout=yn;exports.DefaultMessenger=QC;exports.DeskTicketPriority=lr;exports.DeskTicketStatus=ar;exports.FixedMessenger=mv;exports.ID_INCOMING=We;exports.IncomingMessageLayout=tt;exports.LauncherBase=na;exports.LogLevel=rr;exports.ManualSessionInfo=_s;exports.MessageListUILayout=Cn;exports.MessageLogs=Hi;exports.OutgoingMessageLayout=$t;exports.PlaceholderLayout=bn;exports.SystemMessageLayout=_n;exports.cssVars=h;exports.escapeMarkdownSyntax=Ta;exports.flattenObject=sl;exports.mapCommonStringsToReactFormat=Zs;exports.messengerDispatcher=Qi;exports.noop=ge;exports.parseToMessageTemplate=ys;exports.parseToUITemplate=rl;exports.pickColorByTheme=ol;exports.replaceVariablesAsync=al;exports.replaceVariablesSync=il;exports.useAIAgentContext=ke;exports.useConversationContext=Se;exports.useConversationListContext=Pt;exports.useLocalizationContext=se;exports.useMessageTemplateFetchingContext=Rc;exports.useMessengerContext=me;exports.useMessengerSessionContext=Me;exports.useMessengerThemeContext=ri;exports.useRefreshActiveChannel=fv;
|